text stringlengths 14 6.51M |
|---|
unit pia6821;
interface
type
in_handler=function:byte;
out_handler=procedure(valor:byte);
irq_handler=procedure(state:boolean);
cb_handler=procedure(state_out:boolean);
pia6821_chip=class
constructor Create;
destructor free;
public
irq_a_state,irq_b_state:boolean;
procedure reset;
function read(dir:byte):byte;
procedure write(dir,valor:byte);
procedure change_in_out(in_a,in_b:in_handler;out_a,out_b:out_handler);
procedure change_cb(cb2:cb_handler);
procedure change_irq(irq_a,irq_b:irq_handler);
procedure ca1_w(state:boolean);
procedure cb1_w(state:boolean);
procedure portb_w(valor:byte);
private
a_input_overrides_output_mask,ctl_a,ctl_b,ddr_a,ddr_b,in_a,in_b,port_a_z_mask,out_a,out_b:byte;
logged_ca1_not_connected,in_ca1_pushed,logged_ca2_not_connected,in_ca2_pushed,in_ca1,in_ca2,irq_a1,irq_a2,irq_b1,irq_b2:boolean;
out_ca2,out_cb2,out_ca2_needs_pulled,in_a_pushed,in_b_pushed,logged_port_a_not_connected,logged_port_b_not_connected:boolean;
out_cb2_needs_pulled,last_out_cb2_z,out_a_needs_pulled,out_b_needs_pulled:boolean;
logged_cb1_not_connected,logged_cb2_not_connected,in_cb1_pushed,in_cb2_pushed,in_cb1:boolean;
in_ca1_handler:function:boolean;
in_ca2_handler:function:boolean;
in_cb1_handler:function:boolean;
ca2_handler:procedure(ca2_out:boolean);
cb2_handler:procedure(cb2_out:boolean);
irqa_handler:irq_handler;
irqb_handler:irq_handler;
in_a_handler:in_handler;
in_b_handler:in_handler;
out_a_handler:out_handler;
out_b_handler:out_handler;
function ddr_a_r:byte;
function ddr_b_r:byte;
function control_a_r:byte;
procedure ca2_w(state:boolean);
procedure update_interrupts;
procedure set_out_ca2(data:boolean);
procedure set_out_cb2(data:boolean);
function port_a_r:byte;
function get_in_a_value:byte;
function port_b_r:byte;
function get_in_b_value:byte;
function cb2_output_z:boolean;
function control_b_r:byte;
procedure port_a_w(valor:byte);
procedure ddr_a_w(valor:byte);
procedure control_a_w(valor:byte);
procedure port_b_w(valor:byte);
procedure send_to_out_a_func;
procedure send_to_out_b_func;
function get_out_a_value:byte;
function get_out_b_value:byte;
procedure ddr_b_w(valor:byte);
procedure control_b_w(valor:byte);
end;
var
pia6821_0,pia6821_1,pia6821_2:pia6821_chip;
implementation
const
PIA_IRQ1=$80;
PIA_IRQ2=$40;
function irq1_enabled(c:byte):boolean; begin irq1_enabled:=(c and 1)<>0; end;
function c1_low_to_high(c:byte):boolean; begin c1_low_to_high:=(c and 2)<>0; end;
function c1_high_to_low(c:byte):boolean; begin c1_high_to_low:=(c and 2)=0; end;
function output_selected(c:byte):boolean; begin output_selected:=(c and 4)<>0; end;
function irq2_enabled(c:byte):boolean; begin irq2_enabled:=(c and 8)<>0; end;
function strobe_e_reset(c:byte):boolean; begin strobe_e_reset:=(c and 8)<>0; end;
function strobe_c1_reset(c:byte):boolean; begin strobe_c1_reset:=(c and 8)=0; end;
function c2_set(c:byte):boolean; begin c2_set:=(c and 8)<>0; end;
function c2_low_to_high(c:byte):boolean; begin c2_low_to_high:=(c and $10)<>0; end;
function c2_high_to_low(c:byte):boolean; begin c2_high_to_low:=(c and $10)=0; end;
function c2_set_mode(c:byte):boolean; begin c2_set_mode:=(c and $10)<>0; end;
function c2_strobe_mode(c:byte):boolean; begin c2_strobe_mode:=(c and $10)=0; end;
function c2_output(c:byte):boolean; begin c2_output:=(c and $20)<>0; end;
function c2_input(c:byte):boolean; begin c2_input:=(c and $20)=0; end;
constructor pia6821_chip.Create;
begin
self.in_ca1_handler:=nil;
self.in_ca2_handler:=nil;
self.in_cb1_handler:=nil;
self.cb2_handler:=nil;
self.irqa_handler:=nil;
self.irqb_handler:=nil;
self.in_a_handler:=nil;
self.in_b_handler:=nil;
self.out_a_handler:=nil;
self.out_b_handler:=nil;
end;
destructor pia6821_chip.free;
begin
end;
procedure pia6821_chip.change_in_out(in_a,in_b:in_handler;out_a,out_b:out_handler);
begin
self.in_a_handler:=in_a;
self.in_b_handler:=in_b;
self.out_a_handler:=out_a;
self.out_b_handler:=out_b;
end;
procedure pia6821_chip.change_cb(cb2:cb_handler);
begin
self.cb2_handler:=cb2;
end;
procedure pia6821_chip.change_irq(irq_a,irq_b:irq_handler);
begin
self.irqa_handler:=irq_a;
self.irqb_handler:=irq_b;
end;
procedure pia6821_chip.reset;
begin
self.a_input_overrides_output_mask:=0;
self.logged_ca1_not_connected:=false;
self.in_ca1_pushed:=false;
self.logged_ca2_not_connected:=false;
self.in_ca2_pushed:=false;
self.ctl_a:=0;
self.ctl_b:=0;
self.ddr_a:=0;
self.ddr_b:=0;
self.irq_a1:=false;
self.irq_a2:=false;
self.irq_b1:=false;
self.irq_b2:=false;
self.irq_a_state:=false;
self.irq_b_state:=false;
self.in_ca1:=true;
self.in_ca2:=true;
self.out_ca2:=false;
self.out_cb2:=false;
self.out_ca2_needs_pulled:=false;
self.out_cb2_needs_pulled:=false;
self.in_a_pushed:=false;
self.in_b_pushed:=false;
self.in_a:=$ff;
self.in_b:=0;
self.out_a:=0;
self.out_b:=0;
self.port_a_z_mask:=0;
self.logged_port_a_not_connected:=false;
self.logged_port_b_not_connected:=false;
self.last_out_cb2_z:=false;
self.logged_cb1_not_connected:=false;
self.logged_cb2_not_connected:=false;
self.in_cb1_pushed:=false;
self.in_cb2_pushed:=false;
self.in_cb1:=false;
self.out_a_needs_pulled:=false;
self.out_b_needs_pulled:=false;
if addr(self.irqa_handler)<>nil then self.irqa_handler(false);
if addr(self.irqb_handler)<>nil then self.irqb_handler(false);
if addr(self.out_a_handler)<>nil then self.out_a_handler($ff);
if addr(self.ca2_handler)<>nil then self.ca2_handler(true);
//if (addr(self.out_b_handler)<>nil and addr(self.ts_
end;
function pia6821_chip.ddr_a_r:byte;
begin
ddr_a_r:=self.ddr_a;
end;
function pia6821_chip.ddr_b_r:byte;
begin
ddr_b_r:=self.ddr_b;
end;
procedure pia6821_chip.update_interrupts;
var
new_state:boolean;
begin
// start with IRQ A
new_state:=(self.irq_a1 and irq1_enabled(self.ctl_a)) or (self.irq_a2 and irq2_enabled(self.ctl_a));
if (new_state<>self.irq_a_state) then begin
self.irq_a_state:=new_state;
if (addr(irqa_handler)<>nil) then self.irqa_handler(self.irq_a_state);
end;
// then do IRQ B
new_state:=(self.irq_b1 and irq1_enabled(self.ctl_b)) or (self.irq_b2 and irq2_enabled(self.ctl_b));
if (new_state<>self.irq_b_state) then begin
self.irq_b_state:=new_state;
if (addr(irqb_handler)<>nil) then self.irqb_handler(self.irq_b_state);
end;
end;
procedure pia6821_chip.set_out_ca2(data:boolean);
begin
self.out_ca2:=data;
// send to output function
if (addr(self.ca2_handler)<>nil) then self.ca2_handler(self.out_ca2)
else self.out_ca2_needs_pulled:=true;
end;
procedure pia6821_chip.ca1_w(state:boolean);
begin
// the new state has caused a transition
if ((self.in_ca1<>state) and ((state and c1_low_to_high(self.ctl_a)) or (not(state) and c1_high_to_low(self.ctl_a)))) then begin
// mark the IRQ
self.irq_a1:=true;
// update externals
update_interrupts;
// CA2 is configured as output and in read strobe mode and cleared by a CA1 transition
if(c2_output(self.ctl_a) and c2_strobe_mode(self.ctl_a) and strobe_c1_reset(self.ctl_a) and not(self.out_ca2)) then set_out_ca2(true);
end;
// set the new value for CA1
self.in_ca1:=state;
self.in_ca1_pushed:=true;
end;
procedure pia6821_chip.ca2_w(state:boolean);
begin
// if input mode and the new state has caused a transition
if(c2_input(self.ctl_a) and (self.in_ca2<>state) and ((state and c2_low_to_high(self.ctl_a)) or (not(state) and c2_high_to_low(self.ctl_a)))) then begin
// mark the IRQ
self.irq_a2:=true;
// update externals
update_interrupts;
end;
// set the new value for CA2
self.in_ca2:=state;
self.in_ca2_pushed:=true;
end;
function pia6821_chip.control_a_r:byte;
var
ret:byte;
begin
// update CA1 & CA2 if callback exists, these in turn may update IRQ's
if (addr(self.in_ca1_handler)<>nil) then begin
ca1_w(self.in_ca1_handler);
end else if(not(logged_ca1_not_connected) and not(in_ca1_pushed)) then begin
self.logged_ca1_not_connected:=true;
end;
if (addr(in_ca2_handler)<>nil) then begin
ca2_w(in_ca2_handler);
end else if (not(self.logged_ca2_not_connected) and c2_input(ctl_a) and not(in_ca2_pushed)) then begin
self.logged_ca2_not_connected:=true;
end;
// read control register
ret:=ctl_a;
// set the IRQ flags if we have pending IRQs
if irq_a1 then ret:=ret or PIA_IRQ1;
if (irq_a2 and c2_input(ctl_a)) then ret:=ret or PIA_IRQ2;
control_a_r:=ret;
end;
function pia6821_chip.get_in_a_value:byte;
var
port_a_data,ret:byte;
begin
// update the input
if (addr(in_a_handler)<>nil) then begin
port_a_data:=self.in_a_handler;
end else begin
if (self.in_a_pushed) then begin
port_a_data:=self.in_a;
end else begin
// mark all pins disconnected
port_a_data:=$ff;
if (not(self.logged_port_a_not_connected) and (self.ddr_a<>$ff)) then self.logged_port_a_not_connected:=true;
end;
end;
// - connected pins are always read
// - disconnected pins read the output buffer in output mode
// - disconnected pins are HI in input mode
ret:=(not(self.ddr_a) and port_a_data) // input pins
or (self.ddr_a and self.out_a and not(self.a_input_overrides_output_mask)) // normal output pins
or (self.ddr_a and port_a_data and self.a_input_overrides_output_mask); // overridden output pins
get_in_a_value:=ret;
end;
function pia6821_chip.port_a_r:byte;
var
ret:byte;
begin
ret:=self.get_in_a_value;
// IRQ flags implicitly cleared by a read
self.irq_a1:=false;
self.irq_a2:=false;
self.update_interrupts;
// CA2 is configured as output and in read strobe mode
if (c2_output(self.ctl_a) and c2_strobe_mode(self.ctl_a)) then begin
// this will cause a transition low
if self.out_ca2 then set_out_ca2(false);
// if the CA2 strobe is cleared by the E, reset it right away
if (strobe_e_reset(self.ctl_a)) then set_out_ca2(true);
end;
port_a_r:=ret;
end;
function pia6821_chip.get_in_b_value:byte;
var
port_b_data,ret:byte;
begin
// all output, just return buffer
if (self.ddr_b=$ff) then begin
ret:=self.out_b;
end else begin
// update the input
if (addr(in_b_handler)<>nil) then begin
port_b_data:=self.in_b_handler;
end else begin
if (self.in_b_pushed) then begin
port_b_data:=self.in_b;
end else begin
if (not(self.logged_port_b_not_connected) and (self.ddr_b<>$ff)) then self.logged_port_b_not_connected:=true;
// undefined -- need to return something
port_b_data:=$00;
end;
end;
// the DDR determines if the pin or the output buffer is read
ret:= (self.out_b and self.ddr_b) or (port_b_data and not(self.ddr_b));
end;
get_in_b_value:=ret;
end;
function pia6821_chip.cb2_output_z:boolean;
begin
cb2_output_z:=not(c2_output(self.ctl_b));
end;
procedure pia6821_chip.set_out_cb2(data:boolean);
var
z:boolean;
begin
z:=cb2_output_z;
if ((data<>self.out_cb2) or (z<>self.last_out_cb2_z)) then begin
self.out_cb2:=data;
self.last_out_cb2_z:=z;
// send to output function
if (addr(self.cb2_handler)<>nil) then self.cb2_handler(self.out_cb2)
else self.out_cb2_needs_pulled:=true;
end;
end;
function pia6821_chip.port_b_r:byte;
var
ret:byte;
begin
ret:=self.get_in_b_value;
// This read will implicitly clear the IRQ B1 flag. If CB2 is in write-strobe
// mode with CB1 restore, and a CB1 active transition set the flag,
// clearing it will cause CB2 to go high again. Note that this is different
// from what happens with port A.
if(self.irq_b1 and c2_strobe_mode(self.ctl_b) and strobe_c1_reset(self.ctl_b)) then set_out_cb2(true);
// IRQ flags implicitly cleared by a read
self.irq_b1:=false;
self.irq_b2:=false;
self.update_interrupts;
port_b_r:=ret;
end;
procedure pia6821_chip.cb1_w(state:boolean);
begin
// the new state has caused a transition
if ((self.in_cb1<>state) and ((state and c1_low_to_high(self.ctl_b)) or (not(state) and c1_high_to_low(self.ctl_b)))) then begin
// mark the IRQ
self.irq_b1:=true;
// update externals
self.update_interrupts;
// If CB2 is configured as a write-strobe output which is reset by a CB1
// transition, this reset will only happen when a read from port B implicitly
// clears the IRQ B1 flag. So we handle the CB2 reset there. Note that this
// is different from what happens with port A.
end;
// set the new value for CB1
self.in_cb1:=state;
self.in_cb1_pushed:=true;
end;
function pia6821_chip.control_b_r:byte;
var
ret:byte;
begin
// update CB1 & CB2 if callback exists, these in turn may update IRQ's
if (addr(self.in_cb1_handler)<>nil) then begin
cb1_w(in_cb1_handler);
end else if (not(self.logged_cb1_not_connected) and not(in_cb1_pushed)) then begin
self.logged_cb1_not_connected:=true;
end;
if(not(logged_cb2_not_connected) and c2_input(self.ctl_b) and not(in_cb2_pushed)) then begin
self.logged_cb2_not_connected:=true;
end;
// read control register
ret:=self.ctl_b;
// set the IRQ flags if we have pending IRQs
if(self.irq_b1) then ret:=ret or PIA_IRQ1;
if(self.irq_b2 and c2_input(self.ctl_b)) then ret:=ret or PIA_IRQ2;
control_b_r:=ret;
end;
function pia6821_chip.read(dir:byte):byte;
var
ret:byte;
begin
case (dir and $03) of
$00:if (output_selected(ctl_a)) then ret:=port_a_r
else ret:=ddr_a_r;
$01:ret:=control_a_r;
$02:if (output_selected(ctl_b)) then ret:=port_b_r
else ret:=ddr_b_r;
$03:ret:=control_b_r;
end;
read:=ret;
end;
procedure pia6821_chip.port_a_w(valor:byte);
begin
// buffer the output value
self.out_a:=valor;
self.send_to_out_a_func;
end;
function pia6821_chip.get_out_a_value:byte;
var
ret:byte;
begin
if (self.ddr_a=$ff) then // all output
ret:=self.out_a
else // input pins don't change
ret:=(self.out_a and self.ddr_a) or (self.get_in_a_value and not(self.ddr_a));
get_out_a_value:=ret;
end;
procedure pia6821_chip.send_to_out_a_func;
var
data:byte;
begin
// input pins are pulled high
data:=self.get_out_a_value;
if (addr(self.out_a_handler)<>nil) then self.out_a_handler(data)
else self.out_a_needs_pulled:=true;
end;
procedure pia6821_chip.ddr_a_w(valor:byte);
begin
if (self.ddr_a<>valor) then begin
// DDR changed, call the callback again
self.ddr_a:=valor;
self.logged_port_a_not_connected:=false;
self.send_to_out_a_func;
end;
end;
procedure pia6821_chip.control_a_w(valor:byte);
var
ca2_was_output,tempb2:boolean;
begin
// bit 7 and 6 are read only
valor:=valor and $3f;
// update the control register
ca2_was_output:=c2_output(self.ctl_a);
self.ctl_a:=valor;
// CA2 is configured as output
if (c2_output(self.ctl_a)) then begin
if (c2_set_mode(self.ctl_a)) then begin // set/reset mode - bit value determines the new output
tempb2:=c2_set(self.ctl_a);
if (not(ca2_was_output) or (self.out_ca2<>tempb2)) then set_out_ca2(tempb2);
end else begin // strobe mode - output is always high unless strobed
if (not(ca2_was_output) or not(self.out_ca2)) then self.set_out_ca2(true); // strobe mode - output is always high unless strobed
end;
end else begin
if ca2_was_output then begin
if addr(self.ca2_handler)<>nil then self.ca2_handler(true);
end;
end;
// update externals
self.update_interrupts;
end;
function pia6821_chip.get_out_b_value:byte;
begin
// input pins are high-impedance - we just send them as zeros for backwards compatibility
get_out_b_value:=self.out_b and self.ddr_b;
end;
procedure pia6821_chip.send_to_out_b_func;
var
data:byte;
begin
// input pins are high-impedance - we just send them as zeros for backwards compatibility
data:=self.get_out_b_value;
if (addr(self.out_b_handler)<>nil) then self.out_b_handler(data)
else self.out_b_needs_pulled:=true;
end;
procedure pia6821_chip.port_b_w(valor:byte);
begin
// buffer the output value
self.out_b:=valor;
self.send_to_out_b_func;
// CB2 in write strobe mode
if (c2_strobe_mode(self.ctl_b)) then begin
// this will cause a transition low
self.set_out_cb2(false);
// if the CB2 strobe is cleared by the E, reset it right away
if (strobe_e_reset(self.ctl_b)) then set_out_cb2(true);
end;
end;
procedure pia6821_chip.ddr_b_w(valor:byte);
begin
if (self.ddr_b<>valor) then begin
// DDR changed, call the callback again
self.ddr_b:=valor;
self.logged_port_b_not_connected:=false;
self.send_to_out_b_func;
end;
end;
procedure pia6821_chip.control_b_w(valor:byte);
var
temp:boolean;
begin
// bit 7 and 6 are read only
valor:=valor and $3f;
// update the control register
self.ctl_b:=valor;
if (c2_set_mode(self.ctl_b)) then // set/reset mode - bit value determines the new output
temp:=c2_set(self.ctl_b)
else // strobe mode - output is always high unless strobed
temp:=true;
self.set_out_cb2(temp);
// update externals
self.update_interrupts;
end;
procedure pia6821_chip.write(dir,valor:byte);
begin
case (dir and $3) of
$00:if (output_selected(self.ctl_a)) then port_a_w(valor)
else ddr_a_w(valor);
$01:control_a_w(valor);
$02:if (output_selected(self.ctl_b)) then port_b_w(valor)
else ddr_b_w(valor);
$03:control_b_w(valor);
end;
end;
procedure pia6821_chip.portb_w(valor:byte);
begin
//assert_always(m_in_b_handler.isnull(), "pia_set_input_b() called when in_b_func implemented");
self.in_b:=valor;
self.in_b_pushed:=true;
end;
end.
|
unit K609602166;
{* [Requestlink:609602166] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K609602166.pas"
// Стереотип: "TestCase"
// Элемент модели: "K609602166" MUID: (5625E50C0063)
// Имя типа: "TK609602166"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK609602166 = class(TRTFtoEVDWriterTest)
{* [Requestlink:609602166] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK609602166
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *5625E50C0063impl_uses*
//#UC END# *5625E50C0063impl_uses*
;
function TK609602166.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.12';
end;//TK609602166.GetFolder
function TK609602166.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '5625E50C0063';
end;//TK609602166.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK609602166.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit Test.Models;
interface
uses
Spring,
System.Variants;
type
TAddress = class
private
FStreet: string;
FNumHouse: integer;
public
property Street: string read FStreet;
property NumHouse: integer read FNumHouse;
constructor Create(const AStreet: string; const ANumHouse: integer);
end;
TAddressWriteble = class
private
FStreet: string;
FNumHouse: integer;
public
property Street: string read FStreet write FStreet;
property NumHouse: integer read FNumHouse write FNumHouse;
constructor Create(const AStreet: string; const ANumHouse: integer);
end;
{$M+}
TPerson = class
private
FLastName: string;
FFirstName: string;
FMiddleName: Nullable<string>;
FAge: Nullable<integer>;
FAddress: TAddress;
FPost: string;
public
Status: Nullable<integer>;
published
property LastName: string read FLastName;
property FirstName: string read FFirstName;
property MiddleName: Nullable<string> read FMiddleName;
property Age: Nullable<integer> read FAge;
property Address: TAddress read FAddress;
property Post: string read FPost;
constructor Create(ALastName, AFirstName: string; AMiddleName: Nullable<string>; AAge: Nullable<integer>; AAddress: TAddress; APost: string); overload;
end;
implementation
{ TPerson }
constructor TPerson.Create(ALastName, AFirstName: string;
AMiddleName: Nullable<string>; AAge: Nullable<integer>; AAddress: TAddress; APost: string);
begin
FLastName := ALastName;
FFirstName := AFirstName;
FMiddleName := AMiddleName;
FAge := AAge;
FAddress := AAddress;
FPost := APost;
end;
{ TAddress }
constructor TAddress.Create(const AStreet: string; const ANumHouse: integer);
begin
FStreet := AStreet;
FNumHouse := ANumHouse;
end;
{ TAddressWriteble }
constructor TAddressWriteble.Create(const AStreet: string;
const ANumHouse: integer);
begin
FStreet := AStreet;
FNumHouse := ANumHouse;
end;
end.
|
unit uImageConsts;
interface
type
TImageConsts = class
public
class function GetRequiredControlImagePath: string;
end;
const
cRequiredControlImagePath = 'C:\Users\Anonymous\Desktop\Projekty\WorkPoint\obr\ExclamationMark.png';
implementation
{ TImageConsts }
class function TImageConsts.GetRequiredControlImagePath: string;
begin
Result := cRequiredControlImagePath;
end;
end.
|
{ Invokable interface IServico }
unit ServicoIntf;
interface
uses InvokeRegistry, Types, XSBuiltIns, Classes, uLib;
type
{ Invokable interfaces must derive from IInvokable }
IServico = interface(IInvokable)
['{C10CE1E8-ED99-4A45-9DFD-ABDD9B0DEACB}']
function SendNotFis(ChaveAut: string; aNomeArquivo: string; aConteudoArquivo: WideString): string; stdcall;
function GetOcorren(ChaveAut, Filial, TpChave, Chave, dtInicial, dtFinal: string): string; stdcall;
{ Methods of Invokable interface must not use the default }
{ calling convention; stdcall is recommended }
end;
implementation
initialization
{ Invokable interfaces must be registered }
InvRegistry.RegisterInterface(TypeInfo(IServico));
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.IO,
RemObjects.Elements.EUnit;
type
FileUtilsTest = public class (Test)
private
const NAME: String = "sugar.testcase.txt";
private
FileName: String;
CopyName: String;
public
method Setup; override;
method TearDown; override;
method CopyTest;
method Create;
method Delete;
method Exists;
method Move;
method AppendText;
method AppendBytes;
method AppendBinary;
method ReadText;
method ReadBytes;
method ReadBinary;
method WriteBytes;
method WriteText;
method WriteBinary;
end;
implementation
method FileUtilsTest.Setup;
begin
var aFile := Folder.UserLocal.CreateFile(NAME, false);
FileUtils.WriteText(aFile.Path, "");
FileName := aFile.Path;
CopyName := FileName+".copy";
end;
method FileUtilsTest.TearDown;
begin
if FileUtils.Exists(FileName) then
FileUtils.Delete(FileName);
if FileUtils.Exists(CopyName) then
FileUtils.Delete(CopyName);
end;
method FileUtilsTest.CopyTest;
begin
Assert.IsTrue(FileUtils.Exists(FileName));
Assert.IsFalse(FileUtils.Exists(CopyName));
FileUtils.Copy(FileName, CopyName);
Assert.IsTrue(FileUtils.Exists(FileName));
Assert.IsTrue(FileUtils.Exists(CopyName));
Assert.Throws(->FileUtils.Copy(FileName, CopyName));
Assert.Throws(->FileUtils.Copy(nil, CopyName));
Assert.Throws(->FileUtils.Copy(FileName, nil));
Assert.Throws(->FileUtils.Copy(FileName+"doesnotexists", CopyName));
end;
method FileUtilsTest.Create;
begin
Assert.IsFalse(FileUtils.Exists(CopyName));
FileUtils.Create(CopyName);
Assert.IsTrue(FileUtils.Exists(CopyName));
Assert.Throws(->FileUtils.Create(CopyName));
Assert.Throws(->FileUtils.Create(nil));
end;
method FileUtilsTest.Delete;
begin
Assert.IsFalse(FileUtils.Exists(CopyName));
Assert.Throws(->FileUtils.Delete(CopyName));
Assert.Throws(->FileUtils.Delete(nil));
Assert.IsTrue(FileUtils.Exists(FileName));
FileUtils.Delete(FileName);
Assert.IsFalse(FileUtils.Exists(FileName));
end;
method FileUtilsTest.Exists;
begin
Assert.IsTrue(FileUtils.Exists(FileName));
Assert.IsFalse(FileUtils.Exists(CopyName));
FileUtils.Create(CopyName);
Assert.IsTrue(FileUtils.Exists(CopyName));
FileUtils.Delete(FileName);
Assert.IsFalse(FileUtils.Exists(FileName));
end;
method FileUtilsTest.Move;
begin
Assert.IsTrue(FileUtils.Exists(FileName));
Assert.IsFalse(FileUtils.Exists(CopyName));
FileUtils.Move(FileName, CopyName);
Assert.IsFalse(FileUtils.Exists(FileName));
Assert.IsTrue(FileUtils.Exists(CopyName));
Assert.Throws(->FileUtils.Move(CopyName, CopyName));
Assert.Throws(->FileUtils.Move(nil, CopyName));
Assert.Throws(->FileUtils.Move(FileName, nil));
Assert.Throws(->FileUtils.Move(CopyName+"doesnotexists", FileName));
end;
method FileUtilsTest.AppendText;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.AppendText(FileName, "Hello");
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
FileUtils.AppendText(FileName, " World");
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello World");
Assert.Throws(->FileUtils.AppendText(FileName, nil));
Assert.Throws(->FileUtils.AppendText(nil, ""));
end;
method FileUtilsTest.AppendBytes;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.AppendBytes(FileName, String("Hello").ToByteArray);
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
FileUtils.AppendBytes(FileName, String(" World").ToByteArray);
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello World");
Assert.Throws(->FileUtils.AppendBytes(FileName, nil));
Assert.Throws(->FileUtils.AppendBytes(nil, []));
end;
method FileUtilsTest.AppendBinary;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.AppendBinary(FileName, new Binary(String("Hello").ToByteArray));
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
FileUtils.AppendBinary(FileName, new Binary(String(" World").ToByteArray));
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello World");
Assert.Throws(->FileUtils.AppendBinary(FileName, nil));
Assert.Throws(->FileUtils.AppendBinary(nil, new Binary));
end;
method FileUtilsTest.ReadText;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.WriteText(FileName, "Hello");
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
Assert.Throws(->FileUtils.ReadText(nil, Encoding.UTF8));
Assert.Throws(->FileUtils.ReadText(CopyName, Encoding.UTF8));
end;
method FileUtilsTest.ReadBytes;
begin
Assert.AreEqual(length(FileUtils.ReadBytes(FileName)), 0);
var Expected: array of Byte := [4, 8, 15, 16, 23, 42];
FileUtils.WriteBytes(FileName, Expected);
var Actual := FileUtils.ReadBytes(FileName);
Assert.IsTrue(Actual <> nil);
Assert.AreEqual(length(Actual), length(Expected));
Assert.AreEqual(Actual, Expected);
Assert.Throws(->FileUtils.ReadBytes(nil));
Assert.Throws(->FileUtils.ReadBytes(CopyName));
end;
method FileUtilsTest.ReadBinary;
begin
var Actual: Binary := FileUtils.ReadBinary(FileName);
Assert.IsNotNil(Actual);
Assert.AreEqual(Actual.Length, 0);
var Expected: array of Byte := [4, 8, 15, 16, 23, 42];
FileUtils.WriteBytes(FileName, Expected);
Actual := FileUtils.ReadBinary(FileName);
Assert.IsNotNil(Actual);
Assert.AreEqual(Actual.Length, length(Expected));
Assert.AreEqual(Actual.ToArray, Expected);
Assert.Throws(->FileUtils.ReadBinary(nil));
Assert.Throws(->FileUtils.ReadBinary(CopyName));
end;
method FileUtilsTest.WriteBytes;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.WriteBytes(FileName, String("Hello").ToByteArray);
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
FileUtils.WriteBytes(FileName, String("World").ToByteArray);
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "World");
Assert.Throws(->FileUtils.WriteBytes(FileName, nil));
Assert.Throws(->FileUtils.WriteBytes(nil, []));
end;
method FileUtilsTest.WriteText;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.WriteText(FileName, "Hello");
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
FileUtils.WriteText(FileName, "World");
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "World");
Assert.Throws(->FileUtils.WriteText(FileName, nil));
Assert.Throws(->FileUtils.WriteText(nil, ""));
end;
method FileUtilsTest.WriteBinary;
begin
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "");
FileUtils.WriteBinary(FileName, new Binary(String("Hello").ToByteArray));
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "Hello");
FileUtils.WriteBinary(FileName, new Binary(String("World").ToByteArray));
Assert.AreEqual(FileUtils.ReadText(FileName, Encoding.UTF8), "World");
Assert.Throws(->FileUtils.WriteBinary(FileName, nil));
Assert.Throws(->FileUtils.WriteBinary(nil, new Binary));
end;
end. |
unit atXMLScenarioGenerator;
// Модуль: "w:\quality\test\garant6x\AdapterTest\OperationsFramework\atXMLScenarioGenerator.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatXMLScenarioGenerator" MUID: (483EC52400C9)
interface
uses
l3IntfUses
, atScenario
, atOperationBase
, XMLIntf
, SysUtils
;
type
EInvalidXMLScenario = class(Exception)
end;//EInvalidXMLScenario
TatXMLScenarioGenerator = class
private
f_Scenario: TatScenario;
private
procedure FillOperationParameters(anOperation: TatOperationBase;
const anAttributes: IXMLNodeList); virtual;
procedure ParseXMLDoc(const aXmlDoc: IXMLDocument); virtual;
procedure ParseOperationNode(const aXmlNode: IXMLNode;
aParentOp: TatOperationBase); virtual;
public
function FillScenario(aScenario: TatScenario;
const aXmlFileName: AnsiString): Boolean; virtual;
end;//TatXMLScenarioGenerator
implementation
uses
l3ImplUses
, atLogger
, atOperationFactory
, XMLDoc
{$If NOT Defined(NoScripts)}
, TtfwTypeRegistrator_Proxy
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *483EC52400C9impl_uses*
//#UC END# *483EC52400C9impl_uses*
;
function TatXMLScenarioGenerator.FillScenario(aScenario: TatScenario;
const aXmlFileName: AnsiString): Boolean;
//#UC START# *483ECFCA023D_483EC52400C9_var*
var
xmlDoc : IXMLDocument;
//#UC END# *483ECFCA023D_483EC52400C9_var*
begin
//#UC START# *483ECFCA023D_483EC52400C9_impl*
xmlDoc := TXMLDocument.Create(aXmlFileName);
Assert(aScenario <> nil, 'aScenario <> nil');
f_Scenario := aScenario;
ParseXMLDoc(xmlDoc);
Result := true;
//#UC END# *483ECFCA023D_483EC52400C9_impl*
end;//TatXMLScenarioGenerator.FillScenario
procedure TatXMLScenarioGenerator.FillOperationParameters(anOperation: TatOperationBase;
const anAttributes: IXMLNodeList);
//#UC START# *483ECFFD02CA_483EC52400C9_var*
var
i : Integer;
attribute : IXMLNode;
//#UC END# *483ECFFD02CA_483EC52400C9_var*
begin
//#UC START# *483ECFFD02CA_483EC52400C9_impl*
for i := 0 to anAttributes.Count-1 do
begin
attribute := anAttributes.Nodes[i];
if attribute.NodeName = 'name' then
continue
else
anOperation.Parameters[attribute.NodeName].AsStr := attribute.NodeValue;
end;
//#UC END# *483ECFFD02CA_483EC52400C9_impl*
end;//TatXMLScenarioGenerator.FillOperationParameters
procedure TatXMLScenarioGenerator.ParseXMLDoc(const aXmlDoc: IXMLDocument);
//#UC START# *483ED078005D_483EC52400C9_var*
var
nodes : IXMLNodeList;
scenarioNode : IXMLNode;
operationNodes : IXMLNodeList;
i : integer;
//#UC END# *483ED078005D_483EC52400C9_var*
begin
//#UC START# *483ED078005D_483EC52400C9_impl*
nodes := aXmlDoc.ChildNodes;
if nodes.Count <> 2 then
Raise EInvalidXMLScenario.Create(Logger.Error('В xml-файле обнаружено более одного корневого элемента!'));
nodes := nodes.Nodes['scenarios'].ChildNodes;
scenarioNode := nodes.Nodes['scenario'];
if (scenarioNode = nil) then
Raise EInvalidXMLScenario.Create(Logger.Error('Cценарий не найден!'));
// парсим ноду сценария
FillOperationParameters(f_Scenario, scenarioNode.AttributeNodes);
// парсим операции
operationNodes := scenarioNode.ChildNodes;
if (operationNodes.Count < 1) then
Raise EInvalidXMLScenario.Create(Logger.Error('Должна быть как-минимум одна операция!'));
for i := 0 to operationNodes.Count-1 do
ParseOperationNode(operationNodes.Nodes[i], f_Scenario);
//#UC END# *483ED078005D_483EC52400C9_impl*
end;//TatXMLScenarioGenerator.ParseXMLDoc
procedure TatXMLScenarioGenerator.ParseOperationNode(const aXmlNode: IXMLNode;
aParentOp: TatOperationBase);
//#UC START# *483ED09F0138_483EC52400C9_var*
var
opName : String;
attributes, childs : IXMLNodeList;
operation : TatOperationBase;
i : integer;
//#UC END# *483ED09F0138_483EC52400C9_var*
begin
//#UC START# *483ED09F0138_483EC52400C9_impl*
if (aXmlNode.NodeType = ntComment) then
Exit; // пропускаем комментарии
if (aXmlNode.NodeName <> 'operation') then
Raise EInvalidXMLScenario.Create(Logger.Error('Ожидали ноду operation, а встретили "' + aXmlNode.NodeName + '"'));
// получаем имя операции и создаем ее
opName := aXmlNode.Attributes['name'];
operation := OperationFactory.MakeOperation(opName);
attributes := aXmlNode.AttributeNodes;
// добавляем к родителю
aParentOp.AddChild(operation);
// заполняем параметры
FillOperationParameters(operation, attributes);
operation.AfterFillingParamList();
// парсим детей
childs := aXmlNode.ChildNodes;
for i := 0 to childs.Count-1 do
ParseOperationNode(childs.Nodes[i], operation);
//#UC END# *483ED09F0138_483EC52400C9_impl*
end;//TatXMLScenarioGenerator.ParseOperationNode
initialization
{$If NOT Defined(NoScripts)}
TtfwTypeRegistrator.RegisterType(TypeInfo(EInvalidXMLScenario));
{* Регистрация типа EInvalidXMLScenario }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit K585129079_NSRC;
{* [RequestLink:585129079] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K585129079_NSRC.pas"
// Стереотип: "TestCase"
// Элемент модели: "K585129079_NSRC" MUID: (5491A60A003A)
// Имя типа: "TK585129079_NSRC"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, EVDtoBothNSRCWriterTest
;
type
TK585129079_NSRC = class(TEVDtoBothNSRCWriterTest)
{* [RequestLink:585129079] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK585129079_NSRC
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *5491A60A003Aimpl_uses*
//#UC END# *5491A60A003Aimpl_uses*
;
function TK585129079_NSRC.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.11';
end;//TK585129079_NSRC.GetFolder
function TK585129079_NSRC.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '5491A60A003A';
end;//TK585129079_NSRC.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK585129079_NSRC.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ShellApi, StrUtils ;
type
TForm1 = class(TForm)
txnType: TComboBox;
Label2: TLabel;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
txnReference: TEdit;
txnAmount: TEdit;
txnCurrency: TEdit;
Label5: TLabel;
Label9: TLabel;
Label7: TLabel;
merchantID: TEdit;
altMerchantID: TEdit;
Label8: TLabel;
shortCode: TEdit;
customerID: TEdit;
LaunchBtn: TButton;
ComanndArg: TEdit;
Command: TLabel;
Result: TEdit;
Label6: TLabel;
procedure LaunchBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255] of AnsiChar;
BytesRead: Cardinal;
WorkDir: string;
Handle: Boolean;
begin
Result := '';
with SA do begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
WorkDir := Work;
Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
Result := Result + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(PI.hProcess, INFINITE);
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
procedure TForm1.LaunchBtnClick(Sender: TObject);
var
GeneratorCmd, HcpUrl, CurrPath: string;
begin
LaunchBtn.Caption := 'Processing, please wait ...';
LaunchBtn.Enabled := False;
CurrPath := GetCurrentDir();
GeneratorCmd := 'php\php.exe php\generatehcp.php' +
' --txnType=' + txnType.Text +
' --txnReference=' + txnReference.Text +
' --txnAmount=' + txnAmount.Text +
' --txnCurrency=' + txnCurrency.Text +
' --merchantID=' + merchantID.Text+
' --shortCode=' + shortCode.Text +
' --altMerchantID='+ altMerchantID.Text +
' --customerID=' + customerID.Text+
' --transactionKey=***REPLACE-WITH-TRANSACTION-KEY***';
HcpUrl := GetDosOutput(GeneratorCmd,CurrPath);
ComanndArg.Text := GeneratorCmd;
Result.Text := HcpUrl;
//if AnsiContainsText(HcpUrl,'hpp') then ShellExecute(self.WindowHandle,'open',PChar(HcpUrl),nil,nil, SW_SHOWNORMAL);
LaunchBtn.Caption := 'Launch HCP';
LaunchBtn.Enabled := True;
end;
end.
|
//Exercício 7: Escreva um algoritmo que receba o valor das 3 notas de um aluno, calcule e exiba sua média podenrada
//conforme a fórmula: (1ª prova(peso 2) + 2ª prova (peso 3) + 3ª prova(peso 4))/9
{ Solução em Portugol
Algoritmo Exercicio7;
Var
P1,P2,P3,media_ponderada: real;
Inicio
exiba("Programa que calcula a média ponderada de um aluno.");
exiba("Digite a nota da primeira prova: ");
leia(P1);
exiba("Digite a nota da segunda prova: ");
leia(P2);
exiba("Digite a nota da terceira prova: ");
leia(P3);
media_ponderada <- (2 * P1 + 3 * P2 + 4 * P3)/9;
exiba("A média ponderada do aluno é: ",media_ponderada);
Fim.
}
// Solução em Pascal
Program Exercicio7;
uses crt;
var
P1,P2,P3,media_ponderada:real;
begin
clrscr;
writeln('Programa que calcula a média ponderada de um aluno.');
writeln('Digite a nota da primeira prova: ');
readln(P1);
writeln('Digite a nota da segunda prova: ');
readln(P2);
writeln('Digite a nota da terceira prova: ');
readln(P3);
media_ponderada := (2 * P1 + 3 * P2 + 4 * P3)/9;
writeln('A média ponderada do aluno é: ',media_ponderada:2:2);
repeat until keypressed;
end.
|
unit LandInfo;
interface
uses
Land, Windows, Graphics, Collection;
const
LandMax = 10000;
type
PLandMatrix = ^TLandMatrix;
TLandMatrix = array[0..LandMax*LandMax] of TLandVisualClassId;
type
TLandClassInfo =
class( TInterfacedObject, ILandClassInfo )
public
constructor Create( classfile : string );
private
fImageURL : string;
fAlterColor : TColor;
fLandVisualClassId : TLandVisualClassId;
private
function GetImageURL( zoomlevel : integer ) : string;
function GetAlterColor : TColor;
function GetLandVisualClassId : TLandVisualClassId;
end;
TLandClassesInfo =
class( TInterfacedObject, ILandClassesInfo )
public
constructor Create( classdir : string );
destructor Destroy; override;
private
fLandClassesInfo : TCollection;
private
function GetClass( LandVisualClassId : TLandVisualClassId ) : ILandClassInfo;
end;
TLandInfo =
class( TInterfacedObject, ILandInfo )
public
constructor Create( Bitmap : TBitmap );
destructor Destroy; override;
private
fLandMatrix : PLandMatrix;
fLandSize : TPoint;
private
function LandSize : TPoint;
function LandVisualClassAt( x, y : integer ) : TLandVisualClassId;
function LandClassAt( x, y : integer ) : TLandClass;
function LandTypeAt( x, y : integer ) : TLandType;
end;
implementation
uses
IniFiles, SysUtils;
// TLandClassInfo
constructor TLandClassInfo.Create( classfile : string );
var
IniFile : TIniFile;
begin
inherited Create;
IniFile := TIniFile.Create( classfile );
try
fImageURL := IniFile.ReadString( 'Images', '64x32', 'unknown.gif' );
fAlterColor := IniFile.ReadInteger( 'General', 'MapColor', 0 );
fLandVisualClassId := IniFile.ReadInteger( 'General', 'Id', NoLand );
finally
IniFile.Free;
end;
end;
function TLandClassInfo.GetImageURL( zoomlevel : integer ) : string;
begin
result := fImageURL;
end;
function TLandClassInfo.GetAlterColor : TColor;
begin
result := fAlterColor;
end;
function TLandClassInfo.GetLandVisualClassId : TLandVisualClassId;
begin
result := fLandVisualClassId;
end;
// TLandClassesInfo
constructor TLandClassesInfo.Create( classdir : string );
procedure LoadClasses;
var
SearchRec : TSearchRec;
LandClassInfo : TLandClassInfo;
begin
if FindFirst( classdir + '*.ini', faAnyFile, SearchRec ) = 0
then
repeat
LandClassInfo := TLandClassInfo.Create( ClassDir + SearchRec.Name );
fLandClassesInfo.Insert( LandClassInfo );
until FindNext( SearchRec ) <> 0;
end;
begin
inherited Create;
try
fLandClassesInfo := TCollection.Create( 0, rkBelonguer );
except
fLandClassesInfo.Free;
raise;
end;
end;
destructor TLandClassesInfo.Destroy;
begin
fLandClassesInfo.Free;
inherited;
end;
function TLandClassesInfo.GetClass( LandVisualClassId : TLandVisualClassId ) : ILandClassInfo;
var
i : integer;
begin
i := 0;
while (i < fLandClassesInfo.Count) and (TLandClassInfo(fLandClassesInfo[i]).GetLandVisualClassId <> LandVisualClassId) do
inc( i );
if i < fLandClassesInfo.Count
then result := TLandClassInfo(fLandClassesInfo[i])
else result := nil;
end;
// TLandInfo
constructor TLandInfo.Create( Bitmap : TBitmap );
procedure LoadLandInfo( Bitmap : TBitmap );
var
x, y : integer;
line : PByteArray;
begin
for y := 0 to pred(fLandSize.y) do
begin
line := Bitmap.ScanLine[y];
for x := 0 to pred(fLandSize.x) do
fLandMatrix[fLandSize.x*y + x] := line[x];
end;
end;
begin
inherited Create;
fLandSize.x := Bitmap.Width;
fLandSize.y := Bitmap.Height;
getmem( fLandMatrix, fLandSize.x*fLandSize.y*sizeof(fLandMatrix[0]) );
try
fillchar( fLandMatrix^, fLandSize.x*fLandSize.y*sizeof(fLandMatrix[0]), NoLand );
LoadLandInfo( Bitmap );
except
freemem( fLandMatrix );
raise;
end;
end;
destructor TLandInfo.Destroy;
begin
freemem( fLandMatrix );
inherited;
end;
function TLandInfo.LandSize : TPoint;
begin
result := fLandSize;
end;
function TLandInfo.LandVisualClassAt( x, y : integer ) : TLandVisualClassId;
begin
result := fLandMatrix[fLandSize.x*y + x];
end;
function TLandInfo.LandClassAt( x, y : integer ) : TLandClass;
begin
result := Land.LandPrimaryClassOf( LandVisualClassAt( x, y ));
end;
function TLandInfo.LandTypeAt( x, y : integer ) : TLandType;
begin
result := Land.LandTypeOf( LandVisualClassAt( x, y ));
end;
end.
|
unit vtFocusLabel;
{ Библиотека "" }
{ Начал: Люлин А.В. }
{ Модуль: vtFocusLabel - }
{ Начат: 29.03.2007 20:12 }
{ $Id: vtFocusLabel.pas,v 1.24 2013/05/14 14:37:20 morozov Exp $ }
// $Log: vtFocusLabel.pas,v $
// Revision 1.24 2013/05/14 14:37:20 morozov
// {RequestLink:449678181}
//
// Revision 1.23 2011/01/21 14:19:44 lulin
// {RequestLink:245209881}.
// - граммар наци.
//
// Revision 1.22 2011/01/21 13:13:46 lulin
// - чистка кода.
//
// Revision 1.21 2011/01/21 08:23:09 vkuprovich
// {RequestLink:228688553}
// Mark (квадратик слева от контрола) стал объемным - [$251334989]
//
// Revision 1.20 2011/01/20 16:06:44 vkuprovich
// {RequestLink:228688553}
// Ссылки в диалогах теперь отображают слева от себя квадратик [$251334731]
//
// Revision 1.19 2010/11/15 16:54:28 lulin
// {RequestLink:241010148}.
//
// Revision 1.18 2010/07/21 06:22:20 oman
// - fix: {RequestLink:220595111}
//
// Revision 1.17 2010/05/27 07:36:51 oman
// - fix: {RequestLink:197493364}
//
// Revision 1.16 2010/03/15 11:09:29 oman
// - new: {RequestLink:197493364}
//
// Revision 1.15 2010/01/27 12:14:59 oman
// - new: развлекаемся с метками {RequestLink:182452345}
//
// Revision 1.14 2010/01/14 17:29:06 lulin
// {RequestLink:177538554}.
//
// Revision 1.13 2010/01/13 14:50:04 lulin
// {RequestLink:177538554}.
//
// Revision 1.11 2009/12/30 10:54:43 lulin
// {RequestLink:175966766}.
//
// Revision 1.10 2009/09/03 06:52:41 oman
// - new: Зачистка - {RequestLink:159369920}
//
// Revision 1.9 2009/09/02 11:48:58 lulin
// {RequestLink:159360578}. №20.
//
// Revision 1.8 2009/01/21 15:30:18 lulin
// - боремся со шрифтами.
//
// Revision 1.7 2008/09/02 12:38:16 lulin
// - <K>: 88080895.
//
// Revision 1.6 2008/09/01 14:19:38 lulin
// - <K>: 112722344.
//
// Revision 1.5 2007/08/14 19:31:40 lulin
// - оптимизируем очистку памяти.
//
// Revision 1.4 2007/05/25 11:57:43 oman
// - fix: Фокусирующую рамку рисуем цветом текста (cq25398)
//
// Revision 1.3 2007/04/24 14:39:14 oman
// - fix: Не было возможности настраивать цвета.
// Готовим контролы для базового поиска (cq25145)
//
// Revision 1.2 2007/03/29 17:27:12 lulin
// - даем компонентам правильные названия.
//
// Revision 1.1 2007/03/29 17:02:36 lulin
// - отделяем мух от котлет.
//
{$Include vtDefine.inc }
interface
uses
Windows,
Types,
Messages,
Classes,
Graphics,
Controls,
l3Interfaces,
l3Types,
l3InternalInterfaces,
afwTextControl
;
type
TvtFocusLabel = class(TafwTextControl)
private
// internal fields
f_Group : Boolean;
f_AutoWidth : Boolean;
f_Alignment : TAlignment;
f_HighlightColor : TColor;
f_TextColor : TColor;
f_Hyperlink : Boolean;
f_DrawWithEllipsis: Boolean;
f_ShowMark : Boolean;
private
// internal methods
procedure SetAutoWidth(const Value: Boolean);
{-}
private
// property methods
procedure pm_SetHyperlink(const Value : Boolean);
{-}
procedure pm_SetHighlightColor(const aValue: TColor);
{-}
procedure pm_SetTextColor(const aValue: TColor);
{-}
procedure pm_SetDrawWithEllipsis(aValue: Boolean);
{-}
procedure pm_SetShowMark(aValue: Boolean);
{-}
private
function CalculatedTextColor: TColor;
{-}
function CalculatedFontStyle(aStyle: TFontStyles): TFontStyles;
{-}
function CalcMarkSpace : Integer;
{VK. - величина отступа для значка слева от текста }
private
// messages
procedure CMTextChanged(var Message: TMessage);
message CM_TEXTCHANGED;
{-}
procedure CMParentFontChanged(var Message: TMessage);
message CM_PARENTFONTCHANGED;
{-}
procedure WMGetDlgCode(var Message: TWMGetDlgCode);
message WM_GETDLGCODE;
{-}
procedure WMEraseBkgnd(var Message : TWMEraseBkgnd);
message WM_ERASEBKGND;
{-}
procedure WMPaint(var Message : TWMPaint);
message WM_PAINT;
{-}
procedure WMNCPaint(var Message : TWMNCPaint);
message WM_NCPAINT;
{-}
procedure CNKeyDown(var Message : TWMKeyDown);
message CN_KEYDOWN;
{-}
protected
// Методы интерфейса Il3CommandTarget
protected
// protected methods
function CalcWidth: Integer;
{-}
function CalcClientRect : TRect;
{VK. - подсчитывает размеры прямоугольника всей области контрола }
function CalcTextRect : TRect;
{* - подсчитывает размеры прямоугольника текстовой области для Caption. }
procedure ChangeScale(M, D: Integer);
override;
{-}
procedure DoAutoSize;
//virtual;
{-}
procedure Paint(const CN: Il3Canvas);
override;
{-}
procedure WndProc(var Message: TMessage);
override;
{-}
function IsHandledShortcut(var Msg: TMessage): Boolean;
{-}
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
override;
{-}
function NeedUnderLine: Boolean;
virtual;
{-}
procedure KeyDown(var Key: Word; Shift: TShiftState);
override;
{-}
function AllowClickByKeyBoard: Boolean;
virtual;
{-}
function AllowTranslateReturn: Boolean;
virtual;
{-}
public
// public methods
constructor Create(AOwner: TComponent);
override;
{-}
function FullWidth: Integer;
{-}
public
// public properties
property DrawWithEllipsis: Boolean
read f_DrawWithEllipsis
write pm_SetDrawWithEllipsis;
{-}
published
// published property
property Caption;
{-}
property TabOrder;
{-}
property Alignment: TAlignment read f_Alignment write f_Alignment default taLeftJustify;
{-}
property AutoWidth: Boolean read f_AutoWidth write SetAutoWidth default True;
{-}
property Enabled;
{-}
property Font;
{-}
property Color;
{-}
property Group: Boolean read f_Group write f_Group default False;
{-}
property HighlightColor: TColor read f_HighlightColor write pm_SetHighlightColor default clHighlight;
{-}
property Hyperlink: Boolean read f_Hyperlink write pm_SetHyperlink;
{* - цвет шрифта , когда метка находится не в фокусе. }
property OnClick;
{* - цвет шрифта, когда метка находится в фокусе. }
property ShowMark: Boolean read f_ShowMark write pm_SetShowMark default false;
{VK. - включает/выключает квадратик слева от текста. }
property TextColor: TColor read f_TextColor write pm_SetTextColor default clBtnText;
end;//TvtFocusLabel
implementation
uses
Forms,
OvcConst,
OvcBase,
OvcCmd,
l3Units,
l3String,
l3Base,
l3Math,
afwFacade
;
{ TvtFocusLabel }
function TvtFocusLabel.CalcMarkSpace : Integer;
begin
if f_ShowMark then
Result := Abs(Font.Height)
else
Result := 0;
end;
function TvtFocusLabel.CalcClientRect : TRect;
{-}
begin
Result := CalcTextRect;
if f_ShowMark then
Result.Left := 0;
end;
function TvtFocusLabel.CalcTextRect : TRect;
begin
l3FillChar(Result, SizeOf(Result), 0);
with Canvas do
begin
BeginPaint;
try
Font.AssignFont(Self.Font);
DrawEnabled := True;
try
DrawText(l3PCharLen(CCaption), Result, DT_SINGLELINE or DT_CALCRECT);
Inc(Result.Right, 3);
// - запас на рамку
OffsetRect(Result, CalcMarkSpace, 0);
finally
DrawEnabled := False;
end;//try..finally
finally
EndPaint;
end;//try..finally
end;//with Canvas
end;
function TvtFocusLabel.CalcWidth: Integer;
begin
Canvas.Font.AssignFont(Font);
with CalcClientRect do
Result := Right - Left;
end;
constructor TvtFocusLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
(* inherited *)
TabStop := True;
Height := 17;
Width := 65;
Visible := True;
(* self *)
f_Alignment := taLeftJustify;
f_Group := False;
f_AutoWidth := True;
f_HighlightColor := clHighlight;
f_TextColor := clBtnText;
f_ShowMark := False;
end;
procedure TvtFocusLabel.ChangeScale(M, D: Integer);
var
l_ScalingFlags: TScalingFlags;
begin
// Иначе шрифт масштабируется дважды
// http://mdp.garant.ru/pages/viewpage.action?pageId=449678181
if (sfFont in ScalingFlags) then
begin
l_ScalingFlags := ScalingFlags;
Exclude(l_ScalingFlags, sfFont);
ScalingFlags := l_ScalingFlags;
end;
inherited;
DoAutoSize;
end;
procedure TvtFocusLabel.DoAutoSize;
var
lR : TRect;
begin
if not l3IsNil(CCaption) then
begin
lR := CalcTextRect;
SetBounds(Left, Top, lR.Right + 2, lR.Bottom + 2);
end;//not l3IsNil(CCaption)
end;
procedure TvtFocusLabel.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if TabStop AND not Focused then
begin
SetFocus;
Invalidate;
end;//TabStop..
end;
procedure TvtFocusLabel.Paint(const CN : Il3Canvas);
// override;
{-}
var
l_Rect : Tl3SRect;
procedure lpDrawText;
const
arrAlignment: array [TAlignment] of DWORD = (DT_LEFT, DT_RIGHT, DT_CENTER);
arrEllipsis: array [Boolean] of DWORD = (0, DT_END_ELLIPSIS);
begin//lpDrawText
with CN do
begin
with Font do
begin
Style := CalculatedFontStyle(Style);
BackColor := Self.Color;
end;
DrawText(l3PCharLen(CCaption), l_Rect.R.WR, arrAlignment[f_Alignment] or arrEllipsis[DrawWithEllipsis]);
end;
end;//lpDrawText
procedure lpDrawMark;
const
cMarkBorderColor = $00E09070;
cMarkAreaColor = $00FFB080;
cMarkBorderInLeftTopColor = $00FFB890;
cMarkBorderInRightBottomColor = $00F0A070;
var
l_MarkRect : Tl3SRect;
l_MarkSpace : Integer;
begin//lpDrawMark
with CN do
begin
l_MarkSpace := CalcMarkSpace;
l_MarkRect.R.WR := Rect(l3MulDiv(l_MarkSpace,2,5),
l3MulDiv(l_MarkSpace,2,5),
l3MulDiv(l_MarkSpace,4,5),
l3MulDiv(l_MarkSpace,4,5));
Canvas.Brush.Color := cMarkBorderColor;
FillRect(l_MarkRect);
InflateRect(l_MarkRect.R.WR, -1, -1);
Canvas.Brush.Color := cMarkBorderInLeftTopColor;
FillRect(l_MarkRect);
Inc(l_MarkRect.R.WR.Left);
Inc(l_MarkRect.R.WR.Top);
Canvas.Brush.Color := cMarkBorderInRightBottomColor;
FillRect(l_MarkRect);
Dec(l_MarkRect.R.WR.Right);
Dec(l_MarkRect.R.WR.Bottom);
Canvas.Brush.Color := cMarkAreaColor;
FillRect(l_MarkRect);
end;//with CN
end;//lpDrawMark
begin
inherited;
with CN do
begin
l_Rect.R.WR := ClientRect;
Font.AssignFont(Self.Font);
(* FillRect *)
BackColor := Self.Color;
FillRect(l_Rect);
(* Focus *)
if Focused then
begin
BackColor := Self.Color;
Font.ForeColor := clBlack;
Canvas.Brush.Color := ColorToRGB(clBlack{CalculatedTextColor}) xor ColorToRGB(Self.Color);
//Canvas.Brush.Color := clBlack{CalculatedTextColor} xor ColorToRGB(BackColor);
DrawFocusRect(Tl3SRect(l_Rect));
Font.AssignFont(Self.Font);
BackColor := Self.Color;
end;//if Focused then
Inc(l_Rect.R.Left);
(* DrawMark *)
if f_ShowMark then
begin
lpDrawMark;
Canvas.Brush.Color := ColorToRGB(clBlack{CalculatedTextColor}) xor ColorToRGB(Self.Color);
Inc(l_Rect.R.Left, CalcMarkSpace);
end;//f_ShowMark
(* DrawText *)
if not l3IsNil(CCaption) then
begin
InflateRect(l_Rect.R.WR, -1, -1);
Canvas.Brush.Style := bsClear;
if not Enabled then
begin
OffsetRect(l_Rect.R.WR, 1, 1);
Font.ForeColor := clBtnHighlight;
lpDrawText;
OffsetRect(l_Rect.R.WR, -1, -1);
Font.ForeColor := clBtnShadow;
lpDrawText;
end//if not Enabled then
else
begin
Font.ForeColor := CalculatedTextColor;
lpDrawText;
end;//not Enabled
end;//if not l3IsNil(CCaption) then
end;//with CN do
end;
procedure TvtFocusLabel.SetAutoWidth(const Value: Boolean);
begin
f_AutoWidth := Value;
if Value then
DoAutoSize;
end;
procedure TvtFocusLabel.CMTextChanged(var Message: TMessage);
//message CM_TEXTCHANGED;
{-}
begin
if not l3IsNil(CCaption) then
if f_AutoWidth then
DoAutoSize;
inherited;
end;
type
THackedControl = class(TControl);
procedure TvtFocusLabel.CMParentFontChanged(var Message: TMessage);
var
F: TFont;
begin
(* При загрузке не нужно реагировать на изменение родительского шрифта,
потому, что на больших шрифтах происходит двойное увеличение
(CMParentFontChanged и Scaled) в следствии чего шрифт меток больше чем у
остальных компонентов *)
if csLoading in ComponentState then
begin
inherited;
Exit;
end;//csLoading in ComponentState
if Message.wParam <> 0 then
F := TFont(Message.lParam)
else
F := THackedControl(Parent).Font;
if Assigned(F) then
begin
Font.Name := F.Name;
Font.Size := F.Size;
DoAutoSize;
end;//Assigned(F)
end;
procedure TvtFocusLabel.WMEraseBkgnd(var Message : TWMEraseBkgnd);
//message WM_ERASEBKGND;
begin
Message.Result := LRESULT(False);
end;
procedure TvtFocusLabel.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
inherited;
if csDesigning in ComponentState then
Message.Result := DLGC_STATIC
else
Message.Result := Message.Result or DLGC_WANTCHARS or DLGC_WANTARROWS or DLGC_WANTALLKEYS;
end;
procedure TvtFocusLabel.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_SETFOCUS, WM_KILLFOCUS:
Repaint;
WM_KEYDOWN, WM_SYSKEYDOWN:
IsHandledShortcut(Message);
CM_ENABLEDCHANGED:
Repaint;
end;//case Message.Msg
inherited WndProc(Message);
end;
function TvtFocusLabel.IsHandledShortcut(var Msg: TMessage): Boolean;
var
l_Controller : TOvcController;
begin
Result := false;
l_Controller := Controller;
if Assigned(l_Controller) then
with l_Controller.EntryCommands do
if TranslateUsing([], Msg, GetTickCount) = ccShortCut then
begin
Msg.Result := 0; {indicate that this message was processed}
Result := true;
end;//TranslateUsing([], Msg, GetTickCount) = ccShortCut
end;
procedure TvtFocusLabel.WMNCPaint(var Message: TWMNCPaint);
begin
if not afw.IsObjectLocked(Self) then
inherited
else
Message.Result := 0;
end;
procedure TvtFocusLabel.WMPaint(var Message: TWMPaint);
Var
DC: HDC;
PS: tagPaintStruct;
begin
if not afw.IsObjectLocked(Self) then
inherited
else
begin
DC := BeginPaint(Handle, PS);
EndPaint(Handle, PS);
end;//not afw.IsObjectLocked(Self)
end;
procedure TvtFocusLabel.pm_SetHyperlink(const Value: Boolean);
begin
f_Hyperlink := Value;
case Value of
True:
if (Cursor <> crHandPoint) then
Cursor := crHandPoint;
False:
Cursor := crDefault;
end;//case Value
Invalidate;
end;
procedure TvtFocusLabel.CNKeyDown(var Message : TWMKeyDown);
var
l_Controller : TOvcController;
l_Translation : Word;
procedure TranslateKey;
var
F : TCustomForm;
begin//TranslateKey
F := GetParentForm(Self);
if (F <> nil) then with TMessage(Message) do
Result := F.Perform(CM_DialogKey, wParam, lParam);
end;//TranslateKey
procedure TranslateReturn;
begin//TranslateReturn
Message.Result := -1;
if not DoKeyDown(Message) then Broadcast(Message);
if (Message.Result <> 0) then
TranslateKey;
end;//TranslateReturn
begin
l_Controller := Controller;
if l_Controller <> nil then
with l_Controller.EntryCommands do
begin
l_Translation := TranslateUsing(OvcCmd.ovcTextEditorCommands,
TMessage(Message), GetTickCount, Il3CommandTarget(Self));
case l_Translation of
ccShortCut:
begin
Message.CharCode := 0;
Message.Result := 1;
exit;
end;//ccShortCut
end;//case l_Translation
end;//with l_Controller.EntryCommands
case Message.CharCode of
vk_Escape, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN:
TranslateKey;
vk_Return:
begin
inherited;
if (Message.Result = 0) and AllowTranslateReturn then
TranslateReturn;
end;//vk_Return
else
inherited;
end;//case Message.CharCode
end;
function TvtFocusLabel.CalculatedTextColor: TColor;
begin
if HyperLink then
Result := HighlightColor
else
Result := TextColor;
end;
function TvtFocusLabel.CalculatedFontStyle(aStyle: TFontStyles): TFontStyles;
begin
Result := aStyle;
if NeedUnderLine then
Include(Result, fsUnderline);
end;
procedure TvtFocusLabel.pm_SetHighlightColor(const aValue: TColor);
begin
if f_HighlightColor <> aValue then
begin
f_HighlightColor := aValue;
Invalidate;
end;//f_HighlightColor <> aValue
end;
procedure TvtFocusLabel.pm_SetShowMark(aValue: Boolean);
begin
if (f_ShowMark <> aValue) then
begin
f_ShowMark := aValue;
Invalidate;
end;//f_ShowMark <> aValue
end;
procedure TvtFocusLabel.pm_SetTextColor(const aValue: TColor);
begin
if f_TextColor <> aValue then
begin
f_TextColor := aValue;
Invalidate;
end;//f_TextColor <> aValue
end;
function TvtFocusLabel.NeedUnderLine: Boolean;
begin
Result := HyperLink;
end;
procedure TvtFocusLabel.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if Enabled and AllowClickByKeyBoard and Assigned(OnClick) and (Key in [vk_Return, vk_Space]) and (Shift = []) then
begin
Key := 0;
Click;
end;//Enabled..
end;
function TvtFocusLabel.AllowClickByKeyBoard: Boolean;
begin
Result := HyperLink;
end;
function TvtFocusLabel.AllowTranslateReturn: Boolean;
begin
Result := True;
end;
function TvtFocusLabel.FullWidth: Integer;
begin
Result := CalcWidth;
end;
procedure TvtFocusLabel.pm_SetDrawWithEllipsis(aValue: Boolean);
begin
if aValue <> DrawWithEllipsis then
begin
f_DrawWithEllipsis := aValue;
Invalidate;
end;//aValue <> DrawWithEllipsis
end;
end.
|
unit CaptionList;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
CAPLIST_REFRESH = WM_USER + 100;
type
TCaptionList = class(Tcomponent)
private
FItems: TStringList;
tl,
FKeys,
FList : TStringList;
FListIndex: integer;
ItemList: TList;
procedure SetItems(const Value: TStringList);
procedure SetListIndex(const Value: integer);
procedure RefreshLabels;
procedure SplitTheList;
function GetCaption(AKey: string): string;
{ Private declarations }
protected
{ Protected declarations }
procedure Loaded; override;
public
{ Public declarations }
constructor create(AOwner:TComponent); override;
destructor destroy; override;
function CaptionFormat(AKey,AFormat:string):string;
procedure RemoveItem(AControl:TControl);
procedure AddItem(AControl:TControl);
published
{ Published declarations }
property Items:TStringList read FItems write SetItems;
property ListIndex:integer read FListIndex write SetListIndex;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Common', [TCaptionList]);
end;
{ TCaptionList }
procedure TCaptionList.AddItem(AControl: TControl);
begin
ItemList.Add(AControl);
end;
function TCaptionList.CaptionFormat(AKey, AFormat: string): string;
var s : string;
begin
s := GetCaption(AKey);
result := s;
if AFormat > '' then result := format(AFormat, [s]);
end;
constructor TCaptionList.create(AOwner: TComponent);
begin
FItems := TStringList.create;
FKeys := TStringList.create;
FList := TStringList.Create;
tl := TStringList.Create;
ItemList := TList.Create;
inherited;
end;
destructor TCaptionList.destroy;
begin
ItemList.Free;
tl.free;
FKeys.Free;
FList.Free;
FItems.free;
inherited;
end;
function TCaptionList.GetCaption(AKey: string): string;
var y : integer;
begin
result := '';
AKey := Uppercase(AKey);
y := FKeys.IndexOf(AKey);
if y >= 0 then
begin
tl.commatext := FList[y];
if (ListIndex >= 0) and (ListIndex < tl.Count) then result := tl[ListIndex];
end;
end;
procedure TCaptionList.Loaded;
begin
inherited;
SplitTheList;
end;
procedure TCaptionList.RefreshLabels;
var x : integer;
begin
for x := 0 to ItemList.Count - 1 do TControl(ItemList[x]).Perform(CAPLIST_REFRESH, 0, 0);
end;
procedure TCaptionList.RemoveItem(AControl: TControl);
begin
ItemList.Remove(AControl);
end;
procedure TCaptionList.SetItems(const Value: TStringList);
begin
FItems.assign(Value);
SplitTheList;
end;
procedure TCaptionList.SetListIndex(const Value: integer);
begin
FListIndex := Value;
RefreshLabels;
end;
procedure TCaptionList.SplitTheList;
var x : integer;
begin
FKeys.clear;
FList.clear;
for x := 0 to FItems.count - 1 do
begin
tl.CommaText := FItems[x];
FKeys.add(Uppercase(tl[0]));
tl.Delete(0);
FList.add(tl.commatext);
end;
if not (csLoading in ComponentState) then RefreshLabels;
end;
end.
|
program FolgenInverter (input, output);
{ liest eine Folge von 5 integer-Zahlen ein und gibt sie in umgekehrter Reihenfolge wieder aus }
type
tIndex = 1..5;
tZahlenFeld = array [tIndex] of integer;
var
Feld : tZahlenFeld;
i : tIndex;
begin
for i := 1 to 5 do
begin
write ('Bitte ', i, '. Zahl eingeben: ');
readln (Feld[i])
end;
for i := 5 downto 1 do
writeln (Feld[i])
end. { FolgenInverter }
|
unit StatusThread;
interface
uses
Classes, SysUtils, Messages, Controls, Windows{$ifdef Lazarus}, LMessages, WSControls, InterfaceBase, LCLType{$endif};
type
TNotifyDataFunction = function(Sender: TObject; Data: pointer): Integer of object;
TExceptionEvent = procedure(Sender: TThread; E: Exception; msg: String) of object;
TThreadStatusEvent = procedure(Sender: TThread; ABezeichner, AStatus: String) of object;
TSThread = class(TThread)
protected
FStatus: String;
FOnThreadStatus: TThreadStatusEvent;
Sync_NotifyEvent: TNotifyEvent;
Sync_NotifyEvent_Object: TObject;
Sync_NotifyDFunk: TNotifyDataFunction;
Sync_NotifyDFunk_Result: Integer;
Sync_NotifyDFunk_data: pointer;
procedure SetStatus(S: String);
procedure SetOnThreadStatus(Event: TThreadStatusEvent);
procedure DoSync_NotifyEvent;
procedure DoSync_NotifyDFunk;
public
OnException: TExceptionEvent;
OnOnThreadStatusChange: TNotifyEvent;
Name: String;
property OnThreadStatus: TThreadStatusEvent read FOnThreadStatus write SetOnThreadStatus;
property Status: String read FStatus write SetStatus;
destructor Destroy; override;
constructor Create(CreateSuspended: Boolean);
{$ifndef Lazarus}
procedure SynchronizeNotifyEvent(Proc: TNotifyEvent; Sender: TObject);
function SynchroniseNotifyDataFunction(Proc: TNotifyDataFunction;
Sender: TObject; Data: pointer): Integer;
{$endif}
procedure Execute; override;
end;
TToMainThreadOnSyncData = procedure(Sender: TObject; Index: Byte;
Data: Pointer; Size: Integer) of object;
TToMainThread = class(TComponent)
private
FHandle: THandle;
FOnSyncData: TToMainThreadOnSyncData;
{$ifdef Lazarus}
procedure WndProc(var Msg: TLMessage);
{$else}
procedure WndProc(var Msg: TMessage);
{$endif}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SyncData(const Index: Byte; Data: pointer; Size: Integer);
published
property OnSyncData: TToMainThreadOnSyncData read FOnSyncData
write FOnSyncData;
end;
var
ThreadStatusActive: Boolean;
procedure Register;
threadvar
gThreadID: Cardinal;
implementation
procedure Register;
begin
RegisterComponents('nice things', [TToMainThread]);
end;
procedure TSThread.DoSync_NotifyEvent;
begin
Sync_NotifyEvent(Sync_NotifyEvent_Object);
end;
procedure TSThread.DoSync_NotifyDFunk;
begin
Sync_NotifyDFunk_Result := Sync_NotifyDFunk(Sync_NotifyEvent_Object,
Sync_NotifyDFunk_data);
end;
{$ifndef Lazarus}
procedure TSThread.SynchronizeNotifyEvent(Proc: TNotifyEvent; Sender: TObject);
begin
Sync_NotifyEvent := Proc;
Sync_NotifyEvent_Object := Sender;
Synchronize(DoSync_NotifyEvent);
end;
function TSThread.SynchroniseNotifyDataFunction(Proc: TNotifyDataFunction;
Sender: TObject; Data: pointer): Integer;
begin
Sync_NotifyEvent_Object := Sender;
Sync_NotifyDFunk := Proc;
Sync_NotifyDFunk_data := Data;
Synchronize(DoSync_NotifyDFunk);
Result := Sync_NotifyDFunk_Result;
end;
{$endif}
constructor TSThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
Name := ClassName;
end;
destructor TSThread.Destroy;
begin
inherited Destroy;
end;
procedure TSThread.SetOnThreadStatus(Event: TThreadStatusEvent);
begin
FOnThreadStatus := Event;
if Assigned(OnOnThreadStatusChange) then
OnOnThreadStatusChange(self);
Status := 'SetOnThreadStatus';
end;
procedure TSThread.SetStatus(S: String);
begin
FStatus := S;
OutputDebugString(PChar('"RunThreadID: ' + IntToStr(GetCurrentThreadId) +
' ThreadObj(ID): ' + Name + '(' + IntToStr(ThreadID) +
') notify: ' + FStatus + '"'));
if ThreadStatusActive and Assigned(OnThreadStatus) then
OnThreadStatus(Self,Name,FStatus);
end;
procedure TSThread.Execute;
begin
gThreadID := ThreadID;
{$ifndef Lazarus}
Inherited;
{$endif}
end;
constructor TToMainThread.Create(AOwner: TComponent);
var cp: TCreateParams;
begin
inherited;
{$ifdef Lazarus}
FHandle := TWSWinControl(WidgetSet).CreateHandle(Self, cp);
{$else}
FHandle := AllocateHWnd(WndProc);
{$endif}
end;
destructor TToMainThread.Destroy;
begin
{$ifdef Lazarus}
TWSWinControl(WidgetSet).DestroyHandle(Self);
{$else}
DeallocateHWnd(FHandle);
{$endif}
inherited;
end;
{$ifdef Lazarus}
procedure TToMainThread.WndProc(var Msg: TLMessage);
{$else}
procedure TToMainThread.WndProc(var Msg: TMessage);
{$endif}
begin
if (Msg.Msg >= WM_APP) and
(Msg.Msg <= WM_APP + high(byte)) then
begin
if Assigned(FOnSyncData) then
FOnSyncData(Self,Msg.Msg - WM_APP,pointer(Msg.WParam),
Msg.LParam);
end;
end;
procedure TToMainThread.SyncData(const Index: Byte; Data: pointer;
Size: Integer);
begin
{$ifdef Lazarus}
WidgetSet.PostMessage(FHandle,WM_APP + Index,Integer(Data),Size);
{$else}
PostMessage(FHandle,WM_APP + Index,Integer(Data),Size);
{$endif}
end;
end.
|
unit xplatformutils;
{$I jedi-sdl.inc}
interface
uses
{$IFDEF WIN32}
Windows;
{$ELSE}
{$IFDEF UNIX}
{$IFDEF FPC}
libc;
{$ELSE}
Libc,
Xlib;
{$ENDIF}
{$ENDIF}
{$ENDIF}
const
{$IFDEF MACOS}
DIR_SEP = ':';
DIR_CUR = ':';
{$ELSE}
{$IFDEF DARWIN}
DIR_SEP = ':';
DIR_CUR = ':';
{$ELSE}
{$IFDEF WIN32}
DIR_SEP = '\';
DIR_CUR = '';
{$ELSE}
DIR_SEP = '/';
DIR_CUR = '';
{$ENDIF}
{$ENDIF}
{$ENDIF}
procedure ExecAndWait( aProcess : string; aArguments : array of string );
implementation
procedure ExecAndWait( aProcess : string; aArguments : array of string );
var
{$IFDEF WIN32}
CommandLine : string;
ProcessInfo: TProcessInformation;
Startupinfo: TStartupInfo;
ExitCode: longword;
x : integer;
{$ELSE}
{$IFDEF UNIX}
pid: PID_T;
Max: Integer;
i: Integer;
parg: PPCharArray;
argnum: Integer;
returnvalue : Integer;
{$ENDIF}
{$ENDIF}
begin
{$IFDEF WIN32}
// Initialize the structures
FillChar(ProcessInfo, sizeof(TProcessInformation), 0);
FillChar(Startupinfo, sizeof(TStartupInfo), 0);
Startupinfo.cb := sizeof(TStartupInfo);
// Attempts to create the process
Startupinfo.dwFlags := STARTF_USESHOWWINDOW;
Startupinfo.wShowWindow := 1;
CommandLine := aProcess;
for x := Low(aArguments ) to High(aArguments ) do
CommandLine := CommandLine + ' ' + aArguments[ x ];
if CreateProcess( nil, PChar( CommandLine ), nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, Startupinfo, ProcessInfo ) then
begin
// The process has been successfully created
// No let's wait till it ends...
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
// Process has finished. Now we should close it.
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode); // Optional
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
end;
{$ELSE}
{$IFDEF UNIX}
pid := fork;
if pid = 0 then
begin
Max := sysconf(_SC_OPEN_MAX);
for i := (STDERR_FILENO+1) to Max do
begin
fcntl(i, F_SETFD, FD_CLOEXEC);
end;
argnum := High(aArguments) + 1;
GetMem(parg,(2 + argnum) * sizeof(PChar));
parg[0] := PChar(aProcess);
i := 0;
while i <= high(aArguments) do
begin
inc(i);
parg[i] := PChar(aArguments[i-1]);
end;
parg[i+1] := nil;
execvp(PChar(aProcess),PPChar(@parg[0]));
halt;
end;
if pid > 0 then
begin
waitpid(pid,@returnvalue,0);
end;
{$ENDIF}
{$ENDIF}
end;
end.
|
program DeskPet;
uses SwinGame, sgTypes, sgBackendTypes, sgTimers, sgSprites, SysUtils, Math;
type
PetState = (Idle, Sleep, Sick, Eating, Upset, Dancing);
FoodKind = (AppleGood, AppleBad);
Pet = record
health: Integer;
nextFlipTicks: Integer;
x, y: Double;
dx, dy: Double;
flip: Boolean;
animationName: String;
state: PetState;
sprite: Sprite;
moveTimer: Timer;
moveFlipTimer: Timer;
healthTimer: Timer;
danceTimer: Timer;
danceFlipTimer: Timer;
end;
Food = record
kind: FoodKind;
sprite: Sprite;
end;
Buttons = record
sleep: Sprite;
heal: Sprite;
feed: Sprite;
end;
Game = record
pet: Pet;
foods: array of Food;
buttons: Buttons;
lowHealthTimer: Timer;
isPlayingFoodGame: Boolean;
isDay: Boolean;
dayBackground: Bitmap;
nightBackground: Bitmap;
border: Bitmap;
heartFull: Bitmap;
heartHalf: Bitmap;
heartEmpty: Bitmap;
idleMusic: Music;
sickMusic: Music;
danceMusic: Music;
sleepMusic: Music;
foodMusic: Music;
currentMusic: ^Music;
end;
// ============================
// Utility Procedures/Functions
// ============================
function SpriteClicked(const sprite: Sprite): Boolean;
var
mouseXPos, mouseYPos: Single;
rect: Rectangle;
begin
mouseXPos := MouseX();
mouseYPos := MouseY();
rect := SpriteCollisionRectangle(sprite);
result := false;
if MouseClicked(LeftButton) then
begin
if (mouseXPos >= rect.x) and (mouseXPos <= rect.x + rect.width)
and (mouseYPos >= rect.y) and (mouseYPos <= rect.y + rect.height) then
begin
result := true;
end;
end;
end;
procedure WrapSprite(sprite: Sprite; var x, y: Double);
begin
if x < -SpriteWidth(sprite) then //offscreen left
x := ScreenWidth()
else if x > ScreenWidth() then //offscreen right
x := -SpriteWidth(sprite);
if y < -SpriteHeight(sprite) then //offscreen top
y := ScreenHeight()
else if y > ScreenHeight() then //offscreen bottom
y := -SpriteHeight(sprite);
end;
procedure CenterPet(var pet: Pet);
begin
pet.x := 250;
pet.y := 160;
end;
// Changed from sgGraphics
procedure DrawSpriteWithOpts(s: Sprite; xOffset, yOffset: Longint; const o: DrawingOptions);
var
i, idx: Longint;
angle, scale: Single;
sp: SpritePtr;
opts: DrawingOptions;
begin
opts := o;
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
angle := SpriteRotation(s);
if angle <> 0 then
opts := OptionRotateBmp(angle, sp^.anchorPoint.x - SpriteLayerWidth(s, 0) / 2, sp^.anchorPoint.y - SpriteLayerHeight(s, 0) / 2, opts);
scale := SpriteScale(s);
if scale <> 1 then
opts := OptionScaleBmp(scale, scale, opts);
for i := 0 to High(sp^.visibleLayers) do
begin
idx := sp^.visibleLayers[i];
DrawCell(SpriteLayer(s, idx), SpriteCurrentCell(s),
Round(sp^.position.x + xOffset + sp^.layerOffsets[idx].x),
Round(sp^.position.y + yOffset + sp^.layerOffsets[idx].y),
opts);
end;
end;
procedure DrawSpriteWithOpts(s: Sprite; const opts: DrawingOptions);
begin
DrawSpriteWithOpts(s, 0, 0, opts);
end;
// ==========================
// Setup Procedures/Functions
// ==========================
procedure LoadResources();
begin
LoadResourceBundleNamed('PetBundle', 'PetBundle.txt', false);
LoadBitmapNamed('day', 'Day.png');
LoadBitmapNamed('night', 'Night.png');
LoadBitmapNamed('border', 'Border.png');
LoadBitmapNamed('AppleBad','AppleBad.png');
LoadBitmapNamed('AppleGood', 'AppleGood.png');
LoadBitmapNamed('SleepIcon','Icon_Sleep.png');
LoadBitmapNamed('MediIcon', 'Icon_Medi.png');
LoadBitmapNamed('FeedIcon', 'Icon_Feed.png');
LoadBitmapNamed('HeartFull','HeartFull.png');
LoadBitmapNamed('HeartHalf', 'HeartHalf.png');
LoadBitmapNamed('HeartEmpty', 'HeartEmpty.png');
LoadSoundEffectNamed('AppleGoodSound', '238283__meroleroman7__8-bit-noise.wav');
LoadSoundEffectNamed('AppleBadSound', '239987__jalastram__fx114.wav');
LoadSoundEffectNamed('GameOver', '333785__projectsu012__8-bit-failure-sound.wav');
end;
procedure SetupButtons(var buttons: Buttons);
begin
buttons.sleep := CreateSprite(BitmapNamed('SleepIcon'));
SpriteSetX(buttons.sleep, 300);
SpriteSetY(buttons.sleep, 20);
buttons.heal := CreateSprite(BitmapNamed('MediIcon'));
SpriteSetX(buttons.heal, 350);
SpriteSetY(buttons.heal, 20);
buttons.feed := CreateSprite(BitmapNamed('FeedIcon'));
SpriteSetX(buttons.feed, 400);
SpriteSetY(buttons.feed, 20);
end;
procedure SetupPet(var pet: Pet);
begin
pet.animationName := '';
pet.state := Idle;
pet.flip := false;
pet.sprite := CreateSprite(
BitmapNamed('Pet'),
AnimationScriptNamed('PetAnimations'));
CenterPet(pet);
pet.dx := 0;
pet.dy := 0;
pet.moveFlipTimer := CreateTimer();
pet.moveTimer := CreateTimer();
StartTimer(pet.moveFlipTimer);
StartTimer(pet.moveTimer);
pet.nextFlipTicks := 12000;
pet.health := 10;
pet.healthTimer := CreateTimer();
StartTimer(pet.healthTimer);
end;
function SpawnFood(): Food;
begin
// We're randomly spawning a good or bad apple.
result.kind := FoodKind(Rnd(2));
if result.kind = AppleGood then
result.sprite := CreateSprite(BitmapNamed('AppleGood'))
else if result.kind = AppleBad then
result.sprite := CreateSprite(BitmapNamed('AppleBad'));
// Sets the X cord of an apple, makes sure we spawn the apples within the screens border.
SpriteSetX(result.sprite, 40 + Rnd(ScreenWidth() - 80 - SpriteWidth(result.sprite)));
// Sets the Y cord of an apple, we always spawn at the top of the screen.
SpriteSetY(result.sprite, 0);
// We're randomizing the speed of the apples for variety and to avoid too much overlap.
SpriteSetDY(result.sprite, 1 + Rnd(4));
end;
procedure SetupFoods(var game: Game);
var
i: Integer;
begin
// Sets how many apples we're spawning.
SetLength(game.foods, 5);
for i := Low(game.foods) to High(game.foods) do
begin
game.foods[i] := SpawnFood();
end;
end;
procedure SetupGame(var game: Game);
begin
SetupButtons(game.buttons);
SetupPet(game.pet);
SetupFoods(game);
// Food game variables.
game.isPlayingFoodGame := false;
// Day/Night cycle variables.
game.isDay := true;
game.dayBackground := BitmapNamed('day');
game.nightBackground := BitmapNamed('night');
// Border.
game.border := BitmapNamed('border');
// Heart states.
game.heartFull := BitmapNamed('HeartFull');
game.heartHalf := BitmapNamed('HeartHalf');
game.heartEmpty := BitmapNamed('HeartEmpty');
// Timer for screen effect when Deskpet is in Sick state.
game.lowHealthTimer := CreateTimer();
StartTimer(game.lowHealthTimer);
//Music from: https://freesound.org/people/cabled_mess/sounds/335361/
game.idleMusic := LoadMusic('335361__cabled-mess__little-happy-tune-22-10.wav');
//Music from: https://freesound.org/people/Clinthammer/sounds/179510/
game.sickMusic := LoadMusic('179510__clinthammer__clinthammermusic-gamerstep-chords-2.wav');
//Music from: https://freesound.org/people/ynef/sounds/352756/
game.danceMusic := LoadMusic('352756__ynef__trance-beat-with-deep-bassline.wav');
//Music from: https://freesound.org/people/FoolBoyMedia/sounds/264295/
game.sleepMusic := LoadMusic('264295__foolboymedia__sky-loop.wav');
//Music from: https://freesound.org/people/Burinskas/sounds/362133/
game.foodMusic := LoadMusic('362133__burinskas__chiptune-loop-light.wav');
end;
// ===========================
// Update Procedures/Functions
// ===========================
function CanSleep(const game: Game): Boolean;
begin
// Deskpet can Sleep if, isn't Sick, isn't Dancing and we're not playing food game.
result := (not game.isPlayingFoodGame) and (game.pet.state <> Sick) and (game.pet.state <> Dancing);
end;
function CanHeal(const game: Game): Boolean;
begin
// Can Heal if Deskpet is Sick, isn't Dancing and we're not playing food game.
result := (not game.isPlayingFoodGame) and (game.pet.state = Sick) and (game.pet.state <> Dancing);
end;
function CanFoodGame(const game: Game): Boolean;
begin
// Can play food game if, Deskpet isn't Sick, isn't Sleeping and isn't Dancing.
result := (game.pet.state <> Sick) and (game.pet.state <> Sleep) and (game.pet.state <> Dancing);
end;
procedure HandleButtons(var game: Game);
begin
UpdateSprite(game.buttons.sleep);
UpdateSprite(game.buttons.heal);
UpdateSprite(game.buttons.feed);
// Handle Sleep
if CanSleep(game) and SpriteClicked(game.buttons.sleep) then
begin
// Toggles sleep depending on Deskpet state.
if game.pet.state = Sleep then
game.pet.state := Idle
else
game.pet.state := Sleep;
end;
// Handle Heal
if CanHeal(game) and SpriteClicked(game.buttons.heal) then
begin
// Sets Deskpet to Idle with 4 hp,
// Resets the timer so we don't immediately start dropping hp.
game.pet.state := Idle;
game.pet.health := 4;
ResetTimer(game.pet.healthTimer);
end;
// Handle Food
if CanFoodGame(game) and SpriteClicked(game.buttons.feed) then
begin
// Toggles food game.
game.isPlayingFoodGame := not game.isPlayingFoodGame;
end;
end;
procedure UpdateDay(var game: Game);
var
currTime: TDateTime;
hh,mm,ss,ms: Word;
begin
currTime := Now;
DecodeTime(currTime, hh, mm, ss, ms);
// The background will change depending on the computers time.
// From 7am to 5pm it will be set to Day 6pm to 6am is Night.
if (hh >= 7) and (hh <= 17) then
game.isDay := true
else
game.isDay := false;
end;
procedure HandleFoodsClicked(var game: Game);
var
i: Integer;
begin
for i := Low(game.foods) to High(game.foods) do
begin
if SpriteClicked(game.foods[i].sprite)
and (game.foods[i].kind = AppleGood) then
begin
// AppleGood = +1 hp
game.pet.health += 1;
PlaySoundEffect('AppleGoodSound');
// If an apple is clicked it spawns a new one
game.foods[i] := SpawnFood();
end
else if SpriteClicked(game.foods[i].sprite)
and (game.foods[i].kind = AppleBad) then
begin
// AppleBad = -1 hp
game.pet.health -= 1;
PlaySoundEffect('AppleBadSound');
game.foods[i] := SpawnFood();
end;
end;
end;
procedure UpdateFoods(var foods: array of Food);
var
i: Integer;
begin
for i := Low(foods) to High(foods) do
begin
UpdateSprite(foods[i].sprite);
// If an apple has moved off the screen spawn a new apple.
if(SpriteY(foods[i].sprite) > ScreenHeight()) then
foods[i] := SpawnFood();
end;
end;
procedure UpdateFoodGame(var game: Game);
begin
// If we're playing food game but Deskpets hp reaches 0,
// kick us back to the main screen and play the Gameover SFX.
if (game.pet.health = 0) and (game.isPlayingFoodGame) then
begin
game.isPlayingFoodGame := false;
PlaySoundEffect('GameOver');
Delay(1000);
end;
// If we're playing the food game,
// Deskpet should be in the Eating state.
if game.isPlayingFoodGame = true then
begin
game.pet.state := Eating;
HandleFoodsClicked(game);
UpdateFoods(game.foods);
end
else if game.pet.state = Eating then
begin
// Deskpet is in the Eating state but the game has ended,
// Go back to Idle state.
game.pet.state := Idle;
end;
end;
procedure UpdatePetHealth(var pet: Pet);
begin
// Deskpets health should go down by 1hp every 10 secs.
if TimerTicks(pet.healthTimer) > 10000 then
begin
ResetTimer(pet.healthTimer);
// Deskpet doesn't lose hp when eating, sleeping or dancing.
if (pet.state = Eating) or (pet.state = Sleep) or (pet.state = Dancing) then
Exit;
pet.health -= 1;
end;
// Deskpets hp should never go below 0.
pet.health := Max(pet.health, 0);
// Deskpets hp should never go above 10.
pet.health := Min(pet.health, 10);
end;
procedure UpdatePetState(var pet: Pet);
begin
// Eating state takes priority, that means we're
// playing the food game which should handle
// the state transition itself.
if pet.state = Eating then
Exit;
// If DeskPet is sleeping then we suspend other states.
if pet.state = Sleep then
Exit;
// If DeskPet is dancing then we suspend other states.
if pet.state = Dancing then
Exit;
// If DeskPets health is at 0 it's sick.
if pet.health = 0 then
pet.state := Sick
// If DeskPets health is <= 3 it's sad
else if pet.health <= 3 then
pet.state := Upset
else
pet.state := Idle;
end;
procedure UpdateMusic(var game: Game);
var
newMusic: ^Music;
begin
// The music will change depending on what state DeskPets in.
newMusic := nil;
if game.pet.state = Idle then
newMusic := @game.idleMusic;
if (game.pet.state = Sick) or (game.pet.state = Upset) then
newMusic := @game.sickMusic;
if game.pet.state = Dancing then
newMusic := @game.danceMusic;
if game.pet.state = Sleep then
newMusic := @game.sleepMusic;
if game.pet.state = Eating then
newMusic := @game.foodMusic;
if newMusic = nil then
StopMusic()
else if (not MusicPlaying()) or (MusicFilename(newMusic^) <> MusicFilename(game.currentMusic^)) then
begin
game.currentMusic := newMusic;
PlayMusic(game.currentMusic^);
end;
end;
procedure UpdatePetDance(var pet: Pet);
begin
// If Deskpets clicked, start dancing!
if (pet.state = Idle) and SpriteClicked(pet.sprite) then
begin
pet.state := Dancing;
pet.danceTimer := CreateTimer();
pet.danceFlipTimer := CreateTimer();
StartTimer(pet.danceTimer);
StartTimer(pet.danceFlipTimer);
end;
if (pet.state = Dancing) and (TimerTicks(pet.danceFlipTimer) > 200) then
begin
ResetTimer(pet.danceFlipTimer);
pet.flip := not pet.flip;
end;
// If our dance timer has finished, back to Idle.
if (pet.state = Dancing) and (TimerTicks(pet.danceTimer) > 2000) then
begin
StopTimer(pet.danceTimer);
StopTimer(pet.danceFlipTimer);
pet.flip := false;
pet.state := Idle;
end;
end;
procedure UpdatePetMove(var pet: Pet);
begin
// We want to move around if we're Idle.
// We use a timer to delay it which makes it
// look more like a retro game.
if pet.state = Idle then
begin
if TimerTicks(pet.moveTimer) > 200 then
begin
ResetTimer(pet.moveTimer);
if TimerTicks(pet.moveFlipTimer) > pet.nextFlipTicks then
begin
ResetTimer(pet.moveFlipTimer);
pet.flip := not pet.flip;
pet.nextFlipTicks := 3000 + Rnd(12000);
end;
// Makes Deskpet not walk off the screen
if (pet.x < 0) or ((pet.x + SpriteWidth(pet.sprite)) > ScreenWidth()) then
pet.flip := not pet.flip;
if pet.flip then
pet.dx := 5
else
pet.dx := -5;
// Makes Deskpet hop between +10 and -10
if pet.dy = 10 then
pet.dy := -10
else
pet.dy := 10;
pet.x += pet.dx;
pet.y += pet.dy;
// Wrap Deskpet if it goes offscreen
// This is left in for future minigames.
WrapSprite(pet.sprite, pet.x, pet.y);
end;
end
else
begin
// In other states we want to center the pet.
pet.dx := 0;
pet.dy := 0;
CenterPet(pet);
end;
SpriteSetX(pet.sprite, pet.x);
SpriteSetY(pet.sprite, pet.y);
end;
procedure UpdatePetSprite(var pet: Pet);
var
newAnimation: String;
begin
case pet.state of
Idle: newAnimation := 'Idle';
Sleep: newAnimation := 'Sleep';
Sick: newAnimation := 'Sick';
Eating: newAnimation := 'Eating';
Upset: newAnimation := 'Upset';
Dancing: newAnimation := 'Dancing';
end;
// We only want to start an animation
// if we're changing from our current animation.
if pet.animationName <> newAnimation then
begin
pet.animationName := newAnimation;
SpriteStartAnimation(pet.sprite, newAnimation);
end;
UpdateSprite(pet.sprite);
end;
procedure UpdatePet(var pet: Pet);
begin
UpdatePetHealth(pet);
UpdatePetState(pet);
UpdatePetDance(pet);
UpdatePetMove(pet);
UpdatePetSprite(pet);
end;
procedure UpdateGame(var game: Game);
begin
HandleButtons(game);
UpdateDay(game);
UpdateFoodGame(game);
UpdatePet(game.pet);
UpdateMusic(game);
end;
// ===============
// Draw Procedures
// ===============
procedure DrawBackground(const game: Game);
begin
if game.isDay = true then
DrawBitmap(game.dayBackground, 0, 0, OptionFlipY())
else
DrawBitmap(game.nightBackground, 0, 0);
end;
procedure DrawPet(const pet: Pet);
begin
if pet.flip then
DrawSpriteWithOpts(pet.Sprite, OptionFlipY())
else
DrawSprite(pet.Sprite);
end;
procedure DrawLight(const game: Game);
begin
// The background dims.
if game.pet.state = Sleep then
FillRectangle(RGBAColor(0, 0, 0, 125), 0, 0, ScreenWidth(), ScreenHeight());
// The background raves between a random colours.
if game.pet.state = Dancing then
FillRectangle(RGBAColor(Rnd(255), Rnd(255), Rnd(255), 125), 0, 0, ScreenWidth(), ScreenHeight());
// The background flicks between 2 red hues for an emergency effect.
if game.pet.state = Sick then
begin
if TimerTicks(game.lowHealthTimer) < 600 then
FillRectangle(RGBAColor(100, 0, 0, 125), 0, 0, ScreenWidth(), ScreenHeight());
if (TimerTicks(game.lowHealthTimer) >= 600) and (TimerTicks(game.lowHealthTimer) <= 1000) then
FillRectangle(RGBAColor(200, 0, 0, 125), 0, 0, ScreenWidth(), ScreenHeight());
if TimerTicks(game.lowHealthTimer) >= 1000 then
begin
FillRectangle(RGBAColor(200, 0, 0, 125), 0, 0, ScreenWidth(), ScreenHeight());
ResetTimer(game.lowHealthTimer);
end;
end;
end;
procedure DrawFoods(const game: Game);
var
i: Integer;
begin
if game.isPlayingFoodGame then
begin
for i := Low(game.foods) to High(game.foods) do
begin
DrawSprite(game.foods[i].sprite);
end;
end;
end;
procedure DrawBorder(const game: Game);
begin
DrawBitmap(game.border, 0, 0);
end;
procedure DrawButtons(const game: Game);
begin
DrawSprite(game.buttons.sleep);
// Draws a black semi-transparent rectangle over the button if it cannot be clicked.
if not CanSleep(game) then
FillRectangle(RGBAColor(0, 0, 0, 125), SpriteCollisionRectangle(game.buttons.sleep));
DrawSprite(game.buttons.heal);
if not CanHeal(game) then
FillRectangle(RGBAColor(0, 0, 0, 125), SpriteCollisionRectangle(game.buttons.heal));
DrawSprite(game.buttons.feed);
if not CanFoodGame(game) then
FillRectangle(RGBAColor(0, 0, 0, 125), SpriteCollisionRectangle(game.buttons.feed));
end;
procedure DrawHealth(const game: Game);
var
i: Integer;
x, y: Single;
bmp: Bitmap;
begin
for i := 0 to 4 do
begin
// i | 0 | 1 | 2 | 3 | 4
// ---+-----------+-----------+-----------+-----------+------------
// h | [0, 1, 2] | [2, 3, 4] | [4, 5, 6] | [6, 7, 8] | [8, 9, 10]
// x | 0 + 10 | 45 + 10 | 90 + 10 | 135 + 10 | 180 + 10
// y | 10 | 5 | 10 | 5 | 10
// Start 10 away from border,
// 45 units between hearts.
x := (i * 45) + 10;
// If i is even y = 10, if i is odd y = 5
y := 10 - (5 * (i Mod 2));
if game.pet.health <= (i * 2) then
bmp := game.heartEmpty
else if game.pet.health = (i * 2) + 1 then
bmp := game.heartHalf
else if game.pet.health >= (i * 2) + 2 then
bmp := game.heartFull;
DrawBitmap(bmp, x, y);
end;
end;
procedure DrawGame(const game: Game);
begin
DrawBackground(game);
DrawPet(game.pet);
DrawLight(game);
DrawFoods(game);
DrawBorder(game);
DrawButtons(game);
DrawHealth(game);
end;
procedure TerminalInstructions();
begin
WriteLn('+-----Instructions------+');
WriteLn('| |');
WriteLn('| Deskpet <3s Red Apples|');
WriteLn('| |');
WriteLn('| If Deskpet is Sick |');
WriteLn('| you cant Play anymore |');
WriteLn('| |');
WriteLn('| If Deskpet hits 0 hp |');
WriteLn('| during food game = |');
WriteLn('| GAMEOVER |');
WriteLn('| |');
WriteLn('|Click Deskpet to Dance!|');
WriteLn('+-----------------------+');
end;
// =========
// Game Loop
// =========
procedure Main();
var
myGame: Game;
begin
OpenGraphicsWindow('DeskPet', 476, 299);
LoadResources();
SetupGame(myGame);
TerminalInstructions();
repeat
ProcessEvents();
ClearScreen(ColorWhite);
UpdateGame(myGame);
DrawGame(myGame);
RefreshScreen(60);
until WindowCloseRequested();
end;
begin
Main();
end. |
unit LzmaDec;
interface
uses Winapi.Windows, System.Win.Crtl, System.SysUtils, LzmaTypes;
const
LZMA_REQUIRED_INPUT_MAX = 20;
{$Z4}
type
{$define _LZMA_PROB32}
PCLzmaProb = ^TCLzmaProb;
{$ifdef _LZMA_PROB32}
TCLzmaProb = UInt32;
{$else}
TCLzmaProb = Word;
{$endif}
TCLzmaProps = record
lc, lp, pb: Cardinal;
dicSize: UInt32;
end;
ELzmaFinishMode = (
LZMA_FINISH_ANY, { finish at any point }
LZMA_FINISH_END { block must be finished at the end }
);
ELzmaStatus = (
LZMA_STATUS_NOT_SPECIFIED, { use main error code instead }
LZMA_STATUS_FINISHED_WITH_MARK, { stream was finished with end mark. }
LZMA_STATUS_NOT_FINISHED, { stream was not finished }
LZMA_STATUS_NEEDS_MORE_INPUT, { you must provide more input bytes }
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK { there is probability that stream was finished without end mark }
);
TCLzmaDec = record
prob: TCLzmaProps;
prop: PCLzmaProb;
dic: TBytes;
buf: TBytes;
range, code: UInt32;
dicPos: SIZE_T;
dicBufSize: SIZE_T;
processedPos: UInt32;
checkDicSize: UInt32;
state: Cardinal;
reps: array[0..3] of UInt32;
remainLen: Cardinal;
needFlush: Integer;
needInitState: Integer;
numProbs: UInt32;
tempBufSize: Cardinal;
tempBuf: array[0..LZMA_REQUIRED_INPUT_MAX - 1] of Byte;
public
procedure Construct;
end;
function LzmaDec_Allocate(var state: TCLzmaDec; const prop; propsSize:
Cardinal; var alloc: TISzAlloc): TSRes; cdecl; external name _PU +
'LzmaDec_Allocate';
procedure LzmaDec_Init(var p: TCLzmaDec); cdecl; external name _PU +
'LzmaDec_Init';
procedure LzmaDec_Free(var state: TCLzmaDec; var alloc: TISzAlloc); cdecl;
external name _PU + 'LzmaDec_Free';
function LzmaDec_DecodeToBuf(var p: TCLzmaDec; var dest; var destLen: SIZE_T;
const src; var srcLen: SIZE_T; finishMode: ElzmaFinishMode; var status:
ELzmaStatus): TSRes; cdecl; external name _PU + 'LzmaDec_DecodeToBuf';
implementation
{$ifdef Win32}
{$L Win32\LzmaDec.obj}
{$else}
{$L Win64\LzmaDec.o}
{$endif}
procedure TCLzmaDec.Construct;
begin
FillChar(Self, SizeOf(Self), 0);
end;
end.
|
unit frmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BaseForms, StdCtrls, ActnList;
type
TMainForm = class(TBaseForm)
ActionList1: TActionList;
acCreateEventsForm: TAction;
acShowEventsForm: TAction;
acCloseEventsForm: TAction;
acCloseQueryEventsForm: TAction;
acHideEventsForm: TAction;
acEventsFormVisible: TAction;
acDestroyEventsForm: TAction;
acShowModalEventsForm: TAction;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
CheckBox1: TCheckBox;
memBkLog: TMemo;
Button1: TButton;
Button6: TButton;
btnClearEventsFormLog: TButton;
Button7: TButton;
chkLogActivateEvents: TCheckBox;
procedure acXXXUpdate(Sender: TObject);
procedure acCreateEventsFormExecute(Sender: TObject);
procedure acShowEventsFormExecute(Sender: TObject);
procedure acHideEventsFormExecute(Sender: TObject);
procedure acDestroyEventsFormExecute(Sender: TObject);
procedure acEventsFormVisibleExecute(Sender: TObject);
procedure acCloseEventsFormExecute(Sender: TObject);
procedure acCloseQueryEventsFormExecute(Sender: TObject);
procedure btnClearEventsFormLogClick(Sender: TObject);
procedure acShowModalEventsFormExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
procedure LogEF(const Msg: string);
procedure LogEFA(const Msg: string);
function CloseActionToString(const CloseAction: TCloseAction): string;
function MouseActivateToString(const MouseActivate: TMouseActivate): string;
function ModalResultToString(const ModalResult: TModalResult): string;
implementation
{$R *.dfm}
uses
frmEvents;
procedure LogEF(const Msg: string);
begin
if Assigned(MainForm) then
MainForm.memBkLog.Lines.Add(Msg);
end;
procedure LogEFA(const Msg: string);
begin
if Assigned(MainForm) and MainForm.chkLogActivateEvents.Checked then
LogEF(Msg);
end;
function CloseActionToString(const CloseAction: TCloseAction): string;
const
SCloseAction: array [TCloseAction] of string = ('caNone', 'caHide', 'caFree', 'caMinimize');
begin
Result := SCloseAction[CloseAction];
end;
function MouseActivateToString(const MouseActivate: TMouseActivate): string;
const
SMouseActivate: array [TMouseActivate] of string = ('maDefault', 'maActivate', 'maActivateAndEat', 'maNoActivate', 'maNoActivateAndEat');
begin
Result := SMouseActivate[MouseActivate];
end;
function ModalResultToString(const ModalResult: TModalResult): string;
begin
case ModalResult of
mrNone:
Result := 'mrNone';
mrOk:
Result := 'mrOk';
mrCancel:
Result := 'mrCancel';
mrAbort:
Result := 'mrAbort';
mrRetry:
Result := 'mrRetry';
mrIgnore:
Result := 'mrIgnore';
mrYes:
Result := 'mrYes';
mrNo:
Result := 'mrNo';
mrAll:
Result := 'mrAll';
mrNoToAll:
Result := 'mrNoToAll';
mrYesToAll:
Result := 'mrYesToAll';
mrClose:
Result := 'mrClose';
else
Result := IntToStr(ModalResult);
end;
end;
{ TMainForm }
procedure TMainForm.acXXXUpdate(Sender: TObject);
var
Flag: Boolean;
begin
if Sender = acCreateEventsForm
then Flag := not Assigned(EventsForm)
else Flag := Assigned(EventsForm);
if Sender = acShowModalEventsForm then
Flag := Flag and not EventsForm.Visible;
(Sender as TAction).Enabled := Flag;
if (Sender = acEventsFormVisible) then
(Sender as TAction).Checked := Flag and EventsForm.Visible;
end;
procedure TMainForm.acEventsFormVisibleExecute(Sender: TObject);
begin
LogEF('-- toggle visible click --');
EventsForm.Visible := not EventsForm.Visible;
end;
procedure TMainForm.acCloseEventsFormExecute(Sender: TObject);
begin
LogEF('-- close click --');
EventsForm.Close;
end;
procedure TMainForm.acCloseQueryEventsFormExecute(Sender: TObject);
var
CloseQueryResult: Boolean;
begin
LogEF('-- close query click --');
CloseQueryResult := EventsForm.CloseQuery;
LogEF('-- close query result = ' + BoolToStr(CloseQueryResult, True) + ' --');
end;
procedure TMainForm.acCreateEventsFormExecute(Sender: TObject);
begin
LogEF('-- create click --');
Application.CreateForm(TEventsForm, EventsForm);
//EventsForm := TEventsForm.Create(Self);
//EventsForm := TEventsForm.Create(Application);
end;
procedure TMainForm.acDestroyEventsFormExecute(Sender: TObject);
begin
LogEF('-- destroy click --');
FreeAndNil(EventsForm);
end;
procedure TMainForm.acHideEventsFormExecute(Sender: TObject);
begin
LogEF('-- hide click --');
EventsForm.Hide;
end;
procedure TMainForm.acShowEventsFormExecute(Sender: TObject);
begin
LogEF('-- show click --');
EventsForm.Show;
end;
procedure TMainForm.acShowModalEventsFormExecute(Sender: TObject);
var
ModalResult: TModalResult;
begin
LogEF('-- show modal click --');
ModalResult := EventsForm.ShowModal;
LogEF('-- show modal result = ' + ModalResultToString(ModalResult) + ' --');
end;
procedure TMainForm.btnClearEventsFormLogClick(Sender: TObject);
begin
memBkLog.Clear;
end;
end.
|
unit uDMManifesto;
interface
uses
System.SysUtils, System.Classes, DmdConnection, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, ACBrBase, ACBrDFe, ACBrNFe,
uUtilPadrao, Datasnap.DBClient, pcnConversao;
type
TDMManifesto = class(TDataModule)
sqlManifesto: TFDQuery;
sqlFilial: TFDQuery;
dsFilial: TDataSource;
sqlFilialID: TIntegerField;
sqlFilialNOME: TStringField;
sqlFilialNOME_INTERNO: TStringField;
ACBrNFe: TACBrNFe;
sqlConsulta: TFDQuery;
sqlFilialUF: TStringField;
sqlFilialCNPJ_CPF: TStringField;
dsManifesto: TDataSource;
sqlManifestoID: TIntegerField;
sqlManifestoCHAVE_ACESSO: TStringField;
sqlManifestoCNPJ: TStringField;
sqlManifestoINSC_ESTADUAL: TStringField;
sqlManifestoDTEMISSAO: TStringField;
sqlManifestoNOME: TStringField;
sqlManifestoNUM_NOTA: TLargeintField;
sqlManifestoVLR_NOTA: TFloatField;
sqlManifestoNUM_PROTOCOLO: TStringField;
sqlManifestoDOWNLOAD: TStringField;
sqlManifestoGRAVADA_NOTA: TStringField;
sqlManifestoTIPO_EVE: TStringField;
sqlManifestoCNPJ_FILIAL: TStringField;
sqlManifestoFILIAL: TIntegerField;
sqlManifestoNOTA_PROPRIA: TStringField;
sqlManifestoSERIE: TStringField;
sqlManifestoNSU: TStringField;
sqlManifestoDTEMISSAO2: TDateField;
sqlManifestoPOSSUI_CCE: TStringField;
sqlManifestoOCULTAR: TStringField;
sqlManifestoDTRECEBIMENTO: TDateField;
sqlManifestoSITUACAO_MANIF: TStringField;
sqlManifestoSITUACAO_NFE: TStringField;
sqlManifestoBaixado: TStringField;
sqlManifestoDescSituacao_Manif: TStringField;
sqlManifesto_Eve: TFDQuery;
sqlManifesto_EveID: TIntegerField;
sqlManifesto_EveCHAVE_ACESSO: TStringField;
sqlManifesto_EveTIPO_EVENTO: TStringField;
sqlManifesto_EveSCHEMA: TStringField;
sqlManifesto_EveXML: TMemoField;
sqlManifesto_EveORGAO: TStringField;
sqlManifesto_EveSEQ_EVENTO: TIntegerField;
sqlManifesto_EveDTEVENTO: TDateField;
sqlManifesto_EveDESCRICAO_EVENTO: TStringField;
sqlManifesto_EveCOD_EVENTO: TStringField;
sqlManifesto_EveFILIAL: TIntegerField;
sqlManifesto_EveNOTA_PROPRIA: TStringField;
sqlManifesto_EveNUM_NOTA: TIntegerField;
sqlManifesto_EveSERIE: TStringField;
sqlManifesto_EveNSU: TStringField;
dsManifestoEventos: TDataSource;
procedure DataModuleCreate(Sender: TObject);
procedure sqlManifestoCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
ctConsulta : String;
procedure Inicia_NFe;
procedure prc_Localizar(ID : Integer);
procedure EnviarEvento(pTipo : TpcnTpEvento);
function ultimo_nsu(ID_Filial : Integer) : Integer;
end;
var
DMManifesto: TDMManifesto;
implementation
uses
Vcl.Dialogs;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDMManifesto }
procedure TDMManifesto.DataModuleCreate(Sender: TObject);
begin
ctConsulta := sqlConsulta.SQL.Text;
end;
procedure TDMManifesto.EnviarEvento(pTipo: TpcnTpEvento);
var
sCNPJ, lMsg, vSIT_EVENTO : String;
begin
ACBrNFe.NotasFiscais.Clear;
Inicia_NFe;
sCNPJ := Monta_Numero(sqlFilialCNPJ_CPF.AsString,14);
ACBrNFe.EventoNFe.Evento.Clear;
with ACBrNFe.EventoNFe.Evento.New do
begin
InfEvento.cOrgao := 91;
InfEvento.chNFe := Trim(sqlManifestoCHAVE_ACESSO.AsString);
InfEvento.CNPJ := sCNPJ;
InfEvento.dhEvento := Now;
InfEvento.tpEvento := pTipo;
InfEvento.versaoEvento := '1.00';
end;
if (pTipo = teManifDestCiencia) then
vSIT_EVENTO := '1'
else
if (pTipo = teManifDestConfirmacao) then
vSIT_EVENTO := '2'
else
if (pTipo = teManifDestDesconhecimento) then
vSIT_EVENTO := '3'
else
if (pTipo = teManifDestOperNaoRealizada) then
vSIT_EVENTO := '4';
ACBrNFe.EnviarEvento(StrToInt(vSIT_EVENTO));
if (ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 128)or
(ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 135) then
begin
sqlManifesto.Edit;
sqlManifestoSITUACAO_MANIF.AsString := vSIT_EVENTO;
sqlManifesto.Post;
end
else
if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 573 then
begin
ShowMessage('Duplicidade de Evento!');
sqlManifesto.Edit;
sqlManifestoSITUACAO_MANIF.AsString := vSIT_EVENTO;
sqlManifesto.Post;
end
else
if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.xMotivo <> '135' then
begin
with ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento do
begin
lMsg:=
'Id: '+Id+#13+
'tpAmb: '+TpAmbToStr(tpAmb)+#13+
'verAplic: '+verAplic+#13+
'cOrgao: '+IntToStr(cOrgao)+#13+
'cStat: '+IntToStr(cStat)+#13+
'xMotivo: '+xMotivo+#13+
'chNFe: '+chNFe+#13+
'tpEvento: '+TpEventoToStr(tpEvento)+#13+
'xEvento: '+xEvento+#13+
'nSeqEvento: '+IntToStr(nSeqEvento)+#13+
'CNPJDest: '+CNPJDest+#13+
'emailDest: '+emailDest+#13+
'dhRegEvento: '+DateTimeToStr(dhRegEvento)+#13+
'nProt: '+nProt;
end;
ShowMessage(lMsg);
end;
end;
procedure TDMManifesto.Inicia_NFe;
begin
{$IFDEF ACBrNFeOpenSSL}
ACBrNFe.Configuracoes.Certificados.Certificado := SQLLocate('FILIAL_CERTIFICADOS','ID','NUMERO_SERIE',sqlFilialID.AsString);
ACBrNFe.Configuracoes.Certificados.Senha := SQLLocate('FILIAL_CERTIFICADOS','ID','SENHA_WEB',sqlFilialID.AsString);
{$ELSE}
ACBrNFe.Configuracoes.Certificados.NumeroSerie := SQLLocate('FILIAL_CERTIFICADOS','ID','NUMERO_SERIE',sqlFilialID.AsString);
{$ENDIF}
end;
procedure TDMManifesto.prc_Localizar(ID: Integer);
begin
sqlManifesto.Close;
sqlManifesto.ParamByName('ID').AsInteger := ID;
sqlManifesto.Open;
end;
procedure TDMManifesto.sqlManifestoCalcFields(DataSet: TDataSet);
begin
if sqlManifestoSITUACAO_MANIF.AsString = '1' then
sqlManifestoDescSituacao_Manif.AsString := 'Ciencia Operação';
if sqlManifestoSITUACAO_MANIF.AsString = '2' then
sqlManifestoDescSituacao_Manif.AsString := 'Confirmada Operação';
if sqlManifestoSITUACAO_MANIF.AsString = '3' then
sqlManifestoDescSituacao_Manif.AsString := 'Desconhece Operação';
if sqlManifestoSITUACAO_MANIF.AsString = '4' then
sqlManifestoDescSituacao_Manif.AsString := 'Operação não Realizada';
if sqlManifestoDOWNLOAD.AsString = 'S' then
sqlManifestoBaixado.AsString := 'SIM'
else
sqlManifestoBaixado.AsString := 'NÃO';
end;
function TDMManifesto.ultimo_nsu(ID_Filial: Integer): Integer;
var
i : Integer;
xSql : String;
FDconn : TDMConection;
begin
FDconn := TDMConection.Create(nil);
try
xSql := 'select coalesce(max(NSU), 0) NSU from MANIFESTO_AN where FILIAL = ' + IntToStr(ID_Filial);
i := FDconn.FDConnection.ExecSQLScalar(xSql);
Result := i;
finally
FDconn.Free;
end;
end;
initialization
ReportMemoryLeaksOnShutdown := True;
end.
|
unit GXHtmlHelp;
interface
uses Windows;
function HtmlHelp(hWndCaller: HWND; pszFile: PChar; uCommand: UINT; dwData: DWORD): HWND;
function HtmlHelpA(hWndCaller: HWND; pszFile: PAnsiChar; uCommand: UINT; dwData: DWORD): HWND;
function HtmlHelpW(hWndCaller: HWND; pszFile: PWideChar; uCommand: UINT; dwData: DWORD): HWND;
const
HH_DISPLAY_INDEX = 2;
HH_HELP_CONTEXT = $F;
implementation
uses SysUtils;
type
THtmlHelpAProc = function (hWndCaller: HWND; pszFile: PAnsiChar; uCommand: UINT; dwData: DWORD): HWnd; stdcall;
THtmlHelpWProc = function (hWndCaller: HWND; pszFile: PWideChar; uCommand: UINT; dwData: DWORD): HWnd; stdcall;
var
HtmlHelpOcxModule: HModule;
HtmlHelpAProc: THtmlHelpAProc;
HtmlHelpWProc: THtmlHelpWPRoc;
function HtmlHelpSupported: Boolean;
begin
if HtmlHelpOcxModule = 0 then
begin
HtmlHelpOcxModule := LoadLibrary('hhctrl.ocx');
if HtmlHelpOcxModule <> 0 then
begin
@HtmlHelpAProc := GetProcAddress(HtmlHelpOcxModule, 'HtmlHelpA');
@HtmlHelpWProc := GetProcAddress(HtmlHelpOcxModule, 'HtmlHelpW');
end;
end;
if Assigned(HtmlHelpAProc) and Assigned(HtmlHelpWProc) then
Result := True
else
Result := False;
end;
function HtmlHelp(hWndCaller: HWND; pszFile: LPCTSTR; uCommand: UINT; dwData: DWORD): HWND;
begin
Result := HtmlHelpA(hWndCaller, pszFile, uCommand, dwData);
if Result = 0 then
raise Exception.Create('Microsoft HTML Help is not functioning. Please update to Internet Explorer 5 or later.');
end;
function HtmlHelpA(hWndCaller: HWND; pszFile: PAnsiChar; uCommand: UINT; dwData:DWORD): HWND;
begin
if HtmlHelpSupported then
Result := HtmlHelpAProc(hWndCaller, pszFile, uCommand, dwData)
else
Result := 0;
end;
function HtmlHelpW(hWndCaller: HWND; pszFile: PWideChar; uCommand: UINT; dwData:DWORD): HWND;
begin
if HtmlHelpSupported then
Result := HtmlHelpWProc(hWndCaller, pszFile, uCommand, dwData)
else
Result := 0;
end;
procedure UnloadHtmlHelpModule;
begin
if HtmlHelpOcxModule <> 0 then
FreeLibrary(HtmlHelpOcxModule);
end;
initialization
HtmlHelpOcxModule := 0;
finalization
UnloadHtmlHelpModule;
end.
|
unit SimpleOptionPart;
interface
uses
SearchOption_Intf;
type
TSimpleOptionPart = class(TAbsSearchOptionPart)
protected
FKey: String;
FValue: String;
public
function GetValues(key: String): String; override;
procedure SetValues(key, val: String); override;
end;
implementation
{ TSimpleOptionPart }
function TSimpleOptionPart.GetValues(key: String): String;
begin
if key = 'use' then
begin
if IsUse = true then
result := 'true'
else
result := 'false';
end
else if key = FKey then
begin
result := FValue;
end;
end;
procedure TSimpleOptionPart.SetValues(key, val: String);
begin
FKey := key;
FValue := val;
end;
end.
|
unit MainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics,
Dialogs, StdCtrls,
WpcExceptions,
WpcScript,
WpcScriptParser,
WpcScriptExecutor,
WallpaperSetter;
type
{ TBannerForm }
TBannerForm = class(TForm)
Button1: TButton;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
BannerForm: TBannerForm;
implementation
{$R *.lfm}
procedure RunScript(PathToScript : String);
var
ScriptContent : TStringList;
ScriptParser : TWpcScriptParser;
Script : TWpcScript;
ScriptExecutor : TWpcScriptExecutor;
WallpaperSetter : IWallpaperSetter;
ErrorMessage : String;
begin
try
try
ScriptContent := TStringList.Create();
// TODO check file type and size (limit into property)
ScriptContent.LoadFromFile(PathToScript);
ScriptParser := TWpcScriptParser.Create(ScriptContent);
Script := ScriptParser.Parse();
WallpaperSetter := TWpcDebugWallpaperSetter.Create('log.txt');
ScriptExecutor := TWpcScriptExecutor.Create(Script, WallpaperSetter);
ScriptExecutor.ExecuteScript();
except
on ParseExcepton : TWpcScriptParseException do begin
ErrorMessage := Concat('Failed to parse script: ', ParseExcepton.Message);
if (ParseExcepton.Line <> TWpcScriptParseException.UNKNOWN_LINE) then
ErrorMessage := Concat(ErrorMessage, ' Line: ', IntToStr(ParseExcepton.Line + 1));
if (ParseExcepton.WordNumer <> TWpcScriptParseException.UNKNOWN_WORD_NUMBER) then
ErrorMessage := Concat(ErrorMessage, ' Word: ', IntToStr(ParseExcepton.WordNumer + 1));
WriteLn(ErrorMessage);
end;
on WpcException : TWpcException do begin
ErrorMessage := Concat('Error: ', WpcException.Message);
WriteLn(ErrorMessage);
end;
on E : Exception do begin
ErrorMessage := Concat('Unknown error: ', E.Message);
WriteLn(ErrorMessage);
end;
end;
finally
{if (ScriptParser <> nil) then ScriptParser.Free();
if (ScriptExecutor <> nil) then ScriptExecutor.Free();
if (WallpaperSetter <> nil) then WallpaperSetter.Free(); }
ScriptContent.Free();
end;
end;
{ TBannerForm }
procedure TBannerForm.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute() then
RunScript(OpenDialog1.Filename);
WriteLn('The Script exits without erros.');
end;
end.
|
unit Log;
interface
type
TLog = class
private
FFileName: string;
FFile: TextFile;
procedure OpenLogfile;
public
constructor Create(const FileName: string);
procedure Debug(const Message: string);
procedure Warning(const Message: string);
procedure Error(const Message: string);
procedure Information(const Message: string);
end;
implementation
uses
Forms, SysUtils;
const
BreakingLine =
'//----------------------------------------------------------------------------//';
// ** This procedure just creates a new Logfile an appends when it was created **
constructor TLog.Create(const FileName: string);
begin
FFileName := FileName;
end;
procedure TLog.OpenLogfile;
begin
// Assigns Filename to variable F
AssignFile(FFile, FFileName);
// Rewrites the file F
Rewrite(FFile);
// Open file for appending
Append(FFile);
// Write text to Textfile F
WriteLn(FFile, BreakingLine);
WriteLn(FFile, 'This Logfile was created on ' + DateTimeToStr(Now));
WriteLn(FFile, BreakingLine);
WriteLn(FFile, '');
end;
procedure TLog.Debug(const Message: string);
begin
Information('Debug: ' + Message);
end;
procedure TLog.Error(const Message: string);
begin
Information('Error: ' + Message);
end;
procedure TLog.Information(const Message: string);
begin
try
// Checking for file
if not FileExists(FFileName) then
OpenLogfile // if file is not available then create a new file
else
begin// Assigns Filename to variable F
AssignFile(FFile, FFileName);
// start appending text
Append(FFile);
end;
except
Exit;
end;
// Write a new line with current date and message to the file
WriteLn(FFile, DateTimeToStr(Now) + ': ' + Message);
// Close file
CloseFile(FFile)
end;
procedure TLog.Warning(const Message: string);
begin
Information('Warning: ' + Message);
end;
end.
|
program hw3q3b;
var
Vtype : char ;
Vval : string ;
Vint : integer ;
Vreal : real ;
Vbool : Boolean ;
strCode : integer ;
(*Only one procedure is needed to negate the input, but without using variant
records, we then need separate variables for each different type of input,
plus a test variable to serve as the equivalent of the 'kind' field in the
variant record. Thus, we are being wasteful as we have to send along two
"dummy variables" in each procedure call instead of just the variable type
actually given by the user. The variable 'test' will indicate which kind
of input was given. We can then negate this value and print the result.*)
procedure NEG(test : char; ival : integer; rval : real; bval : Boolean) ;
begin
case test of
'i' : begin
ival := -1 * ival ;
writeln('Negation of input is: ', ival)
end ;
'r' : begin
rval := -1.0 * rval ;
writeln('Negation of input is: ', rval)
end ;
'b' : begin
bval := not bval ;
writeln('Negation of input is: ', bval)
end ;
end; (*case*)
end;(*proc NEG*)
begin (*program*)
(*identification*)
writeln('Mark Sattolo, 428500, CSI3125, DGD-2, Homework#3') ;
writeln ;
(*initialize the variables*)
Vint := 0 ;
Vreal := 0.0 ;
Vbool := false ;
(*ask for the input*)
writeln('Please enter a value preceded by its type (i, r, or b).') ;
writeln('For example: r 3.14129') ;
writeln ;
write('Input: ') ;
(*get the input*)
readln(Vtype, Vval) ;
(*According to Prof.Szpackowicz in class on Nov.9, we can assume that all input
will be perfect and do not have to do any error-checking for this.*)
(*if a boolean*)
if Vtype = 'b' then begin
(*check for the most probable variations of 'true'*)
if ((Vval = ' true') or (Vval = ' True') or (Vval = ' TRUE')) then
Vbool := true
(*else can assume the input must be some variation of 'false'*)
else Vbool := false ;
end ;
(*if an integer*)
if Vtype = 'i' then
(*convert the string to an integer - we can assume Vval will represent an integer*)
Val(Vval, Vint, strCode) ;
(*if a real*)
if Vtype = 'r' then
(*convert the string to a real - we can assume Vval will represent a real*)
Val(Vval, Vreal, strCode) ;
(*negate the input value by calling the NEG procedure*)
NEG(Vtype, Vint, Vreal, Vbool) ;
end.
|
unit History;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
THistoryForm = class(TForm)
JumpMemo: TMemo;
SaveBtn: TButton;
CloseBtn: TButton;
JumpSaveDialog: TSaveDialog;
procedure CloseBtnClick(Sender: TObject);
procedure SaveBtnClick(Sender: TObject);
end;
var
HistoryForm: THistoryForm;
implementation
{$R *.dfm}
uses
Constants;
procedure THistoryForm.CloseBtnClick(Sender: TObject);
begin
Close();
end;
procedure THistoryForm.SaveBtnClick(Sender: TObject);
resourcestring
LNG_SAVED = 'History successfully saved!';
begin
if JumpSaveDialog.Execute then
begin
JumpMemo.Lines.SaveToFile(JumpSaveDialog.FileName);
MessageDlg(LNG_SAVED, mtInformation, [mbOk], 0);
end;
end;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{NOTE: THIS UNIT IS NOT TO BE DISTRIBUTED}
unit STGenLIC;
interface
function GenerateHexString(const aSerialNumber : string) : string;
implementation
uses
Windows,
SysUtils;
const
MagicSeed = $6457;
MagicHash = $5746;
var
RandSeed : longint;
function RandomNumber : integer;
begin
Result := ((RandSeed * 4561) + 51349) mod 243000;
RandSeed := Result;
end;
function HashBKDR(const S : string; Lower, Upper : integer; StartValue : longint) : longint;
var
i : integer;
begin
Result := StartValue;
for i := Lower to Upper do begin
Result := (Result * 31) + ord(S[i]);
end;
end;
function IsDigit(aCh : char) : boolean;
begin
Result := ('0' <= aCh) and (aCh <= '9');
end;
procedure IncString(var S : string);
var
Done : boolean;
i : integer;
begin
i := 8;
repeat
Done := true;
if (S[i] = '9') then
S[i] := 'A'
else if (S[i] = 'F') then begin
S[i] := '0';
dec(i);
if (i <> 0) then
Done := false;
end
else
inc(S[i])
until Done;
end;
function GenerateHexString(const aSerialNumber : string) : string;
var
i : integer;
SNHash : longint;
StartHash : longint;
NextDigit : integer;
begin
{validate the serial number}
if (length(aSerialNumber) <> 6) then
raise Exception.Create('GenerateHexString: serial number must be 6 digits');
for i := 1 to 6 do
if not IsDigit(aSerialNumber[i]) then
raise Exception.Create('GenerateHexString: serial number not all digits');
{calculate the serial number hash: this will give us an index
between 0 and 9}
SNHash := HashBKDR(aSerialNumber, 1, 6, 0);
SNHash := (SNHash shr 5) mod 10;
{calculate a hex string that matches the serial number}
RandSeed := MagicSeed;
StartHash := RandomNumber;
for i := 0 to SNHash do
StartHash := RandomNumber;
{randomize}
RandSeed := GetTickCount;
{create a random hex string}
SetLength(Result, 8);
for i := 1 to 8 do begin
NextDigit := (RandomNumber and $F000) shr 12;
if NextDigit <= 9 then
Result[i] := char(ord('0') + NextDigit)
else
Result[i] := char(ord('A') + NextDigit - 10)
end;
while true do begin
if (HashBKDR(Result, 1, 8, StartHash) and $FFFF) = MagicHash then
Exit;
IncString(Result);
end;
end;
end.
|
unit mebdd_worker_reg;
(*
MEB-DD's register-related functions.
*)
{$MODE OBJFPC}
interface
function read_registry_hklm_value_int (key_path:AnsiString; key_name:AnsiString):Integer;
function read_registry_hklm_value_str (key_path:AnsiString; key_name:AnsiString):AnsiString;
function read_registry_hkcu_value_int (key_path:AnsiString; key_name:AnsiString):Integer;
function read_registry_hkcu_value_string (key_path:AnsiString; key_name:AnsiString):AnsiString;
function write_registry_hkcu_value_int (key_path:AnsiString; key_name:AnsiString; new_value:Integer):Boolean;
function write_registry_hkcu_value_string (key_path:AnsiString; key_name:AnsiString; new_value:AnsiString):Boolean;
implementation
uses registry, Classes, SysUtils, Windows;
function is_windows_64: boolean;
{
Detect if we are running on 64 bit Windows or 32 bit Windows,
independently of bitness of this program.
Original source:
http://www.delphipraxis.net/118485-ermitteln-ob-32-bit-oder-64-bit-betriebssystem.html
modified for FreePascal in German Lazarus forum:
http://www.lazarusforum.de/viewtopic.php?f=55&t=5287
}
{$ifdef WIN32} //Modified KpjComp for 64bit compile mode
type
TIsWow64Process = function( // Type of IsWow64Process API fn
Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall;
var
IsWow64Result: Windows.BOOL; // Result from IsWow64Process
IsWow64Process: TIsWow64Process; // IsWow64Process fn reference
begin
// Try to load required function from kernel32
IsWow64Process := TIsWow64Process(Windows.GetProcAddress(Windows.GetModuleHandle('kernel32'),'IsWow64Process'));
if Assigned(IsWow64Process) then
begin
// Function is implemented: call it
if not IsWow64Process(Windows.GetCurrentProcess, IsWow64Result) then
raise SysUtils.Exception.Create('IsWindows64: bad process handle');
// Return result of function
Result := IsWow64Result;
end
else
// Function not implemented: can't be running on Wow64
Result := False;
{$else} //if were running 64bit code, OS must be 64bit :)
begin
Result := True;
{$endif}
end;
function read_registry_hklm_value_int (key_path:AnsiString; key_name:AnsiString):Integer;
var
key_value: Integer;
registry: TRegistry;
begin
if is_windows_64() then
registry := TRegistry.Create(KEY_READ)
else
registry := TRegistry.Create(KEY_READ OR KEY_WOW64_32KEY);
{$I-}
try
registry.RootKey := HKEY_LOCAL_MACHINE;
if registry.OpenKeyReadOnly(key_path) then
key_value := registry.ReadInteger(key_name);
except
On ERegistryException do
key_value := -1;
end;
{$I+}
registry.Free;
read_registry_hklm_value_int := key_value;
end;
function read_registry_hklm_value_str (key_path:AnsiString; key_name:AnsiString):AnsiString;
var
key_value: AnsiString='';
registry: TRegistry;
begin
if is_windows_64() then
registry := TRegistry.Create(KEY_READ)
else
registry := TRegistry.Create(KEY_READ OR KEY_WOW64_32KEY);
{$I-}
try
registry.RootKey := HKEY_LOCAL_MACHINE;
if registry.OpenKeyReadOnly(key_path) then
key_value := registry.ReadString(key_name);
except
On ERegistryException do
key_value := '';
end;
{$I+}
registry.Free;
read_registry_hklm_value_str := key_value;
end;
function read_registry_hkcu_value_int (key_path:AnsiString; key_name:AnsiString):Integer;
var
key_value: integer=-1;
registry: TRegistry;
begin
if is_windows_64() Then
registry := TRegistry.Create(KEY_READ OR KEY_WOW64_64KEY)
else
registry := TRegistry.Create(KEY_READ OR KEY_WOW64_32KEY);
{$I-}
try
registry.RootKey := HKEY_CURRENT_USER;
if registry.OpenKeyReadOnly(key_path) then
key_value := registry.ReadInteger(key_name);
except
On ERegistryException do
key_value := -1;
end;
{$I+}
registry.Free;
read_registry_hkcu_value_int := key_value;
end;
function read_registry_hkcu_value_string (key_path:AnsiString; key_name:AnsiString):AnsiString;
var
key_value: AnsiString;
registry: TRegistry;
begin
if is_windows_64() Then
registry := TRegistry.Create(KEY_READ OR KEY_WOW64_64KEY)
else
registry := TRegistry.Create(KEY_READ OR KEY_WOW64_32KEY);
{$I-}
try
registry.RootKey := HKEY_CURRENT_USER;
if registry.OpenKeyReadOnly(key_path) then
key_value := registry.ReadString(key_name);
except
On ERegistryException do
key_value := '';
end;
{$I+}
registry.Free;
read_registry_hkcu_value_string := key_value;
end;
function write_registry_hkcu_value_int (key_path:AnsiString; key_name:AnsiString; new_value:Integer):Boolean;
var
write_ok: boolean=false;
registry: TRegistry;
begin
if is_windows_64() Then
registry := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY)
else
registry := TRegistry.Create(KEY_WRITE OR KEY_WOW64_32KEY);
try
registry.RootKey := HKEY_CURRENT_USER;
if registry.OpenKey(key_path, True) then
begin
registry.WriteInteger(key_name, new_value);
registry.CloseKey;
write_ok := true;
end;
except
On ERegistryException do
write_ok := False;
end;
registry.Free;
write_registry_hkcu_value_int := write_ok;
end;
function write_registry_hkcu_value_string (key_path:AnsiString; key_name:AnsiString; new_value:AnsiString):Boolean;
var
write_ok: boolean=false;
registry: TRegistry;
begin
if is_windows_64() Then
registry := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY)
else
registry := TRegistry.Create(KEY_WRITE OR KEY_WOW64_32KEY);
try
registry.RootKey := HKEY_CURRENT_USER;
if registry.OpenKey(key_path, True) then
begin
registry.WriteString(key_name, new_value);
registry.CloseKey;
write_ok := true;
end;
except
On ERegistryException do
write_ok := False;
end;
registry.Free;
write_registry_hkcu_value_string := write_ok;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Panel1: TPanel;
procedure FormCreate(Sender: TObject);
procedure Panel1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Panel1Paint(Sender: TObject);
private
FOldCell: integer;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
FOldCell:= -1;
Application.HintHidePause:= 5000;
end;
procedure TForm1.Panel1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
nCell: integer;
w: integer;
begin
w:= panel1.Width;
if X<w div 3 then nCell:= 0
else
if X<w*2 div 3 then nCell:= 1
else
nCell:= 2;
if nCell<>FOldCell then
begin
FOldCell:= nCell;
Panel1.Hint:= 'Hint for cell '+Inttostr(nCell+1);
Application.HideHint;
Application.ActivateHint(Mouse.CursorPos, true);
end;
end;
procedure TForm1.Panel1Paint(Sender: TObject);
const
cells=3;
var
w, h, i: integer;
c: tcanvas;
begin
w:= panel1.Width;
h:= panel1.Height;
c:= panel1.Canvas;
for i:= 0 to cells-1 do
begin
c.pen.color:= clNavy;
c.Rectangle(i*w div 3+1, 0, (i+1)*w div 3-1, h);
c.TextOut(i*w div 3+15, h div 2 - 5, 'Cell '+Inttostr(i+1));
end;
end;
end.
|
program jugamosConListas;
type
lista = ^nodo;
nodo = record
num : Integer;
sig : lista;
end;
procedure insertarOrdenado(var pri:lista; valor:Integer);
var
nue,act,ant: lista;
begin
new(nue);
nue^.num:= valor;
act:=pri;
ant:=pri;
while (act <> nil) and (valor > act^.num) do
begin
ant:= act;
act:= act^.sig;
end;
if (act = ant) then
pri:= nue
else
ant^.sig:=nue;
nue^.sig:= act;
end;
procedure IncrementarLista(L:lista; valorX: Integer);
begin
while (L <> nil) do
begin
L^.num:= L^.num + valorX;
L:= L^.sig;
end;
end;
function estaOrdenada(pri:lista): Boolean;
var
act: lista;
begin
act:= pri;
while (act <> nil) and (pri^.num <= act^.num) do
begin
pri:= act;
act:= act^.sig;
end;
if (act = nil) then
estaOrdenada:= true
else
estaOrdenada:= false;
end;
procedure subLista(pri:lista; var L:lista; numA,numB:Integer);
begin
while (pri <> nil) do
begin
if (pri^.num > numA) and (pri^.num < numB) then
begin
insertarOrdenado(L, pri^.num);
end;
pri:= pri^.sig;
end;
end;
procedure imprimirLista(L:lista);
begin
while (L <> nil) do
begin
writeln(L^.num);
L:= L^.sig;
end;
end;
procedure eliminar(var pri:lista; valorB:Integer);
var
act,ant: lista;
begin
act:= pri;
ant:= pri;
while (act <> nil ) and (act^.num <> valorB) do
begin
ant:= act;
act:= act^.sig;
end;
if (act <> nil) then
begin
if (act = pri) then
pri:= act^.sig
else
ant^.sig:= act^.sig;
dispose(act);
end;
end;
var
pri: lista;
L: lista;
valor,valorX,valorB, numA,numB: Integer;
begin
pri:= nil;
L:=nil;
write('Ingrese un numero: ');
readln(valor);
while (valor <> 0) do
begin
insertarOrdenado(pri, valor);
write('Ingrese un numero: ');
readln(valor);
end;
imprimirLista(pri);
write('Ingrese un numeroX: ');
readln(valorX);
IncrementarLista(pri, valorX);
imprimirLista(pri);
if (estaOrdenada(pri)) then
writeln('La lista esta ORDENADA')
else
writeln('La lista NO ESTA ORDENADA');
write('Ingrese el numero a eliminar: ');
readln(valorB);
eliminar(pri,valorB);
writeln();
imprimirLista(pri);
write('Ingrese el numero A: ');
readln(numA);
write('Ingrese el numero B: ');
readln(numB);
subLista(pri,L,numA,numB);
imprimirLista(L);
readln();
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmSchemaPublicEvent;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel,
cxPC, cxControls, StdCtrls, cxButtons, ExtCtrls,
Ora, OraStorage, GenelDM;
type
TSchemaPublicEventFrm = class(TForm)
Panel1: TPanel;
btnOK: TcxButton;
btnCancel: TcxButton;
Panel2: TPanel;
imgToolBar: TImage;
imgObject: TImage;
Shape1: TShape;
lblAction: TLabel;
lblObjectName: TcxLabel;
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
FResult : boolean;
FObj: TObject;
FOraEvent: TOraEvent;
public
{ Public declarations }
function Init(obj: TObject; OEvent: TOraEvent): boolean;
end;
var
SchemaPublicEventFrm: TSchemaPublicEventFrm;
implementation
{$R *.dfm}
uses OraSynonym, OraSequence, OraProcSource, OraDBLink, OraTriger, OraConstraint,
OraIndex, OraView, VisualOptions, OraUser, OraDirectory, OraRollbackSegment,
OraTablespace;
function TSchemaPublicEventFrm.Init(Obj: TObject; OEvent: TOraEvent): boolean;
var
objectID: integer;
begin
SchemaPublicEventFrm := TSchemaPublicEventFrm.Create(Application);
Self := SchemaPublicEventFrm;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
FObj := Obj;
FOraEvent := OEvent;
FResult := false;
objectID := 0;
if (FObj is TSynonymList) then
begin
lblObjectName.Caption := TSynonymList(FObj).SynonymItems[0].SynonymName;
objectID := Integer(TDBFormType(dbSynonyms));
end;
if (FObj is TSequence) then
begin
lblObjectName.Caption := 'Sequence [ '+TSequence(FObj).SEQUENCE_NAME+' ]';
objectID := Integer(TDBFormType(dbSequences));
end;
if (FObj is TProcSource) then
begin
lblObjectName.Caption := TProcSource(FObj).SOURCE_NAME;
if TProcSource(FObj).SOURCE_TYPE = stProcedure then objectID := Integer(TDBFormType(dbProcedures));
if TProcSource(FObj).SOURCE_TYPE = stPackage then objectID := Integer(TDBFormType(dbPackages));
if TProcSource(FObj).SOURCE_TYPE = stTrigger then objectID := Integer(TDBFormType(dbTriggers));
if TProcSource(FObj).SOURCE_TYPE = stFunction then objectID := Integer(TDBFormType(dbFunctions));
if TProcSource(FObj).SOURCE_TYPE = stType then objectID := Integer(TDBFormType(dbTypes));
end;
if (FObj is TSynonyms) then
begin
lblObjectName.Caption := TSynonyms(FObj).SYNONYM_NAME;
objectID := Integer(TDBFormType(dbSynonyms));
end;
if (FObj is TDBLink) then
begin
lblObjectName.Caption := TDBLink(FObj).DB_LINK;
objectID := Integer(TDBFormType(dbDatabaseLinks));
end;
if (FObj is TTrigger) then
begin
lblObjectName.Caption := TTrigger(FObj).TRIGGER_NAME;
objectID := Integer(TDBFormType(dbTriggers));
end;
if (FObj is TSynonymList) then
begin
lblObjectName.Caption := TSynonymList(FObj).SynonymItems[0].SynonymName;
objectID := Integer(TDBFormType(dbSynonyms));
end;
if (FObj is TColumnList) then
begin
lblObjectName.Caption := TColumnList(FObj).TableName+'.'+TColumnList(FObj).Items[0].ColumnName;
objectID := Integer(TDBFormType(dbColumns));
end;
if (FObj is TConstraint) then
begin
lblObjectName.Caption := TConstraint(FObj).ConstraintName;
objectID := Integer(TDBFormType(dbConstraint));
end;
if (FObj is TTableIndex) then
begin
lblObjectName.Caption := TTableIndex(FObj).IndexName;
objectID := Integer(TDBFormType(dbIndexes));
end;
if (FObj is TView) then
begin
lblObjectName.Caption := TView(FObj).VIEW_NAME;
objectID := Integer(TDBFormType(dbView));
end;
if (FObj is TUser) then
begin
lblObjectName.Caption := TUser(FObj).USERNAME;
objectID := Integer(TDBFormType(dbUsers));
end;
if (FObj is TDBDirectory) then
begin
lblObjectName.Caption := TDBDirectory(FObj).DIRECTORY_NAME;
objectID := Integer(TDBFormType(dbDirectories));
end;
if (FObj is TRollbackSegment) then
begin
lblObjectName.Caption := TRollbackSegment(FObj).SEGMENT_NAME;
objectID := Integer(TDBFormType(dbRollbackSegments));
end;
if (FObj is TTablespace) then
begin
lblObjectName.Caption := TTablespace(FObj).TABLESPACE_NAME;
objectID := Integer(TDBFormType(dbTablespaces));
end;
dmGenel.ilSchemaBrowser.GetBitmap(objectID,imgObject.Picture.Bitmap);
Caption := OraEvent[FOraEvent]+' '+DBFormType[TDBFormType(objectID)];
lblAction.Caption := 'Are you sure you want to '+UpperCase(OraEvent[FOraEvent])+' selected '+DBFormType[TDBFormType(objectID)]+' ?';
ShowModal;
result := FResult;
Free;
end;
procedure TSchemaPublicEventFrm.btnCancelClick(Sender: TObject);
begin
close;
end;
procedure TSchemaPublicEventFrm.btnOKClick(Sender: TObject);
begin
btnOK.Enabled := false;
if (FObj is TSynonymList) then
begin
if FOraEvent = oeDrop then FResult := TSynonymList(FObj).DropSynonym;
end;
if (FObj is TSequence) then
begin
if FOraEvent = oeDrop then FResult := TSequence(FObj).DropSequence;
end;
if (FObj is TProcSource) then
begin
if FOraEvent = oeDrop then FResult := TProcSource(FObj).DropSource;
if FOraEvent = oeCompile then
begin
FResult := TProcSource(FObj).CompileSource;
FResult := true;
end;
end;
if (FObj is TSynonyms) then
begin
if FOraEvent = oeDrop then FResult := TSynonyms(FObj).DropSynonym;
end;
if (FObj is TSynonymList) then
begin
if FOraEvent = oeDrop then FResult := TSynonymList(FObj).DropSynonym;
end;
if (FObj is TDBLink) then
begin
if FOraEvent = oeDrop then FResult := TDBLink(FObj).DropDBLink;
end;
if (FObj is TTrigger) then
begin
if FOraEvent = oeDrop then FResult := TTrigger(FObj).DropTrigger;
if FOraEvent = oeEnable then FResult := TTrigger(FObj).EnableTrigger;
if FOraEvent = oeDisable then FResult := TTrigger(FObj).DisableTrigger;
if FOraEvent = oeCompile then
begin
TTrigger(FObj).CompileTrigger;
FResult := True;
end;
end;
if (FObj is TColumnList) then
begin
if FOraEvent = oeDrop then FResult := TColumnList(FObj).DropColumn;
end;
if (FObj is TConstraint) then
begin
if FOraEvent = oeDrop then FResult := TConstraint(FObj).DropConstraint;
if FOraEvent = oeEnable then FResult := TConstraint(FObj).EnableConstraint;
if FOraEvent = oeDisable then FResult := TConstraint(FObj).DisableConstraint;
end;
if (FObj is TTableIndex) then
begin
if FOraEvent = oeDrop then FResult := TTableIndex(FObj).DropIndex;
if FOraEvent = oeRebuild then FResult := TTableIndex(FObj).RebuildIndex;
if FOraEvent = oeCoalesce then FResult := TTableIndex(FObj).CoalesceIndex;
end;
if (FObj is TView) then
begin
if FOraEvent = oeDrop then FResult := TView(FObj).DropView;
if FOraEvent = oeCompile then FResult := TView(FObj).CompileView;
if FOraEvent = oeDisableTriggers then FResult := TView(FObj).DisableALLTriggers;
if FOraEvent = oeEnableTriggers then FResult := TView(FObj).EnableALLTriggers;
end;
if (FObj is TUser) then
begin
if FOraEvent = oeDrop then FResult := TUser(FObj).DropUser;
end;
if (FObj is TDBDirectory) then
begin
if FOraEvent = oeDrop then FResult := TDBDirectory(FObj).DropDBDirectory;
end;
if (FObj is TRollbackSegment) then
begin
if FOraEvent = oeDrop then FResult := TRollbackSegment(FObj).DropRollbackSegment;
if FOraEvent = oeOffLine then FResult := TRollbackSegment(FObj).RollbackSegmentToOffline;
if FOraEvent = oeOnLine then FResult := TRollbackSegment(FObj).RollbackSegmentToOnline
end;
if (FObj is TTablespace) then
begin
if FOraEvent = oeDrop then FResult := TTablespace(FObj).DropTablespace;
if FOraEvent = oeOffLine then FResult := TTablespace(FObj).TablespaceToOffline;
if FOraEvent = oeOnLine then FResult := TTablespace(FObj).TablespaceToOnline
end;
if FResult then close;
end;
end.
|
unit Model.ConsumoInsumos;
interface
type
TConsumoInsumos = class
private
var
FID: Integer;
FInsumo: Integer;
FPlaca: String;
FData: System.TDate;
FKmConsumo: Double;
FControle: Integer;
FConsumo: Double;
FValor: Double;
FEstoque: String;
FLog: String;
public
property ID: Integer read FID write FID;
property Insumo: Integer read FInsumo write FInsumo;
property Placa: String read FPlaca write FPlaca;
property Data: System.TDate read FData write FData;
property KMConsumo: Double read FKmConsumo write FKmConsumo;
property Controle: Integer read FControle write FControle;
property Consumo: Double read FConsumo write FConsumo;
property Valor: Double read FValor write FValor;
property Estoque: String read FEstoque write FEstoque;
property Log: String read FLog write FLog;
constructor Create; overload;
constructor Create(pFID: Integer; pFInsumo: Integer; pFPlaca: String; pFData: System.TDate;
pFKmConsumo: Double; pFControle: Integer; pFConsumo: Double; pFValor: Double; pFEstoque: String;
pFLog: String); overload;
end;
implementation
constructor TConsumoInsumos.Create;
begin
inherited Create;
end;
constructor TConsumoInsumos.Create(pFID: Integer; pFInsumo: Integer; pFPlaca: String; pFData: System.TDate;
pFKmConsumo: Double; pFControle: Integer; pFConsumo: Double; pFValor: Double; pFEstoque: String;
pFLog: String);
begin
FID := pFID;
FInsumo := pFInsumo;
FPlaca := pFPlaca;
FData := pFData;
FKmConsumo := pFKmConsumo;
FControle := pFControle;
FConsumo := pFConsumo;
FValor := pFValor;
FEstoque := pFEStoque;
FLog := pFLog;
end;
end.
|
{*************************************************************************}
{ TTodoList component }
{ for Delphi & C++Builder }
{ version 1.2 - rel. February 2005 }
{ }
{ written by TMS Software }
{ copyright © 2001 - 2005 }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{*************************************************************************}
unit TodoListReg;
{$I TMSDEFS.INC}
interface
uses
Classes, TodoList;
{$IFDEF TMSDOTNET}
{$R TTodoList.bmp}
{$ENDIF}
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('TMS Planner', [TTodoList]);
end;
end.
|
unit evDelayedPaintersSpy;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Автор: Инишев Д.А.
// Модуль: "w:/common/components/gui/Garant/Everest/evDelayedPaintersSpy.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::ParaList Painters::TevDelayedPaintersSpy
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
uses
l3Filer,
l3LongintList,
evSelectedParts,
l3ProtoObject
;
type
IevDelayedPainterLogger = interface(IUnknown)
['{87EBBF2A-E6CC-41AF-A26B-012D8BB879CB}']
function OpenSelectionLog: AnsiString;
procedure CloseSelectionLog(const aLogName: AnsiString);
end;//IevDelayedPainterLogger
TevDelayedPaintersSpy = class(Tl3ProtoObject)
private
// private fields
f_Logger : IevDelayedPainterLogger;
f_Filer : Tl3CustomFiler;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
// public methods
procedure SetLogger(const aLogger: IevDelayedPainterLogger);
procedure RemoveLogger(const aLogger: IevDelayedPainterLogger);
class function Exists: Boolean;
procedure LogSelections(const aSelParts: TevSelectedParts;
const aRowHeights: Tl3LongintList);
public
// singleton factory method
class function Instance: TevDelayedPaintersSpy;
{- возвращает экземпляр синглетона. }
end;//TevDelayedPaintersSpy
implementation
uses
l3Base {a},
SysUtils,
l3Types
;
// start class TevDelayedPaintersSpy
var g_TevDelayedPaintersSpy : TevDelayedPaintersSpy = nil;
procedure TevDelayedPaintersSpyFree;
begin
l3Free(g_TevDelayedPaintersSpy);
end;
class function TevDelayedPaintersSpy.Instance: TevDelayedPaintersSpy;
begin
if (g_TevDelayedPaintersSpy = nil) then
begin
l3System.AddExitProc(TevDelayedPaintersSpyFree);
g_TevDelayedPaintersSpy := Create;
end;
Result := g_TevDelayedPaintersSpy;
end;
procedure TevDelayedPaintersSpy.SetLogger(const aLogger: IevDelayedPainterLogger);
//#UC START# *4D6F41880325_4D6F3F42007C_var*
//#UC END# *4D6F41880325_4D6F3F42007C_var*
begin
//#UC START# *4D6F41880325_4D6F3F42007C_impl*
Assert(f_Logger = nil);
f_Logger := aLogger;
//#UC END# *4D6F41880325_4D6F3F42007C_impl*
end;//TevDelayedPaintersSpy.SetLogger
procedure TevDelayedPaintersSpy.RemoveLogger(const aLogger: IevDelayedPainterLogger);
//#UC START# *4D6F43CA0257_4D6F3F42007C_var*
//#UC END# *4D6F43CA0257_4D6F3F42007C_var*
begin
//#UC START# *4D6F43CA0257_4D6F3F42007C_impl*
Assert(f_Logger = aLogger);
f_Logger := nil;
//#UC END# *4D6F43CA0257_4D6F3F42007C_impl*
end;//TevDelayedPaintersSpy.RemoveLogger
class function TevDelayedPaintersSpy.Exists: Boolean;
//#UC START# *4D6F440500EE_4D6F3F42007C_var*
//#UC END# *4D6F440500EE_4D6F3F42007C_var*
begin
//#UC START# *4D6F440500EE_4D6F3F42007C_impl*
Result := g_TevDelayedPaintersSpy <> nil;
//#UC END# *4D6F440500EE_4D6F3F42007C_impl*
end;//TevDelayedPaintersSpy.Exists
procedure TevDelayedPaintersSpy.LogSelections(const aSelParts: TevSelectedParts;
const aRowHeights: Tl3LongintList);
//#UC START# *4D6F4C1700DC_4D6F3F42007C_var*
function LogSelPart(const Data: TevSelectedPart; Index: Integer): Boolean;
var
l_SelPart: TevSelectedPart;
begin
Result := True;
f_Filer.WriteLn('-------------------');
with Data do
begin
f_Filer.WriteLn(Format('"Row Height" : %d', [aRowHeights[rRowIndex]]));
f_Filer.WriteLn(Format('"Width" : %d', [rWidth]));
f_Filer.WriteLn(Format('"WindowOrg" : %d, %d', [rWindowOrg.X, rWindowOrg.Y]));
end; // with l_SelPart do
end;
var
l_LogName : String;
//#UC END# *4D6F4C1700DC_4D6F3F42007C_var*
begin
//#UC START# *4D6F4C1700DC_4D6F3F42007C_impl*
if (f_Logger <> nil) then
begin
l_LogName := f_Logger.OpenSelectionLog;
try
f_Filer := Tl3CustomDOSFiler.Make(l_LogName, l3_fmWrite);
try
f_Filer.Open;
try
f_Filer.WriteLn('-------------------');
f_Filer.WriteLn('Данные о выделении:');
aSelParts.IterateAllF(l3L2IA(@LogSelPart));
finally
f_Filer.Close;
end;//try..finally
finally
FreeAndNil(f_Filer);
end;//try..finally
finally
f_Logger.CloseSelectionLog(l_LogName);
end;//try..finally
end;//f_Logger <> nil
//#UC END# *4D6F4C1700DC_4D6F3F42007C_impl*
end;//TevDelayedPaintersSpy.LogSelections
procedure TevDelayedPaintersSpy.Cleanup;
//#UC START# *479731C50290_4D6F3F42007C_var*
//#UC END# *479731C50290_4D6F3F42007C_var*
begin
//#UC START# *479731C50290_4D6F3F42007C_impl*
FreeAndNil(f_Filer);
inherited Cleanup;
//#UC END# *479731C50290_4D6F3F42007C_impl*
end;//TevDelayedPaintersSpy.Cleanup
procedure TevDelayedPaintersSpy.ClearFields;
{-}
begin
f_Logger := nil;
inherited;
end;//TevDelayedPaintersSpy.ClearFields
end. |
{********************************************************************
TSECTIONLISTBOX design time property editor
for Delphi & C++Builder
Copyright © 1998-2012
TMS Software
Email : info@tmssoftware.com
Web : http://www.tmssoftware.com
The source code is given as is. The author is not responsible
for any possible damage done due to the use of this code.
The component can be freely used in any application. The complete
source code remains property of the author and may not be distributed,
published, given or sold in any form as such. No parts of the source
code can be included in any other component or application without
written authorization of the author.
********************************************************************}
unit slstde;
interface
{$I TMSDEFS.INC}
uses
SlstBox,
{$IFDEF DELPHI6_LVL}
DesignIntf, DesignEditors
{$ELSE}
DsgnIntf
{$ENDIF}
;
type
{---------------------------------------------------}
{ Section property editor class : not used yet }
{---------------------------------------------------}
TSectionListBoxEditor = class(TDefaultEditor)
protected
{$IFNDEF DELPHI6_LVL}
procedure EditProperty(PropertyEditor: TPropertyEditor;
var Continue, FreeEditor: Boolean); override;
{$ELSE}
procedure EditProperty(const PropertyEditor: IProperty; var Continue: Boolean); override;
{$ENDIF}
public
function GetVerb(index:integer):string; override;
function GetVerbCount:integer; override;
procedure ExecuteVerb(Index:integer); override;
end;
implementation
uses
sysutils,dialogs;
procedure TSectionListBoxEditor.ExecuteVerb(Index: integer);
var
compiler:string;
begin
case Index of
0: Edit;
1: (Component as TSectionListBox).ExpandAll;
2: (Component as TSectionListBox).ContractAll;
3: begin
{$IFDEF VER90}
compiler:='Delphi 2';
{$ENDIF}
{$IFDEF VER93}
compiler:='C++Builder 1';
{$ENDIF}
{$IFDEF VER100}
compiler:='Delphi 3';
{$ENDIF}
{$IFDEF VER110}
compiler:='C++Builder 3';
{$ENDIF}
{$IFDEF VER120}
compiler:='Delphi 4';
{$ENDIF}
{$IFDEF VER125}
compiler:='C++Builder 4';
{$ENDIF}
{$IFDEF VER130}
{$IFDEF BCB}
compiler:='C++Builder 5';
{$ELSE}
compiler:='Delphi 5';
{$ENDIF}
{$ENDIF}
{$IFDEF VER140}
compiler:='Delphi 6';
{$ENDIF}
messagedlg(component.className+' version 1.8 for '+compiler+#13#10#13#10'© 1999-2000 by TMS software'#13#10'http://www.tmssoftware.com',
mtinformation,[mbok],0);
end;
end;
end;
{$IFDEF DELPHI6_LVL}
procedure TSectionListBoxEditor.EditProperty(const PropertyEditor: IProperty; var Continue: Boolean);
{$ELSE}
procedure TSectionListBoxEditor.EditProperty(PropertyEditor: TPropertyEditor;
var Continue, FreeEditor: Boolean);
{$ENDIF}
var
PropName: string;
begin
PropName := PropertyEditor.GetName;
if (CompareText(PropName, 'SECTIONS') = 0) then
begin
PropertyEditor.Edit;
Continue := False;
end;
end;
function TSectionListBoxEditor.GetVerb(index: integer): string;
begin
result:='';
case index of
0:result:='Section Editor';
1:result:='Expand all';
2:result:='Contract all';
3:result:='About';
end;
end;
function TSectionListBoxEditor.GetVerbCount: integer;
begin
result:=4;
end;
end.
|
unit DW.ThreadedTCPClient;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
// THIS IS A WORK IN PROGRESS - Apologies for the lack of documentation - coming soon
interface
uses
// RTL
System.Classes, System.SysUtils, System.SyncObjs, System.Generics.Collections,
// Indy
IdTCPClient;
type
// Based partly on: https://forums.embarcadero.com/message.jspa?messageID=773729&tstart=0
// PROBLEM!!!! This code can be Windows-only because of WaitForMultiple - check http://seanbdurkin.id.au/pascaliburnus2/archives/230
TErrorEvent = procedure(Sender: TObject; const ErrorMsg: string) of object;
TExceptionEvent = procedure(Sender: TObject; const E: Exception) of object;
TResponseEvent = procedure(Sender: TObject; const Code: Integer; const Response: string) of object;
TReceiveDataEvent = procedure(Sender: TObject; const Data: TBytes) of object;
TCmdEvent = procedure(Sender: TObject; const Cmd: string) of object;
TClientState = (None, Connecting, Disconnecting, Sending, Receiving, ConnectError);
TSendQueue = class(TThreadList<string>)
protected
function Count: Integer;
procedure Push(const ACmd: string);
function Pop: string;
end;
TCustomThreadedTCPClient = class(TThread)
private
FClientState: TClientState;
FConnectEvent: TEvent;
FDisconnectEvent: TEvent;
FEvents: THandleObjectArray;
FIsConnected: Boolean;
FIsSynchronized: Boolean;
FSendQueue: TSendQueue;
FTCPClient: TIdTCPClient;
FOnConnected: TNotifyEvent;
FOnDisconnected: TNotifyEvent;
FOnException: TExceptionEvent;
FOnReceiveData: TReceiveDataEvent;
FOnResponse: TResponseEvent;
FOnSendingCmd: TCmdEvent;
procedure ConnectClient;
procedure DisconnectClient;
procedure DoConnected;
procedure DoDisconnected;
procedure DoException(const AException: Exception);
procedure DoReceiveData(const AData: TBytes);
procedure DoResponse(const ACode: Integer; const AResponse: string);
procedure DoSendingCommand(const ACmd: string);
function GetConnectTimeout: Integer;
function GetHost: string;
function GetIsConnected: Boolean;
function GetPort: Integer;
function GetReadTimeout: Integer;
procedure HandleException(const AException: Exception);
function InternalConnect: Boolean;
procedure InternalDisconnect;
procedure InternalSendCmd;
function IsMainThread: Boolean;
procedure ReadData;
procedure ReadDataFromBuffer;
procedure SendCmdFromClient(const ACmd: string);
procedure SetConnectTimeout(const Value: Integer);
procedure SetPort(const Value: Integer);
procedure SetReadTimeout(const Value: Integer);
procedure SetHost(const Value: string);
procedure TCPClientConnectedHandler(Sender: TObject);
procedure TCPClientDisconnectedHandler(Sender: TObject);
protected
procedure Execute; override;
procedure InternalDoConnected; virtual;
procedure InternalDoDisconnected; virtual;
procedure InternalDoException(const AException: Exception); virtual;
procedure InternalDoReceiveData(const AData: TBytes); virtual;
procedure InternalDoResponse(const ACode: Integer; const AResponse: string); virtual;
procedure InternalDoSendingCmd(const ACmd: string); virtual;
property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
property OnDisconnected: TNotifyEvent read FOnDisconnected write FOnDisconnected;
property OnException: TExceptionEvent read FOnException write FOnException;
property OnReceiveData: TReceiveDataEvent read FOnReceiveData write FOnReceiveData;
property OnResponse: TResponseEvent read FOnResponse write FOnResponse;
property OnSendingCmd: TCmdEvent read FOnSendingCmd write FOnSendingCmd;
public
constructor Create;
destructor Destroy; override;
function CanConnect: Boolean;
procedure Connect;
procedure Disconnect;
procedure SendCmd(const ACmd: string); virtual;
property ClientState: TClientState read FClientState;
property ConnectTimeout: Integer read GetConnectTimeout write SetConnectTimeout;
property Host: string read GetHost write SetHost;
property IsConnected: Boolean read GetIsConnected;
property IsSynchronized: Boolean read FIsSynchronized write FIsSynchronized;
property Port: Integer read GetPort write SetPort;
property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout;
end;
TThreadedTCPClient = class(TCustomThreadedTCPClient)
public
property OnConnected;
property OnDisconnected;
property OnException;
property OnReceiveData;
property OnResponse;
property OnSendingCmd;
end;
implementation
uses
// Indy
IdGlobal, IdExceptionCore,
// DW
DW.OSLog;
{ TSendQueue }
function TSendQueue.Count: Integer;
var
LList: TList<string>;
begin
LList := LockList;
try
Result := LList.Count;
finally
UnlockList;
end;
end;
function TSendQueue.Pop: string;
var
LList: TList<string>;
begin
LList := LockList;
try
Result := LList[0];
LList.Delete(0);
finally
UnlockList;
end;
end;
procedure TSendQueue.Push(const ACmd: string);
var
LList: TList<string>;
begin
LList := LockList;
try
LList.Add(ACmd);
finally
UnlockList;
end;
end;
{ TCustomThreadedTCPClient }
constructor TCustomThreadedTCPClient.Create;
begin
inherited Create;
// FIsSynchronized := True;
FSendQueue := TSendQueue.Create;
FTCPClient := TIdTCPClient.Create(nil);
FTCPClient.ConnectTimeout := 5000;
FTCPClient.ReadTimeout := 5000;
FTCPClient.OnConnected := TCPClientConnectedHandler;
FTCPClient.OnDisconnected := TCPClientDisconnectedHandler;
FConnectEvent := TEvent.Create(nil, True, False, '');
FDisconnectEvent := TEvent.Create(nil, True, False, '');
FEvents := [FConnectEvent, FDisconnectEvent];
end;
destructor TCustomThreadedTCPClient.Destroy;
begin
FConnectEvent.Free;
FDisconnectEvent.Free;
FTCPClient.Free;
FSendQueue.Free;
inherited;
end;
function TCustomThreadedTCPClient.GetConnectTimeout: Integer;
begin
Result := FTCPClient.ConnectTimeout;
end;
function TCustomThreadedTCPClient.GetHost: string;
begin
Result := FTCPClient.Host;
end;
function TCustomThreadedTCPClient.GetIsConnected: Boolean;
begin
Result := FIsConnected;
end;
function TCustomThreadedTCPClient.GetPort: Integer;
begin
Result := FTCPClient.Port;
end;
function TCustomThreadedTCPClient.GetReadTimeout: Integer;
begin
Result := FTCPClient.ReadTimeout;
end;
procedure TCustomThreadedTCPClient.SetConnectTimeout(const Value: Integer);
begin
FTCPClient.ConnectTimeout := Value;
end;
procedure TCustomThreadedTCPClient.SetHost(const Value: string);
begin
FTCPClient.Host := Value;
end;
procedure TCustomThreadedTCPClient.SetPort(const Value: Integer);
begin
FTCPClient.Port := Value;
end;
procedure TCustomThreadedTCPClient.SetReadTimeout(const Value: Integer);
begin
FTCPClient.ReadTimeout := Value;
end;
function TCustomThreadedTCPClient.IsMainThread: Boolean;
begin
Result := TThread.CurrentThread.ThreadID = MainThreadID;
end;
procedure TCustomThreadedTCPClient.TCPClientConnectedHandler(Sender: TObject);
begin
FIsConnected := True;
DoConnected;
end;
procedure TCustomThreadedTCPClient.TCPClientDisconnectedHandler(Sender: TObject);
begin
TOSLog.d('TCustomThreadedTCPClient.TCPClientDisconnectedHandler');
DoDisconnected;
end;
function TCustomThreadedTCPClient.InternalConnect: Boolean;
begin
FConnectEvent.ResetEvent;
Result := FIsConnected;
if not Result then
begin
FClientState := TClientState.Connecting;
try
ConnectClient;
Result := FIsConnected;
finally
FClientState := TClientState.None;
end;
end;
end;
procedure TCustomThreadedTCPClient.DoConnected;
begin
if FIsSynchronized and not IsMainThread then
Synchronize(InternalDoConnected)
else
InternalDoConnected;
end;
procedure TCustomThreadedTCPClient.InternalDoConnected;
begin
if Assigned(FOnConnected) then
FOnConnected(Self);
end;
procedure TCustomThreadedTCPClient.ConnectClient;
begin
try
FTCPClient.Connect;
except
on E: Exception do
HandleException(E);
end;
end;
procedure TCustomThreadedTCPClient.InternalDisconnect;
begin
FDisconnectEvent.ResetEvent;
FClientState := TClientState.Disconnecting;
try
DisconnectClient;
finally
FClientState := TClientState.None;
end;
end;
procedure TCustomThreadedTCPClient.DisconnectClient;
begin
try
FTCPClient.Disconnect;
except
on E: Exception do
HandleException(E);
end;
end;
procedure TCustomThreadedTCPClient.DoDisconnected;
begin
FIsConnected := False;
if FIsSynchronized and not IsMainThread then
Synchronize(InternalDoDisconnected)
else
InternalDoDisconnected;
end;
procedure TCustomThreadedTCPClient.InternalDoDisconnected;
begin
if Assigned(FOnDisconnected) then
FOnDisconnected(Self);
end;
procedure TCustomThreadedTCPClient.InternalSendCmd;
var
LCmd: string;
begin
LCmd := FSendQueue.Pop;
if InternalConnect then
begin
FClientState := TClientState.Sending;
try
SendCmdFromClient(LCmd);
finally
FClientState := TClientState.None;
end;
end;
end;
procedure TCustomThreadedTCPClient.SendCmdFromClient(const ACmd: string);
begin
try
DoSendingCommand(ACmd);
except
on E: Exception do
HandleException(E);
end;
try
FTCPClient.SendCmd(ACmd);
if not Terminated then
DoResponse(FTCPClient.LastCmdResult.NumericCode, FTCPClient.LastCmdResult.Text.Text);
except
on E: Exception do
HandleException(E);
end;
end;
procedure TCustomThreadedTCPClient.ReadData;
begin
if FTCPClient.IOHandler <> nil then
begin
if not FTCPClient.IOHandler.ClosedGracefully then
begin
try
ReadDataFromBuffer;
except
on E: Exception do
HandleException(E);
end;
end
else
DoDisconnected;
end;
end;
procedure TCustomThreadedTCPClient.ReadDataFromBuffer;
var
LData: TBytes;
begin
if FTCPClient.IOHandler.CheckForDataOnSource(10) then
begin
// TOSLog.d('TCustomThreadedTCPClient.ReadDataFromBuffer - has data');
FClientState := TClientState.Receiving;
try
FTCPClient.IOHandler.InputBuffer.ExtractToBytes(TIdBytes(LData));
finally
FClientState := TClientState.None;
end;
if not Terminated and (Length(LData) > 0) then
DoReceiveData(LData)
else if not Terminated then
TOSLog.d('TCustomThreadedTCPClient.ReadDataFromBuffer - had data, but nothing there!');
end;
end;
procedure TCustomThreadedTCPClient.HandleException(const AException: Exception);
begin
TOSLog.d('TCustomThreadedTCPClient.HandleException: %s - %s', [AException.ClassName, AException.Message]);
if AException.InheritsFrom(EIdSocksServerConnectionRefusedError) then
FClientState := TClientState.ConnectError;
DoException(AException);
end;
procedure TCustomThreadedTCPClient.DoException(const AException: Exception);
begin
if FIsSynchronized and not IsMainThread then
begin
Synchronize(
procedure
begin
InternalDoException(AException);
end
);
end
else
InternalDoException(AException);
end;
procedure TCustomThreadedTCPClient.InternalDoException(const AException: Exception);
begin
if Assigned(FOnException) then
FOnException(Self, AException);
end;
procedure TCustomThreadedTCPClient.DoResponse(const ACode: Integer; const AResponse: string);
begin
if FIsSynchronized and not IsMainThread then
begin
Synchronize(
procedure
begin
InternalDoResponse(ACode, AResponse);
end
);
end
else
InternalDoResponse(ACode, AResponse);
end;
procedure TCustomThreadedTCPClient.DoSendingCommand(const ACmd: string);
begin
if FIsSynchronized and not IsMainThread then
begin
Synchronize(
procedure
begin
InternalDoSendingCmd(ACmd);
end
);
end
else
InternalDoSendingCmd(ACmd);
end;
procedure TCustomThreadedTCPClient.InternalDoResponse(const ACode: Integer; const AResponse: string);
begin
if Assigned(FOnResponse) then
FOnResponse(Self, ACode, AResponse);
end;
procedure TCustomThreadedTCPClient.InternalDoSendingCmd(const ACmd: string);
begin
if Assigned(FOnSendingCmd) then
FOnSendingCmd(Self, ACmd);
end;
procedure TCustomThreadedTCPClient.DoReceiveData(const AData: TBytes);
begin
if FIsSynchronized and not IsMainThread then
Synchronize(
procedure
begin
InternalDoReceiveData(AData)
end
)
else
InternalDoReceiveData(AData);
end;
procedure TCustomThreadedTCPClient.InternalDoReceiveData(const AData: TBytes);
begin
if Assigned(FOnReceiveData) then
FOnReceiveData(Self, AData);
end;
procedure TCustomThreadedTCPClient.Execute;
var
LSignaledEvent: THandleObject;
begin
while not Terminated do
begin
LSignaledEvent := nil;
TEvent.WaitForMultiple(FEvents, 20, False, LSignaledEvent);
if LSignaledEvent = FDisconnectEvent then
InternalDisconnect
else if LSignaledEvent = FConnectEvent then
InternalConnect
else if not Terminated then
begin
if FIsConnected then
ReadData;
if FSendQueue.Count > 0 then
InternalSendCmd;
end;
end;
end;
function TCustomThreadedTCPClient.CanConnect: Boolean;
begin
Result := not Host.IsEmpty and (Port > 0);
end;
procedure TCustomThreadedTCPClient.Connect;
begin
FConnectEvent.SetEvent;
end;
procedure TCustomThreadedTCPClient.Disconnect;
begin
FDisconnectEvent.SetEvent;
end;
procedure TCustomThreadedTCPClient.SendCmd(const ACmd: string);
begin
FSendQueue.Push(ACmd);
end;
end.
|
{
File: AEHelpers.p
Contains: AEPrint, AEBuild and AEStream for Carbon
Version: Technology: Mac OS X, CarbonLib
Release: Universal Interfaces 3.4.2
Copyright: © 1999-2002 by Apple Computer, Inc., all rights reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://www.freepascal.org/bugs.html
}
{
* Originally from AEGIzmos by Jens Alfke, circa 1992.
}
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit AEHelpers;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,AppleEvents,AEDataModel;
{$ALIGN MAC68K}
{
* AEBuild is only available for C programmers.
}
{
* AEPrintDescToHandle
*
* AEPrintDescToHandle provides a way to turn an AEDesc into a textual
* representation. This is most useful for debugging calls to
* AEBuildDesc and friends. The Handle returned should be disposed by
* the caller. The size of the handle is the actual number of
* characters in the string.
}
{
* AEPrintDescToHandle()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEPrintDescToHandle(const (*var*) desc: AEDesc; var result: Handle): OSStatus; external name '_AEPrintDescToHandle';
{
* AEStream:
*
* The AEStream interface allows you to build AppleEvents by appending
* to an opaque structure (an AEStreamRef) and then turning this
* structure into an AppleEvent. The basic idea is to open the
* stream, write data, and then close it - closing it produces an
* AEDesc, which may be partially complete, or may be a complete
* AppleEvent.
}
type
AEStreamRef = ^SInt32; { an opaque 32-bit type }
AEStreamRefPtr = ^AEStreamRef; { when a var xx:AEStreamRef parameter can be nil, it is changed to xx: AEStreamRefPtr }
{
Create and return an AEStreamRef
Returns NULL on memory allocation failure
}
{
* AEStreamOpen()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOpen: AEStreamRef; external name '_AEStreamOpen';
{
Closes and disposes of an AEStreamRef, producing
results in the desc. You must dispose of the desc yourself.
If you just want to dispose of the AEStreamRef, you can pass NULL for desc.
}
{
* AEStreamClose()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamClose(ref: AEStreamRef; var desc: AEDesc): OSStatus; external name '_AEStreamClose';
{
Prepares an AEStreamRef for appending data to a newly created desc.
You append data with AEStreamWriteData
}
{
* AEStreamOpenDesc()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOpenDesc(ref: AEStreamRef; newType: DescType): OSStatus; external name '_AEStreamOpenDesc';
{ Append data to the previously opened desc. }
{
* AEStreamWriteData()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamWriteData(ref: AEStreamRef; data: UnivPtr; length: Size): OSStatus; external name '_AEStreamWriteData';
{
Finish a desc. After this, you can close the stream, or adding new
descs, if you're assembling a list.
}
{
* AEStreamCloseDesc()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamCloseDesc(ref: AEStreamRef): OSStatus; external name '_AEStreamCloseDesc';
{ Write data as a desc to the stream }
{
* AEStreamWriteDesc()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamWriteDesc(ref: AEStreamRef; newType: DescType; data: UnivPtr; length: Size): OSStatus; external name '_AEStreamWriteDesc';
{ Write an entire desc to the stream }
{
* AEStreamWriteAEDesc()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamWriteAEDesc(ref: AEStreamRef; const (*var*) desc: AEDesc): OSStatus; external name '_AEStreamWriteAEDesc';
{
Begin a list. You can then append to the list by doing
AEStreamOpenDesc, or AEStreamWriteDesc.
}
{
* AEStreamOpenList()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOpenList(ref: AEStreamRef): OSStatus; external name '_AEStreamOpenList';
{ Finish a list. }
{
* AEStreamCloseList()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamCloseList(ref: AEStreamRef): OSStatus; external name '_AEStreamCloseList';
{
Begin a record. A record usually has type 'reco', however, this is
rather generic, and frequently a different type is used.
}
{
* AEStreamOpenRecord()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOpenRecord(ref: AEStreamRef; newType: DescType): OSStatus; external name '_AEStreamOpenRecord';
{ Change the type of a record. }
{
* AEStreamSetRecordType()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamSetRecordType(ref: AEStreamRef; newType: DescType): OSStatus; external name '_AEStreamSetRecordType';
{ Finish a record }
{
* AEStreamCloseRecord()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamCloseRecord(ref: AEStreamRef): OSStatus; external name '_AEStreamCloseRecord';
{
Add a keyed descriptor to a record. This is analogous to AEPutParamDesc.
it can only be used when writing to a record.
}
{
* AEStreamWriteKeyDesc()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamWriteKeyDesc(ref: AEStreamRef; key: AEKeyword; newType: DescType; data: UnivPtr; length: Size): OSStatus; external name '_AEStreamWriteKeyDesc';
{
OpenDesc for a keyed record entry. You can youse AEStreamWriteData
after opening a keyed desc.
}
{
* AEStreamOpenKeyDesc()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOpenKeyDesc(ref: AEStreamRef; key: AEKeyword; newType: DescType): OSStatus; external name '_AEStreamOpenKeyDesc';
{ Write a key to the stream - you can follow this with an AEWriteDesc. }
{
* AEStreamWriteKey()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamWriteKey(ref: AEStreamRef; key: AEKeyword): OSStatus; external name '_AEStreamWriteKey';
{
Create a complete AppleEvent. This creates and returns a new stream.
Use this call to populate the meta fields in an AppleEvent record.
After this, you can add your records, lists and other parameters.
}
{
* AEStreamCreateEvent()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamCreateEvent(clazz: AEEventClass; id: AEEventID; targetType: DescType; targetData: UnivPtr; targetLength: SInt32; returnID: SInt16; transactionID: SInt32): AEStreamRef; external name '_AEStreamCreateEvent';
{
This call lets you augment an existing AppleEvent using the stream
APIs. This would be useful, for example, in constructing the reply
record in an AppleEvent handler. Note that AEStreamOpenEvent will
consume the AppleEvent passed in - you can't access it again until the
stream is closed. When you're done building the event, AEStreamCloseStream
will reconstitute it.
}
{
* AEStreamOpenEvent()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOpenEvent(var event: AppleEvent): AEStreamRef; external name '_AEStreamOpenEvent';
{ Mark a keyword as being an optional parameter. }
{
* AEStreamOptionalParam()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.1 and later
* Mac OS X: in version 10.0 and later
}
function AEStreamOptionalParam(ref: AEStreamRef; key: AEKeyword): OSStatus; external name '_AEStreamOptionalParam';
{$ALIGN MAC68K}
end.
|
unit UCrypto;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{ Copyright (c) 2016 by Albert Molina
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
This unit is a part of Pascal Coin, a P2P crypto currency without need of
historical operations.
If you like it, consider a donation using BitCoin:
16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk
}
{$I config.inc}
interface
uses
Classes, SysUtils, UOpenSSL, UOpenSSLdef, UECDSA_Public;
Type
TRawBytes = AnsiString;
PRawBytes = ^TRawBytes;
TECDSA_SIG = record
r: TRawBytes;
s: TRawBytes;
end; { record }
{ TCrypto }
TCrypto = Class
private
public
class function IsHexString(const AHexString: AnsiString) : boolean;
class function ToHexaString(const raw : TRawBytes) : AnsiString;
class function HexaToRaw(const HexaString : AnsiString) : TRawBytes; overload;
class function HexaToRaw(const HexaString : AnsiString; out raw : TRawBytes) : Boolean; overload;
class function DoSha256(p : PAnsiChar; plength : Cardinal) : TRawBytes; overload;
class function DoSha256(const TheMessage : AnsiString) : TRawBytes; overload;
class procedure DoSha256(const TheMessage : AnsiString; out ResultSha256 : TRawBytes); overload;
class function DoDoubleSha256(const TheMessage : AnsiString) : TRawBytes; overload;
class procedure DoDoubleSha256(p : PAnsiChar; plength : Cardinal; out ResultSha256 : TRawBytes); overload;
class function DoRipeMD160_HEXASTRING(const TheMessage : AnsiString) : TRawBytes; overload;
class function DoRipeMD160AsRaw(p : PAnsiChar; plength : Cardinal) : TRawBytes; overload;
class function DoRipeMD160AsRaw(const TheMessage : AnsiString) : TRawBytes; overload;
class function PrivateKey2Hexa(Key : PEC_KEY) : AnsiString;
class function ECDSASign(Key : PEC_KEY; const digest : AnsiString) : TECDSA_SIG;
class function ECDSAVerify(EC_OpenSSL_NID : Word; PubKey : EC_POINT; const digest : AnsiString; Signature : TECDSA_SIG) : Boolean; overload;
class function ECDSAVerify(PubKey : TECDSA_Public; const digest : AnsiString; Signature : TECDSA_SIG) : Boolean; overload;
class procedure InitCrypto;
class function IsHumanReadable(Const ReadableText : TRawBytes) : Boolean;
class function EncodeSignature(const signature : TECDSA_SIG) : TRawBytes;
class function DecodeSignature(const rawSignature : TRawBytes; out signature : TECDSA_SIG) : Boolean;
End;
var
CT_TECDSA_SIG_Nul : TECDSA_SIG;
implementation
uses
ULog, UConst, UStreamOp, UPtrInt, UCryptoException; // UAccounts, UStreamOp;
Var _initialized : Boolean = false;
Procedure _DoInit;
var err : String;
c : Cardinal;
Begin
if Not (_initialized) then begin
_initialized := true;
If Not InitSSLFunctions then begin
err := 'Cannot load OpenSSL library '+SSL_C_LIB;
TLog.NewLog(ltError,'OpenSSL',err);
Raise Exception.Create(err);
end;
If Not Assigned(OpenSSL_version_num) then begin
err := 'OpenSSL library is not v1.1 version: '+SSL_C_LIB;
TLog.NewLog(ltError,'OpenSSL',err);
Raise Exception.Create(err);
end;
c := OpenSSL_version_num;
if (c<$10100000) Or (c>$1010FFFF) then begin
err := 'OpenSSL library is not v1.1 version ('+IntToHex(c,8)+'): '+SSL_C_LIB;
TLog.NewLog(ltError,'OpenSSL',err);
Raise Exception.Create(err);
end;
end;
End;
{ TCrypto }
{ New at Build 1.0.2
Note: Delphi is slowly when working with Strings (allowing space)... so to
increase speed we use a String as a pointer, and only increase speed if
needed. Also the same with functions "GetMem" and "FreeMem" }
class procedure TCrypto.DoDoubleSha256(p: PAnsiChar; plength: Cardinal; out ResultSha256: TRawBytes);
Var PS : PAnsiChar;
begin
If length(ResultSha256)<>32 then SetLength(ResultSha256,32);
PS := @ResultSha256[1];
SHA256(p,plength,PS);
SHA256(PS,32,PS);
end;
class function TCrypto.DoDoubleSha256(const TheMessage: AnsiString): TRawBytes;
begin
Result := DoSha256(DoSha256(TheMessage));
end;
class function TCrypto.DoRipeMD160_HEXASTRING(const TheMessage: AnsiString): TRawBytes;
Var PS : PAnsiChar;
PC : PAnsiChar;
i : Integer;
begin
GetMem(PS,33);
RIPEMD160(PAnsiChar(TheMessage),Length(TheMessage),PS);
PC := PS;
Result := '';
for I := 1 to 20 do begin
Result := Result + IntToHex(PtrInt(PC^),2);
inc(PC);
end;
FreeMem(PS,33);
end;
class function TCrypto.DoRipeMD160AsRaw(p: PAnsiChar; plength: Cardinal): TRawBytes;
Var PS : PAnsiChar;
begin
SetLength(Result,20);
PS := @Result[1];
RIPEMD160(p,plength,PS);
end;
class function TCrypto.DoRipeMD160AsRaw(const TheMessage: AnsiString): TRawBytes;
Var PS : PAnsiChar;
begin
SetLength(Result,20);
PS := @Result[1];
RIPEMD160(PAnsiChar(TheMessage),Length(TheMessage),PS);
end;
class function TCrypto.DoSha256(p: PAnsiChar; plength: Cardinal): TRawBytes;
Var PS : PAnsiChar;
begin
SetLength(Result,32);
PS := @Result[1];
SHA256(p,plength,PS);
end;
class function TCrypto.DoSha256(const TheMessage: AnsiString): TRawBytes;
Var PS : PAnsiChar;
begin
SetLength(Result,32);
PS := @Result[1];
SHA256(PAnsiChar(TheMessage),Length(TheMessage),PS);
end;
{ New at Build 2.1.6
Note: Delphi is slowly when working with Strings (allowing space)... so to
increase speed we use a String as a pointer, and only increase speed if
needed. Also the same with functions "GetMem" and "FreeMem" }
class procedure TCrypto.DoSha256(const TheMessage: AnsiString; out ResultSha256: TRawBytes);
Var PS : PAnsiChar;
begin
If length(ResultSha256)<>32 then SetLength(ResultSha256,32);
PS := @ResultSha256[1];
SHA256(PAnsiChar(TheMessage),Length(TheMessage),PS);
end;
class function TCrypto.ECDSASign(Key: PEC_KEY; const digest: AnsiString): TECDSA_SIG;
Var PECS : PECDSA_SIG;
p : PAnsiChar;
i : Integer;
begin
PECS := ECDSA_do_sign(PAnsiChar(digest),length(digest),Key);
Try
if PECS = Nil then raise ECryptoException.Create('Error signing');
i := BN_num_bytes(PECS^._r);
SetLength(Result.r,i);
p := @Result.r[1];
i := BN_bn2bin(PECS^._r,p);
i := BN_num_bytes(PECS^._s);
SetLength(Result.s,i);
p := @Result.s[1];
i := BN_bn2bin(PECS^._s,p);
Finally
ECDSA_SIG_free(PECS);
End;
end;
class function TCrypto.ECDSAVerify(EC_OpenSSL_NID : Word; PubKey: EC_POINT; const digest: AnsiString; Signature: TECDSA_SIG): Boolean;
Var PECS : PECDSA_SIG;
PK : PEC_KEY;
{$IFDEF OpenSSL10}
{$ELSE}
bnr,bns : PBIGNUM;
{$ENDIF}
begin
PECS := ECDSA_SIG_new;
Try
{$IFDEF OpenSSL10}
BN_bin2bn(PAnsiChar(Signature.r),length(Signature.r),PECS^._r);
BN_bin2bn(PAnsiChar(Signature.s),length(Signature.s),PECS^._s);
{$ELSE}
{ ECDSA_SIG_get0(PECS,@bnr,@bns);
BN_bin2bn(PAnsiChar(Signature.r),length(Signature.r),bnr);
BN_bin2bn(PAnsiChar(Signature.s),length(Signature.s),bns);}
bnr := BN_bin2bn(PAnsiChar(Signature.r),length(Signature.r),nil);
bns := BN_bin2bn(PAnsiChar(Signature.s),length(Signature.s),nil);
if ECDSA_SIG_set0(PECS,bnr,bns)<>1 then Raise Exception.Create('Dev error 20161019-1 '+ERR_error_string(ERR_get_error(),nil));
{$ENDIF}
PK := EC_KEY_new_by_curve_name(EC_OpenSSL_NID);
EC_KEY_set_public_key(PK,@PubKey);
Case ECDSA_do_verify(PAnsiChar(digest),length(digest),PECS,PK) of
1 : Result := true;
0 : Result := false;
Else
raise ECryptoException.Create('Error on Verify');
End;
EC_KEY_free(PK);
Finally
ECDSA_SIG_free(PECS);
End;
end;
class function TCrypto.ECDSAVerify(PubKey: TECDSA_Public; const digest: AnsiString; Signature: TECDSA_SIG): Boolean;
Var BNx,BNy : PBIGNUM;
ECG : PEC_GROUP;
ctx : PBN_CTX;
pub_key : PEC_POINT;
begin
BNx := BN_bin2bn(PAnsiChar(PubKey.x),length(PubKey.x),nil);
BNy := BN_bin2bn(PAnsiChar(PubKey.y),length(PubKey.y),nil);
ECG := EC_GROUP_new_by_curve_name(PubKey.EC_OpenSSL_NID);
pub_key := EC_POINT_new(ECG);
ctx := BN_CTX_new;
if EC_POINT_set_affine_coordinates_GFp(ECG,pub_key,BNx,BNy,ctx)=1 then begin
Result := ECDSAVerify(PubKey.EC_OpenSSL_NID, pub_key^,digest,signature);
end else begin
Result := false;
end;
BN_CTX_free(ctx);
EC_POINT_free(pub_key);
EC_GROUP_free(ECG);
BN_free(BNx);
BN_free(BNy);
end;
class function TCrypto.HexaToRaw(const HexaString: AnsiString): TRawBytes;
Var P : PAnsiChar;
lc : AnsiString;
i : Integer;
begin
Result := '';
if ((length(HexaString) MOD 2)<>0) Or (length(HexaString)=0) then exit;
SetLength(result,length(HexaString) DIV 2);
P := @Result[1];
lc := LowerCase(HexaString);
i := HexToBin(PAnsiChar(@lc[1]),P,length(Result));
if (i<>(length(HexaString) DIV 2)) then begin
TLog.NewLog(lterror,Classname,'Invalid HEXADECIMAL string result '+inttostr(i)+'<>'+inttostr(length(HexaString) DIV 2)+': '+HexaString);
Result := '';
end;
end;
class function TCrypto.HexaToRaw(const HexaString: AnsiString; out raw: TRawBytes): Boolean;
Var P : PAnsiChar;
lc : AnsiString;
i : Integer;
begin
Result := False; raw := '';
if ((length(HexaString) MOD 2)<>0) then Exit;
if (length(HexaString)=0) then begin
Result := True;
exit;
end;
SetLength(raw,length(HexaString) DIV 2);
P := @raw[1];
lc := LowerCase(HexaString);
i := HexToBin(PAnsiChar(@lc[1]),P,length(raw));
Result := (i = (length(HexaString) DIV 2));
end;
class procedure TCrypto.InitCrypto;
begin
_DoInit;
end;
class function TCrypto.IsHumanReadable(const ReadableText: TRawBytes): Boolean;
Var i : Integer;
Begin
Result := true;
for i := 1 to length(ReadableText) do begin
if (ord(ReadableText[i])<32) Or (ord(ReadableText[i])>=255) then begin
Result := false;
Exit;
end;
end;
end;
class function TCrypto.EncodeSignature(const signature: TECDSA_SIG): TRawBytes;
Var ms : TStream;
begin
ms := TMemoryStream.Create;
Try
TStreamOp.WriteAnsiString(ms,signature.r);
TStreamOp.WriteAnsiString(ms,signature.s);
Result := TStreamOp.SaveStreamToRaw(ms);
finally
ms.Free;
end;
end;
class function TCrypto.DecodeSignature(const rawSignature : TRawBytes; out signature : TECDSA_SIG) : Boolean;
var ms : TStream;
begin
signature := CT_TECDSA_SIG_Nul;
Result := False;
ms := TMemoryStream.Create;
Try
TStreamOp.LoadStreamFromRaw(ms,rawSignature);
ms.Position:=0;
if TStreamOp.ReadAnsiString(ms,signature.r)<0 then Exit;
if TStreamOp.ReadAnsiString(ms,signature.s)<0 then Exit;
if ms.Position<ms.Size then Exit; // Invalid position
Result := True;
finally
ms.Free;
end;
end;
class function TCrypto.PrivateKey2Hexa(Key: PEC_KEY): AnsiString;
Var p : PAnsiChar;
begin
p := BN_bn2hex(EC_KEY_get0_private_key(Key));
// p := BN_bn2hex(Key^.priv_key);
Result := strpas(p);
OPENSSL_free(p);
end;
class function TCrypto.ToHexaString(const raw: TRawBytes): AnsiString;
Var i : Integer;
s : AnsiString;
b : Byte;
begin
SetLength(Result,length(raw)*2);
for i := 0 to length(raw)-1 do begin
b := Ord(raw[i+1]);
s := IntToHex(b,2);
Result[(i*2)+1] := s[1];
Result[(i*2)+2] := s[2];
end;
end;
class function TCrypto.IsHexString(const AHexString: AnsiString) : boolean;
var
i : Integer;
begin
Result := true;
for i := 1 to length(AHexString) do
if (NOT (AHexString[i] in ['0'..'9'])) AND
(NOT (AHexString[i] in ['a'..'f'])) AND
(NOT (AHexString[i] in ['A'..'F'])) then begin
Result := false;
exit;
end;
end;
initialization
Initialize(CT_TECDSA_SIG_Nul);
// Skybuck: On windows this basically means RandSeed is set to a value from high performance counter
Randomize; // Initial random generator based on system time
finalization
end.
|
unit GetOrderUnit;
interface
uses SysUtils, BaseExampleUnit, OrderUnit;
type
TGetOrder = class(TBaseExample)
public
procedure Execute(OrderId: integer);
end;
implementation
procedure TGetOrder.Execute(OrderId: integer);
var
ErrorString: String;
Order: TOrder;
begin
Order := Route4MeManager.Order.Get(OrderId, ErrorString);
try
WriteLn('');
if (ErrorString = EmptyStr) then
WriteLn('GetOrder executed successfully')
else
WriteLn(Format('GetOrder error: "%s"', [ErrorString]));
finally
FreeAndNil(Order);
end;
end;
end.
|
unit mod_winboard;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
StdCtrls, Forms, Controls,
chessmodules, chessgame, chessdrawer;
type
{ TWinboardChessModule }
TWinboardChessModule = class(TChessModule)
private
textEnginePatch : TStaticText;
editEnginePatch : TEdit;
public
constructor Create; override;
procedure CreateUserInterface(); override;
procedure ShowUserInterface(AParent: TWinControl); override;
procedure HideUserInterface(); override;
procedure FreeUserInterface(); override;
procedure PrepareForGame(); override;
function GetSecondPlayerName(): ansistring; override;
procedure HandleOnMove(AFrom, ATo: TPoint); override;
procedure HandleOnTimer(); override;
end;
implementation
uses winboardConn;
{ TSinglePlayerChessModule }
constructor TWinboardChessModule.Create;
begin
inherited Create;
SelectionDescription := 'Play against a winboard engine';
PlayingDescription := 'Play against a winboard engine';
Kind := cmkAgainstComputer;
end;
procedure TWinboardChessModule.CreateUserInterface;
begin
textEnginePatch := TStaticText.Create(nil);
textEnginePatch.SetBounds(20, 20, 180, 50);
textEnginePatch.Caption := 'Full patch to the engine';
editEnginePatch := TEdit.Create(nil);
editEnginePatch.SetBounds(200, 20, 150, 50);
editEnginePatch.Text := 'gnuchess';
end;
procedure TWinboardChessModule.ShowUserInterface(AParent: TWinControl);
begin
textEnginePatch.Parent := AParent;
editEnginePatch.Parent := AParent;
end;
procedure TWinboardChessModule.HideUserInterface();
begin
textEnginePatch.Parent := nil;
editEnginePatch.Parent := nil;
end;
procedure TWinboardChessModule.FreeUserInterface();
begin
textEnginePatch.Free;
editEnginePatch.Free;
end;
function TWinboardChessModule.GetSecondPlayerName(): ansistring;
begin
Result := editEnginePatch.text;
end;
procedure TWinboardChessModule.HandleOnMove(AFrom, ATo: TPoint);
var
moveStr : String;
begin
moveStr:=vwinboardConn.coordToString(AFrom,ATo,vChessGame.PreviousMove.PieceMoved,vChessGame.PreviousMove.PieceCaptured);
vwinboardConn.tellMove(moveStr);
end;
procedure TWinboardChessModule.HandleOnTimer;
var
CompMove: moveInCoord;
lAnimation: TChessMoveAnimation;
begin
CompMove:=vwinboardConn.engineMove;
if (CompMove <> nilCoord) then
begin
lAnimation := TChessMoveAnimation.Create;
lAnimation.AFrom := CompMove[1];
lAnimation.ATo := CompMove[2];
vChessDrawer.AddAnimation(lAnimation);
end;
end;
procedure TWinboardChessModule.PrepareForGame;
begin
vwinboardConn.startEngine(editEnginePatch.text);
if not vChessGame.FirstPlayerIsWhite then
begin
vwinboardConn.tellMove('go');
end;
end;
initialization
RegisterChessModule(TWinboardChessModule.Create);
finalization
vwinboardConn.stopEngine(True);
end.
|
unit np.HttpConnect;
interface
uses np.core, np.EventEmitter, np.httpParser, Generics.Collections, sysUtils,
np.buffer, np.url, np.OpenSSL, np.http_parser, np.common;
const
ev_BeforeProcess = 1;
ev_HeaderLoaded = 2;
// ev_ContentUpdated = 3;
ev_Complete = 4;
ev_connected = 5;
ev_disconnected = 6;
ev_error = 7;
ev_destroy = 8;
ev_connecting = 9;
type
THttpConnect = class;
TBaseHttpRequest = class(TEventEmitter)
private
lostConnectObjectHandler : IEventHandler;
req : TStringBuilder;
fCookieCount: integer;
isGet: Boolean;
isPending: Boolean;
isInQueue: Boolean;
isDone: Boolean;
//isPaused: Boolean;
initState: (isWantBeginHeader,isWantEndHeader,isWantCookieEnd, isRdy);
protected
public
request: BufferRef;
protocol: Utf8String;
statusCode: integer; //<0 internal reason
statusReason: Utf8string;
ResponseHeader: THTTPHeader;
ResponseContent: BufferRef;
connect: THttpConnect;
ConnectionOwner: Boolean;
ReqMethod : string;
ReqPath: string;
// CompleteReaction: TCompleteReaction;
procedure beginHeader(const method: string; const path: string; AkeepAlive:Boolean=true);
procedure addHeader(const name:string; const value: string);
procedure beginCookie;
procedure addCookie(const name:string; const value: string);
procedure endCookie;
procedure endHeader(const content: BufferRef; const contentType:string);overload;
procedure endHeader; overload;
procedure ClearResponse;
constructor Create(Aconnect: THttpConnect);
destructor Destroy; override;
procedure resume; //reuse request object again
procedure done; //request do not need anymore (default before ev_complete)
procedure autoDone;
end;
THttpConnect = class(TEventEmitter)
private
Fctx: TSSL_CTX;
FSSL : TSSL;
Fin_bio : TBIO;
Fout_bio: TBIO;
Fis_init_finished: integer;
FSSLData : TBytes;
FData : BufferRef;
queue: TQueue<TBaseHttpRequest>;
con : INPTCPConnect;
Isshutdown: Boolean;
IsConnected: Boolean;
isHandshake: Boolean;
onTimeout: INPTimer;
Fsettings : Thttp_parser_settings;
FParser: Thttp_parser;
Flast_header_name: string;
Flast_header_value: string;
// isFin: Boolean;
procedure CheckConnect;
procedure ProcessRequest;
procedure do_handshake;
procedure do_shutdown;
procedure onPlainData(const chunk:BufferRef);
procedure onSSLData(const chunk:BufferRef);
procedure InternalClose;
procedure Request(req: TBaseHttpRequest);
procedure on_message_begin;
// procedure on_url(const s : string);
procedure on_status(const s : string);
procedure on_header_field;
procedure on_headers_complete;
procedure on_body(const ABuf : BufferRef);
procedure on_message_complete;
public
url : TURL;
function _GET(const Apath: string): TBaseHttpRequest;
constructor Create(const BaseURL: string);
procedure Shutdown;
destructor Destroy; override;
end;
implementation
uses np.ut, np.netEncoding;
function tos(const at:PAnsiChar; len: SiZE_t) : string;
begin
SetString(result,at,len);
end;
function _on_message_begin( parser: PHttp_parser) : integer; cdecl;
begin
THttpConnect( parser.data ).on_message_begin;
result := 0;
end;
// function _on_url(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
// begin
// THttpConnect( parser.data ).on_url( TURL._DecodeURL( tos(at,len) ) );
// result := 0;
// end;
function _on_status(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
THttpConnect(parser.data).on_status( tos(at,len) );
result := 0;
end;
function _on_header_field(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
// outputdebugStr('on_header_field "%s"', [tos(at,len)]);
THttpConnect( parser.data ).Flast_header_name := LowerCase( tos(at,len) );
result := 0;
end;
function _on_header_value(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
// outputdebugStr('on_header_value "%s"', [tos(at,len)]);
with THttpConnect( parser.data ) do
begin
// outputdebugStr('| %s = %s',[ Flast_header_name, tos(at,len) ] );
//FHeaders.addSubFields( Flast_header_name, tos(at,len) );
Flast_header_value := tos(at,len);
on_header_field();
Flast_header_name := '';
Flast_header_value := '';
end;
result := 0;
end;
function _on_headers_complete( parser: PHttp_parser) : integer; cdecl;
begin
THttpConnect( parser.data ).on_headers_complete;
result := 0;
end;
function _on_body(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
THttpConnect( parser.data ).on_body( BufferRef.CreateWeakRef(at,len) );
result := 0;
end;
function _on_message_complete( parser: PHttp_parser) : integer; cdecl;
begin
//outputdebugStr('on_message_complete');
THttpConnect( parser.data ).on_message_complete();
result := 0;
end;
// function _on_chunk_header( parser: PHttp_parser) : integer; cdecl;
// begin
// //outputdebugStr('on_chunk_header');
// result := 0;
// end;
//
// function _on_chunk_complete( parser: PHttp_parser) : integer; cdecl;
// begin
// //outputdebugStr('on_chunk_complete');
// result := 0;
// end;
{ TBaseHttpRequest }
constructor THttpConnect.Create(const BaseURL: string);
var
onSd : IEventHandler;
begin
loop.addTask;
inherited Create();
queue:= TQueue<TBaseHttpRequest>.Create;
url.Parse(BaseURL);
onSd := loop.once(ev_loop_shutdown,
procedure
begin
shutdown;
end);
once(ev_destroy,
procedure
begin
onSd.remove;
onSd := nil;
if onTimeout <> nil then
begin
onTimeout.Clear;
onTimeout := nil;
end;
end);
http_parser_settings_init(FSettings);
FSettings.on_message_begin := _on_message_begin;
// FSettings.on_url := _on_url;
FSettings.on_status := _on_status;
FSettings.on_header_field := _on_header_field;
FSettings.on_header_value := _on_header_value;
FSettings.on_headers_complete := _on_headers_complete;
FSettings.on_body := _on_body;
FSettings.on_message_complete := _on_message_complete;
// FSettings.on_chunk_header := _on_chunk_header;
// FSettings.on_chunk_complete := _on_chunk_complete;
http_parser_init(FParser, HTTP_RESPONSE);
FParser.data := self;
// fltc := 0;
// fltd := 0;
// on_(ev_connected,
// procedure
// begin
// fltc := CurrentTimestamp;
// end);
// on_(ev_disconnected,
// procedure
// begin
// fltd := CurrentTimestamp;
// end );
end;
{ TBaseHttpRequest }
procedure TBaseHttpRequest.addHeader(const name: string; const value: string);
begin
if initState = isWantCookieEnd then
endCookie;
if initState = isWantEndHeader then
req.Append(name).Append(': ').Append(value).Append(#13).Append(#10);
end;
procedure TBaseHttpRequest.autoDone;
begin
once(ev_Complete,
procedure
begin
done;
end);
end;
procedure TBaseHttpRequest.beginCookie;
begin
assert( fCookieCount = 0 );
end;
procedure TBaseHttpRequest.beginHeader(const method: string; const path: string; AkeepAlive:Boolean);
begin
ClearResponse;
assert(assigned(connect));
ReqMethod := method;
initState := isWantEndHeader;
isGet := method = 'GET';
req.Clear;
req.Append(method).Append(' ');
if path = '' then
ReqPath := '/'
else
ReqPath := TNetEncoding.URL.Encode( path );
req.Append(ReqPath);
req.Append(' HTTP/1.1').Append(#13).Append(#10);
addHeader('Host', connect.Url.HttpHost);
if AkeepAlive then
addHeader('Connection', 'keep-alive')
else
addHeader('Connection', 'close');
initState := isWantEndHeader;
end;
procedure TBaseHttpRequest.ClearResponse;
begin
FreeAndNil(ResponseHeader);
ResponseContent := Buffer.Null;
protocol := '';
statusCode := 0;
statusReason := '';
fCookieCount := 0;
end;
constructor TBaseHttpRequest.Create(Aconnect: THttpConnect);
begin
inherited Create();
//CompleteReaction := crFree;
req := TStringBuilder.Create;
connect := AConnect;
lostConnectObjectHandler := connect.once(ev_destroy,
procedure
begin
connect := nil;
isPending := false;
isInQueue := false;
done;
end);
// resume;
end;
destructor TBaseHttpRequest.Destroy;
begin
assert(not isPending);
lostConnectObjectHandler.remove;
FreeAndNil(req);
FreeAndNil(ResponseHeader);
emit(ev_destroy);
inherited;
end;
procedure TBaseHttpRequest.done;
begin
// assert(isPending = false);
IsDone := true;
if not isInQueue then
NextTick(
procedure
begin
Free;
end);
end;
procedure TBaseHttpRequest.addCookie(const name, value: string);
begin
if name = '' then
exit;
if fCookieCount > 0 then
begin
if initState <> isWantCookieEnd then
exit;
req.Append('; ');
end
else
begin
if initState <> isWantEndHeader then
exit;
initState := isWantCookieEnd;
req.Append('Cookie: ');
end;
inc(fCookieCount);
req.Append(name).Append('=').Append(value);
end;
procedure TBaseHttpRequest.endCookie;
begin
if initState = isWantCookieEnd then
begin
req.Append(#13).append(#10);
initState := isWantEndHeader;
end;
end;
procedure TBaseHttpRequest.endHeader;
begin
endHeader(Buffer.Null,'');
end;
procedure TBaseHttpRequest.resume;
begin
if not isDone and
not isPending then
connect.Request(self);
end;
procedure TBaseHttpRequest.endHeader(const content: BufferRef; const contentType:string);
begin
if initState = isWantCookieEnd then
endCookie;
if initState <> isWantEndHeader then
exit;
if contentType <> '' then
addHeader('Content-Type', contentType);
if (Content.length > 0) or (not isGet) then
addHeader('Content-Length',IntToStr( Content.length) );
req.Append(#13).append(#10);
request := Buffer.Create( [Buffer.Create( req.ToString, CP_USASCII ), Content] );
initState := isRdy;
end;
procedure THttpConnect.onPlainData(const chunk: BufferRef);
var
req: TBaseHttpRequest;
header: BufferRef;
begin
if (chunk.length > 0) then
http_parser_execute(FParser,Fsettings,PAnsiChar( chunk.ref ), chunk.length);
// if queue.Count = 0 then
// exit;
// req := queue.Peek;
// assert( req.isPending );
//
//
//// if not req.isPending then
//// begin
//// req.ClearResponse;
//// req.isPending := true;
//// end;
//
// if req.ResponseHeader <> nil then
// optimized_append(req.ResponseContent,chunk)
// else
// begin
// optimized_append(Fdata,chunk);
// if not CheckHttpAnswer(Fdata,req.protocol,req.statusCode,req.statusReason, header, req.ResponseContent) then
// exit;
// req.ResponseHeader := THTTPHeader.Create(header);
// req.emit(ev_HeaderLoaded, req);
// Fdata.length := 0;
// end;
// if req.ConnectionOwner then
// begin
// if req.ResponseContent.length > 0 then
// req.emit(ev_ContentUpdated, @req.ResponseContent);
// end
// else
// if req.ResponseContent.length >= req.ResponseHeader.ContentLength then
// begin
// req.ResponseContent.length := req.ResponseHeader.ContentLength;
// req.isPending := false;
// queue.Dequeue;
// req.isInQueue := false;
// if not req.isDone then
// begin
// req.emit(ev_Complete, req);
// end
// else
// req.free;
// ProcessRequest; //Check next request
// end;
end;
procedure THttpConnect.onSSLData(const chunk: BufferRef);
var
nbytes : integer;
begin
try
repeat
nbytes := BIO_write(Fin_bio,chunk.ref,chunk.length);
assert( nbytes > 0);
chunk.TrimL(nbytes);
if isHandshake then
begin
do_handshake;
if Fis_init_finished = 1 then
begin
isHandshake := false;
FData.length := 0;
IsConnected := true;
emit(ev_connected, self);
ProcessRequest;
end;
end;
if not isHandshake then
begin
repeat
nbytes := SSL_read(FSSL,@FSSLData[0],length(FSSLData));
if nbytes <= 0 then
break;
//optimized_append(FData, BufferRef.CreateWeakRef(@FSSLData[0],nbytes));
onPlainData(BufferRef.CreateWeakRef(@FSSLData[0],nbytes));
until false;
end;
until chunk.length = 0;
except
con.Clear;
end;
end;
procedure THttpConnect.on_body(const ABuf: BufferRef);
var
req : TBaseHttpRequest;
begin
if (queue.Count >0) then
begin
req := queue.Peek;
optimized_append( req.ResponseContent, ABuf);
end;
end;
procedure THttpConnect.on_headers_complete;
var
req : TBaseHttpRequest;
begin
OutputDebugStr('on_headers_complete');
if (queue.Count >0) then
begin
req := queue.Peek;
req.ResponseHeader.parse(Buffer.Null);
req.emit(ev_HeaderLoaded, req);
end;
end;
procedure THttpConnect.on_header_field;
var
req : TBaseHttpRequest;
begin
OutputDebugStr('on_header_field %s=%s',[Flast_header_name, Flast_header_value]);
if (queue.Count >0) then
begin
req := queue.Peek;
if assigned( req.ResponseHeader ) then
req.ResponseHeader.addSubFields( Flast_header_name, Flast_header_value );
end;
end;
procedure THttpConnect.on_message_begin;
var
req : TBaseHttpRequest;
begin
Flast_header_name := '';
Flast_header_value := '';
OutputDebugStr('on_message_begin');
if (queue.Count >0) then
begin
req := queue.Peek;
if assigned( req.ResponseHeader ) then
req.ResponseHeader.Clear
else
req.ResponseHeader := THTTPHeader.Create(Buffer.Null);
end;
end;
procedure THttpConnect.on_message_complete;
var
req : TBaseHttpRequest;
begin
OutputDebugStr('on_message_complete');
if queue.Count > 0 then
begin
req := queue.Peek;
req.isPending := false;
queue.Dequeue;
req.isInQueue := false;
if not req.isDone then
begin
req.emit(ev_Complete, req);
end
else
req.free; //no one interest with reques...
ProcessRequest; //Check next request
end;
end;
procedure THttpConnect.on_status(const s: string);
var
req : TBaseHttpRequest;
begin
if queue.Count > 0 then
begin
req := queue.Peek;
req.statusCode := ord ( http_parser_get_status_code( FParser ) );
req.statusReason := s;
req.protocol := Format('HTTP/%u.%u',[ FParser.http_major, FParser.http_minor ]);
OutputDebugStr(Format('on_status: %u %s (%s)',[req.statusCode, req.statusReason, req.protocol]));
end;
end;
//procedure THttpConnect.on_url(const s: string);
//begin
// OutputDebugStr('on_url: '+s);
//end;
procedure THttpConnect.Request(req: TBaseHttpRequest);
begin
if (not IsShutdown) and (not req.isInQueue) then
begin
queue.Enqueue(req);
req.isInQueue := true;
begin
NextTick(
procedure
begin
ProcessRequest;
end);
end;
end;
end;
destructor THttpConnect.Destroy;
begin
Isshutdown := true;
if assigned(con) then
begin
con.setOnConnect(nil);
con.SetonClose(nil);
con.setOnError(nil);
con.setOnData(nil);
con.setOnEnd(nil);
if assigned(con) then
do_shutdown;
con.Clear;
InternalClose;
end;
emit(ev_destroy,self);
// while queue.Count > 0 do
// begin
// req := queue.Dequeue;
// req.isPending := false;
// req.isInQueue := false;
// req.isDone := true;
// req.emit(ev_Complete);
// req.connect := nil;
// if req.CompleteReaction = crFree then
// req.Free;
// end;
freeAndNil(queue);
if assigned(FCtx) then
begin
SSL_CTX_free(Fctx);
Fctx := nil;
end;
inherited;
loop.removeTask;
end;
procedure THttpConnect.CheckConnect;
var
closeBadly : boolean;
begin
if (not Isshutdown) and (not assigned(con)) and (queue.Count > 0) and not assigned(onTimeout) then
begin
if url.Schema = 'https' then
begin
if not assigned(Fctx) then
begin
Fctx := SSL_CTX_new( TLS_client_method());
assert(assigned(Fctx));
SSL_CTX_set_verify(FCTX, SSL_VERIFY_NONE, nil);
end;
end
else
if url.Schema <> 'http' then
raise ENotSupportedException.CreateFmt('unknown url schema: "%s"',[url.Schema]);
emit(ev_connecting,self);
http_parser_init(FParser, HTTP_RESPONSE);
FParser.data := self;
closeBadly := false;
con := TNPTCPStream.CreateConnect;
con.set_nodelay(true);
// con.bind(url.HostName,url.Port);
con.SetonClose(
procedure
var
delay : Boolean;
begin
delay := not IsConnected or closeBadly;
InternalClose;
if (queue.Count > 0) and (queue.Peek.ConnectionOwner) then
Shutdown
else
begin
if delay then
begin
onTimeout := SetTimeout(
procedure
begin
onTimeout := nil;
CheckConnect;
end, 100);
onTimeout.unref;
end
else
CheckConnect;
end;
end);
con.setOnError(
procedure (err:PNPError)
begin
closeBadly := true;
emit(ev_error, @err);
end
);
if assigned(Fctx) then
begin
con.setOnConnect(
procedure
begin
isConnected:=true;
isHandshake:=true;
Fin_bio := BIO_new(BIO_s_mem());
assert(Fin_bio <> nil);
BIO_set_mem_eof_return(Fin_bio,-1);
Fout_bio := BIO_new(BIO_s_mem());
assert(Fout_bio <> nil);
BIO_set_mem_eof_return(Fout_bio,-1);
FSSL := SSL_new(FCtx);
assert(assigned( FSSL ) );
SSL_set_connect_state(FSSL);
SSL_set_bio(FSSL, Fin_bio, Fout_bio);
setLength( FSSLData, 4096);
con.setOnData(
procedure (data:PBufferRef)
begin
onSSLData(data^);
end);
do_handshake;
end);
end
else
begin
con.setOnConnect(
procedure
begin
con.setOnData(
procedure (data:PBufferRef)
begin
onPlainData(data^);
end);
IsConnected := true;
emit(ev_connected,self);
Fdata.length := 0;
ProcessRequest;
end);
end;
con.connect(url.HostName,url.Port);
end;
end;
procedure THttpConnect.ProcessRequest;
var
req : TBaseHttpRequest;
nbytes : integer;
begin
if Isshutdown then
exit;
if not IsConnected then
begin
CheckConnect;
exit;
end;
while (not Isshutdown) and (queue.Count > 0) do
begin
req := queue.Peek;
if req.isPending then
exit;
req.ClearResponse;
assert(assigned(req));
req.emit(ev_BeforeProcess); //dymanic request handler
emit( ev_BeforeProcess, req);
if req.isDone then
begin
queue.Dequeue;
continue;
end;
if req.request.length = 0 then //error dynamic request
begin
queue.Dequeue;
req.statusCode := -1;
req.statusReason := 'no request header';
req.isPending := false;
req.isInQueue := false;
req.emit(ev_Complete);
continue;
end;
req.isPending := true;
if assigned(FSSL) then
begin
nbytes := SSL_write(Fssl,req.request.ref, req.request.length);
assert( nbytes = req.request.length);
repeat
nbytes := BIO_read(Fout_bio, @FSSLData[0] , length(FSSLData));
if nbytes <= 0 then
break;
con.write(BufferRef.CreateWeakRef( @FSSLData[0], nbytes) );
until false;
end
else
begin
con.write( req.request );
///req.request := Buffer.Null;
end;
exit;
end;
end;
procedure THttpConnect.Shutdown;
begin
if not IsShutdown then
begin
IsShutdown := true;
loop.NextTick(
procedure
begin
free;
end);
end;
end;
function THttpConnect._GET(const Apath: string): TBaseHttpRequest;
begin
result := TBaseHttpRequest.Create(self);
result.beginHeader('GET',Apath);
result.endHeader();
result.resume;
end;
procedure THttpConnect.do_handshake;
var
err : integer;
nbytes : integer;
begin
if Fis_init_finished <> 1 then
begin
Fis_init_finished := SSL_do_handshake(Fssl);
if Fis_init_finished <> 1 then
begin
err := SSL_get_error(Fssl, Fis_init_finished);
//WriteLn(Format('handshake error: %d',[err]));
if Fis_init_finished = 0 then
begin
//WriteLn(Format('fatal code:%d',[err]));
abort;
end;
if err = SSL_ERROR_WANT_READ then
begin
// len := BIO_read(Fout_bio,@FSSLData[0],length(FSSLData));
// assert(len > 0);
// write(@FSSLData[0],len);
end
else
if err = SSL_ERROR_WANT_WRITE then
begin
//WriteLn('SSL_ERROR_WANT_WRITE');
end
else
abort;
end
else
begin
end;
end;
repeat
nbytes := BIO_read(Fout_bio,@FSSLData[0],length(FSSLData));
if nbytes <= 0 then
break;
con.write(BufferRef.CreateWeakRef( @FSSLData[0],nbytes) );
until false;
end;
procedure THttpConnect.do_shutdown;
var
res : integer;
len : integer;
begin
if isConnected then
begin
if assigned(FSSL) then
begin
res := SSL_shutdown(Fssl);
if res = 0 then
res := SSL_shutdown(Fssl);
// if res < 0 then
// Rescode := SSL_get_error(FSSL,res);
repeat
len := BIO_read(Fout_bio,@FSSLData[0],length(FSSLData));
if len <= 0 then
begin
break;
end;
con.write(BufferRef.CreateWeakRef( @FSSLData[0],len) );
until false;
con.setOnData(nil);
con.shutdown(nil);
end
else
begin
con.setOnData(nil);
con.shutdown(nil);
end;
end;
con.Clear;
end;
procedure THttpConnect.InternalClose;
begin
if http_message_needs_eof(FParser) <> 0 then
http_parser_execute(FParser,Fsettings,nil,0);
ClearTimer( onTimeout );
if isConnected then
begin
emit(ev_disconnected,self);
end;
if assigned(con) then
begin
con := nil;
Fis_init_finished := 0;
isConnected := false;
Fdata.length := 0;
if assigned(Fssl) then
SSL_free(Fssl);
Fssl := nil;
end;
end;
{ THttpRequest }
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MainAncestor, Vcl.Menus, Data.Win.ADODB,
Data.DB, Vcl.ImgList, Vcl.ComCtrls, MyListView, Vcl.ToolWin,
Vcl.StdCtrls, Vcl.ExtCtrls, HControls, ListViewEx, frxClass, frxDBSet,
HolderEdits, frxExportPDF, Data.Bind.EngExt, Vcl.Bind.DBEngExt,
Data.Bind.Components;
type
TfrmMain = class(TfrmMainAncestor)
DBTKasboek: TADOTable;
btnKas: TToolButton;
btnAlles: TToolButton;
Panel1: TPanel;
LblSaldo: TLabel;
pmpNieuwKasboek: TMenuItem;
pmpNieuwBankBoek: TMenuItem;
edtVolgKwit: TEdit;
edtBanknr: TEdit;
btnClearSearch: TButton;
edtNaam: TEdit;
lblZoekHeader: TLabel;
frxDBKasboek: TfrxDBDataset;
edtDag: TEdit;
edtMaand: TEdit;
edtJaar: TEdit;
edtCode: TEdit;
edtOmschrijving: TEdit;
edtInkomen: THCurrencyEdit;
edtUitgaven: THCurrencyEdit;
frxRepPDFExport: TfrxPDFExport;
frxDBTotals: TfrxUserDataSet;
frxRepKasboek: TfrxReport;
frxRepBankBoek: TfrxReport;
btnDataMapEx: TMenuItem;
btnDataMapImp: TMenuItem;
frxRepAll: TfrxReport;
btnAddUser: TMenuItem;
DBTKasboekId: TAutoIncField;
DBTKasboekNr: TIntegerField;
DBTKasboekDag: TIntegerField;
DBTKasboekMaand: TIntegerField;
DBTKasboekJaar: TIntegerField;
DBTKasboekBanknr: TWideStringField;
DBTKasboekVolgKwit: TWideStringField;
DBTKasboekCode: TWideStringField;
DBTKasboekNaam: TWideStringField;
DBTKasboekOmschrijving: TWideStringField;
DBTKasboekInkomen: TBCDField;
DBTKasboekUitgaven: TBCDField;
DBTKasboekKasboek: TBooleanField;
DBTKasboekAangemaaktDoor: TWideStringField;
DBTKasboekAangemaaktOp: TDateTimeField;
DBTKasboekBoekDate: TDateTimeField;
procedure btnBeginClick(Sender: TObject);
procedure btnKasClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure btnPrintenClick(Sender: TObject);
procedure btnClearSearchClick(Sender: TObject);
procedure lvwItemsCustomDrawItem(Sender: TCustomListView; Item: TListItem;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure btnNewClick(Sender: TObject);
procedure edtBanknrChange(Sender: TObject);
procedure btnAllesClick(Sender: TObject);
procedure frxDBTotalsNewGetValue(Sender: TObject; const VarName: string;
var Value: Variant);
procedure btnDataMapExClick(Sender: TObject);
procedure btnDataMapImpClick(Sender: TObject);
procedure btnAddUserClick(Sender: TObject);
procedure frxRepBankBoekGetValue(const VarName: string; var Value: Variant);
procedure frxRepBankBoekNewGetValue(Sender: TObject; const VarName: string;
var Value: Variant);
private
repInkomen: Double;
repUitgaven: Double;
donotSearch: Boolean;
procedure LoadKasboek;
procedure LoadBankboek;
procedure LoadKasboekColumns;
procedure LoadKasboekDetails;
procedure LoadBankboekColumns(All: Boolean);
procedure LoadBankboekDetails;
procedure LoadBankZoekHeader;
procedure LoadKasZoekHeader;
procedure UncheckAll(button: TToolButton);
procedure SetDBready(Filter: String);
procedure ShowSaldo(TotalInkomen: Double; TotalUitgaven: Double);
procedure LoadFilteredData;
function GetDagFilter(): String;
function GetMaandFilter(): String;
function GetYaarFilter(): String;
function GetVolgnrFilter(): String;
function GetCodeFilter(): String;
function GetNaamFilter(): String;
function GetBankFilter(): String;
function GetOmschrijvingFilter(): String;
function GetInkomenFilter(): String;
function GetUitgavenFilter(): String;
procedure ClearSearch();
procedure SetPrintData();
protected
procedure Refresh; override;
procedure OpenDatasets; override;
procedure ExecuteFix; override;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses EditBoek, ReportAncestor, DateUtils, StrUtils, FileCtrl, EditUser;
{$R *.dfm}
{ TfrmMain }
procedure TfrmMain.btnAddUserClick(Sender: TObject);
begin
frmEditUser := TfrmEditUser.Create(Self, DBTUsers);
try
if frmEditUser.ShowModal = MrOk then
ShowMessage('Gebruiker is toegevoegd');
finally
frmEditUser.Free;
end;
end;
procedure TfrmMain.btnAllesClick(Sender: TObject);
begin
objectType := 'Alles';
ClearSearch;
SetDBready('');
LoadBankboekColumns(True);
LoadBankboekDetails();
UncheckAll(btnAlles);
end;
procedure TfrmMain.btnKasClick(Sender: TObject);
begin
objectType := 'Kasboek';
ClearSearch;
LoadKasboek;
end;
procedure TfrmMain.btnBeginClick(Sender: TObject);
begin
objectType := 'Bankboek';
ClearSearch;
LoadBankboek;
end;
procedure TfrmMain.btnClearSearchClick(Sender: TObject);
begin
SetFilterFalse;
end;
procedure TfrmMain.btnDataMapExClick(Sender: TObject);
var
chosenDirectory : string;
begin
if SelectDirectory('Kies een map om de data op te slaan', '', chosenDirectory) then begin
CopyFile(PChar(DatabaseLocation +DatabaseName), PChar(chosenDirectory +'\'+ DatabaseName),False);
FileSetAttr(PChar(chosenDirectory +'\'+ DatabaseName), 2);
end;
end;
procedure TfrmMain.btnDataMapImpClick(Sender: TObject);
var
chosenDirectory : string;
begin
if SelectDirectory('Kies de map om data te importeren', '', chosenDirectory) then begin
CloseDatase();
CopyFile(PChar(chosenDirectory +'\'+ DatabaseName), PChar(DatabaseLocation +DatabaseName),False);
FileSetAttr(PChar(DatabaseLocation + DatabaseName), 2);
ReloadDatabase;
end;
end;
procedure TfrmMain.btnEditClick(Sender: TObject);
begin
if lvwItems.Selected = nil then
Exit;
CurrentTable.Locate('ID', Integer(lvwItems.Selected.Data), []);
frmEditAncestor := TfrmEditBoek.Create(Self, Integer(lvwItems.Selected.Data),
CurrentTable);
inherited;
end;
procedure TfrmMain.btnNewClick(Sender: TObject);
var
Nr: String;
begin
CurrentTable.Last;
if not(CurrentTable.FieldByName('Nr').AsString = '') then
Nr := IntToStr(CurrentTable.FieldByName('Nr').asInteger + 1)
else
Nr := '1';
try
frmEditAncestor := TfrmEditBoek.Create(Self, 0, CurrentTable);
if objectType = 'Kasboek' then
TfrmEditBoek(frmEditAncestor).ckbBoek.Checked := True
else
TfrmEditBoek(frmEditAncestor).ckbBoek.Checked := False;
TfrmEditBoek(frmEditAncestor).edtNr.Text := Nr;
TfrmEditBoek(frmEditAncestor).loadBoekValues;
if frmEditAncestor.ShowModal = mrOk then
Refresh;
finally
frmEditAncestor.Free;
end;
end;
procedure TfrmMain.btnPrintenClick(Sender: TObject);
begin
SetPrintData();
if objectType = 'Kasboek' then
frxRepKasboek.ShowReport()
else if objectType = 'Alles' then
frxRepAll.ShowReport()
else
frxRepBankBoek.ShowReport();
end;
procedure TfrmMain.ClearSearch;
begin
donotSearch := True;
edtDag.Text := '';
edtMaand.Text := '';
edtJaar.Text := '';
edtBanknr.Text := '';
edtCode.Text := '';
edtVolgKwit.Text := '';
edtNaam.Text := '';
edtOmschrijving.Text := '';
edtInkomen.Value := 0;
edtUitgaven.Value := 0;
donotSearch := False;
btnNew.Enabled := not(objectType = 'Alles');
end;
procedure TfrmMain.edtBanknrChange(Sender: TObject);
begin
if not(donotSearch) then
LoadFilteredData();
end;
procedure TfrmMain.ExecuteFix;
var frmBoek : TfrmEditBoek;
I: Integer;
Query:String;
begin
Query := Inifile.ReadString('app','sql','');
DBTQuery.SQL.Clear;
DBTQuery.SQL.Add(Query);
DBTQuery.ExecSQL;
DBTKasboek.Open;
DBTKasboek.Filtered := False;
DBTKasboek.First;
for I := 0 to DBTKasboek.RecordCount - 1 do
begin
frmBoek := TfrmEditBoek.Create(Self, Integer(DBTKasboekId.AsInteger), DBTKasboek);
frmBoek.btnSave.Click;
DBTKasboek.Next;
end;
showFix := False;
Inifile.WriteString('app','convert','fixed');
end;
procedure TfrmMain.frxDBTotalsNewGetValue(Sender: TObject;
const VarName: string; var Value: Variant);
begin
if VarName = 'inkomen' then
Value := FloatToStrF(repInkomen, ffCurrency, 8, 2);
if VarName = 'uitgaven' then
Value := FloatToStrF(repUitgaven, ffCurrency, 8, 2);
if VarName = 'totaal' then
Value := FloatToStrF(repInkomen-repUitgaven, ffCurrency, 8, 2);
inherited;
end;
procedure TfrmMain.frxRepBankBoekGetValue(const VarName: string;
var Value: Variant);
begin
ShowMessage(VarName);
inherited;
Value := Value;
end;
procedure TfrmMain.frxRepBankBoekNewGetValue(Sender: TObject;
const VarName: string; var Value: Variant);
begin
ShowMessage('HK'+VarName);
inherited;
Value := Value;
end;
function TfrmMain.GetMaandFilter: String;
begin
if not(edtMaand.Text = '') then
Result := ' AND Maand =' + edtMaand.Text
else
Result := '';
end;
function TfrmMain.GetBankFilter: String;
begin
if not(edtBanknr.Text = '') then
Result := ' AND Banknr Like ' + QuotedStr(edtBanknr.Text + '*')
else
Result := '';
end;
function TfrmMain.GetCodeFilter: String;
begin
if not(edtCode.Text = '') then
Result := ' AND Code Like ' + QuotedStr(edtCode.Text + '*')
else
Result := '';
end;
function TfrmMain.GetDagFilter: String;
begin
if not(edtDag.Text = '') then
Result := ' AND Dag =' + edtDag.Text
else
Result := '';
end;
function TfrmMain.GetInkomenFilter: String;
var tempString:String;
begin
if edtInkomen.Value > 0 then begin
tempString := ' AND Inkomen=' + FloatToStr(edtInkomen.Value);
Result := StringReplace(tempString, ',', '.', [rfReplaceAll])
end
else
Result := '';
end;
function TfrmMain.GetNaamFilter: String;
begin
if not(edtNaam.Text = '') then
Result := ' AND Naam LIKE ' + QuotedStr(edtNaam.Text + '*')
else
Result := '';
end;
function TfrmMain.GetOmschrijvingFilter: String;
begin
if not(edtOmschrijving.Text = '') then
Result := ' AND Omschrijving Like ' + QuotedStr(edtOmschrijving.Text + '*')
else
Result := '';
end;
function TfrmMain.GetUitgavenFilter: String;
var tempString:String;
begin
if edtUitgaven.Value > 0 then begin
tempString := ' AND Uitgaven=' + FloatToStr(edtUitgaven.Value);
Result := StringReplace(tempString, ',', '.', [rfReplaceAll]) ;
end
else
Result := '';
end;
function TfrmMain.GetVolgnrFilter: String;
begin
if not(edtVolgKwit.Text = '') then
Result := ' AND VolgKwit Like ' + QuotedStr(edtVolgKwit.Text + '*')
else
Result := '';
end;
function TfrmMain.GetYaarFilter: String;
begin
if not(edtJaar.Text = '') then
Result := ' AND Jaar =' + edtJaar.Text
else
Result := '';
end;
procedure TfrmMain.LoadBankboek;
begin
CurrentTable := DBTKasboek;
SetDBready('Kasboek=False');
objectType := 'Bankboek';
btnNew.Caption := 'Nieuw Bankboek';
LoadBankboekColumns(False);
LoadBankboekDetails();
UncheckAll(btnBegin);
LoadBankZoekHeader;
end;
procedure TfrmMain.LoadBankboekColumns(all: Boolean);
begin
addColumn('Id', 40);
addColumn('Dag', 40, taRightJustify);
addColumn('Maand', 50, taRightJustify);
addColumn('Jaar', 40, taRightJustify);
addColumn('Banknummer', 100);
if all then
addColumn('Volg/Kwit nr', 70)
else
addColumn('Volgnummer', 70);
addColumn('Code', 60);
addColumn('Naam', 100);
addColumn('Omschrijving', 150);
addColumn('Inkomen', 100, taRightJustify);
addColumn('Uitgaven', 100, taRightJustify);
end;
procedure TfrmMain.LoadBankboekDetails;
var
LI: TListItem;
I: Integer;
TotalInkomen, TotalUitgaven: Double;
begin
for I := 0 to DBTKasboek.RecordCount - 1 do
begin
LI := lvwItems.Items.Add;
LI.Caption := DBTKasboek.FieldByName('Nr').AsString;
LI.SubItems.Add(DBTKasboek.FieldByName('Dag').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Maand').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Jaar').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Banknr').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('VolgKwit').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Code').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Naam').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Omschrijving').AsString);
LI.SubItems.Add( '€ '+FormatFloat('0.00',DBTKasboek.FieldByName('Inkomen').AsFloat));
LI.SubItems.Add( '€ '+FormatFloat('0.00',DBTKasboek.FieldByName('Uitgaven').AsFloat));
if DBTKasboek.FieldByName('Inkomen').AsFloat > 0 then
TotalInkomen := TotalInkomen + DBTKasboek.FieldByName('Inkomen').AsFloat
else
TotalUitgaven := TotalUitgaven + DBTKasboek.FieldByName
('Uitgaven').AsFloat;
LI.Data := Pointer(DBTKasboek.FieldByName('ID').asInteger);
DBTKasboek.Prior;
end;
repInkomen := TotalInkomen;
repUitgaven := TotalUitgaven;
ShowSaldo(TotalInkomen, TotalUitgaven);
end;
procedure TfrmMain.LoadBankZoekHeader;
begin
lblZoekHeader.Caption := 'Datum: Bankrekening: Volgnr: Code: Naam: Omschrijving: Inkomen: Uitgaven:';
edtBanknr.Visible := True;
edtBanknr.Left := 177;
edtVolgKwit.Left := 274;
edtCode.Left := 340;
edtNaam.Left := 401;
edtOmschrijving.Left := 510;
edtInkomen.Left := 657;
edtUitgaven.Left := 740;
end;
procedure TfrmMain.LoadFilteredData;
begin
if objectType = 'Kasboek' then
begin
SetDBready('Kasboek=True' + GetDagFilter() + GetMaandFilter() +
GetYaarFilter() + GetVolgnrFilter + GetCodeFilter + GetNaamFilter +
GetOmschrijvingFilter + GetInkomenFilter + GetUitgavenFilter);
LoadKasboekColumns();
LoadKasboekDetails();
end
else if objectType = 'Bankboek' then
begin
SetDBready('Kasboek=False' + GetDagFilter() + GetMaandFilter() +
GetYaarFilter() + GetBankFilter() + GetVolgnrFilter + GetCodeFilter + GetNaamFilter +
GetOmschrijvingFilter()+ GetInkomenFilter + GetUitgavenFilter);
LoadBankboekColumns(False);
LoadBankboekDetails();
end
else
begin
SetDBready(GetDagFilter() + GetMaandFilter() + GetYaarFilter() +
GetVolgnrFilter + GetCodeFilter + GetNaamFilter +
GetInkomenFilter + GetUitgavenFilter);
LoadBankboekColumns(True);
LoadBankboekDetails();
end;
end;
procedure TfrmMain.LoadKasboek;
begin
CurrentTable := DBTKasboek;
lvwItems.Clear;
lvwItems.Columns.Clear;
objectType := 'Kasboek';
SetDBready('Kasboek=True');
btnNew.Caption := 'Nieuw Kasboek ';
LoadKasboekColumns();
LoadKasboekDetails();
UncheckAll(btnKas);
LoadKasZoekHeader;
end;
procedure TfrmMain.LoadKasboekColumns;
begin
addColumn('Id', 40);
addColumn('Dag', 40, taRightJustify);
addColumn('Maand', 50, taRightJustify);
addColumn('Jaar', 40, taRightJustify);
addColumn('Kwitnummer', 70);
addColumn('Code', 60);
addColumn('Naam', 100);
addColumn('Omschrijving', 150);
addColumn('Inkomen', 100, taRightJustify);
addColumn('Uitgaven', 100, taRightJustify);
end;
procedure TfrmMain.LoadKasboekDetails;
var
LI: TListItem;
I: Integer;
TotalInkomen, TotalUitgaven: Double;
begin
for I := 0 to DBTKasboek.RecordCount - 1 do
begin
LI := lvwItems.Items.Add;
LI.Caption := DBTKasboek.FieldByName('Nr').AsString;
LI.SubItems.Add(DBTKasboek.FieldByName('Dag').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Maand').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Jaar').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('VolgKwit').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Code').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Naam').AsString);
LI.SubItems.Add(DBTKasboek.FieldByName('Omschrijving').AsString);
LI.SubItems.Add( '€ '+FormatFloat('0.00',DBTKasboek.FieldByName('Inkomen').AsFloat));
LI.SubItems.Add( '€ '+FormatFloat('0.00',DBTKasboek.FieldByName('Uitgaven').AsFloat));
if DBTKasboek.FieldByName('Inkomen').AsFloat > 0 then
TotalInkomen := TotalInkomen + DBTKasboek.FieldByName('Inkomen').AsFloat
else
TotalUitgaven := TotalUitgaven + DBTKasboek.FieldByName
('Uitgaven').AsFloat;
LI.Data := Pointer(DBTKasboek.FieldByName('ID').asInteger);
DBTKasboek.Prior;
end;
repInkomen := TotalInkomen;
repUitgaven := TotalUitgaven;
ShowSaldo(TotalInkomen, TotalUitgaven);
end;
procedure TfrmMain.LoadKasZoekHeader;
begin
lblZoekHeader.Caption := 'Datum: Kwitnr: Code: Naam: Omschrijving: Inkomen: Uitgaven:';
edtBanknr.Visible := False;
edtVolgKwit.Left := 174;
edtCode.Left := 240;
edtNaam.Left := 301;
edtOmschrijving.Left := 410;
edtInkomen.Left := 557;
edtUitgaven.Left := 640;
end;
procedure TfrmMain.lvwItemsCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if Odd(Item.Index) then
Sender.Canvas.Brush.Color := $00C6C600;;
end;
procedure TfrmMain.OpenDatasets;
begin
inherited;
if not(showFix) then
DBTKasboek.Open
else
ExecuteFix;
end;
procedure TfrmMain.Refresh;
begin
ClearSearch;
if (objectType = 'Bankboek') or (objectType = '') then
LoadBankboek
else if (objectType = 'Alles') then
btnAlles.Click
else
LoadKasboek;
end;
procedure TfrmMain.SetDBready(Filter: String);
begin
lvwItems.Clear;
lvwItems.Columns.Clear;
CurrentTable.Filtered := False;
if (AnsiStartsStr(' AND', Filter)) then
CurrentTable.Filter := Copy(Filter, Pos('AND', Filter) + 4)
else
CurrentTable.Filter := Filter;
CurrentTable.Filtered := True;
CurrentTable.Sort := 'BoekDate';
CurrentTable.Last;
CurrentTable.RecNo;
end;
procedure TfrmMain.SetPrintData;
var repHeaderPciture:TfrxPictureView;
repTitle:TfrxMemoView;
repFooter:TfrxMemoView;
reportLogoPath: String;
reportTitle: String;
reportFooter: String;
begin
if objectType='Kasboek' then begin
repHeaderPciture := TfrxPictureView(frxRepKasboek.FindObject('repHeaderPicture'));
repTitle := TfrxMemoView(frxRepKasboek.FindObject('mmTitle'));
repFooter := TfrxMemoView(frxRepKasboek.FindObject('mmFooter'));
end
else if objectType='Alles' then begin
repHeaderPciture := TfrxPictureView(frxRepAll.FindObject('repHeaderPicture'));
repTitle := TfrxMemoView(frxRepAll.FindObject('mmTitle'));
repFooter := TfrxMemoView(frxRepAll.FindObject('mmFooter'));
end
else begin
repHeaderPciture := TfrxPictureView(frxRepBankBoek.FindObject('repHeaderPicture'));
repTitle := TfrxMemoView(frxRepBankBoek.FindObject('mmTitle'));
repFooter := TfrxMemoView(frxRepBankBoek.FindObject('mmFooter'));
end;
reportLogoPath := Inifile.ReadString('report','background','');
reportTitle := Inifile.ReadString('report','title','Jaarrekening');
reportFooter := Inifile.ReadString('report','footer','');
if not(reportLogoPath ='') then begin
repHeaderPciture.Picture.LoadFromFile(reportLogoPath);
end;
repTitle.Memo.Text := reportTitle;
repFooter.Memo.Text := reportFooter;
end;
procedure TfrmMain.ShowSaldo(TotalInkomen: Double; TotalUitgaven: Double);
begin
if (TotalInkomen - TotalUitgaven) > 0 then
LblSaldo.Font.Color := clWhite
else
LblSaldo.Font.Color := $000F0FFF;
LblSaldo.Caption := 'Inkomen : ' + FloatToStrF(TotalInkomen, ffCurrency, 8, 2)
+ ' Uitgaven : ' + FloatToStrF(TotalUitgaven, ffCurrency, 8, 2) +
' SALDO : ' + FloatToStrF(TotalInkomen - TotalUitgaven,
ffCurrency, 8, 2);
end;
procedure TfrmMain.UncheckAll(button: TToolButton);
begin
btnKas.Down := False;
btnBegin.Down := False;
btnAlles.Down := False;
button.Down := True;
end;
end.
|
{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J+,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
unit SingleInstance;
interface
uses
Classes, SysUtils;
type
TOneTimeDataObserver = class (TObject)
private
FEnabled: Boolean;
FOnUpdate: TNotifyEvent;
procedure SetOnUpdate(const Value: TNotifyEvent);
public
constructor Create (anEvent: TNotifyEvent);
procedure Update;
published
property Enabled: Boolean read FEnabled write FEnabled;
property OnUpdate: TNotifyEvent read FOnUpdate write SetOnUpdate;
end;
TOneTimeData = class (TObject)
private
FGlobalCount: Integer;
FObservers: TList;
procedure SetGlobalCount(const Value: Integer);
protected
constructor CreateInstance;
class function AccessInstance(Request: Integer): TOneTimeData;
public
constructor Create;
destructor Destroy; override;
class function Instance: TOneTimeData;
procedure RegisterObserver(Observer: TOneTimeDataObserver);
procedure PublishToObservers;
class procedure ReleaseInstance;
procedure UnregisterObserver(Observer: TOneTimeDataObserver);
property GlobalCount: Integer read FGlobalCount write SetGlobalCount;
end;
implementation
{ OneTimeData }
{
********************************* TOneTimeData *********************************
}
constructor TOneTimeData.Create;
begin
inherited Create;
raise Exception.CreateFmt('Access class %s through Instance only',
[ClassName]);
end;
constructor TOneTimeData.CreateInstance;
begin
inherited Create;
FObservers := TList.Create;
end;
destructor TOneTimeData.Destroy;
begin
if AccessInstance(0) = Self then AccessInstance(2);
inherited Destroy;
end;
class function TOneTimeData.AccessInstance(Request: Integer): TOneTimeData;
const FInstance: TOneTimeData = nil;
begin
case Request of
0 : ;
1 : if not Assigned(FInstance) then FInstance := CreateInstance;
2 : FInstance := nil;
else
raise Exception.CreateFmt('Illegal request %d in AccessInstance',
[Request]);
end;
Result := FInstance;
end;
class function TOneTimeData.Instance: TOneTimeData;
begin
Result := AccessInstance(1);
end;
procedure TOneTimeData.RegisterObserver(Observer: TOneTimeDataObserver);
begin
if FObservers.IndexOf(Observer) = -1 then
FObservers.Add(Observer);
end;
class procedure TOneTimeData.ReleaseInstance;
begin
AccessInstance(0).Free;
end;
procedure TOneTimeData.SetGlobalCount(const Value: Integer);
begin
FGlobalCount := Value;
PublishToObservers;
end;
procedure TOneTimeData.UnregisterObserver(Observer: TOneTimeDataObserver);
begin
FObservers.Remove(Observer);
end;
{ TOneTimeDataObserver }
constructor TOneTimeDataObserver.Create(anEvent: TNotifyEvent);
begin
fOnUpdate := anEvent;
end;
procedure TOneTimeDataObserver.SetOnUpdate(const Value: TNotifyEvent);
begin
FOnUpdate := Value;
end;
procedure TOneTimeDataObserver.Update;
begin
if Assigned (fOnUpdate) then
fOnUpdate (self);
end;
procedure TOneTimeData.PublishToObservers;
var
I: Integer;
begin
for I := 0 to FObservers.Count - 1 do
TOneTimeDataObserver(FObservers [i]).Update;
end;
end.
|
unit uPareto;
interface
uses
System.Math,
System.Generics.Collections,
Generics.Defaults;
type
{$M+}
TBasePareItem<T> = Class
private
FA: T;
FB: T;
FTag: T;
public
Constructor Create(Const A, B: T); Virtual;
published
property A: T read FA write FA;
property B: T read FB write FB;
property Tag: T read FTag write FTag;
End;
TWebItems = TArray<TBasePareItem<Integer>>;
TParetoItem = Class(TBasePareItem<Single>)
private
FName: String;
public
Constructor Create(Const A, B: Single; Const Name: String);
published
property Name: String read FName write FName;
End;
TPareto = CLass(TObjectList<TParetoItem>)
private
FMaxA: Boolean;
FMaxB: Boolean;
protected
Class Function FillMapAB(Const Start, Finish: Integer): TWebItems;
public
Class Function WebElement(Const Count: Integer): TWebItems; overload;
Class Function WebElement(Const Values: TArray<Integer>)
: TWebItems; overload;
Function Compare(Const Index1, Index2: Integer): TValueSign;
Function Compress: Integer;
Constructor Create;
destructor Destroy; override;
public
property MaxA: Boolean read FMaxA write FMaxA default true;
property MaxB: Boolean read FMaxB write FMaxB default true;
End;
implementation
{ TMyClass }
function TPareto.Compare(const Index1, Index2: Integer): TValueSign;
var
Coeff1, Coeff2: SmallInt;
begin
Coeff1 := CompareValue(Items[Index1].A, Items[Index2].A);
Coeff2 := CompareValue(Items[Index1].B, Items[Index2].B);
if NOT MaxA then
Coeff1 := Coeff1 * -1;
if NOT MaxB then
Coeff2 := Coeff2 * -1;
Result := (Coeff1 + Coeff2);
if Result > 1 then
Result := 1;
if Result < -1 then
Result := -1;
end;
function TPareto.Compress: Integer;
Var
MAP_COMPRESS: TWebItems;
mapForDelete: TList<Integer>;
I: Integer;
begin
MAP_COMPRESS := WebElement(Self.Count);
mapForDelete := TList<Integer>.Create;
try
for I := Low(MAP_COMPRESS) to High(MAP_COMPRESS) do
if Compare(MAP_COMPRESS[I].A, MAP_COMPRESS[I].B) > 0 then
Begin
if NOT mapForDelete.Contains(MAP_COMPRESS[I].B) then
mapForDelete.Add(MAP_COMPRESS[I].B);
End
else if Compare(MAP_COMPRESS[I].A, MAP_COMPRESS[I].B) < 0 then
Begin
if NOT mapForDelete.Contains(MAP_COMPRESS[I].A) then
mapForDelete.Add(MAP_COMPRESS[I].A);
End;
mapForDelete.Sort;
for I := mapForDelete.Count - 1 downTo 0 do
Self.Delete(mapForDelete[I]);
finally
for I := Low(MAP_COMPRESS) to High(MAP_COMPRESS) do
MAP_COMPRESS[I].Free;
mapForDelete.Free;
end;
Result := Count;
end;
constructor TPareto.Create;
begin
inherited Create;
MaxA := true;
MaxB := true;
end;
destructor TPareto.Destroy;
begin
inherited Destroy;
end;
Class function TPareto.FillMapAB(const Start, Finish: Integer): TWebItems;
var
I, j: Integer;
begin
SetLength(Result, (Finish - Start));
j := low(Result);
for I := Start + 1 to Finish do
Begin
Result[j] := TBasePareItem<Integer>.Create(Start, I);
Inc(j);
End;
end;
class function TPareto.WebElement(const Values: TArray<Integer>): TWebItems;
Var
IndexPath: TArray<TBasePareItem<Integer>>;
I: Integer;
begin
try
IndexPath := WebElement(Length(Values));
SetLength(Result, Length(IndexPath));
for I := Low(Result) to High(Result) do
Result[I] := TBasePareItem<Integer>.Create(Values[IndexPath[I].A],
Values[IndexPath[I].B]);
finally
for I := Low(IndexPath) to High(IndexPath) do
IndexPath[I].Free;
end;
end;
Class function TPareto.WebElement(const Count: Integer): TWebItems;
var
I: Integer;
begin
Result := [];
for I := 0 to Count - 1 do
Result := Result + FillMapAB(I, Count - 1);
end;
{ TBasePareItem<T> }
constructor TBasePareItem<T>.Create(const A, B: T);
begin
Self.A := A;
Self.B := B;
end;
{ TParetoItem<T> }
constructor TParetoItem.Create(const A, B: Single; const Name: String);
begin
Self.A := A;
Self.B := B;
Self.Name := Name;
end;
end.
|
unit uCadPessoa;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uTelaHeranca, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.DBCtrls, Vcl.Grids,
Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, Vcl.ExtCtrls, Vcl.ComCtrls,
cCadPessoa, RxToolEdit, uDTMConexao, uEnum, Vcl.Menus,cFuncao,
Vcl.Imaging.jpeg, Vcl.ExtDlgs, uDWResponseTranslator, uDWAbout, uDWConstsData,
uRESTDWPoolerDB;
type
TfrmCadPessoa = class(TfrmTelaheranca)
grpDatas: TGroupBox;
lbl1: TLabel;
lbl1btespirito: TLabel;
lblMembroCongregado: TLabel;
lblbtaguas: TLabel;
dtdtBtaguas: TDateEdit;
dtdtbtespirito: TDateEdit;
dtdtConversao: TDateEdit;
dtdtMembroCongregado: TDateEdit;
grpEscolaridade: TGroupBox;
cbbAcademica: TComboBox;
lbl3: TLabel;
lbl4: TLabel;
cbbSitAcad: TComboBox;
lbl5: TLabel;
lbl6: TLabel;
cbbFormTeo: TComboBox;
lbl7: TLabel;
lbl8: TLabel;
cbbSitformteo: TComboBox;
lbledtOrigecles: TLabeledEdit;
lbledtProcedeclesi: TLabeledEdit;
grpCivil: TGroupBox;
cbbEstdCivil: TComboBox;
lbl9: TLabel;
cbbEstcivianterior: TComboBox;
lbl10: TLabel;
lbledtNomeConjugue: TLabeledEdit;
dtdtCasamento: TDateEdit;
lbl11: TLabel;
grpResidencia: TGroupBox;
lbledtEmail: TLabeledEdit;
lbledtBairro: TLabeledEdit;
lbledtEndereco: TLabeledEdit;
lbledtCidade: TLabeledEdit;
lblCEP: TLabel;
medtCEP: TMaskEdit;
lblTelefone: TLabel;
medtTelefoneCel: TMaskEdit;
lbledtComplemento: TLabeledEdit;
cbbEstadoImovel: TComboBox;
lbl12: TLabel;
cbbUfImovel: TComboBox;
lbl13: TLabel;
lbl14: TLabel;
medtTelFixo: TMaskEdit;
grpProfissional: TGroupBox;
lbledtProfissao: TLabeledEdit;
lbledtHabprof: TLabeledEdit;
lbledtEmpregoAtual: TLabeledEdit;
lbledtFuncao: TLabeledEdit;
lbl15: TLabel;
medtTeltrabalho: TMaskEdit;
pnlImagem: TPanel;
imgFoto: TImage;
QryListagemcod_pessoa: TFDAutoIncField;
QryListagemnome_pessoa: TStringField;
QryListagemfoto: TBlobField;
QryListagemsexo: TStringField;
QryListagemnome_pai: TStringField;
QryListagemnome_mae: TStringField;
QryListagemdta_nascimento: TDateField;
QryListagemnaturalidade: TStringField;
QryListagemuf_nascimento: TStringField;
QryListagemnacionalidade: TStringField;
QryListagemnrorg: TStringField;
QryListagemorgaorg: TStringField;
QryListagemcpf: TStringField;
QryListagememail: TStringField;
QryListagemgrau_instr_situacao: TStringField;
QryListagemgrau_instrucao: TStringField;
QryListagemform_teo_situacao: TStringField;
QryListagemformacao_teologica: TStringField;
QryListagemestado_civil_atual: TStringField;
QryListagemestado_civil_anterior: TStringField;
QryListagemnome_conjugue: TStringField;
QryListagemdta_casamento: TDateField;
QryListagemlogradouro: TStringField;
QryListagemuf_endereco: TStringField;
QryListagemestado_casa: TStringField;
QryListagemcomplemento: TStringField;
QryListagemfone_residencial: TStringField;
QryListagembairro: TStringField;
QryListagemcep: TStringField;
QryListagemcidade: TStringField;
QryListagemfone_celular: TStringField;
QryListagemdta_conversao: TDateField;
QryListagemdta_batismo_esprito: TDateField;
QryListagemdta_batismo_aguas: TDateField;
QryListagemdta_congregado: TDateField;
QryListagemlocal_descisao_congregado: TStringField;
QryListagemdta_membro: TDateField;
QryListagemorigem_eclesiastica: TStringField;
QryListagemproced_eclesiastica: TStringField;
QryListagemprofissao: TStringField;
QryListagemhabilitacao_profissional: TStringField;
QryListagememprego_atual: TStringField;
QryListagemfuncao: TStringField;
QryListagemfone_trabalho: TStringField;
QryListagemigreja: TStringField;
QryListagemsetor: TStringField;
QryListagemcongregacao: TStringField;
QryListagemnro_rol: TStringField;
QryListagemnro_cad_congregado: TStringField;
QryListagemmembro_congregado: TStringField;
QryListagemdta_inclusao: TDateField;
QryListagemUSUARIO_CADASTRO: TStringField;
QryListagemSITUACAO: TStringField;
QryListagemcod_congregacao: TIntegerField;
QryListagemcod_situacao: TIntegerField;
dlgOpenPicBuscarFoto: TOpenPictureDialog;
pnl1: TPanel;
imgFotoP: TImage;
lblnome: TLabel;
lblEstadoCivil: TLabel;
lbl16: TLabel;
btnConsultaCEP: TSpeedButton;
dwGetCEP: TRESTDWClientSQL;
DWResponseTranslatorCEP: TDWResponseTranslator;
DWClientRESTCEP: TDWClientREST;
pnlBasicas: TPanel;
lbledt_codigo: TLabeledEdit;
lbledtNome: TLabeledEdit;
cbbMembCong: TComboBox;
cbbSexo: TComboBox;
lbledtRol: TLabeledEdit;
lblSexo: TLabel;
lblTipo: TLabel;
lbledtNatural: TLabeledEdit;
cbbUFnascimento: TComboBox;
lblufnascimento: TLabel;
medtCPF: TMaskEdit;
lbledtRG: TLabeledEdit;
lbledtNacionalidade: TLabeledEdit;
lbledtNomeMae: TLabeledEdit;
lbledtNomePai: TLabeledEdit;
lblDataNascimento: TLabel;
dtdtNascimento: TDateEdit;
lblcpf: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnNovoClick(Sender: TObject);
procedure grdListagemKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbbMembCongChange(Sender: TObject);
procedure mniLimparImagem1Click(Sender: TObject);
procedure mniCarregarImagem1Click(Sender: TObject);
procedure pgcPrincipalChange(Sender: TObject);
procedure imgFotoDblClick(Sender: TObject);
procedure dtsListagemDataChange(Sender: TObject; Field: TField);
procedure grdListagemCellClick(Column: TColumn);
procedure grdListagemTitleClick(Column: TColumn);
procedure btnGravarClick(Sender: TObject);
procedure btnConsultaCEPClick(Sender: TObject);
procedure DWClientRESTCEPBeforeGet(var AUrl: string;
var AHeaders: TStringList);
procedure medtCPFExit(Sender: TObject);
private
{ Private declarations }
oPessoa: TPessoa;
function Apagar: Boolean; override;
function Gravar(EstadodoCadastro: TEstadoDoCadastro): Boolean; override;
procedure Tipo;
public
{ Public declarations }
end;
var
frmCadPessoa: TfrmCadPessoa;
implementation
{$R *.dfm}
{$REGION 'Override'}
function TfrmCadPessoa.Apagar: Boolean;
begin
if oPessoa.Selecionar(QryListagem.FieldByName('cod_pessoa').AsInteger) then
Result := oPessoa.Apagar;
end;
function TfrmCadPessoa.Gravar(EstadodoCadastro: TEstadoDoCadastro): Boolean;
var jpg : TJPEGImage;
begin
if lbledt_codigo.Text <> EmptyStr then
oPessoa.cod_pessoa := StrToInt(lbledt_codigo.Text)
else
oPessoa.cod_pessoa := 0;
oPessoa.nome := lbledtNome.Text;
oPessoa.nome_pai := lbledtNomePai.Text;
oPessoa.nome_mae := lbledtNomeMae.Text;
oPessoa.sexo := cbbSexo.Text;
oPessoa.dta_nascimento := dtdtNascimento.Date;
oPessoa.cod_congregacao := dtmPrincipal.congAtiva;
oPessoa.nro_rol := StrToInt(lbledtRol.Text);
oPessoa.nrorg := lbledtRG.Text;
oPessoa.nacionalidade := lbledtNacionalidade.Text;
oPessoa.naturalidade := lbledtNatural.Text;
oPessoa.dta_casamento := dtdtCasamento.Date;
oPessoa.dta_conversao :=dtdtConversao.Date;
oPessoa.dta_batismo_esprito :=dtdtbtespirito.Date;
oPessoa.dta_batismo_aguas :=dtdtBtaguas.Date;
oPessoa.cep := medtCEP.Text;
oPessoa.logradouro := lbledtEndereco.Text;
oPessoa.bairro := lbledtBairro.Text;
oPessoa.cidade := lbledtCidade.Text;
oPessoa.fone_celular := medtTelefoneCel.Text;
oPessoa.fone_residecial := medtTelFixo.Text;
oPessoa.fone_trabalho := medtTeltrabalho.Text;
oPessoa.membro_congregado := cbbMembCong.Text;
oPessoa.cpf := medtCPF.Text;
oPessoa.funcao := lbledtFuncao.Text;
oPessoa.uf_nascimento := cbbUFnascimento.Text;
oPessoa.uf_endereco := cbbUfImovel.Text;
oPessoa.congregacao := dtmPrincipal.descCongAtiva;
oPessoa.setor :=dtmPrincipal.setor;
oPessoa.estado_civil_atual := cbbEstdCivil.Text;
oPessoa.estado_civil_anterior:=cbbEstcivianterior.Text;
oPessoa.nome_conjugue :=lbledtNomeConjugue.Text;
oPessoa.email := lbledtEmail.Text;
oPessoa.profissao:= lbledtProfissao.Text;
oPessoa.habilitacao_profissional := lbledtHabprof.Text;
oPessoa.emprego_atual := lbledtEmpregoAtual.Text;
oPessoa.funcao := lbledtFuncao.Text;
oPessoa.grau_instrucao :=cbbAcademica.Text;
oPessoa.grau_inst_situacao := cbbSitAcad.Text;
oPessoa.formacao_teologica := cbbFormTeo.Text;
oPessoa.form_teo_situacao := cbbSitformteo.Text;
oPessoa.origem_eclesiastica :=lbledtOrigecles.Text;
oPessoa.proced_eclesiastica :=lbledtProcedeclesi.Text;
if cbbMembCong.Text ='CONGREGADO' then
oPessoa.dta_congregado :=dtdtMembroCongregado.Date else
oPessoa.dta_membro :=dtdtMembroCongregado.Date;
//jpg.LoadFromFile(imgFoto.Picture.Bitmap);
if imgFoto.Picture.Bitmap.Empty then
begin
oPessoa.foto.Assign(nil)
//imgFoto.Picture.LoadFromFile('C:\mysql\img\semfoto.jpg');
end
else
begin
oPessoa.foto.Assign(imgFoto.Picture);
end;
if (EstadodoCadastro = ecInserir) then
Result := oPessoa.Inserir
else if (EstadodoCadastro = ecAlterar) then
Result := oPessoa.Atualizar;
end;
procedure TfrmCadPessoa.grdListagemCellClick(Column: TColumn);
var jpg1 : TJPEGImage;
stream : TMemoryStream;
caminho: AnsiString;
begin
inherited;
lblnome.Caption:= QryListagemnome_pessoa.Text;
lblEstadoCivil.Caption:= 'Estado Civíl:'+QryListagemestado_civil_atual.Text ;
//ARQUIVO BINARIOS AUDIO, VIDEO E FOTOS
begin
inherited;
if not QryListagemfoto.IsNull then
BEGIN
try
// ALOCANDO ESPAÇO NA MEMORIA RAM
jpg1:= TJPEGImage.Create;
stream:= TMemoryStream.Create;
//CARREGANDO A IMAGEM PARA A MEMORIA RAM
QryListagemfoto.SaveToStream(stream);
//VOLTANDO O PONTEIRO PARA O INICIO DOS DADOS
stream.Seek(0, soFromBeginning);
//GRANDO A INFORMAÇÃO NA JPG
jpg1.LoadFromStream(stream);
//CARREGANDO A IMAGEM NO IMAGE
imgFotoP.Picture.Assign(jpg1);
//LIBERANDO MEMORIA APAGANDO AS INSTANCIAS
jpg1.Free;
stream.Free;
except
on e : Exception do begin
jpg1.Free;
stream.Free;
MessageBox(Application.Handle, PChar(e.Message),PChar('Falha ao carregar a imagem da Igreja'),MB_OK+MB_ICONWARNING);
end;
end;
END
else
begin
// caminho:=(ExtractFilePath(Application.ExeName) + 'semfoto.jpg');
caminho :='C:\mysql\img\semfoto.jpg';
imgFotoP.Picture.LoadFromFile(caminho);
//imgFoto.Picture.LoadFromFile('C:\Program Files (x86)\Eltecom\semfoto.jpg');
//imgFoto.Picture.Assign(nil);
end;
end;
end;
procedure TfrmCadPessoa.grdListagemKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var jpg1 : TJPEGImage;
stream : TMemoryStream;
caminho: AnsiString;
begin
inherited;
BloqueiaCTRL_DEL_DBGRID(Key,Shift);
lblnome.Caption:= QryListagemnome_pessoa.Text;
lblEstadoCivil.Caption:= 'Estado Civíl:'+QryListagemestado_civil_atual.Text;
//ARQUIVO BINARIOS AUDIO, VIDEO E FOTOS
begin
inherited;
if not QryListagemfoto.IsNull then
BEGIN
try
// ALOCANDO ESPAÇO NA MEMORIA RAM
jpg1:= TJPEGImage.Create;
stream:= TMemoryStream.Create;
//CARREGANDO A IMAGEM PARA A MEMORIA RAM
QryListagemfoto.SaveToStream(stream);
//VOLTANDO O PONTEIRO PARA O INICIO DOS DADOS
stream.Seek(0, soFromBeginning);
//GRANDO A INFORMAÇÃO NA JPG
jpg1.LoadFromStream(stream);
//CARREGANDO A IMAGEM NO IMAGE
imgFotoP.Picture.Assign(jpg1);
//LIBERANDO MEMORIA APAGANDO AS INSTANCIAS
jpg1.Free;
stream.Free;
except
on e : Exception do begin
jpg1.Free;
stream.Free;
MessageBox(Application.Handle, PChar(e.Message),PChar('Falha ao carregar a imagem da Igreja'),MB_OK+MB_ICONWARNING);
end;
end;
END
else
begin
// caminho:=(ExtractFilePath(Application.ExeName) + 'semfoto.jpg');
caminho :='C:\mysql\img\semfoto.jpg';
imgFotoP.Picture.LoadFromFile(caminho);
//imgFoto.Picture.LoadFromFile('C:\Program Files (x86)\Eltecom\semfoto.jpg');
//imgFoto.Picture.Assign(nil);
end;
end;
end;
procedure TfrmCadPessoa.grdListagemTitleClick(Column: TColumn);
begin
inherited;
lblnome.Caption:= QryListagemnome_pessoa.Text;
lblEstadoCivil.Caption:= 'Estado Civíl:'+QryListagemestado_civil_atual.Text;
end;
procedure TfrmCadPessoa.imgFotoDblClick(Sender: TObject);
var jpg : TJPEGImage;
foto_stream : TMemoryStream;
begin
inherited;
if dlgOpenPicBuscarFoto.Execute then
begin
foto_stream := TMemoryStream.Create;
foto_stream.Clear;
foto_stream.LoadFromFile( dlgOpenPicBuscarFoto.FileName );
if ( foto_stream.Size < 200000 ) then begin
imgFoto.Picture.LoadFromFile( dlgOpenPicBuscarFoto.FileName );
end else begin
showMessage( 'Tamanho da imagem excedeu 200Kb' );
Abort;
end;
{imgFoto.Picture.LoadFromFile(dlgOpenPicBuscarFoto.FileName);
//Label1.Caption := Format('%dx%d', [imgFoto.Picture.Height, imgFoto.Picture.Width]);
if (imgFoto.Picture.Height > 200) and (imgFoto.Picture.Width > 200) then
begin
imgFoto.Picture := nil;
ShowMessage('Imagem maior do que o esperado');
end; }
try
dtsListagem.Edit;
jpg:= TJPEGImage.Create;
// dtmcon.fdqryMembroFOTO.
QryListagemfoto.LoadFromFile(dlgOpenPicBuscarFoto.FileName);
//dtmcon.fdqryMembroFOTO.LoadFromFile(dlgOpenPicBuscarFoto.FileName);
jpg.CompressionQuality :=7;
jpg.LoadFromFile(dlgOpenPicBuscarFoto.FileName);
imgFoto.Picture.Assign(jpg);
jpg.Free;
except
on E: Exception do begin
jpg.Free;
Application.MessageBox('Arquivo não permitido!','Atenção');
end;
end;
end;
end;
procedure TfrmCadPessoa.medtCPFExit(Sender: TObject);
var qry:TFDQuery;
qtd :Integer;
begin
inherited;
//TODO: CONSULTAR SE O CPF INFORMADO JÁ EXISTE NA BASE
if medtCPF.Text <> ' . . - ' then begin
qtd := StrToInt(dtmPrincipal.ConexaoDB.ExecSQLScalar('SELECT COUNT(*) AS QTD FROM TB_PESSOA WHERE CPF=:CPF',[medtCPF.Text]));
if qtd > 0 then begin
ShowMessage('CPF informado já está cadastrado! Favor verificar: '+medtCPF.Text);
medtCPF.Clear;
medtCPF.SetFocus;
end;
end;
end;
procedure TfrmCadPessoa.mniCarregarImagem1Click(Sender: TObject);
begin
inherited;
TFuncao.CarregarImagem(imgFoto);
end;
procedure TfrmCadPessoa.mniLimparImagem1Click(Sender: TObject);
begin
inherited;
TFuncao.LimparImagem(imgFoto);
end;
procedure TfrmCadPessoa.pgcPrincipalChange(Sender: TObject);
begin
inherited;
end;
{$ENDREGION}
procedure TfrmCadPessoa.btnAlterarClick(Sender: TObject);
var JPG: TImage;
begin
if oPessoa.Selecionar(QryListagem.FieldByName('cod_pessoa').AsInteger) then
begin
lbledt_codigo.Text := IntToStr(oPessoa.cod_pessoa);
lbledtNome.Text := oPessoa.nome;
lbledtCidade.Text := oPessoa.cidade;
lbledtEmail.Text := oPessoa.email;
lbledtBairro.Text := oPessoa.bairro;
lbledtEndereco.Text := oPessoa.logradouro;
lbledtNomePai.Text := oPessoa.nome_pai;
lbledtNomeMae.Text := oPessoa.nome_mae;
medtTelFixo.Text := oPessoa.fone_residecial;
medtTelefoneCel.Text := oPessoa.fone_celular;
medtTeltrabalho.Text := oPessoa.fone_trabalho;
cbbSexo.Text := oPessoa.sexo;
cbbUFnascimento.Text := oPessoa.uf_nascimento;
cbbUfImovel.Text := oPessoa.uf_endereco;
cbbMembCong.Text := oPessoa.membro_congregado;
lbledtRG.Text := oPessoa.nrorg;
lbledtNatural.Text := oPessoa.naturalidade;
lbledtNacionalidade.Text:=oPessoa.nacionalidade;
lbledtRol.Text :=IntToStr(oPessoa.nro_rol);
medtCEP.Text := oPessoa.cep;
lbledtProfissao.Text :=oPessoa.profissao;
lbledtHabprof.Text :=oPessoa.habilitacao_profissional;
lbledtEmpregoAtual.Text :=oPessoa.emprego_atual;
lbledtFuncao.Text:=oPessoa.funcao;
cbbAcademica.Text:= oPessoa.grau_instrucao;
cbbSitAcad.Text:=oPessoa.SITUACAO;
cbbFormTeo.Text:=oPessoa.formacao_teologica;
cbbSitformteo.Text:=oPessoa.form_teo_situacao;
lbledtOrigecles.Text:=oPessoa.origem_eclesiastica;
lbledtProcedeclesi.Text:=oPessoa.proced_eclesiastica;
if DateToStr(oPessoa.dta_nascimento)='30/12/1899' then
dtdtNascimento.Clear else dtdtNascimento.Text :=DateToStr(oPessoa.dta_nascimento) ;
if DateToStr(oPessoa.dta_batismo_aguas)='30/12/1899' then
dtdtBtaguas.Clear else dtdtBtaguas.Text :=DateToStr(oPessoa.dta_batismo_aguas) ;
if DateToStr(oPessoa.dta_batismo_esprito)='30/12/1899' then
dtdtbtespirito.Clear else dtdtbtespirito.Text :=DateToStr(oPessoa.dta_batismo_esprito) ;
if DateToStr(oPessoa.dta_conversao)='30/12/1899' then
dtdtConversao.Clear else dtdtConversao.Text :=DateToStr(oPessoa.dta_conversao) ;
if DateToStr(oPessoa.dta_casamento)='30/12/1899' then
dtdtCasamento.Clear else dtdtCasamento.Text :=DateToStr(oPessoa.dta_casamento) ;
if DateToStr(oPessoa.dta_membro)='30/12/1899' then
dtdtMembroCongregado.Clear else dtdtMembroCongregado.Text :=DateToStr(oPessoa.dta_membro) ;
dtdtMembroCongregado.Text :=DateToStr(oPessoa.dta_membro);
if cbbMembCong.Text ='CONGREGADO' then
begin
if DateToStr(oPessoa.dta_membro)='30/12/1899' then
dtdtMembroCongregado.Clear else dtdtMembroCongregado.Text :=DateToStr(oPessoa.dta_congregado) ;
dtdtMembroCongregado.Text :=DateToStr(oPessoa.dta_congregado);
end;
dtdtMembroCongregado.Text :=DateToStr(oPessoa.dta_membro);
//dtdtMembro.Text :=DateToStr(oPessoa.dta_congregado);
medtCPF.Text := oPessoa.cpf;
lbledtNomeConjugue.Text:= oPessoa.nome_conjugue;
lbledtFuncao.Text := oPessoa.funcao;
cbbSitAcad.Text := oPessoa.grau_inst_situacao;
cbbAcademica.Text := oPessoa.grau_instrucao;
cbbFormTeo.Text := oPessoa.formacao_teologica;
cbbSitformteo.Text := oPessoa.form_teo_situacao;
cbbEstdCivil.Text :=oPessoa.estado_civil_atual;
cbbEstcivianterior.Text :=oPessoa.estado_civil_anterior;
lbledtNomeConjugue.Text :=oPessoa.nome_conjugue;
//imgFoto.Picture.Assign(oPessoa.foto);
{ if oPessoa.foto.Empty then
//if oPessoa.foto. then
//imgFoto.Picture.Assign(JPG)
imgFoto.Picture.LoadFromFile('C:\mysql\img\semfoto.jpg')
else
imgFoto.Picture.Assign(oPessoa.foto); }
// cbbEstdCivil.Text := oPessoa.
// :=
{
cbbEstcivianterior.Text
cbbSitAcad.Text
cbbFormTeo.Text
lbledtOrigecles.Text
lbledtProcedeclesi.Text }
end
else
begin
btnCancelar.Click;
Abort;
end;
inherited;
end;
procedure TfrmCadPessoa.btnConsultaCEPClick(Sender: TObject);
begin
inherited;
if Length(medtCEP.Text) = 8 then
begin
Screen.Cursor := crSQLWait;
dwGetCEP.Close;
dwGetCEP.Open;
if (dwGetCEP.FieldCount > 1) then
begin
{
https://viacep.com.br/ws/%s/json/
"cep": "88801-530",
"logradouro": "Rua João Pessoa",
"complemento": "até 743/744",
"bairro": "Centro",
"localidade": "Criciúma",
"uf": "SC",
"unidade": "",
"ibge": "4204608",
"gia": ""
}
lbledtEndereco.Text := dwGetCEP.FieldByName('logradouro').AsString;
lbledtComplemento.Text := dwGetCEP.FieldByName('complemento').AsString;
lbledtBairro.Text := dwGetCEP.FieldByName('bairro').AsString;
lbledtCidade.Text := dwGetCEP.FieldByName('localidade').AsString;
cbbUfImovel.ItemIndex := cbbUfImovel.Items.IndexOf(dwGetCEP.FieldByName('uf').AsString);
end
else
ShowMessage('CEP não encontrado!');
Screen.Cursor := crDefault;
end
else
ShowMessage('CEP inválido, verifique!'+medtCEP.Text);
end;
procedure TfrmCadPessoa.btnGravarClick(Sender: TObject);
begin
inherited;
imgFoto.Enabled:=true;
end;
procedure TfrmCadPessoa.btnNovoClick(Sender: TObject);
begin
inherited;
dtdtNascimento.Date := Date;
lbledtNome.SetFocus;
cbbMembCong.ItemIndex:=0;
imgFoto.Enabled:=false;
end;
procedure TfrmCadPessoa.cbbMembCongChange(Sender: TObject);
begin
inherited;
Tipo;
end;
procedure TfrmCadPessoa.dtsListagemDataChange(Sender: TObject; Field: TField);
var jpg1 : TJPEGImage;
stream : TMemoryStream;
caminho: AnsiString;
//ARQUIVO BINARIOS AUDIO, VIDEO E FOTOS
begin
inherited;
if not QryListagemfoto.IsNull then
BEGIN
try
// ALOCANDO ESPAÇO NA MEMORIA RAM
jpg1:= TJPEGImage.Create;
stream:= TMemoryStream.Create;
//CARREGANDO A IMAGEM PARA A MEMORIA RAM
QryListagemfoto.SaveToStream(stream);
//VOLTANDO O PONTEIRO PARA O INICIO DOS DADOS
stream.Seek(0, soFromBeginning);
//GRANDO A INFORMAÇÃO NA JPG
jpg1.LoadFromStream(stream);
//CARREGANDO A IMAGEM NO IMAGE
imgFoto.Picture.Assign(jpg1);
//LIBERANDO MEMORIA APAGANDO AS INSTANCIAS
jpg1.Free;
stream.Free;
except
on e : Exception do begin
jpg1.Free;
stream.Free;
MessageBox(Application.Handle, PChar(e.Message),PChar('Falha ao carregar a imagem da Igreja'),MB_OK+MB_ICONWARNING);
end;
end;
END
else
begin
// caminho:=(ExtractFilePath(Application.ExeName) + 'semfoto.jpg');
caminho :='C:\mysql\img\semfoto.jpg';
imgFoto.Picture.LoadFromFile(caminho);
//imgFoto.Picture.LoadFromFile('C:\Program Files (x86)\Eltecom\semfoto.jpg');
//imgFoto.Picture.Assign(nil);
end;
end;
procedure TfrmCadPessoa.DWClientRESTCEPBeforeGet(var AUrl: string;
var AHeaders: TStringList);
begin
inherited;
AUrl := format('https://viacep.com.br/ws/%s/json/', [medtCEP.Text]);
end;
procedure TfrmCadPessoa.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if Assigned(oPessoa) then
FreeAndNil(oPessoa);
end;
procedure TfrmCadPessoa.FormCreate(Sender: TObject);
begin
//QryListagem.ParamByName('cod_congregacao').AsInteger:=dtmPrincipal.congAtiva;
inherited;
oPessoa := TPessoa.Create(dtmPrincipal.ConexaoDB);
IndiceAtual := 'cod_pessoa';
end;
procedure TfrmCadPessoa.Tipo;
begin
if cbbMembCong.Text = 'MEMBRO' then
begin
lblMembroCongregado.Caption:= 'Membro desde';
end;
if cbbMembCong.Text ='CONGREGADO' then
begin
lblMembroCongregado.Caption:= 'Congregado desde';
end;
end;
end.
|
unit ConnectionUnit;
interface
uses
Classes, SysUtils, System.JSON, IdURI,
REST.Client, REST.Types, IPPeerCommon, IPPeerClient,
System.Net.HttpClient, System.NetConsts, System.Net.URLClient, System.Net.HttpClient.Win,
IConnectionUnit, GenericParametersUnit, DataObjectUnit, CommonTypesUnit;
type
TConnectionFacade = class
strict private
FClient2: THTTPClient;
FClient: TRESTClient;
FRESTRequest: TRESTRequest;
FRESTResponse: TRESTResponse;
procedure RESTRequest(URL: String; Method: TRESTRequestMethod;
Body: String; ContentType: TRESTContentType;
out Success: boolean; out StatusCode: integer;
out JSONValue: TJsonValue; out ResponseContent: String);
procedure DeleteRequest(URL: String;
Body: String; ContentType: TRESTContentType;
out Success: boolean; out StatusCode: integer;
out JSONValue: TJsonValue; out ResponseContent: String);
public
constructor Create();
destructor Destroy; override;
function ExecuteRequest(URL: String; Method: TRESTRequestMethod;
Body: String; ContentType: TRESTContentType; out ErrorString: String): TJsonValue;
procedure SetProxy(Host: String; Port: integer; Username, Password: String);
end;
TConnection = class(TInterfacedObject, IConnection)
private
FConnection: TConnectionFacade;
FApiKey: String;
function ExecuteRequest(Url: String; Data: TGenericParameters;
Method: TRESTRequestMethod; ResultClassType: TClass;
out ErrorString: String): TObject;
function UrlParameters(Parameters: TListStringPair): String;
protected
function RunRequest(URL: String; Method: TRESTRequestMethod;
Body: String; ContentType: TRESTContentType; out ErrorString: String): TJsonValue; virtual;
public
constructor Create(ApiKey: String);
destructor Destroy; override;
procedure SetProxy(Host: String; Port: integer; Username, Password: String);
function Get(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
function Post(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
function Put(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
function Delete(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
end;
implementation
{ TConnection }
uses SettingsUnit, MarshalUnMarshalUnit, ErrorResponseUnit;
function TConnection.Post(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
begin
Result := ExecuteRequest(Url, Data, rmPOST, ResultClassType, ErrorString);
end;
function TConnection.Put(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
begin
Result := ExecuteRequest(Url, Data, rmPUT, ResultClassType, ErrorString);
end;
constructor TConnection.Create(ApiKey: String);
begin
FApiKey := ApiKey;
FConnection := TConnectionFacade.Create();
end;
function TConnection.Delete(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
begin
Result := ExecuteRequest(Url, Data, rmDELETE, ResultClassType, ErrorString);
end;
destructor TConnection.Destroy;
begin
FreeAndNil(FConnection);
inherited;
end;
function TConnection.Get(Url: String; Data: TGenericParameters;
ResultClassType: TClass; out ErrorString: String): TObject;
begin
Result := ExecuteRequest(Url, Data, rmGET, ResultClassType, ErrorString);
end;
function TConnection.ExecuteRequest(Url: String; Data: TGenericParameters;
Method: TRESTRequestMethod; ResultClassType: TClass;
out ErrorString: String): TObject;
var
Responce: TJSONValue;
Parameters: TListStringPair;
st: TStringList;
Body: String;
Pair: TStringPair;
ContentType: TRESTContentType;
begin
Parameters := Data.Serialize(FApiKey);
try
Body := EmptyStr;
ContentType := TRESTContentType.ctTEXT_PLAIN;
if (Method <> rmGET) then
begin
if (Data.BodyParameters.Count > 0) then
begin
for Pair in Data.BodyParameters do
Body := Body + Pair.Key + '=' + Pair.Value + '&';
System.Delete(Body, Length(Body), 1);
ContentType := TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED;
end
else
Body := Data.ToJsonValue.ToString;
end;
Responce := RunRequest(
Url + UrlParameters(Parameters),
Method, Body, ContentType, ErrorString);
finally
FreeAndNil(Parameters);
end;
if (Responce = nil) then
Result := nil
else
begin
st := TStringList.Create;
st.Text := Responce.ToString;
// st.SaveToFile('d:\post.json');
FreeAndNil(st);
Result := TMarshalUnMarshal.FromJson(ResultClassType, Responce);
end;
end;
function TConnection.RunRequest(URL: String; Method: TRESTRequestMethod;
Body: String; ContentType: TRESTContentType; out ErrorString: String): TJsonValue;
begin
Result := FConnection.ExecuteRequest(URL, Method, Body, ContentType, ErrorString);
end;
procedure TConnection.SetProxy(Host: String; Port: integer; Username, Password: String);
begin
FConnection.SetProxy(Host, Port, Username, Password);
end;
function TConnection.UrlParameters(Parameters: TListStringPair): String;
var
Pair: TStringPair;
begin
Result := EmptyStr;
for Pair in Parameters do
Result := Result + Pair.Key + '=' + EncodeURL(Pair.Value) + '&';
if (Result <> EmptyStr) then
begin
Result := '?' + Result;
System.Delete(Result, Length(Result), 1);
end;
end;
{ TConnectionFacade }
constructor TConnectionFacade.Create;
begin
FRESTResponse := TRESTResponse.Create(nil);
FClient := TRESTClient.Create(nil);
FRESTRequest := TRESTRequest.Create(FClient);
FRESTRequest.Timeout := TSettings.DefaultTimeOutMinutes * 3600;
FRESTRequest.Response := FRESTResponse;
FClient.HandleRedirects := False;
FRESTRequest.HandleRedirects := False;
FClient2 := THttpClient.Create;
FClient2.HandleRedirects := False;
end;
destructor TConnectionFacade.Destroy;
begin
FreeAndNil(FRESTRequest);
FreeAndNil(FClient);
FreeAndNil(FRESTResponse);
FreeAndNil(FClient2);
inherited;
end;
procedure TConnectionFacade.DeleteRequest(URL, Body: String;
ContentType: TRESTContentType; out Success: boolean; out StatusCode: integer;
out JSONValue: TJsonValue; out ResponseContent: String);
var
Request: IHTTPRequest;
AResponseContent: TStream;
ABodyStream: TStream;
Response: IHTTPResponse;
LBuffer: TBytes;
begin
ABodyStream := TStringStream.Create;
try
LBuffer := TEncoding.UTF8.GetBytes(Body);
TStringStream(ABodyStream).WriteData(LBuffer, Length(LBuffer));
ABodyStream.Position := 0;
Request := FClient2.GetRequest(sHTTPMethodDelete, URL);
Request.SourceStream := ABodyStream;
try
AResponseContent := nil;
Response := FClient2.Execute(Request, AResponseContent);
StatusCode := Response.StatusCode;
Success := (StatusCode >= 200) and (StatusCode < 300);
ResponseContent := Response.ContentAsString();
if (ResponseContent <> EmptyStr) then
JSONValue := TJSONObject.ParseJSONValue(ResponseContent)
else
JSONValue := nil;
except
on e: Exception do
raise Exception.Create('DeleteRequest exception: ' + e.Message);
end;
finally
FreeAndNil(ABodyStream);
end;
end;
function TConnectionFacade.ExecuteRequest(URL: String;
Method: TRESTRequestMethod; Body: String; ContentType: TRESTContentType;
out ErrorString: String): TJsonValue;
function GetHeaderValue(Name: String): String;
var
s: String;
begin
Result := EmptyStr;
for s in FRESTResponse.Headers do
if s.StartsWith(Name, True) then
begin
Result := s;
System.Delete(Result, 1, Length(Name) + 1);
Break;
end;
end;
var
ErrorResponse: TErrorResponse;
Error: String;
JsonResponce: TJsonValue;
Success: boolean;
StatusCode: integer;
JSONValue: TJsonValue;
ResponseContent: String;
begin
Result := nil;
ErrorString := EmptyStr;
FClient.BaseURL := URL;
if (Method = TRESTRequestMethod.rmDELETE) and (Body <> EmptyStr) then
DeleteRequest(URL, Body, ContentType,
Success, StatusCode, JSONValue, ResponseContent)
else
RESTRequest(URL, Method, Body, ContentType,
Success, StatusCode, JSONValue, ResponseContent);
if (Success) then
Result := JSONValue
else
if (StatusCode = 303) then
Result := ExecuteRequest(
GetHeaderValue('Location'), TRESTRequestMethod.rmGET, EmptyStr, ContentType, ErrorString)
else
begin
ErrorString := EmptyStr;
JsonResponce := TJSONObject.ParseJSONValue(ResponseContent);
if (JsonResponce <> nil) then
begin
ErrorResponse := TMarshalUnMarshal.FromJson(TErrorResponse, JsonResponce) as TErrorResponse;
if (ErrorResponse <> nil) then
for Error in ErrorResponse.Errors do
begin
if (Length(ErrorString) > 0) then
ErrorString := ErrorString + '; ';
ErrorString := ErrorString + Error;
end;
end
else
ErrorString := 'Response: ' + FRESTResponse.StatusText;
end;
end;
procedure TConnectionFacade.RESTRequest(URL: String;
Method: TRESTRequestMethod; Body: String; ContentType: TRESTContentType;
out Success: boolean; out StatusCode: integer; out JSONValue: TJsonValue;
out ResponseContent: String);
begin
FRESTRequest.Client.BaseURL := URL;
FRESTRequest.Method := Method;
FRESTRequest.ClearBody;
FRESTRequest.AddBody(Body, ContentType);
if (ContentType = TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED) then
FRESTRequest.Params[FRESTRequest.Params.Count - 1].Options :=
FRESTRequest.Params[FRESTRequest.Params.Count - 1].Options + [TRESTRequestParameterOption.poDoNotEncode];
FRESTRequest.Execute;
Success := FRESTResponse.Status.Success;
StatusCode := FRESTResponse.StatusCode;
JSONValue := FRESTResponse.JSONValue;
ResponseContent := FRESTResponse.Content;
end;
procedure TConnectionFacade.SetProxy(Host: String; Port: integer; Username,
Password: String);
begin
FClient.ProxyServer := Host;
FClient.ProxyPort := Port;
FClient.ProxyUsername := Username;
FClient.ProxyPassword := Password;
FClient2.ProxySettings := TProxySettings.Create(Host, Port, Username, Password);
end;
end.
|
{ RxViewsPanel unit
Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit RxViewsPanel;
{$I rx.inc}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Buttons, StdCtrls, LCLType;
type
TRxViewsPanel = class;
TRxViewsPanelItem = class;
TSelectViewEvent = procedure (Sender: TObject; ItemIndex:integer; const Item:TRxViewsPanelItem) of object;
{ TRxViewsPanelItem }
TRxViewsPanelItem = class(TCollectionItem)
private
FButton: TSpeedButton;
FImageIndex: integer;
FLabel:TLabel;
function GetAction: TBasicAction;
function GetCaption: string;
function GetEnabled: Boolean;
function GetHint: TTranslateString;
function GetImageIndex: integer;
function GetTag: Longint;
function GetVisible: boolean;
procedure SetAction(const AValue: TBasicAction);
procedure SetCaption(const AValue: string);
procedure SetEnabled(const AValue: Boolean);
procedure SetHint(const AValue: TTranslateString);
procedure SetImageIndex(const AValue: integer);
procedure SetTag(const AValue: Longint);
procedure SetVisible(const AValue: boolean);
procedure UpdatePosition;
procedure UpdateImage;
procedure DoViewButtonClick(Sender:TObject);
protected
function GetDisplayName: string; override;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
published
property Action:TBasicAction read GetAction write SetAction;
property Visible:boolean read GetVisible write SetVisible;
property Caption:string read GetCaption Write SetCaption;
property Tag: Longint read GetTag write SetTag default 0;
property ImageIndex:integer read GetImageIndex write SetImageIndex;
property Hint:TTranslateString read GetHint write SetHint;
property Enabled: Boolean read GetEnabled write SetEnabled default True;
end;
{ TRxViewsPanelItems }
TRxViewsPanelItems = class(TCollection)
private
FRxViewsPanel:TRxViewsPanel;
function GetPanelItem(Index: Integer): TRxViewsPanelItem;
procedure SetPanelItem(Index: Integer; const AValue: TRxViewsPanelItem);
protected
procedure Update(Item: TCollectionItem);override;
public
constructor Create(ARxViewsPanel: TRxViewsPanel);
property Items[Index: Integer]: TRxViewsPanelItem read GetPanelItem write SetPanelItem; default;
procedure UpdateImages;
end;
{ TRxViewsPanel }
TRxViewsPanel = class(TCustomPanel)
private
FButtonHeght: integer;
FImageList: TImageList;
FItemIndex: integer;
FItems:TRxViewsPanelItems;
FOnSelectViewEvent: TSelectViewEvent;
function GetItems: TRxViewsPanelItems;
procedure SetButtonHeght(const AValue: integer);
procedure SetImageList(const AValue: TImageList);
procedure SetItemIndex(const AValue: integer);
procedure SetItems(const AValue: TRxViewsPanelItems);
procedure InternalSelectView(Item:TRxViewsPanelItem);
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Anchors;
property ButtonHeght:integer read FButtonHeght write SetButtonHeght;
property Color default clGrayText;
property Items:TRxViewsPanelItems read GetItems write SetItems;
property ImageList:TImageList read FImageList write SetImageList;
property OnSelectViewEvent:TSelectViewEvent read FOnSelectViewEvent write FOnSelectViewEvent;
property ItemIndex:integer read FItemIndex write SetItemIndex;
property Alignment;
property AutoSize;
property BorderSpacing;
property BevelInner;
property BevelOuter;
property BevelWidth;
property BidiMode;
property BorderWidth;
property BorderStyle;
property Caption;
property ChildSizing;
property ClientHeight;
property ClientWidth;
property Constraints;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property FullRepaint;
property ParentBidiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property UseDockManager default True;
property Visible;
property OnClick;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnGetDockCaption;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
end;
implementation
{ TRxViewsPanel }
function TRxViewsPanel.GetItems: TRxViewsPanelItems;
begin
Result:=FItems;
end;
procedure TRxViewsPanel.SetButtonHeght(const AValue: integer);
var
I:integer;
begin
if FButtonHeght=AValue then exit;
FButtonHeght:=AValue;
for i:=0 to FItems.Count - 1 do
Items[i].FButton.Height:=AValue;
end;
procedure TRxViewsPanel.SetImageList(const AValue: TImageList);
begin
if FImageList=AValue then exit;
FImageList:=AValue;
FItems.UpdateImages;
end;
procedure TRxViewsPanel.SetItemIndex(const AValue: integer);
begin
if FItemIndex=AValue then exit;
if (AValue < 0) or (AValue > FItems.Count - 1) then exit;
FItemIndex:=AValue;
Items[AValue].FButton.Click;
Items[AValue].FButton.Down:=true;
end;
procedure TRxViewsPanel.SetItems(const AValue: TRxViewsPanelItems);
begin
FItems.Assign(AValue);
end;
procedure TRxViewsPanel.InternalSelectView(Item: TRxViewsPanelItem);
begin
FItemIndex:=Item.Index;
if Assigned(FOnSelectViewEvent) then
FOnSelectViewEvent(Self, Item.Index, Item);
end;
procedure TRxViewsPanel.Loaded;
begin
inherited Loaded;
FItems.Update(nil);
FItems.UpdateImages;
if (FItems.Count>0) and (FItemIndex>-1) and (FItemIndex < FItems.Count) then
FItems[FItemIndex].FButton.Down:=true;
end;
constructor TRxViewsPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
BevelOuter:=bvLowered;
Caption:='';
if Assigned(AOwner) then
Align:=alLeft;
Color:=clGrayText;
FItems:=TRxViewsPanelItems.Create(Self);
ControlStyle:=ControlStyle - [csSetCaption, csAcceptsControls];
FButtonHeght:=50;
end;
destructor TRxViewsPanel.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
{ TRxViewsPanelItem }
function TRxViewsPanelItem.GetAction: TBasicAction;
begin
Result:=FButton.Action;
end;
function TRxViewsPanelItem.GetCaption: string;
begin
Result:=FLabel.Caption;
end;
function TRxViewsPanelItem.GetEnabled: Boolean;
begin
Result:=FButton.Enabled;
end;
function TRxViewsPanelItem.GetHint: TTranslateString;
begin
Result:=FButton.Hint;
end;
function TRxViewsPanelItem.GetImageIndex: integer;
begin
{ if Assigned(FButton.Action) then
Result:=FButton.Action.;}
Result:=FImageIndex;
// FButton.Glyph.;
end;
function TRxViewsPanelItem.GetTag: Longint;
begin
Result:=FButton.Tag;
end;
function TRxViewsPanelItem.GetVisible: boolean;
begin
Result:=FButton.Visible;
end;
procedure TRxViewsPanelItem.SetAction(const AValue: TBasicAction);
begin
FButton.Action:=AValue;
end;
procedure TRxViewsPanelItem.SetCaption(const AValue: string);
begin
FLabel.Caption:=AValue;
end;
procedure TRxViewsPanelItem.SetEnabled(const AValue: Boolean);
begin
FButton.Enabled:=AValue;
FLabel.Enabled:=AValue;
end;
procedure TRxViewsPanelItem.SetHint(const AValue: TTranslateString);
begin
FButton.Hint:=AValue;
end;
procedure TRxViewsPanelItem.SetImageIndex(const AValue: integer);
begin
if FImageIndex=AValue then exit;
FImageIndex:=AValue;
UpdateImage;
end;
procedure TRxViewsPanelItem.SetTag(const AValue: Longint);
begin
FButton.Tag:=AValue;
end;
procedure TRxViewsPanelItem.SetVisible(const AValue: boolean);
begin
FButton.Visible:=AValue;
FLabel.Visible:=AValue;
end;
procedure TRxViewsPanelItem.UpdatePosition;
var
PP:TRxViewsPanelItem;
begin
if Index <> 0 then
begin
PP:=TRxViewsPanelItems(Collection).GetPanelItem(Index - 1);
if Assigned(PP.FLabel) then
begin
FButton.Top:=PP.FLabel.Top + PP.FLabel.Height;
end;
end;
FLabel.Top:=FButton.Top + FButton.Height;
end;
procedure TRxViewsPanelItem.UpdateImage;
var
VP:TRxViewsPanel;
begin
VP:=TRxViewsPanelItems(Collection).FRxViewsPanel;
if Assigned(VP.FImageList) then
VP.FImageList.GetBitmap(FImageIndex, FButton.Glyph);
end;
procedure TRxViewsPanelItem.DoViewButtonClick(Sender: TObject);
begin
TRxViewsPanelItems(Collection).FRxViewsPanel.InternalSelectView(Self);
end;
function TRxViewsPanelItem.GetDisplayName: string;
begin
if FLabel.Caption<> '' then
Result:=FLabel.Caption
else
Result:=inherited GetDisplayName;
end;
constructor TRxViewsPanelItem.Create(ACollection: TCollection);
var
VP:TRxViewsPanel;
begin
inherited Create(ACollection);
VP:=TRxViewsPanelItems(ACollection).FRxViewsPanel;
FImageIndex:=-1;
FButton:=TSpeedButton.Create(VP);
// FButton.Align:=alTop;
FButton.ShowCaption:=false;
FButton.Transparent:=true;
FButton.GroupIndex:=1;
FButton.Height:=VP.FButtonHeght;
FButton.Parent:=VP;
FLabel:=TLabel.Create(VP);
// FLabel.Align:=alTop;
FLabel.WordWrap:=true;
FLabel.Alignment:=taCenter;
FLabel.AutoSize:=true;
FLabel.Parent:=VP;
FButton.BorderSpacing.Around:=6;
FLabel.BorderSpacing.Around:=6;
FButton.AnchorSide[akLeft].Control:=VP;
FButton.AnchorSide[akRight].Control:=VP;
FButton.AnchorSide[akRight].Side:=asrBottom;
FButton.Anchors:=[akTop, akLeft, akRight];
FButton.OnClick:=@DoViewButtonClick;
FLabel.AnchorSide[akTop].Control:=FButton;
FLabel.AnchorSide[akLeft].Control:=VP;
FLabel.AnchorSide[akRight].Control:=VP;
FLabel.AnchorSide[akRight].Side:=asrBottom;
FLabel.Anchors:=[akTop, akLeft, akRight];
FLabel.Top:=FButton.Top + FButton.Height;
UpdatePosition;
end;
destructor TRxViewsPanelItem.Destroy;
begin
FreeAndNil(FButton);
FreeAndNil(FLabel);
inherited Destroy;
end;
{ TRxViewsPanelItems }
function TRxViewsPanelItems.GetPanelItem(Index: Integer): TRxViewsPanelItem;
begin
result := TRxViewsPanelItem( inherited Items[Index] );
end;
procedure TRxViewsPanelItems.SetPanelItem(Index: Integer;
const AValue: TRxViewsPanelItem);
begin
Items[Index].Assign( AValue );
end;
procedure TRxViewsPanelItems.Update(Item: TCollectionItem);
var
i:integer;
P, P1:TRxViewsPanelItem;
begin
inherited Update(Item);
if not Assigned(Item) then
begin
for i:=0 to Count - 1 do
begin
P:=GetPanelItem(I);
if Assigned(P.FButton) and Assigned(P.FLabel) then
begin
if i=0 then
begin
P.FButton.AnchorSide[akTop].Control:=FRxViewsPanel;
P.FButton.AnchorSide[akTop].Side:=asrTop;
P.FLabel.AnchorSide[akTop].Control:=P.FButton;
P.FLabel.AnchorSide[akTop].Side:=asrBottom;
end
else
begin
P1:=GetPanelItem(I-1);
if Assigned(P1.FButton) and Assigned(P1.FLabel) then
begin
P.FButton.AnchorSide[akTop].Control:=P1.FLabel;
P.FButton.AnchorSide[akTop].Side:=asrBottom;
P.FLabel.AnchorSide[akTop].Control:=P.FButton;
P.FLabel.AnchorSide[akTop].Side:=asrBottom;
end;
end;
P.FButton.AnchorSide[akLeft].Control:=FRxViewsPanel;
P.FButton.AnchorSide[akRight].Control:=FRxViewsPanel;
P.FButton.AnchorSide[akRight].Side:=asrBottom;
P.FLabel.AnchorSide[akTop].Control:=P.FButton;
P.FLabel.AnchorSide[akLeft].Control:=FRxViewsPanel;
P.FLabel.AnchorSide[akRight].Control:=FRxViewsPanel;
P.FLabel.AnchorSide[akRight].Side:=asrBottom;
end;
end;
end;
end;
constructor TRxViewsPanelItems.Create(ARxViewsPanel: TRxViewsPanel);
begin
inherited Create(TRxViewsPanelItem);
FRxViewsPanel:=ARxViewsPanel;
end;
procedure TRxViewsPanelItems.UpdateImages;
var
i:integer;
begin
for I:=0 to Count - 1 do
Items[i].UpdateImage;
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 Base.System.JsonFiles;
interface
uses System.Classes, System.SysUtils, System.Rtti, System.Json, {Rest.Json,}
System.IOUtils,
System.TypInfo;
type
TMemJsonFile = class
private
FEncoding: TEncoding;
FFileName: string;
FJson: TJsonObject;
FAutoSave: boolean;
FModified: boolean;
procedure SetAutoSave(const Value: boolean);
procedure SetModified(const Value: boolean);
protected
// base
procedure WriteValue(const Section, Ident: string; Value: TValue); virtual;
function ReadValue(const Section, Ident: string; Default: Variant)
: Variant; virtual;
public
procedure LoadValues; virtual;
constructor Create(AFilename: string); overload; virtual;
constructor Create(const AFilename: string; const AEncoding: TEncoding);
overload; virtual;
destructor Destroy; override;
property FileName: string read FFileName;
procedure ReadSection(const Section: string; Strings: TStrings); overload;
function ReadSection(const Section: string): TJsonObject; overload;
function ReadSectionJsonValue(const Section: TJsonObject; Ident: string)
: TJsonValue;
procedure ReadSections(Strings: TStrings); virtual;
procedure ReadSectionValues(const Section: string;
Strings: TStrings); virtual;
procedure WriteString(const Section, Ident: string; Value: string); virtual;
procedure WriteInteger(const Section, Ident: string;
Value: Integer); virtual;
procedure WriteDateTime(const Section, Ident: string;
Value: TDateTime); virtual;
procedure WriteBool(const Section, Ident: string; Value: boolean); virtual;
procedure WriteFloat(const Section, Ident: string; Value: double); virtual;
function ReadString(const Section, Ident, Default: string): string; virtual;
function ReadInteger(const Section, Ident: string; Default: Integer)
: Integer; virtual;
function ReadBool(const Section, Ident: string; Default: boolean)
: boolean; virtual;
function ReadDatetime(const Section, Ident: string; Default: TDateTime)
: TDateTime; virtual;
function ReadFloat(const Section, Ident: string; Default: double)
: double; virtual;
procedure DeleteKey(const Section, Ident: String); virtual;
procedure EraseSection(const Section: string); virtual;
// RTTI
procedure ReadObject(const ASection: string; AObj: TObject);
procedure WriteObject(const ASection: string; AObj: TObject);
procedure Clear;
procedure UpdateFile; virtual;
property Modified: boolean read FModified write SetModified;
property AutoSave: boolean read FAutoSave write SetAutoSave;
// Json
function ToJson: string;
procedure FromJson(AJson: string);
published
end;
TJsonFile = class(TMemJsonFile)
public
procedure UpdateFile; override;
procedure LoadValues; override;
end;
implementation
// System.IniFiles
uses System.DateUtils;
{ TMemJsonFiles }
type
TJsonObjectHelper = class helper for TJsonObject
public
function Find(Section: string): TJsonValue;
end;
TValueHelper = record helper for TValue
private
function IsNumeric: boolean;
function IsInteger: boolean;
function IsDate: boolean;
function IsDateTime: boolean;
function IsBoolean: boolean;
function AsDouble: double;
function IsFloat: boolean;
function AsFloat: Extended;
end;
function ISODateTimeToString(ADateTime: TDateTime): string;
begin
result := DateToISO8601(ADateTime);
end;
function ISOStrToDateTime(DateTimeAsString: string): TDateTime;
begin
TryISO8601ToDate(DateTimeAsString, result);
end;
function TValueHelper.IsNumeric: boolean;
begin
result := Kind in [tkInteger, tkChar, tkEnumeration, tkFloat,
tkWChar, tkInt64];
end;
function TValueHelper.IsBoolean: boolean;
begin
result := TypeInfo = System.TypeInfo(boolean);
end;
function TValueHelper.IsInteger: boolean;
begin
result := TypeInfo = System.TypeInfo(Integer);
end;
function TValueHelper.IsDate: boolean;
begin
result := TypeInfo = System.TypeInfo(TDate);
end;
function TValueHelper.IsDateTime: boolean;
begin
result := TypeInfo = System.TypeInfo(TDateTime);
end;
procedure TMemJsonFile.Clear;
begin
FreeAndNil(FJson);
FJson := TJsonObject.Create;
end;
constructor TMemJsonFile.Create(AFilename: string);
begin
Create(AFilename, nil);
end;
constructor TMemJsonFile.Create(const AFilename: string;
const AEncoding: TEncoding);
begin
inherited Create;
FAutoSave := true;
FJson := TJsonObject.Create;
FEncoding := AEncoding;
{$IFNDEF MSWINDOWS)}
if extractFileName(AFileName)=AFileName then
FFileName := TPath.Combine( TPath.GetHomePath, AFileName );
{$ELSE}
FFileName := AFilename;
{$ENDIF}
LoadValues;
end;
procedure TMemJsonFile.DeleteKey(const Section, Ident: String);
var
sec: TJsonObject;
begin
sec := ReadSection(Section);
if assigned(sec) then
begin
sec.RemovePair(Ident);
FModified := true;
end;
end;
destructor TMemJsonFile.Destroy;
begin
if AutoSave and Modified then
UpdateFile;
FJson.Free;
inherited;
end;
procedure TMemJsonFile.EraseSection(const Section: string);
begin
FJson.RemovePair(Section);
FModified := true;
end;
procedure TMemJsonFile.FromJson(AJson: string);
begin
FreeAndNil(FJson);
FJson := TJsonObject.ParseJSONValue(AJson) as TJsonObject;
FModified := false;
end;
procedure TMemJsonFile.LoadValues;
begin
end;
function TValueHelper.AsDouble: double;
begin
result := AsType<double>;
end;
function TValueHelper.IsFloat: boolean;
begin
result := Kind = tkFloat;
end;
function TValueHelper.AsFloat: Extended;
begin
result := AsType<Extended>;
end;
procedure TMemJsonFile.WriteObject(const ASection: string; AObj: TObject);
var
aCtx: TRttiContext;
AFld: TRttiProperty;
AValue: TValue;
begin
aCtx := TRttiContext.Create;
try
for AFld in aCtx.GetType(AObj.ClassType).GetProperties do
begin
if AFld.Visibility in [mvPublic] then
begin
AValue := AFld.GetValue(AObj);
if AValue.IsDate or AValue.IsDateTime then
WriteString(ASection, AFld.Name, ISODateTimeToString(AValue.AsDouble))
else if AValue.IsBoolean then
WriteBool(ASection, AFld.Name, AValue.AsBoolean)
else if AValue.IsInteger then
WriteInteger(ASection, AFld.Name, AValue.AsInteger)
else if AValue.IsFloat or AValue.IsNumeric then
WriteFloat(ASection, AFld.Name, AValue.AsFloat)
else
WriteString(ASection, AFld.Name, AValue.ToString);
end;
end;
finally
aCtx.Free;
end;
end;
procedure TMemJsonFile.ReadObject(const ASection: string; AObj: TObject);
var
aCtx: TRttiContext;
AFld: TRttiProperty;
AValue, ABase: TValue;
begin
aCtx := TRttiContext.Create;
try
for AFld in aCtx.GetType(AObj.ClassType).GetProperties do
begin
if AFld.Visibility in [mvPublic] then
begin
ABase := AFld.GetValue(AObj);
AValue := AFld.GetValue(AObj);
if ABase.IsDate or ABase.IsDateTime then
AValue := ISOStrToDateTime(ReadString(ASection, AFld.Name,
ISODateTimeToString(ABase.AsDouble)))
else if ABase.IsBoolean then
AValue := ReadBool(ASection, AFld.Name, ABase.AsBoolean)
else if ABase.IsInteger then
AValue := ReadInteger(ASection, AFld.Name, ABase.AsInteger)
else if ABase.IsFloat or ABase.IsNumeric then
AValue := ReadFloat(ASection, AFld.Name, ABase.AsFloat)
else
AValue := ReadString(ASection, AFld.Name, ABase.asString);
AFld.SetValue(AObj, AValue);
end;
end;
finally
aCtx.Free;
end;
end;
procedure TJsonFile.LoadValues;
var
Size: Integer;
Buffer: TBytes;
Stream: TFileStream;
begin
// copy from Ssytem.IniFiles .TIniFiles (embarcadero)
try
if (FileName <> '') and FileExists(FileName) then
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
// Load file into buffer and detect encoding
Size := Stream.Size - Stream.Position;
SetLength(Buffer, Size);
Stream.Read(Buffer[0], Size);
Size := TEncoding.GetBufferEncoding(Buffer, FEncoding);
// Load strings from buffer
FromJson(FEncoding.GetString(Buffer, Size, Length(Buffer) - Size));
finally
Stream.Free;
end;
end
else
Clear;
finally
Modified := false;
end;
end;
procedure TMemJsonFile.SetAutoSave(const Value: boolean);
begin
FAutoSave := Value;
end;
procedure TMemJsonFile.SetModified(const Value: boolean);
begin
FModified := Value;
end;
function TMemJsonFile.ToJson: string;
begin
result := FJson.ToJson;
end;
procedure TMemJsonFile.UpdateFile;
begin
end;
procedure TJsonFile.UpdateFile;
var
List: TStringList;
begin
List := TStringList.Create;
try
List.Text := ToJson;
List.SaveToFile(FFileName, FEncoding);
finally
List.Free;
end;
Modified := false;
end;
procedure TMemJsonFile.ReadSection(const Section: string; Strings: TStrings);
var
sec: TJsonObject;
v: TJsonPair;
begin
Strings.Clear;
sec := ReadSection(Section);
if not assigned(sec) then
exit;
for v in sec do
begin
Strings.Add(v.JsonString.Value);
end;
end;
function TMemJsonFile.ReadBool(const Section, Ident: string;
Default: boolean): boolean;
var
j: TJsonObject;
begin
// result := ReadValue(Section,Ident,Default);
end;
function TMemJsonFile.ReadDatetime(const Section, Ident: string;
Default: TDateTime): TDateTime;
var
v: Variant;
begin
result := Default;
v := ReadValue(Section, Ident, ISODateTimeToString(Default));
result := ISOStrToDateTime(v);
end;
function TMemJsonFile.ReadFloat(const Section, Ident: string;
Default: double): double;
var
v: Variant;
begin
result := Default;
v := ReadValue(Section, Ident, Default);
result := StrToFloatDef(v, 0);
end;
function TMemJsonFile.ReadInteger(const Section, Ident: string;
Default: Integer): Integer;
var
v: Variant;
begin
v := ReadValue(Section, Ident, Default);
result := StrToIntDef(v, 0);
end;
function TMemJsonFile.ReadSection(const Section: string): TJsonObject;
var
v: TJsonValue;
begin
result := nil;
v := nil;
FJson.TryGetValue<TJsonValue>(Section, v);
if assigned(v) then
result := v as TJsonObject;
end;
procedure TMemJsonFile.ReadSections(Strings: TStrings);
var
v: TJsonPair;
begin
Strings.Clear;
for v in FJson do
begin
Strings.Add(v.JsonString.Value);
end;
end;
function TMemJsonFile.ReadSectionJsonValue(const Section: TJsonObject;
Ident: string): TJsonValue;
begin
result := nil;
Section.TryGetValue<TJsonValue>(Ident, result);
end;
procedure TMemJsonFile.ReadSectionValues(const Section: string;
Strings: TStrings);
var
v: TJsonPair;
j: TJsonObject;
begin
//Strings.Clear;
j := ReadSection(Section);
if not assigned(j) then
exit;
for v in j do
begin
Strings.Add(v.JsonString.Value + '=' + v.JsonValue.Value);
end;
end;
function TMemJsonFile.ReadString(const Section, Ident, Default: string): string;
var
v: Variant;
begin
result := Default;
v := ReadValue(Section, Ident, Default);
result := v;
end;
function TMemJsonFile.ReadValue(const Section, Ident: string;
Default: Variant): Variant;
var
j: TJsonObject;
v: TJsonValue;
begin
result := Default;
j := ReadSection(Section);
if not assigned(j) then
exit;
v := j.Find(Ident);
if not assigned(v) then
exit;
result := v.Value;
end;
procedure TMemJsonFile.WriteBool(const Section, Ident: string; Value: boolean);
begin
WriteValue(Section, Ident, Value);
end;
procedure TMemJsonFile.WriteDateTime(const Section, Ident: string;
Value: TDateTime);
begin
WriteValue(Section, Ident, ISODateTimeToString(Value));
end;
procedure TMemJsonFile.WriteFloat(const Section, Ident: string; Value: double);
begin
WriteValue(Section, Ident, Value);
end;
procedure TMemJsonFile.WriteInteger(const Section, Ident: string;
Value: Integer);
begin
WriteValue(Section, Ident, Value);
end;
procedure TMemJsonFile.WriteString(const Section, Ident: string; Value: string);
begin
WriteValue(Section, Ident, Value);
end;
procedure TMemJsonFile.WriteValue(const Section, Ident: string; Value: TValue);
var
AArray: TJsonObject;
AValue: TJsonValue;
procedure Add;
begin
if Value.IsInteger then
AArray.AddPair(Ident, TJSONNumber.Create(Value.AsInteger))
else if Value.IsDate or Value.IsDateTime then
AArray.AddPair(Ident, ISODateTimeToString(Value.AsExtended))
else if Value.IsBoolean then
AArray.AddPair(Ident, TJSONBool.Create(Value.AsBoolean))
else if Value.IsNumeric then
AArray.AddPair(Ident, TJSONNumber.Create(Value.AsExtended))
else
AArray.AddPair(Ident, Value.asString)
end;
begin
AArray := ReadSection(Section);
if not assigned(AArray) then
begin
AArray := TJsonObject.Create;
FJson.AddPair(Section, AArray)
end;
AValue := ReadSectionJsonValue(AArray, Ident);
if not assigned(AValue) then
Add
else
begin
AArray.RemovePair(Ident);
Add;
end;
FModified := true;
end;
{ TJsonObjectHelper }
function TJsonObjectHelper.Find(Section: string): TJsonValue;
begin
result := FindValue(Section);
end;
end.
|
unit UFourSquareDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSCloudBase,
FMX.TMSCloudFourSquare, FMX.TMSCloudXUtil, FMX.StdCtrls, FMX.Objects,
FMX.TMSCloudImage, FMX.Layouts, FMX.ListBox, FMX.Edit, FMX.TreeView;
type
TForm1 = class(TForm)
TMSFMXCloudFourSquare1: TTMSFMXCloudFourSquare;
ToolBar1: TToolBar;
btConnect: TButton;
btDisconnect: TButton;
lbUserName: TLabel;
lbEmail: TLabel;
lbCity: TLabel;
lbBio: TLabel;
lbPhone: TLabel;
lbFriends: TLabel;
lbCheckins: TLabel;
lbGender: TLabel;
ciUser: TTMSFMXCloudImage;
Panel1: TPanel;
Line1: TLine;
btGetCheckIns: TButton;
ListBox2: TListBox;
Label1: TLabel;
Label2: TLabel;
lbKeyword: TLabel;
lbCat: TLabel;
lbLocation: TLabel;
ListBox3: TListBox;
edKeyword: TEdit;
edSearch: TEdit;
btSearch: TButton;
lbUserFriends: TLabel;
lbUserCheckins: TLabel;
Label3: TLabel;
TreeView1: TTreeView;
lbCategories: TLabel;
lbResult: TLabel;
btCheckIn: TButton;
edCheckin: TEdit;
TMSFMXCloudImage1: TTMSFMXCloudImage;
procedure btConnectClick(Sender: TObject);
procedure TMSFMXCloudFourSquare1ReceivedAccessToken(Sender: TObject);
procedure btDisconnectClick(Sender: TObject);
procedure btGetCheckInsClick(Sender: TObject);
procedure btSearchClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TreeView1Change(Sender: TObject);
procedure ListBox3Change(Sender: TObject);
procedure btCheckInClick(Sender: TObject);
procedure ListBox2Change(Sender: TObject);
private
{ Private declarations }
Connected: Boolean;
CategoryList: TStringList;
CategoryIDList: TStringList;
VenueImage: integer;
public
{ Public declarations }
procedure ToggleControls;
procedure FillUserProfile(Profile: TFourSquareUserProfile = nil);
procedure FillTreeView(ATreeView: TTreeView);
procedure GetVenues(CategoryID: string = '');
procedure FillCategories;
procedure SelectCategory;
procedure LoadCheckIns;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// FourSquareAppkey = 'xxxxxxxxx';
// FourSquareAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1.FillCategories;
begin
if TMSFMXCloudFourSquare1.Categories.Count = 0 then
TMSFMXCloudFourSquare1.GetCategories;
FillTreeView(TreeView1);
end;
procedure TForm1.FillTreeView(ATreeView: TTreeView);
procedure AddFolder(ParentNode: TTreeViewItem; Cats: TFourSquareCategories);
var
tn: TTreeViewItem;
i: integer;
begin
for i := 0 to Cats.Count - 1 do
begin
tn := TTreeViewItem.Create(ParentNode);
tn.TagString := Cats.Items[i].ID;
tn.Text := Cats.Items[i].Summary;
if Assigned(ParentNode) then
ParentNode.AddObject(tn)
else
ATreeView.AddObject(tn);
if Assigned(Cats.Items[i].SubCategories) then
if (Cats.Items[i].SubCategories.Count > 0) then
AddFolder(tn, Cats.Items[i].SubCategories);
end;
end;
begin
if Assigned(ATreeView) then
begin
ATreeView.Clear;
AddFolder(nil, TMSFMXCloudFourSquare1.Categories);
if ATreeView.Count > 0 then
begin
ATreeView.Selected := ATreeView.Items[0];
end;
end;
end;
procedure TForm1.btGetCheckInsClick(Sender: TObject);
begin
LoadCheckins;
end;
procedure TForm1.btSearchClick(Sender: TObject);
begin
if CategoryIDList.Count = 0 then
Exit;
GetVenues(CategoryIDList[0]);
end;
procedure TForm1.btCheckInClick(Sender: TObject);
begin
if ListBox3.ItemIndex > -1 then
TMSFMXCloudFourSquare1.CheckIn(TMSFMXCloudFourSquare1.Venues[ListBox3.ItemIndex].ID, edCheckIn.Text);
LoadCheckIns;
end;
procedure TForm1.btConnectClick(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudFourSquare1.App.Key := FourSquare_AppKey;
TMSFMXCloudFourSquare1.App.Secret := FourSquare_AppSecret;
if TMSFMXCloudFourSquare1.App.Key <> '' then
begin
TMSFMXCloudFourSquare1.PersistTokens.Key := XGetDocumentsDirectory + '/foursquare.ini';
TMSFMXCloudFourSquare1.PersistTokens.Section := 'tokens';
TMSFMXCloudFourSquare1.LoadTokens;
acc := TMSFMXCloudFourSquare1.TestTokens;
if not acc then
begin
TMSFMXCloudFourSquare1.RefreshAccess;
acc := TMSFMXCloudFourSquare1.TestTokens;
if not acc then
TMSFMXCloudFourSquare1.DoAuth;
end
else
begin
Connected := true;
ToggleControls;
end;
if Connected then
begin
FillUserProfile;
FillCategories;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm1.btDisconnectClick(Sender: TObject);
begin
TMSFMXCloudFourSquare1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1.FillUserProfile(Profile: TFourSquareUserProfile = nil);
begin
if Profile = nil then
Profile := TMSFMXCloudFourSquare1.UserProfile;
TMSFMXCloudFourSquare1.GetUserProfile(Profile);
lbUserName.Text := Profile.FirstName + ' ' + Profile.LastName;
lbEmail.Text := Profile.Email;
lbCity.Text := Profile.HomeCity;
lbBio.Text := Profile.Bio;
lbPhone.Text := Profile.PhoneNumber;
lbUserFriends.Text := IntToStr(Profile.FriendsCount);
lbUserCheckins.Text := IntToStr(Profile.CheckInsCount);
ciUser.URL := Profile.ImageURL;
if Profile.Gender = fgFemale then
lbGender.Text := 'Female'
else if Profile.Gender = fgMale then
lbGender.Text := 'Male'
else
lbGender.Text := '';
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
VenueImage := -1;
ToggleControls;
CategoryList := TStringList.Create;
CategoryIDList := TStringList.Create;
end;
procedure TForm1.GetVenues(CategoryID: string);
var
I: integer;
err: string;
begin
if (edSearch.Text <> EmptyStr) or (edKeyword.Text <> EmptyStr) then
begin
err := TMSFMXCloudFourSquare1.GetNearbyVenues(0, 0, edSearch.Text, edKeyword.Text, CategoryID, 20);
if err <> EmptyStr then
ShowMessage(err)
else
begin
lbResult.Text := TMSFMXCloudFourSquare1.Location.Summary + ', ' + TMSFMXCloudFourSquare1.Location.CountryCode;
ListBox3.Items.Clear;
for I := 0 to TMSFMXCloudFourSquare1.Venues.Count - 1 do
begin
ListBox3.Items.AddObject(TMSFMXCloudFourSquare1.Venues[I].Summary, TMSFMXCloudFourSquare1.Venues[I]);
end;
end;
end;
end;
procedure TForm1.ListBox2Change(Sender: TObject);
begin
if Assigned(ListBox2.Selected) then
ShowMessage((listbox2.Selected.Data as TFourSquareCheckIn).Comment);
end;
procedure TForm1.ListBox3Change(Sender: TObject);
begin
if Assigned(ListBox3.Selected) then
begin
btCheckIn.Text := 'Check-in "'+ ListBox3.Selected.Text+'"';
TMSFMXCloudFourSquare1.GetPhotos((ListBox3.Selected.Data as TFourSquareVenue), 1, 0);
if (ListBox3.Selected.Data as TFourSquareVenue).Photos.Count > 0 then
TMSFMXCloudImage1.URL := (ListBox3.Selected.Data as TFourSquareVenue).Photos[0].ImageURL
else
TMSFMXCloudImage1.URL := '';
end;
end;
procedure TForm1.LoadCheckIns;
var
I: integer;
begin
TMSFMXCloudFourSquare1.GetCheckIns;
ListBox2.Clear;
for I := 0 to TMSFMXCloudFourSquare1.UserProfile.CheckIns.Count - 1 do
ListBox2.Items.AddObject(TMSFMXCloudFourSquare1.UserProfile.CheckIns[I].Venue.Summary + ' ' + DateToStr(TMSFMXCloudFourSquare1.UserProfile.CheckIns[I].Created), TMSFMXCloudFourSquare1.UserProfile.CheckIns[I]);
end;
procedure TForm1.SelectCategory;
begin
CategoryList.Clear;
CategoryIDList.Clear;
lbCategories.Text := 'Selected Category: ';
if Assigned(TreeView1.Selected) then
begin
CategoryList.Add(TreeView1.Selected.Text);
CategoryIDList.Add(TreeView1.Selected.TagString);
lbCategories.Text := 'Selected Category: ' + TreeView1.Selected.Text;
end;
end;
procedure TForm1.TMSFMXCloudFourSquare1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudFourSquare1.SaveTokens;
Connected := true;
FillUserProfile;
FillCategories;
ToggleControls;
end;
procedure TForm1.ToggleControls;
begin
btConnect.Enabled := not connected;
btDisconnect.Enabled := connected;
edKeyword.Enabled := connected;
edSearch.Enabled := connected;
btSearch.Enabled := connected;
btCheckIn.Enabled := connected;
edCheckIn.Enabled := connected;
btGetCheckIns.Enabled := connected;
ListBox2.Enabled := connected;
ListBox3.Enabled := connected;
TreeView1.Enabled := connected;
end;
procedure TForm1.TreeView1Change(Sender: TObject);
begin
SelectCategory;
end;
end.
|
unit msmModelServicePack;
// Модуль: "w:\common\components\gui\Garant\msm\msmModelServicePack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "msmModelServicePack" MUID: (57EE6C5602EB)
{$Include w:\common\components\msm.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwGlobalKeyWord
, l3Interfaces
, tfwScriptingInterfaces
, TypInfo
, msmModelService
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *57EE6C5602EBimpl_uses*
//#UC END# *57EE6C5602EBimpl_uses*
;
type
TkwMsmModelRoot = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта msm:ModelRoot }
private
function msm_ModelRoot(const aCtx: TtfwContext): Il3CString;
{* Реализация слова скрипта msm:ModelRoot }
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;//TkwMsmModelRoot
function TkwMsmModelRoot.msm_ModelRoot(const aCtx: TtfwContext): Il3CString;
{* Реализация слова скрипта msm:ModelRoot }
//#UC START# *57EE6C7A01B3_57EE6C7A01B3_Word_var*
//#UC END# *57EE6C7A01B3_57EE6C7A01B3_Word_var*
begin
//#UC START# *57EE6C7A01B3_57EE6C7A01B3_Word_impl*
Result := TtfwCStringFactory.C(TmsmModelService.Instance.ModelRoot);
//#UC END# *57EE6C7A01B3_57EE6C7A01B3_Word_impl*
end;//TkwMsmModelRoot.msm_ModelRoot
class function TkwMsmModelRoot.GetWordNameForRegister: AnsiString;
begin
Result := 'msm:ModelRoot';
end;//TkwMsmModelRoot.GetWordNameForRegister
function TkwMsmModelRoot.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwMsmModelRoot.GetResultTypeInfo
function TkwMsmModelRoot.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwMsmModelRoot.GetAllParamsCount
function TkwMsmModelRoot.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwMsmModelRoot.ParamsTypes
procedure TkwMsmModelRoot.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString(msm_ModelRoot(aCtx));
end;//TkwMsmModelRoot.DoDoIt
initialization
TkwMsmModelRoot.RegisterInEngine;
{* Регистрация msm_ModelRoot }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа Il3CString }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
{| Unit: pmdev
| Version: 1.00
| translated from file pmdev.H
| Original translation: Peter Sawatzki (ps)
| Contributing:
| (fill in)
|
| change history:
| Date: Ver: Author:
| 11/19/93 1.00 ps original translation by ps
}
Unit pmdev;
Interface
Uses
Os2Def;
{**************************************************************************\
*
* Module Name: PMDEV.H
*
* OS/2 Presentation Manager Device Context constants, types and
* function declarations
*
\**************************************************************************}
Type
{ pointer data for DevOpenDC }
pDevOpenData = ^PSZ;
{ General DEV return values }
Const
DEV_ERROR = 0 ;
DEV_OK = 1 ;
{ DC type for DevOpenDC }
OD_QUEUED = 2 ;
OD_DIRECT = 5 ;
OD_INFO = 6 ;
OD_METAFILE = 7 ;
OD_MEMORY = 8 ;
OD_METAFILE_NOQUERY = 9 ;
{ codes for DevQueryCaps }
CAPS_FAMILY = 0 ;
CAPS_IO_CAPS = 1 ;
CAPS_TECHNOLOGY = 2 ;
CAPS_DRIVER_VERSION = 3 ;
CAPS_WIDTH = 4 ; { pels }
CAPS_HEIGHT = 5 ; { pels }
CAPS_WIDTH_IN_CHARS = 6 ;
CAPS_HEIGHT_IN_CHARS = 7 ;
CAPS_HORIZONTAL_RESOLUTION = 8 ; { pels per meter }
CAPS_VERTICAL_RESOLUTION = 9 ; { pels per meter }
CAPS_CHAR_WIDTH = 10 ; { pels }
CAPS_CHAR_HEIGHT = 11 ; { pels }
CAPS_SMALL_CHAR_WIDTH = 12 ; { pels }
CAPS_SMALL_CHAR_HEIGHT = 13 ; { pels }
CAPS_COLORS = 14 ;
CAPS_COLOR_PLANES = 15 ;
CAPS_COLOR_BITCOUNT = 16 ;
CAPS_COLOR_TABLE_SUPPORT = 17 ;
CAPS_MOUSE_BUTTONS = 18 ;
CAPS_FOREGROUND_MIX_SUPPORT = 19 ;
CAPS_BACKGROUND_MIX_SUPPORT = 20 ;
CAPS_DEVICE_WINDOWING = 31 ;
CAPS_ADDITIONAL_GRAPHICS = 32 ;
CAPS_VIO_LOADABLE_FONTS = 21 ;
CAPS_WINDOW_BYTE_ALIGNMENT = 22 ;
CAPS_BITMAP_FORMATS = 23 ;
CAPS_RASTER_CAPS = 24 ;
CAPS_MARKER_HEIGHT = 25 ; { pels }
CAPS_MARKER_WIDTH = 26 ; { pels }
CAPS_DEVICE_FONTS = 27 ;
CAPS_GRAPHICS_SUBSET = 28 ;
CAPS_GRAPHICS_VERSION = 29 ;
CAPS_GRAPHICS_VECTOR_SUBSET = 30 ;
CAPS_PHYS_COLORS = 33 ;
CAPS_COLOR_INDEX = 34 ;
CAPS_GRAPHICS_CHAR_WIDTH = 35 ;
CAPS_GRAPHICS_CHAR_HEIGHT = 36 ;
CAPS_HORIZONTAL_FONT_RES = 37 ;
CAPS_VERTICAL_FONT_RES = 38 ;
CAPS_DEVICE_FONT_SIM = 39 ;
{ Constants for CAPS_IO_CAPS }
CAPS_IO_DUMMY = 1 ;
CAPS_IO_SUPPORTS_OP = 2 ;
CAPS_IO_SUPPORTS_IP = 3 ;
CAPS_IO_SUPPORTS_IO = 4 ;
{ Constants for CAPS_TECHNOLOGY }
CAPS_TECH_UNKNOWN = 0 ;
CAPS_TECH_VECTOR_PLOTTER = 1 ;
CAPS_TECH_RASTER_DISPLAY = 2 ;
CAPS_TECH_RASTER_PRINTER = 3 ;
CAPS_TECH_RASTER_CAMERA = 4 ;
CAPS_TECH_POSTSCRIPT = 5 ;
{ Constants for CAPS_COLOR_TABLE_SUPPORT }
CAPS_COLTABL_RGB_8 = 1 ;
CAPS_COLTABL_RGB_8_PLUS = 2 ;
CAPS_COLTABL_TRUE_MIX = 4 ;
CAPS_COLTABL_REALIZE = 8 ;
{ Constants for CAPS_FOREGROUND_MIX_SUPPORT }
CAPS_FM_OR = 1 ;
CAPS_FM_OVERPAINT = 2 ;
CAPS_FM_XOR = 8 ;
CAPS_FM_LEAVEALONE = 16 ;
CAPS_FM_AND = 32 ;
CAPS_FM_GENERAL_BOOLEAN = 64 ;
{ Constants for CAPS_BACKGROUND_MIX_SUPPORT }
CAPS_BM_OR = 1 ;
CAPS_BM_OVERPAINT = 2 ;
CAPS_BM_XOR = 8 ;
CAPS_BM_LEAVEALONE = 16 ;
{ Constants for CAPS_DEVICE_WINDOWING }
CAPS_DEV_WINDOWING_SUPPORT = 1 ;
{ Constants for CAPS_ADDITIONAL_GRAPHICS }
CAPS_GRAPHICS_KERNING_SUPPORT = 2 ;
CAPS_FONT_OUTLINE_DEFAULT = 4 ;
CAPS_FONT_IMAGE_DEFAULT = 8 ;
{ bits represented by values 16L and 32L are reserved }
CAPS_SCALED_DEFAULT_MARKERS = 64 ;
{ Constants for CAPS_WINDOW_BYTE_ALIGNMENT }
CAPS_BYTE_ALIGN_REQUIRED = 0 ;
CAPS_BYTE_ALIGN_RECOMMENDED = 1 ;
CAPS_BYTE_ALIGN_NOT_REQUIRED = 2 ;
{ Constants for CAPS_RASTER_CAPS }
CAPS_RASTER_BITBLT = 1 ;
CAPS_RASTER_BANDING = 2 ;
CAPS_RASTER_BITBLT_SCALING = 4 ;
CAPS_RASTER_SET_PEL = 16 ;
CAPS_RASTER_FONTS = 32 ;
Function DevOpenDC (hab: HAB; lType: LongInt; pszToken: PSZ; lCount: LongInt;pdopData: PDEVOPENDATA;
hdcComp: HDC): HDC;
Function DevCloseDC (hdc: HDC): HMF;
Function DevQueryCaps (hdc: HDC;lStart,lCount: LongInt;alArray: PLONG): BOOL;
{ structures for DEVESC_QUERYVIOCELLSIZES }
Type
VIOSIZECOUNT = Record { vios }
maxcount,
count: LongInt
End;
pVIOSIZECOUNT = ^VIOSIZECOUNT;
VIOFONTCELLSIZE = Record { viof }
cx,
cy: LongInt
End;
pVIOFONTCELLSIZE = ^VIOFONTCELLSIZE;
{ structure for DEVESC_GETCP }
ESCGETCP = Record { escgcp }
options: ULONG;
codepage,
fontid: USHORT
End;
pESCGETCP = ^ESCGETCP;
{ structure for DEVESC_GETSCALINGFACTOR }
SFACTORS = Record { sfactors }
x,
y: LongInt
End;
pSFACTORS = ^SFACTORS;
{ structure for DEVESC_NEXTBAND }
BANDRECT = Record { bandrect }
xleft,
ybottom,
xright,
ytop: LongInt
End;
pBANDRECT = ^BANDRECT;
{ return codes for DevEscape }
Const
DEVESC_ERROR = (-1 );
DEVESC_NOTIMPLEMENTED = 0 ;
{ codes for DevEscape }
DEVESC_QUERYESCSUPPORT = 0 ;
DEVESC_GETSCALINGFACTOR = 1 ;
DEVESC_QUERYVIOCELLSIZES = 2 ;
DEVESC_GETCP = 8000 ;
DEVESC_STARTDOC = 8150 ;
DEVESC_ENDDOC = 8151 ;
DEVESC_NEXTBAND = 8152 ;
DEVESC_ABORTDOC = 8153 ;
DEVESC_NEWFRAME = 16300 ;
DEVESC_DRAFTMODE = 16301 ;
DEVESC_FLUSHOUTPUT = 16302 ;
DEVESC_RAWDATA = 16303 ;
DEVESC_SETMODE = 16304 ;
DEVESC_DBE_FIRST = 24450 ;
DEVESC_DBE_LAST = 24455 ;
{ DevEscape codes for adding extra space to character strings }
DEVESC_CHAR_EXTRA = 16998 ;
DEVESC_BREAK_EXTRA = 16999 ;
{ codes for DevEscape PM_Q_ESC spool files }
DEVESC_STD_JOURNAL = 32600 ;
{ return codes for DevPostDeviceModes }
DPDM_ERROR = (-1 );
DPDM_NONE = 0 ;
{ codes for DevPostDeviceModes }
DPDM_POSTJOBPROP = 0 ;
DPDM_CHANGEPROP = 1 ;
DPDM_QUERYJOBPROP = 2 ;
Type
{ string types for DevQueryDeviceNames }
STR16 = Array[0..15] Of Char; { str16 }
pSTR16 = ^STR16;
STR32 = Array[0..31] Of Char; { str32 }
pSTR32 = ^PSTR32;
STR64 = Array[0..63] Of Char; { str64 }
pSTR64 = ^STR64;
Const
{ return code for DevQueryHardcopyCaps }
DQHC_ERROR = (-1 );
{ codes for DevQueryHardcopyCaps }
HCAPS_CURRENT = 1 ;
HCAPS_SELECTABLE = 2 ;
{ structure for DevQueryHardcopyCaps }
Type
HCINFO = Record { hci }
szFormname: Array[0..31] Of Char;
cx,
cy,
xLeftClip,
yBottomClip,
xRightClip,
yTopClip,
xPels,
yPels,
flAttributes: LongInt
End;
pHCINFO = ^HCINFO;
{ structure for DEVESC_SETMODE }
ESCSETMODE = Record { escsm }
mode: ULONG;
codepage: USHORT
End;
pESCSETMODE = ^ESCSETMODE;
Function DevEscape (hdc: HDC;lCode,lInCount: LongInt;pbInData: PBYTE;plOutCount: PLONG;pbOutData: PBYTE): LongInt;
Function DevQueryDeviceNames (hab: HAB;pszDriverName: PSZ;pldn: PLONG;aDeviceName: PSTR32;
aDeviceDesc: PSTR64;pldt: PLONG;aDataType: PSTR16): BOOL;
Function DevQueryHardcopyCaps (hdc: HDC;lStartForm,lForms: LongInt;phciHcInfo: PHCINFO): LongInt;
Function DevPostDeviceModes (hab: HAB;pdrivDriverData: PDRIVDATA;pszDriverName,pszDeviceName,
pszName: PSZ;flOptions: ULONG): LongInt;
{ AAB error codes for the DEV - same as GPI errors at present }
Implementation
Function DevCloseDC; External 'PMGPI' Index 2;
Function DevEscape; External 'PMGPI' Index 4;
Function DevOpenDC; External 'PMGPI' Index 1;
Function DevPostDeviceModes; External 'PMGPI' Index 3;
Function DevQueryCaps; External 'PMGPI' Index 6;
Function DevQueryDeviceNames; External 'PMGPI' Index 165;
Function DevQueryHardcopyCaps; External 'PMGPI' Index 5;
End.
|
{--------------------------program 9.20-------------------------}
UNIT PriorityQueueTypesUnit;
INTERFACE
CONST
MaxCount = 10;
TYPE
PQItem = Integer;
PQArray = ARRAY[1..MaxCount] OF PQItem;
PriorityQueue = RECORD
Count : Integer;
ItemList : PQArray;
END{RECORD};
END{UNIT}.
{--------------------------program 9.21-------------------------}
UNIT HeapPriorityQueueUnit;
INTERFACE
USES PriorityQueueTypesUnit; {defines types: PQItem and PriorityQueue}
PROCEDURE Initialize(VAR PQ:PriorityQueue);
FUNCTION Empty(PQ:PriorityQueue):Boolean;
FUNCTION Full(PQ:PriorityQueue):Boolean;
PROCEDURE Insert(Item: PQItem; VAR PQ:PriorityQueue);
FUNCTION Remove(VAR PQ:PriorityQueue):PQItem;
IMPLEMENTATION
{----------------------------}
PROCEDURE Initialize{(VAR PQ:PriorityQueue)};
BEGIN
PQ.Count := 0;
END{Initialize};
{----------------------------}
FUNCTION Empty{(PQ:PriorityQueue):Boolean};
BEGIN
Empty := (PQ.Count = 0);
END{Empty};
{----------------------------}
FUNCTION Full{(PQ:PriorityQueue):Boolean};
BEGIN
Full := (PQ.Count = MaxCount);
END{Full};
{----------------------------}
PROCEDURE Insert{(Item: PQItem; VAR PQ:PriorityQueue)};
VAR ChildLoc,ParentLoc:Integer; Finished:Boolean;
BEGIN
WITH PQ DO BEGIN
Count := Count + 1; {caution: insertion does not}
ChildLoc:= Count; {guard against overflow}
Parent := ChildLoc div 2;
Finished := (ParentLoc = 0);
WHILE (not Finished) DO BEGIN
IF Item <= ItemArray[ParentLoc] THEN
Finished := true
ELSE BEGIN {here, Item > ItemArray[ParentLoc]}
ItemArray[ChildLoc] := ItemArray[ParentLoc];
ChildLoc := ParentLoc;
ParentLoc := ParentLoc div 2;
Finished := (ParentLoc = 0)
END{IF};
END{WHILE};
ItemArray[ChildLoc] := Item; {Item goes in final resting place}
END{WITH};
END{Insert};
{----------------------------}
FUNCTION Remove{(VAR PQ:PriorityQueue):PQItem};
VAR
CurrentLoc, ChildLoc: Integer;
ItemToPlace: PQItem;
Finished: Boolean;
BEGIN
WITH PQ DO BEGIN
IF Count > 0 THEN BEGIN {result is undefined if PQ was empty}
Remove := ItemArray[1];
ItemToPlace := ItemArray[Count]; {save value of last leaf}
Count := Count - 1; {delete last leaf in level order}
CurrentLoc := 1; {CurrentLoc starts at the root}
ChildLoc := 2 * CurrentLoc;
Finished := (ChildLoc > Count);
WHILE not Finished DO BEGIN
{Set ChildLoc to the location of the larger child of CurrentLoc}
IF ChildLoc < Count THEN BEGIN {if right child exists}
IF ItemArray[ChildLoc + 1] > ItemArray[ChildLoc] THEN BEGIN
ChildLoc := ChildLoc + 1;
END{IF};
END{IF};
{If item at ChildLoc is larger than ItemToPlace, move this}
{larger item to CurrentLoc, and move CurrentLoc down}
IF ItemArray[ChildLoc] <= ItemToPlace THEN
Finished := true {to force loop termination}
ELSE BEGIN
ItemArray[CurrentLoc] := ItemArray[ChildLoc];
CurrentLoc := ChildLoc;
ChildLoc := 2 * CurrentLoc;
Finished := (ChildLoc > Count)
END{IF};
END{WHILE};
{final placement of ItemToPlace}
ItemArray[CurrentLoc] := ItemToPlace
END{IF}
END{WITH}
END{Remove};
{----------------------------}
BEGIN
{there is no initialization}
END{UNIT}.
{--------------------------program 9.28-------------------------}
PROCEDURE Traverse(T:NodePointer; TraversalOrder:OrderOfTraversal);
{to visit T's nodes in the order specified by the TraversalOrder parameter}
BEGIN
IF T <> nil THEN BEGIN {If T = nil, do nothing}
IF TraversalOrder = PreOrder THEN
BEGIN
Visit(T);
Traverse(T^.LLink, PreOrder);
Traverse(T^.RLink, PreOrder)
END
ELSE IF TraversalOrder = InOrder THEN
BEGIN
Traverse(T^.LLink, InOrder);
Visit(T);
Traverse(T^.RLink, InOrder)
END
ELSE IF TraversalOrder = PostOrder THEN BEGIN
Traverse(T^.LLink, PostOrder);
Traverse(T^.RLink, PostOrder);
Visit(T)
END{IF}
END{IF}
END{Traverse};
{--------------------------program 9.29-------------------------}
PROCEDURE PreOrderTraversal(T:NodePointer);
USES
StackADT; {to use the operations in Figure 7.3, Chapter 7}
VAR
S : Stack;
N : NodePointer;
BEGIN
InitializeStack(S); {initialize the stack S to be the empty stack}
Push(T,S); {push the pointer T onto the stack}
WHILE (not Empty(S)) DO BEGIN
Pop(S,N); {pop top pointer of S into N}
IF (N <> nil) THEN BEGIN
Write(N^.Symbol); {when visiting N, print its symbol}
Push(N^.RLink,S); {push right pointer onto S}
Push(N^.LLink,S); {push left pointer onto S}
END{IF}
END{WHILE}
END{PreOrderTraversal};
{--------------------------program 9.30-------------------------}
PROCEDURE LevelOrderTraversal(T:NodePointer);
USES
QueueADT; {to use the operations in Figure 7.4 in Chapter 7}
VAR
Q : Queue;
N : NodePointer;
BEGIN
InitializeQueue(Q); {initialize the queue Q to be the empty queue}
Insert(T,Q); {insert the pointer T into queue Q}
WHILE (not Empty(Q)) DO BEGIN
Remove(Q,N); {remove first pointer of Q and put it in N}
IF (N <> nil) THEN BEGIN
Write(N^.Symbol);
Insert(N^.LLink,Q); {insert left pointer on rear of Q}
Insert(N^.RLink,Q) {insert right pointer on rear of Q}
END{IF}
END{WHILE}
END{LevelOrderTraversal};
{---------------------------------------------------------------}
|
unit FFSFormDisplay;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FFSTypes,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDFormDisplay;
type
TFFSFormDisplay = class(TLMDFormDisplay)
private
{ Private declarations }
FFieldsColorScheme: TFieldsColorScheme;
procedure SetFieldsColorScheme(const Value: TFieldsColorScheme);
procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange;
protected
{ Protected declarations }
public
{ Public declarations }
constructor create(AOwner:TComponent);override;
procedure MakeFormList(AList:TStringList);
function IndexofKey(AKey1, AKey2, AKey3:string):integer;
published
{ Published declarations }
property FieldsColorScheme:TFieldsColorScheme read FFieldsColorScheme write SetFieldsColorScheme;
end;
TFFSForm = class(TForm)
private
FIsDestroying: boolean;
procedure SetSearchable(const Value: boolean);
protected
FFormName: string;
FKey1: string;
FKey2: string;
FKey3: string;
FSearchable: boolean;
procedure DoHide; override;
procedure DoShow; override;
procedure DoDestroy; override;
procedure VisibleChanging; override;
procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange;
procedure MsgFFSCanClose(var Msg: TMessage); message Msg_FFSCanClose;
procedure MsgFFSCanDetach(var Msg: TMessage);message Msg_FFSCanDetach;
public
property Key1 : string read FKey1;
property Key2 : string read FKey2;
property Key3 : string read FKey3;
property Searchable:boolean read FSearchable write SetSearchable;
property FormName:string Read FFormName;
property IsDestroying:boolean read FIsDestroying;
procedure SetKeys(AFormName, AKey1:string; AKey2:string = ''; AKey3:string = '');
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Controls', [TFFSFormDisplay]);
end;
{ TFFSFormDisplay }
constructor TFFSFormDisplay.create(AOwner: TComponent);
begin
inherited;
FieldsColorScheme := fcsDataBackGround;
end;
function TFFSFormDisplay.IndexofKey(AKey1, AKey2, AKey3: string): integer;
var x : integer;
frm : TCustomForm;
begin
result := -1;
for x := 1 to FormCount do begin
frm := Forms[x-1];
if frm is TFFSForm then begin
if (TFFSForm(frm).FKey1 = AKey1) and (TFFSForm(frm).FKey2 = AKey2) and (TFFSForm(frm).FKey3 = AKey3) then begin
result := x-1;
break;
end;
end;
end;
end;
procedure TFFSFormDisplay.MakeFormList(AList: TStringList);
var x : integer;
frm : TCustomForm;
s : string;
begin
AList.Clear;
for x := 1 to FormCount do begin
frm := Forms[x-1];
if frm is TFFSForm then s := TFFSForm(frm).FFormName + ': ' + frm.caption
else s := 'Unknown: ' + frm.caption;
AList.Add(s);
end;
end;
procedure TFFSFormDisplay.MsgFFSColorChange(var Msg: TMessage);
begin
color := FFSColor[fcsDataBackground];
BroadCast(Msg);
end;
procedure TFFSFormDisplay.SetFieldsColorScheme(const Value: TFieldsColorScheme);
begin
FFieldsColorScheme := Value;
color := FFSColor[fcsDataBackground];
end;
{ TFFSForm }
procedure TFFSForm.DoDestroy;
begin
FIsDestroying := true;
Application.MainForm.Perform(Msg_FFSRequeryForm, 0, 0);
inherited;
end;
procedure TFFSForm.DoHide;
begin
inherited;
Application.MainForm.Perform(Msg_FFSRequeryForm, 0, 0);
end;
procedure TFFSForm.DoShow;
begin
inherited;
Application.MainForm.Perform(Msg_FFSRequeryForm, 0, 0);
end;
procedure TFFSForm.MsgFFSCanClose(var Msg: TMessage);
begin
msg.result := 1;
end;
procedure TFFSForm.MsgFFSCanDetach(var Msg: TMessage);
begin
msg.result := 0;
end;
procedure TFFSForm.MsgFFSColorChange(var Msg: TMessage);
begin
Color := FFSColor[fcsDataBackground];
BroadCast(Msg);
end;
procedure TFFSForm.SetKeys(AFormName, AKey1, AKey2, AKey3: string);
begin
FFormName := AFormName;
FKey1 := AKey1;
FKey2 := AKey2;
FKey3 := AKey3;
end;
procedure TFFSForm.SetSearchable(const Value: boolean);
begin
FSearchable := Value;
end;
procedure TFFSForm.VisibleChanging;
begin
inherited;
Application.MainForm.Perform(Msg_FFSRequeryForm, 0, 0);
end;
end.
|
unit UIWrapper_RoundUnit;
interface
uses
UIWrapper_SchOptPartUnit, FMX.ListBox, FMX.Controls, SearchOption_Intf;
const
ITEM_LIST_ROUND_DECPLACE_MIN = 0;
ITEM_LIST_ROUND_DECPLACE_MAX = 7;
ITEM_LIST_ROUND_DECPLACE_DEF = ITEM_LIST_ROUND_DECPLACE_MAX;
type
TUIWrapper_SchOpt_Round = class(TUIWrapper_AbsSearchOptionPart)
private
FCmbDecPlace: TComboBox;
public
constructor Create(owner: TExpander; cmbDecPlace: TComboBox);
function GetSearchOptionPart: ISearchOptionPart; override;
end;
implementation
uses
SimpleOptionPart, SysUtils, Const_SearchOptionUnit;
{ TEvent_SchOpt_Round }
constructor TUIWrapper_SchOpt_Round.Create(owner: TExpander;
cmbDecPlace: TComboBox);
var
i: Integer;
begin
Init( owner );
FCmbDecPlace := cmbDecPlace;
for i := ITEM_LIST_ROUND_DECPLACE_MIN to ITEM_LIST_ROUND_DECPLACE_MAX do
begin
FCmbDecPlace.Items.Add( IntToStr( i ) );
end;
FCmbDecPlace.ItemIndex := ITEM_LIST_ROUND_DECPLACE_DEF;
end;
function TUIWrapper_SchOpt_Round.GetSearchOptionPart: ISearchOptionPart;
var
schOpt: TSimpleOptionPart;
begin
schOpt := TSimpleOptionPart.Create;
schOpt.SetUse( FExpander.IsChecked );
schOpt.SetValues( SOP_ITEM_SEQ[ 9 ], FCmbDecPlace.Selected.Text );
end;
end.
|
{------------------------------------------------------------------------------------}
{program p031_000 exercises production #031 }
{statement -> compound_statement }
{------------------------------------------------------------------------------------}
{Author: Thomas R. Turner }
{E-Mail: trturner@uco.edu }
{Date: January, 2012 }
{------------------------------------------------------------------------------------}
{Copyright January, 2012 by Thomas R. Turner }
{Do not reproduce without permission from Thomas R. Turner. }
{------------------------------------------------------------------------------------}
program p031_000;
var cash:real;
begin{p031_000}
write('How much cash do you have? ');
readln(cash);
if cash<100.0 then
begin
writeln('You wicked and slothful person.');
writeln('I''d never go out with you.')
end
else
begin
writeln('Come on, honey, let''s have a good time tonight!')
end;
writeln('See you later!')
end{p031_000}.
|
unit KopConfigUnit;
interface
uses XSuperObject, IdGlobal, System.SysUtils, ProtocolCommon, Classes, Global;
const
MaxHostSize = 128;
MaxApnSize = 32;
MaxGsmLoginSize = 32;
MaxUssdBalanceSize = 10;
MaxPhoneNumberSize = 10;
AlarmSensorCount = 8;
OutputsCount = 4;
// MaxHostSize = 127;
// MaxApnSize = 31;
// MaxGsmLoginSize = 31;
// MaxUssdBalanceSize = 9;
// MaxPhoneNumberSize = 9;
// AlarmSensorCount = 7;
// OutputsCount = 3;
type TEndpointConf = packed record
Host: Array [0..MaxHostSize -1] of UInt8;
Port: UInt16;
end;
TSimCardConf = packed record
Apn : Array[0..MaxApnSize -1] of UInt8;
User : Array[0..MaxGsmLoginSize -1] of UInt8;
Pass : Array[0..MaxGsmLoginSize -1] of UInt8;
UssdBalance : Array[0..MaxUssdBalanceSize -1] of UInt8;
BalanceRequestPeriod : UInt8;
BalanceFirstDigit : UInt8;
end;
TGsmConf = packed record
PSim1 : TSimCardConf;
PSim2 : TSimCardConf;
MainSim : UInt8;
ReturnToMainSimTime : UInt8;
BalanceRenewalTime : UInt8;
SmsPhone : Array[0..MaxPhoneNumberSize -1] of UInt8;
SendEventsViaSms : UInt8;
end;
TEthernetConf = packed record
UseDhcp : UInt8;
Ip : TBuf4;
Mask : TBuf4;
Gateway : TBuf4;
end;
TConnectionConf = packed record
PEthernetServer1 : TEndpointConf;
PEthernetServer2 : TEndpointConf;
PGprsServer1 : TEndpointConf;
PGprsServer2 : TEndpointConf;
ChanellOrder : UInt8;
PGsm : TGsmConf;
PEthernet : TEthernetConf;
SendEventsViaATS100 : UInt8;
DeviceId : UInt16;
CryptKey : Array[0..7] of UInt32;
end;
TSensorConf = packed record
TypeSensor : UInt8;
AlarmEnableDelay : UInt16;
GetDelay : UInt16;
ExternalIndicatorEnableTime : UInt16;
TakeType : UInt8;
end;
TKopConfig = packed record
PConnection : TConnectionConf;
PSensors : Array[0..AlarmSensorCount - 1] of TSensorConf;
Outputs : Array[0..OutputsCount - 1] of UInt8;
BatteryLevel : Single;
SensorPower12V : UInt8;
Crc : UInt16;
end;
function ReadFile(FilePath: string): TFirmwareBuf;
function RecordToJson(KopCfg: TKopConfig): ISuperObject;
function JsonToBytes(KopCfgJson: ISuperObject): TBuf874;
implementation
uses Service, ProtocolLib, PublicUtils;
function ReadFile(FilePath: string): TFirmwareBuf;
var
oneByte : byte;
FileBuf : TFirmwareBuf;
Crc : word;
f: File; i: integer;
begin
AssignFile(f, FilePath);
FileMode := fmOpenRead;
Reset(f, 1); // Теперь мы определяем одну запись как 1 байт
// Теперь читаем один байт за один раз и так до конца файла
i := 0;
while not Eof(f) do
begin
BlockRead(f, oneByte, 1); // Чтение одного байта за один раз
FileBuf[i] := oneByte;
Inc(i);
end;
CloseFile(f);
// PrintBuf(FileBuf, 'Изначальный файл');
Result := FileBuf;
crc := protocolCrc16(@FileBuf, 872);
// LogOut(IntToHex(crc, 4));
//
// LogOut(IntToStr(Length(FileBuf)));
end;
function IpToBytes(Ip: string): TBuf4;
var i: byte; Words: TArray<string>;
begin
Words := Ip.Split(['.']);
for i := 0 to High(Words) do Result[i] := StrToInt(Words[i]);
end;
function JsonToBytes(KopCfgJson: ISuperObject): TBuf874;
var
KopCfg: TKopConfig;
Bytes: TArray<Byte>;
I: Integer;
CfgByte: TIdBytes;
CfgByte2: Array [0 .. 871] of Byte;
CfgByte3: TBuf874;
fs: TFileStream;
n: Integer;
Crc: Word;
a: UInt32;
IntBytes: TIdBytes;
Words: TArray<string>;
Key : string;
begin
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостEthernet1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PEthernetServer1.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PEthernetServer1.Host) do
KopCfg.PConnection.PEthernetServer1.Host[I] := 0;
KopCfg.PConnection.PEthernetServer1.Port := KopCfgJson.I['ПортEthernet1'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостEthernet2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PEthernetServer2.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PEthernetServer2.Host) do
KopCfg.PConnection.PEthernetServer2.Host[I] := 0;
KopCfg.PConnection.PEthernetServer2.Port := KopCfgJson.I['ПортEthernet2'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостGPRS1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGprsServer1.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGprsServer1.Host) do
KopCfg.PConnection.PGprsServer1.Host[I] := 0;
KopCfg.PConnection.PGprsServer1.Port := KopCfgJson.I['ПортGPRS1'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостGPRS2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGprsServer2.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGprsServer2.Host) do
KopCfg.PConnection.PGprsServer2.Host[I] := 0;
KopCfg.PConnection.PGprsServer2.Port := KopCfgJson.I['ПортGPRS2'];
KopCfg.PConnection.ChanellOrder := KopCfgJson.I['ПорядокКаналовСвязи'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['APN1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.Apn[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.Apn) do
KopCfg.PConnection.PGsm.PSim1.Apn[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Логин1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.User[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.User) do
KopCfg.PConnection.PGsm.PSim1.User[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Пароль1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.Pass[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.Pass) do
KopCfg.PConnection.PGsm.PSim1.Pass[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['USSD1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.UssdBalance[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.UssdBalance) do
KopCfg.PConnection.PGsm.PSim1.UssdBalance[I] := 0;
KopCfg.PConnection.PGsm.PSim1.BalanceRequestPeriod := KopCfgJson.I['ПериодЗапросаБаланса1'];
KopCfg.PConnection.PGsm.PSim1.BalanceFirstDigit := KopCfgJson.I['ПозицияПервойЦифры1'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['APN2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.Apn[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.Apn) do
KopCfg.PConnection.PGsm.PSim2.Apn[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Логин2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.User[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.User) do
KopCfg.PConnection.PGsm.PSim2.User[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Пароль2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.Pass[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.Pass) do
KopCfg.PConnection.PGsm.PSim2.Pass[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['USSD2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.UssdBalance[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.UssdBalance) do
KopCfg.PConnection.PGsm.PSim2.UssdBalance[I] := 0;
KopCfg.PConnection.PGsm.PSim2.BalanceRequestPeriod := KopCfgJson.I['ПериодЗапросаБаланса2'];
KopCfg.PConnection.PGsm.PSim2.BalanceFirstDigit := KopCfgJson.I['ПозицияПервойЦифры2'];
KopCfg.PConnection.PGsm.MainSim := KopCfgJson.I['ОсновнаяSIMКарта'];
KopCfg.PConnection.PGsm.ReturnToMainSimTime := KopCfgJson.I['ВернутьсяНаОсновнуюSIMЧерез'];
KopCfg.PConnection.PGsm.BalanceRenewalTime := KopCfgJson.I['ПродлеватьБалансРезервнойSIMРазВ'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['НомерДляОтправкиСМС']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.SmsPhone[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.SmsPhone) do
KopCfg.PConnection.PGsm.SmsPhone[I] := 0;
if KopCfgJson.B['ОтправлятьСобытияПоСМС'] then
KopCfg.PConnection.PGsm.SendEventsViaSms := 1
else
KopCfg.PConnection.PGsm.SendEventsViaSms := 0;
if KopCfgJson.B['ИспользоватьDHCP'] then
KopCfg.PConnection.PEthernet.UseDhcp := 1
else
KopCfg.PConnection.PEthernet.UseDhcp := 0;
Words := KopCfgJson.S['IP'].Split(['.']);
if Length(Words) = 4 then
begin
KopCfg.PConnection.PEthernet.Ip[0] := StrToInt(Words[0]);
KopCfg.PConnection.PEthernet.Ip[1] := StrToInt(Words[1]);
KopCfg.PConnection.PEthernet.Ip[2] := StrToInt(Words[2]);
KopCfg.PConnection.PEthernet.Ip[3] := StrToInt(Words[3]);
end;
Words := KopCfgJson.S['Маска'].Split(['.']);
if Length(Words) = 4 then
begin
KopCfg.PConnection.PEthernet.Mask[0] := StrToInt(Words[0]);
KopCfg.PConnection.PEthernet.Mask[1] := StrToInt(Words[1]);
KopCfg.PConnection.PEthernet.Mask[2] := StrToInt(Words[2]);
KopCfg.PConnection.PEthernet.Mask[3] := StrToInt(Words[3]);
end;
Words := KopCfgJson.S['Шлюз'].Split(['.']);
if Length(Words) = 4 then
begin
KopCfg.PConnection.PEthernet.Gateway[0] := StrToInt(Words[0]);
KopCfg.PConnection.PEthernet.Gateway[1] := StrToInt(Words[1]);
KopCfg.PConnection.PEthernet.Gateway[2] := StrToInt(Words[2]);
KopCfg.PConnection.PEthernet.Gateway[3] := StrToInt(Words[3]);
end;
if KopCfgJson.B['ОтправлятьСобытияЧерезATS100'] then
KopCfg.PConnection.SendEventsViaATS100 := 1
else
KopCfg.PConnection.SendEventsViaATS100 := 0;
KopCfg.PConnection.DeviceId := KopCfgJson.I['УИД'];
Key := KopCfgJson.S['КлючШифрования'];
KopCfg.PConnection.CryptKey[0] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 1, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[1] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 9, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[2] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 17, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[3] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 25, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[4] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 33, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[5] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 41, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[6] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 49, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[7] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 57, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PSensors[0].TypeSensor := KopCfgJson.I['Шлейф1'];
KopCfg.PSensors[0].AlarmEnableDelay := 0;
KopCfg.PSensors[0].GetDelay := 0;
KopCfg.PSensors[0].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[0].TakeType := 0;
KopCfg.PSensors[1].TypeSensor := KopCfgJson.I['Шлейф2'];
KopCfg.PSensors[1].AlarmEnableDelay := 0;
KopCfg.PSensors[1].GetDelay := 0;
KopCfg.PSensors[1].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[1].TakeType := 0;
KopCfg.PSensors[2].TypeSensor := KopCfgJson.I['Шлейф3'];
KopCfg.PSensors[2].AlarmEnableDelay := 0;
KopCfg.PSensors[2].GetDelay := 0;
KopCfg.PSensors[2].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[2].TakeType := 0;
KopCfg.PSensors[3].TypeSensor := KopCfgJson.I['Шлейф4'];
KopCfg.PSensors[3].AlarmEnableDelay := 0;
KopCfg.PSensors[3].GetDelay := 0;
KopCfg.PSensors[3].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[3].TakeType := 0;
KopCfg.PSensors[4].TypeSensor := KopCfgJson.I['Шлейф5'];
KopCfg.PSensors[4].AlarmEnableDelay := 0;
KopCfg.PSensors[4].GetDelay := 0;
KopCfg.PSensors[4].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[4].TakeType := 0;
KopCfg.PSensors[5].TypeSensor := KopCfgJson.I['Шлейф6'];
KopCfg.PSensors[5].AlarmEnableDelay := 0;
KopCfg.PSensors[5].GetDelay := 0;
KopCfg.PSensors[5].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[5].TakeType := 0;
KopCfg.PSensors[6].TypeSensor := KopCfgJson.I['Шлейф7'];
KopCfg.PSensors[6].AlarmEnableDelay := 0;
KopCfg.PSensors[6].GetDelay := 0;
KopCfg.PSensors[6].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[6].TakeType := 0;
KopCfg.PSensors[7].TypeSensor := KopCfgJson.I['Шлейф8'];
KopCfg.PSensors[7].AlarmEnableDelay := 0;
KopCfg.PSensors[7].GetDelay := 0;
KopCfg.PSensors[7].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[7].TakeType := 0;
KopCfg.Outputs[0] := KopCfgJson.I['Выход1'];
KopCfg.Outputs[1] := KopCfgJson.I['Выход2'];
KopCfg.Outputs[2] := KopCfgJson.I['Выход3'];
KopCfg.Outputs[3] := KopCfgJson.I['Выход4'];
KopCfg.BatteryLevel := KopCfgJson.I['ПороговоеНапряжение'];
KopCfg.SensorPower12V := KopCfgJson.I['НапряжениеШлейфов'];
CfgByte := RawToBytes(KopCfg, 872);
LogOut(IntToStr(High(CfgByte)));
for I := 0 to High(CfgByte) do
CfgByte2[I] := CfgByte[I];
// PrintBuf2(CfgByte2);
Crc := protocolCrc16(@CfgByte2, 872);
KopCfg.Crc := Crc;
LogOut(IntToStr(Crc));
CfgByte := RawToBytes(KopCfg, 874);
// PrintBuf(CfgByte);
for I := 0 to High(CfgByte) do
CfgByte3[I] := CfgByte[I];
Result := CfgByte3;
// AssignFile(f, 'mycfg.kopcfg');
// FileMode := fmOpenWrite;
// Reset(f, 1);
// for I := 0 to High(CfgByte) do
// BlockWrite(f, CfgByte[I], 1);
end;
function JsonToBytesOld(KopCfgJson: ISuperObject): TBuf874;
var
KopCfg: TKopConfig;
Bytes: TArray<Byte>;
I: Integer;
CfgByte: TIdBytes;
CfgByte2: Array [0 .. 871] of Byte;
CfgByte3: TBuf874;
fs: TFileStream;
n: Integer;
Crc: Word;
a: UInt32;
IntBytes: TIdBytes;
Words: TArray<string>;
Key : string;
begin
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостEthernet1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PEthernetServer1.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PEthernetServer1.Host) do
KopCfg.PConnection.PEthernetServer1.Host[I] := 0;
KopCfg.PConnection.PEthernetServer1.Port := KopCfgJson.I['ПортEthernet1'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостEthernet2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PEthernetServer2.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PEthernetServer2.Host) do
KopCfg.PConnection.PEthernetServer2.Host[I] := 0;
KopCfg.PConnection.PEthernetServer2.Port := KopCfgJson.I['ПортEthernet2'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостGPRS1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGprsServer1.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGprsServer1.Host) do
KopCfg.PConnection.PGprsServer1.Host[I] := 0;
KopCfg.PConnection.PGprsServer1.Port := KopCfgJson.I['ПортGPRS1'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['ХостGPRS2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGprsServer2.Host[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGprsServer2.Host) do
KopCfg.PConnection.PGprsServer2.Host[I] := 0;
KopCfg.PConnection.PGprsServer2.Port := KopCfgJson.I['ПортGPRS2'];
KopCfg.PConnection.ChanellOrder := KopCfgJson.I['ПорядокКаналовСвязи'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['APN1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.Apn[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.Apn) do
KopCfg.PConnection.PGsm.PSim1.Apn[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Логин1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.User[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.User) do
KopCfg.PConnection.PGsm.PSim1.User[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Пароль1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.Pass[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.Pass) do
KopCfg.PConnection.PGsm.PSim1.Pass[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['USSD1']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim1.UssdBalance[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim1.UssdBalance) do
KopCfg.PConnection.PGsm.PSim1.UssdBalance[I] := 0;
KopCfg.PConnection.PGsm.PSim1.BalanceRequestPeriod := KopCfgJson.I['ПериодЗапросаБаланса1'];
KopCfg.PConnection.PGsm.PSim1.BalanceFirstDigit := KopCfgJson.I['ПозицияПервойЦифры1'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['APN2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.Apn[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.Apn) do
KopCfg.PConnection.PGsm.PSim2.Apn[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Логин2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.User[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.User) do
KopCfg.PConnection.PGsm.PSim2.User[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['Пароль2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.Pass[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.Pass) do
KopCfg.PConnection.PGsm.PSim2.Pass[I] := 0;
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['USSD2']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.PSim2.UssdBalance[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.PSim2.UssdBalance) do
KopCfg.PConnection.PGsm.PSim2.UssdBalance[I] := 0;
KopCfg.PConnection.PGsm.PSim2.BalanceRequestPeriod := KopCfgJson.I['ПериодЗапросаБаланса2'];
KopCfg.PConnection.PGsm.PSim2.BalanceFirstDigit := KopCfgJson.I['ПозицияПервойЦифры2'];
KopCfg.PConnection.PGsm.MainSim := KopCfgJson.I['ОсновнаяSIMКарта'];
KopCfg.PConnection.PGsm.ReturnToMainSimTime := KopCfgJson.I['ВернутьсяНаОсновнуюSIMЧерез'];
KopCfg.PConnection.PGsm.BalanceRenewalTime := KopCfgJson.I['ПродлеватьБалансРезервнойSIMРазВ'];
Bytes := TEncoding.UTF8.GetBytes(KopCfgJson.S['НомерДляОтправкиСМС']);
for I := 0 to High(Bytes) do
KopCfg.PConnection.PGsm.SmsPhone[I] := Bytes[I];
for I := Length(Bytes) to High(KopCfg.PConnection.PGsm.SmsPhone) do
KopCfg.PConnection.PGsm.SmsPhone[I] := 0;
if KopCfgJson.B['ОтправлятьСобытияПоСМС'] then
KopCfg.PConnection.PGsm.SendEventsViaSms := 1
else
KopCfg.PConnection.PGsm.SendEventsViaSms := 0;
if KopCfgJson.B['ИспользоватьDHCP'] then
KopCfg.PConnection.PEthernet.UseDhcp := 1
else
KopCfg.PConnection.PEthernet.UseDhcp := 0;
KopCfg.PConnection.PEthernet.Ip := IpToBytes(KopCfgJson.S['IP']);
KopCfg.PConnection.PEthernet.Mask := IpToBytes(KopCfgJson.S['Маска']);
KopCfg.PConnection.PEthernet.Gateway := IpToBytes(KopCfgJson.S['Шлюз']);
if KopCfgJson.B['ОтправлятьСобытияЧерезATS100'] then
KopCfg.PConnection.SendEventsViaATS100 := 1
else
KopCfg.PConnection.SendEventsViaATS100 := 0;
KopCfg.PConnection.DeviceId := KopCfgJson.I['УИД'];
Key := KopCfgJson.S['КлючШифрования'];
KopCfg.PConnection.CryptKey[0] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 1, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[1] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 9, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[2] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 17, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[3] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 25, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[4] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 33, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[5] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 41, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[6] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 49, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PConnection.CryptKey[7] :=
BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 57, 8)), SizeOf(UInt32))), SizeOf(UInt32));
KopCfg.PSensors[0].TypeSensor := KopCfgJson.I['Шлейф1'];
KopCfg.PSensors[0].AlarmEnableDelay := 0;
KopCfg.PSensors[0].GetDelay := 0;
KopCfg.PSensors[0].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[0].TakeType := 0;
KopCfg.PSensors[1].TypeSensor := KopCfgJson.I['Шлейф2'];
KopCfg.PSensors[1].AlarmEnableDelay := 0;
KopCfg.PSensors[1].GetDelay := 0;
KopCfg.PSensors[1].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[1].TakeType := 0;
KopCfg.PSensors[2].TypeSensor := KopCfgJson.I['Шлейф3'];
KopCfg.PSensors[2].AlarmEnableDelay := 0;
KopCfg.PSensors[2].GetDelay := 0;
KopCfg.PSensors[2].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[2].TakeType := 0;
KopCfg.PSensors[3].TypeSensor := KopCfgJson.I['Шлейф4'];
KopCfg.PSensors[3].AlarmEnableDelay := 0;
KopCfg.PSensors[3].GetDelay := 0;
KopCfg.PSensors[3].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[3].TakeType := 0;
KopCfg.PSensors[4].TypeSensor := KopCfgJson.I['Шлейф5'];
KopCfg.PSensors[4].AlarmEnableDelay := 0;
KopCfg.PSensors[4].GetDelay := 0;
KopCfg.PSensors[4].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[4].TakeType := 0;
KopCfg.PSensors[5].TypeSensor := KopCfgJson.I['Шлейф6'];
KopCfg.PSensors[5].AlarmEnableDelay := 0;
KopCfg.PSensors[5].GetDelay := 0;
KopCfg.PSensors[5].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[5].TakeType := 0;
KopCfg.PSensors[6].TypeSensor := KopCfgJson.I['Шлейф7'];
KopCfg.PSensors[6].AlarmEnableDelay := 0;
KopCfg.PSensors[6].GetDelay := 0;
KopCfg.PSensors[6].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[6].TakeType := 0;
KopCfg.PSensors[7].TypeSensor := KopCfgJson.I['Шлейф8'];
KopCfg.PSensors[7].AlarmEnableDelay := 0;
KopCfg.PSensors[7].GetDelay := 0;
KopCfg.PSensors[7].ExternalIndicatorEnableTime := 0;
KopCfg.PSensors[7].TakeType := 0;
KopCfg.Outputs[0] := KopCfgJson.I['Выход1'];
KopCfg.Outputs[1] := KopCfgJson.I['Выход2'];
KopCfg.Outputs[2] := KopCfgJson.I['Выход3'];
KopCfg.Outputs[3] := KopCfgJson.I['Выход4'];
KopCfg.BatteryLevel := KopCfgJson.I['ПороговоеНапряжение'];
KopCfg.SensorPower12V := KopCfgJson.I['НапряжениеШлейфов'];
CfgByte := RawToBytes(KopCfg, 872);
LogOut(IntToStr(High(CfgByte)));
for I := 0 to High(CfgByte) do
CfgByte2[I] := CfgByte[I];
// PrintBuf2(CfgByte2);
Crc := protocolCrc16(@CfgByte2, 872);
KopCfg.Crc := Crc;
LogOut('Crc = ' + IntToStr(Crc));
CfgByte := RawToBytes(KopCfg, 874);
// PrintBuf(CfgByte);
for I := 0 to High(CfgByte) do
CfgByte3[I] := CfgByte[I];
Result := CfgByte3;
// AssignFile(f, 'mycfg.kopcfg');
// FileMode := fmOpenWrite;
// Reset(f, 1);
// for I := 0 to High(CfgByte) do
// BlockWrite(f, CfgByte[I], 1);
end;
function Test: boolean;
begin
end;
function BufToStr(var Buf): string;
var i: integer; IdBuf: TIdBytes;
begin
Result := '';
SetLength(IdBuf, SizeOf(Buf));
Move(Buf, IdBuf, SizeOf(Buf));
//
//
for i := 0 to SizeOf(Buf) - 1 do
begin
Result := Result + Chr(IdBuf[i]);
end;
Result := Trim(Result);
end;
function RecordToJson(KopCfg: TKopConfig): ISuperObject;
var
Line : string;
Bytes : TArray<Byte>;
I : Integer;
begin
Result := SO();
SetLength(Bytes, Length(KopCfg.PConnection.PEthernetServer1.Host));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PEthernetServer1.Host[I];
Result.S['ХостEthernet1'] := TEncoding.UTF8.GetString(Bytes);
Result.I['ПортEthernet1'] := KopCfg.PConnection.PEthernetServer1.Port;
SetLength(Bytes, Length(KopCfg.PConnection.PEthernetServer2.Host));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PEthernetServer2.Host[I];
Result.S['ХостEthernet2'] := TEncoding.UTF8.GetString(Bytes);
Result.I['ПортEthernet2'] := KopCfg.PConnection.PEthernetServer2.Port;
SetLength(Bytes, Length(KopCfg.PConnection.PGprsServer1.Host));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGprsServer1.Host[I];
Result.S['ХостGPRS1'] := TEncoding.UTF8.GetString(Bytes);
Result.I['ПортGPRS1'] := KopCfg.PConnection.PGprsServer1.Port;
SetLength(Bytes, Length(KopCfg.PConnection.PGprsServer2.Host));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGprsServer2.Host[I];
Result.S['ХостGPRS2'] := TEncoding.UTF8.GetString(Bytes);
Result.I['ПортGPRS2'] := KopCfg.PConnection.PGprsServer2.Port;
Result.I['ПорядокКаналовСвязи'] := KopCfg.PConnection.ChanellOrder;
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim1.Apn));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim1.Apn[I];
Result.S['APN1'] := TEncoding.UTF8.GetString(Bytes);
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim1.User));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim1.User[I];
Result.S['Логин1'] := TEncoding.UTF8.GetString(Bytes);
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim1.Pass));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim1.Pass[I];
Result.S['Пароль1'] := TEncoding.UTF8.GetString(Bytes);
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim1.UssdBalance));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim1.UssdBalance[I];
Result.S['USSD1'] := TEncoding.UTF8.GetString(Bytes);
Result.I['ПериодЗапросаБаланса1'] := KopCfg.PConnection.PGsm.PSim1.BalanceRequestPeriod;
Result.I['ПозицияПервойЦифры1'] := KopCfg.PConnection.PGsm.PSim1.BalanceFirstDigit;
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim2.Apn));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim2.Apn[I];
Result.S['APN2'] := TEncoding.UTF8.GetString(Bytes);
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim2.User));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim2.User[I];
Result.S['Логин2'] := TEncoding.UTF8.GetString(Bytes);
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim2.Pass));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim2.Pass[I];
Result.S['Пароль2'] := TEncoding.UTF8.GetString(Bytes);
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.PSim2.UssdBalance));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.PSim2.UssdBalance[I];
Result.S['USSD2'] := TEncoding.UTF8.GetString(Bytes);
Result.I['ПериодЗапросаБаланса2'] := KopCfg.PConnection.PGsm.PSim2.BalanceRequestPeriod;
Result.I['ПозицияПервойЦифры2'] := KopCfg.PConnection.PGsm.PSim2.BalanceFirstDigit;
Result.I['ОсновнаяSIMКарта'] := KopCfg.PConnection.PGsm.MainSim;
Result.I['ВернутьсяНаОсновнуюSIMЧерез'] := KopCfg.PConnection.PGsm.ReturnToMainSimTime;
Result.I['ПродлеватьБалансРезервнойSIMРазВ'] := KopCfg.PConnection.PGsm.BalanceRenewalTime;
SetLength(Bytes, Length(KopCfg.PConnection.PGsm.SmsPhone));
for I := 0 to High(Bytes) do
Bytes[I] := KopCfg.PConnection.PGsm.SmsPhone[I];
Result.S['НомерДляОтправкиСМС'] := TEncoding.UTF8.GetString(Bytes);
if KopCfg.PConnection.PGsm.SendEventsViaSms = 1 then
Result.B['ОтправлятьСобытияПоСМС'] := True
else if KopCfg.PConnection.PGsm.SendEventsViaSms = 0 then
Result.B['ОтправлятьСобытияПоСМС'] := False;
if KopCfg.PConnection.PEthernet.UseDhcp = 1 then
Result.B['ИспользоватьDHCP'] := True
else if KopCfg.PConnection.PEthernet.UseDhcp = 0 then
Result.B['ИспользоватьDHCP'] := False;
Result.S['IP'] := IntToStr(KopCfg.PConnection.PEthernet.Ip[0]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Ip[1]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Ip[2]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Ip[3]);
Result.S['Маска'] := IntToStr(KopCfg.PConnection.PEthernet.Mask[0]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Mask[1]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Mask[2]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Mask[3]);
Result.S['Шлюз'] := IntToStr(KopCfg.PConnection.PEthernet.Gateway[0]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Gateway[1]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Gateway[2]) + '.' +
IntToStr(KopCfg.PConnection.PEthernet.Gateway[3]);
if KopCfg.PConnection.SendEventsViaATS100 = 1 then
Result.B['ОтправлятьСобытияЧерезATS100'] := True
else if KopCfg.PConnection.SendEventsViaATS100 = 0 then
Result.B['ОтправлятьСобытияЧерезATS100'] := False;
Result.I['УИД'] := KopCfg.PConnection.DeviceId;
Result.S['КлючШифрования'] :=
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[0], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[1], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[2], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[3], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[4], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[5], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[6], SizeOf(UInt32))), SizeOf(UInt32)), 8) +
IntToHex(BtsToInt(SwapBytes(IntToBytes(KopCfg.PConnection.CryptKey[7], SizeOf(UInt32))), SizeOf(UInt32)), 8);
// BtsToInt(SwapBytes(IntToBytes(KopCfg.PSensors[0].TypeSensor, SizeOf(UInt32))), SizeOf(UInt32))
Result.I['Шлейф1'] := KopCfg.PSensors[0].TypeSensor;
Result.I['Шлейф2'] := KopCfg.PSensors[1].TypeSensor;
Result.I['Шлейф3'] := KopCfg.PSensors[2].TypeSensor;
Result.I['Шлейф4'] := KopCfg.PSensors[3].TypeSensor;
Result.I['Шлейф5'] := KopCfg.PSensors[4].TypeSensor;
Result.I['Шлейф6'] := KopCfg.PSensors[5].TypeSensor;
Result.I['Шлейф7'] := KopCfg.PSensors[6].TypeSensor;
Result.I['Шлейф8'] := KopCfg.PSensors[7].TypeSensor;
Result.I['Выход1'] := KopCfg.Outputs[0];
Result.I['Выход2'] := KopCfg.Outputs[1];
Result.I['Выход3'] := KopCfg.Outputs[2];
Result.I['Выход4'] := KopCfg.Outputs[3];
Result.F ['ПороговоеНапряжение'] := KopCfg.BatteryLevel;
Result.I['НапряжениеШлейфов'] := KopCfg.SensorPower12V;
// Key := KopCfgJson.S['КлючШифрования'];
//
// KopCfg.PConnection.CryptKey[0] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 1, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[1] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 9, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[2] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 17, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[3] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 25, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[4] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 33, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[5] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 41, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[6] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 49, 8)), SizeOf(UInt32))), SizeOf(UInt32));
// KopCfg.PConnection.CryptKey[7] :=
// BtsToInt(SwapBytes(IntToBytes(HexToInt(Copy(Key, 57, 8)), SizeOf(UInt32))), SizeOf(UInt32));
end;
end.
|
unit l3Filer;
{* Реализация компонента-обертки вокруг потока. }
{ Библиотека "L3 (Low Level Library)" }
{ Автор: Люлин А.В. c }
{ Модуль: l3Filer - функции виртуальной файловой системы}
{ Начат: 08.04.1997 18:33 }
{ $Id: l3Filer.pas,v 1.206 2016/04/06 21:08:11 lulin Exp $ }
// $Log: l3Filer.pas,v $
// Revision 1.206 2016/04/06 21:08:11 lulin
// - обрабатываем ошибки.
//
// Revision 1.205 2016/01/26 12:02:20 fireton
// - корректируем f_StreamPos при Readln (чтобы работал Seek c soCurrent
// в случае если он происходит назад через границу буфера [UngetChars])
//
// Revision 1.204 2015/12/28 15:13:11 lulin
// - заготовочка следилки за списком скриптов.
//
// Revision 1.203 2015/10/09 14:48:40 kostitsin
// {requestlink: 604917289 } - инициализируем неинициализированное
//
// Revision 1.202 2015/09/25 09:44:34 dinishev
// {Requestlink:607284377}
//
// Revision 1.201 2015/05/19 16:46:46 lulin
// - чистим код.
//
// Revision 1.200 2015/05/08 12:12:07 dinishev
// {Requestlink:598615356}. Поддержка чтения картинок с формулами.
//
// Revision 1.199 2015/02/26 12:18:26 fireton
// - более правильно корректируем размер буфера при его переполнении
//
// Revision 1.198 2015/01/30 09:51:08 dinishev
// {Requestlink:522781827}
//
// Revision 1.197 2014/10/27 15:50:35 lulin
// - вставляем затычку.
//
// Revision 1.196 2014/04/08 08:18:00 dinishev
// {Requestlink:526715670}
//
// Revision 1.195 2014/02/03 16:10:25 lulin
// - рефакторинг парсера.
//
// Revision 1.194 2013/12/27 10:50:31 lulin
// {RequestLink:509706011}
//
// Revision 1.193 2013/12/16 16:57:56 lulin
// {RequestLink:509088042}
//
// Revision 1.192 2013/12/11 13:49:59 morozov
// {RequestLink: 508445329}
//
// Revision 1.191 2013/07/10 16:29:35 lulin
// - чистим код.
//
// Revision 1.190 2013/06/06 11:03:32 dinishev
// Фактичски правки для {Requestlink:459284359}
//
// Revision 1.189 2013/05/17 16:03:54 voba
// - K:455105818
//
// Revision 1.188 2013/04/29 11:38:06 fireton
// - заменил Assert на Stack2Log (чтобы не прерывать процессы, которые обламываются по assert)
//
// Revision 1.187 2013/04/26 10:20:56 fireton
// - возвращаем Assert
//
// Revision 1.186 2013/04/26 06:13:11 fireton
// - откручиваем Assert
//
// Revision 1.185 2013/04/25 13:41:37 voba
// - вставил Assert контролирующий попытку записи в закрытый поток
//
// Revision 1.184 2013/04/10 16:00:33 lulin
// - портируем.
//
// Revision 1.183 2013/04/10 13:59:30 lulin
// - портируем.
//
// Revision 1.182 2013/04/10 11:27:01 lulin
// - портируем.
// - и поправил ошибку с проездом по памяти.
//
// Revision 1.181 2013/04/08 18:10:29 lulin
// - пытаемся отладиться под XE.
//
// Revision 1.180 2013/04/08 14:50:41 lulin
// - портируем.
//
// Revision 1.179 2013/03/28 16:13:50 lulin
// - портируем.
//
// Revision 1.178 2012/07/11 09:56:36 fireton
// - получаем размер через GetSize инкапсулированного элемента (чтобы избежать Seek)
//
// Revision 1.177 2012/03/02 11:14:52 lulin
// - работа с файлами.
// - работа с символами.
// - работа со строками с длинной.
// - доопределение методов внутри стереотипов/классов.
//
// Revision 1.176 2012/02/28 12:55:37 lulin
// {RequestLink:336664105}
//
// Revision 1.175 2012/01/27 14:48:17 lulin
// http://mdp.garant.ru/pages/viewpage.action?pageId=288786476&focusedCommentId=331187776#comment-331187776
//
// Revision 1.174 2011/12/28 11:13:02 lulin
// {RequestLink:325256237}
//
// Revision 1.173 2011/12/27 15:34:04 lulin
// {RequestLink:324571064}
// - обкладываем все возможные неудачные Seek ловушками try..except. Чтобы таки попытаться считать документ.
//
// Revision 1.172 2011/09/20 09:25:38 lulin
// - очищаем состояние Filer'а.
//
// Revision 1.171 2011/09/19 13:54:04 lulin
// - очищаем состояние Filer'а.
//
// Revision 1.170 2011/09/19 13:17:16 lulin
// - очищаем состояние Filer'а.
//
// Revision 1.169 2011/09/19 10:23:01 lulin
// - делаем Filer'ам возможность быть не компонентами и кешируемыми.
//
// Revision 1.168 2011/09/19 10:13:35 lulin
// - делаем Filer'ам возможность быть не компонентами и кешируемыми.
//
// Revision 1.166 2011/05/06 15:49:38 lulin
// - делаем "предложения".
//
// Revision 1.165 2010/12/08 19:04:29 lulin
// {RequestLink:228688602}.
// - закругляем край у строки ввода.
//
// Revision 1.164 2010/11/19 14:40:18 fireton
// - _Write и Writeln для Tl3WString
//
// Revision 1.163 2010/11/19 14:39:49 lulin
// {RequestLink:220202427}.
//
// Revision 1.162 2010/07/28 10:57:45 lulin
// {RequestLink:228691360}.
//
// Revision 1.161 2010/06/18 11:41:11 lulin
// {RequestLink:219119831}.
// - правим ошибку.
// - добавляем тест.
// - давим вывод в лог.
// - вставляем проверку на корректность длины результирующей строки.
//
// Revision 1.160 2010/06/16 11:49:13 narry
// - K217689968
//
// Revision 1.159 2010/03/18 14:15:46 lulin
// {RequestLink:197951943}.
//
// Revision 1.158 2009/12/25 14:23:52 lulin
// - избегаем магических чисел.
//
// Revision 1.157 2009/12/25 14:16:49 lulin
// - выкидываем старый код.
//
// Revision 1.156 2009/12/25 14:09:31 lulin
// {RequestLink:175964656}.
//
// Revision 1.155 2009/12/24 19:04:16 lulin
// - вставлен Assert.
//
// Revision 1.154 2009/12/24 15:04:09 lulin
// {RequestLink:175540286}.
//
// Revision 1.153 2009/12/17 10:28:34 lulin
// - закомментировал устаревший метод.
//
// Revision 1.152 2009/12/17 10:15:42 lulin
// {RequestLink:174293230}. Не обрабатывали Юникод.
//
// Revision 1.151 2009/12/16 15:30:15 lulin
// - правильнее вычисляем конец файла.
//
// Revision 1.150 2009/12/16 15:26:29 lulin
// - правильнее вычислем указатель на запомненную строку.
//
// Revision 1.149 2009/12/16 15:06:19 lulin
// - обходимся без дополнительной строки. Просто расширяем существующий буфер.
//
// Revision 1.148 2009/12/16 14:22:03 lulin
// - боремся с распуханием буферов.
//
// Revision 1.147 2009/12/15 12:11:43 lulin
// - чистим код и правим ошибки.
//
// Revision 1.146 2009/12/15 09:58:55 lulin
// - по-другому перераспределяем память.
//
// Revision 1.145 2009/12/14 16:53:39 lulin
// {RequestLink:168230991}.
//
// Revision 1.144 2009/12/14 12:07:49 lulin
// - чистка кода.
//
// Revision 1.143 2009/12/14 12:01:44 lulin
// - временно отказываемся читать юникодные файлы.
//
// Revision 1.142 2009/12/14 11:58:41 lulin
// - прячем кишки.
//
// Revision 1.141 2009/12/14 11:46:55 lulin
// - готовимся к возврату более простых строк.
//
// Revision 1.140 2009/09/07 10:28:45 voba
// - opt. Tl3BufferStreamMemoryPool - Стандартный буфер для буферизованных потоков
//
// Revision 1.139 2009/07/23 08:15:07 lulin
// - вычищаем ненужное использование процессора операций.
//
// Revision 1.138 2009/03/18 14:59:56 lulin
// - делаем возможность отката, если во время записи произошло исключение.
//
// Revision 1.137 2008/12/12 19:19:30 lulin
// - <K>: 129762414.
//
// Revision 1.136 2008/06/06 11:58:08 fireton
// - форматирование
//
// Revision 1.135 2008/03/24 11:52:14 lulin
// - <K>: 85169205.
//
// Revision 1.134 2007/12/24 15:25:32 lulin
// - удалены ненужные файлы.
//
// Revision 1.133 2007/08/30 10:09:23 lulin
// - убираем ненужную функцию поиска.
//
// Revision 1.132 2007/08/28 17:07:12 lulin
// - оптимизируем загрузку строк.
//
// Revision 1.131 2007/08/28 16:25:14 lulin
// - не поддерживаем чтение очень старых версий EVD.
//
// Revision 1.130 2007/08/28 15:13:14 lulin
// - читаем данные в буфер, когда точно поняли, что он пустой.
//
// Revision 1.129 2007/08/28 14:27:03 lulin
// - поднимаем исключение, если считано меньше, чем просили.
//
// Revision 1.128 2007/08/28 13:53:29 lulin
// - оптимизируем чтение.
//
// Revision 1.127 2007/08/28 12:59:06 lulin
// - лишний раз не получаем файлер.
// - оптимизируем процедуру чтения файлера.
//
// Revision 1.126 2007/08/15 15:34:07 lulin
// - используем общую процедуру.
//
// Revision 1.125 2007/08/14 19:31:59 lulin
// - оптимизируем очистку памяти.
//
// Revision 1.124 2007/08/14 15:19:28 lulin
// - оптимизируем перемещение блоков памяти.
//
// Revision 1.123 2007/08/14 14:30:12 lulin
// - оптимизируем перемещение блоков памяти.
//
// Revision 1.122 2007/08/14 13:13:20 lulin
// - откатываем предудущие изменения.
//
// Revision 1.120 2007/08/14 12:33:06 lulin
// - оптимизируем _Move.
//
// Revision 1.119 2007/08/14 12:27:56 lulin
// - cleanup.
//
// Revision 1.118 2007/08/14 12:07:16 lulin
// - cleanup.
//
// Revision 1.117 2007/08/14 11:42:14 lulin
// - оптимизируем _Move.
//
// Revision 1.116 2007/08/13 15:48:58 lulin
// - уменьшаем ненужное определение типа потока.
//
// Revision 1.115 2007/08/10 19:17:27 lulin
// - cleanup.
//
// Revision 1.114 2007/08/09 08:19:04 lulin
// - при записи строци используем целевую кодировку потока.
//
// Revision 1.113 2007/08/06 07:23:26 voba
// - bug fix
//
// Revision 1.112 2007/08/02 18:02:58 lulin
// - оптимизируем строки.
//
// Revision 1.111 2007/08/02 17:38:14 lulin
// - оптимизируем строки.
//
// Revision 1.110 2007/08/02 17:24:55 lulin
// - оптимизируем строки.
//
// Revision 1.109 2007/08/01 15:15:53 voba
// - opt.
//
// Revision 1.108 2007/02/12 18:45:06 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.107 2007/02/12 18:06:19 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.106 2007/02/12 16:40:36 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.105 2007/01/22 15:20:13 oman
// - new: Локализация библиотек - l3 (cq24078)
//
// Revision 1.104 2006/09/06 11:21:59 voba
// - bug fix
//
// Revision 1.103 2006/04/26 12:16:23 voba
// - bug fix: архивирующие потоки не работали над файловыми потоками, отличными от m3.
//
// Revision 1.102 2006/04/25 12:47:50 lulin
// - cleanup.
//
// Revision 1.101 2005/10/04 09:19:58 lulin
// - new behavior: сделана возможность получать имя записываемго в поток файла.
//
// Revision 1.100 2005/10/04 09:13:24 lulin
// - new behavior: сделана возможность получать имя записываемго в поток файла.
//
// Revision 1.99 2005/10/04 08:42:09 lulin
// - cleanup.
//
// Revision 1.98 2005/06/24 18:19:59 lulin
// - обрабатываем потоки, которые вообще не поддерживают Seek.
//
// Revision 1.97 2005/05/23 15:06:07 lulin
// - cleanup.
//
// Revision 1.96 2005/04/19 15:41:51 lulin
// - переходим на "правильный" ProcessMessages.
//
// Revision 1.95 2005/01/26 17:18:04 lulin
// - изменено собщение о загрузке файла.
//
// Revision 1.94 2005/01/24 11:43:23 lulin
// - new behavior: при освобождении заглушки очищаем указатель на нее.
//
// Revision 1.93 2005/01/19 14:29:56 lulin
// - не пишем дурацкий ноль и/или пустые квадратные скобки.
//
// Revision 1.92 2005/01/17 16:37:33 migel
// - add: поддержка задания времени таймаута при открытии файла на диске.
//
// Revision 1.91 2004/12/30 11:46:34 lulin
// - интерфейсы относящиеся к Preview переехали в библиотеку _AFW.
//
// Revision 1.90 2004/12/17 14:00:28 am
// change: в Tl3CustomFiler._Write вместо TStream._Write используем TStream.WriteBuffer, соотв. если запись не удаётся - поднимается исключение.
//
// Revision 1.89 2004/11/03 14:27:00 lulin
// - bug fix: не пытаемся делать Seek при записи файла.
//
// Revision 1.88 2004/10/19 17:58:04 lulin
// - new behavior: избавился от фрагментации памяти в методе TevCustomEvdReader._AddRawData.
//
// Revision 1.87 2004/09/27 11:32:58 lulin
// - new method: Im3DB.SingleDocument.
//
// Revision 1.86 2004/09/24 16:20:12 lulin
// - добавлены комментарии.
//
// Revision 1.85 2004/09/24 16:13:43 lulin
// - bug fix: аккуратнее обрабатываем переполнение буфера.
//
// Revision 1.84 2004/09/24 15:51:19 lulin
// - bug fix: повторная (неправильная) загрузка буфера приводила к затиранию чужой памяти.
// - bug fix: аккуратнее обходимся с ситуацией когда Stream = nil.
//
// Revision 1.83 2004/09/24 07:54:47 lulin
// - были несбалансированы скобки индикатора.
//
// Revision 1.82 2004/09/21 10:30:18 lulin
// - Release заменил на Cleanup.
//
// Revision 1.81 2004/08/31 17:02:20 law
// - cleanup: убраны ненужные параметры.
//
// Revision 1.80 2004/08/27 10:56:20 law
// - new const: l3_fmExclusiveReadWrite.
//
// Revision 1.79 2004/08/24 07:31:51 law
// - bug fix: падало при попытке установки f_EOF при открытии файла на запись.
//
// Revision 1.78 2004/08/24 04:47:23 law
// - bug fix: после падения при открытии файла последующая работа с существующим экземпляром Tl3CustomFiler была невозможно, т.к. в ней "повисал" старый поток - в котором произошла ошибка.
//
// Revision 1.77 2004/08/20 15:15:27 law
// - cleanup.
//
// Revision 1.76 2004/08/19 15:36:58 law
// - в нулевом приближении сделана индексация нового хранилища.
//
// Revision 1.75 2004/08/13 13:57:28 law
// - добавлена "своя" константа.
//
// Revision 1.74 2004/08/13 13:09:26 law
// - cleanup.
//
// Revision 1.73 2004/08/06 14:22:32 law
// - избавился от части Warnings/Hints.
//
// Revision 1.72 2004/05/20 12:06:27 law
// - bug fix: неправильно записывались концы строк в cp_UnicodeText и cp_Text.
//
// Revision 1.71 2004/05/07 16:38:17 law
// - заготовка для сбора статистики по длинам файлов.
//
// Revision 1.70 2004/04/26 14:28:24 law
// - new behavior: Tl3Filer теперь при чтении посимвольно учитывает кодировку.
// - bug fix: в свойство TevMemo.Buffer теперь нормально присваиваются строки с кодировкой Unicode.
//
// Revision 1.69 2004/04/26 13:06:03 law
// - bug fix: теперь в TevEdit и TevMemo корректно присваиваются строчки не только с кодировками CP_ANSI, CP_OEM.
//
// Revision 1.68 2004/03/31 17:59:28 law
// - bug fix: корректно пишем/читаем Unicode-строки в бинарный EVD.
//
// Revision 1.67 2004/03/31 17:31:09 law
// - new behavior: парсер теперь умеет читать unicode-строки (как в Delphi).
//
// Revision 1.66 2003/12/26 13:38:29 law
// - bug fix: другая (более успешная попытка) попытка починить ошибку CQ OIT5-4532.
//
// Revision 1.65 2003/11/06 14:13:54 law
// - bug fix: Tl3SubStream не работал с потоком, который не поддерживает Seek.
//
// Revision 1.64 2003/10/15 08:29:27 law
// - bug fix: оформление параграфов накапливалось в один буфер.
//
// Revision 1.63 2003/09/12 16:37:08 law
// - bug fix: не затиралось предыдущее значение окна для закрытия -> бесконечный цикл закрытия.
//
// Revision 1.62 2003/06/20 16:52:25 law
// - new behavior: при получении размера потока учитываем тот факт, что данная функция может быть нереализована.
//
// Revision 1.61 2003/03/13 16:37:20 law
// - change: попытка портировать на Builder.
//
// Revision 1.60 2002/12/24 13:02:03 law
// - change: объединил Int64_Seek c основной веткой.
//
// Revision 1.59.2.1 2002/12/23 15:51:28 law
// - bug fix: не работали с хранилищем > 2Гб.
//
// Revision 1.59 2002/09/09 13:25:05 law
// - cleanup.
//
// Revision 1.58 2002/04/15 12:18:27 law
// - new behavior: запрещение определения кодировки в режиме "не для чтения".
//
// Revision 1.57 2002/04/03 13:50:39 law
// - new const: 3_fmExclusiveWrite, l3_fmExclusiveAppend.
//
// Revision 1.56 2002/02/26 15:48:08 law
// - optimization: попытка оптимизации путем уменьшения фрагментации выделяемой памяти.
//
// Revision 1.55 2002/02/20 12:41:39 law
// - new behavior: стараемся избежать двойной буферизации.
//
// Revision 1.54 2002/01/29 12:49:20 law
// - new behavior: переделан способ кеширования буферов.
//
// Revision 1.53 2002/01/16 15:43:30 law
// - bug fix: несогласованность при работе с индикатором.
//
// Revision 1.52 2002/01/08 12:11:27 narry
// - new behavior: проверка на совпадение имени файла при его присвоении.
//
// Revision 1.51 2002/01/08 09:29:50 law
// - change comment: исправлен предыдущий комментарий.
//
// Revision 1.50 2002/01/08 09:25:08 law
// - rename class: TevDOSFiler -> Tl3DOSFiler.
//
// Revision 1.49 2001/12/28 14:57:19 law
// - change: типы переименованы в соответствии с названием библиотеки.
//
// Revision 1.48 2001/10/18 14:54:37 law
// - new unit: l3WindowsStorageFiler.
//
// Revision 1.47 2001/10/15 14:56:09 law
// - bug fix: не нужен _LoadBuffer при Seek и Mode <> l3_fmRead.
//
// Revision 1.46 2001/09/11 10:12:02 law
// - new behavior: теперь в статус выводится идентификатор файла.
//
// Revision 1.45 2001/09/10 09:51:19 law
// - new behavior: изменена логика работы с индикатором при присваивании Stream.
//
// Revision 1.44 2001/09/07 12:40:38 law
// - new behavior: при закрытом потоке Filer открывает его когда отдает интерфейс IStream.
//
// Revision 1.43 2001/09/03 14:32:10 law
// - change method: изменен списока параметров метода Tl3CustomDOSFiler.Make.
//
// Revision 1.42 2001/09/03 14:22:40 law
// - new method: Tl3CustomDOSFiler.Make.
//
// Revision 1.41 2001/08/31 08:50:08 law
// - cleanup: первые шаги к кроссплатформенности.
//
// Revision 1.40 2001/08/29 07:01:10 law
// - split unit: l3Intf -> l3BaseStream, l3BaseDraw, l3InterfacedComponent.
//
// Revision 1.39 2001/07/24 12:30:24 law
// - comments: xHelpGen.
//
// Revision 1.38 2001/04/27 12:22:19 voba
// - bug fix: добавлена обработка ошибки получения размера файла.
//
// Revision 1.37 2001/04/27 11:37:22 voba
// - bug fix: добавлена очистка буфера после сбоя открытия потока.
//
// Revision 1.36 2001/03/27 14:22:36 law
// - к Tl3CustomFiler добавлен метод Identifier.
//
// Revision 1.35 2001/03/12 10:17:26 law
// - добавлены функции WriteLn.
//
// Revision 1.34 2001/03/02 12:54:44 law
// - bug fix: AV при _f_Stream = nil.
//
// Revision 1.33 2000/12/15 14:57:02 law
// - вставлены директивы Log.
//
{$Include l3Define.inc}
interface
uses
Windows,
SysUtils,
Classes,
l3Interfaces,
l3Types,
l3IID,
l3Base,
l3BaseStream,
l3Stream,
l3Chars,
l3ProgressComponent,
l3ProtoProgressComponent
;
type
Tl3CommentString = String[4];
Tl3CommentState = (l3_csNone, l3_csLine, l3_csMultiLine, l3_csAnOtherMultiLine);
Tl3NextTokenFlag = (l3_ntfSkipBlanks, l3_ntfSkipComment, l3_ntfCheckString, l3_ntfCheckDoubleQuotedString);
Tl3NextTokenFlags = set of Tl3NextTokenFlag;
Tl3GetFilePath = function : AnsiString of object;
Tl3CheckAbortedLoadEvent = procedure(Sender: TObject; var Aborted: Bool) of object;
{* - событие для проверки необходимости прервать операцию чтения. }
Tl3FilerBuffer = class(Tl3String);
Tl3StreamType = (l3_stUnknown, l3_stString, l3_stOther);
{$IfDef l3FilerIsComponent}
Tl3FilerOwner = Tl3ProgressComponentOwner;
{$Else l3FilerIsComponent}
Tl3FilerOwner = TObject;
{$EndIf l3FilerIsComponent}
Tl3CustomFiler = class({$IfDef l3FilerIsComponent}Tl3ProgressComponent{$Else}Tl3ProtoProgressComponent{$EndIf}, Il3Rollback)
{* Реализация компонента-обертки вокруг потока. }
private
// internal fields
f_Buffer : Tl3FilerBuffer; {-буфер чтения}
f_BufS : Tl3WString;
f_BufSize : Integer;
f_BufferOffset : Long;
f_PrevBuffer : Tl3FilerBuffer;
f_Mode : Tl3FileMode;
f_Line : Tl3String;
f_StreamType : Tl3StreamType;
private
// internal fields
f_StreamPos : Int64;
fl_WndToClose : hWnd;
fl_OpenCount : Long;
private
// property fields
f_ReadOnly : Bool;
f_AbortedLoad : Bool;
f_Handle : Long;
f_NeedProcessMessages : Bool;
f_EOF : Bool;
f_CodePage : Long;
f_NotSeekStream : Bool;
f_SoftEnterAsEOL: Boolean;
protected
// property fields
f_Stream : TStream;
private
// event fields
f_OnGetFilePath : Tl3GetFilePath;
f_OnCheckAbortedLoad : Tl3CheckAbortedLoadEvent;
protected
// property methods
function pm_GetSize: Int64;
{-}
function pm_GetOpened: Bool;
{-}
procedure pm_SetStream(Value: TStream);
{-}
function pm_GetCOMStream: IStream;
procedure pm_SetCOMStream(const Value: IStream);
{-}
procedure pm_SetMode(Value: Tl3FileMode);
{-}
procedure pm_SetHandle(Value: Long);
{-}
function pm_GetCodePage: Long;
{-}
protected
// internal methods
function InternalOpen(aMode: Tl3FileMode): Boolean;
{* - метод для внутреннего открытия потока. }
function DoOpen: Boolean;
virtual;
{* - метод для открытия потока. Для перекрытия в потомках. }
procedure DoClose;
virtual;
{* - метод для закрытия потока. Для перекрытия в потомках. }
procedure ProcessMessages;
{* - отдать управление. }
procedure AbortLoad;
{* - прервать операцию чтения. }
procedure CheckAbortedLoad;
{* - проверить необходимость прервать операцию чтения. }
function IsWriteMode(Mode: Tl3FileMode): Bool;
{-}
procedure FreeBuffer(aFullClean : Boolean);
{* - освободить буфер. }
function LoadBuffer: Bool;
{* - загрузить буфер. }
procedure Cleanup;
override;
{-}
procedure StartIndicator;
{-}
{$IfNDef l3FilerIsComponent}
class function IsCacheable : Boolean;
override;
{$EndIf l3FilerIsComponent}
public
{public methods}
constructor Create(anOwner: Tl3FilerOwner = nil); {$IfDef l3FilerIsComponent}override;{$EndIf}
{-}
function GetFilePath: AnsiString;
{-}
procedure Open;
{* - открыть поток. }
procedure Close;
{* - закрыть поток. }
procedure Rollback;
{* Откатить данные }
procedure Read(aBuf: PAnsiChar; aCount: Long);
{* - считать буфер из потока. }
function SizedRead(aBuf: PAnsiChar; aCount: Long): Long;
{* - считать буфер из потока. }
function ReadWord: Word;
{-}
function ReadLong: Long;
{-}
function ReadByte: Byte;
{-}
function Seek(const aOffset: Int64; aOrigin: TSeekOrigin): Int64;
{* - сместить указатель потока. }
function ReadLn: Tl3WString;
{* - считать строку до #13#10. }
function ReadHexLn(const aLineChars: TCharSet; aFinishChar: AnsiChar): Tl3WString;
{* - Считать строку с данными в шестнадцатиричном виде. В качестве параметра - допустимые символы. }
function MakeReadString(aLen : Long;
aCodePage : Long): Tl3String;
{* - считать строку. }
function GetC: Tl3Char;
{* - получить символ из потока. }
procedure UngetC;
{* - вернуть символ в поток. }
procedure UngetChars(aCount: Integer);
{* - вернуть несколько символов в поток. }
function Write(C: Char): Long;
overload;
{* - записать символ в поток. }
function Write(Buf: PAnsiChar; Count: Long): Long;
overload;
{* - записать буфер в поток. }
function Write(const S: AnsiString): Long;
overload;
{* - записать строку в поток. }
function Write(S: Tl3PrimString): Long;
overload;
{* - записать строку в поток. }
function WriteLn(S: Tl3PrimString): Long;
overload;
{* - записать строку в поток дополнив ее #13#10. }
function Write(const S: Tl3WString): Long;
overload;
{* - записать строку в поток. }
function WriteLn(const S: Tl3WString): Long;
overload;
{* - записать строку в поток дополнив ее #13#10. }
function WriteLn(const S: AnsiString): Long;
overload;
{* - записать строку в поток дополнив ее #13#10. }
function CloseQuery(Wnd: hWnd): Bool;
{* - запрос на возможность закрытия. }
function GetCodePage: Long;
{* - получить кодовую страницу символов потока эмпирическим путем. }
procedure AnalizeCodePage;
{* - установить __CodePage в значение, полученное при помощи GetCodePage. }
procedure Analize(var OEMCount, ANSICount: Long);
{* - проанализировать поток на предмет частоты встречаемости символов. }
procedure SkipEOL;
{* - пропустить конец строки. }
function OutEOL: Long;
{* - вывести конец строки. }
function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult;
override;
{-}
function CheckLine(NeedChangeCodePage: Boolean = true): Tl3String;
{* - вернуть временный буфер. }
function Identifier: String;
virtual;
{* - вернуть идентификатор потока (например имя файла). }
procedure Flush;
{-}
public
// public properties
property ReadOnly: Bool
read f_ReadOnly
write f_ReadOnly
default false;
{* - поток только для чтения? }
property Size: Int64
read pm_GetSize;
{* - размер потока. }
property Pos: Int64
read f_StreamPos;
{* - текущая позиция потока. }
property Stream: TStream
read f_Stream
write pm_SetStream;
{* - собственно поток. }
property COMStream: IStream
read pm_GetCOMStream
write pm_SetCOMStream;
{* - поток для COM. }
property Opened: Bool
read pm_GetOpened;
{* - поток открыт? }
property NeedProcessMessages: Bool
read f_NeedProcessMessages
write f_NeedProcessMessages
default false;
{* - надо ли отдавать управление во время длительных операций? }
property AbortedLoad: Bool
read f_AbortedLoad
write f_AbortedLoad;
{* - прервана загрузка? }
property Handle: Long
read f_Handle
write pm_SetHandle;
{* - целочисленный идентификатор потока. }
property EOF: Bool
read f_EOF;
{* - достигнут конец потока? }
property Mode: Tl3FileMode
read f_Mode
write pm_SetMode;
{* - режим работы с потоком. }
property CodePage: Long
read pm_GetCodePage
write f_CodePage
default CP_ANSI;
{* - кодовая страница данных потока. }
property NotSeekStream: Bool
read f_NotSeekStream;
property SoftEnterAsEOL: Boolean
read f_SoftEnterAsEOL
write f_SoftEnterAsEOL;
{-}
public
{events}
property OnGetFilePath: Tl3GetFilePath
read f_OnGetFilePath
write f_OnGetFilePath;
{* - Событие для получения пути к файлу. }
property OnCheckAbortedLoad: Tl3CheckAbortedLoadEvent
read f_OnCheckAbortedLoad
write f_OnCheckAbortedLoad;
{* - событие для проверки необходимости прервать операцию чтения. }
end;{Tl3CustomFiler}
Il3FilerSource = interface(Il3Base)
['{94E711B9-E159-4CC9-B3A4-80612AC0A12E}']
{property methods}
function pm_GetFiler: Tl3CustomFiler;
procedure pm_SetFiler(Value: Tl3CustomFiler);
{-}
{public properties}
property Filer: Tl3CustomFiler
read pm_GetFiler
write pm_SetFiler;
{-}
end;//Il3FilerSource
Tl3FilerStream = class(Tl3Stream, Il3FilerSource, Il3Rollback)
{* Класс для преобразования обертки обратно в поток. }
private
{internal fields}
f_Filer : Tl3CustomFiler;
protected
// interface methods
function pm_GetFiler: Tl3CustomFiler;
procedure pm_SetFiler(Value: Tl3CustomFiler);
{-}
protected
{internal methods}
procedure Cleanup;
override;
function GetSize: Int64; override;
{-}
public
{public methods}
constructor Create(anOwner: Tl3CustomFiler);
reintroduce;
{-}
procedure Rollback;
{* Откатить данные }
function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult;
override;
{-}
function Read(var Buffer; Count: Longint): Longint;
override;
{-}
function Write(const Buffer; Count: Longint): Longint;
override;
{-}
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
override;
{-}
public
// public properties
property Filer: Tl3CustomFiler
read f_Filer;
{-}
end;{Tl3FilerStream}
Tl3OutExtLongEvent = procedure(Sender: TObject; Handle: Long; Filer: Tl3CustomFiler) of object;
{* - событие для записи целочисленного параметра в поток. }
Tl3CustomDOSFiler = class(Tl3CustomFiler)
{* Обертка вокруг потока, который работает с файлом на диске. }
private
{ Private declarations }
f_FileName : TFileName;
f_TimeOut : Longword;
protected
{property methods}
procedure pm_SetFileName(const Value: TFileName);
{-}
procedure pm_SetTimeOut(Value: Longword);
{-}
protected
{internal methods}
function DoOpen: Boolean;
override;
{-}
procedure Cleanup;
override;
{-}
public
//public methods
constructor Make(const aFileName : String;
anOpenMode : Tl3FileMode = l3_fmRead;
NeedAnalizeCodePage : Bool = true;
aTimeOut : Longword = Cl3FileStreamDefaultTimeOut);
{* - создает Filer. }
function Identifier: String;
override;
{-}
public
// public properties
property FileName: TFileName
read f_FileName
write pm_SetFileName;
{* - имя файла. }
property TimeOut: Longword
read f_TimeOut
write pm_SetTimeOut;
{* - время таймаута (измеряется в тиках). }
end;//Tl3CustomDOSFiler
Tl3DOSFiler = class(Tl3CustomDOSFiler)
{*! Обертка вокруг потока, который работает с файлом на диске. Для конечного использования на форме. }
published
// properties
property ReadOnly;
{-}
property FileName;
{-}
property TimeOut default Cl3FileStreamDefaultTimeOut;
{-}
property NeedProcessMessages;
{-}
property Indicator;
{-}
property CodePage;
{-}
published
// events
property OnCheckAbortedLoad;
{-}
end;//Tl3DOSFiler
TevDOSFiler = class(Tl3DOSFiler);
Tl3FilerAction = function(aFiler: Tl3CustomFiler): Bool;
{-}
function l3FileMode2SysUtilsFileMode(l3FileMode: Tl3FileMode): Cardinal;
{* - преобразовать Tl3FileMode в режим работы с файлом из модуля SysUtils. }
function l3L2FilerAction(Action: Pointer): Tl3FilerAction;
{* - делает заглушку для локальной процедуры. }
procedure l3FreeFilerAction(var Stub: Tl3FilerAction);
{* - освобождает заглушку для локальной процедуры. }
implementation
uses
ComObj,
Messages,
{$IfDef l3ConsoleApp}
{$Else l3ConsoleApp}
Forms,
{$EndIf l3ConsoleApp}
l3InternalInterfaces,
l3MinMax,
l3Const,
l3Except,
l3InterfacesMisc,
l3Memory,
l3IntegerValueMapManager,
l3String,
l3StringEx,
l3FilerRes,
m2InternalInterfaces,
afwFacade
;
resourcestring
cFileSizeErrorFmt = 'Ошибка получения размера файла [%s]';
const
l3FilerBufSize = l3ParseBufSize
//{$IfDef XE} * 2 {$EndIf}
{$IfDef Nemesis}
{* 2}
{$EndIf Nemesis}
;
function l3StreamSize(aStream : TStream): Int64;
var
l_SS : Im2StoreStat;
begin
if Supports(aStream, Im2StoreStat, l_SS) then
try
Result := l_SS.Size
finally
l_SS := nil;
end//try..finally
else
Result := aStream.Size;
end;
function l3StreamPos(aStream : TStream): Int64;
var
l_SS : Im2StoreStat;
begin
if Supports(aStream, Im2StoreStat, l_SS) then
try
Result := l_SS.Position
finally
l_SS := nil;
end//try..finally
else
Result := aStream.Position;
end;
function IsReadMode(aMode: Tl3FileMode): Boolean;
begin
Result := (aMode = l3_fmRead) OR (aMode = l3_fmFullShareRead);
end;
function l3FileMode2SysUtilsFileMode(l3FileMode: Tl3FileMode): Cardinal;
begin
Case l3FileMode of
l3_fmRead,
l3_fmFullShareRead: Result := fmOpenRead;
l3_fmWrite,
l3_fmExclusiveWrite : Result := fmOpenWrite;
l3_fmAppend,
l3_fmExclusiveAppend : Result := fmOpenWrite;
l3_fmExclusiveReadWrite,
l3_fmReadWrite : Result := fmOpenReadWrite;
else
begin
Result := fmOpenRead;
Assert(false);
end;//else
end;{Case l3FileMode}
end;
procedure Tl3CustomFiler.Cleanup;
{override;}
{-}
begin
// http://mdp.garant.ru/pages/viewpage.action?pageId=508445329
if HasIndicator then
Indicator.Finish;
f_OnCheckAbortedLoad := nil;
FreeAndNil(f_Line);
if Opened then
begin
fl_OpenCount := 1;
Close;
end;//Opened
FreeBuffer(true);
f_StreamPos := 0;
f_EOF := false;
f_AbortedLoad := false;
f_StreamType := l3_stUnknown;
f_Mode := Low(f_Mode);
fl_OpenCount := 0;
f_SoftEnterAsEOL := false;
f_NotSeekStream := false;
f_CodePage := 0;
f_NeedProcessMessages := false;
fl_WndToClose := 0;
f_ReadOnly := false;
inherited;
end;
procedure Tl3CustomFiler.AbortLoad;
{-}
var
l_Wnd : hWnd;
begin
f_AbortedLoad := false;
if (fl_WndToClose <> 0) then begin
l_Wnd := fl_WndToClose;
fl_WndToClose := 0;
PostMessage(l_Wnd, WM_Close, 0, 0);
end;//fl_WndToClose <> 0
raise El3AbortLoad.Create(l3_excAbortLoad);
end;
procedure Tl3CustomFiler.CheckAbortedLoad;
{-}
var
AL : Bool;
begin
if Assigned(f_OnCheckAbortedLoad) then
f_OnCheckAbortedLoad(Self, AL)
else
AL := false;
if AL OR f_AbortedLoad then AbortLoad;
end;
procedure Tl3CustomFiler.ProcessMessages;
{override;}
{-}
begin
{$IfDef l3ConsoleApp}
{$Else l3ConsoleApp}
if f_NeedProcessMessages then afw.ProcessMessages;
{&ProcessMessages&}
{$EndIf l3ConsoleApp}
end;
function Tl3CustomFiler.pm_GetSize: Int64;
{-}
begin
if (f_Stream <> nil) then
Result := l3StreamSize(f_Stream)
else
Result := 0;
end;
function Tl3CustomFiler.pm_GetOpened: Bool;
{-}
begin
Result := (f_Stream <> nil);
end;
procedure Tl3CustomFiler.pm_SetStream(Value: TStream);
{-}
begin
if l3Set(f_Stream, Value) then
begin
f_StreamType := l3_stUnknown;
if (f_Stream = nil) then
begin
FreeBuffer(false);
if IsWriteMode(Mode) then
Indicator.ChangeIO(false)
else
Indicator.FinishEx(true);
end//f_Stream = nil
else
begin
f_NotSeekStream := false;
if IsWriteMode(Mode) then
begin
f_EOF := true;
f_StreamPos := 0;
end//IsWriteMode(Mode)
else
begin
try
f_StreamPos := l3StreamPos(f_Stream);
except
on E: EOleSysError do
if (E.ErrorCode = E_NOTIMPL) OR (E.ErrorCode = STG_E_INVALIDFUNCTION) OR (E.ErrorCode = E_UNEXPECTED) then
begin
f_StreamPos := 0;
f_NotSeekStream := true;
end//E.ErrorCode = E_NOTIMPL..
else
raise;
end;//try..except
try
f_EOF := (f_StreamPos = l3StreamSize(f_Stream));
except
on E: EOleSysError do
if (E.ErrorCode = E_NOTIMPL) OR (E.ErrorCode = STG_E_INVALIDFUNCTION) OR (E.ErrorCode = E_UNEXPECTED) then
begin
f_EOF := false;
f_NotSeekStream := true;
end//E.ErrorCode = E_NOTIMPL)
else
raise;
end;//try..except
end;//if IsWriteMode(Mode)
if IsReadMode(Mode) OR (Mode = l3_fmExclusiveReadWrite) then
begin
StartIndicator;
LoadBuffer;
end;//Mode = l3_fmRead
end;//f_Stream = nil
end;//l3Set(f_Stream, Value)
end;
function Tl3CustomFiler.pm_GetCOMStream: IStream;
{-}
begin
Result := l3Stream2IStream(Stream);
end;
procedure Tl3CustomFiler.pm_SetCOMStream(const Value: IStream);
{-}
var
l_Stream : TStream;
begin
if (Value = nil) then
Stream := nil
else
begin
l3IStream2Stream(Value, l_Stream);
try
Stream := l_Stream;
finally
FreeAndNil(l_Stream);
end;//try..finally
end;//Value = nil
end;
procedure Tl3CustomFiler.pm_SetMode(Value: Tl3FileMode);
{-}
begin
if (Self <> nil) then begin
f_Mode := Value;
end;
end;
procedure Tl3CustomFiler.pm_SetHandle(Value: Long);
{-}
begin
{if (f_Handle <> Value) then }begin
f_StreamPos := 0;
if Opened then
DoClose;
f_Handle := Value;
if (fl_OpenCount > 0) AND not Opened then
InternalOpen(Mode);
end;
end;
function Tl3CustomFiler.pm_GetCodePage: Long;
{-}
begin
Case f_StreamType of
l3_stUnknown:
begin
if (f_Stream Is Tl3StringStream) then
begin
Result := Tl3StringStream(f_Stream)._String.CodePage;
f_StreamType := l3_stString;
end//f_Stream Is Tl3StringStream
else
begin
Result := f_CodePage;
f_StreamType := l3_stOther;
end;//f_Stream Is Tl3StringStream
end;//l3_stUnknown
l3_stString:
Result := Tl3StringStream(f_Stream)._String.CodePage
else
Result := f_CodePage;
end;//Case f_StreamType
end;
function Tl3CustomFiler.InternalOpen(aMode: Tl3FileMode): Boolean;
{-}
begin
Result := DoOpen;
if Opened then
begin
Case aMode of
l3_fmRead,
l3_fmFullShareRead,
l3_fmExclusiveReadWrite:
LoadBuffer;
l3_fmAppend :
f_StreamPos := Stream.Seek(0, soEnd);
else
if IsReadMode(aMode) then
LoadBuffer;
end;{Case aMode}
end;{Opened}
end;
function Tl3CustomFiler.DoOpen: Boolean;
{virtual;}
{-}
begin
Result := true;
end;
function Tl3CustomFiler.IsWriteMode(Mode: Tl3FileMode): Bool;
{-}
begin
Result := Mode in l3_fmWriteMode;
end;
constructor Tl3CustomFiler.Create(anOwner: Tl3FilerOwner = nil);
{override;}
{-}
begin
inherited Create{$IfDef l3FilerIsComponent}(anOwner){$EndIf};
f_EOF := true;
f_SoftEnterAsEOL := False;
end;
procedure Tl3CustomFiler.Open;
{-}
var
l_Start : Boolean;
begin
if (Self <> nil) then begin
if (fl_OpenCount = 0) then begin
if not Opened then begin
f_EOF := false;
try
l_Start := InternalOpen(Mode);
except
Stream := nil;
raise;
end;//try..except
if Opened AND l_Start then
begin
if IsWriteMode(Mode) then
begin
if ReadOnly then Exit;
Indicator.ChangeIO(true);
//IsWriteMode(Mode)
end
else
StartIndicator;
end;//Opened
end;{not Opened}
{f_EOF := false;}
end;{fl_OpenCount = 0}
Inc(fl_OpenCount);
end;
end;
procedure Tl3CustomFiler.StartIndicator;
{-}
var
l_Size : Int64;
l_Ident : String;
begin
try
l_Size := Size;
except
on E: EOleSysError do
begin
if (E.ErrorCode = E_NOTIMPL) OR (E.ErrorCode = E_UNEXPECTED) then
l_Size := 2048 // - например такой размер
else
raise;
end//on E: EOleSysError
else
begin
l3System.Msg2Log(Format(cFileSizeErrorFmt, [Identifier]));
l_Size := 2048; // - например такой размер
end;//on E: EOleSysError
end;//try..except
l_Ident := Identifier;
if (l_Ident = '') OR (l_Ident = '0') then
Indicator.StartEx(l_Size, str_l3mmFileOp.AsCStr, true)
else
Indicator.StartEx(l_Size, l3Fmt(str_l3mmFileOpFmt.AsCStr, [l_Ident]), true);
end;
{$IfNDef l3FilerIsComponent}
class function Tl3CustomFiler.IsCacheable : Boolean;
begin
Result := true;
end;
{$EndIf l3FilerIsComponent}
procedure Tl3CustomFiler.DoClose;
{virtual;}
{-}
begin
FreeAndNil(f_Stream);
Handle := 0;
end;
procedure Tl3CustomFiler.Close;
begin
if (Self <> nil) then begin
if (fl_OpenCount = 0) then begin
FreeBuffer(false);
Exit;
end;//fl_OpenCount = 0
Dec(fl_OpenCount);
if (fl_OpenCount = 0) then begin
if Opened then begin
f_EOF := true;
f_StreamPos := 0;
DoClose;
if IsWriteMode(Mode) then
Indicator.ChangeIO(false)
else
Indicator.FinishEx(true);
end;{Opened}
FreeBuffer(false);
end;{fl_OpenCount = 0}
end;
end;
function Tl3CustomFiler.GetFilePath: AnsiString;
begin
Result := '';
if Assigned(f_OnGetFilePath) then
Result := f_OnGetFilePath;
end;
procedure Tl3CustomFiler.Rollback;
{* Откатить данные }
var
l_RB : Il3Rollback;
begin
if Supports(f_Stream, Il3Rollback, l_RB) then
try
l_RB.Rollback;
finally
l_RB := nil;
end;//try..finally
end;
procedure Tl3CustomFiler.FreeBuffer(aFullClean : Boolean);
{-}
begin
{$IfNDef l3NoObjectCache}
if aFullClean then
{$EndIf l3NoObjectCache}
begin
f_BufSize := 0;
FreeAndNil(f_Buffer);
FreeAndNil(f_PrevBuffer);
end//aFullClean
{$IfNDef l3NoObjectCache}
else
begin
try
if (f_Buffer <> nil) then
begin
f_Buffer.BeforeAddToCache;
f_BufSize := f_Buffer.StSize;
end;//f_Buffer <> nil
if (f_PrevBuffer <> nil) then
f_PrevBuffer.BeforeAddToCache;
except
on E: Exception do
begin
f_Buffer := nil;
f_PrevBuffer := nil;
f_BufSize := 0;
try
l3System.Msg2Log('Проблемы при освобождении буфера');
l3System.Exception2Log(E);
except
// - давим, осознанно
end;//try..except
end;//on E
end;//try..except
end//aFullClean
{$EndIf l3NoObjectCache}
;//aFullClean
f_BufferOffset := 0;
f_StreamPos := 0;
f_EOF := true;
l3FillChar(f_BufS, SizeOf(f_BufS), 0);
end;
function Tl3CustomFiler.LoadBuffer: Bool;
var
OddsSize : Long;
Count : Long;
begin
if (f_Stream = nil) then
begin
Result := false;
l3FillChar(f_BufS, SizeOf(f_BufS), 0);
end//f_Stream = nil
else
begin
if (f_Buffer = nil) then
begin
f_Buffer := Tl3FilerBuffer.Create;
f_Buffer._CodePage := CP_ANSI{Self.CodePage};
// - Здесь ТОЛЬКО CP_ANSI, т.к. иначе начинается чехарда с Len, StSize и Count
// т.к. они перестают совпадать
f_Buffer.StSize := l3FilerBufSize;
f_BufSize := f_Buffer.StSize;
Assert(f_Buffer.StSize >= l3FilerBufSize);
CheckAbortedLoad;
ProcessMessages;
f_BufS := f_Buffer.AsWStr;
Assert(f_BufS.S = f_Buffer.St);
if (Self.CodePage = CP_Unicode) then
Count := f_Stream.Read(f_BufS.S^, f_BufSize - 2)
else
Count := f_Stream.Read(f_BufS.S^, Pred(f_BufSize));
Assert(f_BufS.S = f_Buffer.St);
Assert(f_Buffer.StSize >= l3FilerBufSize);
f_Buffer.Len := Count;
f_BufS.SLen := Count;
Assert(f_BufS.S = f_Buffer.St);
end//f_Buffer = nil
else
begin
if (f_PrevBuffer <> nil) AND (f_PrevBuffer.StSize > l3FilerBufSize * 4) then
FreeAndNil(f_PrevBuffer);
if (f_PrevBuffer = nil) then
begin
f_PrevBuffer := Tl3FilerBuffer.Create;
f_PrevBuffer._CodePage := CP_ANSI{Self.CodePage};
f_PrevBuffer.StSize := l3FilerBufSize;
end//f_PrevBuffer = nil
else
if (f_PrevBuffer.StSize < l3FilerBufSize) then
f_PrevBuffer.StSize := l3FilerBufSize;
Assert(f_PrevBuffer.StSize >= l3FilerBufSize);
l3Swap(Pointer(f_Buffer), Pointer(f_PrevBuffer));
OddsSize := f_PrevBuffer.Len - f_BufferOffset;
f_BufS := f_Buffer.AsWStr;
f_BufSize := f_Buffer.StSize;
if (OddsSize <> 0) then
begin
//Assert(OddsSize <= f_BufSize);
// - это проверка того, что буфер переполнится
if (OddsSize > f_BufSize) then
begin
f_Buffer.StSize := OddsSize + 1; // +1 - учитываем конечный 0
// - а этим мы можем исправить ситуацию с переполнением буфера
f_BufS := f_Buffer.AsWStr;
f_BufSize := f_Buffer.StSize;
end;//OddsSize > f_BufSize
l3Move(f_PrevBuffer.St[f_BufferOffset], f_BufS.S^, OddsSize);
// - копируем хвост предыдущего буфера в текущий
f_PrevBuffer.Delete(f_BufferOffset, OddsSize);
// - это нужно, чтобы при RollBack (Seek назад) не дублировались данные
end;//OddsSize <> 0
CheckAbortedLoad;
ProcessMessages;
Assert(f_Buffer.StSize >= l3FilerBufSize);
if (Self.CodePage = CP_Unicode) then
begin
Assert(f_BufSize - 2 - OddsSize >= 0);
Count := f_Stream.Read(f_BufS.S[OddsSize], f_BufSize - 2 - OddsSize)
end
else
begin
Assert(Pred(f_BufSize) - OddsSize >= 0);
Count := f_Stream.Read(f_BufS.S[OddsSize], Pred(f_BufSize) - OddsSize);
end;
Assert(f_BufS.S = f_Buffer.St);
Assert(f_Buffer.StSize >= l3FilerBufSize);
f_Buffer.Len := Count + OddsSize;
if (f_BufS.SLen <> Count + OddsSize) then
f_BufS := f_Buffer.AsWStr;
Assert(f_BufS.S = f_Buffer.St);
Assert(f_Buffer.StSize >= l3FilerBufSize);
end;//f_Buffer = nil
f_BufferOffset := 0;
Result := (f_BufS.SLen > 0);
end;//f_Stream = nil
f_EOF := not Result;
end;
{$IfOpt R+}
{$R-}
{$Define _Range_}
{$EndIf}
procedure Tl3CustomFiler.Read(aBuf: PAnsiChar; aCount: Long);
{-}
var
Cnt : Long;
begin
if (aCount = 0) then
Exit;
Cnt := f_BufS.SLen - f_BufferOffset;
while true do
begin
if (Cnt > aCount) then
// - у нас в буфере данные с запасом
begin
//Cnt := aCount;
l3Move(f_BufS.S[f_BufferOffset], aBuf^, aCount);
//Inc(aBuf, Cnt);
Inc(f_BufferOffset, aCount);
Inc(f_StreamPos, aCount);
Exit;
end//Cnt > aCount
else
begin
l3Move(f_BufS.S[f_BufferOffset], aBuf^, Cnt);
Inc(aBuf, Cnt);
Inc(f_BufferOffset, Cnt);
Inc(f_StreamPos, Cnt);
Dec(aCount, Cnt);
if (aCount = 0) then
// - считали сколько просили, больше читать не нужно
begin
if LoadBuffer then
// - грузим буфер - чтобы правильно конец файла выставился
Indicator.Progress(Pos);
Exit;
end//aCount = 0
else
begin
// - у нас ничего не осталось
//Cnt := 0;
if LoadBuffer then
begin
Indicator.Progress(Pos);
Cnt := f_BufS.SLen{ - f_BufferOffset};
// ^ после загрузки буфера смещение равно 0
end//LoadBuffer;
else
raise El3ReadError.CreateFmt('Невозможно считать требуемое число байт %d', [aCount]);
end;//aCount = 0
end;//Cnt > aCount
end;//while true
end;
function Tl3CustomFiler.SizedRead(aBuf: PAnsiChar; aCount: Long): Long;
{* - считать буфер из потока. }
var
Cnt : Long;
begin
Result := 0;
if (aCount = 0) then
Exit;
Cnt := f_BufS.SLen - f_BufferOffset;
while true do
begin
if (Cnt > aCount) then
// - у нас в буфере данные с запасом
begin
//Cnt := aCount;
l3Move(f_BufS.S[f_BufferOffset], aBuf^, aCount);
//Inc(aBuf, Cnt);
Inc(f_BufferOffset, aCount);
Inc(Result, aCount);
Inc(f_StreamPos, aCount);
Exit;
end//Cnt > aCount
else
begin
l3Move(f_BufS.S[f_BufferOffset], aBuf^, Cnt);
Inc(aBuf, Cnt);
Inc(f_BufferOffset, Cnt);
Inc(Result, Cnt);
Inc(f_StreamPos, Cnt);
Dec(aCount, Cnt);
if (aCount = 0) then
// - считали сколько просили, больше читать не нужно
begin
if LoadBuffer then
// - грузим буфер - чтобы правильно конец файла выставился
Indicator.Progress(Pos);
Exit;
end//aCount = 0
else
begin
// - у нас ничего не осталось
//Cnt := 0;
if LoadBuffer then
begin
Indicator.Progress(Pos);
Cnt := f_BufS.SLen{ - f_BufferOffset};
// ^ после загрузки буфера смещение равно 0
end//LoadBuffer
else
break;
end;//aCount = 0
end;//Cnt > aCount
end;//while true
end;
{$IfDef _Range_}
{$R+}
{$Undef _Range_}
{$EndIf _Range_}
function Tl3CustomFiler.ReadWord: Word;
{-}
begin
Read(@Result, SizeOf(Result));
end;
function Tl3CustomFiler.ReadLong: Long;
{-}
begin
Read(@Result, SizeOf(Result));
end;
function Tl3CustomFiler.ReadByte: Byte;
{-}
begin
Read(@Result, SizeOf(Result));
end;
function Tl3CustomFiler.Seek(const aOffset: Int64; aOrigin: TSeekOrigin): Int64;
{-}
procedure SeekFromBeginning;
begin{SeekFromBeginning}
FreeBuffer(false);
f_StreamPos := Stream.Seek(aOffset, soBeginning);
end;{SeekFromBeginning}
procedure JoinBuffers;
begin{JoinBuffers}
f_PrevBuffer.JoinWith(f_Buffer);
if (f_Buffer <> nil) then
begin
f_Buffer.BeforeAddToCache;
f_BufSize := 0;
l3FillChar(f_BufS, SizeOf(f_BufS), 0);
end;//f_Buffer <> nil
//FreeAndNil(f_Buffer);
l3Swap(Pointer(f_Buffer), Pointer(f_PrevBuffer));
if (f_Buffer <> nil) then
begin
f_BufSize := f_Buffer.StSize;
f_BufS := f_Buffer.AsWStr;
end;//f_Buffer <> nil
end;{JoinBuffers}
var
l_Offset : Int64;
l_NegOffset : Int64;
begin
try
Case aOrigin of
soBeginning:
begin
if (aOffset >= 0) then
begin
if l3IsNil(f_BufS) then
if (Stream = nil) then
begin
f_StreamPos := 0;
Assert(aOffset = 0);
end
else
f_StreamPos := Stream.Seek(aOffset, soBeginning)
else
begin
Inc(f_BufferOffset, aOffset);
Dec(f_BufferOffset, Pos);
f_StreamPos := aOffset;
if (f_BufferOffset >= f_BufS.SLen) then
SeekFromBeginning
else
if (f_BufferOffset < 0) then
begin
if f_PrevBuffer.Empty then
SeekFromBeginning
else
begin
Inc(f_BufferOffset, f_PrevBuffer.Len);
if (f_BufferOffset >= 0) then
JoinBuffers
else
SeekFromBeginning;
end;//f_PrevBuffer.Empty
end;//f_BufferOffset < 0
end;//l3IsNil(f_BufS)
end//aOffset >= 0
else
raise EStreamError.Create(l3ErrSeekPastEOF);
end;//soFromBeginning
soCurrent:
begin
if (aOffset > 0) then
begin
if l3IsNil(f_BufS) OR (f_BufferOffset + aOffset >= f_BufS.SLen) then
begin
l_Offset := Pos + aOffset - l3StreamPos(Stream);
FreeBuffer(false);
f_StreamPos := Stream.Seek(l_Offset, soCurrent);
end//l3IsNil(f_BufS)..
else
begin
Inc(f_BufferOffset, aOffset);
Inc(f_StreamPos, aOffset);
end;//l3IsNil(f_BufS)..
end//aOffset > 0
else
if (aOffset < 0) then
begin
l_NegOffset := -aOffset;
Dec(f_StreamPos, l_NegOffset);
if (f_BufferOffset >= l_NegOffset) then
Dec(f_BufferOffset, l_NegOffset)
else
if f_PrevBuffer.Empty OR (f_BufferOffset + f_PrevBuffer.Len < l_NegOffset) then
begin
l_Offset := Pos - l3StreamPos(Stream);
FreeBuffer(false);
f_StreamPos := Stream.Seek(l_Offset, soCurrent);
end//f_PrevBuffer.Empty
else
begin
Inc(f_BufferOffset, f_PrevBuffer.Len);
Dec(f_BufferOffset, l_NegOffset);
JoinBuffers;
end;//f_PrevBuffer.Empty
end;//aOffset < 0
end;//soFromCurrent
soEnd:
begin
if (aOffset <= 0) then
begin
Result := Stream.Seek(aOffset, soEnd);
if not l3IsNil(f_BufS) then
begin
Dec(f_BufferOffset, Pos);
Inc(f_BufferOffset, Result);
if (f_BufferOffset >= f_BufS.SLen) then
FreeBuffer(false)
else
if (f_BufferOffset < 0) then
begin
if f_PrevBuffer.Empty then
FreeBuffer(false)
else
begin
Inc(f_BufferOffset, f_PrevBuffer.Len);
if (f_BufferOffset >= 0) then
JoinBuffers
else
FreeBuffer(false);
end;//f_PrevBuffer.Empty
end;//f_BufferOffset < 0
end;//not l3IsNil(f_BufS)
f_StreamPos := Result;
end//aOffset <= 0
else
raise EStreamError.Create(l3ErrSeekPastEOF);
end;{soFromEnd}
else
raise EStreamError.Create(l3ErrInvalidOrigin);
end;{Case aOrigin}
except
on E: EOleSysError do
if (E.ErrorCode = E_NOTIMPL) OR (E.ErrorCode = E_UNEXPECTED) then
begin
if (aOffset <> 0) OR (aOrigin <> soBeginning) OR (Pos <> 0) then
raise;
end//E.ErrorCode = E_NOTIMPL
else
raise;
end;//try..except
if (IsReadMode(Mode) OR (Mode = l3_fmExclusiveReadWrite)) AND (l3IsNil(f_BufS) OR (f_BufferOffset >= f_BufS.SLen)) then
LoadBuffer
{-на самом деле это сделано для правильного выставления EOF}
else
f_EOF := false;
Result := f_StreamPos;
end;
function Tl3CustomFiler.ReadLn: Tl3WString;
{-}
procedure ReadUnicode;
var
l_Rest : Integer;
procedure DecPtr;
begin
Dec(f_BufferOffset, 2);
Dec(f_StreamPos, 2);
Inc(l_Rest, 2);
Dec(Result.SLen);
end;
procedure DoLoad;
var
l_Cnt : Integer;
l_SaveOffset : Integer;
begin
if (l_Rest <= 0) then
begin
Assert(l_Rest >= 0);
FreeAndNil(f_PrevBuffer);
if (Result.SLen > 0) then
// - остался кусок строки
begin
if (Result.SLen * SizeOf(WideChar) >= (f_BufSize * 3) div 4) then
begin
l_SaveOffset := Result.S - f_BufS.S;
f_Buffer.StSize := f_Buffer.StSize + l3FilerBufSize;
f_BufSize := f_Buffer.StSize;
f_BufS := f_Buffer.AsWStr;
Result.S := f_BufS.S + l_SaveOffset;
end;//Result.SLen * SizeOf(WideChar) >= (f_BufSize * 3) div 4
l3Move(Result.S^, f_BufS.S^, Result.SLen * SizeOf(WideChar));
end;//Result.SLen > 0
f_BufferOffset := Result.SLen * SizeOf(WideChar);
l_Cnt := f_Stream.Read(f_BufS.S[f_BufferOffset], f_BufSize - 2 - f_BufferOffset);
//Inc(f_StreamPos, l_Cnt);
Indicator.Progress(Pos);
f_Buffer.Len := l_Cnt + f_BufferOffset;
if (f_BufS.SLen <> l_Cnt + f_BufferOffset) then
f_BufS := f_Buffer.AsWStr;
Result.S := f_BufS.S;
l_Rest := f_BufS.SLen - f_BufferOffset;
f_EOF := (l_Rest <= 0)
end;//l_Rest <= 0
end;
procedure IncPtr;
begin
Inc(f_BufferOffset, 2);
Inc(f_StreamPos, 2);
Dec(l_Rest, 2);
Inc(Result.SLen);
DoLoad;
end;
var
l_C : WideChar;
begin
Result.S := f_BufS.S + f_BufferOffset;
Result.SLen := 0;
Result.SCodePage := CodePage;
l_Rest := f_BufS.SLen - f_BufferOffset;
DoLoad;
while not EOF do
begin
try
l_C := PWideChar(f_BufS.S + f_BufferOffset)^;
except
l_C := PWideChar(f_BufS.S + f_BufferOffset)^;
end;
IncPtr;
Case l_C of
cc_Null:
if EOF then
Exit
else
PWideChar(f_BufS.S + f_BufferOffset - 2)^ := cc_HardSpace;
cc_SoftEnter:
if SoftEnterAsEOL then
begin
Dec(Result.SLen);
exit;
end;
cc_HardEnter:
begin
Dec(Result.SLen);
// - выкидываем из конечной строки cc_HardEnter
if EOF then
Exit
else
begin
if (PWideChar(f_BufS.S + f_BufferOffset)^ = cc_SoftEnter) then
begin
IncPtr;
Dec(Result.SLen);
// - выкидываем из конечной строки cc_SoftEnter
if EOF then
f_EOF := false;
Exit;
end//f_BufS.S[f_BufferOffset] = cc_SoftEnter
else
begin
Exit;
end;//f_BufS.S[f_BufferOffset] = cc_SoftEnter
end;//EOF
end;//cc_HardEnter
cc_EOP:
begin
Assert(Result.SLen > 0);
if (Result.SLen <= 1) then
Result := cc_EOPStr
else
DecPtr;
Exit;
end;//cc_EOP
else
// - ничего не делаем;
end;//Case l_C
end;//while not EOF
end;
procedure ReadANSI;
var
l_Rest : Integer;
procedure DecPtr;
begin
Dec(f_BufferOffset);
Dec(f_StreamPos);
Inc(l_Rest);
Dec(Result.SLen);
end;
procedure DoLoad;
var
l_Cnt : Integer;
l_SaveOffset : Integer;
begin
if (l_Rest <= 0) then
begin
FreeAndNil(f_PrevBuffer);
if (Result.SLen > 0) then
// - остался кусок строки
begin
if (Result.SLen >= (f_BufSize * 3) div 4) then
begin
l_SaveOffset := Result.S - f_BufS.S;
f_Buffer.StSize := f_Buffer.StSize + l3FilerBufSize;
f_BufSize := f_Buffer.StSize;
f_BufS := f_Buffer.AsWStr;
Result.S := f_BufS.S + l_SaveOffset;
end;//Result.SLen >= (f_BufSize * 3) div 4
l3Move(Result.S^, f_BufS.S^, Result.SLen);
end;//Result.SLen > 0
f_BufferOffset := Result.SLen;
l_Cnt := f_Stream.Read(f_BufS.S[f_BufferOffset], Pred(f_BufSize) - f_BufferOffset);
// Inc(f_StreamPos, l_Cnt);
Indicator.Progress(Pos);
f_Buffer.Len := l_Cnt + f_BufferOffset;
if (f_BufS.SLen <> l_Cnt + f_BufferOffset) then
f_BufS := f_Buffer.AsWStr;
Result.S := f_BufS.S;
l_Rest := f_BufS.SLen - f_BufferOffset;
f_EOF := (l_Rest <= 0)
end;//l_Rest <= 0
end;
procedure IncPtr;
begin
Inc(f_BufferOffset);
Inc(f_StreamPos);
Dec(l_Rest);
Inc(Result.SLen);
DoLoad;
end;
var
l_C : AnsiChar;
begin
Result.S := f_BufS.S + f_BufferOffset;
Result.SLen := 0;
Result.SCodePage := CodePage;
l_Rest := f_BufS.SLen - f_BufferOffset;
DoLoad;
while not EOF do
begin
l_C := f_BufS.S[f_BufferOffset];
IncPtr;
Case l_C of
cc_Null:
if EOF then
Exit
else
f_BufS.S[f_BufferOffset - 1] := cc_HardSpace;
cc_SoftEnter:
if SoftEnterAsEOL then
begin
Dec(Result.SLen);
exit;
end;
cc_HardEnter:
begin
Dec(Result.SLen);
// - выкидываем из конечной строки cc_HardEnter
if EOF then
Exit
else
begin
if (f_BufS.S[f_BufferOffset] = cc_SoftEnter) then
begin
IncPtr;
Dec(Result.SLen);
// - выкидываем из конечной строки cc_SoftEnter
if EOF then
f_EOF := false;
Exit;
end//f_BufS.S[f_BufferOffset] = cc_SoftEnter
else
begin
Exit;
end;//f_BufS.S[f_BufferOffset] = cc_SoftEnter
end;//EOF
end;//cc_HardEnter
cc_EOP:
begin
Assert(Result.SLen > 0);
if (Result.SLen <= 1) then
Result := cc_EOPStr
else
DecPtr;
Exit;
end;//cc_EOP
else
// - ничего не делаем;
end;//Case l_C
end;//while not EOF
end;
begin
if (f_Stream = nil) then
begin
l3AssignNil(Result);
f_EOF := true;
end//f_Stream = nil
else
if (CodePage <> CP_Unicode) then
ReadANSI
else
ReadUnicode;
end;
function Tl3CustomFiler.ReadHexLn(const aLineChars: TCharSet; aFinishChar: AnsiChar): Tl3WString;
{* - Считать строку с данными в шестнадцатиричном виде. В качестве параметра - допустимые символы. }
procedure lp_ReadLine;
var
l_Rest : Integer;
procedure DecPtr;
begin
Dec(f_BufferOffset);
Dec(f_StreamPos);
Inc(l_Rest);
Dec(Result.SLen);
end;
procedure DoLoad;
var
l_Cnt : Integer;
l_SaveOffset : Integer;
begin
if (l_Rest <= 0) then
begin
FreeAndNil(f_PrevBuffer);
if (Result.SLen > 0) then
// - остался кусок строки
begin
if (Result.SLen >= (f_BufSize * 3) div 4) then
begin
l_SaveOffset := Result.S - f_BufS.S;
f_Buffer.StSize := f_Buffer.StSize + l3FilerBufSize;
f_BufSize := f_Buffer.StSize;
f_BufS := f_Buffer.AsWStr;
Result.S := f_BufS.S + l_SaveOffset;
end;//Result.SLen >= (f_BufSize * 3) div 4
l3Move(Result.S^, f_BufS.S^, Result.SLen);
end;//Result.SLen > 0
f_BufferOffset := Result.SLen;
l_Cnt := f_Stream.Read(f_BufS.S[f_BufferOffset], Pred(f_BufSize) - f_BufferOffset);
//Inc(f_StreamPos, l_Cnt);
Indicator.Progress(Pos);
f_Buffer.Len := l_Cnt + f_BufferOffset;
if (f_BufS.SLen <> l_Cnt + f_BufferOffset) then
f_BufS := f_Buffer.AsWStr;
Result.S := f_BufS.S;
l_Rest := f_BufS.SLen - f_BufferOffset;
f_EOF := (l_Rest <= 0)
end;//l_Rest <= 0
end;
procedure IncPtr;
begin
Inc(f_BufferOffset);
Inc(f_StreamPos);
Dec(l_Rest);
Inc(Result.SLen);
DoLoad;
end;
var
l_C : AnsiChar;
begin
Result.S := f_BufS.S + f_BufferOffset;
Result.SLen := 0;
Result.SCodePage := CodePage;
l_Rest := f_BufS.SLen - f_BufferOffset;
DoLoad;
while not EOF do
begin
l_C := f_BufS.S[f_BufferOffset];
IncPtr;
case l_C of
cc_Null:
if EOF then Exit;
cc_EOP:
begin
Assert(Result.SLen > 0);
if (Result.SLen <= 1) then
Result := cc_EOPStr
else
DecPtr;
Exit;
end;//cc_EOP
else
if not (l_C in aLineChars) then
begin
if l_C = aFinishChar then
begin
DecPtr;
Exit;
end; // if l_C in aFinishChars then
end; // if not (l_C in aLineChars) then
end;//Case l_C
end;//while not EOF
end;
begin
if (f_Stream = nil) then
begin
l3AssignNil(Result);
f_EOF := True;
end//f_Stream = nil
else
lp_ReadLine;
end;
function Tl3CustomFiler.MakeReadString(aLen : Long;
aCodePage : Long): Tl3String;
{* - считать строку. }
var
l_S : Tl3WString;
begin
Result := Tl3String.Make(aCodePage);
Result.Len := aLen;
l_S := Result.AsWStr;
if (l_S.SCodePage = CP_Unicode) then
Read(l_S.S, aLen * SizeOf(WideChar))
else
Read(l_S.S, aLen * SizeOf(AnsiChar));
end;
function Tl3CustomFiler.GetC: Tl3Char;
{-}
begin
Result.rCodePage := CodePage;
if (Result.rCodePage = CP_Unicode) then
begin
try
Read(@Result.rWC, SizeOf(Result.rWC));
except
on El3ReadError do
Result.rWC := cc_Null;
end;//try..except
end//Result.rCodePage = CP_Unicode
else
begin
try
Read(@Result.rAC, SizeOf(Result.rAC));
except
on El3ReadError do
Result.rAC := cc_Null;
end;//try..except
end;//Result.rCodePage = CP_Unicode
end;
procedure Tl3CustomFiler.UngetC;
{-}
begin
if (CodePage = CP_Unicode) then
Seek(-SizeOf(WideChar), soCurrent)
else
Seek(-SizeOf(ANSIChar), soCurrent);
end;
procedure Tl3CustomFiler.UngetChars(aCount: Integer);
begin
if (CodePage = CP_Unicode) then
Seek(-SizeOf(WideChar) * aCount, soCurrent)
else
Seek(-SizeOf(ANSIChar)* aCount, soCurrent);
end;
function Tl3CustomFiler.Write(C: Char): Long;
{overload;}
{-}
begin
Result := Write(@C, SizeOf(C));
end;
function Tl3CustomFiler.Write(Buf: PAnsiChar; Count: Long): Long;
{overload;}
{-}
begin
//if not Opened then
// l3System.Stack2Log('Tl3CustomFiler.Write: Попытка писать в неоткрытый поток!');
if Opened and (not ReadOnly) AND (Buf <> nil) then
begin
// старый код, не поднимающий exception'а
//Result := f_Stream.Write(Buf^, Count);
//Inc(f_StreamPos, Result);
f_Stream.WriteBuffer(Buf^, Count);
Result := Count;
Inc(f_StreamPos, Count);
Indicator.Progress(Pos);
end//f_Stream <> nil..
else
Result := 0;
end;
function Tl3CustomFiler.Write(const S: AnsiString): Long;
{overload;}
{-}
begin
Result := Write(PAnsiChar(S), Length(S));
end;
function Tl3CustomFiler.Write(const S: Tl3WString): Long;
{overload;}
{-}
var
l_S : Tl3Str;
begin
if (S.SCodePage = Self.CodePage) then
Result := Self.Write(S.S, S.SLen)
else
begin
l_S.Init(S, Self.CodePage);
try
Result := Self.Write(l_S.S, l_S.SLen);
finally
l_S.Clear;
end;//try..finally
end;//CodePage = Self.CodePage
end;
function Tl3CustomFiler.WriteLn(const S: Tl3WString): Long;
//overload;
{-}
begin
Result := Write(S);
Inc(Result, OutEOL);
end;
function Tl3CustomFiler.Write(S: Tl3PrimString): Long;
{overload;}
{-}
begin
Result := Write(S.AsWStr);
end;
function Tl3CustomFiler.WriteLn(S: Tl3PrimString): Long;
//overload;
{-}
begin
Result := Write(S);
Inc(Result, OutEOL);
end;
function Tl3CustomFiler.WriteLn(const S: AnsiString): Long;
//overload;
{-}
begin
Result := Write(S);
Inc(Result, OutEOL);
end;
function Tl3CustomFiler.CloseQuery(Wnd: hWnd): Bool;
{-запрос на закрытие}
begin
if Indicator.InIO then
begin
fl_WndToClose := Wnd;
AbortedLoad := true;
Result := false;
end//Indicator.InIO
else
Result := true;
end;
function Tl3CustomFiler.GetCodePage: Long;
{-}
begin
Mode := l3_fmRead;
Open;
try
try
if f_Buffer.Empty then
if not LoadBuffer then
begin
Result := CP_ANSI;
Exit;
end;//not LoadBuffer
Result := l3AnalizeCodePageExEx(f_Buffer.St, f_Buffer.St + f_Buffer.Len);
finally
Seek(0, soBeginning);
end;{try..finally}
finally
Close;
end;{try..finally}
end;{Analize}
procedure Tl3CustomFiler.AnalizeCodePage;
{-}
begin
CodePage := GetCodePage;
end;
procedure Tl3CustomFiler.Analize(var OEMCount, ANSICount: Long);
{-}
begin
Mode := l3_fmRead;
Open;
try
try
l3AnalizeCodePage(f_Buffer.St, f_Buffer.St + f_Buffer.Len, OEMCount, ANSICount);
finally
Seek(0, soBeginning);
end;{try..finally}
finally
Close;
end;{try..finally}
end;{Analize}
procedure Tl3CustomFiler.SkipEOL;
{-}
begin
if (GetC.rAC <> cc_HardEnter) then
UngetC
else if (GetC.rAC <> cc_SoftEnter) then
UngetC;
end;
function Tl3CustomFiler.OutEOL: Long;
{-}
begin
if (CodePage = CP_Unicode) then
Result := Write(PAnsiChar(PWideChar(cc_EOLW)), cc_EOLW_Size)
else
Result := Write(cc_EOL, cc_EOL_Len);
end;
function Tl3CustomFiler.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult;
{override;}
{-}
var
l_FilerStream: Tl3FilerStream;
begin
if IID.EQ(IStream) then
begin
l_FilerStream := Tl3FilerStream.Create(Self);
try
if not Opened then Open;
if not Opened then
Result.SetNoInterface
else
Result := Tl3HResult_C(l_FilerStream.QueryInterface(IStream, Obj));
finally
FreeAndNil(l_FilerStream);
end;{try..finally}
end//IID.EQ(IStream)
else
if IID.EQ(Im2StoreStat) then
begin
if Supports(f_Stream, IID.IID, Obj) then
Result.SetOk
else
Result.SetNoInterface;
end//IID.EQ(Im2StoreStat)
else
Result := inherited COMQueryInterface(IID, Obj);
end;
function Tl3CustomFiler.CheckLine(NeedChangeCodePage: Boolean = true): Tl3String;
{-}
begin
if (f_Line = nil) OR (f_Line.RefCount > 1) then
begin
FreeAndNil(f_Line);
f_Line := Tl3String.Make(CodePage);
end//f_Line = nil..
else
if NeedChangeCodePage then
f_Line._CodePage := CodePage;
Result := f_Line;
end;
function Tl3CustomFiler.Identifier: String;
//virtual;
{-}
begin
if (f_Stream Is Tl3NamedTextStream) then
Result := Tl3NamedTextStream(f_Stream).FileName
else
if (f_Stream Is Tl3NamedFileStream) then
Result := Tl3NamedFileStream(f_Stream).FileName
else
Result := IntToStr(Handle);
end;
procedure Tl3CustomFiler.Flush;
{-}
var
l_Flush : Il3Flush;
begin
if (Self <> nil) AND l3BQueryInterface(f_Stream, Il3Flush, l_Flush) then
try
l_Flush.Flush;
finally
l_Flush := nil;
end;//try..finally
end;
{ Tl3CustomDOSFiler }
constructor Tl3CustomDOSFiler.Make(const aFileName : String;
anOpenMode : Tl3FileMode = l3_fmRead;
NeedAnalizeCodePage : Bool = true;
aTimeOut : Longword = Cl3FileStreamDefaultTimeOut);
{* - создает Filer. }
begin
Create;
FileName := aFileName;
TimeOut := aTimeOut;
if (anOpenMode in [l3_fmRead, l3_fmReadWrite]) AND NeedAnalizeCodePage then
AnalizeCodePage;
Mode := anOpenMode;
end;
procedure Tl3CustomDOSFiler.pm_SetFileName(const Value: TFileName);
{-}
begin
if (f_FileName <> Value) then
begin
f_FileName := Value;
Handle := 0; {-переоткрываем файл}
end;//f_FileName <> Value
end;
procedure Tl3CustomDOSFiler.pm_SetTimeOut(Value: Longword);
{-}
begin
if (f_TimeOut <> Value) then
f_TimeOut := Value;
//f_TimeOut <> Value
end;
function Tl3CustomDOSFiler.DoOpen: Boolean;
begin
Result := true;
if IsReadMode(Mode) then
f_Stream := Tl3NamedFileStream.Create(f_FileName, Mode, TimeOut)
else
f_Stream := Tl3NamedTextStream.Create(f_FileName, Mode, TimeOut);
end;
procedure Tl3CustomDOSFiler.Cleanup;
//override;
{-}
begin
inherited;
f_TimeOut := 0;
f_FileName := '';
end;
function Tl3CustomDOSFiler.Identifier: String;
//override;
{-}
begin
Result := FileName;
end;
// start class Tl3FilerStream
constructor Tl3FilerStream.Create(anOwner: Tl3CustomFiler);
{reintroduce;}
{-}
begin
inherited Create;
l3Set(f_Filer, anOwner);
end;
procedure Tl3FilerStream.Rollback;
{* Откатить данные }
begin
if (f_Filer <> nil) then
f_Filer.Rollback;
end;
procedure Tl3FilerStream.Cleanup;
{override;}
{-}
begin
FreeAndNil(f_Filer);
inherited;
end;
function Tl3FilerStream.pm_GetFiler: Tl3CustomFiler;
{-}
begin
Result := f_Filer;
end;
procedure Tl3FilerStream.pm_SetFiler(Value: Tl3CustomFiler);
{-}
begin
l3Set(f_Filer, Value);
end;
function Tl3FilerStream.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult;
//override;
{-}
begin
Result.SetOk;
if IID.EQ(Im2StoreStat) then
begin
if not Supports(f_Filer, IID.IID, Obj) then
Result.SetNoInterface;
end//IID.EQ(Im2StoreStat)
else
Result := inherited COMQueryInterface(IID, Obj);
end;
function Tl3FilerStream.GetSize: Int64;
begin
Result := f_Filer.Size;
end;
function Tl3FilerStream.Read(var Buffer; Count: Longint): Longint;
{override;}
{-}
begin
Result := f_Filer.SizedRead(@Buffer, Count);
end;
function Tl3FilerStream.Write(const Buffer; Count: Longint): Longint;
{override;}
{-}
begin
Result := f_Filer.Write(@Buffer, Count);
end;
function Tl3FilerStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
{override;}
{-}
begin
Result := f_Filer.Seek(Offset, Origin);
end;
function l3L2FilerAction(Action: Pointer): Tl3FilerAction;
{* - делает заглушку для локальной процедуры. }
register;
{-}
asm
jmp l3LocalStub
end;{asm}
procedure l3FreeFilerAction(var Stub: Tl3FilerAction);
{* - освобождает заглушку для локальной процедуры. }
register;
{-}
asm
jmp l3FreeLocalStub
end;{asm}
end.
|
unit gResources;
interface
uses gTypes, SwinGame, sgTypes, sysUtils;
procedure InitResources(var game : GameData);
implementation
// Loads all the bitmaps used in the game
procedure LoadBitmaps();
begin
DebugMsg('Resources: Loading Bitmaps...');
// Tiles
LoadBitmapNamed('TileDirt01','tiles/dirt_1.png');
LoadBitmapNamed('TileConcrete','tiles/concrete.png');
LoadBitmapNamed('TileGrass01','tiles/grass_0_lp.png');
LoadBitmapNamed('TileGrassZoned','tiles/grass_zoned.png');
LoadBitmapNamed('TileWater01','tiles/water_0.png');
LoadBitmapNamed('TileRoad01','tiles/road_0_lp.png');
LoadBitmapNamed('TileRoad02','tiles/road_1_lp.png');
LoadBitmapNamed('TileRoadIntersection','tiles/road_intersection.png');
LoadBitmapNamed('TileTunnelLeft','tiles/tunnel_l.png');
LoadBitmapNamed('TileTunnelRight','tiles/tunnel_r.png');
LoadBitmapNamed('TileTunnelBottomLeft','tiles/tunnel_bl.png');
LoadBitmapNamed('TileSlopeLeft','tiles/slope_l.png');
LoadBitmapNamed('TileSlopeRight','tiles/slope_r.png');
LoadBitmapNamed('TileSlopeBottomLeft','tiles/slope_bl.png');
LoadBitmapNamed('TileSlopeBottomRight','tiles/slope_br.png');
DebugMsg('Resources: Loaded tile bitmaps.');
// Buildings
LoadBitmapNamed('HQBuilding','buildings/hq.png');
LoadBitmapNamed('GenericBuilding01','buildings/generic_0.png');
LoadBitmapNamed('House01','buildings/house_0.png');
LoadBitmapNamed('House01Shadow','buildings/house_1.shadow.png');
LoadBitmapNamed('House02','buildings/house_1.png');
LoadBitmapNamed('ShopBL01','buildings/shop_bl_1.png');
LoadBitmapNamed('PowerPlant','buildings/powerplant.png');
LoadBitmapNamed('WaterPump','buildings/waterpump.png');
DebugMsg('Resources: Loaded building bitmaps.');
LoadBitmapNamed('UISidebarTop','ui/side_top.png');
LoadBitmapNamed('UISidebarRow','ui/side_row.png');
LoadBitmapNamed('UISidebarBottom','ui/side_bottom.png');
LoadBitmapNamed('UIMouseSelect','ui/mouse_select.png');
LoadBitmapNamed('UIMouseMove','ui/mouse_move.png');
LoadBitmapNamed('UINotification','ui/notification.png');
LoadBitmapNamed('UIBldgHover','ui/bldg_hover.png');
LoadBitmapNamed('UIZoneBg','ui/zone_bg.png');
LoadBitmapNamed('UIZoneBgActive','ui/zone_bg_active.png');
LoadBitmapNamed('UIZoneRes','ui/zone_bg_res.png');
LoadBitmapNamed('UIZoneCom','ui/zone_bg_com.png');
LoadBitmapNamed('UIZoneBull','ui/zone_bg_bull.png');
LoadBitmapNamed('UIZoneRoad','ui/zone_bg_road.png');
LoadBitmapNamed('UIZonePower','ui/zone_bg_power.png');
LoadBitmapNamed('UIZoneWater','ui/zone_bg_water.png');
LoadBitmapNamed('UIIconNoPower','ui/icon_nopower.png');
LoadBitmapNamed('UIPlaceValid','ui/place_valid.png');
LoadBitmapNamed('UIPlaceValidDouble','ui/place_valid_double.png');
DebugMsg('Resources: Loaded UI bitmaps.');
LoadBitmapNamed('MainMenuBackground','ui/mainmenu_bg.png');
LoadBitmapNamed('MainMenuName','ui/mainmenu_name.png');
LoadBitmapNamed('MainMenuPlayBtnHover','ui/mainmenu_bg_btn_play_hover.png');
LoadBitmapNamed('MainMenuQuitBtnHover','ui/mainmenu_bg_btn_quit_hover.png');
LoadBitmapNamed('MainMenuOkBtnHover','ui/mainmenu_bg_btn_ok_hover.png');
DebugMsg('Resources: Loaded main menu bitmaps.');
LoadBitmapNamed('AgentTruckRedTL', 'agents/truck_red_tl.png');
LoadBitmapNamed('AgentTruckRedTR', 'agents/truck_red_tr.png');
LoadBitmapNamed('AgentTruckRedBL', 'agents/truck_red_bl.png');
LoadBitmapNamed('AgentTruckRedBR', 'agents/truck_red_br.png');
DebugMsg('Resources: Loaded agent bitmaps.');
DebugMsg('Resources: Loading Bitmaps... done.');
DebugMsg('Resources: Loading game audio...');
LoadMusicNamed('MainThemeOne', 'TSFH - I Love You Forever.mp3');
LoadSoundEffectNamed('UIClick', 'ui_click.wav');
LoadSoundEffectNamed('BuildRes', 'res_build.wav');
LoadSoundEffectNamed('BuildCom', 'com_build.wav');
LoadSoundEffectNamed('BuildPower', 'power.wav');
LoadSoundEffectNamed('BuildWater', 'water.wav');
LoadSoundEffectNamed('PaidNotif', 'paid.wav');
DebugMsg('Resources: Loaded game audio.');
end;
// Defines a tile type
procedure DefineTile(var game : GameData; bitmap: String; terrainType: TerrainType);
var
idx: Integer;
begin
SetLength(game.tileTypes, Length(game.tileTypes) + 1);
idx := High(game.tileTypes);
game.tileTypes[idx].bitmap := BitmapNamed(bitmap);
game.tileTypes[idx].terrainType := terrainType;
end;
// Defines an agent type
procedure DefineUnit(var game : GameData; img,icon : Bitmap; name : String; cost : Integer);
var
idx: Integer;
begin
SetLength(game.unitTypes, Length(game.unitTypes) + 1);
idx := High(game.unitTypes);
game.unitTypes[idx].img := img;
game.unitTypes[idx].icon := icon;
game.unitTypes[idx].name := name;
game.unitTypes[idx].cost := cost;
end;
// Load all the tile types
procedure LoadTileTypes(var game : GameData);
begin
DebugMsg('Resources: Loading Tile Types...');
// DefineTile(game, bitmap name, terraintype)
DefineTile(game, 'TileDirt01', TERRAIN_NORMAL); // 0
DefineTile(game, 'TileGrass01', TERRAIN_NORMAL); // 1
DefineTile(game, 'TileWater01', TERRAIN_WATER); // 2
DefineTile(game, 'TileRoad01', TERRAIN_ROAD); // 3
DefineTile(game, 'TileRoad02', TERRAIN_ROAD); // 4
DefineTile(game, 'TileGrassZoned', TERRAIN_ZONE); // 5
// DefineTile(game, 'TileGrassZoned', TERRAIN_ZONE); // 6
DebugMsg('Resources: Loading Tile Types... done.');
end;
// Load all the agent types
procedure LoadUnitTypes(var game : GameData);
begin
// DefineUnit(game, bitmap, icon, name, cost)
DefineUnit(game, BitmapNamed('AgentTruckRedTL'), BitmapNamed('AgentTruckRedTL'), 'Test Unit', 500);
end;
procedure LoadFonts();
begin
LoadFontNamed('OpenSansRegular', 'opensans_regular.ttf', 12);
LoadFontNamed('OpenSansSemiBold', 'opensans_semibold.ttf', 12);
LoadFontNamed('OpenSansSemiBold16', 'opensans_semibold.ttf', 16);
LoadFontNamed('OpenSansSemiBold22', 'opensans_semibold.ttf', 22);
LoadFontNamed('OpenSansSemiBold42', 'opensans_semibold.ttf', 42);
LoadFontNamed('NotifHeader', 'opensans_semibold.ttf', 14);
LoadFontNamed('NotifContent', 'opensans_regular.ttf', 12);
LoadFontNamed('HoogUILarge', 'hoog0555.ttf', 22);
end;
procedure LoadNames(var game : GameData);
var
tfIn: TextFile;
s: string;
begin
AssignFile(tfIn, PathToResource('names.txt'));
// Embed the file handling in a try/except block to handle errors gracefully
try
// Open the file for reading
Reset(tfIn);
// Keep reading lines until the end of the file is reached
while not eof(tfIn) do
begin
ReadLn(tfIn, s);
// DebugMsg('Reading Name: '+ s);
SetLength(game.names, Length(game.names) + 1);
game.names[High(game.names)] := s;
SetLength(game.names[High(game.names)], Length(s) - 2);
end;
// Done so close the file
CloseFile(tfIn);
except
on E: EInOutError do
WriteLn('File handling error occurred. Details: ', E.Message);
end;
end;
// Calls other resource procedures
procedure InitResources(var game : GameData);
begin
DebugMsg('Resources: Initialising...');
LoadBitmaps();
LoadTileTypes(game);
LoadUnitTypes(game);
LoadNames(game);
LoadFonts();
DebugMsg('Resources: Initialising... done.');
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpBase64;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
SbpBase64,
{$IFDEF DELPHI}
SbpIBase64,
{$ENDIF DELPHI}
ClpCryptoLibTypes;
type
TBase64 = class sealed(TObject)
public
class function Encode(const Input: TCryptoLibByteArray): String; static;
class function Decode(const Input: String): TCryptoLibByteArray; static;
end;
implementation
{ TBase64 }
class function TBase64.Decode(const Input: String): TCryptoLibByteArray;
begin
result := SbpBase64.TBase64.Default.Decode(Input);
end;
class function TBase64.Encode(const Input: TCryptoLibByteArray): String;
begin
result := SbpBase64.TBase64.Default.Encode(Input);
end;
end.
|
unit m_checkbox;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TMariaeCheckBox }
TMariaeCheckBox = class(TCheckBox)
private
FChanged: boolean;
procedure SetChanged(AValue: boolean);
protected
public
procedure OnChange;
procedure ResetChanged;
published
property Changed: Boolean read FChanged write SetChanged;
end;
procedure Register;
implementation
procedure Register;
begin
{$I m_checkbox_icon.lrs}
RegisterComponents('Mariae Controls',[TMariaeCheckBox]);
end;
{ TMariaeCheckBox }
procedure TMariaeCheckBox.SetChanged(AValue: boolean);
begin
if FChanged = AValue then Exit;
FChanged := AValue;
end;
procedure TMariaeCheckBox.OnChange;
begin
Self.SetChanged(True);
end;
procedure TMariaeCheckBox.ResetChanged;
begin
Self.SetChanged(False);
end;
end.
|
(******************************************************************************
Massimo Magnano 08-11-2004.
File : MGTree16.pas REV. 1.1
Implementazione di un albero per la memorizzazione di 2^32 Dati a 32 Bit.
Nel caso peggiore si hanno 16 passi tra i nodi per la ricerca di un dato
Implementation of a tree to store 2^32 Data of 32 Bit.
In the worst case you have 16 walk on the nodes for data research
******************************************************************************)
unit MGTree16;
{$mode delphi}{$H+}
interface
//{$O-}
Type
PMGTree16Data =^TMGTree16Data;
TMGTree16Data = packed record
Data :Integer;
UData :TObject;
Nodes :array[0..3] of PMGTree16Data;
end;
PPMGTree16Data =^PMGTree16Data;
TWalkFunction = procedure (Tag:Integer; Data :Integer; UData :TObject) of object;
TMGTree16 = class
protected
pRoot :PMGTree16Data;
Allocated :Cardinal;
function allocData :PMGTree16Data;
procedure deallocData(pData :PMGTree16Data);
function InternalFind(Value :Integer; var pParent :PMGTree16Data;
var ValNode :Byte) :PMGTree16Data;
public
constructor Create;
destructor Destroy; override;
function Add(Data:Integer; UData :TObject=nil; pNode :PMGTree16Data=Nil) : PMGTree16Data;
function Del(Data :Integer) : Boolean;
function Find(Value :Integer; var Data :Integer; var UData :TObject) : Boolean;
procedure WalkOnTree(Tag:Integer; WalkFunction :TWalkFunction);
procedure Clear(Tag:Integer=0; WalkFunction :TWalkFunction=Nil);
end;
implementation
constructor TMGTree16.Create;
begin
Allocated :=0;
pRoot :=Self.allocData;
end;
destructor TMGTree16.Destroy;
begin
Self.Clear;
FreeMem(pRoot);
inherited Destroy;
end;
function TMGTree16.allocData :PMGTree16Data;
begin
GetMem(Result, sizeof(TMGTree16Data));
FillChar(Result^, sizeof(TMGTree16Data), 0);
Inc(Allocated, sizeof(TMGTree16Data));
end;
procedure TMGTree16.deallocData(pData :PMGTree16Data);
begin
FreeMem(pData, sizeof(TMGTree16Data));
Dec(Allocated, sizeof(TMGTree16Data));
end;
//Add a new node on tree, if pNode <> nil add pNode else create a new node and
//assign to it Data, UData
// Return : the node just created or nil if error
function TMGTree16.Add(Data :Integer; UData :TObject=nil; pNode :PMGTree16Data=Nil) : PMGTree16Data;
Var
ValNode :Byte; //0..3
i :Integer;
pParent,
pData :PMGTree16Data;
iValue :Integer;
begin
pData :=pRoot;
Result :=Nil;
if (pNode<>Nil)
then Data :=pNode^.Data;
iValue :=Data;
for i:=0 to 15 do
begin
ValNode := (Data and $00000003);
pParent :=pData;
pData :=pData^.Nodes[ValNode];
if (pData=Nil)
then begin
if pNode=Nil
then begin
pData :=Self.allocData;
pData^.Data :=iValue;
pData^.UData :=UData;
end
else pData :=pNode;
pParent^.Nodes[ValNode] :=pData;
Result :=pData;
Exit;
end;
if (pData^.Data=iValue)
then begin
Result :=pData;
Exit;
end;
Data :=Data shr 2;
end;
end;
//Del the node that have Data as ID, if node have subnode attached to it
// reinsert in correct position.
function TMGTree16.Del(Data :Integer) : Boolean;
Var
pData,
pParent :PMGTree16Data;
ValNode, i :Byte;
begin
pData :=InternalFind(Data, pParent, ValNode);
Result := (pData<>Nil);
if Result
then begin
//Reinserisco le (foglie <> Nil) del nodo che si sta per eliminare
pParent^.Nodes[ValNode] :=pData^.Nodes[ValNode]; //bypass
for i:=0 to 3 do
begin
if (i<>ValNode) and (pData^.Nodes[i]<>Nil)
then Add(0, nil, pData^.Nodes[i]);
end;
Self.deallocData(pData);
end;
end;
//Find the node that have Value as ID
//Return :
// pParent = Parent of the Node
// ValNode = sub Node on were i'm attached in Parent
// Result = the Node
function TMGTree16.InternalFind(Value :Integer; var pParent :PMGTree16Data;
var ValNode :Byte) :PMGTree16Data;
Var
i :Integer;
pData :PMGTree16Data;
iValue :Integer;
begin
pData :=pRoot;
iValue :=Value;
Result :=Nil;
for i:=0 to 15 do
begin
ValNode := (Value and $00000003);
pParent :=pData;
pData :=pData^.Nodes[ValNode];
if (pData=Nil)
then begin
Result :=Nil;
Exit;
end;
if (pData^.Data=iValue)
then begin
Result :=pData;
Exit;
end;
Value :=Value shr 2;
end;
end;
//User Visible Find, search for node that have Value as ID
//Return : Data, UData = Node data
// Result = True if find
function TMGTree16.Find(Value :Integer; var Data :Integer; var UData :TObject) : Boolean;
Var
pData,
pParent :PMGTree16Data;
ValNode :Byte;
begin
pData :=InternalFind(Value, pParent, ValNode);
Result := (pData<>Nil);
if Result
then begin
Data :=pData^.Data;
UData :=pData^.UData;
end;
end;
//Recursivly Walk on tree and call user defined function on every node
procedure TMGTree16.WalkOnTree(Tag:Integer; WalkFunction :TWalkFunction);
procedure __Walk(pData :PMGTree16Data);
Var
i :Byte;
begin
for i :=0 to 3 do
begin
if pData^.Nodes[i]<>Nil
then begin
__Walk(pData^.Nodes[i]);
if Assigned(WalkFunction)
then WalkFunction(Tag, pData^.Nodes[i]^.Data, pData^.Nodes[i]^.UData);
end;
end;
end;
begin
__Walk(pRoot);
end;
//Recursivly delete node on tree, first call user defined function on every node.
procedure TMGTree16.Clear(Tag:Integer=0; WalkFunction :TWalkFunction=Nil);
procedure __Clear(pData :PMGTree16Data);
Var
i :Byte;
begin
for i :=0 to 3 do
begin
if pData^.Nodes[i]<>Nil
then begin
__Clear(pData^.Nodes[i]);
if Assigned(WalkFunction)
then WalkFunction(Tag, pData^.Nodes[i]^.Data, pData^.Nodes[i]^.UData);
Self.deallocData(pData^.Nodes[i]);
pData^.Nodes[i] :=Nil;
end;
end;
end;
begin
__Clear(pRoot);
end;
end.
|
unit ItfwParserWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\ItfwParserWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ItfwParserWordsPack" MUID: (559BC65F0292)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, l3Interfaces
, l3Parser
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwParserInterfaces
, tfwClassLike
, tfwScriptingInterfaces
, TypInfo
, ItfwKeywordFinderWordsPack
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *559BC65F0292impl_uses*
//#UC END# *559BC65F0292impl_uses*
;
type
TkwPopParserNextToken = {final} class(TtfwClassLike)
{* Слово скрипта pop:Parser:NextToken }
private
procedure NextToken(const aCtx: TtfwContext;
const aParser: ItfwParser);
{* Реализация слова скрипта pop:Parser:NextToken }
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;//TkwPopParserNextToken
TkwPopParserTokenLongString = {final} class(TtfwClassLike)
{* Слово скрипта pop:Parser:TokenLongString }
private
function TokenLongString(const aCtx: TtfwContext;
const aParser: ItfwParser): Il3CString;
{* Реализация слова скрипта pop:Parser:TokenLongString }
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;//TkwPopParserTokenLongString
TkwPopParserTokenInt = {final} class(TtfwClassLike)
{* Слово скрипта pop:Parser:TokenInt }
private
function TokenInt(const aCtx: TtfwContext;
const aParser: ItfwParser): Integer;
{* Реализация слова скрипта pop:Parser:TokenInt }
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;//TkwPopParserTokenInt
TkwPopParserFileName = {final} class(TtfwClassLike)
{* Слово скрипта pop:Parser:FileName }
private
function FileName(const aCtx: TtfwContext;
const aParser: ItfwParser): AnsiString;
{* Реализация слова скрипта pop:Parser:FileName }
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;//TkwPopParserFileName
TkwPopParserTokenType = {final} class(TtfwClassLike)
{* Слово скрипта pop:Parser:TokenType }
private
function TokenType(const aCtx: TtfwContext;
const aParser: ItfwParser): Tl3TokenType;
{* Реализация слова скрипта pop:Parser:TokenType }
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;//TkwPopParserTokenType
TkwPopParserSourceLine = {final} class(TtfwClassLike)
{* Слово скрипта pop:Parser:SourceLine }
private
function SourceLine(const aCtx: TtfwContext;
const aParser: ItfwParser): Integer;
{* Реализация слова скрипта pop:Parser:SourceLine }
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;//TkwPopParserSourceLine
procedure TkwPopParserNextToken.NextToken(const aCtx: TtfwContext;
const aParser: ItfwParser);
{* Реализация слова скрипта pop:Parser:NextToken }
begin
aParser.NextToken;
end;//TkwPopParserNextToken.NextToken
class function TkwPopParserNextToken.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Parser:NextToken';
end;//TkwPopParserNextToken.GetWordNameForRegister
function TkwPopParserNextToken.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopParserNextToken.GetResultTypeInfo
function TkwPopParserNextToken.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopParserNextToken.GetAllParamsCount
function TkwPopParserNextToken.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(ItfwParser)]);
end;//TkwPopParserNextToken.ParamsTypes
procedure TkwPopParserNextToken.DoDoIt(const aCtx: TtfwContext);
var l_aParser: ItfwParser;
begin
try
l_aParser := ItfwParser(aCtx.rEngine.PopIntf(ItfwParser));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParser: ItfwParser : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
NextToken(aCtx, l_aParser);
end;//TkwPopParserNextToken.DoDoIt
function TkwPopParserTokenLongString.TokenLongString(const aCtx: TtfwContext;
const aParser: ItfwParser): Il3CString;
{* Реализация слова скрипта pop:Parser:TokenLongString }
begin
Result := aParser.TokenLongString;
end;//TkwPopParserTokenLongString.TokenLongString
class function TkwPopParserTokenLongString.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Parser:TokenLongString';
end;//TkwPopParserTokenLongString.GetWordNameForRegister
function TkwPopParserTokenLongString.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwPopParserTokenLongString.GetResultTypeInfo
function TkwPopParserTokenLongString.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopParserTokenLongString.GetAllParamsCount
function TkwPopParserTokenLongString.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(ItfwParser)]);
end;//TkwPopParserTokenLongString.ParamsTypes
procedure TkwPopParserTokenLongString.DoDoIt(const aCtx: TtfwContext);
var l_aParser: ItfwParser;
begin
try
l_aParser := ItfwParser(aCtx.rEngine.PopIntf(ItfwParser));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParser: ItfwParser : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushString(TokenLongString(aCtx, l_aParser));
end;//TkwPopParserTokenLongString.DoDoIt
function TkwPopParserTokenInt.TokenInt(const aCtx: TtfwContext;
const aParser: ItfwParser): Integer;
{* Реализация слова скрипта pop:Parser:TokenInt }
begin
Result := aParser.TokenInt;
end;//TkwPopParserTokenInt.TokenInt
class function TkwPopParserTokenInt.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Parser:TokenInt';
end;//TkwPopParserTokenInt.GetWordNameForRegister
function TkwPopParserTokenInt.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwPopParserTokenInt.GetResultTypeInfo
function TkwPopParserTokenInt.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopParserTokenInt.GetAllParamsCount
function TkwPopParserTokenInt.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(ItfwParser)]);
end;//TkwPopParserTokenInt.ParamsTypes
procedure TkwPopParserTokenInt.DoDoIt(const aCtx: TtfwContext);
var l_aParser: ItfwParser;
begin
try
l_aParser := ItfwParser(aCtx.rEngine.PopIntf(ItfwParser));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParser: ItfwParser : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(TokenInt(aCtx, l_aParser));
end;//TkwPopParserTokenInt.DoDoIt
function TkwPopParserFileName.FileName(const aCtx: TtfwContext;
const aParser: ItfwParser): AnsiString;
{* Реализация слова скрипта pop:Parser:FileName }
begin
Result := aParser.FileName;
end;//TkwPopParserFileName.FileName
class function TkwPopParserFileName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Parser:FileName';
end;//TkwPopParserFileName.GetWordNameForRegister
function TkwPopParserFileName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwPopParserFileName.GetResultTypeInfo
function TkwPopParserFileName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopParserFileName.GetAllParamsCount
function TkwPopParserFileName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(ItfwParser)]);
end;//TkwPopParserFileName.ParamsTypes
procedure TkwPopParserFileName.DoDoIt(const aCtx: TtfwContext);
var l_aParser: ItfwParser;
begin
try
l_aParser := ItfwParser(aCtx.rEngine.PopIntf(ItfwParser));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParser: ItfwParser : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushString(FileName(aCtx, l_aParser));
end;//TkwPopParserFileName.DoDoIt
function TkwPopParserTokenType.TokenType(const aCtx: TtfwContext;
const aParser: ItfwParser): Tl3TokenType;
{* Реализация слова скрипта pop:Parser:TokenType }
begin
Result := aParser.TokenType;
end;//TkwPopParserTokenType.TokenType
class function TkwPopParserTokenType.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Parser:TokenType';
end;//TkwPopParserTokenType.GetWordNameForRegister
function TkwPopParserTokenType.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Tl3TokenType);
end;//TkwPopParserTokenType.GetResultTypeInfo
function TkwPopParserTokenType.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopParserTokenType.GetAllParamsCount
function TkwPopParserTokenType.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(ItfwParser)]);
end;//TkwPopParserTokenType.ParamsTypes
procedure TkwPopParserTokenType.DoDoIt(const aCtx: TtfwContext);
var l_aParser: ItfwParser;
begin
try
l_aParser := ItfwParser(aCtx.rEngine.PopIntf(ItfwParser));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParser: ItfwParser : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Ord(TokenType(aCtx, l_aParser)));
end;//TkwPopParserTokenType.DoDoIt
function TkwPopParserSourceLine.SourceLine(const aCtx: TtfwContext;
const aParser: ItfwParser): Integer;
{* Реализация слова скрипта pop:Parser:SourceLine }
begin
Result := aParser.SourceLine;
end;//TkwPopParserSourceLine.SourceLine
class function TkwPopParserSourceLine.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Parser:SourceLine';
end;//TkwPopParserSourceLine.GetWordNameForRegister
function TkwPopParserSourceLine.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwPopParserSourceLine.GetResultTypeInfo
function TkwPopParserSourceLine.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopParserSourceLine.GetAllParamsCount
function TkwPopParserSourceLine.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(ItfwParser)]);
end;//TkwPopParserSourceLine.ParamsTypes
procedure TkwPopParserSourceLine.DoDoIt(const aCtx: TtfwContext);
var l_aParser: ItfwParser;
begin
try
l_aParser := ItfwParser(aCtx.rEngine.PopIntf(ItfwParser));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParser: ItfwParser : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(SourceLine(aCtx, l_aParser));
end;//TkwPopParserSourceLine.DoDoIt
initialization
TkwPopParserNextToken.RegisterInEngine;
{* Регистрация pop_Parser_NextToken }
TkwPopParserTokenLongString.RegisterInEngine;
{* Регистрация pop_Parser_TokenLongString }
TkwPopParserTokenInt.RegisterInEngine;
{* Регистрация pop_Parser_TokenInt }
TkwPopParserFileName.RegisterInEngine;
{* Регистрация pop_Parser_FileName }
TkwPopParserTokenType.RegisterInEngine;
{* Регистрация pop_Parser_TokenType }
TkwPopParserSourceLine.RegisterInEngine;
{* Регистрация pop_Parser_SourceLine }
TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwParser));
{* Регистрация типа ItfwParser }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа Il3CString }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа AnsiString }
TtfwTypeRegistrator.RegisterType(TypeInfo(Tl3TokenType));
{* Регистрация типа Tl3TokenType }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit shaolinsroad_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,main_engine,controls_engine,sn_76496,gfx_engine,rom_engine,
pal_engine,sound_engine,qsnapshot;
function iniciar_shaolin:boolean;
implementation
const
shaolin_rom:array[0..2] of tipo_roms=(
(n:'477-l03.d9';l:$2000;p:$6000;crc:$2598dfdd),(n:'477-l04.d10';l:$4000;p:$8000;crc:$0cf0351a),
(n:'477-l05.d11';l:$4000;p:$c000;crc:$654037f8));
shaolin_char:array[0..1] of tipo_roms=(
(n:'shaolins.a10';l:$2000;p:0;crc:$ff18a7ed),(n:'shaolins.a11';l:$2000;p:$2000;crc:$5f53ae61));
shaolin_sprites:array[0..1] of tipo_roms=(
(n:'477-k02.h15';l:$4000;p:0;crc:$b94e645b),(n:'477-k01.h14';l:$4000;p:$4000;crc:$61bbf797));
shaolin_pal:array[0..4] of tipo_roms=(
(n:'477j10.a12';l:$100;p:$0;crc:$b09db4b4),(n:'477j11.a13';l:$100;p:$100;crc:$270a2bf3),
(n:'477j12.a14';l:$100;p:$200;crc:$83e95ea8),(n:'477j09.b8';l:$100;p:$300;crc:$aa900724),
(n:'477j08.f16';l:$100;p:$400;crc:$80009cf5));
//Dip
shaolin_dip_a:array [0..5] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'2'),(dip_val:$2;dip_name:'3'),(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:'30K 70K+'),(dip_val:$10;dip_name:'40K 80K+'),(dip_val:$8;dip_name:'40K'),(dip_val:$0;dip_name:'50K'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Medium'),(dip_val:$20;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
shaolin_dip_b:array [0..2] of def_dip=(
(mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Upright Controls';number:2;dip:((dip_val:$2;dip_name:'Single'),(dip_val:$0;dip_name:'Dual'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
shaolin_dip_c:array [0..2] of def_dip=(
(mask:$0f;name:'Coin A';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:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),())),());
var
banco_pal,scroll:byte;
pedir_nmi:boolean;
procedure update_video_shaolin;
var
x,y,f,color,nchar:word;
atrib:byte;
begin
for f:=0 to $3ff do begin
if gfx[0].buffer[f] then begin
y:=f mod 32;
x:=31-(f div 32);
atrib:=memoria[$3800+f];
color:=((atrib and $f)+($10*banco_pal)) shl 4;
nchar:=memoria[$3c00+f]+((atrib and $40) shl 2);
put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $20)<>0,(atrib and $10)<>0);
gfx[0].buffer[f]:=false;
end;
end;
scroll__x(1,2,scroll);
actualiza_trozo(0,0,256,32,1,0,0,256,32,2);
for f:=$17 downto 0 do if ((memoria[$3100+(f*32)]<>0) and (memoria[$3106+(f*32)]<>0)) then begin
atrib:=memoria[$3109+(f*32)];
color:=((atrib and $f)+($10*banco_pal)) shl 4;
x:=memoria[$3104+(f*32)]-8;
y:=240-memoria[$3106+(f*32)];
nchar:=memoria[$3108+(f*32)];
put_gfx_sprite(nchar,color,(atrib and $80)<>0,(atrib and $40)=0,1);
actualiza_gfx_sprite(x,y,2,1);
end;
actualiza_trozo_final(16,0,224,256,2);
end;
procedure eventos_shaolin;
begin
if event.arcade then begin
//P1
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.left[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.down[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.left[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.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2);
end;
end;
procedure shaolin_principal;
var
f:byte;
frame:single;
begin
init_controls(false,false,false,true);
frame:=m6809_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
m6809_0.run(trunc(frame));
frame:=frame+m6809_0.tframes-m6809_0.contador;
if f=239 then begin
m6809_0.change_irq(HOLD_LINE);
update_video_shaolin;
end else begin
if (((f and $1f)=0) and pedir_nmi) then m6809_0.change_nmi(PULSE_LINE);
end;
end;
eventos_shaolin;
video_sync;
end;
end;
function shaolin_getbyte(direccion:word):byte;
begin
case direccion of
$2800..$2bff,$3000..$33ff,$3800..$ffff:shaolin_getbyte:=memoria[direccion];
$500:shaolin_getbyte:=marcade.dswa;
$600:shaolin_getbyte:=marcade.dswb;
$700:shaolin_getbyte:=marcade.in0;
$701:shaolin_getbyte:=marcade.in1;
$702:shaolin_getbyte:=marcade.in2;
$703:shaolin_getbyte:=marcade.dswc;
end;
end;
procedure shaolin_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0:begin
main_screen.flip_main_screen:=(valor and 1)<>0;
pedir_nmi:=(valor and $2)<>0;
end;
$0300:sn_76496_0.Write(valor);
$0400:sn_76496_1.Write(valor);
$1800:banco_pal:=valor and $7;
$2000:scroll:=not(valor);
$2800..$2bff,$3000..$33ff:memoria[direccion]:=valor;
$3800..$3fff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$4000..$ffff:; //ROM
end;
end;
procedure shaolin_sound;
begin
sn_76496_0.Update;
sn_76496_1.Update;
end;
procedure shaolin_qsave(nombre:string);
var
data:pbyte;
buffer:array[0..2] of byte;
size:word;
begin
open_qsnapshot_save('shaolinsroad'+nombre);
getmem(data,180);
//CPU
size:=m6809_0.save_snapshot(data);
savedata_qsnapshot(data,size);
//SND
size:=sn_76496_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=sn_76496_1.save_snapshot(data);
savedata_qsnapshot(data,size);
//MEM
savedata_com_qsnapshot(@memoria,$4000);
//MISC
buffer[0]:=banco_pal;
buffer[1]:=scroll;
buffer[2]:=byte(pedir_nmi);
savedata_qsnapshot(@buffer,3);
freemem(data);
close_qsnapshot;
end;
procedure shaolin_qload(nombre:string);
var
data:pbyte;
buffer:array[0..2] of byte;
begin
if not(open_qsnapshot_load('shaolinsroad'+nombre)) then exit;
getmem(data,180);
//CPU
loaddata_qsnapshot(data);
m6809_0.load_snapshot(data);
//SND
loaddata_qsnapshot(data);
sn_76496_0.load_snapshot(data);
loaddata_qsnapshot(data);
sn_76496_1.load_snapshot(data);
//MEM
loaddata_qsnapshot(@memoria);
//MISC
loaddata_qsnapshot(@buffer);
banco_pal:=buffer[0];
scroll:=buffer[1];
byte(pedir_nmi):=buffer[2];
freemem(data);
close_qsnapshot;
//END
fillchar(gfx[0].buffer,$400,1);
end;
//Main
procedure reset_shaolin;
begin
m6809_0.reset;
sn_76496_0.reset;
sn_76496_1.reset;
reset_audio;
banco_pal:=0;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
pedir_nmi:=false;
end;
function iniciar_shaolin:boolean;
var
colores:tpaleta;
f:word;
bit0,bit1,bit2,bit3:byte;
memoria_temp:array[0..$7fff] of byte;
rweights,gweights,bweights:array[0..3] of single;
const
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8);
resistances:array[0..3] of integer=(2200,1000,470,220);
begin
llamadas_maquina.bucle_general:=shaolin_principal;
llamadas_maquina.reset:=reset_shaolin;
llamadas_maquina.save_qsnap:=shaolin_qsave;
llamadas_maquina.load_qsnap:=shaolin_qload;
iniciar_shaolin:=false;
iniciar_audio(false);
screen_init(1,256,256);
screen_mod_scroll(1,256,256,255,256,256,255);
screen_init(2,256,256,false,true);
iniciar_video(224,256);
//Main CPU
m6809_0:=cpu_m6809.Create(18432000 div 12,$100,TCPU_MC6809E);
m6809_0.change_ram_calls(shaolin_getbyte,shaolin_putbyte);
m6809_0.init_sound(shaolin_sound);
//Sound Chip
sn_76496_0:=sn76496_chip.Create(18432000 div 12);
sn_76496_1:=sn76496_chip.Create(18432000 div 6);
//cargar roms
if not(roms_load(@memoria,shaolin_rom)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,shaolin_char)) then exit;
init_gfx(0,8,8,512);
gfx_set_desc_data(4,0,16*8,512*16*8+4,512*16*8+0,4,0);
convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,true,false);
//sprites
if not(roms_load(@memoria_temp,shaolin_sprites)) then exit;
init_gfx(1,16,16,256);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,256*64*8+4,256*64*8+0,4,0);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,true,false);
//paleta
if not(roms_load(@memoria_temp,shaolin_pal)) then exit;
compute_resistor_weights(0, 255, -1.0,
4,@resistances[0],@rweights[0],470,0,
4,@resistances[0],@gweights[0],470,0,
4,@resistances[0],@bweights[0],470,0);
for f:=0 to $ff do begin
// red component
bit0:=(memoria_temp[f] shr 0) and $01;
bit1:=(memoria_temp[f] shr 1) and $01;
bit2:=(memoria_temp[f] shr 2) and $01;
bit3:=(memoria_temp[f] shr 3) and $01;
colores[f].r:=combine_4_weights(@rweights[0],bit0,bit1,bit2,bit3);
// green component
bit0:=(memoria_temp[f+$100] shr 0) and $01;
bit1:=(memoria_temp[f+$100] shr 1) and $01;
bit2:=(memoria_temp[f+$100] shr 2) and $01;
bit3:=(memoria_temp[f+$100] shr 3) and $01;
colores[f].g:=combine_4_weights(@gweights[0],bit0,bit1,bit2,bit3);
// blue component
bit0:=(memoria_temp[f+$200] shr 0) and $01;
bit1:=(memoria_temp[f+$200] shr 1) and $01;
bit2:=(memoria_temp[f+$200] shr 2) and $01;
bit3:=(memoria_temp[f+$200] shr 3) and $01;
colores[f].b:=combine_4_weights(@gweights[0],bit0,bit1,bit2,bit3);
end;
set_pal(colores,$100);
//tabla_colores char & sprites
bit0:=0;
for bit1:=0 to 255 do begin
for bit2:=0 to 7 do begin
gfx[0].colores[bit1+bit2*256]:=(memoria_temp[bit0+$300] and $f)+32*bit2+16;
gfx[1].colores[bit1+bit2*256]:=(memoria_temp[bit0+$400] and $f)+32*bit2;
end;
bit0:=bit0+1;
end;
//DIP
marcade.dswa:=$5a;
marcade.dswb:=$0f;
marcade.dswc:=$ff;
marcade.dswa_val:=@shaolin_dip_a;
marcade.dswb_val:=@shaolin_dip_b;
marcade.dswc_val:=@shaolin_dip_c;
//final
reset_shaolin;
iniciar_shaolin:=true;
end;
end.
|
unit Solid.Samples.OCP.Streaming.Wrong;
interface
type
{ TDownloadingFile }
TDownloadingFile = class
private
FLength: Longint;
FSent: Longint;
public
constructor Create(const ALength: Longint);
property Length: Longint read FLength;
property Sent: Longint read FSent write FSent;
end;
{ TDownloadingProgress }
TDownloadingProgress = class
private
FFile: TDownloadingFile;
public
constructor Create(AFile: TDownloadingFile);
function GetAsPercent: Double;
end;
implementation
{ TDownloadingFile }
constructor TDownloadingFile.Create(const ALength: Longint);
begin
inherited Create;
FLength := ALength;
end;
{ TDownloadingProgress }
constructor TDownloadingProgress.Create(AFile: TDownloadingFile);
begin
inherited Create;
FFile := AFile;
end;
function TDownloadingProgress.GetAsPercent: Double;
begin
Result := FFile.Sent / FFile.Length * 100;
end;
end.
|
unit InterfaceCollection;
interface
uses
Windows, Collection;
type
TInterfaceCollection =
class(TInterfacedObject)
public
constructor Create;
destructor Destroy; override;
private
fInterfaces : TLockableCollection;
private
procedure ReleaseItem(index : integer);
public
procedure lock;
procedure unlock;
procedure Insert(Item : IUnknown);
procedure Delete(Item : IUnknown);
function IndexOf(Item : IUnknown) : integer;
private
function GetCount : integer;
function GetInterface(index : integer) : IUnknown;
procedure SetInterface(index : integer; Item : IUnknown);
public
property Count : integer read GetCount;
property Interfaces[index : integer] : IUnknown read GetInterface write SetInterface; default;
end;
implementation
// TInterfaceCollection
constructor TInterfaceCollection.Create;
begin
inherited;
fInterfaces := TLockableCollection.Create(0, rkUse);
end;
destructor TInterfaceCollection.Destroy;
var
i : integer;
begin
for i := 0 to pred(Count) do
ReleaseItem(i);
inherited;
end;
procedure TInterfaceCollection.ReleaseItem(index : integer);
var
p : TObject;
Item : IUnknown absolute p;
begin
p := fInterfaces[index];
if p <> nil
then Item._Release;
end;
procedure TInterfaceCollection.lock;
begin
fInterfaces.lock;
end;
procedure TInterfaceCollection.unlock;
begin
fInterfaces.unlock;
end;
procedure TInterfaceCollection.Insert(Item : IUnknown);
var
p : TObject absolute Item;
begin
lock;
try
fInterfaces.Insert(p);
Item._AddRef;
finally
unlock;
end;
end;
procedure TInterfaceCollection.Delete(Item : IUnknown);
var
index : integer;
begin
lock;
try
index := IndexOf(Item);
if index <> -1
then
begin
ReleaseItem(index);
fInterfaces.AtDelete(index);
end;
finally
unlock;
end;
end;
function TInterfaceCollection.IndexOf(Item : IUnknown) : integer;
var
p : TObject absolute Item;
begin
lock;
try
result := fInterfaces.IndexOf(p);
finally
unlock;
end;
end;
function TInterfaceCollection.GetCount : integer;
begin
result := fInterfaces.Count;
end;
function TInterfaceCollection.GetInterface(index : integer) : IUnknown;
var
p : TObject absolute result;
begin
lock;
try
p := fInterfaces[index];
result._AddRef;
finally
unlock;
end;
end;
procedure TInterfaceCollection.SetInterface(index : integer; Item : IUnknown);
var
p : TObject absolute Item;
begin
lock;
try
ReleaseItem(index);
fInterfaces[index] := p;
Item._AddRef;
finally
unlock;
end;
end;
end.
|
{----------------------------------------------------------------------------
|
| Library: Envision
|
| Module: EnWmfGr
|
| Description: TDibGraphic descendant for WMF/EMF files.
|
| History: Dec 24, 1998. Michel Brazeau, first version
|
|---------------------------------------------------------------------------}
unit EnWmfGr;
{$I Envision.Inc}
interface
uses
Classes, { for TStream }
EnDiGrph; { for TDibGraphic }
type
TMetaFileGraphic = class(TDibGraphic)
public
procedure SingleLoadFromStream( const Stream : TStream;
const ImageToLoad : LongInt
); override;
procedure SaveToStream(Stream: TStream); override;
end;
{--------------------------------------------------------------------------}
implementation
uses
Windows, { for TRect }
Graphics, { for TMetaFile }
EnMisc; { for ifTrueColor }
{--------------------------------------------------------------------------}
type
TProtectedMetaFile = class(TMetaFile);
procedure TMetaFileGraphic.SingleLoadFromStream(
const Stream : TStream;
const ImageToLoad : LongInt
);
var
MetaFile : TMetaFile;
Rect : TRect;
begin
MetaFile := TMetaFile.Create;
try
MetaFile.LoadFromStream(Stream);
Self.NewImage( MetaFile.Width, MetaFile.Height,
ifTrueColor, nil, 0, 0 );
{ set the background white }
FillChar(Bits^, BitmapInfo.BmpHeader.biSizeImage, $FF);
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := MetaFile.Width;
Rect.Bottom := MetaFile.Height;
TProtectedMetaFile(MetaFile).Draw(Self.Canvas, Rect);
finally
MetaFile.Free;
end;
end;
{--------------------------------------------------------------------------}
procedure TMetaFileGraphic.SaveToStream(Stream: TStream);
var
MetaFile : TMetaFile;
Canvas : TMetaFileCanvas;
begin
MetaFile := TMetaFile.Create;
try
MetaFile.Width := Self.Width;
MetaFile.Height := Self.Height;
Canvas := TMetafileCanvas.Create(Metafile, 0);
try
Canvas.Draw(0, 0, Self);
finally
Canvas.Free;
end;
MetaFile.SaveToStream(Stream);
finally
MetaFile.Free;
end;
end;
{--------------------------------------------------------------------------}
initialization
{$ifdef __RegisterEnvisionWmf}
RegisterDibGraphic('WMF', 'Windows meta file', TMetaFileGraphic);
RegisterDibGraphic('EMF', 'Enhanced meta file', TMetaFileGraphic);
{$endif}
finalization
end.
|
unit InfoXLTRPOLTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoXLTRPOLRecord = record
PCode: String[6];
PDescription: String[30];
PAutoCreate: Boolean;
PModCount: SmallInt;
End;
TInfoXLTRPOLClass2 = class
public
PCode: String[6];
PDescription: String[30];
PAutoCreate: Boolean;
PModCount: SmallInt;
End;
// function CtoRInfoXLTRPOL(AClass:TInfoXLTRPOLClass):TInfoXLTRPOLRecord;
// procedure RtoCInfoXLTRPOL(ARecord:TInfoXLTRPOLRecord;AClass:TInfoXLTRPOLClass);
TInfoXLTRPOLBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoXLTRPOLRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoXLTRPOL = (InfoXLTRPOLPrimaryKey);
TInfoXLTRPOLTable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFAutoCreate: TBooleanField;
FDFTemplate: TBlobField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPAutoCreate(const Value: Boolean);
function GetPAutoCreate:Boolean;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetEnumIndex(Value: TEIInfoXLTRPOL);
function GetEnumIndex: TEIInfoXLTRPOL;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoXLTRPOLRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLTRPOLRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFAutoCreate: TBooleanField read FDFAutoCreate;
property DFTemplate: TBlobField read FDFTemplate;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PAutoCreate: Boolean read GetPAutoCreate write SetPAutoCreate;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEIInfoXLTRPOL read GetEnumIndex write SetEnumIndex;
end; { TInfoXLTRPOLTable }
TInfoXLTRPOLQuery = class( TDBISAMQueryAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFAutoCreate: TBooleanField;
FDFTemplate: TBlobField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPAutoCreate(const Value: Boolean);
function GetPAutoCreate:Boolean;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoXLTRPOLRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLTRPOLRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFAutoCreate: TBooleanField read FDFAutoCreate;
property DFTemplate: TBlobField read FDFTemplate;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PAutoCreate: Boolean read GetPAutoCreate write SetPAutoCreate;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
end; { TInfoXLTRPOLTable }
procedure Register;
implementation
procedure TInfoXLTRPOLTable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFAutoCreate := CreateField( 'AutoCreate' ) as TBooleanField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXLTRPOLTable.CreateFields }
procedure TInfoXLTRPOLTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLTRPOLTable.SetActive }
procedure TInfoXLTRPOLTable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXLTRPOLTable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXLTRPOLTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoXLTRPOLTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoXLTRPOLTable.SetPAutoCreate(const Value: Boolean);
begin
DFAutoCreate.Value := Value;
end;
function TInfoXLTRPOLTable.GetPAutoCreate:Boolean;
begin
result := DFAutoCreate.Value;
end;
procedure TInfoXLTRPOLTable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXLTRPOLTable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoXLTRPOLTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 6, N');
Add('Description, String, 30, N');
Add('AutoCreate, Boolean, 0, N');
Add('Template, Memo, 0, N');
Add('ModCount, SmallInt, 0, N');
end;
end;
procedure TInfoXLTRPOLTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoXLTRPOLTable.SetEnumIndex(Value: TEIInfoXLTRPOL);
begin
case Value of
InfoXLTRPOLPrimaryKey : IndexName := '';
end;
end;
function TInfoXLTRPOLTable.GetDataBuffer:TInfoXLTRPOLRecord;
var buf: TInfoXLTRPOLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PAutoCreate := DFAutoCreate.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXLTRPOLTable.StoreDataBuffer(ABuffer:TInfoXLTRPOLRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFAutoCreate.Value := ABuffer.PAutoCreate;
DFModCount.Value := ABuffer.PModCount;
end;
function TInfoXLTRPOLTable.GetEnumIndex: TEIInfoXLTRPOL;
var iname : string;
begin
result := InfoXLTRPOLPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoXLTRPOLPrimaryKey;
end;
procedure TInfoXLTRPOLQuery.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFAutoCreate := CreateField( 'AutoCreate' ) as TBooleanField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXLTRPOLQuery.CreateFields }
procedure TInfoXLTRPOLQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLTRPOLQuery.SetActive }
procedure TInfoXLTRPOLQuery.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXLTRPOLQuery.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXLTRPOLQuery.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoXLTRPOLQuery.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoXLTRPOLQuery.SetPAutoCreate(const Value: Boolean);
begin
DFAutoCreate.Value := Value;
end;
function TInfoXLTRPOLQuery.GetPAutoCreate:Boolean;
begin
result := DFAutoCreate.Value;
end;
procedure TInfoXLTRPOLQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXLTRPOLQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
function TInfoXLTRPOLQuery.GetDataBuffer:TInfoXLTRPOLRecord;
var buf: TInfoXLTRPOLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PAutoCreate := DFAutoCreate.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXLTRPOLQuery.StoreDataBuffer(ABuffer:TInfoXLTRPOLRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFAutoCreate.Value := ABuffer.PAutoCreate;
DFModCount.Value := ABuffer.PModCount;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoXLTRPOLTable, TInfoXLTRPOLQuery, TInfoXLTRPOLBuffer ] );
end; { Register }
function TInfoXLTRPOLBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..4] of string = ('CODE','DESCRIPTION','AUTOCREATE','MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 4) and (flist[x] <> s) do inc(x);
if x <= 4 then result := x else result := 0;
end;
function TInfoXLTRPOLBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftBoolean;
4 : result := ftSmallInt;
end;
end;
function TInfoXLTRPOLBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PAutoCreate;
4 : result := @Data.PModCount;
end;
end;
end.
|
unit IngDatos;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtCtrls, Db, Menus, TypInfo, AdoDb, JvDBLookup,
DBCtrls, jpeg, JvComponent, DbClient,
JvFormPlacement, JvAppStorage, JvAppIniStorage, JvComponentBase, StdCtrls,
Buttons, DBClientActns, StdActns, DBActns, ActnList, ImgList, ToolWin,
JvExStdCtrls, JvCombobox, Mask, JvExMask, JvToolEdit, JvMaskEdit,
JvDBFindEdit, JvEdit, JvDBSearchEdit, JvBalloonHint, JvBaseDlg,
JvProgressDialog;
type
TFIngDatos = class(TForm)
SB: TStatusBar;
DIng: TDataSource;
FormStorage1: TJvFormStorage;
JvAppIniFileStorage1: TJvAppIniFileStorage;
MainMenu1: TMainMenu;
Ventana1: TMenuItem;
Salir1: TMenuItem;
Editar1: TMenuItem;
Copiar1: TMenuItem;
Cortar1: TMenuItem;
Pegar1: TMenuItem;
N2: TMenuItem;
Insertar1: TMenuItem;
Grabar1: TMenuItem;
Borrar1: TMenuItem;
N3: TMenuItem;
Ayuda3: TMenuItem;
Actualizar2: TMenuItem;
Anularcambios1: TMenuItem;
N4: TMenuItem;
Anular1: TMenuItem;
Editar2: TMenuItem;
Navegar1: TMenuItem;
Primero1: TMenuItem;
Anterior1: TMenuItem;
Siguiente1: TMenuItem;
Ultimo1: TMenuItem;
N1: TMenuItem;
Actualizar1: TMenuItem;
VerenGrilla1: TMenuItem;
BuscarRegistro1: TMenuItem;
CambiarOrden1: TMenuItem;
Ayuda1: TMenuItem;
Ayuda2: TMenuItem;
imglst: TImageList;
ActionList1: TActionList;
Salir: TAction;
Imprimir: TAction;
DataSetCancel1: TDataSetCancel;
BorrarReg: TDataSetDelete;
DataSetEdit1: TDataSetEdit;
DataSetFirst1: TDataSetFirst;
DataSetInsert1: TDataSetInsert;
DataSetLast1: TDataSetLast;
DataSetNext1: TDataSetNext;
GrabarReg: TDataSetPost;
DataSetPrior1: TDataSetPrior;
DataSetRefresh1: TDataSetRefresh;
EditCopy1: TEditCopy;
EditCut1: TEditCut;
EditPaste1: TEditPaste;
Ayuda: TAction;
Buscar: TAction;
Grilla: TAction;
Ordenar: TAction;
ClientDataSetApply1: TClientDataSetApply;
ClientDataSetRevert1: TClientDataSetRevert;
pnlMain: TPanel;
pnlBot: TPanel;
bbGrabar: TBitBtn;
bbAnular: TBitBtn;
bbInsert: TBitBtn;
coolbar: TCoolBar;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton6: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
sEdit: TJvDBSearchEdit;
jvFiltrar: TJvDBFindEdit;
cbSearch: TJvComboBox;
cbIni: TCheckBox;
btnFiltro: TBitBtn;
mBorrarFiltro: TAction;
jvHint: TJvBalloonHint;
PopupMenu1: TPopupMenu;
Primero2: TMenuItem;
CambiodeFechas2: TMenuItem;
prgBar: TJvProgressDialog;
GrabarDlg: TSaveDialog;
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure BuscarExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure GrillaExecute(Sender: TObject);
procedure DIngStateChange(Sender: TObject);
procedure Grabarexecute(Sender: TObject);
procedure BorrarExecute(Sender: TObject);
procedure OrdenarExecute(Sender: TObject);
procedure AyudaExecute(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure SalirExecute(Sender: TObject);
procedure ImprimirExecute(Sender: TObject);
procedure mBorrarFiltroExecute(Sender: TObject);
procedure cbSearchChange(Sender: TObject);
private
{ Private declarations }
FCampoActivo: TWinControl;
FConfirmaBorrar: boolean;
FConfirmaGrabacion: boolean;
FAutoInsert: boolean;
FMayusculas: boolean;
FNoCerrar: boolean;
FPrimeraVez: boolean;
procedure AplicarEstilo;
procedure CambiarOrden;
function EsCampoNumerico: boolean;
procedure SetCampoActivo(const Value: TWinControl);
procedure SetConfirmaBorrar(const Value: boolean);
procedure SetConfirmaGrabacion(const Value: boolean);
procedure SetAutoInsert(const Value: boolean);
procedure SetMayusculas(const Value: boolean);
procedure ModiOrden(AFieldName: string; asc: boolean);
public
{ Public declarations }
Ascending: boolean;
procedure CreateWnd; override;
procedure EnHint(Sender: TObject);
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;
end;
var
FIngDatos: TFIngDatos;
implementation
uses
BusVal2, IngGrid, OrdenDlg;
{$R *.DFM}
procedure TFIngDatos.EnHint(Sender: TObject);
begin
sb.Panels[ 0 ].Text := Application.Hint;
end;
procedure TFIngDatos.FormActivate(Sender: TObject);
begin
Application.OnHint := EnHint;
Screen.Cursor := crDefault;
end;
procedure TFIngDatos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.OnHint := nil;
if ( Assigned( DIng.DataSet )) and not ( FNoCerrar ) then
DIng.DataSet.Close;
Action := caFree;
jvFiltrar.ResetFilter;
end;
procedure TFIngDatos.FormCreate(Sender: TObject);
var
x: integer;
begin
if FCampoActivo = nil then
for x:= 0 to PnlMain.ControlCount-1 do
if PnlMain.Controls[ x ] is TWinControl then
begin
FCampoActivo := TWinControl( PnlMain.Controls[ x ] );
break;
end;
if ( FPrimeraVez ) and ( FMayusculas ) then
AplicarEstilo;
FPrimeraVez := false;
if Assigned( DIng.DataSet ) then
begin
FNoCerrar := ( DIng.DataSet.Active = true );
if not ( DIng.DataSet.Active ) then
DIng.DataSet.open;
if FAutoInsert then
DIng.DataSet.Append;
end;
for x:= 0 to DIng.dataset.FieldCount - 1 do
cbSearch.Items.Add( DIng.dataset.Fields[x].fieldName );
cbSearch.ItemIndex := 0;
sEdit.DataField := DIng.dataset.Fields[0].FieldName;
jvFiltrar.DataField := DIng.dataset.Fields[ cbSearch.ItemIndex ].FieldName;
jvFiltrar.ResetFilter;
end;
procedure TFIngDatos.BuscarExecute(Sender: TObject);
var
PropInfo: PPropInfo;
FCampo: string;
FNombre: string;
begin
if ( ActiveControl <> nil ) then
begin
PropInfo := GetPropInfo( ActiveControl, 'DataField' );
if PropInfo = nil then
begin
FCampo := DIng.DataSet.Fields[ 0 ].FieldName;
FNombre := DIng.DataSet.Fields[ 0 ].DisplayName;
end
else
begin
FCampo := GetStrProp( ActiveControl, 'DataField' );
FNombre := DIng.DataSet.FieldByname( FCampo ).DisplayName;
end;
end;
BusValDlg2 := TBusValDlg2.create( self );
BusValDlg2.DataSet := ( DIng.DataSet );
BusValDlg2.Setear( FCampo );
BusValDlg2.ShowModal;
BusValDlg2.free;
end;
procedure TFIngDatos.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if Assigned( DIng.DataSet ) and ( DIng.DataSet.Active ) then
if ( DIng.DataSet ).UpdateStatus in [ usInserted, usModified, usDeleted ] then
CanClose := MessageDlg( 'Anula las modificaciones y Sale?' , mtConfirmation,
[ mbYes, mbNo ], 0 ) = mrYes;
end;
procedure TFIngDatos.FormKeyPress(Sender: TObject; var Key: Char);
begin
if ( Key in [ ',', '.' ] ) and ( EsCampoNumerico ) then
Key := DecimalSeparator
else if ( Key = #13 ) then
if not (( ActiveControl is TJvDbLookupCombo ) and
( TJvDbLookupCombo( ActiveControl ).IsDropDown )) then
begin
Key := #0;
SendMessage( Handle, WM_NEXTDLGCTL, 0, 0 );
end
end;
procedure TFIngDatos.FormResize(Sender: TObject);
begin
bbGrabar.Left := ( ClientWidth div 2 ) - ( bbGrabar.Width * 3 div 2 );
bbAnular.Left := bbGrabar.Left + bbGrabar.width + 1;
bbInsert.Left := bbAnular.Left + bbAnular.width + 1;
end;
procedure TFIngDatos.GrillaExecute(Sender: TObject);
begin
with TFIngGrid.create( application ) do
try
Inicializar( DIng.DataSet );
ShowModal;
finally
free;
end;
end;
procedure TFIngDatos.ImprimirExecute(Sender: TObject);
begin
Print;
end;
procedure TFIngDatos.mBorrarFiltroExecute(Sender: TObject);
begin
jvFiltrar.ResetFilter;
end;
procedure TFIngDatos.DIngStateChange(Sender: TObject);
begin
if ( DIng.state in [ dsInsert ] ) and ( Assigned( FCampoActivo )) then
ActiveControl := FCampoActivo;
end;
procedure TFIngDatos.SetCampoActivo(const Value: TWinControl);
begin
FCampoActivo := Value;
end;
procedure TFIngDatos.SetConfirmaBorrar(const Value: boolean);
begin
FConfirmaBorrar := Value;
end;
procedure TFIngDatos.SetConfirmaGrabacion(const Value: boolean);
begin
FConfirmaGrabacion := Value;
end;
procedure TFIngDatos.Grabarexecute(Sender: TObject);
begin
try
if not ( FConfirmaGrabacion ) or ( MessageDlg( 'Confirma Grabacion ?', mtConfirmation,
[ mbYes, mbNo ], 0 ) = mrYes ) then
if ( DIng.State in [ dsInsert ] ) then
begin
DIng.DataSet.Post;
if FAutoInsert then
DIng.DataSet.Append;
end
else if ( DIng.State in [ dsEdit ] ) then
DIng.DataSet.Post;
except
ActiveControl := TWinControl( Sender );
abort;
end;
end;
procedure TFIngDatos.BorrarExecute(Sender: TObject);
begin
if not ( FConfirmaBorrar ) or ( MessageDlg( 'Confirma Eliminacion de Registro ?', mtConfirmation,
[ mbYes, mbNo ], 0 ) = mrYes ) then
DIng.DataSet.delete;
end;
procedure TFIngDatos.SalirExecute(Sender: TObject);
begin
close;
end;
procedure TFIngDatos.SetAutoInsert(const Value: boolean);
begin
FAutoInsert := Value;
end;
function TFIngDatos.EsCampoNumerico: boolean;
var
PropInfo: PPropInfo;
begin
Result := false;
PropInfo := GetPropInfo( ActiveControl, 'DataField' );
if PropInfo <> nil then
if DIng.DataSet.FieldByName( GetStrProp( ActiveControl, PropInfo )).DataType in [ ftFloat, ftCurrency, ftBCD ] then
Result := true;
end;
procedure TFIngDatos.AplicarEstilo;
var
x: integer;
PropInfo: PPropInfo;
begin
with PnlMain do
for x:=0 to ControlCount-1 do
begin
PropInfo := GetPropInfo( Controls[ x ], 'CharCase' );
if PropInfo <> nil then
SetEnumProp( Controls[ x ], PropInfo, 'ecUpperCase' );
end;
end;
procedure TFIngDatos.SetMayusculas(const Value: boolean);
begin
FMayusculas := Value;
end;
procedure TFIngDatos.CreateWnd;
begin
inherited;
FPrimeraVez := true;
FMayusculas := true;
FConfirmaGrabacion := false;
FConfirmaBorrar := false;
FAutoInsert := false;
end;
procedure TFIngDatos.OrdenarExecute(Sender: TObject);
begin
if ( DIng.DataSet.state in [ dsInsert, dsEdit ] ) then
raise exception.create( 'Por favor, grabe o anule las modificaciones primero' );
CambiarOrden;
end;
procedure TFIngDatos.AyudaExecute(Sender: TObject);
begin
if Application.HelpFile <> '' then
Application.HelpCommand( HELP_CONTENTS, 0 )
else
ShowMessage( 'Archivo de ayuda no ha sido especificado' );
end;
procedure TFIngDatos.CambiarOrden;
var
FIndice: string;
begin
FIndice := ShowOrderDlg( TStringlist( TDataSet( Ding.DataSet ).FieldList ));
Application.ProcessMessages;
if FIndice <> '' then
try
Screen.Cursor := crHourGlass;
ModiOrden( FIndice, Ascending );
finally
Screen.Cursor := crDefault;
end;
end;
procedure TFIngDatos.cbSearchChange(Sender: TObject);
begin
if cbSearch.ItemIndex >= 0 then
begin
sEdit.DataField := Ding.DataSet.Fields[ cbSearch.ItemIndex ].FieldName;
jvFiltrar.DataField := Ding.DataSet.Fields[ cbSearch.ItemIndex ].FieldName;
if Ding.DataSet.Fields[ cbSearch.ItemIndex ] is TDateField then
jvFiltrar.EditMask := '!99/99/9999;1;_'
else
jvFiltrar.EditMask := '';
end;
end;
procedure TFIngDatos.ModiOrden( AFieldName: string; asc:boolean );
var
hBook: TBookmark;
begin
Screen.Cursor := crHourGlass;
try
( DIng.DataSet ).DisableControls;
hBook := ( DIng.DataSet ).GetBookmark;
if ( DIng.Dataset is TAdoDataSet ) then
TAdoDataSet( DIng.DataSet ).IndexFieldNames := AFieldName
else if (DIng.DataSet is TClientDataSet ) then
TClientDataSet( DIng.DataSet ).IndexFieldNames := AFieldName;
( DIng.DataSet ).GotoBookmark( hBook );
finally
( DIng.DataSet ).FreeBookmark( hBook );
( DIng.DataSet ).EnableControls;
Screen.Cursor := crDefault;
end;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpHex;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
SbpBase16,
ClpCryptoLibTypes;
type
THex = class sealed(TObject)
public
class function Decode(const Hex: String): TCryptoLibByteArray; static;
class function Encode(const Input: TCryptoLibByteArray;
UpperCase: Boolean = True): String; static;
end;
implementation
{ THex }
class function THex.Decode(const Hex: String): TCryptoLibByteArray;
begin
result := SbpBase16.TBase16.Decode(Hex);
end;
class function THex.Encode(const Input: TCryptoLibByteArray;
UpperCase: Boolean): String;
begin
case UpperCase of
True:
result := SbpBase16.TBase16.EncodeUpper(Input);
False:
result := SbpBase16.TBase16.EncodeLower(Input);
end;
end;
end.
|
unit FingerTabs;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
noFinger = -1;
type
TFingetTabAlign = (ftaLeft, ftaRight);
TFingerType = (ftFinger, ftGradient);
TFingerTabAdjust = procedure(Sender : TObject; DeltaSize : integer) of object;
PRects = ^TRects;
TRects = array[0..0] of TRect;
TFingerTabs =
class(TCustomControl)
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
private
fLeftColor : TColor;
fRightColor : TColor;
fLineColor : TColor;
fFingerColor : TColor;
fSelTabColor : TColor;
fTextColor : TColor;
fHilTextColor : TColor;
fSelTextColor : TColor;
fTabNames : TStrings;
fCurrentFinger : integer;
fTextAlign : TFingetTabAlign;
fTextMargin : integer;
fFingerRadius : integer;
fFixedSize : boolean;
fFingerType : TFingerType;
fOnFingerChange : TNotifyEvent;
fOnAdjustHeight : TFingerTabAdjust;
private
fBitmap : TBitmap;
fRects : PRects;
fLightedTab : integer;
fUpdating : boolean;
fStdHeight : word;
private
function MessureLineHeight(const text : string) : TRect;
function GetTotalHeight : integer;
procedure CalcRects;
procedure RebuildRects;
function GetTextFlags : integer;
procedure DrawText(index : integer; aCanvas : TCanvas; color : TColor; render : boolean);
procedure RedrawTabText(tab : integer; color : TColor; toBmp : boolean);
procedure DrawFinger(index : integer);
procedure DrawTabs;
procedure RenderToBmp;
procedure RedrawAll;
protected
procedure Paint; override;
procedure Loaded; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
private
function PointInTab(aX, aY : integer; var tab : integer) : boolean;
protected
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
procedure BeginUpdate;
procedure EndUpdate;
procedure AddFinger(name : string; Obj : TObject);
procedure ClearFingers;
private
function GetObject(index : integer) : TObject;
public
property Objects[index : integer] : TObject read GetObject;
private
procedure SetLeftColor(aColor : TColor);
procedure SetRightColor(aColor : TColor);
procedure SetLineColor(aColor : TColor);
procedure SetFingerColor(aColor : TColor);
procedure SetSelTabColor(aColor : TColor);
procedure SetTextColor(aColor : TColor);
procedure SetHilTextColor(aColor : TColor);
procedure SetSelTextColor(aColor : TColor);
procedure SetTabNames(Names : TStrings);
procedure SetCurrentFinger(index : integer);
procedure SetTextAlign(anAlign : TFingetTabAlign);
procedure SetTextMargin(aMargin : integer);
procedure SetFingerRadius(aRadius : integer);
procedure SetFixedSize(fixed : boolean);
procedure SetFingerType(aType : TFingerType);
published
property LeftColor : TColor read fLeftColor write SetLeftColor;
property RightColor : TColor read fRightColor write SetRightColor;
property LineColor : TColor read fLineColor write SetLineColor;
property FingerColor : TColor read fFingerColor write SetFingerColor;
property SelTabColor : TColor read fSelTabColor write SetSelTabColor;
property TextColor : TColor read fTextColor write SetTextColor;
property HilTextColor : TColor read fHilTextColor write SetHilTextColor;
property SelTextColor : TColor read fSelTextColor write SetSelTextColor;
property TabNames : TStrings read fTabNames write SetTabNames;
property CurrentFinger : integer read fCurrentFinger write SetCurrentFinger;
property TextAlign : TFingetTabAlign read fTextAlign write SetTextAlign;
property TextMargin : integer read fTextMargin write SetTextMargin;
property FingerRadius : integer read fFingerRadius write SetFingerRadius;
property FixedSize : boolean read fFixedSize write SetFixedSize;
property FingerType : TFingerType read fFingerType write SetFingerType;
published
property OnOnFingerChange : TNotifyEvent read fOnFingerChange write fOnFingerChange;
property OnAdjustHeight : TFingerTabAdjust read fOnAdjustHeight write fOnAdjustHeight;
published
property Align;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
implementation
uses
GradientUtils;
function max(a, b : integer) : integer;
begin
if a > b
then result := a
else result := b;
end;
function min(a, b : integer) : integer;
begin
if a > b
then result := b
else result := a;
end;
// TFingerTabs
constructor TFingerTabs.Create(AOwner : TComponent);
begin
inherited;
fBitmap := TBitmap.Create;
fTabNames := TStringList.Create;
fTextMargin := 2;
fLightedTab := noFinger;
fCurrentFinger := noFinger;
end;
destructor TFingerTabs.Destroy;
begin
fBitmap.Free;
fUpdating := true;
ClearFingers;
fTabNames.Free;
inherited;
end;
function TFingerTabs.MessureLineHeight(const text : string) : TRect;
begin
result.Left := 0;
result.Top := 0;
result.Right := Width - 2*(fFingerRadius + fTextMargin);
result.Bottom := 0;
Windows.DrawText(fBitmap.Canvas.Handle, pchar(text), -1, result, DT_CALCRECT or DT_WORDBREAK);
end;
function TFingerTabs.GetTotalHeight : integer;
var
i : integer;
begin
result := 0;
for i := 0 to pred(fTabNames.Count) do
inc(result, MessureLineHeight(fTabNames[i]).Bottom);
inc(result, pred(fTabNames.Count)*fTextMargin + 2*fFingerRadius + 2*fTextMargin);
end;
procedure TFingerTabs.CalcRects;
var
i : integer;
crHgh : integer;
R : TRect;
crTop : integer;
begin
if fCurrentFinger = noFinger
then crTop := fFingerRadius
else
if fCurrentFinger = 0
then crTop := 0
else crTop := fTextMargin;
for i := 0 to pred(fTabNames.Count) do
begin
R := MessureLineHeight(fTabNames[i]);
crHgh := R.Bottom;
// Le's align the Rect
if fFixedSize
then
begin
R.Left := fFingerRadius + fTextMargin;
R.Right := Width - fTextMargin;
end
else
begin
case fTextAlign of
ftaLeft : R.Left := fFingerRadius + fTextMargin;
ftaRight : R.Left := Width - R.Right - fTextMargin;
end;
inc(R.Right, R.Left);
end;
if i <> fCurrentFinger
then
begin
R.Top := crTop;
inc(crTop, crHgh);
R.Bottom := crTop;
end
else
begin
inc(crTop, fFingerRadius);
R.Top := crTop;
inc(crTop, crHgh);
R.Bottom := crTop;
inc(crTop, fFingerRadius);
end;
fRects[i] := R;
inc(crTop, fTextMargin);
end;
end;
procedure TFingerTabs.RebuildRects;
begin
ReallocMem(fRects, fTabNames.Count*sizeof(TRect));
CalcRects;
end;
function TFingerTabs.GetTextFlags : integer;
begin
result := DT_NOPREFIX or DT_VCENTER or DT_WORDBREAK;
case fTextAlign of
ftaLeft :
result := result or DT_LEFT;
ftaRight :
result := result or DT_RIGHT;
end;
end;
procedure TFingerTabs.DrawText(index : integer; aCanvas : TCanvas; color : TColor; render : boolean);
var
R : TRect;
aux : pchar;
begin
aux := pchar(fTabNames[index]);
R := fRects[index];
aCanvas.Font.Color := color;
aCanvas.Brush.Style := bsClear;
Windows.DrawText(aCanvas.Handle, aux, -1, R, GetTextFlags);
if render
then Canvas.CopyRect(R, fBitmap.Canvas, R);
end;
procedure TFingerTabs.RedrawTabText(tab : integer; color : TColor; toBmp : boolean);
begin
if tab <> noFinger
then DrawText(tab, fBitmap.Canvas, color, not toBmp);
end;
procedure TFingerTabs.DrawFinger(index : integer);
var
R : TRect;
pts : array[0..5] of TPoint;
d : integer;
h : integer;
begin
R := fRects[index];
case fFingerType of
ftFinger :
begin
h := fStdHeight div 2;
d := 2*(h + fFingerRadius);
fBitmap.Canvas.Brush.Style := bsSolid;
fBitmap.Canvas.Brush.Color := fFingerColor;
InflateRect(R, fTextMargin, fFingerRadius);
dec(R.Left, fFingerRadius);
pts[0].x := R.Left;
pts[0].y := R.Top + fFingerRadius + h;
pts[1].x := R.Left + fFingerRadius + h;
pts[1].y := R.Top;
pts[2].x := R.Right;
pts[2].y := R.Top;
pts[3].x := R.Right;
pts[3].y := R.Bottom - 1;
pts[4].x := R.Left + fFingerRadius + h;
pts[4].y := R.Bottom - 1;
pts[5].x := R.Left;
pts[5].y := R.Bottom - (fFingerRadius + h);
fBitmap.Canvas.Pen.Color := fFingerColor;
fBitmap.Canvas.Polygon(pts);
fBitmap.Canvas.Ellipse(R.Left, R.Top, R.Left + d, R.Top + d);
fBitmap.Canvas.Ellipse(R.Left, R.Bottom - d, R.Left + d, R.Bottom);
end;
ftGradient :
begin
InflateRect(R, fTextMargin, fFingerRadius);
dec(R.Left, fFingerRadius);
GradientUtils.Gradient(fBitmap.Canvas, fLeftColor, fFingerColor, true, R);
end;
end;
end;
procedure TFingerTabs.DrawTabs;
var
i : integer;
begin
fBitmap.Canvas.Brush.Style := bsClear;
for i := 0 to pred(fTabNames.Count) do
if i <> fCurrentFinger
then RedrawTabText(i, fTextColor, true)
else
begin
DrawFinger(i);
RedrawTabText(i, fSelTextColor, true);
end;
end;
procedure TFingerTabs.RenderToBmp;
begin
fBitmap.Canvas.Font := Font;
fBitmap.Canvas.Brush.Color := fLeftColor;
fBitmap.Canvas.Brush.Style := bsSolid;
fBitmap.Canvas.FillRect(ClientRect);
DrawTabs;
end;
procedure TFingerTabs.RedrawAll;
var
TtHght : integer;
begin
if not fUpdating
then
begin
fStdHeight := Canvas.TextHeight('|') div 2;
TtHght := GetTotalHeight;
if (TtHght <> Height) and Assigned(fOnAdjustHeight)
then fOnAdjustHeight(self, TtHght - Height);
if TtHght > 0
then
begin
fBitmap.Height := TtHght;
RebuildRects;
Height := max(Height, TtHght);
RenderToBmp;
Refresh;
end;
end;
end;
procedure TFingerTabs.Paint;
begin
Canvas.CopyRect(ClientRect, fBitmap.Canvas, ClientRect);
end;
procedure TFingerTabs.Loaded;
begin
inherited;
fFingerRadius := Canvas.TextHeight('|') div 2;
end;
procedure TFingerTabs.SetBounds(ALeft, ATop, AWidth, AHeight : Integer);
begin
inherited;
if (AWidth > 0) and (AHeight > 0) and (AWidth <> fBitmap.Width) and (AHeight <> fBitmap.Height)
then
begin
fBitmap.Width := Width;
fBitmap.Height := Height;
fBitmap.Canvas.FillRect(ClientRect);
Canvas.CopyRect(ClientRect, fBitmap.Canvas, ClientRect);
end;
end;
function TFingerTabs.PointInTab(aX, aY : integer; var tab : integer) : boolean;
var
cnt : integer;
begin
tab := 0;
cnt := fTabNames.Count;
while (tab < cnt) and not PtInRect(fRects[tab], Point(aX, aY)) do
inc(tab);
result := tab < cnt;
end;
procedure TFingerTabs.CMMouseEnter(var Message: TMessage);
begin
end;
procedure TFingerTabs.CMMouseLeave(var Message: TMessage);
begin
RedrawTabText(fLightedTab, fTextColor, false);
fLightedTab := noFinger;
Cursor := crDefault;
end;
procedure TFingerTabs.CMFontChanged(var Message: TMessage);
begin
RedrawAll;
end;
procedure TFingerTabs.WMEraseBkgnd(var Message: TMessage);
begin
Message.Result := 1;
end;
procedure TFingerTabs.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
tab : integer;
begin
inherited;
if PointInTab(X, Y, tab)
then
begin
fLightedTab := noFinger;
MouseCapture := true;
CurrentFinger := tab;
end;
end;
procedure TFingerTabs.MouseMove(Shift: TShiftState; X, Y: Integer);
var
tab : integer;
begin
inherited;
if PointInTab(X, Y, tab) and (Shift = [])
then
begin
Cursor := crHandPoint;
if fLightedTab <> tab
then
begin
RedrawTabText(fLightedTab, fTextColor, false);
if tab <> fCurrentFinger
then
begin
fLightedTab := tab;
RedrawTabText(tab, fHilTextColor, false);
end
else
begin
fLightedTab := noFinger;
Cursor := crDefault;
end;
end
end
else
begin
Cursor := crDefault;
RedrawTabText(fLightedTab, fTextColor, false);
fLightedTab := noFinger;
end;
end;
procedure TFingerTabs.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
MouseCapture := false;
end;
procedure TFingerTabs.BeginUpdate;
begin
fUpdating := true;
end;
procedure TFingerTabs.EndUpdate;
begin
fUpdating := false;
RedrawAll;
end;
procedure TFingerTabs.AddFinger(name : string; Obj : TObject);
begin
fTabNames.AddObject(name, Obj);
ReDrawAll;
end;
procedure TFingerTabs.ClearFingers;
var
i : integer;
begin
for i := 0 to pred(fTabNames.Count) do
fTabNames.Objects[i].Free;
fTabNames.Clear;
fCurrentFinger := noFinger;
ReDrawAll;
end;
function TFingerTabs.GetObject(index : integer) : TObject;
begin
result := fTabNames.Objects[index];
end;
procedure TFingerTabs.SetLeftColor(aColor : TColor);
begin
if fLeftColor <> aColor
then
begin
fLeftColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetRightColor(aColor : TColor);
begin
if fRightColor <> aColor
then
begin
fRightColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetLineColor(aColor : TColor);
begin
if fLineColor <> aColor
then
begin
fLineColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetFingerColor(aColor : TColor);
begin
if fFingerColor <> aColor
then
begin
fFingerColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetSelTabColor(aColor : TColor);
begin
if fSelTabColor <> aColor
then
begin
fSelTabColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetTextColor(aColor : TColor);
begin
if fTextColor <> aColor
then
begin
fTextColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetHilTextColor(aColor : TColor);
begin
if fHilTextColor <> aColor
then
begin
fHilTextColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetSelTextColor(aColor : TColor);
begin
if fSelTextColor <> aColor
then
begin
fSelTextColor := aColor;
RedrawAll;
end;
end;
procedure TFingerTabs.SetTabNames(Names : TStrings);
begin
fCurrentFinger := -1;
fTabNames.Clear;
fTabNames.AddStrings(Names);
RedrawAll;
end;
procedure TFingerTabs.SetCurrentFinger(index : integer);
begin
if fCurrentFinger <> index
then
begin
fCurrentFinger := index;
RedrawAll;
if Assigned(fOnFingerChange)
then fOnFingerChange(self);
end;
end;
procedure TFingerTabs.SetTextAlign(anAlign : TFingetTabAlign);
begin
if fTextAlign <> anAlign
then
begin
fTextAlign := anAlign;
RedrawAll;
end;
end;
procedure TFingerTabs.SetTextMargin(aMargin : integer);
begin
if fTextMargin <> aMargin
then
begin
fTextMargin := aMargin;
RedrawAll;
end;
end;
procedure TFingerTabs.SetFingerRadius(aRadius : integer);
begin
if fFingerRadius <> aRadius
then
begin
fFingerRadius := aRadius;
RedrawAll;
end;
end;
procedure TFingerTabs.SetFixedSize(fixed : boolean);
begin
if fFixedSize <> fixed
then
begin
fFixedSize := fixed;
RedrawAll;
end;
end;
procedure TFingerTabs.SetFingerType(aType : TFingerType);
begin
if fFingerType <> aType
then
begin
fFingerType := aType;
RedrawAll;
end;
end;
procedure Register;
begin
RegisterComponents('Five', [TFingerTabs]);
end;
end.
|
unit UCliente;
interface
uses
Data.Win.ADODB, Data.DB, System.Generics.Collections, System.SysUtils, UPadrao;
type
TCliente = class(TPadrao)
private
Fid: Integer;
Fcliente: string;
FTipoPessoa: string;
FInscrEstadual: string;
FCPF_CNPJ: string;
FDtNascimento: TDateTime;
FIdentidade: string;
FSexo: string;
function GetCliente: string;
function GetId: Integer;
procedure SetCliente(const Value: string);
procedure SetId(const Value: Integer);
procedure SetCPF_CNPJ(const Value: string);
procedure SetDtNascimento(const Value: TDateTime);
procedure SetIdentidade(const Value: string);
procedure SetInscrEstadual(const Value: string);
procedure SetSexo(const Value: string);
procedure SetTipoPessoa(const Value: string);
public
property id: Integer read GetId write SetId;
property cliente: string read GetCliente write SetCliente;
property CPF_CNPJ: string read FCPF_CNPJ write SetCPF_CNPJ;
property Identidade: string read FIdentidade write SetIdentidade;
property Sexo: string read FSexo write SetSexo;
property DtNascimento: TDateTime read FDtNascimento write SetDtNascimento;
property TipoPessoa: string read FTipoPessoa write SetTipoPessoa;
property InscrEstadual: string read FInscrEstadual write SetInscrEstadual;
end;
TEndereco = class(TPadrao)
private
FBairro: string;
FIdEndereco: Integer;
FCep: string;
FLocalidade: string;
FComplemento: string;
FTipoEndereco: string;
FIdCliente: Integer;
FCidade: string;
FEstado: string;
procedure SetBairro(const Value: string);
procedure SetCep(const Value: string);
procedure SetCidade(const Value: string);
procedure SetComplemento(const Value: string);
procedure SetEstado(const Value: string);
procedure SetIdCliente(const Value: Integer);
procedure SetIdEndereco(const Value: Integer);
procedure SetLocalidade(const Value: string);
procedure SetTipoEndereco(const Value: string);
public
property IdEndereco: Integer read FIdEndereco write SetIdEndereco;
property IdCliente: Integer read FIdCliente write SetIdCliente;
property TipoEndereco: string read FTipoEndereco write SetTipoEndereco;
property Localidade: string read FLocalidade write SetLocalidade;
property Bairro: string read FBairro write SetBairro;
property Cidade: string read FCidade write SetCidade;
property Estado: string read FEstado write SetEstado;
property Cep: string read FCep write SetCep;
property Complemento: string read FComplemento write SetComplemento;
end;
TTelefone = class(TPadrao)
private
FID: Integer;
FTipoTelefone: string;
FIdCliente: Integer;
FTelefone: string;
Fddd: string;
Fwhatsapp: string;
Fpais: string;
procedure SetID(const Value: Integer);
procedure SetIdCliente(const Value: Integer);
procedure SetTelefone(const Value: string);
procedure SetTipoTelefone(const Value: string);
procedure Setddd(const Value: string);
procedure Setpais(const Value: string);
procedure Setwhatsapp(const Value: string);
public
procedure SetObjeto(const AValue: TFields);
property ID: Integer read FID write SetID;
property IdCliente: Integer read FIdCliente write SetIdCliente;
property TipoTelefone: string read FTipoTelefone write SetTipoTelefone;
property Telefone: string read FTelefone write SetTelefone;
property pais: string read Fpais write Setpais;
property ddd: string read Fddd write Setddd;
property whatsapp: string read Fwhatsapp write Setwhatsapp;
end;
TEmail = class(TPadrao)
private
FEmail: string;
FID: Integer;
FIdCliente: Integer;
procedure SetEmail(const Value: string);
procedure SetID(const Value: Integer);
procedure SetIdCliente(const Value: Integer);
public
property ID: Integer read FID write SetID;
property IdCliente: Integer read FIdCliente write SetIdCliente;
property Email: string read FEmail write SetEmail;
end;
TImgCli = class(TPadrao)
private
FidImagem: Integer;
FID: Integer;
FidCliente: Integer;
procedure SetID(const Value: Integer);
procedure SetidCliente(const Value: Integer);
procedure SetidImagem(const Value: Integer);
public
property ID: Integer read FID write SetID;
property idCliente: Integer read FidCliente write SetidCliente;
property idImagem: Integer read FidImagem write SetidImagem;
end;
TGeralCli = class(TPadrao)
private
FCliente: TCliente;
FEndereco: TEndereco;
FTelefone: TTelefone;
FEmail: TEmail;
procedure SetCliente(const Value: TCliente);
procedure SetEndereco(const Value: TEndereco);
procedure SetTelefone(const Value: TTelefone);
procedure SetEmail(const Value: TEmail);
public
constructor Create;
destructor Destroy;override;
property Cliente: TCliente read FCliente write SetCliente;
property Endereco: TEndereco read FEndereco write SetEndereco;
property Telefone: TTelefone read FTelefone write SetTelefone;
property Email: TEmail read FEmail write SetEmail;
end;
implementation
uses System.Variants, Vcl.Dialogs;
{$REGION 'TCliente'}
function TCliente.GetCliente: string;
begin
Result := Self.Fcliente;
end;
function TCliente.GetId: Integer;
begin
Result := Self.Fid;
end;
procedure TCliente.SetCliente(const Value: string);
begin
Self.Fcliente := Value;
end;
procedure TCliente.SetCPF_CNPJ(const Value: string);
begin
FCPF_CNPJ := Value;
end;
procedure TCliente.SetDtNascimento(const Value: TDateTime);
begin
FDtNascimento := Value;
end;
procedure TCliente.SetId(const Value: Integer);
begin
Self.Fid := Value;
end;
procedure TCliente.SetIdentidade(const Value: string);
begin
FIdentidade := Value;
end;
procedure TCliente.SetInscrEstadual(const Value: string);
begin
FInscrEstadual := Value;
end;
procedure TCliente.SetSexo(const Value: string);
begin
FSexo := Value;
end;
procedure TCliente.SetTipoPessoa(const Value: string);
begin
FTipoPessoa := Value;
end;
{$ENDREGION}
{$REGION 'TEndereco' }
procedure TEndereco.SetBairro(const Value: string);
begin
FBairro := Value;
end;
procedure TEndereco.SetCep(const Value: string);
begin
FCep := Value;
end;
procedure TEndereco.SetCidade(const Value: string);
begin
FCidade := Value;
end;
procedure TEndereco.SetComplemento(const Value: string);
begin
FComplemento := Value;
end;
procedure TEndereco.SetEstado(const Value: string);
begin
FEstado := Value;
end;
procedure TEndereco.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TEndereco.SetIdEndereco(const Value: Integer);
begin
FIdEndereco := Value;
end;
procedure TEndereco.SetLocalidade(const Value: string);
begin
FLocalidade := Value;
end;
procedure TEndereco.SetTipoEndereco(const Value: string);
begin
FTipoEndereco := Value;
end;
{$ENDREGION}
{$REGION 'TTelefone' }
procedure TTelefone.Setddd(const Value: string);
begin
Fddd := Value;
end;
procedure TTelefone.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TTelefone.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TTelefone.SetObjeto(const AValue: TFields);
begin
Self.FID := AValue.FieldByName('ID').Value;
Self.FIdCliente := AValue.FieldByName('IdCliente').Value;
Self.FTipoTelefone := AValue.FieldByName('TipoTelefone').Value;
Self.FTelefone := AValue.FieldByName('Telefone').Value;
Self.Fpais := AValue.FieldByName('pais').Value;
Self.Fddd := AValue.FieldByName('ddd').Value;
Self.Fwhatsapp := AValue.FieldByName('whatsapp').Value;
end;
procedure TTelefone.Setpais(const Value: string);
begin
Fpais := Value;
end;
procedure TTelefone.SetTelefone(const Value: string);
begin
FTelefone := Value;
end;
procedure TTelefone.SetTipoTelefone(const Value: string);
begin
FTipoTelefone := Value;
end;
procedure TTelefone.Setwhatsapp(const Value: string);
begin
Fwhatsapp := Value;
end;
{$ENDREGION}
{$REGION 'TEmail' }
procedure TEmail.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TEmail.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TEmail.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
{$ENDREGION}
{$REGION 'TImgCli' }
procedure TImgCli.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TImgCli.SetidCliente(const Value: Integer);
begin
FidCliente := Value;
end;
procedure TImgCli.SetidImagem(const Value: Integer);
begin
FidImagem := Value;
end;
{$ENDREGION}
{$REGION 'TGeralCli' }
constructor TGeralCli.Create;
begin
inherited;
FCliente := TCliente.Create;
FEndereco := TEndereco.Create;
FTelefone := TTelefone.Create;
FEmail := TEmail.Create;
end;
destructor TGeralCli.Destroy;
begin
FreeAndNil(FCliente);
FreeAndNil(FEndereco);
FreeAndNil(FTelefone);
FreeAndNil(FEmail);
inherited;
end;
procedure TGeralCli.SetCliente(const Value: TCliente);
begin
FCliente := Value;
end;
procedure TGeralCli.SetEmail(const Value: TEmail);
begin
FEmail := Value;
end;
procedure TGeralCli.SetEndereco(const Value: TEndereco);
begin
FEndereco := Value;
end;
procedure TGeralCli.SetTelefone(const Value: TTelefone);
begin
FTelefone := Value;
end;
{$ENDREGION}
end.
|
{*******************************************************}
{ }
{ Zlot programistów Delphi }
{ RTTI w Delph }
{ Sylwester Wojnar }
{ }
{ Mszczonów 2019 }
{*******************************************************}
unit demortti.dbsession.fd;
interface
uses
System.Classes, System.SysUtils, Data.DB,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Stan.Option,
FireDAC.Comp.Client, demortti.dbsession;
type
TFDSession = class(TInterfacedObject, IDBSession)
private
FConnection: TFDConnection;
FLogFileName: String;
protected
procedure OpenConnection();
procedure CloseConnection();
function CreateQuery(ASQLText: String): TDataSet;
procedure ExecuteSQL(ACmd: String);
procedure BeginTran();
procedure CommitTran();
procedure RollbackTran();
function Connected(): Boolean;
procedure WriteToLog(AText: String);
public
constructor Create();
destructor Destroy; override;
property LogFileName: String read FLogFileName write FLogFileName;
end;
implementation
{ TDFSession }
procedure TFDSession.BeginTran;
begin
FConnection.StartTransaction();
end;
procedure TFDSession.CloseConnection;
begin
FConnection.Close;
end;
procedure TFDSession.CommitTran;
begin
FConnection.Commit();
end;
constructor TFDSession.Create();
begin
inherited;
FConnection := TFDConnection.Create(nil);
FLogFileName := 'sql.log';
end;
function TFDSession.CreateQuery(ASQLText: String): TDataSet;
begin
Result := TFDQuery.Create(FConnection);
TFDQuery(Result).SQL.Text := ASQLText;
TFDQuery(Result).Connection := FConnection;
WriteToLog('=====================================================');
WriteToLog(ASQLText);
end;
destructor TFDSession.Destroy;
begin
if (FConnection.Connected) then
CloseConnection();
FConnection.Free;
inherited;
end;
procedure TFDSession.ExecuteSQL(ACmd: String);
var
LCmd: TFDCommand;
begin
inherited;
LCmd := TFDCommand.Create(FConnection);
try
LCmd.Connection := FConnection;
LCmd.CommandText.Text := ACmd;
LCmd.Execute();
WriteToLog('=====================================================');
WriteToLog(ACmd);
finally
LCmd.Free;
end;
end;
function TFDSession.Connected: Boolean;
begin
Result := FConnection.Connected;
end;
procedure TFDSession.OpenConnection;
var
LS: TStrings;
begin
LS := TStringList.Create;
LS.LoadFromFile('demo.ini');
FConnection.DriverName := 'PG';
//FConnection.ConnectionName :=
FConnection.Params.Password := LS.Values['password'];
FConnection.Params.UserName := LS.Values['UserName'];
FConnection.Params.Database := LS.Values['Database'];
FConnection.Open();
end;
procedure TFDSession.RollbackTran;
begin
FConnection.Rollback();
end;
procedure TFDSession.WriteToLog(AText: String);
var
LAnsiTxt: AnsiString;
oFS: TFileStream;
begin
if (not FileExists(LogFileName)) then begin
with TFileStream.Create(LogFileName, fmCreate) do
Free;
end;
{$WARNINGS OFF}
LAnsiTxt := AText;
{$WARNINGS ON}
oFS := TFileStream.Create(LogFileName, fmOpenWrite or fmShareDenyWrite);
try
oFS.Seek(0, soFromEnd);
oFS.Write(PAnsiChar(LAnsiTxt)^, Length(LAnsiTxt));
finally
oFS.Free;
end;
end;
end.
|
unit InfoXLTRBORRTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoXLTRBORRRecord = record
PCode: String[6];
PDescription: String[60];
PModCount: SmallInt;
End;
TInfoXLTRBORRClass2 = class
public
PCode: String[6];
PDescription: String[60];
PModCount: SmallInt;
End;
// function CtoRInfoXLTRBORR(AClass:TInfoXLTRBORRClass):TInfoXLTRBORRRecord;
// procedure RtoCInfoXLTRBORR(ARecord:TInfoXLTRBORRRecord;AClass:TInfoXLTRBORRClass);
TInfoXLTRBORRBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoXLTRBORRRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoXLTRBORR = (InfoXLTRBORRPrimaryKey);
TInfoXLTRBORRTable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFTemplate: TBlobField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetEnumIndex(Value: TEIInfoXLTRBORR);
function GetEnumIndex: TEIInfoXLTRBORR;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoXLTRBORRRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLTRBORRRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFTemplate: TBlobField read FDFTemplate;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEIInfoXLTRBORR read GetEnumIndex write SetEnumIndex;
end; { TInfoXLTRBORRTable }
TInfoXLTRBORRQuery = class( TDBISAMQueryAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFTemplate: TBlobField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoXLTRBORRRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLTRBORRRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFTemplate: TBlobField read FDFTemplate;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
end; { TInfoXLTRBORRTable }
procedure Register;
implementation
procedure TInfoXLTRBORRTable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXLTRBORRTable.CreateFields }
procedure TInfoXLTRBORRTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLTRBORRTable.SetActive }
procedure TInfoXLTRBORRTable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXLTRBORRTable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXLTRBORRTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoXLTRBORRTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoXLTRBORRTable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXLTRBORRTable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoXLTRBORRTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 6, N');
Add('Description, String, 60, N');
Add('Template, Memo, 0, N');
Add('ModCount, SmallInt, 0, N');
end;
end;
procedure TInfoXLTRBORRTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoXLTRBORRTable.SetEnumIndex(Value: TEIInfoXLTRBORR);
begin
case Value of
InfoXLTRBORRPrimaryKey : IndexName := '';
end;
end;
function TInfoXLTRBORRTable.GetDataBuffer:TInfoXLTRBORRRecord;
var buf: TInfoXLTRBORRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXLTRBORRTable.StoreDataBuffer(ABuffer:TInfoXLTRBORRRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFModCount.Value := ABuffer.PModCount;
end;
function TInfoXLTRBORRTable.GetEnumIndex: TEIInfoXLTRBORR;
var iname : string;
begin
result := InfoXLTRBORRPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoXLTRBORRPrimaryKey;
end;
procedure TInfoXLTRBORRQuery.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXLTRBORRQuery.CreateFields }
procedure TInfoXLTRBORRQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLTRBORRQuery.SetActive }
procedure TInfoXLTRBORRQuery.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXLTRBORRQuery.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXLTRBORRQuery.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoXLTRBORRQuery.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoXLTRBORRQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXLTRBORRQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
function TInfoXLTRBORRQuery.GetDataBuffer:TInfoXLTRBORRRecord;
var buf: TInfoXLTRBORRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXLTRBORRQuery.StoreDataBuffer(ABuffer:TInfoXLTRBORRRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFModCount.Value := ABuffer.PModCount;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoXLTRBORRTable, TInfoXLTRBORRQuery, TInfoXLTRBORRBuffer ] );
end; { Register }
function TInfoXLTRBORRBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..3] of string = ('CODE','DESCRIPTION','MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 3) and (flist[x] <> s) do inc(x);
if x <= 3 then result := x else result := 0;
end;
function TInfoXLTRBORRBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftSmallInt;
end;
end;
function TInfoXLTRBORRBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PModCount;
end;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpAesLightEngine;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
SysUtils,
ClpIAesLightEngine,
ClpIBlockCipher,
ClpICipherParameters,
ClpIKeyParameter,
ClpCheck,
ClpBits,
ClpConverters,
ClpCryptoLibTypes;
resourcestring
AESEngineNotInitialised = 'AES Engine not Initialised';
SInputBuffertooShort = 'Input Buffer too Short';
SOutputBuffertooShort = 'Output Buffer too Short';
SInvalidParameterAESInit = 'Invalid Parameter Passed to AES Init - "%s"';
SInvalidKeyLength = 'Key Length not 128/192/256 bits.';
SInvalidOperation = 'Should Never Get Here';
type
/// <summary>
/// <para>
/// an implementation of the AES (Rijndael), from FIPS-197.
/// </para>
/// <para>
/// For further details see: <see href="http://csrc.nist.gov/encryption/aes/" />
/// </para>
/// <para>
/// This implementation is based on optimizations from Dr. Brian
/// Gladman's paper and C code at <see href="http://fp.gladman.plus.com/cryptography_technology/rijndael/" />
/// </para>
/// <para>
/// This version uses no static tables at all and computes the values
/// in each round.
/// </para>
/// <para>
/// This file contains the slowest performance version with no static
/// tables for round precomputation, but it has the smallest foot
/// print.
/// </para>
/// </summary>
TAesLightEngine = class sealed(TInterfacedObject, IAesLightEngine,
IBlockCipher)
strict private
const
// multiply four bytes in GF(2^8) by 'x' {02} in parallel //
m1 = UInt32($80808080);
m2 = UInt32($7F7F7F7F);
m3 = UInt32($0000001B);
m4 = UInt32($C0C0C0C0);
m5 = UInt32($3F3F3F3F);
BLOCK_SIZE = Int32(16);
var
FROUNDS: Int32;
FWorkingKey: TCryptoLibMatrixUInt32Array;
FC0, FC1, FC2, FC3: UInt32;
FforEncryption: Boolean;
function GetAlgorithmName: String; virtual;
function GetIsPartialBlockOkay: Boolean; virtual;
function GetBlockSize(): Int32; virtual;
/// <summary>
/// <para>
/// Calculate the necessary round keys
/// </para>
/// <para>
/// The number of calculations depends on key size and block size
/// </para>
/// <para>
/// AES specified a fixed block size of 128 bits and key sizes
/// 128/192/256 bits
/// </para>
/// <para>
/// This code is written assuming those are the only possible values
/// </para>
/// </summary>
function GenerateWorkingKey(const key: TCryptoLibByteArray;
forEncryption: Boolean): TCryptoLibMatrixUInt32Array;
procedure UnPackBlock(const bytes: TCryptoLibByteArray; off: Int32); inline;
procedure PackBlock(const bytes: TCryptoLibByteArray; off: Int32); inline;
procedure EncryptBlock(const KW: TCryptoLibMatrixUInt32Array);
procedure DecryptBlock(const KW: TCryptoLibMatrixUInt32Array);
class var
Fs, FSi, Frcon: TCryptoLibByteArray;
class function Shift(r: UInt32; Shift: Int32): UInt32; static; inline;
class function FFmulX(x: UInt32): UInt32; static; inline;
class function FFmulX2(x: UInt32): UInt32; static; inline;
// The following defines provide alternative definitions of FFmulX that might
// give improved performance if a fast 32-bit multiply is not available.
//
// private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); }
// private static final int m4 = 0x1b1b1b1b;
// private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); }
class function Mcol(x: UInt32): UInt32; static; inline;
class function Inv_Mcol(x: UInt32): UInt32; static; inline;
class function SubWord(x: UInt32): UInt32; static; inline;
class constructor AesLightEngine();
public
/// <summary>
/// initialise an AES cipher.
/// </summary>
/// <param name="forEncryption">
/// whether or not we are for encryption.
/// </param>
/// <param name="parameters">
/// the parameters required to set up the cipher.
/// </param>
/// <exception cref="EArgumentCryptoLibException">
/// if the parameters argument is inappropriate.
/// </exception>
procedure Init(forEncryption: Boolean;
const parameters: ICipherParameters); virtual;
function ProcessBlock(const input: TCryptoLibByteArray; inOff: Int32;
const output: TCryptoLibByteArray; outOff: Int32): Int32; virtual;
procedure Reset(); virtual;
property AlgorithmName: String read GetAlgorithmName;
property IsPartialBlockOkay: Boolean read GetIsPartialBlockOkay;
class procedure Boot; static;
end;
implementation
{ TAesLightEngine }
class procedure TAesLightEngine.Boot;
begin
// The S box
Fs := TCryptoLibByteArray.Create(99, 124, 119, 123, 242, 107, 111, 197, 48, 1,
103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212,
162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165,
229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128,
226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179,
41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74,
76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60,
159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255,
243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25,
115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231,
200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186,
120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112,
62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248,
152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161,
137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22);
// The inverse S-box
FSi := TCryptoLibByteArray.Create(82, 9, 106, 213, 48, 54, 165, 56, 191, 64,
163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142,
67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76,
149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162,
73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92,
204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70,
87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88,
5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1,
19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240,
180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28,
117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170,
24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120,
205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128,
236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201,
156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83,
153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85,
33, 12, 125);
// vector used in calculating key schedule (powers of x in GF(256))
Frcon := TCryptoLibByteArray.Create($01, $02, $04, $08, $10, $20, $40, $80,
$1B, $36, $6C, $D8, $AB, $4D, $9A, $2F, $5E, $BC, $63, $C6, $97, $35, $6A,
$D4, $B3, $7D, $FA, $EF, $C5, $91);
end;
class constructor TAesLightEngine.AesLightEngine;
begin
TAesLightEngine.Boot;
end;
class function TAesLightEngine.Shift(r: UInt32; Shift: Int32): UInt32;
begin
// result := (r shr shift) or (r shl (32 - shift));
result := TBits.RotateRight32(r, Shift);
end;
class function TAesLightEngine.SubWord(x: UInt32): UInt32;
begin
result := UInt32(Fs[x and 255]) or (UInt32(Fs[(x shr 8) and 255]) shl 8) or
(UInt32(Fs[(x shr 16) and 255]) shl 16) or
(UInt32(Fs[(x shr 24) and 255]) shl 24);
end;
class function TAesLightEngine.FFmulX(x: UInt32): UInt32;
begin
result := ((x and m2) shl 1) xor (((x and m1) shr 7) * m3);
end;
class function TAesLightEngine.FFmulX2(x: UInt32): UInt32;
var
t0, t1: UInt32;
begin
t0 := (x and m5) shl 2;
t1 := (x and m4);
t1 := t1 xor (t1 shr 1);
result := t0 xor (t1 shr 2) xor (t1 shr 5);
end;
class function TAesLightEngine.Mcol(x: UInt32): UInt32;
var
t0, t1: UInt32;
begin
t0 := Shift(x, 8);
t1 := x xor t0;
result := Shift(t1, 16) xor t0 xor FFmulX(t1);
end;
class function TAesLightEngine.Inv_Mcol(x: UInt32): UInt32;
var
t0, t1: UInt32;
begin
t0 := x;
t1 := t0 xor Shift(t0, 8);
t0 := t0 xor FFmulX(t1);
t1 := t1 xor FFmulX2(t0);
t0 := t0 xor (t1 xor Shift(t1, 16));
result := t0;
end;
procedure TAesLightEngine.EncryptBlock(const KW: TCryptoLibMatrixUInt32Array);
var
lkw: TCryptoLibUInt32Array;
lt0, lt1, lt2, lr0, lr1, lr2, lr3: UInt32;
lr: Int32;
begin
lkw := KW[0];
lt0 := FC0 xor lkw[0];
lt1 := FC1 xor lkw[1];
lt2 := FC2 xor lkw[2];
lr3 := FC3 xor lkw[3];
lr := 1;
while (lr < FROUNDS - 1) do
begin
lkw := KW[lr];
System.Inc(lr);
lr0 := Mcol(UInt32(Fs[lt0 and 255]) xor ((UInt32(Fs[(lt1 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lt2 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr3 shr 24) and 255])) shl 24)) xor lkw[0];
lr1 := Mcol(UInt32(Fs[lt1 and 255]) xor ((UInt32(Fs[(lt2 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lr3 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lt0 shr 24) and 255])) shl 24)) xor lkw[1];
lr2 := Mcol(UInt32(Fs[lt2 and 255]) xor ((UInt32(Fs[(lr3 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lt0 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lt1 shr 24) and 255])) shl 24)) xor lkw[2];
lr3 := Mcol(UInt32(Fs[lr3 and 255]) xor ((UInt32(Fs[(lt0 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lt1 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lt2 shr 24) and 255])) shl 24)) xor lkw[3];
lkw := KW[lr];
System.Inc(lr);
lt0 := Mcol(UInt32(Fs[lr0 and 255]) xor ((UInt32(Fs[(lr1 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lr2 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr3 shr 24) and 255])) shl 24)) xor lkw[0];
lt1 := Mcol(UInt32(Fs[lr1 and 255]) xor ((UInt32(Fs[(lr2 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lr3 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr0 shr 24) and 255])) shl 24)) xor lkw[1];
lt2 := Mcol(UInt32(Fs[lr2 and 255]) xor ((UInt32(Fs[(lr3 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lr0 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr1 shr 24) and 255])) shl 24)) xor lkw[2];
lr3 := Mcol(UInt32(Fs[lr3 and 255]) xor ((UInt32(Fs[(lr0 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lr1 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr2 shr 24) and 255])) shl 24)) xor lkw[3];
end;
lkw := KW[lr];
System.Inc(lr);
lr0 := Mcol(UInt32(Fs[lt0 and 255]) xor ((UInt32(Fs[(lt1 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lt2 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr3 shr 24) and 255])) shl 24)) xor lkw[0];
lr1 := Mcol(UInt32(Fs[lt1 and 255]) xor ((UInt32(Fs[(lt2 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lr3 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lt0 shr 24) and 255])) shl 24)) xor lkw[1];
lr2 := Mcol(UInt32(Fs[lt2 and 255]) xor ((UInt32(Fs[(lr3 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lt0 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lt1 shr 24) and 255])) shl 24)) xor lkw[2];
lr3 := Mcol(UInt32(Fs[lr3 and 255]) xor ((UInt32(Fs[(lt0 shr 8) and 255]))
shl 8) xor ((UInt32(Fs[(lt1 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lt2 shr 24) and 255])) shl 24)) xor lkw[3];
// the final round is a simple function of S
lkw := KW[lr];
FC0 := UInt32(Fs[lr0 and 255]) xor ((UInt32(Fs[(lr1 shr 8) and 255])) shl 8)
xor ((UInt32(Fs[(lr2 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr3 shr 24) and 255])) shl 24) xor lkw[0];
FC1 := UInt32(Fs[lr1 and 255]) xor ((UInt32(Fs[(lr2 shr 8) and 255])) shl 8)
xor ((UInt32(Fs[(lr3 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr0 shr 24) and 255])) shl 24) xor lkw[1];
FC2 := UInt32(Fs[lr2 and 255]) xor ((UInt32(Fs[(lr3 shr 8) and 255])) shl 8)
xor ((UInt32(Fs[(lr0 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr1 shr 24) and 255])) shl 24) xor lkw[2];
FC3 := UInt32(Fs[lr3 and 255]) xor ((UInt32(Fs[(lr0 shr 8) and 255])) shl 8)
xor ((UInt32(Fs[(lr1 shr 16) and 255])) shl 16)
xor ((UInt32(Fs[(lr2 shr 24) and 255])) shl 24) xor lkw[3];
end;
procedure TAesLightEngine.DecryptBlock(const KW: TCryptoLibMatrixUInt32Array);
var
lkw: TCryptoLibUInt32Array;
lt0, lt1, lt2, lr0, lr1, lr2, lr3: UInt32;
lr: Int32;
begin
lkw := KW[FROUNDS];
lt0 := FC0 xor lkw[0];
lt1 := FC1 xor lkw[1];
lt2 := FC2 xor lkw[2];
lr3 := FC3 xor lkw[3];
lr := FROUNDS - 1;
while (lr > 1) do
begin
lkw := KW[lr];
System.Dec(lr);
lr0 := Inv_Mcol(UInt32(FSi[lt0 and 255])
xor ((UInt32(FSi[(lr3 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lt2 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lt1 shr 24) and 255]) shl 24)) xor lkw[0];
lr1 := Inv_Mcol(UInt32(FSi[lt1 and 255])
xor ((UInt32(FSi[(lt0 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr3 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lt2 shr 24) and 255]) shl 24)) xor lkw[1];
lr2 := Inv_Mcol(UInt32(FSi[lt2 and 255])
xor ((UInt32(FSi[(lt1 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lt0 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lr3 shr 24) and 255]) shl 24)) xor lkw[2];
lr3 := Inv_Mcol(UInt32(FSi[lr3 and 255])
xor ((UInt32(FSi[(lt2 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lt1 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lt0 shr 24) and 255]) shl 24)) xor lkw[3];
lkw := KW[lr];
System.Dec(lr);
lt0 := Inv_Mcol(UInt32(FSi[lr0 and 255])
xor ((UInt32(FSi[(lr3 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr2 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lr1 shr 24) and 255]) shl 24)) xor lkw[0];
lt1 := Inv_Mcol(UInt32(FSi[lr1 and 255])
xor ((UInt32(FSi[(lr0 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr3 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lr2 shr 24) and 255]) shl 24)) xor lkw[1];
lt2 := Inv_Mcol(UInt32(FSi[lr2 and 255])
xor ((UInt32(FSi[(lr1 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr0 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lr3 shr 24) and 255]) shl 24)) xor lkw[2];
lr3 := Inv_Mcol(UInt32(FSi[lr3 and 255])
xor ((UInt32(FSi[(lr2 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr1 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lr0 shr 24) and 255]) shl 24)) xor lkw[3];
end;
lkw := KW[1];
lr0 := Inv_Mcol(UInt32(FSi[lt0 and 255])
xor ((UInt32(FSi[(lr3 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lt2 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lt1 shr 24) and 255]) shl 24)) xor lkw[0];
lr1 := Inv_Mcol(UInt32(FSi[lt1 and 255])
xor ((UInt32(FSi[(lt0 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr3 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lt2 shr 24) and 255]) shl 24)) xor lkw[1];
lr2 := Inv_Mcol(UInt32(FSi[lt2 and 255])
xor ((UInt32(FSi[(lt1 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lt0 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lr3 shr 24) and 255]) shl 24)) xor lkw[2];
lr3 := Inv_Mcol(UInt32(FSi[lr3 and 255])
xor ((UInt32(FSi[(lt2 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lt1 shr 16) and 255])) shl 16)
xor (UInt32(FSi[(lt0 shr 24) and 255]) shl 24)) xor lkw[3];
// the final round's table is a simple function of Si
lkw := KW[0];
FC0 := UInt32(FSi[lr0 and 255]) xor ((UInt32(FSi[(lr3 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr2 shr 16) and 255])) shl 16)
xor ((UInt32(FSi[(lr1 shr 24) and 255])) shl 24) xor lkw[0];
FC1 := UInt32(FSi[lr1 and 255]) xor ((UInt32(FSi[(lr0 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr3 shr 16) and 255])) shl 16)
xor ((UInt32(FSi[(lr2 shr 24) and 255])) shl 24) xor lkw[1];
FC2 := UInt32(FSi[lr2 and 255]) xor ((UInt32(FSi[(lr1 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr0 shr 16) and 255])) shl 16)
xor ((UInt32(FSi[(lr3 shr 24) and 255])) shl 24) xor lkw[2];
FC3 := UInt32(FSi[lr3 and 255]) xor ((UInt32(FSi[(lr2 shr 8) and 255])) shl 8)
xor ((UInt32(FSi[(lr1 shr 16) and 255])) shl 16)
xor ((UInt32(FSi[(lr0 shr 24) and 255])) shl 24) xor lkw[3];
end;
function TAesLightEngine.GenerateWorkingKey(const key: TCryptoLibByteArray;
forEncryption: Boolean): TCryptoLibMatrixUInt32Array;
var
keyLen, KC, i, j: Int32;
smallw: TCryptoLibUInt32Array;
bigW: TCryptoLibMatrixUInt32Array;
u, rcon, t0, t1, t2, t3, t4, t5, t6, t7: UInt32;
begin
keyLen := System.Length(key);
if ((keyLen < 16) or (keyLen > 32) or ((keyLen and 7) <> 0)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidKeyLength);
end;
KC := keyLen shr 2; // KC := keyLen div 4;
FROUNDS := KC + 6;
// This is not always true for the generalized Rijndael that allows larger block sizes
System.SetLength(bigW, FROUNDS + 1); // 4 words in a block
for i := 0 to FROUNDS do
begin
System.SetLength(bigW[i], 4);
end;
case KC of
4:
begin
t0 := TConverters.ReadBytesAsUInt32LE(PByte(key), 0);
bigW[0][0] := t0;
t1 := TConverters.ReadBytesAsUInt32LE(PByte(key), 4);
bigW[0][1] := t1;
t2 := TConverters.ReadBytesAsUInt32LE(PByte(key), 8);
bigW[0][2] := t2;
t3 := TConverters.ReadBytesAsUInt32LE(PByte(key), 12);
bigW[0][3] := t3;
for i := 1 to 10 do
begin
u := SubWord(Shift(t3, 8)) xor Frcon[i - 1];
t0 := t0 xor u;
bigW[i][0] := t0;
t1 := t1 xor t0;
bigW[i][1] := t1;
t2 := t2 xor t1;
bigW[i][2] := t2;
t3 := t3 xor t2;
bigW[i][3] := t3;
end;
end;
6:
begin
t0 := TConverters.ReadBytesAsUInt32LE(PByte(key), 0);
bigW[0][0] := t0;
t1 := TConverters.ReadBytesAsUInt32LE(PByte(key), 4);
bigW[0][1] := t1;
t2 := TConverters.ReadBytesAsUInt32LE(PByte(key), 8);
bigW[0][2] := t2;
t3 := TConverters.ReadBytesAsUInt32LE(PByte(key), 12);
bigW[0][3] := t3;
t4 := TConverters.ReadBytesAsUInt32LE(PByte(key), 16);
bigW[1][0] := t4;
t5 := TConverters.ReadBytesAsUInt32LE(PByte(key), 20);
bigW[1][1] := t5;
rcon := 1;
u := SubWord(Shift(t5, 8)) xor rcon;
rcon := rcon shl 1;
t0 := t0 xor u;
bigW[1][2] := t0;
t1 := t1 xor t0;
bigW[1][3] := t1;
t2 := t2 xor t1;
bigW[2][0] := t2;
t3 := t3 xor t2;
bigW[2][1] := t3;
t4 := t4 xor t3;
bigW[2][2] := t4;
t5 := t5 xor t4;
bigW[2][3] := t5;
i := 3;
while i < 12 do
begin
u := SubWord(Shift(t5, 8)) xor rcon;
rcon := rcon shl 1;
t0 := t0 xor u;
bigW[i][0] := t0;
t1 := t1 xor t0;
bigW[i][1] := t1;
t2 := t2 xor t1;
bigW[i][2] := t2;
t3 := t3 xor t2;
bigW[i][3] := t3;
t4 := t4 xor t3;
bigW[i + 1][0] := t4;
t5 := t5 xor t4;
bigW[i + 1][1] := t5;
u := SubWord(Shift(t5, 8)) xor rcon;
rcon := rcon shl 1;
t0 := t0 xor u;
bigW[i + 1][2] := t0;
t1 := t1 xor t0;
bigW[i + 1][3] := t1;
t2 := t2 xor t1;
bigW[i + 2][0] := t2;
t3 := t3 xor t2;
bigW[i + 2][1] := t3;
t4 := t4 xor t3;
bigW[i + 2][2] := t4;
t5 := t5 xor t4;
bigW[i + 2][3] := t5;
System.Inc(i, 3);
end;
u := SubWord(Shift(t5, 8)) xor rcon;
t0 := t0 xor u;
bigW[12][0] := t0;
t1 := t1 xor t0;
bigW[12][1] := t1;
t2 := t2 xor t1;
bigW[12][2] := t2;
t3 := t3 xor t2;
bigW[12][3] := t3;
end;
8:
begin
t0 := TConverters.ReadBytesAsUInt32LE(PByte(key), 0);
bigW[0][0] := t0;
t1 := TConverters.ReadBytesAsUInt32LE(PByte(key), 4);
bigW[0][1] := t1;
t2 := TConverters.ReadBytesAsUInt32LE(PByte(key), 8);
bigW[0][2] := t2;
t3 := TConverters.ReadBytesAsUInt32LE(PByte(key), 12);
bigW[0][3] := t3;
t4 := TConverters.ReadBytesAsUInt32LE(PByte(key), 16);
bigW[1][0] := t4;
t5 := TConverters.ReadBytesAsUInt32LE(PByte(key), 20);
bigW[1][1] := t5;
t6 := TConverters.ReadBytesAsUInt32LE(PByte(key), 24);
bigW[1][2] := t6;
t7 := TConverters.ReadBytesAsUInt32LE(PByte(key), 28);
bigW[1][3] := t7;
rcon := 1;
i := 2;
while i < 14 do
begin
u := SubWord(Shift(t7, 8)) xor rcon;
rcon := rcon shl 1;
t0 := t0 xor u;
bigW[i][0] := t0;
t1 := t1 xor t0;
bigW[i][1] := t1;
t2 := t2 xor t1;
bigW[i][2] := t2;
t3 := t3 xor t2;;
bigW[i][3] := t3;
u := SubWord(t3);
t4 := t4 xor u;
bigW[i + 1][0] := t4;
t5 := t5 xor t4;
bigW[i + 1][1] := t5;
t6 := t6 xor t5;
bigW[i + 1][2] := t6;
t7 := t7 xor t6;
bigW[i + 1][3] := t7;
System.Inc(i, 2);
end;
u := SubWord(Shift(t7, 8)) xor rcon;
t0 := t0 xor u;
bigW[14][0] := t0;
t1 := t1 xor t0;
bigW[14][1] := t1;
t2 := t2 xor t1;
bigW[14][2] := t2;
t3 := t3 xor t2;;
bigW[14][3] := t3;
end
else
begin
raise EInvalidOperationCryptoLibException.CreateRes(@SInvalidOperation);
end;
end;
if (not forEncryption) then
begin
for j := 1 to System.Pred(FROUNDS) do
begin
smallw := bigW[j];
for i := 0 to System.Pred(4) do
begin
smallw[i] := Inv_Mcol(smallw[i]);
end;
end;
end;
result := bigW;
end;
function TAesLightEngine.GetAlgorithmName: String;
begin
result := 'AES';
end;
function TAesLightEngine.GetBlockSize: Int32;
begin
result := BLOCK_SIZE;
end;
function TAesLightEngine.GetIsPartialBlockOkay: Boolean;
begin
result := false;
end;
procedure TAesLightEngine.Init(forEncryption: Boolean;
const parameters: ICipherParameters);
var
keyParameter: IKeyParameter;
begin
if not Supports(parameters, IKeyParameter, keyParameter) then
begin
raise EArgumentCryptoLibException.CreateResFmt(@SInvalidParameterAESInit,
[(parameters as TObject).ToString]);
end;
FWorkingKey := GenerateWorkingKey(keyParameter.GetKey(), forEncryption);
FforEncryption := forEncryption;
end;
procedure TAesLightEngine.PackBlock(const bytes: TCryptoLibByteArray;
off: Int32);
begin
TConverters.ReadUInt32AsBytesLE(FC0, bytes, off);
TConverters.ReadUInt32AsBytesLE(FC1, bytes, off + 4);
TConverters.ReadUInt32AsBytesLE(FC2, bytes, off + 8);
TConverters.ReadUInt32AsBytesLE(FC3, bytes, off + 12);
end;
procedure TAesLightEngine.UnPackBlock(const bytes: TCryptoLibByteArray;
off: Int32);
begin
FC0 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off);
FC1 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off + 4);
FC2 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off + 8);
FC3 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off + 12);
end;
function TAesLightEngine.ProcessBlock(const input: TCryptoLibByteArray;
inOff: Int32; const output: TCryptoLibByteArray; outOff: Int32): Int32;
begin
if (FWorkingKey = Nil) then
begin
raise EInvalidOperationCryptoLibException.CreateRes
(@AESEngineNotInitialised);
end;
TCheck.DataLength(input, inOff, 16, SInputBuffertooShort);
TCheck.OutputLength(output, outOff, 16, SOutputBuffertooShort);
UnPackBlock(input, inOff);
if (FforEncryption) then
begin
EncryptBlock(FWorkingKey);
end
else
begin
DecryptBlock(FWorkingKey);
end;
PackBlock(output, outOff);
result := BLOCK_SIZE;
end;
procedure TAesLightEngine.Reset;
begin
// nothing to do.
end;
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2015 * }
{ *********************************************************** }
unit tfCRCs;
interface
{$I TFL.inc}
uses
tfTypes, tfArrays, tfExceptions;
type
TCRC = record
private
FGenerator: UInt64;
FDigest: UInt64;
FXorIn: UInt64;
FXorOut: UInt64;
FBitSize: Cardinal;
FRevIn: Boolean;
FRevOut: Boolean;
public
class function Init(ABitSize: Cardinal; AGenerator: UInt64;
AXorIn, AXorOut: UInt64; ARevIn, ARevOut: Boolean;
ARevGen: Boolean = False): TCRC; static;
class function BitReverse(AValue: UInt64; ABitSize: Cardinal): UInt64; static;
procedure Reset;
procedure Update(const Data; DataSize: Cardinal);
function Digest: UInt64;
function Hash(const Data; DataSize: Cardinal): UInt64; overload;
function Hash(const Data: ByteArray): UInt64; overload;
property BitSize: Cardinal read FBitSize;
property Generator: UInt64 read FGenerator;
class function CRC16: TCRC; static; // ANSI, IBM, ARC, ..
class function CRC16_AUG_CCITT: TCRC; static;
class function CRC16_XMODEM: TCRC; static;
class function CRC32: TCRC; static; // ANSI, Ethernet, ..
class function CRC32C: TCRC; static; // Castagnoli
class function CRC32K: TCRC; static; // Koopman
end;
implementation
function BitReverseByte(B: Byte): Byte;
begin
B:= ((B and $F0) shr 4) or ((B and $0F) shl 4);
B:= ((B and $CC) shr 2) or ((B and $33) shl 2);
B:= ((B and $AA) shr 1) or ((B and $55) shl 1);
Result:= B;
end;
{ TCRC }
class function TCRC.BitReverse(AValue: UInt64; ABitSize: Cardinal): UInt64;
var
Mask: UInt64;
S: Cardinal;
begin
Mask:= UInt64($FFFFFFFFFFFFFFFF);
S:= 32;
repeat
Mask:= Mask xor (Mask shl S);
AValue:= ((AValue shr S) and Mask) or ((AValue shl S) and not Mask);
S:= S shr 1;
until S = 0;
Result:= AValue shr (64 - ABitSize);
end;
class function TCRC.Init(ABitSize: Cardinal; AGenerator: UInt64;
AXorIn, AXorOut: UInt64; ARevIn, ARevOut: Boolean;
ARevGen: Boolean): TCRC;
begin
if (ABitSize > 64) or (ABitSize = 0) then ForgeError(TF_E_INVALIDARG);
Result.FBitSize:= ABitSize;
if not ARevGen
then Result.FGenerator:= BitReverse(AGenerator, ABitSize)
else Result.FGenerator:= AGenerator;
if not ARevIn
then Result.FXorIn:= BitReverse(AXorIn, ABitSize)
else Result.FXorIn:= AXorIn;
Result.FXorOut:= AXorOut;
Result.FRevIn:= ARevIn;
Result.FRevOut:= ARevOut;
Result.Reset;
end;
procedure TCRC.Reset;
begin
FDigest:= FXorIn;
end;
class function TCRC.CRC16: TCRC;
begin
Result:= Init(16, $8005, 0, 0, True, True);
end;
class function TCRC.CRC16_AUG_CCITT: TCRC;
begin
Result:= Init(16, $1021, $1D0F, 0, False, False);
end;
class function TCRC.CRC16_XMODEM: TCRC;
begin
Result:= Init(16, $1021, 0, 0, False, False);
end;
class function TCRC.CRC32: TCRC;
begin
Result:= Init(32, $EDB88320, $FFFFFFFF, $FFFFFFFF, True, True, True);
end;
class function TCRC.CRC32C: TCRC;
begin
Result:= Init(32, $82F63B78, $FFFFFFFF, $FFFFFFFF, True, True, True);
end;
class function TCRC.CRC32K: TCRC;
begin
Result:= Init(32, $EB31D82E, $FFFFFFFF, $FFFFFFFF, True, True, True);
end;
function TCRC.Digest: UInt64;
begin
if not FRevOut then FDigest:= BitReverse(FDigest, FBitSize);
Result:= FDigest xor FXorOut;
Reset;
end;
procedure TCRC.Update(const Data; DataSize: Cardinal);
var
I: Cardinal;
P: PByte;
B: Byte;
Carry: Boolean;
begin
P:= @Data;
while DataSize > 0 do begin
if not FRevIn
then B:= BitReverseByte(P^)
else B:= P^;
PLongWord(@FDigest)^:= LongWord(FDigest) xor B;
I:= 8;
Inc(P);
repeat
Carry:= Odd(FDigest);
FDigest:= FDigest shr 1;
if Carry then
FDigest:= FDigest xor FGenerator;
Dec(I);
until I = 0;
Dec(DataSize);
end;
end;
function TCRC.Hash(const Data; DataSize: Cardinal): UInt64;
begin
Update(Data, DataSize);
Result:= Digest;
end;
function TCRC.Hash(const Data: ByteArray): UInt64;
begin
Result:= Hash(Data.GetRawData^, Data.GetLen);
end;
end.
|
unit StockDayData_Save;
interface
uses
BaseApp,
StockDayDataAccess;
procedure SaveStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess); overload;
procedure SaveStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess; AFileUrl: string); overload;
implementation
uses
Windows,
BaseWinFile,
Define_Price,
define_datasrc,
define_stock_quotes,
define_dealstore_header,
define_dealstore_file;
{$IFNDEF RELEASE}
const
LOGTAG = 'StockDayData_Save.pas';
{$ENDIF}
procedure SaveStockDayDataToBuffer(App: TBaseApp; ADataAccess: TStockDayDataAccess; AMemory: pointer);
var
tmpHead: PStore_Quote_M1_Day_Header_V1Rec;
tmpQuoteData: PStore64;
tmpStoreDayData: PStore_Quote64_Day;
tmpRTDayData: PRT_Quote_Day;
i: integer;
begin
if nil = ADataAccess then
exit;
if 1 > ADataAccess.RecordCount then
exit;
tmpHead := AMemory;
tmpHead.Header.BaseHeader.CommonHeader.Signature.Signature := 7784; // 6
tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer1 := 1;
tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer2 := 0;
tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer3 := 0;
// 字节存储顺序 java 和 delphi 不同
// 00
// 01
tmpHead.Header.BaseHeader.CommonHeader.Signature.BytesOrder:= 1;
tmpHead.Header.BaseHeader.CommonHeader.HeadSize := SizeOf(TStore_Quote_M1_Day_Header_V1Rec); // 1 -- 7
tmpHead.Header.BaseHeader.CommonHeader.StoreSizeMode.Value := 16; // 1 -- 8 page size mode
{ 表明是什么数据 }
tmpHead.Header.BaseHeader.CommonHeader.DataType := DataType_Stock; // 2 -- 10
tmpHead.Header.BaseHeader.CommonHeader.DataMode := DataMode_DayData; // 1 -- 11
tmpHead.Header.BaseHeader.CommonHeader.RecordSizeMode.Value:= 6; // 1 -- 12
tmpHead.Header.BaseHeader.CommonHeader.RecordCount := ADataAccess.RecordCount; // 4 -- 16
tmpHead.Header.BaseHeader.CommonHeader.CompressFlag := 0; // 1 -- 17
tmpHead.Header.BaseHeader.CommonHeader.EncryptFlag := 0; // 1 -- 18
tmpHead.Header.BaseHeader.CommonHeader.DataSourceId := GetDealDataSourceCode(ADataAccess.DataSource); // 2 -- 20
CopyMemory(@tmpHead.Header.BaseHeader.Code[0], @ADataAccess.StockItem.sCode[1], Length(ADataAccess.StockItem.sCode));
//Move(ADataAccess.StockItem.Code, tmpHead.Header.BaseHeader.Code[0], Length(ADataAccess.StockItem.Code)); // 12 - 32
// ----------------------------------------------------
tmpHead.Header.BaseHeader.StorePriceFactor := 1000; // 2 - 34
tmpHead.Header.FirstDealDate := ADataAccess.FirstDealDate; // 2 - 36
if 0 = ADataAccess.StockItem.FirstDealDate then
begin
if ADataAccess.FirstDealDate <> ADataAccess.StockItem.FirstDealDate then
begin
ADataAccess.StockItem.FirstDealDate := ADataAccess.FirstDealDate;
ADataAccess.StockItem.IsDataChange := 1;
end;
end;
tmpHead.Header.LastDealDate := ADataAccess.LastDealDate; // 2 - 38
tmpHead.Header.EndDealDate := ADataAccess.EndDealDate; // 2 - 40
Inc(tmpHead);
tmpQuoteData := PStore64(tmpHead);
ADataAccess.Sort;
for i := 0 to ADataAccess.RecordCount - 1 do
begin
tmpRTDayData := ADataAccess.RecordItem[i];
if nil <> tmpRTDayData then
begin
tmpStoreDayData := PStore_Quote64_Day(tmpQuoteData);
RTPricePackRange2StorePriceRange(@tmpStoreDayData.PriceRange, @tmpRTDayData.PriceRange);
tmpStoreDayData.DealVolume := tmpRTDayData.DealVolume; // 8 - 24 成交量
tmpStoreDayData.DealAmount := tmpRTDayData.DealAmount; // 8 - 32 成交金额
tmpStoreDayData.DealDate := tmpRTDayData.DealDate.Value; // 4 - 36 交易日期
tmpStoreDayData.Weight.Value := tmpRTDayData.Weight.Value; // 4 - 40 复权权重 * 100
tmpStoreDayData.TotalValue := tmpRTDayData.TotalValue; // 8 - 48 总市值
tmpStoreDayData.DealValue := tmpRTDayData.DealValue; // 8 - 56 流通市值
Inc(tmpQuoteData);
end;
end;
end;
procedure SaveStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess);
var
tmpFileUrl: string;
begin
if nil = ADataAccess then
exit;
if 1 > ADataAccess.RecordCount then
exit;
tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType,
GetDealDataSourceCode(ADataAccess.DataSource),
Integer(ADataAccess.WeightMode),
ADataAccess.StockItem);
if '' <> tmpFileUrl then
begin
SaveStockDayData(App, ADataAccess, tmpFileUrl);
end;
end;
procedure SaveStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess; AFileUrl: string);
var
tmpWinFile: TWinFile;
tmpFileMapView: Pointer;
tmpFileNewSize: integer;
begin
tmpWinFile := TWinFile.Create;
try
if tmpWinFile.OpenFile(AFileUrl, true) then
begin
tmpFileNewSize := SizeOf(TStore_Quote_M1_Day_Header_V1Rec) + ADataAccess.RecordCount * SizeOf(TStore64); //400k
tmpFileNewSize := ((tmpFileNewSize div (64 * 1024)) + 1) * 64 * 1024;
tmpWinFile.FileSize := tmpFileNewSize;
tmpFileMapView := tmpWinFile.OpenFileMap;
if nil <> tmpFileMapView then
begin
SaveStockDayDataToBuffer(App, ADataAccess, tmpFileMapView);
end;
end;
finally
tmpWinFile.Free;
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
uses Math;
{$R *.dfm}
function StringLikeness(Ptrn, Str: string): single;
var
lf, m: single;
j, i: integer;
P, S: string;
begin
lf := length(Ptrn) / (length(Ptrn) + Abs(length(Ptrn) - length(Str)));
P := Ptrn;
S := Str;
m := 0;
j := length(P);
if length(S) < j then
j := length(S);
for i := 1 to j do
begin
if length(S) >= i then
m := m + 1 / (1 + Abs(ord(S[i]) - ord(P[i]))); // Abstand der Zeichen
end;
m := m / length(P); // Durchschnittspunkte
m := m * 0.6 + lf * 0.4; // Lšngenfaktor mit 40% einbeziehen
Result := m;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := FormatFloat('0.000', StringLikeness(Edit1.Text, Edit2.Text));
end;
end.
|
unit PE.COFF;
interface
uses
System.Classes,
System.SysUtils,
PE.COFF.Types;
type
TCOFF = class
private
FPE: TObject;
FStrings: TBytes;
procedure LoadStrings(AStream: TStream);
public
constructor Create(PEImage: TObject);
procedure Clear;
procedure LoadFromStream(AStream: TStream);
function GetString(Offset: integer; out Str: String): boolean;
end;
implementation
uses
// Expand
PE.Types.FileHeader,
//
PE.Common,
PE.Image,
PE.Utils;
{ TCOFF }
procedure TCOFF.Clear;
begin
SetLength(FStrings, 0);
end;
constructor TCOFF.Create(PEImage: TObject);
begin
self.FPE := PEImage;
end;
function TCOFF.GetString(Offset: integer; out Str: String): boolean;
begin
Result := (Offset >= 0) and (Offset < Length(FStrings));
if Result then
Str := String(PAnsiChar(@FStrings[Offset]));
end;
procedure TCOFF.LoadFromStream(AStream: TStream);
begin
LoadStrings(AStream);
end;
procedure TCOFF.LoadStrings(AStream: TStream);
var
StrTableOfs, EndPos: uint64;
cbStringData: uint32;
FileHdr: TImageFileHeader;
begin
Clear;
// 4.6. COFF String Table
FileHdr := TPEImage(FPE).FileHeader^;
if FileHdr.PointerToSymbolTable = 0 then
exit;
if FileHdr.PointerToSymbolTable >= AStream.Size then
begin
TPEImage(FPE).Msg.Write('[FileHeader] Bad PointerToSymbolTable (0x%x)', [FileHdr.PointerToSymbolTable]);
exit;
end;
StrTableOfs :=
FileHdr.PointerToSymbolTable +
FileHdr.NumberOfSymbols * SizeOf(TCOFFSymbolTable);
if not StreamSeek(AStream, StrTableOfs) then
exit; // table not found
if not StreamPeek(AStream, cbStringData, SizeOf(cbStringData)) then
exit;
EndPos := AStream.Position + cbStringData;
if EndPos > AStream.Size then
exit;
// Load string block.
if cbStringData <> 0 then
begin
SetLength(FStrings, cbStringData);
StreamRead(AStream, FStrings[0], cbStringData);
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, SieveOfEratosthenes;
type
TForm1 = class(TForm)
Memo1: TMemo;
Panel1: TPanel;
Button1: TButton;
EditMinZ: TEdit;
EditMaxZ: TEdit;
Label1: TLabel;
Label2: TLabel;
EditMinV: TEdit;
EditMaxV: TEdit;
Label3: TLabel;
Label4: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private-Deklarationen }
procedure BerechneAlles(MinZ, MaxZ:integer; MinV, MaxV:double);
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function ggT(A, B: Integer): Cardinal;
var
Rest: Integer;
begin
while B <> 0 do
begin
Rest := A mod B;
A := B;
B := Rest;
end;
Result := A;
end;
procedure SortTStrings(Strings:TStrings; Duplicates:TDuplicates);
var
tmp: TStringList;
begin
Assert(Assigned(Strings), 'SortTStrings: invalid arg');
if Strings is TStringList then
begin
TStringList(Strings).Duplicates := Duplicates;
TStringList(Strings).Sort;
end else
begin
tmp := TStringList.Create;
try
tmp.Duplicates := Duplicates;
tmp.Sorted := True;
// make a sorted copy
tmp.Assign(Strings);
// copy back
Strings.Assign(tmp);
finally
tmp.Free;
end;
end;
end;
procedure TForm1.BerechneAlles(MinZ, MaxZ:integer; MinV, MaxV:double);
var
x, y : integer;
v : double;
sieb : TSieveOfEratosthenes;
function IsPrime(value:integer):char;
begin
if sieb.IsPrime(value) then
result := '*'
else
result := ' ';
end;
begin
sieb := TSieveOfEratosthenes.Create(MaxZ);
try
sieb.FindPrimes;
for x := minZ to maxZ do
begin
for y := minZ to maxZ do
begin
if ggt(x,y) = 1 then
begin
v := x / y;
if (v >= minv) and (v <= maxV) then
begin
Memo1.Lines.add(Format('%02.4f %2d:%2d %s:%s', [v,x,y, IsPrime(x), IsPrime(y)]));
end;
end;
end;
end;
finally
sieb.free;
end;
SortTStrings(memo1.Lines, dupAccept);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
minZ, maxZ : integer;
minV, maxV : double;
begin
memo1.Clear;
minZ := StrToint(EditMinZ.Text);
maxz := StrToInt(EditMaxZ.Text);
minV := Strtofloat(EditMinV.Text);
maxV := Strtofloat(EditMaxV.Text);
BerechneAlles(minZ, maxZ, minV, maxV);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
// richtig vorbelegen, damit es keine Probleme mit dem Dezimalseparator gibt
EditMinV.Text := FloatToStr(0.0);
EditMaxV.Text := FloattoStr(100.0);
end;
end.
|
{
@name GradButton
@author Eugen Bolz
@lastchange 23.01.2011
@version 1.5
@thx to http://www.delphipraxis.net/topic67805_farbverlauf+berechnen.html
@license http://creativecommons.org/licenses/LGPL/2.1/
@wiki http://wiki.lazarus.freepascal.org/TGradButton
}
unit ugradbtn;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, graphics, LCLType,LResources,
LCLIntf ,Buttons, urotatebitmap, types, Menus, gradcustomcontrol;
type
TGradButton = class;
TDropDownMarkDirection = (mdUp, mdLeft, mdDown, mdRight);
TDropDownMarkPosition = (mpLeft, mpRight);
TTextAlignment = (taLeftJustify, taRightJustify, taCenter);
TBorderSide = (bsTopLine, bsBottomLine, bsLeftLine, bsRightLine);
TBorderSides = set of TBorderSide;
TGradientType = (gtHorizontal,gtVertical);
TGBBackgroundPaintEvent = procedure(Sender: TGradButton;
TargetCanvas: TCanvas; R: TRect; BState : TButtonState) of object;
{ TStateBitmap }
TStateBitmap = class
private
FBitmaps : Array of TBitmap;
function StateToInt(AState: TButtonState): integer;
function GetBitmap(State: TButtonState): TBitmap;
public
constructor Create;
destructor Destroy; override;
public
property Bitmap[State: TButtonState] : TBitmap read GetBitmap; default;
end;
{ TDropDownSettings }
TDropDownSettings = class(TPersistent)
private
FColor: TColor;
FMarkDirection: TDropDownMarkDirection;
FMarkPosition: TDropDownMarkPosition;
FOnlyOnMark: boolean;
FPopupMenu: TPopupMenu;
FPressedColor: TColor;
FShow: Boolean;
FSize: integer;
FNotify: TNotifyEvent;
FSplitButton: Boolean;
procedure SetColor(const AValue: TColor);
procedure SetMarkDirection(const AValue: TDropDownMarkDirection);
procedure SetMarkPosition(const AValue: TDropDownMarkPosition);
procedure SetOnlyOnMark(const AValue: boolean);
procedure SetPopupMenu(const AValue: TPopupMenu);
procedure SetPressedColor(const AValue: TColor);
procedure SetShow(const AValue: Boolean);
procedure SetSize(const AValue: integer);
procedure Notify;
procedure SetSplitButton(const AValue: Boolean);
public
constructor Create(ANotify: TNotifyEvent);
procedure AssignTo(Dest: TPersistent); override;
function IsPopupStored: boolean;
published
property Color : TColor read FColor write SetColor default clSilver;
property MarkDirection : TDropDownMarkDirection read FMarkDirection
write SetMarkDirection default mdDown;
property MarkPosition : TDropDownMarkPosition read FMarkPosition
write SetMarkPosition default mpRight;
property OnlyOnMark: boolean read FOnlyOnMark write SetOnlyOnMark;
property PopupMenu : TPopupMenu read FPopupMenu write SetPopupMenu;
property PressedColor: TColor read FPressedColor write SetPressedColor default clBlack;
property Show : Boolean read FShow write SetShow;
property Size: integer read FSize write SetSize default 8;
property SplitButton: Boolean read FSplitButton write SetSplitButton;
end;
{ TGradButton }
TGradButton = class(TGradCustomControl)
private
FDropDownSettings: TDropDownSettings;
FAutoHeight: Boolean;
FAutoHeightBorderSpacing: Integer;
FAutoWidthBorderSpacing: Integer;
FOnBorderBackgroundPaint: TGBBackgroundPaintEvent;
FRotateDirection : TRotateDirection;
FTextAlignment : TTextAlignment;
FButtonLayout: TButtonLayout;
FDropdownMarkRect, FDropdownMarkAreaRect: TRect;
FTextPoint, FGlyphPoint: TPoint;
FTextSize, FGlyphSize, FAutoSize : TSize;
FBackground, bm : TBitmap;
FBackgroundCaches, FBackgroundSplitCaches : TStateBitmap;
FRotatedGlyph : TRotatedGlyph;
FTextGlyphSpacing: Integer;
FGradientType : TGradientType;
FShowFocusBorder, FOnlyBackground,
FAutoWidth, FShowGlyph, FEnabled, FFocused : Boolean;
FBorderSides: TBorderSides;
FOnNormalBackgroundPaint, FOnHotBackgroundPaint,
FOnDownBackgroundPaint, FOnDisabledBackgroundPaint : TGBBackgroundPaintEvent;
procedure DrawDropDownArrow;
procedure PaintGradient(TrgCanvas: TCanvas; pr : TRect; AState: TButtonState);
procedure SetDropDownSettings(const AValue: TDropDownSettings);
procedure UpdateBackground;
procedure PaintBackground(AState: TButtonState; Normal: Boolean = true);
procedure ShowDropdownPopupMenu;
procedure DropDownSettingsChanged(Sender: TObject);
protected
FState, FOldState, FDropDownState: TButtonState;
FNormalBlend,FOverBlend : Extended;
FBaseColor, FNormalBlendColor, FOverBlendColor, FDisabledColor,
FBackgroundColor, FGlyphBackgroundColor, FClickColor: TColor;
FOwnerBackgroundDraw : Boolean;
function DropDownEnabled : Boolean;
procedure SetAutoHeight(const AValue: Boolean); virtual;
procedure SetAutoHeightBorderSpacing(const AValue: Integer); virtual;
procedure SetAutoWidthBorderSpacing(const AValue: Integer); virtual;
procedure InvPaint(StateCheck:Boolean=false);
procedure FontChanged(Sender: TObject); override;
procedure GlyphChanged(Sender: TObject); virtual;
function GetDropDownAreaSize : Integer;
procedure GetFocusContentRect(var TheRect: TRect; OnlyForFocus : Boolean);
procedure GetContentRect(var TheRect: TRect); virtual;
procedure GetContentRect(var TheRect: TRect; Sides: TBorderSides); overload; virtual;
procedure GetContentRect(var TheRect: TRect; Sides: TBorderSides;
AWidth: Integer; AHeight: Integer); overload; virtual;
function GetGlyph : TBitmap;
procedure SetEnabled(Value: Boolean); override;
procedure SetAutoWidth(const Value : Boolean); virtual;
procedure SetNormalBlend(const Value: Extended); virtual;
procedure SetOverBlend(const Value: Extended); virtual;
procedure SetBaseColor(const Value: TColor); virtual;
procedure SetNormalBlendColor(const Value: TColor); virtual;
procedure SetOverBlendColor(const Value: TColor); virtual;
procedure SetBackgroundColor(const Value: TColor); virtual;
procedure SetBorderSides(const Value: TBorderSides); virtual;
procedure SetOwnerBackgroundDraw(const Value: Boolean); virtual;
procedure SetGradientType(const Value: TGradientType); virtual;
procedure SetRotateDirection(const Value: TRotateDirection); virtual;
procedure SetShowGlyph(const Value: Boolean); virtual;
procedure SetGlyphBackgroundColor(const Value: TColor); virtual;
procedure SetTextAlignment(const Value: TTextAlignment); virtual;
procedure SetTextGlyphSpacing(const Value: Integer); virtual;
procedure SetButtonLayout(const Value: TButtonLayout); virtual;
procedure SetClickColor(const Value: TColor); virtual;
procedure SetDisabledColor(const Value: TColor); virtual;
procedure SetName(const Value: TComponentName); override;
procedure SetShowFocusBorder(const Value: Boolean); virtual;
procedure SetGlyph(const Value: TBitmap); virtual;
procedure TextChanged; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: integer;
KeepBase: boolean); override;
procedure Paint; override;
procedure _Paint(ACanvas: TCanvas); override;
procedure MouseEnter; override;
procedure MouseLeave; override;
procedure MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState;
X, Y: Integer); override;
procedure DoEnter; override;
procedure DoExit; override;
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
function GetBackground : TCanvas;
procedure Click; override;
function Focused: Boolean; override;
procedure UpdateButton;
procedure UpdatePositions;
function GetAutoWidth : Integer;
function GetAutoHeight : Integer;
class function GetControlClassDefaultSize: TSize; override;
published
property Action;
property Anchors;
property Align;
property BorderSpacing;
property Caption;
property Enabled;
property DropDownSettings: TDropDownSettings read FDropDownSettings
write SetDropDownSettings;
property PopupMenu;
property Font;
property Visible;
property OnClick;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnPaint;
property OnResize;
property OnStartDrag;
property DragMode;
property DragKind;
property DragCursor;
property TabOrder;
property TabStop;
property NormalBlend : Extended read FNormalBlend write SetNormalBlend;
property OverBlend : Extended read FOverBlend write SetOverBlend;
property BaseColor: TColor read FBaseColor write SetBaseColor;
property Color: TColor read FBaseColor write SetBaseColor;
property NormalBlendColor: TColor read FNormalBlendColor write SetNormalBlendColor;
property OverBlendColor: TColor read FOverBlendColor write SetOverBlendColor;
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor;
property AutoWidth : Boolean read FAutoWidth write SetAutoWidth default false;
property AutoHeight: Boolean read FAutoHeight write SetAutoHeight default false;
property BorderSides : TBorderSides read FBorderSides write SetBorderSides default [bsTopLine,bsBottomLine,bsLeftLine,bsRightLine];
property GradientType : TGradientType read FGradientType write SetGradientType default gtHorizontal;
property ShowFocusBorder : Boolean read FShowFocusBorder write SetShowFocusBorder;
property RotateDirection : TRotateDirection read FRotateDirection write SetRotateDirection default rdNormal;
property ButtonLayout : TButtonLayout read FButtonLayout write SetButtonLayout default blGlyphLeft;
property Glyph : TBitmap read GetGlyph write SetGlyph;
property ShowGlyph : Boolean read FShowGlyph write SetShowGlyph;
property GlyphBackgroundColor : TColor read FGlyphBackgroundColor write SetGlyphBackgroundColor;
property TextAlignment : TTextAlignment read FTextAlignment write SetTextAlignment default taCenter;
property TextGlyphSpacing : Integer read FTextGlyphSpacing write SetTextGlyphSpacing default 2;
property ClickColor : TColor read FClickColor write SetClickColor;
property DisabledColor : TColor read FDisabledColor write SetDisabledColor default clGray;
property OwnerBackgroundDraw : Boolean read FOwnerBackgroundDraw write SetOwnerBackgroundDraw;
property AutoWidthBorderSpacing : Integer read FAutoWidthBorderSpacing write SetAutoWidthBorderSpacing;
property AutoHeightBorderSpacing : Integer read FAutoHeightBorderSpacing write SetAutoHeightBorderSpacing;
property OnNormalBackgroundPaint : TGBBackgroundPaintEvent read FOnNormalBackgroundPaint write FOnNormalBackgroundPaint;
property OnHotBackgroundPaint : TGBBackgroundPaintEvent read FOnHotBackgroundPaint write FOnHotBackgroundPaint;
property OnDownBackgroundPaint : TGBBackgroundPaintEvent read FOnDownBackgroundPaint write FOnDownBackgroundPaint;
property OnDisabledBackgroundPaint : TGBBackgroundPaintEvent read FOnDisabledBackgroundPaint write FOnDisabledBackgroundPaint;
property OnBorderBackgroundPaint : TGBBackgroundPaintEvent read FOnBorderBackgroundPaint write FOnBorderBackgroundPaint;
end;
function ColorBetween(C1, C2 : TColor; blend:Extended):TColor;
function ColorsBetween(colors:array of TColor; blend:Extended):TColor;
function AlignItem(ItemLength, AreaLength,Spacing: Integer; ATextAlignment: TTextAlignment):Integer;
function IfThen(ATest, ValA: Boolean; ValB: Boolean = false): Boolean; overload;
function IfThen(ATest: Boolean; ValA, ValB: TRect): TRect; overload;
procedure Register;
implementation
uses
LCLProc, math;
procedure PaintArrow(ACanvas: TCanvas; ARect: TRect; ADirection: TDropDownMarkDirection; AColor: TColor);
var
Points : Array of TPoint;
ASize: TSize;
i: Integer;
begin
SetLength(Points, 3);
ASize := Size(ARect);
ASize.cx:= ASize.cx - 1;
ASize.cy:= ASize.cy - 1;
case ADirection of
mdUp:
begin
Points[0] := Point(0, ASize.cy);
Points[1] := Point(ASize.cx, ASize.cy);
Points[2] := Point(ASize.cx div 2, 0);
end;
mdDown:
begin
Points[0] := Point(0, 0);
Points[1] := Point(ASize.cx, 0);
Points[2] := Point(ASize.cx div 2, ASize.cy);
end;
mdLeft:
begin
Points[0] := Point(ASize.cx, 0);
Points[1] := Point(ASize.cx, ASize.cy);
Points[2] := Point(0, ASize.cy div 2);
end;
mdRight:
begin
Points[0] := Point(0, 0);
Points[1] := Point(0, ASize.cy);
Points[2] := Point(ASize.cx, ASize.cy div 2);
end;
end;
for i := 0 to 2 do
with Points[i] do
begin
Inc(X, ARect.Left);
Inc(Y, ARect.Top);
end;
ACanvas.Brush.Style:=bsSolid;
ACanvas.Brush.Color:=AColor;
ACanvas.Pen.Color:=AColor;
ACanvas.Polygon(Points);
SetLength(Points, 0);
end;
// Debug PaintRect
procedure PaintRect(ACanvas: TCanvas; ARect: TRect);
begin
with ACanvas do
begin
with ARect do
begin
Rectangle(Left, Top, Right, Bottom);
MoveTo(Left,Top);
LineTo(Right, Bottom);
MoveTo(Right, Top);
LineTo(Left, Bottom);
end;
end;
end;
function AlignItem(ItemLength, AreaLength,Spacing: Integer; ATextAlignment: TTextAlignment):Integer;
begin
case ATextAlignment of
taLeftJustify : Result := Spacing;
taRightJustify: begin
Result := AreaLength-ItemLength-Spacing;
end;
taCenter : begin
Result := (AreaLength div 2)-(ItemLength div 2);
end;
end;
end;
procedure TGradButton.SetShowFocusBorder(const Value: Boolean);
begin
FShowFocusBorder:=Value;
InvPaint;
end;
procedure TGradButton.SetGlyph(const Value: TBitmap);
begin
FRotatedGlyph.Bitmap := Value;
end;
procedure TGradButton.TextChanged;
begin
inherited TextChanged;
if FAutoWidth then
UpdateButton
else
UpdatePositions;
InvPaint;
end;
procedure TGradButton.SetName(const Value: TComponentName);
begin
if (Caption='') OR (Caption=Name) then
begin
Caption:=Value;
end;
inherited;
end;
function TGradButton.Focused: Boolean;
begin
FFocused:=FFocused OR (Inherited Focused);
Result := FFocused;
end;
procedure TGradButton.SetAutoWidth(const Value : Boolean);
begin
if FAutoWidth = Value then
Exit;
FAutoWidth := Value;
UpdateButton;
end;
procedure TGradButton.UpdatePositions;
var
tempTS,tempGS,Area : TSize;
Offset1, Offset2 :Integer;
tempBL : TButtonLayout;
DropDownAreaSize: TSize;
TheBackgroundRect: TRect;
begin
GetFocusContentRect(TheBackgroundRect, false);
Area := Size(TheBackgroundRect);
tempGS.cx:=0;
tempGS.cy:=0;
if FShowGlyph and not FRotatedGlyph.Empty then
begin
tempGS.cx:=FRotatedGlyph.Width;
tempGS.cy:=FRotatedGlyph.Height;
end;
tempTS := FBuffer.Canvas.TextExtent(Caption);
if FRotateDirection <> rdNormal then
begin
FTextSize.cx := tempTS.cy;
FTextSize.cy := tempTS.cx;
tempTS := FTextSize;
end
else
FTextSize := tempTS;
tempBL := FButtonLayout;
if FShowGlyph and not FRotatedGlyph.Empty then begin
case tempBL of
blGlyphLeft: begin
FGlyphPoint.x := AlignItem(tempGS.cx+FTextGlyphSpacing+tempTS.cx,Area.cx,4,FTextAlignment);
FGlyphPoint.y := AlignItem(tempGS.cy,Area.cy,0, taCenter);
FTextPoint.x := FGlyphPoint.x+tempGS.cx+FTextGlyphSpacing;
FTextPoint.y := AlignItem(tempTS.cy,Area.cy,0, taCenter);
end;
blGlyphRight: begin
//Glyph Right, Text Left
FTextPoint.x := AlignItem(tempTS.cx+FTextGlyphSpacing+tempGS.cx,Area.cx,4, FTextAlignment);
FTextPoint.y := AlignItem(tempTS.cy,Area.cy,0, taCenter);
FGlyphPoint.x := FTextPoint.x+tempTS.cx+FTextGlyphSpacing;
FGlyphPoint.y := AlignItem(tempGS.cy,Area.cy,0, taCenter);
end;
blGlyphTop: begin
//Glyph Top, Text Bottom
FGlyphPoint.x := AlignItem(tempGS.cx, Area.cx, 0, FTextAlignment);
FTextPoint.x := AlignItem(tempTS.cx, Area.cx, 0, FTextAlignment);
FGlyphPoint.y := AlignItem(tempGS.cy+FTextGlyphSpacing+tempTS.cy, Area.cy, 4, taCenter);
FTextPoint.y := FGlyphPoint.y+tempGS.cy+FTextGlyphSpacing;
end;
blGlyphBottom: begin
//Glyph Bottom, Text Top
FGlyphPoint.x := AlignItem(tempGS.cx, Area.cx, 0, FTextAlignment);
FTextPoint.x := AlignItem(tempTS.cx, Area.cx, 0, FTextAlignment);
FTextPoint.y := AlignItem(tempGS.cy+FTextGlyphSpacing+tempTS.cy, Area.cy, 4, taCenter);
FGlyphPoint.y := FTextPoint.y+tempTS.cy+FTextGlyphSpacing;
end;
end;
end else begin
FGlyphPoint.x := 0;
FGlyphPoint.y := 0;
FTextPoint.x := AlignItem(tempTS.cx,Area.cx,4, FTextAlignment);
FTextPoint.y := AlignItem(tempTS.cy,Area.cy,0, taCenter);
end;
FAutoSize.cx := Max(FGlyphPoint.x + FGlyphSize.cx, FTextPoint.x + FTextSize.cx);
FAutoSize.cy := Max(FGlyphPoint.y + FGlyphSize.cy, FTextPoint.y + FTextSize.cy);
FTextPoint.x := TheBackgroundRect.Left + FTextPoint.x;
FGlyphPoint.x := TheBackgroundRect.Left + FGlyphPoint.x;
if DropDownEnabled then
begin
FDropdownMarkRect.Top := AlignItem(FDropDownSettings.Size, Area.cy, 0, taCenter);
if not FDropDownSettings.SplitButton then
begin
Offset1 := IfThen(FDropDownSettings.MarkPosition<>mpLeft,
FTextSize.cx, -FDropDownSettings.Size - 2);
Offset2 := IfThen(FDropDownSettings.MarkPosition<>mpLeft,
FGlyphSize.cx, -FDropDownSettings.Size - 2);
FDropdownMarkRect.Left := IfThen(FDropDownSettings.MarkPosition=mpRight,
Max(FTextPoint.X+Offset1, FGlyphPoint.X+Offset2),
Min(FTextPoint.X+Offset1, FGlyphPoint.X+Offset2));
end
else
begin
Offset1 := GetDropDownAreaSize;
FDropdownMarkAreaRect.Top := 0;
FDropdownMarkAreaRect.Bottom := Height;
FDropdownMarkAreaRect.Left := Ifthen(FDropDownSettings.MarkPosition=mpRight, Width - Offset1);
FDropdownMarkAreaRect.Right := FDropdownMarkAreaRect.Left + Offset1;
DropDownAreaSize := Size(FDropdownMarkAreaRect);
FDropdownMarkRect.Left:=FDropdownMarkAreaRect.Left+
AlignItem(FDropDownSettings.Size, DropDownAreaSize.cx, 0, taCenter);
end;
FAutoSize.cy := Max(FAutoSize.cy, FDropdownMarkRect.Bottom);
FAutoSize.cx := Max(FAutoSize.cx, FDropdownMarkRect.Right);
if FDropDownSettings.SplitButton then
begin
DropDownAreaSize := Size(FDropdownMarkAreaRect);
FAutoSize.cx := Max(Area.cx, FAutoSize.cx)+DropDownAreaSize.cx;
end;
FDropdownMarkRect.Right := FDropdownMarkRect.Left + FDropDownSettings.Size;
FDropdownMarkRect.Bottom := FDropdownMarkRect.Top + FDropDownSettings.Size;
end;
FGlyphSize:=tempGS;
end;
function TGradButton.GetAutoWidth: Integer;
begin
Result := FAutoSize.cx + FAutoWidthBorderSpacing;
end;
function TGradButton.GetAutoHeight: Integer;
begin
Result := FAutoSize.cy + FAutoHeightBorderSpacing;
end;
class function TGradButton.GetControlClassDefaultSize: TSize;
begin
Result.CX := 80;
Result.CY := 25;
end;
procedure TGradButton.PaintBackground(AState: TButtonState; Normal: Boolean);
var
FOnTemp : TGBBackgroundPaintEvent;
TrgBitmap: TBitmap;
TempSides: TBorderSides;
TempRect: TRect;
begin
TempSides:= BorderSides;
if not FEnabled then AState:=bsDisabled;
if Normal then
TrgBitmap := FBackgroundCaches[AState]
else
TrgBitmap := FBackgroundSplitCaches[AState];
with TrgBitmap do
begin
Canvas.Font.Color := Self.Font.Color;
Canvas.Font := Self.Font;
if Normal then
begin
Width := Self.Width;
Height:= Self.Height;
end
else
begin
if not FDropDownSettings.SplitButton then Exit;
Width := GetDropDownAreaSize;
Height:= Self.Height;
if AState = bsUp then
if FDropDownSettings.MarkPosition = mpLeft then
begin
TempSides := TempSides - [bsRightLine]
end
else
begin
TempSides := TempSides - [bsLeftLine];
end;
end;
GetContentRect(TempRect, TempSides, Width, Height);
TempRect.Left := TempRect.Left
- IfThen(not Normal and (FDropDownSettings.MarkPosition = mpRight), 1);
if not Normal then
WriteLn('Paint: ', DbgS(TempRect));
if Self.Parent is TGradButton then
begin
Canvas.CopyRect(Rect(0, 0, Width, Height), (Self.Parent as TGradButton).GetBackground,
Rect(Left,Top,Left+Width,Top+Height));
end else begin
Canvas.Brush.Color:=FBackgroundColor;
Canvas.FillRect(0 , 0, Width, Height);
end;
if FOwnerBackgroundDraw AND (FOnBorderBackgroundPaint<>nil) then
begin
//FOnBorderBackgroundPaint(Self, Canvas, FBackgroundRect, AState);
end else begin
//Top
if (bsTopLine in TempSides) then
begin
Canvas.Pen.Color:=clBlack;
Canvas.Line(TempRect.Left,0,TempRect.Right+{$IFDEF DARWIN}1{$ELSE}0{$ENDIF},0);
Canvas.Pen.Color:=clWhite;
Canvas.Line(TempRect.Left,1,TempRect.Right+{$IFDEF DARWIN}1{$ELSE}0{$ENDIF},1);
end;
//Left
if (bsLeftLine in TempSides) then
begin
Canvas.Pen.Color:=clBlack;
Canvas.Line(0,TempRect.Top,0,TempRect.Bottom);
Canvas.Pen.Color:=clWhite;
Canvas.Line(1,TempRect.Top,1,TempRect.Bottom);
end;
//Right
if (bsRightLine in TempSides) then
begin
Canvas.Pen.Color:=clBlack;
Canvas.Line(Width-1,TempRect.Top,Width-1,TempRect.Bottom);
Canvas.Pen.Color:=clWhite;
Canvas.Line(Width-2,TempRect.Top,Width-2,TempRect.Bottom);
end;
//Bottom
if (bsBottomLine in TempSides) then
begin
Canvas.Pen.Color:=clBlack;
Canvas.Line(TempRect.Left,Height-1,TempRect.Right+{$IFDEF DARWIN}1{$ELSE}0{$ENDIF},Height-1);
Canvas.Pen.Color:=clWhite;
Canvas.Line(TempRect.Left,Height-2,TempRect.Right+{$IFDEF DARWIN}1{$ELSE}0{$ENDIF},Height-2);
end;
//TopLeft
if (bsTopLine in TempSides) AND (bsLeftLine in TempSides) then
Canvas.Pixels[1,1]:=clBlack;
//TopRight
if (bsTopLine in TempSides) AND (bsRightLine in TempSides) then
Canvas.Pixels[Width-2,1] := clBlack;
//BottomLeft
if (bsBottomLine in TempSides) AND (bsLeftLine in TempSides) then
Canvas.Pixels[1, Height-2]:=clBlack;
//BottomRight
if (bsBottomLine in TempSides) AND (bsRightLine in TempSides) then
Canvas.Pixels[Width-2,Height-2]:=clBlack;
end;
{if FOwnerBackgroundDraw then
begin
if not FEnabled then
FState := bsDisabled;
case FState of
bsUp: FOnTemp := FOnNormalBackgroundPaint;
bsHot:FOnTemp := FOnHotBackgroundPaint;
bsDown: FOnTemp := FOnDownBackgroundPaint;
bsDisabled: FOnTemp := FOnDisabledBackgroundPaint;
end;
if FOnTemp <> nil then
begin
FOnTemp(Self, Canvas, FBackgroundRect, FState);
end;
end else begin}
//PaintRect(Canvas, TempRect);
PaintGradient(Canvas, TempRect, AState);
//end;
end;
end;
procedure TGradButton.ShowDropdownPopupMenu;
var
lowerLeft: TPoint;
begin
if not DropDownEnabled then Exit;
lowerLeft := Point(0, Height);
lowerLeft := ControlToScreen(lowerLeft);
FDropDownSettings.PopupMenu.Popup(lowerLeft.X, lowerLeft.Y);
end;
procedure TGradButton.DropDownSettingsChanged(Sender: TObject);
begin
UpdateButton;
InvPaint();
end;
function TGradButton.DropDownEnabled: Boolean;
begin
Result := FDropDownSettings.Show and FDropDownSettings.IsPopupStored;
end;
procedure TGradButton.UpdateBackground;
var
FTempState : TButtonState;
begin
FTempState:= FState;
FEnabled:=true;
PaintBackground(bsUp);
PaintBackground(bsUp, false);
PaintBackground(bsHot);
PaintBackground(bsHot, false);
PaintBackground(bsDown);
PaintBackground(bsDown, false);
FEnabled:=false;
PaintBackground(bsUp);
PaintBackground(bsUp, false);
FEnabled:=Enabled;
FState:=FTempState;
InvPaint;
end;
function TGradButton.GetGlyph : TBitmap;
begin
Result := FRotatedGlyph.Bitmap;
end;
procedure TGradButton.SetDisabledColor(const Value: TColor);
begin
FDisabledColor:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetClickColor(const Value: TColor);
begin
FClickColor:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetButtonLayout(const Value: TButtonLayout);
begin
FButtonLayout:=Value;
UpdatePositions;
InvPaint;
end;
procedure TGradButton.SetGlyphBackgroundColor(const Value: TColor);
begin
FGlyphBackgroundColor:=Value;
//todo: see the desired behavior of GlyphBackgroundColor
//FRotatedGlyph.TransparentColor:=Value;
InvPaint;
end;
procedure TGradButton.SetTextAlignment(const Value: TTextAlignment);
begin
FTextAlignment:=Value;
UpdatePositions;
InvPaint;
end;
procedure TGradButton.SetTextGlyphSpacing(const Value: Integer);
begin
FTextGlyphSpacing:=Value;
UpdatePositions;
InvPaint;
end;
procedure TGradButton.SetEnabled(Value: Boolean);
begin
Inherited;
FEnabled:=Value;
InvPaint;
end;
procedure TGradButton.UpdateButton;
begin
UpdateBackground;
UpdatePositions;
end;
procedure TGradButton.SetShowGlyph(const Value: Boolean);
begin
if (FShowGlyph <> Value) AND FRotatedGlyph.IsBitmapStored then
begin
FShowGlyph:=Value;
UpdatePositions;
InvPaint;
end;
end;
procedure TGradButton.SetRotateDirection(const Value: TRotateDirection);
begin
if FRotateDirection = Value then
Exit;
FRotateDirection:=Value;
//Rotate and Cache
FRotatedGlyph.Direction:=FRotateDirection;
UpdatePositions;
UpdateButton;
InvPaint;
end;
procedure TGradButton.SetBackgroundColor(const Value: TColor);
begin
FBackgroundColor:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetGradientType(const Value: TGradientType);
begin
if FGradientType = Value then
Exit;
FGradientType:=Value;
UpdateBackground;
InvPaint;
end;
function TGradButton.GetBackground : TCanvas;
begin
FOnlyBackground:=true;
Paint;
FOnlyBackground:=false;
Result := FBackground.Canvas;
end;
procedure TGradButton.DrawDropDownArrow;
var
ArrowColor: Integer;
begin
ArrowColor := FDropDownSettings.Color;
if FDropDownState = bsDown then
ArrowColor:=FDropDownSettings.PressedColor;
PaintArrow(FBuffer.Canvas, FDropdownMarkRect, FDropDownSettings.FMarkDirection,
ArrowColor);
end;
procedure TGradButton.PaintGradient(TrgCanvas: TCanvas; pr: TRect;
AState: TButtonState);
var
r : Integer;
t1,t2,t3 : TColor;
begin
case AState of
bsHot,bsDown : begin
t3 := FOverBlendColor;
end;
else begin
t3 := FNormalBlendColor;
end;
end;
if AState = bsDown then begin
t1 := FClickColor;
end else if FEnabled then begin
t1 := FBaseColor;
end else begin
t1 := FDisabledColor;
t3 := FNormalBlendColor;
end;
t2 := ColorBetween(t1, t3, FNormalBlend);
if GradientType = gtHorizontal then
begin
if AState = bsDown then
begin
for r := (pr.Bottom)-1 downto pr.Top do
begin
if (r > (pr.Bottom/2)) then
begin
TrgCanvas.Pen.Color:= ColorBetween(t1,t2,FOverBlend);
end else begin
TrgCanvas.Pen.Color := ColorsBetween([t1,t2], 1.0-(r / pr.Bottom));
end;
TrgCanvas.Line(pr.Left,r,pr.Right{$IFDEF DARWIN}+1{$ENDIF},r);
end;
end else
for r := (pr.Bottom)-1 downto pr.Top do
begin
if (r <= (pr.Bottom/2)) then
begin
//WriteLn('R: ', r, ' M: ', Trunc(pr.Bottom/2));
TrgCanvas.Pen.Color:= ColorBetween(t1,t2,FOverBlend);
end else begin
TrgCanvas.Pen.Color := ColorsBetween([t1,t2], r / pr.Bottom);
end;
TrgCanvas.Line(pr.Left,r,pr.Right{$IFDEF DARWIN}+1{$ENDIF},r);
end;
end else begin
if AState = bsDown then
begin
for r := (pr.Right)-{$IFDEF DARWIN}0{$ELSE}1{$ENDIF} downto pr.Left do
begin
if (r >= (pr.Right/2)) then
begin
TrgCanvas.Pen.Color:= ColorBetween(t1,t2,FOverBlend);
end else begin
TrgCanvas.Pen.Color := ColorsBetween([t1,t2], 1.0-(r / pr.Right));
end;
TrgCanvas.Line(r,pr.Top,r,pr.Bottom);
end;
end else
for r := (pr.Right)-{$IFDEF DARWIN}0{$ELSE}1{$ENDIF} downto pr.Left do
begin
if (r <= (pr.Right/2)) then
begin
TrgCanvas.Pen.Color:= ColorBetween(t1,t2,FOverBlend);
end else begin
TrgCanvas.Pen.Color := ColorsBetween([t1,t2], r / pr.Right);
end;
TrgCanvas.Line(r,pr.Top,r,pr.Bottom);
end;
end;
end;
procedure TGradButton.SetDropDownSettings(const AValue: TDropDownSettings);
begin
if FDropDownSettings=AValue then exit;
FDropDownSettings.Assign(AValue);
FDropDownSettings.Notify;
end;
procedure TGradButton.SetAutoHeight(const AValue: Boolean);
begin
if FAutoHeight=AValue then exit;
FAutoHeight:=AValue;
UpdateButton;
end;
procedure TGradButton.SetAutoHeightBorderSpacing(const AValue: Integer);
begin
if FAutoHeightBorderSpacing=AValue then exit;
FAutoHeightBorderSpacing:=AValue;
UpdateButton;
end;
procedure TGradButton.SetAutoWidthBorderSpacing(const AValue: Integer);
begin
if FAutoWidthBorderSpacing=AValue then exit;
FAutoWidthBorderSpacing:=AValue;
UpdateButton;
end;
constructor TGradButton.Create(AOwner: TComponent);
begin
inherited;
FDropDownSettings := TDropDownSettings.Create(@DropDownSettingsChanged);
FBackgroundCaches := TStateBitmap.Create;
FBackgroundSplitCaches := TStateBitmap.Create;
FAutoWidthBorderSpacing:=15;
FAutoHeightBorderSpacing:=15;
FNormalBlend:=0.5;
FOverBlend:=0.653;
FBaseColor:=clBlue;
FNormalBlendColor:=clWhite;
FOverBlendColor:=clSilver;
FBackgroundColor:=clBtnFace;
FClickColor:=clBlue;
FDisabledColor:=clGray;
FEnabled:=true;
FAutoWidth:=false;
FAutoHeight:=false;
FOwnerBackgroundDraw := false;
FOnlyBackground:=false;
FShowFocusBorder:=true;
FRotateDirection:=rdNormal;
FTextAlignment:=taCenter;
FTextGlyphSpacing := 2;
TabStop:=true;
ControlStyle := ControlStyle + [csAcceptsControls];
DoubleBuffered:=true;
FBackground := TBitmap.Create;
with FBackground do
begin
Width:=Self.Width;
Height:=Self.Height;
end;
FRotatedGlyph := TRotatedGlyph.Create;
FRotatedGlyph.OnChange := @GlyphChanged;
FButtonLayout:=blGlyphLeft;
FGlyphBackgroundColor:=clWhite;
FBorderSides:=[bsTopLine,bsBottomLine,bsLeftLine,bsRightLine];
bm := TBitmap.Create;
bm.Canvas.Brush.Style := bsClear;
UpdateBackground;
Font.Color:=clWhite;
end;
destructor TGradButton.Destroy;
begin
FDropDownSettings.Free;
FBackgroundCaches.Free;
FBackgroundSplitCaches.Free;
//DebugLn('bm.Free');
bm.Free;
//DebugLn('FRotatedGlyph.Free');
FRotatedGlyph.Free;
//DebugLn('FBackground.Free');
FBackground.Free;
inherited;
end;
procedure TGradButton.ChangeBounds(ALeft, ATop, AWidth, AHeight: integer;
KeepBase: boolean);
begin
if FAutoWidth then
AWidth := GetAutoWidth;
if FAutoHeight then
AHeight := GetAutoHeight;
if (HasParent) then
begin
if FAutoWidth or FAutoHeight then
UpdateButton
else begin
UpdatePositions;
UpdateBackground;
end;
end;
inherited ChangeBounds(ALeft, ATop, AWidth, AHeight, KeepBase);
end;
procedure TGradButton.Paint;
begin
_Paint(FBuffer.Canvas);
Canvas.Draw(0,0, FBuffer);
end;
procedure TGradButton._Paint(ACanvas: TCanvas);
var
TextOffset : Integer;
tempState: TButtonState;
FocusRect: TRect;
begin
GetFocusContentRect(FocusRect, true);
FBackground.Width:=Width;
FBackground.Height:=Height;
ACanvas.Brush.Color:=clBlack;
ACanvas.FillRect(0,0,Width, Height);
if not FEnabled then
tempState := bsDisabled
else
tempState := FState;
ACanvas.Draw(0,0, FBackgroundCaches[tempState]);
if DropDownEnabled and FDropDownSettings.SplitButton then
begin
ACanvas.Brush.Style:=bsSolid;
ACanvas.Brush.Color:=FBackgroundColor;
ACanvas.FillRect(FDropdownMarkAreaRect);
ACanvas.Draw(FDropdownMarkAreaRect.Left, FDropdownMarkAreaRect.Top, FBackgroundSplitCaches[FDropDownState]);
end else
ACanvas.Brush.Style := bsClear;
TextOffset := IfThen(tempState = bsDown, 1);
DrawRotatedText(ACanvas, FTextPoint.x + TextOffset, FTextPoint.y + TextOffset,
FTextSize.cx, FTextSize.cy, Caption, FRotateDirection);
if FShowGlyph and FRotatedGlyph.IsBitmapStored then
begin
FRotatedGlyph.State := FState;
FRotatedGlyph.Draw(ACanvas, FGlyphPoint.x+TextOffset, FGlyphPoint.y+TextOffset);
end;
if not (csDesigning in ComponentState) then
if FFocused and FShowFocusBorder then
ACanvas.DrawFocusRect(RECT(FocusRect.Left+2, FocusRect.Top+2,
FocusRect.Right-2, FocusRect.Bottom-2));
if DropDownEnabled then
DrawDropDownArrow;
end;
procedure TGradButton.SetBorderSides(const Value: TBorderSides);
begin
FBorderSides:=Value;
UpdateBackground;
UpdatePositions;
InvPaint;
end;
procedure TGradButton.SetOwnerBackgroundDraw(const Value: Boolean);
begin
FOwnerBackgroundDraw:=Value;
if Value then
begin
UpdateBackground;
InvPaint;
end;
end;
procedure TGradButton.SetNormalBlend(const Value: Extended);
begin
FNormalBlend:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetOverBlend(const Value: Extended);
begin
FOverBlend:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetBaseColor(const Value: TColor);
begin
if FBaseColor = FClickColor then FClickColor := Value;
FBaseColor:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetNormalBlendColor(const Value: TColor);
begin
FNormalBlendColor:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.SetOverBlendColor(const Value: TColor);
begin
FOverBlendColor:=Value;
UpdateBackground;
InvPaint;
end;
procedure TGradButton.InvPaint(StateCheck:Boolean);
var
doIt : Boolean;
begin
doIt := true;
if StateCheck then
begin
doIt := (FOldState<>FState);
end;
if doIt then
begin
FOldState:=FState;
Invalidate;
end;
end;
procedure TGradButton.FontChanged(Sender: TObject);
begin
inherited FontChanged(Sender);
FBuffer.Canvas.Font := Font;
UpdatePositions;
end;
procedure TGradButton.GlyphChanged(Sender: TObject);
begin
UpdatePositions;
Invalidate;
end;
function TGradButton.GetDropDownAreaSize: Integer;
begin
Result := FAutoWidthBorderSpacing + FDropDownSettings.Size;
end;
procedure TGradButton.GetFocusContentRect(var TheRect: TRect;
OnlyForFocus: Boolean);
var
Offset1: LongInt;
TempSides: TBorderSides;
Split: Boolean;
begin
GetContentRect(TheRect);
Split := FDropDownSettings.SplitButton;
if DropDownEnabled then begin
Offset1 := IfThen(Split, GetDropDownAreaSize,
IfThen(not OnlyForFocus, FDropDownSettings.Size + 2));
if FDropDownSettings.MarkPosition = mpLeft then
begin
if Split then
begin
TempSides := BorderSides - [bsLeftLine];
GetContentRect(TheRect, TempSides);
end;
TheRect.Left := TheRect.Left + Offset1
end
else begin
if Split then
begin
TempSides := BorderSides - [bsRightLine];
GetContentRect(TheRect, TempSides);
end;
TheRect.Right := TheRect.Right - Offset1;
end;
end;
end;
procedure TGradButton.GetContentRect(var TheRect: TRect);
begin
GetContentRect(TheRect, BorderSides, Width, Height);
end;
procedure TGradButton.GetContentRect(var TheRect: TRect; Sides: TBorderSides);
begin
GetContentRect(TheRect, Sides, Width, Height);
end;
procedure TGradButton.GetContentRect(var TheRect: TRect; Sides: TBorderSides;
AWidth: Integer; AHeight: Integer);
begin
TheRect := Rect(0, 0,AWidth, AHeight);
//Top
TheRect.Top := IfThen(bsTopLine in Sides, 2);
//Left
TheRect.Left := IfThen(bsLeftLine in Sides, 2);
//Right
if (bsRightLine in Sides) then
begin
TheRect.Right := TheRect.Right-{$IFDEF windows}2{$ELSE}3{$ENDIF};
end;
//Bottom
if (bsBottomLine in Sides) then
begin
TheRect.Bottom := TheRect.Bottom - 2;
end;
end;
procedure TGradButton.DoEnter;
begin
//FState:=bsHot;
FFocused:=true;
InvPaint;
inherited;
end;
procedure TGradButton.KeyUp(var Key: Word; Shift: TShiftState);
begin
if Key in [VK_RETURN, VK_SPACE] then
inherited Click;
inherited;
end;
procedure TGradButton.DoExit;
begin
FState:=bsUp;
FDropDownState:=bsUp;
FFocused:=false;
InvPaint;
inherited;
end;
procedure TGradButton.MouseEnter;
begin
inherited;
{if FState<>bsDown then
begin
if not FDropDownSettings.SplitButton then
FState:=bsHot;
InvPaint(true);
end; }
end;
procedure TGradButton.MouseMove(Shift: TShiftState;
X, Y: Integer);
var
TempPoint: TPoint;
function ShiftToState: TButtonState;
begin
if ssLeft in Shift then
Result := bsDown
else
Result := bsHot;
end;
begin
TempPoint := Point(X, Y);
if FDropDownSettings.SplitButton then
begin
FDropDownState:= bsUp;
FState:=bsUp;
if PtInRect(FDropdownMarkAreaRect, TempPoint) then
FDropDownState:= ShiftToState
else
if PtInRect(Rect(0,0,Width, Height), TempPoint) then
FState:= ShiftToState;
end
else
begin
FState:=ShiftToState;
end;
InvPaint;
//inherited MouseMove calls OnMouseMove
inherited MouseMove(Shift, X, Y);
end;
procedure TGradButton.MouseLeave;
begin
inherited;
//WriteLn('MouseLeave');
FDropDownState:= bsUp;
FState:=bsUp;
//FFocused:=false;
InvPaint;
end;
procedure TGradButton.Click;
begin
//inherited;
end;
procedure TGradButton.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
TempPoint : TPoint;
TempRect: TRect;
begin
TempPoint:= Point(X,Y);
TempRect := IfThen(FDropDownSettings.SplitButton, FDropdownMarkAreaRect, FDropdownMarkRect);
if PtInRect(TempRect, TempPoint) then
begin
FState := bsUp;
FDropDownState := bsDown;
InvPaint;
end
else
begin
if PtInRect(Rect(0,0,Width,Height),TempPoint) then
begin
FState:=bsDown;
InvPaint;
end else begin
FState:=bsUp;
FFocused:=false;
if Assigned(PopupMenu) then
PopupMenu.Close;
InvPaint;
end;
FDropDownState:=bsUp;
end;
inherited;
end;
procedure TGradButton.MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
TempPoint : TPoint;
TempRect: TRect;
begin
TempPoint:= Point(X,Y);
TempRect := IfThen(FDropDownSettings.SplitButton, FDropdownMarkAreaRect, FDropdownMarkRect);
if PtInRect(TempRect, TempPoint) then
begin
if not FDropDownSettings.SplitButton then
FState := bsHot;
FDropDownState := bsHot;
InvPaint;
if Button = mbLeft then
ShowDropdownPopupMenu;
end
else
begin
if PtInRect(Rect(0,0,Width,Height),TempPoint) then
begin
FState:=bsHot;
InvPaint;
if Button = mbLeft then
inherited Click; //Faster, than the Overrided Click procedure
end
else
begin
FState := bsUp;
FFocused:=false;
InvPaint;
end;
FDropDownState:=bsUp;
InvPaint;
inherited;
end;
end;
{ TDropDownSettings }
procedure TDropDownSettings.SetMarkPosition(const AValue: TDropDownMarkPosition);
begin
if FMarkPosition=AValue then exit;
FMarkPosition:=AValue;
Notify;
end;
procedure TDropDownSettings.SetMarkDirection(
const AValue: TDropDownMarkDirection);
begin
if FMarkDirection=AValue then exit;
FMarkDirection:=AValue;
Notify;
end;
procedure TDropDownSettings.SetColor(const AValue: TColor);
begin
if FColor=AValue then exit;
FColor:=AValue;
Notify;
end;
procedure TDropDownSettings.SetOnlyOnMark(const AValue: boolean);
begin
if FOnlyOnMark=AValue then exit;
FOnlyOnMark:=AValue;
Notify;
end;
procedure TDropDownSettings.SetPopupMenu(const AValue: TPopupMenu);
begin
if FPopupMenu=AValue then exit;
FPopupMenu:=AValue;
Notify;
end;
procedure TDropDownSettings.SetPressedColor(const AValue: TColor);
begin
if FPressedColor=AValue then exit;
FPressedColor:=AValue;
Notify;
end;
procedure TDropDownSettings.SetShow(const AValue: Boolean);
begin
if FShow=AValue then exit;
FShow:=AValue;
Notify;
end;
procedure TDropDownSettings.SetSize(const AValue: integer);
begin
if FSize=AValue then exit;
FSize:=AValue;
Notify;
end;
procedure TDropDownSettings.Notify;
begin
if FNotify <> nil then
FNotify(Self);
end;
procedure TDropDownSettings.SetSplitButton(const AValue: Boolean);
begin
if FSplitButton=AValue then exit;
FSplitButton:=AValue;
Notify;
end;
constructor TDropDownSettings.Create(ANotify: TNotifyEvent);
begin
FNotify := ANotify;
FColor:= clSilver;
FPressedColor:= clBlack;
FMarkDirection:= mdDown;
FMarkPosition:= mpRight;
FOnlyOnMark:= false;
FShow:= false;
FSize:= 8;
end;
procedure TDropDownSettings.AssignTo(Dest: TPersistent);
begin
if Dest is TDropDownSettings then
begin
with TDropDownSettings(Dest) do
begin
FNotify := Self.FNotify;
FColor:= Self.FColor;
FPressedColor:=Self.FPressedColor;
FMarkDirection:=Self.FMarkDirection;
FMarkPosition:=Self.FMarkPosition;
FOnlyOnMark:=Self.FOnlyOnMark;
FShow:=Self.FShow;
FSize:=Self.FSize;
end;
end
else
inherited;
end;
function TDropDownSettings.IsPopupStored: boolean;
begin
Result := FPopupMenu <> nil;
end;
{ TStateBitmap }
function TStateBitmap.StateToInt(AState: TButtonState): integer;
begin
case AState of
bsUp: Result := 0;
bsDown: Result := 1;
bsHot: Result := 2;
else Result := 3;
end;
end;
function TStateBitmap.GetBitmap(State: TButtonState): TBitmap;
begin
Result := FBitmaps[StateToInt(State)];
end;
constructor TStateBitmap.Create;
var
i: Integer;
begin
SetLength(FBitmaps, 4);
for i := 0 to 3 do
FBitmaps[i] := TBitmap.Create;
end;
destructor TStateBitmap.Destroy;
var
i: Integer;
begin
for i := 0 to 3 do
FBitmaps[i].Free;
SetLength(FBitmaps, 0);
inherited Destroy;
end;
//Thx to: http://www.delphipraxis.net/topic67805_farbverlauf+berechnen.html
function ColorBetween(C1, C2 : TColor; blend:Extended):TColor;
var
r, g, b : Byte;
y1, y2 : Byte;
begin
C1 := ColorToRGB(C1);
C2 := ColorToRGB(C2);
y1 := Red(C1);
y2 := Red(C2);
r := Round(y1 + (y2-y1)*blend);
y1 := Green(C1);
y2 := Green(C2);
g := Round(y1 + (y2-y1)*blend);
y1 := Blue(C1);
y2 := Blue(C2);
b := Round(y1 + (y2-y1)*blend);
Result := RGBToColor(r, g, b);
end;
// Farbe zwischen beliebig vielen vorgegebenen Farbwerten berechnen
function ColorsBetween(colors:array of TColor; blend:Extended):TColor;
var
a : Integer;
faktor : Extended;
begin
if Length(colors) < 2 then
raise Exception.Create('ColorsBetween() at least 2 Colors required');
if blend <= 0.0 then
Result := colors[0]
else if blend >= 1.0 then
Result := colors[High(colors)]
else
begin
a := Trunc(High(colors) * blend);
faktor := 1.0 / High(colors);
Result := ColorBetween(colors[a], colors[a+1], (blend-(a * faktor)) / faktor);
end;
end;
function IfThen(ATest, ValA: Boolean; ValB: Boolean): Boolean;
begin
if ATest then
Result := ValA
else
Result := ValB;
end;
function IfThen(ATest: Boolean; ValA, ValB: TRect): TRect;
begin
if ATest then
Result := ValA
else
Result := ValB;
end;
procedure Register;
begin
RegisterComponents('Misc',[TGradButton]);
end;
initialization
{$I tgradbutton.lrs}
end.
|
unit Mat.ProjectUnitParser;
interface
uses
System.Classes, System.SysUtils, System.IOUtils,
System.Generics.Collections;
type
// Class for Unit file parsing.
TUnitStructFile = class
private
FUnitFileName: string;
FUnitPath: string;
FFormName: string;
FUsesList: TStringList;
FTypesList: TStringList;
FLinesCount: integer;
FIsPointersDetected: boolean;
FisUnicodeDetected: boolean;
FIs32BitSupport: boolean;
FIs64BitSupport: boolean;
FIsAssemblerDetected: boolean;
public
property IsPointersDetected: boolean read FIsPointersDetected
write FIsPointersDetected;
property IsUnicodeDetected: boolean read FisUnicodeDetected
write FisUnicodeDetected;
property Is32BitSupport: boolean read FIs32BitSupport
write FIs32BitSupport;
property Is64BitSupport: boolean read FIs64BitSupport
write FIs64BitSupport;
property IsAssemblerDetected: boolean read FIsAssemblerDetected
write FIsAssemblerDetected;
constructor Create;
destructor Destroy; override;
property UnitFileName: string read FUnitFileName write FUnitFileName;
property UnitPath: string read FUnitPath write FUnitPath;
property FormName: string read FFormName write FFormName;
property LinesCount: integer read FLinesCount write FLinesCount;
procedure ParseBlockUses(const ABlock: string;
var ARowUsesList: TStringList);
procedure ParseBlockType(const ABlock: string;
var ARowTypesList: TStringList);
public
procedure ParseTypes(const AFilePath: string;
var ATypesList: TStringList);
end;
TUnitStructList = class(TList<TUnitStructFile>)
public
function ParseFile(const AFilePath: string): TUnitStructFile;
procedure ParseDirectory(const ADirectory: string;
AIsRecursively: boolean);
end;
implementation
uses Mat.Constants, Mat.AnalysisProcessor;
constructor TUnitStructFile.Create;
begin
FUsesList := TStringList.Create;
FTypesList := TStringList.Create;
FIsPointersDetected := false;
FisUnicodeDetected := false;
FIs32BitSupport := false;
FIs64BitSupport := false;
FIsAssemblerDetected := false;
end;
destructor TUnitStructFile.Destroy;
begin
FUsesList.Free;
inherited;
end;
function TUnitStructList.ParseFile(const AFilePath: string): TUnitStructFile;
var
LFileData: TStringList;
i: integer;
LParsingStarted: boolean;
LBlock, LRow: string;
LRowUsesList, LRowTypesList: TStringList;
begin
LParsingStarted := false;
LBlock := '';
LRowUsesList := nil;
LFileData := nil;
Result := nil;
try
LFileData := TStringList.Create;
LRowUsesList := TStringList.Create;
LRowTypesList := TStringList.Create;
if TFile.Exists(AFilePath) then
begin
LFileData.LoadFromFile(AFilePath, TEncoding.ANSI);
Result := TUnitStructFile.Create;
Result.UnitPath := AFilePath;
Result.UnitFileName := TPath.GetFileNameWithoutExtension(AFilePath);
Result.FLinesCount := LFileData.Count;
for i := 0 to Pred(LFileData.Count) do
begin
if Result.FIsAssemblerDetected = false then
Result.FIsAssemblerDetected :=
FAnalysisProcessor.CheckStringPresent(ASM_SEARCH_STRING,
LFileData[i].ToLower);
if Result.FIsPointersDetected = false then
Result.FIsPointersDetected :=
FAnalysisProcessor.CheckPointerPresent(LFileData[i].ToLower);
if Pos(LFileData[i].ToLower, USES_SEARCH_STRING) > 0 then
LParsingStarted := True;
if LParsingStarted then
begin
LBlock := LBlock + LFileData[i] + Mat.Constants.CRLF;
if LFileData[i].IndexOf(';') > 0 then
LParsingStarted := false;
end;
if (not LParsingStarted) and (not LBlock.IsEmpty) then
begin
Result.ParseBlockUses(LBlock, LRowUsesList);
for LRow in LRowUsesList do
FAnalysisProcessor.UsesList.Add(LRow);
LBlock := '';
end;
end;
for i := 0 to Pred(LFileData.Count) do
begin
if Pos(LFileData[i].ToLower, TYPE_SEARCH_STRING) = 1 then
LParsingStarted := True;
if LParsingStarted then
begin
LBlock := LBlock + LFileData[i] + Mat.Constants.CRLF;
if Pos(IMPLEMENTATION_SEARCH_STRING, LFileData[i]) > 0 then
LParsingStarted := false;
end;
if (not LParsingStarted) and (not LBlock.IsEmpty) then
begin
Result.ParseBlockType(LBlock, LRowTypesList);
for LRow in LRowTypesList do
FAnalysisProcessor.TypesList.Add(LRow);
LBlock := '';
end;
end;
// Result.ParseTypes(AFilePath, LTypeInfo);
end;
finally
LRowUsesList.Free;
LRowTypesList.Free;
LFileData.Free
end;
end;
procedure TUnitStructFile.ParseBlockType(const ABlock: string;
var ARowTypesList: TStringList);
begin
// ShowMessage(ABlock);
end;
procedure TUnitStructList.ParseDirectory(const ADirectory: string;
AIsRecursively: boolean);
var
LFiles: TArray<String>;
LDirectories: TArray<String>;
LCurrentPath: string;
LUsf: TUnitStructFile;
begin
if AIsRecursively then
begin
LDirectories := TDirectory.GetDirectories(ADirectory);
for LCurrentPath in LDirectories do
ParseDirectory(LCurrentPath, AIsRecursively);
end;
LFiles := TDirectory.GetFiles(ADirectory, PAS_EXT_AST);
for LCurrentPath in LFiles do
begin
FAnalysisProcessor.ProjectUnitsList.Add
(TPath.GetFileNameWithoutExtension(LCurrentPath).ToLower);
LUsf := ParseFile(LCurrentPath);
Add(LUsf);
end;
end;
procedure TUnitStructFile.ParseBlockUses(const ABlock: string;
var ARowUsesList: TStringList);
var
TempStr: string;
P: PChar;
NewStr: string;
Removing: boolean;
RemovingReasonIndex: integer;
begin
RemovingReasonIndex := 0;
ARowUsesList.Clear;
Removing := false;
NewStr := '';
TempStr := ABlock.Trim;
if Pos(TempStr, USES_SEARCH_STRING) = 0 then
TempStr := TempStr.Substring(4).Trim;
P := PChar(TempStr);
while (P^ <> #0) do
begin
if (not Removing) and (P^ = '{') then
begin
RemovingReasonIndex := 1;
Removing := True;
end;
if (not Removing) and (P^ = ';') then
begin
RemovingReasonIndex := 2;
Removing := True;
end;
if (not Removing) and (P^ = '/') and ((P + 1)^ = '/') then
begin
RemovingReasonIndex := 3;
Removing := True;
end;
if (not Removing) and (P^ = '(') and ((P + 1)^ = '*') then
begin
RemovingReasonIndex := 4;
Removing := True;
end;
if not Removing then
NewStr := NewStr + P^;
if (P^ = '}') and (RemovingReasonIndex = 1) then
Removing := false;
if (P^ = ';') and (RemovingReasonIndex = 2) then
Removing := false;
if ((P^ = #10) or (P^ = #13)) and (RemovingReasonIndex = 3) then
Removing := false;
if ((P^ = ')') and ((P - 1)^ = '*')) and (RemovingReasonIndex = 4) then
Removing := false;
Inc(P)
end;
TempStr := StringReplace(NewStr, ' ', '', [rfReplaceAll]);
ARowUsesList.DelimitedText := TempStr;
end;
procedure TUnitStructFile.ParseTypes(const AFilePath: string;
var ATypesList: TStringList);
var
LRowTypesList: TStringList;
LFileData: TStringList;
i: integer;
LParsingStarted: boolean;
LBlock, LRow: string;
begin
LParsingStarted := false;
LBlock := '';
LRowTypesList := nil;
LFileData := nil;
try
LFileData := TStringList.Create;
LRowTypesList := TStringList.Create;
if TFile.Exists(AFilePath) then
begin
LFileData.LoadFromFile(AFilePath, TEncoding.ANSI);
for i := 0 to Pred(LFileData.Count) do
begin
if Pos(LFileData[i].ToLower, TYPE_SEARCH_STRING) = 1 then
LParsingStarted := True;
if LParsingStarted then
begin
LBlock := LBlock + LFileData[i] + Mat.Constants.CRLF;
if Pos(IMPLEMENTATION_SEARCH_STRING, LFileData[i]) > 0 then
LParsingStarted := false;
end;
if (not LParsingStarted) and (not LBlock.IsEmpty) then
begin
LBlock := '';
for LRow in LRowTypesList do
ATypesList.Add(LRow.ToLower);
end;
end;
end;
finally
LRowTypesList.Free;
LFileData.Free
end;
end;
end.
|
unit Redefined.Pascal.Win32.NetworkAccess;
{ ***************************************************************************
Copyright (c) 2015-2018 Enrique Fuentes
Unit : Redefined NetworkAccess
Description : Windows Networking Info and Scrapping methods
Author : Turric4n
Version : 1.0
Created : 11/07/2017
Modified : 09/10/2017
ARCH : x86 & x86/64
SO : NT4.0 or better
Unit Dependencies : Quick.Network
***************************************************************************
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.
*************************************************************************** }
interface
uses
SysUtils, Classes, Windows, Registry, Quick.Network, IPtypes, Winapi.Winsock2;
{
IsWrongIP : testing if IP address is valid
IPAddrToName: Get Machines name from IP address
MACAddress : MAC address;
IPAddress : IP address;
DefaultUser : User name;
ComputerName: Computer name;
DNSServers : available DNS servers;
NWComputers : available Machines on network NETBIOS;
GetNWCompARP : available machines on newtwork by Ip/Name resolution;
DomainName : domain name;
InternetConnected: Internet connection type(None, Proxy, Dialup);
}
const
MAX_HOSTNAME_LEN = 128;
MAX_DOMAIN_NAME_LEN = 128;
MAX_SCOPE_ID_LEN = 256;
cERROR_BUFFER_TOO_SMALL = 603;
cRAS_MaxEntryName = 256;
cRAS_MaxDeviceName = 128;
cRAS_MaxDeviceType = 16;
INTERNET_CONNECTION_MODEM = 1;
INTERNET_CONNECTION_LAN = 2;
INTERNET_CONNECTION_PROXY = 4;
INTERNET_CONNECTION_MODEM_BUSY = 8;
MAX_INTERFACE_NAME_LEN = 256;
MAXLEN_PHYSADDR = 8;
MAXLEN_IFDESCR = 256;
MIB_IF_TYPE_OTHER = 1;
MIB_IF_TYPE_ETHERNET = 6;
MIB_IF_TYPE_TOKENRING = 9;
MIB_IF_TYPE_FDDI = 15;
MIB_IF_TYPE_PPP = 23;
MIB_IF_TYPE_LOOPBACK = 24;
MIB_IF_TYPE_SLIP = 28;
type
ERasError = class(Exception);
HRASConn = DWORD;
PRASConn = ^TRASConn;
TRASConn = record
dwSize: DWORD;
rasConn: HRASConn;
szEntryName: array[0..cRAS_MaxEntryName] of Char;
szDeviceType: array[0..cRAS_MaxDeviceType] of Char;
szDeviceName: array [0..cRAS_MaxDeviceName] of Char;
end;
TRasEnumConnections = function(RASConn: PrasConn; { buffer to receive Connections data }
var BufSize: DWORD; { size in bytes of buffer }
var Connections: DWORD { number of Connections written to buffer }
): Longint;
stdcall;
TConnectionType = (Modem, Lan, Proxy, ModemBuzy, None);
SERVER_INFO_503 = record
sv503_sessopens : Integer;
sv503_sessvcs : Integer;
sv503_opensearch : Integer;
sv503_sizreqbuf : Integer;
sv503_initworkitems : Integer;
sv503_maxworkitems : Integer;
sv503_rawworkitems : Integer;
sv503_irpstacksize : Integer;
sv503_maxrawbuflen : Integer;
sv503_sessusers : Integer;
sv503_sessconns : Integer;
sv503_maxpagedmemoryusage : Integer;
sv503_maxnonpagedmemoryusage : Integer;
sv503_enablesoftcompat :BOOL;
sv503_enableforcedlogoff :BOOL;
sv503_timesource :BOOL;
sv503_acceptdownlevelapis :BOOL;
sv503_lmannounce :BOOL;
sv503_domain : PWideChar;
sv503_maxcopyreadlen : Integer;
sv503_maxcopywritelen : Integer;
sv503_minkeepsearch : Integer;
sv503_maxkeepsearch : Integer;
sv503_minkeepcomplsearch : Integer;
sv503_maxkeepcomplsearch : Integer;
sv503_threadcountadd : Integer;
sv503_numblockthreads : Integer;
sv503_scavtimeout : Integer;
sv503_minrcvqueue : Integer;
sv503_minfreeworkitems : Integer;
sv503_xactmemsize : Integer;
sv503_threadpriority : Integer;
sv503_maxmpxct : Integer;
sv503_oplockbreakwait : Integer;
sv503_oplockbreakresponsewait : Integer;
sv503_enableoplocks : BOOL;
sv503_enableoplockforceclose : BOOL;
sv503_enablefcbopens : BOOL;
sv503_enableraw : BOOL;
sv503_enablesharednetdrives : BOOL;
sv503_minfreeconnections : Integer;
sv503_maxfreeconnections : Integer;
end;
PSERVER_INFO_503 = ^SERVER_INFO_503;
PNetResourceArray = ^TNetResourceArray;
TNetResourceArray = array[0..100] of TNetResource;
// TIPAddressString - store an IP address or mask as dotted decimal string
PIPAddressString = ^TIPAddressString;
PIPMaskString = ^TIPAddressString;
TIPAddressString = record
_String: array[0..(4 * 4) - 1] of Char;
end;
TIPMaskString = TIPAddressString;
// TIPAddrString - store an IP address with its corresponding subnet mask,
// both as dotted decimal strings
PIPAddrString = ^TIPAddrString;
TIPAddrString = packed record
Next: PIPAddrString;
IpAddress: TIPAddressString;
IpMask: TIPMaskString;
Context: DWORD;
end;
// FIXED_INFO - the set of IP-related information which does not depend on DHCP
PFixedInfo = ^TFixedInfo;
TFixedInfo = packed record
HostName: array[0..MAX_HOSTNAME_LEN + 4 - 1] of Char;
DomainName: array[0..MAX_DOMAIN_NAME_LEN + 4 - 1] of Char;
CurrentDnsServer: PIPAddrString;
DnsServerList: TIPAddrString;
NodeType: UINT;
ScopeId: array[0..MAX_SCOPE_ID_LEN + 4 - 1] of Char;
EnableRouting,
EnableProxy,
EnableDns: UINT;
end;
PULONG = ^ULONG;
IP_ADDRESS_STRING = array[1..16] of Char;
IP_MASK_STRING = array[1..16] of Char;
PIP_ADDR_STRING = ^TIP_ADDR_STRING;
TIP_ADDR_STRING = record
Next: PIP_ADDR_STRING;
IpAddress: IP_ADDRESS_STRING;
IpMask: IP_MASK_STRING;
Context: DWORD;
end;
PFIXED_INFO = ^TFIXED_INFO;
TFIXED_INFO = record
HostName: array[1..MAX_HOSTNAME_LEN + 4] of Char;
DomainName: array[1..MAX_DOMAIN_NAME_LEN + 4] of Char;
CurrentDnsServer: PIP_ADDR_STRING;
DnsServerList: TIP_ADDR_STRING;
NodeType: UINT;
ScopeId: array[1..MAX_SCOPE_ID_LEN + 4] of Char;
EnableRouting: UINT;
EnableProxy: UINT;
EnableDns: UINT;
end;
PMIB_IPADDRROW = ^TMIB_IPADDRROW;
TMIB_IPADDRROW = packed record
dwAddr: DWORD;
dwIndex: DWORD;
dwMask: DWORD;
dwBCastAddr: DWORD;
dwReasmSize: DWORD;
unused1: SmallInt;
wType: SmallInt;
end;
PMIB_IPADDRTABLE = ^TMIB_IPADDRTABLE;
TMIB_IPADDRTABLE = record
dwNumEntries: DWORD;
table: array[0..0] of TMIB_IPADDRROW;
end;
PMIB_IFROW = ^TMIB_IFROW;
TMIB_IFROW = record
wszName: array[1..MAX_INTERFACE_NAME_LEN] of WCHAR;
dwIndex: DWORD;
dwType: DWORD;
dwMtu: DWORD;
dwSpeed: DWORD;
dwPhysAddrLen: DWORD;
bPhysAddr: array[1..MAXLEN_PHYSADDR] of Byte;
dwAdminStatus: DWORD;
dwOperStatus: DWORD;
dwLastChange: DWORD;
dwInOctets: DWORD;
dwInUcastPkts: DWORD;
dwInNUcastPkts: DWORD;
dwInDiscards: DWORD;
dwInErrors: DWORD;
dwInUnknownProtos: DWORD;
dwOutOctets: DWORD;
dwOutUcastPkts: DWORD;
dwOutNUcastPkts: DWORD;
dwOutDiscards: DWORD;
dwOutErrors: DWORD;
dwOutQLen: DWORD;
dwDescrLen: DWORD;
bDescr: array[1..MAXLEN_IFDESCR] of Byte;
end;
TDiscoveryCallback = reference to procedure(const ComputerName : string);
TNetWorkInfo = class
private
fcurrentworkers : Integer;
function GetMAC: string;
function GetIP: string;
function GetUser: string;
function GetCompName: string;
function GetDNSServ: TStringList;
function GetNWComp: TStringList;
function GetDN: String;
function GetCIDR : string;
function GetIntConnected: TConnectionType;
function GetMask: string;
function GetNetworkProperties(Adapter : Integer) : TMIB_IPADDRROW;
procedure OnGetComputerTerminated(aSender : TObject);
protected
function Get_MACAddress: string;
function GetIPAddress: String;
function GetDefaultNetWareUserName: string;
function GetDefaultComputerName: string;
procedure GetDNSServers(AList: TStringList);
function CreateNetResourceList(ResourceType: DWord; NetResource: PNetResource; out Entries: DWord; out List: PNetResourceArray): Boolean;
procedure ScanNetworkResources(ResourceType, DisplayType: DWord; List: TStrings);
function GetDomainName : string;
function InternetconnectionType: TConnectionType;
function RasConnectionCount : Integer;
public
function IsWrongIP(Ip: string): Boolean;
function IPAddrToName(IPAddr: string): string;
procedure GetNWCompARP(CallBack : TDiscoveryCallback);
property CIDR : string read GetCIDR;
property MACAddress : string read GetMAC;
property Mask : string read GetMask;
property IPAddress : string read GetIP;
property DefaultUser : string read GetUser;
property ComputerName: string read GetCompName;
property DNSServers : TStringList read GetDNSServ;
property DomainName : String read GetDN;
property InternetConnected: TConnectionType read GetIntConnected;
published
end;
TDiscoveryWorker = class(TThread)
private
fCurrentIP : string;
fCallback : TDiscoveryCallback;
public
constructor Create(CreateSuspended: Boolean; CurrentIP : string; Callback : TDiscoveryCallback);
procedure Execute; override;
end;
function GetNetworkParams(pFixedInfo: PFixedInfo; pOutBufLen: PULONG): DWORD; stdcall;
function NetServerGetInfo(serverName : PWideChar; level : Integer;var bufptr : Pointer) : Cardinal; stdcall; external 'NETAPI32.DLL';
function NetApiBufferFree(buffer : Pointer) : Cardinal; stdcall; external 'NETAPI32.DLL';
function InternetGetConnectedState(lpdwFlags: LPDWORD;dwReserved: DWORD): BOOL; stdcall; external 'WININET.DLL';
implementation
uses ActiveX, NB30;
const
{$IFDEF MSWINDOWS}
iphlpapidll = 'iphlpapi.dll';
{$ENDIF}
Const
IFF_UP = $00000001; //* Interface is up */
IFF_BROADCAST = $00000002; //* Broadcast is supported */
IFF_LOOPBACK = $00000004; //* this is loopback interface */
IFF_POINTTOPOINT = $00000008; //*this is point-to-point interface*/
IFF_MULTICAST = $00000010; //* multicast is supported */
function GetNetworkParams; external iphlpapidll Name 'GetNetworkParams';
function GetIpAddrTable(IpAddrTable: PMIB_IPADDRTABLE; pdwSize: PULONG;
Order: BOOL): DWORD; stdcall; external 'iphlpapi.dll' name 'GetIpAddrTable';
function GetIfEntry(pIfRow: PMIB_IFROW): DWORD;
stdcall; external 'iphlpapi.dll' name 'GetIfEntry';
function PhysAddrToStr(PhysAddr: PByte; Len: DWORD): string;
begin
Result:= EmptyStr;
while Len > 1 do
begin
Result:= Result + IntToHex(PhysAddr^,2) + '-';
inc(PhysAddr);
dec(Len);
end;
if Len > 0 then
Result:= Result + IntToHex(PhysAddr^,2);
end;
function IfTypeToStr(IfType: DWORD): string;
begin
case ifType of
MIB_IF_TYPE_ETHERNET: Result:= 'ETHERNET';
MIB_IF_TYPE_TOKENRING: Result:= 'TOKENRING';
MIB_IF_TYPE_FDDI: Result:= 'FDDI';
MIB_IF_TYPE_PPP: Result:= 'PPP';
MIB_IF_TYPE_LOOPBACK: Result:= 'LOOPBACK';
MIB_IF_TYPE_SLIP: Result:= 'SLIP';
else
Result:= EmptyStr;
end;
end;
function IpToStr(Ip: DWORD): string;
begin
Result:= Format('%d.%d.%d.%d',
[IP and $FF,(IP shr 8) and $FF,(IP shr 16) and $FF,(IP shr 24) and $FF]);
end;
function ReverseBits(anInt : Integer) : Integer;
var
i : Integer;
begin
result := 0;
for i := 0 to (SizeOf(anInt) * 8 - 1) do
begin
result := (result shl 1) or (anInt and $01);
anInt := anInt shr 1;
end;
end;
{ TNetWorkInfo }
function TNetWorkInfo.IPAddrToName(IPAddr: string): string;
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
WSAData: TWSAData;
lasterr : Cardinal;
a : string;
begin
WSAStartup($101, WSAData);
SockAddrIn.sin_addr.s_addr := IPv4ToIntReverse(IPAddr);
HostEnt := gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
if HostEnt <> nil then
Result := StrPas(Hostent^.h_name)
else
Result := '';
end;
function TNetWorkInfo.RasConnectionCount: Integer;
var
RasDLL: HInst;
Conns: array[1..4] of TRasConn;
RasEnums: TRasEnumConnections;
BufSize: DWORD;
NumConns: DWORD;
RasResult: Longint;
begin
Result := 0;
//Load the RAS DLL
RasDLL := LoadLibrary('rasapi32.dll');
if RasDLL = 0 then Exit;
try
RasEnums := GetProcAddress(RasDLL, 'RasEnumConnectionsA');
if @RasEnums = nil then
raise ERasError.Create('RasEnumConnectionsA not found in rasapi32.dll');
Conns[1].dwSize := SizeOf(Conns[1]);
BufSize := SizeOf(Conns);
RasResult := RasEnums(@Conns, BufSize, NumConns);
if (RasResult = 0) or (Result = cERROR_BUFFER_TOO_SMALL) then Result := NumConns;
finally
FreeLibrary(RasDLL);
end;
end;
function TNetWorkInfo.GetDomainName : string;
var
err : Integer;
buf : pointer;
fDomainName: string;
wServerName : WideString;
begin
wServerName := GetDefaultComputerName;
err := NetServerGetInfo (PWideChar (wServerName), 503, buf);
if err = 0 then
try
fDomainName := PSERVER_INFO_503 (buf)^.sv503_domain;
finally
NetAPIBufferFree (buf)
end;
result := fDomainName;
end;
function TNetWorkInfo.IsWrongIP(Ip: string): Boolean;
const
Z = ['0'..'9', '.'];
var
I, J, P: Integer;
W: string;
begin
Result := False;
if (Length(Ip) > 15) or (Ip[1] = '.') then Exit;
I := 1;
J := 0;
P := 0;
W := '';
repeat
if (Ip[I] in Z) and (J < 4) then
begin
if Ip[I] = '.' then
begin
Inc(P);
J := 0;
try
StrToInt(Ip[I + 1]);
except
Exit;
end;
W := '';
end
else
begin
W := W + Ip[I];
if (StrToInt(W) > 255) or (Length(W) > 3) then Exit;
Inc(J);
end;
end
else
Exit;
Inc(I);
until I > Length(Ip);
if P < 3 then Exit;
Result := True;
end;
procedure TNetWorkInfo.OnGetComputerTerminated(aSender: TObject);
begin
Dec(fcurrentworkers);
end;
function TNetWorkInfo.CreateNetResourceList(ResourceType: DWord; NetResource: PNetResource;
out Entries: DWord; out List: PNetResourceArray): Boolean;
var
EnumHandle: THandle;
BufSize: DWord;
Res: DWord;
begin
Result := False;
List := Nil;
Entries := 0;
if WNetOpenEnum(RESOURCE_GLOBALNET,
ResourceType,
0,
NetResource,
EnumHandle) = NO_ERROR then begin
try
BufSize := $4000; // 16 kByte
GetMem(List, BufSize);
try
repeat
Entries := DWord(-1);
FillChar(List^, BufSize, 0);
Res := WNetEnumResource(EnumHandle, Entries, List, BufSize);
if Res = ERROR_MORE_DATA then
begin
ReAllocMem(List, BufSize);
end;
until Res <> ERROR_MORE_DATA;
Result := Res = NO_ERROR;
if not Result then
begin
FreeMem(List);
List := Nil;
Entries := 0;
end;
except
FreeMem(List);
raise;
end;
finally
WNetCloseEnum(EnumHandle);
end;
end;
end;
procedure TNetWorkInfo.ScanNetworkResources(ResourceType, DisplayType: DWord; List: TStrings);
procedure ScanLevel(NetResource: PNetResource);
var
Entries: DWord;
NetResourceList: PNetResourceArray;
i: Integer;
begin
if CreateNetResourceList(ResourceType, NetResource, Entries, NetResourceList) then try
for i := 0 to Integer(Entries) - 1 do
begin
if (DisplayType = RESOURCEDISPLAYTYPE_GENERIC) or
(NetResourceList[i].dwDisplayType = DisplayType) then begin
List.AddObject(NetResourceList[i].lpRemoteName, Pointer(NetResourceList[i].dwDisplayType));
end;
if (NetResourceList[i].dwUsage and RESOURCEUSAGE_CONTAINER) <> 0 then
ScanLevel(@NetResourceList[i]);
end;
finally
FreeMem(NetResourceList);
end;
end;
begin
ScanLevel(Nil);
end;
procedure TNetWorkInfo.GetDNSServers(AList: TStringList);
var
pFI: PFixedInfo;
pIPAddr: PIPAddrString;
OutLen: Cardinal;
begin
AList.Clear;
OutLen := SizeOf(TFixedInfo);
GetMem(pFI, SizeOf(TFixedInfo));
try
if GetNetworkParams(pFI, @OutLen) = ERROR_BUFFER_OVERFLOW then
begin
ReallocMem(pFI, OutLen);
if GetNetworkParams(pFI, @OutLen) <> NO_ERROR then Exit;
end;
// If there is no network available there may be no DNS servers defined
if pFI^.DnsServerList.IpAddress._String[0] = #0 then Exit;
// Add first server
AList.Add(pFI^.DnsServerList.IpAddress._String);
// Add rest of servers
pIPAddr := pFI^.DnsServerList.Next;
while Assigned(pIPAddr) do
begin
AList.Add(pIPAddr^.IpAddress._String);
pIPAddr := pIPAddr^.Next;
end;
finally
FreeMem(pFI);
end;
end;
function TNetWorkInfo.GetDefaultNetWareUserName: string;
var ipNam: PChar;
Size: DWord;
begin
ipNam := nil;
Size := 128;
try
Result := '';
GetMem(ipNam, Size);
if GetUserName(ipNam, Size)
then Result := UpperCase(TRIM(strPas(ipNam)))
else Result := '?';
finally
FreeMem(ipNam, 10);
end;
end;
function TNetWorkInfo.GetDefaultComputerName: string;
var ipNam: PChar;
Size: DWord;
begin
ipNam := nil;
Size := MAX_COMPUTERNAME_LENGTH + 1;
try
Result := '';
GetMem(ipNam, Size);
if GetComputerName(ipNam, Size)
then Result := UpperCase(TRIM(strPas(ipNam)))
else Result := '?';
finally
FreeMem(ipNam, 10);
end;
end;
function TNetWorkInfo.Get_MACAddress: string;
var
NCB: PNCB;
Adapter: PAdapterStatus;
URetCode: PChar;
RetCode: AnsiChar;
I: integer;
Lenum: PlanaEnum;
_SystemID: string;
TMPSTR: string;
begin
Result := '';
_SystemID := '';
Getmem(NCB, SizeOf(TNCB));
Fillchar(NCB^, SizeOf(TNCB), 0);
Getmem(Lenum, SizeOf(TLanaEnum));
Fillchar(Lenum^, SizeOf(TLanaEnum), 0);
Getmem(Adapter, SizeOf(TAdapterStatus));
Fillchar(Adapter^, SizeOf(TAdapterStatus), 0);
Lenum.Length := chr(0);
NCB.ncb_command := chr(NCBENUM);
NCB.ncb_buffer := Pointer(Lenum);
NCB.ncb_length := SizeOf(Lenum);
RetCode := Netbios(NCB);
i := 0;
repeat
Fillchar(NCB^, SizeOf(TNCB), 0);
Ncb.ncb_command := chr(NCBRESET);
Ncb.ncb_lana_num := lenum.lana[I];
RetCode := Netbios(Ncb);
Fillchar(NCB^, SizeOf(TNCB), 0);
Ncb.ncb_command := chr(NCBASTAT);
Ncb.ncb_lana_num := lenum.lana[I];
// Must be 16
Ncb.ncb_callname := '* ';
Ncb.ncb_buffer := Pointer(Adapter);
Ncb.ncb_length := SizeOf(TAdapterStatus);
RetCode := Netbios(Ncb);
//---- calc _systemId from mac-address[2-5] XOR mac-address[1]...
if (RetCode = chr(0)) or (RetCode = chr(6)) then
begin
_SystemId := IntToHex(Ord(Adapter.adapter_address[0]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[1]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[2]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[3]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[4]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[5]), 2);
end;
Inc(i);
until (I >= Ord(Lenum.Length)) or (_SystemID <> '00-00-00-00-00-00');
FreeMem(NCB);
FreeMem(Adapter);
FreeMem(Lenum);
Result := _SystemID;
end;
function TNetWorkInfo.GetIPAddress: String;
type
TaPInAddr = Array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
Buffer: Array[0..63] of AnsiChar;
I: Integer;
GInitData: TWSAData;
begin
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
I := 0;
while pPtr^[I] <> nil do
begin
Result := inet_ntoa(pptr^[I]^);
Inc(I);
end;
WSACleanup;
end;
function TNetWorkInfo.GetMAC: string;
begin
Result := Get_MACAddress ;
end;
function TNetWorkInfo.GetMask: string;
begin
Result := IpToStr(GetNetworkProperties(0).dwMask);
end;
function TNetWorkInfo.GetIP: string;
begin
Result := GetIPAddress;
end;
function TNetWorkInfo.GetUser: string;
begin
Result := GetDefaultNetWareUserName;
end;
function TNetWorkInfo.GetCIDR: string;
begin
//TODO Get CIDR from the first adapter.
end;
function TNetWorkInfo.GetCompName: string;
begin
Result := GetDefaultComputerName;
end;
function TNetWorkInfo.GetDNSServ: TStringList;
var
DNSList : TStringList;
begin
DNSList := TStringList.Create;
GetDNSServers(DNSList);
Result := DNSList;
end;
function TNetWorkInfo.GetNetworkProperties(Adapter : Integer) : TMIB_IPADDRROW;
var
OutBufLen: ULONG;
IpAddr: PIP_ADDR_STRING;
IfRow: TMIB_IFROW;
Table: PMIB_IPADDRTABLE;
Size: DWORD;
i: Integer;
begin
// Ip Address Table
GetMem(Table, Sizeof(TMIB_IPADDRTABLE));
try
Size:= Sizeof(TMIB_IPADDRTABLE);
if GetIpAddrTable(Table, @Size, FALSE) = ERROR_INSUFFICIENT_BUFFER then
begin
FreeMem(Table);
GetMem(Table,Size);
end;
FillChar(Table^,Size,0);
if GetIpAddrTable(Table, @Size, FALSE) = NO_ERROR then
begin
for i:= 0 to Table.dwNumEntries - 1 do
begin
if Adapter = i then result := Table.Table[i];
Exit;
end;
end;
finally
Freemem(Table);
end;
end;
function TNetWorkInfo.GetNWComp: TStringList;
var
CompList : TStringList;
begin
CompList := TStringList.Create;
ScanNetworkResources(RESOURCETYPE_DISK, RESOURCEDISPLAYTYPE_SERVER,CompList);
Result := CompList;
end;
procedure TNetWorkInfo.GetNWCompARP(CallBack : TDiscoveryCallback);
var
localIP : string;
localMask : string;
highip : TArray<string>;
lowip : TArray<string>;
templowip : string;
temphighip : string;
highiptemp : integer;
currentip : integer;
const
TOTALWORKERS : Integer = 32;
begin
fcurrentworkers := 0;
localIP := GetIPAddress;
localMask := GetMask;
GetIPRange(localIP, localMask, templowip, temphighip);
if (templowip <> '') and (temphighip <> '') then
begin
lowip := templowip.Split(['.']);
highip := temphighip.Split(['.']);
if (High(lowip) = 3) and (High(highip) = 3) then
begin
currentip := lowip[3].ToInteger;
highiptemp := highip[3].ToInteger;
while currentip <= highiptemp do
begin
if currentip = 0 then Inc(currentip);
while fcurrentworkers = TOTALWORKERS do
begin
Sleep(100);
end;
if fcurrentworkers <= TOTALWORKERS then
begin
inc(fcurrentworkers);
with TDiscoveryWorker.Create(True, Format('%s.%s.%s.%d', [lowip[0], lowip[1], lowip[2], currentip]), CallBack) do
begin
OnTerminate := OnGetComputerTerminated;
Start;
end;
end;
Inc(currentip);
end;
end;
end;
end;
function TNetWorkInfo.GetDN: String;
begin
Result := GetDomainName;
end;
function TNetWorkInfo.GetIntConnected: TConnectionType;
begin
Result := InternetconnectionType;
end;
function TNetWorkInfo.InternetconnectionType: TConnectionType;
var
dwConnectionTypes: Integer;
Res : boolean;
begin
Res := InternetGetConnectedState(@dwConnectionTypes, 0);
if (dwConnectionTypes and INTERNET_CONNECTION_MODEM )= INTERNET_CONNECTION_MODEM then
begin
Result := Modem;
Exit;
end;
if (dwConnectionTypes and INTERNET_CONNECTION_LAN )= INTERNET_CONNECTION_LAN then
begin
Result := Lan;
Exit;
end;
if (dwConnectionTypes and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then
begin
Result := Proxy;
Exit;
end;
Result := None;
end;
function IPAddrToName(const IPAddr: string): string;
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
WSAData: TWSAData;
begin
WSAStartup($101, WSAData);
SockAddrIn.sin_addr.s_addr:=IPv4ToIntReverse(IPAddr);
HostEnt:= GetHostByAddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
if HostEnt<>nil then
begin
Result:=StrPas(Hostent^.h_name)
end
else
begin
Result:='';
end;
WSACleanup;
end;
{ TDiscoveryWorker }
constructor TDiscoveryWorker.Create(CreateSuspended: Boolean; CurrentIP : string; CallBack : TDiscoveryCallback);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := True;
fCurrentIP := CurrentIP;
fCallback := CallBack;
end;
procedure TDiscoveryWorker.Execute;
var
name : string;
ip : Integer;
begin
name := IPAddrToName(fCurrentIP);
tthread.Synchronize(nil,
procedure
begin
if not name.IsEmpty and Assigned(fCallback) then fCallback(name);
end
);
end;
end.
|
unit CleanArch_EmbrConf.Infra.Database.Impl.Database;
interface
uses
Dataset.Serialize,
CleanArch_EmbrConf.Infra.Database.Interfaces,
CleanArch_EmbrConf.Core.Entity.Interfaces,
CleanArch_EmbrConf.Infra.Database.Conexao,
CleanArch_EmbrConf.Core.Entity.Impl.ParkingLot, System.JSON;
type
TDatabase = class(TInterfacedObject, iDatabase)
private
FConexao : iConexao;
FParkingLot : iParkingLot;
public
constructor Create;
destructor Destroy; override;
class function New : iDatabase;
function getOneOrNone(aSQL : String; const aParams : Array of String) : iParkingLot;
function OneOrNone(aSQL : String; const aParams : Array of String) : TJsonArray;
function postPark(aSQL : String; const aParams : Array of String) : iDatabase;
end;
implementation
constructor TDatabase.Create;
begin
FConexao := TConexao.New;
FParkingLot := TParkingLot.New;
end;
destructor TDatabase.Destroy;
begin
inherited;
end;
function TDatabase.getOneOrNone(aSQL: String;
const aParams: array of String): iParkingLot;
begin
FConexao
.SQL(aSQL)
.Params('code', aParams[0])
.Open;
Result := FParkingLot
.Code(FConexao.DataSet.FieldByName('code').AsString)
.Capacity(FConexao.DataSet.FieldByName('capacity').AsInteger)
.OpenHour(FConexao.DataSet.FieldByName('openhour').AsInteger)
.CloseHour(FConexao.DataSet.FieldByName('closehour').AsInteger)
.OccupiedSpaces(FConexao.DataSet.FieldByName('occupied_spaces').AsInteger);
end;
class function TDatabase.New : iDatabase;
begin
Result := Self.Create;
end;
function TDatabase.OneOrNone(aSQL: String;
const aParams: array of String): TJsonArray;
begin
Result := FConexao
.SQL(aSQL)
.Params('code', aParams[0])
.Open.DataSet.ToJSONArray;
end;
function TDatabase.postPark(aSQL: String;
const aParams: array of String): iDatabase;
begin
Result := Self;
FConexao
.SQL(aSQL)
.Params('code',aParams[0])
.Params('plate',aParams[1])
.Params('data',aParams[2])
.ExecSQL;
end;
end.
|
unit uBTStack;
{$mode delphi}{$H+}
(* BTStack
* Copyright (C) 2014 BlueKitchen GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH 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 MATTHIAS
* RINGWALD 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.
*
* Please inquire about commercial licensing options at
* contact@bluekitchen-gmbh.com
*
* Ultibo adaption pjde 2018
*)
interface
uses
Classes, SysUtils, SysCalls, GlobalTypes;
{$linklib btstack}
const
LOG_LEVEL_DEBUG = 0;
LOG_LEVEL_INFO = 1;
LOG_LEVEL_ERROR = 2;
HCI_DUMP_BLUEZ = 0;
HCI_DUMP_PACKETLOGGER = 1;
HCI_DUMP_STDOUT = 2;
BTSTACK_UART_SLEEP_OFF = 0; // UART active, sleep off
BTSTACK_UART_SLEEP_RTS_HIGH_WAKE_ON_CTS_PULSE = 1; // used for eHCILL
BTSTACK_UART_SLEEP_RTS_LOW_WAKE_ON_RX_EDGE = 2; // used for H5 and for eHCILL without support for wake on CTS pulse
BTSTACK_UART_SLEEP_MASK_RTS_HIGH_WAKE_ON_CTS_PULSE = 1 shl BTSTACK_UART_SLEEP_RTS_HIGH_WAKE_ON_CTS_PULSE;
BTSTACK_UART_SLEEP_MASK_RTS_LOW_WAKE_ON_RX_EDGE = 1 shl BTSTACK_UART_SLEEP_RTS_LOW_WAKE_ON_RX_EDGE;
DATA_SOURCE_CALLBACK_POLL = 1 shl 0;
DATA_SOURCE_CALLBACK_READ = 1 shl 1;
DATA_SOURCE_CALLBACK_WRITE = 1 shl 2;
HCI_TRANSPORT_CONFIG_UART = 0;
HCI_TRANSPORT_CONFIG_USB = 1;
type
uint8_t = uint8;
uint16_t = uint16;
uint32_t = uint32;
btstack_uart_sleep_mode_t = LongWord; // enum
hci_dump_format_t = LongWord; // enum
btstack_uart_sleep_mode_mask_t = LongWord; // enum
btstack_data_source_callback_type_t = LongWord; // enum
hci_transport_config_type_t = LongWord; // enum
Puint8_t = ^uint8_t;
Puint16_t = ^uint16_t;
Puint32_t = ^uint32_t;
Phci_transport_t = ^hci_transport_t;
Pbtstack_run_loop_t = ^btstack_run_loop_t;
Pbtstack_uart_config_t = ^btstack_uart_config_t;
Pbtstack_uart_block_t = ^btstack_uart_block_t;
Pbtstack_data_source_t = ^btstack_data_source_t;
Pbtstack_timer_source_t = ^btstack_timer_source_t;
Pbtstack_linked_item_t = ^btstack_linked_item_t;
btstack_linked_list_t = ^btstack_linked_item_t;
Pbtstack_linked_list_t = ^btstack_linked_list_t;
Pbtstack_linked_list_iterator_t = ^btstack_linked_list_iterator_t;
Pbtstack_packet_callback_registration_t = ^btstack_packet_callback_registration_t;
{$PACKRECORDS C}
btstack_uart_config_t = record
baudrate : uint32_t;
flowcontrol : integer;
device_name : PChar;
end;
hci_transport_config_uart_t = record
type_ : hci_transport_config_type_t; // = HCI_TRANSPORT_CONFIG_UART
baudrate_init : uint32_t; // initial baud rate
baudrate_main : uint32_t; // = 0: same as initial baudrate
flowcontrol : integer; //
device_name : PChar;
end;
// uart block functions
TBlockHandler = procedure; cdecl;
TUartInitFunc = function (const uart_config : Pbtstack_uart_config_t) : integer; cdecl;
TUartOpenFunc = function : integer; cdecl;
TUartCloseFunc = function : integer; cdecl;
TReceivedFunc = procedure (block_handler : TBlockHandler); cdecl;
TSentFunc = procedure (block_handler : TBlockHandler); cdecl;
TBaudRateFunc = procedure (baudrate : uint32_t); cdecl;
TParityFunc = procedure (parity : integer); cdecl;
TFlowControlFunc = procedure (flowcontrol : integer); cdecl;
TReceiveBlockFunc = procedure (buffer : Puint8_t; len : uint16_t); cdecl;
TSendBlockFunc = procedure (const buffer : Puint8_t; length : uint16_t); cdecl;
TSleepModesFunc = function : Pinteger; cdecl;
TSetSleepFunc = procedure (sleep_mode : btstack_uart_sleep_mode_t); cdecl;
TWakeUpHandlerFunc = procedure; cdecl;
TWakeUpFunc = procedure (wakeup_handler : TWakeUpHandlerFunc); cdecl;
btstack_uart_block_t = record // size 52 bytes
Init : TUartInitFunc;
Open : TUartOpenFunc;
Close : TUartCloseFunc;
SetBlockReceived : TReceivedFunc;
SetBlockSent : TSentFunc;
SetBaudRate : TBaudRateFunc;
SetParity : TParityFunc;
SetFlowControl : TFlowControlFunc;
ReceiveBlock : TReceiveBlockFunc;
SendBlock : TSendBlockFunc;
GetSupportedSleepModes : TSleepModesFunc;
SetSleep : TSetSleepFunc;
SetWakeUpHandler : TWakeUpFunc;
end;
btstack_linked_item_t = record // size 4 bytes
next : Pbtstack_linked_item_t; // <-- next element in list, or NULL
end;
btstack_linked_list_iterator_t = record
advance_on_next : integer;
prev : Pbtstack_linked_item_t; // points to the item before the current one
curr : Pbtstack_linked_item_t; // points to the current item (to detect item removal)
end;
TDataProcessFunc = procedure (ds : Pbtstack_data_source_t; callback_type : btstack_data_source_callback_type_t); cdecl;
btstack_data_source_t = record // size 16 bytes
item : btstack_linked_item_t; // linked item
handle : HANDLE; // handle on windows
Process : TDataProcessFunc; // callback to call for enabled callback types
flags : uint16_t; // flags storing enabled callback types
end;
TTimerProcessFunc = procedure (ts : Pbtstack_timer_source_t); cdecl;
btstack_timer_source_t = record // size 16 bytes
item : btstack_linked_item_t;
timeout : uint32_t; // timeout in system ticks (HAVE_EMBEDDED_TICK) or milliseconds (HAVE_EMBEDDED_TIME_MS)
Process : TTimerProcessFunc; // will be called when timer fired
context : pointer;
end;
TLoopInitFunc = procedure; cdecl;
TAddDataSourceFunc = procedure (data_source : Pbtstack_data_source_t); cdecl;
TRemoveDataSourceFunc = function (data_source : Pbtstack_data_source_t) : integer; cdecl;
TEnableDataSourceCallbacksFunc = procedure (data_source : Pbtstack_data_source_t; callbacks : uint16_t); cdecl;
TDisableDataSourceCallbacksFunc = procedure (data_source : Pbtstack_data_source_t; callbacks : uint16_t); cdecl;
TSetTimerFunc = procedure (timer : Pbtstack_timer_source_t; timeout_in_ms : uint32_t); cdecl;
TAddTimerFunc = procedure (timer : Pbtstack_timer_source_t); cdecl;
TRemoveTimerFunc = function (timer : Pbtstack_timer_source_t) : integer; cdecl;
TLoopExecuteFunc = procedure; cdecl;
TDumpTimerFunc = procedure; cdecl;
TGetTimeMSFunc = function : uint32_t; cdecl;
btstack_run_loop_t = record // size 44 bytes
Init : TLoopInitFunc;
AddDataSource : TAddDataSourceFunc;
RemoveDataSource : TRemoveDataSourceFunc;
EnableDataSourceCallbacks : TEnableDataSourceCallbacksFunc;
DisableDataSourceCallbacks : TDisableDataSourceCallbacksFunc;
SetTimer : TSetTimerFunc;
AddTimer : TAddTimerFunc;
RemoveTimer : TRemoveTimerFunc;
Execute : TLoopExecuteFunc;
DumpTimer : TDumpTimerFunc;
GetTimeMS : TGetTimeMSFunc;
end;
{ hci_transport_t = record // size 40 bytes
stuffing : array [0..39] of byte;
end; }
TTransInitFunc = procedure (transport_config : pointer); cdecl;
TTransOpenFunc = procedure; cdecl;
TTransCloseFunc = procedure; cdecl;
TTransHandlerFunc = procedure (packet_type : uint8_t; packet : Puint8_t; size : uint16_t); cdecl;
TTransRegHandlerFunc = procedure (handler : TTransHandlerFunc); cdecl;
TTransCanSendFunc = function (packet_type : uint8_t) : integer; cdecl;
TTransSendPacketFunc = function (packet_type : uint8_t; packet : Puint8_t; size : integer) : integer; cdecl;
TTransSetBaudRateFunc = function (baudrate : uint32_t) : integer; cdecl;
TTransResetLinkFunc = procedure; cdecl;
TTransSetSCOConfigFunc = procedure (voice_setting : uint16_t; num_connections : integer); cdecl;
hci_transport_t = record
name : PChar;
Init : TTransInitFunc;
Open : TTransOpenFunc;
Close : TTranscloseFunc;
register_packet_handler : TTransRegHandlerFunc;
CanSendPacketNow : TTransCanSendFunc;
SendPacket : TTransSendPacketFunc;
SetBaudRate : TTransSetBaudRateFunc;
ResetLink : TTransResetLinkFunc;
SetSCOConfig : TTransSetSCOConfigFunc;
end;
btstack_packet_handler_t = procedure (packet_type : uint8_t; channel :uint16_t; packet : Puint8_t; size : uint16_t); cdecl;
// packet callback supporting multiple registrations
btstack_packet_callback_registration_t = record
item : btstack_linked_item_t;
callback : btstack_packet_handler_t;
end;
// BTStack APIs
procedure btstack_memory_init; cdecl; external;
procedure btstack_run_loop_init (const run_loop : Pbtstack_run_loop_t); cdecl; external;
procedure btstack_run_loop_execute; cdecl; external;
function hci_transport_h4_instance (const uart_driver : Pbtstack_uart_block_t) : Phci_transport_t; cdecl; external;
(*procedure hci_transport_h4_init (const transport_config : pointer); cdecl; external;
function hci_transport_h4_open : integer; cdecl; external;
function hci_transport_h4_close : integer; cdecl; external; *)
procedure hci_dump_open (const filename : PChar; formt : hci_dump_format_t); cdecl; external;
procedure hci_dump_set_max_packets (packets : integer); cdecl; external; // -1 for unlimited
procedure hci_dump_packet (packet_type : uint8_t; in_ : uint8_t; packet : Puint8_t; len : uint16_t); cdecl; external;
procedure hci_dump_log (log_level : integer; const format_ : PChar); cdecl; varargs; external;
procedure hci_dump_enable_log_level (log_level : integer; enable : integer); cdecl; external;
procedure hci_dump_close; cdecl; external;
function btstack_linked_list_empty (list : Pbtstack_linked_list_t) : integer; cdecl; external;
procedure btstack_linked_list_add (list : Pbtstack_linked_list_t; item : Pbtstack_linked_item_t); cdecl; external;
procedure btstack_linked_list_add_tail (list : Pbtstack_linked_list_t; item : Pbtstack_linked_item_t); cdecl; external;
function btstack_linked_list_pop (list : Pbtstack_linked_list_t) : Pbtstack_linked_item_t; cdecl; external;
function btstack_linked_list_remove (list : Pbtstack_linked_list_t; item : Pbtstack_linked_item_t) : integer; cdecl; external;
function btstack_linked_list_get_first_item (list : Pbtstack_linked_list_t) : Pbtstack_linked_item_t; cdecl; external;
function btstack_linked_list_get_last_item (list : Pbtstack_linked_list_t) : Pbtstack_linked_item_t; cdecl; external;
function btstack_linked_list_count (list : Pbtstack_linked_list_t) : integer; cdecl; external;
procedure btstack_linked_list_iterator_init (it : Pbtstack_linked_list_iterator_t; list : Pbtstack_linked_list_t); cdecl; external;
function btstack_linked_list_iterator_has_next (it : Pbtstack_linked_list_iterator_t) : integer; cdecl; external;
function btstack_linked_list_iterator_next (it : Pbtstack_linked_list_iterator_t) : Pbtstack_linked_item_t; cdecl; external;
procedure btstack_linked_list_iterator_remove (it : Pbtstack_linked_list_iterator_t); cdecl; external;
procedure hci_init (const transport : Phci_transport_t; const config : pointer); cdecl; external;
procedure hci_close; cdecl; external;
procedure hci_add_event_handler (callback_handler : Pbtstack_packet_callback_registration_t); cdecl; external;
procedure hci_register_acl_packet_handler (handler : btstack_packet_handler_t); cdecl; external;
procedure hci_register_sco_packet_handler (handler : btstack_packet_handler_t); cdecl; external;
// my functions
procedure MyTest; cdecl; external;
// ultibo specific
function btstack_uart_block_ultibo_instance : Pbtstack_uart_block_t; cdecl;
function btstack_run_loop_ultibo_get_instance : Pbtstack_run_loop_t; cdecl;
implementation
uses
uLog, Ultibo, GlobalConst;
var
btstack_uart_ultibo : btstack_uart_block_t;
btstack_run_loop_ultibo : btstack_run_loop_t;
data_sources_modified : boolean = false;
timers : btstack_linked_list_t = nil;
data_sources : btstack_linked_list_t = nil;
start_time : ULARGE_INTEGER;
function btstack_uart_block_ultibo_instance : Pbtstack_uart_block_t; cdecl;
begin
Result := @btstack_uart_ultibo;
end;
function btstack_uart_ultibo_init (const uart_config : Pbtstack_uart_config_t) : integer; cdecl;
begin
Log ('UART Initialising');
Result := 0;
end;
function btstack_uart_ultibo_open : integer; cdecl;
begin
Log ('open');
Result := 0;
end;
function btstack_uart_ultibo_close : integer; cdecl;
begin
Log ('close');
Result := 0;
end;
procedure btstack_uart_ultibo_setbaudrate (baudrate : uint32_t); cdecl;
begin
//
Log ('set baud rate');
end;
procedure btstack_uart_ultibo_setparity (parity : integer); cdecl;
begin
//
end;
procedure btstack_uart_ultibo_setflowcontrol (flowcontrol : integer); cdecl;
begin
//
end;
// ultibo run loop based of windows run loop
function btstack_run_loop_ultibo_get_instance : Pbtstack_run_loop_t; cdecl;
begin
Result := @btstack_run_loop_ultibo;
end;
procedure btstack_run_loop_ultibo_init; cdecl;
var
file_time : FILETIME;
system_time : SYSTEMTIME;
begin
Log ('Ultibo Run Loop init');
data_sources := nil;
timers := nil;
GetSystemTime (system_time); // store start time
SystemTimeToFileTime (system_time, file_time);
start_time.LowPart := file_time.dwLowDateTime;
start_time.HighPart := file_time.dwHighDateTime;
end;
procedure btstack_run_loop_ultibo_dump_timer; cdecl;
var
it : Pbtstack_linked_item_t;
ts : Pbtstack_timer_source_t;
i : integer;
begin
i := 0;
it := Pbtstack_linked_item_t (timers);
while it <> nil do
begin
ts := Pbtstack_timer_source_t (it);
log (format ('timer %u, timeout %u', [i, ts^.timeout]));
it := it^.next;
i := i + 1;
end;
end;
procedure btstack_run_loop_ultibo_add_data_source (ds : Pbtstack_data_source_t); cdecl;
begin
data_sources_modified := true;
// log_info("btstack_run_loop_ultibo_add_data_source %x with fd %u\n", (int) ds, ds->fd);
btstack_linked_list_add (@data_sources, Pbtstack_linked_item_t (ds));
end;
function btstack_run_loop_ultibo_remove_data_source (ds : Pbtstack_data_source_t) : integer; cdecl;
begin
data_sources_modified := true;
// log_info("btstack_run_loop_ultibo_remove_data_source %x\n", (int) ds);
Result := btstack_linked_list_remove (@data_sources, Pbtstack_linked_item_t (ds));
end;
procedure btstack_run_loop_ultibo_add_timer (ts : Pbtstack_timer_source_t); cdecl;
var
it : Pbtstack_linked_item_t;
next : Pbtstack_timer_source_t;
begin
log ('add timer');
it := Pbtstack_linked_item_t (@timers);
while it^.next <> nil do
begin
next := Pbtstack_timer_source_t (it^.next);
if next = ts then
begin
log ('btstack_run_loop_timer_add error: timer to add already in list!');
exit;
end;
if next^.timeout > ts^.timeout then break;
it := it^.next;
end;
ts^.item.next := it^.next;
it^.next := Pbtstack_linked_item_t (ts);
log (format ('Added timer %p at %u', [ts, ts^.timeout]));
// btstack_run_loop_ultibo_dump_timer;
end;
function btstack_run_loop_ultibo_remove_timer (ts : Pbtstack_timer_source_t) : integer; cdecl;
begin
// log_info("Removed timer %x at %u\n", (int) ts, (unsigned int) ts->timeout.tv_sec);
// btstack_run_loop_ultibo_dump_timer();
Result := btstack_linked_list_remove (@timers, Pbtstack_linked_item_t (ts));
end;
procedure btstack_run_loop_ultibo_enable_data_source_callbacks (ds : Pbtstack_data_source_t; callback_types : uint16_t); cdecl;
begin
ds^.flags := ds^.flags or callback_types;
end;
procedure btstack_run_loop_ultibo_disable_data_source_callbacks (ds : Pbtstack_data_source_t; callback_types : uint16_t); cdecl;
begin
ds^.flags := ds^.flags and (not callback_types);
end;
function btstack_run_loop_ultibo_get_time_ms : uint32_t; cdecl;
var
file_time : FILETIME;
system_time : SYSTEMTIME;
now_time : ULARGE_INTEGER;
time_ms : uint32_t;
begin
GetSystemTime (system_time);
SystemTimeToFileTime (system_time, file_time);
now_time.LowPart := file_time.dwLowDateTime;
now_time.HighPart := file_time.dwHighDateTime;
time_ms := (now_time.QuadPart - start_time.QuadPart) div 10000;
log (format ('btstack_run_loop_ultibo_get_time_ms: %u', [time_ms]));
Result := time_ms;
end;
procedure btstack_run_loop_ultibo_set_timer (a : Pbtstack_timer_source_t; timeout_in_ms : uint32_t); cdecl;
var
time_ms : uint32_t;
begin
time_ms := btstack_run_loop_ultibo_get_time_ms;
a^.timeout := time_ms + timeout_in_ms;
log (format ('btstack_run_loop_ultibo_set_timer to %u ms (now %u, timeout %u)', [a^.timeout, time_ms, timeout_in_ms]));
end;
procedure btstack_run_loop_ultibo_execute; cdecl;
var
ts : Pbtstack_timer_source_t;
ds : Pbtstack_data_source_t;
it : btstack_linked_list_iterator_t;
handles : array [0..99] of HANDLE;
num_handles : integer;
timeout_ms : uint32_t;
now_ms : uint32_t;
res : integer;
triggered_handle : HANDLE;
begin
while true do
begin
// collect handles to wait for
FillChar (handles, sizeof (handles), 0);
num_handles := 0;
btstack_linked_list_iterator_init (@it, @data_sources);
while btstack_linked_list_iterator_has_next (@it) <> 0 do
begin
ds := Pbtstack_data_source_t (btstack_linked_list_iterator_next (@it));
if ds^.handle = 0 then continue;
if (ds^.flags and (DATA_SOURCE_CALLBACK_READ or DATA_SOURCE_CALLBACK_WRITE)) > 0 then
begin
handles[num_handles] := ds^.handle;
num_handles := num_handles + 1;
log (format ('btstack_run_loop_execute adding handle %p', [ds^.handle]));
end;
end;
// get next timeout
timeout_ms := INFINITE;
if timers <> nil then
begin
ts := Pbtstack_timer_source_t (timers);
now_ms := btstack_run_loop_ultibo_get_time_ms;
timeout_ms := ts^.timeout - now_ms;
// if timeout_ms < 0 then timeout_ms := 0;
log (format ('btstack_run_loop_execute next timeout in %u ms', [timeout_ms]));
end;
if num_handles > 0 then
// wait for ready Events or timeout
res := WaitForMultipleObjects (num_handles, @handles[0], false, timeout_ms)
else
begin
// just wait for timeout
Sleep (timeout_ms);
res := WAIT_TIMEOUT;
end;
// process data source
if (WAIT_OBJECT_0 <= res) and (res < (WAIT_OBJECT_0 + num_handles)) then
begin
triggered_handle := handles[res - WAIT_OBJECT_0];
btstack_linked_list_iterator_init (@it, @data_sources);
while btstack_linked_list_iterator_has_next (@it) <> 0 do
begin
ds := Pbtstack_data_source_t (btstack_linked_list_iterator_next (@it));
log (format ('btstack_run_loop_ultibo_execute: check ds %p with handle %p', [ds, ds^.handle]));
if triggered_handle = ds^.handle then
begin
if ds^.flags and DATA_SOURCE_CALLBACK_READ > 0 then
begin
log (format ('btstack_run_loop_ultibo_execute: process read ds %p with handle %p', [ds, ds^.handle]));
if assigned (ds^.Process) then ds^.Process (ds, DATA_SOURCE_CALLBACK_READ);
end
else if ds^.flags and DATA_SOURCE_CALLBACK_WRITE > 0 then
begin
log (format ('btstack_run_loop_ultibo_execute: process write ds %p with handle %p', [ds, ds^.handle]));
if assigned (ds^.Process) then ds^.Process (ds, DATA_SOURCE_CALLBACK_WRITE);
end;
break;
end;
end;
end;
// process timers
now_ms := btstack_run_loop_ultibo_get_time_ms;
while timers <> nil do
begin
ts := Pbtstack_timer_source_t (timers);
if (ts^.timeout > now_ms) then break;
log (format ('btstack_run_loop_ultibo_execute: process timer %p', [ts]));
// remove timer before processing it to allow handler to re-register with run loop
btstack_run_loop_ultibo_remove_timer (ts);
if Assigned (ts^.Process) then ts^.Process (ts);
end;
end;
end;
initialization
btstack_uart_ultibo.Init := btstack_uart_ultibo_init;
btstack_uart_ultibo.Open := btstack_uart_ultibo_open;
btstack_uart_ultibo.Close := btstack_uart_ultibo_close;
btstack_uart_ultibo.SetBlockReceived := nil;
btstack_uart_ultibo.SetBlockSent := nil;
btstack_uart_ultibo.SetBaudRate := btstack_uart_ultibo_setbaudrate;
btstack_uart_ultibo.SetParity := btstack_uart_ultibo_setparity;
btstack_uart_ultibo.SetFlowControl := btstack_uart_ultibo_setflowcontrol;
btstack_uart_ultibo.ReceiveBlock := nil;
btstack_uart_ultibo.SendBlock := nil;
btstack_uart_ultibo.GetSupportedSleepModes := nil;
btstack_uart_ultibo.SetSleep := nil;
btstack_uart_ultibo.SetWakeupHandler := nil;
btstack_run_loop_ultibo.Init := btstack_run_loop_ultibo_init;
btstack_run_loop_ultibo.AddDataSource := btstack_run_loop_ultibo_add_data_source;
btstack_run_loop_ultibo.RemoveDataSource := btstack_run_loop_ultibo_remove_data_source;
btstack_run_loop_ultibo.EnableDataSourceCallbacks := btstack_run_loop_ultibo_enable_data_source_callbacks;
btstack_run_loop_ultibo.DisableDataSourceCallbacks := btstack_run_loop_ultibo_disable_data_source_callbacks;
btstack_run_loop_ultibo.SetTimer := btstack_run_loop_ultibo_set_timer;
btstack_run_loop_ultibo.AddTimer := btstack_run_loop_ultibo_add_timer;
btstack_run_loop_ultibo.RemoveTimer := btstack_run_loop_ultibo_remove_timer;
btstack_run_loop_ultibo.Execute := btstack_run_loop_ultibo_execute;
btstack_run_loop_ultibo.DumpTimer := btstack_run_loop_ultibo_dump_timer;
btstack_run_loop_ultibo.GetTimeMS := btstack_run_loop_ultibo_get_time_ms;
end.
|
unit uRelPedidoVenda;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uModeloRel, StdCtrls, Buttons, Mask, ExtCtrls, JvBaseEdits,
JvExControls, JvSpeedButton, JvExMask, JvToolEdit, JvNavigationPane, DB,
ZAbstractRODataset, ZDataset, ZConnection, frxClass, frxDBSet,
JvExStdCtrls, JvCombobox, JvDBCombobox, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxImageComboBox, ACBrBase, ACBrEnterTab,
JvDBControls, frxExportPDF, JvComponentBase, JvFormPlacement;
type
TfrmRelPedidoVenda = class(TfrmModeloRel)
qrRelPedidosVenda: TZReadOnlyQuery;
frxPedidosVenda: TfrxReport;
frxDBPedidosVenda: TfrxDBDataset;
Bevel2: TBevel;
Label10: TLabel;
Label1: TLabel;
Label2: TLabel;
d02: TJvDateEdit;
d01: TJvDateEdit;
Bevel3: TBevel;
Label11: TLabel;
Label7: TLabel;
Label8: TLabel;
d03: TJvDateEdit;
d04: TJvDateEdit;
Bevel4: TBevel;
Label12: TLabel;
Label3: TLabel;
Label4: TLabel;
Label9: TLabel;
edCNPJ: TMaskEdit;
Bevel5: TBevel;
Label5: TLabel;
Bevel7: TBevel;
Label15: TLabel;
cbStatus: TComboBox;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
cbPagamento: TcxImageComboBox;
cbForma: TcxImageComboBox;
Bevel8: TBevel;
Label19: TLabel;
Label20: TLabel;
cbVendedor: TcxImageComboBox;
qrRelPedidosVendaAnalitico: TZReadOnlyQuery;
frxPedidosVendaAnalitco: TfrxReport;
frxDBPedidosVendaAnalitico: TfrxDBDataset;
Label13: TLabel;
Bevel6: TBevel;
Label14: TLabel;
Label21: TLabel;
Label22: TLabel;
cbTipoRelatorio: TComboBox;
edNumero: TEdit;
edPedido: TEdit;
Label6: TLabel;
cbOrdenacao: TComboBox;
qrRelPedidosVendanome_empresa: TStringField;
qrRelPedidosVendasite_empresa: TStringField;
qrRelPedidosVendatelefone_empresa: TStringField;
qrRelPedidosVendaendereco_empresa: TStringField;
qrRelPedidosVendaendereco_empresa2: TStringField;
qrRelPedidosVendaid: TIntegerField;
qrRelPedidosVendaempresa_codigo: TLargeintField;
qrRelPedidosVendadata: TDateField;
qrRelPedidosVendavencimento: TDateField;
qrRelPedidosVendanumero: TIntegerField;
qrRelPedidosVendanome: TStringField;
qrRelPedidosVendacomissao_vendedor: TFloatField;
qrRelPedidosVendatipo_comissao: TStringField;
qrRelPedidosVendavendedor: TLargeintField;
qrRelPedidosVendacliente_codigo: TLargeintField;
qrRelPedidosVendacliente_filial: TLargeintField;
qrRelPedidosVendanome_1: TStringField;
qrRelPedidosVendafantasia: TStringField;
qrRelPedidosVendaoperacao: TLargeintField;
qrRelPedidosVendameio_pagamento: TLargeintField;
qrRelPedidosVendaforma_pagamento: TLargeintField;
qrRelPedidosVendatabela: TLargeintField;
qrRelPedidosVendatabela_conversao: TLargeintField;
qrRelPedidosVendastatus: TSmallintField;
qrRelPedidosVendavalor_pedido: TFloatField;
qrRelPedidosVendaperc_desc_nota: TFloatField;
qrRelPedidosVendadesconto_nota: TFloatField;
qrRelPedidosVendaperc_desc_financeiro: TFloatField;
qrRelPedidosVendadesconto_financeiro: TFloatField;
ACBrEnterTab1: TACBrEnterTab;
qrRelPedidosVendaAnaliticoempresa: TStringField;
qrRelPedidosVendaAnaliticocnpj_empresa: TStringField;
qrRelPedidosVendaAnaliticotelefone_empresa: TStringField;
qrRelPedidosVendaAnaliticosite_empresa: TStringField;
qrRelPedidosVendaAnaliticoendereco_empresa: TStringField;
qrRelPedidosVendaAnaliticoendereco_empresa2: TStringField;
qrRelPedidosVendaAnaliticoid: TIntegerField;
qrRelPedidosVendaAnaliticodata: TDateField;
qrRelPedidosVendaAnaliticofantasia: TStringField;
qrRelPedidosVendaAnaliticonumero: TIntegerField;
qrRelPedidosVendaAnaliticovalor_pedido: TFloatField;
qrRelPedidosVendaAnaliticovalor_descontos: TFloatField;
qrRelPedidosVendaAnaliticonome: TStringField;
qrRelPedidosVendaAnaliticounidade: TStringField;
qrRelPedidosVendaAnaliticoquantidade: TFloatField;
qrRelPedidosVendaAnaliticovalor_unitario: TFloatField;
qrRelPedidosVendaAnaliticovalor_total: TFloatField;
qrRelPedidosVendaAnaliticodesconto_item: TFloatField;
qrRelPedidosVendaAnaliticocliente_codigo: TLargeintField;
qrRelPedidosVendaAnaliticocliente_filial: TLargeintField;
edtCliente: TJvDBComboEdit;
edtFantasia: TJvDBComboEdit;
Label23: TLabel;
cbOperacao: TcxImageComboBox;
Label24: TLabel;
frxPDFExport1: TfrxPDFExport;
JvNavPanelHeader1: TJvNavPanelHeader;
Bevel1: TBevel;
JvFormStorage1: TJvFormStorage;
edPedido1: TEdit;
edNumero1: TEdit;
Label25: TLabel;
Label26: TLabel;
procedure btnImprimirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure frxPedidosVendaGetValue(const VarName: string;
var Value: Variant);
procedure frxPedidosVendaAnalitcoGetValue(const VarName: string;
var Value: Variant);
procedure edPedidoChange(Sender: TObject);
procedure edNumeroChange(Sender: TObject);
procedure edtClienteButtonClick(Sender: TObject);
procedure edtFantasiaButtonClick(Sender: TObject);
procedure Label24MouseEnter(Sender: TObject);
procedure Label24MouseLeave(Sender: TObject);
procedure Label24Click(Sender: TObject);
procedure cbTipoRelatorioChange(Sender: TObject);
private
{ Private declarations }
cliente, filial: string;
procedure RelPedidosVenda;
procedure RelPedidosVendaAnalitico;
procedure ApagaCampos;
public
{ Public declarations }
end;
var
frmRelPedidoVenda: TfrmRelPedidoVenda;
implementation
uses
udmPrincipal, funcoes, uConsulta_Padrao;
{$R *.dfm}
procedure TfrmRelPedidoVenda.RelPedidosVenda;
begin
try
if (d01.Date = 0) and (d02.Date = 0) and (cliente = EmptyStr)
and (filial = EmptyStr) and (d03.Date = 0) and (d04.Date = 0) and (edCNPJ.Text = EmptyStr)
and (cbVendedor.ItemIndex < 0) and (edNumero.Text = EmptyStr) and (edPedido.Text = EmptyStr) then
begin
Application.MessageBox('Você deve selecionar algum filtro primeiro!', 'Atenção', MB_ICONERROR);
Exit;
end;
qrRelPedidosVenda.Close;
qrRelPedidosVenda.SQL.Clear;
qrRelPedidosVenda.SQL.Add('select');
qrRelPedidosVenda.SQL.Add('e.fantasia as nome_empresa, e.site as site_empresa, e.telefone as telefone_empresa,');
qrRelPedidosVenda.SQL.Add('concat(e.logradouro,", ",e.numero," ", ifnull(e.complemento,"")) as endereco_empresa,');
qrRelPedidosVenda.SQL.Add('concat(e.cidade, " - ", e.uf, " - ", e.cep) as endereco_empresa2,');
qrRelPedidosVenda.SQL.Add('v.id, v.empresa_codigo, v.data, v.vencimento, v.numero,');
qrRelPedidosVenda.SQL.Add('vd.nome, v.comissao_vendedor, vd.tipo_comissao,v.vendedor,');
qrRelPedidosVenda.SQL.Add('v.cliente_codigo, v.cliente_filial, cf.nome, cf.fantasia,');
qrRelPedidosVenda.SQL.Add('v.operacao,');
qrRelPedidosVenda.SQL.Add('v.meio_pagamento, v.forma_pagamento, v.tabela,');
qrRelPedidosVenda.SQL.Add('v.tabela_conversao, v.status,');
qrRelPedidosVenda.SQL.Add('(v.valor_pedido-v.desconto_nota-v.desconto_financeiro) as valor_pedido,');
qrRelPedidosVenda.SQL.Add('v.perc_desc_nota, v.desconto_nota,');
qrRelPedidosVenda.SQL.Add('v.perc_desc_financeiro, v.desconto_financeiro');
qrRelPedidosVenda.SQL.Add('from vendas as v');
qrRelPedidosVenda.SQL.Add(' left join clientes_fornecedores as cf');
qrRelPedidosVenda.SQL.Add(' on v.cliente_codigo=cf.codigo and v.cliente_filial=cf.filial');
qrRelPedidosVenda.SQL.Add(' left join vendedores as vd on vd.codigo=v.vendedor');
qrRelPedidosVenda.SQL.Add(' left join empresas as e on v.empresa_codigo=e.codigo');
qrRelPedidosVenda.SQL.Add('where v.empresa_codigo=:EmpresaLogada');
qrRelPedidosVenda.SQL.Add('and isnull(v.data_exc)');
qrRelPedidosVenda.ParamByName('EmpresaLogada').AsInteger := dmPrincipal.empresa_login;
if (d01.Date <> 0) and (d02.Date = 0) then
begin
qrRelPedidosVenda.SQL.add('and v.data=:data1');
qrRelPedidosVenda.ParamByName('data1').AsDate := d01.Date;
end
else if (d01.Date > 0) and (d02.Date > 0) then
begin
qrRelPedidosVenda.SQL.add('and v.data between :data1 and :data2');
qrRelPedidosVenda.ParamByName('data1').AsDate := d01.Date;
qrRelPedidosVenda.ParamByName('data2').AsDate := d02.Date;
end;
if (d03.Date <> 0) and (d04.Date = 0) then
begin
qrRelPedidosVenda.SQL.add('and v.vencimento=:data3');
qrRelPedidosVenda.ParamByName('data3').AsDate := d03.Date;
end
else if (d03.Date > 0) and (d04.Date > 0) then
begin
qrRelPedidosVenda.SQL.add('and v.vencimento between :data3 and :data4');
qrRelPedidosVenda.ParamByName('data3').AsDate := d03.Date;
qrRelPedidosVenda.ParamByName('data4').AsDate := d04.Date;
end;
if edCNPJ.Text <> EmptyStr then
begin
qrRelPedidosVenda.SQL.add('and left(replace(cf.cliente_cnpj,".",""),8)=:cnpj');
qrRelPedidosVenda.ParamByName('cnpj').AsString := Copy(edCNPJ.Text, 1, 8);
end;
if (edNumero.Text <> EmptyStr) and (edNumero1.Text = EmptyStr) then
begin
qrRelPedidosVenda.SQL.add('and v.numero=:pNumero');
qrRelPedidosVenda.ParamByName('pNumero').AsString := edNumero.Text;
end;
if (edNumero.Text <> EmptyStr) and (edNumero1.Text <> EmptyStr) then
begin
qrRelPedidosVenda.SQL.add('and v.numero between :pNumero1 and :pNumero2');
qrRelPedidosVenda.ParamByName('pNumero1').AsString := edNumero.Text;
qrRelPedidosVenda.ParamByName('pNumero2').AsString := edNumero1.Text;
end;
if (edPedido.Text <> EmptyStr) and (edPedido1.Text = EmptyStr) then
begin
qrRelPedidosVenda.SQL.add('and v.id=:pPedido');
qrRelPedidosVenda.ParamByName('pPedido').AsString := edPedido.Text;
end;
if (edPedido.Text <> EmptyStr) and (edPedido1.Text <> EmptyStr) then
begin
qrRelPedidosVenda.SQL.add('and v.id between :edPedido1 and :edPedido2');
qrRelPedidosVenda.ParamByName('edPedido1').AsString := edPedido.Text;
qrRelPedidosVenda.ParamByName('edPedido2').AsString := edPedido1.Text;
end;
if cliente <> '' then
qrRelPedidosVenda.SQL.Add('and v.cliente_codigo=' + cliente);
if filial <> '' then
qrRelPedidosVenda.SQL.Add('and v.cliente_filial=' + filial);
if cbPagamento.ItemIndex <> -1 then
begin
qrRelPedidosVenda.SQL.add('and v.meio_pagamento=:MeioPagamento');
qrRelPedidosVenda.ParamByName('MeioPagamento').AsInteger := cbPagamento.Properties.Items.Items[cbPagamento.ItemIndex].Value;
end;
if cbForma.ItemIndex <> -1 then
begin
qrRelPedidosVenda.SQL.add('and v.forma_pagamento=:FormaPagamento');
qrRelPedidosVenda.ParamByName('FormaPagamento').AsInteger := cbForma.Properties.Items.Items[cbForma.ItemIndex].Value;
end;
if cbVendedor.ItemIndex <> -1 then
begin
qrRelPedidosVenda.SQL.add('and v.vendedor=:Vendedor');
qrRelPedidosVenda.ParamByName('Vendedor').AsInteger := cbVendedor.Properties.Items.Items[cbVendedor.ItemIndex].Value;
end;
if cbOperacao.ItemIndex <> -1 then
begin
qrRelPedidosVenda.SQL.add('and v.operacao=:Operacao');
qrRelPedidosVenda.ParamByName('Operacao').AsInteger := cbOperacao.Properties.Items.Items[cbOperacao.ItemIndex].Value;
end;
case cbStatus.ItemIndex of
0: qrRelPedidosVenda.SQL.Add('');
1: qrRelPedidosVenda.SQL.Add('and v.status in (0,1)');
2: qrRelPedidosVenda.SQL.Add('and v.status=2');
end;
case cbOrdenacao.ItemIndex of
0: qrRelPedidosVenda.SQL.Add('order by cf.fantasia');
1: qrRelPedidosVenda.SQL.Add('order by v.data');
2: qrRelPedidosVenda.SQL.Add('order by v.id');
3: qrRelPedidosVenda.SQL.Add('order by v.vencimento');
4: qrRelPedidosVenda.SQL.Add('order by v.numero');
end;
qrRelPedidosVenda.Open;
if qrRelPedidosVenda.IsEmpty then
begin
Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR);
Exit;
end
else
begin
frxPedidosVenda.ShowReport;
end;
finally
qrRelPedidosVenda.Close;
ApagaCampos;
end;
end;
procedure TfrmRelPedidoVenda.btnImprimirClick(Sender: TObject);
begin
inherited;
if cbTipoRelatorio.ItemIndex = 1 then
RelPedidosVenda
else
RelPedidosVendaAnalitico;
end;
procedure TfrmRelPedidoVenda.FormCreate(Sender: TObject);
begin
inherited;
CarregaCombo(cbPagamento, 'select id,a.descricao from meio_pagamento a join meio_cobranca b on meio_cobranca=b.codigo where ativo="S" order by descricao');
CarregaCombo(cbForma, 'select id,descricao from forma_pagamento where ativo="S" order by descricao');
CarregaCombo(cbVendedor, 'select codigo, nome from vendedores where ativo="S" order by nome');
CarregaCombo(cbOperacao, 'select codigo, nome from operacoes where tipo="S" and ativo="S" order by nome');
cliente := '';
filial := '';
d01.Date := dmPrincipal.SoData;
end;
procedure TfrmRelPedidoVenda.RelPedidosVendaAnalitico;
begin
try
if (d01.Date = 0) and (d02.Date = 0) and (cliente = EmptyStr)
and (filial = EmptyStr) and (d03.Date = 0) and (d04.Date = 0) and (edCNPJ.Text = EmptyStr)
and (cbVendedor.ItemIndex < 0) and (edNumero.Text = EmptyStr) and (edPedido.Text = EmptyStr) then
begin
Application.MessageBox('Você deve selecionar algum filtro primeiro!', 'Atenção', MB_ICONERROR);
Exit;
end;
qrRelPedidosVendaAnalitico.Close;
qrRelPedidosVendaAnalitico.SQL.Clear;
qrRelPedidosVendaAnalitico.SQL.Add('select');
qrRelPedidosVendaAnalitico.SQL.Add('e.fantasia as empresa, e.cnpj as cnpj_empresa,');
qrRelPedidosVendaAnalitico.SQL.Add('e.telefone as telefone_empresa, e.site as site_empresa,');
qrRelPedidosVendaAnalitico.SQL.Add('concat(e.logradouro,", ",e.numero," ", ifnull(e.complemento,"")) as endereco_empresa,');
qrRelPedidosVendaAnalitico.SQL.Add('concat(e.cidade, " - ", e.uf, " - ", e.cep) as endereco_empresa2,');
qrRelPedidosVendaAnalitico.SQL.Add('v.id,v.data, cf. fantasia, v.numero,');
qrRelPedidosVendaAnalitico.SQL.Add('(v.valor_pedido-v.desconto_nota-v.desconto_financeiro) as valor_pedido,');
qrRelPedidosVendaAnalitico.SQL.Add('(v.desconto_nota+v.desconto_financeiro) as valor_descontos,');
qrRelPedidosVendaAnalitico.SQL.Add('p.nome, p.unidade, v.cliente_codigo, v.cliente_filial,');
qrRelPedidosVendaAnalitico.SQL.Add('vi.quantidade, vi.valor_unitario, vi.valor_total, vi.desconto_item');
qrRelPedidosVendaAnalitico.SQL.Add('from vendas v');
qrRelPedidosVendaAnalitico.SQL.Add(' left join empresas e on v.empresa_codigo=e.codigo');
qrRelPedidosVendaAnalitico.SQL.Add(' left join clientes_fornecedores cf on v.cliente_codigo=cf.codigo and v.cliente_filial=cf.filial');
qrRelPedidosVendaAnalitico.SQL.Add(' left join vendas_itens vi on v.id=vi.id_venda');
qrRelPedidosVendaAnalitico.SQL.Add(' left join produtos p on vi.produto_codigo=p.codigo');
qrRelPedidosVendaAnalitico.SQL.Add('where isnull(vi.data_exc)');
qrRelPedidosVendaAnalitico.SQL.Add('and isnull(v.data_exc)');
qrRelPedidosVendaAnalitico.SQL.Add('and v.empresa_codigo=:EmpresaLogada');
qrRelPedidosVendaAnalitico.ParamByName('EmpresaLogada').AsInteger := dmPrincipal.empresa_login;
if (d01.Date <> 0) and (d02.Date = 0) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.data=:data1');
qrRelPedidosVendaAnalitico.ParamByName('data1').AsDate := d01.Date;
end
else if (d01.Date > 0) and (d02.Date > 0) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.data between :data1 and :data2');
qrRelPedidosVendaAnalitico.ParamByName('data1').AsDate := d01.Date;
qrRelPedidosVendaAnalitico.ParamByName('data2').AsDate := d02.Date;
end;
if (d03.Date <> 0) and (d04.Date = 0) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.vencimento=:data3');
qrRelPedidosVendaAnalitico.ParamByName('data3').AsDate := d03.Date;
end
else if (d03.Date > 0) and (d04.Date > 0) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.vencimento between :data3 and :data4');
qrRelPedidosVendaAnalitico.ParamByName('data3').AsDate := d03.Date;
qrRelPedidosVendaAnalitico.ParamByName('data4').AsDate := d04.Date;
end;
if edCNPJ.Text <> EmptyStr then
begin
qrRelPedidosVendaAnalitico.SQL.add('and left(replace(cf.cliente_cnpj,".",""),8)=:cnpj');
qrRelPedidosVendaAnalitico.ParamByName('cnpj').AsString := Copy(edCNPJ.Text, 1, 8);
end;
if (edNumero.Text <> EmptyStr) and (edNumero1.Text = EmptyStr) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.numero=:pNumero');
qrRelPedidosVendaAnalitico.ParamByName('pNumero').AsString := edNumero.Text;
end;
if (edNumero.Text <> EmptyStr) and (edNumero1.Text <> EmptyStr) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.numero between :pNumero1 and :pNumero2');
qrRelPedidosVendaAnalitico.ParamByName('pNumero1').AsString := edNumero.Text;
qrRelPedidosVendaAnalitico.ParamByName('pNumero2').AsString := edNumero1.Text;
end;
if (edPedido.Text <> EmptyStr) and (edPedido1.Text = EmptyStr) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.id=:pPedido');
qrRelPedidosVendaAnalitico.ParamByName('pPedido').AsString := edPedido.Text;
end;
if (edPedido.Text <> EmptyStr) and (edPedido1.Text <> EmptyStr) then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.id between :edPedido1 and :edPedido2');
qrRelPedidosVendaAnalitico.ParamByName('edPedido1').AsString := edPedido.Text;
qrRelPedidosVendaAnalitico.ParamByName('edPedido2').AsString := edPedido1.Text;
end;
if cliente <> '' then
qrRelPedidosVendaAnalitico.SQL.Add('and v.cliente_codigo=' + cliente);
if filial <> '' then
qrRelPedidosVendaAnalitico.SQL.Add('and v.cliente_filial=' + filial);
if cbPagamento.ItemIndex <> -1 then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.meio_pagamento=:MeioPagamento');
qrRelPedidosVendaAnalitico.ParamByName('MeioPagamento').AsInteger := cbPagamento.Properties.Items.Items[cbPagamento.ItemIndex].Value;
end;
if cbForma.ItemIndex <> -1 then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.forma_pagamento=:FormaPagamento');
qrRelPedidosVendaAnalitico.ParamByName('FormaPagamento').AsInteger := cbForma.Properties.Items.Items[cbForma.ItemIndex].Value;
end;
if cbVendedor.ItemIndex <> -1 then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.vendedor=:Vendedor');
qrRelPedidosVendaAnalitico.ParamByName('Vendedor').AsInteger := cbVendedor.Properties.Items.Items[cbVendedor.ItemIndex].Value;
end;
if cbOperacao.ItemIndex <> -1 then
begin
qrRelPedidosVendaAnalitico.SQL.add('and v.operacao=:Operacao');
qrRelPedidosVendaAnalitico.ParamByName('Operacao').AsInteger := cbOperacao.Properties.Items.Items[cbOperacao.ItemIndex].Value;
end;
case cbStatus.ItemIndex of
0: qrRelPedidosVendaAnalitico.SQL.Add('');
1: qrRelPedidosVendaAnalitico.SQL.Add('and v.status in (0,1)');
2: qrRelPedidosVendaAnalitico.SQL.Add('and v.status=2');
end;
case cbOrdenacao.ItemIndex of
0: qrRelPedidosVendaAnalitico.SQL.Add('order by cf.fantasia');
1: qrRelPedidosVendaAnalitico.SQL.Add('order by v.data');
2: qrRelPedidosVendaAnalitico.SQL.Add('order by v.id');
3: qrRelPedidosVendaAnalitico.SQL.Add('order by v.vencimento');
4: qrRelPedidosVenda.SQL.Add('order by v.numero');
end;
qrRelPedidosVendaAnalitico.Open;
if qrRelPedidosVendaAnalitico.IsEmpty then
begin
Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR);
Exit;
end
else
begin
frxPedidosVendaAnalitco.ShowReport;
end;
finally
qrRelPedidosVendaAnalitico.Close;
ApagaCampos; ;
end
end;
procedure TfrmRelPedidoVenda.FormShow(Sender: TObject);
begin
inherited;
if d01.CanFocus then
d01.SetFocus;
end;
procedure TfrmRelPedidoVenda.frxPedidosVendaGetValue(const VarName: string;
var Value: Variant);
var
s: string;
begin
inherited;
if (d01.Date <> 0) and (d02.Date = 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date))
else if (d01.Date > 0) and (d02.Date > 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date), ' Até ', formatdatetime('dd/mm/yyyy', d02.Date));
if CompareText(VarName, 'periodo') = 0 then
Value := s;
end;
procedure TfrmRelPedidoVenda.frxPedidosVendaAnalitcoGetValue(
const VarName: string; var Value: Variant);
var
s: string;
begin
inherited;
if (d01.Date <> 0) and (d02.Date = 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date))
else if (d01.Date > 0) and (d02.Date > 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date), ' Até ', formatdatetime('dd/mm/yyyy', d02.Date));
if CompareText(VarName, 'periodo') = 0 then
Value := s;
end;
procedure TfrmRelPedidoVenda.edPedidoChange(Sender: TObject);
begin
inherited;
if not StringEmBranco(edPedido.Text) then
begin
d01.Clear;
d02.Clear;
end;
end;
procedure TfrmRelPedidoVenda.edNumeroChange(Sender: TObject);
begin
inherited;
if not StringEmBranco(edNumero.Text) then
begin
d01.Clear;
d02.Clear;
end;
end;
procedure TfrmRelPedidoVenda.edtClienteButtonClick(Sender: TObject);
begin
inherited;
with TfrmConsulta_Padrao.Create(self) do
begin
with Query.SQL do
begin
Clear;
Add('select nome Nome, codigo Código from clientes_fornecedores');
Add('where nome like :pFantasia and ativo="S" and tipo_cadastro in ("C","A")');
Add('group by codigo order by 1');
end;
CampoLocate := 'nome';
Parametro := 'pFantasia';
ColunasGrid := 2;
ShowModal;
if Tag = 1 then
begin
edtCliente.Text := Query.Fields[0].Value;
cliente := Query.Fields[1].Value;
end;
Free;
end;
end;
procedure TfrmRelPedidoVenda.edtFantasiaButtonClick(Sender: TObject);
begin
inherited;
with TfrmConsulta_Padrao.Create(self) do
begin
with Query.SQL do
begin
Clear;
Add('select fantasia Fantasia, filial Filial, codigo Código from clientes_fornecedores');
Add('where fantasia like :pFantasia and ativo="S" and tipo_cadastro in ("C","A")');
if cliente <> '' then
begin
Add('and codigo=:pCodigo');
Query.ParamByName('pCodigo').Value := cliente;
end;
Add('order by 1');
end;
CampoLocate := 'fantasia';
Parametro := 'pFantasia';
ColunasGrid := 2;
ShowModal;
if Tag = 1 then
begin
edtFantasia.Text := Query.Fields[0].Value;
cliente := Query.Fields[2].Value;
filial := Query.Fields[1].Value;
end;
Free;
end;
end;
procedure TfrmRelPedidoVenda.ApagaCampos;
begin
cbVendedor.ItemIndex := -1;
cbPagamento.ItemIndex := -1;
cbForma.ItemIndex := -1;
cbOperacao.ItemIndex := -1;
edtCliente.Clear;
edtFantasia.Clear;
cliente := '';
filial := '';
edCNPJ.Clear;
edPedido.Clear;
edPedido1.Clear;
edNumero.Clear;
edNumero1.Clear;
end;
procedure TfrmRelPedidoVenda.Label24MouseEnter(Sender: TObject);
begin
inherited;
(Sender as TLabel).Font.Style := [fsBold];
end;
procedure TfrmRelPedidoVenda.Label24MouseLeave(Sender: TObject);
begin
inherited;
(Sender as TLabel).Font.Style := [];
end;
procedure TfrmRelPedidoVenda.Label24Click(Sender: TObject);
begin
inherited;
ApagaCampos;
end;
procedure TfrmRelPedidoVenda.cbTipoRelatorioChange(Sender: TObject);
begin
inherited;
if cbTipoRelatorio.ItemIndex = 0 then
cbOrdenacao.ItemIndex := 2;
end;
end.
|
{ Subroutine SST_INTRINSIC_DTYPE (NAME,DTYPE,SIZE,DT_P)
*
* Create a new intrinsic data type in the current scope. NAME is the symbol
* name for the new data type. DTYPE is the SST library data type ID.
* SIZE if the size of the data type in machine addresses. DT_P will be returned
* pointing to the new data type descriptor block. The data type block will
* be initialized, but may need to have additional fields set or fixed by the
* calling routine.
*
* The SIZE parameter will be used to initialize the BITS_MIN, ALIGN_NAT,
* SIZE_USED, and SIZE_ALIGN fields. It will be assumed that the natural alignment
* size is the same as SIZE. Natural alignment will be assumed regardless of
* the current setting.
}
module sst_INTRINSIC_DTYPE;
define sst_intrinsic_dtype;
%include 'sst2.ins.pas';
procedure sst_intrinsic_dtype ( {create intrinsic data type in curr scope}
in name: string; {data type name}
in dtype: sst_dtype_k_t; {which base data type is this}
in size: sys_int_adr_t; {size in machine addresses}
out dt_p: sst_dtype_p_t); {pointer to created and initialized data type}
var
vname: string_var80_t; {var string symbol name}
stat: sys_err_t;
begin
vname.max := sizeof(vname.str); {init local var string}
sst_dtype_new (dt_p); {create new data type}
dt_p^.dtype := dtype; {set the data type}
dt_p^.bits_min := size * sst_config.bits_adr;
dt_p^.align_nat := size;
dt_p^.align := size;
dt_p^.size_used := size;
dt_p^.size_align := size;
string_vstring (vname, name, sizeof(name));
sst_symbol_new_name (vname, dt_p^.symbol_p, stat); {create symbol for new data type}
sys_error_abort (stat, '', '', nil, 0);
dt_p^.symbol_p^.symtype := sst_symtype_dtype_k; {symbol is a data type}
dt_p^.symbol_p^.flags := dt_p^.symbol_p^.flags + {symbol is intrinsic and defined}
[sst_symflag_def_k, sst_symflag_intrinsic_in_k];
dt_p^.symbol_p^.dtype_dtype_p := dt_p; {point symbol to the data type block}
end;
|
unit MFichas.Model.Entidade.USUARIOPERMISSOES;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('USUARIOPERMISSOES', '')]
[PrimaryKey('DESCRICAO', NotInc, NoSort, False, 'Chave primária')]
TUSUARIOPERMISSOES = class
private
{ Private declarations }
FDESCRICAO: String;
FPERMISSAO: Integer;
public
{ Public declarations }
[Column('DESCRICAO', ftString, 60)]
[Dictionary('DESCRICAO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property DESCRICAO: String read FDESCRICAO write FDESCRICAO;
[Column('PERMISSAO', ftInteger)]
[Dictionary('PERMISSAO', 'Mensagem de validação', '', '', '', taCenter)]
property PERMISSAO: Integer read FPERMISSAO write FPERMISSAO;
end;
implementation
initialization
TRegisterClass.RegisterEntity(TUSUARIOPERMISSOES)
end.
|
//***********************************************************
// InventorySystem
//
// Copyright (c) 2002 Failproof Manufacturing Systems
//
//***********************************************************
//
// 10/31/2002 Aaron Huge Initial creation
unit ConfirmPassword;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Buttons, DataModule; //IniFiles;
type
TConfirmPassword_Form = class(TForm)
Panel2: TPanel;
Password_Label: TLabel;
bitBtnLogon: TBitBtn;
BitBtnCancel: TBitBtn;
Password_Edit: TEdit;
procedure bitBtnLogonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function Execute: boolean;
end;
var
ConfirmPassword_Form: TConfirmPassword_Form;
implementation
{$R *.DFM}
procedure TConfirmPassword_Form.bitBtnLogonClick(Sender: TObject);
begin
If (Trim(Password_Edit.Text) = '') Then
Begin
MessageDlg('The Password box is blank.' +
#13 + 'Please try again.', mtInformation, [mbOK], 0);
Password_Edit.SetFocus;
End
Else
Begin
If Data_Module.gobjUser.AppUserPass = Trim(Password_Edit.Text) Then
Begin
ModalResult := mrOK;
Data_Module.LogActLog('USER ADMIN', 'Confirmed password to enter User Administration.', 0);
End
Else
Begin
Data_Module.LogActLog('ADMIN ERR', 'FAILED to match password to enter User Administration.', 0);
Password_Edit.Text := '';
Password_Edit.SetFocus;
MessageDlg('The password you entered is invalid.' +
#13 + 'Please try again.', mtInformation, [mbOK], 0);
End;
End;
end;
function TConfirmPassword_Form.Execute: boolean;
Begin
Result:= True;
Password_Edit.Text:='';
try
try
ShowModal;
except
On E:Exception do
showMessage('Unable to generate logon screen.'
+ #13 + 'ERROR:'
+ #13 + E.Message);
end;
finally
If ModalResult = mrCancel Then
Result:= False;
end;
end;
end.
|
namespace Sugar.Legacy;
interface
{$HIDE W0} //supress case-mismatch errors
uses
Sugar,
Sugar.IO,
Sugar.Collections;
type
MemIniFile = public class
private
fList: Dictionary<String,Dictionary<String,String>>;
fFile : File;
method LoadValues;
method int_ReadSectionValues(const Section: String; List: List<String>);
method Int_AddSection(const Section: String):Dictionary<String,String>;
method Int_AddValue(const Section: Dictionary<String,String>; Ident, Value: String);
protected
public
constructor (const aFile: File);
method Clear;
method DeleteKey(const Section, Ident: String);
method EraseSection(const Section: String);
method GetStrings(List: List<String>);
method ReadSection(const Section: String; List: List<String>);
method ReadSections(List: List<String>);
method ReadSectionValues(const Section: String; List: List<String>);
method ReadString(const Section, Ident, &Default: String): String;
method SetStrings(List: List<String>);
method UpdateFile;
method WriteString(const Section, Ident, Value: String);
method SectionExists(const Section: String): Boolean;
method ValueExists(const Section, Ident: String): Boolean;
method Revert;
property &File: File read fFile;
end;
implementation
method String_IndexOf(Source: String; aChar : Char): Int32;
begin
exit String_IndexOf(Source, aChar+'');
end;
method String_IndexOf(Source: String; aString : String): Int32;
begin
result := -1;
var llen := aString:Length;
if llen = 0 then exit;
var lcnt := Source:Length - llen + 1;
if lcnt < 0 then exit;
var i: Integer;
var j := 0;
for i := 0 to lcnt do begin
while (j >= 0) and (j < llen) do begin
if Source.Chars[i + j] = aString.Chars[j] then
inc(j)
else
j := -1;
end;
if j >= llen then exit i;
end;
end;
method String_Split(Source: String; Separator : Char): List<String>;
begin
exit String_Split(Source,Separator+'');
end;
method String_Split(Source: String; Separator : String): List<String>;
begin
result := new List<String>;
var ls := Source;
var i: Integer;
repeat
i := String_IndexOf(ls,Separator);
if i = -1 then break;
result.Add(ls.Substring(0,i));
ls := ls.Substring(i+Separator.Length);
until false;
result.Add(ls);
end;
constructor MemIniFile(const aFile: File);
begin
fFile := aFile;
fList := new Dictionary<String,Dictionary<String,String>>();
LoadValues;
end;
method MemIniFile.Clear;
begin
fList.Clear;
end;
method MemIniFile.DeleteKey(Section: String; Ident: String);
begin
if SectionExists(Section) then
fList.Item[Section].Remove(Ident);
end;
method MemIniFile.EraseSection(Section: String);
begin
if SectionExists(Section) then fList.Remove(Section);
end;
method MemIniFile.GetStrings(List: List<String>);
begin
List.Clear;
for lk in fList.Keys do begin
List.Add('['+lk+']');
int_ReadSectionValues(lk,List);
List.Add('');
end;
end;
method MemIniFile.ReadSection(Section: String; List: List<String>);
begin
List.Clear;
if fList.ContainsKey(Section) then
for lk1 in fList.Item[Section].Keys do
List.Add(lk1);
end;
method MemIniFile.ReadSections(List: List<String>);
begin
List.Clear;
for lk in fList.Keys do
List.Add(lk);
end;
method MemIniFile.ReadSectionValues(Section: String; List: List<String>);
begin
List.Clear;
int_ReadSectionValues(Section,List);
end;
method MemIniFile.ReadString(Section: String; Ident: String; &Default: String): String;
begin
result := &Default;
if SectionExists(Section) then begin
var lDict := fList.Item[Section];
if lDict.ContainsKey(Ident) then result := lDict.Item[Ident];
end;
end;
method MemIniFile.SetStrings(List: List<String>);
begin
Clear;
var ldict: Dictionary<String,String> := nil;
var i: Integer;
var lSectionfound := false;
for i := 0 to List.Count - 1 do begin
var lname := List[i].Trim;
if String.IsNullOrEmpty(lname) or (lname[0] = ';') then continue;
if (lname[0] = '[') and (lname[lname.Length-1] = ']') then begin
lSectionfound := true;
ldict := Int_AddSection(lname.Substring(1, lname.Length-2).Trim);
end
else begin
if lSectionfound then begin
var lvalue := '';
var lindex := String_IndexOf(lname,'=');
if lindex <>-1 then begin
lvalue:= lname.Substring(lindex+1).Trim;
lname := lname.Substring(0, lindex).Trim;
end;
Int_AddValue(ldict,lname,lvalue);
end;
end;
end;
end;
method MemIniFile.UpdateFile;
begin
var lList := new List<String>;
var lsb := new StringBuilder;
GetStrings(lList);
var i: Integer;
for i:=0 to lList.Count do
lsb.AppendLine(lList[i]);
File.WriteText(lsb.ToString);
end;
method MemIniFile.WriteString(Section: String; Ident: String; Value: String);
begin
Int_AddValue(Int_AddSection(Section), Ident, Value);
end;
method MemIniFile.LoadValues;
begin
Clear;
SetStrings(String_Split(fFile.ReadText.Replace(#13#10,#10),#10));
end;
method MemIniFile.SectionExists(Section: String): Boolean;
begin
result := fList.ContainsKey(Section);
end;
method MemIniFile.ValueExists(Section: String; Ident: String): Boolean;
begin
result := true;
if SectionExists(Section) then begin
var lDict := fList.Item[Section];
result := lDict.ContainsKey(Ident);
end;
end;
method MemIniFile.int_ReadSectionValues(Section: String; List: List<String>);
begin
if fList.ContainsKey(Section) then begin
var lv := fList.Item[Section];
for lk1 in lv.Keys do
List.Add(lk1+'='+lv.Item[lk1]);
end;
end;
method MemIniFile.Int_AddSection(Section: String): Dictionary<String, String>;
begin
if fList.ContainsKey(Section) then exit fList[Section];
result := new Dictionary<String, String>;
fList.Add(Section,result);
end;
method MemIniFile.Int_AddValue(Section: Dictionary<String, String>; Ident: String; Value: String);
begin
if Section.ContainsKey(Ident) then
Section.Item[Ident] := Value
else
Section.Add(Ident,Value);
end;
method MemIniFile.Revert;
begin
LoadValues;
end;
end.
|
{!DOCTOPIC}{
Type » TStringArray
}
{!DOCREF} {
@method: function TStringArray.Len(): Int32;
@desc: Returns the length of the array. Same as c'Length(arr)'
}
function TStringArray.Len(): Int32;
begin
Result := Length(Self);
end;
{!DOCREF} {
@method: function TStringArray.IsEmpty(): Boolean;
@desc: Returns True if the array is empty. Same as c'Length(arr) = 0'
}
function TStringArray.IsEmpty(): Boolean;
begin
Result := Length(Self) = 0;
end;
{!DOCREF} {
@method: procedure TStrngArray.Append(const Str:String);
@desc: Add another string to the array
}
procedure TStringArray.Append(const Str:String); {$IFDEF SRL6}override;{$ENDIF}
var
l:Int32;
begin
l := Length(Self);
SetLength(Self, l+1);
Self[l] := Str;
end;
{!DOCREF} {
@method: procedure TStringArray.Insert(idx:Int32; Value:String);
@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 TStringArray.Insert(idx:Int32; Value:String);
var i,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);
for i:=l downto idx+1 do
Self[i] := Self[i-1];
Self[i] := Value;
end;
{!DOCREF} {
@method: function TStringArray.Pop(): String;
@desc: Removes and returns the last item in the array
}
function TStringArray.Pop(): String;
var
H:Int32;
begin
H := high(Self);
Result := Self[H];
SetLength(Self, H);
end;
{!DOCREF} {
@method: function TStringArray.PopLeft(): String;
@desc: Removes and returns the first item in the array
}
function TStringArray.PopLeft(): String;
begin
Result := Self[0];
Self := Self.Slice(1,-1);
end;
{!DOCREF} {
@method: function TStringArray.Slice(Start,Stop: Int32; Step:Int32=1): TStringArray;
@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(..)`[br]
If c'Start >= Stop', and c'Step <= -1' it will result in reversed output.[br]
[note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note]
}
function TStringArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TStringArray;
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 TStringArray.Extend(Arr:TStringArray);
@desc: Extends the TSA with another TSA
}
procedure TStringArray.Extend(Arr:TStringArray);
var L,i:Int32;
begin
L := Length(Self);
SetLength(Self, Length(Arr) + L);
for i:=L to High(Self) do
Self[i] := Copy(Arr[i-L]);
end;
{!DOCREF} {
@method: procedure TStringArray.Sort(key:TSortKey=sort_Default; IgnoreCase:Boolean=False);
@desc:
Sorts the array of strings
Supported keys: c'sort_Default, sort_lex, sort_logical'
}
procedure TStringArray.Sort(key:TSortKey=sort_Default; IgnoreCase:Boolean=False);
begin
case key of
sort_default, sort_lex: se.SortTSA(Self,IgnoreCase);
sort_logical: se.SortTSANatural(Self);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: function TStringArray.Sorted(key:TSortKey=sort_Default; IgnoreCase:Boolean=False): TStringArray;
@desc:
Sorts and returns a copy of the array.
Supports the keys: c'sort_Default, sort_lex, sort_logical'
[note]Partial, key not supported fully yet[/note]
}
function TStringArray.Sorted(key:TSortKey=sort_Default; IgnoreCase:Boolean=False): TStringArray;
begin
Result := Self.Slice();
case key of
sort_default, sort_lex: se.SortTSA(Result,IgnoreCase);
sort_logical: se.SortTSANatural(Result);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: function StringArray.Find(Value:String): Int32;
@desc: Searces for the given value and returns the first position from the left.
}
function TStringArray.Find(Value:String): Int32;
var TSA:TStringArray;
begin
TSA := [Value];
Result := exp_Find(Self,TSA);
end;
{!DOCREF} {
@method: function TStringArray.Find(Sequence:TStringArray): Int32; overload;
@desc: Searces for the given sequence and returns the first position from the left.
}
function TStringArray.Find(Sequence:TStringArray): Int32; overload;
begin
Result := exp_Find(Self,Sequence);
end;
{!DOCREF} {
@method: function TStringArray.FindAll(Value:String): TIntArray;
@desc: Searces for the given value and returns all the position where it was found.
}
function TStringArray.FindAll(Value:String): TIntArray;
var TSA:TStringArray;
begin
TSA := [Value];
Result := exp_FindAll(Self,TSA);
end;
{!DOCREF} {
@method: function TStringArray.FindAll(Sequence:TStringArray): TIntArray; overload;
@desc: Searces for the given sequence and returns all the position where it was found.
}
function TStringArray.FindAll(Sequence:TStringArray): TIntArray; overload;
begin
Result := exp_FindAll(Self,sequence);
end;
{!DOCREF} {
@method: function TStringArray.Contains(Value:String): Boolean;
@desc: Checks if the array contains the given `Value`.
}
function TStringArray.Contains(Value:String): Boolean;
begin
Result := Self.Find(Value) <> -1;
end;
{!DOCREF} {
@method: function TStringArray.Count(Value:String): Boolean;
@desc: Counts the number of occurances of the given `Value`.
}
function TStringArray.Count(Value:String): Boolean;
begin
Result := Length(Self.FindAll(Value));
end;
{!DOCREF} {
@method: function TStringArray.Reversed(): TStringArray;
@desc: Creates a reversed copy of the array
}
function TStringArray.Reversed(): TStringArray;
begin
Result := Self.Slice(,,-1);
end;
{!DOCREF} {
@method: procedure TStringArray.Reverse();
@desc: Reverses the array
}
procedure TStringArray.Reverse();
begin
Self := Self.Slice(,,-1);
end;
{!DOCREF} {
@method: function TStringArray.ToStr(Sep:String=', '): String;
@desc: Convert the TSA to a string representing the items in the TSA.
}
function TStringArray.ToStr(Sep:String=', '): String;
var i:=0;
begin
Result := '';
if High(Self) = -1 then Exit('');
Result := '['+#39+Self[0]+#39;
for i:=1 to High(Self) do
Result := Result + sep +#39+Self[i]+#39;
Result := Result + ']';
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 TStringArray.Capital(): TStringArray;
@desc: Return a copy of the array with each strings first character capitalized and the rest lowercased.
}
function TStringArray.Capital(): TStringArray;
var i:Int32;
begin
Result := Self.Slice();
for i:=0 to High(Self) do
Result[i] := Capitalize(Result[i]);
end;
{!DOCREF} {
@method: function TStringArray.Lower(): TStringArray;
@desc: Return a copy of the array with each string lowercased.
}
function TStringArray.Lower(): TStringArray;
var i:Int32;
begin
Result := Self.Slice();
for i:=0 to High(Self) do
Result[i] := LowerCase(Result[i]);
end;
{!DOCREF} {
@method: function TStringArray.Upper(): TStringArray;
@desc: Return a copy of the array with each string uppercased.
}
function TStringArray.Upper(): TStringArray;
var i:Int32;
begin
Result := Self.Slice();
for i:=0 to High(Self) do
Result[i] := UpperCase(Result[i]);
end;
{!DOCREF} {
@method: function TStringArray.Mode(IgnoreCase:Boolean=True): String;
@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.
[code=pascal]
var Arr: TStringArray = ['red', 'blue', 'blue', 'red', 'green', 'red', 'red'];
begin
WriteLn(Arr.Mode());
end.
[/code]
}
function TStringArray.Mode(IgnoreCase:Boolean=True): String;
var
arr:TStringArray;
cur:String;
i,hits,best: Int32;
begin
arr := self.sorted(sort_lex,IgnoreCase);
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;
|
(**
This module contains a IDE derived dockable form to contain the results of the
searches where the IDE cannot provide help.
@Version 1.0
@Author David Hoyle
@Date 19 Apr 2016
**)
Unit DockableBrowserForm;
Interface
Uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
OleCtrls,
SHDocVw,
DockForm,
StdCtrls,
Buttons,
ToolWin,
ComCtrls,
ActnList,
ImgList,
WebBrowserFrame;
Type
(** This class is a IDE dockable form for the results of the internet searches. **)
TfrmDockableBrowser = Class(TDockableForm)
Strict private
FWebBrowser: TfmWebBrowser;
Private
{Private declarations}
Public
{Public declarations}
Constructor Create(AOwner : TComponent); Override;
Destructor Destroy; Override;
Class Procedure Execute(strURL : String);
Class Procedure RemoveDockableBrowser;
Class Procedure CreateDockableBrowser;
Class Procedure ShowDockableBrowser;
Procedure Focus;
Function CurrentURL : String;
End;
(** This is a type to define a class of the dockable for required for the
registration. **)
TfrmDockableBrowserClass = Class Of TfrmDockableBrowser;
Implementation
{$R *.dfm}
Uses
DeskUtil,
ApplicationsOptions;
Var
(** This is a private varaible to hold the singleton instance of the
dockable form. **)
FormInstance : TfrmDockableBrowser;
(**
This procedure makes the dockable module explorer visible.
@precon None.
@postcon Makes the dockable module explorer visible.
@param Form as a TfrmDockableBrowser
**)
Procedure ShowDockableForm(Form : TfrmDockableBrowser);
Begin
If Not Assigned(Form) Then
Exit;
If Not Form.Floating Then
Begin
Form.ForceShow;
FocusWindow(Form);
Form.Focus;
End Else
Begin
Form.Show;
Form.Focus;
End;
If Form.Visible And (Form.CurrentURL = '') And (AppOptions.PermanentURLs.Count > 0) Then
Form.Execute(AppOptions.PermanentURLs[0]);
End;
(**
This procedure registers the dockable form with the IDE.
@precon None.
@postcon The dockable form is registered with the IDE.
@param FormClass as a TfrmDockableBrowserClass
@param FormVar
@param FormName as a String as a constant
**)
Procedure RegisterDockableForm(FormClass : TfrmDockableBrowserClass; var FormVar;
Const FormName : String);
Begin
If @RegisterFieldAddress <> Nil Then
RegisterFieldAddress(FormName, @FormVar);
RegisterDesktopFormClass(FormClass, FormName, FormName);
End;
(**
This method unregisters the dockable form with the IDE.
@precon None.
@postcon The dockable form is unregistered with the IDE.
@param FormVar
@param FormName as a String as a constant
**)
Procedure UnRegisterDockableForm(var FormVar; Const FormName : String);
Begin
If @UnRegisterFieldAddress <> Nil Then
UnregisterFieldAddress(@FormVar);
End;
(**
This procedure creates an instance of the dockable form.
@precon FormVar is the instance reference and FormCass is the type of class
to be created..
@postcon The form instance is created.
@param FormVar as a TfrmDockableBrowser as a reference
@param FormClass as a TfrmDockableBrowserClass
**)
Procedure CreateDockableForm(var FormVar : TfrmDockableBrowser;
FormClass : TfrmDockableBrowserClass);
Begin
TCustomForm(FormVar) := FormClass.Create(Nil);
RegisterDockableform(FormClass, FormVar, TCustomForm(FormVar).Name);
End;
(**
This procedure frees the instance of the dockable form.
@precon None.
@postcon Free the instance of the dockable form.
@param FormVar as a TfrmDockableBrowser as a reference
**)
Procedure FreeDockableForm(var FormVar : TfrmDockableBrowser);
Begin
If Assigned(FormVar) Then
Begin
UnRegisterDockableForm(FormVar, FormVar.Name);
FreeAndNil(FormVar);
End;
End;
{ TfrmDockableBrowser }
(**
This is the constructor method for the TfrmDockableModuleExplorer class.
@precon None.
@postcon Sets the dockable form up for being saved within the BDS 2006 IDE and
then creates a Module Explorer Frame and places inside the form.
@param AOwner as a TComponent
**)
constructor TfrmDockableBrowser.Create(AOwner: TComponent);
begin
inherited;
DeskSection := Name;
AutoSave := True;
SaveStateNecessary := True;
FWebBrowser := TfmWebBrowser.Create(Self);
FWebBrowser.Parent := Self;
FWebBrowser.Align := alClient;
end;
(**
This is the destructor method for the TfrmDockableModuleExplorer class.
@precon None.
@postcon Destroys the Module Explorer Frame and ensures the desktop is saved.
**)
destructor TfrmDockableBrowser.Destroy;
begin
SaveStateNecessary := True;
inherited;
end;
(**
This method focuses the modukle explorers tree view the be focused IF
available.
@precon None.
@postcon Focuses the modukle explorers tree view the be focused IF available.
**)
procedure TfrmDockableBrowser.Focus;
begin
FormInstance.SetFocus;
end;
(**
This is a class method to create the dockable form instance.
@precon None.
@postcon The form instance is created if one is not already present.
**)
class procedure TfrmDockableBrowser.CreateDockableBrowser;
begin
If Not Assigned(FormInstance) Then
CreateDockableForm(FormInstance, TfrmDockableBrowser);
end;
(**
This method returns the current URL of the browser frame.
@precon None.
@postcon The current URL of the browser is returned.
@return a String
**)
Function TfrmDockableBrowser.CurrentURL: String;
Begin
Result := FWebBrowser.CurrentURL;
End;
(**
This is a class method to remove the dockable form.
@precon None.
@postcon Removes the instance of the dockable form.
**)
class procedure TfrmDockableBrowser.RemoveDockableBrowser;
begin
FreeDockableForm(FormInstance);
end;
(**
This method is a class method for displaying the dockable form. If the form
does not already exist it is created first.
@precon None.
@postcon Displays the dockable form.
**)
class procedure TfrmDockableBrowser.ShowDockableBrowser;
begin
CreateDockableBrowser;
ShowDockableForm(FormInstance);
end;
(**
This is th forms main method for displaying the results of the given URL.
@precon None.
@postcon If the form exists (which it should) the web browser is asked to render the
given URL.
@param strURL as a String
**)
Class Procedure TfrmDockableBrowser.Execute(strURL: String);
Begin
If Assigned(FormInstance) Then
Begin
FormInstance.FWebBrowser.Navigate(strURL);
If Not FormInstance.Floating Then //: @refactor Refactor with ShowDockableForm().
Begin
FormInstance.ForceShow;
FocusWindow(FormInstance);
FormInstance.Focus;
End Else
Begin
FormInstance.Show;
FormInstance.Focus;
End;
End;
End;
End.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.StdCtrls,
FMX.Objects, FMX.Platform.iOS, FMX.Layouts, FMX.Memo, FMX.ListBox,
libzbar;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
ToolBar2: TToolBar;
swtONOFF: TSwitch;
butClear: TButton;
Label1: TLabel;
edtResult: TEdit;
btnCopy: TButton;
memImage: TMemo;
lstHistory: TListBox;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure swtONOFFSwitch(Sender: TObject);
procedure butClearClick(Sender: TObject);
procedure btnCopyClick(Sender: TObject);
private
{ Private declarations }
ZBarCode: TZBarCode;
procedure OnFindBarCode(Sender: TObject; BarCode: String);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
uses iOSapi.CoreGraphics;
procedure TMainForm.butClearClick(Sender: TObject);
begin
edtResult.Text := '';
lstHistory.Items.Clear;
end;
procedure TMainForm.btnCopyClick(Sender: TObject);
begin
edtResult.SelectAll;
edtResult.CopyToClipboard;
end;
procedure TMainForm.OnFindBarCode(Sender: TObject; BarCode: String);
begin
edtResult.Text := BarCode;
lstHistory.Items.Add(FormatDateTime('dd/mm/yyyy hh:nn:ss', Now) + ' - ' + BarCode);
end;
procedure TMainForm.swtONOFFSwitch(Sender: TObject);
begin
if not Assigned(ZBarCode) then
begin
ZBarCode := TZBarCode.Create;
ZBarCode.OnBarCode := OnFindBarCode;
ZBarCode.setFrame(WindowHandleToPlatform(Self.Handle).View,
CGRectMake(memImage.Position.X, memImage.Position.Y, memImage.Width,
memImage.Height));
end;
ZBarCode.Active := swtONOFF.IsChecked;
end;
end.
|
{ GDAX/Coinbase-Pro client library
Copyright (c) 2018 mr-highball
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
unit gdax.api.consts;
{$i gdax.inc}
interface
uses
Classes, SysUtils;
type
TGDAXApi = (gdSand,gdProd);
TGDAXApis = set of TGDAXApi;
TGDAXBookLevel = (blOne=1,blTwo=2,blThree=3);
TGDAXBookLevels = set of TGDAXBookLevel;
TRestOperation = (roGet,roPost,roDelete);
TRestOperations = set of TRestOperation;
(*
1:1 relation to corresponding string arrays
*)
TOrderType = (otMarket,otLimit,otUnknown);
TOrderTypes = set of TOrderType;
TOrderSide = (osBuy,osSell,osUnknown);
TOrderSides = set of TOrderSide;
TOrderStatus = (stPending,stOpen,stActive,stSettled,stDone,stRejected,stCancelled,stUnknown);
TOrderStatuses = set of TOrderStatus;
TMarketType = (mtBuyers,mtSellers,mtUnknown);
TMarketTypes = set of TMarketType;
TLedgerType = (ltTransfer,ltMatch,ltFee,ltRebate);
TledgerTypes = set of TLedgerType;
(*
helper methods
*)
function BuildFullEndpoint(Const AResource:String; Const AMode:TGDAXApi):String;
function OrderTypeToString(Const AType:TOrderType):String;
function StringToOrderType(Const AType:String):TOrderType;
function OrderSideToString(Const ASide:TOrderSide):String;
function StringToOrderSide(Const ASide:String):TOrderSide;
function OrderStatusToString(Const AStatus:TOrderStatus):String;
function StringToOrderStatus(Const AStatus:String):TOrderStatus;
function LedgerTypeToString(Const AType:TLedgerType):String;
function StringToLedgerType(Const AType:String):TLedgerType;
const
//maximum requests per second to the public REST API endpoints
GDAX_PUBLIC_REQUESTS_PSEC = 3;
//maximum requests per second to the public REST API endpoints
GDAX_PRIVATE_REQUESTS_PSEC = 5;
//https://docs.gdax.com/?python#api
GDAX_END_API_BASE = 'https://api.pro.coinbase.com';//'https://api.gdax.com';
//https://docs.gdax.com/?python#sandbox
GDAX_END_API_BASE_SAND = 'https://api-public.sandbox.pro.coinbase.com';//'https://api-public.sandbox.gdax.com';
//https://docs.gdax.com/?python#list-accounts
GDAX_END_API_ACCTS = '/accounts';
//https://docs.gdax.com/?python#get-an-account
GDAX_END_API_ACCT = GDAX_END_API_ACCTS+'/%s';
//https://docs.gdax.com/?python#get-account-history
GDAX_END_API_ACCT_HIST = GDAX_END_API_ACCT+'/ledger';
//https://docs.gdax.com/?python#get-holds
GDAX_END_API_ACCT_HOLD = GDAX_END_API_ACCT+'/holds';
//https://docs.gdax.com/?python#orders (post)
GDAX_END_API_ORDERS = '/orders';
GDAX_END_API_ORDER = GDAX_END_API_ORDERS+'/%s';
//https://docs.gdax.com/?python#fills
GDAX_END_API_FILLS = '/fills';
//https://docs.gdax.com/#selecting-a-timestamp
GDAX_END_API_TIME = '/time';
//https://docs.gdax.com/#get-product-order-book
GDAX_END_API_PRODUCT = '/products';
GDAX_END_API_PRODUCTS = GDAX_END_API_PRODUCT+'/%s';
GDAX_END_API_BOOK = GDAX_END_API_PRODUCTS+'/book?level=%d';
GDAX_END_API_TICKER = GDAX_END_API_PRODUCTS+'/ticker';
GDAX_END_API_CANDLES = GDAX_END_API_PRODUCTS+'/candles';
//https://docs.pro.coinbase.com/#currencies
GDAX_END_API_CURRENCIES = '/currencies';
//header names for gdax authentication
CB_ACCESS_KEY = 'CB-ACCESS-KEY';
CB_ACCESS_SIGN = 'CB-ACCESS-SIGN';
CB_ACCESS_TIME = 'CB-ACCESS-TIMESTAMP';
CB_ACCESS_PASS = 'CB-ACCESS-PASSPHRASE';
//header names and url consts for pagination
CB_BEFORE = 'CB-BEFORE';
CB_AFTER = 'CB-AFTER';
URL_PAGE_BEFORE = 'before';
URL_PAGE_AFTER = 'after';
URL_PAGE_LIMIT = 'limit';
//Order types that can be made
ORDER_TYPES : array [0..1] of string = (
'market',
'limit'
);
//which side, buy or sell, this order falls on (or is posted on)
ORDER_SIDES : array[0..1] of string = (
'buy',
'sell'
);
ORDER_STATUS : array[0..6] of string = (
'pending',
'open',
'active',
'settled',
'done',
'rejected',
'cancelled'
);
//types of entries for the account history endpoint (ledger)
LEDGER_TYPES : array[0..3] of string = (
'transfer',
'match',
'fee',
'rebate'
);
//rest operations expanded text
OP_POST = 'POST';
OP_GET = 'GET';
OP_DELETE = 'DELETE';
USER_AGENT_MOZILLA = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0';
E_UNSUPPORTED = '%s operation unsupported in class %s';
E_BADJSON = 'bad json format';
E_BADJSON_PROP = 'property %s cannot be found';
E_UNKNOWN = '%s is unknown in %s';
E_INVALID = '%s is invalid, must be %s';
E_NOT_IMPL = '%s is not implemented in %s';
implementation
function BuildFullEndpoint(Const AResource:String; Const AMode:TGDAXApi):String;
begin
if AMode=gdSand then
Result := GDAX_END_API_BASE_SAND+AResource
else
Result := GDAX_END_API_BASE+AResource;
end;
function StringToOrderStatus(Const AStatus:String):TOrderStatus;
var
I: Integer;
begin
Result := stUnknown;
for I := Low(ORDER_STATUS) to High(ORDER_STATUS) do
if LowerCase(ORDER_STATUS[I])=LowerCase(AStatus) then
begin
Result := TOrderStatus(I);
Exit;
end;
end;
function LedgerTypeToString(Const AType: TLedgerType): String;
begin
Result:='';
if Ord(AType)<=High(LEDGER_TYPES) then
Result := LEDGER_TYPES[Ord(AType)];
end;
function StringToLedgerType(Const AType: String): TLedgerType;
var
I: Integer;
begin
Result := ltTransfer;
for I := Low(LEDGER_TYPES) to High(LEDGER_TYPES) do
if LowerCase(LEDGER_TYPES[I])=LowerCase(AType) then
begin
Result := TLedgerType(I);
Exit;
end;
end;
function StringToOrderSide(Const ASide:String):TOrderSide;
var
I: Integer;
begin
Result := osUnknown;
for I := Low(ORDER_SIDES) to High(ORDER_SIDES) do
if LowerCase(ORDER_SIDES[I])=LowerCase(ASide) then
begin
Result := TOrderSide(I);
Exit;
end;
end;
function StringToOrderType(Const AType:String):TOrderType;
var
I: Integer;
begin
Result := otUnknown;
for I := Low(ORDER_TYPES) to High(ORDER_TYPES) do
if LowerCase(ORDER_TYPES[I])=LowerCase(AType) then
begin
Result := TOrderType(I);
Exit;
end;
end;
function OrderStatusToString(Const AStatus:TOrderStatus):String;
begin
Result:='';
if AStatus=stUnknown then
Exit;
Result := ORDER_STATUS[Ord(AStatus)];
end;
function OrderSideToString(Const ASide:TOrderSide):String;
begin
Result:='';
if ASide=osUnknown then
Exit;
Result := ORDER_SIDES[Ord(ASide)];
end;
function OrderTypeToString(Const AType:TOrderType):String;
begin
Result:='';
if AType=otUnknown then
Exit;
Result := ORDER_TYPES[Ord(AType)];
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
HMAC specification on the NIST website
http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf
}
unit IdHMAC;
interface
uses
IdGlobal, IdObjs, IdSys, IdHash;
type
TIdHMACKeyBuilder = class(TIdBaseObject)
public
class function Key(const ASize: Integer) : TIdBytes;
class function IV(const ASize: Integer) : TIdBytes;
end;
TIdHMAC = class
private
protected
FHashSize: Integer; // n bytes
FBlockSize: Integer; // n bytes
FKey: TIdBytes;
FHash: TIdHash;
FHashName: string;
procedure InitHash; virtual; abstract;
procedure InitKey;
function InternalHashValue(const ABuffer: TIdBytes) : TIdBytes; virtual; abstract;
public
constructor Create; virtual;
destructor Destroy; override;
function HashValue(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1) : TIdBytes; // for now, supply in bytes
property HashSize: Integer read FHashSize;
property BlockSize: Integer read FBlockSize;
property HashName: string read FHashName;
property Key: TIdBytes read FKey write FKey;
end;
implementation
{ TIdHMACKeyBuilder }
class function TIdHMACKeyBuilder.Key(const ASize: Integer): TIdBytes;
var
I: Integer;
begin
SetLength(Result, ASize);
for I := Low(Result) to High(Result) do
begin
Result[I] := Byte(Random(255));
end;
end;
class function TIdHMACKeyBuilder.IV(const ASize: Integer): TIdBytes;
var
I: Integer;
begin
SetLength(Result, ASize);
for I := Low(Result) to High(Result) do
begin
Result[I] := Byte(Random(255));
end;
end;
{ TIdHMAC }
constructor TIdHMAC.Create;
begin
inherited;
SetLength(FKey, 0);
InitHash;
end;
destructor TIdHMAC.Destroy;
begin
Sys.FreeAndNil(FHash);
inherited;
end;
function TIdHMAC.HashValue(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1): TIdBytes;
const
CInnerPad : Byte = $36;
COuterPad : Byte = $5C;
var
TempBuffer1: TIdBytes;
TempBuffer2: TIdBytes;
LKey: TIdBytes;
I: Integer;
begin
InitKey;
LKey := Copy(FKey, 0, MaxInt);
SetLength(LKey, FBlockSize);
SetLength(TempBuffer1, FBlockSize + Length(ABuffer));
for I := Low(LKey) to High(LKey) do
begin
TempBuffer1[I] := LKey[I] xor CInnerPad;
end;
CopyTIdBytes(ABuffer, 0, TempBuffer1, Length(LKey), Length(ABuffer));
TempBuffer2 := InternalHashValue(TempBuffer1);
SetLength(TempBuffer1, 0);
SetLength(TempBuffer1, FBlockSize + FHashSize);
for I := Low(LKey) to High(LKey) do
begin
TempBuffer1[I] := LKey[I] xor COuterPad;
end;
CopyTIdBytes(TempBuffer2, 0, TempBuffer1, Length(LKey), Length(TempBuffer2));
Result := InternalHashValue(TempBuffer1);
SetLength(TempBuffer1, 0);
SetLength(TempBuffer2, 0);
SetLength(LKey, 0);
if ATruncateTo > -1 then
begin
SetLength(Result, ATruncateTo);
end;
end;
procedure TIdHMAC.InitKey;
begin
if FKey = nil then
begin
TIdHMACKeyBuilder.Key(FHashSize);
end
else
begin
if Length(FKey) > FBlockSize then
begin
FKey := InternalHashValue(FKey);
end;
end;
end;
initialization
Randomize;
end.
|
unit TestAvoidanceZoneSamplesUnit;
interface
uses
TestFramework, Classes, SysUtils,
BaseTestOnlineExamplesUnit;
type
TTestAvoidanceZoneSamples = class(TTestOnlineExamples)
published
procedure AddCircleAvoidanceZone;
procedure AddPolygonAvoidanceZone;
procedure AddRectangularAvoidanceZone;
procedure GetAvoidanceZones;
procedure GetAvoidanceZone;
procedure UpdateAvoidanceZone;
procedure RemoveAvoidanceZone;
end;
implementation
uses NullableBasicTypesUnit, TerritoryContourUnit, AvoidanceZoneUnit,
PositionUnit;
var
FAvoidanceZone: TAvoidanceZone;
FAvoidanceZoneIds: TArray<String>;
procedure AddAvoidanceZoneId(Id: NullableString);
begin
if (Id.IsNotNull) then
begin
SetLength(FAvoidanceZoneIds, Length(FAvoidanceZoneIds) + 1);
FAvoidanceZoneIds[High(FAvoidanceZoneIds)] := Id;
end;
end;
procedure TTestAvoidanceZoneSamples.AddCircleAvoidanceZone;
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
Parameters: TAvoidanceZone;
TerritoryName, TerritoryColor: String;
Territory: TTerritoryContour;
begin
TerritoryName := 'Circle Territory';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakeCircleContour(
37.5697528227865, -77.4783325195313, 5000);
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
FAvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
CheckNotNull(AvoidanceZone);
CheckTrue(FAvoidanceZone.TerritoryId.IsNotNull);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Parameters);
end;
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, nil);
try
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
try
CheckNull(AvoidanceZone);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
finally
FreeAndNil(Parameters);
end;
TerritoryName := '';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakeCircleContour(
37.5697528227865, -77.4783325195313, 5000);
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
try
CheckNull(AvoidanceZone);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
finally
FreeAndNil(Parameters);
end;
end;
procedure TTestAvoidanceZoneSamples.AddPolygonAvoidanceZone;
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
Parameters: TAvoidanceZone;
TerritoryName, TerritoryColor: String;
Territory: TTerritoryContour;
begin
TerritoryName := 'Polygon Territory';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakePolygonContour([
TPosition.Create(37.76975282278,-77.67833251953),
TPosition.Create(37.75886716305,-77.68974800109),
TPosition.Create(37.74763966054,-77.69172210693)
]);
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
try
CheckNotNull(AvoidanceZone);
AddAvoidanceZoneId(AvoidanceZone.TerritoryId);
CheckTrue(AvoidanceZone.TerritoryId.IsNotNull);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
finally
FreeAndNil(Parameters);
end;
TerritoryName := 'Polygon Territory';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakePolygonContour([
TPosition.Create(37.76975282278,-77.67833251953),
TPosition.Create(37.75886716305,-77.68974800109)
]);
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
try
CheckNotNull(AvoidanceZone);
AddAvoidanceZoneId(AvoidanceZone.TerritoryId);
CheckTrue(AvoidanceZone.TerritoryId.IsNotNull);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
finally
FreeAndNil(Parameters);
end;
TerritoryName := 'Polygon Territory';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakePolygonContour([
TPosition.Create(37.76975282278,-77.67833251953)
]);
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
try
CheckNotNull(AvoidanceZone);
AddAvoidanceZoneId(AvoidanceZone.TerritoryId);
CheckTrue(AvoidanceZone.TerritoryId.IsNotNull);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
finally
FreeAndNil(Parameters);
end;
end;
procedure TTestAvoidanceZoneSamples.AddRectangularAvoidanceZone;
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
Parameters: TAvoidanceZone;
TerritoryName, TerritoryColor: String;
Territory: TTerritoryContour;
begin
TerritoryName := 'Rect Territory';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakeRectangularContour(
43.51668853502909, -109.3798828125, 46.98025235521883, -101.865234375);
Parameters := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Add(Parameters, ErrorString);
try
CheckNotNull(AvoidanceZone);
AddAvoidanceZoneId(AvoidanceZone.TerritoryId);
CheckTrue(AvoidanceZone.TerritoryId.IsNotNull);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
finally
FreeAndNil(Parameters);
end;
end;
procedure TTestAvoidanceZoneSamples.GetAvoidanceZone;
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
begin
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Get('-123', ErrorString);
try
CheckNull(AvoidanceZone);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Get(
FAvoidanceZone.TerritoryId, ErrorString);
try
CheckNotNull(AvoidanceZone);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone);
end;
end;
procedure TTestAvoidanceZoneSamples.GetAvoidanceZones;
var
ErrorString: String;
AvoidanceZones: TAvoidanceZoneList;
begin
AvoidanceZones := FRoute4MeManager.AvoidanceZone.GetList(ErrorString);
try
CheckNotNull(AvoidanceZones);
CheckTrue(AvoidanceZones.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZones);
end;
end;
procedure TTestAvoidanceZoneSamples.RemoveAvoidanceZone;
var
ErrorString: String;
begin
CheckTrue(FRoute4MeManager.AvoidanceZone.Remove('-123', ErrorString));
CheckEquals(EmptyStr, ErrorString);
CheckTrue(FRoute4MeManager.AvoidanceZone.Remove(FAvoidanceZone.TerritoryId, ErrorString));
CheckEquals(EmptyStr, ErrorString);
CheckTrue(FRoute4MeManager.AvoidanceZone.Remove(FAvoidanceZoneIds, ErrorString));
CheckEquals(EmptyStr, ErrorString);
FreeAndNil(FAvoidanceZone);
end;
procedure TTestAvoidanceZoneSamples.UpdateAvoidanceZone;
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
Id: String;
begin
FAvoidanceZone.TerritoryName := 'New name';
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Update(FAvoidanceZone, ErrorString);
try
CheckNotNull(AvoidanceZone);
CheckEquals(EmptyStr, ErrorString);
CheckEquals('New name', AvoidanceZone.TerritoryName);
finally
FreeAndNil(AvoidanceZone)
end;
Id := FAvoidanceZone.TerritoryId;
FAvoidanceZone.TerritoryId := NullableString.Null;
try
FAvoidanceZone.TerritoryName := 'Error';
AvoidanceZone := FRoute4MeManager.AvoidanceZone.Update(FAvoidanceZone, ErrorString);
try
CheckNull(AvoidanceZone);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(AvoidanceZone)
end;
finally
FAvoidanceZone.TerritoryId := Id;
end;
end;
initialization
RegisterTest('Examples\Online\AvoidanceZone\', TTestAvoidanceZoneSamples.Suite);
SetLength(FAvoidanceZoneIds, 0);
end.
|
// Client and Server common constants
unit CommonConstants;
interface
const
// Client/Server Command() interface codes
// Server-side codes
cmdGetDir = 0; // get server-side directory contents to the client
cmdSetSingleUserMode = 1;
cmdSetSingleUserMode_res_NotOwner = 1; // singleuser mode is already set and we are not the owner
cmdSetSingleUserMode_res_NotAlone = 2; // multiple users connected already
cmdSetServerDebugLevel = 2; // param < 0 to query current dlevel
cmdGetServerSysInfo = 3;
cmdMaxCmdID = 3;
//---------------------------------------------------------------------------
// client-side command codes
// cmdID constants for processCommand()
// here is internal ones. Prefixed cltI
cltIcmdWebCatRefresh = 0; // refreshes web category tree node by id. need treeID and nodeID (ignored for now-refreshes whole trees only)
implementation
end.
|
{
Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit LogViewer.Receivers.WinIPC;
{ WinIPC channel receiver. }
interface
uses
System.Classes,
Vcl.ExtCtrls,
Spring,
DDuce.WinIPC.Server,
LogViewer.Receivers.Base, LogViewer.Interfaces, LogViewer.WinIPC.Settings;
{$REGION 'documentation'}
{ Receives logmessages through WinIPC (WM_COPYDATA) messages.
The communication with the message source is synchronous, so when the source
application sends a message, it blocks until it is received by the receiver.
REMARK:
- the sending application and the logviewer need to be started with the same
windows user credentials.
}
{ TODO : Notification when a ProcessId/ProcessName does not exist anymore }
{$ENDREGION}
type
TWinIPCChannelReceiver = class(TChannelReceiver, IChannelReceiver, IWinIPC)
private
FIPCServer : TWinIPCServer;
protected
{$REGION 'property access methods'}
function GetWindowName: string;
function GetMsgWindowClassName: string;
function GetSettings: TWinIPCSettings;
procedure SetEnabled(const Value: Boolean); override;
{$ENDREGION}
procedure FIPCServerMessage(
Sender : TObject;
ASourceId : UInt32;
AData : TStream
);
function CreateSubscriber(
ASourceId : UInt32;
AThreadId : UInt32;
const ASourceName : string
): ISubscriber; override;
procedure SettingsChanged(Sender: TObject);
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
property Settings: TWinIPCSettings
read GetSettings;
property WindowName: string
read GetWindowName;
property MsgWindowClassName: string
read GetMsgWindowClassName;
end;
implementation
uses
System.SysUtils,
DDuce.Utils, DDuce.Utils.Winapi, DDuce.Logger,
LogViewer.Subscribers.WinIPC;
{$REGION 'construction and destruction'}
procedure TWinIPCChannelReceiver.AfterConstruction;
begin
inherited AfterConstruction;
FIPCServer := TWinIPCServer.Create;
FIPCServer.OnMessage := FIPCServerMessage;
FIPCServer.Active := True;
Settings.OnChanged.Add(SettingsChanged);
end;
procedure TWinIPCChannelReceiver.BeforeDestruction;
begin
FIPCServer.Active := False;
FIPCServer.Free;
inherited BeforeDestruction;
end;
function TWinIPCChannelReceiver.CreateSubscriber(ASourceId, AThreadId: UInt32;
const ASourceName: string): ISubscriber;
begin
Result := TWinIPCSubscriber.Create(Self, ASourceId, '', ASourceName, True);
end;
{$ENDREGION}
{$REGION 'property access methods'}
procedure TWinIPCChannelReceiver.SetEnabled(const Value: Boolean);
begin
inherited SetEnabled(Value);
if Value then
FIPCServer.OnMessage := FIPCServerMessage
else
FIPCServer.OnMessage := nil;
FIPCServer.Active := Value;
end;
function TWinIPCChannelReceiver.GetMsgWindowClassName: string;
begin
Result := FIPCServer.MsgWindowClassName;
end;
function TWinIPCChannelReceiver.GetSettings: TWinIPCSettings;
begin
Result := Manager.Settings.WinIPCSettings;
end;
function TWinIPCChannelReceiver.GetWindowName: string;
begin
Result := FIPCServer.WindowName;
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TWinIPCChannelReceiver.FIPCServerMessage(Sender: TObject;
ASourceId: UInt32; AData: TStream);
var
LProcessName : string;
begin
if not Processes.TryGetValue(ASourceId, LProcessName) then
begin
LProcessName := GetExenameForProcess(ASourceId);
Processes.AddOrSetValue(ASourceId, LProcessName);
end;
DoReceiveMessage(AData, ASourceId, 0, LProcessName);
end;
procedure TWinIPCChannelReceiver.SettingsChanged(Sender: TObject);
begin
Enabled := Settings.Enabled;
end;
{$ENDREGION}
end.
|
unit FromWithPanelKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы FromWithPanel }
// Модуль: "w:\common\components\gui\Garant\Daily\Forms\FromWithPanelKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "FromWithPanelKeywordsPack" MUID: (51D534260378_Pack)
{$Include w:\common\components\gui\sdotDefine.inc}
interface
{$If Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, FromWithPanel_Form
, tfwPropertyLike
, vtPanel
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *51D534260378_Packimpl_uses*
//#UC END# *51D534260378_Packimpl_uses*
;
type
TkwFromWithPanelFormWorkSpace = {final} class(TtfwPropertyLike)
{* Слово скрипта .TFromWithPanelForm.WorkSpace }
private
function WorkSpace(const aCtx: TtfwContext;
aFromWithPanelForm: TFromWithPanelForm): TvtPanel;
{* Реализация слова скрипта .TFromWithPanelForm.WorkSpace }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwFromWithPanelFormWorkSpace
Tkw_Form_FromWithPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы FromWithPanel
----
*Пример использования*:
[code]форма::FromWithPanel TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_FromWithPanel
Tkw_FromWithPanel_Control_WorkSpace = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола WorkSpace
----
*Пример использования*:
[code]контрол::WorkSpace TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_FromWithPanel_Control_WorkSpace
Tkw_FromWithPanel_Control_WorkSpace_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола WorkSpace
----
*Пример использования*:
[code]контрол::WorkSpace:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_FromWithPanel_Control_WorkSpace_Push
function TkwFromWithPanelFormWorkSpace.WorkSpace(const aCtx: TtfwContext;
aFromWithPanelForm: TFromWithPanelForm): TvtPanel;
{* Реализация слова скрипта .TFromWithPanelForm.WorkSpace }
begin
Result := aFromWithPanelForm.WorkSpace;
end;//TkwFromWithPanelFormWorkSpace.WorkSpace
class function TkwFromWithPanelFormWorkSpace.GetWordNameForRegister: AnsiString;
begin
Result := '.TFromWithPanelForm.WorkSpace';
end;//TkwFromWithPanelFormWorkSpace.GetWordNameForRegister
function TkwFromWithPanelFormWorkSpace.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwFromWithPanelFormWorkSpace.GetResultTypeInfo
function TkwFromWithPanelFormWorkSpace.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwFromWithPanelFormWorkSpace.GetAllParamsCount
function TkwFromWithPanelFormWorkSpace.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TFromWithPanelForm)]);
end;//TkwFromWithPanelFormWorkSpace.ParamsTypes
procedure TkwFromWithPanelFormWorkSpace.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству WorkSpace', aCtx);
end;//TkwFromWithPanelFormWorkSpace.SetValuePrim
procedure TkwFromWithPanelFormWorkSpace.DoDoIt(const aCtx: TtfwContext);
var l_aFromWithPanelForm: TFromWithPanelForm;
begin
try
l_aFromWithPanelForm := TFromWithPanelForm(aCtx.rEngine.PopObjAs(TFromWithPanelForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aFromWithPanelForm: TFromWithPanelForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(WorkSpace(aCtx, l_aFromWithPanelForm));
end;//TkwFromWithPanelFormWorkSpace.DoDoIt
function Tkw_Form_FromWithPanel.GetString: AnsiString;
begin
Result := 'FromWithPanelForm';
end;//Tkw_Form_FromWithPanel.GetString
class procedure Tkw_Form_FromWithPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TFromWithPanelForm);
end;//Tkw_Form_FromWithPanel.RegisterInEngine
class function Tkw_Form_FromWithPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::FromWithPanel';
end;//Tkw_Form_FromWithPanel.GetWordNameForRegister
function Tkw_FromWithPanel_Control_WorkSpace.GetString: AnsiString;
begin
Result := 'WorkSpace';
end;//Tkw_FromWithPanel_Control_WorkSpace.GetString
class procedure Tkw_FromWithPanel_Control_WorkSpace.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_FromWithPanel_Control_WorkSpace.RegisterInEngine
class function Tkw_FromWithPanel_Control_WorkSpace.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::WorkSpace';
end;//Tkw_FromWithPanel_Control_WorkSpace.GetWordNameForRegister
procedure Tkw_FromWithPanel_Control_WorkSpace_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('WorkSpace');
inherited;
end;//Tkw_FromWithPanel_Control_WorkSpace_Push.DoDoIt
class function Tkw_FromWithPanel_Control_WorkSpace_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::WorkSpace:push';
end;//Tkw_FromWithPanel_Control_WorkSpace_Push.GetWordNameForRegister
initialization
TkwFromWithPanelFormWorkSpace.RegisterInEngine;
{* Регистрация FromWithPanelForm_WorkSpace }
Tkw_Form_FromWithPanel.RegisterInEngine;
{* Регистрация Tkw_Form_FromWithPanel }
Tkw_FromWithPanel_Control_WorkSpace.RegisterInEngine;
{* Регистрация Tkw_FromWithPanel_Control_WorkSpace }
Tkw_FromWithPanel_Control_WorkSpace_Push.RegisterInEngine;
{* Регистрация Tkw_FromWithPanel_Control_WorkSpace_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TFromWithPanelForm));
{* Регистрация типа TFromWithPanelForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
unit caPriorityCalculator;
// Модуль: "w:\common\components\rtl\Garant\ComboAccess\caPriorityCalculator.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TcaPriorityCalculator" MUID: (5751293D00A9)
{$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc}
interface
{$If Defined(UsePostgres) AND Defined(TestComboAccess)}
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, daTypes
;
type
TcaPriorityCalculator = class(Tl3ProtoObject, IdaPriorityCalculator)
private
f_HTCalculator: IdaPriorityCalculator;
f_PGCalculator: IdaPriorityCalculator;
protected
function Calc(aUserId: TdaUserID;
out aImportPriority: TdaPriority;
out aExportPriority: TdaPriority): Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aHTCalculator: IdaPriorityCalculator;
const aPGCalculator: IdaPriorityCalculator); reintroduce;
class function Make(const aHTCalculator: IdaPriorityCalculator;
const aPGCalculator: IdaPriorityCalculator): IdaPriorityCalculator; reintroduce;
end;//TcaPriorityCalculator
{$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess)
implementation
{$If Defined(UsePostgres) AND Defined(TestComboAccess)}
uses
l3ImplUses
//#UC START# *5751293D00A9impl_uses*
//#UC END# *5751293D00A9impl_uses*
;
constructor TcaPriorityCalculator.Create(const aHTCalculator: IdaPriorityCalculator;
const aPGCalculator: IdaPriorityCalculator);
//#UC START# *5751296703D0_5751293D00A9_var*
//#UC END# *5751296703D0_5751293D00A9_var*
begin
//#UC START# *5751296703D0_5751293D00A9_impl*
inherited Create;
f_HTCalculator := aHTCalculator;
f_PGCalculator := aPGCalculator;
//#UC END# *5751296703D0_5751293D00A9_impl*
end;//TcaPriorityCalculator.Create
class function TcaPriorityCalculator.Make(const aHTCalculator: IdaPriorityCalculator;
const aPGCalculator: IdaPriorityCalculator): IdaPriorityCalculator;
var
l_Inst : TcaPriorityCalculator;
begin
l_Inst := Create(aHTCalculator, aPGCalculator);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TcaPriorityCalculator.Make
function TcaPriorityCalculator.Calc(aUserId: TdaUserID;
out aImportPriority: TdaPriority;
out aExportPriority: TdaPriority): Boolean;
//#UC START# *575000000164_5751293D00A9_var*
var
l_ImportPriority: TdaPriority;
l_ExportPriority: TdaPriority;
//#UC END# *575000000164_5751293D00A9_var*
begin
//#UC START# *575000000164_5751293D00A9_impl*
Result := f_HTCalculator.Calc(aUserID, aImportPriority, aExportPriority);
Assert(Result = f_PGCalculator.Calc(aUserID, l_ImportPriority, l_ExportPriority));
if Result then
Assert((aImportPriority = l_ImportPriority) and (aExportPriority = l_ExportPriority));
//#UC END# *575000000164_5751293D00A9_impl*
end;//TcaPriorityCalculator.Calc
procedure TcaPriorityCalculator.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_5751293D00A9_var*
//#UC END# *479731C50290_5751293D00A9_var*
begin
//#UC START# *479731C50290_5751293D00A9_impl*
f_HTCalculator := nil;
f_PGCalculator := nil;
inherited;
//#UC END# *479731C50290_5751293D00A9_impl*
end;//TcaPriorityCalculator.Cleanup
{$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess)
end.
|
unit SearchOptionManager;
interface
uses
SearchOption, DBManager, SearchResult;
type
TSearchOptionManager = class(TSearchOption)
private
FDBMS: TAbsDBManager;
protected
function GetDBMSName: String; override;
procedure SetDBMSName(dbms: String); override;
public
procedure SetDBManager(dbm: TAbsDBManager);
function GetSearchResult: TSearchResultSet;
end;
implementation
uses
MsSqlDBManager, FireBirdDBManager;
{ TSearchOptionManager }
function TSearchOptionManager.GetDBMSName: String;
begin
if FDBMS <> nil then
result := FDBMS.GetDBMSName
else
result := '';
end;
function TSearchOptionManager.GetSearchResult: TSearchResultSet;
var
searchResult: TSearchResultSet;
begin
searchResult := TSearchResultSet.Create( self );
result := searchResult;
end;
procedure TSearchOptionManager.SetDBManager(dbm: TAbsDBManager);
begin
FDBMS := dbm
end;
procedure TSearchOptionManager.SetDBMSName(dbms: String);
begin
if FDBMS.GetDBMSName <> dbms then
begin
FDBMS.Free;
if dbms = DBMS_MSSQL then
FDBMS := TMsSQLDBManager.Create
else if dbms = DBMS_FIREBIRD then
FDBMS := TFireBirdDBManager.Create;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.