text
stringlengths
14
6.51M
unit NewFrontiers.Utility.DateUtil; interface type TDateUtil = class public /// <summary> /// Gibt das Datum des nächsten Wochentags zurück (z.B. nächster /// Montag) /// </summary> /// <param name="aAusgangsdatum"> /// Ab diesem Datum wird der nächste Tag gesucht. DIe Sucher erfolgt /// inklusive des Ausgangsdatums. /// </param> class function getNextWochentag(aAusgangsdatum: TDateTime; aWochentag: Integer): TDateTime; end; implementation uses DateUtils; { TDateUtil } class function TDateUtil.getNextWochentag(aAusgangsdatum: TDateTime; aWochentag: Integer): TDateTime; begin result := aAusgangsdatum; while (DayOfTheWeek(result) <> aWochentag) do result := result +1; end; end.
unit EditTunning; interface uses StdCtrls, Graphics; type TEdit = class(StdCtrls.TEdit) private FOldColor: TColor; protected procedure DoEnter; override; { Estamos reescrevendo o método DoEnter, para adaptar de acordo com a nossa necessidade} procedure DoExit; override; { Estamos reescrevendo o método DoExit, para adaptar de acordo com a nossa necessidade} end; TDBEdit = class(StdCtrls.TEdit) private FOldColor: TColor; protected procedure DoEnter; override; { Estamos reescrevendo o método DoEnter, para adaptar de acordo com a nossa necessidade} procedure DoExit; override; { Estamos reescrevendo o método DoExit, para adaptar de acordo com a nossa necessidade} end; //Leia mais em: Mudar Cor: Edit http://www.devmedia.com.br/mudar-cor-edit/17877#ixzz2RE5G2v00 implementation { TEdit } procedure TEdit.DoEnter; begin inherited; { Observe a variável/field FOldColor, onde ela guarda a cor anterior } FOldColor := Color; { Observe neste ponto dizemos que a cor ao entrar no Edit será clYellow } Color := clYellow; end; procedure TEdit.DoExit; begin inherited; { Observe a cor agora irá receber o conteúdo da variável/field FOldColor } Color := FOldColor; end; procedure TDBEdit.DoEnter; begin inherited; { Observe a variável/field FOldColor, onde ela guarda a cor anterior } FOldColor := Color; { Observe neste ponto dizemos que a cor ao entrar no Edit será clYellow } Color := clYellow; end; procedure TDBEdit.DoExit; begin inherited; { Observe a cor agora irá receber o conteúdo da variável/field FOldColor } Color := FOldColor; end; end.
unit THX; interface uses Graph; type TFill = record Pattern : Word; Color : Byte; end; TOutLine = record LineStyle, Pattern, Thickness : Word; Color : Byte; end; PPoint = ^TPoint; PRect = ^TRect; PSquare = ^TSquare; PCaption = ^TCaption; TPoint = object x, y : Word; Procedure Assign(ax, ay : Word); Procedure Move(mx, my : Integer); Procedure Copy(p : TPoint); Function Equals(p : TPoint) : Boolean; end; TRect = object a, b : TPoint; Procedure Assign(ax, ay, bx, by : Word); Procedure Intersect(r : TRect); Procedure Move(mx, my : Integer); Procedure Grow(gx, gy : Integer); Procedure Copy(r : TRect); Procedure Union(r : TRect); Function Contains(p : TPoint) : Boolean; Function Equals(r : TRect) : Boolean; Function Empty : Boolean; end; TSquare = object(TRect) Fill : TFill; OutLine : TOutLine; Mode : Byte; Procedure Init; Procedure Draw; end; TCaption = object(TSquare) CapStr : String; TextColor : Byte; Procedure Init(iCap : String); Procedure Draw; end; const moFill = 1; moOutLine = 2; stFill : TFill = (Pattern : SolidFill; Color : Blue); stOutLine : TOutLine = (LineStyle : SolidLn; Pattern : 0; Thickness : NormWidth; Color : White); implementation Procedure TPoint.Assign; begin x := ax; y := ay end; Procedure TPoint.Move; begin Inc(x, mx); Inc(y, my) end; Function TPoint.Equals; begin Equals := (x = p.x) and (y = p.y) end; Procedure TRect.Assign; begin a.x := ax; b.x := bx; a.y := ay; b.y := by end; Procedure TPoint.Copy; begin x := p.x; y := p.y end; Procedure TRect.Intersect; var r1, r2 : PRect; pa, pb : TPoint; begin r1 := @Self; (* erstmal so annehmen *) r2 := @r; if r.a.x < a.x then begin (* wer is links ? *) r1 := @r; r2 := @Self; end; pa.Assign(r2^.a.x, r1^.a.y); (* einen Punkt von machen *) if r1^.Contains(pa) then begin (* is der Punkt auch "Links"? *) if r2^.a.y > r1^.a.y then pa.Assign(r2^.a.x, r2^.a.y) else pa.Assign(r2^.a.x, r1^.a.y); if r2^.b.x > r1^.b.x then pb.x := r1^.b.x else pb.x := r2^.b.x; if r2^.b.y > r1^.b.y then pb.y := r1^.b.y else pb.y := r2^.b.y; a.Copy(pa); b.Copy(pb) end end; Procedure TRect.Union; var pa, pb : TPoint; begin if a.x < r.a.x then pa.x := a.x else pa.x := r.a.x; if a.y < r.a.y then pa.y := a.y else pa.y := r.a.y; if b.x > r.b.x then pb.x := b.x else pb.x := r.b.x; if b.y > r.b.y then pb.y := b.y else pb.y := r.b.y; a.Copy(pa); b.Copy(pb); end; Procedure TRect.Move; begin a.Move(mx, my); b.Move(mx, my) end; Procedure TRect.Grow; begin a.Move(-gx, -gy); b.Move(gx, gy) end; Procedure TRect.Copy; begin a.Copy(r.a); b.Copy(r.b) end; Function TRect.Contains; begin Contains := (p.x >= a.x) and (p.x <= b.x) and (p.y >= a.y) and (p.y <= b.y) end; Function TRect.Equals; begin Equals := a.Equals(r.a) and b.Equals(r.b) end; Function TRect.Empty; begin Empty := a.Equals(b) end; Procedure TSquare.Init; begin Fill := stFill; OutLine := stOutLine; Mode := moFill + moOutLine; end; Procedure TSquare.Draw; begin with Fill do SetFillStyle(Pattern, Color); with OutLine do begin SetColor(Color); SetLineStyle(LineStyle, Pattern, Thickness); end; if (Mode and moFill) = moFill then Bar(a.x, a.y, b.x, b.y); if (Mode and moOutLine) = moOutLine then Rectangle(a.x, a.y, b.x, b.y); end; Procedure TCaption.Init; begin TSquare.Init; CapStr := iCap; TextColor := White; end; Procedure TCaption.Draw; begin TSquare.Draw; SetTextStyle(DefaultFont, HorizDir, 1); SetTextJustify(LeftText, Centertext); SetColor(TextColor); OutTextXY(a.x + 6, a.y + (b.y - a.y), CapStr); end; end.
unit ConverterFunctions; interface function ConvertCelsiusToFahrenheit(AValue:Extended): Extended; function ConvertFahrenheitToCelsius(AValue:Extended): Extended; function ConvertCelsiusToKelvin(AValue: Extended): Extended; function ConvertKelvinToCelsius(AValue: Extended): Extended; function ConvertFahrenheitToKelvin(AValue: Extended): Extended; function ConvertKelvinToFahrenheit(AValue: Extended): Extended; implementation // from Celsius to Celsius // Fahrenheit [F] = [C] x 9/5 + 32 [C] = ([F] - 32) x 5/9 // Kelvin [K] = [C] + 273.15 [C] = [K] - 273.15 // Rankine [R] = ([C] + 273.15) x 9/5 [C] = ([R] - 491.67) x 5/9 function ConvertCelsiusToFahrenheit(AValue:Extended): Extended; begin Result := AValue * 9 / 5 + 32; end; function ConvertFahrenheitToCelsius(AValue:Extended): Extended; begin Result := (AValue - 32) * 5/9; end; function ConvertCelsiusToKelvin(AValue:Extended): Extended; begin Result := AValue + 273.15; end; function ConvertKelvinToCelsius(AValue:Extended): Extended; begin Result := AValue - 273.15; end; function ConvertFahrenheitToKelvin(AValue:Extended): Extended; begin Result := ConvertFahrenheitToCelsius(AValue); Result := ConvertCelsiusToKelvin(Result); end; function ConvertKelvinToFahrenheit(AValue:Extended): Extended; begin Result := ConvertKelvinToCelsius(AValue); Result := ConvertCelsiusToFahrenheit(Result); end; end.
unit UContasPagarController; interface uses Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon, ConexaoBD, UPessoasVO, UController, DBClient, DB, UContasPagarVO, UPessoasController, UCondominioController, UPlanoCOntasController, UCondominioVO, UPlanoContasVO, UHistoricoVO, ULancamentoContabilVO, UEmpresaTrab; type TContasPagarController = class(TController<TContasPagarVO>) private public function ConsultarPorId(id: integer): TContasPagarVO; procedure ValidarDados(Objeto:TContasPagarVO);override; function Inserir(ContasPagar: TContasPagarVO): integer; function InserirBaixa(ContasPagar : TContasPagarVO) : integer; function RemoverBaixa(idcontapagar:integer):integer; function Excluir(ContasPagar: TContasPagarVO): boolean; function Alterar(ContasPagar: TContasPagarVO): boolean; end; implementation uses UDao, Constantes, Vcl.Dialogs; function TContasPagarController.Alterar(ContasPagar: TContasPagarVO): boolean; var Lancamentos : TObjectList<TLancamentoContabilVO>; IdContaFor, idContaDebito, idContaCredito : Integer; Lancamento : TLancamentoContabilVO; PlanoContasController : TPlanoContasCOntroller; ListaConta : TObjectList<TPlanoContasVO>; ContaPlano : TPlanoContasVO; Query : string; begin validarDados(ContasPagar); idContaFor := 0; try TDBExpress.IniciaTransacao; Result := TDAO.Alterar(ContasPagar); Lancamentos:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASPAGAR = '+inttostr(ContasPagar.idContasPagar), '',0,true); if(Lancamentos.Count>0)then begin TDAO.Excluir(Lancamentos.First); end; if(ContasPagar.IdPessoa>0)then begin PlanoContasController := TPlanoContasController.Create; Query := ' PlanoContas.idPessoa = ' +(IntTOsTR(ContasPagar.IdPessoa) + ' and PlanoContas.idCondominio = ' + IntToStr(FormEmpresaTrab.CodigoEmpLogada)); listaConta := PlanoContasController.Consultar(query); if (listaConta.Count <= 0) then begin ContasPagar.PessoaVO := TDao.ConsultarPorId<TPessoasVO>(ContasPagar.IdPessoa); contaPlano:=TPlanoContasVO.Create; ContaPlano.nrClassificacao:= '2.1.25.01'; contaplano.dsConta:= ContasPagar.PessoaVO.nome; contaplano.flTipo:= 'F'; contaPlano.idcondominio:=ContasPagar.idcondominio; contaPlano.idPessoa:= ContasPagar.IdPessoa; idcontafor:= TDAO.Inserir(contaPlano); end else idcontafor:=listaConta[0].idPlanoContas; end; if idContaFor <> 0 then idContaCredito := idContaFor; if ContasPagar.IdConta <> 0 then idContaCredito := ContasPagar.IdConta; if COntasPagar.IdContraPartida <> 0 then idContaDebito := ContasPagar.IdContraPartida; Lancamento := TLancamentoContabilVo.Create; Lancamento.idcontadebito := idContaDebito; Lancamento.idContaCredito := idContaCredito; Lancamento.complemento := COntasPagar.DsComplemento; Lancamento.dtLcto := ContasPagar.DtEmissao; Lancamento.VlValor := ContasPagar.VlValor; Lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idHistorico := ContasPagar.IdHistorico; TDao.Inserir(Lancamento); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasPagarController.ConsultarPorId(id: integer): TContasPagarVO; var P: TContasPagarVO; begin P := TDAO.ConsultarPorId<TContasPagarVO>(id); if (P <> nil) then begin p.CondominioVO := TDAO.ConsultarPorId<TCondominioVO>(P.IdCondominio); p.PessoaVO := TDAO.ConsultarPorId<TPessoasVO>(P.IdPessoa); p.PlanoContasContaVO := TDAO.ConsultarPorId<TPlanoContasVO>(P.IdConta); P.PlanoContasContraPartidaVO := TDao.ConsultarPorId<TPlanoContasVO>(P.IdContraPartida); p.HistoricoVO := TDao.ConsultarPorId<THistoricoVO>(P.IdHistorico); end; result := P; end; function TContasPagarController.Excluir(ContasPagar: TContasPagarVO): boolean; var Lancamento : TObjectList<TLancamentoContabilVO>; begin try TDBExpress.IniciaTransacao; Lancamento:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASPAGAR = '+inttostr(ContasPagar.idContasPagar), '',0,true); if(Lancamento.Count>0)then begin TDAO.Excluir(Lancamento.First); end; Result := TDAO.Excluir(ContasPagar); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasPagarController.Inserir(ContasPagar: TContasPagarVO): integer; var contaPlano:TPlanoContasVO; PessoaVo : TPessoASvo; listaConta :TObjectList<TPlanoContasVO>; Query : String; idcontafor, idcontadebito,idcontacredito:integer; PlanoContasController : TPlanoContasController; Lancamento : TLancamentoContabilVO; begin try idcontafor:=0; TDBExpress.IniciaTransacao; Result := TDAO.Inserir(ContasPagar); if(ContasPagar.IdPessoa>0)then begin PlanoContasController := TPlanoContasController.Create; Query := ' PlanoContas.idPessoa = ' +(IntTOsTR(ContasPagar.IdPessoa)+ ' and PlanoContas.idCondominio = '+ IntToStr(FormEmpresaTrab.CodigoEmpLogada)); listaConta := PlanoContasController.Consultar(query); if (listaConta.Count <= 0) then begin ContasPagar.PessoaVO := TDao.ConsultarPorId<TPessoasVO>(ContasPagar.IdPessoa); contaPlano:=TPlanoContasVO.Create; ContaPlano.nrClassificacao:= '2.1.25.01'; contaplano.dsConta:= ContasPagar.PessoaVO.nome; contaplano.flTipo:= 'F'; contaPlano.idcondominio:=ContasPagar.idcondominio; contaPlano.idPessoa:= ContasPagar.IdPessoa; idcontafor:= TDAO.Inserir(contaPlano); end else idcontafor:=listaConta[0].idPlanoContas; end; if idContaFor <> 0 then idContaCredito := idContaFor; if ContasPagar.IdConta <> 0 then idContaCredito := ContasPagar.IdConta; if COntasPagar.IdContraPartida <> 0 then idContaDebito := ContasPagar.IdContraPartida; Lancamento := TLancamentoContabilVo.Create; Lancamento.idcontadebito := idContaDebito; Lancamento.idContaCredito := idContaCredito; Lancamento.complemento := COntasPagar.DsComplemento; Lancamento.dtLcto := ContasPagar.DtEmissao; Lancamento.VlValor := ContasPagar.VlValor; Lancamento.idContasPagar := result; Lancamento.idHistorico := ContasPagar.IdHistorico; TDao.Inserir(Lancamento); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasPagarController.InserirBaixa(ContasPagar: TContasPagarVO): integer; var Lancamentos : TObjectList<TLancamentoContabilVO>; i:integer; Lancamento, lctoDesconto, lctoJurosMulta : TLancamentoContabilVO; PlanoContasController : TPlanoContasController; query : string; listaConta : TObjectList<TPlanoContasVO>; valorcredito:currency; begin TDBExpress.IniciaTransacao; try TDAO.Alterar(ContasPagar); Lancamentos:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASPAGAR = '+inttostr(ContasPagar.idContasPagar) + ' AND LANCAMENTOCONTABIL.IDBAIXA = '+inttostr(ContasPagar.idContasPagar), '',0,true); if(Lancamentos.Count>0)then begin for i:=0 to Lancamentos.Count-1 do begin TDAO.Excluir(Lancamentos[i]); end; end; Lancamento := TLancamentoContabilVo.Create; if(ContasPagar.IdPessoa>0)then begin PlanoContasController := TPlanoContasController.Create; Query := ' PlanoContas.idPessoa = ' +(IntTOsTR(ContasPagar.IdPessoa) + ' AND PLANOCONTAS.IDCONDOMINIO = ' + IntToStr(FormEmpresaTrab.CodigoEmpLogada)); listaConta := PlanoContasController.Consultar(query); if (listaConta.Count > 0) then begin Lancamento.idcontadebito := listaConta[0].idPlanoContas; end; end else Lancamento.idcontadebito := ContasPagar.idConta; Lancamento.dtLcto := ContasPagar.DtBaixa; Lancamento.VlValor := ContasPagar.VlBaixa; Lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idbaixa := ContasPagar.idContasPagar; Lancamento.idHistorico := ContasPagar.IdHistoricoBx; TDAO.Inserir(Lancamento); valorcredito:= contaspagar.VlBaixa; if(ContasPagar.VlDesconto>0)then begin LctoDesconto := TLancamentoContabilVo.Create; LctoDesconto.idContaCredito := FormEmpresaTrab.ctdescontor; LctoDesconto.dtLcto := ContasPagar.DtBaixa; LctoDesconto.VlValor := ContasPagar.vldesconto; LctoDesconto.idContasPagar := ContasPagar.idContasPagar; LctoDesconto.idBaixa:=ContasPagar.idContasPagar; valorcredito:=valorcredito-contaspagar.VlDesconto; TDao.Inserir(LctoDesconto); end; if(contaspagar.VlMulta>0)then begin lctoJurosMulta := TLancamentoContabilVo.Create; lctoJurosMulta.idcontadebito := FormEmpresaTrab.ctmultap; lctoJurosMulta.dtLcto := ContasPagar.DtBaixa; lctoJurosMulta.VlValor := ContasPagar.vlmulta; lctoJurosMulta.idContasPagar := ContasPagar.idContasPagar; lctoJurosMulta.idBaixa:=ContasPagar.idContasPagar; valorcredito:=valorcredito+ContasPagar.VlMulta; TDao.Inserir(lctoJurosMulta); end; if(contasPagar.VlJuros>0)then begin lctoJurosMulta := TLancamentoContabilVo.Create; lctoJurosMulta.idcontadebito := FormEmpresaTrab.ctjurosp; lctoJurosMulta.dtLcto := ContasPagar.DtBaixa; lctoJurosMulta.VlValor := ContasPagar.vljuros; lctoJurosMulta.idContasPagar := ContasPagar.idContasPagar; lctoJurosMulta.idBaixa:=ContasPagar.idContasPagar; valorcredito:=valorcredito+contaspagar.VlJuros; TDao.Inserir(lctoJurosMulta); end; lancamento := TLancamentoContabilVo.Create; Lancamento.dtLcto := ContasPagar.DtBaixa; Lancamento.VlValor := valorcredito; lancamento.idContaCredito := ContasPagar.IdContaBaixa; Lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idbaixa := ContasPagar.idContasPagar; TDAO.Inserir(Lancamento); {if((ContasPagar.VlDesconto>0)) then//and (ContasPagar.VlMulta = 0) and (ContasPagar.VlJuros = 0))then begin LctoDesconto := TLancamentoContabilVo.Create; lancamento := TLancamentoContabilVO.Create; LctoDesconto.idContaCredito := FormEmpresaTrab.ctdescontor; LctoDesconto.dtLcto := ContasPagar.DtBaixa; LctoDesconto.VlValor := ContasPagar.vldesconto; LctoDesconto.idContasPagar := ContasPagar.idContasPagar; LctoDesconto.idBaixa:=ContasPagar.idContasPagar; Lancamento.dtlcto := ContasPagar.dtBaixa; Lancamento.idContaCredito := ContasPagar.IdContaBaixa; Lancamento.VlValor := ContasPagar.VlBaixa - ContasPagar.VlDesconto; lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idbaixa := ContasPagar.idContasPagar; lancamento.idHistorico := ContasPagar.IdHistoricoBx; TDao.Inserir(Lancamento); TDao.Inserir(LctoDesconto); end ; if((ContasPagar.VlJuros>0)) then// and (ContasPagar.VlDesconto = 0) and (ContasPagar.VlMulta = 0))then begin lctoJurosMulta := TLancamentoContabilVo.Create; lancamento := TLancamentoContabilVO.Create; lctoJurosMulta.idcontadebito := FormEmpresaTrab.ctjurosp; lctoJurosMulta.dtLcto := ContasPagar.DtBaixa; lctoJurosMulta.VlValor := ContasPagar.vljuros; lctoJurosMulta.idContasPagar := ContasPagar.idContasPagar; lctoJurosMulta.idBaixa:=ContasPagar.idContasPagar; Lancamento.dtlcto := ContasPagar.dtBaixa; Lancamento.idContaCredito := ContasPagar.IdContaBaixa; lancamento.VlValor := ContasPagar.VlBaixa + ContasPagar.VlJuros; lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idbaixa := ContasPagar.idContasPagar; lancamento.idHistorico := ContasPagar.IdHistoricoBx; TDao.Inserir(lctoJurosMulta); TDAo.Inserir(lancamento); end; if((ContasPagar.VlMulta>0)) then//and (ContasPagar.VlJuros=0) and (ContasPagar.VlDesconto = 0))then begin lctoJurosMulta := TLancamentoContabilVo.Create; lancamento := TLancamentoContabilVO.Create; lctoJurosMulta.idcontadebito := FormEmpresaTrab.ctmultap; lctoJurosMulta.dtLcto := ContasPagar.DtBaixa; lctoJurosMulta.VlValor := ContasPagar.vlmulta; lctoJurosMulta.idContasPagar := ContasPagar.idContasPagar; lctoJurosMulta.idBaixa:=ContasPagar.idContasPagar; Lancamento.dtlcto := ContasPagar.dtBaixa; Lancamento.idContaCredito := ContasPagar.IdContaBaixa; lancamento.VlValor := ContasPagar.VlBaixa + ContasPagar.vlmulta; lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idbaixa := ContasPagar.idContasPagar; lancamento.idHistorico := ContasPagar.IdHistoricoBx; TDao.Inserir(lctoJurosMulta); TDAo.Inserir(lancamento); end; if((ContasPagar.VlMulta=0)and (ContasPagar.VlJuros=0) and (ContasPagar.VlDesconto = 0))then begin lancamento := TLancamentoContabilVo.Create; Lancamento.dtLcto := ContasPagar.DtBaixa; Lancamento.VlValor := ContasPagar.VlBaixa; lancamento.idContaCredito := ContasPagar.IdContaBaixa; Lancamento.idContasPagar := ContasPagar.idContasPagar; Lancamento.idbaixa := ContasPagar.idContasPagar; TDAO.Inserir(Lancamento); end;} TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TContasPagarController.RemoverBaixa(idcontapagar:integer): integer; var Lancamentos : TObjectList<TLancamentoContabilVO>; ContasPagar:TContasPagarVO; i:integer; begin TDBExpress.IniciaTransacao; try ContasPagar := nil; ContasPagar := self.ConsultarPorId(idcontapagar); ContasPagar.DtBaixa := 0; ContasPagar.VlBaixa := 0; ContasPagar.VlJuros := 0; ContasPagar.VlMulta := 0; ContasPagar.VlDesconto := 0; ContasPagar.IdHistoricoBx := 0; ContasPagar.IdContaBaixa := 0; ContasPagar.VlPago := 0; ContasPagar.FlBaixa := 'P'; TDAO.Alterar(ContasPagar); Lancamentos:= TDAO.Consultar<TLancamentoContabilVO>(' LANCAMENTOCONTABIL.IDCONTASPAGAR = '+inttostr(ContasPagar.idContasPagar) + ' AND LANCAMENTOCONTABIL.IDBAIXA = '+inttostr(ContasPagar.idContasPagar), '',0,true); if(Lancamentos.Count>0)then begin for i:=0 to Lancamentos.Count-1 do begin TDAO.Excluir(Lancamentos[i]); end; end; TDBEXpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; procedure TContasPagarController.ValidarDados(Objeto: TContasPagarVO); begin inherited; end; begin end.
unit Odontologia.Modelo.Producto; interface uses Data.DB, SimpleDAO, SimpleInterface, SimpleQueryFiredac, SimpleQueryRestDW, Odontologia.Modelo.Producto.Interfaces, Odontologia.Modelo.Entidades.Producto, Odontologia.Modelo.Conexion.RestDW, System.SysUtils; type TModelProducto = class (TInterfacedOBject, iModelProducto) private FEntidade : TPRODUCTO; FDAO : iSimpleDao<TPRODUCTO>; FDataSource : TDataSource; public constructor Create; destructor Destroy; override; class function New : iModelProducto; function Entidad : TPRODUCTO; function DAO : iSimpleDAO<TPRODUCTO>; function DataSource (aDataSource : TDataSource) : iModelProducto; end; implementation { TModelProducto } constructor TModelProducto.Create; begin FEntidade := TPRODUCTO.Create; FDAO := TSimpleDAO<TPRODUCTO> .New(TSimpleQueryRestDW<TPRODUCTO> .New(ModelConexion.RESTDWDataBase1)); end; function TModelProducto.DAO: iSimpleDAO<TPRODUCTO>; begin Result := FDAO; end; function TModelProducto.DataSource(aDataSource: TDataSource): iModelProducto; begin Result := Self; FDataSource := aDataSource; FDAO.DataSource(FDataSource); end; destructor TModelProducto.Destroy; begin FreeAndNil(FEntidade); inherited; end; function TModelProducto.Entidad: TPRODUCTO; begin Result := FEntidade; end; class function TModelProducto.New: iModelProducto; begin Result := Self.Create; end; end.
unit uMainRetailTransferData; interface Uses SysUtils, Variants, Classes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP, DBClient, AbBase, AbBrowse, AbZBrows, AbZipper, AbArcTyp; type TMRZipFile = class AbZipper: TAbZipper; public function ZipFile(AFile : String) : String; constructor Create; destructor Destroy; override; end; TMRFTPTransfer = class FDeleteFileAfterSend : Boolean; FZipFile : Boolean; FTP: TIdFTP; BkpFTP: TIdFTP; FTimeOut: Integer; function SendBkpFile(AFile : String):Boolean; public procedure setTimeOut(arg_value: Integer); function getTimeOut(): Integer; function SendFile(AFile : String; ASendBkp : Boolean):Boolean; constructor Create; destructor Destroy; override; end; implementation { TMRFTPTransfer } constructor TMRFTPTransfer.Create; begin FTP := TIdFTP.Create(nil); BkpFTP := TIdFTP.Create(nil); with FTP do begin Host := 'uploads.pinogy.com'; Username := '360uploads'; Password := 'x8EyMD_%'; Port := 21; end; with BkpFTP do begin Host := 'vulcan.pinogy.net'; Username := '360uploads'; Password := 'x8EyMD_%'; Port := 21; end; end; destructor TMRFTPTransfer.Destroy; begin FTP.Disconnect; BkpFTP.Disconnect; FreeAndNil(FTP); FreeAndNil(BkpFTP); inherited; inherited; end; function TMRFTPTransfer.getTimeOut: Integer; begin result := FTimeOut; end; function TMRFTPTransfer.SendBkpFile(AFile: String): Boolean; var Zip : TMRZipFile; sXMLFile, sZIPFile : String; begin Result := False; try if FileExists(AFile) then begin with BkpFTP do try Connect(True, FTimeOut); ChangeDir('Data'); if Connected then begin Put(AFile, ExtractFileName(AFile), True); Result := True; end finally Disconnect; end; end; except Result := False; end; end; function TMRFTPTransfer.SendFile(AFile: String; ASendBkp : Boolean): Boolean; var Zip : TMRZipFile; sXMLFile, sZIPFile : String; begin Result := False; try if FileExists(AFile) then begin sXMLFile := AFile; sZIPFile := ''; if FZipFile then try Zip := TMRZipFile.Create; sZIPFile := Zip.ZipFile(sXMLFile); AFile := sZIPFile; finally FreeAndNil(Zip); end; with FTP do try Connect(True, FTimeOut); if Connected then begin Put(AFile, ExtractFileName(AFile), True); Result := True; end finally Disconnect; end; if ASendBkp then SendBkpFile(AFile); end; finally if FDeleteFileAfterSend then begin if FileExists(sXMLFile) then DeleteFile(sXMLFile); if FileExists(sZIPFile) then DeleteFile(sZIPFile); end; end; end; procedure TMRFTPTransfer.setTimeOut(arg_value: Integer); begin FTimeOut := arg_value; end; { TMRZipFile } constructor TMRZipFile.Create; begin AbZipper := TAbZipper.Create(nil); end; destructor TMRZipFile.Destroy; begin FreeAndNil(AbZipper); inherited; end; function TMRZipFile.ZipFile(AFile: String): String; var fs : TFileStream; begin try Result := ChangeFileExt(AFile, '.zip'); if FileExists(Result) then DeleteFile(Result); fs := TFileStream.Create(Result, fmCreate); try finally fs.Free; end; Sleep(0); AbZipper.BaseDirectory := ExtractFileDir(Result); AbZipper.FileName := Result; AbZipper.StoreOptions := [soStripDrive,soStripPath,soRemoveDots,soReplace]; try AbZipper.AddFiles(AFile, 0); Sleep(0); AbZipper.Save; Sleep(0); finally AbZipper.CloseArchive; end; except Result := AFile; end; end; end.
unit Grafix; {$MODE Delphi} interface uses Windows; const clWhite: Longint = $00FFFFFF; clGray: Longint = $00808080; clLtGray: Longint = $00C0C0C0; procedure Line(DC: HDC; left, top, right, bottom: Integer; Color: Longint); procedure DrawBitmap(DC: HDC; Pic: HBitMap; x, y, w, h: Integer; Stretch: Boolean); procedure DrawPartOfBitmap(DC: HDC; Pic: HBitMap; x1, y1, w1, h1, x2, y2, w2, h2: Integer; Stretch: Boolean); procedure RaisedRect(DC: HDC; var R: TRect); procedure SunkRect(DC: HDC; var R: TRect); procedure CarreEffect(DC: HDC; hPic: HBITMAP; BlockX, BlockY: Integer); procedure CarreEffectThread(DC: HDC; hPic: HBITMAP; BlockX, BlockY: Integer); procedure WallpaperFill(DC: HDC; hPic: HBITMAP; Width, Height: Integer); function BitmapSize(hPic: HBITMAP): TSize; function BitmapWidth(hPic: HBITMAP): Integer; function BitmapHeight(hPic: HBITMAP): Integer; implementation procedure Line(DC: HDC; left, top, right, bottom: Integer; Color: Longint); var MyPen, OldPen: HPen; p: PPoint; begin MyPen := CreatePen(PS_Solid, 1, Color); OldPen := SelectObject(DC, MyPen); New(p); MoveToEx(DC, left, top, p); LineTo(DC, right, bottom); SelectObject(DC, OldPen); DeleteObject(MyPen); Dispose(p); end; function BitmapSize(hPic: HBITMAP): TSize; var bm: TBitmap; begin GetObject(hPic, SizeOf(bm), @bm); Result.cx := bm.bmWidth; Result.cy := bm.bmHeight; end; function BitmapWidth(hPic: HBITMAP): Integer; var bm: TBitmap; begin GetObject(hPic, SizeOf(bm), @bm); Result := bm.bmWidth; end; function BitmapHeight(hPic: HBITMAP): Integer; var bm: TBitmap; begin GetObject(hPic, SizeOf(bm), @bm); Result := bm.bmHeight; end; procedure DrawPartOfBitmap(DC: HDC; Pic: HBitMap; x1, y1, w1, h1, x2, y2, w2, h2: Integer; Stretch: Boolean); var MemDC: HDC; oldPic: HBitmap; begin MemDC := CreateCompatibleDC(DC); oldPic := SelectObject(MemDC, Pic); if Stretch then StretchBlt(DC, x2, y2, w2, h2, MemDC, x1, y1, w1, h1, SRCCOPY) else BitBlt(DC, x2, y2, w1, h1, MemDC, x1, y1, SRCCOPY); SelectObject(MemDC, oldPic); DeleteDC(MemDC); end; procedure DrawBitmap(DC: HDC; Pic: HBitMap; x, y, w, h: Integer; Stretch: Boolean); var S: TSize; begin S := BitmapSize(Pic); DrawPartOfBitmap(DC, Pic, 0, 0, S.cx, S.cy, x, y, w, h, Stretch); end; procedure RaisedRect(DC: HDC; var R: TRect); begin Line(DC, R.Left, R.Top, R.Right, R.Top, clWhite); Line(DC, R.Left, R.Top, R.Left, R.Bottom, clWhite); Line(DC, R.Right - 1, R.Top, R.Right - 1, R.Bottom, 0); Line(DC, R.Left, R.Bottom - 1, R.Right, R.Bottom - 1, 0); InflateRect(R, -1, -1); Line(DC, R.Left, R.Top, R.Right, R.Top, clLtGray); Line(DC, R.Left, R.Top, R.Left, R.Bottom, clLtGray); Line(DC, R.Right - 1, R.Top, R.Right - 1, R.Bottom, clGray); Line(DC, R.Left, R.Bottom - 1, R.Right, R.Bottom - 1, clGray); end; procedure SunkRect(DC: HDC; var R: TRect); begin Line(DC, R.Left, R.Top, R.Right, R.Top, 0); Line(DC, R.Left, R.Top, R.Left, R.Bottom, 0); Line(DC, R.Right - 1, R.Top, R.Right - 1, R.Bottom, clWhite); Line(DC, R.Left, R.Bottom - 1, R.Right, R.Bottom - 1, clWhite); InflateRect(R, -1, -1); Line(DC, R.Left, R.Top, R.Right, R.Top, clGray); Line(DC, R.Left, R.Top, R.Left, R.Bottom, clGray); Line(DC, R.Right - 1, R.Top, R.Right - 1, R.Bottom, clLtGray); Line(DC, R.Left, R.Bottom - 1, R.Right, R.Bottom - 1, clLtGray); end; type PCarreEffectParam = ^TCarreEffectParam; TCarreEffectParam = record DC: HDC; hPic: HBITMAP; BlockX: Integer; BlockY: Integer; end; function CarreEffectFun(c: PCarreEffectParam): Longint; stdcall; var x, y, BlocksFilled: Integer; w, h: Double; Blocks: array of array of Boolean; bm: TBitmap; begin GetObject(c^.hPic, SizeOf(bm), @bm); SetLength(Blocks, c^.BlockX, c^.BlockY); for y := 0 to c^.BlockY - 1 do for x := 0 to c^.BlockX - 1 do Blocks[x, y] := False; w := bm.bmWidth / c^.BlockX; h := bm.bmHeight / c^.BlockY; BlocksFilled := 0; repeat y := Random(c^.BlockY); x := Random(c^.BlockX); if not Blocks[x, y] then begin DrawPartOfBitmap(c^.DC, c^.hPic, Round(x * w), Round(y * h), Round(w), Round(h), Round(x * w), Round(y * h), 0, 0, False); Blocks[x, y] := True; Inc(BlocksFilled); end; until BlocksFilled = c^.BlockX * c^.BlockY; Result := 0; Dispose(c); end; procedure CarreEffect(DC: HDC; hPic: HBITMAP; BlockX, BlockY: Integer); var param: PCarreEffectParam; begin New(param); param^.DC := DC; param^.hPic := hPic; param^.BlockX := BlockX; param^.BlockY := BlockY; CarreEffectFun(param); end; procedure CarreEffectThread(DC: HDC; hPic: HBITMAP; BlockX, BlockY: Integer); var ThreadID: DWORD; param: PCarreEffectParam; begin New(param); param^.DC := DC; param^.hPic := hPic; param^.BlockX := BlockX; param^.BlockY := BlockY; CreateThread(nil, 0, @CarreEffectFun, param, 0, ThreadID); end; procedure WallpaperFill(DC: HDC; hPic: HBITMAP; Width, Height: Integer); var S: TSize; x, y: Integer; begin S := BitmapSize(hPic); x := 0; y := 0; repeat repeat DrawBitmap(DC, hPic, x, y, 0, 0, False); x := x + S.cx; until x >= Width; x := 0; y := y + S.cy; until y >= Height; end; procedure SlideImage(DC: HDC; hPic: HBITMAP; x1, y1, x2, y2: Integer); begin end; end.
unit guiPassWord; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, siComp, siLngLnk; type TPasswordDlg = class(TForm) Label1: TLabel; EditUser: TEdit; OKBtn: TButton; CancelBtn: TButton; EditPwd: TEdit; Label2: TLabel; EditNewPwd: TEdit; EditNewPwd2: TEdit; Label3: TLabel; Label4: TLabel; siLangLinked_PasswordDlg: TsiLangLinked; private { Private declarations } public function getUser: string; function getPwd: string; function getNewPwd: string; function getNewPwd2: string; end; { var PasswordDlg: TPasswordDlg; } implementation {$R *.dfm} { TPasswordDlg } function TPasswordDlg.getUser : string; begin result := EditUser .Text end; function TPasswordDlg.getPwd : string; begin result := EditPwd .Text end; function TPasswordDlg.getNewPwd : string; begin result := EditNewPwd .Text end; function TPasswordDlg.getNewPwd2: string; begin result := EditNewPwd2.Text end; end.
unit frmOperationMapMachineModel; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, ComCtrls, ImgList, cxControls, cxContainer, cxTreeView; type TOperationMapMachineModelForm = class(TForm) grp1: TGroupBox; cbbOperationList: TComboBox; btnRefresh: TSpeedButton; btnDelete: TSpeedButton; btnExit: TSpeedButton; btnSave: TSpeedButton; btnAdd: TSpeedButton; ImageList2: TImageList; A: TPanel; tvColorList: TcxTreeView; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnRefreshClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure cbbOperationListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure Add; { Private declarations } public { Public declarations } end; var OperationMapMachineModelForm: TOperationMapMachineModelForm; implementation uses ServerDllPub, uFNMResource ,uDictionary, uShowMessage, uLogin, uGlobal; {$R *.dfm} procedure TOperationMapMachineModelForm.FormCreate(Sender: TObject); begin btnRefresh.Glyph.LoadFromResourceName(HInstance, RES_REFRESH); btnAdd.Glyph.LoadFromResourceName(HInstance, RES_LEFT); btnDelete.Glyph.LoadFromResourceName(HInstance, RES_DELETE); btnSave.Glyph.LoadFromResourceName(HInstance, RES_SAVE); btnExit.Glyph.LoadFromResourceName(HInstance, RES_EXIT); (cbbOperationList as TControl).Align:=alClient; TGlobal.FillComboBoxFromDataSet(Dictionary.cds_OperationHdrList,'Operation_Code', 'Operation_CHN','--',cbbOperationList); end; procedure TOperationMapMachineModelForm.FormDestroy(Sender: TObject); begin OperationMapMachineModelForm := nil; end; procedure TOperationMapMachineModelForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TOperationMapMachineModelForm.btnRefreshClick(Sender: TObject); var vData: OleVariant; sCondition,sErrorMsg: WideString; MachineModel: string; Node: TTreeNode; i: Integer; begin inherited; sCondition := QuotedStr('')+','+ QuotedStr('')+',0'; FNMServerObj.GetQueryData(vData,'SaveOperationMapMachineModel',sCondition,sErrorMsg); if sErrorMsg<>'' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; TempClientDataSet.Data:=vData; MachineModel := ''; tvColorList.Items.Clear; Node := nil; i := 0 ; tvColorList.Items.BeginUpdate; with TempClientDataSet do begin First; while not Eof do begin if MachineModel <> FieldByName('Machine_Model').AsString then begin if (i<>0) and (Node <> nil) then begin Node.Data := pointer(i); Node.Text := Node.Text + '¡¾'+IntToStr(Integer(Node.Data))+'¡¿'; i := 0; end; MachineModel := FieldByName('Machine_Model').AsString; Node := tvColorList.Items.AddChild(nil,MachineModel); Node.ImageIndex := 0; Node.SelectedIndex := 1; end; with tvColorList.Items.AddChild(Node,FieldByName('Operation_Code').AsString) do begin inc(i); ImageIndex := 2; SelectedIndex := 2; end; Next; if Eof then begin Node.Data := pointer(i); Node.Text := Node.Text + '¡¾'+IntToStr(Integer(Node.Data))+'¡¿'; end; end; end; tvColorList.Items.EndUpdate; end; procedure TOperationMapMachineModelForm.btnAddClick(Sender: TObject); begin Add; end; procedure TOperationMapMachineModelForm.Add; var Node: TTreeNode; begin if tvColorList.Selected = nil then Exit; if cbbOperationList.ItemIndex = -1 then Exit; Node := tvColorList.Selected; if tvColorList.Selected.Level = 1 then Node := tvColorList.Selected.Parent; with tvColorList.Items.AddChild(Node,cbbOperationList.Text) do begin ImageIndex := 2; SelectedIndex := 2; end; end; procedure TOperationMapMachineModelForm.btnDeleteClick(Sender: TObject); begin if tvColorList.Selected = nil then Exit; if tvColorList.Selected.Level = 0 then Exit; tvColorList.Items.Delete(tvColorList.Selected); end; procedure TOperationMapMachineModelForm.btnSaveClick(Sender: TObject); var sCondition,sErrorMsg: WideString; MachineModelStr,OperationCodeStr: string; ATreeNode: TTreeNode; i: Integer; begin inherited; MachineModelStr :=''; OperationCodeStr := ''; ATreeNode:=tvColorList.Items.GetFirstNode; while ATreeNode<>nil do begin if not ATreeNode.HasChildren then begin MachineModelStr := MachineModelStr + Copy(ATreeNode.Parent.Text,1,2) +','; OperationCodeStr := OperationCodeStr + Copy(ATreeNode.Text,1,3) +','; end; ATreeNode:=ATreeNode.GetNext; end; sCondition := QuotedStr(MachineModelStr)+','+ QuotedStr(OperationCodeStr)+',1'; FNMServerObj.SaveDataBySQL('SaveOperationMapMachineModel',sCondition,sErrorMsg); if sErrorMsg<>'' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; end; procedure TOperationMapMachineModelForm.btnExitClick(Sender: TObject); begin Close; end; procedure TOperationMapMachineModelForm.FormActivate(Sender: TObject); begin btnRefreshcLICK(SELF); end; procedure TOperationMapMachineModelForm.cbbOperationListKeyDown( Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=13 then add; end; end.
unit ProdutoOperacaoConsultar.Controller; interface uses Produto.Controller.interf, Produto.Model.interf, TESTPRODUTO.Entidade.Model, System.SysUtils; type TProdutoOperacaoConsultarController = class(TInterfacedObject, IProdutoOperacaoConsultarController) private FProdutoController: IProdutoController; FProdutoModel: IProdutoModel; FRegistro: TTESTPRODUTO; public constructor Create; destructor Destroy; override; class function New: IProdutoOperacaoConsultarController; function produtoController(AValue: IProdutoController) : IProdutoOperacaoConsultarController; function produtoModel(AValue: IProdutoModel) : IProdutoOperacaoConsultarController; function localizar(AValue: string): IProdutoOperacaoConsultarController; function codigoSinapi: string; function descricao: string; function unidMedida: string; function prMedioSinapi: string; function &end: IProdutoController; end; implementation { TProdutoOperacaoConsultarController } function TProdutoOperacaoConsultarController.codigoSinapi: string; begin Result := IntToStr(FRegistro.CODIGO_SINAPI); end; function TProdutoOperacaoConsultarController.&end: IProdutoController; begin Result := FProdutoController; end; constructor TProdutoOperacaoConsultarController.Create; begin end; function TProdutoOperacaoConsultarController.descricao: string; begin Result := FRegistro.descricao; end; destructor TProdutoOperacaoConsultarController.Destroy; begin inherited; end; function TProdutoOperacaoConsultarController.localizar(AValue: string) : IProdutoOperacaoConsultarController; begin Result := Self; FRegistro := FProdutoModel.DAO.FindWhere('CODIGO=' + QuotedStr(AValue), 'DESCRICAO').Items[0]; end; class function TProdutoOperacaoConsultarController.New : IProdutoOperacaoConsultarController; begin Result := Self.Create; end; function TProdutoOperacaoConsultarController.prMedioSinapi: string; begin Result := CurrToStr(FRegistro.PRMEDIO_SINAPI); end; function TProdutoOperacaoConsultarController.produtoController (AValue: IProdutoController): IProdutoOperacaoConsultarController; begin Result := Self; FProdutoController := AValue; end; function TProdutoOperacaoConsultarController.produtoModel(AValue: IProdutoModel) : IProdutoOperacaoConsultarController; begin Result := Self; FProdutoModel := AValue; end; function TProdutoOperacaoConsultarController.unidMedida: string; begin Result := FRegistro.unidMedida; end; end.
{*------------------------------------------------------------------------------ File uTSINIFile berisi rutin-rutin yg digunakan untuk keperluan membaca dan menulis di file *.ini. Biasa untuk keperluan menyimpan konfigurasi suatu aplikasi. Copyright @ Gamatechno 2006 @author Didit Ahendra @version 0.1.0 Initiate rutin @date 29-04-2006 Start create rutin @bug - -----------------------------------------------------------------------------*} unit uTSINIFile; interface uses SysUtils, Forms, INIFiles, Registry; procedure _INIWriteString(AFilename, ASection, AIdentifier, AValue: String); procedure _INIWriteInteger(AFilename, ASection, AIdentifier: String; AValue: Integer); procedure _INIWriteBoolean(AFilename, ASection, AIdentifier: String; AValue: Boolean); function _INIReadString(AFilename, ASection, AIdentifier: String): String; function _INIReadInteger(AFilename, ASection, AIdentifier: String): Integer; function _INIReadBoolean(AFilename, ASection, AIdentifier: String): Boolean; procedure _DeleteIdent(AFilename, ASection, AIdenfifier: String); function _IsSectionExists(AFilename, ASection: String): Boolean; function _IsIdentExists(AFilename, ASection, AIdentifier: String): Boolean; function BacaRegistry(aNama: String; aPath : String = ''): string; function TulisRegistry(aName, aValue: String; sAppName : String = ''): Boolean; implementation uses Winapi.Windows; procedure _INIWriteString(AFilename, ASection, AIdentifier, AValue: String); var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try WriteString(ASection, AIdentifier, AValue); finally Free; end; end; end; procedure _INIWriteInteger(AFilename, ASection, AIdentifier: String; AValue: Integer); var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try WriteInteger(ASection, AIdentifier, AValue); finally Free; end; end; end; procedure _INIWriteBoolean(AFilename, ASection, AIdentifier: String; AValue: Boolean); var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try WriteBool(ASection, AIdentifier, AValue); finally Free; end; end; end; function _INIReadString(AFilename, ASection, AIdentifier: String): String; var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try Result := ReadString(ASection, AIdentifier, ''); finally Free; end; end; end; function _INIReadInteger(AFilename, ASection, AIdentifier: String): Integer; var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try Result := ReadInteger(ASection, AIdentifier, 999); finally Free; end; end; end; function _INIReadBoolean(AFilename, ASection, AIdentifier: String): Boolean; var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try Result := ReadBool(ASection, AIdentifier, False); finally Free; end; end; end; procedure _DeleteIdent(AFilename, ASection, AIdenfifier: String); var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try DeleteKey(ASection, AIdenfifier); finally Free; end; end; end; function _IsSectionExists(AFilename, ASection: String): Boolean; var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try Result := SectionExists(ASection); finally Free; end; end; end; function _IsIdentExists(AFilename, ASection, AIdentifier: String): Boolean; var INIFile: TIniFile; begin INIFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + AFilename); with INIFile do begin try Result := ValueExists(ASection, AIdentifier); finally Free; end; end; end; function BacaRegistry(aNama: String; aPath : String = ''): string; var Registry: TRegistry; //S: string; begin Registry:=TRegistry.Create; Registry.RootKey := HKEY_CURRENT_USER; {False because we do not want to create it if it doesn’t exist} if Trim(aPath) = '' then Registry.OpenKey('\Software\' + Application.Title, False) else Registry.OpenKey('\Software\' + aPath, False); Result := Registry.ReadString(aNama); Registry.Free; end; function TulisRegistry(aName, aValue: String; sAppName : String = ''): Boolean; var Reg : TRegistry; begin result := true; Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if sAppName = '' then begin if Reg.OpenKey('\Software\' + Application.Title, True) then begin Reg.WriteString(aName, aValue); Reg.CloseKey; end end else begin if Reg.OpenKey('\Software\' + sAppName, True) then begin Reg.WriteString(aName, aValue); Reg.CloseKey; end; end; Except result := false; Reg.Free; exit; end; Reg.Free; end; end.
unit ibSHDDLGenerator; interface uses SysUtils, Classes, Controls, Dialogs, StrUtils, DB, SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHComponent; const SDDLOffset = ' '; SDDLTerminator = '^'; DescrHeader: array[0..1] of string = ( '/* Description ----------------------------------------------------------------%s', '----------------------------------------------------------------------------- */'); DescrFooter: array[0..3] of string = ( ' ', '/* Insert description ---------------------------------------------------------', '%s', '----------------------------------------------------------------------------- */'); StatisticsFooter: array[0..3] of string = ( ' ', '/* Statistics -----------------------------------------------------------------', '%s', '----------------------------------------------------------------------------- */'); DeleteOld = '/* Delete OLD object -------------------------------------------------------- */'; CreateNew = '/* Create NEW object -------------------------------------------------------- */'; BeginRTFM = '/* RTFM --------------------------------------------------------------------- */'; EndRTFM = '----------------------------------------------------------------------------- */'; type TibBTDDLGenerator = class(TibBTComponent, IibSHDDLGenerator,IibBTTemplates) private FTerminator: string; FUseFakeValues: Boolean; FDBObjectIntf: IibSHDBObject; FDRVQueryIntf: IibSHDRVQuery; FState: TSHDBComponentState; FVersion: string; FDialect: Integer; FExistsPrecision: Boolean; FExistsProcParamDomains: Boolean; FDBCharset: string; FDDL: TStrings; FCodeNormalizer: IibSHCodeNormalizer; FIntDRVTransaction: TComponent; FIntDRVTransactionIntf: IibSHDRVTransaction; FIntDRVQuery: TComponent; FIntDRVQueryIntf: IibSHDRVQuery; FDBDomainIntf: IibSHDomain; FDBTableIntf: IibSHTable; FDBFieldIntf: IibSHField; FDBConstraintIntf: IibSHConstraint; FDBIndexIntf: IibSHIndex; FDBViewIntf: IibSHView; FDBProcedureIntf: IibSHProcedure; FDBTriggerIntf: IibSHTrigger; FDBGeneratorIntf: IibSHGenerator; FDBExceptionIntf: IibSHException; FDBFunctionIntf: IibSHFunction; FDBFilterIntf: IibSHFilter; FDBRoleIntf: IibSHRole; FDBShadowIntf: IibSHShadow; FDBQueryIntf: IibSHQuery; FCurrentTemplateFile:string; function GetTerminator: string; procedure SetTerminator(Value: string); function GetUseFakeValues: Boolean; procedure SetUseFakeValues(Value: Boolean); procedure SetBasedOnDomain(ADRVQuery: IibSHDRVQuery; ADomain: IibSHDomain; const ACaption: string); procedure SetRealValues; function ReplaceNameConsts(const ADDLText, ACaption: string): string; procedure SetFakeValues(DDL: TStrings; FileName:string=''); procedure SetDDLFromValues(DDL: TStrings); procedure SetAlterDDLNotSupported(DDL: TStrings); procedure SetSourceDDL(DDL: TStrings); procedure SetCreateDDL(DDL: TStrings); procedure SetAlterDDL(DDL: TStrings); procedure SetDropDDL(DDL: TStrings); procedure SetRecreateDDL(DDL: TStrings); procedure CreateIntDRV; procedure FreeIntDRV; function NormalizeName(const S: string): string; function NormalizeName2(const S: string;DB:IibSHDatabase=nil): string; function GetMaxStrLength(AStrings: TStrings): Integer; function SpaceGenerator(const MaxStrLength: Integer; const S: string): string; (* function IncludeDesciption(const ADDL: string): string; *) (* function ExcludeDesciption(const ADDL: string): string; *) //IibBTTemplates function GetCurrentTemplateFile:string; procedure SetCurrentTemplateFile(const FileName:string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetDDLText(const Intf: IInterface): string; // <- Вход property DBObject: IibSHDBObject read FDBObjectIntf; property DRVQuery: IibSHDRVQuery read FDRVQueryIntf; property State: TSHDBComponentState read FState; property Version: string read FVersion; property Dialect: Integer read FDialect; property ExistsPrecision: Boolean read FExistsPrecision; property DBCharset: string read FDBCharset; property DDL: TStrings read FDDL; property CodeNormalizer: IibSHCodeNormalizer read FCodeNormalizer; property DBDomain: IibSHDomain read FDBDomainIntf; property DBTable: IibSHTable read FDBTableIntf; property DBField: IibSHField read FDBFieldIntf; property DBConstraint: IibSHConstraint read FDBConstraintIntf; property DBIndex: IibSHIndex read FDBIndexIntf; property DBView: IibSHView read FDBViewIntf; property DBProcedure: IibSHProcedure read FDBProcedureIntf; property DBTrigger: IibSHTrigger read FDBTriggerIntf; property DBGenerator: IibSHGenerator read FDBGeneratorIntf; property DBException: IibSHException read FDBExceptionIntf; property DBFunction: IibSHFunction read FDBFunctionIntf; property DBFilter: IibSHFilter read FDBFilterIntf; property DBRole: IibSHRole read FDBRoleIntf; property DBShadow: IibSHShadow read FDBShadowIntf; property DBQuery: IibSHQuery read FDBQueryIntf; end; implementation uses ibSHConsts, ibSHSQLs, ibSHMessages, ibSHValues; { TibBTDDLGenerator } constructor TibBTDDLGenerator.Create(AOwner: TComponent); begin inherited Create(AOwner); FTerminator := ';'; FUseFakeValues := True; FDDL := TStringList.Create; Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, FCodeNormalizer); end; destructor TibBTDDLGenerator.Destroy; begin FreeAndNil(FIntDRVTransaction); FreeAndNil(FIntDRVQuery); FDDL.Free; inherited Destroy; end; function TibBTDDLGenerator.GetDDLText(const Intf: IInterface): string; var vDDL:TStrings; begin vDDL:=TStringList.Create; try Supports(Intf, IibSHDBObject, FDBObjectIntf); FDRVQueryIntf := DBObject.BTCLDatabase.DRVQuery; FState := DBObject.State; FVersion := DBObject.BTCLDatabase.BTCLServer.Version; FDialect := DBObject.BTCLDatabase.SQLDialect; FExistsPrecision := DBObject.BTCLDatabase.ExistsPrecision; FExistsProcParamDomains:=DBObject.BTCLDatabase.ExistsProcParamDomains; FDBCharset := DBObject.BTCLDatabase.DBCharset; CreateIntDRV; if not Supports(Intf, IibSHField, FDBFieldIntf) then Supports(Intf, IibSHDomain,FDBDomainIntf); { if Supports(Intf, IibSHDomain,FDBDomainIntf) then begin if Supports(Intf, IibSHField, FDBFieldIntf) then FDBDomainIntf:=nil; end; } Supports(Intf, IibSHTable, FDBTableIntf); Supports(Intf, IibSHConstraint, FDBConstraintIntf); Supports(Intf, IibSHIndex, FDBIndexIntf); Supports(Intf, IibSHView, FDBViewIntf); Supports(Intf, IibSHProcedure, FDBProcedureIntf); Supports(Intf, IibSHTrigger, FDBTriggerIntf); Supports(Intf, IibSHGenerator, FDBGeneratorIntf); Supports(Intf, IibSHException, FDBExceptionIntf); Supports(Intf, IibSHFunction, FDBFunctionIntf); Supports(Intf, IibSHFilter, FDBFilterIntf); Supports(Intf, IibSHRole, FDBRoleIntf); Supports(Intf, IibSHShadow, FDBShadowIntf); Supports(Intf, IibSHQuery, FDBQueryIntf); // DDL.Clear; if Assigned(DBProcedure) then DBProcedure.HeaderDDL.Clear; case State of csUnknown: ; csSource,csRelatedSource: SetSourceDDL(vDDL); csCreate: SetCreateDDL(vDDL); csAlter: SetAlterDDL(vDDL); csDrop: SetDropDDL(vDDL); csRecreate: SetRecreateDDL(vDDL); end; // SetDDLFromValues(DDL: TStrings); // SetAlterDDLNotSupported(DDL: TStrings); Result := Trim(vDDL.Text); // if Length(Result) > 0 then // begin // if State <> csDrop then Result := IncludeDesciption(Result); // end else // Result := '/* UNDER CONSTRUCTION */'; // if (Result = 'User Cancel') or DBObject.BTCLDatabase.WasLostconnect then // Result := EmptyStr; finally //Buzz // Полная лажа. При рекурсивном вызове все летит в тар-тарары. // Все треба переписать без глобальных полей. Или создавать генератор по новой для каждого вызова vDDL.Free; FreeIntDRV; FDBObjectIntf := nil; FDRVQueryIntf := nil; FDBDomainIntf := nil; FDBTableIntf := nil; FDBFieldIntf := nil; FDBConstraintIntf := nil; FDBIndexIntf := nil; FDBViewIntf := nil; FDBProcedureIntf := nil; FDBTriggerIntf := nil; FDBGeneratorIntf := nil; FDBExceptionIntf := nil; FDBFunctionIntf := nil; FDBFilterIntf := nil; FDBRoleIntf := nil; FDBShadowIntf := nil; FDBQueryIntf := nil; end; end; procedure TibBTDDLGenerator.CreateIntDRV; var vComponentClass: TSHComponentClass; begin if not Assigned(FIntDRVTransaction) then begin vComponentClass := Designer.GetComponent(DBObject.BTCLDatabase.BTCLServer.DRVNormalize(IibSHDRVTransaction)); if Assigned(vComponentClass) then begin FIntDRVTransaction := vComponentClass.Create(Self); end; end; if Assigned(FIntDRVTransaction) then begin Supports(FIntDRVTransaction, IibSHDRVTransaction, FIntDRVTransactionIntf); (FIntDRVTransaction as IibSHDRVTransaction).Params.Text := TRWriteParams; end; if not Assigned(FIntDRVQuery) then begin vComponentClass := Designer.GetComponent(DBObject.BTCLDatabase.BTCLServer.DRVNormalize(IibSHDRVQuery)); if Assigned(vComponentClass) then begin FIntDRVQuery := vComponentClass.Create(Self); end; end; if Assigned(FIntDRVQuery) then Supports(FIntDRVQuery, IibSHDRVQuery, FIntDRVQueryIntf); if Assigned(FIntDRVTransaction) and Assigned(FIntDRVQuery) then begin FIntDRVTransactionIntf.Database := DBObject.BTCLDatabase.DRVQuery.Database; FIntDRVQueryIntf.Transaction := FIntDRVTransactionIntf; FIntDRVQueryIntf.Database := DBObject.BTCLDatabase.DRVQuery.Database; end; end; procedure TibBTDDLGenerator.FreeIntDRV; begin if FIntDRVQueryIntf<>nil then begin FIntDRVQueryIntf.Transaction:=nil; FIntDRVQueryIntf.Database := nil; end; FIntDRVQueryIntf := nil; if FIntDRVTransactionIntf<>nil then FIntDRVTransactionIntf.Database := nil; FIntDRVTransactionIntf := nil; { FreeAndNil(FIntDRVTransaction); FreeAndNil(FIntDRVQuery);} end; function TibBTDDLGenerator.NormalizeName(const S: string): string; begin Result := S; if Assigned(DBObject) then begin // if (State = csCreate) and (CompareStr(DBObject.Caption, Result) <> 0) then Exit; //^^Buzz непонятно что автор подразумевал этим произведением // этот код дает ошибку при попытки добавить поле в таблицу с нестандартным именем. if Assigned(CodeNormalizer) then Result := CodeNormalizer.MetadataNameToSourceDDL(DBObject.BTCLDatabase, Result); end; end; function TibBTDDLGenerator.NormalizeName2(const S: string;DB:IibSHDatabase=nil): string; begin Result := S; if Assigned(DBObject) or Assigned(DB) then begin if not Assigned(DB) then DB:=DBObject.BTCLDatabase; if Assigned(CodeNormalizer) then Result := CodeNormalizer.MetadataNameToSourceDDL(DB, Result); end; end; function TibBTDDLGenerator.GetMaxStrLength(AStrings: TStrings): Integer; var I: Integer; S: string; begin Result := 0; // Вообще-то, правильнее рассчитывать через Canvas.TextWidth... for I := 0 to Pred(AStrings.Count) do begin S := NormalizeName(AStrings[I]); if Result < Length(S) then Result := Length(S); end; end; function TibBTDDLGenerator.SpaceGenerator(const MaxStrLength: Integer; const S: string): string; {var I: Integer;} begin if MaxStrLength<=Length(S) then Result := ' ' else begin SetLength(Result,MaxStrLength - Length(S)+1); FillChar(Result[1],MaxStrLength - Length(S)+1,' ') end { Result := ' '; for I := 0 to Pred(MaxStrLength - Length(S)) do Result := Result + ' ';} end; (* function TibBTDDLGenerator.IncludeDesciption(const ADDL: string): string; var Description: string; begin if Assigned(DBGenerator) or Assigned(DBRole) or Assigned(DBShadow) then begin Result := ADDL; Exit; end; case DBObject.State of csSource: begin if Length(DBObject.Description.Text) > 0 then begin Description := Format(FormatSQL(DescrHeader), [SLineBreak + TrimRight(DBObject.Description.Text)]); Result := Format('%s%s', [Description, ADDL]); end else Result := ADDL; end; csCreate, csAlter, csRecreate: begin Description := FormatSQL(DescrFooter); if Assigned(DBDomain) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_DOMAIN))]); if Assigned(DBTable) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_TABLE))]); if Assigned(DBIndex) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_INDEX))]); if Assigned(DBView) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_VIEW))]); if Assigned(DBProcedure) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_PROCEDURE))]); if Assigned(DBTrigger) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_TRIGGER))]); if Assigned(DBException) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_EXCEPTION))]); if Assigned(DBFunction) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_FUNCTION))]); if Assigned(DBFilter) then Description := Format(Description, [TrimRight(FormatSQL(SQL_SET_COMMENT_FILTER))]); if Length(DBObject.Description.Text) = 0 then Description := Format(Description, ['<description>', DBObject.Caption]) else Description := Format(Description, [TrimRight(DBObject.Description.Text), DBObject.Caption]); Result := Format('%s%s', [ADDL, SLineBreak + Description]); end; end; end; *) (* function TibBTDDLGenerator.ExcludeDesciption(const ADDL: string): string; begin if Length(DBObject.Description.Text) > 0 then Result := AnsiReplaceText(ADDL, Format(FormatSQL(DescrHeader), [SLineBreak + TrimRight(DBObject.Description.Text)]), EmptyStr); end; *) function TibBTDDLGenerator.GetTerminator: string; begin Result := FTerminator; end; procedure TibBTDDLGenerator.SetTerminator(Value: string); begin FTerminator := Value; end; function TibBTDDLGenerator.GetUseFakeValues: Boolean; begin Result := FUseFakeValues; end; procedure TibBTDDLGenerator.SetUseFakeValues(Value: Boolean); begin FUseFakeValues := Value; end; procedure TibBTDDLGenerator.SetBasedOnDomain(ADRVQuery: IibSHDRVQuery; ADomain: IibSHDomain; const ACaption: string); var S,S1: string; Precision: Integer; BasedOnDomain, NeedCharset: Boolean; vForceInitDRV:boolean; begin ADomain.Caption := ACaption; ADomain.ObjectName := ACaption; if ADRVQuery.FieldExists('DESCRIPTION') then ADomain.Description.Text := Trim(ADRVQuery.GetFieldStrValue('DESCRIPTION')); if ADRVQuery.FieldExists('FIELD_TYPE_ID') then ADomain.FieldTypeID := ADRVQuery.GetFieldIntValue('FIELD_TYPE_ID'); if ADRVQuery.FieldExists('SUB_TYPE_ID') then ADomain.SubTypeID := ADRVQuery.GetFieldIntValue('SUB_TYPE_ID'); if ADRVQuery.FieldExists('CHARSET_ID') then ADomain.CharsetID := ADRVQuery.GetFieldIntValue('CHARSET_ID'); if ADRVQuery.FieldExists('COLLATE_ID') then ADomain.CollateID := ADRVQuery.GetFieldIntValue('COLLATE_ID'); if ADRVQuery.FieldExists('ARRAY_DIM') then ADomain.ArrayDimID := ADRVQuery.GetFieldIntValue('ARRAY_DIM'); if ADRVQuery.FieldExists('NOT_NULL') then ADomain.NotNull := ADRVQuery.GetFieldIntValue('NOT_NULL') = 1; if ADRVQuery.FieldExists('DEFAULT_SOURCE') then ADomain.DefaultExpression.Text := Trim(ADRVQuery.GetFieldStrValue('DEFAULT_SOURCE')) else if ADRVQuery.FieldExists('DEFAULT_EXPRESSION') then ADomain.DefaultExpression.Text := Trim(AnsiReplaceText(ADRVQuery.GetFieldStrValue('DEFAULT_EXPRESSION'), 'DEFAULT', '')) else ADomain.DefaultExpression.Text := ''; if ADRVQuery.FieldExists('DEFAULT_SOURCE_OVER') then ADomain.DefaultExpression.Text := Trim(ADRVQuery.GetFieldStrValue('DEFAULT_SOURCE_OVER')); if ADRVQuery.FieldExists('LENGTH_') then begin ADomain.Length := ADRVQuery.GetFieldIntValue('LENGTH_'); if ADRVQuery.FieldExists('SYSTEM_FLAG') and (ADRVQuery.GetFieldIntValue('SYSTEM_FLAG') = 1) and ADRVQuery.FieldExists('FIELD_LENGTH_') then ADomain.Length := ADRVQuery.GetFieldIntValue('FIELD_LENGTH_'); end; if ADRVQuery.FieldExists('PRECISION_') then {ADomain.}Precision := ADRVQuery.GetFieldIntValue('PRECISION_'); if ADRVQuery.FieldExists('SCALE') then ADomain.Scale := ADRVQuery.GetFieldIntValue('SCALE') * (-1); if ADRVQuery.FieldExists('SEGMENT_SIZE') then ADomain.SegmentSize := ADRVQuery.GetFieldIntValue('SEGMENT_SIZE'); if ADRVQuery.FieldExists('CHECK_CONSTRAINT') then begin ADomain.CheckConstraint.Text := Trim(AnsiReplaceText(ADRVQuery.GetFieldStrValue('CHECK_CONSTRAINT'), 'CHECK', '')); ADomain.CheckConstraint.Text := AnsiMidStr(Trim(ADomain.CheckConstraint.Text), 2, Length(Trim(ADomain.CheckConstraint.Text)) - 2); end; if ADRVQuery.FieldExists('COMPUTED_SOURCE') then ADomain.ComputedSource.Text := Trim(ADRVQuery.GetFieldStrValue('COMPUTED_SOURCE')); if ADRVQuery.FieldExists('F_BASED_ON_DOMAIN') then ADomain.Domain := ADRVQuery.GetFieldStrValue('F_BASED_ON_DOMAIN'); // if ADRVQuery.FieldExists('F_FIELD_NAME') then if ADRVQuery.FieldExists('F_TABLE_NAME') then ADomain.TableName := ADRVQuery.GetFieldStrValue('F_TABLE_NAME'); if Assigned(DBProcedure) then ADomain.TableName := DBProcedure.Caption; if ADRVQuery.FieldExists('F_DESCRIPTION') then ADomain.Description.Text := Trim(ADRVQuery.GetFieldStrValue('F_DESCRIPTION')); if ADRVQuery.FieldExists('F_NOT_NULL') then ADomain.FieldNotNull := ADRVQuery.GetFieldIntValue('F_NOT_NULL') = 1; if ADRVQuery.FieldExists('F_DEFAULT_EXPRESSION') then ADomain.FieldDefault.Text := Trim(AnsiReplaceText(ADRVQuery.GetFieldStrValue('F_DEFAULT_EXPRESSION'), 'DEFAULT', '')); ADomain.FieldCollateID := -1; if ADRVQuery.FieldExists('F_COLLATE_ID') and not ADRVQuery.GetFieldIsNull('F_COLLATE_ID') and Assigned(DBTable) then ADomain.FieldCollateID := ADRVQuery.GetFieldIntValue('F_COLLATE_ID'); if (ADomain.ArrayDimID > 0) and (ADomain.Domain<>'') then begin { TODO -oBuzz -cProposal : Все-таки вытащить размеры аррай поля } //Buzz vForceInitDRV:=FIntDRVQueryIntf=nil; if vForceInitDRV then begin Supports(ADomain, IibSHDBObject, FDBObjectIntf); CreateIntDRV; end; //Buzz try if Length(ADomain.Domain) > 0 then S := ADomain.Domain else S := ADomain.Caption; S1:=FormatSQL(SQL_GET_DIMENSIONS); if FIntDRVQueryIntf.ExecSQL(S1, [S], False,True) then begin while not FIntDRVQueryIntf.Eof do begin if System.Length(ADomain.ArrayDim) > 0 then ADomain.ArrayDim := Format('%s, ', [ADomain.ArrayDim]); ADomain.ArrayDim := Format('%s%s:%s', [ADomain.ArrayDim, FIntDRVQueryIntf.GetFieldStrValue('LOWER_BOUND'), FIntDRVQueryIntf.GetFieldStrValue('UPPER_BOUND')]); FIntDRVQueryIntf.Next; end; end; ADomain.ArrayDim := Format('[%s]', [ADomain.ArrayDim]); FIntDRVQueryIntf.Close; FIntDRVQueryIntf.Transaction.Commit; finally if vForceInitDRV then begin FreeIntDRV; FDBObjectIntf:=nil end end ; end; if ADomain.NotNull then ADomain.NullType := NullTypes[1] else ADomain.NullType := ''; if ADomain.FieldNotNull then ADomain.FieldNullType := NullTypes[1] else ADomain.FieldNullType := ''; ADomain.SubType := IDToBlobSubType(ADomain.SubTypeID); if SameText(Version, SInterBase4x) or SameText(Version, SInterBase5x) or SameText(Version, SInterBase6x) or SameText(Version, SInterBase65) or SameText(Version, SFirebird1x) then begin ADomain.Charset := GetCharsetFromIDFB10(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDFB10(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDFB10(ADomain.CharsetID, ADomain.FieldCollateID); end else if SameText(Version, SFirebird15) then begin ADomain.Charset := GetCharsetFromIDFB15(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDFB15(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDFB15(ADomain.CharsetID, ADomain.FieldCollateID); end else if SameText(Version, SFirebird20) then begin ADomain.Charset := GetCharsetFromIDFB20(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDFB20(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDFB20(ADomain.CharsetID, ADomain.FieldCollateID); end else if SameText(Version, SFirebird21) then begin ADomain.Charset := GetCharsetFromIDFB21(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDFB21(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDFB21(ADomain.CharsetID, ADomain.FieldCollateID); end else if SameText(Version, SInterBase70) then begin ADomain.Charset := GetCharsetFromIDIB70(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDIB70(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDIB70(ADomain.CharsetID, ADomain.FieldCollateID); end else if SameText(Version, SInterBase71) then begin ADomain.Charset := GetCharsetFromIDIB71(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDIB71(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDIB71(ADomain.CharsetID, ADomain.FieldCollateID); end else if SameText(Version, SInterBase75) or SameText(Version, SInterBase2007) then begin ADomain.Charset := GetCharsetFromIDIB75(ADomain.CharsetID); ADomain.Collate := GetCollateFromIDIB75(ADomain.CharsetID, ADomain.CollateID); if ADomain.FieldCollateID <> -1 then ADomain.FieldCollate := GetCollateFromIDIB75(ADomain.CharsetID, ADomain.FieldCollateID); end; case ADomain.FieldTypeID of _SMALLINT: begin ADomain.DataType := Get_SMALLINT({ADomain.}Precision, ADomain.Scale, ADomain.SubTypeID); ADomain.DataTypeExt := Get_SMALLINT({ADomain.}Precision, ADomain.Scale, ADomain.SubTypeID, True); end; _INTEGER: begin ADomain.DataType := Get_INTEGER({ADomain.}Precision, ADomain.Scale, ADomain.SubTypeID); ADomain.DataTypeExt := Get_INTEGER({ADomain.}Precision, ADomain.Scale, ADomain.SubTypeID, True); end; _BIGINT: begin ADomain.DataType := Get_BIGINT({ADomain.}Precision, ADomain.Scale, ADomain.SubTypeID); ADomain.DataTypeExt := Get_BIGINT({ADomain.}Precision, ADomain.Scale, ADomain.SubTypeID, True); end; _BOOLEAN: begin ADomain.DataType := Get_BOOLEAN; ADomain.DataTypeExt := Get_BOOLEAN; end; _FLOAT: begin ADomain.DataType := Get_FLOAT({ADomain.}Precision, ADomain.Scale); ADomain.DataTypeExt := Get_FLOAT({ADomain.}Precision, ADomain.Scale, True); end; _DOUBLE: begin ADomain.DataType := Get_DOUBLE({ADomain.}Precision, ADomain.Scale); ADomain.DataTypeExt := Get_DOUBLE({ADomain.}Precision, ADomain.Scale, True); end; _DATE: begin ADomain.DataType := Get_DATE; ADomain.DataTypeExt := Get_DATE; end; _TIME: begin ADomain.DataType := Get_TIME; ADomain.DataTypeExt := Get_TIME; end; _TIMESTAMP: begin ADomain.DataType := Get_TIMESTAMP(Dialect); ADomain.DataTypeExt := Get_TIMESTAMP(Dialect); end; _CHAR: begin ADomain.DataType := Get_CHAR(ADomain.Length); ADomain.DataTypeExt := Get_CHAR(ADomain.Length, True); end; _VARCHAR: begin ADomain.DataType := Get_VARCHAR(ADomain.Length); ADomain.DataTypeExt := Get_VARCHAR(ADomain.Length, True); end; _BLOB: begin ADomain.DataType := Get_BLOB(ADomain.SubTypeID, ADomain.SegmentSize); ADomain.DataTypeExt := Get_BLOB(ADomain.SubTypeID, ADomain.SegmentSize, True); if (ADomain.SubTypeID <> 1) then ADomain.Charset := EmptyStr; ADomain.Collate := EmptyStr end; _CSTRING: begin ADomain.DataType := Get_CSTRING(ADomain.Length); ADomain.DataTypeExt := Get_CSTRING(ADomain.Length, True); end; _QUAD: begin ADomain.DataType := Get_QUAD; ADomain.DataTypeExt := Get_QUAD; end; end; ADomain.Precision := Precision; // For Fields BasedOnDomain := not IsSystemDomain(ADomain.Domain); // Pos('RDB$', ADomain.Domain) = 0; NeedCharset := not AnsiSameText(ADomain.Charset, DBCharset); ADomain.DataTypeField := Format('%s', [ADomain.DataTypeExt]); ADomain.DataTypeFieldExt := Format('%s', [ADomain.DataTypeExt]); case ADomain.FieldTypeID of _SMALLINT, _INTEGER, _BIGINT, _BOOLEAN, _FLOAT, _DOUBLE, _DATE, _TIME, _TIMESTAMP, _CHAR, _VARCHAR: begin if Length(ADomain.ArrayDim) > 0 then begin ADomain.DataTypeField := Format('%s %s', [ADomain.DataTypeField, ADomain.ArrayDim]); ADomain.DataTypeFieldExt := Format('%s %s', [ADomain.DataTypeFieldExt, ADomain.ArrayDim]); end; end; end; case ADomain.FieldTypeID of _CHAR, _VARCHAR: if NeedCharset then begin ADomain.DataTypeField := Format('%s CHARACTER SET %s', [ADomain.DataTypeField, ADomain.Charset]); ADomain.DataTypeFieldExt := Format('%s CHARACTER SET %s', [ADomain.DataTypeFieldExt, ADomain.Charset]); end; _BLOB: if NeedCharset and (ADomain.SubTypeID = 1) then begin ADomain.DataTypeField := Format('%s CHARACTER SET %s', [ADomain.DataTypeField, ADomain.Charset]); ADomain.DataTypeFieldExt := Format('%s CHARACTER SET %s', [ADomain.DataTypeFieldExt, ADomain.Charset]); end; end; if BasedOnDomain and (ADomain.Domain<>'') then begin if not ADRVQuery.FieldExists('MECHANIZM') or (ADRVQuery.GetFieldIntValue('MECHANIZM')=0) then ADomain.DataTypeField := Format('%s', [NormalizeName(ADomain.Domain)]) else ADomain.DataTypeField := Format('TYPE OF %s', [NormalizeName(ADomain.Domain)]) end else ADomain.DataTypeField := ADomain.DataTypeExt; // DecodeDomains if Assigned(DBTable) and not DBTable.DecodeDomains and BasedOnDomain then ADomain.DataTypeFieldExt := Format('%s', [NormalizeName(ADomain.Domain)]); if Length(ADomain.FieldDefault.Text) > 0 then begin ADomain.DataTypeField := Format('%s DEFAULT %s', [ADomain.DataTypeField, Trim(ADomain.FieldDefault.Text)]); ADomain.DataTypeFieldExt := Format('%s DEFAULT %s', [ADomain.DataTypeFieldExt, Trim(ADomain.FieldDefault.Text)]); end; // DecodeDomains if Assigned(DBTable) and DBTable.DecodeDomains and (Length(ADomain.FieldDefault.Text) = 0) then begin if Length(ADomain.DefaultExpression.Text) > 0 then ADomain.DataTypeFieldExt := Format('%s DEFAULT %s', [ADomain.DataTypeFieldExt, Trim(ADomain.DefaultExpression.Text)]); end; if ADomain.FieldNotNull then ADomain.DataTypeField := Format('%s %s', [ADomain.DataTypeField, ADomain.FieldNullType]); // DecodeDomains if Assigned(DBTable) and DBTable.DecodeDomains {and not ADomain.FieldNotNull} then begin if ADomain.NotNull then ADomain.DataTypeFieldExt := Format('%s %s', [ADomain.DataTypeFieldExt, ADomain.NullType]) else begin if ADomain.FieldNotNull then ADomain.DataTypeFieldExt := Format('%s %s', [ADomain.DataTypeFieldExt, ADomain.FieldNullType]); end; end; // DecodeDomains if Assigned(DBTable) and DBTable.DecodeDomains and (Length(ADomain.CheckConstraint.Text) > 0) then ADomain.DataTypeFieldExt := Format('%s CHECK (%s)', [ADomain.DataTypeFieldExt, Trim(AnsiReplaceText(ADomain.CheckConstraint.Text, 'VALUE', NormalizeName(ACaption)))]); case ADomain.FieldTypeID of _CHAR, _VARCHAR: begin if not BasedOnDomain then begin if ADomain.FieldCollateID = -1 then begin if not AnsiSameText(ADomain.Charset, ADomain.Collate) then ADomain.DataTypeField := Format('%s COLLATE %s', [ADomain.DataTypeField, ADomain.FieldCollate]); end else begin if not AnsiSameText(ADomain.Charset, ADomain.FieldCollate) then ADomain.DataTypeField := Format('%s COLLATE %s', [ADomain.DataTypeField, ADomain.FieldCollate]); end; // DecodeDomains if Assigned(DBTable) and DBTable.DecodeDomains then if (Length(ADomain.Collate) > 0) and not AnsiSameText(ADomain.Charset, ADomain.Collate) then ADomain.DataTypeFieldExt := Format('%s COLLATE %s', [ADomain.DataTypeFieldExt, ADomain.Collate]); end; if BasedOnDomain and (ADomain.FieldCollateID <> - 1) {and (AnsiSameText(ADomain.Collate, ADomain.FieldCollate) <> 0)} then ADomain.DataTypeField := Format('%s COLLATE %s', [ADomain.DataTypeField, ADomain.FieldCollate]); end; end; if Length(ADomain.ComputedSource.Text) > 0 then begin ADomain.DataTypeField := Format('COMPUTED BY %s', [Trim(ADomain.ComputedSource.Text)]); ADomain.DataTypeFieldExt := Format('COMPUTED BY %s', [Trim(ADomain.ComputedSource.Text)]); end; if (ADomain.DataType = 'SMALLINT') or (ADomain.DataType = 'INTEGER') or (ADomain.DataType = 'BOOLEAN') or (ADomain.DataType = 'BIGINT') or (ADomain.DataType = 'FLOAT') or (ADomain.DataType = 'DOUBLE PRECISION') or (ADomain.DataType = 'DATE') or (ADomain.DataType = 'TIME') or (ADomain.DataType = 'TIMESTAMP') or (ADomain.DataType = 'NUMERIC') or (ADomain.DataType = 'DECIMAL') or (Length(ADomain.ComputedSource.Text) > 0) then begin ADomain.Charset := ''; ADomain.Collate := ''; end; end; procedure TibBTDDLGenerator.SetRealValues; const sh: array [0..2] of Integer = (1, 3, 5); var I: Integer; SQL: string; // For Trigger Active, TriggerTypeID: Integer; vSuf, vDelim: string; // For Function ReturnsParamPos, Mechanism: Integer; RefConstraint, RefIndex: string; // For Query varDomain: IibSHDomain; varPrecision: Integer; MaxStrLength:Integer; S :String; S1:String; begin if Assigned(DBDomain) then begin if not ExistsPrecision then SQL := FormatSQL(SQL_INIT_DOMAIN1) else SQL := FormatSQL(SQL_INIT_DOMAIN3); if DRVQuery.ExecSQL(SQL, [DBDomain.Caption], False,True) then begin DBDomain.ObjectName := DBDomain.Caption; SetBasedOnDomain(DRVQuery, DBDomain as IibSHDomain, DBDomain.Caption); end; DRVQuery.Transaction.Commit; end else if Assigned(DBTable) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE), [DBTable.Caption], False,True) then begin DBTable.ObjectName := DBTable.Caption; DBTable.OwnerName := DRVQuery.GetFieldStrValue('OWNER_NAME'); DBTable.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); DBTable.SetExternalFile(DRVQuery.GetFieldStrValue('EXTERNAL_FILE')); DBTable.Triggers.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_TRIGGERS), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin DBTable.Triggers.Add(DRVQuery.GetFieldStrValue('TRIGGER_NAME')); DRVQuery.Next; end; end; DBTable.Constraints.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_CONSTRAINTS_PRIMARY), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin DBTable.Constraints.Add(DRVQuery.GetFieldStrValue('CONSTRAINT_NAME')); DRVQuery.Next; end; end; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_CONSTRAINTS_UNIQUE), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin DBTable.Constraints.Add(DRVQuery.GetFieldStrValue('CONSTRAINT_NAME')); DRVQuery.Next; end; end; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_CONSTRAINTS_FOREIGN), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin DBTable.Constraints.Add(DRVQuery.GetFieldStrValue('CONSTRAINT_NAME')); DRVQuery.Next; end; end; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_CONSTRAINTS_CHECK), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin DBTable.Constraints.Add(DRVQuery.GetFieldStrValue('CONSTRAINT_NAME')); DRVQuery.Next; end; end; DBTable.Indices.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_INDICES), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin DBTable.Indices.Add(DRVQuery.GetFieldStrValue('INDEX_NAME')); DRVQuery.Next; end; end; if not ExistsPrecision then SQL := FormatSQL(SQL_INIT_TABLE_FIELDS1) else SQL := FormatSQL(SQL_INIT_TABLE_FIELDS3); DBTable.Fields.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL), [DBTable.Caption], False,True) then begin while not DRVQuery.Eof do begin if DBTable.WithoutComputed and DRVQuery.FieldExists('COMPUTED_SOURCE') and (Length(Trim(DRVQuery.GetFieldStrValue('COMPUTED_SOURCE'))) > 0) then begin // skip DRVQuery.Next; Continue; end; DBTable.Fields.Add(DRVQuery.GetFieldStrValue('F_FIELD_NAME')); SetBasedOnDomain(DRVQuery, DBTable.GetField(Pred(DBTable.Fields.Count)) as IibSHDomain, DRVQuery.GetFieldStrValue('F_FIELD_NAME')); DRVQuery.Next; end; end; end; DRVQuery.Transaction.Commit; end else if Assigned(DBField) then begin end else if Assigned(DBConstraint) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT), [DBConstraint.Caption], False,True) then begin DBConstraint.ObjectName := DBConstraint.Caption; DBConstraint.ConstraintType := DRVQuery.GetFieldStrValue('CONSTRAINT_TYPE'); DBConstraint.TableName := DRVQuery.GetFieldStrValue('TABLE_NAME'); DBConstraint.IndexName := DRVQuery.GetFieldStrValue('INDEX_NAME'); if Length(DBConstraint.IndexName) > 0 then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT_INDEX), [DBConstraint.IndexName], False,True) then DBConstraint.IndexSorting := Sortings[DRVQuery.GetFieldIntValue('ASCENDING_')]; end; if SameText(DBConstraint.ConstraintType, 'PRIMARY KEY') or SameText(DBConstraint.ConstraintType, 'UNIQUE') then begin DBConstraint.Fields.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT_FIELDS), [DBConstraint.IndexName], False,True) then begin while not DRVQuery.Eof do begin DBConstraint.Fields.Add(DRVQuery.GetFieldStrValue('FIELD_NAME')); DRVQuery.Next; end; end; DBConstraint.MakePropertyInvisible('ReferenceTable'); DBConstraint.MakePropertyInvisible('ReferenceFields'); DBConstraint.MakePropertyInvisible('OnDeleteRule'); DBConstraint.MakePropertyInvisible('OnUpdateRule'); DBConstraint.MakePropertyInvisible('CheckSource'); end else if SameText(DBConstraint.ConstraintType, 'FOREIGN KEY') then begin DBConstraint.Fields.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT_FIELDS), [DBConstraint.IndexName], False,True) then begin while not DRVQuery.Eof do begin DBConstraint.Fields.Add(DRVQuery.GetFieldStrValue('FIELD_NAME')); DRVQuery.Next; end; end; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT_REFERENCE), [DBConstraint.Caption], False,True) then begin RefConstraint := DRVQuery.GetFieldStrValue('CONST_NAME_UQ'); DBConstraint.OnUpdateRule := DRVQuery.GetFieldStrValue('UPDATE_RULE'); if SameText(DBConstraint.OnUpdateRule, 'RESTRICT') then DBConstraint.OnUpdateRule := ConstraintRules[0]; DBConstraint.OnDeleteRule := DRVQuery.GetFieldStrValue('DELETE_RULE'); if SameText(DBConstraint.OnDeleteRule, 'RESTRICT') then DBConstraint.OnDeleteRule := ConstraintRules[0]; end; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT), [RefConstraint], False,True) then begin DBConstraint.ReferenceTable := DRVQuery.GetFieldStrValue('TABLE_NAME'); RefIndex := DRVQuery.GetFieldStrValue('INDEX_NAME') end; DBConstraint.ReferenceFields.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT_FIELDS), [RefIndex], False,True) then begin while not DRVQuery.Eof do begin DBConstraint.ReferenceFields.Add(DRVQuery.GetFieldStrValue('FIELD_NAME')); DRVQuery.Next; end; end; DBConstraint.MakePropertyInvisible('CheckSource'); end else if SameText(DBConstraint.ConstraintType, 'CHECK') then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_CONSTRAINT_CHECK), [DBConstraint.Caption], False,True) then DBConstraint.CheckSource.Text := TrimRight(DRVQuery.GetFieldStrValue('SOURCE')); DBConstraint.Fields.Text := DBConstraint.CheckSource.Text; DBConstraint.Fields.Text := Trim(AnsiReplaceText(DBConstraint.Fields.Text, 'CHECK', '')); DBConstraint.Fields.Text := AnsiMidStr(Trim(DBConstraint.Fields.Text), 2, Length(Trim(DBConstraint.Fields.Text)) - 2); DBConstraint.CheckSource.Text := DBConstraint.Fields.Text; DBConstraint.Fields.Clear; DBConstraint.MakePropertyInvisible('Fields'); DBConstraint.MakePropertyInvisible('ReferenceTable'); DBConstraint.MakePropertyInvisible('ReferenceFields'); DBConstraint.MakePropertyInvisible('OnUpdateRule'); DBConstraint.MakePropertyInvisible('OnDeleteRule'); DBConstraint.MakePropertyInvisible('IndexName'); DBConstraint.MakePropertyInvisible('IndexSorting'); end; DRVQuery.Transaction.Commit; end; end else if Assigned(DBIndex) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_INDEX), [DBIndex.Caption], False,True) then begin DBIndex.ObjectName := DBIndex.Caption; DBIndex.IndexTypeID := DRVQuery.GetFieldIntValue('UNIQUE_FLAG'); DBIndex.SortingID := DRVQuery.GetFieldIntValue('ASCENDING_'); DBIndex.StatusID := DRVQuery.GetFieldIntValue('IN_ACTIVE'); DBIndex.TableName := DRVQuery.GetFieldStrValue('TABLE_NAME'); DBIndex.Expression.Text := Trim(DRVQuery.GetFieldStrValue('EXPRESSION_SOURCE')); DBIndex.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); DBIndex.Statistics := FloatToStrF(DRVQuery.GetFieldFloatValue('STATISTIC'), ffNumber, 15, 15); if DRVQuery.ExecSQL(FormatSQL(SQL_IS_CONSTRAINT_INDEX), [DBIndex.Caption], False,True) then DBIndex.IsConstraintIndex:=DRVQuery.GetFieldIntValue(0)>0 else DBIndex.IsConstraintIndex:=False; DBIndex.IndexType := IndexTypes[DBIndex.IndexTypeID]; DBIndex.Sorting := Sortings[DBIndex.SortingID]; DBIndex.Status := Statuses[DBIndex.StatusID]; DBIndex.Fields.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_INDEX_FIELDS), [DBIndex.Caption], False,True) then begin while not DRVQuery.Eof do begin DBIndex.Fields.Add(DRVQuery.GetFieldStrValue('FIELD_NAME')); DRVQuery.Next; end; end; DRVQuery.Transaction.Commit; end; end else if Assigned(DBView) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_VIEW), [DBView.Caption], False,True) then begin DBView.ObjectName := DBView.Caption; DBView.OwnerName := DRVQuery.GetFieldStrValue('OWNER_NAME'); DBView.BodyText.Text := TrimRight(DRVQuery.GetFieldStrValue('SOURCE')); DBView.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); if not ExistsPrecision then SQL := FormatSQL(SQL_INIT_TABLE_FIELDS1) else SQL := FormatSQL(SQL_INIT_TABLE_FIELDS3); DBView.Fields.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL), [DBView.Caption], False,True) then begin while not DRVQuery.Eof do begin DBView.Fields.Add(DRVQuery.GetFieldStrValue('F_FIELD_NAME')); SetBasedOnDomain(DRVQuery, DBView.GetField(Pred(DBView.Fields.Count)) as IibSHDomain, DRVQuery.GetFieldStrValue('F_FIELD_NAME')); DRVQuery.Next; end; end; DBView.Triggers.Clear; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TABLE_TRIGGERS), [DBView.Caption], False,True) then begin while not DRVQuery.Eof do begin DBView.Triggers.Add(DRVQuery.GetFieldStrValue('TRIGGER_NAME')); DRVQuery.Next; end; end; DRVQuery.Transaction.Commit; end; end else if Assigned(DBProcedure) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_PROCEDURE), [DBProcedure.Caption], False,True) then begin DBProcedure.ObjectName := DBProcedure.Caption; DBProcedure.OwnerName := DRVQuery.GetFieldStrValue('OWNER_NAME'); DBProcedure.BodyText.Text := TrimRight(DRVQuery.GetFieldStrValue('SOURCE')); DBProcedure.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); if not ExistsPrecision then SQL := FormatSQL(SQL_INIT_PROCEDURE_PARAMS1) else if not FExistsProcParamDomains then SQL := FormatSQL(SQL_INIT_PROCEDURE_PARAMS3) else SQL := FormatSQL(SQL_INIT_PROCEDURE_PARAMS4); DBProcedure.Params.Clear; DBProcedure.ParamsExt.Clear; if DRVQuery.ExecSQL(SQL, [DBProcedure.Caption, 0], False,True) then begin while not DRVQuery.Eof do begin DBProcedure.Params.Add(DRVQuery.GetFieldStrValue('PARAMETER_NAME')); SetBasedOnDomain(DRVQuery, DBProcedure.GetParam(Pred(DBProcedure.Params.Count)) as IibSHDomain, DRVQuery.GetFieldStrValue('PARAMETER_NAME') ); DRVQuery.Next; end; end; DBProcedure.Returns.Clear; DBProcedure.ReturnsExt.Clear; if DRVQuery.ExecSQL(SQL, [DBProcedure.Caption, 1], False,True) then begin while not DRVQuery.Eof do begin DBProcedure.Returns.Add(DRVQuery.GetFieldStrValue('PARAMETER_NAME')); SetBasedOnDomain(DRVQuery, DBProcedure.GetReturn(Pred(DBProcedure.Returns.Count)) as IibSHDomain, DRVQuery.GetFieldStrValue('PARAMETER_NAME')); DRVQuery.Next; end; end; DRVQuery.Transaction.Commit; end; MaxStrLength := GetMaxStrLength(DBProcedure.Params); for I := 0 to Pred(DBProcedure.Params.Count) do with DBProcedure do begin S:=GetParam(I).DataTypeField; S1:=NormalizeName(Params[I]); S:=Trim(Format('%s %s %s %s',[S1, SpaceGenerator(MaxStrLength, S1),S , Trim(GetParam(I).DefaultExpression.Text)])); if I <> Pred(DBProcedure.Params.Count) then ParamsExt.Add(S+',') else ParamsExt.Add(S); end; MaxStrLength := GetMaxStrLength(DBProcedure.Returns); for I := 0 to Pred(DBProcedure.Returns.Count) do with DBProcedure do begin S:=GetReturn(I).DataTypeField; S1:=NormalizeName(Returns[I]); S:=Trim(Format('%s %s %s %s',[S1,SpaceGenerator(MaxStrLength, S1) ,S , Trim(GetReturn(I).DefaultExpression.Text)])); if I <> Pred(DBProcedure.Returns.Count) then DBProcedure.ReturnsExt.Add(S+',') else DBProcedure.ReturnsExt.Add(S) end; end else if Assigned(DBTrigger) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_TRIGGER), [DBTrigger.Caption], False,True) then begin DBTrigger.ObjectName := DBTrigger.Caption; DBTrigger.TableName := DRVQuery.GetFieldStrValue('TABLE_NAME'); DBTrigger.Position := DRVQuery.GetFieldIntValue('POSITION1'); DBTrigger.BodyText.Text := TrimRight(DRVQuery.GetFieldStrValue('SOURCE')); DBTrigger.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); Active := DRVQuery.GetFieldIntValue('IN_ACTIVE'); TriggerTypeID := DRVQuery.GetFieldIntValue('TRIGGER_TYPE_ID'); DRVQuery.Transaction.Commit; if IntToBooleanInvers(Active) then DBTrigger.Status := Statuses[0] else DBTrigger.Status := Statuses[1]; vSuf := ''; vDelim := ''; if (Length(DBTrigger.TableName)=0) then begin DBTrigger.TypePrefix := 'ON'; case Byte(TriggerTypeID) of 0:vSuf :=' CONNECT '; 1:vSuf :=' DISCONNECT '; 2:vSuf :=' TRANSACTION START '; 3:vSuf :=' TRANSACTION COMMIT '; 4:vSuf :=' TRANSACTION ROLLBACK '; end end else begin DBTrigger.TypePrefix := TypePrefixes[(TriggerTypeID + 1) and 1]; for I := 0 to 2 do case (((TriggerTypeID + 1) shr sh[I]) and 3) of 1: begin vSuf := 'INSERT'; vDelim := ' OR '; end; 2: begin if System.Length(vSuf) > 0 then vSuf := vSuf + vDelim + 'UPDATE' else begin vSuf := 'UPDATE'; vDelim := ' OR '; end; end; 3: begin if System.Length(vSuf) > 0 then vSuf := vSuf + vDelim + 'DELETE' else vSuf := 'DELETE'; end; end; end; DBTrigger.TypeSuffix := vSuf; end; end else if Assigned(DBGenerator) then begin if DRVQuery.ExecSQL(Format(FormatSQL(SQL_INIT_GENERATOR), [NormalizeName(DBGenerator.Caption)]), [], False) then begin DBGenerator.ObjectName := DBGenerator.Caption; DBGenerator.Value := DRVQuery.GetFieldInt64Value(0); DRVQuery.Transaction.Commit; end; end else if Assigned(DBException) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_EXCEPTION), [DBException.Caption], False,True) then begin DBException.ObjectName := DBException.Caption; DBException.Text := DRVQuery.GetFieldStrValue('TEXT'); DBException.Number := DRVQuery.GetFieldIntValue('NUMBER_'); DBException.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); DRVQuery.Transaction.Commit; end; end else if Assigned(DBFunction) then begin I := 0; if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_FUNCTION), [DBFunction.Caption], False,True) then begin DBFunction.ObjectName := DBFunction.Caption; DBFunction.EntryPoint := DRVQuery.GetFieldStrValue('ENTRYPOINT'); DBFunction.ModuleName := DRVQuery.GetFieldStrValue('MODULENAME'); DBFunction.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); ReturnsParamPos := DRVQuery.GetFieldIntValue('RETURN_ARGUMENT'); DBFunction.ReturnsArgument := ReturnsParamPos; if not ExistsPrecision then SQL := FormatSQL(SQL_INIT_FUNCTION_ARGUMENTS1) else SQL := FormatSQL(SQL_INIT_FUNCTION_ARGUMENTS3); DBFunction.Params.Clear; DBFunction.Returns.Clear; if DRVQuery.ExecSQL(SQL, [DBFunction.Caption], False,True) then begin while not DRVQuery.Eof do begin DBFunction.Params.Add(' '); SetBasedOnDomain(DRVQuery, DBFunction.GetParam(Pred(DBFunction.Params.Count)) as IibSHDomain, EmptyStr); DBFunction.Params[I] := DBFunction.GetParam(I).DataTypeExt; Mechanism := DRVQuery.GetFieldIntValue('MECHANISM'); case Mechanism of -1: DBFunction.Params[I] := Format('%s %s', [DBFunction.Params[I], 'FREE_IT']); 0: DBFunction.Params[I] := Format('%s %s', [DBFunction.Params[I], 'BY VALUE']); 2: DBFunction.Params[I] := Format('%s %s', [DBFunction.Params[I], 'BY DESCRIPTOR']); end; Inc(I); DRVQuery.Next; end; end; DRVQuery.Transaction.Commit; if ReturnsParamPos = 0 then begin DBFunction.Returns.Add(DBFunction.Params[0]); DBFunction.Params.Delete(0); end else DBFunction.Returns.Add(Format('PARAMETER %d', [DBFunction.ReturnsArgument])); end; end else if Assigned(DBFilter) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_FILTER), [DBFilter.Caption], False,True) then begin DBFilter.ObjectName := DBFilter.Caption; DBFilter.InputType := DRVQuery.GetFieldIntValue('INPUT_SUB_TYPE'); DBFilter.OutputType := DRVQuery.GetFieldIntValue('OUTPUT_SUB_TYPE'); DBFilter.EntryPoint := DRVQuery.GetFieldStrValue('ENTRYPOINT'); DBFilter.ModuleName := DRVQuery.GetFieldStrValue('MODULENAME'); DBFilter.Description.Text := Trim(DRVQuery.GetFieldStrValue('DESCRIPTION')); DRVQuery.Transaction.Commit; end; end else if Assigned(DBRole) then begin if DRVQuery.ExecSQL(FormatSQL(SQL_INIT_ROLE), [DBRole.Caption], False,True) then begin DBRole.ObjectName := DBRole.Caption; DBRole.OwnerName := DRVQuery.GetFieldStrValue('OWNER_NAME'); DRVQuery.Transaction.Commit; end; end else if Assigned(DBShadow) then begin end else if Assigned(DBQuery) and Assigned(DBQuery.Data) then begin DBQuery.ObjectName := 'EMPTY';; DBQuery.OwnerName := 'EMPTY'; DBQuery.Description.Text := 'EMPTY'; if not ExistsPrecision then SQL := FormatSQL(SQL_INIT_QUERY_FIELDS1) else SQL := FormatSQL(SQL_INIT_QUERY_FIELDS3); DBQuery.Fields.Clear; for I := 0 to Pred(DBQuery.Data.Dataset.Dataset.FieldCount) do begin //if DBQuery.Data.Dataset.GetRelationFieldName(I) = 'DB_KEY' then Continue; if (DBQuery.Data.Dataset.Dataset.Fields[I].FieldKind <> fkCalculated) and (Length(Trim(DBQuery.Data.Dataset.GetRelationTableName(I))) > 0) then begin if DRVQuery.ExecSQL(FormatSQL(SQL), [DBQuery.Data.Dataset.GetRelationTableName(I), DBQuery.Data.Dataset.GetRelationFieldName(I)], False,True) then begin DBQuery.Fields.Add(DBQuery.Data.Dataset.Dataset.Fields[I].FieldName); SetBasedOnDomain(DRVQuery, DBQuery.GetField(Pred(DBQuery.Fields.Count)) as IibSHDomain, DRVQuery.GetFieldStrValue('F_FIELD_NAME')); end end else begin DBQuery.Fields.Add(DBQuery.Data.Dataset.Dataset.Fields[I].FieldName); varDomain := DBQuery.GetField(Pred(DBQuery.Fields.Count)) as IibSHDomain; varPrecision := 0; with varDomain do case DBQuery.Data.Dataset.Dataset.Fields[I].DataType of ftSmallint: begin Scale := 0; SubTypeID := 0; DataType := Get_SMALLINT(varPrecision, Scale, SubTypeID); DataTypeExt := Get_SMALLINT(varPrecision, Scale, SubTypeID); end; ftInteger, ftWord, ftAutoInc: begin Scale := 0; SubTypeID := 0; DataType := Get_INTEGER(varPrecision, Scale, SubTypeID); DataTypeExt := Get_INTEGER(varPrecision, Scale, SubTypeID); end; ftLargeint: begin Scale := 0; SubTypeID := 0; DataType := Get_BIGINT(varPrecision, Scale, SubTypeID); DataTypeExt := Get_BIGINT(varPrecision, Scale, SubTypeID); end; ftBoolean: begin DataType := Get_BOOLEAN; DataTypeExt := Get_BOOLEAN; end; ftFloat: begin if DBQuery.Data.Dataset.Dataset.Fields[I].Size > 9 then begin Scale := 9; DataType := Get_FLOAT(varPrecision, Scale, False); DataTypeExt := Get_FLOAT(varPrecision, Scale, True); end else begin varPrecision := (DBQuery.Data.Dataset.Dataset.Fields[I] as TFloatField).Precision; Scale := DBQuery.Data.Dataset.Dataset.Fields[I].Size; DataType := Get_FLOAT(varPrecision, Scale); DataTypeExt := Get_FLOAT(varPrecision, Scale, True); end; end; ftBCD, ftFMTBcd: begin varPrecision := (DBQuery.Data.Dataset.Dataset.Fields[I] as TBCDField).Precision; Scale := DBQuery.Data.Dataset.Dataset.Fields[I].Size; DataType := Get_DOUBLE(varPrecision, Scale); DataTypeExt := Get_DOUBLE(varPrecision, Scale, True); end; ftDate: begin DataType := Get_DATE; DataTypeExt := Get_DATE; end; ftTime: begin DataType := Get_TIME; DataTypeExt := Get_TIME; end; ftDateTime, ftTimeStamp: begin DataType := Get_TIMESTAMP(Dialect); DataTypeExt := Get_TIMESTAMP(Dialect); end; (*_CHAR: begin ADomain.DataType := Get_CHAR(ADomain.Length); ADomain.DataTypeExt := Get_CHAR(ADomain.Length, True); end;*) ftString: begin Length := (DBQuery.Data.Dataset.Dataset.Fields[I] as TStringField).Size; DataType := Get_VARCHAR(Length); DataTypeExt := Get_VARCHAR(Length, True); end; ftMemo: begin SubTypeID := 1; SegmentSize := 0; DataType := Get_BLOB(SubTypeID, SegmentSize); DataTypeExt := Get_BLOB(SubTypeID, SegmentSize, True); Charset := EmptyStr; Collate := EmptyStr end; ftBlob, ftGraphic, ftFmtMemo: begin SubTypeID := 0; SegmentSize := 0; DataType := Get_BLOB(SubTypeID, SegmentSize); DataTypeExt := Get_BLOB(SubTypeID, SegmentSize, True); Charset := EmptyStr; Collate := EmptyStr end; (*_CSTRING: begin ADomain.DataType := Get_CSTRING(ADomain.Length); ADomain.DataTypeExt := Get_CSTRING(ADomain.Length, True); end; _QUAD: begin ADomain.DataType := Get_QUAD; ADomain.DataTypeExt := Get_QUAD; end;*) ftUnknown, ftCurrency, ftBytes, ftVarBytes, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar, ftWideString, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, ftVariant, ftInterface, ftIDispatch, ftGuid: begin DataType := 'UNKNOWN'; DataTypeExt := 'UNKNOWN'; end; end; end; end; DRVQuery.Transaction.Commit; end; end; function TibBTDDLGenerator.ReplaceNameConsts(const ADDLText, ACaption: string): string; var FileName: string; ConstList: TStrings; I: Integer; S: string; begin FileName := Format('%s%s\ObjectNameRtns.txt', [(Designer.GetDemon(DBObject.BranchIID) as ISHDataRootDirectory).DataRootDirectory, 'Repository\DDL']); ConstList := TStringList.Create; try if FileExists(FileName) then begin ConstList.LoadFromFile(FileName); Result := AnsiReplaceText(ADDLText, '{NAME}', NormalizeName(ACaption)); if Assigned(DBTable) then begin if Pos('{TABLE_NAME}', Result) > 0 then Result := AnsiReplaceText(Result, '{TABLE_NAME}', NormalizeName(ACaption)); for I := 0 to Pred(ConstList.Count) do begin S := ConstList.Names[I]; if Pos(S, Result) > 0 then Result := AnsiReplaceText(Result, S, NormalizeName2(AnsiReplaceText(ConstList.ValueFromIndex[I], '{TABLE_NAME}', ACaption))); end; end; if Assigned(DBField) then begin if (Pos('{TABLE_NAME}', Result) > 0) and (Length(DBField.TableName) > 0) then Result := AnsiReplaceText(Result, '{TABLE_NAME}', NormalizeName(DBField.TableName)); for I := 0 to Pred(ConstList.Count) do begin S := ConstList.Names[I]; if Pos(S, Result) > 0 then begin if Length(DBField.TableName) > 0 then Result := AnsiReplaceText(Result, S, NormalizeName2(AnsiReplaceText(ConstList.ValueFromIndex[I], '{TABLE_NAME}', DBField.TableName))) else Result := AnsiReplaceText(Result, S, ConstList.ValueFromIndex[I]); end; end; end; if Assigned(DBConstraint) then begin if (Pos('{TABLE_NAME}', Result) > 0) and (Length(DBConstraint.TableName) > 0) then Result := AnsiReplaceText(Result, '{TABLE_NAME}', NormalizeName(DBConstraint.TableName)); for I := 0 to Pred(ConstList.Count) do begin S := ConstList.Names[I]; if Pos(S, Result) > 0 then begin if Length(DBConstraint.TableName) > 0 then Result := AnsiReplaceText(Result, S, NormalizeName2(AnsiReplaceText(ConstList.ValueFromIndex[I], '{TABLE_NAME}', DBConstraint.TableName))) else Result := AnsiReplaceText(Result, S, ConstList.ValueFromIndex[I]); end; end; end; if Assigned(DBIndex) then begin if (Pos('{TABLE_NAME}', Result) > 0) and (Length(DBIndex.TableName) > 0) then Result := AnsiReplaceText(Result, '{TABLE_NAME}', NormalizeName(DBIndex.TableName)); for I := 0 to Pred(ConstList.Count) do begin S := ConstList.Names[I]; if Pos(S, Result) > 0 then begin if Length(DBIndex.TableName) > 0 then Result := AnsiReplaceText(Result, S, NormalizeName2(AnsiReplaceText(ConstList.ValueFromIndex[I], '{TABLE_NAME}', DBIndex.TableName))) else Result := AnsiReplaceText(Result, S, ConstList.ValueFromIndex[I]); end; end; end; if Assigned(DBTrigger) then begin if (Pos('{TABLE_NAME}', Result) > 0) and (Length(DBTrigger.TableName) > 0) then Result := AnsiReplaceText(Result, '{TABLE_NAME}', NormalizeName(DBTrigger.TableName)); for I := 0 to Pred(ConstList.Count) do begin S := ConstList.Names[I]; if Pos(S, Result) > 0 then begin if Length(DBTrigger.TableName) > 0 then Result := AnsiReplaceText(Result, S, NormalizeName2(AnsiReplaceText(ConstList.ValueFromIndex[I], '{TABLE_NAME}', DBTrigger.TableName))) else Result := AnsiReplaceText(Result, S, ConstList.ValueFromIndex[I]); end; end; end; end; finally ConstList.Free; end; (* {GENERATOR_NAME}=GEN_{TABLE_NAME}_ID {TRIGGER_NAME}=TR_{TABLE_NAME}_BI {PRIMARY_KEY_NAME}=PK_{TABLE_NAME} {FOREIGN_KEY_NAME}=FK_{TABLE_NAME} {UNIQUE_NAME}=UNQ_{TABLE_NAME} {CHECK_NAME}=CHK_{TABLE_NAME} {INDEX_NAME}=IDX_{TABLE_NAME} *) end; procedure TibBTDDLGenerator.SetFakeValues(DDL: TStrings; FileName:string=''); var ACaption: string; begin if FileName='' then FileName := Format('%s%s\%s\Default.txt', [(Designer.GetDemon(DBObject.BranchIID) as ISHDataRootDirectory).DataRootDirectory, 'Repository\DDL', GUIDToName(DBObject.ClassIID, 1)] ) else FileName := Format('%s%s\%s\'+FileName, [(Designer.GetDemon(DBObject.BranchIID) as ISHDataRootDirectory).DataRootDirectory, 'Repository\DDL', GUIDToName(DBObject.ClassIID, 1)] ); if State = csCreate then if FileExists(FileName) then begin ACaption := DBObject.Caption; DDL.LoadFromFile(FileName); if (Pos('{NAME}', DDL.Text) > 0) then begin // Buzz //if Designer.InputQuery(Format('%s', [SLoadingDefaultTemplate]), Format('%s', [SObjectNameNew]), ACaption{, False}) and (Length(ACaption) > 0) then begin if Assigned(CodeNormalizer) then ACaption := CodeNormalizer.InputValueToMetadata(DBObject.BTCLDatabase, ACaption); DBObject.Caption := ACaption; end;// else // DDL.Clear; end; if Length(DDL.Text) > 0 then DDL.Text := ReplaceNameConsts(DDL.Text, ACaption); end; end; procedure TibBTDDLGenerator.SetDDLFromValues(DDL: TStrings); var I, MaxStrLength: Integer; S: string; S1, C1: string; B,B1,B2:Boolean; vTable:IibSHTable; iField:IibSHField; begin (* Код переехал в DDLForm if (State = csCreate) or (State = csRecreate) then begin // здесь(?) проверить на наличие зарегистрированного визивинг редактора case State of csCreate: C := SChangeDefaultName; csRecreate: C := SChangeCurrentName; end; S := DBObject.Caption; if Designer.InputQuery(Format('%s', [C]), Format('%s', [SObjectNameNew]), S{, False}) and (Length(S) > 0) then begin if Assigned(CodeNormalizer) then S := CodeNormalizer.InputValueToMetadata(DBObject.BTCLDatabase, S); DBObject.Caption := S; end else begin DDL.Text := 'User Cancel'; // do not localize Exit; end; end; *) if Assigned(DBDomain) then begin if DBDomain.UseCustomValues then begin DBDomain.DataTypeExt := DBDomain.DataType; DBDomain.FieldTypeID := GetFieldTypeID(DBDomain.DataType); if AnsiContainsText(DBDomain.DataType, 'NUMERIC') or AnsiContainsText(DBDomain.DataType, 'DECIMAL') then DBDomain.DataTypeExt := Format('%s(%d, %d)', [DBDomain.DataType, DBDomain.Precision, DBDomain.Scale]) else if AnsiContainsText(DBDomain.DataType, 'CHAR') or AnsiContainsText(DBDomain.DataType, 'VARCHAR') then DBDomain.DataTypeExt := Format('%s(%d)', [DBDomain.DataType, DBDomain.Length]) else if AnsiContainsText(DBDomain.DataType, 'BLOB') then DBDomain.DataTypeExt := Format('%s SUB_TYPE %d SEGMENT SIZE %d', [DBDomain.DataType, BlobSubTypeToID(DBDomain.SubType), DBDomain.SegmentSize]); end; case State of csSource, csCreate, csRecreate: begin DDL.Add(Format('CREATE DOMAIN %s AS', [NormalizeName(DBDomain.Caption)])); DDL.Add(DBDomain.DataTypeExt); case DBDomain.FieldTypeID of _SMALLINT, _INTEGER, _BIGINT, _BOOLEAN, _FLOAT, _DOUBLE, _DATE, _TIME, _TIMESTAMP, _CHAR, _VARCHAR: if Length(DBDomain.ArrayDim) > 0 then DDL.Strings[Pred(DDL.Count)] := Format('%s %s', [DDL.Strings[Pred(DDL.Count)], DBDomain.ArrayDim]); end; case DBDomain.FieldTypeID of _CHAR, _VARCHAR: begin if (Length(DBDomain.Charset) > 0) and (not AnsiSameText(DBDomain.Charset, DBCharset) or not AnsiSameText(DBDomain.Charset, DBDomain.Collate)) then DDL.Strings[Pred(DDL.Count)] := Format('%s CHARACTER SET %s', [DDL.Strings[Pred(DDL.Count)], DBDomain.Charset]); end; _BLOB: begin if AnsiSameText(DBDomain.SubType, BlobSubTypes[1]) and (Length(DBDomain.Charset) > 0) and not AnsiSameText(DBDomain.Charset, DBCharset) then DDL.Strings[Pred(DDL.Count)] := Format('%s CHARACTER SET %s', [DDL.Strings[Pred(DDL.Count)], DBDomain.Charset]); end; end; if Length(DBDomain.DefaultExpression.Text) > 0 then case State of csSource, csCreate, csRecreate: DDL.Add(Format('DEFAULT %s', [Trim(DBDomain.DefaultExpression.Text)])); csAlter:; end; if System.Length(DBDomain.NullType) > 0 then DDL.Add(DBDomain.NullType); if Length(DBDomain.CheckConstraint.Text) > 0 then case State of csSource, csCreate, csRecreate: DDL.Add(Format('CHECK (%s)', [Trim(DBDomain.CheckConstraint.Text)])); csAlter:; end; case DBDomain.FieldTypeID of _CHAR, _VARCHAR: if (Length(DBDomain.Collate) > 0) and not AnsiSameText(DBDomain.Charset, DBDomain.Collate) then DDL.Add(Format('COLLATE %s', [DBDomain.Collate])); end; DDL.Strings[Pred(DDL.Count)] := DDL.Strings[Pred(DDL.Count)] + FTerminator; if (DBDomain.DataType = 'SMALLINT') or (DBDomain.DataType = 'INTEGER') or (DBDomain.DataType = 'BOOLEAN') or (DBDomain.DataType = 'BIGINT') or (DBDomain.DataType = 'FLOAT') or (DBDomain.DataType = 'DOUBLE PRECISION') or (DBDomain.DataType = 'DATE') or (DBDomain.DataType = 'TIME') or (DBDomain.DataType = 'TIMESTAMP') then begin DBDomain.MakePropertyInvisible('Length'); DBDomain.MakePropertyInvisible('Precision'); DBDomain.MakePropertyInvisible('Scale'); DBDomain.MakePropertyInvisible('Charset'); DBDomain.MakePropertyInvisible('Collate'); DBDomain.MakePropertyInvisible('SubType'); DBDomain.MakePropertyInvisible('SegmentSize'); end else if (DBDomain.DataType = 'NUMERIC') or (DBDomain.DataType = 'DECIMAL') then begin DBDomain.MakePropertyInvisible('Length'); DBDomain.MakePropertyInvisible('Charset'); DBDomain.MakePropertyInvisible('Collate'); DBDomain.MakePropertyInvisible('SubType'); DBDomain.MakePropertyInvisible('SegmentSize'); end else if (DBDomain.DataType = 'CHAR') or (DBDomain.DataType = 'VARCHAR') then begin DBDomain.MakePropertyInvisible('Precision'); DBDomain.MakePropertyInvisible('Scale'); DBDomain.MakePropertyInvisible('SubType'); DBDomain.MakePropertyInvisible('SegmentSize'); end else if (DBDomain.DataType = 'BLOB') then begin DBDomain.MakePropertyInvisible('Length'); DBDomain.MakePropertyInvisible('Precision'); DBDomain.MakePropertyInvisible('Scale'); if DBDomain.SubTypeID <> 1 then DBDomain.MakePropertyInvisible('Charset'); DBDomain.MakePropertyInvisible('Collate'); DBDomain.MakePropertyInvisible('ArrayDim'); end; end; csAlter: begin if DBDomain.UseCustomValues then begin if DBDomain.NameWasChanged or DBDomain.DataTypeWasChanged or DBDomain.DefaultWasChanged or DBDomain.CheckWasChanged then begin DDL.Add(Format('ALTER DOMAIN %s', [NormalizeName(DBDomain.ObjectName)])); // SetFakeValues if DBDomain.NameWasChanged then begin DDL.Add(Format('TO %s', [NormalizeName(DBDomain.Caption)])); end; if DBDomain.DataTypeWasChanged then begin DDL.Add(Format('TYPE %s', [DBDomain.DataTypeExt])); end; if DBDomain.DefaultWasChanged then begin if Length(Trim(DBDomain.DefaultExpression.Text)) > 0 then DDL.Add(Format('SET DEFAULT %s', [Trim(DBDomain.DefaultExpression.Text)])) else DDL.Add(Format('DROP DEFAULT', [])); end; if DBDomain.CheckWasChanged then begin DDL.Add(Format('DROP CONSTRAINT', [])); DDL.Add(FTerminator); if Length(Trim(DBDomain.CheckConstraint.Text)) > 0 then begin DDL.Add(''); DDL.Add(Format('ALTER DOMAIN %s', [NormalizeName(DBDomain.ObjectName)])); DDL.Add(Format('ADD CONSTRAINT CHECK (%s)', [Trim(DBDomain.CheckConstraint.Text)])); DDL.Add(FTerminator); end; end else DDL.Add(FTerminator); end; if DBDomain.NullTypeWasChanged then begin if Length(DDL.Text) > 0 then DDL.Add(''); if Length(DBDomain.NullType) > 0 then begin DDL.Add(Format('UPDATE RDB$FIELDS F', [])); DDL.Add(Format('SET F.RDB$NULL_FLAG = 1 /* <- NOT NULL */', [])); DDL.Add(Format('WHERE F.RDB$FIELD_NAME = ''%s''', [DBDomain.ObjectName])); DDL.Add(FTerminator); end else begin DDL.Add(Format('UPDATE RDB$FIELDS F', [])); DDL.Add(Format('SET F.RDB$NULL_FLAG = NULL', [])); DDL.Add(Format('WHERE F.RDB$FIELD_NAME = ''%s''', [DBDomain.ObjectName])); DDL.Add(FTerminator); end; end; if DBDomain.CollateWasChanged then begin if Length(DDL.Text) > 0 then DDL.Add(''); DDL.Add(Format('UPDATE RDB$FIELDS F', [])); DDL.Add(Format('SET F.RDB$COLLATION_ID = %d /* <- %s */', [DBDomain.CollateID, DBDomain.Collate])); DDL.Add(Format('WHERE F.RDB$FIELD_NAME = ''%s''', [DBDomain.ObjectName])); DDL.Add(FTerminator); end; end else begin DDL.Add(Format('ALTER DOMAIN %s', [NormalizeName(DBDomain.Caption)])); DDL.Add('/* TO <new_domain_name> TYPE <data_type> */'); DDL.Add('/*DROP DEFAULT*/'); DDL.Add('/* SET DEFAULT {literal | NULL | USER} */'); DDL.Add('/*DROP CONSTRAINT*/'); DDL.Add('/* ADD CONSTRAINT CHECK (VALUE <operator> <val> | IS [NOT] NULL) */'); DDL.Add(FTerminator); end end; end; end else if Assigned(DBTable) then begin case State of csSource, csCreate, csRecreate,csRelatedSource: begin MaxStrLength := GetMaxStrLength(DBTable.Fields); if Length(DBTable.ExternalFile)>0 then DDL.Add(Format('CREATE TABLE %s EXTERNAL %s(', [NormalizeName(DBTable.Caption),''''+DBTable.ExternalFile+''''])) else DDL.Add(Format('CREATE TABLE %s(', [NormalizeName(DBTable.Caption)])); if (State=csCreate) and (DBTable.Fields.Count=0) then begin DDL.Add(' <field_def>,'); DDL.Add(' <field_def>...'); // DDL.Add('/* ADD CONSTRAINT <constraint_def> */'); end else for I := 0 to Pred(DBTable.Fields.Count) do begin S:=NormalizeName(DBTable.Fields[I]); iField:=DBTable.GetField(I); if (State in [csSource,csRelatedSource]) and DBTable.DecodeDomains then begin if I <> Pred(DBTable.Fields.Count) then DDL.Add(Format(SDDLOffset + '%s%s%s,', [S, SpaceGenerator(MaxStrLength, S), iField.DataTypeFieldExt])) else DDL.Add(Format(SDDLOffset + '%s%s%s', [S, SpaceGenerator(MaxStrLength, S), iField.DataTypeFieldExt])); end else begin if I <> Pred(DBTable.Fields.Count) then DDL.Add(Format(SDDLOffset + '%s%s%s,', [S, SpaceGenerator(MaxStrLength, S), iField.DataTypeField])) else DDL.Add(Format(SDDLOffset + '%s%s%s', [S, SpaceGenerator(MaxStrLength, S), iField.DataTypeField])); end; // SourceDDL for Field (!!!) iField.SourceDDL.Text := Format('ALTER TABLE %s ADD %s%s %s%s', [NormalizeName(iField.TableName), SLineBreak, s, iField.DataTypeField, FTerminator]); end; DDL.Add(')' + FTerminator); { TODO : DDL таблицы } vTable:=DBTable; // if State=csRelatedSource then if State in [csRecreate,csRelatedSource] then begin if vTable.Constraints.Count>0 then begin B:=True; B1:=True; B2:=True; for I:=0 to Pred(vTable.Constraints.Count) do begin if vTable.GetConstraint(I).ConstraintType='PRIMARY KEY' then begin DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Primary Keys */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); end else if vTable.GetConstraint(I).ConstraintType='UNIQUE' then begin if B then begin DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Unique constraints */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); B:=False end; end else if vTable.GetConstraint(I).ConstraintType='FOREIGN KEY' then begin if B1 then begin DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Foreign Keys */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); B1:=False end end else if vTable.GetConstraint(I).ConstraintType='CHECK' then begin if B2 then begin DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Check constraints */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); B2:=False end end; DDL.AddStrings( vTable.GetConstraint(I).SourceDDL); end; end; if vTable.Indices.Count>0 then begin B:=True; for I:=0 to Pred(vTable.Indices.Count) do if not vTable.GetIndex(I).IsConstraintIndex then begin if B then begin B:=False; DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Indices */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); end; DDL.AddStrings( vTable.GetIndex(I).SourceDDL); end; end; if vTable.Triggers.Count>0 then begin DDL.Add(''); FTerminator:='^'; DDL.Add('SET TERM ^ ;'); DDL.Add(''); DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Triggers */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); for I:=0 to Pred(vTable.Triggers.Count) do begin DDL.AddStrings( vTable.GetTrigger(I).SourceDDL ); DDL[DDL.Count-1]:=FTerminator; DDL.Add(''); end; end; B:=False; B:=(vTable.Description.Count>0); if not B then For I:=0 to Pred(vTable.Fields.Count) do if vTable.GetField(i).Description.Count>0 then begin B:=True; Break end; if B then begin DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Descriptions */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); if vTable.Description.Count>0 then DDL.Add(vTable.GetDescriptionStatement(False)); for I:=0 to Pred(vTable.Fields.Count) do if vTable.GetField(i).Description.Count>0 then begin DDL.Add(vTable.GetField(i).GetDescriptionStatement(False)); DDL.Add(''); end; end; vTable:=nil; FTerminator:=';' end; end; csAlter: begin DDL.Add(Format('ALTER TABLE %s', [NormalizeName(DBTable.Caption)])); DDL.Add(' ADD <field_def>,'); DDL.Add(' ADD <field_def>...'); DDL.Add('/* ADD CONSTRAINT <constraint_def> */'); DDL.Add('/* DROP <field_name> */'); DDL.Add('/* DROP CONSTRAINT <constraint_name> */'); DDL.Add(FTerminator); end; end; end; if Assigned(DBField) then begin case State of csSource, csCreate, csRecreate: begin if DBField.UseCustomValues then begin // DDL.Add(Format('ALTER TABLE %s ADD', [NormalizeName(DBField.TableName)])); // Domain if Length(DBField.Domain) > 0 then begin DDL.Add(Format('%s %s', [NormalizeName(DBField.Caption), DBField.Domain])); if Length(DBField.FieldDefault.Text) > 0 then DDL.Add(Format('DEFAULT %s', [Trim(DBField.FieldDefault.Text)])); if Length(DBField.FieldNullType) > 0 then DDL.Add(Format('%s', [DBField.FieldNullType])); if Length(DBField.FieldCollate) > 0 then DDL.Add(Format('COLLATE %s', [DBField.FieldCollate])); DDL.Strings[Pred(DDL.Count)] := DDL.Strings[Pred(DDL.Count)] + FTerminator; Exit; end; // DataType if Length(DBField.DataType) > 0 then begin DBField.DataTypeExt := DBField.DataType; DBField.FieldTypeID := GetFieldTypeID(DBField.DataType); if AnsiContainsText(DBField.DataType, 'NUMERIC') or AnsiContainsText(DBField.DataType, 'DECIMAL') then DBField.DataTypeExt := Format('%s(%d, %d)', [DBField.DataType, DBField.Precision, DBField.Scale]) else if AnsiContainsText(DBField.DataType, 'CHAR') or AnsiContainsText(DBField.DataType, 'VARCHAR') then DBField.DataTypeExt := Format('%s(%d)', [DBField.DataType, DBField.Length]) else if AnsiContainsText(DBField.DataType, 'BLOB') then DBField.DataTypeExt := Format('%s SUB_TYPE %d SEGMENT SIZE %d', [DBField.DataType, BlobSubTypeToID(DBField.SubType), DBField.SegmentSize]); DDL.Add(Format('%s %s', [NormalizeName(DBField.Caption), DBField.DataTypeExt])); case DBField.FieldTypeID of _SMALLINT, _INTEGER, _BIGINT, _BOOLEAN, _FLOAT, _DOUBLE, _DATE, _TIME, _TIMESTAMP, _CHAR, _VARCHAR: if Length(DBField.ArrayDim) > 0 then DDL.Strings[Pred(DDL.Count)] := Format('%s %s', [DDL.Strings[Pred(DDL.Count)], DBField.ArrayDim]); end; case DBField.FieldTypeID of _CHAR, _VARCHAR: begin if (Length(DBField.Charset) > 0) and (not AnsiSameText(DBField.Charset, DBCharset) or not AnsiSameText(DBField.Charset, DBField.Collate)) then DDL.Strings[Pred(DDL.Count)] := Format('%s CHARACTER SET %s', [DDL.Strings[Pred(DDL.Count)], DBField.Charset]); end; _BLOB: begin if AnsiSameText(DBField.SubType, BlobSubTypes[1]) and (Length(DBField.Charset) > 0) and not AnsiSameText(DBField.Charset, DBCharset) then DDL.Strings[Pred(DDL.Count)] := Format('%s CHARACTER SET %s', [DDL.Strings[Pred(DDL.Count)], DBField.Charset]); end; end; if Length(DBField.DefaultExpression.Text) > 0 then case State of csSource, csCreate, csRecreate: DDL.Add(Format('DEFAULT %s', [Trim(DBField.DefaultExpression.Text)])); csAlter:; end; if System.Length(DBField.NullType) > 0 then DDL.Add(DBField.NullType); case DBField.FieldTypeID of _CHAR, _VARCHAR: if (Length(DBField.Collate) > 0) and not AnsiSameText(DBField.Charset, DBField.Collate) then DDL.Add(Format('COLLATE %s', [DBField.Collate])); end; DDL.Strings[Pred(DDL.Count)] := DDL.Strings[Pred(DDL.Count)] + FTerminator; Exit; end; // Computed if DBField.ComputedSource.Count > 0 then begin DDL.Add(Format('%s COMPUTED BY (%s)', [NormalizeName(DBField.Caption), Trim(DBField.ComputedSource.Text)])); DDL.Strings[Pred(DDL.Count)] := DDL.Strings[Pred(DDL.Count)] + FTerminator; Exit; end; end else DDL.AddStrings(DBField.SourceDDL); end; csAlter: begin if AnsiContainsText(Version, SInterBase4x) or AnsiContainsText(Version, SInterBase5x) then begin // DDL.Add(DeleteOld); // SetDropDDL(DDL); // DDL.Add(''); // DDL.Add(CreateNew); // SetDDLFromValues(DDL); end else begin DDL.Add(Format('ALTER TABLE %s ALTER COLUMN', [NormalizeName(DBField.TableName)])); DDL.Add(Format('%s', [NormalizeName(DBField.Caption)])); DDL.Add('TO new_col_name'); DDL.Add('/* TYPE new_col_datatype */'); DDL.Add(FTerminator); end; end; end; end; if Assigned(DBConstraint) then begin case State of csSource, csCreate, csRecreate: begin if (DBConstraint.ConstraintType='PRIMARY KEY') or (DBConstraint.ConstraintType='UNIQUE') then begin for I := 0 to Pred(DBConstraint.Fields.Count) do begin if Length(S1) > 0 then S1 := Format('%s, %s', [S1, NormalizeName(DBConstraint.Fields[I])]) else S1 := NormalizeName(DBConstraint.Fields[I]); end; S1 := '('+S1+')'; end else if DBConstraint.ConstraintType='FOREIGN KEY' then begin for I := 0 to Pred(DBConstraint.Fields.Count) do begin if Length(S1) > 0 then S1 := Format('%s, %s', [S1, NormalizeName(DBConstraint.Fields[I])]) else S1 := NormalizeName(DBConstraint.Fields[I]); end; S1 := '('+S1+')'; for I := 0 to Pred(DBConstraint.ReferenceFields.Count) do begin if Length(C1) > 0 then C1 := Format('%s, %s', [C1, NormalizeName(DBConstraint.ReferenceFields[I])]) else C1 := NormalizeName(DBConstraint.ReferenceFields[I]); end; C1 := '('+C1+')'; S1 := Format('%s REFERENCES %s %s', [S1, NormalizeName(DBConstraint.ReferenceTable), C1]); if not SameText(DBConstraint.OnDeleteRule, 'NO ACTION') then S1 := Format('%s %sON DELETE %s', [S1, SLineBreak, DBConstraint.OnDeleteRule]); if not SameText(DBConstraint.OnUpdateRule, 'NO ACTION') then S1 := Format('%s %sON UPDATE %s', [S1, SLineBreak, DBConstraint.OnUpdateRule]); end else if DBConstraint.ConstraintType='CHECK' then begin S1 := '('+Trim(DBConstraint.CheckSource.Text)+')'; end else begin if (Length(DBConstraint.IndexName) > 0) and (DBConstraint.IndexName <> DBConstraint.Caption) and not IsSystemIndex(DBConstraint.IndexName) then begin S1 := Format('%s %sUSING', [S1, SLineBreak]); if DBConstraint.IndexSorting<> 'ASCENDING' then S1 := Format('%s %s', [S1, 'DESCENDING']); S1 := Format('%s INDEX %s', [S1, DBConstraint.IndexName]); end; end; if Pos('INTEG_', DBConstraint.Caption) <> 1 then DDL.Add(Format('ALTER TABLE %s ADD CONSTRAINT%s%s', [NormalizeName(DBConstraint.TableName), SLineBreak, NormalizeName(DBConstraint.Caption)])) else DDL.Add(Format('ALTER TABLE %s ADD', [NormalizeName(DBConstraint.TableName)])); DDL.Add(Format('%s %s%s', [DBConstraint.ConstraintType, S1, FTerminator])); end; end; end; if Assigned(DBIndex) then begin case State of csSource, csCreate, csRecreate: begin if Length(DBIndex.IndexType) > 0 then S := Trim(DBIndex.IndexType); if AnsiSameText(DBIndex.Sorting, Sortings[1]) then S := Format('%s %s', [S, DBIndex.Sorting]); if Length(S) > 0 then DDL.Add(Format('CREATE %s INDEX %s', [S, NormalizeName(DBIndex.Caption)])) else DDL.Add(Format('CREATE INDEX %s', [NormalizeName(DBIndex.Caption)])); // S := AnsiReplaceStr(AnsiReplaceStr(DBIndex.Fields.CommaText, '"', ''), ',',', '); S := EmptyStr; if DBIndex.Fields.Count>0 then begin for I := 0 to Pred(DBIndex.Fields.Count) do begin if Length(S) > 0 then S := Format('%s, %s', [S, NormalizeName(DBIndex.Fields[I])]) else S := Format('%s', [NormalizeName(DBIndex.Fields[I])]); end; DDL.Add(Format('ON %s (%s)%s', [NormalizeName(DBIndex.TableName), S, FTerminator])); end else begin S:=TrimRight(DBIndex.Expression.Text); DDL.Add(Format('ON %s COMPUTED BY %s %s', [NormalizeName(DBIndex.TableName), S, FTerminator])); end end; csAlter: begin if SameText(DBIndex.Status, Statuses[0]) then DDL.Add(Format('ALTER INDEX %s %s%s', [NormalizeName(DBIndex.Caption), Statuses[1], FTerminator])) else DDL.Add(Format('ALTER INDEX %s %s%s', [NormalizeName(DBIndex.Caption), Statuses[0], FTerminator])); end; end; end; if Assigned(DBView) then begin if State = csCreate then begin DBView.Fields.Add('view_cols'); end; if DBView.Fields.Count > 0 then begin DDL.Add(Format('CREATE VIEW %s (', [NormalizeName(DBView.Caption)])); for I := 0 to Pred(DBView.Fields.Count) do begin if I <> Pred(DBView.Fields.Count) then DDL.Add(Format(SDDLOffset + '%s,', [NormalizeName(DBView.Fields[I])])) else DDL.Add(Format(SDDLOffset + '%s', [NormalizeName(DBView.Fields[I])])); end; DDL.Add(')'); end else DDL.Add(Format('CREATE VIEW %s', [NormalizeName(DBView.Caption)])); DDL.Add('AS'); if Length(DBView.BodyText.Text) > 0 then if Length(Trim(DBView.BodyText[0])) = 0 then DBView.BodyText.Delete(0); if State = csCreate then begin DBView.BodyText.Add(SDDLOffset + '/* <select> */'); end; DDL.AddStrings(DBView.BodyText); DDL.Add(FTerminator); if State in [csRelatedSource,csRecreate] then begin if DBView.Triggers.Count>0 then begin DDL.Add(''); FTerminator:='^'; DDL.Add('SET TERM ^ ;'); DDL.Add(''); DDL.Add(''); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Triggers */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); for I:=0 to Pred(DBView.Triggers.Count) do begin DDL.AddStrings( DBView.GetTrigger(I).SourceDDL ); DDL[DDL.Count-1]:=FTerminator; DDL.Add(''); end; end; end end; if Assigned(DBProcedure) then begin if DBProcedure.ParamsExt.Count > 0 then begin case State of csSource, csCreate, csRecreate: DDL.Add(Format('CREATE PROCEDURE %s (', [NormalizeName(DBProcedure.Caption)])); csAlter: DDL.Add(Format('ALTER PROCEDURE %s (', [NormalizeName(DBProcedure.Caption)])); end; for I := 0 to Pred(DBProcedure.ParamsExt.Count) do DDL.Add(SDDLOffset + DBProcedure.ParamsExt[I]); DDL.Add(')'); end else begin case State of csSource, csCreate, csRecreate: DDL.Add(Format('CREATE PROCEDURE %s', [NormalizeName(DBProcedure.Caption)])); csAlter: DDL.Add(Format('ALTER PROCEDURE %s', [NormalizeName(DBProcedure.Caption)])); end; end; if DBProcedure.ReturnsExt.Count > 0 then begin DDL.Add('RETURNS ('); for I := 0 to Pred(DBProcedure.ReturnsExt.Count) do DDL.Add(SDDLOffset + DBProcedure.ReturnsExt[I]); DDL.Add(')'); end; DDL.Add('AS'); DBProcedure.HeaderDDL.Assign(DDL); DBProcedure.HeaderDDL.Add('BEGIN'); DBProcedure.HeaderDDL.Add(Format(SDDLOffset +'SUSPEND;', [])); DBProcedure.HeaderDDL.Add('END'); DBProcedure.HeaderDDL.Add(FTerminator); if Length(DBProcedure.BodyText.Text) > 0 then if Length(Trim(DBProcedure.BodyText[0])) = 0 then DBProcedure.BodyText.Delete(0); if State = csCreate then begin DBProcedure.BodyText.Add('BEGIN'); DBProcedure.BodyText.Add(SDDLOffset + '/* <procedure_body> */'); DBProcedure.BodyText.Add('END'); end; DDL.AddStrings(DBProcedure.BodyText); DDL.Add(FTerminator); end; if Assigned(DBTrigger) then begin case State of csSource, csCreate, csRecreate: if Length(DBTrigger.TableName)>0 then DDL.Add(Format('CREATE TRIGGER %s FOR %s', [NormalizeName(DBTrigger.Caption), NormalizeName(DBTrigger.TableName)])) else DDL.Add(Format('CREATE TRIGGER %s ', [NormalizeName(DBTrigger.Caption)])); csAlter: DDL.Add(Format('ALTER TRIGGER %s', [NormalizeName(DBTrigger.Caption)])); end; DDL.Add(Format('%s %s %s POSITION %d', [DBTrigger.Status, DBTrigger.TypePrefix, DBTrigger.TypeSuffix, DBTrigger.Position])); if State = csCreate then begin DBTrigger.BodyText.Clear; DBTrigger.BodyText.Add('AS'); DBTrigger.BodyText.Add('BEGIN'); DBTrigger.BodyText.Add(SDDLOffset + '/* <trigger_body> */'); DBTrigger.BodyText.Add('END'); end else if DBTrigger.BodyText.Count > 0 then if Length(Trim(DBTrigger.BodyText[0])) = 0 then DBTrigger.BodyText.Delete(0); DDL.AddStrings(DBTrigger.BodyText); DDL.Add(FTerminator); end; if Assigned(DBGenerator) then begin case State of csSource, csCreate, csRecreate: DDL.Add(Format('CREATE GENERATOR %s%s', [NormalizeName(DBGenerator.Caption), FTerminator])); end; if DBGenerator.ShowSetClause then DDL.Add(Format('SET GENERATOR %s TO %d%s', [NormalizeName(DBGenerator.Caption), DBGenerator.Value, FTerminator])); end; if Assigned(DBException) then begin case State of csSource, csCreate, csRecreate: DDL.Add(Format('CREATE EXCEPTION %s', [NormalizeName(DBException.Caption)])); csAlter: DDL.Add(Format('ALTER EXCEPTION %s', [NormalizeName(DBException.Caption)])); end; DDL.Add(Format('''%s''%s', [AnsiReplaceText(DBException.Text, '''', ''''''), FTerminator])); end; if Assigned(DBFunction) then begin DDL.Add(Format('DECLARE EXTERNAL FUNCTION %s', [NormalizeName(DBFunction.Caption)])); for I := 0 to Pred(DBFunction.Params.Count) do begin if I <> Pred(DBFunction.Params.Count) then DDL.Add(Format(SDDLOffset + '%s,', [DBFunction.Params[I]])) else DDL.Add(Format(SDDLOffset + '%s', [DBFunction.Params[I]])); end; DDL.Add('RETURNS'); for I := 0 to Pred(DBFunction.Returns.Count) do begin if I <> Pred(DBFunction.Returns.Count) then DDL.Add(Format(SDDLOffset + '%s,', [DBFunction.Returns[I]])) else DDL.Add(Format(SDDLOffset + '%s', [DBFunction.Returns[I]])); end; DDL.Add(Format('ENTRY_POINT ''%s'' MODULE_NAME ''%s''%s', [DBFunction.EntryPoint, DBFunction.ModuleName, FTerminator])); end; if Assigned(DBFilter) then begin DDL.Add(Format('DECLARE FILTER %s', [NormalizeName(DBFilter.Caption)])); DDL.Add(Format(SDDLOffset + 'INPUT_TYPE %d', [DBFilter.InputType])); DDL.Add(Format(SDDLOffset + 'OUTPUT_TYPE %d', [DBFilter.OutputType])); DDL.Add(Format('ENTRY_POINT ''%s'' MODULE_NAME ''%s''%s', [DBFilter.EntryPoint, DBFilter.ModuleName, FTerminator])); end; if Assigned(DBRole) then begin DDL.Add(Format('CREATE ROLE %s%s', [NormalizeName(DBRole.Caption), FTerminator])); end; if Assigned(DBShadow) then begin end; if Assigned(DBQuery) then begin end; end; procedure TibBTDDLGenerator.SetAlterDDLNotSupported(DDL: TStrings); var S: string; begin if Assigned(DBField) then S := 'FIELD'; if Assigned(DBConstraint) then S := 'CONSTRAINT'; if Assigned(DBView) then S := 'VIEW'; if Assigned(DBFunction) then S := 'EXTERNAL FUNCTION'; if Assigned(DBFilter) then S := 'FILTER'; if Assigned(DBRole) then S := 'ROLE'; if Assigned(DBShadow) then S := 'SHADOW'; if Length(S) > 0 then begin DDL.Add('/*'); DDL.Add(Format('This server does not support "ALTER %s" DDL statement,', [S])); DDL.Add('try to use "Recreate" action'); DDL.Add('*/'); end; end; procedure TibBTDDLGenerator.SetSourceDDL(DDL: TStrings); begin SetRealValues; SetDDLFromValues(DDL); end; procedure TibBTDDLGenerator.SetCreateDDL(DDL: TStrings); begin if FUseFakeValues then SetFakeValues(DDL, FCurrentTemplateFile) else SetDDLFromValues(DDL); end; procedure TibBTDDLGenerator.SetAlterDDL(DDL: TStrings); begin if Assigned(DBDomain) then SetDDLFromValues(DDL) else if Assigned(DBTable) then SetDDLFromValues(DDL) else if Assigned(DBField) then SetDDLFromValues(DDL) else if Assigned(DBConstraint) then SetAlterDDLNotSupported(DDL) else if Assigned(DBIndex) then SetDDLFromValues(DDL) else if Assigned(DBView) then SetAlterDDLNotSupported(DDL) else if Assigned(DBProcedure) then SetDDLFromValues(DDL) else if Assigned(DBTrigger) then SetDDLFromValues(DDL) else if Assigned(DBGenerator) then SetDDLFromValues(DDL) else if Assigned(DBException) then SetDDLFromValues(DDL) else if Assigned(DBFunction) then SetAlterDDLNotSupported(DDL) else if Assigned(DBFilter) then SetAlterDDLNotSupported(DDL) else if Assigned(DBRole) then SetAlterDDLNotSupported(DDL) else if Assigned(DBShadow) then SetAlterDDLNotSupported(DDL); end; procedure TibBTDDLGenerator.SetDropDDL(DDL: TStrings); var S: string; begin if Assigned(DBDomain) then S := 'DOMAIN' else if Assigned(DBTable) then S := 'TABLE' else if Assigned(DBField) then S := NormalizeName(DBField.ObjectName) else if Assigned(DBConstraint) then S := 'CONSTRAINT' else if Assigned(DBIndex) then S := 'INDEX' else if Assigned(DBView) then S := 'VIEW' else if Assigned(DBProcedure) then S := 'PROCEDURE' else if Assigned(DBTrigger) then S := 'TRIGGER' else if Assigned(DBGenerator) then S := 'GENERATOR' else if Assigned(DBException) then S := 'EXCEPTION' else if Assigned(DBFunction) then S := 'EXTERNAL FUNCTION' else if Assigned(DBFilter) then S := 'FILTER' else if Assigned(DBRole) then S := 'ROLE' else if Assigned(DBShadow) then S := 'SHADOW'; if Assigned(DBField) then S := Format('DROP %s' + FTerminator, [S]) else S := Format('DROP %s %s' + FTerminator, [S, '%s']); if Assigned(DBGenerator) then begin if not (SameText(Version, SFirebird1x) or SameText(Version, SFirebird15) or SameText(Version, SFirebird20) or SameText(Version, SFirebird21)) then S := 'DELETE FROM RDB$GENERATORS G WHERE G.RDB$GENERATOR_NAME = ''%s''' + FTerminator; end; if Assigned(DBField) then S := Format('ALTER TABLE %s %s', [NormalizeName(DBField.TableName), S]); if Assigned(DBConstraint) then S := Format('ALTER TABLE %s %s', [NormalizeName(DBConstraint.TableName), S]); DDL.Add(Format(S, [NormalizeName(DBObject.ObjectName)])); end; procedure RemoveDouble(List:TStrings); var i:integer; j:integer; begin i:=Pred(List.Count); while i>0 do begin j:=i-1; while j<i do begin j:=List.IndexOf(List[i]); if i<>j then begin List.Delete(j); Dec(i) end end; Dec(i) end; end; procedure FillViewsUsedByView(const ViewName:string; Query:IibSHDRVQuery; Results:TStrings); var CurView:string; StartIndexInList:integer; EndIndexInList :integer; begin Query.Close; StartIndexInList:=Results.Count; if Query.ExecSQL(SQL_VIEWS_USED_BY,[ViewName],False,True) then while not Query.Eof do begin CurView:=Query.GetFieldStrValue(0); Results.Add(CurView); Query.Next end; EndIndexInList:=Results.Count; while StartIndexInList< EndIndexInList do begin FillViewsUsedByView(Results[StartIndexInList],Query,Results); Inc(StartIndexInList) end; end; function MakeIn(List:TStrings;const AddStr:string ):string; var i:integer; begin Result:='('''+AddStr+''','; for i:=0 to Pred(List.Count) do Result:=Result+''''+List[i]+''','; Result[Length(Result)]:=')'; end; procedure TibBTDDLGenerator.SetRecreateDDL(DDL: TStrings); var rDescriptions:TStringList; rProcedures:TStringList; rTriggers :TStringList; rViews :TStringList; rViewTriggers:TStringList; rConstraints:TStringList; DeleteOldDDL:TStrings; DDLCreateViews:TStrings; iv:IibSHView; iv1:IibSHView; ip:IibSHProcedure; it:IIbSHTrigger; ic:IibSHConstraint; i:integer; vComponentClass: TSHComponentClass; vComponent:TComponent; s:String; CurTerm:Char; procedure SaveDescriptions(DBObject:IibSHDBObject); var i:integer; begin if DBObject.Description.Count>0 then begin rDescriptions.Add(''); Designer.TextToStrings(DBObject.GetDescriptionStatement(False),rDescriptions); end; if Supports(DBObject,IibSHView) then with (DBObject as IibSHView) do for i:=0 to Pred(Fields.Count) do if GetField(i).Description.Count>0 then begin rDescriptions.Add(''); Designer.TextToStrings(GetField(i).GetDescriptionStatement(False),rDescriptions); end; end; begin if not Assigned(DBView) then begin DDL.Add(DeleteOld); SetDropDDL(DDL); DDL.Add(''); DDL.Add(CreateNew); SetDDLFromValues(DDL); end else begin // Вьюхи блин rProcedures:=TStringList.Create; rTriggers :=TStringList.Create; rViews :=TStringList.Create; DeleteOldDDL:=TStringList.Create; DDLCreateViews:=TStringList.Create; rViewTriggers:=TStringList.Create; rConstraints:=TStringList.Create; rDescriptions:=TStringList.Create; try FillViewsUsedByView(DBView.Caption,DRVQuery,rViews); RemoveDouble(rViews); s:=MakeIn(rViews,DBView.Caption); if not DRVQuery.ExecSQL(SQL_GET_VIEW_USED_BY1,[s,s],False,False) or DRVQuery.Eof then begin DDL.Add(DeleteOld); SetDropDDL(DDL); DDL.Add(''); DDL.Add(CreateNew); SetDDLFromValues(DDL); SaveDescriptions(DBView); for I:=0 to Pred(DBView.Triggers.Count) do begin it:=DBView.GetTrigger(I); it.Refresh; SaveDescriptions(it); end; if rDescriptions.Count>0 then begin DDL.Add('/*********************************************************************************/'); DDL.Add('/* Restore Comments */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); if FTerminator='^' then DDL.Add('SET TERM ; ^'); DDL.AddStrings(rDescriptions); end; Exit; end; // Здесь мы окончательно поняли что есть зависимости CurTerm:=';' ; DBView.State:=csSource; rViewTriggers.Assign(DBView.Triggers); FState:=csSource; iv:=DBView; SetUseFakeValues(False); DDLCreateViews.Add('/*********************************************************************************/'); DDLCreateViews.Add('/* Restore dependence Views */'); DDLCreateViews.Add('/*********************************************************************************/'); DDLCreateViews.Add(''); SetDDLFromValues(DDLCreateViews); SaveDescriptions(iv); while not DRVQuery.Eof do begin case DRVQuery.GetFieldValue(0) of 2: if rTriggers.IndexOf(DRVQuery.GetFieldStrValue(1))=-1 then rTriggers.Add(DRVQuery.GetFieldStrValue(1)); 5: if rProcedures.IndexOf(DRVQuery.GetFieldStrValue(1))=-1 then rProcedures.Add(DRVQuery.GetFieldStrValue(1)); 7: if rConstraints.IndexOf(DRVQuery.GetFieldStrValue(1))=-1 then rConstraints.Add(DRVQuery.GetFieldStrValue(1)); end; DRVQuery.Next; end; if rProcedures.Count>0 then begin DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add('/* Clear dependence procedures */'); DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add('SET TERM ^ ;'); CurTerm:='^' ; FTerminator:=CurTerm; DDL.Add('/*********************************************************************************/'); DDL.Add('/* Restore dependence procedures */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); vComponentClass := Designer.GetComponent(IibSHProcedure); if Assigned(vComponentClass) then begin vComponent:=vComponentClass.Create(Self); Supports(vComponent,IibSHProcedure,ip); try ip.OwnerIID:=iv.OwnerIID; for i:=0 to Pred(rProcedures.Count) do begin ip.Caption:=TrimRight(rProcedures[i]); ip.State:=csSource; S := GetDDLText(ip); s:=ip.HeaderDDL.Text; s:=StringReplace(s,'CREATE','ALTER',[]); Designer.TextToStrings(s,DeleteOldDDL); // ^^^^^^^^^^Обнуляем процедуры ip.State:=csAlter; s:=GetDDLText(ip); Designer.TextToStrings(s,DDL); // ^^^^^^^^^^Восстанавливаем процедуры end finally ip:=nil; vComponent.Free; end; end; // Конец обработки процедур end; if rTriggers.Count>0 then begin DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add('/* Clear dependence triggers */'); DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add(''); if CurTerm<>'^' then begin DeleteOldDDL.Add('SET TERM ^ ;'); CurTerm:='^'; end; DDL.Add('/*********************************************************************************/'); DDL.Add('/* Restore dependence triggers */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); FTerminator:='^'; vComponentClass := Designer.GetComponent(IibSHTrigger); if Assigned(vComponentClass) then begin vComponent:=vComponentClass.Create(Self); Supports(vComponent,IibSHTrigger,it); try it.OwnerIID:=iv.OwnerIID; for i:=0 to Pred(rTriggers.Count) do begin DeleteOldDDL.Add('ALTER TRIGGER '+NormalizeName2(TrimRight(rTriggers[i]),it.BTCLDatabase) ); DeleteOldDDL.Add('AS '); DeleteOldDDL.Add('BEGIN '); DeleteOldDDL.Add(' /**/ '); DeleteOldDDL.Add('END'); DeleteOldDDL.Add('^'); DeleteOldDDL.Add(''); // ^^^^^^^^^^Обнуляем триггера it.Caption:=TrimRight(rTriggers[i]); it.State:=csAlter; it.Refresh; s:=GetDDLText(it); Designer.TextToStrings(s,DDL); // ^^^^^^^^^^Восстанавливаем триггера end finally it:=nil; vComponent.Free; end; end end; // Конец обработки триггеров if rConstraints.Count>0 then begin DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add('/* Drop dependence constraint */'); DeleteOldDDL.Add('/*********************************************************************************/'); DDL.Add('/*********************************************************************************/'); DDL.Add('/* Restore dependence constraint */'); DDL.Add('/*********************************************************************************/'); if CurTerm='^' then begin CurTerm:=';'; FTerminator:=';'; DeleteOldDDL.Add('SET TERM ; ^'); DDL.Add('SET TERM ; ^'); end; vComponentClass := Designer.GetComponent(IibSHConstraint); if Assigned(vComponentClass) then begin vComponent:=vComponentClass.Create(Self); Supports(vComponent,IibSHConstraint,ic); try ic.OwnerIID:=iv.OwnerIID; for i:=0 to Pred(rConstraints.Count) do begin ic.Caption:=TrimRight(rConstraints[i]); ic.Refresh; ic.State:=csDrop; S := GetDDLText(ic); Designer.TextToStrings(s,DeleteOldDDL); ic.State:=csSource; S := GetDDLText(ic); Designer.TextToStrings(s,DDL); end; finally ic:=nil; vComponent.Free; end; end; end; // Конец обработки констрэйнтов DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add('/* Clear dependence Views */'); DeleteOldDDL.Add('/*********************************************************************************/'); DeleteOldDDL.Add(' '); if CurTerm='^' then DeleteOldDDL.Add('SET TERM ; ^'); DeleteOldDDL.Add(' '); for i:=Pred(rViews.Count) downto 0 do begin DeleteOldDDL.Add('DROP VIEW '+NormalizeName2(TrimRight(rViews[i]),iv.BTCLDatabase)+ ';'); end; DeleteOldDDL.Add('DROP VIEW '+NormalizeName2(iv.Caption,iv.BTCLDatabase)+ ';'); DeleteOldDDL.Add(' '); if rViews.Count>0 then begin FTerminator:=';' ; vComponentClass := Designer.GetComponent(IibSHView); if Assigned(vComponentClass) then begin vComponent:=vComponentClass.Create(Self); Supports(vComponent,IibSHView,iv1); try iv1.OwnerIID:=iv.OwnerIID; iv1.State:=csSource; for i:=0 to Pred(rViews.Count) do begin iv1.Caption:=TrimRight(rViews[i]); s:=GetDDLText(iv1); DDLCreateViews.Add(''); Designer.TextToStrings(s,DDLCreateViews); rViewTriggers.AddStrings(iv1.Triggers); SaveDescriptions(iv1); end; finally iv1:=nil; vComponent.Free; end end end; if rViewTriggers.Count>0 then begin vComponentClass := Designer.GetComponent(IibSHTrigger); if Assigned(vComponentClass) then begin vComponent:=vComponentClass.Create(Self); Supports(vComponent,IibSHTrigger,it); try it.OwnerIID:=iv.OwnerIID; DDLCreateViews.Add(''); DDLCreateViews.Add('/*********************************************************************************/'); DDLCreateViews.Add('/* Create empty view triggers */'); DDLCreateViews.Add('/*********************************************************************************/'); DDLCreateViews.Add(''); DDLCreateViews.Add('SET TERM ^ ;'); FTerminator:='^'; for i:=0 to Pred(rViewTriggers.Count) do begin it.Caption:=TrimRight(rViewTriggers[i]); it.Refresh; it.State:=csCreate; s:=GetDDLText(it); Designer.TextToStrings(s,DDLCreateViews); SaveDescriptions(it); end; DDLCreateViews.Add(''); DDLCreateViews.Add('/*********************************************************************************/'); DDLCreateViews.Add('/* Restore view triggers */'); DDLCreateViews.Add('/*********************************************************************************/'); DDLCreateViews.Add(''); for i:=0 to Pred(rViewTriggers.Count) do begin it.Caption:=TrimRight(rViewTriggers[i]); it.State:=csAlter; it.Refresh; s:=GetDDLText(it); Designer.TextToStrings(s,DDLCreateViews); end; finally it:=nil; vComponent.Free end; end end; DDLCreateViews.AddStrings(DDL); DeleteOldDDL.AddStrings(DDLCreateViews); DDL.Assign(DeleteOldDDL); if rDescriptions.Count>0 then begin DDL.Add('/*********************************************************************************/'); DDL.Add('/* Restore Comments */'); DDL.Add('/*********************************************************************************/'); DDL.Add(''); DDL.Add('SET TERM ; ^'); DDL.AddStrings(rDescriptions) end finally rConstraints.Free; rDescriptions.Free; rViewTriggers.Free; rProcedures.Free; rTriggers .Free; rViews .Free; DeleteOldDDL.Free; DDLCreateViews.Free; if Assigned(DRVQuery) then begin DRVQuery.Close; if DRVQuery.Transaction.InTransaction then DRVQuery.Transaction.Commit end end; end; end; { ShadowMode ShadowType FileName SecondaryFiles } function TibBTDDLGenerator.GetCurrentTemplateFile: string; begin Result:=FCurrentTemplateFile end; procedure TibBTDDLGenerator.SetCurrentTemplateFile(const FileName: string); begin FCurrentTemplateFile:=FileName end; end.
{ Taken from PC World Best of *.* Volume 2 (1989) } { NO LICENSE PROVIDED, PROBABLY PUBLIC DOMAIN (published on coverdisk) } { Documentation: } { Title: "Bullet-Proofing Pascal Input" } { Reference: PC World April 1989 } { Author: Michael Fang } { Although Turbo Pascal's Readln and Read procedures can input strings, } { they lack the editing features of a word processor. To enhance string } { input in your own Pascal programs, add procedure GetLn to your code, } { as demonstrated in TESTEDIT.PAS. To try it out, load the program into } { Turbo's editor and press <Ctrl>-<F9> to run. The procedure duplicates } { many of WordStar's popular keystrokes. Press <Ctrl>-T to delete a } { word, <Ctrl>-<Cursor Right> to move to the next word, <Ctrl>-<Cursor } { Left> to move to the previous word, and <Home> and <End> to jump to } { the beginning and end of the string. } PROGRAM TestEdit; USES Dos, Crt; CONST HOME=18176; ENDD=20224; LEFT=19200; RIGHT=19712; BACK=8; ENTER=13; ESC=27; INS=20992; DEL=21248; WRDLEFT=29440; WRDRIGHT=29696; DELWRD=20; DELEOL=17; Blank=' '; {one blank} VAR teststr: string; p: integer; FUNCTION GetKey:Integer; var regs: registers; key: integer; BEGIN regs.ah := 0; intr( $16, regs ); if regs.al = 0 then begin key := regs.ah; key := key shl 8 end else key := regs.al; getkey := key END; { getkey } PROCEDURE GetLn( var xstr: string; n: integer; var position: integer ); var oldx, oldy: byte; workstr: string; xlen: integer; strpos: integer; oldlen: integer; key: integer; insmode: Boolean; i: integer; procedure initialize; begin oldx := wherex; oldy := whereY; workstr := xstr; insmode := true; xlen := lo( windmax ) - lo( windmin ) + 1 - oldx; if n > xlen then n := xlen; if length( workstr ) > n then workstr[0] := char(n); if position < 1 then position := 1; if position > length( workstr ) then position := length( workstr ) + 1; strpos := oldx + position - 1; write( workstr ); gotoxy( strpos, oldy ) end; { intitialize } BEGIN { GetLn } initialize; repeat key := getkey; case key of 32..126: if ( length( workstr ) < n ) and ( insmode or ( position > length( workstr ) ) ) then begin insert( char(key), workstr, position ); inc( position ); gotoxy( oldx, oldy ); write( workstr ) end else if ( not insmode ) and ( position < n + 1 ) then begin workstr[ position ] := char( key ); write( workstr[ position ] ); inc( position ) end; INS: insmode := not insmode; ENTER: xstr := workstr; LEFT: if position > 1 then dec( position ); RIGHT: if position <= length( workstr ) then inc( position ); HOME: position := 1; ENDD: position := length( workstr ) + 1; BACK: if position > 1 then begin dec( position ); delete( workstr, position, 1 ); gotoxy( oldx, oldy ); write( workstr, Blank ) end; DEL: if position <= length( workstr ) then begin delete( workstr, position, 1 ); gotoxy( oldx, oldy ); write( workstr, Blank ) end; DELWRD: begin oldlen := length( workstr ); if workstr[ position ] = Blank then while ( workstr[ position ] = Blank ) and ( position <= length( workstr ) ) do delete( workstr, position, 1 ) else begin while ( workstr[ position ] <> Blank ) and ( position <= length( workstr ) ) do delete( workstr, position, 1 ); while ( workstr[ position ] = Blank ) and ( position <= length( workstr ) ) do delete( workstr, position, 1 ); end; { else } gotoxy( oldx, oldy ); write( workstr ); for i := 1 to oldlen - length( workstr ) do write( Blank ) end; DELEOL: begin oldlen := length( workstr ); case getkey of 89, 121: if position <= oldlen then delete( workstr, position, 256 ) end; { case } for i := 1 to oldlen - length( workstr ) do write( Blank ) end; WRDLEFT: if position > 1 then if ( position = 2 ) and ( workstr[ position ] <> Blank ) and ( workstr[ position-1 ] = Blank ) then dec( position ) else begin if ( workstr[ position - 1 ] = Blank ) or ( workstr[ position ] = Blank ) then repeat dec( position ); until ( position = 1 ) or ( workstr[ position ] <> Blank ); while ( workstr[ position ] <> Blank ) and ( position > 1 ) do dec( position ); if ( workstr[ position ] = Blank ) and ( workstr[ position + 1 ] <> Blank ) then inc( position ) end; WRDRIGHT: if position < length( workstr ) + 1 then begin while ( workstr[ position ] <> Blank ) and ( position < length( workstr ) + 1 ) do inc( position ); while ( workstr[ position ] = Blank ) and ( position < length( workstr ) + 1 ) do inc( position ); end; end; { case } strpos := oldx + position - 1; gotoxy( strpos, oldy ) until ( key = ENTER ) or ( key = ESC ) END; { GetLn } BEGIN { TestEdit } clrscr; teststr := 'Read Star-Dot-Star in PC World!'; p := 1; GetLn( teststr, 79, p ); gotoxy( 1, 3 ); writeln( 'Edited string = ', teststr ) END.
{ NAME: Jordan Millett CLASS: Comp Sci 1 DATE: 10/31/2016 PURPOSE: To create graphics. } Program grafdemo; uses crt,graph; {step 1:include graphics library} Procedure getInt(ask:string; num : integer); var numStr : string; code : integer; begin repeat write(ask); readln(numstr); val(numStr, num, code); if code <> 0 then begin writeln('Not an integer '); writeln('Press any key to continue'); readkey; clrscr; end; until (code = 0); end; {*********** Main Body ***********} var gd,gm:smallint; {step 2:create varibles} x,y,count:integer; begin {main} gd:=DETECT; {step 3:set varibles} initgraph(gd,gm,''); {step 4:initialize graphics} {step 5:code graphics} setcolor(blue); line(1,640,1024,1); setcolor(lightgreen); for y:=1 to 640 do line(1,640,1024,y); setcolor(red); for x:=1024 downto 1 do line(1,640,x,1); setcolor(blue); circle(512,320,200); setfillstyle(solidfill,cyan); floodfill(520,320,blue); delay(1000); setcolor(yellow); settextstyle(defaultfont, horizdir,8); outtextxy(320,300,'Jordan'); readkey; closegraph; {step 6:close graph} end. {main}
unit Encryption; interface function Decrypt(const S: AnsiString; Key: Word): AnsiString; function Encrypt(const S: AnsiString; Key: Word): AnsiString; implementation const C1 = 52845; C2 = 22719; function Decode(const S: AnsiString): AnsiString; const Map: array[Char] of Byte = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); var I: LongInt; begin case Length(S) of 2: begin I := Map[S[1]] + (Map[S[2]] shl 6); SetLength(Result, 1); Move(I, Result[1], Length(Result)) end; 3: begin I := Map[S[1]] + (Map[S[2]] shl 6) + (Map[S[3]] shl 12); SetLength(Result, 2); Move(I, Result[1], Length(Result)) end; 4: begin I := Map[S[1]] + (Map[S[2]] shl 6) + (Map[S[3]] shl 12) + (Map[S[4]] shl 18); SetLength(Result, 3); Move(I, Result[1], Length(Result)) end end end; function PreProcess(const S: AnsiString): AnsiString; var SS: AnsiString; begin SS := S; Result := ''; while SS <> '' do begin Result := Result + Decode(Copy(SS, 1, 4)); Delete(SS, 1, 4) end end; function InternalDecrypt(const S: AnsiString; Key: Word): AnsiString; var I: Word; Seed: Word; begin Result := S; Seed := Key; for I := 1 to Length(Result) do begin Result[I] := Char(Byte(Result[I]) xor (Seed shr 8)); Seed := (Byte(S[I]) + Seed) * Word(C1) + Word(C2) end end; function Decrypt(const S: AnsiString; Key: Word): AnsiString; begin Result := InternalDecrypt(PreProcess(S), Key) end; function Encode(const S: AnsiString): AnsiString; const Map: array[0..63] of Char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789+/'; var I: LongInt; begin I := 0; Move(S[1], I, Length(S)); case Length(S) of 1: Result := Map[I mod 64] + Map[(I shr 6) mod 64]; 2: Result := Map[I mod 64] + Map[(I shr 6) mod 64] + Map[(I shr 12) mod 64]; 3: Result := Map[I mod 64] + Map[(I shr 6) mod 64] + Map[(I shr 12) mod 64] + Map[(I shr 18) mod 64] end end; function PostProcess(const S: AnsiString): AnsiString; var SS: AnsiString; begin SS := S; Result := ''; while SS <> '' do begin Result := Result + Encode(Copy(SS, 1, 3)); Delete(SS, 1, 3) end end; function InternalEncrypt(const S: AnsiString; Key: Word): AnsiString; var I: Word; Seed: Word; begin Result := S; Seed := Key; for I := 1 to Length(Result) do begin Result[I] := Char(Byte(Result[I]) xor (Seed shr 8)); Seed := (Byte(Result[I]) + Seed) * Word(C1) + Word(C2) end end; function Encrypt(const S: AnsiString; Key: Word): AnsiString; begin Result := PostProcess(InternalEncrypt(S, Key)) end; end. end.
unit ConnectionProperty; interface uses SysUtils, Classes, Forms, ADODB, Db, dcfdes, dcsystem, dcdsgnstuff, ThComponent, ThDataConnection, TpPersistComponent; type TConnnectionStringPropertyEditor = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure Edit; override; end; procedure RegisterConnectionStringPropertyEditor; implementation uses ConnectionStringEdit, Config; procedure RegisterConnectionStringPropertyEditor; begin RegisterPropertyEditor(TypeInfo(string), TThDataConnection, 'ConnectionString', TConnnectionStringPropertyEditor); end; { TConnnectionStringPropertyEditor } function TConnnectionStringPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [ paDialog ]; end; procedure TConnnectionStringPropertyEditor.Edit; begin with TConnectionStringEditForm.Create(nil) do try ConnectionString := Value; ShowModal; Value := ConnectionString; finally Free; end; end; procedure TConnnectionStringPropertyEditor.GetValues(Proc: TGetStrProc); var i: Integer; begin with NeedConnectionStore do for i := 0 to Pred(ConnectionStrings.Count) do Proc(ConnectionStrings[i]); end; end.
object FCheckList: TFCheckList Left = 269 Top = 144 BorderStyle = bsDialog Caption = 'FCheckList' ClientHeight = 250 ClientWidth = 570 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poOwnerFormCenter OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object CheckListBox: TcxCheckListBox Left = 0 Top = 25 Width = 570 Height = 192 EditValue = 0 Align = alClient Columns = 0 Items = <> ParentFont = False ScrollWidth = 0 Style.Color = 16247513 Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clNavy Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 0 TabWidth = 0 end object Panel1: TPanel Left = 0 Top = 0 Width = 570 Height = 25 Align = alTop BevelOuter = bvNone TabOrder = 1 object CheckAllBtn: TcxButton Left = 360 Top = 0 Width = 105 Height = 25 Caption = 'CheckAllBtn' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False TabOrder = 0 OnClick = CheckAllBtnClick LookAndFeel.Kind = lfFlat end object UnCheckAllBtn: TcxButton Left = 464 Top = 0 Width = 105 Height = 25 Caption = 'UnCheckAllBtn' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False TabOrder = 1 OnClick = UnCheckAllBtnClick LookAndFeel.Kind = lfFlat end end object Panel2: TPanel Left = 0 Top = 217 Width = 570 Height = 33 Align = alBottom BevelOuter = bvNone TabOrder = 2 object YesBtn: TcxButton Left = 416 Top = 5 Width = 73 Height = 25 Action = Action1 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False TabOrder = 0 LookAndFeel.Kind = lfFlat end object CancelBtn: TcxButton Left = 488 Top = 5 Width = 73 Height = 25 Caption = 'CancelBtn' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False TabOrder = 1 OnClick = CancelBtnClick LookAndFeel.Kind = lfFlat end end object ActionList1: TActionList Left = 288 Top = 216 object Action1: TAction Caption = 'Action1' ShortCut = 121 OnExecute = Action1Execute end end end
unit CFDateTimePicker; interface uses Windows, Classes, Messages, Controls, Graphics, CFControl, CFPopup, CFMonthCalendar, CFButtonEdit; type TECalendar = class(TCFMonthCalendar) private procedure WMCFMOUSEMOVE(var Message: TMessage); message WM_CF_MOUSEMOVE; procedure WMCFLBUTTONDOWN(var Message: TMessage); message WM_CF_LBUTTONDOWN; procedure WMCFLBUTTONUP(var Message: TMessage); message WM_CF_LBUTTONUP; procedure WMCFLBUTTONDBLCLK(var Message: TMessage); message WM_CF_LBUTTONDBLCLK; end; TDateTimeArea = (dtaNone, dtaYear, dtaMonth, dtaDay, dtaHour, dtaMinute, dtaSecond, dtaMillisecond); TCFDateTimePicker = class(TCFTextControl) private FFocus: Boolean; FReadOnly: Boolean; FButtonVisible: Boolean; //FAlwaysShowButton: Boolean; FFormat: string; FCalendar: TECalendar; FPopup: TCFPopup; FArea: TDateTimeArea; // 当前激活的日期时间区域 FAreaRect: TRect; // 区域范围 FNewYear: string; // 当前输入的年新值 FJoinKey: Boolean; // 键盘修改除年外时,记录是否连接输入 /// <summary> 绘制时左侧的偏移(>=0) </summary> FLeftDrawOffset: Integer; procedure DoDateTimeChanged(Sender: TObject); procedure PopupPicker; procedure DoOnPopupDrawWindow(const ADC: HDC; const AClentRect: TRect); procedure DoButtonClick(Sender: TObject); /// <summary> 返回指定位置是日期时间的哪一部位(坐标不处理偏移) </summary> /// <param name="X">横坐标(无偏移)</param> /// <param name="Y">纵坐标(无偏移)</param> /// <param name="AArea">日期时间某一部位</param> /// <returns>该部位对应的区域(无偏移)</returns> function GetAreaAt(const X, Y: Integer; var AArea: TDateTimeArea; const ACalcArea: Boolean = True): TRect; /// <summary> 根据当前坐标重新计算当前日期时间部位、绘制偏移、部位区域(偏移后) </summary> /// <param name="X">横坐标(无偏移)</param> /// <param name="Y">纵坐标(无偏移)</param> procedure ReBuildArea(X, Y: Integer); /// <summary> 将日期的年部分修改为输入的年字符串 </summary> procedure SetInputYear; /// <summary> 返回格式化日期时间后的第一个有效部位(可用于非鼠标操作时激活某一部位) </summary> /// <param name="AArea">部位</param> /// <returns>部位区域</returns> function FindFirstDateTimeArea(var AArea: TDateTimeArea): TRect; // 通过Tab移入焦点 //procedure CMUIActivate(var Message: TMessage); message CM_UIACTIVATE; // 通过Tab移出焦点 //procedure CMUIDeActivate(var Message: TMessage); message CM_UIDEACTIVATE; protected procedure DrawControl(ACanvas: TCanvas); override; procedure AdjustBounds; override; function GetMaxDateTime: TDateTime; procedure SetMaxDateTime(Value: TDateTime); function GetMinDateTime: TDateTime; procedure SetMinDateTime(Value: TDateTime); function GetDateTime: TDateTime; procedure SetDateTime(Value: TDateTime); procedure SetFormat(Value: string); procedure SetButtonVisible(Value: Boolean); /// <summary> 取消激活状态 </summary> procedure DisActive; // 便于嵌套父控件调用取消 procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; //procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER; procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMCFLBUTTONDOWN(var Message: TMessage); message WM_CF_LBUTTONDOWN; procedure WMCFLBUTTONUP(var Message: TMessage); message WM_CF_LBUTTONUP; procedure WMCFMOUSEMOVE(var Message: TMessage); message WM_CF_MOUSEMOVE; procedure WMCFLBUTTONDBLCLK(var Message: TMessage); message WM_CF_LBUTTONDBLCLK; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published property DateTime: TDateTime read GetDateTime write SetDateTime; property MaxDateTime: TDateTime read GetMaxDateTime write SetMaxDateTime; property MinDateTime: TDateTime read GetMinDateTime write SetMinDateTime; property Format: string read FFormat write SetFormat; property ReadOnly: Boolean read FReadOnly write FReadOnly default False; /// <summary> True:一直显示按钮 False:仅在鼠标移入或有焦点时显示按钮 </summary> property ButtonVisible: Boolean read FButtonVisible write SetButtonVisible; property OnChange; end; implementation uses SysUtils, DateUtils; { TECalendar } procedure TECalendar.WMCFLBUTTONDBLCLK(var Message: TMessage); var vOldDate: TDate; begin vOldDate := Self.Date; MouseDown(mbLeft, KeysToShiftState(Message.WParam) + MouseOriginToShiftState, Message.LParam and $FFFF, Message.LParam shr 16); if CompareDate(vOldDate, Self.Date) <> 0 then // 选择了新日期 Message.Result := 1; // 不关闭 end; procedure TECalendar.WMCFLBUTTONDOWN(var Message: TMessage); var vOldDate: TDate; begin vOldDate := Self.Date; MouseDown(mbLeft, KeysToShiftState(Message.WParam) + MouseOriginToShiftState, Message.LParam and $FFFF, Message.LParam shr 16); Message.Result := 1; if CompareDate(vOldDate, Self.Date) <> 0 then // 选择了新日期 begin if Message.LParam shr 16 > 50 then // 在日期区选择了新日期 Message.Result := 0; // 关闭 end; end; procedure TECalendar.WMCFLBUTTONUP(var Message: TMessage); var X, Y: Integer; vRect: TRect; vOldDisplayModel: TDisplayModel; begin if not HandleAllocated then Exit; X := Message.LParam and $FFFF; Y := Message.LParam shr 16; vRect := ClientRect; if PtInRect(vRect, Point(X, Y)) then // 在区域 begin vOldDisplayModel := Self.FDisplayModel; MouseUp(mbLeft, KeysToShiftState(Message.WParam) + MouseOriginToShiftState, X, Y); if Self.FDisplayModel <> vOldDisplayModel then Message.Result := 1; // 不关闭 end; end; procedure TECalendar.WMCFMOUSEMOVE(var Message: TMessage); var vShift: TShiftState; X, Y: Integer; vRect: TRect; vOldMoveDate: TDate; begin if not HandleAllocated then Exit; X := Message.LParam and $FFFF; Y := Message.LParam shr 16; vRect := ClientRect; if PtInRect(vRect, Point(X, Y)) then // 在区域 begin vShift := []; if Message.WParam and MK_LBUTTON <> 0 then begin Include(vShift, ssLeft); Message.Result := 1; end; vOldMoveDate := Self.FMoveDate; MouseMove(vShift, X, Y); if Self.FMoveDate <> vOldMoveDate then Message.Result := 1; end; end; { TCFDateTimePicker } procedure TCFDateTimePicker.AdjustBounds; var vDC: HDC; vHeight, vWidth: Integer; begin if not (csReading in ComponentState) then begin vDC := GetDC(0); try Canvas.Handle := vDC; Canvas.Font := Font; vWidth := Canvas.TextWidth(FormatDateTime('YYYY-MM-DD', Now)) + GetSystemMetrics(SM_CYBORDER) * 2; if FButtonVisible then vWidth := vWidth + GIconWidth; if vWidth < Width then vWidth := Width; vHeight := Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth; if vHeight < Height then vHeight := Height; Canvas.Handle := 0; finally ReleaseDC(0, vDC); end; SetBounds(Left, Top, vWidth, vHeight); end; end; procedure TCFDateTimePicker.CMMouseEnter(var Msg: TMessage); begin inherited; UpdateDirectUI; end; procedure TCFDateTimePicker.CMMouseLeave(var Msg: TMessage); begin inherited; UpdateDirectUI; end; procedure TCFDateTimePicker.CMTextChanged(var Message: TMessage); begin inherited; UpdateDirectUI; end; constructor TCFDateTimePicker.Create(AOwner: TComponent); begin inherited Create(AOwner); FLeftDrawOffset := 0; FButtonVisible := True; FFormat := 'YYYY-M-D HH:mm:ss'; //Self.OnButtonClick := DoButtonClick; FCalendar := TECalendar.Create(Self); FCalendar.Parent := Self; FCalendar.Top := 1000; Width := 75; Height := 20; FCalendar.Width := 210; FCalendar.Height := 231; Text := FormatDateTime(FFormat, FCalendar.Date); end; procedure TCFDateTimePicker.DoDateTimeChanged(Sender: TObject); begin Text := FormatDateTime(FFormat, FCalendar.Date); end; destructor TCFDateTimePicker.Destroy; begin FCalendar.Free; inherited; end; procedure TCFDateTimePicker.DisActive; begin SetInputYear; if FArea <> dtaNone then begin FArea := dtaNone; FLeftDrawOffset := 0; UpdateDirectUI end; end; procedure TCFDateTimePicker.DoButtonClick(Sender: TObject); begin if not (csDesigning in ComponentState) then begin if ReadOnly then Exit; PopupPicker; end; end; function TCFDateTimePicker.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; var vPt: TPoint; vYear, vMonth, vDay, vMSec, vCount: Word; vHour: Word absolute vYear; vMin: Word absolute vMonth; vSec: Word absolute vDay; begin vPt := ScreenToClient(Mouse.CursorPos); if not PtInRect(ClientRect, vPt) then Exit; if FArea <> dtaNone then begin case FArea of dtaYear: begin if WheelDelta < 0 then // 向下 DateTime := IncYear(DateTime, -1) else DateTime := IncYear(DateTime); end; dtaMonth: begin DecodeDate(DateTime, vYear, vMonth, vDay); if vMonth > 9 then vMSec := 1 // 2位数 else vMSec := 0; // 1位数 if WheelDelta < 0 then // 向下 begin Dec(vMonth); if vMonth < 1 then vMonth := 12; end else begin Inc(vMonth); if vMonth > 12 then vMonth := 1; end; BeginUpdate; try vCount := DaysInAMonth(vYear, vMonth); // 新月的天数 if vDay > vCount then // 当前天数大于新月天数 DateTime := RecodeDay(DateTime, vCount); // 修正 DateTime := RecodeMonth(DateTime, vMonth); finally EndUpdate; end; // 这里应该再调用DecodeDate(DateTime, vYear, vMonth, vDay);计算新月 // 因为DateTime赋值后可能超出允许范围,并没有发生变化 // 实际并没有调用是因为影响可以忽略 if vMonth > 9 then // 新月2位数 and (vMSec = 0)) // 1位变2位 then begin if vMSec = 0 then // 旧月1位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end else // 新月1位数 if vMSec = 1 then // 旧月2位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end; dtaDay: begin vCount := DaysInMonth(DateTime); DecodeDate(DateTime, vYear, vMonth, vDay); if vDay > 9 then vMSec := 1 // 2位数 else vMSec := 0; // 1位数 if WheelDelta < 0 then // 向下 begin Dec(vDay); if vDay < 1 then vDay := vCount; end else begin Inc(vDay); if vDay > vCount then vDay := 1; end; DateTime := RecodeDay(DateTime, vDay); if vDay > 9 then // 新日2位数 and (vMSec = 0)) // 1位变2位 then begin if vMSec = 0 then // 旧日1位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end else // 新日1位数 if vMSec = 1 then // 旧日2位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end; dtaHour: begin DecodeTime(DateTime, vHour, vMin, vSec, vMSec); if vHour > 9 then vMSec := 1 // 2位数 else vMSec := 0; // 1位数 if WheelDelta < 0 then // 向下 begin Dec(vHour); if vHour > 23 then vHour := 23; end else begin Inc(vHour); if vHour > 23 then vHour := 0; end; DateTime := RecodeHour(DateTime, vHour); if vHour > 9 then // 新时2位数 and (vMSec = 0)) // 1位变2位 then begin if vMSec = 0 then // 旧时1位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end else // 新时1位数 if vMSec = 1 then // 旧时2位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end; dtaMinute: begin DecodeTime(DateTime, vHour, vMin, vSec, vMSec); if vMin > 9 then vMSec := 1 // 2位数 else vMSec := 0; // 1位数 if WheelDelta < 0 then // 向下 begin Dec(vMin); if vMin > 59 then vMin := 59; end else begin Inc(vMin); if vMin > 59 then vMin := 0; end; DateTime := RecodeMinute(DateTime, vMin); if vMin > 9 then // 新分2位数 and (vMSec = 0)) // 1位变2位 then begin if vMSec = 0 then // 旧分1位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end else // 新分1位数 if vMSec = 1 then // 旧分2位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end; dtaSecond: begin DecodeTime(DateTime, vHour, vMin, vSec, vMSec); if vSec > 9 then vMSec := 1 // 2位数 else vMSec := 0; // 1位数 if WheelDelta < 0 then // 向下 begin Dec(vSec); if vSec > 59 then vSec := 59; end else begin Inc(vSec); if vSec > 59 then vSec := 0; end; DateTime := RecodeSecond(DateTime, vSec); if vSec > 9 then // 新秒2位数 and (vMSec = 0)) // 1位变2位 then begin if vMSec = 0 then // 旧秒1位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end else // 新秒1位数 if vMSec = 1 then // 旧秒2位数 ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); end; //dtaMillisecond: ; end; end; end; procedure TCFDateTimePicker.DoOnPopupDrawWindow(const ADC: HDC; const AClentRect: TRect); var vCanvas: TCanvas; begin vCanvas := TCanvas.Create; try vCanvas.Handle := ADC; FCalendar.DrawTo(vCanvas); vCanvas.Handle := 0; finally vCanvas.Free; end; end; procedure TCFDateTimePicker.DrawControl(ACanvas: TCanvas); var vRect: TRect; vLeft, vTop: Integer; vBmp: TBitmap; begin inherited DrawControl(ACanvas); // 外观,圆角矩形 vRect := Rect(0, 0, Width, Height); ACanvas.Brush.Style := bsSolid; if FReadOnly then ACanvas.Brush.Color := GReadOlnyBackColor; if BorderVisible then begin if FFocus or (cmsMouseIn in MouseState) then ACanvas.Pen.Color := GBorderHotColor else ACanvas.Pen.Color := GBorderColor; ACanvas.Pen.Style := psSolid; end else ACanvas.Pen.Style := psClear; if RoundCorner > 0 then ACanvas.RoundRect(vRect, GRoundSize, GRoundSize) else ACanvas.Rectangle(vRect); // 按钮 if FButtonVisible then begin // if FAlwayShowButton or Focus or (cmsMouseIn in MouseState) then vRect.Right := vRect.Right - GIconWidth; if Self.Focused or (cmsMouseIn in MouseState) then begin {ACanvas.Brush.Color := GHotColor; if BorderVisible then ACanvas.FillRect(Rect(vRect.Right, GBorderWidth, Width - GBorderWidth - GBorderWidth, Height - GBorderWidth - GBorderWidth)) else ACanvas.FillRect(Rect(vRect.Right, GBorderWidth, Width - GBorderWidth, Height - GBorderWidth));} end; ACanvas.Pen.Color := GLineColor; ACanvas.MoveTo(vRect.Right, GBorderWidth); ACanvas.LineTo(vRect.Right, Height - GBorderWidth); vBmp := TBitmap.Create; try vBmp.Transparent := True; vBmp.LoadFromResourceName(HInstance, 'DROPDOWN'); ACanvas.Draw(vRect.Right, (Height - GIconWidth) div 2, vBmp); finally vBmp.Free; end; end; // 设置内容可绘制区域 InflateRect(vRect, -GBorderWidth, -GBorderWidth); vRect.Left := vRect.Left + GPadding; // IntersectClipRect(ACanvas.Handle, vRect.Left, vRect.Top, vRect.Right, vRect.Bottom); // try // 高亮区域 if FArea <> dtaNone then begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(FAreaRect); end; // 内容 vLeft := GPadding - FLeftDrawOffset; vTop := (Height - ACanvas.TextHeight('荆')) div 2; ACanvas.Brush.Style := bsClear; Windows.ExtTextOut(ACanvas.Handle, vLeft, vTop, 0, nil, Text, Length(Text), nil); if (FArea = dtaYear) and (FNewYear <> '') then begin //vRect := Rect(vLeft, vTop, FAreaRect.Right, FAreaRect.Bottom); ACanvas.Brush.Style := bsSolid; ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(FAreaRect); Windows.DrawText(ACanvas.Handle, FNewYear, -1, FAreaRect, DT_RIGHT or DT_SINGLELINE); end; // finally // SelectClipRgn(ACanvas.Handle, 0); // 清除剪切区域 // end; end; function TCFDateTimePicker.FindFirstDateTimeArea(var AArea: TDateTimeArea): TRect; var vDC: HDC; vSize: TSize; vS, vDateTimeText: string; vOffset, AppendLevel: Integer; {$REGION '内部函数'} procedure AppendChars(P: PChar; Count: Integer); begin Inc(vOffset, Count); end; function NumberText(Number, Digits: Integer): string; const Format: array[0..3] of Char = '%.*d'; var NumBuf: array[0..15] of Char; vLen: Integer; begin vLen := FormatBuf(NumBuf, Length(NumBuf), Format, Length(Format), [Digits, Number]); SetString(Result, NumBuf, vLen); end; procedure AppendFormat(Format: PChar); var Starter, Token, LastToken: Char; DateDecoded, TimeDecoded, Use12HourClock, BetweenQuotes: Boolean; P: PChar; Count: Integer; Year, Month, Day, Hour, Min, Sec, MSec, H: Word; procedure GetCount; // 获取连续是Starter的字符有几个 var P: PChar; begin P := Format; while Format^ = Starter do Inc(Format); Count := Format - P + 1; end; procedure GetDate; // 分解日期 begin if not DateDecoded then begin DecodeDate(DateTime, Year, Month, Day); DateDecoded := True; end; end; procedure GetTime; // 分解时间 begin if not TimeDecoded then begin DecodeTime(DateTime, Hour, Min, Sec, MSec); TimeDecoded := True; end; end; function ConvertEraString(const Count: Integer) : string; var FormatStr: string; SystemTime: TSystemTime; Buffer: array[Byte] of Char; P: PChar; begin Result := ''; with SystemTime do begin wYear := Year; wMonth := Month; wDay := Day; end; FormatStr := 'gg'; if GetDateFormat(GetThreadLocale, DATE_USE_ALT_CALENDAR, @SystemTime, PChar(FormatStr), Buffer, Length(Buffer)) <> 0 then begin Result := Buffer; if Count = 1 then begin case SysLocale.PriLangID of LANG_JAPANESE: Result := Copy(Result, 1, CharToBytelen(Result, 1)); LANG_CHINESE: if (SysLocale.SubLangID = SUBLANG_CHINESE_TRADITIONAL) and (ByteToCharLen(Result, Length(Result)) = 4) then begin P := Buffer + CharToByteIndex(Result, 3) - 1; SetString(Result, P, CharToByteLen(P, 2)); end; end; end; end; end; function ConvertYearString(const Count: Integer): string; var FormatStr: string; SystemTime: TSystemTime; Buffer: array[Byte] of Char; begin Result := ''; with SystemTime do begin wYear := Year; wMonth := Month; wDay := Day; end; if Count <= 2 then FormatStr := 'yy' // avoid Win95 bug. else FormatStr := 'yyyy'; if GetDateFormat(GetThreadLocale, DATE_USE_ALT_CALENDAR, @SystemTime, PChar(FormatStr), Buffer, Length(Buffer)) <> 0 then begin Result := Buffer; if (Count = 1) and (Result[1] = '0') then Result := Copy(Result, 2, Length(Result)-1); end; end; begin if (Format <> nil) and (AppendLevel < 2) then begin Inc(AppendLevel); LastToken := ' '; DateDecoded := False; TimeDecoded := False; Use12HourClock := False; while Format^ <> #0 do begin Starter := Format^; // 当前字符串第1个字符 if IsLeadChar(Starter) then // 本地 MBCS Ansi 字符的集合 begin Format := StrNextChar(Format); LastToken := ' '; Continue; end; Format := StrNextChar(Format); Token := Starter; if Token in ['a'..'z'] then Dec(Token, 32); if Token in ['A'..'Z'] then begin if (Token = 'M') and (LastToken = 'H') then Token := 'N'; LastToken := Token; end; case Token of 'Y': // 年 begin GetCount; // 年有几位 GetDate; // 分解日期 // 年起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 年数据 if Count <= 2 then begin vS := NumberText(Year mod 100, 2); Inc(vOffset, Length(vS)); end else begin vS := NumberText(Year, 4); Inc(vOffset, Length(vS)); end; // 年数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaYear; Exit; end; 'G': // 公元 begin GetCount; // 公元几位显示 GetDate; //AppendString(ConvertEraString(Count)); Inc(vOffset, Length(ConvertEraString(Count))); end; 'E': // 年,只有一个E时表示后2位年 begin GetCount; GetDate; // 年起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 年数据 vS := ConvertYearString(Count); Inc(vOffset, Length(vS)); // 年数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaYear; Exit; end; 'M': // 月 begin GetCount; // 月份几位显示 GetDate; // 月起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 月数据 case Count of 1, 2: vS := NumberText(Month, Count); 3: vS := FormatSettings.ShortMonthNames[Month]; else vS := FormatSettings.LongMonthNames[Month]; end; Inc(vOffset, Length(vS)); // 月数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaMonth; Exit; end; 'D': // 日 begin GetCount; // 日期几位显示 // 日起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 日数据 if Count < 5 then begin case Count of 1, 2: begin GetDate; vS := NumberText(Day, Count); end; 3: vS := FormatSettings.ShortDayNames[DayOfWeek(DateTime)]; 4: vS := FormatSettings.LongDayNames[DayOfWeek(DateTime)]; end; Inc(vOffset, Length(vS)); // 日数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaDay; Exit; end else if Count = 5 then AppendFormat(Pointer(FormatSettings.ShortDateFormat)) else if Count > 5 then AppendFormat(Pointer(FormatSettings.LongDateFormat)); end; 'H': // 时 begin GetCount; // 小时几位显示 GetTime; // 分散时间 BetweenQuotes := False; P := Format; while P^ <> #0 do begin if IsLeadChar(P^) then begin P := StrNextChar(P); Continue; end; case P^ of 'A', 'a': if not BetweenQuotes then begin if ( (StrLIComp(P, 'AM/PM', 5) = 0) or (StrLIComp(P, 'A/P', 3) = 0) or (StrLIComp(P, 'AMPM', 4) = 0) ) then Use12HourClock := True; Break; end; 'H', 'h': Break; '''', '"': BetweenQuotes := not BetweenQuotes; end; Inc(P); end; H := Hour; if Use12HourClock then if H = 0 then H := 12 else if H > 12 then Dec(H, 12); if Count > 2 then Count := 2; //AppendNumber(H, Count); // 时起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 时数据 vS := NumberText(H, Count); Inc(vOffset, Length(vS)); // 时数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaHour; Exit; end; 'N': // 分 begin GetCount; GetTime; if Count > 2 then Count := 2; //AppendNumber(Min, Count); // 分起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 分数据 vS := NumberText(Min, Count); Inc(vOffset, Length(vS)); // 分数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaMinute; Exit; end; 'S': // 秒 begin GetCount; GetTime; if Count > 2 then Count := 2; //AppendNumber(Sec, Count); // 秒起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 秒数据 vS := NumberText(Sec, Count); Inc(vOffset, Length(vS)); // 秒数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaSecond; Exit; end; 'T': // 时间 begin GetCount; if Count = 1 then AppendFormat(Pointer(FormatSettings.ShortTimeFormat)) else AppendFormat(Pointer(FormatSettings.LongTimeFormat)); end; 'Z': // 毫秒 begin GetCount; GetTime; if Count > 3 then Count := 3; //AppendNumber(MSec, Count); // 毫秒起始坐标 vS := Copy(vDateTimeText, 1, vOffset); Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 毫秒数据 vS := NumberText(MSec, Count); Inc(vOffset, Length(vS)); // 毫秒数据所在范围 Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; AArea := dtaMillisecond; Exit; end; 'A': // 上午、下午 begin GetTime; P := Format - 1; if StrLIComp(P, 'AM/PM', 5) = 0 then begin if Hour >= 12 then Inc(P, 3); //AppendChars(P, 2); Inc(vOffset, 2); Inc(Format, 4); Use12HourClock := TRUE; end else if StrLIComp(P, 'A/P', 3) = 0 then begin if Hour >= 12 then Inc(P, 2); //AppendChars(P, 1); Inc(vOffset); Inc(Format, 2); Use12HourClock := TRUE; end else if StrLIComp(P, 'AMPM', 4) = 0 then begin if Hour < 12 then begin //AppendString(TimeAMString); Inc(vOffset, Length(FormatSettings.TimeAMString)); end else begin //AppendString(TimePMString); Inc(vOffset, Length(FormatSettings.TimePMString)); end; Inc(Format, 3); Use12HourClock := TRUE; end else if StrLIComp(P, 'AAAA', 4) = 0 then begin GetDate; //AppendString(LongDayNames[DayOfWeek(DateTime)]); Inc(vOffset, Length(FormatSettings.LongDayNames[DayOfWeek(DateTime)])); Inc(Format, 3); end else if StrLIComp(P, 'AAA', 3) = 0 then begin GetDate; //AppendString(ShortDayNames[DayOfWeek(DateTime)]); Inc(vOffset, Length(FormatSettings.ShortDayNames[DayOfWeek(DateTime)])); Inc(Format, 2); end else begin //AppendChars(@Starter, 1); Inc(vOffset); end; end; 'C': // 短格式日期时间 begin GetCount; AppendFormat(Pointer(FormatSettings.ShortDateFormat)); GetTime; if (Hour <> 0) or (Min <> 0) or (Sec <> 0) then begin //AppendChars(' ', 1); Inc(vOffset); AppendFormat(Pointer(FormatSettings.LongTimeFormat)); end; end; '/': // 日期分隔 if FormatSettings.DateSeparator <> #0 then begin //AppendChars(@DateSeparator, 1); Inc(vOffset); end; ':': // 时间分隔 if FormatSettings.TimeSeparator <> #0 then begin //AppendChars(@TimeSeparator, 1); Inc(vOffset); end; '''', '"': // 无效字符不做输出? begin P := Format; while (Format^ <> #0) and (Format^ <> Starter) do begin if IsLeadChar(Format^) then Format := StrNextChar(Format) else Inc(Format); end; //AppendChars(P, Format - P); Inc(vOffset, Format - P); if Format^ <> #0 then Inc(Format); end; else begin //AppendChars(@Starter, 1); Inc(vOffset); end; end; end; Dec(AppendLevel); end; end; {$ENDREGION} var vOldFont: hGdiObj; begin SetRectEmpty(Result); AArea := dtaNone; vDateTimeText := FormatDateTime(FFormat, DateTime); vOffset := 0; AppendLevel := 0; vDC := GetDC(0); try vOldFont := GetCurrentObject(vDC, OBJ_FONT); SelectObject(vDC, Font.Handle); try if FFormat <> '' then AppendFormat(PChar(FFormat)) else AppendFormat('C'); // C 用短格式显示日期与时间 finally SelectObject(vDC, vOldFont); end; finally ReleaseDC(0, vDC); end; end; function TCFDateTimePicker.GetAreaAt(const X, Y: Integer; var AArea: TDateTimeArea; const ACalcArea: Boolean = True): TRect; var //vDC: HDC; vSize: TSize; vS, vDateTimeText: string; vOffset, AppendLevel: Integer; {$REGION '内部函数'} procedure AppendChars(P: PChar; Count: Integer); begin Inc(vOffset, Count); end; function NumberText(Number, Digits: Integer): string; const Format: array[0..3] of Char = '%.*d'; var NumBuf: array[0..15] of Char; vLen: Integer; begin vLen := FormatBuf(NumBuf, Length(NumBuf), Format, Length(Format), [Digits, Number]); SetString(Result, NumBuf, vLen); end; procedure AppendFormat(Format: PChar); var Starter, Token, LastToken: Char; DateDecoded, TimeDecoded, Use12HourClock, BetweenQuotes: Boolean; P: PChar; Count: Integer; Year, Month, Day, Hour, Min, Sec, MSec, H: Word; procedure GetCount; // 获取连续是Starter的字符有几个 var P: PChar; begin P := Format; while Format^ = Starter do Inc(Format); Count := Format - P + 1; end; procedure GetDate; // 分解日期 begin if not DateDecoded then begin DecodeDate(DateTime, Year, Month, Day); DateDecoded := True; end; end; procedure GetTime; // 分解时间 begin if not TimeDecoded then begin DecodeTime(DateTime, Hour, Min, Sec, MSec); TimeDecoded := True; end; end; function ConvertEraString(const Count: Integer) : string; var FormatStr: string; SystemTime: TSystemTime; Buffer: array[Byte] of Char; P: PChar; begin Result := ''; with SystemTime do begin wYear := Year; wMonth := Month; wDay := Day; end; FormatStr := 'gg'; if GetDateFormat(GetThreadLocale, DATE_USE_ALT_CALENDAR, @SystemTime, PChar(FormatStr), Buffer, Length(Buffer)) <> 0 then begin Result := Buffer; if Count = 1 then begin case SysLocale.PriLangID of LANG_JAPANESE: Result := Copy(Result, 1, CharToBytelen(Result, 1)); LANG_CHINESE: if (SysLocale.SubLangID = SUBLANG_CHINESE_TRADITIONAL) and (ByteToCharLen(Result, Length(Result)) = 4) then begin P := Buffer + CharToByteIndex(Result, 3) - 1; SetString(Result, P, CharToByteLen(P, 2)); end; end; end; end; end; function ConvertYearString(const Count: Integer): string; var FormatStr: string; SystemTime: TSystemTime; Buffer: array[Byte] of Char; begin Result := ''; with SystemTime do begin wYear := Year; wMonth := Month; wDay := Day; end; if Count <= 2 then FormatStr := 'yy' // avoid Win95 bug. else FormatStr := 'yyyy'; if GetDateFormat(GetThreadLocale, DATE_USE_ALT_CALENDAR, @SystemTime, PChar(FormatStr), Buffer, Length(Buffer)) <> 0 then begin Result := Buffer; if (Count = 1) and (Result[1] = '0') then Result := Copy(Result, 2, Length(Result)-1); end; end; begin if (Format <> nil) and (AppendLevel < 2) then begin Inc(AppendLevel); LastToken := ' '; DateDecoded := False; TimeDecoded := False; Use12HourClock := False; while Format^ <> #0 do begin Starter := Format^; // 当前字符串第1个字符 if IsLeadChar(Starter) then // 本地 MBCS Ansi 字符的集合 begin Format := StrNextChar(Format); LastToken := ' '; Continue; end; Format := StrNextChar(Format); Token := Starter; if Token in ['a'..'z'] then Dec(Token, 32); if Token in ['A'..'Z'] then begin if (Token = 'M') and (LastToken = 'H') then Token := 'N'; LastToken := Token; end; case Token of 'Y': // 年 begin GetCount; // 年有几位 GetDate; // 分解日期 // 年起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 年数据 if Count <= 2 then begin vS := NumberText(Year mod 100, 2); Inc(vOffset, Length(vS)); end else begin vS := NumberText(Year, 4); Inc(vOffset, Length(vS)); end; // 年数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaYear then Exit; if Format = '' then begin AArea := dtaYear; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaYear; Exit; end; end; 'G': // 公元 begin GetCount; // 公元几位显示 GetDate; //AppendString(ConvertEraString(Count)); Inc(vOffset, Length(ConvertEraString(Count))); end; 'E': // 年,只有一个E时表示后2位年 begin GetCount; GetDate; // 年起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 年数据 vS := ConvertYearString(Count); Inc(vOffset, Length(vS)); // 年数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaYear then Exit; if Format = '' then begin AArea := dtaYear; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaYear; Exit; end; end; 'M': // 月 begin GetCount; // 月份几位显示 GetDate; // 月起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 月数据 case Count of 1, 2: vS := NumberText(Month, Count); 3: vS := FormatSettings.ShortMonthNames[Month]; else vS := FormatSettings.LongMonthNames[Month]; end; Inc(vOffset, Length(vS)); // 月数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaMonth then Exit; if Format = '' then begin AArea := dtaMonth; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaMonth; Exit; end; end; 'D': // 日 begin GetCount; // 日期几位显示 // 日起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 日数据 case Count of 1, 2: begin GetDate; vS := NumberText(Day, Count); end; 3: vS := FormatSettings.ShortDayNames[DayOfWeek(DateTime)]; 4: vS := FormatSettings.LongDayNames[DayOfWeek(DateTime)]; end; Inc(vOffset, Length(vS)); // 日数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaDay then Exit; if Format = '' then begin AArea := dtaDay; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaDay; Exit; end; if Count = 5 then AppendFormat(Pointer(FormatSettings.ShortDateFormat)) else if Count > 5 then AppendFormat(Pointer(FormatSettings.LongDateFormat)); end; 'H': // 时 begin GetCount; // 小时几位显示 GetTime; // 分散时间 BetweenQuotes := False; P := Format; while P^ <> #0 do begin if IsLeadChar(P^) then begin P := StrNextChar(P); Continue; end; case P^ of 'A', 'a': if not BetweenQuotes then begin if ( (StrLIComp(P, 'AM/PM', 5) = 0) or (StrLIComp(P, 'A/P', 3) = 0) or (StrLIComp(P, 'AMPM', 4) = 0) ) then Use12HourClock := True; Break; end; 'H', 'h': Break; '''', '"': BetweenQuotes := not BetweenQuotes; end; Inc(P); end; H := Hour; if Use12HourClock then if H = 0 then H := 12 else if H > 12 then Dec(H, 12); if Count > 2 then Count := 2; //AppendNumber(H, Count); // 时起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 时数据 vS := NumberText(H, Count); Inc(vOffset, Length(vS)); // 时数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaHour then Exit; if Format = '' then begin AArea := dtaHour; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaHour; Exit; end; end; 'N': // 分 begin GetCount; GetTime; if Count > 2 then Count := 2; //AppendNumber(Min, Count); // 分起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 分数据 vS := NumberText(Min, Count); Inc(vOffset, Length(vS)); // 分数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaMinute then Exit; if Format = '' then begin AArea := dtaMinute; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaMinute; Exit; end; end; 'S': // 秒 begin GetCount; GetTime; if Count > 2 then Count := 2; //AppendNumber(Sec, Count); // 秒起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 秒数据 vS := NumberText(Sec, Count); Inc(vOffset, Length(vS)); // 秒数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaSecond then Exit; if Format = '' then begin AArea := dtaSecond; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaSecond; Exit; end; end; 'T': // 时间 begin GetCount; if Count = 1 then AppendFormat(Pointer(FormatSettings.ShortTimeFormat)) else AppendFormat(Pointer(FormatSettings.LongTimeFormat)); end; 'Z': // 毫秒 begin GetCount; GetTime; if Count > 3 then Count := 3; //AppendNumber(MSec, Count); // 毫秒起始坐标 vS := Copy(vDateTimeText, 1, vOffset); vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Left := GPadding + vSize.cx; // 毫秒数据 vS := NumberText(MSec, Count); Inc(vOffset, Length(vS)); // 毫秒数据所在范围 vSize := Canvas.TextExtent(vS); //Windows.GetTextExtentPoint32(vDC, vS, Length(vS), vSize); Result.Top := (Height - vSize.cy) div 2; Result.Right := Result.Left + vSize.cx; Result.Bottom := Result.Top + vSize.cy; if not ACalcArea then begin if AArea = dtaMillisecond then Exit; if Format = '' then begin AArea := dtaMillisecond; //SetRectEmpty(Result); Exit; end; end; if PtInRect(Result, Point(X, Y)) then begin AArea := dtaMillisecond; Exit; end; end; 'A': // 上午、下午 begin GetTime; P := Format - 1; if StrLIComp(P, 'AM/PM', 5) = 0 then begin if Hour >= 12 then Inc(P, 3); //AppendChars(P, 2); Inc(vOffset, 2); Inc(Format, 4); Use12HourClock := TRUE; end else if StrLIComp(P, 'A/P', 3) = 0 then begin if Hour >= 12 then Inc(P, 2); //AppendChars(P, 1); Inc(vOffset); Inc(Format, 2); Use12HourClock := TRUE; end else if StrLIComp(P, 'AMPM', 4) = 0 then begin if Hour < 12 then begin //AppendString(TimeAMString); Inc(vOffset, Length(FormatSettings.TimeAMString)); end else begin //AppendString(TimePMString); Inc(vOffset, Length(FormatSettings.TimePMString)); end; Inc(Format, 3); Use12HourClock := TRUE; end else if StrLIComp(P, 'AAAA', 4) = 0 then begin GetDate; //AppendString(LongDayNames[DayOfWeek(DateTime)]); Inc(vOffset, Length(FormatSettings.LongDayNames[DayOfWeek(DateTime)])); Inc(Format, 3); end else if StrLIComp(P, 'AAA', 3) = 0 then begin GetDate; //AppendString(ShortDayNames[DayOfWeek(DateTime)]); Inc(vOffset, Length(FormatSettings.ShortDayNames[DayOfWeek(DateTime)])); Inc(Format, 2); end else begin //AppendChars(@Starter, 1); Inc(vOffset); end; end; 'C': // 短格式日期时间 begin GetCount; AppendFormat(Pointer(FormatSettings.ShortDateFormat)); GetTime; if (Hour <> 0) or (Min <> 0) or (Sec <> 0) then begin //AppendChars(' ', 1); Inc(vOffset); AppendFormat(Pointer(FormatSettings.LongTimeFormat)); end; end; '/': // 日期分隔 if FormatSettings.DateSeparator <> #0 then begin //AppendChars(@DateSeparator, 1); Inc(vOffset); end; ':': // 时间分隔 if FormatSettings.TimeSeparator <> #0 then begin //AppendChars(@TimeSeparator, 1); Inc(vOffset); end; '''', '"': // 无效字符不做输出? begin P := Format; while (Format^ <> #0) and (Format^ <> Starter) do begin if IsLeadChar(Format^) then Format := StrNextChar(Format) else Inc(Format); end; //AppendChars(P, Format - P); Inc(vOffset, Format - P); if Format^ <> #0 then Inc(Format); end; else begin //AppendChars(@Starter, 1); Inc(vOffset); end; end; end; Dec(AppendLevel); end; end; {$ENDREGION} begin SetRectEmpty(Result); if ACalcArea then AArea := dtaNone; vDateTimeText := FormatDateTime(FFormat, DateTime); vOffset := 0; AppendLevel := 0; if FFormat <> '' then AppendFormat(PChar(FFormat)) else AppendFormat('C'); // C 用短格式显示日期与时间 end; function TCFDateTimePicker.GetDateTime: TDateTime; begin Result := FCalendar.Date; end; function TCFDateTimePicker.GetMaxDateTime: TDateTime; begin Result := FCalendar.MaxDate; end; function TCFDateTimePicker.GetMinDateTime: TDateTime; begin Result := FCalendar.MinDate; end; procedure TCFDateTimePicker.KeyDown(var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: // 取消输入的年字符串 begin if FNewYear <> '' then begin FNewYear := ''; UpdateDirectUI; end; end; VK_RETURN: begin if FNewYear <> '' then SetInputYear; end; VK_LEFT: begin if FNewYear <> '' then SetInputYear; case FArea of dtaNone, dtaYear: FArea := dtaMillisecond; dtaMonth: FArea := dtaYear; dtaDay: FArea := dtaMonth; dtaHour: FArea := dtaDay; dtaMinute: FArea := dtaHour; dtaSecond: FArea := dtaMinute; dtaMillisecond: FArea := dtaSecond; end; //FArea := Pred(FArea); FAreaRect := GetAreaAt(0, 0, FArea, False); UpdateDirectUI; end; VK_RIGHT: begin if FNewYear <> '' then SetInputYear; case FArea of dtaNone, dtaYear: FArea := dtaMonth; dtaMonth: FArea := dtaDay; dtaDay: FArea := dtaHour; dtaHour: FArea := dtaMinute; dtaMinute: FArea := dtaSecond; dtaSecond: FArea := dtaMillisecond; dtaMillisecond: FArea := dtaYear; end; //FArea := Succ(FArea); FAreaRect := GetAreaAt(0, 0, FArea, False); UpdateDirectUI; end; end; inherited KeyDown(Key, Shift); end; procedure TCFDateTimePicker.KeyPress(var Key: Char); var vNumber, vCount: Word; begin inherited KeyPress(Key); if FReadOnly then Exit; if FArea <> dtaNone then begin if Key in ['0'..'9'] then begin case FArea of dtaYear: begin if Length(FNewYear) > 3 then System.Delete(FNewYear, 1, 1); FNewYear := FNewYear + Key; end; dtaMonth: begin; vNumber := MonthOf(DateTime); // 当前月份 if vNumber > 9 then // 当前月份已经是2位数了 begin if Key = '0' then Exit; // 2位月份再输入0不处理 DateTime := RecodeMonth(DateTime, StrToInt(Key)); // 直接修改为新键入 end else // 当前月份是1位数字 if (vNumber = 1) and FJoinKey then // 当前月份是1月且是连续输入 begin if Key in ['0'..'2'] then // 10, 11, 12 begin vNumber := vNumber * 10 + StrToInt(Key); DateTime := RecodeMonth(DateTime, vNumber); // 直接修改为新键入 end; end else // 不是连续输入,是第1次输入 begin if Key = '0' then Exit; // 月份第1位是0不处理 DateTime := RecodeMonth(DateTime, StrToInt(Key)); // 直接修改为新键入 end; end; dtaDay: begin vNumber := DayOf(DateTime); // 当前日期 if vNumber > 9 then // 当前日期已经是2位数了 begin if Key = '0' then Exit; // 2位日期再输入0不处理 DateTime := RecodeDay(DateTime, StrToInt(Key)); // 直接修改为新键入 end else // 当前日期是1位数字 if FJoinKey then // 是连续输入 begin vNumber := vNumber * 10 + StrToInt(Key); vCount := DaysInMonth(DateTime); if vNumber > vCount then vNumber := StrToInt(Key); DateTime := RecodeDay(DateTime, vNumber); // 直接修改为新键入 end else // 不是连续输入,是第1次输入 begin if Key = '0' then Exit; // 月份第1位是0不处理 DateTime := RecodeDay(DateTime, StrToInt(Key)); // 直接修改为新键入 end; end; dtaHour: begin vNumber := HourOf(DateTime); // 当前时 if vNumber > 9 then // 当前时已经是2位数了 begin if Key = '0' then Exit; // 2位时再输入0不处理 DateTime := RecodeHour(DateTime, StrToInt(Key)); // 直接修改为新键入 end else // 当前时是1位数字 if FJoinKey then // 当前时是是连续输入 begin vNumber := vNumber * 10 + StrToInt(Key); if vNumber > 24 then vNumber := StrToInt(Key); DateTime := RecodeHour(DateTime, vNumber); // 直接修改为新键入 end else // 不是连续输入,是第1次输入 begin if Key = '0' then Exit; // 时第1位是0不处理 DateTime := RecodeHour(DateTime, StrToInt(Key)); // 直接修改为新键入 end; end; dtaMinute: begin vNumber := MinuteOf(DateTime); // 当前分 if vNumber > 9 then // 当前分已经是2位数了 begin if Key = '0' then Exit; // 2位时再输入0不处理 DateTime := RecodeMinute(DateTime, StrToInt(Key)); // 直接修改为新键入 end else // 当前分是1位数字 if FJoinKey then // 当前分是是连续输入 begin vNumber := vNumber * 10 + StrToInt(Key); if vNumber > 60 then vNumber := StrToInt(Key); DateTime := RecodeMinute(DateTime, vNumber); // 直接修改为新键入 end else // 不是连续输入,是第1次输入 begin if Key = '0' then Exit; // 分第1位是0不处理 DateTime := RecodeMinute(DateTime, StrToInt(Key)); // 直接修改为新键入 end; end; dtaSecond: begin vNumber := SecondOf(DateTime); // 当前秒 if vNumber > 9 then // 当前秒已经是2位数了 begin if Key = '0' then Exit; // 2位时再输入0不处理 DateTime := RecodeSecond(DateTime, StrToInt(Key)); // 直接修改为新键入 end else // 当前秒是1位数字 if FJoinKey then // 当前秒是是连续输入 begin vNumber := vNumber * 10 + StrToInt(Key); if vNumber > 60 then vNumber := StrToInt(Key); DateTime := RecodeSecond(DateTime, vNumber); // 直接修改为新键入 end else // 不是连续输入,是第1次输入 begin if Key = '0' then Exit; // 秒第1位是0不处理 DateTime := RecodeSecond(DateTime, StrToInt(Key)); // 直接修改为新键入 end; end; dtaMillisecond: Exit; end; end; if FArea <> dtaYear then // 除年外,其他的需要实时更新 begin ReBuildArea(FAreaRect.Left + FLeftDrawOffset, FAreaRect.Top); FJoinKey := True; end; UpdateDirectUI; end; end; procedure TCFDateTimePicker.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var vOldArea: TDateTimeArea; begin inherited MouseDown(Button, Shift, X, Y); FJoinKey := False; // 中断连续输入 vOldArea := FArea; ReBuildArea(X + FLeftDrawOffset, Y); // 不偏移时点击在日期时间的哪一部位 if FArea <> vOldArea then begin if vOldArea = dtaYear then // 上一个激活的区域是年 SetInputYear; UpdateDirectUI; end; end; procedure TCFDateTimePicker.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); // 如果放到DouseDonw中,则弹出框显示时再点击按钮执行关闭弹出框 if PtInRect(Rect(Width - GIconWidth, GBorderWidth, Width - GBorderWidth, Height - GBorderWidth), Point(X, Y)) then DoButtonClick(Self); end; procedure TCFDateTimePicker.PopupPicker; begin FPopup := TCFPopup.Create(Self); try FPopup.PopupControl := Self; FPopup.OnDrawWindow := DoOnPopupDrawWindow; FPopup.SetSize(FCalendar.Width, FCalendar.Height); FPopup.Popup(Self); finally FPopup.Free; end; end; procedure TCFDateTimePicker.ReBuildArea(X, Y: Integer); begin FAreaRect := GetAreaAt(X, Y, FArea); if FArea <> dtaNone then // 有效区域,计算偏移 begin if FAreaRect.Left - FLeftDrawOffset < GPadding then // 优先判断左侧不能显示全 FLeftDrawOffset := FAreaRect.Left - FLeftDrawOffset else begin if FButtonVisible then begin if FAreaRect.Right > Width - GIconWidth then // 右侧不能显示全 FLeftDrawOffset := FAreaRect.Right - (Width - GIconWidth); end else begin if FAreaRect.Right > Width - GPadding then // 右侧不能显示全 FLeftDrawOffset := FAreaRect.Right - (Width - GPadding); end; end; OffsetRect(FAreaRect, -FLeftDrawOffset, 0); end else FLeftDrawOffset := 0; end; procedure TCFDateTimePicker.SetFormat(Value: string); begin if FFormat <> Value then begin FFormat := Value; Text := FormatDateTime(FFormat, FCalendar.Date); end; end; procedure TCFDateTimePicker.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var vDC: HDC; vHeight, vWidth: Integer; begin vDC := GetDC(0); try Canvas.Handle := vDC; Canvas.Font := Font; vWidth := Canvas.TextWidth(FormatDateTime('YYYY-MM-DD', Now)) + GetSystemMetrics(SM_CYBORDER) * 2; if FButtonVisible then vWidth := vWidth + GIconWidth; if vWidth < AWidth then vWidth := AWidth; vHeight := Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth; if vHeight < AHeight then vHeight := AHeight; Canvas.Handle := 0; finally ReleaseDC(0, vDC); end; inherited SetBounds(ALeft, ATop, vWidth, vHeight); end; procedure TCFDateTimePicker.SetButtonVisible(Value: Boolean); begin if FButtonVisible <> Value then begin FButtonVisible := Value; UpdateDirectUI; end; end; procedure TCFDateTimePicker.SetDateTime(Value: TDateTime); begin FCalendar.Date := Value; DoDateTimeChanged(Self); end; procedure TCFDateTimePicker.SetInputYear; function GetYear(const AYear: string): Word; function Power10(const Sqr: Byte): Cardinal; var i: Integer; begin Result := 10; for i := 2 to Sqr do Result := Result * 10; end; var vYear: Word; vPie: Cardinal; begin Result := YearOf(DateTime); vYear := StrToIntDef(AYear, Result); if vYear < Result then begin vPie := Power10(System.Length(AYear)); Result := Result div vPie; Result := Result * vPie + vYear; end else Result := vYear; end; begin if FNewYear <> '' then // 有输入年,根据输入字符串确定输入的年 begin DateTime := RecodeYear(DateTime, GetYear(FNewYear)); FNewYear := ''; // 取消输入的年内容 end; end; procedure TCFDateTimePicker.SetMaxDateTime(Value: TDateTime); begin FCalendar.MaxDate := Value; end; procedure TCFDateTimePicker.SetMinDateTime(Value: TDateTime); begin FCalendar.MinDate := Value; end; procedure TCFDateTimePicker.WMCFLBUTTONDBLCLK(var Message: TMessage); begin // if (CompareDate(FCalendar.Date, MinDate) >= 0) // and (CompareDate(FCalendar.Date, FMaxDate) <= 0) // 在边界范围内 // then if FCalendar.Perform(Message.Msg, Message.WParam, Message.LParam) = 1 then FPopup.UpdatePopup else begin FPopup.ClosePopup(False); DoDateTimeChanged(Self); end; {if Assigned(FOnCloseUp) then FOnCloseUp(Self);} end; procedure TCFDateTimePicker.WMCFLBUTTONDOWN(var Message: TMessage); begin if FCalendar.Perform(Message.Msg, Message.WParam, Message.LParam) = 1 then FPopup.UpdatePopup else begin FPopup.ClosePopup(False); DoDateTimeChanged(Self); end; end; procedure TCFDateTimePicker.WMCFLBUTTONUP(var Message: TMessage); begin if FCalendar.Perform(Message.Msg, Message.WParam, Message.LParam) = 1 then FPopup.UpdatePopup; end; procedure TCFDateTimePicker.WMCFMOUSEMOVE(var Message: TMessage); begin if FCalendar.Perform(Message.Msg, Message.WParam, Message.LParam) = 1 then FPopup.UpdatePopup; end; procedure TCFDateTimePicker.WMKillFocus(var Message: TWMKillFocus); begin inherited; DisActive; end; end.
unit LessEqOpTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntXLibTypes, uIntX; type { TTestLessEqOp } TTestLessEqOp = class(TTestCase) published procedure Simple(); procedure SimpleFail(); procedure Big(); procedure BigFail(); procedure EqualValues(); end; implementation procedure TTestLessEqOp.Simple(); var int1, int2: TIntX; begin int1 := TIntX.Create(7); int2 := TIntX.Create(8); AssertTrue(int1 <= int2); end; procedure TTestLessEqOp.SimpleFail(); var int1: TIntX; begin int1 := TIntX.Create(8); AssertFalse(int1 <= 7); end; procedure TTestLessEqOp.Big(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); AssertTrue(int2 <= int1); end; procedure TTestLessEqOp.BigFail(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); AssertFalse(int1 <= int2); end; procedure TTestLessEqOp.EqualValues(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 3); temp1[0] := 1; temp1[1] := 2; temp1[2] := 3; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, True); int2 := TIntX.Create(temp2, True); AssertTrue(int1 <= int2); end; initialization RegisterTest(TTestLessEqOp); end.
{**************************************************************************************} { } { CCR.VirtualKeying - sending virtual keystrokes on OS X and Windows } { } { The contents of this file are subject to the Mozilla Public License Version 2.0 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at https://www.mozilla.org/MPL/2.0 } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. See the License for the specific } { language governing rights and limitations under the License. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2015 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} unit VirtualKeying.Consts; interface resourcestring SVirtualKeyingUnsupported = 'Virtual keying is not supported'; SUnrecognizedVirtualKeyCode = 'Unrecognised virtual key code (%d)'; implementation end.
unit tesseractocr.utils; { The MIT License (MIT) TTesseractOCR4 Copyright (c) 2018 Damian Woroch, http://rime.ddns.net/ 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. } interface uses tesseractocr.capi, tesseractocr.consts; function PageOrientationToString(ATessPageOrientation: TessOrientation): String; function TextlineOrderToString(ATessTextlineOrder: TessTextlineOrder): String; function WritingDirectionToString(ATessWritingDirection: TessWritingDirection): String; function ParagraphJustificationToString(ATessParagraphJustification: TessParagraphJustification): String; function BlockTypeToString(ATessPolyBlockType: TessPolyBlockType): String; function PUTF8CharToString(AUTF8Char: PUTF8Char; ADeleteText: Boolean = True): String; implementation function PageOrientationToString(ATessPageOrientation: TessOrientation): String; begin case ATessPageOrientation of ORIENTATION_PAGE_UP: Result := 'Up'; ORIENTATION_PAGE_RIGHT: Result := 'Right'; ORIENTATION_PAGE_DOWN: Result := 'Down'; ORIENTATION_PAGE_LEFT: Result := 'Left'; else Result := ''; end; end; function TextlineOrderToString(ATessTextlineOrder: TessTextlineOrder): String; begin case ATessTextlineOrder of TEXTLINE_ORDER_LEFT_TO_RIGHT: Result := 'LTR'; TEXTLINE_ORDER_RIGHT_TO_LEFT: Result := 'RTL'; TEXTLINE_ORDER_TOP_TO_BOTTOM: Result := 'TTB'; else Result := ''; end; end; function WritingDirectionToString(ATessWritingDirection: TessWritingDirection): String; begin case ATessWritingDirection of WRITING_DIRECTION_LEFT_TO_RIGHT: Result := 'LTR'; WRITING_DIRECTION_RIGHT_TO_LEFT: Result := 'RTL'; WRITING_DIRECTION_TOP_TO_BOTTOM: Result := 'TTB'; else Result := ''; end; end; function ParagraphJustificationToString(ATessParagraphJustification: TessParagraphJustification): String; begin case ATessParagraphJustification of JUSTIFICATION_UNKNOWN: Result := 'Unknown'; JUSTIFICATION_LEFT: Result := 'Left'; JUSTIFICATION_CENTER: Result := 'Center'; JUSTIFICATION_RIGHT: Result := 'Right'; else Result := ''; end; end; function BlockTypeToString(ATessPolyBlockType: TessPolyBlockType): String; begin case ATessPolyBlockType of PT_UNKNOWN: Result := 'Unknown'; PT_FLOWING_TEXT: Result := 'Flowing text'; PT_HEADING_TEXT: Result := 'Heading text'; PT_PULLOUT_TEXT: Result := 'Pull-out text'; PT_EQUATION: Result := 'Equation'; PT_INLINE_EQUATION: Result := 'Inline equation'; PT_TABLE: Result := 'Table'; PT_VERTICAL_TEXT: Result := 'Vertical text'; PT_CAPTION_TEXT: Result := 'Caption'; PT_FLOWING_IMAGE: Result := 'Flowing image'; PT_HEADING_IMAGE: Result := 'Heading image'; PT_PULLOUT_IMAGE: Result := 'Pull-out image'; PT_HORZ_LINE: Result := 'Horizontal line'; PT_VERT_LINE: Result := 'Vertical line'; PT_NOISE: Result := 'Noise'; PT_COUNT: Result := 'Count'; else Result := ''; end; end; function PUTF8CharToString(AUTF8Char: PUTF8Char; ADeleteText: Boolean = True): String; var utfString: UTF8String; begin Result := ''; if Assigned(AUTF8Char) then begin SetString(utfString, AUTF8Char, Length(AUTF8Char)); if ADeleteText then TessDeleteText(AUTF8Char); Result := String(utfString); end; end; end.
unit uDlgRemoveObjects; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBASE_SelectForm, Menus, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons, cxControls, cxSplitter, uFrameObjectList, uFrameObjectList_ContractActual, ActnList, dxBar, cxClasses, uFrameBaseGrid, uFrameObjectsByProps, uBASE_DialogForm, dxRibbon, uDlgSelectObjects, DB, ADODB; type TdlgRemoveObjects = class(TBASE_SelectForm) pnlData: TPanel; FrameActual: TFrameObjectList_ContractActual; cxSplitter: TcxSplitter; alRecordsAction: TActionList; actAddRecord: TAction; actRemoveRecord: TAction; pnlSelectedGrid: TPanel; pnlCaption: TPanel; FrameSelected: TFrameObjectsByProps; BarManagerRecordsAction: TdxBarManager; bbAddObject: TdxBarButton; bbDeleteObject: TdxBarButton; BarManagerRecordsActionBar1: TdxBar; BarManagerRecordsActionBar2: TdxBar; dsView: TDataSource; qryView: TADOQuery; dsStatus: TDataSource; qryStatus: TADOQuery; procedure actAddRecordExecute(Sender: TObject); procedure actAddRecordUpdate(Sender: TObject); procedure actRemoveRecordUpdate(Sender: TObject); procedure actRemoveRecordExecute(Sender: TObject); procedure FrameSelectedspObjectListAfterPost(DataSet: TDataSet); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private function GetContractID: integer; function GetOnDate: variant; procedure SetContractID(const Value: integer); procedure SetOnDate(const Value: variant); function GetForDelete: boolean; procedure SetForDelete(const Value: boolean); protected procedure AddObjectById(ObjectID: integer); public SelectedIDs: TIdCollection; property ContractID: integer read GetContractID write SetContractID; property OnDate: variant read GetOnDate write SetOnDate; property ForDelete: boolean read GetForDelete write SetForDelete; procedure ApplyParamsAfterOpen; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var dlgRemoveObjects: TdlgRemoveObjects; implementation uses uMain, uCommonUtils; {$R *.dfm} { TdlgRemoveObjects } procedure TdlgRemoveObjects.ApplyParamsAfterOpen; begin ContractID:=Params['код_Договор'].Value; OnDate:=Params['НаДату'].Value; ForDelete:=Params['ДляУдаления'].Value; //14-07-2009 if Params.Exists('Заголовок окна удаления объектов') then Caption:='Выбор объектов для удаления - ['+Params['Заголовок окна удаления объектов'].Value+']'; //^^^14-07-2009 end; constructor TdlgRemoveObjects.Create(AOwner: TComponent); begin inherited; BarManagerRecordsActionBar1.DockControl:=FrameActual.FrameByProps.DockControlGridToolBar; self.FrameSelected.OpenEmptyData; SelectedIDs:=TIdCollection.Create(TIdItem); qryView.Open; qryStatus.Open; end; destructor TdlgRemoveObjects.Destroy; begin SelectedIDs.Free; inherited; end; function TdlgRemoveObjects.GetContractID: integer; begin result:=FrameActual.ContractID; end; function TdlgRemoveObjects.GetOnDate: variant; begin result:=FrameActual.OnDate; end; procedure TdlgRemoveObjects.SetContractID(const Value: integer); begin FrameActual.ContractID:=Value; end; procedure TdlgRemoveObjects.SetOnDate(const Value: variant); begin FrameActual.OnDate:=Value; end; procedure TdlgRemoveObjects.actAddRecordExecute(Sender: TObject); var i: integer; sr: TViewSelectedRecords; // csr: TCashViewSelectedRecords; begin inherited; { csr:=TCashViewSelectedRecords.Create(self.FrameActual.FrameByProps.ViewCds); if Assigned(csr) then begin for i:=0 to csr.Count-1 do AddObjectById(csr.Items[i].PrimaryKeyValue); csr.Free; end;} sr:=TViewSelectedRecords.Create(self.FrameActual.FrameByProps.ViewCds); if Assigned(sr) then begin for i:=0 to sr.Count-1 do AddObjectById(sr.Items[i].PrimaryKeyValue); sr.Free; end; end; procedure TdlgRemoveObjects.AddObjectById(ObjectID: integer); var qry: TAdoQuery; i: integer; begin if SelectedIDs.Exists(ObjectID) then raise Exception.Create('Данный объект уже в списке для удаления'); qry:=CreateQuery('[sp_Учетная единица_получить] @код_Учетная_единица = '+IntToStr(ObjectID)); try qry.Open; with FrameSelected do begin if not spObjectList.Active then spObjectList.Open; spObjectList.Insert; spObjectList['IntValue']:=ObjectID; spObjectList['ForADOInsertCol']:=false; spObjectList['Учетная единица.Реeстровый номер']:=qry['Учетная единица.Реeстровый номер']; spObjectList['Учетная единица.Балансовая стоимость']:=qry['Учетная единица.Балансовая стоимость']; spObjectList['Учетная единица.Дата ввода в эксплуатацию']:=qry['Учетная единица.Дата ввода в эксплуатацию']; spObjectList['Учетная единица.Входящий износ']:=qry['Учетная единица.Входящий износ']; spObjectList['ОКОФ.ОКОФ']:=qry['ОКОФ.ОКОФ']; spObjectList['Учетная единица.Входящая остаточная стоимость']:=qry['Учетная единица.Входящая остаточная стоимость']; spObjectList['Адрес.Район']:=qry['Адрес.Район']; spObjectList['Адрес.Населенный пункт']:=qry['Адрес.Населенный пункт']; spObjectList['Адрес.Тип']:=qry['Адрес.Тип']; spObjectList['Адрес.Улица']:=qry['Адрес.Улица']; spObjectList['Адрес.№ дома']:=qry['Адрес.№ дома']; spObjectList['Адрес.Корпус']:=qry['Адрес.Корпус']; spObjectList['Адрес.Литер']:=qry['Адрес.Литер']; spObjectList['Адрес.№ квартиры']:=qry['Адрес.№ квартиры']; spObjectList['Учетная единица.Тип объекта']:=qry['Учетная единица.Тип объекта']; spObjectList['Учетная единица.Вид пользования имуществом']:=qry['Учетная единица.Вид пользования имуществом']; spObjectList['Учетная единица.Статус объекта']:=qry['Учетная единица.Статус объекта']; spObjectList.Post; SelectedIDs.Add(ObjectID, qry['Учетная единица.Вид пользования имуществом'], qry['Учетная единица.Статус объекта']); end; finally qry.Free; end; end; procedure TdlgRemoveObjects.actAddRecordUpdate(Sender: TObject); begin inherited; with FrameActual.FrameByProps.DataSourceCash do (Sender as TAction).Enabled:=Active and (FrameActual.FrameByProps.ViewCds.DataController.FilteredRecordCount>0) end; procedure TdlgRemoveObjects.actRemoveRecordUpdate(Sender: TObject); begin inherited; with FrameSelected.spObjectList do (Sender as TAction).Enabled:=Active and (RecordCount>0) end; procedure TdlgRemoveObjects.actRemoveRecordExecute(Sender: TObject); var id: integer; begin if MessageBox(Handle, 'Удалить объект из списка удаляемых?', 'Удаление', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL)=IDNO then exit; id:=FrameSelected.spObjectList['IntValue']; FrameSelected.spObjectList.Delete; SelectedIDs.Delete(id); end; function TdlgRemoveObjects.GetForDelete: boolean; begin result:=FrameActual.ForDelete; end; procedure TdlgRemoveObjects.SetForDelete(const Value: boolean); begin FrameActual.ForDelete:=Value; end; procedure TdlgRemoveObjects.FrameSelectedspObjectListAfterPost( DataSet: TDataSet); var i: integer; begin inherited; i:=SelectedIDs.IdIndex(DataSet.Fields[0].Value); if i=-1 then exit; SelectedIDs[i].ViewID:=DataSet['Учетная единица.Вид пользования имуществом']; SelectedIDs[i].StatusID:=DataSet['Учетная единица.Статус объекта']; end; procedure TdlgRemoveObjects.btnOKClick(Sender: TObject); begin if FrameSelected.spObjectList.State=dsEdit then FrameSelected.spObjectList.Post; inherited; end; procedure TdlgRemoveObjects.FormShow(Sender: TObject); begin inherited; FrameSelected.spObjectList.Close; FrameSelected.spObjectList.CursorLocation:=clUseClient; FrameSelected.spObjectList.LockType:=ltBatchOptimistic; FrameSelected.spObjectList.AfterOpen:=nil; FrameSelected.DataSourceCash.DataSet:=nil; FrameSelected.spObjectList.Open; FrameSelected.GridLevel.GridView:=FrameSelected.View; end; end.
unit uModDOTrader; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModAPP, uModPOTrader, uModBarang, uModSatuan, uModOrganization, System.Generics.Collections, uModUnit, uModGudang, uModAR; type TModDOTraderItem = class; TModDOTrader = class(TModApp) private FDOTraderItems: TObjectList<TModDOTraderItem>; FDOT_DATE: TDatetime; FDOT_DESCRIPTION: string; FDOT_DISC: Double; FDOT_DISC_MEMBER: Double; FDOT_GUDANG: TModGudang; FDOT_LEAD_TIME: Double; FDOT_NO: string; FDOT_Organization: TModOrganization; FDOT_POTrader: TModPOTrader; FDOT_PPN: Double; FDOT_PPNBM: Double; FDOT_STATUS: string; FDOT_SUBTOTAL: Double; FDOT_TOP: Integer; FDOT_TOTAL: Double; FDOT_UNIT: TModUnit; FDOT_AR: TModAR; FDOT_VALID_DATE: TDatetime; function GetDOTraderItems: TObjectList<TModDOTraderItem>; public property DOTraderItems: TObjectList<TModDOTraderItem> read GetDOTraderItems write FDOTraderItems; published property DOT_DATE: TDatetime read FDOT_DATE write FDOT_DATE; property DOT_DESCRIPTION: string read FDOT_DESCRIPTION write FDOT_DESCRIPTION; property DOT_DISC: Double read FDOT_DISC write FDOT_DISC; property DOT_DISC_MEMBER: Double read FDOT_DISC_MEMBER write FDOT_DISC_MEMBER; property DOT_GUDANG: TModGudang read FDOT_GUDANG write FDOT_GUDANG; property DOT_LEAD_TIME: Double read FDOT_LEAD_TIME write FDOT_LEAD_TIME; [AttributeOfCode] property DOT_NO: string read FDOT_NO write FDOT_NO; property DOT_Organization: TModOrganization read FDOT_Organization write FDOT_Organization; property DOT_POTrader: TModPOTrader read FDOT_POTrader write FDOT_POTrader; property DOT_PPN: Double read FDOT_PPN write FDOT_PPN; property DOT_PPNBM: Double read FDOT_PPNBM write FDOT_PPNBM; property DOT_STATUS: string read FDOT_STATUS write FDOT_STATUS; property DOT_SUBTOTAL: Double read FDOT_SUBTOTAL write FDOT_SUBTOTAL; property DOT_TOP: Integer read FDOT_TOP write FDOT_TOP; property DOT_TOTAL: Double read FDOT_TOTAL write FDOT_TOTAL; property DOT_UNIT: TModUnit read FDOT_UNIT write FDOT_UNIT; property DOT_AR: TModAR read FDOT_AR write FDOT_AR; property DOT_VALID_DATE: TDatetime read FDOT_VALID_DATE write FDOT_VALID_DATE; end; TModDOTraderItem = class(TModApp) private FDOTITEM_BARANG: TModBarang; FDOTITEM_COGS: Double; FDOTITEM_DISC: Double; FDOTITEM_DISCRP: Double; FDOTITEM_DOTRADER: TModDOTrader; FDOTITEM_NETSALE: Double; FDOTITEM_PPN: Double; FDOTITEM_PPNRP: Double; FDOTITEM_QTY: Double; FDOTITEM_SATUAN: TModSatuan; FDOTITEM_SELLPRICE: Double; FDOTITEM_TOTAL: Double; public destructor Destroy; override; published property DOTITEM_BARANG: TModBarang read FDOTITEM_BARANG write FDOTITEM_BARANG; property DOTITEM_COGS: Double read FDOTITEM_COGS write FDOTITEM_COGS; property DOTITEM_DISC: Double read FDOTITEM_DISC write FDOTITEM_DISC; property DOTITEM_DISCRP: Double read FDOTITEM_DISCRP write FDOTITEM_DISCRP; [AttributeOfHeader] property DOTITEM_DOTRADER: TModDOTrader read FDOTITEM_DOTRADER write FDOTITEM_DOTRADER; property DOTITEM_NETSALE: Double read FDOTITEM_NETSALE write FDOTITEM_NETSALE; property DOTITEM_PPN: Double read FDOTITEM_PPN write FDOTITEM_PPN; property DOTITEM_PPNRP: Double read FDOTITEM_PPNRP write FDOTITEM_PPNRP; property DOTITEM_QTY: Double read FDOTITEM_QTY write FDOTITEM_QTY; property DOTITEM_SATUAN: TModSatuan read FDOTITEM_SATUAN write FDOTITEM_SATUAN; property DOTITEM_SELLPRICE: Double read FDOTITEM_SELLPRICE write FDOTITEM_SELLPRICE; property DOTITEM_TOTAL: Double read FDOTITEM_TOTAL write FDOTITEM_TOTAL; end; implementation destructor TModDOTraderItem.Destroy; begin inherited; if FDOTITEM_BARANG <> nil then FreeAndNil(FDOTITEM_BARANG); if FDOTITEM_SATUAN <> nil then FreeAndNil(FDOTITEM_SATUAN); end; function TModDOTrader.GetDOTraderItems: TObjectList<TModDOTraderItem>; begin if not Assigned(FDOTraderItems) then FDOTraderItems := TObjectList<TModDOTraderItem>.Create; Result := FDOTraderItems; end; initialization TModDOTrader.RegisterRTTI; end.
unit cWingCalc; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, System.Generics.Collections, Vcl.ExtCtrls, SynCommons; type TForm1 = class(TForm) mmoOutput: TMemo; pnl1: TPanel; pnl2: TPanel; lblNoWings: TLabel; se1: TSpinEdit; btnCalculate: TButton; procedure btnCalculateClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } fWingPrice : TDictionary<integer, Float32>; KeyArray : TIntegerDynArray; function GetMinPrice : string; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnCalculateClick(Sender: TObject); var Min : string; begin Min := GetMinPrice; mmoOutput.Lines.Add(Min); end; procedure TForm1.FormShow(Sender: TObject); begin SetLength(keyArray, 40); fWingPrice := TDictionary<Integer, Float32>.Create; fWingPrice.Add(150,1.112); fWingPrice.Add(125,1.112); fWingPrice.Add(50,1.112); fWingPrice.Add(25,1.112); fWingPrice.Add(200,1.113); fWingPrice.Add(100,1.113); fWingPrice.Add(75,1.113); fWingPrice.Add(26,1.113); fWingPrice.Add(80,1.114); fWingPrice.Add(28,1.114); fWingPrice.Add(27,1.115); fWingPrice.Add(90,1.116); fWingPrice.Add(29,1.116); fWingPrice.Add(60,1.117); fWingPrice.Add(30,1.117); fWingPrice.Add(70,1.119); fWingPrice.Add(35,1.119); fWingPrice.Add(40,1.120); fWingPrice.Add(45,1.122); fWingPrice.Add(21,1.133); fWingPrice.Add(18,1.133); fWingPrice.Add(15,1.133); fWingPrice.Add(12,1.133); fWingPrice.Add(9,1.133); fWingPrice.Add(6,1.133); fWingPrice.Add(22,1.134); fWingPrice.Add(19,1.134); fWingPrice.Add(16,1.134); fWingPrice.Add(24,1.135); fWingPrice.Add(23,1.135); fWingPrice.Add(20,1.135); fWingPrice.Add(17,1.135); fWingPrice.Add(13,1.135); fWingPrice.Add(10,1.135); fWingPrice.Add(14,1.136); fWingPrice.Add(11,1.136); fWingPrice.Add(7,1.136); fWingPrice.Add(8,1.138); fWingPrice.Add(4,1.138); fWingPrice.Add(5,1.140); keyArray[0] := 150; keyArray[1] := 125; keyArray[2] := 50; keyArray[3] := 25; keyArray[4] := 200; keyArray[5] := 100; keyArray[6] := 75; keyArray[7] := 26; keyArray[8] := 80; keyArray[9] := 28; keyArray[10] := 27; keyArray[11] := 90; keyArray[12] := 29; keyArray[13] := 60; keyArray[14] := 30; keyArray[15] := 70; keyArray[16] := 35; keyArray[17] := 40; keyArray[18] := 45; keyArray[19] := 21; keyArray[20] := 18; keyArray[21] := 15; keyArray[22] := 12; keyArray[23] := 9; keyArray[24] := 6; keyArray[25] := 22; keyArray[26] := 19; keyArray[27] := 16; keyArray[28] := 24; keyArray[29] := 23; keyArray[30] := 20; keyArray[31] := 17; keyArray[32] := 13; keyArray[33] := 10; keyArray[34] := 14; keyArray[35] := 11; keyArray[36] := 7; keyArray[37] := 8; keyArray[38] := 4; keyArray[39] := 5; end; function TForm1.GetMinPrice: string; var I : integer; combo, index : TIntegerDynArray; comboDynArray, indexDynArray : TDynArray; current : integer; goal : integer; found, finished : bool; cost : Float32; begin comboDynArray.Init(TypeInfo(TIntegerDynArray), combo); indexDynArray.Init(TypeInfo(TIntegerDynArray), index); found := false; finished := false; goal := se1.Value; I := 0; current := 0; cost := 0; while not finished do begin if current + keyArray[i] = goal then begin current := current + keyArray[I]; comboDynArray.Add(keyArray[I]); finished := true; found := true; end else if current + keyArray[i] > goal then inc(I) else begin current := current + keyArray[I]; comboDynArray.Add(keyArray[I]); indexDynArray.Add(I); end; if (I = length(keyArray)) and (not found) then begin current := current - keyArray[index[indexDynArray.Count - 1]]; I := index[indexDynArray.Count - 1] + 1; if I = length(keyArray) then begin finished := true; exit; end; indexDynArray.Delete(indexDynArray.Count - 1); comboDynArray.Delete(comboDynArray.Count - 1); end; end; if found = false then result := 'No Valid Combination Found' else begin result := 'The cheapest combo for ' + goal.tostring + ' wings is: '; for I in combo do begin result := result + I.ToString + ' + '; cost := cost + ((fWingPrice[I]/goal) * I ); end; result := copy(result, 0, length(result) - 2) + '@ ' + format('%.3f', [cost]) + ' per wing'; end; end; end.
unit System_Settings; {$mode objfpc}{$H+} interface uses Classes, SysUtils, XMLConf, FileUtil, Forms; type { TSystemSettings } TSystemSettings = class(TDataModule) xmlStore: TXMLConfig; procedure DataModuleCreate(Sender: TObject); private function GetPreferencesFolder: string; public procedure saveFormState(var Form: TForm); procedure restoreFormState(var Form: TForm); function ReadString(const Section, Key, default: string): string; procedure WriteString(const Section, Key, Value: string); function ReadInteger(const Section, Key: string; default: integer): integer; procedure WriteInteger(const Section, Key: string; Value: integer); function ReadBoolean(const Section, Key: string; default: boolean): boolean; procedure WriteBoolean(const Section, Key: string; Value: boolean); end; var SystemSettings: TSystemSettings; implementation {$R *.lfm} uses strutils; // -------------------------------------------------------------------------------- procedure TSystemSettings.DataModuleCreate(Sender: TObject); begin xmlStore.Filename := GetPreferencesFolder + 'settings.xml'; end; // -------------------------------------------------------------------------------- function TSystemSettings.GetPreferencesFolder: string; {$ifdef LCLCarbon} const kMaxPath = 1024; var theError: OSErr; theRef: FSRef; pathBuffer: PChar; {$endif} begin {$ifdef LCLCarbon} try pathBuffer := Allocmem(kMaxPath); except on Exception do exit; end; try Fillchar(pathBuffer^, kMaxPath, #0); Fillchar(theRef, Sizeof(theRef), #0); theError := FSFindFolder(kOnAppropriateDisk, kPreferencesFolderType, kDontCreateFolder, theRef); if (pathBuffer <> nil) and (theError = noErr) then begin theError := FSRefMakePath(theRef, pathBuffer, kMaxPath); if theError = noErr then Result := UTF8ToAnsi(StrPas(pathBuffer)) + '/'; end; finally Freemem(pathBuffer); end; {$else} Result := GetAppConfigDir(False); if (not DirectoryExists(Result, False)) then begin MkDir(Result); end; {$endif} end; // -------------------------------------------------------------------------------- procedure TSystemSettings.saveFormState(var Form: TForm); var FormState: string; begin FormState := IntToHex(Form.Left, 6); FormState := FormState + IntToHex(Form.Top, 6); FormState := FormState + IntToHex(Form.Width, 6); FormState := FormState + IntToHex(Form.Height, 6); FormState := FormState + IntToHex(Form.RestoredLeft, 6); FormState := FormState + IntToHex(Form.RestoredTop, 6); FormState := FormState + IntToHex(Form.RestoredWidth, 6); FormState := FormState + IntToHex(Form.RestoredHeight, 6); FormState := FormState + IntToHex(integer(Form.WindowState), 6); xmlStore.OpenKey('Forms/' + Form.Name); xmlStore.SetValue('State', FormState); //xmlStore.Flush; xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- procedure TSystemSettings.restoreFormState(var Form: TForm); var LastWindowState: TWindowState; FormState: string; begin xmlStore.OpenKey('Forms/' + Form.Name); FormState := xmlStore.GetValue('State', '000000000000000000000000000000000000000000000000000000'); xmlStore.CloseKey; LastWindowState := TWindowState(Hex2Dec(FormState.Substring(48, 6))); if LastWindowState = wsMaximized then begin Form.WindowState := wsNormal; Form.BoundsRect := Bounds(Hex2Dec(FormState.Substring(24, 6)), Hex2Dec(FormState.Substring(30, 6)), Hex2Dec(FormState.Substring(36, 6)), Hex2Dec(FormState.Substring(42, 6))); Form.WindowState := wsMaximized; end else begin Form.WindowState := wsNormal; Form.BoundsRect := Bounds(Hex2Dec(FormState.Substring(0, 6)), Hex2Dec(FormState.Substring(6, 6)), Hex2Dec(FormState.Substring(12, 6)), Hex2Dec(FormState.Substring(18, 6))); end; end; // -------------------------------------------------------------------------------- function TSystemSettings.ReadString(const Section, Key, default: string): string; begin xmlStore.OpenKey(Section + '/' + Key); Result := xmlStore.GetValue('Value', default); xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- procedure TSystemSettings.WriteString(const Section, Key, Value: string); begin xmlStore.OpenKey(Section + '/' + Key); xmlStore.SetValue('Value', Value); //xmlStore.Flush; xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- function TSystemSettings.ReadInteger(const Section, Key: string; default: integer): integer; begin xmlStore.OpenKey(Section + '/' + Key); Result := xmlStore.GetValue('Value', default); xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- procedure TSystemSettings.WriteInteger(const Section, Key: string; Value: integer); begin xmlStore.OpenKey(Section + '/' + Key); xmlStore.SetValue('Value', Value); //xmlStore.Flush; xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- function TSystemSettings.ReadBoolean(const Section, Key: string; default: boolean): boolean; begin xmlStore.OpenKey(Section + '/' + Key); Result := xmlStore.GetValue('Value', default); xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- procedure TSystemSettings.WriteBoolean(const Section, Key: string; Value: boolean); begin xmlStore.OpenKey(Section + '/' + Key); xmlStore.SetValue('Value', Value); //xmlStore.Flush; xmlStore.CloseKey; end; // -------------------------------------------------------------------------------- end.
unit tabul_atd; interface uses crt; type tabula_coord = record {координаты доски} MinX, MinY, MaxX, MaxY : byte end; type Coords = record {координаты - используются для всего остального} LeftX, LeftY, RightX, RightY : byte end; type tabula_Colors = record {цвета} Ramka_color, Up_menu_color, Down_menu_color, Right_Column_color, Left_Column_color, Console_color, Delimeters_color: byte end; type ramka_type = record {тип линий рамки - любого окна} Left_up_corner, Right_up_corner, Left_down_corner, Right_down_corner, Down_Line, Forward_line : char; end; type Main_tabula = record {основной модуль} Tabula_pos : tabula_coord; {координаты доски} Up_menu_pos, {координаты верхнего меню} Down_Menu_pos, {координаты нижнего меню} Left_Column_pos, {координаты левого столбца} Right_Column_pos, {координаты правого столбца} Console_pos : Coords; {координаты консоли} ramka_lines : ramka_type; {тип линий рамки} Colors : tabula_colors {цвета} end; type main_lines_type = record {типы линий различных меню} Menu_Up_lines, Menu_Down_lines, Left_Column_lines, Right_Column_lines, Console_lines : ramka_type; Right_Delimiter_line, Left_Delimiter_line : char; end; type tabula = object public constructor init (_step : integer; r_color : integer); {инициализация} procedure draw_ramka; {рисуем рамку} procedure draw_Up_Menu; {рисуем верхнее меню} procedure Draw_Down_Menu; {рисуем нижнее меню} procedure Draw_Left_Column; {рисуем левый столбец} procedure Draw_Right_Column; {рисуем правый столбец} procedure Draw_Console; {рисуем командную строку} procedure Draw_Visual_Part; {рисует все} function Get_ramka_coordinates : Tabula_Coord; {получить координаты рамки} function Get_Up_menu_coordinates : Coords; {получить координаты верхнего меню} function Get_Down_menu_coordinates : Coords; {получить координаты нижнего меню} function Get_Left_Column_Coordinates : Coords; {получить координаты левого столбца} function Get_Right_Column_Coordinates : Coords; {получить координаты правого столбца} function Get_Console_Coordinates : Coords; {получить координаты командной строки} procedure Set_ramka_coordinates (coordinates : Tabula_Coord); {установить координаты рамки} procedure Set_Up_menu_coordinates (coordinates : Coords); {установить координаты верхнего меню} procedure Set_Down_menu_coordinates (coordinates : Coords); {установить координаты нижнего меню} procedure Set_Left_Column_Coordinates (coordinates : Coords); {установить координаты левого столбца} procedure Set_Right_Column_Coordinates (coordinates : Coords); {установить координаты консоли} procedure Set_Console_Coordinates (coordinates : Coords); {установить координаты консоли} procedure Get_Cursor_Position_Coordinates (Coordinates : Coords; var first, second : Coords);{получить координаты начала и конца столбца} function Get_Colors : Tabula_Colors; {получить цвета } procedure Set_Colors (enter_colors : Tabula_colors); {установить цвета} procedure Set_Ramka_color (enter_color : byte); {установить цвет рамки} procedure Set_Up_Menu_color (enter_color : byte); {установить цвет верхнего меню} procedure Set_Down_Menu_color (enter_color : byte); {установить цвет нижнего меню} procedure Set_Left_Column_color (enter_color : byte); {установить цвеи левой колонки} procedure Set_Right_Column_color (enter_color : byte); {установить цвет правой колонки} procedure Set_Delimeters_color (enter_color : byte); {установить цвет разделителей} private main : main_tabula; lines_type : main_lines_type; step, length_delimeters : byte; {шаг рисования меню} procedure GetMaxXY; {определить в зависимости от граф режима - макс положение} procedure Draw_Rectangle (Left_X, Left_Y, Right_X, Right_Y: byte; sym : ramka_type); {нарисовать окно с рамкой} procedure Draw_Down_Line (Left_X, Left_Y, {нарисовать} Right_Y : byte; sym : char); {линию вниз} procedure Draw_Delimiters (Left_X, Left_Y, {нарисовать } Right_X, Right_Y, length : byte; sym : char); {разделители} end; implementation procedure tabula.GetMaxXY; begin with main do begin with tabula_Pos do begin MaxX := 80; MaxY := 25; end end end; procedure tabula.Draw_Rectangle (Left_X, Left_Y, Right_X, Right_Y : byte; sym : ramka_type); var i : byte; begin GotoXY (Left_X, Left_Y); {рисуем} Write (Sym.Left_Up_Corner); {левый верхний угол} GotoXY (Right_X, Left_Y); {рисуем} Write (Sym.Right_Up_Corner); {правый верхний угол} GotoXY (Left_X, Right_Y); {рисуем} Write (Sym.Left_Down_Corner); {левый нижний угол} GotoXY (Right_X, Right_Y); {рисуем} Write (Sym.Right_Down_Corner); {правый нижний угол} GotoXY (Left_X + 1, Left_Y); {рисуем} for i := Left_X + 1 to Right_X - 1 do {верхнюю} Write (Sym.Forward_line); {линию} GotoXY (Left_X + 1, Right_Y); {рисуем} for i := Left_X + 1 to Right_X - 1 do {нижнюю} Write (Sym.Forward_Line); {линию} for i := Left_Y + 1 to Right_Y - 1 do begin {рисуем} GotoXY (Left_X, i); {левую} Write (Sym.Down_line) {линию} end; for i := Left_Y + 1 to Right_Y - 1 do begin {рисуем} GotoXY (Right_X, i); {правую} Write (Sym.Down_line) {линию} end end; procedure tabula.Draw_Down_Line (Left_X, Left_Y, Right_Y : byte; sym : char); var i : byte; begin for i := Left_Y to Right_Y do begin gotoxy (Left_X, i); Write (sym) end end; procedure tabula.draw_delimiters (Left_X, Left_Y, Right_X, Right_Y, length : byte; sym : char); begin textcolor (main.colors.delimeters_color); Self.Draw_Down_Line (Left_X + length, Left_Y + 1, Right_Y - 1, sym); Self.Draw_Down_Line (Left_X + 2 * length, Left_Y + 1, Right_Y - 1, #186) end; constructor tabula.init (_step : integer; r_color : integer); begin step := _step; with main do begin with tabula_Pos do begin {устанавливаем координаты доски} MinX := 1; MinY := 1; GetMaxXY end; with Ramka_lines do begin {устанавливаем символы рамки} Left_up_corner := #218; Right_up_corner := #191; Left_Down_corner := #192; Right_Down_corner := #217; Down_line := #179; Forward_line := #196 { Left_up_corner := #201; Right_up_corner := #187; Left_Down_corner := #200; Right_Down_corner := #188; Down_line := #186; Forward_line := #205 } end; begin {устанавливаем координаты верхнего меню} Up_menu_pos.LeftX := Tabula_Pos.MinX; Up_menu_pos.LeftY := Tabula_Pos.MinY; Up_menu_pos.RightX := Tabula_Pos.MaxX; Up_menu_pos.Righty := Tabula_Pos.MinY + step; end; begin {устанавливаем координаты нижнего меню} Down_menu_pos.LeftX := Tabula_Pos.MinX; Down_menu_pos.LeftY := Tabula_Pos.MaxY - step; Down_menu_pos.RightX := Tabula_Pos.MaxX; Down_menu_pos.RightY := Tabula_Pos.MaxY end; begin {устанавливаем координаты левой колонки} Left_Column_Pos.LeftX := Tabula_Pos.MinX + (step * 2); Left_Column_Pos.LeftY := Tabula_Pos.MinY + (step * 2); Left_Column_Pos.RightX := Tabula_Pos.MaXX div 2 - step; Left_Column_Pos.RightY := Tabula_Pos.MaxY - step * 3 end; begin {устанавливаем координаты правой колонки} Right_Column_Pos.LeftX := Tabula_Pos.MaXX div 2 + step ; Right_Column_Pos.LeftY := Tabula_Pos.MinY + (step * 2); Right_Column_Pos.RightX := Tabula_Pos.MaXX - (step * 2); Right_Column_Pos.RightY := Tabula_Pos.MaxY - step * 3 end; begin {устанавливаем координаты командной строки} Console_Pos.LeftX := Tabula_Pos.MinX + step; Console_Pos.LeftY := Tabula_Pos.MaxY - (step * 2); Console_Pos.RightX := Tabula_Pos.MaxX; Console_Pos.RightY := Tabula_Pos.MaxY - step end; with colors do begin ramka_color := r_color; {цвет рамки} Up_Menu_color := blue; {цвет верхнего меню} Down_Menu_color := blue; {цвет нижнего меню} Left_Column_color := green; Right_Column_color := green; Console_color := lightgray; Delimeters_color := 2 end end; length_delimeters := 13 {длина разделителей окна - 13} end; procedure tabula.draw_ramka; {нарисовать рамку} var i : byte; begin textcolor (main.colors.ramka_color); HighVideo; with main do Draw_Rectangle (Tabula_Pos.MinX, Tabula_Pos.MinX, Tabula_Pos.MaxX, Tabula_Pos.MaxY, ramka_lines) end; procedure tabula.Draw_Up_Menu; begin textcolor (main.colors.Up_Menu_color);{цвет символов} highvideo; {в режиме повышенной яркости} Lines_type.Menu_Up_lines := Main.Ramka_lines; {тип линий - такой же, как у рамки} Draw_Rectangle (Main.UP_Menu_pos.LeftX, Main.Up_Menu_pos.LeftY, Main.Up_Menu_pos.RightX, Main.Up_Menu_pos.RightY, Lines_type.Menu_Up_lines) {рисуем} end; procedure tabula.Draw_Down_Menu; begin textcolor (main.colors.Down_Menu_color);{цвет символов} highvideo; {в режиме повышенной яркости} Lines_type.Menu_Down_lines := Main.Ramka_lines;{тип линий - такой же, как у рамки} Draw_Rectangle (Main.Down_Menu_pos.LeftX, Main.Down_Menu_pos.LeftY, Main.Down_Menu_pos.RightX, Main.Down_Menu_pos.RightY, Lines_type.Menu_Down_lines) {рисуем} end; procedure Tabula.Draw_Left_Column; begin textcolor (main.colors.Left_Column_color); {цвет символов} highvideo; {в режиме повышенной яркости} with lines_type.Left_column_lines do begin {обозначения символов} Left_up_corner := #213; Right_up_corner := #184; Left_Down_corner := #212; Right_Down_corner := #190; Down_line := #179; Forward_line := #205 end; Lines_type.Left_Delimiter_line := #179; Draw_Rectangle (Main.Left_Column_pos.LeftX, Main.Left_COlumn_pos.LeftY, Main.Left_Column_pos.RightX, Main.Left_Column_pos.RightY, Lines_type.Left_Column_lines); {рисуем} Draw_delimiters (Main.Left_Column_pos.LeftX, Main.Left_COlumn_pos.LeftY, Main.Left_Column_pos.RightX, Main.Left_Column_pos.RightY, length_delimeters, Lines_type.Left_Delimiter_line) end; procedure Tabula.Draw_Right_Column; begin textcolor (main.colors.Right_Column_color); {цвет символов} highvideo; {в режиме повышенной яркости} with lines_type.Right_column_lines do begin {обозначения символов} Left_up_corner := #213; Right_up_corner := #184; Left_Down_corner := #212; Right_Down_corner := #190; Down_line := #179; Forward_line := #205 end; Lines_Type.Right_Delimiter_Line := #179; Draw_Rectangle (Main.Right_Column_pos.LeftX, Main.RIght_COlumn_pos.LeftY, Main.Right_Column_pos.RightX, Main.Right_Column_pos.RightY, Lines_type.Right_Column_lines); {рисуем} Draw_delimiters (Main.Right_Column_pos.LeftX, Main.Right_COlumn_pos.LeftY, Main.Right_Column_pos.RightX, Main.Right_Column_pos.RightY, length_delimeters, Lines_type.Right_Delimiter_line) end; procedure Tabula.Draw_Console; begin textcolor (main.colors.Console_color); {цвет символов} Lowvideo; {в режиме повышенной яркости} {обозначения символов} Lines_type.Console_lines := Main.Ramka_lines; textbackground (black); Window (Main.Console_pos.LeftX, Main.Console_pos.LeftY, Main.Console_pos.RightX, Main.Console_pos.RightY); gotoxy (Main.Console_pos.LeftX, Main.Console_pos.RightY); Write ('C:\') end; procedure Tabula.Draw_Visual_Part; begin clrscr; Draw_ramka; {рисуем рамку} Draw_Up_Menu; {рисуем верхнее меню} Draw_Down_Menu; {рисуем нижнее меню} Draw_Left_Column; {рисуем левый столбец} Draw_Right_Column; {рисуем правый столбец} Draw_Console {консоль} end; function Tabula.Get_ramka_coordinates : Tabula_coord; begin Get_Ramka_coordinates := main.tabula_pos end; function Tabula.Get_Up_menu_coordinates : Coords; begin Get_Up_Menu_coordinates := Main.Up_Menu_pos end; function Tabula.Get_Down_menu_coordinates : Coords; begin Get_Down_menu_coordinates := Main.Down_menu_pos end; function Tabula.Get_Left_Column_Coordinates : Coords; begin Get_Left_Column_coordinates := Main.Left_column_pos end; function Tabula.Get_Right_Column_Coordinates : Coords; begin Get_Right_Column_Coordinates := Main.Right_COlumn_Pos end; function Tabula.Get_Console_Coordinates : Coords; begin Get_Console_Coordinates := Main.Console_pos end; procedure Tabula.Set_ramka_coordinates (coordinates : Tabula_coord); begin Main.Tabula_Pos := Coordinates end; procedure Tabula.Set_Up_menu_coordinates (coordinates : Coords); begin Main.Up_Menu_pos := Coordinates end; procedure Tabula.Set_Down_menu_coordinates (coordinates : Coords); begin Main.Down_menu_pos := Coordinates end; procedure Tabula.Set_Left_Column_Coordinates (coordinates : Coords); begin Main.Left_column_pos := Coordinates end; procedure Tabula.Set_Right_Column_Coordinates (coordinates : Coords); begin Main.Right_column_pos := Coordinates end; procedure Tabula.Set_Console_Coordinates (coordinates : Coords); begin Main.Console_Pos := Coordinates end; procedure Tabula.Get_Cursor_Position_Coordinates (Coordinates : Coords; var first, second : Coords); begin {первый столбец} First.LeftX := Coordinates.LeftX + 1; First.LeftY := Coordinates.LeftY + 1; First.RightX := Coordinates.LeftX + 1; First.RightY := Coordinates. RightY - 1; {второй столбец} Second.LeftX := Coordinates.LeftX + length_delimeters + 1; Second.LeftY := Coordinates.LeftY + 1; Second.RightX := Coordinates.LeftX + length_delimeters + 1; Second.RightY := Coordinates. RightY - 1 end; function Tabula.Get_Colors : Tabula_Colors; begin Get_Colors := Main.Colors end; procedure Tabula.Set_Colors (enter_colors : Tabula_Colors); begin Main.Colors := enter_colors end; procedure Tabula.Set_Ramka_color (enter_color : byte); begin Main.Colors.Ramka_color := enter_color end; procedure Tabula.Set_Up_Menu_color (enter_color : byte); begin Main.Colors.Up_menu_color := enter_color end; procedure Tabula.Set_Down_Menu_color (enter_color : byte); begin Main.Colors.Down_menu_color := enter_color end; procedure Tabula.Set_Right_Column_color (enter_color : byte); begin Main.Colors.Right_Column_color := enter_color end; procedure Tabula.Set_Left_Column_color (enter_color : byte); begin Main.Colors.Left_Column_color := enter_color end; procedure Tabula.Set_Delimeters_color (enter_color : byte); begin Main.Colors.Right_Column_color := enter_color end; end.
unit UnitOpenGLSolidColorShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses SysUtils,Classes,{$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader; type TSolidColorShader=class(TShader) public uModelViewProjectionMatrix:glInt; uColor:glInt; constructor Create; destructor Destroy; override; procedure BindAttributes; override; procedure BindVariables; override; end; implementation constructor TSolidColorShader.Create; var f,v:ansistring; begin v:='#version 430'+#13#10+ 'layout(location = 0) in vec3 aPosition;'+#13#10+ 'uniform mat4 uModelViewProjectionMatrix;'+#13#10+ 'void main(){'+#13#10+ ' gl_Position = uModelViewProjectionMatrix * vec4(aPosition, 1.0);'+#13#10+ '}'+#13#10; f:='#version 430'+#13#10+ 'layout(location = 0) out vec4 oOutput;'+#13#10+ 'uniform vec4 uColor;'+#13#10+ 'void main(){'+#13#10+ ' oOutput = uColor;'+#13#10+ '}'+#13#10; inherited Create(v,f); end; destructor TSolidColorShader.Destroy; begin inherited Destroy; end; procedure TSolidColorShader.BindAttributes; begin inherited BindAttributes; glBindAttribLocation(ProgramHandle,0,'aPosition'); end; procedure TSolidColorShader.BindVariables; begin inherited BindVariables; uModelViewProjectionMatrix:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uModelViewProjectionMatrix'))); uColor:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uColor'))); end; end.
{Part 4 of regression test for SPECFUNX unit (c) 2010 W.Ehrhardt} unit t_sfx4; {$i STD.INC} {$ifdef BIT16} {$N+} {$ifndef Windows} {$O+} {$endif} {$endif} interface procedure test_erfx; procedure test_erfcx; procedure test_erfcex; procedure test_erfgx; procedure test_inerfcx; procedure test_erfix; procedure test_dawsonx; procedure test_dawson2x; procedure test_erfinvx; procedure test_erfcinvx; procedure test_erf_zx; procedure test_erf_px; procedure test_erf_qx; procedure test_fresnelx; procedure test_gsix; procedure test_expint3x; implementation uses amath, specfunx, t_sfx0; {---------------------------------------------------------------------------} procedure test_erfx; var y,f: extended; cnt, failed: integer; const NE = 6; begin cnt := 0; failed := 0; writeln('Function: ','erfx'); {-Inf .. -7 .. -1 .. 1 .. 7 .. Inf} y := erfx(NegInf_x); f := -1; testabs( 1, 0, y, f, cnt,failed); y := erfx(-100); f := -1; testrel( 2, NE, y, f, cnt,failed); y := erfx(-6.0); f := -0.99999999999999997848; testrel( 3, NE, y, f, cnt,failed); y := erfx(-2.0); f := -0.99532226501895273416; testrel( 4, NE, y, f, cnt,failed); y := erfx(-1.1); f := -0.88020506957408169977; testrel( 5, NE, y, f, cnt,failed); y := erfx(-1.0); f := -0.84270079294971486934; testrel( 6, NE, y, f, cnt,failed); y := erfx(-0.9); f := -0.79690821242283212852; testrel( 7, NE, y, f, cnt,failed); y := erfx(-0.5); f := -0.52049987781304653768; testrel( 8, NE, y, f, cnt,failed); y := erfx(-0.125); f := -0.14031620480133381739; testrel( 9, NE, y, f, cnt,failed); y := erfx(-0.0078125); f := -0.88152828951791887128e-2; testrel(10, NE, y, f, cnt,failed); y := erfx(0.0); f := 0; testrel(11, NE, y, f, cnt,failed); y := erfx(0.0078125); f := 0.88152828951791887128e-2; testrel(12, NE, y, f, cnt,failed); y := erfx(0.125); f := 0.14031620480133381739; testrel(13, NE, y, f, cnt,failed); y := erfx(0.5); f := 0.52049987781304653768; testrel(14, NE, y, f, cnt,failed); y := erfx(0.9); f := 0.79690821242283212852; testrel(15, NE, y, f, cnt,failed); y := erfx(1.0); f := 0.84270079294971486934; testrel(16, NE, y, f, cnt,failed); y := erfx(1.1); f := 0.88020506957408169977; testrel(17, NE, y, f, cnt,failed); y := erfx(2.0); f := 0.99532226501895273416; testrel(18, NE, y, f, cnt,failed); y := erfx(6.0); f := 0.99999999999999997848; testrel(19, NE, y, f, cnt,failed); y := erfx(100); f := 1; testrel(20, NE, y, f, cnt,failed); y := erfx(PosInf_x); f := 1; testabs(21, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erfcx; var y,f: extended; cnt, failed: integer; const NE = 8; begin cnt := 0; failed := 0; writeln('Function: ','erfcx'); {-Inf .. -7 .. -1 .. 1 .. 7 .. 107 .. Inf} y := erfcx(NegInf_x); f := 2; testabs( 1, 0, y, f, cnt,failed); y := erfcx(-100); f := 2; testrel( 2, NE, y, f, cnt,failed); y := erfcx(-6.0); f := 1.9999999999999999785; testrel( 3, NE, y, f, cnt,failed); y := erfcx(-2.0); f := 1.9953222650189527342; testrel( 4, NE, y, f, cnt,failed); y := erfcx(-1.1); f := 1.8802050695740816998; testrel( 5, NE, y, f, cnt,failed); y := erfcx(-1.0); f := 1.8427007929497148693; testrel( 6, NE, y, f, cnt,failed); y := erfcx(-0.9); f := 1.7969082124228321285; testrel( 7, NE, y, f, cnt,failed); y := erfcx(-0.5); f := 1.5204998778130465377; testrel( 8, NE, y, f, cnt,failed); y := erfcx(-0.125); f := 1.1403162048013338174; testrel( 9, NE, y, f, cnt,failed); y := erfcx(-0.0078125); f := 1.0088152828951791887; testrel(10, NE, y, f, cnt,failed); y := erfcx(0.0); f := 1; testrel(11, NE, y, f, cnt,failed); y := erfcx(0.0078125); f := 0.99118471710482081129; testrel(12, NE, y, f, cnt,failed); y := erfcx(0.125); f := 0.85968379519866618261; testrel(13, NE, y, f, cnt,failed); y := erfcx(0.5); f := 0.47950012218695346232; testrel(14, NE, y, f, cnt,failed); y := erfcx(0.9); f := 0.20309178757716787148; testrel(15, NE, y, f, cnt,failed); y := erfcx(1.0); f := 0.15729920705028513066; testrel(16, NE, y, f, cnt,failed); y := erfcx(1.1); f := 0.11979493042591830023; testrel(17, NE, y, f, cnt,failed); y := erfcx(2.0); f := 0.46777349810472658379e-2; testrel(18, NE, y, f, cnt,failed); y := erfcx(4.0); f := 0.15417257900280018852e-7; testrel(19, NE, y, f, cnt,failed); y := erfcx(6.0); f := 0.21519736712498913117e-16; testrel(20, NE, y, f, cnt,failed); y := erfcx(10.0); f := 0.20884875837625447570e-44; testrel(21, NE, y, f, cnt,failed); y := erfcx(50.0); f := 0.20709207788416560484e-1087; testrel(22, NE, y, f, cnt,failed); y := erfcx(100); f := 0.64059614249217320390e-4345; testrel(23, NE, y, f, cnt,failed); y := erfcx(PosInf_x); f := 0; testabs(24, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erfix; var x,y,f: extended; cnt, failed: integer; const NE = 5; begin cnt := 0; failed := 0; writeln('Function: ','erfix'); {erfi := x -> erf(I*x)/I;} x := 1e-20; y := erfix(x); f := 0.1128379167095512574e-19; testrel( 1, NE, y, f, cnt,failed); x := 1e-5; y := erfix(x); f := 0.1128379167133125213e-4; testrel( 2, NE, y, f, cnt,failed); x := -0.125; y := erfix(x); f := -0.14178547413026538933; testrel( 3, NE, y, f, cnt,failed); x := 0.5; y := erfix(x); f := 0.6149520946965109808; testrel( 4, NE, y, f, cnt,failed); x := 0.75; y := erfix(x); f := 1.035757284411962968; testrel( 5, NE, y, f, cnt,failed); x := -1; y := erfix(x); f := -1.650425758797542876; testrel( 6, NE, y, f, cnt,failed); x := 2; y := erfix(x); f := 18.56480241457555260; testrel( 7, NE, y, f, cnt,failed); x := 4; y := erfix(x); f := 1296959.730717639232; testrel( 8, NE, y, f, cnt,failed); x := -10; y := erfix(x); f := -0.1524307422708669699e43; testrel( 9, NE, y, f, cnt,failed); x := 26.5; y := erfix(x); f := 2.0501652832248793153e303; testrel(10, NE, y, f, cnt,failed); x := 99.762451171875; y := erfix(x); f := 0.1226243604626303240235e4321; testrel(11, NE, y, f, cnt,failed); x := 100; y := erfix(x); f := 4.9689635801475924641e4340; testrel(12, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erfcex; var x,y,f: extended; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','erfcex'); x := 1e-6; f := 0.999998871621832904; y := erfcex(x); testrel( 1, NE, y, f, cnt,failed); x := 0.125; f := 0.8732218450821508096; y := erfcex(x); testrel( 2, NE, y, f, cnt,failed); x := 1/3.0; f := 0.7122528886000577139; y := erfcex(x); testrel( 3, NE, y, f, cnt,failed); x := 1; f := 0.4275835761558070044; y := erfcex(x); testrel( 4, NE, y, f, cnt,failed); x := 2; f := 0.2553956763105057439; y := erfcex(x); testrel( 5, NE, y, f, cnt,failed); x := 10.0; f := 0.5614099274382258586e-1; y := erfcex(x); testrel( 6, NE, y, f, cnt,failed); x := 100.0; f := 0.5641613782989432904e-2; y := erfcex(x); testrel( 7, NE, y, f, cnt,failed); x := 130.0; f := 0.4339791484842787238e-2; y := erfcex(x); testrel( 8, NE, y, f, cnt,failed); x := 5000.0; f := 0.1128379144527930586e-3; y := erfcex(x); testrel( 9, NE, y, f, cnt,failed); x := 70000.0; f := 0.8059851192716941733e-5; y := erfcex(x); testrel(10, NE, y, f, cnt,failed); x := -1e-15; f := 1.000000000000001128; y := erfcex(x); testrel(11, NE, y, f, cnt,failed); x := -0.25; f := 1.358642370104722115; y := erfcex(x); testrel(12, NE, y, f, cnt,failed); x := -1; f := 5.008980080762283466; y := erfcex(x); testrel(13, NE, y, f, cnt,failed); x := -8/7; f := 6.992173861723201774; y := erfcex(x); testrel(14, NE, y, f, cnt,failed); x := -2; f := 108.9409043899779724; y := erfcex(x); testrel(15, NE, y, f, cnt,failed); x := -6.75; f := 0.1226231102139051807e21; y := erfcex(x); testrel(16, NE, y, f, cnt,failed); x := -26.5; f := 0.1924553162418568809e306; y := erfcex(x); testrel(17, NE, y, f, cnt,failed); x := -106.5637380121098418; f := PosInf_x; y := erfcex(x); testabs(18, 0, y, f, cnt,failed); x := -106.5625; f := 0.9138167535613739207e4932; y := erfcex(x); testrel(19, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erfgx; var x,y,f,p: extended; cnt,failed,i: integer; const NE = 4; NE2 = 2*NE; begin cnt := 0; failed := 0; writeln('Function: ','erfgx'); {Maple: gerf := (p,x) -> int(exp(-t^p), t=0..x);} { gerf := (p,x) -> (GAMMA(1/p)-GAMMA(1/p,x^p))/p;} {Pari: gerf(p,x) = intnum(t=0,x,exp(-t^p))} { gerf(p,x) = incgamc(1/p, x^p)/p} p := 0.5; y := erfgx(p,1/1024); f := 0.9564538925403311883e-3; testrel( 1, NE, y, f, cnt,failed); y := erfgx(p,0.125); f := 0.9910074638765149504e-1; testrel( 2, NE, y, f, cnt,failed); y := erfgx(p,0.5); f := 0.3165581866568181266; testrel( 3, NE, y, f, cnt,failed); y := erfgx(p,1); f := 0.5284822353142307136; testrel( 4, NE, y, f, cnt,failed); y := erfgx(p,2); f := 0.8261285649781240111; testrel( 5, NE, y, f, cnt,failed); y := erfgx(p,10); f := 1.647628069579945710; testrel( 6, NE, y, f, cnt,failed); y := erfgx(p,1000); f := 1.999999999998795093; testrel( 7, NE, y, f, cnt,failed); p := 5; y := erfgx(p,1/1024); f := 2*0.4882812499999999277e-3; testrel( 8, NE, y, f, cnt,failed); y := erfgx(p,0.125); f := 0.12499936422241396436; testrel( 9, NE, y, f, cnt,failed); y := erfgx(p,0.5); f := 0.4974178699312369020; testrel(10, NE, y, f, cnt,failed); y := erfgx(p,1); f := 0.8700746676858926573; testrel(11, NE, y, f, cnt,failed); y := erfgx(p,2); f := 0.9181687423997604561; testrel(12, NE, y, f, cnt,failed); y := erfgx(p,10); f := 0.9181687423997606106; testrel(13, NE, y, f, cnt,failed); p := 1.5; y := erfgx(p,1/1024); f := 2*0.4882752895923654593e-3; testrel(14, NE, y, f, cnt,failed); y := erfgx(p,0.125); f := 0.12282048474733161436; testrel(15, NE, y, f, cnt,failed); y := erfgx(p,0.5); f := 0.4364761380885268077; testrel(16, NE, y, f, cnt,failed); y := erfgx(p,1); f := 0.6997923277614944777; testrel(17, NE, y, f, cnt,failed); y := erfgx(p,2); f := 0.8772524660847196675; testrel(18, NE, y, f, cnt,failed); y := erfgx(p,10); f := 0.9027452929509297575; testrel(19, NE, y, f, cnt,failed); y := erfgx(p,1000); f := 0.9027452929509336113; testrel(20, NE, y, f, cnt,failed); {pari} p := 0.01; y := erfgx(p,1/1024); f := 0.0003877209165992133333; testrel(21, NE, y, f, cnt,failed); y := erfgx(p,0.125); f := 0.04740070277221238905; testrel(22, NE, y, f, cnt,failed); y := erfgx(p,0.5); f := 0.1870537286914434240; testrel(23, NE, y, f, cnt,failed); y := erfgx(p,1); f := 0.3715578714528098103; testrel(24, NE, y, f, cnt,failed); y := erfgx(p,2); f := 0.7380162212946553285; testrel(25, NE, y, f, cnt,failed); y := erfgx(p,10); f := 3.630877526710845930; testrel(26, NE, y, f, cnt,failed); y := erfgx(p,1000); f := 346.1598375906238578; testrel(27, NE, y, f, cnt,failed); y := erfgx(p,1e100); f := 5.038299480618184746e95; testrel(28, NE, y, f, cnt,failed); {selected values} y := erfgx(20,0); f := 0; testrel(29, NE, y, f, cnt,failed); y := erfgx(0,20); f := 7.357588823428846432; testrel(30, NE, y, f, cnt,failed); y := erfgx(1,20); f := 2*0.4999999989694231888; testrel(31, NE, y, f, cnt,failed); y := erfgx(0.25,10); f := 2.525854435942086756; testrel(32, NE, y, f, cnt,failed); y := erfgx(10,0.125); f := 0.1249999999894167889; testrel(33, NE, y, f, cnt,failed); y := erfgx(20,0.25); f := 0.2499999999999891727; testrel(34, NE, y, f, cnt,failed); y := erfgx(40,0.5); f := 0.4999999999999889086; testrel(35, NE, y, f, cnt,failed); y := erfgx(100,1-1/1024); f := 0.991745400651105407; testrel(36, NE, y, f, cnt,failed); y := erfgx(10000,1-1/1024); f := 2*0.4995117158972298877; testrel(37, NE, y, f, cnt,failed); {expint3 tests} for i:=0 to 63 do begin x := i/16; y := erfgx(3,x); f := expint3x(x); testrel(100+i, NE2, y, f, cnt,failed); end; if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_inerfcx; var y,f: extended; cnt, failed: integer; const NE = 8; NE2 = 16; NE3 = 24; begin cnt := 0; failed := 0; writeln('Function: ','inerfcx'); y := inerfcx(3,1e-40); f := 0.9403159725795938116e-1; testrel(1, NE, y, f, cnt,failed); y := inerfcx(250,1e-40); f := 0.2935791617973459071e-284; testrel(2, NE, y, f, cnt,failed); y := inerfcx(3,0.5); f := 0.2775132137764753636e-1; testrel(3, NE, y, f, cnt,failed); y := inerfcx(10,20); f := 0.2480339545677166807e-17; testrel(4, NE, y, f, cnt,failed); y := inerfcx(10,2); f := 0.4519702487098470796e-8; testrel(5, NE, y, f, cnt,failed); y := inerfcx(10,1); f := 0.1305302483913995620e-6; testrel(6, NE, y, f, cnt,failed); y := inerfcx(10,0.5); f := 0.9245065129805797129e-6; testrel(7, NE, y, f, cnt,failed); y := inerfcx(10,0.25); f := 0.26649953573332452744e-5; testrel(8, NE, y, f, cnt,failed); y := inerfcx(10,0.125); f := 0.4622606908901843597e-5; testrel(9, NE, y, f, cnt,failed); y := inerfcx(10,1/1024); f := 0.8101666489669277473e-5; testrel(10, NE, y, f, cnt,failed); y := inerfcx(100,8); f := 0.3327723273692355744e-132; testrel(11, NE, y, f, cnt,failed); y := inerfcx(100,2); f := 0.8417913154612625873e-106; testrel(12, NE, y, f, cnt,failed); y := inerfcx(100,0.5); f := 0.2448087104431131554e-97; testrel(13, NE, y, f, cnt,failed); y := inerfcx(100,0.25); f := 0.7728184538695565628e-96; testrel(14, NE, y, f, cnt,failed); y := inerfcx(100,1/1024); f := 0.2558072521643705004e-94; testrel(15, NE, y, f, cnt,failed); y := inerfcx(100,1e-10); f := 0.2593734749448854344e-94; testrel(16, NE, y, f, cnt,failed); y := inerfcx(5,0.125); f := 0.6252579526727030871e-2; testrel(17, NE, y, f, cnt,failed); y := inerfcx(20,0.125); f := 0.1189350337542980588e-12; testrel(18, NE, y, f, cnt,failed); y := inerfcx(100,0.125); f := 0.4442699570076624848e-95; testrel(19, NE, y, f, cnt,failed); y := inerfcx(250,0.125); f := 0.1803034248451498754e-285; testrel(20, NE, y, f, cnt,failed); y := inerfcx(5,0.75); f := 0.9967894387400569614e-3; testrel(21, NE, y, f, cnt,failed); y := inerfcx(20,0.75); f := 0.2815855137500476563e-14; testrel(22, NE, y, f, cnt,failed); y := inerfcx(50,0.75); f := 0.4007073297196590972e-43; testrel(23, NE, y, f, cnt,failed); y := inerfcx(125,0.75); f := 0.8592345382450687318e-129; testrel(24, NE, y, f, cnt,failed); y := inerfcx(250,0.75); f := 0.1984987852267995133e-291; testrel(25, NE, y, f, cnt,failed); y := inerfcx(5,50); {AE} f := 0.1123656973372330445e-11; testrel(26, NE, y, f, cnt,failed); y := inerfcx(20,50); {AE} f := 0.1077656273122095687e-41; testrel(27, NE, y, f, cnt,failed); y := inerfcx(100,50); {AE} f := 0.4110694394268175203e-202; testrel(28, NE, y, f, cnt,failed); y := inerfcx(150,50); {CF} f := 0.1215088638985536402e-302; testrel(29, NE, y, f, cnt,failed); y := inerfcx(10,1000); f := 0.5509482087061094431e-36; testrel(30, NE, y, f, cnt,failed); y := inerfcx(90,1000); f := 0.4547958756280478593e-300; testrel(31, NE, y, f, cnt,failed); {x<0} y := inerfcx(-1,-2); f := 0.2066698535409205386e-1; testrel(32, NE, y, f, cnt,failed); y := inerfcx(0,-2); f := 1.9953222650189527342; testrel(33, NE, y, f, cnt,failed); y := inerfcx(1,-2); f := 4.000978022714951495; testrel(34, NE, y, f, cnt,failed); y := inerfcx(5,-0.5); f := 0.4374437542410532658e-1; testrel(35, NE, y, f, cnt,failed); y := inerfcx(5,-2); f := 1.325001048378169994; testrel(36, NE, y, f, cnt,failed); y := inerfcx(5,-10); f := 1750.625; testrel(37, NE, y, f, cnt,failed); y := inerfcx(5,-300); f := 40502250018.75; testrel(38, NE, y, f, cnt,failed); y := inerfcx(20,-0.5); f := 0.5711213876890956573e-11; testrel(39, NE, y, f, cnt,failed); y := inerfcx(20,-2); f := 0.1557830391267366734e-7; testrel(40, NE, y, f, cnt,failed); y := inerfcx(20,-10); f := 196.8746175638803787; testrel(41, NE, y, f, cnt,failed); y := inerfcx(20,-300); f := 0.2869385160990788617e32; testrel(42, NE, y, f, cnt,failed); y := inerfcx(1000,-500); f := 0.1257148984018811968e133; testrel(43, NE, y, f, cnt,failed); y := inerfcx(100,-1000); f := 0.2148330859419028936e143; testrel(44, NE, y, f, cnt,failed); y := inerfcx(5000,-2000); f := 0.3183024088162901648e181; testrel(45, NE3, y, f, cnt,failed); y := inerfcx(2000,-1000); f := 0.1636906036218412122e266; testrel(46, NE3, y, f, cnt,failed); y := inerfcx(30000,-11000); f := 0.2806686227497745515e-44; testrel(47, NE3, y, f, cnt,failed); {--------- extended only ---------} y := inerfcx(500,8); f := 0.6053717215571535792e-740; testrel(48, NE, y, f, cnt,failed); y := inerfcx(1000,8); f := 0.3437870361645832591e-1577; testrel(49, NE, y, f, cnt,failed); y := inerfcx(2000,8); f := 0.7612760696923994492e-3376; testrel(50, NE2, y, f, cnt,failed); y := inerfcx(2800,8); f := 0.9088747209936031381e-4888; testrel(51, NE, y, f, cnt,failed); y := inerfcx(2000,2); f := 0.1792400092894991409e-3223; testrel(52, NE, y, f, cnt,failed); y := inerfcx(2000,0.5); f := 0.4510111198053716206e-3183; testrel(53, NE, y, f, cnt,failed); y := inerfcx(2000,0.125); f := 0.8033895338468148036e-3173; testrel(54, NE, y, f, cnt,failed); y := inerfcx(2000,0); f := 0.2164534188917535707e-3169; testrel(55, NE, y, f, cnt,failed); y := inerfcx(1400,400); {CF} f := 0.3135483200306032641e-4068; testrel(56, NE, y, f, cnt,failed); y := inerfcx(1200,400); {AF} f := 0.2920331348555060292e-3487; testrel(57, NE2, y, f, cnt,failed); {x<0} y := inerfcx(1000,-10); f := 0.1098327100833423869e-1260; testrel(58, NE2, y, f, cnt,failed); y := inerfcx(1000,-20); f := 0.1345511944678638231e-1120; testrel(59, NE2, y, f, cnt,failed); y := inerfcx(1000,-50); f := 0.2790843160428145087e-831; testrel(60, NE, y, f, cnt,failed); y := inerfcx(100,-1e20); f := 0.2143020576250933846e1843; testrel(61, NE, y, f, cnt,failed); y := inerfcx(500,-1e10); f := 0.1639160426434480284e3867; testrel(62, NE2, y, f, cnt,failed); y := inerfcx(10000,-1200); f := 0.1486872156150231891e-4859; testrel(63, NE2, y, f, cnt,failed); y := inerfcx(10000,-2600); f := 0.1531112204308584074e-1507; testrel(64, NE2, y, f, cnt,failed); y := inerfcx(10000,-4000); f := 0.1333441997807055193e363; testrel(65, NE3, y, f, cnt,failed); y := inerfcx(10000,-6000); f := 0.4579105761886398102e2123; testrel(66, NE2, y, f, cnt,failed); y := inerfcx(10000,-10000); f := 0.9022207499862962510e4341; testrel(67, NE2, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_dawsonx; var x,y,f: extended; cnt, failed: integer; const NE = 7; begin cnt := 0; failed := 0; writeln('Function: ','dawsonx'); x := 0; y := dawsonx(x); f := 0; testrel( 1, NE, y, f, cnt,failed); x := succx(0); {x=0.5^16445} y := dawsonx(x); {$ifdef HAS_DENORM_LIT} f := 0.36451995318824746025e-4950; {$else} f := 0.36451995318824746025e-950; f := f*1e-4000; {$endif} testrel( 2, NE, y, f, cnt,failed); x := 1e-100; y := dawsonx(x); f := 1e-100; testrel( 3, NE, y, f, cnt,failed); x := 1e-6; y := dawsonx(x); f := 0.99999999999933333333e-6; testrel( 4, NE, y, f, cnt,failed); x := 0.0009765625; y := dawsonx(x); f := 0.97656187911852043720e-3; testrel( 5, NE, y, f, cnt,failed); x := 0.125; y := dawsonx(x); f := 0.12370601848283973394; testrel( 6, NE, y, f, cnt,failed); x := 0.5; y := dawsonx(x); f := 0.42443638350202229593; testrel( 7, NE, y, f, cnt,failed); x := 0.92413887300459176701; y := dawsonx(x); f := 0.54104422463518169847; testrel( 8, NE, y, f, cnt,failed); x := 0.9990234375; y := dawsonx(x); f := 0.53815344009396028924; testrel( 9, NE, y, f, cnt,failed); x := 1.0; y := dawsonx(x); f := 0.53807950691276841914; testrel(10, NE, y, f, cnt,failed); x := 1.0009765625; y := dawsonx(x); f := 0.53800469268824945169; testrel(11, NE, y, f, cnt,failed); x := 3.9990234375; y := dawsonx(x); f := 0.12938197933297510231; testrel(12, NE, y, f, cnt,failed); x := 4.0; y := dawsonx(x); f := 0.12934800123600511559; testrel(13, NE, y, f, cnt,failed); x := 4.0009765625; y := dawsonx(x); f := 0.12931404180823832109; testrel(14, NE, y, f, cnt,failed); x := 3.0e9; y := dawsonx(x); f := 0.16666666666666666667e-9; testrel(15, NE, y, f, cnt,failed); x := 4.0e9; y := dawsonx(x); f := 0.12500000000000000000e-9; testrel(16, NE, y, f, cnt,failed); x := 1.0e307; y := dawsonx(x); f := 5e-308; testrel(17, NE, y, f, cnt,failed); x := 1.4871643691965395E+4931; y := dawsonx(x); f := 0.33621031431120939728e-4931; testrel(18, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_dawson2x; var p,x,y,f: extended; cnt, failed: integer; const NE = 5; NE2 = 8; begin cnt := 0; failed := 0; writeln('Function: ','dawson2x'); {Pari: gd(p,x)=intnum(t=0,x,exp(t^p))*exp(-x^p)} {Standard Dawson} p := 2; y := dawson2x(p,1); f := 0.5380795069127684191; testrel(1, NE, y, f, cnt,failed); y := dawson2x(p,3); f := 0.1782710306105582873; testrel(2, NE, y, f, cnt,failed); y := dawson2x(p,5); f := 0.1021340744242768355; testrel(3, NE, y, f, cnt,failed); y := dawson2x(p,100); f := 0.5000250037509378283e-2; testrel(4, NE, y, f, cnt,failed); y := dawson2x(p,1e300); f := 0.5e-300; testrel(5, NE, y, f, cnt,failed); y := dawson2x(p,1/16); f := 0.6233749361289893996e-1; testrel(6, NE, y, f, cnt,failed); y := dawson2x(p,1e-5); f := 0.9999999999333333333e-5; testrel(7, NE, y, f, cnt,failed); y := dawson2x(p,1e-10); f := 1e-10; testrel(8, NE, y, f, cnt,failed); y := dawson2x(p,1e-15); f := 1e-15; testrel(9, NE, y, f, cnt,failed); {Special case x=1} x := 1; y := dawson2x(1+1/1024,x); f := 0.6319767998075155365; testrel(10, NE, y, f, cnt,failed); y := dawson2x(10,x); f := 0.4125034088017899048; testrel(11, NE, y, f, cnt,failed); y := dawson2x(100,x); f := 0.3726859445420274430; testrel(12, NE, y, f, cnt,failed); y := dawson2x(1000,x); f := 0.3683638488980294743; testrel(13, NE, y, f, cnt,failed); y := dawson2x(1e10,x); f := 0.3678794412199252323; testrel(14, NE, y, f, cnt,failed); y := dawson2x(1e300,x); f := 0.3678794411714423216; testrel(15, NE, y, f, cnt,failed); y := dawson2x(1/1024,x); f := 0.9990253402056163500; testrel(16, NE, y, f, cnt,failed); y := dawson2x(1e-9,x); f := 0.999999999000000002; testrel(17, NE, y, f, cnt,failed); y := dawson2x(1e-10,x); f := 0.9999999999; testrel(18, NE, y, f, cnt,failed); y := dawson2x(1e-11,x); f := 0.99999999999; testrel(19, NE, y, f, cnt,failed); y := dawson2x(1e-16,x); f := 0.9999999999999999; testrel(20, NE, y, f, cnt,failed); {Other cases} y := dawson2x(1/80,80); f := 78.97000764508719285; testrel(21, NE, y, f, cnt,failed); y := dawson2x(1.5,100); f := 0.6668891858788577765e-1; testrel(22, NE, y, f, cnt,failed); y := dawson2x(1,4); f := 0.981684361111265820; testrel(23, NE, y, f, cnt,failed); y := dawson2x(1,1e-10); f := 0.99999999995e-10; testrel(24, NE, y, f, cnt,failed); y := dawson2x(1/2,100); f := 18.00009079985952497; testrel(25, NE, y, f, cnt,failed); y := dawson2x(1/2,1e10); f := 199998.0; testrel(26, NE, y, f, cnt,failed); y := dawson2x(0.1,10); f := 8.964926863611165808; testrel(27, NE, y, f, cnt,failed); y := dawson2x(0.01,100); f := 98.9737752892581009; testrel(28, NE, y, f, cnt,failed); y := dawson2x(0.01,1e10); f := 9876873773.46623806; testrel(29, NE, y, f, cnt,failed); y := dawson2x(0.01,1e100); f := 9.09837270131716558e99; testrel(30, NE, y, f, cnt,failed); y := dawson2x(1/1024,1/2); f := 0.49951299954466997501; testrel(31, NE, y, f, cnt,failed); y := dawson2x(1e-5,1e20); f := 9.99989995593902475e19; testrel(32, NE, y, f, cnt,failed); y := dawson2x(1e-10,1e10); f := 9999999999.0; testrel(33, NE, y, f, cnt,failed); y := dawson2x(25,2); f := 0.2384185859227731617e-8; testrel(34, NE, y, f, cnt,failed); y := dawson2x(5,50); f := 0.3200000008192000047e-7; testrel(35, NE, y, f, cnt,failed); y := dawson2x(4,100); f := 0.2500000018750000328e-6; testrel(36, NE, y, f, cnt,failed); y := dawson2x(40,1.25); f := 0.4154375964424212495e-5; testrel(37, NE, y, f, cnt,failed); y := dawson2x(40,1.5); f := 0.3391415055475334289e-8; testrel(38, NE, y, f, cnt,failed); y := dawson2x(300,1+1/16); f := 4.4722500002707202404e-11; testrel(39, NE, y, f, cnt,failed); y := dawson2x(300,1-1/16); f := 0.937499996353225120; testrel(40, NE, y, f, cnt,failed); y := dawson2x(500,3); f := 0.1650151773721882811e-240; testrel(41, NE, y, f, cnt,failed); y := dawson2x(200,10); f := 5.0e-202; testrel(42, NE, y, f, cnt,failed); y := dawson2x(200,8); f := 0.9639679460411536471e-182; testrel(43, NE, y, f, cnt,failed); y := dawson2x(1000,1-1/16); f := 0.9375; testrel(44, NE, y, f, cnt,failed); y := dawson2x(1000,1+1/16); f := 0.4981845059124721260e-29; testrel(45, NE, y, f, cnt,failed); y := dawson2x(10000,1+1/16); f := 0.545684622222586877e-267; testrel(46, NE2, y, f, cnt,failed); y := dawson2x(1000,2); f := 1.866527237006437758e-304; testrel(47, NE2, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erfinvx; var x,y,f: extended; cnt, failed: integer; const NE = 8; begin cnt := 0; failed := 0; writeln('Function: ','erf_invx'); x := 0; y := erf_invx(x); f := 0; testrel( 1, NE, y, f, cnt,failed); x := 1e-4900; y := erf_invx(x); {$ifdef HAS_DENORM_LIT} f := 0.886226925452758013649e-4900; {$else} f := 0.886226925452758013649e-900; f := f*1e-4000; {$endif} testrel( 2, NE, y, f, cnt,failed); x := 1e-800; y := erf_invx(x); f := 0.886226925452758013649e-800; testrel( 3, NE, y, f, cnt,failed); x := -1e-100; y := erf_invx(x); f := -0.886226925452758013649e-100; testrel( 4, NE, y, f, cnt,failed); x := 1e-6; y := erf_invx(x); f := 0.8862269254529900273156e-6; testrel( 5, NE, y, f, cnt,failed); x := 0.0009765625; y := erf_invx(x); f := 0.86545619796713755345e-3; testrel( 6, NE, y, f, cnt,failed); x := -0.125; y := erf_invx(x); f := -0.1112354518409499591471840; testrel( 7, NE, y, f, cnt,failed); x := 0.5; y := erf_invx(x); f := 0.47693627620446987338; testrel( 8, NE, y, f, cnt,failed); x := -0.75; y := erf_invx(x); f := -0.8134198475976185417; testrel( 9, NE, y, f, cnt,failed); x := 0.9375; y := erf_invx(x); f := 1.31715033498613074888; testrel(10, NE, y, f, cnt,failed); x := -0.9990234375; y := erf_invx(x); f := -2.3314677736219476723; testrel(11, NE, y, f, cnt,failed); x := 1.0-ldexp(1,-20); y := erf_invx(x); f := 3.465505025803330717256; testrel(12, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erf_zx; var y,f: extended; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','erf_zx'); {Maple: statevalf[pdf,normald](x)} y := erf_zx(NegInf_x); f := 0; testabs( 1, 0, y, f, cnt,failed); y := erf_zx(-100); f := 0.13443134677817230434e-2171; testrel( 2, NE, y, f, cnt,failed); y := erf_zx(-6.0); f := 0.60758828498232854869e-8; testrel( 3, NE, y, f, cnt,failed); y := erf_zx(-2.0); f := 0.53990966513188051949e-1; testrel( 4, NE, y, f, cnt,failed); y := erf_zx(-1.1); f := 0.21785217703255053138; testrel( 5, NE, y, f, cnt,failed); y := erf_zx(-1.0); f := 0.24197072451914334980; testrel( 6, NE, y, f, cnt,failed); y := erf_zx(-0.9); f := 0.26608524989875482182; testrel( 7, NE, y, f, cnt,failed); y := erf_zx(-0.5); f := 0.35206532676429947777; testrel( 8, NE, y, f, cnt,failed); y := erf_zx(-0.125); f := 0.39583768694474948414; testrel( 9, NE, y, f, cnt,failed); y := erf_zx(-0.0078125); f := 0.39893010583499324766; testrel(10, NE, y, f, cnt,failed); y := erf_zx(0.0); f := 0.39894228040143267794; testrel(11, NE, y, f, cnt,failed); y := erf_zx(0.0078125); f := 0.39893010583499324766; testrel(12, NE, y, f, cnt,failed); y := erf_zx(0.125); f := 0.39583768694474948414; testrel(13, NE, y, f, cnt,failed); y := erf_zx(0.5); f := 0.35206532676429947777; testrel(14, NE, y, f, cnt,failed); y := erf_zx(0.9); f := 0.26608524989875482182; testrel(15, NE, y, f, cnt,failed); y := erf_zx(1.0); f := 0.24197072451914334980; testrel(16, NE, y, f, cnt,failed); y := erf_zx(1.1); f := 0.21785217703255053138; testrel(17, NE, y, f, cnt,failed); y := erf_zx(2.0); f := 0.53990966513188051949e-1; testrel(18, NE, y, f, cnt,failed); y := erf_zx(4.0); f := 0.5*0.26766045152977070355e-3; {0.133830225764885351774074488441e-3} testrel(19, NE, y, f, cnt,failed); y := erf_zx(6.0); f := 0.60758828498232854869e-8; testrel(20, NE, y, f, cnt,failed); y := erf_zx(10.0); f := 0.76945986267064193463e-22; testrel(21, NE, y, f, cnt,failed); y := erf_zx(50.0); f := 0.54051492041927084473e-543; testrel(22, NE, y, f, cnt,failed); y := erf_zx(100); f := 0.13443134677817230434e-2171; testrel(23, NE, y, f, cnt,failed); y := erf_zx(150); f := 0.61374597109796063650e-4886; testrel(24, NE, y, f, cnt,failed); y := erf_zx(PosInf_x); f := 0; testabs(25, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erf_px; var y,f: extended; cnt, failed: integer; const NE = 10; NE1 = 25; NE2 = 80; NE3 = 260; begin cnt := 0; failed := 0; writeln('Function: ','erf_px'); {Maple: statevalf[cdf,normald](x)} y := erf_px(NegInf_x); f := 0; testabs( 1, 0, y, f, cnt,failed); y := erf_px(-35); f := 0.1124910706472406243978835e-267; testrel( 2, NE, y, f, cnt,failed); y := erf_px(-30); f := 0.4906713927148187059531905e-197; testrel( 3, NE, y, f, cnt,failed); y := erf_px(-20); f := 0.27536241186062336951e-88; testrel( 4, NE, y, f, cnt,failed); y := erf_px(-10); f := 0.76198530241605260660e-23; testrel( 5, NE, y, f, cnt,failed); y := erf_px(-6.0); f := 0.98658764503769814070e-9; testrel( 6, NE, y, f, cnt,failed); y := erf_px(-2.0); f := 0.227501319481792072003e-1; testrel( 7, NE, y, f, cnt,failed); y := erf_px(-1.1); f := 0.13566606094638267518; testrel( 8, NE, y, f, cnt,failed); y := erf_px(-1.0); f := 0.15865525393145705142; testrel( 9, NE, y, f, cnt,failed); y := erf_px(-0.9); f := 0.18406012534675948856; testrel(10, NE, y, f, cnt,failed); y := erf_px(-0.5); f := 0.30853753872598689637; testrel(11, NE, y, f, cnt,failed); y := erf_px(-0.125); f := 0.45026177516988710702; testrel(12, NE, y, f, cnt,failed); y := erf_px(-0.0078125); f := 0.49688329513915741955; testrel(13, NE, y, f, cnt,failed); y := erf_px(0.0); f := 0.5; testrel(14, NE, y, f, cnt,failed); y := erf_px(0.0078125); f := 0.50311670486084258045; testrel(15, NE, y, f, cnt,failed); y := erf_px(0.125); f := 0.54973822483011289298; testrel(16, NE, y, f, cnt,failed); y := erf_px(0.5); f := 0.69146246127401310364; testrel(17, NE, y, f, cnt,failed); y := erf_px(0.9); f := 0.81593987465324051145; testrel(18, NE, y, f, cnt,failed); y := erf_px(1.0); f := 0.84134474606854294859; testrel(19, NE, y, f, cnt,failed); y := erf_px(1.1); f := 0.86433393905361732483; testrel(20, NE, y, f, cnt,failed); y := erf_px(2.0); f := 0.97724986805182079280; testrel(21, NE, y, f, cnt,failed); y := erf_px(4.0); f := 0.99996832875816688008; testrel(22, NE, y, f, cnt,failed); y := erf_px(6.0); f := 0.99999999901341235496; testrel(23, NE, y, f, cnt,failed); y := erf_px(10.0); f := 1; testrel(24, NE, y, f, cnt,failed); y := erf_px(PosInf_x); f := 1; testabs(25, NE, y, f, cnt,failed); {precision for -150 < x < -40 is increased but still suboptimal} y := erf_px(-150); f := 0.40914579809030025090e-4888; testrel(26, NE3, y, f, cnt,failed); y := erf_px(-107); f := 0.2836133751848002929e-2488; testrel(27, NE1, y, f, cnt,failed); y := erf_px(-80); f := 0.90242300162047361580e-1392; testrel(28, NE2, y, f, cnt,failed); y := erf_px(-40); f := 0.36558935409150297108e-349; testrel(29, NE1, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erf_qx; var y,f: extended; cnt, failed: integer; const NE = 2; begin cnt := 0; failed := 0; writeln('Function: ','erf_qx'); {Maple: statevalf[cdf,normald](-x)} y := erf_qx(0); f := 0.5; testrel(1, NE, y, f, cnt,failed); y := erf_qx(0.5); f := 0.3085375387259868964; testrel(2, NE, y, f, cnt,failed); y := erf_qx(1); f := 0.1586552539314570514; testrel(3, NE, y, f, cnt,failed); y := erf_qx(2); f := 0.2275013194817920720e-1; testrel(4, NE, y, f, cnt,failed); y := erf_qx(5); f := 0.2866515718791939117e-6; testrel(5, NE, y, f, cnt,failed); y := erf_qx(10); f := 0.7619853024160526066e-23; testrel(6, NE, y, f, cnt,failed); y := erf_qx(20); f := 0.27536241186062336951e-88; testrel(7, NE, y, f, cnt,failed); y := erf_qx(35); f := 0.1124910706472406244e-267; testrel(8, NE, y, f, cnt,failed); y := erf_qx(-0.25); f := 0.5987063256829237242; testrel(9, NE, y, f, cnt,failed); y := erf_qx(-1.5); f := 0.9331927987311419340; testrel(10, NE, y, f, cnt,failed); y := erf_qx(-4); f := 0.9999683287581668801; testrel(11, NE, y, f, cnt,failed); y := erf_qx(-8); f := 2*0.4999999999999996890; {0.999999999999999377903942572822;} testrel(12, NE, y, f, cnt,failed); y := erf_qx(-10); f := 1.0; testrel(13, NE, y, f, cnt,failed); y := erf_qx(100); f := 0.1344179076744198305e-2173; {$ifdef FPC} testrel(14, NE+1, y, f, cnt,failed); {FPC271 only} {$else} testrel(14, NE, y, f, cnt,failed); {$endif} if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_erfcinvx; var x,y,f: extended; cnt, failed: integer; const NE = 8; begin cnt := 0; failed := 0; writeln('Function: ','erfc_invx'); x := ldexp(1,-16000); y := erfc_invx(x); f := 105.2859240315651474724078; testrel( 1, NE, y, f, cnt,failed); x := 1e-4200; y := erfc_invx(x); f := 98.31427569110739080218294;; testrel( 2, NE, y, f, cnt,failed); x := 1e-2000; y := erfc_invx(x); f := 67.82610681154402285494; testrel( 3, NE, y, f, cnt,failed); x := 1e-800; y := erfc_invx(x); f := 42.86883824391192220198; testrel( 4, NE, y, f, cnt,failed); x := 1e-100; y := erfc_invx(x); f := 15.06557470259264570440; testrel( 5, NE, y, f, cnt,failed); x := 1e-10; y := erfc_invx(x); f := 4.572824967389485278741; testrel( 6, NE, y, f, cnt,failed); x := 0.0009765625; y := erfc_invx(x); f := 2.33146777362194767232; testrel( 7, NE, y, f, cnt,failed); x := 0.125; y := erfc_invx(x); f := 1.08478704006928314131; testrel( 8, NE, y, f, cnt,failed); x := 0.2; y := erfc_invx(x); f := 0.90619380243682322007; testrel( 9, NE, y, f, cnt,failed); x := 0.5; y := erfc_invx(x); f := 0.47693627620446987338; testrel(10, NE, y, f, cnt,failed); x := 0.75; y := erfc_invx(x); f := 0.225312055012178104725; testrel(11, NE, y, f, cnt,failed); x := 0.9375; y := erfc_invx(x); f := 0.55445948772782020299e-1; testrel(12, NE, y, f, cnt,failed); x := 0.9990234375; y := erfc_invx(x); f := 0.86545619796713755345e-3; testrel(13, NE, y, f, cnt,failed); x := 1.0009765625; y := erfc_invx(x); f := -0.86545619796713755345e-3; testrel(14, NE, y, f, cnt,failed); x := 1.125; y := erfc_invx(x); f := -0.111235451840949959147; testrel(15, NE, y, f, cnt,failed); x := 1.25; y := erfc_invx(x); f := -0.225312055012178104725; testrel(16, NE, y, f, cnt,failed); x := 1.5; y := erfc_invx(x); f := -0.47693627620446987338; testrel(17, NE, y, f, cnt,failed); x := 1.75; y := erfc_invx(x); f := -0.81341984759761854169; testrel(18, NE, y, f, cnt,failed); x := 1.875; y := erfc_invx(x); f := -1.08478704006928314131; testrel(19, NE, y, f, cnt,failed); x := 1.9375; y := erfc_invx(x); f := -1.31715033498613074888; testrel(20, NE, y, f, cnt,failed); x := 1.9990234375; y := erfc_invx(x); f := -2.3314677736219476723; testrel(21, NE, y, f, cnt,failed); x := 2.0-ldexp(1,-20); y := erfc_invx(x); f := -3.4655050258033307173; testrel(22, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_fresnelx; var x,yc,ys,fs,fc: extended; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','Fresnel(CS)x'); x := 0; fs := 0; fc := 0; Fresnelx(x,ys,yc); testrel( 1, NE, ys, fs, cnt,failed); testrel( 2, NE, yc, fc, cnt,failed); x := 1e-300; fs := 0.5235987755982988730e-900; fc := 1e-300;; Fresnelx(x,ys,yc); testrel( 3, NE, ys, fs, cnt,failed); testrel( 4, NE, yc, fc, cnt,failed); x := 1e-10; fs := 0.5235987755982988731e-30; fc := 1e-10; Fresnelx(x,ys,yc); testrel( 5, NE, ys, fs, cnt,failed); testrel( 6, NE, yc, fc, cnt,failed); x := 0.00048828125; fs := 0.6095491996946437605e-10; fc := 0.4882812499999931516e-3; Fresnelx(x,ys,yc); testrel( 7, NE, ys, fs, cnt,failed); testrel( 8, NE, yc, fc, cnt,failed); x := -0.125; fs := -0.1022609856621743054e-2; fc := -0.1249924702994110995; Fresnelx(x,ys,yc); testrel( 9, NE, ys, fs, cnt,failed); testrel(10, NE, yc, fc, cnt,failed); x := 0.5; fs := 0.6473243285999927761e-1; fc := 0.4923442258714463929; Fresnelx(x,ys,yc); testrel(11, NE, ys, fs, cnt,failed); testrel(12, NE, yc, fc, cnt,failed); x := 1.0; fs := 0.4382591473903547661; fc := 0.7798934003768228295; Fresnelx(x,ys,yc); testrel(13, NE, ys, fs, cnt,failed); testrel(14, NE, yc, fc, cnt,failed); x := -1.5; fs := -0.6975049600820930131; fc := -0.4452611760398215351; Fresnelx(x,ys,yc); testrel(15, NE, ys, fs, cnt,failed); testrel(16, NE, yc, fc, cnt,failed); x := 2.0; fs := 0.3434156783636982422; fc := 0.4882534060753407545; Fresnelx(x,ys,yc); testrel(17, NE, ys, fs, cnt,failed); testrel(18, NE, yc, fc, cnt,failed); x := 10.0; fs := 0.4681699785848822404; fc := 0.4998986942055157236; Fresnelx(x,ys,yc); testrel(19, NE, ys, fs, cnt,failed); testrel(20, NE, yc, fc, cnt,failed); x := -100.0; fs := -0.4968169011478375533; fc := -0.4999998986788178976; Fresnelx(x,ys,yc); testrel(21, NE, ys, fs, cnt,failed); testrel(22, NE, yc, fc, cnt,failed); x := 1000.0; fs := 0.4996816901138163061; fc := 0.4999999998986788164; Fresnelx(x,ys,yc); testrel(23, NE, ys, fs, cnt,failed); testrel(24, NE, yc, fc, cnt,failed); x := 5000.10009765625; fs := 0.4999986583294711585; fc := 0.5000636465631322710; Fresnelx(x,ys,yc); testrel(25, NE, ys, fs, cnt,failed); testrel(26, NE, yc, fc, cnt,failed); x := 6000; fs := 0.4999469483523027016; fc := 0.4999999999995309204; Fresnelx(x,ys,yc); testrel(27, NE, ys, fs, cnt,failed); testrel(28, NE, yc, fc, cnt,failed); x := 1e5; fs := 0.4999968169011381621; fc := 0.4999999999999998987; Fresnelx(x,ys,yc); testrel(29, NE, ys, fs, cnt,failed); testrel(20, NE, yc, fc, cnt,failed); x := 2e6; fs := 0.4999998408450569081; fc := 0.5; Fresnelx(x,ys,yc); testrel(31, NE, ys, fs, cnt,failed); testrel(32, NE, yc, fc, cnt,failed); x := 1e7; fs := 0.4999999681690113816; fc := 0.5; Fresnelx(x,ys,yc); testrel(33, NE, ys, fs, cnt,failed); testrel(34, NE, yc, fc, cnt,failed); x := 2e19; fs := 0.5; fc := 0.5; Fresnelx(x,ys,yc); testrel(35, NE, ys, fs, cnt,failed); testrel(36, NE, yc, fc, cnt,failed); x := 1e-2000; fs := 0; fc := 1e-2000; Fresnelx(x,ys,yc); testrel(37, NE, ys, fs, cnt,failed); testrel(38, NE, yc, fc, cnt,failed); {one test for separate functions} x := 0.75; fs := 0.2088771112333835702; fc := 0.6935259907871358975; ys := FresnelSx(x); yc := FresnelCx(x); testrel(39, NE, ys, fs, cnt,failed); testrel(40, NE, yc, fc, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_gsix; var x,y,t: extended; cnt, failed: integer; const NE = 4; {$ifdef BIT16} t5 : THexExtW = ($DD79,$61D8,$E600,$F6AB,$3FFE); {9.6356046208697728562E-1} {$endif} begin cnt := 0; failed := 0; writeln('Function: ','gsix'); {Test values from MISCFUN [22]} x := 1.0/512.0; t := 0.59531540040441651584e1; y := gsix(x); testrel( 1, NE, y, t, cnt,failed); x := 1.0/128.0; t := 0.45769601268624494109e1; y := gsix(x); testrel( 2, NE, y, t, cnt,failed); x := 1.0/32.0; t := 0.32288921331902217638e1; y := gsix(x); testrel( 2, NE, y, t, cnt,failed); x := 1.0/8.0; t := 0.19746110873568719362e1; y := gsix(x); testrel( 4, NE, y, t, cnt,failed); x := 1.0/2.0; {$ifdef BIT16} t := extended(t5); {$else} t := 0.96356046208697728563; {$endif} y := gsix(x); testrel( 5, NE, y, t, cnt,failed); x := 1.0; t := 0.60513365250334458174; y := gsix(x); testrel( 6, NE, y, t, cnt,failed); x := 5.0/4.0; t := 0.51305506459532198016; y := gsix(x); testrel( 7, NE, y, t, cnt,failed); x := 3.0/2.0; t := 0.44598602820946133091; y := gsix(x); testrel( 8, NE, y, t, cnt,failed); x := 15.0/8.0; t := 0.37344458206879749357; y := gsix(x); testrel( 9, NE, y, t, cnt,failed); x := 2.0; t := 0.35433592884953063055; y := gsix(x); testrel(10, NE, y, t, cnt,failed); x := 17.0/8.0; t := 0.33712156518881920994; y := gsix(x); testrel(11, NE, y, t, cnt,failed); x := 5.0/2.0; t := 0.29436170729362979176; y := gsix(x); testrel(12, NE, y, t, cnt,failed); x := 3.0; t := 0.25193499644897222840; y := gsix(x); testrel(13, NE, y, t, cnt,failed); x := 7.0/2.0; t := 0.22028778222123939276; y := gsix(x); testrel(14, NE, y, t, cnt,failed); x := 4.0; t := 0.19575258237698917033; y := gsix(x); testrel(15, NE, y, t, cnt,failed); x := 9.0/2.0; t := 0.17616303166670699424; y := gsix(x); testrel(16, NE, y, t, cnt,failed); x := 5.0; t := 0.16015469479664778673; y := gsix(x); testrel(17, NE, y, t, cnt,failed); x := 23.0/4.0; t := 0.14096116876193391066; y := gsix(x); testrel(18, NE, y, t, cnt,failed); x := 6.0; t := 0.13554987191049066274; y := gsix(x); testrel(19, NE, y, t, cnt,failed); x := 7.0; t := 0.11751605060085098084; y := gsix(x); testrel(20, NE, y, t, cnt,failed); {Test values calculated with Maple} x := 100; t := 0.88127074334736483777e-2; y := gsix(x); testrel(21, NE, y, t, cnt,failed); x := 1000; t := 0.88572736806688441188e-3; y := gsix(x); testrel(22, NE, y, t, cnt,failed); x := 1e18; t := 0.88622692545275801315e-18; y := gsix(x); testrel(23, NE, y, t, cnt,failed); x := 1e19; t := 0.886226925452758013599e-19; y := gsix(x); testrel(24, NE, y, t, cnt,failed); x := 1e20; t := 0.88622692545275801364e-20; y := gsix(x); testrel(25, NE, y, t, cnt,failed); x := 1e-20; t := 45.7630940274301472501; y := gsix(x); testrel(26, NE, y, t, cnt,failed); x := 1e-19; t := 43.4605089344361015662; y := gsix(x); testrel(27, NE, y, t, cnt,failed); x := 1e-18; t := 41.1579238414420558838; y := gsix(x); testrel(28, NE, y, t, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_expint3x; var x,y,t: extended; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','expint3x'); {Test values from MISCFUN [22]} x := 1.0/512.0; t := 0.19531249963620212007e-2; y := expint3x(x); testrel( 1, NE, y, t, cnt,failed); x := 1.0/128.0; t := 0.78124990686775522671e-2; y := expint3x(x); testrel( 2, NE, y, t, cnt,failed); x := 1.0/32.0; t := 0.31249761583499728667e-1; y := expint3x(x); testrel( 3, NE, y, t, cnt,failed); x := 1.0/8.0; t := 0.12493899888803079984; y := expint3x(x); testrel( 4, NE, y, t, cnt,failed); x := 1.0/2.0; t := 0.48491714311363971332; y := expint3x(x); testrel( 5, NE, y, t, cnt,failed); x := 1.0; t := 0.80751118213967145286; y := expint3x(x); testrel( 6, NE, y, t, cnt,failed); x := 5.0/4.0; t := 0.86889265412623270696; y := expint3x(x); testrel( 7, NE, y, t, cnt,failed); x := 3.0/2.0; t := 0.88861722235357162648; y := expint3x(x); testrel( 8, NE, y, t, cnt,failed); x := 15.0/8.0; t := 0.89286018500218176869; y := expint3x(x); testrel( 9, NE, y, t, cnt,failed); x := 2.0; t := 0.89295351429387631138; y := expint3x(x); testrel(10, NE, y, t, cnt,failed); x := 17.0/8.0; t := 0.89297479112737843939; y := expint3x(x); testrel(11, NE, y, t, cnt,failed); x := 18.0/8.0; t := 0.89297880579798112220; y := expint3x(x); testrel(12, NE, y, t, cnt,failed); x := 5.0/2.0; t := 0.89297950317496621294; y := expint3x(x); testrel(13, NE, y, t, cnt,failed); x := 11.0/4.0; t := 0.89297951152951902903; y := expint3x(x); testrel(14, NE, y, t, cnt,failed); x := 3.0; t := 0.89297951156918122102; y := expint3x(x); testrel(15, NE, y, t, cnt,failed); x := 25.0/8.0; t := 0.89297951156924734716; y := expint3x(x); testrel(16, NE, y, t, cnt,failed); x := 13.0/4.0; t := 0.89297951156924917298; y := expint3x(x); testrel(17, NE, y, t, cnt,failed); x := 7.0/2.0; t := 0.89297951156924921121; y := expint3x(x); testrel(18, NE, y, t, cnt,failed); x := 15.0/4.0; t := 0.89297951156924921122; y := expint3x(x); testrel(19, NE, y, t, cnt,failed); x := 4.0; t := 0.89297951156924921122; y := expint3x(x); testrel(20, NE, y, t, cnt,failed); {Test values calculated with Maple} x := 1e-10; t := 1e-10; y := expint3x(x); testrel(21, NE, y, t, cnt,failed); x := 1e-5; t := 0.99999999999999975e-5; y := expint3x(x); testrel(22, NE, y, t, cnt,failed); x := 1e-3; t := 0.99999999975e-3; y := expint3x(x); testrel(23, NE, y, t, cnt,failed); x := PosInf_x; t := 0.89297951156924921122; y := expint3x(x); testrel(24, NE, y, t, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; end.
namespace RemObjects.Elements.EUnit; interface type ArgumentException = public class (BaseException) public constructor (anArgument: String; Message: String); property Argument: String read write; readonly; end; implementation constructor ArgumentException(anArgument: String; Message: String); begin inherited constructor(Message); Argument := anArgument; end; end.
{ ---------------------------------------------------------------- File - WINDRVR_INT_THREAD.PAS Copyright (c) 2003 Jungo Ltd. http://www.jungo.com ---------------------------------------------------------------- } unit WinDrvr_Int_Thread; interface uses Windows, windrvr; type INT_HANDLER_FUNC = procedure(pData : POINTER); EVENT_HANDLER_FUNC = procedure(event : WD_EVENT; pData : POINTER); PWD_INTERRUPT = ^WD_INTERRUPT; INT_THREAD_DATA = record hThread : HANDLE; hWD : HANDLE; func : INT_HANDLER_FUNC; pData : POINTER; pInt : PWD_INTERRUPT; end; PINT_THREAD_DATA = ^INT_THREAD_DATA; EVENT_HANDLE_T = record func : EVENT_HANDLER_FUNC; hWD : HANDLE; pdata : POINTER; thread : HANDLE; pInt : WD_INTERRUPT; end; PEVENT_HANDLE_T = ^EVENT_HANDLE_T; PPEVENT_HANDLE_T = ^PEVENT_HANDLE_T; { OLD prototypes for backward compatibility } function InterruptThreadEnable(phThread : PHANDLE; hWD : HANDLE; pInt : PWD_INTERRUPT; func : INT_HANDLER_FUNC; pData : POINTER) : BOOLEAN; procedure InterruptThreadDisable(hThread : HANDLE); function event_register(hWD : HANDLE; event : PWD_EVENT; func : EVENT_HANDLER_FUNC; pdata : Pointer) : PEVENT_HANDLE_T; procedure event_unregister(hWD : HANDLE ; handle : PEVENT_HANDLE_T); { New prototypes. Functions return status. } function InterruptEnable(phThread : PHANDLE; hWD : HANDLE; pInt : PWD_INTERRUPT; func : INT_HANDLER_FUNC; pData : POINTER) : DWORD; function InterruptEnable1(phThread : PHANDLE; hWD : HANDLE; pInt : PWD_INTERRUPT; func : INT_HANDLER_FUNC; pData : POINTER) : DWORD; function InterruptDisable(hThread : HANDLE) : DWORD; function EventRegister(phThread : PPEVENT_HANDLE_T; hWD : HANDLE; event : PWD_EVENT; func : EVENT_HANDLER_FUNC; pdata : Pointer) : DWORD; function EventUnregister(handle : PEVENT_HANDLE_T) : DWORD; implementation function InterruptThreadHandler(pData : POINTER) : INTEGER; var pThread : PINT_THREAD_DATA; begin pThread := PINT_THREAD_DATA (pData); while True do begin WD_IntWait(pThread^.hWD, pThread^.pInt^); if pThread^.pInt^.fStopped = 1 then Break; pThread^.func(pThread^.pData); end; InterruptThreadHandler := 0; end; function InterruptThreadHandler1(pData : POINTER) : INTEGER;stdCall; var pThread : PINT_THREAD_DATA; begin pThread := PINT_THREAD_DATA (pData); while True do begin WD_IntWait(pThread^.hWD, pThread^.pInt^); if pThread^.pInt^.fStopped = 1 then Break; pThread^.func(pThread^.pData); end; InterruptThreadHandler1 := 0; end; function InterruptThreadEnable(phThread : PHANDLE; hWD : HANDLE; pInt : PWD_INTERRUPT; func : INT_HANDLER_FUNC; pData : POINTER) : BOOLEAN; var dwStatus : DWORD; begin dwStatus := InterruptEnable(phThread, hWD, pInt, func, pData); if dwStatus=0 then InterruptThreadEnable := True else InterruptThreadEnable := False end; function InterruptEnable(phThread : PHANDLE; hWD : HANDLE; pInt : PWD_INTERRUPT; func : INT_HANDLER_FUNC; pData : POINTER) : DWORD; var pThread : ^INT_THREAD_DATA; dwStatus : DWORD; begin phThread^ := 0; dwStatus := WD_IntEnable(hWD, pInt^); { check if WD_IntEnable failed } if dwStatus>0 then begin InterruptEnable := dwStatus; Exit; end; GetMem(POINTER(pThread), SizeOf(INT_THREAD_DATA)); pThread^.func := func; pThread^.pData := pData; pThread^.hWD := hWD; pThread^.pInt := pInt; pThread^.hThread := BeginThread (nil, $1000, InterruptThreadHandler, POINTER(pThread), 0, WinDriverGlobalDW); phThread^ := HANDLE (pThread); InterruptEnable := WD_STATUS_SUCCESS; end; function InterruptEnable1(phThread : PHANDLE; hWD : HANDLE; pInt : PWD_INTERRUPT; func : INT_HANDLER_FUNC; pData : POINTER) : DWORD; var pThread : ^INT_THREAD_DATA; dwStatus : DWORD; begin phThread^ := 0; dwStatus := WD_IntEnable(hWD, pInt^); { check if WD_IntEnable failed } if dwStatus>0 then begin InterruptEnable1 := dwStatus; Exit; end; GetMem(POINTER(pThread), SizeOf(INT_THREAD_DATA)); pThread^.func := func; pThread^.pData := pData; pThread^.hWD := hWD; pThread^.pInt := pInt; pThread^.hThread := createThread (nil, $1000, @InterruptThreadHandler1, POINTER(pThread), 0, WinDriverGlobalDW); setThreadPriority(pThread^.hThread,THREAD_PRIORITY_TIME_CRITICAL); phThread^ := HANDLE (pThread); InterruptEnable1 := WD_STATUS_SUCCESS; end; procedure InterruptThreadDisable(hThread : HANDLE); begin InterruptDisable(hThread); end; function InterruptDisable(hThread : HANDLE) : DWORD; var pThread : PINT_THREAD_DATA; begin if hThread=0 then begin InterruptDisable := WD_INVALID_HANDLE; end; pThread := PINT_THREAD_DATA (hThread); InterruptDisable := WD_IntDisable(pThread^.hWD, pThread^.pInt^); WaitForSingleObject(pThread^.hThread, INFINITE); CloseHandle(pThread^.hThread); Freemem(pThread); end; function EventHandler(pData : Pointer) : integer; Var handle : PEVENT_HANDLE_T; pull :WD_EVENT; Begin handle := PEVENT_HANDLE_T(pData); pull.handle := handle.pInt.hInterrupt; WD_EventPull(handle.hWD, @pull); if (pull.dwAction <> 0) then handle.func(pull, handle.pdata); if (pull.dwOptions = WD_ACKNOWLEDGE) then WD_EventSend(handle.hWD, @pull); end; function event_register(hWD : HANDLE; event : PWD_EVENT; func : EVENT_HANDLER_FUNC; pdata : Pointer) : PEVENT_HANDLE_T; var pEvent : PEVENT_HANDLE_T; begin EventRegister(@pEvent, hWD, event, func, pdata); event_register := pEvent; end; function EventRegister(phThread : PPEVENT_HANDLE_T; hWD : HANDLE; event : PWD_EVENT; func : EVENT_HANDLER_FUNC; pdata : Pointer) : DWORD; Var handle : PEVENT_HANDLE_T; wdevent : WD_EVENT; dwStatus : DWORD; label Error; Begin phThread^ := nil; handle := nil; getmem(handle,sizeof(EVENT_HANDLE_T)); if (handle = nil) then begin EventRegister := WD_INSUFFICIENT_RESOURCES; goto Error; end; fillchar(handle^,sizeof(EVENT_HANDLE_T),0); handle^.func := func; handle^.hWD := hWD; handle^.pdata := pdata; fillchar(wdevent,sizeof(WD_EVENT),0); event^.dwOptions := WD_ACKNOWLEDGE; wdevent := event^; EventRegister := WD_EventRegister(hWD, @wdevent); if (wdevent.handle = 0) then goto Error; handle^.pInt.hInterrupt := wdevent.handle; dwStatus := InterruptEnable(@handle^.thread, hWD, @handle.pInt, @EventHandler, Pointer(handle)); EventRegister := dwStatus; if dwStatus=WD_STATUS_SUCCESS then begin phThread^ := handle; Exit; end; Error: if ((handle <> nil) and (handle.pInt.hInterrupt <> 0)) then WD_EventUnregister(hWD, @event_register); if (handle <> nil) then freemem(handle); End; procedure event_unregister(hWD : HANDLE ; handle : PEVENT_HANDLE_T); begin EventUnregister(handle); end; function EventUnregister(handle : PEVENT_HANDLE_T) : DWORD; Var event : WD_EVENT; begin event.handle := handle.pInt.hInterrupt; InterruptDisable(handle.thread); EventUnregister := WD_EventUnregister(handle^.hWD, @event); freemem(handle); end; end.
unit uConstanta; interface uses Windows, SysUtils, Classes, Messages; // biar bisa dpull const // core CONFIG_FILE = 'config.ini'; DB_HO = 'DBHO'; DB_STORE = 'DBSTORE'; DEBUG = 'DEBUG'; //POS DB_POS = 'DBPOS'; FILE_HEADER : string = 'header.txt'; FILE_HEAD_STRUK = '_headstruk.txt'; FILE_ISI_STRUK = '_isistruk.txt'; FILE_FOOTER_STRUK = '_footstruk.txt'; FILE_FOOTER = 'footer.txt'; FILE_FOOTER_SISA = 'footersisa.txt'; FILE_HEADER_CASHBACK = 'headcb.txt'; FILE_FOOTER_CASHBACK = 'footcb.txt'; FILE_ISI_CASHBACK = '_isicb.txt'; FILE_VALIDASI = '_valid.txt'; MSG_PAYMENT_NOT_VALID: string = 'Jumlah pembayaran masih kurang.'; MSG_MAX_KEMBALIAN = 'Uang kembalian harus kurang dari = Rp. '; MSG_CREDIT_CARD_MINIMUM = 'Transaksi minimal untuk pembayaran kartu = Rp. '; MSG_CREDIT_CARD_MAXIMUM = 'Pembayaran dengan kartu tidak bisa melebihi dari total pembelian'; MSG_CREDIT_CARD_NOT_FOUND = 'Kode kartu tidak ditemukan.'; MSG_CREDIT_CARD_NO_EMPTY = 'Nomor kartu masih kosong.'; MSG_CREDIT_CARD_AUTHORIZE_EMPTY = 'Otorisasi kartu masih kosong.'; MSG_CASHBACK_KELIPATAN_INVALID = 'Penarikan cashback harus kelipatan = Rp. '; MSG_CASHBACK_MAXIMUM = 'Penarikan cashback maximum = Rp. '; //POS POS_ACTIVATION_FAILED = 'Failed to activate POS'; POS_ACTIVATION_SUCCESSFULLY = 'POS Activated successfully'; CONF_RESET_CASHIER = 'Are you sure want to Close this Cashier(s)?'; CONF_UNRESET_CASHIER = 'Are you sure want to Open this Cashier(s)?'; REFRESH_SERVER = 'REFRESH_SERVER'; LOCAL_CLIENT = 'LOCAL_CLIENT'; PATH_FILE_NOTA = 'PATH_FILE_NOTA'; PATH_TEMPLATE = 'PATH_REPORT'; // error message ER_EMPTY = ' Tidak Boleh Kosong'; ER_EXIST = ' Sudah Ada'; ER_STOPPED = 'Process stopped. '; ER_PO_IS_NOT_EXIST = 'Nomor PO Tida Ditemukan!'; ER_INSERT_FAILED = 'Gagal Menyimpan Data'; ER_UPDATE_FAILED = 'Gagal Mengubah Data'; ER_DELETE_FAILED = 'Gagal Menghapus Data'; ER_QUERY_FAILED = 'Gagal Eksekusi Query'; ER_SP_FAILED = 'Gagal Eksekusi Stored Procedure'; ER_QTY_NOT_ALLOWED = 'Qty Tidak Diperbolehkan'; ER_SO_NOT_SPECIFIC = '"Create SO for" must be specific.'; ER_BRG_NOT_SPECIFIC = 'Produk Harus Specific'; ER_SAVE_DO = 'Gagal Simpan DO'; ER_DO_BONUS = 'Gagal Simpan DO Bonus'; ER_SHIFT_NOT_FOUND = 'Shift name not found.'; ER_TRANSACT_NOT_FOUND = 'Transaction number not found.'; ER_FAILED_INSERT_PO_ASSGROS = 'Input PO from trader failed.'; ER_UNIT_NOT_SPECIFIC = 'Unit Belum Dipilih'; ER_COMPANY_NOT_SPECIFIC = 'Company Belum Dipilih'; ER_UNIT_OR_COMPANY_NOT_SPECIFIC = 'Company Atau Unit Belum Dipilih'; ER_NOT_FOUND = 'Tidak Ditemukan'; ER_TOTAL_ALLOCATION = 'Total Alokasi Harus 100'; ER_TAX_EXPIRED = 'Tax is Expired, Please Renew.'; ER_SUBSIDY_TELAH_DIGUNAKAN = 'Subsidy can not delete, because already used '; ER_VIOLATION_FOREIGN_KEY = 'Could not delete data. It has already used'; ERR_CODE_VIOLATION=335544466; ER_FISCAL_PERIODE_INACTIVE = 'Fiscal Periode Is Inactive'; // confirm CONF_ADD_SUCCESSFULLY = 'Berhasil Menyimpan Data'; CONF_EDIT_SUCCESSFULLY = 'Berhasil Mengubah Data'; CONF_DELETE_SUCCESSFULLY = 'Berhasil Menghapus Data'; CONF_VALIDATE_SUCCESSFULLY = 'Validate successfully.'; CONF_COULD_NOT_EDIT = 'Data could not edit.'; CONF_COULD_NOT_DELETE = 'Data could not delete.'; CONF_TOTAL_AGREEMENT = 'Total agreement not enough.'; SAVE_DO_SUCCESSFULLY = 'DO saved successfully.'; SAVE_DO_EXPIRED = 'PO updated successfully.'; SAVE_SERVICE_LEVEL_SUCCESSFULLY = 'Service Level saved successfully.'; SAVE_CN_SUCCESSFULLY = 'Credit Note saved successfully.'; SAVE_DN_SUCCESSFULLY = 'Debit Note saved successfully.'; SAVE_RETUR_SUCCESSFULLY = 'Retur saved successfully.'; PRINT_NP_SUCCESSFULLY = 'NP printed successfully.'; PRINT_CN_SUCCESSFULLY = 'CN printed successfully.'; PRINT_DN_SUCCESSFULLY = 'DN printed successfully.'; PRINT_PAYMENT_RETUR_NOTA = 'Payment Retur Nota printed successfully.'; GENERATE_PO_SUCCESSFULLY = 'PO generated successfully.'; GENERATE_SYNC_SUCCESSFULLY = 'Synchronize generated successfully.'; GENERATE_SYNC_FINISH = 'Synchronize finish.'; GENERATE_SYNC_FINISH_WARNING = 'Export failed.'; IMPORT_SYNC_SUCCESSFULLY = 'Synchronizing is done successfully.'; IMPORT_SYNC_ERROR = 'Synchronizing is done with error.'; ACTIVATE_POS_SUCCESSFULLY = 'POS Activated successfully.'; PRODUCT_NOT_FOUND = 'Product not found.'; PRINT_DO_FOR_ASSGROS_SUCCESSFULLY = 'DO For Assgrss printed successfully.'; PO_APPROVED_SUCCESSFULLY = 'PO approved successfully'; PO_CHANGED_SUCCESSFULLY = 'PO changed successfully'; PO_CANCELLED_SUCCESSFULLY = 'PO canceled successfully'; // db DEBUG_MODE_ON = true; DEBUG_MODE_OFF = false; // micellanious CN_RECV_DESCRIPTION = 'CN Receive'; DN_RECV_DESCRIPTION = 'DN Receive'; PO_DESCRIPTION_EXPIRED = 'Valid Date was expired'; PO_DESCRIPTION_RECEIVED = 'Valid Date was received'; PO_DESCRIPTION_GENERATED = 'PO generated'; DO_DESCRIPTION_RECEIVED = 'Delivery Order was received'; TRANSACTION_NUMBER_CANT_BE_DELETED = 'Transaction could not be deleted'; TRANSACTION_NUMBER_CANT_BE_EDITED = 'Transaction could not be edited'; // BEGINNING BALANCE BEGINNING_BALANCE_MODAL = 200000; // loading caption USER_MENU_LOADING = 'Please wait. Creating user menu ...'; USER_LOGIN_LOADING = 'Please wait. Authorizing user ...'; FORM_LOADING = 'Please wait. Form loading ...'; // button show message BUTTON_CAPTION1 = 'Yes'; BUTTON_CAPTION2 = 'No'; BUTTON_CAPTION3 = 'Cancel'; MESSAGE_CAPTION = 'Point of Sales - '; // sync SYNC_LOCAL_DIR = 'sinkronisasi\sync\'; SYNC_XMLFILENAME = 'sync.xml'; REFERENCES_TABLE = 'references'; IGRA_TABLE = 'igra'; RECEIVING_TABLE = 'receiving'; SYNC_SESSION_FILE = '_session.xml'; //default number INVOICE_NO = '/INV/MG/'; ACCRUAL_NO = '/ACR/MG/'; //Finance AP_PAYMENT_DAY_1 = '3'; AP_PAYMENT_DAY_2 = '5'; {Note: 1 -> Sunday, 7 --> Saturday} //Jurnal CONF_JURNAL_ALREADY_POSTED = 'The Jurnal has already posted'; PROC_REVERSE_JOUNAL = 'Reverse Journal'; //Message Constant STORE_PARAM = 2010; GORO_MAIN_MESSAGE = WM_USER + 7251; GORO_HO_MAIN_FORM_CHX_COMP_ID = GORO_MAIN_MESSAGE + 1; GORO_HO_MAIN_FORM_CHX_UNIT_ID = GORO_MAIN_MESSAGE + 2; TABLE_NODE = 'table'; RECORD_NODE = 'record'; TYPE_NODE = 'type'; SQL_NODE = 'sql'; ATT_RECORD_NODE = 'no'; DELIMITER_ASSIGN = '='; DELIMITER_COMMA = ','; INSERT_TYPE = 'insert'; UPDATE_TYPE = 'update'; DELETE_TYPE = 'delete'; // MESSAGE CONSTANTA WM_REFRESH_SERVER_MESSAGE = WM_USER + 1000; WM_STORE_MESSAGE = WM_USER + 2000; STORE_POS_TRANS_BOTOL = STORE_PARAM + 1; STORE_POS_TRANS_VOUCHER = STORE_PARAM + 2; STORE_POS_RESET_CASHIER = STORE_PARAM + 3; STORE_REFRESH_TRANS_BOTOL = STORE_PARAM + 4; STORE_REFRESH_VOUCHER = STORE_PARAM + 5; STORE_REFRESH_RESET_CASHIER = STORE_PARAM + 8; REFRESH_SERVER_UP = STORE_PARAM + 6; REFRESH_SERVER_DOWN = STORE_PARAM + 7; // PO LEAD_TIME = 7; INT_MAX_ROW_PO = 20; // LIST MEMBERSHIP JENIS_BAYAR_KARTU_BARU = 'BIAYA KARTU BARU'; JENIS_BAYAR_PERPANJANGAN_KARTU = 'BIAYA PERPANJANGAN KARTU'; MSG_SUPPLIER = WM_USER + 200; SUPLIER_REFRESH_UNIT = MSG_SUPPLIER + 1; //POS Transaksi Column Index _KolPLU : integer = 1; _KolNamaBarang : integer = 2; _KolJumlah : integer = 3; _KolUOM : integer = 4; _KolHarga : integer = 5; _KolDisc : integer = 6; //zainal _KolDiscManForm : integer = 7; //added 7 April 2015 _KolDiscMan : integer = 8; _KolTotal : integer = 9; _KolIsDecimal : integer = 10; _KolIsDiscGMC : integer = 11; _KolIsMailer : integer = 12; _KolPPN : integer = 13; _KolPPNBM : integer = 14; _KolIsCharge : integer = 15; _KolCOGS : integer = 16; _KolLastCost : integer = 17; _KolIsBKP : integer = 18; _KolBHJID : integer = 19; _KolHargaExcPajak : integer = 20; _KolTipeBarang : integer = 21; _KolHargaAvg : integer = 22; _KolMaxDiscQTY : integer = 23; _KolPairCode : integer = 24; _KolIsGalon : integer = 25; _KolDetailID : integer = 26; _KolDiscP : integer = 27; _Koldiscoto : Integer = 28; _KolIsKontrabon : Integer = 29; {$IFDEF TSN} _ColCount : Integer = 30; {$ELSE} _ColCount : Integer = 29; {$ENDIF} var //dibawah ini dipindah ke variabel global database saja ya.. //Product ig=integer global igProd_Code_Length : Integer = 6; // max 9 ya. integer safe , def = 6 //Precision Harga di Transaksi End user dan Kring , def = -2 igPrice_Precision : Integer = -2; //Precision Qty di Transaksi End user dan Kring , def = -3 igQty_Precision : Integer = -3; implementation end.
program TestRegExpr; { Very simple test of Delphi Regular Expression library (www.RegExpStudio.com) for Delphi/FreePascal compilers. This is also self-test (very basic one) for the library. Adapted from FreePascal test application \source\packages\base\regexpr\testreg1.pp by Andrey V. Sorokin. 2004.01.04 v.1.0 -=- Just first version } {$IFDEF FPC} {$MODE DELPHI} // Delphi-compatible mode in FreePascal {$ENDIF} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, RegExpr, tests; type { TestApplication } TestApplication = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TestApplication } procedure TestApplication.DoRun; begin tests.tests(); // stop program loop readln (); Terminate; end; constructor TestApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TestApplication.Destroy; begin inherited Destroy; end; procedure TestApplication.WriteHelp; begin { add your help code here } writeln('Usage: ', ExeName, ' -h'); end; var Application: TestApplication; begin Application:=TestApplication.Create(nil); Application.Title:='My Application'; Application.Run; Application.Free; end.
unit Objekt.DHLValidateStateList; interface uses System.SysUtils, System.Classes, Objekt.DHLValidateState, Objekt.DHLBaseList, System.Contnrs; type TDHLValidateStateList = class(TDHLBaseList) private fValidateState : TDHLValidateState; function getDHLValidateState(Index: Integer): TDHLValidateState; public constructor Create; override; destructor Destroy; override; property Item[Index: Integer]: TDHLValidateState read getDHLValidateState; function Add: TDHLValidateState; end; implementation { TDHLValidateStateList } constructor TDHLValidateStateList.Create; begin inherited; end; destructor TDHLValidateStateList.Destroy; begin inherited; end; function TDHLValidateStateList.Add: TDHLValidateState; begin fValidateState := TDHLValidateState.Create; fList.Add(fValidateState); Result := fValidateState; end; function TDHLValidateStateList.getDHLValidateState(Index: Integer): TDHLValidateState; begin Result := nil; if Index > fList.Count -1 then exit; Result := TDHLValidateState(fList[Index]); end; end.
unit Unit1; {$DEFINE ZERO} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Label0_0: TLabel; Label0_1: TLabel; Label1_1: TLabel; Label0_2: TLabel; Label1_2: TLabel; Label2_2: TLabel; Label1_3: TLabel; Label2_3: TLabel; Label1_10: TLabel; Label5_10: TLabel; ZeroCheckBox: TCheckBox; StartCheckBox: TCheckBox; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure CheckBoxClick(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateValues; end; var Form1: TForm1; implementation {$R *.dfm} uses NtPattern, NtLanguageDlg; procedure TForm1.UpdateValues; resourcestring // Contains two parts: // - Part 1 handles completed steps. // - Part 2 handles the total amount of steps. SMessagePlural = '{plural, one {I have completed one step} other {I have completed %d steps}} {plural one {out of one step} other {out of %d steps}}'; // Same as above but with top level pattern. This makes pattern shorter and help eliminating // repeating the same text on multiple patterns. Contains three parts: // - Top level pattern that has two placeholders for plural parts. // - Part 1 handles completed steps. // - Part 2 handles the total amount of steps. SStartMessagePlural = 'I have completed {plural, one {one step} other {%d steps}} {plural, one {out of one step} other {out of %d steps}}'; // Same as above but with special zero case. SZeroMessagePlural = 'I have completed {plural, zero {no steps} one {one step} other {%d steps}} {plural, zero {out of none steps} one {out of one step} other {out of %d steps}}'; function Process(completed, total: Integer): String; var pattern: String; begin if ZeroCheckBox.Checked then pattern := SZeroMessagePlural else if StartCheckBox.Checked then pattern := SStartMessagePlural else pattern := SMessagePlural; Result := TMultiPattern.Format(pattern, [completed, total]); end; begin Label0_0.Caption := Process(0, 0); Label0_1.Caption := Process(0, 1); Label1_1.Caption := Process(1, 1); Label0_2.Caption := Process(0, 2); Label1_2.Caption := Process(1, 2); Label2_2.Caption := Process(2, 2); Label1_3.Caption := Process(1, 3); Label2_3.Caption := Process(2, 3); Label1_10.Caption := Process(1, 10); Label5_10.Caption := Process(5, 10); end; procedure TForm1.FormCreate(Sender: TObject); begin UpdateValues; end; procedure TForm1.CheckBoxClick(Sender: TObject); begin UpdateValues; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select then UpdateValues; end; // If your original language is not English remove comments and set the default language here. { initialization DefaultLocale := 'de'; } end.
unit ModflowFmpBaseClasses; interface uses ModflowBoundaryUnit, FormulaManagerUnit, Classes, OrderedCollectionUnit, SysUtils, GoPhastTypes, RealListUnit; type TCustomFarmItem = class(TCustomModflowBoundaryItem) protected FFormulaObjects: array of TFormulaObject; procedure AssignObserverEvents(Collection: TCollection); override; procedure GetPropertyObserver(Sender: TObject; List: TList); override; procedure RemoveFormulaObjects; override; // @name checks whether AnotherItem is the same as the current @classname. function IsSame(AnotherItem: TOrderedItem): boolean; override; public // @name copies Source to this @classname. procedure CreateFormulaObjects; override; procedure Assign(Source: TPersistent); override; end; TCustomZeroFarmItem = class(TCustomFarmItem) protected procedure SetFormulasToZero; public constructor Create(Collection: TCollection); override; Destructor Destroy; override; end; TCustomFarmCollection = class(TCustomNonSpatialBoundColl) public constructor Create(Model: TBaseModel); reintroduce; function ItemByStartTime(ATime: Double): TCustomBoundaryItem; procedure UpdateTimes(Times: TRealList; StartTestTime, EndTestTime: double; var StartRangeExtended, EndRangeExtended: boolean); end; TDefineGlobalObject = class(TObject) private FModel: TBaseModel; FOldName: string; FNewName: string; FComment: string; public constructor Create(Model: TBaseModel; const OldName, NewName, Comment: string); procedure Rename; procedure SetValue(Value: Integer); end; implementation uses frmGoPhastUnit, PhastModelUnit, GlobalVariablesUnit, RbwParser; { TCustomFarmItem } procedure TCustomFarmItem.Assign(Source: TPersistent); var Index: integer; OtherItem: TCustomFarmItem; begin if Source is TCustomFarmItem then begin OtherItem := TCustomFarmItem(Source); for Index := 0 to BoundaryFormulaCount - 1 do begin BoundaryFormula[Index] := OtherItem.BoundaryFormula[Index]; end; end; inherited; end; procedure TCustomFarmItem.AssignObserverEvents(Collection: TCollection); begin // do nothing end; procedure TCustomFarmItem.CreateFormulaObjects; var Index: integer; begin SetLength(FFormulaObjects, BoundaryFormulaCount); for Index := 0 to BoundaryFormulaCount - 1 do begin FFormulaObjects[Index] := CreateFormulaObject(dso3D); end; end; procedure TCustomFarmItem.GetPropertyObserver(Sender: TObject; List: TList); var Index: integer; begin for Index := 0 to BoundaryFormulaCount - 1 do begin if Sender = FFormulaObjects[Index] then begin List.Add(FObserverList[Index]); Break; end; end; end; function TCustomFarmItem.IsSame(AnotherItem: TOrderedItem): boolean; var OtherItem: TCustomFarmItem; Index: integer; begin result := (AnotherItem is TCustomFarmItem) and inherited IsSame(AnotherItem); if result then begin OtherItem := TCustomFarmItem(AnotherItem); for Index := 0 to BoundaryFormulaCount - 1 do begin result := BoundaryFormula[Index] = OtherItem.BoundaryFormula[Index]; if not result then begin Exit; end; end; end; end; procedure TCustomFarmItem.RemoveFormulaObjects; var Index: integer; begin for Index := 0 to BoundaryFormulaCount - 1 do begin frmGoPhast.PhastModel.FormulaManager.Remove(FFormulaObjects[Index], GlobalRemoveModflowBoundaryItemSubscription, GlobalRestoreModflowBoundaryItemSubscription, self); end; end; { TCustomZeroFarmItem } constructor TCustomZeroFarmItem.Create(Collection: TCollection); begin inherited; SetFormulasToZero; end; destructor TCustomZeroFarmItem.Destroy; begin SetFormulasToZero; inherited; end; procedure TCustomZeroFarmItem.SetFormulasToZero; var Index: integer; begin for Index := 0 to BoundaryFormulaCount - 1 do begin BoundaryFormula[Index] := '0'; end; end; { TCustomFarmCollection } constructor TCustomFarmCollection.Create(Model: TBaseModel); begin inherited Create(nil, Model, nil); end; function TCustomFarmCollection.ItemByStartTime( ATime: Double): TCustomBoundaryItem; var TimeIndex: Integer; AnItem: TCustomBoundaryItem; begin result := nil; for TimeIndex := 0 to Count - 1 do begin AnItem := Items[TimeIndex]; if AnItem.StartTime <= ATime then begin result := AnItem; if AnItem is TCustomModflowBoundaryItem then begin if TCustomModflowBoundaryItem(AnItem).EndTime > ATime then begin Break; end; end; end; end; end; procedure TCustomFarmCollection.UpdateTimes(Times: TRealList; StartTestTime, EndTestTime: double; var StartRangeExtended, EndRangeExtended: boolean); var BoundaryIndex: Integer; Boundary: TCustomModflowBoundaryItem; CosestIndex: Integer; ExistingTime: Double; SP_Epsilon: Extended; begin SP_Epsilon := (Model as TCustomModel).SP_Epsilon; for BoundaryIndex := 0 to Count - 1 do begin Boundary := Items[BoundaryIndex] as TCustomModflowBoundaryItem; CosestIndex := Times.IndexOfClosest(Boundary.StartTime); if CosestIndex >= 0 then begin ExistingTime := Times[CosestIndex]; if Abs(ExistingTime-Boundary.StartTime) > SP_Epsilon then begin Times.AddUnique(Boundary.StartTime); end; end; CosestIndex := Times.IndexOfClosest(Boundary.EndTime); if CosestIndex >= 0 then begin ExistingTime := Times[CosestIndex]; if Abs(ExistingTime-Boundary.EndTime) > SP_Epsilon then begin Times.AddUnique(Boundary.EndTime); end; end; if (Boundary.StartTime < StartTestTime-SP_Epsilon) then begin StartRangeExtended := True; end; if (Boundary.EndTime > EndTestTime+SP_Epsilon) then begin EndRangeExtended := True; end; end; end; { TDefineGlobalObject } constructor TDefineGlobalObject.Create(Model: TBaseModel; const OldName, NewName, Comment: string); begin FModel := Model; FOldName := OldName; FNewName := NewName; FComment := Comment; end; procedure TDefineGlobalObject.Rename; var LocalModel: TPhastModel; NewVariables: TGlobalVariables; Variable: TGlobalVariable; OldNames: TStringList; NewNames: TStringList; begin LocalModel := (FModel as TPhastModel); NewVariables := TGlobalVariables.Create(nil); try NewVariables.Assign(LocalModel.GlobalVariables); Variable := NewVariables.GetVariableByName(FOldName); if Variable <> nil then begin OldNames := TStringList.Create; NewNames := TStringList.Create; try OldNames.Add(FOldName); NewNames.Add(FNewName); LocalModel.UpdateFormulas(OldNames, NewNames); Variable.Name := FNewName; LocalModel.GlobalVariables := NewVariables; LocalModel.FormulaManager.RestoreSubscriptions; finally NewNames.Free; OldNames.Free; end; end; finally NewVariables.Free; end; end; procedure TDefineGlobalObject.SetValue(Value: Integer); var LocalModel: TPhastModel; Variable: TGlobalVariable; begin LocalModel := (FModel as TPhastModel); Variable := LocalModel.GlobalVariables.GetVariableByName(FNewName); if Variable = nil then begin Variable := (LocalModel.GlobalVariables.Add as TGlobalVariableItem).Variable; Variable.Format := rdtInteger; Variable.Name := FNewName; end; Variable.IntegerValue := Value; Variable.Locked := True; Variable.Comment := FComment; end; end.
unit UEnumPublisher; interface uses TypInfo, SysUtils, SysConst, Generics.Collections; type // TTestEnum = (en1, en2, en3); TEnumTextInfo = record Name: string; Comment: String; end; //const // CTestEnumInfo: array[TTestEnum] of TEnumTextInfo = ( // (Name: '1'; Comment: '11'), // (Name: '2'; Comment: '22'), // (Name: '3'; Comment: '33') // ); type TRttiEnumIterHelp<TEnum> = class private class function EnumValue(const aValue: Integer): TEnum; static; protected class procedure DoIter(AIdx: Integer; AInfo: TEnumTextInfo); virtual; abstract; class procedure EnumAll(AInfoArray: array of TEnumTextInfo); static; public end; // пример: TRttiEnumIterHelp<TTestEnum>.EnumAll(CTestEnumInfo); TestEnumPublishMySql<TEnum> = class(TRttiEnumIterHelp<TEnum>) protected class procedure DoIter(AIdx: Integer; AInfo: TEnumTextInfo); public class procedure Publish(AInfoArray: array of TEnumTextInfo; ATableName: string); overload; static; end; // end; // TEnumPublish<TEnum, CConstArray> = class // class procedure EnumIter<TEnum {:enum}>; static; // procedure // end; implementation class procedure TRttiEnumIterHelp<TEnum>.EnumAll(AInfoArray: array of TEnumTextInfo); var typeInf: PTypeInfo; typeData: PTypeData; iterValue: Integer; begin typeInf := PTypeInfo(TypeInfo(TEnum)); if typeInf^.Kind <> tkEnumeration then raise EInvalidCast.CreateRes(@SInvalidCast); typeData := GetTypeData(typeInf); for iterValue := typeData.MinValue to typeData.MaxValue do DoIter(iterValue, AInfoArray[iterValue]); end; class function TRttiEnumIterHelp<TEnum>.EnumValue(const aValue: Integer): TEnum; var typeInf: PTypeInfo; begin typeInf := PTypeInfo(TypeInfo(TEnum)); if typeInf^.Kind <> tkEnumeration then raise EInvalidCast.CreateRes(@SInvalidCast); case GetTypeData(typeInf)^.OrdType of otUByte, otSByte: PByte(@Result)^ := aValue; otUWord, otSWord: PWord(@Result)^ := aValue; otULong, otSLong: PInteger(@Result)^ := aValue; else raise EInvalidCast.CreateRes(@SInvalidCast); end; end; { TestEnumMySqlPublish<TEnum> } class procedure TestEnumPublishMySql<TEnum>.DoIter(AIdx: Integer; AInfo: TEnumTextInfo); begin end; class procedure TestEnumPublishMySql<TEnum>.Publish(AInfoArray: array of TEnumTextInfo; ATableName: string); begin end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // 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 ConTEXT Project Ltd 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 OWNER 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. unit fCustomizeFileTypes; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, uCommon, SynEditHighlighter, uMultiLanguage, MainInstance; type TItem = class private fHL :pTHighlighter; public Modified :boolean; constructor Create(HL:pTHighlighter); property HL :pTHighlighter read fHL; end; TfmCustomizeType = class(TForm) lbHL: TListBox; labHighlighters: TLabel; btnOK: TButton; btnCancel: TButton; btnEdit: TButton; procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure lbHLDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure btnEditClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private TabPos1 :integer; procedure Clear; procedure RefreshList; procedure InstanceFileOpenNotify(var Msg: tMessage); message wmMainInstanceOpenFile; public modal_result :TModalResult; end; var fmCustomizeType: TfmCustomizeType; implementation uses fMain; {$R *.DFM} const COL1_WIDTH_FACTOR = 0.35; //////////////////////////////////////////////////////////////////////////////////////////// // Form events //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TItem.Create(HL:pTHighlighter); begin fHL:=HL; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Messages //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.InstanceFileOpenNotify(var Msg: tMessage); begin fmMain.InstanceFileOpenNotify(Msg); end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function ExtToStr(ext:string):string; var i :integer; begin result:=''; while (Length(ext)>0) do begin ext:=TrimLeft(ext); if (Pos('*.',ext)=1) then Delete(ext,1,2); i:=1; while (i<=Length(ext)) and (ext[i]<>';') do inc(i); if (Length(result)>0) then result:=result+', '; result:=result+Copy(ext,1,i-1); Delete(ext,1,i); end; end; //------------------------------------------------------------------------------------------ function StrToExt(s:string):string; var i :integer; begin result:=''; while (Length(s)>0) do begin i:=1; while (i<=Length(s)) and (s[i]<>',') do inc(i); result:=result+'*.'+Trim(Copy(s,1,i-1))+';'; Delete(s,1,i); end; if ((Length(result)>0) and (result[Length(result)]=';')) then SetLength(result,Length(result)-1); end; //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.Clear; var i :integer; begin for i:=0 to lbHL.Items.Count-1 do TItem(lbHL.Items.Objects[i]).Free; lbHL.Items.Clear; end; //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.RefreshList; var i :integer; begin Clear; for i:=1 to HIGHLIGHTERS_COUNT-1 do begin lbHL.Items.AddObject(Highlighters[i].Name+#09+ExtToStr(Highlighters[i].Ext), TItem.Create(@Highlighters[i])); end; lbHL.ItemIndex:=0; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Buttons //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.btnOKClick(Sender: TObject); var i :integer; s :string; Item :TItem; begin for i:=0 to lbHL.Items.Count-1 do begin s:=lbHL.Items[i]; Item:=TItem(lbHL.Items.Objects[i]); if Item.Modified then begin Item.HL^.Ext:=StrToExt(Copy(s,Pos(#09,s)+1,Length(s))); CopyExtToDefaultFilter(Item.HL); Item.HL^.ChangedAttr:=TRUE; end; end; OptionsChanged:=TRUE; modal_result:=mrOK; Close; end; //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.btnCancelClick(Sender: TObject); begin modal_result:=mrCancel; Close; end; //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.btnEditClick(Sender: TObject); var s :string; Item :TItem; begin if (lbHL.ItemIndex=-1) then EXIT; s:=lbHL.Items[lbHL.ItemIndex]; s:=Copy(s,Pos(#09,s)+1,Length(s)); Item:=TItem(lbHL.Items.Objects[lbHL.ItemIndex]); if InputQuery(mlStr(ML_CUSTTYP_EXT_EDIT_CAPTION,'Extension edit')+' - '+Item.HL^.Name, mlStr(ML_CUSTTYP_EXT_EDIT_TEXT,'Enter extensions separated with commas')+':',s) then begin lbHL.Items[lbHL.ItemIndex]:=Item.HL^.Name+#09+s; Item.Modified:=TRUE; end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // OnDraw //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.lbHLDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var name :string; ext :string; s :string; begin s:=lbHL.Items[Index]; name:=Copy(s,1,Pos(#09,s)-1); ext:=Copy(s,Pos(#09,s)+1,Length(s)); with TListBox(Control).Canvas do begin FillRect(Rect); if (odSelected in State) then Font.Color:=clHighLightText; TextOut(4, Rect.top, name); TextOut(TabPos1+2, Rect.top, ext); end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Form events //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.FormShow(Sender: TObject); begin mlApplyLanguageToForm(SELF, Name); TabPos1:=Round(lbHL.Width*COL1_WIDTH_FACTOR); lbHL.ItemHeight:=fmMain.DefaultlbItemHeight; RefreshList; end; //------------------------------------------------------------------------------------------ procedure TfmCustomizeType.FormDestroy(Sender: TObject); begin Clear; end; //------------------------------------------------------------------------------------------ end.
unit ControllerObjectCommandItem; interface uses ControllerDataTypes; type TControllerObjectCommandItem = class public Command: longint; Params: TCommandParams; // Constructors and Destructors constructor Create; overload; constructor Create(_Command: longint; var _Params: TCommandParams); overload; destructor Destroy; override; end; implementation constructor TControllerObjectCommandItem.Create; begin Params := nil; Command := 0; end; constructor TControllerObjectCommandItem.Create(_Command: longint; var _Params: TCommandParams); begin Params := _Params; Command := _Command; end; destructor TControllerObjectCommandItem.Destroy; begin if Params <> nil then begin Params.Free; end; inherited Destroy; end; end.
unit AlimonyCtrl_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxDropDownEdit, cxCalendar, cxSpinEdit, cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls, cxControls, cxGroupBox, cxButtonEdit, Kernel, Unit_ZGlobal_Consts, IBase, PackageLoad, FIBQuery, pFIBQuery,ZTypes, pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, ZMessages, ActnList, AlimonyCtrl_DM, zProc; type TFAlimonyControl = class(TForm) IdentificationBox: TcxGroupBox; PeopleLabel: TcxLabel; OptionsBox: TcxGroupBox; Bevel2: TBevel; MaxPercentLabel: TcxLabel; PercentLabel: TcxLabel; PochtaPercentLabel: TcxLabel; PochtaPercentEdit: TcxMaskEdit; PeriodBox: TcxGroupBox; DateEnd: TcxDateEdit; DateBeg: TcxDateEdit; DateBegLabel: TcxLabel; DateEndLabel: TcxLabel; YesBtn: TcxButton; CancelBtn: TcxButton; maxPercentEdit: TcxMaskEdit; PercentEdit: TcxMaskEdit; SendBox: TcxGroupBox; Bevel3: TBevel; SendPeopleLabel: TcxLabel; SendAdressLabel: TcxLabel; SendPeopleEdit: TcxMaskEdit; SendAdressEdit: TcxMaskEdit; PeopleEdit: TcxButtonEdit; DolgEdit: TcxMaskEdit; Bevel4: TBevel; DolgLabel: TcxLabel; DocumentEdit: TcxMaskEdit; DocumentLabel: TcxLabel; Bevel1: TBevel; ActionList1: TActionList; Action1: TAction; Action2: TAction; procedure CancelBtnClick(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Action2Execute(Sender: TObject); private PParameter:TZAlimonyParameters; DM:TDM_Ctrl; PLanguageIndex:byte; public constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AParameter:TZAlimonyParameters);reintroduce; property Parameter:TZAlimonyParameters read PParameter; end; implementation {$R *.dfm} constructor TFAlimonyControl.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AParameter:TZAlimonyParameters); var RecInfo:RECORD_INFO_STRUCTURE; DecimalSeparator:string; begin inherited Create(AOwner); PParameter:=AParameter; PLanguageIndex:=LanguageIndex; //****************************************************************************** PeopleLabel.Caption:=LabelMan_Caption[PLanguageIndex]; DocumentLabel.Caption:=LabelDocument_Caption[PLanguageIndex]; MaxPercentLabel.Caption:=LabelMaxPercent_Caption[PLanguageIndex]; PercentLabel.Caption:=LabelPercent_Caption[PLanguageIndex]; PochtaPercentLabel.Caption:=LabelPochtaPercent_Caption[PLanguageIndex]; DateBegLabel.Caption:=LabelDateBeg_Caption[PLanguageIndex]; DateEndLabel.Caption:=LabelDateEnd_Caption[PLanguageIndex]; SendPeopleLabel.Caption:=LabelSender_Caption[PLanguageIndex]; SendAdressLabel.Caption:=LabelAdress_Caption[PLanguageIndex]; DolgLabel.Caption:=LabelDolg_Caption[PLanguageIndex]; YesBtn.Caption:=YesBtn_Caption[PLanguageIndex]; //****************************************************************************** //100,00 | \d\d? ([,]\d\d?)? DecimalSeparator := ZSystemDecimalSeparator; DolgEdit.Properties.EditMask := '\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+DecimalSeparator+']\d\d?)?'; maxPercentEdit.Properties.EditMask := '(100 (['+DecimalSeparator+']00?)?) | (\d\d? (['+DecimalSeparator+']\d\d?)?)'; PercentEdit.Properties.EditMask := '(100 (['+DecimalSeparator+']00?)?) | (\d\d? (['+DecimalSeparator+']\d\d?)?)'; PochtaPercentEdit.Properties.EditMask := '(100 (['+DecimalSeparator+']00?)?) | (\d\d? (['+DecimalSeparator+']\d\d?)?)'; //****************************************************************************** DM:=TDM_Ctrl.Create(self,ADB_HANDLE,PParameter); DM.DSetData.Open; case PParameter.ControlFormStyle of zcfsInsert: begin Caption:=ZAlimonyCtrl_Caption_Insert[PLanguageIndex]; IdentificationBox.Enabled := False; PeopleEdit.Text := VarToStr(dm.DSetData['TN'])+' - '+VarToStr(DM.DSetData['FIO']); DateBeg.Date := VarToDateTime(DM.DSetData['DATE_BEG']); DateEnd.Date := VarToDateTime(DM.DSetData['DATE_END']); CancelBtn.Caption:= CancelBtn_Caption[PLanguageIndex]; end; zcfsUpdate: begin with DM do try StoredProc.Transaction.StartTransaction; RecInfo.TRHANDLE :=WriteTransaction.Handle; RecInfo.DBHANDLE :=DB.Handle; RecInfo.ID_RECORD :=VarArrayOf([PParameter.ID]); RecInfo.PK_FIELD_NAME :=VarArrayOf(['ID_ALIMONY']); RecInfo.TABLE_NAME :='Z_ALIMONY'; RecInfo.RAISE_FLAG :=True; LockRecord(@RecInfo); except on E:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; PParameter.ID := -1; Exit; end; end; Caption:=ZAlimonyCtrl_Caption_Update[PLanguageIndex]; IdentificationBox.Enabled := False; PeopleEdit.Text := VarToStr(dm.DSetData['TN'])+' - '+VarToStr(DM.DSetData['FIO']); DateBeg.Date := VarToDateTime(DM.DSetData['DATE_BEG']); DateEnd.Date := VarToDateTime(DM.DSetData['DATE_END']); DocumentEdit.Text := VarToStr(DM.DSetData['DOCUMENT']); DolgEdit.Text := VarToStr(DM.DSetData['SUMMA_DOLG']); maxPercentEdit.Text := VarToStr(DM.DSetData['MAX_PERCENT']); PercentEdit.Text := VarToStr(DM.DSetData['PERCENT']); PochtaPercentEdit.Text := VarToStr(DM.DSetData['POCHTA_PERCENT']); SendPeopleEdit.Text := VarToStr(DM.DSetData['SEND_PEOPLE']); SendAdressEdit.Text := VarToStr(DM.DSetData['SEND_ADRESS']); CancelBtn.Caption:= CancelBtn_Caption[PLanguageIndex]; end; zcfsShowDetails: begin Caption:=ZAlimonyCtrl_Caption_Detail[PLanguageIndex]; IdentificationBox.Enabled:=False; OptionsBox.Enabled:=False; PeriodBox.Enabled:=False; SendBox.Enabled:=False; YesBtn.Visible:=False; PeopleEdit.Text := VarToStr(dm.DSetData['TN'])+' - '+VarToStr(DM.DSetData['FIO']); DateBeg.Date := VarToDateTime(DM.DSetData['DATE_BEG']); DateEnd.Date := VarToDateTime(DM.DSetData['DATE_END']); DocumentEdit.Text := VarToStr(DM.DSetData['DOCUMENT']); DolgEdit.Text := VarToStr(DM.DSetData['SUMMA_DOLG']); maxPercentEdit.Text := VarToStr(DM.DSetData['MAX_PERCENT']); PercentEdit.Text := VarToStr(DM.DSetData['PERCENT']); PochtaPercentEdit.Text := VarToStr(DM.DSetData['POCHTA_PERCENT']); SendPeopleEdit.Text := VarToStr(DM.DSetData['SEND_PEOPLE']); SendAdressEdit.Text := VarToStr(DM.DSetData['SEND_ADRESS']); CancelBtn.Caption:= ExitBtn_Caption[PLanguageIndex]; end; end; YesBtn.Hint := YesBtn.Caption; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; end; procedure TFAlimonyControl.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFAlimonyControl.Action1Execute(Sender: TObject); var TId:Integer; begin if DocumentEdit.Text = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputDocument_Error_Text[PLanguageIndex],mtWarning,[mbOk]); DocumentEdit.SetFocus; exit; end; if DolgEdit.Text = '' then begin DolgEdit.Text := '0'; { ZShowMessage(Error_Caption[PLanguageIndex],ZeInputDolg_Error_Text[PLanguageIndex],mtWarning,[mbOk]); DolgEdit.SetFocus; Exit;} end; If maxPercentEdit.Text = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputMaxPercent_Error_Text[PLanguageIndex],mtWarning,[mbOk]); maxPercentEdit.SetFocus; Exit; end; if PercentEdit.Text = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputPercent_Error_Text[PLanguageIndex],mtWarning,[mbOk]); PercentEdit.SetFocus; Exit; end; if PochtaPercentEdit.Text = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputPochtaPercent_Error_Text[PLanguageIndex],mtWarning,[mbOk]); PochtaPercentEdit.SetFocus; Exit; end; if DateBeg.Date > DateEnd.Date then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOk]); DateBeg.SetFocus; Exit; end; if SendPeopleEdit.Text = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputSender_Error_Text[PLanguageIndex],mtWarning,[mbOk]); SendPeopleEdit.SetFocus; Exit; end; if SendAdressEdit.Text = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputAddress_Error_Text[PLanguageIndex],mtWarning,[mbOk]); SendAdressEdit.SetFocus; Exit; end; if StrToFloat(PercentEdit.Text)>StrToFloat(maxPercentEdit.Text) then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputPercents_Error_Text[PLanguageIndex],mtWarning,[mbOK]); PercentEdit.SetFocus; Exit; end; if StrToFloat(PochtaPercentEdit.Text)>StrToFloat(PercentEdit.Text) then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputPercents_Error_Text[PLanguageIndex],mtWarning,[mbOk]); PochtaPercentEdit.SetFocus; Exit; end; case PParameter.ControlFormStyle of zcfsInsert: with DM do try StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_ALIMONY_INSERT'; StoredProc.Prepare; StoredProc.ParamByName('ID_MAN').AsInteger := PParameter.ID; StoredProc.ParamByName('SUMMA_DOLG').AsExtended := StrToFloat(DolgEdit.Text); StoredProc.ParamByName('DATE_BEG').AsDate := DateBeg.Date; StoredProc.ParamByName('DATE_END').AsDate := DateEnd.Date; StoredProc.ParamByName('PERCENT').AsFloat := StrToFloat(PercentEdit.Text); StoredProc.ParamByName('MAX_PERCENT').AsFloat := StrToFloat(maxPercentEdit.Text); StoredProc.ParamByName('POCHTA_PERCENT').AsFloat:= StrToFloat(PochtaPercentEdit.Text); StoredProc.ParamByName('DOCUMENT').AsString := DocumentEdit.Text; StoredProc.ParamByName('SEND_PEOPLE').AsString := SendPeopleEdit.Text; StoredProc.ParamByName('SEND_ADRESS').AsString := SendAdressEdit.Text; StoredProc.ExecProc; TID := StoredProc.ParamByName('ID_ALIMONY').AsInteger; StoredProc.Transaction.Commit; PParameter.ID := TId; ModalResult:=mrYes; except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; end end; zcfsUpdate: with DM do try StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_ALIMONY_UPDATE'; StoredProc.Prepare; StoredProc.ParamByName('ID_ALIMONY').AsInteger := PParameter.ID; StoredProc.ParamByName('ID_MAN').AsInteger := DSetData.FieldValues['ID_MAN']; StoredProc.ParamByName('SUMMA_DOLG').AsExtended := StrToFloat(DolgEdit.Text); StoredProc.ParamByName('DATE_BEG').AsDate := DateBeg.Date; StoredProc.ParamByName('DATE_END').AsDate := DateEnd.Date; StoredProc.ParamByName('PERCENT').AsFloat := StrToFloat(PercentEdit.Text); StoredProc.ParamByName('MAX_PERCENT').AsFloat := StrToFloat(maxPercentEdit.Text); StoredProc.ParamByName('POCHTA_PERCENT').AsFloat:= StrToFloat(PochtaPercentEdit.Text); StoredProc.ParamByName('DOCUMENT').AsString := DocumentEdit.Text; StoredProc.ParamByName('SEND_PEOPLE').AsString := SendPeopleEdit.Text; StoredProc.ParamByName('SEND_ADRESS').AsString := SendAdressEdit.Text; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult:=mrYes; except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; end end; end; end; procedure TFAlimonyControl.FormCreate(Sender: TObject); var RecInfo:RECORD_INFO_STRUCTURE; begin if PParameter.ControlFormStyle=zcfsDelete then begin with DM do try StoredProc.Transaction.StartTransaction; RecInfo.TRHANDLE :=WriteTransaction.Handle; RecInfo.DBHANDLE :=DB.Handle; RecInfo.ID_RECORD :=VarArrayOf([PParameter.ID]); RecInfo.PK_FIELD_NAME :=VarArrayOf(['ID_ALIMONY']); RecInfo.TABLE_NAME :='Z_ALIMONY'; RecInfo.RAISE_FLAG :=True; LockRecord(@RecInfo); if ZShowMessage(ZAlimonyCtrl_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then begin StoredProc.StoredProcName := 'Z_ALIMONY_DELETE'; StoredProc.Prepare; StoredProc.ParamByName('ID_ALIMONY').AsInteger := PParameter.ID; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult:=mrYes; PParameter.ID:=-1; end else begin PParameter.ID := -1; StoredProc.Transaction.Rollback; ModalResult:=mrCancel; end; except on E:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; PParameter.ID := -1; ModalResult:=mrCancel; end; end; end; end; procedure TFAlimonyControl.FormDestroy(Sender: TObject); begin if DM<>nil then DM.Destroy; end; procedure TFAlimonyControl.Action2Execute(Sender: TObject); begin SendKeyDown(Self.ActiveControl,VK_TAB,[]); end; end.
unit MSysUtils; interface uses Windows, Messages, MCommCtrl; function StringReplace(S, Old, New : String; ReplaceAll : Bool) : String; function LoadStr(I : Integer) : String; function IntToStr(I : Integer) : String; function StrToInt(S : String) : Integer; function FileExists(FileName : String) : Boolean; function ExtractFilePath(FileName : String) : String; function Format(FmtStr : String; Params : Array of const) : String; function CenterWindow(hWindow : THandle) : Boolean; function StrAlloc(Size : Cardinal) : PChar; function StrLCopy(Dest, Source : PChar; MaxLen : Cardinal) : PChar; assembler; function IntToHex(ACard : Cardinal; ADigits : Byte) : String; function StrDispose(Str : PChar) : Integer; function Edit_GetText(hEdit : THandle) : String; function ListBox_GetText(hBox : THandle) : String; function SysIP32_GetBlank(hSysIP : THandle) : Boolean; function SysIP32_GetText(hSysIP : THandle) : String; function SysIP32_SetText(hSysIP : THandle; Value : String) : Boolean; function FormatTime(st : TSystemTime) : String; function FormatDate : String; function AllocMem(Size : Integer) : Pointer; function ProcessMessages(hWnd : DWORD) : Boolean; function HideTaskBarButton(hWnd : HWND) : Boolean; function SysErrorMessage(ErrorCode : Integer) : String; function Cmbx_GetText(hCmbx : THandle) : String; implementation function StringReplace(S, Old, New : String; ReplaceAll : Bool) : String; var Position : Integer; Len : Integer; begin Len := Length(Old); while TRUE do begin Position := Pos(Old, S); if Position <> 0 then begin Delete(S, Position, Len); Insert(New, S, Position); end else Break; if ReplaceAll = FALSE then Break; end; Result := S; end; function LoadStr(I : Integer) : String; var Buffer : Array [0..255] of Char; begin LoadString(hInstance, I, Buffer, SizeOf(Buffer)); Result := String(Buffer); end; function IntToStr(I : Integer) : String; begin Str(I, Result); end; function StrToInt(S : String) : Integer; var I : Integer; begin Val(S, Result, I); end; function FileExists(FileName : String) : Boolean; var Attributes : Cardinal; begin Attributes := GetFileAttributes(Pointer(Filename)); Result := (Attributes <> $FFFFFFFF) and (Attributes and FILE_ATTRIBUTE_DIRECTORY = 0); end; function ExtractFilePath(FileName : String) : String; var I : Integer; begin Result := ''; I := Length(FileName); while(i > 0) do begin if(FileName[I] = ':') or (FileName[I] = '\') then begin Result := Copy(FileName, 1, I); Break; end; Dec(I); end; end; function Format(FmtStr : String; Params : Array of const) : String; var PDW1 : PDWORD; PDW2 : PDWORD; I : Integer; PC : PChar; begin PDW1 := nil; if Length(Params) > 0 then GetMem(PDW1, Length(Params) * SizeOf(Pointer)); PDW2 := PDW1; for I := 0 to High(Params) do begin PDW2^ := DWORD(PDWORD(@Params[I])^); Inc(PDW2); end; GetMem(PC, 1024 - 1); try SetString(Result, PC, wvsprintf(PC, PChar(FmtStr), PChar(PDW1))); except Result := ''; end; if (PDW1 <> nil) then FreeMem(PDW1); if (PC <> nil) then FreeMem(PC); end; function CenterWindow(hWindow : THandle) : Boolean; var WndRect : TRect; iWidth : Integer; iHeight : Integer; begin GetWindowRect(hWindow, WndRect); iWidth := WndRect.Right - WndRect.Left; iHeight := WndRect.Bottom - WndRect.Top; WndRect.Left := (GetSystemMetrics(SM_CXSCREEN) - iWidth) div 2; WndRect.Top := (GetSystemMetrics(SM_CYSCREEN) - iHeight) div 2; MoveWindow(hWindow, WndRect.Left, WndRect.Top, iWidth, iHeight, FALSE); Result := TRUE; end; function StrAlloc(Size : Cardinal) : PChar; begin Inc(Size, SizeOf(Cardinal)); GetMem(Result, Size); Cardinal(Pointer(Result)^) := Size; Inc(Result, SizeOf(Cardinal)); end; function StrLCopy(Dest, Source : PChar; MaxLen : Cardinal) : PChar; assembler; asm PUSH EDI PUSH ESI PUSH EBX MOV ESI,EAX MOV EDI,EDX MOV EBX,ECX XOR AL,AL TEST ECX,ECX JZ @@1 REPNE SCASB JNE @@1 INC ECX @@1: SUB EBX,ECX MOV EDI,ESI MOV ESI,EDX MOV EDX,EDI MOV ECX,EBX SHR ECX,2 REP MOVSD MOV ECX,EBX AND ECX,3 REP MOVSB STOSB MOV EAX,EDX POP EBX POP ESI POP EDI end; function IntToHex(ACard : Cardinal; ADigits : Byte) : String; const HexArray : array[0..15] of Char = ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ); var LHex : String; LInt : DWORD; LHInt : DWORD; begin LHex := StringOfChar('0', ADigits); LInt := ADigits; LHInt := 16; while ACard > 0 do begin LHex[LInt] := HexArray[(ACard mod LHint) mod 16]; ACard := ACard div 16; LHInt := LHInt * 16; if LHInt = 0 then LHInt := $FFFFFFFF; Dec(LInt); end; Result := LHex; end; function StrDispose(Str : PChar) : Integer; begin if Str <> nil then begin Dec(Str, SizeOf(Cardinal)); FreeMem(Str, Cardinal(Pointer(Str)^)); end; end; function Edit_GetText(hEdit : THandle) : String; var Buffer : Array [0..255] of Char; begin ZeroMemory(@Buffer, Length(Buffer)); SendMessage(hEdit, WM_GETTEXT, SizeOf(Buffer), Integer(@Buffer)); Result := String(Buffer); end; function ListBox_GetText(hBox : THandle) : String; var I : Integer; L : Integer; S : String; P : PChar; begin I := SendMessage(hBox, LB_GETCURSEL, 0, 0); L := SendMessage(hBox, LB_GETTEXTLEN, wParam(I), 0); GetMem(P, L + 1); SendMessage(hBox, LB_GETTEXT, wParam(I), lParam(P)); SetString(S, P, L); FreeMem(P); Result := S; end; function SysIP32_GetBlank(hSysIP : THandle) : Boolean; begin Result := Bool(SendMessage(hSysIP, IPM_ISBLANK, 0, 0)); end; function SysIP32_GetText(hSysIP : THandle) : String; var D : DWORD; S : String; begin SendMessage(hSysIP, IPM_GETADDRESS, 0, Integer(@D)); S := Format('%d.%d.%d.%d', [FIRST_IPADDRESS(D), SECOND_IPADDRESS(D), THIRD_IPADDRESS(D), FOURTH_IPADDRESS(D)]); Result := S; end; function SysIP32_SetText(hSysIP : THandle; Value : String) : Boolean; var I : Integer; D : Integer; IP : DWORD; P : DWORD; begin IP := 0; try I := 0; repeat D := Pos('.', Value); if D <= 1 then if I < 3 then Break else P := StrToInt(Value) else P := StrToInt(Copy(Value, 1, D - 1)); if P > 255 then Break; Delete(Value, 1, D); IP := (IP shl 8) or P; Inc(I); until I > 3; except end; SendMessage(hSysIP, IPM_SETADDRESS, 0, IP); Result := TRUE; end; function FormatTime(st : TSystemTime) : String; var lpBuf : Array [0..MAX_PATH] of Char; begin ZeroMemory(@lpBuf, SizeOf(lpBuf)); if (GetTimeFormat(LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, @st, nil, lpBuf, SizeOf(lpBuf)) = 0) then lstrcpy(lpBuf, PChar(Format('%.2d:%.2d:%.2d', [st.wHour, st.wMinute, st.wSecond]))); Result := lpBuf; end; function FormatDate : String; var st : TSystemTime; lpBuf : Array [0..MAX_PATH] of Char; begin ZeroMemory(@lpBuf, SizeOf(lpBuf)); if (GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, nil, nil, lpBuf, SizeOf(lpBuf)) = 0) then begin GetLocalTime(st); lstrcpy(lpBuf, PChar(Format('%.4d-%.2d-%.2d', [st.wYear, st.wMonth, st.wDay]))); end; Result := lpBuf; end; function AllocMem(Size : Integer) : Pointer; asm TEST EAX, EAX JZ @@exit PUSH EAX CALL System.@GetMem POP EDX PUSH EAX MOV CL, 0 CALL System.@FillChar POP EAX @@exit : end; function ProcessMessages(hWnd : DWORD) : Boolean; var Msg : TMsg; begin while PeekMessage(Msg, hWnd, 0, 0, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; Result := TRUE; end; function HideTaskBarButton(hWnd : HWND) : Boolean; var Wnd : THandle; begin Wnd := CreateWindow('STATIC', #0, WS_POPUP, 0, 0, 0, 0, 0, 0, 0, nil); ShowWindow(hWnd, SW_HIDE); SetWindowLong(hWnd, GWL_HWNDPARENT, Wnd); ShowWindow(hWnd, SW_SHOW); Result := TRUE; end; function SysErrorMessage(ErrorCode : Integer) : String; var LenMsg : Integer; Buffer : Array [0..255] of Char; begin LenMsg := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ARGUMENT_ARRAY, nil, ErrorCode, 0, Buffer, SizeOf(Buffer), nil); while (LenMsg > 0) and (Buffer[LenMsg - 1] in [#0..#32, '.']) do Dec(LenMsg); SetString(Result, Buffer, LenMsg); end; function Cmbx_GetText(hCmbx : THandle) : String; var Idx : Integer; Len : Integer; S : string; Buffer : PChar; begin Idx := SendMessage(hCmbx, CB_GETCURSEL, 0, 0); Len := SendMessage(hCmbx, CB_GETLBTEXTLEN, wParam(Idx), 0); GetMem(Buffer, Len + 1); SendMessage(hCmbx, CB_GETLBTEXT, wParam(Idx), lParam(Buffer)); SetString(S, Buffer, Len); FreeMem(Buffer); Result := S; end; end.
unit KFItemEntity; interface uses Windows, Classes, Dialogs, Forms, Controls, SysUtils, KFFile, KFWksp, UFuncoes, IOUtils, ItemProgress; type TApplicationType = (atCmd, atGUI); TKFServerProfile = class(TObject) private public var DefaultDifficulty: Integer; DefaultLength: Integer; DefaultGameMode: Integer; DefaultPass: string; AdditionalParam: string; DefaultMap: string; ProfileName: string; constructor Create; destructor Destroy; override; end; TAppProgress = class(TObject) private var frmPB: TformPB; public var constructor Create(appProgressType: TApplicationType); destructor Destroy; override; end; TKFItem = class(TObject) private public var FileName: string; ID: string; ServerSubscribe: Boolean; MapEntry: Boolean; MapCycleEntry: Boolean; ServerCache: Boolean; ItemType: TKFItemType; constructor Create; destructor Destroy; override; end; TKFItems = class(TObject) private var kfWebIniSubPath: string; kfGameIniSubPath: string; kfEngineIniSubPath: string; kfApplicationPath: string; KFServerPathEXE: string; procedure CheckIfTheServerIsRunning; function GetIDIndex(ID: string): Integer; function GetModName(files: TStringList): string; public var Items: array of TKFItem; appType: TApplicationType; constructor Create; destructor Destroy; override; function NewItem(ID: String; Name: String; WorkshopSubscribe: Boolean; DownloadNow: Boolean; MapCycle: Boolean; MapEntry: Boolean): Boolean; function RemoveItem(ItemName: string; itemID: string; rmvMapEntry, rmvMapCycle, rmvSubcribe, rmvCache: Boolean): Boolean; function LoadItems(): Boolean; function GetGameCycle(): TStringList; function CreateBlankACFFile: Boolean; procedure SetKFWebIniSubPath(path: string); procedure SetKFGameIniSubPath(path: string); procedure SetkKFngineIniSubPath(path: string); procedure SetKFApplicationPath(path: string); function GetKFApplicationPath(): string; function ForceUpdate(itemID: String; IsMod: Boolean): Boolean; function InstallWorkshopManager: Boolean; function IsWorkshopManagerInstalled: Boolean; function RemoveWorkshopManager: Boolean; function AddWorkshopSubcribe(ID: String): Boolean; function DownloadWorkshopItem(ID: String): Boolean; function GetMapName(ID: string): string; function AddMapCycle(name: String): Boolean; function AddMapEntry(name: String): Boolean; procedure SetWebStatus(Status: Boolean); function GetWebStatus(): Boolean; procedure SetWebPort(Port: Integer); function GetWebPort(): Integer; procedure GetKFServerPathEXE(path: string); procedure SetKFServerPathEXE(path: string); end; implementation uses Main; { KFMap } constructor TKFItem.Create; begin end; destructor TKFItem.Destroy; begin inherited; end; { KFMaps } function TKFItems.AddWorkshopSubcribe(ID: String): Boolean; var egIni: TKFEngineIni; begin result := False; egIni := TKFEngineIni.Create; try if egIni.LoadFile(kfApplicationPath + kfEngineIniSubPath) then begin result := egIni.AddWorkshopItem(ID); egIni.SaveFile(kfApplicationPath + kfEngineIniSubPath); end; finally egIni.Free; end; end; function TKFItems.DownloadWorkshopItem(ID: String): Boolean; var wksp: TKFWorkshop; ItemDownloaded: Boolean; ItemInCache: Boolean; begin result := False; wksp := TKFWorkshop.Create(kfApplicationPath); try wksp.RemoveAcfReference(ID, True); ItemDownloaded := wksp.DownloadWorkshopItem(ID); ItemInCache := wksp.CopyItemToCache(ID); result := ItemDownloaded and ItemInCache; finally wksp.Free end; end; function TKFItems.CreateBlankACFFile(): Boolean; var wksp: TKFWorkshop; begin result := False; wksp := TKFWorkshop.Create(kfApplicationPath); try result := wksp.CreateBlankACFFile; finally wksp.Free end; end; function TKFItems.GetMapName(ID: string): string; var wksp: TKFWorkshop; begin result := ''; wksp := TKFWorkshop.Create(kfApplicationPath); try result := wksp.GetMapName(kfApplicationPath + wksp.CServeCacheFolder + ID, False); finally wksp.Free end; end; function TKFItems.AddMapCycle(name: String): Boolean; var gmIni: TKFGameIni; begin result := False; gmIni := TKFGameIni.Create; try if gmIni.LoadFile(kfApplicationPath + kfGameIniSubPath) then begin if gmIni.AddMapCycle(Name) then gmIni.SaveFile(kfApplicationPath + kfGameIniSubPath); end; finally gmIni.Free; end; end; function TKFItems.AddMapEntry(name: String): Boolean; var gmIni: TKFGameIni; begin result := False; gmIni := TKFGameIni.Create; try if gmIni.LoadFile(kfApplicationPath + kfGameIniSubPath) then begin if gmIni.AddMapEntry(name) then gmIni.SaveFile(kfApplicationPath + kfGameIniSubPath); end; finally gmIni.Free; end; end; function TKFItems.NewItem(ID: String; Name: String; WorkshopSubscribe: Boolean; DownloadNow: Boolean; MapCycle: Boolean; MapEntry: Boolean): Boolean; var ItemDownloaded: Boolean; AddedMapEntry: Boolean; AddedMapCycle: Boolean; AddedWkspSub: Boolean; progress: TformPB; begin CheckIfTheServerIsRunning; result := False; AddedMapEntry := False; AddedMapCycle := False; AddedWkspSub := False; progress := TformPB.Create(FormMain); try progress.SetPBMax(4); progress.SetPBValue(0); progress.Show; if (ID <> '') or (Name <> '') then begin try // AddWorkshopSubcribe if WorkshopSubscribe then begin progress.NextPBValue('Adding workshop subcribe...'); AddedWkspSub := AddWorkshopSubcribe(ID); end; // Download workshop Item if DownloadNow and (ID <> '') then begin progress.NextPBValue('Downloading workshop item, please wait...'); ItemDownloaded := DownloadWorkshopItem(ID); if ItemDownloaded then Name := GetMapName(ID); end; // MapCycle and Map Entry if (Name <> '') then begin if MapEntry then begin progress.NextPBValue('Adding map entry..'); AddedMapEntry := AddMapEntry(Name); end; if MapCycle then begin AddedMapCycle := AddMapCycle(Name); progress.NextPBValue('Adding map cycle..'); end; end; progress.SetPBValue(0); progress.UpdateStatus('Done'); progress.SetPBValue(0); result := True; Application.ProcessMessages; Sleep(100); progress.Close; except on E: Exception do begin raise Exception.Create('Exception Adding item: ' + E.Message); result := False; end; end; end else begin // No id passed raise Exception.Create('No id or name passed'); result := False; end; finally progress.Free; end; end; constructor TKFItems.Create; begin SetLength(Items, 0); end; destructor TKFItems.Destroy; var i: Integer; begin try for i := 0 to High(Items) do FreeAndNil(Items[i]); except end; inherited; end; function TKFItems.LoadItems: Boolean; var directorys: TStringList; files: TStringList; fileExt: string; ItemFolder: string; I, y: Integer; aItem: TKFItem; ItemName: String; egIniLoaded, gmIniLoaded: Boolean; egIni: TKFEngineIni; gmIni: TKFGameIni; wkspID: string; FileType: TKFItemType; begin // Directoy result := False; directorys := ListDir(kfApplicationPath + TKFWorkshop.CServeCacheFolder); egIni := TKFEngineIni.Create; gmIni := TKFGameIni.Create; try egIniLoaded := egIni.LoadFile(kfApplicationPath + kfEngineIniSubPath); gmIniLoaded := gmIni.LoadFile(kfApplicationPath + kfGameIniSubPath); for I := 0 to High(Items) do Items[I].Free; SetLength(Items, 0); if (gmIniLoaded = False) or (egIniLoaded = False) then begin raise Exception.Create( 'Falied to load PCServer-KFGame and PCServer-KFEngine. ' + #13 + 'Check if the app is in the server folder and if you ran the server at least once'); end; for I := 0 to directorys.Count - 1 do begin try ItemFolder := kfApplicationPath + TKFWorkshop.CServeCacheFolder + directorys[I] + '\'; files := GetAllFilesSubDirectory(ItemFolder, '*.*'); try FileType := KFUnknowed; if (files.Count > 0) then begin // Check folder type for y := 0 to files.Count - 1 do begin ItemName := ExtractFileName(files[y]); fileExt := UpperCase(ExtractFileExt(ItemName)); if (Pos('KF', UpperCase(ItemName)) = 1) and (fileExt = '.KFM') then begin FileType := KFMap; Break; end; if (fileExt = '.U') or (fileExt = '.UC') then begin FileType := KFmod; end; end; if FileType <> KFUnknowed then begin aItem := TKFItem.Create; aItem.ItemType := FileType; if FileType = KFmod then aItem.FileName := GetModName(files) else aItem.FileName := TPath.GetFileNameWithoutExtension(ItemName); aItem.ID := directorys[I]; aItem.ServerSubscribe := egIni.GetWorkshopItemIndex (directorys[I]) >= 0; aItem.MapCycleEntry := gmIni.GetMapCycleIndex (TPath.GetFileNameWithoutExtension(ItemName)) >= 0; aItem.MapEntry := gmIni.GetMapEntryIndex (TPath.GetFileNameWithoutExtension(ItemName)) > 0; aItem.ServerCache := True; SetLength(Items, Length(Items) + 1); Items[ High(Items)] := aItem; directorys.Objects[I] := files; end; end; finally files.Free; end; except ShowMessage('Error loading folder: ' + directorys[I] + ' of number ' + IntToStr(I) + '. Check this folder or delete.'); end; end; // Workshop subscribe for I := 0 to egIni.GetWorkshopSubcribeCount - 1 do begin wkspID := egIni.GetWorkshopSubcribeID(I); if (GetIDIndex(wkspID) < 0) and (wkspID <> '') then begin aItem := TKFItem.Create; aItem.ID := wkspID; aItem.ServerSubscribe := True; aItem.MapEntry := False; aItem.ServerCache := False; aItem.MapCycleEntry := False; aItem.ItemType := KFUnknowed; aItem.FileName := '???'; SetLength(Items, Length(Items) + 1); Items[ High(Items)] := aItem; end; result := True; end; finally egIni.Free; gmIni.Free; directorys.Free; end; end; function TKFItems.GetModName(files: TStringList): string; var I: Integer; begin for I := 0 to files.Count do begin if LowerCase(ExtractFileExt(files[I])) = '.u' then begin result := TPath.GetFileNameWithoutExtension(files[I]); Exit; end else begin result := TPath.GetFileNameWithoutExtension(files[I]); end; end; end; function TKFItems.GetWebPort: Integer; var KFWeb: TKFWebIni; begin if FileExists(kfApplicationPath + kfWebIniSubPath) then begin KFWeb := TKFWebIni.Create; KFWeb.LoadFile(kfApplicationPath + kfWebIniSubPath); result := KFWeb.GetWebPort(); KFWeb.Free; end else begin raise Exception.Create('Invalid KFWeb Path (Not found in ' + kfApplicationPath + kfWebIniSubPath + ')'); end; end; function TKFItems.GetWebStatus: Boolean; var KFWeb: TKFWebIni; begin if FileExists(kfApplicationPath + kfWebIniSubPath) then begin KFWeb := TKFWebIni.Create; KFWeb.LoadFile(kfApplicationPath + kfWebIniSubPath); result := KFWeb.GetWebStatus(); KFWeb.Free; end else begin raise Exception.Create('Invalid KFWeb Path (Not found in ' + kfApplicationPath + kfWebIniSubPath + ')'); end; end; function TKFItems.GetIDIndex(ID: string): Integer; var I: Integer; begin result := -1; for I := 0 to High(Items) do begin if Items[I].ID = ID then begin result := I; Exit; end; end; end; function TKFItems.ForceUpdate(itemID: String; IsMod: Boolean): Boolean; var wksp: TKFWorkshop; progress: TformPB; begin CheckIfTheServerIsRunning; progress := TformPB.Create(FormMain); try progress.SetPBMax(2); progress.Show; wksp := TKFWorkshop.Create(kfApplicationPath); try progress.NextPBValue('Removing old references...'); wksp.RemoveAcfReference(itemID, True); progress.NextPBValue('Downloading Item...'); wksp.DownloadWorkshopItem(itemID); progress.NextPBValue('Copying the files to server cache...'); result := wksp.CopyItemToCache(itemID); finally wksp.Free; end; progress.Close; finally progress.Free; end; end; function TKFItems.GetGameCycle: TStringList; var gmIni: TKFGameIni; begin gmIni := TKFGameIni.Create; try if gmIni.LoadFile(kfApplicationPath + kfGameIniSubPath) then begin result := gmIni.GetMapCycleList; end else begin result := TStringList.Create; end; finally gmIni.Free; end; end; procedure TKFItems.CheckIfTheServerIsRunning; var warningText, serverRunning: string; cmdOp: String; begin warningText := 'You should close the server before make changes. ' + #13#10 + 'Do you wanna close it now?'; serverRunning := 'Server is running'; if ProcessExists(ExtractFileName(KFServerPathEXE)) then begin if appType = atCmd then begin Writeln(warningText); Writeln(' YES/NO'); Readln(cmdOp); if (LowerCase(cmdOp) = 'yes') or (LowerCase(cmdOp) = 'y') then KillProcessByName(ExtractFileName(FormMain.pathServerEXE)); end else begin if FormMain.appLanguage = 'BR' then begin warningText := 'Você precisa fechar o server antes de fazer alterações. ' + #13#10 + 'Fecha-lo agora??'; serverRunning := 'Server em execução'; end; if Application.MessageBox(PWideChar(warningText), PWideChar(serverRunning), MB_YESNO + MB_ICONWARNING) = IDYES then begin KillProcessByName(ExtractFileName(FormMain.pathServerEXE)); end; end; end; end; function TKFItems.RemoveItem(ItemName: string; itemID: string; rmvMapEntry, rmvMapCycle, rmvSubcribe, rmvCache: Boolean): Boolean; var egIni: TKFEngineIni; gmIni: TKFGameIni; wksp: TKFWorkshop; egIniLoaded, gmIniLoaded: Boolean; progress: TformPB; begin CheckIfTheServerIsRunning; progress := TformPB.Create(FormMain); Result := False; try progress.SetPBMax(1); progress.btncancel.Visible := False; if rmvMapEntry then progress.SetPBMax(progress.GetPBMax + 1); if rmvMapCycle then progress.SetPBMax(progress.GetPBMax + 1); if rmvSubcribe then progress.SetPBMax(progress.GetPBMax + 1); if rmvCache then progress.SetPBMax(progress.GetPBMax + 3); progress.SetPBValue(0); progress.Show; if rmvSubcribe then begin if itemID = '' then begin raise Exception.Create('No ID, unable to remove subscription'); end else begin egIni := TKFEngineIni.Create; try egIniLoaded := egIni.LoadFile(kfApplicationPath + kfEngineIniSubPath); progress.NextPBValue('Removing Server Subcribe'); if egIniLoaded then begin egIni.RemoveWorkshopItem(itemID, True); egIni.SaveFile(kfApplicationPath + kfEngineIniSubPath); end; finally egIni.Free; end; end; end; if rmvMapEntry or rmvMapCycle then begin if ItemName = '' then begin raise Exception.Create('No Map name, unable to remove'); end else begin gmIni := TKFGameIni.Create; try gmIniLoaded := gmIni.LoadFile(kfApplicationPath + kfGameIniSubPath); if rmvMapEntry and gmIniLoaded then begin progress.NextPBValue('Removing Map Entry'); gmIni.RemoveMapEntry(ItemName, True); end; if rmvMapCycle and gmIniLoaded then begin progress.NextPBValue('Removing Map Cycle'); gmIni.RemoveMapCycle(ItemName, True); end; gmIni.SaveFile(kfApplicationPath + kfGameIniSubPath); finally gmIni.Free end; end; end; if rmvCache then begin if itemID = '' then begin raise Exception.Create('No ID, unable to remove cache'); end else begin wksp := TKFWorkshop.Create(kfApplicationPath); try progress.NextPBValue('Removing ACF reference'); wksp.RemoveAcfReference(itemID, True); progress.NextPBValue('Deleting server cache'); wksp.RemoveServeItemCache(itemID); progress.NextPBValue('Deleting workshop cache'); wksp.RemoveWorkshoItemCache(itemID); finally wksp.Free; end; end; end; Sleep(100); progress.NextPBValue('Done'); Sleep(100); progress.Close; result := True; finally progress.Free; end; end; function TKFItems.IsWorkshopManagerInstalled(): Boolean; var egIni: TKFEngineIni; begin result := True; egIni := TKFEngineIni.Create; try if egIni.LoadFile(kfApplicationPath + kfEngineIniSubPath) then begin result := egIni.WorkshopRedirectInstalled; end; finally egIni.Free; end; end; function TKFItems.InstallWorkshopManager(): Boolean; var egIni: TKFEngineIni; begin result := False; egIni := TKFEngineIni.Create; try if egIni.LoadFile(kfApplicationPath + kfEngineIniSubPath) then begin egIni.AddWorkshopRedirect; result := egIni.SaveFile(kfApplicationPath + kfEngineIniSubPath); end; finally egIni.Free; end; end; function TKFItems.RemoveWorkshopManager(): Boolean; var egIni: TKFEngineIni; begin result := False; egIni := TKFEngineIni.Create; try if egIni.LoadFile(kfApplicationPath + kfEngineIniSubPath) then begin egIni.RemoveWorkshopRedirect; result := egIni.SaveFile(kfApplicationPath + kfEngineIniSubPath); end; finally egIni.Free; end; end; procedure TKFItems.SetKFApplicationPath(path: string); begin kfApplicationPath := path; end; function TKFItems.GetKFApplicationPath(): String; begin result := kfApplicationPath; end; procedure TKFItems.SetKFGameIniSubPath(path: string); begin kfGameIniSubPath := path; end; procedure TKFItems.SetkKFngineIniSubPath(path: string); begin kfEngineIniSubPath := path; end; procedure TKFItems.SetWebPort(Port: Integer); var KFWeb: TKFWebIni; begin if FileExists(kfApplicationPath + kfWebIniSubPath) then begin KFWeb := TKFWebIni.Create; KFWeb.LoadFile(kfApplicationPath + kfWebIniSubPath); KFWeb.SetWebPort(Port); KFWeb.SaveFile(kfApplicationPath + kfWebIniSubPath); KFWeb.Free; end else begin raise Exception.Create(' Invalid KFWeb Path (Not found in ' + kfApplicationPath + kfWebIniSubPath + ')'); end; end; procedure TKFItems.SetWebStatus(Status: Boolean); var KFWeb: TKFWebIni; begin if FileExists(kfApplicationPath + kfWebIniSubPath) then begin KFWeb := TKFWebIni.Create; KFWeb.LoadFile(kfApplicationPath + kfWebIniSubPath); KFWeb.SetWebStatus(Status); KFWeb.SaveFile(kfApplicationPath + kfWebIniSubPath); KFWeb.Free; end else begin raise Exception.Create(' Invalid KFWeb Path (Not found in ' + kfApplicationPath + kfWebIniSubPath + ')'); end; end; procedure TKFItems.SetKFServerPathEXE(path: string); begin KFServerPathEXE := path; end; procedure TKFItems.SetKFWebIniSubPath(path: string); begin kfWebIniSubPath := path; end; procedure TKFItems.GetKFServerPathEXE(path: string); begin KFServerPathEXE := path; end; { TAppProgress } constructor TAppProgress.Create(appProgressType: TApplicationType); begin if appProgressType = atCmd then begin end else begin end; end; destructor TAppProgress.Destroy; begin inherited; end; { TKFServerProfile } constructor TKFServerProfile.Create; begin end; destructor TKFServerProfile.Destroy; begin inherited; end; end.
unit ImageWin; interface uses Windows, Classes, Graphics, Forms, Controls, FileCtrl, StdCtrls, ExtCtrls, Buttons, Spin, ComCtrls, Dialogs; type TImageForm = class(TForm) DirectoryListBox1: TDirectoryListBox; DriveComboBox1 : TDriveComboBox; FileEdit : TEdit; Panel1 : TPanel; Image1 : TImage; FileListBox1 : TFileListBox; Bevel1 : TBevel; FilterComboBox1 : TFilterComboBox; Button1 : TButton; Button2 : TButton; Label1 : TLabel; procedure FileListBox1Click(Sender: TObject); procedure ViewBtnClick (Sender: TObject); procedure ViewAsGlyph (const FileExt: string); procedure GlyphCheckClick (Sender: TObject); procedure StretchCheckClick(Sender: TObject); procedure FileEditKeyPress (Sender: TObject; var Key: Char); procedure UpDownEditChange (Sender: TObject); procedure FormCreate (Sender: TObject); private FormCaption: string; end; var ImageForm: TImageForm; // MainForm.ImageName: String; implementation uses SysUtils, MAIN; //ViewWin, {$R *.dfm} procedure TImageForm.FileListBox1Click(Sender: TObject); var FileExt: string[4]; begin FileExt := AnsiUpperCase(ExtractFileExt(FileListBox1.Filename)); if (FileExt = '.BMP') or (FileExt = '.JPG') then begin Image1.Picture.LoadFromFile(FileListBox1.Filename); ImageName:= FileListBox1.Filename; Caption := FormCaption + ExtractFilename(FileListBox1.Filename); if (FileExt = '.BMP') or (FileExt = '.JPG')then begin Caption := Caption + Format(' (%d x %d)', [Image1.Picture.Width, Image1.Picture.Height]); // ViewForm.Image1.Picture := Image1.Picture; Button1.Enabled:=True; end; end else //Button1.Enabled:=False; end; procedure TImageForm.GlyphCheckClick(Sender: TObject); begin // ViewAsGlyph(AnsiUpperCase(ExtractFileExt(FileListBox1.Filename))); end; procedure TImageForm.ViewAsGlyph(const FileExt: string); begin // if GlyphCheck.Checked and (FileExt = '.BMP') then // begin // SpeedButton1.Glyph := Image1.Picture.Bitmap; // SpeedButton2.Glyph := Image1.Picture.Bitmap; // UpDown1.Position := SpeedButton1.NumGlyphs; // BitBtn1.Glyph := Image1.Picture.Bitmap; // BitBtn2.Glyph := Image1.Picture.Bitmap; // end /// else begin // SpeedButton1.Glyph := nil; // SpeedButton2.Glyph := nil; // BitBtn1.Glyph := nil; // BitBtn2.Glyph := nil; // end; // UpDown1.Enabled := GlyphCheck.Checked; // UpDownEdit.Enabled := GlyphCheck.Checked; // Label2.Enabled := GlyphCheck.Checked; end; procedure TImageForm.ViewBtnClick(Sender: TObject); begin //ViewForm.HorzScrollBar.Range := Image1.Picture.Width; // ViewForm.VertScrollBar.Range := Image1.Picture.Height; // ViewForm.Caption := Caption; // ViewForm.Show; // ViewForm.WindowState := wsNormal; end; procedure TImageForm.UpDownEditChange(Sender: TObject); resourcestring sMinValue = 'Value below minimum'; sMaxValue = 'Value over maximum'; begin // if (StrToInt(UpDownEdit.Text) < UpDown1.Min) then // begin // UpDownEdit.Text := '1'; // raise ERangeError.Create(sMinValue); // end // else if (StrToInt(UpDownEdit.Text) > UpDown1.Max) then // begin // UpDownEdit.Text := '4'; // raise ERangeError.Create(sMaxValue); // end; // SpeedButton1.NumGlyphs := UpDown1.Position; // SpeedButton2.NumGlyphs := UpDown1.Position; end; procedure TImageForm.StretchCheckClick(Sender: TObject); begin // Image1.Stretch := StretchCheck.Checked; end; procedure TImageForm.FileEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin FileListBox1.ApplyFilePath(FileEdit.Text); Key := #0; end; end; procedure TImageForm.FormCreate(Sender: TObject); begin FormCaption := Caption + ' - '; // UpDown1.Min := 1; // UpDown1.Max := 4; end; end.
unit VCL.Helpers; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, System.JSON, System.Classes, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, VCL.Dialogs, Vcl.DBCtrls, VCL.DBGrids,System.RegularExpressions; type TDBGridHelper = class helper for TDBGrid procedure AutoSize; end; type TDBComboBoxHelper = class helper for TDBComboBox procedure Lista(aItems :String; Separador : String = ','); end; implementation { TDBGridHelper } procedure TDBGridHelper.AutoSize; {https://showdelphi.com.br/como-ajustar-automaticamente-o-tamanho-das-colunas-do-dbgrid} type TArray = Array of Integer; procedure AjustarColumns(Swidth, TSize: Integer; Asize: TArray); var idx: Integer; begin if TSize = 0 then begin TSize := Self.Columns.count; for idx := 0 to Self. Columns.count - 1 do Self.Columns[idx].Width := (Self.Width - Self.Canvas.TextWidth('AAAAAA')) div TSize end else for idx := 0 to Self.Columns.count - 1 do Self.Columns[idx].Width := Self.Columns[idx].Width + (Swidth * Asize[idx] div TSize); end; var idx, Twidth, TSize, Swidth: Integer; AWidth: TArray; Asize: TArray; NomeColuna: String; begin SetLength(AWidth, Self.Columns.count); SetLength(Asize, Self.Columns.count); Twidth := 0; TSize := 0; for idx := 0 to Self.Columns.count - 1 do begin NomeColuna := Self.Columns[idx].Title.Caption; Self.Columns[idx].Width := Self.Canvas.TextWidth(Self.Columns[idx].Title.Caption + 'A'); AWidth[idx] := Self.Columns[idx].Width; Twidth := Twidth + AWidth[idx]; if Assigned(Self.Columns[idx].Field) then Asize[idx] := Self.Columns[idx].Field.Size else Asize[idx] := 1; TSize := TSize + Asize[idx]; end; if TDBGridOption.dgColLines in Self.Options then Twidth := Twidth + Self.Columns.count; if TDBGridOption.dgIndicator in Self.Options then Twidth := Twidth + IndicatorWidth; Swidth := Self.ClientWidth - Twidth; AjustarColumns(Swidth, TSize, Asize); end; { TDBComboBoxHelper } procedure TDBComboBoxHelper.Lista(aItems :String; Separador : String = ','); var I :Integer; Item :TArray<String>; begin Self.Clear; if aItems <> '' then begin Item := TRegEx.Split(aItems,Separador); for I := 0 to TRegEx.Matches(aItems,Separador).Count do Self.Items.Add(Item[I]) end; end; end.
program BasicPascal(output); var result : integer; procedure sayHello(); begin writeln('Hello World!') end; function returnInt(): integer; begin returnInt:= 10; end; begin sayHello(); result := returnInt(); writeln(result) end.
unit JO5_dmRegSCH; interface uses SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, IBase, Jo5_Types, Controls, FIBQuery, pFIBQuery, pFIBStoredProc, RxMemDS, frxClass, frxDBSet, Forms, frxDesgn, Jo5_Consts, Jo5_Proc, Jo5_ErrorSch; type TdmRegSCH = class(TDataModule) DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; DSet1: TpFIBDataSet; DSource1: TDataSource; DSet2: TpFIBDataSet; DSource2: TDataSource; spcSchet: TpFIBStoredProc; WriteTransaction: TpFIBTransaction; DBDataset: TfrxDBDataset; frxDesigner1: TfrxDesigner; dstBuffer: TRxMemoryData; fldSCH_NUMBER: TStringField; fldSCH_TITLE: TStringField; fldSCH_ERROR: TStringField; Report: TfrxReport; procedure ReportGetValue(const VarName: String; var Value: Variant); private { Private declarations } pRegUchArray:TArrayInt64; pLanguageIndex:Byte; public pSelSch:TJo5SelectShc; { Public declarations } SysInfo:TJo5SysInfo; constructor Create(AOwner:TComponent;AHandle:TISC_DB_HANDLE;In_SysInfo:TJo5SysInfo); reintroduce; procedure Refresh(id_system:Integer); procedure Filter(NewKodSetup:Integer;NewDate:TDate;pRegUchList:TStrings;RegIndex:Integer;NewIdSchTypeObj:Integer;id_system:Integer); function ReturnRegUch(pRegUchList:TStrings;SelDate:TDateTime):integer; function GetKorParam:TJo5SchKor; procedure SelectSch(Num:Integer); procedure OpenSch; procedure CloseSch; procedure DoPrint; procedure RefreshSchByID(ID:Int64); function GetCurrIDSch:Int64; function GetCurrSelDate:TDate; end; implementation {$R *.dfm} uses Dates, zProc, Kernel, ZMessages, Dialogs, JO5_Classes; constructor TdmRegSCH.Create(AOwner:TComponent;AHandle:TISC_DB_HANDLE;In_SysInfo:TJo5SysInfo); begin inherited Create(AOwner); pLanguageIndex:=IndexLanguage; //****************************************************************************** SysInfo:=In_SysInfo; pSelSch.SelDate:=SysInfo.CurrDate; pSelSch.SelKodSetup:=SysInfo.KodSetup; pSelSch.IdSchTypeObj:=SysInfo.IdSchTypeObj; pSelSch.IdRegUch:=SysInfo.DefIdRegUch; // SysInfo.KodSetup := CurrentKodSetup(AHandle); //****************************************************************************** DB.Handle:=AHandle; ReadTransaction.Active:=True; end; procedure TdmRegSCH.Refresh(id_system:Integer); begin if DSet1.Active then DSet1.Close; DSet1.SQLs.SelectSQL.Text:='SELECT * FROM JO5_GET_ALL_SCH_OBORT(' +IntToStr(pSelSch.IdRegUch)+',''' +DateToStr(pSelSch.SelDate)+''',' +IntToStr(pSelSch.IdSchTypeObj)+',' +IntToStr(id_system)+')'; DSet1.Open; end; procedure TdmRegSCH.Filter(NewKodSetup:Integer;NewDate:TDate; pRegUchList:TStrings;RegIndex:Integer;NewIdSchTypeObj:Integer;id_system:Integer); begin pSelSch.SelKodSetup := NewKodSetup; pSelSch.SelDate := NewDate; pSelSch.IdRegUch :=TRegValue(pRegUchList.Objects[RegIndex]).id_reg; Refresh(id_system); end; function TdmRegSCH.ReturnRegUch(pRegUchList:TStrings; SelDate:TDateTime):integer; var id_reg_uch:TRegValue; RC:Integer; begin Result:=-1; pRegUchList.Clear; if DSet2.Active then DSet2.Close; DSet2.SQLs.SelectSQL.Text:='SELECT * FROM JO5_GET_ALL_REG_UCH_EX('+IntToStr(SysInfo.id_system)+','+''''+DateToStr(Seldate)+''''+')'; DSet2.Open; DSet2.Last; RC:=DSet2.RecordCount+1; SetLength(pRegUchArray, RC); DSet2.First; while not DSet2.Eof do begin id_reg_uch:=TRegValue.Create; id_reg_uch.id_reg:=DSet2.FieldByName('OUT_ID_REG_UCH').Value; pRegUchList.AddObject(DSet2['OUT_REG_UCH_FULL_NAME'], TObject(id_reg_uch)); pRegUchArray[DSet2.RecNo-1]:=DSet2['OUT_ID_REG_UCH']; if DSet2['OUT_ID_REG_UCH']=pSelSch.IdRegUch then Result:=DSet2.RecNo-1; DSet2.Next; end; end; function TdmRegSCH.GetKorParam:TJo5SchKor; begin with Result do begin IdRegUch:=pSelSch.IdRegUch; IdSch:=DSet1['OUT_ID_SCH']; SelDate:=pSelSch.SelDate; HasChildren:=IfThen(DSet1['OUT_HAS_CHILDREN_BOOLEAN']=1,True,False); SchTitle:='№ '+DSet1['OUT_SCH_NUMBER']+' - "'+ DSet1['OUT_SCH_TITLE']+'"'; Oborots[0]:=DSet1['OUT_DB_SUMMA']; Oborots[1]:=DSet1['OUT_KR_SUMMA']; end; end; procedure TdmRegSCH.SelectSch(Num:Integer); begin DSet1.RecNo:=Num+1; end; procedure TdmRegSCH.OpenSch; var ModRes : Integer; IdSCH : Int64; IsOpen : Boolean; IsClose : Boolean; IsChild : Boolean; MonthNum : String; Handle : String; // fmErrSch : TfmErrorSch; IsSchSingle : Boolean; ResultSchStr : RESULT_STRUCTURE; PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE; begin Handle:=RegSch_Caption[PLanguageIndex]; try try if not DSet1.IsEmpty {1} then begin //Подготавливаем буфер для протоколирования возможных ошибок открытия счёта if dstBuffer.Active then dstBuffer.Close; dstBuffer.Open; IsOpen := True; IsClose := not DSet1.FBN('OUT_IS_OPEN_BOOLEAN').AsBoolean; IsChild := not DSet1.FBN('OUT_HAS_CHILDREN_BOOLEAN').AsBoolean; //Проверяем: возможно ли корректное открытие текущего счёта? if ( IsClose and IsChild ) {2} then begin try IdSCH := DSet1.FBN('OUT_ID_SCH').AsVariant; //Заполняем структуру для менеджера счетов New( PKernelSchStr ); WriteTransaction.StartTransaction; PKernelSchStr^.MODE := Ord( mmOpenSch ); PKernelSchStr^.DBHANDLE := DSet1.Database.Handle; PKernelSchStr^.TRHANDLE := WriteTransaction.Handle; PKernelSchStr^.ID_SCH := IdSCH; //Вызываем менеджер счетов ResultSchStr := SchManager( PKernelSchStr ); WriteTransaction.Commit; //Анализируем результат перевода текущего счёта if ResultSchStr.RESULT_CODE = Ord( msrError ) {3} then begin //Запоминаем информацию для непереведённого счёта dstBuffer.Insert; dstBuffer.FieldByName('SCH_NUMBER').Value := DSet1.FBN('OUT_SCH_NUMBER').AsString; dstBuffer.FieldByName('SCH_TITLE' ).Value := DSet1.FBN('OUT_SCH_TITLE' ).AsString; dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE; dstBuffer.Post; IsOpen := False; {-3} end; finally //Освобождаем динамически выделенную память if PKernelSchStr <> nil {4} then begin PKernelSchStr := nil; Dispose( PKernelSchStr ); {-4} end; end; //Оповещаем пользователя о результатах перевода текущего счёта в предыдущий период if IsOpen {5} then begin //Проверяем: является ли данный счёт единственным закрытым в текущем периоде? spcSchet.StoredProcName := 'JO5_IS_SCH_SINGLE_IN_CUR_PERIOD'; spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; spcSchet.ParamByName('IN_IS_CLOSE').AsInteger := Ord( smOpen ); WriteTransaction.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; WriteTransaction.Commit; //Получаем результат проверки IsSchSingle := Boolean( spcSchet.FN('OUT_SCH_IS_SINGLE_BOOLEAN').AsInteger ); //Анализируем необходимость переведения всей системы в предыдущий период if IsSchSingle {6} then begin //Переводим систему в предыдущий период spcSchet.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smOpen ); WriteTransaction.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; WriteTransaction.Commit; //Получаем данные для текущего периода системы SysInfo.KodSetup := spcSchet.FN('OUT_KOD_CURR_PERIOD' ).AsInteger; SysInfo.CurrDate := spcSchet.FN('OUT_DATE_CURR_PERIOD').AsDate; //Обновляем значение текущего периода MonthNum:=IntToStr(YearMonthFromKodSetup(SysInfo.KodSetup,False)); if Length(MonthNum)=1 then MonthNum:='0'+MonthNum; //fmMain.mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT; {-6} end; RefreshSchByID(IdSCH); ZShowMessage(Handle, PChar( sMsgOKOpenSCH[PLanguageIndex] ),mtConfirmation,[mbOk]); {-5} end {7} else begin ModRes := zShowMessage( Handle, PChar( sMsgErrOpenSCH[PLanguageIndex] ), mtError, [mbYes,mbNo]); //Показываем расшифровку ошибок для текущего счёта if ModRes = mrYes {8} then begin ZShowMessage(Handle,ResultSchStr.RESULT_MESSAGE, mtInformation, [mbOk]); { try fmErrSch := TfmErrorSch.Create( Self, dstBuffer ); fmErrSch.ShowModal; finally FreeAndNil( fmErrSch ); end; } {-8} end; {-7} end; dstBuffer.Close; {-2} end {9} else begin //Извещаем пользователя о причинах отказа в открытии текущего счёта if not IsChild then ZShowMessage( Handle, PChar( sMsgSchIsParentOp[PLanguageIndex] ), mtWarning, [mbOk] ) else if not IsClose then zShowMessage( Handle, PChar( sMsgSchIsOpened[PLanguageIndex] ), mtWarning , [mbOk] ); {-9} end; {-1} end else begin ZShowMessage( Handle, PChar( sMsgSchIsAbsent[PLanguageIndex] ), mtError, [mbOk]); end; except //Завершаем транзанкцию if WriteTransaction.InTransaction then WriteTransaction.Rollback; //Освобождаем память для НД if dstBuffer.Active then dstBuffer.Close; //Протоколируем ИС // LogException( pSysOptions.LogFileName ); Raise; end; except on E: Exception do begin ZShowMessage( Handle, ECaption[PLanguageIndex] + E.Message, mtError, [mbOk] ); end; end; end; //Закрываем текущий счёт procedure TdmRegSCH.CloseSch; var ModRes : Integer; IdSCH : Int64; IsOpen : Boolean; IsClose : Boolean; IsChild : Boolean; NewSaldo : Currency; Handle : String; MonthNum : String; // fmErrorSch : TfmErrorSch; IsSchSingle : Boolean; ResultSchStr : RESULT_STRUCTURE; PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE; begin Handle:=RegSch_Caption[PLanguageIndex]; try try if not DSet1.IsEmpty then begin //Подготавливаем буфер для протоколирования возможных ошибок закрытия счёта if dstBuffer.Active then dstBuffer.Close; dstBuffer.Open; IsOpen := DSet1.FBN('OUT_IS_OPEN_BOOLEAN').AsBoolean; IsChild := not DSet1.FBN('OUT_HAS_CHILDREN_BOOLEAN').AsBoolean; IsClose := True; //Проверяем: возможно ли корректное закрытие текущего счёта? if ( IsOpen and IsChild ) then begin try IdSCH := DSet1.FBN('OUT_ID_SCH').AsVariant; //Заполняем структуру для менеджера счетов New( PKernelSchStr ); WriteTransaction.StartTransaction; PKernelSchStr^.MODE := Ord( mmCloseSch ); PKernelSchStr^.DBHANDLE := DSet1.Database.Handle; PKernelSchStr^.TRHANDLE := WriteTransaction.Handle; PKernelSchStr^.ID_SCH := IdSCH; PKernelSchStr^.DB_OBOR := DSet1.FBN('OUT_DB_SUMMA' ).AsCurrency; PKernelSchStr^.KR_OBOR := DSet1.FBN('OUT_KR_SUMMA' ).AsCurrency; PKernelSchStr^.DB_SALDO_IN := DSet1.FBN('OUT_DB_SALDO_INPUT' ).AsCurrency; PKernelSchStr^.KR_SALDO_IN := DSet1.FBN('OUT_KR_SALDO_INPUT' ).AsCurrency; PKernelSchStr^.DB_SALDO_OUT := DSet1.FBN('OUT_DB_SALDO_CUR' ).AsCurrency; PKernelSchStr^.KR_SALDO_OUT := DSet1.FBN('OUT_KR_SALDO_CUR' ).AsCurrency; //Вызываем менеджер счетов ResultSchStr := SchManager( PKernelSchStr ); WriteTransaction.Commit; //Анализируем результат перевода текущего счёта if ResultSchStr.RESULT_CODE = Ord( msrError ) then begin //Запоминаем информацию для непереведённого счёта dstBuffer.Insert; dstBuffer.FieldByName('SCH_NUMBER').Value := DSet1.FBN('OUT_SCH_NUMBER').AsString; dstBuffer.FieldByName('SCH_TITLE' ).Value := DSet1.FBN('OUT_SCH_TITLE' ).AsString; dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE; dstBuffer.Post; IsClose := False; end; finally //Освобождаем динамически выделенную память if PKernelSchStr <> nil then begin PKernelSchStr := nil; Dispose( PKernelSchStr ); end; end; //Оповещаем пользователя о результатах перевода текущего счёта в следующий период if IsClose then begin //Проверяем: является ли данный счёт единственным незакрытым в текущем периоде? spcSchet.StoredProcName := 'JO5_IS_SCH_SINGLE_IN_CUR_PERIOD'; spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; spcSchet.ParamByName('IN_IS_CLOSE').AsInteger := Ord( smClose ); WriteTransaction.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; WriteTransaction.Commit; //Получаем результат проверки IsSchSingle := Boolean( spcSchet.FN('OUT_SCH_IS_SINGLE_BOOLEAN').AsInteger ); //Удалям существующее вступительное сальдо для следующего периода spcSchet.StoredProcName := 'JO5_DT_SALDO_DEL_EXT'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; WriteTransaction.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; //Добавляем пресчитанное вступительное сальдо для следующего периода spcSchet.StoredProcName := 'JO5_DT_SALDO_INS_EXT'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; spcSchet.Prepare; spcSchet.ExecProc; //Анализируем необходимость переведения всей системы в следующий период if IsSchSingle then begin //Переводим систему в следующий период spcSchet.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcSchet.Prepare; spcSchet.ExecProc; WriteTransaction.Commit; //Получаем данные для текущего периода системы SysInfo.KodSetup := spcSchet.FN('OUT_KOD_CURR_PERIOD' ).AsInteger; SysInfo.CurrDate := spcSchet.FN('OUT_DATE_CURR_PERIOD').AsDate; //Обновляем значение текущего периода MonthNum:=IntToStr(YearMonthFromKodSetup(SysInfo.KodSetup,False)); if Length(MonthNum)=1 then MonthNum:='0'+MonthNum; //fmMain.mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT; end; RefreshSchByID(IdSCH); ZShowMessage( Handle, PChar( sMsgOKCloseSCH[PLanguageIndex] ), mtInformation, [mbOk]); end else begin ModRes := ZShowMessage( Handle, PChar( sMsgErrCloseSCH[PLanguageIndex] ), mtError, [mbYes, mbNo]); //Показываем расшифровку ошибок для текущего счёта if ModRes = mrYes then begin ZShowMessage(Handle,ResultSchStr.RESULT_MESSAGE, mtInformation, [mbOk]); { try fmErrorSch := TfmErrorSch.Create( Self, dstBuffer ); fmErrorSch.ShowModal; finally FreeAndNil( fmErrorSch ); end;} end; end; dstBuffer.Close; end else begin //Извещаем пользователя о причинах отказа в закрытии текущего счёта if not IsChild then ZShowMessage( Handle, PChar( sMsgSchIsParentCl[PLanguageIndex] ), mtWarning, [mbOk]) else if not IsOpen then ZShowMessage( Handle, PChar( sMsgSchIsClosed[PLanguageIndex] ), mtWarning, [mbOk]); end; end else begin ZShowMessage( Handle, PChar( sMsgSchIsAbsent[PLanguageIndex] ), mtError, [mbOk]); end; except //Завершаем транзанкцию if WriteTransaction.InTransaction then WriteTransaction.Rollback; //Освобождаем память для НД if dstBuffer.Active then dstBuffer.Close; //Протоколируем ИС // LogException( pSysOptions.LogFileName ); Raise; end; except on E: Exception do begin ZShowMessage( Handle, ECaption[PLanguageIndex] + E.Message, mtError, [mbOk] ); end; end; end; procedure TdmRegSCH.ReportGetValue(const VarName: String; var Value: Variant); //const VisaText = 'ДонНУ'+#13; begin if VarName = 'Period' then Value := KodSetupToPeriod(pSelSch.SelKodSetup,4); if VarName = 'Visa' then Value :={ VisaText + }DateToStr( Date ); if VarName = 'Order' then begin if pSelSch.IdRegUch<>-1 then Value :=GetRegInfo(self,DB.Handle,pSelSch.IdRegUch) else Value := '5'; end end; procedure TdmRegSCH.DoPrint; const ReportName='Reports\JO5\JO5_ALL_SCH_INFO'; var FileName : String; begin FileName:=ExtractFilePath(Application.ExeName)+ReportName+'.fr3'; if FileExists(FileName) then begin DSet1.DisableControls; Refresh(SysInfo.id_system); //Выводим отчет на экран Report.LoadFromFile(FileName,True); { if zDesignReport then Report.DesignReport else} Report.ShowReport; DSet1.First; DSet1.EnableControls; end; end; procedure TdmRegSCH.RefreshSchByID(ID:Int64); begin // Обновление записи DSet1.DisableControls; DSet1.SQLs.UpdateSQL.Text := 'execute procedure Z_EMPTY_PROC'; DSet1.SQLs.RefreshSQL.Text :='select * from JO5_GET_SCH_OBORT_BY_ID(' +IntToStr(pSelSch.IdRegUch)+',''' +DateToStr(pSelSch.SelDate)+''',' +IntToStr(pSelSch.IdSchTypeObj)+',' +IntToStr(ID)+')'; DSet1.Edit; DSet1.Post; DSet1.SQLs.UpdateSQL.Clear; DSet1.SQLs.RefreshSQL.Clear; DSet1.EnableControls; end; function TdmRegSCH.GetCurrIDSch:Int64; begin Result:=DSet1['OUT_ID_SCH']; end; function TdmRegSCH.GetCurrSelDate:TDate; begin Result:=pSelSch.SelDate; end; end.
//4-Escriba un programa donde se ingrese el tiempo necesario para un cierto proceso en horas, minutos y segundos. //Calcule el costo total del proceso sabiendo que el costo por segundo es 0,25$. (Debe salir por pantalla el //tiempo expresado en horas, minutos ,segundos y el costo total) Program tiempo4; Var horas,minutos,segundos:byte; costoSeg,costoTotal:real; Begin writeln('ingrese la cantidad de horas :');readln(horas); writeln('ingrese la cantidad de minutos :');readln(minutos); writeln('ingrese la cantidad de segundos :');readln(segundos); costoSeg:= segundos * 0.25; costoTotal:= horas * minutos * costoSeg; writeln(' el tiempo del proceso es :',horas, ' horas ',minutos, ' minutos ',segundos,' segundos con un costo total de : $',costoTotal:2:0); end.
Unit ioctl; { * Ioctl : * * * * Implementacion de las llamadas de control * * * * Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> * * All Rights Reserved * * * * Versiones : * * 2 / 2 / 2005 : Primera Version * * * *************************************************************** } interface {$I ../include/toro/procesos.inc} {$I ../include/head/scheduler.h} {$I ../include/head/printk_.h} {$I ../include/head/asm.h} implementation { * Sys_Ioctl : * * * * Fichero : Descriptor de Archivo * * req : Numero de procedimiento * * argp : Puntero a los argumentos * * Retorno : -1 si fallo * * * * * * Implementacion de la llamada al sistema IOCTL donde se llama a un * * procedimiento de control de un driver dado * * * *********************************************************************** } function sys_ioctl (Fichero , req : dword ; argp : pointer) : dword ;cdecl;[public , alias :'SYS_IOCTL']; var fd : p_file_t ; begin If (Fichero > 32) then begin set_errno := -EBADF ; exit(-1); end; fd := @Tarea_Actual^.Archivos[Fichero]; If fd^.f_op = nil then begin set_Errno := -EBADF ; exit(-1); end; If fd^.f_op^.ioctl = nil then begin set_errno := -EPERM ; exit(-1); end; exit(fd^.f_op^.ioctl(fd,req,argp)); end; end.
unit GLDCylinderParamsFrame; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, GL, GLDTypes, GLDSystem, GLDCylinder, GLDNameAndColorFrame, GLDUpDown; type TGLDCylinderParamsFrame = class(TFrame) NameAndColor: TGLDNameAndColorFrame; GB_Params: TGroupBox; L_Radius: TLabel; L_Height: TLabel; L_HeightSegs: TLabel; L_CapSegs: TLabel; L_Sides: TLabel; L_StartAngle: TLabel; L_SweepAngle: TLabel; E_Radius: TEdit; E_Height: TEdit; E_HeightSegs: TEdit; E_CapSegs: TEdit; E_Sides: TEdit; E_StartAngle: TEdit; E_SweepAngle: TEdit; UD_Radius: TGLDUpDown; UD_Height: TGLDUpDown; UD_HeightSegs: TUpDown; UD_CapSegs: TUpDown; UD_Sides: TUpDown; UD_StartAngle: TGLDUpDown; UD_SweepAngle: TGLDUpDown; procedure ParamsChangeUD(Sender: TObject); procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function HaveCylinder: GLboolean; function GetParams: TGLDCylinderParams; procedure SetParams(const Name: string; const Color: TGLDColor3ub; const Radius, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat); procedure SetParamsFrom(Cylinder: TGLDCylinder); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; procedure Register; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX; constructor TGLDCylinderParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; end; destructor TGLDCylinderParamsFrame.Destroy; begin if Assigned(FDrawer) then if FDrawer.IOFrame = Self then FDrawer.IOFrame := nil; inherited Destroy; end; function TGLDCylinderParamsFrame.HaveCylinder: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedObject) and (FDrawer.EditedObject is TGLDCylinder) then Result := True; end; function TGLDCylinderParamsFrame.GetParams: TGLDCylinderParams; begin if HaveCylinder then with TGLDCylinder(FDrawer.EditedObject) do begin Result.Position := Position.Vector3f; Result.Rotation := Rotation.Params; end else begin Result.Position := GLD_VECTOR3F_ZERO; Result.Rotation := GLD_ROTATION3D_ZERO; end; Result.Color := NameAndColor.ColorParam; Result.Radius := UD_Radius.Position; Result.Height := UD_Height.Position; Result.HeightSegs := UD_HeightSegs.Position; Result.CapSegs := UD_CapSegs.Position; Result.Sides := UD_Sides.Position; Result.StartAngle := UD_StartAngle.Position; Result.SweepAngle := UD_SweepAngle.Position; end; procedure TGLDCylinderParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub; const Radius, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat); begin NameAndColor.NameParam := Name; NameAndColor.ColorParam := Color; UD_Radius.Position := Radius; UD_Height.Position := Height; UD_HeightSegs.Position := HeightSegs; UD_CapSegs.Position := CapSegs; UD_Sides.Position := Sides; UD_StartAngle.Position := StartAngle; UD_SweepAngle.Position := SweepAngle; end; procedure TGLDCylinderParamsFrame.SetParamsFrom(Cylinder: TGLDCylinder); begin if not Assigned(Cylinder) then Exit; with Cylinder do SetParams(Name, Color.Color3ub, Radius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle); end; procedure TGLDCylinderParamsFrame.ApplyParams; begin if HaveCylinder then TGLDCylinder(FDrawer.EditedObject).Params := GetParams; end; procedure TGLDCylinderParamsFrame.ParamsChangeUD(Sender: TObject); begin if HaveCylinder then with TGLDCylinder(FDrawer.EditedObject) do if Sender = UD_Radius then Radius := UD_Radius.Position else if Sender = UD_Height then Height := UD_Height.Position else if Sender = UD_StartAngle then StartAngle := UD_StartAngle.Position else if Sender = UD_SweepAngle then SweepAngle := UD_SweepAngle.Position; end; procedure TGLDCylinderParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); begin if HaveCylinder then with TGLDCylinder(FDrawer.EditedObject) do if Sender = UD_HeightSegs then HeightSegs := UD_HeightSegs.Position else if Sender = UD_CapSegs then CapSegs := UD_CapSegs.Position else if Sender = UD_Sides then Sides := UD_Sides.Position; end; procedure TGLDCylinderParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDCylinderParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDCylinderParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; NAmeAndColor.Drawer := FDrawer; end; procedure Register; begin //RegisterComponents('GLDraw', [TGLDCylinderParamsFrame]); end; end.
unit uCustomAttributesEntity; interface type TableName = class(TCustomAttribute) private FName: String; public property Name: String read FName write FName; constructor Create(AName: String); end; type KeyField = class(TCustomAttribute) private FName: String; public property Name: String read FName write FName; constructor Create(AName: String); end; type FieldName = class(TCustomAttribute) private FName: String; public property Name: String read FName write FName; constructor Create(AName: String); end; type ForeignKey = class(TCustomAttribute) private FName: String; FReferenceFieldName: String; FReferenceTableName: String; procedure SetName(const Value: String); procedure SetReferenceFieldName(const Value: String); procedure SetReferenceTableName(const Value: String); public property Name: String read FName write SetName; property ReferenceFieldName: String read FReferenceFieldName write SetReferenceFieldName; property ReferenceTableName: String read FReferenceTableName write SetReferenceTableName; constructor Create(AName, AReferenceFieldName, AReferenceTableName: String); end; implementation constructor TableName.Create(AName: String); begin FName := AName end; constructor KeyField.Create(AName: String); begin FName := AName; end; constructor FieldName.Create(AName: String); begin FName := AName; end; { ForeignKey } constructor ForeignKey.Create(AName, AReferenceFieldName, AReferenceTableName: String); begin FName := AName; FReferenceFieldName := AReferenceFieldName; FReferenceTableName := AReferenceTableName; end; procedure ForeignKey.SetName(const Value: String); begin FName := Value; end; procedure ForeignKey.SetReferenceFieldName(const Value: String); begin FReferenceFieldName := Value; end; procedure ForeignKey.SetReferenceTableName(const Value: String); begin FReferenceTableName := Value; end; end.
{ Unit to boot-strap and create a new database, if it's not already present } unit DSServerLogDB; interface const DB_NAME = 'DSServerLog.ib'; DBEMPLOYEE_NAME = 'Employee.ib'; procedure CreateLogDB; implementation uses Forms, SysUtils, SqlExpr, DbxMetaDataHelper, DbxCommon, DbxMetaDataProvider, DBXDataExpressMetaDataProvider, DbxInterbase, DbxClient, Dialogs; procedure CreateSchema(conn: TSQLConnection); var Provider: TDBXDataExpressMetaDataProvider; Jobs, Log, Users: TDBXMetaDataTable; LogIdField: TDBXInt32Column; JobIdField: TDBXInt32Column; StrField : TDBXUnicodeVarCharColumn; UserIdField: TDBXInt32Column; begin Provider := DBXGetMetaProvider(conn.DBXConnection); // Jobs Jobs := TDBXMetaDataTable.Create; Jobs.TableName := 'JOBS'; JobIdField := TDBXInt32Column.Create('JOBID'); JobIdField.Nullable := false; JobIdField.AutoIncrement := false; Jobs.AddColumn(JobIdField); StrField := TDBXUnicodeVarCharColumn.Create('JOBNAME', 50); StrField.Nullable := False; Jobs.AddColumn(StrField); StrField := TDBXUnicodeVarCharColumn.Create('DESCRIPTION', 100); StrField.Nullable := False; Jobs.AddColumn(StrField); Jobs.AddColumn(TDBXUnicodeVarCharColumn.Create('JOBCMD', 200)); Provider.CreateTable(Jobs); AddPrimaryKey(Provider, 'JOBS', 'JOBID'); AddUniqueIndex(Provider, 'JOBS', 'JOBNAME'); // Log Log := TDBXMetaDataTable.Create; Log.TableName := 'LOG'; LogIdField := TDBXInt32Column.Create('LOGID'); LogIdField.Nullable := false; Log.AddColumn(LogIdField); StrField := TDBXUnicodeVarCharColumn.Create('IP_ADDRESS', 20); StrField.Nullable := False; Log.AddColumn(StrField); StrField := TDBXUnicodeVarCharColumn.Create('EVENT', 50); StrField.Nullable := False; Log.AddColumn(StrField); Log.AddColumn(TDBXTimestampColumn.Create('CREATED')); Provider.CreateTable(Log); AddPrimaryKey(Provider, 'LOG', 'LOGID'); // Users Users := TDBXMetaDataTable.Create; Users.TableName := 'USERS'; UserIdField := TDBXInt32Column.Create('USERID'); UserIdField.Nullable := false; // UserIdField.AutoIncrement := true; Users.AddColumn(UserIdField); StrField := TDBXUnicodeVarCharColumn.Create('LOGIN', 20); StrField.Nullable := False; Users.AddColumn(StrField); StrField := TDBXUnicodeVarCharColumn.Create('PASSWORD', 20); StrField.Nullable := False; Users.AddColumn(StrField); StrField := TDBXUnicodeVarCharColumn.Create('NAME', 50); StrField.Nullable := False; Users.AddColumn(StrField); Users.AddColumn(TDBXBooleanColumn.Create('ACTIVE')); Provider.CreateTable(Users); AddPrimaryKey(Provider, 'USERS', 'USERID'); AddUniqueIndex(Provider, 'USERS', 'NAME'); CreateGenerator(Provider, 'GEN_JOB_ID'); CreateGenerator(Provider, 'GEN_LOG_ID'); CreateGenerator(Provider, 'GEN_USER_ID'); CreateAutoIncTrigger(Provider, 'BI_JOBID', 'JOBS', 'JOBID', 'GEN_JOB_ID' ); CreateAutoIncTrigger(Provider, 'BI_LOGID', 'LOG' , 'LOGID', 'GEN_LOG_ID' ); CreateAutoIncTrigger(Provider, 'BI_USERID', 'USERs', 'USERID', 'GEN_USER_ID' ); FreeAndNil(Provider); FreeAndNil(Users); FreeAndNil(Log); FreeAndNil(Jobs); end; procedure PopulateData(conn: TSQLConnection); Const SqlInsertUser : String = 'Insert Into Users (Login, "PASSWORD", Name, "ACTIVE") ' + 'Values ( ''%s'', ''%s'', ''%s'', %s )'; SqlInsertJob : String = 'Insert Into Jobs (JobName, Description, JobCmd) ' + 'Values ( ''%s'', ''%s'', ''%s'')'; var Comm : TDBXCommand; begin Comm := conn.DBXConnection.CreateCommand; try // Populate Users Comm.Text := Format(SqlInsertUser, ['admin', 'admin', 'Administrator', 'true']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertUser, ['peter', 'p134', 'Peter Kaster', 'false']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertUser, ['john', 'noguera', 'John Lala', 'true']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertUser, ['paul', 'ddsn', 'Paul Mark', 'true']); Comm.ExecuteQuery; // Populate Jobs Comm.Text := Format(SqlInsertJob, ['Notepad', 'Execute notepad', 'notepad.exe']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertJob, ['InterBase', 'Start InterBase Server', 'ibserver']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertJob, ['Calc', 'Execute windows Calc', 'calc.exe']); Comm.ExecuteQuery; finally Comm.Free; end; end; procedure CreateLogDB; var conn: TSQLConnection; Exists: Boolean; begin conn := TSQLConnection.Create(nil); try try InitConnection(conn, DB_NAME, False); Exists := True; conn.Close; Except Exists := False; end; if not Exists then begin try InitConnection(conn, DB_NAME, True); CreateSchema(conn); PopulateData(conn); conn.Close; except on E: Exception do showmessage(e.Message); end; end; finally conn.Free; end; end; end.
unit WorkReasonMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, dxBar, dxBarExtItems, ZProc, Unit_ZGlobal_Consts, IBase, ActnList, ZTypes, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, Kernel, cxTextEdit, PackageLoad, Unit_NumericConsts, zMessages, dxStatusBar, Menus; type TFZWorkReason = class(TForm) BarManager: TdxBarManager; UpdateBtn: TdxBarLargeButton; RefreshBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; Grid: TcxGrid; GridDBTableView1: TcxGridDBTableView; GridClNameShort: TcxGridDBColumn; GridClNameFull: TcxGridDBColumn; GridLevel1: TcxGridLevel; DataSource: TDataSource; DataBase: TpFIBDatabase; DataSet: TpFIBDataSet; WriteTransaction: TpFIBTransaction; StoredProc: TpFIBStoredProc; Styles: TcxStyleRepository; ReadTransaction: TpFIBTransaction; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; GridClKodVidopl: TcxGridDBColumn; GridClNameVidopl: TcxGridDBColumn; StatusBar: TdxStatusBar; procedure ExitBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure RefreshBtnClick(Sender: TObject); procedure GridDBTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure UpdateBtnClick(Sender: TObject); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); private Ins_Resault:Variant; Ins_ZFormStyle:TZFormStyle; pLanguageIndex:integer; public constructor Create(ComeComponent:TComponent;ComeDB:TISC_DB_HANDLE);reintroduce; property Resault:variant read Ins_Resault; property ZFormStyle:TZFormStyle read Ins_ZFormStyle; end; function ViewForm(AOwner : TComponent;DB:TISC_DB_HANDLE):Variant;stdcall; exports ViewForm; implementation {$R *.dfm} function ViewForm(AOwner : TComponent;DB:TISC_DB_HANDLE):Variant; var ViewForm: TFZWorkReason; begin if not IsMDIChildFormShow(TFZWorkReason) then ViewForm := TFZWorkReason.Create(AOwner, DB); end; constructor TFZWorkReason.Create(ComeComponent:TComponent;ComeDB:TISC_DB_HANDLE); begin inherited Create(ComeComponent); //------------------------------------------------------------------------------ pLanguageIndex := LanguageIndex; Caption := FSpAsupIniWorkReason_Caption[pLanguageIndex]; RefreshBtn.Caption := RefreshBtn_Caption[pLanguageIndex]; UpdateBtn.Caption := UpdateBtn_Caption[pLanguageIndex]; ExitBtn.Caption := ExitBtn_Caption[pLanguageIndex]; GridClNameFull.Caption := GridClFullName_Caption[pLanguageIndex]; GridClNameShort.Caption := GridClShortName_Caption[pLanguageIndex]; GridClKodVidopl.Caption := GridClKodVidOpl_Caption[pLanguageIndex]; GridClNameVidopl.Caption := GridClNameVidopl_Caption[pLanguageIndex]; StatusBar.Panels[0].Text := ShortCutToText(RefreshBtn.ShortCut)+' - '+RefreshBtn.Caption; StatusBar.Panels[1].Text := ShortCutToText(UpdateBtn.ShortCut)+' - '+UpdateBtn.Caption; StatusBar.Panels[2].Text := ShortCutToText(ExitBtn.ShortCut)+' - '+ExitBtn.Caption; //------------------------------------------------------------------------------ DataBase.Handle := ComeDB; DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ASUP_INI_WORK_REASON_S(NULL)'; DataSet.Open; UpdateBtn.Enabled := DataSet.VisibleRecordCount>0; //------------------------------------------------------------------------------ WindowState := wsMaximized; end; procedure TFZWorkReason.ExitBtnClick(Sender: TObject); begin Close; end; procedure TFZWorkReason.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TFZWorkReason.RefreshBtnClick(Sender: TObject); begin DataSetCloseOpen(DataSet); end; procedure TFZWorkReason.GridDBTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin UpdateBtn.Enabled:=not(AFocusedRecord=nil); end; procedure TFZWorkReason.UpdateBtnClick(Sender: TObject); var Id:variant; begin Id:=LoadVidOpl(self,DataBase.Handle,zfsModal,0,Id_System); if not VarIsNull(Id) then try StoredProc.StoredProcName := 'Z_ASUP_INI_WORK_REASON_U'; StoredProc.Transaction.StartTransaction; StoredProc.Prepare; StoredProc.ParamByName('ID_WORK_REASON').AsInteger := DataSet['ID_WORK_REASON']; StoredProc.ParamByName('ID_VIDOPL').AsInteger := Id[0]; StoredProc.ExecProc; StoredProc.Transaction.Commit; DataSet.SQLs.RefreshSQL.Text := 'select * from Z_ASUP_INI_WORK_REASON_S('+VarToStr(DataSet['ID_WORK_REASON'])+')'; DataSet.SQLs.UpdateSQL.Text := 'execute procedure Z_EMPTY_PROC'; DataSet.Edit; DataSet.Post; DataSet.SQLs.UpdateSQL.Clear; DataSet.SQLs.RefreshSQL.Clear; except on E:Exception do begin ZShowMessage(Error_Caption[pLanguageIndex],e.Message,mtWarning,[mbOk]); StoredProc.Transaction.Rollback; end; end; end; procedure TFZWorkReason.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); var i:integer; begin for i:=0 to StatusBar.Panels.Count-1 do StatusBar.Panels[i].Width := StatusBar.Width div StatusBar.Panels.Count; end; end.
// 347. 前 K 个高频元素 // // 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 // // 示例 1: // // 输入: nums = [1,1,1,2,2,3], k = 2 // 输出: [1,2] // 示例 2: // // 输入: nums = [1], k = 1 // 输出: [1] // 说明: // // 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 // 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 // // class Solution { // public List<Integer> topKFrequent(int[] nums, int k) { // // } // } unit DSA.LeetCode._347; interface uses System.SysUtils, DSA.Tree.BSTMap, DSA.Tree.PriorityQueue, DSA.Utils, DSA.Interfaces.Comparer; type TSolution = class private type TFreq = class public E, Freq: Integer; constructor Create(newE, newFreq: Integer); end; TFreqComparer = class(TInterfacedObject, IComparer<TFreq>) function Compare(const Left, Right: TFreq): Integer; end; public function topKFrequent(nums: TArray_int; k: Integer): TArrayList_int; end; procedure Main; implementation procedure Main; var list: TArrayList_int; slt: TSolution; i: Integer; begin slt := TSolution.Create; list := slt.topKFrequent([1, 1, 1, 2, 2, 3], 2); for i := 0 to list.GetSize - 1 do write(list[i], #9); Writeln; TDSAUtils.DrawLine; list := slt.topKFrequent([1], 1); for i := 0 to list.GetSize - 1 do write(list[i], #9); Writeln; end; { TSolution.TFreq } constructor TSolution.TFreq.Create(newE, newFreq: Integer); begin Self.E := newE; Self.Freq := newFreq; end; { TSolution.TComparer } function TSolution.TFreqComparer.Compare(const Left, Right: TFreq): Integer; begin Result := Left.Freq - Right.Freq; end; { TSolution } function TSolution.topKFrequent(nums: TArray_int; k: Integer): TArrayList_int; type TBSTMap_int_int = TBSTMap<Integer, Integer>; TPriorityQueue_TSolution_TFreq = TPriorityQueue<TSolution.TFreq>; var map: TBSTMap_int_int; queue: TPriorityQueue_TSolution_TFreq; i, n, key: Integer; list: TArrayList_int; tempFreg: TFreq; begin map := TBSTMap_int_int.Create; for i := 0 to Length(nums) - 1 do begin n := nums[i]; if map.Contains(n) then map.Set_(n, map.Get(n).PValue^ + 1) else map.Add(n, 1); end; queue := TPriorityQueue_TSolution_TFreq.Create(TQueueKind.Min, TFreqComparer.Create); for key in map.KeySets.ToArray do begin if (queue.GetSize < k) then begin tempFreg := TFreq.Create(key, map.Get(key).PValue^); queue.EnQueue(tempFreg); end else begin if queue.Peek.E < map.Get(key).PValue^ then begin tempFreg := TFreq.Create(key, map.Get(key).PValue^); queue.DeQueue; queue.EnQueue(tempFreg); map.Remove(key); end; end; end; list := TArrayList_int.Create(); while not(queue.IsEmpty) do begin list.AddLast(queue.DeQueue.E); end; Result := list; end; end.
unit NewFrontiers.Entity; interface uses NewFrontiers.GUI.PropertyChanged, Data.DB, System.Rtti, NewFrontiers.Entity.Mapping, NewFrontiers.Database, System.Classes, Generics.Collections; type /// <summary> /// Mapping-Attribut. Legt die Tabelle fest, in der das Entity /// gespeichert wird /// </summary> Table = class(TCustomAttribute) protected _tablename: string; _prefix: string; _generator: string; public constructor Create(aTablename, aPrefix, aGenerator: string); property Tablename: string read _tablename; property Prefix: string read _prefix; property Generator: string read _generator; end; /// <summary> /// Mapping-Attribut. Legt fest, welche Eigenschaften eins Enttiy in der /// Datenbank gespeichert werden /// </summary> Column = class(TCustomAttribute) protected _fieldname: string; public constructor Create(aFieldname: string = ''); property Fieldname: string read _fieldname; end; /// <summary> /// Mapping-Attribute. Legt das Feld für den Primärschlüssel fest. /// </summary> Primary = class(TCustomAttribute) end; /// <summary> /// Basisklasse für Entitys. Vereinfacht den Umgang mit dem Mapper. Ziel /// ist es auch PODOs verwenden zu können. /// </summary> TEntity = class(TPropertyChangedObject) protected _id: integer; _dirty: boolean; _new: boolean; _deleted: boolean; function updateV(var aAlterWert: string; aNeuerWert: string; aPropertyName: string): boolean; overload; function updateV(var aAlterWert: integer; aNeuerWert: integer; aPropertyName: string): boolean; overload; function updateV(var aAlterWert: real; aNeuerWert: real; aPropertyName: string): boolean; overload; function updateV(var aAlterWert: boolean; aNeuerWert: boolean; aPropertyName: string): boolean; overload; function updateV(var aAlterWert: TDateTime; aNeuerWert: TDateTime; aPropertyName: string): boolean; overload; public [Primary] property Id: integer read _id write _id; /// <summary> /// Gibt zurück, ob es Änderungen an diesem Objekt gab /// </summary> property IsDirty: boolean read _dirty write _dirty; /// <summary> /// Gibt zurück, ob es sich um einen neuen Datensatz handelt /// </summary> property IsNew: boolean read _new write _new; /// <summary> /// Gibt zurück, ob dieser Datensatz gelöscht wurde /// </summary> property IsDeleted: boolean read _deleted write _deleted; procedure save(); procedure delete(); end; TEntityList<T: class> = class(TObjectList<T>); /// <summary> /// Repository-Klasse, die statische Methoden für die CRUD Operationen /// von Entities zur Verfügung stellt. /// </summary> TEntityRepository = class public /// <summary> /// Lädt einen Datensatz des Typs T mit der übergebenen ID /// </summary> class function load<T: class, constructor>(aId: integer): T; overload; /// <summary> /// Lädt einen Datensatz des Typs T auf Basis des aktuellen /// Datensatzes in der übergebenen Query /// </summary> class function load<T: class, constructor>(aQuery: TDataset): T; overload; /// <summary> /// Lädt einen Datensatz des Typs T auf Basis des ersten Eintrags der /// Query, die vom übergebenen QueryBuilder definiert wird /// </summary> class function load<T: class, constructor>(aQueryBuilder: TQueryBuilder; aTransaction: TNfsTransaction = nil): T; overload; /// <summary> /// Lädt alle Datensätze der Entity (ohne Sortierung!) /// </summary> class function loadAll<T: class, constructor>(aTransaction: TNfsTransaction = nil): TList<T>; overload; /// <summary> /// Lädt alle Datensätze der Entity auf Basis des übergebenen /// QueryBuilders /// </summary> class function loadList<T: class, constructor>(aQueryBuilder: TQueryBuilder; aTransaction: TNfsTransaction = nil): TList<T>; overload; /// <summary> /// Lädt alle Datensätze der Entity auf Basis der übergebenen Query /// </summary> class function loadList<T: class, constructor>(aQuery: TDataset): TList<T>; overload; /// <summary> /// Speichert das übergebene Entity in der Datenbank ab /// </summary> class procedure save(aEntity: TEntity; aTransaction: TNfsTransaction = nil); /// <summary> /// Erzeugt ein neues Entity des Typs T /// </summary> class function new<T: class, constructor>(): T; /// <summary> /// Löscht einen Datensatz ind er Datenbank /// </summary> class procedure delete(aEntity: TEntity; aTransaction: TNfsTransaction = nil); class function getValueFromDBField(aQuery: TDataset; aField: TEntityField): TValue; end; type /// <summary> /// Shortcut-Klasse, damit maan weniger tippen muss /// </summary> TNfs = TEntityRepository; implementation uses System.SysUtils, NewFrontiers.Reflection, System.TypInfo, NewFrontiers.Database.Utility; { TEntityRepository } class function TEntityRepository.load<T>(aId: integer): T; var queryBuilder: TQueryBuilder; mapping: TEntityMapping; begin mapping := TEntityMappingDictionary.getMappingFor(T); queryBuilder := TQueryBuilder .select .from(mapping.Tablename) .where(mapping.Primary + ' = :id') .param('id', aId); result := TEntityRepository.load<T>(queryBuilder); queryBuilder.free; end; class procedure TEntityRepository.delete(aEntity: TEntity; aTransaction: TNfsTransaction); var queryBuilder: TQueryBuilder; mapping: TEntityMapping; query: TNfsQuery; wasOpen: boolean; begin if (aTransaction = nil) then aTransaction := TDatabaseProvider.getDefaultTransaction; wasOpen := aTransaction.InTransaction; if not WasOpen then aTransaction.StartTransaction; mapping := TEntityMappingDictionary.getMappingFor(aEntity.ClassType); queryBuilder := TQueryBuilder .delete .from(mapping.Tablename) .where(mapping.Primary + ' = :id') .param('id', aEntity.Id); query := queryBuilder.getQuery(nil, aTransaction); query.Execute; query.Free; queryBuilder.Free; if not wasOpen then aTransaction.Commit; aEntity.IsDeleted := true; end; class function TEntityRepository.getValueFromDBField(aQuery: TDataset; aField: TEntityField): TValue; begin if (aField is TEntityFieldInteger) then result := TValue.From<integer>(aQuery.FieldByName(aField.FieldName).AsInteger) else if (aField is TEntityFieldFloat) then result := TValue.From<Double>(aQuery.FieldByName(aField.FieldName).AsFloat) else if (aField is TEntityFieldString) then result := TValue.From<string>(aQuery.FieldByName(aField.FieldName).AsString); end; class function TEntityRepository.load<T>(aQuery: TDataset): T; var mapping: TEntityMapping; aktField: TEntityField; value: TValue; begin if (not aQuery.Active) then raise Exception.Create('Übergebene Query ist nicht geöffnet'); if (aQuery.IsEmpty) then raise Exception.Create('Übergebene Query ist leer'); mapping := TEntityMappingDictionary.getMappingFor(T); result := T.Create; TEntity(result).Id := aQuery.FieldByName(mapping.Primary).AsInteger; for aktField in mapping.Fields do begin value := getValueFromDBField(aQuery, aktField); TReflectionManager.setPropertyValue(result, aktField.RttiProperty.Name, value); end; end; class function TEntityRepository.load<T>(aQueryBuilder: TQueryBuilder; aTransaction: TNfsTransaction = nil): T; var wasOpen: boolean; query: TNfsQuery; begin if (aTransaction = nil) then aTransaction := TDatabaseProvider.getDefaultTransaction; wasOpen := aTransaction.InTransaction; if not wasOpen then aTransaction.StartTransaction; query := aQueryBuilder.getQuery(nil, aTransaction); query.Open; result := TEntityRepository.load<T>(query); query.Close; query.Free; if not wasOpen then aTransaction.Commit; end; class function TEntityRepository.loadAll<T>( aTransaction: TNfsTransaction): TList<T>; var mapping : TEntityMapping; queryBuilder: TQueryBuilder; begin mapping := TEntityMappingDictionary.getMappingFor(T); queryBuilder := TQueryBuilder.select.from(mapping.Tablename); result := TEntityRepository.loadList<T>(queryBuilder, aTransaction); queryBuilder.free; end; class function TEntityRepository.loadList<T>(aQueryBuilder: TQueryBuilder; aTransaction: TNfsTransaction): TList<T>; var query: TNfsQuery; begin query := aQueryBuilder.getQuery(nil, aTransaction); result := TEntityRepository.loadList<T>(query); end; class function TEntityRepository.loadList<T>(aQuery: TDataset): TList<T>; var wasOpen: boolean; begin wasOpen := aQuery.Active; // TODO: Passt das mit der Transaction? if (not wasOpen) then begin aQuery.Open; end; result := TList<T>.Create; while (not aQuery.Eof) do begin result.Add(TEntityRepository.load<T>(aQuery)); aQuery.Next; end; if (not wasOpen) then begin aQuery.Close; end; end; class function TEntityRepository.new<T>: T; var mapping: TEntityMapping; begin result := T.Create; mapping := TEntityMappingDictionary.getMappingFor(T); TEntity(result).Id := TDatabaseUtility.getGeneratorValue(mapping.Generator, TDatabaseProvider.getDefaultTransaction); TEntity(result).IsNew := true; end; class procedure TEntityRepository.save(aEntity: TEntity; aTransaction: TNfsTransaction = nil); var queryBuilder: TQueryBuilder; mapping: TEntityMapping; aktFeld: TEntityField; query: TNfsQuery; wasOpen: boolean; begin if (not aEntity.IsDirty) and (not aEntity.IsNew) then exit; if (aTransaction = nil) then aTransaction := TDatabaseProvider.getDefaultTransaction; wasOpen := aTransaction.InTransaction; if not WasOpen then aTransaction.StartTransaction; mapping := TEntityMappingDictionary.getMappingFor(aEntity.ClassType); if (aEntity.IsNew) then queryBuilder := TQueryBuilder.insert.field(mapping.Primary, aEntity.Id) else queryBuilder := TQueryBuilder.update.where(mapping.Primary + ' = :id').param('id', aEntity.Id); queryBuilder .table(mapping.Tablename); for aktFeld in mapping.Fields do begin queryBuilder.field(aktFeld.Fieldname, aktFeld.RttiProperty.GetValue(aEntity)); // TODO: Geht nicht für Felder end; query := queryBuilder.getQuery(nil, aTransaction); query.Execute; query.Free; queryBuilder.Free; if not wasOpen then aTransaction.Commit; aEntity.IsDirty := false; aEntity.IsNew := false; end; { Table } constructor Table.Create(aTablename, aPrefix, aGenerator: string); begin _tablename := aTablename; _prefix := aPrefix; _generator := aGenerator; end; { Column } constructor Column.Create(aFieldname: string); begin _fieldname := aFieldname; end; { TEntity } function TEntity.updateV(var aAlterWert: string; aNeuerWert, aPropertyName: string): boolean; begin result := false; if (aAlterWert <> aNeuerWert) then begin aAlterWert := aNeuerWert; _dirty := true; PropertyChanged(aPropertyName); result := true; end; end; function TEntity.updateV(var aAlterWert: real; aNeuerWert: real; aPropertyName: string): boolean; begin result := false; if (aAlterWert <> aNeuerWert) then begin aAlterWert := aNeuerWert; _dirty := true; PropertyChanged(aPropertyName); result := true; end; end; function TEntity.updateV(var aAlterWert: integer; aNeuerWert: integer; aPropertyName: string): boolean; begin result := false; if (aAlterWert <> aNeuerWert) then begin aAlterWert := aNeuerWert; _dirty := true; PropertyChanged(aPropertyName); result := true; end; end; procedure TEntity.delete; begin TNfs.delete(self); end; procedure TEntity.save; begin TNfs.save(self); end; function TEntity.updateV(var aAlterWert: TDateTime; aNeuerWert: TDateTime; aPropertyName: string): boolean; begin result := false; if (aAlterWert <> aNeuerWert) then begin aAlterWert := aNeuerWert; _dirty := true; PropertyChanged(aPropertyName); result := true; end; end; function TEntity.updateV(var aAlterWert: boolean; aNeuerWert: boolean; aPropertyName: string): boolean; begin result := false; if (aAlterWert <> aNeuerWert) then begin aAlterWert := aNeuerWert; _dirty := true; PropertyChanged(aPropertyName); result := true; end; end; end.
{ Source by Prodigy - [#DELPHIX] - irc.brasnet.org } unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImageHlp, StdCtrls, FileCtrl; type TForm1 = class(TForm) DriveComboBox1: TDriveComboBox; DirectoryListBox1: TDirectoryListBox; FileListBox1: TFileListBox; FilterComboBox1: TFilterComboBox; Memo1: TMemo; procedure FileListBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } List: TStrings; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure ListDLLFunctions(DLLName: String; List: TStrings); type chararr = array [0..$FFFFFF] of Char; var H: THandle; I, fc: integer; st: string; arr: Pointer; ImageDebugInformation: PImageDebugInformation; begin List.Clear; DLLName := ExpandFileName(DLLName); if FileExists(DLLName) then begin H := CreateFile(PChar(DLLName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if H<>INVALID_HANDLE_VALUE then try ImageDebugInformation := MapDebugInformation(H, PChar(DLLName), nil, 0); if ImageDebugInformation<>nil then try arr := ImageDebugInformation^.ExportedNames; fc := 0; for I := 0 to ImageDebugInformation^.ExportedNamesSize - 1 do if chararr(arr^)[I]=#0 then begin st := PChar(@chararr(arr^)[fc]); if Length(st)>0 then List.Add(st); if (I>0) and (chararr(arr^)[I-1]=#0) then Break; fc := I + 1 end finally UnmapDebugInformation(ImageDebugInformation) end finally CloseHandle(H) end end end; procedure TForm1.FileListBox1Change(Sender: TObject); var Arquivo: String; I: integer; S: String; begin if FileListBox1.ItemIndex <> -1 then begin Arquivo := FileListBox1.FileName; Memo1.Lines.Clear; ListDLLFunctions(Arquivo, List); S := 'Lista de funções encontrada:'; for I := 0 to List.Count - 1 do S := S + #13#10 + List[I]; Memo1.Lines.Add(S); Memo1.Lines.Add('-------------------------------'); Memo1.Lines.Add('Número de funções: '+ IntToStr(List.Count)); end; end; procedure TForm1.FormCreate(Sender: TObject); begin List := TStringList.Create; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin List.Free; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: DataModule 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 UDataModule; {$MODE Delphi} interface uses SysUtils, Classes, DB, BufDataset, ImgList, Controls, Dialogs, Variants, Tipos, Graphics, ACBrSpedContabil, folderlister, ACBrNFe, ACBrBoleto, ACBrBoletoFCFortesFr, ACBrBase; type { TFDataModule } TFDataModule = class(TDataModule) ACBrBoletoFCFortes1: TACBrBoletoFCFortes; ACBrBoletoFCFR: TACBrBoletoFCFortes; ACBrNFe: TACBrNFe; ACBrNFe1: TACBrNFe; ACBrSPEDContabil: TACBrSPEDContabil; SaveDialog: TSaveDialog; OpenDialog: TOpenDialog; ImagensCadastros: TImageList; ImagensCadastrosD: TImageList; ImagemPadrao: TImageList; ACBrBoleto: TACBrBoleto; ImagensCheck: TImageList; CDSLookup: TBufDataSet; DSLookup: TDataSource; Folder: TSelectDirectoryDialog; private { Private declarations } public { Public declarations } end; var FDataModule: TFDataModule; implementation {$R *.lfm} { TFDataModule } end.
unit API_Parse; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs ,IdHTTP ,IdSSLOpenSSL ,API_MVC ,API_DBases ,API_Threads, Vcl.Grids, Vcl.StdCtrls; type TParser = class private FMySQLEngine: TMySQLEngine; FHTTP: TIdHTTP; FIdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL; FParserID: integer; FParserName: string; function GetParserId: Integer; procedure HTTPInit; procedure SetLinkHandledValue(aLinkId, aValue: integer); public constructor Create(aDBEngine: TMySQLEngine; aParserName: string); overload; constructor Create; overload; destructor Destroy; override; function GetHTMLByLinkId(aLinkId: integer): string; function PostHTMLByLinkId(aLinkId: integer): string; function GetHTMLByURL(aURL: string; aPostData: TStringList = nil): string; function GetLinkLevel(aLinkId: integer): integer; function AddLink(aLevel: integer; aLink: String; aParentLinkID: Integer; aParentNum: integer; aIsPost: Boolean = False): integer; function GetLinkToProcess(out aLinkId: Integer; out alevel: Integer; out aIsPost: Boolean; out aLinkCount: Integer; out aHandledCount: integer; aThreadNum: Integer=1): Boolean; function GetLinkById(aLinkId: Integer): string; function GetValueByKey(aLinkId: Integer; aKey: string; out alevel: integer; aNum: integer = 1): String; function GetArrayByKey(aLinkId: Integer; aKey: string; aNum: integer = 1): TArray<string>; function GetRedirectedUrl(aURL: string): String; function GetLinkParentNum(aLinkId: integer): integer; procedure AddData(aLinkId, aRecordNum: Integer; aKey, aValue: string); procedure ParserInit; procedure WriteErrorLog(aLinkID: integer; aFunction, aIParams, aEMessage: string); end; TParseTool = class public class function MultiParseByKey(aPage:string; aFirstKey:string; aLastKey:string): TArray<string>; {class function ParseByKey(aPage:string; aFirstKey:string; aLastKey:string; aFirstKeyCount:integer = 0): string;} class function ParseByKeyReverse(aPage: string; aFirstKey: string; aLastKey: string; aFirstKeyCount: Integer): string; class function Explode(aIncome: string; aDelimiter: string): TArray<string>; class function Inplode(aIncome: TArray<string>; aDelimiter: string; aFirstIndex: integer=0; aLastIndex: integer=0): string; {class function RemoveTags(aIncome: string): string;} class function CutBetween(aIncome, aFirstKey, aLastKey: string): string; class function TranslitRus2Lat(const Str: string): string; end; TParseMethod = procedure(aLinkId: integer; aPage: string) of object; TModelParse = class abstract(TModelThread) private procedure SetZeroAndStartLinks; protected FParseMethod: TParseMethod; FParser: TParser; FLevelForCustomerAddRecord: Integer; procedure InitParserData; virtual; abstract; procedure DeinitParserData; virtual; procedure SetParseMethods(aLevel: Integer); virtual; abstract; procedure SetStartLinks(aLinkID: integer); virtual; abstract; procedure CustomerTableAddRecord(aLinkId: integer); virtual; public procedure ModelInitForThreads; override; procedure Execute; override; end; TParserInfo = record Name: string; Num: Integer; StartMessage: string; end; TViewParse = class(TViewAbstract) ParsersGrid: TStringGrid; btnStop: TButton; btnStart: TButton; procedure btnStartClick(Sender: TObject); private { Private declarations } procedure InitParserGrid; protected FParsersList: TArray<TParserInfo>; procedure SetParsers; virtual; abstract; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure UpdateCountersInGrid(aParserNum, aLinkCount, aHandledCount: integer); property ParsersList: TArray<TParserInfo> read FParsersList; end; TParserStateModel = class(TModelAbstract) public procedure Execute; override; end; implementation {$R *.dfm} uses System.StrUtils ,System.Threading ,API_Files ,FireDAC.Comp.Client ,FireDAC.Stan.Param ,Data.DB; function TParser.PostHTMLByLinkId(aLinkId: Integer): string; var Link, tx: string; Rows: TArray<string>; Row: string; PostData: TStringList; begin tx:=GetLinkById(aLinkId); Link:=TParseTool.ParseByKey(tx, '', '?'); tx:=TParseTool.ParseByKey(tx, '?', ''); Rows:=TParseTool.Explode(tx, '&'); PostData:=TStringList.Create; try for Row in Rows do begin PostData.Add(Row); end; Result := GetHTMLByURL(Link, PostData); finally PostData.Free; end; if Result='HTTP_READ_ERROR' then SetLinkHandledValue(aLinkId, -1) else SetLinkHandledValue(aLinkId, 2); end; function TParser.GetLinkParentNum(aLinkId: integer): integer; var sql: string; dsQuery: TFDQuery; begin dsQuery:=TFDQuery.Create(nil); try sql:='select parent_num from links where id=:id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('id').AsInteger:=aLinkId; FMySQLEngine.OpenQuery(dsQuery); Result:=dsQuery.FieldByName('parent_num').AsInteger; finally dsQuery.Free; end; end; class function TParseTool.TranslitRus2Lat(const Str: string): string; const RArrayL = 'абвгдеЄжзийклмнопрстуфхцчшщьыъэю€'; RArrayU = 'јЅ¬√ƒ≈®∆«»… ЋћЌќѕ–—“”‘’÷„Ўў№џЏЁёя'; colChar = 33; arr: array[1..2, 1..ColChar] of string = (('a', 'b', 'v', 'g', 'd', 'e', 'yo', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'kh', 'ts', 'ch', 'sh', 'shch', '''', 'y', '''', 'e', 'yu', 'ya'), ('A', 'B', 'V', 'G', 'D', 'E', 'Yo', 'Zh', 'Z', 'I', 'Y', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'Kh', 'Ts', 'Ch', 'Sh', 'Shch', '''', 'Y', '''', 'E', 'Yu', 'Ya')); var i: Integer; LenS: Integer; p: integer; d: byte; begin result := ''; LenS := length(str); for i := 1 to lenS do begin d := 1; p := pos(str[i], RArrayL); if p = 0 then begin p := pos(str[i], RArrayU); d := 2 end; if p <> 0 then result := result + arr[d, p] else result := result + str[i]; //если не русска€ буква, то берем исходную end; end; procedure TModelParse.DeinitParserData; begin end; procedure TViewParse.UpdateCountersInGrid(aParserNum, aLinkCount, aHandledCount: integer); begin ParsersGrid.Cells[2, aParserNum] := IntToStr(aLinkCount); ParsersGrid.Cells[3, aParserNum] := IntToStr(aHandledCount); end; procedure TParserStateModel.Execute; var Parcer: TParser; LinkId, Level, LinkCount, HandledCount: Integer; IsPost: Boolean; begin Parcer := TParser.Create(TMySQLEngine(FDBEngine), FData.Items['ParserName']); try Parcer.GetLinkToProcess(LinkId, Level, IsPost, LinkCount, HandledCount); Self.FEventData.AddOrSetValue('LinkCount', LinkCount); Self.FEventData.AddOrSetValue('HandledCount', HandledCount); Self.FEventData.AddOrSetValue('ParserNum', FData.Items['ParserNum']); Self.GenerateEvent('UpdateGrid'); finally Parcer.Free; end; end; procedure TViewParse.InitParserGrid; var Parser: TParserInfo; i: Integer; begin ParsersGrid.Cells[0,0]:='parser'; ParsersGrid.Cells[1,0]:='status'; ParsersGrid.Cells[2,0]:='links count'; ParsersGrid.Cells[3,0]:='handled links'; ParsersGrid.Cells[4,0]:=''; i:=0; for Parser in FParsersList do begin Inc(i); if i>1 then ParsersGrid.RowCount:=ParsersGrid.RowCount+1; ParsersGrid.Cells[0, Parser.Num] := Parser.Name; ParsersGrid.Cells[1, Parser.Num] := 'not working'; end; end; procedure TModelParse.CustomerTableAddRecord(aLinkId: integer); begin end; class function TParseTool.CutBetween(aIncome, aFirstKey, aLastKey: string): string; var FirstIndx, LastIndx, CutLength: Integer; begin FirstIndx:=Pos(aFirstKey, aIncome); while FirstIndx>0 do begin LastIndx:=PosEx(aLastKey, aIncome, FirstIndx); if LastIndx>0 then CutLength:=LastIndx-FirstIndx+Length(aLastKey) else Break; Delete(aIncome, FirstIndx, CutLength); FirstIndx:=Pos(aFirstKey, aIncome); end; Result:=aIncome; end; procedure TModelParse.SetZeroAndStartLinks; var LinkId: Integer; begin LinkId:=FParser.AddLink(0, FData.Items['ZeroLink'], 0, 0); FDBEngine.SetData('update links set handled=2 where id='+LinkId.ToString); SetStartLinks(LinkId); end; procedure TModelParse.ModelInitForThreads; begin InitParserData; DeinitParserData; FParser := TParser.Create(TMySQLEngine(FDBEngine), FData.Items['ParserName']); try FParser.ParserInit; finally FParser.Free; end; end; procedure TModelParse.Execute; var Level: Integer; LinkId: Integer; LinkCount: Integer; HandledCount: Integer; Page: string; i: Integer; isPost: Boolean; isProcessing: Boolean; begin InitParserData; i:=0; FParser := TParser.Create(TMySQLEngine(FDBEngine), FData.Items['ParserName']); try isProcessing := True; while isProcessing do begin // запрос на LinkId выполн€ем в главном потоке, чтобы дочерние потоки не хватали одну ссылку одновременно TThread.Synchronize(nil, procedure() begin isProcessing := FParser.GetLinkToProcess(LinkId, Level, isPost, LinkCount, HandledCount, FThreadNum) end ); inc(i); if LinkCount>0 then begin FEventData.AddOrSetValue('LinkCount',IntToStr(LinkCount)); FEventData.AddOrSetValue('HandledCount',IntToStr(HandledCount)); FEventData.AddOrSetValue('ParserNum', FData.Items['ParserNum']); Self.GenerateEvent('UpdateGrid'); end; if Level=0 then SetZeroAndStartLinks else begin FParseMethod:=nil; SetParseMethods(Level); end; if (LinkId>0) and (Level>0) then begin if isPost then Page:=FParser.PostHTMLByLinkId(LinkId) else Page:=FParser.GetHTMLByLinkId(LinkId); FParseMethod(LinkId, Page); if FLevelForCustomerAddRecord=level then try CustomerTableAddRecord(LinkId); except On E : Exception do begin // log FParser.WriteErrorLog(LinkId, 'CustomerTableAddRecord', '', E.Message); end; end; end; end; finally FParser.Free; DeinitParserData; end; end; procedure TParser.WriteErrorLog(aLinkID: integer; aFunction, aIParams, aEMessage: string); var sql: string; dsQuery: TFDQuery; begin sql:='insert into errors set'; sql:=sql+' e_datetime=now()'; sql:=sql+',project_id=:project_id'; sql:=sql+',link_id=:link_id'; sql:=sql+',function=:function'; sql:=sql+',input_params=:input_params'; sql:=sql+',e_message=:e_message'; dsQuery:=TFDQuery.Create(nil); try dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; if aLinkID=0 then dsQuery.ParamByName('link_id').Clear else dsQuery.ParamByName('link_id').AsInteger:=aLinkID; dsQuery.ParamByName('link_id').DataType:=ftInteger; dsQuery.ParamByName('function').AsString:=aFunction; dsQuery.ParamByName('input_params').AsString:=aIParams; dsQuery.ParamByName('e_message').AsString:=aEMessage; FMySQLEngine.ExecQuery(dsQuery); finally dsQuery.Free; end; end; function TParser.GetParserId: Integer; var sql: string; dsQuery: TFDQuery; begin Result:=-1; sql:='select id from projects where name='+FMySQLEngine.StrToSQL(FParserName); dsQuery:=TFDQuery.Create(nil); try FMySQLEngine.GetData(dsQuery,sql); if not dsQuery.IsEmpty then Result:=dsQuery.FieldByName('id').AsInteger finally dsQuery.Free; end; end; procedure TParser.ParserInit; var sql: string; dsQuery: TFDQuery; begin dsQuery:=TFDQuery.Create(nil); try if FParserID=-1 then begin FMySQLEngine.SetData('insert into projects set name='+FMySQLEngine.StrToSQL(FParserName)); FParserID:=FMySQLEngine.GetLastInsertedId; end; sql:=Format('update links set handled=NULL where project_id=%d and handled=1', [FParserID]); FMySQLEngine.SetData(sql); finally dsQuery.Free end; end; procedure TParser.SetLinkHandledValue(aLinkId, aValue: integer); var dsQuery: TFDQuery; sql: string; begin dsQuery:=TFDQuery.Create(nil); try sql:='update links set handled=:value where id=:id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('id').AsInteger:=aLinkId; dsQuery.ParamByName('value').AsInteger:=aValue; FMySQLEngine.ExecQuery(dsQuery); finally dsQuery.Free; end; end; procedure TParser.HTTPInit; begin if Assigned(FHTTP) then FreeAndNil(FHTTP); if Assigned(FIdSSLIOHandlerSocketOpenSSL) then FreeAndNil(FIdSSLIOHandlerSocketOpenSSL); FHTTP := TIdHTTP.Create; FHTTP.HandleRedirects:=True; FHTTP.Request.UserAgent:='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36'; FIdSSLIOHandlerSocketOpenSSL:=TIdSSLIOHandlerSocketOpenSSL.Create; FHTTP.IOHandler:=FIdSSLIOHandlerSocketOpenSSL; end; {function TParseTool.RemoveTags(aIncome: string): string; var tx, tag:string; i,t: integer; begin t:=0; tag:=''; tx:=aIncome; for i:=1 to length(aIncome) do begin if aIncome[i]='<' then t:=1; if t=1 then tag:=tag+aIncome[i]; if aIncome[i]='>' then begin tx:=StringReplace(tx,tag,'',[rfReplaceAll, rfIgnoreCase]); t:=0; tag:=''; end; end; while Pos(#$A+#$A, tx)>0 do tx:=StringReplace(tx,#$A+#$A,#$A,[rfReplaceAll, rfIgnoreCase]); Result:=tx; end;} function TParser.GetHTMLByURL(aURL: string; aPostData: TStringList = nil): string; var i: Integer; begin i:=0; while i<11 do begin try Inc(i); if aPostData=nil then Result := FHTTP.get(aURL) else Result := FHTTP.Post(aURL, aPostData); Exit(Result); except On E : Exception do begin // log WriteErrorLog(0, 'GetHTMLByURL', aURL, E.Message); HTTPInit; end; end; end; Result:='HTTP_READ_ERROR'; end; function TParser.GetRedirectedUrl(aURL: string): String; begin Result:=''; FHTTP.HandleRedirects:=False; try FHTTP.Get(aURL); except on E: EIdHTTPProtocolException do Result := FHTTP.Response.Location; end; FHTTP.HandleRedirects:=True; end; class function TParseTool.Inplode(aIncome: TArray<string>; aDelimiter: string; aFirstIndex: integer=0; aLastIndex: integer=0): string; var i:integer; tx:string; begin Result:=''; if aLastIndex=0 then aLastIndex:=Length(aIncome); for i:=aFirstIndex to aLastIndex-1 do begin if i>aFirstIndex then Result:=Result+aDelimiter; Result:=Result+aIncome[i]; end; end; function TParser.GetArrayByKey(aLinkId: Integer; aKey: string; aNum: integer = 1): TArray<string>; var sql: string; dsQuery: TFDQuery; LinkId: integer; Num: Integer; IsProcess: Boolean; IsSkip: Boolean; begin Result:=[]; LinkId:=aLinkId; Num:=aNum; IsProcess:=True; IsSkip:=False; dsQuery:=TFDQuery.Create(nil); try while IsProcess do begin if not IsSkip then begin sql:='select `value`, level from `records`'; sql:=sql+' join links on links.id=`records`.link_id'; sql:=sql+' where link_id=:link_id and `key`=:key and num=:num'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('key').AsString:=aKey; dsQuery.ParamByName('link_id').AsInteger:=LinkId; dsQuery.ParamByName('num').AsInteger:=Num; FMySQLEngine.OpenQuery(dsQuery); dsQuery.FetchAll; while not dsQuery.Eof do begin Result:=Result+[dsQuery.FieldByName('value').AsString]; dsQuery.Next; end; end; if (dsQuery.RecordCount>0) and not IsSkip then IsProcess:=False else begin sql:='select l2.id, l1.parent_num, l1.`level` as lv1, l2.`level` as lv2 from links l1'; sql:=sql+' join links l2 on l2.id=l1.parent_link_id'; sql:=sql+' where l1.id=:id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('id').AsInteger:=LinkId; FMySQLEngine.OpenQuery(dsQuery); if dsQuery.FieldByName('id').AsInteger>0 then begin LinkId:=dsQuery.FieldByName('id').AsInteger; Num:=dsQuery.FieldByName('parent_num').AsInteger; if dsQuery.FieldByName('lv1').AsInteger=dsQuery.FieldByName('lv2').AsInteger then IsSkip:=True else IsSkip:=False; end else IsProcess:=False; end; end; finally dsQuery.Free; end; end; class function TParseTool.ParseByKeyReverse(aPage: string; aFirstKey: string; aLastKey: string; aFirstKeyCount: Integer): string; var i: integer; begin if Pos(aFirstKey, aPage)>0 then begin for i:=0 to aFirstKeyCount do begin Delete(aPage, Pos(aFirstKey, aPage), Length(aPage)); end; for i:=Length(aPage)-1 downto 0 do begin if Copy(aPage, i, Length(aLastKey))=aLastKey then break; end; if i>0 then Delete(aPage, 1, i+Length(aLastKey)-1) else aPage:=''; Result:=Trim(aPage); end else Result:=''; end; function TParser.GetValueByKey(aLinkId: Integer; aKey: string; out alevel: integer; aNum: integer = 1): String; var sql: string; dsQuery: TFDQuery; LinkId: integer; Num: Integer; IsProcess: Boolean; IsSkip: Boolean; begin Result:=''; LinkId:=aLinkId; Num:=aNum; IsProcess:=True; IsSkip:=False; dsQuery:=TFDQuery.Create(nil); try while IsProcess do begin if not IsSkip then begin sql:='select `value`, level from `records`'; sql:=sql+' join links on links.id=`records`.link_id'; sql:=sql+' where link_id=:link_id and `key`=:key and num=:num'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('key').AsString:=aKey; dsQuery.ParamByName('link_id').AsInteger:=LinkId; dsQuery.ParamByName('num').AsInteger:=Num; FMySQLEngine.OpenQuery(dsQuery); if not dsQuery.FieldByName('value').IsNull then begin Result:=dsQuery.FieldByName('value').AsString; alevel:=dsQuery.FieldByName('level').AsInteger; end; end; if (dsQuery.RecordCount>0) and not IsSkip then IsProcess:=False else begin sql:='select l2.id, l1.parent_num, l1.`level` as lv1, l2.`level` as lv2 from links l1'; sql:=sql+' join links l2 on l2.id=l1.parent_link_id'; sql:=sql+' where l1.id=:id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('id').AsInteger:=LinkId; FMySQLEngine.OpenQuery(dsQuery); if dsQuery.FieldByName('id').AsInteger>0 then begin LinkId:=dsQuery.FieldByName('id').AsInteger; Num:=dsQuery.FieldByName('parent_num').AsInteger; if dsQuery.FieldByName('lv1').AsInteger=dsQuery.FieldByName('lv2').AsInteger then IsSkip:=True else IsSkip:=False; end else IsProcess:=False; end; end; finally dsQuery.Free; end; end; function TParser.GetLinkById(aLinkId: Integer): string; var sql: string; dsQuery: TFDQuery; begin dsQuery:=TFDQuery.Create(nil); try sql:='select link from links where id=:id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('id').AsInteger:=aLinkId; FMySQLEngine.OpenQuery(dsQuery); Result:=dsQuery.FieldByName('link').AsString; finally dsQuery.Free; end; end; function TParser.GetLinkToProcess(out aLinkId: Integer; out alevel: Integer; out aIsPost: Boolean; out aLinkCount: Integer; out aHandledCount: integer; aThreadNum: Integer=1): Boolean; var sql: string; dsQuery: TFDQuery; UnHandledCount: integer; begin dsQuery:=TFDQuery.Create(nil); try if aThreadNum = 1 then begin sql:='select count(*) as link_count from links where project_id=:project_id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; FMySQLEngine.OpenQuery(dsQuery); aLinkCount:=dsQuery.FieldByName('link_count').AsInteger; sql:='select count(*) as unhandled_count from links where handled is null'; sql:=sql+' and project_id=:project_id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; FMySQLEngine.OpenQuery(dsQuery); UnHandledCount:=dsQuery.FieldByName('unhandled_count').AsInteger; aHandledCount:=aLinkCount-UnHandledCount; end; if (aLinkCount>1) and (UnHandledCount=0) then Result:=False else begin Result:=True; sql:='select id, level, is_post from links'; sql:=sql+' where project_id=:project_id'; sql:=sql+' and handled is null'; sql:=sql+' order by level desc, id'; sql:=sql+' limit :limit, 1'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; dsQuery.ParamByName('limit').AsInteger:=aThreadNum-1; FMySQLEngine.OpenQuery(dsQuery); aLinkId:=dsQuery.FieldByName('id').AsInteger; alevel:=dsQuery.FieldByName('level').AsInteger; aIsPost:=Boolean(dsQuery.FieldByName('is_post').AsInteger); if (dsQuery.IsEmpty) and (aThreadNum>1) then alevel := -1; // дл€ потока нет доступной ссылки, пропускаем итерацию SetLinkHandledValue(aLinkId, 1); end; finally dsQuery.Free; end; end; function TParser.AddLink(aLevel: integer; aLink: String; aParentLinkID: Integer; aParentNum: integer; aIsPost: Boolean = False): integer; var sql: string; dsQuery: TFDQuery; begin Result:=0; dsQuery:=TFDQuery.Create(nil); try sql:='select * from links where link_hash=md5(:link) and project_id=:project_id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; dsQuery.ParamByName('link').AsString:=aLink; FMySQLEngine.OpenQuery(dsQuery); if not dsQuery.IsEmpty then exit; sql:='insert into links set'; sql:=sql+' project_id=:project_id'; sql:=sql+',level=:level'; sql:=sql+',link=:link'; sql:=sql+',parent_link_id=:parent_link_id'; sql:=sql+',parent_num=:parent_num'; sql:=sql+',link_hash=md5(:link)'; sql:=sql+',is_post=:is_post'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; dsQuery.ParamByName('level').AsInteger:=aLevel; dsQuery.ParamByName('link').AsString:=aLink; dsQuery.ParamByName('parent_link_id').DataType:=ftInteger; if aParentLinkID>0 then dsQuery.ParamByName('parent_link_id').AsInteger:=aParentLinkID else dsQuery.ParamByName('parent_link_id').Clear; dsQuery.ParamByName('parent_num').DataType:=ftInteger; if aParentNum>0 then dsQuery.ParamByName('parent_num').AsInteger:=aParentNum else dsQuery.ParamByName('parent_num').Clear; dsQuery.ParamByName('is_post').DataType:=ftInteger; if aIsPost then dsQuery.ParamByName('is_post').AsInteger:=1 else dsQuery.ParamByName('is_post').Clear; try FMySQLEngine.ExecQuery(dsQuery); except On E : Exception do begin // log WriteErrorLog(aParentLinkID, 'AddLink', aLink, E.Message); Exit; end; end; Result:=FMySQLEngine.GetLastInsertedId; finally dsQuery.Free; end; end; procedure TParser.AddData(aLinkId: Integer; aRecordNum: Integer; aKey: string; aValue: string); var sql: string; dsQuery: TFDQuery; begin dsQuery:=TFDQuery.Create(nil); try sql:='insert into records set'; sql:=sql+' `link_id`=:link_id'; sql:=sql+',`num`=:num'; sql:=sql+',`key`=:key'; sql:=sql+',`value`=:value'; sql:=sql+',`value_hash`=md5(:value)'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('link_id').AsInteger:=aLinkId; dsQuery.ParamByName('num').AsInteger:=aRecordNum; dsQuery.ParamByName('key').AsString:=aKey; dsQuery.ParamByName('value').AsWideString:=aValue; try FMySQLEngine.ExecQuery(dsQuery); except On E : Exception do begin // log WriteErrorLog(aLinkId, 'AddData', aKey+': '+aValue, E.Message); Exit; end; end; finally dsQuery.Free; end; end; function TParser.GetLinkLevel(aLinkID: Integer): integer; var dsQuery: TFDQuery; sql: string; begin Result:=-1; dsQuery:=TFDQuery.Create(nil); try sql:='select level from links where project_id=:project_id and id=:id'; dsQuery.SQL.Text:=sql; dsQuery.ParamByName('project_id').AsInteger:=FParserID; dsQuery.ParamByName('id').AsInteger:=aLinkID; FMySQLEngine.OpenQuery(dsQuery); Result:=dsQuery.FieldByName('level').AsInteger; finally dsQuery.Free; end; end; {class function TParseTool.ParseByKey(aPage:string; aFirstKey:string; aLastKey:string; aFirstKeyCount:integer = 0): string; var tx:string; i:integer; begin if aFirstKey.Length=0 then begin aFirstKey:='!#!'; aPage:='!#!'+aPage; end; for i:=1 to aFirstKeyCount-1 do begin Delete(aPage, 1, Pos(aFirstKey, aPage) + Length(aFirstKey)); end; if Pos(aFirstKey, aPage)>0 then begin tx:=Copy(aPage, Pos(aFirstKey, aPage) + Length(aFirstKey), Length(aPage)); Delete(tx, Pos(aLastKey, tx), Length(tx)); tx:=Trim(tx); end; Result:=tx; end;} class function TParseTool.MultiParseByKey(aPage: string; aFirstKey: string; aLastKey: string): TArray<string>; var RowData: TArray<string>; RowNum: integer; tx: string; begin RowNum:=0; while Pos(aFirstKey, aPage)>0 do begin Inc(RowNum); SetLength(RowData, RowNum); tx:=Copy(aPage, Pos(aFirstKey, aPage) + Length(aFirstKey), Length(aPage)); Delete(tx, Pos(aLastKey, tx), Length(tx)); RowData[RowNum-1]:=Trim(tx); Delete(aPage, 1, Pos(aFirstKey, aPage) + Length(aFirstKey)); Delete(aPage, 1, Pos(aLastKey, aPage)); end; Result:=RowData; end; constructor TParser.Create; begin inherited Create; HTTPInit; end; constructor TParser.Create(aDBEngine: TMySQLEngine; aParserName: string); var sql: string; dsQuery: TFDQuery; begin inherited Create; HTTPInit; FMySQLEngine:=aDBEngine; FParserName:=aParserName; FParserID:=Self.GetParserId; end; destructor TParser.Destroy; begin FHTTP.Free; FIdSSLIOHandlerSocketOpenSSL.Free; inherited; end; function TParser.GetHTMLByLinkId(aLinkId: integer): string; var Link: string; begin Link:=GetLinkById(aLinkId); Result := GetHTMLByURL(Link); if Result='HTTP_READ_ERROR' then SetLinkHandledValue(aLinkId, -1) else SetLinkHandledValue(aLinkId, 2); end; class function TParseTool.Explode(aIncome: string; aDelimiter: string): TArray<string>; var i: integer; tx: string; begin tx:=''; for i := 1 to Length(aIncome) do begin if (aIncome[i]<>aDelimiter) then tx:=tx+aIncome[i]; if (aIncome[i]=aDelimiter) or (i=Length(aIncome)) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1]:=Trim(tx); tx:=''; end; end; end; procedure TViewParse.btnStartClick(Sender: TObject); begin btnStart.Enabled:=False; btnStop.Enabled:=True; ParsersGrid.Cells[1, ParsersGrid.Row]:='working'; SendViewMessage(FParsersList[ParsersGrid.Row-1].StartMessage); end; constructor TViewParse.Create(AOwner: TComponent); begin inherited; SetParsers; InitParserGrid; end; end.
unit CompileErrorManager; interface uses SysUtils,Windows,Classes,StdCtrls,COW_RunTime,Graphics; type ISourceEditor=interface(IInterfaceComponentReference) ['{70D607DE-2DBA-40A9-8186-B7FD1F9D5ED1}'] procedure MarkCompileError(CharOffset,CharLength:Integer); procedure MarkExecuteError(CharOffset,CharLength:Integer); procedure MarkWarning(CharOffset,CharLength:Integer); function GetCode:string; end; TErrorType=(etParse,etCompile,etWarning); TErrorData=record ErrorType:TErrorType; CharOffset,CharLength:Integer; Message:string; end; PErrorData=^TErrorData; TCompileErrorManager=class(TCustomListBox,IParserExceptionHandler,IExecuterExceptionHandler) private FSourceEditor: ISourceEditor; procedure SetSourceEditor(const Value: ISourceEditor); function GetError(Index: Integer): TErrorData; function GetErrorCount: Integer; protected procedure Notification(AComponent:TComponent;Operation:TOperation);override; procedure RaiseException(SoftMode:Boolean;AParser:IParser;ALexer:ILexer;ABuffer:ICharBuffer;AFound:Word;AExpected:array of Word;DefError:string);overload; function RaiseException(ExceptionObject:TObject;CharOffset:Cardinal):Boolean;overload; function RaiseUnknownException(CharOffset:Cardinal):Boolean; procedure BeforeCompile; procedure AfterCompile; procedure MeasureItem(Index:Integer;var Height:Integer);override; procedure DrawItem(Index:Integer;Rect:TRect;State:TOwnerDrawState);override; procedure DblClick;override; procedure DestroyWND;override; public constructor Create(AOwner:TComponent);override; procedure AddError(ErrorType:TErrorType;CharOffset,CharLength:Integer;Message:string); procedure Clear;override; property ErrorCount:Integer read GetErrorCount; property Error[Index:Integer]:TErrorData read GetError; destructor Destroy;override; published property SourceEditor:ISourceEditor read FSourceEditor write SetSourceEditor; property Align; property BevelKind; property BorderStyle; property Anchors; end; implementation { TCompileErrorManager } procedure TCompileErrorManager.AddError(ErrorType: TErrorType; CharOffset, CharLength: Integer; Message: string); var p:PErrorData; begin New(p); p.ErrorType:=ErrorType; p.CharOffset:=CharOffset; p.CharLength:=CharLength; p.Message:=Message; Items.AddObject(Message,TObject(p)); if Assigned(FSourceEditor) then case ErrorType of etParse:FSourceEditor.MarkCompileError(CharOffset,CharLength); etCompile:FSourceEditor.MarkExecuteError(CharOffset,CharLength); etWarning:FSourceEditor.MarkWarning(CharOffset,CharLength); end; end; procedure TCompileErrorManager.AfterCompile; begin end; procedure TCompileErrorManager.BeforeCompile; begin while Items.Count>0 do begin Dispose(PErrorData(Items.Objects[0])); Items.Delete(0); end; end; procedure TCompileErrorManager.Clear; var a:Integer; begin for a:=0 to Items.Count-1 do Dispose(PErrorData(Items.Objects[a])); inherited; end; constructor TCompileErrorManager.Create(AOwner: TComponent); begin inherited; Style:=lbOwnerDrawVariable; Color:=0; end; procedure TCompileErrorManager.DblClick; begin inherited; if (ItemIndex>-1) and (ItemIndex<Items.Count) and Assigned(FSourceEditor) then with PErrorData(Items.Objects[ItemIndex])^ do case ErrorType of etParse:FSourceEditor.MarkCompileError(CharOffset,CharLength); etCompile:FSourceEditor.MarkExecuteError(CharOffset,CharLength); etWarning:FSourceEditor.MarkWarning(CharOffset,CharLength); end; end; destructor TCompileErrorManager.Destroy; begin FSourceEditor:=nil; inherited; end; procedure TCompileErrorManager.DestroyWND; begin Clear; inherited; end; procedure TCompileErrorManager.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); var a:Integer; s:string; begin with Canvas,PErrorData(Items.Objects[Index])^ do begin case ErrorType of etParse,etCompile:begin Brush.Color:=RGB(150,0,0); Font.Color:=clWhite; end; etWarning:begin Brush.Color:=RGB(150,100,0); Font.Color:=clWhite; end; end; if Index=ItemIndex then begin case ErrorType of etParse,etCompile:Pen.Color:=RGB(255,100,100); etWarning:Pen.Color:=RGB(255,150,100); end; Rectangle(Rect); end else FillRect(Rect); Font.Name:=Self.Font.Name; Font.Size:=Self.Font.Size; Font.Style:=[fsBold]; case ErrorType of etParse:s:='Syntax error'; etCompile:s:='Fatal error'; etWarning:s:='Warning'; end; s:=s+' : '; TextOut(Rect.Left+2,Rect.Top+2,s); a:=TextWidth(s); Font.Style:=[]; TextOut(Rect.Left+a+2,Rect.Top+2,Message); if Focused and (Index=ItemIndex) then DrawFocusRect(Rect); end; end; function TCompileErrorManager.GetError(Index: Integer): TErrorData; begin Result:=PErrorData(Items.Objects[Index])^; end; function TCompileErrorManager.GetErrorCount: Integer; begin Result:=Items.Count; end; procedure TCompileErrorManager.MeasureItem(Index: Integer; var Height: Integer); begin Height:=2*Abs(Font.Size)+2; end; procedure TCompileErrorManager.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FSourceEditor) and (AComponent=FSourceEditor.GetComponent) then FSourceEditor:=nil; inherited; end; procedure TCompileErrorManager.RaiseException(SoftMode: Boolean; AParser: IParser; ALexer: ILexer; ABuffer: ICharBuffer; AFound: Word; AExpected: array of Word; DefError: string); begin AddError(etParse,ALexer.LastLexerPos,ALexer.LexerPos-ALexer.LastLexerPos,DefError); if not SoftMode then raise Exception.Create(DefError); end; function TCompileErrorManager.RaiseException(ExceptionObject: TObject; CharOffset: Cardinal): Boolean; begin if Assigned(ExceptionObject) and (ExceptionObject is Exception) then AddError(etCompile,CharOffset,0,(ExceptionObject as Exception).Message) else AddError(etCompile,CharOffset,0,'Unknown error'); Result:=False; end; function TCompileErrorManager.RaiseUnknownException( CharOffset: Cardinal): Boolean; begin AddError(etCompile,CharOffset,0,'Unknown error'); Result:=False; end; procedure TCompileErrorManager.SetSourceEditor(const Value: ISourceEditor); begin FSourceEditor := Value; if Assigned(FSourceEditor) then FSourceEditor.GetComponent.FreeNotification(Self); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Compiler.EnvironmentProvider; interface {$SCOPEDENUMS ON} uses System.Classes, DPM.Core.Types, DPM.Core.Logging, DPM.Core.Compiler.Interfaces; type //singleton, inject where needed. TCompilerEnvironmentProvider = class(TInterfacedObject, ICompilerEnvironmentProvider) private type TStatus = (unknown, found, notfound); private FLogger : ILogger; FFound : array[TCompilerVersion.UnknownVersion..TCompilerVersion.RS11_0] of TStatus; FRsVarFiles : array[TCompilerVersion.UnknownVersion..TCompilerVersion.RS11_0] of string; protected function FoundCompilerInfo(const compilerVersion : TCompilerVersion) : Boolean; function GetRsVarsFilePath(const compilerVersion : TCompilerVersion) : string; public constructor Create(const logger : ILogger); destructor Destroy; override; end; implementation uses System.Win.Registry, System.SysUtils, WinApi.Windows; { TCompilerEnvironmentProvider } constructor TCompilerEnvironmentProvider.Create(const logger : ILogger); begin FLogger := logger; end; destructor TCompilerEnvironmentProvider.Destroy; begin inherited; end; function TCompilerEnvironmentProvider.FoundCompilerInfo(const compilerVersion : TCompilerVersion) : Boolean; begin result := FFound[compilerVersion] = TStatus.found; end; function TCompilerEnvironmentProvider.GetRsVarsFilePath(const compilerVersion : TCompilerVersion) : string; var bdsVersion : string; key : string; reg : TRegistry; rootDir : string; begin result := ''; case FFound[compilerVersion] of TStatus.found : begin result := FRsVarFiles[compilerVersion]; exit; end; TStatus.notfound : exit; TStatus.unknown : begin bdsVersion := CompilerToBDSVersion(compilerVersion); key := 'Software\Embarcadero\BDS\%s'; key := Format(key, [bdsVersion]); reg := TRegistry.Create(KEY_READ); try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey(key, False) then begin rootDir := reg.ReadString('RootDir'); if rootDir = '' then begin FLogger.Error('Unable to find install location for compiler [' + CompilerToString(compilerVersion) + ']'); FFound[compilerVersion] := TStatus.notfound; raise Exception.Create('Unable to find install location for compiler [' + CompilerToString(compilerVersion) + ']'); // exit; end; end else begin FLogger.Error('Unable to find install location for compiler [' + CompilerToString(compilerVersion) + ']'); FFound[compilerVersion] := TStatus.notfound; raise Exception.Create('Unable to find install location for compiler [' + CompilerToString(compilerVersion) + ']'); // exit; end; finally reg.Free; end; FRsVarFiles[compilerVersion] := IncludeTrailingPathDelimiter(rootDir) + 'bin\rsvars.bat'; result := FRsVarFiles[compilerVersion]; FFound[compilerVersion] := TStatus.found; end; end; end; end.
unit SimpleSQL; interface uses SimpleInterface; Type TSimpleSQL<T : class, constructor> = class(TInterfacedObject, iSimpleSQL<T>) private FInstance : T; FFields : String; FWhere : String; FOrderBy : String; FGroupBy : String; FJoin : String; FLimitPagePosition : TSimpleDAOLimitPagePosition; FLimitPageSQL : String; public constructor Create(aInstance : T); destructor Destroy; override; class function New(aInstance : T) : iSimpleSQL<T>; function Insert (var aSQL : String) : iSimpleSQL<T>; function Update (var aSQL : String) : iSimpleSQL<T>; function Delete (var aSQL : String) : iSimpleSQL<T>; function Select (var aSQL : String) : iSimpleSQL<T>; function SelectId(var aSQL: String): iSimpleSQL<T>; function Fields (aSQL : String) : iSimpleSQL<T>; function Where (aSQL : String) : iSimpleSQL<T>; function OrderBy (aSQL : String) : iSimpleSQL<T>; function GroupBy (aSQL : String) : iSimpleSQL<T>; function Join (aSQL : String) : iSimpleSQL<T>; function LimitPagePosition(AValue : TSimpleDAOLimitPagePosition): iSimpleSQL<T>; function LimitPageSQL(aSQL : String) : iSimpleSQL<T>; function &End : iSimpleSQL<T>; end; implementation uses System.SysUtils, SimpleRTTI, System.Generics.Collections; { TSimpleSQL<T> } constructor TSimpleSQL<T>.Create(aInstance : T); begin FInstance := aInstance; end; function TSimpleSQL<T>.Delete(var aSQL: String): iSimpleSQL<T>; var aClassName, aWhere : String; begin Result := Self; TSimpleRTTI<T>.New(FInstance) .TableName(aClassName) .Where(aWhere); aSQL := aSQL + 'DELETE FROM ' + aClassName; aSQL := aSQL + ' WHERE ' + aWhere; end; destructor TSimpleSQL<T>.Destroy; begin inherited; end; function TSimpleSQL<T>.Fields(aSQL: String): iSimpleSQL<T>; begin Result := Self; FFields := aSQL; end; function TSimpleSQL<T>.GroupBy(aSQL: String): iSimpleSQL<T>; begin Result := Self; FGroupBy := aSQL; end; function TSimpleSQL<T>.Insert(var aSQL: String): iSimpleSQL<T>; var aClassName, aFields, aParam : String; begin Result := Self; TSimpleRTTI<T>.New(FInstance) .TableName(aClassName) .FieldsInsert(aFields) .Param(aParam); aSQL := aSQL + 'INSERT INTO ' + aClassName; aSQL := aSQL + ' (' + aFields + ') '; aSQL := aSQL + ' VALUES (' + aParam + ');'; end; function TSimpleSQL<T>.Join(aSQL: String): iSimpleSQL<T>; begin Result := Self; FJoin := aSQL; end; class function TSimpleSQL<T>.New(aInstance : T): iSimpleSQL<T>; begin Result := Self.Create(aInstance); end; function TSimpleSQL<T>.OrderBy(aSQL: String): iSimpleSQL<T>; begin Result := Self; FOrderBy := aSQL; end; function TSimpleSQL<T>.Select (var aSQL : String) : iSimpleSQL<T>; var aFields, aJoins, aClassName : String; begin Result := Self; TSimpleRTTI<T>.New(nil) .Fields(aFields) .Joins(aJoins) .TableName(aClassName); if length(trim(FFields)) <> 0 then aSQL := aSQL + ' SELECT ' + FFields else aSQL := aSQL + ' SELECT ' + aFields; aSQL := aSQL + ' FROM ' + aClassName; if length(trim(FJoin)) <> 0 then aSQL := aSQL + ' ' + FJoin + ' ' else aSQL := aSQL + ' ' + aJoins + ' '; if length(trim(FWhere)) <> 0 then aSQL := aSQL + ' WHERE ' + FWhere; if length(trim(FGroupBy)) <> 0 then aSQL := aSQL + ' GROUP BY ' + FGroupBy; if length(trim(FOrderBy)) <> 0 then aSQL := aSQL + ' ORDER BY ' + FOrderBy; if (length(trim(FLimitPageSQL)) <> 0) and (FLimitPagePosition = lpBottom) then aSQL := aSQL + ' ' + FLimitPageSQL; end; function TSimpleSQL<T>.SelectId(var aSQL: String): iSimpleSQL<T>; var aFields, aClassName, aWhere : String; begin Result := Self; TSimpleRTTI<T>.New(FInstance) .Fields(aFields) .TableName(aClassName) .Where(aWhere); if length(trim(FWhere)) <> 0 then aSQL := aSQL + ' WHERE ' + FWhere; aSQL := aSQL + ' SELECT ' + aFields; aSQL := aSQL + ' FROM ' + aClassName; aSQL := aSQL + ' WHERE ' + aWhere; end; function TSimpleSQL<T>.Update(var aSQL: String): iSimpleSQL<T>; var ClassName, aUpdate, aWhere : String; begin Result := Self; TSimpleRTTI<T>.New(FInstance) .TableName(ClassName) .Update(aUpdate) .Where(aWhere); aSQL := aSQL + 'UPDATE ' + ClassName; aSQL := aSQL + ' SET ' + aUpdate; aSQL := aSQL + ' WHERE ' + aWhere; end; function TSimpleSQL<T>.Where(aSQL: String): iSimpleSQL<T>; begin Result := Self; FWhere := aSQL; end; function TSimpleSQL<T>.LimitPagePosition(AValue: TSimpleDAOLimitPagePosition): iSimpleSQL<T>; begin Result := Self; FLimitPagePosition := AValue; end; function TSimpleSQL<T>.LimitPageSQL(aSQL: String): iSimpleSQL<T>; begin Result := Self; FLimitPageSQL := aSQL; end; function TSimpleSQL<T>.&End: iSimpleSQL<T>; begin Result := Self; end; end.
// 第3版Union-Find unit DSA.Tree.UnionFind3; interface uses System.SysUtils, DSA.Interfaces.DataStructure; type TUnionFind3 = class(TInterfacedObject, IUnionFind) private __parent: TArray<Integer>; /// <summary> sz[i]表示以i为根的集合中元素个数 </summary> __sz: TArray<Integer>; /// <summary> 查找元素p所对应的集合编号 </summary> function __find(p: Integer): Integer; public constructor Create(size: Integer); function GetSize: Integer; /// <summary> 查看元素p和元素q是否所属一个集合 </summary> function IsConnected(p, q: Integer): Boolean; /// <summary> 合并元素p和元素q所属的集合 </summary> procedure UnionElements(p, q: Integer); end; implementation { TUnionFind2 } constructor TUnionFind3.Create(size: Integer); var i: Integer; begin SetLength(__parent, size); SetLength(__sz, size); for i := 0 to size - 1 do begin __parent[i] := i; __sz[i] := 1; end; end; function TUnionFind3.GetSize: Integer; begin Result := Length(__parent); end; function TUnionFind3.IsConnected(p, q: Integer): Boolean; begin Result := __find(p) = __find(q); end; procedure TUnionFind3.UnionElements(p, q: Integer); var pRoot, qRoot: Integer; begin pRoot := __find(p); qRoot := __find(q); if pRoot = qRoot then Exit; // 根据两个元素所在树的元素个数不同判断合并方向 // 将元素个数少的集合合并到元素个数多的集合上 if __sz[pRoot] < __sz[qRoot] then begin __parent[pRoot] := qRoot; __sz[qRoot] := __sz[qRoot] + __sz[pRoot]; end else begin __parent[qRoot] := pRoot; __sz[pRoot] := __sz[pRoot] + __sz[qRoot]; end; end; function TUnionFind3.__find(p: Integer): Integer; begin if (p < 0) and (p >= Length(__parent)) then raise Exception.Create('p is out of bound.'); while p <> __parent[p] do p := __parent[p]; Result := p; end; end.
unit UDPSocketUtils; interface uses PacketBuffer, Classes, SysUtils, SyncObjs; type TPacketHeader = packed record Key : array [0..16-1] of byte; end; PPacketHeader = ^TPacketHeader; TPacketData = class private FData : pointer; FSize : integer; FCS : TCriticalSection; procedure prepareHeader; private function GetIsEmpty: boolean; public constructor Create; destructor Destroy; override; procedure Clear; procedure LoadFromPacketBuffer(APacketBuffer:TPacketBuffer); property IsEmpty : boolean read GetIsEmpty; property Data : pointer read FData; property Size : integer read FSize; end; implementation { TPacketData } procedure TPacketData.Clear; begin FCS.Enter; try FSize := 0; if FData <> nil then begin FreeMem(FData); FData := nil; end; finally FCS.Leave; end; end; constructor TPacketData.Create; begin inherited; FData := nil; FSize := 0; FCS := TCriticalSection.Create; end; procedure TPacketData.prepareHeader; var Loop: Integer; pHeader: PPacketHeader; begin pPacketHeader := Pointer(FData); Randomize; for Loop := Low(pHeader^.Key) to High(pHeader^.Key) do pHeader^.Key[Loop] := Random(256); end; destructor TPacketData.Destroy; begin Clear; FreeAndNil(FCS); inherited; end; function TPacketData.GetIsEmpty: boolean; begin FCS.Enter; try Result := FData = nil; finally FCS.Leave; end; end; procedure TPacketData.LoadFromPacketBuffer(APacketBuffer: TPacketBuffer); var pData : PPacketHeader; Data : pointer; Size : integer; begin FCS.Enter; try if APacketBuffer.GetPacket(Data, Size) = false then begin Clear; Exit; end; try GetMem(FData, Size + SizeOf(TPacketData)); pData := FData; Inc(pData); Move(Data^, pData^, Size); prepareHeader; finally if Data <> nil then FreeMem(Data); end; finally FCS.Leave; end; end; end.
unit PaymentDebitCard; interface uses uPaymentCard, uMRPinPad; type TPaymentDebitCard = class(TPaymentCard) private FPinPad: TMRPinPad; protected procedure BeforeProcessPayment; override; // procedure PreparePCC; override; public property PinPad: TMRPinPad read FPinPad write FPinPad; end; implementation uses DeviceIntegrationInterface; { TPaymentDebitCard } procedure TPaymentDebitCard.BeforeProcessPayment; var return: Boolean; begin inherited; processor.SetPurchase(FPaymentValue); // credit transaction if ( FPaymentValue > 0 ) then begin return := device.DebitProcessSale(); end else begin return := device.DebitProcessReturn(); end; end; end.
unit Classes.Service; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs , Classes.WorkerThread ; type TErgoLicenseServerMasterWiRL = class(TService) procedure ServiceAfterInstall(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceShutdown(Sender: TService); procedure ServiceAfterUninstall(Sender: TService); private { Private declarations } WorkerThread: TWorkerThread; procedure ServiceStopShutdown; public function GetServiceController: TServiceController; override; { Public declarations } end; var ErgoLicenseServerMasterWiRL: TErgoLicenseServerMasterWiRL; implementation uses Registry , System.IOUtils , Server.Register , Classes.Database ; {$R *.dfm} {$R ErgoLicenseServerMasterWSVC_EventLog.res} {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure ServiceController(CtrlCode: DWord); stdcall; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} begin ArtPictureService.Controller(CtrlCode); end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} function TErgoLicenseServerMasterWiRL.GetServiceController: TServiceController; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} begin Result := ServiceController; end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure TErgoLicenseServerMasterWiRL.ServiceAfterInstall(Sender: TService); {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} var reg: TRegistry; key: String; begin reg := TRegistry.Create(KEY_READ or KEY_WRITE); try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey('\SYSTEM\CurrentControlSet\Services\' + Name, false) then begin reg.WriteString('Description', 'Servizio di aggiornamento immagini articoli'); reg.CloseKey; end; finally reg.Free; end; // Create registry entries so that the event viewer show messages properly when we use the LogMessage method. Key := '\SYSTEM\CurrentControlSet\Services\Eventlog\Application\' + Self.Name; reg := TRegistry.Create(KEY_READ or KEY_WRITE); try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey(Key, True) then begin reg.WriteString('EventMessageFile', ParamStr(0)); reg.WriteInteger('TypesSupported', 7); reg.CloseKey; end; finally reg.Free; end; end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure TErgoLicenseServerMasterWiRL.ServiceAfterUninstall(Sender: TService); {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} var reg: TRegistry; key: String; begin // Delete registry entries for event viewer. key := '\SYSTEM\CurrentControlSet\Services\Eventlog\Application\' + Self.Name; reg := TRegistry.Create(KEY_READ or KEY_WRITE); try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.KeyExists(key) then reg.DeleteKey(key); finally reg.Free; end; end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure TErgoLicenseServerMasterWiRL.ServiceStart(Sender: TService; var Started: Boolean); {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} var appPath: String; appName: String; iniFileName: String; database: TDatabase; begin appPath := IncludeTrailingBackslash(TPath.GetDirectoryName(ParamStr(0))); appName := TPath.GetFileNameWithoutExtension(ParamStr(0)); iniFileName := appPath + appName + '.ini'; if not FileExists(iniFileName) then begin LogMessage( Format('Can''t find then configuration file ''%s'' - Service won''t start!', [iniFileName]), EVENTLOG_WARNING_TYPE, 0, 3 ); Started := False; Exit; end; database := GetContainer.Resolve<TDatabase>; if not database.SQLConnection.Connected then database.SQLConnection.Connected := True; WorkerThread := GetContainer.Resolve<TWorkerThread>; WorkerThread.Start; LogMessage('ServiceStart succeeded', EVENTLOG_SUCCESS, 0, 1); // LogMessage('Your message goes here INFO', EVENTLOG_INFORMATION_TYPE, 0, 2); // LogMessage('Your message goes here WARN', EVENTLOG_WARNING_TYPE, 0, 3); // LogMessage('Your message goes here ERRO', EVENTLOG_ERROR_TYPE, 0, 4); end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure TErgoLicenseServerMasterWiRL.ServiceStop(Sender: TService; var Stopped: Boolean); {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} begin ServiceStopShutdown; end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure TErgoLicenseServerMasterWiRL.ServiceShutdown(Sender: TService); {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} begin ServiceStopShutdown; end; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} procedure TErgoLicenseServerMasterWiRL.ServiceStopShutdown; {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} var database: TDatabase; begin if Assigned(WorkerThread) and (not WorkerThread.CheckTerminated) then begin LogMessage('ServiceStopShutdown is terminating WorkerThread', EVENTLOG_INFORMATION_TYPE, 0, 2); WorkerThread.Terminate; WorkerThread.Event.SetEvent; WorkerThread.WaitFor; FreeAndNil(WorkerThread); LogMessage('ServiceStopShutdown succeeded', EVENTLOG_SUCCESS, 0, 1); end; database := GetContainer.Resolve<TDatabase>; database.SQLConnection.Connected := False; end; end.
{/*! Provides definition of various event types and event handlers for simulation, sensor, vehicle and signal events. \modified 2019-07-09 14:42am \author Wuping Xin */} namespace TsmPluginFx.Core; uses rtl; type //--------------------------------------------- // Simulation Events //--------------------------------------------- {/*! Occurs when a simulation project is opened. \param aProjectFileName Full path of the .smp project. */} ProjectOpenedEventHandler = public block (const aProjectFileName: OleString); {/*! Occurs when a simulation run is being started. \param aRunSeqID Current iteration ID. \param aRunType Tpe of the run. \param Whether in a preload or actual simulation stage. */} SimulationStartingEventHandler = public block (aRunSeqID: Int16; aRunType: TsmRunType; aIsInPreload: VARIANT_BOOL); {/*! Occurs when a simulation run has all internal modules initialized, and simulation clock is about to start ticking. */} SimulationStartedEventHandler = public block; {/*! Occurs when simulation clock time is being advanced. \param aTime Current simulation time in seconds past midnight. \param aNextTime Next scheduled call back time for advancing event. */} SimulationAdvanceEventHandler = public block (aTime: Double; out aNextTime: Double); {/*! Occurs when a simulation run is completed, yet before all internal modules begin to post-process the simulation outputs. \param aState Simulation state indicating whether a simulation finishes successfully, canceled by the user, or aborted due to runtime error. */} SimulationStoppedEventHandler = public block (aState: TsmState); {/*! Occurs when a simulation run has finished with all post processing of the simulation output done. \param aState Simulation state. */} SimulationEndedEvent = public block (aState: TsmState); {/*! Occurs when a simulation project is being closed. This is where project-specific cleaning up can be performed. */} ProjectClosedEventHandler = public block (); {/*! Occurs when TransModeler is shutting down. */} TsmApplicationShutdownEventHandler = public block (); //--------------------------------------------- // Sensor Events //--------------------------------------------- {/*! Occurs when a vehicle activates the sensor. \param aSensorID Sensor ID. \param aVehicleID Vehicle ID. \param aActivateTime The time when vehicle front bumper crossing the upstream edge of the sensor. \param aSpeed Vehicle speed. */} VehicleEnterEventHandler = public block (aSensorID: Integer; aVehicleID: Integer; aActivateTime: Double; aSpeed: Single); {/*! Occurs when a vehicle deactivates the sensor. \param aSensorID Sensor ID. \param aVehicleID Vehicle ID. \param aActivateTime The time when vehicle rear bumper crossing the downstream edge of the sensor. \param aSpeed Vehicle speed. */} VehicleLeaveEventHandler = public block (aSensorID: Integer; aVehicleID: Integer; aDeactivateTime: Double; aSpeed: Single); //--------------------------------------------- // Signal Events //--------------------------------------------- {/*! Occurs when a new signal plan is started. \param aCookie Unique ID identifying the signal control plan. \param aControllClass Class of controller type, such as nodes for controlled intersections, signals for traffic management devices, or lanes for lane access control. \param aIDs A list of IDs of controlled features such as nodes, signals, or lanes. */} SignalPlanStartedEventHandler = public block (aCookie: Integer; aControllClass: TsmControlClass; aIDs: VARIANT); {/*! Occurs when a signal plan is ended. \param aCookie Cookie ID of the signal plan. */} SignalPlanEndedEventHandler = public block (aCookie: Integer); {/*! Occurs when HOT faires are set to initial values for the given entrance. \param aEntranceID Entrance ID. */} HotFaresInitializedEventHandler = public block (aEntranceID: Integer); {/*! Occurs when HOT faires are released for the given entrance. \param aEntranceID Entrance ID. */} HotFaresReleasedEvent = public block (aEntranceID: Integer); {/*! Occurs when signal state is changed. \remark ITsmSignal::IsNotifyingEvents must have been set to true in order the for the event to be fired. */} SignalStateChangedEventHandler = public block (aSignalID: Integer; aTime: Double; aState: TsmSignalState); //--------------------------------------------- // Vehicle Events //--------------------------------------------- {/*! Occurs when a vehicle departs its origin. */} DepartedEventHandler = public block (aVehicleID: Integer; aTime: Double); {/*! Occurs when a vehicle parks into parking space at its destination. \remark This event occurs before the Arrival event is fired. */} ParkedEventHandler = public block (aVehicleID: Integer; aTime: Double); {/*! Occurs when a vehicle is stalled or released. \param aTime Time of the event. \param aStalled Whether the vehicle is stalled (true), or released(false). */} StalledEventHandler = public block (aVehicleID: Integer; aTime: Double; aStalled: VARIANT_BOOL); {/*! Occurs when a vehicle arrives at its destination. \param aVehicleID ID of the vehicle. \param aTime The time when the vehicle arrives at its destination. */} ArrivedEventHandler = public block (aVehicleID: Integer; aTime: Double); {/*! Occurs when a vehicle enters a new lane. \remark ITsmVehicle::Tracking must have been set to true in order for the event to be fired. */} EnterLaneEventHandler = public block (const aVehicle: ITsmVehicle; aLaneID: Integer; aLaneEntryTime: Double); {/*! Occurs when a vehicle enters a new segment. \remark ITsmVehicle::Tracking must have been set to true in order for the event to be fired. */} EnterSegmentEventHandler = public block (const aVehicle: ITsmVehicle; aSegmentID: Integer; aSegmentEntryTime: Double); {/*! Occurs when a vehicle enters a new link. \remark ITsmVehicle::Tracking must have been set to true in order for the event to be fired. */} EnterLinkEventHandler = public block (const aVehicle: ITsmVehicle; aLinkID: Integer; aLinkEntryTime: Double); {/*! Occurs when a vehicle changes its path en-route. \param aVehicle The subject vehicle changing path. \param aPathID ID of the new path. If It has a positive value, then it represents path ID of a normal vehicle. If it has a negative value, then it represents route ID of a transit vehicle. If it is 0, then the vehicle will end its trip with the next link. \param aPosition A 0-based index to the links along the referenced path or route. If only a single link is involved, no path is explicitly defined and aPathID will be 0. In such case, aPosition will be a signed link ID, where a positive value indicates AB direction, while negative value BA direction. \param aTime The time when the vehicle changes to the new path. \remark ITsmVehicle::Tracking must have been set to true in order for the event to be fired. */} PathChangedEventHandler = public block (const aVehicle: ITsmVehicle; aPathID: Integer; aPosition: Integer; aTime: Double); {/*! Occurs when a transit vehicle enters route stop. \param aTime Current lock time. \param aVehicle A ITsmVehicle reference. \param aRoute A ITsmRoute reference. \param aStop A ITsmStop reference. \param aMaxCapacity Maximum capacity of the stop. \param aPassengers Number of passengers on board. \param aDelay Deviation from the scedule at last stop served in seconds. \param aSwellTime A user computed dwell time for TransModeler to implement. */} EnterTransitStopEventHandler = public block (aTime: Double; const aVehicle: ITsmVehicle; const aRoute: ITsmRoute; const aStop: ITsmStop; aMaxCapacity: Int16; aPassengers: Int16; aDelay: Single; aDefaultDwellTime: Single; out aDwellTime: Single); {/*! Occurs periodically to provide Automated Vehicle Location (AVL) update. \param aPremptionTypeIndex A 1-based index or 0 if no preemption. \remark ITsmVehicle::Tracking must have been set to true in order for the event to be fired. */} AvlUpdateEventHandler = public block (const aVehicle: ITsmVehicle; aVehicleClassIndex: Int16; aOccupancy: Int16; aPremptionTypeIndex: Int16; var aCoordinate: STsmCoord3); {/*! This event provides an alternative cost of a link when computing the shortest path or evaluating the cost for a predefined path. The value returned by this function is added to the current cost of the link, which is either travel time or generalized cost, depending on the project setting for vehicle routing. \remark ITsmApplication::EnableLinkCostCallback must have been set to true in order for the event to be fired. */} CalculateLinkCostEventHandler = public block (aVehicleClassIndex: Int16; aOccupancy: Int16; aDriverGroupIndex: Int16; aVehicleType: TsmVehicleType; aLinkEntryTime: Double; const aFromLink: ITsmLink; const aLink: ITsmLink; var aValue: Single ); {/*! Occurs when the value of the user defined field is retrieved. \remark ITsmApplication::CreateUserVehicleProperty must have been called successfully to have the field registered in order for the event to be fired. */} GetPropertyValueEventHandler = public block (const aVehicle: ITsmVehicle; aColumnIndex: Int16; out aValue: VARIANT); {/*! Occurs when the value of the user-defined field is edited. \remark The field must have been registered as editable in order for the event to be fired. */} SetPropertyValueEventHandler = public block (const aVehicle: ITsmVehicle; aColumnIndex: Int16; aValue: VARIANT); [COM, Guid('{80B67AD2-79A3-4FE7-833C-AF83947B6AF8}')] ITsmEventSink = public interface(IUnknown) method ConnectEvents; method DisconnectEvents; property ConnectionID: Int32 read; property IsConnected: Boolean read; property EventSinkType: TsmEventSinkType read; end; [COM, Guid('{6F29FAA7-4AD7-425D-A1D0-DCEB6232F029}')] ITsmSimulationEventSink = public interface(ITsmEventSink) event ProjectOpened: ProjectOpenedEventHandler; event ProjectClosed: ProjectClosedEventHandler; event SimulationStarting: SimulationStartingEventHandler; event SimulationStarted: SimulationStartedEventHandler; event SimulationAdvance: SimulationAdvanceEventHandler; event SimulationStopped: SimulationStoppedEventHandler; event SimulationEnded: SimulationEndedEvent; event TsmApplicationShutdown: TsmApplicationShutdownEventHandler; end; [COM, Guid('{D305FC5D-70F8-466F-ACEF-BAEDBAB5E6B4}')] ITsmSensorEventSink = public interface(ITsmEventSink) event VehicleEnter: VehicleEnterEventHandler; event VehicleLeave: VehicleLeaveEventHandler; end; [COM, Guid('1D0F3CEF-C140-4F40-A003-990D65DFC836')])] ITsmSignalEventSink = public interface(ITsmEventSink) event SignalPlanStarted: SignalPlanStartedEventHandler; event SignalPlanEnded: SignalPlanEndedEventHandler; event SignalStateChanged: SignalStateChangedEventHandler; event HotFaresInitialized: HotFaresInitializedEventHandler; event HotFaresReleased: HotFaresReleasedEvent; end; [COM, Guid('{0EB7A5CB-EEB5-498B-A6AC-B2663DCD4818}')] ITsmVehicleEventSink = public interface(ITsmEventSink) event Departed: DepartedEventHandler; event Parked: ParkedEventHandler; event Stalled: StalledEventHandler; event Arrived: ArrivedEventHandler; event EnterLane: EnterLaneEventHandler; event EnterSegment: EnterSegmentEventHandler; event EnterLink: EnterLaneEventHandler; event PathChanged: PathChangedEventHandler; event EnterTransitStop: EnterTransitStopEventHandler; event AvlUpdate: AvlUpdateEventHandler; event CalculateLinkCost: CalculateLinkCostEventHandler; event GetPropertyValue: GetPropertyValueEventHandler; event SetPropertyValue: SetPropertyValueEventHandler; end; TsmEventSink<T> = public abstract class(ITsmEventSink) private finalizer; begin DisconnectEvents; fEventSource := nil; end; const cUndefinedCoookie = 0; var fCookie: DWORD; var fEventSource: IUnknown; var fGuid: GUID; protected method ConnectEvents; begin if IsConnected then exit; InterfaceConnect(fEventSource, var fGuid, Self, var fCookie); end; method DisconnectEvents; begin if not IsConnected then exit; InterfaceDisconnect(fEventSource, var fGuid, fCookie); fCookie := cUndefinedCoookie; end; method GetEventSinkType: TsmEventSinkType; virtual; abstract; public constructor(aEventSource: IUnknown); begin fCookie := cUndefinedCoookie; fEventSource := aEventSource; fGuid := guidOf(T); end; public property ConnectionID: Int32 read begin exit fCookie; end; property IsConnected: Boolean read begin exit (fCookie > cUndefinedCoookie); end; property EventSinkType: TsmEventSinkType read begin result := GetEventSinkType(); end; end; TsmSimulationEventSink = public class(TsmEventSink<_ISimulationEvents>, ITsmSimulationEventSink, _ISimulationEvents) {$REGION '_ISimulationEvents'} private [CallingConvention(CallingConvention.Stdcall)] method OnProjectOpened(const aProjectFileName: OleString): HRESULT; begin if assigned(ProjectOpened) then ProjectOpened(aProjectFileName); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSimulationStarting(aRunSeqID: Int16; aTsmRunType: TsmRunType; aIsInPreload: VARIANT_BOOL): HRESULT; begin if assigned(SimulationStarting) then SimulationStarting(aRunSeqID, aTsmRunType, aIsInPreload); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSimulationStarted: HRESULT; begin if assigned(SimulationStarted) then SimulationStarted(); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnAdvance(aTime: Double; out aNextCallbackTime: Double): HRESULT; begin if assigned(SimulationAdvance) then SimulationAdvance(aTime, out aNextCallbackTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSimulationStopped(aTsmState: TsmState): HRESULT; begin if assigned(SimulationStopped) then SimulationStopped(aTsmState); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSimulationEnded(aTsmState: TsmState): HRESULT; begin if assigned(SimulationEnded) then SimulationEnded(aTsmState); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnProjectClosed: HRESULT; begin if assigned(ProjectClosed) then ProjectClosed(); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnTsmApplicationShutdown: HRESULT; begin if assigned(TsmApplicationShutdown) then TsmApplicationShutdown(); result := S_OK; end; {$ENDREGION} protected method GetEventSinkType: TsmEventSinkType; override; begin exit TsmEventSinkType.Simulation; end; public event ProjectOpened: ProjectOpenedEventHandler; event ProjectClosed: ProjectClosedEventHandler; event SimulationStarting: SimulationStartingEventHandler; event SimulationStarted: SimulationStartedEventHandler; event SimulationAdvance: SimulationAdvanceEventHandler; event SimulationStopped: SimulationStoppedEventHandler; event SimulationEnded: SimulationEndedEvent; event TsmApplicationShutdown: TsmApplicationShutdownEventHandler; end; TsmSensorEventSink = public class(TsmEventSink<_ISensorEvents>, ITsmSensorEventSink, _ISensorEvents) {$REGION '_ISensorEvents'} private [CallingConvention(CallingConvention.Stdcall)] method OnVehicleEnter(aSensorID: Integer; aVehicleID: Integer; aActivateTime: Double; aSpeed: Single): HRESULT; begin if assigned(VehicleEnter) then VehicleEnter(aSensorID, aVehicleID, aActivateTime, aSpeed); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnVehicleLeave(aSensorID: Integer; aVehicleID: Integer; aDeactivateTime: Double; aSpeed: Single): HRESULT; begin if assigned(VehicleLeave) then VehicleLeave(aSensorID, aVehicleID, aDeactivateTime, aSpeed); result := S_OK; end; {$ENDREGION} protected method GetEventSinkType: TsmEventSinkType; override; begin exit TsmEventSinkType.Sensor; end; public event VehicleEnter: VehicleEnterEventHandler; event VehicleLeave: VehicleLeaveEventHandler; end; TsmSignalEventSink = public class(TsmEventSink<_ISignalEvents>, ITsmSignalEventSink, _ISignalEvents) {$REGION '_ISignalEvents Methods'} private [CallingConvention(CallingConvention.Stdcall)] method OnSignalPlanStarted(aCookie: Integer; aControllClass: TsmControlClass; aIDs: VARIANT): HRESULT; begin if assigned(SignalPlanStarted) then SignalPlanStarted(aCookie, aControllClass, aIDs); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSignalPlanEnded(aCookie: Integer): HRESULT; begin if assigned(SignalPlanEnded) then SignalPlanEnded(aCookie); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnHotFaresInitialized(aEntranceID: Integer): HRESULT; begin if assigned(HotFaresInitialized) then HotFaresInitialized(aEntranceID); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnHotFaresReleased(aEntranceID: Integer): HRESULT; begin if assigned(HotFaresReleased) then HotFaresReleased(aEntranceID); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSignalStateChanged(aSignalID: Integer; aTime: Double; aSignalState: TsmSignalState): HRESULT; begin if assigned(SignalStateChanged) then SignalStateChanged(aSignalID, aTime, aSignalState); result := S_OK; end; {$ENDREGION} protected method GetEventSinkType: TsmEventSinkType; override; begin exit TsmEventSinkType.Signal; end; public event SignalPlanStarted: SignalPlanStartedEventHandler; event SignalPlanEnded: SignalPlanEndedEventHandler; event SignalStateChanged: SignalStateChangedEventHandler; event HotFaresInitialized: HotFaresInitializedEventHandler; event HotFaresReleased: HotFaresReleasedEvent; end; TsmVehicleEventSink = public class(TsmEventSink<_IVehicleEvents>, ITsmVehicleEventSink, _IVehicleEvents) {$REGION '_IVehicleEvents Methods'} private [CallingConvention(CallingConvention.Stdcall)] method OnDeparted(aVehicleID: Integer; aTime: Double): HRESULT; begin if assigned(Departed) then Departed(aVehicleID, aTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnParked(aVehicleID: Integer; aTime: Double): HRESULT; begin if assigned(Parked) then Parked(aVehicleID, aTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnStalled(aVehicleID: Integer; aTime: Double; aStalled: VARIANT_BOOL): HRESULT; begin if assigned(Stalled) then Stalled(aVehicleID, aTime, aStalled); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnArrived(aVehicleID: Integer; aTime: Double): HRESULT; begin if assigned(Arrived) then Arrived(aVehicleID, aTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnEnterLane(const aVehicle: ITsmVehicle; aLaneID: Integer; aLaneEntryTime: Double): HRESULT; begin if assigned(EnterLane) then EnterLane(aVehicle, aLaneID, aLaneEntryTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnEnterSegment(const aVehicle: ITsmVehicle; aSegmentID: Integer; aSegmentEntryTime: Double): HRESULT; begin if assigned(EnterSegment) then EnterSegment(aVehicle, aSegmentID, aSegmentEntryTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnEnterLink(const aVehicle: ITsmVehicle; aLinkID: Integer; aLinkEntryTime: Double): HRESULT; begin if assigned(EnterLink) then EnterLink(aVehicle, aLinkID, aLinkEntryTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnPathChanged(const aVehicle: ITsmVehicle; aPathID: Integer; aPosition: Integer; aTime: Double): HRESULT; begin if assigned(PathChanged) then PathChanged(aVehicle, aPathID,aPosition, aTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnEnterTransitStop(aTime: Double; const aVehicle: ITsmVehicle; const aRoute: ITsmRoute; const aStop: ITsmStop; aMaxCapacity: Int16; aPassengers: Int16; aDelay: Single; aDefaultDwellTime: Single; out aDwellTime: Single): HRESULT; begin if assigned(EnterTransitStop) then EnterTransitStop(aTime, aVehicle, aRoute, aStop, aMaxCapacity, aPassengers, aDelay, aDefaultDwellTime, out aDwellTime); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnAvlUpdate(const aVehicle: ITsmVehicle; aVehicleClassIndex: Int16; aOccupancy: Int16; aPreemptionTypeIndex: Int16; var aCoordinate: STsmCoord3): HRESULT; begin if assigned(AvlUpdate) then AvlUpdate(aVehicle, aVehicleClassIndex, aOccupancy, aPreemptionTypeIndex, var aCoordinate); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnCalculateLinkCost(aVehicleClassIndex: Int16; aOccupancy: Int16; aDriverGroupIndex: Int16; aVehicleType: TsmVehicleType; aLinkEntryTime: Double; const aFromLink: ITsmLink; const aLink: ITsmLink; var aValue: Single): HRESULT; begin if assigned(CalculateLinkCost) then CalculateLinkCost(aVehicleClassIndex, aOccupancy, aDriverGroupIndex, aVehicleType, aLinkEntryTime, aFromLink, aLink, var aValue); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnGetPropertyValue(const aVehicle: ITsmVehicle; aColumnIndex: Int16; out aValue: VARIANT): HRESULT; begin if assigned(GetPropertyValue) then GetPropertyValue(aVehicle, aColumnIndex, out aValue); result := S_OK; end; [CallingConvention(CallingConvention.Stdcall)] method OnSetPropertyValue(const aVehicle: ITsmVehicle; aColumnIndex: Int16; aValue: VARIANT): HRESULT; begin if assigned(SetPropertyValue) then SetPropertyValue(aVehicle, aColumnIndex, aValue); result := S_OK; end; {$ENDREGION} protected method GetEventSinkType: TsmEventSinkType; override; begin exit TsmEventSinkType.Vehicle; end; public event Departed: DepartedEventHandler; event Parked: ParkedEventHandler; event Stalled: StalledEventHandler; event Arrived: ArrivedEventHandler; event EnterLane: EnterLaneEventHandler; event EnterSegment: EnterSegmentEventHandler; event EnterLink: EnterLaneEventHandler; event PathChanged: PathChangedEventHandler; event EnterTransitStop: EnterTransitStopEventHandler; event AvlUpdate: AvlUpdateEventHandler; event CalculateLinkCost: CalculateLinkCostEventHandler; event GetPropertyValue: GetPropertyValueEventHandler; event SetPropertyValue: SetPropertyValueEventHandler; end; TsmEventSinkType = public enum ( Undefined, Simulation, Signal, Sensor, Vehicle, All ); TsmEventSinkTypes = public set of TsmEventSinkType; [COM, Guid('{5CB6D9ED-80C5-4612-9D4B-FE36A6B3B1E3}')] ITsmEventSinkManager = public interface(IUnknown) method Connect(aEventSinkTypes: TsmEventSinkTypes); method Disconnect(aEventSinkTypes: TsmEventSinkTypes); method GetEventSink(aType: TsmEventSinkType): ITsmEventSink; end; TsmEventSinkManager = public class(ITsmEventSinkManager) private finalizer; begin Disconnect([TsmEventSinkType.All]); fEventSinkMap.Clear; end; method SetEventSinkConnection(aEventSinkTypes: TsmEventSinkTypes; aConnected: Boolean); begin for lType in fEventSinkMap.Keys do if (lType in aEventSinkTypes) or (TsmEventSinkType.All in aEventSinkTypes) then if aConnected then fEventSinkMap[lType].ConnectEvents() else fEventSinkMap[lType].DisconnectEvents(); end; var fEventSinkMap: Dictionary<TsmEventSinkType, ITsmEventSink>; protected method Connect(aEventSinkTypes: TsmEventSinkTypes); begin SetEventSinkConnection(aEventSinkTypes, true); end; method Disconnect(aEventSinkTypes: TsmEventSinkTypes); begin SetEventSinkConnection(aEventSinkTypes, false); end; method GetEventSink(aType: TsmEventSinkType): ITsmEventSink; begin if aType in [TsmEventSinkType.Undefined, TsmEventSinkType.All] then exit nil; result := fEventSinkMap[aType]; end; public constructor(aTsmApp: ITsmApplication); begin fEventSinkMap := new Dictionary<TsmEventSinkType, ITsmEventSink>; fEventSinkMap.Add( TsmEventSinkType.Sensor, new TsmSensorEventSink(aTsmApp) ); fEventSinkMap.Add( TsmEventSinkType.Simulation, new TsmSimulationEventSink(aTsmApp) ); fEventSinkMap.Add( TsmEventSinkType.Signal, new TsmSignalEventSink(aTsmApp) ); fEventSinkMap.Add( TsmEventSinkType.Vehicle, new TsmVehicleEventSink(aTsmApp) ); end; end; end.
unit FileServiceClientEx; //makes use of FileServiceClient to transfer files from remote servers interface uses debug, typex, numbers, memoryfilestream, FileServiceClient, dir, dirfile, sysutils, classes, systemx, commandprocessor, helpers_stream; const {$IFDEF CPUx64} PUT_CHUNK_SIZE = 262144*4*16; GET_CHUNK_SIZE = 262144*4*16; {$ELSE} PUT_CHUNK_SIZE = 262144*2; GET_CHUNK_SIZE = 262144*2; {$ENDIF} DEFAULT_HOST = '192.168.101.12'; // DEFAULT_HOST = 'localhost'; DEFAULT_PORT = '876'; type TFileServiceClientEx = class(TFileServiceClient) public connattempts: ni; procedure GetFileEx(sRemoteFile: string; sLocalFile: string; prog: PProgress = nil); procedure PutFileEx(sLocalFile: string; sRemoteFile: string; prog: PProgress = nil); end; Tcmd_FileEx = class(TCommand) public cli: TFileServiceClientEx; RemoteFile, LocalFile: string; end; Tcmd_GetFileEx = class(Tcmd_FileEx) public procedure DoExecute; override; end; Tcmd_PutFileEx = class(Tcmd_FileEx) public procedure DoExecute; override; end; { TFileServiceClientEx } implementation procedure TFileServiceClientEx.GetFileEx(sRemoteFile, sLocalFile: string; prog: PProgress = nil); var ftr: TFileTransferReference; iStart: int64; fs: TFileStream; iToWrite, iWritePos, iTotal: int64; t: ni; chunksize: int64; begin OpenFile_Async(sRemoteFile, fmOpenRead+fmShareDenyNone); GetFileSize_Async(sRemoteFile); ftr := nil; if OpenFile_Response(ftr) then //CREATES TFileTransferReference try iTotal := GetFileSize_Response(); if prog <> nil then begin prog.stepcount := iTotal; prog.step := 0; end; iStart := 0; if FileExists(sLocalFile) then Deletefile(sLocalFile); ForceDirectories(extractfilepath(sLocalFile)); fs := TFileStream.create(sLocalFile, fmCreate); try if iTotal > 0 then begin chunksize := GET_CHUNK_SIZE; iWritePos := 0; repeat ftr.o.StartBlock := iStart; iToWRite := lesserof(chunksize, iTotal-iWritePos); ftr.o.Length := iToWrite; ftr.o.ContainsData := false; ftr.o.FreeBuffer; GetFile_Async(ftr); //destroys TFileTransferReference GetFile_Response(ftr); //creates TFileTransferReference stream_GuaranteeWrite(fs, ftr.o.buffer, ftr.o.Length); if ftr.o.length < 0 then raise ECritical.create('ftr length < 0'); if prog<> nil then prog.step := iWritePos; if ftr.o.eof then begin fileSetDate(fs.Handle, DatetimeToFileDate(ftr.o.FileDate)); end; inc(iStart,ftr.o.Length); inc(iWritePos, ftr.o.Length); until iWritePos = iTotal; CloseFile_Async(ftr); //destroys TfileTransferReference; end else begin chunksize := 262144*4*16; iWritePos := 0; repeat ftr.o.StartBlock := iStart; iToWRite := lesserof(chunksize, iTotal-iWritePos); ftr.o.Length := iToWrite; ftr.o.Buffer := nil; ftr.o.ContainsData := false; GetFile_Async(ftr); if prog<> nil then inc(prog.step, ftr.o.Length); inc(iStart,ftr.o.Length); inc(iWritePos, iToWrite); until iWritePos = iTotal; CloseFile_Async(ftr); iStart := 0; iWritePos := 0; prog.step := 0; repeat ftr.o.StartBlock := iStart; iToWRite := lesserof(chunksize, iTotal-iWritePos); ftr.o.Length := iToWrite; ftr.o.Buffer := nil; ftr.o.ContainsData := false; // GetFile_Async(ftr); GetFile_Response(ftr); stream_GuaranteeWrite(fs, ftr.o.buffer, ftr.o.Length); if prog<> nil then inc(prog.step, ftr.o.Length); if ftr.o.eof then begin fileSetDate(fs.Handle, DatetimeToFileDate(ftr.o.FileDate)); end; inc(iStart,ftr.o.Length); inc(iWritePos, iToWrite); until iWritePos = iTotal; end; finally fs.free; end; finally ftr.o.ContainsData := false; self.CloseFile_REsponse(); // ftr.free; end else raise ECritical.create('Failed to open remote file '+sRemoteFile); end; procedure TFileServiceClientEx.PutFileEx(sLocalFile, sRemotefile: string; prog: PProgress = nil); var ftr: TFileTransferReference; fs: TMemoryFileStream; iPOs: integer; // a: array [0..PUT_SIZE] of byte; // aa: PByte; b: PByte; iToWrite: int64; begin // GetMem(aa, PUT_SIZE); try fs := TMemoryFileStream.create(sLocalFile, fmOpenRead+fmShareDenyNone); try if prog <> nil then begin prog.stepcount := Dirfile.GetFileSize(sLocalFile); prog.step := 0; end; if self.OpenFile(sRemoteFile, ftr, fmCReate) then try iPos := 0; //call putfile for every block of the file repeat iToWrite := lesserof(PUT_CHUNK_SIZE, fs.Size-fs.Position); GEtMem(b, iToWrite); ftr.o.Buffer := b; ftr.o.StartBlock := iPos; ftr.o.Length := stream_guaranteeread(fs, ftr.o.Buffer, iToWrite);//fs.Read(b[0], PUT_SIZE); inc(iPos, ftr.o.Length); if prog<> nil then inc(prog.step, ftr.o.Length); ftr.o.EOF := fs.Position >= fs.Size; ftr.o.FileDate := FileDateToDateTime(FileGetDAte(fs.handle)); ftr.o.ContainsData := true; self.PutFile(ftr); ftr.o.FreeBuffer; until ftr.o.eof; finally ftr.o.Buffer := nil; ftr.o.length := 0; self.CloseFile(ftr); ftr.o.free; end; finally fs.free; end; finally // FreeMem(aa); end; end; { Tcmd_GetFileEx } procedure Tcmd_GetFileEx.DoExecute; begin inherited; cli.GetFileEx(remotefile, localfile, @self.volatile_progress); end; { Tcmd_PutFileEx } procedure Tcmd_PutFileEx.DoExecute; begin inherited; cli.GetFileEx(localfile, remotefile, @self.volatile_progress); end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox; type TForm1 = class(TForm) Label1: TLabel; SkiLabel: TLabel; SkiCombo: TComboBox; BicycleLabel: TLabel; BicycleCombo: TComboBox; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure ComboChange(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private function GetSkiAmount: Integer; function GetBicycleAmount: Integer; procedure UpdateStrings; public property SkiAmount: Integer read GetSkiAmount; property BicycleAmount: Integer read GetBicycleAmount; end; var Form1: TForm1; implementation {$R *.fmx} uses NtPattern, NtResource, NtResourceString, // Turns on resource string translation FMX.NtLanguageDlg, FMX.NtTranslator; function TForm1.GetSkiAmount: Integer; begin if SkiCombo.ItemIndex >= 0 then Result := StrToInt(SkiCombo.Items[SkiCombo.ItemIndex]) else Result := 0; end; function TForm1.GetBicycleAmount: Integer; begin if BicycleCombo.ItemIndex >= 0 then Result := StrToInt(BicycleCombo.Items[BicycleCombo.ItemIndex]) else Result := 0; end; procedure TForm1.UpdateStrings; resourcestring SMessagePlural = 'I have {plural, zero {no skis} one {one ski} other {%d skis}} {plural, zero {and no bicycles} one {and one bicycle} other {and %d bicycles}}'; //loc 0: ski or bicyle count begin Label1.Text := TMultiPattern.Format(SMessagePlural, [SkiAmount, BicycleAmount]); end; procedure TForm1.FormCreate(Sender: TObject); procedure Add(value: Integer); begin SkiCombo.Items.Add(IntToStr(value)); BicycleCombo.Items.Add(IntToStr(value)); end; resourcestring SEnglish = 'English'; SFinnish = 'Finnish'; SGerman = 'German'; SFrench = 'French'; SJapanese = 'Japanese'; begin NtResources.Add('English', 'English', SEnglish, 'en'); NtResources.Add('Finnish', 'suomi', SFinnish, 'fi'); NtResources.Add('German', 'Deutsch', SGerman, 'de'); NtResources.Add('French', 'français', SFrench, 'fr'); NtResources.Add('Japanese', '日本語', SJapanese, 'ja'); _T(Self); Add(0); Add(1); Add(2); Add(3); Add(4); Add(5); Add(11); Add(21); Add(101); Add(111); SkiCombo.ItemIndex := 1; BicycleCombo.ItemIndex := 2; ComboChange(Self); end; procedure TForm1.ComboChange(Sender: TObject); begin UpdateStrings; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select then UpdateStrings; end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PosFrame, StdCtrls, GameLogic, Menus, ComCtrls, Clipbrd, ActnList; const MM_DOMOVE = WM_USER + 1; MM_DEBUG = WM_USER + 2; MM_IS_ANIMATION = WM_USER + 3; type TMode = (mdMachineWhite, mdMachineBlack, mdTwoMachine, mdView); TGameHistory = class private function GetPartyView: TListView; function GetPositionFrame: TPositionFrame; private FPositions: array[0..255] of TPosition; FMoveNo: Integer; procedure AddBlackMove(const Move: string); procedure AddWhiteMove(const Move: string); property PositionFrame: TPositionFrame read GetPositionFrame; property PartyView: TListView read GetPartyView; public procedure NewGame; procedure AddMove(NewPosition: TPosition); procedure Undo; property MoveNo: Integer read FMoveNo write FMoveNo; end; TMainForm = class(TForm) PositionFrame: TPositionFrame; Memo: TMemo; MainMenu: TMainMenu; GameMenu: TMenuItem; NewItem: TMenuItem; Separator1: TMenuItem; BeginerItem: TMenuItem; IntermediateItem: TMenuItem; ExpertItem: TMenuItem; Separator2: TMenuItem; ExitItem: TMenuItem; ModeMenu: TMenuItem; MachineWhiteItem: TMenuItem; MachineBlackItem: TMenuItem; TwoMachineItem: TMenuItem; ViewItem: TMenuItem; Separator3: TMenuItem; FlipBoardItem: TMenuItem; PartyView: TListView; DebugMenu: TMenuItem; SetPositionItem: TMenuItem; AddToLibraryItem: TMenuItem; CopyGameItem: TMenuItem; Separator4: TMenuItem; UndoMoveItem: TMenuItem; ActionList: TActionList; NewGameAction: TAction; BeginerAction: TAction; IntermediateAction: TAction; ExpertAction: TAction; UndoMoveAction: TAction; ExitAction: TAction; MachineWhiteAction: TAction; MachineBlackAction: TAction; TwoMachineAction: TAction; ViewGameAction: TAction; FlipBoardAction: TAction; SetPositionAction: TAction; AddToLibraryAction: TAction; CopyGameAction: TAction; procedure FormShow(Sender: TObject); procedure SelectCellBtnClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure UndoMoveItemClick(Sender: TObject); procedure NewGameActionExecute(Sender: TObject); procedure LevelActionExecute(Sender: TObject); procedure UndoMoveActionExecute(Sender: TObject); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure ExitActionExecute(Sender: TObject); procedure MachineWhiteActionExecute(Sender: TObject); procedure MachineBlackActionExecute(Sender: TObject); procedure TwoMachineActionExecute(Sender: TObject); procedure ViewGameActionExecute(Sender: TObject); procedure FlipBoardActionExecute(Sender: TObject); procedure SetPositionActionExecute(Sender: TObject); procedure AddToLibraryActionExecute(Sender: TObject); procedure CopyGameActionExecute(Sender: TObject); private FDeep: Integer; FGameHistory: TGameHistory; FMode: TMode; FThreadHandle: THandle; procedure AcceptMove(Sender: TObject; const NewPosition: TPosition); procedure TuneState; procedure StopThinking; procedure DoMove(var Message: TMessage); message MM_DOMOVE; procedure DoDebug(var Message: TMessage); message MM_DEBUG; procedure IsAnimation(var Message: TMessage); message MM_IS_ANIMATION; property Mode: TMode read FMode; property Deep: Integer read FDeep write FDeep; property ThreadHandle: THandle read FThreadHandle write FThreadHandle; property GameHistory: TGameHistory read FGameHistory write FGameHistory; procedure Deselect(Action: TAction; const Category: string); end; var MainForm: TMainForm; implementation uses GameTactics; {$R *.DFM} function Thinker(APosition: Pointer): Integer; var Position: TPosition; Estimate: Integer; begin Position := TPosition(APosition^); SelectMove(Position, MainForm.Deep, Estimate); SendMessage(MainForm.Handle, MM_DOMOVE, Integer(@Position), Estimate); Result := 0; end; procedure TMainForm.FormShow(Sender: TObject); var Position: TPosition; begin LoadLib; Position := StartBoard; PositionFrame.Debug := Memo.Lines; PositionFrame.OnAcceptMove := AcceptMove; NewGameAction.Execute; BeginerAction.Execute; MachineBlackAction.Execute; end; procedure TMainForm.SelectCellBtnClick(Sender: TObject); begin PositionFrame.SelectCell(1, 6); end; procedure TMainForm.AcceptMove(Sender: TObject; const NewPosition: TPosition); var St: string; begin GameHistory.AddMove(NewPosition); PositionFrame.SetPosition(NewPosition); St := GameOver(NewPosition); if St <> '' then begin ShowMessage(St); PositionFrame.AcceptMove := False; Exit; end; TuneState; end; procedure TMainForm.FormResize(Sender: TObject); begin PositionFrame.Left := 3; PositionFrame.Top := 3; Memo.Left := 3; Memo.Top := PositionFrame.Top + PositionFrame.Height + 3; Memo.Width := ClientWidth - 6; Memo.Height := ClientHeight - PositionFrame.Height - 9; PartyView.Left := PositionFrame.Left + PositionFrame.Width + 3; PartyView.Width := ClientWidth - PositionFrame.Width - 9; PartyView.Top := 3; PartyView.Height := PositionFrame.Height; PartyView.Columns[0].Width := 30; PartyView.Columns[1].Width := (PartyView.Width - 40) div 2; PartyView.Columns[2].Width := (PartyView.Width - 40) div 2; end; procedure TMainForm.DoMove(var Message: TMessage); var NewPosition: TPosition; begin NewPosition := TPosition(Pointer(Message.WParam)^); CloseHandle(ThreadHandle); ThreadHandle := 0; AcceptMove(nil, NewPosition); end; procedure TMainForm.FormCreate(Sender: TObject); begin FMode := mdMachineBlack; Memo.Clear; DoubleBuffered := True; FGameHistory := TGameHistory.Create; end; procedure TMainForm.TuneState; var RunThinker: Boolean; ThreadId: Cardinal; Index: Integer; V: Integer; begin if ThreadHandle <> 0 then StopThinking; PositionFrame.AcceptMove := (Mode = mdView) or ((Mode = mdMachineWhite) and (PositionFrame.Position.Active = ActiveBlack)) or ((Mode = mdMachineBlack) and (PositionFrame.Position.Active = ActiveWhite)); RunThinker := (Mode = mdTwoMachine) or ((Mode = mdMachineWhite) and (PositionFrame.Position.Active = ActiveWhite)) or ((Mode = mdMachineBlack) and (PositionFrame.Position.Active = ActiveBlack)); if DebugMenu.Visible then begin Index := Lib.IndexOf(FormatPosition(PositionFrame.Position)); if Index <> -1 then begin V := Integer(Lib.Objects[Index]); Memo.Lines.Add(Format('Theory = %.3f', [V/200])); end; end; if not RunThinker then Exit; ThreadHandle := BeginThread(nil, 8*4096, @Thinker, @PositionFrame.Position, CREATE_SUSPENDED, ThreadId); SetThreadPriority(ThreadHandle, THREAD_PRIORITY_BELOW_NORMAL); ResumeThread(ThreadHandle); end; procedure TMainForm.DoDebug(var Message: TMessage); var Position: PPosition; begin if not DebugMenu.Visible then Exit; if Message.WPAram = 0 then begin Memo.Clear; Exit; end; Position := Pointer(Message.WPAram); Memo.Lines.Add(Format('E=%d N=%.3f M=%s', [Message.LParam, Message.LParam/200, GetLastMove(Position^)])); end; procedure TMainForm.IsAnimation(var Message: TMessage); begin if PositionFrame.Animate then Message.Result := 1 else Message.Result := 0 end; const MAX_LEN = 60; procedure TMainForm.StopThinking; begin TerminateThread(ThreadHandle, 0); CloseHandle(ThreadHandle); ThreadHandle := 0; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(FGameHistory); end; procedure TMainForm.UndoMoveItemClick(Sender: TObject); begin end; { TGameHistory } procedure TGameHistory.AddWhiteMove(const Move: string); var NewItem: TListItem; begin NewItem := PartyView.Items.Add; NewItem.Caption := IntToStr((MoveNo div 2) + 1); NewItem.Subitems.Add(Move); PartyView.Selected := NewItem; PartyView.Selected.MakeVisible(False); end; procedure TGameHistory.AddBlackMove(const Move: string); var Item: TListItem; begin Assert(MainForm.PartyView.Items.Count > 0); Item := PartyView.Items[PartyView.Items.Count-1]; Item.Subitems.Add(Move); PartyView.Selected := Item; PartyView.Selected.MakeVisible(False); end; procedure TGameHistory.AddMove(NewPosition: TPosition); var Move: string; begin Move := GetLastMove(NewPosition); if Move <> '' then if FPositions[MoveNo].Active = ActiveWhite then AddWhiteMove(Move) else AddBlackMove(Move); MoveNo := MoveNo + 1; FPositions[MoveNo] := NewPosition; end; procedure TGameHistory.NewGame; begin MoveNo := 0; PartyView.Items.Clear; FPositions[0] := StartBoard; PositionFrame.SetPosition(StartBoard); end; function TGameHistory.GetPartyView: TListView; begin Result := MainForm.PartyView; end; function TGameHistory.GetPositionFrame: TPositionFrame; begin Result := MainForm.PositionFrame; end; procedure TGameHistory.Undo; var Last: Integer; Item: TListItem; begin Assert(MoveNo > 0); MainForm.ViewItem.Click; MoveNo := MoveNo - 1; PositionFrame.SetPosition(FPositions[MoveNo], False); Last := PartyView.Items.Count-1; Assert(Last >= 0); Item := PartyView.Items[Last]; if Item.SubItems.Count > 1 then Item.SubItems.Delete(1) else PartyView.Items.Delete(Last); end; procedure TMainForm.NewGameActionExecute(Sender: TObject); begin StopThinking; GameHistory.NewGame; if Mode in [mdMachineWhite, mdTwoMachine] then MachineBlackItem.Click; PositionFrame.AcceptMove := True; end; procedure TMainForm.Deselect(Action: TAction; const Category: string); var I: Integer; begin for I := 0 to ActionList.ActionCount - 1 do begin if ActionList.Actions[I].Category <> Category then Continue; if ActionList.Actions[I] = Action then Continue; (ActionList.Actions[I] as TAction).Checked := False; end; end; procedure TMainForm.LevelActionExecute(Sender: TObject); begin Deselect(Sender as TAction, 'Level'); with Sender as TAction do begin Checked := True; Deep := Tag; end; end; procedure TMainForm.UndoMoveActionExecute(Sender: TObject); begin GameHistory.Undo; end; procedure TMainForm.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin UndoMoveAction.Enabled := GameHistory.MoveNo > 0; end; procedure TMainForm.ExitActionExecute(Sender: TObject); begin ViewItem.Click; Close; end; procedure TMainForm.MachineWhiteActionExecute(Sender: TObject); begin Deselect(Sender as TAction, 'Mode'); (Sender as TAction).Checked := True; if Mode = mdMachineWhite then Exit; FMode := mdMachineWhite; PositionFrame.FlipBoard := True; TuneState; end; procedure TMainForm.MachineBlackActionExecute(Sender: TObject); begin Deselect(Sender as TAction, 'Mode'); (Sender as TAction).Checked := True; if Mode = mdMachineBlack then Exit; FMode := mdMachineBlack; PositionFrame.FlipBoard := False; TuneState; end; procedure TMainForm.TwoMachineActionExecute(Sender: TObject); begin Deselect(Sender as TAction, 'Mode'); (Sender as TAction).Checked := True; if Mode = mdTwoMachine then Exit; FMode := mdTwoMachine; TuneState; end; procedure TMainForm.ViewGameActionExecute(Sender: TObject); begin Deselect(Sender as TAction, 'Mode'); (Sender as TAction).Checked := True; if Mode = mdView then Exit; FMode := mdView; ViewItem.Checked := True; if ThreadHandle <> 0 then StopThinking; end; procedure TMainForm.FlipBoardActionExecute(Sender: TObject); begin PositionFrame.FlipBoard := not PositionFrame.FlipBoard; end; procedure TMainForm.SetPositionActionExecute(Sender: TObject); var Position: TPosition; begin ViewItem.Click; FillChar(Position.Field, 32, $00); Position.Field[31] := -20; Position.Field[29] := 70; Position.Active := ActiveWhite; // Position.Field[0] := 20; // Position.Field[2] := -70; // Position.Active := ActiveBlack; Position.MoveCount := 0; PositionFrame.SetPosition(Position); end; procedure TMainForm.AddToLibraryActionExecute(Sender: TObject); var V: Integer; Estimate: string; PositionFmt: string; Index: Integer; begin DecimalSeparator := '.'; Estimate := InputBox('Input', 'Please, enter estimate', ''); if Estimate = '' then Exit; Estimate := StringReplace(Estimate, ',', '.', []); V := Round(200 * StrToFloat(Estimate)); PositionFmt := FormatPosition(PositionFrame.Position); Index := Lib.IndexOf(PositionFmt); if Index = -1 then Lib.AddObject(PositionFmt, TObject(V)) else begin Lib.Sorted := False; Lib[Index] := PositionFmt; Lib.Objects[Index] := TObject(V); Lib.Sorted := True; end; SaveLib; end; procedure TMainForm.CopyGameActionExecute(Sender: TObject); var MoveNo: Integer; Item: TListItem; CurrentSt: string; AllParty: TStringList; procedure Add(const St: string); begin if Length(CurrentSt) + Length(St) + 1 > MAX_LEN then begin AllParty.Add(CurrentSt); CurrentSt := ''; end; if CurrentSt <> '' then CurrentSt := CurrentSt + ' '; CurrentSt := CurrentSt + St; end; begin AllParty := TStringList.Create; try CurrentSt := ''; for MoveNo := 0 to PartyView.Items.Count-1 do begin Item := PartyView.Items[MoveNo]; Add(Item.Caption + '.'); Add(Item.SubItems[0]); if Item.SubItems.Count > 1 then Add(Item.SubItems[1]); end; if CurrentSt <> '' then AllParty.Add(CurrentSt); Clipboard.AsText := AllParty.Text; finally AllParty.Free; end; end; end.
unit fos_firmbox_applianceapp; {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FOS_TOOL_INTERFACES, fre_hal_schemes, FRE_DB_INTERFACE,fos_stats_control_interface,fos_firmbox_vm_machines_mod, fre_system, FRE_DB_COMMON, fre_zfs; type TAppliancePerformanceData = record cpu_aggr_sys : Single; cpu_aggr_sys_user : Single; net_aggr_rx_bytes : single; net_aggr_tx_bytes : single; disk_aggr_wps : single; disk_aggr_rps : single; vmstat_memory_free : single; vmstat_memory_swap : single; cache_relMisses : single; cache_relHits : single; end; var G_HACK_SHARE_OBJECT : IFRE_DB_Object; G_AppliancePerformanceBuffer : array [0..179] of TAppliancePerformanceData; G_AppliancePerformanceCurrentIdx : NativeInt=1; type { TFRE_FIRMBOX_APPLIANCE_APP } TFRE_FIRMBOX_APPLIANCE_APP=class(TFRE_DB_APPLICATION) private procedure SetupApplicationStructure ; override; procedure _UpdateSitemap (const session: TFRE_DB_UserSession); protected procedure MySessionInitialize (const session: TFRE_DB_UserSession);override; procedure MySessionPromotion (const session: TFRE_DB_UserSession); override; public class procedure RegisterSystemScheme (const scheme:IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; class procedure InstallDBObjects4SysDomain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override; published function WEB_RAW_DATA_FEED (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RAW_DATA_FEED30 (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; { TFRE_FIRMBOX_APPLIANCE_STATUS_MOD } TFRE_FIRMBOX_APPLIANCE_STATUS_MOD = class (TFRE_DB_APPLICATION_MODULE) private FtotalSwap,FtotalRam : Integer; //in kb FtotalNet : Integer; //in byte procedure _fillPoolCollection (const conn: IFRE_DB_CONNECTION; const data: IFRE_DB_Object); procedure _SendData (const session: IFRE_DB_UserSession); procedure _HandleRegisterSend (session : TFRE_DB_UserSession); protected class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; procedure SetupAppModuleStructure ; override; procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);override; procedure MyServerInitializeModule (const admin_dbc : IFRE_DB_CONNECTION); override; procedure UpdateDiskCollection (const pool_disks : IFRE_DB_COLLECTION ; const data:IFRE_DB_Object); //obsolete, change to new collection published function WEB_Content (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_CPUStatusStopStart (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_CPUStatusInit (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_NetStatusStopStart (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_NetStatusInit (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RAMStatusStopStart (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RAMStatusInit (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DiskStatusStopStart (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DiskStatusInit (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_CacheStatusStopStart (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_CacheStatusInit (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RAW_UPDATE (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RAW_UPDATE30 (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; { TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD } TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD = class (TFRE_DB_APPLICATION_MODULE) private protected class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; procedure SetupAppModuleStructure ; override; public procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);override; published function WEB_Content (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ContentSystem (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ContentDatalink (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ContentFC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_SYSTEMContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_SYSTEMMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DatalinkContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DatalinkMenu (const input:IFRE_DB_OBject; const ses: IFRE_DB_Usersession ; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DatalinkCreateAggr (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_FCContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_FCMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; { TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD } TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD = class (TFRE_DB_APPLICATION_MODULE) private protected class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; procedure SetupAppModuleStructure ; override; public procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);override; published function WEB_Content (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; procedure Register_DB_Extensions; implementation var __idxCPU,__idxRAM,__idxCache,__idxDisk,__idxNet: NativeInt; //FIXXXME - remove me __SendAdded : boolean; { TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD } class procedure TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE'); end; procedure TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD.SetupAppModuleStructure; begin inherited SetupAppModuleStructure; InitModuleDesc('analytics_description') end; procedure TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD.MySessionInitializeModule(const session: TFRE_DB_UserSession); begin inherited MySessionInitializeModule(session); end; function TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD.WEB_Content(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; begin result := GFRE_DB_NIL_DESC; end; { TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD } class procedure TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE'); end; procedure TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.SetupAppModuleStructure; begin inherited SetupAppModuleStructure; InitModuleDesc('settings_description') end; procedure TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.MySessionInitializeModule(const session: TFRE_DB_UserSession); var datalink_dc : IFRE_DB_DERIVED_COLLECTION; datalink_tr_Grid : IFRE_DB_SIMPLE_TRANSFORM; fc_dc : IFRE_DB_DERIVED_COLLECTION; fc_tr_Grid : IFRE_DB_SIMPLE_TRANSFORM; system_dc : IFRE_DB_DERIVED_COLLECTION; system_tr_Grid : IFRE_DB_SIMPLE_TRANSFORM; app : TFRE_DB_APPLICATION; conn : IFRE_DB_CONNECTION; begin inherited; app := GetEmbeddingApp; conn := session.GetDBConnection; if session.IsInteractiveSession then begin GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,datalink_tr_Grid); with datalink_tr_Grid do begin //AddOneToOnescheme('icon','',app.FetchAppTextShort(conn,'datalink_icon'),dt_icon); AddOneToOnescheme('objname','linkname',app.FetchAppTextShort(session,'datalink_name'),dt_string,true,false,false,true,1,'icon'); // AddOneToOnescheme('zoned','zoned',app.FetchAppTextShort(conn,'datalink_zoned')); AddCollectorscheme('%s',TFRE_DB_NameTypeArray.Create('desc.txt') ,'description', app.FetchAppTextShort(session,'datalink_desc')); end; datalink_dc := session.NewDerivedCollection('APPLIANCE_SETTINGS_MOD_DATALINK_GRID'); with datalink_dc do begin SetDeriveParent(conn.GetCollection('datalink')); SetDeriveTransformation(datalink_tr_Grid); // AddBooleanFieldFilter('zoned','zoned',false); Filters.AddBooleanFieldFilter('showglobal','showglobal',true); SetDisplayType (cdt_Listview,[cdgf_Children,cdgf_ShowSearchbox,cdgf_ColumnDragable,cdgf_ColumnHideable,cdgf_ColumnResizeable],'',CWSF(@WEB_DatalinkMenu),nil,CWSF(@WEB_DatalinkContent)); SetParentToChildLinkField ('<PARENTID'); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,system_tr_Grid); with system_tr_Grid do begin AddOneToOnescheme('objname','Name',app.FetchAppTextShort(session,'system_name')); AddCollectorscheme('%s',TFRE_DB_NameTypeArray.Create('desc.txt') ,'description', app.FetchAppTextShort(session,'system_desc')); end; system_dc := session.NewDerivedCollection('APPLIANCE_SETTINGS_MOD_SYSTEM_GRID'); with system_dc do begin SetDeriveParent(conn.GetCollection('setting')); SetDeriveTransformation(system_tr_Grid); SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_SYSTEMMenu),nil,CWSF(@WEB_SYSTEMContent)); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,fc_tr_Grid); with fc_tr_Grid do begin AddOneToOnescheme('objname','wwn',app.FetchAppTextShort(session,'fc_wwn')); AddOneToOnescheme('targetmode','targetmode',app.FetchAppTextShort(session,'fc_targetmode')); AddOneToOnescheme('state','state',app.FetchAppTextShort(session,'fc_state')); AddCollectorscheme('%s',TFRE_DB_NameTypeArray.Create('desc.txt') ,'description', app.FetchAppTextShort(session,'fc_desc')); end; fc_dc := session.NewDerivedCollection('APPLIANCE_SETTINGS_MOD_FC_GRID'); with fc_dc do begin SetDeriveParent(conn.GetCollection('hba')); SetDeriveTransformation(fc_tr_Grid); SetDisplayType(cdt_Listview,[cdgf_ShowSearchbox,cdgf_ColumnDragable,cdgf_ColumnHideable,cdgf_ColumnResizeable],'',CWSF(@WEB_FCMenu),nil,CWSF(@WEB_FCContent)); end; end; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_Content(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var sub_sec_s : TFRE_DB_SUBSECTIONS_DESC; begin CheckClassVisibility4MyDomain(ses); sub_sec_s := TFRE_DB_SUBSECTIONS_DESC.Create.Describe(sec_dt_tab); sub_sec_s.AddSection.Describe(CWSF(@WEB_ContentSystem),app.FetchAppTextShort(ses,'appliance_settings_system'),1,'system'); sub_sec_s.AddSection.Describe(CWSF(@WEB_ContentDatalink),app.FetchAppTextShort(ses,'appliance_settings_datalink'),2,'datalink'); // sub_sec_s.AddSection.Describe(TFRE_DB_HTML_DESC.create.Describe('iscsi'),app.FetchAppTextShort(conn,'appliance_settings_iscsi'),3,'iscsi'); //sub_sec_s.AddSection.Describe(CWSF(@WEB_ContentFC),app.FetchAppTextShort(ses,'appliance_settings_fibrechannel'),4,'fibrechannel'); result := sub_sec_s; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_ContentSystem(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var grid_system : TFRE_DB_VIEW_LIST_DESC; dc_system : IFRE_DB_DERIVED_COLLECTION; system_content : TFRE_DB_FORM_PANEL_DESC; begin CheckClassVisibility4MyDomain(ses); dc_system := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_SYSTEM_GRID'); grid_system := dc_system.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; system_content :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'system_content_header')); system_content.contentId :='SYSTEM_CONTENT'; Result := TFRE_DB_LAYOUT_DESC.create.Describe.SetLayout(grid_system,system_content,nil,nil,nil,true,1,4); end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_ContentDatalink(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var grid_datalink : TFRE_DB_VIEW_LIST_DESC; dc_datalink : IFRE_DB_DERIVED_COLLECTION; datalink_content: TFRE_DB_FORM_PANEL_DESC; txt : IFRE_DB_TEXT; begin CheckClassVisibility4MyDomain(ses); dc_datalink := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_DATALINK_GRID'); grid_datalink := dc_datalink.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; if conn.sys.CheckClassRight4MyDomain(sr_STORE,TFRE_DB_DATALINK_AGGR) then begin txt:=app.FetchAppTextFull(ses,'create_aggr'); grid_datalink.AddButton.Describe(CWSF(@WEB_DatalinkCreateAggr),'images_apps/firmbox_appliance/create_aggr.png',txt.Getshort,txt.GetHint); txt.Finalize; end; datalink_content := TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'datalink_content_header')); datalink_content.contentId :='DATALINK_CONTENT'; Result := TFRE_DB_LAYOUT_DESC.create.Describe.SetLayout(grid_datalink,datalink_content,nil,nil,nil,true,1,1); end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_ContentFC(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var grid_fc : TFRE_DB_VIEW_LIST_DESC; dc_fc : IFRE_DB_DERIVED_COLLECTION; fc_content : TFRE_DB_FORM_PANEL_DESC; begin CheckClassVisibility4MyDomain(ses); dc_fc := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_FC_GRID'); grid_fc := dc_fc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; fc_content :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'fc_content_header')); fc_content.contentId:='FC_HBA_CONTENT'; Result := TFRE_DB_LAYOUT_DESC.create.Describe.SetLayout(grid_fc,fc_content,nil,nil,nil,true,2); end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_SYSTEMContent(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var panel : TFRE_DB_FORM_PANEL_DESC; scheme : IFRE_DB_SchemeObject; dc : IFRE_DB_DERIVED_COLLECTION; so : IFRE_DB_Object; sel_guid : TFRE_DB_GUID; menu : TFRE_DB_MENU_DESC; begin if input.Field('SELECTED').ValueCount>0 then begin sel_guid := input.Field('SELECTED').AsGUID; dc := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_SYSTEM_GRID'); if dc.FetchInDerived(sel_guid,so) then begin GetSystemSchemeByName(so.SchemeClass,scheme); panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'system_content_header')); panel.AddSchemeFormGroup(scheme.GetInputGroup('main'),GetSession(input)); panel.AddSchemeFormGroup(scheme.GetInputGroup('setting'),GetSession(input)); panel.FillWithObjectValues(so,GetSession(input)); if so.SchemeClass=TFRE_DB_MACHINE_SETTING_POWER.ClassName then begin menu:=TFRE_DB_MENU_DESC.create.Describe; menu.AddEntry.Describe(app.FetchAppTextShort(ses,'system_reboot'),'',TFRE_DB_SERVER_FUNC_DESC.create.Describe(so,'Reboot')); menu.AddEntry.Describe(app.FetchAppTextShort(ses,'system_shutdown'),'',TFRE_DB_SERVER_FUNC_DESC.create.Describe(so,'Shutdown')); panel.SetMenu(menu); end else panel.AddButton.Describe('Save',TFRE_DB_SERVER_FUNC_DESC.create.Describe(so,'saveOperation'),fdbbt_submit); panel.contentId:='SYSTEM_CONTENT'; Result:=panel; end; end else begin panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'system_content_header')); panel.contentId:='SYSTEM_CONTENT'; Result:=panel; end; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_SYSTEMMenu(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin result := GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_DatalinkContent(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var panel : TFRE_DB_FORM_PANEL_DESC; scheme : IFRE_DB_SchemeObject; dc : IFRE_DB_DERIVED_COLLECTION; dl : IFRE_DB_Object; sel_guid : TFRE_DB_GUID; begin if input.Field('SELECTED').ValueCount=1 then begin sel_guid := input.Field('SELECTED').AsGUID; dc := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_DATALINK_GRID'); if dc.FetchInDerived(sel_guid,dl) then begin GetSystemSchemeByName(dl.SchemeClass,scheme); panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'datalink_content_header')); panel.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses); panel.FillWithObjectValues(dl,ses); panel.contentId:='DATALINK_CONTENT'; panel.AddButton.Describe('Save',TFRE_DB_SERVER_FUNC_DESC.create.Describe(dl,'saveOperation'),fdbbt_submit); Result:=panel; end; end else begin panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'datalink_content_header')); panel.contentId:='DATALINK_CONTENT'; Result:=panel; end; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_DatalinkMenu(const input: IFRE_DB_OBject; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_MENU_DESC; func : TFRE_DB_SERVER_FUNC_DESC; dc : IFRE_DB_DERIVED_COLLECTION; dl : IFRE_DB_Object; sel_guid : TFRE_DB_GUID; sclass : TFRE_DB_NameType; begin Result:=GFRE_DB_NIL_DESC; if conn.sys.CheckClassRight4MyDomain(sr_STORE,TFRE_DB_DATALINK_VNIC) or conn.sys.CheckClassRight4MyDomain(sr_DELETE,TFRE_DB_DATALINK_VNIC) or conn.sys.CheckClassRight4MyDomain(sr_DELETE,TFRE_DB_DATALINK_AGGR) or conn.sys.CheckClassRight4MyDomain(sr_DELETE,TFRE_DB_DATALINK_STUB) then begin if input.Field('SELECTED').ValueCount=1 then begin sel_guid := input.Field('SELECTED').AsGUID; dc := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_DATALINK_GRID'); if dc.FetchInDerived(sel_guid,dl) then begin sclass := dl.SchemeClass; writeln(schemeclass); if conn.sys.CheckClassRight4MyDomain(sr_STORE,TFRE_DB_DATALINK_VNIC) then input.Field('add_vnic').AsString := app.FetchAppTextShort(ses,'datalink_add_vnic'); if conn.sys.CheckClassRight4MyDomain(sr_DELETE,TFRE_DB_DATALINK_VNIC) then input.Field('delete_vnic').AsString := app.FetchAppTextShort(ses,'datalink_delete_vnic'); if conn.sys.CheckClassRight4MyDomain(sr_DELETE,TFRE_DB_DATALINK_AGGR) then input.Field('delete_aggr').AsString := app.FetchAppTextShort(ses,'datalink_delete_aggr'); if conn.sys.CheckClassRight4MyDomain(sr_DELETE,TFRE_DB_DATALINK_STUB) then input.Field('delete_stub').AsString := app.FetchAppTextShort(ses,'datalink_delete_stub'); result := dl.Invoke('Menu',input,ses,app,conn); end; end; end; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_DatalinkCreateAggr(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var scheme : IFRE_DB_SchemeObject; res : TFRE_DB_FORM_DIALOG_DESC; serverfunc : TFRE_DB_SERVER_FUNC_DESC; begin if not conn.sys.CheckClassRight4MyDomain(sr_STORE,TFRE_DB_DATALINK_AGGR) then raise EFRE_DB_Exception.Create('No access to edit settings!'); GetSystemScheme(TFRE_DB_DATALINK_AGGR,scheme); res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(app.FetchAppTextShort(ses,'aggr_add_diag_cap'),600,true,true,false); res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false); res.SetElementValue('objname','aggr'); serverfunc := TFRE_DB_SERVER_FUNC_DESC.create.Describe(TFRE_DB_DATALINK_AGGR.ClassName,'NewOperation'); serverFunc.AddParam.Describe('collection','datalink'); res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),serverfunc,fdbbt_submit); Result:=res; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_FCContent(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var panel : TFRE_DB_FORM_PANEL_DESC; scheme : IFRE_DB_SchemeObject; dc : IFRE_DB_DERIVED_COLLECTION; fc : IFRE_DB_Object; sel_guid : TFRE_DB_GUID; begin if input.Field('SELECTED').ValueCount>0 then begin sel_guid := input.Field('SELECTED').AsGUID; dc := GetSession(input).FetchDerivedCollection('APPLIANCE_SETTINGS_MOD_FC_GRID'); if dc.FetchInDerived(sel_guid,fc) then begin GetSystemSchemeByName(fc.SchemeClass,scheme); panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'fc_content_header')); panel.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses); panel.FillWithObjectValues(fc,ses); panel.AddButton.Describe('Save',TFRE_DB_SERVER_FUNC_DESC.create.Describe(fc,'saveOperation'),fdbbt_submit); panel.contentId:='FC_HBA_CONTENT'; Result:=panel; end; end else begin panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(app.FetchAppTextShort(ses,'fc_content_header')); panel.contentId:='FC_HBA_CONTENT'; Result:=panel; end; end; function TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.WEB_FCMenu(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin result := GFRE_DB_NIL_DESC; end; { TFRE_FIRMBOX_APPLIANCE_STATUS_MOD } procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD._fillPoolCollection(const conn: IFRE_DB_CONNECTION; const data: IFRE_DB_Object); var coll : IFRE_DB_COLLECTION; pool_space: IFRE_DB_Object; upObj : IFRE_DB_Object; procedure _addValues(const obj: IFRE_DB_Object); begin case obj.Field('name').AsString of 'used' : begin obj.Field('value').AsReal32 := data.FieldPath(cDEBUG_ZPOOL_NAME+'.used').AsInt64; obj.Field('value_lbl').AsString := GFRE_BT.ByteToString(data.FieldPath(cDEBUG_ZPOOL_NAME+'.used').AsInt64); end; 'avail': begin obj.Field('value').AsReal32 := data.FieldPath(cDEBUG_ZPOOL_NAME+'.available').AsInt64; obj.Field('value_lbl').AsString := GFRE_BT.ByteToString(data.FieldPath(cDEBUG_ZPOOL_NAME+'.available').AsInt64); end; 'ref' : begin obj.Field('value').AsReal32 := data.FieldPath(cDEBUG_ZPOOL_NAME+'.referenced').AsInt64; obj.Field('value_lbl').AsString := GFRE_BT.ByteToString(data.FieldPath(cDEBUG_ZPOOL_NAME+'.referenced').AsInt64); end; end; CheckDbResult(coll.Update(obj),'Update pool space'); end; begin coll := conn.GetCollection('ZONES_SPACE'); //coll.ForAll(@_addValues); end; procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD._SendData(const session: IFRE_DB_UserSession); var res : TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC; totalCache : Int64; begin if __idxCPU>-1 then begin with G_AppliancePerformanceBuffer[G_AppliancePerformanceCurrentIdx] do res:=TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC.create.Describe('appl_stat_cpu',__idxCPU,TFRE_DB_Real32Array.create(cpu_aggr_sys,cpu_aggr_sys_user)); inc(__idxCPU); session.SendServerClientRequest(res); end; if __idxNet>-1 then begin with G_AppliancePerformanceBuffer[G_AppliancePerformanceCurrentIdx] do res:=TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC.create.Describe('appl_stat_net',__idxNet,TFRE_DB_Real32Array.create(net_aggr_rx_bytes,net_aggr_tx_bytes)); inc(__idxNet); session.SendServerClientRequest(res); end; if __idxDisk>-1 then begin with G_AppliancePerformanceBuffer[G_AppliancePerformanceCurrentIdx] do res:=TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC.create.Describe('appl_stat_disk',__idxDisk,TFRE_DB_Real32Array.create(disk_aggr_wps,disk_aggr_rps)); inc(__idxDisk); session.SendServerClientRequest(res); end; if __idxRAM>-1 then begin with G_AppliancePerformanceBuffer[G_AppliancePerformanceCurrentIdx] do res:=TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC.create.Describe('appl_stat_ram',__idxRAM,TFRE_DB_Real32Array.create(vmstat_memory_free,vmstat_memory_swap)); inc(__idxRAM); session.SendServerClientRequest(res); end; if __idxCache>-1 then begin with G_AppliancePerformanceBuffer[G_AppliancePerformanceCurrentIdx] do res:=TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC.create.Describe('appl_stat_cache',__idxCache,TFRE_DB_Real32Array.create(cache_relMisses,cache_relHits)); inc(__idxCache); session.SendServerClientRequest(res); end; end; procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD._HandleRegisterSend(session : TFRE_DB_UserSession); begin if (__idxRAM=-1) and (__idxCache=-1) and (__idxDisk=-1) and (__idxNet=-1) and (__idxCPU=-1) then begin if __SendAdded then begin session.RemoveTaskMethod('ASM'); __SendAdded := false; writeln('DISABLE SEND'); end; end else if not __SendAdded then begin session.RegisterTaskMethod(@_SendData,1000,'ASM'); __SendAdded := true; writeln('ENABLE SEND'); end; end; class procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE'); end; procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.SetupAppModuleStructure; begin inherited SetupAppModuleStructure; InitModuleDesc('status_description') end; procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.MySessionInitializeModule(const session: TFRE_DB_UserSession); var DC_CHARTDATA_ZONES : IFRE_DB_DERIVED_COLLECTION; CHARTDATA : IFRE_DB_COLLECTION; busy,ast,rbw,wbw : IFRE_DB_DERIVED_COLLECTION; disks : IFRE_DB_COLLECTION; labels : TFRE_DB_StringArray; idx : NativeInt; conn : IFRE_DB_CONNECTION; procedure _AddDisk(const obj:IFRE_DB_Object); var diskname : string; begin diskname := obj.Field('caption').AsString; if Pos('C',diskname)=1 then begin labels[idx]:='D '+inttostr(idx); end else begin if Pos('RAM',diskname)=1 then begin labels[idx]:='RD'; end else begin labels[idx]:=diskname; end; end; idx:=idx+1; end; begin inherited MySessionInitializeModule(session); if session.IsInteractiveSession then begin conn:=session.GetDBConnection; __idxCPU:=-1;__idxRAM:=-1;__idxCache:=-1;__idxDisk:=-1;__idxNet:=-1; //CHARTDATA := conn.getCollection('ZONES_SPACE'); //FIXXME - Use LiveChart //DC_CHARTDATA_ZONES := session.NewDerivedCollection('DC_ZONES_SPACE'); //with DC_CHARTDATA_ZONES do begin // SetDeriveParent(CHARTDATA); // SetDisplayTypeChart('Space on Diskpool',fdbct_pie,TFRE_DB_StringArray.Create('value'),True,True,nil,true); //end; // //disks := conn.GetCollection('POOL_DISKS'); //idx:=0; // //ast := session.NewDerivedCollection('APP_POOL_AST'); //ast.SetDeriveParent(disks); //ast.SetDefaultOrderField('diskid',true); //ast.SetDisplayTypeChart('Pool Disk Avg. Service Time (ms)',fdbct_column,TFRE_DB_StringArray.Create('ast'),false,false,labels,false,20); //SetLength(labels,ast.ItemCount); //ast.ForAllDerived(@_AddDisk); //ast.SetDisplayTypeChart('Pool Disk Avg. Service Time (ms)',fdbct_column,TFRE_DB_StringArray.Create('ast'),false,false,labels,false,20); // Hack for labels, must be redone // //rbw := session.NewDerivedCollection('APP_POOL_RBW'); //rbw.SetDeriveParent(disks); //rbw.SetDefaultOrderField('diskid',true); //rbw.SetDisplayTypeChart('Raw Disk Bandwidth Read (kBytes/s)',fdbct_column,TFRE_DB_StringArray.Create('rbw'),false,false,labels,false,400000); // //wbw := session.NewDerivedCollection('APP_POOL_WBW'); //wbw.SetDeriveParent(disks); //wbw.SetDefaultOrderField('diskid',true); //wbw.SetDisplayTypeChart('Raw Disk Bandwidth Write (kBytes/s)',fdbct_column,TFRE_DB_StringArray.Create('wbw'),false,false,labels,false,400000); // //busy := session.NewDerivedCollection('APP_POOL_BUSY'); //busy.SetDeriveParent(disks); //busy.SetDefaultOrderField('diskid',true); //busy.SetDisplayTypeChart('Raw Disk Busy Times [%]',fdbct_column,TFRE_DB_StringArray.Create('b'),false,false,labels,false,100); end; end; procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.MyServerInitializeModule(const admin_dbc: IFRE_DB_CONNECTION); var coll : IFRE_DB_COLLECTION; used : Extended; avail : Extended; ref : Extended; space : IFRE_DB_Object; DISKI_HACK: IFOS_STATS_CONTROL; zfs_data : IFRE_DB_Object; begin inherited MyServerInitializeModule(admin_dbc); //FIXXME heli FtotalRam:=221242708; //in kb FtotalSwap:=338566808; //may change? mysessioninitializemodule better? feeder? FtotalNet:=100*1024*1024*2;//100MB * 2 Devices coll := admin_dbc.CreateCollection('ZONES_SPACE',true); coll.DefineIndexOnField('name',fdbft_String,true,true); space := GFRE_DBI.NewObject; space.Field('name').AsString := 'used'; space.Field('value_col').AsString := '#3A6D9E'; space.Field('value_leg').AsString := 'Used'; CheckDbResult(coll.Store(space),'Add zones space'); space := GFRE_DBI.NewObject; space.Field('name').AsString := 'avail'; space.Field('value_col').AsString := '#70A258'; space.Field('value_leg').AsString := 'Available'; CheckDbResult(coll.Store(space),'Add zones space'); space := GFRE_DBI.NewObject; space.Field('name').AsString := 'ref'; space.Field('value_col').AsString := '#EDAF49'; space.Field('value_leg').AsString := 'Referred'; CheckDbResult(coll.Store(space),'Add zones space'); //FIRMBOX TESTMODE STARTUP SPEED ENHANCEMENT //DISKI_HACK := Get_Stats_Control(cFRE_REMOTE_USER,cFRE_REMOTE_HOST); //RZNORD //_fillPoolCollection(admin_dbc,DISKI_HACK.Get_ZFS_Data_Once); coll := admin_dbc.CreateCollection('LIVE_STATUS',true); coll.DefineIndexOnField('feedname',fdbft_String,true,true); end; procedure TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.UpdateDiskCollection(const pool_disks: IFRE_DB_COLLECTION; const data: IFRE_DB_Object); var debugs : string; procedure UpdateDisks(const field:IFRE_DB_Field); var diskname : string; disk : IFRE_DB_Object; disko : IFRE_DB_Object; begin if field.FieldType=fdbft_Object then begin try diskname := field.FieldName; disko := field.AsObject; if diskname='DISK_AGGR' then exit; if pool_disks.GetIndexedObj(diskname,disk) then begin disk.Field('caption').AsString := diskname; disk.Field('ast').AsReal32 := disko.Field('actv_t').AsReal32; disk.Field('wbw').AsReal32 := disko.Field('kwps').AsReal32; disk.Field('rbw').AsReal32 := disko.Field('krps').AsReal32;; disk.Field('b').AsReal32 := disko.Field('perc_b').AsReal32; //writeln('>> ',format('%30.30s AST %05.1f WBW %05.1f RBW %05.1f BUSY %05.1f',[disk.Field('caption').AsString,disk.Field('ast').AsReal32,disk.Field('wbw').AsReal32,disk.Field('rbw').AsReal32,disk.Field('b').AsReal32])); pool_disks.Update(disk); end else begin disk := GFRE_DBI.NewObject; disk.Field('diskid').AsString := diskname; disk.Field('caption').AsString := diskname; disk.Field('ast_uid').AsGUID := disk.UID; disk.Field('wbw_uid').AsGUID := disk.UID; disk.Field('rbw_uid').AsGUID := disk.UID; disk.Field('b_uid').AsGUID := disk.UID; disk.Field('ast').AsReal32 := disko.Field('actv_t').AsReal32; disk.Field('wbw').AsReal32 := disko.Field('kwps').AsReal32; disk.Field('rbw').AsReal32 := disko.Field('krps').AsReal32;; disk.Field('b').AsReal32 := disko.Field('perc_b').AsReal32;; pool_disks.Store(disk); end; except on e:exception do begin writeln('>UPDATE DISK ERROR : ',e.Message); end;end; end; end; begin //obsolete exit; debugs := ''; {TODO - Use Explicit Transactions} //pool_disks.StartBlockUpdating; try data.ForAllFields(@UpdateDisks); finally //pool_disks.FinishBlockUpdating; end; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_Content(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var res,sub1,sub2 : TFRE_DB_LAYOUT_DESC; c1 : TFRE_DB_LAYOUT_DESC; c2,c3,c4,c5,c6 : TFRE_DB_LIVE_CHART_DESC; main : TFRE_DB_LAYOUT_DESC; sub3,sub4 : TFRE_DB_LAYOUT_DESC; left : TFRE_DB_LAYOUT_DESC; right : TFRE_DB_LAYOUT_DESC; sub1l : TFRE_DB_LAYOUT_DESC; sub2l : TFRE_DB_LAYOUT_DESC; begin CheckClassVisibility4MyDomain(ses); //c1:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(nil,ses.FetchDerivedCollection('DC_ZONES_SPACE').GetDisplayDescription,nil,nil,nil,false); c2:=TFRE_DB_LIVE_CHART_DESC.create.DescribeLine('appl_stat_cpu',2,120,CWSF(@WEB_CPUStatusStopStart),0,100,app.FetchAppTextShort(ses,'overview_caption_cpu'),TFRE_DB_StringArray.create('f00','0f0'), TFRE_DB_StringArray.create(app.FetchAppTextShort(ses,'overview_cpu_system_legend'),app.FetchAppTextShort(ses,'overview_cpu_user_legend')),11,CWSF(@WEB_CPUStatusInit)); c3:=TFRE_DB_LIVE_CHART_DESC.create.DescribeLine('appl_stat_net',2,120,CWSF(@WEB_NetStatusStopStart),0,100,app.FetchAppTextShort(ses,'overview_caption_net'),TFRE_DB_StringArray.create('f00','0f0'), TFRE_DB_StringArray.create(app.FetchAppTextShort(ses,'overview_net_receive_legend'),app.FetchAppTextShort(ses,'overview_net_transmit_legend')),11,CWSF(@WEB_NetStatusInit)); c4:=TFRE_DB_LIVE_CHART_DESC.create.DescribeLine('appl_stat_disk',2,120,CWSF(@WEB_DiskStatusStopStart),0,30,app.FetchAppTextShort(ses,'overview_caption_disk'),TFRE_DB_StringArray.create('f00','0f0'), TFRE_DB_StringArray.create(app.FetchAppTextShort(ses,'overview_disk_write_legend'),app.FetchAppTextShort(ses,'overview_disk_read_legend')),11,CWSF(@WEB_DiskStatusInit)); c5:=TFRE_DB_LIVE_CHART_DESC.create.DescribeLine('appl_stat_ram',2,120,CWSF(@WEB_RAMStatusStopStart),0,100,app.FetchAppTextShort(ses,'overview_caption_ram'),TFRE_DB_StringArray.create('f00','0f0'), TFRE_DB_StringArray.create(app.FetchAppTextShort(ses,'overview_ram_ram_legend'),app.FetchAppTextShort(ses,'overview_ram_swap_legend')),11,CWSF(@WEB_RAMStatusInit)); c6:=TFRE_DB_LIVE_CHART_DESC.create.DescribeLine('appl_stat_cache',2,120,CWSF(@WEB_CacheStatusStopStart),0,100,app.FetchAppTextShort(ses,'overview_caption_cache'),TFRE_DB_StringArray.create('f00','0f0'), TFRE_DB_StringArray.create(app.FetchAppTextShort(ses,'overview_cache_misses_legend'),app.FetchAppTextShort(ses,'overview_cache_hits_legend')),11,CWSF(@WEB_CacheStatusInit)); sub1l:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(c2,c5,nil,nil,nil,false,1,1); //sub1:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(sub1l,c1,nil,nil,nil,false,2,1); sub1:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(nil,sub1l,nil,nil,nil,false,2,1); sub2l:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(c3,c4,nil,nil,nil,false,1,1); sub2:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(sub2l,c6,nil,nil,nil,false,2,1); left:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(nil,sub2,nil,sub1,nil,false,-1,1,-1,1); //sub3:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(GetSession(input).FetchDerivedCollection('APP_POOL_BUSY').GetDisplayDescription,GetSession(input).FetchDerivedCollection('APP_POOL_AST').GetDisplayDescription,nil,nil,nil,false,1,1); //sub4:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(GetSession(input).FetchDerivedCollection('APP_POOL_WBW').GetDisplayDescription,GetSession(input).FetchDerivedCollection('APP_POOL_RBW').GetDisplayDescription,nil,nil,nil,false,1,1); //right:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(nil,sub4,nil,sub3,nil,false,-1,1,-1,1); //res:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(left,right,nil,nil,nil,false,3,2); res:=TFRE_DB_LAYOUT_DESC.create.Describe().SetLayout(nil,left,nil,nil,nil,false,3,2); result := res; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_CPUStatusStopStart(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin if input.Field('action').AsString='start' then __idxCPU:=0 else __idxCPU:=-1; _HandleRegisterSend(GetSession(input)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_CPUStatusInit(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var data : TFRE_DB_LIVE_CHART_DATA_ARRAY; i : Integer; start : Integer; bufidx: Integer; begin SetLength(data,2); SetLength(data[0],122); SetLength(data[1],122); start:=G_AppliancePerformanceCurrentIdx - 121; if start<0 then begin start:=Length(G_AppliancePerformanceBuffer) + start; end; for i := 0 to 121 do begin bufidx := (start + i) mod Length(G_AppliancePerformanceBuffer); data[0][i]:=G_AppliancePerformanceBuffer[bufidx].cpu_aggr_sys; data[1][i]:=G_AppliancePerformanceBuffer[bufidx].cpu_aggr_sys_user; end; Result:=TFRE_DB_LIVE_CHART_INIT_DATA_DESC.create.Describe(data); end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_NetStatusStopStart(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin if input.Field('action').AsString='start' then __idxNet:=0 else __idxNet:=-1; _HandleRegisterSend(GetSession(input)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_NetStatusInit(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var data : TFRE_DB_LIVE_CHART_DATA_ARRAY; i : Integer; start : Integer; bufidx: Integer; begin SetLength(data,2); SetLength(data[0],122); SetLength(data[1],122); start:=G_AppliancePerformanceCurrentIdx - 121; if start<0 then begin start:=Length(G_AppliancePerformanceBuffer) + start; end; for i := 0 to 121 do begin bufidx := (start + i) mod Length(G_AppliancePerformanceBuffer); data[0][i]:=G_AppliancePerformanceBuffer[bufidx].net_aggr_rx_bytes; data[1][i]:=G_AppliancePerformanceBuffer[bufidx].net_aggr_tx_bytes; end; Result:=TFRE_DB_LIVE_CHART_INIT_DATA_DESC.create.Describe(data); end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_RAMStatusStopStart(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin if input.Field('action').AsString='start' then __idxRAM:=0 else __idxRAM:=-1; _HandleRegisterSend(GetSession(input)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_RAMStatusInit(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var data : TFRE_DB_LIVE_CHART_DATA_ARRAY; i : Integer; start : Integer; bufidx: Integer; begin SetLength(data,2); SetLength(data[0],122); SetLength(data[1],122); start:=G_AppliancePerformanceCurrentIdx - 121; if start<0 then begin start:=Length(G_AppliancePerformanceBuffer) + start; end; for i := 0 to 121 do begin bufidx := (start + i) mod Length(G_AppliancePerformanceBuffer); data[0][i]:=G_AppliancePerformanceBuffer[bufidx].vmstat_memory_free; data[1][i]:=G_AppliancePerformanceBuffer[bufidx].vmstat_memory_swap; end; Result:=TFRE_DB_LIVE_CHART_INIT_DATA_DESC.create.Describe(data); end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_DiskStatusStopStart(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin if input.Field('action').AsString='start' then __idxDisk:=0 else __idxDisk:=-1; _HandleRegisterSend(GetSession(input)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_DiskStatusInit(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var data : TFRE_DB_LIVE_CHART_DATA_ARRAY; i : Integer; start : Integer; bufidx: Integer; begin SetLength(data,2); SetLength(data[0],122); SetLength(data[1],122); start:=G_AppliancePerformanceCurrentIdx - 121; if start<0 then begin start:=Length(G_AppliancePerformanceBuffer) + start; end; for i := 0 to 121 do begin bufidx := (start + i) mod Length(G_AppliancePerformanceBuffer); data[0][i]:=G_AppliancePerformanceBuffer[bufidx].disk_aggr_wps; data[1][i]:=G_AppliancePerformanceBuffer[bufidx].disk_aggr_rps; end; Result:=TFRE_DB_LIVE_CHART_INIT_DATA_DESC.create.Describe(data); end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_CacheStatusStopStart(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin if input.Field('action').AsString='start' then __idxCache:=0 else __idxCache:=-1; _HandleRegisterSend(GetSession(input)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_CacheStatusInit(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var // data : TFRE_DB_LIVE_CHART_INIT_DATA_ARRAY; i : Integer; start : Integer; bufidx: Integer; begin //SetLength(data,2); //SetLength(data[0],122); //SetLength(data[1],122); //start:=G_AppliancePerformanceCurrentIdx - 121; //if start<0 then begin // start:=Length(G_AppliancePerformanceBuffer) + start; //end; //for i := 0 to 121 do begin // bufidx := (start + i) mod Length(G_AppliancePerformanceBuffer); // data[0][i]:=G_AppliancePerformanceBuffer[bufidx].cache_relMisses; // data[1][i]:=G_AppliancePerformanceBuffer[bufidx].cache_relHits; //end; //Result:=TFRE_DB_LIVE_CHART_INIT_DATA_DESC.create.Describe(data); RESULT := TFRE_DB_MESSAGE_DESC.create.Describe('FIX','IT - CACHESTATUSINIT',fdbmt_info); end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_RAW_UPDATE(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var LIVE_DATA : IFRE_DB_COLLECTION; LD : IFRE_DB_Object; totalCache : Int64; begin if assigned(G_HACK_SHARE_OBJECT) then begin G_HACK_SHARE_OBJECT.Finalize; G_HACK_SHARE_OBJECT:=nil; end; G_HACK_SHARE_OBJECT := input.CloneToNewObject(); inc(G_AppliancePerformanceCurrentIdx); if G_AppliancePerformanceCurrentIdx>High(G_AppliancePerformanceBuffer) then G_AppliancePerformanceCurrentIdx:=0; with G_AppliancePerformanceBuffer[G_AppliancePerformanceCurrentIdx] do with G_HACK_SHARE_OBJECT do begin if FieldPathExists('cpu.cpu_aggr.sys') then begin cpu_aggr_sys := FieldPath('cpu.cpu_aggr.sys').AsReal32; cpu_aggr_sys_user := (FieldPath('cpu.cpu_aggr.sys').AsReal32 + FieldPath('cpu.cpu_aggr.usr').AsReal32); end; if FieldPathExists('net.net_aggr.rx.bytes') then begin net_aggr_rx_bytes := FieldPath('net.net_aggr.rx.bytes').AsInt32/FtotalNet*100; net_aggr_tx_bytes := FieldPath('net.net_aggr.tx.bytes').AsInt32/FtotalNet*100; end; if FieldPathExists('disk.disk_aggr.wps') then begin disk_aggr_wps := FieldPath('disk.disk_aggr.wps').AsInt32 / 1000; disk_aggr_rps := FieldPath('disk.disk_aggr.rps').AsInt32 / 1000; end; if FieldPathExists('vmstat.memory_free') then begin vmstat_memory_free := (1-(FieldPath('vmstat.memory_free').AsInt32 / FtotalRam)) * 100; vmstat_memory_swap := (1-(FieldPath('vmstat.memory_swap').AsInt32 / FtotalSwap)) * 100; end; if FieldPathExists('cache.relHits') then begin totalCache := FieldPath('cache.relHits').AsInt64 +FieldPath('cache.relMisses').AsInt64; if totalCache=0 then totalCache:=1; cache_relMisses := FieldPath('cache.relMisses').AsInt64 / totalCache * 100; cache_relHits := FieldPath('cache.relHits').AsInt64 / totalCache * 100; end; end; //LIVE_DATA := GetDBConnection(raw_data).Collection('LIVE_STATUS',false,false); //if LIVE_DATA.GetIndexedObj('live',ld) then // begin // ld.Field('data').AsObject := raw_data.CloneToNewObject; // //LIVE_DATA.Update(ld); // end //else // begin // ld := GFRE_DBI.NewObject; // ld.Field('feedname').AsString:='live'; // ld.Field('data').AsObject := raw_data.CloneToNewObject; // writeln(ld.DumpToString()); // LIVE_DATA.Store(ld); // Abort; // halt; // end; // result := GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.WEB_RAW_UPDATE30(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var coll : IFRE_DB_COLLECTION; begin //TURN OFF SAFETY //_fillPoolCollection(ses.GetDBConnection,input.Field('zfs').AsObject); result := GFRE_DB_NIL_DESC; end; { TFRE_FIRMBOX_APPLIANCE_APP } procedure TFRE_FIRMBOX_APPLIANCE_APP.SetupApplicationStructure; begin inherited SetupApplicationStructure; InitApp('description'); AddApplicationModule(TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.create); AddApplicationModule(TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.create); //AddApplicationModule(TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD.create); end; procedure TFRE_FIRMBOX_APPLIANCE_APP._UpdateSitemap(const session: TFRE_DB_UserSession); var SiteMapData : IFRE_DB_Object; conn : IFRE_DB_CONNECTION; begin conn:=session.GetDBConnection; SiteMapData := GFRE_DBI.NewObject; FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status',FetchAppTextShort(session,'sitemap_main'),'images_apps/firmbox_appliance/appliance_white.svg','',0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFRE_FIRMBOX_APPLIANCE_APP)); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/Overview',FetchAppTextShort(session,'sitemap_status'),'images_apps/firmbox_appliance/status_white.svg',TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.Classname,0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFRE_FIRMBOX_APPLIANCE_STATUS_MOD)); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/Settings',FetchAppTextShort(session,'sitemap_settings'),'images_apps/firmbox_appliance/settings_white.svg',TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.Classname,0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD)); //FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/Analytics',FetchAppTextShort(session,'sitemap_analytics'),'images_apps/firmbox_appliance/analytics_white.svg',TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD.ClassName,0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD)); FREDB_SiteMap_RadialAutoposition(SiteMapData); session.GetSessionAppData(Classname).Field('SITEMAP').AsObject := SiteMapData; end; procedure TFRE_FIRMBOX_APPLIANCE_APP.MySessionInitialize(const session: TFRE_DB_UserSession); begin inherited MySessionInitialize(session); if session.IsInteractiveSession then begin _UpdateSitemap(session); end; end; procedure TFRE_FIRMBOX_APPLIANCE_APP.MySessionPromotion(const session: TFRE_DB_UserSession); begin inherited MySessionPromotion(session); if session.IsInteractiveSession then _UpdateSitemap(session); end; class procedure TFRE_FIRMBOX_APPLIANCE_APP.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION'); end; class procedure TFRE_FIRMBOX_APPLIANCE_APP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if (currentVersionId='') then begin currentVersionId := '1.0'; CreateAppText(conn,'caption','Appliance','Appliance','Appliance'); CreateAppText(conn,'sitemap_main','Appliance','','Appliance'); CreateAppText(conn,'sitemap_status','Overview','','Overview'); CreateAppText(conn,'sitemap_settings','Settings','','Settings'); CreateAppText(conn,'sitemap_analytics','Analytics','','Analytics'); CreateAppText(conn,'status_description','Status','Appliance Status','Overall status of appliance'); CreateAppText(conn,'settings_description','Settings','Appliance Settings','Global settings of appliance'); CreateAppText(conn,'analytics_description','Analytics','Appliance Analytics','Analytics of appliance'); CreateAppText(conn,'appliance_settings_system','System'); CreateAppText(conn,'appliance_settings_datalink','Network'); CreateAppText(conn,'appliance_settings_iscsi','iSCSI'); CreateAppText(conn,'appliance_settings_fibrechannel','Fibre Channel'); CreateAppText(conn,'system_content_header','Details about the selected Setting'); CreateAppText(conn,'system_name','Setting'); CreateAppText(conn,'system_desc','Description'); CreateAppText(conn,'system_reboot','Reboot'); CreateAppText(conn,'system_shutdown','Shutdown'); CreateAppText(conn,'datalink_content_header','Details about the selected Network Interface'); CreateAppText(conn,'datalink_name','Name'); CreateAppText(conn,'datalink_zoned','Zoned'); CreateAppText(conn,'datalink_desc','Description'); CreateAppText(conn,'create_aggr','Create Aggregation'); CreateAppText(conn,'aggr_add_diag_cap','New Interface Aggregation'); CreateAppText(conn,'datalink_add_vnic','Add new Virtual Interface'); CreateAppText(conn,'datalink_delete_vnic','Delete Virtual Interface'); CreateAppText(conn,'datalink_delete_aggr','Delete Aggregation'); CreateAppText(conn,'datalink_delete_stub','Delete Virtual Switch'); CreateAppText(conn,'fc_content_header','Details about the selected Fibre Channel port'); CreateAppText(conn,'fc_wwn','Port WWN'); CreateAppText(conn,'fc_targetmode','Target Mode'); CreateAppText(conn,'fc_state','State'); CreateAppText(conn,'fc_desc','Description'); CreateAppText(conn,'overview_caption_cpu','CPU Load (4 Intel E5-4620@2.20GHz)'); CreateAppText(conn,'overview_cpu_system_legend','System [%]'); CreateAppText(conn,'overview_cpu_user_legend','User [%]'); CreateAppText(conn,'overview_caption_net','Network'); CreateAppText(conn,'overview_net_receive_legend','Receive [%]'); CreateAppText(conn,'overview_net_transmit_legend','Transmit [%]'); CreateAppText(conn,'overview_caption_disk','Disk I/O (Device Aggregation)'); CreateAppText(conn,'overview_disk_read_legend','Read [kIOPS]'); CreateAppText(conn,'overview_disk_write_legend','Write [kIOPS]'); CreateAppText(conn,'overview_caption_ram','Memory Usage (256GB RAM, 256GB Swap)'); CreateAppText(conn,'overview_ram_ram_legend','RAM [%]'); CreateAppText(conn,'overview_ram_swap_legend','Swap [%]'); CreateAppText(conn,'overview_caption_cache','Cache (Adaptive Read Cache)'); CreateAppText(conn,'overview_cache_hits_legend','Hits [%]'); CreateAppText(conn,'overview_cache_misses_legend','Misses [%]'); end; end; class procedure TFRE_FIRMBOX_APPLIANCE_APP.InstallDBObjects4SysDomain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); begin inherited InstallDBObjects4SysDomain(conn, currentVersionId, domainUID); if currentVersionId='' then begin currentVersionId := '1.0'; CheckDbResult(conn.AddGroup('APPLIANCEFEEDER','Group for Appliance Data Feeder','VM Feeder',domainUID,true,true),'could not create Appliance feeder group'); CheckDbResult(conn.AddRolesToGroup('APPLIANCEFEEDER',domainUID,TFRE_DB_StringArray.Create( TFRE_FIRMBOX_APPLIANCE_APP.GetClassRoleNameFetch )),'could not add roles for group APPLIANCEFEEDER'); end; end; function TFRE_FIRMBOX_APPLIANCE_APP.WEB_RAW_DATA_FEED(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin result := DelegateInvoke(TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.ClassName,'RAW_UPDATE',input); end; function TFRE_FIRMBOX_APPLIANCE_APP.WEB_RAW_DATA_FEED30(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; begin result := DelegateInvoke(TFRE_FIRMBOX_APPLIANCE_STATUS_MOD.ClassName,'RAW_UPDATE30',input); end; procedure Register_DB_Extensions; begin GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_APPLIANCE_ANALYTICS_MOD); GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_APPLIANCE_SETTINGS_MOD); GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_APPLIANCE_STATUS_MOD); GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_APPLIANCE_APP); //GFRE_DBI.Initialize_Extension_Objects; end; end.
unit untVisualizaDados; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ExtCtrls, Grids, DBGrids, StdCtrls, ImgList, ComCtrls, ToolWin, DbClient, DAO, Formulario, SQL, ComObj, untDeclaracoes; type TVizualizaDadoDAO = class(TDao) FFormularioManutencao : String; FTabela : String; procedure showForm(lblVizualizaDados:String;cds:TClientDataSet; FormManutencao:String;campos:String;tabela:string;sql:string;identificador:string); end; TfrmVizualizaDados = class(TForm) grid: TDBGrid; pnlVizualizaDados: TPanel; dataSource: TDataSource; Label3: TLabel; lblregistros: TLabel; ToolBar1: TToolBar; tbAdicionar: TToolButton; tbEditar: TToolButton; tbExcluir: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; imgVizualizaDados: TImageList; lblVizualizaDados: TLabel; pnlPesquisa: TPanel; imgPesquisar: TImage; Label2: TLabel; tmVizualizaDados: TTimer; cdsVizualizaDados: TClientDataSet; tbExcel: TToolButton; ToolButton2: TToolButton; procedure gridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure tbAdicionarClick(Sender: TObject); procedure tbEditarClick(Sender: TObject); procedure tbExcluirClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure imgPesquisarClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tmVizualizaDadosTimer(Sender: TObject); procedure gridTitleClick(Column: TColumn); procedure gridDblClick(Sender: TObject); procedure tbExcelClick(Sender: TObject); private F: TFuncoes; procedure showFormManutencao; procedure geraExcel(cds:TClientDataSet); { Private declarations } public { Public declarations } end; var frmVizualizaDados: TfrmVizualizaDados; VD : TVizualizaDadoDAO; implementation uses untDM, untPrincipal, untManutencao, untPesquisaRapida, untManuFornecedores; {$R *.dfm} procedure TfrmVizualizaDados.gridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin TDbGrid(Sender).Canvas.font.Color:= clblack; //aqui é definida a cor da fonte sem a selecao if gdSelected in State then with (Sender as TDBGrid).Canvas do begin Brush.Color:=$000080FF; //aqui é definida a cor de seleção TDbGrid(Sender).Canvas.font.Color:= clwindow; //aqui é definida a cor da fonte com a selecao TDbGrid(Sender).Canvas.Font.Style := (Sender as TDBGrid).Canvas.Font.Style + [FSBOLD]; //aqui é definida a a fonte negrito com a selecao FillRect(Rect); end; TDbGrid(Sender).DefaultDrawDataCell(Rect, TDbGrid(Sender).columns[datacol].field, State); end; procedure TfrmVizualizaDados.tbAdicionarClick(Sender: TObject); begin VD.inserir; showFormManutencao; end; procedure TfrmVizualizaDados.tbEditarClick(Sender: TObject); begin VD.editar; showFormManutencao; end; procedure TfrmVizualizaDados.tbExcluirClick(Sender: TObject); begin case MessageDlg('ATENÇÃO: Deseja Excluir!' + #13 + 'o dado da tabela?', mtConfirmation ,[mbYes,mbNo], 0) of mryes: VD.excluir; mrno: VD.cancelar; end; end; procedure TfrmVizualizaDados.FormClose(Sender: TObject; var Action: TCloseAction); begin vd.Free; frmVizualizaDados.free; end; procedure TfrmVizualizaDados.showFormManutencao; var fc: TFormClass; f: TForm; begin fc:= TFormClass (FindClass (vd.FFormularioManutencao)); f:= fc.Create (Application); f.ShowModal; f.Free; end; procedure TfrmVizualizaDados.imgPesquisarClick(Sender: TObject); begin frmPesquisaRapida := TfrmPesquisaRapida.Create(Application); frmPesquisaRapida.pesq := vd.FTabela; frmPesquisaRapida.ShowModal; end; procedure TfrmVizualizaDados.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_F7: imgPesquisar.OnClick(Sender); end; end; procedure TfrmVizualizaDados.tmVizualizaDadosTimer(Sender: TObject); begin cdsVizualizaDados.Close; cdsVizualizaDados.Open; lblregistros.Caption := Format('%9.9d',[(cdsVizualizaDados.RecordCount)]); end; procedure TfrmVizualizaDados.gridTitleClick(Column: TColumn); var campo:string; begin campo:=column.fieldname; // CAMPO RECEBE O NOME DA COLUNA CLICADA, f.OrdenaClientDataSet(vd.BancoNavegacao,Column.Field); End; { TVizualizaDadoDAO } procedure TVizualizaDadoDAO.showForm(lblVizualizaDados: String; cds: TClientDataSet; FormManutencao: String; campos, tabela, sql: string; identificador:string); begin Vd := TVizualizaDadoDAO.Create(cds); vd.FTabela := tabela; frmVizualizaDados := TfrmVizualizaDados.Create(Application); FormDAO := TFormulario.Create(tabela); FormDAO.Identificador := identificador; formDAO.montaGrid(); frmVizualizaDados.Caption := lblVizualizaDados; frmVizualizaDados.lblVizualizaDados.Caption := lblVizualizaDados; frmVizualizaDados.dataSource.DataSet := cds; if (vd.FTabela = 'empre') or (vd.FTabela = 'banco') then begin vd.SQL.executaSql(cds,'select '+campos+' from '+tabela +' '+sql); vd.SQL.executaSql(frmVizualizaDados.cdsVizualizaDados,'select '+campos+' from '+tabela +' '+sql); end else begin VD.SQL.executaSQlPorEmp(cds,campos,vd.FTabela,sql); vd.SQL.executaSQlPorEmp(frmVizualizaDados.cdsVizualizaDados,campos,vd.FTabela,sql); end; vd.FFormularioManutencao := FormManutencao; frmVizualizaDados.show; end; procedure TfrmVizualizaDados.gridDblClick(Sender: TObject); begin VD.editar; showFormManutencao; end; procedure TfrmVizualizaDados.geraExcel(cds: TClientDataSet); var coluna, linha: integer;excel: variant;valor: string; begin try excel:=CreateOleObject('Excel.Application'); excel.Workbooks.add(1); except f.Mensagem(false,'Versão do Ms-Excel Incompatível!'); end; Cds.First; try for linha:=0 to Cds.RecordCount-1 do begin for coluna:=1 to CDS.FieldCount do // eliminei a coluna 0 da relação doExcel begin valor:= CDS.Fields[coluna-1].AsString; excel.cells [linha+2,coluna]:=valor; end; cds.Next; end; for coluna:=1 to Cds.FieldCount do // eliminei a coluna 0 da relação do Excel begin valor:= cds.Fields[coluna-1].DisplayLabel; excel.cells[1,coluna]:=valor; end; excel.columns.AutoFit; // esta linha é para fazer com que o Excel dimencione ascélulas adequadamente. excel.visible:=true; except f.Mensagem(false,'Aconteceu um erro desconhecido durante aconversão'+ 'da tabela para o Ms-Excel'); end; end; procedure TfrmVizualizaDados.tbExcelClick(Sender: TObject); begin geraExcel(vd.BancoNavegacao); end; end.
unit aclass5; { S A M P L E 5 The complete definition of the TUserInfo object. This object can be used by any unit that includes this unit in its uses clause.} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Registry; { Use the Registry unit to fetch User/Company Name } type ERegInfoNotFound = class(Exception); TUserInfo = class(TObject) Reg: TRegistry; private function GetUserName: string; function GetCompanyName: string; public property UserName: string read GetUserName; property CompanyName: string read GetCompanyName; end; const Win95RegInfo = 'SOFTWARE\Microsoft\Windows\CurrentVersion\'; implementation { Functional definition of TUserInfo code starts here } function TUserInfo.GetUserName: string; {var fileHandle: THandle; fileBuffer: Array [0..29] of Char;} begin { Fetch registered user name from Win95 Registry } Reg := TRegistry.Create; with Reg do begin RootKey := HKEY_LOCAL_MACHINE; if KeyExists(Win95RegInfo) then begin OpenKey(Win95RegInfo, False); Result := ReadString('RegisteredOwner'); end else raise ERegInfoNotFound.Create('Could not locate ' + 'registered user name'); Free; end; { with } end; function TUserInfo.GetCompanyName: string; {var fileHandle: THandle; fileBuffer: Array [0..29] of Char;} begin { Fetch registered company name from Win95 Registry } Reg := TRegistry.Create; with Reg do begin RootKey := HKEY_LOCAL_MACHINE; if KeyExists(Win95RegInfo) then begin OpenKey(Win95RegInfo, False); Result := ReadString('RegisteredOrganization'); end else raise ERegInfoNotFound.Create('Could not locate ' + 'registered company name'); Free; end; { with } end; end.
program ian(input,output); const { These definitions are useful for manipulating strings } msl = 80; { max length of a string } mslPlusOne = 81; { max length of string buffer } mns = 10; { max number symbols - getsyms } { For converting back and forth between radians and degrees } radPerDeg = 0.0174532925; degPerRad = 57.2957795131; type fileOfChar = file of char; { These types are useful for manipulating strings } ptrToAlfa = ^ alfa; alfa = packed array[1..mslPlusOne] of char; strind = 0..msl; string = record len: strind; str: alfa end; arrayOfStrings = array[1..mns] of string; ptrToString = ^ string; var terminal : fileOfChar; { for prompts, error messages, etc. } { #include "/u/gr/include/grutil/grutil.h" } { Copyright (c) 1980,1981 Ian D. Allen / University of Waterloo } { REVMKR: make figures of revolution } procedure main; const PI = 3.14159265; MAXSLICES = 1024; { Max points allowed in profile file. } MAXFACES = 1024; { Max number of faces in revolution. } MAXPOLYS = 100; { Max polygon nodes which can be generated. } MAXCOMMENTS = 20; { Max comments which can be passed to output file. } type nonneg = 0..maxint; { Non-negative integer. } positive = 1..maxint; { Positive integer. } polytype = ( polygon, rotation, user ); commentindex= 1..MAXCOMMENTS; userindex = 1..MAXPOLYS; commentptr = ^ alfa; var commentarray: array [1..MAXCOMMENTS] of commentptr; { Store comments. } numcomments : 0..MAXCOMMENTS; slicearray : array [1..MAXSLICES] of record z,x : real end; { Store profile points. } numslices : 0..MAXSLICES; polyarray : array [1..MAXPOLYS] of { Store polygon/rotation/user nodes. } record down : integer; next : integer; case ptype : polytype of {begin} rotation: ( degrees : real ); polygon : ( nverts : nonneg ); user : ( usertype:char; ptr: ^alfa ); end {record}; numpolys : 0..MAXPOLYS; numtransnodes : 0..MAXPOLYS; { Number of User Transformaion Nodes. } numfaces : integer; { Number of faces in revolution. } dtheta : real; { Delta Theta (radians) for rotation. } dthetadegree: real; { Delta Theta (degrees) for rotation. } cosdtheta, sindtheta : real; dotop, dobottom : boolean; { Do Top or Bottom polygon flags. } topwedgerot : positive; { Start of wedge rotation polygon nodes. } startwedge : positive; { Pointer to start of wedge rotation polygon nodes. } starttop : positive; { Location of Top polygon. } startbottom : positive; { Locaton of Bottom polygon. } startfigure : positive; { Entry/start node for complete figure of rot. } startuser : positive; { Entry/start node in User Transform Section. } pnum : nonneg; { Polygon/Rotation node number. } pcheck : nonneg; { To check node number when reading User Transform Nodes. } p1,p2,p3,p4 : positive; { Vertex numbers used building wedge polygons. } vertcounter : nonneg; { Vertex counter used building wedge polygons. } maxtwo : positive; { Max power of two <= numfaces. } maxpower : nonneg; { Exponent of maxtwo, i.e. log2(maxtwo). } donesofar : positive; { Number of rotation faces done so far. } remainder : nonneg; { Number of rotation faces left to do. } rempower : nonneg; { Max power of two <= remainder. } remtwo : positive; { Exponent of rempower, i.e. log2(rempower). } horiz : nonneg; { Number of nodes in horizontal remainder chain} downlink : positive; { Index into vertical power-of-two tree. } nextlink : nonneg; { Link to next polygon used building wedge polys} down : integer; { Link to down polygon in User Transform Section. } next : integer; { Link to next polygon in User Transform Section. } offset : positive; { Used in renumbering User Transform nodes. } totalverts : positive; { Total number of vertices generated. } totalpolys : positive; { Total number of polygon/rotation nodes generated. } rightleft : char; { Right or Left -handed normal points inward. } saverightleft : char; { Saved (input) rightleft flag. } x,y,z : real; vnum : nonneg; { Vertex Number. } ptype : char; { Type of User Transform node. } syms : arrayOfStrings; { Used by GETSYMS. } nsyms : integer; { Used by GETSYMS. } i,j : nonneg; profile : fileOfChar; { Input profile data file. } profilename : alfa; proeof : boolean; { Set true on end-of-file for profile file. } proerrflag : boolean; { Set and checked for profile line errors. } prostring : string; { Profile file input line. } profilineno : nonneg; { Current profile line number. } outfile : text; { Ouput file for ReadScene. } outfilename : alfa; procedure storecomment( var c : alfa ); begin if ( numcomments < MAXCOMMENTS ) then begin numcomments := numcomments + 1; new( commentarray[numcomments] ); { Create space for comment. } c[1] := 'C'; { Make sure comment starts with C for ReadScene. } commentarray[numcomments]^ := c; { Save comment. } end {if} else begin commentarray[MAXCOMMENTS]^ := 'C ...comments truncated...'; end {else}; end {procedure storecomment}; procedure freecomment( i : commentindex ); begin dispose( commentarray[i] ); { Free storage. } end {procedure freecomment}; procedure storepoly( pdown, pnext : nonneg ); begin if ( numpolys < MAXPOLYS ) then begin numpolys := numpolys + 1; polyarray[numpolys].ptype := polygon; polyarray[numpolys].down := pdown; polyarray[numpolys].next := pnext; { Don't need to assign .nverts -- it is always zero. } end {if} else begin writeln( output, 'REVMKR: Too many polygons in storepoly list, maximum is ', MAXPOLYS:1 ); halt; end {else}; end {procedure storepoly}; procedure storerot( pdown, pnext: nonneg; rot : real ); begin if ( numpolys < MAXPOLYS ) then begin numpolys := numpolys + 1; polyarray[numpolys].ptype := rotation; polyarray[numpolys].down := pdown; polyarray[numpolys].next := pnext; polyarray[numpolys].degrees := rot; end {if} else begin writeln( output, 'REVMKR: Too many polygons in storerot list, maximum is ', MAXPOLYS:1 ); halt; end {else}; end {procedure storerot}; procedure storeuser( pdown, pnext : integer; usertype : char; var pstring : alfa ); begin if ( numpolys < MAXPOLYS ) then begin numpolys := numpolys + 1; polyarray[numpolys].ptype := user; polyarray[numpolys].down := pdown; polyarray[numpolys].next := pnext; polyarray[numpolys].usertype := usertype; new( polyarray[numpolys].ptr ); { To hold string. } polyarray[numpolys].ptr^ := pstring; end {if} else begin writeln( output, 'REVMKR: Too many polygons in storeuser list, maximum is ', MAXPOLYS:1 ); halt; end {else}; end {procedure storeuser}; procedure freeuser( i : userindex ); begin dispose( polyarray[i].ptr ); { Return to free storage. } end {procedure freeuser}; function Power2( i : nonneg; var outexponent : nonneg ) : nonneg; var outpower : nonneg; begin outpower := 1; outexponent := 0; while ( outpower <= i ) do begin outpower := outpower * 2; outexponent := outexponent + 1; end {while}; Power2 := outpower div 2; outexponent := outexponent - 1; end {function Power2 }; begin {procedure main} { *** Run-Time Parameter Input Section. *** } writeln( output, 'Enter input and output filenames:' ); Getline( prostring ); getsyms( prostring, syms, nsyms ); if ( nsyms <= 1 ) then begin syms[2].str := 'revout '; end {if}; profilename := syms[1].str; outfilename := syms[2].str; writeln( output, 'Enter number of faces, Top(t/f), Bottom(t/f):' ); Getline( prostring ); getsyms( prostring, syms, nsyms ); numfaces := convi( syms[1] ); dotop := ( syms[2].str[1] in ['t','T'] ); dobottom := ( syms[3].str[1] in ['t','T'] ); if ( numfaces < 2 ) or ( numfaces > MAXFACES ) then begin writeln( output, 'REVMKR: Number of faces must be 2..', MAXFACES:1 ); halt; end {if}; writeln( output, 'Enter right or left handed normal points in (r/l):' ); readln( input, rightleft ); { This may change when data is read. } if (rightleft in ['l','L']) then begin rightleft := 'l'; end {if} else begin if (rightleft in ['r','R']) then begin rightleft := 'r'; end {if} else begin writeln( output, 'REVMKR: Error -- polygon normal must be R or L. "', rightleft, '" found.' ); halt; end {else}; end {else}; saverightleft := rightleft; { Save what user typed in. } { *** Initialization Section. *** } numcomments := 0; { No comment lines yet. } numpolys := 0; { No polygons in array yet. } proerrflag := false; { No error so far. } profilineno := 0; { No lines read yet. } { *** Rotation Parameters. *** } dtheta := (2 * PI) / numfaces; { Delta Theta. } dthetadegree := 360.0 / numfaces; { In Degrees for output. } sindtheta := sin( dtheta ); cosdtheta := cos( dtheta ); { *** Save Input Comments. *** } reset( profile, profilename ); { Open profile data input file. } proeof := ( eof(profile) ); if ( proeof ) then begin writeln( output, 'REVMKR: Profile file is empty: ', profilename ); halt; end {if}; fGetline( profile, prostring ); profilineno := profilineno + 1; while ( prostring.str[1] in ['c','C','*',';'] ) and not ( proeof ) do begin storecomment( prostring.str ); { Save comment lines. } if ( eof(profile) ) then proeof := true else begin fGetline( profile, prostring ); profilineno := profilineno + 1; end {else}; end {while}; { *** Input Profile Slices into Slicearray. *** } if ( proeof ) then begin writeln( output, 'REVMKR: No profile data on file ', profilename ); halt; end {if}; numslices := 0; { No slices yet. } while not ( (prostring.str[1] in ['c','C','*',';']) or ( proeof ) ) do begin getsyms( prostring, syms, nsyms ); if (syms[2].len = 0) then begin writeln( output, 'REVMKR: Missing co-ordinate on line ', profilineno:1, ' in profile file ', profilename ); proerrflag := true; end {if}; z := convr( syms[1] ); x := convr( syms[2] ); if ( numslices < MAXSLICES ) then begin numslices := numslices + 1; slicearray[numslices].x := x; slicearray[numslices].z := z; end {if} else begin writeln( output, 'REVMKR: Too many data points in profile file,', ' maximum is ', MAXSLICES:1 ); halt; end {else}; if ( eof(profile) ) then proeof := true else begin fGetline( profile, prostring ); profilineno := profilineno + 1; end {else}; end {while}; if ( proerrflag ) then begin halt; end {if}; writeln( output, 'Number of data points read from profile file: ', numslices:1 ); if ( numslices < 2 ) then begin writeln( output, 'REVMKR: Need at least two points in profile file.' ); halt; end {if}; { Make sure we traverse polygons clockwise, viewed externally. } if ( slicearray[1].z > slicearray[numslices].z ) then begin if ( rightleft = 'l' ) then begin rightleft := 'r'; { We are going the other way! } end {if} else begin rightleft := 'l'; { We are going the other way! } end {else}; end {if}; { *** Input User-Transformation nodes *** } if not ( proeof ) then begin while ( prostring.str[1] in ['c','C','*',';'] ) and not ( proeof ) do begin storecomment( prostring.str ); { Save comment lines. } if ( eof(profile) ) then proeof := true else begin fGetline( profile, prostring ); profilineno := profilineno + 1; end {else}; end {while}; pcheck := 0; { Use this to verify pnum correct sequence. } while not ( proeof ) do begin { Read user transformation and save it for later. } getsyms( prostring, syms, nsyms ); if ( syms[1].len > 0 ) then begin pcheck := pcheck + 1; { Increment check counter too. } pnum := convi( syms[1] ); { Node number. } ptype := syms[2].str[1]; { Polygon node type. } down := convi( syms[3] ); { Down pointer. } next := convi( syms[4] ); { Next pointer. } if (pnum<>pcheck) or (syms[5].len=0) then begin writeln( prostring.str ); writeln( output, 'REVMKR: Unrecognizable user-transform nodes ', 'after second set of Comments -- ignored.' ); while ( numpolys > 0 ) do begin freeuser( numpolys ); { Free storage. } numpolys := numpolys - 1; end {while}; proeof := true; { Premature end of file. } end {if} else begin { Shift string left 4 args to get past node numbers. } i := 1; for j:= 1 to 4 do begin while ( prostring.str[i] = ' ' ) do i := i + 1; while ( prostring.str[i] <> ' ' ) do i := i + 1; end {for}; { Move remainder of string to beginning of string. } j := 1; for i := i to msl do begin prostring.str[j] := prostring.str[i]; j := j + 1; end {for}; { Pad with blanks. } for j := j to msl do begin prostring.str[j] := ' '; end {for}; storeuser( down, next, ptype, prostring.str ); end {else}; end {if}; if ( proeof or eof(profile) ) then proeof := true else begin fGetline( profile, prostring ); profilineno := profilineno + 1; end {else}; end {while}; end {if}; rewrite( outfile, outfilename); { Get ready to write data. } numtransnodes := numpolys; { Number of user-transform nodes. } { *** Verify Existence of Top and Bottom Polygons. *** } if ( slicearray[1].x = 0.0 ) then dotop := false; if ( slicearray[numslices].x = 0.0 ) then dobottom := false; { *** Calculate total number of vertices needed. *** } totalverts := numslices * 2; { Start with wedge vertices. } if ( dotop ) then totalverts := totalverts + numfaces; { Add top. } if ( dobottom ) then totalverts := totalverts + numfaces; { Add bottom. } { *** Calculate polygon rotation tree for wedge of vertices. *** } { This is a binary tree using powers of two to construct the needed rotations with as few polygon transformation nodes as possible. It consists of a "vertical" string of powers of two, and a "horizontal" string of pointers into the vertical string. The horizontal string deals with the rotation remaining after the preceding power of two has been done. } { The numslices-1 wedge polygons precede the polygons of the wedge tree. } topwedgerot := numslices; { There are numslices-1 polys in the wedge. } pnum := topwedgerot; { Start counting from here. } maxtwo := Power2( numfaces, maxpower ); { Find biggest power of 2 <= } donesofar := maxtwo; { Vertical rotation tree handles the power of 2. } remainder := numfaces - donesofar; { Number of faces left to do. } horiz := 0; { Horizontal rotation string starts zero length. } while (remainder > 0) do begin remainder := remainder - Power2( remainder, rempower ); horiz := horiz + 1; { Add a node to horizontal string. } end {while}; remainder := numfaces - donesofar; { Number of faces left to do. } while (remainder > 0) do begin remtwo := Power2( remainder, rempower ); downlink := topwedgerot + horiz + (maxpower-rempower); {Index vertical} pnum := pnum + 1; storerot( downlink, pnum, donesofar*dthetadegree ); {A horizontal node} donesofar := donesofar + remtwo; { Done this many more now. } remainder := remainder - remtwo; { This much less remainder now. } end {while}; i := maxtwo div 2; { Construct the Vertical power-of-two tree. } while (i > 0) do begin pnum := pnum + 1; storerot( pnum, pnum, i * dthetadegree ); { A vertical node. } i := i div 2; { Next power of two. } end {while}; storepoly( 000, 001 ); { This points to start of list of wedge polys. } pnum := pnum + 1; startwedge := pnum; { This points to the wedge rotations. } pnum := pnum + 1; { This will be the top polygon. } starttop := pnum; pnum := pnum + 1; { This will be the bottom polygon. } startbottom := pnum; pnum := pnum + 3; { Three pointer polygons go here. } startfigure := pnum; { This will be the final (entry) polygon. } { Any user transformation is expected to keep entry point last. } totalpolys := startfigure + numtransnodes; startuser := totalpolys; { Last poly node is start/entry point. } { *** Output Section. *** } { *** Echo Terminal Input to Output File. *** } writeln( outfile, 'C REVMKR input file was ', profilename ); writeln( outfile, 'C Number of faces was ', numfaces:1 ); write( outfile, 'C Top polygon was ' ); if ( dotop ) then writeln( outfile, 'requested.' ) else writeln( outfile, 'omitted.' ); write( outfile, 'C Bottom polygon was ' ); if ( dobottom ) then writeln( outfile, 'requested.' ) else writeln( outfile, 'omitted.' ); writeln( outfile, 'C Polygon Right/Left flag was "', saverightleft, '"' ); writeln( outfile, 'C Number of user transformation nodes was ', numtransnodes:1 ); for i := 1 to numcomments do begin writeln( outfile, commentarray[i]^ ); freecomment( i ); { Free storage to be tidy. } end {for}; writeln( outfile, '\n' ); { Two line feeds for Read Scene. } { *** Important Numbers for ReadScene. *** } writeln( outfile, totalverts:6, totalpolys:6, startuser:6 ); { *** Give the user some Statistics. *** } writeln( output, 'Total vertices=', totalverts:1, ' Total polygons=', totalpolys:1, ' Start polygon=', startuser:1 ); if ( numtransnodes > 0 ) then begin writeln( output, 'Number of user transformaton nodes: ', numtransnodes:1 ); end {if}; { *** Vertex Output Section *** } { The 2*numslices wedge vertices. } vnum := 1; for i := 1 to numslices do begin x := slicearray[i].x; y := 0.0; writeln( outfile, vnum:6, x:16:8, y:16:8, slicearray[i].z:16:8 ); vnum := vnum + 1; y := x * sindtheta; x := x * cosdtheta; writeln( outfile, vnum:6, x:16:8, y:16:8, slicearray[i].z:16:8 ); vnum := vnum + 1; end {for}; { The top and bottom polygon vertices, if needed. } if ( dotop ) then begin x := slicearray[1].x; z := slicearray[1].z; for i := 1 to numfaces do begin writeln( outfile, vnum:6, x * cos( i * dtheta ):16:8, x * sin( i * dtheta ):16:8, z:16:8 ); vnum := vnum + 1; end {for}; end {if}; if ( dobottom ) then begin x := slicearray[numslices].x; z := slicearray[numslices].z; for i := 1 to numfaces do begin writeln( outfile, vnum:6, x * cos( i * dtheta ):16:8, x * sin( i * dtheta ):16:8, z:16:8 ); vnum := vnum + 1; end {for}; end {if}; { Internal Consistency Check. } if ( vnum-1 <> totalverts ) then begin writeln( output, 'REVMKR: Warning: expected ', totalverts:1, ' vertices, but ', vnum-1:1, ' were output.' ); end {if}; { *** Polygon Output Section *** } { Write out numslices-1 wedge polygons. } vertcounter := 0; for pnum := 1 to numslices-1 do begin p1 := vertcounter + 1; p2 := vertcounter + 2; p3 := vertcounter + 4; p4 := vertcounter + 3; if ( pnum = numslices-1 ) then nextlink := 0 else nextlink := pnum + 1; write( outfile, pnum:6, ' p 000', nextlink:6, ' 4' ); if rightleft = 'l' then writeln( outfile, p1:6, p2:6, p3:6, p4:6 ) else writeln( outfile, p4:6, p3:6, p2:6, p1:6 ); vertcounter := vertcounter + 2; end {for}; { Write out the wedge rotation tree. } numpolys := numtransnodes; { Skip over user tranform nodes. } for pnum := numslices to startwedge-1 do begin numpolys := numpolys + 1; write( outfile, pnum:6 ); if ( polyarray[numpolys].ptype = polygon ) then write( outfile, ' p' ) else write( outfile, ' z' ); write( outfile, polyarray[numpolys].down:6, polyarray[numpolys].next:6 ); if ( polyarray[numpolys].ptype = polygon ) then begin writeln( outfile, ' 000' ); end {if} else writeln( outfile, polyarray[numpolys].degrees:16:8 ); end {for}; pnum := startwedge; writeln( outfile, pnum:6, ' p 000', topwedgerot:6, ' 0 -- points to start of wedge rotation polygons' ); { write out polygon forming the top } pnum := starttop; if ( dotop ) then begin writeln( outfile, pnum:6, ' p 000 000', numfaces:6 ); j := 2*numslices; { Wedge vertices precede top. } if rightleft = 'r' then begin for i := 1 to numfaces do begin if ( (i mod 10) = 0 ) then begin writeln( outfile ); {Split long lines.} end {if}; write( outfile, j+i:6 ); end {for}; end {if} else begin for i := numfaces downto 1 do begin if ( (i mod 10) = 0 ) then begin writeln( outfile ); {Split long lines. } end {if}; write( outfile, j+i:6 ); end {for}; end {else}; writeln( outfile ); end {if} else begin writeln( outfile, pnum:6, ' p 000 000 0 -- No Top Polygon' ); end {else}; { write out polygon forming the bottom } pnum := startbottom; if ( dobottom ) then begin writeln( outfile, pnum:6, ' p 000 000', numfaces:6 ); j := 2*numslices; { Wedge vertices precede bottom. } if (dotop) then j := j + numfaces; {Top vertices also precede. } if rightleft = 'l' then begin for i := 1 to numfaces do begin if ( (i mod 10) = 0 ) then begin writeln( outfile ); {Split long lines. } end {if}; write( outfile, j+i:6 ); end {for}; end {if} else begin for i := numfaces downto 1 do begin if ( (i mod 10) = 0 ) then begin writeln( outfile ); {Split long lines. } end {if}; write( outfile, j+i:6 ); end {for}; end {else}; writeln( outfile ); end {if} else begin writeln( outfile, pnum:6, ' p 000 000 0 -- No Bottom Polygon' ); end {else}; { *** Linkage Polygon Output Section. *** } { Chain the Top, Wedge, and Bottom together, with entry at last node. } pnum := startbottom + 1; writeln( outfile, pnum:6, ' p', startbottom:6, ' 000 0 -- points to start of bottom polygon' ); pnum := pnum + 1; writeln( outfile, pnum:6, ' p', topwedgerot:6, pnum-1:6, ' 0 -- points to start of wedge rotation polygons' ); pnum := pnum + 1; writeln( outfile, pnum:6, ' p', starttop:6, pnum-1:6, ' 0 -- points to start of top polygon', ' <== START NODE FOR FIGURE ==' ); pnum := pnum + 1; { *** Add the user-specified transformation to end of the file. *** } if ( numtransnodes > 0 ) then begin { Renumber user transformation and output it at end of file. } offset := pnum - 1; { Last generated polygon. } for i := 1 to numtransnodes do begin down := polyarray[i].down; next := polyarray[i].next; if ( down > 0 ) then down := down + offset else if ( down < 0 ) then down := down + offset + 1; if ( next > 0 ) then next := next + offset else if ( next < 0 ) then next := next + offset + 1; writeln( outfile, pnum:6, polyarray[i].usertype:2, down:6, next:6, polyarray[i].ptr^ ); freeuser( i ); { Free storage to be tidy. } pnum := pnum + 1; end {for}; end {if}; { Internal Consistency Check. } if ( pnum-1 <> totalpolys ) then begin writeln( output, 'REVMKR: Warning: expected ', totalpolys:1, ' polygons, but ', pnum-1:1, ' were output.' ); end {if}; end {procedure main}; begin main; end.
unit ugerador_combinatorio; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls, Grids; // Este registro guarda a informação do jogo escolhido, a quantidade de números jogados // e a quantidade de volantes jogados. type TJogoInfo = record JogoTipo: string; bolaInicial: integer; bolaFinal: integer; // Cada jogo, pode-se apostar tantas bolas bolaAposta: integer; // Quantidade de volantes apostados. quantidadeBilhetes: integer; // Indica, que todos os números devem ser sorteados, antes de repetir um novo número. naoRepetirBolas: boolean; // Alternar entre par e impar. alternarParImpar: boolean; // Cada grupo de bola terá x bolas que não estarão em outro grupo. bolas_combinadas: integer; end; const JogoTipo: array[0..7] of string = ('DUPLASENA', 'LOTOFACIL', 'LOTOMANIA', 'MEGASENA', 'QUINA', 'INTRALOT_MINAS_5', 'INTRALOT_LOTOMINAS', 'INTRALOT_KENO_MINAS'); type { TJogoThread } TJogoThread = class(TThread) public constructor Create(jogoInfo: TJogoInfo; jogoGrade: TStringGrid; CreateSuspended: boolean); procedure Execute; override; private jogoInfo: TJogoInfo; jogoGrade: TStringGrid; procedure GerarLotomania; procedure GerarLotomaniaGrupo10Numeros; procedure GerarLotomaniaGrupo2Numeros; procedure GerarLotomaniaGrupo5Numeros; procedure Preencher_Grade; end; type { TfrmGerador_Combinatorio } TfrmGerador_Combinatorio = class(TForm) btnImportar: TButton; btnGerar: TButton; btnCopiar: TButton; btnExportar: TButton; btnLimpar_Resultados: TButton; chkAlternarParImpar: TCheckBox; chkAlternarParImpar1: TCheckBox; cmbJogo_Tipo: TComboBox; cmbJogo_com: TComboBox; cmbJogo_Quantidade: TComboBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; panel_Superior: TPanel; Panel2: TPanel; panel_Direito: TPanel; StatusBar1: TStatusBar; gradeJogos: TStringGrid; procedure btnCopiarClick(Sender: TObject); procedure btnExportarClick(Sender: TObject); procedure btnGerarClick(Sender: TObject); procedure btnImportarClick(Sender: TObject); procedure btnLimpar_ResultadosClick(Sender: TObject); procedure cmbJogo_comChange(Sender: TObject); procedure cmbJogo_TipoChange(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); private strJogo_Tipo: string; strErro: string; iJogo_com, iJogo_Quantidade: integer; iMenor_Bola, iMaior_Bola: integer; // Indica a quantidade de bolas, que compõe o jogo. iQuantidade_de_Bolas: integer; // Estrutura que guarda o jogo selecionado. jogoInfo: TJogoInfo; // JogoThread. jogoThread: TJogoThread; { private declarations } procedure Preencher_Jogos(Sender: TObject); procedure Preencher_Jogos_Quantidade; //function Retornar_Aposta_com_x_numeros(strJogo_com: string; // out strErro: string): integer; //function Retornar_Quantidade_de_Jogos(strJogo_Quantidade: string; // out strErro: string): integer; function Validar_Jogo: boolean; overload; //function Validar_Campos(strJogo, strJogo_Com, strJogo_Quantidade: string; // var strErro: string): boolean; overload; procedure Exportar_Arquivo_csv; procedure Importar_Arquivo_csv; //procedure Preencher_Grade; //function Validar_Jogo(strJogo: string; out strErro: string): boolean; //procedure Preencher_Grade_Lotofacil; public { public declarations } end; var frmGerador_Aleatorio: TfrmGerador_Combinatorio; implementation uses dmLtk; {$R *.lfm} { TJogoThread } constructor TJogoThread.Create(jogoInfo: TJogoInfo; jogoGrade: TStringGrid; CreateSuspended: boolean); begin self.FreeOnTerminate:=true; self.jogoInfo := jogoInfo; self.jogoGrade := jogoGrade; end; procedure TJogoThread.Execute; begin self.Preencher_Grade; end; { TfrmGerador_Combinatorio } procedure TfrmGerador_Combinatorio.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction := TCloseAction.caFree; FreeAndNil(JogoThread); end; // A informação disponível na caixa de combinação é alterada conforme o tipo do // jogo. procedure TfrmGerador_Combinatorio.cmbJogo_comChange(Sender: TObject); var strJogo: TCaption; iA: integer; begin // Altera o valor conforme o jogo. strJogo := cmbJogo_Tipo.Text; // Apagar sempre a caixa de combinação de cmbJogo_Quantidade cmbJogo_Quantidade.Items.Clear; if strJogo = 'LOTOMANIA' then begin for iA in [2, 5, 10, 25] do begin cmbJogo_Quantidade.Items.Add(IntToStr(iA)); end; end else if strJogo = 'LOTOFACIL' then begin if cmbJogo_com.Text = '15' then begin for iA in [3, 5] do begin cmbJogo_Quantidade.Items.Add(IntToStr(iA)); end; end else if cmbJogo_com.Text = '16' then begin for iA in [2, 4, 8] do begin cmbJogo_Quantidade.Items.Add(IntToStr(iA)); end; end; end; end; procedure TfrmGerador_Combinatorio.btnGerarClick(Sender: TObject); begin // Vamos preencher os dados e passa para validar. JogoInfo.JogoTipo:= cmbJogo_Tipo.Text; JogoInfo.bolaAposta:= StrToInt(cmbJogo_Com.Text); JogoInfo.quantidadeBilhetes:= StrToInt(cmbJogo_Quantidade.Text); JogoInfo.alternarParImpar:= chkAlternarParImpar.Checked; JogoInfo.bolas_combinadas:= StrToInt(cmbJogo_Quantidade.Text); if Validar_Jogo = false then begin MessageDlg(strErro, TMsgDlgType.mtError, [mbOK], 0); Exit; end; JogoThread := TJogoThread.Create(jogoInfo, gradeJogos, true); JogoThread.Execute; end; procedure TfrmGerador_Combinatorio.btnImportarClick(Sender: TObject); begin self.Importar_Arquivo_csv; end; procedure TfrmGerador_Combinatorio.btnExportarClick(Sender: TObject); begin self.Exportar_Arquivo_csv; end; procedure TfrmGerador_Combinatorio.btnCopiarClick(Sender: TObject); begin // Vamos copiar para o ClipBoard; self.gradeJogos.CopyToClipboard(False); end; procedure TfrmGerador_Combinatorio.btnLimpar_ResultadosClick(Sender: TObject); var iResposta: integer; begin iResposta := MessageDlg('Deseja apagar os resultados', TMsgDlgType.mtInformation, [mbYes, mbNo], 0); if iResposta = mrYes then begin gradeJogos.Clean; gradeJogos.RowCount := 0; end; end; // Toda vez que o usuário clicar na caixa de combinação Jogo_Tipo, devemos // atualizar o controle cmbJogo_com para refletir a quantidade de números // a jogar para o jogo respectivo. procedure TfrmGerador_Combinatorio.cmbJogo_TipoChange(Sender: TObject); var iA: integer; strJogo: string; begin // Sempre apagar o que já havia na caixa de combinação. cmbJogo_com.Items.Clear; cmbJogo_Quantidade.Items.Clear; strJogo := cmbJogo_Tipo.Text; // Vamos garantir que sempre o valor estará em maiúsculas. strJogo := UpCase(strJogo); if strJogo = 'QUINA' then begin for iA := 5 to 7 do begin cmbJogo_com.Items.Add(IntToStr(iA)); end; end else if (strJogo = 'MEGASENA') or (strJogo = 'DUPLASENA') then begin for iA := 6 to 15 do begin cmbJogo_com.Items.Add(IntToStr(iA)); end; end else if strJogo = 'LOTOFACIL' then begin for iA := 15 to 18 do begin cmbJogo_com.Items.Add(IntToStr(iA)); end; end else if strJogo = 'LOTOMANIA' then begin cmbJogo_com.Items.Add('50'); for iA in [2, 5, 10, 25] do begin cmbJogo_Quantidade.Items.Add(IntToStr(iA)); end end else if strJogo = 'INTRALOT_MINAS_5' then begin cmbJogo_com.Items.Add('5'); end else if strJogo = 'INTRALOT_LOTOMINAS' then begin cmbJogo_com.Items.Add('6'); end; IF strJogo = 'INTRALOT_KENO_MINAS' then begin for iA := 1 to 10 do cmbJogo_Com.Items.Add(IntToStr(iA)); end; // Selecionar sempre o primeiro ítem. cmbJogo_com.ItemIndex := 0; cmbJogo_Quantidade.ItemIndex := 0; end; procedure TfrmGerador_Combinatorio.FormCreate(Sender: TObject); begin self.Preencher_Jogos(Sender); self.Preencher_Jogos_Quantidade; end; procedure TfrmGerador_Combinatorio.Preencher_Jogos(Sender: TObject); var iA: integer; begin // Preencher combobox com o nome dos jogos. for iA := 0 to High(JogoTipo) do cmbJogo_Tipo.Items.Add(JogoTipo[iA]); // Definir o primeiro ítem, na inicialização. cmbJogo_Tipo.ItemIndex := 0; // Vamos também atualizar o controle 'cmbJogo_com' para refletir o jogo selecionado cmbJogo_Tipo.OnChange(Sender); end; // Preencher o controle 'cmbJogo_Quantidade' com a lista de quantidade de jogos. procedure TfrmGerador_Combinatorio.Preencher_Jogos_Quantidade; var iA: integer; begin for iA := 1 to 10 do begin cmbJogo_Quantidade.Items.Add(IntToStr(iA)); end; iA := 20; repeat cmbJogo_Quantidade.Items.Add(IntToStr(iA)); if iA < 100 then begin iA += 10; end else begin iA += 100; end; until iA > 1000; cmbJogo_Quantidade.ItemIndex := 0; end; // Validar o jogo e definir a menor e maior bola function TfrmGerador_Combinatorio.Validar_Jogo: boolean; var strJogo: String; begin // Validar nome do jogo. strJogo := UpperCase(JogoInfo.JogoTipo); if (strJogo <> 'QUINA') and (strJogo <> 'MEGASENA') and (strJogo <> 'LOTOFACIL') and (strJogo <> 'LOTOMANIA') and (strJogo <> 'DUPLASENA') and (strJogo <> 'INTRALOT_MINAS_5') and (strJogo <> 'INTRALOT_LOTOMINAS') and (strJogo <> 'INTRALOT_KENO_MINAS') then begin strErro := 'Jogo inválido: ' + strJogo; Exit(False); end; // Definir limite inferior e superior. // Nos jogos da loteria, somente o jogo lotomania, a menor bola é 0. if strJogo = 'LOTOMANIA' then JogoInfo.bolaInicial:=0 else JogoInfo.bolaInicial := 1; // Definir limite superior. if strJogo = 'QUINA' then JogoInfo.BolaFinal := 80 else if strJogo = 'MEGASENA' then JogoInfo.BolaFinal := 60 else if strJogo = 'LOTOFACIL' then JogoInfo.BolaFinal := 25 else if strJogo = 'LOTOMANIA' then JogoInfo.BolaFinal := 99 else if strJogo = 'DUPLASENA' then JogoInfo.BolaFinal := 50 else if strJogo = 'INTRALOT_MINAS_5' then JogoInfo.BolaFinal := 34 else if strJogo = 'INTRALOT_LOTOMINAS' then JogoInfo.BolaFinal := 38 else if strJogo = 'INTRALOT_KENO_MINAS' then JogoInfo.BolaFinal := 80; // Validar o campo de quantidade de números apostados escolhido pelo usuário. if ((strJogo = 'MEGASENA') or (strJogo = 'DUPLASENA')) AND not(JogoInfo.bolaAposta in [6..15]) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; if (strJogo = 'QUINA') and not(JogoInfo.bolaAposta in [5..7]) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; if (strJogo = 'LOTOFACIL') and not(JogoInfo.bolaAposta in [15..18]) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; if (strJogo = 'LOTOMANIA') and (JogoInfo.bolaAposta <> 50) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; if (strJogo = 'INTRALOT_MINAS_5') and (JogoInfo.bolaAposta <> 5) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; if (strJogo = 'INTRALOT_LOTO_MINAS') and (JogoInfo.bolaAposta <> 6) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; if (strJogo = 'INTRALOT_KENO_MINAS') and (JogoInfo.bolaAposta <> 5) then begin strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo; Exit(False); end; Exit(True); end; procedure TfrmGerador_Combinatorio.Exportar_Arquivo_csv; var dlgExportar_Csv: TSaveDialog; strArquivo_Sugestao: string; begin // Se não há nenhum jogo gerado, emiti um erro e sair. if gradeJogos.RowCount = 0 then begin MessageDlg('Erro, não há nenhum jogo gerado.', TMsgDlgType.mtError, [mbOK], 0); Exit; end; // Vamos pegar o nome do arquivo, através da caixa de diálogo. dlgExportar_Csv := TSaveDialog.Create(TComponent(self)); dlgExportar_Csv.Filter := '*.csv'; dlgExportar_Csv.InitialDir := '/home/fabiuz/meus_documentos/exportados'; // Vamos sugerir um nome baseado no jogo atual strArquivo_Sugestao := JogoInfo.JogoTipo + '_com_' + IntToStr(JogoInfo.bolaAposta) + '_números_' + FormatDateTime('dd_mm_yyyy', Now) + '-' + FormatDateTime('hh_mm_ss', Now) + '.csv'; dlgExportar_Csv.FileName := strArquivo_Sugestao; if dlgExportar_Csv.Execute = False then begin Exit; end; // O Arquivo não pode existir if FileExists(dlgExportar_Csv.FileName) = True then begin MessageDlg('Erro, arquivo já existe.', TMsgDlgType.mtError, [mbOK], 0); Exit; end; gradeJogos.SaveToCSVFile(dlgExportar_Csv.FileName, ';', True, False); end; procedure TfrmGerador_Combinatorio.Importar_Arquivo_csv; var dlgExportar_Csv: TOpenDialog; begin dlgExportar_Csv := TOpenDialog.Create(TComponent(self)); dlgExportar_Csv.InitialDir := '~/meus_documentos/exportados/'; dlgExportar_Csv.Filter := '*.csv'; if dlgExportar_Csv.Execute = False then begin Exit; end; // Vamos verificar se o arquivo existe. if FileExists(dlgExportar_Csv.FileName) = False then begin MessageDlg('Arquivo ' + dlgExportar_Csv.FileName + ' não existe.', TMsgDlgType.mtError, [mbOK], 0); Exit; end; // Se o arquivo existe, iremos preencher no controle 'gradeJogos'. // Se o controle não está vazio, avisar ao usuário que os dados serão sobrescritos. if gradeJogos.RowCount <> 0 then begin if MessageDlg( 'Os dados que serão importados, sobrescreverão os dados atuais, desejar continuar.', TMsgDlgType.mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin MessageDlg('Dados não foram importados, nenhuma informação foi sobrescrita.', TMsgDlgType.mtInformation, [mbOK], 0); Exit; end; end; try gradeJogos.LoadFromCSVFile(dlgExportar_csv.FileName, ';', True); except On Exception do begin MessageDlg('Um erro ocorreu ao importar.', TMsgDlgType.mtError, [mbOK], 0); gradeJogos.RowCount := 0; end; end; // Ajusta a largura das colunas gradeJogos.AutoSizeColumns; end; procedure TJogoThread.GerarLotomania; begin case JogoInfo.bolas_combinadas of //2: GerarLotomaniaGrupo2Numeros; //5: GerarLotomaniaGrupo5Numeros; 10: GerarLotomaniaGrupo10Numeros; end; end; procedure TJogoThread.GerarLotomaniaGrupo10Numeros; begin end; procedure TJogoThread.GerarLotomaniaGrupo2Numeros; begin end; procedure TJogoThread.GerarLotomaniaGrupo5Numeros; begin end; procedure TJogoThread.Preencher_Grade; type TParImpar = (NumeroPar, NumeroImpar); var iA, iB, iC: integer; numeroAleatorio: integer; // Guarda cada bola, de cada aposta //iJogo_Grade: array of array of integer; iJogo_Grade: array[0..1000, 0..50] of integer; bolaJaSorteada: array[0..99] of boolean; // Indica a quantidade de bolas já sorteadas. quantidadeBolasSorteadas: integer; // Indica o total de bolas que compõe o jogo. bolaTotal, numeroTemp, iD, iE, ColunaBolaCombinada: Integer; bTrocou: Boolean; listaNumero: TStringList; TrocarParImpar: TParImpar; listaNumeroPar: TStringList; listaNumeroImpar: TStringList; IndiceLista: LongInt; strNumeroConcatenado: String; Data: TDateTime; begin bolaTotal := JogoInfo.bolaFinal - JogoInfo.bolaInicial + 1; quantidadeBolasSorteadas := 0; Dec(JogoInfo.quantidadeBilhetes); // Iniciar o gerador de números randômicos. Randomize; // Vamos criar uma lista de string com os números listaNumero := TStringList.Create; listaNumeroImpar := TStringList.Create; listaNUmeroPar := TStringList.Create; for iC := JogoInfo.bolaInicial to JogoInfo.bolaFinal do begin bolaJaSorteada[iC] := false; listaNumero.Add(IntToStr(iC)); if iC mod 2 = 0 then ListaNumeroPar.Add(IntToSTr(iC)) else ListaNumeroImpar.Add(IntToStr(iC)); end; // Indica qual o tipo do número a usar. TrocarParImpar := TParImpar.NumeroPar; for iA := 0 to JogoInfo.quantidadeBilhetes do begin iB := 0; while iB < JogoInfo.bolaAposta do begin // Nossa lista irá guardar todos os números, iremos pegar um número aleatória, // este número corresponde a qualquer número que corresponde ao índice da lista. // Em seguida, iremos remove este ítem da lista, a lista, irá diminuir, até a // quantidade de ítens ser igual a zero. // Fiz, desta maneira, pois sempre é garantido que a cada iteração, sempre // vai sair um ítem da lista, ao contrário, da outra tentativa, que às vezes, // o mesmo número pode já ter sido selecionado e o loop demorar a executar. // Hoje, 10/06/2016, coloquei uma nova opção, a opção de escolher // se desejar que saía alternadamente par e impar. // Devemos observar, que pode acontecer que a quantidade de números pares e // impares não seja igual, neste caso, devemos pegar o número que resta, // por exemplo, há os números 2, 5, 8, 15, 17. // Por exemplo, ao percorrermos, iremos pegar par 2, impar 5, par 8, impar // 15 e em seguida, deveriamos pegar um número par, mas há um número impar // neste caso, devemos pegar o número ímpar. if JogoInfo.alternarParImpar = true then begin // Se as duas lista está vazia então enviar mensagem de erro. if (listaNumeroPar.Count = 0) and (listaNumeroImpar.Count = 0) then begin Raise Exception.Create('Lista de números pares e impares vazia.'); Exit end; if TrocarParImpar = TParImpar.NumeroPar then begin // Vamos verificar se há números pares ainda na lista. if listaNumeroPar.Count <> 0 then begin IndiceLista := Random(listaNumeroPar.Count); numeroAleatorio := StrToInt(listaNumeroPar.Strings[IndiceLista]); // Sempre sai um número não precisamos, gravar um arranjo de booleanos // indica o número já lido. listaNumeroPar.Delete(IndiceLista); // Gravar no arranjo. iJogo_Grade[iA, iB] := numeroAleatorio; Inc(quantidadeBolasSorteadas); Inc(iB); end; // Alterna para impar. TrocarParImpar := TParImpar.NumeroImpar; end else begin // Vamos verificar se há números impares na lista. if listaNumeroImpar.Count <> 0 then begin IndiceLista := Random(listaNumeroImpar.Count); numeroAleatorio := StrToInt(listaNumeroImpar.Strings[IndiceLista]); // Sempre sai número impar, não precisamos marcar qual saiu. listaNumeroImpar.Delete(IndiceLista); // Gravar no arranjo. iJogo_Grade[iA, iB] := numeroAleatorio; Inc(quantidadeBolasSorteadas); Inc(iB); end else begin // Geralmente, isto nunca acontecerá. Raise Exception.Create('Isto não deve nunca acontecer.' + #10#13 + 'A próxima iteração é par mas não há nenhum par.'); Exit; end; // Alterna para par. TrocarParImpar := TParImpar.NumeroPar; end end else begin // Isto quer dizer que o número pode vir em qualquer ordem de números par e impar. IndiceLista := Random(ListaNumero.Count); numeroAleatorio := StrToInt(ListaNumero.Strings[IndiceLista]); // Retirar item da lista. listaNumero.Delete(IndiceLista); // Gravar no arranjo. iJogo_Grade[iA, iB] := numeroAleatorio; Inc(quantidadeBolasSorteadas); Inc(iB); end; // Se a quantidade de bolas já foi atingida, // devemos resetar a variável 'BolaJaSorteada', em seguida, devemos // definir para true, as bolas que já foram sorteadas, aqui, neste loop. if quantidadeBolasSorteadas = bolaTotal then begin quantidadeBolasSorteadas := 0; // Garantir que a lista está vazia, não é necessário. listaNumero.Clear; listaNumeroPar.Clear; listaNumeroImpar.Clear; for iC := JogoInfo.bolaInicial to JogoInfo.bolaFinal do begin // Adiciona os números à lista de string de números. listaNumero.Add(IntToStr(iC)); if iC mod 2 = 0 then listaNumeroPar.Add(IntToStr(iC)) else listaNumeroImpar.Add(IntToStr(iC)); end; // Se iB é igual a quantidade de números apostados, e que se todos // as bolas foram sorteadas, quer dizer, que todos os números foram // sorteados, podemos começar um novo jogo, escolhendo qualquer número. if iB = JogoInfo.bolaAposta then begin // Randomize os números. //RandSeed := StrToFloat(Format('%f', [Now])); Randomize; Continue; end else begin // Se chegamos aqui, quer dizer, que a quantidade de bolas aposta // ainda está incompleta, então devemos repetir bolas que estão no // nos concurso anterior e que não pode estar no concurso atual. // Vamos percorrer, cada bola já sorteada e retirar da lista de número // que ainda não foram sorteados. // Definir a quantidade de bolas sorteadas, da aposta corrente. // Será iB - 1, pois iB é baseado em zero. quantidadeBolasSorteadas := iB; for iC := 0 to iB - 1 do begin if JogoInfo.alternarParImpar = true then begin // Vamos verificar se é par ou impar. numeroAleatorio := iJogo_Grade[iA, iC]; if numeroAleatorio mod 2 = 0 then begin IndiceLista := ListaNumeroPar.IndexOf(IntToStr(numeroAleatorio)); if IndiceLista <> -1 then begin ListaNumeroPar.Delete(IndiceLista); end else begin // Isto, nunca pode acontecer. Raise Exception.Create('O número é par, mas não está na lista, deveria estar.'); Exit; end; end else begin // O número é impar. IndiceLista := ListaNumeroImpar.IndexOf(IntToStr(numeroAleatorio)); if IndiceLista <> -1 then begin ListaNumeroImpar.Delete(IndiceLista); end else begin // Isto, nunca pode acontecer. Raise Exception.Create('O número é impar, mas não está na lista, deveria estar.'); Exit; end; end; end else begin // O usuário não marcou que quer par e impar alternados. IndiceLista := ListaNumero.IndexOf(IntToStr(iJogo_Grade[iA, iC])); if IndiceLista <> -1 then begin ListaNumero.Delete(IndiceLista); end else begin // Isto, nunca pode acontecer, somente acontecer, se algum número // repetiu, acho bem improvável acontecer. Raise Exception.Create('O número não foi localizado, provavelmente, este ' + 'número saiu mais de uma vez.'); Exit; end; end; end; end; end; end; //O arranjo é baseado em zero, devemos diminuir iB, para utilizar //com melhor desempenho no loop. dec(iB); repeat bTrocou := false; for iE := 0 to iB - 1 do begin if iJogo_Grade[iA, iE] > iJogo_Grade[iA, iE + 1] then begin numeroTemp := iJogo_Grade[iA, iE]; iJogo_Grade[iA, iE] := iJogo_Grade[iA, iE + 1]; iJogo_Grade[iA, iE + 1] := numeroTemp; bTrocou := true; end; end; until bTrocou = false ; end; // A quantidade de números apostados, indicará a quantidade de colunas que haverá. // Também, haverá colunas adicionais para indicar informações para identificar // O tipo do jogo, a quantidade de números apostados, e quantos jogos foram // selecionados. // Haverá 4 colunas a mais, para indicar: // Tipo do jogo; // quantidade de números apostados; // quantidade de jogos apostados; e, // bolas_concatenadas. // bolas_repetidas; JogoGrade.ColCount := JogoInfo.bolaAposta + 5; // A quantidade de fileira será 1 maior, pois uma coluna será o cabeçalho. // Retorna ao estado atual. Inc(JogoInfo.quantidadeBilhetes); JogoGrade.RowCount := JogoInfo.quantidadeBilhetes + 1; // A primeira fileira conterá o cabeçalho JogoGrade.FixedRows := 1; // As três colunas iniciais de cada fileira, indica: // O tipo do jogo, // A quantidade de números apostados, // e, quantidade de jogos apostados. JogoGrade.FixedCols := 3; // Vamos preencher o cabeçalho JogoGrade.Cells[0, 0] := 'BILHETE'; JogoGrade.Cells[1, 0] := 'JOGO'; JogoGrade.Cells[2, 0] := 'APOSTA'; JogoGrade.Cells[JogoGrade.ColCount - 2 , 0] := 'BOLAS_COMBINADAS'; JogoGrade.Cells[JogoGrade.ColCount - 1, 0] := 'REPETIU'; // Vamos começar na coluna 3, como os índices são baseados em 0 // iremos adicionar + 2 for iA := 1 to JogoInfo.bolaAposta do begin JogoGrade.Cells[iA + 2, 0] := 'B' + IntToStr(iA); end; // Preencher grid. for iA := 1 to JogoInfo.quantidadeBilhetes do begin // Insira informações das colunas 1 a 2 JogoGrade.Cells[0, iA] := IntToStr(iA); JogoGrade.cells[1, iA] := JogoInfo.JogoTipo; JogoGrade.Cells[2, iA] := 'com ' + IntToStr(JogoInfo.bolaAposta) + ' números.'; //statusBar1.Panels[0].Text := 'Processando linha: ' + IntToStr(iA + 1); //statusBar1.Refresh; strNumeroConcatenado := ''; for iB := 0 to JogoInfo.bolaAposta-1 do begin JogoGrade.Cells[3 + iB, iA] := IntToStr(iJogo_Grade[iA-1, iB]); strNumeroConcatenado += '_' + Format('%.2d', [iJogo_Grade[iA - 1, iB]]); end; // Números concatenados. Inc(iB); JogoGrade.Cells[3 + iB, iA] := strNumeroConcatenado; JogoGrade.Cells[4 + iB, iA] := ''; end; // Pega a coluna das bolas combinadas ColunaBolaCombinada := JogoGrade.ColCount - 2; for iA := 1 to JogoInfo.quantidadeBilhetes do for iB := iA + 1 to JogoInfo.quantidadeBilhetes do begin if JogoGrade.Cells[ColunaBolaCombinada, iA] = JogoGrade.Cells[ColunaBolaCombinada, iB] then begin // Vamos acrescentar os dados ao que já está na célula. JogoGrade.Cells[ColunaBolaCombinada + 1, iB] := JogoGrade.Cells[ColunaBolaCombinada + 1, iB] + IntToStr(iA) + ';' end; end; JogoGrade.AutoSizeColumns; FreeAndNil(listaNumero); end; end.
namespace TestApplication; interface uses proholz.xsdparser, RemObjects.Elements.EUnit; type AndroidParseTest = public class(TestBaseClass) private protected method SetupTest; override; public; begin //var xsd := gettestParser('android.xsd'); end; public // * // * Asserts if the hierarchy is being parsed correctly. The hierarchy is implemented with the base // * field. // * Example: If element A has a {@link XsdExtension} with his base with element B that means that // * element A extends element B. // method testHierarchy; end; implementation method AndroidParseTest.testHierarchy; begin var relativeLayoutOptional: XsdElement := elements .Where(element -> element.getName().equals('RelativeLayout')) .FirstOrDefault(); Assert.IsTrue(relativeLayoutOptional <> nil); var relativeLayout: XsdElement := relativeLayoutOptional; var relativeLayoutComplexType: XsdComplexType := relativeLayout.getXsdComplexType(); Assert.IsNotNil(relativeLayoutComplexType); var relativeLayoutComplexContent: XsdComplexContent := relativeLayoutComplexType.getComplexContent(); Assert.IsNotNil(relativeLayoutComplexContent); var relativeLayoutExtension: XsdExtension := relativeLayoutComplexContent.getXsdExtension(); var viewGroupType: XsdComplexType := relativeLayoutExtension.getBaseAsComplexType(); Assert.IsNotNil(viewGroupType); var viewGroupComplexContent: XsdComplexContent := viewGroupType.getComplexContent(); Assert.IsNotNil(viewGroupComplexContent); var viewGroupExtension: XsdExtension := viewGroupComplexContent.getXsdExtension(); var view: XsdComplexType := viewGroupExtension.getBaseAsComplexType(); Assert.IsNotNil(view); Assert.AreEqual('View', view.getName()); end; end.
(* Category: SWAG Title: MEMORY/DPMI MANAGEMENT ROUTINES Original name: 0021.PAS Description: BIG Arrays on the HEAP Author: SEPP MAYER Date: 08-27-93 20:15 *) { SEPP MAYER > Unfortunately I can't cut down on the size of my variables...(well, > ok, one of them I did, but it drastically reduces the usefulness of > the program itself). So now I got rid of it, but one of my variables > is of Array [1..1000] Of String[12]. I'd like to have the array go to > 2500. Unfortunately, when I do this, it gives me the error. Is there > some way to get around that?? At the Time your Array uses 13000 Byte of Memory in the Data-Segment (12 Byte for the 12 characters in the string + 1 Byte for the Length). The Only Thing You have to do, is to put your Array to the Heap, so you can have an Array[1..3250] of your String with the same Use of Memory in your Data-Segment. } program BigArray; type PStr12 = ^TStr12; tStr12 = String[12]; var TheTab : Array[1..3250] of PStr12; i : Integer; function AddTabEle(i : Integer; s : String) : Boolean; begin if i < 1 then begin WriteLn('You Used an Index lower than 1'); AddTabEle := false; Exit; end; if i > 3250 then begin WriteLn('You Used an Index higher then 3250'); AddTabEle := false; Exit; end; if TheTab[i] <> nil then begin WriteLn('TAB Element is already in Use'); AddTabEle := false; Exit; end; {if MemAvail < 13 then begin WriteLn('Not Enough Heap Memory'); AddTabEle := false; Exit; end;} New(TheTab[i]); TheTab[i]^ := Copy(s,1,12); {Limit to 12 Characters} AddTabEle := true; end; function ChangeTabEle(i : integer; s : string) : Boolean; begin if TheTab[i] = nil then begin WriteLn('You Tried to Modify an non-existing TAB Element, Use AddTabEle'); ChangeTabEle := false; Exit; end; TheTab[i]^ := Copy(s, 1, 12); ChangeTabEle := true; end; function GetTabEle(i : integer) : string; begin if TheTab[i] = nil then begin GetTabEle := 'TAB Ele not found'; {No error occurs} Exit; end; GetTabEle := TheTab[i]^; end; function FreeTabEle(i : integer) : Boolean; begin if TheTab[i] = nil then begin WriteLn('TAB Element is not used'); FreeTabEle := false; Exit; end; Dispose(TheTab[i]); TheTab[i] := nil; FreeTabEle := true; end; procedure FreeTab; begin for i := 1 to 3250 do begin if TheTab[i] <> nil then if NOT FreeTabEle(i) then WriteLn('Error releasing Tab element'); end; end; begin for i := 1 to 3250 do {Initialize Pointers with nil, to test } TheTab[i] := nil; {if Element is Used, compare pointer with nil} {.......} {Your Program} if NOT AddTabEle(1, 'Max 12 Chars') then {Add an Ele} WriteLn('Error creating TAB element'); {evtl. use FreeMem + Halt(1)} {to terminate Programm} WriteLn(GetTabEle(1)); {Write an Tab Ele} if NOT ChangeTabEle(1, '12 Chars Max') then {Change an Ele} WriteLn('Error changing TAB element'); {evtl. use FreeMem + Halt(1)} {to terminate Programm} WriteLn(GetTabEle(1)); {Write an Tab Ele} if NOT FreeTabEle(1) then {Delete(Free) an Ele} WriteLn('Error releasing Tab element'); {evtl. use FreeMem + Halt(1)} {to terminate Programm} {.......} {Your Program} FreeTab; {At The End of Your Program free all TAB Ele} end.
unit frmHashInfo; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, Controls, Dialogs, Forms, Graphics, Messages, OTFEFreeOTFE_U, OTFEFreeOTFEBase_U, SDUForms, StdCtrls, SysUtils, Windows; type TfrmHashInfo = class (TSDUForm) gbHashDriver: TGroupBox; lblDeviceName: TLabel; lblDeviceUserModeName: TLabel; lblDeviceKernelModeName: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; edDriverDeviceName: TEdit; edDriverDeviceUserModeName: TEdit; edDriverDeviceKernelModeName: TEdit; edDriverTitle: TEdit; edDriverVersionID: TEdit; edDriverHashCount: TEdit; gbHash: TGroupBox; Label7: TLabel; Label8: TLabel; Label10: TLabel; Label11: TLabel; edHashGUID: TEdit; edHashTitle: TEdit; edHashLength: TEdit; edHashVersionID: TEdit; pbClose: TButton; edDriverGUID: TEdit; Label9: TLabel; edHashBlockSize: TEdit; Label12: TLabel; procedure pbCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); PRIVATE { Private declarations } // These two items uniquely identify which should be shown fShowDriverName: String; fShowGUID: TGUID; PUBLIC // OTFEFreeOTFEObj: TOTFEFreeOTFEBase; property ShowDriverName : String write fShowDriverName ; property ShowGUID : TGUID write fShowGUID; end; implementation {$R *.DFM} uses ComObj, SDUi18n, // Required for GUIDToString(...) ActiveX, // Required for IsEqualGUID OTFEFreeOTFEDLL_U, SDUGeneral; resourcestring RS_UNABLE_LOCATE_HASH_DRIVER = '<Unable to locate correct hash driver>'; RS_UNABLE_LOCATE_HASH = '<Unable to locate hash>'; procedure TfrmHashInfo.pbCloseClick(Sender: TObject); begin Close(); end; procedure TfrmHashInfo.FormShow(Sender: TObject); var hashDrivers: array of TFreeOTFEHashDriver; i, j: Integer; currHashDriver: TFreeOTFEHashDriver; currHash: TFreeOTFEHash; tmpString: String; begin // Blank out in case none found edDriverGUID.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edDriverDeviceName.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edDriverDeviceKernelModeName.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edDriverDeviceUserModeName.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edDriverTitle.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edDriverVersionID.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edDriverHashCount.Text := RS_UNABLE_LOCATE_HASH_DRIVER; edHashGUID.Text := RS_UNABLE_LOCATE_HASH; edHashTitle.Text := RS_UNABLE_LOCATE_HASH; edHashVersionID.Text := RS_UNABLE_LOCATE_HASH; edHashLength.Text := RS_UNABLE_LOCATE_HASH; edHashBlockSize.Text := RS_UNABLE_LOCATE_HASH; if (GetFreeOTFEBase() is TOTFEFreeOTFEDLL) then begin lblDeviceName.Caption := _('Library:'); lblDeviceUserModeName.Visible := False; edDriverDeviceUserModeName.Visible := False; lblDeviceKernelModeName.Visible := False; edDriverDeviceKernelModeName.Visible := False; end; SetLength(hashDrivers, 0); if GetFreeOTFEBase().GetHashDrivers(TFreeOTFEHashDriverArray(hashDrivers)) then begin for i := low(hashDrivers) to high(hashDrivers) do begin currHashDriver := hashDrivers[i]; if ((currHashDriver.LibFNOrDevKnlMdeName = fShowDriverName) or (currHashDriver.DeviceUserModeName = fShowDriverName)) then begin edDriverGUID.Text := GUIDToString(currHashDriver.DriverGUID); if (GetFreeOTFEBase() is TOTFEFreeOTFEDLL) then begin edDriverDeviceName.Text := currHashDriver.LibFNOrDevKnlMdeName; end else begin edDriverDeviceName.Text := currHashDriver.DeviceName; edDriverDeviceKernelModeName.Text := currHashDriver.LibFNOrDevKnlMdeName; edDriverDeviceUserModeName.Text := currHashDriver.DeviceUserModeName; end; edDriverTitle.Text := currHashDriver.Title; edDriverVersionID.Text := GetFreeOTFEBase().VersionIDToStr(currHashDriver.VersionID); edDriverHashCount.Text := IntToStr(currHashDriver.HashCount); for j := low(hashDrivers[i].Hashes) to high(hashDrivers[i].Hashes) do begin currHash := hashDrivers[i].Hashes[j]; if (IsEqualGUID(currHash.HashGUID, fShowGUID)) then begin edHashGUID.Text := GUIDToString(currHash.HashGUID); edHashTitle.Text := currHash.Title; edHashVersionID.Text := GetFreeOTFEBase().VersionIDToStr(currHash.VersionID); tmpString := SDUParamSubstitute(COUNT_BITS, [currHash.Length]); if (currHash.Length = -1) then begin tmpString := tmpString + ' ' + _('(length of hash returned may vary)'); end; edHashLength.Text := tmpString; tmpString := SDUParamSubstitute(COUNT_BITS, [currHash.BlockSize]); if (currHash.BlockSize = -1) then begin tmpString := tmpString + ' ' + _('(n/a)'); end; edHashBlockSize.Text := tmpString; end; end; end; end; end; end; end.
{ FileName: DXVAHD.h } unit Win32.DXVAHD; interface // Updated to SDK 10.0.17763.0 // (c) Translation to Pascal by Norbert Sonnleitner {$IFDEF FPC} {$mode delphi} {$ENDIF} {$Z4} {$A4} uses Windows, Classes; const DXVAHD_DLL = 'Dxva2.dll'; const IID_IDXVAHD_Device: TGUID = '{95f12dfd-d77e-49be-815f-57d579634d6d}'; IID_IDXVAHD_VideoProcessor: TGUID = '{95f4edf4-6e03-4cd7-be1b-3075d665aa52}'; DXVAHDControlGuid: TGUID = '{a0386e75-f70c-464c-a9ce-33c44e091623}'; // DXVA2Trace_Control DXVAHDETWGUID_CREATEVIDEOPROCESSOR: TGUID = '{681e3d1e-5674-4fb3-a503-2f2055e91f60}'; DXVAHDETWGUID_VIDEOPROCESSBLTSTATE: TGUID = '{76c94b5a-193f-4692-9484-a4d999da81a8}'; DXVAHDETWGUID_VIDEOPROCESSSTREAMSTATE: TGUID = '{262c0b02-209d-47ed-94d8-82ae02b84aa7}'; DXVAHDETWGUID_VIDEOPROCESSBLTHD: TGUID = '{bef3d435-78c7-4de3-9707-cd1b083b160a}'; DXVAHDETWGUID_VIDEOPROCESSBLTHD_STREAM: TGUID = '{27ae473e-a5fc-4be5-b4e3-f24994d3c495}'; DXVAHDETWGUID_DESTROYVIDEOPROCESSOR: TGUID = '{f943f0a0-3f16-43e0-8093-105a986aa5f1}'; DXVAHD_STREAM_STATE_PRIVATE_IVTC: TGUID = '{9c601e3c-0f33-414c-a739-99540ee42da5}'; type IDirect3DDevice9Ex = DWORD; PIDirect3DDevice9Ex = ^IDirect3DDevice9Ex; IDirect3DSurface9 = DWORD; PIDirect3DSurface9 = ^IDirect3DSurface9; TD3DCOLOR = DWORD; PD3DCOLOR = ^TD3DCOLOR; TD3DFORMAT = DWORD; PD3DFORMAT = ^TD3DFORMAT; TD3DPOOL = DWORD; TDXVAHD_FRAME_FORMAT = (DXVAHD_FRAME_FORMAT_PROGRESSIVE = 0, DXVAHD_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST = 1, DXVAHD_FRAME_FORMAT_INTERLACED_BOTTOM_FIELD_FIRST = 2); TDXVAHD_DEVICE_USAGE = (DXVAHD_DEVICE_USAGE_PLAYBACK_NORMAL = 0, DXVAHD_DEVICE_USAGE_OPTIMAL_SPEED = 1, DXVAHD_DEVICE_USAGE_OPTIMAL_QUALITY = 2); TDXVAHD_SURFACE_TYPE = (DXVAHD_SURFACE_TYPE_VIDEO_INPUT = 0, DXVAHD_SURFACE_TYPE_VIDEO_INPUT_PRIVATE = 1, DXVAHD_SURFACE_TYPE_VIDEO_OUTPUT = 2); TDXVAHD_DEVICE_TYPE = (DXVAHD_DEVICE_TYPE_HARDWARE = 0, DXVAHD_DEVICE_TYPE_SOFTWARE = 1, DXVAHD_DEVICE_TYPE_REFERENCE = 2, DXVAHD_DEVICE_TYPE_OTHER = 3); TDXVAHD_DEVICE_CAPS = (DXVAHD_DEVICE_CAPS_LINEAR_SPACE = $1, DXVAHD_DEVICE_CAPS_xvYCC = $2, DXVAHD_DEVICE_CAPS_RGB_RANGE_CONVERSION = $4, DXVAHD_DEVICE_CAPS_YCbCr_MATRIX_CONVERSION = $8); TDXVAHD_FEATURE_CAPS = (DXVAHD_FEATURE_CAPS_ALPHA_FILL = $1, DXVAHD_FEATURE_CAPS_CONSTRICTION = $2, DXVAHD_FEATURE_CAPS_LUMA_KEY = $4, DXVAHD_FEATURE_CAPS_ALPHA_PALETTE = $8); TDXVAHD_FILTER_CAPS = (DXVAHD_FILTER_CAPS_BRIGHTNESS = $1, DXVAHD_FILTER_CAPS_CONTRAST = $2, DXVAHD_FILTER_CAPS_HUE = $4, DXVAHD_FILTER_CAPS_SATURATION = $8, DXVAHD_FILTER_CAPS_NOISE_REDUCTION = $10, DXVAHD_FILTER_CAPS_EDGE_ENHANCEMENT = $20, DXVAHD_FILTER_CAPS_ANAMORPHIC_SCALING = $40); TDXVAHD_INPUT_FORMAT_CAPS = (DXVAHD_INPUT_FORMAT_CAPS_RGB_INTERLACED = $1, DXVAHD_INPUT_FORMAT_CAPS_RGB_PROCAMP = $2, DXVAHD_INPUT_FORMAT_CAPS_RGB_LUMA_KEY = $4, DXVAHD_INPUT_FORMAT_CAPS_PALETTE_INTERLACED = $8); TDXVAHD_PROCESSOR_CAPS = (DXVAHD_PROCESSOR_CAPS_DEINTERLACE_BLEND = $1, DXVAHD_PROCESSOR_CAPS_DEINTERLACE_BOB = $2, DXVAHD_PROCESSOR_CAPS_DEINTERLACE_ADAPTIVE = $4, DXVAHD_PROCESSOR_CAPS_DEINTERLACE_MOTION_COMPENSATION = $8, DXVAHD_PROCESSOR_CAPS_INVERSE_TELECINE = $10, DXVAHD_PROCESSOR_CAPS_FRAME_RATE_CONVERSION = $20); TDXVAHD_ITELECINE_CAPS = (DXVAHD_ITELECINE_CAPS_32 = $1, DXVAHD_ITELECINE_CAPS_22 = $2, DXVAHD_ITELECINE_CAPS_2224 = $4, DXVAHD_ITELECINE_CAPS_2332 = $8, DXVAHD_ITELECINE_CAPS_32322 = $10, DXVAHD_ITELECINE_CAPS_55 = $20, DXVAHD_ITELECINE_CAPS_64 = $40, DXVAHD_ITELECINE_CAPS_87 = $80, DXVAHD_ITELECINE_CAPS_222222222223 = $100, DXVAHD_ITELECINE_CAPS_OTHER = $80000000); TDXVAHD_FILTER = (DXVAHD_FILTER_BRIGHTNESS = 0, DXVAHD_FILTER_CONTRAST = 1, DXVAHD_FILTER_HUE = 2, DXVAHD_FILTER_SATURATION = 3, DXVAHD_FILTER_NOISE_REDUCTION = 4, DXVAHD_FILTER_EDGE_ENHANCEMENT = 5, DXVAHD_FILTER_ANAMORPHIC_SCALING = 6); TDXVAHD_BLT_STATE = (DXVAHD_BLT_STATE_TARGET_RECT = 0, DXVAHD_BLT_STATE_BACKGROUND_COLOR = 1, DXVAHD_BLT_STATE_OUTPUT_COLOR_SPACE = 2, DXVAHD_BLT_STATE_ALPHA_FILL = 3, DXVAHD_BLT_STATE_CONSTRICTION = 4, DXVAHD_BLT_STATE_PRIVATE = 1000); TDXVAHD_ALPHA_FILL_MODE = (DXVAHD_ALPHA_FILL_MODE_OPAQUE = 0, DXVAHD_ALPHA_FILL_MODE_BACKGROUND = 1, DXVAHD_ALPHA_FILL_MODE_DESTINATION = 2, DXVAHD_ALPHA_FILL_MODE_SOURCE_STREAM = 3); TDXVAHD_STREAM_STATE = (DXVAHD_STREAM_STATE_D3DFORMAT = 0, DXVAHD_STREAM_STATE_FRAME_FORMAT = 1, DXVAHD_STREAM_STATE_INPUT_COLOR_SPACE = 2, DXVAHD_STREAM_STATE_OUTPUT_RATE = 3, DXVAHD_STREAM_STATE_SOURCE_RECT = 4, DXVAHD_STREAM_STATE_DESTINATION_RECT = 5, DXVAHD_STREAM_STATE_ALPHA = 6, DXVAHD_STREAM_STATE_PALETTE = 7, DXVAHD_STREAM_STATE_LUMA_KEY = 8, DXVAHD_STREAM_STATE_ASPECT_RATIO = 9, DXVAHD_STREAM_STATE_FILTER_BRIGHTNESS = 100, DXVAHD_STREAM_STATE_FILTER_CONTRAST = 101, DXVAHD_STREAM_STATE_FILTER_HUE = 102, DXVAHD_STREAM_STATE_FILTER_SATURATION = 103, DXVAHD_STREAM_STATE_FILTER_NOISE_REDUCTION = 104, DXVAHD_STREAM_STATE_FILTER_EDGE_ENHANCEMENT = 105, DXVAHD_STREAM_STATE_FILTER_ANAMORPHIC_SCALING = 106, DXVAHD_STREAM_STATE_PRIVATE = 1000); TDXVAHD_OUTPUT_RATE = (DXVAHD_OUTPUT_RATE_NORMAL = 0, DXVAHD_OUTPUT_RATE_HALF = 1, DXVAHD_OUTPUT_RATE_CUSTOM = 2); TDXVAHD_RATIONAL = record Numerator: UINT; Denominator: UINT; end; TDXVAHD_COLOR_RGBA = record R: single; G: single; B: single; A: single; end; TDXVAHD_COLOR_YCbCrA = record Y: single; Cb: single; Cr: single; A: single; end; TDXVAHD_CONTENT_DESC = record InputFrameFormat: TDXVAHD_FRAME_FORMAT; InputFrameRate: TDXVAHD_RATIONAL; InputWidth: UINT; InputHeight: UINT; OutputFrameRate: TDXVAHD_RATIONAL; OutputWidth: UINT; OutputHeight: UINT; end; TDXVAHD_VPDEVCAPS = record DeviceType: TDXVAHD_DEVICE_TYPE; DeviceCaps: UINT; FeatureCaps: UINT; FilterCaps: UINT; InputFormatCaps: UINT; InputPool: TD3DPOOL; OutputFormatCount: UINT; InputFormatCount: UINT; VideoProcessorCount: UINT; MaxInputStreams: UINT; MaxStreamStates: UINT; end; TDXVAHD_VPCAPS = record VPGuid: TGUID; PastFrames: UINT; FutureFrames: UINT; ProcessorCaps: UINT; ITelecineCaps: UINT; CustomRateCount: UINT; end; PDXVAHD_VPCAPS = ^TDXVAHD_VPCAPS; TDXVAHD_CUSTOM_RATE_DATA = record CustomRate: TDXVAHD_RATIONAL; OutputFrames: UINT; InputInterlaced: boolean; InputFramesOrFields: UINT; end; PDXVAHD_CUSTOM_RATE_DATA = ^TDXVAHD_CUSTOM_RATE_DATA; TDXVAHD_FILTER_RANGE_DATA = record Minimum: integer; Maximum: integer; _Default: integer; Multiplier: single; end; TDXVAHD_BLT_STATE_TARGET_RECT_DATA = record Enable: boolean; TargetRect: TRECT; end; TDXVAHD_COLOR = record case integer of 0: (RGB: TDXVAHD_COLOR_RGBA); 1: (YCbCr: TDXVAHD_COLOR_YCbCrA); end; TDXVAHD_BLT_STATE_BACKGROUND_COLOR_DATA = record YCbCr: boolean; BackgroundColor: TDXVAHD_COLOR; end; {$IFDEF FPC} TDXVAHD_BLT_STATE_OUTPUT_COLOR_SPACE_DATA = bitpacked record case integer of 0: (Usage: 0..1; RGB_Range: 0..1; YCbCr_Matrix: 0..1; YCbCr_xvYCC: 0..1; Reserved: 0..268435455); 1: (Value: UINT); end; {$ELSE} TDXVAHD_BLT_STATE_OUTPUT_COLOR_SPACE_DATA = record Value: UINT; end; {$ENDIF} TDXVAHD_BLT_STATE_ALPHA_FILL_DATA = record Mode: TDXVAHD_ALPHA_FILL_MODE; StreamNumber: UINT; end; TDXVAHD_BLT_STATE_CONSTRICTION_DATA = record Enable: boolean; Size: TSIZE; end; TDXVAHD_BLT_STATE_PRIVATE_DATA = record Guid: TGUID; DataSize: UINT; pData: Pointer; end; TDXVAHD_STREAM_STATE_D3DFORMAT_DATA = record Format: TD3DFORMAT; end; TDXVAHD_STREAM_STATE_FRAME_FORMAT_DATA = record FrameFormat: TDXVAHD_FRAME_FORMAT; end; {$IFDEF FPC} TDXVAHD_STREAM_STATE_INPUT_COLOR_SPACE_DATA = record case integer of 0: (_Type: 0..1; RGB_Range: 0..1; YCbCr_Matrix: 0..1; YCbCr_xvYCC: 0..1; Reserved: 0..(1 shl 28)-1); 1: (Value: UINT); end; {$ELSE} TDXVAHD_STREAM_STATE_INPUT_COLOR_SPACE_DATA = record Value: UINT; end; {$ENDIF} TDXVAHD_STREAM_STATE_OUTPUT_RATE_DATA = record RepeatFrame: boolean; OutputRate: TDXVAHD_OUTPUT_RATE; CustomRate: TDXVAHD_RATIONAL; end; TDXVAHD_STREAM_STATE_SOURCE_RECT_DATA = record Enable: boolean; SourceRect: TRECT; end; TDXVAHD_STREAM_STATE_DESTINATION_RECT_DATA = record Enable: boolean; DestinationRect: TRECT; end; TDXVAHD_STREAM_STATE_ALPHA_DATA = record Enable: boolean; Alpha: single; end; TDXVAHD_STREAM_STATE_PALETTE_DATA = record Count: UINT; pEntries: PD3DCOLOR; end; TDXVAHD_STREAM_STATE_LUMA_KEY_DATA = record Enable: boolean; Lower: single; Upper: single; end; TDXVAHD_STREAM_STATE_ASPECT_RATIO_DATA = record Enable: boolean; SourceAspectRatio: TDXVAHD_RATIONAL; DestinationAspectRatio: TDXVAHD_RATIONAL; end; TDXVAHD_STREAM_STATE_FILTER_DATA = record Enable: boolean; Level: integer; end; TDXVAHD_STREAM_STATE_PRIVATE_DATA = record Guid: TGUID; DataSize: UINT; pData: Pointer; end; TDXVAHD_STREAM_DATA = record Enable: boolean; OutputIndex: UINT; InputFrameOrField: UINT; PastFrames: UINT; FutureFrames: UINT; ppPastSurfaces: PIDirect3DSurface9; pInputSurface: PIDirect3DSurface9; ppFutureSurfaces: PIDirect3DSurface9; end; PDXVAHD_STREAM_DATA = ^TDXVAHD_STREAM_DATA; TDXVAHD_STREAM_STATE_PRIVATE_IVTC_DATA = record Enable: boolean; ITelecineFlags: UINT; Frames: UINT; InputField: UINT; end; PDXVAHDSW_CreateDevice = function(pD3DDevice: IDirect3DDevice9Ex; out phDevice: THANDLE): HResult; stdcall; // callback PDXVAHDSW_ProposeVideoPrivateFormat = function(hDevice: THANDLE; var pFormat: TD3DFORMAT): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessorDeviceCaps = function(hDevice: THANDLE; const pContentDesc: TDXVAHD_CONTENT_DESC; Usage: TDXVAHD_DEVICE_USAGE; out pCaps: TDXVAHD_VPDEVCAPS): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessorOutputFormats = function(hDevice: THANDLE; const pContentDesc: TDXVAHD_CONTENT_DESC; Usage: TDXVAHD_DEVICE_USAGE; Count: UINT; out pFormats: PD3DFORMAT): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessorInputFormats = function(hDevice: THANDLE; const pContentDesc: TDXVAHD_CONTENT_DESC; Usage: TDXVAHD_DEVICE_USAGE; Count: UINT; out pFormats: PD3DFORMAT): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessorCaps = function(hDevice: THANDLE; const pContentDesc: TDXVAHD_CONTENT_DESC; Usage: TDXVAHD_DEVICE_USAGE; Count: UINT; out pCaps: PDXVAHD_VPCAPS): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessorCustomRates = function(hDevice: THANDLE; const pVPGuid: TGUID; Count: UINT; out pRates: PDXVAHD_CUSTOM_RATE_DATA): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessorFilterRange = function(hDevice: THANDLE; Filter: TDXVAHD_FILTER; out pRange: TDXVAHD_FILTER_RANGE_DATA): HResult; stdcall; // callback PDXVAHDSW_DestroyDevice = function(hDevice: THANDLE): HResult; stdcall; // callback PDXVAHDSW_CreateVideoProcessor = function(hDevice: THANDLE; const pVPGuid: TGUID; out phVideoProcessor: THANDLE): HResult; stdcall; // callback PDXVAHDSW_SetVideoProcessBltState = function(hVideoProcessor: THANDLE; State: TDXVAHD_BLT_STATE; DataSize: UINT; const pData: Pointer): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessBltStatePrivate = function(hVideoProcessor: THANDLE; var pData: TDXVAHD_BLT_STATE_PRIVATE_DATA): HResult; stdcall; // callback PDXVAHDSW_SetVideoProcessStreamState = function(hVideoProcessor: THANDLE; StreamNumber: UINT; State: TDXVAHD_STREAM_STATE; DataSize: UINT; const pData: Pointer): HResult; stdcall; // callback PDXVAHDSW_GetVideoProcessStreamStatePrivate = function(hVideoProcessor: THANDLE; StreamNumber: UINT; var pData: TDXVAHD_STREAM_STATE_PRIVATE_DATA): HResult; stdcall; // callback PDXVAHDSW_VideoProcessBltHD = function(hVideoProcessor: THANDLE; pOutputSurface: IDirect3DSurface9; OutputFrame: UINT; StreamCount: UINT; const pStreams: PDXVAHD_STREAM_DATA): HResult; stdcall; // callback PDXVAHDSW_DestroyVideoProcessor = function(hVideoProcessor: THANDLE): HResult; stdcall; // callback TDXVAHDSW_CALLBACKS = record CreateDevice: PDXVAHDSW_CreateDevice; ProposeVideoPrivateFormat: PDXVAHDSW_ProposeVideoPrivateFormat; GetVideoProcessorDeviceCaps: PDXVAHDSW_GetVideoProcessorDeviceCaps; GetVideoProcessorOutputFormats: PDXVAHDSW_GetVideoProcessorOutputFormats; GetVideoProcessorInputFormats: PDXVAHDSW_GetVideoProcessorInputFormats; GetVideoProcessorCaps: PDXVAHDSW_GetVideoProcessorCaps; GetVideoProcessorCustomRates: PDXVAHDSW_GetVideoProcessorCustomRates; GetVideoProcessorFilterRange: PDXVAHDSW_GetVideoProcessorFilterRange; DestroyDevice: PDXVAHDSW_DestroyDevice; CreateVideoProcessor: PDXVAHDSW_CreateVideoProcessor; SetVideoProcessBltState: PDXVAHDSW_SetVideoProcessBltState; GetVideoProcessBltStatePrivate: PDXVAHDSW_GetVideoProcessBltStatePrivate; SetVideoProcessStreamState: PDXVAHDSW_SetVideoProcessStreamState; GetVideoProcessStreamStatePrivate: PDXVAHDSW_GetVideoProcessStreamStatePrivate; VideoProcessBltHD: PDXVAHDSW_VideoProcessBltHD; DestroyVideoProcessor: PDXVAHDSW_DestroyVideoProcessor; end; PDXVAHDSW_Plugin = function(Size: UINT; out pCallbacks: Pointer): HResult; stdcall; // CALLBACK* TDXVAHDETW_CREATEVIDEOPROCESSOR = record pObject: ULONGLONG; pD3D9Ex: ULONGLONG; VPGuid: TGUID; end; TDXVAHDETW_VIDEOPROCESSBLTSTATE = record pObject: ULONGLONG; State: TDXVAHD_BLT_STATE; DataSize: UINT; SetState: boolean; end; TDXVAHDETW_VIDEOPROCESSSTREAMSTATE = record pObject: ULONGLONG; StreamNumber: UINT; State: TDXVAHD_STREAM_STATE; DataSize: UINT; SetState: boolean; end; TDXVAHDETW_VIDEOPROCESSBLTHD = record pObject: ULONGLONG; pOutputSurface: ULONGLONG; TargetRect: TRECT; OutputFormat: TD3DFORMAT; ColorSpace: UINT; OutputFrame: UINT; StreamCount: UINT; Enter: boolean; end; TDXVAHDETW_VIDEOPROCESSBLTHD_STREAM = record pObject: ULONGLONG; pInputSurface: ULONGLONG; SourceRect: TRECT; DestinationRect: TRECT; InputFormat: TD3DFORMAT; FrameFormat: TDXVAHD_FRAME_FORMAT; ColorSpace: UINT; StreamNumber: UINT; OutputIndex: UINT; InputFrameOrField: UINT; PastFrames: UINT; FutureFrames: UINT; end; TDXVAHDETW_DESTROYVIDEOPROCESSOR = record pObject: ULONGLONG; end; IDXVAHD_VideoProcessor = interface(IUnknown) ['{95f4edf4-6e03-4cd7-be1b-3075d665aa52}'] function SetVideoProcessBltState(State: TDXVAHD_BLT_STATE; DataSize: UINT; const pData: Pointer): HResult; stdcall; function GetVideoProcessBltState(State: TDXVAHD_BLT_STATE; DataSize: UINT; var pData: Pointer): HResult; stdcall; function SetVideoProcessStreamState(StreamNumber: UINT; State: TDXVAHD_STREAM_STATE; DataSize: UINT; const pData: Pointer): HResult; stdcall; function GetVideoProcessStreamState(StreamNumber: UINT; State: TDXVAHD_STREAM_STATE; DataSize: UINT; var pData: Pointer): HResult; stdcall; function VideoProcessBltHD(pOutputSurface: IDirect3DSurface9; OutputFrame: UINT; StreamCount: UINT; const pStreams: PDXVAHD_STREAM_DATA): HResult; stdcall; end; IDXVAHD_Device = interface(IUnknown) ['{95f12dfd-d77e-49be-815f-57d579634d6d}'] function CreateVideoSurface(Width: UINT; Height: UINT; Format: TD3DFORMAT; Pool: TD3DPOOL; Usage: DWORD; _Type: TDXVAHD_SURFACE_TYPE; NumSurfaces: UINT; out ppSurfaces: PIDirect3DSurface9; var pSharedHandle: THANDLE): HResult; stdcall; function GetVideoProcessorDeviceCaps( out pCaps: TDXVAHD_VPDEVCAPS): HResult; stdcall; function GetVideoProcessorOutputFormats(Count: UINT; out pFormats: PD3DFORMAT): HResult; stdcall; function GetVideoProcessorInputFormats(Count: UINT; out pFormats: PD3DFORMAT): HResult; stdcall; function GetVideoProcessorCaps(Count: UINT; out pCaps: PDXVAHD_VPCAPS): HResult; stdcall; function GetVideoProcessorCustomRates(const pVPGuid: TGUID; Count: UINT; out pRates: PDXVAHD_CUSTOM_RATE_DATA): HResult; stdcall; function GetVideoProcessorFilterRange(Filter: TDXVAHD_FILTER; out pRange: TDXVAHD_FILTER_RANGE_DATA): HResult; stdcall; function CreateVideoProcessor(const pVPGuid: TGUID; out ppVideoProcessor: IDXVAHD_VideoProcessor): HResult; stdcall; end; PDXVAHD_CreateDevice = function (pD3DDevice: IDirect3DDevice9Ex; const pContentDesc: TDXVAHD_CONTENT_DESC; Usage: TDXVAHD_DEVICE_USAGE; pPlugin: PDXVAHDSW_Plugin; out ppDevice: IDXVAHD_Device): HResult; stdcall; function DXVAHD_CreateDevice(pD3DDevice: IDirect3DDevice9Ex; const pContentDesc: TDXVAHD_CONTENT_DESC; Usage: TDXVAHD_DEVICE_USAGE; pPlugin: PDXVAHDSW_Plugin; out ppDevice: IDXVAHD_Device): HResult; stdcall; external DXVAHD_DLL; implementation end.
unit Scale; {$mode objfpc}{$H+} interface uses Classes, SysUtils, GraphMath; function WorldToScreen(APoint: TFloatPoint): TPoint; function ScreenToWorld(APoint: TPoint): TFloatPoint; procedure MaxMin(APoint: TFloatPoint); procedure RectZoom(AHeight, AWidth: extended; MinPoint, MaxPoint: TFloatPoint); function Scrn2Wrld(P: TPoint): TFloatPoint; var Zoom: double; Offset: TPoint; MinPoint, MaxPoint: TFloatPoint; AHeight, AWidth: extended; AHeightPB, AWidthPB: extended; implementation function Scrn2Wrld(P: TPoint): TFloatPoint; begin Result.X := (P.x + Offset.x) / Zoom * 100; Result.Y := (P.y + Offset.y) / Zoom * 100; end; procedure RectZoom(AHeight, AWidth: extended; MinPoint, MaxPoint: TFloatPoint); begin if (MaxPoint.X-MinPoint.X<>0) and (MaxPoint.Y-MinPoint.Y<>0) then begin if (Awidth/(abs(MaxPoint.X-MinPoint.X)))>(AHeight/(abs(MaxPoint.Y-MinPoint.Y)))then Zoom := 100*AHeight/(abs(MaxPoint.Y-MinPoint.Y)) else Zoom := 100*AWidth/(abs(MaxPoint.X-MinPoint.X)); If MinPoint.X<MaxPoint.X then Offset.x:=round(MinPoint.X*Zoom/100) else Offset.x:=round(MaxPoint.X*Zoom/100); If MinPoint.Y<MaxPoint.Y then Offset.y:=round(MinPoint.Y*Zoom/100) else Offset.Y:=round(MaxPoint.Y*Zoom/100) end; end; function WorldToScreen(APoint: TFloatPoint): TPoint; begin WorldToScreen.X:=round(APoint.X*Zoom/100)-Offset.x; WorldToScreen.y:=round(APoint.Y*Zoom/100)-Offset.y; end; function ScreenToWorld(APoint: TPoint): TFloatPoint; begin ScreenToWorld.X:=(APoint.x+Offset.x)/(Zoom/100); ScreenToWorld.Y:=(APoint.y+Offset.y)/(Zoom/100); end; procedure MaxMin(APoint: TFloatPoint); begin if (APoint.x > MaxPoint.x) then MaxPoint.x := APoint.x; if (APoint.y > MaxPoint.y) then MaxPoint.y := APoint.y; if (APoint.x < MinPoint.x) then MinPoint.x := APoint.x; if (APoint.y < MinPoint.y) then MinPoint.y := APoint.y; end; begin end.
unit UThreadManager; //------------------------------------------------------------------------------ // модуль реализует класс менеджера потоков //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, SyncObjs, ExtCtrls, UThreads, Ils.Logger; //------------------------------------------------------------------------------ //! запрос выполнения задачи //------------------------------------------------------------------------------ function TryExecuteThis( const AProc: TThCallback; const AError: TThError; const AData: Pointer ): Boolean; //------------------------------------------------------------------------------ //! завершение модуля //! должно вызываться из внешего источника ! //------------------------------------------------------------------------------ procedure FinalizeTMM(); //------------------------------------------------------------------------------ implementation type //------------------------------------------------------------------------------ //! информация о потоке //------------------------------------------------------------------------------ PMyThreadRec = ^TMyThreadRec; TMyThreadRec = record //! время последнего выполнения работы потоком LastTime: TDateTime; //! ссылка на класс потока Th: TThreadActivated; //! что выполняем CBProc: TThCallback; //! с чем выполняем CBData: Pointer; //! что выполняем если ошибка CBError: TThError; //! выполняет ли поток полезную работу InWork: Boolean; //! возникла ли ошибка выполнения WasError: Boolean; end; TMyThreadRecArray = array of TMyThreadRec; //------------------------------------------------------------------------------ //! фиктивный класс для процедуры таймера очистки холостых потоков //------------------------------------------------------------------------------ TTMMTimerDummy = class public class procedure IdleTimerTick( Sender: TObject ); end; //------------------------------------------------------------------------------ const //------------------------------------------------------------------------------ //! максимальное количество создаваемых потоков //------------------------------------------------------------------------------ CTMMaxThreads = 1500; //------------------------------------------------------------------------------ //! интервал очистки холостых потоков //------------------------------------------------------------------------------ CTMCleanUpInterval = 30000; // 30 секунд //------------------------------------------------------------------------------ //! сообщения //------------------------------------------------------------------------------ CTMCreateError: string = 'Не удалось создать новый поток:'#13#10'%s'; CTMLimitError: string = 'Достигнут лимит потоков, создание нового невозможно. (Max=%d)'; // CTMProcessError: string = 'Зафиксирована следующая ошибка во время выполнения потока:'#13#10'%s'; //------------------------------------------------------------------------------ var //------------------------------------------------------------------------------ //! список потоков //------------------------------------------------------------------------------ GTMMThreadsPool: TMyThreadRecArray; //------------------------------------------------------------------------------ //! блокировщик работы со списком //------------------------------------------------------------------------------ GTMMCritical: TCriticalSection; //------------------------------------------------------------------------------ //! таймер очистки холостых потоков //------------------------------------------------------------------------------ GTMMIdleTimer: TTimer; //------------------------------------------------------------------------------ //! флаг остановки модуля //------------------------------------------------------------------------------ GTMMEnded: Boolean; // = False //------------------------------------------------------------------------------ //! рабочая процедура потока //! выполняется в отдельном потоке //------------------------------------------------------------------------------ procedure ThWork( const AData: Pointer ); var //! типизированный AData This: PMyThreadRec; //------------------------------------------------------------------------------ begin This := AData; This^.CBProc(This^.CBData); This^.LastTime := Now(); This^.InWork := False; end; //------------------------------------------------------------------------------ //! процедура ошибки потока //! выполняется в отдельном потоке //------------------------------------------------------------------------------ procedure ThError( const AData: Pointer; var AException: Exception; const AThreadID: TThreadID ); var //! типизированный AData This: PMyThreadRec; //------------------------------------------------------------------------------ begin This := AData; // This^.LogRef.ErrorToLog(Format(CTMProcessError, [AException.Message])); This^.CBError(This^.CBData, AException, AThreadID); This^.WasError := True; end; //------------------------------------------------------------------------------ //! поиск свободного потока в списке //------------------------------------------------------------------------------ function FindIdleThread(): Integer; begin for Result := Low(GTMMThreadsPool) to High(GTMMThreadsPool) do begin if Assigned(GTMMThreadsPool[Result].Th) and (not GTMMThreadsPool[Result].InWork) then Exit; end; Result := -1; end; //------------------------------------------------------------------------------ //! поиск пустого места в списке для нового потока //------------------------------------------------------------------------------ function FindEmptySlot(): Integer; begin for Result := Low(GTMMThreadsPool) to High(GTMMThreadsPool) do begin if not Assigned(GTMMThreadsPool[Result].Th) then Exit; end; Result := -1; end; //------------------------------------------------------------------------------ //! запрос выполнения задачи //------------------------------------------------------------------------------ function TryExecuteThis( const AProc: TThCallback; const AError: TThError; const AData: Pointer ): Boolean; label A; var //! LRef: PMyThreadRec; //! LIndex: Integer; //------------------------------------------------------------------------------ begin Result := False; if GTMMEnded then Exit; // работаем GTMMCritical.Acquire(); try // ищем простаивающий поток LIndex := FindIdleThread(); if (LIndex <> -1) then begin // нашли простаивающий поток LRef := @GTMMThreadsPool[LIndex]; // простая ссылка A: LRef^.WasError := False; // нет ошибки LRef^.InWork := True; // в работе LRef^.CBProc := AProc; // что LRef^.CBData := AData; // с чем LRef^.CBError := AError; // если всё плохо LRef^.Th.Work(LRef); // вызов выполнения end else begin // не нашли простаивающий поток // ищем место для нового потока LIndex := FindEmptySlot(); if (LIndex <> -1) then begin // нашли место для нового потока LRef := @GTMMThreadsPool[LIndex]; // простая ссылка // создаём новый поток try LRef^.Th := TThreadActivated.Create(ThWork, ThError); except on Ex: Exception do begin ToLog(Format(CTMCreateError, [Ex.Message])); Exit; end; end; // всё остальное goto A; end else begin // не нашли место для нового потока ToLog(Format(CTMLimitError, [CTMMaxThreads])); Exit; end; end; finally GTMMCritical.Release(); end; Result := True; end; //------------------------------------------------------------------------------ //! процедура таймера очистки холостых потоков //------------------------------------------------------------------------------ class procedure TTMMTimerDummy.IdleTimerTick( Sender: TObject ); var //! I: Integer; //------------------------------------------------------------------------------ begin if GTMMEnded then Exit; GTMMCritical.Acquire(); try for I := Low(GTMMThreadsPool) to High(GTMMThreadsPool) do begin // очищаем остановившиеся при ошибках потоки if Assigned(GTMMThreadsPool[I].Th) and GTMMThreadsPool[I].Th.IsTerminated() then FreeAndNil(GTMMThreadsPool[I].Th); // завершаем потоки с возникшей внешней ошибкой if Assigned(GTMMThreadsPool[I].Th) and GTMMThreadsPool[I].WasError then FreeAndNil(GTMMThreadsPool[I].Th); // завершаем лишние не занятые работой потоки if Assigned(GTMMThreadsPool[I].Th) and (not GTMMThreadsPool[I].InWork) and (Now() - GTMMThreadsPool[I].LastTime > (CTMCleanUpInterval / 86400000)) then FreeAndNil(GTMMThreadsPool[I].Th); end; finally GTMMCritical.Release(); end; end; //------------------------------------------------------------------------------ //! начальная инициализация модуля //------------------------------------------------------------------------------ procedure InitTMM(); begin IsMultiThread := True; GTMMCritical := TCriticalSection.Create(); SetLength(GTMMThreadsPool, CTMMaxThreads); GTMMIdleTimer := TTimer.Create(nil); GTMMIdleTimer.Interval := CTMCleanUpInterval; GTMMIdleTimer.Enabled := True; GTMMIdleTimer.OnTimer := TTMMTimerDummy.IdleTimerTick; end; //------------------------------------------------------------------------------ //! завершение модуля //! должно вызываться из внешего источника !!! //------------------------------------------------------------------------------ procedure FinalizeTMM(); var //! I: Integer; //------------------------------------------------------------------------------ begin if GTMMEnded then Exit; GTMMEnded := True; FreeAndNil(GTMMIdleTimer); for I := Low(GTMMThreadsPool) to High(GTMMThreadsPool) do begin FreeAndNil(GTMMThreadsPool[I].Th); end; SetLength(GTMMThreadsPool, 0); FreeAndNil(GTMMCritical); end; //------------------------------------------------------------------------------ initialization InitTMM(); //------------------------------------------------------------------------------ finalization FinalizeTMM(); end.
unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls, Menus, ActnList, StdActns; type { TNewProxyServerForm } TNewProxyServerForm = class(TForm) CrtInput: TEdit; CrtLabel: TLabel; ServerNameInput: TEdit; KcpPwdInput: TEdit; KcpPwdLabel: TLabel; KeyInput: TEdit; KeyLabel: TLabel; Label15: TLabel; Label4: TLabel; PageControl1: TPageControl; ProxyTypeComboBox: TComboBox; SelectCrtAction: TAction; SelectCrtBtn: TButton; SelectKeyAction: TAction; SelectKeyBtn: TButton; SelectPrivateKeyAction: TAction; ActionList1: TActionList; ConfirmBtn: TButton; CancelBtn: TButton; GroupBox4: TGroupBox; ListView1: TListView; AddMapping: TMenuItem; ModifyMapping: TMenuItem; DelMapping: TMenuItem; SelectCrtDialog: TOpenDialog; SelectKeyDialog: TOpenDialog; SelectPrivateKeyBtn: TButton; SelectPrivateKeyDialog: TOpenDialog; PopupMenu1: TPopupMenu; LocalProtocolComboBox: TComboBox; DnsInput: TEdit; LocalPort: TEdit; Label13: TLabel; Label14: TLabel; LocalIp: TEdit; Label12: TLabel; SshKeyInput: TEdit; SshKeyLabel: TLabel; SshPwdInput: TEdit; SshPwdLabel: TLabel; SshUserNameInput: TEdit; SshUserNameLabel: TLabel; TlsPage: TTabSheet; SSHPage: TTabSheet; KcpPage: TTabSheet; TTLInput: TEdit; GroupBox2: TGroupBox; GroupBox3: TGroupBox; Label10: TLabel; Label11: TLabel; ServerProtocolComboBox: TComboBox; IpInput: TEdit; PortInput: TEdit; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure AddMappingClick(Sender: TObject); procedure DelMappingClick(Sender: TObject); procedure LocalProtocolComboBoxChange(Sender: TObject); procedure ModifyMappingClick(Sender: TObject); procedure ProxyTypeComboBoxChange(Sender: TObject); procedure SelectCrtActionExecute(Sender: TObject); procedure SelectCrtBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure ConfirmBtnClick(Sender: TObject); procedure SelectKeyActionExecute(Sender: TObject); procedure SelectPrivateKeyActionExecute(Sender: TObject); procedure ServerProtocolComboBoxChange(Sender: TObject); private public end; var NewProxyServerForm: TNewProxyServerForm; implementation {$R *.lfm} { TNewProxyServerForm } procedure TNewProxyServerForm.ConfirmBtnClick(Sender: TObject); begin end; procedure TNewProxyServerForm.SelectKeyActionExecute(Sender: TObject); begin end; procedure TNewProxyServerForm.SelectPrivateKeyActionExecute(Sender: TObject); begin end; procedure TNewProxyServerForm.ServerProtocolComboBoxChange(Sender: TObject); begin end; procedure TNewProxyServerForm.CancelBtnClick(Sender: TObject); begin end; procedure TNewProxyServerForm.SelectCrtBtnClick(Sender: TObject); begin end; procedure TNewProxyServerForm.SelectCrtActionExecute(Sender: TObject); begin end; procedure TNewProxyServerForm.ProxyTypeComboBoxChange(Sender: TObject); begin end; procedure TNewProxyServerForm.LocalProtocolComboBoxChange(Sender: TObject); begin end; procedure TNewProxyServerForm.ModifyMappingClick(Sender: TObject); begin end; procedure TNewProxyServerForm.AddMappingClick(Sender: TObject); begin end; procedure TNewProxyServerForm.DelMappingClick(Sender: TObject); begin end; end.
unit Base.View.Interf; interface uses Tipos.Controller.Interf; type IBasePesquisaView = interface ['{71221DC5-588B-42C9-9F1D-F2B7DF151D19}'] procedure listarRegistros; function incluirRegistro: IBasePesquisaView; function alterarRegistro: IBasePesquisaView; function consultarRegistro: IBasePesquisaView; function excluirRegistro: IBasePesquisaView; function duplicarRegistro: IBasePesquisaView; procedure &executar; end; IBaseCadastroView = interface ['{8EE97A85-684A-4960-A1B1-CC4949192F05}'] function operacao(AValue: TTipoOperacao): IBaseCadastroView; function registroSelecionado(AValue: string): IBaseCadastroView; procedure salvarDados; procedure exibirDadosNaTela; procedure desabilitaCampos; procedure &executar; end; IBaseImportarView = interface ['{5FF57410-57EC-4D79-948B-0227720BED55}'] procedure salvarDados; procedure importarArquivo; procedure &executar; end; IBaseMensagemView = interface ['{5D214805-B310-4B45-B616-E0B797B8F05B}'] function mensagem(AValue: string): IBaseMensagemView; function &exibir: Boolean; end; IBaseLocalizarView = interface ['{3E5D8E06-093C-4943-BC53-CE9C4740C56C}'] procedure listarRegistros; function exibir: string; end; implementation end.
namespace proholz.xsdparser; interface type XsdComplexTypeVisitor = public class(AttributesVisitor) private // * // * The {@link XsdComplexType} instance which owns this {@link XsdComplexTypeVisitor} instance. This way this visitor // * instance can perform changes in the {@link XsdComplexType} object. // // var owner: XsdComplexType; public constructor(aowner: XsdComplexType); method visit(element: XsdMultipleElements); override; method visit(element: XsdGroup); override; method visit(element: XsdComplexContent); override; method visit(element: XsdSimpleContent); override; end; implementation constructor XsdComplexTypeVisitor(aowner: XsdComplexType); begin inherited constructor(aowner); self.owner := aowner; end; method XsdComplexTypeVisitor.visit(element: XsdMultipleElements); begin inherited visit(element); owner.setChildElement(ReferenceBase.createFromXsd(element)); end; method XsdComplexTypeVisitor.visit(element: XsdGroup); begin inherited visit(element); owner.setChildElement(ReferenceBase.createFromXsd(element)); end; method XsdComplexTypeVisitor.visit(element: XsdComplexContent); begin inherited visit(element); owner.setComplexContent(element); end; method XsdComplexTypeVisitor.visit(element: XsdSimpleContent); begin inherited visit(element); owner.setSimpleContent(element); end; end.
unit Odontologia.Controlador.Empresa; interface uses Data.DB, System.SysUtils, System.Generics.Collections, Odontologia.Controlador.Ciudad, Odontologia.Controlador.Ciudad.Interfaces, Odontologia.Controlador.Empresa.Interfaces, Odontologia.Controlador.EmpresaTipo, Odontologia.Controlador.EmpresaTipo.Interfaces, Odontologia.Modelo, Odontologia.Modelo.Entidades.Empresa, Odontologia.Modelo.Empresa.Interfaces, Odontologia.Modelo.EmpresaTipo.Interfaces; type TControllerEmpresa = class(TInterfacedObject, iControllerEmpresa) private FModel : iModelEmpresa; FDataSource : TDataSource; FCiudad : iControllerCiudad; FEmpresaTipo : iControllerEmpresaTipo; procedure DataChange (sender : tobject ; field : Tfield) ; public constructor Create; destructor Destroy; override; class function New: iControllerEmpresa; function DataSource (aDataSource : TDataSource) : iControllerEmpresa; function Buscar : iControllerEmpresa; overload; function Buscar (aDepartamento : String) : iControllerEmpresa; overload; function Insertar : iControllerEmpresa; function Modificar : iControllerEmpresa; function Eliminar : iControllerEmpresa; function Entidad : TDEMPRESA; function Ciudad : iControllerCiudad; function EmpresaTipo : iControllerEmpresaTipo; end; implementation { TControllerEmpresa } function TControllerEmpresa.Buscar: iControllerEmpresa; begin Result := Self; FDataSource.dataset.DisableControls; FModel.DAO.SQL.Fields('DEMPRESA.EMP_CODIGO AS CODIGO,') .Fields('DEMPRESA.EMP_RAZSOCIAL AS RAZON,') .Fields('DEMPRESA.EMP_FANTASIA AS FANTASIA,') .Fields('DEMPRESA.EMP_RUC AS RUC,') .Fields('DEMPRESA.EMP_DIRECCION AS DIRECCION,') .Fields('DEMPRESA.EMP_NUMERO AS NUMERO,') .Fields('DEMPRESA.EMP_BARRIO AS BARRIO,') .Fields('DEMPRESA.EMP_TELEFONO AS TELEFONO,') .Fields('DEMPRESA.EMP_EMAIL AS EMAIL,') .Fields('DEMPRESA.EMP_COD_CIUDAD AS COD_CIU,') .Fields('DEMPRESA.EMP_COD_TIP_EMPRESA AS COD_EMP,') .Fields('DCIUDAD.CIU_NOMBRE AS CIUDAD') .Join('INNER JOIN DCIUDAD ON DCIUDAD.CIU_CODIGO = DEMPRESA.EMP_COD_CIUDAD ') .Where('') .OrderBy('RAZON') .&End.Find; FDataSource.dataset.EnableControls; FDataSource.dataset.FieldByName('CODIGO').Visible := false; FDataSource.dataset.FieldByName('RAZON').Visible := TRUE; FDataSource.dataset.FieldByName('FANTASIA').Visible := True; FDataSource.dataset.FieldByName('RUC').Visible := tRUE; FDataSource.dataset.FieldByName('DIRECCION').Visible := false; FDataSource.dataset.FieldByName('NUMERO').Visible := false; FDataSource.dataset.FieldByName('BARRIO').Visible := false; FDataSource.dataset.FieldByName('TELEFONO').Visible := True; FDataSource.dataset.FieldByName('EMAIL').Visible := True; FDataSource.dataset.FieldByName('COD_CIU').Visible := false; FDataSource.dataset.FieldByName('COD_EMP').Visible := FALSE; FDataSource.dataset.FieldByName('RAZON').DisplayWidth :=50; end; function TControllerEmpresa.Buscar(aDepartamento: String): iControllerEmpresa; begin Result := Self; FDataSource.dataset.DisableControls; FModel.DAO.SQL.Fields('DEMPRESA.EMP_CODIGO AS CODIGO,') .Fields('DEMPRESA.EMP_RAZSOCIAL AS RAZON,') .Fields('DEMPRESA.EMP_FANTASIA AS FANTASIA,') .Fields('DEMPRESA.EMP_RUC AS RUC,') .Fields('DEMPRESA.EMP_DIRECCION AS DIRECCION,') .Fields('DEMPRESA.EMP_NUMERO AS NUMERO,') .Fields('DEMPRESA.EMP_BARRIO AS BARRIO,') .Fields('DEMPRESA.EMP_TELEFONO AS TELEFONO,') .Fields('DEMPRESA.EMP_EMAIL AS EMAIL,') .Fields('DEMPRESA.EMP_COD_CIUDAD AS COD_CIU,') .Fields('DEMPRESA.EMP_COD_TIP_EMPRESA AS COD_EMP,') .Fields('DCIUDAD.CIU_NOMBRE AS CIUDAD') .Join('INNER JOIN DCIUDAD ON DCIUDAD.CIU_CODIGO = DEMPRESA.EMP_COD_CIUDAD ') .Where('DEMPRESA.EMP_RAZSOCIAL CONTAINING ' +QuotedStr(aDepartamento) + '') .OrderBy('RAZON') .&End.Find; FDataSource.dataset.EnableControls; FDataSource.dataset.FieldByName('CODIGO').Visible := false; FDataSource.dataset.FieldByName('RAZON').Visible := TRUE; FDataSource.dataset.FieldByName('FANTASIA').Visible := True; FDataSource.dataset.FieldByName('RUC').Visible := tRUE; FDataSource.dataset.FieldByName('DIRECCION').Visible := false; FDataSource.dataset.FieldByName('NUMERO').Visible := false; FDataSource.dataset.FieldByName('BARRIO').Visible := false; FDataSource.dataset.FieldByName('TELEFONO').Visible := True; FDataSource.dataset.FieldByName('EMAIL').Visible := True; FDataSource.dataset.FieldByName('COD_CIU').Visible := false; FDataSource.dataset.FieldByName('COD_EMP').Visible := FALSE; FDataSource.dataset.FieldByName('RAZON').DisplayWidth :=50; end; constructor TControllerEmpresa.Create; begin FModel := TModel.New.Empresa; FCiudad := TControllerCiudad.New; end; procedure TControllerEmpresa.DataChange(sender: tobject; field: Tfield); begin end; function TControllerEmpresa.DataSource(aDataSource: TDataSource) : iControllerEmpresa; begin Result := Self; FDataSource := aDataSource; FModel.DataSource(FDataSource); FDataSource.OnDataChange := DataChange; end; destructor TControllerEmpresa.Destroy; begin inherited; end; function TControllerEmpresa.Eliminar: iControllerEmpresa; begin Result := Self; FModel.DAO.Delete(FModel.Entidad); end; function TControllerEmpresa.EmpresaTipo: iControllerEmpresaTipo; begin Result := FEmpresaTipo; end; function TControllerEmpresa.Entidad: TDEMPRESA; begin Result := FModel.Entidad; end; function TControllerEmpresa.Insertar: iControllerEmpresa; begin Result := Self; FModel.DAO.Insert(FModel.Entidad); end; function TControllerEmpresa.Ciudad: iControllerCiudad; begin Result := FCiudad; end; function TControllerEmpresa.Modificar: iControllerEmpresa; begin Result := Self; FModel.DAO.Update(FModel.Entidad); end; class function TControllerEmpresa.New: iControllerEmpresa; begin Result := Self.Create; end; end.
unit Unidade_Forward_de_Classes; interface Uses Classes, SysUtils, DbTables; type //declaracao FORWARD da ClasseBase... TClasseBase = Class; TCalculateClass = class Private //campo interno do Tipo da Classebase... FClassBase : TClassebase; //campos internos manipuladores da Base e do Exponente... FBase : Extended; FExpoente : Integer; //--------------------------------- // Seção Privada à TOOPClass. // //--------------------------------- Protected function SetValue : Extended; //--------------------------------- // Seção Protegida // //--------------------------------- Public constructor Create; destructor Destroy; override; //--------------------------------- // Seção Publica // //--------------------------------- Published property Base : Extended read FBase write FBase; property Expoente : Integer read FExpoente write FExpoente; property ResutlValue : Extended read SetValue; //--------------------------------- // Seção Publicada // //--------------------------------- end;// TClasseBase = Class Private //--------------------------------- // Seção Privada à TOOPClass. // //--------------------------------- Protected function ResultPowerEx(const Base: Extended; Expoente: Integer): Extended; //--------------------------------- // Seção Protegida // //--------------------------------- Public constructor Create(AOwner : TObject); reintroduce; destructor Destroy; override; //--------------------------------- // Seção Publica // //--------------------------------- Published //--------------------------------- // Seção Publicada // //--------------------------------- end;// implementation { TClasseBase } //*******************************************************************// // METODO : Create // // AUTOR, DATA : Roberto, 28/10/2002 // // DESCRIÇÃO : instanciar novos objetos e/ou iniciar valores.... // //*******************************************************************// constructor TClasseBase.Create(AOwner : TObject); begin end; //*******************************************************************// // METODO : Destroy // // AUTOR, DATA : Roberto, 28/10/2002 // // DESCRIÇÃO : Liberar um objeto instanciado e/ou reinicalizar valor.// //*******************************************************************// destructor TClasseBase.Destroy; begin end; //*******************************************************************// // METODO : ResultPowerEx // // AUTOR, DATA : Roberto, 28/10/2002 // // DESCRIÇÃO : Calcular o Exponencial de um Numero... // //*******************************************************************// function TClasseBase.ResultPowerEx(const Base: Extended; Expoente: Integer): Extended; var Index : integer; exBase : Extended; begin //pegamos a base passada como parametro... exBase := 1; //caso o Exponente seja... case Expoente of //Zero(0) entao Resulte 1. 0 : begin Result := 1; //sai. Exit; end;// end;//case-of. //precorre de q ate o valor do expoente... for index := 1 to Expoente do //calculando a base exBase := exBase * Base; //resultando o valor calculado. Result := exBase; end; { TCalculateClass } constructor TCalculateClass.Create; begin FClassBase := TClasseBase.Create(Self); end; destructor TCalculateClass.Destroy; begin //liberando a Classe Base que se tornou Filha de TCalculateClass... FClassBase.Free; end; //*******************************************************************// // METODO : SetValue // // AUTOR, DATA : Roberto, 28/10/2002 // // DESCRIÇÃO : Setar a propriedade ResultValue.... // //*******************************************************************// function TCalculateClass.SetValue : Extended; begin //se temos as propriedades preenchidas entao... if (Base <> 0) and (Expoente <> 0) then //calculamos o valor do Exponencial... Result := FClassBase.ResultPowerEx(Base, Expoente) else raise Exception.Create('Não Podemos continuar com o Cálculo.'+#13+#10+ 'Para isso preencha as propriedades Base e Expoente...'); end; end.
unit uFrmAddItemCommission; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, Buttons, Mask, SuperComboADO, DB, ADODB, PowerADOQuery, uFrmPOSFunctions; const SCREEN_TYPE_PRESALE = 0; SCREEN_TYPE_INVOICE = 1; SCREEN_TYPE_START_PRESALE = 3; type TFrmAddItemCommission = class(TFrmParent) lbSalesPerson: TListBox; cmbSalesPerson: TSuperComboADO; Label7: TLabel; edPercent: TEdit; quSalesPerson: TPowerADOQuery; dsSalesPerson: TDataSource; quSalesPersonPessoa: TStringField; quSalesPersonIDPessoa: TIntegerField; quSalesPersonCommissionPercent: TBCDField; quName: TADODataSet; quNamePessoa: TStringField; lbPercent: TLabel; btRemove: TBitBtn; btAdd: TBitBtn; btApplyAll: TSpeedButton; btOK: TButton; procedure btAddClick(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure quSalesPersonAfterOpen(DataSet: TDataSet); procedure btCloseClick(Sender: TObject); procedure edPercentKeyPress(Sender: TObject; var Key: Char); procedure btOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private FScreenType : Integer; procedure AddCommisList; function AddItem(IDSalesPerson: String; Percent: Real): Boolean; function GetName(ID: String): String; function VerifyLimitPercentage(Percent: Real): Boolean; function VerifyPercentage: Boolean; function VerifyExactlySalesPerson(IDSalesPerson: String):Boolean; function GetPercentRemain: String; public SalesPerson: TSalesPerson; MyIDPreInventoryMov: Integer; procedure Start(iScreenType: Integer; var AApplyAll: Boolean); end; implementation uses uDM, uMsgBox, uCharFunctions, uMsgConstant; {$R *.dfm} function TFrmAddItemCommission.AddItem(IDSalesPerson: String; Percent:Real): Boolean; var Name : String; begin Result := False; if (lbSalesPerson.Items.IndexOf(IDSalesPerson)=-1) then begin SalesPerson := TSalesPerson.Create; SalesPerson.IDPessoa := StrtoInt(IDSalesPerson); SalesPerson.Pessoa := GetName(IDSalesPerson); SalesPerson.Percent := Percent; DM.fPOS.fCommisList.AddObject(SalesPerson.Pessoa + ' - ' + FloattoStr(SalesPerson.Percent) + '%',SalesPerson); lbSalesPerson.Items.AddObject(SalesPerson.Pessoa + ' - ' + FloattoStr(SalesPerson.Percent) + '%',SalesPerson); Result := True; end; end; procedure TFrmAddItemCommission.btAddClick(Sender: TObject); var test : string; begin if (edPercent.Text <> '') and (edPercent.Text <> '0') and (cmbSalesPerson.LookUpValue <> '') then begin if not VerifyLimitPercentage(StrToFloat(edPercent.Text)) then begin MsgBox(MSG_INF_INV_TOT_COMMIS_PERCENT, vbOKOnly + vbInformation); Exit; end; if not VerifyExactlySalesPerson(cmbSalesPerson.LookUpValue) then begin MsgBox(MSG_INF_EXAC_SALESPERSON_COMMIS, vbOKOnly + vbInformation); Exit; end; if Additem(cmbSalesPerson.LookUpValue,StrtoFloat(edPercent.Text)) then begin edPercent.Clear; edPercent.SetFocus; end; edPercent.Text := GetPercentRemain; end; end; procedure TFrmAddItemCommission.btRemoveClick(Sender: TObject); var Friend, Friend2: TSalesPerson; begin if lbSalesPerson.ItemIndex >= 0 then begin Friend := TSalesPerson(lbSalesPerson.Items.Objects[lbSalesPerson.ItemIndex]); if Friend <> Nil then Friend.Free; DM.fPOS.fCommisList.Delete(lbSalesPerson.ItemIndex); lbSalesPerson.DeleteSelected; edPercent.Text := GetPercentRemain; end; end; procedure TFrmAddItemCommission.Start(iScreenType: Integer; var AApplyAll: Boolean); var SalesPerson: TSalesPerson; begin FScreenType := iScreenType; btApplyAll.Visible := FScreenType = SCREEN_TYPE_INVOICE; if FScreenType = SCREEN_TYPE_START_PRESALE then begin cmbSalesPerson.LookUpValue := ''; cmbSalesPerson.LookUpValue := IntToStr(DM.fUser.IDCommission); edPercent.Text := '100'; lbSalesPerson.Clear; DM.fPOS.ClearCommissionList; end else begin if DM.fPOS.fCommisList <> nil then begin if DM.fPOS.fCommisList.Count > 1 then AddCommisList else DM.fPOS.ClearCommissionList; end; cmbSalesPerson.LookUpValue := ''; edPercent.Text := GetPercentRemain; lbSalesPerson.Items := DM.fPOS.fCommisList; end; ShowModal; AApplyAll := btApplyAll.Down; end; procedure TFrmAddItemCommission.quSalesPersonAfterOpen(DataSet: TDataSet); begin lbSalesPerson.Items.Clear; lbSalesPerson.Items.DelimitedText := quSalesPersonPessoa.AsString + ':' + quSalesPersonCommissionPercent.AsString; edPercent.Text := ''; end; function TFrmAddItemCommission.GetName(ID: String): String; begin with quName do begin if Active then Close; Parameters.ParamByName('IDPessoa').Value := StrtoInt(ID); Open; end; Result := quNamePessoa.AsString; end; procedure TFrmAddItemCommission.btCloseClick(Sender: TObject); begin DM.fPOS.ClearCommissionList; Close; end; function TFrmAddItemCommission.VerifyLimitPercentage(Percent: Real): Boolean; var i: Integer; TotalPercent: Real; begin Result := False; TotalPercent := Percent; for i := 0 to lbSalesPerson.Items.Count - 1 do TotalPercent := TSalesPerson(lbSalesPerson.Items.Objects[I]).Percent + TotalPercent; if TotalPercent <= 100 then Result := True; end; procedure TFrmAddItemCommission.edPercentKeyPress(Sender: TObject; var Key: Char); begin Key := ValidateNumbers(Key); end; procedure TFrmAddItemCommission.AddCommisList; var i: Integer; begin lbSalesPerson.Clear; for i:=0 to DM.fPOS.fCommisList.Count - 1 do begin SalesPerson := TSalesPerson.Create; SalesPerson.IDPessoa := TSalesPerson(DM.fPOS.fCommisList.Objects[I]).IDPessoa; SalesPerson.Pessoa := TSalesPerson(DM.fPOS.fCommisList.Objects[I]).Pessoa; SalesPerson.Percent := TSalesPerson(DM.fPOS.fCommisList.Objects[I]).Percent; lbSalesPerson.Items.AddObject(SalesPerson.Pessoa + ' - ' + FloattoStr(SalesPerson.Percent) + '%',SalesPerson); end; end; function TFrmAddItemCommission.VerifyPercentage: Boolean; var i: Integer; TotalPercent: Real; begin Result := False; TotalPercent := 0; for i := 0 to lbSalesPerson.Items.Count - 1 do TotalPercent := TSalesPerson(lbSalesPerson.Items.Objects[I]).Percent + TotalPercent; Result := TotalPercent = 100; end; procedure TFrmAddItemCommission.btOKClick(Sender: TObject); begin if (FScreenType = SCREEN_TYPE_START_PRESALE) and ((edPercent.Text = '100') and (lbSalesPerson.Items.Count = 0) and (cmbSalesPerson.LookUpValue = IntToStr(DM.fUser.IDCommission))) then AddItem(cmbSalesPerson.LookUpValue,StrtoFloat(edPercent.Text)); if (VerifyPercentage) then ModalResult := mrOk else MsgBox(MSG_INF_INV_TOT_COMMIS_PERCENT, vbOKOnly + vbInformation); end; function TFrmAddItemCommission.VerifyExactlySalesPerson(IDSalesPerson: String): Boolean; var i: Integer; begin Result := True; for i := 0 to lbSalesPerson.Items.Count - 1 do if TSalesPerson(lbSalesPerson.Items.Objects[I]).IDPessoa = StrtoInt(IDSalesPerson) then Result := False; end; function TFrmAddItemCommission.GetPercentRemain: String; var i: Integer; PercentRemain: Real; begin PercentRemain := 0; for i := 0 to lbSalesPerson.Items.Count - 1 do PercentRemain := TSalesPerson(lbSalesPerson.Items.Objects[I]).Percent + PercentRemain; Result := FloattoStr(100 - PercentRemain); end; procedure TFrmAddItemCommission.FormShow(Sender: TObject); begin inherited; cmbSalesPerson.SetFocus; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [VIEW_COMPRA_MAPA_COMPARATIVO] The MIT License Copyright: Copyright (C) 2015 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 ViewCompraMapaComparativoController; interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, ViewCompraMapaComparativoVO, CompraCotacaoVO, CompraPedidoVO, CompraPedidoDetalheVO, CompraCotacaoPedidoDetalheVO, CompraCotacaoDetalheVO; type TViewCompraMapaComparativoController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaViewCompraMapaComparativoVO; class function ConsultaObjeto(pFiltro: String): TViewCompraMapaComparativoVO; class procedure Insere(pObjeto: TViewCompraMapaComparativoVO); class function Altera(pObjeto: TViewCompraMapaComparativoVO): Boolean; class function GerarPedidos(pObjeto: TCompraCotacaoVO): Boolean; end; implementation uses UDataModule, T2TiORM; var ObjetoLocal: TViewCompraMapaComparativoVO; class function TViewCompraMapaComparativoController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TViewCompraMapaComparativoVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TViewCompraMapaComparativoController.ConsultaLista(pFiltro: String): TListaViewCompraMapaComparativoVO; begin try ObjetoLocal := TViewCompraMapaComparativoVO.Create; Result := TListaViewCompraMapaComparativoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TViewCompraMapaComparativoController.ConsultaObjeto(pFiltro: String): TViewCompraMapaComparativoVO; begin try Result := TViewCompraMapaComparativoVO.Create; Result := TViewCompraMapaComparativoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); finally end; end; class procedure TViewCompraMapaComparativoController.Insere(pObjeto: TViewCompraMapaComparativoVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TViewCompraMapaComparativoController.Altera(pObjeto: TViewCompraMapaComparativoVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TViewCompraMapaComparativoController.GerarPedidos(pObjeto: TCompraCotacaoVO): Boolean; var UltimoID: Integer; i, j: Integer; FornecedorAtual: Integer; // objViewCompraMapaComparativo: TViewCompraMapaComparativoVO; // CompraCotacao: TCompraCotacaoVO; CompraPedido: TCompraPedidoVO; CompraPedidoDetalhe: TCompraPedidoDetalheVO; CompraCotacaoPedidoDetalhe: TCompraCotacaoPedidoDetalheVO; CompraCotacaoDetalhe: TCompraCotacaoDetalheVO; begin try for i := 0 to pObjeto.ListaMapaComparativo.Count - 1 do begin objViewCompraMapaComparativo := pObjeto.ListaMapaComparativo[i]; /// EXERCICIO: Um novo pedido é sempre criado. E se já existir um pedido para esse fornecedor referente a essa cotação? Corrija isso! CompraPedido := TCompraPedidoVO.Create; CompraPedido.ListaCompraPedidoDetalheVO := TListaCompraPedidoDetalheVO.Create; CompraPedido.ListaCompraCotacaoPedidoDetalheVO := TListaCompraCotacaoPedidoDetalheVO.Create; // Pedido vindo de cotação sempre será marcado como Normal CompraPedido.IdCompraTipoPedido := 1; CompraPedido.IdFornecedor := objViewCompraMapaComparativo.IdFornecedor; CompraPedido.DataPedido := Now; // Insere o item no pedido CompraPedidoDetalhe := TCompraPedidoDetalheVO.Create; CompraPedidoDetalhe.IdProduto := objViewCompraMapaComparativo.IdProduto; CompraPedidoDetalhe.Quantidade := objViewCompraMapaComparativo.QuantidadePedida; CompraPedidoDetalhe.ValorUnitario := objViewCompraMapaComparativo.ValorUnitario; CompraPedidoDetalhe.ValorSubtotal := objViewCompraMapaComparativo.ValorSubtotal; CompraPedidoDetalhe.TaxaDesconto := objViewCompraMapaComparativo.TaxaDesconto; CompraPedidoDetalhe.ValorDesconto := objViewCompraMapaComparativo.ValorDesconto; CompraPedidoDetalhe.ValorTotal := objViewCompraMapaComparativo.ValorTotal; CompraPedido.ListaCompraPedidoDetalheVO.Add(CompraPedidoDetalhe); // Insere o item da cotação que foi utilizado no pedido CompraCotacaoPedidoDetalhe := TCompraCotacaoPedidoDetalheVO.Create; CompraCotacaoPedidoDetalhe.IdCompraCotacaoDetalhe := objViewCompraMapaComparativo.IdCompraCotacaoDetalhe; CompraCotacaoPedidoDetalhe.QuantidadePedida := objViewCompraMapaComparativo.QuantidadePedida; CompraPedido.ListaCompraCotacaoPedidoDetalheVO.Add(CompraCotacaoPedidoDetalhe); // Insere o Pedido UltimoID := TT2TiORM.Inserir(CompraPedido); // Insere os itens do pedido no banco de dados for j := 0 to CompraPedido.ListaCompraPedidoDetalheVO.Count - 1 do begin CompraPedidoDetalhe := CompraPedido.ListaCompraPedidoDetalheVO[j]; CompraPedidoDetalhe.IdCompraPedido := UltimoID; TT2TiORM.Inserir(CompraPedidoDetalhe); end; // Insere os items em COMPRA_COTACAO_PEDIDO_DETALHE for j := 0 to CompraPedido.ListaCompraCotacaoPedidoDetalheVO.Count - 1 do begin CompraCotacaoPedidoDetalhe := CompraPedido.ListaCompraCotacaoPedidoDetalheVO[j]; CompraCotacaoPedidoDetalhe.IdCompraPedido := UltimoID; TT2TiORM.Inserir(CompraCotacaoPedidoDetalhe); end; // Atualiza o detalhe da cotação no banco de dados CompraCotacaoDetalhe := TCompraCotacaoDetalheVO.Create; CompraCotacaoDetalhe.Id := objViewCompraMapaComparativo.IdCompraCotacaoDetalhe; CompraCotacaoDetalhe.QuantidadePedida := objViewCompraMapaComparativo.QuantidadePedida; TT2TiORM.Alterar(CompraCotacaoDetalhe); end; // Atualiza o campo SITUACAO da cotação para F - Fechada CompraCotacao := TCompraCotacaoVO.Create; CompraCotacao.Id := objViewCompraMapaComparativo.IdCompraCotacao; CompraCotacao.Situacao := 'F'; Result := TT2TiORM.Alterar(CompraCotacao); finally end; end; initialization Classes.RegisterClass(TViewCompraMapaComparativoController); finalization Classes.UnRegisterClass(TViewCompraMapaComparativoController); end.
unit UIniEx; //------------------------------------------------------------------------------ // модуль расширения стандартного TIniFile //------------------------------------------------------------------------------ // теперь функции чтения не только читают, но и записывают обратно // значения по умолчанию, если изначально их там не было //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, IniFiles, Ils.Utils; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! //------------------------------------------------------------------------------ TIniFileEx = class(TIniFile) public function ReadString( const Section, Ident, Default: string ): string; override; function ReadInteger( const Section, Ident: string; Default: Longint ): Longint; override; function ReadBool( const Section, Ident: string; Default: Boolean ): Boolean; override; function ReadILSDateTime( const Section, Ident: string; const Default: TDateTime ): TDateTime; virtual; function ReadOnlyILSDateTime( const Section, Ident: string; const Default: TDateTime ): TDateTime; procedure WriteILSDateTime( const Section, Ident: string; const Value: TDateTime ); virtual; end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ // TIniFileEx //------------------------------------------------------------------------------ function TIniFileEx.ReadString( const Section, Ident, Default: string ): string; begin Result := inherited ReadString(Section, Ident, Default); if (Result = Default) then begin try WriteString(Section, Ident, Default); except // не бросаем исключения на чтении end; end; end; function TIniFileEx.ReadInteger( const Section, Ident: string; Default: Longint ): Longint; begin Result := inherited ReadInteger(Section, Ident, Default); if (Result = Default) then begin try WriteInteger(Section, Ident, Default); except // не бросаем исключения на чтении end; end; end; function TIniFileEx.ReadBool( const Section, Ident: string; Default: Boolean ): Boolean; begin Result := inherited ReadBool(Section, Ident, Default); if (Result = Default) then begin try WriteBool(Section, Ident, Default); except // не бросаем исключения на чтении end; end; end; function TIniFileEx.ReadILSDateTime( const Section, Ident: string; const Default: TDateTime ): TDateTime; begin Result := ReadOnlyILSDateTime(Section, Ident, Default); if (Result = Default) then begin try WriteILSDateTime(Section, Ident, Default); except // не бросаем исключения на чтении end; end; end; function TIniFileEx.ReadOnlyILSDateTime( const Section, Ident: string; const Default: TDateTime ): TDateTime; begin Result := IlsToDateTime(inherited ReadString(Section, Ident, ''), Default); end; procedure TIniFileEx.WriteILSDateTime( const Section, Ident: string; const Value: TDateTime ); begin WriteString(Section, Ident, DateTimeToIls(Value)); end; end.
unit illUsb; interface uses Windows, Messages, UnitDiversos; type { Event Types } TOnUsbChangeEvent = procedure(AObject : TObject; ADriverName: string) of object; { USB Class } TUsbClass = class(TObject) private FHandle : HWND; FOnUsbRemoval, FOnUsbInsertion : TOnUsbChangeEvent; procedure WinMethod(var AMessage : TMessage); procedure WMDeviceChange(var Msg : TMessage); public constructor Create; destructor Destroy; override; property OnUsbInsertion : TOnUsbChangeEvent read FOnUsbInsertion write FOnUsbInsertion; property OnUsbRemoval : TOnUsbChangeEvent read FOnUsbRemoval write FOnUsbRemoval; end; // ----------------------------------------------------------------------------- implementation // Device constants const DBT_DEVICEARRIVAL = $00008000; DBT_DEVICEREMOVECOMPLETE = $00008004; DBT_DEVTYP_VOLUME = $00000002; // Device structs type _DEV_BROADCAST_HDR = packed record dbch_size: DWORD; dbch_devicetype: DWORD; dbch_reserved: DWORD; end; DEV_BROADCAST_HDR = _DEV_BROADCAST_HDR; TDevBroadcastHeader = DEV_BROADCAST_HDR; PDevBroadcastHeader = ^TDevBroadcastHeader; type _DEV_BROADCAST_VOLUME = packed record dbch_size: DWORD; dbch_devicetype: DWORD; dbch_reserved: DWORD; dbcv_unitmask: DWORD; dbcv_flags: WORD; end; DEV_BROADCAST_VOLUME = _DEV_BROADCAST_VOLUME; TDevBroadcastVolume = DEV_BROADCAST_VOLUME; PDevBroadcastVolume = ^TDevBroadcastVolume; type TWndMethod = procedure(var Message: TMessage) of object; var UtilWindowClass: TWndClass = ( style: 0; lpfnWndProc: @DefWindowProc; cbClsExtra: 0; cbWndExtra: 0; hInstance: 0; hIcon: 0; hCursor: 0; hbrBackground: 0; lpszMenuName: nil; lpszClassName: 'TPUtilWindow'); const InstanceCount = 313; { Object instance management } type PObjectInstance = ^TObjectInstance; TObjectInstance = packed record Code: Byte; Offset: Integer; case Integer of 0: (Next: PObjectInstance); 1: (Method: TWndMethod); end; type PInstanceBlock = ^TInstanceBlock; TInstanceBlock = packed record Next: PInstanceBlock; Code: array[1..2] of Byte; WndProcPtr: Pointer; Instances: array[0..InstanceCount] of TObjectInstance; end; var InstBlockList: PInstanceBlock; InstFreeList: PObjectInstance; function CalcJmpOffset(Src, Dest: Pointer): Longint; begin Result := Longint(Dest) - (Longint(Src) + 5); end; function StdWndProc(Window: HWND; Message, WParam: Longint; LParam: Longint): Longint; stdcall; assembler; asm XOR EAX,EAX PUSH EAX PUSH LParam PUSH WParam PUSH Message MOV EDX,ESP MOV EAX,[ECX].Longint[4] CALL [ECX].Pointer ADD ESP,12 POP EAX end; function MakeObjectInstance(Method: TWndMethod): Pointer; const BlockCode: array[1..2] of Byte = ( $59, { POP ECX } $E9); { JMP StdWndProc } PageSize = 4096; var Block: PInstanceBlock; Instance: PObjectInstance; begin if InstFreeList = nil then begin Block := VirtualAlloc(nil, PageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Block^.Next := InstBlockList; Move(BlockCode, Block^.Code, SizeOf(BlockCode)); Block^.WndProcPtr := Pointer(CalcJmpOffset(@Block^.Code[2], @StdWndProc)); Instance := @Block^.Instances; repeat Instance^.Code := $E8; { CALL NEAR PTR Offset } Instance^.Offset := CalcJmpOffset(Instance, @Block^.Code); Instance^.Next := InstFreeList; InstFreeList := Instance; Inc(Longint(Instance), SizeOf(TObjectInstance)); until Longint(Instance) - Longint(Block) >= SizeOf(TInstanceBlock); InstBlockList := Block; end; Result := InstFreeList; Instance := InstFreeList; InstFreeList := Instance^.Next; Instance^.Method := Method; end; function AllocateHWnd(Method: TWndMethod): HWND; var TempClass: TWndClass; ClassRegistered: Boolean; begin UtilWindowClass.hInstance := HInstance; {$IFDEF PIC} UtilWindowClass.lpfnWndProc := @DefWindowProc; {$ENDIF} ClassRegistered := GetClassInfo(HInstance, UtilWindowClass.lpszClassName, TempClass); if not ClassRegistered or (TempClass.lpfnWndProc <> @DefWindowProc) then begin if ClassRegistered then Windows.UnregisterClass(UtilWindowClass.lpszClassName, HInstance); Windows.RegisterClass(UtilWindowClass); end; Result := CreateWindowEx(WS_EX_TOOLWINDOW, UtilWindowClass.lpszClassName, '', WS_POPUP {!0}, 0, 0, 0, 0, 0, 0, HInstance, nil); if Assigned(Method) then SetWindowLong(Result, GWL_WNDPROC, Longint(MakeObjectInstance(Method))); end; procedure FreeObjectInstance(ObjectInstance: Pointer); begin if ObjectInstance <> nil then begin PObjectInstance(ObjectInstance)^.Next := InstFreeList; InstFreeList := ObjectInstance; end; end; procedure DeallocateHWnd(Wnd: HWND); var Instance: Pointer; begin Instance := Pointer(GetWindowLong(Wnd, GWL_WNDPROC)); DestroyWindow(Wnd); if Instance <> @DefWindowProc then FreeObjectInstance(Instance); end; constructor TUsbClass.Create; begin inherited Create; FHandle := AllocateHWnd(WinMethod); end; destructor TUsbClass.Destroy; begin DeallocateHWnd(FHandle); inherited Destroy; end; procedure TUsbClass.WMDeviceChange(var Msg : TMessage); var lpdbhHeader: PDevBroadcastHeader; lpdbvData: PDevBroadcastVolume; dwIndex: Integer; lpszDrive: String; begin // Get the device notification header lpdbhHeader:=PDevBroadcastHeader(Msg.lParam); case Msg.WParam of DBT_DEVICEARRIVAL : {a USB drive was connected} begin if (lpdbhHeader^.dbch_devicetype = DBT_DEVTYP_VOLUME) then begin lpdbvData:=PDevBroadcastVolume(Msg.lParam); for dwIndex :=0 to 25 do begin if ((lpdbvData^.dbcv_unitmask shr dwIndex) = 1) then begin lpszDrive := Chr(65 + dwIndex) + ':\'; break; end; end; if Assigned(FOnUsbInsertion) then FOnUsbInsertion(self, lpszDrive); end; end; DBT_DEVICEREMOVECOMPLETE: {a USB drive was removed} begin if (lpdbhHeader^.dbch_devicetype = DBT_DEVTYP_VOLUME) then begin lpdbvData:=PDevBroadcastVolume(Msg.lParam); for dwIndex:=0 to 25 do begin if ((lpdbvData^.dbcv_unitmask shr dwIndex) = 1) then begin lpszDrive := Chr(65 + dwIndex) + ':\'; break; end; end; if Assigned(FOnUsbRemoval) then FOnUsbRemoval(self, lpszDrive); end; end; end; end; procedure TUsbClass.WinMethod(var AMessage : TMessage); begin if (AMessage.Msg = WM_DEVICECHANGE) then WMDeviceChange(AMessage) else AMessage.Result := DefWindowProc(FHandle,AMessage.Msg, AMessage.wParam,AMessage.lParam); end; end.
unit gui; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, GLScene, GLObjects, GLWin32Viewer, GLMaterial, GLTexture, GLKeyboard, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLGraph; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLDummyCube1: TGLDummyCube; GLCamera1: TGLCamera; GLMaterialLibrary1: TGLMaterialLibrary; Image1: TImage; GLLightSource1: TGLLightSource; Timer1: TTimer; GLXYZGrid1: TGLXYZGrid; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); private procedure Loadstars; procedure Checkstars; public end; const numberstars = 255; fieldsize = 100; halffieldsize = 50; var Form1: TForm1; vx, vy: Integer; StarField: array [0 .. numberstars] of TObject; implementation {$R *.dfm} procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin vx := X; vy := Y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Shift <> [ssLeft] then exit; GLCamera1.MoveAroundTarget(vy - Y, vx - X); vx := X; vy := Y; end; procedure TForm1.Loadstars; var X: Integer; begin for X := 0 to numberstars do StarField[X] := GLScene1.Objects.AddNewChild(TGLSprite); Randomize; for X := 0 to numberstars do with (StarField[X] as TGLSprite) do begin Position.X := Random(fieldsize) - halffieldsize; Position.Y := Random(fieldsize) - halffieldsize; Position.Z := Random(fieldsize) - halffieldsize; Material := Form1.GLMaterialLibrary1.Materials.Items[0].Material; end; end; procedure TForm1.Checkstars; var X: Integer; begin for X := 0 to numberstars do with (StarField[X] as TGLSprite) do begin if abs(Position.X - GLDummyCube1.Position.X) > halffieldsize then Position.X := Position.X - 2 * (Position.X - GLDummyCube1.Position.X); if abs(Position.Y - GLDummyCube1.Position.Y) > halffieldsize then Position.Y := Position.Y - 2 * (Position.Y - GLDummyCube1.Position.Y); if abs(Position.Z - GLDummyCube1.Position.Z) > halffieldsize then Position.Z := Position.Z - 2 * (Position.Z - GLDummyCube1.Position.Z); end; end; procedure TForm1.FormCreate(Sender: TObject); begin Image1.Picture.LoadFromFile('star.bmp'); GLMaterialLibrary1.Materials[0].Material.Texture.Image.Assign(Image1.Picture); loadstars; end; procedure TForm1.Timer1Timer(Sender: TObject); begin if IsKeyDown(38) then begin GLDummyCube1.Position.X := GLDummyCube1.Position.X + GLSceneViewer1.Buffer.ScreenToVector(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2).X; GLDummyCube1.Position.Y := GLDummyCube1.Position.Y + GLSceneViewer1.Buffer.ScreenToVector(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2).Y; GLDummyCube1.Position.Z := GLDummyCube1.Position.Z + GLSceneViewer1.Buffer.ScreenToVector(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2).Z; end else if IsKeyDown(40) then begin GLDummyCube1.Position.X := GLDummyCube1.Position.X - GLSceneViewer1.Buffer.ScreenToVector(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2).X; GLDummyCube1.Position.Y := GLDummyCube1.Position.Y - GLSceneViewer1.Buffer.ScreenToVector(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2).Y; GLDummyCube1.Position.Z := GLDummyCube1.Position.Z - GLSceneViewer1.Buffer.ScreenToVector(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2).Z; end; checkstars; end; end.
{ Laz-Model Copyright (C) 2016 Peter Dyson. Initial Lazarus port Portions (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit ufpcIntegrator; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uIntegrator, uModel, ufpcParser, uCodeProvider, uCodeParser, uError; type TfpciImporter = class(TImportIntegrator) private // Implementation of parser callback to retrieve a named package function NeedPackageHandler(const AName: string; var AStream: TStream; OnlyLookUp: Boolean = True):String; public procedure ImportOneFile(const FileName : string); override; class function GetFileExtensions : TStringList; override; end; implementation procedure TfpciImporter.ImportOneFile(const FileName : string); var Parser: TfpcParser; GlobalDefines : TStringList; begin GlobalDefines := TStringList.Create; {$ifdef WIN32} ////FPCTODO sort this properly for fpc GlobalDefines.Add('MSWINDOWS'); GlobalDefines.Add('WIN32'); {$endif} {$ifdef LINUX} GlobalDefines.Add('LINUX'); {$endif} Parser := TfpcParser.Create; try Parser.Filename := FileName; Parser.NeedPackage := @NeedPackageHandler; // Parser.ParseStreamWithDefines(Str, Model.ModelRoot, Model, GlobalDefines); Parser.ParseFileWithDefines(Model.ModelRoot, Model, GlobalDefines); finally Parser.Free; GlobalDefines.Free; end; end; class function TfpciImporter.GetFileExtensions: TStringList; begin Result := TStringList.Create; Result.Values['.pas'] := 'code'; Result.Values['.pp'] := 'code'; Result.Values['.inc'] := 'include'; Result.Values['.lpr'] := 'Lazarus project'; // Result.Values['.lpk'] := 'Lazarus package'; end; function TfpciImporter.NeedPackageHandler(const AName: string; var AStream: TStream; OnlyLookUp: Boolean = True):String; var FileName: string; begin AStream := nil; if ExtractFileExt(AName) = '' then FileName := ExtractFileName(AName) + '.pas' else FileName := AName; FileName := CodeProvider.LocateFile(FileName); Result := FileName; if (FilesRead.IndexOf(FileName)>-1) then Result := ''; if {(not OnlyLookUp) and }(FileName<>'') and (FilesRead.IndexOf(FileName)=-1) then begin // AStream := CodeProvider.LoadStream(FileName); FilesRead.Add(FileName); end; end; initialization Integrators.Register(TfpciImporter); end.
unit uFrmBaseDtypeInput; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmBaseInput, Menus, cxLookAndFeelPainters, ActnList, cxLabel, cxControls, cxContainer, cxEdit, cxCheckBox, StdCtrls, cxButtons, ExtCtrls, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxGraphics, cxDropDownEdit, uParamObject, ComCtrls, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, uDBComConfig, cxMemo; type TfrmBaseDtypeInput = class(TfrmBaseInput) edtFullname: TcxButtonEdit; lbl1: TLabel; lbl2: TLabel; edtUsercode: TcxButtonEdit; Label1: TLabel; edtName: TcxButtonEdit; edtPYM: TcxButtonEdit; lbl3: TLabel; chkStop: TcxCheckBox; grpComment: TGroupBox; mmComment: TcxMemo; protected { Private declarations } procedure SetFrmData(ASender: TObject; AList: TParamObject); override; procedure GetFrmData(ASender: TObject; AList: TParamObject); override; procedure ClearFrmData; override; public { Public declarations } procedure BeforeFormShow; override; class function GetMdlDisName: string; override; //得到模块显示名称 end; var frmBaseDtypeInput: TfrmBaseDtypeInput; implementation {$R *.dfm} uses uSysSvc, uBaseFormPlugin, uBaseInfoDef, uModelBaseTypeIntf, uModelControlIntf, uOtherIntf, uDefCom; { TfrmBasePtypeInput } procedure TfrmBaseDtypeInput.BeforeFormShow; begin SetTitle('部门信息'); FModelBaseType := IModelBaseTypePtype((SysService as IModelControl).GetModelIntf(IModelBaseTypeDtype)); FModelBaseType.SetParamList(ParamList); FModelBaseType.SetBasicType(btDtype); DBComItem.AddItem(edtFullname, 'Fullname', 'DFullname'); DBComItem.AddItem(edtUsercode, 'Usercode', 'DUsercode'); DBComItem.AddItem(edtName, 'Name', 'Name'); DBComItem.AddItem(edtPYM, 'Namepy', 'Dnamepy'); DBComItem.AddItem(chkStop, 'IsStop', 'IsStop'); DBComItem.AddItem(mmComment, 'Comment', 'DComment'); inherited; end; procedure TfrmBaseDtypeInput.ClearFrmData; begin inherited; end; procedure TfrmBaseDtypeInput.GetFrmData(ASender: TObject; AList: TParamObject); begin inherited; AList.Add('@Parid', ParamList.AsString('ParId')); DBComItem.SetDataToParam(AList); if FModelBaseType.DataChangeType in [dctModif] then begin AList.Add('@typeId', ParamList.AsString('CurTypeid')); end; end; class function TfrmBaseDtypeInput.GetMdlDisName: string; begin Result := '部门信息'; end; procedure TfrmBaseDtypeInput.SetFrmData(ASender: TObject; AList: TParamObject); begin inherited; DBComItem.GetDataFormParam(AList); end; end.
unit period; interface uses kernel, timez; type TPeriod = class function ToIndex(tiT: times): longword; virtual; abstract; function FromIndex(dwT: longword): times; virtual; abstract; function ToString(ti: times): string; virtual; abstract; function GetNames: names; virtual; abstract; end; TDay = class sealed (TPeriod) function ToIndex(ti: times): longword; override; function FromIndex(dw: longword): times; override; function ToString(ti: times): string; override; function GetNames: names; override; end; TMonth = class sealed (TPeriod) function ToIndex(ti: times): longword; override; function FromIndex(dw: longword): times; override; function ToString(ti: times): string; override; function GetNames: names; override; end; implementation uses calendar; function TDay.ToIndex(ti: times): longword; begin Result := DateToDayIndex(ti); end; function TDay.FromIndex(dw: longword): times; begin Result := DayIndexToDate(dw); end; function TDay.ToString(ti: times): string; begin Result := Times2StrDay(ti); end; function TDay.GetNames: names; begin Result := DAY_NAMES; end; function TMonth.ToIndex(ti: times): longword; begin Result := DateToMonIndex(ti); end; function TMonth.FromIndex(dw: longword): times; begin Result := MonIndexToDate(dw); end; function TMonth.ToString(ti: times): string; begin Result := Times2StrMon(ti); end; function TMonth.GetNames: names; begin Result := MONTH_NAMES; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CTE_INFORMACAO_NF_OUTROS] 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 @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit CteInformacaoNfOutrosVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TCteInformacaoNfOutrosVO = class(TVO) private FID: Integer; FID_CTE_CABECALHO: Integer; FNUMERO_ROMANEIO: String; FNUMERO_PEDIDO: String; FCHAVE_ACESSO_NFE: String; FCODIGO_MODELO: String; FSERIE: String; FNUMERO: String; FDATA_EMISSAO: TDateTime; FUF_EMITENTE: Integer; FBASE_CALCULO_ICMS: Extended; FVALOR_ICMS: Extended; FBASE_CALCULO_ICMS_ST: Extended; FVALOR_ICMS_ST: Extended; FVALOR_TOTAL_PRODUTOS: Extended; FVALOR_TOTAL: Extended; FCFOP_PREDOMINANTE: Integer; FPESO_TOTAL_KG: Extended; FPIN_SUFRAMA: Integer; FDATA_PREVISTA_ENTREGA: TDateTime; FOUTRO_TIPO_DOC_ORIG: String; FOUTRO_DESCRICAO: String; FOUTRO_VALOR_DOCUMENTO: Extended; //Transientes published property Id: Integer read FID write FID; property IdCteCabecalho: Integer read FID_CTE_CABECALHO write FID_CTE_CABECALHO; property NumeroRomaneio: String read FNUMERO_ROMANEIO write FNUMERO_ROMANEIO; property NumeroPedido: String read FNUMERO_PEDIDO write FNUMERO_PEDIDO; property ChaveAcessoNfe: String read FCHAVE_ACESSO_NFE write FCHAVE_ACESSO_NFE; property CodigoModelo: String read FCODIGO_MODELO write FCODIGO_MODELO; property Serie: String read FSERIE write FSERIE; property Numero: String read FNUMERO write FNUMERO; property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO; property UfEmitente: Integer read FUF_EMITENTE write FUF_EMITENTE; property BaseCalculoIcms: Extended read FBASE_CALCULO_ICMS write FBASE_CALCULO_ICMS; property ValorIcms: Extended read FVALOR_ICMS write FVALOR_ICMS; property BaseCalculoIcmsSt: Extended read FBASE_CALCULO_ICMS_ST write FBASE_CALCULO_ICMS_ST; property ValorIcmsSt: Extended read FVALOR_ICMS_ST write FVALOR_ICMS_ST; property ValorTotalProdutos: Extended read FVALOR_TOTAL_PRODUTOS write FVALOR_TOTAL_PRODUTOS; property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL; property CfopPredominante: Integer read FCFOP_PREDOMINANTE write FCFOP_PREDOMINANTE; property PesoTotalKg: Extended read FPESO_TOTAL_KG write FPESO_TOTAL_KG; property PinSuframa: Integer read FPIN_SUFRAMA write FPIN_SUFRAMA; property DataPrevistaEntrega: TDateTime read FDATA_PREVISTA_ENTREGA write FDATA_PREVISTA_ENTREGA; property OutroTipoDocOrig: String read FOUTRO_TIPO_DOC_ORIG write FOUTRO_TIPO_DOC_ORIG; property OutroDescricao: String read FOUTRO_DESCRICAO write FOUTRO_DESCRICAO; property OutroValorDocumento: Extended read FOUTRO_VALOR_DOCUMENTO write FOUTRO_VALOR_DOCUMENTO; //Transientes end; TListaCteInformacaoNfOutrosVO = specialize TFPGObjectList<TCteInformacaoNfOutrosVO>; implementation initialization Classes.RegisterClass(TCteInformacaoNfOutrosVO); finalization Classes.UnRegisterClass(TCteInformacaoNfOutrosVO); end.
unit frmKeyEntryLUKS; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms, Graphics, Messages, OTFEFreeOTFE_U, PasswordRichEdit, SDUForms, Spin64, StdCtrls, SysUtils, Windows, // Required for TFreeOTFEMountAs DriverAPI, OTFEFreeOTFE_PasswordRichEdit, OTFEFreeOTFEBase_U, SDUFrames, SDUSpin64Units, SDUStdCtrls, // Required for TFreeOTFESectorIVGenMethod and NULL_GUID fmeLUKSKeyOrKeyfileEntry, SDUDropFiles, SDUFilenameEdit_U, SDUGeneral; type TfrmKeyEntryLUKS = class (TSDUForm) pbCancel: TButton; pbOK: TButton; GroupBox2: TGroupBox; lblDrive: TLabel; lblMountAs: TLabel; cbDrive: TComboBox; ckMountReadonly: TSDUCheckBox; cbMediaType: TComboBox; GroupBox4: TGroupBox; Label10: TLabel; Label22: TLabel; GroupBox1: TGroupBox; Label1: TLabel; ckBaseIVCypherOnHashLength: TSDUCheckBox; ckMountForAllUsers: TSDUCheckBox; se64UnitSizeLimit: TSDUSpin64Unit_Storage; frmeLUKSKeyOrKeyfileEntry: TfrmeLUKSKeyOrKeyfileEntry; procedure FormCreate(Sender: TObject); procedure pbOKClick(Sender: TObject); procedure SelectionChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure preUserkeyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pbCancelClick(Sender: TObject); procedure ckSelected(Sender: TObject); private protected // These are ordered lists corresponding to the items shown in the combobox fHashKernelModeDriverNames: TStringList; fHashGUIDs: TStringList; fCypherKernelModeDriverNames: TStringList; fCypherGUIDs: TStringList; procedure PopulateDrives(); procedure PopulateMountAs(); procedure DefaultOptions(); procedure EnableDisableControls(); procedure DoCancel(); public // fFreeOTFEObj: TOTFEFreeOTFEBase; procedure Initialize(); // Key... function GetKey(var userKey: TSDUBYtes): Boolean; function SetKey(userKey: PasswordString): Boolean; function SetKeyfile(filename: String): Boolean; function GetKeyfileIsASCII(var isASCII: Boolean): Boolean; function SetKeyfileIsASCII(isASCII: Boolean): Boolean; function GetKeyfileNewlineType(var nlType: TSDUNewline): Boolean; function SetKeyfileNewlineType(nlType: TSDUNewline): Boolean; function GetIVCypherBase(var baseIVCypherOnHashLength: Boolean): Boolean; function SetIVCypherBase(baseIVCypherOnHashLength: Boolean): Boolean; // File options... function GetSizeLimit(var fileOptSizeLimit: Int64): Boolean; function SetSizeLimit(fileOptSizeLimit: Int64): Boolean; // Mount options... function GetDriveLetter(var mountDriveLetter: DriveLetterChar): Boolean; function SetDriveLetter(mountDriveLetter: DriveLetterChar): Boolean; function GetReadonly(var mountReadonly: Boolean): Boolean; function SetReadonly(mountReadonly: Boolean): Boolean; function GetMountAs(var mountAs: TFreeOTFEMountAs): Boolean; function SetMountAs(mountAs: TFreeOTFEMountAs): Boolean; function GetMountForAllUsers(): Boolean; procedure SetMountForAllUsers(allUsers: Boolean); end; implementation {$R *.DFM} uses ComObj, // Required for StringToGUID VolumeFileAPI, // Required for SCTRIVGEN_USES_SECTOR_ID and SCTRIVGEN_USES_HASH INIFiles, OTFEFreeOTFEDLL_U, lcDialogs, SDUi18n; procedure TfrmKeyEntryLUKS.FormCreate(Sender: TObject); begin fhashKernelModeDriverNames := TStringList.Create(); fhashGUIDs := TStringList.Create(); fcypherKernelModeDriverNames := TStringList.Create(); fcypherGUIDs := TStringList.Create(); end; procedure TfrmKeyEntryLUKS.PopulateDrives(); var driveLetters: Ansistring; i: Integer; begin cbDrive.Items.Clear(); cbDrive.Items.Add(_('Use default')); driveLetters := SDUGetUnusedDriveLetters(); for i := 1 to length(driveLetters) do begin // Skip the drive letters traditionally reserved for floppy disk drives // if ( // (driveLetters[i] <> 'A') AND // (driveLetters[i] <> 'B') // ) then // begin cbDrive.Items.Add(driveLetters[i] + ':'); // end; end; end; procedure TfrmKeyEntryLUKS.PopulateMountAs(); var currMountAs: TFreeOTFEMountAs; begin cbMediaType.Items.Clear(); for currMountAs := low(TFreeOTFEMountAs) to high(TFreeOTFEMountAs) do begin if (currMountAs <> fomaUnknown) then begin cbMediaType.Items.Add(FreeOTFEMountAsTitle(currMountAs)); end; end; end; procedure TfrmKeyEntryLUKS.DefaultOptions(); var i: Integer; currDriveLetter: DriveLetterChar; begin frmeLUKSKeyOrKeyfileEntry.DefaultOptions(); if (GetFreeOTFEBase() is TOTFEFreeOTFE) then begin if (cbDrive.Items.Count > 0) then begin cbDrive.ItemIndex := 0; if (GetFreeOTFE().DefaultDriveLetter <> #0) then begin // Start from 1; skip the default for i := 1 to (cbDrive.items.Count - 1) do begin currDriveLetter := cbDrive.Items[i][1]; if (currDriveLetter >= GetFreeOTFE().DefaultDriveLetter) then begin cbDrive.ItemIndex := i; break; end; end; end; end; end; if (GetFreeOTFEBase() is TOTFEFreeOTFE) then begin SetMountAs(GetFreeOTFE().DefaultMountAs); end else begin SetMountAs(fomaRemovableDisk); end; ckBaseIVCypherOnHashLength.Checked := True; se64UnitSizeLimit.Value := 0; // Default to TRUE to allow formatting under Windows Vista ckMountForAllUsers.Checked := True; end; procedure TfrmKeyEntryLUKS.pbOKClick(Sender: TObject); var tmpKey: TSDUBYtes; msgZeroLenKey: String; begin if GetKey(tmpKey) then begin if (Length(tmpKey) = 0) then begin if frmeLUKSKeyOrKeyfileEntry.KeyIsUserEntered() then begin msgZeroLenKey := _('You have not entered a password.'); end else begin msgZeroLenKey := _('Keyfile contained a zero-length key.'); end; if (SDUMessageDlg(msgZeroLenKey + SDUCRLF + SDUCRLF + _('Are you sure you wish to proceed?'), mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin ModalResult := mrOk; end; end else begin // No problems with the password as entered; OK to close the dialog ModalResult := mrOk; end; end // if GetKey(tmpKey) then else begin if not (frmeLUKSKeyOrKeyfileEntry.KeyIsUserEntered()) then begin SDUMessageDlg(_('Unable to read keyfile.'), mtError); end; end; end; procedure TfrmKeyEntryLUKS.EnableDisableControls(); var junkInt64: Int64; junkChar: DriveLetterChar; mountAsOK: Boolean; tmpMountAs: TFreeOTFEMountAs; begin // Ensure we know what to mount as mountAsOK := GetMountAs(tmpMountAs); ckMountReadonly.Enabled := False; if (mountAsOK) then begin if not (FreeOTFEMountAsCanWrite[tmpMountAs]) then begin ckMountReadonly.Checked := True; end; SDUEnableControl(ckMountReadonly, FreeOTFEMountAsCanWrite[tmpMountAs]); end; mountAsOK := mountAsOK and (tmpMountAs <> fomaUnknown); pbOK.Enabled := ((GetSizeLimit(junkInt64)) and (GetDriveLetter(junkChar)) and mountAsOK); end; procedure TfrmKeyEntryLUKS.SelectionChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryLUKS.FormShow(Sender: TObject); begin // Position cursor to the *end* of any password frmeLUKSKeyOrKeyfileEntry.CursorToEndOfPassword(); // Certain controls only visble if used in conjunction with drive mounting lblDrive.Visible := GetFreeOTFEBase() is TOTFEFreeOTFE; cbDrive.Visible := GetFreeOTFEBase() is TOTFEFreeOTFE; lblMountAs.Visible := GetFreeOTFEBase() is TOTFEFreeOTFE; cbMediaType.Visible := GetFreeOTFEBase() is TOTFEFreeOTFE; ckMountForAllUsers.Visible := GetFreeOTFEBase() is TOTFEFreeOTFE; // Prevent making remaining control look odd, stuck in the middle if not (GetFreeOTFEBase() is TOTFEFreeOTFE) then begin ckMountReadonly.top := lblDrive.top; ckMountReadonly.left := lblDrive.left; end; EnableDisableControls(); end; procedure TfrmKeyEntryLUKS.FormDestroy(Sender: TObject); begin fhashKernelModeDriverNames.Free(); fhashGUIDs.Free(); fcypherKernelModeDriverNames.Free(); fcypherGUIDs.Free(); end; procedure TfrmKeyEntryLUKS.preUserkeyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key = 27) then begin DoCancel(); end; end; procedure TfrmKeyEntryLUKS.pbCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmKeyEntryLUKS.DoCancel(); begin ModalResult := mrCancel; end; function TfrmKeyEntryLUKS.GetIVCypherBase(var baseIVCypherOnHashLength: Boolean): Boolean; begin baseIVCypherOnHashLength := ckBaseIVCypherOnHashLength.Checked; Result := True; end; function TfrmKeyEntryLUKS.SetIVCypherBase(baseIVCypherOnHashLength: Boolean): Boolean; begin ckBaseIVCypherOnHashLength.Checked := baseIVCypherOnHashLength; Result := True; end; function TfrmKeyEntryLUKS.GetKey(var userKey: TSDUBYtes): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.GetKey(userKey); end; function TfrmKeyEntryLUKS.SetKey(userKey: PasswordString): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.SetKey(userKey); end; function TfrmKeyEntryLUKS.SetKeyfile(filename: String): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.SetKeyfile(filename); end; function TfrmKeyEntryLUKS.GetKeyfileIsASCII(var isASCII: Boolean): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.GetKeyfileIsASCII(isASCII); end; function TfrmKeyEntryLUKS.SetKeyfileIsASCII(isASCII: Boolean): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.SetKeyfileIsASCII(isASCII); end; function TfrmKeyEntryLUKS.GetKeyfileNewlineType(var nlType: TSDUNewline): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.GetKeyfileNewlineType(nlType); end; function TfrmKeyEntryLUKS.SetKeyfileNewlineType(nlType: TSDUNewline): Boolean; begin Result := frmeLUKSKeyOrKeyfileEntry.SetKeyfileNewlineType(nlType); end; function TfrmKeyEntryLUKS.GetSizeLimit(var fileOptSizeLimit: Int64): Boolean; begin fileOptSizeLimit := se64UnitSizeLimit.Value; Result := True; end; function TfrmKeyEntryLUKS.SetSizeLimit(fileOptSizeLimit: Int64): Boolean; begin se64UnitSizeLimit.Value := fileOptSizeLimit; Result := True; end; // Note: This may return #0 as mountDriveLetter to indicate "any" function TfrmKeyEntryLUKS.GetDriveLetter(var mountDriveLetter: DriveLetterChar): Boolean; begin mountDriveLetter := #0; // Note: The item at index zero is "Use default"; #0 is returned for this if (cbDrive.ItemIndex > 0) then begin mountDriveLetter := cbDrive.Items[cbDrive.ItemIndex][1]; end; Result := True; end; // mountDriveLetter - Set to #0 to indicate "Use default" function TfrmKeyEntryLUKS.SetDriveLetter(mountDriveLetter: DriveLetterChar): Boolean; var idx: Integer; begin Result := True; if (mountDriveLetter = #0) then begin // The item at idx 0 will *always* be "Use default" idx := 0; end else begin idx := cbDrive.Items.IndexOf(mountDriveLetter + ':'); end; if (idx < 0) then begin idx := 0; Result := False; end; cbDrive.ItemIndex := idx; end; function TfrmKeyEntryLUKS.GetReadonly(var mountReadonly: Boolean): Boolean; begin mountReadonly := ckMountReadonly.Checked; Result := True; end; function TfrmKeyEntryLUKS.SetReadonly(mountReadonly: Boolean): Boolean; begin ckMountReadonly.Checked := mountReadonly; Result := True; end; function TfrmKeyEntryLUKS.GetMountAs(var mountAs: TFreeOTFEMountAs): Boolean; var currMountAs: TFreeOTFEMountAs; begin Result := False; for currMountAs := low(TFreeOTFEMountAs) to high(TFreeOTFEMountAs) do begin if (cbMediaType.Items[cbMediaType.ItemIndex] = FreeOTFEMountAsTitle(currMountAs)) then begin mountAs := currMountAs; Result := True; break; end; end; end; function TfrmKeyEntryLUKS.SetMountAs(mountAs: TFreeOTFEMountAs): Boolean; var idx: Integer; begin idx := cbMediaType.Items.IndexOf(FreeOTFEMountAsTitle(mountAs)); cbMediaType.ItemIndex := idx; Result := (idx >= 0); end; procedure TfrmKeyEntryLUKS.SetMountForAllUsers(allUsers: Boolean); begin ckMountForAllUsers.Checked := allUsers; end; function TfrmKeyEntryLUKS.GetMountForAllUsers(): Boolean; begin Result := ckMountForAllUsers.Checked; end; procedure TfrmKeyEntryLUKS.ckSelected(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryLUKS.Initialize(); begin // frmeLUKSKeyOrKeyfileEntry.FreeOTFEObj := fFreeOTFEObj; frmeLUKSKeyOrKeyfileEntry.Initialize(); PopulateDrives(); PopulateMountAs(); DefaultOptions(); end; end.
//==================================================== // // 转换来自JavaClassToDelphiUnit // 时间:2014/8/4 22:14:22 // 作者:ying32 // QQ: 1444386932 // 396506155 // Email:yuanfen3287@vip.qq.com // 个人小站:http://www.ying32.com // 博客:http://blog.csdn.net/zyjying520 // //==================================================== unit Androidapi.JNI.view.ViewGroup; interface uses Androidapi.JNIBridge, Androidapi.JNI.JavaTypes; type JViewGroup = interface; // android.view.ViewGroup JViewGroupClass = interface(JViewClass) ['{CE5E73D0-E5FA-48E8-8D60-9D32E5A5F4A6}'] { Property Methods } function _GETFOCUS_BEFORE_DESCENDANTS: Integer; function _GETFOCUS_AFTER_DESCENDANTS: Integer; function _GETFOCUS_BLOCK_DESCENDANTS: Integer; function _GETPERSISTENT_NO_CACHE: Integer; function _GETPERSISTENT_ANIMATION_CACHE: Integer; function _GETPERSISTENT_SCROLLING_CACHE: Integer; function _GETPERSISTENT_ALL_CACHES: Integer; function _GETCLIP_TO_PADDING_MASK: Integer; { static Methods } function init(context: JContext): JViewGroup; cdecl; function init(context: JContext; attrs: JAttributeSet): JViewGroup; cdecl; function init(context: JContext; attrs: JAttributeSet; defStyle: Integer): JViewGroup; cdecl; function getChildMeasureSpec(padding: Integer; childDimension: Integer): JViewGroup; cdecl; { Property } property FOCUS_BEFORE_DESCENDANTS: Integer read _GETFOCUS_BEFORE_DESCENDANTS; property FOCUS_AFTER_DESCENDANTS: Integer read _GETFOCUS_AFTER_DESCENDANTS; property FOCUS_BLOCK_DESCENDANTS: Integer read _GETFOCUS_BLOCK_DESCENDANTS; property PERSISTENT_NO_CACHE: Integer read _GETPERSISTENT_NO_CACHE; property PERSISTENT_ANIMATION_CACHE: Integer read _GETPERSISTENT_ANIMATION_CACHE; property PERSISTENT_SCROLLING_CACHE: Integer read _GETPERSISTENT_SCROLLING_CACHE; property PERSISTENT_ALL_CACHES: Integer read _GETPERSISTENT_ALL_CACHES; property CLIP_TO_PADDING_MASK: Integer read _GETCLIP_TO_PADDING_MASK; end; [JavaSignature('android/view/ViewGroup')] JViewGroup = interface(JView) ['{AC419BA1-2A66-4B4A-B986-E7118DD224B8}'] { methods } function getDescendantFocusability(): Integer; cdecl; procedure setDescendantFocusability(focusability: Integer); cdecl; procedure requestChildFocus(child: JView; focused: JView); cdecl; procedure focusableViewAvailable(v: JView); cdecl; function showContextMenuForChild(originalView: JView): Boolean; cdecl; function startActionModeForChild(originalView: JView; callback: JActionMode_Callback): JActionMode; cdecl; function focusSearch(focused: JView; direction: Integer): JView; cdecl; function requestChildRectangleOnScreen(child: JView; rectangle: JRect; immediate: Boolean): Boolean; cdecl; function requestSendAccessibilityEvent(child: JView; event: JAccessibilityEvent): Boolean; cdecl; function onRequestSendAccessibilityEvent(child: JView; event: JAccessibilityEvent): Boolean; cdecl; function dispatchUnhandledMove(focused: JView; direction: Integer): Boolean; cdecl; procedure clearChildFocus(child: JView); cdecl; procedure clearFocus(); cdecl; function getFocusedChild(): JView; cdecl; function hasFocus(): Boolean; cdecl; function findFocus(): JView; cdecl; function hasFocusable(): Boolean; cdecl; procedure addFocusables(views: JArrayList; direction: Integer; focusableMode: Integer); cdecl; procedure findViewsWithText(outViews: JArrayList; text: JCharSequence; flags: Integer); cdecl; procedure dispatchWindowFocusChanged(hasFocus: Boolean); cdecl; procedure addTouchables(views: JArrayList); cdecl; procedure dispatchDisplayHint(hint: Integer); cdecl; procedure dispatchWindowVisibilityChanged(visibility: Integer); cdecl; procedure dispatchConfigurationChanged(newConfig: JConfiguration); cdecl; procedure recomputeViewAttributes(child: JView); cdecl; procedure bringChildToFront(child: JView); cdecl; function dispatchDragEvent(event: JDragEvent): Boolean; cdecl; procedure dispatchWindowSystemUiVisiblityChanged(visible: Integer); cdecl; procedure dispatchSystemUiVisibilityChanged(visible: Integer); cdecl; function dispatchKeyEventPreIme(event: JKeyEvent): Boolean; cdecl; function dispatchKeyEvent(event: JKeyEvent): Boolean; cdecl; function dispatchKeyShortcutEvent(event: JKeyEvent): Boolean; cdecl; function dispatchTrackballEvent(event: JMotionEvent): Boolean; cdecl; procedure addChildrenForAccessibility(childrenForAccessibility: JArrayList); cdecl; function onInterceptHoverEvent(event: JMotionEvent): Boolean; cdecl; function dispatchTouchEvent(ev: JMotionEvent): Boolean; cdecl; procedure setMotionEventSplittingEnabled(split: Boolean); cdecl; function isMotionEventSplittingEnabled(): Boolean; cdecl; procedure requestDisallowInterceptTouchEvent(disallowIntercept: Boolean); cdecl; function onInterceptTouchEvent(ev: JMotionEvent): Boolean; cdecl; function requestFocus(direction: Integer; previouslyFocusedRect: JRect): Boolean; cdecl; procedure setClipChildren(clipChildren: Boolean); cdecl; procedure setClipToPadding(clipToPadding: Boolean); cdecl; procedure dispatchSetSelected(selected: Boolean); cdecl; procedure dispatchSetActivated(activated: Boolean); cdecl; procedure addView(child: JView); cdecl; procedure addView(child: JView; index: Integer); cdecl; procedure addView(child: JView; width: Integer; height: Integer); cdecl; procedure addView(child: JView; params: JViewGroup_LayoutParams); cdecl; procedure addView(child: JView; index: Integer; params: JViewGroup_LayoutParams); cdecl; procedure updateViewLayout(view: JView; params: JViewGroup_LayoutParams); cdecl; procedure setOnHierarchyChangeListener(listener: JViewGroup_OnHierarchyChangeListener); cdecl; procedure removeView(view: JView); cdecl; procedure removeViewInLayout(view: JView); cdecl; procedure removeViewsInLayout(start: Integer; count: Integer); cdecl; procedure removeViewAt(index: Integer); cdecl; procedure removeViews(start: Integer; count: Integer); cdecl; procedure setLayoutTransition(transition: JLayoutTransition); cdecl; function getLayoutTransition(): JLayoutTransition; cdecl; procedure removeAllViews(); cdecl; procedure removeAllViewsInLayout(); cdecl; function invalidateChildInParent(location: TArray<Integer>; dirty: JRect): JViewParent; cdecl; function getChildVisibleRect(child: JView; r: JRect; offset: JPoint): Boolean; cdecl; procedure startLayoutAnimation(); cdecl; procedure scheduleLayoutAnimation(); cdecl; procedure setLayoutAnimation(controller: JLayoutAnimationController); cdecl; function getLayoutAnimation(): JLayoutAnimationController; cdecl; function isAnimationCacheEnabled(): Boolean; cdecl; procedure setAnimationCacheEnabled(enabled: Boolean); cdecl; function isAlwaysDrawnWithCacheEnabled(): Boolean; cdecl; procedure setAlwaysDrawnWithCacheEnabled(always: Boolean); cdecl; function getPersistentDrawingCache(): Integer; cdecl; procedure setPersistentDrawingCache(drawingCacheToKeep: Integer); cdecl; function generateLayoutParams(attrs: JAttributeSet): JViewGroup_LayoutParams; cdecl; function indexOfChild(child: JView): Integer; cdecl; function getChildCount(): Integer; cdecl; function getChildAt(index: Integer): JView; cdecl; procedure clearDisappearingChildren(); cdecl; procedure startViewTransition(view: JView); cdecl; procedure endViewTransition(view: JView); cdecl; function gatherTransparentRegion(region: JRegion): Boolean; cdecl; procedure requestTransparentRegion(child: JView); cdecl; function getLayoutAnimationListener(): JAnimation_AnimationListener; cdecl; procedure jumpDrawablesToCurrentState(); cdecl; procedure setAddStatesFromChildren(addsStates: Boolean); cdecl; function addStatesFromChildren(): Boolean; cdecl; procedure childDrawableStateChanged(child: JView); cdecl; procedure setLayoutAnimationListener(animationListener: JAnimation_AnimationListener); cdecl; function shouldDelayChildPressedState(): Boolean; cdecl; end; TJViewGroup = class(TJavaGenericImport<JViewGroupClass, JViewGroup>) end; implementation end.
namespace org.me.serviceapp; //Sample app by Brian Long (http://blong.com) { This example shows an activity interacting with a service (both ways) via intents and broadcast receivers. This file defines the service and its broadcast receiver. The service uses a timer to send regular messages to the activity with information stored within. The service's broadcast receiver looks out for a message telling the service to stop. } interface uses java.util, android.os, android.app, android.content, android.util, android.view, android.widget; type SampleService = public class(Service) private const TAG = 'SvcAppService'; var receiver: ServiceReceiver; var startValue: Integer; var running: Boolean := false; public const SAMPLE_SERVICE_ACTION = 'SAMPLE_SERVICE_ACTION'; const ID_INT_START_VALUE = 'START_VALUE'; const ID_INT_ITERATION = 'ITERATION'; const ID_INT_CALCULATED_VALUE = 'CALCULATED_VALUE'; const ID_INT_COMMAND = 'COMMAND'; const CMD_STOP_SERVICE = 1; method onCreate; override; method onDestroy; override; method onBind(bindingIntent: Intent): IBinder; override; method onStartCommand(startIntent: Intent; &flags, startId: Integer): Integer; override; end; //Nested thread class that will periodically send messages to the activity ServiceThread nested in SampleService = public class(Thread) private owningService: SampleService; public constructor (theService: SampleService); method run; override; end; //Nested broadcast receiver that listens out for messages from the activity ServiceReceiver nested in SampleService = public class(BroadcastReceiver) private owningService: SampleService; public constructor (theService: SampleService); method onReceive(ctx: Context; receivedIntent: Intent); override; end; implementation method SampleService.onCreate; begin inherited; Log.i(TAG, 'Service onCreate'); //Set up the service's broadcast receiver receiver := new ServiceReceiver(self); end; method SampleService.onDestroy; begin Log.i(TAG, 'Service onDestroy'); //Shut down the service's broadcast receiver unregisterReceiver(receiver); inherited end; method SampleService.onBind(bindingIntent: Intent): IBinder; begin exit nil end; method SampleService.onStartCommand(startIntent: Intent; &flags: Integer; startId: Integer): Integer; begin Log.i(TAG, 'Service onStartCommand'); //Bear in mind the activity could call startService more than once, so we need to filter out subsequent invocations if not running then begin //Register the service's broadcast receiver which will pick up messages from the activity var filter := new IntentFilter; filter.addAction(ServiceInteractionActivity.SAMPLE_ACTIVITY_ACTION); registerReceiver(receiver, filter); //Now get the service thread up and running running := true; //Extract information passed along to the service startValue := startIntent.getIntExtra(ID_INT_START_VALUE, 1); //Kickstart the service worker thread var myThread := new ServiceThread(self); myThread.start; end; exit inherited; end; constructor SampleService.ServiceThread(theService: SampleService); begin inherited constructor; owningService := theService; end; //Thread body that sends a message to the activity every 5 seconds method SampleService.ServiceThread.run; begin var i := 1; while owningService.running do try Thread.sleep(5000); var activityIntent := new Intent; activityIntent.Action := SAMPLE_SERVICE_ACTION; //Package up a couple of pieces of information in the intent message activityIntent.putExtra(ID_INT_ITERATION, i); activityIntent.putExtra(ID_INT_CALCULATED_VALUE, i + owningService.startValue); if owningService.running then owningService.sendBroadcast(activityIntent); inc(i); Log.i(TAG, 'Sent a message from service to activity'); except on InterruptedException do //nothing end; owningService.stopSelf end; constructor SampleService.ServiceReceiver(theService: SampleService); begin inherited constructor; owningService := theService; end; //If the broadcast receiver receives a stop command then stop the worker thread and the service method SampleService.ServiceReceiver.onReceive(ctx: Context; receivedIntent: Intent); begin var cmd := receivedIntent.getIntExtra(ID_INT_COMMAND, 0); if cmd = CMD_STOP_SERVICE then begin owningService.running := false; owningService.stopSelf; Toast.makeText(owningService, 'Service stopped by main activity', Toast.LENGTH_LONG).show end; end; end.
unit tExecuteTask; interface uses SysUtils, Classes, ShellAPI, OoMisc, uDMClientThread; type TReplicationStatusEvent = procedure (Msg: String; Count: Integer ) of Object; TReplicationStepCompleted = procedure of Object; TThreadExecuteTask = class(TThread) private { Private declarations } fRunning : Boolean; fTextLog : string; FDMClientThread: TDMClientThread; FDefaultStore: Integer; FReplicateSince: Integer; FSQLBatchCount: Integer; FHost: String; FLocalTables: String; FExceptTables: String; fLocalPath: String; FClientInfo: String; FGlobalTables: String; FOnReplicationStatus: TReplicationStatusEvent; FOnReplicationStepCompleted: TReplicationStepCompleted; FExceptFields: String; FInsertTables: String; FDisableUpdateQty: Boolean; function StopVPN:Boolean; procedure ForwardParameters; protected procedure ExecuteJobs; procedure Execute; override; public property Running : Boolean read fRunning; property LocalPath : String read fLocalPath write fLocalPath; property GlobalTables : String read FGlobalTables write FGlobalTables; property SQLBatchCount: Integer read FSQLBatchCount write FSQLBatchCount; property ExceptTables: String read FExceptTables write FExceptTables; property ExceptFields: String read FExceptFields write FExceptFields; property LocalTables: String read FLocalTables write FLocalTables; property InsertTables: String read FInsertTables write FInsertTables; property ReplicateSince: Integer read FReplicateSince write FReplicateSince; property ClientInfo: String read FClientInfo write FClientInfo; property Host: String read FHost write FHost; property DefaultStore: Integer read FDefaultStore write FDefaultStore; property DisableUpdateQty : Boolean read FDisableUpdateQty write FDisableUpdateQty; property OnReplicationStatus: TReplicationStatusEvent read FOnReplicationStatus write FOnReplicationStatus; property OnReplicationStepCompleted: TReplicationStepCompleted read FOnReplicationStepCompleted write FOnReplicationStepCompleted; constructor Create(CreateSuspended: Boolean); destructor Destroy;override; end; implementation uses uMainConf; { TThreadExecuteTask } function TThreadExecuteTask.StopVPN:Boolean; begin Result := False; if ((FrmMain.fNetworkCon.NetworkCon1 <> '') and (FrmMain.VPN1.ConnectState = csRasConnected)) and (FrmMain.fNetworkCon.StopVPN1) then FrmMain.VPN1.Hangup; if ((FrmMain.fNetworkCon.NetworkCon2 <> '') and (FrmMain.VPN2.ConnectState = csRasConnected)) and (FrmMain.fNetworkCon.StopVPN2) then FrmMain.VPN2.Hangup; end; procedure TThreadExecuteTask.ExecuteJobs; begin fRunning := True; try ForwardParameters; FDMClientThread.ExecuteReplication; finally fRunning := False; FDMClientThread.CloseConnection; StopVPN; end; end; procedure TThreadExecuteTask.ForwardParameters; begin FDMClientThread.LocalPath := FLocalPath; FDMClientThread.GlobalTables := FGlobalTables; FDMClientThread.SQLBatchCount := FSQLBatchCount; FDMClientThread.ExceptTables := FExceptTables; FDMClientThread.LocalTables := FLocalTables; FDMClientThread.ExceptFields := FExceptFields; FDMClientThread.InsertTables := FInsertTables; FDMClientThread.ReplicateSince := FReplicateSince; FDMClientThread.ClientInfo := FClientInfo; FDMClientThread.Host := FHost; FDMClientThread.DefaultStore := FDefaultStore; FDMClientThread.DisableUpdateQty := FDisableUpdateQty; FDMClientThread.Thread := Self; end; procedure TThreadExecuteTask.Execute; begin { Place thread code here } ExecuteJobs; end; constructor TThreadExecuteTask.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FDMClientThread := TDMClientThread.create(nil); end; destructor TThreadExecuteTask.Destroy; begin FDMClientThread.Free; Inherited Destroy; end; end.
unit mainprocessor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, cmtwriter, twmreader; type TOnLog = procedure(msg: String) of object; TOnProgress = procedure(perc1, perc2: Integer) of object; TMainProcessor = class(TObject) FOnLog: TOnLog; FOnProgress: TOnProgress; procedure run(directory: String); property OnLog: TOnLog read FOnLog write FOnLog; property OnProgress: TOnProgress read FOnProgress write FOnProgress; end; implementation procedure TMainProcessor.run(directory: String); var fileList: TStringList; i: integer; cmtwriter: TCmtWriter; twmreader: TTwmReader; begin cmtwriter := TCmtWriter.Create; cmtwriter.OnLog := OnLog; cmtwriter.OnProgress := OnProgress; cmtwriter.open(); fileList := FindAllFiles(directory, '*.gbk.twm', true); try for i:=0 to fileList.count-1 do begin twmreader := TTwmReader.Create; twmreader.OnLog := OnLog; twmreader.open(fileList[i], cmtwriter); twmreader.process(); twmreader.close(); twmreader.Destroy; if Assigned(FOnProgress) then FOnProgress((i+1)*100 div fileList.count, -1); end; finally fileList.Free; end; if Assigned(FOnLog) then FOnLog('Writing commentary records'); cmtwriter.buildCommentaryRecords(); cmtwriter.close(); if Assigned(FOnLog) then FOnLog('Finished.'); end; end.
unit ContaReceberService; interface uses BasicService, Datasnap.DBClient, PessoaVO, Vcl.StdCtrls, System.SysUtils, Vcl.ExtCtrls, RecebimentoContaVO; type TContaReceberService = class(TBasicService) class procedure getPessoa(idOfPessoa: Integer; EdtNome, EdtDoc: TLabeledEdit; Dataset: TClientDataSet); class function RecebimentoContaInserir(RecebimentoConta: TRecebimentoContaVO): Boolean; end; implementation { TContaReceberService } uses ContaReceberRepository; class procedure TContaReceberService.getPessoa(idOfPessoa: Integer; EdtNome, EdtDoc: TLabeledEdit; Dataset: TClientDataSet); var Pessoa: TPessoaVO; I: Integer; begin if not (Dataset.Active) then Dataset.CreateDataSet; Dataset.EmptyDataSet; Pessoa:= TContaReceberRepository.getPessoaById(idOfPessoa); if Assigned(Pessoa) then begin EdtNome.Text:= Pessoa.Nome; EdtDoc.Text:= Pessoa.Doc; if Pessoa.Contas.Count > 0 then begin for I := 0 to Pred(Pessoa.Contas.Count) do begin Dataset.Append; Dataset.FieldByName('ID').AsInteger:= Pessoa.Contas.Items[i].Id; Dataset.FieldByName('ID_PESSOA').AsInteger:= Pessoa.Contas.Items[i].IdPessoa; Dataset.FieldByName('ID_VENDA').AsInteger:= Pessoa.Contas.Items[i].IdVenda; Dataset.FieldByName('LANCAMENTO').AsDateTime:= Pessoa.Contas.Items[i].Lancamento; Dataset.FieldByName('VALOR').AsFloat:= Pessoa.Contas.Items[i].Valor; Dataset.FieldByName('RECEBIDO').AsFloat:= Pessoa.Contas.Items[i].Recebido; Dataset.FieldByName('RECEBER').AsFloat:= Pessoa.Contas.Items[i].Receber; Dataset.FieldByName('RC').AsInteger:= 1; Dataset.Post; end; end; FreeAndNil(Pessoa); end; end; class function TContaReceberService.RecebimentoContaInserir( RecebimentoConta: TRecebimentoContaVO): Boolean; begin Result:= True; BeginTransaction; try TContaReceberRepository.RecebimentoContaInserir(RecebimentoConta); TContaReceberRepository.RecebimentoContaParcelaInserir(RecebimentoConta.Id,RecebimentoConta.Parcelas); TContaReceberRepository.RecebimentoContaRecebimentoInserir(RecebimentoConta.Id,RecebimentoConta.Recebimentos); TContaReceberRepository.CartaoRecebimentoInserir(RecebimentoConta.Id,RecebimentoConta.CartaoRecebimentos); TContaReceberRepository.AtualizarContas(RecebimentoConta.IdPessoa); Commit; except Rollback; Result:= False; end; end; end.
unit TarockFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, CSEdit, CSLabel, Vcl.ExtCtrls,Common.Entities.Card, cxLabel,Common.Entities.Round, cxMemo,GamesSelectFra,KingSelectFra,TalonSelectFra, BiddingFra, ScoreFra,TalonInfoFra,Common.Entities.Player, Classes.Entities, hyieutils, iexBitmaps, hyiedefs, iesettings, ieview, imageenview, imageen; const CSM_REFRESHCARDS=WM_USER+1; type TfrmTarock = class(TForm) Button2: TButton; pBottom: TPanel; clME: TcxLabel; pLeft: TPanel; clFirstPlayer: TcxLabel; pRight: TPanel; pTop: TPanel; pMyCards: TPanel; clThirdPlayer: TcxLabel; clSecondPlayer: TcxLabel; bRegister: TButton; bStartGame: TButton; pFirstplayerCards: TPanel; pThirdPlayerCards: TPanel; tRefresh: TTimer; mGameInfo: TcxMemo; cbPlayers: TComboBox; pBoard: TPanel; pCenter: TPanel; pSecondPlayerCards: TPanel; pThrowCards: TPanel; imgFirstCard: TImage; imgSecondCard: TImage; imgMyCard: TImage; imgThirdCard: TImage; imgTalon: TImage; procedure bRegisterClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BStartGameClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure tRefreshTimer(Sender: TObject); private { Private declarations } FScore:TfraScore; FGameSelect:TfraGameSelect; FKingSelect:TfraKingSelect; FTalonSelect:TfraTalonSelect; FBiddingSelect:TfraBidding; FTalonInfo:TfraTalonInfo; FLastThrowShown:Boolean; FThrowActive:Boolean; FScalingFactor:Double; procedure GetPlayers; procedure ClearCards(const AParent:TWinControl); procedure ShowCards;overload; procedure ShowCards(ACards:TCards; APosition:TCardPosition);overload; procedure ShowThrow(const ARound:TGameRound); procedure ShowTurn; procedure DoThrowCard(Sender:TObject); procedure GameInfo; procedure ShowGameSelect; procedure ShowKingSelect; procedure ShowTalon; procedure CreateTalonInfo; procedure ShowBiddingSelect; procedure ClearThrownCards; procedure ShowCardOfOthers; procedure ScaleCardImages; procedure CenterFrame(AFrame:TFrame); procedure CenterCards(const APanel: TPanel; AHorizontal:Boolean); function GetCardParent(const APosition: TCardPosition): TPanel; procedure ShowForbiddenCardsLaysDown; protected procedure WndProc(var Message:TMessage);override; public { Public declarations } end; var frmTarock: TfrmTarock; implementation uses System.JSON,TarockDM,Classes.CardControl, Common.Entities.GameSituation, Common.Entities.GameType, ConnectionErrorFrm, WiRL.http.Client.Interfaces, RegistrationFrm, System.UIConsts, System.UITypes; {$R *.dfm} const MYCARDMOSTTOP=410; MYCARDMOSTLEFT=20; BACKCARDXOFFSET=30; CARDYOFFSET=0; OTHERCARDPANELHEIGHT=40; procedure TfrmTarock.bRegisterClick(Sender: TObject); begin if cbPlayers.ItemIndex>=0 then begin try dm.MyName:=cbPlayers.Items[cbPlayers.ItemIndex]; dm.RegisterPlayer(dm.MyName); FreeAndNil(FTalonSelect); finally GetPlayers; end; end; end; procedure TfrmTarock.DoThrowCard(Sender: TObject); var error:String; card:TCard; begin if not FThrowActive then Exit; if (dm.GameSituation.State=gsPlaying) and dm.IsMyTurn then begin card:=dm.MyCards.Find(TCardControl(Sender).Card.ID); if dm.CanThrow(card,error) then begin card.Fold:=True; dm.PutTurn(TCardControl(Sender).Card.ID); PostMessage(Handle,CSM_REFRESHCARDS,0,0); end else begin Beep; ShowMessage('Du kannst diese Karte nicht werfen. '+error); end; end; end; procedure TfrmTarock.CenterCards(const APanel: TPanel; AHorizontal:Boolean); var i:Integer; mostLeft: Integer; mostRight: Integer; offset: Integer; begin mostLeft:=10000; mostRight:=0; for i:=0 to APanel.ControlCount-1 do begin if APanel.Controls[i] is TCardControl then begin if AHorizontal then begin if APanel.Controls[i].Left<mostLeft then mostLeft:=APanel.Controls[i].Left; if APanel.Controls[i].Left+APanel.Controls[i].Width>mostRight then mostRight:=APanel.Controls[i].Left+APanel.Controls[i].Width; end else begin if APanel.Controls[i].Top<mostLeft then mostLeft:=APanel.Controls[i].Top; if APanel.Controls[i].Top+APanel.Controls[i].Height>mostRight then mostRight:=APanel.Controls[i].Top+APanel.Controls[i].Height; end; end; end; if mostLeft=10000 then Exit; if AHorizontal then begin offset:=((APanel.Width-mostRight+mostleft) div 2)-mostleft; for i:=0 to APanel.ControlCount-1 do begin if APanel.Controls[i] is TCardControl then APanel.Controls[i].Left:=APanel.Controls[i].Left+offset; end; end else begin offset:=((APanel.Height-mostRight+mostleft) div 2)-mostleft; for i:=0 to APanel.ControlCount-1 do begin if APanel.Controls[i] is TCardControl then APanel.Controls[i].Top:=APanel.Controls[i].Top+offset; end; end; end; procedure TfrmTarock.CenterFrame(AFrame: TFrame); begin AFrame.Top:=(pBoard.Height-AFrame.Height) div 2; AFrame.Left:=(pBoard.Width-AFrame.Width) div 2; end; procedure TfrmTarock.ClearCards(const AParent: TWinControl); var i: Integer; begin for i:=AParent.ControlCount-1 downto 0 do begin if AParent.Controls[i] is TCardControl then AParent.Controls[i].Free end; end; procedure TfrmTarock.ClearThrownCards; var player:TPlayer; begin for player in dm.Players do // clear last thrown of game before player.CardImage.Picture.Assign(nil); imgTalon.Picture.Assign(nil); end; procedure TfrmTarock.bStartGameClick(Sender: TObject); begin dm.StartNewGame; bStartGame.Enabled:=False; end; var TaskCount:Integer; function EnumWindowsProc(hWnd: HWND; lParam: LPARAM): Bool;stdCall; var Capt: PWideChar; begin GetMem(Capt,255); GetWindowText(hWnd, Capt,Sizeof(capt)-1); if Capt='Tarock' then Inc(TaskCount); end; procedure TfrmTarock.FormClose(Sender: TObject; var Action: TCloseAction); begin tRefresh.Enabled:=false; try // dm.UnRegisterPlayer; except end; end; procedure TfrmTarock.FormCreate(Sender: TObject); var frm: TfrmRegistration; dc:HDC; // dpi:Double; begin cbPlayers.Visible:=dm.DebugMode; bRegister.Visible:=dm.DebugMode; dc:=GetDC(0); // dpi:=GetDeviceCaps(dc, LOGPIXELSX)/96; FScalingFactor:=GetDeviceCaps(dc, VERTRES)/1080; CARDWIDTH:=Round(CARDWIDTH*FScalingFactor); CARDHEIGHT:=Round(CARDHEIGHT*FScalingFactor); CARDXOFFSET:=Round(CARDXOFFSET*FScalingFactor); SMALLCARDWIDTH:=Round(SMALLCARDWIDTH*FScalingFactor); SMALLCARDHEIGHT:=Round(SMALLCARDHEIGHT*FScalingFactor); SMALLCARDXOFFSET:=Round(SMALLCARDXOFFSET*FScalingFactor); mGameInfo.Lines.Clear; bStartGame.Enabled:=False; TaskCount:=0; clFirstPlayer.Caption:=''; clSecondPlayer.Caption:=''; clThirdPlayer.Caption:=''; clME.Caption:=''; FScore:=TfraScore.Create(Self); FScore.Parent:=pBoard; FScore.Top:=0; FScore.Left:=0; FScore.Hide; ScaleCardImages; if not dm.DebugMode then begin frm:=TfrmRegistration.Create(self); try if frm.ShowModal<>mrOk then begin Application.Terminate; Exit; end; finally frm.Free end; end; tRefresh.Enabled:=True; end; procedure TfrmTarock.FormResize(Sender: TObject); begin if Assigned(FGameSelect) and FGameSelect.Visible then begin FGameSelect.Height:=400; CenterFrame(FGameSelect); if FGameSelect.Top+FGameSelect.Height>pMyCards.Top then FGameSelect.Top:=pMyCards.Top-FGameSelect.Height; if FgameSelect.Top<pSecondPlayerCards.height then begin FGameSelect.Height:=pCenter.Height; FGameSelect.Top:=pSecondPlayerCards.Height; end; end; if Assigned(FTalonSelect) and FTalonSelect.Visible then CenterFrame(FTalonSelect); if Assigned(FBiddingSelect) and FBiddingSelect.Visible then CenterFrame(FBiddingSelect); if Assigned(FKingSelect) and FKingSelect.Visible then CenterFrame(FKingSelect); pThrowCards.Top:=(pCenter.Height-pSecondPlayerCards.Height-pThrowCards.Height) div 2+pSecondPlayerCards.Height; pThrowCards.Left:=(pCenter.Width-pThrowCards.Width) div 2; CenterCards(pMyCards,True); if Assigned(dm.ActGame) and (dm.ActGame.TeamKind in [tkOuvert,tkAllOuvert]) then begin CenterCards(pFirstPlayerCards,False); CenterCards(pSecondPlayerCards,True); CenterCards(pThirdPlayerCards,False); end; if Assigned(FTalonInfo) then begin FTalonInfo.Top:=pMyCards.Top-FTalonInfo.Height; FTalonInfo.Left:=pBoard.Width-FTalonInfo.Width; end; end; procedure TfrmTarock.GameInfo; var i:Integer; begin if mGameInfo.Lines.Text<>dm.GameSituation.GameInfo.Text then begin mGameInfo.Lines.Assign(dm.GameSituation.GameInfo); SendMessage(mGameInfo.InnerControl.Handle,EM_LINESCROLL,0,mGameInfo.Lines.Count-1); if Assigned(FTalonSelect) and FTalonSelect.Visible then begin for I := mGameInfo.Lines.Count-1 downto 0 do begin if Pos('hat den linken Talon',mGameInfo.Lines[i])>0 then begin FTalonSelect.HighlightTalon(tsLeft); Break; end else if Pos('hat den rechten Talon',mGameInfo.Lines[i])>0 then begin FTalonSelect.HighlightTalon(tsRight); Break; end; end; end; end; end; procedure TfrmTarock.GetPlayers; var itm:TPlayer; begin dm.GetPlayers; for itm in dm.Players do begin itm.PlayerLabel.Caption:=itm.Name; end; end; procedure TfrmTarock.ScaleCardImages; begin imgFirstCard.Height:=CARDHEIGHT; imgFirstCard.Width:=CARDWIDTH; imgSecondCard.Height:=CARDHEIGHT; imgSecondCard.Width:=CARDWIDTH; imgThirdCard.Height:=CARDHEIGHT; imgThirdCard.Width:=CARDWIDTH; imgMyCard.Height:=CARDHEIGHT; imgMyCard.Width:=CARDWIDTH; imgTalon.Height:=CARDHEIGHT; imgTalon.Width:=CARDWIDTH; imgFirstCard.Top:=imgSecondCard.Height div 2 +imgSecondCard.Top; imgThirdCard.Top:=imgFirstCard.Top; imgMyCard.Top:=imgSecondCard.Top+imgSecondCard.Height+30; imgTalon.Top:=imgMyCard.Top; pMyCards.Height:=CARDHEIGHT+CARDUPLIFT; pThrowCards.Height:=CARDHEIGHT*2+CARDUPLIFT; FormResize(Self); end; procedure TfrmTarock.ShowBiddingSelect; begin FreeAndNil(FBiddingSelect); FBiddingSelect:=TfraBidding.Create(Self); FBiddingSelect.Parent:=pBoard; CenterFrame(FBiddingSelect); FBiddingSelect.Show; end; procedure TfrmTarock.ShowForbiddenCardsLaysDown; begin dm.RefreshGameSituation; if not Assigned(FTalonInfo) and (dm.ActGame.Talon<>tkNoTalon) and Assigned(dm.GameSituation.CardsLayedDown) and (dm.GameSituation.CardsLayedDown.Count>0) then begin CreateTalonInfo; FTalonInfo.lCaption.Caption:=dm.GameSituation.Gamer+' hat abgelegt'; FTalonInfo.ShowCards(dm.GameSituation.CardsLayedDown); end; end; procedure TfrmTarock.ShowCards(ACards: TCards; APosition: TCardPosition); type TCardAlignment=(caUp,caLeft,caRight); function CreateCardControl(ACard:TCard; AParent:TWinControl; AAlignment:TCardAlignment; ASmall:Boolean=False):TCardControl; var imageen: TImageEn; begin Result:=TCardControl.Create(Self,ACard); Result.Parent:=AParent; if AAlignment=caUp then begin if ASmall then begin Result.Height:=SMALLCARDHEIGHT; Result.Width:=SMALLCARDWIDTH; end else begin Result.Height:=CARDHEIGHT; Result.Width:=CARDWIDTH; end; dm.imCards.GetBitmap(ACard.ImageIndex,Result.Picture.Bitmap); end else begin if ASmall then begin Result.Width:=SMALLCARDHEIGHT; Result.Height:=SMALLCARDWIDTH; end else begin Result.Width:=CARDHEIGHT; Result.Height:=CARDWIDTH; end; imageen:=TImageEn.Create(nil); try dm.imCards.GetBitmap(ACard.ImageIndex,imageen.Bitmap); if AAlignment=caLeft then imageen.Proc.Rotate(90) else imageen.Proc.Rotate(-90); Result.Picture.Bitmap:=imageen.Bitmap; finally imageen.Free; end; end; end; var imgLeft,imgTop:Integer; img:TCardControl; card:TCard; cardParent:TPanel; begin cardParent:=GetCardParent(APosition); ClearCards(cardParent); if APosition in [cpMyCards] then begin imgLeft:=(Width-((ACards.UnFoldCount-1)*CARDXOFFSET)-CARDWIDTH) div 2; imgLeft:=imgLeft-(CARDXOFFSET div 2); for card in ACards do begin if not card.Fold then begin img:=CreateCardControl(card,cardParent,caUp); img.OnDblClick:=DoThrowCard; img.Top:=CARDUPLIFT; img.Left:=imgLeft; imgLeft:=imgLeft+CARDXOFFSET; end; end; end else if APosition=cpSecondPlayer then begin imgLeft:=(Width-((ACards.UnFoldCount-1)*SMALLCARDXOFFSET)-SMALLCARDWIDTH) div 2; for card in ACards do begin if not card.Fold then begin img:=CreateCardControl(card,cardParent,caUp,True); img.Top:=0; img.Left:=imgLeft; imgLeft:=imgLeft+SMALLCARDXOFFSET; img.Enabled:=False; end; end; end else begin imgTop:=(pFirstPlayerCards.Height-((ACards.UnFoldCount-1)*SMALLCARDXOFFSET)-SMALLCARDWIDTH) div 2; for card in ACards do begin if not card.Fold then begin if APosition=cpFirstPlayer then img:=CreateCardControl(card,cardParent,caLeft,True) else img:=CreateCardControl(card,cardParent,caRight,True); img.Top:=imgTop; img.Left:=0; imgTop:=imgTop+SMALLCARDXOFFSET; img.Enabled:=False; end; end; end; (* else if APosition=cpSecondPlayer then begin imgLeft:=(Width-((ACards.Count-1)*BACKCARDXOFFSET)-CARDWIDTH) div 2; for card in ACards do begin if not card.Fold then begin with TBackCardControl.Create(Self,backCardKind) do begin Parent:=cardParent; Top:=0; Left:=imgLeft; end; imgLeft:=imgLeft+BACKCARDXOFFSET; end; end; end else begin imgTop:=(pFirstPlayerCards.Height-((ACards.Count-1)*BACKCARDXOFFSET)-CARDWIDTH) div 2; for card in ACards do begin if not card.Fold then begin with TBackCardControl.Create(Self,backCardKind) do begin Parent:=cardParent; Top:=imgTop; Left:=0; end; imgTop:=imgTop+BACKCARDXOFFSET; end; end; end;*) end; procedure TfrmTarock.ShowGameSelect; begin FreeAndNil(FGameSelect); FGameSelect:=TfraGameSelect.Create(Self); FGameSelect.Parent:=pBoard; CenterFrame(FGameSelect); FGameSelect.Show; end; procedure TfrmTarock.ShowKingSelect; begin FreeAndNil(FKingSelect); FKingSelect:=TfraKingSelect.Create(Self); FKingSelect.Parent:=pBoard; CenterFrame(FKingSelect); FKingSelect.Show; end; procedure TfrmTarock.ShowCards; begin ShowCards(dm.MyCards,cpMyCards); CenterCards(pMyCards,True); end; procedure TfrmTarock.ShowCardOfOthers; var player:TPlayer; cards:TCards; begin if not (dm.ActGame.TeamKind in [tkOuvert,tkAllOuvert]) then Exit; mGameinfo.Visible:=False; FScore.Visible:=false; for player in dm.Players do begin if (player.Name<>dm.MyName) and ((dm.ActGame.TeamKind=tkAllOuvert) or (player.Name=dm.GameSituation.Gamer)) then begin if player.CardPosition=cpSecondPlayer then GetCardParent(player.CardPosition).Height:=SMALLCARDHEIGHT else GetCardParent(player.CardPosition).Width:=SMALLCARDHEIGHT; cards:=dm.GetCards(player.Name); try ShowCards(cards,player.CardPosition); finally cards.Free; end; end; end; FormResize(Self); end; procedure TfrmTarock.ShowTalon; var i: Integer; begin FreeAndNil(FTalonSelect); FTalonSelect:=TfraTalonSelect.Create(Self); FTalonSelect.Parent:=pBoard; CenterFrame(FTalonSelect); FTalonSelect.Show; for i:=0 to pMyCards.ControlCount-1 do begin if pMyCards.Controls[i] is TCardControl then begin TCardControl(pMyCards.Controls[i]).RemainUp:=True; TCardControl(pMyCards.Controls[i]).Up:=False; end; end; end; procedure TfrmTarock.CreateTalonInfo; begin FreeAndNil(FTalonInfo); FTalonInfo:=TfraTalonInfo.Create(Self); FTalonInfo.Parent:=pBoard; FTalonInfo.Top:=pMyCards.Top-FTalonInfo.Height; FTalonInfo.Left:=pBoard.Width-FTalonInfo.Width; end; procedure TfrmTarock.ShowThrow(const ARound:TGameRound); var itm:TCardThrown; player:TPlayer; begin if ARound=nil then Exit; imgTalon.Picture.Assign(nil); for itm in ARound.CardsThrown do begin if itm.PlayerName='TALON' then dm.imCards.GetBitmap(ALLCARDS.Find(itm.Card).ImageIndex,imgTalon.Picture.Bitmap) else begin player:=dm.Players.Find(itm.PlayerName); if itm.Card=None then player.CardImage.Picture.Assign(nil) else dm.imCards.GetBitmap(ALLCARDS.Find(itm.Card).ImageIndex,player.CardImage.Picture.Bitmap); end; end; if Assigned(dm.ActGame) and (dm.ActGame.TeamKind in [tkOuvert,tkAllOuvert]) and (dm.GameSituation.RoundNo>1) then ShowCardOfOthers; end; procedure TfrmTarock.ShowTurn; var player:TPlayer; begin for player in dm.Players do begin if Assigned(dm.GameSituation) and (dm.GameSituation.TurnOn=player.Name) then begin player.PlayerLabel.Style.Font.Style:=player.PlayerLabel.Style.Font.Style+[fsBold]; player.PlayerLabel.Style.Color:=clSkyBlue; end else begin player.PlayerLabel.Style.Font.Style:=player.PlayerLabel.Style.Font.Style-[fsBold]; player.PlayerLabel.Style.Color:=clBtnFace; end; end; end; function TfrmTarock.GetCardParent(const APosition:TCardPosition):TPanel; begin case APosition of cpMyCards: Result:=pMyCards ; cpFirstPlayer: Result:=pFirstPlayerCards; cpSecondPlayer:Result:=pSecondPlayerCards; cpThirdPlayer: Result:=pThirdPlayerCards; end; end; procedure TfrmTarock.tRefreshTimer(Sender: TObject); procedure SetScore(const ALabel:TcxLabel; const AScore:Smallint); begin ALabel.Caption:=IntToStr(AScore); if AScore<0 then ALabel.Style.Font.Color:=clRed else ALabel.Style.Font.Color:=clBlack; end; procedure ShowScore; begin if not FScore.Visible then begin FScore.clPlayer1.Caption:=dm.GameSituation.Players[0].Name; FScore.clPlayer2.Caption:=dm.GameSituation.Players[1].Name; FScore.clPlayer3.Caption:=dm.GameSituation.Players[2].Name; FScore.clPlayer4.Caption:=dm.GameSituation.Players[3].Name; SetScore(FScore.clScore1,dm.GameSituation.Players[0].Score); SetScore(FScore.clScore2,dm.GameSituation.Players[1].Score); SetScore(FScore.clScore3,dm.GameSituation.Players[2].Score); SetScore(FScore.clScore4,dm.GameSituation.Players[3].Score); FScore.Show; end; if dm.Gamesituation.GameNo>0 then FScore.clGameNo.Caption:=IntToStr(dm.Gamesituation.GameNo)+'. Spiel'; end; procedure Setup; begin if not Assigned(dm.Players) or (dm.Players.Count<dm.GameSituation.Players.Count) then GetPlayers; if (dm.GameSituation.State>gsNone) then ShowScore; FThrowActive:=False; if dm.GameSituation.State<>gsNone then begin if not Assigned(dm.MyCards) then begin dm.GetMyCards; if Assigned(dm.ActGame) and (dm.ActGame.GameTypeid='TRISCH') then pThrowCards.Width:=imgTalon.Left+imgTalon.Width else pThrowCards.Width:=imgThirdCard.Left+imgThirdCard.Width; FormResize(Self); end; ShowCards; end else if dm.Players.Count=4 then bStartGame.Enabled:=True; end; procedure Bidding; begin ShowScore; if not Assigned(FGameSelect) then begin bStartGame.Enabled:=False; FLastThrowShown:=False; ClearThrownCards; FreeAndnil(FTalonInfo); dm.GetMyCards; ShowCards; ShowGameSelect; end; dm.GetBets; FGameSelect.RefreshGames; FGameSelect.CheckMyTurn; end; procedure ShowActGame; begin if Assigned(FGameSelect) and Assigned(dm.ActGame) then begin FreeAndNil(FGameSelect); end; end; procedure CallingKing; begin ShowActGame; if (dm.MyName=dm.GameSituation.Gamer) and not Assigned(FKingSelect) then ShowKingSelect; end; procedure GettingTalon; begin ShowActGame; FreeAndNil(FKingSelect); if not Assigned(FTalonSelect) and ((dm.ActGame.GameTypeid<>'63') or dm.IAmGamer) then ShowTalon; end; procedure FinalBidding; begin ShowActGame; FreeAndNil(FKingSelect); if Assigned(FTalonSelect) then begin FreeAndNil(FTalonSelect); if (dm.MyName=dm.GameSituation.Gamer) then begin dm.GetMyCards; ShowCards; end; end; if not Assigned(FBiddingSelect) then ShowBiddingSelect; if (dm.MyName<>dm.GameSituation.Gamer) and not Assigned(FTalonInfo) then begin ShowForbiddenCardsLaysDown; end; FBiddingSelect.CheckMyTurn; end; procedure Playing; var r:TGameRound; begin if Assigned(FBiddingSelect) then begin FreeAndnil(FBiddingSelect); if Assigned(dm.ActGame) and (dm.ActGame.GameTypeid='TRISCH') then pThrowCards.Width:=imgTalon.Left+imgTalon.Width else pThrowCards.Width:=imgThirdCard.Left+imgThirdCard.Width; FormResize(Self); end; if Assigned(FTalonInfo) then FreeAndnil(FTalonInfo); FThrowActive:=True; r:=dm.GetRound; try if Assigned(r) then begin // game is started ShowThrow(r); if r.Done and dm.IsMyTurn then begin FThrowActive:=False; Application.ProcessMessages; Sleep(2000); dm.NewRound; FThrowActive:=True; end; end; finally r.Free; end; end; procedure GameTerminated; var r:TGameRound; begin mGameInfo.Visible:=true; FScore.Visible:=True; if not FLastThrowShown then begin r:=dm.GetRound; try if Assigned(r) then begin //show last cards thrown ShowThrow(r); FLastThrowShown:=True; end; finally r.Free; end; if dm.ActGame.TeamKind in [tkOuvert,tkAllOuvert] then begin pFirstPlayerCards.Width:=OTHERCARDPANELHEIGHT; pSecondPlayerCards.Height:=OTHERCARDPANELHEIGHT; pThirdPlayerCards.Width:=OTHERCARDPANELHEIGHT; ClearCards(pFirstPlayerCards); ClearCards(pSecondPlayerCards); ClearCards(pThirdPlayerCards); end; end; FreeAndnil(FTalonSelect); if (dm.ActGame.Talon in [tkNoTalon,tk6Talon]) and not Assigned(FTalonInfo) then begin CreateTalonInfo; FTalonInfo.ShowCards(dm.GetCards('TALON')); end; SetScore(FScore.clScore1,dm.GameSituation.Players[0].Score); SetScore(FScore.clScore2,dm.GameSituation.Players[1].Score); SetScore(FScore.clScore3,dm.GameSituation.Players[2].Score); SetScore(FScore.clScore4,dm.GameSituation.Players[3].Score); bStartGame.Enabled:=True; end; begin tRefresh.Enabled:=False; try if dm.MyName='' then exit; try dm.RefreshGameSituation; GameInfo; if not Assigned(dm.Players) then Setup; ShowTurn; case dm.GameSituation.State of gsNone: Setup; gsBidding:Bidding; gsCallKing:CallingKing; gsGetTalon:GettingTalon; gsFinalBet:FinalBidding; gsPlaying:Playing; gsTerminated:GameTerminated; end; except on E:EWiRLSocketException do begin tRefresh.Enabled:=False; dm.ReactiveServerConnection; end; on E:EInvalidCast do begin if E.Message='SS' then Beep; end; on E:Exception do Showmessage(E.ClassName+' '+E.Message); end; finally tRefresh.Enabled:=True; end; end; procedure TfrmTarock.WndProc(var Message: TMessage); begin inherited; if Message.Msg=CSM_REFRESHCARDS then ShowCards(dm.MyCards,cpMyCards) end; end.