text
stringlengths
14
6.51M
{$N+} Unit Curves; Interface Uses Graph; Procedure Curve (x1, y1, x2, y2, x3, y3: Integer; Segments: Word); Procedure CubicBezierCurve (x1, y1, x2, y2, x3, y3, x4, y4: Integer; Segments: Word); Procedure BSpline (NumPoints: Word; Points: array of pointtype; Segments: Word); Procedure Catmull_Rom_Spline (NumPoints: Word; Points: Array Of pointtype; Segments: Word); {----------------------------------------------------------------------------} Implementation Procedure Curve (x1, y1, x2, y2, x3, y3: Integer; Segments: Word); { Draw a curve from (x1,y1) through (x2,y2) to (x3,y3) divided in "Segments" segments } Var lsteps, ex, ey, fx, fy: LongInt; t1, t2: Integer; Begin x2:=(x2 SHL 1)-((x1+x3) SHR 1); y2:=(y2 SHL 1)-((y1+y3) SHR 1); lsteps:=Segments; If (lsteps<2) then lsteps:=2; If (lsteps>128) then lsteps:=128; { Clamp value to avoid overcalculation } ex:=(LongInt (x2-x1) SHL 17) DIV lsteps; ey:=(LongInt (y2-y1) SHL 17) DIV lsteps; fx:=(LongInt (x3-(2*x2)+x1) SHL 16) DIV (lsteps*lsteps); fy:=(LongInt (y3-(2*y2)+y1) SHL 16) DIV (lsteps*lsteps); Dec (lsteps); While lsteps>0 Do Begin t1:=x3; t2:=y3; x3:=(((fx*lsteps+ex)*lsteps) SHR 16)+x1; y3:=(((fy*lsteps+ey)*lsteps) SHR 16)+y1; Line ( t1,t2,x3,y3 ); Dec (lsteps); End; Line ( x3,y3,x1,y1 ); End; Procedure CubicBezierCurve (x1, y1, x2, y2, x3, y3, x4, y4: Integer; Segments: Word); { Draw a cubic bezier-curve using the basis functions directly } Var tx1, tx2, tx3, ty1, ty2, ty3, mu, mu2, mu3, mudelta: Real; xstart, ystart, xend, yend, n: Integer; Begin If (Segments<1) then Exit; If Segments>128 then Segments:=128; { Clamp value to avoid overcalculation } mudelta:=1/Segments; mu:=0; tx1:=-x1+3*x2-3*x3+x4; ty1:=-y1+3*y2-3*y3+y4; tx2:=3*x1-6*x2+3*x3; ty2:=3*y1-6*y2+3*y3; tx3:=-3*x1+3*x2; ty3:=-3*y1+3*y2; xstart:=x1; ystart:=y1; mu:=mu+mudelta; For n:=1 to Segments Do Begin mu2:=mu*mu; mu3:=mu2*mu; xend:=Round (mu3*tx1+mu2*tx2+mu*tx3+x1); yend:=Round (mu3*ty1+mu2*ty2+mu*ty3+y1); Line ( xstart, ystart, xend, yend ); mu:=mu+mudelta; xstart:=xend; ystart:=yend; End; End; Procedure Catmull_Rom_Spline (NumPoints: Word; Points: Array Of pointtype; Segments: Word); { Draw a spline approximating a curve defined by the array of points. } { In contrast to the BSpline this curve will pass through the points } { defining is except the first and the last point. The curve will only } { pass through the first and the last point if these points are given } { twice after eachother, like this: } { Array of points: } { } { First point defined twice Last point defined twice } { |-----| |----------| } { (0,0),(0,0),(100,100),....,(150,100),(200,200),(200,200) } { the curve defined by these points will pass through all the points. } Function Calculate (mu: Real; p0, p1, p2, p3: Integer): Integer; Var mu2, mu3: Real; Begin mu2:=mu*mu; mu3:=mu2*mu; Calculate:=Round ((1/2)*(mu3*(-p0+3*p1-3*p2+p3)+ mu2*(2*p0-5*p1+4*p2-p3)+ mu *(-p0+p2)+(2*p1))); End; Var mu, mudelta: Real; x1, y1, x2, y2, n, h: Integer; Begin If (NumPoints<4) Or (NumPoints>16383) then Exit; mudelta:=1/Segments; For n:=3 to NumPoints-1 Do Begin mu:=0; x1:=Calculate (mu,Points[n-3].x,Points[n-2].x,Points[n-1].x,Points[n].x); y1:=Calculate (mu,Points[n-3].y,Points[n-2].y,Points[n-1].y,Points[n].y); mu:=mu+mudelta; For h:=1 to Segments Do Begin x2:=Calculate (mu,Points[n-3].x,Points[n-2].x,Points[n-1].x,Points[n].x); y2:=Calculate (mu,Points[n-3].y,Points[n-2].y,Points[n-1].y,Points[n].y); Line ( x1, y1, x2, y2 ); mu:=mu+mudelta; x1:=x2; y1:=y2; End; End; End; Procedure BSpline (NumPoints: Word; Points: Array of Pointtype; Segments: Word); type Rmas=array[0..10] of real; Var i,oldy,oldx,x,y,j:integer; part,t,xx,yy,xmin,xmax,sum:real; dx,dy,wx,wy,px,py,xp,yp,temp,path,zc,u:Rmas; Function f(g:real):real; begin f:=g*g*g-g; end; Begin if NumPoints>10 then exit; oldx:=999; x:=Points[0].x; y:=Points[0].y; zc[0]:=0.0; for i:=1 to NumPoints do begin xx:=Points[i-1].x-Points[i].x; yy:=Points[i-1].y-Points[i].y; t:=sqrt(xx*xx+yy*yy); zc[i]:=zc[i-1]+t; {establish a proportional linear progression} end; {Calculate x & y matrix stuff} for i:=1 to NumPoints-1 do begin dx[i]:=2*(zc[i+1]-zc[i-1]); dy[i]:=2*(zc[i+1]-zc[i-1]); end; for i:=0 to NumPoints-1 do begin u[i]:=zc[i+1]-zc[i]; end; for i:=1 to NumPoints-1 do begin wy[i]:=6*((Points[i+1].y-Points[i].y)/u[i]-(Points[i].y-Points[i-1].y)/u[i-1]); wx[i]:=6*((Points[i+1].x-Points[i].x)/u[i]-(Points[i].x-Points[i-1].x)/u[i-1]); end; py[0]:=0.0; px[0]:=0.0; px[1]:=0; py[1]:=0; py[NumPoints]:=0.0; px[NumPoints]:=0.0; for i:=1 to NumPoints-2 do begin wy[i+1]:=wy[i+1]-wy[i]*u[i]/dy[i]; dy[i+1]:=dy[i+1]-u[i]*u[i]/dy[i]; wx[i+1]:=wx[i+1]-wx[i]*u[i]/dx[i]; dx[i+1]:=dx[i+1]-u[i]*u[i]/dx[i]; end; for i:=NumPoints-1 downto 1 do begin py[i]:=(wy[i]-u[i]*py[i+1])/dy[i]; px[i]:=(wx[i]-u[i]*px[i+1])/dx[i]; end; { Draw spline } for i:=0 to NumPoints-1 do begin for j:=0 to 30 do begin part:=zc[i]-(((zc[i]-zc[i+1])/30)*j); t:=(part-zc[i])/u[i]; part:=t*Points[i+1].y+(1-t)*Points[i].y+u[i]*u[i]*(f(t)*py[i+1]+f(1-t)*py[i])/6.0; y:=round(part); part:=zc[i]-(((zc[i]-zc[i+1])/30)*j); t:=(part-zc[i])/u[i]; part:=t*Points[i+1].x+(1-t)*Points[i].x+u[i]*u[i]*(f(t)*px[i+1]+f(1-t)*px[i])/6.0; x:=round(part); if oldx<>999 then line(oldx,oldy,x,y); oldx:=x; oldy:=y; end; end; end; END.
unit UDependente; interface type TDependente = class private FNome: String; FIsCalculaIR: Boolean; FIsCalculaINSS: Boolean; FId: Integer; FIdFuncionario: Integer; function getNome: String; procedure SetNome(const Value: String); function getIsCalculaIR: Boolean; procedure setIsCalculaIR(const Value: Boolean); function getIsCalculaINSS: Boolean; procedure setIsCalculaINSS(const Value: Boolean); function GetId: Integer; procedure setId(const Value: Integer); function getIdFuncionario: Integer; procedure setIdFuncionario(const Value: Integer); public constructor Create(Id:Integer; idFuncionario: integer; nome: String; CalculaIR, CalculaINSS: Boolean); property Id: Integer read GetId write setId; property IdFuncionario: Integer read getIdFuncionario write setIdFuncionario; property Nome: String read getNome write SetNome; property IsCalculaIR: Boolean read getIsCalculaIR write setIsCalculaIR; property isCalculaINSS: Boolean read getIsCalculaINSS write setIsCalculaINSS; end; implementation { TDependente } constructor TDependente.Create(id: integer; idFuncionario: integer; nome: String; CalculaIR, CalculaINSS: Boolean); begin Fid := Id; fidfuncionario := idFuncionario; FNome := nome; FIsCalculaIR := CalculaIR; FIsCalculaINSS := CalculaINSS; end; function TDependente.GetId: Integer; begin result := FId; end; function TDependente.getIdFuncionario: Integer; begin result := FIdFuncionario; end; function TDependente.getIsCalculaINSS: Boolean; begin result := FIsCalculaINSS; end; function TDependente.getIsCalculaIR: Boolean; begin result := FIsCalculaIR; end; function TDependente.getNome: String; begin result := FNome; end; procedure TDependente.setId(const Value: Integer); begin FId := value; end; procedure TDependente.setIdFuncionario(const Value: Integer); begin FIdFuncionario := Value; end; procedure TDependente.setIsCalculaINSS(const Value: Boolean); begin FIsCalculaINSS := value; end; procedure TDependente.setIsCalculaIR(const Value: Boolean); begin FIsCalculaIR := Value; end; procedure TDependente.SetNome(const Value: String); begin FNome := Value; end; end.
unit principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls; type TfrmPrincipal = class(TForm) Label6: TLabel; pgControl: TPageControl; formEmissao: TTabSheet; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; btnEmitir: TButton; memoConteudoEnviar: TMemo; cbTpConteudo: TComboBox; chkExibirEmis: TCheckBox; txtCNPJ: TEdit; GroupBox4: TGroupBox; memoRetornoEmis: TMemo; txtCaminhoSalvar: TEdit; labelTokenEnviar: TLabel; TabSheet1: TTabSheet; txtchMDFeEnc: TEdit; txtcUFEnc: TEdit; txtcMunEnc: TEdit; Label7: TLabel; Label8: TLabel; Label9: TLabel; txtnProtEnc: TEdit; Label10: TLabel; Label11: TLabel; Label12: TLabel; chkExibirEnc: TCheckBox; btnEncerrar: TButton; GroupBox1: TGroupBox; memoRetornoEnc: TMemo; cbtpDownEnc: TComboBox; cbtpAmbEnc: TComboBox; cbTpDownEmis: TComboBox; cbTpAmbEmis: TComboBox; Label13: TLabel; procedure btnEncerrarClick(Sender: TObject); procedure btnEnviarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmPrincipal: TfrmPrincipal; implementation {$R *.dfm} uses MDFeAPI, System.JSON; procedure TfrmPrincipal.btnEnviarClick(Sender: TObject); var retorno, statusEnvio, statusConsulta, statusDownload: String; cStat, chMDFe, nProt, motivo, nsNRec, erros: String; jsonRetorno: TJSONObject; begin // Valida se todos os campos foram preenchidos if ((txtCaminhoSalvar.Text <> '') and (txtCNPJ.Text <> '') and (memoConteudoEnviar.Text <> '')) then begin memoRetornoEmis.Lines.Clear; retorno := emitirMDFeSincrono(memoConteudoEnviar.Text, cbTpConteudo.Text, txtCNPJ.Text, cbTpDownEmis.Text, cbTpAmbEmis.Text, txtCaminhoSalvar.Text, chkExibirEmis.Checked); memoRetornoEmis.Text := retorno; jsonRetorno := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(retorno), 0) as TJSONObject; statusEnvio := jsonRetorno.GetValue('statusEnvio').Value; statusConsulta := jsonRetorno.GetValue('statusConsulta').Value; statusDownload := jsonRetorno.GetValue('statusDownload').Value; cStat := jsonRetorno.GetValue('cStat').Value; chMDFe := jsonRetorno.GetValue('chMDFe').Value; nProt := jsonRetorno.GetValue('nProt').Value; motivo := jsonRetorno.GetValue('motivo').Value; nsNRec := jsonRetorno.GetValue('nsNRec').Value; erros := jsonRetorno.GetValue('erros').Value; if ((statusEnvio = '200') Or (statusEnvio = '-6')) then begin if(statusConsulta = '200') then begin if (cStat = '100') then begin ShowMessage(motivo); if (statusDownload <> '200') then begin // Aqui vocÍ pode realizar um tratamento em caso de erro no download end end else begin ShowMessage(motivo); end end else begin ShowMessage(motivo + #13 + erros); end end else begin ShowMessage(motivo + #13 + erros); end; end else begin Showmessage('Todos os campos devem estar preenchidos'); end; end; procedure TfrmPrincipal.btnEncerrarClick(Sender: TObject); var retorno, dhEvento, dtEnc, hora, fuso: String; begin // Valida se todos os campos foram preenchidos if ((txtCaminhoSalvar.Text <> '') and (txtchMDFeEnc.Text <> '') and (txtnProtEnc.Text <> '') and (txtcUFEnc.Text <> '') and (txtcMunEnc.Text <> '')) then begin fuso := '-03:00'; dtEnc := FormatDateTime('yyyy-mm-dd',now); hora := FormatDateTime('hh:mm:ss',now); dhEvento := dtEnc + 'T' + hora + fuso; memoRetornoEnc.Lines.Clear; retorno := encerrarMDFe(txtchMDFeEnc.Text, txtnProtEnc.Text, dhEvento, dtEnc, txtcUFEnc.Text, txtcMunEnc.Text, cbTpAmbEnc.Text, cbTpDownEnc.Text, txtCaminhoSalvar.Text, chkExibirEnc.Checked); memoRetornoEnc.Text := retorno; end else begin Showmessage('Todos os campos devem estar preenchidos'); end; end; end.
unit Aurelius.Id.Exceptions; {$I Aurelius.Inc} interface uses SysUtils, Aurelius.Global.Exceptions, Aurelius.Sql.BaseTypes; type ECannotGetLastInsertId = class(EOPFBaseException) public constructor Create(SQLField: TSQLField); end; implementation { ECannotGetLastInsertId } constructor ECannotGetLastInsertId.Create(SQLField: TSQLField); begin inherited CreateFmt('Cannot get Last Insert Id from table %s, field %s.', [SQLField.Table.Schema + '.' + SQLField.Table.Name, SQLField.Field]); end; end.
{ Program PIC_READ [options] * * Read the programmed data from a PIC plugged into the PICPRG programmer * and write it to a HEX file. } program pic_prog; %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'stuff.ins.pas'; %include 'picprg.ins.pas'; const max_msg_args = 2; {max arguments we can pass to a message} var fnam_out: {HEX output file name} %include '(cog)lib/string_treename.ins.pas'; oname_set: boolean; {TRUE if the output file name already set} name: {PIC name selected by user} %include '(cog)lib/string32.ins.pas'; pr: picprg_t; {PICPRG library state} tinfo: picprg_tinfo_t; {configuration info about the target chip} dat_p: picprg_datar_p_t; {pnt to data array for max size data region} dat: picprg_dat_t; {scratch target data value} adr: picprg_adr_t; {scratch target address} ent_p: picprg_adrent_p_t; {pointer to address list entry} iho: ihex_out_t; {HEX file writing state} timer: sys_timer_t; {stopwatch timer} mskinfo: picprg_maskdat_t; {info about mask of valid bits} sz: sys_int_adr_t; {memory size} i: sys_int_machine_t; {scratch integer and loop counter} r: real; {scratch floating point number} datwid: sys_int_machine_t; {data EEPROM word width, bits} hdouble: boolean; {addresses in HEX file are doubled} eedouble: boolean; {EEPROM addresses doubled after HDOUBLE appl} hexopen: boolean; {TRUE when HEX file is open} opt: {upcased command line option} %include '(cog)lib/string_treename.ins.pas'; parm: {command line option parameter} %include '(cog)lib/string_treename.ins.pas'; pick: sys_int_machine_t; {number of token picked from list} msg_parm: {references arguments passed to a message} array[1..max_msg_args] of sys_parm_msg_t; stat: sys_err_t; {completion status code} label next_opt, done_opt, err_parm, err_conflict, parm_bad, done_opts, abort, leave_all; { ****************************************************************** * * Subroutine WRITE_WORD (ADR, W, STAT) * * Write the target data word W at target address ADR to the HEX file. } procedure write_word ( {write one target word to the HEX file} in adr: picprg_adr_t; {target address of the word} in w: picprg_dat_t; {the data word} out stat: sys_err_t); {completion status} val_param; var hadr: picprg_adr_t; {HEX file address of this word} begin hadr := adr; {init to write word to its address} { * The address to write this word to in the HEX file is in HADR. } if hdouble then begin {HEX file addresses are doubled} ihex_out_byte (iho, hadr * 2, w & 255, stat); {write low byte} if sys_error(stat) then return; ihex_out_byte (iho, (hadr * 2) + 1, rshft(w, 8) & 255, stat); {write high byte} end else begin {HEX file addresses are same as target} ihex_out_byte (iho, hadr, w & 255, stat); {write low byte of word} end ; end; { ****************************************************************** * * Start of main routine. } begin sys_timer_init (timer); {initialize the stopwatch} sys_timer_start (timer); {start the stopwatch} string_cmline_init; {init for reading the command line} { * Initialize our state before reading the command line options. } picprg_init (pr); {select defaults for opening PICPRG library} oname_set := false; {no output file name specified} hexopen := false; {init to HEX output file not open} sys_envvar_get ( {init programmer name from environment variable} string_v('PICPRG_NAME'), {environment variable name} parm, {returned environment variable value} stat); if not sys_error(stat) then begin {envvar exists and got its value ?} string_copy (parm, pr.prgname); {initialize target programmer name} end; { * Back here each new command line option. } next_opt: string_cmline_token (opt, stat); {get next command line option name} if string_eos(stat) then goto done_opts; {exhausted command line ?} sys_error_abort (stat, 'string', 'cmline_opt_err', nil, 0); if (opt.len >= 1) and (opt.str[1] <> '-') then begin {implicit pathname token ?} if not oname_set then begin {output file name not set yet ?} string_copy (opt, fnam_out); {set output file name} oname_set := true; {output file name is now set} goto next_opt; end; goto err_conflict; end; string_upcase (opt); {make upper case for matching list} string_tkpick80 (opt, {pick command line option name from list} '-HEX -SIO -PIC -N -LVP', pick); {number of keyword picked from list} case pick of {do routine for specific option} { * -HEX filename } 1: begin if oname_set then goto err_conflict; {output file name already set ?} string_cmline_token (fnam_out, stat); oname_set := true; end; { * -SIO n } 2: begin string_cmline_token_int (pr.sio, stat); pr.devconn := picprg_devconn_sio_k; end; { * -PIC name } 3: begin string_cmline_token (name, stat); string_upcase (name); end; { * -N name } 4: begin string_cmline_token (pr.prgname, stat); {get programmer name} if sys_error(stat) then goto err_parm; end; { * -LVP } 5: begin pr.hvpenab := false; {disallow high voltage program mode entry} end; { * Unrecognized command line option. } otherwise string_cmline_opt_bad; {unrecognized command line option} end; {end of command line option case statement} done_opt: {done handling this command line option} err_parm: {jump here on error with parameter} string_cmline_parm_check (stat, opt); {check for bad command line option parameter} goto next_opt; {back for next command line option} err_conflict: {this option conflicts with a previous opt} sys_msg_parm_vstr (msg_parm[1], opt); sys_message_bomb ('string', 'cmline_opt_conflict', msg_parm, 1); parm_bad: {jump here on got illegal parameter} string_cmline_reuse; {re-read last command line token next time} string_cmline_token (parm, stat); {re-read the token for the bad parameter} sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_vstr (msg_parm[2], opt); sys_message_bomb ('string', 'cmline_parm_bad', msg_parm, 2); done_opts: {done with all the command line options} { * All done reading the command line. } picprg_open (pr, stat); {open the PICPRG programmer library} sys_error_abort (stat, 'picprg', 'open', nil, 0); { * Get the firmware info and check the version. } picprg_fw_show1 (pr, pr.fwinfo, stat); {show version and organization to user} sys_error_abort (stat, '', '', nil, 0); picprg_fw_check (pr, pr.fwinfo, stat); {check firmware version for compatibility} sys_error_abort (stat, '', '', nil, 0); { * Configure to the specific target chip. } picprg_config (pr, name, stat); {configure the library to the target chip} if sys_error_check (stat, '', '', nil, 0) then goto abort; picprg_tinfo (pr, tinfo, stat); {get detailed info about the target chip} if sys_error_check (stat, '', '', nil, 0) then goto abort; sys_msg_parm_vstr (msg_parm[1], tinfo.name); sys_msg_parm_int (msg_parm[2], tinfo.rev); sys_message_parms ('picprg', 'target_type', msg_parm, 2); {show target name} ihex_out_open_fnam ( {open the HEX output file} fnam_out, {output file name} '.hex', {mandatory file name suffix} iho, {returned HEX file writing state} stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; hexopen := true; {indicate the HEX output file is open} { * Allocate an array for holding the maximum size program memory or data * memory area. } hdouble := {set flag if HEX file addresses doubled} (tinfo.maskprg.maske ! tinfo.maskprg.masko ! 255) <> 255; eedouble := not hdouble; {data adr still doubled after HDOUBLE applied} datwid := 8; {init size of data EEPROM word} case tinfo.fam of {special handling for some PIC families} picprg_picfam_18f_k, {PIC 18} picprg_picfam_18f2520_k, picprg_picfam_18f2523_k, picprg_picfam_18f6680_k, picprg_picfam_18f6310_k, picprg_picfam_18j_k, picprg_picfam_18f14k22_k, picprg_picfam_18f14k50_k: begin eedouble := false; end; picprg_picfam_30f_k, picprg_picfam_24h_k, picprg_picfam_24f_k: begin eedouble := true; datwid := 16; end; end; sz := max(tinfo.nprog, tinfo.ndat); {max words required for any region} sz := sz * sizeof(dat_p^[0]); {memory size needed for the number of words} sys_mem_alloc (sz, dat_p); {allocate the data array} { * Read the regular program memory and write it to the HEX output file. } picprg_read ( {read the program memory} pr, {PICPRG library state} 0, {starting address to read from} tinfo.nprog, {number of locations to read} tinfo.maskprg, {mask for valid data bits} dat_p^, {array to read the data into} stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; for i := 0 to tinfo.nprog-1 do begin {once for each data word} write_word (i, dat_p^[i], stat); {write this word to HEX output file} if sys_error_check (stat, '', '', nil, 0) then goto abort; end; { * Read the non-volatile data memory and write it to the HEX output file. } picprg_space_set ( {switch to data memory address space} pr, picprg_space_data_k, stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; picprg_read ( {read the data memory} pr, {PICPRG library state} 0, {starting address to read from} tinfo.ndat, {number of locations to read} tinfo.maskdat, {mask for valid data bits} dat_p^, {array to read the data into} stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; for i := 0 to tinfo.ndat-1 do begin {once for each data word} if eedouble then begin {each word is written to two addresses} write_word ( {write first byte to HEX output file} i * 2 + tinfo.datmap, {target address} dat_p^[i] & tinfo.maskdat.maske, {word at this address} stat); write_word ( {write second byte to HEX output file} i * 2 + 1 + tinfo.datmap, {target address} rshft(dat_p^[i], datwid) & tinfo.maskdat.masko, {word at this address} stat); end else begin {each word goes into a single address} write_word ( {write first byte to HEX output file} i + tinfo.datmap, {target address} dat_p^[i], {word at this address} stat); end ; if sys_error_check (stat, '', '', nil, 0) then goto abort; end; picprg_space_set ( {switch back to program memory address space} pr, picprg_space_prog_k, stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; { * Read the OTHER program memory locations and write them to the HEX * output file. } ent_p := tinfo.other_p; {init to first list entry} while ent_p <> nil do begin {once for address in the list} picprg_mask_same (ent_p^.mask, mskinfo); {make mask info for this word} picprg_read ( {read from this address} pr, {PICPRG library state} ent_p^.adr, {address to read from} 1, {number of locations to read} mskinfo, {mask info for this data word} dat, {the returned data word} stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; write_word (ent_p^.adr, dat, stat); {write the word to the HEX file} if sys_error_check (stat, '', '', nil, 0) then goto abort; ent_p := ent_p^.next_p; {advance to the next address in the list} end; { * Read the CONFIG program memory locations and write them to the HEX * output file. } ent_p := tinfo.config_p; {init to first list entry} while ent_p <> nil do begin {once for address in the list} picprg_mask_same (ent_p^.mask, mskinfo); {make mask info for this word} picprg_read ( {read from this address} pr, {PICPRG library state} ent_p^.adr, {address to read from} 1, {number of locations to read} mskinfo, {mask info for this data word} dat, {the returned data word} stat); if sys_error_check (stat, '', '', nil, 0) then goto abort; { * Special check for 10F config word. This config word is always * stored in the HEX file at address FFFh regardless of its real * address in the chip. Yes, we think that's stupid too, but that's * the way Microchip did it. } adr := ent_p^.adr; {init HEX file address of this word} if {check for 10F config word} (tinfo.fam = picprg_picfam_10f_k) and {target PIC is a 10F ?} (ent_p = tinfo.config_p) {this is first config word in the list ?} then begin adr := 16#FFF; {switch to special HEX file address} string_f_int_max_base ( {make 4 digit HEX address} parm, adr, 16, 4, [string_fi_leadz_k, string_fi_unsig_k], stat); write ('Switching config word address, ', parm.str:parm.len, ': '); string_f_int_max_base ( {make 3 digit HEX contents} parm, dat, 16, 3, [string_fi_leadz_k, string_fi_unsig_k], stat); writeln (parm.str:parm.len); end; write_word (adr, dat, stat); {write the word to the HEX file} if sys_error_check (stat, '', '', nil, 0) then goto abort; ent_p := ent_p^.next_p; {advance to the next address in the list} end; { * Common point for exiting the program with the PICPRG library open * and no error. } ihex_out_close (iho, stat); {close the HEX output file} if sys_error_check (stat, '', '', nil, 0) then goto abort; picprg_cmdw_off (pr, stat); {turn off power, etc, to the target chip} sys_error_abort (stat, '', '', nil, 0); picprg_close (pr, stat); {close the PICPRG library} sys_error_abort (stat, 'picprg', 'close', nil, 0); sys_timer_stop (timer); {stop the stopwatch} r := sys_timer_sec (timer); {get total elapsed seconds} sys_msg_parm_real (msg_parm[1], r); sys_message_parms ('picprg', 'no_errors', msg_parm, 1); goto leave_all; { * Error exit point with the PICPRG library open. } abort: if hexopen then begin ihex_out_close (iho, stat); {close the HEX output file} sys_error_print (stat, '', '', nil, 0); end; picprg_cmdw_off (pr, stat); {turn off power, etc, to the target chip} sys_error_print (stat, '', '', nil, 0); picprg_close (pr, stat); {close the PICPRG library} sys_error_print (stat, 'picprg', 'close', nil, 0); sys_bomb; {exit the program with error status} leave_all: end.
unit FHIRPluginValidator; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. } interface Uses SysUtils, Classes, ActiveX, ComObj, MsXml, MsXmlParser, StringSupport, AdvObjects, AdvBuffers, AdvNameBuffers, AdvMemories, AdvVclStreams, AdvZipReaders, AdvZipParts, AdvGenerics, FHIRTypes, FHIRResources, FHIRValidator, FHIRParser, FHIRUtilities, FHIRProfileUtilities, FHIRConstants, FHIRClient, FHIRBase, FHIRContext; Type TFHIRPluginValidatorContext = class (TBaseWorkerContext) private FUrl : String; FServer : TFhirHTTPClient; FCapabilityStatement : TFHIRCapabilityStatement; FValueSets : TAdvMap<TFHIRValueSet>; FCodeSystems : TAdvMap<TFHIRCodeSystem>; procedure checkClient; function findCode(list : TFhirCodeSystemConceptList; code : String; caseSensitive : boolean) : TFhirCodeSystemConcept; protected procedure SeeResource(r : TFhirResource); override; public Constructor Create(terminologyServer : String); virtual; Destructor Destroy; Override; Function Link : TFHIRPluginValidatorContext; overload; function fetchResource(t : TFhirResourceType; url : String) : TFhirResource; override; function expand(vs : TFhirValueSet) : TFHIRValueSet; override; function supportsSystem(system, version : string) : boolean; override; function validateCode(system, version, code, display : String) : TValidationResult; override; function validateCode(system, version, code : String; vs : TFHIRValueSet) : TValidationResult; override; function validateCode(code : TFHIRCoding; vs : TFhirValueSet) : TValidationResult; override; function validateCode(code : TFHIRCodeableConcept; vs : TFhirValueSet) : TValidationResult; override; end; implementation { TFHIRPluginValidatorContext } procedure TFHIRPluginValidatorContext.checkClient; begin if (FServer = nil) or (FCapabilityStatement = nil) then begin if FServer <> nil then FServer.Free; FServer := TFhirHTTPClient.Create(self.link, FUrl, true); FServer.timeout := 5000; FServer.allowR2 := true; FCapabilityStatement := FServer.conformance(true); if FCapabilityStatement.fhirVersion <> FHIR_GENERATED_VERSION then raise Exception.Create('Terminology Server / Plug-in Version mismatch ('+FCapabilityStatement.fhirVersion+' / '+FHIR_GENERATED_VERSION+')'); end; end; constructor TFHIRPluginValidatorContext.Create(terminologyServer : String); begin inherited Create; FValueSets := TAdvMap<TFHIRValueSet>.create; FCodeSystems := TAdvMap<TFHIRCodeSystem>.create; FUrl := terminologyServer; end; destructor TFHIRPluginValidatorContext.Destroy; begin FValueSets.Free; FServer.Free; FCapabilityStatement.Free; FCodeSystems.Free; inherited; end; function TFHIRPluginValidatorContext.expand(vs: TFhirValueSet): TFHIRValueSet; var pIn : TFhirParameters; begin CheckClient; pIn := TFhirParameters.Create; try pIn.AddParameter('valueSet', vs.Link); pIn.AddParameter('_incomplete', true); pIn.AddParameter('_limit', '10'); result := FServer.operation(frtValueSet, 'expand', pIn) as TFhirValueSet; finally pIn.Free; end; end; function TFHIRPluginValidatorContext.fetchResource(t: TFhirResourceType; url: String): TFhirResource; begin if (t = frtValueSet) then result := FValueSets[url].link else result := inherited fetchResource(t, url); end; function TFHIRPluginValidatorContext.findCode(list: TFhirCodeSystemConceptList; code: String; caseSensitive : boolean): TFhirCodeSystemConcept; var d, d1 : TFhirCodeSystemConcept; begin result := nil; for d in list do begin if (caseSensitive and (d.code = code)) then begin result := d; exit; end; if (not caseSensitive and (d.code.ToLower = code.ToLower)) then begin result := d; exit; end; result := findCode(d.conceptList, code, caseSensitive); if (result <> nil) then exit; end; end; function TFHIRPluginValidatorContext.Link: TFHIRPluginValidatorContext; begin result := TFHIRPluginValidatorContext(inherited Link); end; procedure TFHIRPluginValidatorContext.SeeResource(r: TFhirResource); var vs : TFhirValueset; begin if (r.ResourceType = frtValueSet) then begin vs := (r as TFHIRValueSet); FValueSets.Add(vs.url, vs.Link); {$IFDEF FHIR2} if (vs.codeSystem <> nil) then FCodeSystems.Add(vs.codeSystem.system, vs.Link) {$ENDIF} end {$IFDEF FHIR3} else if (r.ResourceType = frtCodeSystem) then FCodeSystems.Add(TFHIRCodeSystem(r).url, TFHIRCodeSystem(r).Link) {$ENDIF} else inherited; end; function TFHIRPluginValidatorContext.supportsSystem(system, version: string): boolean; var ex : TFhirExtension; begin CheckClient; result := FCodeSystems.ContainsKey(system); if (not result) then for ex in FCapabilityStatement.extensionList do if (ex.url = 'http://hl7.org/fhir/StructureDefinition/conformance-common-supported-system') and (ex.value is TFHIRString) and (TFHIRString(ex.value).value = system) then result := true; end; function TFHIRPluginValidatorContext.validateCode(system, version, code, display: String): TValidationResult; var pIn, pOut : TFhirParameters; cs : TFHIRCodeSystem; def : TFhirCodeSystemConcept; begin if FCodeSystems.ContainsKey(system) then begin cs := FCodeSystems[system]; def := FindCode(cs.conceptList, code, cs.caseSensitive); if (def = nil) then result := TValidationResult.Create(IssueSeverityError, 'Unknown code ' +code) else result := TValidationResult.Create(def.display); end else begin checkClient; pIn := TFhirParameters.Create; try pIn.AddParameter('system', system); pIn.AddParameter('code', code); pIn.AddParameter('display', display); pOut := FServer.operation(frtValueSet, 'validate-code', pIn) as TFhirParameters; try if pOut.bool['result'] then result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']) else result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']); finally pOut.Free; end; finally pIn.Free; end; end; end; function TFHIRPluginValidatorContext.validateCode(system, version, code: String; vs: TFHIRValueSet): TValidationResult; var pIn, pOut : TFhirParameters; def : TFhirCodeSystemConcept; begin checkClient; pIn := TFhirParameters.Create; try pIn.AddParameter('system', system); pIn.AddParameter('code', code); pIn.AddParameter('version', version); pIn.AddParameter('valueSet', vs.Link); pOut := FServer.operation(frtValueSet, 'validate-code', pIn) as TFhirParameters; try if pOut.bool['result'] then result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']) else result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']); finally pOut.Free; end; finally pIn.Free; end; end; function TFHIRPluginValidatorContext.validateCode(code: TFHIRCodeableConcept; vs: TFhirValueSet): TValidationResult; var pIn, pOut : TFhirParameters; begin checkClient; pIn := TFhirParameters.Create; try pIn.AddParameter('codeableConcept', code.Link); pIn.AddParameter('valueSet', vs.Link); pOut := FServer.operation(frtValueSet, 'validate-code', pIn) as TFhirParameters; try if pOut.bool['result'] then result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']) else result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']); finally pOut.Free; end; finally pIn.Free; end; end; function TFHIRPluginValidatorContext.validateCode(code: TFHIRCoding; vs: TFhirValueSet): TValidationResult; var pIn, pOut : TFhirParameters; begin checkClient; pIn := TFhirParameters.Create; try pIn.AddParameter('coding', code.Link); pIn.AddParameter('valueSet', vs.Link); pOut := FServer.operation(frtValueSet, 'validate-code', pIn) as TFhirParameters; try if pOut.bool['result'] then result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']) else result := TValidationResult.Create(IssueSeverityInformation, pOut.str['message']); finally pOut.Free; end; finally pIn.Free; end; end; end.
PROGRAM binary_tree_sort; USES dos,CRT; CONST TWordLength = 10; TYPE TWord = STRING [TWordLength]; TYPE PTree = ^TTree; TTree = RECORD info : TWord; num : INTEGER; Left, Right : PTree; END; TYPE tinfile = text; PROCEDURE readword (VAR infile : tinfile; VAR s : TWord); VAR letter : string[1]; BEGIN REPEAT if eoln(infile) then readln(infile) else READ (infile, letter); UNTIL ( (letter > ' ') OR (EOF (infile) ) ); IF (NOT (EOF (infile) ) ) THEN BEGIN s := letter; WHILE ( (letter > ' ') AND (NOT EOF (infile) ) AND (LENGTH (s) < TWordLength) and (not eoln(infile))) DO BEGIN READ (infile, letter); IF (letter > ' ') THEN s := s + letter; END; END ELSE s := ''; END; PROCEDURE addelem (VAR root : PTree; info : TWord); VAR elem : PTree; BEGIN IF (root = NIL) THEN (* Если дерево пустое, то *) BEGIN NEW (elem); (* Создать новый лист *) elem^.Left := NIL; elem^.Right := NIL; elem^.num := 1; elem^.info := info; (* Записать в него нужный элемент *) root := elem; (* Поключить его вместо пустого дерева *) END ELSE IF (root^.info = info) THEN (* Если текущий узел равен добавляемому элементу *) INC (root^.num) (* Увеличить число появлений данного элемента *) ELSE (* Иначе *) BEGIN IF (info < root^.info) THEN (* Если добавляемый элемент меньше тек.узла, то *) addelem (root^.Left, info) (* Добавить элемент в левое поддерево *) ELSE (* Иначе *) addelem (root^.Right, info); (* Добавить элемент в правое поддерево *) END; END; PROCEDURE readfile (VAR infile : tinfile; VAR tree : PTree); VAR s : TWord; BEGIN WHILE (NOT (EOF (infile) ) ) DO (* Пока файл не закончился *) BEGIN readword (infile, s); (* Считать из него слово *) IF (s <> '') THEN (* Если слово не пустое *) addelem (tree, s); (* Добавить его в дерево *) END; END; PROCEDURE writefile (VAR outfile : TEXT; VAR root : PTree); BEGIN IF (root <> NIL) THEN (* Если дерево не пустое, то *) BEGIN writefile (outfile, root^.Left); (* Записать в файл его левую ветвь *) WRITELN (outfile, root^.info, '-', root^.num); (* Записать в файл его корень *) writefile (outfile, root^.Right); (* Записать в файл его правую ветвь *) END; END; VAR tree : PTree; infname, outfname : STRING; infile : tinfile; outfile : TEXT; IOR : INTEGER; h1,m1,s1,decs1 : word; h2,m2,s2,decs2 : word; wtime:longint; BEGIN tree := NIL; WRITELN ('Сортировка файла бинарным деревом.'); REPEAT WRITE ('Введите имя входного файла : '); READLN (infname); (* Считать с клавиатуры имя входного файла *) ASSIGN (infile, infname); {$I-} RESET (infile); (* Открыть входной файл *) {$I+} IOR := IORESULT; IF (IOR <> 0) THEN WRITELN ('Не могу открыть входной файл!'); UNTIL (IOR = 0); REPEAT WRITE ('Введите имя выходного файла : '); READLN (outfname); (* Считать с клавиатуры имя выходного файла *) ASSIGN (outfile, outfname); {$I-} REWRITE (outfile); (* Открыть выходной файл *) {$I+} IOR := IORESULT; IF (IOR <> 0) THEN WRITELN ('Не могу открыть выходной файл!'); UNTIL (IOR = 0); gettime(h1,m1,s1,decs1); readfile (infile, tree); (* Считать входной файл в дерево *) writefile (outfile, tree); (* Записать дерево в виде ЛКП в выходной файл *) gettime(h2,m2,s2,decs2); wtime:=(decs2+s2*100+m2*6000+h2*360000)-(decs1+s1*100+m1*6000+h1*360000); writeln('Время работы : ',(wtime/100):2:2); CLOSE (outfile); (* Закрыть выходной файл *) CLOSE (infile); (* Закрыть входной файл *) END.
(* GAME AI & ALGORITHM *) { player selection algorithm } function TFormGaple.FirstPlayer(PairValue: integer): integer; var i: integer; begin // selecting start card if IncFirstCardPair then PairValue := PairValue mod 7 else PairValue := FirstCardPair; // selecting player who has the start card for i := 1 to NumberOfCards do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if (TopValue = PairValue) and (BottomValue = PairValue) then begin DeckGaple.TopValue := TopValue; DeckGaple.BottomValue := BottomValue; LabelDeck.Visible := true; LabelDeck.Caption := 'Deck expecting: '+IntToStr(DeckGaple.TopValue)+'_'+IntToStr(DeckGaple.BottomValue); result := Tag; Break; end else result := 1; end; procedure TFormGaple.NextPlayerTurn; var i: integer; begin if GameRunning then begin ListBoxCards.Items := StepList; with TLabel(FindComponent('LabelPlayer'+IntToStr(CurrentPlayer))) do Font.Color := clWhite; repeat Inc(CurrentPlayer); if CurrentPlayer > 4 then CurrentPlayer := 1; until not NoCardLeft(CurrentPlayer) or GameIsOver; Application.ProcessMessages; Sleep(250); if not GameIsOver then begin with TLabel(FindComponent('LabelPlayer'+IntToStr(CurrentPlayer))) do Font.Color := clLime; if Players[CurrentPlayer].Kind = plComputer then ComputerPlaying(CurrentPlayer) else if Players[CurrentPlayer].Kind = plNetwork then NetworkPlaying(CurrentPlayer) else LabelStatus.Caption := 'Waiting for '+Players[CurrentPlayer].Name+' ... '; end else begin GameRunning := false; for i := 1 to NumberOfCards do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then ShowDeck := false; LabelStatus.Caption := 'Game is over.'; GameOverInformation; Exit; end; end; end; { player algorithm } procedure TFormGaple.HumanPlaying(SelectedCard: TDominoCard); var turn_info: string; answer: integer; i: integer; begin if GameRunning then begin // check player turn if (SelectedCard.Tag = CurrentPlayer) and (Players[CurrentPlayer].Kind = plHuman) then begin // check player status if not DeckGaple.IsEmpty then begin PlayerPass := NoCardMatch(SelectedCard.Tag); PlayerPlay := not NoCardLeft(SelectedCard.Tag); // check for deck reorganizing if (TurnStep mod 4 = 0) then begin ReorganizeDeckCards; DominoDeck.TopValue := DeckGaple.TopValue; DominoDeck.BottomValue := DeckGaple.BottomValue; DominoDeck.ShowDeck := false; end; end; // player allowed to play if PlayerPlay and (not PlayerPass) then begin // first turn if DeckGaple.IsEmpty then begin if not CardMatchBoth(SelectedCard) then begin WrongCardWarning; Exit; end; FirstCard(SelectedCard); end // next turn else if CardMatchBoth(SelectedCard) then begin if (DeckGaple.TopValue = DeckGaple.BottomValue) then PlaceCardOnTop(SelectedCard) else // player must select card begin answer := SelectCardQuestion; if answer = mrYes then PlaceCardOnTop(SelectedCard) else if answer = mrNo then PlaceCardOnBottom(SelectedCard) else Exit; end; end else if CardMatchBottom(SelectedCard) then PlaceCardOnBottom(SelectedCard) else if CardMatchTop(SelectedCard) then PlaceCardOnTop(SelectedCard) // player select unmatch card else begin WrongCardWarning; LabelStatus.Caption := Players[CurrentPlayer].Name+' is thinking... wrong!'; end; end // player has no card to play then pass the turn else if PlayerPass then begin // passing card required if PassCardRequired then begin answer := PassCardQuestion; if answer = mrYes then DisableCard(SelectedCard); end // no passing card required else begin NoCardInformation; DisableCard(SelectedCard); end; end // player not allowed to play else if not PlayerPlay then begin // by passing turn Inc(TurnStep); NoCardInformation; // write game info turn_info := IntToStr(TurnStep)+': '; turn_info := turn_info + 'pass = '; turn_info := turn_info + IntToStr(DeckGaple.TopValue)+'_'; turn_info := turn_info + IntToStr(DeckGaple.BottomValue); StepList.Add(turn_info); // move to next player NextPlayerTurn; end; end // wrong turn else WrongTurnWarning; // no more turn if GameIsOver and GameRunning then begin // show all disabled cards GameRunning := false; for i := 1 to NumberOfCards do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then ShowDeck := false; LabelStatus.Caption := 'Game is over.'; GameOverInformation; Exit; end; end; end; procedure TFormGaple.NetworkPlaying(Player: integer); begin end; procedure TFormGaple.ComputerPlaying(Player: integer); type card = record top_value: integer; bottom_value: integer; is_match: boolean; index: integer; end; var place_on_top: boolean; card_match,some_match: boolean; i,highest,lowest: integer; card_idx,lowest_idx,highest_idx: integer; play_cards_count: integer; play_cards: array of card; begin if GameRunning then begin // check player turn if (Player = CurrentPlayer) and (Players[CurrentPlayer].Kind = plComputer) then begin Cursor := crHourGlass; LabelStatus.Caption := Players[Player].Name+' is thinking... '; Application.ProcessMessages; Sleep(250); // check for deck reorganizing if (TurnStep mod 4 = 0) then begin ReorganizeDeckCards; DominoDeck.TopValue := DeckGaple.TopValue; DominoDeck.BottomValue := DeckGaple.BottomValue; DominoDeck.ShowDeck := false; end; // store value of available cards play_cards_count := 0; for i := 1 to NumberOfCards do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do begin if (Tag = Player) and Visible and Enabled then begin SetLength(play_cards,play_cards_count+1); play_cards[play_cards_count].top_value := TopValue; play_cards[play_cards_count].bottom_value := BottomValue; play_cards[play_cards_count].index := i; Inc(play_cards_count); end; end; // search for match cards some_match := false; for i := 0 to play_cards_count-1 do begin card_match := (play_cards[i].top_value = DeckGaple.TopValue) or (play_cards[i].bottom_value = DeckGaple.TopValue) or (play_cards[i].top_value = DeckGaple.BottomValue) or (play_cards[i].bottom_value = DeckGaple.BottomValue); play_cards[i].is_match := card_match; if card_match then some_match := true; end; // player allowed to play if some_match then begin // selecting play card algorithm highest := -1; card_idx := -1; highest_idx := -1; for i := 0 to play_cards_count-1 do // if first turn, select card which match the deck if DeckGaple.IsEmpty then begin if (play_cards[i].is_match) and (play_cards[i].top_value = DeckGaple.TopValue) and (play_cards[i].bottom_value = DeckGaple.BottomValue) then begin highest_idx := play_cards[i].index; card_idx := i; Break; end; end // else, select card with biggest value else begin if (play_cards[i].is_match) and ((play_cards[i].top_value + play_cards[i].bottom_value) >= highest) then begin highest := play_cards[i].top_value + play_cards[i].bottom_value; highest_idx := play_cards[i].index; card_idx := i; end; end; // place selected card if DeckGaple.IsEmpty then FirstCard(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))) else if CardMatchBoth(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))) then begin place_on_top := false; // place on value which there's same value on hand for i := 0 to play_cards_count-1 do begin if play_cards[i].top_value = play_cards[card_idx].top_value then place_on_top := true else if play_cards[i].bottom_value = play_cards[card_idx].bottom_value then place_on_top := false; end; if place_on_top then PlaceCardOnTop(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))) else PlaceCardOnBottom(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))); end else if CardMatchBottom(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))) then PlaceCardOnBottom(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))) else PlaceCardOnTop(TDominoCard(FindComponent('DominoCard'+IntToStr(highest_idx)))); // no more turn if GameIsOver and GameRunning then begin // show all disabled cards GameRunning := false; for i := 1 to NumberOfCards do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then ShowDeck := false; LabelStatus.Caption := 'Game is over.'; GameOverInformation; Exit; end; end // selecting disable card algorithm else begin if play_cards_count > 0 then begin lowest := 111; lowest_idx := -1; // select card with lowest value for i := 0 to play_cards_count-1 do begin if ((play_cards[i].top_value + play_cards[i].bottom_value) <= lowest) then begin lowest := play_cards[i].top_value + play_cards[i].bottom_value; lowest_idx := play_cards[i].index; end; end; DisableCard(TDominoCard(FindComponent('DominoCard'+IntToStr(lowest_idx)))); end else NextPlayerTurn; end; end else NextPlayerTurn; Cursor := crDefault; Application.ProcessMessages; end; end;
{ DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(DBEBr Framework) @created(20 Jul 2016) @author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>) } unit dbebr.factory.zeos; interface uses DB, Classes, dbebr.factory.connection, dbebr.factory.interfaces; type // Fábrica de conexão concreta com dbExpress TFactoryZeos = class(TFactoryConnection) public constructor Create(const AConnection: TComponent; const ADriverName: TDriverName); override; destructor Destroy; override; procedure Connect; override; procedure Disconnect; override; procedure StartTransaction; override; procedure Commit; override; procedure Rollback; override; procedure ExecuteDirect(const ASQL: string); override; procedure ExecuteDirect(const ASQL: string; const AParams: TParams); override; procedure ExecuteScript(const ASQL: string); override; procedure AddScript(const ASQL: string); override; procedure ExecuteScripts; override; function InTransaction: Boolean; override; function IsConnected: Boolean; override; function GetDriverName: TDriverName; override; function CreateQuery: IDBQuery; override; function CreateResultSet(const ASQL: String): IDBResultSet; override; function ExecuteSQL(const ASQL: string): IDBResultSet; override; end; implementation uses dbebr.driver.zeos, dbebr.driver.zeos.transaction; { TFactoryZeos } procedure TFactoryZeos.Connect; begin if not IsConnected then FDriverConnection.Connect; end; constructor TFactoryZeos.Create(const AConnection: TComponent; const ADriverName: TDriverName); begin inherited; FDriverConnection := TDriverZeos.Create(AConnection, ADriverName); FDriverTransaction := TDriverZeosTransaction.Create(AConnection); end; function TFactoryZeos.CreateQuery: IDBQuery; begin Result := FDriverConnection.CreateQuery; end; function TFactoryZeos.CreateResultSet(const ASQL: String): IDBResultSet; begin Result := FDriverConnection.CreateResultSet(ASQL); end; destructor TFactoryZeos.Destroy; begin FDriverTransaction.Free; FDriverConnection.Free; inherited; end; procedure TFactoryZeos.Disconnect; begin if IsConnected then FDriverConnection.Disconnect; end; procedure TFactoryZeos.ExecuteDirect(const ASQL: string); begin inherited; end; procedure TFactoryZeos.ExecuteDirect(const ASQL: string; const AParams: TParams); begin inherited; end; procedure TFactoryZeos.ExecuteScript(const ASQL: string); begin inherited; end; procedure TFactoryZeos.ExecuteScripts; begin inherited; end; function TFactoryZeos.ExecuteSQL(const ASQL: string): IDBResultSet; begin Result := FDriverConnection.ExecuteSQL(ASQL); end; function TFactoryZeos.GetDriverName: TDriverName; begin Result := FDriverConnection.DriverName; end; function TFactoryZeos.IsConnected: Boolean; begin Result := FDriverConnection.IsConnected; end; function TFactoryZeos.InTransaction: Boolean; begin Result := FDriverTransaction.InTransaction; end; procedure TFactoryZeos.StartTransaction; begin inherited; FDriverTransaction.StartTransaction; end; procedure TFactoryZeos.AddScript(const ASQL: string); begin FDriverConnection.AddScript(ASQL); end; procedure TFactoryZeos.Commit; begin FDriverTransaction.Commit; inherited; end; procedure TFactoryZeos.Rollback; begin FDriverTransaction.Rollback; inherited; end; end.
unit avConfig; interface uses Windows, SysUtils, Classes, avMessages; const FILE_DELETE = 0000; FILE_QUARANTIN = 0001; FILE_SKIP = 0002; PRIORITY_NORMAL = 0003; PRIORITY_HIGHT = 0004; ConfigFileName = 'AVSConfig.cfg'; type TConfig = record PathBase : string;//путь к антивирусной базе PathLog : string;//путь к файлу отчета PathQuarantine : string;//путь к папке карантина AutoSave : boolean;//признак автосохранения отчета ShowFile : boolean;//отображать проверяемые файлы в отчете FileAction : integer;//действие с вредоносным файлов Priority : integer;//приоритет потока сканирования ExeOnly : boolean;//проверять только exe-файлы end; var CurrentDir : string;//текущий каталог AV Scanner ConfigFile : TStrings;//файл конфигурации сканера ScannerConfig : TConfig;//текущая конфигурация сканера procedure LoadConfig(const ConfigFileName : string); procedure SaveConfig(const ConfigFilename : string); implementation procedure LoadConfig(const ConfigFileName : string); begin SetCurrentDir(CurrentDir); try ConfigFile := TStringList.Create; ConfigFile.LoadFromFile(ConfigFileName); with ScannerConfig do begin PathBase := ConfigFile.Strings[0]; PathLog := ConfigFile.Strings[1]; PathQuarantine := ConfigFile.Strings[2]; if ConfigFile.Strings[3] = 'AutoSaveOn' then AutoSave := true else AutoSave := false; if ConfigFile.Strings[4] = 'ShowFileOn' then ShowFile := true else ShowFile := false; FileAction := strtoint(ConfigFile.Strings[5]); Priority := strtoint(ConfigFile.Strings[6]); if ConfigFile.Strings[7] = 'ExeOnlyOn' then ExeOnly := true else ExeOnly := false; end; ConfigFile.Free; EngineMessage(MES_LOADCONFIG_OK); except EngineMessage(MES_LOADCONFIG_ERROR); end; end; procedure SaveConfig(const ConfigFilename : string); begin SetCurrentDir(CurrentDir); try ConfigFile := TStringList.Create; with ConfigFile do begin LoadFromFile(ConfigFilename); Strings[0] := ScannerConfig.PathBase; Strings[1] := ScannerConfig.PathLog; Strings[2] := ScannerConfig.PathQuarantine; if ScannerConfig.AutoSave then Strings[3] := 'AutoSaveOn' else Strings[3] := 'AutoSaveOff'; if ScannerConfig.ShowFile then Strings[4] := 'ShowFileOn' else Strings[4] := 'ShowFileOff'; case ScannerConfig.FileAction of FILE_DELETE : Strings[5] := '0'; FILE_QUARANTIN : Strings[5] := '1'; FILE_SKIP : Strings[5] := '2'; end; case ScannerConfig.Priority of PRIORITY_NORMAL : Strings[6] := '3'; PRIORITY_HIGHT : Strings[6] := '4'; end; if ScannerConfig.ExeOnly then Strings[7] := 'ExeFileOn' else Strings[7] := 'ExeFileOff'; end; ConfigFile.SaveToFile(ConfigFilename); ConfigFile.Free; EngineMessage(MES_SAVECONFIG_OK); except EngineMessage(MES_SAVECONFIG_ERROR); end; end; end.
unit ImgManager; ////////////////////////////////////////////////// //| ImageManager unit 1.0 |// //| Copyright (C) Martin Poelstra 2000 |// //| Beryllium Engineering (www.beryllium.nu) |// ////////////////////////////////////////////////// interface uses Windows, Classes, Graphics, SysUtils; const imNormalCenter = 0; // normal, centered imNormalLeftTop = 1; // normal, not centered imStretch = 2; // just stretch imStretchAspect = 3; // stretch, but keep aspect ratio (not implemented) imTile = 4; // tiled (repeated) type PImageData = ^TImageData; TImageData = record ImgID: Integer; // Handle of image in ImageManager Mode: Integer; // drawing mode Opacity: Integer; // 100 = pure image, 0 = pure BackColor BackColor: TColor; Bounds: TRect; // size of image that has to be drawn Canvas: TCanvas; // the destination canvas end; PImgListItem = ^TImgListItem; TImgListItem = record ImgID: Integer; RefCount: Integer; FileName: string; // uppercase (for windows at least) version of the FULL filename Picture: TPicture; // of course, this is what it's all about end; TImageManager = class private ImgList: TList; NewIDCounter: Integer; function CreateListItem(const FileName: string): PImgListItem; procedure DestroyListItem(LI: PImgListItem); public constructor Create; destructor Destroy; override; function RegisterImage(FileName: string): PImageData; procedure ReleaseImage(ImgData: PImageData); // also frees ImgData function GetFileName(ImgID: Integer): string; procedure Draw(ImgData: PImageData); end; var ImageManager: TImageManager; { Little note: the ImgID is declared as an integer. Every newly created handle is chosen by using the last assigned one, incremented by 1. So, if you go on long enough, this handle will overflow. That's right. Well, I don't bother to much about that: you can load approx 2 milion images, so I guess you won't reach that anyway. I don't think Windows will run that long, so please don't bother me with comments about it :) } implementation constructor TImageManager.Create; begin inherited Create; ImgList:=TList.Create; NewIDCounter:=0; end; destructor TImageManager.Destroy; begin while ImgList.Count>0 do DestroyListItem(ImgList[ImgList.Count-1]); ImgList.Free; inherited Destroy; end; function TImageManager.CreateListItem(const FileName: string): PImgListItem; begin New(Result); Result.RefCount:=1; Result.FileName:=FileName; Result.Picture:=TPicture.Create; try Result.Picture.LoadFromFile(FileName); Result.ImgID:=NewIDCounter; Inc(NewIDCounter); ImgList.Insert(0,Result); except Result.ImgID:=-1; // error occured end; end; procedure TImageManager.DestroyListItem(LI: PImgListItem); var I: Integer; begin for I:=ImgList.Count-1 downto 0 do if ImgList[I]=LI then ImgList.Delete(I); LI.Picture.Free; SetLength(LI.FileName,0); Dispose(LI); end; function TImageManager.RegisterImage(FileName: string): PImageData; var I: Integer; LI: PImgListItem; begin FileName:=UpperCase(ExpandFileName(FileName)); New(Result); Result.Mode:=imNormalCenter; Result.Opacity:=100; Result.BackColor:=clBlack; Result.Bounds.Left:=0; Result.Bounds.Top:=0; Result.Bounds.Right:=100; Result.Bounds.Bottom:=100; // find if it is already loaded: for I:=0 to ImgList.Count-1 do if PImgListItem(ImgList[I]).FileName=FileName then with PImgListItem(ImgList[I])^ do begin Inc(RefCount); Result.ImgID:=ImgID; Exit; end; // hmmm, it isn't, let's try to load it then LI:=CreateListItem(FileName); if LI.ImgID=-1 then // couldn't load it begin Result.ImgID:=-1; DestroyListItem(LI); Exit; end; Result.ImgID:=LI.ImgID; end; procedure TImageManager.ReleaseImage(ImgData: PImageData); // also frees ImgData var I: Integer; begin for I:=0 to ImgList.Count-1 do if PImgListItem(ImgList[I]).ImgID=ImgData.ImgID then with PImgListItem(ImgList[I])^ do begin Dec(RefCount); if RefCount<=0 then DestroyListItem(ImgList[I]); Dispose(ImgData); Exit; end; Dispose(ImgData); // shouldn't come here at all... end; procedure TImageManager.Draw(ImgData: PImageData); var P: PImgListItem; I: Integer; SR, DR: TRect; // source and destination rectangle begin P:=nil; // let's find it: for I:=0 to ImgList.Count-1 do if PImgListItem(ImgList[I]).ImgID=ImgData.ImgID then begin P:=ImgList[I]; Break; end; if P=nil then // Panic! begin ImgData.Canvas.Brush.Color:=clBlack; ImgData.Canvas.FillRect(ImgData.Bounds); Exit; end; case ImgData.Mode of imNormalCenter: ImgData.Canvas.Draw( ImgData.Bounds.Left+((ImgData.Bounds.Right-ImgData.Bounds.Left-P.Picture.Width) div 2), ImgData.Bounds.Top+((ImgData.Bounds.Bottom-ImgData.Bounds.Top-P.Picture.Height) div 2), P.Picture.Graphic ); imStretch: ImgData.Canvas.StretchDraw(ImgData.Bounds,P.Picture.Graphic); imTile: begin SR.Right:=P.Picture.Width; SR.Bottom:=P.Picture.Height; DR.Top:=ImgData.Bounds.Top; repeat DR.Left:=ImgData.Bounds.Left; repeat ImgData.Canvas.Draw(DR.Left,DR.Top,P.Picture.Graphic); Inc(DR.Left,SR.Right); until DR.Left>ImgData.Bounds.Right; Inc(DR.Top,SR.Bottom); until DR.Top>ImgData.Bounds.Bottom; end; { TODO -omartin -cImgManager : StrectDrawAspect maken } else // imNormalLeftTop ImgData.Canvas.Draw(0,0,P.Picture.Graphic); end; end; function TImageManager.GetFileName(ImgID: Integer): string; var I: Integer; begin // let's find it: for I:=0 to ImgList.Count-1 do if PImgListItem(ImgList[I]).ImgID=ImgID then begin Result:=PImgListItem(ImgList[I]).FileName; Exit; end; Result:=''; end; initialization ImageManager:=TImageManager.Create; finalization ImageManager.Free; end.
unit FreeOTFEExplorerCheckFilesystem; interface uses SDFilesystem_FAT; procedure CheckFilesystem(Filesystem: TSDFilesystem_FAT); implementation uses Dialogs, Forms, SDUGeneral, SDUDialogs, SDUi18n; procedure CheckFilesystem(Filesystem: TSDFilesystem_FAT); var allOK: boolean; begin //SetStatusMsg(_('Checking filesystem...')); try allOK := Filesystem.CheckFilesystem(); finally //SetStatusMsg(''); end; if allOK then begin SDUMessageDlg(_('Filesystem OK'), mtInformation); end else begin Filesystem.Readonly := TRUE; SDUMessageDlg( SDUParamSubstitute( _('Filesystem errors detected.'+SDUCRLF+ SDUCRLF+ 'Please mount as a normal drive, and run chkdsk to correct.'+ SDUCRLF+ '%1 will continue in readonly mode'), [Application.Title] ), mtError ); end; end; END.
unit adu; interface uses SysUtils {StrToInt, IntToStr},Dialogs {error dialog}; type TIO = (StandardPolarity,ReversedPolarity, Sham,TMS,Off,StandardPolarityTrigger,ReversedPolarityTrigger, ShamTrigger); function PortIn:integer; procedure PortOutx (lOut: TIO); function PortToStr (lPort: TIO): string; function AddOpticalTrigger(lPort: TIO): TIO; //procedure PortOut(lOut: integer); var gaduHandle: Longint; implementation type ValAsLong = longint; RefAsLong = ^ValAsLong; CharRA = String[8]; CharPtr = ^CharRA; const kaduTimeout = 50; function OpenAduDevice(iTimeOut: ValAsLong): Longint; stdcall; external 'AduHid.dll'; procedure WriteAduDevice( aduHandle: ValAsLong; lpBuffer: CharPtr; nNumberOfBytesToRead: ValAsLong; lpNumberOfBytesRead: RefAsLong; iTimeout: ValAsLong ); stdcall; external 'AduHid.dll'; procedure ReadAduDevice( aduHandle: ValAsLong; lpBuffer: CharPtr; nNumberOfBytesToRead: ValAsLong; lpNumberOfBytesRead: RefAsLong; iTimeout: ValAsLong ); stdcall; external 'AduHid.dll'; function CloseAduDevice(iHandle: ValAsLong): longint; stdcall; external 'AduHid.dll'; function AddOpticalTrigger(lPort: TIO): TIO; begin result := lPort; case lPort of StandardPolarity,StandardPolarityTrigger : result := StandardPolarityTrigger; ReversedPolarity,ReversedPolarityTrigger : result :=ReversedPolarityTrigger; Sham,ShamTrigger : result := ShamTrigger; else showmessage('Serious error with AddOpticalTrigger.'); end; end; function PortToStr (lPort: TIO): string; begin case lPort of StandardPolarity : result := 'StandardPolarity'; ReversedPolarity : result := 'ReversedPolarity'; Sham : result := 'Sham'; TMS : result := 'TMS'; Off : result := 'Off'; StandardPolarityTrigger : result := 'StandardPolarityTrigger'; ReversedPolarityTrigger : result := 'ReversedPolarityTrigger'; ShamTrigger : result := 'ShamTrigger'; else result := '?'; end; end; procedure PortOut(lOut: integer); var lRead: ValAsLong; lnRead: RefAsLong; lStr: CharRA; begin //showmessage (inttostr(lout)); lnRead := @lRead; lStr := 'MK'+inttostr(lOut); WriteAduDevice(gaduHandle, @lStr[1], length(lStr), lnRead,kaduTimeout ); end; procedure PortOutx (lOut: TIO); begin case lOut of StandardPolarity : PortOut(6); ReversedPolarity : PortOut(9); Sham : PortOut(16); TMS : PortOut(16+64+128);//sham+gnd+vdd StandardPolarityTrigger : PortOut(6+128); ReversedPolarityTrigger: PortOut(9+128); ShamTrigger : PortOut(16+128); else PortOut(0); //off end; end; function PortIn:integer; var lStr : CharRA; lRead: ValAsLong; lnRead: RefAsLong; begin result := 0; lnRead := @lRead; lStr := 'PA'; WriteAduDevice(gaduHandle, @lStr[1], 2, lnRead,kaduTimeout ); ReadAduDevice(gaduHandle, @lStr[1], 2, lnRead,kaduTimeout ); if lRead < 1 then exit; result := StrToInt(lStr); end; initialization gaduHandle := OpenAduDevice(kaduTimeout ); if gaduHandle < 1 then showmessage('Warning: ADU218 not connected - you must connect the input device before running this software.'); finalization CloseAduDevice(gaduHandle); end.
unit URegraCRUDAgendamento; interface uses URegraCRUD, UEntidade, UAgendamento, URepositorioDB, URepositorioAgendamento, Dateutils; type TRegraCRUDAgendamento = class(TRegraCRUD) protected procedure ValidaAtualizacao(const coENTIDADE: TENTIDADE); override; procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; function RetornaAgendamentos: TArray<TAGENDAMENTO>; function RetornaAgendamentosConsultor(const csNome: String; const ciIdCONSULTOR: Integer): TArray<TAGENDAMENTO>; overload; function RetornaAgendamentosConsultor(const csNome: String; const ciIdCONSULTOR: Integer; const DataInicial: TDate; const QtdDias: Integer): TArray<TAGENDAMENTO>; overload; function RetornaAgendamentosConsultorComCliente(const csConsultor: String; const ciIdCONSULTOR: Integer; const csCliente: String; const ciIdCLIENTE: Integer; const DataInicial: TDate; const QtdDias: Integer): TArray<TAGENDAMENTO>; overload; procedure ValidaAgendamento(const ciIdCONSULTOR: Integer; const DataInicial: TDate; const HorarioAtendimento: TTime; const DuracaoAtedimento: TTime); end; implementation { TRegraCRUDAgendamento } uses Generics.Collections , SysUtils , UUtilitarios , UMensagens , UConstantes , RegularExpressions ; constructor TRegraCRUDAgendamento.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioAgendamento.Create); end; function TRegraCRUDAgendamento.RetornaAgendamentos: TArray<TAGENDAMENTO>; begin Result := TRepositorioAgendamento(FRepositorioDB).RetornaTodos.ToArray; end; function TRegraCRUDAgendamento.RetornaAgendamentosConsultor (const csNome: String; const ciIdCONSULTOR: Integer; const DataInicial: TDate; const QtdDias: Integer): TArray<TAGENDAMENTO>; var loAGENDAMENTO: TAGENDAMENTO; AgendaConsultor: TList<TAGENDAMENTO>; begin try Result := nil; AgendaConsultor := TList<TAGENDAMENTO>.Create; for loAGENDAMENTO in TRepositorioAgendamento(FRepositorioDB).RetornaTodos do begin if (loAGENDAMENTO.NOME_CONSULTOR = csNome) AND (loAGENDAMENTO.ID_CONSULTOR = ciIdCONSULTOR) then begin // Fazer a verificação dos dias: if (loAGENDAMENTO.DATA_INICIO >= DataInicial) AND (loAGENDAMENTO.DATA_INICIO <= INCDAY(DataInicial, QtdDias)) then begin AgendaConsultor.Add(loAGENDAMENTO); end; end; end; Result := AgendaConsultor.ToArray; finally FreeAndNil(AgendaConsultor); end; end; function TRegraCRUDAgendamento.RetornaAgendamentosConsultorComCliente (const csConsultor: String; const ciIdCONSULTOR: Integer; const csCliente: String; const ciIdCLIENTE: Integer; const DataInicial: TDate; const QtdDias: Integer): TArray<TAGENDAMENTO>; var loAGENDAMENTO: TAGENDAMENTO; AgendaConsultor: TList<TAGENDAMENTO>; begin try Result := nil; AgendaConsultor := TList<TAGENDAMENTO>.Create; for loAGENDAMENTO in TRepositorioAgendamento(FRepositorioDB).RetornaTodos do begin if (loAGENDAMENTO.NOME_CONSULTOR = csConsultor) AND (loAGENDAMENTO.ID_CONSULTOR = ciIdCONSULTOR) then begin if (loAGENDAMENTO.NOME_CLIENTE = csCliente) AND (loAGENDAMENTO.ID_CLIENTE = ciIdCLIENTE) then begin // Fazer a verificação dos dias: if (loAGENDAMENTO.DATA_INICIO >= DataInicial) AND (loAGENDAMENTO.DATA_INICIO <= INCDAY(DataInicial, QtdDias)) then begin AgendaConsultor.Add(loAGENDAMENTO); end; end; end; end; Result := AgendaConsultor.ToArray; finally FreeAndNil(AgendaConsultor); end; end; function TRegraCRUDAgendamento.RetornaAgendamentosConsultor (const csNome: String; const ciIdCONSULTOR: Integer): TArray<TAGENDAMENTO>; var loAGENDAMENTO: TAGENDAMENTO; AgendaConsultor: TList<TAGENDAMENTO>; begin try Result := nil; AgendaConsultor := TList<TAGENDAMENTO>.Create; for loAGENDAMENTO in TRepositorioAgendamento(FRepositorioDB).RetornaTodos do begin if (loAGENDAMENTO.NOME_CONSULTOR = csNome) AND (loAGENDAMENTO.ID_CONSULTOR = ciIdCONSULTOR) then begin AgendaConsultor.Add(loAGENDAMENTO); end; end; Result := AgendaConsultor.ToArray; finally FreeAndNil(AgendaConsultor); end; end; procedure TRegraCRUDAgendamento.ValidaAgendamento(const ciIdCONSULTOR: Integer; const DataInicial: TDate; const HorarioAtendimento, DuracaoAtedimento: TTime); var loAGENDAMENTO: TAGENDAMENTO; loDataHoraInicio: TDateTime; loDataHoraTermino: TDateTime; begin loDataHoraInicio := DataInicial; loDataHoraTermino := DataInicial; ReplaceTime(loDataHoraInicio, HorarioAtendimento); ReplaceTime(loDataHoraTermino, (HorarioAtendimento + DuracaoAtedimento)); for loAGENDAMENTO in TRepositorioAgendamento(FRepositorioDB).RetornaTodos do begin if ciIdCONSULTOR = loAGENDAMENTO.ID_CONSULTOR then begin if DateTimeInRange(loDataHoraInicio, loAGENDAMENTO.DATA_HORA_INICIO, loAGENDAMENTO.DATA_HORA_TERMINO) or DateTimeInRange(loDataHoraTermino, loAGENDAMENTO.DATA_HORA_INICIO, loAGENDAMENTO.DATA_HORA_TERMINO) then begin raise EValidacaoNegocio.Create(STR_AGENDAMENTO_JA_POSSUI_HORARIO_MARCADO); end; end; end; end; procedure TRegraCRUDAgendamento.ValidaAtualizacao(const coENTIDADE: TENTIDADE); begin inherited; ValidaAgendamento(TAGENDAMENTO(coENTIDADE).ID_CONSULTOR , TAGENDAMENTO(coENTIDADE).DATA_INICIO , TAGENDAMENTO(coENTIDADE).HORARIO_INICIO , TAGENDAMENTO(coENTIDADE).DURACAO); end; procedure TRegraCRUDAgendamento.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; ValidaAgendamento(TAGENDAMENTO(coENTIDADE).ID_CONSULTOR , TAGENDAMENTO(coENTIDADE).DATA_INICIO , TAGENDAMENTO(coENTIDADE).HORARIO_INICIO , TAGENDAMENTO(coENTIDADE).DURACAO); end; end.
unit PM_Messages; interface type TMode = ( AM_None, AM_Move, AM_Grabber, AM_Scale, AM_ZoomIn, AM_ZoomOut ); TCameraType = ( CT_CONST_H_DONT_OBSCURE, CT_CONST_H_OBSCURE, CT_GLIDE_TERRAIN_DONT_OBSCURE, CT_GLIDE_TERRAIN_OBSCURE, CT_GLIDE_TERRAIN_GLIDE ); const PM_CAMERA_DESCRIPTION: array [0..4] of string = ('Высота-постоянная над уровнем моря, наклон камеры-постоянный', 'Высота-постоянная над уровнем моря, обзор заданной точки', 'Плавное огибание рельефа местности, наклон камеры-постоянный', 'Плавное огибание рельефа местности, обзор заданной точки', 'Плавное огибание рельефа местности, камера огибает рельеф'); // programm messages PM_MAIN_HEADER = 'FlyGIS3D'; PM_ZONES_HEADER = 'Зона видимости '; PM_MODEL_3D = 'Трёхмерная модель местности'; PM_PROCESS_HEADER = 'Триангуляция'; PM_BREAK_TRIANGULATION = 'Прервать процесс триангуляции?'; PM_ATTENTION_HEADER = 'Внимание!'; PM_NO_POINTS_MSG = 'Нет набора точек, описывающих рельеф местности.'; PM_TN_WAS_CREATED_CONTINUE = 'Триангуляционная сеть уже создана. Продолжить?'; MIF_COLUMNS = 'Columns'; MIF_ABSOLUTE_HEIGHT = 'ВЫСОТА_АБСОЛЮТНАЯ'; MIF_PLINE = 'Pline'; PM_NO_TRAEKTORY = 'Траектория не задана!'; PM_NOT_GRAYSCALE_IMAGE_MSG = 'Изображение не полутоновое! Его можно применить '+ 'только в качестве текстуры.'; PM_NO_TRIANGULATION_NETWORK = 'Триангуляционная сеть не создана!'; PM_HEIGHT_RASTER_HEADER = 'Создание полутонового изображения'; PM_HEIGHT_RASTER_PROCESS = 'Создание высотного растра...'; PM_GET_ISOLINES_HEADER = 'Выделение изолиний'; PM_DISCRETISATION_MSG1 = 'Дискретизация по уровням (через '; PM_DISCRETISATION_MSG2 = ' пикс.)...'; PM_GET_ISOLINES_PROCESS = 'Выделение изолиний...'; PM_FORMAT_NOT_SUPPORTED_MSG = 'Формат файла не поддерживается !'; PM_NO_VISIBLE_POINT_MSG = 'Не определена точка видимости!'; PM_VISIBLE_ZONE_HEADER = 'Зона видимости '; PM_VISIBLE_ZONE_MSG1 = 'Определение зоны видимости ( выс.: '; PM_VISIBLE_ZONE_MSG2 = ' пикс.)'; PM_VISIBLE_ZONE_PROCESS = 'Определение зоны видимости...'; PM_DTM_HEADER = 'Создание ЦМРМ'; PM_DTM_PROCESS = 'Создание ЦМРМ...'; PM_POINTS_INFO = 'Всего точек: '; PM_MIN_X_INFO = 'Xmin = '; PM_MAX_X_INFO = 'Xmax = '; PM_MIN_Y_INFO = 'Ymin = '; PM_MAX_Y_INFO = 'Ymax = '; PM_MIN_Z_INFO = 'Zmin = '; PM_MAX_Z_INFO = 'Zmax = '; var CameraType: TCameraType; implementation end.
{ ID: a_zaky01 PROG: palsquare LANG: PASCAL } const angka = '0123456789ABCDEFGHIJ'; var base,i:integer; fin,fout:text; procedure check(n:longint); var length,diff,temp,i:longint; palbase:boolean; result:array[1..100] of char; procedure print; var l,i:longint; result2:array[1..100] of char; begin l:=0; diff:=n; while diff>0 do begin diff:=diff div base; inc(l); end; for i:=1 to l do begin if n mod base=0 then result2[l+1-i]:='0' else result2[l+1-i]:=angka[(n mod base)+1]; n:=n div base; end; for i:=1 to l do write(fout,result2[i]); write(fout,' '); for i:=1 to length do write(fout,result[i]); writeln(fout); end; begin length:=0; diff:=n*n; while diff>0 do begin diff:=diff div base; inc(length); end; diff:=n*n; for i:=1 to length do begin if diff mod base=0 then result[length+1-i]:='0' else result[length+1-i]:=angka[(diff mod base)+1]; diff:=diff div base; end; palbase:=true; for i:=1 to length div 2 do if result[i]<>result[length+1-i] then begin palbase:=false; break; end; if palbase then print; end; begin assign(fin,'palsquare.in'); assign(fout,'palsquare.out'); reset(fin); rewrite(fout); readln(fin,base); for i:=1 to 300 do check(i); close(fin); close(fout); end.
unit UJobXml; interface uses UModelUtil; type {$Region ' 离线Job Xml 写 ' } {$Region ' 数据结构 ' } {$Region ' 父类 ' } // 父类 TOfflineJobWriteXml = class( TChangeInfo ) end; // 父类 修改 TOfflineJobChangeXml = class( TOfflineJobWriteXml ) public PcID : string; public procedure SetPcID( _PcID : string ); end; {$EndRegion} {$Region ' 添加 ' } // 父类 添加 TOfflineJobAddXml = class( TOfflineJobChangeXml ) public FileSize, Position : Int64; FileTime : TDateTime; public procedure SetFileInfo( _FileSize, _Position : Int64 ); procedure SetFileTime( _FileTime : TDateTime ); end; // 添加 备份 TOfflineBackupJobAddXml = class( TOfflineJobAddXml ) public UpFilePath : string; public procedure SetUpFilePath( _UpFilePath : string ); end; // 添加 下载 TOfflineDownJobAddXml = class( TOfflineJobAddXml ) public FilePath : string; DownFilePath : string; public procedure SetFilePath( _FilePath : string ); procedure SetDownFilePath( _DownFilePath : string ); end; // 添加 搜索 TOfflineSearchJobAddXml = class( TOfflineDownJobAddXml ) public IsBackupFile : Boolean; BackupFilePcID : string; public procedure SetSearchXml( _IsBackupFile : Boolean; _BackupFilePcID : string ); end; // 添加 恢复 TOfflineRestoreJobAddXml = class( TOfflineDownJobAddXml ) end; {$EndRegion} {$EndRegion} {$Region ' 数据操作 ' } {$Region ' 父类 ' } TOfflineJobChangeXmlHandle = class( TChangeHandle ) protected PcID : string; protected procedure ExtractInfo;override; end; {$EndRegion} {$Region ' 添加 ' } // 父类 TOfflineJobAddXmlHandle = class( TOfflineJobChangeXmlHandle ) protected FileSize, Position : Int64; FileTime : TDateTime; public procedure Update;override; protected procedure ExtractInfo;override; end; // 备份 TOfflineBackupJobAddXmlHandle = class( TOfflineJobAddXmlHandle ) private UpFilePath : string; protected procedure ExtractInfo;override; end; // 下载 TOfflineDownJobAddXmlHandle = class( TOfflineJobAddXmlHandle ) protected FilePath : string; DownFilePath : string; protected procedure ExtractInfo;override; end; // 搜索 TOfflineSearchJobAddXmlHandle = class( TOfflineDownJobAddXmlHandle ) private IsBackupFile : Boolean; BackupFilePcID : string; protected procedure ExtractInfo;override; end; // 恢复 TOfflineRestoreJobAddXmlHandle = class( TOfflineDownJobAddXmlHandle ) end; {$EndRegion} {$EndRegion} TJobXmlWriteThread = class( TChangeXmlHandleThread ) end; implementation { TOfflineJobChangeXml } procedure TOfflineJobChangeXml.SetPcID(_PcID: string); begin PcID := _PcID; end; { TOfflineJobAddXml } procedure TOfflineJobAddXml.SetFileInfo(_FileSize, _Position: Int64); begin FileSize := _FileSize; Position := _Position; end; procedure TOfflineJobAddXml.SetFileTime(_FileTime: TDateTime); begin FileTime := _FileTime; end; { TOfflineBackupJobAddXml } procedure TOfflineBackupJobAddXml.SetUpFilePath(_UpFilePath: string); begin UpFilePath := _UpFilePath; end; { TOfflineDownJobAddXml } procedure TOfflineDownJobAddXml.SetDownFilePath(_DownFilePath: string); begin DownFilePath := _DownFilePath; end; procedure TOfflineDownJobAddXml.SetFilePath(_FilePath: string); begin FilePath := _FilePath; end; { TOfflineSearchJobAddXml } procedure TOfflineSearchJobAddXml.SetSearchXml(_IsBackupFile: Boolean; _BackupFilePcID: string); begin IsBackupFile := _IsBackupFile; BackupFilePcID := _BackupFilePcID; end; { TOfflineJobChangeXmlHandle } procedure TOfflineJobChangeXmlHandle.ExtractInfo; var OfflineJobChangeXml : TOfflineJobChangeXml; begin OfflineJobChangeXml := ( ChangeInfo as TOfflineJobChangeXml ); PcID := OfflineJobChangeXml.PcID; end; { TOfflineJobAddXmlHandle } procedure TOfflineJobAddXmlHandle.ExtractInfo; var OfflineJobAddXml : TOfflineJobAddXml; begin inherited; OfflineJobAddXml := ( ChangeInfo as TOfflineJobAddXml ); FileSize := OfflineJobAddXml.FileSize; Position := OfflineJobAddXml.Position; FileTime := OfflineJobAddXml.FileTime; end; procedure TOfflineJobAddXmlHandle.Update; begin end; { TOfflineBackupJobAddXmlHandle } procedure TOfflineBackupJobAddXmlHandle.ExtractInfo; var OfflineBackupJobAddXml : TOfflineBackupJobAddXml; begin inherited; OfflineBackupJobAddXml := ( ChangeInfo as TOfflineBackupJobAddXml ); UpFilePath := OfflineBackupJobAddXml.UpFilePath; end; { TOfflineDownJobAddXmlHandle } procedure TOfflineDownJobAddXmlHandle.ExtractInfo; var OfflineDownJobAddXml : TOfflineDownJobAddXml; begin inherited; OfflineDownJobAddXml := ( ChangeInfo as TOfflineDownJobAddXml ); FilePath := OfflineDownJobAddXml.FilePath; DownFilePath := OfflineDownJobAddXml.DownFilePath; end; { TOfflineSearchJobAddXmlHandle } procedure TOfflineSearchJobAddXmlHandle.ExtractInfo; var OfflineSearchJobAddXml : TOfflineSearchJobAddXml; begin inherited; OfflineSearchJobAddXml := ( ChangeInfo as TOfflineSearchJobAddXml ); IsBackupFile := OfflineSearchJobAddXml.IsBackupFile; BackupFilePcID := OfflineSearchJobAddXml.BackupFilePcID; end; end.
program Ex1_ListaCasamento; type rItemDaLista = record Descricao: String; Quantidade: Real; end; rLista = record Itens: array[0..9] of rItemDaLista; UltimaPosicao: Integer; end; var ListaDeCompras: rLista; nOpcao: Integer; lSair: Boolean; procedure MontarMenu; begin clrscr; writeln('1 - Adicionar'); writeln('2 - Remover'); writeln('3 - Mostrar Lista'); writeln('0 - Sair'); write('Escolha uma opção: '); readln(nOpcao); end; procedure LimparLista; begin ListaDeCompras.UltimaPosicao := -1; end; procedure Adicionar; var nNovaPosicao: Integer; begin clrscr; if (ListaDeCompras.UltimaPosicao = 4) then writeln('Erro: Não é possível adicionar mais itens') else begin Inc(ListaDeCompras.UltimaPosicao); nNovaPosicao := ListaDeCompras.UltimaPosicao; write('Descrição: '); readln(ListaDeCompras.Itens[nNovaPosicao].Descricao); write('Quantidade: '); readln(ListaDeCompras.Itens[nNovaPosicao].Quantidade); writeln('Item adicionado!'); end; readkey; end; procedure Remover; var nPosRemover, i: Integer; begin clrscr; if ListaDeCompras.UltimaPosicao = -1 then writeln('Erro: A lista está vazia!') else begin write('Qual posição deseja remover?: '); readln(nPosRemover); if nPosRemover > ListaDeCompras.UltimaPosicao then writeln('Erro: A posição ', nPosRemover, ' não existe!') else begin if nPosRemover <> ListaDeCompras.UltimaPosicao then begin for i := nPosRemover to ListaDeCompras.UltimaPosicao -1 do ListaDeCompras.Itens[i] := ListaDeCompras.Itens[i + 1]; end; ListaDeCompras.UltimaPosicao := ListaDeCompras.UltimaPosicao - 1; writeln('Item removido com sucesso!'); end; end; readkey; end; procedure MostrarLista; var i: Integer; begin clrscr; for i := 0 to ListaDeCompras.UltimaPosicao do begin writeln(i, ' - Item: ', ListaDeCompras.Itens[i].Descricao); end; readkey; end; begin LimparLista; lSair := False; while not lSair do begin MontarMenu; case nOpcao of 1: Adicionar; 2: Remover; 3: MostrarLista; else lSair := True; end; end; end.
unit XLSDbRead; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$I XLSRWII.inc} interface uses Classes, SysUtils, XLSReadWriteII, BIFFRecsII, CellFormats, db, XLSRWIIResourceStrings; type TXLSDbRead = class(TComponent) private FXLS: TXLSReadWriteII; FDataSet: TDataSet; FCol: byte; FRow: word; FSheet: integer; FIncludeFieldsInx: array of boolean; FExcludeFieldsInx: array of boolean; FIncludeFields: TStrings; FExcludeFields: TStrings; FIncludeFieldnames: boolean; procedure SetExcludeFields(const Value: TStrings); procedure SetIncludeFields(const Value: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Read; published property Column: byte read FCol write FCol; property Dataset: TDataset read FDataset write FDataset; property ExcludeFields: TStrings read FExcludeFields write SetExcludeFields; property IncludeFields: TStrings read FIncludeFields write SetIncludeFields; property IncludeFieldnames: boolean read FIncludeFieldnames write FIncludeFieldnames; property Row: word read FRow write FRow; property Sheet: integer read FSheet write FSheet; property XLS: TXLSReadWriteII read FXLS write FXLS; end; implementation { TXLSDbRead } constructor TXLSDbRead.Create(AOwner: TComponent); begin inherited Create(AOwner); FIncludeFieldnames := True; FIncludeFields := TStringList.Create; FExcludeFields := TStringList.Create; end; destructor TXLSDbRead.Destroy; begin FIncludeFields.Free; FExcludeFields.Free; inherited; end; procedure TXLSDbRead.Read; var i,ARow,ACol,FmtDate,FmtTime: integer; Field: TField; begin if FXLS = Nil then raise Exception.Create(ersNoTXLSReadWriteIIDefined); if FSheet >= FXLS.Sheets.Count then raise Exception.Create(ersSheetIndexOutOfRange); if FDataset = Nil then raise Exception.Create(ersNoDatasetDefined); SetLength(FIncludeFieldsInx,FDataset.FieldCount); SetLength(FExcludeFieldsInx,FDataset.FieldCount); for i := 0 to FDataset.FieldCount - 1 do begin FIncludeFieldsInx[i] := FIncludeFields.Count <= 0; FExcludeFieldsInx[i] := False; end; for i := 0 to FIncludeFields.Count - 1 do begin Field := FDataset.Fields.FindField(FIncludeFields[i]); if Field <> Nil then FIncludeFieldsInx[Field.Index] := True; end; for i := 0 to FExcludeFields.Count - 1 do begin Field := FDataset.Fields.FindField(FExcludeFields[i]); if Field <> Nil then FExcludeFieldsInx[Field.Index] := True; end; ARow := FRow; FmtDate := -1; FmtTime := -1; ACol := FCol; for i := 0 to FDataset.FieldCount - 1 do begin if FIncludeFieldsInx[i] and not FExcludeFieldsInx[i] then begin if FIncludeFieldnames then FXLS.Sheets[FSheet].AsString[ACol,ARow] := FDataset.Fields[i].DisplayName; if FDataset.Fields[i].DataType in [ftDate,ftDateTime] then FmtDate := 0; if FDataset.Fields[i].DataType in [ftTime] then FmtTime := 0; Inc(ACol); end; end; if FIncludeFieldnames then Inc(ARow); if FmtDate = 0 then with FXLS.Formats.Add do begin NumberFormat := TInternalNumberFormats[NUMFORMAT_DATE]; FmtDate := FXLS.Formats.Count - 1; end; if FmtTime = 0 then with FXLS.Formats.Add do begin NumberFormat := TInternalNumberFormats[NUMFORMAT_TIME]; FmtTime := FXLS.Formats.Count - 1; end; FDataset.First; while not FDataset.Eof do begin ACol := FCol; for i := 0 to FDataset.FieldCount - 1 do begin if FIncludeFieldsInx[i] and not FExcludeFieldsInx[i] then begin if not FDataset.Fields[i].IsNull then begin case FDataset.Fields[i].DataType of ftString, {$ifndef ver120} ftVariant, {$endif} ftFixedChar, {$ifdef D6_AND_LATER} ftGuid: FXLS.Sheets[FSheet].AsString[ACol,ARow] := FDataset.Fields[i].AsString; {$endif} ftWideString: FXLS.Sheets[FSheet].AsWideString[ACol,ARow] := FDataset.Fields[i].AsString; ftMemo, ftFmtMemo: FXLS.Sheets[FSheet].AsString[ACol,ARow] := FDataset.Fields[i].AsString; ftSmallint, ftInteger, ftLargeInt, ftWord, ftCurrency, {$ifdef D6_AND_LATER} ftBCD, ftFMTBcd, {$endif} ftAutoInc, ftFloat: FXLS.Sheets[FSheet].AsFloat[ACol,ARow] := FDataset.Fields[i].AsFloat; ftBoolean: FXLS.Sheets[FSheet].AsBoolean[ACol,ARow] := FDataset.Fields[i].AsBoolean; ftGraphic: ; ftDate, {$ifdef D6_AND_LATER} ftTimestamp, {$endif} ftDateTime:FXLS.Sheets[FSheet].WriteNumber(ACol,ARow,FmtDate,FDataset.Fields[i].AsFloat); ftTime: FXLS.Sheets[FSheet].WriteNumber(ACol,ARow,FmtTime,FDataset.Fields[i].AsFloat); end; end; Inc(ACol); end; end; Inc(ARow); if ARow >= FXLS.MaxRowCount then Break; FDataset.Next; end; FXLS.Sheets[FSheet].CalcDimensions; end; procedure TXLSDbRead.SetExcludeFields(const Value: TStrings); begin FExcludeFields.Assign(Value); end; procedure TXLSDbRead.SetIncludeFields(const Value: TStrings); begin FIncludeFields.Assign(Value); end; end.
unit frmFindDialogUnit; { The lazarus finddialog window has too many options I never use, AND when you remove them, the up/down direction disappears as well, and overal shoddy look Thus this version instead } {$mode delphi} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, betterControls; type { TfrmFindDialog } TFindDirection=(fdUp, fdDown); TfrmFindDialog = class(TForm) btnFind: TButton; Button1: TButton; cbCaseSensitive: TCheckBox; edtText: TEdit; gbDirection: TGroupBox; Label1: TLabel; lblDescription: TLabel; rbDirectionUp: TRadioButton; rbDirectionDown: TRadioButton; private { private declarations } function getFindText: string; procedure setFindText(s: string); function getDirection: TFindDirection; procedure setDirection(d: TFindDirection); function getCaseSensitive: boolean; procedure setCaseSensitive(s: boolean); function getShowDirection: boolean; procedure setShowDirection(s: boolean); function getShowCaseSensitive: boolean; procedure setShowCaseSensitive(s: boolean); function getDescription: string; procedure setDescription(s: string); public { public declarations } function execute:boolean; property FindText: string read getFindText write setFindText; property Description: string read getDescription write setDescription; property Direction: TFindDirection read getDirection write setDirection; property CaseSensitive: boolean read getCaseSensitive write setCaseSensitive; property ShowDirection: boolean read getShowDirection write setShowDirection; property ShowCaseSensitive: boolean read getShowCaseSensitive write setShowCaseSensitive; end; implementation {$R *.lfm} function TfrmFindDialog.getDescription: string; begin result:=lblDescription.caption; end; procedure TfrmFindDialog.setDescription(s: string); begin lblDescription.caption:=s; end; function TfrmFindDialog.getShowDirection: boolean; begin result:=gbDirection.Visible; end; procedure TfrmFindDialog.setShowDirection(s: boolean); begin gbDirection.visible:=s; end; function TfrmFindDialog.getShowCaseSensitive: boolean; begin result:=cbCaseSensitive.visible; end; procedure TfrmFindDialog.setShowCaseSensitive(s: boolean); begin cbCaseSensitive.visible:=s; end; function TfrmFindDialog.getCaseSensitive: boolean; begin result:=cbCaseSensitive.checked; end; procedure TfrmFindDialog.setCaseSensitive(s: boolean); begin cbCaseSensitive.checked:=s; end; function TfrmFindDialog.getDirection: TFindDirection; begin if rbDirectionUp.checked then result:=fdUp else result:=fdDown; end; procedure TfrmFindDialog.setDirection(d: TFindDirection); begin if d=fdDown then rbDirectionDown.Checked:=true else rbDirectionUp.checked:=true; end; function TfrmFindDialog.getFindText: string; begin result:=edtText.Text; end; procedure TfrmFindDialog.setFindText(s: string); begin edtText.Text:=s; end; function TfrmFindDialog.execute:boolean; begin result:=showmodal=mrok; end; end.
unit ErrorHandler; //This unit implements functions for tracking the last error received from the data-tier, and logging errors. interface uses Sysutils, Exceptions, Windows, classes, typex, systemx, stringx; function GetResultCodeForException(e: Exception): integer; procedure GetErrorLogHTML(slOutput: TStringList); procedure LogError(sLocation, sMessage: widestring; iCode: integer); procedure LogErrorToFile(sLocation, sMessage: widestring; iCode: integer); procedure LockErrorLog; procedure UnlockErrorLog; var slErrorLog: TStringList; sectError: _RTL_CRITICAL_SECTION; implementation uses {$IFNDEF NOSERVER} WebConfig, {$ENDIF} WebString; //------------------------------------------------------------------------------ function GetResultCodeForException(e: Exception): integer; //Checks the class type of the exception passed, and generates an HTTP result code for it begin if e is ETransportError then result := 503 //Service Unavailable else result := 500; //Internal Server Error end; //------------------------------------------------------------------------------ procedure LockErrorLog; //Locks the error log with a critical section so that other threads to not write at the same time. begin EnterCriticalSection(sectError); end; //------------------------------------------------------------------------------ procedure UnlockErrorLog; //UnLocks the error log with a critical section so that other threads may write. begin LeaveCriticalSection(sectError); end; //------------------------------------------------------------------------------ procedure LogError(sLocation, sMessage: widestring; iCode: integer); //Logs an error to the in-memory error log. begin LockErrorLog; try try slErrorLog.add('*'+FormatDateTime('yyyymmdd-hh:nn:ss', now)+inttostr(iCode)+' '+MakeThreadSafe(sLocation)); slErrorLog.add(MakeThreadSafe(sMessage)); while slErrorLog.count > 500 do begin slErrorLog.delete(0); end; except end; finally UnLockErrorLog; end; try LogErrorToFile(sLocation, sMessage, iCode); except end; end; //------------------------------------------------------------------------------ procedure LogErrorToFile(sLocation, sMessage: widestring; iCode: integer); //Logs an error to an error log file. var f: TextFile; sfile: ansistring; sTemp: ansistring; begin exit; LockErrorLog; sTemp := MakeThreadSafe(sMessage); try try {$IFNDEF NOSERVER} sFile := slash(dllpath+WebServerConfig.LogFileName)+'error.'+formatDateTime('yyyymmdd', now)+'.txt'; ForceDirectories(extractfilepath(sFile)); AssignFile(f, sFile); if fileexists(sfile) then Append(f) else Rewrite(f); try writeln(f, '*'+FormatDateTime('yyyymmdd-hh:nn:ss', now)+inttostr(iCode)+' '+MakethreadSafe(sLocation)); writeln(f, sTemp); finally CloseFile(f); end; {$ENDIF} except Beep(1000,100); end; finally UnLockErrorLog; end; end; procedure AuditLog(sMessage: ansistring); //Writes sMessage to the server audit log. var f: TextFile; sfile: ansistring; sTemp: ansistring; begin sTemp := sMessage; LockErrorLog; try try {$IFNDEF NOSERVER} sFile := WebServerConfig.LogFileName+'.'+SlashDot(DateToStr(date)+'.txt'); {$ENDIF} AssignFile(f, sFile); if fileexists(sfile) then Append(f) else Rewrite(f); try writeln(f, '*'+FormatDateTime('yyyymmdd-hh:nn:ss', now)+' '+sMessage); finally CloseFile(f); end; except Beep(1000,100); end; finally UnLockErrorLog; end; end; procedure GetErrorLogHTML(slOutput: TStringList); //Returns the in-memory error log (limited to 500 lines) in HTML format for display //on web pages. var t: integer; begin LockErrorLog; try for t:= 0 to slErrorLog.count -1 do begin if pos('*', slErrorLog[t])>0 then slOutput.add('<B>'+slErrorLog[t]+'</B><BR>') else slOutput.add(slErrorLog[t]+'<BR>'); end; finally UnLockErrorLog; end; end; //------------------------------------------------------------------------------ initialization InitializeCriticalSection(sectError); LockErrorLog; try slErrorLog := TStringList.create; finally UnlockErrorLog; end; //------------------------------------------------------------------------------ finalization LockErrorLog; try slErrorLog.free; finally UnlockErrorLog; end; DeleteCriticalSection(secterror); end.
unit UniConvert; // Convert from a codepage to the current one using unicode! interface uses Unicode; Procedure Init_Convert(SourceCP:longint); Procedure Uninit_Convert; Function Convert(s:AnsiString):AnsiString; implementation const Convert_Initialized:boolean=false; var ToUc,FromUc:UConvObject; procedure Init_Convert(SourceCP:longint); var UniCPName:pUniString; rc:longint; begin Convert_Initialized:=false; getmem(UniCPName,1024); if UniCPName=Nil then exit; // *** Not enough memory to create Unicode CP Name string! rc:=UniMapCpToUcsCp(SourceCP,UniCPName,1024); if rc<>0 then // *** Error mapping codepage to Unicode codepage begin freemem(UniCPName); exit; end; rc:=UniCreateUconvObject(UniCPName, ToUC); if rc<>0 then begin freemem(UniCPName); exit; // *** Error creating Unicode convertation object end; // Ok, we have the unicode object that converts from pchar to unicode. Now the backwards direction. UniCPName^[0]:=0; // Empty string: convert to actual codepage! rc:=UniCreateUconvObject(UniCPName, FromUC); if rc<>0 then begin UniFreeUconvObject(ToUC); freemem(UniCPName); exit; // *** Error creating Unicode convertation object end; Convert_Initialized:=true; freemem(UniCPName); end; procedure Uninit_Convert; begin if Convert_Initialized then begin Convert_Initialized:=false; UniFreeUconvObject(FromUC); UniFreeUconvObject(ToUC); end; end; Function Convert(s:AnsiString):AnsiString; var UniName:pUniString; UniCharsLeft,inBytesLeft,NonIdentical:size_t; outbytesleft:size_t; rc:longint; ps:pointer; TempS:AnsiString; pus:pUniString; begin temps:=s; // Use local variable instead of parameter! // Unicode api seems to change the parameter even if it is // passed as value, not address! (might be AnsiString problem?) if length(s)>0 then TempS[1]:=s[1]; // Make sure it will be allocated, not just address-copied! result:=TempS; if not Convert_Initialized then exit; getmem(UniName,sizeof(UniChar)*(length(TempS)+1)); if UniName=Nil then exit; // *** Not enough memory to create temporary Unicode string! inbytesleft:=length(TempS)+1; UniCharsLeft:=inBytesLeft; Nonidentical:=0; ps:=@TempS[1]; // The function will change the addresses, so use a local variable! pus:=UniName; rc:=UniUconvToUcs(ToUC,ps,inBytesLeft,pus,UniCharsLeft,nonidentical); if rc=0 then begin // now back from unicode to actual codepage outbytesleft:=length(TempS); UniCharsLeft:=UniStringLength(UniName); Nonidentical:=0; ps:=@TempS[1]; pus:=UniName; rc:=UniUconvFromUcs(FromUC,pus,UniCharsLeft,ps,OutBytesLeft,nonidentical); if rc=0 then result:=TempS; end; freemem(UniName); end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Configuração do boleto The MIT License Copyright: Copyright (C) 2016 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit UFinConfiguracaoBoleto; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, FinConfiguracaoBoletoVO, FinConfiguracaoBoletoController, Tipos, Atributos, Constantes, LabeledCtrls, JvToolEdit, Mask, JvExMask, JvBaseEdits, Math, StrUtils, ActnList, Generics.Collections, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, ShellApi, ACBrBoleto, Controller; type [TFormDescription(TConstantes.MODULO_CONTAS_RECEBER, 'Configurações do Boleto')] TFFinConfiguracaoBoleto = class(TFTelaCadastro) PanelParcelas: TPanel; PanelMestre: TPanel; EditInstrucao01: TLabeledEdit; EditTaxaMulta: TLabeledCalcEdit; EditIdContaCaixa: TLabeledCalcEdit; EditContaCaixa: TLabeledEdit; EditInstrucao02: TLabeledEdit; EditCaminhoArquivoRemessa: TLabeledEdit; SpeedButton1: TSpeedButton; EditCaminhoArquivoRetorno: TLabeledEdit; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; EditCaminhoArquivoLogotipoBanco: TLabeledEdit; SpeedButton4: TSpeedButton; EditCaminhoArquivoPdfBoleto: TLabeledEdit; MemoMensagem: TLabeledMemo; EditLocalPagamento: TLabeledEdit; ComboBoxLayoutRemessa: TLabeledComboBox; ComboBoxAceite: TLabeledComboBox; ComboBoxEspecie: TLabeledComboBox; EditCarteira: TLabeledEdit; EditCodigoConvenio: TLabeledEdit; EditCodigoCedente: TLabeledEdit; procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure SpeedButton4Click(Sender: TObject); procedure EditIdContaCaixaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FFinConfiguracaoBoleto: TFFinConfiguracaoBoleto; implementation uses ULookup, Biblioteca, UDataModule, ContaCaixaVO, ContaCaixaController; {$R *.dfm} {$REGION 'Infra'} procedure TFFinConfiguracaoBoleto.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TFinConfiguracaoBoletoVO; ObjetoController := TFinConfiguracaoBoletoController.Create; inherited; end; procedure TFFinConfiguracaoBoleto.SpeedButton1Click(Sender: TObject); begin FDataModule.Folder.Execute; EditCaminhoArquivoRemessa.Text := StringReplace(FDataModule.Folder.Directory,'\','/',[rfReplaceAll]) + '/'; end; procedure TFFinConfiguracaoBoleto.SpeedButton2Click(Sender: TObject); begin FDataModule.Folder.Execute; EditCaminhoArquivoRetorno.Text := StringReplace(FDataModule.Folder.Directory,'\','/',[rfReplaceAll]) + '/'; end; procedure TFFinConfiguracaoBoleto.SpeedButton3Click(Sender: TObject); begin FDataModule.Folder.Execute; EditCaminhoArquivoLogotipoBanco.Text := StringReplace(FDataModule.Folder.Directory,'\','/',[rfReplaceAll]) + '/'; end; procedure TFFinConfiguracaoBoleto.SpeedButton4Click(Sender: TObject); begin FDataModule.Folder.Execute; EditCaminhoArquivoPdfBoleto.Text := StringReplace(FDataModule.Folder.Directory,'\','/',[rfReplaceAll]) + '/'; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFFinConfiguracaoBoleto.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdContaCaixa.SetFocus; end; end; function TFFinConfiguracaoBoleto.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdContaCaixa.SetFocus; end; end; function TFFinConfiguracaoBoleto.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('FinConfiguracaoBoletoController.TFinConfiguracaoBoletoController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('FinConfiguracaoBoletoController.TFinConfiguracaoBoletoController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFFinConfiguracaoBoleto.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TFinConfiguracaoBoletoVO.Create; TFinConfiguracaoBoletoVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id; TFinConfiguracaoBoletoVO(ObjetoVO).IdContaCaixa := EditIdContaCaixa.AsInteger; TFinConfiguracaoBoletoVO(ObjetoVO).ContaCaixaNome := EditContaCaixa.Text; TFinConfiguracaoBoletoVO(ObjetoVO).Instrucao01 := EditInstrucao01.Text; TFinConfiguracaoBoletoVO(ObjetoVO).Instrucao02 := EditInstrucao02.Text; TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoRemessa := EditCaminhoArquivoRemessa.Text; TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoRetorno := EditCaminhoArquivoRetorno.Text; TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoLogotipo := EditCaminhoArquivoLogotipoBanco.Text; TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoPdf := EditCaminhoArquivoPdfBoleto.Text; TFinConfiguracaoBoletoVO(ObjetoVO).Mensagem := MemoMensagem.Text; TFinConfiguracaoBoletoVO(ObjetoVO).LocalPagamento := EditLocalPagamento.Text; TFinConfiguracaoBoletoVO(ObjetoVO).LayoutRemessa := ComboBoxLayoutRemessa.Text; TFinConfiguracaoBoletoVO(ObjetoVO).Aceite := IfThen(ComboBoxAceite.ItemIndex = 0, 'S', 'N'); TFinConfiguracaoBoletoVO(ObjetoVO).Especie := Copy(ComboBoxEspecie.Text, 1, 2); TFinConfiguracaoBoletoVO(ObjetoVO).Carteira := EditCarteira.Text; TFinConfiguracaoBoletoVO(ObjetoVO).CodigoConvenio := EditCodigoConvenio.Text; TFinConfiguracaoBoletoVO(ObjetoVO).CodigoCedente := EditCodigoCedente.Text; TFinConfiguracaoBoletoVO(ObjetoVO).TaxaMulta := EditTaxaMulta.Value; if StatusTela = stInserindo then begin TController.ExecutarMetodo('FinConfiguracaoBoletoController.TFinConfiguracaoBoletoController', 'Insere', [TFinConfiguracaoBoletoVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TFinConfiguracaoBoletoVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('FinConfiguracaoBoletoController.TFinConfiguracaoBoletoController', 'Altera', [TFinConfiguracaoBoletoVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFFinConfiguracaoBoleto.EditIdContaCaixaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdContaCaixa.Value <> 0 then Filtro := 'ID = ' + EditIdContaCaixa.Text else Filtro := 'ID=0'; try EditIdContaCaixa.Clear; EditContaCaixa.Clear; if not PopulaCamposTransientes(Filtro, TContaCaixaVO, TContaCaixaController) then PopulaCamposTransientesLookup(TContaCaixaVO, TContaCaixaController); if CDSTransiente.RecordCount > 0 then begin EditIdContaCaixa.Text := CDSTransiente.FieldByName('ID').AsString; EditContaCaixa.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditInstrucao01.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFFinConfiguracaoBoleto.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TFinConfiguracaoBoletoVO(TController.BuscarObjeto('FinConfiguracaoBoletoController.TFinConfiguracaoBoletoController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdContaCaixa.AsInteger := TFinConfiguracaoBoletoVO(ObjetoVO).IdContaCaixa; EditContaCaixa.Text := TFinConfiguracaoBoletoVO(ObjetoVO).ContaCaixaNome; EditInstrucao01.Text := TFinConfiguracaoBoletoVO(ObjetoVO).Instrucao01; EditInstrucao02.Text := TFinConfiguracaoBoletoVO(ObjetoVO).Instrucao02; EditCaminhoArquivoRemessa.Text := TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoRemessa; EditCaminhoArquivoRetorno.Text := TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoRetorno; EditCaminhoArquivoLogotipoBanco.Text := TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoLogotipo; EditCaminhoArquivoPdfBoleto.Text := TFinConfiguracaoBoletoVO(ObjetoVO).CaminhoArquivoPdf; MemoMensagem.Text := TFinConfiguracaoBoletoVO(ObjetoVO).Mensagem; EditLocalPagamento.Text := TFinConfiguracaoBoletoVO(ObjetoVO).LocalPagamento; ComboBoxLayoutRemessa.Text := TFinConfiguracaoBoletoVO(ObjetoVO).LayoutRemessa; ComboBoxAceite.ItemIndex := AnsiIndexStr(TFinConfiguracaoBoletoVO(ObjetoVO).Aceite, ['S', 'N']); ComboBoxEspecie.ItemIndex := AnsiIndexStr(TFinConfiguracaoBoletoVO(ObjetoVO).Especie, ['DM', 'DS', 'RC', 'NP']); EditCarteira.Text := TFinConfiguracaoBoletoVO(ObjetoVO).Carteira; EditCodigoConvenio.Text := TFinConfiguracaoBoletoVO(ObjetoVO).CodigoConvenio; EditCodigoCedente.Text := TFinConfiguracaoBoletoVO(ObjetoVO).CodigoCedente; EditTaxaMulta.Value := TFinConfiguracaoBoletoVO(ObjetoVO).TaxaMulta; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, Sugar.TestFramework; type DocumentTypeTest = public class (Testcase) private Doc: XmlDocument; Data: XmlDocumentType; public method Setup; override; method Name; method LocalName; method PublicId; method SystemId; method NodeType; method AccessFromDocument; method Childs; method Value; end; implementation method DocumentTypeTest.Setup; begin Doc := XmlDocument.FromString(XmlTestData.DTDXml); Assert.IsNotNull(Doc); Data := Doc.FirstChild as XmlDocumentType; Assert.IsNotNull(Data); end; method DocumentTypeTest.PublicId; begin Assert.IsNotNull(Data.PublicId); Assert.CheckString("", Data.PublicId); Doc := XmlDocument.FromString(XmlTestData.CharXml); Assert.IsNotNull(Doc); Assert.IsNotNull(Doc.DocumentType); Assert.IsNotNull(Doc.DocumentType.PublicId); Assert.CheckString("-//W3C//DTD XHTML 1.0 Transitional//EN", Doc.DocumentType.PublicId); end; method DocumentTypeTest.SystemId; begin Assert.IsNotNull(Data.SystemId); Assert.CheckString("", Data.SystemId); Doc := XmlDocument.FromString(XmlTestData.CharXml); Assert.IsNotNull(Doc); Assert.IsNotNull(Doc.DocumentType); Assert.IsNotNull(Doc.DocumentType.SystemId); Assert.CheckString("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", Doc.DocumentType.SystemId); end; method DocumentTypeTest.NodeType; begin Assert.CheckBool(true, Data.NodeType = XmlNodeType.DocumentType); end; method DocumentTypeTest.AccessFromDocument; begin Assert.IsNotNull(Doc.DocumentType); Assert.CheckBool(true, Doc.DocumentType.Equals(Data)); end; method DocumentTypeTest.Name; begin Assert.IsNotNull(Data.Name); Assert.CheckString("note", Data.Name); end; method DocumentTypeTest.LocalName; begin Assert.IsNotNull(Data.LocalName); Assert.CheckString("note", Data.LocalName); end; method DocumentTypeTest.Childs; begin Assert.CheckInt(0, Data.ChildCount); Assert.IsNull(Data.FirstChild); Assert.IsNull(Data.LastChild); Assert.CheckInt(0, length(Data.ChildNodes)); end; method DocumentTypeTest.Value; begin Assert.IsNull(Data.Value); end; end.
unit Thread.SalvaRemessasVA; interface uses System.Classes, System.Generics.Collections, System.SysUtils, Model.RemessasVA, DAO.RemessasVA, Vcl.Forms, System.UITypes, Model.BancaVA, DAO.BancaVA, uGlobais; type Thread_SalvaRemessasVA = class(TThread) private { Private declarations } FdPos: Double; FTexto: String; remessa : TRemessasVA; remessas : TObjectList<TRemessasVA>; remessaDAO : TRemessasVADAO; banca : TBancaVA; bancas : TObjectList<TBancaVA>; bancaDAO : TBancaVADAO; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProcesso; procedure TerminaProcesso; procedure SetupClass; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_SalvaRemessasVA.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { Thread_SalvaRemessasVA } uses View.ResultatoProcesso, udm, View.ManutencaoRepartes; procedure Thread_SalvaRemessasVA.IniciaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Visible := True; view_ManutencaoRepartesVA.dsRepartes.Enabled := False; view_ManutencaoRepartesVA.pbRepartes.Position := 0; view_ManutencaoRepartesVA.pbRepartes.Refresh; end; procedure Thread_SalvaRemessasVA.Execute; var ocorrenciaTMP: TRemessasVA; iTotal : Integer; iPos : Integer; sMensagem: String; iId: Integer; begin { Place thread code here } try Synchronize(IniciaProcesso); if not Assigned(view_ResultadoProcesso) then begin view_ResultadoProcesso := Tview_ResultadoProcesso.Create(Application); end; view_ResultadoProcesso.Show; Screen.Cursor := crHourGlass; remessaDAO := TRemessasVADAO.Create(); remessa := TRemessasVA.Create(); iTotal := view_ManutencaoRepartesVA.tbRepartes.RecordCount; iPos := 0; FdPos := 0; if not view_ManutencaoRepartesVA.tbRepartes.IsEmpty then view_ManutencaoRepartesVA.tbRepartes.First; while not view_ManutencaoRepartesVA.tbRepartes.Eof do begin sMensagem := ''; SetupClass; if remessa.Id > 0 then begin if not remessaDAO.Update(remessa) then begin sMensagem := 'Erro ao alterar a remessa ' + view_ManutencaoRepartesVA.tbRepartesCOD_BANCA.AsString + '-' + view_ManutencaoRepartesVA.tbRepartesDAT_REMESSA.AsString + '-' + view_ManutencaoRepartesVA.tbRepartesCOD_PRODUTO.AsString; end; end else begin if not remessaDAO.Insert(remessa) then begin sMensagem := 'Erro ao incluir a remessa ' + view_ManutencaoRepartesVA.tbRepartesCOD_BANCA.AsString + '-' + view_ManutencaoRepartesVA.tbRepartesDAT_REMESSA.AsString + '-' + view_ManutencaoRepartesVA.tbRepartesCOD_PRODUTO.AsString; end; end; if not sMensagem.IsEmpty then begin view_ResultadoProcesso.edtResultado.Lines.Add(sMensagem); view_ResultadoProcesso.edtResultado.Refresh; end; view_ManutencaoRepartesVA.tbRepartes.Next; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally Synchronize(TerminaProcesso); Screen.Cursor := crDefault; remessaDAO.Free; remessa.Free; end; end; procedure Thread_SalvaRemessasVA.AtualizaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Position := FdPos; view_ManutencaoRepartesVA.pbRepartes.Properties.Text := FormatFloat('0.00%',FdPos); view_ManutencaoRepartesVA.pbRepartes.Refresh; end; procedure Thread_SalvaRemessasVA.TerminaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Position := 0; view_ManutencaoRepartesVA.pbRepartes.Properties.Text := ''; view_ManutencaoRepartesVA.pbRepartes.Refresh; view_ManutencaoRepartesVA.tbRepartes.IsLoading := False; view_ManutencaoRepartesVA.dsRepartes.Enabled := True; view_ManutencaoRepartesVA.pbRepartes.Visible := False; end; procedure Thread_SalvaRemessasVA.SetupClass; var lLog: TStringList; begin lLog := TStringList.Create(); remessa.Id := view_ManutencaoRepartesVA.tbRepartesID_REMESSA.AsInteger; remessa.Distribuidor := view_ManutencaoRepartesVA.tbRepartesCOD_DISTRIBUIDOR.AsInteger; remessa.Banca := view_ManutencaoRepartesVA.tbRepartesCOD_BANCA.AsInteger; remessa.Produto := view_ManutencaoRepartesVA.tbRepartesCOD_PRODUTO.AsString; remessa.DataRemessa := view_ManutencaoRepartesVA.tbRepartesDAT_REMESSA.AsDateTime; remessa.NumeroRemessa := view_ManutencaoRepartesVA.tbRepartesNUM_REMESSA.AsString; remessa.Remessa := view_ManutencaoRepartesVA.tbRepartesQTD_REMESSA.AsFloat; remessa.DataRecobertura := view_ManutencaoRepartesVA.tbRepartesDAT_RECOBERTURA.AsDateTime; remessa.Recobertura := view_ManutencaoRepartesVA.tbRepartesQTD_RECOBERTURA.AsFloat; remessa.DataChamada := view_ManutencaoRepartesVA.tbRepartesDAT_CHAMADA.AsDateTime; remessa.NumeroDevolucao := view_ManutencaoRepartesVA.tbRepartesNUM_DEVOLUCAO.AsString; remessa.Encalhe := view_ManutencaoRepartesVA.tbRepartesQTD_ENCALHE.AsFloat; remessa.ValorCobranca := view_ManutencaoRepartesVA.tbRepartesVAL_COBRANCA.AsFloat; remessa.ValorVenda := view_ManutencaoRepartesVA.tbRepartesVAL_VENDA.AsFloat; remessa.Inventario := view_ManutencaoRepartesVA.tbRepartesDOM_INVENTARIO.AsInteger; lLog.Text := view_ManutencaoRepartesVA.tbRepartesDES_LOG.AsString; if remessa.Id = 0 then begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now()) + ' inserido por ' + uGlobais.sUsuario); end else begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now()) + ' alterado por ' + uGlobais.sUsuario); end; remessa.Log := lLog.Text; lLog.Free; end; end.
unit uFormulario; { Exemplo de Bridge com Delphi Criado por André Luis Celestino: www.andrecelestino.com } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls, Buttons; type TfFormulario = class(TForm) ClientDataSetClientes: TClientDataSet; ClientDataSetProdutos: TClientDataSet; DBGridClientes: TDBGrid; DBGridProdutos: TDBGrid; BitBtnExportarClientesXLS: TBitBtn; BitBtnExportarClientesHTML: TBitBtn; BitBtnExportarProdutosXLS: TBitBtn; BitBtnExportarProdutosHTML: TBitBtn; DataSourceClientes: TDataSource; DataSourceProdutos: TDataSource; ClientDataSetClientesCodigo: TIntegerField; ClientDataSetClientesNome: TStringField; ClientDataSetClientesCidade: TStringField; ClientDataSetProdutosCodigo: TIntegerField; ClientDataSetProdutosDescricao: TStringField; ClientDataSetProdutosEstoque: TIntegerField; Bevel: TBevel; LabelClientes: TLabel; LabelProdutos: TLabel; procedure FormCreate(Sender: TObject); procedure BitBtnExportarClientesXLSClick(Sender: TObject); procedure BitBtnExportarClientesHTMLClick(Sender: TObject); procedure BitBtnExportarProdutosXLSClick(Sender: TObject); procedure BitBtnExportarProdutosHTMLClick(Sender: TObject); end; var fFormulario: TfFormulario; implementation uses uInterfaceExportador, uExportadorClientes, uExportadorProdutos, uFormatoXLS, uFormatoHTML; {$R *.dfm} procedure TfFormulario.BitBtnExportarClientesXLSClick(Sender: TObject); var Exportador: IExportador; begin Exportador := TExportadorClientes.Create(TFormatoXLS.Create); try Exportador.ExportarDados(ClientDataSetClientes.Data); finally Exportador := nil; end; end; procedure TfFormulario.BitBtnExportarClientesHTMLClick(Sender: TObject); var Exportador: IExportador; begin Exportador := TExportadorClientes.Create(TFormatoHTML.Create); try Exportador.ExportarDados(ClientDataSetClientes.Data); finally Exportador := nil; end; end; procedure TfFormulario.FormCreate(Sender: TObject); var CaminhoAplicacao: string; begin CaminhoAplicacao := ExtractFilePath(Application.ExeName); ClientDataSetClientes.LoadFromFile(CaminhoAplicacao + 'Clientes.xml'); ClientDataSetProdutos.LoadFromFile(CaminhoAplicacao + 'Produtos.xml'); end; procedure TfFormulario.BitBtnExportarProdutosXLSClick(Sender: TObject); var Exportador: IExportador; begin Exportador := TExportadorProdutos.Create(TFormatoXLS.Create); try Exportador.ExportarDados(ClientDataSetProdutos.Data); finally Exportador := nil; end; end; procedure TfFormulario.BitBtnExportarProdutosHTMLClick(Sender: TObject); var Exportador: IExportador; begin Exportador := TExportadorProdutos.Create(TFormatoHTML.Create); try Exportador.ExportarDados(ClientDataSetProdutos.Data); finally Exportador := nil; end; end; end.
{ Subroutine STRING_F_INTRJ (S, I, FW, STAT) * * Create the string representation of the machine integer I in the * variable length string S. I will be right justified in a field of * width FW. STAT is the completion status code. It will be abnormal * if FW is too small for the value in I. } module string_f_intrj; define string_f_intrj; %include 'string2.ins.pas'; procedure string_f_intrj ( {right-justified string from machine integer} in out s: univ string_var_arg_t; {output string} in i: sys_int_machine_t; {input integer} in fw: string_index_t; {width of output field in string S} out stat: sys_err_t); {completion code} val_param; var im: sys_int_max_t; {integer of right format for convert routine} begin im := i; {into format for convert routine} string_f_int_max_base ( {make string from integer} s, {output string} im, {input integer} 10, {number base} fw, {output field width in characters} [], {signed number, no lead zeros or plus} stat); end;
unit ObjectLines; interface uses Classes, SysUtils; {$DEFINE NOFORMS} type TLines = class(TObject) constructor Create; destructor Destroy; override; procedure SetLanguage(Path: string); function GetIcon(Path: string): string; protected function Get(Index: Integer): string; procedure Put(Index: Integer; Item: string); public property Items[Index: Integer]: string read Get write Put; default; private InternalList: TStringList; List : TStringList; IconsDef : TStringList; procedure SetIcons; procedure AddIconDef(Icon: string; LineIndex: Integer; SubLineIndex: Integer = -1); end; implementation constructor TLines.Create; begin List := TStringList.Create; IconsDef := TStringList.Create; InternalList := TStringList.Create; InternalList.Add('[Connect]'); // 0 InternalList.Add('Get URL'); InternalList.Add('[Add to bookmark]'); InternalList.Add('Loading '); InternalList.Add('Loading complete'); InternalList.Add('[%s] added to bookmark'); // 5 InternalList.Add('Choose Language'); end; // ______________________________________________________________________________ destructor TLines.Destroy; begin List.Free; InternalList.Free; IconsDef.Free; inherited; end; // ______________________________________________________________________________ function TLines.Get(Index: Integer): string; begin if Index < InternalList.Count then if Index < List.Count then Result := List[Index] else Result := InternalList[Index] else Result := ''; Result := Result.Replace('<br>', #13#10); end; // ______________________________________________________________________________ procedure TLines.Put(Index: Integer; Item: string); begin if Index < List.Count then List[Index] := Item; end; // ______________________________________________________________________________ procedure TLines.AddIconDef(Icon: string; LineIndex, SubLineIndex: Integer); var s: string; begin if (LineIndex > List.Count - 1) or (SubLineIndex > List.Count - 1) then Exit; s := '\' + List[LineIndex]; if SubLineIndex > -1 then s := s + '\' + List[SubLineIndex]; s := s + '=' + Icon; IconsDef.Add(s); end; // ______________________________________________________________________________ procedure TLines.SetIcons; begin IconsDef.Clear; AddIconDef('ZLEFT', 0, 1); end; // ______________________________________________________________________________ procedure TLines.SetLanguage(Path: string); var DefLangFile: string; begin if FileExists(Path) then List.LoadFromFile(Path) else begin List.Clear; List.AddStrings(InternalList); DefLangFile := ExtractFilePath(Path) + 'english.lng'; try List.SaveToFile(DefLangFile); DefLangFile := ExtractFilePath(Path) + 'hb_english.lng'; if not FileExists(DefLangFile) then List.SaveToFile(DefLangFile); except end; end; SetIcons; end; // ______________________________________________________________________________ function TLines.GetIcon(Path: string): string; var p: Integer; s: string; i: Integer; begin for i := 0 to IconsDef.Count - 1 do begin p := Pos('=', IconsDef[i]); s := Copy(IconsDef[i], 1, p - 1); if Path.StartsWith(s) then Exit(Copy(IconsDef[i], p + 1, Length(IconsDef[i]))); end; Result := 'MAINICON'; end; end.
unit uJSRTTIExtension; {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} Vcl.Imaging.pngimage, uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFApplication, uCEFTypes, uCEFConstants, uCEFWinControl, uCEFSentinel, uCEFChromiumCore; const MINIBROWSER_DEBUGMESSAGE = WM_APP + $100; MINIBROWSER_CONTEXTMENU_SHOWDEVTOOLS = MENU_ID_USER_FIRST + 1; type TStatusWhatsType = (Desconectado, Conectado); TfrmMain = class(TForm) StatusBar1: TStatusBar; CEFWindowParent1: TCEFWindowParent; Chromium1: TChromium; Timer1: TTimer; btnReload: TButton; mmoDebug: TMemo; imgQrCode: TImage; Button1: TButton; procedure FormShow(Sender: TObject); procedure Chromium1BeforeContextMenu(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); procedure Chromium1ContextMenuCommand(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: Cardinal; out Result: Boolean); procedure Chromium1ProcessMessageReceived(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; sourceProcess: TCefProcessId; const message: ICefProcessMessage; out Result: Boolean); procedure Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser); procedure Timer1Timer(Sender: TObject); procedure Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; const popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var extra_info: ICefDictionaryValue; var noJavascriptAccess: Boolean; var Result: Boolean); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Chromium1Close(Sender: TObject; const browser: ICefBrowser; var aAction: TCefCloseBrowserAction); procedure Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser); procedure Chromium1LoadStart(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; transitionType: Cardinal); procedure Chromium1LoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); procedure btnReloadClick(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure JSFuncoesBase; procedure LoadQrCode(const pQrCode: String); procedure JSBuscaQrCode; procedure JSConfirmaLogin; protected FStatusWhats: TStatusWhatsType; FRetorno: string; // Variables to control when can we destroy the form safely FCanClose: Boolean; // Set to True in TChromium.OnBeforeClose FClosing: Boolean; // Set to True in the CloseQuery event. FMemo: String; procedure BrowserCreatedMsg(var aMessage: TMessage); message CEF_AFTERCREATED; procedure BrowserDestroyMsg(var aMessage: TMessage); message CEF_DESTROY; procedure DebugMsg(var aMessage: TMessage); message MINIBROWSER_DEBUGMESSAGE; procedure CarregaApi; procedure WMMove(var aMessage: TWMMove); message WM_MOVE; procedure WMMoving(var aMessage: TMessage); message WM_MOVING; public property StatusWhats: TStatusWhatsType read FStatusWhats; { Public declarations } end; var frmMain: TfrmMain; procedure CreateGlobalCEFApp; implementation {$R *.dfm} uses uCEFv8Handler, uTestExtension, uCEFMiscFunctions, System.NetEncoding; procedure GlobalCEFApp_OnWebKitInitialized; begin {$IFDEF DELPHI14_UP} // Registering the extension. Read this document for more details : // https://bitbucket.org/chromiumembedded/cef/wiki/JavaScriptIntegration.md if TCefRTTIExtension.Register('myextension', TTestExtension) then {$IFDEF DEBUG}CefDebugLog('JavaScript extension registered successfully!'){$ENDIF} else {$IFDEF DEBUG}CefDebugLog('There was an error registering the JavaScript extension!'){$ENDIF}; {$ENDIF} end; procedure CreateGlobalCEFApp; begin GlobalCEFApp := TCefApplication.Create; GlobalCEFApp.OnWebKitInitialized := GlobalCEFApp_OnWebKitInitialized; {$IFDEF DEBUG} GlobalCEFApp.LogFile := 'debug.log'; GlobalCEFApp.LogSeverity := LOGSEVERITY_INFO; {$ENDIF} end; procedure TfrmMain.CarregaApi; var lScriptJS: TStringList; begin lScriptJS := TStringList.Create; try if FileExists(ExtractFilePath(ParamStr(0)) + 'js.abr') then begin // lScriptJS.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'js.abr'); lScriptJS.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'wapi_plus.js'); Chromium1.browser.MainFrame.ExecuteJavaScript(lScriptJS.Text, 'about:blank', 0); end else begin MessageDlg('Não foi possível carregar o arquivo de configuração', mtError, [mbOK], 0); end; finally lScriptJS.Free; end; end; procedure TfrmMain.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser); begin PostMessage(Handle, CEF_AFTERCREATED, 0, 0); end; procedure TfrmMain.Chromium1BeforeContextMenu(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); begin // Adding some custom context menu entries model.AddSeparator; model.AddItem(MINIBROWSER_CONTEXTMENU_SHOWDEVTOOLS, 'Show DevTools'); end; procedure TfrmMain.Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; const popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var extra_info: ICefDictionaryValue; var noJavascriptAccess: Boolean; var Result: Boolean); begin // For simplicity, this demo blocks all popup windows and new tabs Result := (targetDisposition in [WOD_NEW_FOREGROUND_TAB, WOD_NEW_BACKGROUND_TAB, WOD_NEW_POPUP, WOD_NEW_WINDOW]); end; procedure TfrmMain.Chromium1ContextMenuCommand(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: Cardinal; out Result: Boolean); const ELEMENT_ID = 'keywords'; // ID attribute in the search box at https://www.briskbard.com/forum/ var TempPoint: TPoint; TempJSCode: string; begin Result := False; case commandId of MINIBROWSER_CONTEXTMENU_SHOWDEVTOOLS: begin TempPoint.x := params.XCoord; TempPoint.y := params.YCoord; Chromium1.ShowDevTools(TempPoint, nil); end; end; end; procedure TfrmMain.JSFuncoesBase; var JS: String; begin JS := JS + 'function cmdAsync() { '; JS := JS + ' return new Promise(resolve => { '; JS := JS + ' requestAnimationFrame(resolve); '; JS := JS + ' }); '; JS := JS + '} '; JS := JS + 'function checkElement(selector) { '; JS := JS + ' if (document.querySelector(selector) === null) { '; JS := JS + ' return cmdAsync().then(() => checkElement(selector)); '; JS := JS + ' } else { '; JS := JS + ' return Promise.resolve(true); '; JS := JS + ' } '; JS := JS + '} '; Chromium1.browser.MainFrame.ExecuteJavaScript(JS, 'about:blank', 0); end; procedure TfrmMain.Chromium1LoadStart(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; transitionType: Cardinal); begin JSFuncoesBase; end; procedure TfrmMain.JSBuscaQrCode; var JS: String; begin // Observa Mutações no QrCode JS := JS + 'var contQR = 0; '; JS := JS + 'var observer = new MutationObserver(function(mutations) { '; JS := JS + ' contQR++; '; JS := JS + ' if (contQR >= 5) location.reload();'; // JS := JS + ' console.log("Atualiza QrCode"); '; JS := JS + ' var canvas = document.getElementsByTagName("canvas")[0];'; JS := JS + ' myextension.whatsfunction("getQrCode", canvas.toDataURL("image/png"));'; JS := JS + '}); '; JS := JS + 'var config = { attributes: true, childList: true, characterData: true }; '; // Verifica se o QrCode já foi criado JS := JS + 'checkElement("canvas").then((element) => { '; // JS := JS + ' console.info(element); '; JS := JS + ' var canvas = document.getElementsByTagName("canvas")[0];'; JS := JS + ' myextension.whatsfunction("getQrCode", canvas.toDataURL("image/png"));'; // JS := JS + ' console.info("Começa a Observar o Canvas"); '; JS := JS + ' var target = document.querySelector("canvas"); '; JS := JS + ' observer.observe(target.parentElement, config); '; JS := JS + '}); '; Chromium1.browser.MainFrame.ExecuteJavaScript(JS, 'about:blank', 0); end; procedure TfrmMain.JSConfirmaLogin; var JS: String; begin // Verifica se está logado JS := JS + 'var elemento = "#pane-side";'; JS := JS + 'checkElement(elemento).then((element) => { '; JS := JS + ' console.log("Logado com Sucesso."); '; JS := JS + ' myextension.whatsfunction("whatsconectado", "true");'; JS := JS + '}); '; Chromium1.browser.MainFrame.ExecuteJavaScript(JS, 'about:blank', 0); end; procedure TfrmMain.Chromium1LoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); begin JSBuscaQrCode; JSConfirmaLogin; end; procedure TfrmMain.Button1Click(Sender: TObject); var JS: String; begin // Verifica se está logado JS := JS + 'console.log(window.WAPI.getAllContacts()); '; JS := JS + 'myextension.whatsfunction("getAllContacts", window.WAPI.getAllContacts());'; Chromium1.browser.MainFrame.ExecuteJavaScript(JS, 'about:blank', 0); end; procedure TfrmMain.Chromium1ProcessMessageReceived(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; sourceProcess: TCefProcessId; const message: ICefProcessMessage; out Result: Boolean); begin Result := False; if (message = nil) or (message.ArgumentList = nil) then exit; if (message.Name = 'getQrCode') then begin FStatusWhats := Desconectado; LoadQrCode(message.ArgumentList.GetString(0)); Result := True; end; if (message.Name = 'whatsconectado') then begin if (message.ArgumentList.GetString(0) = 'true') then begin FStatusWhats := Conectado; CarregaApi; end; JSBuscaQrCode; Result := True; end; if (message.Name = 'getAllContacts') then begin FStatusWhats := Desconectado; FRetorno := message.ArgumentList.GetString(0); PostMessage(Handle, MINIBROWSER_DEBUGMESSAGE, 0, 0); Result := True; end; end; procedure TfrmMain.LoadQrCode(const pQrCode: String); var SLQrCodeBase64: TStringList; MSQrCodeBase64: TMemoryStream; MSQrCode: TMemoryStream; tmpPNG: TpngImage; PicQrCode: TPicture; begin SLQrCodeBase64 := TStringList.Create; try SLQrCodeBase64.Add(copy(pQrCode, 23, length(pQrCode))); MSQrCodeBase64 := TMemoryStream.Create; try SLQrCodeBase64.SaveToStream(MSQrCodeBase64); if MSQrCodeBase64.Size > 3000 Then // Tamanho minimo de uma imagem begin MSQrCodeBase64.Position := 0; MSQrCode := TMemoryStream.Create; try TNetEncoding.Base64.Decode(MSQrCodeBase64, MSQrCode); if MSQrCode.Size > 0 then begin MSQrCode.Position := 0; PicQrCode := TPicture.Create; try {$IFDEF VER330}PicQrCode.LoadFromStream(MSQrCode); {$ELSE} tmpPNG := TpngImage.Create; try tmpPNG.LoadFromStream(MSQrCode); PicQrCode.Graphic := tmpPNG; finally tmpPNG.Free; end; {$ENDIF} finally imgQrCode.Picture := PicQrCode; PicQrCode.Free; end; end; finally MSQrCode.Free; end; end; finally MSQrCodeBase64.Free; end; finally SLQrCodeBase64.Free; end; end; procedure TfrmMain.DebugMsg(var aMessage: TMessage); begin mmoDebug.Lines.Clear; mmoDebug.Lines.Add(FRetorno); end; procedure TfrmMain.FormShow(Sender: TObject); begin StatusBar1.Panels[0].Text := 'Initializing browser. Please wait...'; Chromium1.DefaultURL := 'https://web.whatsapp.com/'; // GlobalCEFApp.GlobalContextInitialized has to be TRUE before creating any browser // If it's not initialized yet, we use a simple timer to create the browser later. if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) then Timer1.Enabled := True; end; procedure TfrmMain.WMMove(var aMessage: TWMMove); begin inherited; if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted; end; procedure TfrmMain.WMMoving(var aMessage: TMessage); begin inherited; if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted; end; procedure TfrmMain.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) and not(Chromium1.Initialized) then Timer1.Enabled := True; end; procedure TfrmMain.BrowserCreatedMsg(var aMessage: TMessage); begin StatusBar1.Panels[0].Text := ''; CEFWindowParent1.UpdateSize; end; procedure TfrmMain.Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser); begin FCanClose := True; PostMessage(Handle, WM_CLOSE, 0, 0); end; procedure TfrmMain.Chromium1Close(Sender: TObject; const browser: ICefBrowser; var aAction: TCefCloseBrowserAction); begin PostMessage(Handle, CEF_DESTROY, 0, 0); aAction := cbaDelay; end; procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := FCanClose; if not(FClosing) then begin FClosing := True; Visible := False; Chromium1.CloseBrowser(True); end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin FCanClose := False; FClosing := False; end; procedure TfrmMain.BrowserDestroyMsg(var aMessage: TMessage); begin CEFWindowParent1.Free; end; procedure TfrmMain.btnReloadClick(Sender: TObject); begin Chromium1.Reload; end; end.
{ Module of routines that deal with C-style string issues. } module string_c; define string_t_c; define string_terminate_null; %include 'string2.ins.pas'; { ********************************************************************** * * Subroutine STRING_T_C (VSTR, CSTR, CSTR_LEN) * * Convert the var string VSTR to the C-style string CSTR. CSTR_LEN is the * maximum number of characters (including the NULL terminator) we may write * into CSTR. CSTR will always be NULL terminated. If the input string * contains more thatn CSTR_LEN-1 characters only the first LEN-1 characters * are copied and the NULL terminator is written to the last character position. } procedure string_t_c ( {convert var string to C-style NULL term str} in vstr: univ string_var_arg_t; {input var string} out cstr: univ string; {returned null terminated C string} in cstr_len: sys_int_machine_t); {max characters allowed to write into CSTR} val_param; var n: sys_int_machine_t; {number of characters to really copy} i: sys_int_machine_t; {loop counter} begin if cstr_len <= 0 then return; {nothing to do ?} n := max(0, min(vstr.len, cstr_len - 1)); {make number of chars to actually copy} for i := 1 to n do begin {copy the text characters} cstr[i] := vstr.str[i]; end; cstr[n + 1] := chr(0); {add NULL terminator to end of string} end; { ********************************************************************** * * Subroutine STRING_TERMINATE_NULL (S) * * Insure that the body of S is NULL terminated, as compatible with C-style * strings. Is S is not filled to its maximum number of characters, then the * NULL is added after the last character without the var string length being * effected. If S is at its maximum length, then the last character is replaced * by the NULL, and the var string length is decremented by one. } procedure string_terminate_null ( {insure .STR field is null-terminated} in out s: univ string_var_arg_t); {hidden NULL will be added after string body} begin if s.max <= 0 then return; {nothing we can do ?} if s.len < s.max then begin {S is not at its maximum length} s.str[s.len + 1] := chr(0); {put NULL terminator after last character} end else begin {S is already maxed out} s.str[s.max] := chr(0); {stomp on last character to become NULL} s.len := s.max - 1; {indicate number of real string chars left} end ; end;
unit UFrmConsultaContaReceber; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrmFormDataSetConsulta, Data.DB, System.Actions, Vcl.ActnList, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls,system.DateUtils, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.DBCtrls,UFrmFaturaContaReceber, PBNumEdit,System.UITypes, siComp, siLngLnk, Vcl.Mask, frxClass; type TFrmConsultaContaReceber = class(TFrmFormDataSetConsulta) edt_codcliente: TEdit; dtpInicio: TDateTimePicker; dtpFim: TDateTimePicker; cbxFiltro: TComboBox; Panel3: TPanel; lb_nome_cliente: TLabel; pTotais: TPanel; edt_saldoGS: TPBNumEdit; edtSaldo: TPBNumEdit; Panel6: TPanel; Panel8: TPanel; chkFatura: TCheckBox; pAjuda: TPanel; BitBtn5: TBitBtn; BitBtn6: TBitBtn; BitBtn7: TBitBtn; acExtrato: TAction; BtnPagare: TBitBtn; acPagare: TAction; ultima_data_pagamento: TLabel; lbValorSelecionadoText: TLabel; lbValorSelecionadoValor: TLabel; Label1: TLabel; btnConsultaCliente: TBitBtn; Label2: TLabel; Label3: TLabel; Label4: TLabel; Panel5: TPanel; edtCredito: TPBNumEdit; BitBtn8: TBitBtn; acCredito: TAction; lb_razaosocial_cliente: TLabel; siLangLinked_FrmConsultaContaReceber: TsiLangLinked; grpDividaCliente: TGroupBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; DBEdit1: TDBEdit; DBEdit2: TDBEdit; DBEdit3: TDBEdit; frxReport1: TfrxReport; procedure FormCreate(Sender: TObject); procedure acNovoExecute(Sender: TObject); procedure acAlterarExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure BitBtn6Click(Sender: TObject); procedure BitBtn5Click(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure edt_codclienteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dtpInicioKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dtpFimKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbxFiltroChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure acExtratoExecute(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure acSairExecute(Sender: TObject); procedure acPagareExecute(Sender: TObject); procedure acAtualizarExecute(Sender: TObject); procedure DBGrid1CellClick(Column: TColumn); procedure DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnConsultaClienteClick(Sender: TObject); procedure acCreditoExecute(Sender: TObject); procedure FormActivate(Sender: TObject); private FvalorField, FvalorpagoField, FvencimentoField: Tfield; FValorGS: Real; FValorRS: Real; FValorUS: Real; FFecharForm: Boolean; FCliente_Documento: string; FCliente_Nome: string; FCliente_Endereco: String; FValorGSCredito: Real; procedure ExpXLS(DataSet: TDataSet; Arq: string); { Private declarations } public { Public declarations } procedure selecionarCliente; procedure CarregaContasReceber; procedure AtualizaSaldoCliente; procedure exibirValorSelecionado; procedure SomaTotais; property ValorUS: Real read FValorUS write FValorUS; property ValorGS: Real read FValorGS write FValorGS; property ValorGSCredito: Real read FValorGSCredito write FValorGSCredito; property ValorRS: Real read FValorRS write FValorRS; property FecharForm: Boolean read FFecharForm write FFecharForm; property Cliente_nome:string read FCliente_Nome write FCliente_nome; property Cliente_documento:string read FCliente_Documento write FCliente_Documento; property Cliente_Endereco: String read FCliente_Endereco write FCliente_Endereco; end; var FrmConsultaContaReceber : TFrmConsultaContaReceber; implementation {$R *.dfm} uses uDM, UFrmCadContaReceber, UFrmPesquisaPadrao, uDMPesquisa, uDMLista, uDMRelatorio, uFrmPrincipal, uLib, uFrmFaturaContaReceberNovo, uFrmRelatorioContaReceberExtratoOpcoes, uFrmCadClienteCredito, UFrmCadCliente, uDMMKAuth,dbWeb, ComObj, XMLDoc, XMLIntf,ShlObj, ActiveX,SHFolder; procedure TFrmConsultaContaReceber.acAlterarExecute(Sender: TObject); var codigo: integer; begin inherited; try codigo := DBGrid1.DataSource.DataSet.FieldByName('id_contareceber').asInteger; dmdados.qContaReceber.Close; dmdados.qContaReceber.Macros.MacroByName('filtro').AsRaw :=' where id_contareceber = :id_contareceber'; DMDados.qContaReceber.Params.ParamByName('id_contareceber').AsInteger := codigo; dmdados.qContaReceber.open; dmdados.qContaReceber.refresh; FrmCadContaReceber := TFrmCadContaReceber.create(self); FrmCadContaReceber.modo :='alterar'; if dmDados.qContaReceber.RecordCount > 0 then begin FrmCadContaReceber.showModal; end else begin siLangLinked_FrmConsultaContaReceber.ShowMessage(siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_5' (* 'No fue posible localizar en registro! Llame el programador!' *) )); end; finally FreeAndNil(FrmCadContaReceber); end; DataSet1.Refresh; end; procedure TFrmConsultaContaReceber.acAtualizarExecute(Sender: TObject); begin inherited; if assigned(dataset1) then begin if dataset1.active then dataset1.Refresh; end; end; procedure TFrmConsultaContaReceber.acCreditoExecute(Sender: TObject); var id_cliente: integer; nome: string; begin inherited; if tryStrToInt(edt_codcliente.Text,id_cliente) then begin try FrmCadClienteCredito := TFrmCadClienteCredito.create(self); FrmCadClienteCredito.id_cliente := id_cliente; FrmCadClienteCredito.nome_cliente := lb_nome_cliente.Caption; FrmCadClienteCredito.showModal; finally FreeAndNil(FrmCadClienteCredito); end; CarregaContasReceber; end else begin siLangLinked_FrmConsultaContaReceber.showMessage(siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_6' (* 'Elija un cliente!' *) )); end; end; procedure TFrmConsultaContaReceber.acExtratoExecute(Sender: TObject); var path_relatorio,path_debug: string; data1,data2: TDateTime; filtro: string; opcaoData: Integer; dia, mes, ano, hora, minuto, segundo: String; d,m,a,hh,hm,hs,hms: word; filename: string; begin inherited; path_debug := StringReplace( ExtractFilePath(application.exename),'Win32\Debug\','Relatorios',[]); filtro := ''; try FrmRelatorioContaReceberExtratoOpcoes := TFrmRelatorioContaReceberExtratoOpcoes.create(self); FrmRelatorioContaReceberExtratoOpcoes.ShowModal; if not FrmRelatorioContaReceberExtratoOpcoes.saiu then begin opcaoData:= FrmRelatorioContaReceberExtratoOpcoes.rgopcoes.itemIndex; end else begin opcaoData := -1; end; finally FreeAndNil(FrmRelatorioContaReceberExtratoOpcoes); end; with dmrelatorio do begin qempresa.close; qempresa.open; path_relatorio := qempresa.fieldbyname('path_relatorio').asString; data1 := dtpInicio.DateTime; data2 := dtpFim.dateTime; ReplaceTime(data1,EncodeTime(0,0,0,0)); ReplaceTime(data2,EncodeTime(23,59,59,999)); qClienteExtrato.Close; if opcaoData = 0 then begin case cbxFiltro.ItemIndex of 0: filtro := ' where A.id_cliente = :id_cliente and A.data_vencimento between :data1 and :data2 '; 1: filtro := ' where A.id_cliente = :id_cliente and A.data_vencimento between :data1 and :data2 and A.valor - coalesce(A.valor_pago,0) > 0 '; 2: filtro :=' where A.id_cliente = :id_cliente and A.data_vencimento between :data1 and :data2 and A.data_pagamento is not null '; end; qClienteExtrato.Macros.MacroByName('ordenacao').AsRaw :=' order by A.data_vencimento '; end else if opcaoData = 1 then begin case cbxFiltro.ItemIndex of 0: filtro :=' where A.id_cliente = :id_cliente and A.data_lancamento between :data1 and :data2 '; 1: filtro :=' where A.id_cliente = :id_cliente and A.data_lancamento between :data1 and :data2 and A.valor - coalesce(A.valor_pago,0) > 0 '; 2: filtro :=' where A.id_cliente = :id_cliente and A.data_lancamento between :data1 and :data2 and A.data_pagamento is not null '; end; qClienteExtrato.Macros.MacroByName('ordenacao').AsRaw :=' order by A.data_lancamento '; end else if opcaoData = 2 then begin case cbxFiltro.ItemIndex of 0: filtro :=' where A.id_cliente = :id_cliente and A.data_pagamento between :data1 and :data2 '; 1: filtro :=' where A.id_cliente = :id_cliente and A.data_pagamento between :data1 and :data2 and A.valor - coalesce(A.valor_pago,0) > 0 '; 2: filtro :=' where A.id_cliente = :id_cliente and A.data_pagamento between :data1 and :data2 and A.data_pagamento is not null '; end; qClienteExtrato.Macros.MacroByName('ordenacao').AsRaw :=' order by A.data_lancamento '; end else begin case cbxFiltro.ItemIndex of 0: filtro :=' where A.id_cliente = :id_cliente and A.data_vencimento between :data1 and :data2 '; 1: filtro :=' where A.id_cliente = :id_cliente and A.data_vencimento between :data1 and :data2 and A.valor - coalesce(A.valor_pago,0) > 0 '; 2: filtro :=' where A.id_cliente = :id_cliente and A.data_vencimento between :data1 and :data2 and A.data_pagamento is not null '; end; qClienteExtrato.Macros.MacroByName('ordenacao').AsRaw :=' order by A.data_vencimento '; end; qClienteExtrato.Macros.MacroByName('filtro').AsRaw := filtro; qClienteExtrato.params.ParamByName('id_cliente').AsInteger := StrToInt(edt_codcliente.Text); qClienteExtrato.Params.ParamByName('data1').AsDateTime := data1; qClienteExtrato.Params.ParamByName('data2').AsDateTime := data2; qClienteExtrato.open; qClienteExtratoSaldoAnterior.Close; if opcaoData = 0 then begin qClienteExtratoSaldoAnterior.macros.MacroByName('filtro').AsRaw :=' where id_cliente = :id_cliente and data_vencimento < :data'; end else if opcaoData = 1 then begin qClienteExtratoSaldoAnterior.macros.MacroByName('filtro').AsRaw :=' where id_cliente = :id_cliente and data_lancamento < :data'; end else begin qClienteExtratoSaldoAnterior.macros.MacroByName('filtro').AsRaw :=' where id_cliente = :id_cliente and data_vencimento < :data'; end; qClienteExtratoSaldoAnterior.params.ParamByName('id_cliente').AsInteger := StrToInt(edt_codcliente.Text); qClienteExtratoSaldoAnterior.Params.ParamByName('data').AsDate := data1; qClienteExtratoSaldoAnterior.open; DecodeDateTime(now,a,m,d,hh,hm,hs,hms); dia := formatFloat('00',d); mes := formatFloat('00',m); ano := formatFloat('0000',a); hora := formatFloat('00',hh); minuto := formatFloat('00',hm); segundo := formatFloat('00',hs); filename := 'arquivos\relatorio-'+ano+mes+dia+'-'+hora+minuto+segundo+'.xlsx'; //ExpXLS(qClienteExtrato, filename); qClienteExtrato.open; ExpXLS(qClienteExtrato, filename); qClienteExtrato.Refresh; qClienteExtratoDetalhe.Close; qClienteExtratoDetalhe.open; qClienteExtratoDetalhe.Refresh; if opcaoData = 1 then Begin {$IFDEF DEBUG} frxReport.LoadFromFile(path_debug+'\cliente_extrato_lancamento.fr3'); {$ELSE} frxReport.LoadFromFile(path_relatorio+'\cliente_extrato_lancamento.fr3'); {$ENDIF} end else begin {$IFDEF DEBUG} frxReport.LoadFromFile(path_debug+'\cliente_extrato.fr3'); {$ELSE} frxReport.LoadFromFile(path_relatorio+'\cliente_extrato.fr3'); {$ENDIF} end; fnSetLogoReport(frxReport,qempresa); fnSetCabecalho(frxReport,qempresa,siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_46' (* 'ESTADO DE CUENTA' *) )); frxReport.Variables.Variables['PDATA1'] := #39+DateTimeToStr(data1)+#39; frxReport.Variables.Variables['PDATA2'] := #39+DateTimeToStr(data2)+#39; frxReport.Variables.Variables['CLIENTE'] := #39+lb_nome_cliente.Caption+#39; {$IFDEF DEBUG} frxReport.DesignReport(true); {$ENDIF} frxReport.ShowReport(true); qempresa.close; qClienteExtrato.close; end; end; procedure TFrmConsultaContaReceber.acNovoExecute(Sender: TObject); begin inherited; try FrmCadContaReceber := TFrmCadContaReceber.create(self); FrmCadContaReceber.modo := 'cadastrar'; FrmCadContaReceber.showModal; finally FreeAndNil(FrmCadContaReceber); end; end; procedure TFrmConsultaContaReceber.acPagareExecute(Sender: TObject); var path_relatorio,path_debug: string; moeda: string; d,m,y: Word; empresa: string; cidade, pagare_cidade: string; begin inherited; DMRelatorio.qEmpresa.Close; DMRelatorio.qEmpresa.Open(); path_relatorio := dmRelatorio.qEmpresa.fieldbyname('path_relatorio').asString; path_debug := StringReplace( ExtractFilePath(application.exename),'Win32\Debug\','Relatorios',[]); with DmRelatorio do begin {$IFDEF DEBUG} frxReport.LoadFromFile(path_debug+'\cliente_pagare.fr3'); {$ELSE} frxReport.LoadFromFile(path_relatorio+'\cliente_pagare.fr3'); {$ENDIF} empresa := qEmpresa.FieldByName('razaosocial').AsString; cidade := qEmpresa.FieldByName('cidade').AsString; pagare_cidade := qEmpresa.FieldByName('pagare_cidade').AsString; qGenerica.close; qGenerica.sql.clear; qGenerica.sql.add(' select (datename(day,:vencimento)+'+quotedstr(' de ')+'+ datename(month,:vencimento)+'+quotedstr(' de ')+'+datename(year,:vencimento)) as Vencimento, dbo.extenso(:valor,:moeda,:moedaplural,:decimal) as Extenso,datename(day,:vencimento) as Dia, datename(month,:vencimento) as Mes, datename(year,:vencimento) as Ano,datename(month,:data) as MesEmissao '); qGenerica.Params.ParamByName('vencimento').AsDateTime := DBGrid1.DataSource.DataSet.FieldByName('vencimento').asDateTime; qGenerica.Params.ParamByName('data').AsDateTime := fngetDataHora; qGenerica.Params.ParamByName('valor').AsFloat := DBGrid1.DataSource.DataSet.FieldByName('valor').asFloat; qGenerica.Params.ParamByName('moeda').AsString := 'GUARANI'; qGenerica.Params.ParamByName('moedaplural').AsString := 'GUARANIES'; qGenerica.Params.ParamByName('decimal').AsInteger := 0; qGenerica.Open(); DecodeDate(fnGetDataHora,y,m,d); frxReport.Variables.Variables['CLIENTE'] := #39+Cliente_nome+#39; frxReport.Variables.Variables['CLIENTE_DOCUMENTO'] := #39+Cliente_documento+#39; FrxReport.Variables.Variables['CLIENTE_ENDERECO'] := #39+Cliente_endereco+#39; frxReport.Variables.Variables['DOCUMENTO'] := #39+DBGrid1.DataSource.DataSet.FieldByName('documento').asString+#39; FrxReport.Variables.Variables['VENCIMENTO'] := #39+qGenerica.FieldByName('vencimento').AsString+#39; FrxReport.Variables.Variables['VENCIMENTO_DIA'] := #39+qGenerica.FieldByName('dia').AsString+#39; FrxReport.Variables.Variables['VENCIMENTO_MES'] := #39+qGenerica.FieldByName('mes').AsString+#39; FrxReport.Variables.Variables['VENCIMENTO_ANO'] := #39+qGenerica.FieldByName('ano').AsString+#39; FrxReport.Variables.Variables['VALOR_EXTENSO'] := #39+qGenerica.FieldByName('extenso').AsString+#39; FrxReport.Variables.Variables['EMPRESA'] := #39+EMPRESA+#39; FrxReport.Variables.Variables['EMPRESA_CIDADE'] := #39+CIDADE+#39; FrxReport.Variables.Variables['PAGARE_CIDADE'] := #39+pagare_CIDADE+#39; FrxReport.Variables.Variables['DATA_DIA'] := #39+intToStr(d)+#39; FrxReport.Variables.Variables['DATA_MES'] := #39+qGenerica.FieldByName('MesEmissao').AsString+#39; FrxReport.Variables.Variables['DATA_ANO'] := #39+intToStr(y)+#39; frxReport.Variables.Variables['PAGARE_NRO'] := #39+DbGrid1.DataSource.DataSet.FieldByName('documento').AsString+#39; frxReport.Variables.Variables['NOTAFISCAL'] := #39+DbGrid1.DataSource.DataSet.FieldByName('fatura').AsString+#39; moeda := DBGrid1.DataSource.DataSet.FieldByName('moeda').asString; if moeda ='G$' then begin frxReport.Variables.Variables['VALOR'] := #39+FormatFloat(fngetMoedaMascara,DBGrid1.DataSource.DataSet.FieldByName('valor').asFloat-DBGrid1.DataSource.DataSet.FieldByName('valorPago').asFloat)+#39; end else begin frxReport.Variables.Variables['VALOR'] := #39+FormatFloat(fngetMoedaMascara,DBGrid1.DataSource.DataSet.FieldByName('valor').asFloat-DBGrid1.DataSource.DataSet.FieldByName('valorPago').asFloat)+#39; end; frxReport.Variables.Variables[ 'VALOR_MOEDA'] := #39+moeda+#39; {$IFDEF DEBUG} frxReport.DesignReport(true); {$ENDIF} frxReport.ShowReport(true); end; end; procedure TFrmConsultaContaReceber.acSairExecute(Sender: TObject); begin FFecharForm := true; inherited; end; procedure TFrmConsultaContaReceber.AtualizaSaldoCliente; var id_cliente: Integer; sql: ansiString; // DMDadosPesquisa.qClientePesquisa.Refresh; //if not fnConfigEmpresa('multimoeda') then //begin // if fnGetMoedaPadrao = 'G$' then // begin // if TryStrToInt(edt_codcliente.Text,id_cliente) then // begin // lb_saldo_cliente_gs.Caption := formatFloat(fngetMoedaMascara,fngetClienteSaldo( id_cliente )); // end; // end // else // begin // if TryStrToInt(edt_codcliente.Text,id_cliente) then // begin // lb_saldo_cliente_gs.Caption := formatFloat(fngetMoedaMascara,fngetClienteSaldo( id_cliente )); // end; // // end; // DBEdit1.Text := formatFloat(fngetMoedaMascara,dmdadospesquisa.qClientePesquisa.FieldByName('SaldoUS').AsFloat); // DBEdit2.Text := formatFloat(fngetMoedaMascara,dmdadospesquisa.qClientePesquisa.FieldByName('SaldoGS').AsFloat); // DBEdit3.Text := formatFloat(fngetMoedaMascara,dmdadospesquisa.qClientePesquisa.FieldByName('SaldoRS').AsFloat); // grpDividaCliente.Visible := true; begin with DMDadosLista do begin sql := 'select A.id_cliente, A.nome,A.pppoe, A.limitecredito, coalesce(A.tipoCliente,0) as TipoCliente, '; sql := sql + ' sum(iif(sigla ='+quotedstr('U$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoUS, '; sql := sql + ' sum(iif(sigla ='+quotedstr('G$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoGS, '; sql := sql + ' sum(iif(sigla ='+quotedstr('R$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoRS, '; // sql := sql + ' sum(iif(sigla ='+quotedstr('P$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoPS, '; // sql := sql + ' sum(iif(sigla ='+quotedstr('E$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoES, '; sql := sql + ' concat(A.documento1,'+quotedstr(' - ')+',A.documento2) as documento,A.endereco,A.razaosocial,A.documento1, A.documento2,A.datacad, A.telefone,A.celular, D.nome as Cidade,D.id_cidade,A.id_vendedor, US.nome as Vendedor ,'; sql := sql + ' A.registrodistribuidor, A.registrovencimento ' ; sql := sql + ' from cliente A '; sql := sql + ' left join conta_receber B on (A.id_cliente = B.id_cliente)'; sql := sql + ' left join moeda C on (B.id_moeda = C.id_moeda)'; sql := sql + ' left join cidade D on (A.id_cidade = D.id_cidade) '; sql := sql + ' left join usuario US on (A.id_vendedor = US.id_usuario)'; sql := sql + ' !filtro '; sql := sql + ' group by A.tipoCliente, A.id_cliente,A.id_vendedor,US.nome, A.nome,A.pppoe, A.limitecredito,A.documento1,A.documento2,A.endereco,A.razaosocial,A.datacad,A.telefone,A.celular,D.nome,D.id_cidade, A.registrodistribuidor, A.registrovencimento'; qGenerica.Close; qGenerica.SQL.Clear; qGenerica.SQL.Add(sql); qGenerica.Macros.MacroByName('filtro').AsRaw := ' where A.id_cliente = :id_cliente ' ; qGenerica.Params.ParamByName('id_cliente').AsInteger := strToInt(edt_codcliente.Text); qGenerica.open; DBEdit1.Text := formatFloat(fngetMoedaMascara,qgenerica.fieldbyname('SaldoUS').AsFloat); DBEdit2.Text := formatFloat(fngetMoedaMascara,qgenerica.fieldbyname('SaldoGS').AsFloat); DBEdit3.Text := formatFloat(fngetMoedaMascara,qgenerica.fieldbyname('SaldoRS').AsFloat); lb_nome_cliente.Caption := qgenerica.fieldbyname('nome').AsString; lb_razaosocial_cliente.Caption := qgenerica.fieldbyname('razaosocial').AsString; grpDividacliente.Visible := true; CarregaContasReceber; end; end; procedure TFrmConsultaContaReceber.BitBtn5Click(Sender: TObject); var path: string; path_relatorio: string; path_debug : string; vListaContas : TStringList; BookMarkList : TBookmarkList; i: integer; contas: string; sql: string; bValorCheio: boolean; begin inherited; if dataset2.FieldByName('tipo_empresa').AsInteger = 2 then begin path := dataset2.fieldbyname('path').asString; path_relatorio := dataset2.fieldbyname('path_relatorio').asString; path_debug := StringReplace( ExtractFilePath(application.exename),'Win32\Debug\','Relatorios',[]); bValorCheio := false; vListaContas := TStringList.Create; BookMarkList := DBGrid1.SelectedRows; for i := 0 to BookMarkList.count - 1 do begin dbgrid1.DataSource.DataSet.Bookmark := bookMarkList[i]; vListaContas.add(dbgrid1.DataSource.dataset.fieldbyname('id_contareceber').asString); end; if vListaContas.Count > 0 then begin contas := '('; for I := 0 to vListaContas.count -1 do begin contas := contas + vListaContas.Strings[i]; if (i < vListaContas.count -1) then contas := contas + ','; end; contas := contas + ')'; with DMRelatorio do begin if vListaContas.Count = 1 then begin if (dbgrid1.DataSource.dataset.fieldbyname('ValorPago').asFloat > 0) then begin if MessageDlg(siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_118' (* 'Desea emitir recibo Parcial?' *) ),mtConfirmation,mbYesNo,0) = mrYes then begin bValorCheio := false; end else begin bValorCheio := true; end; end; end; qrecibo.close; qRecibo.Macros.MacroByName('selecionados').AsRaw :=' where A.id_contareceber in ' + contas + ' order by B.nome '; {$IFDEF DEBUG} frxReport.LoadFromFile(path_debug+'\recibo.fr3'); {$ELSE} frxReport.LoadFromFile(path_relatorio+'\recibo.fr3'); {$ENDIF} frxReport.Variables.Variables['EMPRESA_NOME'] := #39+dataset2.fieldbyname('rel_nome').asString+#39; frxReport.Variables.Variables['EMPRESA_ENDERECO'] := #39+dataset2.fieldbyname('rel_endereco').asString+#39; frxReport.Variables.Variables['EMPRESA_HOMEPAGE'] := #39+dataset2.fieldbyname('rel_homepage').asString+#39; frxReport.Variables.Variables['EMPRESA_TELEFONE'] := #39+dataset2.fieldbyname('rel_telefone').asString+#39; frxReport.Variables.Variables['TOTAL'] := #39+BoolToStr(bValorCheio)+#39; {$IFDEF DEBUG} frxReport.DesignReport(true); {$ENDIF} frxReport.ShowReport(true); qRecibo.Close; qRecibo.Close; end; end; end else begin //IMPRESSAO DE RECIBO NORMAL PARA CONTAS PAGAS end; end; procedure TFrmConsultaContaReceber.BitBtn6Click(Sender: TObject); var i: integer; BookMarkList: TBookMarkList; vListaContas: TStringList; ValorPago : Boolean; TotalACobrar: Real; moeda : String; begin inherited; try totalACobrar := 0; moeda := ''; // cria lista de compras vListaContas := TStringList.Create; //pega todas as linhas selecionadas BookMarkList := DBGrid1.SelectedRows; //flag para verificar se o valor pago eh falso valorPago := false; if BookMarkList.count = 0 then begin //SE NAO TEM ITEMS, ABRE PARA SELECIONAR VÁRIAS CONTAS DE VÁRIOS CLIENTES //DE UMA VEZ SÓ try FrmFaturaContaReceber := TFrmFaturaContaReceber.create(self); FrmFaturaContaReceber.Modo :='leitor'; FrmFaturaContaReceber.MoedaPadrao := FrmPrincipal.MoedaPadrao; FrmFaturaContaReceber.DS1_index:= 'cliente_recibo'; FrmFaturaContaReceber.showModal; finally FreeAndNil(FrmFaturaContaReceber); end; end else begin //Verificar se tem VALOR PAGO, e se o valor pago é o total //se nao for o total permitir que seja feito novamente a operacao //conforme estiver verificando, somar o valor por moeda for i := 0 to BookMarkList.count - 1 do begin dbgrid1.DataSource.DataSet.Bookmark := bookMarkList[i]; vListaContas.add(dbgrid1.DataSource.dataset.fieldbyname('id_contareceber').asString); if dbgrid1.DataSource.dataset.fieldbyname('Valor').asFloat = dbgrid1.DataSource.dataset.fieldbyname('ValorPago').asFloat then valorPago := true; totalACobrar := totalACobrar + (dbgrid1.DataSource.dataset.fieldbyname('Valor').asFloat - dbgrid1.DataSource.dataset.fieldbyname('ValorPago').asFloat); if moeda = '' then moeda := dbGrid1.datasource.dataset.fieldbyname('moeda').asString; end; if not valorPago then begin if vListaContas.Count > 0 then begin if not fnConfigEmpresa('conta_receber_opfixa') then begin try FrmFaturaContaReceber := TFrmFaturaContaReceber.create(self); FrmFaturaContaReceber.ListaContas := vListaContas; FrmFaturaContaReceber.MoedaPadrao := FrmPrincipal.MoedaPadrao; FrmFaturaContaReceber.DS1_index:='cliente_recibo'; FrmFaturaContaReceber.showModal; dataset1.refresh; finally FreeAndNil(FrmFaturaContaReceber); end; end else begin try FrmFaturaContaReceberNovo := TFrmFaturaContaReceberNovo.create(self); frmFaturaContaReceberNovo.TotalACobrar := TotalACobrar; frmFaturaContaReceberNovo.ListaContas := vListaContas; FrmFaturaContaReceberNovo.MoedaOperacao := moeda; FrmFaturaContaReceberNovo.Cliente := DBGrid1.DataSource.DataSet.FieldByName('id_cliente').AsInteger; FrmFaturaContaReceberNovo.ClienteNome := DBGrid1.DataSource.DataSet.FieldByName('Cliente').asString; FrmFaturaContaReceberNovo.showModal; dataset1.refresh; finally FreeAndNil(FrmFaturaContaReceberNovo); end; end; end end else begin siLangLinked_FrmConsultaContaReceber.showMessage(siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_145' (* 'No se le permite recibir facturas anteriormente abonadas!' *) )); end; end; AtualizaSaldoCliente; except on E:Exception do begin siLangLinked_FrmConsultaContaReceber.ShowMessage(E.Message + ' - '+ E.ClassName); end; end; end; procedure TFrmConsultaContaReceber.btnConsultaClienteClick(Sender: TObject); begin inherited; selecionarCliente; end; procedure TFrmConsultaContaReceber.CarregaContasReceber; var id_cliente: integer; begin id_cliente := 0; Dataset1.Close; //significa que tem cliente, entao selecionar as contas apenas desse cliente if edt_codcliente.text <> '' then begin Dataset1.Macros.MacroByName('filtro1').AsRaw :=' and A.id_cliente = :id_cliente '; DataSet1.Params.ParamByName('id_cliente').AsInteger := strToInt(edt_codcliente.Text); end else begin Dataset1.Macros.MacroByName('filtro1').AsRaw := ''; end; DataSet1.Params.ParamByName('data1').AsDate := dtpInicio.Date; Dataset1.params.parambyname('data2').AsDate := dtpFim.Date; case cbxFiltro.ItemIndex of 1: dataset1.Macros.MacroByName('filtro2').AsRaw :=' and A.valor - ( coalesce(A.valor_pago,0) - coalesce(A.desconto,0)) > 0 '; 2: dataset1.Macros.MacroByName('filtro2').AsRaw :=' and coalesce(valor_pago,0) > 0'; else dataset1.Macros.MacroByName('filtro2').AsRaw := ''; end; //ativar somente quando é tipo provedor //e ativar somente quando o campo edt_codigocliente estiver vazio if edt_codcliente.Text = '' then begin if DataSet2.FieldByName('tipo_empresa').AsInteger = 2 then begin if chkFatura.Checked then begin dataset1.Macros.MacroByName('filtro2').AsRaw := dataset1.Macros.MacroByName('filtro2').AsRaw +' and B.fatura = 1 '; end else begin dataset1.Macros.MacroByName('filtro2').AsRaw := dataset1.Macros.MacroByName('filtro2').AsRaw + ' and coalesce(B.fatura,0) = 0 '; end; // if dbLookupCidade.Visible then // begin // // if dbLookupCidade.KeyValue <> null then // begin // // dataset1.Macros.MacroByName('filtro3').AsRaw :=' and id_cidade = :id_cidade'; // dataset1.Params.ParamByName('id_cidade').AsInteger := dbLookupCidade.KeyValue; // // // // end; // // // end; end; end; Dataset1.open; fvalorField := Dataset1.fieldbyname('Valor'); fValorPagoField := dataset1.FieldByname('Valorpago'); fVencimentoField := dataset1.fieldbyname('Vencimento'); somaTotais; if pTotais.Visible then begin //edt_saldoUS.AsCurrency := ValorUS; edt_saldoGS.AsCurrency := ValorGS; //edt_saldoRS.AsCurrency := ValorRS; end; //AtualizaSaldoCliente; end; procedure TFrmConsultaContaReceber.cbxFiltroChange(Sender: TObject); begin inherited; CarregaContasReceber; end; procedure TFrmConsultaContaReceber.DBGrid1CellClick(Column: TColumn); begin inherited; exibirValorSelecionado; end; procedure TFrmConsultaContaReceber.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var Valor, ValorPago: Double; Vencimento: TDateTime; begin inherited; {$IFDEF NOT DEBUG} { Valor := FValorField.asFloat; ValorPago := FValorPagoField.asFloat; Vencimento := FVencimentoField.asDateTime; if ValorPago > 0 then begin if (ValorPago = Valor) then begin DBGrid1.Canvas.Brush.Color := clMoneyGreen; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawDataCell(rect,Column.Field,state); end else if (ValorPago < Valor) then begin DBGrid1.Canvas.Brush.Color := clYellow; if Vencimento <= fnGetDataSistema then DBGrid1.Canvas.Font.Color := clRed; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawDataCell(rect,Column.Field,state); end; end else begin if Vencimento <= fnGetDataSistema then begin DBGrid1.Canvas.Font.Color := clRed; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawDataCell(rect,Column.Field,state); end; end;} {$ENDIF} if Column.Field.FieldName = 'Saldo' then begin if Column.Field.AsFloat > 0 then begin DBGrid1.Canvas.Font.Color := clRed; DBGrid1.Canvas.Font.Style := [fsbold]; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end else if Column.Field.AsFloat = 0 then begin DBGrid1.Canvas.Font.Color:= clGreen; DBGrid1.Canvas.Font.Style := [fsbold]; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end; // if Column.Field.FieldName = 'historico' then // begin // DBGrid1.Canvas.Font.Style := [fsbold]; // DBGrid1.Canvas.FillRect(Rect); // DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); // end; if Column.Field.FieldName ='ValorFormatado' then begin DBGrid1.Canvas.Font.Color := clRed; DBGrid1.Canvas.Font.Style := [fsbold]; DBGrid1.Canvas.FillRect(Rect); DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; //SE EU COLOCO ISSO AQUI ELE DESTACA ESTE CAMPO (INTESSANTE, PARA PENSAR NO FUTURO) // if Column.Field.FieldName = 'Vencimento' then // begin // DBGrid1.Canvas.Font.Style := [fsbold]; // DBGrid1.Canvas.FillRect(Rect); // DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); // end; end; procedure TFrmConsultaContaReceber.DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_DOWN then begin //exibirValorSelecionado; //SomaTotais; end; if Key = vk_up then begin //exibirValorSelecionado; //SomaTotais; end; end; procedure TFrmConsultaContaReceber.dtpFimKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = VK_RETURN then begin CarregaContasReceber; end; end; procedure TFrmConsultaContaReceber.dtpInicioKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = VK_RETURN then begin CarregaContasReceber; end; end; procedure TFrmConsultaContaReceber.edt_codclienteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = VK_RETURN then begin if edt_codcliente.text = '' then begin selecionarCliente; end else begin AtualizaSaldoCliente; end; end; end; procedure TFrmConsultaContaReceber.exibirValorSelecionado; var Selecionado: TBookmark; i: integer; valor_selecionado: Real; begin valor_selecionado := 0; for i := 1 to DBGrid1.SelectedRows.Count do begin //DMDadosLista.qListaContaReceber.GotoBookmark(Pointer(DBGrid1.SelectedRows.Items[i-1])); valor_selecionado := valor_selecionado + dmdadosLista.qListaContaReceber.FieldByName('saldo').AsFloat; end; lbValorSelecionadoText.Visible := true; lbValorSelecionadoValor.Visible := true; lbValorSelecionadoValor.Caption := FormatFloat(fngetMoedaMascara,valor_selecionado ); end; procedure TFrmConsultaContaReceber.FormActivate(Sender: TObject); begin inherited; siLangLinked_FrmConsultaContaReceber.Language := DMDados.siLang_DMDados.Language; end; procedure TFrmConsultaContaReceber.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin inherited; CanClose := FFecharForm; end; procedure TFrmConsultaContaReceber.FormCreate(Sender: TObject); begin inherited; DataSet1 := DMDadosLista.qListaContaReceber; Dataset2 := DMDadosLista.qListaEmpresa; ValorUS := 0; ValorGS := 0; ValorRS := 0; ValorGSCredito := 0; FFecharForm := false; end; procedure TFrmConsultaContaReceber.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var msg: string; begin inherited; if Key = VK_F1 then begin edt_codcliente.SetFocus; end else if Key = VK_F2 then begin if (pTotais.Visible) and (pTotais.Width = 150) then begin //edt_saldoUS.AsCurrency := 0; edt_saldoGS.AsCurrency := 0; //edt_saldoRS.AsCurrency := 0; pTotais.Width := 1; pTotais.Color := clBlack; edt_codcliente.SetFocus; end else begin pTotais.Width := 150; pTotais.Color := clMoneyGreen; //edt_saldoUS.AsCurrency := ValorUS; edt_saldoGS.AsCurrency := ValorGS; //edt_saldoRS.AsCurrency := ValorRS; edt_codcliente.SetFocus; end; end else if key = VK_escape then begin if edt_codcliente.Text <> '' then begin msg := siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_174' (* 'Desea realmente salir del cuentas a recibir ?' *) ); if MessageDlg(msg,mtConfirmation,mbYesNo,0) = mrYes then begin FFecharForm := true; end else begin FFecharForm := false; close; end; end else begin FFecharForm := true; close; end; end; end; procedure TFrmConsultaContaReceber.FormShow(Sender: TObject); begin inherited; cbxFiltro.itemIndex := 1; if Assigned(Dataset2) then begin Dataset2.open; if dataset2.FieldByName('tipo_empresa').AsInteger = 2 then begin dtpInicio.DateTime := incday(Dataset2.fieldbyname('dt_inicio').AsDateTime,-365); dtpFim.datetime := incday(fnGetDataSistema,15); end else begin dtpInicio.DateTime := Dataset2.fieldbyname('dt_inicio').AsDateTime; dtpFim.datetime := incday(fnGetDataSistema,730); end; end; edt_codcliente.setfocus; lb_nome_cliente.Caption := ''; lb_razaosocial_cliente.Caption := ''; if fnGetMoedaPadrao = 'G$' then begin edt_saldoGS.Decimals := 0; edtCredito.decimals := 0; edtSaldo.Decimals := 0; end else begin edt_saldoGS.Decimals := 2; edtCredito.decimals := 2; edtSaldo.Decimals := 2; end; // if dbLookupCidade.Visible then // begin // // with dmdadoslista do // begin // // qListaCidade.Close; // qListaCidade.Open(); // // // end; // end; grpDividaCliente.Visible := false; end; procedure TFrmConsultaContaReceber.selecionarCliente; VAR vListaCampos: TStringList; sql: ansiString; begin sql := 'select A.id_cliente, A.nome,A.pppoe, A.limitecredito,coalesce(A.tipoCliente,0) as TipoCliente, '; sql := sql + ' sum(iif(sigla ='+quotedstr('U$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoUS, '; sql := sql + ' sum(iif(sigla ='+quotedstr('G$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoGS, '; sql := sql + ' sum(iif(sigla ='+quotedstr('R$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoRS, '; // sql := sql + ' sum(iif(sigla ='+quotedstr('P$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoPS, '; // sql := sql + ' sum(iif(sigla ='+quotedstr('E$')+',valor-(coalesce(valor_pago,0)+coalesce(desconto,0)) ,0)) as SaldoES, '; sql := sql + ' concat(A.documento1,'+quotedstr(' - ')+',A.documento2) as documento,A.endereco,A.razaosocial,A.documento1, A.documento2,A.datacad, A.telefone,A.celular, D.nome as Cidade,D.id_cidade,A.id_vendedor, US.nome as Vendedor ,'; sql := sql + ' A.registrodistribuidor, A.registrovencimento ' ; sql := sql + ' from cliente A '; sql := sql + ' left join conta_receber B on (A.id_cliente = B.id_cliente)'; sql := sql + ' left join moeda C on (B.id_moeda = C.id_moeda)'; sql := sql + ' left join cidade D on (A.id_cidade = D.id_cidade) '; sql := sql + ' left join usuario US on (A.id_vendedor = US.id_usuario)'; sql := sql + ' !filtro '; sql := sql + ' group by A.tipoCliente,A.id_cliente,A.id_vendedor,US.nome, A.nome,A.pppoe, A.limitecredito,A.documento1,A.documento2,A.endereco,A.razaosocial,A.datacad,A.telefone,A.celular,D.nome,D.id_cidade, A.registrodistribuidor, A.registrovencimento'; vListaCampos := TStringList.create; vListaCampos.add('id_cliente'); vListaCampos.add('nome'); vListaCampos.add('documento'); vListaCampos.add('endereco'); vListaCampos.add('SaldoUS'); vListaCampos.add('SaldoGS'); vListaCampos.add('SaldoRS'); frmPesquisaPadrao := TfrmPesquisaPadrao.create(self); frmPesquisaPadrao.Caption := siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_204' (* ':: Pesquisar: CLIENTE ::' *) ); frmPesquisaPadrao.DataSource := DMDadosPesquisa.dsClientePesquisa; FrmPesquisaPadrao.Tabela := DMDadosPesquisa.qClientePesquisa; FrmPesquisaPadrao.TabelaNome := 'cliente'; FrmPesquisaPadrao.CampoPesquisa := 'nome'; FrmPesquisaPadrao.CampoRetorno := 'id_cliente'; FrmPesquisaPadrao.Operador := 'like'; FrmPesquisaPadrao.SQL := sql; FrmPesquisaPadrao.CampoExibir := vListaCampos; frmPesquisaPadrao.showModal; if FrmPesquisaPadrao.retorno <> '' then begin DMDadosPesquisa.qClientePesquisa.IndexFieldNames := FrmPesquisaPadrao.CampoRetorno; DMDadosPesquisa.qClientePesquisa.FindKey([FrmPesquisaPadrao.Retorno]); edt_codcliente.text := DMDadosPesquisa.qClientePesquisa.FieldByName(FrmPesquisaPadrao.campoRetorno).asString; lb_nome_cliente.Caption := DMDadosPesquisa.qClientePesquisa.FieldByName('nome').asString; lb_razaosocial_cliente.Caption := DMDadosPesquisa.qClientePesquisa.FieldByName('razaosocial').asString; //apos pesquisar o cliente, identificar se por acaso ele esta bloqueado no mkauth if DataSet2.FieldByName('tipo_empresa').AsInteger = 2 then begin TThread.Queue(nil, procedure begin DMDadosMKAUTH.mysql.Connected := false; DMDadosMKAUTH.mysql.Connected := true; DMDadosMkAuth.qGenerica.Close; DMDadosMkAuth.qGenerica.SQL.Clear; DMDadosMkAuth.qGenerica.SQL.Add('select bloqueado from sis_cliente where login = :login and bloqueado = '+quotedstr('sim')); DMDadosMkAuth.qGenerica.Params.ParamByName('login').AsString := DMDadosPesquisa.qClientePesquisa.FieldByName('pppoe').asString; DMDadosMKAuth.qGenerica.Open(); if DMDadosMkAuth.qGenerica.RecordCount > 0 then begin lb_nome_cliente.Font.Color := clRed; lb_nome_cliente.Caption :='BLOQUEADO - ' +lb_nome_cliente.Caption; panel3.Color := clYellow;; end else begin lb_nome_cliente.Font.Color := clWhite; panel3.Color := clTeal; end; DMDadosMkAuth.qGenerica.Close; end ); end; if DataSet2.FieldByName('tipo_empresa').AsInteger = 2 then begin TThread.Queue(nil, procedure begin DMDadosMKAUTH.mysql.Connected := false; DMDadosMKAUTH.mysql.Connected := true; DMDadosMkAuth.qGenerica.Close; DMDadosMkAuth.qGenerica.SQL.Clear; DMDadosMkAuth.qGenerica.SQL.Add('select plano from sis_cliente where login = :login and bloqueado = '+quotedstr('sim')); DMDadosMkAuth.qGenerica.Params.ParamByName('login').AsString := DMDadosPesquisa.qClientePesquisa.FieldByName('pppoe').asString; DMDadosMKAuth.qGenerica.Open(); if DMDadosMkAuth.qGenerica.RecordCount > 0 then begin lb_razaosocial_cliente.Caption := DMDadosMkAuth.qGenerica.FieldByName('plano').AsString; end else begin lb_razaosocial_cliente.Caption := ''; end; DMDadosMkAuth.qGenerica.Close; end ); end; cliente_nome := DMDadosPesquisa.qClientePesquisa.FieldByName('nome').asString; cliente_documento := DMDadosPesquisa.qClientePesquisa.FieldByName('documento1').asString; cliente_endereco := DMDadosPesquisa.qClientePesquisa.FieldByName('endereco').asString; if DMDadosPesquisa.qClientePesquisa.FieldByName('documento1').asString <> '' then lb_nome_cliente.Caption := lb_nome_cliente.Caption + ' - ' + DMDadosPesquisa.qClientePesquisa.FieldByName('documento1').asString; if DMDadosPesquisa.qClientePesquisa.FieldByName('telefone').AsString <> '' then lb_nome_cliente.Caption := lb_nome_cliente.Caption + ' - '+ DMDadosPesquisa.qClientePesquisa.FieldByName('telefone').asString; if DMDadosPesquisa.qClientePesquisa.FieldByName('celular').AsString <> '' then lb_nome_cliente.Caption := lb_nome_cliente.Caption + ' - '+ DMDadosPesquisa.qClientePesquisa.FieldByName('celular').asString; DMDadosLista.qGenerica.Close; dmdadosLista.qGenerica.SQL.Clear; DMDadosLista.qGenerica.sql.Add('select max(data_pagamento) as data_pagamento from conta_receber where id_cliente = :id_cliente'); dmdadosLista.qGenerica.Params.ParamByName('id_cliente').AsInteger := StrToInt(edt_codcliente.Text); DMDadosLista.qGenerica.Open(); if DMDadosLista.qGenerica.RecordCount > 0 then begin ultima_data_pagamento.Caption := siLangLinked_FrmConsultaContaReceber.GetTextOrDefault('IDS_234' (* 'Ult. Pagto: ' *) ) + FormatDateTime('dd/mm/yyyy',DMDadosLista.qGenerica.FieldByName('data_pagamento').asDateTime); ultima_data_pagamento.Font.Color := clRed; end; lbValorSelecionadoText.Visible := false; lbValorSelecionadoValor.Visible := false; lbValorSelecionadoValor.Caption := ''; dtpInicio.DateTime := DMDadosPesquisa.qClientePesquisa.FieldByName('datacad').AsDateTime; end; FreeAndNil(vListaCampos); CarregaContasReceber; DBGrid1.SetFocus; end; procedure TFrmConsultaContaReceber.SomaTotais; begin valorUS := 0; ValorGS := 0; ValorRS := 0; if not (DataSet1.FieldByName('totalus').AsVariant = null) then valorUS := DataSet1.FieldByName('totalus').AsVariant; if not (DataSet1.FieldByName('totalgs').AsVariant = null) then valorGS := DataSet1.FieldByName('totalgs').asVariant; if not (DataSet1.FieldByName('totalrs').AsVariant = null) then valorRS := DataSet1.FieldByName('totalrs').asVariant; if edt_codcliente.text <> '' then begin ValorGSCredito := fnGetTotalCreditoCliente(StrToInt( edt_codcliente.text)); end; edtCredito.AsFloat := ValorGSCredito; edtSaldo.AsFloat := ValorGS - ValorGSCredito; end; procedure TFrmConsultaContaReceber.ExpXLS(DataSet: TDataSet; Arq: string); var ExcApp: OleVariant; i,l: integer; k: Integer; J: Integer; coluna: Integer; saldo: string; saldototal: Double; begin ExcApp := CreateOleObject('Excel.Application'); ExcApp.Visible := False; ExcApp.WorkBooks.Add(1); ExcApp.Caption := 'Extrato Cliente ' ; DataSet.First; l := 2; DataSet.First; // for k := 2 to dataset.Fields.Count -1 do // begin // ExcApp.WorkBooks[1].Sheets[1].Cells[1,k] := DataSet.Fields[k].FieldName; // end; ExcApp.WorkBooks[1].Sheets[1].Cells[1,1] := 'Cliente'; ExcApp.WorkBooks[1].Sheets[1].Cells[1,2] := 'Nota'; ExcApp.WorkBooks[1].Sheets[1].Cells[1,3] := 'Lancamento'; ExcApp.WorkBooks[1].Sheets[1].Cells[1,4] := 'Vencimento'; ExcApp.WorkBooks[1].Sheets[1].Cells[1,5] := 'Valor'; ExcApp.WorkBooks[1].Sheets[1].Cells[1,6] := 'Valor Pago'; ExcApp.WorkBooks[1].Sheets[1].Cells[1,7] := 'Saldo'; // ExcApp.WorkBooks[1].Sheets[1].Cells[1,7] := DataSet.Fields[6].FieldName; // ExcApp.WorkBooks[1].Sheets[1].Cells[1,8] := DataSet.Fields[7].FieldName; // ExcApp.WorkBooks[1].Sheets[1].Cells[1,9] := DataSet.Fields[8].FieldName; j := 0; while not DataSet.EOF do // for J := 0 to dataset.RecordCount - 1 do begin saldototal := dataset.FieldByName('valor').AsFloat - dataset.FieldByName('valor_pago').AsFloat; ExcApp.WorkBooks[1].Sheets[1].Cells[l,7] := saldototal; for i := 0 to DataSet.Fields.Count - 1 do begin if ((Dataset.fields.Fields[i].FieldName = 'valor') or (Dataset.fields.Fields[i].FieldName = 'nome') or (Dataset.fields.Fields[i].FieldName = 'historico') or (Dataset.fields.Fields[i].FieldName = 'data_lancamento') or (Dataset.fields.Fields[i].FieldName = 'valor_pago') or (Dataset.fields.Fields[i].FieldName = 'data_vencimento')) then begin // nome = 1 // Vencimento = 2 // Valor = 3 // Valor Pago = 4 // Saldo = 5 if DataSet.Fields[i].DataType = ftString then begin if Dataset.fields.Fields[i].FieldName = 'nome' then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,1] := DataSet.Fields[i].asString; end else if Dataset.fields.Fields[i].FieldName = 'historico' then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,2] := DataSet.Fields[i].asString; end; end else if DataSet.Fields[i].DataType = ftLargeint then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,coluna] := DataSet.Fields[i].asInteger; end else if dataset.Fields[i].DataType = ftFMTBcd then begin if (Dataset.fields.Fields[i].FieldName = 'valor') then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,5] := formatFloat(fngetMoedaMascara,DataSet.Fields[i].asFloat); //ExcApp.WorkBooks[1].Sheets[1].Cells[l,5].Font.Bold := true; end else if (Dataset.fields.Fields[i].FieldName = 'valor_pago') then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,6] := formatFloat(fngetMoedaMascara,DataSet.Fields[i].asFloat); end else if (Dataset.fields.Fields[i].FieldName = 'saldo') then begin //saldo := ExcApp.WorkBooks[1].Sheets[1].Cells[l,3] - ExcApp.WorkBooks[1].Sheets[1].Cells[l,4]; ExcApp.WorkBooks[1].Sheets[1].Cells[l,7] := formatFloat(fngetMoedaMascara,DataSet.Fields[i].asFloat); //saldo := formatFloat(fngetMoedaMascara,DataSet.Fields[i].asFloat); end; end else if ( (dataset.Fields[i].DataType = ftDate) or (dataset.Fields[i].DataType = ftDateTime))then begin if Dataset.fields.Fields[i].FieldName = 'data_vencimento' then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,4] := DataSet.Fields[i].AsDateTime; end else if Dataset.fields.Fields[i].FieldName = 'data_lancamento' then begin ExcApp.WorkBooks[1].Sheets[1].Cells[l,3] := DataSet.Fields[i].AsDateTime; end; end; inc(coluna); end; end; l := l + 1; inc(j); dataset.next; end; ExcApp.Columns.AutoFit; ExcApp.WorkBooks[1].SaveAs( ExtractFilePath(Application.ExeName)+Arq); end; end.
{ ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: QuickReport 3.5 for Delphi and C++Builder :: :: :: :: QRWIZARD - WIZARD WRAPPER AND BASIC WIZARDS :: :: :: :: Copyright (c) 2007 QBS Sofware :: :: All Rights Reserved :: :: :: :: web: http://www.qusoft.no :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: } unit QRWizard; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, QR5Const, StdCtrls, ExtCtrls, QuickRpt, DBTables, QRDataWz, QRExtra; type TQRWizard = class; TMainWizardForm = class(TForm) SelectPanel: TPanel; StartWizardBtn: TButton; Button1: TButton; GroupBox1: TGroupBox; WizardCB: TComboBox; Description: TMemo; Image2: TImage; procedure FormActivate(Sender: TObject); procedure WizardCBChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure StartWizardBtnClick(Sender: TObject); procedure Button1Click(Sender: TObject); private FReport : TCustomQuickRep; ActiveWizard : TQRWizard; public property Report : TCustomQuickRep read FReport; end; TQRWizard = class public function Name : string; virtual; abstract; function Description : string; virtual; abstract; function CanClose : boolean; virtual; abstract; function Picture : TPicture; virtual; abstract; function Execute(Parent : TWinControl) : TCustomQuickRep; virtual; abstract; end; TQRWizardClass = class of TQRWizard; TQRPlainWizard = class(TQRWizard) public function Name : string; override; function Description : string; override; function CanClose : boolean; override; function Execute(Parent : TWinControl) : TCustomQuickRep; override; end; TQRPlainWizardClass = class of TQRPlainWizard; TQRListWizard = class(TQRWizard) public function Name : string; override; function Description : string; override; function CanClose : boolean; override; function Execute(Parent : TWinControl) : TCustomQuickRep; override; end; TQRListWizardClass = class of TQRListWizard; TQRMasterDetailWizard = class(TQRWizard) public function Name : string; override; function Description : string; override; function CanClose : boolean; override; function Execute(Parent : TWinControl) : TCustomQuickRep; override; end; TQRMasterDetailWizardClass = class of TQRMasterDetailWizard; TQRLabelWizard = class(TQRWizard) public function Name : string; override; function Description : string; override; function CanClose : boolean; override; function Execute(Parent : TWinControl) : TCustomQuickRep; override; end; TQRLabelWizardClass = class of TQRLabelWizard; procedure RegisterQRWizard(WizardClass : TQRWizardClass); function ExecuteQRWizard : TCustomQuickRep; function WizardList : TList; implementation {$R *.DFM} function ExecuteQRWizard : TCustomQuickRep; begin with TMainWizardForm.Create(Application) do try ShowModal; if ModalResult = mrOK then Result := Report else Result := nil; finally Free; end; end; procedure TMainWizardForm.FormActivate(Sender: TObject); var I : integer; begin WizardCB.Items.Clear; for I := 0 to WizardList.Count - 1 do WizardCB.Items.Add(TQRWizard(WizardList[I]).Name); WizardCB.ItemIndex := 0; WizardCBChange(Self); end; procedure TMainWizardForm.WizardCBChange(Sender: TObject); begin Description.Lines.Clear; if WizardList.Count > 0 then Description.Lines.Add(TQRWizard(WizardList[WizardCB.ItemIndex]).Description); end; procedure TMainWizardForm.FormCreate(Sender: TObject); begin FReport := nil; ActiveWizard := nil; end; procedure TMainWizardForm.StartWizardBtnClick(Sender: TObject); begin if WizardList.Count > 0 then begin ActiveWizard := TQRWizard(WizardList[WizardCB.ItemIndex]); FReport := ActiveWizard.Execute(SelectPanel); end; if FReport <> nil then ModalResult := mrOK; ActiveWizard := nil; end; function TQRPlainWizard.Name : string; begin Result := SqrPlainWizardName; end; function TQRPlainWizard.Description : string; begin Result := SqrPlainWizardDescription; end; function TQRPlainWizard.CanClose : boolean; begin Result := true; end; function TQRPlainWizard.Execute(Parent : TWinControl) : TCustomQuickRep; begin Result := TQuickRep.Create(nil); with TQuickRep(Result).Bands do begin HasTitle := true; HasPageHeader := true; HasPageFooter := true; HasSummary := true; HasDetail := true; end; end; function TQRListWizard.Name : string; begin Result := SqrListWizardName; end; function TQRListWizard.Description : string; begin Result := SqrListWizardDescription; end; function TQRListWizard.CanClose : boolean; begin Result := true; end; function TQRListWizard.Execute(Parent : TWinControl) : TCustomQuickRep; var PageNumber : integer; PageResult : integer; TableName : string; AliasName : string; FieldList : TStrings; ATable : TTable; begin FieldList := TStringList.Create; AliasName := ''; TableName := ''; PageNumber := 1; pageresult := 1; Result := nil; repeat case PageNumber of 1 : PageResult := GetTable(AliasName, TableName, FieldList, Parent); end; until (PageResult = 3) or ((PageResult = 2) and (PageNumber = 1)); if PageResult = 2 then begin ATable := TTable.Create(nil); ATable.DatabaseName := AliasName; ATable.TableName := TableName; ATable.FieldDefs.Update; ATable.Active := true; ATable.Name := 'Table1'; QRCreateList(Result, nil, ATable, '', FieldList); Result.InsertComponent(ATable); TQuickRep(Result).DataSet := ATable; Result.Visible := true; end; end; function TQRMasterDetailWizard.Name : string; begin Result := SqrMasterDetailWizardName; end; function TQRMasterDetailWizard.Description : string; begin Result := SqrMasterDetailWizardDescription; end; function TQRMasterDetailWizard.CanClose : boolean; begin Result := true; end; function TQRMasterDetailWizard.Execute(Parent : TWinControl) : TCustomQuickRep; begin Result := nil; end; function TQRLabelWizard.Name : string; begin Result := SqrLabelWizardName; end; function TQRLabelWizard.Description : string; begin Result := SqrLabelWizardDescription; end; function TQRLabelWizard.CanClose : boolean; begin Result := true; end; function TQRLabelWizard.Execute(Parent : TWinControl) : TCustomQuickRep; begin Result := nil; end; var AWizardList : TList; function WizardList : TList; begin if AWizardList = nil then AWizardList := TList.Create; Result := AWizardList; end; procedure RegisterQRWizard(WizardClass : TQRWizardClass); begin if AWizardList = nil then AWizardList := TList.Create; AWizardList.Add(WizardClass.Create); end; procedure TMainWizardForm.Button1Click(Sender: TObject); begin Close end; initialization AWizardList := nil; finalization if WizardList <> nil then begin while WizardList.Count > 0 do begin TObject(WizardList[0]).Free; WizardList.Delete(0); end; WizardList.Free; end; end.
unit LuaDissectCode; {$mode delphi} interface uses {$ifdef darwin}MacPort,{$endif}Classes, SysUtils, lua, lauxlib, lualib; procedure initializeLuaDissectCode; implementation uses DissectCodeThread, luahandler, LuaClass, LuaObject, symbolhandler, symbolhandlerstructs, newkernelhandler, ProcessHandlerUnit; resourcestring rsTheModuleNamed = 'The module named '; rsCouldNotBeFound = ' could not be found'; rsInvalidParametersForDissect = 'Invalid parameters for dissect'; function getDissectCode(L: PLua_State): integer; cdecl; begin if dissectcode=nil then dissectcode:=TDissectCodeThread.create(false); luaclass_newClass(L, dissectcode); result:=1; end; function dissectcode_dissect(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; start: ptruint; size: integer; mi: TModuleInfo; modulename: string; begin //2 versions, modulename and base,size //base can be a string too, so check paramcount result:=0; dc:=luaclass_getClassObject(L); dc.waitTillDone; //just in case... if lua_gettop(L)=1 then begin //modulename modulename:=Lua_ToString(L,1); if symhandler.getmodulebyname(modulename, mi) then begin start:=mi.baseaddress; size:=mi.basesize; end else raise exception.create(rsTheModuleNamed+modulename+rsCouldNotBeFound) end else if lua_gettop(L)=2 then begin if lua_type(L,1)=LUA_TSTRING then start:=symhandler.getAddressFromName(Lua_ToString(L,1)) else start:=lua_tointeger(L,1); size:=lua_tointeger(L, 2); end else raise exception.create(rsInvalidParametersForDissect); //all date is here, setup a scan config setlength(dissectcode.memoryregion,1); dissectcode.memoryregion[0].BaseAddress:=start; dissectcode.memoryregion[0].MemorySize:=size; dc.dowork; dc.waitTillDone; result:=0; end; function dissectcode_clear(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; begin dc:=luaclass_getClassObject(L); dc.clear; result:=0; end; function dissectcode_addReference(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; fromaddress, toaddress: ptruint; reftype: tjumptype; isstring: boolean; begin dc:=luaclass_getClassObject(L); if lua_type(L,1)=LUA_TSTRING then fromaddress:=symhandler.getAddressFromName(Lua_ToString(L,1)) else fromaddress:=lua_tointeger(L,1); if lua_type(L,2)=LUA_TSTRING then toaddress:=symhandler.getAddressFromName(Lua_ToString(L,2)) else toaddress:=lua_tointeger(L,2); reftype:=tjumptype(lua_tointeger(L,3)); if lua_gettop(L)=4 then isstring:=lua_toboolean(L, 4) else isstring:=false; dc.addReference(fromaddress, toaddress,reftype, isstring); result:=0; end; function dissectcode_deleteReference(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; fromaddress, toaddress: ptruint; begin dc:=luaclass_getClassObject(L); if lua_type(L,1)=LUA_TSTRING then fromaddress:=symhandler.getAddressFromName(Lua_ToString(L,1)) else fromaddress:=lua_tointeger(L,1); if lua_type(L,2)=LUA_TSTRING then toaddress:=symhandler.getAddressFromName(Lua_ToString(L,2)) else toaddress:=lua_tointeger(L,2); dc.removeReference(fromaddress, toaddress); result:=0; end; function dissectcode_getReferences(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; address: ptruint; da: tdissectarray; i,t: integer; begin result:=1; dc:=luaclass_getClassObject(L); if lua_type(L,1)=LUA_TSTRING then address:=symhandler.getAddressFromName(Lua_ToString(L,1)) else address:=lua_tointeger(L,1); setlength(da,0); if dc.CheckAddress(address, da) then begin lua_newtable(L); t:=lua_gettop(L); for i:=0 to length(da)-1 do begin lua_pushinteger(L, da[i].address); lua_pushinteger(L, integer(da[i].jumptype)); lua_settable(L, t); end; end else lua_pushnil(L); end; function dissectcode_getReferencedStrings(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; s: tstringlist; i,t: integer; sr: TStringReference; str: pchar; strw: pwidechar absolute str; x: ptruint; temps: string; begin result:=1; dc:=luaclass_getClassObject(L); s:=TStringList.create; dc.getstringlist(s); if s.count>0 then begin lua_newtable(L); t:=lua_gettop(L); getmem(str,512); for i:=0 to s.count-1 do begin sr:=TStringReference(s.Objects[i]); if readprocessmemory(processhandle, pointer(sr.address), str,512,x) then begin str[511]:=#0; str[510]:=#0; if strlen(str)>strlen(strw) then temps:=str else temps:=strw; end else temps:=''; lua_pushinteger(L, sr.address); lua_pushstring(L, temps); lua_settable(L, t); freeandnil(sr); end; FreeMemAndNil(str); end else lua_pushnil(L); s.free; end; function dissectcode_getReferencedFunctions(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; callList: TList; i: integer; begin result:=1; dc:=luaclass_getClassObject(L); lua_pop(L, lua_gettop(L)); callList:=tlist.create; dc.getCallList(callList); if callList.count>0 then begin lua_newtable(L); for i:=0 to callList.count-1 do begin lua_pushinteger(L, i+1); lua_pushinteger(L, TDissectReference(callList[i]).address); lua_settable(L, -3); TDissectReference(callList[i]).free; end; end else lua_pushnil(L); callList.free; end; function dissectcode_saveToFile(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; begin result:=0; dc:=luaclass_getClassObject(L); try if lua_gettop(L)=1 then dc.saveToFile(Lua_ToString(L,1)); lua_pushboolean(L, true); result:=1; except on e:exception do begin lua_pushboolean(L, false); lua_pushstring(L, e.Message); result:=2; end; end; end; function dissectcode_loadFromFile(L: PLua_State): integer; cdecl; var dc: TDissectCodeThread; begin result:=0; dc:=luaclass_getClassObject(L); try if lua_gettop(L)=1 then dc.loadFromFile(Lua_ToString(L,1)); lua_pushboolean(L, true); result:=1; except on e:exception do begin lua_pushboolean(L, false); lua_pushstring(L, e.Message); result:=2; end; end; end; procedure dissectcode_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'dissect', dissectcode_dissect); luaclass_addClassFunctionToTable(L, metatable, userdata, 'clear', dissectcode_clear); luaclass_addClassFunctionToTable(L, metatable, userdata, 'addReference', dissectcode_addReference); luaclass_addClassFunctionToTable(L, metatable, userdata, 'deleteReference', dissectcode_deleteReference); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getReferences', dissectcode_getReferences); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getReferencedStrings', dissectcode_getReferencedStrings); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getReferencedFunctions', dissectcode_getReferencedFunctions); luaclass_addClassFunctionToTable(L, metatable, userdata, 'saveToFile', dissectcode_saveToFile); luaclass_addClassFunctionToTable(L, metatable, userdata, 'loadFromFile', dissectcode_loadFromFile); end; procedure initializeLuaDissectCode; begin lua_register(LuaVM, 'getDissectCode', getDissectCode); end; initialization luaclass_register(TDissectCodeThread, dissectcode_addMetaData); end.
unit uthrImportarEntregas; interface uses System.Classes, Dialogs, Windows, Forms, SysUtils, clUtil, clCodigosEntregadores, clStatus, clAgentes, clEntrega, Messages, Controls, System.DateUtils, System.StrUtils; type TCSVEntrega = record _agenteTFO: String; _descricaoAgenteTFO: String; _nossonumero: String; _cliente: String; _nota: String; _consumidor: String; _cuidados: String; _logradouro: String; _complemento: String; _bairro: String; _cidade: String; _cep: String; _telefone: String; _expedicao: String; _previsao: String; _status: String; _descricaoStatus: String; _entregador: String; _container: String; _valorProduto: String; _verba: String; _altura: String; _largura: String; _comprimento: String; _peso: String; _volumes: String; _codcliente: String; end; type thrImportarEntregas = class(TThread) private { Private declarations } entregador: TCodigosEntregadores; entrega: TEntrega; agentes: TAgente; status: TStatus; CSVEntrega: TCSVEntrega; protected procedure Execute; override; procedure AtualizaLog; procedure AtualizaProgress; procedure TerminaProcesso; function TrataLinha(sLinha: String): String; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure thrImportarEntregas.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { thrImportarEntregas } uses ufrmImportaentrega, uGlobais; function thrImportarEntregas.TrataLinha(sLinha: String): String; var iConta: Integer; sLin: String; bFlag: Boolean; begin if Pos('"', sLinha) = 0 then begin Result := sLinha; Exit; end; iConta := 1; bFlag := False; sLin := ''; while sLinha[iConta] >= ' ' do begin if sLinha[iConta] = '"' then begin if bFlag then bFlag := False else bFlag := True; end; if bFlag then begin if sLinha[iConta] = ';' then sLin := sLin + ' ' else sLin := sLin + sLinha[iConta]; end else sLin := sLin + sLinha[iConta]; Inc(iConta); end; Result := sLin; end; procedure thrImportarEntregas.Execute; var ArquivoCSV: TextFile; Contador, I, LinhasTotal, iRet: Integer; Linha, campo, codigo, sMess, sData: String; d: Real; // Lê Linha e Monta os valores function MontaValor: String; var ValorMontado: String; begin ValorMontado := ''; Inc(I); While Linha[I] >= ' ' do begin If Linha[I] = ';' then // vc pode usar qualquer delimitador ... eu // estou usando o ";" break; ValorMontado := ValorMontado + Linha[I]; Inc(I); end; Result := ValorMontado; end; begin entregador := TCodigosEntregadores.Create; entrega := TEntrega.Create; agentes := TAgente.Create; status := TStatus.Create; LinhasTotal := TUtil.NumeroDeLinhasTXT(frmImportaEntregas.cxArquivo.Text); // Carregando o arquivo ... AssignFile(ArquivoCSV, frmImportaEntregas.cxArquivo.Text); try Reset(ArquivoCSV); Readln(ArquivoCSV, Linha); if Copy(Linha, 0, 38) <> 'CONSULTA DE ENTREGAS NA WEB POR STATUS' then begin MessageDlg ('Arquivo informado não é de CONSULTA DE ENTREGAS NA WEB POR STATUS.', mtWarning, [mbOK], 0); Abort; end; Readln(ArquivoCSV, Linha); Readln(ArquivoCSV, Linha); Contador := 3; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, Linha); Linha := TrataLinha(Linha); with CSVEntrega do begin _agenteTFO := MontaValor; _descricaoAgenteTFO := MontaValor; _nossonumero := MontaValor; _cliente := MontaValor; _nota := MontaValor; _consumidor := MontaValor; _cuidados := MontaValor; _logradouro := MontaValor; _complemento := MontaValor; _bairro := MontaValor; _cidade := MontaValor; _cep := MontaValor; _telefone := MontaValor; _expedicao := MontaValor; _previsao := MontaValor; _status := MontaValor; _descricaoStatus := MontaValor; _entregador := MontaValor; _container := MontaValor; _valorProduto := MontaValor; _verba := MontaValor; _altura := MontaValor; _largura := MontaValor; _comprimento := MontaValor; _peso := MontaValor; _volumes := MontaValor; _codcliente := '1'; end; if not(entrega.getObject(CSVEntrega._nossonumero, 'NOSSONUMERO')) then begin entrega.Agente := 0; entrega.entregador := 0; entrega.NossoNumero := CSVEntrega._nossonumero; entrega.Cliente := StrToInt(CSVEntrega._cliente); entrega.NF := CSVEntrega._nota; entrega.Consumidor := CSVEntrega._consumidor; entrega.Endereco := CSVEntrega._logradouro; entrega.Complemento := Copy(Trim(CSVEntrega._complemento),1,50); entrega.Bairro := CSVEntrega._bairro; entrega.Cidade := CSVEntrega._cidade; entrega.Cep := CSVEntrega._cep; entrega.Telefone := Copy(CSVEntrega._telefone,1,30); entrega.Expedicao := StrToDate(CSVEntrega._expedicao); entrega.PrevDistribuicao := StrToDate(CSVEntrega._previsao); entrega.status := StrToInt(CSVEntrega._status); entrega.Baixado := 'N'; if not(status.getObject(CSVEntrega._status, 'CODIGO')) then begin status.Codigo := StrToInt(CSVEntrega._status); status.Descricao := CSVEntrega._descricaoStatus; status.Percentual := 0; status.Baixa := 'S'; if (not status.Insert) then begin sMensagem := 'Erro ao Incluir o Status de Entrega ' + CSVEntrega._status + ' - ' + CSVEntrega._descricaoStatus + ' na tabela de Apoio!'; Synchronize(AtualizaLog); end; end; CSVEntrega._verba := ReplaceStr(CSVEntrega._verba, 'R$ ', ''); entrega.VerbaDistribuicao := StrToFloatDef(CSVEntrega._verba,0); CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, ' KG', ''); CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, '.', ','); entrega.PesoReal := StrToFloatDef(CSVEntrega._peso,0); entrega.Volumes := StrToInt(CSVEntrega._volumes); entrega.VolumesExtra := 0; entrega.ValorExtra := 0; entrega.DiasAtraso := 0; entrega.Container := CSVEntrega._container; CSVEntrega._valorProduto := ReplaceStr(CSVEntrega._valorProduto, 'R$ ', ''); entrega.ValorProduto := StrToFloatDef(CSVEntrega._valorProduto,0); entrega.Altura := StrToIntDef(CSVEntrega._altura, 0); entrega.Largura := StrToIntDef(CSVEntrega._largura, 0); entrega.Comprimento := StrToIntDef(CSVEntrega._comprimento, 0); entrega.CodCliente := StrToIntDef(CSVEntrega._codcliente, 0); entrega.Rastreio := 'Entrega importada em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' por ' + uGlobais.sNomeUsuario; if not(entrega.Insert) then begin sMensagem := 'Erro ao Incluir os dados do NN ' + entrega.NossoNumero + ' !'; Synchronize(AtualizaLog); end; end else begin entrega.Cliente := StrToInt(CSVEntrega._cliente); entrega.NF := CSVEntrega._nota; entrega.Consumidor := CSVEntrega._consumidor; entrega.Endereco := CSVEntrega._logradouro; entrega.Complemento := CSVEntrega._complemento; entrega.Bairro := CSVEntrega._bairro; entrega.Cidade := CSVEntrega._cidade; entrega.Cep := CSVEntrega._cep; entrega.Telefone := Copy(CSVEntrega._telefone,1,30); entrega.Expedicao := StrToDate(CSVEntrega._expedicao); entrega.PrevDistribuicao := StrToDate(CSVEntrega._previsao); entrega.status := StrToInt(CSVEntrega._status); CSVEntrega._verba := ReplaceStr(CSVEntrega._verba, 'R$ ', ''); entrega.VerbaDistribuicao := StrToFloatDef(CSVEntrega._verba,0); CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, ' KG', ''); CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, '.', ','); entrega.PesoReal := StrToFloatDef(CSVEntrega._peso,0); entrega.Volumes := StrToInt(CSVEntrega._volumes); entrega.Container := CSVEntrega._container; CSVEntrega._valorProduto := ReplaceStr(CSVEntrega._valorProduto, 'R$ ', ''); entrega.ValorProduto := StrToFloatDef(CSVEntrega._valorProduto,0); entrega.Altura := StrToIntDef(CSVEntrega._altura, 0); entrega.Largura := StrToIntDef(CSVEntrega._largura, 0); entrega.Comprimento := StrToIntDef(CSVEntrega._comprimento, 0); entrega.CodCliente := StrToIntDef(CSVEntrega._codcliente, 0); entrega.Rastreio := entrega.Rastreio + #13 + 'Entrega re-importada em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' por ' + uGlobais.sNomeUsuario; if not(entrega.Update) then begin sMensagem := 'Erro ao Alterar os dados do NN ' + entrega.NossoNumero + ' !'; Synchronize(AtualizaLog); end; end; I := 0; iConta := Contador; iTotal := LinhasTotal; dPosicao := (iConta / iTotal) * 100; Inc(Contador, 1); if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin entregador.Free; entrega.Free; agentes.Free; status.Free; Abort; end; end; finally CloseFile(ArquivoCSV); Application.MessageBox('Importação concluída!', 'Importação de Entregas', MB_OK + MB_ICONINFORMATION); sMensagem := 'Importação terminada em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now); Synchronize(AtualizaLog); Synchronize(TerminaProcesso); entregador.Free; entrega.Free; agentes.Free; status.Free; end; end; procedure thrImportarEntregas.AtualizaLog; begin frmImportaEntregas.cxLog.Lines.Add(sMensagem); frmImportaEntregas.cxLog.Refresh; end; procedure thrImportarEntregas.AtualizaProgress; begin frmImportaEntregas.cxProgressBar1.Position := dPosicao; frmImportaEntregas.cxProgressBar1.Properties.Text := 'Registro ' + IntToStr(iConta) + ' de ' + IntToStr(iTotal); frmImportaEntregas.cxProgressBar1.Refresh; if not(frmImportaEntregas.actImportaEntregaCancelar.Visible) then begin frmImportaEntregas.actImportaEntregaCancelar.Visible := True; frmImportaEntregas.actImportaEntregaSair.Enabled := False; frmImportaEntregas.actImportarEntregaImportar.Enabled := False; end; end; procedure thrImportarEntregas.TerminaProcesso; begin frmImportaEntregas.actImportaEntregaCancelar.Visible := False; frmImportaEntregas.actImportaEntregaSair.Enabled := True; frmImportaEntregas.actImportarEntregaImportar.Enabled := True; frmImportaEntregas.cxArquivo.Clear; frmImportaEntregas.cxProgressBar1.Properties.Text := ''; frmImportaEntregas.cxProgressBar1.Position := 0; frmImportaEntregas.cxProgressBar1.Clear; end; end.
unit Main; {$I uniCompilers.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIRegClasses, uniGUIForm, uniGUIBaseClasses, uniPanel, uniSplitter, uniEdit, uniTreeView, uniStatusBar, uniMultiItem, uniComboBox, uniTimer, uniPageControl, uniButton, uniBitBtn, uniGUIFrame, umain, uniToolBar, uniImageList, uniLabel, Menus, uniMainMenu, pngimage, uniImage, Data.DBXMySQL, Data.DB, Data.SqlExpr, Datasnap.DBClient, uniBasicGrid, uniDBGrid; type TMainForm = class(TUniForm) UniPanel1: TUniPanel; UniSplitter1: TUniSplitter; NavTree: TUniTreeView; UniStatusBar1: TUniStatusBar; UniContainerPanel2: TUniContainerPanel; UniContainerPanel3: TUniContainerPanel; ThemeComboBox: TUniComboBox; UniClockTimer: TUniTimer; UniPageControl1: TUniPageControl; UniTabSheet1: TUniTabSheet; FrameMain1: TFrameMain; UniToolBar1: TUniToolBar; UniToolButton1: TUniToolButton; UniToolButton2: TUniToolButton; UniToolButton3: TUniToolButton; UniToolButton4: TUniToolButton; UniLabel1: TUniLabel; UniMainMenu1: TUniMainMenu; File1: TUniMenuItem; Exit1: TUniMenuItem; UniToolButton5: TUniToolButton; UniToolButton6: TUniToolButton; uniGUIWebsite1: TUniMenuItem; UniNativeImageList1: TUniNativeImageList; SearchEdit: TUniComboBox; Favorites1: TUniMenuItem; UniPopupMenu1: TUniPopupMenu; AddtoFavorites1: TUniMenuItem; RemoveFromFavorites1: TUniMenuItem; UniNativeImageList2: TUniNativeImageList; SQLConnection: TSQLConnection; CDSCarrinho: TClientDataSet; CDSCarrinhoID: TIntegerField; CDSCarrinhoNOME: TStringField; CDSCarrinhoQUANTIDADE: TFloatField; CDSCarrinhoVALOR: TFloatField; CDSCarrinhoGTIN: TStringField; CDSCarrinhoTOTAL: TAggregateField; procedure UniClockTimerTimer(Sender: TObject); procedure UniFormCreate(Sender: TObject); procedure NavTreeClick(Sender: TObject); procedure TabSheetClose(Sender: TObject; var AllowClose: Boolean); procedure UniFormDestroy(Sender: TObject); procedure UniPageControl1Change(Sender: TObject); procedure UniToolButton1Click(Sender: TObject); procedure UniToolButton2Click(Sender: TObject); procedure UniToolButton4Click(Sender: TObject); procedure ThemeComboBoxChange(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure Navigate1Click(Sender: TObject); procedure UniToolButton6Click(Sender: TObject); procedure UniFormAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); procedure FrameMain1Create(Sender: TObject); procedure SearchEditTriggerEvent(Sender: TUniCustomComboBox; AButtonId: Integer); procedure SearchEditChange(Sender: TObject); procedure NavTreeLoaded(Sender: TObject); procedure AddtoFavorites1Click(Sender: TObject); procedure NavTreeCellContextClick(ANode: TUniTreeNode; X, Y: Integer); procedure RemoveFromFavorites1Click(Sender: TObject); private { Private declarations } FileNames : TStrings; PSString, FHomeUrl : string; procedure RefreshTime; procedure ConstructNavigator; procedure GetThemes; function CreateImageIndex(filename: string): Integer; procedure SearchTree(const AText: string); procedure AddToSubMenu(ANode: TUniTreeNode); procedure WriteFavs; public Item: Integer; { Public declarations } end; function MainForm: TMainForm; implementation {$R *.dfm} uses uniGUIVars, MainModule, uniGUIApplication, ShowSource, ServerModule, uniStrUtils, uniGUITheme, UniGUIJSUtils, IniFiles; function MainForm: TMainForm; begin Result := TMainForm(UniMainModule.GetFormInstance(TMainForm)); end; procedure TMainForm.UniClockTimerTimer(Sender: TObject); begin RefreshTime; end; procedure TMainForm.SearchEditChange(Sender: TObject); begin SearchTree(SearchEdit.Text); end; procedure TMainForm.SearchTree(const AText: string); var S, SString : string; I : Integer; aExpand : Boolean; begin SString := Trim(AText); if SString<>PSString then begin PSString := LowerCase(SString); if (Length(PSString) > 1) or (PSString = '') then begin aExpand := PSString<>''; NavTree.BeginUpdate; try NavTree.ResetData; for I := 0 to NavTree.Items.Count - 1 do begin S := LowerCase(NavTree.Items[I].Text); NavTree.Items[I].Visible := (Length(PSString) = 0) or (Pos(PSString, S)>0); NavTree.Items[I].Expanded := aExpand; end; finally NavTree.EndUpdate; end; end; end; end; procedure TMainForm.SearchEditTriggerEvent(Sender: TUniCustomComboBox; AButtonId: Integer); begin case AButtonId of 0 : SearchTree(Sender.Text); end; end; function TMainForm.CreateImageIndex(filename: string): Integer; begin Result := UniNativeImageList2.AddIconFile(filename); end; procedure TMainForm.Exit1Click(Sender: TObject); begin Close; end; procedure TMainForm.FrameMain1Create(Sender: TObject); begin FrameMain1.UniFrameCreate(Sender); end; procedure TMainForm.GetThemes; var S : TUniStringArray; I : Integer; begin S := UniServerModule.ThemeManager.AllThemes; ThemeComboBox.Items.Clear; for I := Low(S) to High(S) do ThemeComboBox.Items.Add(S[I]); end; procedure TMainForm.UniFormAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); begin if EventName = 'mybrowsercallback' then begin if Params.Values['RES'] = 'OK' then ShowMessage('Operation Succeeded: '+Params.Values['firstname'] +' '+Params.Values['lastname']) else if Params.Values['RES']='CANCEL' then ShowMessage('Operation Cancelled.'); end else if EventName = 'mycallback' then begin ShowMessage('Operation Succeeded:'^M^M+Params.Values['user']+^M^M+Params.Text) end; end; procedure TMainForm.UniFormCreate(Sender: TObject); var I, Count : Integer; Ini: TIniFile; begin Item := 0; SQLConnection.Connected := True; UniMainModule.Main := Self; FileNames := TStringList.Create; RefreshTime; ConstructNavigator; GetThemes; ThemeComboBox.Text := UniMainModule.Theme; FHomeUrl := 'http://www.unigui.com'; SearchEdit.Text := ''; //Favorites Ini := TIniFile.Create(UniServerModule.FilesFolderPath+'Favorites.ini'); try Count := Ini.ReadInteger('favorites','FavoritesCount', 0); for I := 0 to Count - 1 do AddToSubMenu(NavTree.Items.FindNodeByCaption( Ini.ReadString('favorites', IntToStr(I), '') )); finally Ini.Free; end; end; procedure TMainForm.WriteFavs; var Ini: TIniFile; C, I: Integer; begin Ini := TIniFile.Create(UniServerModule.FilesFolderPath+'Favorites.ini'); try C := Favorites1.Count; Ini.WriteInteger('favorites', 'FavoritesCount', C); for I := 0 to C - 1 do Ini.WriteString('favorites', IntToStr(I), Favorites1.Items[I].Caption); finally Ini.Free; end; end; procedure TMainForm.UniFormDestroy(Sender: TObject); begin FileNames.Free; end; procedure TMainForm.UniPageControl1Change(Sender: TObject); var Ts : TUniTabSheet; Nd : TUniTreeNode; begin Ts := UniPageControl1.ActivePage; Nd := Pointer(Ts.Tag); NavTree.Selected := Nd; end; procedure TMainForm.UniToolButton1Click(Sender: TObject); begin NavTree.FullExpand; end; procedure TMainForm.UniToolButton2Click(Sender: TObject); begin NavTree.FullCollapse; end; procedure TMainForm.UniToolButton4Click(Sender: TObject); var I: Integer; Ts : TUniTabSheet; begin for I := UniPageControl1.PageCount - 1 downto 0 do begin Ts := UniPageControl1.Pages[I]; if Ts.Closable then Ts.Close; end; end; procedure TMainForm.UniToolButton6Click(Sender: TObject); begin UniSession.UrlRedirect(FHomeUrl); end; procedure TMainForm.TabSheetClose(Sender: TObject; var AllowClose: Boolean); var Ts : TUniTabSheet; Nd : TUniTreeNode; begin Ts := Sender as TUniTabSheet; Nd := Pointer(Ts.Tag); if Assigned(Nd) then begin Nd.Data := nil; if NavTree.Selected = Nd then NavTree.Selected := nil; end; end; procedure TMainForm.ThemeComboBoxChange(Sender: TObject); begin UniMainModule.Theme:=ThemeComboBox.Text; end; procedure TMainForm.AddtoFavorites1Click(Sender: TObject); var ANode : TUniTreeNode; begin ANode := NavTree.Selected; AddToSubMenu(ANode); WriteFavs; end; procedure TMainForm.AddToSubMenu(ANode: TUniTreeNode); var M : TUniMenuItem; begin if Assigned(ANode) then begin M:=TUniMenuItem.Create(Self); M.Caption:= ANode.Text; M.Tag := UniInteger(ANode); M.ImageIndex := ANode.ImageIndex; M.OnClick := Navigate1Click; Favorites1.Add(M); end; end; procedure TMainForm.ConstructNavigator; var RawS : RawByteString; S, S1, Path, SubS : string; sr: TSearchRec; Ls : TStringList; Txt : TextFile; I, iPos, index, groupindex, mainindex : Integer; Nd : TUniTreeNode; iconfile, groupIconFile, mainIconFile: string; begin Path := UniServerModule.StartPath + 'units\'; Ls := TStringList.Create; try if SysUtils.FindFirst(Path+'*.pas', faAnyFile, sr) = 0 then begin repeat if (sr.Attr and faDirectory) = 0 then begin AssignFile(Txt, Path + Sr.Name); Reset(Txt); ReadLn(Txt, RawS); CloseFile(Txt); S := DecodeCharSet(RawS, 'utf-8'); iPos := Pos('//', S); S := Trim(Copy(S, iPos + 2, MaxInt)); iPos := Pos('=', S); if iPos > 0 then begin S1 := Trim(Copy(S, 1, iPos - 1)); S := Trim(Copy(S, iPos+1, MaxInt)); Ls.Add(S + '=' + S1); FileNames.Values[S1] := ExtractFileNameNoExt(Sr.Name); end; end; until FindNext(sr) <> 0; FindClose(sr); end; Ls.Sorted := True; for I := 0 to Ls.Count -1 do begin S := Ls.Names[I]; SubS := Trim(Ls.ValueFromIndex[I]); if S = '' then // Main begin Nd := NavTree.Items.Add(nil, SubS); Nd.Data := UniTabSheet1; mainIconFile := Path+'Icons\main.ico'; if FileExists(mainIconFile) then begin mainindex := CreateImageIndex(mainIconFile); end else mainindex := -1; nd.ImageIndex := mainindex; UniTabSheet1.Caption := SubS; UniTabSheet1.Tag := NativeInt(Nd); UniTabSheet1.ImageIndex := mainindex; NavTree.Selected := Nd; end else begin Nd := NavTree.Items.FindNodeByCaption(S); if Nd = nil then begin Nd := NavTree.Items.Add(nil, S); groupIconFile := Path+'Icons\'+S+'.ico'; if FileExists(groupIconFile) then begin groupindex := CreateImageIndex(groupIconFile); nd.ImageIndex := groupindex; end else nd.ImageIndex := -1; end; iconfile := Path+'Icons\'+FileNames.Values[SubS] +'.ico'; if FileExists(iconfile) then index := CreateImageIndex(iconfile) else index := -1; Nd := NavTree.Items.Add(Nd, SubS); Nd.ImageIndex := index; end; end; finally Ls.Free; end; end; procedure TMainForm.Navigate1Click(Sender: TObject); var Nd : TUniTreeNode; begin Nd := Pointer((Sender as TUniMenuItem).Tag); if Assigned(Nd) then begin NavTree.Selected := Nd; NavTreeClick(Nd); end; end; procedure TMainForm.NavTreeCellContextClick(ANode: TUniTreeNode; X, Y: Integer); begin if ANode.Count = 0 then begin if Favorites1.Find(ANode.Text) = nil then begin AddtoFavorites1.Enabled := True; RemoveFromFavorites1.Enabled := False; end else begin AddtoFavorites1.Enabled := False; RemoveFromFavorites1.Enabled := True; end; UniPopupMenu1.Popup(X, Y); end; end; procedure TMainForm.NavTreeClick(Sender: TObject); var Nd : TUniTreeNode; Ts : TUniTabSheet; FrC : TUniFrameClass; Fr : TUniFrame; FClassName, Path: string; begin Path := UniServerModule.StartPath + 'units\'; Nd := NavTree.Selected; if Nd.Count = 0 then begin Ts := Nd.Data; if not Assigned(Ts) then begin Ts := TUniTabSheet.Create(Self); Ts.PageControl := UniPageControl1; Ts.Closable := True; Ts.OnClose := TabSheetClose; Ts.Tag := NativeInt(Nd); Ts.Caption := Nd.Text; Ts.ImageIndex := Nd.ImageIndex; FClassName := 'TUni' + FileNames.Values[Nd.Text]; FrC := TUniFrameClass(FindClass(FClassName)); Fr := FrC.Create(Self); Fr.Align := alClient; Fr.Parent := Ts; Nd.Data := Ts; end; UniPageControl1.ActivePage := Ts; end; end; procedure TMainForm.NavTreeLoaded(Sender: TObject); begin SearchEdit.SetFocus; end; procedure TMainForm.RefreshTime; begin UniStatusBar1.Panels[0].Text := FormatDateTime('dd/mm/yyyy hh:nn', Now); end; procedure TMainForm.RemoveFromFavorites1Click(Sender: TObject); var M : TUniMenuItem; begin M := Favorites1.Find(NavTree.Selected.Text); if Assigned(M) then begin M.Free; WriteFavs; end; end; initialization RegisterAppFormClass(TMainForm); end.
unit Aurelius.Sql.Commands; {$I Aurelius.inc} interface uses Generics.Collections, Aurelius.Sql.BaseTypes; type TDMLCommand = class abstract private FTable: TSQLTable; public property Table: TSQLTable read FTable write FTable; destructor Destroy; override; end; TSelectCommand = class(TDMLCommand) private FSelectFields: TObjectList<TSQLSelectField>; FJoins: TObjectList<TSQLJoin>; FWhereFields: TObjectList<TSQLWhereField>; FGroupByFields: TObjectList<TSQLField>; FOrderByFields: TObjectList<TSQLOrderField>; FWhereStatement: string; FSelectStatement: string; FGroupByStatement: string; FHavingStatement: string; FOrderByStatement: string; FFirstRow: integer; FMaxRows: integer; function GetLastAlias: string; function GetNextAlias: string; function GetHasLimits: boolean; function GetHasFirstRow: boolean; function GetHasMaxRows: boolean; function GetLastRow: integer; public property SelectFields: TObjectList<TSQLSelectField> read FSelectFields write FSelectFields; property SelectStatement: string read FSelectStatement write FSelectStatement; property Joins: TObjectList<TSQLJoin> read FJoins write FJoins; property WhereFields: TObjectList<TSQLWhereField> read FWhereFields write FWhereFields; property WhereStatement: string read FWhereStatement write FWhereStatement; property GroupByFields: TObjectList<TSQLField> read FGroupByFields write FGroupByFields; property GroupByStatement: string read FGroupByStatement write FGroupByStatement; property HavingStatement: string read FHavingStatement write FHavingStatement; property OrderByFields: TObjectList<TSQLOrderField> read FOrderByFields write FOrderByFields; property OrderByStatement: string read FOrderByStatement write FOrderByStatement; property LastAlias: string read GetLastAlias; property NextAlias: string read GetNextAlias; property FirstRow: integer read FFirstRow write FFirstRow; property MaxRows: integer read FMaxRows write FMaxRows default -1; property HasLimits: boolean read GetHasLimits; property HasFirstRow: boolean read GetHasFirstRow; property HasMaxRows: boolean read GetHasMaxRows; property LastRow: integer read GetLastRow; function GetAliasFromTable(OriginAlias, DestinyTable: string; FKFields: array of string): string; constructor Create; virtual; destructor Destroy; override; end; TInsertCommand = class(TDMLCommand) private FInsertFields: TObjectList<TSQLField>; public property InsertFields: TObjectList<TSQLField> read FInsertFields write FInsertFields; constructor Create; virtual; destructor Destroy; override; end; TUpdateCommand = class(TDMLCommand) private FUpdateFields: TObjectList<TSQLField>; FWhereFields: TObjectList<TSQLWhereField>; public property UpdateFields: TObjectList<TSQLField> read FUpdateFields write FUpdateFields; property WhereFields: TObjectList<TSQLWhereField> read FWhereFields write FWhereFields; constructor Create; virtual; destructor Destroy; override; end; TDeleteCommand = class(TDMLCommand) private FWhereFields: TObjectList<TSQLWhereField>; public property WhereFields: TObjectList<TSQLWhereField> read FWhereFields write FWhereFields; constructor Create; virtual; destructor Destroy; override; end; TGetNextSequenceValueCommand = class(TDMLCommand) private FSequenceName: string; FIncrement: integer; public property SequenceName: string read FSequenceName write FSequenceName; property Increment: integer read FIncrement write FIncrement; end; implementation uses Classes, Aurelius.Global.Utils, Aurelius.Sql.Exceptions; { TInsertCommand } constructor TInsertCommand.Create; begin FInsertFields := TObjectList<TSQLField>.Create; end; destructor TInsertCommand.Destroy; begin FInsertFields.Free; inherited; end; { TUpdateCommand } constructor TUpdateCommand.Create; begin FUpdateFields := TObjectList<TSQLField>.Create; FWhereFields := TObjectList<TSQLWhereField>.Create; end; destructor TUpdateCommand.Destroy; begin FUpdateFields.Free; FWhereFields.Free; inherited; end; { TDeleteCommand } constructor TDeleteCommand.Create; begin FWhereFields := TObjectList<TSQLWhereField>.Create; end; destructor TDeleteCommand.Destroy; begin FWhereFields.Free; inherited; end; { TSelectCommand } constructor TSelectCommand.Create; begin FSelectFields := TObjectList<TSQLSelectField>.Create; FJoins := TObjectList<TSQLJoin>.Create; FWhereFields := TObjectList<TSQLWhereField>.Create; FGroupByFields := TObjectList<TSQLField>.Create; FOrderByFields := TObjectList<TSQLOrderField>.Create; FMaxRows := -1; end; destructor TSelectCommand.Destroy; begin FSelectFields.Free; FJoins.Free; FWhereFields.Free; FGroupByFields.Free; FOrderByFields.Free; inherited; end; function TSelectCommand.GetAliasFromTable(OriginAlias, DestinyTable: string; FKFields: array of string): string; var I, J: Integer; FKAlias, PKTable: string; OrderedParamFields, OrderedJoinFields: TStringList; begin OrderedParamFields := TStringList.Create; OrderedJoinFields := TStringList.Create; try OrderedParamFields.Sorted := True; OrderedJoinFields.Sorted := True; for I := 0 to Length(FKFields) - 1 do OrderedParamFields.Add(FKFields[I]); for I := 0 to FJoins.Count - 1 do begin FKAlias := FJoins[I].Segments[0].FKField.Table.Alias; PKTable := FJoins[I].Segments[0].PKField.Table.Name; if (FKAlias = OriginAlias) and (PKTable = DestinyTable) then begin OrderedJoinFields.Clear; for J := 0 to FJoins[I].Segments.Count - 1 do OrderedJoinFields.Add(FJoins[I].Segments[J].FKField.Field); if OrderedJoinFields.Equals(OrderedParamFields) then Exit(FJoins[I].Segments[0].PKField.Table.Alias); end; end; raise ESQLInternalError.CreateFmt( 'No alias found for table "%s". Origin alias="%s", FKFields="%s"', [DestinyTable, OriginAlias, TUtils.ConcatString(FKFields)]); finally OrderedParamFields.Free; OrderedJoinFields.Free; end; end; function TSelectCommand.GetHasFirstRow: boolean; begin Result := FirstRow > 0; end; function TSelectCommand.GetHasLimits: boolean; begin Result := HasFirstRow or HasMaxRows; end; function TSelectCommand.GetHasMaxRows: boolean; begin Result := MaxRows > -1; end; function TSelectCommand.GetLastAlias: string; var I: Integer; Current: string; begin if FTable = nil then Result := '' else Result := FTable.Alias; for I := 0 to FJoins.Count - 1 do begin Current := FJoins[I].Segments[0].PKField.Table.Alias; if TUtils.AliasToInt(Current) > TUtils.AliasToInt(Result) then Result := Current; end; end; function TSelectCommand.GetLastRow: integer; begin Result := MaxInt - 1; if HasMaxRows then begin if HasFirstRow then Result := FirstRow + MaxRows - 1 else Result := MaxRows - 1; if Result < FirstRow - 1 then Result := FirstRow - 1; end; end; function TSelectCommand.GetNextAlias: string; begin Result := TUtils.IntToAlias(TUtils.AliasToInt(GetLastAlias) + 1); end; { TDMLCommand } destructor TDMLCommand.Destroy; begin FTable.Free; inherited; end; end.
unit HFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ADODB, ExtCtrls, ComCtrls, StdCtrls, EditAncestor, Menus; type TfrAncestor = class(TFrame) lvwItems: TListView; Panel1: TPanel; btnNew: TButton; btnEdit: TButton; btnDelete: TButton; pmpRightClick: TPopupMenu; Yeni1: TMenuItem; Degistir1: TMenuItem; Sil1: TMenuItem; lblTitel: TLabel; procedure lvwItemsDblClick(Sender: TObject); procedure lvwItemsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btnDeleteClick(Sender: TObject); procedure lvwItemsClick(Sender: TObject); private FForm: TfrmEditAncestor; FFTable: TADOTable; FTitel: String; procedure SetTitel(const Value: String); procedure LoadItems(Velden: array of string); public // Use this and other properties to set the owner form and table to use with new edit and delete property FTable: TADOTable read FFTable write FFTable; property EForm: TfrmEditAncestor read FForm write FForm; property Titel: String read FTitel write SetTitel; procedure addColumn(Name: STring; Size: Integer); procedure addAlignColumn(Name: STring; Size: Integer; alingment: TAlignment); //procedure LoadItems(Velden: Array of string); function editObject: Boolean; end; implementation {$R *.dfm} procedure TfrAncestor.lvwItemsDblClick(Sender: TObject); begin btnEdit.Click; end; procedure TfrAncestor.addColumn(Name: STring; Size: Integer); var column: TListColumn; begin lvwItems.Columns.BeginUpdate; column := lvwItems.Columns.Add; column.Caption := Name; column.Width := Size; lvwItems.Columns.EndUpdate; end; procedure TfrAncestor.addAlignColumn(Name: STring; Size: Integer; alingment: TAlignment); var column: TListColumn; begin lvwItems.Columns.BeginUpdate; column := lvwItems.Columns.Add; column.Caption := Name; column.Width := Size; column.Alignment := alingment; lvwItems.Columns.EndUpdate; end; procedure TfrAncestor.lvwItemsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin btnEdit.Enabled := Selected; btnDelete.Enabled := Selected; end; function TfrAncestor.editObject: Boolean; begin Result := False; try if EForm.ShowModal = mrOk then begin Result := True; end finally EForm.Free; end; end; procedure TfrAncestor.btnDeleteClick(Sender: TObject); begin FTable.Locate('ID', Integer(lvwItems.Selected.Data), []); FTable.DeleteRecords(arCurrent); TfrmEditAncestor(Self.Owner).loadDetails; end; procedure TfrAncestor.lvwItemsClick(Sender: TObject); begin btnEdit.Enabled := lvwItems.Selected <> nil; btnDelete.Enabled := lvwItems.Selected <> nil; end; procedure TfrAncestor.SetTitel(const Value: String); begin FTitel := Value; lblTitel.Caption := FTitel; end; procedure TfrAncestor.LoadItems(Velden: array of string); begin // FFTable.FieldByName('').AsVariant end; end.
unit Expedicao.Services.uExpedicaoFactory; interface uses Expedicao.Interfaces.uSeguradoraPersistencia, Expedicao.Services.uSeguradoraMock, Expedicao.Services.uCombustivelMock, Expedicao.Interfaces.uCombustivelPersistencia, Expedicao.Services.uInfracaoMock, Expedicao.Interfaces.uInfracaoPersistencia, Expedicao.Services.uRomaneioMock, Expedicao.Interfaces.uRomaneioPersistencia, Expedicao.Services.uVeiculoMock, Expedicao.Interfaces.uVeiculoPersistencia; type TTipoPersistencia = (tpMock, tpMySql, tpUnknown); TExpedicaoFactory = class public function ObterSeguradoraPersistencia(pTipoPersistencia: TTipoPersistencia) : ISeguradoraPersistencia; function ObterCombustivelPersistencia(pTipoPersistencia: TTipoPersistencia) : ICombustivelPersistencia; function ObterInfracaoPersistencia(pTipoPersistencia: TTipoPersistencia) : IInfracaoPersistencia; function ObterRomaneioPersistencia(pTipoPersistencia: TTipoPersistencia) : IRomaneioPersistencia; function ObterVeiculoPersistencia(pTipoPersistencia: TTipoPersistencia) : IVeiculoPersistencia; end; implementation uses SysUtils; { TExpedicaoFactory } function TExpedicaoFactory.ObterCombustivelPersistencia(pTipoPersistencia : TTipoPersistencia): ICombustivelPersistencia; begin case pTipoPersistencia of tpMock: Result := TCombustivelMock.Create; tpMySql: ; // Deverá devolver a instancia da classe que fará uso MySQL; tpUnknown: raise Exception.Create('Tipo de Persistência não implementado!'); end; end; function TExpedicaoFactory.ObterInfracaoPersistencia(pTipoPersistencia : TTipoPersistencia): IInfracaoPersistencia; begin case pTipoPersistencia of tpMock: Result := TInfracaoMock.Create; tpMySql: ; // Deverá devolver a instancia da classe que fará uso MySQL; tpUnknown: raise Exception.Create('Tipo de Persistência não implementado!'); end; end; function TExpedicaoFactory.ObterRomaneioPersistencia(pTipoPersistencia : TTipoPersistencia): IRomaneioPersistencia; begin case pTipoPersistencia of tpMock: Result := TRomaneioMock.Create; tpMySql: ; // Deverá devolver a instancia da classe que fará uso MySQL; tpUnknown: raise Exception.Create('Tipo de Persistência não implementado!'); end; end; function TExpedicaoFactory.ObterSeguradoraPersistencia(pTipoPersistencia : TTipoPersistencia): ISeguradoraPersistencia; begin case pTipoPersistencia of tpMock: Result := TSeguradoraMock.Create; tpMySql: ; // Deverá devolver a instancia da classe que fará uso MySQL; tpUnknown: raise Exception.Create('Tipo de Persistência não implementado!'); end; end; function TExpedicaoFactory.ObterVeiculoPersistencia(pTipoPersistencia : TTipoPersistencia): IVeiculoPersistencia; begin case pTipoPersistencia of tpMock: Result := TVeiculoMock.Create; tpMySql: ; // Deverá devolver a instancia da classe que fará uso MySQL; tpUnknown: raise Exception.Create('Tipo de Persistência não implementado!'); end; end; end.
unit UxlCanvas; interface uses Windows, UxlWinControl, UxlClasses; type TxlCanvas = class private FOwner: TxlWinControl; FForeColor: TColor; function OwnerHandle (): HWND; procedure SetBackColor (value: Tcolor); function GetBackColor (): TColor; public constructor Create (AOwner: TxlWinControl); destructor Destroy (); override; function Width(): cardinal; function Height(): cardinal; function XLow (): cardinal; function XHigh (): cardinal; function YLow (): cardinal; function YHigh (): cardinal; procedure Circle (o_center: TPoint; i_radius: cardinal); procedure Line (o_start, o_end: TPoint); property ForeColor: TColor read FForeColor write FForeColor; property BackColor: TColor read GetBackColor write SetBackColor; end; implementation uses UxlCommDlgs; constructor TxlCanvas.Create (AOwner: TxlWinControl); begin FOwner := AOwner; end; destructor TxlCanvas.Destroy (); begin inherited; end; function TxlCanvas.Width(): cardinal; var rc: TRect; begin GetClientRect (FOwner.Handle, rc); result := RectToPos(rc).width; end; function TxlCanvas.Height(): cardinal; var rc: TRect; begin GetClientRect (FOwner.Handle, rc); result := RectToPos(rc).height; end; function TxlCanvas.XLow (): cardinal; begin result := 0; end; function TxlCanvas.XHigh (): cardinal; begin result := Width - 1; end; function TxlCanvas.YLow (): cardinal; begin result := 0; end; function TxlCanvas.YHigh (): cardinal; begin result := Height - 1; end; //---------------------- function TxlCanvas.OwnerHandle (): HWND; begin if FOwner <> nil then result := FOwner.handle else result := 0; end; procedure TxlCanvas.SetBackColor (value: Tcolor); begin FOwner.Color := value; end; function TxlCanvas.GetBackColor (): TColor; begin result := FOwner.Color end; //---------------- procedure TxlCanvas.Line (o_start, o_end: TPoint); var h_dc: HDC; begin h_dc := GetDC (Ownerhandle); MoveToEx (h_dc, o_start.x, o_start.y, nil); LineTo (h_dc, o_end.X, o_end.Y); ReleaseDC (Ownerhandle, h_dc); end; procedure TxlCanvas.Circle (o_center: TPoint; i_radius: cardinal); var h_dc: HDC; h_pen: HBrush; o_rect: TRect; o_start: TPoint; begin with o_rect do begin Left := o_center.x - i_radius; Top := o_center.Y - i_radius; Right := o_center.x + i_radius; Bottom := o_center.Y + i_radius; end; o_start.x := o_center.x; o_start.y := o_rect.Top; h_dc := GetDC (Ownerhandle); h_pen := CreatePen (PS_Solid, 1, FForeColor); SelectObject (h_dc, h_pen); Arc (h_dc, o_rect.Left, o_rect.Top, o_rect.right, o_rect.bottom, o_start.x, o_start.Y, o_start.x, o_start.y); ReleaseDC (Ownerhandle, h_dc); DeleteObject (h_pen); end; end.
unit fbapitransaction; interface uses SysUtils, Classes, DB, IB, fbapidatabase, FbMessages; type TFbTransactionParams = array of byte; TDefaultEndAction = TARollback..TACommit; TIBDatabase = TFbApiDatabase; TFbApiTransaction = class(TComponent) private FTransaction: ITransaction; FParams: IB.TByteArray; FDefaultDatabase: TFbApiDatabase; FDatabases: TList; FSQLObjects : TList; FTPB : ITPB; // FTimer : TFPTimer; FDefaultAction : TDefaultEndAction; FTRParams : TStrings; FTRParamsChanged : Boolean; FInEndTransaction : boolean; FEndAction : TTransactionAction; FStreamedActive: Boolean; // FDefaultCompletion: TTransactionCompletion; IsParamsChanged: Boolean; FDefaultCompletion: TTransactionCompletion; FTransactionIntf: ITransaction; procedure EnsureNotInTransaction; procedure EndTransaction(Action: TTransactionAction; Force: Boolean); procedure SetDatabase(const Value: TFbApiDatabase); procedure SetParams(const Value: TByteArray); function GretInTransaction: Boolean; procedure SetDefaultCompletion(const Value: TTransactionCompletion); function CheckTransaction:Boolean; procedure CreateNewTransaction; procedure TRParamsChange(Sender: TObject); procedure TRParamsChanging(Sender: TObject); function GetDatabase(Index: Integer): TFbApiDatabase; function GetDatabaseCount: Integer; function GetInTransaction: Boolean; procedure SetActive(const Value: Boolean); procedure SetDefaultDatabase(const Value: TFbApiDatabase); procedure SetTRParams(const Value: TStrings); procedure Start; protected procedure Loaded; override; procedure Notification( AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent);override; destructor Destroy;override; procedure Commit; procedure CommitRetaining; procedure Rollback; procedure RollbackRetaining; procedure StartTransaction; procedure CheckInTransaction; procedure CheckNotInTransaction; function AddDatabase(db: TFbApiDatabase): Integer; function FindDatabase(db: TFbApiDatabase): Integer; function FindDefaultDatabase: TFbApiDatabase; function GetEndAction: TTransactionAction; procedure RemoveDatabase(Idx: Integer); procedure RemoveDatabases; procedure CheckDatabasesInList; property DatabaseCount: Integer read GetDatabaseCount; property Databases[Index: Integer]: TFbApiDatabase read GetDatabase; // property SQLObjectCount: Integer read GetSQLObjectCount; // property SQLObjects[Index: Integer]: TIBBase read GetSQLObject; property InTransaction: Boolean read GetInTransaction; property TransactionIntf: ITransaction read FTransactionIntf; property TPB: ITPB read FTPB; published property Active: Boolean read GetInTransaction write SetActive; property DefaultDatabase: TFbApiDatabase read FDefaultDatabase write SetDefaultDatabase; // property IdleTimer: Integer read GetIdleTimer write SetIdleTimer default 0; property DefaultAction: TDefaultEndAction read FDefaultAction write FDefaultAction default taCommit; property Params: TStrings read FTRParams write SetTRParams; // property OnIdleTimer: TNotifyEvent read FOnIdleTimer write FOnIdleTimer; // property BeforeTransactionEnd: TNotifyEvent read FBeforeTransactionEnd // write FBeforeTransactionEnd; // property AfterTransactionEnd: TNotifyEvent read FAfterTransactionEnd // write FAfterTransactionEnd; // property OnStartTransaction: TNotifyEvent read FOnStartTransaction // write FOnStartTransaction; // property AfterExecQuery: TNotifyEvent read FAfterExecQuery // write FAfterExecQuery; // property AfterEdit: TNotifyEvent read FAfterEdit write FAfterEdit; // property AfterDelete: TNotifyEvent read FAfterDelete write FAfterDelete; // property AfterInsert: TNotifyEvent read FAfterInsert write FAfterInsert; // property AfterPost: TNotifyEvent read FAfterPost write FAfterPost; { procedure Start; procedure Commit; procedure Rollback; property Params:TByteArray read FParams write SetParams; property Database:TFbApiDatabase read FDefaultDatabase write SetDatabase; property InTransaction: Boolean read GretInTransaction; property TransactionIntf:ITransaction read FTransaction ; property DefaultCompletion: TTransactionCompletion read FDefaultCompletion write SetDefaultCompletion;} end; implementation { TFbTransaction } function TFbApiTransaction.AddDatabase(db: TFbApiDatabase): Integer; var i: Integer; NilFound: Boolean; begin EnsureNotInTransaction; CheckNotInTransaction; FTransactionIntf := nil; i := FindDatabase(db); if i <> -1 then begin result := i; exit; end; NilFound := False; i := 0; while (not NilFound) and (i < FDatabases.Count) do begin NilFound := (FDatabases[i] = nil); if (not NilFound) then Inc(i); end; if (NilFound) then begin FDatabases[i] := db; result := i; end else begin result := FDatabases.Count; FDatabases.Add(db); end; end; procedure TFbApiTransaction.CheckDatabasesInList; begin if GetDatabaseCount = 0 then IBError(ibxeNoDatabasesInTransaction, [nil]); end; procedure TFbApiTransaction.CheckInTransaction; begin if FStreamedActive and (not InTransaction) then Loaded; if (TransactionIntf = nil) then IBError(ibxeNotInTransaction, [nil]); end; procedure TFbApiTransaction.CheckNotInTransaction; begin if (TransactionIntf <> nil) and TransactionIntf.InTransaction then IBError(ibxeInTransaction, [nil]); end; function TFbApiTransaction.CheckTransaction: Boolean; begin if not Assigned(FTransaction) then raise Exception.Create('Transaction not started'); Result := true; end; procedure TFbApiTransaction.Commit; begin EndTransaction(TACommit, False); end; procedure TFbApiTransaction.CommitRetaining; begin EndTransaction(TACommitRetaining, False); end; constructor TFbApiTransaction.Create; var I: Integer; begin inherited Create(AOwner); FDatabases := TList.Create; FSQLObjects := TList.Create; FTPB := nil; FTRParams := TStringList.Create; FTRParamsChanged := True; TStringList(FTRParams).OnChange := TRParamsChange; TStringList(FTRParams).OnChanging := TRParamsChanging; FDefaultAction := taCommit; IsParamsChanged := True; SetLength(FParams,3); for I := 0 to 2 do FParams[i] := TR_READ_CONCURENCY_PARAMS[i]; FDefaultCompletion := TACommit; FTransaction := nil; end; procedure TFbApiTransaction.CreateNewTransaction; begin FTransaction := nil; FTransaction := FDefaultDatabase.Attachment.StartTransaction(FParams,FDefaultCompletion); end; destructor TFbApiTransaction.Destroy; var i: Integer; begin if InTransaction then EndTransaction(FDefaultAction, True); { for i := 0 to FSQLObjects.Count - 1 do if FSQLObjects[i] <> nil then SQLObjects[i].DoTransactionFree; RemoveSQLObjects;} RemoveDatabases; FTPB := nil; FTRParams.Free; FSQLObjects.Free; FDatabases.Free; inherited Destroy; end; procedure TFbApiTransaction.EndTransaction(Action: TTransactionAction; Force: Boolean); var i: Integer; begin CheckInTransaction; if FInEndTransaction then Exit; FInEndTransaction := true; FEndAction := Action; try case Action of TARollback, TACommit: begin try //DoBeforeTransactionEnd; except on E: EIBInterBaseError do begin if not Force then raise; end; end; for i := 0 to FSQLObjects.Count - 1 do if FSQLObjects[i] <> nil then try //SQLObjects[i].DoBeforeTransactionEnd(Action); except on E: EIBInterBaseError do begin if not Force then raise; end; end; if InTransaction then begin if (Action = TARollback) then FTransactionIntf.Rollback(Force) else try FTransactionIntf.Commit; except on E: EIBInterBaseError do begin if Force then FTransactionIntf.Rollback(Force) else raise; end; end; for i := 0 to FSQLObjects.Count - 1 do if FSQLObjects[i] <> nil then try //SQLObjects[i].DoAfterTransactionEnd; except on E: EIBInterBaseError do begin if not Force then raise; end; end; try //DoAfterTransactionEnd; except on E: EIBInterBaseError do begin if not Force then raise; end; end; end; end; TACommitRetaining: FTransactionIntf.CommitRetaining; TARollbackRetaining: FTransactionIntf.RollbackRetaining; end; { if not (csDesigning in ComponentState) then begin case Action of TACommit: MonitorHook.TRCommit(Self); TARollback: MonitorHook.TRRollback(Self); TACommitRetaining: MonitorHook.TRCommitRetaining(Self); TARollbackRetaining: MonitorHook.TRRollbackRetaining(Self); end; end;} finally FInEndTransaction := false end; end; procedure TFbApiTransaction.EnsureNotInTransaction; begin if csDesigning in ComponentState then begin if TransactionIntf <> nil then Rollback; end; end; function TFbApiTransaction.FindDatabase(db: TFbApiDatabase): Integer; var i: Integer; begin result := -1; for i := 0 to FDatabases.Count - 1 do if db = TIBDatabase(FDatabases[i]) then begin result := i; break; end; end; function TFbApiTransaction.FindDefaultDatabase: TFbApiDatabase; var i: Integer; begin result := FDefaultDatabase; if result = nil then begin for i := 0 to FDatabases.Count - 1 do if (TFbApiDatabase(FDatabases[i]) <> nil) and (TFbApiDatabase(FDatabases[i]).DefaultTransaction = self) then begin result := TIBDatabase(FDatabases[i]); break; end; end; end; function TFbApiTransaction.GetDatabase(Index: Integer): TFbApiDatabase; begin result := FDatabases[Index]; end; function TFbApiTransaction.GetDatabaseCount: Integer; var i, Cnt: Integer; begin result := 0; Cnt := FDatabases.Count - 1; for i := 0 to Cnt do if FDatabases[i] <> nil then Inc(result); end; function TFbApiTransaction.GetEndAction: TTransactionAction; begin if FInEndTransaction then Result := FEndAction else IBError(ibxeIB60feature, [nil]) end; function TFbApiTransaction.GetInTransaction: Boolean; begin result := (TransactionIntf <> nil) and TransactionIntf.InTransaction; end; function TFbApiTransaction.GretInTransaction: Boolean; begin Result := Assigned(FTransaction) and FTransaction.InTransaction; end; procedure TFbApiTransaction.Loaded; begin inherited Loaded; end; procedure TFbApiTransaction.Notification(AComponent: TComponent; Operation: TOperation); var i: Integer; begin inherited Notification( AComponent, Operation); if (Operation = opRemove) and (AComponent = FDefaultDatabase) then begin i := FindDatabase(FDefaultDatabase); if (i <> -1) then RemoveDatabase(i); FDefaultDatabase := nil; end; end; procedure TFbApiTransaction.RemoveDatabase(Idx: Integer); var DB: TIBDatabase; begin if ((Idx >= 0) and (FDatabases[Idx] <> nil)) then begin EnsureNotInTransaction; CheckNotInTransaction; FTransactionIntf := nil; DB := Databases[Idx]; FDatabases[Idx] := nil; DB.RemoveTransaction(DB.FindTransaction(Self)); if DB = FDefaultDatabase then FDefaultDatabase := nil; end; end; procedure TFbApiTransaction.RemoveDatabases; var i: Integer; begin EnsureNotInTransaction; CheckNotInTransaction; FTransactionIntf := nil; for i := 0 to FDatabases.Count - 1 do if FDatabases[i] <> nil then RemoveDatabase(i); end; procedure TFbApiTransaction.Rollback; begin EndTransaction(TARollback, False); end; procedure TFbApiTransaction.RollbackRetaining; begin EndTransaction(TARollbackRetaining, False); end; procedure TFbApiTransaction.SetActive(const Value: Boolean); begin if csReading in ComponentState then FStreamedActive := Value else if Value and not InTransaction then StartTransaction else if not Value and InTransaction then Rollback; end; procedure TFbApiTransaction.SetDatabase(const Value: TFbApiDatabase); var i: integer; begin if (FDefaultDatabase <> nil) and (FDefaultDatabase <> Value) then begin i := FDefaultDatabase.FindTransaction(self); if (i <> -1) then FDefaultDatabase.RemoveTransaction(i); end; if (Value <> nil) and (FDefaultDatabase <> Value) then begin Value.AddTransaction(Self); AddDatabase(Value); {for i := 0 to FSQLObjects.Count - 1 do if (FSQLObjects[i] <> nil) and (TIBBase(FSQLObjects[i]).Database = nil) then SetObjectProp(TIBBase(FSQLObjects[i]).Owner, 'Database', Value);} end; FDefaultDatabase := Value; end; procedure TFbApiTransaction.SetDefaultCompletion(const Value: TTransactionCompletion); begin FDefaultCompletion := Value; end; procedure TFbApiTransaction.SetDefaultDatabase(const Value: TFbApiDatabase); begin FDefaultDatabase := Value; end; procedure TFbApiTransaction.SetParams(const Value: TByteArray); begin if FParams <> Value then begin FParams := Value; IsParamsChanged := True; end; end; procedure TFbApiTransaction.SetTRParams(const Value: TStrings); begin FTRParams.Assign(Value); end; procedure TFbApiTransaction.Start; begin // if not Assigned(FTransaction) then // FTransaction := TFB30Transaction.Create(FDatabase.FirebirdApi,[FDatabase.Attachment],FParams,FDefaultCompletion); // if Assigned(FTransaction) and not FTransaction.InTransaction then // FTransaction.Start(FDefaultCompletion) // else // fTransaction := FDatabase.Attachment. if Assigned(FTransaction) then begin if not FTransaction.InTransaction then if IsParamsChanged then createNewTransaction else FTransaction.Start(FDefaultCompletion) else raise Exception.Create('Transaction is active'); end else createNewTransaction // FTransaction := FDatabase.Attachment.StartTransaction(FParams,FDefaultCompletion); end; procedure TFbApiTransaction.StartTransaction; var i: Integer; Attachments: array of IAttachment; ValidDatabaseCount: integer; begin CheckNotInTransaction; CheckDatabasesInList; if TransactionIntf <> nil then TransactionIntf.Start(DefaultAction) else begin for i := 0 to FDatabases.Count - 1 do if FDatabases[i] <> nil then begin with TIBDatabase(FDatabases[i]) do if not Connected then if StreamedConnected then begin Open; StreamedConnected := False; end else IBError(ibxeDatabaseClosed, [nil]); end; if FTRParamsChanged then begin FTRParamsChanged := False; FTPB := GenerateTPB(Databases[0].FirebirdAPI,FTRParams); end; ValidDatabaseCount := 0; for i := 0 to DatabaseCount - 1 do if Databases[i] <> nil then Inc(ValidDatabaseCount); if ValidDatabaseCount = 1 then FTransactionIntf := Databases[0].Attachment.StartTransaction(FTPB,DefaultAction) else begin SetLength(Attachments,ValidDatabaseCount); for i := 0 to DatabaseCount - 1 do if Databases[i] <> nil then Attachments[i] := Databases[i].Attachment; FTransactionIntf := Databases[0].FirebirdAPI.StartTransaction(Attachments,FTPB,DefaultAction); end; end; // if not (csDesigning in ComponentState) then // MonitorHook.TRStart(Self); // DoOnStartTransaction; end; procedure TFbApiTransaction.TRParamsChange(Sender: TObject); begin FTRParamsChanged := True; end; procedure TFbApiTransaction.TRParamsChanging(Sender: TObject); begin EnsureNotInTransaction; CheckNotInTransaction; FTransactionIntf := nil; end; end.
unit VSEForms; interface uses Windows, Messages, AvL, avlUtils, VSECore, VSEOpenGLExt, VSEGUI, VSEFormManager; type TOnMessageBox = procedure(Sender: TObject; BtnNum: Integer) of object; //MessageBox button click handler; BtnNum: bumber of pressed button TMessageBox = class(TAlignedForm) //MessageBox form private FHandler: TOnMessageBox; procedure Click(Btn: PBtn); public constructor Create(const Caption, Prompt: string; const Buttons: array of string; Handler: TOnMessageBox = nil); //Creates MessageBox; Caption: Form caption, Prompt: message text, Buttons: buttons' captions, Handler: button click handler function KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; override; end; TOptionsForm = class(TAlignedForm) protected FLResolution, FLRefreshRate, FLColorDepth, FLResolutionCap, FLRefreshRateCap, FLColorDepthCap, FCFullscreen, FCVSync, FCurrentResolution, FCurrentRefreshRate, FColorDepth, FBOK, FBCancel: Integer; FResolutions: TResolutions; FNeedRestart: Boolean; FRestartMessage, FRestartYes, FRestartNo: string; procedure DrawForm(State: TBtnState); override; procedure ResClick(Btn: PBtn); procedure RefrClick(Btn: PBtn); procedure DepthClick(Btn: PBtn); procedure OKClick(Btn: PBtn); dynamic; procedure CancelClick(Btn: PBtn); procedure RestartClick(Sender: TObject; BtnNum: Integer); public constructor Create(Width, Height: Integer); destructor Destroy; override; function KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; override; end; {$IFNDEF FORMS_NO_BINDMAN} TBindManCfgForm=class(TAlignedForm) // Keys configuration form private FLabels, FButtons: array of Integer; FPageLabel, FPage, FPages, FActive: Integer; procedure ChangePage(Btn: PBtn); procedure KeyBtnClick(Btn: PBtn); procedure CloseClick(Btn: PBtn); procedure DefaultClick(Btn: PBtn); procedure SetKey(Key: Integer); public constructor Create(Width, Height: Integer; const DefaultCapt, CloseCapt: string); destructor Destroy; override; function MouseEvent(Button: Integer; Event: TMouseEvents; Cursor: TPoint): Boolean; override; function KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; override; procedure Refresh; end; {$ENDIF} TTextView = class(TAlignedForm) protected FCurPage, FLines, FPages, FLPage: Integer; FText: TStringList; procedure DrawForm(State: TBtnState); override; procedure ChangePage(Btn: PBtn); procedure Close(Btn: PBtn); public constructor Create(Width, Height: Integer; const Caption, CloseCaption: string; Text: TStringList); destructor Destroy; override; function KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; override; end; procedure ShowMessage(const Caption, Prompt: string; const Buttons: array of string; Handler: TOnMessageBox = nil; const Parent: string = ''); //Shows Message Box; Parent: parent form, Caption: Form caption, Prompt: message text, Buttons: buttons' captions, Handler: button click handler implementation uses VSERender2D{$IFNDEF FORMS_NO_BINDMAN}, VSEBindMan{$ENDIF}; { TMessageBox } constructor TMessageBox.Create(const Caption, Prompt: string; const Buttons: array of string; Handler: TOnMessageBox); const BtnWidth = 75; WndHeight = 90; var i, WndWidth: Integer; Lbl: TLbl; Btn: TBtn; begin WndWidth := Min(Max(Render2D.TextWidth(GUIFont, Prompt) + 25, Length(Buttons) * (BtnWidth + 10) + 10), Render2D.VSWidth); inherited Create(0, 0, WndWidth, WndHeight); Alignment := [faCenter, faMiddle]; FCaption := Caption; FHandler := Handler; with Lbl do begin Align := laCenter; Color := 0; X := 10; Y := 30; Width := WndWidth - 20; Caption := Prompt; end; AddLabel(Lbl); WndWidth := Max(0, WndWidth - Length(Buttons) * BtnWidth - High(Buttons) * 10) div 2; with Btn do begin Type_ := btPush; Y := 55; Width := BtnWidth; Height := 25; OnClick := Click; Enabled := true; for i := 0 to High(Buttons) do begin X := WndWidth + i * (BtnWidth + 10); Tag := i; Caption := Buttons[i]; AddButton(Btn); end; end; end; procedure TMessageBox.Click(Btn: PBtn); begin if Assigned(FHandler) then FHandler(Self, Btn.Tag); Close; end; function TMessageBox.KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; const Buttons: array[Boolean] of Integer = (0, -1); begin if (Key in [VK_ESCAPE, VK_RETURN]) and (Event = keUp) then begin if Assigned(FHandler) then FHandler(Self, Buttons[Key = VK_ESCAPE]); Close; Result := true; end else Result := inherited KeyEvent(Key, Event); end; {TOptionsForm} constructor TOptionsForm.Create(Width, Height: Integer); var Btn: TBtn; Lbl: TLbl; i: Integer; begin inherited Create(0, 0, Width, Height); Alignment := [faCenter, faMiddle]; FCaption := 'Options'; FRestartMessage := 'Selected settings requires restarting of the game. Restart now?'; FRestartYes := 'Yes'; FRestartNo := 'No'; FResolutions := gleGetResolutions; FLResolution := CreateSelect(Self, 10, 60, 190, 20, ResClick, '-', '+'); FLRefreshRate := CreateSelect(Self, 10, 110, 190, 20, RefrClick, '-', '+'); FLColorDepth := CreateSelect(Self, 10, 160, 190, 20, DepthClick, '-', '+'); with Btn do begin Enabled := true; X := 10; Width := 190; Tag := 0; Y := 200; Height := 20; Type_ := btCheck; OnClick := nil; Caption := 'Fullscreen'; Checked := Core.Fullscreen; FCFullscreen := AddButton(Btn); Y := 230; Caption := 'V. Sync'; Checked := Core.VSync; FCVSync := AddButton(Btn); X := FWidth - 190; Y := FHeight - 35; Width := 85; Height := 25; Type_ := btPush; Caption := 'OK'; OnClick := OKClick; FBOK := AddButton(Btn); X := X + Width + 10; Caption := 'Cancel'; OnClick := CancelClick; FBCancel := AddButton(Btn); end; with Lbl do begin Align := laCenter; Color := 0; X := 10; Y := 38; Width := 190; Caption := 'Resolution'; FLResolutionCap := AddLabel(Lbl); Y := 88; Caption := 'Refresh rate'; FLRefreshRateCap := AddLabel(Lbl); Y := 138; Caption := 'Color depth'; FLColorDepthCap := AddLabel(Lbl); end; FNeedRestart := false; FColorDepth := Core.ColorDepth; FCurrentResolution := -1; for i := 0 to High(FResolutions) do if (FResolutions[i].Width = Core.ResolutionX) and (FResolutions[i].Height = Core.ResolutionY) then FCurrentResolution := i; if FCurrentResolution = -1 then begin FCurrentResolution := Length(FResolutions); SetLength(FResolutions, FCurrentResolution + 1); with FResolutions[FCurrentResolution] do begin Width := Core.ResolutionX; Height := Core.ResolutionY; SetLength(RefreshRates, 1); RefreshRates[0] := Core.RefreshRate; end; end; FCurrentRefreshRate := -1; for i := 0 to High(FResolutions[FCurrentResolution].RefreshRates) do if FResolutions[FCurrentResolution].RefreshRates[i] = Core.RefreshRate then FCurrentRefreshRate := i; if FCurrentRefreshRate = -1 then begin FCurrentRefreshRate := Length(FResolutions[FCurrentResolution].RefreshRates); SetLength(FResolutions[FCurrentResolution].RefreshRates, FCurrentRefreshRate + 1); FResolutions[FCurrentResolution].RefreshRates[FCurrentRefreshRate] := Core.RefreshRate; end; end; destructor TOptionsForm.Destroy; begin Finalize(FResolutions); inherited Destroy; end; function TOptionsForm.KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; begin if (Key in [VK_ESCAPE, VK_RETURN]) and (Event = keUp) then begin if Key = VK_RETURN then OKClick(nil) else CancelClick(nil); Result := true; end else Result := inherited KeyEvent(Key, Event); end; procedure TOptionsForm.DrawForm(State: TBtnState); begin Lbl[FLResolution].Caption := Format('%dx%d', [FResolutions[FCurrentResolution].Width, FResolutions[FCurrentResolution].Height]); Lbl[FLRefreshRate].Caption := IntToStr(FResolutions[FCurrentResolution].RefreshRates[FCurrentRefreshRate]); Lbl[FLColorDepth].Caption := IntToStr(FColorDepth); inherited; end; procedure TOptionsForm.ResClick(Btn: PBtn); begin FCurrentResolution := Max(0, Min(FCurrentResolution + Btn.Tag, High(FResolutions))); FCurrentRefreshRate := 0; end; procedure TOptionsForm.RefrClick(Btn: PBtn); begin FCurrentRefreshRate := Max(0, Min(FCurrentRefreshRate + Btn.Tag, High(FResolutions[FCurrentResolution].RefreshRates))); end; procedure TOptionsForm.DepthClick(Btn: PBtn); const Depth: array[-1..1] of Integer = (16, 0, 32); begin FColorDepth := Depth[Btn.Tag]; end; procedure TOptionsForm.OKClick(Btn: PBtn); begin FNeedRestart := FNeedRestart or (Core.ColorDepth <> FColorDepth); with FResolutions[FCurrentResolution] do if (Core.ResolutionX <> Width) or (Core.ResolutionY <> Height) or (Core.RefreshRate <> RefreshRates[FCurrentRefreshRate]) then Core.SetResolution(Width, Height, RefreshRates[FCurrentRefreshRate], Button[FCFullscreen].Checked, true) else Core.Fullscreen := Button[FCFullscreen].Checked; Core.VSync := Button[FCVSync].Checked; Core.ColorDepth := FColorDepth; if FNeedRestart then ShowMessage(Caption, FRestartMessage, [FRestartYes, FRestartNo], RestartClick, Name) else Close; FNeedRestart := false; end; procedure TOptionsForm.CancelClick(Btn: PBtn); begin FNeedRestart := false; Close; end; procedure TOptionsForm.RestartClick(Sender: TObject; BtnNum: Integer); begin if BtnNum = 0 then Core.StopEngine(StopNeedRestart); Close; end; { TBindManCfgForm } {$IFNDEF FORMS_NO_BINDMAN} const PageLabel = '%d/%d'; constructor TBindManCfgForm.Create(Width, Height: Integer; const DefaultCapt, CloseCapt: string); const BHeight = 25; var Btn: TBtn; Lbl: TLbl; i: Integer; begin inherited Create(0, 0, Width, Height); Alignment := [faCenter, faMiddle]; Caption := 'Controls'; FActive := -1; SetLength(FLabels, Min(Length(BindMan.Bindings), (Height - 20 - Render2D.TextHeight(Font)) div (BHeight + 10))); SetLength(FButtons, Length(FLabels)); FPages := High(BindMan.Bindings) div Max(Length(FLabels), 1); with Btn do begin Type_ := btPush; X := 2*FWidth div 3; Width := FWidth - X - 10; Height := BHeight; OnClick := KeyBtnClick; Enabled := true; end; with Lbl do begin X := 10; Width := Btn.X - 20; Align := laLeft; Color := 0; end; for i := 0 to High(FLabels) do begin with Btn do begin Y := 20 + Render2D.TextHeight(Font) + i * (BHeight + 10); Tag := i; end; Lbl.Y := 25 + Render2D.TextHeight(Font) + i * (BHeight + 10); FButtons[i] := AddButton(Btn); FLabels[i] := AddLabel(Lbl); end; Refresh; if FPages > 0 then begin FPageLabel := CreateSelect(Self, 10, Height - 40, Min(Width div 2, Width - 280), 30, ChangePage, '<', '>'); Self.Lbl[FPageLabel]^.Caption := Format(PageLabel, [FPage + 1, FPages + 1]); end; with Btn do begin Width := 120; Y := FHeight - 40; X := FWidth - 260; Caption := DefaultCapt; OnClick := DefaultClick; AddButton(Btn); X := FWidth - 130; Caption := CloseCapt; OnClick := CloseClick; AddButton(Btn); end; end; procedure TBindManCfgForm.ChangePage(Btn: PBtn); begin FPage := Min(FPages, Max(0, FPage + Btn^.Tag)); Lbl[FPageLabel].Caption := Format(PageLabel, [FPage + 1, FPages + 1]); Refresh; end; procedure TBindManCfgForm.Refresh; var i: Integer; begin for i := 0 to High(FLabels) do begin if FPage * Length(FLabels) + i > High(BindMan.Bindings) then begin Lbl[FLabels[i]]^.Caption := ''; with Button[FButtons[i]]^ do begin Caption := ''; Enabled := false; end; Continue; end; Lbl[FLabels[i]]^.Caption := BindMan.Bindings[FPage * Length(FLabels) + i].Description; with Button[FButtons[i]]^ do begin Caption := KeyToStr(BindMan.Bindings[FPage * Length(FLabels) + i].Key); Enabled := true; end; end; end; procedure TBindManCfgForm.KeyBtnClick(Btn: PBtn); begin FActive := FPage * Length(FLabels) + Btn^.Tag; Btn^.Caption := '???'; end; function TBindManCfgForm.MouseEvent(Button: Integer; Event: TMouseEvents; Cursor: TPoint): Boolean; begin Result := false; if FActive > -1 then begin if not (Event in [meDown, meWheel]) then Exit; if Event = meWheel then begin if Button > 0 then SetKey(VK_MWHEELUP) else SetKey(VK_MWHEELDOWN); end else SetKey(MBtnMap[Button]); Result := true; end else Result := inherited MouseEvent(Button, Event, Cursor); end; function TBindManCfgForm.KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; begin Result := false; if FActive > -1 then begin if Event <> keUp then Exit; if Key = VK_ESCAPE then begin FActive := -1; Refresh; end else if Key = VK_BACK then SetKey(0) else SetKey(Key); Result := true; end else begin if (Event = keUp) and (Key = VK_ESCAPE) then begin CloseClick(nil); Result := true; end else Result := inherited KeyEvent(Key, Event); end; end; procedure TBindManCfgForm.CloseClick(Btn: PBtn); begin BindMan.SaveBindings; Close; end; destructor TBindManCfgForm.Destroy; begin Finalize(FLabels); Finalize(FButtons); inherited Destroy; end; procedure TBindManCfgForm.DefaultClick(Btn: PBtn); begin Settings.EraseSection(SSectionBindings); BindMan.ResetKeys; Refresh; end; procedure TBindManCfgForm.SetKey(Key: Integer); var i: Integer; begin if Key in [VK_SNAPSHOT] then Exit; for i := 0 to High(BindMan.Bindings) do if (i <> FActive) and (BindMan.Bindings[i].Key = Key) then BindMan.Bindings[i].Key := BindMan.Bindings[FActive].Key; BindMan.Bindings[FActive].Key := Key; FActive := -1; Refresh; end; {$ENDIF} { TTextView } constructor TTextView.Create(Width, Height: Integer; const Caption, CloseCaption: string; Text: TStringList); var Line: Integer; Src, Dst: string; Btn: TBtn; begin inherited Create(0, 0, Width, Height); Alignment := [faCenter, faMiddle]; FCaption := Caption; FText := Text; FLines := (Height - 70) div 16; Line := 0; while Line < FText.Count do begin Src := {$IFNDEF FORMS_NO_BINDMAN}ProcessKeyTags(FText[Line]){$ELSE}FText[Line]{$ENDIF}; Dst := ''; while (Src <> '') and (Render2D.TextWidth(Font, Src) > Width - 20) do begin Dst := Src[Length(Src)] + Dst; Delete(Src, Length(Src), 1); end; FText[Line] := Src; if Dst <> '' then FText.Insert(Line + 1, Dst); Inc(Line); end; FPages := (FText.Count - 1) div FLines; FCurPage := 0; with Btn do begin Type_ := btPush; X := FWidth - 95; Y := FHeight - 35; Width := 85; Height := 25; Enabled := true; Caption := CloseCaption; OnClick := Close; AddButton(Btn); end; if FPages > 0 then FLPage := CreateSelect(Self, 10, Height - 35, Min(150, Width - 115), 25, ChangePage, '<', '>'); end; destructor TTextView.Destroy; begin FAN(FText); inherited Destroy; end; function TTextView.KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; var Btn: TBtn; begin Result := true; if Event = keDown then case Key of VK_LEFT: begin Btn.Tag := -1; ChangePage(@Btn); end; VK_RIGHT: begin Btn.Tag := 1; ChangePage(@Btn); end; else Result := inherited KeyEvent(Key, Event); end else if Key = VK_ESCAPE then Close(nil) else Result := inherited KeyEvent(Key, Event); end; procedure TTextView.DrawForm(State: TBtnState); var i, Left: Integer; S: string; begin if FPages > 0 then Lbl[FLPage].Caption := Format('%d/%d', [FCurPage + 1, FPages + 1]); inherited; gleColor(clText); for i := 0 to FLines - 1 do if FLines * FCurPage + i < FText.Count then begin S := FText[FLines * FCurPage + i]; Left := 10; if (S <> '') and (S[1] = #9) then begin S := Copy(S, 2, MaxInt); Inc(Left, (Width - Render2D.TextWidth(Font, S) - 20) div 2); end; Render2D.TextOut(Font, Left, 35 + 16 * i, S); end; end; procedure TTextView.ChangePage(Btn: PBtn); begin FCurPage := Max(0, Min(FCurPage + Btn.Tag, FPages)); end; procedure TTextView.Close(Btn: PBtn); begin inherited Close; end; { Functions } procedure ShowMessage(const Caption, Prompt: string; const Buttons: array of string; Handler: TOnMessageBox = nil; const Parent: string = ''); begin if not Assigned(FormManager.FormsSet) then Exit; FormManager.Show(FormManager.FormsSet.AddForm('MessageBox:' + Prompt, TMessageBox.Create(Caption, Prompt, Buttons, Handler), Parent).Name); end; end.
unit uData; interface uses SysUtils, Classes, xmldom, msxmldom, XMLDoc, Graphics, SQLite3, SQLiteTable3, XMLIntf; type Tdm = class(TDataModule) xmlDoc: TXMLDocument; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } fDataFile, sqliteFile: string; sql: TStringList; procedure createTableUser(); procedure createTableSavePoints(); procedure createTableParams(); procedure dropTable(const tableName: string); procedure loadUserFromFile(fl: string); public { Public declarations } sqlite : TSQLiteDatabase; property DataFile: string read fDataFile; procedure SaveParam(const paramName, paramValue: string); function LoadParam(const paramName: string): string; end; var dm: Tdm; implementation uses uOGE, uUser, uGlobals, Windows; {$R *.dfm} { Tdm } //{$DEFINE TEST} procedure Tdm.createTableParams; begin if sqlite.TableExists('PARAMS') then exit; sql.Clear; sql.Add('CREATE TABLE PARAMS'); sql.Add('(ID INTEGER PRIMARY KEY AUTOINCREMENT,'); sql.Add('KEY_FIELD TEXT,'); sql.Add('VALUE_FIELD TEXT)'); sqlite.ExecSQL(ansistring(sql.Text)); end; procedure Tdm.createTableSavePoints; begin if sqlite.TableExists('SAVEPOINT') then exit; sql.Clear; sql.Add('CREATE TABLE SAVEPOINT'); sql.Add('(ID INTEGER PRIMARY KEY AUTOINCREMENT,'); sql.Add('US_ID INTEGER,'); sql.Add('WINDOW TEXT,'); sql.Add('KEY_FIELD TEXT,'); sql.Add('VALUE_FIELD TEXT)'); sqlite.ExecSQL(ansistring(sql.Text)); sql.Clear; sql.Add('CREATE INDEX US_ID_INDEX ON [SAVEPOINT] (US_ID)'); sqlite.ExecSQL(ansistring(sql.Text)); end; procedure Tdm.createTableUser; var defaultUser: TUser; begin if sqlite.TableExists('USER') then exit; sql.Clear; sql.Add('CREATE TABLE USER '); sql.Add('(ID INTEGER PRIMARY KEY AUTOINCREMENT,'); sql.Add('UT_ID INTEGER,'); sql.Add('FIO TEXT,'); sql.Add('PASSWORD TEXT)'); sqlite.ExecSQL(ansiString(sql.Text)); defaultUser.ut_id := 1; defaultUser.fio := 'Administrator'; defaultUser.password := 'saidov1986'; sql.Clear; sql.Add('INSERT INTO USER(UT_ID, FIO, PASSWORD)'); sql.Add(format('VALUES(%d, "%s", "%s")', [defaultUser.ut_id, defaultUser.fio, defaultUser.password])); sqlite.ExecSQL(ansiString(sql.Text)); if FileExists('usr.sql') then loadUserFromFile('usr.sql'); end; procedure Tdm.dropTable(const tableName: string); begin sql.Clear; sql.Add('DROP TABLE ' + tablename); sqlite.ExecSQL(ansiString(sql.Text)); end; procedure Tdm.DataModuleCreate(Sender: TObject); var appData: string; begin {$IFDEF TEST} fDataFile := exePath + 'OGE.dat'; sqliteFile := exePath + 'sqlite.dat'; {$ELSE} appData := GetEnvironmentVariable('LocalAppData'); fDataFile := appData + '\OGE\' + 'OGE.dat'; sqliteFile := appData + '\OGE\' + 'sqlite.dat'; {$ENDIF} if not FileExists(fDataFile) then begin messageBox(0, PWideChar('Ôàéë ' + fDataFile + ' íå íàéäåí!'), 'ÎÃÅ', MB_OK or MB_ICONERROR); halt(0); end; if not FileExists(sqliteFile) then begin messageBox(0, PWideChar('Ôàéë ' + sqliteFile + ' íå íàéäåí!'), 'ÎÃÅ', MB_OK or MB_ICONERROR); halt(0); end; sql := TStringList.Create; sqlite := TSQLiteDatabase.Create(sqliteFile); createTableUser(); createTableSavePoints(); createTableParams(); // dropTable('RESULTS') end; procedure Tdm.loadUserFromFile(fl: string); var l: TStringList; i: integer; begin l := TStringList.Create; l.LoadFromFile(fl); for i := 0 to l.Count - 1 do begin sql.Clear; sql.Add(l.Strings[i]); if trim(sql.Text) = '' then continue; sqlite.ExecSQL(ansistring(sql.Text)); end; end; procedure Tdm.SaveParam(const paramName, paramValue: string); var table: TSQLiteUniTable; cnt: integer; begin sql.Clear; sql.Add(format('SELECT COUNT(*) FROM PARAMS WHERE KEY_FIELD = "%s"', [paramName])); try table := TSQLiteUniTable.Create(dm.sqlite, ansiString(sql.Text)); cnt := table.FieldAsInteger(0); finally freeAndNil(table); end; sql.Clear; if cnt = 0 then begin sql.Add(format( 'INSERT INTO PARAMS(KEY_FIELD, VALUE_FIELD)' + 'VALUES("%s", "%s")', [paramName, paramValue])) end else begin sql.Add(format( 'UPDATE PARAMS ' + 'SET VALUE_FIELD = "%s" ' + 'WHERE KEY_FIELD = "%s"', [paramValue, paramName])); end; sqlite.ExecSQL(ansistring(sql.Text)); end; function Tdm.LoadParam(const paramName: string): string; var table: TSQLiteUniTable; begin sql.Clear; sql.Add(format('SELECT VALUE_FIELD FROM PARAMS WHERE KEY_FIELD = "%s"', [paramName])); try table := TSQLiteUniTable.Create(sqlite, ansiString(sql.Text)); result := table.FieldAsString(0); finally freeAndNil(table); end; end; procedure Tdm.DataModuleDestroy(Sender: TObject); begin sql.Free; sqlite.Free; end; end.
unit unit_main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, SynEdit, SynMemo, Forms, Controls, Graphics, Dialogs, ExtCtrls, Spin, StdCtrls, Buttons, Menus, unit_history; const DefaultLineWidth = 1; BoldLineWidth = 3; {DFFSM = Determ Figure Finite-State Machine} ValidDirectionChars: set of char = ['r', 'R', 'd', 'D', 'l', 'L', 'u', 'U', 'n', 'N']; ValidIntegers: set of char = ['0'..'9']; ArrowChars: array [0..8] of string = ('↰', '↑', '↱', '←', '', '→', '↲', '↓', '↳'); ArrowTrueChars: array [0..8] of string = ('ul', 'u', 'ur', 'l', 'n', 'r', 'dl', 'd', 'dr'); type { TMainForm } TDirection = (dNone, dRightUp, dRight, dRightDown, dDown, dLeftDown, dLeft, dLeftUp, dUp); { 0 = start 1 = reading first char of direction 2 = reading second char of direction 3 = reading length 4 = finish } TFSMState = (msStart, msFirstChar, msSecondChar, msNum, msFinish); TDetermFigureFSM = class private FCurState: TFSMState; FCurNum: integer; FCurChars: string; public function Analyze(ANewChar: char; var ACurLength: integer; var ADirection: TDirection): boolean; function AnalyzeNumFirst(ANewChar: char; var ACurLength: integer; var ADirection: TDirection): boolean; constructor Create; end; TLine = class private FDirection: TDirection; FLength: integer; FStartPoint: TPoint; FEndPoint: TPoint; FColor: TColor; public property Direction: TDirection read FDirection; property Size: integer read FLength; property StartPoint: TPoint read FStartPoint; property EndPoint: TPoint read FEndPoint; constructor Create(ABitmap: TBitmap; ADirection: TDirection; ALength, AScale: integer; APoint: TPoint; AColor: TColor); end; TDot = class private FSize: integer; FPoint: TPoint; FColor: TColor; public property Size: integer read FSize; property StartPoint: TPoint read FPoint; constructor Create(ABitmap: TBitmap; AScale: integer; APoint: TPoint; AColor: TColor); end; TMainForm = class(TForm) btnHistory: TBitBtn; procedure btnHistoryClick(Sender: TObject); public FSM: TDetermFigureFSM; ArrowButtons: array [0..8] of TBitBtn; published memoText: TSynEdit; pnlArrows: TPanel; cbColor: TColorButton; pbPicture: TPaintBox; pnlPicture: TPanel; pnlText: TPanel; pnlColorSize: TPanel; spinSize: TSpinEdit; bmPicture: TBitmap; bbClear: TBitBtn; bbSave: TBitBtn; SaveDialog: TSaveDialog; procedure bbClearClick(Sender: TObject); procedure bbSaveClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbPictureMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbPicturePaint(Sender: TObject); procedure DrawFigure(APoint: TPoint; AColor: TColor; AScale: integer; IsNumFirst: boolean); procedure DrawDot(APoint: TPoint; AColor: TColor; AScale: integer); procedure CreateArrowButtons(APanel: TPanel); procedure ArrowButtonClick(Sender: TObject); end; var MainForm: TMainForm; implementation {$R *.lfm} { TMainForm } function TDetermFigureFSM.Analyze(ANewChar: char; var ACurLength: integer; var ADirection: TDirection): boolean; begin Result := false; {CurState = reading num} if FCurState = msNum then if ANewChar in ValidIntegers then begin FCurNum := FCurNum*10 + StrToInt(ANewChar); exit(false); end else if ANewChar in ValidDirectionChars then begin FCurState := msFirstChar; FCurChars := ANewChar; ACurLength := FCurNum; FCurNum := 0; exit(true); end else begin FCurState := msStart; ACurLength := FCurNum; FCurNum := 0; exit(true); end; {CurState = reading first char} if FCurState = msFirstChar then begin case FCurChars of 'r', 'R': ADirection := dRight; 'd', 'D': ADirection := dDown; 'l', 'L': ADirection := dLeft; 'u', 'U': ADirection := dUp; 'n', 'N': ADirection := dNone; end; if ANewChar in ValidDirectionChars then begin FCurChars := FCurChars + ANewChar; FCurState := msSecondChar; exit(false); end else if ANewChar in ValidIntegers then begin FCurNum := StrToInt(ANewChar); FCurState := msNum; FCurChars := ''; exit(false); end else begin FCurState := msStart; FCurChars := ''; exit(false); end; end; {CurState = reading second char} if FCurState = msSecondChar then begin case FCurChars of 'rr', 'RR': ADirection := dRight; 'dd', 'DD': ADirection := dDown; 'll', 'LL': ADirection := dLeft; 'uu', 'UU': ADirection := dUp; 'ru', 'rU', 'Ru', 'RU', 'ur', 'uR', 'Ur', 'UR': ADirection := dRightUp; 'rd', 'rD', 'Rd', 'RD', 'dr', 'dR', 'Dr', 'DR': ADirection := dRightDown; 'lu', 'lU', 'Lu', 'LU', 'ul', 'uL', 'Ul', 'UL': ADirection := dLeftUp; 'ld', 'lD', 'Ld', 'LD', 'dl', 'dL', 'Dl', 'DL': ADirection := dLeftDown; else ADirection := dNone; end; if ANewChar in ValidIntegers then begin FCurState := msNum; FCurNum := StrToInt(ANewChar); FCurChars := ''; exit(false); end else begin FCurState := msStart; FCurChars := ''; exit(false); end; end; {CurState = reading start} if FCurState = msStart then begin if ANewChar in ValidDirectionChars then begin FCurChars := ANewChar; FCurState := msFirstChar; exit(false); end else if ANewChar in ValidIntegers then begin FCurNum := StrToInt(ANewChar); FCurState := msNum; exit(false); end; end; end; function TDetermFigureFSM.AnalyzeNumFirst(ANewChar: char; var ACurLength: integer; var ADirection: TDirection): boolean; begin Result := false; {CurState = reading num} if FCurState = msNum then if ANewChar in ValidIntegers then begin FCurNum := FCurNum*10 + StrToInt(ANewChar); exit(false); end else if ANewChar in ValidDirectionChars then begin FCurChars := ANewChar; FCurState := msFirstChar; ACurLength := FCurNum; FCurNum := 0; exit(false); end else begin FCurState := msStart; ACurLength := FCurNum; FCurNum := 0; exit(false); end; {CurState = reading first char} if FCurState = msFirstChar then begin case FCurChars of 'r', 'R': ADirection := dRight; 'd', 'D': ADirection := dDown; 'l', 'L': ADirection := dLeft; 'u', 'U': ADirection := dUp; 'n', 'N': ADirection := dNone; end; if ANewChar in ValidDirectionChars then begin FCurChars := FCurChars + ANewChar; FCurState := msSecondChar; exit(false); end else if ANewChar in ValidIntegers then begin FCurNum := StrToInt(ANewChar); FCurState := msNum; FCurChars := ''; exit(true); end else begin FCurState := msStart; FCurChars := ''; exit(true); end; end; {CurState = reading second char} if FCurState = msSecondChar then begin case FCurChars of 'rr', 'RR': ADirection := dRight; 'dd', 'DD': ADirection := dDown; 'll', 'LL': ADirection := dLeft; 'uu', 'UU': ADirection := dUp; 'ru', 'rU', 'Ru', 'RU', 'ur', 'uR', 'Ur', 'UR': ADirection := dRightUp; 'rd', 'rD', 'Rd', 'RD', 'dr', 'dR', 'Dr', 'DR': ADirection := dRightDown; 'lu', 'lU', 'Lu', 'LU', 'ul', 'uL', 'Ul', 'UL': ADirection := dLeftUp; 'ld', 'lD', 'Ld', 'LD', 'dl', 'dL', 'Dl', 'DL': ADirection := dLeftDown; else ADirection := dNone; end; if ANewChar in ValidIntegers then begin FCurState := msNum; FCurNum := StrToInt(ANewChar); FCurChars := ''; exit(true); end else begin FCurState := msStart; FCurChars := ''; exit(true); end; end; {CurState = reading start} if FCurState = msStart then begin if ANewChar in ValidDirectionChars then begin FCurChars := ANewChar; FCurState := msFirstChar; exit(false); end else if ANewChar in ValidIntegers then begin FCurNum := StrToInt(ANewChar); FCurState := msNum; exit(false); end; end; end; constructor TDetermFigureFSM.Create; begin FCurState := msStart; FCurNum := 0; FCurChars := ''; end; constructor TLine.Create(ABitmap: TBitmap; ADirection: TDirection; ALength, AScale: integer; APoint: TPoint; AColor: TColor); var DirectLength: integer; begin DirectLength := AScale * ALength * 2; FStartPoint := APoint; FColor := AColor; case ADirection of dRightUp: FEndPoint := Point(APoint.X + DirectLength, APoint.Y - DirectLength); dRight: FEndPoint := Point(APoint.X + DirectLength, APoint.Y); dRightDown: FEndPoint := Point(APoint.X + DirectLength, APoint.Y + DirectLength); dDown: FEndPoint := Point(APoint.X, APoint.Y + DirectLength); dLeftDown: FEndPoint := Point(APoint.X - DirectLength, APoint.Y + DirectLength); dLeft: FEndPoint := Point(APoint.X - DirectLength, APoint.Y); dLeftUp: FEndPoint := Point(APoint.X - DirectLength, APoint.Y - DirectLength); dUp: FEndPoint := Point(APoint.X, APoint.Y - DirectLength); else FEndPoint := APoint; end; with ABitmap.Canvas do begin if ADirection = dNone then Pen.Width := BoldLineWidth; Pen.Color := AColor; MoveTo(FStartPoint); LineTo(FEndPoint); Pen.Width := DefaultLineWidth; end; end; constructor TDot.Create(ABitmap: TBitmap; AScale: integer; APoint: TPoint; AColor: TColor); begin FPoint := APoint; FColor := AColor; with ABitmap.Canvas do begin Pen.Color := AColor; Pen.Width := AScale div 2; MoveTo(FPoint); LineTo(FPoint); Pen.Width := DefaultLineWidth; end; end; procedure TMainForm.btnHistoryClick(Sender: TObject); begin HistoryForm.Show; end; procedure TMainForm.bbClearClick(Sender: TObject); begin bmPicture.Canvas.FillRect(0, 0, Width, Height); pbPicture.Invalidate; end; procedure TMainForm.bbSaveClick(Sender: TObject); begin if SaveDialog.Execute then bmPicture.SaveToFile(SaveDialog.FileName + '.bmp'); end; procedure TMainForm.FormResize(Sender: TObject); begin bmPicture.Width := MainForm.Width; bmPicture.Height := MainForm.Height; end; procedure TMainForm.FormCreate(Sender: TObject); begin ActiveControl := memoText; bmPicture := TBitmap.Create; bmPicture.Width := MainForm.Width; bmPicture.Height := MainForm.Height; with bmPicture.Canvas do begin Brush.Color := clWhite; Brush.Style := bsSolid; Pen.Color := clWhite; Pen.Style := psSolid; Pen.Width := DefaultLineWidth; end; bmPicture.Canvas.FillRect(0, 0, Width, Height); FSM := TDetermFigureFSM.Create; CreateArrowButtons(pnlArrows); end; procedure TMainForm.pbPictureMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MemoString: string; i, j: integer; IsNumFirst: boolean; begin for i := 0 to memoText.Lines.Count - 1 do begin MemoString := memoText.Lines[i]; if (Length(MemoString) > 0) and (MemoString[Length(MemoString) - 1] <> ' ') then memoText.Lines[i] := MemoString + ' '; end; i := 0; j := 0; MemoString := '#'; while (j < Length(MemoString)) and not ((MemoString[j] in ValidDirectionChars) or (MemoString[j] in ValidIntegers)) do begin MemoString := memoText.Lines[i]; while (j < Length(MemoString)) and not ((MemoString[j] in ValidDirectionChars) or (MemoString[j] in ValidIntegers)) do begin inc(j); if j >= Length(MemoString) then break; end; inc(i); if (i = memoText.Lines.Count) and (j = Length(MemoString)) then break; end; IsNumFirst := (j < Length(MemoString)) and (MemoString[j] in ValidIntegers); if Button = mbLeft then begin DrawFigure(Point(X, Y), cbColor.ButtonColor, spinSize.Value, IsNumFirst); with HistoryForm.memoHistory do begin Text := Text + memoText.Text; Lines.Append(''); end; end else begin DrawDot(Point(X, Y), cbColor.ButtonColor, spinSize.Value); end; end; procedure TMainForm.pbPicturePaint(Sender: TObject); begin with bmPicture do pbPicture.Canvas.CopyRect(Rect(0, 0, Width, Height), bmPicture.Canvas, Rect(0, 0, Width, Height)); end; procedure TMainForm.DrawFigure(APoint: TPoint; AColor: TColor; AScale: integer; IsNumFirst: boolean); var i, j: integer; CurLength: integer; CurDirection: TDirection; CurPoint: TPoint; CurMemoString: string; NewLine: TLine; begin CurPoint := APoint; CurDirection := dNone; CurLength := 0; NewLine := nil; for i := 0 to memoText.Lines.Count - 1 do begin CurMemoString := memoText.Lines[i]; for j := 0 to Length(CurMemoString) - 1 do begin if IsNumFirst then begin if FSM.AnalyzeNumFirst(CurMemoString[j], CurLength, CurDirection) then begin NewLine := TLine.Create(bmPicture, CurDirection, CurLength, AScale, CurPoint, AColor); CurPoint := NewLine.EndPoint; FreeAndNil(NewLine); end; end else if FSM.Analyze(CurMemoString[j], CurLength, CurDirection) then begin NewLine := TLine.Create(bmPicture, CurDirection, CurLength, AScale, CurPoint, AColor); CurPoint := NewLine.EndPoint; FreeAndNil(NewLine); end; end; end; with bmPicture do pbPicture.Canvas.CopyRect(Rect(0, 0, Width, Height), bmPicture.Canvas, Rect(0, 0, Width, Height)); end; procedure TMainForm.DrawDot(APoint: TPoint; AColor: TColor; AScale: integer); var Dot: TDot; begin Dot := TDot.Create(bmPicture, AScale, APoint, AColor); pbPicture.Invalidate; FreeAndNil(Dot); end; procedure TMainForm.CreateArrowButtons(APanel: TPanel); var i, j, k: integer; DefaultButtonHeight: integer; begin DefaultButtonHeight := APanel.Height div 3; for i := 0 to 2 do for j := 0 to 2 do begin k := i*3 + j; ArrowButtons[k] := TBitBtn.Create(APanel); with ArrowButtons[k] do begin Parent := APanel; Height := DefaultButtonHeight; Width := Height; Top := Height * i; Left := Width * j; Caption := ArrowChars[k]; Hint := ArrowTrueChars[k]; ShowHint := true; Font.Size := 12; OnClick := @ArrowButtonClick; end; end; end; procedure TMainForm.ArrowButtonClick(Sender: TObject); var Button: TBitBtn; i, j: integer; MemoString: string; Direction: string; begin Button := Sender as TBitBtn; Direction := Button.Hint; i := memoText.CaretY - 1; j := memoText.CaretX - 1; MemoString := memoText.Lines[i]; MemoString := Copy(MemoString, 1, j) + Direction + Copy(MemoString, j + 1, Length(MemoString)); memoText.Lines[i] := MemoString; memoText.CaretXY := Point(j + Length(Direction) + 1, i + 1); ActiveControl := memoText; end; end.
unit DAO.ControleBaixasTFO; interface uses DAO.Base, Model.ControleBaixasTFO, Generics.Collections, System.Classes; type TControleBaixaTFODAO = class(TDAO) public function Insert(aControle: TControleBaixasTFO): Boolean; function Update(aControle: TControleBaixasTFO): Boolean; function Detele(aParam: array of variant): Boolean; function Find(aParam:array of Variant): TObjectList<TControleBaixasTFO>; function MaxDate(dtBaixa: TDate): TDate; end; const TABLENAME = 'exp_controle_baixas_TFO'; implementation { TControleBaixaTFODAO } uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TControleBaixaTFODAO.Detele(aParam: array of variant): Boolean; var sSQL : String; begin Result := False; sSQL := 'delete from ' + TABLENAME; if aParam[0] = 'ID' then begin sSQL := sSQL + ' where ID_CONTROLE = :ID'; Connection.ExecSQL(sSQL,[aParam[1]],[ftInteger]); end else begin sSQL := sSQL + ' where DAT_CONTROLE = :DATA'; Connection.ExecSQL(sSQL,[aParam[1]],[ftDate]); end; Result := True; end; function TControleBaixaTFODAO.Find(aParam: array of Variant): TObjectList<TControleBaixasTFO>; var FDQuery: TFDQuery; controles: TObjectList<TControleBaixasTFO>; begin try controles := TObjectList<TControleBaixasTFO>.Create; FDQuery := TFDQuery.Create(nil); FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if Length(aParam) < 2 then Exit; if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where ID_CONTROLE = :ID'); FDQuery.ParamByName('ID').AsInteger := aParam[1]; end; if aParam[0] = 'DATA' then begin FDQuery.SQL.Add('where DAT_CONTROLE = :DATA'); FDQuery.ParamByName('DATA').AsDate := aParam[1]; end; FDQuery.Open(); while not FDQuery.Eof do begin controles.Add(TControleBaixasTFO.Create(FDQuery.FieldByName('ID_CONTROLE').AsInteger, FDQuery.FieldByName('DAT_CONTROLE').AsDateTime, FDQuery.FieldByName('DOM_STATUS').AsInteger, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; Result := controles; finally FDQuery.Free; end; end; function TControleBaixaTFODAO.Insert(aControle: TControleBaixasTFO): Boolean; var sSQL : String; begin Result := False; sSQL := 'INSERT INTO ' + TABLENAME + ' (ID_CONTROLE, DAT_CONTROLE, DOM_STATUS, DES_LOG) VALUES (:ID_CONTROLE, :DAT_CONTROLE, :DOM_STATUS, :DES_LOG);'; Connection.ExecSQL(sSQL,[aControle.Id, aControle.Data, aControle.Status, aControle.Log], [ftInteger, ftDate, ftInteger, ftString]); Result := True; end; function TControleBaixaTFODAO.MaxDate(dtBaixa: TDate): TDate; var FDQuery: TFDQuery; dtData: TDate; begin try FDQuery := TFDQuery.Create(nil); FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('select max(DAT_CONTROLE) from ' + TABLENAME); FDQuery.Open(); if FDQuery.RecordCount > 0 then begin dtData := FDQuery.Fields[0].AsDateTime; if dtData = 0 then begin dtData := dtBaixa; end; end else begin dtData := dtBaixa; end; Result := dtData; finally FDQuery.Free; end; end; function TControleBaixaTFODAO.Update(aControle: TControleBaixasTFO): Boolean; var sSQL : String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' SET DAT_CONTROLE = :DAT_CONTROLE, DOM_STATUS = :DOM_STATUS, DES_LOG = :DES_LOG WHERE ID_CONTROLE = :ID_CONTROLE;'; Connection.ExecSQL(sSQL,[aControle.Data, aControle.Status, aControle.Log, aControle.Id], [ftDate, ftInteger, ftString, ftInteger]); Result := True; end; end.
unit RRManagerEditMainBedInfoFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, RRManagerBaseObjects, CommonComplexCombo, RRManagerObjects, ClientCommon, RRManagerBaseGUI, ExtCtrls; type TfrmMainBedInfo = class(TBaseFrame) // TfrmMainBedInfo = class(TFrame) gbxAll: TGroupBox; Label1: TLabel; edtBedIndex: TEdit; cmplxNGK: TfrmComplexCombo; cmplxCollectorType: TfrmComplexCombo; cmplxLithology: TfrmComplexCombo; cmplxFluidType: TfrmComplexCombo; cmplxBedType: TfrmComplexCombo; cmplxStructureElementType: TfrmComplexCombo; Bevel1: TBevel; edtDepth: TEdit; Label2: TLabel; edtComment: TEdit; Label3: TLabel; chbxIsBalanced: TCheckBox; private { Private declarations } function GetBed: TOldBed; function GetField: TOldField; protected procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; public { Public declarations } property Bed: TOldBed read GetBed; property Field: TOldField read GetField; constructor Create(AOwner: TComponent); override; procedure Save; override; end; implementation {$R *.DFM} { TfrmMainBedInfo } procedure TfrmMainBedInfo.ClearControls; begin edtBedIndex.Clear; cmplxNGK.Clear; cmplxBedType.Clear; cmplxCollectorType.Clear; cmplxLithology.Clear; cmplxFluidType.Clear; edtDepth.Clear; if Assigned(Field) then FEditingObject := Field.Beds.Add; end; constructor TfrmMainBedInfo.Create(AOwner: TComponent); begin inherited; EditingClass := TOldBed; cmplxStructureElementType.Caption := 'Блок, купол'; cmplxStructureElementType.FullLoad := true; cmplxStructureElementType.DictName := 'TBL_STRUCTURE_TECTONIC_ELEMENT'; cmplxNGK.Caption := 'Нефтегазоносный комплекс'; cmplxNGK.FullLoad := true; cmplxNGK.DictName := 'TBL_OIL_COMPLEX_DICT'; cmplxBedType.Caption := 'Тип залежи по геологическому строению'; cmplxBedType.FullLoad := true; cmplxBedType.DictName := 'TBL_BED_TYPE_DICT'; cmplxCollectorType.Caption := 'Тип коллектора'; cmplxCollectorType.FullLoad := true; cmplxCollectorType.DictName := 'TBL_COLLECTOR_TYPE_DICT'; cmplxLithology.Caption := 'Литология коллектора'; cmplxLithology.FullLoad := true; cmplxLithology.DictName := 'TBL_LITHOLOGY_DICT'; cmplxFluidType.Caption := 'Тип залежи по типу флюида'; cmplxFluidType.FullLoad := true; cmplxFluidType.DictName := 'TBL_FIELD_TYPE_DICT'; end; procedure TfrmMainBedInfo.FillControls(ABaseObject: TBaseObject); var b: TOldBed; begin if not Assigned(ABaseObject) then B := Bed else B := ABaseObject as TOldBed; // DebugFileSave('FillFirstFrame: ' + IntToStr(Bed.Field.UIN) + '; ' + Bed.Field.Name); edtBedIndex.Text := B.BedIndex; cmplxNGK.AddItem(B.ComplexID, B.ComplexName); cmplxBedType.AddItem(B.BedTypeID, B.BedType); cmplxStructureElementType.AddItem(B.StructureElementID, B.StructureElement); cmplxCollectorType.AddItem(B.CollectorTypeID, B.CollectorType); cmplxLithology.AddItem(B.RockID, B.RockName); cmplxFluidType.AddItem(B.FluidTypeID, B.FluidType); if b.Depth <> -1 then edtDepth.Text := Trim(Format('%8.2f', [B.Depth])); edtComment.Text := Bed.Name; chbxIsBalanced.Checked := Bed.IsBalanced; end; procedure TfrmMainBedInfo.FillParentControls; begin cmplxFluidType.AddItem(Field.FieldTypeID, Field.FieldType); end; function TfrmMainBedInfo.GetBed: TOldBed; begin if EditingObject is TOldBed then Result := EditingObject as TOldBed else Result := nil; end; function TfrmMainBedInfo.GetField: TOldField; begin Result := nil; if EditingObject is TOldField then Result := EditingObject as TOldField else if EditingObject is TOldBed then Result := (EditingObject as TOldBed).Field; end; procedure TfrmMainBedInfo.RegisterInspector; begin inherited; Inspector.Add(edtBedIndex, nil, ptString, 'индекс залежи', false); Inspector.Add(cmplxNGK.cmbxName, nil, ptString, 'НГК', false); Inspector.Add(cmplxFluidType.cmbxName, nil, ptString, 'тип флюида', false); Inspector.Add(edtDepth, nil, ptFloat, 'глубина кровли залежи', true); end; procedure TfrmMainBedInfo.Save; begin inherited; if FEditingObject is TOldField then FEditingObject := Field.Beds.Add; Bed.BedIndex := edtBedIndex.Text; Bed.RockID := cmplxLithology.SelectedElementID; Bed.RockName := cmplxLithology.SelectedElementName; Bed.CollectorTypeID := cmplxCollectorType.SelectedElementID; Bed.CollectorType := cmplxCollectorType.SelectedElementName; Bed.BedTypeID := cmplxBedType.SelectedElementID; Bed.BedType := cmplxBedType.SelectedElementName; Bed.ComplexID := cmplxNGK.SelectedElementID; Bed.ComplexName := cmplxNGK.SelectedElementName; Bed.FluidTypeID := cmplxFluidType.SelectedElementID; Bed.FluidType := cmplxFluidType.SelectedElementName; Bed.StructureElementID := cmplxStructureElementType.SelectedElementID; Bed.StructureElement := cmplxStructureElementType.SelectedElementName; Bed.Name := edtComment.Text; try Bed.Depth := StrToFloat(edtDepth.Text); except Bed.Depth := -1; end; Bed.IsBalanced := chbxIsBalanced.Checked; end; end.
unit StateGame; interface uses Windows, AvL, avlUtils, avlEventBus, avlMath, avlVectors, OpenGL, oglExtensions, VSEOpenGLExt, VSECore, VSECamera, VSEGUI, Scene, Game; type TStateGame=class(TGameState) private {$IFDEF VSE_DEBUG} FFont: Cardinal; FShowDebugInfo: Boolean; {$ENDIF} FFreeList: TList; FFormsSet: TGUIFormsSet; FCamera: TCamera; FScene: TScene; FGame: TGame; FMouse3D: TVector3D; FOnMouseEvent: Integer; function GetCanResumeGame: Boolean; procedure FreeList; procedure FreeListAdd(Sender: TObject; const Args: array of const); procedure FreeListRemove(Sender: TObject; const Args: array of const); procedure PlayerActionsChanged(Sender: TObject; const Args: array of const); procedure ActivePlayerChanged(Sender: TObject; const Args: array of const); protected function GetName: string; override; public constructor Create; destructor Destroy; override; procedure Draw; override; procedure Update; override; function Activate: Cardinal; override; procedure Deactivate; override; procedure OnEvent(var Event: TCoreEvent); override; procedure NewGame; property CanResumeGame: Boolean read GetCanResumeGame; property Mouse3D: TVector3D read FMouse3D; end; const SIDGame = 'Game'; implementation uses VSERender2D, VSETexMan, VSEFormManager, VSEBindMan, VSECollisionCheck {$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}{$IFDEF VSE_LOG}, VSELog{$ENDIF}, StateMenu, GameForms, GameObjects, GameData; const MoveBorder = 25; constructor TStateGame.Create; begin inherited Create; FOnMouseEvent := EventBus.RegisterEvent(GameOnMouseEvent); FFreeList := TList.Create; EventBus.AddListener(EventBus.RegisterEvent(GameObjects.FreeListAdd), FreeListAdd); EventBus.AddListener(EventBus.RegisterEvent(GameObjects.FreeListRemove), FreeListRemove); FFormsSet := TGUIFormsSet.Create; {$IFDEF VSE_DEBUG} FFormsSet.AddForm(IDLogPoints, TLogPointsForm.Create, ''); FFormsSet.Visible[IDLogPoints] := false; {$IFDEF VSE_CONSOLE} Console['debuginfo ?show=eoff:on'] := Console.GetConVarHandler(FShowDebugInfo, cvBool); Console['logpoints ?show=eoff:on'] := Console.GetConVarHandler(FFormsSet.FindForm(IDLogPoints).Visible, cvBool); {$ENDIF} FShowDebugInfo := true; FFont := Render2D.CreateFont('Courier New', 10); {$ENDIF} BindMan.AddBindings(Bindings); FCamera := TCamera.Create; end; destructor TStateGame.Destroy; begin EventBus.RemoveListeners([FreeListAdd, FreeListRemove, PlayerActionsChanged, ActivePlayerChanged]); FreeList; FAN(FCamera); FAN(FFormsSet); FAN(FFreeList); inherited Destroy; end; procedure TStateGame.Draw; begin inherited; glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT); DrawBackground; glePerspectiveMatrix2(60, Core.ResolutionX, Core.ResolutionY, 1, 500); FCamera.Apply; FScene.Draw; with Core.MouseCursor do FMouse3D := gleScreenTo3D(X, Y, true); {$IFDEF VSE_DEBUG} if FormManager.Visible[IDLogPoints] then (FormManager[IDLogPoints] as TLogPointsForm).DrawPoints; if FShowDebugInfo then begin Render2D.Enter; gleColor(clWhite); with Render2D.VSBounds do begin Render2D.TextOut(FFont, Left + 5, Top + 5, 'FPS: ' + IntToStr(Core.FPS)); with FCamera.Eye do Render2D.TextOut(FFont, Left + 5, Top + 25, Format('Pos=%s, %s, %s', [FloatToStr2(X, 4, 2), FloatToStr2(Y, 4, 2), FloatToStr2(Z, 4, 2)])); with FCamera do Render2D.TextOut(FFont, Left + 5, Top + 45, Format('Angles=%s, %s', [FloatToStr2(Angle.X, 4, 2), FloatToStr2(Angle.Y, 4, 2)])); with FMouse3D do Render2D.TextOut(FFont, Left + 5, Top + 65, Format('Mouse=%s, %s, %s', [FloatToStr2(X, 4, 2), FloatToStr2(Y, 4, 2), FloatToStr2(Z, 4, 2)])); end; Render2D.Leave; end; {$ENDIF} end; procedure TStateGame.Update; const Move: array[Boolean, Boolean] of Single = ((0, -1), (1, 0)); begin inherited; with Core do FCamera.Move(Vector2D( Move[ BindMan[BindCamLeft] or PointInRect(MouseCursor, Rect(0, 0, MoveBorder, ResolutionY)), BindMan[BindCamRight] or PointInRect(MouseCursor, Rect(ResolutionX - MoveBorder, 0, ResolutionX, ResolutionY))], Move[ BindMan[BindCamFwd] or PointInRect(MouseCursor, Rect(0, 0, ResolutionX, MoveBorder)), BindMan[BindCamBwd] or PointInRect(MouseCursor, Rect(0, ResolutionY - MoveBorder, ResolutionX, ResolutionY))]), MapBounds.Min, MapBounds.Max); if Assigned(FGame) then begin EventBus.SendEvent(FOnMouseEvent, FGame, [Integer(meMove), @FMouse3D]); FGame.Update; FScene.Update; end; end; function TStateGame.Activate: Cardinal; begin inherited Activate; Result := 20; glClearColor(0, 0, 0, 1); glClearStencil(0); FormManager.FormsSet := FFormsSet; Draw; Core.ResetUpdateTimer; //TODO: FGame.Resume; end; procedure TStateGame.Deactivate; begin inherited; FormManager.FormsSet := nil; //TODO: FGame.Pause; end; procedure TStateGame.OnEvent(var Event: TCoreEvent); begin if Event is TMouseEvent then with Event as TMouseEvent do begin case EvType of meDown: if Button in [mbRight, mbMiddle] then Core.MouseCapture := true else if Assigned(FGame) and (Button = mbLeft) then EventBus.SendEvent(FOnMouseEvent, FGame, [Integer(meDown), @FMouse3D]); meUp: if Button in [mbRight, mbMiddle] then Core.MouseCapture := false else if Assigned(FGame) and (Button = mbLeft) then EventBus.SendEvent(FOnMouseEvent, FGame, [Integer(meUp), @FMouse3D]); meMove: if Core.MouseCapture then //TODO: Panning & Rotating speed to Options with FCamera, Cursor do if Core.KeyPressed[VK_RBUTTON] then Angle := Vector2D(Max(90.0, Min(Angle.X + X / 10, 270.0)), Max(-89.9, Min(Angle.Y - Y / 10, -35.0))) else Move(Vector2D(0.1 * X, 0.1 * Y), MapBounds.Min, MapBounds.Max); meWheel: FCamera.Height := Max(10.0, Min(FCamera.Height - Button, 75.0)); end; end else if (Event is TKeyEvent) and ((Event as TKeyEvent).EvType = keUp) then case (Event as TKeyEvent).Key of VK_ESCAPE: Core.SwitchState(SIDMenu); end else if (Event is TSysNotify) and ((Event as TSysNotify).Notify = snMinimized) then Core.SwitchState(SIDMenu) else inherited; end; procedure TStateGame.NewGame; begin FreeList; FCamera.Eye := Vector3D(0, 50, 45); FCamera.Angle := Vector2D(180, -60); FScene := TScene.Create; EventBus.SendEvent(GameObjects.FreeListAdd, FScene, []); FGame := TGame.Create(FScene); EventBus.SendEvent(GameObjects.FreeListAdd, FGame, []); EventBus.AddListener(PlayerOnActionsChanged, PlayerActionsChanged); EventBus.AddListener(GameOnActivePlayerChanged, ActivePlayerChanged); ActivePlayerChanged(FGame, [TObject(nil), FGame.ActivePlayer]); {$IFDEF VSE_DEBUG} FFormsSet[IDPlayerSelect].Free; FFormsSet.AddForm(IDPlayerSelect, TPlayerSelectForm.Create(FGame)); {$ENDIF} end; function TStateGame.GetName: string; begin Result := SIDGame; end; function TStateGame.GetCanResumeGame: Boolean; begin Result := Assigned(FGame); end; procedure TStateGame.FreeList; var Item: TObject; begin while FFreeList.Count > 0 do begin Item := TObject(FFreeList.Last); FFreeList.Remove(Item); Item.Free; end; end; procedure TStateGame.FreeListAdd(Sender: TObject; const Args: array of const); begin Assert(Assigned(Sender) and (Length(Args) = 0)); if FFreeList.IndexOf(Sender) < 0 then FFreeList.Add(Sender); end; procedure TStateGame.FreeListRemove(Sender: TObject; const Args: array of const); begin Assert(Assigned(Sender) and (Length(Args) = 0)); FFreeList.Remove(Sender); end; procedure TStateGame.PlayerActionsChanged(Sender: TObject; const Args: array of const); var i: Integer; begin if not Assigned(FGame) or (Sender <> FGame.ActivePlayer) then Exit; for i := 0 to High(FGame.ActivePlayer.AvailActions) do with FGame.ActivePlayer.AvailActions[i] do if Assigned(Form) and not Assigned(FFormsSet.FindForm(Form)) then FFormsSet.AddForm(ClassName, Form, ''); end; procedure TStateGame.ActivePlayerChanged(Sender: TObject; const Args: array of const); var i: Integer; begin Assert((Length(Args) = 2) and (Args[0].VType = vtObject) and (Args[1].VType = vtObject)); if Assigned(Args[0].VObject) then with Args[0].VObject as TPlayer do for i := 0 to High(AvailActions) do with AvailActions[i] do if Assigned(Form) then FFormsSet.RemoveForm(Form); PlayerActionsChanged(Args[1].VObject, []); end; end.
unit SJ_BitmapButton; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TBitmapButton = class(TGraphicControl) private FBitmap: TBitmap; FLighter: TBitmap; FDarker: Tbitmap; FPushDown:boolean; FMouseOver:boolean; FLatching: boolean; FDown: boolean; FHotTrack: boolean; procedure SetBitmap(const Value: TBitmap); procedure MakeDarker; procedure MakeLighter; procedure SetLatching(const Value: boolean); procedure SetDown(const Value: boolean); procedure SetHotTrack(const Value: boolean); { Private declarations } protected { Protected declarations } 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 Click;override; procedure CMMouseLeave(var Message:TMessage); message CM_MouseLeave; procedure Loaded;override; procedure Resize;override; public { Public declarations } constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Paint; override; published { Published declarations } property Bitmap:TBitmap read FBitmap write SetBitmap; property Down:boolean read FDown write SetDown; property Latching:boolean read FLatching write SetLatching; property HotTrack:boolean read FHotTrack write SetHotTrack; property onclick; property onmousedown; property onmouseup; end; procedure Register; implementation procedure Register; begin RegisterComponents('SimJoy', [TBitmapButton]); end; { TBitmapButton } procedure TBitmapButton.Click; begin inherited; // if FPushDown then if assigned(onclick) then onclick(self); end; constructor TBitmapButton.Create(AOwner: TComponent); begin inherited; width:=24; height:=24; FPushDown:=false; FMouseOver:=false; FLatching:=false; FHotTrack:=true; FDown:=false; FBitmap:=TBitmap.create; Fbitmap.width:=24; Fbitmap.Height:=24; Fbitmap.canvas.brush.color:=clgray; FBitmap.canvas.FillRect (rect(1,1,23,23)); FLighter:=Tbitmap.create; FDarker:=Tbitmap.create; end; destructor TBitmapButton.Destroy; begin FBitmap.free; FLighter.free; FDarker.free; inherited; end; procedure TBitmapButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if FBitmap.canvas.pixels[x,y]<>Fbitmap.canvas.pixels[0,FBitmap.height-1] then FPushDown:=true else FPushDown:=false; Paint; if assigned(onmousedown) then onmousedown(self,button,shift,x,y); end; procedure TBitmapButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; FPushDown:=false; if Latching then FDown:= not FDown else FDown:=false; Paint; if assigned(onmouseup) then onmouseup(self,button,shift,x,y); end; procedure TBitmapButton.Paint; var Acolor:TColor; begin inherited; if assigned(FBitmap) then begin AColor:=FBitmap.canvas.pixels[0,FBitmap.height-1]; Fbitmap.transparent:=true; Fbitmap.transparentcolor:=Acolor; FLighter.transparent:=true; Flighter.TransparentColor :=AColor; FDarker.transparent:=true; FDarker.TransparentColor :=AColor; if FPushdown then begin canvas.draw(1,1,FDarker) end else begin if Down then canvas.Draw(1,1,FDarker) else if (FMouseOver and FHotTrack) then canvas.draw(0,0,FLighter) else canvas.Draw (0,0,FBitmap); end; end; end; procedure TBitmapButton.SetBitmap(const Value: TBitmap); begin FBitmap.assign(Value); FBitmap.transparent:=true; FBitmap.TransparentColor :=FBitmap.Canvas.pixels[0,FBitmap.Height-1]; width:=FBitmap.Width ; height:=FBitmap.Height ; MakeLighter; MakeDarker; end; procedure TBitmapButton.MakeLighter; var p1,p2:Pbytearray; x,y:integer; rt,gt,bt:byte; AColor:TColor; begin FLighter.Width :=FBitmap.Width ; FLighter.Height :=FBitmap.height; Acolor:=colortorgb(FBitmap.canvas.pixels[0,FBitmap.height-1]); rt:=GetRValue(Acolor); gt:=GetGValue(AColor); bt:=getBValue(AColor); FBitmap.PixelFormat :=pf24bit; FLighter.PixelFormat :=pf24bit; for y:=0 to Fbitmap.height-1 do begin p1:=Fbitmap.ScanLine [y]; p2:=FLighter.ScanLine [y]; for x:=0 to FBitmap.width-1 do begin if (p1[x*3]=bt)and (p1[x*3+1]=gt)and (p1[x*3+2]=rt) then begin p2[x*3]:=p1[x*3]; p2[x*3+1]:=p1[x*3+1]; p2[x*3+2]:=p1[x*3+2]; end else begin p2[x*3]:=$FF-round(0.8*abs($FF-p1[x*3])); p2[x*3+1]:=$FF-round(0.8*abs($FF-p1[x*3+1])); p2[x*3+2]:=$FF-round(0.8*abs($FF-p1[x*3+2])); end; end; end; end; procedure TBitmapButton.MakeDarker; var p1,p2:Pbytearray; x,y:integer; rt,gt,bt:byte; AColor:TColor; begin FDarker.Width :=FBitmap.Width ; FDarker.Height :=FBitmap.height; Acolor:=colortorgb(FBitmap.canvas.pixels[0,FBitmap.height-1]); rt:=GetRValue(Acolor); gt:=GetGValue(AColor); bt:=getBValue(AColor); FBitmap.PixelFormat :=pf24bit; FDarker.PixelFormat :=pf24bit; for y:=0 to Fbitmap.height-1 do begin p1:=Fbitmap.ScanLine [y]; p2:=FDarker.ScanLine [y]; for x:=0 to FBitmap.width-1 do begin if (p1[x*3]=bt)and (p1[x*3+1]=gt)and (p1[x*3+2]=rt) then begin p2[x*3]:=p1[x*3]; p2[x*3+1]:=p1[x*3+1]; p2[x*3+2]:=p1[x*3+2]; end else begin p2[x*3]:=round(0.7*p1[x*3]); p2[x*3+1]:=round(0.7*p1[x*3+1]); p2[x*3+2]:=round(0.7*p1[x*3+2]); end end; end; end; procedure TBitmapButton.CMMouseLeave(var Message: TMessage); begin FMouseOver:=false; Paint; end; procedure TBitmapButton.Loaded; begin inherited; if not FBitmap.Empty then begin MakeDarker; MakeLighter; end; end; procedure TBitmapButton.SetLatching(const Value: boolean); begin FLatching := Value; if not FLatching then begin FDown:=false; paint; end; end; procedure TBitmapButton.SetDown(const Value: boolean); begin if FLatching then begin FDown := Value; paint; end else begin FDown:=false; paint; end; end; procedure TBitmapButton.Resize; begin inherited; if assigned(Fbitmap) then begin width:=FBitmap.width; height:=FBitmap.Height ; end else begin width:=24; height:=24; end; end; procedure TBitmapButton.SetHotTrack(const Value: boolean); begin FHotTrack := Value; end; procedure TBitmapButton.MouseMove(Shift: TShiftState; X, Y: Integer); var Value:boolean; begin inherited; Value:= FBitmap.canvas.pixels[x,y]<>Fbitmap.canvas.pixels[0,FBitmap.height-1]; if value<>FMouseOver then begin FMouseOver:=value; Paint; end; if assigned(onmousemove) then onmousemove(self,shift,x,y); end; end.
{$r+} {$mode delphi} uses character; function caesar(input:integer; s:string): string; var c_update,c:char; code:integer; output:string=''; begin if input >= 26 then input := input mod 26; if input <= -26 then input := input mod 26; for c in s do begin c_update := c; if isLetter(c) then c_update := upCase(c_update); if (c_update >= 'A') and (c_update <= 'Z') then begin code := ord(c_update); code := code + input; if code < 65 then code := 90 - (64 - code); if code > 90 then code := 64 + (code - 90); c_update := chr(code); end; output := output + c_update; end; exit(output); end; var input:integer; s:string; begin readln(input); readln(s); writeln(caesar(input, s)); end.
unit FinanceSourcePoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, FinanceSource; type TFinanceSourceDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TFinanceSourceWellDataPoster = class(TImplementedDataPoster) private FAllFinanceSources: TFinanceSources; procedure SetAllFinanceSources(const Value: TFinanceSources); public property AllFinanceSources: TFinanceSources read FAllFinanceSources write SetAllFinanceSources; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils, well, Variants; { TFinanceSourceDataPoster } constructor TFinanceSourceDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_FINANCE_SOURCE_DICT'; KeyFieldNames := 'FINANCE_SOURCE_ID'; FieldNames := 'FINANCE_SOURCE_ID, VCH_FINANCE_SOURCE_NAME'; AccessoryFieldNames := 'FINANCE_SOURCE_ID, VCH_FINANCE_SOURCE_NAME'; AutoFillDates := false; Sort := 'VCH_FINANCE_SOURCE_NAME'; end; function TFinanceSourceDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TFinanceSourceDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TFinanceSource; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TFinanceSource; o.ID := ds.FieldByName('FINANCE_SOURCE_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_FINANCE_SOURCE_NAME').AsString); ds.Next; end; ds.First; end; end; function TFinanceSourceDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TFinanceSource; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := TFinanceSource(AObject); ds.FieldByName('FINANCE_SOURCE_ID').AsInteger := o.ID; ds.FieldByName('VCH_FINANCE_SOURCE_NAME').AsString := trim (o.Name); ds.Post; o.ID := ds.FieldByName('FINANCE_SOURCE_ID').AsInteger; end; { TFinanceSourceWellDataPoster } constructor TFinanceSourceWellDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_FINANCE_SOURCE'; KeyFieldNames := 'WELL_UIN; FINANCE_SOURCE_ID'; FieldNames := 'WELL_UIN, FINANCE_SOURCE_ID'; AccessoryFieldNames := 'WELL_UIN, FINANCE_SOURCE_ID'; AutoFillDates := false; Sort := 'WELL_UIN, FINANCE_SOURCE_ID'; end; function TFinanceSourceWellDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TFinanceSourceWellDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TFinanceSourceWell; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TFinanceSourceWell; if Assigned (FAllFinanceSources) then o.Assign(FAllFinanceSources.ItemsByID[ds.FieldByName('FINANCE_SOURCE_ID').AsInteger]); ds.Next; end; ds.First; end; end; function TFinanceSourceWellDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TFinanceSourceWell; begin Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName); Result := 0; o := AObject as TFinanceSourceWell; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if ds.Locate('WELL_UIN', o.Collection.Owner.ID, []) then begin ds.Delete; ds.First; end; ds.Append; except on E: Exception do begin raise; end; end; ds := TMainFacade.GetInstance.DBGates.Add(Self); ds.FieldByName('WELL_UIN').AsInteger := o.Collection.Owner.ID; ds.FieldByName('FINANCE_SOURCE_ID').AsInteger := o.ID; ds.Post; end; procedure TFinanceSourceWellDataPoster.SetAllFinanceSources( const Value: TFinanceSources); begin if FAllFinanceSources <> Value then FAllFinanceSources := Value; end; end.
unit Server.Models.Cadastros.Contatos; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('CONTATOS','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TContatos = class(TTabelaBase) private fEMAIL: String; fCARGO: Integer; fNOME: String; fAREA_DIRETO: String; fAREA_CEL: String; fFONE_DIRETO: String; fFONE_RESIDENCIAL: String; fCLIENTE: Integer; fTIME_FUTEBOL: String; fAREA_RESI: String; fANIVERSARIO: TDate; fFILHOS: Integer; fSEXO: String; fTRATAMENTO: String; fCELULAR: String; fCARGO_DESCRICAO: String; function Getid: Integer; procedure Setid(const Value: Integer); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('NOME', ftString, 100)] [Dictionary('NOME','Mensagem de validação','','','',taLeftJustify)] property NOME: String read fNOME write fNOME; [Column('CARGO', ftInteger)] property CARGO:Integer read fCARGO write fCARGO; [Column('EMAIL', ftString, 150)] property EMAIL:String read fEMAIL write fEMAIL; [Column('AREA_DIRETO', ftString, 5)] property AREA_DIRETO:String read fAREA_DIRETO write fAREA_DIRETO; [Column('AREA_CEL', ftString, 5)] property AREA_CEL:String read fAREA_CEL write fAREA_CEL; [Column('AREA_RESI', ftString, 5)] property AREA_RESI:String read fAREA_RESI write fAREA_RESI; [Column('FONE_DIRETO', ftString, 10)] property FONE_DIRETO:String read fFONE_DIRETO write fFONE_DIRETO; [Column('CELULAR', ftString, 10)] property CELULAR:String read fCELULAR write fCELULAR; [Column('FONE_RESIDENCIAL', ftString, 10)] property FONE_RESIDENCIAL:String read fFONE_RESIDENCIAL write fFONE_RESIDENCIAL; [Column('ANIVERSARIO', ftDate)] property ANIVERSARIO:TDate read fANIVERSARIO write fANIVERSARIO; [Column('TIME_FUTEBOL', ftString, 80)] property TIME_FUTEBOL:String read fTIME_FUTEBOL write fTIME_FUTEBOL; [Column('SEXO', ftString, 1)] property SEXO:String read fSEXO write fSEXO; [Column('FILHOS', ftInteger)] property FILHOS:Integer read fFILHOS write fFILHOS; [Column('CLIENTE', ftInteger)] property CLIENTE:Integer read fCLIENTE write fCLIENTE; [Column('TRATAMENTO', ftString, 50)] property TRATAMENTO:String read fTRATAMENTO write fTRATAMENTO; property CARGO_DESCRICAO:String read fCARGO_DESCRICAO write fCARGO_DESCRICAO; end; implementation { TCONTATOS } constructor TContatos.create; begin end; destructor TContatos.destroy; begin inherited; end; function TContatos.Getid: Integer; begin Result := fid; end; procedure TContatos.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TContatos); end.
unit NovusFileUtils; interface uses StrUtils, NovusUtilities, Windows, SysUtils, SHFolder, ShellApi, ShlObj; Type TNovusFileUtils = class(tNovusUtilities) public class function IsFileInUse(fName : string) : boolean; class function IsFileReadonly(fName : string) : boolean; class function MoveDir(aFromDirectory, aToDirectory: String): Boolean; class function CopyDir(aFromDirectory, aToDirectory: String): Boolean; class function AbsoluteFilePath(aFilename: String): String; class function TrailingBackSlash(const aFilename: string): string; class function GetSpecialFolder(const CSIDL: integer) : string; end; function PathCombine(lpszDest: PChar; const lpszDir, lpszFile: PChar):PChar; stdcall; external 'shlwapi.dll' name 'PathCombineA'; implementation class function TNovusFileUtils.IsFileReadonly(fName : string) : boolean; var HFileRes : HFILE; Res: string[6]; function CheckAttributes(FileNam: string; CheckAttr: string): Boolean; var fa: Integer; begin fa := GetFileAttributes(PChar(FileNam)) ; Res := ''; if (fa and FILE_ATTRIBUTE_NORMAL) <> 0 then begin Result := False; Exit; end; if (fa and FILE_ATTRIBUTE_ARCHIVE) <> 0 then Res := Res + 'A'; if (fa and FILE_ATTRIBUTE_COMPRESSED) <> 0 then Res := Res + 'C'; if (fa and FILE_ATTRIBUTE_DIRECTORY) <> 0 then Res := Res + 'D'; if (fa and FILE_ATTRIBUTE_HIDDEN) <> 0 then Res := Res + 'H'; if (fa and FILE_ATTRIBUTE_READONLY) <> 0 then Res := Res + 'R'; if (fa and FILE_ATTRIBUTE_SYSTEM) <> 0 then Res := Res + 'S'; Result := AnsiContainsText(Res, CheckAttr) ; end; (*CheckAttributes*) procedure SetAttr(fName: string) ; var Attr: Integer; begin Attr := 0; if AnsiContainsText(Res, 'A') then Attr := Attr + FILE_ATTRIBUTE_ARCHIVE; if AnsiContainsText(Res, 'C') then Attr := Attr + FILE_ATTRIBUTE_COMPRESSED; if AnsiContainsText(Res, 'D') then Attr := Attr + FILE_ATTRIBUTE_DIRECTORY; if AnsiContainsText(Res, 'H') then Attr := Attr + FILE_ATTRIBUTE_HIDDEN; if AnsiContainsText(Res, 'S') then Attr := Attr + FILE_ATTRIBUTE_SYSTEM; SetFileAttributes(PChar(fName), Attr) ; end; (*SetAttr*) begin //IsFileInUse Result := False; if not FileExists(fName) then exit; Result := CheckAttributes(fName, 'R'); end; class function TNovusFileUtils.IsFileInUse(fName : string) : boolean; var HFileRes: HFILE; begin Result := False; if not FileExists(fName) then begin Exit; end; HFileRes := CreateFile(PChar(fName) ,GENERIC_READ or GENERIC_WRITE ,0 ,nil ,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL ,0); Result := (HFileRes = INVALID_HANDLE_VALUE); if not(Result) then begin CloseHandle(HFileRes); end; end; class function TNovusFileUtils.MoveDir(aFromDirectory, aToDirectory: String): Boolean; var fos: TSHFileOpStruct; begin ZeroMemory(@fos, SizeOf(fos)); with fos do begin wFunc := FO_MOVE; fFlags := FOF_FILESONLY; pFrom := PChar(aFromDirectory + #0); pTo := PChar(aToDirectory) end; Result := (0 = ShFileOperation(fos)); end; class function TNovusFileUtils.CopyDir(aFromDirectory, aToDirectory: String): Boolean; var fos: TSHFileOpStruct; begin ZeroMemory(@fos, SizeOf(fos)); with fos do begin wFunc := FO_COPY; fFlags := FOF_FILESONLY; pFrom := PChar(aFromDirectory + #0); pTo := PChar(aToDirectory) end; Result := (0 = ShFileOperation(fos)); end; class function TNovusFileUtils.AbsoluteFilePath(aFilename: String): String; var lpFileName : pchar; lpBuffer : array[0..MAX_PATH] of char; cResult: Cardinal; begin lpFileName := PCHAR(aFilename); cResult := GetFullPathName(lpFileName , MAX_PATH, lpBuffer, lpFileName ); result := ExtractFilePath(lpBuffer); end; class function TNovusFileUtils.TrailingBackSlash(const aFilename: string): string; begin Result := ''; if Trim(aFilename) <> '' then Result := IncludeTrailingPathDelimiter(aFilename); end; class function TNovusFileUtils.GetSpecialFolder(const CSIDL: integer) : string; var RecPath : PWideChar; begin RecPath := StrAlloc(MAX_PATH); try FillChar(RecPath^, MAX_PATH, 0); if SHGetSpecialFolderPath(0, RecPath, CSIDL, false) then result := RecPath else result := ''; finally StrDispose(RecPath); end; end; end.
unit frmMainUnit; { NNTP Client Demo The program is intended to show the very basic nntp client capabilities. That is, listing groups, downloading headers, reading articles and posting both new and follow up articles. Articles are not sorted in any way. This demo has been kept single-threaded, since threading is not the issue here. by Asbjørn Heid (AH) History 26 july 1999 - Added message indenting, body has to be downloaded for this to work (AH) 15 july 1999 - Initial release (AH) } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, StdCtrls, Winshoes, WinshoeMessage, NNTPWinshoe, Menus, frmPropertiesUnit, frmArticleUnit, fileio; type TfrmMain = class(TForm) wsNNTP: TWinshoeNNTP; lbGroups: TListBox; Label1: TLabel; Label2: TLabel; lwMessages: TListView; ilFolders: TImageList; ilToolbar: TImageList; mnuMain: TMainMenu; mnuFile: TMenuItem; mnuGroup: TMenuItem; mnuMessage: TMenuItem; mnuExit: TMenuItem; mnuGetGroups: TMenuItem; mnuGetHeaders: TMenuItem; mnuGetBodies: TMenuItem; N1: TMenuItem; mnuNewFollowUp: TMenuItem; mnuOnline: TMenuItem; mnuConnect: TMenuItem; mnuProperties: TMenuItem; sbNews: TStatusBar; memoMsg: TMemo; mnuNewArticle: TMenuItem; mnuDisconnect: TMenuItem; procedure mnuConnectClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure wsNNTPStatus(Sender: TComponent; const sOut: String); procedure wsNNTPNewsgroupList(const sNewsgroup: String; const lLow, lHigh: Cardinal; const sType: String; var CanContinue: Boolean); procedure FormCreate(Sender: TObject); procedure lwMessagesDblClick(Sender: TObject); procedure lwMessagesDeletion(Sender: TObject; Item: TListItem); procedure lbGroupsDblClick(Sender: TObject); procedure mnuDisconnectClick(Sender: TObject); procedure mnuPropertiesClick(Sender: TObject); procedure mnuExitClick(Sender: TObject); procedure mnuGetGroupsClick(Sender: TObject); procedure mnuGetHeadersClick(Sender: TObject); procedure mnuGetBodiesClick(Sender: TObject); procedure mnuNewArticleClick(Sender: TObject); procedure mnuNewFollowUpClick(Sender: TObject); procedure wsNNTPWork(Sender: TComponent; const plWork, plWorkSize: Integer); private { Private declarations } FCanContinue: boolean; FCurrentGroup: string; procedure DisableOnlineActions; procedure EnableOnlineActions; procedure DisableGroupActions; procedure EnableGroupActions; procedure DisableMessageActions; procedure EnableMessageActions; procedure AddMessageItem(const wsMsg: TWinshoeMessage); procedure SetServerValues; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.DFM} const OnlineStatus: array[boolean] of string = ('Offline', 'Online'); MSG_IMG_BODY = 4; MSG_IMG_HEADER = 3; procedure TfrmMain.mnuGetGroupsClick(Sender: TObject); begin lbGroups.Clear; FCanContinue:= True; wsNNTP.GetNewsgroupList; wsNNTP.DoStatus('Finished retrieving groups'); end; procedure TfrmMain.wsNNTPNewsgroupList(const sNewsgroup: String; const lLow, lHigh: Cardinal; const sType: String; var CanContinue: Boolean); begin lbGroups.Items.Add(sNewsgroup); CanContinue:= FCanContinue; end; procedure TfrmMain.AddMessageItem(const wsMsg: TWinshoeMessage); var item: TListItem; begin item:= lwMessages.Items.Add; item.SubItems.Add(wsMsg.Subject); item.SubItems.Add(wsMsg.From); item.SubItems.Add(FormatDateTime('dd.mm.yy hh:mm', wsMsg.Date)); item.Data:= wsMsg; item.ImageIndex:= MSG_IMG_HEADER; end; procedure TfrmMain.lwMessagesDblClick(Sender: TObject); // view article body var item: TListItem; begin // in case we're not supposed to do anything if not mnuGroup.Enabled then exit; item:= lwMessages.Selected; if not Assigned(item) then exit; // if we just got the header, retrive body if item.ImageIndex = MSG_IMG_HEADER then begin // get body if we need to // might fail if message isnt found for some reason mnuGetBodies.Click; end; // display body if we got one (retrival might have // failed, and we'll have nothing to show) if item.ImageIndex = MSG_IMG_BODY then begin memoMsg.Clear; memoMsg.Lines.AddStrings(TWinshoeMessage(item.data).Text); end; end; procedure TfrmMain.lwMessagesDeletion(Sender: TObject; Item: TListItem); begin // free the message object we've created if Assigned(Item.Data) then TWinshoeMessage(Item.Data).Free; end; procedure TfrmMain.mnuGetHeadersClick(Sender: TObject); var wsMsg: TWinshoeMessage; r: boolean; begin if lbGroups.ItemIndex < 0 then // if no group selected exit; DisableOnlineActions; lwMessages.Items.Clear; // select group FCurrentGroup:= lbGroups.Items[lbGroups.ItemIndex]; wsNNTP.SelectGroup(FCurrentGroup); // select the first article in the group r:= wsNNTP.SelectArticle(wsNNTP.MsgLow); wsMsg:= TWinshoeMessage.Create(nil); wsMsg.ExtractAttachments:= false; while r do begin wsNNTP.DoStatus('Retrieving header of article no. ' + IntToStr(wsNNTP.MsgNo)); if wsNNTP.GetHeader(wsNNTP.MsgNo, '', wsMsg) then begin // if we find the article, add it to the list // the message object will be associated with the icon AddMessageItem(wsMsg); // we'll need a new message object wsMsg:= TWinshoeMessage.Create(nil); wsMsg.ExtractAttachments:= false; end; // as Rutger Hauer so elegantly put it: NEXT! r:= wsNNTP.Next; end; wsMsg.Free; EnableOnlineActions; end; procedure TfrmMain.mnuGetBodiesClick(Sender: TObject); var i: integer; item: TListItem; wsMsg: TWinshoeMessage; begin for i:= 0 to lwMessages.Items.Count-1 do begin item:= lwMessages.Items[i]; if item.Selected then begin wsMsg:= TWinshoeMessage(Item.Data); wsNNTP.DoStatus('Retrieved body of article no. ' + IntToStr(wsMsg.MsgNo)); // the msgID is in the form <id>, but the GetBody expects it to just be the id, // so we need to strip it if wsNNTP.GetBody(0, Copy(wsMsg.MsgID, 2, length(wsMsg.MsgID)-2), wsMsg) then // show that we successfully got the body item.ImageIndex:= MSG_IMG_BODY; end; end; end; procedure TfrmMain.mnuNewArticleClick(Sender: TObject); begin with frmArticle do begin // setup the message object wsMessage.Clear; editNewsgroups.Text:= FCurrentGroup; end; if frmArticle.ShowModal = 1 then begin // DisableOnlineActions; wsNNTP.Send(frmArticle.wsMessage); EnableOnlineActions; end; end; procedure TfrmMain.mnuNewFollowUpClick(Sender: TObject); procedure IndentMessage(wsNew, wsOriginal: TWinshoeMessage; indent: string); var i: integer; begin if wsOriginal.Text.Text = '' then exit; wsNew.Text.Add(wsOriginal.From + ' wrote:'); for i:= 0 to wsOriginal.Text.Count-1 do wsNew.Text.Add(indent + wsOriginal.Text.Strings[i]); end; var item: TListItem; wsOriginalMsg: TWinshoeMessage; begin item:= lwMessages.Selected; if not Assigned (item) then exit; wsOriginalMsg:= TWinshoeMessage(item.data); with frmArticle do begin // setup the message object wsMessage.Clear; editNewsgroups.Text:= FCurrentGroup; // since this is a follow-up we must build the reference field // and subject line if wsOriginalMsg.References = '' then begin // we're replying to a original post here, so we must create // the reference field by inserting the msgID of the original wsMessage.References:= wsOriginalMsg.MsgID; editSubject.Text:= 'RE: ' + wsOriginalMsg.Subject; IndentMessage(wsMessage, wsOriginalMsg, '> '); end else begin // this is a follow-up to a follow-up, add the msgID to the end // of the chain, also assume there's a re: there wsMessage.References:= wsOriginalMsg.References + ' ' + wsOriginalMsg.MsgID; editSubject.Text:= wsOriginalMsg.Subject; IndentMessage(wsMessage, wsOriginalMsg, '>'); end; // so we can see the previous post memoArticle.Lines:= wsMessage.Text; end; if frmArticle.ShowModal = 1 then begin DisableOnlineActions; wsNNTP.Send(frmArticle.wsMessage); EnableOnlineActions; end; end; procedure TfrmMain.mnuConnectClick(Sender: TObject); begin try SetServerValues; wsNNTP.Connect; mnuConnect.Enabled:= False; mnuDisconnect.Enabled:= True; mnuGetGroups.Click; EnableGroupActions; finally end; end; procedure TfrmMain.mnuDisconnectClick(Sender: TObject); begin try wsNNTP.Disconnect; mnuConnect.Enabled:= True; mnuDisconnect.Enabled:= False; DisableOnlineActions; finally // connect might not have successfull, so show currect status end; end; procedure TfrmMain.mnuPropertiesClick(Sender: TObject); begin frmProperties.ShowModal; end; procedure TfrmMain.mnuExitClick(Sender: TObject); begin Close; end; procedure TfrmMain.SetServerValues; begin with frmProperties do begin wsNNTP.Host:= Server; wsNNTP.Port:= Port; wsNNTP.UserID:= UserName; wsNNTP.Password:= Password; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin DisableOnlineActions; end; procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if wsNNTP.Connected then wsNNTP.Disconnect; CanClose:= not wsNNTP.Connected; end; procedure TfrmMain.lbGroupsDblClick(Sender: TObject); begin mnuGetHeaders.Click; end; procedure TfrmMain.DisableGroupActions; begin mnuGroup.Enabled:= false; end; procedure TfrmMain.EnableGroupActions; begin mnuGroup.Enabled:= true; end; procedure TfrmMain.DisableMessageActions; begin mnuMessage.Enabled:= false; end; procedure TfrmMain.EnableMessageActions; begin mnuMessage.Enabled:= true; end; procedure TfrmMain.DisableOnlineActions; begin // make sure user is unable to issue other commands DisableGroupActions; DisableMessageActions; end; procedure TfrmMain.EnableOnlineActions; begin EnableGroupActions; EnableMessageActions; end; procedure TfrmMain.wsNNTPWork(Sender: TComponent; const plWork, plWorkSize: Integer); begin // so that the client doesnt lock up when we retrive data Application.ProcessMessages; end; procedure TfrmMain.wsNNTPStatus(Sender: TComponent; const sOut: String); begin sbNews.Panels[0].Text:= sOut; sbNews.Panels[1].Text:= OnlineStatus[wsNNTP.Connected]; Application.ProcessMessages; end; end.
unit WatcherUnit; interface uses Windows, Forms, Controls, Classes, IniFiles, SysUtils, BeChatView, Common, Menus, ExtCtrls; type TWatcher = class(TChatView) private fPopupMenu: TPopupMenu; StayTopTimer: TTimer; fMonitor: Integer; function GetLastWorld: string; procedure StayTopTimerTimer(Sender: TObject); procedure SetOnTop; public procedure LoadTheme; procedure Activate; procedure CreateParams(var Params: TCreateParams); override; constructor Create(AOwner: TComponent); override; procedure ChatViewClick(Sender: TObject); procedure AddWatch(const World, Line: string); function WorldIsActive: Boolean; procedure SwitchToWorld; procedure SwitchBack; procedure DoMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); property PopupMenu: TPopupMenu read fPopupMenu write fPopupMenu; property Monitor: Integer read fMonitor write fMonitor; end; var Watcher: TWatcher; procedure TellWatcher(const World, Line: string); implementation uses MainFrm, ClientPage, UpdateCheck; var LastWorld, LastLine: string; procedure TellWatcher(const World, Line: string); begin LastWorld:=World; LastLine:=Line; if Watcher<>nil then Watcher.AddWatch(World,Line); end; { TWatcher } constructor TWatcher.Create(AOwner: TComponent); begin inherited Create(AOwner); StayTopTimer:=TTimer.Create(Self); with StayTopTimer do begin Interval:=1000; OnTimer:=StayTopTimerTimer; Enabled:=True; end; fPopupMenu:=nil; // Top:=0; Left:=150; Width:=Screen.DesktopWidth-250; Top:=Screen.Monitors[fMonitor].Top; Left:=Screen.Monitors[fMonitor].Left + 150; Width:=Screen.Monitors[fMonitor].Width-350; OnClick:=ChatViewClick; OnMouseUp:=DoMouseUp; LoadTheme; if LastWorld<>'' then AddWatch(LastWorld,LastLine) else AddLine('Beryllium Engineering Moops! '+UpdChecker.ThisVersion); end; procedure TWatcher.SetOnTop; begin SetWindowPos(Handle, HWND_TOPMOST, Left, Top, Width, Height, SWP_SHOWWINDOW or SWP_NOACTIVATE); end; procedure TWatcher.Activate; begin SetOnTop; Invalidate; end; procedure TWatcher.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := WS_POPUP; if NewStyleControls then ExStyle := WS_EX_TOOLWINDOW; AddBiDiModeExStyle(ExStyle); end; end; procedure TWatcher.AddWatch(const World, Line: string); begin AddLine('['+World+'] '+Line); end; procedure TWatcher.LoadTheme; var Ini: TIniFile; FileName: string; begin FileName:=AppDir+'Themes\watcher.mth'; if FileExists(FileName) then begin Ini:=TIniFile.Create(FileName); try LoadFromIni(Ini); finally Ini.Free; end; end; WordWrap:=0; HorizScrollBar:=False; FollowMode:=cfOn; EnableBeep:=False; DisableSelect:=True; Height:=CharHeight+4; end; procedure TWatcher.ChatViewClick(Sender: TObject); begin {if WorldIsActive then SwitchBack else} // SwitchToWorld; end; procedure TWatcher.SwitchBack; begin //Beep; SetForegroundWindow(GetWindow(Application.Handle,GW_HWNDNEXT)); end; function TWatcher.WorldIsActive: Boolean; begin Result:=Application.Active {and MainForm.Active} and (MainForm.CurPage<>nil) and (MainForm.CurPage.Caption=GetLastWorld); end; procedure TWatcher.SwitchToWorld; var S: string; I: Integer; begin Application.BringToFront; S:=GetLastWorld; if S='' then Exit; with MainForm do begin for I:=0 to ClientPages.Count-1 do if TNetClientPage(ClientPages[I]).Caption=S then begin ActivatePage(ClientPages[I]); Exit; end; Activate; end; end; procedure TWatcher.DoMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button=mbRight) and Assigned(PopupMenu) then begin StayTopTimer.Interval:=20000; // Otherwise the Watcher will get // on top of the menu... PopupMenu.Popup(X,Y); end else if Focused then // Don't leave this window active SwitchBack; end; function TWatcher.GetLastWorld: string; begin if ActLineCount=0 then begin Result:=''; Exit; end; Result:=GetLineText(TopLine); Result:=Copy(Result,2,Pos(']',Result)-2); end; procedure TWatcher.StayTopTimerTimer(Sender: TObject); begin StayTopTimer.Interval:=1000; // because of popup-menu SetOnTop; end; end.
unit keyhookcode; interface uses Windows, Winapi.Messages; function StartMouseIMEHook(hWnd: hWnd): Boolean; stdcall; procedure StopMouseIMEHook; stdcall; implementation type PHookInfo = ^THookInfo; THookInfo = record HookMouse: HHook; HookIME: HHook; HostWnd: hWnd; end; var hMapFile: THandle; const MapFileName = 'keyhook'; function MapFileMemory(out hMap: THandle; out pMap: Pointer): integer; begin hMap := OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MapFileName); if hMap = 0 then begin result := -1; Exit; end; pMap := MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); if pMap = nil then begin result := -2; CloseHandle(hMap); Exit; end; result := 0; end; procedure UnMapFileMemory(hMap: THandle; pMap: Pointer); begin if pMap <> nil then UnMapViewOfFile(pMap); if hMap <> 0 then CloseHandle(hMap); end; function MouseHookProc(nCode: integer; wPar: WPARAM; lPar: LPARAM) : LRESULT; stdcall; var lpMap: Pointer; LMapWnd: THandle; msg: PMsg; begin result := 0; if MapFileMemory(LMapWnd, lpMap) = 0 then Exit; msg := PMsg(lPar); if (nCode = HC_ACTION) and (wPar = PM_REMOVE) then if msg.hWnd <> PHookInfo(lpMap)^.HostWnd then PostMessage(PHookInfo(lpMap)^.HostWnd, WM_APP, msg.message, msg.hWnd); result := CallNextHookEx(PHookInfo(lpMap)^.HookMouse, nCode, wPar, lPar); UnMapFileMemory(LMapWnd, lpMap); end; function IMEHookProc(nCode: integer; wPar: WPARAM; lPar: LPARAM) : LRESULT; stdcall; var lpMap: Pointer; LMapWnd: THandle; msg: PMsg; begin result := 0; if MapFileMemory(LMapWnd, lpMap) = 0 then Exit; msg := PMsg(lPar); if (nCode = HC_ACTION) and (wPar = PM_REMOVE) then if msg.hWnd <> PHookInfo(lpMap)^.HostWnd then PostMessage(PHookInfo(lpMap)^.HostWnd, WM_APP + 1, msg.message, msg.hWnd); result := CallNextHookEx(PHookInfo(lpMap)^.HookIME, nCode, wPar, lPar); UnMapFileMemory(LMapWnd, lpMap); end; function StartMouseIMEHook(hWnd: hWnd): Boolean; stdcall; var lpMap: Pointer; LMapWnd: THandle; begin result := false; MapFileMemory(LMapWnd, lpMap); if lpMap = nil then begin LMapWnd := 0; Exit; end; with PHookInfo(lpMap)^ do begin HostWnd := hWnd; HookMouse := SetWindowsHookEx(WH_MOUSE, Addr(MouseHookProc), hInstance, 0); HookIME := SetWindowsHookEx(WH_CALLWNDPROC, Addr(IMEHookProc), hInstance, 0); if (HookMouse > 0) and (HookIME > 0) then result := true; end; UnMapFileMemory(LMapWnd, lpMap); end; procedure StopMouseIMEHook; stdcall; var lpMap: Pointer; LMapWnd: THandle; begin MapFileMemory(LMapWnd, lpMap); if lpMap = nil then Exit; if PHookInfo(lpMap)^.HookMouse > 0 then UnHookWindowsHookEx(PHookInfo(lpMap)^.HookMouse); if PHookInfo(lpMap)^.HookIME > 0 then UnHookWindowsHookEx(PHookInfo(lpMap)^.HookIME); UnMapFileMemory(LMapWnd, lpMap); end; initialization hMapFile := CreateFileMapping(High(NativeUInt), nil, PAGE_READWRITE, 0, SizeOf(THookInfo), MapFileName); finalization if hMapFile <> 0 then CloseHandle(hMapFile); end.
program Degrees; var cel: Real; fahr: Real; kelv: Real; begin writeln('Please enter the temperature in C degrees'); readln(cel); fahr := (cel* 1.8) + 32; kelv := cel + 272.15; writeln('Fahrenheit ', fahr:0:2, ' F'); writeln('Kelvin ', kelv:0:2, ' K'); readln(); end.
unit UNum_Test; interface Uses sysutils, TestFramework, TestExtensions, GUITesting; type TNum_Test = class(TGUITestCase) private protected public published procedure Test_Roman; procedure Test_Decimal; end; implementation uses uNum; type TData = record roman: string; num: integer; end; const TestData : array [1..3] of TData = ( (roman: 'I' ; num: 1), (roman: 'II' ; num: 2), (roman: 'III'; num: 3) ); procedure TNum_Test.Test_Decimal; begin CheckEquals(1, toDec('I')); end; procedure TNum_Test.Test_Roman; begin CheckEquals('I', toRoman(1)); CheckEquals('II', toRoman(2)); CheckEquals('III', toRoman(3)); CheckEquals('IV', toRoman(4)); CheckEquals('V', toRoman(5)); CheckEquals('VI', toRoman(6)); CheckEquals('VII', toRoman(7)); CheckEquals('VIII', toRoman(8)); CheckEquals('IX', toRoman(9)); CheckEquals('X', toRoman(10)); CheckEquals('XI', toRoman(11)); CheckEquals('XII', toRoman(12)); CheckEquals('XIII', toRoman(13)); CheckEquals('XIV', toRoman(14)); CheckEquals('XV', toRoman(15)); CheckEquals('XVII', toRoman(17)); CheckEquals('XIX', toRoman(19)); CheckEquals('XX', toRoman(20)); CheckEquals('XXI', toRoman(21)); CheckEquals('XXXVI', toRoman(36)); CheckEquals('XLI', toRoman(41)); CheckEquals('XLVI', toRoman(46)); CheckEquals('XLIX', toRoman(49)); CheckEquals('L', toRoman(50)); CheckEquals('LII', toRoman(52)); CheckEquals('LIX', toRoman(59)); CheckEquals('LX', toRoman(60)); CheckEquals('XCIX', toRoman(99)); CheckEquals('C', toRoman(100)); CheckEquals('D', toRoman(500)); CheckEquals('M', toRoman(1000)); CheckEquals('MCMXCIX', toRoman(1999)); CheckEquals('MMDCCLI', toRoman(2751)); CheckEquals('MMM', toRoman(3000)); end; initialization TestFramework.RegisterTest('', TNum_Test.Suite); end.
unit GLStrings; interface resourcestring // SceneViewer glsNoRenderingContext = 'Could not create a rendering context'; glsWrongVersion = 'Need at least OpenGL version 1.1'; glsTooManyLights = 'Too many lights in the scene'; glsDisplayList = 'Failed to create a new display list for object ''%s'''; glsWrongBitmapCanvas = 'Couldn''t create a rendering context for the given bitmap'; glsWrongPrinter = 'Couldn''t render to printer'; glsAlreadyRendering = 'Already rendering'; // GLTree glsSceneRoot = 'Scene root'; glsObjectRoot = 'Scene objects'; glsCameraRoot = 'Cameras'; glsCamera = 'Camera'; // GLTexture glsImageInvalid = 'Could not load texture, image is invalid'; glsNoNewTexture = 'Could not get new texture name'; // GLObjects glsSphereTopBottom = 'The top angle must be higher than the bottom angle'; glsSphereStartStop = 'The start angle must be smaller than then stop angle'; glsMaterialNotFound = 'Loading failed: could not find material %s'; glsInterleaveNotSupported = 'Interleaved Array format not supported yet. Sorry.'; // common messages glsOutOfMemory = 'Fatal: Out of memory'; glsFailedOpenFile = 'Could not open file: %s'; glsNoDescriptionAvailable = 'No description available'; glsUnBalancedBeginEndUpdate = 'Unbalanced Begin/EndUpdate'; // object categories glsOCBasicGeometry = 'Basic geometry'; glsOCAdvancedGeometry = 'Advanced geometry'; glsOCMeshObjects = 'Mesh objects'; glsOCProceduralObjects = 'Procedural objects'; glsOCSpecialObjects = 'Special objects'; glsOCGraphPlottingObjects = 'Graph-plotting objects'; glsOCHUDObjects = 'HUD objects'; implementation end.
{ p_37_2.pas - ввод и вывод числового множества } program p_37_2; type tSet = set of 1..255; { объявление типа "множество" } {----- Процедура чтения множества из файла -----} procedure ReadSet(var aFile: text; var aSet: tSet); var k: integer; begin while not Eoln(aFile) do begin { пока не конец строки } Read(aFile, k); { читаем очередное число } aSet := aSet + [k]; { и добавляем к множеству } end; Readln(aFile); { переход на следующую строку } end; {----- Процедура вывода множества в файл -----} procedure WriteSet(var aFile: text; const aSet: tSet); var k: integer; begin for k:=1 to 255 do { цикл по всем элементам множества } if k in aSet then { если k входит в множество } Write(aFile, k:4); { печатаем в строке } Writeln(aFile); { по окончании - переход на следующую строку } end; {----- Программа для проверки процедуры ввода -----} var s1: tSet; f, d: text; begin Assign(f, ''); { вывод на экран } Rewrite(f); Assign(d, ''); { ввод с клавиатуры } Reset(d); ReadSet(d, s1); { вводим множество из файла } WriteSet(f, s1); { печатаем } Close(f); Close(d); end.
unit Expedicao.Interfaces.uInfracaoPersistencia; interface uses System.Generics.Collections, Expedicao.Models.uInfracao; type IInfracaoPersistencia = interface ['{19E90F0C-754F-4C0D-9F01-265C67473511}'] function ObterListaInfracao: TList<TInfracao>; function ObterInfracao(pInfracaoOID: Integer): TInfracao; function IncluirInfracao(pInfracao: TInfracao): Boolean; function AlterarInfracao(pInfracao: TInfracao): Boolean; function ExcluirInfracao(pInfracaoOID: Integer): Boolean; end; implementation end.
unit mwMooSyn; {$I mwEdit.inc} interface uses SysUtils, Windows, Messages, Classes, Controls, Graphics, Registry, mwHighlighter, mwExport, mwLocalStr; Type TmoTokenKind = ( moBuiltinFunc, moComment, moKeyword, moNull, moNumber, moObject, moDollarRef, moSpace, moString, moSymbol, moUnknown, moVariable); TRangeState = (rsUnknown); TProcTableProc = procedure of Object; PIdentFuncTableFunc = ^TIdentFuncTableFunc; TIdentFuncTableFunc = function: TmoTokenKind of Object; type TmwMOOSyntax = class(TmwCustomHighLighter) private fRange: TRangeState; fLine: PChar; fLineNumber: Integer; fExporter: TmwCustomExport; fProcTable: array[#0..#255] of TProcTableProc; Run: LongInt; fStringLen: Integer; fToIdent: PChar; fTokenPos: Integer; FTokenID: TmoTokenKind; fIdentFuncTable: array[0..126] of TIdentFuncTableFunc; fCommentAttri: TmwHighLightAttributes; fKeywordAttri: TmwHighLightAttributes; fNumberAttri: TmwHighLightAttributes; fObjectAttri: TmwHighLightAttributes; fDollarRefAttri: TmwHighLightAttributes; fSpaceAttri: TmwHighLightAttributes; fStringAttri: TmwHighLightAttributes; fSymbolAttri: TmwHighLightAttributes; fVariableAttri: TmwHighLightAttributes; fBuiltinFuncAttri: TmwHighLightAttributes; fStringIsComment: Boolean; function KeyHash(ToHash: PChar): Integer; function KeyComp(const aKey: String): Boolean; function Func0: TmoTokenKind; function Func1: TmoTokenKind; function Func2: TmoTokenKind; function Func6: TmoTokenKind; function Func8: TmoTokenKind; function Func10: TmoTokenKind; function Func12: TmoTokenKind; function Func13: TmoTokenKind; function Func15: TmoTokenKind; function Func16: TmoTokenKind; function Func17: TmoTokenKind; function Func18: TmoTokenKind; function Func22: TmoTokenKind; function Func23: TmoTokenKind; function Func24: TmoTokenKind; function Func25: TmoTokenKind; function Func26: TmoTokenKind; function Func27: TmoTokenKind; function Func28: TmoTokenKind; function Func29: TmoTokenKind; function Func30: TmoTokenKind; function Func32: TmoTokenKind; function Func33: TmoTokenKind; function Func34: TmoTokenKind; function Func35: TmoTokenKind; function Func36: TmoTokenKind; function Func37: TmoTokenKind; function Func38: TmoTokenKind; function Func39: TmoTokenKind; function Func40: TmoTokenKind; function Func41: TmoTokenKind; function Func42: TmoTokenKind; function Func43: TmoTokenKind; function Func45: TmoTokenKind; function Func46: TmoTokenKind; function Func47: TmoTokenKind; function Func48: TmoTokenKind; function Func49: TmoTokenKind; function Func50: TmoTokenKind; function Func51: TmoTokenKind; function Func52: TmoTokenKind; function Func53: TmoTokenKind; function Func55: TmoTokenKind; function Func56: TmoTokenKind; function Func57: TmoTokenKind; function Func60: TmoTokenKind; function Func62: TmoTokenKind; function Func63: TmoTokenKind; function Func65: TmoTokenKind; function Func66: TmoTokenKind; function Func69: TmoTokenKind; function Func70: TmoTokenKind; function Func71: TmoTokenKind; function Func73: TmoTokenKind; function Func74: TmoTokenKind; function Func75: TmoTokenKind; function Func76: TmoTokenKind; function Func78: TmoTokenKind; function Func79: TmoTokenKind; function Func80: TmoTokenKind; function Func81: TmoTokenKind; function Func82: TmoTokenKind; function Func83: TmoTokenKind; function Func85: TmoTokenKind; function Func86: TmoTokenKind; function Func87: TmoTokenKind; function Func89: TmoTokenKind; function Func92: TmoTokenKind; function Func94: TmoTokenKind; function Func95: TmoTokenKind; function Func96: TmoTokenKind; function Func98: TmoTokenKind; function Func99: TmoTokenKind; function Func100: TmoTokenKind; function Func101: TmoTokenKind; function Func104: TmoTokenKind; function Func105: TmoTokenKind; function Func108: TmoTokenKind; function Func111: TmoTokenKind; function Func112: TmoTokenKind; function Func114: TmoTokenKind; function Func115: TmoTokenKind; function Func116: TmoTokenKind; function Func121: TmoTokenKind; function Func122: TmoTokenKind; function Func123: TmoTokenKind; function Func124: TmoTokenKind; function Func126: TmoTokenKind; procedure SlashProc; procedure DollarProc; procedure HashMarkProc; procedure IdentProc; procedure NumberProc; procedure NullProc; procedure SpaceProc; procedure StringProc; procedure SymbolProc; procedure UnknownProc; function AltFunc: TmoTokenKind; procedure InitIdent; function IdentKind(MayBe: PChar): TmoTokenKind; procedure MakeMethodTables; function FindBracket: Boolean; // used for IdentKind protected function GetIdentChars: TIdentChars; override; function GetLanguageName: string; override; function GetCapability: THighlighterCapability; override; public constructor Create(AOwner: TComponent); override; function GetEOL: Boolean; override; function GetRange: Pointer; override; function GetTokenID: TmoTokenKind; procedure SetLine(NewValue: String; LineNumber: Integer); override; procedure ExportNext; override; procedure SetLineForExport(NewValue: String); override; function GetToken: String; override; function GetTokenAttribute: TmwHighLightAttributes; override; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; procedure Next; override; procedure SetRange(Value: Pointer); override; procedure ReSetRange; override; property IdentChars; published property CommentAttri: TmwHighLightAttributes read fCommentAttri write fCommentAttri; property KeywordAttri: TmwHighLightAttributes read fKeywordAttri write fKeywordAttri; property NumberAttri: TmwHighLightAttributes read fNumberAttri write fNumberAttri; property ObjectAttri: TmwHighLightAttributes read fObjectAttri write fObjectAttri; property DollarRefAttri: TmwHighLightAttributes read fDollarRefAttri write fDollarRefAttri; property SpaceAttri: TmwHighLightAttributes read fSpaceAttri write fSpaceAttri; property StringAttri: TmwHighLightAttributes read fStringAttri write fStringAttri; property SymbolAttri: TmwHighLightAttributes read fSymbolAttri write fSymbolAttri; property VariableAttri: TmwHighLightAttributes read fVariableAttri write fVariableAttri; property BuiltinFuncAttri: TmwHighLightAttributes read fBuiltinFuncAttri write fBuiltinFuncAttri; property Exporter: TmwCustomExport read FExporter write FExporter; end; var mwMooHighLighter: TmwMooSyntax; implementation var Identifiers: array[#0..#255] of ByteBool; mHashTable: array[#0..#255] of Integer; procedure MakeIdentTable; var I, J: Char; begin for I := #0 to #255 do begin case I of '_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True; else Identifiers[I] := False; end; J := UpCase(I); case I in ['_', 'A'..'Z', 'a'..'z'] of True: mHashTable[I] := Ord(J) - 64 else mHashTable[I] := 0; end; end; end; procedure TmwMOOSyntax.InitIdent; var I: Integer; pF: PIdentFuncTableFunc; begin pF := PIdentFuncTableFunc(@fIdentFuncTable); for I := Low(fIdentFuncTable) to High(fIdentFuncTable) do begin pF^ := AltFunc; Inc(pF); end; fIdentFuncTable[0] := Func0; fIdentFuncTable[1] := Func1; fIdentFuncTable[2] := Func2; fIdentFuncTable[6] := Func6; fIdentFuncTable[8] := Func8; fIdentFuncTable[10] := Func10; fIdentFuncTable[12] := Func12; fIdentFuncTable[13] := Func13; fIdentFuncTable[15] := Func15; fIdentFuncTable[16] := Func16; fIdentFuncTable[17] := Func17; fIdentFuncTable[18] := Func18; fIdentFuncTable[22] := Func22; fIdentFuncTable[23] := Func23; fIdentFuncTable[24] := Func24; fIdentFuncTable[25] := Func25; fIdentFuncTable[26] := Func26; fIdentFuncTable[27] := Func27; fIdentFuncTable[28] := Func28; fIdentFuncTable[29] := Func29; fIdentFuncTable[30] := Func30; fIdentFuncTable[32] := Func32; fIdentFuncTable[33] := Func33; fIdentFuncTable[34] := Func34; fIdentFuncTable[35] := Func35; fIdentFuncTable[36] := Func36; fIdentFuncTable[37] := Func37; fIdentFuncTable[38] := Func38; fIdentFuncTable[39] := Func39; fIdentFuncTable[40] := Func40; fIdentFuncTable[41] := Func41; fIdentFuncTable[42] := Func42; fIdentFuncTable[43] := Func43; fIdentFuncTable[45] := Func45; fIdentFuncTable[46] := Func46; fIdentFuncTable[47] := Func47; fIdentFuncTable[48] := Func48; fIdentFuncTable[49] := Func49; fIdentFuncTable[50] := Func50; fIdentFuncTable[51] := Func51; fIdentFuncTable[52] := Func52; fIdentFuncTable[53] := Func53; fIdentFuncTable[55] := Func55; fIdentFuncTable[56] := Func56; fIdentFuncTable[57] := Func57; fIdentFuncTable[60] := Func60; fIdentFuncTable[62] := Func62; fIdentFuncTable[63] := Func63; fIdentFuncTable[65] := Func65; fIdentFuncTable[66] := Func66; fIdentFuncTable[69] := Func69; fIdentFuncTable[70] := Func70; fIdentFuncTable[71] := Func71; fIdentFuncTable[73] := Func73; fIdentFuncTable[74] := Func74; fIdentFuncTable[75] := Func75; fIdentFuncTable[76] := Func76; fIdentFuncTable[78] := Func78; fIdentFuncTable[79] := Func79; fIdentFuncTable[80] := Func80; fIdentFuncTable[81] := Func81; fIdentFuncTable[82] := Func82; fIdentFuncTable[83] := Func83; fIdentFuncTable[85] := Func85; fIdentFuncTable[86] := Func86; fIdentFuncTable[87] := Func87; fIdentFuncTable[89] := Func89; fIdentFuncTable[92] := Func92; fIdentFuncTable[94] := Func94; fIdentFuncTable[95] := Func95; fIdentFuncTable[96] := Func96; fIdentFuncTable[98] := Func98; fIdentFuncTable[99] := Func99; fIdentFuncTable[100] := Func100; fIdentFuncTable[101] := Func101; fIdentFuncTable[104] := Func104; fIdentFuncTable[105] := Func105; fIdentFuncTable[108] := Func108; fIdentFuncTable[111] := Func111; fIdentFuncTable[112] := Func112; fIdentFuncTable[114] := Func114; fIdentFuncTable[115] := Func115; fIdentFuncTable[116] := Func116; fIdentFuncTable[121] := Func121; fIdentFuncTable[122] := Func122; fIdentFuncTable[123] := Func123; fIdentFuncTable[124] := Func124; fIdentFuncTable[126] := Func126; end; function TmwMOOSyntax.KeyHash(ToHash: PChar): Integer; begin Result := 0; while ToHash^ in ['_', '0'..'9', 'a'..'z', 'A'..'Z'] do begin inc(Result, mHashTable[ToHash^]); inc(ToHash); end; Result:=Result and 127; fStringLen := ToHash - fToIdent; end; function TmwMOOSyntax.KeyComp(const aKey: String): Boolean; var I: Integer; Temp: PChar; begin Temp := fToIdent; if Length(aKey) = fStringLen then begin Result := True; for i := 1 to fStringLen do begin if mHashTable[Temp^] <> mHashTable[aKey[i]] then begin Result := False; break; end; inc(Temp); end; end else Result := False; end; function TmwMOOSyntax.Func0: TmoTokenKind; begin if KeyComp('value_hash') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func1: TmoTokenKind; begin if KeyComp('delete_verb') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func2: TmoTokenKind; begin if KeyComp('output_delimiters') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func6: TmoTokenKind; begin if KeyComp('is_clear_property') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func8: TmoTokenKind; begin if KeyComp('decode_binary') then Result := moBuiltinFunc else if KeyComp('binary_hash') then Result := moBuiltinFunc else if KeyComp('task_stack') then Result := moBuiltinFunc else if KeyComp('ticks_left') then Result := moBuiltinFunc else if KeyComp('is_player') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func10: TmoTokenKind; begin if KeyComp('dump_database') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func12: TmoTokenKind; begin if KeyComp('idle_seconds') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func13: TmoTokenKind; begin if KeyComp('properties') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func15: TmoTokenKind; begin if KeyComp('if') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func16: TmoTokenKind; begin if KeyComp('queue_info') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func17: TmoTokenKind; begin if KeyComp('listinsert') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func18: TmoTokenKind; begin if KeyComp('encode_binary') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func22: TmoTokenKind; begin if KeyComp('abs') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func23: TmoTokenKind; begin if KeyComp('in') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func24: TmoTokenKind; begin if KeyComp('server_log') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func25: TmoTokenKind; begin if KeyComp('caller_perms') then Result := moBuiltinFunc else if KeyComp('seconds_left') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func26: TmoTokenKind; begin if KeyComp('string_hash') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func27: TmoTokenKind; begin if KeyComp('set_property_info') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func28: TmoTokenKind; begin if KeyComp('read') then Result := moBuiltinFunc else if KeyComp('substitute') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func29: TmoTokenKind; begin if KeyComp('object_bytes') then Result := moBuiltinFunc else if KeyComp('ceil') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func30: TmoTokenKind; begin if KeyComp('force_input') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func32: TmoTokenKind; begin if KeyComp('boot_player') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func33: TmoTokenKind; begin if KeyComp('call_function') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func34: TmoTokenKind; begin if KeyComp('log') then Result := moBuiltinFunc else if KeyComp('log10') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func35: TmoTokenKind; begin if KeyComp('value_bytes') then Result := moBuiltinFunc else if KeyComp('tan') then Result := moBuiltinFunc else if KeyComp('notify_ansi') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func36: TmoTokenKind; begin if KeyComp('atan') then Result := moBuiltinFunc else if KeyComp('min') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func37: TmoTokenKind; begin if KeyComp('break') then Result := moKeyword else if KeyComp('cos') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func38: TmoTokenKind; begin if KeyComp('endif') then Result := moKeyword else if KeyComp('max') then Result := moBuiltinFunc else if KeyComp('acos') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func39: TmoTokenKind; begin if KeyComp('for') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func40: TmoTokenKind; begin if KeyComp('eval') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func41: TmoTokenKind; begin if KeyComp('else') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func42: TmoTokenKind; begin if KeyComp('sin') then Result := moBuiltinFunc else if KeyComp('db_disk_size') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func43: TmoTokenKind; begin if KeyComp('asin') then Result := moBuiltinFunc else if KeyComp('tanh') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func45: TmoTokenKind; begin if KeyComp('memory_usage') then Result := moBuiltinFunc else if KeyComp('add_property') then Result := moBuiltinFunc else if KeyComp('exp') then Result := moBuiltinFunc else if KeyComp('cosh') then Result := moBuiltinFunc else if KeyComp('match') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func46: TmoTokenKind; begin if KeyComp('queued_tasks') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func47: TmoTokenKind; begin if KeyComp('time') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func48: TmoTokenKind; begin if KeyComp('valid') then Result := moBuiltinFunc else if KeyComp('connection_name') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func49: TmoTokenKind; begin if KeyComp('function_info') then Result := moBuiltinFunc else if KeyComp('flush_input') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func50: TmoTokenKind; begin if KeyComp('fork') then Result := moKeyword else if KeyComp('ctime') then Result := moBuiltinFunc else if KeyComp('sinh') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func51: TmoTokenKind; begin if KeyComp('set_connection_option') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func52: TmoTokenKind; begin if KeyComp('buffered_output_length') then Result := moBuiltinFunc else if KeyComp('raise') then Result := moBuiltinFunc else if KeyComp('create') then Result := moBuiltinFunc else if KeyComp('set_verb_code') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func53: TmoTokenKind; begin if KeyComp('setadd') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func55: TmoTokenKind; begin if KeyComp('pass') then Result := moBuiltinFunc else if KeyComp('move') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func56: TmoTokenKind; begin if KeyComp('elseif') then Result := moKeyword else if KeyComp('index') then Result := moBuiltinFunc else if KeyComp('equal') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func57: TmoTokenKind; begin if KeyComp('while') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func60: TmoTokenKind; begin if KeyComp('nis_password') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func62: TmoTokenKind; begin if KeyComp('endfor') then Result := moKeyword else if KeyComp('toobj') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func63: TmoTokenKind; begin if KeyComp('rmatch') then Result := moBuiltinFunc else if KeyComp('try') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func65: TmoTokenKind; begin if KeyComp('connected_seconds') then Result := moBuiltinFunc else if KeyComp('random') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func66: TmoTokenKind; begin if KeyComp('length') then Result := moBuiltinFunc else if KeyComp('floor') then Result := moBuiltinFunc else if KeyComp('verbs') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func69: TmoTokenKind; begin if KeyComp('set_verb_info') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func70: TmoTokenKind; begin if KeyComp('set_verb_args') then Result := moBuiltinFunc else if KeyComp('callers') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func71: TmoTokenKind; begin if KeyComp('recycle') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func73: TmoTokenKind; begin if KeyComp('endfork') then Result := moKeyword else if KeyComp('except') then Result := moKeyword else if KeyComp('children') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func74: TmoTokenKind; begin if KeyComp('sqrt') then Result := moBuiltinFunc else if KeyComp('parent') then Result := moBuiltinFunc else if KeyComp('open_network_connection') then Result := moBuiltinFunc else if KeyComp('rindex') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func75: TmoTokenKind; begin if KeyComp('clear_property') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func76: TmoTokenKind; begin if KeyComp('trunc') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func78: TmoTokenKind; begin if KeyComp('uudecode') then Result := moBuiltinFunc else if KeyComp('toint') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func79: TmoTokenKind; begin if KeyComp('finally') then Result := moKeyword else if KeyComp('listen') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func80: TmoTokenKind; begin if KeyComp('endwhile') then Result := moKeyword else if KeyComp('property_info') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func81: TmoTokenKind; begin if KeyComp('set_player_flag') then Result := moBuiltinFunc else if KeyComp('resume') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func82: TmoTokenKind; begin if KeyComp('connected_players') then Result := moBuiltinFunc else if KeyComp('crypt') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func83: TmoTokenKind; begin if KeyComp('tonum') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func85: TmoTokenKind; begin if KeyComp('chparent') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func86: TmoTokenKind; begin if KeyComp('endtry') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func87: TmoTokenKind; begin if KeyComp('add_verb') then Result := moBuiltinFunc else if KeyComp('delete_property') then Result := moBuiltinFunc else if KeyComp('typeof') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func89: TmoTokenKind; begin if KeyComp('tofloat') then Result := moBuiltinFunc else if KeyComp('notify') then Result := moBuiltinFunc else if KeyComp('strcmp') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func92: TmoTokenKind; begin if KeyComp('server_version') then Result := moBuiltinFunc else if KeyComp('tostr') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func94: TmoTokenKind; begin if KeyComp('reset_max_object') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func95: TmoTokenKind; begin if KeyComp('task_id') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func96: TmoTokenKind; begin if KeyComp('return') then Result := moKeyword else if KeyComp('renumber') then Result := moBuiltinFunc else if KeyComp('players') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func98: TmoTokenKind; begin if KeyComp('suspend') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func99: TmoTokenKind; begin if KeyComp('strsub') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func100: TmoTokenKind; begin if KeyComp('set_task_perms') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func101: TmoTokenKind; begin if KeyComp('continue') then Result := moKeyword else Result := moVariable; end; function TmwMOOSyntax.Func104: TmoTokenKind; begin if KeyComp('listset') then Result := moBuiltinFunc else if KeyComp('connection_option') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func105: TmoTokenKind; begin if KeyComp('verb_code') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func108: TmoTokenKind; begin if KeyComp('disassemble') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func111: TmoTokenKind; begin if KeyComp('floatstr') then Result := moBuiltinFunc else if KeyComp('listdelete') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func112: TmoTokenKind; begin if KeyComp('toliteral') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func114: TmoTokenKind; begin if KeyComp('unlisten') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func115: TmoTokenKind; begin if KeyComp('is_member') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func116: TmoTokenKind; begin if KeyComp('listappend') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func121: TmoTokenKind; begin if KeyComp('listeners') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func122: TmoTokenKind; begin if KeyComp('verb_info') then Result := moBuiltinFunc else if KeyComp('setremove') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func123: TmoTokenKind; begin if KeyComp('verb_args') then Result := moBuiltinFunc else if KeyComp('connection_options') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func124: TmoTokenKind; begin if KeyComp('shutdown') then Result := moBuiltinFunc else if KeyComp('max_object') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.Func126: TmoTokenKind; begin if KeyComp('kill_task') then Result := moBuiltinFunc else Result := moVariable; end; function TmwMOOSyntax.AltFunc: TmoTokenKind; begin Result := moVariable; end; function TmwMOOSyntax.FindBracket: Boolean; var TempRun: Integer; begin TempRun:=Run+fStringLen; while fLine[TempRun] in [' ',#9] do Inc(TempRun); Result:=fLine[TempRun]='('; end; function TmwMOOSyntax.IdentKind(MayBe: PChar): TmoTokenKind; var HashKey: Integer; begin fToIdent := MayBe; HashKey := KeyHash(MayBe); if HashKey < 127 then Result := fIdentFuncTable[HashKey] else Result := moVariable; if (Result=moBuiltinFunc) and (not FindBracket) then Result:=moVariable; end; procedure TmwMOOSyntax.MakeMethodTables; var I: Char; begin for I := #0 to #255 do case I of 'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc; #0: fProcTable[I] := NullProc; #1..#32: fProcTable[I] := SpaceProc; '"': fProcTable[I] := StringProc; '@','?','|','&','!','%','*','(',')','{','}','[',']',':',';',',','.': fProcTable[I] := SymbolProc; '$': fProcTable[I] := DollarProc; '#': fProcTable[I] := HashMarkProc; '0'..'9': fProcTable[I] := NumberProc; '/': fProcTable[I] := SlashProc; else fProcTable[I] := UnknownProc; end; end; constructor TmwMOOSyntax.Create(AOwner: TComponent); begin fCommentAttri := TmwHighLightAttributes.Create(MWS_AttrReservedWord); fKeywordAttri := TmwHighLightAttributes.Create('Keyword'); fNumberAttri := TmwHighLightAttributes.Create(MWS_AttrNumber); fObjectAttri := TmwHighLightAttributes.Create('Object'); fDollarRefAttri := TmwHighLightAttributes.Create('$-ref'); fSpaceAttri := TmwHighLightAttributes.Create(MWS_AttrSpace); fStringAttri := TmwHighLightAttributes.Create(MWS_AttrString); fSymbolAttri := TmwHighLightAttributes.Create(MWS_AttrSymbol); fVariableAttri := TmwHighLightAttributes.Create(MWS_AttrVariable); fBuiltinFuncAttri := TmwHighLightAttributes.Create('Builtin function'); fCommentAttri.ForeGround:=clGray; fKeyWordAttri.ForeGround:=clBlue; fNumberAttri.ForeGround:=clBlack; fObjectAttri.ForeGround:=clRed; fDollarRefAttri.ForeGround:=clRed; fStringAttri.Foreground:=clGreen; fSymbolAttri.ForeGround:=clNavy; fVariableAttri.ForeGround:=clBlack; fBuiltinFuncAttri.ForeGround:=clNavy; inherited Create(AOwner); AddAttribute(fCommentAttri); AddAttribute(fKeywordAttri); AddAttribute(fNumberAttri); AddAttribute(fObjectAttri); AddAttribute(fDollarRefAttri); AddAttribute(fSpaceAttri); AddAttribute(fStringAttri); AddAttribute(fSymbolAttri); AddAttribute(fVariableAttri); AddAttribute(fBuiltinFuncAttri); SetAttributesOnChange(DefHighlightChange); InitIdent; MakeMethodTables; fDefaultFilter := 'All files (*.*)|*.*'; fRange := rsUnknown; end; procedure TmwMOOSyntax.SetLine(NewValue: String; LineNumber: Integer); begin fLine := PChar(NewValue); Run := 0; fLineNumber := LineNumber; fStringIsComment:=True; Next; end; procedure TmwMOOSyntax.DollarProc; begin fTokenID := moDollarRef; while not (fLine[Run] in ['@','?','|','&','!','%','*','/','(',')','{','}','[',']',':',';',',','.',#0..#32]) do inc(Run); if fTokenPos=Run-1 then fTokenID:=moSymbol; end; procedure TmwMOOSyntax.HashMarkProc; begin fTokenID := moObject; while not (fLine[Run] in ['@','?','|','&','!','%','*','/','(',')','{','}','[',']',':',';',',','.',#0..#32]) do inc(Run); end; procedure TmwMOOSyntax.IdentProc; begin fTokenID := IdentKind((fLine + Run)); inc(Run, fStringLen); while Identifiers[fLine[Run]] do inc(Run); end; procedure TmwMOOSyntax.SlashProc; begin inc(Run); if fLine[Run]<>'/' then begin fTokenID:=moSymbol; Exit; end; fTokenID := moComment; while not (FLine[Run] in [#0,#10]) do inc(Run); end; procedure TmwMOOSyntax.NumberProc; begin inc(Run); fTokenID := moNumber; while FLine[Run] in ['0'..'9', '.', 'x', 'X', 'e', 'E'] do begin case FLine[Run] of '.': if FLine[Run + 1] = '.' then break; end; inc(Run); end; end; procedure TmwMOOSyntax.NullProc; begin fTokenID := moNull; end; procedure TmwMOOSyntax.SpaceProc; begin fTokenID := moSpace; repeat inc(Run); until not (fLine[Run] in [#1..#32]); end; procedure TmwMOOSyntax.StringProc; begin if not fStringIsComment then fTokenID := moString else fTokenID := moComment; if (fLine[Run + 1] = '"') and (fLine[Run + 2] = '"') then Inc(Run, 2); repeat case fLine[Run] of #0, #10, #13: Break; '\': if fLine[Run+1]='"' then Inc(Run); end; Inc(Run); until fLine[Run] = '"'; if fStringIsComment and (fLine[Run+1]=';') then Inc(Run); if fLine[Run] <> #0 then Inc(Run); end; procedure TmwMOOSyntax.SymbolProc; begin fTokenID := moSymbol; repeat inc(Run); until not (fLine[Run] in ['@','?','|','&','!','%','*','/','(',')','{','}','[',']',':',';',',','.']); end; procedure TmwMOOSyntax.UnknownProc; begin inc(Run); fTokenID := moUnknown; end; procedure TmwMOOSyntax.Next; begin fTokenPos := Run; fProcTable[fLine[Run]]; if fTokenID<>moSpace then fStringIsComment:=False; end; function TmwMOOSyntax.GetEOL: Boolean; begin Result := fTokenID = moNull; end; function TmwMOOSyntax.GetRange: Pointer; begin Result := Pointer(fRange); end; function TmwMOOSyntax.GetToken: String; var Len: LongInt; begin Len := Run - fTokenPos; SetString(Result, (FLine + fTokenPos), Len); end; function TmwMOOSyntax.GetTokenID: TmoTokenKind; begin Result := fTokenId; end; function TmwMOOSyntax.GetTokenAttribute: TmwHighLightAttributes; begin case GetTokenID of moComment: Result := fCommentAttri; moKeyword: Result := fKeywordAttri; moNumber: Result := fNumberAttri; moObject: Result := fObjectAttri; moDollarRef: Result := fDollarRefAttri; moSpace: Result := fSpaceAttri; moString: Result := fStringAttri; moSymbol: Result := fSymbolAttri; moVariable: Result := fVariableAttri; moUnknown: Result := fVariableAttri; moBuiltinFunc: Result := fBuiltinFuncAttri; else Result := nil; end; end; function TmwMOOSyntax.GetTokenKind: integer; begin Result := Ord(fTokenId); end; function TmwMOOSyntax.GetTokenPos: Integer; begin Result := fTokenPos; end; procedure TmwMOOSyntax.ReSetRange; begin fRange := rsUnknown; end; procedure TmwMOOSyntax.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; function TmwMOOSyntax.GetIdentChars: TIdentChars; begin Result := ['_', '0'..'9', 'a'..'z', 'A'..'Z']; end; function TmwMOOSyntax.GetLanguageName: string; begin Result := 'MOO-verb'; end; function TmwMOOSyntax.GetCapability: THighlighterCapability; begin Result := inherited GetCapability + [hcUserSettings, hcExportable]; end; procedure TmwMOOSyntax.SetLineForExport(NewValue: String); begin fLine := PChar(NewValue); Run := 0; ExportNext; end; procedure TmwMOOSyntax.ExportNext; begin fTokenPos := Run; fProcTable[fLine[Run]]; if Assigned(Exporter) then Case GetTokenID of moComment: TmwCustomExport(Exporter).FormatToken(GetToken, fCommentAttri, True, False); moKeyword: TmwCustomExport(Exporter).FormatToken(GetToken, fKeywordAttri, False, False); moNumber: TmwCustomExport(Exporter).FormatToken(GetToken, fNumberAttri, False, False); moObject: TmwCustomExport(Exporter).FormatToken(GetToken, fObjectAttri, False, False); moDollarRef: TmwCustomExport(Exporter).FormatToken(GetToken, fDollarRefAttri, False, False); moSpace: TmwCustomExport(Exporter).FormatToken(GetToken, fSpaceAttri, False, True); moString: TmwCustomExport(Exporter).FormatToken(GetToken, fStringAttri, True, False); moSymbol: TmwCustomExport(Exporter).FormatToken(GetToken, fSymbolAttri, True, False); moVariable: TmwCustomExport(Exporter).FormatToken(GetToken, fVariableAttri, False, False); moBuiltinFunc: TmwCustomExport(Exporter).FormatToken(GetToken, fBuiltinFuncAttri, False, False); end; end; initialization MakeIdentTable; mwMooHighLighter:=TmwMooSyntax.Create(nil); finalization mwMooHighLighter.Free; end.
{ Reports undefined, NONE and invalid script properties in selected records. Requires script source files to report undefined properties. } unit UserScript; var slProps: TStringList; regexp: TPerlRegEx; LastRec: IInterface; LastScript, LastProperty: string; //====================================================================== function Initialize: integer; begin slProps := TStringList.Create; regexp := TPerlRegEx.Create; regexp.Options := [preCaseLess, preMultiLine, preSingleLine]; regexp.RegEx := '^[\w\[\]]+\sproperty\s(\w+)(.*?)$'; regexp.Study; LastScript: = ''; LastProperty := ''; end; //====================================================================== procedure ReadScriptProperties(aScriptName: string); var s: string; begin try slProps.Clear; slProps.LoadFromFile(DataPath + 'Scripts\Source\' + aScriptName + '.psc'); except end; if slProps.Count = 0 then begin //AddMessage('Error reading script source for ' + aScriptName); Exit; end; regexp.Subject := slProps.Text; slProps.Clear; while regexp.MatchAgain do begin s := Trim(regexp.Groups[2]); if s = '' then Continue; // property has set an get functions if s[1] = '=' then Continue; // property has value slProps.Add(regexp.Groups[1]); end; end; //====================================================================== procedure ReportMissingProps(rec: IInterface); var i: integer; begin //if LastScript = '' then Exit; for i := 0 to slProps.Count - 1 do AddMessage(Format('%s \ %s \ %s property IS UNDEFINED', [Name(rec), LastScript, slProps[i]])); slProps.Clear; end; //====================================================================== procedure ScanVMAD(e: IInterface); var ElemName: string; i: integer; begin ElemName := Name(e); // new script entry if ElemName = 'scriptName' then begin // report missing props for previous script ReportMissingProps(LastRec); LastScript := GetEditValue(e); ReadScriptProperties(LastScript); end else // new property entry if ElemName = 'propertyName' then begin LastProperty := GetEditValue(e); // property exists, delete from list i := slProps.IndexOf(LastProperty); if i <> -1 then slProps.Delete(i); end else // new object property value entry if ElemName = 'FormID' then begin if GetNativeValue(e) = 0 then AddMessage(Format('%s \ %s \ %s property IS NONE', [Name(LastRec), LastScript, LastProperty])) else if not Assigned(LinksTo(e)) then AddMessage(Format('%s \ %s \ %s property IS INVALID', [Name(LastRec), LastScript, LastProperty])); end else // skip fragments, they contain scripts without properties if Pos('Fragments', ElemName) > 0 then Exit; for i := 0 to ElementCount(e) - 1 do ScanVMAD(ElementByIndex(e, i)); end; //====================================================================== function Process(e: IInterface): integer; begin // process VMAD subrecord only if ElementType(e) = etMainRecord then if ElementExists(e, 'VMAD') then begin LastRec := e; ScanVMAD(ElementBySignature(e, 'VMAD')); ReportMissingProps(e); end; end; //====================================================================== function Finalize: integer; begin slProps.Free; regexp.Free; end; end.
unit CFSFiles; { ------------------------------------------------------------------ Cambridge Electronic Design CFS data file import/export module ------------------------------------------------------------------ 23/7/00 18/2/01 ... Modified to handle scaling to 12 or 16 bit WCP files } interface uses global,fileio,SysUtils,shared,Dialogs,Messages,forms,controls, maths, Import,Progress ; function ConvertCFSToWCP( FileName : string ) : Boolean ; implementation uses mdiform ; type TChannelDef = packed record ChanName : String[21] ; UnitsY : String[9] ; UnitsX : String[9] ; dType : Byte ; dKind : Byte ; dSpacing : Word ; OtherChan : Word ; end ; TChannelInfo = packed record DataOffset : LongInt ; {offset to first point} DataPoints : LongInt ; {number of points in channel} scaleY : single ; offsetY : single ; scaleX : single ; offsetX : single ; end ; TDataHeader = packed record lastDS : LongInt ; dataSt : LongInt ; dataSz : LongInt ; Flags : Word ; Space : Array[1..8] of Word ; end ; TCFSFileHeader = packed record Marker : Array[1..8] of char ; Name : Array[1..14] of char ; FileSz : LongInt ; TimeStr : Array[1..8] of char ; DateStr : Array[1..8] of char ; DataChans : SmallInt ; FilVars : SmallInt ; DatVars : SmallInt ; fileHeadSz : SmallInt ; DataHeadSz : SmallInt ; EndPnt : LongInt ; DataSecs : SmallInt ; DiskBlkSize : SmallInt ; CommentStr : String[73] ; TablePos : LongInt ; Fspace : Array[1..20] of Word ; end ; function ConvertCFSToWCP( FileName : string ) : Boolean ; { -------------------------------------------------------------- Import data from an CFS data file and store in a WCP data file -------------------------------------------------------------- } var ChannelDef : TChannelDef ; ChannelInfo : TChannelInfo ; CFSFileHeader : TCFSFileHeader ; RecHeader : TDataHeader ; FilePointer,DataPointer : Integer ; Rec : Integer ; FileHandle,i,LastChannel,Src,Dest,SrcStep,iOff,nSamples : Integer ; ADCScale : single ; OK,Quit : boolean ; Ch : Integer ; Buf,CEDBuf : ^TIntArray ; rH : ^TRecHeader ; NumSamplesInChannel : Array[0..ChannelLimit] of Integer ; DataOffset : Array[0..ChannelLimit] of Integer ; SampleSpacing : Array[0..ChannelLimit] of Integer ; x : single ; s : string ; TimeUnits : string ; TScale,ScaleBits : single ; begin OK := True ; { Create buffers } New(Buf) ; New(rH) ; New(CEDBuf) ; try { Close existing WCP data file } if RawFH.FileHandle >= 0 then FileClose( RawFH.FileHandle ) ; { Create name of WCP file to hold CED file } RawFH.FileName := ChangeFileExt( FileName, '.wcp' ) ; { Open CFS data file } FileHandle := FileOpen( FileName, fmOpenRead ) ; if FileHandle < 0 then begin OK := False ; WriteToLogFile( 'Unable to open ' + FileName ) ; end ; { Read CFS file header block } if OK then begin FileSeek( FileHandle, 0, 0 ) ; if FileRead(FileHandle,CFSFileHeader,Sizeof(CFSFileHeader)) <> Sizeof(CFSFileHeader) then begin WriteToLogFile( FileName + ' - CFS Header unreadable') ; OK := False ; end ; end ; { Check that this is a CFS data file } if OK then begin s := ArrayToString(CFSFileHeader.Marker) ; if Pos('CEDFILE',s) = 0 then begin WriteToLogFile( FileName + ' - is not a CFS file.') ; OK := False ; end ; end ; { Get data from header block } if OK then begin { No. of analog input channels held in file } if CFSFileHeader.DataChans > (ChannelLimit+1) then WriteToLogFile( format( 'Input channels 6-%d ignored', [CFSFileHeader.DataChans-1])) ; { Number of analog input channels } RawFH.NumChannels := IntLimitTo(CFSFileHeader.DataChans,1,ChannelLimit+1) ; { Last channel number } LastChannel := RawFH.NumChannels - 1 ; { Get experiment identification text } RawFH.IdentLine := CFSFileHeader.CommentStr ; WriteToLogFile( 'CFS File : ' + FileName ) ; WriteToLogFile( RawFH.IdentLine ) ; WriteToLogFile( CFSFileHeader.TimeStr ) ; WriteToLogFile( CFSFileHeader.DateStr ) ; { A/D converter input voltage range } RawFH.ADCVoltageRange := 5. ; // Scale from 16 bit CED format to 16 or 12 bit WCP ScaleBits := 32768.0 / (Main.SESLabIO.ADCMaxValue + 1) ; { Read Channel definition records } for Ch := 0 to LastChannel do begin { Read signal channel definition record } if FileRead(FileHandle,ChannelDef,Sizeof(ChannelDef)) = Sizeof(ChannelDef) then begin { Name of signal channel } Channel[Ch].ADCName := ChannelDef.ChanName ; { Units of signal channel } Channel[Ch].ADCUnits := ChannelDef.UnitsY ; { Time units } TimeUnits := ChannelDef.UnitsX ; { Determine scaling to secs factor } if Pos( 'us', TimeUnits ) > 0 then TScale := 1E-6 else if Pos( 'ms', TimeUnits ) > 0 then TScale := 1E-3 else TScale := 1. ; SampleSpacing[Ch] := ChannelDef.dSpacing ; end else WriteToLogFile( format( 'Ch.%d definition record unreadable',[Ch])) ; end ; end ; { Create a new WCP file to hold converted data } if OK then begin RawFH.FileHandle := FileCreate( RawFH.FileName ) ; if RawFH.FileHandle < 0 then begin OK := False ; WriteToLogFile( 'Unable to open ' + FileName ) ; end ; end ; { Read data records from CFS file } if OK then begin RawFH.NumRecords := 0 ; ProgressFrm.Initialise( 1,CFSFileHeader.DataSecs ) ; ProgressFrm.Show ; While not ProgressFrm.Done do begin Rec := ProgressFrm.Position ; { Get pointer to start of data record #Rec } FileSeek( FileHandle,CFSFileHeader.TablePos + (Rec-1)*4, 0 ) ; FileRead(FileHandle,DataPointer,SizeOf(DataPointer)) ; { Read record data header } FileSeek( FileHandle, DataPointer, 0 ) ; FileRead(FileHandle,RecHeader,SizeOf(RecHeader)) ; { Read channel offset/scaling information records which follow data record } for Ch := 0 to LastChannel do begin { Read channel definition record } FileRead(FileHandle,ChannelInfo,SizeOf(ChannelInfo)) ; { Derive WCP's calibration factors from first record scaling factor } If Rec = 1 then begin { Get signal bits->units scaling factor } Channel[ch].ADCScale := ChannelInfo.ScaleY * ScaleBits ; Channel[ch].ADCCalibrationFactor := rawFH.ADCVoltageRange / ( Channel[ch].ADCScale * (MaxADCValue+1) ) ; Channel[ch].ADCAmplifierGain := 1. ; end ; { Correct record's input voltage range setting to account for an changes in signal scaling } rH^.ADCVoltageRange[Ch] := ( RawFH.ADCVoltageRange * ChannelInfo.ScaleY * ScaleBits ) / Channel[ch].ADCScale ; { Offset into groups of A/D samples for this channel } Channel[ch].ChannelOffset := Ch ; { Inter sample interval } RawFH.dt := ChannelInfo.scaleX*TScale ; rH^.dt := RawfH.dt ; { Number of samples in this channel } NumSamplesInChannel[Ch] := ChannelInfo.DataPoints ; { Offset (bytes) of samples for this channel in record data area } DataOffset[Ch] := ChannelInfo.DataOffset ; end ; { Find a suitable number of samples per record } if Rec = 1 then begin RawFH.NumSamples := 256 ; Quit := False ; while not Quit do begin Quit := True ; for Ch := 0 to LastChannel do begin { Increase in steps of 256 } if NumSamplesInChannel[Ch] > RawFH.NumSamples then begin RawFH.NumSamples := RawFH.NumSamples + 256 ; Quit := False ; end ; { Stop if buffer space limit reached } if (RawFH.NumSamples*RawFH.NumChannels) >= (MaxTBuf+1) then Quit := True ; end ; end ; end ; { Read binary data from CED data file into CED record buffer } FileSeek( FileHandle,RecHeader.DataSt,0) ; FileRead( FileHandle, CEDBuf^, RecHeader.DataSz ) ; { Copy from CED buffer to WCP buffer } for Ch := 0 to LastChannel do begin { Increment between samples for this channel in CED buffer } SrcStep := SampleSpacing[Ch] div 2 ; { Number of samples for this channel } nSamples := NumSamplesInChannel[Ch] ; { Starting point of sample data in CED buffer } Src := DataOffset[Ch] div 2 ; { Place samples in WCP buffer starting here } Dest := Channel[ch].ChannelOffset ; for i := 1 to RawFH.NumSamples do begin { Re-scale samples from 16 -> 12 bits } if( i <= nSamples ) then Buf^[Dest] := Round(CEDBuf^[Src] / ScaleBits ) else Buf^[Dest] := 0 ; { Increment WCP buffer point by sample spacing } Dest := Dest + RawFH.NumChannels ; { Increment CED buffer point by sample spacing } Src := Src + SrcStep ; end ; end ; { Save record to WCP data file } Inc(RawFH.NumRecords) ; rH^.Status := 'ACCEPTED' ; rH^.RecType := 'TEST' ; rH^.Number := RawFH.NumRecords ; rH^.Time := rH^.Number ; rH^.Ident := ' ' ; rH^.Equation.Available := False ; rH^.Analysis.Available := False ; PutRecord( RawfH, rH^, RawfH.NumRecords, Buf^ ) ; ProgressFrm.Increment ; end ; { Save file header } SaveHeader( RawFH ) ; { Close WCP file } if RawFH.FileHandle >= 0 then FileClose( RawFH.FileHandle ) ; WriteToLogFile( 'converted to WCP file : ' + RawFH.FileName ) ; end ; finally { Close CED file } if FileHandle >= 0 then FileClose( FileHandle ) ; { Free buffers } Dispose(rH) ; Dispose(Buf) ; Dispose(CEDBuf) ; if not OK then MessageDlg( 'Unable to import ' + FileName,mtWarning,[mbOK],0) ; Result := OK ; end ; end ; end.
{ ---------------------------------------------------------------------------- PLOX Scanner (Pascal version of CLOX) based on Crafting Interpreters by Robert Nystrom (well worth reading) https://www.craftinginterpreters.com/scanning-on-demand.html Bruce Wernick 1 July 2019 ---------------------------------------------------------------------------- } unit uScanner; interface type TTokenKind = ( // Single-character tokens. tkLPAREN, tkRPAREN, tkLBRACE, tkRBRACE, tkCOMMA, tkDOT, tkMINUS, tkPLUS, tkSEMICOLON, tkSLASH, tkSTAR, // One or two character tokens. tkBANG, tkBANGEQUAL, tkEQUAL, tkEQUALEQUAL, tkGREATER, tkGREATEREQUAL, tkLESS, tkLESSEQUAL, // Literals. tkIDENT, tkSTRING, tkNUMBER, // Keywords. tkAND, tkCLASS, tkELSE, tkFALSE, tkFOR, tkFUN, tkIF, tkNIL, tkOR, tkPRINT, tkRETURN, tkSUPER, tkTHIS, tkTRUE, tkVAR, tkWHILE, // Error and End tokens tkERR, tkEOS); type TTokenRec = record kind: TTokenKind; start: pchar; length: integer; line: integer; end; type TScanner = record private sp: pchar; cp: pchar; line: integer; function isAlpha(c: char): boolean; function isDigit(c: char): boolean; function atEnd: boolean; function step: char; function peek: char; function spy: char; function matchChar(Value: char): boolean; function makeToken(Value: TTokenKind): TTokenRec; function errToken(Value: pchar): TTokenRec; procedure skipWhite; function isKeyword(Value: string): boolean; function identKind: TTokenKind; function getIdent: TTokenRec; function getNumber: TTokenRec; function getString: TTokenRec; public procedure Init(source: pchar); function getToken: TTokenRec; end; function GetTokenStr(Value: TTokenKind): string; implementation uses SysUtils, TypInfo; const lo_alpha = 'abcdefghijklmnopqrstuvwxyz'; hi_alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; alpha = lo_alpha + hi_alpha + '_'; digits = '0123456789'; dotChar = '.'; quoteChar = '"'; spaceChar = ' '; // special symbols ssEOS = Char(0); ssTAB = Char(9); ssLF = Char(10); ssCR = Char(13); function GetTokenStr(Value: TTokenKind): string; {- use Rtti to get string from enum } begin Result := GetEnumName(TypeInfo(TTokenKind), ord(Value)) end; procedure TScanner.Init(source: pchar); begin self.sp := source; self.cp := source; self.line := 1 end; function TScanner.isAlpha(c: char): boolean; begin Result := AnsiPos(c, alpha) > 0 end; function TScanner.isDigit(c: char): boolean; begin Result := AnsiPos(c, digits) > 0 end; function TScanner.atEnd: boolean; begin Result := self.cp[0] = ssEOS end; function TScanner.peek: char; begin Result := self.cp[0] end; function TScanner.step: char; begin Result := peek; inc(self.cp) end; function TScanner.spy: char; {- look ahead to next character } begin if atEnd then Exit(ssEOS); Result := self.cp[1] end; function TScanner.matchChar(Value: char): boolean; begin Result := True; if atEnd then Exit(False); if self.cp <> Value then Exit(False); inc(self.cp) end; function TScanner.makeToken(Value: TTokenKind): TTokenRec; begin Result.kind := Value; Result.start := self.sp; Result.length := self.cp - self.sp; Result.line := self.line end; function TScanner.errToken(Value: pchar): TTokenRec; begin Result.kind := tkERR; Result.start := Value; Result.length := length(Value); Result.line := self.line end; procedure TScanner.skipWhite; var c: char; begin while True do begin c := peek; case c of spaceChar, ssLF, ssTAB: step; ssCR: begin inc(self.line); step; end; '/': if (spy = '/') then begin while ((peek <> ssLF) and not atEnd) do step; end; else Exit; end; end; end; function TScanner.isKeyword(Value: string): boolean; var s: string; k: integer; begin k := length(Value); SetString(s, self.sp, self.cp-self.sp); Result := SameText(s, Value) end; function TScanner.identKind: TTokenKind; begin Result := tkIDENT; if isKeyword('and') then Exit(tkAND); if isKeyword('class') then Exit(tkCLASS); if isKeyword('else') then Exit(tkELSE); if isKeyword('false') then Exit(tkFALSE); if isKeyword('for') then Exit(tkFOR); if isKeyword('fun') then Exit(tkFUN); if isKeyword('if') then Exit(tkIF); if isKeyword('nil') then Exit(tkNIL); if isKeyword('or') then Exit(tkOR); if isKeyword('print') then Exit(tkPRINT); if isKeyword('return') then Exit(tkRETURN); if isKeyword('super') then Exit(tkSUPER); if isKeyword('this') then Exit(tkTHIS); if isKeyword('true') then Exit(tkTRUE); if isKeyword('var') then Exit(tkVAR); if isKeyword('while') then Exit(tkWHILE); end; function TScanner.getIdent: TTokenRec; begin while (isAlpha(peek) or isDigit(peek)) do step; Result := makeToken(identKind) end; function TScanner.getNumber: TTokenRec; begin while isDigit(peek) do step; if (peek = dotChar) and isDigit(spy) then begin step; while isDigit(peek) do step; end; Result := makeToken(tkNUMBER); end; function TScanner.getString: TTokenRec; begin while (peek <> QuoteChar) and not atEnd do begin if (peek = ssLF) then inc(self.line); step; end; if atEnd then Exit(errToken('Un-terminated string!')); step; Result := makeToken(tkSTRING); end; function TScanner.getToken: TTokenRec; var c: char; begin skipWhite(); self.sp := self.cp; if atEnd then Exit(makeToken(tkEOS)); c := step; if isAlpha(c) then Exit(getIdent); if isDigit(c) then Exit(getNumber); case c of '(': Exit(makeToken(tkLPAREN)); ')': Exit(makeToken(tkRPAREN)); '{': Exit(makeToken(tkLBRACE)); '}': Exit(makeToken(tkRBRACE)); ';': Exit(makeToken(tkSEMICOLON)); ',': Exit(makeToken(tkCOMMA)); '.': Exit(makeToken(tkDOT)); '-': Exit(makeToken(tkMINUS)); '+': Exit(makeToken(tkPLUS)); '/': Exit(makeToken(tkSLASH)); '*': Exit(makeToken(tkSTAR)); '!': if matchChar('=') then Exit(makeToken(tkBANGEQUAL)) else Exit(makeToken(tkBANG)); '=': if matchChar('=') then Exit(makeToken(tkEQUALEQUAL)) else Exit(makeToken(tkEQUAL)); '<': if matchChar('=') then Exit(makeToken(tkLESSEQUAL)) else Exit(makeToken(tkLESS)); '>': if matchChar('=') then Exit(makeToken(tkGREATEREQUAL)) else Exit(makeToken(tkGREATER)); '"': Exit(getString); end; Result := errToken('Unexpected character!'); end; end.
{*************************************************************************************************************************************** TTableAttribute: Usado para vincular a model a table do db. TFieldsAttribute> Usado para vincular o atributo ao field da table. TAssociationFieldAttribute: Usado para relacionamento do tipo FK. TProxyModel: Usado para não carregar os dados sem necessidade do tipo relacionamento na hora de acessar o object que possui relacionamentos, evitando muita carga de dados. ***************************************************************************************************************************************} unit untModels; interface uses untORM; type [TTableAttribute('tb_empresa')] TEmpresa = class(TModel) private [TFieldAttribute('cnpj')] FCnpj: String; [TFieldAttribute('descricao')] FDescricao: String; [TFieldAttribute('contato')] FContato: String; [TFieldAttribute('endereco')] FEndereco: String; public property Cnpj: String read FCnpj write FCnpj; property Descricao: String read FDescricao write FDescricao; property Contato: String read FContato write FContato; property Endereco: String read FEndereco write FEndereco; end; [TTableAttribute('tb_tanque')] TTanque = class(TModel) private [TFieldAttribute('codigo')] FCodigo: String; [TFieldAttribute('descricao')] FDescricao: String; [TFieldAttribute('tipo')] FTipo: Integer; [TAssociationFieldAttribute('id_empresa')] FEmpresa: TProxyModel<TEmpresa>; function GetEmpresa: TEmpresa; procedure SetEmpresa(const Value: TEmpresa); public property Codigo: String read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Tipo: Integer read FTipo write FTipo; property Empresa: TEmpresa read GetEmpresa write SetEmpresa; constructor create(); override; end; [TTableAttribute('tb_bomba')] TBomba = class(TModel) private [TFieldAttribute('codigo')] FCodigo: String; [TFieldAttribute('descricao')] FDescricao: String; [TAssociationFieldAttribute('id_tanque')] FTanque: TProxyModel<TTanque>; function GetTanque: TTanque; procedure SetTanque(const Value: TTanque); public property Codigo: String read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Tanque: TTanque read GetTanque write SetTanque; constructor create(); override; end; [TTableAttribute('tb_abastecimento')] TAbastecimento = class(TModel) private [TFieldAttribute('codigo')] FCodigo: String; [TFieldAttribute('quantidade_litros')] FQuantidadeLitros: Double; [TFieldAttribute('valor')] FValor: Currency; [TFieldAttribute('data')] FData: TDateTime; [TAssociationFieldAttribute('id_bomba')] FBomba: TProxyModel<TBomba>; function GetBomba: TBomba; procedure SetBomba(const Value: TBomba); public property Codigo: String read FCodigo write FCodigo; property QuantidadeLitros: Double read FQuantidadeLitros write FQuantidadeLitros; property Valor: Currency read FValor write FValor; property Data: TDateTime read FData write FData; property Bomba: TBomba read GetBomba write SetBomba; constructor create(); override; end; implementation uses System.SysUtils; { TAbastecimento } constructor TAbastecimento.create; begin inherited; FBomba := TProxyModel<TBomba>.create; end; function TAbastecimento.GetBomba: TBomba; begin Result := FBomba.Value; end; procedure TAbastecimento.SetBomba(const Value: TBomba); begin FBomba.Value := Value; end; { TBomba } constructor TBomba.create; begin inherited; FTanque := TProxyModel<TTanque>.create; end; function TBomba.GetTanque: TTanque; begin Result := FTanque.Value; end; procedure TBomba.SetTanque(const Value: TTanque); begin FTanque.Value := Value; end; { TTanque } constructor TTanque.create; begin inherited; FEmpresa := TProxyModel<TEmpresa>.create; end; function TTanque.GetEmpresa: TEmpresa; begin Result := FEmpresa.Value; end; procedure TTanque.SetEmpresa(const Value: TEmpresa); begin FEmpresa.Value := Value; end; end.
{------------------------------------ 功能说明:权限管理 创建日期:2010/05/22 作者:wzw 版权:wzw -------------------------------------} unit uRoleMgr; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseForm, ComCtrls, ImgList, ExtCtrls, ToolWin, DBClient, SysSvc, DB, DBIntf, AuthoritySvrIntf, System.ImageList; type PNodeData = ^TNodeData; TNodeData = record State: Integer;//0:不选 1:不确定 2:选择 aDefault: Boolean; Key: String; end; TFrmRoleMgr = class(TBaseForm) ToolBar1: TToolBar; Panel1: TPanel; lv_Role: TListView; Panel2: TPanel; tv_Authority: TTreeView; imgList: TImageList; btn_UpdateRole: TToolButton; btn_NewRole: TToolButton; Btn_EdtRole: TToolButton; Splitter1: TSplitter; ImgRole: TImageList; cds_Authority: TClientDataSet; ToolButton4: TToolButton; btn_delRole: TToolButton; btn_Save: TToolButton; ToolButton7: TToolButton; cds_Role: TClientDataSet; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tv_AuthorityGetImageIndex(Sender: TObject; Node: TTreeNode); procedure tv_AuthorityGetSelectedIndex(Sender: TObject; Node: TTreeNode); procedure tv_AuthorityMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure tv_AuthorityDeletion(Sender: TObject; Node: TTreeNode); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lv_RoleDeletion(Sender: TObject; Item: TListItem); procedure lv_RoleSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btn_UpdateRoleClick(Sender: TObject); procedure lv_RoleInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); procedure btn_NewRoleClick(Sender: TObject); procedure lv_RoleDblClick(Sender: TObject); procedure btn_delRoleClick(Sender: TObject); procedure Btn_EdtRoleClick(Sender: TObject); procedure btn_SaveClick(Sender: TObject); private DBAC: IDBAccess; FCurRoleID: Integer; FModified: Boolean; procedure UpdateParentState(PNode: TTreeNode); procedure SetChildState(Node: TTreeNode; State: Integer); procedure InitTv; function GetTVNode(const NodeText: String): TTreeNode; procedure LoadRoles; procedure DisRoleInLv; procedure LoadAuthority(const RoleID: Integer); procedure CheckToSave; procedure Save; protected class procedure RegAuthority(aIntf: IAuthorityRegistrar); override; procedure HandleAuthority(const Key: String; aEnable: Boolean); override; public { Public declarations } end; var FrmRoleMgr: TFrmRoleMgr; implementation uses uEdtRole, _Sys; {$R *.dfm} procedure TFrmRoleMgr.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; CheckToSave; Action := caFree; end; procedure TFrmRoleMgr.SetChildState(Node: TTreeNode; State: Integer); var i: Integer; begin for i := 0 to Node.Count - 1 do begin if Assigned(Node.Item[i].Data) then PNodeData(Node.Item[i].Data)^.State := State; if Node.HasChildren then SetChildState(Node.Item[i], State); end; end; procedure TFrmRoleMgr.UpdateParentState(PNode: TTreeNode); var i: Integer; NodeData: PNodeData; State: Integer; begin if not Assigned(PNode) then exit; State := -1; for i := 0 to PNode.Count - 1 do begin if Assigned(PNode.Item[i].Data) then begin NodeData := PNodeData(PNode.Item[i].Data); if State = -1 then State := NodeData^.State else begin if State <> NodeData^.State then begin State := 1; Break; end; end; end; end; if Assigned(PNode.Data) then PNodeData(PNode.Data)^.State := State; UpdateParentState(PNode.Parent); end; procedure TFrmRoleMgr.tv_AuthorityGetImageIndex(Sender: TObject; Node: TTreeNode); begin if Assigned(Node.Data) then Node.ImageIndex := PNodeData(Node.Data)^.State; end; procedure TFrmRoleMgr.tv_AuthorityGetSelectedIndex(Sender: TObject; Node: TTreeNode); begin inherited; Node.SelectedIndex := Node.ImageIndex; end; procedure TFrmRoleMgr.tv_AuthorityMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ht: THitTests; Node: TTreeNode; NodeData: PNodeData; begin if not Assigned(lv_Role.Selected) then exit; ht := self.tv_Authority.GetHitTestInfoAt(x, y); Node := self.tv_Authority.GetNodeAt(x, y); if htOnIcon in ht then begin if Assigned(Node) then begin if Assigned(Node.Data) then begin NodeData := PNodeData(Node.Data); case NodeData^.State of 0: NodeData^.State := 2; 1, 2: NodeData^.State := 0; end; self.SetChildState(Node, NodeData^.State); self.UpdateParentState(Node.Parent); FModified := True; end; end; end; self.tv_Authority.Refresh; end; procedure TFrmRoleMgr.tv_AuthorityDeletion(Sender: TObject; Node: TTreeNode); begin if Assigned(Node.Data) then DisPose(PNodeData(Node.Data)); end; procedure TFrmRoleMgr.InitTv; const Sql = 'Select * from [AuthorityItem]'; var tmpCds: TClientDataSet; RootNode, PNode, NewNode: TTreeNode; aList: TStrings; i: Integer; NodeData: PNodeData; begin tmpCds := TClientDataSet.Create(nil); aList := TStringList.Create; self.tv_Authority.Items.BeginUpdate; try self.tv_Authority.Items.Clear; RootNode := self.tv_Authority.Items.AddChildFirst(nil, '所有权限'); New(NodeData); NodeData^.State := 0; NodeData^.Key := ''; RootNode.Data := NodeData; DBAC.QuerySQL(tmpCds, Sql); tmpCds.First; while not tmpCds.Eof do begin aList.Delimiter := '\'; aList.DelimitedText := tmpCds.fieldbyname('aPath').AsString; PNode := RootNode; for i := 0 to aList.Count - 1 do begin NewNode := self.GetTVNode(aList[i]); if NewNode = nil then begin NewNode := self.tv_Authority.Items.AddChild(PNode, aList[i]); New(NodeData); NodeData^.State := 0; NodeData^.Key := ''; NewNode.Data := NodeData; end; PNode := NewNode; end; NewNode := self.tv_Authority.Items.AddChild(PNode, tmpCds.fieldbyname('aItemName').AsString); New(NodeData); NodeData^.State := 0; NodeData^.Key := tmpCds.fieldbyname('aKey').AsString; NodeData^.aDefault := tmpCds.fieldbyname('aDefault').AsBoolean; NewNode.Data := NodeData; tmpCds.Next; end; self.tv_Authority.FullExpand; finally tmpCds.Free; aList.Free; self.tv_Authority.Items.EndUpdate; end; end; function TFrmRoleMgr.GetTVNode(const NodeText: String): TTreeNode; var i: integer; begin Result := nil; for i := 0 to self.tv_Authority.Items.Count - 1 do begin if CompareText(self.tv_Authority.Items[i].Text, NodeText) = 0 then begin Result := self.tv_Authority.Items[i]; exit; end; end; end; procedure TFrmRoleMgr.FormShow(Sender: TObject); begin inherited; self.LoadRoles; self.InitTv; self.DisRoleInLv; end; procedure TFrmRoleMgr.FormCreate(Sender: TObject); begin inherited; FModified := False; DBAC := SysService as IDBAccess; end; procedure TFrmRoleMgr.LoadRoles; const Sql = 'Select * from [Role]'; begin DBAC.QuerySQL(Cds_Role, Sql); end; procedure TFrmRoleMgr.lv_RoleDeletion(Sender: TObject; Item: TListItem); begin inherited; if Assigned(Item.Data) then IDataRecord(Item.Data)._Release; end; procedure TFrmRoleMgr.LoadAuthority(const RoleID: Integer); const Sql = 'select * from [RoleAuthority] where RoleID=%d'; var i: Integer; NodeData: PNodeData; begin CheckToSave; FCurRoleID := RoleID; DBAC.QuerySQL(cds_Authority, Format(Sql, [RoleID])); self.tv_Authority.Items.BeginUpdate; try for i := 0 to self.tv_Authority.Items.Count - 1 do begin if Assigned(self.tv_Authority.Items[i].Data) then begin NodeData := PNodeData(self.tv_Authority.Items[i].Data); if NodeData^.Key <> '' then begin if cds_Authority.Locate('aKey', NodeData^.Key, []) then begin if cds_Authority.FieldByName('aEnable').AsBoolean then NodeData^.State := 2 else NodeData^.State := 0; end else begin if NodeData^.aDefault then NodeData^.State := 2 else NodeData^.State := 0; end; self.UpdateParentState(self.tv_Authority.Items[i].Parent); end; end; end; self.FModified := False; finally self.tv_Authority.Items.EndUpdate; end; end; procedure TFrmRoleMgr.lv_RoleSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then begin if Assigned(Item.Data) then self.LoadAuthority(IDataRecord(Item.Data).FieldValueAsInteger('ID')); end; end; procedure TFrmRoleMgr.btn_UpdateRoleClick(Sender: TObject); begin inherited; (SysService as IAuthoritySvr).UpdateAuthority; self.InitTv; if Assigned(self.lv_Role.Selected) then self.LoadAuthority(IDataRecord(self.lv_Role.Selected.Data).FieldValueAsInteger('ID')); end; procedure TFrmRoleMgr.lv_RoleInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); begin if Assigned(Item.Data) then InfoTip := IDataRecord(Item.Data).FieldValueAsString('Description'); end; procedure TFrmRoleMgr.btn_NewRoleClick(Sender: TObject); begin inherited; FrmEdtRole := TFrmEdtRole.Create(nil, nil); try FrmEdtRole.Caption := '新增角色'; if FrmEdtRole.ShowModal = mrOK then begin FrmEdtRole.ResultData.SaveToDataSet('ID', Cds_Role); DBAC.BeginTrans; try DBAC.ApplyUpdate('[Role]', Cds_Role); DBAC.CommitTrans; self.LoadRoles;//新增要重新加载一下,不然没有ID,因为ID是自增的。。。 self.DisRoleInLv; except on E: Exception do sys.Dialogs.ShowError(E); end; end; finally FrmEdtRole.Free; end; end; procedure TFrmRoleMgr.lv_RoleDblClick(Sender: TObject); begin inherited; Btn_EdtRole.Click; end; procedure TFrmRoleMgr.btn_delRoleClick(Sender: TObject); const DelRoleAuthoritySql = 'Delete From RoleAuthority where RoleID=%d'; var Rec: IDataRecord; RoleID: Integer; begin if Assigned(self.lv_Role.Selected) then begin Rec := IDataRecord(self.lv_Role.Selected.Data); if sys.Dialogs.Confirm('删除角色', '您确定要删除当前选中的角色吗?' + #13#10 + '注意:删除角色后,该角色下的所有用户将丢失所有权限!') then begin RoleID := Rec.FieldValueAsInteger('ID'); if Cds_Role.Locate('ID', RoleID, []) then begin Cds_Role.Delete; DBAC.BeginTrans; try DBAC.ApplyUpdate('[Role]', Cds_Role); DBAC.ExecuteSQL(Format(DelRoleAuthoritySql, [RoleID])); DBAC.CommitTrans; self.lv_Role.Selected.Delete; except on E: Exception do sys.Dialogs.ShowError(E); end; end; end; end else sys.Dialogs.ShowInfo('请先选择一个角色!'); end; procedure TFrmRoleMgr.Btn_EdtRoleClick(Sender: TObject); var Rec: IDataRecord; begin if Assigned(self.lv_Role.Selected) then begin Rec := IDataRecord(self.lv_Role.Selected.Data); FrmEdtRole := TFrmEdtRole.Create(nil, Rec); try FrmEdtRole.Caption := '新增角色'; if FrmEdtRole.ShowModal = mrOK then begin FrmEdtRole.ResultData.SaveToDataSet('ID', Cds_Role); DBAC.BeginTrans; try DBAC.ApplyUpdate('[Role]', Cds_Role); DBAC.CommitTrans; self.DisRoleInLv; except on E: Exception do sys.Dialogs.ShowError(E); end; end; finally FrmEdtRole.Free; end; end else sys.Dialogs.ShowInfo('请先选择一个角色!'); end; procedure TFrmRoleMgr.DisRoleInLv; var NewItem: TListItem; Rec: IDataRecord; begin self.lv_Role.Items.BeginUpdate; try self.lv_Role.Clear; Cds_Role.First; while not Cds_Role.Eof do begin NewItem := self.lv_Role.Items.Add; NewItem.Caption := Cds_Role.fieldbyname('RoleName').AsString; NewItem.ImageIndex := 0; Rec := SysService as IDataRecord; Rec.LoadFromDataSet(Cds_Role); Rec._AddRef; NewItem.Data := Pointer(Rec); Cds_Role.Next; end; finally self.lv_Role.Items.EndUpdate; end; end; procedure TFrmRoleMgr.Save; const Sql = 'select * from [RoleAuthority] where RoleID=%d'; var i: Integer; NodeData: PNodeData; tmpCds: TClientDataSet; begin if not self.FModified then exit; tmpCds := TClientDataSet.Create(nil); try DBAC.QuerySQL(tmpCds, Format(Sql, [self.FCurRoleID])); for i := 0 to self.tv_Authority.Items.Count - 1 do begin if Assigned(self.tv_Authority.Items[i].Data) then begin NodeData := PNodeData(self.tv_Authority.Items[i].Data); if NodeData^.Key <> '' then begin if tmpCds.Locate('aKey', NodeData^.Key, []) then tmpCds.Edit else tmpCds.Append; tmpCds.FieldByName('RoleID').AsInteger := self.FCurRoleID; tmpCds.FieldByName('aKey').AsString := NodeData^.Key; tmpCds.FieldByName('aEnable').AsBoolean := NodeData^.State = 2; tmpCds.Post; end; end; end; DBAC.BeginTrans; try DBAC.ApplyUpdate('[RoleAuthority]', tmpCds); DBAC.CommitTrans; Sys.Dialogs.ShowInfo('保存成功!'); except on E: Exception do begin DBAC.RollbackTrans; Sys.Dialogs.ShowError(E); end; end; FModified := False; finally tmpCds.Free; end; end; procedure TFrmRoleMgr.CheckToSave; begin if self.FModified then begin if Sys.Dialogs.Ask('角色管理', '权限已经改变,是否保存?') then self.Save; end; end; procedure TFrmRoleMgr.btn_SaveClick(Sender: TObject); begin inherited; self.Save; end; const Key1 = '{B928DA74-D9D0-4616-B91B-D2DE65B0DB58}'; class procedure TFrmRoleMgr.RegAuthority(aIntf: IAuthorityRegistrar); begin aIntf.RegAuthorityItem(Key1, '系统管理\权限', '角色管理', True); end; procedure TFrmRoleMgr.HandleAuthority(const Key: String; aEnable: Boolean); begin if Key = Key1 then begin if not aEnable then raise Exception.Create('对不起,你没有权限!'); end; end; end.
unit tgutils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, registry, fileutil, dateutils, zstream, libtar; type hms = Record hrs: Integer; mins: Integer; secs: Integer; end; function tgUtils_TimeDataNow(IncludeDate:Boolean):string; function tgUtils_TimeDataNowForFileName:string; function tgUtils_FormatStrAlarmType(alarmInt: integer): string; function tgUtils_MinutesToHMSComponents( mins: integer ): hms; function tgutils_SessionDataRange( filepath: string; var first, last: string ): integer; function tgutils_CountDataFiles( sessionfolderpath: string ): Integer; procedure tgUtils_DelimitString(s:string; var l:TStringList); function tgUtils_CelciusToFahrenheit(celcius: Double): Double; function tgUtils_CheckCmdIntegrity(s:string): Integer; procedure tgUtils_DirectoryList( searchPath: string; var dirList: TStringList ); //procedure tgutils_graphZoomAlarms(); function tgUtils_targzUnpack(fileToUnpack:string): Boolean; function tgUtils_untar(tarfilename:string): Boolean; function tgUtils_GetRootFsDirectory: String; function tgUtils_RegistryGetAppDataPath: String; const TGRQST_INTEGRITY_PASS : Integer = 0; TGRQST_INTEGRITY_ERROR_TOKEN_COUNT : Integer = 1; TGRQST_INTEGRITY_ERROR_CMD_MISMATCH : Integer = 2; TGRQST_INTEGRITY_ERROR_OTHER : integer = 3; implementation { List directories within directory at given path } procedure tgUtils_DirectoryList( searchPath: string; var dirList: TStringList ); var DirSearch: SysUtils.TSearchRec; begin if SysUtils.FindFirst( searchPath + '*', faDirectory, DirSearch ) = 0 then begin repeat if Length( DirSearch.Name ) = 10 then dirList.Add( format( '%s',[DirSearch.Name] ) ); until SysUtils.FindNext( DirSearch ) <> 0; SysUtils.FindClose( DirSearch ); end; end; function tgUtils_TimeDataNow(IncludeDate:Boolean):string; var strTime, strDate:string; timeNow: TdateTime; begin strTime := ''; strDate := ''; timeNow := now; DateTimeToString( StrTime, 'hh:nn:ss' , timeNow ); if IncludeDate then begin DateTimeToString( StrDate, 'dd/mm/yy' , timeNow ); result := format('%s %s',[StrDate,StrTime]); end else result := format('%s',[StrTime]); end; function tgUtils_TimeDataNowForFileName:string; begin DateTimeToString( result, 'ddmmyyhhnnss' , now ); end; function tgUtils_FormatStrAlarmType(alarmInt: integer): string; begin if alarmInt = 1 then result := 'High/High Interpretation' else if alarmInt = 2 then result := 'High/Low Interpretation' else if alarmInt = 3 then result := 'Low/Low Interpretation' else result := 'None' end; procedure tgUtils_DelimitString(s:string; var l:TStringList); begin l.Delimiter:=','; l.StrictDelimiter:=true; l.DelimitedText:=s; end; function tgUtils_CelciusToFahrenheit(celcius:Double):Double; begin result := (celcius * 9 * 0.2) + 32; end; function tgUtils_checkCmdIntegrity(s:string): Integer; var tokens: TStringList; ActualTokenCount, IntendedTokenCount: Integer; begin tokens := TStringList.Create; tgUtils_DelimitString(s,tokens); ActualTokenCount := tokens.Count; try IntendedTokenCount := StrToInt(tokens[1]); except result := TGRQST_INTEGRITY_ERROR_OTHER; tokens.Free; Exit; end; // token count error if ActualTokenCount <> IntendedTokenCount then begin result := TGRQST_INTEGRITY_ERROR_TOKEN_COUNT; tokens.Free; exit; end; // command match error if tokens[0] <> tokens[ActualTokenCount-1] then begin result := TGRQST_INTEGRITY_ERROR_CMD_MISMATCH; tokens.Free; exit; end; tokens.Free; result := TGRQST_INTEGRITY_PASS; end; function tgUtils_GetRootFsDirectory: String; var Registry: TRegistry; begin Registry := TRegistry.Create(KEY_READ or $0200); try // Navigate to proper "directory": Registry.RootKey := HKEY_LOCAL_MACHINE; if Registry.OpenKeyReadOnly('\SOFTWARE\Wow6432Node\Tempgard\Tempgard\Settings') then result:=Registry.ReadString('DataPath') else if Registry.OpenKeyReadOnly('\SOFTWARE\Tempgard\Tempgard\Settings') then result:=Registry.ReadString('DataPath'); finally Registry.Free; end; end; function tgUtils_MinutesToHMSComponents( mins: Integer ): hms; var hr, mhr, min, scd, sec: Integer; begin sec := mins * 60; hr := sec div 3600; mhr := sec mod 3600; min := mhr div 60; scd := mhr mod 60; if hr > 0 then begin result.hrs := hr; result.mins := 0; result.secs := 0; end else if min > 0 then begin result.hrs := 0; result.mins := min; result.secs := 0; end else begin result.hrs := 0; result.mins := 0; result.secs := scd; end; end; { Extract the start and stop date/time stamps for the session } function tgutils_SessionDataRange( filepath: string; var first, last: string ): integer; var fileToOpen: String; sf, sl: TStringList; fieldCount, lineCount : Integer; numberOfNrdFiles: integer; begin numberOfNrdFiles := tgUtils_CountDataFiles(filepath); if numberOfNrdFiles = 0 then begin first:=''; last:=''; result := 0; end; // get the start sample, try open nrd0 fileToOpen := format( '%s\%dnrd.txt', [ filepath, 0 ] ); sf := TStringList.Create; try sf.LoadFromFile( fileToOpen ); except on e:Exception do begin first:=''; last:=''; result := 0; sf.Free; Exit; end; end; sl := TStringList.Create; sl.Delimiter := ','; sl.StrictDelimiter := True; sl.DelimitedText := sf[0]; // number of fields per line, should be 6 fieldCount := sl.Count; if fieldCount = 0 then begin first:=''; last:=''; sl.Free; sf.Free; result := 0; Exit; end; first := sl[0]; sl.Free; sf.Free; // get the last sample, try open last page from sensor 1 fileToOpen := format( '%s\%dnrd.txt', [ filepath, numberOfNrdFiles-1 ] ); sf := TStringList.Create; try sf.LoadFromFile( fileToOpen ); except on e:Exception do begin first:=''; last:=''; sf.Free; result := 0; Exit; end; end; lineCount := sf.Count; sl := TStringList.Create; sl.Delimiter := ','; sl.StrictDelimiter := True; sl.DelimitedText := sf[lineCount -1]; // number of fields per line, should be 6 fieldCount := sl.Count; if fieldCount = 0 then begin first:=''; last:=''; sl.Free; sf.Free; result := 0; Exit; end; last := sl[0]; result := numberofnrdfiles; sl.Free; sf.Free; end; function tgutils_CountDataFiles( sessionfolderpath: string ): Integer; var FileSearch: SysUtils.TSearchRec; begin // number of log files result := 0; if SysUtils.FindFirst( sessionfolderpath + '\*nrd.txt', faAnyFile, FileSearch ) = 0 then begin repeat result := result + 1; until SysUtils.FindNext( FileSearch ) <> 0; SysUtils.FindClose( FileSearch ); end; end; function tgUtils_targzUnpack(fileToUnpack:string): Boolean; var gz: TGZFileStream; tx: TFileStream; trfileName: String; block: array[0..4095] of char; chp: PChar; bytes: longint; begin if not fileExists( fileToUnpack ) then begin result := False; Exit; end; chp := Addr( block[0] ); trfilename := ExtractFilePath(fileToUnpack) + EXtractFileName(fileToUnpack) + '.tar'; // tar file stream tx := TFileStream.Create(trfilename, fmOpenWrite or fmCreate); // gz file stream gz := TGZFileStream.create(fileToUnpack, gzopenread); // copy uncompressed gz stream to text file string try repeat bytes := gz.read(chp^, 4096); tx.Write(chp^, bytes); until bytes = 0; finally tx.Free; gz.Free; end; // Extract tar if tgUtils_untar(trfilename) then Result := True else Result := False; end; {: Extract a .tar file } function tgUtils_untar(tarfilename:string): Boolean; var TarArch : TTarArchive; TarDir : TTarDirRec; TarDirectory: string; begin if not FileExists( tarfilename ) then begin Result := False; Exit; end; TarDirectory := ExtractFilePath(tarfilename); TarArch := TTarArchive.Create( tarfilename ); Try TarArch.Reset; // dummy init TarDir.Name:=''; while TarArch.FindNext( TarDir ) do begin // if directory then create it {if TarDir.FileType = ftDirectory then ForceDirectories( ExcludeTrailingBackslash(TarDirectory) +'\' + string(TarDir.Name) ); } // if file then, extract from archive to file if TarDir.FileType = ftNormal then TarArch.ReadFile( TarDirectory + string(TarDir.Name) ); //TarArch.ReadFile( currentDir + 'Elogger\Alfatron - Engineering Room\eloggerrpi\Copy\tpg\shd\' + string(TarDir.Name) ); end; finally TarArch.Destroy; Result := True; end; end; function tgUtils_RegistryGetAppDataPath: String; var Registry: TRegistry; begin Registry := TRegistry.Create(KEY_READ or $0200); try // Navigate to proper "directory": Registry.RootKey := HKEY_LOCAL_MACHINE; if Registry.OpenKeyReadOnly('\SOFTWARE\Wow6432Node\Tempgard\Tempgard\Settings') then result:=Registry.ReadString('DataPath') else if Registry.OpenKeyReadOnly('\SOFTWARE\Tempgard\Tempgard\Settings') then result:=Registry.ReadString('DataPath'); finally Registry.Free; end; end; end.
var a:array[0..20000] of longint; n,b,i,j:longint; procedure quicksort(m,n:longint); var i,j,x,temp:longint; begin x:=a[(m+n) div 2]; i:=m; j:=n; repeat while a[i]>x do i:=i+1; while a[j]<x do j:=j-1; if i<=j then begin temp:=a[i]; a[i]:=a[j]; a[j]:=temp; i:=i+1; j:=j-1; end; until i>j; if m<j then quicksort(m,j); if i<n then quicksort(i,n); end; begin read(n,b); for i:=1 to n do read(a[i]); quicksort(1,n); j:=0; i:=0; while j<b do begin inc(i); j:=j+a[i]; end; writeln(i); end.
unit XmlPatch; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. } interface uses SysUtils, StringSupport, AdvObjects, AdvGenerics, MXML; type TXmlPatchEngine = class (TAdvObject) private class procedure remove(doc : TMXmlDocument; sel : String; target : TMXmlElement); class procedure add(doc : TMXmlDocument; op : TMXmlElement; target : TMXmlElement); class procedure replace(doc : TMXmlDocument; op : TMXmlElement; target : TMXmlElement); class procedure addChildNodes(doc : TMXmlDocument; source, target : TMXmlElement; pos : String); public class procedure execute(doc : TMXmlDocument; target : TMXmlElement; patch : TMXmlElement); end; implementation { TXmlPatchEngine } class procedure TXmlPatchEngine.execute(doc : TMXmlDocument; target : TMXmlElement; patch: TMXmlElement); begin if doc = nil then raise Exception.Create('No Target Document Root Found'); if target = nil then raise Exception.Create('No Target Element Found'); if patch = nil then raise Exception.Create('No Patch Operations Found'); patch := patch.firstElement; if patch = nil then raise Exception.Create('No Patch Operations Found'); doc.NamespaceAbbreviations.AddOrSetValue('f', 'http://hl7.org/fhir'); doc.NamespaceAbbreviations.AddOrSetValue('h', 'http://www.w3.org/1999/xhtml'); while (patch <> nil) do begin if (patch.localName = 'remove') then remove(doc, patch.attribute['sel'], target) else if (patch.localName = 'add') then add(doc, patch, target) else if (patch.localName = 'replace') then replace(doc, patch, target) else raise Exception.Create('Unknown Patch Operation "'+patch.localName+'"'); patch := patch.nextElement; end; end; procedure checkEndsWithAttribute(var path, attrName : String); var l, r : String; begin StringSplitRight(path, '/', l, r); if (r.StartsWith('@')) then begin path := l; attrName := r.Substring(1); end else attrName := ''; end; class procedure TXmlPatchEngine.add(doc : TMXmlDocument; op : TMXmlElement; target : TMXmlElement); var matches : TAdvList<TMXmlNode>; elem : TMXmlElement; sel, typ, pos : String; begin sel := op.attribute['sel']; typ := op.attribute['type']; pos := op.attribute['pos']; matches := doc.select(sel, target); try if matches.count = 0 then raise Exception.Create('No match found for '+sel+' performing addition'); if matches.count > 1 then raise Exception.Create('The xpath '+sel+' matched multiple nodes performing addition'); if typ = '' then addChildNodes(doc, op, matches[0] as TMXmlElement, pos) else if typ.StartsWith('@') then begin elem := matches[0] as TMXmlElement; elem.attribute[typ.Substring(1)] := op.text; end else if typ.StartsWith('namespace::') then begin elem := matches[0] as TMXmlElement; elem.attribute['xmlns:'+typ.Substring(11)] := op.text; end else raise Exception.Create('Unknown value for type: '+typ); finally matches.Free; end; end; class procedure TXmlPatchEngine.replace(doc : TMXmlDocument; op : TMXmlElement; target : TMXmlElement); var matches : TAdvList<TMXmlNode>; n, ce : TMXmlElement; sel : String; begin sel := op.attribute['sel']; matches := doc.select(sel, target); try if matches.count = 0 then raise Exception.Create('No match found for '+sel+' performing replace'); if matches.count > 1 then raise Exception.Create('The xpath '+sel+' matched multiple nodes performing replace'); case TMXmlNamedNode(matches[0]).nodeType of ntElement : begin n := op.first; ce := TMXmlElement.Create(ntElement, TMXmlElement(n).Name, n.localName, n.namespaceURI); try ce.Attributes.addAll(n.Attributes); addChildNodes(doc, n, ce, ''); TMXmlElement(matches[0]).parent.Children.replace(TMXmlElement(matches[0]), ce.Link); ce.Parent := matches[0].parent; finally ce.Free; end; end; ntText, ntComment : TMXmlElement(matches[0]).text := op.text; ntAttribute : TMXmlAttribute(matches[0]).value := op.text; else raise Exception.Create('Unsupported Node Type for replace'); end; finally matches.Free; end; end; class procedure TXmlPatchEngine.remove(doc : TMXmlDocument; sel: String; target: TMXmlElement); var matches : TAdvList<TMXmlNode>; elem : TMXmlElement; attrName : String; begin checkEndsWithAttribute(sel, attrName); matches := doc.select(sel, target); try if matches.count = 0 then raise Exception.Create('Nothing to delete found for xpath '+sel); if matches.count > 1 then raise Exception.Create('The xpath '+sel+' matched multiple nodes'); if attrName <> '' then begin elem := matches[0] as TMXmlElement; elem.Attributes.Remove(attrName) end else matches[0].parent.Children.remove(matches[0] as TMXmlElement); finally matches.Free; end; end; class procedure TXmlPatchEngine.addChildNodes(doc : TMXmlDocument; source, target: TMXmlElement; pos : String); var n, c : TMXmlElement; ce, elem : TMXmlElement; begin n := source.first; while n <> nil do begin case n.nodeType of ntElement : begin ce := TMXmlElement.create(ntElement, n.Name, n.localName, n.namespaceURI); try elem := (n as TMXmlElement); ce.Attributes.addAll(elem.attributes); addChildNodes(doc, n, ce, ''); c := ce.Link; finally ce.Free; end; end; ntText : c := TMXmlElement.createText(n.text); ntComment : c := TMXmlElement.createComment(n.text); else raise Exception.Create('Node type not supported '+inttostr(ord(n.nodeType))); end; if pos = '' then begin target.Children.add(c); c.Parent := target; end else if (pos = 'before') then begin target.parent.Children.insert(target.parent.Children.IndexOf(target), c); c.Parent := target.Parent; end else raise Exception.Create('Pos "'+pos+'" not supported'); n := n.next; end; end; end.
(* @abstract(Contient un composant pour gérer et interagir avec les raccourcis clavier. @br TBZHotKeyManager permet d'intercepter les raccourcis clavier depuis le système (Application minimisée) et dans la fenêtre active en cours.) -------------------------------------------------------------------------------- @created(2016-11-16) @author(J.Delauney (BeanzMaster)) Historique : @unorderedList( @item(10/07/2019 : Creation ) ) -------------------------------------------------------------------------------- @bold(Notes) : - Compatible Windows et Linux (Gnome, KDE, XFCE...) - Sous MacOS fonctionne si vous utiliser GTK et X11 -------------------------------------------------------------------------------- @bold(Dependances) : -------------------------------------------------------------------------------- @bold(Credits :) @unorderedList( @item () @item(J.Delauney (BeanzMaster)) ) -------------------------------------------------------------------------------- @bold(LICENCE) : MPL / GPL -------------------------------------------------------------------------------- *) unit BZHotKeyManager; //============================================================================== {$mode objfpc}{$H+} {$i ..\..\bzscene_options.inc} //============================================================================== interface //============================================================================== uses Classes, SysUtils, LCLProc, LCLType, LCLIntf, LResources, LMessages, Forms, Controls, Graphics, Dialogs, {$IFDEF WINDOWS} windows {$ENDIF} {$IFDEF LINUX} Unix, x, xlib, gdk2, gdk2x {$ENDIF}; {.$IFDEF DARWIN} // Il semblrerait qu'en utilisant "NSEvent" il est possible d'intercepter les evenements clavier // à la fois sous Carbon et Cocoa. Mais aucune idées comment implémenter ça. {.$IFDEF CARBON} // FPCMacOSAll, {.$ELSE} {.$ENDIF} {.$ENDIF} {$IFDEF UNIX} Const MOD_SHIFT = $2000; //< scShift MOD_CONTROL = $4000; //< scCtrl MOD_ALT = $8000; //< scAlt MOD_WIN = $10000; //< scWin {$ENDIF} // ============================================================================== Type { Methode de déclenchement d'une action, lors de l'appui d'un raccourci clavier } TOnHotKeyEvent = procedure(Index: Integer) of object; Type { Permet de définir un raccourci clavier } TBZHotKeyItem = class(TCollectionItem) private FHotKey: TShortCut; // Cardinal; FKeyIndex: Integer; FOnExecute: TNotifyEvent; protected procedure setKeyIndex(AValue: Integer); public constructor Create(ACollection: TCollection); override; published { Definition du raccourci } property HotKey: TShortCut read FHotKey write FHotKey; { Index du raccourci dans la liste} property Index: Integer read FKeyIndex; { Evènement déclencher à l'appui du raccourci } property OnExecute: TNotifyEvent Read FOnExecute Write FOnExecute stored; end; { Liste des raccourcis clavier } TBZHotKeyList = class(TCollection) private function GetItems(Index: Integer): TBZHotKeyItem; procedure SetItems(Index: Integer; AValue: TBZHotKeyItem); public constructor Create; public { Ajout d'un raccourci à la liste } function Add: TBZHotKeyItem; { Acces aux raccourcis de la liste } property Items[Index: Integer]: TBZHotKeyItem read GetItems write SetItems; default; end; {$IFDEF LINUX} Type { TBZHotKeyManager : Gestionnaire de raccourcis clavier } TBZHotKeyManager = class; Type { TBZXEventListener : Ecoute des évènements clavier sous Linux } TBZXEventListener = class(TThread) private FApplicationHotKeys: TBZHotKeyManager; protected procedure Execute; override; public constructor Create(AAppHotKey: TBZHotKeyManager); end; {$ENDIF} type { Gestionnaire de raccourcis clavier standard } TBZHotKeyManager = class(TComponent) private FHotKeyList: TBZHotKeyList; // FOnHotKey : TOnHotKeyEvent; //TNotifyEvent; // ---------------------------------------------------------------------------- // Variables pour intercepter les "HotKeys" sous Linux {$IFDEF LINUX} FXEventListener: TThread; // Un thread pour intercepter les messages du systeme {$ENDIF} // -------------------------------------------------------------------------- // Fonctions pour intercepter les "HotKeys" sous Windows {$IFDEF WINDOWS} function CreateAppWindow: boolean; {$ENDIF} // -------------------------------------------------------------------------- // Fonctions internes du composant pour construire et detruire les raccourcis function DoRegisterHotKey(hk: Cardinal): Integer; function DoUnregisterHotKey(KeyIndex: Integer): boolean; protected FActive: boolean; // Lancement de notre evenement à l'interception d'un raccourci procedure DoOnHotKey(Index: Integer); virtual; procedure Loaded; override; procedure SetActive(Value: boolean); virtual; // -------------------------------------------------------------------------- // Fonctions pour intercepter les "HotKeys" sous Linux {$IFDEF LINUX} procedure WaitForXevent; {$ENDIF} // Fonctions pour intercepter les "HotKeys" sous Mac {$IFDEF DARWIN} {$ENDIF} public { Public declarations } {$IFDEF LINUX} Display: PDisplay; {$ENDIF} { Creation du composant TBZHotKeyManager } constructor Create(AOwner: TComponent); override; { Destruction du composant TBZHotKeyManager } destructor Destroy; override; { Creation d'un raccourci clavier. Exemple : CreateHotKey(MOD_CONTROL+MOD_ALT,VK_G); Correspond à CTRL+ALT+G } function CreateHotKey(Modifiers, Key: Word): Cardinal; { Ajoute un raccourci clavier à la liste } function AddHotKey(HotKey: Cardinal): Integer; { Modifie un raccourci clavier à la liste } function ChangeHotKey(Index: Integer; NewHotKey: Cardinal): Integer; { Efface un raccourci clavier à la liste } function RemoveHotKey(HotKey: Cardinal): boolean; { Efface le raccourci clavier à l'index "Index" de la liste } function RemoveHotKeyByIndex(Index: Integer): boolean; { Efface tous les raccourcis clavier de la liste } procedure ClearHotKeys; { Retourne @True si le raccourci clavier est valide } function HotKeyValid(HotKey: Cardinal): boolean; { Vérifie si un raccourci est deja inscrit dans le systeme. Retourne @True si le raccourci clavier peu être utilisé } function HotKeyExist(Index: Integer): Integer; { Efface et libère le raccourci clavier de la liste } function FreeHotKey(Index: Integer): boolean; published { Gestion des raccourcis actif ou pas } property Active: boolean read FActive write SetActive default false; { Liste des raccourcis } property HotKeys: TBZHotKeyList read FHotKeyList write FHotKeyList; // property OnHotKey : TOnHotKeyEvent read FOnHotKey write FOnHotKey; end; { Gestionnaire de raccourcis clavier au niveau d'une fenêtre } TBZFormHotKeyManager = class(TBZHotKeyManager) private protected FInitialized: boolean; FParentForm: TForm; FSaveProc: TShortCutEvent; procedure DoOnFormShortCut(var Msg: TLMKey; var Handled: boolean); virtual; procedure Loaded; override; procedure SetActive(Value: boolean); override; public { Creation du composant TBZHotKeyManager } constructor Create(AOwner: TComponent); override; { Destruction du composant TBZHotKeyManager } destructor Destroy; override; published { Published declarations } property Active; property HotKeys; end; { Gestionnaire de raccourcis clavier au niveau de l'application } TBZAppHotKeyManager = class(TBZFormHotKeyManager) private protected procedure DoOnApplicationShortCut(var Msg: TLMKey; var Handled: boolean); virtual; procedure SetActive(Value: boolean); override; procedure Loaded; override; public { Creation du composant TBZHotKeyManager } constructor Create(AOwner: TComponent); override; { Destruction du composant TBZHotKeyManager } destructor Destroy; override; published property Active; property HotKeys; end; //============================================================================== //procedure SeparateHotKey(HotKey: Cardinal; var Modifiers, Key: Word); //============================================================================== implementation // ============================================================================== {$IFDEF WINDOWS} const WinClassName: string = 'HOTKEYBZAPPLICATIONHOTKEY'; HotKeyAtomPrefix: string = 'BeanzHotKeyAtom'; var // ---------------------------------------------------------------------------- // Variables pour intercepter les "HotKeys" sous Windows HWindow: HWND; WindowClassAtom: ATOM; // Renvoyer par RegisterWindowClass en cas de succes. WindowClassInfo: WNDCLASSEX; // Structure des infos d'une fenetre {$ENDIF} {%region=====[ Fonctions Internes ]=============================================================} { Separe les touches normal et les touches de controle du Hotkeys pour les utiliser avec RegisterHotKey } procedure SeparateHotKey(HotKey: Cardinal; var Modifiers, Key: Word); {$IFDEF WINDOWS} const VK2_SHIFT = 32; VK2_CONTROL = 64; VK2_ALT = 128; VK2_WIN = 256; {$ENDIF} var Virtuals: Integer; V: Word; x: Word; {$IFDEF LINUX} i: Integer; function correctModifiers(Modifiers: Word; flags: Integer): Integer; var ret: Word; begin ret := Modifiers; if ((flags and 1) <> 0) then ret := ret OR LockMask; if ((flags and 2) <> 0) then ret := ret OR Mod2Mask; if ((flags and 4) <> 0) then ret := ret OR Mod3Mask; if ((flags and 8) <> 0) then ret := ret OR Mod5Mask; Result := ret; end; {$ENDIF} begin Key := Byte(HotKey); x := HotKey shr 8; Virtuals := x; {$IFDEF WINDOWS} V := 0; if (Virtuals and VK2_WIN) <> 0 then Inc(V, MOD_WIN); if (Virtuals and VK2_ALT) <> 0 then Inc(V, MOD_ALT); if (Virtuals and VK2_CONTROL) <> 0 then Inc(V, MOD_CONTROL); if (Virtuals and VK2_SHIFT) <> 0 then Inc(V, MOD_SHIFT); Modifiers := V; {$ENDIF} {$IFDEF LINUX} V := Virtuals; for i := 0 to 15 do begin V := correctModifiers(V, i); end; Modifiers := V; {$ENDIF} {$IFDEF DARWIN} {$ENDIF} end; {$IFDEF WINDOWS} { Handler pour Intercepter les message WM_HOTKEY Nb: Vous pouvez intercepter d'autre messages comme ceux de la souris, suffit d'ajouter des conditions au CASE ce qui permettrai avec un peu d'ingéniosité de faire des HotKeys genre : CRTL + ALT + G + SOURIS_BOUTON_GAUCHE } function WinProc(hw: HWND; uMsg: UINT; wp: WPARAM; lp: LPARAM): LRESULT; stdcall; export; var obj: TBZHotKeyManager; idx: Integer; begin Result := 0; case uMsg of WM_HOTKEY: begin obj := TBZHotKeyManager(GetWindowLongPtr(HWindow, GWL_USERDATA)); idx := obj.HotKeyExist(Longint(wp)); if (idx > -1) and (obj.Active) then obj.DoOnHotKey(idx); end else Result := DefWindowProc(hw, uMsg, wp, lp); end; end; {$ENDIF} { Récupère la fenètre propriétaire du composant } function GetOwnerForm(AComponent: TComponent): TCustomForm; var LOwner: TComponent; begin LOwner := AComponent.Owner; if (LOwner = nil) or (LOwner is TCustomForm) then Result := TCustomForm(LOwner) else Result := GetOwnerForm(LOwner); end; {%endregion%} {%region=====[ TBZHotKeyItem ]==================================================================} constructor TBZHotKeyItem.Create(ACollection: TCollection); begin if Assigned(ACollection) and (ACollection is TBZHotKeyList) then inherited Create(ACollection); end; procedure TBZHotKeyItem.setKeyIndex(AValue: Integer); begin if FKeyIndex = AValue then exit; FKeyIndex := AValue; end; {%endregion%} {%region=====[ TBZHotKeyList ]==================================================================} constructor TBZHotKeyList.Create; begin inherited Create(TBZHotKeyItem); end; function TBZHotKeyList.GetItems(Index: Integer): TBZHotKeyItem; begin Result := TBZHotKeyItem(inherited Items[Index]); end; procedure TBZHotKeyList.SetItems(Index: Integer; AValue: TBZHotKeyItem); begin Items[Index].Assign(AValue); end; function TBZHotKeyList.Add: TBZHotKeyItem; begin Result := inherited Add as TBZHotKeyItem; end; {%endregion%} {%region=====[ TBZXEventListener ]==============================================================} {$IFDEF LINUX} constructor TBZXEventListener.Create(AAppHotKey: TBZHotKeyManager); begin inherited Create(True); FApplicationHotKeys := AAppHotKey; end; { Ecoute les evenements } procedure TBZXEventListener.Execute; begin while not(Terminated) do begin //if not Terminated then //begin Synchronize(@FApplicationHotKeys.WaitForXevent); //end; //if Terminated then exit; end; end; {$ENDIF} {%endregion%} {%region=====[ TBZHotKeyManager ]===============================================================} constructor TBZHotKeyManager.Create(AOwner: TComponent); begin inherited Create(AOwner); Self.SetSubComponent(True); // add this line if you want to put this class inside other and also be streamed FHotKeyList := TBZHotKeyList.Create; if not(csDesigning in ComponentState) then begin {$IFDEF WINDOWS} CreateAppWindow; {$ENDIF} {$IFDEF LINUX} FXEventListener := TBZXEventListener.Create(Self); Display := XOpenDisplay(gdk_get_display); {$ENDIF} {$IFDEF DARWIN} {$ENDIF} end; end; destructor TBZHotKeyManager.Destroy; begin ClearHotKeys; {$IFDEF WINDOWS} DestroyWindow(HWindow); {$ENDIF} {$IFDEF LINUX} FXEventListener.Terminate; FXEventListener.WaitFor; FXEventListener.Free; XCloseDisplay(Display); {$ENDIF} {$IFDEF DARWIN} {$ENDIF} FHotKeyList.Free; inherited Destroy; end; {$IFDEF WINDOWS} { Creation d'une fenetre virtuelle avec notre Hook } function TBZHotKeyManager.CreateAppWindow: boolean; function RegisterWindowClass: boolean; begin WindowClassInfo.cbSize := sizeof(WindowClassInfo); WindowClassInfo.Style := 0; WindowClassInfo.lpfnWndProc := @WinProc; WindowClassInfo.cbClsExtra := 0; WindowClassInfo.cbWndExtra := 0; WindowClassInfo.hInstance := hInstance; WindowClassInfo.hIcon := 0; WindowClassInfo.hCursor := 0; WindowClassInfo.hbrBackground := 0; WindowClassInfo.lpszMenuName := nil; WindowClassInfo.lpszClassName := PChar(WinClassName); WindowClassInfo.hIconSm := 0; WindowClassAtom := RegisterClassEx(WindowClassInfo); Result := WindowClassAtom <> 0; end; begin Result := false; if not RegisterWindowClass then begin exit; end; HWindow := CreateWindowEx(WS_EX_NOACTIVATE or WS_EX_TRANSPARENT, PChar(WinClassName), PChar(WinClassName), Ws_popup or WS_CLIPSIBLINGS, 0, 0, 0, 0, 0, 0, hInstance, nil); if HWindow <> 0 then begin ShowWindow(HWindow, SW_HIDE); SetWindowLongPtr(HWindow, GWL_USERDATA, PtrInt(Self)); UpdateWindow(HWindow); Result := True; exit; end; end; {$ENDIF} { Ajoute un HotKey Global dans le systeme d'exploitation } function TBZHotKeyManager.DoRegisterHotKey(hk: Cardinal): Integer; var Modifiers, Key: Word; id: Integer; {$IFDEF LINUX} root: PGdkWindow; {$ENDIF} begin Result := 0; Modifiers := 0; Key := 0; SeparateHotKey(hk, Modifiers, Key); {$IFDEF WINDOWS} id := GlobalAddAtom(PChar(HotKeyAtomPrefix + IntToStr(hk))); RegisterHotKey(HWindow, Longint(id), Modifiers, Key); Result := id; {$ENDIF} {$IFDEF LINUX} root := gdk_get_default_root_window(); Display := GDK_WINDOW_XDISPLAY(root); gdk_error_trap_push; id := XGrabKey(Display, Key, Modifiers, gdk_x11_drawable_get_xid(root), 1, GrabModeAsync, GrabModeAsync); gdk_flush; Result := id; //(gdk_error_trap_pop); //= 0; {$ENDIF} {$IFDEF DARWIN} {$ENDIF} end; { Supprime un HotKey Global dans le systeme d'exploitation } function TBZHotKeyManager.DoUnregisterHotKey(KeyIndex: Integer): boolean; {$IFDEF LINUX} var root: PGdkWindow; Modifiers, Key: Word; hk: Cardinal; {$ENDIF} begin {$IFDEF WINDOWS} Result := UnRegisterHotkey(HWindow, Longint(KeyIndex)); GlobalDeleteAtom(KeyIndex); {$ENDIF} {$IFDEF LINUX} root := gdk_get_default_root_window(); Display := GDK_WINDOW_XDISPLAY(root); hk := Cardinal(FHotKeyList[HotKeyExist(KeyIndex)].HotKey); SeparateHotKey(hk, Modifiers, Key); XUngrabKey(Display, Key, Modifiers, gdk_x11_drawable_get_xid(root)); Result := (gdk_error_trap_pop)= 0; {$ENDIF } {$IFDEF DARWIN} {$ENDIF} end; { Lance une action lorsque le HotKey est intercepté } procedure TBZHotKeyManager.DoOnHotKey(Index: Integer); begin if Assigned(FHotKeyList[Index].OnExecute) then FHotKeyList[Index].OnExecute(Self); end; { Active/Désactive l'interception des HotKeys Est utilisé par la version Linux et n'a aucun effet sous Windows } procedure TBZHotKeyManager.SetActive(Value: boolean); begin if FActive <> Value then begin FActive := Value; {$IFDEF LINUX} if not(csDesigning in ComponentState) then begin if FActive then begin FXEventListener.Suspended := false; end else begin FXEventListener.Suspended := True; end end; {$ENDIF} end; end; { Effectue une action lorsque le composant est chargé } procedure TBZHotKeyManager.Loaded; var i, j: Integer; // hk: TBZHotKeyItem; id: Integer; begin inherited; if not(csDesigning in ComponentState) then begin j := FHotKeyList.Count; if j > 0 then begin for i := 0 to j - 1 do begin // hk:=; id := DoRegisterHotKey(Cardinal(FHotKeyList.Items[i].HotKey)); if id > 0 then begin FHotKeyList.Items[i].setKeyIndex(id); end else Showmessage('Erreur'); end; end; end; end; {$IFDEF LINUX} { Attente d'interception des raccourcis sous Linux } procedure TBZHotKeyManager.WaitForXevent; var event: TXEvent; i, j, state: Integer; Modifiers, Key: Word; xkey: TXKeyEvent; hk: TBZHotKeyItem; begin // event := XEvent.Create(); while (XPending(Display) > 0) do begin XNextEvent(Display, @event); if (event._type = KeyPress) then begin xkey := TXKeyEvent(event.xkey); state := xkey.state and (ShiftMask or ControlMask or Mod1Mask or Mod4Mask); j := FHotKeyList.Count - 1; for i := 0 to j do begin hk := FHotKeyList[i]; // ;^.HotKey; SeparateHotKey(Cardinal(hk.HotKey), Modifiers, Key); if (xkey.keycode = Key) and (state = Modifiers) then begin DoOnHotKey(i); end; end; end; end; end; {$ENDIF} function TBZHotKeyManager.CreateHotKey(Modifiers, Key: Word): Cardinal; const VK2_SHIFT = 32; VK2_CONTROL = 64; VK2_ALT = 128; VK2_WIN = 256; var hk: Cardinal; begin hk := 0; if (Modifiers and MOD_ALT) <> 0 then Inc(hk, VK2_ALT); if (Modifiers and MOD_CONTROL) <> 0 then Inc(hk, VK2_CONTROL); if (Modifiers and MOD_SHIFT) <> 0 then Inc(hk, VK2_SHIFT); if (Modifiers and MOD_WIN) <> 0 then Inc(hk, VK2_WIN); hk := hk shl 8; Inc(hk, Key); Result := hk; end; function TBZHotKeyManager.AddHotKey(HotKey: Cardinal): Integer; var hk: TBZHotKeyItem; // PHotKey; id: Integer; begin // Creation d'un ID Unique id := DoRegisterHotKey(HotKey); if id > 0 then begin hk := FHotKeyList.Add; hk.HotKey := TShortCut(HotKey); hk.setKeyIndex(id); // hk := New(PHotKey); // hk^.HotKey := HotKey; // hk^.KeyIndex := id; // FHotKeyList.Add(hk); Result := FHotKeyList.Count - 1; end else begin Result := -1; end; end; function TBZHotKeyManager.ChangeHotKey(Index: Integer; NewHotKey: Cardinal): Integer; var i, j: Integer; hk: TBZHotKeyItem; // PHotKey; begin Result := 0; j := FHotKeyList.Count - 1; for i := 0 to j do begin hk := FHotKeyList[i]; if hk.Index = Index then begin RemoveHotKeyByIndex(Index); Result := AddHotKey(NewHotKey); exit; end; end; end; function TBZHotKeyManager.RemoveHotKey(HotKey: Cardinal): boolean; var i, j: Integer; hk: TBZHotKeyItem; // PHotKey; begin Result := false; j := FHotKeyList.Count - 1; for i := 0 to j do begin hk := FHotKeyList[i]; if hk.HotKey = TShortCut(HotKey) then begin Result := FreeHotKey(i); FHotKeyList.Delete(i); exit; end; end; end; function TBZHotKeyManager.RemoveHotKeyByIndex(Index: Integer): boolean; var i, j: Integer; hk: TBZHotKeyItem; begin Result := false; j := FHotKeyList.Count - 1; for i := 0 to j do begin hk := FHotKeyList[i]; if hk.Index = Index then begin Result := FreeHotKey(i); FHotKeyList.Delete(i); exit; end; end; end; function TBZHotKeyManager.HotKeyValid(HotKey: Cardinal): boolean; var M, K: Word; WasRegistered: boolean; {$IFDEF WINDOWS} ATOM: Word; {$ENDIF} begin {$IFDEF WINDOWS} K := 0; M := 0; ATOM := GlobalAddAtom(PChar(HotKeyAtomPrefix + IntToStr(HotKey))); SeparateHotKey(HotKey, M, K); WasRegistered := UnRegisterHotkey(HWindow, ATOM); if WasRegistered then begin RegisterHotKey(HWindow, ATOM, M, K); Result := True; end else begin Result := RegisterHotKey(HWindow, ATOM, M, K); if Result then UnRegisterHotkey(HWindow, ATOM); end; GlobalDeleteAtom(ATOM); {$ENDIF} {$IFDEF LINUX} // @TODO : A Compléter Result := True; {$ENDIF} {$IFDEF DARWIN} {$ENDIF} end; function TBZHotKeyManager.HotKeyExist(Index: Integer): Integer; var i, j: Integer; begin Result := -1; j := FHotKeyList.Count - 1; for i := 0 to j do if FHotKeyList[i].Index = Index then begin Result := i; Break; end; end; procedure TBZHotKeyManager.ClearHotKeys; var i, j: Integer; // hk: PHotKey; begin j := FHotKeyList.Count - 1; for i := j downto 0 do begin // hk := PHotKey(FHotKeyList[I]); FreeHotKey(i); FHotKeyList.Delete(i); end; // FHotKeyList.Clear; end; function TBZHotKeyManager.FreeHotKey(Index: Integer): boolean; begin Result := DoUnregisterHotKey(FHotKeyList[Index].Index); // if Result then // Dispose(hk); end; {%endregion%} {%region=====[ TBZFormHotKeyManager ]===========================================================} constructor TBZFormHotKeyManager.Create(AOwner: TComponent); begin inherited Create(AOwner); FInitialized := false; FParentForm := TForm(GetOwnerForm(self)); //self.SetSubComponent(true); end; destructor TBZFormHotKeyManager.Destroy; begin inherited Destroy; end; { Handler OnShortCut de la form } procedure TBZFormHotKeyManager.DoOnFormShortCut(var Msg: TLMKey;var Handled: boolean); var wShortCut: TShortCut; i: Integer; ShiftState: TShiftState; // Word; begin Handled := false; ShiftState := MsgKeyDataToShiftState(Msg.KeyData); wShortCut := KeyToShortcut(Msg.CharCode, ShiftState); i := HotKeyExist(wShortCut); if i > -1 then begin DoOnHotKey(i); Handled := true; end; if Assigned(FSaveProc) then FSaveProc(Msg, Handled); end; procedure TBZFormHotKeyManager.SetActive(Value: boolean); begin if FActive = Value then exit; FActive := Value; if not(csDesigning in ComponentState) and FInitialized then begin if FActive then begin FParentForm.OnShortcut := @DoOnFormShortCut; end else begin FParentForm.OnShortcut := FSaveProc; end end; end; { Effectue une action lorsque le composant est chargé } procedure TBZFormHotKeyManager.Loaded; begin inherited; if Assigned(FParentForm.OnShortcut) then FSaveProc := FParentForm.OnShortcut else FSaveProc := nil; if Active then begin FParentForm.OnShortcut := @DoOnFormShortCut; FInitialized := true; end; end; {%endregion%} {%region=====[ TBZAppHotKeyManager ]============================================================} constructor TBZAppHotKeyManager.Create(AOwner: TComponent); begin inherited Create(AOwner); end; { Destruction de notre composant } destructor TBZAppHotKeyManager.Destroy; begin inherited Destroy; end; { Handler OnShortCut de la form } procedure TBZAppHotKeyManager.DoOnApplicationShortCut(var Msg: TLMKey; var Handled: boolean); var wShortCut: TShortCut; ShiftState: TShiftState; i: Integer; begin Handled := false; ShiftState := MsgKeyDataToShiftState(Msg.KeyData); wShortCut := KeyToShortcut(Msg.CharCode, ShiftState); {$IFDEF WINDOWS} case Msg.Msg of WM_HOTKEY: begin // Get modifier keys status if (lo(Msg.KeyData) and MOD_SHIFT) <> 0 then Include(ShiftState,ssShift); if (lo(Msg.KeyData) and MOD_CONTROL) <> 0 then Include(ShiftState, ssCtrl); if (lo(Msg.KeyData) and MOD_ALT) <> 0 then Include(ShiftState, ssAlt); if (lo(Msg.KeyData) and MOD_WIN) <> 0 then Include(ShiftState, ssSuper); end; end; {$ENDIF} wShortCut := KeyToShortcut(Msg.CharCode, ShiftState); i := HotKeyExist(wShortCut); if i > -1 then begin DoOnHotKey(i); Handled := true; end; if Assigned(FSaveProc) then FSaveProc(Msg, Handled); end; procedure TBZAppHotKeyManager.SetActive(Value: boolean); begin if FActive = Value then exit; FActive := Value; if not(csDesigning in ComponentState) and FInitialized then begin if FActive then begin Application.OnShortcut := @DoOnApplicationShortCut; end else begin Application.OnShortcut := FSaveProc; end end; end; { Effectue une action lorsque le composant est chargé } procedure TBZAppHotKeyManager.Loaded; begin inherited; if Assigned(FParentForm.OnShortcut) then FSaveProc := Application.OnShortcut else FSaveProc := nil; if Active then begin Application.OnShortcut := @DoOnApplicationShortCut; FInitialized := true; end; end; {%endregion%} end.
unit MainForm; //TODO: Service functions: //Autopaste //Directory capture (listing, .diz, etc) //TODO: Multiple files in tree? MDI? interface uses Windows, CommCtrl, Messages, ShellAPI, AvL, avlUtils, avlSettings, avlSplitter, Navigator, Editor, NotesFile, DataNode, ImportExport; type TVSNotesMainForm = class(TForm) MainMenu: TMenu; ToolBar: TToolBar; StatusBar: TStatusBar; Splitter: TSplitter; Navigator: TNavigator; Editor: TEditor; private FMinWidth, FMinHeight: Integer; FAccelTable: HAccel; FTBImages: TImageList; FFile: TNotesFile; procedure FileModified(Sender: TObject); function FormClose(Sender: TObject): Boolean; procedure FormResize(Sender: TObject); function FormProcessMsg(var Msg: TMsg): Boolean; function GetSettings: TSettings; procedure NavigatorNodeSelected(Sender: TObject); procedure NewClick(Sender: TObject); procedure OpenClick(Sender: TObject); procedure RepaintAll; procedure SaveClick(Sender: TObject; SaveAs: Boolean); procedure ImportClick(Sender: TObject); procedure OpenFile(const FileName: string); procedure ShowAbout; procedure SplitterMove(Sender: TObject); function RequestSave: Boolean; procedure SaveFile(const FileName: string); procedure UpdateCaptions; procedure WMCommand(var Msg: TWMCommand); message WM_COMMAND; procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; procedure WMSizing(var Msg: TWMMoving); message WM_SIZING; public constructor Create; destructor Destroy; override; end; var FormMain: TVSNotesMainForm; const AppCaption = 'VS Notes'; AppName = 'VSNotes'; implementation type TTBButtons = (tbNew, tbOpen, tbSave, tbPrint, tbUndo, tbCut, tbCopy, tbPaste, tbOptions); const SVFNFilter = 'VS Notes files|*.vsn|All files|*.*'; SDefExt = 'vsn'; SSaveNow = 'Current file has unsaved changes.'#13'Save now?'; CRLF = #13#10; AboutIcon = 'MAINICON'; AboutCaption = 'About '; AboutText = 'VgaSoft Notes 1.0 alpha'+CRLF+CRLF+ 'Copyright '#169' VgaSoft, 2015-2019'+CRLF+ 'vgasoft@gmail.com'; IDMenuFile = 1000; IDNew = IDMenuFile + 1; IDOpen = IDNew + 1; IDSave = IDOpen + 1; IDSaveAs = IDSave + 1; IDImport = IDSaveAs + 1; IDPrint = IDImport + 1; IDOptions = IDPrint + 1; IDExit = IDOptions + 2; MenuFileCapt = '&File'; MenuFile: array[0..9] of PChar = ('1001', '&New'#9'Ctrl-N', '&Open...'#9'Ctrl-O', '&Save'#9'Ctrl-S', 'Save &As...', 'Import...', '&Print...'#9'Ctrl-P', 'Op&tions...', '-', 'E&xit'#9'Alt-X'); IDMenuEdit = 2000; IDUndo = IDMenuEdit + 1; IDRedo = IDUndo + 1; IDCut = IDRedo + 2; IDCopy = IDCut + 1; IDPaste = IDCopy + 1; IDSelectAll = IDPaste + 1; MenuEditCapt = '&Edit'; MenuEdit: array[0..7] of PChar = ('2001', '&Undo'#9'Ctrl-Z', '&Redo'#9'Ctrl-Y', '-', 'Cu&t'#9'Ctrl-X', '&Copy'#9'Ctrl-C', '&Paste'#9'Ctrl-V', 'Se&lect All'#9'Ctrl-A'); IDMenuHelp = 5000; IDAbout = IDMenuHelp + 1; MenuHelpCapt = '&Help'; MenuHelp: array[0..1] of PChar = ('5001', '&About...'#9'F1'); TBButtons: array[0..10] of record Caption: string; ImageIndex: Integer; end = ( (Caption: 'New'; ImageIndex: 0), (Caption: 'Open'; ImageIndex: 1), (Caption: 'Save'; ImageIndex: 2), (Caption: 'Print'; ImageIndex: 7), (Caption: '-'; ImageIndex: -1), (Caption: 'Undo'; ImageIndex: 3), (Caption: 'Cut'; ImageIndex: 4), (Caption: 'Copy'; ImageIndex: 5), (Caption: 'Paste'; ImageIndex: 6), (Caption: '-'; ImageIndex: -1), (Caption: 'Options'; ImageIndex: 8)); TBMenuIDs: array[TTBButtons] of Word = (IDNew, IDOpen, IDSave, IDPrint, IDUndo, IDCut, IDCopy, IDPaste, IDOptions); var Accels: array[0..11] of TAccel = ( (fVirt: FCONTROL or FVIRTKEY; Key: Ord('N'); Cmd: IDNew), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('O'); Cmd: IDOpen), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('S'); Cmd: IDSave), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('P'); Cmd: IDPrint), (fVirt: FALT or FVIRTKEY; Key: Ord('X'); Cmd: IDExit), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('Z'); Cmd: IDUndo), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('Y'); Cmd: IDRedo), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('X'); Cmd: IDCut), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('C'); Cmd: IDCopy), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('V'); Cmd: IDPaste), (fVirt: FCONTROL or FVIRTKEY; Key: Ord('A'); Cmd: IDSelectAll), (fVirt: FVIRTKEY; Key: VK_F1; Cmd: IDAbout)); constructor TVSNotesMainForm.Create; procedure AddMenu(const Name: string; ID: Cardinal; const Template: array of PChar); var Menu: TMenu; begin Menu := TMenu.Create(Self, false, Template); InsertMenu(MainMenu.Handle, ID, MF_BYCOMMAND or MF_POPUP, Menu.Handle, PChar(Name)); end; var i: Integer; begin inherited Create(nil, AppCaption); OnClose := FormClose; OnProcessMsg := FormProcessMsg; SetSize(600, 400); Position := poScreenCenter; FMinHeight := 200; FMinWidth := 400; MainMenu := TMenu.Create(Self, true, ['0']); AddMenu(MenuFileCapt, IDMenuFile, MenuFile); AddMenu(MenuEditCapt, IDMenuEdit, MenuEdit); AddMenu(MenuHelpCapt, IDMenuHelp, MenuHelp); SetMenu(Handle, MainMenu.Handle); FAccelTable := CreateAcceleratorTable(Accels[0], Length(Accels)); FTBImages := TImageList.Create; FTBImages.AddMasked(LoadImage(hInstance, 'TBMAIN', IMAGE_BITMAP, 0, 0, 0), clFuchsia); ToolBar := TToolBar.Create(Self, true); ToolBar.Style := ToolBar.Style or TBSTYLE_TOOLTIPS or CCS_TOP; ToolBar.ExStyle := ToolBar.ExStyle or TBSTYLE_EX_MIXEDBUTTONS; ToolBar.Perform(TB_SETMAXTEXTROWS, 0, 0); ToolBar.Perform(TB_AUTOSIZE, 0, 0); ToolBar.Images := FTBImages; for i := Low(TBButtons) to High(TBButtons) do ToolBar.ButtonAdd(TBButtons[i].Caption, TBButtons[i].ImageIndex); StatusBar := TStatusBar.Create(Self, ''); Splitter := TSplitter.Create(Self, true); Splitter.SetBounds(200, ToolBar.Height, Splitter.Width, ClientHeight - ToolBar.Height - StatusBar.Height); Splitter.OnMove := SplitterMove; Navigator := TNavigator.Create(Self); Navigator.SetBounds(0, Splitter.Top, Splitter.Left, Splitter.Height); Navigator.OnModify := FileModified; Navigator.OnNodeSelected := NavigatorNodeSelected; Editor := TEditor.Create(Self); Editor.SetBounds(Splitter.Right, Splitter.Top, ClientWidth - Splitter.Right, Splitter.Height); Editor.OnModify := FileModified; for i := 1 to ParamCount do if FileExists(ParamStr(i)) then OpenFile(ExpandFileName(ParamStr(i))); DragAcceptFiles(Handle, true); OnResize := FormResize; FormResize(Self); end; function TVSNotesMainForm.GetSettings: TSettings; begin Result := TSettings.Create(AppName); end; procedure TVSNotesMainForm.ShowAbout; var Version: TOSVersionInfo; MsgBoxParamsW: TMsgBoxParamsW; MsgBoxParamsA: TMsgBoxParamsA; begin Version.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(Version); if Version.dwPlatformId = VER_PLATFORM_WIN32_NT then begin FillChar(MsgBoxParamsW, SizeOf(MsgBoxParamsW), #0); with MsgBoxParamsW do begin cbSize := SizeOf(MsgBoxParamsW); hwndOwner := Handle; hInstance := SysInit.hInstance; lpszText := PWideChar(WideString(AboutText)); lpszCaption := PWideChar(WideString(AboutCaption+Caption)); lpszIcon := AboutIcon; dwStyle := MB_USERICON; end; MessageBoxIndirectW(MsgBoxParamsW); end else begin FillChar(MsgBoxParamsA, SizeOf(MsgBoxParamsA), #0); with MsgBoxParamsA do begin cbSize := SizeOf(MsgBoxParamsA); hwndOwner := Handle; hInstance := SysInit.hInstance; lpszText := PAnsiChar(AboutText); lpszCaption := PAnsiChar(AboutCaption+Caption); lpszIcon := AboutIcon; dwStyle := MB_USERICON; end; MessageBoxIndirectA(MsgBoxParamsA); end; end; procedure TVSNotesMainForm.SplitterMove(Sender: TObject); begin Navigator.SetBounds(0, Splitter.Top, Splitter.Left, Splitter.Height); Editor.SetBounds(Splitter.Right, Splitter.Top, ClientWidth - Splitter.Right, Splitter.Height); end; procedure TVSNotesMainForm.WMCommand(var Msg: TWMCommand); begin if (Msg.Ctl = 0) and (Msg.NotifyCode in [0, 1]) then case Msg.ItemID of IDExit: Close; IDNew: NewClick(Self); IDOpen: OpenClick(Self); IDSave: SaveClick(Self, false); IDSaveAs: SaveClick(Self, true); IDImport: ImportClick(Self); IDPrint: ShowMessage('No printing supported'); IDOptions: ShowMessage('What? Options? Fuck that!'); IDUndo: Editor.DoEditAction(eaUndo); //TODO: Send dat to active control IDRedo: Editor.DoEditAction(eaRedo); IDCut: Editor.DoEditAction(eaCut); IDCopy: Editor.DoEditAction(eaCopy); IDPaste: Editor.DoEditAction(eaPaste); IDSelectAll: Editor.DoEditAction(eaSelectAll); IDAbout: ShowAbout; end; if Assigned(ToolBar) and (Msg.Ctl = ToolBar.Handle) then Perform(WM_COMMAND, TBMenuIDs[TTBButtons(Msg.ItemID)], 0); end; procedure TVSNotesMainForm.WMDropFiles(var Msg: TWMDropFiles); var FileName: array[0..MAX_PATH] of Char; i: Integer; begin //TODO: Import for i := 0 to DragQueryFile(Msg.Drop, $FFFFFFFF, nil, 0) - 1 do begin DragQueryFile(Msg.Drop, i, FileName, MAX_PATH + 1); if FileExists(string(FileName)) and IsVSNFile(string(FileName)) then begin if not RequestSave then Exit; OpenFile(string(FileName)); Break; end; end; DragFinish(Msg.Drop); end; procedure TVSNotesMainForm.FormResize(Sender: TObject); begin ToolBar.Perform(TB_AUTOSIZE, 0, 0); StatusBar.Perform(WM_SIZE, 0, 0); Splitter.Height := ClientHeight - ToolBar.Height - StatusBar.Height; if ClientWidth > 0 then Splitter.MaxPos := ClientWidth - Splitter.Width; Navigator.Height := Splitter.Height; Editor.SetSize(ClientWidth - Splitter.Right, Splitter.Height); //RepaintAll; end; procedure TVSNotesMainForm.WMSizing(var Msg: TWMMoving); begin with Msg do begin if DragRect.Right - DragRect.Left < FMinWidth then if (Edge = WMSZ_LEFT) or (Edge = WMSZ_TOPLEFT) or (Edge = WMSZ_BOTTOMLEFT) then DragRect.Left := DragRect.Right - FMinWidth else DragRect.Right := DragRect.Left + FMinWidth; if DragRect.Bottom - DragRect.Top < FMinHeight then if (Edge = WMSZ_TOP) or (Edge = WMSZ_TOPLEFT) or (Edge = WMSZ_TOPRIGHT) then DragRect.Top := DragRect.Bottom - FMinHeight else DragRect.Bottom := DragRect.Top + FMinHeight; end; end; procedure TVSNotesMainForm.RepaintAll; var Cur: TWinControl; begin Cur := NextControl; while Assigned(Cur) do begin Cur.Invalidate; UpdateWindow(Cur.Handle); Cur := Cur.NextControl; end; end; destructor TVSNotesMainForm.Destroy; begin DestroyAcceleratorTable(FAccelTable); FreeAndNil(FTBImages); inherited; end; procedure TVSNotesMainForm.FileModified(Sender: TObject); begin if Assigned(FFile) then FFile.Modify; UpdateCaptions; end; function TVSNotesMainForm.FormClose(Sender: TObject): Boolean; begin Result := RequestSave; end; function TVSNotesMainForm.FormProcessMsg(var Msg: TMsg): Boolean; begin Result := TranslateAccelerator(Handle, FAccelTable, Msg) <> 0; end; procedure TVSNotesMainForm.NavigatorNodeSelected(Sender: TObject); begin Editor.Save; Editor.Node := Navigator.SelNode; UpdateCaptions; end; procedure TVSNotesMainForm.NewClick(Sender: TObject); begin if not RequestSave then Exit; Navigator.Clear; Editor.Node := nil; FFile.Free; FFile := TNotesFile.Create; FFile.MakeBackup := true; //TODO: Fill metadata UpdateCaptions; Navigator.RootNode := FFile.RootNode; end; procedure TVSNotesMainForm.OpenClick(Sender: TObject); var FileName: string; begin if not RequestSave then Exit; if Assigned(FFile) then FileName := FFile.Name else FileName := ''; if not OpenSaveDialog(Handle, true, '', SDefExt, SVFNFilter, '', 0, OFN_FILEMUSTEXIST, FileName) then Exit; OpenFile(FileName); end; procedure TVSNotesMainForm.SaveClick(Sender: TObject; SaveAs: Boolean); var FileName: string; begin if not Assigned(FFile) then Exit; FileName := FFile.Name; if ((FFile.Name = '') or SaveAs) and not OpenSaveDialog(Handle, false, '', SDefExt, SVFNFilter, '', 0, OFN_OVERWRITEPROMPT, FileName) then Exit; SaveFile(FileName); end; procedure TVSNotesMainForm.ImportClick(Sender: TObject); var FileName, Key: string; i: Integer; DestNode, Data: TDataNode; begin FileName := ''; if not OpenSaveDialog(Handle, true, '', '', SImportFilter, '', 0, OFN_FILEMUSTEXIST, FileName) then Exit; Data := ImportFile(FileName); if not Assigned(Data) then Exit; if not Assigned(FFile) then NewClick(Self); DestNode := Navigator.SelNode; if not Assigned(DestNode) then DestNode := FFile.RootNode; for i := 0 to Data.RawMetadata.Count - 1 do begin Key := Copy(Data.RawMetadata[i], 1, FirstDelimiter('=', Data.RawMetadata[i]) - 1); if DestNode.RawMetadata.IndexOfName(Key) < 0 then DestNode.RawMetadata.Values[Key] := Data.RawMetadata.Values[Key]; end; while Data.Children.Count > 0 do DestNode.Children.Add(Data.Children[0]); FFile.Modify; UpdateCaptions; Navigator.UpdateTree; end; procedure TVSNotesMainForm.OpenFile(const FileName: string); begin if not Assigned(FFile) then FFile := TNotesFile.Create; FFile.MakeBackup := true; Navigator.Clear; Editor.Node := nil; FFile.Name := FileName; FFile.Load; UpdateCaptions; Navigator.RootNode := FFile.RootNode; end; function TVSNotesMainForm.RequestSave: Boolean; begin Editor.Save; Result := true; if not Assigned(FFile) or not FFile.Modified then Exit; case MessageBox(Handle, SSaveNow, AppCaption, MB_YESNOCANCEL or MB_ICONEXCLAMATION) of IDYES: SaveClick(Self, false); IDCANCEL: Result := false; end; end; procedure TVSNotesMainForm.SaveFile(const FileName: string); begin if not Assigned(FFile) then Exit; FFile.Name := FileName; Editor.Save; FFile.Save; UpdateCaptions; end; procedure TVSNotesMainForm.UpdateCaptions; const Modified: array[Boolean] of string = ('', '*'); begin Caption := AppCaption; if Assigned(FFile) then begin Caption := Caption + ':'; if FFile.RootNode.Metadata[SMKTitle, ''] <> '' then Caption := Caption + ' ' + FFile.RootNode.Metadata[SMKTitle, '']; if FFile.Name = '' then Caption := Caption + ' [unsaved]' else Caption := Caption + ' [' + ExtractFileName(FFile.Name) + ']'; Caption := Caption + Modified[FFile.Modified]; end; end; end.
unit uSphere; interface uses uVect, uRay, uColour, uSceneObject; type Sphere = class(SceneObject) private center: Vect; radius: Double; color: Colour; public constructor Create; overload; constructor Create(centerValue: Vect; radiusValue: Double; colorValue: Colour); overload; function getSphereCenter: Vect; function getSphereRadius: Double; function getColor: Colour; override; function getNormalAt(point: Vect): Vect; override; function findIntersection(r: Ray): Double; override; end; implementation { Sphere } constructor Sphere.Create; begin center := Vect.Create(0,0,0); radius := 1; color := Colour.Create(0.5, 0.5, 0.5, 0); end; constructor Sphere.Create(centerValue: Vect; radiusValue: Double; colorValue: Colour); begin center := centerValue; radius := radiusValue; color := colorValue; end; function Sphere.findIntersection(r: Ray): Double; var ray_origin, ray_direction, sphere_center: Vect; ray_origin_x, ray_origin_y, ray_origin_z, ray_direction_x, ray_direction_y, ray_direction_z, sphere_center_x, sphere_center_y, sphere_center_z, b, c, discriminant, root_1, root_2: Double; begin ray_origin := r.origin; ray_origin_x := ray_origin.x; ray_origin_y := ray_origin.y; ray_origin_z := ray_origin.z; ray_direction := r.direction; ray_direction_x := ray_direction.x; ray_direction_y := ray_direction.y; ray_direction_z := ray_direction.z; sphere_center := center; sphere_center_x := sphere_center.x; sphere_center_y := sphere_center.y; sphere_center_z := sphere_center.z; b := (2*(ray_origin_x - sphere_center_x)*ray_direction_x) + (2*(ray_origin_y - sphere_center_y)*ray_direction_y) + (2*(ray_origin_z - sphere_center_z)*ray_direction_z); c := (ray_origin_x - sphere_center_x)*(ray_origin_x - sphere_center_x) + (ray_origin_y - sphere_center_y)*(ray_origin_y - sphere_center_y) + (ray_origin_z - sphere_center_z)*(ray_origin_z - sphere_center_z) - (radius*radius); discriminant := b*b - 4*c; if discriminant > 0 then begin // the ray intersects the sphere // the first root root_1 := ((-1*b - sqrt(discriminant))/2) - 0.000001; if root_1 > 0 then // the first root is the smallest positive root Result := root_1 else begin // the second root is the smallest positive root root_2 := ((sqrt(discriminant) - b)/2) - 0.000001; Result := root_2; end; end else // the ray missed the sphere Result := -1; end; function Sphere.getColor: Colour; begin Result := color; end; function Sphere.getNormalAt(point: Vect): Vect; begin // normal always points away from the center of a sphere Result := point.vectAdd(center.negative()).normalize(); end; function Sphere.getSphereCenter: Vect; begin Result := center; end; function Sphere.getSphereRadius: Double; begin Result := radius; end; end.
unit ImageRender; interface {$MINENUMSIZE 4} uses Windows, Image; // 图像滤镜ID type IMAGE_FILTER_ID = ( IFI_NONE, IFI_ZOOM_BLUR, // Zoom模糊 nRadius - 模糊深度 IFI_GAUSS_BLUR, // 高斯模糊 nRadius - 模糊半径 IFI_SHADOW, // 添加阴影 nRadius - 不透明度 nParam1 - 阴影颜色(COLORREF) nParam2 - 平滑程度 nParam3 - X方向偏移 nParam4 - Y方向偏移 IFI_INVERT = 300, // 图像反色 IFI_GRAY_SCALE, // 灰度图像 IFI_THRESHOLD, // 阀值 nRadius (0 - 255) IFI_FLIP, // 垂直翻转 IFI_FLIP_HORZ, // 水平翻转 IFI_EMBOSS, // 浮雕 nRadius (0 - 100) IFI_SPLASH, // 斑点 nRadius (0 - 255) IFI_MOSAIC, // 马赛克 nRadius (0 - 255) IFI_OIL_PAINT, // 油画 nRadius (0 - 10) IFI_3DGRID, // 3D网格 nParam1 - 网格尺寸(1 - ) nParam2 - 网格深度(1 - ) IFI_WHIRL_PINCH, // 旋转挤压 nParam1 - 旋转(0 - 360) nParam2 - 挤压(0 - 100) IFI_GRADIENT_RADIAL, // 放射型渐变 暂不使用 IFI_GAMMA, // gamma调节 nRadius (0 - 255) IFI_ROTATE90, // 顺时针旋转90度/rotate 90' IFI_RIBBON, // 带形 nParam1 : 振幅[0..100],此值为一百分比 nParam2 : 频率>=0,每10为一个pi IFI_HALFTONE_M3, // 半影调 无参数 IFI_BRIGHTNESS, // 调节亮度 使用nParam1参数(0 - 200) IFI_CONTRAST, // 调节对比度 使用nParam1参数(0 - 200) IFI_COLORTONE, // 单色调 nParam1 - R分量 nParam2 - G分量 nParam3 - B分量 IFI_HUE_SATURATION, // 色调饱和度/hue saturation nParam1 - 色调(-180, 180) nParam2 - 饱和度(-100, 100) IFI_CREATEHALO, // 制作光晕 IFI_OLD_PHOTO, // 老照片 nRadius (0 - 10) 暂时未使用任何参数 IFI_STRETCH = 500, // nQuality 取值见IMAGE_INTERPOLATION定义 nParam1 - 缩放后图像的宽度 nParam2 - 缩放后图像的高度 IFI_ROTATE, // 旋转 nAngle - (0 - 360) IFI_COUNT ); // Image Filter Parameter structure type IMAGE_FILTER_PARAM = record uFilterID : IMAGE_FILTER_ID; // 滤镜ID nRadius : Integer; // 半径 nAngle : Integer; // 角度 nQuality : Integer; // 品质 nParam1 : Integer; nParam2 : Integer; nParam3 : Integer; nParam4 : Integer; end; type FILTERPARAM = record uFilterID : IMAGE_FILTER_ID; IDCaption : Array[0..63] of WideChar; //显示的标题 bRadius : BOOL; RadiusText: Array[0..31] of WideChar; RadiusMax, RadiusMin: integer; bAngle : BOOL; AngleText: Array[0..31] of WideChar; AngleMax, AngleMin: integer; bQuality: BOOL; QualityText: Array[0..31] of WideChar; QualityMax, QualityMin: integer; bParam1: BOOL; Param1Text: Array[0..31] of WideChar; Param1Max, Param1Min :integer; bParam2: BOOL; Param2Text: Array[0..31] of WideChar; Param2Max, Param2Min :integer; bParam3: BOOL; Param3Text: Array[0..31] of WideChar; Param3Max, Param3Min :integer; bParam4: BOOL; Param4Text: Array[0..31] of WideChar; Param4Max, Param4Min :integer; end; LPFILTERPARAM = ^FILTERPARAM; LPIMAGE_FILTER_PARAM = ^IMAGE_FILTER_PARAM; LPVOID = Pointer; // // 图像滤镜回掉函数定义 //typedef BOOL (__stdcall * IMAGE_FILTER_CALLBACK)(void* pUserObj, UINT uMesg, WPARAM wParam, LPARAM lParam); type IMAGE_FILTER_CALLBACK = function(pUserObj: Pointer; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): DWORD; stdcall; // 图像滤镜处理 暂不支持回掉 //BOOL __stdcall IRImageFitler(HDIBIMAGE hImageDst, HDIBIMAGE hImageSrc, LPIMAGE_FILTER_PARAM pParam, IMAGE_FILTER_CALLBACK fnCallback = 0, void* pUserObj = 0); function IRImageFitler(hImageDst : HDIBIMAGE; hImageSrc : HDIBIMAGE; pParam : LPIMAGE_FILTER_PARAM; fnCallback : IMAGE_FILTER_CALLBACK = nil; pUserObj : LPVOID = nil) : BOOL; stdcall; //BOOL __stdcall IRGetFilterParam(IMAGE_FILTER_ID uFilterID, LPFILTERPARAM pParam); // 取得Filter参数 function IRGetFilterParam(uFilterID : IMAGE_FILTER_ID; pParam : LPFILTERPARAM) : BOOL; stdcall; //int __stdcall IRGetFilterCount() //取得Filter的个数; function IRGetFilterCount(): integer; stdcall; //BOOL __stdcall IRGetFilterItem(int Index , LPFILTERPARAM pParam) //取得第 index项 function IRGetFilterItem(Index: integer; pParam: LPFILTERPARAM): BOOL; stdcall; implementation const DLLNAME = 'WS_ImageProc.dll'; function IRImageFitler ; external DLLNAME Name 'IRImageFitler'; function IRGetFilterParam ; external DLLNAME Name 'IRGetFilterParam'; function IRGetFilterCount ; external DLLNAME Name 'IRGetFilterCount'; function IRGetFilterItem ; external DLLNAME Name 'IRGetFilterItem'; end.
program operations; begin { math operators } writeln('Math works as exptected.'); writeln(' 1 + 1 = ', 1 + 1 ); writeln(' 5 - 1 = ', 5 - 1 ); writeln(' 3 * 3 = ', 3 * 3 ); writeln(' 6 / 3 = ', (6 / 3):2:2 ); writeln(' 7 mod 3 = ', 7 mod 3, ' (i can haz module/resto operator too)'); writeln; { comparison operators } writeln('Comparison operators too.'); writeln; writeln('equal operator: '); writeln('1 = 1 : ', 1 = 1 ); writeln('1 = 2 : ', 1 = 2 ); writeln('1 = 3 : ', 1 = 3 ); writeln; writeln('not-equal operator: '); writeln('1 <> 1 : ', 1 <> 1 ); writeln('1 <> 2 : ', 1 <> 2 ); writeln('1 <> 3 : ', 1 <> 3 ); writeln; writeln('greater-than operator: '); writeln('1 > 1 : ', 1 > 1 ); writeln('1 > 2 : ', 1 > 2 ); writeln('1 > 3 : ', 1 > 3 ); writeln; writeln('less-than operator: '); writeln('1 < 1 : ', 1 < 1 ); writeln('1 < 2 : ', 1 < 2 ); writeln('1 < 3 : ', 1 < 3 ); writeln; writeln('greater-or-equal operator: '); writeln('1 >= 1 : ', 1 >= 1 ); writeln('1 >= 2 : ', 1 >= 2 ); writeln('1 >= 3 : ', 1 >= 3 ); writeln; writeln('less-or-equal operator: '); writeln('1 <= 1 : ', 1 <= 1 ); writeln('1 <= 2 : ', 1 <= 2 ); writeln('1 <= 3 : ', 1 <= 3 ); writeln; { boolean operators } writeln('boolean operators too, but there are some surprises'); writeln('true and true : ', true and true ); writeln('true and false : ', true and false ); writeln('false and false : ', false and false ); writeln; writeln('true or true : ', true or true ); writeln('true of false : ', true or false ); writeln('false or false : ', false or false ); writeln; writeln('not true : ', not true ); writeln('not false : ', not false ); writeln; { bitwise operators } writeln('And we have bitwise operators (half of programmers do not know those)'); writeln('64 and 2 : ', 64 and 2); writeln('64 or 2 : ', 64 or 2); writeln(' not 64 : ', not 64); writeln('64 << 3 : ', 64<<3); writeln('64 >> 3 : ', 64>>3); writeln('64 shl 3 : ', 64 shl 3); writeln('64 shr 3 : ', 64 shr 3); end.
unit InfraPresenter; interface uses InfraCommon, InfraValueTypeIntf, InfraCommonIntf, InfraMVPIntf; type TPresenter = class(TElement, IPresenter) private FModel: IModel; FView: IView; FName: string; // *** FCommandSet: IInfraFeatureList; FParentPresenter: IPresenter; FSubPresenters: IPresenterList; procedure ModelValueChanged(const Event: IInfraEvent); procedure ModelValueExchanged(const Event: IInfraEvent); protected // *** function GetCommandSet: IInfraFeatureList; function GetName: string; function HasSubPresenters: boolean; function GetSubPresenters: IPresenterList; procedure BindCommands; virtual; procedure SetName(const Value: string); procedure SetupSubPresenters; virtual; procedure UpdatePresenter; virtual; public function GetModel: IModel; function GetParentPresenter: IPresenter; function GetView: IView; procedure SetModel(const Value: IModel); procedure SetParentPresenter(const Value: IPresenter); procedure SetView(const Value: IView); // *** property CommandSet: IInfraFeatureList read GetCommandSet; property Model: IModel read GetModel write SetModel; property Name: string read GetName write SetName; property ParentPresenter: IPresenter read GetParentPresenter; property SubPresenters: IPresenterList read GetSubPresenters; property View: IView read GetView write SetView; procedure InfraInitInstance; override; end; TValuePresenter = class(TPresenter, IValuePresenter); TTextPresenter = class(TValuePresenter, ITextPresenter); TNumberPresenter = class(TValuePresenter, INumberPresenter); TIntegerPresenter = class(TNumberPresenter, IIntegerPresenter); TDateTimePresenter = class(TValuePresenter, IDateTimePresenter); TBooleanPresenter = class(TValuePresenter, IBooleanPresenter); TListPresenter = class(TPresenter, IListPresenter) protected function GetListItem: IListItemPresenter; public property ListItem: IListItemPresenter read GetListItem; end; TListItemPresenter = class(TPresenter, IListItemPresenter); implementation uses List_Presenter; { TPresenter } procedure TPresenter.InfraInitInstance; begin inherited; EventService.Subscribe(IModelValueChanged, Self as ISubscriber, ModelValueChanged, 'Model'); EventService.Subscribe(IModelValueExchanged, Self as ISubscriber, ModelValueExchanged, 'Model'); BindCommands; end; procedure TPresenter.ModelValueChanged(const Event: IInfraEvent); begin UpdatePresenter end; procedure TPresenter.ModelValueExchanged(const Event: IInfraEvent); begin SetupSubPresenters; end; procedure TPresenter.BindCommands; begin // inherited in descendents end; function TPresenter.HasSubPresenters: boolean; begin Result := Assigned(FSubPresenters) and (FSubPresenters.Count <> 0); end; function TPresenter.GetModel: IModel; begin Result := FModel; end; function TPresenter.GetName: string; begin Result := FName; end; function TPresenter.GetParentPresenter: IPresenter; begin Result := FParentPresenter; end; function TPresenter.GetSubPresenters: IPresenterList; begin if not Assigned(FSubPresenters) then begin FSubPresenters := TPresenterList.Create; FSubPresenters.Owner := Self as IPresenter; end; Result := FSubPresenters; end; function TPresenter.GetView: IView; begin Result := FView; end; procedure TPresenter.SetModel(const Value: IModel); begin if Value <> FModel then FModel := Value; end; procedure TPresenter.SetName(const Value: string); begin FName := Value; end; procedure TPresenter.SetParentPresenter(const Value: IPresenter); begin SetReference(IInterface(FParentPresenter), Value); end; procedure TPresenter.SetView(const Value: IView); begin if Value <> FView then begin FView := Value; FView.Presenter := Self as IPresenter; end; end; procedure TPresenter.UpdatePresenter; var Iterator: IInfraIterator; begin If Assigned(View) then View.Update; if HasSubPresenters then begin Iterator := SubPresenters.NewIterator; while not Iterator.IsDone do begin (Iterator.CurrentItem as IPresenter).UpdatePresenter; Iterator.Next; end; end; end; procedure TPresenter.SetupSubPresenters; begin // inherited in descendents end; (* *** function TPresenter.GetCommandSet: IInfraFeatureList; begin if not Assigned(FCommandSet) then FCommandSet := TInfraFeatureList.Create(Self as IElement); Result := FCommandSet; end; *) { TListPresenter } function TListPresenter.GetListItem: IListItemPresenter; begin Result := SubPresenters.Items[0] as IListItemPresenter; end; end.
unit Model.RHOperacionalAusencias; interface type TRHOperacionalAusencias = class private var FID: Integer; FCadastro: Integer; FData: System.TDate; FStatusOperacao: String; FObs: String; FIDReferencia: Integer; FLog: String; public property ID: Integer read FID write FID; property Data: System.TDate read FData write FData; property Cadastro: Integer read FCadastro write FCadastro; property StatusOperacao: String read FStatusOperacao write FStatusOperacao; property Obs: String read FObs write FObs; property IDReferencia: Integer read FIDReferencia write FIDReferencia; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFID: Integer; pFData: System.TDate; pFCadastro: Integer; pFStatusOperacao: String; pFObs: String; pFIDReferencia: Integer; pFLog: String); overload; end; implementation constructor TRHOperacionalAusencias.Create; begin inherited Create; end; constructor TRHOperacionalAusencias.Create(pFID: Integer; pFData: System.TDate; pFCadastro: Integer; pFStatusOperacao: String; pFObs: String; pFIDReferencia: Integer; pFLog: String); begin FID := pFID; FData := pFData; FCadastro := pFCadastro; FStatusOperacao := pFStatusOperacao; FObs := pFObs; FIDReferencia := pFIDReferencia; FLog := pFLog; end; end.
unit ValEdit; { ---------------------------------------------------------- Validated Edit box component (c) J. Dempster 1999 ---------------------------------------------------------- Numeric parameter edit box which ensures user-entered numbers are kept within specified limits 28/10/99 ... Now handles both comma and period as decimal separator 13/2/02 .... Invalid floating point values now trapped by LimitTo method } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, strutils ; type TValidatedEdit = class(TCustomEdit) private { Private declarations } FValue : single ; FLoLimit : single ; FHiLimit : single ; FUnits : string ; FFormatString : string ; FScale : single ; procedure UpdateEditBox ; procedure SetValue( Value : single ) ; function GetValue : single ; procedure SetScale( Value : single ) ; procedure SetUnits( Value : string ) ; procedure SetFormatString( Value : string ) ; procedure ReadEditBox ; function LimitTo( Value : single ; { Value to be checked } Lo : single ; { Lower limit } Hi : single { Upper limit } ) : single ; procedure ExtractFloat ( CBuf : string ; var Value : Single ) ; protected { Protected declarations } procedure KeyPress( var Key : Char ) ; override ; public { Public declarations } Constructor Create(AOwner : TComponent) ; override ; published { Published declarations } property OnKeyPress ; property AutoSelect ; property AutoSize ; property BorderStyle ; property Color ; property Font ; property Height ; property HelpContext ; property HideSelection ; property Hint ; property Left ; property Name ; property ShowHint ; property Top ; property Text ; property Visible ; property Width ; property Value : single read GetValue write SetValue ; property LoLimit : single read FLoLimit write FLoLimit ; property HiLimit : single read FHiLimit write FHiLimit ; property Scale : single read FScale write SetScale ; property Units : string read FUnits write SetUnits ; property NumberFormat : string read FFormatString write SetFormatString ; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TValidatedEdit]); end; constructor TValidatedEdit.Create(AOwner : TComponent) ; { -------------------------------------------------- Initialise component's internal objects and fields -------------------------------------------------- } begin inherited Create(AOwner) ; FScale := 1.0 ; FUnits := '' ; FLoLimit := -1E29 ; FHiLimit := 1E29 ; FFormatString := '%g' ; FValue := 0.0 ; end ; procedure TValidatedEdit.SetValue( Value : single ) ; { ----------------------------------------------- Set the current numerical value in the edit box -----------------------------------------------} begin FValue := LimitTo( Value, FLoLimit, FHiLimit ) ; UpdateEditBox ; Invalidate ; end ; function TValidatedEdit.GetValue : single ; { ----------------------------------------------- Get the current numerical value in the edit box -----------------------------------------------} begin ReadEditBox ; Result := FValue ; end ; procedure TValidatedEdit.SetScale( Value : single ) ; { -------------------------------------------- Set the interval -> edit box scaling factor --------------------------------------------} begin FScale := Value ; UpdateEditBox ; Invalidate ; end ; procedure TValidatedEdit.SetUnits( Value : string ) ; { ------------------------------------------------- Set the units of the value stored in the edit box -------------------------------------------------} begin FUnits := Value ; UpdateEditBox ; Invalidate ; end ; procedure TValidatedEdit.SetFormatString( Value : string ) ; { ------------------------------------------------- Set the units of the value stored in the edit box -------------------------------------------------} begin FFormatString := Value ; UpdateEditBox ; Invalidate ; end ; procedure TValidatedEdit.UpdateEditBox ; { ------------------------------------ Update the edit box with a new value -----------------------------------} begin text := ' ' + format( FFormatString, [FValue*FScale] ) + ' ' + FUnits ; end ; procedure TValidatedEdit.KeyPress( var Key : Char ) ; begin inherited KeyPress( Key ) ; if Key = chr(13) then begin ReadEditBox ; UpdateEditBox ; Invalidate ; end ; end ; procedure TValidatedEdit.ReadEditBox ; { ----------------------------------------------- Read the edit box and convert to floating point -----------------------------------------------} begin ExtractFloat( text, FValue ) ; FValue := FValue / FScale ; // if (FValue < LoLimit) or (FValue > HiLimit) then Beep ; FValue := LimitTo( FValue, LoLimit, HiLimit ) ; end ; function TValidatedEdit.LimitTo( Value : single ; { Value to be checked } Lo : single ; { Lower limit } Hi : single { Upper limit } ) : single ; { Return limited value } { -------------------------------- Limit Value to the range Lo - Hi --------------------------------} begin //outputdebugString(PChar(format('%.4g ',[Value]))) ; try if Value < Lo then Value := Lo ; Except On EInvalidOp do Value := Lo ; end ; try if Value > Hi then Value := Hi ; Except On EInvalidOp do Value := Hi ; end ; Result := Value ; end ; procedure TValidatedEdit.ExtractFloat ( CBuf : string ; { ASCII text to be processed } var Value : Single { Default value if text is not valid } ) ; { ------------------------------------------------------------------- Extract a floating point number from a string which may contain additional non-numeric text 28/10/99 ... Now handles both comma and period as decimal separator -------------------------------------------------------------------} var CNum,dsep : string ; i : integer ; Done,NumberFound : Boolean ; begin { Extract number from other text which may be around it } CNum := '' ; Done := False ; NumberFound := False ; i := 1 ; repeat if CBuf[i] in ['0'..'9', 'E', 'e', '+', '-', '.', ',' ] then begin CNum := CNum + CBuf[i] ; NumberFound := True ; end else if NumberFound then Done := True ; Inc(i) ; if i > Length(CBuf) then Done := True ; until Done ; { Correct for use of comma/period as decimal separator } {$IF CompilerVersion > 7.0} dsep := formatsettings.DECIMALSEPARATOR ; {$ELSE} dsep := DECIMALSEPARATOR ; {$IFEND} if dsep = '.' then CNum := ANSIReplaceText(CNum ,',',dsep); if dsep = ',' then CNum := ANSIReplaceText(CNum, '.',dsep); { Convert number from ASCII to real } try if Length(CNum)>0 then Value := StrToFloat( CNum ) ; except on E : EConvertError do ; end ; end ; end.
unit UFerramentas; interface uses Forms, SysUtils, Classes, StdCtrls, Dialogs, Windows, Registry, FileCtrl, Math, ShellApi; procedure CriaScrollBar(vptForm: TForm); procedure ValidaCGC(vpsCgc: String); procedure ValidaCPF(vpsCpf: String); function RedimencionaCampo(vptCampo: TComponent; vpsConteudo: String): Integer; function DelChar(vpsPalavra: String; vpsDelChar: String): String; function DoubleExtenso(Numero: Double; Moeda: String): String; function RealStr(Numero: Double; Decimais: Byte): String; function IfThen(AValue: Boolean; const ATrue: String; AFalse: String = ''): String; overload; function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = 0): Integer; overload; function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64 = 0): Int64; overload; function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double = 0.0): Double; overload; function StrToValor(vpsValor: String): Extended; function RoundFloat(vpeVlr: Extended; vpiPrecision: Integer = 2): Extended; function TruncFloat(vpeVlr: Extended; vpiPrecision: Integer = 2): Extended; function RoundUpFloat(vpeVlr: Extended; vpiPrecision: Integer = 2): Extended; function DataIni(vptDataIni: TDateTime): TDateTime; function DataFin(vptDataFin: TDateTime): TDateTime; function LogTxt(vpsTexto: String; vpsNomeArq: String = 'LogTxt'): String; procedure AbreArqTxt(vpsNomeArq: String); procedure ExecAppWin(vpsNomeProg: String; vpsParametro: String = ''); function Criptografa(const vpsPalavra: String): String; function Descriptografa(const vpsPalavra: String): String; function VersaoExe(vpsArqExe: String): String; function VersaoDoWindows: Integer; function EhWindows64: Boolean; function Barra(vpsPasta: String; vpbInclui: Boolean = True): String; procedure GeraArqTxt(vpsDirArq, vpsNomArq, vpsExtArq, vpsConteudo: String); function ExecutaProgramaEEspera(vpsPrograma: String): Boolean; procedure ExecutaPrograma(vpsPrograma: String); procedure DeletaPrograma(vpsPrograma: String); procedure CriaCompatibilidadeWin64NoWin32(vpsPrograma: String); procedure CriaODBCFireBird(vpsAliasDB, vpsPastaDB, vpsNomeDB: String); function NomeProgramaSemExt(vpsPrograma: String): String; function SistemaAAADriveCorrente: String; function DeletaCharAlfanumerico(vpsTexto: String; vpsExcecao: String = ''): String; function ContemNumeros(vpsTexto: String): Boolean; implementation procedure CriaScrollBar(vptForm: TForm); begin vptForm.HorzScrollBar.Visible := True; vptForm.VertScrollBar.Visible := True; vptForm.HorzScrollBar.Tracking := True; vptForm.VertScrollBar.Tracking := True; vptForm.HorzScrollBar.Range := vptForm.ClientWidth; vptForm.VertScrollBar.Range := vptForm.ClientHeight; end; procedure ValidaCGC(vpsCgc: String); var i, Digito1, Digito2, Operador1, Operador2: Byte; Acumulado: Integer; const Multiplicador: Array[1..13] of byte = (6,5,4,3,2,9,8,7,6,5,4,3,2); begin if Length(vpsCgc) <> 14 then begin if Length(vpsCgc) < 14 then raise Exception.Create( 'C.G.C. está incompleto') else raise Exception.Create( 'Numero do C.G.C. muito grande'); end else begin // calcula o primeiro digito Acumulado := 0; for i := 2 to 13 do Acumulado := Acumulado + (Multiplicador[i] * StrToInt(vpsCgc[i-1])); Operador1 := Acumulado mod 11; if (Operador1 = 0) or (Operador1 = 1) then Digito1 := 0 else Digito1 := 11-Operador1; // calcula o segundo digito Acumulado := 0; for i := 1 to 12 do Acumulado := Acumulado+(Multiplicador[i] * StrToInt(vpsCgc[i])); Acumulado := Acumulado + (Multiplicador[13] * Digito1); Operador2 := Acumulado mod 11; if (Operador2 = 0) or (Operador2 = 1) then Digito2 := 0 else Digito2 := 11-Operador2; if (Digito1 = StrToInt(vpsCgc[13])) and (Digito2 = StrToInt(vpsCgc[14])) then begin end else begin raise Exception.Create( 'Número do C.G.C. está incorreto'); end; end; end; procedure ValidaCPF(vpsCpf: String); var acum, i, dig1, dig2: Integer; begin if Length(vpsCpf) <> 11 then begin if Length(vpsCpf) < 11 then raise Exception.Create( 'C.P.F. está incompleto') else raise Exception.Create( 'Numero do C.P.F. muito grande'); end else begin acum := 0; // Calcula o primeiro digito for i := 10 downto 2 do acum := acum + StrToInt(vpsCpf[11-i]) * i; dig1 := 11-(acum mod 11); if dig1 > 9 then dig1 := 0; if dig1 <> StrToInt(vpsCpf[10]) then begin raise Exception.Create( 'Número do C.P.F. está incorreto'); end else // Calcula o segundo digito begin acum := 0; for i := 9 downto 2 do acum := acum + StrToInt(vpsCpf[11-i]) * (i+1); acum := acum + dig1 * 2; dig2 := 11-(acum mod 11); if dig2 > 9 then dig2 := 0; if dig2 <> StrToInt(vpsCpf[11]) then begin raise Exception.Create( 'Número do C.P.F. está incorreto'); end; end; end; end; function RedimencionaCampo( vptCampo: TComponent; vpsConteudo: String): Integer; var vltCampoRedimencionado: TLabel; begin vltCampoRedimencionado := TLabel.Create(nil); vltCampoRedimencionado.AutoSize := True; vltCampoRedimencionado.Font.Size := TLabel(vptCampo).Font.Size; vltCampoRedimencionado.Font.Style := TLabel(vptCampo).Font.Style; vltCampoRedimencionado.Font.Color := TLabel(vptCampo).Font.Color; vltCampoRedimencionado.Font.Pitch := TLabel(vptCampo).Font.Pitch; vltCampoRedimencionado.Font.PixelsPerInch := TLabel(vptCampo).Font.PixelsPerInch; vltCampoRedimencionado.Caption := vpsConteudo; Result := vltCampoRedimencionado.Width + 20; vltCampoRedimencionado.Free; end; function DelChar(vpsPalavra: String; vpsDelChar: String): String; var vli1: byte; begin Result := ''; for vli1 := 1 to Length(vpsPalavra) do if vpsPalavra[vli1] <> vpsDelChar then Result := Result + vpsPalavra[vli1]; end; function DoubleExtenso(Numero: Double; Moeda: String): String; const UNIDADE: array['0'..'9'] of String[10] = ('', ' HUM', ' DOIS', ' TREIS', ' QUATRO', ' CINCO', ' SEIS', ' SETE', ' OITO', ' NOVE'); DEZENA: array['0'..'9'] of String[10] = ('', ' DEZ', ' VINTE', ' TRINTA', ' QUARENTA', ' CINQUENTA', ' SESSENTA', ' SETENTA', ' OITENTA', ' NOVENTA'); DEZ_A_VINTE: array['0'..'9'] of String[10]= (' DEZ', ' ONZE', ' DOZE', ' TREZE', ' QUATORZE', ' QUINZE', ' DEZESSEIS', ' DEZESSETE', ' DEZOITO', ' DEZENOVE'); CENTENA: array['0'..'9'] of string[13] = ('',' CENTO', ' DUZENTOS', ' TREZENTOS', ' QUATROCENTOS', ' QUINHENTOS', ' SEISCENTOS', ' SETECENTOS', ' OITOCENTOS', ' NOVECENTOS'); CEM: array[0..3] of String = ('',' CEM',' CENTO',' CENTO'); MIL: array[0..1] of String = ('',' MIL'); MILHAO: array[0..2] of String = ('', ' MILHAO', ' MILHOES'); BILHAO: array[0..2] of String = ('', ' BILHAO', ' BILHOES'); TRILHAO: array[0..2] of String = ('', ' TRiLHAO', ' TRILHOES'); LIGACAO: array[0..2] of String = ('', ' E',' DE'); CENTAVO: array[0..1] of String = ('', ' CENTAVOS'); WNumeroExtenso: String = ''; var Centavos, S: String; C: integer; begin DoubleExtenso := ''; if Numero = 0 then Exit; S := RealStr(Numero, 2); C := Pos('.', S); Centavos := Copy(S, C + 1, 2); while Length(Centavos) < 2 do Centavos := Centavos + '0'; Delete(S, c, 3); while length(S) < 13 do S := '0' + S; WNumeroExtenso := Unidade[S[1]]; WNumeroExtenso := WNumeroExtenso + Trilhao[ord(S[1] = '1') + 2 * ord(S[1] > '1')] + Ligacao[Ord(S[2] <> '0')]; if S[2] + S[3] + S[4] = '100' then WNumeroExtenso := WNumeroExtenso + ' CEM' else WNumeroExtenso := WNumeroExtenso + Centena[S[2]]; WNumeroExtenso := WNumeroExtenso + Ligacao[Ord(S[3] <> '0')]; if S[3] = '1' then WNumeroExtenso := WNumeroExtenso + DEZ_A_VINTE[S[4]] else begin WNumeroExtenso := WNumeroExtenso + Dezena[S[3]] + Ligacao[Ord(S[4] <> '0')] + Unidade[S[4]]; end; WNumeroExtenso := WNumeroExtenso + Bilhao[Ord(S[2] + S[3] + S[4] = '001') + 2 * Ord(S[2] + S[3] + S[4] > '001')] + Ligacao[Ord(S[5] <> '0')]; if S[5] + S[6] + S[7] = '100' then WNumeroExtenso := WNumeroExtenso + ' CEM' else WNumeroExtenso := WNumeroExtenso + Centena[S[5]]; WNumeroExtenso := WNumeroExtenso + Ligacao[Ord(S[6] <> '0')]; if S[6] = '1' then WNumeroExtenso := WNumeroExtenso + DEZ_A_VINTE[S[7]] else begin WNumeroExtenso := WNumeroExtenso + Dezena[S[6]] + Ligacao[Ord(S[7] <> '0')] + Unidade[S[7]]; end; WNumeroExtenso := WNumeroExtenso + Milhao[Ord(S[5] + S[6] + S[7] = '001') + 2 * Ord(S[5] + S[6] + S[7] > '001')] + Ligacao[Ord(S[8] <> '0')]; if S[8] + S[9] + S[10] = '100' then WNumeroExtenso := WNumeroExtenso + ' CEM' else WNumeroExtenso := WNumeroExtenso + Centena[S[8]]; WNumeroExtenso := WNumeroExtenso + Ligacao[Ord(S[9] <> '0')]; if S[9] = '1' then WNumeroExtenso := WNumeroExtenso + DEZ_A_VINTE[S[10]] else begin WNumeroExtenso := WNumeroExtenso + Dezena[S[9]] + Ligacao[Ord(S[10] <> '0')] + Unidade[S[10]]; end; WNumeroExtenso := WNumeroExtenso + Mil[Ord(S[8] + S[9] + S[10] > '000')]+ Ligacao[Ord(S[11] <> '0')]; if S[11] + S[12] + S[13] = '100' then WNumeroExtenso := WNumeroExtenso + ' CEM' else WNumeroExtenso := WNumeroExtenso + Centena[S[11]]; WNumeroExtenso := WNumeroExtenso + Ligacao[Ord(S[12] <> '0')]; if S[12] = '1' then WNumeroExtenso := WNumeroExtenso + DEZ_A_VINTE[S[13]] else begin WNumeroExtenso := WNumeroExtenso + Dezena[S[12]] + Ligacao[Ord(S[13] <> '0')] + Unidade[S[13]]; end; WNumeroExtenso := WNumeroExtenso + Ligacao[ 2 * Ord(Copy(S, 8, 6) = '000000')] + ' ' + Moeda + Ligacao[ord(Centavos[1] <> '0')]; if Centavos[1] = '1' then WNumeroExtenso := WNumeroExtenso + DEZ_A_VINTE[Centavos[2]] + ' CENTAVOS' else WNumeroExtenso := WNumeroExtenso + Dezena[Centavos[1]] + Ligacao[Ord(Centavos[2] <> '0')] + Unidade[Centavos[2]] + Centavo[Ord(Centavos[1] + Centavos[2] <> '00')]; if WNumeroExtenso[2] = 'E' then Delete(WNumeroExtenso, 1, 3); if Numero < 1 then Delete(WNumeroExtenso, 1, Pos(' E ',WNumeroExtenso) + 2); DoubleExtenso := WNumeroExtenso; end; function RealStr(Numero: Double; Decimais: Byte): String; var S: String; begin Str(Numero: 40: Decimais, S); RealStr := Trim(S); end; function IfThen(AValue: Boolean; const ATrue: String; AFalse: String = ''): String; begin if AValue then Result := ATrue else Result := AFalse; end; function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer): Integer; begin if AValue then Result := ATrue else Result := AFalse; end; function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64): Int64; begin if AValue then Result := ATrue else Result := AFalse; end; function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double): Double; begin if AValue then Result := ATrue else Result := AFalse; end; function StrToValor(vpsValor: String): Extended; var vli1: Integer; vlsValor, vlsResult: String; begin vlsValor := Trim(vpsValor); if vlsValor = '' then begin Result := 0.0; Exit; end; vlsResult := ''; for vli1 := 1 to Length(vlsValor) do if ((Copy(vlsValor, vli1, 1) >= '0') and (Copy(vlsValor, vli1, 1) <= '9')) or (Copy(vlsValor, vli1, 1) = ',') then vlsResult := vlsResult + Copy(vlsValor, vli1, 1); Result := StrToFloat(vlsResult); end; function RoundFloat(vpeVlr: Extended; vpiPrecision: Integer = 2): Extended; var vliInteiro: Int64; vleDecimal, vleExp: Extended; begin try vliInteiro := Trunc(vpeVlr); vleDecimal := vpeVlr - vliInteiro; vleExp := Power(10, vpiPrecision); Result := Round(vleDecimal * vleExp) / vleExp; Result := vliInteiro + Result; except on E: Exception do raise Exception.Create('Resultado [' + E.message + '] muito grande!!!'); end; end; function TruncFloat(vpeVlr: Extended; vpiPrecision: Integer = 2): Extended; var vlsPrecisao: String; vli1, vliPrecisao, vliInteiro: Integer; vle1, vleResult: Extended; begin vlsPrecisao := '1'; for vli1 := 1 to vpiPrecision do vlsPrecisao := vlsPrecisao + '0'; vliPrecisao := StrToInt(vlsPrecisao); vle1 := vpeVlr * vliPrecisao; vliInteiro := Trunc(vle1); vleResult := vliInteiro / vliPrecisao; Result := vleResult; end; function RoundUpFloat(vpeVlr: Extended; vpiPrecision: Integer = 2): Extended; var vliInteiro: Int64; vleDecimal, vleExp: Extended; begin try vliInteiro := Trunc(vpeVlr); vleDecimal := vpeVlr - vliInteiro; vleExp := Power(10, vpiPrecision); Result := (Trunc((vleDecimal * vleExp)) + 1) / vleExp; Result := vliInteiro + Result; except on E:Exception do begin raise Exception.Create('Resultado [' + E.message + '] muito grande!!!'); end; end; end; function DataIni(vptDataIni: TDateTime): TDateTime; begin Result := StrToDateTime(FormatDateTime('dd/mm/yyyy', vptDataIni) + ' 00:00:00.0000'); end; function DataFin(vptDataFin: TDateTime): TDateTime; begin Result := StrToDateTime(FormatDateTime('dd/mm/yyyy', vptDataFin) + ' 23:59:59.9999'); end; function LogTxt(vpsTexto: String; vpsNomeArq: String = 'LogTxt'): String; var vltLista: TStringList; vlsNomeArq: String; vliSeq: Integer; //------------------------------------------------------------------------------ procedure MontaNomeArq; var vlsNomeExe: String; begin vlsNomeExe := NomeProgramaSemExt(Application.ExeName); vlsNomeArq := ExtractFilePath(Application.ExeName) + vlsNomeExe + '_' + vpsNomeArq + '_' + FormatDateTime('yyyymmdd"_"hhmmss"_"zzz', Now) + '(' + FormatFloat('000', vliSeq) + ').txt' end; //------------------------------------------------------------------------------ //function LogTxt(vpsTexto: String; vpsNomeArq: String = 'LogTxt'): String; //------------------------------------------------------------------------------ begin vltLista := TStringList.Create; vltLista.Add(vpsTexto); vliSeq := 0; repeat Inc(vliSeq); MontaNomeArq; until not FileExists(vlsNomeArq); vltLista.SaveToFile(vlsNomeArq); vltLista.Free; Result := vlsNomeArq; end; procedure AbreArqTxt(vpsNomeArq: String); begin ExecAppWin('\NotePad.exe', vpsNomeArq); end; procedure ExecAppWin(vpsNomeProg: String; vpsParametro: String = ''); var vltReg: TRegistry; vlsPastaPadraoWindows, vlsPrograma: String; vltLista: TStringList; vli1: Integer; begin vlsPrograma := ''; vlsPastaPadraoWindows := SistemaAAADriveCorrente + '\windows' + vpsNomeProg; if FileExists(vlsPastaPadraoWindows) then vlsPrograma := vlsPastaPadraoWindows; if not (Trim(vlsPrograma) > '') then begin vlsPastaPadraoWindows := SistemaAAADriveCorrente + 'windows\system32' + vpsNomeProg; if FileExists(vlsPastaPadraoWindows) then vlsPrograma := vlsPastaPadraoWindows; end; if not (Trim(vlsPrograma) > '') then begin vlsPastaPadraoWindows := SistemaAAADriveCorrente + 'windows\SysWOW64' + vpsNomeProg; if FileExists(vlsPastaPadraoWindows) then vlsPrograma := vlsPastaPadraoWindows; end; if not (Trim(vlsPrograma) > '') then begin vltReg := TRegistry.Create; vltLista := TStringList.Create; try vltReg.RootKey := HKEY_CURRENT_USER; vltReg.OpenKey('\Software\Microsoft\Windows\ShellNoRoam\MUICache', True); vltReg.GetValueNames(vltLista); for vli1 := 0 to vltLista.Count - 1 do if (Pos(UpperCase(vpsNomeProg), UpperCase(vltLista.Strings[vli1])) > 0) and (Copy(UpperCase(vltLista.Strings[vli1]), 1, 3) = Barra(SistemaAAADriveCorrente)) then begin vlsPrograma := vltLista.Strings[vli1]; Break; end; vltReg.CloseKey; finally vltReg.Free; vltLista.Free; end; end; if not FileExists(vlsPrograma) then begin MessageDlg( 'Aplicativo [' + vlsPrograma + '] Inexistente!', mtWarning, [mbOk], 0); Exit; end; if Trim(vpsParametro) > '' then vlsPrograma := vlsPrograma + ' ' + vpsParametro; WinExec(PChar(vlsPrograma), SW_Normal); end; function Criptografa(const vpsPalavra: String): String; var vli1, Letra, vliTamanho, vliPosicao: Integer; vlsSubPalavra: String; begin Result := ''; vliTamanho := Length(vpsPalavra); if vliTamanho > 14 then begin vlsSubPalavra := ''; for vliPosicao := 1 to vliTamanho do begin vlsSubPalavra := vlsSubPalavra + vpsPalavra[vliPosicao]; if Length(vlsSubPalavra) = 14 then begin Result := Result + Criptografa(vlsSubPalavra); vlsSubPalavra := ''; end; end; if Length(vlsSubPalavra) > 0 then begin Result := Result + Criptografa(vlsSubPalavra); end; end else begin for vliPosicao := 1 to vliTamanho do begin Letra := ord(vpsPalavra[vliPosicao]); vli1 := Letra - 33 + SQR(vliPosicao); if (vli1 > 224) then vli1 := vli1 - 224; vli1 := vli1 + 33; Result := Result + CHR(vli1); end; end; end; function Descriptografa(const vpsPalavra: String): String; var vli1, vliLetra, vliTamanho, vliPosicao: Integer; vlsSubPalavra: String; begin Result := ''; vliTamanho := Length(vpsPalavra); if vliTamanho > 14 then begin vlsSubPalavra := ''; for vliPosicao := 1 to vliTamanho do begin vlsSubPalavra := vlsSubPalavra + vpsPalavra[vliPosicao]; if Length(vlsSubPalavra) = 14 then begin Result := Result + Descriptografa(vlsSubPalavra); vlsSubPalavra := ''; end; end; if Length(vlsSubPalavra) > 0 then begin Result := Result + Descriptografa(vlsSubPalavra); end; end else begin for vliPosicao := 1 to vliTamanho do begin vli1 := ord(vpsPalavra[vliPosicao]); vliLetra := vli1 - 33 - SQR(vliPosicao); if (vliLetra < 0) then vliLetra := 224 + vliLetra; vliLetra := vliLetra + 33; Result := Result + CHR(vliLetra); end; end; end; function VersaoExe(vpsArqExe: String): String; var // seta ponteiros e buffers utilizados para recolher a versão da package vldWnd, vldVerInfoSize, vldVerValueSize: DWORD; vlpVerInfo: Pointer; vlpVerValue: PVSFixedFileInfo; vlsVersao: String; begin vlsVersao := '0.0.0.0'; vldVerInfoSize := GetFileVersionInfoSize(PChar(vpsArqExe), vldWnd); if vldVerInfoSize <> 0 then begin // recolhe valor do ponteiro GetMem(vlpVerInfo, vldVerInfoSize); try // recolhe informacoes do sistema no ponteiro vlpVerInfo if GetFileVersionInfo( PChar(vpsArqExe), vldWnd, vldVerInfoSize, vlpVerInfo) then // recolhe informacoes do ponteiro na vlpVerValue if VerQueryValue( vlpVerInfo, '\', Pointer(vlpVerValue), vldVerValueSize) then begin vlsVersao := IntToStr(vlpVerValue.dwFileVersionMS shr 16); vlsVersao := vlsVersao + '.' + IntToStr(vlpVerValue.dwFileVersionMS and $FFFF); vlsVersao := vlsVersao + '.' + IntToStr(vlpVerValue.dwFileVersionLS shr 16); vlsVersao := vlsVersao + '.' + IntToStr(vlpVerValue.dwFileVersionLS and $FFFF); end; finally FreeMem(vlpVerInfo); end; end; Result := vlsVersao; end; function VersaoDoWindows: Integer; type TIsWow64Process = function(AHandle:THandle; var AIsWow64: BOOL): BOOL; stdcall; var vKernel32Handle: DWORD; vIsWow64Process: TIsWow64Process; vIsWow64: BOOL; begin Result := 32; vKernel32Handle := LoadLibrary('kernel32.dll'); if (vKernel32Handle = 0) then Exit; try @vIsWow64Process := GetProcAddress(vKernel32Handle, 'IsWow64Process'); if not Assigned(vIsWow64Process) then Exit; vIsWow64 := False; if (vIsWow64Process(GetCurrentProcess, vIsWow64)) then Result := IfThen(vIsWow64, 64, 32); finally FreeLibrary(vKernel32Handle); end; end; function EhWindows64: Boolean; type TIsWow64Process = function(AHandle:THandle; var AIsWow64: BOOL): BOOL; stdcall; var vKernel32Handle: DWORD; vIsWow64Process: TIsWow64Process; vIsWow64: BOOL; begin vKernel32Handle := LoadLibrary('kernel32.dll'); if (vKernel32Handle = 0) then begin Result := False; Exit; end; try @vIsWow64Process := GetProcAddress(vKernel32Handle, 'IsWow64Process'); if not Assigned(vIsWow64Process) then begin Result := False; Exit; end; vIsWow64Process(GetCurrentProcess, vIsWow64); Result := vIsWow64; finally FreeLibrary(vKernel32Handle); end; end; function Barra(vpsPasta: String; vpbInclui: Boolean = True): String; begin Result := Trim(vpsPasta); if vpbInclui then begin if not (Result[Length(Result)] = '\') then Result := Result + '\'; end else begin if (Result[Length(Result)] = '\') then Result := Copy(Result, 1, Length(Result) - 1); end; end; procedure GeraArqTxt(vpsDirArq, vpsNomArq, vpsExtArq, vpsConteudo: String); var vlsNomArq: String; vltTextFile: TextFile; vlsDirArq: String; begin try vlsDirArq := Barra(vpsDirArq, False); if not DirectoryExists(vlsDirArq) then if not CreateDir(vlsDirArq) then raise Exception.Create( 'Não foi possível criar a pasta [' + vlsDirArq + ']'); vlsNomArq := Barra(vpsDirArq); vlsNomArq := vlsNomArq + vpsNomArq + '.' + vpsExtArq; AssignFile(vltTextFile, vlsNomArq); if not (FileExists(vlsNomArq)) then ReWrite(vltTextFile) else Append(vltTextFile); WriteLn(vltTextFile, vpsConteudo); CloseFile(vltTextFile); except raise Exception.Create( 'Erro ao criar arquivo [' + vpsDirArq + vpsNomArq + '.' + vpsExtArq + ']'); end; end; function ExecutaProgramaEEspera(vpsPrograma: String): Boolean; var vltSh: TShellExecuteInfo; vldCodigoSaida: DWord; begin FillChar(vltSh, SizeOf(vltSh), 0); vltSh.cbSize := SizeOf(TShellExecuteInfo); with vltSh do begin fMask := SEE_MASK_NOCLOSEPROCESS; Wnd := Application.Handle; lpVerb := nil; lpFile := PChar(vpsPrograma); nShow := SW_SHOWNORMAL; end; if ShellExecuteEx(@vltSh) then begin repeat Application.ProcessMessages; GetExitCodeProcess(vltSh.hProcess, vldCodigoSaida); until not(vldCodigoSaida = STILL_ACTIVE); Result := True; end else Result := False; end; procedure ExecutaPrograma(vpsPrograma: String); begin if not FileExists(vpsPrograma) then begin raise Exception.Create( 'Programa [' + vpsPrograma + '] não encontrado para executar!'); end; WinExec(Pchar(vpsPrograma), SW_Normal); end; procedure DeletaPrograma(vpsPrograma: String); begin if not FileExists(vpsPrograma) then begin raise Exception.Create( 'Programa [' + vpsPrograma + '] inexistente para deletar!'); end; DeleteFile(PChar(vpsPrograma)); end; procedure CriaCompatibilidadeWin64NoWin32(vpsPrograma: String); var vltReg: TRegistry; begin if not FileExists(vpsPrograma) then begin raise Exception.Create( 'Programa [' + vpsPrograma + '] inexistente para tornar compatível com Win32!'); end; vltReg := TRegistry.Create; try vltReg.RootKey := HKEY_CURRENT_USER; vltReg.OpenKey('\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers', True); vltReg.WriteString(vpsPrograma, 'WINXPSP3'); vltReg.CloseKey; finally vltReg.Free; end; end; procedure CriaODBCFireBird(vpsAliasDB, vpsPastaDB, vpsNomeDB: String); var vltReg: TRegistry; vlsAliasDB, vlsPastaDB, vlsNomeDB, vlsDB: String; begin vlsAliasDB := vpsAliasDB; //Exemplo: 'OdbcTx16'; vlsPastaDB := vpsPastaDB; //Exemplo: 'C:\AAA\Tx16\db\'; vlsNomeDB := vpsNomeDB; //Exemplo: 'Tx16.FDB'; vlsDB := Barra(vlsPastaDB) + vlsNomeDB; vltReg := TRegistry.Create; try vltReg.RootKey := HKEY_LOCAL_MACHINE; vltReg.OpenKey('\Software\ODBC\ODBC.INI\' + vlsAliasDB, True); vltReg.WriteString('AutoQuotedIdentifier', 'N'); vltReg.WriteString('CharacterSet', 'NONE'); vltReg.WriteString('Client', ''); vltReg.WriteString('Dbname', vlsDB); vltReg.WriteString('Description', ''); vltReg.WriteString('Dialect', '3'); vltReg.WriteString('Driver', SistemaAAADriveCorrente + '\WINDOWS\system32\OdbcFb.dll'); vltReg.WriteString('JdbcDriver', 'IscDbc'); vltReg.WriteString('LockTimeoutWaitTransactions', ''); vltReg.WriteString('NoWait', 'N'); vltReg.WriteString('Password', 'DKEBFJENHFCOBHGHLAIMNAAFICELEAEGDNMFNOGALAMHBBGCHFADNKCBPPGMANOGIEKENIOPHDIPBIECPLLLCBIKEJKMJLPLIB'); vltReg.WriteString('QuotedIdentifier', 'Y'); vltReg.WriteString('ReadOnly', 'N'); vltReg.WriteString('Role', ''); vltReg.WriteString('SafeThread', 'Y'); vltReg.WriteString('SensitiveIdentifier', 'N'); vltReg.WriteString('User', 'SYSDBA'); vltReg.WriteString('UseSchemaIdentifier', '0'); vltReg.CloseKey; vltReg.OpenKey('\Software\ODBC\ODBC.INI\ODBC Data Sources', True); vltReg.WriteString(vlsAliasDB, 'Firebird/InterBase(r) driver'); vltReg.CloseKey; finally vltReg.Free; end; end; function NomeProgramaSemExt(vpsPrograma: String): String; var vlsNomeExe: String; begin vlsNomeExe := ExtractFileName(vpsPrograma); vlsNomeExe := Copy(vlsNomeExe, 1, Length(vlsNomeExe) - 4); Result := vlsNomeExe; end; function SistemaAAADriveCorrente: String; begin Result := ExtractFileDrive(Application.ExeName); end; function DeletaCharAlfanumerico(vpsTexto: String; vpsExcecao: String = ''): String; var vliPos: Integer; begin Result := ''; for vliPos := 1 to Length(vpsTexto) do begin if (Pos(vpsTexto[vliPos], vpsExcecao) > 0) then Result := Result + vpsTexto[vliPos] else if (Pos(vpsTexto[vliPos], '1234567890') > 0) then Result := Result + vpsTexto[vliPos]; end; end; function ContemNumeros(vpsTexto: String): Boolean; var vliPos: Integer; begin Result := False; for vliPos := 1 to Length(vpsTexto) do if (Pos(vpsTexto[vliPos], '1234567890') > 0) then begin Result := True; Break; end; end; end.
unit UFormFileSelect; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, UMyUtil, UIconUtil, ExtCtrls, StdCtrls, siComp, UMainForm; type TVstSelectFileData = record FullPath : WideString; IsFolder : Boolean; FileSize : Int64; FileTime : TDateTime; end; PVstSelectFileData = ^TVstSelectFileData; TfrmFileSelect = class(TForm) vstSelectPath: TVirtualStringTree; Panel1: TPanel; Panel2: TPanel; btnCancel: TButton; btnOK: TButton; siLang_frmFileSelect: TsiLang; procedure vstSelectPathGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); procedure vstSelectPathGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure vstSelectPathInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure vstSelectPathInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure FormCreate(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure siLang_frmFileSelectChangeLanguage(Sender: TObject); private { Private declarations } public procedure AddRootFolder( RootPathList, SelectList : TStringList ); procedure AddDefaultRoot; function getSelectFileList : TStringList; private procedure CheckedNode( Node : PVirtualNode ); procedure AddSelectFile( FilePath : string ); procedure FindSelectFile( Node : PVirtualNode; SelectFileList : TStringList ); end; const VstSelectFile_FileName = 0; VstSelectFile_FileSize = 1; VstSelectFile_FileTime = 2; var frmFileSelect: TfrmFileSelect; implementation {$R *.dfm} { TForm3 } procedure TfrmFileSelect.AddSelectFile(FilePath: string); var ChildNode : PVirtualNode; NodeData : PVstSelectFileData; NodeFullPath : string; begin ChildNode := vstSelectPath.RootNode.FirstChild; while Assigned( ChildNode ) do begin NodeData := vstSelectPath.GetNodeData( ChildNode ); NodeFullPath := NodeData.FullPath; // 找到了节点 if FilePath = NodeFullPath then begin CheckedNode( ChildNode ); Break; end; // 找到了父节点 if MyMatchMask.CheckChild( FilePath, NodeFullPath ) then begin ChildNode.States := ChildNode.States + [ vsHasChildren ]; ChildNode.CheckState := csMixedNormal; vstSelectPath.ValidateChildren( ChildNode, False ); ChildNode := ChildNode.FirstChild; Continue; end; // 下一个节点 ChildNode := ChildNode.NextSibling; end; end; procedure TfrmFileSelect.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmFileSelect.btnOKClick(Sender: TObject); begin Close; ModalResult := mrOk; end; procedure TfrmFileSelect.CheckedNode(Node: PVirtualNode); var ChildNode : PVirtualNode; begin vstSelectPath.CheckState[ Node ] := csCheckedNormal; ChildNode := Node.FirstChild; while Assigned( ChildNode ) do begin CheckedNode( ChildNode ); ChildNode := ChildNode.NextSibling; end; end; procedure TfrmFileSelect.FindSelectFile(Node : PVirtualNode; SelectFileList: TStringList); var ChildNode : PVirtualNode; NodeData : PVstSelectFileData; FullPath : string; begin ChildNode := Node.FirstChild; while Assigned( ChildNode ) do begin if ( ChildNode.CheckState = csCheckedNormal ) then // 找到选择的路径 begin NodeData := vstSelectPath.GetNodeData( ChildNode ); FullPath := NodeData.FullPath; SelectFileList.Add( FullPath ); end else if ChildNode.CheckState = csMixedNormal then // 找下一层 FindSelectFile( ChildNode, SelectFileList ); ChildNode := ChildNode.NextSibling; end; end; procedure TfrmFileSelect.FormCreate(Sender: TObject); begin vstSelectPath.NodeDataSize := SizeOf( TVstSelectFileData ); vstSelectPath.Images := MyIcon.getSysIcon; siLang_frmFileSelectChangeLanguage( nil ); end; procedure TfrmFileSelect.FormShow(Sender: TObject); begin ModalResult := mrCancel; end; function TfrmFileSelect.getSelectFileList: TStringList; begin Result := TStringList.Create; FindSelectFile( vstSelectPath.RootNode, Result ); end; procedure TfrmFileSelect.siLang_frmFileSelectChangeLanguage(Sender: TObject); begin with vstSelectPath.Header do begin Columns[ VstSelectFile_FileName ].Text := siLang_frmFileSelect.GetText( 'vstFileName' ); Columns[ VstSelectFile_FileSize ].Text := siLang_frmFileSelect.GetText( 'vstFileSize' ); Columns[ VstSelectFile_FileTime ].Text := siLang_frmFileSelect.GetText( 'vstFileDate' ); end; end; procedure TfrmFileSelect.AddDefaultRoot; var RootNode : PVirtualNode; begin RootNode := vstSelectPath.RootNode.FirstChild; while Assigned( RootNode ) do begin if RootNode.CheckState = csUncheckedNormal then CheckedNode( RootNode ); // 下一个节点 RootNode := RootNode.NextSibling; end; end; procedure TfrmFileSelect.AddRootFolder( RootPathList,SelectList : TStringList ); var RootFolderNode : PVirtualNode; RootFolderData : PVstSelectFileData; i : Integer; FolderPath : string; begin vstSelectPath.Clear; for i := 0 to RootPathList.Count - 1 do begin FolderPath := RootPathList[i]; RootFolderNode := vstSelectPath.AddChild( vstSelectPath.RootNode ); RootFolderData := vstSelectPath.GetNodeData( RootFolderNode ); RootFolderData.FullPath := FolderPath; RootFolderData.IsFolder := True; RootFolderData.FileSize := 0; RootFolderData.FileTime := MyFileInfo.getFileLastWriteTime( FolderPath ); vstSelectPath.Expanded[ RootFolderNode ] := True; end; for i := 0 to SelectList.Count - 1 do AddSelectFile( SelectList[i] ); end; procedure TfrmFileSelect.vstSelectPathGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var NodeData: PVstSelectFileData; begin if ( Column = VstSelectFile_FileName ) and ( ( Kind = ikNormal ) or ( Kind = ikSelected ) ) then begin NodeData := Sender.GetNodeData(Node); ImageIndex := MyIcon.getIconByFilePath( NodeData.FullPath ); end else ImageIndex := -1; end; procedure TfrmFileSelect.vstSelectPathGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); var NodeData : PVstSelectFileData; begin NodeData := Sender.GetNodeData( Node ); if Column = VstSelectFile_FileName then begin if Node.Parent = Sender.RootNode then CellText := NodeData.FullPath else CellText := ExtractFileName( NodeData.FullPath ); end else if Column = VstSelectFile_FileSize then begin if NodeData.IsFolder then CellText := '' else CellText := MySize.getFileSizeStr( NodeData.FileSize ) end else if Column = VstSelectFile_FileTime then CellText := DateTimeToStr( NodeData.FileTime ) else CellText := ''; end; procedure TfrmFileSelect.vstSelectPathInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var Data, ChildData: PVstSelectFileData; sr: TSearchRec; FullPath, FileName, FilePath : string; FileSize : Int64; FileTime : TDateTime; IsFolder : Boolean; ChildNode: PVirtualNode; LastWriteTimeSystem: TSystemTime; begin Screen.Cursor := crHourGlass; // 搜索目录的信息,找不到则跳过 Data := Sender.GetNodeData(Node); FullPath := MyFilePath.getPath( Data.FullPath ); if FindFirst( FullPath + '*', faAnyfile, sr ) = 0 then begin repeat FileName := sr.Name; if ( FileName = '.' ) or ( FileName = '..' ) then Continue; // 文件信息 FilePath := FullPath + FileName; FileSize := sr.Size; FileTimeToSystemTime( sr.FindData.ftLastWriteTime, LastWriteTimeSystem ); LastWriteTimeSystem.wMilliseconds := 0; FileTime := SystemTimeToDateTime( LastWriteTimeSystem ); IsFolder := DirectoryExists( FilePath ); // 子节点数据 ChildNode := Sender.AddChild( Node ); ChildData := Sender.GetNodeData(ChildNode); ChildData.FullPath := FilePath; ChildData.FileSize := FileSize; ChildData.FileTime := FileTime; ChildData.IsFolder := IsFolder; // 初始化 if Node.CheckState = csCheckedNormal then // 如果父节点全部Check, 则子节点 check ChildNode.CheckState := csCheckedNormal; // 子节点数目 Inc( ChildCount ); until FindNext(sr) <> 0; end; FindClose(sr); Screen.Cursor := crDefault; end; procedure TfrmFileSelect.vstSelectPathInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var NodeData: PVstSelectFileData; begin NodeData := Sender.GetNodeData(Node); if MyFilePath.getHasChild( NodeData.FullPath ) then Include( InitialStates, ivsHasChildren ); Node.CheckType := ctTriStateCheckBox; end; end.
unit JPL.Utils; interface function IfThenStr(BoolValue: Boolean; const ResultIfTrue: string; ResultIfFalse: string = ''): string; function IfThenInt(BoolValue: Boolean; const ResultIfTrue: integer; ResultIfFalse: integer = -1): integer; function IfThenUInt(BoolValue: Boolean; const ResultIfTrue: UInt32; ResultIfFalse: UInt32 = 0): UInt32; function IfThenInt64(BoolValue: Boolean; const ResultIfTrue: Int64; ResultIfFalse: Int64 = -1): Int64; function IfThenUInt64(BoolValue: Boolean; const ResultIfTrue: UInt64; ResultIfFalse: UInt64 = 0): UInt64; function IfThenFloat(BoolValue: Boolean; const ResultIfTrue: Double; ResultIfFalse: Double = -1): Double; implementation function IfThenStr(BoolValue: Boolean; const ResultIfTrue: string; ResultIfFalse: string = ''): string; begin if BoolValue then Result := ResultIfTrue else Result := ResultIfFalse; end; function IfThenInt(BoolValue: Boolean; const ResultIfTrue: integer; ResultIfFalse: integer = -1): integer; begin if BoolValue then Result := ResultIfTrue else Result := ResultIfFalse; end; function IfThenUInt(BoolValue: Boolean; const ResultIfTrue: UInt32; ResultIfFalse: UInt32 = 0): UInt32; begin if BoolValue then Result := ResultIfTrue else Result := ResultIfFalse; end; function IfThenInt64(BoolValue: Boolean; const ResultIfTrue: Int64; ResultIfFalse: Int64 = -1): Int64; begin if BoolValue then Result := ResultIfTrue else Result := ResultIfFalse; end; function IfThenUInt64(BoolValue: Boolean; const ResultIfTrue: UInt64; ResultIfFalse: UInt64 = 0): UInt64; begin if BoolValue then Result := ResultIfTrue else Result := ResultIfFalse; end; function IfThenFloat(BoolValue: Boolean; const ResultIfTrue: Double; ResultIfFalse: Double = -1): Double; begin if BoolValue then Result := ResultIfTrue else Result := ResultIfFalse; end; end.
unit Facade; interface uses BaseFacades, Registrator, Classes, DBGate, SDFacade, LicenseZOne, GRRObligation, MeasureUnits, BaseObjects,Well, State, SeismWorkType, GRRClientGISQueries, GRRParameter; type TMainFacade = class (TSDFacade) private FFilter: string; FRegistrator: TRegistrator; FLicenseZone: TLicenseZone; FOnActiveLicenseZoneChanged: TNotifyEvent; FNirTypes: TNirTypes; FNirStates: TNIRStates; FMeasureUnits : TMeasureUnits; FWellCategories: TWellCategories; FWellStates: TStates; FMainNirObligations: TNIRObligations; FSeisWorkTypes : TSeismWorkTypes; FGRRReportConcreteQueries: TGRRReportConcreteQueries; FGRRReportGISExcelQueries: TGRRReportGISXLQueries; FActiveWell: TWell; FParameterTypes: TGRRParameterTypes; FParamGroups : TGRRParamGroups; FGRRWellItervalTypes : TGRRWellIntervalTypes; //FNirObligation: procedure SetLicenseZone(const Value: TLicenseZone); function GetAllNirStates: TNIRStates; function GetAllNirTypes: TNirTypes; function GetAllMeasureUnits: TMeasureUnits; function GetAllWellCategories: TWellCategories; function GetAllWellStates: TStates; function GetAllMainNirObligations: TNIRObligations; function GetAllSeisWorkTypes: TSeismWorkTypes; function GetGRRReportConcreteQueries: TGRRReportConcreteQueries; function GetGRRReportGISXLQueries: TGRRReportGISXLQueries; function GetParameterTypes: TGRRParameterTypes; function GetGRRParamGroups: TGRRParamGroups; function GeTWellIntervalTypes: TGRRWellIntervalTypes; protected function GetRegistrator: TRegistrator; override; function GetDataPosterByClassType(ADataPosterClass: TDataPosterClass): TDataPoster; override; public class function GetInstance: TMainFacade; // фильтр property Filter: string read FFilter write FFilter; property ActiveLicenseZone: TLicenseZone read FLicenseZone write SetLicenseZone; property OnActiveLicenseZoneChanged: TNotifyEvent read FOnActiveLicenseZoneChanged write FOnActiveLicenseZoneChanged; //все состояния работ property AllNirStates : TNIRStates read GetAllNirStates; // все типы работы property AllNirTypes: TNirTypes read GetAllNirTypes; // все единицы измерения property AllMeasureUnits: TMeasureUnits read GetAllMeasureUnits; //все категории скважин property AllWellCategories : TWellCategories read GetAllWellCategories; // все типы скважин property AllWellStates: TStates read GetAllWellStates; // все обязательства по НИР property AllMainNirObligations: TNIRObligations read GetAllMainNirObligations; //все типы сейсморазведочных работ property AllSeisWorkTypes: TSeismWorkTypes read GetAllSeisWorkTypes; property GRRReportConcreteQueries: TGRRReportConcreteQueries read GetGRRReportConcreteQueries; property GRRReportGISXLQueries: TGRRReportGISXLQueries read GetGRRReportGISXLQueries; // выбранная скважина property ActiveWell: TWell read FActiveWell write FActiveWell; // типы параметров property ParameterTypes: TGRRParameterTypes read GetParameterTypes; // все группы параметров property ParamGroups: TGRRParamGroups read GetGRRParamGroups; // все типы интервалов property WellIntervalTypes: TGRRWellIntervalTypes read GeTWellIntervalTypes; // в конструкторе создаются и настраиваются всякие // необходимые в скором времени вещи constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TConcreteRegistrator = class(TRegistrator) public constructor Create; override; end; implementation uses Math, GRRObligationPoster, TypInfo, SysUtils; { TMDFacade } constructor TMainFacade.Create(AOwner: TComponent); begin inherited; // настройка соединения с бд //DBGates.ServerClassString := 'RiccServer.CommonServer'; DBGates.AutorizationMethod := amEnum; DBGates.NewAutorizationMode := false; // обязательно также тип клиента прям здесь указать //DBGates.ClientAppTypeID := 19; // нам нужны только версии фонда лицензионных участков VersionFilter := '(CLIENT_APP_TYPE_ID = 16) OR (VERSION_ID = 0)'; LicenseZoneFilter := '(VCH_SERIA = ' + '''' + 'СЫК' + '''' + ') AND (LICENSE_TYPE_ID IS NOT NULL)'; end; destructor TMainFacade.Destroy; begin FreeAndNil(FGRRReportConcreteQueries); inherited; end; function TMainFacade.GetAllMainNirObligations: TNIRObligations; begin if not Assigned(FMainNirObligations) then begin FMainNirObligations := TNirObligations.Create; FMainNirObligations.Reload('', true); end; Result := FMainNirObligations; end; function TMainFacade.GetAllMeasureUnits: TMeasureUnits; begin if not Assigned(FMeasureUnits) then begin FMeasureUnits := TMeasureUnits.Create; FMeasureUnits.Reload('', true); end; Result := FMeasureUnits; end; function TMainFacade.GetAllNirStates: TNIRStates; begin if not Assigned (FNirStates) then begin FNirStates := TNIRStates.Create; FNirStates.Reload('', true); end; Result := FNirStates; end; function TMainFacade.GetAllNirTypes: TNirTypes; begin if not Assigned(FNirTypes) then begin FNirTypes := TNirTypes.Create; FNirTypes.Reload('NIR_TYPE_ID <= 0', true); end; Result := FNirTypes; end; function TMainFacade.GetAllSeisWorkTypes: TSeismWorkTypes; begin if not Assigned(FSeisWorkTypes) then begin FSeisWorkTypes := TSeismWorkTypes.Create; FSeisWorkTypes.Reload('', true); end; Result := FSeisWorkTypes; end; function TMainFacade.GetAllWellCategories: TWellCategories; begin if not Assigned(FWellCategories) then begin FWellCategories := TWellCategories.Create; FWellCategories.Reload('', true); end; Result := FWellCategories; end; function TMainFacade.GetAllWellStates: TStates; begin if not Assigned(FWellStates) then begin FWellStates := TStates.Create; FWellStates.Reload('',true); end; Result := FWellStates; end; function TMainFacade.GetDataPosterByClassType( ADataPosterClass: TDataPosterClass): TDataPoster; begin Result := inherited GetDataPosterByClassType(ADataPosterClass); if Result is TBaseObligationDataPoster then begin (Result as TBaseObligationDataPoster).AllNirTypes := AllNirTypes; (Result as TBaseObligationDataPoster).AllNirStates := AllNirStates; end; if Result is TNIRDataPoster then begin (Result as TNIRDataPoster).AllMeasureUnits := AllMeasureUnits; //(Result as TNIRDataPoster).AllMainNirObligations := AllMainNirObligations; end else if Result is TSeismicObligationDataPoster then begin (Result as TSeismicObligationDataPoster).AllSeismWorkTypes := AllSeisWorkTypes; end else if Result is TDrillingObligationDataPoster then begin (Result as TDrillingObligationDataPoster).AllWellStates := AllWellStates; (Result as TDrillingObligationDataPoster).AllWellCategories := AllWellCategories; end else if Result is TNirObligationPlaceDataPoster then begin (Result as TNirObligationPlaceDataPoster).AllStructures := AllStructures; end else if Result is TSeismicObligationPlaceDataPoster then begin (Result as TSeismicObligationPlaceDataPoster).AllAreas := AllAreas; (Result as TSeismicObligationPlaceDataPoster).AllStructures := AllStructures; end else if Result is TDrillingObligationWellDataPoster then begin (Result as TDrillingObligationWellDataPoster).AllNirStates := AllNirStates; (Result as TDrillingObligationWellDataPoster).AllWells := AllWells; (Result as TDrillingObligationWellDataPoster).AllStructures := AllStructures; end ; end; function TMainFacade.GetGRRParamGroups: TGRRParamGroups; begin if not Assigned(FParamGroups) then begin FParamGroups := TGRRParamGroups.Create; FParamGroups.Reload('', true); end; Result := FParamGroups; end; function TMainFacade.GetGRRReportConcreteQueries: TGRRReportConcreteQueries; begin if not Assigned(FGRRReportConcreteQueries) then FGRRReportConcreteQueries := TGRRReportConcreteQueries.Create; Result := FGRRReportConcreteQueries; end; function TMainFacade.GetGRRReportGISXLQueries: TGRRReportGISXLQueries; begin if not Assigned(FGRRReportGISExcelQueries) then FGRRReportGISExcelQueries := TGRRReportGISXLQueries.Create; Result := FGRRReportGISExcelQueries; end; class function TMainFacade.GetInstance: TMainFacade; begin Result := inherited GetInstance as TMainFacade; end; function TMainFacade.GetParameterTypes: TGRRParameterTypes; begin if not Assigned(FParameterTypes) then begin FParameterTypes := TGRRParameterTypes.Create; FParameterTypes.Reload('', true); end; Result := FParameterTypes; end; function TMainFacade.GetRegistrator: TRegistrator; begin if not Assigned(FRegistrator) then FRegistrator := TConcreteRegistrator.Create; Result := FRegistrator; end; { TConcreteRegistrator } constructor TConcreteRegistrator.Create; begin inherited; AllowedControlClasses.Add(TStringsRegisteredObject); AllowedControlClasses.Add(TTreeViewRegisteredObject); end; function TMainFacade.GeTWellIntervalTypes: TGRRWellIntervalTypes; begin if not Assigned(FGRRWellItervalTypes) then begin FGRRWellItervalTypes := TGRRWellIntervalTypes.Create; FGRRWellItervalTypes .Reload('', true); end; Result := FGRRWellItervalTypes; end; procedure TMainFacade.SetLicenseZone(const Value: TLicenseZone); begin if FLicenseZOne <> Value then begin FLicenseZone := Value; if Assigned(FOnActiveLicenseZoneChanged) then FOnActiveLicenseZoneChanged(Self); end; end; end.
unit TaskClass; interface type CTaskManager = class private SleepTime: Integer; CycleTime: Integer; TaskPosition: Integer; SleepState: Boolean; WorkState: Boolean; CurrentTaskTime: Integer; CurrentSleepTime: Integer; TaskTimes: TArray<Integer>; TaskCost: Integer; public function IsWork(): Boolean; function IsSleep(): Boolean; function GetTaskCost(): Integer; constructor Create(CycleTime, SleepTime: Integer; TaskTimes: TArray<Integer>); procedure Update(); procedure Process(); end; implementation procedure CTaskManager.Process; begin if (not SleepState) and (IsWork) then begin Dec(CurrentTaskTime, CycleTime); if (CurrentTaskTime <= 0) then begin Inc(TaskPosition); if (TaskPosition = Length(TaskTimes)) then begin WorkState := False; end else begin CurrentTaskTime := TaskTimes[TaskPosition]; SleepState := True; end; end; end; end; procedure CTaskManager.Update; begin if (SleepState) and (IsWork) then begin Dec(CurrentSleepTime, CycleTime); if (CurrentSleepTime <= 0) then begin CurrentSleepTime := SleepTime; SleepState := False; end; end; end; function CTaskManager.GetTaskCost(): Integer; begin Result := TaskCost; end; function CTaskManager.IsSleep(): Boolean; begin Result := SleepState; end; function CTaskManager.IsWork(): Boolean; begin Result := WorkState; end; constructor CTaskManager.Create(CycleTime, SleepTime: Integer; TaskTimes: TArray<Integer>); var I: Integer; begin Self.CycleTime := CycleTime; Self.SleepTime := SleepTime; Self.TaskTimes := TaskTimes; TaskPosition := 0; CurrentTaskTime := TaskTimes[TaskPosition]; CurrentSleepTime := SleepTime; SleepState := False; WorkState := True; TaskCost := 0; for I := 0 to High(TaskTimes) do begin Inc(TaskCost, TaskTimes[I]); end; end; end.
program Main; var x, y : real; var str: string; var varname : string; var myvar : any; var i : integer; procedure Alpha(a, b : real); var s : real; begin x := a + y + b; if (x) then begin y := x + 3; end; panic() end; procedure fib(i : integer) -> integer; begin if (i = real_to_int(0)) then begin return real_to_int(1); end else if (i = real_to_int(1)) begin return real_to_int(1); end else begin return fib(i - real_to_int(1)) + fib(i - real_to_int(2)); end; end; begin { Main } {print(fib(4));} i := real_to_int(0); while (i < real_to_int(10000)) do begin i := i - real_to_int(1); end; end. { Main }
unit fViewSales; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, Aurelius.Bind.Dataset, AdvEdit, Vcl.Mask, Vcl.DBCtrls, Aurelius.Engine.ObjectManager, Entidades.Comercial; type TfmViewSales = class(TForm) PageControl1: TPageControl; cbDates: TComboBox; tsGrouped: TTabSheet; tsItems: TTabSheet; DBGrid1: TDBGrid; adsSaleItems: TAureliusDataset; adsSaleItemsSelf: TAureliusEntityField; adsSaleItemsDesconto: TCurrencyField; adsSaleItemsId: TIntegerField; adsSaleItemsProduto: TAureliusEntityField; adsSaleItemsQtde: TIntegerField; adsSaleItemsValorUnitario: TCurrencyField; adsSaleItemsValorFinal: TCurrencyField; adsSaleItemsAnimal: TAureliusEntityField; adsSaleItemsProdutoDescricao: TStringField; adsSaleItemsAnimalNome: TStringField; dsSasleItems: TDataSource; adsSales: TAureliusDataset; dsSales: TDataSource; Splitter1: TSplitter; adsSalesSelf: TAureliusEntityField; adsSalesId: TIntegerField; adsSalesData: TDateTimeField; adsSalesPessoa: TAureliusEntityField; adsSalesItens: TDataSetField; adsSalesPaymentType: TAureliusEntityField; Panel1: TPanel; DBGrid2: TDBGrid; Panel2: TPanel; edTotalFinal: TDBEdit; Label1: TLabel; Label2: TLabel; edCustomer: TDBEdit; adsSalesPessoaNome: TStringField; adsSalesItemsTotal: TCurrencyField; DBGrid3: TDBGrid; dsItems: TDataSource; adsItems: TAureliusDataset; AureliusEntityField1: TAureliusEntityField; CurrencyField1: TCurrencyField; IntegerField1: TIntegerField; AureliusEntityField2: TAureliusEntityField; IntegerField2: TIntegerField; CurrencyField2: TCurrencyField; CurrencyField3: TCurrencyField; AureliusEntityField3: TAureliusEntityField; StringField1: TStringField; StringField2: TStringField; adsItemsVendaPessoaNome: TStringField; adsItemsSaleData: TDateTimeField; procedure FormCreate(Sender: TObject); procedure cbDatesChange(Sender: TObject); procedure FormDestroy(Sender: TObject); private FManager: TObjectManager; procedure RefreshSales(Start, Finish: TDateTime); public end; implementation uses Aurelius.Criteria.Base, Aurelius.Criteria.Linq, dConnection; {$R *.dfm} procedure TfmViewSales.cbDatesChange(Sender: TObject); var Start, Finish: TDateTime; begin if cbDates.ItemIndex = -1 then Exit; Start := Date; Finish := Date; case cbDates.ItemIndex of 0: Start := Date - 1; 1: Start := Date - 6; 2: Start := Date - 29; end; RefreshSales(Start, Finish); end; procedure TfmViewSales.FormCreate(Sender: TObject); begin FManager := dmConnection.CreateManager; cbDates.Items.Clear; cbDates.Items.Add('Hoje e Ontem'); cbDates.Items.Add('Últimos 7 dias'); cbDates.Items.Add('Últimos 30 dias'); cbDates.ItemIndex := 0; cbDatesChange(nil); end; procedure TfmViewSales.FormDestroy(Sender: TObject); begin adsSales.Close; adsItems.Close; FManager.Free; end; procedure TfmViewSales.RefreshSales(Start, Finish: TDateTime); begin adsSales.Close; adsSales.SetSourceCriteria( FManager.Find<TVenda> .Where( TLinq.GreaterOrEqual('Data', Trunc(Start)) and TLinq.LessThan('Data', Trunc(Finish) + 1) ) .OrderBy('Data', false), 40 ); adsSales.Open; adsItems.Close; adsItems.SetSourceCriteria( FManager.Find<TItemVenda> .CreateAlias('Sale', 'Sale') .Where( TLinq.GreaterOrEqual('Sale.Data', Trunc(Start)) and TLinq.LessThan('Sale.Data', Trunc(Finish) + 1) ) .OrderBy('Sale.Data', false), 40 ); adsItems.Open; end; end.
unit uCoupled; interface type TCompressionService = class private function DoCompression(aByteArray: TArray<Byte>): TArray<Byte>; public procedure Compress(aSourceFilename: string; aTargetFilename: string); end; implementation uses System.Classes , System.SysUtils ; { TCompressionService } procedure TCompressionService.Compress(aSourceFilename: string; aTargetFilename: string); var LContent, CompressedContent: TArray<Byte>; InFS, OutFS: TFileStream; begin // Read content InFS := TFileStream.Create(aSourceFilename, fmOpenRead); try SetLength(LContent, InFS.Size); InFS.Read(LContent, InFS.Size); finally InFS.Free; end; // Compress CompressedContent := DoCompression(LContent); // Write compressed content OutFS := TFileStream.Create(aTargetFilename, fmCreate); try OutFS.Write(CompressedContent, Length(CompressedContent)); finally OutFS.Free; end; end; function TCompressionService.DoCompression(aByteArray: TArray<Byte>): TArray<Byte>; begin // Here's where you'd compress the file.......... Result := aByteArray; end; end.
unit TxServerFormUnit; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. } interface uses {$IFNDEF OSX} WIndows, {$ENDIF} System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, IniFiles, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Menus, FMX.Platform, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Edit, IOUtils, OSXUIUtils, FileSupport, SystemSupport, kCritSct, StringSupport, DateSupport, FHIRResources, FHIRParser, FHIRSecurity, FHIRServerContext, FHIRUserProvider, FHIRStorageService, FHIRRestServer, ServerUtilities, FHIRLog, VocabPocServerCore, TerminologyServer, WebSourceProvider; const MIN_WIDTH = 400; MIN_HEIGHT = 200; type TServerStatus = (Resting, Starting, Running, Stopping); TServerControl = class (TThread) private FStatus : TServerStatus; FSource : String; FWantStart : boolean; FWantStop : boolean; FLock : TCriticalSection; FMsgs : TStringList; FIni : TFHIRServerIniFile; FWebServer : TFhirWebServer; FStart : TDateTime; procedure loadVocab(server : TTerminologyServer; folder : String); procedure loadPoC(server : TTerminologyServer); procedure DoStart; procedure DoStop; procedure log(s : String); procedure init; procedure close; protected procedure Execute; override; public Constructor Create; Destructor Destroy; override; procedure start; procedure stop; end; TTxServerForm = class(TForm) pnlSettings: TPanel; MainMenu1: TMainMenu; mnuFile: TMenuItem; mnuHelp: TMenuItem; mnuServer: TMenuItem; mnuExit: TMenuItem; mnuAbout: TMenuItem; mnuStatus: TMenuItem; Label1: TLabel; Label2: TLabel; Label3: TLabel; edtFolder: TEdit; edtPort: TEdit; edtSnomed: TEdit; pnlStatus: TPanel; StyleBook1: TStyleBook; btnStatus: TButton; lblStatus: TLabel; mLog: TMemo; btnPoCFolder: TButton; btnSnomed: TButton; odSnomed: TOpenDialog; tmrStatus: TTimer; mnuView: TMenuItem; mnuViewSettings: TMenuItem; btnBrowser: TButton; procedure mnuExitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure btnPoCFolderClick(Sender: TObject); procedure btnSnomedClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tmrStatusTimer(Sender: TObject); procedure btnStatusClick(Sender: TObject); procedure mnuViewSettingsClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure webDidFinishLoad(ASender: TObject); procedure btnBrowserClick(Sender: TObject); private { Private declarations } FIni : TIniFile; FStatus : TServerStatus; FServer : TServerControl; FWantClose : boolean; procedure checkPreRequisites; public { Public declarations } end; var TxServerForm: TTxServerForm; implementation {$R *.fmx} procedure TTxServerForm.btnBrowserClick(Sender: TObject); begin OpenURL(FServer.FWebServer.ServerContext.FormalURLPlainOpen); end; procedure TTxServerForm.btnPoCFolderClick(Sender: TObject); var s : String; begin if SelectDirectory(Handle, 'Select Vocab PoC', edtFolder.text, s) then edtFolder.Text := s; end; procedure TTxServerForm.btnSnomedClick(Sender: TObject); begin odSnomed.InitialDir := PathFolder(edtSnomed.Text); if odSnomed.Execute then edtSnomed.Text := odSnomed.FileName; end; procedure TTxServerForm.btnStatusClick(Sender: TObject); begin if btnStatus.Text = 'Start' then begin if not StringIsInteger16(edtPort.Text) then raise Exception.Create('Port must be a Positive Integer between 0 and 65535'); FServer.FSource := edtFolder.Text; FServer.FIni.WriteString('web', 'http', edtPort.Text); FServer.FIni.WriteString('web', 'host', 'localhost'); FServer.FIni.WriteString('web', 'base', '/vocab'); FServer.FIni.WriteString('web', 'clients', IncludeTrailingPathDelimiter(SystemTemp) + 'auth.ini'); FServer.FIni.WriteString('admin', 'email', 'grahame@hl7.org'); FServer.FIni.WriteString('ucum', 'source', path([ExtractFilePath(paramstr(0)), 'ucum-essence.xml'])); FServer.FIni.WriteString('loinc', 'cache', path([ExtractFilePath(paramstr(0)), 'loinc_261.cache'])); FServer.FIni.WriteString('lang', 'source', path([ExtractFilePath(paramstr(0)), 'lang.txt'])); FServer.FIni.WriteString('snomed', 'cache', edtSnomed.text); FServer.start; end else FServer.stop; end; procedure TTxServerForm.checkPreRequisites; var s : String; begin s := ''; if not FileExists(path([ExtractFilePath(paramstr(0)), 'ucum-essence.xml'])) then s := s + 'File '+path([ExtractFilePath(paramstr(0)), 'ucum-essence.xml'])+' not found'+#13#10; if not FileExists(path([ExtractFilePath(paramstr(0)), 'loinc_261.cache'])) then s := s + 'File '+path([ExtractFilePath(paramstr(0)), 'loinc_261.cache'])+' not found'+#13#10; if not FileExists(path([ExtractFilePath(paramstr(0)), 'web.zip'])) then s := s + 'File '+path([ExtractFilePath(paramstr(0)), 'web.zip'])+' not found'+#13#10; if s <> '' then MessageDlg('Installation Problem: '+#13#10+s, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0); end; procedure TTxServerForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caNone; case FStatus of Resting : Action := TCloseAction.caFree; Starting : beep; Running: begin FWantClose := true; FServer.Stop; end; Stopping: FWantClose := true; end; end; procedure TTxServerForm.FormCreate(Sender: TObject); begin FIni := TIniFile.Create(IncludeTrailingPathDelimiter(SystemTemp) + 'vocab-server.ini'); edtFolder.Text := Fini.ReadString('server', 'folder', ''); edtPort.Text := Fini.ReadString('server', 'port', ''); edtSnomed.Text := Fini.ReadString('server', 'snomed', ''); FServer := TServerControl.Create; FStatus := Stopping; tmrStatusTimer(nil); end; procedure TTxServerForm.FormDestroy(Sender: TObject); begin FServer.Free; Fini.WriteString('server', 'folder', edtFolder.Text); Fini.WriteString('server', 'port', edtPort.Text); Fini.WriteString('server', 'snomed', edtSnomed.Text); Fini.WriteBool('view', 'settings', mnuViewSettings.IsChecked); FIni.Free; end; procedure TTxServerForm.FormResize(Sender: TObject); begin if ClientWidth < MIN_WIDTH then ClientWidth := MIN_WIDTH else if ClientHeight < MIN_HEIGHT then ClientHeight := MIN_HEIGHT else exit; {$IFNDEF OSX} Mouse_Event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); {$ENDIF} end; procedure TTxServerForm.FormShow(Sender: TObject); begin mnuViewSettings.IsChecked := Fini.ReadBool('view', 'settings', true); if not mnuViewSettings.IsChecked then pnlSettings.size.height := 0; checkPreRequisites; end; procedure TTxServerForm.mnuExitClick(Sender: TObject); begin Close; end; procedure TTxServerForm.mnuViewSettingsClick(Sender: TObject); begin if mnuViewSettings.IsChecked then begin pnlSettings.size.height := 0; mnuViewSettings.IsChecked := false; end else begin pnlSettings.size.height := 105; mnuViewSettings.IsChecked := true; end; end; procedure TTxServerForm.tmrStatusTimer(Sender: TObject); var b : boolean; begin if FServer = nil then exit; if FServer.FStatus <> FStatus then begin FStatus := FServer.FStatus; case FStatus of Resting: begin if FWantClose then Close; btnStatus.Text := 'Start'; btnStatus.enabled := true; mnuStatus.Text := 'Start'; mnuStatus.enabled := true; edtFolder.enabled := true; edtPort.enabled := true; edtSnomed.enabled := true; btnPoCFolder.enabled := true; btnSnomed.enabled := true; lblStatus.Text := 'The server is not running'; btnBrowser.Enabled := false; end; Starting: begin btnStatus.Text := 'Starting'; btnStatus.enabled := false; mnuStatus.Text := 'Starting'; mnuStatus.enabled := false; edtFolder.enabled := false; edtPort.enabled := false; edtSnomed.enabled := false; btnPoCFolder.enabled := false; btnSnomed.enabled := false; lblStatus.Text := 'The server is starting'; btnBrowser.Enabled := false; end; Running: begin btnStatus.Text := 'Stop'; btnStatus.enabled := true; mnuStatus.Text := 'Stop'; mnuStatus.enabled := true; edtFolder.enabled := false; edtPort.enabled := false; edtSnomed.enabled := false; btnPoCFolder.enabled := false; btnSnomed.enabled := false; lblStatus.Text := 'The server is running'; btnBrowser.Enabled := true; end; Stopping: begin btnStatus.Text := 'Stopping'; btnStatus.enabled := false; mnuStatus.Text := 'Stopping'; mnuStatus.enabled := false; edtFolder.enabled := false; edtPort.enabled := false; edtSnomed.enabled := false; btnPoCFolder.enabled := false; btnSnomed.enabled := false; lblStatus.Text := 'The server is stopping'; btnBrowser.Enabled := false; end; end; end; FServer.FLock.Enter; try b := FServer.FMsgs.Count > 0; if b then begin mLog.Lines.AddStrings(FServer.FMsgs); FServer.FMsgs.Clear; end; finally FServer.FLock.Leave; end; if b then mLog.GoToTextEnd; end; procedure TTxServerForm.webDidFinishLoad(ASender: TObject); begin end; { TServerControl } procedure TServerControl.close; begin FMsgs.Free; FIni.Free; end; constructor TServerControl.Create; begin inherited Create; FLock := TCriticalSection.Create('Control Thread'); end; destructor TServerControl.Destroy; begin FLock.Free; inherited; end; procedure TServerControl.DoStart; var ctxt : TFHIRServerContext; store : TTerminologyServerStorage; procedure SetAccess(cfg : TFHIRResourceConfig); begin cfg.Supported := true; cfg.cmdUpdate := false; cfg.cmdDelete := false; cfg.cmdValidate := false; cfg.cmdHistoryInstance := false; cfg.cmdHistoryType := true; cfg.cmdSearch := true; cfg.cmdCreate := false; cfg.cmdOperation := true; cfg.cmdVRead := false; end; begin FStart := now; FStatus := Starting; Log('Starting Server'); Try store := TTerminologyServerStorage.create(TTerminologyServer.create(nil)); try ctxt := TFHIRServerContext.Create(store.Link); try ctxt.TerminologyServer := store.Server.Link; store.ServerContext := ctxt; ctxt.TerminologyServer.load(FIni); setAccess(ctxt.ResConfig['CodeSystem']); setAccess(ctxt.ResConfig['ValueSet']); setAccess(ctxt.ResConfig['ConceptMap']); loadPoC(ctxt.TerminologyServer); ctxt.ownername := 'Vocab PoC Server'; FWebServer := TFhirWebServer.create(FIni.Link, ctxt.ownername, ctxt.TerminologyServer, ctxt.link); FWebServer.SourceProvider := TFHIRWebServerSourceZipProvider.Create(path([ExtractFilePath(paramstr(0)), 'web.zip'])); ctxt.UserProvider := TTerminologyServerUserProvider.Create; ctxt.userProvider.OnProcessFile := FWebServer.ReturnProcessedFile; FWebServer.AuthServer.UserProvider := ctxt.userProvider.Link; FWebServer.IsTerminologyServerOnly := true; FWebServer.Start(true); finally ctxt.free; end; finally store.free; end; Log('Server is Started and ready for business at '+FWebServer.ServerContext.FormalURLPlainOpen); FStatus := Running; except on e : Exception do begin Log('Server failed to Start: '+e.message); FStatus := Resting; if FWebServer <> nil then try FWebServer.Free; except end; end; End; end; procedure TServerControl.DoStop; begin FStatus := Stopping; Log('Stopping'); FWebServer.Stop; FWebServer.Free; Log('Stopped'); FStatus := Resting; end; procedure TServerControl.Execute; begin init; try try repeat if FWantStart then begin FWantStart := false; DoStart; end; if FWantStop then begin FWantStop := false; DoStop; end; sleep(50); until Terminated; except on e:exception do Log('internal thread exiting: '+e.Message); end; finally close; end; end; procedure TServerControl.init; begin FMsgs := TStringList.create; FIni := TFHIRServerIniFile.Create(''); logevent := log; end; procedure TServerControl.loadPoC(server: TTerminologyServer); begin log('Loading Vocab from '+FSource); loadVocab(server, 'fhir'); loadVocab(server, 'v2'); loadVocab(server, 'v3'); loadVocab(server, 'cda'); loadVocab(server, 'cimi'); end; procedure TServerControl.loadVocab(server: TTerminologyServer; folder: String); var filename : String; count : integer; procedure load(fn : String); var res : TFHIRResource; begin inc(count); res := TFHIRXmlParser.ParseFile(nil, 'en', fn); try server.SeeTerminologyResource(res); finally res.Free; end; end; begin count := 0; log(folder+'...'); for filename in TDirectory.GetFiles(path([FSource, folder]), '*.xml', TSearchOption.soTopDirectoryOnly) do load(filename); if FolderExists(path([FSource, folder, 'codeSystems'])) then for filename in TDirectory.GetFiles(path([FSource, folder, 'codeSystems']), '*.xml', TSearchOption.soTopDirectoryOnly) do load(filename); if FolderExists(path([FSource, folder, 'valueSets'])) then for filename in TDirectory.GetFiles(path([FSource, folder, 'valueSets']), '*.xml', TSearchOption.soTopDirectoryOnly) do load(filename); log(inttostr(count)+' resources loaded'); end; procedure TServerControl.log(s: String); begin s := DescribePeriod(now - FStart)+' '+s; FLock.Enter; try FMsgs.Add(s); finally FLock.Leave; end; end; procedure TServerControl.start; begin FWantStart := true; end; procedure TServerControl.stop; begin FWantStop := true; end; end.
Program Aufgabe3(input, output); { wir berechnen die stadardabweichung der element eines feldes vom typ tFeld } const FELDGROESSE=5; type tIndex=1..FELDGROESSE; tFeld=array[tIndex] of real; var feld : tFeld; m : real; function mittelwert(inFeld : tFeld) : real; var sum : real; i : integer; {iter variable} begin { init } sum := 0; for i := 1 to FELDGROESSE do begin sum := sum + inFeld[i]; end; mittelwert := sum / FELDGROESSE; end; function standardabweichung(inFeld : tFeld; inMittelwert : real) : real; var s : real; {standardbweichung} i : integer; {iter} sum : real; begin sum := 0; for i := 1 to FELDGROESSE do begin sum := sum + (inFeld[i] - inMittelwert) * (inFeld[i] - inMittelwert); end; s := sqrt(sum / FELDGROESSE); standardabweichung := s; end; begin { init } feld[1] := 1; feld[2] := 2; feld[3] := 3; feld[4] := 4; feld[5] := 5; m := mittelwert(feld); writeln(standardabweichung(feld, m)); end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [AGENCIA_BANCO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit AgenciaBancoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, DB, SysUtils, BancoVO; type [TEntity] [TTable('AGENCIA_BANCO')] TAgenciaBancoVO = class(TVO) private FID: Integer; FID_BANCO: Integer; FCODIGO: String; FDIGITO: String; FNOME: String; FLOGRADOURO: String; FNUMERO: String; FCEP: String; FBAIRRO: String; FMUNICIPIO: String; FUF: String; FTELEFONE: String; FGERENTE: String; FCONTATO: String; FOBSERVACAO: String; //Transientes FBancoNome: String; FBancoVO: TBancoVO; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_BANCO', 'Id Banco', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdBanco: Integer read FID_BANCO write FID_BANCO; [TColumnDisplay('BANCO.NOME', 'Banco', 150, [ldGrid, ldLookup], ftString, 'BancoVO.TBancoVO', True)] property BancoNome: String read FBancoNome write FBancoNome; [TColumn('CODIGO', 'Codigo', 80, [ldGrid, ldLookup, ldCombobox], False)] property Codigo: String read FCODIGO write FCODIGO; [TColumn('DIGITO', 'Digito', 8, [ldGrid, ldLookup, ldCombobox], False)] property Digito: String read FDIGITO write FDIGITO; [TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('LOGRADOURO', 'Logradouro', 450, [ldGrid, ldLookup, ldCombobox], False)] property Logradouro: String read FLOGRADOURO write FLOGRADOURO; [TColumn('NUMERO', 'Numero', 80, [ldGrid, ldLookup, ldCombobox], False)] property Numero: String read FNUMERO write FNUMERO; [TColumn('CEP', 'Cep', 64, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftCep, taLeftJustify)] property Cep: String read FCEP write FCEP; [TColumn('BAIRRO', 'Bairro', 450, [ldGrid, ldLookup, ldCombobox], False)] property Bairro: String read FBAIRRO write FBAIRRO; [TColumn('MUNICIPIO', 'Municipio', 450, [ldGrid, ldLookup, ldCombobox], False)] property Municipio: String read FMUNICIPIO write FMUNICIPIO; [TColumn('UF', 'Uf', 16, [ldGrid, ldLookup, ldCombobox], False)] property Uf: String read FUF write FUF; [TColumn('TELEFONE', 'Telefone', 112, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftTelefone, taLeftJustify)] property Telefone: String read FTELEFONE write FTELEFONE; [TColumn('GERENTE', 'Gerente', 240, [ldGrid, ldLookup, ldCombobox], False)] property Gerente: String read FGERENTE write FGERENTE; [TColumn('CONTATO', 'Empresa Contato', 240, [ldGrid, ldLookup, ldCombobox], False)] property Contato: String read FCONTATO write FCONTATO; [TColumn('OBSERVACAO', 'Observacao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Observacao: String read FOBSERVACAO write FOBSERVACAO; //Transientes [TAssociation('ID', 'ID_BANCO')] property BancoVO: TBancoVO read FBancoVO write FBancoVO; end; implementation constructor TAgenciaBancoVO.Create; begin inherited; FBancoVO := TBancoVO.Create; end; destructor TAgenciaBancoVO.Destroy; begin FreeAndNil(FBancoVO); inherited; end; initialization Classes.RegisterClass(TAgenciaBancoVO); finalization Classes.UnRegisterClass(TAgenciaBancoVO); end.
unit UFrmDiaog; interface uses Windows, Controls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, ImgList, StdCtrls, cxButtons, ExtCtrls, Classes, Forms, HJYDialogs, Clipbrd, ActnList; type TMessageKind = (mkSuccess, mkInformation, mkWarning, mkConfirm, mkYesOrNo, mkError); TFrmDiaog = class(TForm) pnlClient: TPanel; imgIcon: TImage; lblText: TLabel; pnlBottom: TPanel; btnOk: TcxButton; btnCancel: TcxButton; bvl1: TBevel; ilIcon: TcxImageList; actlst1: TActionList; actCopy: TAction; procedure actCopyExecute(Sender: TObject); private procedure LoadIcon(AMessageKind: TMessageKind); procedure InitMsgForm(const ACaption, AText: string; AMessageKind: TMessageKind); public class function ShowDialogForm(const ACaption, AText: string; AMessageKind: TMessageKind): Boolean; end; THJYDialog = class(TInterfacedObject, IHJYDialog) public procedure ShowSuccess(const ACaption, AText: string); procedure ShowMsg(const ACaption, AText: string); procedure ShowWarning(const ACaption, AText: string); function ShowConfirm(const ACaption, AText: string): Boolean; function ShowYesOrNo(const ACaption, AText: string): Boolean; procedure ShowError(const ACaption, AText: string); end; var FrmDiaog: TFrmDiaog; implementation {$R *.dfm} { TFrmDiaog } procedure TFrmDiaog.LoadIcon(AMessageKind: TMessageKind); begin case AMessageKind of mkSuccess: ilIcon.GetIcon(0, imgIcon.Picture.Icon); mkInformation: ilIcon.GetIcon(1, imgIcon.Picture.Icon); mkWarning: ilIcon.GetIcon(2, imgIcon.Picture.Icon); mkConfirm, mkYesOrNo: ilIcon.GetIcon(3, imgIcon.Picture.Icon); mkError: ilIcon.GetIcon(4, imgIcon.Picture.Icon); end; end; procedure TFrmDiaog.actCopyExecute(Sender: TObject); begin Clipboard.AsText := lblText.Caption; end; procedure TFrmDiaog.InitMsgForm(const ACaption, AText: string; AMessageKind: TMessageKind); begin Self.Caption := ACaption; lblText.Caption := AText; case AMessageKind of mkSuccess, mkInformation, mkWarning, mkError: begin btnCancel.Visible := False; btnOk.Left := btnCancel.Left; end; mkYesOrNo: begin btnOk.Caption := 'تا'; btnCancel.Caption := '·ٌ'; end; end; LoadIcon(AMessageKind); end; class function TFrmDiaog.ShowDialogForm(const ACaption, AText: string; AMessageKind: TMessageKind): Boolean; var lForm: TFrmDiaog; lMsgEvent: TMessageEvent; begin lForm := TFrmDiaog.Create(nil); lMsgEvent := Application.OnMessage; try Application.OnMessage := nil; lForm.InitMsgForm(ACaption, AText, AMessageKind); Result := lForm.ShowModal = mrOk; finally Application.OnMessage := lMsgEvent; lForm.Free; end; end; { THJYDialog } procedure THJYDialog.ShowSuccess(const ACaption, AText: string); begin TFrmDiaog.ShowDialogForm(ACaption, AText, mkSuccess); end; procedure THJYDialog.ShowMsg(const ACaption, AText: string); begin TFrmDiaog.ShowDialogForm(ACaption, AText, mkInformation); end; procedure THJYDialog.ShowWarning(const ACaption, AText: string); begin TFrmDiaog.ShowDialogForm(ACaption, AText, mkWarning); end; function THJYDialog.ShowConfirm(const ACaption, AText: string): Boolean; begin Result := TFrmDiaog.ShowDialogForm(ACaption, AText, mkConfirm); end; function THJYDialog.ShowYesOrNo(const ACaption, AText: string): Boolean; begin Result := TFrmDiaog.ShowDialogForm(ACaption, AText, mkYesOrNo); end; procedure THJYDialog.ShowError(const ACaption, AText: string); begin TFrmDiaog.ShowDialogForm(ACaption, AText, mkError); end; initialization HJYDialog := THJYDialog.Create; finalization HJYDialog := nil; end.
(************************************* Ext2D Engine *************************************) (* Модуль : Ext2D.pas *) (* Автор : Есин Владимир *) (* Создан : 03.11.06 *) (* Информация : Модуль является заголовочным файлом для библиотеки Ext2D Engine. *) (* Изменения : нет изменений. *) (****************************************************************************************) unit Ext2D; interface uses Windows; type { Тип результата функций } E2D_Result = Longword; { Информация об изображении } E2D_TImageInfo = packed record Width : Longword; { Выстоа } Height : Longword; { Ширина } DataSize : Longword; { Размер данных } end; { Указатель на информацию об изображении } E2D_PImageInfo = ^E2D_TImageInfo; { Информация о звуке } E2D_TSoundInfo = packed record Channels : Word; { Количество каналов } SamplesPerSec : Longword; { Частота дискретизации } BlockAlign : Word; { Блочное выравнивание } BitsPerSample : Word; { Качество } DataSize : Longword; { Размер данных } end; { Указатель на информацию о звуке } E2D_PSoundInfo = ^E2D_TSoundInfo; { Информвция о символе } E2D_TCharInfo = packed record X : Word; { Позиция по горизонтали } Y : Word; { Позиция по вертикали } Width : Word; { Ширина } end; { Информация о шрифте } E2D_TFontInfo = packed record Image : E2D_TImageInfo; { Изобоажение шрифта } Size : Longword; { Размер } CharsInfo : array [0..255] of E2D_TCharInfo; { Информация о символах } end; { Указатель на информацию о шрифте } E2D_PFontInfo = ^E2D_TFontInfo; { Тип идентификатора изображений } E2D_TImageID = Longword; { Тип идентификатора звуков } E2D_TSoundID = Longword; { Тип идентификатора шрифтов } E2D_TFontID = Longword; { Описание устройства вывода } E2D_TDeviceDesc = packed record Name : PChar; { Имя } tVidMem : Longword; { Всего видеопамяти } aVidMem : Longword; { Доступно видеопамяти } Gamma : Boolean; { Поддержка яркости } end; { Указатель на описание устройства вывода } E2D_PDeviceDesc = ^E2D_TDeviceDesc; { Яркость } E2D_TGamma = 0..256; { Цвет } E2D_TColor = Word; { Прозрачность } E2D_TAlpha = 0..256; { Громкость } E2D_TSoundVolume = -10000..0; { Панорама } E2D_TSoundPan = -10000..10000; { Кнопки мыши } E2D_TMouseButton = 0..7; { Функция для вычисления цвета пиксела } E2D_TColorCalcFunc = function (SrcColor, DstColor : E2D_TColor) : E2D_TColor; stdcall; const { Общие константы } E2DERR_OK = $00000000; { Нет ошибок } { Константы системных ошибок } E2DERR_SYSTEM_INVPOINTER = $00000101; { Неправильный указатель } E2DERR_SYSTEM_CANTGETMEM = $00000102; { Невозможно выделить память } E2DERR_SYSTEM_CANTCOPYMEM = $00000103; { Невозможно копировать память } E2DERR_SYSTEM_INVALIDID = $00000104; { Неправильный идентификатор } E2DERR_SYSTEM_SETCOOPLVL = $00000105; { Невозможно установить уровень кооперации } { Константы ошибок загрузки } E2DERR_LOAD_CANTOPEN = $00000201; { Невозможно открыть файл } E2DERR_LOAD_CANTREAD = $00000202; { Невозможно выполнить чтение из файла } E2DERR_LOAD_INVALID = $00000203; { Файл неправильный или поврежден } E2DERR_LOAD_DECOMPRESS = $00000204; { Ошибка декомпрессии } { Константы ошибок управления } E2DERR_MANAGE_OUTOFMEM = $00000301; { Недостаточно памяти массива } E2DERR_MANAGE_CREATESURF = $00000302; { Невозможно создать поверхность } E2DERR_MANAGE_CREATEBUF = $00000303; { Невозможно создать буфер } E2DERR_MANAGE_CANTLOCK = $00000304; { Невозможно заблокировать обьект } { Константы ошибок экрана } E2DERR_SCREEN_CREATEDD = $00000401; { Невозможно создать главный обьект DirectDraw } E2DERR_SCREEN_SETDISPMD = $00000402; { Невозможно установить видеорежим } E2DERR_SCREEN_GETDESCR = $00000403; { Невозможно получить описание устройства } E2DERR_SCREEN_CREATEGAM = $00000404; { Невозможно создать гамма контроль } E2DERR_SCREEN_CREATESURF = $00000405; { Невозможно создать поверхность } E2DERR_SCREEN_CANTDRAW = $00000406; { Невозможно выполнить вывод } E2DERR_SCREEN_CANTFLIP = $00000407; { Невозможно выполнить переключение } E2DERR_SCREEN_CANTCLEAR = $00000408; { Невозможно очистить буфер } E2DERR_SCREEN_CANTRESTORE = $00000409; { Невозможно восстановить поверхность } E2DERR_SCREEN_CANTSETGAM = $00000410; { Невозможно установить яркость } { Константы ошибок звука } E2DERR_SOUND_CREATEDS = $00000501; { Невозможно создать главный обьект DirectSound } E2DERR_SOUND_CANTPLAY = $00000502; { Невозможно воспроизвести звук } E2DERR_SOUND_CANTSTOP = $00000503; { Невозможно остановить звук } E2DERR_SOUND_CANTGETVOL = $00000504; { Невозможно получить громкость } E2DERR_SOUND_CANTSETVOL = $00000505; { Невозможно установить громкость } E2DERR_SOUND_CANTGETPAN = $00000506; { Невозможно получить панораму } E2DERR_SOUND_CANTSETPAN = $00000507; { Невозможно установить панораму } { Константы ошибок ввода } E2DERR_INPUT_CREATEDI = $00000601; { Невозможно создать главный обьект DirectInput } E2DERR_INPUT_CREATEDEV = $00000602; { Невозможно создать устройство } E2DERR_INPUT_SETDATAFMT = $00000603; { Невозможно задать формат данных } E2DERR_INPUT_CANTACQR = $00000604; { Невозможно захватить устройство } E2DERR_INPUT_GETSTATE = $00000605; { Невозможно получить данные } { Константы управления } E2D_MANAGE_MAXIMAGES = $10000; { Максимальное количество изображений } E2D_MANAGE_MAXSOUNDS = $10000; { Максимальное количество звуков } E2D_MANAGE_MAXFONTS = $100; { Максимальное количество шрифтов } E2D_MANAGE_DELETEALL = $0; { Удалить все } { Константы параметров экрана } E2D_SCREEN_BITSPP = $10; { Глубина цвета (бит на пиксел) } E2D_SCREEN_FRECDEF = $0; { Частота обновления монитора по умолчанию } E2D_SCREEN_COLORKEY = $0; { Цветовой ключ } { Константы звуков } E2D_SOUND_MAXVOLUME = 0; { Максимальная громкость } E2D_SOUND_MINVOLUME = -10000; { Минимальная громкость } E2D_SOUND_PANLEFT = -10000; { Баланс : слева } E2D_SOUND_PANRIGHT = 10000; { Баланс : справа } E2D_SOUND_PANCENTER = $0; { Баланс : центр } { Кнопки мыши } E2D_INPUT_MBLEFT = 0; { Левая } E2D_INPUT_MBRIGHT = 1; { Правая } E2D_INPUT_MBMIDDLE = 2; { Средняя } E2D_INPUT_MBADD1 = 3; { Дополнительная 1 } E2D_INPUT_MBADD2 = 4; { Дополнительная 2 } E2D_INPUT_MBADD3 = 5; { Дополнительная 3 } E2D_INPUT_MBADD4 = 6; { Дополнительная 4 } { Процедура для начальной инициализации. Параметры : WindowHandle : ссылка на окно приложения. } procedure E2D_InitEngine(WindowHandle : Longword); stdcall; { Процедура для удаления всех созданных обьектов и освобождения занятых ресерсов. } procedure E2D_FreeEngine; stdcall; { Функция для получения версии библиотеки Ext2D Engine. Возвращаемое значение : старший байт старшего слова - основная версия, младший байт - дополнительная версия; старший байт младшего слова - релиз, младший байт - билд. } function E2D_GetEngineVersion : Longword; stdcall; { Функция для загрузки изобоажений из файлов в память. Параметры : FileName : имя файла изображения для загрузки (*.eif файлы); ImageData : адрес буфера для сохранения данных изображения; ImageInfo : указатель на структуру E2D_TImageInfo для сохранения информации о загруженном изображении (высота, ширина, размер данных). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_LoadImage(FileName : PChar; var ImageData : Pointer; ImageInfo : E2D_PImageInfo) : E2D_Result; stdcall; { Функция для загрузки звуков из файлов в память. Параметры : FileName : имя файла звука для загрузки (*.esf файлы); SoundData : адрес буфера для сохранения данных звука; SoundInfo : указатель на структуру E2D_TSoundInfo для сохранения информации о загруженном звуке (количество каналов, частота дискретизации и другое). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_LoadSound(FileName : PChar; var SoundData : Pointer; SoundInfo : E2D_PSoundInfo) : E2D_Result; stdcall; { Функция для загрузки шрифтов из файлов в память. Параметры : FileName : имя файла шрифта для загрузки (*.eff файлы); FontData : адрес буфера для сохранения данных шрифта; FontInfo : указатель на структуру E2D_TFontInfo для сохранения информации о загруженном шрифте (размер, информация о символах и другое). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_LoadFont(FileName : PChar; var FontData : Pointer; FontInfo : E2D_PFontInfo) : E2D_Result; stdcall; { Функция для освобождения памяти, выделенной для данных изображения, звука или шрифта. Параметры : Data : адрес буфера, в котором сохранены данные изображения, звука или шрифта. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_FreeMem(var Data : Pointer) : E2D_Result; stdcall; { Функция для загрузки изображений из файлов и создания из них поверхности. Параметры : FileName : имя файла изображения для загрузки (*.eif файлы); ImageInfo : указатель на структуру E2D_TImageInfo для сохранения информации о загруженном изображении (высота, ширина, размер данных); данный параметр может быть nil, если информация не нужна; ImageID : переменная для сохранения идентификатора загруженного изображения. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddImageFromFile(FileName : PChar; ImageInfo : E2D_PImageInfo; var ImageID : E2D_TImageID) : E2D_Result; stdcall; { Функция для загрузки изображений из памяти и создания из них поверхности. Параметры : ImageData : адрес буфера, где сохранены данные изображения; ImageInfo : указатель на структуру E2D_TImageInfo, где сохранена информация об изображении (высота, ширина, размер данных); ImageID : переменная для сохранения идентификатора загруженного изображения. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddImageFromMem(ImageData : Pointer; ImageInfo : E2D_PImageInfo; var ImageID : E2D_TImageID) : E2D_Result; stdcall; { Процедура для удаления загруженных изображений. Параметры : FirstImage : идентификатор изображения, с которого необходимо начать удаление (будут удалены все изображения загруженные после данного); для удаления всех изображений данный параметр должен быть равен E2D_MANAGE_DELETEALL. } procedure E2D_DeleteImages(FirstImage : E2D_TImageID); stdcall; { Функция для получения информации о загруженном изображении. Параметры : ImageID : идентификатор изображения, информацию о котором необходимо получить; ImageInfo : указатель на структуру E2D_TImageInfo для сохранения информации (высота, ширина, размер данных). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetImageInfo(ImageID : E2D_TImageID; ImageInfo : E2D_PImageInfo) : E2D_Result; stdcall; { Функция для загрузки звуков из файлов и создания для них буферов. Параметры : FileName : имя файла звука для загрузки (*.esf файлы); SoundInfo : указатель на структуру E2D_TSoundInfo для сохранения информации о загруженном звуке (количество каналов, частота дискретизации и другое); данный параметр может быть nil, если информация не нужна; SoundID : переменная для сохранения идентификатора загруженного звука. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddSoundFromFile(FileName : PChar; SoundInfo : E2D_PSoundInfo; var SoundID : E2D_TSoundID) : E2D_Result; stdcall; { Функция для загрузки звуков из памяти и создания для них буферов. Параметры : SoundData : адрес буфера, где сохранены данные звука; SoundInfo : указатель на структуру E2D_TSoundInfo, где сохранена информация о звуке (количество каналов, частота дискретизации и другое); SoundID : переменная для сохранения идентификатора загруженного звука. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddSoundFromMem(SoundData : Pointer; SoundInfo : E2D_PSoundInfo; var SoundID : E2D_TSoundID) : E2D_Result; stdcall; { Процедура для удаления загруженных звуков. Параметры : FirstSound : идентификатор звука, с которого необходимо начать удаление (будут удалены все звуки загруженные после данного); для удаления всех звуков данный параметр должен быть равен E2D_MANAGE_DELETEALL. } procedure E2D_DeleteSounds(FirstSound : E2D_TSoundID); stdcall; { Функция для получения информации о загруженном звуке. Параметры : SoundID : идентификатор звука, информацию о котором необходимо получить; SoundInfo : указатель на структуру E2D_TSoundInfo для сохранения информации (количество каналов, частота дискретизации и другое). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetSoundInfo(SoundID : E2D_TSoundID; SoundInfo : E2D_PSoundInfo) : E2D_Result; stdcall; { Функция для загрузки шрифтов из файлов и создания из них поверхности. Параметры : FileName : имя файла шрифта для загрузки (*.eff файлы); FontInfo : указатель на структуру E2D_TFontInfo для сохранения информации о загруженном шрифте (размер, информация о символах и другое); данный параметр может быть nil, если информация не нужна; FontID : переменная для сохранения идентификатора загруженного шрифта. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddFontFromFile(FileName : PChar; FontInfo : E2D_PFontInfo; var FontID : E2D_TFontID) : E2D_Result; stdcall; { Функция для загрузки изображений из памяти и создания из них поверхности. Параметры : FontData : адрес буфера, где сохранены данные шрифта; FontInfo : указатель на структуру E2D_TFontInfo, где сохранена информация о шрифте (размер, информация о символах и другое); FontID : переменная для сохранения идентификатора загруженного шрифта. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddFontFromMem(FontData : Pointer; FontInfo : E2D_PFontInfo; var FontID : E2D_TFontID) : E2D_Result; stdcall; { Процедура для удаления загруженных шрифтов. Параметры : FirstFont : идентификатор шрифта, с которого необходимо начать удаление (будут удалены все шрифты загруженные после данного); для удаления всех шрифтов данный параметр должен быть равен E2D_MANAGE_DELETEALL. } procedure E2D_DeleteFonts(FirstFont : E2D_TFontID); stdcall; { Функция для получения информации о загруженном шрифте. Параметры : FontID : идентификатор шрифта, информацию о котором необходимо получить; FontInfo : указатель на структуру E2D_TFontInfo для сохранения информации (размер, информация о символах и другое). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetFontInfo(FontID : E2D_TFontID; FontInfo : E2D_PFontInfo) : E2D_Result; stdcall; { Функция для создания обьектов DirectDraw и перехода в полноэкранный видеорежим. Параметры : ScreenWidth : ширина экрана; ScreenHeight : высота экрана; Frec : частота обновления монитора. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_CreateFullscreen(ScreenWidth, ScreenHeight, Frec : Longword) : E2D_Result; stdcall; { Функция для получения описания утройства вывода. Параметры : Desc : указатель на структуру E2D_TDeviceDesc для сохранения описания. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetDeviceDesc(Desc : E2D_PDeviceDesc) : E2D_Result; stdcall; { Функция для вывода изображения на экран. Параметры : ImageID : идентификатор изображения, которое необходимо вывести; ImgRect : прямоугольник изображения для вывода; Place : место расположения изображения на экране. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_DrawImage(ImageID : E2D_TImageID; ImgRect : PRect; Place : PPoint) : E2D_Result; stdcall; { Функция для вывода растянутого изображения на экран. Параметры : ImageID : идентификатор изображения, которое необходимо вывести; ImgRect : прямоугольник изображения для вывода (для вывода всего изображения данный параметр может быть nil); DstRect : прямоугольник изображения на экране (для вывода изображения на весь экран данный параметр может быть nil). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_StretchDraw(ImageID : E2D_TImageID; ImgRect, DstRect : PRect) : E2D_Result; stdcall; { Функция для вывода на экран заднего буфера. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_ShowBuffer : E2D_Result; stdcall; { Функция для очистки заднего буфера. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_ClearBuffer : E2D_Result; stdcall; { Функция для восстановления поверхностей. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_RestoreSurfaces : E2D_Result; stdcall; { Функция для вывода текста. Параметры : FontID : идентификатор шрифта, которым необходимо вывести текст; Text : указатель на строку, которую необходимо вывести; X, Y : позиция текста на экране; Size : длина строки. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_DrawText(FontID : E2D_TFontID; Text : PChar; X, Y : Longword; Size : Longword) : E2D_Result; stdcall; { Функция для рисования прямоугольника. Параметры : Color : цвет прямоугольника; Rect : прямоугольник. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_DrawRect(Color : E2D_TColor; Rect : PRect) : E2D_Result; stdcall; { Функция для получения яркости экрана. Возвращаемое значение : яркость. } function E2D_GetGamma : E2D_TGamma; stdcall; { Функция для установки яркости экрана. Параметры : Gamma : яркость. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_SetGamma(Gamma : E2D_TGamma) : E2D_Result; stdcall; { Функция для установки яркости цветовых составляющих. Параметры : R, G, B : яркость красного, зеленого и синего цвета. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_SetRGBGamma(R, G, B : E2D_TGamma) : E2D_Result; stdcall; { Функция для зеркального отражения изображения. Параметры : ImageID : идентификатор изображения, которое необходимо отразить; FlipHor : отражение по горизонтали (слева направо); FlipVer : отражение по вертикали (сверху вниз). Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_FlipImage(ImageID : E2D_TImageID; FlipHor, FlipVer : Boolean) : E2D_Result; stdcall; { Функция для создания обьектов DirectSound. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_CreateSound : E2D_Result; stdcall; { Функция для воспроизведения звука. Параметры : SoundID : идентификатор звука, который необходимо воспроизвести; Loop : флаг, сигнализирующий надо ли зациклить воспроизведение. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_PlaySound(SoundID : E2D_TSoundID; Loop : Boolean) : E2D_Result; stdcall; { Функция для остановки воспроизведения звука. Параметры : SoundID : идентификатор звука, который необходимо остановить. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_StopSound(SoundID : E2D_TSoundID) : E2D_Result; stdcall; { Функция для получения громкости звука. Параметры : SoundID : идентификатор звука, громкость которго необходимо получить; Volume : переменная для сохранения громкости. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetSoundVolume(SoundID : E2D_TSoundID; var Volume : E2D_TSoundVolume) : E2D_Result; stdcall; { Функция для установления громкости звука. Параметры : SoundID : идентификатор звука, громкость которго необходимо установить; Volume : громкость. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_SetSoundVolume(SoundID : E2D_TSoundID; Volume : E2D_TSoundVolume) : E2D_Result; stdcall; { Функция для получения глобальной громкости. Возвращаемое значение : громкость. } function E2D_GetGlobalVolume : E2D_TSoundVolume; stdcall; { Функция для установления глобальной громкости. Параметры : Volume : громкость. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_SetGlobalVolume(Volume : E2D_TSoundVolume) : E2D_Result; stdcall; { Функция для получения панорамы звука. Параметры : SoundID : идентификатор звука, панораму которго необходимо получить; Pan : переменная для сохранения панорамы. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetSoundPan(SoundID : E2D_TSoundID; var Pan : E2D_TSoundPan) : E2D_Result; stdcall; { Функция для установления панорамы звука. Параметры : SoundID : идентификатор звука, панораму которго необходимо установить; Pan : панорама. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_SetSoundPan(SoundID : E2D_TSoundID; Pan : E2D_TSoundPan) : E2D_Result; stdcall; { Функция для создания обьектов DirectInput. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_CreateInput : E2D_Result; stdcall; { Функция для создания устройства клавиатуры. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddKeyboard : E2D_Result; stdcall; { Функция для создания устройства мыши. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddMouse : E2D_Result; stdcall; { Функция для обновления данных клавиатуры. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_UpdateKeyboard : E2D_Result; stdcall; { Функция для обновления данных мыши. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_UpdateMouse : E2D_Result; stdcall; { Функция для получения информации о том, нажата ли клавиша на клавиатуре. Параметры : Key : код клавиши, информацию о которой необходимо получить. Возвращаемое значение : если клавиша нажата - True, если нет - False. } function E2D_IsKeyboardKeyDown(Key : Byte) : Boolean; stdcall; { Процедура для получения позиции курсора. Параметры : CursorPos : переменная для сохранения позиции курсора. } procedure E2D_GetCursorPosition(var CursorPos : TPoint); stdcall; { Процедура для получения приращения позиции курсора. Параметры : CursorDeltas : переменная для сохранения приращений позиции курсора. } procedure E2D_GetCursorDelta(var CursorDeltas : TPoint); stdcall; { Функция для получения информации о том, нажата ли кнопка мыши. Параметры : Button : кнопка, информацию о которой необходимо получить. Возвращаемое значение : если клавиша нажата - True, если нет - False. } function E2D_IsMouseButtonDown(Button : E2D_TMouseButton) : Boolean; stdcall; { Функция для создания поверхности выбора. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_CreateSelection : E2D_Result; stdcall; { Функция для вывода изображения на поверхность выбора. Параметры : ImageID : идентификатор изображения, которое необходимо вывести; ImgRect : прямоугольник изображения для вывода; Place : место расположения изображения на поверхности выбора. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_DrawImageToSelect(ImageID : E2D_TImageID; ImgRect : PRect; Place : PPoint) : E2D_Result; stdcall; { Функция для рисования прямоугольника на поверхности выбора. Параметры : Color : цвет прямоугольника; Rect : прямоугольник. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_DrawRectToSelect(Color : E2D_TColor; Rect : PRect) : E2D_Result; stdcall; { Функция для очистки поверхности выбора. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_ClearSelect : E2D_Result; stdcall; { Функция для подготовки к выбору. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_BeginSelection : E2D_Result; stdcall; { Функция для завершения выбора. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_EndSelection : E2D_Result; stdcall; { Функция для осуществления выбора. Параметры : X, Y : координаты точки, для которой осуществляется выбор. Возвращаемое значение : цвет пиксела поверхности. } function E2D_GetSelectionVal(X, Y : Longword) : E2D_TColor; stdcall; { Функция для определения столкновения. Параметры : Image1ID, Image2ID : идентификаторы изображений, для обьектов которых необходимо определить столкновение; Place1, Place2 : место расположения изображения на экране; Collision : переменная для сохранения результата столкновения. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetCollision(Image1ID, Image2ID : E2D_TImageID; ImageRect1, ImageRect2 : PRect; Place1, Place2 : PPoint; var Collision : Boolean) : E2D_Result; stdcall; { Функция для подготовки к выводу визуальных эффектов. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_BeginEffects : E2D_Result; stdcall; { Функция для завершения вывода визуальных эффектов. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_EndEffects : E2D_Result; stdcall; { Функция для вывода прозрачного изображения на экран. Параметры : ImageID : идентификатор изображения, которое необходимо вывести; ImgRect : прямоугольник изображения для вывода; Place : место расположения изображения на экране; Alpha : коэффициент прозрачности. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_EffectBlend(ImageID : E2D_TImageID; ImgRect : PRect; Place : PPoint; Alpha : E2D_TAlpha) : E2D_Result; stdcall; { Функция для вывода прозрачного изображения на экран с использованием альфа маски. Параметры : ImageID : идентификатор изображения, которое необходимо вывести; MaskImageID : идентификатор изображения альфа маски; ImgRect : прямоугольник изображения для вывода; Place : место расположения изображения на экране; MaskPlace : место расположения изображения альфа маски. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_EffectAlphaMask(ImageID, MaskImageID : E2D_TImageID; ImgRect : PRect; Place, MaskPlace : PPoint) : E2D_Result; stdcall; { Функция для вывода изображения на экран с использованием пользовательского эффекта. Параметры : ImageID : идентификатор изображения, которое необходимо вывести; ImgRect : прямоугольник изображения для вывода; Place : место расположения изображения на экране; ColorCalc : функция для вычисления цвета пиксела. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_EffectUser(ImageID : E2D_TImageID; ImgRect : PRect; Place : PPoint; ColorCalc : E2D_TColorCalcFunc) : E2D_Result; stdcall; { Процедура для вывода на экран точки. Параметры : X, Y : место расположения точки на экране; Color : цвет точки. } procedure E2D_PutPoint(X, Y : Longword; Color : E2D_TColor); stdcall; { Функция возвращает информацию об ошибке. Параметры : ErrorCode : код возникшей ошибки. Возвращаемое значение : указатель на строку с описанием ошибки. } function E2D_ErrorString(ErrorCode : E2D_Result) : PChar; stdcall; implementation const Ext2DDLL = 'Ext2D.dll'; procedure E2D_InitEngine; external Ext2DDLL; procedure E2D_FreeEngine; external Ext2DDLL; function E2D_GetEngineVersion; external Ext2DDLL; function E2D_LoadImage; external Ext2DDLL; function E2D_LoadSound; external Ext2DDLL; function E2D_LoadFont; external Ext2DDLL; function E2D_FreeMem; external Ext2DDLL; function E2D_AddImageFromFile; external Ext2DDLL; function E2D_AddImageFromMem; external Ext2DDLL; procedure E2D_DeleteImages; external Ext2DDLL; function E2D_GetImageInfo; external Ext2DDLL; function E2D_AddSoundFromFile; external Ext2DDLL; function E2D_AddSoundFromMem; external Ext2DDLL; procedure E2D_DeleteSounds; external Ext2DDLL; function E2D_GetSoundInfo; external Ext2DDLL; function E2D_AddFontFromFile; external Ext2DDLL; function E2D_AddFontFromMem; external Ext2DDLL; procedure E2D_DeleteFonts; external Ext2DDLL; function E2D_GetFontInfo; external Ext2DDLL; function E2D_CreateFullscreen; external Ext2DDLL; function E2D_GetDeviceDesc; external Ext2DDLL; function E2D_DrawImage; external Ext2DDLL; function E2D_StretchDraw; external Ext2DDLL; function E2D_ShowBuffer; external Ext2DDLL; function E2D_ClearBuffer; external Ext2DDLL; function E2D_RestoreSurfaces; external Ext2DDLL; function E2D_DrawText; external Ext2DDLL; function E2D_DrawRect; external Ext2DDLL; function E2D_GetGamma; external Ext2DDLL; function E2D_SetGamma; external Ext2DDLL; function E2D_SetRGBGamma; external Ext2DDLL; function E2D_FlipImage; external Ext2DDLL; function E2D_CreateSound; external Ext2DDLL; function E2D_PlaySound; external Ext2DDLL; function E2D_StopSound; external Ext2DDLL; function E2D_GetSoundVolume; external Ext2DDLL; function E2D_SetSoundVolume; external Ext2DDLL; function E2D_GetGlobalVolume; external Ext2DDLL; function E2D_SetGlobalVolume; external Ext2DDLL; function E2D_GetSoundPan; external Ext2DDLL; function E2D_SetSoundPan; external Ext2DDLL; function E2D_CreateInput; external Ext2DDLL; function E2D_AddKeyboard; external Ext2DDLL; function E2D_AddMouse; external Ext2DDLL; function E2D_UpdateKeyboard; external Ext2DDLL; function E2D_UpdateMouse; external Ext2DDLL; function E2D_IsKeyboardKeyDown; external Ext2DDLL; procedure E2D_GetCursorPosition; external Ext2DDLL; procedure E2D_GetCursorDelta; external Ext2DDLL; function E2D_IsMouseButtonDown; external Ext2DDLL; function E2D_CreateSelection; external Ext2DDLL; function E2D_DrawImageToSelect; external Ext2DDLL; function E2D_DrawRectToSelect; external Ext2DDLL; function E2D_ClearSelect; external Ext2DDLL; function E2D_BeginSelection; external Ext2DDLL; function E2D_EndSelection; external Ext2DDLL; function E2D_GetSelectionVal; external Ext2DDLL; function E2D_GetCollision; external Ext2DDLL; function E2D_BeginEffects; external Ext2DDLL; function E2D_EndEffects; external Ext2DDLL; function E2D_EffectBlend; external Ext2DDLL; function E2D_EffectAlphaMask; external Ext2DDLL; function E2D_EffectUser; external Ext2DDLL; procedure E2D_PutPoint; external Ext2DDLL; function E2D_ErrorString; external Ext2DDLL; end.
unit PascalCoin.RPC.API.Operations; interface Uses System.JSON, System.Generics.Collections, PascalCoin.RPC.Interfaces, PascalCoin.RPC.API.Base; Type TPascalCoinOperationsAPI = Class(TPascalCoinAPIBase, IPascalCoinOperationsAPI) Private Protected Function payloadEncryptWithPublicKey(Const APayload: String; Const AKey: String; Const AKeyStyle: TKeyStyle): String; Function executeoperation(Const RawOperation: String): IPascalCoinOperation; Public Constructor Create(AClient: IPascalCoinRPCClient); End; implementation uses Rest.JSON, PascalCoin.RPC.Operation; { TPascalCoinOperationsAPI } constructor TPascalCoinOperationsAPI.Create(AClient: IPascalCoinRPCClient); begin inherited Create(AClient); end; function TPascalCoinOperationsAPI.executeoperation(const RawOperation: String): IPascalCoinOperation; begin If FClient.RPCCall('executeoperations', [TParamPair.Create('rawoperations', RawOperation)]) Then Begin result := TJSON.JsonToObject<TPascalCoinOperation>((GetJSONResult As TJSONObject)); End; end; function TPascalCoinOperationsAPI.payloadEncryptWithPublicKey(const APayload, AKey: String; const AKeyStyle: TKeyStyle): String; begin If FClient.RPCCall('payloadencrypt', [TParamPair.Create('payload', APayload), TParamPair.Create('payload_method', 'pubkey'), PublicKeyParam(AKey, AKeyStyle)]) Then result := GetJSONResult.AsType<String>; End; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [VENDEDOR] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit VendedorVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, ColaboradorVO; type [TEntity] [TTable('VENDEDOR')] TVendedorVO = class(TVO) private FID: Integer; FID_COLABORADOR: Integer; FCOMISSAO: Extended; FMETA_VENDAS: Extended; FTIPO_COMISSAO: String; FColaboradorVO: TColaboradorVO; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_COLABORADOR','Id Colaborador',80,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR; [TColumn('COMISSAO','Comissao',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Comissao: Extended read FCOMISSAO write FCOMISSAO; [TColumn('META_VENDAS','Meta Vendas',128,[ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property MetaVendas: Extended read FMETA_VENDAS write FMETA_VENDAS; [TColumn('TIPO_COMISSAO','Tipo Comissao',8,[ldGrid, ldLookup, ldCombobox], False)] property TipoComissao: String read FTIPO_COMISSAO write FTIPO_COMISSAO; [TAssociation('ID', 'ID_COLABORADOR')] property ColaboradorVO: TColaboradorVO read FColaboradorVO write FColaboradorVO; end; implementation constructor TVendedorVO.Create; begin inherited; FColaboradorVO := TColaboradorVO.Create; end; destructor TVendedorVO.Destroy; begin FreeAndNil(FColaboradorVO); inherited; end; initialization Classes.RegisterClass(TVendedorVO); finalization Classes.UnRegisterClass(TVendedorVO); end.
{ Тетрино Игрушка создана студентом направления Прикладная математика и информатика Карпов Денис, 2014. } unit Tetrino_Main; {$mode objfpc}{$H+} interface uses LCLType, Classes, SysUtils, FileUtil, RTTICtrls, Forms, Controls, Graphics, Dialogs, ExtCtrls, EditBtn, LResources, Tetrino_Grid; const TIMER_START_VALUE = 500; PLAYER_SCORE_FOR_GODLIKE = 18000; PLAYER_HARD_FOR_GODLIKE = 80; type TForm1 = class(TetrinoGrid) Timer1: TTimer; Timer2: TTimer; procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormPaint(Sender: TObject); procedure DrawHUD(); procedure Create_Grid(); procedure Timer1Timer(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure CheckScore(); procedure GameOver(); private { private declarations } public { public declarations } end; var Form1: TForm1; Bitmap: TBitmap; isGodlike, isPause: boolean; Start, StartPreview: tPoint; A: integer; //размер клеток поля TimeSpeed: word; PlayerScore, Lines: dword; implementation procedure TForm1.Create_Grid(); var TempPoint: tPoint; x, y: byte; begin Create_Figure(); BitMap.Canvas.Brush.Color := clBlack; BitMap.Canvas.FillRect(Canvas.ClipRect); TempPoint := Start; for y := 5 to 25 do begin for x := 1 to 10 do begin case GRID[x,y] mod 10 of 0 : BitMap.Canvas.Brush.Color := clBlack; // Empty Square 1 : BitMap.Canvas.Brush.Color := clAqua; // I 2 : BitMap.Canvas.Brush.Color := clBlue; // J 3 : BitMap.Canvas.Brush.Color := $00ffff; // L 4 : BitMap.Canvas.Brush.Color := clYellow; // O 5 : BitMap.Canvas.Brush.Color := clGreen; // S 6 : BitMap.Canvas.Brush.Color := clPurple; // T 7 : BitMap.Canvas.Brush.Color := clRed; // Z end; Bitmap.Canvas.Rectangle(round(TempPoint.x), round(TempPoint.y), round(TempPoint.x)+A, round(TempPoint.y)+A); TempPoint.x += A; end; TempPoint.x := Start.x; TempPoint.y += A; end; TempPoint := StartPreview; for y := 1 to 4 do begin for x := 1 to 4 do begin case Preview[x,y] of 0 : BitMap.Canvas.Brush.Color := clBlack; // Empty Square 1 : BitMap.Canvas.Brush.Color := clAqua; // I 2 : BitMap.Canvas.Brush.Color := clBlue; // J 3 : BitMap.Canvas.Brush.Color := $00ffff; // L 4 : BitMap.Canvas.Brush.Color := clYellow; // O 5 : BitMap.Canvas.Brush.Color := clGreen; // S 6 : BitMap.Canvas.Brush.Color := clPurple; // T 7 : BitMap.Canvas.Brush.Color := clRed; // Z end; Bitmap.Canvas.Rectangle(round(TempPoint.x), round(TempPoint.y), round(TempPoint.x)+A, round(TempPoint.y)+A); TempPoint.x += A; end; TempPoint.x := StartPreview.x; TempPoint.y += A; end; end; procedure TForm1.FormCreate(Sender: TObject); begin A := 30; Start.x := A; Start.y := A + 20; StartPreview.x := A*12; StartPreview.y := A + 70; PlayerScore := 0; isGodlike := False; isPause := False; Lines := 0; TimeSpeed := TIMER_START_VALUE; Timer1.Interval := TIMER_START_VALUE; BitMap := TBitmap.Create; BitMap.SetSize(Screen.DesktopWidth, Screen.DesktopHeight); BitMap.Canvas.Pen.Color := clGray; BitMap.Canvas.Brush.Color := clBlack; BitMap.Canvas.FillRect(Canvas.ClipRect); randomize; CurrentFigure := random(7)+1; Spawn(CurrentFigure); FutureFigure := random(7)+1; UpdatePreview(FutureFigure); end; procedure TForm1.FormPaint(Sender: TObject); begin //перерисовка изображения при изменении параметров окна Form1.Canvas.Draw(0, 0, Bitmap); end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var x, y, i, j: integer; begin if Key = VK_SPACE then begin if isGameOver() then exit; if not isPause then begin if PlayerScore > 100 then PlayerScore -= 100; PlayRezSound('Pause'); TTimer(Timer1).Enabled := False; TTimer(Timer2).Enabled := False; Bitmap.Canvas.Font.Size := 20; Bitmap.Canvas.Font.Color := clAQUA; Bitmap.Canvas.TextOut(Form1.Width div 2 - 100, Form1.Height div 2, 'PAUSED'); Form1.Canvas.Draw(0, 0, Bitmap); isPause := True; end else begin TTimer(Timer1).Enabled := True; TTimer(Timer2).Enabled := True; isPause := False; end; end; if isPause then exit; Create_Figure(); if Key = VK_RIGHT then begin i := 0; j := 0; //finding figure for x := 10 downto 1 do begin for y := 25 downto 1 do if GRID[x,y] > 10 then begin i := x; j := y; break; end; if (i = x) and (j = y) then break; end; //if not found if i + j = 0 then exit; if Check_right(i,j,GRID[i,j]) then Here.x += 1; end; if Key = VK_LEFT then begin i := 0; j := 0; //finding figure for x := 1 to 10 do begin for y := 25 downto 1 do if GRID[x,y] > 10 then begin i := x; j := y; break; end; if (i = x) and (j = y) then break; end; //if not found if i + j = 0 then exit; if Check_left(i,j,GRID[i,j]) then Here.x -= 1; end; if Key = VK_UP then begin if CurrentFigure = 1 then { === I === } if CurrentState = 1 then begin if (Here.x < 1) or (Here.x > 7) then exit; if not isClear( Here.x+4-1,Here.y+3-1, Here.x+2-1,Here.y+3-1, Here.x+1-1,Here.y+3-1, Square[3,3] ) then exit; Square[3,1] := 0; Square[3,2] := 0; Square[3,4] := 0; Square[4,3] := Square[3,3]; Square[2,3] := Square[3,3]; Square[1,3] := Square[3,3]; CurrentState := 0; exit; end else begin if (Here.x < 1) or (Here.x > 7) then exit; if not isClear( Here.x+3-1,Here.y+1-1, Here.x+3-1,Here.y+2-1, Here.x+3-1,Here.y+4-1, Square[3,3] ) then exit; Square[3,1] := Square[3,3]; Square[3,2] := Square[3,3]; Square[3,4] := Square[3,3]; Square[4,3] := 0; Square[2,3] := 0; Square[1,3] := 0; CurrentState := 1; exit; end; if CurrentFigure = 2 then { === J === } case CurrentState of 0 : begin if not isClear( Here.x+2-1,Here.y+1-1, Here.x+3-1,Here.y+1-1, Here.x+2-1,Here.y+3-1, Square[2,2] ) then exit; Square[1,1] := 0; Square[1,2] := 0; Square[3,2] := 0; Square[2,1] := Square[2,2]; Square[3,1] := Square[2,2]; Square[2,3] := Square[2,2]; CurrentState := 1; exit; end; 1 : begin if not isClear( Here.x+1-1,Here.y+2-1, Here.x+3-1,Here.y+2-1, Here.x+3-1,Here.y+3-1, Square[2,2] ) then exit; Square[2,1] := 0; Square[3,1] := 0; Square[2,3] := 0; Square[1,2] := Square[2,2]; Square[3,2] := Square[2,2]; Square[3,3] := Square[2,2]; CurrentState := 2; exit; end; 2 : begin if not isClear( Here.x+2-1,Here.y+1-1, Here.x+1-1,Here.y+3-1, Here.x+2-1,Here.y+3-1, Square[2,2] ) then exit; Square[1,2] := 0; Square[3,2] := 0; Square[3,3] := 0; Square[2,1] := Square[2,2]; Square[1,3] := Square[2,2]; Square[2,3] := Square[2,2]; CurrentState := 3; exit; end; 3 : begin if not isClear( Here.x+1-1,Here.y+1-1, Here.x+1-1,Here.y+2-1, Here.x+3-1,Here.y+2-1, Square[2,2] ) then exit; Square[2,1] := 0; Square[1,3] := 0; Square[2,3] := 0; Square[1,1] := Square[2,2]; Square[1,2] := Square[2,2]; Square[3,2] := Square[2,2]; CurrentState := 0; exit; end; end; if CurrentFigure = 3 then { === L === } case CurrentState of 0 : begin if not isClear( Here.x+2-1,Here.y+1-1, Here.x+3-1,Here.y+3-1, Here.x+2-1,Here.y+3-1, Square[2,2] ) then exit; Square[1,2] := 0; Square[3,1] := 0; Square[3,2] := 0; Square[2,1] := Square[2,2]; Square[3,3] := Square[2,2]; Square[2,3] := Square[2,2]; CurrentState := 1; exit; end; 1 : begin if not isClear( Here.x+1-1,Here.y+2-1, Here.x+3-1,Here.y+2-1, Here.x+1-1,Here.y+3-1, Square[2,2] ) then exit; Square[2,1] := 0; Square[2,3] := 0; Square[3,3] := 0; Square[1,2] := Square[2,2]; Square[3,2] := Square[2,2]; Square[1,3] := Square[2,2]; CurrentState := 2; exit; end; 2 : begin if not isClear( Here.x+2-1,Here.y+1-1, Here.x+1-1,Here.y+1-1, Here.x+2-1,Here.y+3-1, Square[2,2] ) then exit; Square[1,2] := 0; Square[3,2] := 0; Square[1,3] := 0; Square[2,1] := Square[2,2]; Square[1,1] := Square[2,2]; Square[2,3] := Square[2,2]; CurrentState := 3; exit; end; 3 : begin if not isClear( Here.x+1-1,Here.y+2-1, Here.x+3-1,Here.y+1-1, Here.x+3-1,Here.y+2-1, Square[2,2] ) then exit; Square[1,1] := 0; Square[2,1] := 0; Square[2,3] := 0; Square[1,2] := Square[2,2]; Square[3,1] := Square[2,2]; Square[3,2] := Square[2,2]; CurrentState := 0; exit; end; end; if CurrentFigure = 4 then { === O === } exit; if CurrentFigure = 5 then { === S === } case CurrentState of 0 : begin if not isClear( Here.x+1-1,Here.y+1-1, Here.x+2-1,Here.y+3-1, 1,1, Square[2,2] ) then exit; Square[2,1] := 0; Square[3,1] := 0; Square[1,1] := Square[2,2]; Square[2,3] := Square[2,2]; CurrentState := 1; exit; end; 1 : begin if not isClear( Here.x+2-1,Here.y+1-1, Here.x+3-1,Here.y+1-1, 1,1, Square[2,2] ) then exit; Square[1,1] := 0; Square[2,3] := 0; Square[2,1] := Square[2,2]; Square[3,1] := Square[2,2]; CurrentState := 0; exit; end; end; if CurrentFigure = 6 then { === T === } case CurrentState of 0 : begin if (Here.x < 1) or (Here.x > 8) then exit; if not isClear( Here.x+2-1,Here.y+3-1, 1,1, 1,1, Square[2,2] ) then exit; Square[1,2] := 0; Square[2,3] := Square[2,2]; CurrentState := 1; exit; end; 1 : begin if (Here.x < 1) or (Here.x > 8) then exit; if not isClear( Here.x+1-1,Here.y+2-1, 1,1, 1,1, Square[2,2] ) then exit; Square[2,1] := 0; Square[1,2] := Square[2,2]; CurrentState := 2; exit; end; 2 : begin if not isClear( Here.x+2-1,Here.y+1-1, 1,1, 1,1, Square[2,2] ) then exit; Square[3,2] := 0; Square[2,1] := Square[2,2]; CurrentState := 3; exit; end; 3 : begin if not isClear( Here.x+3-1,Here.y+2-1, 1,1, 1,1, Square[2,2] ) then exit; Square[2,3] := 0; Square[3,2] := Square[2,2]; CurrentState := 0; exit; end; end; if CurrentFigure = 7 then { === Z === } case CurrentState of 0 : begin if not isClear( Here.x+1-1,Here.y+2-1, Here.x+1-1,Here.y+3-1, 1,1, Square[2,2] ) then exit; Square[1,1] := 0; Square[3,2] := 0; Square[1,2] := Square[2,2]; Square[1,3] := Square[2,2]; CurrentState := 1; exit; end; 1 : begin if not isClear( Here.x+1-1,Here.y+1-1, Here.x+3-1,Here.y+2-1, 1,1, Square[2,2] ) then exit; Square[1,2] := 0; Square[1,3] := 0; Square[1,1] := Square[2,2]; Square[3,2] := Square[2,2]; CurrentState := 0; exit; end; end; end; if Key = VK_DOWN then begin Timer1.Interval := TIMER_START_VALUE div 10; end; if Key = VK_R then begin for y := 1 to 25 do for x := 1 to 10 do GRID[x,y] := 0; Spawn(FutureFigure); CurrentFigure := FutureFigure; FutureFigure := random(7)+1; UpdatePreview(FutureFigure); Lines := 0; PlayerScore := 0; TimeSpeed := TIMER_START_VALUE; Timer1.Interval := TIMER_START_VALUE; TTimer(Timer1).Enabled := True; TTimer(Timer2).Enabled := True; end; end; { ACTIONS ======= } procedure TForm1.GameOver(); begin Bitmap.Canvas.Font.Color := clRed; Bitmap.Canvas.Font.Size := 18; Bitmap.Canvas.TextOut(6*A, Form1.Height div 2, 'GAME OVER!' ); Bitmap.Canvas.Font.Size := 16; Bitmap.Canvas.TextOut(5*A, Form1.Height div 2 + 2*A, 'PRESS R TO RESTART' ); Form1.Canvas.Draw(0, 0, Bitmap); Timer1.Interval := TIMER_START_VALUE; Timer1.Enabled := False; Timer2.Enabled := False; PlayRezSound('Gameover'); end; { USER INTERFACE ============== } procedure TForm1.DrawHUD(); begin Bitmap.Canvas.Font.Color := clWhite; Bitmap.Canvas.Font.Name := 'Tahoma'; Bitmap.Canvas.Font.Size := 20; Bitmap.Canvas.Font.Style := [fsitalic, fSBold]; Bitmap.Canvas.TextOut(30, 10, 'TETRINO 2014' ); Bitmap.Canvas.TextOut(80 + 10*A, 2*A, 'NEXT:' ); Bitmap.Canvas.TextOut(70 + 10*A, 8*A + 10, 'SCORE:' ); Bitmap.Canvas.TextOut(70 + 10*A, 11*A + 10, 'LINES:' ); Bitmap.Canvas.TextOut(70 + 10*A, 14*A + 10, 'HARD:' ); Bitmap.Canvas.Font.Size := 16; Bitmap.Canvas.TextOut(60 + 11*A, 9*A + 20, IntToStr(PlayerScore) ); Bitmap.Canvas.TextOut(60 + 11*A, 12*A + 20, IntToStr(Lines) ); Bitmap.Canvas.TextOut(60 + 11*A, 15*A + 20, IntToStr( round( (TIMER_START_VALUE-TimeSpeed)/TIMER_START_VALUE*100 )) + '%'); Bitmap.Canvas.Font.Size := 10; Bitmap.Canvas.TextOut(80 + 9*A, 20*A, 'Pause - Space' ); Bitmap.Canvas.TextOut(80 + 9*A, 21*A, 'Restart - R' ); Bitmap.Canvas.TextOut(80 + 9*A, 22*A, 'Control - Arrows' ); if ((TIMER_START_VALUE-TimeSpeed)/TIMER_START_VALUE*100 > PLAYER_HARD_FOR_GODLIKE) and (PlayerScore > PLAYER_SCORE_FOR_GODLIKE) then begin if not isGodlike then begin PlayRezSound('Achievement'); isGodlike := True; end; Bitmap.Canvas.Font.Size := 20; Bitmap.Canvas.Font.Color := clYELLOW; Bitmap.Canvas.TextOut(50 + 10*A, 17*A, ' YOU''RE'); Bitmap.Canvas.TextOut(50 + 10*A, 18*A, 'GODLIKE'); end; end; { TIMERS ====== } procedure TForm1.Timer2Timer(Sender: TObject); begin Create_Grid(); DrawHUD(); Form1.Canvas.Draw(0, 0, Bitmap); end; procedure TForm1.Timer1Timer(Sender: TObject); var x, y: byte; i, j: byte; begin Create_Figure(); i := 0; j := 0; //finding figure for y := 25 downto 1 do begin for x := 1 to 10 do if GRID[x,y] > 10 then begin i := x; j := y; break; end; if (i = x) and (j = y) then break; end; //if not found if i + j = 0 then exit; //if we touched another figure OR bottom is reached if not Check(i,j,GRID[i,j]) then begin Freeze(); if isGameOver then GameOver; Timer1.Interval := TimeSpeed; CheckScore(); TimeSpeed := Timer1.Interval; Spawn(FutureFigure); CurrentFigure := FutureFigure; FutureFigure := random(7)+1; UpdatePreview(FutureFigure); end else //moving figure down HERE.y += 1; end; procedure TForm1.CheckScore(); var x, y: byte; Bool: Boolean; kombo: integer; begin y := 25; kombo := 0; while y > 5 do begin Bool := True; for x := 1 to 10 do if GRID[x,y] = 0 then begin Bool := False; break; end; if Bool then begin Inc(kombo); for x := 1 to 10 do GRID[x,y] := 0; MoveDownGrid(y); PlayerScore += (100 + (TIMER_START_VALUE-TimeSpeed))*kombo; if TimeSpeed >= 10 then begin TimeSpeed -= 10; Timer1.Interval := TimeSpeed; end; inc(Lines); PlayRezSound('Bonus'); Continue; end; Dec(y); end; end; end.
unit U_Conexao; interface uses System.Classes, Vcl.Forms, System.SysUtils, FireDAC.Comp.Client, FireDAC.Stan.Def, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.UI.Intf, FireDAC.VCLUI.Wait, FireDAC.Comp.UI; type TConexao = class(TComponent) private { private declarations } FConexao: TFDConnection; class var FInstance: TConexao; function GetConexao: TFDConnection; protected { protected declarations } public { public declarations } constructor Create(AWoner: TComponent); override; destructor Destroy; override; property Conexao: TFDConnection read GetConexao; class function GetInstance: TConexao; end; implementation { TConexao } constructor TConexao.Create(AWoner: TComponent); begin inherited Create(AWoner); FConexao := TFDConnection.Create(Self); try FConexao.LoginPrompt := False; FConexao.DriverName := 'SQLite'; FConexao.Params.Database := 'database.db'; FConexao.Connected := True; except on E: Exception do raise Exception.CreateFmt('Erro ao conectar com o banco de dados: %s', [E.Message]); end; end; destructor TConexao.Destroy; begin FConexao.Free; inherited; end; function TConexao.GetConexao: TFDConnection; begin Result := FConexao; end; class function TConexao.GetInstance: TConexao; begin if not Assigned(FInstance) then FInstance := TConexao.Create(Application); Result := FInstance; end; end.
unit MatrixTestCase; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type { TMatrix4TestCase } TMatrix4TestCase = class(TVectorBaseTestCase) protected procedure Setup; override; public {$CODEALIGN RECORDMIN=16} nmtx1,nmtx2, nmtx3 : TNativeBZMatrix4f; mtx1, mtx2, mtx3 : TBZMatrix4f; apl1 : TBZHmgPlane; npl1 : TNativeBZHmgPlane; {$CODEALIGN RECORDMIN=4} published procedure TestAddMatrix; procedure TestAddSingle; procedure TestSubMatrix; procedure TestSubSingle; procedure TestMulMatrix; procedure TestMulSingle; procedure TestMulVector; procedure TestVectorMulMatrix; procedure TestDivSingle; procedure TestMinus; procedure TestMultiply; procedure TestTranspose; procedure TestGetDeterminant; procedure TestTranslate; procedure TestInvert; procedure TestCreateLookAtMatrix; procedure TestCreateRotationMatrixXAngle; procedure TestCreateRotationMatrixXSinCos; procedure TestCreateRotationMatrixYAngle; procedure TestCreateRotationMatrixYSinCos; procedure TestCreateRotationMatrixZAngle; procedure TestCreateRotationMatrixZSinCos; procedure TestCreateRotationMatrixAxisAngle; procedure TestCreateParallelProjectionMatrix; end; implementation { TMatrix4TestCase } procedure TMatrix4TestCase.Setup; begin inherited Setup; nmtx1.V[0].Create(-2,2,-3,1); nmtx1.V[1].Create(-1,1,3,1); nmtx1.V[2].Create(2,0,-1,1); nmtx1.V[3].Create(2,2,2,1); // this should have det of -50 mtx1.M := nmtx1.M; nmtx2.CreateScaleMatrix(nt1); mtx2.CreateScaleMatrix(vt1); end; {%region%====[ TMatrixTestCase ]===============================================} procedure TMatrix4TestCase.TestAddMatrix; begin nmtx3 := nmtx1 + nmtx2; mtx3 := mtx1 + mtx2; AssertTrue('Matrix + Matrix no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestAddSingle; begin nmtx3 := nmtx1 + FS1; mtx3 := mtx1 + FS1; AssertTrue('Matrix + Single no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestSubMatrix; begin nmtx3 := nmtx1 - nmtx2; mtx3 := mtx1 - mtx2; AssertTrue('Matrix - Matrix no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestSubSingle; begin nmtx3 := nmtx1 - FS1; mtx3 := mtx1 - FS1; AssertTrue('Matrix + Single no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestMulMatrix; begin nmtx3 := nmtx1 * nmtx2; mtx3 := mtx1 * mtx2; AssertTrue('Matrix * Matrix no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestMulSingle; begin nmtx3 := nmtx1 * FS1; mtx3 := mtx1 * FS1; AssertTrue('Matrix * Single no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestMulVector; begin nt3 := nmtx1 * nt1; vt3 := mtx1 * vt1; AssertTrue('Matrix * Vector no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TMatrix4TestCase.TestVectorMulMatrix; begin nt3 := nt1 * nmtx1; vt3 := vt1 * mtx1; AssertTrue('Vector * Matrix no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TMatrix4TestCase.TestDivSingle; begin nmtx3 := nmtx1 / FS1; mtx3 := mtx1 / FS1; AssertTrue('Matrix / Single no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestMinus; begin nmtx3 := -nmtx1; mtx3 := -mtx1; AssertTrue('-Matrix no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestMultiply; begin nmtx3 := nmtx1.Multiply(nmtx2); mtx3 := mtx1.Multiply(mtx2); AssertTrue('Matrix Multiply no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestTranspose; begin nmtx3 := nmtx1.Transpose; mtx3 := mtx1.Transpose; AssertTrue('Matrix Transpose no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestGetDeterminant; begin Fs1 := nmtx1.Determinant; Fs2 := mtx1.Determinant; AssertTrue('Matrix Determinat do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2)); end; procedure TMatrix4TestCase.TestTranslate; begin nmtx3 := nmtx1.Translate(nt1); mtx3 := mtx1.Translate(vt1); AssertTrue('Matrix Translate no match'+nmtx3.ToString+' --> '+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestInvert; begin nmtx3 := nmtx1.Invert; mtx3 := mtx1.Invert; AssertTrue('Matrix Invert no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateLookAtMatrix; begin vt1.Create(0,0,10,1); // eye is a point; origin will be center up will be y nt1.V := vt1.V; nmtx3.CreateLookAtMatrix(nt1,NativeNullHmgPoint,NativeYHmgVector); // create look at matrix mtx3.CreateLookAtMatrix(vt1,NullHmgPoint,YHmgVector); // create look at matrix AssertTrue('Matrix CreateLookAtMatrix no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixXAngle; begin mtx3.CreateRotationMatrixX(pi/2); nmtx3.CreateRotationMatrixX(pi/2); AssertTrue('Matrix CreateRotationMatrixXAngle no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixXSinCos; begin mtx3.CreateRotationMatrixX(1,0); nmtx3.CreateRotationMatrixX(1,0); AssertTrue('Matrix CreateRotationMatrixXSinCos no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixYAngle; begin mtx3.CreateRotationMatrixY(pi/2); nmtx3.CreateRotationMatrixY(pi/2); AssertTrue('Matrix CreateRotationMatrixYAngle no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixYSinCos; begin mtx3.CreateRotationMatrixY(1,0); nmtx3.CreateRotationMatrixY(1,0); AssertTrue('Matrix CreateRotationMatrixYSinCos no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixZAngle; begin mtx3.CreateRotationMatrixZ(pi/2); nmtx3.CreateRotationMatrixZ(pi/2); AssertTrue('Matrix CreateRotationMatrixZAngle no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixZSinCos; begin mtx3.CreateRotationMatrixZ(1,0); nmtx3.CreateRotationMatrixZ(1,0); AssertTrue('Matrix CreateRotationMatrixZSinCos no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateRotationMatrixAxisAngle; begin mtx1.CreateRotationMatrix(ZVector,pi/2); nmtx1.CreateRotationMatrix(NativeZVector,pi/2); AssertTrue('Matrix CreateRotationMatrixAxisAngle no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; procedure TMatrix4TestCase.TestCreateParallelProjectionMatrix; begin nt1.Create(1,1,0,1); vt1.Create(1,1,0,1); apl1.Create(vt1, ZHmgVector); // create a xy plane at 0 npl1.Create(nt1, NativeZHmgVector); // create a xy plane at 0 mtx1.CreateParallelProjectionMatrix(apl1, vt1); nmtx1.CreateParallelProjectionMatrix(npl1, nt1); AssertTrue('Matrix CreateParallelProjectionMatrix no match'+#13+#10+nmtx3.ToString+#13+#10+' --> '+#13+#10+mtx3.ToString, CompareMatrix(nmtx3,mtx3)); end; {%endregion%} initialization RegisterTest(REPORT_GROUP_MATRIX4F, TMatrix4TestCase); end.
unit FormConverter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ZConnection, ZDataset, ZAbstractConnection, LCLType, Menus; type { TFrmConverter } TFrmConverter = class(TForm) btSair: TButton; btIniciar: TButton; Label1: TLabel; lbInfo: TLabel; mm: TMemo; conFB: TZConnection; conMy: TZConnection; qryCpoCALCULADO: TStringField; qryCpoCASAS_DECIMAIS: TSmallintField; qryCpoNOME_DO_CAMPO: TStringField; qryCpoOBRIGATORIO: TSmallintField; qryCpoPRECISAO: TSmallintField; qryCpoSEGMENTO: TSmallintField; qryCpoSUBTIPO: TSmallintField; qryCpoTAMANHO: TSmallintField; qryCpoTIPO: TStringField; qryCpoVALOR_PADRAO: TMemoField; qryFB: TZQuery; qryMy: TZQuery; qryTab: TZQuery; qryCpo: TZQuery; qryTabNMTAB: TStringField; procedure btIniciarClick(Sender: TObject); procedure btSairClick(Sender: TObject); procedure conFBBeforeConnect(Sender: TObject); procedure conMyBeforeConnect(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormShow(Sender: TObject); procedure qryTabAfterScroll(DataSet: TDataSet); private { private declarations } public { public declarations } procedure executarMysql(stSql: string); function abrirTabelaFB(tabela: string): Boolean; procedure incluirLinha(lin: string); function RemoveDiacritics(const Str: string): string; end; var FrmConverter: TFrmConverter; implementation {$R *.lfm} { TFrmConverter } procedure TFrmConverter.btSairClick(Sender: TObject); begin close; end; procedure TFrmConverter.btIniciarClick(Sender: TObject); var stSql, stFields, stValues: String; begin if Application.MessageBox('Iniciar Conversão?','Atenção', MB_ICONQUESTION+MB_YESNO)=mrYes then begin incluirLinha('Iniciando a conversão....'); btIniciar.Enabled:=False; qryTab.Open; while not qryTab.EOF do begin incluirLinha('Convertendo Tabela '+qryTabNMTAB.Value+'...'); executarMysql('delete from '+qryTabNMTAB.Value); stSql:='insert into '+qryTabNMTAB.Value; abrirTabelaFB(qryTabNMTAB.Value); while not qryFB.EOF do begin stValues:=') values ( '; stFields:=' ( '; qryCpo.First; while not qryCpo.EOF do begin //if qryCpoCALCULADO.Value='0' then begin DefaultFormatSettings.DecimalSeparator:='.'; stFields:=stFields+' '+qryCpoNOME_DO_CAMPO.Value; if qryFB.FieldByName(qryCpoNOME_DO_CAMPO.Value).IsNull then stValues:=stValues+'NULL' else begin if (qryCpoTIPO.Value = 'SHORT') or (qryCpoTIPO.Value = 'LONG') or (qryCpoTIPO.Value = 'INT64') then stValues:=stValues+ IntToStr(qryFB.FieldByName(qryCpoNOME_DO_CAMPO.Value).AsInteger) else if (qryCpoTIPO.Value = 'FLOAT') or (qryCpoTIPO.Value = 'DOUBLE') then stValues:=stValues+ FloatToStr(qryFB.FieldByName(qryCpoNOME_DO_CAMPO.Value).AsFloat) else if (qryCpoTIPO.Value = 'VARYING') then stValues:=stValues+ QuotedStr(qryFB.FieldByName(qryCpoNOME_DO_CAMPO.Value).AsWideString) else if (qryCpoTIPO.Value = 'DATE') then stValues:=stValues+ QuotedStr(FormatDateTime('yyyy-mm-dd',qryFB.FieldByName(qryCpoNOME_DO_CAMPO.Value).Value)) else if (qryCpoTIPO.Value = 'TIMESTAMP') then begin stValues:=stValues+ QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss',qryFB.FieldByName(qryCpoNOME_DO_CAMPO.Value).Value)); end; end; qryCpo.Next; if not qryCpo.EOF then begin stValues:=stValues+','; stFields:=stFields+','; end; DefaultFormatSettings.DecimalSeparator:=','; //end //else qryCpo.Next; end; //stSql:=stSql+stFields+stValues+')'; if qryFB.RecNo mod 1000 = 0 then incluirLinha(Format('Convertidos %d registros.',[qryFB.RecNo])); executarMysql(stSql + stFields +stValues+')'); lbInfo.Caption:=Format('Tab: %s Reg: %d',[qryTabNMTAB.Value,qryFB.RecNo]); Application.ProcessMessages; qryFB.Next; end; //ShowMessage('Fim da tabela: '+qryTabNMTAB.Value); incluirLinha(Format('Convertidos %d registros.',[qryFB.RecNo])); incluirLinha(stSql+stFields+stValues+')'); qryTab.Next; //if qryTab.RecNo = 4 then Exit; end; end; incluirLinha('Fim de Conversão!'); end; procedure TFrmConverter.conFBBeforeConnect(Sender: TObject); begin incluirLinha('Firebird Conectado!'); end; procedure TFrmConverter.conMyBeforeConnect(Sender: TObject); begin incluirLinha('MySql Conectado!'); end; procedure TFrmConverter.FormClose(Sender: TObject; var CloseAction: TCloseAction ); begin mm.Lines.SaveToFile('andamento.txt'); end; procedure TFrmConverter.FormShow(Sender: TObject); begin btIniciar.Enabled:= (conFB.Connected) and (conMy.Connected) ; end; procedure TFrmConverter.qryTabAfterScroll(DataSet: TDataSet); begin with qryCpo do begin Close; Params[0].Value:=qryTabNMTAB.Value; Open; Filtered:=True; end; end; procedure TFrmConverter.executarMysql(stSql: string); begin with qryMy do begin close; SQL.Clear; SQL.Add(stSql); try ExecSQL; except on E: Exception do begin incluirLinha('Erro Incluindo...'); incluirLinha(stSql); incluirLinha(E.Message); end; end; end; end; function TFrmConverter.abrirTabelaFB(tabela: string): Boolean; begin with qryFB do begin Close; SQL.Clear; SQL.Add('select * from '+tabela); Open; Result:=not EOF; end; end; procedure TFrmConverter.incluirLinha(lin: string); begin mm.Lines.Add(lin); end; function TFrmConverter.RemoveDiacritics(const Str: string): string; const ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇܪº'; SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU..'; var x: Integer; res: string; begin; res := ''; for x := 1 to Length(Str) do if Pos(Str[x],ComAcento) <> 0 then res := res + SemAcento[Pos(Str[x], ComAcento)] else res := res + str[x]; Result := Str; end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. } { Description: this code scans for folders containing at least two files of a known media type (mp3/avi/mpg) } unit helper_autoscan; interface uses classes,classes2,sysutils,windows,ares_types,dialogs; type TFileAttr = (ftReadOnly, ftHidden, ftSystem, ftVolumeID, ftDirectory, ftArchive, ftNormal); TFileType = set of TFileAttr; TDriveType = (dtUnknown, dtNoDrive, dtFloppy, dtFixed, dtNetwork, dtCDROM, dtRAM); type tthread_search_dir = class(TThread) protected directory:widestring; testo:string; drives:tmystringlist; child_fldrs:tmystringlist; last_update_caption:cardinal; procedure Execute; override; // procedure update; // progress +caption // procedure update_caption; // procedure check_end; function get_drives:boolean; procedure SearchTree(dir:widestring); // procedure max_progress; function is_parent_path_already_in(dir:string):boolean; // procedure add_child;//synch end; // procedure start_autoscan_folder; // procedure stop_autoscan_folder; // procedure write_prefs_autoscan; implementation uses {ufrmmain,}helper_unicode,{ufrm_settings,} helper_diskio{,helper_visual_library}; {procedure write_prefs_autoscan; var i:integer; prima_cartella:precord_cartella_share; begin prima_cartella:=nil; with frm_settings.chklstbx_shareset_auto do begin for i:=0 to items.count-1 do if checked[i] then helper_share_settings.add_this_shared_folder(prima_cartella,utf8strtowidestr(hexstr_to_bytestr(items.strings[i]))); helper_share_settings.write_to_file_shared_folders(prima_cartella); end; cancella_cartella_per_treeview2(prima_cartella); end; } {procedure stop_autoscan_folder; begin if search_dir=nil then exit; if frm_settings=nil then exit; with frm_settings do begin chklstbx_shareset_auto.items.endupdate; chklstbx_shareset_auto.enabled:=true; want_stop_autoscan:=true; btn_shareset_atuostop.enabled:=false; btn_shareset_atuostart.enabled:=true; btn_shareset_atuocheckall.enabled:=true; btn_shareset_atuoUncheckall.enabled:=true; end; end;} {procedure start_autoscan_folder; begin if search_dir<>nil then exit; want_stop_autoscan:=false; if frm_settings=nil then exit; with frm_settings do begin btn_shareset_atuostart.enabled:=false; btn_shareset_atuostop.enabled:=true; btn_shareset_atuocheckall.enabled:=false; btn_shareset_atuoUncheckall.enabled:=false; with chklstbx_shareset_auto do begin items.beginupdate; items.clear; enabled:=False; end; end; search_dir:=tthread_search_dir.create(false); end;} {procedure tthread_search_dir.update; var dira:widestring; begin if frm_settings=nil then exit; frm_settings.progbar_shareset_auto.position:=frm_settings.progbar_shareset_auto.position+1; dira:=' '+GetLangStringW(STR_SCAN_IN_PROGRESS)+': '+directory; frm_settings.lbl_shareset_auto.caption:=dira; end;} function Tthread_search_dir.get_drives:boolean; var DriveNum: Integer; DriveChar: Char; DriveType: cardinal; DriveBits: set of 0..25; str:string; begin result:=false; try seterrormode(SEM_FAILCRITICALERRORS); Integer(DriveBits) := GetLogicalDrives; for DriveNum := 0 to 25 do begin if not (DriveNum in DriveBits) then Continue; DriveChar := Char(DriveNum + Ord('a')); DriveType := GetDriveType(PChar(DriveChar + ':\')); if ((DriveType=DRIVE_FIXED) or (DriveType=DRIVE_RAMDISK) or (drivetype=DRIVE_REMOTE)) then begin str:=drivechar+':'; if setcurrentdirectory(pchar(str)) then begin drives.Add(str); result:=true; end; end; end; except end; end; {procedure tthread_search_dir.max_progress; begin if frm_settings=nil then exit; frm_settings.progbar_shareset_auto.max:=(child_fldrs.count+1)*100; end;} procedure tthread_search_dir.Execute; var dir:widestring; begin FreeOnTerminate:=false; priority:=tpnormal; drives:=tmystringlist.create; child_fldrs:=tmystringlist.create; try last_update_caption:=gettickcount; if get_drives then begin //synchronize(max_progress); while (drives.count>0) do begin dir:=utf8strtowidestr(drives.strings[0]); drives.Delete(0); child_fldrs.clear; SearchTree(dir); // synchronize(add_child); if terminated then break; end; end; except end; child_fldrs.free; drives.free; //synchronize(check_end); end; {procedure tthread_search_dir.add_child;//synch var i:integer; str:string; begin if frm_settings=nil then exit; for i:=0 to child_fldrs.count-1 do begin str:=bytestr_to_hexstr(child_fldrs.strings[i]); frm_settings.chklstbx_shareset_auto.items.add(str); end; end;} {procedure tthread_search_dir.check_end; begin if frm_settings=nil then exit; with frm_settings do begin progbar_shareset_auto.position:=progbar_shareset_auto.Max; with chklstbx_shareset_auto do begin enabled:=true; if items.count=1 then lbl_shareset_auto.caption:=' '+GetLangStringW(STR_SCAN_COMPLETED)+', 1 '+GetLangStringW(STR_DIRECTORY_FOUND) else if items.count>1 then lbl_shareset_auto.caption:=' '+GetLangStringW(STR_SCAN_COMPLETED)+', '+inttostr(items.count)+' '+GetLangStringW(STR_DIRECTORY_FOUNDS) else lbl_shareset_auto.caption:=' '+GetLangStringW(STR_SCAN_COMPLETED)+' '+GetLangStringW(STR_NO_DIR_FOUND); cursor:=crdefault; items.endupdate; end; cursor:=crdefault; btn_shareset_atuostart.enabled:=True; btn_shareset_atuostop.enabled:=false; btn_shareset_atuocheckall.enabled:=true; btn_shareset_atuoUncheckall.enabled:=true; postmessage(handle,WM_THREADSEARCHDIR_END,0,0); end; end;} {procedure tthread_search_dir.update_caption; var dira:widestring; begin try if frm_settings=nil then exit; dira:=' '+GetLangStringW(STR_SCANNING)+': '+directory; with frm_settings do begin lbl_shareset_auto.caption:=dira; with progbar_shareset_auto do begin position:=position+1; if position>=max then position:=0; end; end; if vars_global.want_stop_autoscan then terminate; except end; end;} procedure tthread_search_dir.SearchTree(dir:widestring); var SearchRec: TSearchRecW; DosError: integer; estensione:string; dira:widestring; utfname:string; num_mp3, num_avi, num_mpg:integer; begin try if gettickcount-last_update_caption>200 then begin directory:=dir; //per show caption last_update_caption:=gettickcount; // synchronize(update_caption); end; num_mp3:=0; num_avi:=0; num_mpg:=0; try DosError := helper_diskio.FindFirstW(dir+'\*.*', faAnyFile, SearchRec); while DosError = 0 do begin if terminated then exit; if (((SearchRec.attr and faDirectory) > 0) or (SearchRec.name = '.') or (SearchRec.name = '..')) then begin DosError := helper_diskio.FindNextW(SearchRec); continue; end; if searchrec.size<100000 then begin DosError := helper_diskio.FindNextW(SearchRec); continue; end; estensione:=lowercase(extractfileext(widestrtoutf8str(SearchRec.name))); if length(estensione)<2 then begin DosError := helper_diskio.FindNextW(SearchRec); continue; end; if estensione='.mp3' then inc(num_mp3) else if estensione='.avi' then inc(num_avi) else if estensione='.mpg' then inc(num_mpg) else begin DosError := helper_diskio.FindNextW(SearchRec); continue; end; if ((num_mp3>0) or (num_avi>0) or (num_mpg>0)) then begin utfname:=widestrtoutf8str(dir); if not is_parent_path_already_in(utfname) then begin child_fldrs.add(utfname); end; break; end; // fine se c'erano almeno 2 files DosError := helper_diskio.FindNextW(SearchRec); end; // fine while doserror finally helper_diskio.FindCloseW(SearchRec); end; dira:=dir; {Now that we have all the files we need, lets go to subdirectories.} try DosError := helper_diskio.FindFirstW(dir+'\*.*', faDirectory, SearchRec); while DosError = 0 do begin if terminated then exit; {If there is one, go there and search.} if (((SearchRec.attr and faDirectory) > 0) and (SearchRec.name <> '.') and (SearchRec.name <> '..') and (lowercase(SearchRec.name) <> 'winnt') and (lowercase(SearchRec.name) <> 'windows')) then begin SearchTree(dira+'\'+SearchRec.name); {Time for the recursion!} end; DosError := helper_diskio.FindNextW(SearchRec); {Look for another subdirectory} end; finally helper_diskio.FindCloseW(SearchRec); end; except end; end; {SearchTree} function tthread_search_dir.is_parent_path_already_in(dir:string):boolean; var i:integer; begin result:=false; for i:=0 to child_fldrs.count-1 do begin if length(dir)-1<length(child_fldrs.strings[i]) then continue; if dir[length(child_fldrs.strings[i])+1]<>'\' then continue; //non finisce qui vedi folder e folderR example if copy(dir,1,length(child_fldrs.strings[i]))=child_fldrs.strings[i] then begin result:=true; // se ho giÓ sottodir... break; end; end; end; end.
{$include kode.inc} unit kode_waveform; // naive // pta - phase to amplitude //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- const waveform_none = 0; waveform_const = 1; waveform_sin = 2; waveform_tri = 3; waveform_ramp = 4; waveform_saw = 5; waveform_squ = 6; waveform_noise = 7; type KWaveform = class private FType : LongInt; public constructor create; procedure setType(AType:LongInt); function process(APhase:Single) : Single; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses //math, kode_const, kode_random; //---------- constructor KWaveform.create; begin inherited; end; //---------- procedure KWaveform.setType(AType:LongInt); begin FType := AType; end; //---------- function KWaveform.process(APhase:Single) : Single; var a : single; begin result := 0; case FType of waveform_const: result := 1; waveform_sin: result := sin(APhase*KODE_PI2); waveform_tri: begin a := (APhase+0.75); a -= trunc(a); result := abs( (a*4) - 2 ) - 1; end; waveform_ramp: result := (APhase*2)-1; waveform_saw: result := 1 - (APhase*2); waveform_squ: if APhase < 0.5 then result := 1 else result := -1; waveform_noise: result := KRandomSigned; end; end; //---------------------------------------------------------------------- end.
{********************************************************** * Copyright (c) Zeljko Cvijanovic Teslic RS/BiH * www.zeljus.com * Created by: 30-8-15 19:28:32 ***********************************************************} unit AUtils; {$mode objfpc}{$H+} {$modeswitch unicodestrings} {$namespace zeljus.com.units} interface uses androidr15; type ADataType = (ftString, ftInteger, ftFloat, ftEmail); //ok function FormatFloat(aFormat: String; aValue: Real): Real; function Format(aFormat: String; aValue: Real): String; function IntToStr(aValue: jint): String; function StrToInt(aValue: String): jint; function LongToStr(aValue: jlong): String; function StrToLong(aValue: String): jlong; function FloatToStr(aValue: jfloat): String; function StrToFloat(aValue: String): jfloat; function LeftStr(Str: JLString; ch: jChar; Size: Integer): JLString; function RightStr(Str: JLString; ch: jChar; Size: Integer): JLString; function CharReplace(Str: JLString; ch: Char; ToCh: Char): String; function StrToFloat(aStr: JLString): Real; function FBDateTimeToString: JLString; //Firebird Date time function CopyFile(currentDBPath: JLString; backupDBFile: JLString): JLString; //????? function GetNextRedniBroj(PrevBroj:String; aFormat: string): JLString; function isInputTest(aValue: JLString; aFieldType: ADataType): boolean; implementation function FormatFloat(aFormat: String; aValue: Real): Real; var df: JTDecimalFormat; ds: JTDecimalFormatSymbols; begin ds:= JTDecimalFormatSymbols.Create; try ds.setDecimalSeparator(JChar('.')); ds.setGroupingSeparator(JChar(',')); df := JTDecimalFormat.create(aFormat, ds); Result := JLFloat.parseFloat(df.format(aValue).toString); except ds.setDecimalSeparator(JChar(',')); ds.setGroupingSeparator(JChar('.')); df := JTDecimalFormat.create(aFormat, ds); Result := JLFloat.parseFloat(df.format(aValue).toString); end; end; function Format(aFormat: String; aValue: Real): String; //aFormat = '#0.00' var df: JTDecimalFormat; ds: JTDecimalFormatSymbols; begin ds:= JTDecimalFormatSymbols.Create; try ds.setDecimalSeparator(JChar('.')); ds.setGroupingSeparator(JChar(',')); df := JTDecimalFormat.create(aFormat, ds); Result := df.format(aValue).toString; except ds.setDecimalSeparator(JChar(',')); ds.setGroupingSeparator(JChar('.')); df := JTDecimalFormat.create(aFormat, ds); Result :=df.format(aValue).toString; end; end; function LeftStr(Str: JLString; ch: jChar; Size: Integer): JLString; var msg: JLStringBuilder; i: integer; begin msg:= JLStringBuilder.Create(Str); for i:=0 to (Size - msg.length - 1) do msg.insert(0, ch); msg.SetLength(Size); Result := msg.toString; end; function RightStr(Str: JLString; ch: jChar; Size: Integer): JLString; var msg: JLStringBuilder; i: integer; begin msg:= JLStringBuilder.Create(Str); for i:=0 to (Size - msg.length - 1) do msg.append(ch); msg.SetLength(Size); Result := msg.toString; end; function CharReplace(Str: JLString; ch: Char; ToCh: Char): String; var msg: JLStringBuilder; i: integer; begin msg:= JLStringBuilder.Create(Str); for i:= 0 to msg.length - 1 do if msg.charAt(i) = ch then msg.setCharAt(i, toCh); Result := msg.toString; end; function StrToFloat(aStr: JLString): Real; var msg : array of jbyte; i: integer; bStr: JLString; begin msg := aStr.getBytes; bStr := ''; for i:= 0 to aStr.length - 1 do begin if Msg[i] in [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57] then bStr := bStr.concat(JLString.create(Msg[i])); end; Result := JLFloat.valueOf(bStr.trim).floatValue; end; function FBDateTimeToString: JLString; begin //'2015-12-07 16:46:40'; - Firebird format Result := JTSimpleDateFormat.create(JLString('yyyy-MM-dd HH:mm:ss')).format(JUDate.Create); end; function IntToStr(aValue: jint): String; begin Result := JLInteger.toString(aValue); end; function StrToInt(aValue: String): jint; begin Result := JLInteger.parseInt(aValue); end; function LongToStr(aValue: jlong): String; begin Result := JLLong.toString(aValue); end; function StrToLong(aValue: String): jlong; begin Result := JLLong.parseLong(aValue); end; function FloatToStr(aValue: jfloat): String; begin Result := JLFloat.toString(aValue); end; function StrToFloat(aValue: String): jfloat; begin Result := JLFloat.parseFloat(aValue); end; function CopyFile(currentDBPath: JLString; backupDBFile: JLString): JLString; var sd: JIFile; data: JIFile; currentDB: JIFile; backupDB: JIFile; src: JNCFileChannel; dst: JNCFileChannel; begin sd := AOEnvironment.getExternalStorageDirectory; data := AOEnvironment.getDataDirectory; currentDB := JIFile.create(data, currentDBPath); backupDB := JIFile.create(AOEnvironment.getExternalStoragePublicDirectory( AOEnvironment.fDIRECTORY_DOWNLOADS), backupDBFile); //odredi putanju za slanje Result := backupDB.toString; if (currentDB.exists) then begin src := JIFileInputStream.Create(currentDB).getChannel; dst:= JIFileOutputStream.Create(backupDB).getChannel; dst.transferFrom(JNCReadableByteChannel(src), 0, src.size); src.close; dst.close; end; end; function GetNextRedniBroj(PrevBroj: String; aFormat: string): JLString; var RBroj: integer; begin If Length(PrevBroj) < 5 then RBroj := 1 else try RBroj := JLInteger.ParseInt(copy(PrevBroj, 7, Length(PrevBroj))) + 1; except RBroj := 1; end; Result := ''; Result := Result.concat(JTSimpleDateFormat.create(JLString('yy')).format(JUDate.Create)).concat('/'). concat(JTSimpleDateFormat.create(JLString('MM')).format(JUDate.Create)).concat('-'); Result := Result.concat(JTDecimalFormat.create(aFormat).format(RBroj)); end; function isInputTest(aValue: JLString; aFieldType: ADataType): boolean; begin try case aFieldType of //kontrola upisa ftInteger: JLInteger.parseInt(aValue.toString); ftFloat : JLFloat.parseFloat(aValue.toString); end; Result := true; except Result := false; end; end; end.
unit DelphiExt; interface uses System.SysUtils; type EDelphiExtensions = class(Exception) end; EInvalidType = class(EDelphiExtensions) end; Tuple<T1, T2> = packed record private type PT1 = ^T1; PT2 = ^T2; public First: T1; Second: T2; function AssignAndGet1(out BindFirst: T1; out BindSecond: T2): T1; function AssignAndGet2(out BindFirst: T1; out BindSecond: T2): T2; procedure SetTuple(const pFirst: T1; const pSecond: T2); constructor MakeTuple(const pFirst: T1; const pSecond: T2); class operator Implicit(Args: array of const): Tuple<T1, T2>; end; Tuple<T1, T2, T3> = packed record private type PT1 = ^T1; PT2 = ^T2; PT3 = ^T3; public First: T1; Second: T2; Third: T3; function AssignAndGet1(out BindFirst: T1; out BindSecond: T2; BindThird: T3): T1; function AssignAndGet2(out BindFirst: T1; out BindSecond: T2; BindThird: T3): T2; function AssignAndGet3(out BindFirst: T1; out BindSecond: T2; BindThird: T3): T3; procedure SetTuple(const pFirst: T1; const pSecond: T2; const pThird: T3); constructor MakeTuple(const pFirst: T1; const pSecond: T2; const pThird: T3); class operator Implicit(Args: array of const): Tuple<T1, T2, T3>; end; implementation function Tuple<T1, T2>.AssignAndGet1(out BindFirst: T1; out BindSecond: T2): T1; begin BindFirst := First; BindSecond := Second; Result := BindFirst; end; function Tuple<T1, T2>.AssignAndGet2(out BindFirst: T1; out BindSecond: T2): T2; begin BindFirst := First; BindSecond := Second; Result := BindSecond; end; constructor Tuple<T1, T2>.MakeTuple(const pFirst: T1; const pSecond: T2); begin First := First; Second := Second; end; class operator Tuple<T1, T2>.Implicit(Args: array of const): Tuple<T1, T2>; var lT1: PT1; lT2: PT2; begin case Args[0].VType of vtInteger: lT1 := PT1(Pointer(Addr(Args[0].VInteger))); vtInt64: lT1 := PT1(Pointer(Args[0].VInt64)); vtUnicodeString: lT1 := PT1(Pointer(Addr(Args[0].VUnicodeString))); vtString: lT1 := PT1(Args[0].VString); vtBoolean: lT1 := PT1(Addr(Args[0].VBoolean)); vtExtended: lT1 := PT1(Args[0].VExtended); vtCurrency: lT1 := PT1(Args[0].VCurrency); vtInterface: lT1 := PT1(Args[0].VInterface); vtAnsiString: lT1 := PT1(Args[0].VAnsiString); vtVariant: lT1 := PT1(Args[0].VVariant); vtObject: lT1 := PT1(Args[0].VObject); else raise EInvalidType.Create('Unsupported type at index 0'); end; case Args[1].VType of vtInteger: lT2 := PT2(Pointer(Addr(Args[1].VInteger))); vtInt64: lT2 := PT2(Pointer(Args[1].VInt64)); vtUnicodeString: lT2 := PT2(Pointer(Addr(Args[1].VUnicodeString))); vtString: lT2 := PT2(Args[1].VString); vtBoolean: lT2 := PT2(Addr(Args[1].VBoolean)); vtExtended: lT2 := PT2(Args[1].VExtended); vtCurrency: lT2 := PT2(Args[1].VCurrency); vtInterface: lT2 := PT2(Args[1].VInterface); vtAnsiString: lT2 := PT2(Args[1].VAnsiString); vtVariant: lT2 := PT2(Args[1].VVariant); vtObject: lT2 := PT2(Args[1].VObject); else raise EInvalidType.Create('Unsupported type at index 1'); end; { vtChar = 2; vtPointer = 5; vtPChar = 6; vtObject = 7; vtClass = 8; vtWideChar = 9; vtPWideChar = 10; vtAnsiString = 11; vtCurrency = 12; vtVariant = 13; vtInterface = 14; vtWideString = 15; vtInt64 = 16; vtUnicodeString = 17; } Result.First := lT1^; Result.Second := lT2^; end; procedure Tuple<T1, T2>.SetTuple(const pFirst: T1; const pSecond: T2); begin First := pFirst; Second := pSecond; end; { Tuple<T1, T2, T3> } function Tuple<T1, T2, T3>.AssignAndGet1(out BindFirst: T1; out BindSecond: T2; BindThird: T3): T1; begin BindFirst := First; BindSecond := Second; BindThird := Third; Result := BindFirst; end; function Tuple<T1, T2, T3>.AssignAndGet2(out BindFirst: T1; out BindSecond: T2; BindThird: T3): T2; begin BindFirst := First; BindSecond := Second; BindThird := Third; Result := BindSecond; end; function Tuple<T1, T2, T3>.AssignAndGet3(out BindFirst: T1; out BindSecond: T2; BindThird: T3): T3; begin BindFirst := First; BindSecond := Second; BindThird := Third; Result := BindThird; end; class operator Tuple<T1, T2, T3>.Implicit(Args: array of const) : Tuple<T1, T2, T3>; var lT1: PT1; lT2: PT2; lT3: PT3; begin case Args[0].VType of vtInteger: lT1 := PT1(Pointer(Addr(Args[0].VInteger))); vtInt64: lT1 := PT1(Pointer(Args[0].VInt64)); vtUnicodeString: lT1 := PT1(Pointer(Addr(Args[0].VUnicodeString))); vtString: lT1 := PT1(Args[0].VString); vtBoolean: lT1 := PT1(Addr(Args[0].VBoolean)); vtExtended: lT1 := PT1(Args[0].VExtended); vtCurrency: lT1 := PT1(Args[0].VCurrency); vtInterface: lT1 := PT1(Args[0].VInterface); vtAnsiString: lT1 := PT1(Args[0].VAnsiString); vtVariant: lT1 := PT1(Args[0].VVariant); vtObject: lT1 := PT1(Args[0].VObject); else raise EInvalidType.Create('Unsupported type at index 0'); end; case Args[1].VType of vtInteger: lT2 := PT2(Pointer(Addr(Args[1].VInteger))); vtInt64: lT2 := PT2(Pointer(Args[1].VInt64)); vtUnicodeString: lT2 := PT2(Pointer(Addr(Args[1].VUnicodeString))); vtString: lT2 := PT2(Args[1].VString); vtBoolean: lT2 := PT2(Addr(Args[1].VBoolean)); vtExtended: lT2 := PT2(Args[1].VExtended); vtCurrency: lT2 := PT2(Args[1].VCurrency); vtInterface: lT2 := PT2(Args[1].VInterface); vtAnsiString: lT2 := PT2(Args[1].VAnsiString); vtVariant: lT2 := PT2(Args[1].VVariant); vtObject: lT2 := PT2(Args[1].VObject); else raise EInvalidType.Create('Unsupported type at index 1'); end; case Args[2].VType of vtInteger: lT3 := PT3(Pointer(Addr(Args[2].VInteger))); vtInt64: lT3 := PT3(Pointer(Args[2].VInt64)); vtUnicodeString: lT3 := PT3(Pointer(Addr(Args[2].VUnicodeString))); vtString: lT3 := PT3(Args[2].VString); vtBoolean: lT3 := PT3(Addr(Args[2].VBoolean)); vtExtended: lT3 := PT3(Args[2].VExtended); vtCurrency: lT3 := PT3(Args[2].VCurrency); vtInterface: lT3 := PT3(Args[2].VInterface); vtAnsiString: lT3 := PT3(Args[2].VAnsiString); vtVariant: lT3 := PT3(Args[2].VVariant); vtObject: lT3 := PT3(Args[2].VObject); else raise EInvalidType.Create('Unsupported type at index 2'); end; { vtChar = 2; vtPointer = 5; vtPChar = 6; vtObject = 7; vtClass = 8; vtWideChar = 9; vtPWideChar = 10; vtAnsiString = 11; vtCurrency = 12; vtVariant = 13; vtInterface = 14; vtWideString = 15; vtInt64 = 16; vtUnicodeString = 17; } Result.First := lT1^; Result.Second := lT2^; Result.Third := lT3^; end; constructor Tuple<T1, T2, T3>.MakeTuple(const pFirst: T1; const pSecond: T2; const pThird: T3); begin First := pFirst; Second := pSecond; Third := pThird; end; procedure Tuple<T1, T2, T3>.SetTuple(const pFirst: T1; const pSecond: T2; const pThird: T3); begin First := pFirst; Second := pSecond; Third := pThird; end; end.
{$mode macpas} unit Breakpoints; interface uses MacOSAll, LWPGlobals, LightBugs, UtilsTypes, FileUtils, SimpleParser, ProcessUtils, Console; type BreakpointPtr = ^BreakpointRec; BreakpointRec = record line: Longint; filename: AnsiString; next: BreakpointPtr; enabled: Boolean; brNumber: Longint; // Needed for LLDB end; procedure ToggleBreakpoint(theWind: WindowPtr; line, mods: Longint); function GetWindowBreakpoints(theWind: WindowPtr): BreakpointPtr; procedure ClearBreakpoints(editIndex: Integer); function AtLeastOneBreakPoint : boolean; // used to check if there are any breakpoints set at all procedure InitBreakpoints; // Breakpoint correction: function GetBreakpointLineFromReply(s: AnsiString; var brNumber: Longint): Longint; procedure MoveBreakpoint(line, actualLine: Longint; theWind: WindowPtr; brNumber: Longint); //procedure MoveBreakpoint(line, actualLine: Longint; theWind: WindowPtr); implementation uses LWPEdit; var gBreakpointList: array [1..kMaxEditWindows] of BreakpointPtr; // User set or reset breakpoint procedure ChangedBreakpoints(theWind: WindowPtr; line: Longint; add: Boolean; br: BreakpointPtr); var theSpec: FSSpecString; numStr: Str255; err: OSErr; s: AnsiString; actualLine: Longint; brNumber: Longint; brStr: ShortString; editIndex: Longint; begin if not BugsRunning then Exit(ChangedBreakpoints); editIndex := GetWRefCon(theWind); // Filename or full path? err := GetEditFSSpec(theWind, theSpec); if err <> noErr then Exit(ChangedBreakpoints); NumToString(line, numStr); // WriteLn('ChangedBreakpoints ', line, GetLastToken(theSpec)); // PROBLEM: Hangs if breakpoint set when running // Check if running? // (Fixed with timeout?) if gCurrentProcess <> nil then if add then begin if BugsDebuggerIsGDB then // if debugName = 'gdb' then s := ReadToPrompt(gCurrentProcess, 'break ' + GetLastToken(theSpec) + ':' + numStr, BugsGetPrompt) else // lldb s := ReadToPrompt(gCurrentProcess, 'b ' + GetLastToken(theSpec) + ':' + numStr, BugsGetPrompt); WriteLn('Breakpoint reply: '+ s); HelpAppendLn('Breakpoint reply: '+ s); // LLDB reply: // Breakpoint 2: where = test`PASCALMAIN + 119 at test.pas:38, address = 0x00011007 // Parse s to check where it REALLY ended up! // Two rows in reply, number is last in first and first in last (!) actualLine := GetBreakpointLineFromReply(s, brNumber); // if line <> actualLine then - anropa ALLTID fšr att spara brNumber! // NumToString(brNumber, brStr); // WriteLn('Breakpoint number: '+ brStr); // HelpAppendLn('Breakpoint number: '+ brStr); MoveBreakpoint(line, actualLine, theWind, brNumber); // NumToString(brNumber, numStr); // WriteLn('br move got ' + numStr); // HelpAppendLn('br move got ' + numStr); br^.brNumber := brNumber; // br^.brNumber := brNumber; Must be saved SOMEWHERE - can MoveBreakpoint do it? end else if BugsDebuggerIsGDB then begin s := ReadToPrompt(gCurrentProcess, 'clear ' + GetLastToken(theSpec) + ':' + numStr, BugsGetPrompt); end else begin // LLDB delete breakpoint! // br del NR // So what is the number? // Either save at other time, or br l and parse! NumToString(br^.brNumber, numStr); WriteLn('br del ' + numStr); HelpAppendLn('br del ' + numStr); s := ReadToPrompt(gCurrentProcess, 'br del ' + numStr, BugsGetPrompt); WriteLn('br del reply: '+ s); HelpAppendLn('br del reply: '+ s); // We don't need to dispose br since it is done by ToggleBreakpoint. end; end; // Entry point for changing breakpoints! Called from the editor window at mouse down! // We know which file, line and modifiers! procedure ToggleBreakpoint(theWind: WindowPtr; line, mods: Longint); var prev, br: BreakpointPtr; editIndex: Integer; err: OSErr; theSpec: FSSpecString; begin prev := nil; editIndex := GetWRefCon(theWind); if editIndex <= 0 then Exit(ToggleBreakpoint); if editIndex > kMaxEditWindows then Exit(ToggleBreakpoint); err := GetEditFSSpec(theWind, theSpec); // Did we click an existing (known) breakpoint? br := gBreakpointList[editIndex]; while br <> nil do begin if br^.line = line then break; prev := br; br := br^.next; end; // Now br and prev refers to the clicked and previous breakpoint. // br = nil if none is found. if mods = 0 then // Normal click (toggle) begin if br <> nil then begin // Found one! Ditch it. if prev = nil then // first gBreakpointList[editIndex] := br^.next else prev^.next := br^.next; ChangedBreakpoints(theWind, line, false, br); // Remove notification DisposePtr(Ptr(br)); end else begin br := BreakpointPtr(NewPtrClear(SizeOf(BreakPointRec))); br^.next := gBreakpointList[editIndex]; br^.line := line; br^.filename := GetLastToken(theSpec); br^.enabled := true; gBreakpointList[editIndex] := br; ChangedBreakpoints(theWind, line, true, br); // Set breakpoint notification end; end // End of normal click (toggle) else if (mods and optionKey) <> 0 then begin BugsRunTo(theWind, line); // Set temporary breakpoint and run end else if (mods and shiftKey) <> 0 then // Toggle disabled breakpoint begin if br <> nil then begin // Found one! Dis/enable it. br^.enabled := not br^.enabled; ChangedBreakpoints(theWind, line, br^.enabled, br); // Toggle breakpoint end else begin // Found none. Create it disabled. br := BreakpointPtr(NewPtrClear(SizeOf(BreakPointRec))); br^.next := gBreakpointList[editIndex]; br^.line := line; br^.filename := GetLastToken(theSpec); br^.enabled := false; gBreakpointList[editIndex] := br; ChangedBreakpoints(theWind, line, true, br); // Set breakpoint notification end; end; // TO DO: Notify debugger if it is active! end; // Hur ange fšnster? WindowPtr? Index? FSSpecString? function GetWindowBreakpoints(theWind: WindowPtr): BreakpointPtr; var editIndex: Integer; begin editIndex := GetWRefCon(theWind); if editIndex > 0 then if editIndex <= kMaxEditWindows then return gBreakpointList[editIndex]; return nil; end; procedure ClearBreakpoints(editIndex: Integer); var br, prev: BreakpointPtr; begin br := gBreakpointList[editIndex]; while br <> nil do begin prev := br; br := br^.next; DisposePtr(Ptr(prev)); end; gBreakpointList[editIndex] := nil; end; function AtLeastOneBreakPoint : boolean; var i: Longint; begin for i := 1 to kMaxEditWindows do if (gBreakpointList[i] <> nil) then return true; return false; end; procedure InitBreakpoints; var i: Longint; begin for i := 1 to kMaxEditWindows do gBreakpointList[i] := nil; end; // Correction of breakpoint positions // Expected: Something like // Breakpoint 3 at 0x1164d: file test.pas, line 11. // (gdb) // or for LLDB: // Breakpoint 2: where = test`PASCALMAIN + 119 at test.pas:38, address = 0x00011007 function GetBreakpointLineFromReply(s: AnsiString; var brNumber: Longint): Longint; var i, endpoint, line: Longint; nums: AnsiString; tokenType: Longint; tokenValue, fileName: AnsiString; begin // NEW AND BETTER PARSING! // Parse to "at" // Then branch depending on next i := 0; SimpleParserGetToken(s, i, tokenType, tokenValue); // Breakpoint if tokenValue <> 'Breakpoint' then SimpleParserGetToken(s, i, tokenType, tokenValue); // Breakpoint WriteLn('Breakpoint = ', tokenValue); HelpAppendLn('Breakpoint = ' + tokenValue); SimpleParserGetToken(s, i, tokenType, tokenValue); // number Val(tokenValue, brNumber); WriteLn('Br number ', brNumber, ' = ', tokenValue); HelpAppendLn('Br number ' + tokenValue); repeat SimpleParserGetToken(s, i, tokenType, tokenValue); until (i >= Length(s)) or (tokenValue = 'at'); SimpleParserGetToken(s, i, tokenType, tokenValue); if tokenType = kHexToken then begin // gdb SimpleParserGetToken(s, i, tokenType, tokenValue); // : SimpleParserGetToken(s, i, tokenType, tokenValue); // "file" SimpleParserGetToken(s, i, tokenType, fileName); // filename SimpleParserGetToken(s, i, tokenType, tokenValue); // , SimpleParserGetToken(s, i, tokenType, tokenValue); // "line" SimpleParserGetToken(s, i, tokenType, nums); // line number end else begin // lldb SimpleParserGetToken(s, i, tokenType, fileName); // filename SimpleParserGetToken(s, i, tokenType, tokenValue); // : SimpleParserGetToken(s, i, tokenType, nums); // line number end; if Length(nums) > 0 then Val(nums, line) else line := -1; GetBreakpointLineFromReply := line; (* if Length(s) > 3 then // probably includes prompt begin i := 1; while not (s[i] in [#13, #10]) and (i < Length(s)) do i += 1; if (i < Length(s)) and (i > 2) then begin i -= 1; if s[i] = '.' then i -= 1; // Ends with '.' after number endpoint := i; while (s[i] in ['0'..'9']) and (i > 1) do i -= 1; nums := Copy(s, i+1, endpoint - i); WriteLn('GetBreakpointLineFromReply found "', nums, '"'); WriteLn('when searching: "', s, '"'); if Length(nums) > 0 then Val(nums, line) else line := -1; GetBreakpointLineFromReply := line; end end else GetBreakpointLineFromReply := -1; *) end; procedure MoveBreakpoint(line, actualLine: Longint; theWind: WindowPtr; brNumber: Longint); var br: BreakpointPtr; r: Rect; lineStr, numStr: ShortString; begin NumToString(brNumber, numStr); NumToString(line, lineStr); WriteLn('MoveBreakpoint nr ' + numStr + ' by line ', lineStr); HelpAppendLn('MoveBreakpoint nr ' + numStr + ' by line '+ lineStr); if actualLine > 0 then if actualLine <> line then begin br := GetWindowBreakpoints(theWind); // Get the first in the list if br <> nil then // Stega igenom listan efter den med rŠtt rad! while br <> nil do begin if line = br^.line then begin br^.line := actualLine; if brNumber >= 0 then begin br^.brNumber := brNumber; WriteLn('Saved breakpoint nr ' + numStr); HelpAppendLn('Saved breakpoint nr ' + numStr); end; GetPortBounds(GetWindowPort(theWind), r); SetRect(r, 0, 0, 15, r.bottom); InvalWindowRect(theWind, r); end; br := br^.next; end; end; end; end.