text
stringlengths
14
6.51M
program Records; {5 6 7 8 9 10 :-) Done.} type rec1 = record a : integer; b : integer end; rec2 = record a: integer; b: integer; r : rec1 end; var i : integer; r1 : rec1; r2 : rec2; procedure printInt(i:integer); begin putint(i); putch(' ') end; begin r1.a := 5; r1.b := 6; r2.a := 7; r2.b := 8; r2.r.a := 9; r2.r.b := 10; printInt(r1.a); printInt(r1.b); printInt(r2.a); printInt(r2.b); printInt(r2.r.a); printInt(r2.r.b) end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program THEME; Uses Math; Const maxN =5000; minL =5; maxValue =1000000000; Var n,res :Integer; A :Array[1..maxN] of Integer; procedure Enter; var i :Integer; begin Read(n); for i:=1 to n do Read(A[i]); end; procedure Solve; var i,j,count :Integer; tmp :LongInt; begin res:=0; for i:=minL to n-minL do begin tmp:=maxValue; for j:=1 to n-i do if (A[i+j]-A[j]=tmp) then begin if (count=i) then Break; Inc(count); res:=Max(res,count); end else begin count:=1; tmp:=A[i+j]-A[j]; end; end; if (res<minL) then res:=0; end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Solve; Write(res); Close(Input); Close(Output); End.
unit USaveLoadToLPF; {$mode objfpc}{$H+} interface uses Classes, SysUtils, UVisualTools, typinfo, UTransformation, UFigures, Dialogs, UGraph, UExceptions; procedure Save(Put: AnsiString); procedure Open(Loa: AnsiString); implementation procedure SaveFigure(ADest: TStrings; AFigure: TFigure); var PropInfo: PPropInfo; PropList: PPropList; PropCount, K, I: Integer; S: AnsiString; begin ADest.Append(' figure = ' + AFigure.ClassName); PropCount := GetTypeData(AFigure.ClassInfo)^.PropCount; if PropCount > 0 then begin GetMem(PropList, SizeOf(PPropInfo) * PropCount); try GetPropInfos(AFigure.ClassInfo, PropList); for I := 0 to PropCount - 1 do begin PropInfo := PropList^[I]; S := ' ' + PropInfo^.Name + ' = '; if PropInfo^.Name <> 'PointsArr' then S += String(GetPropValue(AFigure, PropInfo^.Name)) else begin for K := 0 to High(AFigure.PointsArr) do S += Format('|%g/%g|,', [AFigure.PointsArr[K].X, AFigure.PointsArr[K].Y]); Delete(S, Length(S), 1); end; ADest.Append(S); end; finally FreeMem(PropList, SizeOf(Pointer) * PropCount); end; ADest.Append(' end'); end; end; procedure SaveArea(ADest: TStrings; ATrans: TTransform); var PropInfo: PPropInfo; PropList: PPropList; I, Count: Integer; begin Count := GetTypeData(ATrans.ClassInfo)^.PropCount; if Count > 0 then begin GetMem(PropList, SizeOf(PPropInfo) * Count); try GetPropInfos(ATrans.ClassInfo, PropList); for I := 0 to Count - 1 do begin PropInfo := PropList^[I]; ADest.Append(' ' + PropInfo^.Name + ' = ' + String(GetPropValue(ATrans, PropInfo^.Name))); end; finally FreeMem(PropList, SizeOf(Pointer) * Count); end; end; end; procedure Save(Put: AnsiString); var J: Integer; ListIng: TStringList; begin ListIng := TStringList.Create; try with ListIng do begin Append('Vector Editor by LifePack'); SaveArea(ListIng, Trans); for J := 0 to High(MAIN_FIGURE_ARRAY) do SaveFigure(ListIng, MAIN_FIGURE_ARRAY[J]); ChangeFileExt(Put, 'lpf'); SaveToFile(Put); end; finally ListIng.Free; end; end; function OpenFigureArray(STR: AnsiString): TDoublePointArray; var List: TStringList; I, PosDot: Integer; begin List := TStringList.Create; List.Delimiter := ','; List.QuoteChar := '|'; List.DelimitedText := STR; if List.Count = 0 then raise Exception.Create('Отсутствуют координаты фигуры'); SetLength(Result, List.Count); for I := 0 to List.Count-1 do begin PosDot := Pos('/', List[I]); if PosDot = 0 then raise Exception.Create('Отсутствует символ "/" между координатами на сттроке'); if not(TryStrToFloat(Copy(List[I], 1 , PosDot - 1), Result[I].X)) then raise Exception.Create('Невозможно привести координату X в вещественное число'); if not(TryStrToFloat(Copy(List[I], PosDot + 1 , Length(List[I]) - PosDot), Result[I].Y)) then raise Exception.Create('Невозможно привести координату Y в вещественное число'); end; end; procedure Open(Loa: AnsiString); var ListIng: TStringList; NewFigureArray: TFigureArray; NewFigureClass: TFigureClass; I, ClassIndex, J: Integer; PropertyName: AnsiString; NotFoundPropertyN, NotFoundPropertyV: TStringList; FigureCount: Integer; begin ListIng := TStringList.Create; NotFoundPropertyN := TStringList.Create; NotFoundPropertyV := TStringList.Create; try With ListIng do begin LoadFromFile(Loa); if Strings[0] <> 'Vector Editor by LifePack' then exit; try Text := StringReplace(Text,' ','',[rfReplaceAll]); for I := 1 to IndexOfName('figure') - 1 do SetPropValue(Trans, Names[I], ValueFromIndex[I]); if NotFoundPropertyN.Capacity <> 0 then raise EErrorList.CreateList(NotFoundPropertyN); if NotFoundPropertyV.Capacity <> 0 then raise EErrorList.CreateList(NotFoundPropertyV); ClassIndex := IndexOfName('figure'); While ClassIndex > 0 do begin SetLength(NewFigureArray, Length(NewFigureArray) + 1); NewFigureClass := ControlFigures.CompareName(ValueFromIndex[ClassIndex]); NewFigureArray[High(NewFigureArray)] := NewFigureClass.Create; ListIng[ClassIndex] := 'No matter what kind of line'; J := ClassIndex + 1; While Strings[J] <> 'end' do begin PropertyName := Names[J]; if PropertyName <> 'PointsArr' then SetPropValue(NewFigureArray[High(NewFigureArray)], PropertyName, ValueFromIndex[J]) else NewFigureArray[High(NewFigureArray)].PointsArr := OpenFigureArray(ValueFromIndex[J]); Inc(J); end; ClassIndex := IndexOfName('figure'); end; MAIN_FIGURE_ARRAY := NewFigureArray; Trans.RefreshScrollBar; Trans.RefreshSpinEdit; ControlTools.MAIN_Invalidate; except on E: EErrorList do E.ShowDialogList; end; end; finally NotFoundPropertyN.Free; NotFoundPropertyV.Free; ListIng.Free; end; end; end.
unit ANovoContratoCliente; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons, Componentes1, ExtCtrls, PainelGradiente, Mask, Localizacao, ComCtrls, Spin, numericos, Constantes, UnDados, Grids, CGrades, DBKeyViolation, UnContrato, UnProdutos; type TRBDColunaGradeServicos =(clCodServico,clDescServico,clDescAdicional,clQtd,clValUnitario, clValTotal); TFNovoContratoCliente = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BGravar: TBitBtn; BCancelar: TBitBtn; BFechar: TBitBtn; ENumContrato: TEditColor; Label1: TLabel; ETipContrato: TEditLocaliza; Label2: TLabel; Label3: TLabel; EValContrato: Tnumerico; Label4: TLabel; EQtdMeses: TSpinEditColor; Label5: TLabel; EDatAssinatura: TCalendario; Label6: TLabel; ECodVendedor: TEditLocaliza; Label9: TLabel; Label17: TLabel; SpeedButton1: TSpeedButton; ConsultaPadrao1: TConsultaPadrao; EDatCancelamento: TMaskEditColor; SpeedButton2: TSpeedButton; Label10: TLabel; ValidaGravacao1: TValidaGravacao; EServico: TEditLocaliza; Label11: TLabel; SpeedButton3: TSpeedButton; Label12: TLabel; ECondicaoPagamento: TEditLocaliza; Label13: TLabel; SpeedButton4: TSpeedButton; ETextoAdicional: TComboBoxColor; Label15: TLabel; Label16: TLabel; EPeriodicidade: TComboBoxColor; Label18: TLabel; ENotaCupom: TEditColor; PManutencaoImpressora: TPanelColor; EQtdFranquia: TSpinEditColor; Label7: TLabel; Label8: TLabel; EValExcedenteFranquia: Tnumerico; ECodTecnicoLeitura: TEditLocaliza; Label19: TLabel; SpeedButton5: TSpeedButton; Label20: TLabel; ENomContato: TEditColor; Label21: TLabel; Label22: TLabel; ECodFormaPagamento: TEditLocaliza; Label14: TLabel; SpeedButton6: TSpeedButton; Label23: TLabel; EContaBancaria: TEditLocaliza; Label24: TLabel; SpeedButton7: TSpeedButton; Label25: TLabel; EValDesconto: Tnumerico; lValDesconto: TLabel; Label26: TLabel; EDatUltimaExecucao: TMaskEditColor; CProcessaAutomatico: TCheckBox; BitBtn2: TBitBtn; EDiaLeitura: Tnumerico; Label27: TLabel; EQtdFranquiaColorida: TSpinEditColor; Label28: TLabel; Label29: TLabel; EValExcedenteColorido: Tnumerico; Label30: TLabel; EPreposto: TEditLocaliza; SpeedButton8: TSpeedButton; Label31: TLabel; EComissaoVendedor: Tnumerico; Label32: TLabel; EComissaoPreposto: Tnumerico; Label33: TLabel; ScrollBox1: TScrollBox; PanelColor3: TPanelColor; EEmail: TEditColor; Label34: TLabel; Label35: TLabel; Shape1: TShape; Label36: TLabel; Shape2: TShape; Label37: TLabel; EInicioVigencia: TCalendario; Label38: TLabel; EFimVigencia: TCalendario; PPaginas: TPageControl; PProdutos: TTabSheet; Grade: TRBStringGridColor; PServicos: TTabSheet; GradeServicos: TRBStringGridColor; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure ETipContratoCadastrar(Sender: TObject); procedure ECodVendedorCadastrar(Sender: TObject); procedure ENumContratoChange(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure BCancelarClick(Sender: TObject); procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GradeNovaLinha(Sender: TObject); procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure EServicoSelect(Sender: TObject); procedure EServicoCadastrar(Sender: TObject); procedure ECodTecnicoLeituraCadastrar(Sender: TObject); procedure EContaBancariaSelect(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure ECodFormaPagamentoRetorno(Retorno1, Retorno2: String); procedure GradeGetCellColor(Sender: TObject; ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont); procedure GradeCellClick(Button: TMouseButton; Shift: TShiftState; VpaColuna, VpaLinha: Integer); procedure EQtdMesesExit(Sender: TObject); procedure GradeServicosCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GradeServicosDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GradeServicosGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: string); procedure GradeServicosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GradeServicosKeyPress(Sender: TObject; var Key: Char); procedure GradeServicosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GradeServicosNovaLinha(Sender: TObject); procedure GradeServicosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); private { Private declarations } VprProdutoAnterior : string; VprCodCliente : Integer; VprAcao : Boolean; VprOperacaoCadastro : TRBDOperacaoCadastro; VprDContrato : TRBDContratoCorpo; VprDItem : TRBDContratoItem; FunContrato : TRBFuncoesContrato; VprDItemServico: TRBDContratoServico; VprServicoAnterior : String; procedure CarTitulosGrade; procedure InicializaClasse; procedure CarDTela; procedure CarDClasse; procedure CarDItemContrato; function ExisteProduto : Boolean; function LocalizaProduto : Boolean; function NumeroSerieValidos : String; function RColunaGradeServicos(VpaColuna : TRBDColunaGradeServicos):Integer; procedure CalculaValorTotalServico; function ExisteServico : Boolean; procedure CarDServicoContrato; function LocalizaServico : Boolean; procedure CalculaContrato; public { Public declarations } function NovoContrato(VpaCodCliente : Integer):Boolean; function AlteraContrato(VpaDContrato : TRBDContratoCorpo) : boolean; procedure ConsultaContrato(VpaDContrato : TRBDContratoCorpo); end; var FNovoContratoCliente: TFNovoContratoCliente; implementation uses APrincipal, ATipoContrato, ANovoVendedor, FunData, FunString, constmsg, ALocalizaProdutos, ANovoServico, Funobjeto, ANovoTecnico, ALocalizaServico; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFNovoContratoCliente.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprDContrato := TRBDContratoCorpo.cria; FunContrato := TRBFuncoesContrato.cria(FPrincipal.BaseDados); PPaginas.ActivePage := PProdutos; Vpracao := false; CarTitulosGrade; Grade.ADados := VprDContrato.ItensContrato; Grade.CarregaGrade; GradeServicos.ADados:= VprDContrato.ServicoContrato; GradeServicos.CarregaGrade; PPaginas.ActivePage:= PProdutos; if not config.ManutencaoImpressoras then begin PManutencaoImpressora.Visible := false; PanelColor1.Height := PanelColor1.Height - PManutencaoImpressora.Height; end; end; { ******************* Quando o formulario e fechado ************************** } procedure TFNovoContratoCliente.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } VprDContrato.free; FunContrato.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFNovoContratoCliente.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFNovoContratoCliente.ETipContratoCadastrar(Sender: TObject); begin FTipoContrato := TFTipoContrato.CriarSDI(application,'', FPrincipal.VerificaPermisao('FTipoContrato')); FTipoContrato.BotaoCadastrar1.Click; FTipoContrato.showmodal; FTipoContrato.free; ConsultaPadrao1.AtualizaConsulta; end; {******************************************************************************} procedure TFNovoContratoCliente.ECodVendedorCadastrar(Sender: TObject); begin FNovoVendedor := TFNovoVendedor.CriarSDI(application,'', FPrincipal.VerificaPermisao('FNovoVendedor')); FNovoVendedor.CadVendedores.Insert; FNovoVendedor.showmodal; FNovoVendedor.free; ConsultaPadrao1.AtualizaConsulta; end; {******************************************************************************} procedure TFNovoContratoCliente.CarTitulosGrade; begin Grade.Cells[1,0] := 'Código'; Grade.Cells[2,0] := 'Produto'; Grade.Cells[3,0] := 'Número Série Produto'; Grade.Cells[4,0] := 'Número Série Interno'; Grade.Cells[5,0] := 'Contador Atual P/B'; Grade.Cells[6,0] := 'Contador Atual Color.'; Grade.Cells[7,0] := 'Setor Empresa'; Grade.Cells[8,0] := 'Medidor Desativação P/B'; Grade.Cells[9,0] := 'Medidor Desativação Color.'; Grade.Cells[10,0] := 'Data Desativação'; Grade.Cells[11,0] := 'Valor Custo Produto'; GradeServicos.Cells[RColunaGradeServicos(clCodServico),0] := 'Código'; GradeServicos.Cells[RColunaGradeServicos(clDescServico),0] := 'Descrição'; GradeServicos.Cells[RColunaGradeServicos(clDescAdicional),0] := 'Descrição Adicional'; GradeServicos.Cells[RColunaGradeServicos(clQtd),0] := 'Qtd'; GradeServicos.Cells[RColunaGradeServicos(clValUnitario),0] := 'Val Unitário'; GradeServicos.Cells[RColunaGradeServicos(clValTotal),0] := 'Valor Total'; end; {******************************************************************************} procedure TFNovoContratoCliente.InicializaClasse; begin VprDContrato.free; VprDContrato := TRBDContratoCorpo.cria; Grade.ADados := VprDContrato.ItensContrato; Grade.CarregaGrade; GradeServicos.ADados:= VprDContrato.ServicoContrato; GradeServicos.CarregaGrade; VprDContrato.CodCliente := VprCodCliente; VprDContrato.CodFilial := varia.codigoEmpfil; VprDContrato.QtdMeses := 12; VprDContrato.DatAssinatura := date; VprDContrato.DatInicioVigencia := VprDContrato.DatAssinatura; VprDContrato.DatFimVigencia := IncMes(VprDContrato.DatInicioVigencia,VprDContrato.QtdMeses); VprDContrato.TipPeriodicidade := 0; VprDContrato.IndProcessamentoAutomatico := true; end; {******************************************************************************} procedure TFNovoContratoCliente.CarDTela; begin ENumContrato.Text := VprDContrato.NumContrato; ETipContrato.AInteiro := VprDContrato.CodTipoContrato; ETipContrato.Atualiza; EValContrato.AValor := VprDContrato.ValContrato; EQtdMeses.Value := VprDContrato.QtdMeses; EDatAssinatura.DateTime := VprDContrato.DatAssinatura; EInicioVigencia.DateTime := VprDContrato.DatInicioVigencia; EFimVigencia.DateTime := VprDContrato.DatFimVigencia; if VprDContrato.DatUltimaExecucao > montadata(1,1,1950) then EDatUltimaExecucao.text := FormatDateTime('DD/MM/YYYY',VprDContrato.DatUltimaExecucao); if VprDContrato.DatCancelamento > montadata(1,1,1950) then EDatCancelamento.text := FormatDateTime('DD/MM/YYYY',VprDContrato.DatCancelamento); EQtdFranquia.Value := VprdContrato.QtdFranquia; EQtdFranquiaColorida.Value := VprDContrato.QtdFranquiaColorida; EValExcedenteFranquia.AValor := VprDContrato.ValExcedenteFranquia; EValExcedenteColorido.Avalor := VprDContrato.ValExcedenteColorido; EServico.AInteiro := VprDContrato.CodServico; EServico.Atualiza; ECodVendedor.AInteiro := VprDContrato.CodVendedor; ECodVendedor.Atualiza; EPreposto.AInteiro := VprDContrato.CodPreposto; Epreposto.Atualiza; ECodVendedor.Atualiza; ECondicaoPagamento.AInteiro := VprDContrato.CodCondicaoPagamento; ECondicaoPagamento.Atualiza; ECodFormaPagamento.AInteiro := VprDContrato.CodFormaPagamento; ECodFormaPagamento.Atualiza; EContaBancaria.Text := VprDContrato.NumContaBancaria; EContaBancaria.Atualiza; ETextoAdicional.ItemIndex := VprDContrato.NumTextoServico; ENotaCupom.Text := VprDContrato.NotaFiscalCupom; EPeriodicidade.ItemIndex := VprDContrato.TipPeriodicidade; ENomContato.Text := VprDContrato.NomContato; ECodTecnicoLeitura.AInteiro := VprDContrato.CodTecnicoLeitura; ECodTecnicoLeitura.Atualiza; EValDesconto.AValor := VprDContrato.ValDesconto; EDiaLeitura.AsInteger := VprDContrato.NumDiaLeitura; CProcessaAutomatico.Checked := VprDContrato.IndProcessamentoAutomatico; EComissaoVendedor.Avalor := VprDContrato.PerComissao; EComissaoPreposto.AValor := VprDContrato.PerComissaoPreposto; EEmail.Text := VprDContrato.desEmail; end; {******************************************************************************} procedure TFNovoContratoCliente.CalculaContrato; begin if VprOperacaoCadastro in [ocInsercao,ocEdicao] then begin CarDClasse; FunContrato.CalculaContrato(VprDContrato); EValContrato.AValor:= VprDContrato.ValTotalServico; end; end; {******************************************************************************} procedure TFNovoContratoCliente.CalculaValorTotalServico; begin if (VprDItemServico.ValUnitario = 0) and (VprDItemServico.ValTotal <> 0) then VprDItemServico.ValUnitario := VprDItemServico.ValTotal / VprDItemServico.QtdServico else VprDItemServico.ValTotal := VprDItemServico.ValUnitario * VprDItemServico.QtdServico; GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha] := FormatFloat(varia.MascaraQtd,VprDItemServico.QtdServico); GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha] := FormatFloat('###,###,###,##0.0000',VprDItemServico.ValUnitario); GradeServicos.Cells[RColunaGradeServicos(clValTotal),GradeServicos.ALinha] := FormatFloat(Varia.MascaraValor,VprDItemServico.ValTotal); end; {******************************************************************************} procedure TFNovoContratoCliente.CarDClasse; begin VprDContrato.NumContrato := ENumContrato.Text; VprDContrato.CodTipoContrato := ETipContrato.AInteiro; VprDContrato.ValContrato := EValContrato.AValor; VprDContrato.QtdMeses := EQtdMeses.Value; VprDContrato.DatAssinatura := EDatAssinatura.DateTime; if DeletaChars(DeletaChars(EDatCancelamento.Text,'/'),' ') <> '' then VprDContrato.DatCancelamento := StrToDate(EDatCancelamento.text) else VprDContrato.DatCancelamento := 0; if DeletaChars(DeletaChars(EDatUltimaExecucao.Text,'/'),' ') <> '' then VprDContrato.DatUltimaExecucao := StrToDate(EDatUltimaExecucao.text); VprdContrato.QtdFranquia := EQtdFranquia.Value; VprDContrato.DatInicioVigencia := EInicioVigencia.Date; VprDContrato.DatFimVigencia := EFimVigencia.Date; VprDContrato.QtdFranquiaColorida := EQtdFranquiaColorida.Value; VprDContrato.ValExcedenteFranquia := EValExcedenteFranquia.AValor; VprDContrato.ValExcedenteColorido := EValExcedenteColorido.AValor; VprDContrato.CodServico := EServico.AInteiro; VprDContrato.CodVendedor := ECodVendedor.AInteiro; VprDContrato.CodPreposto := EPreposto.AInteiro; VprDContrato.CodCondicaoPagamento := ECondicaoPagamento.AInteiro; VprDContrato.CodFormaPagamento := ECodFormaPagamento.AInteiro; VprDContrato.NumContaBancaria := EContaBancaria.text; VprDContrato.NumTextoServico := ETextoAdicional.ItemIndex; VprDContrato.TipPeriodicidade := EPeriodicidade.ItemIndex; VprDContrato.NotaFiscalCupom := ENotaCupom.Text; VprDContrato.NomContato := ENomContato.Text; VprDContrato.CodTecnicoLeitura := ECodTecnicoLeitura.AInteiro; VprDContrato.ValDesconto := EValDesconto.avalor; VprDContrato.NumDiaLeitura := EDiaLeitura.AsInteger; VprDContrato.IndProcessamentoAutomatico := CProcessaAutomatico.Checked; VprDContrato.PerComissao := EComissaoVendedor.AValor; VprDContrato.PerComissaoPreposto := EComissaoPreposto.AValor; VprDContrato.DesEmail := EEmail.Text; end; {******************************************************************************} procedure TFNovoContratoCliente.CarDServicoContrato; begin VprDItemServico.CodServico := StrToInt(GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.Alinha]); if config.PermiteAlteraNomeProdutonaCotacao then VprDItemServico.NomServico := GradeServicos.Cells[RColunaGradeServicos(clDescServico),GradeServicos.ALinha]; VprDItemServico.DesAdicional := GradeServicos.Cells[RColunaGradeServicos(clDescAdicional),GradeServicos.ALinha]; VprDItemServico.QtdServico := StrToFloat(DeletaChars(GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha],'.')); VprDItemServico.ValUnitario := StrToFloat(DeletaChars(GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha],'.')); CalculaValorTotalServico; end; {******************************************************************************} procedure TFNovoContratoCliente.CarDItemContrato; var VpfData : String; begin VprDItem.CodProduto := Grade.Cells[1,Grade.Alinha]; VprDItem.NumSerieProduto := Grade.Cells[3,Grade.ALinha]; VprDItem.NumSerieInterno := Grade.Cells[4,Grade.ALinha]; if Grade.Cells[5,Grade.ALinha] <> '' then VprDItem.QtdUltimaLeitura := StrToInt(DeletaChars(Grade.Cells[5,Grade.ALinha],'.')) else VprDItem.QtdUltimaLeitura := 0; if Grade.Cells[6,Grade.ALinha] <> '' then VprDItem.QtdUltimaLeituraColor := StrToInt(DeletaChars(Grade.Cells[6,Grade.ALinha],'.')) else VprDItem.QtdUltimaLeituraColor := 0; VprDItem.DesSetorEmpresa := Grade.Cells[7,Grade.ALinha]; if Grade.Cells[8,Grade.ALinha] <> '' then VprDItem.QtdLeituraDesativacao := StrtoInt(DeletaChars(Grade.Cells[8,Grade.ALinha],'.')) else VprDItem.QtdLeituraDesativacao := 0; if Grade.Cells[9,Grade.ALinha] <> '' then VprDItem.QtdLeituraDesativacaoColor := StrtoInt(DeletaChars(Grade.Cells[9,Grade.ALinha],'.')) else VprDItem.QtdLeituraDesativacaoColor := 0; if Grade.Cells[10,Grade.ALinha] <> '' then begin try VpfData := Grade.Cells[10,Grade.ALinha]; if VpfData[9] = ' ' then begin VpfData := copy(VpfData,1,6)+'20'+ copy(VpfData,7,2); Grade.Cells[10,Grade.ALinha] := VpfData; end; VprDItem.DatDesativacao := MontaData(StrToInt(Copy(Grade.Cells[10,Grade.ALinha],1,2)),StrToInt(Copy(Grade.Cells[10,Grade.ALinha],4,2)),StrToInt(Copy(Grade.Cells[10,Grade.ALinha],7,4))) except VprDItem.DatDesativacao :=MontaData(01,01,1950); end; end else VprDItem.DatDesativacao := MontaData(01,01,1950); VprDItem.ValCustoProduto := StrToFloat(Grade.Cells[11,Grade.ALinha]); end; {******************************************************************************} function TFNovoContratoCliente.ExisteProduto : Boolean; var VpfCodProduto, vpfNomProduto : String; VpfseqProduto : Integer; begin if (Grade.Cells[1,Grade.ALinha] <> '') then begin if Grade.Cells[1,Grade.ALinha] = VprProdutoAnterior then result := true else begin VpfCodProduto := Grade.Cells[1,Grade.ALinha]; result := FunProdutos.ExisteCodigoProduto(VpfSeqProduto,VpfCodProduto,VpfNomProduto); if result then begin VprDItem.SeqProduto := VpfseqProduto; Grade.Cells[1,Grade.ALinha] := VpfCodProduto; VprProdutoAnterior := VpfCodProduto; VprDItem.SeqProduto := VpfseqProduto; Grade.Cells[2,Grade.ALinha] := vpfNomProduto; VprDItem.CodProduto := VpfCodProduto; VprDItem.NomProduto := vpfNomProduto; end; end; end else result := false; end; {******************************************************************************} function TFNovoContratoCliente.ExisteServico: Boolean; begin if (GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.ALinha] <> '') then begin if (GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.ALinha] = VprServicoAnterior) then result := true else begin result := FunContrato.ExisteServico(GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.ALinha],VprDContrato,VprDItemServico); if result then begin VprServicoAnterior := GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.ALinha]; GradeServicos.Cells[RColunaGradeServicos(clDescServico),GradeServicos.Alinha] := VprDItemServico.NomServico; GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha] := FormatFloat(varia.MascaraQtd,VprDItemServico.QtdServico); GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha] := FormatFloat(varia.MascaraValorUnitario,VprDItemServico.ValUnitario); //if VprDNotaFor.IndCalculaISS then //begin // if VprDServicoNota.PerISSQN <> 0 then // EPerISSQN.AValor := VprDServicoNota.PerISSQN // else // EPerISSQN.AValor := VprPerISSQN; //end; CalculaValorTotalServico; end; end; end else result := false; end; {******************************************************************************} function TFNovoContratoCliente.LocalizaProduto : Boolean; var VpfCadastrou : boolean; VpfSeqProduto : Integer; VpfCodProduto,VpfNomProduto: String; begin FlocalizaProduto := TFlocalizaProduto.criarSDI(Application,'',FPrincipal.VerificaPermisao('FlocalizaProduto')); Result := FlocalizaProduto.LocalizaProduto(VpfCadastrou,VpfSeqProduto,VpfCodProduto,VpfNomProduto); FlocalizaProduto.free; // destroi a classe; if result then // se o usuario nao cancelou a consulta begin VprProdutoAnterior := VpfCodProduto; Grade.Cells[1,Grade.ALinha] := VpfCodProduto; Grade.Cells[2,Grade.ALinha] := VpfNomProduto; VprDItem.CodProduto := VpfCodProduto; VprDItem.NomProduto := VpfNomProduto; VprDItem.SeqProduto := VpfSeqProduto; end; end; {******************************************************************************} function TFNovoContratoCliente.LocalizaServico: Boolean; begin FlocalizaServico := TFlocalizaServico.criarSDI(Application,'',FPrincipal.VerificaPermisao('FlocalizaServico')); result := FlocalizaServico.LocalizaServico(VprDItemServico); FlocalizaServico.free; // destroi a classe; if result then // se o usuario nao cancelou a consulta begin VprDItemServico.QtdServico := 1; GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.ALinha] := IntToStr(VprDItemServico.CodServico); GradeServicos.Cells[RColunaGradeServicos(clDescServico),GradeServicos.ALinha] := VprDItemServico.NomServico; GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha] := FormatFloat(varia.mascaraQtd,VprDItemServico.QtdServico); GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha] := FormatFloat(varia.MascaraValorUnitario,VprDItemServico.ValUnitario); {if VprDNota.IndCalculaISS then begin if VprDServicoNota.PerISSQN <> 0 then EPerISSQN.AValor := VprDServicoNota.PerISSQN else EPerISSQN.AValor := VprPerISSQN; end;} CalculaValorTotalServico; end; end; {******************************************************************************} function TFNovoContratoCliente.NovoContrato(VpaCodCliente : Integer):Boolean; begin VprCodCliente := VpaCodCliente; VprOperacaoCadastro := ocInsercao; InicializaClasse; CarDTela; Showmodal; result := Vpracao; end; {******************************************************************************} function TFNovoContratoCliente.NumeroSerieValidos: String; begin if config.NumeroSerieObrigatorioNoContrato then begin result := FunContrato.NumeroSerieDuplicado(VprDContrato); if result <> '' then Grade.CarregaGrade; end; end; {******************************************************************************} function TFNovoContratoCliente.AlteraContrato(VpaDContrato : TRBDContratoCorpo) : boolean; begin VprCodCliente := VpaDContrato.CodCliente; VprOperacaoCadastro := ocEdicao; VprDContrato.free; VprDContrato := VpaDContrato; Grade.ADados := VpaDContrato.ItensContrato; Grade.CarregaGrade; GradeServicos.ADados:= VpaDContrato.ServicoContrato; GradeServicos.CarregaGrade; CarDTela; Showmodal; result := vprAcao; end; procedure TFNovoContratoCliente.ConsultaContrato(VpaDContrato : TRBDContratoCorpo); begin AlterarEnabledDet([BGravar,BCancelar],false); VprCodCliente := VpaDContrato.CodCliente; PanelColor1.Enabled := false; VprOperacaoCadastro := ocConsulta; VprDContrato.free; VprDContrato := VpaDContrato; Grade.ADados := VpaDContrato.ItensContrato; Grade.CarregaGrade; GradeServicos.ADados:= VpaDContrato.ServicoContrato; GradeServicos.CarregaGrade; CarDTela; Showmodal; end; {******************************************************************************} procedure TFNovoContratoCliente.ENumContratoChange(Sender: TObject); begin if VprOperacaoCadastro in [ocinsercao,ocedicao] then validagravacao1.execute; end; {******************************************************************************} procedure TFNovoContratoCliente.EQtdMesesExit(Sender: TObject); begin if VprOperacaoCadastro in [ocinsercao,ocedicao] then begin if VprDContrato.QtdMeses <> EQtdMeses.Value then begin EFimVigencia.Date := IncMes(EInicioVigencia.Date,EQtdMeses.Value); VprDContrato.QtdMeses := EQtdMeses.Value; end; end; end; procedure TFNovoContratoCliente.BGravarClick(Sender: TObject); var vpfResultado : string; begin if VprOperacaoCadastro in [ocinsercao,ocedicao] then begin vpfResultado := NumeroSerieValidos; if vpfResultado = '' then begin CarDClasse; VpfResultado := FunContrato.GravaDContrato(VprDContrato); end; if VpfResultado = '' then begin VprAcao := true; close; end else aviso(vpfResultado); end; end; {******************************************************************************} procedure TFNovoContratoCliente.BCancelarClick(Sender: TObject); begin Vpracao := false; close; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDItem := TRBDContratoItem(VprDContrato.ItensContrato.Items[vpaLinha-1]); Grade.Cells[1,VpaLinha] := VprDItem.CodProduto; Grade.Cells[2,VpaLinha] := VprDItem.NomProduto; Grade.Cells[3,VpaLinha] := VprDItem.NumSerieProduto; Grade.Cells[4,VpaLinha] := VprDItem.NumSerieInterno; Grade.Cells[5,VpaLinha] := FormatFloat('0',VprDItem.QtdUltimaLeitura); Grade.Cells[6,VpaLinha] := FormatFloat('0',VprDItem.QtdUltimaLeituraColor); Grade.Cells[7,VpaLinha] := VprDItem.DesSetorEmpresa; if VprDItem.QtdLeituraDesativacao <> 0 then Grade.Cells[8,VpaLinha] := FormatFloat('0',VprDItem.QtdLeituraDesativacao) else Grade.Cells[8,VpaLinha] := ''; if VprDItem.QtdLeituraDesativacaoColor <> 0 then Grade.Cells[9,VpaLinha] := FormatFloat('0',VprDItem.QtdLeituraDesativacaoColor) else Grade.Cells[9,VpaLinha] := ''; if VprDItem.DatDesativacao > MontaData(01,01,1970) then Grade.Cells[10,VpaLinha] := FormatDateTime('DD/MM/YYYY',VprDItem.DatDesativacao) else Grade.Cells[10,VpaLinha] := ''; Grade.Cells[11,VpaLinha] := FormatFloat('#,##0.00',VprDItem.ValCustoProduto); end; procedure TFNovoContratoCliente.GradeCellClick(Button: TMouseButton; Shift: TShiftState; VpaColuna, VpaLinha: Integer); begin end; {******************************************************************************} procedure TFNovoContratoCliente.GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos := true; if Grade.Cells[1,Grade.ALinha] = '' then begin VpaValidos := false; aviso(CT_PRODUTONAOCADASTRADO); end else if not ExisteProduto then begin VpaValidos := false; aviso(CT_PRODUTONAOCADASTRADO); Grade.Col := 1; end else if ((Grade.Cells[3,Grade.ALinha]) = '') and (config.NumeroSerieObrigatorioNoContrato) then begin VpaValidos := false; aviso('NUMERO DE SÉRIE NÃO PREENCHIDO!!!'#13'É necessário digitar o número de série do produto'); Grade.Col := 3; end else if (Grade.Cells[10,Grade.ALinha]) <> '' then try if not ValidaData(StrToInt(Copy(Grade.Cells[10,Grade.ALinha],1,2)),StrToInt(Copy(Grade.Cells[10,Grade.ALinha],4,2)),StrToInt(Copy(Grade.Cells[10,Grade.ALinha],7,4))) then begin aviso(CT_DATADESATIVACAOINVALIDA); VpaValidos := false; Grade.Col := 10; end; except aviso(CT_DATADESATIVACAOINVALIDA); VpaValidos := false; Grade.Col := 10; end; if Vpavalidos then begin CarDItemContrato; if (VprDItem.QtdLeituraDesativacao <> 0) then if ((VprDItem.QtdLeituraDesativacao - VprDItem.QtdUltimaLeitura) < 0) then begin aviso('QUANTIDADE MEDIDOR DESATIVAÇÃO INVÁLIDO!!!'#13'A quantidade digitada no medido de desativação não pode ser menor que o da última leitura.'); VpaValidos := false; end; end; if VpaValidos then begin end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 114 : begin case Grade.AColuna of 1: LocalizaProduto; end; end; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDContrato.ItensContrato.Count >0 then begin VprDItem := TRBDContratoItem(VprDContrato.ItensContrato.Items[VpaLinhaAtual-1]); VprProdutoAnterior := VprDItem.CodProduto; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeNovaLinha(Sender: TObject); begin VprDItem := VprDContrato.addItemContrato; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if Grade.AEstadoGrade in [egInsercao,EgEdicao] then if Grade.AColuna <> ACol then begin case Grade.AColuna of 1 :if not ExisteProduto then begin if not LocalizaProduto then begin Grade.Cells[1,Grade.ALinha] := ''; abort; end; end; end; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDItemServico := TRBDContratoServico(VprDContrato.ServicoContrato.Items[VpaLinha-1]); if VprDItemServico.CodServico <> 0 then GradeServicos.Cells[RColunaGradeServicos(clCodServico),VpaLinha] := IntToStr(VprDItemServico.CodServico) else GradeServicos.Cells[RColunaGradeServicos(clCodServico),VpaLinha] := ''; GradeServicos.Cells[RColunaGradeServicos(clDescServico),VpaLinha] := VprDItemServico.NomServico; GradeServicos.Cells[RColunaGradeServicos(clDescAdicional),VpaLinha] := VprDItemServico.DesAdicional; GradeServicos.Cells[RColunaGradeServicos(clQtd),VpaLinha] := FormatFloat(Varia.MascaraQtd,VprDItemServico.QtdServico); GradeServicos.cells[RColunaGradeServicos(clValUnitario),VpaLinha] := FormatFloat(Varia.MascaraValorUnitario,VprDItemServico.ValUnitario); GradeServicos.Cells[RColunaGradeServicos(clValTotal),VpaLinha] := FormatFloat(Varia.MascaraValor,VprDItemServico.ValTotal); CalculaValorTotalServico; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos := false; if not ExisteServico then begin GradeServicos.col := RColunaGradeServicos(clCodServico); aviso('SERVIÇO NÃO PREENCHIDO!!!'#13'É necessário preencher o código do serviço.'); end else if GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha] = '' then begin GradeServicos.col := RColunaGradeServicos(clQtd); Aviso('QUANTIDADE NÃO PREENCHIDA!!!'#13'É necessário preencher a quantidade do serviço.'); end else if GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha] = '' then begin GradeServicos.col := RColunaGradeServicos(clValUnitario); aviso('VALOR UNITÁRIO INVÁLIDO!!!'#13'É necessário preencher o valor unitário do serviço.'); end else VpaValidos := true; if VpaValidos then begin CarDServicoContrato; CalculaContrato; if VprDItemServico.QtdServico = 0 then begin VpaValidos := false; GradeServicos.col := RColunaGradeServicos(clQtd); Aviso('QUANTIDADE NÃO PREENCHIDA!!!'#13'É necessário preencher a quantidade do serviço.'); end else if VprDItemServico.ValUnitario = 0 then begin VpaValidos := false; GradeServicos.col := RColunaGradeServicos(clValUnitario); aviso('VALOR UNITÁRIO INVÁLIDO!!!'#13'É necessário preencher o valor unitário do serviço.'); end; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: string); begin case ACol of 1 : Value := '0000000;0; '; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 114 : begin // F3 case GradeServicos.Col of 1 : LocalizaServico; end; end; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosKeyPress(Sender: TObject; var Key: Char); begin if (key = '.') then key := DecimalSeparator; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDContrato.ServicoContrato.Count >0 then begin VprDItemServico := TRBDContratoServico(VprDContrato.ServicoContrato.Items[VpaLinhaAtual-1]); VprServicoAnterior := InttoStr(VprDItemServico.CodServico); end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosNovaLinha(Sender: TObject); begin VprDItemServico:= VprDContrato.addServicoContrato; VprServicoAnterior := '-10'; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeServicosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if GradeServicos.AEstadoGrade in [egInsercao,EgEdicao] then if GradeServicos.AColuna <> ACol then begin case GradeServicos.AColuna of 1 :if not ExisteServico then begin if not LocalizaServico then begin GradeServicos.Cells[RColunaGradeServicos(clCodServico),GradeServicos.ALinha] := ''; GradeServicos.Col := RColunaGradeServicos(clCodServico); end; end; 4,5 : begin if GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha] <> '' then VprDItemServico.QtdServico := StrToFloat(DeletaChars(GradeServicos.Cells[RColunaGradeServicos(clQtd),GradeServicos.ALinha],'.')) else VprDItemServico.QtdServico := 0; if GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha] <> '' then VprDItemServico.ValUnitario := StrToFloat(DeletaChars(GradeServicos.Cells[RColunaGradeServicos(clValUnitario),GradeServicos.ALinha],'.')) else VprDItemServico.ValUnitario := 0; CalculaValorTotalServico; end; end; end; end; {******************************************************************************} function TFNovoContratoCliente.RColunaGradeServicos( VpaColuna: TRBDColunaGradeServicos): Integer; begin case VpaColuna of clCodServico: result:=1; clDescServico: result:=2 ; clDescAdicional: result:=3; clQtd: result:=4; clValUnitario: result:=5; clValTotal: result:=6; end; end; {******************************************************************************} procedure TFNovoContratoCliente.EServicoSelect(Sender: TObject); begin EServico.ASelectLocaliza.Text := 'Select * from CADSERVICO '+ ' Where C_NOM_SER like ''@%'''+ ' AND I_COD_EMP = '+ InttoStr(varia.CodigoEmpresa)+ ' order by C_NOM_SER '; EServico.ASelectValida.Text := 'Select * from CADSERVICO '+ ' Where I_COD_SER = @ '+ ' AND I_COD_EMP = '+ InttoStr(varia.CodigoEmpresa)+ ' order by C_NOM_SER '; end; {******************************************************************************} procedure TFNovoContratoCliente.EServicoCadastrar(Sender: TObject); var VpfCodServico, VpfNomServico : String; begin FNovoServico := TFNovoServico.CriarSDI(application,'', FPrincipal.VerificaPermisao('FNovoServico')); FNovoServico.InsereNovoServico('',VpfCodServico,VpfNomServico,true); FNovoServico.free; ConsultaPadrao1.AtualizaConsulta; end; {******************************************************************************} procedure TFNovoContratoCliente.ECodTecnicoLeituraCadastrar( Sender: TObject); begin FNovoTecnico := TFNovoTecnico.CriarSDI(application,'', FPrincipal.VerificaPermisao('FNovoTecnico')); FNovoTecnico.Tecnico.Insert; FNovoTecnico.showmodal; FNovoTecnico.free; ConsultaPadrao1.AtualizaConsulta; end; {******************************************************************************} procedure TFNovoContratoCliente.EContaBancariaSelect(Sender: TObject); begin EContaBancaria.ASelectValida.Text := 'Select * from CADCONTAS CON, CADBANCOS BAN '+ ' Where CON.I_EMP_FIL = '+ IntTostr(VprDContrato.CodFilial)+ ' and CON.C_NRO_CON = ''@'''+ ' AND C_IND_ATI = ''T'''+ ' AND CON.I_COD_BAN = BAN.I_COD_BAN '; EContaBancaria.ASelectLocaliza.Text := 'Select * from CADCONTAS CON, CADBANCOS BAN '+ ' Where CON.I_EMP_FIL = '+ IntTostr(VprDContrato.CodFilial)+ ' and CON.C_NOM_CRR LIKE ''@%'''+ ' AND CON.I_COD_BAN = BAN.I_COD_BAN '+ ' AND C_IND_ATI = ''T'''+ ' order by CON.C_NOM_CRR'; end; {******************************************************************************} procedure TFNovoContratoCliente.BitBtn2Click(Sender: TObject); begin EDatCancelamento.Clear; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeGetCellColor(Sender: TObject; ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont); var VpfDItem : TRBDContratoItem; begin if (ARow > 0) and (Acol > 0) then begin if VprDContrato.ItensContrato.Count >0 then begin VpfDItem := TRBDContratoItem(VprDContrato.ItensContrato.Items[arow-1]); if VpfDItem.DatDesativacao > MontaData(1,1,1950) then ABrush.Color := $008080FF; if VpfDItem.IndNumeroSerieDuplicado then ABrush.Color := clYellow; end; end; end; {******************************************************************************} procedure TFNovoContratoCliente.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 10 : Value := '!99/00/0000;1;_'; end; end; {******************************************************************************} procedure TFNovoContratoCliente.ECodFormaPagamentoRetorno(Retorno1, Retorno2: String); begin if VprOperacaoCadastro in [ocinsercao,ocedicao] then begin EContaBancaria.ACampoObrigatorio := Retorno1 = 'B'; ValidaGravacao1.execute; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFNovoContratoCliente]); end.
{ ---------------------------------------------------------------------------- } { BulbTracer for MB3D } { Copyright (C) 2016-2017 Andreas Maschke } { ---------------------------------------------------------------------------- } unit BulbTracerConfig; interface uses SysUtils, Classes, Generics.Collections, VertexList; type TOversampling = (osNone, os2x2x2, os3x3x3); TDoubleWrapper = class private FValue: Double; public constructor Create( const PValue: Double ); property Value: Double read FValue; end; TXYZWrapper = class private FX, FY, FZ: Double; public constructor Create( const PX, PY, PZ: Double ); property X: Double read FX; property Y: Double read FY; property Z: Double read FZ; end; TRange = class private FRangeMin, FRangeMax: Double; FStepCount: Integer; function CalcStepSize: Double; procedure ValidateThreadId(const ThreadId, ThreadCount: Integer); public constructor Create; function CalcStepCount(const ThreadId, ThreadCount: Integer): Integer; function CalcRangeMin(const ThreadId, ThreadCount: Integer): Double; function CalcRangeMinIndex(const ThreadId, ThreadCount: Integer): Integer; property RangeMin: Double read FRangeMin write FRangeMin; property RangeMax: Double read FRangeMax write FRangeMax; property StepCount: Integer read FStepCount write FStepCount; property StepSize: Double read CalcStepSize; end; TMeshType = (mtMesh, mtPointCloud); TTraceRangeMode = (trInclude, trExclude); TTraceRange = class protected FMode: TTraceRangeMode; FIndicatorColorR, FIndicatorColorG, FIndicatorColorB: Double; public constructor Create; function Evaluate( const X, Y, Z: Double ): Boolean; virtual; abstract; procedure AddIndicatorSamples( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); virtual; abstract; property Mode: TTraceRangeMode read FMode write FMode; property IndicatorColorR: Double read FIndicatorColorR write FIndicatorColorR; property IndicatorColorG: Double read FIndicatorColorG write FIndicatorColorG; property IndicatorColorB: Double read FIndicatorColorB write FIndicatorColorB; end; TSphereRange = class ( TTraceRange ) private FCentreX, FCentreY, FCentreZ: Double; FRadius, FRadiusSquared: Double; procedure SetRadius( const Radius: Double ); public constructor Create; function Evaluate( const X, Y, Z: Double ): Boolean; override; procedure AddIndicatorSamples( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); override; property CentreX: Double read FCentreX write FCentreX; property CentreY: Double read FCentreY write FCentreY; property CentreZ: Double read FCentreZ write FCentreZ; property Radius: Double read FRadius write SetRadius; end; TBoxRange = class ( TTraceRange ) private FCentreX, FCentreY, FCentreZ: Double; FSizeX, FSizeY, FSizeZ: Double; FMinX, FMaxX, FMinY, FMaxY, FMinZ, FMaxZ: Double; procedure SetSizeX( const SizeX: Double ); procedure SetSizeY( const SizeY: Double ); procedure SetSizeZ( const SizeZ: Double ); public constructor Create; function Evaluate( const X, Y, Z: Double ): Boolean; override; procedure AddIndicatorSamples( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); override; property CentreX: Double read FCentreX write FCentreX; property CentreY: Double read FCentreY write FCentreY; property CentreZ: Double read FCentreZ write FCentreZ; property SizeX: Double read FSizeX write SetSizeX; property SizeY: Double read FSizeY write SetSizeY; property SizeZ: Double read FSizeZ write SetSizeZ; end; TVertexGenConfig = class private FURange: TRange; FVRange: TRange; FCalcNormals: Boolean; FRemoveDuplicates: Boolean; FSphericalScan: Boolean; FCalcColors: Boolean; FMeshType: TMeshType; FOversampling: TOversampling; FISOValue: Double; FSharedWorkList: TList; FTraceRanges: TList; FSampleJitter: Double; FShowTraceRanges: Boolean; public constructor Create; destructor Destroy; override; procedure Clear; procedure AddSampledTraceRanges( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); property URange: TRange read FURange; property VRange: TRange read FVRange; property CalcNormals: Boolean read FCalcNormals write FCalcNormals; property RemoveDuplicates: Boolean read FRemoveDuplicates write FRemoveDuplicates; property MeshType: TMeshType read FMeshType write FMeshType; property Oversampling: TOversampling read FOversampling write FOversampling; property ISOValue: Double read FISOValue write FISOValue; property SharedWorkList: TList read FSharedWorkList write FSharedWorkList; property SphericalScan: Boolean read FSphericalScan write FSphericalScan; property CalcColors: Boolean read FCalcColors write FCalcColors; property ShowTraceRanges: Boolean read FShowTraceRanges write FShowTraceRanges; property TraceRanges: TList read FTraceRanges; property SampleJitter: Double read FSampleJitter write FSampleJitter; end; implementation uses Contnrs, System.Math; { --------------------------------- TRange ----------------------------------- } constructor TRange.Create; begin inherited Create; FRangeMin := 0.0; FRangeMax := 1.0; FStepCount := 32; end; function TRange.CalcStepSize: Double; begin Result := (FRangeMax - FRangeMin) / (FStepCount - 1); end; procedure TRange.ValidateThreadId(const ThreadId, ThreadCount: Integer); begin if ThreadCount < 1 then raise Exception.Create('Invaid ThreadCount <'+IntToStr(ThreadCount)+'>'); // ThreadId starts with 1 if (ThreadId < 1) or (ThreadId > ThreadCount) then raise Exception.Create('Invalid ThreadId <'+IntToStr(ThreadId)+'>'); end; // ThreadId, unfortunately, starts with 1! function TRange.CalcStepCount(const ThreadId, ThreadCount: Integer): Integer; var d, m: Integer; begin ValidateThreadId(ThreadId, ThreadCount); if ThreadCount > 1 then begin d := FStepCount div ThreadCount; if ( FStepCount mod ThreadCount ) <> 0 then Inc( d ); if ThreadId < ThreadCount then Result := d else Result := FStepCount - d * ( ThreadCount - 1 ); end else Result := FStepCount; end; function TRange.CalcRangeMin(const ThreadId, ThreadCount: Integer): Double; var I, Steps: Integer; begin ValidateThreadId(ThreadId, ThreadCount); if (ThreadId > 1) and (ThreadCount > 1) then begin Steps := 0; for I := 1 to ThreadId - 1 do Inc(Steps, CalcStepCount(I, ThreadCount) ); Result := FRangeMin + Steps * CalcStepSize; end else Result := FRangeMin; end; function TRange.CalcRangeMinIndex(const ThreadId, ThreadCount: Integer): Integer; var I, Steps: Integer; begin ValidateThreadId(ThreadId, ThreadCount); if (ThreadId > 1) and (ThreadCount > 1) then begin Steps := 0; for I := 1 to ThreadId - 1 do Inc(Steps, CalcStepCount(I, ThreadCount) ); Result := Steps; end else Result := 0; end; { ----------------------------- TVertexGenConfig ----------------------------- } constructor TVertexGenConfig.Create; begin inherited Create; FURange := TRange.Create; FVRange := TRange.Create; FTraceRanges := TObjectList.Create; CalcNormals := False; RemoveDuplicates := True; MeshType := mtPointCloud; end; destructor TVertexGenConfig.Destroy; begin FURange.Free; FVRange.Free; FTraceRanges.Free; inherited Destroy; end; procedure TVertexGenConfig.Clear; begin FTraceRanges.Clear; end; procedure TVertexGenConfig.AddSampledTraceRanges( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); var I: Integer; Range: TTraceRange; begin for I := 0 to FTraceRanges.Count - 1 do begin Range := FTraceRanges[ I ]; Range.AddIndicatorSamples( VertexList, NormalsList, ColorList ); end; end; { ------------------------------- TTraceRange -------------------------------- } constructor TTraceRange.Create; begin inherited; FMode := trExclude; FIndicatorColorR := 0.86; FIndicatorColorG := 0.45; FIndicatorColorB := 0.12; end; { ------------------------------ TSphereRange -------------------------------- } constructor TSphereRange.Create; begin inherited; Radius := 100.0; end; procedure TSphereRange.SetRadius( const Radius: Double ); begin FRadius := Radius; FRadiusSquared := Sqr( FRadius ); end; function TSphereRange.Evaluate( const X, Y, Z: Double ): Boolean; begin case Mode of trInclude: Result := Sqr( X - CentreX ) + Sqr( Y - CentreY ) + Sqr( Z - CentreZ ) > FRadiusSquared; trExclude: Result := Sqr( X - CentreX ) + Sqr( Y - CentreY ) + Sqr( Z - CentreZ ) <= FRadiusSquared; end; end; procedure TSphereRange.AddIndicatorSamples( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); const Slices100 = 300; var I, J, Slices: Integer; Theta, DTheta, SinTheta, CosTheta: Double; Phi, DPhi, SinPhi, CosPhi: Double; X, Y, Z: Double; begin Slices := Round( Radius * Slices100 / 100.0 ); DTheta := DegToRad(360.0) / (Slices); DPhi := DegToRad(360.0) / (Slices); for I := 0 to Slices - 1 do begin SinCos(Theta, SinTheta, CosTheta); Phi := 0.0; for J := 0 to Slices - 1 do begin SinCos(Phi, SinPhi, CosPhi); X := - SinTheta * CosPhi * Radius + CentreX; Y := - SinTheta * SinPhi * Radius + CentreY; Z := CosTheta * Radius + CentreZ; VertexList.AddVertex( X, Y, Z ); if NormalsList <> nil then NormalsList.AddVertex( 0.0, 0.0, 0.0 ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); Phi := Phi + DPhi; end; Theta := Theta + DTheta; end; end; { --------------------------------- TBoxRange -------------------------------- } constructor TBoxRange.Create; begin inherited; SizeX := 100.0; SizeY := 100.0; SizeZ := 50.0; end; procedure TBoxRange.SetSizeX( const SizeX: Double ); begin FSizeX := SizeX; FMinX := CentreX - FSizeX / 2.0; FMaxX := CentreX + FSizeX / 2.0; end; procedure TBoxRange.SetSizeY( const SizeY: Double ); begin FSizeY := SizeY; FMinY := CentreY - FSizeY / 2.0; FMaxY := CentreY + FSizeY / 2.0; end; procedure TBoxRange.SetSizeZ( const SizeZ: Double ); begin FSizeZ := SizeZ; FMinZ := CentreZ - FSizeZ / 2.0; FMaxZ := CentreZ + FSizeZ / 2.0; end; function TBoxRange.Evaluate( const X, Y, Z: Double ): Boolean; begin case Mode of trInclude: Result := ( X < FMinX ) or ( X > FMaxX) or ( Y < FMinY ) or ( Y > FMaxY ) or ( Z < FMinZ ) or ( Z > FMaxZ ); trExclude: Result := ( X >= FMinX ) and ( X <= FMaxX) and ( Y >= FMinY ) and ( Y <= FMaxY ) and ( Z >= FMinZ ) and ( Z <= FMaxZ ); end; end; procedure TBoxRange.AddIndicatorSamples( VertexList: TPS3VectorList; NormalsList, ColorList: TPSMI3VectorList ); const Slices100 = 80; var X, Y, Z, DX, DY, DZ, Radius: Double; I, J, Slices: Integer; begin Radius := Sqrt( Sqr( FSizeX ) + Sqr( FSizeY ) + Sqr( FSizeZ ) ); Slices := Round( Radius * Slices100 / 100.0 ); DX := FSizeX / Slices; DY := FSizeY / Slices; DZ := FSizeZ / Slices; X := FMinX; for I := 0 to Slices - 1 do begin Y := FMinY; for J := 0 to Slices - 1 do begin VertexList.AddVertex( X, Y, FMinZ ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); VertexList.AddVertex( X, Y, FMaxZ ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); if NormalsList <> nil then NormalsList.AddVertex( 0.0, 0.0, 0.0 ); Y := Y + DY; end; X := X + DX; end; Y := FMinY; for I := 0 to Slices - 1 do begin Z := FMinZ; for J := 0 to Slices - 1 do begin VertexList.AddVertex( FMinX, Y, Z ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); VertexList.AddVertex( FMaxX, Y, Z ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); if NormalsList <> nil then NormalsList.AddVertex( 0.0, 0.0, 0.0 ); Z := Z + DZ; end; Y := Y + DY; end; Z := FMinZ; for I := 0 to Slices - 1 do begin X := FMinX; for J := 0 to Slices - 1 do begin VertexList.AddVertex( X, FMinY, Z ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); VertexList.AddVertex( X, FMaxY, Z ); if ColorList <> nil then ColorList.AddVertex( IndicatorColorR, IndicatorColorG, IndicatorColorB ); if NormalsList <> nil then NormalsList.AddVertex( 0.0, 0.0, 0.0 ); X := X + DX; end; Z := Z + DZ; end; end; { ------------------------------ TDoubleWrapper ------------------------------ } constructor TDoubleWrapper.Create( const PValue: Double ); begin inherited Create; FValue := PValue; end; { --------------------------------- TXYZWrapper ------------------------------ } constructor TXYZWrapper.Create( const PX, PY, PZ: Double ); begin inherited Create; FX := PX; FY := PY; FZ := PZ; end; end.
unit BlockSizeSpreadBenchmark; interface uses BenchmarkClassUnit, Math; const {The number of pointers} NumPointers = 2000000; {The maximum block size} MaxBlockSize = 25; // *4 type TBlockSizeSpreadBench = class(TFastcodeMMBenchmark) protected FPointers: array[0..NumPointers - 1] of PChar; public constructor CreateBenchmark; override; destructor Destroy; override; procedure RunBenchmark; override; class function GetBenchmarkName: string; override; class function GetBenchmarkDescription: string; override; class function GetCategory: TBenchmarkCategory; override; end; implementation { TSmallResizeBench } constructor TBlockSizeSpreadBench.CreateBenchmark; begin inherited; end; destructor TBlockSizeSpreadBench.Destroy; begin inherited; end; class function TBlockSizeSpreadBench.GetBenchmarkDescription: string; begin Result := 'Allocates millions of small objects, checking that the MM ' + 'has a decent block size spread. ' + 'Benchmark submitted by Pierre le Riche.'; end; class function TBlockSizeSpreadBench.GetBenchmarkName: string; begin Result := 'Block size spread benchmark'; end; class function TBlockSizeSpreadBench.GetCategory: TBenchmarkCategory; begin Result := bmSingleThreadAllocAndFree; end; procedure TBlockSizeSpreadBench.RunBenchmark; var i, n, LSize: integer; begin {Call the inherited handler} inherited; for n := 1 to 3 do // loop added to have more than 1000 MTicks for this benchmark begin {Do the benchmark} for i := 0 to high(FPointers) do begin {Get the initial block size, assume object sizes are 4-byte aligned} LSize := (1 + random(MaxBlockSize)) * 4; GetMem(FPointers[i], LSize); FPointers[i][0] := #13; FPointers[i][LSize - 1] := #13; end; {What we end with should be close to the peak usage} UpdateUsageStatistics; {Free the pointers} for i := 0 to high(FPointers) do FreeMem(FPointers[i]); end; end; end.
{** Message Digest 5 : Rotina de criação de chave fixa a partir de uma semente. } unit osMD5; { Algoritmo de Message Digest MD5 (c) 1991-1992, RSA Data Security, Inc. All rights reserved. A partir do código original em C $Header: \FW/Lib/osMD5.pas,v 1.1.1.1 2004/12/10 19:19:28 Ricardo Acras Exp $ $Log: osMD5.pas,v $ Revision 1.1.1.1 2004/12/10 19:19:28 Ricardo Acras no message Revision 1.2 2004/12/02 16:14:19 Administrador no message Revision 1.1.1.1 2004/11/26 18:33:18 Walter no message Revision 1.1.1.1 2004/11/26 18:09:10 Walter no message Revision 1.1.1.1 2004/11/17 18:48:24 Walter no message Revision 1.1.1.1 2004/10/27 15:11:48 rica no message Revision 1.1.1.1 2004/10/15 18:11:32 Walter no message Revision 1.1.1.1 2004/03/10 14:54:12 rica no message 2 1/10/98 17:26 Josue 1 30/09/98 14:25 Josue Message Digest Algorithm } interface {** Message Digest 5 : Rotina de criação de chave fixa a partir de uma semente. } function MD5Digest(s : String) : string; implementation uses SysUtils; const S11 = 7; S12 = 12; S13 = 17; S14 = 22; S21 = 5; S22 = 9; S23 = 14; S24 = 20; S31 = 4; S32 = 11; S33 = 16; S34 = 23; S41 = 6; S42 = 10; S43 = 15; S44 = 21; type TMD5Context = record State : Array [0..3] of LongWord; Count : Array [0..1] of LongWord; Buffer : Array [0..63] of Byte; end; TInputBlock = record InputBlock : Array [0..1023] of Byte; nSize : Word; end; var Padding : Array [0..63] of Byte; function RotateLeft(x , n : LongWord) : LongWord; begin RotateLeft := (((x) shl (n)) or ((x) shr (32-(n)))); end; function F(x, y, z : LongWord) : LongWord; begin F := ((x and y) or ((not x) and z)); end; function G(x, y, z : LongWord) : LongWord; begin G := ((x and z) or (y and (not z))); end; function H(x, y, z : LongWord) : LongWord; begin H := (x xor y xor z); end; function I(x, y, z : LongWord) : LongWord; begin I := (y xor (x or (not z))); end; // ------------------------------------------ procedure FF(var a : LongWord; b, c, d, x, s, ac : LongWord); begin a := a + F(b, c, d) + x + ac; a := RotateLeft (a, s); a := a + b; end; procedure GG(var a : LongWord; b, c, d, x, s, ac : LongWord); begin a := a + G(b, c, d) + x + ac; a := RotateLeft (a, s); a := a + b; end; procedure HH(var a : LongWord; b, c, d, x, s, ac : LongWord); begin a := a + H(b, c, d) + x + ac; a := RotateLeft (a, s); a := a + b; end; procedure II(var a : LongWord; b, c, d, x, s, ac : LongWord); begin a := a + I(b, c, d) + x + ac; a := RotateLeft (a, s); a := a + b; end; procedure MD5_memcpy (var output : Array of Byte; initout : Word; input : Array of Byte; initin, len : Word); var i : Word; begin for i := 1 to len do output[initout + i - 1] := input[initin + i - 1]; end; procedure MD5_memset (var output : Array of Byte; value : Byte; len : Word); var i : Word; begin for i := 0 to len do output[i] := value; end; procedure Encode (var output : Array of Byte; input : Array of LongWord;init, len : Word); var i, j : Word; begin; i := init; j := 0; while j < len do begin output[j] := input[i] and $FF; output[j + 1] := (input[i] shr 8) and $FF; output[j + 2] := (input[i] shr 16) and $FF; output[j + 3] := (input[i] shr 24) and $FF; i := i + 1; j := j + 4; end; end; procedure Decode (var output : Array of LongWord; input : Array of Byte;init, len : Word); var i, j : Word; begin j := 0; i := init; while j < len do begin output[i] := input[j] or ( (input[j + 1]) shl 8) or ( (input[j + 2]) shl 16) or ( (input[j + 3]) shl 24); i := i + 1; j := j + 4; end; end; procedure MD5Transform (var state : Array of LongWord; Block : array of Byte; init : Word); var a, b, c, d : LongWord; x : Array [0..15] of LongWord; begin a := state[0]; b := state[1]; c := state[2]; d := state[3]; Decode (x, block, init, 64); // Round 1 FF (a, b, c, d, x[ 0], S11, $d76aa478); // 1 FF (d, a, b, c, x[ 1], S12, $e8c7b756); // 2 FF (c, d, a, b, x[ 2], S13, $242070db); // 3 FF (b, c, d, a, x[ 3], S14, $c1bdceee); // 4 FF (a, b, c, d, x[ 4], S11, $f57c0faf); // 5 FF (d, a, b, c, x[ 5], S12, $4787c62a); // 6 FF (c, d, a, b, x[ 6], S13, $a8304613); // 7 FF (b, c, d, a, x[ 7], S14, $fd469501); // 8 FF (a, b, c, d, x[ 8], S11, $698098d8); // 9 FF (d, a, b, c, x[ 9], S12, $8b44f7af); // 10 FF (c, d, a, b, x[10], S13, $ffff5bb1); // 11 FF (b, c, d, a, x[11], S14, $895cd7be); // 12 FF (a, b, c, d, x[12], S11, $6b901122); // 13 FF (d, a, b, c, x[13], S12, $fd987193); // 14 FF (c, d, a, b, x[14], S13, $a679438e); // 15 FF (b, c, d, a, x[15], S14, $49b40821); // 16 // Round 2 GG (a, b, c, d, x[ 1], S21, $f61e2562); // 17 GG (d, a, b, c, x[ 6], S22, $c040b340); // 18 GG (c, d, a, b, x[11], S23, $265e5a51); // 19 GG (b, c, d, a, x[ 0], S24, $e9b6c7aa); // 20 GG (a, b, c, d, x[ 5], S21, $d62f105d); // 21 GG (d, a, b, c, x[10], S22, $2441453); // 22 GG (c, d, a, b, x[15], S23, $d8a1e681); // 23 GG (b, c, d, a, x[ 4], S24, $e7d3fbc8); // 24 GG (a, b, c, d, x[ 9], S21, $21e1cde6); // 25 GG (d, a, b, c, x[14], S22, $c33707d6); // 26 GG (c, d, a, b, x[ 3], S23, $f4d50d87); // 27 GG (b, c, d, a, x[ 8], S24, $455a14ed); // 28 GG (a, b, c, d, x[13], S21, $a9e3e905); // 29 GG (d, a, b, c, x[ 2], S22, $fcefa3f8); // 30 GG (c, d, a, b, x[ 7], S23, $676f02d9); // 31 GG (b, c, d, a, x[12], S24, $8d2a4c8a); // 32 // Round 3 HH (a, b, c, d, x[ 5], S31, $fffa3942); // 33 HH (d, a, b, c, x[ 8], S32, $8771f681); // 34 HH (c, d, a, b, x[11], S33, $6d9d6122); // 35 HH (b, c, d, a, x[14], S34, $fde5380c); // 36 HH (a, b, c, d, x[ 1], S31, $a4beea44); // 37 HH (d, a, b, c, x[ 4], S32, $4bdecfa9); // 38 HH (c, d, a, b, x[ 7], S33, $f6bb4b60); // 39 HH (b, c, d, a, x[10], S34, $bebfbc70); // 40 HH (a, b, c, d, x[13], S31, $289b7ec6); // 41 HH (d, a, b, c, x[ 0], S32, $eaa127fa); // 42 HH (c, d, a, b, x[ 3], S33, $d4ef3085); // 43 HH (b, c, d, a, x[ 6], S34, $4881d05); // 44 HH (a, b, c, d, x[ 9], S31, $d9d4d039); // 45 HH (d, a, b, c, x[12], S32, $e6db99e5); // 46 HH (c, d, a, b, x[15], S33, $1fa27cf8); // 47 HH (b, c, d, a, x[ 2], S34, $c4ac5665); // 48 // Round 4 II (a, b, c, d, x[ 0], S41, $f4292244); // 49 II (d, a, b, c, x[ 7], S42, $432aff97); // 50 II (c, d, a, b, x[14], S43, $ab9423a7); // 51 II (b, c, d, a, x[ 5], S44, $fc93a039); // 52 II (a, b, c, d, x[12], S41, $655b59c3); // 53 II (d, a, b, c, x[ 3], S42, $8f0ccc92); // 54 II (c, d, a, b, x[10], S43, $ffeff47d); // 55 II (b, c, d, a, x[ 1], S44, $85845dd1); // 56 II (a, b, c, d, x[ 8], S41, $6fa87e4f); // 57 II (d, a, b, c, x[15], S42, $fe2ce6e0); // 58 II (c, d, a, b, x[ 6], S43, $a3014314); // 59 II (b, c, d, a, x[13], S44, $4e0811a1); // 60 II (a, b, c, d, x[ 4], S41, $f7537e82); // 61 II (d, a, b, c, x[11], S42, $bd3af235); // 62 II (c, d, a, b, x[ 2], S43, $2ad7d2bb); // 63 II (b, c, d, a, x[ 9], S44, $eb86d391); // 64 state[0] := state[0] + a; state[1] := state[1] + b; state[2] := state[2] + c; state[3] := state[3] + d; // Zeroize sensitive information. // MD5_memset (x, 0, 16); end; procedure MD5Init(var md5Context : TMD5Context); var i : Word; begin md5Context.count[0] := 0; md5Context.count[1] := 0; // Load magic initialization constants. md5Context.state[0] := $67452301; md5Context.state[1] := $efcdab89; md5Context.state[2] := $98badcfe; md5Context.state[3] := $10325476; Padding[0] := $80; for i := 1 to 63 do Padding[i] := 0; end; procedure MD5Update (var md5Context : TMD5Context; inputBlock : TInputBlock); var i, index, partLen : Word; begin // Compute number of bytes mod 64 index := ((md5Context.count[0] shr 3) and $3F); // Update number of bits md5Context.count[0] := md5Context.count[0] + (inputBlock.nSize shl 3); if md5Context.count[0] < (inputBlock.nSize shl 3) then md5Context.count[1] := md5Context.count[1] + 1; md5Context.count[1] := md5Context.count[1] + (inputBlock.nSize shr 29); partLen := 64 - index; // Transform as many times as possible. if inputBlock.nSize >= partLen then begin MD5_memcpy(md5context.buffer, index, inputBlock.inputBlock, 0, partLen); MD5Transform (md5Context.state, md5Context.buffer, 0); i := partLen; while i + 63 < inputBlock.nSize do begin MD5Transform (md5Context.state, inputBlock.inputBlock, i); i := i + 64; end; index := 0; end else i := 0; // Buffer remaining input MD5_memcpy(md5Context.buffer, index, inputBlock.inputBlock, i, inputBlock.nSize - i); end; procedure MD5Final (var digest : array of Byte; md5Context : TMD5Context); var bits : Array [0..7] of Byte; index, padLen : Word; ibTemp : TInputBlock; begin // Save number of bits Encode (bits, md5context.Count, 0, 8); // Pad out to 56 mod 64. index := ((md5Context.count[0] shr 3) and $3f); if index < 56 then padLen := 56 - index else padLen := 120 - index; MD5_memcpy (ibTemp.inputBlock, 0, Padding, 0, 64); ibTemp.nSize := padLen; MD5Update (md5Context, ibTemp); // Append length (before padding) MD5_memcpy (ibTemp.inputBlock, 0, bits, 0, 8); ibTemp.nSize := 8; MD5Update (md5Context, ibTemp); // Store state in digest/ Encode (digest, md5Context.State, 0, 16); // Zeroize sensitive information. ///MD5_memset ((POINTER)context, 0, sizeof (*context)); end; function MD5Digest(s : String) : string; var md5Context : TMD5Context; ibTemp : TInputBlock; digest : Array [0..15] of Byte; retorno : string; i : Word; begin for i := 1 to Length(s) do begin ibTemp.InputBlock[i - 1] := Ord(s[i]); end; ibTemp.nSize := Length(s); MD5Init (md5Context); MD5Update (md5Context, ibTemp); MD5Final (digest, md5Context); retorno := ''; for i := 0 to 15 do retorno := retorno + LowerCase(Format('%.2x', [digest[i]])); MD5Digest := Retorno end; // -- iniciaçao da unit begin end.
unit VAClasses; interface uses Windows, Controls, Classes, SysUtils, Types, RTLConsts; type TVABaseMethodList = class(TObject) strict private FCode: TList; FData: TList; strict protected function GetMethod(index: integer): TMethod; property Code: TList read FCode; property Data: TList read FData; protected constructor Create; virtual; function IndexOf(const Method: TMethod): integer; procedure Add(const Method: TMethod); procedure Clear; function Count: integer; procedure Delete(index: integer); procedure Remove(const Method: TMethod); property Methods[index: integer]: TMethod read GetMethod; default; public destructor Destroy; override; end; TVAMethodList = class(TVABaseMethodList) public constructor Create; override; destructor Destroy; override; function IndexOf(const Method: TMethod): integer; procedure Add(const Method: TMethod); procedure Clear; function Count: integer; procedure Delete(index: integer); procedure Remove(const Method: TMethod); property Methods; end; TVALinkedMethodList = class(TVABaseMethodList) private FLinkedObjects: TList; public constructor Create; override; destructor Destroy; override; procedure Add(Obj: TObject; const Method: TMethod); function IndexOf(const obj: TObject): integer; procedure Clear; function Count: integer; procedure Delete(index: integer); procedure Remove(const obj: TObject); overload; function GetMethod(Obj: TObject): TMethod; // property Methods; end; // event fires before the component has acted on the notification TVANotifyEvent = procedure(AComponent: TComponent; Operation: TOperation) of object; TVANotificationEventComponent = class(TComponent) private FOnNotifyEvent: TVANotifyEvent; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor NotifyCreate(AOwner: TComponent; AOnNotifyEvent: TVANotifyEvent); virtual; property OnNotifyEvent: TVANotifyEvent read FOnNotifyEvent write FOnNotifyEvent; end; TVAListChangeEvent = procedure(Sender: TObject; Item: Pointer; Operation: TOperation) of object; TVAList = class(TList) private FOnChange: TVAListChangeEvent; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public property OnChange: TVAListChangeEvent read FOnChange write FOnChange; end; const DynaPropAccesibilityCaption = 1; type IVADynamicProperty = interface(IInterface) ['{1D1620E9-59D1-475D-94E9-FAE89A601D55}'] function SupportsDynamicProperty(PropertyID: integer): boolean; function GetDynamicProperty(PropertyID: integer): string; end; implementation { TVABaseMethodList } procedure TVABaseMethodList.Add(const Method: TMethod); begin if IndexOf(Method) < 0 then begin FCode.Add(Method.Code); FData.Add(Method.Data); end; end; procedure TVABaseMethodList.Clear; begin FCode.Clear; FData.Clear; end; function TVABaseMethodList.Count: integer; begin Result := FCode.Count; end; constructor TVABaseMethodList.Create; begin FCode := TList.Create; FData := TList.Create; end; procedure TVABaseMethodList.Delete(index: integer); begin FCode.Delete(index); FData.Delete(index); end; destructor TVABaseMethodList.Destroy; begin FreeAndNil(FCode); FreeAndNil(FData); inherited; end; function TVABaseMethodList.GetMethod(index: integer): TMethod; begin Result.Code := FCode[index]; Result.Data := FData[index]; end; function TVABaseMethodList.IndexOf(const Method: TMethod): integer; begin if assigned(Method.Code) and assigned(Method.data) and (FCode.Count > 0) then begin Result := 0; while((Result < FCode.Count) and ((FCode[Result] <> Method.Code) or (FData[Result] <> Method.Data))) do inc(Result); if Result >= FCode.Count then Result := -1; end else Result := -1; end; procedure TVABaseMethodList.Remove(const Method: TMethod); var idx: integer; begin idx := IndexOf(Method); if(idx >= 0) then begin FCode.Delete(idx); FData.Delete(idx); end; end; { TVAMethodList } procedure TVAMethodList.Add(const Method: TMethod); begin inherited Add(Method); end; procedure TVAMethodList.Clear; begin inherited Clear; end; function TVAMethodList.Count: integer; begin Result := inherited Count; end; constructor TVAMethodList.Create; begin inherited Create; end; procedure TVAMethodList.Delete(index: integer); begin inherited Delete(index); end; destructor TVAMethodList.Destroy; begin inherited; end; function TVAMethodList.IndexOf(const Method: TMethod): integer; begin Result := inherited IndexOf(Method); end; procedure TVAMethodList.Remove(const Method: TMethod); begin inherited Remove(Method); end; { TVANotificationEventComponent } procedure TVANotificationEventComponent.Notification(AComponent: TComponent; Operation: TOperation); begin if assigned(FOnNotifyEvent) then FOnNotifyEvent(AComponent, Operation); inherited; end; constructor TVANotificationEventComponent.NotifyCreate(AOwner: TComponent; AOnNotifyEvent: TVANotifyEvent); begin inherited Create(AOwner); FOnNotifyEvent := AOnNotifyEvent; end; { TVALinkedMethodList } procedure TVALinkedMethodList.Add(Obj: TObject; const Method: TMethod); begin if assigned(obj) and assigned(Method.Code) and (IndexOf(Obj) < 0) then begin FLinkedObjects.Add(Obj); Code.Add(Method.Code); Data.Add(Method.Data); end; end; procedure TVALinkedMethodList.Clear; begin FLinkedObjects.Clear; Code.Clear; Data.Clear; end; function TVALinkedMethodList.Count: integer; begin Result := FLinkedObjects.Count; end; constructor TVALinkedMethodList.Create; begin inherited; FLinkedObjects := TList.Create; end; procedure TVALinkedMethodList.Delete(index: integer); begin FLinkedObjects.Delete(index); Code.Delete(index); Data.Delete(index); end; destructor TVALinkedMethodList.Destroy; begin FreeAndNil(FLinkedObjects); inherited; end; function TVALinkedMethodList.GetMethod(Obj: TObject): TMethod; var idx: integer; begin idx := IndexOf(Obj); if idx < 0 then begin Result.Code := nil; Result.Data := nil; end else Result := Methods[idx]; end; function TVALinkedMethodList.IndexOf(const obj: TObject): integer; begin if assigned(obj) then Result := FLinkedObjects.IndexOf(obj) else Result := -1; end; procedure TVALinkedMethodList.Remove(const obj: TObject); var i: integer; begin i := IndexOf(obj); if i >= 0 then Delete(i); end; { TVAList } procedure TVAList.Notify(Ptr: Pointer; Action: TListNotification); begin if assigned(FOnChange) and (Ptr <> nil) then begin if Action = lnAdded then FOnChange(Self, Ptr, opInsert) else FOnChange(Self, Ptr, opRemove) end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.iOS.Devices; interface { The identifiers below should never contain a device generation or version number within the name. Device selection is based on the physical size of the display and not the generation or version of the device. } const siPhone = 'iPhone'; // iPhone with non retina display siPhoneRet = 'iPhoneRet'; // iPhone with retina display siPhone4in = 'iPhone4in'; // iPhone with 4 inch retina display siPhone47in = 'iPhone47in'; // iPhone with 4.7 inch retina display siPhone55in = 'iPhone55in'; // iPhone with 5.5 inch retina display siPod = 'iPod'; // iPod siPodRet = 'iPodRet'; // iPod with retina display siPod4in = 'iPod4in'; // iPod with 4in retina display siPad = 'iPad'; // iPad 1 & 2 siPadMini = 'iPadMini'; // iPad Mini siPadRet = 'iPadRet'; // iPad 3 & 4, iPad Mini with retina display procedure AddDevices; implementation uses System.Types, System.SysUtils, System.Devices; // Unlike the desktop "devices" which vary in near infinite proportions, mobile devices are relatively more limited. // Because of this, we can predefine the possible devices here without any "platform specific" input. // NOTE: This code must be able to run on Windows, so never, ever put platform specific code or references into this // unit. procedure AddDevices; begin TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Phone, siPhone, TSize.Create(480, 320), TSize.Create(480, 320), TOSVersion.TPlatform.pfiOS, 163 { Apple spec }); (* TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Phone, siPhoneRet, TSize.Create(960, 640), TSize.Create(480, 320), TOSVersion.TPlatform.pfiOS, 326 { Apple spec }); *) TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Phone, siPhone4in, TSize.Create(1136, 640), TSize.Create(568, 320), TOSVersion.TPlatform.pfiOS, 326 { Apple spec }); TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Phone, siPhone47in, TSize.Create(1334, 750), TSize.Create(667, 375), TOSVersion.TPlatform.pfiOS, 326 { Apple spec }); TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Phone, siPhone55in, TSize.Create(2208, 1242), TSize.Create(736, 414), TOSVersion.TPlatform.pfiOS, 489); (* TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.MediaPlayer, siPod, TSize.Create(480, 320), TSize.Create(480, 320), TOSVersion.TPlatform.pfiOS, 163 { Apple spec }); TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.MediaPlayer, siPodRet, TSize.Create(960, 640), TSize.Create(480, 320), TOSVersion.TPlatform.pfiOS, 326 { Apple spec }); TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.MediaPlayer, siPod4in, TSize.Create(1136, 640), TSize.Create(568, 320), TOSVersion.TPlatform.pfiOS, 326 { Apple spec }); TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Tablet, siPadMini, TSize.Create(2048, 1536), TSize.Create(1024, 768), TOSVersion.TPlatform.pfiOS, 326 { Apple spec });*) TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Tablet, siPad, TSize.Create(2048, 1536), TSize.Create(1024, 768), TOSVersion.TPlatform.pfiOS, 326 { Apple spec }); end; end.
unit OpenURLUtil; interface {$mode objfpc}{$h+} // Using Win32Proc binds the unit to LCL // to break the binding, check for Unicode Windows must be done manually // CarbonProc CreateCFString should also be replaced with MacOSAll code {$ifdef Windows} uses ShellAPI, Win32Proc; {$endif} {$ifdef LINUX} uses SysUtils, Unix; {$endif} {$ifdef Darwin} // LCLCarbon? uses MacOSAll, CarbonProc; {$endif} function OpenURLWide(const URLWide: WideString): Boolean; function OpenURLAnsi(const URLAnsi: AnsiString): Boolean; function OpenURL(const URLUtf8: String): Boolean; implementation function OpenURLWide(const URLWide: WideString): Boolean; begin Result := OpenURL(UTF8Encode(URLWide)); end; function OpenURLAnsi(const URLAnsi: AnsiString): Boolean; begin Result := OpenURL(AnsiToUtf8(URLAnsi)); end; {$IFDEF WINDOWS} function OpenURL(const URLUtf8: String): Boolean; var ws : WideString; ans : AnsiString; begin Result := false; if URLUtf8 = '' then Exit; if UnicodeEnabledOS then begin ws := UTF8Decode(URLUtf8); Result := ShellExecuteW(0, 'open', PWideChar(ws), nil, nil, 0) > 32; end else begin ans := Utf8ToAnsi(URLUtf8); // utf8 must be converted to Windows Ansi-codepage Result := ShellExecute(0, 'open', PAnsiChar(ans), nil, nil, 0) > 32; end; end; {$ENDIF} {$IFDEF LINUX} function OpenURL(const URLUtf8: string): Boolean; var Helper: string; begin Result := True; try Helper := ''; if fpsystem('which xdg-open') = 0 then Helper := 'xdg-open' else if FileExists('/etc/alternatives/x-www-browser') then Helper := '/etc/alternatives/x-www-browser' else if fpsystem('which firefox') = 0 then Helper := 'firefox' else if fpsystem('which konqueror') = 0 then Helper := 'konqueror' else if fpsystem('which opera') = 0 then Helper := 'opera' else if fpsystem('which mozilla') = 0 then Helper := 'mozilla'; if Helper <> '' then fpSystem(Helper + ' ' + URLUtf8 + '&') else Result := False; except end; end; {$ENDIF} {$IFDEF DARWIN} function OpenURL(const URLUtf8: string): Boolean; var cf : CFStringRef; url : CFURLRef; begin if URLUtf8 = '' then begin Result := false; Exit; end; CreateCFString(URLUtf8, cf); url := CFURLCreateWithString(nil, cf, nil); Result := LSOpenCFURLRef(url, nil) = 0; CFRelease(url); CFRelease(cf); end; {$ENDIF} end.
unit ServiceUnit; interface uses Windows, WinSvc; function ServiceGetStatus(sMachine, sService: PChar): DWORD; function ServiceStart(sMachine, sService : string ) : boolean; function ServiceStop(sMachine, sService : string ) : boolean; implementation function ServiceGetStatus(sMachine, sService: PChar): DWORD; {******************************************} {*** Parameters: ***} {*** sService: specifies the name of the service to open {*** sMachine: specifies the name of the target computer {*** ***} {*** Return Values: ***} {*** -1 = Error opening service ***} {*** 1 = SERVICE_STOPPED ***} {*** 2 = SERVICE_START_PENDING ***} {*** 3 = SERVICE_STOP_PENDING ***} {*** 4 = SERVICE_RUNNING ***} {*** 5 = SERVICE_CONTINUE_PENDING ***} {*** 6 = SERVICE_PAUSE_PENDING ***} {*** 7 = SERVICE_PAUSED ***} {******************************************} var SCManHandle, SvcHandle: SC_Handle; SS: TServiceStatus; dwStat: DWORD; begin dwStat := 0; // Open service manager handle. SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT); if (SCManHandle > 0) then begin SvcHandle := OpenService(SCManHandle, sService, SERVICE_QUERY_STATUS); // if Service installed if (SvcHandle > 0) then begin // SS structure holds the service status (TServiceStatus); if (QueryServiceStatus(SvcHandle, SS)) then dwStat := ss.dwCurrentState; CloseServiceHandle(SvcHandle); end; CloseServiceHandle(SCManHandle); end; Result := dwStat; end; function ServiceStart(sMachine, sService : string ) : boolean; // // start service // // return TRUE if successful // // sMachine: // machine name, ie: \SERVER // empty = local machine // // sService // service name, ie: Alerter // var // // service control // manager handle schm, // // service handle schs : SC_Handle; // // service status ss : TServiceStatus; // // temp char pointer psTemp : PChar; // // check point dwChkP : DWord; begin ss.dwCurrentState := 50; // connect to the service // control manager schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT); // if successful... if(schm > 0)then begin // open a handle to // the specified service schs := OpenService( schm, PChar(sService), // we want to // start the service and SERVICE_START or // query service status SERVICE_QUERY_STATUS); // if successful... if(schs > 0)then begin psTemp := Nil; if(StartService( schs, 0, psTemp))then begin // check status if(QueryServiceStatus( schs, ss))then begin while(SERVICE_RUNNING <> ss.dwCurrentState)do begin // // dwCheckPoint contains a // value that the service // increments periodically // to report its progress // during a lengthy // operation. // // save current value // dwChkP := ss.dwCheckPoint; // // wait a bit before // checking status again // // dwWaitHint is the // estimated amount of time // the calling program // should wait before calling // QueryServiceStatus() again // // idle events should be // handled here... // Sleep(ss.dwWaitHint); if(not QueryServiceStatus( schs, ss))then begin // couldn't check status // break from the loop break; end; if(ss.dwCheckPoint < dwChkP)then begin // QueryServiceStatus // didn't increment // dwCheckPoint as it // should have. // avoid an infinite // loop by breaking break; end; end; end; end; // close service handle CloseServiceHandle(schs); end; // close service control // manager handle CloseServiceHandle(schm); end; // return TRUE if // the service status is running Result := SERVICE_RUNNING = ss.dwCurrentState; end; function ServiceStop(sMachine, sService : string ) : boolean; // // stop service // // return TRUE if successful // // sMachine: // machine name, ie: \SERVER // empty = local machine // // sService // service name, ie: Alerter // var // // service control // manager handle schm, // // service handle schs : SC_Handle; // // service status ss : TServiceStatus; // // check point dwChkP : DWord; begin // connect to the service // control manager schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT); // if successful... if(schm > 0)then begin // open a handle to // the specified service schs := OpenService( schm, PChar(sService), // we want to // stop the service and SERVICE_STOP or // query service status SERVICE_QUERY_STATUS); // if successful... if(schs > 0)then begin if(ControlService( schs, SERVICE_CONTROL_STOP, ss))then begin // check status if(QueryServiceStatus( schs, ss))then begin while(SERVICE_STOPPED <> ss.dwCurrentState)do begin // // dwCheckPoint contains a // value that the service // increments periodically // to report its progress // during a lengthy // operation. // // save current value // dwChkP := ss.dwCheckPoint; // // wait a bit before // checking status again // // dwWaitHint is the // estimated amount of time // the calling program // should wait before calling // QueryServiceStatus() again // // idle events should be // handled here... // Sleep(ss.dwWaitHint); if(not QueryServiceStatus( schs, ss))then begin // couldn't check status // break from the loop break; end; if(ss.dwCheckPoint < dwChkP)then begin // QueryServiceStatus // didn't increment // dwCheckPoint as it // should have. // avoid an infinite // loop by breaking break; end; end; end; end; // close service handle CloseServiceHandle(schs); end; // close service control // manager handle CloseServiceHandle(schm); end; // return TRUE if // the service status is stopped Result := SERVICE_STOPPED = ss.dwCurrentState; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit BindCompFMXReg; interface uses System.Classes, System.Generics.Collections, Data.Bind.Components, Data.Bind.DBLinks; type TDBBindLinkAssocations = class private class var FAssociations: TDictionary<TContainedBindCompClass, TList<TComponentClass>>; public class constructor Create; class destructor Destroy; class function SupportedBindings( AControl: TComponent): TArray<TContainedBindCompClass>; static; class procedure AddAssociation(ABindCompType: TContainedBindCompClass; AControlType: TComponentClass); class procedure AddAssociations( const ABindCompTypes: array of TContainedBindCompClass; const AControlTypes: array of TComponentClass); class procedure RemoveAssociations( const ABindCompTypes: array of TContainedBindCompClass); class procedure RemoveAssociation( ABindCompType: TContainedBindCompClass); class function SupportsControl( ABindLink: TContainedBindComponent; AControl: TComponent; out AHasAssociations: Boolean): Boolean; overload; class function SupportsControl( ABindLinkClass: TContainedBindCompClass; AControl: TComponent; out AHasAssociations: Boolean): Boolean; overload; end; procedure Register; implementation uses DsnConst, System.UITypes, Fmx.Bind.Navigator, Data.Bind.Consts, Fmx.Bind.DBLinks, // Initialization Fmx.Bind.DBEngExt, Fmx.Bind.Editors, BindCompReg, DesignIntf, FMX.Types, BindCompDsnResStrs, BindCompNewDBLinkForm, Data.Bind.DBScope, System.Character, Data.DB, FMX.Controls, FMX.Dialogs, FMX.Edit, FMX.Layouts, FMX.ListBox, FMX.ListView, FMX.StdCtrls, FMX.Memo, FMX.Grid, VCL.Forms, DesignEditors, System.TypInfo, System.SysUtils, BindCompDesigners, BindCompDBReg, BindCompEdit, Fmx.Colors, FMX.Bind.Grid, BindGridReg, Data.Bind.Grid, Fmx.Bind.GenData, System.Actions, BindCompFMXResources; // register type TBindFMXDBControlSelectionEditor = class(TSelectionEditor) public procedure RequiresUnits(Proc: TGetStrProc); override; end; TBindDBControlProperty = class(TComponentProperty) private FTempStrings: TStrings; procedure AddTempString(const S: string); public procedure GetValues(Proc: TGetStrProc); override; end; TFMXControlFrameFactory = class(TControlClassFactory) public function GetEnabled: Boolean; override; function IsControl(AComponent: TComponent): Boolean; override; function ControlClasses: TArray<TComponentClass>; override; function GetControlType(AComponentClass: TComponentClass): string; override; function CreateControl(AClass: TComponentClass; AOptions: TControlClassFactory.TOptions; AProperties: TStrings): TComponent; override; function SupportsOption(AClass: TComponentClass; AOption: TControlClassFactory.TOption): Boolean; override; end; TFMXNavigatorFactory = class(TNavigatorFactory) protected function IsNavigatorFor(AComponent1, AComponent2: TComponent): Boolean; override; function GetEnabled: Boolean; override; public function CreateControl(AOptions: TControlClassFactory.TOptions; AProperties: TStrings): TComponent; override; end; const sFmx = 'fmx'; procedure RegisterDBBindLinkAssociations( const ABindCompTypes: array of TContainedBindCompClass; const AControlTypes: array of TComponentClass); forward; procedure RegisterDBBindLinkAssociations( const ABindCompTypes: array of TContainedBindCompClass; const AControlTypes: array of TComponentClass); begin TDBBindLinkAssocations.AddAssociations(ABindCompTypes, AControlTypes); end; class procedure TDBBindLinkAssocations.AddAssociation (ABindCompType: TContainedBindCompClass; AControlType: TComponentClass); var LList: TList<TComponentClass>; begin if not FAssociations.TryGetValue(ABindCompType, LList) then begin LList := TList<TComponentClass>.Create; FAssociations.Add(ABindCompType, LList); end; LList.Add(AControlType); end; class procedure TDBBindLinkAssocations.AddAssociations (const ABindCompTypes: array of TContainedBindCompClass; const AControlTypes: array of TComponentClass); var LBindCompClass: TContainedBindCompClass; LControlClass: TComponentClass; begin for LBindCompClass in ABindCompTypes do for LControlClass in AControlTypes do TDBBindLinkAssocations.AddAssociation(LBindCompClass, LControlClass); end; { TDBBindLinkAssocations } class constructor TDBBindLinkAssocations.Create; begin FAssociations := TObjectDictionary<TContainedBindCompClass, TList<TComponentClass>>.Create([doOwnsValues]); end; class destructor TDBBindLinkAssocations.Destroy; begin FAssociations.Free; end; class procedure TDBBindLinkAssocations.RemoveAssociation( ABindCompType: TContainedBindCompClass); begin if FAssociations.ContainsKey(ABindCompType) then FAssociations.Remove(ABindCompType); end; class procedure TDBBindLinkAssocations.RemoveAssociations( const ABindCompTypes: array of TContainedBindCompClass); var LBindCompClass: TContainedBindCompClass; begin for LBindCompClass in ABindCompTypes do RemoveAssociation(LBindCompClass); end; class function TDBBindLinkAssocations.SupportsControl( ABindLinkClass: TContainedBindCompClass; AControl: TComponent; out AHasAssociations: Boolean): Boolean; var LList: TList<TComponentClass>; LControlClass: TComponentClass; begin AHasAssociations := False; Result := False; if FAssociations.TryGetValue(ABindLinkClass, LList) then begin AHasAssociations := True; for LControlClass in LList do begin if AControl.ClassType.InheritsFrom(LControlClass) then Exit(True); end; end; end; class function TDBBindLinkAssocations.SupportsControl( ABindLink: TContainedBindComponent; AControl: TComponent; out AHasAssociations: Boolean): Boolean; begin Result := SupportsControl(TContainedBindCompClass(ABindLink.ClassType), AControl, AHasAssociations); end; class function TDBBindLinkAssocations.SupportedBindings( AControl: TComponent): TArray<TContainedBindCompClass>; var // LList: TList<TComponentClass>; LControlClass: TComponentClass; LResult: TList<TContainedBindCompClass>; LPair: TPair<TContainedBindCompClass, TList<TComponentClass>>; begin LResult := TList<TContainedBindCompClass>.Create; try for LPair in FAssociations do begin for LControlClass in LPair.Value do begin if AControl.ClassType.InheritsFrom(LControlClass) then LResult.Add(LPair.Key); end; end; Result := LResult.ToArray; finally LResult.Free; end; end; procedure UnregisterDBBindLinkAssociations( const ABindCompTypes: array of TContainedBindCompClass); var LBindCompClass: TContainedBindCompClass; begin for LBindCompClass in ABindCompTypes do TDBBindLinkAssocations.RemoveAssociations(LBindCompClass) end; type THasExistingDBLink = class private FStrings: TStrings; procedure AddString(const S: string); public constructor Create; destructor Destroy; override; function HasExistingDBLink(ADesigner: IDesigner; AControl: TComponent): Boolean; end; constructor THasExistingDBLink.Create; begin FStrings := TStringList.Create; end; procedure THasExistingDBLink.AddString(const S: string); begin FStrings.Add(S); end; function THasExistingDBLink.HasExistingDBLink(ADesigner: IDesigner; AControl: TComponent): Boolean; var S: string; LDataBinding: TBaseBindDBControlLink; begin FStrings.Clear; ADesigner.GetComponentNames(GetTypeData(TypeInfo(TBaseBindDBControlLink)), AddString); for S in FStrings do begin LDataBinding := TBaseBindDBControlLink(ADesigner.GetComponent(S)); if LDataBinding.ControlComponent = AControl then Exit(True); end; Result := False; end; destructor THasExistingDBLink.Destroy; begin inherited; FStrings.Free; end; { TBindDBControlProperty } procedure TBindDBControlProperty.AddTempString(const S: string); begin FTempStrings.Add(S); end; procedure TBindDBControlProperty.GetValues(Proc: TGetStrProc); var LComponent: TComponent; LHasAssociations: Boolean; LBindComponent: TContainedBindComponent; S: string; begin if not (GetComponent(0) is TContainedBindComponent) then begin inherited GetValues(Proc); Exit; end; LBindComponent := TContainedBindComponent(GetComponent(0)); FTempStrings := TStringList.Create; try Designer.GetComponentNames(GetTypeData(GetPropType), AddTempString); for S in FTempStrings do begin LComponent := Designer.GetComponent(S) as TComponent; if TDBBindLinkAssocations.SupportsControl(LBindComponent, LComponent, LHasAssociations) or (not LHasAssociations) then Proc(S); end; finally FTempStrings.Free; end; end; type TBindDBFieldLinkDesignerFMX_NoParse = class(TBindDBFieldLinkDesigner_NoParse) protected function CanBindComponent(ADataBindingClass: TContainedBindCompClass; AComponent: TComponent; ADesigner: IInterface): Boolean; override; end; TBindDBFieldLinkDesignerFMX = class(TBindDBFieldLinkDesigner) protected function CanBindComponent(ADataBindingClass: TContainedBindCompClass; AComponent: TComponent; ADesigner: IInterface): Boolean; override; end; type TContainedBindComponentSelectionEditor = class(TSelectionEditor) public procedure RequiresUnits(Proc: TGetStrProc); override; end; procedure TContainedBindComponentSelectionEditor.RequiresUnits(Proc: TGetStrProc); var I: Integer; LContainedBindComponent: TContainedBindComponent; begin for I := 0 to Designer.Root.ComponentCount - 1 do begin if Designer.Root.Components[i] is TContainedBindComponent then begin LContainedBindComponent := TContainedBindComponent(Designer.Root.Components[i]); if Assigned(LContainedBindComponent.ControlComponent) then if LContainedBindComponent.ControlComponent is TControl then begin Proc('Fmx.Bind.Editors'); Exit; end; end; end; end; type TBindNavigatorSelectionEditor = class(TSelectionEditor) public procedure RequiresUnits(Proc: TGetStrProc); override; end; procedure TBindNavigatorSelectionEditor.RequiresUnits(Proc: TGetStrProc); begin Proc('Data.Bind.Controls'); end; procedure Register; const sFieldName = 'FieldName'; begin ForceDemandLoadState(dlDisable); // Always register factories RegisterControlFrameFactory(TFMXControlFrameFactory); // Create wizard page to create control RegisterControlFrameFactory(TFMXNavigatorFactory); // Create TBindNavigator RegisterComponents(SBindingComponentsCategory, [TBindNavigator]); RegisterNoIcon([TBindDBEditLink, TBindDBTextLink, TBindDBListLink, TBindDBImageLink, TBindDBMemoLink, TBindDBCheckLink, TBindDBGridLink]); RegisterBindComponents(SDataBindingsCategory_DBLinks, [TBindDBEditLink, TBindDBTextLink, TBindDBListLink, TBindDBImageLink, TBindDBMemoLink, TBindDBCheckLink, TBindDBGridLink]); GroupDescendentsWith(TBaseBindDBFieldControlLink, TFmxObject); GroupDescendentsWith(TBaseBindDBGridControlLink, TFmxObject); RegisterDBBindLinkAssociations( [TBindDBEditLink], [TCustomEdit]); RegisterDBBindLinkAssociations( [TBindDBTextLink], [TLabel]); RegisterDBBindLinkAssociations( [TBindDBListLink], [TListBox, TComboBox]); RegisterDBBindLinkAssociations( [TBindDBMemoLink], [TMemo]); RegisterDBBindLinkAssociations( [TBindDBCheckLink], [TCheckBox]); RegisterDBBindLinkAssociations( [TBindDBImageLink], [TImageControl]); RegisterDBBindLinkAssociations( [TBindDBGridLink], //[TStringGrid, TGrid]); [TStringGrid]); RegisterBindCompDesigner(TCustomBindDBTextLink, TBindDBFieldLinkDesignerFMX_NoParse.Create); RegisterBindCompDesigner(TCustomBindDBImageLink, TBindDBFieldLinkDesignerFMX_NoParse.Create); RegisterBindCompDesigner(TBaseBindDBFieldControlLink, TBindDBFieldLinkDesignerFMX.Create); RegisterBindCompDesigner(TBaseBindDBGridControlLink, TBindDBFieldLinkDesignerFMX.Create); // Remove Link to Field... from object inspector/popup menu // RegisterBindCompFactory(TBindDBLinkDialogFactory.Create); // Filter controls in drop down list RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBEditLink, 'EditControl', TBindDBControlProperty); RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBTextLink, 'TextControl', TBindDBControlProperty); RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBListLink, 'ListControl', TBindDBControlProperty); RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBMemoLink, 'MemoControl', TBindDBControlProperty); RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBCheckLink, 'CheckControl', TBindDBControlProperty); RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBImageLink, 'ImageControl', TBindDBControlProperty); RegisterPropertyEditor(TypeInfo(TStyledControl), TCustomBindDBGridLink, 'GridControl', TBindDBControlProperty); // Add BindingsList used methods/converters required units to the uses list RegisterSelectionEditor(TBaseBindDBFieldControlLink, TBindFMXDBControlSelectionEditor); RegisterSelectionEditor(TBaseBindDBGridControlLink, TBindFMXDBControlSelectionEditor); RegisterComponentEditor(TBindDBGridLink, TBindDBGridLinkEditor); // Add "Live Bindings" to controls RegisterSelectionEditor(Fmx.Controls.TControl, TAddDataBindingsPropertyFilter); // Verbs to add data bindings RegisterSelectionEditor(Fmx.Types.TFmxObject, TBindCompFactorySelectionEditor); // Add "Columns..." verb to grids referenced by TDBGridLink RegisterSelectionEditor(TCustomGrid, TBindDBGridColumnsSelectionEditor); // Add "Columns..." verb to grids referenced by TLinkGridToDataSource RegisterSelectionEditor(TCustomGrid, TLinkGridToDataSourceGridSelectionEditor); // Add "Fill List..." verb to list control referenced by TLinkGridToDataSource RegisterSelectionEditor(TCustomListBox, TLinkFillSelectionEditor); // Add "Fill List..." verb to list control referenced by TLinkGridToDataSource RegisterSelectionEditor(TCustomListView, TLinkFillSelectionEditor); // Use Fmx.Bind.Editors RegisterSelectionEditor(TContainedBindComponent, TContainedBindComponentSelectionEditor); RegisterSelectionEditor(TBindNavigator, TBindNavigatorSelectionEditor); RegisterPropertyEditor(TypeInfo(TBaseLinkingBindSource), TBindNavigator, 'DataSource', TLinkingBindScopePropertyEditor); RegisterActions('LiveBindings', [TFMXBindNavigateFirst, TFMXBindNavigatePrior, TFMXBindNavigateNext, TFMXBindNavigateLast, TFMXBindNavigateInsert, TFMXBindNavigateDelete, TFMXBindNavigateEdit, TFMXBindNavigatePost, TFMXBindNavigateCancel, TFMXBindNavigateRefresh, TFMXBindNavigateApplyUpdates, TFMXBindNavigateCancelUpdates], TFMXBindSourceActions); end; { TBindDBControlSelectionEditor } procedure TBindFMXDBControlSelectionEditor.RequiresUnits(Proc: TGetStrProc); begin Proc('Fmx.Bind.Editors'); Proc('Fmx.Bind.DBEngExt'); // Proc('Data.Bind.EngExt'); // Added by other selection editor end; { TBindDBFieldLinkDesignerFMX_NoParse } function TBindDBFieldLinkDesignerFMX_NoParse.CanBindComponent( ADataBindingClass: TContainedBindCompClass; AComponent: TComponent; ADesigner: IInterface): Boolean; var LHasAssociations: Boolean; begin Result := TDBBindLinkAssocations.SupportsControl( ADataBindingClass, AComponent, LHasAssociations); if Result then with THasExistingDBLink.Create do try Result := not HasExistingDBLink(ADesigner as IDesigner, AComponent); finally Free; end; end; { TBindDBFieldLinkDesignerFMX } function TBindDBFieldLinkDesignerFMX.CanBindComponent( ADataBindingClass: TContainedBindCompClass; AComponent: TComponent; ADesigner: IInterface): Boolean; var LHasAssociations: Boolean; begin Result := TDBBindLinkAssocations.SupportsControl( ADataBindingClass, AComponent, LHasAssociations); if Result then with THasExistingDBLink.Create do try Result := not HasExistingDBLink(ADesigner as IDesigner, AComponent); finally Free; end; end; { TFXMControlFrameFactory } function TFMXControlFrameFactory.ControlClasses: TArray<TComponentClass>; var LList: TList<TComponentClass>; LComponentClass: TComponentClass; begin LList := TList<TComponentClass>.Create; try LList.AddRange(Data.Bind.Components.GetControlValueClasses(sFmx, True)); // Do not localize for LComponentClass in GetGridClasses(sFmx) do if not LList.Contains(LComponentClass) then LList.Add(LComponentClass); Result := LList.ToArray; finally LList.Free; end; end; procedure RenameControl(const ADesigner: IDesigner; AControl: TControl; const ASuffix: string); var LName: string; begin LName := AControl.Name; while (Length(LName) > 0) and (LName[Length(LName)].IsDigit) do Delete(LName, Length(LName), 1); LName := BindCompReg.CreateUniqueComponentName(ADesigner.Root, LName, ASuffix); if ADesigner.Root.FindComponent(LName) = nil then AControl.Name := LName; end; function TFMXControlFrameFactory.CreateControl(AClass: TComponentClass; AOptions: TControlClassFactory.TOptions; AProperties: TStrings): TComponent; var LControl: TControl; LLabel: TLabel; LControlClass: TComponentClass; LCaption: string; begin Result := nil; LControlClass := AClass; if LControlClass <> nil then begin LControl := Designer.CreateComponent(LControlClass, Designer.Root, 0, 0, 0, 0) as TControl; if LControl is TMemo then // Memo clips owned labels Exclude(AOptions, TControlClassFactory.TOption.optLabel); if TControlClassFactory.TOption.optSuffix in AOptions then RenameControl(Designer, LControl, AProperties.Values[TControlClassFactory.sSuffix]); Result := LControl; if TControlClassFactory.TOption.optLabel in AOptions then begin LLabel := Designer.CreateComponent(TLabel, nil, 0, 0, 0, 0) as TLabel; if TControlClassFactory.TOption.optSuffix in AOptions then RenameControl(Designer, LLabel, AProperties.Values[TControlClassFactory.sSuffix]); LLabel.Parent := LControl; LLabel.Position.Y := 1.0 - LLabel.Height; LLabel.Position.X := 0; LLabel.WordWrap := False; if AProperties <> nil then LCaption := AProperties.Values[sLabelCaption]; if LCaption = '' then LLabel.Text := LControl.Name else LLabel.Text := LCaption; end; end; end; function TFMXControlFrameFactory.GetControlType( AComponentClass: TComponentClass): string; var LComponentClass: TComponentClass; begin for LComponentClass in GetGridClasses(sFmx) do if LComponentClass = AComponentClass then Exit(TControlClassFactory.TControlTypes.sGrid); Result := TControlClassFactory.TControlTypes.sStandard; end; function TFMXControlFrameFactory.GetEnabled: Boolean; begin Result := SameText(Designer.DesignerExtention, sFmx); end; function TFMXControlFrameFactory.IsControl(AComponent: TComponent): Boolean; var LPropertyName: string; LWritable: Boolean; begin Result := (GetControlType(TComponentClass(AComponent.ClassType)) = TControlClassFactory.TControlTypes.sGrid) or (GetControlValuePropertyName(AComponent, LPropertyName, LWritable) and LWritable); end; function TFMXControlFrameFactory.SupportsOption(AClass: TComponentClass; AOption: TControlClassFactory.TOption): Boolean; begin Result := False; case AOption of optNoLabel: Result := True; optLabel: // Adding a label to a grid interferes will columns Result := not AClass.InheritsFrom(TCustomGrid) and //Adding a label to a Memo interferes with the memo text not AClass.InheritsFrom(TMemo); optSuffix: Result := True; else Assert(False); end; end; //procedure TFMXControlFrameFactory.ApplyOption(AComponent: TComponent; AOptions: TControlClassFactory.TOptions; AProperties: TStrings); //begin // Assert(False); //end; { TFMXNavigatorFactory } function TFMXNavigatorFactory.CreateControl(AOptions: TControlClassFactory.TOptions; AProperties: TStrings): TComponent; var LControl: TBindNavigator; LControlClass: TComponentClass; LName: string; begin Result := nil; LControlClass := TBindNavigator; if LControlClass <> nil then begin LControl := Self.Designer.CreateComponent(LControlClass, Designer.Root, 0, 0, 0, 0) as TBindNavigator; if TControlClassFactory.TOption.optSuffix in AOptions then begin LName := 'Navigator' + AProperties.Values[TControlClassFactory.sSuffix]; if Designer.Root.FindComponent(LName) = nil then LControl.Name := LName; end; LControl.DataSource := Self.BindScope; Designer.Modified; Result := LControl; end; end; function TFMXNavigatorFactory.GetEnabled: Boolean; begin Result := SameText(Self.Designer.DesignerExtention, sFmx); end; function TFMXNavigatorFactory.IsNavigatorFor(AComponent1, AComponent2: TComponent): Boolean; begin if AComponent1 is TBindNavigator then Result := TBindNavigator(AComponent1).DataSource = AComponent2 else Result := False; end; end.
unit main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,system.Types, Vcl.Buttons, Vcl.Grids, ComObj ; type //===========================================CLASS CHARGE Charge = class private _q : real; _pos : TPoint; _checked : boolean; _color : TColor; public constructor New(q : real; pos: TPoint); end; //===========================================CLASS SPACE Space = class private _charges : array of Charge; _cntCharges : integer; public _canvas : TCanvas; constructor New(canvas : TCanvas; gridPeriod : integer); procedure PointMove(x0:integer;y0:integer;vx0:real;vy0:real); procedure AddCharge(position:tpoint;chargeq:real); procedure RemoveCharge(numbercharge:integer); procedure MoveCharge(numbercharge:integer); procedure Draw(linenumber:array of integer;DropOut:integer); procedure DrawGrid(gridperiod:integer); procedure redraw; procedure scopedraw(point1:tpoint;color:tcolor); procedure opilki; procedure LineFromPoint(pointdraw:tpoint); procedure gridtospace(stringgrid1:tstringgrid); function colour(eint:real):tcolor; end; //==================================================== TfMain = class(TForm) pbMain: TPaintBox; btndelete: TBitBtn; Panel1: TPanel; labelededit1: TLabeledEdit; Button1: TButton; StringGrid1: TStringGrid; exitbtn: TBitBtn; btnaccept: TBitBtn; BitBtn1: TBitBtn; Panel2: TPanel; Label1: TLabel; savebutton: TBitBtn; loadbutton: TBitBtn; statbtn: TButton; Button2: TButton; RadioButton1: TRadioButton; RadioButton2: TRadioButton; Image1: TImage; RadioButton3: TRadioButton; TrackBar1: TTrackBar; Label2: TLabel; Label3: TLabel; ProgressBar1: TProgressBar; TrackBar2: TTrackBar; Label4: TLabel; Label5: TLabel; Label6: TLabel; procedure CleanScreen; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure pbMainPaint(Sender: TObject); procedure pbMainClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure statbtnClick(Sender: TObject); procedure btndeleteClick(Sender: TObject); procedure exitbtnClick(Sender: TObject); procedure btnacceptClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); function foolproof(labele1:tlabelededit):real; procedure savebuttonClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure labelededit1Change(Sender: TObject); procedure pbMainDblClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2KeyPress(Sender: TObject; var Key: Char); procedure exitbtnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure exitbtnEnter(Sender: TObject); procedure Button1Enter(Sender: TObject); procedure btndeleteEnter(Sender: TObject); procedure loadbuttonClick(Sender: TObject); function degree(x:real;y:integer):real; { Private declarations } public { Public declarations } end; var excel:variant; fMain: TfMain; chargeq:real; MySpace : Space; gridperiod:integer ; pt:tpoint; point0,point1:tpoint; implementation {$R *.dfm} uses Unit2, Unit4; constructor Charge.New(q: real; pos: TPoint); begin self._q := q; self._pos := pos; if(q<0)then self._color := clBlue else self._color := clRed; end; function SaveAsExcelFile(stringGrid: TstringGrid; FileName: string): Boolean; const xlWBATWorksheet = -4167; var Row, Col: Integer; GridPrevFile: string; XLApp, Sheet: OLEVariant; begin Result := False; XLApp := CreateOleObject('Excel.Application'); try XLApp.Visible := False; XLApp.Workbooks.Add(xlWBatWorkSheet); Sheet := XLApp.Workbooks[1].WorkSheets[1]; Sheet.Name := 'My Sheet Name'; for col := 0 to stringGrid.ColCount - 1 do for row := 0 to stringGrid.RowCount - 1 do Sheet.Cells[row + 1, col + 1] := stringGrid.Cells[col, row]; try XLApp.Workbooks[1].SaveAs(FileName); Result := True; except // КАКАЯ БЛИН ОШИБКА!!!!!!! end; finally if not VarIsEmpty(XLApp) then begin XLApp.DisplayAlerts := False; XLApp.Quit; XLAPP := Unassigned; Sheet := Unassigned; end; end; end; function Tfmain.degree(x: Real; y: Integer):Real; var i:integer; j:real; begin j:=1; if y>=0 then begin for i := 0 to y-1 do begin j:=j*x; end; end else begin for i := 0 to y+1 do begin j:=j/x; end; end; result:=j end; procedure TfMain.BitBtn1Click(Sender: TObject); begin panel1.Visible:=false; myspace.scopedraw(point1,clwhite); pbmain.Canvas.Pen.Color:=clblack; pbmain.canvas.pen.Width:=1; myspace.DrawGrid(20); myspace.redraw; end; procedure TfMain.btnacceptClick(Sender: TObject); begin chargeq:=FOOLPROOF(LABELEDEDIT1); myspace.addcharge(pOINt1,chargeq); panel1.Visible:=false; pbmain.canvas.Pen.Color:=clwhite; pbmain.canvas.pen.Width:=5; myspace.scopedraw(point1,clwhite); myspace.redraw; myspace.DrawGrid(20); statbtn.click; end; procedure Space.PointMove(x0:integer;y0:integer;vx0:real;vy0:real); var counter2,counter,k:integer; x,y:real; q:real; f,dt,dx,dy:real; cosa,sina,m:real; v,l,vx,vy,dvx,dvy:real; r,e,ex,ey,eint:real; begin self._canvas.Ellipse(x0,y0,x0+5,y0+10); m:=1; q:=1000 ; dt:=0.0001; k:=0; x:=x0; y:=y0; vx:=vx0; vy:=vy0; k:=0; for k := 0 to 1900000 do begin ex:=0; ey:=0; eint:=0; for counter2 := 0 to self._cntcharges-1 do //through oharges influence begin r:=sqrt(sqr(self._charges[counter2]._pos.x-x)+sqr(self._charges[counter2]._pos.y-y)); if r<>0 then cosa:=(x-self._charges[counter2]._pos.x )/r ; if r<>0 then sina:=(y-self._charges[counter2]._pos.y )/r ; if (r<>0) then begin e:=self._charges[counter2]._q*(1/fmain.degree(r/10,fmain.Trackbar2.Position) ); end; ex:=ex+(e)*cosa; ey:=ey+(e)*sina; end; //eint:=sqrt(sqr(ex)+sqr(ey)); vx:=vx+ex*dt*q/m; vy:=vy+ey*dt*q/m; x:=x+vx*dt; y:=y+vy*dt; self._canvas.Pixels[round(x),round(y)]:=clRed; end; vx:=0; vy:=0; end; procedure TfMain.btnClearClick(Sender: TObject); var numbercharge:integer; begin myspace.RemoveCharge(numbercharge); end; procedure TfMain.btndeleteClick(Sender: TObject); begin setlength(myspace._charges,0); myspace._cntCharges:=0; pbmain.Canvas.Rectangle(0,0,pbmain.Width,pbmain.Height); pbmain.Canvas.FloodFill(pbmain.width,pbmain.height,clwhite,fsborder); pbmain.Canvas.Pen.Width:=1; pbmain.Canvas.Pen.Color:=clblack; myspace.DrawGrid(20); statbtn.Click; end; procedure TfMain.btndeleteEnter(Sender: TObject); begin image1.Left:=btndelete.Left-100; image1.top:=btndelete.Top; end; procedure TfMain.Button1Click(Sender: TObject); var stuff:array of integer ; i:integer; begin //fmain.CleanScreen; setlength(stuff,100); for i := 0 to 99 do stuff[i]:=trackbar1.Position; if (radiobutton2.Checked=true) or (radiobutton3.Checked=true) then myspace.Draw(stuff,5 ); if (radiobutton1.Checked=true) then myspace.opilki; for i := 0 to 0 do myspace.PointMove(400,200+20*i,1000,0); end; procedure TfMain.Button1Enter(Sender: TObject); begin image1.Left:=button1.Left-100; image1.top:=button1.Top; end; procedure TfMain.Button2Click(Sender: TObject); begin panel2.visible:=false; myspace.RemoveCharge(myspace._cntCharges-1); //bitbtn1.Click; end; procedure TfMain.Button2KeyPress(Sender: TObject; var Key: Char); begin if key=#27 then button2.Click; end; procedure TfMain.Button3Click(Sender: TObject); begin myspace.opilki end; procedure TfMain.CleanScreen; begin pbmain.Canvas.Rectangle(0,0,pbmain.Width,pbmain.Height); pbmain.Canvas.FloodFill(round(pbmain.width/2),round(pbmain.height/2),clwhite,fsborder); myspace.DrawGrid(20); myspace.redraw; end; procedure TfMain.exitbtnClick(Sender: TObject); begin fmain.Close; form2.show; end; procedure TfMain.exitbtnEnter(Sender: TObject); begin image1.Left:=exitbtn.Left-100; image1.Top:=exitbtn.Top; end; procedure TfMain.exitbtnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (panel1.Visible=false) and (panel2.Visible=false) then begin if key=vk_f1 then form4.show; pbmain.Canvas.pen.color:=clwhite; pbmain.Canvas.pen.width:=1; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); pbmain.Canvas.Pen.Style:=pssolid; pbmain.Canvas.pen.Color:=clsilver; pbmain.Canvas.MoveTo(point1.X-5,point1.Y); pbmain.Canvas.lineTo(point1.X+5,point1.Y); pbmain.Canvas.MoveTo(point1.X,point1.Y-5); pbmain.Canvas.lineTo(point1.X,point1.Y+5); pbmain.Canvas.pen.width:=1; if (key=vk_right) and (point1.X<=pbmain.Width) then point1.x:=point1.x+20; //arrow controls if (key=vk_down)and (point1.Y<=pbmain.Height) then point1.y:=point1.y+20; if (key=vk_left) and (point1.x>=0) then point1.x:=point1.x-20; if (key=vk_up)and (point1.y>=0) then point1.y:=point1.y-20; if key=vk_f7 then myspace.LineFromPoint(point1); if key=vk_f4 then btndelete.Click; if key=vk_f2 then savebutton.Click; if key=vk_f3 then loadbutton.Click; pbmain.Canvas.pen.Color:=clred; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); end; end; function TfMain.foolproof(labele1: tlabelededit): real; VAR isOk:boolean; i: Integer; begin try result:=strtofloat(labele1.Text) except panel2.Left:=point1.X; panel2.Top:=point1.Y; panel2.visible:=true; result:=0; end; end; procedure TfMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin { try Excel.Quit; except end; CanClose:=True; Excel:=Unassigned; } end; procedure TfMain.FormCreate(Sender: TObject); begin MySpace := Space.New(pbMain.Canvas,10); point1:=point(0,0) end; procedure TfMain.FormKeyPress(Sender: TObject; var Key: Char); var i:integer;//simple counter z:integer;//what charge to delete; begin if panel2.Visible=true then begin if key=#27 then button2.Click; end else begin if PANEL1.Visible=TRUE then begin if (key=#101) and (trackbar1.Position<25) then begin trackbar1.SetFocus; trackbar1.Position:=trackbar1.position+1; labelededit1.SetFocus; end; if (key=#113) and (trackbar1.Position>5) then begin trackbar1.SetFocus; trackbar1.Position:=trackbar1.position-1 ; labelededit1.SetFocus; end; if key=#27 then bitbtn1.Click; if key=#13 then btnaccept.Click; end else begin //fmain.CleanScreen; //myspace.redraw; //myspace.DrawGrid(20); pbmain.Canvas.pen.color:=clwhite; pbmain.Canvas.pen.width:=1; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); pbmain.Canvas.Pen.Style:=pssolid; pbmain.Canvas.pen.Color:=clsilver; pbmain.Canvas.MoveTo(point1.X-5,point1.Y); pbmain.Canvas.lineTo(point1.X+5,point1.Y); pbmain.Canvas.MoveTo(point1.X,point1.Y-5); pbmain.Canvas.lineTo(point1.X,point1.Y+5); pbmain.Canvas.pen.width:=1; if (key=#100) and (point1.X<=pbmain.Width) then point1.x:=point1.x+20; //wasd controls if (key=#115)and (point1.Y<=pbmain.Height) then point1.y:=point1.y+20; if (key=#97) and (point1.x>=0) then point1.x:=point1.x-20; if (key=#119)and (point1.y>=0) then point1.y:=point1.y-20; //---- functional hotkeys if Key=#13 then button1.Click; if key=#27 then exitbtn.Click; if key=#127 then btndelete.Click; if (key=#09) and (radiobutton1.Checked=true) then radiobutton2.Checked:=true ; if (key=#09) and (radiobutton2.Checked=true) then radiobutton1.Checked:=true ; if key=#08 then //deleting charges begin for i := 0 to myspace._cntCharges-1 do begin if (myspace._charges[i]._pos=point1) and ( myspace._cntCharges>=1) then z:=i; end; myspace.RemoveCharge(z); statbtn.click; end; pbmain.Canvas.pen.Color:=clred; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); if key=#32 then begin fmain.CleanScreen; myspace.redraw; myspace.DrawGrid(20); panel1.Left:=point1.X+40; panel1.top:=point1.y+40; panel1.Visible:=true; myspace.redraw; myspace.scopedraw(point1,clred); labelededit1.SetFocus; END; if (key=#108) or (key=#76) then loadbutton.Click; if (key=#107) or (key=#75) then savebutton.Click; end; end; end; procedure TfMain.labelededit1Change(Sender: TObject); begin //if (labelededit1.text[length(labelededit1.Text)-1]='e') or (labelededit1.text[length(labelededit1.Text)-1]='q') then labelededit1.text[length(labelededit1.Text)]:='' end; procedure TfMain.loadbuttonClick(Sender: TObject); const xlCellTypeLastCell = $0000000B; var Excel: variant; WorkSheet: OLEVariant; i, j: word; S: string; x,y: integer; FileName: WideString; begin fmain.CleanScreen; myspace.DrawGrid(20); FileName:='charges.xls'; Excel := CreateOleObject('Excel.Application'); Excel.Workbooks.Open(FileName); Excel.Visible:=false; WorkSheet := Excel.Workbooks[ExtractFileName(FileName)].WorkSheets[1]; WorkSheet.Cells.SpecialCells(xlCellTypeLastCell,EmptyParam).Activate; x := Excel.ActiveCell.Row; y := Excel.ActiveCell.Column; StringGrid1.RowCount := x; StringGrid1.ColCount := y; for i := 1 to x do for j := 1 to y do begin S := Excel.Sheets[1].Cells[i,j].Text; StringGrid1.Cells[j-1,i-1]:=s; end; myspace.gridtospace(stringgrid1); myspace.redraw; end; procedure TfMain.pbMainClick(Sender: TObject); begin if PANEL1.Visible=TRUE then ELSE BEGIN //deleting mistakes of youth(key usage rectangle) fmain.CleanScreen; myspace.redraw; pbmain.Canvas.pen.color:=clwhite; pbmain.Canvas.pen.width:=1; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); pbmain.Canvas.Pen.Style:=pssolid; pbmain.Canvas.pen.Color:=clsilver; pbmain.Canvas.MoveTo(point1.X-5,point1.Y); pbmain.Canvas.lineTo(point1.X+5,point1.Y); pbmain.Canvas.MoveTo(point1.X,point1.Y-5); pbmain.Canvas.lineTo(point1.X,point1.Y+5); pbmain.Canvas.pen.width:=1; //---------------------- myspace.DrawGrid(20); getcursorpos(pt) ; point0:=screentoclient(pt) ; point1:=point(round(point0.X/20)*20,round(point0.y/20)*20 ) ; //setting point of charge //showing panel panel1.Left:=point1.X-40; panel1.top:=point1.y+40; panel1.Visible:=true; myspace.redraw; myspace.scopedraw(point1,clred); END; end; procedure TfMain.pbMainDblClick(Sender: TObject); var z,i:integer; pos:tpoint; begin getcursorpos(pos); pos:=screentoclient(pos); pos:=point(round(pos.X/20)*20,round(pos.Y/20)*20); for i := 0 to myspace._cntCharges-1 do begin if (myspace._charges[i]._pos=pos) and (myspace._cntCharges>=1) then z:=i; end; myspace.RemoveCharge(z); statbtn.click; end; procedure TfMain.pbMainPaint(Sender: TObject); begin pbmain.Canvas.Pen.Width:=1; pbmain.Canvas.Pen.Color:=clblack; myspace.DrawGrid(20); end; procedure TfMain.savebuttonClick(Sender: TObject); begin if SaveAsExcelFile(stringGrid1, 'charges.xls') then ShowMessage('Данные сохранены успешно.Загрузка завершена /100%/'); end; procedure TfMain.statbtnClick(Sender: TObject); var i: Integer; begin //if stringgrid1.Visible=false then stringgrid1.Visible:=true else stringgrid1.Visible:=false ; stringgrid1.rowcount:= myspace._cntCharges+1; for i := 0 to myspace._cntCharges-1 do begin stringgrid1.Cells[0,0]:='№ '; stringgrid1.Cells[1,0]:='Заряд'; stringgrid1.Cells[2,0]:=' (X)' ; stringgrid1.Cells[3,0]:=' (Y)' ; if myspace._charges[i]._q<>0 then begin stringgrid1.Cells[1,i+1]:=floattostr(myspace._charges[i]._q ); stringgrid1.Cells[2,i+1]:=inttostr(myspace._charges[i]._pos.X) ; stringgrid1.Cells[3,i+1]:=inttostr(myspace._charges[i]._pos.y); stringgrid1.Cells[0,i+1]:=inttostr(i+1); end; end; end; procedure Space.AddCharge(position:tpoint;chargeq:real); var chargepos:tpoint; begin chargepos:=position; SETLENGTH(self._charges,(self._CNTCHARGES+1)); self._charges[self._cntcharges]:=charge.New(chargeq,point(round(chargepos.x/20)*20,round(chargepos.y/20)*20)) ; self._canvas.Pen.Width:=3; self._canvas.Pen.Color:=self._charges[self._cntCharges]._color; self._canvas.Create.Ellipse((round(chargepos.X/20)*20+10),(round(chargepos.Y/20)*20+10),round(chargepos.X/20)*20-10,round(chargepos.Y/20)*20-10); self._cntcharges:=self._cntcharges+1; self._canvas.Pen.Width:=1; self._canvas.pen.Color:=clblack ; end; function Space.colour(eint:real): tcolor; var i:integer; a,b,k:real; //scalar:real; red,green,blue,z1:byte; emax:real; begin k:=0.4; emax:=-10000; for i := 0 to self._cntCharges-1 do begin if (self._charges[i]._q/100)>emax then emax:=(self._charges[i]._q/100); end; if eint<>0 then b:=ln(abs(eint/emax))*k; if b<-5 then b:=-5 ; if b>0 then b:=0; b:=b+5; b:=5-b; z1:=round((b-trunc(b))*255); if (b<=1) and (b>=0) then begin red:=255; green:=z1; blue:=0; end; if (b<=2) and (b>=1) then begin red:=255-z1; green:=255; blue:=0; end; if (b>=2) and (b<=3) then begin red:=0; green:=255; blue:=z1; end; if (b>=3) and (b<=4) then begin red:=0; green:=255-z1; blue:=255; end; if (b<=5) and (b>=4)then begin red:=0 ; green:=0 ; blue:=255; end; result:=rgb(red,green,blue) end; procedure Space.Draw(linenumber:array of integer;dropout:integer); var ex,ey,e,eint,x,y,r,cosa,sina,angle:real; counter,counter1,counter2,curve:integer; //0-charge,1-line,2-influence linecolor:tcolor; begin fmain.progressbar1.position:=0; fmain.progressbar1.max:=(self._cntcharges); for counter := 0 to self._cntcharges-1 do //cycle which cycles through charges begin for counter1 :=0 to linenumber[counter] do //through different angles of start begin curve:=0; //crutch for length angle:=(counter1/linenumber[counter])*2*pi; x:=self._charges[counter]._pos.X+dropout*cos(angle); y:=self._charges[counter]._pos.y+dropout*sin(angle); while (x<self._canvas.ClipRect.Width)and (y<self._canvas.ClipRect.Height) and (x>0) and (y>0) and (curve<20000) do begin ex:=0 ; ey:=0 ; eint:=0; for counter2 := 0 to self._cntcharges-1 do //through oharges influence begin r:=sqrt(sqr(self._charges[counter2]._pos.x-x)+sqr(self._charges[counter2]._pos.y-y)); if r<>0 then cosa:=(x-self._charges[counter2]._pos.x )/r ; if r<>0 then sina:=(y-self._charges[counter2]._pos.y )/r ; if (r<>0) then begin if (self._charges[counter]._q>0) then e:=self._charges[counter2]._q/r else e:=-1*self._charges[counter2]._q/r ; end; ex:=ex+(e)*cosa; ey:=ey+(e)*sina; end; eint:=sqrt(sqr(ex)+sqr(ey)); //summary if eint<>0 then x:=x+ex/eint; if eint<>0 then y:=y+ey/eint; if fmain.RadioButton2.Checked=true then linecolor:=clblack else linecolor:=myspace.colour(eint); self._canvas.Pixels[round(x),round(y)]:=linecolor; self._canvas.Pixels[round(x)+1,round(y)]:=linecolor; curve:=curve+1; end; end; fmain.progressBar1.Position:=fmain.TrackBar1.Position+1; end; end; procedure Space.RemoveCharge(numbercharge:integer); var chargepos:tpoint; r:integer; begin fmain.CleanScreen; self._canvas.pen.width:=3; self._canvas.pen.color:=clwhite; if (numbercharge>=0) and (numbercharge<=self._cntcharges-1) then self._canvas.Ellipse(self._charges[numbercharge]._pos.X-10,self._charges[numbercharge]._pos.y-10,self._charges[numbercharge]._pos.X+10,self._charges[numbercharge]._pos.y+10); self._canvas.pen.width:=1; if (numbercharge>=0) and (numbercharge<=self._cntcharges-1) then self._charges[numbercharge]._q:=0; if self._cntCharges>=2 then begin for r := numbercharge to self._cntCharges-2 do begin self._charges[r]:=self._charges[r+1]; end; end; self._cntcharges:=self._cntcharges-1; setlength(self._charges,self._cntCharges); myspace.redraw; myspace.DrawGrid(20); end; procedure Space.scopedraw(point1: tpoint;color:tcolor); begin self._canvas.pen.Width:=5; self._Canvas.Pen.Color:=color; self._Canvas.MoveTo(point1.X+10,point1.Y+10); self._Canvas.lineTo(point1.X+40,point1.Y+40); self._Canvas.MoveTo(point1.X-10,point1.Y+10); self._Canvas.lineTo(point1.X-40,point1.Y+40); self._Canvas.MoveTo(point1.X,point1.Y-15); self._Canvas.lineTo(point1.X,point1.Y-40); self._Canvas.Pen.Color:=clblack; self._canvas.pen.Width:=1; end; PROCEDURE space.DrawGrid(gridperiod: Integer); var i,z:integer; begin i:=0; z:=0; self._canvas.pen.width:=1; while i<=self._canvas.ClipRect.Width do begin self._canvas.pen.Color:=clSILVER; self._canvas.MoveTo(i,0); self._canvas.LineTo(i,self._canvas.ClipRect.Height); i:=i+gridperiod; end; while z<=self._canvas.ClipRect.Width do begin self._canvas.pen.Color:=clSILVER; self._canvas.MoveTo(0,z); self._canvas.LineTo(self._canvas.ClipRect.Width,z); z:=z+gridperiod; end; end; procedure Space.gridtospace(stringgrid1: tstringgrid); var i,z:integer; begin for z := 0 to self._cntCharges-1 do self.RemoveCharge(z); fmain.CleanScreen; myspace.DrawGrid(20); for i:=1 to stringgrid1.RowCount-1 do begin self.addcharge(point(strtoint(stringgrid1.Cells[2,i]),strtoint(stringgrid1.Cells[3,i])),strtofloat(stringgrid1.Cells[1,i])); end; end; procedure Space.LineFromPoint(pointdraw: tpoint); var ex,ey,e,emax,emin,eint,x,y,r,cosa,sina,angle:real; counter,counter1,counter2,curve,sign:integer; //0-charge,1-line,2-influence linecolor:tcolor; i: Integer; begin fmain.progressbar1.position:=0; for i := 1 to 2 do begin x:=pointdraw.x; y:=pointdraw.y; while (x<self._canvas.ClipRect.Width)and (y<self._canvas.ClipRect.Height) and (x>0) and (y>0) and (curve<20000) do begin ex:=0 ; ey:=0 ; eint:=0; for counter2 := 0 to self._cntcharges-1 do //through oharges influence begin r:=sqrt(sqr(self._charges[counter2]._pos.x-x)+sqr(self._charges[counter2]._pos.y-y)); if r<>0 then cosa:=(x-self._charges[counter2]._pos.x)/r ; if r<>0 then sina:=(y-self._charges[counter2]._pos.y)/r ; if (r<>0) then begin if i=1 then e:=self._charges[counter2]._q/(r*r*r) else e:=-1*self._charges[counter2]._q/(r*r*r) end; ex:=ex+(e)*cosa; ey:=ey+(e)*sina; end; eint:=sqrt(sqr(ex)+sqr(ey)) ; //summary if eint<>0 then x:=x+ex/eint; if eint<>0 then y:=y+ey/eint; linecolor:=clblack; self._canvas.Pixels[round(x),round(y)]:=linecolor; curve:=curve+1; end; end; end; procedure Space.MoveCharge(numbercharge: integer); begin end; constructor Space.New(canvas: TCanvas; gridPeriod: integer); begin self._canvas:=canvas; self._cntCharges:=0 ; end; procedure Space.opilki; var ex,ey,e,emax,emin,eint,x,y,r,cosa,sina,angle:real; counter,counter1,counter2,curve,sign:integer; //0-charge,1-line,2-influence linecolor:tcolor; begin fmain.progressbar1.position:=0; fmain.progressbar1.max:=round(self._cntcharges); fmain.CleanScreen; begin for counter := 0 to self._cntcharges-1 do //cycle which cycles through charges begin for counter1 :=0 to 15 do //through different angles of start begin curve:=0; //crutch for length angle:=(counter1/15)*2*pi; x:=self._charges[counter]._pos.X+(10*counter1)*cos(angle); y:=self._charges[counter]._pos.y+(10*counter1)*sin(angle); while (x<self._canvas.ClipRect.Width)and (y<self._canvas.ClipRect.Height) and (x>0) and (y>0) and (curve<20000) do begin ex:=0 ; ey:=0 ; eint:=0; for counter2 := 0 to self._cntcharges-1 do //through oharges influence begin r:=sqrt(sqr(self._charges[counter2]._pos.x-x)+sqr(self._charges[counter2]._pos.y-y)); if r<>0 then cosa:=(x-self._charges[counter2]._pos.x)/r ; if r<>0 then sina:=(y-self._charges[counter2]._pos.y)/r ; if (r<>0) then begin if (self._charges[counter]._q>0) then sign:=1 else sign:=-1 ; if (self._charges[counter]._q>0) then e:=self._charges[counter2]._q/sqr(r) else e:=-1*self._charges[counter2]._q/(r*r*r*r*r) ; end; ex:=ex+(e)*cosa; ey:=ey+(e)*sina; end; eint:=sqrt(sqr(ex)+sqr(ey)); //summary if eint<>0 then x:=x+4*ey/eint; if eint<>0 then y:=y-4*ex/eint; linecolor:=clblack; self._canvas.Pixels[round(x),round(y)]:=linecolor; curve:=curve+1; end; end; fmain.progressbar1.position:=fmain.progressbar1.position+1; end; end; end; procedure Space.redraw; var i:integer; begin for i := 0 to self._cntCharges-1 do begin self._canvas.Pen.Width:=3; self._canvas.Pen.Color:=self._charges[i]._color; self._canvas.Ellipse(self._charges[i]._pos.X+10,self._charges[i]._pos.y+10,self._charges[i]._pos.X-10,self._charges[i]._pos.y-10); self._canvas.Pen.Width:=1; end; end; end.
{* FormProgress.pas/dfm --------------------- Begin: 2005/07/14 Last revision: $Date: 2010-11-01 20:40:51 $ $Author: rhupalo $ Version number: $Revision: 1.21 $ Project: APHI General Purpose Delphi Libary Website: http://www.naadsm.org/opensource/delphi/ Author: Aaron Reeves <aaron.reeves@naadsm.org> -------------------------------------------------- Copyright (C) 2005 - 2010 Animal Population Health Institute, Colorado State University 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. ---------------------------------------------------- Can be used to display a counter or show the progress of a primary and secondary process, and display a status message. Used by many of the forms where a XML or CVS file import is occurring. } (* Documentation generation tags begin with {* or /// Replacing these with (* or // foils the documentation generator *) unit FormProgress; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls ; type /// Enumerations for specifying the type (feature set) of progress form TProgressFormType = ( PRSingleBar, /// single progress bar PRDoubleBar, /// primary and secondary progress bars PRCounter /// counter (two flavors) without progress bars ); type /// Progress form TFormProgress = class( TForm ) pnlBase: TPanel; pnlCtrlButtons: TPanel; btnCancel: TButton; pnlMessage: TPanel; lblMessage: TLabel; pnlDoubleBar: TPanel; lblPrimary: TLabel; pbrSecondary: TProgressBar; lblSecondary: TLabel; pbrPrimary: TProgressBar; pnlCounter: TPanel; lblCounter: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCancelClick(Sender: TObject); protected _autoClose: boolean; /// indicates whether the form should close on completion _readyToClose: boolean; /// indicates whether progress is 100% or the user clicked Cancel _formType: TProgressFormType; /// enumerated value to indicate which feature set to show _primaryCounter: integer; /// indicates the current value of the primary progress bar _myForm: TForm; /// owner of self if component is a form else nil procedure translateUI(); procedure handleClose(); procedure stepUp( pbr: TProgressBar; const percent: integer ); public constructor create( AOwner: TComponent; formType: TProgressFormType; autoClose: boolean; cpn: string = '' ); reintroduce; function setPrimary( percent: integer ): boolean; function setSecondary( percent: integer ): boolean; procedure setMessage( msg: string ); function setSecondaryAndMessage( percent: integer; msg: string = '' ): boolean; function setCounter1( val: integer ): boolean; function setCounter2( val, total: integer ): boolean; end ; const DBFORMPROGRESS: boolean = false; /// Set to true to enable debugging messages for this unit implementation {$R *.dfm} uses Math, ControlUtils, MyStrUtils, DebugWindow, I88n ; // ---------------------------------------------------------------------------- // Creation/initialization/destruction // ---------------------------------------------------------------------------- {* Creates a progress form of a specifed type. @param AOwner owner of the progress form or nil formType enumeration for the progress form type (feature set) autoClose true if the form should automatically close on completion, else false cpn descriptive caption for the form @comment The progress form will always be on top when showing. } constructor TFormProgress.create( AOwner: TComponent; formType: TProgressFormType; autoClose: boolean; cpn: string = '' ); begin inherited create( AOwner ); translateUI(); if( AOwner is TForm ) then _myForm := (AOwner as TForm) else _myForm := nil ; // Make sure that this form is always on top when its shown //--------------------------------------------------------- SetWindowPos( Self.Handle, // handle to window HWND_TOPMOST, // placement-order handle {*} Self.Left, // horizontal position Self.Top, // vertical position Self.Width, Self.Height, // window-positioning options SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE ); // Deal with form scaling //----------------------- Assert(not Scaled, 'You should set Scaled property of Form to False!'); // Set this value to the PPI AT WHICH THE FORM WAS ORIGINALLY DESIGNED!! self.PixelsPerInch := 96; // FormCreate() will handle the rest. _formType := formType; lblMessage.left := pbrPrimary.left; case _formType of PRSingleBar: begin pnlDoubleBar.Align := alClient; pnlDoubleBar.Width := self.ClientWidth; pnlDoubleBar.Visible := true; pbrPrimary.Position := 0; pbrPrimary.Max := 100; lblPrimary.Caption := tr( 'Progress:' ); lblPrimary.Top := lblPrimary.Top + 20; pbrPrimary.Top := pbrPrimary.Top + 20; _primaryCounter := -1; pbrSecondary.Position := 0; pbrSecondary.Max := 0; pbrSecondary.Visible := false; lblPrimary.Left := pbrPrimary.Left; lblSecondary.Visible := false; end ; PRDoubleBar: begin pnlDoubleBar.Align := alClient; pnlDoubleBar.Width := self.ClientWidth; pnlDoubleBar.Visible := true; pbrPrimary.Position := 0; pbrPrimary.Max := 100; _primaryCounter := -1; pbrSecondary.Position := 0; pbrSecondary.Max := 100; lblPrimary.Left := pbrPrimary.Left; lblSecondary.Left := pbrPrimary.Left; end ; PRCounter: begin pnlCounter.Align := alClient; pnlCounter.Width := self.ClientWidth; pnlCounter.Visible := true; lblCounter.Visible := false; end ; end; centerChildren( self, true ); if( '' = cpn ) then caption := tr( 'Please wait...' ) else caption := cpn ; _autoClose := autoClose; _readyToClose := false; end ; /// Specifies the captions, hints, and other component text phrases for translation procedure TFormProgress.translateUI(); begin // This function was generated automatically by Caption Collector 0.6.0. // Generation date: Mon Feb 25 15:29:38 2008 // File name: C:/Documents and Settings/apreeves/My Documents/NAADSM/Interface-Fremont/general_purpose_gui/FormProgress.dfm // File date: Thu Oct 12 16:20:40 2006 // Set Caption, Hint, Text, and Filter properties with self do begin Caption := tr( 'Form1' ); btnCancel.Caption := tr( 'Cancel' ); lblMessage.Caption := tr( 'lblMessage' ); lblPrimary.Caption := tr( 'Stage progress:' ); lblSecondary.Caption := tr( 'Overall progress:' ); lblCounter.Caption := tr( 'lblCounter' ); end ; end ; /// Initializes the form when first created. Applications do not call FormCreate procedure TFormProgress.FormCreate(Sender: TObject); begin if Screen.PixelsPerInch <> 96 then ScaleBy( Screen.PixelsPerInch, 96 ) ; end ; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- {* Sets the counter value seen by the user when the form is of type PRCounter @param val count to display @return the current value of _readyToClose } function TFormProgress.setCounter1( val: integer ): boolean; begin lblCounter.Visible := true; lblCounter.Caption := intToStr( val ); horizCenterInside( pnlCounter, lblCounter ); Application.ProcessMessages(); result := _readyToClose; end ; {* Sets the counter values seen by the user when the form is of type PRCounter @param val current count to display @param total total count to display @return the current value of _readyToClose @comment The counter message displayed is val of total, e.g. "53 of 2000" } function TFormProgress.setCounter2( val, total: integer ): boolean; begin lblCounter.Visible := true; lblCounter.Caption := intToStr( val ) + ' ' + tr( 'of' ) + ' ' + intToStr( total ); horizCenterInside( pnlCounter, lblCounter ); Application.ProcessMessages(); result := _readyToClose; end ; {* Helper method to update one of the progress bars to position percent in increments of 10 @param pbr progress bar object to update, could be either the primary or secondary one @param percent final percentage to display in this step } procedure TFormProgress.stepUp( pbr: TProgressBar; const percent: integer ); var startDelay: comp; // Funky type: see Delphi help for an explanation. n: integer; begin while( percent > pbr.Position ) do begin n := pbr.Position + 10; if( n > percent ) then pbr.Position := percent else pbr.Position := n ; repaint(); // Delay for a bit for the progress bar to be drawn startDelay := timeStampToMSecs( dateTimeToTimeStamp( time() ) ); while( timeStampToMSecs( dateTimeToTimeStamp( time() ) ) < startDelay + 15 ) do Application.ProcessMessages() ; end ; end ; {* Increments the primary progress bar to position percentage @param percent final percentage to display in this step @return the current value of _readyToClose } function TFormProgress.setPrimary( percent: integer ): boolean; begin percent := min( percent, 100 ); //dbcout( 'Primary percent is ' + intToStr( percent ), DBFORMPROGRESS ); if( 10 < percent - pbrPrimary.Position ) then stepUp( pbrPrimary, percent ) else pbrPrimary.Position := percent ; handleClose(); Application.ProcessMessages(); result := _readyToClose; end ; {* Increments the secondary progress bar to position percentage @param percent final percentage to display in this step @return the current value of _readyToClose } function TFormProgress.setSecondary( percent: integer ): boolean; begin percent := min( percent, 100 ); //dbcout( 'Scondary percent is ' + intToStr( percent ), DBFORMPROGRESS ); if( 10 < percent - pbrSecondary.Position ) then stepUp( pbrSecondary, percent ) else pbrSecondary.Position := percent ; handleClose(); Application.ProcessMessages(); result := _readyToClose; end ; {* Increments the secondary progress bar to position percentage and displays msg @param percent final percentage to display in this step @param progress status message, optional @return the current value of _readyToClose } function TFormProgress.setSecondaryAndMessage( percent: integer; msg: string = '' ): boolean; begin if( '' <> msg ) then begin inc( _primaryCounter ); pbrPrimary.Position := _primaryCounter; setMessage( msg ); end ; if( 10 > percent - pbrSecondary.Position ) then stepUp( pbrSecondary, percent ) else pbrSecondary.Position := percent ; result := _readyToClose; Application.ProcessMessages(); end ; {* Displays msg at the top of the progress form @param msg text to display } procedure TFormProgress.setMessage( msg: string ); begin lblMessage.Caption := prettyPrint( msg, 40 ); centerChildren( pnlMessage, false ); Application.ProcessMessages(); repaint(); end ; // ---------------------------------------------------------------------------- {* Helper method to manage form behavior when processing progress is completed. } procedure TFormProgress.handleClose(); var startDelay: comp; // Funky type: see Delphi help for an explanation. begin case _formType of PRSingleBar: begin if( pbrPrimary.Max = pbrPrimary.Position ) then begin if( _autoClose ) then begin repaint(); // Delay long enough for the completed progress bar to show up startDelay := timeStampToMSecs( dateTimeToTimeStamp( time() ) ); while( timeStampToMSecs( dateTimeToTimeStamp( time() ) ) < startDelay + 750 ) do Application.ProcessMessages() ; close(); end else begin btnCancel.Caption := tr( 'Close' ); btnCancel.Default := true; btnCancel.Enabled := true; end ; end ; end ; PRDoubleBar: begin if ( pbrPrimary.Max = pbrPrimary.Position ) and ( pbrSecondary.Max = pbrSecondary.Position ) then begin if( _autoClose ) then begin repaint(); // Delay long enough for the completed progress bar to show up startDelay := timeStampToMSecs( dateTimeToTimeStamp( time() ) ); while( timeStampToMSecs( dateTimeToTimeStamp( time() ) ) < startDelay + 750 ) do Application.ProcessMessages() ; close(); end else begin btnCancel.Caption := tr( 'Close' ); btnCancel.Default := true; btnCancel.Enabled := true; end ; end ; end ; PRCounter: begin if( _autoClose ) then begin repaint(); // Delay long enough for the last label to show up startDelay := timeStampToMSecs( dateTimeToTimeStamp( time() ) ); while( timeStampToMSecs( dateTimeToTimeStamp( time() ) ) < startDelay + 250 ) do Application.ProcessMessages() ; close(); end else begin btnCancel.Caption := tr( 'Close' ); btnCancel.Default := true; btnCancel.Enabled := true; end ; end ; end; end ; /// Does nothing, upto to creator to call the form's release() method to free resources procedure TFormProgress.FormClose( Sender: TObject; var Action: TCloseAction ); begin //action := caNone; end ; {* Closes the form if progress is completed or sets _readyToClose true if not. @comment Processing is never actually canceled. However the return value of subsquent set calls will be false. This could be used by the caller to indicate to rollback whatever process is being conducted. } procedure TFormProgress.btnCancelClick(Sender: TObject); begin if ( pbrPrimary.Max = pbrPrimary.Position ) and ( pbrSecondary.Max = pbrSecondary.Position ) then self.Close() else _readyToClose := true ; end ; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Notification Center implementation for MacOS } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Mac.Notification; interface {$SCOPEDENUMS ON} uses System.Notification; /// <summary>Common ancestor used to instantiate platform implementation</summary> type TPlatformNotificationCenter = class(TBaseNotificationCenter) protected class function GetInstance: TBaseNotificationCenter; override; end; implementation uses System.SysUtils, System.Messaging, Macapi.Foundation, Macapi.ObjectiveC, Macapi.Helpers, Macapi.AppKit; type { TNotificationCenterCocoa } TNotificationCenterDelegate = class; TNotificationCenterCocoa = class(TPlatformNotificationCenter) private class var FNotificationCenterSingleton: TNotificationCenterCocoa; FNotificationCenter: NSUserNotificationCenter; FNotificationCenterDelegate: NSUserNotificationCenterDelegate; function CreateNativeNotification(const ANotification: TNotification): NSUserNotification; function ConvertNativeToDelphiNotification(const ANotification: NSUserNotification): TNotification; function FindNativeNotification(const AID: string; out ANotification: NSUserNotification): Boolean; class destructor Destroy; class function GetNotificationCenter: TNotificationCenterCocoa; static; public constructor Create; destructor Destroy; override; procedure ReceiveNotification(const ANotification: NSUserNotification); function GetCurrentNotifications: TNotifications; // Not accesible in base class because android doesn't have it function FindNotification(const AName: string): TNotification; // Not accesible in base class because android doesn't have it procedure DoScheduleNotification(const ANotification: TNotification); override; procedure DoPresentNotification(const ANotification: TNotification); override; procedure DoCancelNotification(const AName: string); overload; override; procedure DoCancelNotification(const ANotification: TNotification); overload; override; procedure DoCancelAllNotifications; override; procedure DoCreateOrUpdateChannel(const AChannel: TChannel); override; procedure DoDeleteChannel(const AChannelId: string); override; procedure DoGetAllChannels(const AChannels: TChannels); override; procedure DoSetIconBadgeNumber(const ACount: Integer); override; function DoGetIconBadgeNumber: Integer; override; procedure DoResetIconBadgeNumber; override; class property NotificationCenter: TNotificationCenterCocoa read GetNotificationCenter; end; { Notification Center Delegate } TNotificationCenterDelegate = class (TOCLocal, NSUserNotificationCenterDelegate) strict private FNotificationCenter: TNotificationCenterCocoa; public constructor Create(ANotificationCenter: TNotificationCenterCocoa); procedure userNotificationCenter(center: NSUserNotificationCenter; didActivateNotification: NSUserNotification); cdecl; end; function RepeatIntervalToNSDateComponents(const AInterval: TRepeatInterval): NSDateComponents; begin if AInterval = TRepeatInterval.None then Exit(nil); Result := TNSDateComponents.Create; case AInterval of TRepeatInterval.Second: Result.setSecond(1); TRepeatInterval.Minute: Result.setMinute(1); TRepeatInterval.Hour: Result.setHour(1); TRepeatInterval.Day: Result.setDay(1); TRepeatInterval.Weekday: Result.setWeekday(1); TRepeatInterval.Week: Result.setWeek(1); TRepeatInterval.Month: Result.setMonth(1); TRepeatInterval.Quarter: Result.setQuarter(1); TRepeatInterval.Year: Result.setYear(1); TRepeatInterval.Era: Result.setEra(1); end; end; function NSDateComponentsToRepeatInterval(const ADate: NSDateComponents): TRepeatInterval; begin if ADate = nil then Result := TRepeatInterval.None else if ADate.era <> NSUndefinedDateComponent then Result := TRepeatInterval.Era else if ADate.year <> NSUndefinedDateComponent then Result := TRepeatInterval.Year else if ADate.quarter <> NSUndefinedDateComponent then Result := TRepeatInterval.Quarter else if ADate.month <> NSUndefinedDateComponent then Result := TRepeatInterval.Month else if ADate.week <> NSUndefinedDateComponent then Result := TRepeatInterval.Week else if ADate.weekday <> NSUndefinedDateComponent then Result := TRepeatInterval.Weekday else if ADate.day <> NSUndefinedDateComponent then Result := TRepeatInterval.Day else if ADate.hour <> NSUndefinedDateComponent then Result := TRepeatInterval.Hour else if ADate.minute <> NSUndefinedDateComponent then Result := TRepeatInterval.Minute else if ADate.second <> NSUndefinedDateComponent then Result := TRepeatInterval.Second else Result := TRepeatInterval.None; end; { TNotificationCenterCocoa } procedure TNotificationCenterCocoa.DoCancelAllNotifications; var Notifications: NSArray; NativeNotification: NSUserNotification; I: Integer; NotificationsCount: Integer; begin Notifications := FNotificationCenter.scheduledNotifications; NotificationsCount := Integer(Notifications.count); for I := 0 to NotificationsCount - 1 do begin NativeNotification := TNSUserNotification.Wrap(Notifications.objectAtIndex(I)); FNotificationCenter.removeScheduledNotification(NativeNotification); end; FNotificationCenter.removeAllDeliveredNotifications; end; procedure TNotificationCenterCocoa.DoCancelNotification(const AName: string); var NativeNotification: NSUserNotification; begin if not AName.IsEmpty and FindNativeNotification(AName, NativeNotification) then begin FNotificationCenter.removeScheduledNotification(NativeNotification); FNotificationCenter.removeDeliveredNotification(NativeNotification); end; end; procedure TNotificationCenterCocoa.DoCancelNotification(const ANotification: TNotification); begin if ANotification <> nil then DoCancelNotification(ANotification.Name); end; procedure TNotificationCenterCocoa.DoCreateOrUpdateChannel(const AChannel: TChannel); begin // Relevant only for Android end; procedure TNotificationCenterCocoa.DoDeleteChannel(const AChannelId: string); begin // Relevant only for Android end; constructor TNotificationCenterCocoa.Create; begin inherited; FNotificationCenter := TNSUserNotificationCenter.Wrap(TNSUserNotificationCenter.OCClass.defaultUserNotificationCenter); FNotificationCenter.retain; FNotificationCenterDelegate := TNotificationCenterDelegate.Create(Self); FNotificationCenter.setDelegate(FNotificationCenterDelegate); end; function TNotificationCenterCocoa.CreateNativeNotification(const ANotification: TNotification): NSUserNotification; var NativeNotification: NSUserNotification; UserInfo: NSDictionary; GMTDateTime: TDateTime; begin NativeNotification := TNSUserNotification.Create; if not ANotification.Name.IsEmpty then begin // Set unique identificator UserInfo := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject( (StrToNSStr(ANotification.Name) as ILocalObject).GetObjectID, (StrToNSStr('id') as ILocalObject).GetObjectID)); NativeNotification.setUserInfo(UserInfo); end; // Get GMT time and set notification fired date GMTDateTime := GetGMTDateTime(ANotification.FireDate); NativeNotification.setDeliveryTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone)); NativeNotification.setDeliveryDate(DateTimeToNSDate(GMTDateTime)); NativeNotification.setDeliveryRepeatInterval(RepeatIntervalToNSDateComponents(ANotification.RepeatInterval)); if not ANotification.Title.IsEmpty then NativeNotification.setTitle(StrToNSStr(ANotification.Title)); NativeNotification.setInformativeText(StrToNSStr(ANotification.AlertBody)); NativeNotification.setHasActionButton(ANotification.HasAction); if ANotification.HasAction then NativeNotification.setActionButtonTitle(StrToNSStr(ANotification.AlertAction)); if ANotification.EnableSound then if ANotification.SoundName.IsEmpty then NativeNotification.setSoundName(NSUserNotificationDefaultSoundName) else NativeNotification.setSoundName(StrToNSStr(ANotification.SoundName)) else NativeNotification.setSoundName(nil); Result := NativeNotification; end; class destructor TNotificationCenterCocoa.Destroy; begin FNotificationCenterSingleton.Free; end; function TNotificationCenterCocoa.ConvertNativeToDelphiNotification(const ANotification: NSUserNotification): TNotification; var UserInfo: NSDictionary; NotificationTmp: TNotification; begin NotificationTmp := TNotification.Create; UserInfo := ANotification.userInfo; if UserInfo <> nil then NotificationTmp.Name := UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(StrToNSStr('id'))).UTF8String); if ANotification.informativeText <> nil then NotificationTmp.AlertBody := UTF8ToString(ANotification.informativeText.UTF8String); if ANotification.actionButtonTitle <> nil then NotificationTmp.AlertAction := UTF8ToString(ANotification.actionButtonTitle.UTF8String);; if ANotification.title <> nil then NotificationTmp.Title := NSStrToStr(ANotification.title); NotificationTmp.FireDate := NSDateToDateTime(ANotification.deliveryDate); NotificationTmp.EnableSound := ANotification.SoundName <> nil; if (ANotification.soundName.compare(NSUserNotificationDefaultSoundName) = NSOrderedSame) or (ANotification.soundName = nil) then NotificationTmp.SoundName := '' else NotificationTmp.SoundName := NSStrToStr(ANotification.soundName); NotificationTmp.HasAction := ANotification.hasActionButton; NotificationTmp.RepeatInterval := NSDateComponentsToRepeatInterval(ANotification.deliveryRepeatInterval); Result := NotificationTmp; end; destructor TNotificationCenterCocoa.Destroy; begin FNotificationCenter.release; FNotificationCenterDelegate := nil; inherited Destroy; end; function TNotificationCenterCocoa.FindNativeNotification(const AID: string; out ANotification: NSUserNotification): Boolean; function FindNotificationInList(const ANotifications: NSArray; out ANotification: NSUserNotification): Boolean; var Found: Boolean; I: Integer; NotificationsCount: Integer; NativeNotification: NSUserNotification; UserInfo: NSDictionary; begin Assert(ANotifications <> nil); Found := False; I := 0; NotificationsCount := Integer(ANotifications.count); while (I < NotificationsCount) and not Found do begin NativeNotification := TNSUserNotification.Wrap(ANotifications.objectAtIndex(I)); UserInfo := NativeNotification.userInfo; if (UserInfo <> nil) and (UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(StrToNSStr('id'))).UTF8String) = AID) then Found := True else Inc(I); end; if Found then ANotification := NativeNotification else ANotification := nil; Result := Found; end; var Found: Boolean; begin { Search notificaition in scheduled notifications list } Found := FindNotificationInList(FNotificationCenter.scheduledNotifications, ANotification); { Search notificaition in delivered notifications list } if not Found then Found := FindNotificationInList(FNotificationCenter.deliveredNotifications, ANotification); Result := Found; end; function TNotificationCenterCocoa.FindNotification(const AName: string): TNotification; var NativeNotification: NSUserNotification; begin if FindNativeNotification(AName, NativeNotification) then Result := ConvertNativeToDelphiNotification(NativeNotification) else Result := nil; end; function TNotificationCenterCocoa.GetCurrentNotifications: TNotifications; var Notifications: NSArray; NativeNotification: NSUserNotification; I: Integer; begin Notifications := FNotificationCenter.scheduledNotifications; SetLength(Result, Notifications.count); for I := 0 to Integer(Notifications.count) - 1 do begin NativeNotification := TNSUserNotification.Wrap(Notifications.objectAtIndex(I)); Result[I] := ConvertNativeToDelphiNotification(NativeNotification); end; end; procedure TNotificationCenterCocoa.DoPresentNotification(const ANotification: TNotification); var NativeNotification: NSUserNotification; begin DoCancelNotification(ANotification); NativeNotification := CreateNativeNotification(ANotification); FNotificationCenter.deliverNotification(NativeNotification); end; procedure TNotificationCenterCocoa.DoScheduleNotification(const ANotification: TNotification); var NativeNotification: NSUserNotification; begin DoCancelNotification(ANotification); NativeNotification := CreateNativeNotification(ANotification); FNotificationCenter.scheduleNotification(NativeNotification); end; procedure TNotificationCenterCocoa.ReceiveNotification(const ANotification: NSUserNotification); begin TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(ConvertNativeToDelphiNotification(ANotification))); end; procedure TNotificationCenterCocoa.DoSetIconBadgeNumber(const ACount: Integer); var NSApp: NSApplication; begin if ACount > 0 then begin NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); NSApp.dockTile.setBadgeLabel(StrToNSStr(ACount.ToString)); end else DoResetIconBadgeNumber; end; procedure TNotificationCenterCocoa.DoGetAllChannels(const AChannels: TChannels); begin // Relevant only for Android end; function TNotificationCenterCocoa.DoGetIconBadgeNumber: Integer; var NSApp: NSApplication; BadgeLabel: string; begin NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); if NSApp.dockTile.badgeLabel <> nil then begin BadgeLabel := UTF8ToString(NSApp.dockTile.badgeLabel.UTF8String); if not TryStrToInt(BadgeLabel, Result) then Result := 0; end else Result := 0; end; class function TNotificationCenterCocoa.GetNotificationCenter: TNotificationCenterCocoa; begin if FNotificationCenterSingleton = nil then FNotificationCenterSingleton := TNotificationCenterCocoa.Create; Result := FNotificationCenterSingleton; end; procedure TNotificationCenterCocoa.DoResetIconBadgeNumber; var NSApp: NSApplication; begin NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); NSApp.dockTile.setBadgeLabel(nil); end; { TNotificationCenterDelegate } constructor TNotificationCenterDelegate.Create(ANotificationCenter: TNotificationCenterCocoa); begin inherited Create; FNotificationCenter := ANotificationCenter; end; procedure TNotificationCenterDelegate.userNotificationCenter(center: NSUserNotificationCenter; didActivateNotification: NSUserNotification); begin if FNotificationCenter <> nil then FNotificationCenter.ReceiveNotification(didActivateNotification); end; { TPlatformNotificationCenter } class function TPlatformNotificationCenter.GetInstance: TBaseNotificationCenter; begin if TOSVersion.Check(10, 8) then Result := TBaseNotificationCenter(TNotificationCenterCocoa.NotificationCenter) else Result := nil; end; end.
unit acao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, CheckLst, ComCtrls, DB, ADODB, DBTables, Grids, DBGrids; type TfrmAcao = class(TForm) Shape1: TShape; Shape2: TShape; Label1: TLabel; Shape3: TShape; SpeedButton1: TSpeedButton; Shape4: TShape; txtConsulta: TEdit; Label3: TLabel; Label4: TLabel; txtCodigoConsulta: TEdit; txtDescricao: TEdit; Label2: TLabel; Bevel1: TBevel; cmbTipo: TComboBox; Label5: TLabel; Label6: TLabel; txtProduto: TEdit; Label7: TLabel; txtUnidade: TEdit; Shape5: TShape; btnNew: TSpeedButton; btnSave: TSpeedButton; btnDelete: TSpeedButton; btnCancel: TSpeedButton; btnPrint: TSpeedButton; Bevel2: TBevel; Shape6: TShape; DBGrid: TDBGrid; qry: TADOQuery; sQry: TDataSource; chbAll: TCheckBox; btnRefresh: TSpeedButton; Label8: TLabel; txtCodigo: TEdit; stp: TADOStoredProc; chbAlfa: TCheckBox; Bevel3: TBevel; procedure SpeedButton1Click(Sender: TObject); procedure FormActivate(Sender: TObject); procedure clearControls(); procedure keyExit(); procedure DBGridCellClick(Column: TColumn); procedure txtCodigoConsultaExit(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure txtConsultaExit(Sender: TObject); procedure txtDescricaoChange(Sender: TObject); procedure isItChanged(); procedure save(); procedure DBGridEnter(Sender: TObject); procedure btnNewClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnPrintClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } st_habilita : string; procedure habilita_sn(habilita :string); end; var frmAcao: TfrmAcao; theOperation : char; itsChanged : boolean; implementation uses data, acaoList; {$R *.dfm} procedure TfrmAcao.SpeedButton1Click(Sender: TObject); begin close; end; procedure TfrmAcao.FormActivate(Sender: TObject); begin habilita_sn('n'); btnRefreshClick(nil); clearControls(); dbGrid.setFocus; end; procedure TfrmAcao.clearControls; begin theOperation := '*'; txtCodigo.text := ''; txtCodigoConsulta.text := ''; txtConsulta.text := ''; txtDescricao.text := ''; txtProduto.text := ''; txtUnidade.text := ''; cmbTipo.text := ''; cmbTipo.itemIndex := -1; txtCodigo.readOnly := true; end; procedure TfrmAcao.keyExit; begin clearControls(); theOperation := 'a'; with qry do begin txtDescricao.text := fieldByName('descricao').asString; txtProduto.text := fieldByName('produto').asString; txtUnidade.text := fieldByName('unidade').asString; txtCodigo.text := fieldByName('codigo').asString; with dmtData do begin setComboBox(fieldByName('tipo').asString, cmbTipo); end; end; itsChanged := false; end; procedure TfrmAcao.DBGridCellClick(Column: TColumn); begin isItChanged(); keyExit(); end; procedure TfrmAcao.txtCodigoConsultaExit(Sender: TObject); begin if trim(txtCodigoConsulta.text) = '' then exit; if not qry.Locate('codigo',txtCodigoConsulta.text,[]) then begin showMessage('Código da Ação Inválido'); txtCodigoConsulta.setFocus; exit; end; keyExit(); end; procedure TfrmAcao.btnRefreshClick(Sender: TObject); begin with qry, qry.SQL do begin close; clear; add('SELECT * FROM acao ORDER BY descricao'); open; end; end; procedure TfrmAcao.txtConsultaExit(Sender: TObject); begin if trim(txtConsulta.text) = '' then exit; with qry, qry.SQL do begin close; clear; if chbAll.checked then add('SELECT * FROM acao WHERE descricao LIKE(''%'+txtConsulta.text+'%'')') else add('SELECT * FROM acao WHERE descricao LIKE('''+txtConsulta.text+'%'')'); open; if qry.eof then begin showMessage('Consulta Inválida'); exit; end; end; keyExit(); end; procedure TfrmAcao.txtDescricaoChange(Sender: TObject); begin itsChanged := true; end; procedure TfrmAcao.isItChanged; begin if theOperation = '*' then exit; if itsChanged then if application.messageBox('Você iniciou uma edição no registro atual. Deseja salvar as alterações ?','',MB_ICONQUESTION+MB_YESNO) = IDYES then save(); end; procedure TfrmAcao.save; begin if (copy(txtCodigo.text,1,1) = '0') OR (copy(txtCodigo.text,1,1) = '1') OR (copy(txtCodigo.text,1,1) = '2') OR (copy(txtCodigo.text,1,1) = '9') then else begin showMessage('Código da Ação Inválido'); exit; end; if trim(txtDescricao.text) = '' then begin showMessage('Falta preencher campo descrição'); exit; end; if (copy(txtCodigo.text,1,1) = '1') then if (copy(cmbTipo.text,1,1) = 'P') then else begin showMessage('Código da Ação Inválido para Projetos'); exit; end; if (copy(txtCodigo.text,1,1) = '2') then if (copy(cmbTipo.text,1,1) = 'A') then else begin showMessage('Código da Ação Inválido para Atividade'); exit; end; if (copy(cmbTipo.text,1,1) = 'P') OR (copy(cmbTipo.text,1,1) = 'A') OR (copy(cmbTipo.text,1,1) = 'E') OR (copy(cmbTipo.text,1,1) = 'O') then else begin showMessage('Tipo da Ação Inválido'); exit; end; if trim(txtProduto.text) = '' then if trim(txtUnidade.text) = '' then else begin showMessage('Falta Preencher Campo Produto da Ação'); exit; end else if trim(txtUnidade.text) = '' then begin showMessage('Falta Preencher Campo Unidade de Medida do Produto da Ação'); exit; end; with stp, stp.parameters do begin paramByName('@p_operation').value := theOperation; paramByName('@p_codigo').value := txtCodigo.text; paramByName('@p_descricao').value := txtDescricao.text; paramByName('@p_tipo').value := copy(cmbTipo.text,1,1); paramByName('@p_produto').value := txtProduto.text; paramByName('@p_unidade').value := txtUnidade.text; execProc; if paramByName('@return_value').value = 0 then showMessage('Alteração Rejeitada'); end; with qry do begin close; open; if theOperation <> 'e' then Locate('codigo',txtCodigo.text,[]); end; clearControls(); habilita_sn('n'); end; procedure TfrmAcao.DBGridEnter(Sender: TObject); begin isItChanged(); end; procedure TfrmAcao.btnNewClick(Sender: TObject); begin isItChanged(); clearControls(); habilita_sn('s'); end; procedure TfrmAcao.btnSaveClick(Sender: TObject); begin save(); end; procedure TfrmAcao.btnCancelClick(Sender: TObject); begin habilita_sn('n'); clearControls; end; procedure TfrmAcao.btnDeleteClick(Sender: TObject); begin if theOperation = 'a' then if application.messageBox('Você tem certeza que deseja excluir o registro corrente?','Confirmação de Exclusão',MB_ICONQUESTION+MB_YESNO) = IDNO then exit else begin theOperation := 'e'; save(); exit; end; btnCancelClick(nil); end; procedure TfrmAcao.btnPrintClick(Sender: TObject); begin Application.CreateForm(TfrmAcaoList, frmAcaoList); if chbAlfa.checked then with frmAcaoList.qry do begin close; SQL[8] := 'ORDER BY descricao'; open; end; frmAcaoList.report.preview; frmAcaoList.free; end; procedure TfrmAcao.habilita_sn(habilita: string); begin if habilita = 's' then begin btnNew.Enabled := False; btnSave.Enabled := True; btnCancel.Enabled := True; btnDelete.Enabled := False; btnRefresh.Enabled := False; theOperation := 'i'; txtCodigo.readOnly := False; txtCodigo.Enabled := True; txtDescricao.readOnly := False; txtDescricao.Enabled := True; cmbTipo.Enabled := True; txtProduto.readOnly := False; txtProduto.Enabled := True; txtUnidade.readOnly := False; txtUnidade.Enabled := True; txtCodigo.setFocus; itsChanged := True; end; if habilita = 'n' then begin btnNew.Enabled := True; btnSave.Enabled := False; btnCancel.Enabled := False; btnDelete.Enabled := True; btnRefresh.Enabled := True; theOperation := '*'; txtCodigo.readOnly := True; txtCodigo.Enabled := False; txtDescricao.readOnly := True; txtDescricao.Enabled := False; cmbTipo.Enabled := false; txtProduto.readOnly := True; txtProduto.Enabled := False; txtUnidade.readOnly := True; txtUnidade.Enabled := False; itsChanged := False; end; end; procedure TfrmAcao.FormClose(Sender: TObject; var Action: TCloseAction); begin if itsChanged then if application.messageBox('Você iniciou uma edição no registro atual. Deseja salvar as alterações ?','',MB_ICONQUESTION+MB_YESNO) = IDYES then begin Action := caNone; save(); exit; end else begin clearControls; habilita_sn('n'); itsChanged := False; end; end; end.
PROGRAM Diagonalsummen; const size = 4; type Matrix = ARRAY [1..size, 1..size] OF INTEGER; type DiagonalSums = ARRAY [1..size] OF INTEGER; PROCEDURE CalculateDiagonalSums(m: Matrix; VAR d: DiagonalSums); var i, j: integer; BEGIN (* CalculateDiagonalSums *) FOR i := 1 TO size DO BEGIN d[i] := 0; END; (* FOR *) FOR i := 1 TO size DO BEGIN FOR j := 1 TO (size + 1 - i) DO BEGIN d[i] := d[i] + m[i + j - 1, j]; END; (* FOR *) END; (* FOR *) END; (* CalculateDiagonalSums *) var input: Matrix; var i, j: INTEGER; var d: DiagonalSums; BEGIN (* Diagonalsummen *) WriteLn('Bitte Matrix eingeben: '); FOR i := 1 TO size DO BEGIN FOR j := 1 TO size DO BEGIN Read(input[i, j]); END; (* FOR *) END; (* FOR *) CalculateDiagonalSums(input, d); Write('Diagonalsummen: '); FOR i := 1 TO size DO BEGIN IF (i = size) THEN BEGIN Write(d[i]); END ELSE BEGIN Write(d[i], ', '); END; (* IF *) END; (* FOR *) END. (* Diagonalsummen *)
unit MainFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Menus; type TMainForm = class(TForm) MainMenu1: TMainMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; pgc: TPageControl; procedure N2Click(Sender: TObject); procedure N3Click(Sender: TObject); private procedure CreateForm(className: string); function IsTabExists(name: string): boolean; { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation uses LinkUtil, DownloadFrm, DrawFrm; {$R *.dfm} function TMainForm.IsTabExists(name: string): Boolean; var i: Integer; begin Result := False; for i := 0 to pgc.PageCount -1 do //这里两个string可以直接使用=,不错不错,这是为什么呢?什么情况下可以呢? if (pgc.Pages[i].Name = name) then begin Result := True; pgc.ActivePageIndex := i; Exit; end; end; procedure TMainForm.CreateForm(className: string); var tabTmp: TTabSheet; formTmp: TForm; formClass: TFormClass; tabName: string; begin tabName := Copy(className, 2, Length(className)); if IsTabExists(tabName) then Exit; tabTmp := TTabSheet.Create(pgc); tabTmp.Parent := pgc; tabTmp.PageControl := pgc; tabTmp.Name := Format('%s',[tabName]); //设置为当前页,找了好久 pgc.ActivePage := tabTmp; //LoadLibrary('D:\Delphi\2016ditu\package\ditu.exe'); //1.需要注册类,才能使用GetClass()方法; //2.要想能调试进内核代码,需要在搜索路径加上内核代码的路径; formClass := TFormClass(GetClass(className)); formTmp := formClass.Create(Application); formTmp.BorderStyle := bsNone; formTmp.Parent := tabTmp; formTmp.Align := alClient; formTmp.Show; end; procedure TMainForm.N2Click(Sender: TObject); begin CreateForm('TDownloadForm'); end; procedure TMainForm.N3Click(Sender: TObject); begin CreateForm('TDrawForm'); end; end.
{ Ultibo QEMU Launcher Tool. Copyright (C) 2022 - SoftOz Pty Ltd. Arch ==== <All> Boards ====== <All> Licence ======= LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt) Credits ======= Information for this unit was obtained from: References ========== QEMU Launcher ============= The QEMU launcher provides a convenient way to launch the QEMU machine emulator with a compiled Ultibo project. The tool determines all of the default configuration information automatically but this can be overridden by creating a QEMULauncher.ini file in the same directory and setting a number of parameters. The format of the INI file is: [QEMULauncher] Path= SystemArm= SystemAarch64= ExtraParams= CommandLine= A brief explanation of each parameter along with the standard default value: Path - The path to the QEMU installation (Default: C:\Ultibo\Core\qemu) (Detected from the application path) SystemArm - The name of the QEMU ARM system emulator (Default: qemu-system-arm.exe) SystemAarch64 - The name of the QEMU AARCH64 system emulator (Default: qemu-system-aarch64.exe) ExtraParams - Any extra parameters to pass to QEMU on launch (Default: <Blank>) CommandLine - The command line parameters to pass to the Ultibo application (Default: <Blank>) A QEMULauncher.ini file can also be created in the same directory as a the project file (the .lpi file) and used to provide project specific parameters such as network settings or disk images to attach. Any settings contained in a QEMULauncher.ini file in the project directory will override the same settings in the default QEMULauncher.ini file. } program QEMULauncher; {$MODE Delphi} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Forms, Interfaces, Main in 'Main.pas' {frmMain}; {$R *.res} var Launch:TQEMULaunch; begin {} RequireDerivedFormResource:=True; if ParamCount >= 4 then begin Launch:=TQEMULaunch.Create; Launch.LoadConfig; Launch.LoadParams; Launch.LoadProjectConfig; Launch.Launch; Launch.Free; end else begin Application.Initialize; Application.Title := 'Ultibo QEMU Launcher'; Application.CreateForm(TfrmMain, frmMain); Application.Run; end; end.
unit FC.StockChart.UnitTask.ValueSupport.DataGridDialog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Contnrs, Dialogs, BaseUtils,SystemService, ufmDialogClose_B, ufmDialog_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, Spin, StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, DB, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, MemoryDS, ComCtrls, FC.StockChart.CustomDialog_B, ImgList, JvCaptionButton, JvComponentBase, JvDockControlForm, FC.Common.PeriodFrame, ToolWin,FC.fmUIDataStorage, Menus; type TfmValueStatisticsDialog = class(TfmStockChartCustomDialog_B) taReport: TMemoryDataSet; DataSource1: TDataSource; grReport: TEditDBGrid; Label2: TLabel; pbProgress: TProgressBar; taReportBarNo: TIntegerField; taReportDateTime: TDateTimeField; taReportValue: TFloatField; paTop: TPanel; frmPeriod: TfrmPeriod; ckFilter: TExtendCheckBox; buApplyFilter: TExtendButton; laStat: TLabel; ToolBar1: TToolBar; ActionList1: TActionList; acReload: TAction; acExportAsInserts: TAction; ToolButton1: TToolButton; ToolButton2: TToolButton; pmExport: TPopupMenu; ExportasSQLInserts1: TMenuItem; acCopyAsText: TAction; Copytoclipboardascommaseparatedtext1: TMenuItem; acExportToDB: TAction; N1: TMenuItem; ExporttoDB1: TMenuItem; procedure buOKClick(Sender: TObject); procedure grReportDblClick(Sender: TObject); procedure buCalculateClick(Sender: TObject); procedure ckFilterClick(Sender: TObject); procedure buApplyFilterClick(Sender: TObject); procedure acExportAsInsertsExecute(Sender: TObject); procedure acCopyAsTextExecute(Sender: TObject); procedure acExportToDBExecute(Sender: TObject); private FIndicator: ISCIndicatorValueSupport; procedure Calculate; procedure ApplyFilter; public class procedure Run(const aIndicator: ISCIndicatorValueSupport; const aStockChart: IStockChart); constructor Create(const aStockChart: IStockChart); override; destructor Destroy; override; end; implementation uses Math,Clipbrd,FC.StockData.StockTempValueCollection,FC.Singletons; type TDirection = (dNone,dUp,dDown); {$R *.dfm} { TfmCalculateWidthDialog } type TOrderState = (osNone,osBuy,osSell); procedure TfmValueStatisticsDialog.buOKClick(Sender: TObject); begin inherited; Close; end; procedure TfmValueStatisticsDialog.Calculate; var i,j,k: Integer; aInputData: ISCInputDataCollection; aCurProgress: integer; aValue : TStockRealNumber; begin TWaitCursor.SetUntilIdle; aInputData:=(FIndicator as ISCIndicator).GetInputData; taReport.DisableControls; try taReport.EmptyTable; taReport.Open; pbProgress.Max:=100; pbProgress.Position:=0; pbProgress.Visible:=true; aCurProgress:=0; for i:=(FIndicator as ISCIndicator).GetFirstValidValueIndex to aInputData.Count-1 do begin aValue:=FIndicator.GetValue(i); k:=taReport.DirectInsertRecord; taReport.DirectSetFieldData(k,taReportBarNo,i); taReport.DirectSetFieldData(k,taReportDateTime,aInputData.DirectGetItem_DataDateTime(i)); taReport.DirectSetFieldData(k,taReportValue,aValue); j:=(i div aInputData.Count)*100; if j<>aCurProgress then begin pbProgress.Position:=j; aCurProgress:=j; Application.ProcessMessages; end; end; i:=(FIndicator as ISCIndicator).GetFirstValidValueIndex; if i<=aInputData.Count-1 then begin frmPeriod.StartFrom:=aInputData.DirectGetItem_DataDateTime(i); frmPeriod.StopAt:=aInputData.DirectGetItem_DataDateTime(aInputData.Count-1); end; ApplyFilter; finally taReport.Refresh; grReport.RefreshSort; pbProgress.Visible:=false; taReport.EnableControls; end; end; procedure TfmValueStatisticsDialog.ckFilterClick(Sender: TObject); begin inherited; frmPeriod.Enabled:=ckFilter.Checked; end; procedure TfmValueStatisticsDialog.acCopyAsTextExecute(Sender: TObject); var aStrings:TStringList; begin inherited; TWaitCursor.SetUntilIdle; aStrings:=TStringList.Create; try taReport.DisableControls; try taReport.First; while not taReport.EOF do begin aStrings.Add(Format('%d, %s, %g',[taReportBarNo.Value,DateTimeToStr(taReportDateTime.Value),taReportValue.Value])); taReport.Next; end; finally taReport.EnableControls; end; Clipboard.Open; Clipboard.AsText:=aStrings.Text; Clipboard.Close; finally aStrings.Free; end; end; procedure TfmValueStatisticsDialog.acExportAsInsertsExecute(Sender: TObject); var aStrings:TStringList; begin inherited; TWaitCursor.SetUntilIdle; aStrings:=TStringList.Create; try taReport.SaveToSqlInserts(aStrings,0,'TMP$VALUE'); Clipboard.Open; Clipboard.AsText:=aStrings.Text; Clipboard.Close; finally aStrings.Free; end; end; procedure TfmValueStatisticsDialog.acExportToDBExecute(Sender: TObject); var aCollection:TStockTempValueCollection; aClearPrevData: boolean; begin inherited; aClearPrevData:=MsgBox.Confirm(Handle,'Empty database table before exporting?',[]); TWaitCursor.SetUntilIdle; aCollection:=TStockTempValueCollection.Create; IInterface(aCollection)._AddRef; try taReport.DisableControls; try taReport.First; while not taReport.EOF do begin aCollection.Add(taReportDateTime.Value,taReportValue.Value,taReportBarNo.Value,StockChart.StockSymbol.Name); taReport.Next; end; finally taReport.EnableControls; end; StockDataStorage.ImportTempValues(aCollection,aClearPrevData); finally IInterface(aCollection)._Release; end; end; procedure TfmValueStatisticsDialog.ApplyFilter; var aAVG:TStockRealNumber; aCount : integer; begin taReport.DisableControls; try taReport.Filter:=Format('(DATETIME >= %g) and (DATETIME<=%g)',[frmPeriod.StartFrom,frmPeriod.StopAt]); if taReport.Filtered<>ckFilter.Checked then taReport.Filtered:=ckFilter.Checked; taReport.First; aAVG:=0; aCount:=0; while not taReport.Eof do begin aAVG:=aAVG+taReportValue.Value; inc(aCount); taReport.Next; end; taReport.First; finally taReport.EnableControls; end; aAVG:=aAVG / aCount; laStat.Caption:=Format('COUNT = %d, AVG = %g',[aCount,aAVG]); end; procedure TfmValueStatisticsDialog.buApplyFilterClick(Sender: TObject); begin inherited; frmPeriod.AddValuesToMRU; TWaitCursor.SetUntilIdle; ApplyFilter; end; procedure TfmValueStatisticsDialog.buCalculateClick(Sender: TObject); begin inherited; Calculate; end; constructor TfmValueStatisticsDialog.Create(const aStockChart: IStockChart); begin inherited; frmPeriod.LoadSettings; ckFilterClick(nil); end; destructor TfmValueStatisticsDialog.Destroy; begin inherited; end; procedure TfmValueStatisticsDialog.grReportDblClick(Sender: TObject); begin inherited; TWaitCursor.SetUntilIdle; StockChart.LocateTo(taReportDateTime.Value,lmCenter); StockChart.Mark(taReportDateTime.Value); end; class procedure TfmValueStatisticsDialog.Run(const aIndicator: ISCIndicatorValueSupport; const aStockChart: IStockChart); begin with TfmValueStatisticsDialog.Create(aStockChart) do begin FIndicator:=aIndicator; Caption:=IndicatorFactory.GetIndicatorInfo((FIndicator as ISCIndicator).GetIID).Name+': '+Caption; Forms.Application.ProcessMessages; Calculate; Show; end; end; end.
(* Implementation of typical Observable. Before deciding to implement your own Observable, check here. --- Implicit infrastructure --- There are principles that may not be obvious in the code. One of the most important is that no event will be issued after the sequence is complete (onError or onCompleted). The implementation of the subject 'respects these principles. Security can not be guaranteed wherever Rx is used, so you better be aware and not violate this principle, as this can lead to vague consequences. *) unit Rx.Subjects; interface uses Rx, Rx.Implementations, Generics.Collections; type /// <summary> /// The simplest implementation of Subject. When data is transmitted to /// PublishSubject, it issues them to all subscribers who are subscribed to /// him at the moment. /// </summary> TPublishSubject<T> = class(TObservableImpl<T>) public procedure OnNext(const Data: T); override; end; /// <summary> /// Has a special ability to cache all the incoming data. /// When he has a new subscriber, the sequence is given to him /// since the beginning. All subsequent received data will be provided /// subscribers as usual. /// </summary> TReplaySubject<T> = class(TPublishSubject<T>) type TValue = TSmartVariable<T>; TVaueDescr = record Value: TValue; Stamp: TTime; end; strict private FCache: TList<TVaueDescr>; protected procedure OnSubscribe(Subscriber: ISubscriber<T>); override; public constructor Create; /// <summary> /// <para> /// Caching everything is not always the best idea, because /// sequences can be long or even infinite. /// </para> /// <para> /// CreateWithSize limits the size of the buffer, and /// CreateWithTime time that objects will remain in the cache. /// </para> /// </summary> constructor CreateWithSize(Size: LongWord); constructor CreateWithTime(Time: LongWord; TimeUnit: LongWord = Rx.TimeUnit.MILLISECONDS; From: TDateTime=Rx.StdSchedulers.IMMEDIATE); destructor Destroy; override; procedure OnNext(const Data: T); override; end; /// <summary> /// BehaviorSubject stores only the last value. This is the same as /// and ReplaySubject, but with a buffer of size 1. During creation, it can /// to be assigned an initial value, thus ensuring that the data /// will always be available to new subscribers. /// </summary> TBehaviorSubject<T> = class(TPublishSubject<T>) strict private FValue: TSmartVariable<T>; FValueExists: Boolean; protected procedure OnSubscribe(Subscriber: ISubscriber<T>); override; public constructor Create(const Value: T); overload; procedure OnNext(const Data: T); override; end; /// <summary> /// Also stores the last value. The difference is that it does not issue data /// until the sequence ends. It is used when /// you need to give a single value and immediately end. /// </summary> TAsyncSubject<T> = class(TObservableImpl<T>) type TValue = TSmartVariable<T>; strict private FCache: TList<TValue>; protected property Cache: TList<TValue> read FCache; public constructor Create; destructor Destroy; override; procedure OnNext(const Data: T); override; procedure OnCompleted; override; end; implementation uses SysUtils, Rx.Schedulers; { TPublishSubject<T> } procedure TPublishSubject<T>.OnNext(const Data: T); var Contract: IContract; Ref: TSmartVariable<T>; begin inherited; Ref := Data; if Supports(Scheduler, StdSchedulers.ICurrentThreadScheduler) then for Contract in Freeze do Contract.GetSubscriber.OnNext(TSmartVariable<T>.Create(Data)) else for Contract in Freeze do Scheduler.Invoke(TOnNextAction<T>.Create(Data, Contract)) end; { TReplaySubject<T> } constructor TReplaySubject<T>.Create; begin FCache := TList<TVaueDescr>.Create; end; constructor TReplaySubject<T>.CreateWithSize(Size: LongWord); begin Create; end; constructor TReplaySubject<T>.CreateWithTime(Time: LongWord; TimeUnit: LongWord; From: TDateTime); begin Create; end; destructor TReplaySubject<T>.Destroy; begin FCache.Free; inherited; end; procedure TReplaySubject<T>.OnNext(const Data: T); var Descr: TVaueDescr; begin inherited OnNext(Data); Descr.Value := Data; Descr.Stamp := Now; FCache.Add(Descr); end; procedure TReplaySubject<T>.OnSubscribe(Subscriber: ISubscriber<T>); var Descr: TVaueDescr; begin inherited; for Descr in FCache do Subscriber.OnNext(Descr.Value); end; { TBehaviorSubject<T> } constructor TBehaviorSubject<T>.Create(const Value: T); begin inherited Create; FValue := Value; FValueExists := True; end; procedure TBehaviorSubject<T>.OnNext(const Data: T); begin inherited; FValue := Data; FValueExists := True; end; procedure TBehaviorSubject<T>.OnSubscribe(Subscriber: ISubscriber<T>); begin inherited; if FValueExists then Subscriber.OnNext(FValue); end; { TAsyncSubject<T> } constructor TAsyncSubject<T>.Create; begin inherited Create; FCache := TList<TValue>.Create; end; destructor TAsyncSubject<T>.Destroy; begin FCache.Free; inherited; end; procedure TAsyncSubject<T>.OnCompleted; var Value: TValue; Contract: IContract; begin if Supports(Scheduler, StdSchedulers.ICurrentThreadScheduler) then for Contract in Freeze do for Value in FCache do Contract.GetSubscriber.OnNext(Value) else for Contract in Freeze do for Value in FCache do Scheduler.Invoke(TOnNextAction<T>.Create(Value, Contract)); inherited; end; procedure TAsyncSubject<T>.OnNext(const Data: T); begin inherited; FCache.Add(Data); end; end.
unit char_to_str_2; interface implementation var C: Char = 'Þ'; S: string; procedure Test; begin S := C; end; initialization Test(); finalization Assert(S = C); end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.Objects; {$I FMX.Defines.inc} {$H+} interface uses System.Classes, System.Types, System.UITypes, FMX.Types, FMX.Video; {$SCOPEDENUMS ON} type { TShape } TShape = class(TControl) private FFill: TBrush; FStrokeThickness: Single; FStroke: TBrush; FStrokeCap: TStrokeCap; FStrokeJoin: TStrokeJoin; FStrokeDash: TStrokeDash; procedure SetFill(const Value: TBrush); procedure SetStroke(const Value: TBrush); procedure SetStrokeThickness(const Value: Single); function IsStrokeThicknessStored: Boolean; procedure SetStrokeCap(const Value: TStrokeCap); procedure SetStrokeJoin(const Value: TStrokeJoin); procedure SetStrokeDash(const Value: TStrokeDash); protected procedure FillChanged(Sender: TObject); virtual; procedure StrokeChanged(Sender: TObject); virtual; function GetShapeRect: TRectF; procedure Painting; override; procedure AfterPaint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Fill: TBrush read FFill write SetFill; property Stroke: TBrush read FStroke write SetStroke; property StrokeThickness: Single read FStrokeThickness write SetStrokeThickness stored IsStrokeThicknessStored; property StrokeCap: TStrokeCap read FStrokeCap write SetStrokeCap default TStrokeCap.scFlat; property StrokeDash: TStrokeDash read FStrokeDash write SetStrokeDash default TStrokeDash.sdSolid; property StrokeJoin: TStrokeJoin read FStrokeJoin write SetStrokeJoin default TStrokeJoin.sjMiter; property ShapeRect: TRectF read GetShapeRect; end; { TLine } TLineType = (ltDiagonal, ltTop, ltLeft); TLine = class(TShape) private FLineType: TLineType; procedure SetLineType(const Value: TLineType); public constructor Create(AOwner: TComponent); override; procedure Paint; override; published property Stroke; property StrokeCap; property StrokeDash; property StrokeJoin; property StrokeThickness; property LineType: TLineType read FLineType write SetLineType; end; { TRectangle } TRectangle = class(TShape) private FYRadius: Single; FXRadius: Single; FCorners: TCorners; FCornerType: TCornerType; FSides: TSides; function IsCornersStored: Boolean; function IsSidesStored: Boolean; protected procedure SetXRadius(const Value: Single); virtual; procedure SetYRadius(const Value: Single); virtual; procedure SetCorners(const Value: TCorners); virtual; procedure SetCornerType(const Value: TCornerType); virtual; procedure SetSides(const Value: TSides); virtual; procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property Fill; property Stroke; property StrokeCap; property StrokeDash; property StrokeJoin; property StrokeThickness; property XRadius: Single read FXRadius write SetXRadius; property YRadius: Single read FYRadius write SetYRadius; property Corners: TCorners read FCorners write SetCorners stored IsCornersStored; property CornerType: TCornerType read FCornerType write SetCornerType default TCornerType.ctRound; property Sides: TSides read FSides write SetSides stored IsSidesStored; end; { TRoundRect } TRoundRect = class(TShape) private FCorners: TCorners; function IsCornersStored: Boolean; protected procedure SetCorners(const Value: TCorners); virtual; procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property Fill; property Stroke; property StrokeCap; property StrokeDash; property StrokeJoin; property StrokeThickness; property Corners: TCorners read FCorners write SetCorners stored IsCornersStored; end; { TCalloutRectangle } TCalloutPosition = (cpTop, cpLeft, cpBottom, cpRight); TCalloutRectangle = class(TRectangle) private FPath: TPathData; FCalloutWidth: Single; FCalloutLength: Single; FCalloutPosition: TCalloutPosition; FCalloutOffset: Single; procedure SetCalloutWidth(const Value: Single); procedure SetCalloutLength(const Value: Single); procedure SetCalloutPosition(const Value: TCalloutPosition); procedure SetCalloutOffset(const Value: Single); protected procedure CreatePath; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Fill; property CalloutWidth: Single read FCalloutWidth write SetCalloutWidth; property CalloutLength: Single read FCalloutLength write SetCalloutLength; property CalloutPosition: TCalloutPosition read FCalloutPosition write SetCalloutPosition default TCalloutPosition.cpTop; property CalloutOffset: Single read FCalloutOffset write SetCalloutOffset; property Stroke; property StrokeCap; property StrokeDash; property StrokeJoin; property StrokeThickness; end; { TEllipse } TEllipse = class(TShape) protected function PointInObject(X, Y: Single): Boolean; override; procedure Paint; override; published property Fill; property Stroke; property StrokeCap; property StrokeDash; property StrokeJoin; property StrokeThickness; end; { TCircle } TCircle = class(TEllipse) protected procedure Paint; override; end; { TPie } TPie = class(TEllipse) private FStartAngle: Single; FEndAngle: Single; procedure SetEndAngle(const Value: Single); procedure SetStartAngle(const Value: Single); protected function PointInObject(X, Y: Single): Boolean; override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property StartAngle: Single read FStartAngle write SetStartAngle; property EndAngle: Single read FEndAngle write SetEndAngle; end; { TArc } TArc = class(TEllipse) private FStartAngle: Single; FEndAngle: Single; procedure SetEndAngle(const Value: Single); procedure SetStartAngle(const Value: Single); protected function PointInObject(X, Y: Single): Boolean; override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property StartAngle: Single read FStartAngle write SetStartAngle; property EndAngle: Single read FEndAngle write SetEndAngle; end; TPathWrapMode = (pwOriginal, pwFit, pwStretch, pwTile); { TCustomPath } TCustomPath = class(TShape) private FData, FCurrent: TPathData; FWrapMode: TPathWrapMode; procedure SetData(const Value: TPathData); procedure SetWrapMode(const Value: TPathWrapMode); protected function PointInObject(X, Y: Single): Boolean; override; procedure DoChanged(Sender: TObject); procedure Paint; override; procedure Resize; override; procedure Loaded; override; procedure UpdatePath; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Data: TPathData read FData write SetData; property WrapMode: TPathWrapMode read FWrapMode write SetWrapMode default TPathWrapMode.pwStretch; published property Fill; property Stroke; property StrokeCap; property StrokeDash; property StrokeJoin; property StrokeThickness; end; { TPath } TPath = class(TCustomPath) published property Data; property WrapMode; end; { TText } TText = class(TShape) private FText: string; FFont: TFont; FVertTextAlign: TTextAlign; FHorzTextAlign: TTextAlign; FWordWrap: Boolean; FAutoSize: Boolean; FStretch: Boolean; procedure SetText(const Value: string); procedure SetFont(const Value: TFont); procedure SetHorzTextAlign(const Value: TTextAlign); procedure SetVertTextAlign(const Value: TTextAlign); procedure SetWordWrap(const Value: Boolean); procedure SetAutoSize(const Value: Boolean); procedure SetStretch(const Value: Boolean); protected procedure FontChanged(Sender: TObject); virtual; procedure Paint; override; function GetData: Variant; override; procedure SetData(const Value: Variant); override; procedure AdjustSize; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Realign; override; published property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property Fill; property Font: TFont read FFont write SetFont; property HorzTextAlign: TTextAlign read FHorzTextAlign write SetHorzTextAlign default TTextAlign.taCenter; property VertTextAlign: TTextAlign read FVertTextAlign write SetVertTextAlign default TTextAlign.taCenter; property Text: string read FText write SetText; property Stretch: Boolean read FStretch write SetStretch default False; property WordWrap: Boolean read FWordWrap write SetWordWrap default True; end; { TImage } TImageWrapMode = (iwOriginal, iwFit, iwStretch, iwTile); TImage = class(TControl) private FBitmap: TBitmap; FBitmapMargins: TBounds; FWrapMode: TImageWrapMode; FDisableInterpolation: Boolean; procedure SetBitmap(const Value: TBitmap); procedure SetWrapMode(const Value: TImageWrapMode); protected procedure DoBitmapChanged(Sender: TObject); virtual; procedure Paint; override; function GetData: Variant; override; procedure SetData(const Value: Variant); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Bitmap: TBitmap read FBitmap write SetBitmap; property BitmapMargins: TBounds read FBitmapMargins write FBitmapMargins; property WrapMode: TImageWrapMode read FWrapMode write SetWrapMode default TImageWrapMode.iwFit; property DisableInterpolation: Boolean read FDisableInterpolation write FDisableInterpolation default False; end; { TPaintBox } TPaintEvent = procedure(Sender: TObject; Canvas: TCanvas) of object; TPaintBox = class(TControl) private FOnPaint: TPaintEvent; protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnPaint: TPaintEvent read FOnPaint write FOnPaint; end; { TSelection } TSelection = class(TControl) private FParentBounds: Boolean; FOnChange: TNotifyEvent; FHideSelection: Boolean; FMinSize: Integer; FOnTrack: TNotifyEvent; FProportional: Boolean; FGripSize: Single; procedure SetHideSelection(const Value: Boolean); procedure SetMinSize(const Value: Integer); procedure SetGripSize(const Value: Single); protected FRatio: Single; FMove, FLeftTop, FLeftBottom, FRightTop, FRightBottom: Boolean; FLeftTopHot, FLeftBottomHot, FRightTopHot, FRightBottomHot: Boolean; FDownPos, FMovePos: TPointF; function GetAbsoluteRect: TRectF; override; function PointInObject(X, Y: Single): Boolean; override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure DoMouseLeave; override; published property GripSize: Single read FGripSize write SetGripSize; property ParentBounds: Boolean read FParentBounds write FParentBounds default True; property HideSelection: Boolean read FHideSelection write SetHideSelection; property MinSize: Integer read FMinSize write SetMinSize default 15; property Proportional: Boolean read FProportional write FProportional; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnTrack: TNotifyEvent read FOnTrack write FOnTrack; end; { TSelectionPoint } TSelectionPoint = class(TControl) private FOnChange: TNotifyEvent; FOnTrack: TNotifyEvent; FParentBounds: Boolean; FGripSize: Single; procedure SetGripSize(const Value: Single); protected FPressed: Boolean; procedure Paint; override; procedure SetHeight(const Value: Single); override; procedure SetWidth(const Value: Single); override; function PointInObject(X, Y: Single): Boolean; override; function GetUpdateRect: TRectF; override; procedure DoMouseEnter; override; procedure DoMouseLeave; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; published property GripSize: Single read FGripSize write SetGripSize; property ParentBounds: Boolean read FParentBounds write FParentBounds default True; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnTrack: TNotifyEvent read FOnTrack write FOnTrack; end; implementation uses System.SysUtils, System.Math, FMX.Effects; { TShape } constructor TShape.Create(AOwner: TComponent); begin inherited; FFill := TBrush.Create(TBrushKind.bkSolid, $FFE0E0E0); FFill.OnChanged := FillChanged; FStroke := TBrush.Create(TBrushKind.bkSolid, $FF000000); FStroke.Color := $FF000000; FStroke.OnChanged := StrokeChanged; FStrokeThickness := 1; SetAcceptsControls(False); end; destructor TShape.Destroy; begin FStroke.Free; FFill.Free; inherited; end; function TShape.GetShapeRect: TRectF; begin Result := LocalRect; if FStroke.Kind <> TBrushKind.bkNone then if Odd(Round(FStrokeThickness)) then begin InflateRect(Result, -(FStrokeThickness / 2), -(FStrokeThickness / 2)); end else InflateRect(Result, -(FStrokeThickness / 2), -(FStrokeThickness / 2)); end; procedure TShape.FillChanged(Sender: TObject); begin if FUpdating = 0 then Repaint; end; procedure TShape.StrokeChanged(Sender: TObject); begin if FUpdating = 0 then Repaint; end; procedure TShape.Painting; begin inherited; Canvas.Fill.Assign(FFill); Canvas.Stroke.Assign(FStroke); Canvas.StrokeThickness := FStrokeThickness; Canvas.StrokeCap := FStrokeCap; Canvas.StrokeJoin := FStrokeJoin; Canvas.StrokeDash := FStrokeDash; end; procedure TShape.AfterPaint; begin inherited AfterPaint; Canvas.StrokeDash := TStrokeDash.sdSolid; Canvas.StrokeThickness := 1; end; function TShape.IsStrokeThicknessStored: Boolean; begin Result := StrokeThickness <> 1; end; procedure TShape.SetFill(const Value: TBrush); begin FFill.Assign(Value); end; procedure TShape.SetStroke(const Value: TBrush); begin FStroke.Assign(Value); end; procedure TShape.SetStrokeThickness(const Value: Single); begin if FStrokeThickness <> Value then begin FStrokeThickness := Value; Repaint; end; end; procedure TShape.SetStrokeCap(const Value: TStrokeCap); begin if FStrokeCap <> Value then begin FStrokeCap := Value; Repaint; end; end; procedure TShape.SetStrokeJoin(const Value: TStrokeJoin); begin if FStrokeJoin <> Value then begin FStrokeJoin := Value; Repaint; end; end; procedure TShape.SetStrokeDash(const Value: TStrokeDash); begin if FStrokeDash <> Value then begin FStrokeDash := Value; Repaint; end; end; { TLine } constructor TLine.Create(AOwner: TComponent); begin inherited; end; procedure TLine.Paint; begin case FLineType of TLineType.ltTop: Canvas.DrawLine(GetShapeRect.TopLeft, PointF(GetShapeRect.Right, GetShapeRect.Top), AbsoluteOpacity); TLineType.ltLeft: Canvas.DrawLine(GetShapeRect.TopLeft, PointF(GetShapeRect.Left, GetShapeRect.Bottom), AbsoluteOpacity); else Canvas.DrawLine(GetShapeRect.TopLeft, GetShapeRect.BottomRight, AbsoluteOpacity); end; end; procedure TLine.SetLineType(const Value: TLineType); begin if FLineType <> Value then begin FLineType := Value; Repaint; end; end; { TEllipse } procedure TEllipse.Paint; begin Canvas.FillEllipse(GetShapeRect, AbsoluteOpacity); Canvas.DrawEllipse(GetShapeRect, AbsoluteOpacity); end; function TEllipse.PointInObject(X, Y: Single): Boolean; var P: TPointF; begin Result := False; P := AbsoluteToLocal(PointF(X, Y)); if Width * Height = 0 then Exit; if (Sqr((P.X * 2 - Width) / Width) + Sqr((P.Y * 2 - Height) / Height) <= 1) then begin Result := True; end; end; { TCircle } procedure TCircle.Paint; var R: TRectF; begin R := RectF(0, 0, Max(Width, Height), Max(Width, Height)); FitRect(R, GetShapeRect); Canvas.FillEllipse(R, AbsoluteOpacity); Canvas.DrawEllipse(R, AbsoluteOpacity); end; { TPie } constructor TPie.Create(AOwner: TComponent); begin inherited; FStartAngle := 0; FEndAngle := -90; end; procedure TPie.Paint; var P: TPathData; begin P := TPathData.Create; P.MoveTo(PointF(Width / 2, Height / 2)); P.AddArc(PointF(Width / 2, Height / 2), PointF((Width - StrokeThickness) / 2, (Height - StrokeThickness) / 2), FStartAngle, FEndAngle - FStartAngle); P.LineTo(PointF(Width / 2, Height / 2)); P.ClosePath; Canvas.FillPath(P, AbsoluteOpacity); Canvas.DrawPath(P, AbsoluteOpacity); P.Free; end; function TPie.PointInObject(X, Y: Single): Boolean; var P: TPathData; begin if (Canvas <> nil) then begin P := TPathData.Create; P.MoveTo(PointF(Width / 2, Height / 2)); P.AddArc(PointF(Width / 2, Height / 2), PointF((Width - StrokeThickness) / 2, (Height - StrokeThickness) / 2), FStartAngle, FEndAngle - FStartAngle); P.LineTo(PointF(Width / 2, Height / 2)); P.ClosePath; Result := Canvas.PtInPath(AbsoluteToLocal(PointF(X, Y)), P); P.Free; end else Result := inherited PointInObject(X, Y); end; procedure TPie.SetEndAngle(const Value: Single); begin if FEndAngle <> Value then begin FEndAngle := Value; Repaint; end; end; procedure TPie.SetStartAngle(const Value: Single); begin if FStartAngle <> Value then begin FStartAngle := Value; Repaint; end; end; { TArc } constructor TArc.Create(AOwner: TComponent); begin inherited; Fill.Kind := TBrushKind.bkNone; Fill.DefaultKind := TBrushKind.bkNone; FStartAngle := 0; FEndAngle := -90; end; procedure TArc.Paint; begin Canvas.FillArc(PointF(Width / 2, Height / 2), PointF((Width - StrokeThickness) / 2, ((Height - StrokeThickness) / 2)), FStartAngle, FEndAngle, AbsoluteOpacity); Canvas.DrawArc(PointF(Width / 2, Height / 2), PointF((Width - StrokeThickness) / 2, ((Height - StrokeThickness) / 2)), FStartAngle, FEndAngle, AbsoluteOpacity); end; function TArc.PointInObject(X, Y: Single): Boolean; begin Result := inherited PointInObject(X, Y); end; procedure TArc.SetEndAngle(const Value: Single); begin if FEndAngle <> Value then begin FEndAngle := Value; Repaint; end; end; procedure TArc.SetStartAngle(const Value: Single); begin if FStartAngle <> Value then begin FStartAngle := Value; Repaint; end; end; { TRectangle } constructor TRectangle.Create(AOwner: TComponent); begin inherited; FCorners := AllCorners; FXRadius := 0; FYRadius := 0; FSides := AllSides; end; function TRectangle.IsCornersStored: Boolean; begin Result := FCorners <> AllCorners; end; function TRectangle.IsSidesStored: Boolean; begin Result := FSides * AllSides <> AllSides end; procedure TRectangle.Paint; var R: TRectF; Off: Single; begin R := GetShapeRect; if Fill.Kind = TBrushKind.bkGrab then OffsetRect(R, Position.X, Position.Y); if Sides <> AllSides then begin Off := R.Left; if not(TSide.sdTop in FSides) then R.Top := R.Top - Off; if not(TSide.sdLeft in FSides) then R.Left := R.Left - Off; if not(TSide.sdBottom in FSides) then R.Bottom := R.Bottom + Off; if not(TSide.sdRight in FSides) then R.Right := R.Right + Off; Canvas.FillRect(R, XRadius, YRadius, FCorners, AbsoluteOpacity, CornerType); Canvas.DrawRectSides(GetShapeRect, XRadius, YRadius, FCorners, AbsoluteOpacity, Sides, CornerType); end else begin Canvas.FillRect(R, XRadius, YRadius, FCorners, AbsoluteOpacity, CornerType); Canvas.DrawRect(R, XRadius, YRadius, FCorners, AbsoluteOpacity, CornerType); end; end; procedure TRectangle.SetCorners(const Value: TCorners); begin if FCorners <> Value then begin FCorners := Value; Repaint; end; end; procedure TRectangle.SetCornerType(const Value: TCornerType); begin if FCornerType <> Value then begin FCornerType := Value; Repaint; end; end; procedure TRectangle.SetXRadius(const Value: Single); begin if FXRadius <> Value then begin FXRadius := Value; Repaint; end; end; procedure TRectangle.SetYRadius(const Value: Single); begin if FYRadius <> Value then begin FYRadius := Value; Repaint; end; end; procedure TRectangle.SetSides(const Value: TSides); begin if FSides <> Value then begin FSides := Value; Repaint; end; end; { TRoundRect } constructor TRoundRect.Create(AOwner: TComponent); begin inherited; FCorners := AllCorners; end; function TRoundRect.IsCornersStored: Boolean; begin Result := FCorners <> AllCorners; end; procedure TRoundRect.Paint; var Radius: Single; begin if Height < Width then Radius := RectHeight(GetShapeRect) / 2 else Radius := RectWidth(GetShapeRect) / 2; Canvas.FillRect(GetShapeRect, Radius, Radius, FCorners, AbsoluteOpacity); Canvas.DrawRect(GetShapeRect, Radius, Radius, FCorners, AbsoluteOpacity); end; procedure TRoundRect.SetCorners(const Value: TCorners); begin if FCorners <> Value then begin FCorners := Value; Repaint; end; end; { TCalloutRectangle } constructor TCalloutRectangle.Create(AOwner: TComponent); begin inherited; FCalloutWidth := 23; FCalloutLength := 11; FPath := TPathData.Create; end; destructor TCalloutRectangle.Destroy; begin FreeAndNil(FPath); inherited; end; procedure TCalloutRectangle.CreatePath; var x1, x2, y1, y2: Single; R: TRectF; Off: Single; begin R := GetShapeRect; case CalloutPosition of TCalloutPosition.cpTop: R.Top := R.Top + FCalloutLength; TCalloutPosition.cpLeft: R.Left := R.Left + FCalloutLength; TCalloutPosition.cpBottom: R.Bottom := R.Bottom - FCalloutLength; TCalloutPosition.cpRight: R.Right := R.Right - FCalloutLength; end; if Sides <> AllSides then begin Off := R.Left; if not(TSide.sdTop in FSides) then R.Top := R.Top - Off; if not(TSide.sdLeft in FSides) then R.Left := R.Left - Off; if not(TSide.sdBottom in FSides) then R.Bottom := R.Bottom + Off; if not(TSide.sdRight in FSides) then R.Right := R.Right + Off; end; x1 := XRadius; if (RectWidth(R) - (x1 * 2) < 0) and (x1 > 0) then x1 := (XRadius * (RectWidth(R) / (x1 * 2))); x2 := x1 / 2; y1 := YRadius; if (RectHeight(R) - (y1 * 2) < 0) and (y1 > 0) then y1 := (YRadius * (RectHeight(R) / (y1 * 2))); y2 := y1 / 2; FPath.Clear; FPath.MoveTo(PointF(R.Left, R.Top + y1)); if TCorner.crTopLeft in FCorners then begin case FCornerType of // ctRound - default TCornerType.ctBevel: FPath.LineTo(PointF(R.Left + x1, R.Top)); TCornerType.ctInnerRound: FPath.CurveTo(PointF(R.Left + x2, R.Top + y1), PointF(R.Left + x1, R.Top + y2), PointF(R.Left + x1, R.Top)); TCornerType.ctInnerLine: begin FPath.LineTo(PointF(R.Left + x2, R.Top + y1)); FPath.LineTo(PointF(R.Left + x1, R.Top + y2)); FPath.LineTo(PointF(R.Left + x1, R.Top)); end; else FPath.CurveTo(PointF(R.Left, R.Top + (y2)), PointF(R.Left + x2, R.Top), PointF(R.Left + x1, R.Top)) end; end else begin if TSide.sdLeft in FSides then FPath.LineTo(R.TopLeft) else FPath.MoveTo(R.TopLeft); if TSide.sdTop in FSides then FPath.LineTo(PointF(R.Left + x1, R.Top)) else FPath.MoveTo(PointF(R.Left + x1, R.Top)); end; if not(TSide.sdTop in FSides) then FPath.MoveTo(PointF(R.Right - x1, R.Top)) else begin if (FCalloutPosition = TCalloutPosition.cpTop) then begin if CalloutOffset = 0 then begin FPath.LineTo(PointF((R.Right - R.Left) / 2 - (CalloutWidth / 2), R.Top)); FPath.LineTo(PointF((R.Right - R.Left) / 2, R.Top - FCalloutLength)); FPath.LineTo(PointF((R.Right - R.Left) / 2 + (CalloutWidth / 2), R.Top)); FPath.LineTo(PointF(R.Right - x1, R.Top)); end else if CalloutOffset > 0 then begin FPath.LineTo(PointF(R.Left + FCalloutOffset, R.Top)); FPath.LineTo(PointF(R.Left + FCalloutOffset + (CalloutWidth / 2), R.Top - FCalloutLength)); FPath.LineTo(PointF(R.Left + FCalloutOffset + CalloutWidth, R.Top)); FPath.LineTo(PointF(R.Right - x1, R.Top)); end else begin FPath.LineTo(PointF(R.Right - Abs(FCalloutOffset) - CalloutWidth, R.Top)); FPath.LineTo(PointF(R.Right - Abs(FCalloutOffset) - (CalloutWidth / 2), R.Top - FCalloutLength)); FPath.LineTo(PointF(R.Right - Abs(FCalloutOffset), R.Top)); FPath.LineTo(PointF(R.Right - x1, R.Top)); end; end else FPath.LineTo(PointF(R.Right - x1, R.Top)); end; if TCorner.crTopRight in FCorners then begin case FCornerType of // ctRound - default TCornerType.ctBevel: FPath.LineTo(PointF(R.Right, R.Top + y1)); TCornerType.ctInnerRound: FPath.CurveTo(PointF(R.Right - x1, R.Top + y2), PointF(R.Right - x2, R.Top + y1), PointF(R.Right, R.Top + y1)); TCornerType.ctInnerLine: begin FPath.LineTo(PointF(R.Right - x1, R.Top + y2)); FPath.LineTo(PointF(R.Right - x2, R.Top + y1)); FPath.LineTo(PointF(R.Right, R.Top + y1)); end; else FPath.CurveTo(PointF(R.Right - x2, R.Top), PointF(R.Right, R.Top + (y2)), PointF(R.Right, R.Top + y1)) end; end else begin if TSide.sdTop in FSides then FPath.LineTo(PointF(R.Right, R.Top)) else FPath.MoveTo(PointF(R.Right, R.Top)); if TSide.sdRight in FSides then FPath.LineTo(PointF(R.Right, R.Top + y1)) else FPath.MoveTo(PointF(R.Right, R.Top + y1)); end; if not(TSide.sdRight in FSides) then FPath.MoveTo(PointF(R.Right, R.Bottom - y1)) else begin if (FCalloutPosition = TCalloutPosition.cpRight) then begin if CalloutOffset = 0 then begin FPath.LineTo(PointF(R.Right, (R.Bottom - R.Top) / 2 - (CalloutWidth / 2))); FPath.LineTo(PointF(R.Right + FCalloutLength, (R.Bottom - R.Top) / 2)); FPath.LineTo(PointF(R.Right, (R.Bottom - R.Top) / 2 + (CalloutWidth / 2))); FPath.LineTo(PointF(R.Right, R.Bottom - y1)); end else if CalloutOffset > 0 then begin FPath.LineTo(PointF(R.Right, R.Top + CalloutOffset)); FPath.LineTo(PointF(R.Right + FCalloutLength, R.Top + CalloutOffset + (CalloutWidth / 2))); FPath.LineTo(PointF(R.Right, R.Top + CalloutOffset + CalloutWidth)); FPath.LineTo(PointF(R.Right, R.Bottom - y1)); end else begin FPath.LineTo(PointF(R.Right, R.Bottom + CalloutOffset)); FPath.LineTo(PointF(R.Right + FCalloutLength, R.Bottom + CalloutOffset + (CalloutWidth / 2))); FPath.LineTo(PointF(R.Right, R.Bottom + CalloutOffset + CalloutWidth)); FPath.LineTo(PointF(R.Right, R.Bottom - y1)); end; end else FPath.LineTo(PointF(R.Right, R.Bottom - y1)); end; if TCorner.crBottomRight in FCorners then begin case FCornerType of // ctRound - default TCornerType.ctBevel: FPath.LineTo(PointF(R.Right - x1, R.Bottom)); TCornerType.ctInnerRound: FPath.CurveTo(PointF(R.Right - x2, R.Bottom - y1), PointF(R.Right - x1, R.Bottom - y2), PointF(R.Right - x1, R.Bottom)); TCornerType.ctInnerLine: begin FPath.LineTo(PointF(R.Right - x2, R.Bottom - y1)); FPath.LineTo(PointF(R.Right - x1, R.Bottom - y2)); FPath.LineTo(PointF(R.Right - x1, R.Bottom)); end; else FPath.CurveTo(PointF(R.Right, R.Bottom - (y2)), PointF(R.Right - x2, R.Bottom), PointF(R.Right - x1, R.Bottom)) end; end else begin if TSide.sdRight in FSides then FPath.LineTo(PointF(R.Right, R.Bottom)) else FPath.MoveTo(PointF(R.Right, R.Bottom)); if TSide.sdBottom in FSides then FPath.LineTo(PointF(R.Right - x1, R.Bottom)) else FPath.MoveTo(PointF(R.Right - x1, R.Bottom)); end; if not(TSide.sdBottom in FSides) then FPath.MoveTo(PointF(R.Left + x1, R.Bottom)) else begin if (FCalloutPosition = TCalloutPosition.cpBottom) then begin if CalloutOffset = 0 then begin FPath.LineTo(PointF((R.Right - R.Left) / 2 + (CalloutWidth / 2), R.Bottom)); FPath.LineTo(PointF((R.Right - R.Left) / 2, R.Bottom + FCalloutLength)); FPath.LineTo(PointF((R.Right - R.Left) / 2 - (CalloutWidth / 2), R.Bottom)); FPath.LineTo(PointF(R.Left + x1, R.Bottom)); end else if CalloutOffset > 0 then begin FPath.LineTo(PointF(R.Left + FCalloutOffset + CalloutWidth, R.Bottom)); FPath.LineTo(PointF(R.Left + FCalloutOffset + (CalloutWidth / 2), R.Bottom + FCalloutLength)); FPath.LineTo(PointF(R.Left + FCalloutOffset, R.Bottom)); FPath.LineTo(PointF(R.Left + x1, R.Bottom)); end else begin FPath.LineTo(PointF(R.Right - Abs(FCalloutOffset), R.Bottom)); FPath.LineTo(PointF(R.Right - Abs(FCalloutOffset) - (CalloutWidth / 2), R.Bottom + FCalloutLength)); FPath.LineTo(PointF(R.Right - Abs(FCalloutOffset) - CalloutWidth, R.Bottom)); FPath.LineTo(PointF(R.Left + x1, R.Bottom)); end; end else FPath.LineTo(PointF(R.Left + x1, R.Bottom)); end; if TCorner.crBottomLeft in FCorners then begin case FCornerType of // ctRound - default TCornerType.ctBevel: FPath.LineTo(PointF(R.Left, R.Bottom - y1)); TCornerType.ctInnerRound: FPath.CurveTo(PointF(R.Left + x1, R.Bottom - y2), PointF(R.Left + x2, R.Bottom - y1), PointF(R.Left, R.Bottom - y1)); TCornerType.ctInnerLine: begin FPath.LineTo(PointF(R.Left + x1, R.Bottom - y2)); FPath.LineTo(PointF(R.Left + x2, R.Bottom - y1)); FPath.LineTo(PointF(R.Left, R.Bottom - y1)); end; else FPath.CurveTo(PointF(R.Left + x2, R.Bottom), PointF(R.Left, R.Bottom - (y2) ), PointF(R.Left, R.Bottom - y1)) end; end else begin if TSide.sdBottom in FSides then FPath.LineTo(PointF(R.Left, R.Bottom)) else FPath.MoveTo(PointF(R.Left, R.Bottom)); if TSide.sdLeft in FSides then FPath.LineTo(PointF(R.Left, R.Bottom - y1)) else FPath.MoveTo(PointF(R.Left, R.Bottom - y1)); end; if (TSide.sdLeft in FSides) then begin if (FCalloutPosition = TCalloutPosition.cpLeft) then begin if CalloutOffset = 0 then begin FPath.LineTo(PointF(R.Left, (R.Bottom - R.Top) / 2 + (CalloutWidth / 2))); FPath.LineTo(PointF(R.Left - FCalloutLength, (R.Bottom - R.Top) / 2)); FPath.LineTo(PointF(R.Left, (R.Bottom - R.Top) / 2 - (CalloutWidth / 2))); FPath.LineTo(PointF(R.Left, R.Top + y1)); end else if CalloutOffset > 0 then begin FPath.LineTo(PointF(R.Left, R.Top + CalloutOffset + CalloutWidth)); FPath.LineTo(PointF(R.Left - FCalloutLength, R.Top + CalloutOffset + (CalloutWidth / 2))); FPath.LineTo(PointF(R.Left, R.Top + CalloutOffset)); FPath.LineTo(PointF(R.Left, R.Top + y1)); end else begin FPath.LineTo(PointF(R.Left, R.Bottom + CalloutOffset + CalloutWidth)); FPath.LineTo(PointF(R.Left - FCalloutLength, R.Bottom + CalloutOffset + (CalloutWidth / 2))); FPath.LineTo(PointF(R.Left, R.Bottom + CalloutOffset)); FPath.LineTo(PointF(R.Left, R.Top + y1)); end; end else FPath.LineTo(PointF(R.Left, R.Top + y1)); end; end; procedure TCalloutRectangle.Paint; begin CreatePath; Canvas.FillPath(FPath, AbsoluteOpacity); Canvas.DrawPath(FPath, AbsoluteOpacity); end; procedure TCalloutRectangle.SetCalloutWidth(const Value: Single); begin if FCalloutWidth <> Value then begin FCalloutWidth := Value; CreatePath; Repaint; end; end; procedure TCalloutRectangle.SetCalloutLength(const Value: Single); begin if FCalloutLength <> Value then begin FCalloutLength := Value; CreatePath; Repaint; end; end; procedure TCalloutRectangle.SetCalloutPosition(const Value: TCalloutPosition); begin if FCalloutPosition <> Value then begin FCalloutPosition := Value; CreatePath; Repaint; end; end; procedure TCalloutRectangle.SetCalloutOffset(const Value: Single); begin if FCalloutOffset <> Value then begin FCalloutOffset := Value; CreatePath; Repaint; end; end; { TText } constructor TText.Create(AOwner: TComponent); begin inherited; FHorzTextAlign := TTextAlign.taCenter; FVertTextAlign := TTextAlign.taCenter; FWordWrap := True; FFont := TFont.Create; FFont.OnChanged := FontChanged; Fill.DefaultColor := $FF000000; Fill.Color := $FF000000; Stroke.DefaultKind := TBrushKind.bkNone; Stroke.Kind := TBrushKind.bkNone; end; destructor TText.Destroy; begin FFont.Free; inherited; end; function TText.GetData: Variant; begin Result := Text; end; procedure TText.SetData(const Value: Variant); begin Text := Value; end; procedure TText.FontChanged(Sender: TObject); begin if FAutoSize then AdjustSize; Repaint; end; procedure TText.Paint; var R: TRectF; M: TMatrix; begin if (csDesigning in ComponentState) and not Locked and not FInPaintTo then begin R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $A0909090; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; end; Canvas.Font.Assign(FFont); if FStretch then begin R := RectF(0, 0, 1000, 1000); Canvas.MeasureText(R, FText, False, [], FHorzTextAlign, FVertTextAlign); OffsetRect(R, -R.Left, -R.Top); M := IdentityMatrix; if not IsRectEmpty(R) then begin M.m11 := RectWidth(LocalRect) / RectWidth(R); M.m22 := RectHeight(LocalRect) / RectHeight(R); end; Canvas.MultyMatrix(M); InflateRect(R, Font.Size / 3, Font.Size / 3); Canvas.FillText(R, FText, False, AbsoluteOpacity, FillTextFlags, TTextAlign.taCenter, TTextAlign.taCenter); end else Canvas.FillText(LocalRect, FText, FWordWrap, AbsoluteOpacity, FillTextFlags, FHorzTextAlign, FVertTextAlign); end; procedure TText.SetWordWrap(const Value: Boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; AdjustSize; Repaint; end; end; procedure TText.SetAutoSize(const Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; AdjustSize; end; end; procedure TText.SetStretch(const Value: Boolean); begin if FStretch <> Value then begin FStretch := Value; if Stretch then AutoSize := False; Repaint; end; end; procedure TText.AdjustSize; var R: TRectF; C: TCanvas; begin if FDisableAlign then Exit; FDisableAlign := True; try if Canvas = nil then begin C := GetMeasureBitmap.Canvas; end else C := Canvas; if FAutoSize and (FText <> '') then begin C.Font.Assign(FFont); if WordWrap then R := RectF(0, 0, Width, MaxSingle) else R := RectF(0, 0, MaxSingle, MaxSingle); C.MeasureText(R, FText, WordWrap, [], TTextAlign.taLeading, TTextAlign.taLeading); if not WordWrap then Width := R.Right; if VertTextAlign <> TTextAlign.taCenter then Height := R.Bottom; end; if FAutoSize and (FText <> '') then begin SetBounds(Position.X, Position.Y, R.Width + 4, R.Height + 4); if (Parent <> nil) and (Parent is TControl) then TControl(Parent).Realign; end; finally FDisableAlign := False; end; end; procedure TText.Realign; begin inherited; if FAutoSize then AdjustSize; end; procedure TText.SetFont(const Value: TFont); begin FFont.Assign(Value); if FAutoSize then AdjustSize; end; procedure TText.SetHorzTextAlign(const Value: TTextAlign); begin if FHorzTextAlign <> Value then begin FHorzTextAlign := Value; Repaint; end; end; procedure TText.SetVertTextAlign(const Value: TTextAlign); begin if FVertTextAlign <> Value then begin FVertTextAlign := Value; Repaint; end; end; procedure TText.SetText(const Value: string); begin if FText <> Value then begin if Length(Value) < Length(FText) then Repaint; FText := Value; if FAutoSize then AdjustSize; Repaint; end; end; { TImage } constructor TImage.Create(AOwner: TComponent); begin inherited; FBitmap := TBitmap.Create(0, 0); FBitmap.OnChange := DoBitmapChanged; FBitmapMargins := TBounds.Create(RectF(0, 0, 0, 0)); FWrapMode := TImageWrapMode.iwFit; SetAcceptsControls(False); end; destructor TImage.Destroy; begin FreeAndNil(FBitmapMargins); FBitmap.Free; inherited; end; function TImage.GetData: Variant; begin Result := ObjectToVariant(FBitmap); end; procedure TImage.SetData(const Value: Variant); begin if VarIsObject(Value) then begin if VariantToObject(Value) is TPersistent then FBitmap.Assign(TPersistent(VariantToObject(Value))); end else FBitmap.LoadFromFile(Value) end; procedure TImage.DoBitmapChanged(Sender: TObject); begin Repaint; UpdateEffects; end; procedure TImage.Paint; var R: TRectF; State: TCanvasSaveState; i, j: Integer; B: TBitmap; begin if (csDesigning in ComponentState) and not Locked and not FInPaintTo then begin R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $A0909090; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; end; B := FBitmap; if FBitmap.ResourceBitmap <> nil then B := FBitmap.ResourceBitmap; if B.IsEmpty then Exit; if not FBitmapMargins.MarginEmpty then begin { lefttop } R := RectF(0, 0, FBitmapMargins.Left, FBitmapMargins.Top); Canvas.DrawBitmap(B, RectF(0, 0, FBitmapMargins.Left, FBitmapMargins.Top), R, AbsoluteOpacity, True); { top } R := RectF(FBitmapMargins.Left, 0, Width - FBitmapMargins.Right, FBitmapMargins.Top); Canvas.DrawBitmap(B, RectF(FBitmapMargins.Left, 0, B.Width - FBitmapMargins.Right, FBitmapMargins.Top), R, AbsoluteOpacity, True); { righttop } R := RectF(Width - FBitmapMargins.Right, 0, Width, FBitmapMargins.Top); Canvas.DrawBitmap(B, RectF(B.Width - FBitmapMargins.Right, 0, B.Width, FBitmapMargins.Top), R, AbsoluteOpacity, True); { left } R := RectF(0, FBitmapMargins.Top, FBitmapMargins.Left, Height - FBitmapMargins.Bottom); Canvas.DrawBitmap(B, RectF(0, FBitmapMargins.Top, FBitmapMargins.Left, B.Height - FBitmapMargins.Bottom), R, AbsoluteOpacity, True); { center } R := RectF(FBitmapMargins.Left, FBitmapMargins.Top, Width - FBitmapMargins.Right, Height - FBitmapMargins.Bottom); Canvas.DrawBitmap(B, RectF(FBitmapMargins.Left, FBitmapMargins.Top, B.Width - FBitmapMargins.Right, B.Height - FBitmapMargins.Bottom), R, AbsoluteOpacity, True); { right } R := RectF(Width - FBitmapMargins.Right, FBitmapMargins.Top, Width, Height - FBitmapMargins.Bottom); Canvas.DrawBitmap(B, RectF(B.Width - FBitmapMargins.Right, FBitmapMargins.Top, B.Width, B.Height - FBitmapMargins.Bottom), R, AbsoluteOpacity, True); { leftbottom } R := RectF(0, Height - FBitmapMargins.Bottom, FBitmapMargins.Left, Height); Canvas.DrawBitmap(B, RectF(0, B.Height - FBitmapMargins.Bottom, FBitmapMargins.Left, B.Height), R, AbsoluteOpacity, True); { bottom } R := RectF(FBitmapMargins.Left, Height - FBitmapMargins.Bottom, Width - FBitmapMargins.Right, Height); Canvas.DrawBitmap(B, RectF(FBitmapMargins.Left, B.Height - FBitmapMargins.Bottom, B.Width - FBitmapMargins.Right, B.Height), R, AbsoluteOpacity, True); { rightbottom } R := RectF(Width - FBitmapMargins.Right, Height - FBitmapMargins.Bottom, Width, Height); Canvas.DrawBitmap(B, RectF(B.Width - FBitmapMargins.Right, B.Height - FBitmapMargins.Bottom, B.Width, B.Height), R, AbsoluteOpacity, True); end else begin case FWrapMode of TImageWrapMode.iwOriginal: begin State := Canvas.SaveState; try Canvas.IntersectClipRect(LocalRect); R := RectF(0, 0, B.Width, B.Height); Canvas.DrawBitmap(B, RectF(0, 0, B.Width, B.Height), R, AbsoluteOpacity, True); finally Canvas.RestoreState(State); end; end; TImageWrapMode.iwFit: begin R := RectF(0, 0, B.Width, B.Height); FitRect(R, LocalRect); Canvas.DrawBitmap(B, RectF(0, 0, B.Width, B.Height), R, AbsoluteOpacity, DisableInterpolation); end; TImageWrapMode.iwStretch: begin R := LocalRect; Canvas.DrawBitmap(B, RectF(0, 0, B.Width, B.Height), R, AbsoluteOpacity, DisableInterpolation) end; TImageWrapMode.iwTile: begin State := Canvas.SaveState; try Canvas.IntersectClipRect(LocalRect); for i := 0 to Round(Width / B.Width) do for j := 0 to Round(Height / B.Height) do begin R := RectF(0, 0, B.Width, B.Height); OffsetRect(R, i * B.Width, j * B.Height); Canvas.DrawBitmap(B, RectF(0, 0, B.Width, B.Height), R, AbsoluteOpacity, True); end; finally Canvas.RestoreState(State); end; end; end; end; end; procedure TImage.SetBitmap(const Value: TBitmap); begin FBitmap.Assign(Value); end; procedure TImage.SetWrapMode(const Value: TImageWrapMode); begin if FWrapMode <> Value then begin FWrapMode := Value; Repaint; end; end; { TPath } constructor TCustomPath.Create(AOwner: TComponent); begin inherited; FWrapMode := TPathWrapMode.pwStretch; FData := TPathData.Create; FData.OnChanged := DoChanged; FCurrent := TPathData.Create; end; destructor TCustomPath.Destroy; begin FreeAndNil(FCurrent); FreeAndNil(FData); inherited; end; procedure TCustomPath.UpdatePath; var B: TRectF; P: TPathData; begin { Update path } P := FData; if FData.ResourcePath <> nil then P := FData.ResourcePath; if not P.IsEmpty then begin case FWrapMode of TPathWrapMode.pwOriginal: begin FCurrent.Assign(P); end; TPathWrapMode.pwFit: begin B := P.GetBounds; FitRect(B, ShapeRect); FCurrent.Assign(P); FCurrent.FitToRect(B); end; TPathWrapMode.pwStretch: begin B := P.GetBounds; FCurrent.Assign(P); FCurrent.Translate(-B.Left, -B.Top); FCurrent.Scale(RectWidth(ShapeRect) / RectWidth(B), RectHeight(ShapeRect) / RectHeight(B)); end; TPathWrapMode.pwTile: begin B := P.GetBounds; FCurrent.Assign(P); FCurrent.Translate(-B.Left, -B.Top); end; end; if Stroke.Kind <> TBrushKind.bkNone then FCurrent.Translate(StrokeThickness / 2, StrokeThickness / 2); end else FCurrent.Clear; end; procedure TCustomPath.DoChanged(Sender: TObject); begin UpdatePath; Repaint; end; procedure TCustomPath.Loaded; begin inherited; UpdatePath; end; function TCustomPath.PointInObject(X, Y: Single): Boolean; begin if (csDesigning in ComponentState) and not FLocked and not FInPaintTo then begin Result := inherited PointInObject(X, Y); end else if (Canvas <> nil) and not (FCurrent.IsEmpty) and (FWrapMode <> TPathWrapMode.pwTile) then begin Result := Canvas.PtInPath(AbsoluteToLocal(PointF(X, Y)), FCurrent) end else Result := inherited PointInObject(X, Y); end; procedure TCustomPath.Resize; begin inherited; UpdatePath; end; procedure TCustomPath.Paint; var B, R: TRectF; i, j: Integer; State: TCanvasSaveState; P1: TPathData; begin if not FCurrent.IsEmpty then begin case FWrapMode of TPathWrapMode.pwOriginal: begin State := Canvas.SaveState; try Canvas.IntersectClipRect(LocalRect); Canvas.FillPath(FCurrent, AbsoluteOpacity); Canvas.DrawPath(FCurrent, AbsoluteOpacity); finally Canvas.RestoreState(State); end; end; TPathWrapMode.pwFit: begin Canvas.FillPath(FCurrent, AbsoluteOpacity); Canvas.DrawPath(FCurrent, AbsoluteOpacity); end; TPathWrapMode.pwStretch: begin Canvas.FillPath(FCurrent, AbsoluteOpacity); Canvas.DrawPath(FCurrent, AbsoluteOpacity); end; TPathWrapMode.pwTile: begin State := Canvas.SaveState; try Canvas.IntersectClipRect(LocalRect); B := FCurrent.GetBounds; R := B; P1 := TPathData.Create; for i := 0 to Round(Width / RectWidth(R)) do for j := 0 to Round(Height / RectHeight(R)) do begin P1.Assign(FCurrent); P1.Translate(ShapeRect.Left + i * (RectWidth(R) + ShapeRect.Left * 2), ShapeRect.Top + j * (RectHeight(R) + ShapeRect.Top * 2)); Canvas.FillPath(P1, AbsoluteOpacity); Canvas.DrawPath(P1, AbsoluteOpacity); end; P1.Free; finally Canvas.RestoreState(State); end; end; end; end; if (csDesigning in ComponentState) and not FLocked and not FInPaintTo then begin R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $A0909090; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; end; end; procedure TCustomPath.SetWrapMode(const Value: TPathWrapMode); begin if FWrapMode <> Value then begin FWrapMode := Value; UpdatePath; Repaint; end; end; procedure TCustomPath.SetData(const Value: TPathData); begin FData.Assign(Value); end; { TPaintBox } constructor TPaintBox.Create(AOwner: TComponent); begin inherited; end; destructor TPaintBox.Destroy; begin inherited; end; procedure TPaintBox.Paint; var R: TRectF; begin if (csDesigning in ComponentState) and not FLocked and not FInPaintTo then begin R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $A0909090; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; end; if Assigned(FOnPaint) then FOnPaint(Self, Canvas); end; { TSelection } constructor TSelection.Create(AOwner: TComponent); begin inherited; AutoCapture := True; ParentBounds := True; FMinSize := 15; FGripSize := 3; SetAcceptsControls(False); end; destructor TSelection.Destroy; begin inherited; end; function TSelection.GetAbsoluteRect: TRectF; begin Result := inherited GetAbsoluteRect; InflateRect(Result, FGripSize + 4, FGripSize + 4); end; procedure TSelection.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var R: TRectF; begin // this line may be necessary because TSelection is not a styled control; // must further investigate for a better fix if not Enabled then Exit; inherited; FDownPos := PointF(X, Y); if Button = TMouseButton.mbLeft then begin FRatio := Width / Height; R := LocalRect; R := RectF(R.Left - (GripSize), R.Top - (GripSize), R.Left + (GripSize), R.Top + (GripSize)); if PointInRect(FDownPos, R) then begin FLeftTop := True; Exit; end; R := LocalRect; R := RectF(R.Right - (GripSize), R.Top - (GripSize), R.Right + (GripSize), R.Top + (GripSize)); if PointInRect(FDownPos, R) then begin FRightTop := True; Exit; end; R := LocalRect; R := RectF(R.Right - (GripSize), R.Bottom - (GripSize), R.Right + (GripSize), R.Bottom + (GripSize)); if PointInRect(FDownPos, R) then begin FRightBottom := True; Exit; end; R := LocalRect; R := RectF(R.Left - (GripSize), R.Bottom - (GripSize), R.Left + (GripSize), R.Bottom + (GripSize)); if PointInRect(FDownPos, R) then begin FLeftBottom := True; Exit; end; FMove := True; end; end; procedure TSelection.MouseMove(Shift: TShiftState; X, Y: Single); var P, OldPos, Size: TPointF; S, SaveW: Single; R: TRectF; begin // this line may be necessary because TSelection is not a styled control; // must further investigate for a better fix if not Enabled then Exit; inherited; if Shift = [] then begin // handle painting for hotspot mouse hovering FMovePos := PointF(X, Y); P := LocalToAbsolute(FMovePos); if (Parent <> nil) and (Parent is TControl) then P := TControl(Parent).AbsoluteToLocal(P); R := LocalRect; R := RectF(R.Left - (GripSize), R.Top - (GripSize), R.Left + (GripSize), R.Top + (GripSize)); if PointInRect(FMovePos, R) xor FLeftTopHot then begin FLeftTopHot := not FLeftTopHot; Repaint; end; R := LocalRect; R := RectF(R.Right - (GripSize), R.Top - (GripSize), R.Right + (GripSize), R.Top + (GripSize)); if PointInRect(FMovePos, R) xor FRightTopHot then begin FRightTopHot := not FRightTopHot; Repaint; end; R := LocalRect; R := RectF(R.Right - (GripSize), R.Bottom - (GripSize), R.Right + (GripSize), R.Bottom + (GripSize)); if PointInRect(FMovePos, R) xor FRightBottomHot then begin FRightBottomHot := not FRightBottomHot; Repaint; end; R := LocalRect; R := RectF(R.Left - (GripSize), R.Bottom - (GripSize), R.Left + (GripSize), R.Bottom + (GripSize)); if PointInRect(FMovePos, R) xor FLeftBottomHot then begin FLeftBottomHot := not FLeftBottomHot; Repaint; end; end; if ssLeft in Shift then begin // handle the movement of the whole selection control by grabbing FMovePos := PointF(X, Y); if FMove then begin Position.X := Position.X + (FMovePos.X - FDownPos.X); Position.Y := Position.Y + (FMovePos.Y - FDownPos.Y); if ParentBounds then begin if Position.X < 0 then Position.X := 0; if Position.Y < 0 then Position.Y := 0; if (Parent <> nil) and (Parent is TControl) then begin if Position.X + Width > TControl(Parent).Width then Position.X := TControl(Parent).Width - Width; if Position.Y + Height > TControl(Parent).Height then Position.Y := TControl(Parent).Height - Height; end else if Canvas <> nil then begin if Position.X + Width > Canvas.Width then Position.X := Canvas.Width - Width; if Position.Y + Height > Canvas.Height then Position.Y := Canvas.Height - Height; end; end; if Assigned(FOnTrack) then FOnTrack(Self); Exit; end; OldPos := Position.Point; P := LocalToAbsolute(FMovePos); if (Parent <> nil) and (Parent is TControl) then P := TControl(Parent).AbsoluteToLocal(P); if ParentBounds then begin if P.Y < 0 then P.Y := 0; if P.X < 0 then P.X := 0; if (Parent <> nil) and (Parent is TControl) then begin if P.X > TControl(Parent).Width then P.X := TControl(Parent).Width; if P.Y > TControl(Parent).Height then P.Y := TControl(Parent).Height; end else if Canvas <> nil then begin if P.X > Canvas.Width then P.X := Canvas.Width; if P.Y > Canvas.Height then P.Y := Canvas.Height; end; end; if FLeftTop then begin Repaint; Size := PointF((Position.X - (P.X + FDownPos.X)), (Position.Y - (P.Y + FDownPos.Y))); if (Parent <> nil) and (Parent is TControl) then Size := PointF(TControl(Parent).LocalToAbsoluteVector(Vector(Size))); Size := PointF(AbsoluteToLocalVector(Vector(Size))); if FProportional then begin Width := Width + Size.X; SaveW := Width; if Width < FMinSize then Width := FMinSize; if Width / FRatio < FMinSize then Width := Round(FMinSize * FRatio); Position.X := P.X + FDownPos.X - (Width - SaveW); Position.Y := Position.Y + (Height - Round(Width / FRatio)); Height := Round(Width / FRatio); end else begin Width := Width + Size.X; Height := Height + Size.Y; Position.X := P.X + FDownPos.X; Position.Y := P.Y + FDownPos.Y; if Width < FMinSize then Width := FMinSize; if Height < FMinSize then Height := FMinSize; end; if Assigned(FOnTrack) then FOnTrack(Self); Repaint; end; if FRightTop then begin Repaint; Size := PointF((P.X { + FDownPos.X } ) - Position.X, (Position.Y - (P.Y + FDownPos.Y))); if (Parent <> nil) and (Parent is TControl) then Size := PointF(TControl(Parent).LocalToAbsoluteVector(Vector(Size))); Size := PointF(AbsoluteToLocalVector(Vector(Size))); Width := Size.X; if FProportional then begin if Width < FMinSize then Width := FMinSize; if Width / FRatio < FMinSize then Width := Round(FMinSize * FRatio); Position.Y := Position.Y + (Height - Round(Width / FRatio)); Height := Round(Width / FRatio); end else begin Height := Height + Size.Y; Position.Y := P.Y + FDownPos.Y; if Width < FMinSize then Width := FMinSize; if Height < FMinSize then Height := FMinSize; end; if Assigned(FOnTrack) then FOnTrack(Self); Repaint; end; if FRightBottom then begin Repaint; Size := PointF((P.X { + FDownPos.X } ) - Position.X, (P.Y { + FDownPos.Y) } ) - Position.Y); if (Parent <> nil) and (Parent is TControl) then Size := PointF(TControl(Parent).LocalToAbsoluteVector(Vector(Size))); Size := PointF(AbsoluteToLocalVector(Vector(Size))); Width := Size.X; if FProportional then begin if Width < FMinSize then Width := FMinSize; if Width / FRatio < FMinSize then Width := Round(FMinSize * FRatio); Height := Round(Width / FRatio); end else begin Height := Size.Y; if Width < FMinSize then Width := FMinSize; if Height < FMinSize then Height := FMinSize; end; if Assigned(FOnTrack) then FOnTrack(Self); Repaint; end; if FLeftBottom then begin Repaint; Size := PointF((Position.X - (P.X + FDownPos.X)), (P.Y { + FDownPos.Y) } ) - Position.Y); if (Parent <> nil) and (Parent is TControl) then Size := PointF(TControl(Parent).LocalToAbsoluteVector(Vector(Size))); Size := PointF(AbsoluteToLocalVector(Vector(Size))); if FProportional then begin Width := Width + Size.X; SaveW := Width; if Width < FMinSize then Width := FMinSize; if Width / FRatio < FMinSize then Width := Round(FMinSize * FRatio); Position.X := P.X + FDownPos.X - (Width - SaveW); Height := Round(Width / FRatio); end else begin Width := Width + Size.X; Position.X := P.X + FDownPos.X; Height := Size.Y; if Width < FMinSize then Width := FMinSize; if Height < FMinSize then Height := FMinSize; end; if Assigned(FOnTrack) then FOnTrack(Self); Repaint; end; end; end; function TSelection.PointInObject(X, Y: Single): Boolean; var R: TRectF; P: TPointF; begin Result := inherited PointInObject(X, Y); if not Result then begin P := AbsoluteToLocal(PointF(X, Y)); R := LocalRect; R := RectF(R.Left - (GripSize), R.Top - (GripSize), R.Left + (GripSize), R.Top + (GripSize)); if PointInRect(P, R) then begin Result := True; Exit; end; R := LocalRect; R := RectF(R.Right - (GripSize), R.Top - (GripSize), R.Right + (GripSize), R.Top + (GripSize)); if PointInRect(P, R) then begin Result := True; Exit; end; R := LocalRect; R := RectF(R.Right - (GripSize), R.Bottom - (GripSize), R.Right + (GripSize), R.Bottom + (GripSize)); if PointInRect(P, R) then begin Result := True; Exit; end; R := LocalRect; R := RectF(R.Left - (GripSize), R.Bottom - (GripSize), R.Left + (GripSize), R.Bottom + (GripSize)); if PointInRect(P, R) then begin Result := True; Exit; end; end; end; procedure TSelection.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin // this line may be necessary because TSelection is not a styled control; // must further investigate for a better fix if not Enabled then Exit; inherited; if FMove or FLeftTop or FLeftBottom or FRightTop or FRightBottom then begin if Assigned(FOnChange) then FOnChange(Self); FMove := False; FLeftTop := False; FLeftBottom := False; FRightTop := False; FRightBottom := False; end; end; procedure TSelection.Paint; var DefColor: TAlphaColor; R: TRectF; // sets the canvas color depending if the control is enabled and if // we need to draw a zone being hot or not procedure SelectZoneColor(HotZone: Boolean); begin if Enabled then if HotZone then Canvas.Fill.Color := claRed else Canvas.Fill.Color := $FFFFFFFF else Canvas.Fill.Color := claGrey; end; begin if FHideSelection then Exit; R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Fill.Color := $FFFFFFFF; Canvas.StrokeThickness := 1; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $FF1072C5; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; { angles } R := LocalRect; InflateRect(R, -0.5, -0.5); SelectZoneColor(FLeftTopHot); Canvas.FillEllipse(RectF(R.Left - (GripSize), R.Top - (GripSize), R.Left + (GripSize), R.Top + (GripSize)), AbsoluteOpacity); Canvas.DrawEllipse(RectF(R.Left - (GripSize), R.Top - (GripSize), R.Left + (GripSize), R.Top + (GripSize)), AbsoluteOpacity); R := LocalRect; SelectZoneColor(FRightTopHot); Canvas.FillEllipse(RectF(R.Right - (GripSize), R.Top - (GripSize), R.Right + (GripSize), R.Top + (GripSize)), AbsoluteOpacity); Canvas.DrawEllipse(RectF(R.Right - (GripSize), R.Top - (GripSize), R.Right + (GripSize), R.Top + (GripSize)), AbsoluteOpacity); R := LocalRect; SelectZoneColor(FLeftBottomHot); Canvas.FillEllipse(RectF(R.Left - (GripSize), R.Bottom - (GripSize), R.Left + (GripSize), R.Bottom + (GripSize)), AbsoluteOpacity); Canvas.DrawEllipse(RectF(R.Left - (GripSize), R.Bottom - (GripSize), R.Left + (GripSize), R.Bottom + (GripSize)), AbsoluteOpacity); R := LocalRect; SelectZoneColor(FRightBottomHot); Canvas.FillEllipse(RectF(R.Right - (GripSize), R.Bottom - (GripSize), R.Right + (GripSize), R.Bottom + (GripSize)), AbsoluteOpacity); Canvas.DrawEllipse(RectF(R.Right - (GripSize), R.Bottom - (GripSize), R.Right + (GripSize), R.Bottom + (GripSize)), AbsoluteOpacity); end; procedure TSelection.DoMouseLeave; begin inherited; FLeftTopHot := False; FLeftBottomHot := False; FRightTopHot := False; FRightBottomHot := False; Repaint; end; procedure TSelection.SetHideSelection(const Value: Boolean); begin if FHideSelection <> Value then begin FHideSelection := Value; Repaint; end; end; procedure TSelection.SetMinSize(const Value: Integer); begin if FMinSize <> Value then begin FMinSize := Value; if FMinSize < 1 then FMinSize := 1; end; end; procedure TSelection.SetGripSize(const Value: Single); begin if FGripSize <> Value then begin FGripSize := Value; if FGripSize > 20 then FGripSize := 20; if FGripSize < 1 then FGripSize := 1; Repaint; end; end; { TSelectionPoint } constructor TSelectionPoint.Create(AOwner: TComponent); begin inherited; AutoCapture := True; ParentBounds := True; FGripSize := 3; Width := FGripSize * 2; Height := FGripSize * 2; SetAcceptsControls(False); end; destructor TSelectionPoint.Destroy; begin inherited; end; function TSelectionPoint.PointInObject(X, Y: Single): Boolean; var P: TPointF; begin Result := False; P := AbsoluteToLocal(PointF(X, Y)); if (Abs(P.X) < GripSize) and (Abs(P.Y) < GripSize) then begin Result := True; end; end; procedure TSelectionPoint.Paint; begin inherited; Canvas.StrokeThickness := 1; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $FF1072C5; Canvas.Fill.Kind := TBrushKind.bkSolid; if IsMouseOver then Canvas.Fill.Color := $FFFF0000 else Canvas.Fill.Color := $FFFFFFFF; Canvas.FillEllipse(RectF(-(GripSize), -(GripSize), (GripSize), (GripSize)), AbsoluteOpacity); Canvas.DrawEllipse(RectF(-(GripSize), -(GripSize), (GripSize), (GripSize)), AbsoluteOpacity); end; procedure TSelectionPoint.SetHeight(const Value: Single); begin inherited SetHeight(FGripSize * 2); end; procedure TSelectionPoint.SetWidth(const Value: Single); begin inherited SetWidth(FGripSize * 2); end; procedure TSelectionPoint.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if Button = TMouseButton.mbLeft then FPressed := True; end; procedure TSelectionPoint.MouseMove(Shift: TShiftState; X, Y: Single); var P: TPointF; begin inherited; if FPressed and (Parent <> nil) and (Parent is TControl) then begin P := LocalToAbsolute(PointF(X, Y)); if (Parent <> nil) and (Parent is TControl) then P := TControl(Parent).AbsoluteToLocal(P); if ParentBounds then begin if P.X < 0 then P.X := 0; if P.Y < 0 then P.Y := 0; if (Parent <> nil) and (Parent is TControl) then begin if P.X > TControl(Parent).Width then P.X := TControl(Parent).Width; if P.Y > TControl(Parent).Height then P.Y := TControl(Parent).Height; end else if (Canvas <> nil) then begin if P.X > Canvas.Width then P.X := Canvas.Width; if P.Y > Canvas.Height then P.Y := Canvas.Height; end; end; Position.X := P.X; Position.Y := P.Y; if Assigned(FOnTrack) then FOnTrack(Self); end; end; procedure TSelectionPoint.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if FPressed then begin if Assigned(FOnChange) then FOnChange(Self); end; FPressed := False; end; procedure TSelectionPoint.DoMouseEnter; begin inherited; Repaint; end; procedure TSelectionPoint.DoMouseLeave; begin inherited; Repaint; end; function TSelectionPoint.GetUpdateRect: TRectF; begin Result := inherited GetUpdateRect; InflateRect(Result, GripSize + 1, GripSize + 1); end; procedure TSelectionPoint.SetGripSize(const Value: Single); begin if FGripSize <> Value then begin FGripSize := Value; if FGripSize > 20 then FGripSize := 20; if FGripSize < 1 then FGripSize := 1; Repaint; end; end; initialization RegisterFmxClasses([TLine, TRectangle, TRoundRect, TEllipse, TCircle, TArc, TPie, TText, TPath, TImage, TPaintBox,TCalloutRectangle, TSelection, TSelectionPoint]); end.
unit uStatusEcho; interface procedure StatusEchoInit; procedure StatusEchoFree; implementation uses Windows, SysUtils, DateUtils, Classes, IdUDPServer, IDSocketHandle; type TUDPServerOwner = class constructor Create; destructor Destroy; override; private FInitUDPOK: boolean; FUDPServer: TIdUDPServer; procedure BuildEchoInfo(ABuf: PByteArray; ABufLen: integer); procedure OnUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle); end; var usoMain: TUDPServerOwner; procedure StatusEchoInit; begin usoMain := TUDPServerOwner.Create; end; procedure StatusEchoFree; begin FreeAndNil(usoMain); end; { TUDPServerOwner } procedure TUDPServerOwner.BuildEchoInfo(ABuf: PByteArray; ABufLen: integer); begin ZeroMemory(ABuf, ABufLen); end; constructor TUDPServerOwner.Create; begin FInitUDPOK := false; try FUDPServer := TIdUDPServer.Create(nil); FUDPServer.DefaultPort := 12345; FUDPServer.OnUDPRead := OnUDPRead; FUDPServer.Active := true; FInitUDPOK := true; except end; end; destructor TUDPServerOwner.Destroy; begin try if Assigned(FUDPServer) then begin FUDPServer.Active := false; FUDPServer.Free; end; except end; inherited; end; procedure TUDPServerOwner.OnUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle); var buf: array[0..127] of byte; begin BuildEchoInfo(@buf[0], SizeOf(buf)); ABinding.SendTo(ABinding.PeerIp, ABinding.PeerPort, buf[0], SizeOf(buf)); end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 本单元主要实现系统信息的获取 OS信息:系统目录、系统版本 打印机 文件创建、修改和最后访问时间等 网络IP的安装与获取 邮件发送与邮件地址合法性验证 //主要实现: //-----------------------------------------------------------------------------} unit untEasyOS; interface uses Windows, Classes, SysUtils, ShellAPI, WinInet, WinSock, Nb30, StdCtrls, Controls, Forms; type TTimeOfWhat = ( ftCreationTime, ftLastAccessTime, ftLastWriteTime ); TFileTimeComparision = ( ftError, ftFileOneIsOlder, ftFileTimesAreEqual, ftFileTwoIsOlder ); TDriveType = (dtUnknown, dtNoDrive, dtFloppy, dtFixed, dtNetwork, dtCDROM, dtRAM); type TVolumeInfo = record Name : String; SerialNumber : DWORD; MaxComponentLength : DWORD; FileSystemFlags : DWORD; FileSystemName : String; end; // TVolumeInfo type PFixedFileInfo = ^TFixedFileInfo; TFixedFileInfo = record dwSignature : DWORD; dwStrucVersion : DWORD; wFileVersionMS : WORD; // Minor Version wFileVersionLS : WORD; // Major Version wProductVersionMS : WORD; // Build Number wProductVersionLS : WORD; // Release Version dwFileFlagsMask : DWORD; dwFileFlags : DWORD; dwFileOS : DWORD; dwFileType : DWORD; dwFileSubtype : DWORD; dwFileDateMS : DWORD; dwFileDateLS : DWORD; end; // TFixedFileInfo TWinVer = Packed Record dwVersion : DWORD; sVerSion : String; end; const TWindowsVersion : array [0..8] of String = ('Windows 3.x', 'Windows 95', 'Windows 98/Me', 'Windows Nt 4.0', 'Windows 2000', 'Windows XP', 'Windows Server 2003', 'Windows Vista', 'Windows Server 2008'); Win3x = $03000000; Win95 = $04000000; Win98ME = $04010000; WinNT40 = $04020000; Win2000 = $05000000; WinXP = $05010000; Win2003 = $05020000; WinVista = $06000000; Win2008 = $06000100; //获取系统版本 function GetWindowsVersion: string; stdcall; function GetWindowsVersion_dw: DWORD; stdcall; //获取计算机用户名 function GetComputerUserName: PChar; stdcall; //获取系统用户名 function GetSystemUserName: PChar; stdcall; //检测TCP/IP协议是否安装 function IsIPInstalled : boolean; stdcall; //得到本机的局域网Ip地址 Function GetLocalIp(var LocalIp:string): Boolean; stdcall; //检测网络状态 Function CheckIPNetState(IpAddr : string): Boolean; stdcall; //检测机器是否上网 Function NetInternetConnected: Boolean; stdcall; {ERROR} //获取本地MAC地址 function GetLocalMAC:string; stdcall; //获取本地MAC地址 调用DLL function GetLocalMAC_DLL: string; stdcall; //* hosttoip 函数作用是将域名解析成ip function HostToIP(Name: string; var Ip: string): Boolean; stdcall; {*out和in汇编指令在Window2000以上Ring3(普通级别)不能再使用,如果要使用,必须 进入Ring0指令级别(操作系统级),驱动程序工作在Ring0级别下*} function GetPrinterStatus : byte; stdcall;//从并行端口读取打印机状态 function CheckPrinter : boolean; stdcall;//获取打印机是否出错 function GetWindowsDirectory : String; stdcall; //系统windows路径 function GetSystemDirectory : String; stdcall; //系统system路径 function GetSystemTime : String; stdcall; //获取系统时间 function GetLocalTime : String; stdcall; //本地时间,和系统时间一样 //文件 function GetCurrentDirectory : String; stdcall; //当前文件路径 function GetTempPath : String; stdcall; //获取TEMP文件路径,为短路径格式 function GetLogicalDrives : String; stdcall; //获取系统的所有盘符,组成一组字符串 //获取文件的创建、修改或最后一次的读取时间 function GetFileTime( const FileName : String; ComparisonType : TTimeOfWhat ) : TFileTime; stdcall; function GlobalMemoryStatus( const Index : Integer ) : DWORD; stdcall; //系统信息 function GetSystemInfoWORD( const Index : Integer ) : WORD; stdcall; function GetSystemInfoDWORD( const Index : Integer ) : DWORD; stdcall; function GetSystemVersion : String; stdcall; function GetSystemInfoPtr( const Index : Integer ) : Pointer; stdcall; //获取指定文件的信息 function GetFileInformation(const FileName, Value : String ): String; stdcall; //获取文件大小 function FileSize(const FileName : String ) : LongInt; stdcall; //判断两个文件的创建时间的早晚 function CompareFileTime(const FileNameOne, FileNameTwo : String; ComparisonType : TTimeOfWhat ): TFileTimeComparision; stdcall; //获取文件的创、修改、最后操作时间 function GetFileTime_0(const FileName : String; ComparisonType : TTimeOfWhat ): TDateTime; stdcall; //获取程序图标 function ExtractIcon(const FileName : String ): HIcon; stdcall; function ExtractAssociatedIcon( const FileName : String ): HIcon; stdcall; //磁盘 function GetFreeDiskSpace(const Drive : Char ) : LongInt; stdcall; function GetAllDiskFreeSpace : string; stdcall; function GetVolumeInformation(const Drive : Char ) : TVolumeInfo; stdcall; function DriveType(const Drive : Char ) : TDriveType; stdcall; function DisconnectNetworkDrive( const Drive : Char ): Boolean; stdcall; function AddNetworkDrive( const Resource : String; const Drive : Char ): Boolean; stdcall; function GetUniversalName( const Drive : Char ): String; stdcall; procedure FormatDrive( const Drive : Char ); stdcall; //短路径 function GetShortPathName(const Path : String ): String; stdcall; function GetFullPathName(const Path : String ): String; stdcall; //根据可执行文件名,查找可执行文件路径 function FindExecutable(const FileName : String ): String; stdcall; procedure ShellAbout( const TitleBar, OtherText : String ); stdcall; procedure ShutDown; stdcall; function FileInfo(const FileName : String ) : TFixedFileInfo; stdcall; //EMAIL有效性判断 procedure SendEMail_Hide; stdcall; function CheckMailAddress(Value : string): boolean; stdcall;//判断EMAIL地址是否合法 function SHFormatDrive(hWnd : HWND;Drive, fmtID, Options : WORD) : longint; stdcall; external 'shell32.dll'; implementation //获得WIN 系统版本号 function GetWindowsVersion_A: TWinVer; begin case Win32Platform of // SysUtils VER_PLATFORM_WIN32s: // Windows 3.X平台 begin Result.dwVersion := Win3x; Result.sVerSion := TWindowsVersion[0]; end; VER_PLATFORM_WIN32_WINDOWS: // Windows 9x/ME 平台 if ((Win32MajorVersion > 4 ) or ((Win32MajorVersion = 4 ) and (Win32MajorVersion > 0 ))) then begin Result.dwVersion := win98ME; Result.sVerSion := TWindowsVersion[2]; end else begin Result.dwVersion := Win95; Result.sVerSion := TWindowsVersion[1]; end; VER_PLATFORM_WIN32_NT: // Windows NT 平台 case Win32MajorVersion of 4: begin Result.dwVersion := WinNT40; Result.sVerSion := TWindowsVersion[3]; end; 5: begin case Win32MinorVersion of // 2K 0: begin Result.dwVersion := Win2000; Result.sVerSion := TWindowsVersion[4]; end; 1: begin // XP Result.dwVersion := WinXP; Result.sVerSion := TWindowsVersion[5]; end; 2: // 2003 begin Result.dwVersion := Win2003; Result.sVerSion := TWindowsVersion[6]; end; end; end; 6: begin case Win32MinorVersion of 0: begin Result.dwVersion := WinVista; Result.sVerSion := TWindowsVersion[7]; end; 1: begin Result.dwVersion := Win2008; Result.sVerSion := TWindowsVersion[8]; end; end; end; end; end; end; //返回操作系统字符串 function GetWindowsVersion: string; var wIND: TWinVer; begin wIND := GetWindowsVersion_A; Result := wIND.sVerSion; end; //返回操作系统版本标识 function GetWindowsVersion_dw: DWORD; var wIND: TWinVer; begin wIND := GetWindowsVersion_A; Result := wIND.dwVersion; end; //获取计算机用户名 function GetComputerUserName: PChar; var pcComputer : PChar; dwCSize : DWORD; begin Result := ''; dwCSize := MAX_COMPUTERNAME_LENGTH + 1; GetMem( pcComputer, dwCSize ); try if Windows.GetComputerName( pcComputer, dwCSize ) then Result := pcComputer; finally FreeMem( pcComputer ); end; end; //获取系统用户名 function GetSystemUserName: PChar; var pcUser : PChar; dwUSize : DWORD; begin Result := ''; dwUSize := 21; // u最大长度为20个字符 GetMem( pcUser, dwUSize ); // 分配内存 try if Windows.GetUserName( pcUser, dwUSize ) then Result := pcUser finally FreeMem( pcUser ); // 释放内存 end; end; //------------------------------------------------------------------------------ //功 能: 判断ip协议有没有安装 //参 数: 无 //返回值: 成功: true 失败: false; //备 注: 该函数还有问题 //版 本: //1.0 2002/10/02 21:05:00 //------------------------------------------------------------------------------ function IsIPInstalled : boolean; var wsdata : TWSAData; protoent: PProtoEnt; begin result := true; try if wsastartup(2,wsdata) = 0 then begin protoent := getprotobyname('ip'); if protoent = nil then result := false end; finally wsacleanup; end; end; {================================================================= 功 能: 返回本机的局域网Ip地址 参 数: 无 返回值: 成功: True, 并填充LocalIp 失败: ?False 备 注: ================================================================} function GetLocalIP(var LocalIp: string): Boolean; var HostEnt : PHostEnt; Ip : string; addr : pchar; Buffer : array [0..63] of char; GInitData: TWSADATA; begin Result := False; try WSAStartup(2, GInitData); GetHostName(Buffer, SizeOf(Buffer)); HostEnt := GetHostByName(buffer); if HostEnt = nil then Exit; addr := HostEnt^.h_addr_list^; ip := Format('%d.%d.%d.%d', [byte(addr [0]), byte (addr [1]), byte (addr [2]), byte (addr [3])]); LocalIp := Ip; Result := True; finally WSACleanup; end; end; {================================================================= 功 能: 检测网络状态 参 数: IpAddr: 被测试网络上主机的IP地址或名称,建议使用Ip 返回值: 成功: True 失败: False; 备 注: uses WinSock =================================================================} function CheckIPNetState(IpAddr: string): Boolean; type PIPOptionInformation = ^TIPOptionInformation; TIPOptionInformation = packed record TTL: Byte; // Time To Live (used for traceroute) TOS: Byte; // Type Of Service (usually 0) Flags: Byte; // IP header flags (usually 0) OptionsSize: Byte; // Size of options data (usually 0, max 40) OptionsData: PChar; // Options data buffer end; PIcmpEchoReply = ^TIcmpEchoReply; TIcmpEchoReply = packed record Address: DWord; // replying address Status: DWord; // IP status value (see below) RTT: DWord; // Round Trip Time in milliseconds DataSize: Word; // reply data size Reserved: Word; Data: Pointer; // pointer to reply data buffer Options: TIPOptionInformation; // reply options end; TIcmpCreateFile = function: THandle; stdcall; TIcmpCloseHandle = function(IcmpHandle: THandle): Boolean; stdcall; TIcmpSendEcho = function( IcmpHandle: THandle; DestinationAddress: DWord; RequestData: Pointer; RequestSize: Word; RequestOptions: PIPOptionInformation; ReplyBuffer: Pointer; ReplySize: DWord; Timeout: DWord ): DWord; stdcall; const Size = 32; TimeOut = 1000; var wsadata: TWSAData; Address: DWord; // Address of host to contact HostName, HostIP: String; // Name and dotted IP of host to contact Phe: PHostEnt; // HostEntry buffer for name lookup BufferSize, nPkts: Integer; pReqData, pData: Pointer; pIPE: PIcmpEchoReply; // ICMP Echo reply buffer IPOpt: TIPOptionInformation; // IP Options for packet to send const IcmpDLL = 'icmp.dll'; var hICMPlib: HModule; IcmpCreateFile : TIcmpCreateFile; IcmpCloseHandle: TIcmpCloseHandle; IcmpSendEcho: TIcmpSendEcho; hICMP: THandle; // Handle for the ICMP Calls begin // initialise winsock Result:=True; if WSAStartup(2,wsadata) <> 0 then begin Result:=False; halt; end; // register the icmp.dll stuff hICMPlib := loadlibrary(icmpDLL); if hICMPlib > 0 then begin @ICMPCreateFile := GetProcAddress(hICMPlib, 'IcmpCreateFile'); @IcmpCloseHandle:= GetProcAddress(hICMPlib, 'IcmpCloseHandle'); @IcmpSendEcho:= GetProcAddress(hICMPlib, 'IcmpSendEcho'); if (@ICMPCreateFile = Nil) or (@IcmpCloseHandle = Nil) or (@IcmpSendEcho = Nil) then begin Result:=False; halt; end; hICMP := IcmpCreateFile; if hICMP = INVALID_HANDLE_VALUE then begin Result:=False; halt; end; end else begin Result:=False; halt; end; // ------------------------------------------------------------ Address := inet_addr(PChar(IpAddr)); if (Address = INADDR_NONE) then begin Phe := GetHostByName(PChar(IpAddr)); if Phe = Nil then Result:=False else begin Address := longint(plongint(Phe^.h_addr_list^)^); HostName := Phe^.h_name; HostIP := StrPas(inet_ntoa(TInAddr(Address))); end; end else begin Phe := GetHostByAddr(@Address, 4, PF_INET); if Phe = Nil then Result:=False; end; if Address = INADDR_NONE then begin Result:=False; end; // Get some data buffer space and put something in the packet to send BufferSize := SizeOf(TICMPEchoReply) + Size; GetMem(pReqData, Size); GetMem(pData, Size); GetMem(pIPE, BufferSize); FillChar(pReqData^, Size, $AA); pIPE^.Data := pData; // Finally Send the packet FillChar(IPOpt, SizeOf(IPOpt), 0); IPOpt.TTL := 64; NPkts := IcmpSendEcho(hICMP, Address, pReqData, Size, @IPOpt, pIPE, BufferSize, TimeOut); if NPkts = 0 then Result:=False; // Free those buffers FreeMem(pIPE); FreeMem(pData); FreeMem(pReqData); // -------------------------------------------------------------- IcmpCloseHandle(hICMP); FreeLibrary(hICMPlib); // free winsock if WSACleanup <> 0 then Result:=False; end; {------------------------------------------------------------------------------- 过程名: tHhfNetWork.GetLocalMAC 作者: Administrator 日期: 2008.11.03 参数: 无 返回值: string LOCAL MAC USES : Nb30 ERROR : 如果机器上存在VM类的虚拟机,则取出的MAC地址为第一个虚拟机的 -------------------------------------------------------------------------------} function GetLocalMAC:string; var ncb : TNCB; status : TAdapterStatus; lanenum : TLanaEnum; procedure ResetAdapter (num : char); begin fillchar(ncb,sizeof(ncb),0); ncb.ncb_command:=char(NCBRESET); ncb.ncb_lana_num:=num; Netbios(@ncb); end; var i:integer; lanNum : char; address : record part1 : Longint; part2 : Word; end absolute status; begin Result:=''; fillchar(ncb,sizeof(ncb),0); ncb.ncb_command:=char(NCBENUM); ncb.ncb_buffer:=@lanenum; ncb.ncb_length:=sizeof(lanenum); Netbios(@ncb); if lanenum.length=#0 then exit; lanNum:=lanenum.lana[0]; ResetAdapter(lanNum); fillchar(ncb,sizeof(ncb),0); ncb.ncb_command:=char(NCBASTAT); ncb.ncb_lana_num:=lanNum; ncb.ncb_callname[0]:='*'; ncb.ncb_buffer:=@status; ncb.ncb_length:=sizeof(status); Netbios(@ncb); ResetAdapter(lanNum); for i:=0 to 5 do begin result:=result+inttoHex(integer(Status.adapter_address[i]),2); if (i<5) then result:=result+'-'; end; end; function GetLocalMAC_DLL:string; var Lib: Cardinal; Func: function(GUID: PGUID): Longint; stdcall; GUID1, GUID2: TGUID; begin Result := ''; Lib := LoadLibrary('rpcrt4.dll'); if Lib <> 0 then begin if Win32Platform <>VER_PLATFORM_WIN32_NT then @Func := GetProcAddress(Lib, 'UuidCreate') else @Func := GetProcAddress(Lib, 'UuidCreateSequential'); if Assigned(Func) then begin if (Func(@GUID1) = 0) and (Func(@GUID2) = 0) and (GUID1.D4[2] = GUID2.D4[2]) and (GUID1.D4[3] = GUID2.D4[3]) and (GUID1.D4[4] = GUID2.D4[4]) and (GUID1.D4[5] = GUID2.D4[5]) and (GUID1.D4[6] = GUID2.D4[6]) and (GUID1.D4[7] = GUID2.D4[7]) then begin Result := IntToHex(GUID1.D4[2], 2) + '-' + IntToHex(GUID1.D4[3], 2) + '-' + IntToHex(GUID1.D4[4], 2) + '-' + IntToHex(GUID1.D4[5], 2) + '-' + IntToHex(GUID1.D4[6], 2) + '-' + IntToHex(GUID1.D4[7], 2); end; end; FreeLibrary(Lib); end; end; {================================================================= 功 能: 检测计算机是否上网 参 数: 无 返 回 值: 成功: True 失败: False; uses : WinInet =================================================================} function NetInternetConnected: Boolean; const // local system uses a modem to connect to the Internet. INTERNET_CONNECTION_MODEM = 1; // local system uses a local area network to connect to the Internet. INTERNET_CONNECTION_LAN = 2; // local system uses a proxy server to connect to the Internet. INTERNET_CONNECTION_PROXY = 4; // local system's modem is busy with a non-Internet connection. INTERNET_CONNECTION_MODEM_BUSY = 8; var dwConnectionTypes : DWORD; begin dwConnectionTypes := INTERNET_CONNECTION_LAN + INTERNET_CONNECTION_MODEM + INTERNET_CONNECTION_PROXY; //Result := InternetGetConnectedState(@dwConnectionTypes, 1); Result := InternetGetConnectedState(@dwConnectionTypes, 0); end; //hosttoip 函数作用是将域名解析成ip function HostToIP(Name: string; var Ip: string): Boolean; var wsdata : TWSAData; hostName : array [0..255] of char; hostEnt : PHostEnt; addr : PChar; begin WSAStartup ($0101, wsdata); try gethostname(hostName, sizeof (hostName)); StrPCopy(hostName, Name); hostEnt := gethostbyname(hostName); if Assigned (hostEnt) then if Assigned (hostEnt^.h_addr_list) then begin addr := hostEnt^.h_addr_list^; if Assigned (addr) then begin IP := Format ('%d.%d.%d.%d', [byte (addr [0]), byte (addr [1]), byte (addr [2]), byte (addr [3])]); Result := True; end else Result := False; end else Result := False else begin Result := False; end; finally WSACleanup; end; end; {* EXP procedure TForm1.Button1Click(Sender: TObject); var //定义一个字符串变量 Temp:string; begin HostToIP(edit1.text,Temp); //将输入的域名解析成IP edit2.Text:=Temp; //显示在EDIT2当中 end; } {*从并行端口读取打印机状态*} function GetPrinterStatus : Byte; asm MOV DX,$379; IN AL,DX; end; {*获取打印机是否出错,至于收银机的检测,最好问厂家要接口函数或Demo来实现*} function CheckPrinter : boolean; var temp : byte; begin temp := GetPrinterStatus; Result := not ( ((temp and $80)=0) //打印机忙 or ((temp and $20)<>0) //打印机缺纸 or ((temp and $10)=0) //打印机未联机 or ((temp and $08)=0) ); //打印机出错; end; function GetWindowsDirectory : String; var pcWindowsDirectory : PChar; dwWDSize : DWORD; begin dwWDSize := MAX_PATH + 1; GetMem( pcWindowsDirectory, dwWDSize ); try if Windows.GetWindowsDirectory( pcWindowsDirectory, dwWDSize ) <> 0 then Result := pcWindowsDirectory; finally FreeMem( pcWindowsDirectory ); end; end; function GetSystemDirectory : String; var pcSystemDirectory : PChar; dwSDSize : DWORD; begin dwSDSize := MAX_PATH + 1; GetMem( pcSystemDirectory, dwSDSize ); try if Windows.GetSystemDirectory( pcSystemDirectory, dwSDSize ) <> 0 then Result := pcSystemDirectory; finally FreeMem( pcSystemDirectory ); end; end; function GetSystemTime : String; var stSystemTime : TSystemTime; begin Windows.GetSystemTime( stSystemTime ); Result := DateTimeToStr( SystemTimeToDateTime( stSystemTime ) ); end; function GetLocalTime : String; var stSystemTime : TSystemTime; begin Windows.GetLocalTime( stSystemTime ); Result := DateTimeToStr( SystemTimeToDateTime( stSystemTime ) ); end; function GetCurrentDirectory: String; var nBufferLength : DWORD; lpBuffer : PChar; begin nBufferLength := MAX_PATH + 1; GetMem( lpBuffer, nBufferLength ); try if Windows.GetCurrentDirectory( nBufferLength, lpBuffer ) > 0 then Result := lpBuffer; finally FreeMem( lpBuffer ); end; end; function GetTempPath: String; var nBufferLength : DWORD; lpBuffer : PChar; begin nBufferLength := MAX_PATH + 1; GetMem( lpBuffer, nBufferLength ); try if Windows.GetTempPath( nBufferLength, lpBuffer ) <> 0 then Result := StrPas( lpBuffer ) else Result := ''; finally FreeMem( lpBuffer ); end; end; function GetLogicalDrives : String; var drives : set of 0..25; drive : integer; begin Result := ''; DWORD( drives ) := Windows.GetLogicalDrives; for drive := 0 to 25 do if drive in drives then Result := Result + Chr( drive + Ord( 'A' )); end; function GetFileTime( const FileName : String; ComparisonType : TTimeOfWhat ) : TFileTime; var FileTime, LocalFileTime : TFileTime; hFile : THandle; begin Result.dwLowDateTime := 0; Result.dwHighDateTime := 0; hFile := FileOpen( FileName, fmShareDenyNone ); try if hFile <> 0 then begin case ComparisonType of ftCreationTime : Windows.GetFileTime( hFile, @FileTime, nil, nil ); ftLastAccessTime : Windows.GetFileTime( hFile, nil, @FileTime, nil ); ftLastWriteTime : Windows.GetFileTime( hFile, nil, nil, @FileTime ); end; FileTimeToLocalFileTime( FileTime, LocalFileTime ); Result := LocalFileTime; end; finally FileClose( hFile ); end; end; function GetSystemVersion: String; var VersionInfo : TOSVersionInfo; OSName : String; begin VersionInfo.dwOSVersionInfoSize := SizeOf( TOSVersionInfo ); if Windows.GetVersionEx( VersionInfo ) then begin with VersionInfo do begin case dwPlatformId of VER_PLATFORM_WIN32s : OSName := 'Win32s'; VER_PLATFORM_WIN32_WINDOWS : OSName := 'Windows 95'; VER_PLATFORM_WIN32_NT : OSName := 'Windows NT'; end; Result := OSName + ' Version ' + IntToStr( dwMajorVersion ) + '.' + IntToStr( dwMinorVersion ) + #13#10' (Build ' + IntToStr( dwBuildNumber ) + ': ' + szCSDVersion + ')'; end; end else Result := ''; end; function GlobalMemoryStatus( const Index : Integer ): DWORD; var MemoryStatus : TMemoryStatus; begin with MemoryStatus do begin dwLength := SizeOf( TMemoryStatus ); Windows.GlobalMemoryStatus( MemoryStatus ); case Index of 1 : Result := dwMemoryLoad; 2 : Result := dwTotalPhys div 1024; 3 : Result := dwAvailPhys div 1024; 4 : Result := dwTotalPageFile div 1024; 5 : Result := dwAvailPageFile div 1024; 6 : Result := dwTotalVirtual div 1024; 7 : Result := dwAvailVirtual div 1024; else Result := 0; end; end; end; function GetSystemInfoWORD( const Index : Integer ) : WORD; var SysInfo : TSystemInfo; begin Windows.GetSystemInfo( SysInfo ); with SysInfo do case Index of 1 : Result := wProcessorArchitecture; 2 : Result := wProcessorLevel; 3 : Result := wProcessorRevision; else Result := 0; end; end; function GetSystemInfoDWORD( const Index : Integer ) : DWORD; var SysInfo : TSystemInfo; begin Windows.GetSystemInfo( SysInfo ); with SysInfo do case Index of 1 : Result := dwPageSize; 2 : Result := dwActiveProcessorMask; 3 : Result := dwNumberOfProcessors; 4 : Result := dwProcessorType; 5 : Result := dwAllocationGranularity; else Result := 0; end; end; function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime; begin with SystemTime do Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds); end; function GetFileInformation( const FileName, Value : String ): String; var dwHandle, dwVersionSize : DWORD; strLangCharSetInfoString : String; pcBuffer : PChar; pTemp : Pointer; begin ////////////////////////////////////////////////////////////////////////////////// // The Win32 API contains the following predefined version information strings: // ////////////////////////////////////////////////////////////////////////////////// // CompanyName FileDescription FileVersion // // InternalName LegalCopyright OriginalFilename // // ProductName ProductVersion Comments // // LegalTrademarks // ////////////////////////////////////////////////////////////////////////////////// strLangCharSetInfoString := '\StringFileInfo\040904E4\' + Value; // 获取版本信息 dwVersionSize := GetFileVersionInfoSize( PChar( FileName ), // 指向文件名 dwHandle ); if dwVersionSize <> 0 then begin GetMem( pcBuffer, dwVersionSize ); try if GetFileVersionInfo( PChar( FileName ), // pointer to filename string dwHandle, // ignored dwVersionSize, // size of buffer pcBuffer ) then // pointer to buffer to receive file-version info. if VerQueryValue( pcBuffer, // pBlock - address of buffer for version resource PChar( strLangCharSetInfoString ), // lpSubBlock - address of value to retrieve pTemp, // lplpBuffer - address of buffer for version pointer dwVersionSize ) then // puLen - address of version-value length buffer Result := PChar( pTemp ); finally FreeMem( pcBuffer ); end; // try end;// if dwVersionSize end; // GetFileInformation function CompareFileTime( const FileNameOne, FileNameTwo : String; ComparisonType : TTimeOfWhat ): TFileTimeComparision; var FileOneFileTime : TFileTime; FileTwoFileTime : TFileTime; begin Result := ftError; FileOneFileTime := GetFileTime( FileNameOne, ComparisonType ); FileTwoFileTime := GetFileTime( FileNameTwo, ComparisonType ); case Windows.CompareFileTime( FileOneFileTime, FileTwoFileTime ) of -1 : Result := ftFileOneIsOlder; 0 : Result := ftFileTimesAreEqual; 1 : Result := ftFileTwoIsOlder; end; end; function GetFileTime_0( const FileName : String; ComparisonType : TTimeOfWhat ): TDateTime; var SystemTime : TSystemTime; FileTime : TFileTime; begin FileTime := GetFileTime( FileName, ComparisonType ); if FileTimeToSystemTime( FileTime, SystemTime ) then Result := SystemTimeToDateTime( SystemTime ) else Result := StrToDateTime('0000-00-00 00:00:00'); end; function FileInfo( const FileName :String ) : TFixedFileInfo; var dwHandle, dwVersionSize : DWORD; strSubBlock : String; pTemp : Pointer; pData : Pointer; begin strSubBlock := '\'; dwVersionSize := GetFileVersionInfoSize( PChar( FileName ), // pointer to filename string dwHandle ); // pointer to variable to receive zero // if GetFileVersionInfoSize is successful if dwVersionSize <> 0 then begin GetMem( pTemp, dwVersionSize ); try if GetFileVersionInfo( PChar( FileName ), // pointer to filename string dwHandle, // ignored dwVersionSize, // size of buffer pTemp ) then // pointer to buffer to receive file-version info. if VerQueryValue( pTemp, // pBlock - address of buffer for version resource PChar( strSubBlock ), // lpSubBlock - address of value to retrieve pData, // lplpBuffer - address of buffer for version pointer dwVersionSize ) then // puLen - address of version-value length buffer Result := PFixedFileInfo( pData )^; finally FreeMem( pTemp ); end; // try end; // if dwVersionSize end; function ExtractIcon( const FileName : String ): HIcon; begin Result := ShellAPI.ExtractIcon( Application.Handle, PChar( FileName ), 0 ); end; {************ Example Image1.Picture.Icon.Handle := ExtractIcon( WindowsDirectory + '\Notepad.exe' );} function ExtractAssociatedIcon( const FileName : String ): HIcon; var wIndex : WORD; pcFileName : Pchar; begin GetMem( pcFileName, MAX_PATH + 1 ); // Allocate memory for our pointer try StrPCopy( pcFilename, FileName ); // Copy the Filename into the Pchar var Result := ShellAPI.ExtractAssociatedIcon( Application.Handle, pcFileName, wIndex ); finally FreeMem( pcFileName ); end; // try end; function GetFreeDiskSpace( const Drive : Char ) : LongInt; var lpRootPathName : PChar; // address of root path lpSectorsPerCluster : DWORD; // address of sectors per cluster lpBytesPerSector : DWORD; // address of bytes per sector lpNumberOfFreeClusters : DWORD; // address of number of free clusters lpTotalNumberOfClusters : DWORD; // address of total number of clusters begin lpRootPathName := PChar( Drive + ':\' ); if Windows.GetDiskFreeSpace( lpRootPathName, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters ) then Result := lpNumberOfFreeClusters * lpBytesPerSector * lpSectorsPerCluster else Result := -1; end; function GetAllDiskFreeSpace : string; var i : integer; s : String; begin Result := ''; for i := 1 to Length(GetLogicalDrives ) do Result := Result + GetLogicalDrives[i] + ':\ ' + IntToStr( GetFreeDiskSpace( GetLogicalDrives[i] ) ) + ' B' + #13#10; end; function FileSize( const FileName : String ) : LongInt; var hFile : THandle; // handle of file to get size of lpFileSizeHigh : DWORD; // address of high-order WORD for file size begin Result := -1; hFile := FileOpen( FileName, fmShareDenyNone ); try if hFile <> 0 then Result := Windows.GetFileSize( hFile, @lpFileSizeHigh ); finally FileClose( hFile ); end; // try end; function GetShortPathName( const Path : String ): String; var lpszShortPath : PChar; // points to a buffer to receive the null-terminated short form of the path begin GetMem( lpszShortPath, MAX_PATH + 1 ); try Windows.GetShortPathName( PChar( Path ), lpszShortPath, MAX_PATH + 1 ); Result := lpszShortPath; finally FreeMem( lpszShortPath ); end; end; function GetFullPathName( const Path : String ): String; var nBufferLength : DWORD; // size, in characters, of path buffer lpBuffer : PChar; // address of path buffer lpFilePart : PChar; // address of filename in path begin nBufferLength := MAX_PATH + 1; GetMem( lpBuffer, MAX_PATH + 1 ); try if Windows.GetFullPathName( PChar( Path ), nBufferLength, lpBuffer, lpFilePart ) <> 0 then Result := lpBuffer else Result := 'ERROR'; finally FreeMem( lpBuffer ); end; end; function GetVolumeInformation( const Drive : Char ) : TVolumeInfo; var lpRootPathName : PChar; // address of root directory of the file system lpVolumeNameBuffer : PChar; // address of name of the volume nVolumeNameSize : DWORD; // length of lpVolumeNameBuffer lpVolumeSerialNumber : DWORD; // address of volume serial number lpMaximumComponentLength : DWORD; // address of system's maximum filename length lpFileSystemFlags : DWORD; // address of file system flags lpFileSystemNameBuffer : PChar; // address of name of file system nFileSystemNameSize : DWORD; // length of lpFileSystemNameBuffer begin GetMem( lpVolumeNameBuffer, MAX_PATH + 1 ); GetMem( lpFileSystemNameBuffer, MAX_PATH + 1 ); try nVolumeNameSize := MAX_PATH + 1; nFileSystemNameSize := MAX_PATH + 1; lpRootPathName := PChar( Drive + ':\' ); if Windows.GetVolumeInformation( lpRootPathName, lpVolumeNameBuffer, nVolumeNameSize, @lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer, nFileSystemNameSize ) then begin with Result do begin Name := lpVolumeNameBuffer; SerialNumber := lpVolumeSerialNumber; MaxComponentLength := lpMaximumComponentLength; FileSystemFlags := lpFileSystemFlags; FileSystemName := lpFileSystemNameBuffer; end; end else begin with Result do begin Name := ''; SerialNumber := 0; MaxComponentLength := 0; FileSystemFlags := 0; FileSystemName := ''; end; end; finally FreeMem( lpVolumeNameBuffer ); FreeMem( lpFileSystemNameBuffer ); end; end; function FindExecutable( const FileName : String ): String; var lpResult : PChar; // address of buffer for string for executable file on return begin GetMem( lpResult, MAX_PATH + 1 ); try if ShellAPI.FindExecutable( PChar( FileName ), PChar(GetCurrentDirectory ), lpResult ) > 32 then Result := lpResult else Result := '文件未找到!'; finally FreeMem( lpResult ); end; // try end; function DriveType( const Drive : Char ) : TDriveType; begin Result := TDriveType(GetDriveType(PChar(Drive + ':\'))); end; function DisconnectNetworkDrive( const Drive : Char ): Boolean; var sDrive : String; pResource : PChar; begin (* WNetCancelConnection2( LPTSTR lpszName, // address of resource name to disconnect DWORD fdwConnection, // connection type flags BOOL fForce // flag for unconditional disconnect ); *) sDrive := Drive + ':'; pResource := PChar( sDrive ); Result := ( Windows.WNetCancelConnection2( pResource, 0, True ) = NO_ERROR ); end; function AddNetworkDrive( const Resource : String; const Drive : Char ): Boolean; var sDrive : String; pDrive : PChar; begin (* DWORD WNetAddConnection( LPTSTR lpszRemoteName, // address of network device name LPTSTR lpszPassword, // address of password LPTSTR lpszLocalName // address of local device name ); *) sDrive := Drive + ':'; pDrive := PChar( sDrive ); Result := ( Windows.WNetAddConnection( PChar( Resource ), '', pDrive ) = NO_ERROR ); end; function GetUniversalName( const Drive : Char ): String; var pResource : PChar; lpBuffer : PUniversalNameInfo; dwWDSize : DWORD; begin (* DWORD WNetGetUniversalName( LPCTSTR lpLocalPath, // address of drive-based path for a network resource DWORD dwInfoLevel, // specifies form of universal name to be obtained LPVOID lpBuffer, // address of buffer that receives universal name data structure LPDWORD lpBufferSize // address of variable that specifies size of buffer ); *) pResource := PChar( Drive + ':\' ); dwWDSize := 1024; GetMem( lpBuffer, dwWDSize ); try if WNetGetUniversalName( pResource, UNIVERSAL_NAME_INFO_LEVEL, lpBuffer, dwWDSize ) = NO_ERROR then Result := lpBuffer.lpUniversalName else Result := 'ERROR'; finally FreeMem( lpBuffer ); end; end; procedure ShellAbout( const TitleBar, OtherText : String ); begin ShellAPI.ShellAbout( Application.Handle, PChar( TitleBar ), PChar( OtherText ), Application.Icon.Handle ); end; procedure FormatDrive( const Drive : Char ); var wDrive : WORD; dtDrive : TDriveType; strDriveType : String; begin dtDrive := DriveType( Drive ); // if it's not a HDD or a FDD then raise an exception if ( dtDrive <> dtFloppy ) and ( dtDrive <> dtFixed ) then begin strDriveType := 'Cannot format a '; case dtDrive of dtUnknown : strDriveType := 'Cannot determine drive type'; dtNoDrive : strDriveType := 'Specified drive does not exist'; dtNetwork : strDriveType := strDriveType + 'Network Drive'; dtCDROM : strDriveType := strDriveType + 'CD-ROM Drive'; dtRAM : strDriveType := strDriveType + 'RAM Drive'; end; // case dtDrive raise Exception.Create( strDriveType + '.' ); end // if DriveType else // proceed with the format begin wDrive := Ord( Drive ) - Ord( 'A' ); // SHFormatDrive is an undocumented API function SHFormatDrive( Application.Handle, wDrive, $ffff, 0); end; // else end; procedure ShutDown; const SE_SHUTDOWN_NAME = 'SeShutdownPrivilege'; // Borland forgot this declaration var hToken : THandle; tkp : TTokenPrivileges; tkpo : TTokenPrivileges; zero : DWORD; begin if Pos( 'Windows NT', GetSystemVersion ) = 1 then // we've got to do a whole buch of things begin zero := 0; if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin MessageBox( 0, 'Exit Error', 'OpenProcessToken() Failed', MB_OK ); Exit; end; // if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin MessageBox( 0, 'Exit Error', 'OpenProcessToken() Failed', MB_OK ); Exit; end; // if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) // SE_SHUTDOWN_NAME if not LookupPrivilegeValue( nil, 'SeShutdownPrivilege' , tkp.Privileges[ 0 ].Luid ) then begin MessageBox( 0, 'Exit Error', 'LookupPrivilegeValue() Failed', MB_OK ); Exit; end; // if not LookupPrivilegeValue( nil, 'SeShutdownPrivilege' , tkp.Privileges[0].Luid ) tkp.PrivilegeCount := 1; tkp.Privileges[ 0 ].Attributes := SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, False, tkp, SizeOf( TTokenPrivileges ), tkpo, zero ); if Boolean( GetLastError() ) then begin MessageBox( 0, 'Exit Error', 'AdjustTokenPrivileges() Failed', MB_OK ); Exit; end // if Boolean( GetLastError() ) else ExitWindowsEx( EWX_FORCE or EWX_SHUTDOWN, 0 ); end // if OSVersion = 'Windows NT' else begin // just shut the machine down ExitWindowsEx( EWX_FORCE or EWX_SHUTDOWN, 0 ); end; // else end; function GetSystemInfoPtr( const Index : Integer ): Pointer; var SysInfo : TSystemInfo; begin //property lpMinimumApplicationAddress : Pointer index 1 read myGetSystemInfoPtr; //property lpMaximumApplicationAddress : Pointer index 2 read myGetSystemInfoPtr; Windows.GetSystemInfo( SysInfo ); with SysInfo do case Index of 1 : Result := lpMinimumApplicationAddress; 2 : Result := lpMaximumApplicationAddress else Result := nil; end; // case Index of end; {*普通状态发送,引用ShellAPI单元*} procedure SendEMail_Hide; var Handle : THandle; begin ShellExecute(Handle,'open',PChar('mailto:收件人?subject=主题&cc=抄送人'),nil, nil, SW_SHOWNORMAL); end; {*判断EMAIL地址是否合法*} function CheckMailAddress(Value : string): boolean; var Index: integer; lp : integer; begin Result := false; if ((length(trim(Value)) > 20) or (Pos('.', Value) < 4)) or (Pos('.HTM', UpperCase(Value)) > 0) or (Pos('.HTML', UpperCase(Value)) > 0) or (Pos('.ASP', UpperCase(Value)) > 0) or (Pos('.JSP', UpperCase(Value)) > 0) then exit; for lp := 1 to length(Value) do if (Ord(Value[lp]) > $80) and (Value[lp] <> '@') then exit; if (Pos('.', Value) < Pos('@', Value) + 1) then exit; Index := Pos('@', Value); if (Index < 2) or (Index >= Length(Value)) then exit; Result := true; end; end.
unit UStopWatch; interface uses Winapi.Windows, System.Classes, System.SysUtils, System.DateUtils; type TStopWatch = class private FOwner: TObject; fFrequency: TLargeInteger; fIsRunning: Boolean; fIsHighResolution: Boolean; fStartCount, fStopCount: TLargeInteger; fActive: Boolean; procedure SetTickStamp(var lInt: TLargeInteger); function GetElapsedTicks: TLargeInteger; function GetElapsedMilliseconds: TLargeInteger; Function GetElapsedNanoSeconds: TLargeInteger; function GetElapsed: string; public constructor Create(AOwner: TComponent; const IsActive: Boolean = false; const startOnCreate: Boolean = false); destructor Destroy; override; procedure Start; procedure Stop; property IsHighResolution: Boolean read fIsHighResolution; property ElapsedTicks: TLargeInteger read GetElapsedTicks; property ElapsedMilliseconds: TLargeInteger read GetElapsedMilliseconds; property ElapsedNanoSeconds: TLargeInteger read GetElapsedNanoSeconds; property Elapsed: string read GetElapsed; property IsRunning: Boolean read fIsRunning; end; implementation {$REGION 'TStopWatch'} Const NSecsPerSec = 1000000000; constructor TStopWatch.Create(AOwner: TComponent; const IsActive: Boolean = false; const startOnCreate: Boolean = false); begin inherited Create(); FOwner := AOwner; fIsRunning := false; fActive := IsActive; fIsHighResolution := QueryPerformanceFrequency(fFrequency); if NOT fIsHighResolution then fFrequency := MSecsPerSec; if startOnCreate then Start; end; destructor TStopWatch.Destroy; begin Stop; inherited Destroy; end; function TStopWatch.GetElapsedTicks: TLargeInteger; begin Result := fStopCount - fStartCount; end; procedure TStopWatch.SetTickStamp(var lInt: TLargeInteger); begin if fIsHighResolution then QueryPerformanceCounter(lInt) else lInt := MilliSecondOf(Now); end; function TStopWatch.GetElapsed: string; begin Result := FloatToStr(ElapsedMilliseconds / 1000) + ' Sec / ' + FloatToStr(ElapsedMilliseconds) + ' Ms / ' + FloatToStr(ElapsedNanoSeconds) + ' Ns'; end; function TStopWatch.GetElapsedMilliseconds: TLargeInteger; var Crnt: TLargeInteger; begin if fIsRunning then begin SetTickStamp(Crnt); Result := (MSecsPerSec * (Crnt - fStartCount)) div fFrequency; end else Result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency; end; function TStopWatch.GetElapsedNanoSeconds: TLargeInteger; begin Result := (NSecsPerSec * (fStopCount - fStartCount)) div fFrequency; end; procedure TStopWatch.Start; begin if fActive then begin SetTickStamp(fStartCount); fIsRunning := true; end; end; procedure TStopWatch.Stop; begin if fActive then begin SetTickStamp(fStopCount); fIsRunning := false; end; end; {$ENDREGION} end.
unit FC.Trade.ViewAlertersDialog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufmDialogClose_B, StdCtrls, ExtendControls, ExtCtrls, ComCtrls, FC.Definitions, ActnList, Menus, ActnPopup; type TfmViewAlertersDialog = class(TfmDialogClose_B) Label1: TLabel; lvAlerters: TExtendListView; buProperties: TButton; ActionList1: TActionList; acAlerterProperties: TAction; acDeleteAlerter: TAction; buAdd: TButton; accAddAlerter: TAction; Button1: TButton; pmAlerter: TPopupActionBar; Properties1: TMenuItem; Delete1: TMenuItem; N1: TMenuItem; Add1: TMenuItem; procedure lvAlertersAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure lvAlertersChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure accAddAlerterExecute(Sender: TObject); procedure acDeleteAlerterUpdate(Sender: TObject); procedure acDeleteAlerterExecute(Sender: TObject); procedure lvAlertersDblClick(Sender: TObject); procedure buOKDialogKey(Sender: TObject; var Key: Word); procedure lvAlertersEdited(Sender: TObject; Item: TListItem; var S: string); procedure acAlerterPropertiesExecute(Sender: TObject); procedure acAlerterPropertiesUpdate(Sender: TObject); private FProject: IStockProject; procedure Fill; function CurrentAlerter: IStockAlerter; public constructor Create(aProject: IStockProject); reintroduce; end; implementation uses FC.Singletons, FC.Trade.CreateAlerterDialog; {$R *.dfm} type TAlerterListItem = class (TListItem) public Alerter: IStockAlerter; end; { TfmViewAlertersDialog } procedure TfmViewAlertersDialog.Fill; var aListItem: TAlerterListItem; aAlerter: IStockAlerter; i: Integer; begin lvAlerters.HandleNeeded; lvAlerters.Items.BeginUpdate; try lvAlerters.Items.Clear; for i := 0 to FProject.AlerterCount-1 do begin aAlerter:=FProject.GetAlerter(i); aListItem:=TAlerterListItem.Create(lvAlerters.Items); lvAlerters.Items.AddItem(aListItem); aListItem.Caption:=aAlerter.GetName; aListItem.Alerter:=aAlerter; aListItem.Checked:=aAlerter.GetEnabled; end; finally lvAlerters.Items.EndUpdate; end; if lvAlerters.Items.Count>0 then lvAlerters.Items[0].Selected:=true; end; procedure TfmViewAlertersDialog.acAlerterPropertiesUpdate(Sender: TObject); begin TAction(Sender).Enabled:=lvAlerters.Selected<>nil; end; constructor TfmViewAlertersDialog.Create(aProject: IStockProject); begin inherited Create(nil); Assert(aProject<>nil); FProject:=aProject; Fill; end; function TfmViewAlertersDialog.CurrentAlerter: IStockAlerter; begin result:=TAlerterListItem(lvAlerters.Selected).Alerter; end; procedure TfmViewAlertersDialog.acAlerterPropertiesExecute(Sender: TObject); begin CurrentAlerter.ShowPropertyWindow; lvAlerters.Selected.Caption:=CurrentAlerter.GetName; end; procedure TfmViewAlertersDialog.lvAlertersEdited(Sender: TObject; Item: TListItem; var S: string); begin TAlerterListItem(Item).Alerter.SetName(S); end; procedure TfmViewAlertersDialog.buOKDialogKey(Sender: TObject; var Key: Word); begin if (Key=VK_RETURN) then if lvAlerters.IsEditing then begin key:=0; //Как сделать EndEdit? buOK.SetFocus; lvAlerters.SetFocus; end; end; procedure TfmViewAlertersDialog.lvAlertersAdvancedCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); begin inherited; if not Item.Checked then Sender.Canvas.Font.Color:=clGrayText else Sender.Canvas.Font.Color:=clWindowText end; procedure TfmViewAlertersDialog.lvAlertersChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if Item<>nil then if TAlerterListItem(Item).Alerter<>nil then if TAlerterListItem(Item).Alerter.GetEnabled<>Item.Checked then TAlerterListItem(Item).Alerter.SetEnabled(Item.Checked); end; procedure TfmViewAlertersDialog.lvAlertersDblClick(Sender: TObject); begin acAlerterProperties.Execute; end; procedure TfmViewAlertersDialog.accAddAlerterExecute(Sender: TObject); var aDialog : TfmCreateAlerterDialog; aAlerter : IStockAlerter; begin aDialog:=TfmCreateAlerterDialog.Create(nil); try //Запуск диалога if aDialog.ShowModal=mrOK then begin aAlerter:=FC.Singletons.AlerterFactory.CreateAlerter(aDialog.SelectedAlerter.IID); aAlerter.SetProject(FProject); if aAlerter.ShowPropertyWindow then begin FProject.AddAlerter(aAlerter); aAlerter.SetEnabled(true); Fill; end else begin aAlerter.SetProject(nil); aAlerter.Dispose; aAlerter:=nil; end; end; finally aDialog.Free; end; end; procedure TfmViewAlertersDialog.acDeleteAlerterExecute(Sender: TObject); begin CurrentAlerter.GetProject.RemoveAlerter(CurrentAlerter); lvAlerters.Selected.Free; end; procedure TfmViewAlertersDialog.acDeleteAlerterUpdate(Sender: TObject); begin TAction(Sender).Enabled:=lvAlerters.Selected<>nil; end; end.
unit jsonquery; interface uses classes,sysutils,DB,DBClient,dialogs,superobject,httpsend; type TJSONQuery = class(TCustomClientDataSet) private FURL: string; FAuthor: string; procedure resetState; function MemoryStreamToString(M: TMemoryStream): string; procedure JSONToData(AData: string); procedure SetAuthor(const Value: string); published property URL: string read FURL write FURL; property CommandText; property Author: string read FAuthor write SetAuthor; public constructor Create(AOwner: TComponent);override; destructor Destroy;override; procedure Open; procedure Execute; end; procedure Register; implementation procedure Register; begin RegisterComponents('Tigor Manurung',[TJSONQuery]); end; { TJSONQuery } constructor TJSONQuery.Create(AOwner: TComponent); begin inherited Create(AOwner); FAuthor := 'Tigor Mangatur Manurung'; end; destructor TJSONQuery.Destroy; begin inherited; end; procedure TJSONQuery.Execute; begin Open; end; procedure TJSONQuery.JSONToData(AData: string); var o,ARecord,item: ISuperObject; iCol,iRow: integer; begin resetState; o := so(AData); if (o = nil) or (trim(AData) = '') then exit; iCol := 0; Close; for item in o['column'] do begin FieldDefs.Add(item.AsString,ftString,40); inc(iCol,1); end; CreateDataSet; iCol := 0; iRow := 1; for ARecord in o['records'] do begin iCol := 0; Append; for item in ARecord do begin FieldByName(FieldDefs[iCol].Name).AsString := item.AsString; Inc(iCol,1); end; Post; Inc(iRow,1); end; end; function TJSONQuery.MemoryStreamToString(M: TMemoryStream): string; begin M.Seek(0,soFromBeginning); SetString(Result, PAnsiChar(M.Memory), M.Size); end; procedure TJSONQuery.Open; var AStream: TMemoryStream; sData: string; begin if FURL = '' then raise Exception.Create('Alamat web service harus diisi!'); if CommandText = '' then raise Exception.Create('Command text harus diisi!'); AStream := TMemoryStream.Create; try HttpPostURL(FURL,Format('sql=%s',[self.CommandText]),AStream); sData := MemoryStreamToString(AStream); JSONToData(sData); finally FreeAndNil(AStream); end; end; procedure TJSONQuery.resetState; begin FieldDefs.Clear; end; procedure TJSONQuery.SetAuthor(const Value: string); begin // FAuthor := Value; end; end.
program Sample; begin WriteLn(1); WriteLn(2.1); WriteLn('a string'); WriteLn(#65); WriteLn('Hello ', 1); end.
{*******************************************************} { } { FMX UI 日志输出模块 } { } { 版权所有 (C) 2013 YangYxd } { } {*******************************************************} unit UI.Debug; {$I 'CMOV.inc'} interface {.$DEFINE UseUDP} uses {$IFDEF UseUDP} iocp, {$ENDIF} {$IFDEF MSWINDOWS} Windows, {$ENDIF} SyncObjs, SysUtils, Classes; {$IFDEF UseUDP} const UdpSvrAddr = '127.0.0.1'; UdpSvrPort = 6699; {$ENDIF} type /// <summary> /// 输出信息类型 /// </summary> TTraceSeverity = (tsDebug {调试信息}, tsInformation {信息}, tsWarning {警告}, tsError {错误}); TTraceSeverities = set of TTraceSeverity; const TRACE_SEVERITIES_ALL = [tsDebug, tsInformation, tsWarning, tsError]; {$IFDEF ShowUI} type TOnWriteLogEvent = procedure (Sender: TObject; AType: TTraceSeverity; const Log: string) of object; var FOnWriteLog: TOnWriteLogEvent = nil; {$ENDIF} // 写日志 procedure Log(sev: TTraceSeverity; const text: string); procedure LogD(const text: string); inline; // tsDeubg procedure LogW(const text: string); inline; // tsWarning procedure LogI(const text: string); inline; // tsInfomation procedure LogE(const text: string); overload; inline; // tsError procedure LogE(Sender: TObject; E: TObject); overload; // tsError procedure LogE(Sender: TObject; const Title: string; E: TObject); overload; // tsError procedure LogE(Sender: TObject; const Title: string; E: Exception); overload; // tsError {$IFDEF UseUDP} /// <summary> /// 设置远程调试服务器地址 /// </summary> procedure LogRemoteDebugSvrAddr(const RemoteAddr: string; RemotePort: Word); {$ENDIF} var SevToStr: array [TTraceSeverity] of string = ('调试', '信息', '警告', '错误'); implementation const sExceptionLogFmt = '[%s.%s] %s'; sExceptionLogSFmt = '[%s] %s'; {$IFDEF MSWINDOWS} sLineLogFmt = '[%s][%s] %s (%d)'#13; {$ELSE} sLineLogFmt = '[%s][%s] %s'#13; {$ENDIF} sLogFmt = '[%s][%s] %s (%d)'; sLogTimeFmt = 'hh:mm:ss.zzz'; sFileNotExist = 'File does not exist.'; sInvalidFileHandle = 'Invalid File Handle. Can''t open the file.'; sLogDir = 'Log\'; sLogFileNameFmt = 'yyyymmdd'; sLogFileExtName = '.log'; sDebuging = '<Debuging>'; type ITrace = interface(IInterface) procedure FillWrite; procedure Write(sev: TTraceSeverity; const text: string); procedure Writeln(sev: TTraceSeverity; const text: string); function ReadAll: string; procedure SetBufferSize(Value: Integer); end; // 输出调试信息 TDebugTrace = class(TInterfacedObject, ITrace) public procedure FillWrite; procedure Write(sev: TTraceSeverity; const text: string); procedure Writeln(sev: TTraceSeverity; const text: string); function ReadAll: string; procedure SetBufferSize(Value: Integer); end; {$IFDEF UseUDP} // 输出远程调试信息 TRemoteDebugTrace = class(TInterfacedObject, ITrace) private udp: TIocpUdpSocket; FAddr: string; FPort: Word; protected procedure prepare; inline; public constructor Create; destructor Destroy; override; procedure FillWrite; procedure Write(sev: TTraceSeverity; const text: string); procedure Writeln(sev: TTraceSeverity; const text: string); function ReadAll: string; procedure SetBufferSize(Value: Integer); property RemoteAddr: string read FAddr write FAddr; property RemotePort: Word read FPort write FPort; end; {$ENDIF} {$IFDEF OuputFileLog} TFileTrace = class(TInterfacedObject, ITrace) private FFile: TFileStream; FLastDate: Int64; procedure InitFile; procedure FillWrite; procedure ToFileEnd; inline; protected class function GetFileName: string; class function GetFilePath: string; public constructor Create; destructor Destroy; override; procedure Write(sev: TTraceSeverity; const text: string); procedure Writeln(sev: TTraceSeverity; const text: string); function ReadAll: string; procedure SetBufferSize(Value: Integer); end; {$ENDIF} var locker: TCriticalSection; FThread: TThread = nil; Trace: ITrace = nil; UdpTrace: ITrace; procedure Lock; inline; begin Locker.Enter; end; procedure UnLock; inline; begin locker.Leave; end; procedure LogInit(New: Boolean); {$IFDEF OuputFileLog} var fname: string; {$ENDIF} begin if New then begin if Trace <> nil then begin Trace._Release; Trace := nil; end; {$IFDEF OuputFileLog} fname := TFileTrace.GetFileName; if FileExists(fname) then DeleteFile(fname); {$ENDIF} end; if Trace <> nil then Exit; {$IFDEF DebugApp} Trace := TDebugTrace.Create; {$ELSE} {$IFDEF OuputFileLog} Trace := TFileTrace.Create; //FThread := TFileRealWriteThd.Create(False); {$ENDIF} {$ENDIF} end; procedure Log(sev: TTraceSeverity; const text: string); begin if Trace <> nil then Trace.Write(sev, text); {$IFDEF UseUDP} if UdpTrace <> nil then UdpTrace.Write(sev, text); {$ENDIF} {$IFDEF ShowUI} if Assigned(FOnWriteLog) then FOnWriteLog(TObject(Trace), sev, text); {$ENDIF} end; procedure LogD(const text: string); begin Log(tsDebug, text); end; procedure LogW(const text: string); begin Log(tsWarning, text); end; procedure LogI(const text: string); begin Log(tsInformation, text); end; procedure LogE(const text: string); begin Log(tsError, text); end; procedure LogE(Sender: TObject; E: TObject); begin if (E <> nil) then begin if (E is Exception) then Log(tsError, Format(sExceptionLogSFmt, [Sender.ClassName, Exception(E).Message])) else Log(tsError, Format(sExceptionLogSFmt, [Sender.ClassName, E.ClassName])); end else Log(tsError, Sender.ClassName); end; procedure LogE(Sender: TObject; const Title: string; E: TObject); begin if (E <> nil) then begin if (E is Exception) then Log(tsError, Format(sExceptionLogFmt, [Sender.ClassName, Title, Exception(E).Message])) else Log(tsError, Format(sExceptionLogFmt, [Sender.ClassName, Title, E.ClassName])); end else Log(tsError, Format(sExceptionLogFmt, [Sender.ClassName, Title, ''])); end; procedure LogE(Sender: TObject; const Title: string; E: Exception); begin if E = nil then Log(tsError, Format(sExceptionLogFmt, [Sender.ClassName, Title, ''])) else Log(tsError, Format(sExceptionLogFmt, [Sender.ClassName, Title, E.Message])); end; procedure LogRemoteDebugSvrAddr(const RemoteAddr: string; RemotePort: Word); begin if UdpTrace <> nil then begin {$IFDEF UseUDP} TRemoteDebugTrace(UdpTrace).RemoteAddr := RemoteAddr; TRemoteDebugTrace(UdpTrace).RemotePort := RemotePort; {$ENDIF} end; end; function LogContent: string; begin if Assigned(Trace) then Result := Trace.ReadAll else Result := ''; end; procedure LogPushFile(); begin if Assigned(Trace) then begin try Trace.FillWrite; except end; end; end; { TDebugTrace } procedure TDebugTrace.FillWrite; begin end; function TDebugTrace.ReadAll: string; begin Result := sDebuging; end; procedure TDebugTrace.SetBufferSize(Value: Integer); begin end; procedure TDebugTrace.Write(sev: TTraceSeverity; const text: string); begin Lock; Writeln(sev, text); UnLock; end; procedure TDebugTrace.Writeln(sev: TTraceSeverity; const text: string); {$IFDEF DebugApp}var Msg: string;{$ENDIF} begin {$IFDEF WRITEDEBUG} if IsConsole then begin Msg := Format(sLogFmt, [FormatDateTime(sLogTimeFmt, Now), SevToStr[sev], text, GetCurrentThreadId]); Lock; System.Writeln(Msg); UnLock; end; {$ENDIF} {$IFDEF OutputDebug} if Length(Msg) = 0 then Msg := Format(sLogFmt, [FormatDateTime(sLogTimeFmt, Now), SevToStr[sev], text, GetCurrentThreadId]); Lock; OutputDebugString(PChar(Msg)); UnLock; {$ENDIF} end; { TRemoteDebugTrace } {$IFDEF UseUDP} constructor TRemoteDebugTrace.Create; begin udp := TIocpUdpSocket.Create(nil); FAddr := UdpSvrAddr; FPort := UdpSvrPort; end; destructor TRemoteDebugTrace.Destroy; begin if udp.Active then udp.Disconnect; FreeAndNil(udp); inherited; end; procedure TRemoteDebugTrace.prepare; begin if (not udp.Active) then udp.Active := True; end; function TRemoteDebugTrace.ReadAll: string; begin Result := ''; end; procedure TRemoteDebugTrace.FillWrite; begin end; procedure TRemoteDebugTrace.Write(sev: TTraceSeverity; const text: string); var Msg: string; begin Msg := Format(sLineLogFmt, [FormatDateTime(sLogTimeFmt, Now), SevToStr[sev], text{$IFDEF MSWINDOWS}, GetCurrentThreadId{$ENDIF}]); Lock; try udp.Send(AnsiString(Msg), Faddr, FPort);//, Msg); finally UnLock; end; end; procedure TRemoteDebugTrace.SetBufferSize(Value: Integer); begin end; procedure TRemoteDebugTrace.Writeln(sev: TTraceSeverity; const text: string); var Msg: string; begin Msg := Format(sLineLogFmt, [FormatDateTime(sLogTimeFmt, Now), SevToStr[sev], text{$IFDEF MSWINDOWS}, GetCurrentThreadId{$ENDIF}]); Lock; try udp.Send(AnsiString(Msg), FAddr, FPort); //, Msg); finally UnLock; end; end; {$ENDIF} { TFileTrace } {$IFDEF OuputFileLog} constructor TFileTrace.Create; begin FFile := nil; InitFile; end; destructor TFileTrace.Destroy; begin FreeAndNil(FFile); inherited; end; function GetExeFileName: string; begin Result := ExtractFileName(ParamStr(0)); Delete(Result, Length(Result) - 4, 4); end; class function TFileTrace.GetFileName: string; var Path: string; begin Path := ExtractFilePath(ParamStr(0)) + GetExeFileName + sLogDir; if not DirectoryExists(Path) then CreateDir(Path); Result := Path + FormatDateTime(sLogFileNameFmt, Now) + sLogFileExtName; end; class function TFileTrace.GetFilePath: string; begin Result := ExtractFilePath(ParamStr(0)) + GetExeFileName + sLogDir; end; procedure TFileTrace.FillWrite; begin end; procedure TFileTrace.InitFile; var FHandle: THandle; begin if (FFile <> nil) then FreeAndNil(FFile); if not FileExists(GetFileName) then begin FHandle := FileCreate(GetFileName); CloseHandle(FHandle); end; FFile := TFileStream.Create(GetFileName, fmOpenReadWrite or fmShareDenyNone); FLastDate := Trunc(Now); end; function TFileTrace.ReadAll: string; begin Lock; if Trunc(Now) - FLastDate <> 0 then InitFile; if FFile.Size > 0 then begin SetLength(Result, FFile.Size); FFile.Position := 0; FFile.Read(Result[1], FFile.Size); end else Result := ''; UnLock; end; procedure TFileTrace.ToFileEnd; begin if Trunc(Now) - FLastDate <> 0 then InitFile else if (FFile.Position <> FFile.Size) then FFile.Position := FFile.Size; end; procedure TFileTrace.Write(sev: TTraceSeverity; const text: string); var Msg: string; begin Msg := Format(sLineLogFmt, [FormatDateTime(sLogTimeFmt, Now), SevToStr[sev], text, GetCurrentThreadId]); Lock; ToFileEnd; FFile.Write(Msg[1], Length(Msg){$IFDEF UNICODE} shl 1{$ENDIF}); UnLock; end; procedure TFileTrace.Writeln(sev: TTraceSeverity; const text: string); var Msg: string; begin Msg := Format(sLineLogFmt, [FormatDateTime(sLogTimeFmt, Now), SevToStr[sev], text, GetCurrentThreadId]); Lock; ToFileEnd; FFile.Write(Msg[1], Length(Msg){$IFDEF UNICODE} shl 1{$ENDIF}); UnLock; end; procedure TFileTrace.SetBufferSize(Value: Integer); begin end; {$ENDIF} initialization locker := TCriticalSection.Create; LogInit(False); {$IFDEF UseUDP} UdpTrace := TRemoteDebugTrace.Create; {$ENDIF} finalization FreeAndNil(FThread); FreeAndNil(locker); if Trace <> nil then Trace._Release; if UdpTrace <> nil then UdpTrace._Release; end.
unit FC.StockChart.UnitTask.ValueSupport.StatisticsDialog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Contnrs, Dialogs, BaseUtils,SystemService, ufmDialogClose_B, ufmDialog_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, Spin, StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, DB, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, MemoryDS, ComCtrls, TeEngine, Series, TeeProcs, Chart, FC.StockChart.CustomDialog_B, ImgList, JvCaptionButton, JvComponentBase, JvDockControlForm, Mask; type TfmValueSupportStatisticsDialog = class(TfmStockChartCustomDialog_B) taReport: TMemoryDataSet; DataSource1: TDataSource; pbProgress: TProgressBar; taReportTime: TTimeField; taReportValue: TFloatField; pcPages: TPageControl; tsIntradays: TTabSheet; tsMonthVolatility: TTabSheet; DataSource2: TDataSource; taWeekdayStatistics: TMemoryDataSet; taWeekdayStatisticsValue: TFloatField; taWeekdayStatisticsWeekday: TStringField; chIntraday: TChart; chIntradayValue: TBarSeries; Label3: TLabel; cbValueSupport: TExtendComboBox; chMonthVolatility: TChart; laHelp: TTipPanel; chMonthVolatilityValue: TBarSeries; tsAllPeaks: TTabSheet; Panel1: TPanel; edValueTreshold: TExtendEdit; ckValueTreshold: TExtendCheckBox; chAllPeaks: TChart; chAllPeaksValue: TBarSeries; ckAllPeaksShowMarks: TExtendCheckBox; Splitter1: TSplitter; Panel2: TPanel; Label2: TLabel; Label1: TLabel; grWeekdayStatistics: TEditDBGrid; grReport: TEditDBGrid; laChartPropsHeader: TLabel; mmChartProps: TExtendMemo; procedure ckAllPeaksShowMarksClick(Sender: TObject); procedure edValueTresholdChange(Sender: TObject); procedure ckHLClick(Sender: TObject); procedure cbValueSupportChange(Sender: TObject); procedure pcPagesChange(Sender: TObject); procedure grReportChangeRecord(Sender: TObject); private FCalculating : integer; FIndicator: ISCIndicatorValueSupport; procedure Init(const aIndicator: ISCIndicatorValueSupport); procedure CalculateIntradays; procedure CaclulateMonthVolatility; procedure CalculateWeekDayStatistics(const aFrom,aTo: TTime); procedure CalculateAllPeaks; public class procedure Run(const aIndicator: ISCIndicatorValueSupport; const aStockChart: IStockChart); constructor Create(const aStockChart: IStockChart); override; destructor Destroy; override; end; implementation uses Math,DateUtils,Application.Definitions; type TDirection = (dNone,dUp,dDown); {$R *.dfm} { TfmCalculateWidthDialog } procedure TfmValueSupportStatisticsDialog.CaclulateMonthVolatility; var aInterval: integer; i: integer; begin aInterval:=StockChart.StockSymbol.GetTimeIntervalValue; cbValueSupport.Clear; for i := 0 to (1440 div aInterval)-1 do cbValueSupport.AddItem(TimeToStr(i*aInterval/MinsPerDay),TObject(i)); end; procedure TfmValueSupportStatisticsDialog.CalculateAllPeaks; var i: integer; aValue:TStockRealNumber; aHLMax: TStockRealNumber; aHLR: boolean; aInputData : ISCInputDataCollection; begin TWaitCursor.SetUntilIdle; aInputData:=(FIndicator as ISCIndicator).GetInputData; chAllPeaks.AutoRepaint:=false; try chAllPeaksValue.Clear; aHLMax:=edValueTreshold.ValueFloat; if not ckValueTreshold.Checked then aHLMax:=Low(integer); for i:=(FIndicator as ISCIndicator).GetFirstValidValueIndex to (FIndicator as ISCIndicator).GetInputData.Count-1 do begin aValue:=FIndicator.GetValue(i); aHLR:=aValue>aHLMax; if aHLR then chAllPeaksValue.AddXY(aInputData.DirectGetItem_DataDateTime(i),aValue); end; finally chAllPeaks.AutoRepaint:=true; chAllPeaks.Repaint; ckAllPeaksShowMarksClick(nil); end; end; procedure TfmValueSupportStatisticsDialog.CalculateIntradays; var i,j: Integer; aIntradayStatisticsVal: array of TSCRealNumber; aIntradayStatisticsCNT: array of integer; aInterval: integer; aInputData : ISCInputDataCollection; aMax,aMin: TSCRealNumber; v,aSum,aTotalSum: TSCRealNumber; aTotalCount: integer; aNullCount : integer; aFVI : integer; aNullValueSupport : ISCIndicatorNullValueSupport; begin TWaitCursor.SetUntilIdle; aInterval:=StockChart.StockSymbol.GetTimeIntervalValue; SetLength(aIntradayStatisticsVal,1440 div aInterval); SetLength(aIntradayStatisticsCNT,1440 div aInterval); aInputData:=(FIndicator as ISCIndicator).GetInputData; aFVI:=(FIndicator as ISCIndicator).GetFirstValidValueIndex; aTotalSum:=0; aTotalCount:=0; aNullCount:=0; Supports(FIndicator,ISCIndicatorNullValueSupport,aNullValueSupport); FIndicator.GetValue(aInputData.Count-1); //Сразу все посчитаем for i:=aFVI to aInputData.Count-1 do begin if (aNullValueSupport<>nil) and (aNullValueSupport.IsNullValue(i)) then begin inc(aNullCount); continue; end; j:=MinuteOfTheDay(aInputData.DirectGetItem_DataDateTime(i)); j:=j div aInterval; aIntradayStatisticsVal[j]:=aIntradayStatisticsVal[j]+ FIndicator.GetValue(i); aIntradayStatisticsCNT[j]:=aIntradayStatisticsCNT[j]+1; inc(aTotalCount); aTotalSum:=aTotalSum+FIndicator.GetValue(i); end; aMin:=high(integer); aMax:=low(integer); aSum:=0; inc(FCalculating); try taReport.DisableControls; taReport.EmptyTable; taReport.Open; chIntradayValue.Clear; for I := 0 to High(aIntradayStatisticsVal) do begin taReport.Append; taReportTime.Value:=i*aInterval/MinsPerDay; if aIntradayStatisticsCNT[i]<>0 then begin v:=aIntradayStatisticsVal[i]/aIntradayStatisticsCNT[i]; taReportValue.Value:=RoundTo(v,-6); chIntradayValue.AddXY(taReportTime.Value,taReportValue.Value); aSum:=aSum+v; aMin:=min(aMin,v); aMax:=max(aMax,v); end else begin chIntradayValue.AddXY(taReportTime.Value,0); end; taReport.Post; end; taReport.First; chIntraday.LeftAxis.AdjustMaxMin; chIntraday.LeftAxis.AutomaticMinimum:=false; if chIntraday.LeftAxis.Maximum>aMin then chIntraday.LeftAxis.Minimum:=aMin; finally dec(FCalculating); taReport.EnableControls; end; inc(FCalculating); try grReport.RefreshSort; finally dec(FCalculating); end; mmChartProps.Clear; mmChartProps.Lines.Add(Format('Max=%g',[aMax])); mmChartProps.Lines.Add(Format('Min=%g',[aMin])); mmChartProps.Lines.Add(Format('Sum=%g',[aSum])); mmChartProps.Lines.Add(Format('Avg=%g',[aSum/Length(aIntradayStatisticsCNT)])); if aSum<>0 then begin mmChartProps.Lines.Add(Format('Max Percentage=%g',[aMax/aSum*100])); mmChartProps.Lines.Add(Format('Min Percentage=%g',[aMin/aSum*100])); end; mmChartProps.Lines.Add(Format('Total Sum=%g',[aTotalSum])); mmChartProps.Lines.Add(Format('Null Value Count=%d',[aNullCount])); mmChartProps.Lines.Add(Format('Total Value Count=%d',[aTotalCount])); if aTotalCount>0 then mmChartProps.Lines.Add(Format('Total Value Avg=%g',[aTotalSum/aTotalCount])); i:=DaysBetween(aInputData.DirectGetItem_DataDateTime(aInputData.Count-1), aInputData.DirectGetItem_DataDateTime(aFVI)); mmChartProps.Lines.Add(Format('Total Days=%d',[i])); grReportChangeRecord(nil); end; procedure TfmValueSupportStatisticsDialog.CalculateWeekDayStatistics(const aFrom, aTo: TTime); var i,j: Integer; aWeekdayStatisticsHL: array [1..7] of TSCRealNumber; aWeekdayStatisticsCNT: array [1..7] of integer; aDT: TDateTime; aInputData : ISCInputDataCollection; begin TWaitCursor.SetUntilIdle; aInputData:=(FIndicator as ISCIndicator).GetInputData; ZeroMemory(@aWeekdayStatisticsHL[1],7*SizeOf(TSCRealNumber)); ZeroMemory(@aWeekdayStatisticsCNT[1],7*SizeOf(integer)); for i:=(FIndicator as ISCIndicator).GetFirstValidValueIndex to (FIndicator as ISCIndicator).GetInputData.Count-1 do begin aDT:=aInputData.DirectGetItem_DataDateTime(i); if (CompareDateTime(Frac(aDT),aFrom)>=0) and (CompareDateTime(Frac(aDT),aTo)<=0) then begin j:=DayOfTheWeek(aDT); aWeekdayStatisticsHL[j]:=aWeekdayStatisticsHL[j]+ FIndicator.GetValue(i); aWeekdayStatisticsCNT[j]:=aWeekdayStatisticsCNT[j]+1; end; end; inc(FCalculating); try taWeekdayStatistics.EmptyTable; taWeekdayStatistics.Open; for I := 1 to 7 do begin taWeekdayStatistics.Append; taWeekdayStatisticsWeekday.Value:=WeekdaysLong[i]; if aWeekdayStatisticsCNT[i]<>0 then taWeekdayStatisticsValue.Value:=RoundTo(aWeekdayStatisticsHL[i]/aWeekdayStatisticsCNT[i],-6); taWeekdayStatistics.Post; end; finally dec(FCalculating); end; grWeekdayStatistics.RefreshSort; end; procedure TfmValueSupportStatisticsDialog.cbValueSupportChange(Sender: TObject); var i: Integer; aMinute: integer; aCount:integer; aValue: TSCRealNumber; aCurrentMonth: integer; aCurrentYear: integer; aInputData : ISCInputDataCollection; begin TWaitCursor.SetUntilIdle; chMonthVolatilityValue.Clear; aInputData:=(FIndicator as ISCIndicator).GetInputData; if cbValueSupport.ItemIndex<>-1 then begin aMinute:=integer(cbValueSupport.Items.Objects[cbValueSupport.ItemIndex])*StockChart.StockSymbol.GetTimeIntervalValue; aValue:=0; aCount:=0; aCurrentMonth:=-1; aCurrentYear:=-1; chMonthVolatility.AutoRepaint:=false; try for i:=(FIndicator as ISCIndicator).GetFirstValidValueIndex to (FIndicator as ISCIndicator).GetInputData.Count-1 do begin if (aCurrentMonth<>MonthOf(aInputData.DirectGetItem_DataDateTime(i))) or (aCurrentYear<>YearOf(aInputData.DirectGetItem_DataDateTime(i))) or (i=aInputData.Count-1) then begin if aCurrentMonth<>-1 then begin if aCount=0 then begin chIntradayValue.AddXY(EncodeDate(aCurrentYear,aCurrentMonth,1),0); end else begin chMonthVolatilityValue.AddXY(EncodeDate(aCurrentYear,aCurrentMonth,1),aValue/aCount); end; end; aCurrentMonth:=MonthOf(aInputData.DirectGetItem_DataDateTime(i)); aCurrentYear:=YearOf(aInputData.DirectGetItem_DataDateTime(i)); aValue:=0; aCount:=0; end; if MinuteOfTheDay(aInputData.DirectGetItem_DataDateTime(i))=aMinute then begin aValue:=aValue+FIndicator.GetValue(i); inc(aCount); end; end; finally chMonthVolatility.AutoRepaint:=true; chMonthVolatility.Repaint; end; end; end; procedure TfmValueSupportStatisticsDialog.ckAllPeaksShowMarksClick(Sender: TObject); begin inherited; chAllPeaksValue.Marks.Visible:=ckAllPeaksShowMarks.Checked; end; procedure TfmValueSupportStatisticsDialog.ckHLClick(Sender: TObject); begin edValueTreshold.Enabled:=ckValueTreshold.Checked; edValueTresholdChange(nil); end; constructor TfmValueSupportStatisticsDialog.Create(const aStockChart: IStockChart); begin inherited; //edValueTreshold.ValueFloat:=Workspace.Storage(self).Read(edValueTreshold,'Value',0); RegisterPersistValue(ckValueTreshold,true); RegisterPersistValue(ckAllPeaksShowMarks,false); chIntradayValue.Clear; chMonthVolatilityValue.Clear; chAllPeaksValue.Clear; pcPages.ActivePageIndex:=0; pcPagesChange(nil); end; destructor TfmValueSupportStatisticsDialog.Destroy; begin //Workspace.Storage(self).WriteInteger(edHL,'Value',edHL.Value); inherited; end; procedure TfmValueSupportStatisticsDialog.Init(const aIndicator: ISCIndicatorValueSupport); begin FIndicator:=aIndicator; Caption:=IndicatorFactory.GetIndicatorInfo((FIndicator as ISCIndicator).GetIID).Name+': '+Caption; pcPagesChange(nil); end; procedure TfmValueSupportStatisticsDialog.edValueTresholdChange(Sender: TObject); begin inherited; if Visible then CalculateAllPeaks; end; procedure TfmValueSupportStatisticsDialog.grReportChangeRecord(Sender: TObject); begin if FCalculating>0 then exit; CalculateWeekDayStatistics( taReportTime.Value, taReportTime.Value+(StockChart.StockSymbol.GetTimeIntervalValue/MinsPerDay)-1/SecsPerDay); end; procedure TfmValueSupportStatisticsDialog.pcPagesChange(Sender: TObject); begin inherited; if not Visible then exit; if pcPages.ActivePage=tsIntradays then begin laHelp.Caption:='This page shows bar''s intraday volatility and it''s dependency from the day of the week'; if (pcPages.ActivePage.Tag=0) then CalculateIntradays; pcPages.ActivePage.Tag:=1; end else if pcPages.ActivePage=tsMonthVolatility then begin laHelp.Caption:='This page shows how the selected bar''s volatility changes from month to month'; if (pcPages.ActivePage.Tag=0) then CaclulateMonthVolatility; pcPages.ActivePage.Tag:=1; end else if pcPages.ActivePage=tsAllPeaks then begin laHelp.Caption:='This page shows all peaks that meet the conditions'; if (pcPages.ActivePage.Tag=0) then CalculateAllPeaks; pcPages.ActivePage.Tag:=1; end; end; class procedure TfmValueSupportStatisticsDialog.Run(const aIndicator: ISCIndicatorValueSupport; const aStockChart: IStockChart); begin with TfmValueSupportStatisticsDialog.Create(aStockChart) do begin Init(aIndicator); Show; pcPagesChange(nil); end; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Bindings.CustomScope; interface uses System.Rtti, System.Bindings.EvalProtocol, System.Bindings.EvalSys; type TScopeClass = class of TCustomScope; TCustomScope = class abstract(TInterfacedObject, IScope, ICustomScope) type TWrapperFoundCallback = reference to procedure (Scope: TCustomScope; const Wrapper: ICustomWrapper); private FCache: TDictionaryScope; FMappedObject: TObject; FMetaClass: TClass; FWrapperFoundCallback: TWrapperFoundCallback; protected { ICustomScope } function GetMappedObject: TObject; function GetMetaClass: TClass; procedure SetMappedObject(const Value: TObject); // the user has to provide the returning of a custom wrapper that will // be used by the engine to parse the expression and evaluate it; // this method is called only once for each different symbol that is // not found on the internal cache function DoLookup(const Name: String): IInterface; virtual; abstract; public constructor Create(const MappedObject: TObject; MetaClass: TClass); virtual; destructor Destroy; override; { ICustomScope } // called by the engine whenever it needs a custom wrapper for the given symbol; // if the wrapper is found on the internal cache, it returns the reference // from there; if it's not on the cache, it calls DoLookup() provided by the user; function Lookup(const Name: string): IInterface; property MappedObject: TObject read GetMappedObject write SetMappedObject; property MetaClass: TClass read GetMetaClass; // named DoWrapperUpdate() that the user must override to synchronize the // custom wrappers information with the information on the scope (i.e. the object // on which the custom scope is created may be nil after it hasn't been nil // at some point and this must be reflected also in the contents of the custom wrapper). // In fact, the step of updating the ParentObject in the custom wrapper can be // The event could still remain along this DoWrapperUpdate(). // triggered when the wrapper is found either in the internal scope cache // or after it is given by the user from DoLookup; it represents the step // of adjustments for the settings in the custom wrapper before returning // to the engine processings property OnWrapperFound: TWrapperFoundCallback read FWrapperFoundCallback write FWrapperFoundCallback; end; implementation { TCustomScope } constructor TCustomScope.Create(const MappedObject: TObject; MetaClass: TClass); begin inherited Create; FCache := TDictionaryScope.Create; FMappedObject := MappedObject; FMetaClass := MetaClass; end; destructor TCustomScope.Destroy; begin FCache.Free; inherited; end; function TCustomScope.GetMappedObject: TObject; begin Result := FMappedObject; end; function TCustomScope.GetMetaClass: TClass; begin Result := FMetaClass; end; function TCustomScope.Lookup(const Name: string): IInterface; begin // search the internal structure for the cached custom wrapper Result := FCache.Lookup(Name); // request the custom wrapper from the user routine if not Assigned(Result) then begin Result := DoLookup(Name); // a custom wrapper has been created for the symbol; add it to the cache if Assigned(Result) then FCache.Map.Add(Name, Result); end; if Assigned(Result) and Assigned(OnWrapperFound) then OnWrapperFound(Self, ICustomWrapper(Result)); end; procedure TCustomScope.SetMappedObject(const Value: TObject); begin FMappedObject := Value; end; end.
unit CmdLineParameters; interface uses Classes; procedure Initialize; function ParamAsString(name : String; isRequired : Boolean = false; sDefault : String = '') : String; function ParamAsInteger(name : String; isRequired : Boolean = false; sDefault : String = '') : Integer; function ParamAsBoolean(name : String; isRequired : Boolean = false; sDefault : string = 'false') : boolean; function ParamExists(name : String) : boolean; var params : TStringList = nil; implementation uses SysUtils, StrUtils; // Gets params from switchs, both unary and binary // All params start with '-' or '/' // Unary parameters are simply flags (e.g. a boolean setting, where existence means true) // Binary parameters start with a param, followed by a space, followed by the param value // for instance /path "c:\test" procedure Initialize; //GetParams(params : TStringList); var i : Integer; firstChar : String; begin params := TStringList.Create; for i := 1 to ParamCount do begin firstChar := LeftStr(ParamStr(i), 1); if (firstChar = '/') or (firstChar = '-') then params.Add(ParamStr(i)) else begin // This is assumed to be the value of a binary parameter if i > 0 then begin params.Values[params[params.Count - 1]] := ParamStr(i); end; end; end; end; function ParamAsString(name : String; isRequired : Boolean = false; sDefault : String = '') : String; var sVal : String; begin sVal := params.Values[name]; if sVal = '' then sVal := sDefault; if (sVal = '') and (isRequired) then raise Exception.Create('Missing parameter ' + name) else begin Result := sVal; end; end; function ParamAsInteger(name : String; isRequired : Boolean = false; sDefault : String = '') : Integer; var sVal : String; retVal : Integer; begin sVal := params.Values[name]; if sVal = '' then sVal := sDefault; if (sVal = '') and (isRequired) then raise Exception.Create('Missing parameter ' + name) else begin if TryStrToInt(sVal, retVal) then Result := retVal else raise Exception.Create('Invalid integer value for parameter ' + name); end; end; function ParamAsBoolean(name : String; isRequired : Boolean = false; sDefault : string = 'false') : boolean; var sVal : String; retVal : boolean; begin sVal := params.Values[name]; if sVal = '' then sVal := sDefault; if (sVal = '') and (isRequired) then raise Exception.Create('Missing parameter ' + name) else begin if TryStrToBool(sVal, retVal) then Result := retVal else raise Exception.Create('Invalid boolean value for parameter ' + name); end; end; function ParamExists(name : String) : boolean; begin Result := params.IndexOf(name) >= 0; end; end.
unit uControls; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls, StdCtrls, ComCtrls, u_xpl_sender; type { TxPLActionPanel } TxPLActionPanel = class(TPanel) private fImage : TImage; fName : TLabel; fStatus : TLabel; fAct1 : TButton; fAct2 : TButton; fxPLMessage : string; procedure ActClick(aSender : TObject); public xPLSender : TxPLSender; constructor create(aOwner : TComponent); override; published property xPLMessage : string read fxPLMessage write fxPLMessage; end; { TxPLTimePanel } TxPLTimePanel = class(TPanel) private fTrack: TTrackBar; fAct1 : TButton; fAct2 : TButton; fPanel : TPanel; fName : TLabel; procedure ActClick(aSender : TObject); function GetTime: TDateTime; procedure SetTime(const AValue: TDateTime); procedure TrackChange({%H-}aSender : TObject); public constructor create(aOwner : TComponent); override; property time : TDateTime read GetTime write SetTime; end; procedure Register; implementation { TActionPanel } uses Controls,StrUtils; procedure TxPLActionPanel.ActClick(aSender: TObject); var s : string; begin s := AnsiReplaceText(xPLMessage,'%action%',TButton(aSender).Caption); xPLSender.SendMessage(s); end; constructor TxPLActionPanel.create(aOwner: TComponent); begin inherited create(aOwner); BevelOuter := bvLowered; Caption := ''; Width := 200; fImage := TImage.Create(self); fImage.Parent := Self; fImage.Height := 48; fImage.Width := 48; fImage.Align := alLeft; fName := TLabel.Create(self); fName.Parent := self; fName.Left := 50; fName.Top := 10; fName.Caption := 'Name'; fName.Font.Bold := true; fStatus:= TLabel.Create(self); fStatus.Parent := self; fStatus.Left:=50; fStatus.Top := 30; fStatus.Caption:='Status'; fAct1 := TButton.Create(self); fAct1.Parent := self; fAct1.Align := alRight; fAct1.Width := 48; fAct1.Caption:='Off'; fAct1.OnClick:= @ActClick; fAct2 := TButton.Create(self); fAct2.Parent := self; fAct2.Align := alRight; fAct2.Width := 48; fAct2.Caption:='On'; fAct2.OnClick := @ActClick; end; { TxPLTimePanel } constructor TxPLTimePanel.create(aOwner: TComponent); begin inherited create(aOwner); BevelOuter := bvLowered; fAct1 := TButton.Create(self); fAct1.Parent := self; fAct1.Align := alLeft; fAct1.Width := 20; fAct1.Caption:='<'; fAct1.OnClick:= @ActClick; fAct2 := TButton.Create(self); fAct2.Parent := self; fAct2.Align := alRight; fAct2.Width := fAct1.Width; fAct2.Caption:='>'; fAct2.OnClick := @ActClick; fPanel := TPanel.Create(self); fPanel.Parent := self; fPanel.Align := alClient; fTrack := TTrackBar.Create(self); fTrack.Parent := fPanel; fTrack.Align := alTop; fTrack.Frequency := 3600; fTrack.PageSize := fTrack.Frequency; fTrack.Max := 86400; fTrack.Position := 0; fTrack.TickMarks := tmTopLeft; fTrack.OnChange := @TrackChange; fName := TLabel.Create(self); fName.Parent := fPanel; fName.Align := alBottom; fName.Caption := 'Name'; fName.Alignment := taCenter; end; procedure TxPLTimePanel.ActClick(aSender: TObject); var i : integer; begin if aSender = fAct1 then i:=-1 else i:=+1; fTrack.Position := fTrack.position + (i*60); TrackChange(asender); end; function TxPLTimePanel.GetTime: TDateTime; begin result := StrToTime(fName.Caption); end; procedure TxPLTimePanel.SetTime(const AValue: TDateTime); var Hour, Minute, Second, MilliSecond : word; begin DecodeTime(aValue,Hour,Minute,Second,Millisecond); fTrack.position := Hour * 3600 + Minute * 60; TrackChange(nil); end; procedure TxPLTimePanel.TrackChange(aSender: TObject); var h, m : integer; reste : integer; begin h := fTrack.Position div 3600; if h > 23 then h := 23; reste := fTrack.position - (h * 3600); m := reste div 60; if m > 59 then m := 59; fName.Caption := FormatDateTime('hh:nn',EncodeTime(h,m,0,0)); end; procedure Register; begin RegisterComponents('xPL Components',[TxPLActionPanel, TxPLTimePanel]); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; ListView1: TListView; btnProses: TButton; procedure FormCreate(Sender: TObject); procedure btnProsesClick(Sender: TObject); private { Private declarations } procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings); procedure InsertListView(AString: string); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} {------------------------------------------------------------------------------- Procedure: TForm1.FormCreate Author: BENK DateTime: 2021.06.22 11:03:28 -------------------------------------------------------------------------------} procedure TForm1.FormCreate(Sender: TObject); begin //Memo1.Lines.Clear; ListView1.Items.Clear; end; {------------------------------------------------------------------------------- Procedure: TForm1.btnProsesClick Author: BENK DateTime: 2021.06.22 11:03:31 -------------------------------------------------------------------------------} procedure TForm1.btnProsesClick(Sender: TObject); var i: Integer; begin for i := 0 to Memo1.Lines.Count - 1 do InsertListView(Memo1.Lines[i]); end; {------------------------------------------------------------------------------- Procedure: TForm1.InsertListView Author: BENK DateTime: 2021.06.22 11:02:20 -------------------------------------------------------------------------------} procedure TForm1.InsertListView(AString: string); var OutPutList: TStringList; i: Integer; Item: TListItem; begin OutPutList := TStringList.Create; try Split(',', AString, OutPutList); for i := 0 to OutPutList.Count - 1 do begin with ListView1 do begin if i = 0 then begin Item := ListView1.Items.Add; Item.Caption := OutPutList[i]; end else Item.SubItems.Add(OutPutList[i]); end; end; finally OutPutList.Free; end; end; {------------------------------------------------------------------------------- Procedure: TForm1.Split Author: BENK DateTime: 2021.06.22 11:03:12 -------------------------------------------------------------------------------} procedure TForm1.Split(Delimiter: Char; Str: string; ListOfStrings: TStrings); begin ListOfStrings.Clear; ListOfStrings.Delimiter := Delimiter; ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer. ListOfStrings.DelimitedText := Str; end; end.
unit uTestuDrawingPage; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Windows, uGraphicPrimitive, GdiPlus, SysUtils, Graphics, uBase, uDrawingPage; type // Test methods for class TDrawingPage TestTDrawingPage = class(TTestCase) strict private FDrawingPage: TDrawingPage; public procedure SetUp; override; procedure TearDown; override; private procedure CreateManyPrimitives( var aLastPrim : TGraphicPrimitive ); published procedure TestNewSize; procedure TestGetBitmap; procedure TestBackgroundPrimitive; procedure TestGetPrimitiveByCoord; procedure TestGetPrimitiveByID; procedure TestSelect; procedure TestAddPrimitive; end; implementation procedure TestTDrawingPage.CreateManyPrimitives( var aLastPrim: TGraphicPrimitive); var i : integer; begin for I := 0 to 100 do begin aLastPrim := TGraphicPrimitive.Create( FDrawingPage.RootPrimitive ); end; end; procedure TestTDrawingPage.SetUp; begin FDrawingPage := TDrawingPage.Create; end; procedure TestTDrawingPage.TearDown; begin FDrawingPage.Free; FDrawingPage := nil; end; procedure TestTDrawingPage.TestNewSize; var L, H : integer; begin L := 0; H := 100000; FDrawingPage.NewSize( H, L ); FDrawingPage.NewSize( L, H ); end; procedure TestTDrawingPage.TestSelect; begin Check( FDrawingPage.SelectPrimitive <> nil ); Check( FDrawingPage.SelectPrimitive is TSelect ); end; procedure TestTDrawingPage.TestAddPrimitive; var pt : TPrimitiveType; ok : boolean; begin for pt := TPrimitiveType.ptBox to High( TPrimitiveType ) do begin FDrawingPage.AddPrimitive( 10, 10, pt ); end; ok := false; try FDrawingPage.AddPrimitive( 10, 10, ptNone ); except ok := true; end; Check( ok ); end; procedure TestTDrawingPage.TestBackgroundPrimitive; begin Check( FDrawingPage.RootPrimitive <> nil ); end; procedure TestTDrawingPage.TestGetBitmap; var ReturnValue: TBitmap; begin FDrawingPage.NewSize( 0, 10000 ); ReturnValue := FDrawingPage.GetBitmap; Check( ReturnValue <> nil ); end; procedure TestTDrawingPage.TestGetPrimitiveByCoord; var i : integer; begin FDrawingPage.NewSize( 100, 100 ); FDrawingPage.GetBitmap; for I := 4 to 50 do begin Check( FDrawingPage.RootPrimitive = FDrawingPage.GetPrimitiveByCoord( 10, i ) ); end; end; procedure TestTDrawingPage.TestGetPrimitiveByID; var Prim, LastPrim : TGraphicPrimitive; id : string; begin LastPrim := nil; CreateManyPrimitives( LastPrim ); Prim := TGraphicPrimitive.Create( LastPrim ); CreateManyPrimitives( LastPrim ); id := Prim.IDAsStr; Check( Prim = FDrawingPage.GetPrimitiveByID( id ) ); Prim := TGraphicPrimitive.Create( FDrawingPage.RootPrimitive ); id := Prim.IDAsStr; Check( Prim = FDrawingPage.GetPrimitiveByID( id ) ); end; initialization // Register any test cases with the test runner RegisterTest(TestTDrawingPage.Suite); end.
unit typeid_1; interface implementation var id: TDataTypeID; procedure Test; begin id := typeid(id); end; initialization Test(); finalization Assert(id = dtEnum); end.
unit AdminMainForm; interface uses NewMemberForm, DAOMember, ResultForm, EstimateForm, LTClasses, Generics.collections, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, BaseGrid, AdvGrid; type TfrAdminMain = class(TLTForm) btEstimateView: TButton; btResultView: TButton; Label3: TLabel; AdvStringGrid1: TAdvStringGrid; btSearch: TButton; edSearch: TEdit; btNew: TButton; btModify: TButton; btDelete: TButton; procedure btEstimateViewClick(Sender: TObject); procedure btResultViewClick(Sender: TObject); procedure PrintMemberlist(Userlist : TObjectlist<TUser>); procedure btSearchClick(Sender: TObject); procedure btNewClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private EstimateForm : TFrEstimate; ResultForm : TFrResult; Userlist : TObjectlist<TUser>; FDAOMember : TDAOmember; { Private declarations } public { Public declarations } destructor Destroy; override; end; var frAdminMain: TfrAdminMain; implementation {$R *.dfm} procedure TfrAdminMain.btEstimateViewClick(Sender: TObject); begin frEstimate := TfrEstimate.Create(self); frEstimate.Parent := self; frEstimate.Show; end; procedure TfrAdminMain.btNewClick(Sender: TObject); begin frNewMember := TfrNewMember.Create(self); frNewMember.Show; end; procedure TfrAdminMain.btResultViewClick(Sender: TObject); begin frResult := TfrResult.Create(self); frResult.Parent := self; frResult.Show; end; procedure TfrAdminMain.btSearchClick(Sender: TObject); var SearchUser : TObjectlist<TUser>; begin PrintMemberlist(Fdaomember.SearchMember(edSearch.text)); end; destructor TfrAdminMain.Destroy; begin userlist.free; inherited; end; procedure TfrAdminMain.FormCreate(Sender: TObject); begin FDAOMember := TDAOMember.Create; PrintMemberlist(Fdaomember.GetAllMember); end; procedure TfrAdminMain.FormDestroy(Sender: TObject); begin FDAOMember.Free; end; procedure TfrAdminMain.PrintMemberlist(Userlist : TObjectlist<TUser>); var i : integer; begin for I := 0 to userlist.Count - 1 do begin AdvStringGrid1.Cells[0,i+1] := inttostr(i+1); AdvStringGrid1.Cells[1,i+1] := userlist.Items[i].UserId; AdvStringGrid1.Cells[2,i+1] := userlist.Items[i].UserPassword; AdvStringGrid1.Cells[3,i+1] := userlist.Items[i].Name; // AdvStringGrid1.Cells[i,4] := userlist.Items[i].Academy; AdvStringGrid1.Cells[4,i+1] := userlist.Items[i].TeacherId; end; AdvStringGrid1.Refresh; AdvStringGrid1.AutoSize := true; // userlist.Clear; userlist.Free; end; end.
(* * This code was generated by the TaskGen tool from file * "DCCTask.xml" * Version: 16.0.0.0 * Runtime Version: v2.0.50727 * Changes to this file may cause incorrect behavior and will be * overwritten when the code is regenerated. *) unit DCCStrs; interface const sTaskName = 'dcc'; // Compiling sOptimize = 'DCC_Optimize'; sGenerateStackFrames = 'DCC_GenerateStackFrames'; sInlining = 'DCC_Inlining'; sInlining_on = 'on'; sInlining_off = 'off'; sInlining_auto = 'auto'; sStringChecks = 'DCC_StringChecks'; sStringChecks_on = 'on'; sStringChecks_off = 'off'; sPentiumSafeDivide = 'DCC_PentiumSafeDivide'; sAlignment = 'DCC_Alignment'; sAlignment_0 = '0'; sAlignment_1 = '1'; sAlignment_2 = '2'; sAlignment_4 = '4'; sAlignment_8 = '8'; sCodePage = 'DCC_CodePage'; sMinimumEnumSize = 'DCC_MinimumEnumSize'; sMinimumEnumSize_1 = '1'; sMinimumEnumSize_2 = '2'; sMinimumEnumSize_4 = '4'; sRunTimeTypeInfo = 'DCC_RunTimeTypeInfo'; sStrictVarStrings = 'DCC_StrictVarStrings'; sFullBooleanEvaluations = 'DCC_FullBooleanEvaluations'; sExtendedSyntax = 'DCC_ExtendedSyntax'; sTypedAtParameter = 'DCC_TypedAtParameter'; sOpenStringParams = 'DCC_OpenStringParams'; sLongStrings = 'DCC_LongStrings'; sWriteableConstants = 'DCC_WriteableConstants'; sRangeChecking = 'DCC_RangeChecking'; sIOChecking = 'DCC_IOChecking'; sIntegerOverflowCheck = 'DCC_IntegerOverflowCheck'; sDebugInformation = 'DCC_DebugInformation'; sLocalDebugSymbols = 'DCC_LocalDebugSymbols'; sAssertionsAtRuntime = 'DCC_AssertionsAtRuntime'; sSymbolReferenceInfo = 'DCC_SymbolReferenceInfo'; sSymbolReferenceInfo_0 = '0'; sSymbolReferenceInfo_1 = '1'; sSymbolReferenceInfo_2 = '2'; sImportedDataReferences = 'DCC_ImportedDataReferences'; sDebugDCUs = 'DCC_DebugDCUs'; sUsePackage = 'DCC_UsePackage'; sAdditionalSwitches = 'DCC_AdditionalSwitches'; sOutputXMLDocumentation = 'DCC_OutputXMLDocumentation'; sOutputDependencies = 'DCC_OutputDependencies'; sNoConfig = 'DCC_NoConfig'; sUnsafeCode = 'DCC_UnsafeCode'; sOldDosFileNames = 'DCC_OldDosFileNames'; sBuildAllUnits = 'DCC_BuildAllUnits'; sFindError = 'DCC_FindError'; sMakeModifiedUnits = 'DCC_MakeModifiedUnits'; sQuiet = 'DCC_Quiet'; sOutputNeverBuildDcps = 'DCC_OutputNeverBuildDcps'; sSignAssembly = 'DCC_SignAssembly'; sDelaySign = 'DCC_DelaySign'; sKeyFile = 'DCC_KeyFile'; sKeyContainer = 'DCC_KeyContainer'; sClearUnitCache = 'DCC_ClearUnitCache'; sOutputExt = 'DCC_OutputExt'; // DCCDirectoriesAndConditionals sUnitAlias = 'DCC_UnitAlias'; sDefine = 'DCC_Define'; sExeOutput = 'DCC_ExeOutput'; sIncludePath = 'DCC_IncludePath'; sBplOutput = 'DCC_BplOutput'; sDcpOutput = 'DCC_DcpOutput'; sDcuOutput = 'DCC_DcuOutput'; sNamespace = 'DCC_Namespace'; sObjPath = 'DCC_ObjPath'; sResourcePath = 'DCC_ResourcePath'; sUnitSearchPath = 'DCC_UnitSearchPath'; sDefaultNamespace = 'DCC_DefaultNamespace'; // DCCLinking sConsoleTarget = 'DCC_ConsoleTarget'; sDebugInfoInExe = 'DCC_DebugInfoInExe'; sDebugInfoInTds = 'DCC_DebugInfoInTds'; sRemoteDebug = 'DCC_RemoteDebug'; sStackSize = 'DCC_StackSize'; sMinStackSize = 'DCC_MinStackSize'; sMaxStackSize = 'DCC_MaxStackSize'; sImageBase = 'DCC_ImageBase'; sDescription = 'DCC_Description'; sProgramExt = 'DCC_ProgramExt'; sMapFile = 'DCC_MapFile'; sMapFile_0 = '0'; sMapFile_1 = '1'; sMapFile_2 = '2'; sMapFile_3 = '3'; sOutputDRCFile = 'DCC_OutputDRCFile'; sBaseAddress = 'DCC_BaseAddress'; sPEFlags = 'DCC_PEFlags'; sPEOptFlags = 'DCC_PEOptFlags'; sPEOSVersion = 'DCC_PEOSVersion'; sPESubSysVersion = 'DCC_PESubSysVersion'; sPEUserVersion = 'DCC_PEUserVersion'; // DCCCppOutput sCBuilderOutput = 'DCC_CBuilderOutput'; sCBuilderOutput_None = 'None'; sCBuilderOutput_J = 'J'; sCBuilderOutput_JP = 'JP'; sCBuilderOutput_JPH = 'JPH'; sCBuilderOutput_JPHN = 'JPHN'; sCBuilderOutput_JPHNE = 'JPHNE'; sCBuilderOutput_JPN = 'JPN'; sCBuilderOutput_JPNE = 'JPNE'; sCBuilderOutput_JPHE = 'JPHE'; sCBuilderOutput_JPE = 'JPE'; sCBuilderOutput_All = 'All'; sLegacyCppHeaders = 'DCC_LegacyCppHeaders'; sBpiOutput = 'DCC_BpiOutput'; sHppOutput = 'DCC_HppOutput'; sObjOutput = 'DCC_ObjOutput'; // DCCHintsAndWarnings sHints = 'DCC_Hints'; sWarnings = 'DCC_Warnings'; sWarnings_true = 'true'; sWarnings_false = 'false'; sWarnings_error = 'error'; sSYMBOL_DEPRECATED = 'DCC_SYMBOL_DEPRECATED'; sSYMBOL_DEPRECATED_true = 'true'; sSYMBOL_DEPRECATED_false = 'false'; sSYMBOL_DEPRECATED_error = 'error'; sSYMBOL_LIBRARY = 'DCC_SYMBOL_LIBRARY'; sSYMBOL_LIBRARY_true = 'true'; sSYMBOL_LIBRARY_false = 'false'; sSYMBOL_LIBRARY_error = 'error'; sSYMBOL_PLATFORM = 'DCC_SYMBOL_PLATFORM'; sSYMBOL_PLATFORM_true = 'true'; sSYMBOL_PLATFORM_false = 'false'; sSYMBOL_PLATFORM_error = 'error'; sSYMBOL_EXPERIMENTAL = 'DCC_SYMBOL_EXPERIMENTAL'; sSYMBOL_EXPERIMENTAL_true = 'true'; sSYMBOL_EXPERIMENTAL_false = 'false'; sSYMBOL_EXPERIMENTAL_error = 'error'; sUNIT_LIBRARY = 'DCC_UNIT_LIBRARY'; sUNIT_LIBRARY_true = 'true'; sUNIT_LIBRARY_false = 'false'; sUNIT_LIBRARY_error = 'error'; sUNIT_PLATFORM = 'DCC_UNIT_PLATFORM'; sUNIT_PLATFORM_true = 'true'; sUNIT_PLATFORM_false = 'false'; sUNIT_PLATFORM_error = 'error'; sUNIT_DEPRECATED = 'DCC_UNIT_DEPRECATED'; sUNIT_DEPRECATED_true = 'true'; sUNIT_DEPRECATED_false = 'false'; sUNIT_DEPRECATED_error = 'error'; sUNIT_EXPERIMENTAL = 'DCC_UNIT_EXPERIMENTAL'; sUNIT_EXPERIMENTAL_true = 'true'; sUNIT_EXPERIMENTAL_false = 'false'; sUNIT_EXPERIMENTAL_error = 'error'; sHRESULT_COMPAT = 'DCC_HRESULT_COMPAT'; sHRESULT_COMPAT_true = 'true'; sHRESULT_COMPAT_false = 'false'; sHRESULT_COMPAT_error = 'error'; sHIDING_MEMBER = 'DCC_HIDING_MEMBER'; sHIDING_MEMBER_true = 'true'; sHIDING_MEMBER_false = 'false'; sHIDING_MEMBER_error = 'error'; sHIDDEN_VIRTUAL = 'DCC_HIDDEN_VIRTUAL'; sHIDDEN_VIRTUAL_true = 'true'; sHIDDEN_VIRTUAL_false = 'false'; sHIDDEN_VIRTUAL_error = 'error'; sGARBAGE = 'DCC_GARBAGE'; sGARBAGE_true = 'true'; sGARBAGE_false = 'false'; sGARBAGE_error = 'error'; sBOUNDS_ERROR = 'DCC_BOUNDS_ERROR'; sBOUNDS_ERROR_true = 'true'; sBOUNDS_ERROR_false = 'false'; sBOUNDS_ERROR_error = 'error'; sZERO_NIL_COMPAT = 'DCC_ZERO_NIL_COMPAT'; sZERO_NIL_COMPAT_true = 'true'; sZERO_NIL_COMPAT_false = 'false'; sZERO_NIL_COMPAT_error = 'error'; sSTRING_CONST_TRUNCED = 'DCC_STRING_CONST_TRUNCED'; sSTRING_CONST_TRUNCED_true = 'true'; sSTRING_CONST_TRUNCED_false = 'false'; sSTRING_CONST_TRUNCED_error = 'error'; sFOR_LOOP_VAR_VARPAR = 'DCC_FOR_LOOP_VAR_VARPAR'; sFOR_LOOP_VAR_VARPAR_true = 'true'; sFOR_LOOP_VAR_VARPAR_false = 'false'; sFOR_LOOP_VAR_VARPAR_error = 'error'; sTYPED_CONST_VARPAR = 'DCC_TYPED_CONST_VARPAR'; sTYPED_CONST_VARPAR_true = 'true'; sTYPED_CONST_VARPAR_false = 'false'; sTYPED_CONST_VARPAR_error = 'error'; sASG_TO_TYPED_CONST = 'DCC_ASG_TO_TYPED_CONST'; sASG_TO_TYPED_CONST_true = 'true'; sASG_TO_TYPED_CONST_false = 'false'; sASG_TO_TYPED_CONST_error = 'error'; sCASE_LABEL_RANGE = 'DCC_CASE_LABEL_RANGE'; sCASE_LABEL_RANGE_true = 'true'; sCASE_LABEL_RANGE_false = 'false'; sCASE_LABEL_RANGE_error = 'error'; sFOR_VARIABLE = 'DCC_FOR_VARIABLE'; sFOR_VARIABLE_true = 'true'; sFOR_VARIABLE_false = 'false'; sFOR_VARIABLE_error = 'error'; sCONSTRUCTING_ABSTRACT = 'DCC_CONSTRUCTING_ABSTRACT'; sCONSTRUCTING_ABSTRACT_true = 'true'; sCONSTRUCTING_ABSTRACT_false = 'false'; sCONSTRUCTING_ABSTRACT_error = 'error'; sCOMPARISON_FALSE = 'DCC_COMPARISON_FALSE'; sCOMPARISON_FALSE_true = 'true'; sCOMPARISON_FALSE_false = 'false'; sCOMPARISON_FALSE_error = 'error'; sCOMPARISON_TRUE = 'DCC_COMPARISON_TRUE'; sCOMPARISON_TRUE_true = 'true'; sCOMPARISON_TRUE_false = 'false'; sCOMPARISON_TRUE_error = 'error'; sCOMPARING_SIGNED_UNSIGNED = 'DCC_COMPARING_SIGNED_UNSIGNED'; sCOMPARING_SIGNED_UNSIGNED_true = 'true'; sCOMPARING_SIGNED_UNSIGNED_false = 'false'; sCOMPARING_SIGNED_UNSIGNED_error = 'error'; sCOMBINING_SIGNED_UNSIGNED = 'DCC_COMBINING_SIGNED_UNSIGNED'; sCOMBINING_SIGNED_UNSIGNED_true = 'true'; sCOMBINING_SIGNED_UNSIGNED_false = 'false'; sCOMBINING_SIGNED_UNSIGNED_error = 'error'; sUNSUPPORTED_CONSTRUCT = 'DCC_UNSUPPORTED_CONSTRUCT'; sUNSUPPORTED_CONSTRUCT_true = 'true'; sUNSUPPORTED_CONSTRUCT_false = 'false'; sUNSUPPORTED_CONSTRUCT_error = 'error'; sFILE_OPEN = 'DCC_FILE_OPEN'; sFILE_OPEN_true = 'true'; sFILE_OPEN_false = 'false'; sFILE_OPEN_error = 'error'; sFILE_OPEN_UNITSRC = 'DCC_FILE_OPEN_UNITSRC'; sFILE_OPEN_UNITSRC_true = 'true'; sFILE_OPEN_UNITSRC_false = 'false'; sFILE_OPEN_UNITSRC_error = 'error'; sBAD_GLOBAL_SYMBOL = 'DCC_BAD_GLOBAL_SYMBOL'; sBAD_GLOBAL_SYMBOL_true = 'true'; sBAD_GLOBAL_SYMBOL_false = 'false'; sBAD_GLOBAL_SYMBOL_error = 'error'; sDUPLICATE_CTOR_DTOR = 'DCC_DUPLICATE_CTOR_DTOR'; sDUPLICATE_CTOR_DTOR_true = 'true'; sDUPLICATE_CTOR_DTOR_false = 'false'; sDUPLICATE_CTOR_DTOR_error = 'error'; sINVALID_DIRECTIVE = 'DCC_INVALID_DIRECTIVE'; sINVALID_DIRECTIVE_true = 'true'; sINVALID_DIRECTIVE_false = 'false'; sINVALID_DIRECTIVE_error = 'error'; sPACKAGE_NO_LINK = 'DCC_PACKAGE_NO_LINK'; sPACKAGE_NO_LINK_true = 'true'; sPACKAGE_NO_LINK_false = 'false'; sPACKAGE_NO_LINK_error = 'error'; sPACKAGED_THREADVAR = 'DCC_PACKAGED_THREADVAR'; sPACKAGED_THREADVAR_true = 'true'; sPACKAGED_THREADVAR_false = 'false'; sPACKAGED_THREADVAR_error = 'error'; sIMPLICIT_IMPORT = 'DCC_IMPLICIT_IMPORT'; sIMPLICIT_IMPORT_true = 'true'; sIMPLICIT_IMPORT_false = 'false'; sIMPLICIT_IMPORT_error = 'error'; sHPPEMIT_IGNORED = 'DCC_HPPEMIT_IGNORED'; sHPPEMIT_IGNORED_true = 'true'; sHPPEMIT_IGNORED_false = 'false'; sHPPEMIT_IGNORED_error = 'error'; sNO_RETVAL = 'DCC_NO_RETVAL'; sNO_RETVAL_true = 'true'; sNO_RETVAL_false = 'false'; sNO_RETVAL_error = 'error'; sUSE_BEFORE_DEF = 'DCC_USE_BEFORE_DEF'; sUSE_BEFORE_DEF_true = 'true'; sUSE_BEFORE_DEF_false = 'false'; sUSE_BEFORE_DEF_error = 'error'; sFOR_LOOP_VAR_UNDEF = 'DCC_FOR_LOOP_VAR_UNDEF'; sFOR_LOOP_VAR_UNDEF_true = 'true'; sFOR_LOOP_VAR_UNDEF_false = 'false'; sFOR_LOOP_VAR_UNDEF_error = 'error'; sUNIT_NAME_MISMATCH = 'DCC_UNIT_NAME_MISMATCH'; sUNIT_NAME_MISMATCH_true = 'true'; sUNIT_NAME_MISMATCH_false = 'false'; sUNIT_NAME_MISMATCH_error = 'error'; sNO_CFG_FILE_FOUND = 'DCC_NO_CFG_FILE_FOUND'; sNO_CFG_FILE_FOUND_true = 'true'; sNO_CFG_FILE_FOUND_false = 'false'; sNO_CFG_FILE_FOUND_error = 'error'; sIMPLICIT_VARIANTS = 'DCC_IMPLICIT_VARIANTS'; sIMPLICIT_VARIANTS_true = 'true'; sIMPLICIT_VARIANTS_false = 'false'; sIMPLICIT_VARIANTS_error = 'error'; sUNICODE_TO_LOCALE = 'DCC_UNICODE_TO_LOCALE'; sUNICODE_TO_LOCALE_true = 'true'; sUNICODE_TO_LOCALE_false = 'false'; sUNICODE_TO_LOCALE_error = 'error'; sLOCALE_TO_UNICODE = 'DCC_LOCALE_TO_UNICODE'; sLOCALE_TO_UNICODE_true = 'true'; sLOCALE_TO_UNICODE_false = 'false'; sLOCALE_TO_UNICODE_error = 'error'; sIMAGEBASE_MULTIPLE = 'DCC_IMAGEBASE_MULTIPLE'; sIMAGEBASE_MULTIPLE_true = 'true'; sIMAGEBASE_MULTIPLE_false = 'false'; sIMAGEBASE_MULTIPLE_error = 'error'; sSUSPICIOUS_TYPECAST = 'DCC_SUSPICIOUS_TYPECAST'; sSUSPICIOUS_TYPECAST_true = 'true'; sSUSPICIOUS_TYPECAST_false = 'false'; sSUSPICIOUS_TYPECAST_error = 'error'; sPRIVATE_PROPACCESSOR = 'DCC_PRIVATE_PROPACCESSOR'; sPRIVATE_PROPACCESSOR_true = 'true'; sPRIVATE_PROPACCESSOR_false = 'false'; sPRIVATE_PROPACCESSOR_error = 'error'; sUNSAFE_TYPE = 'DCC_UNSAFE_TYPE'; sUNSAFE_TYPE_true = 'true'; sUNSAFE_TYPE_false = 'false'; sUNSAFE_TYPE_error = 'error'; sUNSAFE_CODE = 'DCC_UNSAFE_CODE'; sUNSAFE_CODE_true = 'true'; sUNSAFE_CODE_false = 'false'; sUNSAFE_CODE_error = 'error'; sUNSAFE_CAST = 'DCC_UNSAFE_CAST'; sUNSAFE_CAST_true = 'true'; sUNSAFE_CAST_false = 'false'; sUNSAFE_CAST_error = 'error'; sOPTION_TRUNCATED = 'DCC_OPTION_TRUNCATED'; sOPTION_TRUNCATED_true = 'true'; sOPTION_TRUNCATED_false = 'false'; sOPTION_TRUNCATED_error = 'error'; sWIDECHAR_REDUCED = 'DCC_WIDECHAR_REDUCED'; sWIDECHAR_REDUCED_true = 'true'; sWIDECHAR_REDUCED_false = 'false'; sWIDECHAR_REDUCED_error = 'error'; sDUPLICATES_IGNORED = 'DCC_DUPLICATES_IGNORED'; sDUPLICATES_IGNORED_true = 'true'; sDUPLICATES_IGNORED_false = 'false'; sDUPLICATES_IGNORED_error = 'error'; sUNIT_INIT_SEQ = 'DCC_UNIT_INIT_SEQ'; sUNIT_INIT_SEQ_true = 'true'; sUNIT_INIT_SEQ_false = 'false'; sUNIT_INIT_SEQ_error = 'error'; sLOCAL_PINVOKE = 'DCC_LOCAL_PINVOKE'; sLOCAL_PINVOKE_true = 'true'; sLOCAL_PINVOKE_false = 'false'; sLOCAL_PINVOKE_error = 'error'; sMESSAGE_DIRECTIVE = 'DCC_MESSAGE_DIRECTIVE'; sMESSAGE_DIRECTIVE_true = 'true'; sMESSAGE_DIRECTIVE_false = 'false'; sMESSAGE_DIRECTIVE_error = 'error'; sTYPEINFO_IMPLICITLY_ADDED = 'DCC_TYPEINFO_IMPLICITLY_ADDED'; sTYPEINFO_IMPLICITLY_ADDED_true = 'true'; sTYPEINFO_IMPLICITLY_ADDED_false = 'false'; sTYPEINFO_IMPLICITLY_ADDED_error = 'error'; sRLINK_WARNING = 'DCC_RLINK_WARNING'; sRLINK_WARNING_true = 'true'; sRLINK_WARNING_false = 'false'; sRLINK_WARNING_error = 'error'; sIMPLICIT_STRING_CAST = 'DCC_IMPLICIT_STRING_CAST'; sIMPLICIT_STRING_CAST_true = 'true'; sIMPLICIT_STRING_CAST_false = 'false'; sIMPLICIT_STRING_CAST_error = 'error'; sIMPLICIT_STRING_CAST_LOSS = 'DCC_IMPLICIT_STRING_CAST_LOSS'; sIMPLICIT_STRING_CAST_LOSS_true = 'true'; sIMPLICIT_STRING_CAST_LOSS_false = 'false'; sIMPLICIT_STRING_CAST_LOSS_error = 'error'; sEXPLICIT_STRING_CAST = 'DCC_EXPLICIT_STRING_CAST'; sEXPLICIT_STRING_CAST_true = 'true'; sEXPLICIT_STRING_CAST_false = 'false'; sEXPLICIT_STRING_CAST_error = 'error'; sEXPLICIT_STRING_CAST_LOSS = 'DCC_EXPLICIT_STRING_CAST_LOSS'; sEXPLICIT_STRING_CAST_LOSS_true = 'true'; sEXPLICIT_STRING_CAST_LOSS_false = 'false'; sEXPLICIT_STRING_CAST_LOSS_error = 'error'; sCVT_WCHAR_TO_ACHAR = 'DCC_CVT_WCHAR_TO_ACHAR'; sCVT_WCHAR_TO_ACHAR_true = 'true'; sCVT_WCHAR_TO_ACHAR_false = 'false'; sCVT_WCHAR_TO_ACHAR_error = 'error'; sCVT_NARROWING_STRING_LOST = 'DCC_CVT_NARROWING_STRING_LOST'; sCVT_NARROWING_STRING_LOST_true = 'true'; sCVT_NARROWING_STRING_LOST_false = 'false'; sCVT_NARROWING_STRING_LOST_error = 'error'; sCVT_ACHAR_TO_WCHAR = 'DCC_CVT_ACHAR_TO_WCHAR'; sCVT_ACHAR_TO_WCHAR_true = 'true'; sCVT_ACHAR_TO_WCHAR_false = 'false'; sCVT_ACHAR_TO_WCHAR_error = 'error'; sCVT_WIDENING_STRING_LOST = 'DCC_CVT_WIDENING_STRING_LOST'; sCVT_WIDENING_STRING_LOST_true = 'true'; sCVT_WIDENING_STRING_LOST_false = 'false'; sCVT_WIDENING_STRING_LOST_error = 'error'; sNON_PORTABLE_TYPECAST = 'DCC_NON_PORTABLE_TYPECAST'; sNON_PORTABLE_TYPECAST_true = 'true'; sNON_PORTABLE_TYPECAST_false = 'false'; sNON_PORTABLE_TYPECAST_error = 'error'; sXML_WHITESPACE_NOT_ALLOWED = 'DCC_XML_WHITESPACE_NOT_ALLOWED'; sXML_WHITESPACE_NOT_ALLOWED_true = 'true'; sXML_WHITESPACE_NOT_ALLOWED_false = 'false'; sXML_WHITESPACE_NOT_ALLOWED_error = 'error'; sXML_UNKNOWN_ENTITY = 'DCC_XML_UNKNOWN_ENTITY'; sXML_UNKNOWN_ENTITY_true = 'true'; sXML_UNKNOWN_ENTITY_false = 'false'; sXML_UNKNOWN_ENTITY_error = 'error'; sXML_INVALID_NAME_START = 'DCC_XML_INVALID_NAME_START'; sXML_INVALID_NAME_START_true = 'true'; sXML_INVALID_NAME_START_false = 'false'; sXML_INVALID_NAME_START_error = 'error'; sXML_INVALID_NAME = 'DCC_XML_INVALID_NAME'; sXML_INVALID_NAME_true = 'true'; sXML_INVALID_NAME_false = 'false'; sXML_INVALID_NAME_error = 'error'; sXML_EXPECTED_CHARACTER = 'DCC_XML_EXPECTED_CHARACTER'; sXML_EXPECTED_CHARACTER_true = 'true'; sXML_EXPECTED_CHARACTER_false = 'false'; sXML_EXPECTED_CHARACTER_error = 'error'; sXML_CREF_NO_RESOLVE = 'DCC_XML_CREF_NO_RESOLVE'; sXML_CREF_NO_RESOLVE_true = 'true'; sXML_CREF_NO_RESOLVE_false = 'false'; sXML_CREF_NO_RESOLVE_error = 'error'; sXML_NO_PARM = 'DCC_XML_NO_PARM'; sXML_NO_PARM_true = 'true'; sXML_NO_PARM_false = 'false'; sXML_NO_PARM_error = 'error'; sXML_NO_MATCHING_PARM = 'DCC_XML_NO_MATCHING_PARM'; sXML_NO_MATCHING_PARM_true = 'true'; sXML_NO_MATCHING_PARM_false = 'false'; sXML_NO_MATCHING_PARM_error = 'error'; // Outputs sOutput_DcuFiles = 'DcuFiles'; sOutput_FinalOutput = 'FinalOutput'; sOutput_DcpFiles = 'DcpFiles'; sOutput_ObjFiles = 'ObjFiles'; sOutput_BpiFiles = 'BpiFiles'; sOutput_HppFiles = 'HppFiles'; implementation end.
program Z; uses graphABC; const H = 480; W = 600; winColor = clWhite; procedure Brush ( color: System.Drawing.Color; style: System.Drawing.Drawing2D.DashStyle; width: integer ); { Sets brush options } begin SetPenColor(color); SetPenStyle(style); SetPenWidth(width) end; procedure Parallelepiped ( X, Y, // Front-bottom-right corner coordinates sideX, sideY, sideZ, // The lengths of the sides outlineWidth: integer; color: System.Drawing.Color ); { Draws a parallelepiped with a 45 degree slant top and left } var V, Vx, Vy: integer; begin { Devide by 3 to make Y dimension volumetric } V := round(sideY / 3); { Back-bottom-right corner coordinates } Vx := X + V; Vy := Y - V; { The front side of the figure (draws clockwise) } Brush(color, psSolid, outlineWidth); line(X, Y, (X + sideX), Y); line(X, Y, X, (Y - sideZ)); line(X, (Y - sideZ), (X + sideX), (Y - sideZ)); line((X + sideX), Y, (X + sideX), (Y - sideZ)); { The invisible sides of the figure (draws clockwise) } Brush(color, psDash, outlineWidth); line(X, Y, Vx, Vy); line(Vx, Vy, Vx, (Vy - sideZ)); line(Vx, Vy, (Vx + sideX), Vy); { Finish painting the second square } Brush(color, psSolid, outlineWidth); line(Vx, (Vy - sideZ), (Vx + sideX), (Vy - sideZ)); line((Vx + sideX), Vy, (Vx + sideX), (Vy - sideZ)); { Establish a connection between squares to form a parallelepiped } line(X, (Y - sideZ), Vx, (Vy - sideZ)); line((X + sideX), Y, (Vx + sideX), Vy); line((X + sideX), (Y - sideZ), (Vx + sideX), (Vy - sideZ)); end; begin SetWindowSize(W, H); ClearWindow(winColor); Parallelepiped(100, 400, 150, 200, 300, 3, clBlack); end.
unit SDIMAIN; interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.Menus, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ImgList, Vcl.StdActns, Vcl.ActnList, Vcl.ToolWin, System.ImageList, System.Actions, Vcl.Samples.Spin, Vcl.Grids, SysUtils, Vcl.CheckLst, StrUtils, Vcl.DBActns; type TSDIAppForm = class(TForm) OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; ToolBar1: TToolBar; ActionList1: TActionList; FileNew1: TAction; FileOpen1: TAction; FileSave1: TAction; FileSaveAs1: TAction; FileExit1: TAction; EditCut1: TEditCut; EditCopy1: TEditCopy; EditPaste1: TEditPaste; HelpAbout1: TAction; StatusBar: TStatusBar; ImageList1: TImageList; MainMenu1: TMainMenu; File1: TMenuItem; FileNewItem: TMenuItem; FileOpenItem: TMenuItem; FileSaveItem: TMenuItem; FileSaveAsItem: TMenuItem; N1: TMenuItem; FileExitItem: TMenuItem; Edit1: TMenuItem; CutItem: TMenuItem; CopyItem: TMenuItem; PasteItem: TMenuItem; Help1: TMenuItem; HelpAboutItem: TMenuItem; PC: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Memo1: TMemo; TabSheet3: TTabSheet; DatasetInsert1: TDataSetInsert; ToolButton8: TToolButton; Memo2: TMemo; PopupMenu1: TPopupMenu; N2: TMenuItem; procedure FileNew1Execute(Sender: TObject); procedure FileOpen1Execute(Sender: TObject); procedure FileSave1Execute(Sender: TObject); procedure FileExit1Execute(Sender: TObject); procedure HelpAbout1Execute(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure CBLClickCheck(Sender: TObject); procedure ToolButton8Click(Sender: TObject); procedure PCContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure N2Click(Sender: TObject); private { Private declarations } FrmCnt:Integer; procedure NeedMakeProg(Sender: TObject); procedure InsertFrame(PageIndex:Integer); public { Public declarations } procedure MakeProg; end; var SDIAppForm: TSDIAppForm; implementation uses About, FontFrame; {$R *.dfm} procedure TSDIAppForm.FileNew1Execute(Sender: TObject); begin { Do nothing } end; procedure TSDIAppForm.FileOpen1Execute(Sender: TObject); begin OpenDialog.Execute; end; procedure TSDIAppForm.FileSave1Execute(Sender: TObject); begin SaveDialog.Execute; end; procedure TSDIAppForm.FormShow(Sender: TObject); begin PC.TabIndex:=0; InsertFrame(0); end; procedure TSDIAppForm.Button1Click(Sender: TObject); begin MakeProg; end; procedure TSDIAppForm.Button3Click(Sender: TObject); begin MakeProg; end; procedure TSDIAppForm.CBLClickCheck(Sender: TObject); begin MakeProg; end; procedure TSDIAppForm.FileExit1Execute(Sender: TObject); begin Close; end; procedure TSDIAppForm.HelpAbout1Execute(Sender: TObject); begin AboutBox.ShowModal; end; procedure TSDIAppForm.InsertFrame(PageIndex: Integer); var Frm:TFontFrm; begin Frm:=TFontFrm.Create(Self); FRM.Name:=Frm.Name+IntToStr(FrmCnt); FRM.Parent:=PC.Pages[PageIndex]; FRM.InitFont; FRM.OnNeedMakeProg:=NeedMakeProg; FrmCnt:=FrmCnt+1; end; procedure TSDIAppForm.MakeProg; var S,FntNm,Comment:String; p,a,x,y,m,size,FntNmL:Integer; b,bc,cnt:word; L:TLetter; LS,LI:TStrings; indexes:array [0..224] of word; // symbols:array [0..223] of integer; widths:array [0..223] of byte; ipoint:byte; CBL:TCheckListBox; Fnt:TFont; Frm:TFontFrm; begin memo1.Lines.Clear; memo1.Lines.Add('/**'); memo1.Lines.Add(' ******************************************************************************'); memo1.Lines.Add(' * @file : varyfonts.c'); memo1.Lines.Add(' * @brief : fonts descriptions for st7735 and ssd1306'); memo1.Lines.Add(' ******************************************************************************'); memo1.Lines.Add(' * @attention'); memo1.Lines.Add(' *'); memo1.Lines.Add(' * "Дом свободный, живите, кто хотите" (с) Простоквашино ))'); memo1.Lines.Add(' * '); memo1.Lines.Add(' * Created on: '+DateToStr(Now)); memo1.Lines.Add(' * Author: FontGenerator;'); memo1.Lines.Add(' ******************************************************************************'); memo1.Lines.Add(' */'); memo1.Lines.Add(''); memo1.Lines.Add('#include "varyfonts.h"'); memo1.Lines.Add('#include "string.h"'); memo1.Lines.Add(''); LS:=TStringList.Create; LI:=TStringList.Create; FntNmL:=0; try for p := 0 to PC.PageCount-1 do begin if PC.Pages[p].Tag=0 then begin LI.Clear; FRM:=TFontFrm(PC.Pages[p].Controls[0]); CBL:=Frm.CBL; FntNm:=FRM.FontName; FntNm:=ReplaceStr(FntNm,' ','_'); FntNm:=ReplaceStr(FntNm,',',''); if Length(FntNm)>FntNmL then FntNmL:=Length(FntNm); S:='static uint16_t Font_'+FntNm+' [] = {'; LS.Add(' {"'+FntNm+'", '+IntToStr(FRM.MaxH)+', VFontMetrics_'+FntNm+', Font_'+FntNM+'},'); // {"Tahoma_8",13,FontWidths_Tahoma_8,FontOffsets_Tahoma_8,Font_Tahoma_8}, // {"Tahoma_8_bold",13,FontWidths_Tahoma_8_bold,FontOffsets_Tahoma_8_bold,Font_Tahoma_8_bold}, Memo1.Lines.Add(S); ipoint:=0; indexes[0]:=0; indexes[1]:=0; //symbols[0]:=0; for a := 0 to CBL.Count-1 do begin widths[a]:=0; if CBL.Checked[a] then begin indexes[ipoint+1]:=indexes[ipoint]; L:=TLetter(FRM.List.objects[a]); widths[a]:=L.Width; S:=''; b:=0; bc:=32768; cnt:=0; for y := 0 to FRM.MaxH-1 do begin for x := 0 to L.Width-1 do begin if L.Matrix[x][y]=clBlack then b:=b + bc; bc:=Trunc(bc/2); if bc=0 then begin bc:=32768; S:=S+'0x'+IntToHex(b)+', '; b:=0; cnt:=cnt+1; // indexes[ipoint+1]:=indexes[ipoint+1]+1; end; end; end; if bc<>32768 then begin S:=S+'0x'+IntToHex(b)+', '; cnt:=cnt+1; // indexes[ipoint+1]:=indexes[ipoint+1]+1; end; indexes[ipoint+1]:=indexes[ipoint+1]+cnt; if a=0 then Comment:=' // '+IntToStr(a+32)+' sp' else if a=60 then Comment:=' /* '+IntToStr(a+32)+' \ */' else Comment:=' // '+IntToStr(a+32)+' '+AnsiChar(a+32); LI.Add(' {'+IntToStr(widths[a])+', '+IntToStr(cnt)+', '+IntToStr(indexes[ipoint])+'}, '+Comment); S:=S+Comment+' // offset '+IntToStr(Indexes[ipoint])+' 0x'+IntToHex(indexes[ipoint]); Memo1.Lines.Add(S); ipoint:=ipoint+1; end else begin //symbols[a]:=-1; LI.Add(' {0,0,0}, // no symbol'); end; end; Memo1.Lines.Add('};'); Memo1.Lines.Add(''); Memo1.Lines.Add('VLetterMetrics VFontMetrics_'+FntNm+'[]={'); Memo1.Lines.AddStrings(LI); memo1.Lines.Add('};'); Memo1.Lines.Add(''); // Memo1.Lines.Add('// bytes '+IntToStr(Cnt*2)); Memo1.Lines.Add(''); // S:='static const uint8_t FontWidths_'+FntNm+' [] = {'; // Memo1.Lines.Add(S); // for a := 0 to 223 do begin // S:='0x'+IntToHex(widths[a])+', '; // if a=0 then S:=S+' // '+IntToStr(a+32)+' sp' // else if a=60 then S:=S+' /* '+IntToStr(a+32)+' \ */' // else S:=S+' // '+IntToStr(a+32)+' '+AnsiChar(a+32); // Memo1.Lines.Add(S); // end; // Memo1.Lines.Add('};'); // Memo1.Lines.Add(''); // S:='static const uint16_t FontOffsets_'+FntNm+' [] = {'; // Memo1.Lines.Add(S); // ipoint:=0; // for a := 0 to CBL.Count-1 do begin // if CBL.Checked[a] then begin // S:='0x'+IntToHex(indexes[ipoint])+', '; // if a=0 then S:=S+' // '+IntToStr(a+32)+' sp' // else if a=60 then S:=S+' /* '+IntToStr(a+32)+' \ */' // else S:=S+' // '+IntToStr(a+32)+' '+AnsiChar(a+32); // Memo1.Lines.Add(S); // ipoint:=ipoint+1; // end; // end; // Memo1.Lines.Add('};'); end; end; memo1.Lines.Add('VFontDef VFontList[] = {'); Memo1.Lines.AddStrings(LS); memo1.Lines.Add(' {NULL,0,0,0},'); memo1.Lines.Add('};'); memo1.Lines.Add(''); memo1.Lines.Add('VFontDef GetVFont(char *name){'); memo1.Lines.Add(' uint8_t i = 0;'); memo1.Lines.Add(' VFontDef res = {NULL,0,0,0};'); memo1.Lines.Add(' for(;;){'); memo1.Lines.Add(' if(VFontList[i].Name==NULL){'); memo1.Lines.Add(' break;'); memo1.Lines.Add(' }'); memo1.Lines.Add(' if(strcmp(name,VFontList[i].Name)==0){'); memo1.Lines.Add(' res=VFontList[i];'); memo1.Lines.Add(' break;'); memo1.Lines.Add(' }'); memo1.Lines.Add(' i++;'); memo1.Lines.Add(' }'); memo1.Lines.Add(' return res;'); memo1.Lines.Add('}'); memo1.Lines.Add(''); memo2.Lines.Clear; memo2.Lines.Add(''); memo2.Lines.Add('/*'); memo2.Lines.Add(' * varyfonts.h'); memo2.Lines.Add(' *'); memo2.Lines.Add(' * Created on: '+DateToStr(Now)); memo2.Lines.Add(' * Author: FontGenerator'); memo2.Lines.Add(' */'); memo2.Lines.Add(''); memo2.Lines.Add('#ifndef VARYFONTS_H_'); memo2.Lines.Add('#define VARYFONTS_H_'); memo2.Lines.Add(''); memo2.Lines.Add('#include "stdint.h"'); memo2.Lines.Add(''); memo2.Lines.Add(''); memo2.Lines.Add('typedef struct {'); memo2.Lines.Add(' uint8_t Width; // ширина символа в пикселях'); memo2.Lines.Add(' uint8_t Size; // размер данных в словах'); memo2.Lines.Add(' uint16_t Offset; // смещение символа в словах от начала массива данных'); memo2.Lines.Add('} VLetterMetrics;'); memo2.Lines.Add(''); memo2.Lines.Add('typedef struct {'); memo2.Lines.Add(' char Name['+IntToStr(FntNmL+1)+']; // наименование шрифта'); memo2.Lines.Add(' uint8_t Height; // высота в пикселях'); memo2.Lines.Add(' VLetterMetrics * Metrics; // ссылка на метрики символов'); memo2.Lines.Add(' uint16_t * Font; // ссылка на данные шрифта'); memo2.Lines.Add('} VFontDef;'); memo2.Lines.Add(''); memo2.Lines.Add('VFontDef GetVFont(char *name);'); memo2.Lines.Add(''); memo2.Lines.Add('#endif /* VARYFONTS_H_ */'); finally LS.Free; LI.Free; end; end; procedure TSDIAppForm.N2Click(Sender: TObject); var x,c:Integer; begin if PC.ActivePage.Tag=0 then begin c:=0; for x := 0 to PC.PageCount-1 do if PC.Pages[x].Tag=0 then c:=c+1; if c>1 then begin if MessageDlg('Закрыть текущую вкладку?', mtConfirmation, [mbYes, mbNo], 0, mbYes) = mrYes then begin PC.ActivePage.Destroy; if PC.ActivePageIndex<>0 then PC.ActivePageIndex:=PC.ActivePageIndex-1; MakeProg; end; end; end; end; procedure TSDIAppForm.NeedMakeProg(Sender: TObject); var p:Integer; FRM:TFontFrm; begin for p := 0 to PC.PageCount-1 do begin if PC.Pages[p].Tag=0 then begin FRM:=TFontFrm(PC.Pages[p].Controls[0]); if not FRM.Button1.Enabled then PC.Pages[p].Caption:=FRM.FontName; end; end; MakeProg; end; procedure TSDIAppForm.PCContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); var R:TRect; begin R:=PC.TabRect(PC.ActivePageIndex); if(MousePos.Y>R.Bottom) then Handled:=true; end; procedure TSDIAppForm.ToolButton8Click(Sender: TObject); var Tab:TTabSheet; x:Integer; begin Tab:=TTabSheet.Create(PC); Tab.PageControl:=PC; Tab.Caption:='Шрифт'; for x := PC.PageCount-1 downto 0 do begin if PC.Pages[x].Tag=-2 then PC.Pages[x].PageIndex:=PC.PageCount-1; if PC.Pages[x].Tag=-1 then PC.Pages[x].PageIndex:=PC.PageCount-2; end; InsertFrame(Tab.PageIndex); end; end.
{******************************************************************************} { VCLThemeSelector Launcher by Carlo Barazzetta } { A simple example to launch VCLThemeSelector } { } { Copyright (c) 2020 (Ethea S.r.l.) } { Author: Carlo Barazzetta } { https://github.com/EtheaDev/VCLThemeSelector } { } { 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 LauncherForm; interface uses Winapi.Windows , Winapi.Messages , System.SysUtils , System.Variants , System.Classes , Vcl.Graphics , Vcl.Controls , Vcl.Forms , Vcl.Dialogs , Vcl.StdCtrls , Vcl.ExtCtrls , Vcl.Themes , Vcl.Imaging.pngimage; const COMPANY_NAME = 'Ethea'; type TLauncher = class(TForm) ChangeThemeButton: TButton; ExcludeWindowsCkeckBox: TCheckBox; MaxRowsEdit: TLabeledEdit; MaxColsEdit: TLabeledEdit; Image1: TImage; Label1: TLabel; Label2: TLabel; procedure ChangeThemeButtonClick(Sender: TObject); private procedure TrySetStyle(const AStyleName: string); protected procedure Loaded; override; public { Public declarations } end; var Launcher: TLauncher; implementation {$R *.dfm} uses FVCLThemeSelector ; procedure TLauncher.TrySetStyle(const AStyleName: string); begin try TStyleManager.SetStyle(AStyleName); except ; //ignore end; end; procedure TLauncher.ChangeThemeButtonClick(Sender: TObject); var LStyleName: string; begin LStyleName := TStyleManager.ActiveStyle.Name; if ShowVCLThemeSelector(LStyleName, ExcludeWindowsCkeckBox.Checked, StrToInt(MaxRowsEdit.Text), StrToInt(MaxColsEdit.Text)) then TrySetStyle(LStyleName); WriteAppStyleToReg(COMPANY_NAME, ExtractFileName(Application.ExeName), LStyleName); end; procedure TLauncher.Loaded; var LStyleName: string; begin //Acquire system font and size (eg. for windows 10 Segoe UI and 14 at 96 DPI) //but without using Assign! Font.Name := Screen.IconFont.Name; //If you want to use system font Height: Font.Height := Muldiv(Screen.IconFont.Height, 96, Screen.IconFont.PixelsPerInch); //Read Style stored into Registry LStyleName := ReadAppStyleFromReg(COMPANY_NAME, ExtractFileName(Application.ExeName)); TrySetStyle(LStyleName); inherited; end; end.
(***************************************************************************** * * * This file is part of the UMLCat Component Library. * * * * See the file COPYING.modifiedLGPL.txt, included in this distribution, * * for details about the copyright. * * * * 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. * * * ***************************************************************************** **) unit uktsxmlpaneltreeviews; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ukttreecntrs, uktmsgtypes, uktmsgtreecntrs, uktguidstrs, uktpaneltreeviews, uktmsgpaneltreeviews, uktxmlfileansisymbols, uktxmlfiletreenodetokens, uktsxmltreecntrs, dummy; type (* TCustomUKTSXMLPanelTreeView *) TCustomUKTSXMLPanelTreeView = class(TCustomUKTMsgPanelTreeView) private (* Private declarations *) protected (* Protected declarations *) procedure InsertNode (const AContainerParentNode: TUKTContainerTreeNode); override; procedure UpdateStateUponToken (var AContainerNode: TUKTSXMLTreeNode); procedure TreeNodeAfterInsertHandler (const AMsgRec: TUKTMessageParamsRecord); override; procedure TreeNodeAfterChangeSymbol (const AMsgRec: TUKTMessageParamsRecord); procedure TreeNodeAfterChangeTextValue (const AMsgRec: TUKTMessageParamsRecord); procedure TreeNodeAfterChangeTreeToken (const AMsgRec: TUKTMessageParamsRecord); procedure AssignHandlers(); override; public (* Public declarations *) end; implementation (* TCustomUKTSXMLPanelTreeView *) procedure TCustomUKTSXMLPanelTreeView.InsertNode (const AContainerParentNode: TUKTContainerTreeNode); var ATreeviewParentNode: TUKTMsgPanelTreeViewNode; begin // find the node from treeview that references the given parent node, // from the container ATreeviewParentNode := NodeOf(AContainerParentNode); if (ATreeviewParentNode <> nil) then begin // remove all subitems ATreeviewParentNode.Empty(); // refresh subitems //ATreeviewParentNode.InternalExplore(); //ATreeviewParentNode.Hide(); ATreeviewParentNode.UpdateExpand(); end; end; procedure TCustomUKTSXMLPanelTreeView.UpdateStateUponToken (var AContainerNode: TUKTSXMLTreeNode); var ATreeviewNode: TUKTMsgPanelTreeViewNode; begin ATreeviewNode := Self.NodeOf(AContainerNode); if (ATreeviewNode <> nil) then begin case (AContainerNode.TreeToken) of uktxmlfiletreenodetokens.xmlfiletrntkDocument: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkEoF: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkEoPg: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkEoLn: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkTab: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkSpace: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkBlock: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkSingle: begin // force change to "empty" status ATreeviewNode.UpdateExpand(); ATreeviewNode.Explore(); end; uktxmlfiletreenodetokens.xmlfiletrntkComment: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkEncoding: begin Self.DoNothing(); end; uktxmlfiletreenodetokens.xmlfiletrntkText: begin Self.DoNothing(); end; else begin Self.DoNothing(); end; end; end; end; procedure TCustomUKTSXMLPanelTreeView.TreeNodeAfterInsertHandler (const AMsgRec: TUKTMessageParamsRecord); var AContainerParentNode, AContainerNewNode: TUKTSXMLTreeNode; begin AContainerParentNode := TUKTSXMLTreeNode(AMsgRec.Sender); AContainerNewNode := TUKTSXMLTreeNode(AMsgRec.Param); if (AContainerNewNode <> nil) then begin if (AContainerNewNode.IsRoot()) then begin InsertRootNode(AContainerNewNode); end else begin InsertNode(AContainerParentNode); end; end; end; procedure TCustomUKTSXMLPanelTreeView.TreeNodeAfterChangeSymbol (const AMsgRec: TUKTMessageParamsRecord); var AContainerNode: TUKTSXMLTreeNode; begin AContainerNode := TUKTSXMLTreeNode(AMsgRec.Sender); UpdateStateUponToken(AContainerNode); end; procedure TCustomUKTSXMLPanelTreeView.TreeNodeAfterChangeTextValue (const AMsgRec: TUKTMessageParamsRecord); begin // end; procedure TCustomUKTSXMLPanelTreeView.TreeNodeAfterChangeTreeToken (const AMsgRec: TUKTMessageParamsRecord); var AContainerNode: TUKTSXMLTreeNode; begin AContainerNode := TUKTSXMLTreeNode(AMsgRec.Sender); UpdateStateUponToken(AContainerNode); end; procedure TCustomUKTSXMLPanelTreeView.AssignHandlers(); var AMsgID: TGUID; begin // --> keep previous message-handlers inherited AssignHandlers(); // --> declare additional message-handlers uktguidstrs.DoubleStrToGUID (msgTreeNodeAfterChangeSymbol, AMsgID); FMsgHandlerList.Insert (AMsgID, {$IFDEF FPC}@{$ENDIF}TreeNodeAfterChangeSymbol); uktguidstrs.DoubleStrToGUID (msgTreeNodeAfterChangeTextValue, AMsgID); FMsgHandlerList.Insert (AMsgID, {$IFDEF FPC}@{$ENDIF}TreeNodeAfterChangeTextValue); uktguidstrs.DoubleStrToGUID (msgTreeNodeAfterChangeTreeToken, AMsgID); FMsgHandlerList.Insert (AMsgID, {$IFDEF FPC}@{$ENDIF}TreeNodeAfterChangeTreeToken); end; end.
unit frm_Settings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, XPStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, StdCtrls, ExtCtrls, Grids, ValEdit; type TfrmSettings = class(TForm) ActionToolBar1: TActionToolBar; ActionManager1: TActionManager; acSave: TAction; acClose: TAction; SettingsEditor: TValueListEditor; procedure acCloseExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure acSaveExecute(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure SettingsEditorStringsChange(Sender: TObject); private FDataChanged: Boolean; procedure SetDataChanged(const Value: Boolean); public procedure LoadSettings; procedure SaveSettings; property DataChanged:Boolean read FDataChanged write SetDataChanged; end; var frmSettings:TfrmSettings; implementation uses dm_GUI,dm_AlarmDB, frm_Menu; {$R *.dfm} procedure TfrmSettings.acCloseExecute(Sender: TObject); begin Close; end; procedure TfrmSettings.acSaveExecute(Sender: TObject); begin SaveSettings; end; procedure TfrmSettings.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TfrmSettings.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if DataChanged and acSave.Visible then case dmGUI.ConfirmExit of mrYes: begin acSave.Execute; CanClose:=True; end; mrNo: CanClose:=True; else CanClose:=False; end; end; procedure TfrmSettings.FormDestroy(Sender: TObject); begin frmSettings:=nil; end; procedure TfrmSettings.FormShow(Sender: TObject); begin LoadSettings; end; procedure TfrmSettings.LoadSettings; var I,J:Integer; begin SettingsEditor.Strings.Clear; for I := 0 to High(Settings) do begin J:=SettingsEditor.Strings.Add(Settings[I][0]+'='+dmAlarmDB.GetIni(Settings[I][0])); SettingsEditor.ItemProps[J].KeyDesc:=Settings[I][1]; end; DataChanged:=False; end; procedure TfrmSettings.SaveSettings; var I: Integer; begin for I := 1 to SettingsEditor.Strings.Count do //skip title row dmAlarmDB.SetIni(SettingsEditor.Cells[0,I],SettingsEditor.Cells[1,I]); DataChanged:=False; frmMenu.InitTimer; end; procedure TfrmSettings.SetDataChanged(const Value: Boolean); begin FDataChanged := Value; acSave.Enabled:=DataChanged; end; procedure TfrmSettings.SettingsEditorStringsChange(Sender: TObject); begin DataChanged:=True; end; end.
unit Test_FIToolkit.Config.FixInsight; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, FIToolkit.Config.FixInsight; type // Test methods for class TFixInsightOptions TestTFixInsightOptions = class(TGenericTestCase) strict private FFixInsightOptions: TFixInsightOptions; public procedure SetUp; override; procedure TearDown; override; published procedure TestAssign; procedure TestToString; procedure TestValidationWithEmptyProps; procedure TestValidationWithInvalidProps; procedure TestValidationWithValidProps; end; implementation uses System.SysUtils, System.Types, TestUtils, TestConsts, FIToolkit.Config.Exceptions, FIToolkit.Config.Types, FIToolkit.Config.Consts; procedure TestTFixInsightOptions.SetUp; begin FFixInsightOptions := TFixInsightOptions.Create; end; procedure TestTFixInsightOptions.TearDown; begin FreeAndNil(FFixInsightOptions); end; procedure TestTFixInsightOptions.TestAssign; var FIO : TFixInsightOptions; begin FIO := TFixInsightOptions.Create; FIO.ProjectFileName := STR_INVALID_FILENAME; try FFixInsightOptions.Validate := False; CheckException( procedure begin FFixInsightOptions.Assign(FIO, True); end, EFixInsightOptionsException, 'CheckException::EFixInsightOptionsException' ); CheckFalse(FFixInsightOptions.Validate, 'CheckFalse::FFixInsightOptions.Validate'); CheckNotEquals(STR_INVALID_FILENAME, FFixInsightOptions.ProjectFileName, 'FFixInsightOptions.ProjectFileName <> STR_INVALID_FILENAME'); FFixInsightOptions.Validate := True; CheckException( procedure begin FFixInsightOptions.Assign(FIO, False); end, nil, 'CheckException::nil' ); CheckTrue(FFixInsightOptions.Validate, 'CheckTrue::FFixInsightOptions.Validate'); CheckEquals(STR_INVALID_FILENAME, FFixInsightOptions.ProjectFileName, 'FFixInsightOptions.ProjectFileName = STR_INVALID_FILENAME'); finally FIO.Free; end; end; procedure TestTFixInsightOptions.TestToString; const STR_DEFINE1 = 'DEFINE1'; STR_DEFINE2 = 'DEFINE2'; STR_EXPECTED_RESULT = STR_FIPARAM_PROJECT + '"' + STR_NON_EXISTENT_FILE + '" ' + STR_FIPARAM_DEFINES + STR_DEFINE1 + STR_FIPARAM_VALUES_DELIM + STR_DEFINE2 + ' ' + STR_FIPARAM_SETTINGS + '"' + STR_NON_EXISTENT_FILE + '" ' + STR_FIPARAM_OUTPUT + '"' + STR_NON_EXISTENT_FILE + '" ' + STR_FIPARAM_XML + ' ' + STR_FIPARAM_SILENT; var Defines : TStringDynArray; ReturnValue : String; begin Defines := [STR_DEFINE1, STR_DEFINE2]; with FFixInsightOptions do begin Validate := False; ProjectFileName := STR_NON_EXISTENT_FILE; CompilerDefines := Defines; OutputFileName := STR_NON_EXISTENT_FILE; SettingsFileName := STR_NON_EXISTENT_FILE; Silent := True; OutputFormat := fiofXML; end; { Check string format } ReturnValue := FFixInsightOptions.ToString; CheckEquals(STR_EXPECTED_RESULT, ReturnValue, 'ReturnValue = STR_EXPECTED_RESULT'); FFixInsightOptions.SettingsFileName := String.Empty; ReturnValue := FFixInsightOptions.ToString; CheckFalse(ReturnValue.Contains(STR_FIPARAM_SETTINGS), 'CheckFalse::ReturnValue.Contains(%s)', [STR_FIPARAM_SETTINGS]); { Check validation within method call } FFixInsightOptions.Validate := True; CheckException( procedure begin ReturnValue := FFixInsightOptions.ToString; end, EFixInsightOptionsException, 'CheckException::EFixInsightOptionsException' ); end; procedure TestTFixInsightOptions.TestValidationWithEmptyProps; begin FFixInsightOptions.Validate := True; { Check validation - empty project file name } CheckException( procedure begin FFixInsightOptions.ProjectFileName := String.Empty; end, EFIOProjectFileNotFound, 'CheckException::EFIOProjectFileNotFound' ); { Check validation - empty output file name } CheckException( procedure begin FFixInsightOptions.OutputFileName := String.Empty; end, EFIOEmptyOutputFileName, 'CheckException::EFIOEmptyOutputFileName' ); { Check validation - empty settings file name } CheckException( procedure begin FFixInsightOptions.SettingsFileName := String.Empty; end, nil, 'CheckException::nil' ); end; procedure TestTFixInsightOptions.TestValidationWithInvalidProps; begin FFixInsightOptions.Validate := True; { Check validation - invalid project file name } CheckException( procedure begin FFixInsightOptions.ProjectFileName := STR_NON_EXISTENT_FILE; end, EFIOProjectFileNotFound, 'CheckException::EFIOProjectFileNotFound' ); { Check validation - empty output file name } CheckException( procedure begin FFixInsightOptions.OutputFileName := ParamStr(0); FFixInsightOptions.OutputFileName := String.Empty; end, EFIOEmptyOutputFileName, 'CheckException::EFIOEmptyOutputFileName' ); { Check validation - nonexistent output directory } CheckException( procedure begin FFixInsightOptions.OutputFileName := STR_NON_EXISTENT_DIR + ExtractFileName(ParamStr(0)); end, EFIOOutputDirectoryNotFound, 'CheckException::EFIOOutputDirectoryNotFound' ); { Check validation - invalid output file name } CheckException( procedure begin FFixInsightOptions.OutputFileName := ExtractFilePath(ParamStr(0)) + STR_INVALID_FILENAME; end, EFIOInvalidOutputFileName, 'CheckException::EFIOInvalidOutputFileName' ); { Check validation - invalid settings file name } CheckException( procedure begin FFixInsightOptions.SettingsFileName := STR_NON_EXISTENT_FILE; end, EFIOSettingsFileNotFound, 'CheckException::EFIOSettingsFileNotFound' ); end; procedure TestTFixInsightOptions.TestValidationWithValidProps; begin CheckException( procedure begin with FFixInsightOptions do begin Validate := True; CompilerDefines := nil; OutputFileName := ParamStr(0); OutputFormat := fiofPlainText; ProjectFileName := ParamStr(0); SettingsFileName := ParamStr(0); SettingsFileName := String.Empty; end; end, nil, 'CheckException::nil' ); end; initialization // Register any test cases with the test runner RegisterTest(TestTFixInsightOptions.Suite); end.
{ https://www.cnblogs.com/gw811/archive/2012/10/12/2720777.html 【算法分析】表达式不合法有三种情况:①左右括号不匹配;②变量名不合法;③运算符两旁无参与运算的变量或数。 分析表达式树可以看到:表达式的根结点及其子树的根结点为运算符,其在树中的顺序是按运算的先后顺序从后到前,表达树的叶子为参与运算的变量或数。 例如,表达式:a+(b-c)/d 运算顺序: ③ ① ② 表达式树如图8-11-2 处理时,首先找到运算级别最低的运算符“+”作为根结点,继而确定该根结点的左、右子树结点在表达式串中的范围为a和(b-c)/d,再在对应的范围内寻找运算级别最低的运算符作为子树的根结点,直到范围内无运算符,则剩余的变量或数为表达式树的叶子。 【算法步骤】 ① 设数组ex存放表达式串的各字符,lt、rt作为结点的左右指针,变量left、right用于存放每次取字符范围的左、右界。 ② 设置左界初值为1;右界初值为串长度。 ③ 判断左右括号是否匹配,不匹配则认为输入有错误。 ④ 在表达式的左右界范围内寻找运算级别最低的运算符,同时判断运算符两旁有否参与运算的变量或数。若无,则输入表达式不合法;若有,作为当前子树的根结点,设置左子树指针及其左右界值,设置右子树指针及其左右界值。 ⑤ 若表达式在左右界范围内无运算符,则为叶子结点,判断变量名或数是否合法。 ⑥ 转④,直到表达式字符取完为止。 源程序中的h、d、w用于存放文本画图时结点的坐标位置。 } program exptree; uses crt; type point=^tree; tree=record data:string; lt:point; rt:point; end; var n,len,k:integer; ex:string; letters:set of char; root:point; procedure error(er:byte); {出错信息提示} begin write('Enter error:'); case er of 1:writeln('No letter'); 2,3:writeln('No expressint'); 4:writeln('No+,*,-or/'); 5:writeln('No(or)'); end; write('Press<enter>...');readln;halt(1); end; procedure create(left,right:integer;var p:point); var q:point; k,n:integer; begin {找运算级别最低的运算符} if ex[left]='(' then begin n:=left+1;k:=0; while (n<right) and (k>=0) do begin if ex[n]='(' then inc(k); if ex[n]=')' then dec(k); inc(n); end; if n=right then begin dec(right);inc(left); end; end; if right<left then error(1); n:=right;k:=0; repeat if ex[n]=')' then inc(k); if ex[n]='(' then dec(k); dec(n); until (((ex[n]='+') or (ex[n]='-')) and (k=0)) or (n<left); if n=left then error(3); if n>left then begin with p^ do begin data:=ex[n]; new(q);lt:=q; new(q);rt:=q; end; create(left,n-1,p^.lt); create(n+1,right,p^.rt); end else {not found '+''-'} begin n:=right; repeat if ex[n]=')' then inc(k); if ex[n]='(' then dec(k); dec(n); until (((ex[n]='*') or (ex[n]='/')) and (k=0)) or (n<left); if n=left then error(3); if n>left then begin with p^ do begin data:=ex[n]; new(q);rt:=q; new(q);lt:=q; end; create(left,n-1,p^.lt); create(n+1,right,p^.rt); end else {only string} begin {求叶子结点的字串} for k:=left to right do if not(ex[k] in letters) then error(1); p^.data:=''; for k:=left to right do p^.data:=p^.data+ex[k]; p^.lt:=nil; p^.rt:=nil; end; end; end; procedure pr_tree(w,dep:integer;p:point); {画出生成的表达式树} var h,i,lt,rt:integer; begin h:=40;for i:=1 to dep do h:=h div 2; gotoxy(w-1,dep*3);write('(',p^.data,')'); if p^.lt=nil then lt:=w else begin lt:=w-h;pr_tree(lt,dep+1,p^.lt) end; if p^.rt=nil then rt:=w else begin rt:=w+h;pr_tree(rt,dep+1,p^.rt); end; if lt<>rt then begin gotoxy(w,dep*3+1);write('|'); gotoxy(lt,3*dep+2);write('|'); for i:=lt to rt-2 do write('-');write('|'); end; end; begin clrscr; letters:=['A'..'Z','a'..'z','0'..'9']; repeat write('Enter expression:');readln(ex); len:=length(ex) until len>0; n:=1; k:=0; while (n<=len) and (k>=0) do {判断左括号是否匹配} begin if ex[n]='(' then inc(k); if ex[n]=')' then dec(k); inc(n); end; if k<>0 then error(5); new(root);create(1,len,root); pr_tree(40,1,root);readln end.
unit Ths.Erp.Database.Table.AracTakip.Arac; interface uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TArac = class(TTable) private FMarka: TFieldDB; FModel: TFieldDB; FPlaka: TFieldDB; FRenk: TFieldDB; FGelisTarihi: TFieldDB; FGelisKM: TFieldDB; FGelisYeri: TFieldDB; FAciklama: TFieldDB; FIsActive: TFieldDB; FAktifKM: TFieldDB; FAktifKonum: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property Marka: TFieldDB read FMarka write FMarka; Property Model: TFieldDB read FModel write FModel; Property Plaka: TFieldDB read FPlaka write FPlaka; Property Renk: TFieldDB read FRenk write FRenk; Property GelisTarihi: TFieldDB read FGelisTarihi write FGelisTarihi; Property GelisKM: TFieldDB read FGelisKM write FGelisKM; Property GelisYeri: TFieldDB read FGelisYeri write FGelisYeri; Property Aciklama: TFieldDB read FAciklama write FAciklama; Property IsActive: TFieldDB read FIsActive write FIsActive; Property AktifKM: TFieldDB read FAktifKM write FAktifKM; Property AktifKonum: TFieldDB read FAktifKonum write FAktifKonum; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TArac.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'arac'; SourceCode := '1000'; FMarka := TFieldDB.Create('marka', ftString, ''); FModel := TFieldDB.Create('model', ftString, ''); FPlaka := TFieldDB.Create('plaka', ftString, ''); FRenk := TFieldDB.Create('renk', ftString, ''); FGelisTarihi := TFieldDB.Create('gelis_tarihi', ftDate, 0); FGelisKM := TFieldDB.Create('gelis_km', ftInteger, 0); FGelisYeri := TFieldDB.Create('gelis_teri', ftString, ''); FAciklama := TFieldDB.Create('aciklama', ftString, ''); FIsActive := TFieldDB.Create('is_active', ftBoolean, 0); FAktifKM := TFieldDB.Create('aktif_km', ftInteger, 0); FAktifKonum := TFieldDB.Create('aktif_konum', ftString, ''); end; procedure TArac.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FMarka.FieldName, TableName + '.' + FModel.FieldName, TableName + '.' + FPlaka.FieldName, TableName + '.' + FRenk.FieldName, TableName + '.' + FGelisTarihi.FieldName, TableName + '.' + FGelisKM.FieldName, TableName + '.' + FGelisYeri.FieldName, TableName + '.' + FAciklama.FieldName, TableName + '.' + FIsActive.FieldName, TableName + '.' + FAktifKM.FieldName, TableName + '.' + FAktifKonum.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FMarka.FieldName).DisplayLabel := 'Marka'; Self.DataSource.DataSet.FindField(FModel.FieldName).DisplayLabel := 'Model'; Self.DataSource.DataSet.FindField(FPlaka.FieldName).DisplayLabel := 'Plaka'; Self.DataSource.DataSet.FindField(FRenk.FieldName).DisplayLabel := 'Renk'; Self.DataSource.DataSet.FindField(FGelisTarihi.FieldName).DisplayLabel := 'Geliş Tarihi'; Self.DataSource.DataSet.FindField(FGelisKM.FieldName).DisplayLabel := 'Geliş KM'; Self.DataSource.DataSet.FindField(FGelisYeri.FieldName).DisplayLabel := 'Geliş Yeri'; Self.DataSource.DataSet.FindField(FAciklama.FieldName).DisplayLabel := 'Açıklama'; Self.DataSource.DataSet.FindField(FIsActive.FieldName).DisplayLabel := 'Aktif?'; Self.DataSource.DataSet.FindField(FAktifKM.FieldName).DisplayLabel := 'Aktif KM'; Self.DataSource.DataSet.FindField(FAktifKonum.FieldName).DisplayLabel := 'Aktif Konum'; end; end; end; procedure TArac.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE NOWAIT; '; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FMarka.FieldName, TableName + '.' + FModel.FieldName, TableName + '.' + FPlaka.FieldName, TableName + '.' + FRenk.FieldName, TableName + '.' + FGelisTarihi.FieldName, TableName + '.' + FGelisKM.FieldName, TableName + '.' + FGelisYeri.FieldName, TableName + '.' + FAciklama.FieldName, TableName + '.' + FIsActive.FieldName, TableName + '.' + FAktifKM.FieldName, TableName + '.' + FAktifKonum.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FMarka.Value := FormatedVariantVal(FieldByName(FMarka.FieldName).DataType, FieldByName(FMarka.FieldName).Value); FModel.Value := FormatedVariantVal(FieldByName(FModel.FieldName).DataType, FieldByName(FModel.FieldName).Value); FPlaka.Value := FormatedVariantVal(FieldByName(FPlaka.FieldName).DataType, FieldByName(FPlaka.FieldName).Value); FRenk.Value := FormatedVariantVal(FieldByName(FRenk.FieldName).DataType, FieldByName(FRenk.FieldName).Value); FGelisTarihi.Value := FormatedVariantVal(FieldByName(FGelisTarihi.FieldName).DataType, FieldByName(FGelisTarihi.FieldName).Value); FGelisKM.Value := FormatedVariantVal(FieldByName(FGelisKM.FieldName).DataType, FieldByName(FGelisKM.FieldName).Value); FGelisYeri.Value := FormatedVariantVal(FieldByName(FGelisYeri.FieldName).DataType, FieldByName(FGelisYeri.FieldName).Value); FAciklama.Value := FormatedVariantVal(FieldByName(FAciklama.FieldName).DataType, FieldByName(FAciklama.FieldName).Value); FIsActive.Value := FormatedVariantVal(FieldByName(FIsActive.FieldName).DataType, FieldByName(FIsActive.FieldName).Value); FAktifKM.Value := FormatedVariantVal(FieldByName(FAktifKM.FieldName).DataType, FieldByName(FAktifKM.FieldName).Value); FAktifKonum.Value := FormatedVariantVal(FieldByName(FAktifKonum.FieldName).DataType, FieldByName(FAktifKonum.FieldName).Value); List.Add(Self.Clone()); Next; end; Close; end; end; end; procedure TArac.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FMarka.FieldName, FModel.FieldName, FPlaka.FieldName, FRenk.FieldName, FGelisTarihi.FieldName, FGelisKM.FieldName, FGelisYeri.FieldName, FAciklama.FieldName, FIsActive.FieldName, FAktifKM.FieldName, FAktifKonum.FieldName ]); NewParamForQuery(QueryOfInsert, FMarka); NewParamForQuery(QueryOfInsert, FModel); NewParamForQuery(QueryOfInsert, FPlaka); NewParamForQuery(QueryOfInsert, FRenk); NewParamForQuery(QueryOfInsert, FGelisTarihi); NewParamForQuery(QueryOfInsert, FGelisKM); NewParamForQuery(QueryOfInsert, FGelisYeri); NewParamForQuery(QueryOfInsert, FAciklama); NewParamForQuery(QueryOfInsert, FIsActive); NewParamForQuery(QueryOfInsert, FAktifKM); NewParamForQuery(QueryOfInsert, FAktifKonum); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TArac.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FMarka.FieldName, FModel.FieldName, FPlaka.FieldName, FRenk.FieldName, FGelisTarihi.FieldName, FGelisKM.FieldName, FGelisYeri.FieldName, FAciklama.FieldName, FIsActive.FieldName, FAktifKM.FieldName, FAktifKonum.FieldName ]); NewParamForQuery(QueryOfUpdate, FMarka); NewParamForQuery(QueryOfUpdate, FModel); NewParamForQuery(QueryOfUpdate, FPlaka); NewParamForQuery(QueryOfUpdate, FRenk); NewParamForQuery(QueryOfUpdate, FGelisTarihi); NewParamForQuery(QueryOfUpdate, FGelisKM); NewParamForQuery(QueryOfUpdate, FGelisYeri); NewParamForQuery(QueryOfUpdate, FAciklama); NewParamForQuery(QueryOfUpdate, FIsActive); NewParamForQuery(QueryOfUpdate, FAktifKM); NewParamForQuery(QueryOfUpdate, FAktifKonum); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TArac.Clone():TTable; begin Result := TArac.Create(Database); Self.Id.Clone(TArac(Result).Id); FMarka.Clone(TArac(Result).FMarka); FModel.Clone(TArac(Result).FModel); FPlaka.Clone(TArac(Result).FPlaka); FRenk.Clone(TArac(Result).FRenk); FGelisTarihi.Clone(TArac(Result).FGelisTarihi); FGelisKM.Clone(TArac(Result).FGelisKM); FGelisYeri.Clone(TArac(Result).FGelisYeri); FAciklama.Clone(TArac(Result).FAciklama); FIsActive.Clone(TArac(Result).FIsActive); FAktifKM.Clone(TArac(Result).FAktifKM); FAktifKonum.Clone(TArac(Result).FAktifKonum); end; end.
unit MyShlObj; interface uses ShlObj, ShellApi, windows; const { // Следующие идентификаторы имеются в модуле ShlObj: CSIDL_DESKTOP = $0000; // Виртуальный каталог, представляющий Рабочий стол. (Корень в проводнике) CSIDL_INTERNET = $0001; // Виртуальный каталог для Internet Explorer. CSIDL_PROGRAMS = $0002; // Меню Пуск -> Программы CSIDL_CONTROLS = $0003; // Виртуальный каталог, содержащий иконки пунктов панели управления CSIDL_PRINTERS = $0004; // Виртуальный каталог, содержащий установленные принтеры CSIDL_PERSONAL = $0005; // Виртуальный каталог, представляющий папку "Мои документы" // До Vista ссылался на какталог "Мои документы" на жёстком диске CSIDL_FAVORITES = $0006; // Избранное. (обычно C:\Documents and Settings\username\Favorites) CSIDL_STARTUP = $0007; // Пуск -> Программы -> Автозагрузка CSIDL_RECENT = $0008; // Недавние документы (обычно C:\Documents and Settings\username\My Recent Documents // Для добавления ссылки документа используйте SHAddToRecentDocs CSIDL_SENDTO = $0009; // Папка, содержащая ярлыки меню "Отправить" (Sent to...) //(обычно C:\Documents and Settings\username\SendTo) CSIDL_BITBUCKET = $000a; // Виртуальный каталог, содержащий файлы в корзине текущего пользователя CSIDL_STARTMENU = $000b; // Элементы меню Пуск текущего пользователя //(обычно C:\Documents and Settings\username\Start Menu) CSIDL_DESKTOPDIRECTORY = $0010; // Рабочий стол текущего пользователя (обычно C:\Documents and Settings\username\Desktop) CSIDL_DRIVES = $0011; // Виртуальный каталог, представляющий папку "Мой компьютер" CSIDL_NETWORK = $0012; // Виртуальный каталог, представляющий "Сетевое окружение" CSIDL_NETHOOD = $0013; // Папка "My Nethood Places" (обычно C:\Documents and Settings\username\NetHood) // В неё ссылки на избранные расшаренные ресурсы CSIDL_FONTS = $0014; // Папка, содержащая установленные шрифты. (обычно C:\Windows\Fonts) CSIDL_TEMPLATES = $0015; // Шаблоны документов. (Обычно Settings\username\Templates) CSIDL_COMMON_STARTMENU = $0016; // Элементы меню Пуск для всех пользователей. //(обычно C:\Documents and Settings\All Users\Start Menu) // Константы, начинающиеся на CSIDL_COMMON_ существуют только в NT версиях CSIDL_COMMON_PROGRAMS = $0017; // Меню Пуск -> программы для всех пользователей //(обычно C:\Documents and Settings\All Users\Start Menu\Programs) CSIDL_COMMON_STARTUP = $0018; // Меню Пуск -> Программы -> Автозагрузка для всех пользователей //(обычно C:\Documents and Settings\All Users\Start Menu\Programs\Startup) CSIDL_COMMON_DESKTOPDIRECTORY = $0019; // Элементы Рабочего стола для всех пользователей //(обычно C:\Documents and Settings\All Users\Desktop) CSIDL_APPDATA = $001a; // Папка, в которой рограммы должны хранить свои данные //(C:\Documents and Settings\username\Application Data) CSIDL_PRINTHOOD = $001b; // Установленные принтеры. //(обычно C:\Documents and Settings\username\PrintHood) CSIDL_ALTSTARTUP = $001d; // DBCS // user's nonlocalized Startup program group. Устарело. CSIDL_COMMON_ALTSTARTUP = $001e; // DBCS // Устарело CSIDL_COMMON_FAVORITES = $001f; // Ссылки "Избранное" для всех пользователей CSIDL_INTERNET_CACHE = $0020; // Временные Internet файлы //(обычно C:\Documents and Settings\username\Local Settings\Temporary Internet Files) CSIDL_COOKIES = $0021; // Папка для хранения Cookies (обычно C:\Documents and Settings\username\Cookies) CSIDL_HISTORY = $0022; // Хранит ссылки интернет истории IE } // Следующих идентификаторов нет в ShlObj: CSIDL_ADMINTOOLS = $30; // Административные инструменты текущего пользователя (например консоль MMC). Win2000+ CSIDL_CDBURN_AREA = $3b; // Папка для файлов, подготовленных к записи на CD/DVD //(Обычно C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\CD Burning) CSIDL_COMMON_ADMINTOOLS = $2f; // Папка, содержащая инструменты администрирования CSIDL_COMMON_APPDATA = $23; // Папака AppData для всех пользователей. //(обычно C:\Documents and Settings\All Users\Application Data) CSIDL_COMMON_DOCUMENTS = $2e; // Папка "Общие документы" (обычно C:\Documents and Settings\All Users\Documents) CSIDL_COMMON_TEMPLATES = $2d; // Папка шаблонов документов для всех пользователей //(Обычно C:\Documents and Settings\All Users\Templates) CSIDL_COMMON_MUSIC = $35; // Папка "Моя музыка" для всех пользователей. //(обычно C:\Documents and Settings\All Users\Documents\My Music) CSIDL_COMMON_PICTURES = $36; // Папка "Мои рисунки" для всех пользователей. //(обычно C:\Documents and Settings\All Users\Documents\My Pictures) CSIDL_COMMON_VIDEO = $37; // Папка "Моё видео" для всех пользователей //(C:\Documents and Settings\All Users\Documents\My Videos) CSIDL_COMPUTERSNEARME = $3d; // Виртуальная папка, представляет список компьютеров в вашей рабочей группе CSIDL_CONNECTIONS = $31; // Виртуальная папка, представляет список сетевых подключений CSIDL_LOCAL_APPDATA = $1c; // AppData для приложений, которые не переносятся на другой компьютер //(обычно C:\Documents and Settings\username\Local Settings\Application Data) CSIDL_MYDOCUMENTS = $0c; // Виртуальный каталог, представляющий папку "Мои документы" CSIDL_MYMUSIC = $0d; // Папка "Моя музыка" CSIDL_MYPICTURES = $27; // Папка "Мои картинки" CSIDL_MYVIDEO = $0e; // Папка "Моё видео" CSIDL_PROFILE = $28; // Папка пользователя (обычно C:\Documents and Settings\username) CSIDL_PROGRAM_FILES = $26; // Папка Program Files (обычно C:\Program Files) CSIDL_PROGRAM_FILESX86 = $2a; CSIDL_PROGRAM_FILES_COMMON = $2b; // Папка Program Files\Common (обычно C:\Program Files\Common) CSIDL_PROGRAM_FILES_COMMONX86 = $2c; CSIDL_RESOURCES = $38; // Папка для ресерсов. Vista и выше (обычно C:\Windows\Resources) CSIDL_RESOURCES_LOCALIZED = $39; CSIDL_SYSTEM = $25; // Папака System (обычно C:\Windows\System32 или C:\Windows\System) CSIDL_SYSTEMX86 = $29; CSIDL_WINDOWS = $24; // Папка Windows. Она же %windir% или %SYSTEMROOT% (обычно C:\Windows) function GetSpecialPath(CSIDL: word): string; implementation function GetSpecialPath(CSIDL: word): string; var s: string; begin SetLength(s, MAX_PATH); if not SHGetSpecialFolderPath(0, PChar(s), CSIDL, true) // then s := GetSpecialPath(CSIDL_APPDATA); then s := ''; result := PChar(s); end; end.
unit uMidiDevices; interface uses KbdMacro, Windows, Messages, Classes, MidiIn, MidiType, MidiCons; const WM_MIDI_KEY = WM_USER + 304; type TMIDIDevice = class (THIDKeyboard) private fMidiIn: TMidiInput; procedure ReceivedMidiInput(Sender: TObject); public constructor Create(pSystemID: string; pHandle: HWND); destructor Destroy; Override; procedure Open; end; TNewMidiDeviceCallback = procedure(pDev: TMIDIDevice) of object; TMidiControl = class (TObject) private fDevices: TList; fOnNewDevice: TNewMidiDeviceCallback; function GetAvailable: Boolean; public constructor Create; procedure Init; procedure DebugLog(Value: String); function GetDevice(pName: String): TMIDIDevice; destructor Destroy; Override; property OnNewDevice: TNewMidiDeviceCallback read fOnNewDevice write fOnNewDevice; property Available: Boolean read GetAvailable; end; implementation uses uGlobals, Forms, SysUtils; { TMidiControl } function TMidiControl.GetAvailable: Boolean; begin Result := True; end; function TMidiControl.GetDevice(pName: String): TMIDIDevice; var I: Integer; begin Result := nil; for I := 0 to fDevices.Count - 1 do if UpperCase(TMIDIDevice(fDevices[I]).Name) = UpperCase(pName) then begin Result := TMIDIDevice(fDevices[I]); break; end; end; procedure TMidiControl.Init; var I : Integer; lMidiDevice: TMIDIDevice; lMidiIn: TMidiInput; begin // get devices lMidiIn := TMidiInput.Create(nil); try if lMidiIn.DeviceCount > 0 then begin for I := 0 to lMidiIn.DeviceCount - 1 do begin lMidiIn.DeviceID := I; lMidiDevice := TMIDIDevice.Create(lMidiIn.ProductName+' (ID '+IntToStr(i)+')', i+1); fDevices.Add(lMidiDevice); if Assigned(fOnNewDevice) then fOnNewDevice(lMidiDevice); end; end; lMidiIn.StopAndClose; finally lMidiIn.Free; end; for I := 0 to fDevices.Count - 1 do TMIDIDevice(fDevices[I]).Open; end; constructor TMidiControl.Create; begin fDevices := TList.Create; end; procedure TMidiControl.DebugLog(Value: String); begin Glb.DebugLog(Value, 'MIDI'); end; destructor TMidiControl.Destroy; var I : Integer; begin //for I := 0 to fDevices.Count - 1 do // TMIDIDevice(fDevices[I]).Free; fDevices.Free; // each devices are destroyed from form inherited; end; { TMIDIDevice } constructor TMIDIDevice.Create(pSystemID: string; pHandle: HWND); begin inherited; if IsAlive then // which means handle > 0 begin fMidiIn := TMidiInput.Create(nil); fMidiIn.DeviceID := pHandle - 1; fMidiIn.OnMidiInput := ReceivedMidiInput; end else fMidiIn := nil; end; destructor TMIDIDevice.Destroy; begin if fMidiIn <> nil then begin fMidiIn.StopAndClose; fMidiIn.Free; end; inherited; end; procedure TMIDIDevice.Open; begin if fMidiIn <> nil then fMidiIn.OpenAndStart; end; procedure TMIDIDevice.ReceivedMidiInput(Sender: TObject); var lMidiEvent: TMyMidiEvent; begin while fMidiIn.MessageCount > 0 do begin lMidiEvent := fMidiIn.GetMidiEvent; PostMessage(Glb.MainForm.Handle, WM_MIDI_KEY, Integer(self), Integer(lMidiEvent)); end; end; end.
unit SqlThreadUnit; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.StrUtils, System.Win.ComObj, Data.DB, Data.Win.ADODB, WinApi.ADOInt, Vcl.Dialogs, Variants, ThreadUnit, StringGridsUnit, StringGridExUnit, plugin; type TSqlThreadObject = class(TThreadExecObject) private FSql: TStringList; FConnectionString: string; FCacheSize: integer; FCommandTimeOut: integer; FBdType: TBdType; procedure SetConnectionString(const Value: string); procedure SetCacheSize(const Value: integer); procedure SetCommandTimeOut(const Value: integer); function GetLogin: string; const cnstUserID = 'User ID='; public constructor Create; destructor Destroy; override; property SQL: TStringList read FSql; property BdType: TBdType read FBdType write FBdType; property Login: string read GetLogin; property CacheSize: integer read FCacheSize write SetCacheSize; property CommandTimeOut: integer read FCommandTimeOut write SetCommandTimeOut; property ConnectionString: string read FConnectionString write SetConnectionString; end; TSqlQueryObject = class(TSqlThreadObject) private FQuery: TAdoQuery; protected procedure Execute; override; public constructor Create; destructor Destroy; override; property Query: TAdoQuery read FQuery; end; TSqlExecutorObject = class(TSqlThreadObject) private FGrids: TStringGrids; protected procedure Execute; override; public constructor Create; destructor Destroy; override; property Grids: TStringGrids read FGrids; end; implementation uses System.Math; { TSqlThreadObject } constructor TSqlThreadObject.Create; begin inherited; FSql := TStringList.Create; FCacheSize := 20; FCommandTimeOut := 0; end; destructor TSqlThreadObject.Destroy; begin FreeAndNil(FSql); inherited; end; function TSqlThreadObject.GetLogin: string; var i,j: Integer; begin Result := ''; i := FConnectionString.IndexOf(cnstUserID); if i>=0 then begin j := FConnectionString.IndexOf(';',i+1); Result := FConnectionString.Substring(i+cnstUserID.Length,j-i-cnstUserID.Length).Trim; end; end; procedure TSqlThreadObject.SetCacheSize(const Value: integer); begin FCacheSize := Value; end; procedure TSqlThreadObject.SetCommandTimeOut(const Value: integer); begin FCommandTimeOut := Value; end; procedure TSqlThreadObject.SetConnectionString(const Value: string); begin FConnectionString := Value; end; { TSqlQueryObject } constructor TSqlQueryObject.Create; begin inherited; FQuery := nil; end; destructor TSqlQueryObject.Destroy; begin if Assigned(FQuery) then FQuery.Free; inherited; end; procedure TSqlQueryObject.Execute; begin FQuery := TADOQuery.Create(nil); with FQuery do begin AutoCalcFields := False; ExecuteOptions := []; CacheSize := FCacheSize; CommandTimeout := FCommandTimeout; ConnectionString := FConnectionString; end; if Length(FQuery.ConnectionString)>0 then begin if Sql.Count > 0 then begin FQuery.SQL.Clear; FQuery.SQL.AddStrings(Self.Sql); FQuery.Prepared := True; if not FThread.Terminated then FQuery.Open; end; end; end; { TSqlExecutorObject } constructor TSqlExecutorObject.Create; begin inherited; FGrids := nil; end; destructor TSqlExecutorObject.Destroy; begin if Assigned(FGrids) then FGrids.Free; inherited; end; procedure TSqlExecutorObject.Execute; procedure MoveStrings(StringSource,StringsTarget: TStringList); var S0: string; i : integer; begin StringsTarget.Clear; while StringSource.Count > 0 do begin for i := 0 to StringSource.Count-1 do begin S0 := Trim(StringSource[i]); StringSource[i] := ''; if LowerCase(S0) = cnstGo then Break; StringsTarget.Add(S0); end; while (StringSource.Count > 0) and (StringSource[0] = '') do StringSource.Delete(0); if StringsTarget.Count > 0 then Exit; end; end; procedure PostGridMessage(const S: string); var Grid : TStringGridEx; begin Grid := FGrids.Add; Grid.RowCount := 1; Grid.ColCount := 1; Grid.ColWidths[0] := Length(S); Grid.Cells[0,0] := S; end; function GetDots(const S: string): string; begin if length(S) > 150 then Result := '...' else Result := ''; end; var cmd : _Command; Conn : _Connection; rs : _RecordSet; RA : OleVariant; n,i : Integer; Grid : TStringGridEx; S : string; V : OleVariant; Strings: TStringList; begin Conn := CreateComObject(CLASS_Connection) as _Connection; Conn.ConnectionString := FConnectionString; Conn.Open(Conn.ConnectionString,'','',Integer(adConnectUnspecified)); try FGrids := TStringGrids.Create; FGrids.Name := Name; FGrids.Description := Sql.Text; FGrids.ConnectionString := ConnectionString; Strings := TStringList.Create; try MoveStrings(Sql,Strings); while Strings.Count > 0 do begin cmd := CreateComObject(CLASS_Command) as _Command; cmd.CommandType := adCmdUnknown; cmd.Set_ActiveConnection(Conn); cmd.CommandText := Strings.Text; cmd.CommandTimeout := FCommandTimeout; try try rs := cmd.Execute(RA,EmptyParam,Integer(adCmdUnknown)); except on E: Exception do begin PostGridMessage(E.Message); Exit; end; end; while not FThread.Terminated do begin if rs.State = adStateOpen then begin Grid := FGrids.Add; Grid.ColCount := rs.Fields.Count; Grid.RowCount := 1; for i := 0 to rs.Fields.Count -1 do Grid.Cells[i,0] := rs.Fields[i].Name; if not (rs.EOF and rs.BOF) then begin while not rs.EOF do begin if FThread.Terminated then Exit; Grid.RowCount := Grid.RowCount + 1; for i := 0 to rs.Fields.Count -1 do begin S := '<NULL>'; V := rs.Fields[i].Value; if not VarIsNull(V) then case rs.Fields[i].Type_ of 7,133,134,135: S := FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz',VarToDateTime(V)) else S := VarToStr(V); end; Grid.ColWidths[i] := Max(Grid.ColWidths[i],Length(S)); Grid.Cells[i,Grid.RowCount-1] := S; end; rs.MoveNext; end; end; end; if Conn.Errors.Count > 0 then begin for n:=Conn.Errors.Count-1 downto 0 do if Trim(Conn.Errors.Item[n].Description) <> '' then begin if FThread.Terminated then Exit; S := Trim(Conn.Errors.Item[n].Description); if S <> '' then begin Grid := FGrids.Add; Grid.RowCount := 1; Grid.ColCount := 1; Grid.ColWidths[0] := Length(S); Grid.Cells[0,0] := S; end; end; end; rs := rs.NextRecordset(RA); if (rs=nil) then break; end; finally cmd.Set_ActiveConnection(nil); cmd := nil; rs := nil; end; MoveStrings(Sql,Strings); end; if FGrids.Count = 0 then //Empty Result begin if FThread.Terminated then Exit; S := cnstSqlNoResults; Grid := FGrids.Add; Grid.RowCount := 1; Grid.ColCount := 1; Grid.ColWidths[0] := Length(S); Grid.Cells[0,0] := S; end; if FThread.Terminated then begin FGrids.Clear; Exit; end finally Strings.Free; end; finally Conn.Close; Conn := nil; end; end; end.
unit cdrom; {Great Amazing CD player !!!} {Great Amazing CD player !!!} { this program will allow the control of multiple cd-rom audio drives simultaniously. I am not sure just yet what sort of an interface I'm going to provide but we will soon see eh? } { prototype #1, just get talking to an audio CD-ROM } interface uses crt; const MAX_TRACKS_PER_CD = 30; type TAudioTrackRec = record code : byte; track : byte; startPoint : longint; trackInfo : byte; end; TAudioDiskRec = record code : byte; lowTrack : byte; highTrack : byte; startPoint : longint; end; TTrackRec = record number : byte; start : longint; finish : longint; end; TTrackArray = array[1 .. MAX_TRACKS_PER_CD] of TTrackRec; var tracks : TTrackArray; lasttrack:byte; { This is a VERY simple CD-player. It only plays from the first { available CD, and only tracks from 1 - 9 and stops after every { track... but it will give you and idea! } procedure playATrack; {Stop the CD player "drive", no errors, even when already stopped} procedure stopCD( drive : word ); { Play a track from the presumably already loaded tracks array { NO ERROR CHECKING ON THIS!. Programmer to make sure that { this procedured is proceeded at some point by calling of the { procedure "getAllTrackDetails"} procedure playTrack( drive, track : word ); { Play from sectors start to finish on drive. { NO ERROR CHECKING } procedure playTrack2(drive : word; start, finish : longint); { If used after a STOPCD, this will resume play at where the CD { was stopped, assuming same drive } procedure resumePlay( drive : word ); { Gets all the track details for the currently loaded CD and places { it into the "TRACKS" array } procedure getAllTrackDetails( drive : word ); { Stops and causes the CD tray to eject (if supported) } procedure ejectCD( drive : word ); { Closes the CD tray (not supported under OS/2, and many CD players } procedure closeCD( drive : word ); { Locks the CD tray, prevents ejection from eject button pressing } procedure lockCD( drive : word ); { Unlocks the CD track, allows ejection from eject button pressing } procedure unlockCD( drive : word ); { Refreshes the buffers in the CD player, ensures the information is { correct } procedure resetCD( drive : word ); { Get the Universal Product code of the CD, not usually available } procedure getUPC( drive : word; var upc : string ); { Get the VTOC from the CD } procedure readVTOC( drive : word ); { Get the details of a particular track on the CD } procedure getTrackDetails( drive : word; trk : byte; var t : TAudioTrackRec ); { Get the number of CD players, and the first CD number } function getNumberOfCDs( var sLetter : word ) : word; function getUnique( drive : word ) : string; { Get the Details of the currently loaded CD } function getCDDetails( drive : word; var t : TAudioDiskRec ) : word; { Get the number of tracks of the currently loaded CD } function getNumberOfTracks( drive : word ) : word; { Get the running time of the currently playing track } function getRunningTime( drive : word; var min,sec : byte ) : word; { Returns true if the CD player has been changed and no update of { information has occured } function mediaChanged( drive : word ) : boolean; { Returns TRUE if the CD-tray is ejected } function doorOpen(drive : word) : boolean; implementation const EJECT_TRAY = 0; CLOSE_TRAY = 5; PLAY_TRACK = 132; STOP_TRACK = 133; RESUME_TRACK = 136; RESET_CD = 2; GET_TRACK_INFO = 11; GET_DISK_INFO = 10; READ_IOCTL = 3; WRITE_IOCTL = 12; MAX_CDS = 10; UPC_CODE = 14; LOCK_CODE = 1; LOCK_CD = 0; UNLOCK_CD = 1; Q_INFO = 12; MEDIA_CHANGE = 9; DEVICE_STATUS = 6; type rHRec = record length : byte; subUnitCode : byte; commandCode : byte; status : word; reserved : array[1..8] of byte; end; IOCTLRec = record r : rHRec; MDB : byte; tAOfs : word; tASeg : word; bytesToTransfer : word; startingSector : word; error : longint; end; TLockRec = record r : rHRec; code : byte; lock : byte; end; TUPCRec = record code : byte; control : byte; UPC : array[1..7] of byte; zero : byte; aFrame : byte; end; TPlayAudioTrackRec = record r : rHRec; mode : byte; start : longint; sectors : longint; end; TQRec = record code : byte; ADR : byte; Track : byte; Point : byte; min : byte; sec : byte; frame : byte; zero : byte; pMin : byte; pSec : byte; pFrame : byte; end; TMediaRec = record code : byte; media : byte; end; TStatusRec = record code : byte; status : longint; end; TTrackNameArray = array[1 .. MAX_TRACKS_PER_CD] of string[40]; TCDROMRec = record UPC : longint; cdName : string[40]; trackNames : TTrackNameArray; maxTrack : byte; end; TCDRackRec = record status : array[1 .. MAX_CDS] of word; rack : array[1 .. MAX_CDS] of TTrackArray; info : array[1 .. MAX_CDS] of TCDROMRec; end; var CDRack : TCDRackRec; result : word; startLetter : word; {--------------------------------------------------------------------} {Play A Track { This is a very simple CD player, which only plays the first { available CD, and only tracks 1-9. However, it does give { the idea. } procedure playATrack; var k : char; trk : word; e : integer; drive : word; quit : boolean; begin getNumberOfCDs(drive); getAllTrackDetails(drive); quit := FALSE; repeat repeat until keypressed; k := readKey; stopCD(drive); if (k >= '1') and (k <= '9') then begin write('Playing track : ',k,' '); val(k,trk,e); playTrack(drive,trk); end else quit := TRUE; until quit; end; {--------------------------------------------------------------------} { { { { } function getNumberOfCDs( var sLetter : word) : word; var drives, startLetter : word; begin asm mov ax,1500h int 2fh; mov startLetter,CX mov drives,BX end; sLetter := startLetter; getNumberOfCDs := drives; end; {--------------------------------------------------------------------} { { { { } procedure setIOCTL( var i : IOCTLRec ); var index : byte; begin with i do begin with r do begin length := 0; subUnitCode := 0; commandCode := 0; status := 0; for index := 1 to 8 do reserved[index] := 0; end;{with R} MDB := 0; tASeg := 0; tAOfs := 0; bytesToTransfer := 0; startingSector := 0; error := 0; end;{with i} end; {--------------------------------------------------------------------} { { { { } procedure getTrackDetails( drive : word; trk : byte; var t : TAudioTrackRec ); var index : word; i : IOCTLRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 7; tAOfs := ofs(t); tASeg := seg(t); end; with i.r do begin length := sizeof(i); commandCode := READ_IOCTL; end; with t do begin track := trk; code := GET_TRACK_INFO; end; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; { t will now contain the relevant information } end; {--------------------------------------------------------------------} { { { { } function getCDDetails( drive : word; var t : TAudioDiskRec ) : word; var index : word; i : IOCTLRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 7; tAOfs := ofs(t); tASeg := seg(t); end; with i.r do begin length := sizeof(i); commandCode := READ_IOCTL; end; with t do begin code := GET_DISK_INFO; lowTrack := 0; highTrack := 0; startPoint := 0; end; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; { t will now contain the relevant information } getCDDetails := i.r.status; end; {--------------------------------------------------------------------} { { { { } function redBookToSectors( red : longint ) : longint; var frame, minute, second : byte; temp : longint; begin frame := (red AND $000000FF); second := (red AND $0000FF00) shr 8; minute := (red AND $00FF0000) shr 16; temp := minute *60; temp := temp *75; temp := temp + second *75; temp := temp + frame -150; redBookToSectors := temp; end; {--------------------------------------------------------------------} procedure getAllTrackDetails( drive : word ); var diskInfo : TAudioDiskRec; aTrack : TAudioTrackRec; firstCD : word; currentTrack : byte; index1, index2 : byte; pos1,pos2,pos3 : word; begin getCDDetails(drive,diskInfo); lasttrack:=diskinfo.hightrack; for currentTrack := diskInfo.lowTrack to diskInfo.highTrack do begin getTrackDetails(drive,currentTrack,aTrack); with tracks[currentTrack] do begin number := currentTrack; start := aTrack.startPoint; if (currentTrack > 1) then begin tracks[currentTrack-1].finish := tracks[currentTrack].start-1; end; end;{with} end;{for} end; {--------------------------------------------------------------------} procedure stopCD(drive : word); var r : rHRec; s,o : word; begin r.commandCode := 133; r.length := sizeOf(r); s := seg(r); o := ofs(r); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} procedure playTrack(drive,track : word); var index : word; p : TPlayAudioTrackRec; s,o : word; st,fi : longint; begin p.r.subUnitCode := 0; p.r.status := 0; p.r.commandcode := 132; p.r.length := sizeOf(p); for index := 1 to 8 do begin p.r.reserved[index] := 0; end; p.start := tracks[track].start; fi := redBookToSectors(tracks[track].finish); st := redBookToSectors(tracks[track].start); p.sectors := fi-st; p.mode := 1; s := seg(p); o := ofs(p); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } procedure playTrack2(drive : word; start, finish : longint); var index : word; p : TPlayAudioTrackRec; s,o : word; st,fi : longint; begin p.r.subUnitCode := 0; p.r.status := 0; p.r.commandcode := 132; p.r.length := sizeOf(p); for index := 1 to 8 do begin p.r.reserved[index] := 0; end; p.start := start; fi := redBookToSectors(finish); st := redBookToSectors(start); p.sectors := fi-st; p.mode := 1; s := seg(p); o := ofs(p); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } procedure ejectCD( drive : word ); var index : word; ejRec : record code : byte; end; i : IOCTLRec; rq : rHRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 1; tAOfs := ofs(ejRec); tASeg := seg(ejRec); end; with i.r do begin length := sizeof(i); commandCode := 12; end; ejRec.code := EJECT_TRAY; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } procedure closeCD( drive : word ); var index : word; ejRec : record code : byte; end; i : IOCTLRec; rq : rHRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 1; tAOfs := ofs(ejRec); tASeg := seg(ejRec); end; with i.r do begin length := sizeof(i); commandCode := 12; end; ejRec.code := CLOSE_TRAY; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } procedure resetCD( drive : word ); var index : word; resetRec : record code : byte; end; i : IOCTLRec; rq : rHRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 1; tAOfs := ofs(resetRec); tASeg := seg(resetRec); end; with i.r do begin length := sizeof(i); commandCode := 12; end; resetRec.code := RESET_CD; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } procedure lockCD( drive : word ); var index : word; lockRec : record code : byte; lock : byte; end; i : IOCTLRec; rq : rHRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 2; tAOfs := ofs(lockRec); tASeg := seg(lockRec); end; with i.r do begin length := sizeof(i); commandCode := 12; end; lockRec.code := LOCK_CODE; lockRec.lock := LOCK_CD; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } procedure unlockCD( drive : word ); var index : word; lockRec : record code : byte; lock : byte; end; i : IOCTLRec; rq : rHRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 2; tAOfs := ofs(lockRec); tASeg := seg(lockRec); end; with i.r do begin length := sizeof(i); commandCode := 12; end; lockRec.code := LOCK_CODE; lockRec.lock := LOCK_CD; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; end; {--------------------------------------------------------------------} { { { { } function getUnique( drive : word ) : string; var a : TAudioDiskRec; s : string; begin getCDDetails(drive,a); Str(a.startPoint,s); getUnique := s; end; {--------------------------------------------------------------------} { { { { } procedure getUPC( drive : word; var UPC : string ); var u : TUPCRec; s,o : word; index : integer; res : byte; i : IOCTLRec; begin setIOCTL(i); with i do begin bytesToTransfer := 11; tAOfs := ofs(u); tASeg := seg(u); end; with i.r do begin length := 23{sizeof(i);}; commandCode := READ_IOCTL; end; u.code := UPC_CODE; u.control := 2; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; upc := ''; for index := 1 to 7 do begin res := (u.upc[index] AND $0F); upc := concat(upc,chr(res+48)); if (index < 7) then begin res := ((u.upc[index] AND $F0) SHR 4); upc := concat(upc,chr(res+48)); end; end;{for} end; {--------------------------------------------------------------------} { { { { } function getNumberOfTracks( drive : word ) : word; var a : TAudioDiskRec; begin getCDDetails(drive,a); getNumberOfTracks := a.highTrack; end; {--------------------------------------------------------------------} { { { { } procedure readVTOC( drive : word ); var buffer : array[1..2048] of byte; s,o : word; begin o := ofs(buffer); s := seg(buffer); asm mov ax,1508h; mov cx,drive; mov si,s ; mov di,o ; mov dx,1 ; int 2fh; end end; {--------------------------------------------------------------------} { { { { } procedure resumePlay( drive : word ); var r : rHRec; o,s : word; begin r.commandCode := RESUME_TRACK; r.length := 1; o := ofs(r); s := seg(r); asm mov ax,1510h; mov cx,drive; mov es,s ; mov bx,o ; int 2fh; end end; {--------------------------------------------------------------------} function getRunningTime( drive : word; var min,sec : byte ) : word; var q : TQRec; index : word; i : IOCTLRec; rq : rHRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 1; tAOfs := ofs(q); tASeg := seg(q); end; with i.r do begin length := sizeof(i); commandCode := READ_IOCTL; end; q.code := Q_INFO; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; min := q.min; sec := q.sec; getRunningTime := i.r.status; end; {--------------------------------------------------------------------} { { { { } function mediaChanged( drive : word ) : boolean; var q : TMediaRec; index : word; i : IOCTLRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 2; tAOfs := ofs(q); tASeg := seg(q); end; with i.r do begin length := sizeof(i); commandCode := READ_IOCTL; end; q.code := MEDIA_CHANGE; q.media := 0; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; if (q.media < 1) then mediaChanged := TRUE else mediaChanged := FALSE; end; {--------------------------------------------------------------------} { { { { } function doorOpen( drive : word ) : boolean; var q : TStatusRec; index : word; i : IOCTLRec; s,o : word; begin setIOCTL(i); with i do begin bytesToTransfer := 5; tAOfs := ofs(q); tASeg := seg(q); end; with i.r do begin length := sizeof(i); commandCode := READ_IOCTL; end; q.code := DEVICE_STATUS; q.status := 0; s := seg(i); o := ofs(i); asm mov ax,1510h mov cx,drive mov es,S mov bx,O int 2fh end; if (q.status AND $01)=1 then doorOpen := TRUE else doorOpen := FALSE; end; {--------------------------------------------------------------------} { { { { } procedure init; var index : word; begin { initially we start this unit by reading all the available { CD-ROMs and taking in their track details. } for index := 1 to MAX_CDS do begin with CDRack do begin status[index] := 0; info[index].maxTrack := 0; end; end; end; {--------------------------------------------------------------------} { { { { } begin { initially we start this unit by reading all the available { CD-ROMs and taking in their track details. } init; end. { Paul L Daniels Software Development (DOS, OS/2) jackdan@ibm.net jackdan@ozemail.com.au }
{ Copyright (c) 1998-2002 by Florian Klaempfl, Pierre Muller Tokens used by the compiler This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **************************************************************************** } unit mytokens; {$i fpcdefs.inc} interface uses globtype; type ttoken=(NOTOKEN, { operators, which can also be overloaded } _UNSIG, _SIG, _CHAR, _INT, _CONST, _LONG, _FLOAT, _DOUBLE, _STRUCT, _TYPEDEF, _UNION, _ENUM, _VOID, _FOR, _WHILE, _DO, _IF, _THEN, _ELSE, _SWITCH, _CASE, _BREAK, _DEFAULT, _CINCLUDE, _CDEFINE, _IFDEF, _DEF, _IFNDEF, _ENDIF, _EXTERN, _UNDEF, _FILE, _RETURN, _UINT8_T, _UINT16_T, _UINT32_T, _INT8_T, _INT16_T, _INT32_T, _ELIF ); const tokenlenmin = 1; tokenlenmax = 18; { last operator which can be overloaded, the first_overloaded should be declared directly after NOTOKEN } first_overloaded = succ(NOTOKEN); last_overloaded = _UNSIG; last_operator = _CDEFINE; type tokenrec=record str : string[tokenlenmax]; special : boolean; keyword : tmodeswitch; op : ttoken; end; ttokenarray=array[ttoken] of tokenrec; ptokenarray=^ttokenarray; tokenidxrec=record first,last : ttoken; end; ptokenidx=^ttokenidx; ttokenidx=array[tokenlenmin..tokenlenmax,'A'..'Z'] of tokenidxrec; const arraytokeninfo : ttokenarray =( (str:'' ;special:true ;keyword:m_none;op:NOTOKEN), { Operators which can be overloaded } (str:'UNSIGNED' ;special:false;keyword:m_all;op:NOTOKEN), (str:'SIGNED' ;special:false;keyword:m_all;op:NOTOKEN), (str:'CHAR' ;special:false;keyword:m_all;op:NOTOKEN), (str:'INT' ;special:false;keyword:m_all;op:NOTOKEN), (str:'CONST' ;special:false;keyword:m_all;op:NOTOKEN), (str:'LONG' ;special:false;keyword:m_all;op:NOTOKEN), (str:'FLOAT' ;special:false;keyword:m_all;op:NOTOKEN), (str:'DOUBLE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'STRUCT' ;special:false;keyword:m_all;op:NOTOKEN), (str:'TYPEDEF' ;special:false;keyword:m_all;op:NOTOKEN), (str:'UNION' ;special:false;keyword:m_all;op:NOTOKEN), (str:'ENUM' ;special:false;keyword:m_all;op:NOTOKEN), (str:'VOID' ;special:false;keyword:m_all;op:NOTOKEN), (str:'FOR' ;special:false;keyword:m_all;op:NOTOKEN), (str:'WHILE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'DO' ;special:false;keyword:m_all;op:NOTOKEN), (str:'IF' ;special:false;keyword:m_all;op:NOTOKEN), (str:'THEN' ;special:false;keyword:m_all;op:NOTOKEN), (str:'ELSE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'SWITCH' ;special:false;keyword:m_all;op:NOTOKEN), (str:'CASE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'BREAK' ;special:false;keyword:m_all;op:NOTOKEN), (str:'DEFAULT' ;special:false;keyword:m_all;op:NOTOKEN), (str:'INCLUDE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'DEFINE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'IFDEF' ;special:false;keyword:m_all;op:NOTOKEN), (str:'DEFINED' ;special:false;keyword:m_all;op:NOTOKEN), (str:'IFNDEF' ;special:false;keyword:m_all;op:NOTOKEN), (str:'ENDIF' ;special:false;keyword:m_all;op:NOTOKEN), (str:'EXTERN' ;special:false;keyword:m_all;op:NOTOKEN), (str:'UNDEF' ;special:false;keyword:m_all;op:NOTOKEN), (str:'FILE' ;special:false;keyword:m_all;op:NOTOKEN), (str:'RETURN' ;special:false;keyword:m_all;op:NOTOKEN), (str:'UINT8_T' ;special:false;keyword:m_all;op:NOTOKEN), (str:'UINT16_T' ;special:false;keyword:m_all;op:NOTOKEN), (str:'UINT32_T' ;special:false;keyword:m_all;op:NOTOKEN), (str:'INT8_T' ;special:false;keyword:m_all;op:NOTOKEN), (str:'INT16_T' ;special:false;keyword:m_all;op:NOTOKEN), (str:'INT32_T' ;special:false;keyword:m_all;op:NOTOKEN), (str:'ELIF' ;special:false;keyword:m_all;op:NOTOKEN) ); var tokeninfo:ptokenarray; tokenidx:ptokenidx; procedure inittokens; procedure donetokens; procedure create_tokenidx; implementation procedure create_tokenidx; { create an index with the first and last token for every possible token length, so a search only will be done in that small part } var t : ttoken; i : longint; c : char; begin fillchar(tokenidx^,sizeof(tokenidx^),0); for t:=low(ttoken) to high(ttoken) do begin if not arraytokeninfo[t].special then begin i:=length(arraytokeninfo[t].str); c:=arraytokeninfo[t].str[1]; if ord(tokenidx^[i,c].first)=0 then tokenidx^[i,c].first:=t; tokenidx^[i,c].last:=t; end; end; end; procedure inittokens; begin if tokenidx = nil then begin tokeninfo:=@arraytokeninfo; new(tokenidx); create_tokenidx; end; end; procedure donetokens; begin if tokenidx <> nil then begin tokeninfo:=nil; dispose(tokenidx); tokenidx:=nil; end; end; end.
unit tfAlarm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ButtonPanel, StdCtrls, Spin, ExtCtrls, JvTFManager; type { TAlarmForm } TAlarmForm = class(TForm) ButtonPanel1: TButtonPanel; cmbTimeUnits: TComboBox; Label1: TLabel; EventLabel: TLabel; IsDueLabel: TLabel; Panel1: TPanel; TimeLabel: TLabel; Label5: TLabel; Label6: TLabel; seSnoozeTime: TSpinEdit; procedure OKButtonClick(Sender: TObject); private FSnooze: Boolean; FSnoozeMins: Integer; function GetSnoozeMins: Integer; procedure SetSnoozeMins(const AValue: Integer); public procedure SetAppt(AAppt: TJvTFAppt); property SnoozeMins: Integer read GetSnoozeMins write SetSnoozeMins; property Snooze: Boolean read FSnooze; end; var AlarmForm: TAlarmForm; implementation {$R *.lfm} { TAlarmForm } function TAlarmForm.GetSnoozeMins: Integer; begin case cmbTimeUnits.ItemIndex of 0: Result := seSnoozeTime.Value; 1: Result := seSnoozeTime.Value * 60; 2: Result := seSnoozeTime.Value * 60 * 24; end; end; procedure TAlarmForm.OKButtonClick(Sender: TObject); begin FSnooze := true; end; procedure TAlarmForm.SetAppt(AAppt: TJvTFAppt); var deltaMins: Integer; begin EventLabel.Caption := AAppt.Description; if AAppt.StartDate < Now() then begin IsDueLabel.Caption := 'is OVERDUE: '; TimeLabel.Caption := FormatDateTime('t', AAppt.StartTime); // 't' = ShortTimeFormat end else if AAppt.StartDate = Date() then begin IsDueLabel.caption := 'is due at '; TimeLabel.Caption := FormatDateTime('t', AAppt.StartTime); end else begin IsDueLabel.Caption := 'is due on '; TimeLabel.Caption := FormatDateTime('dddddd', AAppt.StartDateTime); // LongDateFormat end; end; procedure TAlarmForm.SetSnoozeMins(const AValue: Integer); begin FSnoozeMins := AValue; if FSnoozeMins <= 60 then begin cmbTimeUnits.ItemIndex := 0; // minutes seSnoozeTime.Value := FSnoozeMins; end else if FSnoozeMins <= 24*60 then begin cmbTimeUnits.ItemIndex := 1; // hours; seSnoozeTime.Value := FSnoozeMins div 24; end else begin cmbTimeUnits.ItemIndex := 2; // days seSnoozeTime.Value := FSnoozeMins div (24*60); end; end; end.
{ PROGRAM: LogonLogoffSkv.exe DESCRIPTION: Register the logon/logoff action of an account in Splunk SKV format USAGE: LogonLogoffSkv.exe \\vm70as006.rec.nsint\INDEXEDBYSPLUNK LOGON P LogonLogoffSkv.exe \\vm70as006.rec.nsint\INDEXEDBYSPLUNK LOGOFF T VERSION: 02 2014-11-13 PVDH Added Prod/Test release option in command line options. 01 2014-11-12 PVDH Initial version RETURNS: Nothing SUGGESTED UPDATES: 1) check for correct Paramstrings } program LogonLogoffSkv; {$mode objfpc} {$H+} uses Classes, SysUtils, StrUtils, USplunkFile, USupportLibrary; const VERSION = '01'; PROGRAM_ID = '000101'; procedure ProgramTitle(); begin WriteLn(); WriteLn(StringOfChar('-', 80)); WriteLn(GetProgramName() + ' -- Log the logon/logoff action of current account'); WriteLn(RightStr(StringOfChar(' ', 80) + PROGRAM_ID + ' ' + VERSION, 80)); WriteLn(StringOfChar('-', 80)); end; // of procedure ProgramTitle procedure ProgramUsage(); begin WriteLn(); WriteLn('Usage:'); WriteLn(Chr(9) + GetProgramName() + ' <share to store files> <action> <release>'); WriteLn(); WriteLn(Chr(9) + '<location>' + Chr(9) + 'Location to store the output store files, \\server\share'); WriteLn(Chr(9) + '<action>' + Chr(9) + 'LOGON or LOGOFF'); WriteLn(Chr(9) + '<release>' + Chr(9) + 'P(roduction) or T(est)'); WriteLn(); WriteLn('Example:'); WriteLn(Chr(9) + GetProgramName() + ' \\server\share\000101 LOGON P'); WriteLn(); end; // of procedure ProgramUsage procedure ProgramRun(share: string; action: string; release: string); var p: string; s: CSplunkFile; u: string; begin //WriteLn('user name: ' + GetCurrentUserName()); //WriteLn('share: ' + share); // WriteLn('action: ' + action); u := GetCurrentUserName(); p := share + '\' + PROGRAM_ID + '\' + release + '\' + GetDateFs() + '\' + GetCurrentComputerName() + '\' + u + '.skv'; WriteLn('Writing current ' + action + ' action for ' + u + ' to file ' + p); MakeFoldertree(p); s := CSplunkFile.Create(p); s.OpenFileWrite(); s.SetDate(); s.SetStatus('INFO'); s.AddKey('account', u, true); s.AddKey('action', action, true); s.WriteLineToFile(); s.CloseFile(); end; procedure ProgramTest(); begin //WriteLn(GetDrive('d:\folder1\folder1\file.txt')); //WriteLn(GetDrive('\\server\share\folder1\folder2\file.txt')); MakeFolderTree('\\vm70as006.rec.nsint\INDEXEDBYSPLUNK\000101\2014-11-13\file.txt'); MakeFolderTree('d:\folder1\folder1\file.txt'); MakeFolderTree('d:\folder1\folder2\folder3\folder4\folder5\folder6\file.txt'); end; // of procedure ProgramTest begin // ProgramTest(); ProgramTitle(); if ParamCount <> 3 then ProgramUsage() else begin ProgramRun(ParamStr(1), ParamStr(2), ParamStr(3)); end; end. // of main program LogonLogoffSkv
unit ResultAll; interface uses Classes,OlegFunction,SomeFunction,OlegMath; type TArguments=(aFe,aB,aT,aD); const DirectoryNames:array[TArguments]of string= ('Iron','Boron','Temperature','Thickness'); ShortDirectoryNames:array[TArguments]of string= ('Fe','Bo','T','d'); FileHeaderNames:array[TArguments]of string= ('N_Fe','N_B','T','d'); FileHeaderNew='nFsrh nFBsrh dnsrh nF nFB dn dnF dnFB'; type TArrayKeyStringList=class private function GetCount:word; procedure Initiate; public Keys:array of string; StringLists:array of TStringList; property Count:word read GetCount; Constructor Create(); function KeyIsPresent(Key:string):boolean; procedure AddKey(Key,SringKey:string); procedure AddKeysFromStringList(StringList:TStringList;PartNumber:word); procedure KeysAndListsToStringList(StringList:TStringList); procedure Free; procedure Clear; procedure SortingByKeyValue(); procedure CreateDirByKeys(Sault:string); procedure DataConvert(); end; TKeyStrList=class {зберігається фактично весь переформатований ResultAll.dat в KeysName назва параметра ('Fe','Bo','T','d') в Keys[i] - значення цього параметра в StringLists[i] - рядки де таке значення зустрічалося, рядки скорочені з точки зору відсутності самого Keys[i]; StringHeader - заголовок файлу ResultAll.dat за виключенням KeysName } private function GetCount:word; function GetSList(index:integer):TStringList; public KeysName:string; StringHeader:string; Keys:array of string; StringLists:array of TStringList; property Count:word read GetCount; property SList[index:integer]:TStringList read GetSList; class function KeysNameDetermine(fileHeader:string):string; class function BigFolderNameDetermine(KeysName:string):string; class function PartOfDataFileName(Key:string):string; procedure AddKey(Key,SringKey:string); {якщо Key вже є в наборі Keys, то SringKey додається у відповідний StringLists, інакше Key додається до Keys і створюється ще один StringLists з рядком SringKey} procedure AddKeysFromStringList(StringList:TStringList;PartNumber:word); {вважаючи, що у колонці PartNumber (нумерація з одиниці) StringList розташовані ключі, створюється набори даних ключ-набір рядків} procedure SortingByKeyValue(); procedure DataConvert(StartPosition:word=0); procedure KeysAndListsToStringList(StringList:TStringList); end; TArrKeyStrList=class {на верхньому рівні весь ResultAll.dat, розбитий на частини, кількість яких дорівнює кількості параметрів - наприклад 4 (Fe, Bo, T, d), ці частини знаходяться в ArrKeyStrList[i]; в нащадках fChields розміщюються розбиті на частинки вказані вище великі частини: фактично в ArrKeyStrList[i].StringLists[j] знаходиться міні-файл ResultAll.dat і вже він розбивається по параметрам; процес закінчується, коли залишається лише один параметр і розраховані величини, у відповідному нащадку лише нульовий елемент в ArrKeyStrList } private ArrKeyStrList:array of TKeyStrList; fFileNamePart:string; fChields:array of TArrKeyStrList; DirectoryPath:string; {шлях, куди будуть записуватися файли} fArgumentNumber:integer; public Constructor Create(SL:TStringList; DataNumber:integer=4; {DataNumber - кількість величин, які розраховувалися, за замовчуванням - чотири значення фактору неідеальності} FolderName:string=''; FileNamePart:string=''); // Parent:TArrKeyStrList=nil); destructor Destroy;override; procedure SaveData; end; implementation uses Dialogs, SysUtils, StrUtils; { TArrayKeyStringList } procedure TArrayKeyStringList.AddKey(Key, SringKey: string); var i:integer; begin // showmessage(inttostr(High(Keys))); for I := 0 to High(Keys) do if Key=Keys[i] then begin StringLists[i].Add(SringKey); Exit; end; SetLength(Keys,High(Keys)+2); SetLength(StringLists,High(StringLists)+2); StringLists[High(StringLists)]:=TStringList.Create; Keys[High(Keys)]:=Key; StringLists[High(StringLists)].Add(SringKey); end; procedure TArrayKeyStringList.AddKeysFromStringList(StringList: TStringList; PartNumber: word); var i:integer; begin for I := 0 to StringList.Count - 1 do AddKey(StringDataFromRow(StringList[i],PartNumber), DeleteStringDataFromRow(StringList[i],PartNumber)); end; procedure TArrayKeyStringList.Clear; begin Free; Initiate; end; procedure TArrayKeyStringList.Initiate; begin SetLength(Keys, 0); SetLength(StringLists, 0); end; constructor TArrayKeyStringList.Create; begin inherited Create; Initiate; end; procedure TArrayKeyStringList.CreateDirByKeys(Sault:string); var i:integer; begin for I := 0 to Count-1 do CreateDirSafety(Sault+ EditString(Keys[i])); end; procedure TArrayKeyStringList.DataConvert; var i:integer; begin for I := 0 to Count - 1 do StringLists[i][0]:=DataStringConvert(StringLists[i][0]); end; procedure TArrayKeyStringList.Free; var i:integer; begin for I := 0 to Count - 1 do StringLists[i].Free; end; function TArrayKeyStringList.GetCount: word; begin Result:=High(Keys)+1; end; function TArrayKeyStringList.KeyIsPresent(Key: string): boolean; var i:word; begin for I := 0 to High(Keys) do if Key=Keys[i] then begin Result:=True; Exit; end; Result:=False; end; procedure TArrayKeyStringList.KeysAndListsToStringList(StringList: TStringList); var i,j:integer; begin StringList.Clear; for I := 0 to Count - 1 do for j := 0 to StringLists[i].Count - 1 do StringList.Add(Keys[i]+' '+StringLists[i][j]); end; procedure TArrayKeyStringList.SortingByKeyValue; var KeyValue:array of double; i,j:integer; tempDouble:double; tempString:string; tempStringList:TStringList; begin tempStringList:=TStringList.Create; SetLength(KeyValue,Count); for I := 0 to Count - 1 do KeyValue[i]:=StrToFloat(Keys[i]); for I := 0 to High(KeyValue)-1 do for j := 0 to High(KeyValue)-1-i do if KeyValue[j]>KeyValue[j+1] then begin tempDouble:=KeyValue[j]; KeyValue[j]:=KeyValue[j+1]; KeyValue[j+1]:=tempDouble; tempString:=Keys[j]; Keys[j]:=Keys[j+1]; Keys[j+1]:=tempString; tempStringList.Assign(StringLists[j]); StringLists[j].Assign(StringLists[j+1]); StringLists[j+1].Assign(tempStringList); end; tempStringList.Free; end; { TArrKeyStrList } //procedure TArrKeyStrList.AddKey(Key, SringKey: string); // var i:integer; //begin // try // StrToFloat(Key); // for I := 0 to High(Keys) do // if Key=Keys[i] then // begin // StringLists[i].Add(SringKey); // Exit; // end; // SetLength(Keys,High(Keys)+2); // SetLength(StringLists,High(StringLists)+2); // StringLists[High(StringLists)]:=TStringList.Create; // Keys[High(Keys)]:=Key; // StringLists[High(StringLists)].Add(SringKey); // except // KeysName:=KeysNameDetermine(Key); // end; //end; constructor TArrKeyStrList.Create(SL: TStringList; DataNumber: integer; FolderName:string; FileNamePart:string); // Parent: TArrKeyStrList); var i,j:integer; begin inherited Create; // fParent:=Parent; // if fParent=nil then DirectoryPath:=GetCurrentDir; if FolderName='' then DirectoryPath:=GetCurrentDir else DirectoryPath:=FolderName; fFileNamePart:=FileNamePart; fArgumentNumber:=NumberOfSubstringInRow(SL[0])-DataNumber; if (FileNamePart<>'')and(fArgumentNumber>1) then DirectoryPath:=DirectoryPath+'\'+FileNamePart; SetLength(ArrKeyStrList,fArgumentNumber); for I := 0 to High(ArrKeyStrList) do begin ArrKeyStrList[i]:=TKeyStrList.Create; ArrKeyStrList[i].AddKeysFromStringList(SL,i+1); ArrKeyStrList[i].SortingByKeyValue; end; SetLength(fChields,0); if fArgumentNumber>1 then begin for I := 0 to High(ArrKeyStrList) do for j := 0 to ArrKeyStrList[i].Count-1 do begin SetLength(fChields,High(fChields)+2); fChields[High(fChields)]:= TArrKeyStrList.Create(ArrKeyStrList[i].StringLists[j], DataNumber, DirectoryPath +'\' +TKeyStrList.BigFolderNameDetermine(ArrKeyStrList[i].KeysName), fFileNamePart +ArrKeyStrList[i].KeysName +TKeyStrList.PartOfDataFileName(ArrKeyStrList[i].Keys[j])); end; end; end; //function TArrKeyStrList.KeysNameDetermine(fileHeader: string): string; // var i:TArguments; //begin // for I := Low(TArguments) to High(TArguments) do // if fileHeader=FileHeaderNames[i] then // begin // Result:=ShortDirectoryNames[i]; // Exit; // end; // Result:='None'; //end; { TKeyStrList } procedure TKeyStrList.AddKey(Key, SringKey: string); var i:integer; begin try StrToFloat(Key); for I := 0 to High(Keys) do if Key=Keys[i] then begin StringLists[i].Add(SringKey); Exit; end; SetLength(Keys,High(Keys)+2); SetLength(StringLists,High(StringLists)+2); StringLists[High(StringLists)]:=TStringList.Create; Keys[High(Keys)]:=Key; StringLists[High(StringLists)].Add(StringHeader); StringLists[High(StringLists)].Add(SringKey); except KeysName:=KeysNameDetermine(Key); StringHeader:=SringKey; end; end; procedure TKeyStrList.AddKeysFromStringList(StringList: TStringList; PartNumber: word); var i:integer; begin for I := 0 to StringList.Count - 1 do AddKey(StringDataFromRow(StringList[i],PartNumber), DeleteStringDataFromRow(StringList[i],PartNumber)); end; class function TKeyStrList.BigFolderNameDetermine(KeysName: string): string; var i:TArguments; begin for I := Low(TArguments) to High(TArguments) do if KeysName=ShortDirectoryNames[i] then begin Result:=DirectoryNames[i]; Exit; end; Result:='None'; end; procedure TKeyStrList.DataConvert(StartPosition:word=0); var i,j:integer; tempstr,header:string; begin for I := 0 to Count - 1 do begin for j := 1 to StringLists[i].Count-1 do StringLists[i][j]:=DataStringConvertNew(StringLists[i][j],StartPosition); header:=StringLists[0][0]; StringLists[i].Delete(0); tempstr:=''; for j := 1 to StartPosition do tempstr:=tempstr+StringDataFromRow(header,j)+' '; StringLists[i].Insert(0,tempstr+FileHeaderNew); end; end; function TKeyStrList.GetCount: word; begin Result:=High(Keys)+1; end; function TKeyStrList.GetSList(index: integer): TStringList; begin Result:=StringLists[index]; end; procedure TKeyStrList.KeysAndListsToStringList(StringList: TStringList); var i,j:integer; begin StringList.Clear; for I := 0 to Count - 1 do for j := 1 to StringLists[i].Count - 1 do StringList.Add(Keys[i]+' '+StringLists[i][j]); StringList.Insert(0,KeysName+' '+StringLists[0][0]); end; class function TKeyStrList.KeysNameDetermine(fileHeader: string): string; var i:TArguments; begin for I := Low(TArguments) to High(TArguments) do if fileHeader=FileHeaderNames[i] then begin Result:=ShortDirectoryNames[i]; Exit; end; Result:='None'; end; class function TKeyStrList.PartOfDataFileName(Key: string): string; begin if (AnsiPos ('e',Key)>0)or(AnsiPos ('E',Key)>0) then Result:=Key[1]+Key[3]+AnsiRightStr(Key, 1) else Result:=Key[2]+Key[3]; end; procedure TKeyStrList.SortingByKeyValue; var KeyValue:array of double; i,j:integer; // tempDouble:double; // tempString:string; tempStringList:TStringList; begin tempStringList:=TStringList.Create; SetLength(KeyValue,Count); for I := 0 to Count - 1 do KeyValue[i]:=StrToFloat(Keys[i]); for I := 0 to High(KeyValue)-1 do for j := 0 to High(KeyValue)-1-i do if KeyValue[j]>KeyValue[j+1] then begin SwapRound(KeyValue[j],KeyValue[j+1]); // tempDouble:=KeyValue[j]; // KeyValue[j]:=KeyValue[j+1]; // KeyValue[j+1]:=tempDouble; SwapRound(Keys[j],Keys[j+1]); // tempString:=Keys[j]; // Keys[j]:=Keys[j+1]; // Keys[j+1]:=tempString; tempStringList.Assign(StringLists[j]); StringLists[j].Assign(StringLists[j+1]); StringLists[j+1].Assign(tempStringList); end; tempStringList.Free; end; destructor TArrKeyStrList.Destroy; var i:integer; begin for I := 0 to High(fChields) do fChields[i].Free; for I := 0 to High(ArrKeyStrList) do ArrKeyStrList[i].Free; inherited; end; procedure TArrKeyStrList.SaveData; var i,j,k:integer; tempStr,tempStr2:string; SimpleDataFile:TStringList; DataNumber:integer; ValueName:string; begin SimpleDataFile:=TStringList.Create; if fArgumentNumber=1 then begin SetCurrentDir(DirectoryPath); ArrKeyStrList[0].DataConvert; ArrKeyStrList[0].KeysAndListsToStringList(SimpleDataFile); SimpleDataFile.SaveToFile(fFileNamePart+'_' +ArrKeyStrList[0].KeysName +'.dat'); SimpleDataFile.Free; Exit; end; for I := 0 to High(ArrKeyStrList) do begin SetCurrentDir(DirectoryPath); tempStr:=TKeyStrList.BigFolderNameDetermine(ArrKeyStrList[i].KeysName); while not(SetCurrentDir(DirectoryPath+'\'+tempStr)) do MkDir(tempStr); end; if fArgumentNumber>2 then begin for I := 0 to High(ArrKeyStrList) do begin tempStr:=DirectoryPath+'\' +TKeyStrList.BigFolderNameDetermine(ArrKeyStrList[i].KeysName); for j := 0 to ArrKeyStrList[i].Count - 1 do begin SetCurrentDir(tempStr); tempStr2:=fFileNamePart +ArrKeyStrList[i].KeysName +TKeyStrList.PartOfDataFileName(ArrKeyStrList[i].Keys[j]); while not(SetCurrentDir(tempStr+'\'+tempStr2)) do MkDir(tempStr2); end; end; end; for I := 0 to High(fChields) do fChields[i].SaveData; if fArgumentNumber=2 then begin tempStr:=DirectoryPath; Delete(tempStr, AnsiPos(fFileNamePart,DirectoryPath)-1, Length(fFileNamePart)+1); SetCurrentDir(tempStr); ArrKeyStrList[0].DataConvert(1); // for j := 0 to ArrKeyStrList[0].Count-1 do // ArrKeyStrList[0].StringLists[j].SaveToFile('aa'+ArrKeyStrList[0].Keys[j]+'.dat'); // DataNumber:=NumberOfSubstringInRow(ArrKeyStrList[0].StringLists[0][0])-1; for I := 1 to DataNumber do begin ValueName:=StringDataFromRow(ArrKeyStrList[0].StringLists[0][0],1+i); while not(SetCurrentDir(tempStr+'\'+ValueName)) do MkDir(ValueName); SimpleDataFile.Clear; tempStr2:=StringDataFromRow(ArrKeyStrList[0].StringLists[0][0],1); for j := 0 to ArrKeyStrList[0].Count-1 do tempStr2:=tempStr2+' '+ArrKeyStrList[0].KeysName +TKeyStrList.PartOfDataFileName(ArrKeyStrList[0].Keys[j]); SimpleDataFile.Add(tempStr2); tempStr2:=ArrKeyStrList[0].KeysName; for j := 0 to ArrKeyStrList[0].Count-1 do tempStr2:=tempStr2+' '+LogKey(ArrKeyStrList[0].Keys[j]); SimpleDataFile.Add(tempStr2); for k := 1 to ArrKeyStrList[0].StringLists[0].Count - 1 do begin tempStr2:=LogKey(StringDataFromRow(ArrKeyStrList[0].StringLists[0][k],1)); for j := 0 to ArrKeyStrList[0].Count-1 do tempStr2:=tempStr2+' '+StringDataFromRow(ArrKeyStrList[0].StringLists[j][k],1+i); SimpleDataFile.Add(tempStr2); end; SimpleDataFile.SaveToFile(ValueName+'_' +fFileNamePart+'_' +ArrKeyStrList[0].KeysName +'.dat'); SetCurrentDir(tempStr); end; // SetCurrentDir(tempStr); SimpleDataFile.Clear; for I := 0 to ArrKeyStrList[1].Count-1 do for j := 0 to ArrKeyStrList[0].Count-1 do for k := 1 to ArrKeyStrList[0].StringLists[j].Count - 1 do if (ArrKeyStrList[1].Keys[i]=StringDataFromRow(ArrKeyStrList[0].StringLists[j][k],1)) then SimpleDataFile.Add(LogKey(ArrKeyStrList[1].Keys[i]) +' '+LogKey(ArrKeyStrList[0].Keys[j]) +' ' +DeleteStringDataFromRow(ArrKeyStrList[0].StringLists[j][k],1)); SimpleDataFile.Insert(0,ArrKeyStrList[1].KeysName +' '+ArrKeyStrList[0].KeysName+' ' +DeleteStringDataFromRow(ArrKeyStrList[0].StringLists[0][0],1)); SimpleDataFile.SaveToFile(fFileNamePart+'_' +ArrKeyStrList[1].KeysName +ArrKeyStrList[0].KeysName +'.dat'); ArrKeyStrList[1].DataConvert(1); DataNumber:=NumberOfSubstringInRow(ArrKeyStrList[1].StringLists[0][0])-1; for I := 1 to DataNumber do begin ValueName:=StringDataFromRow(ArrKeyStrList[1].StringLists[0][0],1+i); SetCurrentDir(tempStr+'\'+ValueName); SimpleDataFile.Clear; tempStr2:=StringDataFromRow(ArrKeyStrList[1].StringLists[0][0],1); for j := 0 to ArrKeyStrList[1].Count-1 do tempStr2:=tempStr2+' '+ArrKeyStrList[1].KeysName +TKeyStrList.PartOfDataFileName(ArrKeyStrList[1].Keys[j]); SimpleDataFile.Add(tempStr2); tempStr2:=ArrKeyStrList[1].KeysName; for j := 0 to ArrKeyStrList[1].Count-1 do tempStr2:=tempStr2+' '+LogKey(ArrKeyStrList[1].Keys[j]); SimpleDataFile.Add(tempStr2); for k := 1 to ArrKeyStrList[1].StringLists[0].Count - 1 do begin tempStr2:=LogKey(StringDataFromRow(ArrKeyStrList[1].StringLists[0][k],1)); for j := 0 to ArrKeyStrList[1].Count-1 do tempStr2:=tempStr2+' '+StringDataFromRow(ArrKeyStrList[1].StringLists[j][k],1+i); SimpleDataFile.Add(tempStr2); end; SimpleDataFile.SaveToFile(ValueName+'_' +fFileNamePart+'_' +ArrKeyStrList[1].KeysName +'.dat'); SetCurrentDir(tempStr); end; end; SimpleDataFile.Free; end; // if FolderName='' then DirectoryPath:=GetCurrentDir // else DirectoryPath:=FolderName; // // if FileNamePart<>'' then DirectoryPath:=DirectoryPath+FileNamePart; // // fFileNamePart:=FileNamePart; // fArgumentNumber:=NumberOfSubstringInRow(SL[0])-DataNumber; // SetLength(ArrKeyStrList,fArgumentNumber); // for I := 0 to High(ArrKeyStrList) do // begin // ArrKeyStrList[i]:=TKeyStrList.Create; // ArrKeyStrList[i].AddKeysFromStringList(SL,i+1); // ArrKeyStrList[i].SortingByKeyValue; // end; // // SetLength(fChields,0); // // if fArgumentNumber>1 then // begin // for I := 0 to High(ArrKeyStrList) do // for j := 0 to ArrKeyStrList[i].Count-1 do // begin // SetLength(fChields,High(fChields)+2); // fChields[High(fChields)]:= // TArrKeyStrList.Create(ArrKeyStrList[i].StringLists[j], // DataNumber, // DirectoryPath // +'\' // +TKeyStrList.BigFolderNameDetermine(ArrKeyStrList[i].KeysName), // ArrKeyStrList[i].KeysName+TKeyStrList.PartOfDataFileName(ArrKeyStrList[i].Keys[j])); // end; // end; end.
unit ServerConsts; interface const JWT_SECRET: string = 'EREWR6DF8S7FSDF7SDFS9F7FSF7SFSFSNF'; API_VERSION: string = '1.00'; implementation end.
unit UnitTransfersManager; interface uses Windows, SocketUnit, UnitConstants, UnitVariables, UnitFunctions, UnitConfiguration, UnitInformations, UnitConnection; procedure SendFile(Filename: string; Filesize, Begining: Int64); function ReceiveFile(Filename, Destination: string; Filesize: Int64; ToSend: string): Boolean; implementation procedure SendFile(Filename: string; Filesize, Begining: Int64); var Buffer: array[0..32767] of Byte; F: file; Count: Integer; TmpStr: string; ClientSocket: TClientSocket; begin _SendDatas(ClientSocket, FILESMANAGER + '|' + FILESDOWNLOADFILE + '|' + Filename + '|' + IntToStr(Filesize) + '|'); try FileMode := $0000; AssignFile(F, Filename); Reset(F, 1); if Begining > 0 then Seek(F, Begining); while not EOF(F) and ClientSocket.Connected do begin BlockRead(F, Buffer, 32768, Count); ClientSocket.SendBuffer(Buffer, Count); end; finally CloseFile(F); end; end; function ReceiveFile(Filename, Destination: string; Filesize: Int64; ToSend: string): Boolean; var Buffer: array[0..32768] of Byte; F: file; iRecv, sRecv, j: Integer; TmpStr: string; ClientSocket: TClientSocket; begin Result := False; _SendDatas(ClientSocket, ToSend + '|' + Filename); try AssignFile(F, Destination); Rewrite(F, 1); iRecv := 0; sRecv := 0; while (iRecv < Filesize) and (ClientSocket.Connected) do begin sRecv := ClientSocket.ReceiveBuffer(Buffer, SizeOf(Buffer)); iRecv := iRecv + sRecv; BlockWrite(F, Buffer, sRecv, j); j := sRecv; end; except CloseFile(F); Exit; end; CloseFile(F); Result := True; end; end.
unit TrackLoginsUnit; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, DB, DBTables; Procedure TrackUserLogin(UserID : String; ActionType : Integer); const lgIn = 0; lgOut = 1; implementation {===================================================================} Function GetComputerNameAsString : String; const MAX_COMPUTERNAME_LENGTH = 15; var Name : array[0..MAX_COMPUTERNAME_LENGTH] of Char; Size : DWORD; begin Size := SizeOf(Name) div SizeOf(Name[0]); try If GetComputerName(Name, Size) then Result := Name else Result := ''; except Result := ''; end; end; {GetComputerNameAsString} {===================================================================} Procedure TrackUserLogin(UserID : String; ActionType : Integer); {CHG03222004-1(2.08): Track user logins.} var LoginTable : TTable; begin LoginTable := TTable.Create(nil); with LoginTable do begin DatabaseName := 'PASsystem'; TableName := 'LoginTrackingTable'; TableType := ttDBase; try Open; Insert; FieldByName('UserID').Text := UserID; FieldByName('Action').AsInteger := ActionType; FieldByName('Date').AsDateTime := Date; FieldByName('Time').AsDateTime := Now; FieldByName('MachineName').Text := GetComputerNameAsString; Post; except {Ignore the exception.} end; end; {with LoginTable do} end; {TrackUserLogins} end.
unit uFIFO_async; interface uses windows, sysutils, math, uFIFO_rec; {$Q-} {$R-} type tFIFO_async=class private fifo_buffer : array of byte; crit_section_read :_RTL_CRITICAL_SECTION; crit_section_write :_RTL_CRITICAL_SECTION; function get_size : integer; function get_free : integer; function get_count : integer; function get_stat : tFIFO_rec_stat; protected fifo : pFIFO_rec; fixed_size : integer; fifo_data_ptr : pointer; string_read : string; string_next : boolean; procedure delete_objects; procedure read_begin;virtual; procedure read_end;virtual; procedure write_begin; virtual; procedure write_end;virtual; public constructor create(v_size : integer); destructor destroy;override; procedure write(buffer:pointer; buf_size:integer); procedure read(buffer:pointer; buf_size:integer); procedure read_void(buf_size:integer); procedure write_string(str:string); function read_string(var str:string) : boolean; procedure reset; procedure reset_stats; procedure reset_stats_exchange(var v_stats:tFIFO_rec_stat); function ratio_free:integer; function ratio_count:integer; property bytes_size : integer read get_size; property bytes_count : integer read get_count; property bytes_free : integer read get_free; property stat : tFIFO_rec_stat read get_stat; end; implementation uses classes; procedure _inf(var v); begin end; constructor tFIFO_async.create(v_size : integer); begin inherited create(); new(fifo); _FIFO_rec_init(fifo^, v_size, fixed_size); setlength(fifo_buffer, fixed_size); fifo_data_ptr := @(fifo_buffer[0]); InitializeCriticalSection(crit_section_read); InitializeCriticalSection(crit_section_write); end; destructor tFIFO_async.destroy; begin delete_objects; DeleteCriticalSection(crit_section_read); DeleteCriticalSection(crit_section_write); inherited destroy; end; procedure tFIFO_async.delete_objects; begin setlength(fifo_buffer, 0); fifo_buffer := nil; fifo_data_ptr := nil; if fifo <> nil then dispose(fifo); fifo := nil; end; procedure tFIFO_async.reset; begin if self=nil then exit; if fifo = nil then exit; _FIFO_rec_reset(fifo^); end; function tFIFO_async.get_count; begin result:=0; if self = nil then exit; if fifo = nil then exit; result := _FIFO_rec_count(fifo^, fixed_size); end; function tFIFO_async.get_free; begin result := 0; if self = nil then exit; if fifo = nil then exit; result := _FIFO_rec_free(fifo^, fixed_size); end; procedure tFIFO_async.write(buffer:pointer; buf_size:integer); begin if self=nil then exit; if fifo = nil then exit; if fifo_data_ptr = nil then exit; if buffer = nil then exit; if bytes_size = 0 then exit; write_begin; _FIFO_rec_write(fifo^, fifo_data_ptr, fixed_size, buffer, buf_size); write_end; end; procedure tFIFO_async.read(buffer:pointer;buf_size:integer); begin if self=nil then exit; if fifo = nil then exit; if fifo_data_ptr = nil then exit; if buffer = nil then exit; if bytes_size = 0 then exit; read_begin; _FIFO_rec_read(fifo^, fifo_data_ptr, fixed_size, buffer, buf_size); read_end; end; procedure tFIFO_async.read_void(buf_size:integer); begin if self=nil then exit; if bytes_size = 0 then exit; if fifo = nil then exit; read_begin; _FIFO_rec_read_void(fifo^, fixed_size, buf_size); read_end; end; procedure tFIFO_async.reset_stats; begin if self = nil then exit; if fifo = nil then exit; _FIFO_rec_stat_reset(fifo^); end; procedure tFIFO_async.reset_stats_exchange(var v_stats:tFIFO_rec_stat); begin if self = nil then exit; if fifo = nil then exit; v_stats := fifo^.stat; _FIFO_rec_stat_reset(fifo^); end; function tFIFO_async.ratio_count:integer; begin result := 0; if self = nil then exit; if fifo = nil then exit; result:=_FIFO_rec_count_ratio(fifo^, fixed_size); end; function tFIFO_async.ratio_free:integer; begin result := 0; if self = nil then exit; if fifo = nil then exit; result:=_FIFO_rec_free_ratio(fifo^, fixed_size); end; function tFIFO_async.get_stat : tFIFO_rec_stat; begin fillchar(result, sizeof(result), 0); if self = nil then exit; if fifo = nil then exit; result := fifo^.stat; end; function tFIFO_async.get_size : integer; begin result := 0; if self = nil then exit; if fifo = nil then exit; result := fixed_size; end; procedure tFIFO_async.write_string(str:string); var bytes : integer; begin if fifo = nil then exit; str := str + #13; string_next := true; bytes := length(str)*sizeof(str[1]); if self.bytes_free < bytes*3 then inc(fifo^.stat.writed.errors, bytes) else self.write(@str[1], bytes); end; function tFIFO_async.read_string(var str:string) : boolean; var buf : array [0..4095] of char; cnt : integer; pos : integer; begin result := false; str := ''; if string_next then begin cnt := min(sizeof(buf)-1, self.bytes_count); if cnt <> 0 then begin fillchar(buf, sizeof(buf), 0); self.read(@buf[0], cnt); cnt := cnt div sizeof(buf[0]); pos := length(string_read) + 1; setlength(string_read, length(string_read) + cnt); move(buf[0], string_read[pos], cnt*sizeof(char)); end else exit; end; pos := 1; cnt := length(string_read); while cnt > 0 do begin if string_read[pos] in [#0, #13] then break; inc(pos); dec(cnt); end; if cnt = 0 then if length(string_read) > length(buf)*2 then begin str := string_read; string_read := ''; string_next := false; result := length(str) > 0; exit; end else begin string_next := true; exit; end; str := copy(string_read, 1, pos-1); delete(string_read, 1, pos); string_next := length(string_read) = 0; result := true; end; procedure tFIFO_async.read_begin; begin if self = nil then exit; EnterCriticalSection(crit_section_read); end; procedure tFIFO_async.read_end; begin if self = nil then exit; LeaveCriticalSection(crit_section_read); end; procedure tFIFO_async.write_begin; begin if self = nil then exit; EnterCriticalSection(crit_section_read); end; procedure tFIFO_async.write_end; begin if self = nil then exit; LeaveCriticalSection(crit_section_read); end; end.
(************************************************************************* Copyright (c) 2007, Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit mannwhitneyu; interface uses Math, Sysutils, Ap; procedure MannWhitneyUTest(const X : TReal1DArray; N : AlglibInteger; const Y : TReal1DArray; M : AlglibInteger; var BothTails : AlglibFloat; var LeftTail : AlglibFloat; var RightTail : AlglibFloat); implementation procedure UCheb(X : AlglibFloat; C : AlglibFloat; var TJ : AlglibFloat; var TJ1 : AlglibFloat; var R : AlglibFloat);forward; function UNInterpolate(P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; N : AlglibInteger):AlglibFloat;forward; function USigma000(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma075(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma150(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma225(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma300(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma333(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma367(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function USigma400(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; function UTblN5N5(S : AlglibFloat):AlglibFloat;forward; function UTblN5N6(S : AlglibFloat):AlglibFloat;forward; function UTblN5N7(S : AlglibFloat):AlglibFloat;forward; function UTblN5N8(S : AlglibFloat):AlglibFloat;forward; function UTblN5N9(S : AlglibFloat):AlglibFloat;forward; function UTblN5N10(S : AlglibFloat):AlglibFloat;forward; function UTblN5N11(S : AlglibFloat):AlglibFloat;forward; function UTblN5N12(S : AlglibFloat):AlglibFloat;forward; function UTblN5N13(S : AlglibFloat):AlglibFloat;forward; function UTblN5N14(S : AlglibFloat):AlglibFloat;forward; function UTblN5N15(S : AlglibFloat):AlglibFloat;forward; function UTblN5N16(S : AlglibFloat):AlglibFloat;forward; function UTblN5N17(S : AlglibFloat):AlglibFloat;forward; function UTblN5N18(S : AlglibFloat):AlglibFloat;forward; function UTblN5N19(S : AlglibFloat):AlglibFloat;forward; function UTblN5N20(S : AlglibFloat):AlglibFloat;forward; function UTblN5N21(S : AlglibFloat):AlglibFloat;forward; function UTblN5N22(S : AlglibFloat):AlglibFloat;forward; function UTblN5N23(S : AlglibFloat):AlglibFloat;forward; function UTblN5N24(S : AlglibFloat):AlglibFloat;forward; function UTblN5N25(S : AlglibFloat):AlglibFloat;forward; function UTblN5N26(S : AlglibFloat):AlglibFloat;forward; function UTblN5N27(S : AlglibFloat):AlglibFloat;forward; function UTblN5N28(S : AlglibFloat):AlglibFloat;forward; function UTblN5N29(S : AlglibFloat):AlglibFloat;forward; function UTblN5N30(S : AlglibFloat):AlglibFloat;forward; function UTblN5N100(S : AlglibFloat):AlglibFloat;forward; function UTblN6N6(S : AlglibFloat):AlglibFloat;forward; function UTblN6N7(S : AlglibFloat):AlglibFloat;forward; function UTblN6N8(S : AlglibFloat):AlglibFloat;forward; function UTblN6N9(S : AlglibFloat):AlglibFloat;forward; function UTblN6N10(S : AlglibFloat):AlglibFloat;forward; function UTblN6N11(S : AlglibFloat):AlglibFloat;forward; function UTblN6N12(S : AlglibFloat):AlglibFloat;forward; function UTblN6N13(S : AlglibFloat):AlglibFloat;forward; function UTblN6N14(S : AlglibFloat):AlglibFloat;forward; function UTblN6N15(S : AlglibFloat):AlglibFloat;forward; function UTblN6N30(S : AlglibFloat):AlglibFloat;forward; function UTblN6N100(S : AlglibFloat):AlglibFloat;forward; function UTblN7N7(S : AlglibFloat):AlglibFloat;forward; function UTblN7N8(S : AlglibFloat):AlglibFloat;forward; function UTblN7N9(S : AlglibFloat):AlglibFloat;forward; function UTblN7N10(S : AlglibFloat):AlglibFloat;forward; function UTblN7N11(S : AlglibFloat):AlglibFloat;forward; function UTblN7N12(S : AlglibFloat):AlglibFloat;forward; function UTblN7N13(S : AlglibFloat):AlglibFloat;forward; function UTblN7N14(S : AlglibFloat):AlglibFloat;forward; function UTblN7N15(S : AlglibFloat):AlglibFloat;forward; function UTblN7N30(S : AlglibFloat):AlglibFloat;forward; function UTblN7N100(S : AlglibFloat):AlglibFloat;forward; function UTblN8N8(S : AlglibFloat):AlglibFloat;forward; function UTblN8N9(S : AlglibFloat):AlglibFloat;forward; function UTblN8N10(S : AlglibFloat):AlglibFloat;forward; function UTblN8N11(S : AlglibFloat):AlglibFloat;forward; function UTblN8N12(S : AlglibFloat):AlglibFloat;forward; function UTblN8N13(S : AlglibFloat):AlglibFloat;forward; function UTblN8N14(S : AlglibFloat):AlglibFloat;forward; function UTblN8N15(S : AlglibFloat):AlglibFloat;forward; function UTblN8N30(S : AlglibFloat):AlglibFloat;forward; function UTblN8N100(S : AlglibFloat):AlglibFloat;forward; function UTblN9N9(S : AlglibFloat):AlglibFloat;forward; function UTblN9N10(S : AlglibFloat):AlglibFloat;forward; function UTblN9N11(S : AlglibFloat):AlglibFloat;forward; function UTblN9N12(S : AlglibFloat):AlglibFloat;forward; function UTblN9N13(S : AlglibFloat):AlglibFloat;forward; function UTblN9N14(S : AlglibFloat):AlglibFloat;forward; function UTblN9N15(S : AlglibFloat):AlglibFloat;forward; function UTblN9N30(S : AlglibFloat):AlglibFloat;forward; function UTblN9N100(S : AlglibFloat):AlglibFloat;forward; function UTblN10N10(S : AlglibFloat):AlglibFloat;forward; function UTblN10N11(S : AlglibFloat):AlglibFloat;forward; function UTblN10N12(S : AlglibFloat):AlglibFloat;forward; function UTblN10N13(S : AlglibFloat):AlglibFloat;forward; function UTblN10N14(S : AlglibFloat):AlglibFloat;forward; function UTblN10N15(S : AlglibFloat):AlglibFloat;forward; function UTblN10N30(S : AlglibFloat):AlglibFloat;forward; function UTblN10N100(S : AlglibFloat):AlglibFloat;forward; function UTblN11N11(S : AlglibFloat):AlglibFloat;forward; function UTblN11N12(S : AlglibFloat):AlglibFloat;forward; function UTblN11N13(S : AlglibFloat):AlglibFloat;forward; function UTblN11N14(S : AlglibFloat):AlglibFloat;forward; function UTblN11N15(S : AlglibFloat):AlglibFloat;forward; function UTblN11N30(S : AlglibFloat):AlglibFloat;forward; function UTblN11N100(S : AlglibFloat):AlglibFloat;forward; function UTblN12N12(S : AlglibFloat):AlglibFloat;forward; function UTblN12N13(S : AlglibFloat):AlglibFloat;forward; function UTblN12N14(S : AlglibFloat):AlglibFloat;forward; function UTblN12N15(S : AlglibFloat):AlglibFloat;forward; function UTblN12N30(S : AlglibFloat):AlglibFloat;forward; function UTblN12N100(S : AlglibFloat):AlglibFloat;forward; function UTblN13N13(S : AlglibFloat):AlglibFloat;forward; function UTblN13N14(S : AlglibFloat):AlglibFloat;forward; function UTblN13N15(S : AlglibFloat):AlglibFloat;forward; function UTblN13N30(S : AlglibFloat):AlglibFloat;forward; function UTblN13N100(S : AlglibFloat):AlglibFloat;forward; function UTblN14N14(S : AlglibFloat):AlglibFloat;forward; function UTblN14N15(S : AlglibFloat):AlglibFloat;forward; function UTblN14N30(S : AlglibFloat):AlglibFloat;forward; function UTblN14N100(S : AlglibFloat):AlglibFloat;forward; function USigma(S : AlglibFloat; N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat;forward; (************************************************************************* Mann-Whitney U-test This test checks hypotheses about whether X and Y are samples of two continuous distributions of the same shape and same median or whether their medians are different. The following tests are performed: * two-tailed test (null hypothesis - the medians are equal) * left-tailed test (null hypothesis - the median of the first sample is greater than or equal to the median of the second sample) * right-tailed test (null hypothesis - the median of the first sample is less than or equal to the median of the second sample). Requirements: * the samples are independent * X and Y are continuous distributions (or discrete distributions well- approximating continuous distributions) * distributions of X and Y have the same shape. The only possible difference is their position (i.e. the value of the median) * the number of elements in each sample is not less than 5 * the scale of measurement should be ordinal, interval or ratio (i.e. the test could not be applied to nominal variables). The test is non-parametric and doesn't require distributions to be normal. Input parameters: X - sample 1. Array whose index goes from 0 to N-1. N - size of the sample. N>=5 Y - sample 2. Array whose index goes from 0 to M-1. M - size of the sample. M>=5 Output parameters: BothTails - p-value for two-tailed test. If BothTails is less than the given significance level the null hypothesis is rejected. LeftTail - p-value for left-tailed test. If LeftTail is less than the given significance level, the null hypothesis is rejected. RightTail - p-value for right-tailed test. If RightTail is less than the given significance level the null hypothesis is rejected. To calculate p-values, special approximation is used. This method lets us calculate p-values with satisfactory accuracy in interval [0.0001, 1]. There is no approximation outside the [0.0001, 1] interval. Therefore, if the significance level outlies this interval, the test returns 0.0001. Relative precision of approximation of p-value: N M Max.err. Rms.err. 5..10 N..10 1.4e-02 6.0e-04 5..10 N..100 2.2e-02 5.3e-06 10..15 N..15 1.0e-02 3.2e-04 10..15 N..100 1.0e-02 2.2e-05 15..100 N..100 6.1e-03 2.7e-06 For N,M>100 accuracy checks weren't put into practice, but taking into account characteristics of asymptotic approximation used, precision should not be sharply different from the values for interval [5, 100]. -- ALGLIB -- Copyright 09.04.2007 by Bochkanov Sergey *************************************************************************) procedure MannWhitneyUTest(const X : TReal1DArray; N : AlglibInteger; const Y : TReal1DArray; M : AlglibInteger; var BothTails : AlglibFloat; var LeftTail : AlglibFloat; var RightTail : AlglibFloat); var I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; T : AlglibInteger; Tmp : AlglibFloat; TmpI : AlglibInteger; NS : AlglibInteger; R : TReal1DArray; C : TInteger1DArray; U : AlglibFloat; P : AlglibFloat; MP : AlglibFloat; S : AlglibFloat; Sigma : AlglibFloat; Mu : AlglibFloat; TieCount : AlglibInteger; TieSize : TInteger1DArray; begin // // Prepare // if (N<=4) or (M<=4) then begin BothTails := 1.0; LeftTail := 1.0; RightTail := 1.0; Exit; end; NS := N+M; SetLength(R, NS-1+1); SetLength(C, NS-1+1); I:=0; while I<=N-1 do begin R[I] := X[I]; C[I] := 0; Inc(I); end; I:=0; while I<=M-1 do begin R[N+I] := Y[I]; C[N+I] := 1; Inc(I); end; // // sort {R, C} // if NS<>1 then begin i := 2; repeat t := i; while t<>1 do begin k := t div 2; if AP_FP_Greater_Eq(R[k-1],R[t-1]) then begin t := 1; end else begin Tmp := R[k-1]; R[k-1] := R[t-1]; R[t-1] := Tmp; TmpI := C[k-1]; C[k-1] := C[t-1]; C[t-1] := TmpI; t := k; end; end; i := i+1; until not (i<=NS); i := NS-1; repeat Tmp := R[i]; R[i] := R[0]; R[0] := Tmp; TmpI := C[i]; C[i] := C[0]; C[0] := TmpI; t := 1; while t<>0 do begin k := 2*t; if k>i then begin t := 0; end else begin if k<i then begin if AP_FP_Greater(R[k],R[k-1]) then begin k := k+1; end; end; if AP_FP_Greater_Eq(R[t-1],R[k-1]) then begin t := 0; end else begin Tmp := R[k-1]; R[k-1] := R[t-1]; R[t-1] := Tmp; TmpI := C[k-1]; C[k-1] := C[t-1]; C[t-1] := TmpI; t := k; end; end; end; i := i-1; until not (i>=1); end; // // compute tied ranks // I := 0; TieCount := 0; SetLength(TieSize, NS-1+1); while I<=NS-1 do begin J := I+1; while J<=NS-1 do begin if AP_FP_Neq(R[J],R[I]) then begin Break; end; J := J+1; end; K:=I; while K<=J-1 do begin R[K] := 1+AP_Double((I+J-1))/2; Inc(K); end; TieSize[TieCount] := J-I; TieCount := TieCount+1; I := J; end; // // Compute U // U := 0; I:=0; while I<=NS-1 do begin if C[I]=0 then begin U := U+R[I]; end; Inc(I); end; U := N*M+N*(N+1) div 2-U; // // Result // Mu := AP_Double(N*M)/2; Tmp := NS*(AP_Sqr(NS)-1)/12; I:=0; while I<=TieCount-1 do begin Tmp := Tmp-TieSize[I]*(AP_Sqr(TieSize[I])-1)/12; Inc(I); end; Sigma := Sqrt(AP_Double(M*N)/NS/(NS-1)*Tmp); S := (U-Mu)/Sigma; if AP_FP_Less_Eq(S,0) then begin P := Exp(USigma(-(U-Mu)/Sigma, N, M)); MP := 1-Exp(USigma(-(U-1-Mu)/Sigma, N, M)); end else begin MP := Exp(USigma((U-Mu)/Sigma, N, M)); P := 1-Exp(USigma((U+1-Mu)/Sigma, N, M)); end; BothTails := Max(2*Min(P, MP), 1.0E-4); LeftTail := Max(MP, 1.0E-4); RightTail := Max(P, 1.0E-4); end; (************************************************************************* Sequential Chebyshev interpolation. *************************************************************************) procedure UCheb(X : AlglibFloat; C : AlglibFloat; var TJ : AlglibFloat; var TJ1 : AlglibFloat; var R : AlglibFloat); var T : AlglibFloat; begin R := R+C*TJ; T := 2*X*TJ1-TJ; TJ := TJ1; TJ1 := T; end; (************************************************************************* Three-point polynomial interpolation. *************************************************************************) function UNInterpolate(P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; N : AlglibInteger):AlglibFloat; var T1 : AlglibFloat; T2 : AlglibFloat; T3 : AlglibFloat; T : AlglibFloat; P12 : AlglibFloat; P23 : AlglibFloat; begin T1 := 1.0/15.0; T2 := 1.0/30.0; T3 := 1.0/100.0; T := 1.0/N; P12 := ((T-T2)*P1+(T1-T)*P2)/(T1-T2); P23 := ((T-T3)*P2+(T2-T)*P3)/(T2-T3); Result := ((T-T3)*P12+(T1-T)*P23)/(T1-T3); end; (************************************************************************* Tail(0, N1, N2) *************************************************************************) function USigma000(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-6.76984e-01, -6.83700e-01, -6.89873e-01, N2); P2 := UNInterpolate(-6.83700e-01, -6.87311e-01, -6.90957e-01, N2); P3 := UNInterpolate(-6.89873e-01, -6.90957e-01, -6.92175e-01, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(0.75, N1, N2) *************************************************************************) function USigma075(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-1.44500e+00, -1.45906e+00, -1.47063e+00, N2); P2 := UNInterpolate(-1.45906e+00, -1.46856e+00, -1.47644e+00, N2); P3 := UNInterpolate(-1.47063e+00, -1.47644e+00, -1.48100e+00, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(1.5, N1, N2) *************************************************************************) function USigma150(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-2.65380e+00, -2.67352e+00, -2.69011e+00, N2); P2 := UNInterpolate(-2.67352e+00, -2.68591e+00, -2.69659e+00, N2); P3 := UNInterpolate(-2.69011e+00, -2.69659e+00, -2.70192e+00, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(2.25, N1, N2) *************************************************************************) function USigma225(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-4.41465e+00, -4.42260e+00, -4.43702e+00, N2); P2 := UNInterpolate(-4.42260e+00, -4.41639e+00, -4.41928e+00, N2); P3 := UNInterpolate(-4.43702e+00, -4.41928e+00, -4.41030e+00, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(3.0, N1, N2) *************************************************************************) function USigma300(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-6.89839e+00, -6.83477e+00, -6.82340e+00, N2); P2 := UNInterpolate(-6.83477e+00, -6.74559e+00, -6.71117e+00, N2); P3 := UNInterpolate(-6.82340e+00, -6.71117e+00, -6.64929e+00, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(3.33, N1, N2) *************************************************************************) function USigma333(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-8.31272e+00, -8.17096e+00, -8.13125e+00, N2); P2 := UNInterpolate(-8.17096e+00, -8.00156e+00, -7.93245e+00, N2); P3 := UNInterpolate(-8.13125e+00, -7.93245e+00, -7.82502e+00, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(3.66, N1, N2) *************************************************************************) function USigma367(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-9.98837e+00, -9.70844e+00, -9.62087e+00, N2); P2 := UNInterpolate(-9.70844e+00, -9.41156e+00, -9.28998e+00, N2); P3 := UNInterpolate(-9.62087e+00, -9.28998e+00, -9.11686e+00, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(4.0, N1, N2) *************************************************************************) function USigma400(N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var P1 : AlglibFloat; P2 : AlglibFloat; P3 : AlglibFloat; begin P1 := UNInterpolate(-1.20250e+01, -1.14911e+01, -1.13231e+01, N2); P2 := UNInterpolate(-1.14911e+01, -1.09927e+01, -1.07937e+01, N2); P3 := UNInterpolate(-1.13231e+01, -1.07937e+01, -1.05285e+01, N2); Result := UNInterpolate(P1, P2, P3, N1); end; (************************************************************************* Tail(S, 5, 5) *************************************************************************) function UTblN5N5(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/2.611165e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -2.596264e+00, TJ, TJ1, Result); UCheb(X, -2.412086e+00, TJ, TJ1, Result); UCheb(X, -4.858542e-01, TJ, TJ1, Result); UCheb(X, -5.614282e-02, TJ, TJ1, Result); UCheb(X, 3.372686e-03, TJ, TJ1, Result); UCheb(X, 8.524731e-03, TJ, TJ1, Result); UCheb(X, 4.435331e-03, TJ, TJ1, Result); UCheb(X, 1.284665e-03, TJ, TJ1, Result); UCheb(X, 4.184141e-03, TJ, TJ1, Result); UCheb(X, 5.298360e-03, TJ, TJ1, Result); UCheb(X, 7.447272e-04, TJ, TJ1, Result); UCheb(X, -3.938769e-03, TJ, TJ1, Result); UCheb(X, -4.276205e-03, TJ, TJ1, Result); UCheb(X, -1.138481e-03, TJ, TJ1, Result); UCheb(X, 8.684625e-04, TJ, TJ1, Result); UCheb(X, 1.558104e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 6) *************************************************************************) function UTblN5N6(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/2.738613e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -2.810459e+00, TJ, TJ1, Result); UCheb(X, -2.684429e+00, TJ, TJ1, Result); UCheb(X, -5.712858e-01, TJ, TJ1, Result); UCheb(X, -8.009324e-02, TJ, TJ1, Result); UCheb(X, -6.644391e-03, TJ, TJ1, Result); UCheb(X, 6.034173e-03, TJ, TJ1, Result); UCheb(X, 4.953498e-03, TJ, TJ1, Result); UCheb(X, 3.279293e-03, TJ, TJ1, Result); UCheb(X, 3.563485e-03, TJ, TJ1, Result); UCheb(X, 4.971952e-03, TJ, TJ1, Result); UCheb(X, 3.506309e-03, TJ, TJ1, Result); UCheb(X, -1.541406e-04, TJ, TJ1, Result); UCheb(X, -3.283205e-03, TJ, TJ1, Result); UCheb(X, -3.016347e-03, TJ, TJ1, Result); UCheb(X, -1.221626e-03, TJ, TJ1, Result); UCheb(X, -1.286752e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 7) *************************************************************************) function UTblN5N7(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/2.841993e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -2.994677e+00, TJ, TJ1, Result); UCheb(X, -2.923264e+00, TJ, TJ1, Result); UCheb(X, -6.506190e-01, TJ, TJ1, Result); UCheb(X, -1.054280e-01, TJ, TJ1, Result); UCheb(X, -1.794587e-02, TJ, TJ1, Result); UCheb(X, 1.726290e-03, TJ, TJ1, Result); UCheb(X, 4.534180e-03, TJ, TJ1, Result); UCheb(X, 4.517845e-03, TJ, TJ1, Result); UCheb(X, 3.904428e-03, TJ, TJ1, Result); UCheb(X, 3.882443e-03, TJ, TJ1, Result); UCheb(X, 3.482988e-03, TJ, TJ1, Result); UCheb(X, 2.114875e-03, TJ, TJ1, Result); UCheb(X, -1.515082e-04, TJ, TJ1, Result); UCheb(X, -1.996056e-03, TJ, TJ1, Result); UCheb(X, -2.293581e-03, TJ, TJ1, Result); UCheb(X, -2.349444e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 8) *************************************************************************) function UTblN5N8(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/2.927700e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.155727e+00, TJ, TJ1, Result); UCheb(X, -3.135078e+00, TJ, TJ1, Result); UCheb(X, -7.247203e-01, TJ, TJ1, Result); UCheb(X, -1.309697e-01, TJ, TJ1, Result); UCheb(X, -2.993725e-02, TJ, TJ1, Result); UCheb(X, -3.567219e-03, TJ, TJ1, Result); UCheb(X, 3.383704e-03, TJ, TJ1, Result); UCheb(X, 5.002188e-03, TJ, TJ1, Result); UCheb(X, 4.487322e-03, TJ, TJ1, Result); UCheb(X, 3.443899e-03, TJ, TJ1, Result); UCheb(X, 2.688270e-03, TJ, TJ1, Result); UCheb(X, 2.600339e-03, TJ, TJ1, Result); UCheb(X, 1.874948e-03, TJ, TJ1, Result); UCheb(X, 1.811593e-04, TJ, TJ1, Result); UCheb(X, -1.072353e-03, TJ, TJ1, Result); UCheb(X, -2.659457e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 9) *************************************************************************) function UTblN5N9(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.000000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.298162e+00, TJ, TJ1, Result); UCheb(X, -3.325016e+00, TJ, TJ1, Result); UCheb(X, -7.939852e-01, TJ, TJ1, Result); UCheb(X, -1.563029e-01, TJ, TJ1, Result); UCheb(X, -4.222652e-02, TJ, TJ1, Result); UCheb(X, -9.195200e-03, TJ, TJ1, Result); UCheb(X, 1.445665e-03, TJ, TJ1, Result); UCheb(X, 5.204792e-03, TJ, TJ1, Result); UCheb(X, 4.775217e-03, TJ, TJ1, Result); UCheb(X, 3.527781e-03, TJ, TJ1, Result); UCheb(X, 2.221948e-03, TJ, TJ1, Result); UCheb(X, 2.242968e-03, TJ, TJ1, Result); UCheb(X, 2.607959e-03, TJ, TJ1, Result); UCheb(X, 1.771285e-03, TJ, TJ1, Result); UCheb(X, 6.694026e-04, TJ, TJ1, Result); UCheb(X, -1.481190e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 10) *************************************************************************) function UTblN5N10(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.061862e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.425360e+00, TJ, TJ1, Result); UCheb(X, -3.496710e+00, TJ, TJ1, Result); UCheb(X, -8.587658e-01, TJ, TJ1, Result); UCheb(X, -1.812005e-01, TJ, TJ1, Result); UCheb(X, -5.427637e-02, TJ, TJ1, Result); UCheb(X, -1.515702e-02, TJ, TJ1, Result); UCheb(X, -5.406867e-04, TJ, TJ1, Result); UCheb(X, 4.796295e-03, TJ, TJ1, Result); UCheb(X, 5.237591e-03, TJ, TJ1, Result); UCheb(X, 3.654249e-03, TJ, TJ1, Result); UCheb(X, 2.181165e-03, TJ, TJ1, Result); UCheb(X, 2.011665e-03, TJ, TJ1, Result); UCheb(X, 2.417927e-03, TJ, TJ1, Result); UCheb(X, 2.534880e-03, TJ, TJ1, Result); UCheb(X, 1.791255e-03, TJ, TJ1, Result); UCheb(X, 1.871512e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 11) *************************************************************************) function UTblN5N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.115427e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.539959e+00, TJ, TJ1, Result); UCheb(X, -3.652998e+00, TJ, TJ1, Result); UCheb(X, -9.196503e-01, TJ, TJ1, Result); UCheb(X, -2.054363e-01, TJ, TJ1, Result); UCheb(X, -6.618848e-02, TJ, TJ1, Result); UCheb(X, -2.109411e-02, TJ, TJ1, Result); UCheb(X, -2.786668e-03, TJ, TJ1, Result); UCheb(X, 4.215648e-03, TJ, TJ1, Result); UCheb(X, 5.484220e-03, TJ, TJ1, Result); UCheb(X, 3.935991e-03, TJ, TJ1, Result); UCheb(X, 2.396191e-03, TJ, TJ1, Result); UCheb(X, 1.894177e-03, TJ, TJ1, Result); UCheb(X, 2.206979e-03, TJ, TJ1, Result); UCheb(X, 2.519055e-03, TJ, TJ1, Result); UCheb(X, 2.210326e-03, TJ, TJ1, Result); UCheb(X, 1.189679e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 12) *************************************************************************) function UTblN5N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.162278e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.644007e+00, TJ, TJ1, Result); UCheb(X, -3.796173e+00, TJ, TJ1, Result); UCheb(X, -9.771177e-01, TJ, TJ1, Result); UCheb(X, -2.290043e-01, TJ, TJ1, Result); UCheb(X, -7.794686e-02, TJ, TJ1, Result); UCheb(X, -2.702110e-02, TJ, TJ1, Result); UCheb(X, -5.185959e-03, TJ, TJ1, Result); UCheb(X, 3.416259e-03, TJ, TJ1, Result); UCheb(X, 5.592056e-03, TJ, TJ1, Result); UCheb(X, 4.201530e-03, TJ, TJ1, Result); UCheb(X, 2.754365e-03, TJ, TJ1, Result); UCheb(X, 1.978945e-03, TJ, TJ1, Result); UCheb(X, 2.012032e-03, TJ, TJ1, Result); UCheb(X, 2.304579e-03, TJ, TJ1, Result); UCheb(X, 2.100378e-03, TJ, TJ1, Result); UCheb(X, 1.728269e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 13) *************************************************************************) function UTblN5N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.203616e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.739120e+00, TJ, TJ1, Result); UCheb(X, -3.928117e+00, TJ, TJ1, Result); UCheb(X, -1.031605e+00, TJ, TJ1, Result); UCheb(X, -2.519403e-01, TJ, TJ1, Result); UCheb(X, -8.962648e-02, TJ, TJ1, Result); UCheb(X, -3.292183e-02, TJ, TJ1, Result); UCheb(X, -7.809293e-03, TJ, TJ1, Result); UCheb(X, 2.465156e-03, TJ, TJ1, Result); UCheb(X, 5.456278e-03, TJ, TJ1, Result); UCheb(X, 4.446055e-03, TJ, TJ1, Result); UCheb(X, 3.109490e-03, TJ, TJ1, Result); UCheb(X, 2.218256e-03, TJ, TJ1, Result); UCheb(X, 1.941479e-03, TJ, TJ1, Result); UCheb(X, 2.058603e-03, TJ, TJ1, Result); UCheb(X, 1.824402e-03, TJ, TJ1, Result); UCheb(X, 1.830947e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 14) *************************************************************************) function UTblN5N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.240370e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.826559e+00, TJ, TJ1, Result); UCheb(X, -4.050370e+00, TJ, TJ1, Result); UCheb(X, -1.083408e+00, TJ, TJ1, Result); UCheb(X, -2.743164e-01, TJ, TJ1, Result); UCheb(X, -1.012030e-01, TJ, TJ1, Result); UCheb(X, -3.884686e-02, TJ, TJ1, Result); UCheb(X, -1.059656e-02, TJ, TJ1, Result); UCheb(X, 1.327521e-03, TJ, TJ1, Result); UCheb(X, 5.134026e-03, TJ, TJ1, Result); UCheb(X, 4.584201e-03, TJ, TJ1, Result); UCheb(X, 3.440618e-03, TJ, TJ1, Result); UCheb(X, 2.524133e-03, TJ, TJ1, Result); UCheb(X, 1.990007e-03, TJ, TJ1, Result); UCheb(X, 1.887334e-03, TJ, TJ1, Result); UCheb(X, 1.534977e-03, TJ, TJ1, Result); UCheb(X, 1.705395e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 15) *************************************************************************) function UTblN5N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.851572e+00, TJ, TJ1, Result); UCheb(X, -4.082033e+00, TJ, TJ1, Result); UCheb(X, -1.095983e+00, TJ, TJ1, Result); UCheb(X, -2.814595e-01, TJ, TJ1, Result); UCheb(X, -1.073148e-01, TJ, TJ1, Result); UCheb(X, -4.420213e-02, TJ, TJ1, Result); UCheb(X, -1.517175e-02, TJ, TJ1, Result); UCheb(X, -2.344180e-03, TJ, TJ1, Result); UCheb(X, 2.371393e-03, TJ, TJ1, Result); UCheb(X, 2.711443e-03, TJ, TJ1, Result); UCheb(X, 2.228569e-03, TJ, TJ1, Result); UCheb(X, 1.683483e-03, TJ, TJ1, Result); UCheb(X, 1.267112e-03, TJ, TJ1, Result); UCheb(X, 1.156044e-03, TJ, TJ1, Result); UCheb(X, 9.131316e-04, TJ, TJ1, Result); UCheb(X, 1.301023e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 16) *************************************************************************) function UTblN5N16(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.852210e+00, TJ, TJ1, Result); UCheb(X, -4.077482e+00, TJ, TJ1, Result); UCheb(X, -1.091186e+00, TJ, TJ1, Result); UCheb(X, -2.797282e-01, TJ, TJ1, Result); UCheb(X, -1.084994e-01, TJ, TJ1, Result); UCheb(X, -4.667054e-02, TJ, TJ1, Result); UCheb(X, -1.843909e-02, TJ, TJ1, Result); UCheb(X, -5.456732e-03, TJ, TJ1, Result); UCheb(X, -5.039830e-04, TJ, TJ1, Result); UCheb(X, 4.723508e-04, TJ, TJ1, Result); UCheb(X, 3.940608e-04, TJ, TJ1, Result); UCheb(X, 1.478285e-04, TJ, TJ1, Result); UCheb(X, -1.649144e-04, TJ, TJ1, Result); UCheb(X, -4.237703e-04, TJ, TJ1, Result); UCheb(X, -4.707410e-04, TJ, TJ1, Result); UCheb(X, -1.874293e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 17) *************************************************************************) function UTblN5N17(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.851752e+00, TJ, TJ1, Result); UCheb(X, -4.071259e+00, TJ, TJ1, Result); UCheb(X, -1.084700e+00, TJ, TJ1, Result); UCheb(X, -2.758898e-01, TJ, TJ1, Result); UCheb(X, -1.073846e-01, TJ, TJ1, Result); UCheb(X, -4.684838e-02, TJ, TJ1, Result); UCheb(X, -1.964936e-02, TJ, TJ1, Result); UCheb(X, -6.782442e-03, TJ, TJ1, Result); UCheb(X, -1.956362e-03, TJ, TJ1, Result); UCheb(X, -5.984727e-04, TJ, TJ1, Result); UCheb(X, -5.196936e-04, TJ, TJ1, Result); UCheb(X, -5.558262e-04, TJ, TJ1, Result); UCheb(X, -8.690746e-04, TJ, TJ1, Result); UCheb(X, -1.364855e-03, TJ, TJ1, Result); UCheb(X, -1.401006e-03, TJ, TJ1, Result); UCheb(X, -1.546748e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 18) *************************************************************************) function UTblN5N18(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.850840e+00, TJ, TJ1, Result); UCheb(X, -4.064799e+00, TJ, TJ1, Result); UCheb(X, -1.077651e+00, TJ, TJ1, Result); UCheb(X, -2.712659e-01, TJ, TJ1, Result); UCheb(X, -1.049217e-01, TJ, TJ1, Result); UCheb(X, -4.571333e-02, TJ, TJ1, Result); UCheb(X, -1.929809e-02, TJ, TJ1, Result); UCheb(X, -6.752044e-03, TJ, TJ1, Result); UCheb(X, -1.949464e-03, TJ, TJ1, Result); UCheb(X, -3.896101e-04, TJ, TJ1, Result); UCheb(X, -4.614460e-05, TJ, TJ1, Result); UCheb(X, 1.384357e-04, TJ, TJ1, Result); UCheb(X, -6.489113e-05, TJ, TJ1, Result); UCheb(X, -6.445725e-04, TJ, TJ1, Result); UCheb(X, -8.945636e-04, TJ, TJ1, Result); UCheb(X, -1.424653e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 19) *************************************************************************) function UTblN5N19(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.850027e+00, TJ, TJ1, Result); UCheb(X, -4.059159e+00, TJ, TJ1, Result); UCheb(X, -1.071106e+00, TJ, TJ1, Result); UCheb(X, -2.669960e-01, TJ, TJ1, Result); UCheb(X, -1.022780e-01, TJ, TJ1, Result); UCheb(X, -4.442555e-02, TJ, TJ1, Result); UCheb(X, -1.851335e-02, TJ, TJ1, Result); UCheb(X, -6.433865e-03, TJ, TJ1, Result); UCheb(X, -1.514465e-03, TJ, TJ1, Result); UCheb(X, 1.332989e-04, TJ, TJ1, Result); UCheb(X, 8.606099e-04, TJ, TJ1, Result); UCheb(X, 1.341945e-03, TJ, TJ1, Result); UCheb(X, 1.402164e-03, TJ, TJ1, Result); UCheb(X, 1.039761e-03, TJ, TJ1, Result); UCheb(X, 5.512831e-04, TJ, TJ1, Result); UCheb(X, -3.284427e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 20) *************************************************************************) function UTblN5N20(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.849651e+00, TJ, TJ1, Result); UCheb(X, -4.054729e+00, TJ, TJ1, Result); UCheb(X, -1.065747e+00, TJ, TJ1, Result); UCheb(X, -2.636243e-01, TJ, TJ1, Result); UCheb(X, -1.003234e-01, TJ, TJ1, Result); UCheb(X, -4.372789e-02, TJ, TJ1, Result); UCheb(X, -1.831551e-02, TJ, TJ1, Result); UCheb(X, -6.763090e-03, TJ, TJ1, Result); UCheb(X, -1.830626e-03, TJ, TJ1, Result); UCheb(X, -2.122384e-04, TJ, TJ1, Result); UCheb(X, 8.108328e-04, TJ, TJ1, Result); UCheb(X, 1.557983e-03, TJ, TJ1, Result); UCheb(X, 1.945666e-03, TJ, TJ1, Result); UCheb(X, 1.965696e-03, TJ, TJ1, Result); UCheb(X, 1.493236e-03, TJ, TJ1, Result); UCheb(X, 1.162591e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 21) *************************************************************************) function UTblN5N21(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.849649e+00, TJ, TJ1, Result); UCheb(X, -4.051155e+00, TJ, TJ1, Result); UCheb(X, -1.061430e+00, TJ, TJ1, Result); UCheb(X, -2.608869e-01, TJ, TJ1, Result); UCheb(X, -9.902788e-02, TJ, TJ1, Result); UCheb(X, -4.346562e-02, TJ, TJ1, Result); UCheb(X, -1.874709e-02, TJ, TJ1, Result); UCheb(X, -7.682887e-03, TJ, TJ1, Result); UCheb(X, -3.026206e-03, TJ, TJ1, Result); UCheb(X, -1.534551e-03, TJ, TJ1, Result); UCheb(X, -4.990575e-04, TJ, TJ1, Result); UCheb(X, 3.713334e-04, TJ, TJ1, Result); UCheb(X, 9.737011e-04, TJ, TJ1, Result); UCheb(X, 1.304571e-03, TJ, TJ1, Result); UCheb(X, 1.133110e-03, TJ, TJ1, Result); UCheb(X, 1.123457e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 22) *************************************************************************) function UTblN5N22(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.849598e+00, TJ, TJ1, Result); UCheb(X, -4.047605e+00, TJ, TJ1, Result); UCheb(X, -1.057264e+00, TJ, TJ1, Result); UCheb(X, -2.579513e-01, TJ, TJ1, Result); UCheb(X, -9.749602e-02, TJ, TJ1, Result); UCheb(X, -4.275137e-02, TJ, TJ1, Result); UCheb(X, -1.881768e-02, TJ, TJ1, Result); UCheb(X, -8.177374e-03, TJ, TJ1, Result); UCheb(X, -3.981056e-03, TJ, TJ1, Result); UCheb(X, -2.696290e-03, TJ, TJ1, Result); UCheb(X, -1.886803e-03, TJ, TJ1, Result); UCheb(X, -1.085378e-03, TJ, TJ1, Result); UCheb(X, -4.675242e-04, TJ, TJ1, Result); UCheb(X, -5.426367e-05, TJ, TJ1, Result); UCheb(X, 1.039613e-04, TJ, TJ1, Result); UCheb(X, 2.662378e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 23) *************************************************************************) function UTblN5N23(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.849269e+00, TJ, TJ1, Result); UCheb(X, -4.043761e+00, TJ, TJ1, Result); UCheb(X, -1.052735e+00, TJ, TJ1, Result); UCheb(X, -2.544683e-01, TJ, TJ1, Result); UCheb(X, -9.517503e-02, TJ, TJ1, Result); UCheb(X, -4.112082e-02, TJ, TJ1, Result); UCheb(X, -1.782070e-02, TJ, TJ1, Result); UCheb(X, -7.549483e-03, TJ, TJ1, Result); UCheb(X, -3.747329e-03, TJ, TJ1, Result); UCheb(X, -2.694263e-03, TJ, TJ1, Result); UCheb(X, -2.147141e-03, TJ, TJ1, Result); UCheb(X, -1.526209e-03, TJ, TJ1, Result); UCheb(X, -1.039173e-03, TJ, TJ1, Result); UCheb(X, -7.235615e-04, TJ, TJ1, Result); UCheb(X, -4.656546e-04, TJ, TJ1, Result); UCheb(X, -3.014423e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 24) *************************************************************************) function UTblN5N24(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.848925e+00, TJ, TJ1, Result); UCheb(X, -4.040178e+00, TJ, TJ1, Result); UCheb(X, -1.048355e+00, TJ, TJ1, Result); UCheb(X, -2.510198e-01, TJ, TJ1, Result); UCheb(X, -9.261134e-02, TJ, TJ1, Result); UCheb(X, -3.915864e-02, TJ, TJ1, Result); UCheb(X, -1.627423e-02, TJ, TJ1, Result); UCheb(X, -6.307345e-03, TJ, TJ1, Result); UCheb(X, -2.732992e-03, TJ, TJ1, Result); UCheb(X, -1.869652e-03, TJ, TJ1, Result); UCheb(X, -1.494176e-03, TJ, TJ1, Result); UCheb(X, -1.047533e-03, TJ, TJ1, Result); UCheb(X, -7.178439e-04, TJ, TJ1, Result); UCheb(X, -5.424171e-04, TJ, TJ1, Result); UCheb(X, -3.829195e-04, TJ, TJ1, Result); UCheb(X, -2.840810e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 25) *************************************************************************) function UTblN5N25(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.848937e+00, TJ, TJ1, Result); UCheb(X, -4.037512e+00, TJ, TJ1, Result); UCheb(X, -1.044866e+00, TJ, TJ1, Result); UCheb(X, -2.483269e-01, TJ, TJ1, Result); UCheb(X, -9.063682e-02, TJ, TJ1, Result); UCheb(X, -3.767778e-02, TJ, TJ1, Result); UCheb(X, -1.508540e-02, TJ, TJ1, Result); UCheb(X, -5.332756e-03, TJ, TJ1, Result); UCheb(X, -1.881511e-03, TJ, TJ1, Result); UCheb(X, -1.124041e-03, TJ, TJ1, Result); UCheb(X, -8.368456e-04, TJ, TJ1, Result); UCheb(X, -4.930499e-04, TJ, TJ1, Result); UCheb(X, -2.779630e-04, TJ, TJ1, Result); UCheb(X, -2.029528e-04, TJ, TJ1, Result); UCheb(X, -1.658678e-04, TJ, TJ1, Result); UCheb(X, -1.289695e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 26) *************************************************************************) function UTblN5N26(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.849416e+00, TJ, TJ1, Result); UCheb(X, -4.035915e+00, TJ, TJ1, Result); UCheb(X, -1.042493e+00, TJ, TJ1, Result); UCheb(X, -2.466021e-01, TJ, TJ1, Result); UCheb(X, -8.956432e-02, TJ, TJ1, Result); UCheb(X, -3.698914e-02, TJ, TJ1, Result); UCheb(X, -1.465689e-02, TJ, TJ1, Result); UCheb(X, -5.035254e-03, TJ, TJ1, Result); UCheb(X, -1.674614e-03, TJ, TJ1, Result); UCheb(X, -9.492734e-04, TJ, TJ1, Result); UCheb(X, -7.014021e-04, TJ, TJ1, Result); UCheb(X, -3.944953e-04, TJ, TJ1, Result); UCheb(X, -2.255750e-04, TJ, TJ1, Result); UCheb(X, -2.075841e-04, TJ, TJ1, Result); UCheb(X, -1.989330e-04, TJ, TJ1, Result); UCheb(X, -2.134862e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 27) *************************************************************************) function UTblN5N27(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.850070e+00, TJ, TJ1, Result); UCheb(X, -4.034815e+00, TJ, TJ1, Result); UCheb(X, -1.040650e+00, TJ, TJ1, Result); UCheb(X, -2.453117e-01, TJ, TJ1, Result); UCheb(X, -8.886426e-02, TJ, TJ1, Result); UCheb(X, -3.661702e-02, TJ, TJ1, Result); UCheb(X, -1.452346e-02, TJ, TJ1, Result); UCheb(X, -5.002476e-03, TJ, TJ1, Result); UCheb(X, -1.720126e-03, TJ, TJ1, Result); UCheb(X, -1.001400e-03, TJ, TJ1, Result); UCheb(X, -7.729826e-04, TJ, TJ1, Result); UCheb(X, -4.740640e-04, TJ, TJ1, Result); UCheb(X, -3.206333e-04, TJ, TJ1, Result); UCheb(X, -3.366093e-04, TJ, TJ1, Result); UCheb(X, -3.193471e-04, TJ, TJ1, Result); UCheb(X, -3.804091e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 28) *************************************************************************) function UTblN5N28(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.850668e+00, TJ, TJ1, Result); UCheb(X, -4.033786e+00, TJ, TJ1, Result); UCheb(X, -1.038853e+00, TJ, TJ1, Result); UCheb(X, -2.440281e-01, TJ, TJ1, Result); UCheb(X, -8.806020e-02, TJ, TJ1, Result); UCheb(X, -3.612883e-02, TJ, TJ1, Result); UCheb(X, -1.420436e-02, TJ, TJ1, Result); UCheb(X, -4.787982e-03, TJ, TJ1, Result); UCheb(X, -1.535230e-03, TJ, TJ1, Result); UCheb(X, -8.263121e-04, TJ, TJ1, Result); UCheb(X, -5.849609e-04, TJ, TJ1, Result); UCheb(X, -2.863967e-04, TJ, TJ1, Result); UCheb(X, -1.391610e-04, TJ, TJ1, Result); UCheb(X, -1.720294e-04, TJ, TJ1, Result); UCheb(X, -1.952273e-04, TJ, TJ1, Result); UCheb(X, -2.901413e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 29) *************************************************************************) function UTblN5N29(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.851217e+00, TJ, TJ1, Result); UCheb(X, -4.032834e+00, TJ, TJ1, Result); UCheb(X, -1.037113e+00, TJ, TJ1, Result); UCheb(X, -2.427762e-01, TJ, TJ1, Result); UCheb(X, -8.719146e-02, TJ, TJ1, Result); UCheb(X, -3.557172e-02, TJ, TJ1, Result); UCheb(X, -1.375498e-02, TJ, TJ1, Result); UCheb(X, -4.452033e-03, TJ, TJ1, Result); UCheb(X, -1.187516e-03, TJ, TJ1, Result); UCheb(X, -4.916936e-04, TJ, TJ1, Result); UCheb(X, -2.065533e-04, TJ, TJ1, Result); UCheb(X, 1.067301e-04, TJ, TJ1, Result); UCheb(X, 2.615824e-04, TJ, TJ1, Result); UCheb(X, 2.432244e-04, TJ, TJ1, Result); UCheb(X, 1.417795e-04, TJ, TJ1, Result); UCheb(X, 4.710038e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 30) *************************************************************************) function UTblN5N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.851845e+00, TJ, TJ1, Result); UCheb(X, -4.032148e+00, TJ, TJ1, Result); UCheb(X, -1.035679e+00, TJ, TJ1, Result); UCheb(X, -2.417758e-01, TJ, TJ1, Result); UCheb(X, -8.655330e-02, TJ, TJ1, Result); UCheb(X, -3.522132e-02, TJ, TJ1, Result); UCheb(X, -1.352106e-02, TJ, TJ1, Result); UCheb(X, -4.326911e-03, TJ, TJ1, Result); UCheb(X, -1.064969e-03, TJ, TJ1, Result); UCheb(X, -3.813321e-04, TJ, TJ1, Result); UCheb(X, -5.683881e-05, TJ, TJ1, Result); UCheb(X, 2.813346e-04, TJ, TJ1, Result); UCheb(X, 4.627085e-04, TJ, TJ1, Result); UCheb(X, 4.832107e-04, TJ, TJ1, Result); UCheb(X, 3.519336e-04, TJ, TJ1, Result); UCheb(X, 2.888530e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 5, 100) *************************************************************************) function UTblN5N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.250000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.877940e+00, TJ, TJ1, Result); UCheb(X, -4.039324e+00, TJ, TJ1, Result); UCheb(X, -1.022243e+00, TJ, TJ1, Result); UCheb(X, -2.305825e-01, TJ, TJ1, Result); UCheb(X, -7.960119e-02, TJ, TJ1, Result); UCheb(X, -3.112000e-02, TJ, TJ1, Result); UCheb(X, -1.138868e-02, TJ, TJ1, Result); UCheb(X, -3.418164e-03, TJ, TJ1, Result); UCheb(X, -9.174520e-04, TJ, TJ1, Result); UCheb(X, -5.489617e-04, TJ, TJ1, Result); UCheb(X, -3.878301e-04, TJ, TJ1, Result); UCheb(X, -1.302233e-04, TJ, TJ1, Result); UCheb(X, 1.054113e-05, TJ, TJ1, Result); UCheb(X, 2.458862e-05, TJ, TJ1, Result); UCheb(X, -4.186591e-06, TJ, TJ1, Result); UCheb(X, -2.623412e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 6) *************************************************************************) function UTblN6N6(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/2.882307e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.054075e+00, TJ, TJ1, Result); UCheb(X, -2.998804e+00, TJ, TJ1, Result); UCheb(X, -6.681518e-01, TJ, TJ1, Result); UCheb(X, -1.067578e-01, TJ, TJ1, Result); UCheb(X, -1.709435e-02, TJ, TJ1, Result); UCheb(X, 9.952661e-04, TJ, TJ1, Result); UCheb(X, 3.641700e-03, TJ, TJ1, Result); UCheb(X, 2.304572e-03, TJ, TJ1, Result); UCheb(X, 3.336275e-03, TJ, TJ1, Result); UCheb(X, 4.770385e-03, TJ, TJ1, Result); UCheb(X, 5.401891e-03, TJ, TJ1, Result); UCheb(X, 2.246148e-03, TJ, TJ1, Result); UCheb(X, -1.442663e-03, TJ, TJ1, Result); UCheb(X, -2.502866e-03, TJ, TJ1, Result); UCheb(X, -2.105855e-03, TJ, TJ1, Result); UCheb(X, -4.739371e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 7) *************************************************************************) function UTblN6N7(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.000000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.265287e+00, TJ, TJ1, Result); UCheb(X, -3.274613e+00, TJ, TJ1, Result); UCheb(X, -7.582352e-01, TJ, TJ1, Result); UCheb(X, -1.334293e-01, TJ, TJ1, Result); UCheb(X, -2.915502e-02, TJ, TJ1, Result); UCheb(X, -4.108091e-03, TJ, TJ1, Result); UCheb(X, 1.546701e-03, TJ, TJ1, Result); UCheb(X, 2.298827e-03, TJ, TJ1, Result); UCheb(X, 2.891501e-03, TJ, TJ1, Result); UCheb(X, 4.313717e-03, TJ, TJ1, Result); UCheb(X, 4.989501e-03, TJ, TJ1, Result); UCheb(X, 3.914594e-03, TJ, TJ1, Result); UCheb(X, 1.062372e-03, TJ, TJ1, Result); UCheb(X, -1.158841e-03, TJ, TJ1, Result); UCheb(X, -1.596443e-03, TJ, TJ1, Result); UCheb(X, -1.185662e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 8) *************************************************************************) function UTblN6N8(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.098387e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.450954e+00, TJ, TJ1, Result); UCheb(X, -3.520462e+00, TJ, TJ1, Result); UCheb(X, -8.420299e-01, TJ, TJ1, Result); UCheb(X, -1.604853e-01, TJ, TJ1, Result); UCheb(X, -4.165840e-02, TJ, TJ1, Result); UCheb(X, -1.008756e-02, TJ, TJ1, Result); UCheb(X, -6.723402e-04, TJ, TJ1, Result); UCheb(X, 1.843521e-03, TJ, TJ1, Result); UCheb(X, 2.883405e-03, TJ, TJ1, Result); UCheb(X, 3.720980e-03, TJ, TJ1, Result); UCheb(X, 4.301709e-03, TJ, TJ1, Result); UCheb(X, 3.948034e-03, TJ, TJ1, Result); UCheb(X, 2.776243e-03, TJ, TJ1, Result); UCheb(X, 8.623736e-04, TJ, TJ1, Result); UCheb(X, -3.742068e-04, TJ, TJ1, Result); UCheb(X, -9.796927e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 9) *************************************************************************) function UTblN6N9(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.181981e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.616113e+00, TJ, TJ1, Result); UCheb(X, -3.741650e+00, TJ, TJ1, Result); UCheb(X, -9.204487e-01, TJ, TJ1, Result); UCheb(X, -1.873068e-01, TJ, TJ1, Result); UCheb(X, -5.446794e-02, TJ, TJ1, Result); UCheb(X, -1.632286e-02, TJ, TJ1, Result); UCheb(X, -3.266481e-03, TJ, TJ1, Result); UCheb(X, 1.280067e-03, TJ, TJ1, Result); UCheb(X, 2.780687e-03, TJ, TJ1, Result); UCheb(X, 3.480242e-03, TJ, TJ1, Result); UCheb(X, 3.592200e-03, TJ, TJ1, Result); UCheb(X, 3.581019e-03, TJ, TJ1, Result); UCheb(X, 3.264231e-03, TJ, TJ1, Result); UCheb(X, 2.347174e-03, TJ, TJ1, Result); UCheb(X, 1.167535e-03, TJ, TJ1, Result); UCheb(X, -1.092185e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 10) *************************************************************************) function UTblN6N10(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.253957e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.764382e+00, TJ, TJ1, Result); UCheb(X, -3.942366e+00, TJ, TJ1, Result); UCheb(X, -9.939896e-01, TJ, TJ1, Result); UCheb(X, -2.137812e-01, TJ, TJ1, Result); UCheb(X, -6.720270e-02, TJ, TJ1, Result); UCheb(X, -2.281070e-02, TJ, TJ1, Result); UCheb(X, -5.901060e-03, TJ, TJ1, Result); UCheb(X, 3.824937e-04, TJ, TJ1, Result); UCheb(X, 2.802812e-03, TJ, TJ1, Result); UCheb(X, 3.258132e-03, TJ, TJ1, Result); UCheb(X, 3.233536e-03, TJ, TJ1, Result); UCheb(X, 3.085530e-03, TJ, TJ1, Result); UCheb(X, 3.212151e-03, TJ, TJ1, Result); UCheb(X, 3.001329e-03, TJ, TJ1, Result); UCheb(X, 2.226048e-03, TJ, TJ1, Result); UCheb(X, 1.035298e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 11) *************************************************************************) function UTblN6N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.316625e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.898597e+00, TJ, TJ1, Result); UCheb(X, -4.125710e+00, TJ, TJ1, Result); UCheb(X, -1.063297e+00, TJ, TJ1, Result); UCheb(X, -2.396852e-01, TJ, TJ1, Result); UCheb(X, -7.990126e-02, TJ, TJ1, Result); UCheb(X, -2.927977e-02, TJ, TJ1, Result); UCheb(X, -8.726500e-03, TJ, TJ1, Result); UCheb(X, -5.858745e-04, TJ, TJ1, Result); UCheb(X, 2.654590e-03, TJ, TJ1, Result); UCheb(X, 3.217736e-03, TJ, TJ1, Result); UCheb(X, 2.989770e-03, TJ, TJ1, Result); UCheb(X, 2.768493e-03, TJ, TJ1, Result); UCheb(X, 2.924364e-03, TJ, TJ1, Result); UCheb(X, 3.140215e-03, TJ, TJ1, Result); UCheb(X, 2.647914e-03, TJ, TJ1, Result); UCheb(X, 1.924802e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 12) *************************************************************************) function UTblN6N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.371709e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.020941e+00, TJ, TJ1, Result); UCheb(X, -4.294250e+00, TJ, TJ1, Result); UCheb(X, -1.128842e+00, TJ, TJ1, Result); UCheb(X, -2.650389e-01, TJ, TJ1, Result); UCheb(X, -9.248611e-02, TJ, TJ1, Result); UCheb(X, -3.578510e-02, TJ, TJ1, Result); UCheb(X, -1.162852e-02, TJ, TJ1, Result); UCheb(X, -1.746982e-03, TJ, TJ1, Result); UCheb(X, 2.454209e-03, TJ, TJ1, Result); UCheb(X, 3.128042e-03, TJ, TJ1, Result); UCheb(X, 2.936650e-03, TJ, TJ1, Result); UCheb(X, 2.530794e-03, TJ, TJ1, Result); UCheb(X, 2.665192e-03, TJ, TJ1, Result); UCheb(X, 2.994144e-03, TJ, TJ1, Result); UCheb(X, 2.662249e-03, TJ, TJ1, Result); UCheb(X, 2.368541e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 13) *************************************************************************) function UTblN6N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.420526e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.133167e+00, TJ, TJ1, Result); UCheb(X, -4.450016e+00, TJ, TJ1, Result); UCheb(X, -1.191088e+00, TJ, TJ1, Result); UCheb(X, -2.898220e-01, TJ, TJ1, Result); UCheb(X, -1.050249e-01, TJ, TJ1, Result); UCheb(X, -4.226901e-02, TJ, TJ1, Result); UCheb(X, -1.471113e-02, TJ, TJ1, Result); UCheb(X, -3.007470e-03, TJ, TJ1, Result); UCheb(X, 2.049420e-03, TJ, TJ1, Result); UCheb(X, 3.059074e-03, TJ, TJ1, Result); UCheb(X, 2.881249e-03, TJ, TJ1, Result); UCheb(X, 2.452780e-03, TJ, TJ1, Result); UCheb(X, 2.441805e-03, TJ, TJ1, Result); UCheb(X, 2.787493e-03, TJ, TJ1, Result); UCheb(X, 2.483957e-03, TJ, TJ1, Result); UCheb(X, 2.481590e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 14) *************************************************************************) function UTblN6N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.450000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.201268e+00, TJ, TJ1, Result); UCheb(X, -4.542568e+00, TJ, TJ1, Result); UCheb(X, -1.226965e+00, TJ, TJ1, Result); UCheb(X, -3.046029e-01, TJ, TJ1, Result); UCheb(X, -1.136657e-01, TJ, TJ1, Result); UCheb(X, -4.786757e-02, TJ, TJ1, Result); UCheb(X, -1.843748e-02, TJ, TJ1, Result); UCheb(X, -5.588022e-03, TJ, TJ1, Result); UCheb(X, 2.253029e-04, TJ, TJ1, Result); UCheb(X, 1.667188e-03, TJ, TJ1, Result); UCheb(X, 1.788330e-03, TJ, TJ1, Result); UCheb(X, 1.474545e-03, TJ, TJ1, Result); UCheb(X, 1.540494e-03, TJ, TJ1, Result); UCheb(X, 1.951188e-03, TJ, TJ1, Result); UCheb(X, 1.863323e-03, TJ, TJ1, Result); UCheb(X, 2.220904e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 15) *************************************************************************) function UTblN6N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.450000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.195689e+00, TJ, TJ1, Result); UCheb(X, -4.526567e+00, TJ, TJ1, Result); UCheb(X, -1.213617e+00, TJ, TJ1, Result); UCheb(X, -2.975035e-01, TJ, TJ1, Result); UCheb(X, -1.118480e-01, TJ, TJ1, Result); UCheb(X, -4.859142e-02, TJ, TJ1, Result); UCheb(X, -2.083312e-02, TJ, TJ1, Result); UCheb(X, -8.298720e-03, TJ, TJ1, Result); UCheb(X, -2.766708e-03, TJ, TJ1, Result); UCheb(X, -1.026356e-03, TJ, TJ1, Result); UCheb(X, -9.093113e-04, TJ, TJ1, Result); UCheb(X, -1.135168e-03, TJ, TJ1, Result); UCheb(X, -1.136376e-03, TJ, TJ1, Result); UCheb(X, -8.190870e-04, TJ, TJ1, Result); UCheb(X, -4.435972e-04, TJ, TJ1, Result); UCheb(X, 1.413129e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 30) *************************************************************************) function UTblN6N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.450000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.166269e+00, TJ, TJ1, Result); UCheb(X, -4.427399e+00, TJ, TJ1, Result); UCheb(X, -1.118239e+00, TJ, TJ1, Result); UCheb(X, -2.360847e-01, TJ, TJ1, Result); UCheb(X, -7.745885e-02, TJ, TJ1, Result); UCheb(X, -3.025041e-02, TJ, TJ1, Result); UCheb(X, -1.187179e-02, TJ, TJ1, Result); UCheb(X, -4.432089e-03, TJ, TJ1, Result); UCheb(X, -1.408451e-03, TJ, TJ1, Result); UCheb(X, -4.388774e-04, TJ, TJ1, Result); UCheb(X, -2.795560e-04, TJ, TJ1, Result); UCheb(X, -2.304136e-04, TJ, TJ1, Result); UCheb(X, -1.258516e-04, TJ, TJ1, Result); UCheb(X, -4.180236e-05, TJ, TJ1, Result); UCheb(X, -4.388679e-06, TJ, TJ1, Result); UCheb(X, 4.836027e-06, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 6, 100) *************************************************************************) function UTblN6N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.450000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.181350e+00, TJ, TJ1, Result); UCheb(X, -4.417919e+00, TJ, TJ1, Result); UCheb(X, -1.094201e+00, TJ, TJ1, Result); UCheb(X, -2.195883e-01, TJ, TJ1, Result); UCheb(X, -6.818937e-02, TJ, TJ1, Result); UCheb(X, -2.514202e-02, TJ, TJ1, Result); UCheb(X, -9.125047e-03, TJ, TJ1, Result); UCheb(X, -3.022148e-03, TJ, TJ1, Result); UCheb(X, -7.284181e-04, TJ, TJ1, Result); UCheb(X, -1.157766e-04, TJ, TJ1, Result); UCheb(X, -1.023752e-04, TJ, TJ1, Result); UCheb(X, -1.127985e-04, TJ, TJ1, Result); UCheb(X, -5.221690e-05, TJ, TJ1, Result); UCheb(X, -3.516179e-06, TJ, TJ1, Result); UCheb(X, 9.501398e-06, TJ, TJ1, Result); UCheb(X, 9.380220e-06, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 7) *************************************************************************) function UTblN7N7(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.130495e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.501264e+00, TJ, TJ1, Result); UCheb(X, -3.584790e+00, TJ, TJ1, Result); UCheb(X, -8.577311e-01, TJ, TJ1, Result); UCheb(X, -1.617002e-01, TJ, TJ1, Result); UCheb(X, -4.145186e-02, TJ, TJ1, Result); UCheb(X, -1.023462e-02, TJ, TJ1, Result); UCheb(X, -1.408251e-03, TJ, TJ1, Result); UCheb(X, 8.626515e-04, TJ, TJ1, Result); UCheb(X, 2.072492e-03, TJ, TJ1, Result); UCheb(X, 3.722926e-03, TJ, TJ1, Result); UCheb(X, 5.095445e-03, TJ, TJ1, Result); UCheb(X, 4.842602e-03, TJ, TJ1, Result); UCheb(X, 2.751427e-03, TJ, TJ1, Result); UCheb(X, 2.008927e-04, TJ, TJ1, Result); UCheb(X, -9.892431e-04, TJ, TJ1, Result); UCheb(X, -8.772386e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 8) *************************************************************************) function UTblN7N8(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.240370e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.709965e+00, TJ, TJ1, Result); UCheb(X, -3.862154e+00, TJ, TJ1, Result); UCheb(X, -9.504541e-01, TJ, TJ1, Result); UCheb(X, -1.900195e-01, TJ, TJ1, Result); UCheb(X, -5.439995e-02, TJ, TJ1, Result); UCheb(X, -1.678028e-02, TJ, TJ1, Result); UCheb(X, -4.485540e-03, TJ, TJ1, Result); UCheb(X, -4.437047e-04, TJ, TJ1, Result); UCheb(X, 1.440092e-03, TJ, TJ1, Result); UCheb(X, 3.114227e-03, TJ, TJ1, Result); UCheb(X, 4.516569e-03, TJ, TJ1, Result); UCheb(X, 4.829457e-03, TJ, TJ1, Result); UCheb(X, 3.787550e-03, TJ, TJ1, Result); UCheb(X, 1.761866e-03, TJ, TJ1, Result); UCheb(X, 1.991911e-04, TJ, TJ1, Result); UCheb(X, -4.533481e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 9) *************************************************************************) function UTblN7N9(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.334314e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.896550e+00, TJ, TJ1, Result); UCheb(X, -4.112671e+00, TJ, TJ1, Result); UCheb(X, -1.037277e+00, TJ, TJ1, Result); UCheb(X, -2.181695e-01, TJ, TJ1, Result); UCheb(X, -6.765190e-02, TJ, TJ1, Result); UCheb(X, -2.360116e-02, TJ, TJ1, Result); UCheb(X, -7.695960e-03, TJ, TJ1, Result); UCheb(X, -1.780578e-03, TJ, TJ1, Result); UCheb(X, 8.963843e-04, TJ, TJ1, Result); UCheb(X, 2.616148e-03, TJ, TJ1, Result); UCheb(X, 3.852104e-03, TJ, TJ1, Result); UCheb(X, 4.390744e-03, TJ, TJ1, Result); UCheb(X, 4.014041e-03, TJ, TJ1, Result); UCheb(X, 2.888101e-03, TJ, TJ1, Result); UCheb(X, 1.467474e-03, TJ, TJ1, Result); UCheb(X, 4.004611e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 10) *************************************************************************) function UTblN7N10(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.415650e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.064844e+00, TJ, TJ1, Result); UCheb(X, -4.340749e+00, TJ, TJ1, Result); UCheb(X, -1.118888e+00, TJ, TJ1, Result); UCheb(X, -2.459730e-01, TJ, TJ1, Result); UCheb(X, -8.097781e-02, TJ, TJ1, Result); UCheb(X, -3.057688e-02, TJ, TJ1, Result); UCheb(X, -1.097406e-02, TJ, TJ1, Result); UCheb(X, -3.209262e-03, TJ, TJ1, Result); UCheb(X, 4.065641e-04, TJ, TJ1, Result); UCheb(X, 2.196677e-03, TJ, TJ1, Result); UCheb(X, 3.313994e-03, TJ, TJ1, Result); UCheb(X, 3.827157e-03, TJ, TJ1, Result); UCheb(X, 3.822284e-03, TJ, TJ1, Result); UCheb(X, 3.389090e-03, TJ, TJ1, Result); UCheb(X, 2.340850e-03, TJ, TJ1, Result); UCheb(X, 1.395172e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 11) *************************************************************************) function UTblN7N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.486817e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.217795e+00, TJ, TJ1, Result); UCheb(X, -4.549783e+00, TJ, TJ1, Result); UCheb(X, -1.195905e+00, TJ, TJ1, Result); UCheb(X, -2.733093e-01, TJ, TJ1, Result); UCheb(X, -9.428447e-02, TJ, TJ1, Result); UCheb(X, -3.760093e-02, TJ, TJ1, Result); UCheb(X, -1.431676e-02, TJ, TJ1, Result); UCheb(X, -4.717152e-03, TJ, TJ1, Result); UCheb(X, -1.032199e-04, TJ, TJ1, Result); UCheb(X, 1.832423e-03, TJ, TJ1, Result); UCheb(X, 2.905979e-03, TJ, TJ1, Result); UCheb(X, 3.302799e-03, TJ, TJ1, Result); UCheb(X, 3.464371e-03, TJ, TJ1, Result); UCheb(X, 3.456211e-03, TJ, TJ1, Result); UCheb(X, 2.736244e-03, TJ, TJ1, Result); UCheb(X, 2.140712e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 12) *************************************************************************) function UTblN7N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.500000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.235822e+00, TJ, TJ1, Result); UCheb(X, -4.564100e+00, TJ, TJ1, Result); UCheb(X, -1.190813e+00, TJ, TJ1, Result); UCheb(X, -2.686546e-01, TJ, TJ1, Result); UCheb(X, -9.395083e-02, TJ, TJ1, Result); UCheb(X, -3.967359e-02, TJ, TJ1, Result); UCheb(X, -1.747096e-02, TJ, TJ1, Result); UCheb(X, -8.304144e-03, TJ, TJ1, Result); UCheb(X, -3.903198e-03, TJ, TJ1, Result); UCheb(X, -2.134906e-03, TJ, TJ1, Result); UCheb(X, -1.175035e-03, TJ, TJ1, Result); UCheb(X, -7.266224e-04, TJ, TJ1, Result); UCheb(X, -1.892931e-04, TJ, TJ1, Result); UCheb(X, 5.604706e-04, TJ, TJ1, Result); UCheb(X, 9.070459e-04, TJ, TJ1, Result); UCheb(X, 1.427010e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 13) *************************************************************************) function UTblN7N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.500000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.222204e+00, TJ, TJ1, Result); UCheb(X, -4.532300e+00, TJ, TJ1, Result); UCheb(X, -1.164642e+00, TJ, TJ1, Result); UCheb(X, -2.523768e-01, TJ, TJ1, Result); UCheb(X, -8.531984e-02, TJ, TJ1, Result); UCheb(X, -3.467857e-02, TJ, TJ1, Result); UCheb(X, -1.483804e-02, TJ, TJ1, Result); UCheb(X, -6.524136e-03, TJ, TJ1, Result); UCheb(X, -3.077740e-03, TJ, TJ1, Result); UCheb(X, -1.745218e-03, TJ, TJ1, Result); UCheb(X, -1.602085e-03, TJ, TJ1, Result); UCheb(X, -1.828831e-03, TJ, TJ1, Result); UCheb(X, -1.994070e-03, TJ, TJ1, Result); UCheb(X, -1.873879e-03, TJ, TJ1, Result); UCheb(X, -1.341937e-03, TJ, TJ1, Result); UCheb(X, -8.706444e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 14) *************************************************************************) function UTblN7N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.500000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.211763e+00, TJ, TJ1, Result); UCheb(X, -4.507542e+00, TJ, TJ1, Result); UCheb(X, -1.143640e+00, TJ, TJ1, Result); UCheb(X, -2.395755e-01, TJ, TJ1, Result); UCheb(X, -7.808020e-02, TJ, TJ1, Result); UCheb(X, -3.044259e-02, TJ, TJ1, Result); UCheb(X, -1.182308e-02, TJ, TJ1, Result); UCheb(X, -4.057325e-03, TJ, TJ1, Result); UCheb(X, -5.724255e-04, TJ, TJ1, Result); UCheb(X, 8.303900e-04, TJ, TJ1, Result); UCheb(X, 1.113148e-03, TJ, TJ1, Result); UCheb(X, 8.102514e-04, TJ, TJ1, Result); UCheb(X, 3.559442e-04, TJ, TJ1, Result); UCheb(X, 4.634986e-05, TJ, TJ1, Result); UCheb(X, -8.776476e-05, TJ, TJ1, Result); UCheb(X, 1.054489e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 15) *************************************************************************) function UTblN7N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.500000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.204898e+00, TJ, TJ1, Result); UCheb(X, -4.489960e+00, TJ, TJ1, Result); UCheb(X, -1.129172e+00, TJ, TJ1, Result); UCheb(X, -2.316741e-01, TJ, TJ1, Result); UCheb(X, -7.506107e-02, TJ, TJ1, Result); UCheb(X, -2.983676e-02, TJ, TJ1, Result); UCheb(X, -1.258013e-02, TJ, TJ1, Result); UCheb(X, -5.262515e-03, TJ, TJ1, Result); UCheb(X, -1.984156e-03, TJ, TJ1, Result); UCheb(X, -3.912108e-04, TJ, TJ1, Result); UCheb(X, 8.974023e-05, TJ, TJ1, Result); UCheb(X, 6.056195e-05, TJ, TJ1, Result); UCheb(X, -2.090842e-04, TJ, TJ1, Result); UCheb(X, -5.232620e-04, TJ, TJ1, Result); UCheb(X, -5.816339e-04, TJ, TJ1, Result); UCheb(X, -7.020421e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 30) *************************************************************************) function UTblN7N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.500000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.176536e+00, TJ, TJ1, Result); UCheb(X, -4.398705e+00, TJ, TJ1, Result); UCheb(X, -1.045481e+00, TJ, TJ1, Result); UCheb(X, -1.821982e-01, TJ, TJ1, Result); UCheb(X, -4.962304e-02, TJ, TJ1, Result); UCheb(X, -1.698132e-02, TJ, TJ1, Result); UCheb(X, -6.062667e-03, TJ, TJ1, Result); UCheb(X, -2.282353e-03, TJ, TJ1, Result); UCheb(X, -8.014836e-04, TJ, TJ1, Result); UCheb(X, -2.035683e-04, TJ, TJ1, Result); UCheb(X, -1.004137e-05, TJ, TJ1, Result); UCheb(X, 3.801453e-06, TJ, TJ1, Result); UCheb(X, -1.920705e-05, TJ, TJ1, Result); UCheb(X, -2.518735e-05, TJ, TJ1, Result); UCheb(X, -1.821501e-05, TJ, TJ1, Result); UCheb(X, -1.801008e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 7, 100) *************************************************************************) function UTblN7N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.500000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.188337e+00, TJ, TJ1, Result); UCheb(X, -4.386949e+00, TJ, TJ1, Result); UCheb(X, -1.022834e+00, TJ, TJ1, Result); UCheb(X, -1.686517e-01, TJ, TJ1, Result); UCheb(X, -4.323516e-02, TJ, TJ1, Result); UCheb(X, -1.399392e-02, TJ, TJ1, Result); UCheb(X, -4.644333e-03, TJ, TJ1, Result); UCheb(X, -1.617044e-03, TJ, TJ1, Result); UCheb(X, -5.031396e-04, TJ, TJ1, Result); UCheb(X, -8.792066e-05, TJ, TJ1, Result); UCheb(X, 2.675457e-05, TJ, TJ1, Result); UCheb(X, 1.673416e-05, TJ, TJ1, Result); UCheb(X, -6.258552e-06, TJ, TJ1, Result); UCheb(X, -8.174214e-06, TJ, TJ1, Result); UCheb(X, -3.073644e-06, TJ, TJ1, Result); UCheb(X, -1.349958e-06, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 8) *************************************************************************) function UTblN8N8(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.360672e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -3.940217e+00, TJ, TJ1, Result); UCheb(X, -4.168913e+00, TJ, TJ1, Result); UCheb(X, -1.051485e+00, TJ, TJ1, Result); UCheb(X, -2.195325e-01, TJ, TJ1, Result); UCheb(X, -6.775196e-02, TJ, TJ1, Result); UCheb(X, -2.385506e-02, TJ, TJ1, Result); UCheb(X, -8.244902e-03, TJ, TJ1, Result); UCheb(X, -2.525632e-03, TJ, TJ1, Result); UCheb(X, 2.771275e-04, TJ, TJ1, Result); UCheb(X, 2.332874e-03, TJ, TJ1, Result); UCheb(X, 4.079599e-03, TJ, TJ1, Result); UCheb(X, 4.882551e-03, TJ, TJ1, Result); UCheb(X, 4.407944e-03, TJ, TJ1, Result); UCheb(X, 2.769844e-03, TJ, TJ1, Result); UCheb(X, 1.062433e-03, TJ, TJ1, Result); UCheb(X, 5.872535e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 9) *************************************************************************) function UTblN8N9(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.464102e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.147004e+00, TJ, TJ1, Result); UCheb(X, -4.446939e+00, TJ, TJ1, Result); UCheb(X, -1.146155e+00, TJ, TJ1, Result); UCheb(X, -2.488561e-01, TJ, TJ1, Result); UCheb(X, -8.144561e-02, TJ, TJ1, Result); UCheb(X, -3.116917e-02, TJ, TJ1, Result); UCheb(X, -1.205667e-02, TJ, TJ1, Result); UCheb(X, -4.515661e-03, TJ, TJ1, Result); UCheb(X, -7.618616e-04, TJ, TJ1, Result); UCheb(X, 1.599011e-03, TJ, TJ1, Result); UCheb(X, 3.457324e-03, TJ, TJ1, Result); UCheb(X, 4.482917e-03, TJ, TJ1, Result); UCheb(X, 4.488267e-03, TJ, TJ1, Result); UCheb(X, 3.469823e-03, TJ, TJ1, Result); UCheb(X, 1.957591e-03, TJ, TJ1, Result); UCheb(X, 8.058326e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 10) *************************************************************************) function UTblN8N10(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.554093e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.334282e+00, TJ, TJ1, Result); UCheb(X, -4.700860e+00, TJ, TJ1, Result); UCheb(X, -1.235253e+00, TJ, TJ1, Result); UCheb(X, -2.778489e-01, TJ, TJ1, Result); UCheb(X, -9.527324e-02, TJ, TJ1, Result); UCheb(X, -3.862885e-02, TJ, TJ1, Result); UCheb(X, -1.589781e-02, TJ, TJ1, Result); UCheb(X, -6.507355e-03, TJ, TJ1, Result); UCheb(X, -1.717526e-03, TJ, TJ1, Result); UCheb(X, 9.215726e-04, TJ, TJ1, Result); UCheb(X, 2.848696e-03, TJ, TJ1, Result); UCheb(X, 3.918854e-03, TJ, TJ1, Result); UCheb(X, 4.219614e-03, TJ, TJ1, Result); UCheb(X, 3.753761e-03, TJ, TJ1, Result); UCheb(X, 2.573688e-03, TJ, TJ1, Result); UCheb(X, 1.602177e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 11) *************************************************************************) function UTblN8N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.421882e+00, TJ, TJ1, Result); UCheb(X, -4.812457e+00, TJ, TJ1, Result); UCheb(X, -1.266153e+00, TJ, TJ1, Result); UCheb(X, -2.849344e-01, TJ, TJ1, Result); UCheb(X, -9.971527e-02, TJ, TJ1, Result); UCheb(X, -4.258944e-02, TJ, TJ1, Result); UCheb(X, -1.944820e-02, TJ, TJ1, Result); UCheb(X, -9.894685e-03, TJ, TJ1, Result); UCheb(X, -5.031836e-03, TJ, TJ1, Result); UCheb(X, -2.514330e-03, TJ, TJ1, Result); UCheb(X, -6.351660e-04, TJ, TJ1, Result); UCheb(X, 6.206748e-04, TJ, TJ1, Result); UCheb(X, 1.492600e-03, TJ, TJ1, Result); UCheb(X, 2.005338e-03, TJ, TJ1, Result); UCheb(X, 1.780099e-03, TJ, TJ1, Result); UCheb(X, 1.673599e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 12) *************************************************************************) function UTblN8N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.398211e+00, TJ, TJ1, Result); UCheb(X, -4.762214e+00, TJ, TJ1, Result); UCheb(X, -1.226296e+00, TJ, TJ1, Result); UCheb(X, -2.603837e-01, TJ, TJ1, Result); UCheb(X, -8.643223e-02, TJ, TJ1, Result); UCheb(X, -3.502438e-02, TJ, TJ1, Result); UCheb(X, -1.544574e-02, TJ, TJ1, Result); UCheb(X, -7.647734e-03, TJ, TJ1, Result); UCheb(X, -4.442259e-03, TJ, TJ1, Result); UCheb(X, -3.011484e-03, TJ, TJ1, Result); UCheb(X, -2.384758e-03, TJ, TJ1, Result); UCheb(X, -1.998259e-03, TJ, TJ1, Result); UCheb(X, -1.659985e-03, TJ, TJ1, Result); UCheb(X, -1.331046e-03, TJ, TJ1, Result); UCheb(X, -8.638478e-04, TJ, TJ1, Result); UCheb(X, -6.056785e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 13) *************************************************************************) function UTblN8N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.380670e+00, TJ, TJ1, Result); UCheb(X, -4.724511e+00, TJ, TJ1, Result); UCheb(X, -1.195851e+00, TJ, TJ1, Result); UCheb(X, -2.420511e-01, TJ, TJ1, Result); UCheb(X, -7.609928e-02, TJ, TJ1, Result); UCheb(X, -2.893999e-02, TJ, TJ1, Result); UCheb(X, -1.115919e-02, TJ, TJ1, Result); UCheb(X, -4.291410e-03, TJ, TJ1, Result); UCheb(X, -1.339664e-03, TJ, TJ1, Result); UCheb(X, -1.801548e-04, TJ, TJ1, Result); UCheb(X, 2.534710e-04, TJ, TJ1, Result); UCheb(X, 2.793250e-04, TJ, TJ1, Result); UCheb(X, 1.806718e-04, TJ, TJ1, Result); UCheb(X, 1.384624e-04, TJ, TJ1, Result); UCheb(X, 1.120582e-04, TJ, TJ1, Result); UCheb(X, 2.936453e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 14) *************************************************************************) function UTblN8N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.368494e+00, TJ, TJ1, Result); UCheb(X, -4.697171e+00, TJ, TJ1, Result); UCheb(X, -1.174440e+00, TJ, TJ1, Result); UCheb(X, -2.300621e-01, TJ, TJ1, Result); UCheb(X, -7.087393e-02, TJ, TJ1, Result); UCheb(X, -2.685826e-02, TJ, TJ1, Result); UCheb(X, -1.085254e-02, TJ, TJ1, Result); UCheb(X, -4.525658e-03, TJ, TJ1, Result); UCheb(X, -1.966647e-03, TJ, TJ1, Result); UCheb(X, -7.453388e-04, TJ, TJ1, Result); UCheb(X, -3.826066e-04, TJ, TJ1, Result); UCheb(X, -3.501958e-04, TJ, TJ1, Result); UCheb(X, -5.336297e-04, TJ, TJ1, Result); UCheb(X, -8.251972e-04, TJ, TJ1, Result); UCheb(X, -8.118456e-04, TJ, TJ1, Result); UCheb(X, -9.415959e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 15) *************************************************************************) function UTblN8N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.358397e+00, TJ, TJ1, Result); UCheb(X, -4.674485e+00, TJ, TJ1, Result); UCheb(X, -1.155941e+00, TJ, TJ1, Result); UCheb(X, -2.195780e-01, TJ, TJ1, Result); UCheb(X, -6.544830e-02, TJ, TJ1, Result); UCheb(X, -2.426183e-02, TJ, TJ1, Result); UCheb(X, -9.309902e-03, TJ, TJ1, Result); UCheb(X, -3.650956e-03, TJ, TJ1, Result); UCheb(X, -1.068874e-03, TJ, TJ1, Result); UCheb(X, 1.538544e-04, TJ, TJ1, Result); UCheb(X, 8.192525e-04, TJ, TJ1, Result); UCheb(X, 1.073905e-03, TJ, TJ1, Result); UCheb(X, 1.079673e-03, TJ, TJ1, Result); UCheb(X, 9.423572e-04, TJ, TJ1, Result); UCheb(X, 6.579647e-04, TJ, TJ1, Result); UCheb(X, 4.765904e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 30) *************************************************************************) function UTblN8N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.318823e+00, TJ, TJ1, Result); UCheb(X, -4.567159e+00, TJ, TJ1, Result); UCheb(X, -1.064864e+00, TJ, TJ1, Result); UCheb(X, -1.688413e-01, TJ, TJ1, Result); UCheb(X, -4.153712e-02, TJ, TJ1, Result); UCheb(X, -1.309389e-02, TJ, TJ1, Result); UCheb(X, -4.226861e-03, TJ, TJ1, Result); UCheb(X, -1.523815e-03, TJ, TJ1, Result); UCheb(X, -5.780987e-04, TJ, TJ1, Result); UCheb(X, -2.166866e-04, TJ, TJ1, Result); UCheb(X, -6.922431e-05, TJ, TJ1, Result); UCheb(X, -1.466397e-05, TJ, TJ1, Result); UCheb(X, -5.690036e-06, TJ, TJ1, Result); UCheb(X, -1.008185e-05, TJ, TJ1, Result); UCheb(X, -9.271903e-06, TJ, TJ1, Result); UCheb(X, -7.534751e-06, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 8, 100) *************************************************************************) function UTblN8N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.600000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.324531e+00, TJ, TJ1, Result); UCheb(X, -4.547071e+00, TJ, TJ1, Result); UCheb(X, -1.038129e+00, TJ, TJ1, Result); UCheb(X, -1.541549e-01, TJ, TJ1, Result); UCheb(X, -3.525605e-02, TJ, TJ1, Result); UCheb(X, -1.044992e-02, TJ, TJ1, Result); UCheb(X, -3.085713e-03, TJ, TJ1, Result); UCheb(X, -1.017871e-03, TJ, TJ1, Result); UCheb(X, -3.459226e-04, TJ, TJ1, Result); UCheb(X, -1.092064e-04, TJ, TJ1, Result); UCheb(X, -2.024349e-05, TJ, TJ1, Result); UCheb(X, 7.366347e-06, TJ, TJ1, Result); UCheb(X, 6.385637e-06, TJ, TJ1, Result); UCheb(X, 8.321722e-08, TJ, TJ1, Result); UCheb(X, -1.439286e-06, TJ, TJ1, Result); UCheb(X, -3.058079e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 9) *************************************************************************) function UTblN9N9(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.576237e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.372857e+00, TJ, TJ1, Result); UCheb(X, -4.750859e+00, TJ, TJ1, Result); UCheb(X, -1.248233e+00, TJ, TJ1, Result); UCheb(X, -2.792868e-01, TJ, TJ1, Result); UCheb(X, -9.559372e-02, TJ, TJ1, Result); UCheb(X, -3.894941e-02, TJ, TJ1, Result); UCheb(X, -1.643256e-02, TJ, TJ1, Result); UCheb(X, -7.091370e-03, TJ, TJ1, Result); UCheb(X, -2.285034e-03, TJ, TJ1, Result); UCheb(X, 6.112997e-04, TJ, TJ1, Result); UCheb(X, 2.806229e-03, TJ, TJ1, Result); UCheb(X, 4.150741e-03, TJ, TJ1, Result); UCheb(X, 4.509825e-03, TJ, TJ1, Result); UCheb(X, 3.891051e-03, TJ, TJ1, Result); UCheb(X, 2.485013e-03, TJ, TJ1, Result); UCheb(X, 1.343653e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 10) *************************************************************************) function UTblN9N10(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.516726e+00, TJ, TJ1, Result); UCheb(X, -4.939333e+00, TJ, TJ1, Result); UCheb(X, -1.305046e+00, TJ, TJ1, Result); UCheb(X, -2.935326e-01, TJ, TJ1, Result); UCheb(X, -1.029141e-01, TJ, TJ1, Result); UCheb(X, -4.420592e-02, TJ, TJ1, Result); UCheb(X, -2.053140e-02, TJ, TJ1, Result); UCheb(X, -1.065930e-02, TJ, TJ1, Result); UCheb(X, -5.523581e-03, TJ, TJ1, Result); UCheb(X, -2.544888e-03, TJ, TJ1, Result); UCheb(X, -1.813741e-04, TJ, TJ1, Result); UCheb(X, 1.510631e-03, TJ, TJ1, Result); UCheb(X, 2.536057e-03, TJ, TJ1, Result); UCheb(X, 2.833815e-03, TJ, TJ1, Result); UCheb(X, 2.189692e-03, TJ, TJ1, Result); UCheb(X, 1.615050e-03, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 11) *************************************************************************) function UTblN9N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.481308e+00, TJ, TJ1, Result); UCheb(X, -4.867483e+00, TJ, TJ1, Result); UCheb(X, -1.249072e+00, TJ, TJ1, Result); UCheb(X, -2.591790e-01, TJ, TJ1, Result); UCheb(X, -8.400128e-02, TJ, TJ1, Result); UCheb(X, -3.341992e-02, TJ, TJ1, Result); UCheb(X, -1.463680e-02, TJ, TJ1, Result); UCheb(X, -7.487211e-03, TJ, TJ1, Result); UCheb(X, -4.671196e-03, TJ, TJ1, Result); UCheb(X, -3.343472e-03, TJ, TJ1, Result); UCheb(X, -2.544146e-03, TJ, TJ1, Result); UCheb(X, -1.802335e-03, TJ, TJ1, Result); UCheb(X, -1.117084e-03, TJ, TJ1, Result); UCheb(X, -6.217443e-04, TJ, TJ1, Result); UCheb(X, -2.858766e-04, TJ, TJ1, Result); UCheb(X, -3.193687e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 12) *************************************************************************) function UTblN9N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.456776e+00, TJ, TJ1, Result); UCheb(X, -4.817037e+00, TJ, TJ1, Result); UCheb(X, -1.209788e+00, TJ, TJ1, Result); UCheb(X, -2.362108e-01, TJ, TJ1, Result); UCheb(X, -7.171356e-02, TJ, TJ1, Result); UCheb(X, -2.661557e-02, TJ, TJ1, Result); UCheb(X, -1.026141e-02, TJ, TJ1, Result); UCheb(X, -4.361908e-03, TJ, TJ1, Result); UCheb(X, -2.093885e-03, TJ, TJ1, Result); UCheb(X, -1.298389e-03, TJ, TJ1, Result); UCheb(X, -9.663603e-04, TJ, TJ1, Result); UCheb(X, -7.768522e-04, TJ, TJ1, Result); UCheb(X, -5.579015e-04, TJ, TJ1, Result); UCheb(X, -2.868677e-04, TJ, TJ1, Result); UCheb(X, -7.440652e-05, TJ, TJ1, Result); UCheb(X, 1.523037e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 13) *************************************************************************) function UTblN9N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.438840e+00, TJ, TJ1, Result); UCheb(X, -4.779308e+00, TJ, TJ1, Result); UCheb(X, -1.180614e+00, TJ, TJ1, Result); UCheb(X, -2.196489e-01, TJ, TJ1, Result); UCheb(X, -6.346621e-02, TJ, TJ1, Result); UCheb(X, -2.234857e-02, TJ, TJ1, Result); UCheb(X, -7.796211e-03, TJ, TJ1, Result); UCheb(X, -2.575715e-03, TJ, TJ1, Result); UCheb(X, -5.525647e-04, TJ, TJ1, Result); UCheb(X, 1.964651e-04, TJ, TJ1, Result); UCheb(X, 4.275235e-04, TJ, TJ1, Result); UCheb(X, 4.299124e-04, TJ, TJ1, Result); UCheb(X, 3.397416e-04, TJ, TJ1, Result); UCheb(X, 2.295781e-04, TJ, TJ1, Result); UCheb(X, 1.237619e-04, TJ, TJ1, Result); UCheb(X, 7.269692e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 14) *************************************************************************) function UTblN9N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.425981e+00, TJ, TJ1, Result); UCheb(X, -4.751545e+00, TJ, TJ1, Result); UCheb(X, -1.159543e+00, TJ, TJ1, Result); UCheb(X, -2.086570e-01, TJ, TJ1, Result); UCheb(X, -5.917446e-02, TJ, TJ1, Result); UCheb(X, -2.120112e-02, TJ, TJ1, Result); UCheb(X, -8.175519e-03, TJ, TJ1, Result); UCheb(X, -3.515473e-03, TJ, TJ1, Result); UCheb(X, -1.727772e-03, TJ, TJ1, Result); UCheb(X, -9.070629e-04, TJ, TJ1, Result); UCheb(X, -5.677569e-04, TJ, TJ1, Result); UCheb(X, -3.876953e-04, TJ, TJ1, Result); UCheb(X, -3.233502e-04, TJ, TJ1, Result); UCheb(X, -3.508182e-04, TJ, TJ1, Result); UCheb(X, -3.120389e-04, TJ, TJ1, Result); UCheb(X, -3.847212e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 15) *************************************************************************) function UTblN9N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.414952e+00, TJ, TJ1, Result); UCheb(X, -4.727612e+00, TJ, TJ1, Result); UCheb(X, -1.140634e+00, TJ, TJ1, Result); UCheb(X, -1.981231e-01, TJ, TJ1, Result); UCheb(X, -5.382635e-02, TJ, TJ1, Result); UCheb(X, -1.853575e-02, TJ, TJ1, Result); UCheb(X, -6.571051e-03, TJ, TJ1, Result); UCheb(X, -2.567625e-03, TJ, TJ1, Result); UCheb(X, -9.214197e-04, TJ, TJ1, Result); UCheb(X, -2.448700e-04, TJ, TJ1, Result); UCheb(X, 1.712669e-04, TJ, TJ1, Result); UCheb(X, 4.015050e-04, TJ, TJ1, Result); UCheb(X, 5.438610e-04, TJ, TJ1, Result); UCheb(X, 6.301363e-04, TJ, TJ1, Result); UCheb(X, 5.309386e-04, TJ, TJ1, Result); UCheb(X, 5.164772e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 30) *************************************************************************) function UTblN9N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.370720e+00, TJ, TJ1, Result); UCheb(X, -4.615712e+00, TJ, TJ1, Result); UCheb(X, -1.050023e+00, TJ, TJ1, Result); UCheb(X, -1.504775e-01, TJ, TJ1, Result); UCheb(X, -3.318265e-02, TJ, TJ1, Result); UCheb(X, -9.646826e-03, TJ, TJ1, Result); UCheb(X, -2.741492e-03, TJ, TJ1, Result); UCheb(X, -8.735360e-04, TJ, TJ1, Result); UCheb(X, -2.966911e-04, TJ, TJ1, Result); UCheb(X, -1.100738e-04, TJ, TJ1, Result); UCheb(X, -4.348991e-05, TJ, TJ1, Result); UCheb(X, -1.527687e-05, TJ, TJ1, Result); UCheb(X, -2.917286e-06, TJ, TJ1, Result); UCheb(X, 3.397466e-07, TJ, TJ1, Result); UCheb(X, -2.360175e-07, TJ, TJ1, Result); UCheb(X, -9.892252e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 9, 100) *************************************************************************) function UTblN9N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.372506e+00, TJ, TJ1, Result); UCheb(X, -4.590966e+00, TJ, TJ1, Result); UCheb(X, -1.021758e+00, TJ, TJ1, Result); UCheb(X, -1.359849e-01, TJ, TJ1, Result); UCheb(X, -2.755519e-02, TJ, TJ1, Result); UCheb(X, -7.533166e-03, TJ, TJ1, Result); UCheb(X, -1.936659e-03, TJ, TJ1, Result); UCheb(X, -5.634913e-04, TJ, TJ1, Result); UCheb(X, -1.730053e-04, TJ, TJ1, Result); UCheb(X, -5.791845e-05, TJ, TJ1, Result); UCheb(X, -2.030682e-05, TJ, TJ1, Result); UCheb(X, -5.228663e-06, TJ, TJ1, Result); UCheb(X, 8.631175e-07, TJ, TJ1, Result); UCheb(X, 1.636749e-06, TJ, TJ1, Result); UCheb(X, 4.404599e-07, TJ, TJ1, Result); UCheb(X, -2.789872e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 10) *************************************************************************) function UTblN10N10(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.468831e+00, TJ, TJ1, Result); UCheb(X, -4.844398e+00, TJ, TJ1, Result); UCheb(X, -1.231728e+00, TJ, TJ1, Result); UCheb(X, -2.486073e-01, TJ, TJ1, Result); UCheb(X, -7.781321e-02, TJ, TJ1, Result); UCheb(X, -2.971425e-02, TJ, TJ1, Result); UCheb(X, -1.215371e-02, TJ, TJ1, Result); UCheb(X, -5.828451e-03, TJ, TJ1, Result); UCheb(X, -3.419872e-03, TJ, TJ1, Result); UCheb(X, -2.430165e-03, TJ, TJ1, Result); UCheb(X, -1.740363e-03, TJ, TJ1, Result); UCheb(X, -1.049211e-03, TJ, TJ1, Result); UCheb(X, -3.269371e-04, TJ, TJ1, Result); UCheb(X, 2.211393e-04, TJ, TJ1, Result); UCheb(X, 4.232314e-04, TJ, TJ1, Result); UCheb(X, 3.016081e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 11) *************************************************************************) function UTblN10N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.437998e+00, TJ, TJ1, Result); UCheb(X, -4.782296e+00, TJ, TJ1, Result); UCheb(X, -1.184732e+00, TJ, TJ1, Result); UCheb(X, -2.219585e-01, TJ, TJ1, Result); UCheb(X, -6.457012e-02, TJ, TJ1, Result); UCheb(X, -2.296008e-02, TJ, TJ1, Result); UCheb(X, -8.481501e-03, TJ, TJ1, Result); UCheb(X, -3.527940e-03, TJ, TJ1, Result); UCheb(X, -1.953426e-03, TJ, TJ1, Result); UCheb(X, -1.563840e-03, TJ, TJ1, Result); UCheb(X, -1.574403e-03, TJ, TJ1, Result); UCheb(X, -1.535775e-03, TJ, TJ1, Result); UCheb(X, -1.338037e-03, TJ, TJ1, Result); UCheb(X, -1.002654e-03, TJ, TJ1, Result); UCheb(X, -5.852676e-04, TJ, TJ1, Result); UCheb(X, -3.318132e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 12) *************************************************************************) function UTblN10N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.416082e+00, TJ, TJ1, Result); UCheb(X, -4.737458e+00, TJ, TJ1, Result); UCheb(X, -1.150952e+00, TJ, TJ1, Result); UCheb(X, -2.036884e-01, TJ, TJ1, Result); UCheb(X, -5.609030e-02, TJ, TJ1, Result); UCheb(X, -1.908684e-02, TJ, TJ1, Result); UCheb(X, -6.439666e-03, TJ, TJ1, Result); UCheb(X, -2.162647e-03, TJ, TJ1, Result); UCheb(X, -6.451601e-04, TJ, TJ1, Result); UCheb(X, -2.148757e-04, TJ, TJ1, Result); UCheb(X, -1.803981e-04, TJ, TJ1, Result); UCheb(X, -2.731621e-04, TJ, TJ1, Result); UCheb(X, -3.346903e-04, TJ, TJ1, Result); UCheb(X, -3.013151e-04, TJ, TJ1, Result); UCheb(X, -1.956148e-04, TJ, TJ1, Result); UCheb(X, -2.438381e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 13) *************************************************************************) function UTblN10N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.399480e+00, TJ, TJ1, Result); UCheb(X, -4.702863e+00, TJ, TJ1, Result); UCheb(X, -1.124829e+00, TJ, TJ1, Result); UCheb(X, -1.897428e-01, TJ, TJ1, Result); UCheb(X, -4.979802e-02, TJ, TJ1, Result); UCheb(X, -1.634368e-02, TJ, TJ1, Result); UCheb(X, -5.180461e-03, TJ, TJ1, Result); UCheb(X, -1.484926e-03, TJ, TJ1, Result); UCheb(X, -7.864376e-05, TJ, TJ1, Result); UCheb(X, 4.186576e-04, TJ, TJ1, Result); UCheb(X, 5.886925e-04, TJ, TJ1, Result); UCheb(X, 5.836828e-04, TJ, TJ1, Result); UCheb(X, 5.074756e-04, TJ, TJ1, Result); UCheb(X, 4.209547e-04, TJ, TJ1, Result); UCheb(X, 2.883266e-04, TJ, TJ1, Result); UCheb(X, 2.380143e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 14) *************************************************************************) function UTblN10N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.386924e+00, TJ, TJ1, Result); UCheb(X, -4.676124e+00, TJ, TJ1, Result); UCheb(X, -1.104740e+00, TJ, TJ1, Result); UCheb(X, -1.793826e-01, TJ, TJ1, Result); UCheb(X, -4.558886e-02, TJ, TJ1, Result); UCheb(X, -1.492462e-02, TJ, TJ1, Result); UCheb(X, -5.052903e-03, TJ, TJ1, Result); UCheb(X, -1.917782e-03, TJ, TJ1, Result); UCheb(X, -7.878696e-04, TJ, TJ1, Result); UCheb(X, -3.576046e-04, TJ, TJ1, Result); UCheb(X, -1.764551e-04, TJ, TJ1, Result); UCheb(X, -9.288778e-05, TJ, TJ1, Result); UCheb(X, -4.757658e-05, TJ, TJ1, Result); UCheb(X, -2.299101e-05, TJ, TJ1, Result); UCheb(X, -9.265197e-06, TJ, TJ1, Result); UCheb(X, -2.384503e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 15) *************************************************************************) function UTblN10N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.376846e+00, TJ, TJ1, Result); UCheb(X, -4.654247e+00, TJ, TJ1, Result); UCheb(X, -1.088083e+00, TJ, TJ1, Result); UCheb(X, -1.705945e-01, TJ, TJ1, Result); UCheb(X, -4.169677e-02, TJ, TJ1, Result); UCheb(X, -1.317213e-02, TJ, TJ1, Result); UCheb(X, -4.264836e-03, TJ, TJ1, Result); UCheb(X, -1.548024e-03, TJ, TJ1, Result); UCheb(X, -6.633910e-04, TJ, TJ1, Result); UCheb(X, -3.505621e-04, TJ, TJ1, Result); UCheb(X, -2.658588e-04, TJ, TJ1, Result); UCheb(X, -2.320254e-04, TJ, TJ1, Result); UCheb(X, -2.175277e-04, TJ, TJ1, Result); UCheb(X, -2.122317e-04, TJ, TJ1, Result); UCheb(X, -1.675688e-04, TJ, TJ1, Result); UCheb(X, -1.661363e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 30) *************************************************************************) function UTblN10N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.333977e+00, TJ, TJ1, Result); UCheb(X, -4.548099e+00, TJ, TJ1, Result); UCheb(X, -1.004444e+00, TJ, TJ1, Result); UCheb(X, -1.291014e-01, TJ, TJ1, Result); UCheb(X, -2.523674e-02, TJ, TJ1, Result); UCheb(X, -6.828211e-03, TJ, TJ1, Result); UCheb(X, -1.716917e-03, TJ, TJ1, Result); UCheb(X, -4.894256e-04, TJ, TJ1, Result); UCheb(X, -1.433371e-04, TJ, TJ1, Result); UCheb(X, -4.522675e-05, TJ, TJ1, Result); UCheb(X, -1.764192e-05, TJ, TJ1, Result); UCheb(X, -9.140235e-06, TJ, TJ1, Result); UCheb(X, -5.629230e-06, TJ, TJ1, Result); UCheb(X, -3.541895e-06, TJ, TJ1, Result); UCheb(X, -1.944946e-06, TJ, TJ1, Result); UCheb(X, -1.726360e-06, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 10, 100) *************************************************************************) function UTblN10N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.650000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.334008e+00, TJ, TJ1, Result); UCheb(X, -4.522316e+00, TJ, TJ1, Result); UCheb(X, -9.769627e-01, TJ, TJ1, Result); UCheb(X, -1.158110e-01, TJ, TJ1, Result); UCheb(X, -2.053650e-02, TJ, TJ1, Result); UCheb(X, -5.242235e-03, TJ, TJ1, Result); UCheb(X, -1.173571e-03, TJ, TJ1, Result); UCheb(X, -3.033661e-04, TJ, TJ1, Result); UCheb(X, -7.824732e-05, TJ, TJ1, Result); UCheb(X, -2.084420e-05, TJ, TJ1, Result); UCheb(X, -6.610036e-06, TJ, TJ1, Result); UCheb(X, -2.728155e-06, TJ, TJ1, Result); UCheb(X, -1.217130e-06, TJ, TJ1, Result); UCheb(X, -2.340966e-07, TJ, TJ1, Result); UCheb(X, 2.001235e-07, TJ, TJ1, Result); UCheb(X, 1.694052e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 11) *************************************************************************) function UTblN11N11(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.519760e+00, TJ, TJ1, Result); UCheb(X, -4.880694e+00, TJ, TJ1, Result); UCheb(X, -1.200698e+00, TJ, TJ1, Result); UCheb(X, -2.174092e-01, TJ, TJ1, Result); UCheb(X, -6.072304e-02, TJ, TJ1, Result); UCheb(X, -2.054773e-02, TJ, TJ1, Result); UCheb(X, -6.506613e-03, TJ, TJ1, Result); UCheb(X, -1.813942e-03, TJ, TJ1, Result); UCheb(X, -1.223644e-04, TJ, TJ1, Result); UCheb(X, 2.417416e-04, TJ, TJ1, Result); UCheb(X, 2.499166e-04, TJ, TJ1, Result); UCheb(X, 1.194332e-04, TJ, TJ1, Result); UCheb(X, 7.369096e-05, TJ, TJ1, Result); UCheb(X, 1.968590e-04, TJ, TJ1, Result); UCheb(X, 2.630532e-04, TJ, TJ1, Result); UCheb(X, 5.061000e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 12) *************************************************************************) function UTblN11N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.495790e+00, TJ, TJ1, Result); UCheb(X, -4.832622e+00, TJ, TJ1, Result); UCheb(X, -1.165420e+00, TJ, TJ1, Result); UCheb(X, -1.987306e-01, TJ, TJ1, Result); UCheb(X, -5.265621e-02, TJ, TJ1, Result); UCheb(X, -1.723537e-02, TJ, TJ1, Result); UCheb(X, -5.347406e-03, TJ, TJ1, Result); UCheb(X, -1.353464e-03, TJ, TJ1, Result); UCheb(X, 6.613369e-05, TJ, TJ1, Result); UCheb(X, 5.102522e-04, TJ, TJ1, Result); UCheb(X, 5.237709e-04, TJ, TJ1, Result); UCheb(X, 3.665652e-04, TJ, TJ1, Result); UCheb(X, 1.626903e-04, TJ, TJ1, Result); UCheb(X, -1.167518e-05, TJ, TJ1, Result); UCheb(X, -8.564455e-05, TJ, TJ1, Result); UCheb(X, -1.047320e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 13) *************************************************************************) function UTblN11N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.477880e+00, TJ, TJ1, Result); UCheb(X, -4.796242e+00, TJ, TJ1, Result); UCheb(X, -1.138769e+00, TJ, TJ1, Result); UCheb(X, -1.851739e-01, TJ, TJ1, Result); UCheb(X, -4.722104e-02, TJ, TJ1, Result); UCheb(X, -1.548304e-02, TJ, TJ1, Result); UCheb(X, -5.176683e-03, TJ, TJ1, Result); UCheb(X, -1.817895e-03, TJ, TJ1, Result); UCheb(X, -5.842451e-04, TJ, TJ1, Result); UCheb(X, -8.935870e-05, TJ, TJ1, Result); UCheb(X, 8.421777e-05, TJ, TJ1, Result); UCheb(X, 1.238831e-04, TJ, TJ1, Result); UCheb(X, 8.867026e-05, TJ, TJ1, Result); UCheb(X, 1.458255e-05, TJ, TJ1, Result); UCheb(X, -3.306259e-05, TJ, TJ1, Result); UCheb(X, -8.961487e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 14) *************************************************************************) function UTblN11N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.463683e+00, TJ, TJ1, Result); UCheb(X, -4.766969e+00, TJ, TJ1, Result); UCheb(X, -1.117082e+00, TJ, TJ1, Result); UCheb(X, -1.739574e-01, TJ, TJ1, Result); UCheb(X, -4.238865e-02, TJ, TJ1, Result); UCheb(X, -1.350306e-02, TJ, TJ1, Result); UCheb(X, -4.425871e-03, TJ, TJ1, Result); UCheb(X, -1.640172e-03, TJ, TJ1, Result); UCheb(X, -6.660633e-04, TJ, TJ1, Result); UCheb(X, -2.879883e-04, TJ, TJ1, Result); UCheb(X, -1.349658e-04, TJ, TJ1, Result); UCheb(X, -6.271795e-05, TJ, TJ1, Result); UCheb(X, -3.304544e-05, TJ, TJ1, Result); UCheb(X, -3.024201e-05, TJ, TJ1, Result); UCheb(X, -2.816867e-05, TJ, TJ1, Result); UCheb(X, -4.596787e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 15) *************************************************************************) function UTblN11N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.452526e+00, TJ, TJ1, Result); UCheb(X, -4.743570e+00, TJ, TJ1, Result); UCheb(X, -1.099705e+00, TJ, TJ1, Result); UCheb(X, -1.650612e-01, TJ, TJ1, Result); UCheb(X, -3.858285e-02, TJ, TJ1, Result); UCheb(X, -1.187036e-02, TJ, TJ1, Result); UCheb(X, -3.689241e-03, TJ, TJ1, Result); UCheb(X, -1.294360e-03, TJ, TJ1, Result); UCheb(X, -5.072623e-04, TJ, TJ1, Result); UCheb(X, -2.278008e-04, TJ, TJ1, Result); UCheb(X, -1.322382e-04, TJ, TJ1, Result); UCheb(X, -9.131558e-05, TJ, TJ1, Result); UCheb(X, -7.305669e-05, TJ, TJ1, Result); UCheb(X, -6.825627e-05, TJ, TJ1, Result); UCheb(X, -5.332689e-05, TJ, TJ1, Result); UCheb(X, -6.120973e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 30) *************************************************************************) function UTblN11N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.402621e+00, TJ, TJ1, Result); UCheb(X, -4.627440e+00, TJ, TJ1, Result); UCheb(X, -1.011333e+00, TJ, TJ1, Result); UCheb(X, -1.224126e-01, TJ, TJ1, Result); UCheb(X, -2.232856e-02, TJ, TJ1, Result); UCheb(X, -5.859347e-03, TJ, TJ1, Result); UCheb(X, -1.377381e-03, TJ, TJ1, Result); UCheb(X, -3.756709e-04, TJ, TJ1, Result); UCheb(X, -1.033230e-04, TJ, TJ1, Result); UCheb(X, -2.875472e-05, TJ, TJ1, Result); UCheb(X, -8.608399e-06, TJ, TJ1, Result); UCheb(X, -3.102943e-06, TJ, TJ1, Result); UCheb(X, -1.740693e-06, TJ, TJ1, Result); UCheb(X, -1.343139e-06, TJ, TJ1, Result); UCheb(X, -9.196878e-07, TJ, TJ1, Result); UCheb(X, -6.658062e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 11, 100) *************************************************************************) function UTblN11N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.398795e+00, TJ, TJ1, Result); UCheb(X, -4.596486e+00, TJ, TJ1, Result); UCheb(X, -9.814761e-01, TJ, TJ1, Result); UCheb(X, -1.085187e-01, TJ, TJ1, Result); UCheb(X, -1.766529e-02, TJ, TJ1, Result); UCheb(X, -4.379425e-03, TJ, TJ1, Result); UCheb(X, -8.986351e-04, TJ, TJ1, Result); UCheb(X, -2.214705e-04, TJ, TJ1, Result); UCheb(X, -5.360075e-05, TJ, TJ1, Result); UCheb(X, -1.260869e-05, TJ, TJ1, Result); UCheb(X, -3.033307e-06, TJ, TJ1, Result); UCheb(X, -7.727087e-07, TJ, TJ1, Result); UCheb(X, -3.393883e-07, TJ, TJ1, Result); UCheb(X, -2.242989e-07, TJ, TJ1, Result); UCheb(X, -1.111928e-07, TJ, TJ1, Result); UCheb(X, 3.898823e-09, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 12, 12) *************************************************************************) function UTblN12N12(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.472616e+00, TJ, TJ1, Result); UCheb(X, -4.786627e+00, TJ, TJ1, Result); UCheb(X, -1.132099e+00, TJ, TJ1, Result); UCheb(X, -1.817523e-01, TJ, TJ1, Result); UCheb(X, -4.570179e-02, TJ, TJ1, Result); UCheb(X, -1.479511e-02, TJ, TJ1, Result); UCheb(X, -4.799492e-03, TJ, TJ1, Result); UCheb(X, -1.565350e-03, TJ, TJ1, Result); UCheb(X, -3.530139e-04, TJ, TJ1, Result); UCheb(X, 1.380132e-04, TJ, TJ1, Result); UCheb(X, 3.242761e-04, TJ, TJ1, Result); UCheb(X, 3.576269e-04, TJ, TJ1, Result); UCheb(X, 3.018771e-04, TJ, TJ1, Result); UCheb(X, 1.933911e-04, TJ, TJ1, Result); UCheb(X, 9.002799e-05, TJ, TJ1, Result); UCheb(X, -2.022048e-06, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 12, 13) *************************************************************************) function UTblN12N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.454800e+00, TJ, TJ1, Result); UCheb(X, -4.750794e+00, TJ, TJ1, Result); UCheb(X, -1.105988e+00, TJ, TJ1, Result); UCheb(X, -1.684754e-01, TJ, TJ1, Result); UCheb(X, -4.011826e-02, TJ, TJ1, Result); UCheb(X, -1.262579e-02, TJ, TJ1, Result); UCheb(X, -4.044492e-03, TJ, TJ1, Result); UCheb(X, -1.478741e-03, TJ, TJ1, Result); UCheb(X, -5.322165e-04, TJ, TJ1, Result); UCheb(X, -1.621104e-04, TJ, TJ1, Result); UCheb(X, 4.068753e-05, TJ, TJ1, Result); UCheb(X, 1.468396e-04, TJ, TJ1, Result); UCheb(X, 2.056235e-04, TJ, TJ1, Result); UCheb(X, 2.327375e-04, TJ, TJ1, Result); UCheb(X, 1.914877e-04, TJ, TJ1, Result); UCheb(X, 1.784191e-04, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 12, 14) *************************************************************************) function UTblN12N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.440910e+00, TJ, TJ1, Result); UCheb(X, -4.722404e+00, TJ, TJ1, Result); UCheb(X, -1.085254e+00, TJ, TJ1, Result); UCheb(X, -1.579439e-01, TJ, TJ1, Result); UCheb(X, -3.563738e-02, TJ, TJ1, Result); UCheb(X, -1.066730e-02, TJ, TJ1, Result); UCheb(X, -3.129346e-03, TJ, TJ1, Result); UCheb(X, -1.014531e-03, TJ, TJ1, Result); UCheb(X, -3.129679e-04, TJ, TJ1, Result); UCheb(X, -8.000909e-05, TJ, TJ1, Result); UCheb(X, 1.996174e-05, TJ, TJ1, Result); UCheb(X, 6.377924e-05, TJ, TJ1, Result); UCheb(X, 8.936304e-05, TJ, TJ1, Result); UCheb(X, 1.051098e-04, TJ, TJ1, Result); UCheb(X, 9.025820e-05, TJ, TJ1, Result); UCheb(X, 8.730585e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 12, 15) *************************************************************************) function UTblN12N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.430123e+00, TJ, TJ1, Result); UCheb(X, -4.700008e+00, TJ, TJ1, Result); UCheb(X, -1.068971e+00, TJ, TJ1, Result); UCheb(X, -1.499725e-01, TJ, TJ1, Result); UCheb(X, -3.250897e-02, TJ, TJ1, Result); UCheb(X, -9.473145e-03, TJ, TJ1, Result); UCheb(X, -2.680008e-03, TJ, TJ1, Result); UCheb(X, -8.483350e-04, TJ, TJ1, Result); UCheb(X, -2.766992e-04, TJ, TJ1, Result); UCheb(X, -9.891081e-05, TJ, TJ1, Result); UCheb(X, -4.015140e-05, TJ, TJ1, Result); UCheb(X, -1.977756e-05, TJ, TJ1, Result); UCheb(X, -8.707414e-06, TJ, TJ1, Result); UCheb(X, 1.114786e-06, TJ, TJ1, Result); UCheb(X, 6.238865e-06, TJ, TJ1, Result); UCheb(X, 1.381445e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 12, 30) *************************************************************************) function UTblN12N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.380023e+00, TJ, TJ1, Result); UCheb(X, -4.585782e+00, TJ, TJ1, Result); UCheb(X, -9.838583e-01, TJ, TJ1, Result); UCheb(X, -1.103394e-01, TJ, TJ1, Result); UCheb(X, -1.834015e-02, TJ, TJ1, Result); UCheb(X, -4.635212e-03, TJ, TJ1, Result); UCheb(X, -9.948212e-04, TJ, TJ1, Result); UCheb(X, -2.574169e-04, TJ, TJ1, Result); UCheb(X, -6.747980e-05, TJ, TJ1, Result); UCheb(X, -1.833672e-05, TJ, TJ1, Result); UCheb(X, -5.722433e-06, TJ, TJ1, Result); UCheb(X, -2.181038e-06, TJ, TJ1, Result); UCheb(X, -1.206473e-06, TJ, TJ1, Result); UCheb(X, -9.716003e-07, TJ, TJ1, Result); UCheb(X, -7.476434e-07, TJ, TJ1, Result); UCheb(X, -7.217700e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 12, 100) *************************************************************************) function UTblN12N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.700000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.374567e+00, TJ, TJ1, Result); UCheb(X, -4.553481e+00, TJ, TJ1, Result); UCheb(X, -9.541334e-01, TJ, TJ1, Result); UCheb(X, -9.701907e-02, TJ, TJ1, Result); UCheb(X, -1.414757e-02, TJ, TJ1, Result); UCheb(X, -3.404103e-03, TJ, TJ1, Result); UCheb(X, -6.234388e-04, TJ, TJ1, Result); UCheb(X, -1.453762e-04, TJ, TJ1, Result); UCheb(X, -3.311060e-05, TJ, TJ1, Result); UCheb(X, -7.317501e-06, TJ, TJ1, Result); UCheb(X, -1.713888e-06, TJ, TJ1, Result); UCheb(X, -3.309583e-07, TJ, TJ1, Result); UCheb(X, -4.019804e-08, TJ, TJ1, Result); UCheb(X, 1.224829e-09, TJ, TJ1, Result); UCheb(X, -1.349019e-08, TJ, TJ1, Result); UCheb(X, -1.893302e-08, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 13, 13) *************************************************************************) function UTblN13N13(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.541046e+00, TJ, TJ1, Result); UCheb(X, -4.859047e+00, TJ, TJ1, Result); UCheb(X, -1.130164e+00, TJ, TJ1, Result); UCheb(X, -1.689719e-01, TJ, TJ1, Result); UCheb(X, -3.950693e-02, TJ, TJ1, Result); UCheb(X, -1.231455e-02, TJ, TJ1, Result); UCheb(X, -3.976550e-03, TJ, TJ1, Result); UCheb(X, -1.538455e-03, TJ, TJ1, Result); UCheb(X, -7.245603e-04, TJ, TJ1, Result); UCheb(X, -4.142647e-04, TJ, TJ1, Result); UCheb(X, -2.831434e-04, TJ, TJ1, Result); UCheb(X, -2.032483e-04, TJ, TJ1, Result); UCheb(X, -1.488405e-04, TJ, TJ1, Result); UCheb(X, -1.156927e-04, TJ, TJ1, Result); UCheb(X, -7.949279e-05, TJ, TJ1, Result); UCheb(X, -7.532700e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 13, 14) *************************************************************************) function UTblN13N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.525655e+00, TJ, TJ1, Result); UCheb(X, -4.828341e+00, TJ, TJ1, Result); UCheb(X, -1.108110e+00, TJ, TJ1, Result); UCheb(X, -1.579552e-01, TJ, TJ1, Result); UCheb(X, -3.488307e-02, TJ, TJ1, Result); UCheb(X, -1.032328e-02, TJ, TJ1, Result); UCheb(X, -2.988741e-03, TJ, TJ1, Result); UCheb(X, -9.766394e-04, TJ, TJ1, Result); UCheb(X, -3.388950e-04, TJ, TJ1, Result); UCheb(X, -1.338179e-04, TJ, TJ1, Result); UCheb(X, -6.133440e-05, TJ, TJ1, Result); UCheb(X, -3.023518e-05, TJ, TJ1, Result); UCheb(X, -1.110570e-05, TJ, TJ1, Result); UCheb(X, 4.202332e-06, TJ, TJ1, Result); UCheb(X, 1.056132e-05, TJ, TJ1, Result); UCheb(X, 1.536323e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 13, 15) *************************************************************************) function UTblN13N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.513585e+00, TJ, TJ1, Result); UCheb(X, -4.803952e+00, TJ, TJ1, Result); UCheb(X, -1.090686e+00, TJ, TJ1, Result); UCheb(X, -1.495310e-01, TJ, TJ1, Result); UCheb(X, -3.160314e-02, TJ, TJ1, Result); UCheb(X, -9.073124e-03, TJ, TJ1, Result); UCheb(X, -2.480313e-03, TJ, TJ1, Result); UCheb(X, -7.478239e-04, TJ, TJ1, Result); UCheb(X, -2.140914e-04, TJ, TJ1, Result); UCheb(X, -5.311541e-05, TJ, TJ1, Result); UCheb(X, -2.677105e-06, TJ, TJ1, Result); UCheb(X, 1.115464e-05, TJ, TJ1, Result); UCheb(X, 1.578563e-05, TJ, TJ1, Result); UCheb(X, 2.044604e-05, TJ, TJ1, Result); UCheb(X, 1.888939e-05, TJ, TJ1, Result); UCheb(X, 2.395644e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 13, 30) *************************************************************************) function UTblN13N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.455999e+00, TJ, TJ1, Result); UCheb(X, -4.678434e+00, TJ, TJ1, Result); UCheb(X, -9.995491e-01, TJ, TJ1, Result); UCheb(X, -1.078100e-01, TJ, TJ1, Result); UCheb(X, -1.705220e-02, TJ, TJ1, Result); UCheb(X, -4.258739e-03, TJ, TJ1, Result); UCheb(X, -8.671526e-04, TJ, TJ1, Result); UCheb(X, -2.185458e-04, TJ, TJ1, Result); UCheb(X, -5.507764e-05, TJ, TJ1, Result); UCheb(X, -1.411446e-05, TJ, TJ1, Result); UCheb(X, -4.044355e-06, TJ, TJ1, Result); UCheb(X, -1.285765e-06, TJ, TJ1, Result); UCheb(X, -5.345282e-07, TJ, TJ1, Result); UCheb(X, -3.066940e-07, TJ, TJ1, Result); UCheb(X, -1.962037e-07, TJ, TJ1, Result); UCheb(X, -1.723644e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 13, 100) *************************************************************************) function UTblN13N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.446787e+00, TJ, TJ1, Result); UCheb(X, -4.640804e+00, TJ, TJ1, Result); UCheb(X, -9.671552e-01, TJ, TJ1, Result); UCheb(X, -9.364990e-02, TJ, TJ1, Result); UCheb(X, -1.274444e-02, TJ, TJ1, Result); UCheb(X, -3.047440e-03, TJ, TJ1, Result); UCheb(X, -5.161439e-04, TJ, TJ1, Result); UCheb(X, -1.171729e-04, TJ, TJ1, Result); UCheb(X, -2.562171e-05, TJ, TJ1, Result); UCheb(X, -5.359762e-06, TJ, TJ1, Result); UCheb(X, -1.275494e-06, TJ, TJ1, Result); UCheb(X, -2.747635e-07, TJ, TJ1, Result); UCheb(X, -5.700292e-08, TJ, TJ1, Result); UCheb(X, -2.565559e-09, TJ, TJ1, Result); UCheb(X, 5.005396e-09, TJ, TJ1, Result); UCheb(X, 3.335794e-09, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 14, 14) *************************************************************************) function UTblN14N14(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.510624e+00, TJ, TJ1, Result); UCheb(X, -4.798584e+00, TJ, TJ1, Result); UCheb(X, -1.087107e+00, TJ, TJ1, Result); UCheb(X, -1.478532e-01, TJ, TJ1, Result); UCheb(X, -3.098050e-02, TJ, TJ1, Result); UCheb(X, -8.855986e-03, TJ, TJ1, Result); UCheb(X, -2.409083e-03, TJ, TJ1, Result); UCheb(X, -7.299536e-04, TJ, TJ1, Result); UCheb(X, -2.176177e-04, TJ, TJ1, Result); UCheb(X, -6.479417e-05, TJ, TJ1, Result); UCheb(X, -1.812761e-05, TJ, TJ1, Result); UCheb(X, -5.225872e-06, TJ, TJ1, Result); UCheb(X, 4.516521e-07, TJ, TJ1, Result); UCheb(X, 6.730551e-06, TJ, TJ1, Result); UCheb(X, 9.237563e-06, TJ, TJ1, Result); UCheb(X, 1.611820e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 14, 15) *************************************************************************) function UTblN14N15(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.498681e+00, TJ, TJ1, Result); UCheb(X, -4.774668e+00, TJ, TJ1, Result); UCheb(X, -1.070267e+00, TJ, TJ1, Result); UCheb(X, -1.399348e-01, TJ, TJ1, Result); UCheb(X, -2.807239e-02, TJ, TJ1, Result); UCheb(X, -7.845763e-03, TJ, TJ1, Result); UCheb(X, -2.071773e-03, TJ, TJ1, Result); UCheb(X, -6.261698e-04, TJ, TJ1, Result); UCheb(X, -2.011695e-04, TJ, TJ1, Result); UCheb(X, -7.305946e-05, TJ, TJ1, Result); UCheb(X, -3.879295e-05, TJ, TJ1, Result); UCheb(X, -2.999439e-05, TJ, TJ1, Result); UCheb(X, -2.904438e-05, TJ, TJ1, Result); UCheb(X, -2.944986e-05, TJ, TJ1, Result); UCheb(X, -2.373908e-05, TJ, TJ1, Result); UCheb(X, -2.140794e-05, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 14, 30) *************************************************************************) function UTblN14N30(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.440378e+00, TJ, TJ1, Result); UCheb(X, -4.649587e+00, TJ, TJ1, Result); UCheb(X, -9.807829e-01, TJ, TJ1, Result); UCheb(X, -9.989753e-02, TJ, TJ1, Result); UCheb(X, -1.463646e-02, TJ, TJ1, Result); UCheb(X, -3.586580e-03, TJ, TJ1, Result); UCheb(X, -6.745917e-04, TJ, TJ1, Result); UCheb(X, -1.635398e-04, TJ, TJ1, Result); UCheb(X, -3.923172e-05, TJ, TJ1, Result); UCheb(X, -9.446699e-06, TJ, TJ1, Result); UCheb(X, -2.613892e-06, TJ, TJ1, Result); UCheb(X, -8.214073e-07, TJ, TJ1, Result); UCheb(X, -3.651683e-07, TJ, TJ1, Result); UCheb(X, -2.272777e-07, TJ, TJ1, Result); UCheb(X, -1.464988e-07, TJ, TJ1, Result); UCheb(X, -1.109803e-07, TJ, TJ1, Result); end; (************************************************************************* Tail(S, 14, 100) *************************************************************************) function UTblN14N100(S : AlglibFloat):AlglibFloat; var X : AlglibFloat; TJ : AlglibFloat; TJ1 : AlglibFloat; begin Result := 0; X := Min(2*(S-0.000000e+00)/3.750000e+00-1, 1.0); TJ := 1; TJ1 := X; UCheb(X, -4.429701e+00, TJ, TJ1, Result); UCheb(X, -4.610577e+00, TJ, TJ1, Result); UCheb(X, -9.482675e-01, TJ, TJ1, Result); UCheb(X, -8.605550e-02, TJ, TJ1, Result); UCheb(X, -1.062151e-02, TJ, TJ1, Result); UCheb(X, -2.525154e-03, TJ, TJ1, Result); UCheb(X, -3.835983e-04, TJ, TJ1, Result); UCheb(X, -8.411440e-05, TJ, TJ1, Result); UCheb(X, -1.744901e-05, TJ, TJ1, Result); UCheb(X, -3.318850e-06, TJ, TJ1, Result); UCheb(X, -7.692100e-07, TJ, TJ1, Result); UCheb(X, -1.536270e-07, TJ, TJ1, Result); UCheb(X, -3.705888e-08, TJ, TJ1, Result); UCheb(X, -7.999599e-09, TJ, TJ1, Result); UCheb(X, -2.908395e-09, TJ, TJ1, Result); UCheb(X, 1.546923e-09, TJ, TJ1, Result); end; (************************************************************************* Tail(S, N1, N2) *************************************************************************) function USigma(S : AlglibFloat; N1 : AlglibInteger; N2 : AlglibInteger):AlglibFloat; var F0 : AlglibFloat; F1 : AlglibFloat; F2 : AlglibFloat; F3 : AlglibFloat; F4 : AlglibFloat; S0 : AlglibFloat; S1 : AlglibFloat; S2 : AlglibFloat; S3 : AlglibFloat; S4 : AlglibFloat; begin // // N1=5, N2 = 5, 6, 7, ... // if Min(N1, N2)=5 then begin if Max(N1, N2)=5 then begin Result := UTblN5N5(S); end; if Max(N1, N2)=6 then begin Result := UTblN5N6(S); end; if Max(N1, N2)=7 then begin Result := UTblN5N7(S); end; if Max(N1, N2)=8 then begin Result := UTblN5N8(S); end; if Max(N1, N2)=9 then begin Result := UTblN5N9(S); end; if Max(N1, N2)=10 then begin Result := UTblN5N10(S); end; if Max(N1, N2)=11 then begin Result := UTblN5N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN5N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN5N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN5N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN5N15(S); end; if Max(N1, N2)=16 then begin Result := UTblN5N16(S); end; if Max(N1, N2)=17 then begin Result := UTblN5N17(S); end; if Max(N1, N2)=18 then begin Result := UTblN5N18(S); end; if Max(N1, N2)=19 then begin Result := UTblN5N19(S); end; if Max(N1, N2)=20 then begin Result := UTblN5N20(S); end; if Max(N1, N2)=21 then begin Result := UTblN5N21(S); end; if Max(N1, N2)=22 then begin Result := UTblN5N22(S); end; if Max(N1, N2)=23 then begin Result := UTblN5N23(S); end; if Max(N1, N2)=24 then begin Result := UTblN5N24(S); end; if Max(N1, N2)=25 then begin Result := UTblN5N25(S); end; if Max(N1, N2)=26 then begin Result := UTblN5N26(S); end; if Max(N1, N2)=27 then begin Result := UTblN5N27(S); end; if Max(N1, N2)=28 then begin Result := UTblN5N28(S); end; if Max(N1, N2)=29 then begin Result := UTblN5N29(S); end; if Max(N1, N2)>29 then begin F0 := UTblN5N15(S); F1 := UTblN5N30(S); F2 := UTblN5N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=6, N2 = 6, 7, 8, ... // if Min(N1, N2)=6 then begin if Max(N1, N2)=6 then begin Result := UTblN6N6(S); end; if Max(N1, N2)=7 then begin Result := UTblN6N7(S); end; if Max(N1, N2)=8 then begin Result := UTblN6N8(S); end; if Max(N1, N2)=9 then begin Result := UTblN6N9(S); end; if Max(N1, N2)=10 then begin Result := UTblN6N10(S); end; if Max(N1, N2)=11 then begin Result := UTblN6N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN6N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN6N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN6N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN6N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN6N15(S); F1 := UTblN6N30(S); F2 := UTblN6N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=7, N2 = 7, 8, ... // if Min(N1, N2)=7 then begin if Max(N1, N2)=7 then begin Result := UTblN7N7(S); end; if Max(N1, N2)=8 then begin Result := UTblN7N8(S); end; if Max(N1, N2)=9 then begin Result := UTblN7N9(S); end; if Max(N1, N2)=10 then begin Result := UTblN7N10(S); end; if Max(N1, N2)=11 then begin Result := UTblN7N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN7N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN7N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN7N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN7N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN7N15(S); F1 := UTblN7N30(S); F2 := UTblN7N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=8, N2 = 8, 9, 10, ... // if Min(N1, N2)=8 then begin if Max(N1, N2)=8 then begin Result := UTblN8N8(S); end; if Max(N1, N2)=9 then begin Result := UTblN8N9(S); end; if Max(N1, N2)=10 then begin Result := UTblN8N10(S); end; if Max(N1, N2)=11 then begin Result := UTblN8N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN8N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN8N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN8N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN8N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN8N15(S); F1 := UTblN8N30(S); F2 := UTblN8N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=9, N2 = 9, 10, ... // if Min(N1, N2)=9 then begin if Max(N1, N2)=9 then begin Result := UTblN9N9(S); end; if Max(N1, N2)=10 then begin Result := UTblN9N10(S); end; if Max(N1, N2)=11 then begin Result := UTblN9N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN9N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN9N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN9N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN9N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN9N15(S); F1 := UTblN9N30(S); F2 := UTblN9N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=10, N2 = 10, 11, ... // if Min(N1, N2)=10 then begin if Max(N1, N2)=10 then begin Result := UTblN10N10(S); end; if Max(N1, N2)=11 then begin Result := UTblN10N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN10N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN10N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN10N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN10N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN10N15(S); F1 := UTblN10N30(S); F2 := UTblN10N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=11, N2 = 11, 12, ... // if Min(N1, N2)=11 then begin if Max(N1, N2)=11 then begin Result := UTblN11N11(S); end; if Max(N1, N2)=12 then begin Result := UTblN11N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN11N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN11N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN11N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN11N15(S); F1 := UTblN11N30(S); F2 := UTblN11N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=12, N2 = 12, 13, ... // if Min(N1, N2)=12 then begin if Max(N1, N2)=12 then begin Result := UTblN12N12(S); end; if Max(N1, N2)=13 then begin Result := UTblN12N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN12N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN12N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN12N15(S); F1 := UTblN12N30(S); F2 := UTblN12N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=13, N2 = 13, 14, ... // if Min(N1, N2)=13 then begin if Max(N1, N2)=13 then begin Result := UTblN13N13(S); end; if Max(N1, N2)=14 then begin Result := UTblN13N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN13N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN13N15(S); F1 := UTblN13N30(S); F2 := UTblN13N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1=14, N2 = 14, 15, ... // if Min(N1, N2)=14 then begin if Max(N1, N2)=14 then begin Result := UTblN14N14(S); end; if Max(N1, N2)=15 then begin Result := UTblN14N15(S); end; if Max(N1, N2)>15 then begin F0 := UTblN14N15(S); F1 := UTblN14N30(S); F2 := UTblN14N100(S); Result := UNInterpolate(F0, F1, F2, Max(N1, N2)); end; Exit; end; // // N1 >= 15, N2 >= 15 // if AP_FP_Greater(S,4) then begin S := 4; end; if AP_FP_Less(S,3) then begin S0 := 0.000000e+00; F0 := USigma000(N1, N2); S1 := 7.500000e-01; F1 := USigma075(N1, N2); S2 := 1.500000e+00; F2 := USigma150(N1, N2); S3 := 2.250000e+00; F3 := USigma225(N1, N2); S4 := 3.000000e+00; F4 := USigma300(N1, N2); F1 := ((S-S0)*F1-(S-S1)*F0)/(S1-S0); F2 := ((S-S0)*F2-(S-S2)*F0)/(S2-S0); F3 := ((S-S0)*F3-(S-S3)*F0)/(S3-S0); F4 := ((S-S0)*F4-(S-S4)*F0)/(S4-S0); F2 := ((S-S1)*F2-(S-S2)*F1)/(S2-S1); F3 := ((S-S1)*F3-(S-S3)*F1)/(S3-S1); F4 := ((S-S1)*F4-(S-S4)*F1)/(S4-S1); F3 := ((S-S2)*F3-(S-S3)*F2)/(S3-S2); F4 := ((S-S2)*F4-(S-S4)*F2)/(S4-S2); F4 := ((S-S3)*F4-(S-S4)*F3)/(S4-S3); Result := F4; end else begin S0 := 3.000000e+00; F0 := USigma300(N1, N2); S1 := 3.333333e+00; F1 := USigma333(N1, N2); S2 := 3.666667e+00; F2 := USigma367(N1, N2); S3 := 4.000000e+00; F3 := USigma400(N1, N2); F1 := ((S-S0)*F1-(S-S1)*F0)/(S1-S0); F2 := ((S-S0)*F2-(S-S2)*F0)/(S2-S0); F3 := ((S-S0)*F3-(S-S3)*F0)/(S3-S0); F2 := ((S-S1)*F2-(S-S2)*F1)/(S2-S1); F3 := ((S-S1)*F3-(S-S3)*F1)/(S3-S1); F3 := ((S-S2)*F3-(S-S3)*F2)/(S3-S2); Result := F3; end; end; end.
unit ThSort; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TThreadSortForm = class(TForm) StartBtn: TButton; BubbleSortBox: TPaintBox; SelectionSortBox: TPaintBox; QuickSortBox: TPaintBox; Label1: TLabel; Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; Label2: TLabel; Label3: TLabel; procedure BubbleSortBoxPaint(Sender: TObject); procedure SelectionSortBoxPaint(Sender: TObject); procedure QuickSortBoxPaint(Sender: TObject); procedure FormCreate(Sender: TObject); procedure StartBtnClick(Sender: TObject); private ThreadsRunning: Integer; procedure RandomizeArrays; procedure ThreadDone(Sender: TObject); public procedure PaintArray(Box: TPaintBox; const A: array of Integer); end; var ThreadSortForm: TThreadSortForm; implementation uses SortThds; {$R *.dfm} type PSortArray = ^TSortArray; TSortArray = array[0..114] of Integer; var ArraysRandom: Boolean; BubbleSortArray, SelectionSortArray, QuickSortArray: TSortArray; { TThreadSortForm } procedure TThreadSortForm.PaintArray(Box: TPaintBox; const A: array of Integer); var I: Integer; begin with Box do begin Canvas.Pen.Color := clRed; for I := Low(A) to High(A) do PaintLine(Canvas, I, A[I]); end; end; procedure TThreadSortForm.BubbleSortBoxPaint(Sender: TObject); begin PaintArray(BubbleSortBox, BubbleSortArray); end; procedure TThreadSortForm.SelectionSortBoxPaint(Sender: TObject); begin PaintArray(SelectionSortBox, SelectionSortArray); end; procedure TThreadSortForm.QuickSortBoxPaint(Sender: TObject); begin PaintArray(QuickSortBox, QuickSortArray); end; procedure TThreadSortForm.FormCreate(Sender: TObject); begin RandomizeArrays; end; procedure TThreadSortForm.StartBtnClick(Sender: TObject); begin RandomizeArrays; ThreadsRunning := 3; with TBubbleSort.Create(BubbleSortBox, BubbleSortArray) do OnTerminate := ThreadDone; with TSelectionSort.Create(SelectionSortBox, SelectionSortArray) do OnTerminate := ThreadDone; with TQuickSort.Create(QuickSortBox, QuickSortArray) do OnTerminate := ThreadDone; StartBtn.Enabled := False; end; procedure TThreadSortForm.RandomizeArrays; var I: Integer; begin if not ArraysRandom then begin Randomize; for I := Low(BubbleSortArray) to High(BubbleSortArray) do BubbleSortArray[I] := Random(170); SelectionSortArray := BubbleSortArray; QuickSortArray := BubbleSortArray; ArraysRandom := True; Repaint; end; end; procedure TThreadSortForm.ThreadDone(Sender: TObject); begin Dec(ThreadsRunning); if ThreadsRunning = 0 then begin StartBtn.Enabled := True; ArraysRandom := False; end; end; end.
unit uImportacaoDogus; interface uses uImportacao, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, JvExStdCtrls, JvGroupBox, ExtCtrls, IOUtils, FMTBcd, DB, SqlExpr, DateUtils, xmldom, XMLIntf, msxmldom, XMLDoc, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, jpeg, StrUtils, PngImage, ActiveX, DBXCommon, SyncObjs, DBClient, Provider; type TImportacaoDogus = class(TImportacao) public procedure ContaImoveisFotos(pathXML: string); override; procedure InseriTempXML(pathXML: string); override; function ValidaTagsXML(node: IXMLNode): Boolean; override; end; implementation uses uThreadImportacao, uPrincipal; const TAGS : array[1..23] of string = ('title','guid','cidade','categoria','tipo','endereco','cond_pag', 'descricao', 'area', 'area_c', 'quartos', 'suites', 'salas', 'ambientes', 'cozinhas', 'wc', 'lavabo', 'piscina', 'garagem', 'telefone', 'valor', 'bairro', 'fotos'); { TImportacaoDogus } procedure TImportacaoDogus.ContaImoveisFotos(pathXML: string); var oNodePai, oNodeItem, oNodeFotos, oNodeFoto: IXMLNode; oXMLDoc: TXMLDocument; begin // Inseri os dados para atualização da tarefa self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Contando imóveis e fotos do arquivo XML', ''); try try // Instância o objeto XMLDocument e carrega o arquivo XML oXMLDoc := TXMLDocument.Create(Application); oXMLDoc.FileName := pathXML; oXMLDoc.Active := True; // Identifica o Node principal do XML oNodePai := oXMLDoc.DocumentElement.ChildNodes.FindNode('channel'); repeat oNodeItem := oNodePai.ChildNodes.FindNode('item'); oNodeItem.ChildNodes.First; repeat // Valida se todas as TAGs estão presentes no Node['item'] atual if(Self.ValidaTagsXML(oNodeItem)) then begin // Contador para gravar a quantidade de registros lidos e gravados no banco de dados Inc(iContTotalItem); oNodeFotos := oNodeitem.ChildNodes.FindNode('fotos'); if oNodeFotos <> nil then begin oNodeFotos.ChildNodes.First; repeat oNodeFoto := oNodeFotos.ChildNodes.FindNode('foto'); if oNodeFoto <> nil then begin oNodeFoto.ChildNodes.First; repeat // Processa as imagens do XML Inc(iContTotalFoto); oNodeFoto := oNodeFoto.NextSibling; until (oNodeFoto = nil) or (ThreadImportacao.CheckTerminated); end; oNodeFotos := oNodeFotos.NextSibling; until (oNodeFotos = nil) ; end; end; oNodeItem := oNodeItem.NextSibling; until (oNodeItem = nil) or (ThreadImportacao.CheckTerminated) ; oNodePai := oNodePai.NextSibling; until (oNodePai = nil) ; except end; finally FreeAndNil(oXMLDoc); end; end; procedure TImportacaoDogus.InseriTempXML(pathXML: string); var oNodePai, oNodeItem, oNodeFotos, oNodeFoto : IXMLNode; oXMLDoc: TXMLDocument; oQry, oQryImg: TSQLQuery; sNameImagem, sValor: string; iIdExterno, iContTemp, iContTempImovel: Integer; begin try try iContTemp := 0; // Instância o objeto XMLDocument e carrega o arquivo XML oXMLDoc := TXMLDocument.Create(Application); oXMLDoc.FileName := pathXML; oXMLDoc.Active := True; // Chama a função para executar a conexão com o respectivo portal onde serão gravados os dados Self.ConectarPortal; oQry := TSQLQuery.Create(nil); oQry.SQLConnection := Self.FConexaoPortal; // Limpa a tabela imoveis_xml oQry.Close; oQry.SQL.Clear; oQry.SQL.Add('DELETE FROM imoveis_xml'); oQry.ExecSQL(); // Limpa a tabela imoveis_fotos_xml oQry.Close; oQry.SQL.Clear; oQry.SQL.Add('DELETE FROM imoveis_fotos_xml'); oQry.ExecSQL(); oQryImg := TSQLQuery.Create(nil); oQryImg.SQLConnection := Self.FConexaoPortal; // Identifica o Node principal do XML oNodePai := oXMLDoc.DocumentElement.ChildNodes.FindNode('channel'); repeat oNodeItem := oNodePai.ChildNodes.FindNode('item'); oNodeItem.ChildNodes.First; // Inseri os dados para atualização da tarefa self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando inclusões temporárias de imóveis', ''); repeat // Valida se todas as TAGs estão presentes no Node['item'] atual e se existem fotos para esse Node['item'] if(Self.ValidaTagsXML(oNodeItem)) then begin iIdExterno := StrToInt(oNodeItem.ChildNodes['guid'].Text); if frmMonitoramento.FALG_SEPARADOR = 'BRA' then begin sValor := StringReplace(oNodeItem.ChildNodes['valor'].Text, '.', '', [rfReplaceAll]); end else begin sValor := StringReplace(oNodeItem.ChildNodes['valor'].Text, '.', '', [rfReplaceAll]); sValor := StringReplace(sValor, ',', '.', [rfReplaceAll]); end; // Grava os imóveis no banco de dados oQry.Close; oQry.SQL.Clear; oQry.SQL.Add('INSERT INTO imoveis_xml (id_externo, categoria, tipo, cidade, endereco, titulo, descricao, cond_pag, area, area_c, quartos, suites, tipo_construcao, salas, ambientes, cozinhas, '); oQry.SQL.Add('wc, lavabo, piscina, garagem, telefone, data, cod_usuario, views, status, aprovado, valor, bairro)VALUES'); oQry.SQL.Add('(:id_externo, :categoria, :tipo, :cidade, :endereco, :titulo, :descricao, :cond_pag, :area, :area_c, :quartos, :suites, :tipo_construcao, :salas, :ambientes, :cozinhas, '); oQry.SQL.Add(':wc, :lavabo, :piscina, :garagem, :telefone, :data, :cod_usuario, :views, :status, :aprovado, :valor, :bairro)'); oQry.ParamByName('id_externo').AsInteger := StrToInt(oNodeItem.ChildNodes['guid'].Text); oQry.ParamByName('categoria').AsString := Self.Ternario(' ', AcertoAcento(oNodeItem.ChildNodes['categoria'].Text), ' '); oQry.ParamByName('tipo').AsString := Self.Ternario(' ', AcertoAcento(oNodeItem.ChildNodes['tipo'].Text), ' '); oQry.ParamByName('cidade').AsString := Self.Ternario(' ', AcertoAcento(oNodeItem.ChildNodes['cidade'].Text), ' '); oQry.ParamByName('endereco').AsString := Self.Ternario(' ', AcertoAcento(oNodeItem.ChildNodes['endereco'].Text), ' '); oQry.ParamByName('titulo').AsString := Self.Ternario(' ', AcertoAcento(oNodeItem.ChildNodes['title'].Text), ' '); oQry.ParamByName('descricao').AsString := Self.Ternario(' ', AcertoAcento(oNodeItem.ChildNodes['descricao'].Text), ' '); oQry.ParamByName('cond_pag').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['cond_pag'].Text, ' '); oQry.ParamByName('area').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['area'].Text, ' '); oQry.ParamByName('area_c').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['area_c'].Text, ' '); oQry.ParamByName('quartos').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['quartos'].Text, ' '); oQry.ParamByName('suites').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['suites'].Text, ' '); oQry.ParamByName('tipo_construcao').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['tipo_construcao'].Text, ' '); oQry.ParamByName('salas').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['salas'].Text, ' '); oQry.ParamByName('ambientes').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['ambientes'].Text, ' '); oQry.ParamByName('cozinhas').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['cozinhas'].Text, ' '); oQry.ParamByName('wc').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['wc'].Text, ' '); oQry.ParamByName('lavabo').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['lavabo'].Text, ' '); oQry.ParamByName('piscina').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['piscina'].Text, ' '); oQry.ParamByName('garagem').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['garagem'].Text, ' '); oQry.ParamByName('telefone').AsString := Self.Ternario(' ', oNodeItem.ChildNodes['telefone'].Text, ' '); oQry.ParamByName('data').AsString := FormatDateTime('dd/mm/yyyy', Date); oQry.ParamByName('cod_usuario').AsString := IntToStr(FIdImobiliaria); OQry.ParamByName('views').AsString := '0'; oQry.ParamByName('status').AsString := 'Ativo'; oQry.ParamByName('aprovado').AsString := 'SIM'; oQry.ParamByName('valor').AsFloat := StrToFloat(sValor); oQry.ParamByName('bairro').AsString := oNodeItem.ChildNodes['bairro'].Text; oQry.ExecSQL(); // Inseri os dados para atualização da tarefa self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando inclusões temporárias de imóveis - ' + IntToStr(iContTempImovel) + ' de ' + IntToStr(iContTotalItem) , ''); oNodeFotos := oNodeitem.ChildNodes.FindNode('fotos'); if oNodeFotos <> nil then begin oNodeFotos.ChildNodes.First; repeat oNodeFoto := oNodeFotos.ChildNodes.FindNode('foto'); if oNodeFoto <> nil then begin oNodeFoto.ChildNodes.First; // Inseri os dados para atualização da tarefa self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando inclusões temporárias de imagens - ' + IntToStr(iContTemp) + ' de ' + IntToStr(iContTotalFoto) , ''); repeat if not Self.FConexaoPortal.Connected then Self.ConectarPortal; oQryImg.Close; oQryImg.SQL.Clear; oQryImg.SQL.Add('INSERT INTO imoveis_fotos_xml (id_imovel, destaque, cod_imobiliaria, data, id_externo, url_foto, processada, nova)VALUES'); oQryImg.SQL.Add('(:id_imovel, :destaque, :cod_imobiliaria, :data, :id_externo, :url_foto, :processada, :nova)'); oQryImg.ParamByName('id_imovel').AsInteger := 0; ///// oQryImg.ParamByName('destaque').AsString := 'NAO'; ////// oQryImg.ParamByName('cod_imobiliaria').AsInteger := Self.FIdImobiliaria; oQryImg.ParamByName('data').AsString := FormatDateTime('dd/mm/yyyy', Date); oQryImg.ParamByName('id_externo').AsInteger := iIdExterno; oQryImg.ParamByName('url_foto').AsString := Trim(oNodeFoto.ChildNodes['url_foto'].Text); oQryImg.ParamByName('processada').AsString := 'NAO'; ////// oQryImg.ParamByName('nova').AsString := 'NAO'; ////// oQryImg.ExecSQL(); Inc(iContTemp); oNodeFoto := oNodeFoto.NextSibling; until (oNodeFoto = nil) or (ThreadImportacao.CheckTerminated); end; oNodeFotos := oNodeFotos.NextSibling; until (oNodeFotos = nil) ; end; Inc(iContTempImovel); end; oNodeItem := oNodeItem.NextSibling; until (oNodeItem = nil) or (ThreadImportacao.CheckTerminated) ; oNodePai := oNodePai.NextSibling; until (oNodePai = nil) ; // Fecha Conexão com banco de dados do portal Self.FConexaoPortal.Close; except on E:Exception do begin MessageDlg('Erro ao inserir dados na tabela temporária: '#13 + E.Message, mtError, [mbOK], 0); Self.FConexaoPortal.Close; end; end; finally FreeAndNil(oXMLDoc); FreeAndNil(oQry); FreeAndNil(oQryImg); end; end; function TImportacaoDogus.ValidaTagsXML(node: IXMLNode): Boolean; var i : Integer; nodeTemp1, nodeTemp2 : IXMLNode; t: string; begin // Verifica se existe valor para o parâmetro if Assigned(node) then begin // Loop para percorrer todas as TAGs dentro do Node['item'] verificando a ausência de TAGs for i := 1 to 23 do begin nodeTemp1 := node.ChildNodes.FindNode(TAGS[i]); if nodeTemp1 = nil then begin Result := False; Exit(); end; end; // Verificando se existem fotos para o Node['fotos'] nodeTemp1 := node.ChildNodes.FindNode('fotos'); nodeTemp1.ChildNodes.First; nodeTemp2 := nodeTemp1.ChildNodes.FindNode('foto'); if nodeTemp2 = nil then begin Result := False; Exit(); end; Result := True; end else Result := false; end; end.
namespace RemObjects.SDK.CodeGen4; uses RemObjects.Elements.RTL; type RodlServiceEntity = public abstract class (RodlComplexEntity<RodlInterface>) public constructor; begin inherited constructor("Interface"); end; property DefaultInterface: RodlInterface read if Count > 0 then Item[0]; method LoadFromXmlNode(node: XmlElement); override; begin LoadFromXmlNode(node, -> new RodlInterface); end; method LoadFromJsonNode(node: JsonNode); override; begin inherited LoadFromJsonNode(node); var lDefaultInterface := new RodlInterface; lDefaultInterface.LoadFromJsonNode(node); lDefaultInterface.Owner := self; Items.Add(lDefaultInterface); //LoadFromJsonNode(node, -> new RodlInterface); end; end; RodlEventSink = public class(RodlServiceEntity) end; RodlService = public class(RodlServiceEntity) private fRoles := new RodlRoles(); public method LoadFromXmlNode(node: XmlElement); override; begin inherited LoadFromXmlNode(node); fRoles.Clear; fRoles.LoadFromXmlNode(node); &Private := node.Attribute["Private"]:Value = "1"; ImplClass := node.Attribute["ImplClass"]:Value; ImplUnit := node.Attribute["ImplUnit"]:Value; end; method LoadFromJsonNode(node: JsonNode); override; begin inherited LoadFromJsonNode(node); fRoles.Clear; fRoles.LoadFromJsonNode(node); &Private := valueOrDefault(node["Private"]:BooleanValue); ImplClass := node["ImplClass"]:StringValue; ImplUnit := node["ImplUnit"]:StringValue; end; property Roles: RodlRoles read fRoles; property ImplUnit:String; property ImplClass:String; property &Private: Boolean; end; // // // RodlInclude = public class(RodlEntity) private method LoadAttribute(node:XmlElement; aName:String):String; begin exit iif(node.Attribute[aName] ≠ nil, node.Attribute[aName].Value, ""); end; public method LoadFromXmlNode(node: XmlElement); override; begin inherited LoadFromXmlNode(node); DelphiModule := node.Attribute["Delphi"]:Value; NetModule := node.Attribute["DotNet"]:Value; ObjCModule := node.Attribute["ObjC"]:Value; JavaModule := node.Attribute["Java"]:Value; JavaScriptModule := node.Attribute["JavaScript"]:Value; CocoaModule := coalesce(node.Attribute["Cocoa"]:Value, node.Attribute["Nougat"]:Value, node.Attribute["Toffee"]:Value); SwiftModule := node.Attribute["Swift"]:Value; end; method LoadFromJsonNode(node: JsonNode); override; begin inherited LoadFromJsonNode(node); DelphiModule := node["Delphi"]:StringValue; NetModule := coalesce(node[".NET"]:StringValue, node[".Net"]:StringValue, node["DotNet"]:StringValue); ObjCModule := node["ObjC"]:StringValue; JavaModule := node["Java"]:StringValue; JavaScriptModule := node["JavaScript"]:StringValue; CocoaModule := coalesce(node["Cocoa"]:StringValue, node["Nougat"]:StringValue, node["Toffee"]:StringValue); SwiftModule := node["Swift"]:StringValue; end; property DelphiModule: String; property JavaModule: String; property JavaScriptModule: String; property NetModule: String; property CocoaModule: String; property ObjCModule: String; property SwiftModule: String; end; RodlInterface = public class(RodlComplexEntity<RodlOperation>) private public constructor; begin inherited constructor("Operation"); end; method LoadFromXmlNode(node: XmlElement); override; begin LoadFromXmlNode(node, ->new RodlOperation); end; method LoadFromJsonNode(node: JsonNode); override; begin inherited LoadFromJsonNode(node); LoadFromJsonNode(node, -> new RodlOperation); end; end; RodlOperation = public class(RodlComplexEntity<RodlParameter>) private fRoles: RodlRoles := new RodlRoles(); public constructor; begin inherited constructor("Parameter"); end; method LoadFromXmlNode(node: XmlElement); override; begin LoadFromXmlNode(node,->new RodlParameter); fRoles.Clear; fRoles.LoadFromXmlNode(node); if (node.Attribute["ForceAsyncResponse"] ≠ nil) then ForceAsyncResponse := node.Attribute["ForceAsyncResponse"].Value = "1"; for parameter: RodlParameter in Items do if parameter.ParamFlag = ParamFlags.Result then self.Result := parameter; Items.Remove(self.Result); end; method LoadFromJsonNode(node: JsonNode); override; begin LoadFromJsonNode(node,->new RodlParameter); fRoles.Clear; fRoles.LoadFromJsonNode(node); ForceAsyncResponse := valueOrDefault(node["ForceAsyncResponse"]:BooleanValue); for parameter: RodlParameter in Items do if parameter.ParamFlag = ParamFlags.Result then self.Result := parameter; Items.Remove(self.Result); end; property Roles: RodlRoles read fRoles; property &Result: RodlParameter; property ForceAsyncResponse: Boolean := false; end; RodlParameter = public class(RodlTypedEntity) public method LoadFromXmlNode(node: XmlElement); override; begin inherited LoadFromXmlNode(node); case caseInsensitive(node.Attribute["Flag"]:Value) of 'in': ParamFlag:= ParamFlags.In; 'out': ParamFlag:= ParamFlags.Out; 'inout': ParamFlag:= ParamFlags.InOut; 'result': ParamFlag:= ParamFlags.Result; else ParamFlag := ParamFlags.In; end; end; method LoadFromJsonNode(node: JsonNode); override; begin inherited LoadFromJsonNode(node); case caseInsensitive(node["Flag"]:StringValue) of 'in': ParamFlag:= ParamFlags.In; 'out': ParamFlag:= ParamFlags.Out; 'inout': ParamFlag:= ParamFlags.InOut; 'result': ParamFlag:= ParamFlags.Result; else ParamFlag := ParamFlags.In; end; end; property ParamFlag: ParamFlags; end; end.
unit chpcConversas; interface uses SysUtils, Classes, Controls, chBase, chfrConversa, cxPC; type TchpcConversas = class ( TcxPageControl ) private FClasseFrameConversa : TchClasseFrameConversa; FChat : TClienteChat; function GetConversa(Index: Integer): TchFrameConversa; function NovaConversa: TchFrameConversa; function GetActiveNodeID: String; procedure SetActiveNodeID(const Value: String); function GetConversaAtiva: TchFrameConversa; public constructor Create(AOwner: TComponent); override; function CriaConversa(ANodeID: String; AMostrar: Boolean): TchFrameConversa; procedure MostraNodeID(ANodeID: String; ACriar: Boolean); procedure AddMsg(ARecebeu: Boolean; ANodeID: String; AMsg: String; AMostrar: Boolean); procedure AtualizaNodeInfo(ANodeID: String); function ConversaPorNodeID(const ANodeID: String): TchFrameConversa; property Conversas[Index: Integer]: TchFrameConversa read GetConversa; published property ClasseFrameConversa: TchClasseFrameConversa read FClasseFrameConversa write FClasseFrameConversa; property ActiveNodeID: String read GetActiveNodeID write SetActiveNodeID; property ConversaAtiva: TchFrameConversa read GetConversaAtiva; property Chat: TClienteChat read FChat write FChat; end; procedure Register; var ClasseFrameConversaPadrao : TchClasseFrameConversa = nil; implementation { TchpcConversas } procedure TchpcConversas.AddMsg(ARecebeu: Boolean; ANodeID, AMsg: String; AMostrar: Boolean); begin CriaConversa(ANodeID, AMostrar).AddMsg(ARecebeu, Now, AMsg); end; procedure TchpcConversas.AtualizaNodeInfo(ANodeID: String); var C : TchFrameConversa; begin C := ConversaPorNodeID(ANodeID); if C <> nil then C.AtualizaNodeInfo; end; function TchpcConversas.ConversaPorNodeID( const ANodeID: String): TchFrameConversa; var I : Integer; begin for I := 0 to PageCount-1 do if Conversas[I].NodeID = ANodeID then begin Result := Conversas[I]; Exit; end; Result := nil; end; constructor TchpcConversas.Create(AOwner: TComponent); begin inherited; FClasseFrameConversa := ClasseFrameConversaPadrao; FChat := nil; end; function TchpcConversas.CriaConversa(ANodeID: String; AMostrar: Boolean): TchFrameConversa; begin Result := ConversaPorNodeID(ANodeID); if Result=nil then begin Result := NovaConversa; Result.NodeID := ANodeID; if AMostrar then ActivePage := Result.TabSheet; end; end; function TchpcConversas.GetActiveNodeID: String; begin if ActivePage = nil then Result := '' else Result := TchFrameConversa(ActivePage.Tag).NodeID; end; function TchpcConversas.GetConversa(Index: Integer): TchFrameConversa; begin Result := TchFrameConversa(Pages[Index].Tag); end; function TchpcConversas.GetConversaAtiva: TchFrameConversa; begin if (ActivePage<>nil) and (ActivePage.Tag<>0) then Result := TchFrameConversa(ActivePage.Tag) else Result := nil; end; procedure TchpcConversas.MostraNodeID(ANodeID: String; ACriar: Boolean); var C : TchFrameConversa; begin if ACriar then C := CriaConversa(ANodeID, ACriar) else C := ConversaPorNodeID(ANodeID); if C<>nil then ActivePage := C.TabSheet; end; function TchpcConversas.NovaConversa: TchFrameConversa; var T: TcxTabSheet; begin T := TcxTabSheet.Create(Owner); Result := FClasseFrameConversa.Create(T); T.Tag := Integer(Result); T.PageControl := Self; T.Color := $00E1FFFF; Result.TabSheet := T; Result.Parent := T; end; procedure TchpcConversas.SetActiveNodeID(const Value: String); var NI : TchNodeInfo; begin if not Chat.GetNodeInfo(Value, NI) then Raise Exception.Create('NodeID inválido'); Self.MostraNodeID(Value, True); end; procedure Register; begin RegisterComponents('Standard', [TchpcConversas]); end; end.
unit HttpConnection; interface uses Classes; type THttpConnectionType = (hctUnknown, hctIndy, hctWinHttp); IHttpConnection = interface ['{B9611100-5243-4874-A777-D91448517116}'] function SetAcceptTypes(AAcceptTypes: string): IHttpConnection; function SetContentTypes(AContentTypes: string): IHttpConnection; function SetAcceptedLanguages(AAcceptedLanguages: string): IHttpConnection; function SetHeaders(AHeaders: TStrings): IHttpConnection; procedure Get(AUrl: string; AResponse: TStream); procedure Post(AUrl: string; AContent, AResponse: TStream); procedure Put(AUrl: string; AContent, AResponse: TStream); procedure Delete(AUrl: string; AContent: TStream); function GetResponseCode: Integer; function GetEnabledCompression: Boolean; procedure SetEnabledCompression(const Value: Boolean); property ResponseCode: Integer read GetResponseCode; property EnabledCompression: Boolean read GetEnabledCompression write SetEnabledCompression; end; implementation end.
{******************************************************************************* Title: T2Ti ERP Description: Classe de controle dos totais de tipos de pagamento. The MIT License Copyright: Copyright (C) 2010 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) @version 1.0 *******************************************************************************} unit TotalTipoPagamentoController; interface uses Classes, SQLExpr, SysUtils, TipoPagamentoVO, Generics.Collections, TotalTipoPagamentoVO, DB, MeiosPagamentoVO; type TTotalTipoPagamentoController = class protected public function MeiosPagamento(DataInicio:String;DataFim:String;IdImpressora:Integer): TObjectList<TMeiosPagamentoVO>; end; implementation uses UDataModule, R07VO, RegistroRController; var Query: TSQLQuery; ConsultaSQL: String; function TTotalTipoPagamentoController.MeiosPagamento(DataInicio:String;DataFim:String;IdImpressora:Integer): TObjectList<TMeiosPagamentoVO>; var ListaMeiosPagamento: TObjectList<TMeiosPagamentoVO>; MeiosPagamento: TMeiosPagamentoVO; begin DataInicio := FormatDateTime('yyyy-mm-dd', StrToDate(DataInicio)); DataFim := FormatDateTime('yyyy-mm-dd', StrToDate(DataFim)); ConsultaSQL := 'SELECT V.DATA_HORA_VENDA, M.ID_ECF_IMPRESSORA, P.DESCRICAO, SUM(TP.VALOR) AS TOTAL '+ 'FROM '+ 'ECF_VENDA_CABECALHO V, ECF_MOVIMENTO M, ECF_TIPO_PAGAMENTO P, ECF_TOTAL_TIPO_PGTO TP '+ 'WHERE '+ 'V.ID_ECF_MOVIMENTO = M.ID AND '+ 'TP.ID_ECF_VENDA_CABECALHO=V.ID AND '+ 'TP.ID_ECF_TIPO_PAGAMENTO = P.ID AND '+ 'M.ID_ECF_IMPRESSORA = '+ IntToStr(idImpressora) + ' AND '+ '(V.DATA_HORA_VENDA BETWEEN ' + QuotedStr(DataInicio) + ' and ' + QuotedStr(DataFim) + ') GROUP BY '+ 'P.DESCRICAO,V.DATA_HORA_VENDA,M.ID_ECF_IMPRESSORA'; try try ListaMeiosPagamento := TObjectList<TMeiosPagamentoVO>.Create; Query := TSQLQuery.Create(nil); Query.SQLConnection := FDataModule.Conexao; Query.sql.Text := ConsultaSQL; Query.Open; Query.First; while not Query.Eof do begin MeiosPagamento := TMeiosPagamentoVO.Create; MeiosPagamento.Descricao := Query.FieldByName('DESCRICAO').AsString; MeiosPagamento.DataHora := Query.FieldByName('DATA_HORA_VENDA').AsString; MeiosPagamento.Total := Query.FieldByName('TOTAL').AsFloat; ListaMeiosPagamento.Add(MeiosPagamento); Query.next; end; result := ListaMeiosPagamento; except result := nil; end; finally Query.Free; end; end; end.
unit FMX.Toast.Windows; interface uses System.SysUtils, System.Classes, System.Types, System.UITypes, FMX.Types, FMX.TextLayout, FMX.Controls, FMX.Graphics, FMX.Ani, FMX.Forms, FMX.Layouts, System.Generics.Collections, DateUtils; type TWindowsToastDuration = (ToastDurationLengthShort, ToastDurationLengthLong); TWindowsToast = class(TControl) private FBackgroundSize: TSize; FFloatAnimationOpacity: TFloatAnimation; FText: string; FFont: TFont; FFillText: TBrush; FFillBackground: TBrush; FOnFinishToast: TNotifyEvent; FIsStarted: Boolean; FDuration: TWindowsToastDuration; FThreadDuration: TThread; procedure SetText(const Value: String); procedure SetFillText(const Value: TBrush); procedure SetFillBackground(const Value: TBrush); procedure SetOnFinishToast(const Value: TNotifyEvent); procedure SetIsStarted(const Value: Boolean); procedure SetDuration(const Value: TWindowsToastDuration); { Private declarations } protected { Protected declarations } procedure DoFinishToast(Sender: TObject); property FillText: TBrush read FFillText write SetFillText; property FillBackground: TBrush read FFillBackground write SetFillBackground; property Duration: TWindowsToastDuration read FDuration write SetDuration; procedure Paint; override; procedure DoTextChanged(Sender: TObject); procedure RecalcToastHeight; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Start; published { Published declarations } property Align; property Anchors; property Width; property Height; property Size; property Enabled; property Padding; property Margins; property Opacity; property ClipChildren; property ClipParent; property HitTest; property Visible; property Locked; property Position; property Text: String read FText write SetText; property OnClick; property OnDblClick; property OnPainting; property OnPaint; property OnResize; property OnResized; property OnFinishToast: TNotifyEvent read FOnFinishToast write SetOnFinishToast; property IsStarted: Boolean read FIsStarted write SetIsStarted; end; TWindowsToastDialog = class(TCustomScrollBox) private FToastList: TObjectList<TWindowsToast>; { private declarations } protected { protected declarations } procedure DoFinishToast(Sender: TObject); function GetDefaultStyleLookupName: string; override; function DoCalcContentBounds: TRectF; override; procedure Paint; override; procedure DoUpdateAniCalculations(const AAniCalculations: TScrollCalculations); override; public { public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Content; procedure MakeText(AText: string; const ADuration: TWindowsToastDuration = TWindowsToastDuration.ToastDurationLengthShort; ABackgroundColor: TAlphaColor = $FF525252; ATextColor: TAlphaColor = $FFFFFFFF); published { published declarations } property Align; property Anchors; property ClipParent; property Cursor; property DisableMouseWheel; property Height; property Locked; property Margins; property Opacity; property Padding; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property TouchTargetExpansion; property Visible; property Width; end; procedure Register; implementation procedure Register; begin RegisterComponents('Material Design', [TWindowsToastDialog]); end; { TWindowsToast } constructor TWindowsToast.Create(AOwner: TComponent); begin inherited; FIsStarted := False; FFont := TFont.Create; FFont.Size := 14; FFont.Family := 'Roboto'; FFillText := TBrush.Create(TBrushKind.Solid, $FFFFFFFF); FFillBackground := TBrush.Create(TBrushKind.Solid, $FF525252); FFloatAnimationOpacity := TFloatAnimation.Create(Self); AddObject(FFloatAnimationOpacity); Width := 300; Height := 30; FBackgroundSize := TSize.Create(270, 30); HitTest := False; end; destructor TWindowsToast.Destroy; begin FFont.Free; FFillText.Free; FFillBackground.Free; FFloatAnimationOpacity.Free; if IsStarted then begin FThreadDuration.Terminate; FreeAndNil(FThreadDuration); end; inherited; end; procedure TWindowsToast.DoFinishToast(Sender: TObject); begin if Assigned(FOnFinishToast) then FOnFinishToast(Self); end; procedure TWindowsToast.DoTextChanged(Sender: TObject); begin RecalcToastHeight; Repaint; end; procedure TWindowsToast.Paint; var FillTextRect: TRectF; begin inherited; FillTextRect := TRectF.Create(Width / 2 - FBackgroundSize.Width / 2, 15, Width / 2 + FBackgroundSize.Width / 2, FBackgroundSize.Height - 15); // Desenha primeiro o fundo... Canvas.Fill.Assign(FFillBackground); Canvas.FillRect(TRectF.Create((Width / 2 - FBackgroundSize.Width / 2) - 15, 0, (Width / 2 + FBackgroundSize.Width / 2) + 15, FBackgroundSize.Height), FBackgroundSize.Height / 2, FBackgroundSize.Height / 2, [TCorner.TopLeft, TCorner.TopRight, TCorner.BottomLeft, TCorner.BottomRight], Opacity, TCornerType.Round); // Depois desenha o texto... Canvas.Fill.Assign(FFillText); Canvas.FillText(FillTextRect, FText, True, Opacity * 0.87 / 1, [], TTextAlign.Center, TTextAlign.Leading); end; procedure TWindowsToast.RecalcToastHeight; var MeasureTextRect: TRectF; begin // Calcula o tamanho do texto MeasureTextRect := TRectF.Create(0, 0, FBackgroundSize.Width, Screen.Height); Canvas.Fill.Assign(FFillText); Canvas.Font.Assign(FFont); Canvas.MeasureText(MeasureTextRect, FText, True, [], TTextAlign.Center, TTextAlign.Leading); FBackgroundSize.Height := Round(MeasureTextRect.Height) + 30; Height := FBackgroundSize.Height; if MeasureTextRect.Width < 250 then FBackgroundSize.Width := Round(MeasureTextRect.Width) + 30; end; procedure TWindowsToast.SetDuration(const Value: TWindowsToastDuration); begin FDuration := Value; end; procedure TWindowsToast.SetFillBackground(const Value: TBrush); begin FFillBackground := Value; end; procedure TWindowsToast.SetFillText(const Value: TBrush); begin FFillText := Value; end; procedure TWindowsToast.SetIsStarted(const Value: Boolean); begin FIsStarted := Value; end; procedure TWindowsToast.SetOnFinishToast(const Value: TNotifyEvent); begin FOnFinishToast := Value; end; procedure TWindowsToast.SetText(const Value: String); var OldText: string; begin OldText := FText; FText := Value; if OldText <> FText then DoTextChanged(Self); end; procedure TWindowsToast.Start; begin FIsStarted := True; FFloatAnimationOpacity.PropertyName := 'Opacity'; FFloatAnimationOpacity.Duration := 0.5; FFloatAnimationOpacity.StartValue := 0; FFloatAnimationOpacity.StopValue := 1; FThreadDuration := TThread.CreateAnonymousThread( procedure var LDateTime: TDateTime; LNow: TDateTime; begin TThread.Synchronize(nil, procedure begin FFloatAnimationOpacity.Enabled := True; end); LDateTime := Now(); LNow := Now(); case FDuration of ToastDurationLengthShort: while (SecondsBetween(LNow, LDateTime) <= 3) and (not FThreadDuration.CheckTerminated) do begin LNow := Now(); Sleep(100); end; ToastDurationLengthLong: while (SecondsBetween(LNow, LDateTime) <= 6) and (not FThreadDuration.CheckTerminated) do begin LNow := Now(); Sleep(100); end; end; TThread.Synchronize(nil, procedure begin FFloatAnimationOpacity.Enabled := False; FFloatAnimationOpacity.StartValue := 1; FFloatAnimationOpacity.StopValue := 0; FFloatAnimationOpacity.OnFinish := DoFinishToast; FFloatAnimationOpacity.Enabled := True; end); end); FThreadDuration.FreeOnTerminate := False; FThreadDuration.Start; end; { TWindowsToastDialog } constructor TWindowsToastDialog.Create(AOwner: TComponent); begin inherited; ShowScrollBars := False; FToastList := TObjectList<TWindowsToast>.Create; HitTest := False; Content.Locked := True; Content.Enabled := False; Enabled := False; end; procedure TWindowsToastDialog.Paint; begin inherited; if (csDesigning in ComponentState) and not Locked then DrawDesignBorder(DesignBorderColor or TAlphaColorRec.Alpha, DesignBorderColor); end; destructor TWindowsToastDialog.Destroy; begin FToastList.Clear; FreeAndNil(FToastList); inherited; end; function TWindowsToastDialog.DoCalcContentBounds: TRectF; begin if (Content <> nil) and (ContentLayout <> nil) then Content.Width := ContentLayout.Width; Result := inherited DoCalcContentBounds; if ContentLayout <> nil then Result.Width := ContentLayout.Width; end; procedure TWindowsToastDialog.DoFinishToast(Sender: TObject); var LWindowsToast: TWindowsToast; begin LWindowsToast := Sender as TWindowsToast; LWindowsToast.Parent := nil; FToastList.Remove(LWindowsToast); // Self.Content.Repaint; end; procedure TWindowsToastDialog.DoUpdateAniCalculations(const AAniCalculations: TScrollCalculations); begin inherited DoUpdateAniCalculations(AAniCalculations); AAniCalculations.TouchTracking := AAniCalculations.TouchTracking - [ttHorizontal]; end; function TWindowsToastDialog.GetDefaultStyleLookupName: string; begin Result := 'scrollboxstyle'; end; procedure TWindowsToastDialog.MakeText(AText: string; const ADuration: TWindowsToastDuration; ABackgroundColor, ATextColor: TAlphaColor); var LWindowsToast: TWindowsToast; begin LWindowsToast := TWindowsToast.Create(nil); FToastList.Add(LWindowsToast); Content.AddObject(LWindowsToast); LWindowsToast.Opacity := 0; LWindowsToast.FillBackground.Color := ABackgroundColor; LWindowsToast.FillText.Color := ATextColor; LWindowsToast.Text := AText; LWindowsToast.Duration := ADuration; LWindowsToast.OnFinishToast := DoFinishToast; LWindowsToast.Margins.Bottom := 5; // LWindowsToast.Position.Y := Self.Content.Height - LWindowsToast.Height - (30); LWindowsToast.Position.X := Self.Content.Width / 2 - LWindowsToast.Width / 2; LWindowsToast.Position.Y := Content.Width; LWindowsToast.Align := TAlignLayout.Bottom; LWindowsToast.Start; end; end.
unit ltr24api; interface uses SysUtils, ltrapitypes, ltrapidefine, ltrapi; const // Текущая версия библиотеки. LTR24_VERSION_CODE = $02000000; // Количество каналов. LTR24_CHANNEL_NUM = 4; // Количество диапазонов в режиме диф. входа. LTR24_RANGE_NUM = 2; // Количество диапазонов в режиме ICP-входа. LTR24_ICP_RANGE_NUM = 2; // Количество частот дискретизации. LTR24_FREQ_NUM = 16; // Количество значений источника тока LTR24_I_SRC_VALUE_NUM = 2; // Размер поля с названием модуля. LTR24_NAME_SIZE = 8; // Размер поля с серийным номером модуля. LTR24_SERIAL_SIZE = 16; { -------------- Коды ошибок, специфичные для LTR24 ------------------------} LTR24_ERR_INVAL_FREQ = -10100; LTR24_ERR_INVAL_FORMAT = -10101; LTR24_ERR_CFG_UNSUP_CH_CNT = -10102; LTR24_ERR_INVAL_RANGE = -10103; LTR24_ERR_WRONG_CRC = -10104; LTR24_ERR_VERIFY_FAILED = -10105; LTR24_ERR_DATA_FORMAT = -10106; LTR24_ERR_UNALIGNED_DATA = -10107; LTR24_ERR_DISCONT_DATA = -10108; LTR24_ERR_CHANNELS_DISBL = -10109; LTR24_ERR_UNSUP_VERS = -10110; LTR24_ERR_FRAME_NOT_FOUND = -10111; LTR24_ERR_UNSUP_FLASH_FMT = -10116; LTR24_ERR_INVAL_I_SRC_VALUE = -10117; LTR24_ERR_UNSUP_ICP_MODE = -10118; {------------------ Коды частот дискретизации. -----------------------------} LTR24_FREQ_117K = 0; // 117.1875 кГц LTR24_FREQ_78K = 1; // 78.125 кГц LTR24_FREQ_58K = 2; // 58.59375 кГц LTR24_FREQ_39K = 3; // 39.0625 кГц LTR24_FREQ_29K = 4; // 29.296875 кГц LTR24_FREQ_19K = 5; // 19.53125 кГц LTR24_FREQ_14K = 6; // 14.6484375 кГц LTR24_FREQ_9K7 = 7; // 9.765625 кГц LTR24_FREQ_7K3 = 8; // 7.32421875 кГц LTR24_FREQ_4K8 = 9; // 4.8828125 кГц LTR24_FREQ_3K6 = 10; // 3.662109375 кГц LTR24_FREQ_2K4 = 11; // 2.44140625 кГц LTR24_FREQ_1K8 = 12; // 1.8310546875 кГц LTR24_FREQ_1K2 = 13; // 1.220703125 кГц LTR24_FREQ_915 = 14; // 915.52734375 Гц LTR24_FREQ_610 = 15; // 610.3515625 Гц {---------------------- Коды диапазонов в режиме диф. вход. -----------------} LTR24_RANGE_2 = 0; // +/-2 В LTR24_RANGE_10 = 1; // +/-10 В {---------------------- Коды диапазонов в режиме ICP-вход. ------------------} LTR24_ICP_RANGE_1 = 0; // ~1 В LTR24_ICP_RANGE_5 = 1; // ~5 В {---------------------- Значения источника тока. ----------------------------} LTR24_I_SRC_VALUE_2_86 = 0; // 2.86 мА LTR24_I_SRC_VALUE_10 = 1; // 10 мА {------------------------ Коды форматов отсчетов. ---------------------------} LTR24_FORMAT_20 = 0; // 20-битный формат LTR24_FORMAT_24 = 1; // 24-битный формат {------------------- Флаги, управляющие обработкой данных. ------------------} //Признак, что нужно применить калибровочные коэффициенты LTR24_PROC_FLAG_CALIBR = $00000001; // Признак, что нужно перевести коды АЦП в Вольты LTR24_PROC_FLAG_VOLT = $00000002; // Признак, что необходимо выполнить коррекцию АЧХ LTR24_PROC_FLAG_AFC_COR = $00000004; // Признак, что идет обработка не непрерывных данных LTR24_PROC_FLAG_NONCONT_DATA = $00000100; type {$A4} { Коэффициенты БИХ-фильтра коррекции АЧХ } TLTR24_AFC_IIR_COEF = record a0 : Double; a1 : Double; b0 : Double; end; { Набор коэффициентов для коррекции АЧХ модуля } TLTR24_AFC_COEFS = record // Частота сигнала, для которой снято отношение амплитуд из FirCoef AfcFreq : Double; { Набор отношений измеренной амплитуды синусоидального сигнала к реальной амплитуде для макс. частоты дискретизации и частоты сигнала из AfcFreq для каждого канала и каждого диапазона } FirCoef : Array [0..LTR24_CHANNEL_NUM-1] of Array [0..LTR24_RANGE_NUM-1] of Double; { @brief Коэффициенты БИХ-фильтра для коррекции АЧХ АЦП на частотах #LTR24_FREQ_39K и ниже } AfcIirCoef : TLTR24_AFC_IIR_COEF; end; { Заводские калибровочные коэффициенты для одного диапазона } TLTR24_CBR_COEF = record Offset : Single; // Смещение Scale : Single; // Коэффициент масштаба end; { Информация о модуле. Содержит информацию о модуле. Вся информация, кроме значений полей SupportICP и VerPLD, берется из ПЗУ моду-ля и действительна только после вызова LTR24_GetConfig(). } TINFO_LTR24 = record // Название модуля ("LTR24") Name : Array [0..LTR24_NAME_SIZE-1] of AnsiChar; // Серийный номер модуля Serial : Array [0..LTR24_SERIAL_SIZE-1] of AnsiChar; // Версия прошивки ПЛИС. VerPLD : Byte; // Признак поддержки измерения с ICP датчиков SupportICP : LongBool; Reserved : Array [1..8] of LongWord; // Массив заводских калибровочных коэффициентов. CalibCoef : Array [0..LTR24_CHANNEL_NUM-1] of Array [0..LTR24_RANGE_NUM-1] of Array [0..LTR24_FREQ_NUM-1] of TLTR24_CBR_COEF; // Коэффициенты для корректировки АЧХ. AfcCoef : TLTR24_AFC_COEFS; // Измеренные значения источников токов для каждого канала(только для LTR24-2). ISrcVals : Array [0..LTR24_CHANNEL_NUM-1] of Array [0..LTR24_I_SRC_VALUE_NUM-1] of Double; end; TLTR24_CHANNEL_MODE = record { Включение канала. } Enable : LongBool; { Код диапазона канала. * Устанавливается равным одной из констант "LTR24_RANGE_*" или "LTR24_ICP_RANGE_* } Range : Byte; { Режим отсечки постоянной составляющей (TRUE -- включен). Имеет значение только только в случае, если поле ICPMode равно FALSE. } AC : LongBool; { Включение режима измерения ICP-датчиков Если FALSE - используется режим "Диф. вход" или "Измерение нуля" (в зависимости от поля TestMode) Если TRUE - режим "ICP" или "ICP тест" } ICPMode : LongBool; { Резерв. Поле не должно изменяться пользователем } Reserved : Array [1..4] of LongWord; end; PTLTR24_INTARNAL = ^TLTR24_INTARNAL; TLTR24_INTARNAL = record end; { Управляющая структура модуля. Хранит текущие настройки модуля, информацию о его состоянии, структуру канала связи. Передается в большинство функций библиотеки. Некоторые поля структуры доступны для изменения пользователем для настройки параметров модуля. Перед использованием требует инициализации с помощью функции LTR24_Init. } TLTR24 = record { Размер структуры TLTR24. Заполняется автоматически при вызове функции LTR24_Init. } Size : Integer; { Канал связи с LTR сервером. } Channel : TLTR; { Текущее состояние сбора данных (TRUE -- сбор данных запущен). } Run : LongBool; { Код частоты дискретизации. Устанавливается равным одной из констант @ref freqs "LTR24_FREQ_*". Устанавливается пользователем. } ADCFreqCode : Byte; { Значение частоты дискретизации в Гц. Заполняется значением частоты дискретизации, соответствующим коду в поле ADCFreqCode, после выполнения функции LTR24_SetADC. } ADCFreq : double; { Код формата данных. Устанавливается равным одной из констант @ref formats "LTR24_FORMAT_*". Устанавливается пользователем. } DataFmt : Byte; { Значение источника тока для всех каналов подключения ICP-датчиков. Устанавливается равным одной из констант @ref i_src_vals "LTR24_I_SRC_VALUE_*". Устанавливается пользователем. } ISrcValue : Byte; { Включение тестовых режимов. Включает тестовые режимы ("Измерение нуля" или "ICP-тест" в зависимости от значения значения поля ICPMode для каждого канала) для всех каналов (TRUE – включен). Устанавливается пользователем. } TestMode : LongBool; { Резерв. Поле не должно изменяться пользователем } Reserved : Array [1..16] of LongWord; { Настройки каналов. } ChannelMode : Array [0..LTR24_CHANNEL_NUM-1] of TLTR24_CHANNEL_MODE; { Информация о модуле. } ModuleInfo : TINFO_LTR24; { Массив используемых калибровочных коэффициентов. Применяемые для коррекции данных в функции LTR24_ProcessData() калибровочные коэффициенты по каждому каналу, диапазону и частоте. При вызове LTR24_GetConfig() в данные поля копируются заводские калибровочные коэффициенты (те же, что и в ModuleInfo). Но, при необходимости, пользователь может записать в данные поля свои коэффициенты. } CalibCoef : Array [0..LTR24_CHANNEL_NUM-1] of Array [0..LTR24_RANGE_NUM-1] of Array [0..LTR24_FREQ_NUM-1] of TLTR24_CBR_COEF; { Коэффициенты для корректировки АЧХ, применяемые в функции LTR24_ProcessData(). При вызове LTR24_GetConfig() поля копируются значения из ПЗУ модуля (те же, что и в ModuleInfo) } AfcCoef : TLTR24_AFC_COEFS ; { Указатель на структуру с параметрами, используемыми только библиотекой и недоступными пользователю. } Internal : PTLTR24_INTARNAL; end; pTLTR24=^TLTR24; {$A+} // Возвращает текущую версию библиотеки Function LTR24_GetVersion : LongWord; // Инициализация описателя модуля Function LTR24_Init(out hnd: TLTR24) : Integer; // Установить соединение с модулем. Function LTR24_Open(var hnd: TLTR24; net_addr : LongWord; net_port : Word; csn: string; slot: Word): Integer; // Закрытие соединения с модулем Function LTR24_Close(var hnd: TLTR24) : Integer; // Проверка, открыто ли соединение с модулем. Function LTR24_IsOpened(var hnd: TLTR24) : Integer; { Считывает информацию из флеш памяти модуля и обновляет поля ModuleInfo в управляющей структуре модуля } Function LTR24_GetConfig(var hnd: TLTR24) : Integer; // Запись настроек в модуль Function LTR24_SetADC(var hnd: TLTR24) : Integer; // Перевод в режим сбора данных Function LTR24_Start(var hnd: TLTR24) : Integer; // Останов режима сбора данных Function LTR24_Stop(var hnd: TLTR24) : Integer; { Используется только при запущенном сборе данных. Включает режим измерения собственного нуля. } Function LTR24_SetZeroMode(var hnd : TLTR24; enable : LongBool) : Integer; { Используется только при запущенном сборе данных. Включает режим отсечения постоянной составляющей для каждого канала. Возвращает код ошибки. } Function LTR24_SetACMode(var hnd : TLTR24; chan : Byte; ac_mode : LongBool) : Integer; // Прием данных от модуля Function LTR24_Recv(var hnd: TLTR24; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer; overload; Function LTR24_Recv(var hnd: TLTR24; out data : array of LongWord; size: LongWord; tout : LongWord): Integer; overload; Function LTR24_RecvEx(var hnd : TLTR24; out data : array of LongWord; out tmark : array of LongWord; size : LongWord; timeout : LongWord; out time_vals: Int64): Integer; // Обработка принятых от модуля слов Function LTR24_ProcessData(var hnd: TLTR24; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out ovload : array of LongBool): Integer; overload; Function LTR24_ProcessData(var hnd: TLTR24; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord): Integer; overload; // Получение сообщения об ошибке. Function LTR24_GetErrorString(err: Integer) : string; // Определяет данные в слоте для хранения управляющей структуры как некорректные Function LTR24_FindFrameStart(var hnd : TLTR24; var data : array of LongWord; size : Integer; out index : Integer) : Integer; implementation Function _get_version : LongWord; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_GetVersion'; Function _init(out hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_Init'; Function _open(var hnd: TLTR24; net_addr : LongWord; net_port : Word; csn: PAnsiChar; slot: Word) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_Open'; Function _close(var hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_Close'; Function _is_opened(var hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_IsOpened'; Function _get_config(var hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_GetConfig'; Function _set_adc(var hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_SetADC'; Function _start(var hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_Start'; Function _stop(var hnd: TLTR24) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_Stop'; Function _set_zero_mode(var hnd : TLTR24; enable : LongBool) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_SetZeroMode'; Function _set_ac_mode(var hnd : TLTR24; chan : Byte; ac_mode : LongBool) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_SetACMode'; Function _recv(var hnd: TLTR24; out data; out tmark; size: LongWord; tout : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_Recv'; function _recv_ex(var hnd : TLTR24; out data; out tmark; size : LongWord; timeout : LongWord; out time_vals: Int64): Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_RecvEx'; Function _process_data(var hnd: TLTR24; var src; out dest; var size: Integer; flags : LongWord; out ovload): Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_ProcessData'; Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_GetErrorString'; // Определяет данные в слоте для хранения управляющей структуры как некорректные Function priv_FindFrameStart(var hnd : TLTR24; var data; size : Integer; out index : Integer) : Integer; {$I ltrapi_callconvention}; external 'ltr24api' name 'LTR24_FindFrameStart'; Function LTR24_GetVersion : LongWord; begin LTR24_GetVersion := _get_version; end; Function LTR24_Init(out hnd: TLTR24) : Integer; begin LTR24_Init := _init(hnd); end; Function LTR24_Open(var hnd: TLTR24; net_addr : LongWord; net_port : Word; csn: string; slot: Word): Integer; begin LTR24_Open:=_open(hnd, net_addr, net_port, PAnsiChar(AnsiString(csn)), slot); end; Function LTR24_Close(var hnd: TLTR24) : Integer; begin LTR24_Close := _close(hnd); end; Function LTR24_IsOpened(var hnd: TLTR24) : Integer; begin LTR24_IsOpened := _is_opened(hnd); end; Function LTR24_GetConfig(var hnd: TLTR24) : Integer; begin LTR24_GetConfig := _get_config(hnd); end; Function LTR24_SetADC(var hnd: TLTR24) : Integer; begin LTR24_SetADC := _set_adc(hnd); end; Function LTR24_Start(var hnd: TLTR24) : Integer; begin LTR24_Start := _start(hnd); end; Function LTR24_Stop(var hnd: TLTR24) : Integer; begin LTR24_Stop := _stop(hnd); end; Function LTR24_SetZeroMode(var hnd : TLTR24; enable : LongBool) : Integer; begin LTR24_SetZeroMode := _set_zero_mode(hnd, enable); end; Function LTR24_SetACMode(var hnd : TLTR24; chan : Byte; ac_mode : LongBool) : Integer; begin LTR24_SetACMode := _set_ac_mode(hnd, chan, ac_mode); end; Function LTR24_GetErrorString(err: Integer) : string; begin LTR24_GetErrorString:=string(_get_err_str(err)); end; Function LTR24_Recv(var hnd: TLTR24; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer; begin LTR24_Recv:=_recv(hnd, data, tmark, size, tout); end; Function LTR24_Recv(var hnd: TLTR24; out data : array of LongWord; size: LongWord; tout : LongWord): Integer; begin LTR24_Recv:=_recv(hnd, data, PLongWord(nil)^, size, tout); end; Function LTR24_RecvEx(var hnd : TLTR24; out data : array of LongWord; out tmark : array of LongWord; size : LongWord; timeout : LongWord; out time_vals: Int64) : Integer; begin LTR24_RecvEx:=_recv_ex(hnd, data, tmark, size, timeout, time_vals); end; Function LTR24_ProcessData(var hnd: TLTR24; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out ovload : array of LongBool): Integer; begin LTR24_ProcessData:=_process_data(hnd, src, dest, size, flags, ovload); end; Function LTR24_ProcessData(var hnd: TLTR24; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord): Integer; begin LTR24_ProcessData:=_process_data(hnd, src, dest, size, flags, PLongWord(nil)^); end; Function LTR24_FindFrameStart(var hnd : TLTR24; var data : array of LongWord; size : Integer; out index : Integer) : Integer; begin LTR24_FindFrameStart:= priv_FindFrameStart(hnd, data, size, index); end; end.
unit Initializer.PhysicalDrive; interface uses SysUtils, Graphics, Global.LanguageString, Initializer.Mainpart, Initializer.PartitionAlign, Initializer.ReplacedSector, Initializer.SMART, BufferInterpreter, Initializer.TotalWrite, Initializer.CriticalWarning, Support, OS.Version.Helper, Getter.OS.Version; type TMainformAlert = record SMARTAlert: TSMARTAlert; IsMisalignedPartitionExists: Boolean; end; TMainformPhysicalDriveApplier = class private MainformAlert: TMainformAlert; IsSerialOpened: Boolean; procedure ApplyAlert; procedure ApplyDataSetManagementSetting; procedure ApplyMainpart; procedure ApplyPartitionAlign; procedure ApplyReplacedSector; procedure ApplySMARTAndSetSMARTAlert; procedure ApplyTotalWrite; procedure RevertLastChangesOfMainform; procedure SetAlertLabelBadPartition; procedure SetAlertLabelBadReadWriteError; procedure SetAlertLabelBadReplacedSector; procedure SetSMARTAlert; function IsNotNVMe: Boolean; procedure ApplyCriticalWarning; function IsNVMeCriticalWarning: Boolean; procedure SetAlertLabelBadCriticalWarning; public procedure ApplyMainformPhysicalDrive(IsSerialOpened: Boolean); end; implementation uses Form.Main; procedure TMainformPhysicalDriveApplier.ApplyMainpart; var MainpartApplier: TMainformMainpartApplier; begin MainpartApplier := TMainformMainpartApplier.Create; MainpartApplier.ApplyMainformMainpart(IsSerialOpened); FreeAndNil(MainpartApplier); end; procedure TMainformPhysicalDriveApplier.ApplyPartitionAlign; var PartitionAlignApplier: TMainformPartitionAlignApplier; begin PartitionAlignApplier := TMainformPartitionAlignApplier.Create; MainformAlert.IsMisalignedPartitionExists := PartitionAlignApplier.ApplyAlignAndGetMisalignedExists; FreeAndNil(PartitionAlignApplier); end; procedure TMainformPhysicalDriveApplier.ApplyReplacedSector; var ReplacedSectorApplier: TMainformReplacedSectorApplier; begin ReplacedSectorApplier := TMainformReplacedSectorApplier.Create; ReplacedSectorApplier.ApplyMainformReplacedSector; FreeAndNil(ReplacedSectorApplier); end; procedure TMainformPhysicalDriveApplier.ApplyCriticalWarning; var CriticalWarningApplier: TMainformCriticalWarningApplier; begin CriticalWarningApplier := TMainformCriticalWarningApplier.Create; CriticalWarningApplier.ApplyMainformCriticalWarning; FreeAndNil(CriticalWarningApplier); end; procedure TMainformPhysicalDriveApplier.ApplySMARTAndSetSMARTAlert; var SMARTApplier: TMainformSMARTApplier; begin SMARTApplier := TMainformSMARTApplier.Create; SMARTApplier.ApplyMainformSMART; FreeAndNil(SMARTApplier); SetSMARTAlert; end; procedure TMainformPhysicalDriveApplier.ApplyTotalWrite; var TotalWriteApplier: TMainformTotalWriteApplier; begin TotalWriteApplier := TMainformTotalWriteApplier.Create; TotalWriteApplier.ApplyMainformTotalWrite; FreeAndNil(TotalWriteApplier); end; procedure TMainformPhysicalDriveApplier.SetAlertLabelBadPartition; begin fMain.lNotSafe.Font.Color := clRed; fMain.lNotsafe.Caption := CapStatus[CurrLang] + CapBadPartition[CurrLang]; end; procedure TMainformPhysicalDriveApplier.SetAlertLabelBadReplacedSector; begin fMain.lSectors.Font.Color := clRed; fMain.lNotsafe.Font.Color := clRed; fMain.lNotsafe.Caption := CapStatus[CurrLang] + CapNotSafeRepSect[CurrLang]; end; procedure TMainformPhysicalDriveApplier.SetAlertLabelBadReadWriteError; begin fMain.lPError.Font.Color := clRed; fMain.lNotsafe.Font.Color := clRed; fMain.lNotsafe.Caption := CapStatus[CurrLang] + CapNotSafeCritical[CurrLang]; end; procedure TMainformPhysicalDriveApplier.SetAlertLabelBadCriticalWarning; begin fMain.lSectors.Font.Color := clRed; fMain.lNotsafe.Font.Color := clRed; fMain.lNotsafe.Caption := CapStatus[CurrLang] + CapNotSafeCritical[CurrLang]; end; procedure TMainformPhysicalDriveApplier.SetSMARTAlert; begin MainformAlert.SMARTAlert := fMain.SelectedDrive.SMARTInterpreted.SMARTAlert; end; function TMainformPhysicalDriveApplier.IsNVMeCriticalWarning: Boolean; begin result := (fMain.SelectedDrive.IdentifyDeviceResult.StorageInterface = TStorageInterface.NVMe) and (MainformAlert.SMARTAlert.CriticalError); end; procedure TMainformPhysicalDriveApplier.ApplyAlert; begin if MainformAlert.IsMisalignedPartitionExists then SetAlertLabelBadPartition; if MainformAlert.SMARTAlert.ReplacedSector then SetAlertLabelBadReplacedSector; if MainformAlert.SMARTAlert.ReadEraseError then SetAlertLabelBadReadWriteError; if IsNVMeCriticalWarning then SetAlertLabelBadCriticalWarning; end; procedure TMainformPhysicalDriveApplier.ApplyDataSetManagementSetting; begin fMain.lTrim.Visible := fMain.SelectedDrive.IdentifyDeviceResult.IsDataSetManagementSupported; fMain.iTrim.Visible := fMain.lTrim.Visible; fMain.bSchedule.Visible := IsBelowWindows8(VersionHelper.Version); if not fMain.bSchedule.Visible then begin fMain.bTrimStart.Width := fMain.bSchedule.Left - fMain.bTrimStart.Left + fMain.bSchedule.Width; end; end; procedure TMainformPhysicalDriveApplier.RevertLastChangesOfMainform; begin if (not fMain.gFirmware.Visible) and (not fMain.gDownload.Visible) then fMain.lFirmware.Font.Style := []; fMain.lSectors.Font.Color := clWindowText; fMain.lPError.Font.Color := clWindowText; fMain.lNotsafe.Font.Color := clWindowText; fMain.lPartitionAlign.Font.Color := clWindowText; fMain.lNotsafe.Caption := CapStatus[CurrLang] + CapSafe[CurrLang]; end; function TMainformPhysicalDriveApplier.IsNotNVMe: Boolean; begin result := fMain.SelectedDrive.IdentifyDeviceResult.StorageInterface <> TStorageInterface.NVMe; end; procedure TMainformPhysicalDriveApplier.ApplyMainformPhysicalDrive( IsSerialOpened: Boolean); begin self.IsSerialOpened := IsSerialOpened; RevertLastChangesOfMainform; ApplyMainpart; ApplyPartitionAlign; if IsNotNVMe then ApplyReplacedSector else ApplyCriticalWarning; ApplySMARTAndSetSMARTAlert; ApplyTotalWrite; ApplyDataSetManagementSetting; ApplyAlert; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.TreeView; {$I FMX.Defines.inc} interface uses System.Classes, System.Types, System.UITypes, FMX.Types, FMX.Layouts, FMX.ListBox, FMX.Controls; type { TTreeViewItem } TCustomTreeView = class; TTreeViewItem = class(TTextControl, IItemsContainer) private FIsExpanded: Boolean; FButton: TCustomButton; FCheck: TCheckBox; FGlobalIndex: Integer; FIsChecked: Boolean; FIsSelected: Boolean; FContent: TContent; procedure SetIsExpanded(const Value: Boolean); procedure DoButtonClick(Sender: TObject); procedure DoCheckClick(Sender: TObject); function GetCount: Integer; procedure SetIsChecked(const Value: Boolean); procedure UpdateCheck; function GetTreeItem(Index: Integer): TTreeViewItem; procedure SetIsSelected(const Value: Boolean); { IItemContainer } function GetItemsCount: Integer; function GetItem(const AIndex: Integer): TFmxObject; protected procedure ChangeOrder; override; procedure ApplyStyle; override; procedure FreeStyle; override; procedure Realign; override; procedure DragEnd; override; function EnterChildren(AObject: TControl): Boolean; override; { TreeView } procedure ContentAddObject(AObject: TFmxObject); virtual; procedure ContentRemoveObject(AObject: TFmxObject); virtual; public constructor Create(AOwner: TComponent); override; procedure Paint; override; procedure AddObject(AObject: TFmxObject); override; procedure RemoveObject(AObject: TFmxObject); override; procedure Sort(Compare: TFmxObjectSortCompare); override; function ItemByPoint(const X, Y: Single): TTreeViewItem; function ItemByIndex(const Idx: Integer): TTreeViewItem; property Count: Integer read GetCount; property GlobalIndex: Integer read FGlobalIndex write FGlobalIndex; function TreeView: TCustomTreeView; function Level: Integer; function ParentItem: TTreeViewItem; property Items[Index: Integer]: TTreeViewItem read GetTreeItem; default; published property IsChecked: Boolean read FIsChecked write SetIsChecked; property IsExpanded: Boolean read FIsExpanded write SetIsExpanded; property IsSelected: Boolean read FIsSelected write SetIsSelected; property AutoTranslate default True; property Font; property StyleLookup; property Text; property TextAlign default TTextAlign.taLeading; end; { TTreeView } TOnCompareTreeViewItemEvent = function(Item1, Item2: TTreeViewItem): Integer of object; TOnTreeViewDragChange = procedure(SourceItem, DestItem: TTreeViewItem; var Allow: Boolean) of object; { TTreeView } TCustomTreeView = class(TScrollBox, IItemsContainer) private FMouseSelecting: Boolean; FOnChange: TNotifyEvent; FSelected: TTreeViewItem; FItemHeight: Single; FCountExpanded: Integer; FHideSelectionUnfocused: Boolean; FGlobalCount: Integer; FShowCheckboxes: Boolean; FOnChangeCheck: TNotifyEvent; FSorted: Boolean; FOnCompare: TOnCompareTreeViewItemEvent; FMultiSelect: Boolean; FFirstSelect: TTreeViewItem; FSelection: TControl; FSelections: TList; FAllowDrag: Boolean; FDragItem: TTreeViewItem; FOnDragChange: TOnTreeViewDragChange; FGlobalList: TList; FAlternatingRowBackground: Boolean; FOddFill: TBrush; procedure SetItemHeight(const Value: Single); procedure SetShowCheckboxes(const Value: Boolean); function GetTreeItem(Index: Integer): TTreeViewItem; procedure SetSorted(const Value: Boolean); procedure SortItems; procedure ClearSelection; procedure SelectAll; procedure SelectRange(Item1, Item2: TTreeViewItem); procedure UpdateSelection; procedure SetAllowDrag(const Value: Boolean); function GetCount: Integer; { IItemContainer } function GetItemsCount: Integer; function GetItem(const AIndex: Integer): TFmxObject; procedure SetAlternatingRowBackground(const Value: Boolean); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetSelected(const Value: TTreeViewItem); virtual; procedure ApplyStyle; override; procedure FreeStyle; override; procedure DoEnter; override; procedure DoExit; override; procedure HScrollChange(Sender: TObject); override; procedure VScrollChange(Sender: TObject); override; function GetContentBounds: TRectF; override; procedure UpdateGlobalIndexes; procedure DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); procedure ContentAddObject(AObject: TFmxObject); override; procedure ContentRemoveObject(AObject: TFmxObject); override; function GetItemRect(Item: TTreeViewItem): TRectF; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure EndUpdate; override; procedure Clear; procedure ExpandAll; procedure CollapseAll; function ItemByText(const AText: string): TTreeViewItem; function ItemByPoint(const X, Y: Single): TTreeViewItem; function ItemByIndex(const Idx: Integer): TTreeViewItem; function ItemByGlobalIndex(const Idx: Integer): TTreeViewItem; procedure AddObject(AObject: TFmxObject); override; procedure RemoveObject(AObject: TFmxObject); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; procedure KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; procedure DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean); override; procedure DragDrop(const Data: TDragObject; const Point: TPointF); override; property Count: Integer read GetCount; property GlobalCount: Integer read FGlobalCount; property CountExpanded: Integer read FCountExpanded; property Selected: TTreeViewItem read FSelected write SetSelected; property Items[Index: Integer]: TTreeViewItem read GetTreeItem; property AllowDrag: Boolean read FAllowDrag write SetAllowDrag; property AlternatingRowBackground: Boolean read FAlternatingRowBackground write SetAlternatingRowBackground; property ItemHeight: Single read FItemHeight write SetItemHeight; property HideSelectionUnfocused: Boolean read FHideSelectionUnfocused write FHideSelectionUnfocused default False; property MultiSelect: Boolean read FMultiSelect write FMultiSelect default False; property ShowCheckboxes: Boolean read FShowCheckboxes write SetShowCheckboxes default False; property Sorted: Boolean read FSorted write SetSorted default False; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChangeCheck: TNotifyEvent read FOnChangeCheck write FOnChangeCheck; property OnCompare: TOnCompareTreeViewItemEvent read FOnCompare write FOnCompare; property OnDragChange: TOnTreeViewDragChange read FOnDragChange write FOnDragChange; end; TTreeView = class(TCustomTreeView) published property StyleLookup; property CanFocus default True; property DisableFocusEffect; property TabOrder; property AllowDrag default False; property AlternatingRowBackground default False; property ItemHeight; property HideSelectionUnfocused default False; property MultiSelect default False; property ShowCheckboxes default False; property Sorted default False; property OnChange; property OnChangeCheck; property OnCompare; property OnDragChange; end; implementation uses System.Math, System.SysUtils, FMX.Ani; type { TTreeViewItemContent } TTreeViewItemContent = class(TContent) public procedure AddObject(AObject: TFmxObject); override; procedure RemoveObject(AObject: TFmxObject); override; end; procedure TTreeViewItemContent.AddObject(AObject: TFmxObject); begin inherited; if (Parent <> nil) and (Parent is TTreeViewItem) then TTreeViewItem(Parent).ContentAddObject(AObject); end; procedure TTreeViewItemContent.RemoveObject(AObject: TFmxObject); begin inherited; if (Parent <> nil) and (Parent is TTreeViewItem) then TTreeViewItem(Parent).ContentRemoveObject(AObject); end; { TTreeViewItem } constructor TTreeViewItem.Create(AOwner: TComponent); begin inherited; Position.Point := PointF(5000, 5000); FAutoTranslate := True; TextAlign := TTextAlign.taLeading; Height := 19; HitTest := False; CanFocus := False; FContent := TTreeViewItemContent.Create(Self); FContent.Parent := Self; FContent.Stored := False; FContent.Locked := True; FContent.HitTest := False; end; procedure TTreeViewItem.Realign; begin if (TreeView <> nil) and (TreeView.FUpdating > 0) then Exit; inherited; end; procedure TTreeViewItem.ChangeOrder; begin inherited; if (TreeView <> nil) then begin TreeView.UpdateGlobalIndexes; if (TreeView.FUpdating = 0) then TreeView.Realign; end; end; procedure TTreeViewItem.ContentAddObject(AObject: TFmxObject); begin if AObject is TTreeViewItem then if FUpdating = 0 then begin TreeView.UpdateGlobalIndexes; TreeView.Realign; end; end; procedure TTreeViewItem.ContentRemoveObject(AObject: TFmxObject); begin if AObject is TTreeViewItem then begin TTreeViewItem(AObject).IsSelected := False; if FUpdating = 0 then begin TreeView.UpdateGlobalIndexes; TreeView.Realign; end; end; end; procedure TTreeViewItem.DragEnd; begin inherited; DragLeave; if (TreeView <> nil) and (TreeView.FDragItem <> nil) then begin TreeView.FDragItem.RemoveFreeNotify(TreeView); TreeView.FDragItem := nil; end; end; function TTreeViewItem.GetCount: Integer; var i: Integer; begin Result := 0; if FContent.ChildrenCount > 0 then for i := 0 to FContent.ChildrenCount - 1 do if FContent.Children[i] is TTreeViewItem then begin Inc(Result); end; end; procedure TTreeViewItem.AddObject(AObject: TFmxObject); begin if AObject is TTreeViewItem then begin FContent.AddObject(AObject); if FUpdating = 0 then begin TreeView.UpdateGlobalIndexes; TreeView.Realign; end; end else inherited; end; procedure TTreeViewItem.RemoveObject(AObject: TFmxObject); begin if (AObject is TTreeViewItem) and (TTreeViewItem(AObject).TreeView = TreeView) then begin TTreeViewItem(AObject).Parent := nil; TTreeViewItem(AObject).IsSelected := False; if FUpdating = 0 then begin TreeView.UpdateGlobalIndexes; TreeView.Realign; end; end else inherited; end; function TTreeViewItem.GetItem(const AIndex: Integer): TFmxObject; begin Result := Items[AIndex]; end; function TTreeViewItem.GetItemsCount: Integer; begin Result := Count; end; function TTreeViewItem.ItemByPoint(const X, Y: Single): TTreeViewItem; var i: Integer; P, P1: TPointF; begin P := LocaltoAbsolute(PointF(X, Y)); for i := 0 to Count - 1 do with ItemByIndex(i) do begin if not Visible then Continue; if pointInObject(P.X, P.Y) then begin Result := Self.ItemByIndex(i); Exit; end else if (Count > 0) and (IsExpanded) then begin P1 := AbsoluteToLocal(P); Result := ItemByPoint(P1.X, P1.Y); if Result <> nil then Exit; end; end; Result := nil; end; function TTreeViewItem.ItemByIndex(const Idx: Integer): TTreeViewItem; var c, i: Integer; begin c := 0; if FContent.ChildrenCount > 0 then for i := 0 to FContent.ChildrenCount - 1 do if FContent.Children[i] is TTreeViewItem then begin if c = Idx then begin Result := TTreeViewItem(FContent.Children[i]); Exit; end; Inc(c); end; Result := nil; end; procedure TTreeViewItem.Paint; var R: TRectF; begin inherited Paint; if (csDesigning in ComponentState) and not Locked and not FInPaintTo then begin R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $A0909090; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; end; end; function TTreeViewItem.ParentItem: TTreeViewItem; begin if (Parent is TTreeViewItemContent) and (Parent.Parent is TTreeViewItem) then Result := TTreeViewItem(TTreeViewItemContent(Parent).Parent) else Result := nil; end; function TTreeViewItem.EnterChildren(AObject: TControl): Boolean; begin Result := inherited EnterChildren(AObject); if (TreeView <> nil) then begin TreeView.Selected := Self; Result := True; end; end; function TTreeViewItem.Level: Integer; var P: TFmxObject; begin Result := 0; P := Parent; while (P <> nil) and not(P is TCustomTreeView) do begin Result := Result + 1; P := P.Parent; if (P is TContent) then P := P.Parent; end; end; function TTreeViewItem.TreeView: TCustomTreeView; var P: TFmxObject; begin P := Parent; while (P <> nil) do begin if P is TCustomTreeView then begin Result := TCustomTreeView(P); Exit; end; P := P.Parent; end; Result := nil; end; procedure TTreeViewItem.FreeStyle; begin inherited; FButton := nil; FCheck := nil; end; procedure TTreeViewItem.ApplyStyle; var B: TFmxObject; begin inherited; B := FindStyleResource('button'); if (B <> nil) and (B is TCustomButton) then begin FButton := TCustomButton(B); FButton.OnClick := DoButtonClick; FButton.Visible := Count > 0; if FButton.Visible then begin FButton.ApplyStyleLookup; FButton.StartTriggerAnimation(Self, 'IsExpanded'); end; end; B := FindStyleResource('check'); if (B <> nil) and (B is TCheckBox) then begin FCheck := TCheckBox(B); FCheck.IsChecked := IsChecked; FCheck.OnChange := DoCheckClick; if TreeView <> nil then FCheck.Visible := TreeView.ShowCheckboxes; end; if IsSelected then begin StartTriggerAnimation(Self, 'IsSelected'); ApplyTriggerEffect(Self, 'IsSelected'); end; end; procedure TTreeViewItem.DoCheckClick(Sender: TObject); begin if FCheck <> nil then FIsChecked := FCheck.IsChecked; if TreeView <> nil then begin TreeView.SetFocus; TreeView.Selected := Self; if Assigned(TreeView.OnChangeCheck) then TreeView.OnChangeCheck(Self); end; end; procedure TTreeViewItem.UpdateCheck; var i: Integer; begin if (TreeView <> nil) and (FCheck <> nil) then FCheck.Visible := TreeView.ShowCheckboxes; if ChildrenCount > 0 then for i := 0 to ChildrenCount - 1 do if Children[i] is TTreeViewItem then TTreeViewItem(Children[i]).UpdateCheck; end; procedure TTreeViewItem.SetIsChecked(const Value: Boolean); begin if FIsChecked <> Value then begin FIsChecked := Value; if FCheck <> nil then FCheck.IsChecked := FIsChecked; end; end; procedure TTreeViewItem.SetIsSelected(const Value: Boolean); begin if FIsSelected <> Value then begin FIsSelected := Value; StartTriggerAnimation(Self, 'IsSelected'); if TreeView <> nil then with Treeview do begin if (Selected = nil) and not (MultiSelect) then Selected := Self; UpdateSelection; end; end; end; procedure TTreeViewItem.Sort(Compare: TFmxObjectSortCompare); begin FContent.Sort(Compare); end; procedure TTreeViewItem.DoButtonClick(Sender: TObject); begin IsExpanded := not IsExpanded; end; procedure TTreeViewItem.SetIsExpanded(const Value: Boolean); var i: Integer; Item: TTreeViewItem; begin if FIsExpanded <> Value then begin FIsExpanded := Value; if FContent.ChildrenCount > 0 then for i := FContent.ChildrenCount - 1 downto 0 do begin Item := nil; if FContent.Children[i] is TTreeViewItem then Item := TTreeViewItem(FContent.Children[i]); if Item <> nil then Item.IsExpanded := True; end; if (FButton <> nil) and not(csLoading in ComponentState) then begin FButton.Visible := Count > 0; if FButton.Visible then FButton.StartTriggerAnimation(Self, 'IsExpanded'); end; if TreeView <> nil then TreeView.Realign; end; end; function TTreeViewItem.GetTreeItem(Index: Integer): TTreeViewItem; begin Result := ItemByIndex(Index); end; { TTreeView } constructor TCustomTreeView.Create(AOwner: TComponent); begin inherited; FGlobalList := TList.Create; FGlobalList.Capacity := 100; FOddFill := TBrush.Create(TBrushKind.bkSolid, $20000000); CanFocus := True; AutoCapture := True; HideSelectionUnfocused := False; Width := 100; Height := 100; FItemHeight := 0; SetAcceptsControls(False); end; destructor TCustomTreeView.Destroy; begin if FSelections <> nil then FreeAndNil(FSelections); FreeAndNil(FGlobalList); FreeAndNil(FOddFill); inherited; end; procedure TCustomTreeView.ApplyStyle; var T: TFmxObject; begin inherited; T := FindStyleResource('content'); if (T <> nil) and (T is TControl) then begin TControl(T).OnPainting := DoContentPaint; end; T := FindStyleResource('selection'); if (T <> nil) and (T is TControl) then begin FSelection := TControl(T); FSelection.Visible := False; end; if (T <> nil) and (T is TControl) then begin TControl(T).Visible := False; end; UpdateSelection; end; procedure TCustomTreeView.FreeStyle; begin inherited; FSelection := nil; if FSelections <> nil then FSelections.Clear; end; procedure TCustomTreeView.UpdateGlobalIndexes; var GlobalIdx: Integer; procedure AlignItem(AItem: TTreeViewItem); var i: Integer; P: TPointF; begin if (AItem <> nil) then //don't do anything if the item is nil begin AItem.GlobalIndex := GlobalIdx; GlobalIdx := GlobalIdx + 1; FGlobalList.Add(AItem); if AItem.Count > 0 then begin if AItem.IsExpanded then for i := 0 to AItem.Count - 1 do AlignItem(AItem.ItemByIndex(i)); end; end; end; var i: Integer; begin FGlobalList.Clear; GlobalIdx := 0; for i := 0 to Count - 1 do AlignItem(ItemByIndex(i)); //not all the items are of type TTreeViewItem, so some may return nil FGlobalCount := GlobalIdx; end; function CompareTreeItem(Item1, Item2: TFmxObject): Integer; begin if (Item1 is TTreeViewItem) and (Item2 is TTreeViewItem) then begin if (TTreeViewItem(Item1).TreeView <> nil) and Assigned(TTreeViewItem(Item1).TreeView.OnCompare) then Result := TTreeViewItem(Item1).TreeView.OnCompare(TTreeViewItem(Item1), TTreeViewItem(Item2)) else {$IFDEF KS_COMPILER5} Result := CompareText(TTreeViewItem(Item1).Text, TTreeViewItem(Item2).Text); {$ELSE} Result := WideCompareText(TTreeViewItem(Item1).Text, TTreeViewItem(Item2).Text); {$ENDIF} end else Result := 0; end; procedure TCustomTreeView.SortItems; begin if not FSorted then Exit; FContent.Sort(CompareTreeItem); end; function TCustomTreeView.GetItemRect(Item: TTreeViewItem): TRectF; var P: TPointF; begin if Item <> nil then begin P := Item.LocaltoAbsolute(PointF(0, 0)); P := FContent.AbsoluteToLocal(P); Result := RectF(0, 0, Item.Width, Item.Height); OffsetRect(Result, P.X, P.Y); end else Result := RectF(0, 0, 0, 0); end; function TCustomTreeView.GetItem(const AIndex: Integer): TFmxObject; begin Result := Items[AIndex]; end; function TCustomTreeView.GetItemsCount: Integer; begin Result := Count; end; procedure TCustomTreeView.UpdateSelection; var i: Integer; P: TPointF; R: TRectF; Sel: Boolean; SelRects: array of TRectF; Clone: TControl; Vis: Boolean; begin if FSelection = nil then Exit; // calc rects Vis := True; Sel := False; SetLength(SelRects, 0); for i := 0 to GlobalCount - 1 do begin if (ItemByGlobalIndex(i).IsSelected) then begin P := ItemByGlobalIndex(i).LocaltoAbsolute(PointF(0, 0)); if (FSelection.Parent <> nil) and (FSelection.Parent is TControl) then P := TControl(FSelection.Parent).AbsoluteToLocal(P); R := RectF(P.X, P.Y, P.X + ItemByGlobalIndex(i).Width, P.Y + ItemByGlobalIndex(i).Height); if (Length(SelRects) > 0) and (i > 0) and (ItemByGlobalIndex(i - 1).IsSelected) then SelRects[High(SelRects)] := UnionRect(R, SelRects[High(SelRects)]) else begin SetLength(SelRects, Length(SelRects) + 1); SelRects[High(SelRects)] := R; end; Sel := True; end; end; // Create selection list if FSelections = nil then FSelections := TList.Create; // create selections if FSelections.Count < Length(SelRects) then for i := FSelections.Count to Length(SelRects) - 1 do begin Clone := TControl(FSelection.Clone(Self)); FSelections.Add(Clone); Clone.Parent := FSelection.Parent; end; // hide if not need if Length(SelRects) < FSelections.Count then for i := Length(SelRects) to FSelections.Count - 1 do begin TControl(FSelections[i]).Visible := False; end; // Check visible if HideSelectionUnfocused and not IsFocused then Vis := False; // align selections for i := 0 to High(SelRects) do begin TControl(FSelections[i]).Visible := Vis; if Vis then begin with SelRects[i] do TControl(FSelections[i]).SetBounds(Left, Top, Right - Left, Bottom - Top); end; end; end; function TCustomTreeView.GetContentBounds: TRectF; const StepX = 19; var CurY, CurX: Single; R: TRectF; procedure HideItem(AItem: TTreeViewItem); var i: Integer; begin AItem.Visible := False; AItem.Opacity := 0; if AItem.Count > 0 then for i := 0 to AItem.Count - 1 do HideItem(AItem.ItemByIndex(i)); end; procedure AlignItem(AItem: TTreeViewItem); var i: Integer; P: TPointF; begin if (AItem <> nil) then begin P := PointF(CurX, CurY); P := FContent.LocalToAbsolute(P); P := TControl(AItem.Parent).AbsoluteToLocal(P); if FItemHeight <> 0 then AItem.SetBounds(P.X + AItem.Padding.Left, P.Y + AItem.Padding.Top, R.Right - R.Left - AItem.Padding.Left - AItem.Padding.Right - (AItem.Level - 1) * StepX, FItemHeight) else AItem.SetBounds(P.X + AItem.Padding.Left, P.Y + AItem.Padding.Top, R.Right - R.Left - AItem.Padding.Left - AItem.Padding.Right - (AItem.Level - 1) * StepX, AItem.Height); if AItem.FButton <> nil then AItem.FButton.Visible := AItem.Count > 0; CurY := CurY + AItem.Height + AItem.Padding.Top + AItem.Padding.Bottom; if AItem.Count > 0 then begin if AItem.IsExpanded then begin CurX := CurX + StepX; for i := 0 to AItem.Count - 1 do begin with AItem.ItemByIndex(i) do begin Visible := True; Opacity := 1; end; AlignItem(AItem.ItemByIndex(i)); end; CurX := CurX - StepX; end else begin for i := 0 to AItem.Count - 1 do HideItem(AItem.ItemByIndex(i)); end; end; end; end; var i: Integer; c: Integer; P: TPointF; Sel: TTreeViewItem; begin Result := LocalRect; UpdateGlobalIndexes; if FUpdating > 0 then Exit; if ContentLayout = nil then Exit; R := ContentLayout.LocalRect; { content } FCountExpanded := 0; if FContent <> nil then begin { Sort if need } SortItems; { align } CurY := 0; CurX := 0; for i := 0 to Count - 1 do AlignItem(ItemByIndex(i)); R.Bottom := R.Top + CurY; end; if R.Bottom = R.Top then R.Bottom := R.Top + 1; Result := R; UpdateSelection; end; procedure TCustomTreeView.HScrollChange(Sender: TObject); begin inherited; UpdateSelection; end; procedure TCustomTreeView.VScrollChange(Sender: TObject); begin inherited; UpdateSelection; end; function TCustomTreeView.ItemByIndex(const Idx: Integer): TTreeViewItem; var c, i: Integer; begin c := 0; if (FContent <> nil) and (FContent.ChildrenCount > 0) then for i := 0 to FContent.ChildrenCount - 1 do if FContent.Children[i] is TTreeViewItem then begin if c = Idx then begin Result := TTreeViewItem(FContent.Children[i]); Exit; end; Inc(c); end; Result := nil; end; function TCustomTreeView.ItemByGlobalIndex(const Idx: Integer): TTreeViewItem; begin Result := TTreeViewItem(FGlobalList[Idx]); end; function TCustomTreeView.ItemByPoint(const X, Y: Single): TTreeViewItem; var i: Integer; P, P1: TPointF; begin P := LocaltoAbsolute(PointF(X, Y)); if (FContent <> nil) and (FContent.ChildrenCount > 0) then for i := 0 to FContent.ChildrenCount - 1 do if FContent.Children[i] is TTreeViewItem then begin if not TTreeViewItem(FContent.Children[i]).Visible then Continue; if not IntersectRect(TTreeViewItem(FContent.Children[i]).UpdateRect, UpdateRect) then Continue; if TTreeViewItem(FContent.Children[i]).pointInObject(P.X, P.Y) then begin Result := TTreeViewItem(FContent.Children[i]); Exit; end else if (TTreeViewItem(FContent.Children[i]).IsExpanded) and (TTreeViewItem(FContent.Children[i]).Count > 0) then begin P1 := TTreeViewItem(FContent.Children[i]).AbsoluteToLocal(P); Result := TTreeViewItem(FContent.Children[i]).ItemByPoint(P1.X, P1.Y); if Result <> nil then Exit; end; end; Result := nil; end; function TCustomTreeView.ItemByText(const AText: string): TTreeViewItem; var Item: TTreeViewItem; i: Integer; begin for i := 0 to GlobalCount - 1 do begin Item := ItemByGlobalIndex(i); if CompareText(AText, Item.Text) = 0 then begin Result := Item; Exit; end; end; Result := nil; end; procedure TCustomTreeView.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); begin inherited; if (Count > 0) and (Selected <> nil) then begin case Key of vkAdd: Selected.IsExpanded := True; vkSubtract: Selected.IsExpanded := False; vkHome: Selected := ItemByGlobalIndex(0); vkEnd: Selected := ItemByGlobalIndex(GlobalCount - 1); vkUp: if Selected.GlobalIndex > 0 then Selected := ItemByGlobalIndex(Selected.GlobalIndex - 1); vkDown: if Selected.GlobalIndex < GlobalCount - 1 then Selected := ItemByGlobalIndex(Selected.GlobalIndex + 1); else Exit; end; Key := 0; end; end; procedure TCustomTreeView.KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); begin inherited; end; procedure TCustomTreeView.DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean); var Obj: TTreeViewItem; begin inherited; with AbsoluteToLocal(Point) do Obj := ItemByPoint(X, Y); if (Obj <> FDragItem) then begin if FDragItem <> nil then begin FDragItem.DragLeave; FDragItem.RemoveFreeNotify(Self); end; FDragItem := Obj; if FDragItem <> nil then begin FDragItem.AddFreeNotify(Self); FDragItem.DragEnter(Data, Point); Accept := True; end else Accept := False; end else Accept := True; if FDragItem = Selected then Accept := False; end; procedure TCustomTreeView.DragDrop(const Data: TDragObject; const Point: TPointF); var Obj: TTreeViewItem; Allow: Boolean; begin inherited; if FDragItem <> nil then begin FDragItem.DragLeave; FDragItem.RemoveFreeNotify(Self); FDragItem := nil; end; with AbsoluteToLocal(Point) do Obj := ItemByPoint(X, Y); if Obj = nil then begin // to root Allow := True; if Assigned(OnDragChange) then OnDragChange(TTreeViewItem(Data.Source), nil, Allow); if Allow then begin TTreeViewItem(Data.Source).Parent := Self; Realign; end; end else begin Allow := True; if Assigned(OnDragChange) then OnDragChange(TTreeViewItem(Data.Source), Obj, Allow); if Allow then begin if not Obj.IsExpanded then Obj.IsExpanded := True; TTreeViewItem(Data.Source).Parent := Obj; Realign; end; end; end; procedure TCustomTreeView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var Item: TTreeViewItem; begin inherited; if Button = TMouseButton.mbLeft then begin Item := ItemByPoint(X, Y); if Item <> nil then begin if MultiSelect then begin if ssCtrl in Shift then Item.IsSelected := not Item.IsSelected else if ssShift in Shift then begin SelectRange(Selected, Item); Selected := Item; end else begin SelectRange(Item, Item); Selected := Item; end; FFirstSelect := Item; end else begin if Selected <> Item then Selected := Item else if AllowDrag then Root.BeginInternalDrag(Selected, Selected.MakeScreenshot); end; end; FMouseSelecting := True; end; end; procedure TCustomTreeView.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; end; procedure TCustomTreeView.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; FFirstSelect := nil; FMouseSelecting := False; end; procedure TCustomTreeView.Clear; var i: Integer; begin BeginUpdate; if FContent <> nil then if FContent.ChildrenCount > 0 then for i := FContent.ChildrenCount - 1 downto 0 do if FContent.Children[i] is TTreeViewItem then TFmxObject(FContent.Children[i]).Free; FScrollDesign.Y := 0; FScrollDesign.X := 0; FSelected := nil; UpdateGlobalIndexes; UpdateSelection; EndUpdate; end; procedure TCustomTreeView.SelectRange(Item1, Item2: TTreeViewItem); var i: Integer; begin if Item1 = nil then Exit; if Item2 = nil then Exit; for i := 0 to Min(Item1.GlobalIndex, Item2.GlobalIndex) - 1 do ItemByGlobalIndex(i).IsSelected := False; for i := Max(Item1.GlobalIndex, Item2.GlobalIndex) + 1 to GlobalCount - 1 do ItemByGlobalIndex(i).IsSelected := False; for i := Min(Item1.GlobalIndex, Item2.GlobalIndex) to Max(Item1.GlobalIndex, Item2.GlobalIndex) do ItemByGlobalIndex(i).IsSelected := True; end; procedure TCustomTreeView.ClearSelection; var i: Integer; begin for i := 0 to GlobalCount - 1 do ItemByGlobalIndex(i).IsSelected := False; end; procedure TCustomTreeView.SelectAll; var i: Integer; begin for i := 0 to GlobalCount - 1 do ItemByGlobalIndex(i).IsSelected := True; end; procedure TCustomTreeView.DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); var i: Integer; Item: TTreeViewItem; P: TPointF; R: TRectF; begin if (FContent <> nil) and (ContentLayout <> nil) then begin if FAlternatingRowBackground then begin Canvas.Fill.Assign(FOddFill); for i := 0 to GlobalCount - 1 do begin if Odd(i) then begin if i > GlobalCount - 1 then Item := ItemByIndex(Count - 1) else Item := ItemByGlobalIndex(i); P := Item.LocalToAbsolute(PointF(0, 0)); P := TControl(Sender).AbsoluteToLocal(P); R := RectF(0, P.Y, ContentLayout.Width, P.Y + Item.Height); if not IntersectRect(R, ARect) then Continue; Canvas.FillRect(R, 0, 0, [], AbsoluteOpacity); end; end; end; end; end; procedure TCustomTreeView.DoEnter; begin inherited; if HideSelectionUnfocused and (Selected <> nil) then UpdateSelection; end; procedure TCustomTreeView.DoExit; begin inherited; if HideSelectionUnfocused and (Selected <> nil) then UpdateSelection; end; procedure TCustomTreeView.AddObject(AObject: TFmxObject); begin if (FContent <> nil) and ((AObject is TTreeViewItem)) then begin FContent.AddObject(AObject); end else inherited; end; procedure TCustomTreeView.RemoveObject(AObject: TFmxObject); begin if (AObject is TTreeViewItem) and (TTreeViewItem(AObject).TreeView = Self) then begin TTreeViewItem(AObject).Parent := nil; end else inherited; end; procedure TCustomTreeView.ContentAddObject(AObject: TFmxObject); begin inherited; if AObject is TTreeViewItem then if FUpdating = 0 then begin UpdateGlobalIndexes; Realign; end; end; procedure TCustomTreeView.ContentRemoveObject(AObject: TFmxObject); begin inherited; if AObject is TTreeViewItem then begin TTreeViewItem(AObject).IsSelected := False; if AObject = FSelected then FSelected := nil; if FUpdating = 0 then begin UpdateGlobalIndexes; Realign; UpdateSelection; end; end; end; procedure TCustomTreeView.SetSelected(const Value: TTreeViewItem); var i: TFmxObject; P: TPointF; begin if FSelected <> Value then begin if (FSelected <> nil) and not MultiSelect then FSelected.IsSelected := False; FSelected := Value; if (FSelected <> nil) and (FContent <> nil) then begin i := FSelected.Parent; while ((i <> nil) and not(i is TCustomTreeView)) do begin if (i is TTreeViewItem) then TTreeViewItem(i).IsExpanded := True; i := i.Parent; end; if (FContent <> nil) and (ContentLayout <> nil) and (VScrollBar <> nil) then begin P := ContentLayout.AbsoluteToLocal (FSelected.LocaltoAbsolute(PointF(0, 0))); if P.Y < 0 then VScrollBar.Value := VScrollBar.Value + P.Y; if P.Y + FSelected.Padding.Top + FSelected.Padding.Bottom + FSelected.Height > ContentLayout.Height then VScrollBar.Value := VScrollBar.Value + (P.Y + FSelected.Padding.Top + FSelected.Padding.Bottom + FSelected.Height - ContentLayout.Height); end; FSelected.IsSelected := True; end; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TCustomTreeView.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FSelected) then FSelected := nil; if (Operation = opRemove) and (AComponent = FDragItem) then FDragItem := nil; end; procedure TCustomTreeView.SetItemHeight(const Value: Single); begin if FItemHeight <> Value then begin FItemHeight := Value; Realign; end; end; procedure TCustomTreeView.CollapseAll; var i: Integer; Item: TTreeViewItem; begin BeginUpdate; for i := GlobalCount - 1 downto 0 do begin Item := ItemByGlobalIndex(i); if Item <> nil then Item.IsExpanded := False; end; EndUpdate; end; procedure TCustomTreeView.ExpandAll; var i: Integer; Item: TTreeViewItem; begin BeginUpdate; for i := GlobalCount - 1 downto 0 do begin Item := ItemByGlobalIndex(i); if Item <> nil then Item.IsExpanded := True; end; EndUpdate; end; procedure TCustomTreeView.SetShowCheckboxes(const Value: Boolean); var i: Integer; begin if FShowCheckboxes <> Value then begin FShowCheckboxes := Value; for i := 0 to Count - 1 do if ItemByIndex(i) <> nil then ItemByIndex(i).UpdateCheck; end; end; function TCustomTreeView.GetTreeItem(Index: Integer): TTreeViewItem; begin Result := ItemByIndex(Index); end; procedure TCustomTreeView.SetSorted(const Value: Boolean); begin if FSorted <> Value then begin FSorted := Value; Realign; end; end; procedure TCustomTreeView.SetAllowDrag(const Value: Boolean); begin if FAllowDrag <> Value then begin FAllowDrag := Value; if FAllowDrag then EnableDragHighlight := True; end; end; procedure TCustomTreeView.SetAlternatingRowBackground(const Value: Boolean); begin if FAlternatingRowBackground <> Value then begin FAlternatingRowBackground := Value; Repaint; end; end; procedure TCustomTreeView.EndUpdate; begin inherited; end; function TCustomTreeView.GetCount: Integer; begin Result := 0; if (FContent <> nil) then Result := FContent.ChildrenCount; end; initialization RegisterFmxClasses([TTreeView, TTreeViewItem]); end.
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.Plextor; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TPlextorSMARTSupport = class(TSMARTSupport) private function IsCFDSSD(const Model: String): Boolean; function IsPlextorSSD(const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; function ModelHasPlextorString(const Model: String): Boolean; function SMARTHasPlextorCharacteristics( const SMARTList: TSMARTValueList): Boolean; function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; const EntryID = $E8; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TPlextorSMARTSupport } function TPlextorSMARTSupport.GetTypeName: String; begin result := 'SmartPlextor'; end; function TPlextorSMARTSupport.IsSSD: Boolean; begin result := true; end; function TPlextorSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := IsPlextorSSD(IdentifyDevice, SMARTList) or IsCFDSSD(IdentifyDevice.Model); end; function TPlextorSMARTSupport.IsCFDSSD(const Model: String): Boolean; begin result := FindAtFirst('CSSD-S6T128NM3PQ', Model) or FindAtFirst('CSSD-S6T256NM3PQ', Model) or FindAtFirst('CSSD-S6T512NM3PQ', Model); end; function TPlextorSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TPlextorSMARTSupport.IsPlextorSSD( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := ModelHasPlextorString(IdentifyDevice.Model) or SMARTHasPlextorCharacteristics(SMARTList); end; function TPlextorSMARTSupport.ModelHasPlextorString(const Model: String): Boolean; begin result := FindAtFirst('PLEXTOR', Model); end; function TPlextorSMARTSupport.SMARTHasPlextorCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin // 2012/10/10 // http://crystalmark.info/bbs/c-board.cgi?cmd=one;no=739;id=diskinfo#739 // http://crystalmark.info/bbs/c-board.cgi?cmd=one;no=829;id=diskinfo#829 result := (SMARTList.Count >= 8) and (SMARTList[0].Id = $01) and (SMARTList[1].Id = $05) and (SMARTList[2].Id = $09) and (SMARTList[3].Id = $0C) and (SMARTList[4].Id = $B1) and (SMARTList[5].Id = $B2) and (SMARTList[6].Id = $B5) and (SMARTList[7].Id = $B6); end; function TPlextorSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID($E8)].Current; end; function TPlextorSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TPlextorSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := IsEntryAvailable(EntryID, SMARTList); end; function TPlextorSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := false; result.Status := InnerCommonIsError(EntryID, SMARTList).Status; end; function TPlextorSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold); end; function TPlextorSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID1 = $B1; WriteID2 = $E9; WriteID3 = $F1; begin try SMARTList.GetIndexByID(WriteID1); result := true; except result := false; end; if not result then begin try SMARTList.GetIndexByID(WriteID2); result := true; except result := false; end; end; if not result then begin try SMARTList.GetIndexByID(WriteID3); result := true; except result := false; end; end; end; function TPlextorSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $09; ThisErrorType = ReadError; ErrorID = $01; ReplacedSectorsID = $05; begin FillChar(result, SizeOf(result), 0); result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID); result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.ReplacedSectors := SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID); result.TotalWrite := GetTotalWrite(SMARTList); end; function TPlextorSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID1 = $B1; WriteID2 = $E9; WriteID3 = $F1; begin try result.InValue.ValueInMiB := SMARTList.GetRAWByID(WriteID1) * 128; result.InValue.TrueHostWriteFalseNANDWrite := NANDWrite; except try result.InValue.ValueInMiB := GBToMB(SMARTList.GetRAWByID(WriteID2)); result.InValue.TrueHostWriteFalseNANDWrite := NANDWrite; except try result.InValue.ValueInMiB := SMARTList.ExceptionFreeGetRAWByID(WriteID3) * 32; result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; except result.InValue.ValueInMiB := 0; end; end; end; end; end.
unit FIToolkit.Reports.Parser.Consts; interface uses System.SysUtils, FIToolkit.Reports.Parser.Types, FIToolkit.Localization; const { FixInsight message types. Do not localize! } REGEX_FIMSG_CODING_CONVENTION = '^C[0-9]+$'; REGEX_FIMSG_FATAL = '^FATAL$'; REGEX_FIMSG_OPTIMIZATION = '^O[0-9]+$'; REGEX_FIMSG_TRIAL = '^Tria$'; REGEX_FIMSG_WARNING = '^W[0-9]+$'; { Common consts } ARR_MSGTYPE_TO_MSGID_REGEX_MAPPING : array [TFixInsightMessageType] of String = ( String.Empty, REGEX_FIMSG_WARNING, REGEX_FIMSG_OPTIMIZATION, REGEX_FIMSG_CODING_CONVENTION, REGEX_FIMSG_FATAL, REGEX_FIMSG_TRIAL ); { XML consts for a FixInsight report format. Do not localize! } // <FixInsightReport>\<file>\<message> STR_FIXML_ROOT_NODE = 'FixInsightReport'; STR_FIXML_FILE_NODE = 'file'; STR_FIXML_MESSAGE_NODE = 'message'; STR_FIXML_COL_ATTRIBUTE = 'col'; STR_FIXML_ID_ATTRIBUTE = 'id'; STR_FIXML_LINE_ATTRIBUTE = 'line'; STR_FIXML_NAME_ATTRIBUTE = 'name'; resourcestring {$IF LANGUAGE = LANG_EN_US} {$INCLUDE 'Locales\en-US.inc'} {$ELSEIF LANGUAGE = LANG_RU_RU} {$INCLUDE 'Locales\ru-RU.inc'} {$ELSE} {$MESSAGE FATAL 'No language defined!'} {$ENDIF} implementation end.
unit Utils; interface uses uniPanel, uniPageControl,uniGUIFrame,forms,System.SysUtils,uniGUIDialogs, uniGUITypes, uniGUIAbstractClasses,uniGUIVars, uniGUIClasses, uniGUIRegClasses, uniGUIForm, uniGUIBaseClasses, Vcl.Controls; procedure AddTab(PC:TuniPageControl;FrameAba: TFrame; Titulo: string); procedure CentralizaPanel(UniPanel:TUniPanel;Width,Height:integer); implementation uses MainModule, uniGUIApplication; procedure CentralizaPanel(UniPanel:TUniPanel;Width,Height:integer); begin // Centraliza o Panel - Colocar no evento OnScreenResize do Form; UniPanel.BorderStyle := ubsNone; // Remove a borda do Panel; UniPanel.Left := Round((Width/ 2) - (UniPanel.Width / 2)); UniPanel.Top := Round((Height / 2) - (UniPanel.Height / 2)); UniPanel.Update; end; procedure AddTab(PC: TuniPageControl; FrameAba: TFrame; // add frames Titulo: string); var TabSheet :TUniTabSheet; Frame : TUniFrame; Aba :Integer; begin for Aba := 0 to PC.PageCount - 1 do with PC do if trim(Pages[Aba].Caption) = Titulo then begin PC.ActivePageIndex := Aba; Abort; end; TabSheet := TUniTabSheet.Create(PC); TabSheet.PageControl := PC; TabSheet.Caption := ' '+Titulo+' '; TabSheet.Closable := True; Frame := TUniFrameClass(FrameAba).Create(PC); Frame.Align := alClient; Frame.Parent := TabSheet; PC.ActivePage := TabSheet; end; end.
// released under MIT license unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows, Dialogs, StrUtils; var ComPort: array[0..4] of Char = 'COM1'; // COMxx PowPort: Integer = 1; FatalError: Boolean = False; procedure PowerOn(); procedure PowerOff(); function GetPower(): Boolean; function GetVoltage(): String; function GetCurrent(): String; function GetTargetVoltage(): String; function GetMaxCurrent(): String; implementation var ComFile: THandle = INVALID_HANDLE_VALUE; procedure OpenCom(); var Device: array[0..10] of Char; Dcb: TDCB; CommTimeouts : TCommTimeouts; begin FatalError := False; Device := '\\.\' + ComPort; ComFile := CreateFile(Device, GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if ComFile = INVALID_HANDLE_VALUE then begin FatalError := True; ShowMessage('Cannot open COM port'); Exit; end; Dcb := Default(TDCB); if not GetCommState(ComFile, Dcb) then Exit; with Dcb do begin BaudRate := 9600; ByteSize := 8; Parity := NOPARITY; StopBits := ONESTOPBIT; Flags := bm_DCB_fOutX or bm_DCB_fInX; end; if not SetCommState(ComFile, Dcb) then Exit; CommTimeouts := Default(TCommTimeouts); with CommTimeouts do begin ReadIntervalTimeout := MAXDWORD; ReadTotalTimeoutConstant := 0; ReadTotalTimeoutMultiplier := 0; WriteTotalTimeoutConstant := 1; WriteTotalTimeoutMultiplier := 1; end; if not SetCommTimeouts(ComFile, CommTimeouts) then Exit; end; procedure CloseCom(); begin if ComFile <> INVALID_HANDLE_VALUE then begin CloseHandle(ComFile); ComFile := INVALID_HANDLE_VALUE; end; end; procedure SendString(s: string); var BytesWritten: DWORD = 0; begin if ComFile <> INVALID_HANDLE_VALUE then begin s := s + #10; if not WriteFile(ComFile, s[1], Length(s), BytesWritten, nil) then begin ShowMessage('Timeout write'); end; end; end; function ReceiveString: string; var BytesRead: DWORD = 0; r: array[0..9] of Char = ''; begin Result := ''; if ComFile <> INVALID_HANDLE_VALUE then begin if ReadFile(ComFile, r, 10, BytesRead, nil) then begin Result := LeftStr(r, Pos(#13, r) - 1); end else begin ShowMessage('Timeout read'); end; end; end; procedure PowerON(); var s: string; begin s:= 'OP' + Char($30 + PowPort) + ' 1'; OpenCom(); SendString(s); CloseCom(); end; procedure PowerOFF(); var s: string; begin s:= 'OP' + Chr($30 + PowPort) + ' 0'; OpenCom(); SendString(s); CloseCom(); end; function GetPower(): Boolean; var s, r: string; begin s := 'OP' + Chr($30 + PowPort) + '?'; OpenCom(); SendString(s); Sleep(100); r := ReceiveString(); if CompareStr(r, '1') = 0 then begin Result := True; end else begin Result := False; end; CloseCom(); end; function GetVoltage(): String; var s: string; begin s := 'V' + Chr($30 + PowPort) + 'O?'; OpenCom(); SendString(s); Sleep(100); Result := ReceiveString(); CloseCom(); end; function GetCurrent(): String; var s: string; begin s := 'I' + Chr($30 + PowPort) + 'O?'; OpenCom(); SendString(s); Sleep(100); Result := ReceiveString(); CloseCom(); end; function GetTargetVoltage(): String; var s, r: string; begin s := 'V' + Chr($30 + PowPort) + '?'; OpenCom(); SendString(s); Sleep(100); r := ReceiveString(); Result := MidStr(r, 4, Length(r)-3); CloseCom(); end; function GetMaxCurrent(): String; var s, r: string; begin s := 'I' + Chr($30 + PowPort) + '?'; OpenCom(); SendString(s); Sleep(100); r := ReceiveString(); Result := MidStr(r, 4, Length(r)-3); CloseCom(); end; end.
unit Test.CommonRoutines; interface uses Windows, TestFrameWork, GMGlobals; type TCommonRoutinesTest = class(TTestCase) private protected procedure SetUp; override; procedure TearDown; override; published procedure MultiLineSplit; procedure Zip; procedure Md5; procedure Buf_WriteStringMd5; procedure Buf_ReadMd5String; procedure Float_FormatToShow(); procedure ExtractPrefix; procedure EncodedSingle; procedure EnumName; end; implementation uses Math, Classes, SysUtils, GMConst, System.TypInfo; { TCommonRoutinesTest } procedure TCommonRoutinesTest.SetUp; begin inherited; end; procedure TCommonRoutinesTest.TearDown; begin inherited; end; procedure TCommonRoutinesTest.Buf_ReadMd5String; var buf: arrayofByte; example, s: string; begin example := '12 2a 34 4e 56 67 89 00 08 07 06 12 33 34 56 78 aa ab dd'; buf := TextNumbersStringToArray(example); s := lowerCase(ReadMd5String(buf, 1)); Check(s = StringReplace(Copy(example, 3, 16 * 3), ' ', '', [rfReplaceAll])); end; procedure TCommonRoutinesTest.Buf_WriteStringMd5; var buf: array [0..20]of byte; i: int; s: string; begin s := '11111 2222222222222222222 33 44 55 66 77 88 AbdbvfhiruhJJJJJ'; ZeroMemory(@buf[0], 20); Check(WriteStringMd5(buf, 1, s) = 17, 'Len'); Check(buf[0] = 0); for i := 1 to 16 do Check(buf[i] <> 0, 'buf ' + IntToStr(i) + ' = 0'); end; procedure TCommonRoutinesTest.EncodedSingle; {var buf: ArrayOfByte; buf2: array[0..3] of byte; i, j, k, l: int; sl: TStringList; res: double; } begin { buf := TextNumbersStringToArray('1A 2A 43 5E'); sl := TStringList.Create(); for i := 0 to 3 do for j := 0 to 3 do begin if i = j then continue; for k := 0 to 3 do begin if k in [i, j] then continue; for l := 0 to 3 do begin if l in [i, j, k] then continue; buf2[0] := buf[i]; buf2[1] := buf[j]; buf2[2] := buf[k]; buf2[3] := buf[l]; try res := ReadSingleInv(buf2, 0); sl.Add(Format('%d %d %d %d: %s - %g', [i, j, k, l, ArrayToString(buf2, 4, false, true), res])); except end; end; end; end; ShowMessageBox(sl.Text); sl.Free(); } Check(true); end; procedure TCommonRoutinesTest.EnumName; var s: string; begin s := GetEnumName(TypeInfo(T485RequestType), ord(T485RequestType.rqtUBZ_ALARMS)); CheckEquals('rqtUBZ_ALARMS', s); s := T485RequestType.rqtTR101_SP4.ToString(); CheckEquals('rqtTR101_SP4', s); end; procedure TCommonRoutinesTest.ExtractPrefix; var name: string; number: int; begin GetNamePrefix('curve-1', name, number); Check((name = 'curve-') and (number = 1)); GetNamePrefix('curve', name, number); Check((name = 'curve') and (number = -1)); GetNamePrefix('10', name, number); Check((name = '') and (number = 10)); end; procedure TCommonRoutinesTest.Float_FormatToShow; begin Check(FormatFloatToShow(1.1) = '1.1'); Check(FormatFloatToShow(10.1) = '10'); end; procedure TCommonRoutinesTest.Md5; var s: string; begin s := '11111 2222222222222222222 33 44 55 66 77 88 AbdbvfhiruhJJJJJ'; Check(CalcMD5(s) <> s); Check(CalcMD5(s) <> ''); Check(CalcMD5(s) = CalcMD5(s)); Check(CalcMD5(s) <> CalcMD5(s + 'A')); Check(CalcMD5(s) <> CalcMD5(UpperCase(s))); end; procedure TCommonRoutinesTest.MultiLineSplit; begin Check(SplitToThreeLines('') = '', '1'); Check(SplitToThreeLines('11111 222222222') = '11111'#13#10'222222222', '2'); Check(SplitToThreeLines('11111 ,.\ 222222222') = '11111 ,.\'#13#10'222222222', '2_1'); Check(SplitToThreeLines('11111 22222222222222 33') = '11111'#13#10'22222222222222'#13#10'33', '3'); Check(SplitToThreeLines('11111 2222222222222222222 33 44') = '11111'#13#10'2222222222222222222'#13#10'33 44', '4'); Check(SplitToThreeLines('11111 2222222222222222222 33 44 55 66 77 88') = '11111'#13#10'2222222222222222222'#13#10'33 44 55 66 77 88', '5'); Check(SplitToThreeLines('Т1 Давление теплоносителя') = 'Т1'#13#10'Давление'#13#10'теплоносителя', '6'); end; procedure TCommonRoutinesTest.Zip; {var s, s2: TStringStream; ms, ms2: TMemoryStream; i: int;} begin Check(true); { try s := TSTringStream.Create(''); for i := 1 to 1000 do s.WriteString(Chr(Ord('A') + RandomRange(0, 25))); ms := CompressStream(s, '12345'); Check(ms.Size > 0, 'ms.Size > 0'); Check(ms.Size < s.Size, 'Size < s.Size'); ms2 := DeCompressStream(ms); Check(ms2 = nil, 'ms2 password failed'); ms2 := DeCompressStream(ms, '12345'); s2 := TSTringStream.Create(''); ms2.Seek(0, soFromBeginning); s2.CopyFrom(ms2, ms2.Size); Check(s.DataString = s2.DataString, 'DataString'); finally TryFreeAndNil(s); TryFreeAndNil(s2); TryFreeAndNil(ms); TryFreeAndNil(ms2); end;} end; initialization RegisterTest('CommonRoutines', TCommonRoutinesTest.Suite); end.
{$G+} Unit Files; { Files library v1.0 by Maple Leaf, 13 Nov 1996 ------------------------------------------------------------------------- no comments necessary... } interface uses String_s, Dos; Const OwnDirectory : String = ''; OwnFileName : String = ''; OwnPath : String = ''; function OnlyFileName (path : string) : string; { Extract file name from a full path ('????????.???') } function OnlyName (path : string) : string; { Extract only the name from a full path ('????????') } function OnlyExt (path : string) : string; { Extract extension from the name contained in the full path ('.???') } function OnlyDir (path : string) : string; { Extract directory from the full path then add '\' at the end of string (if needs) } function FMatch(file1,file2 : string) : Boolean; { Check if files format match (ex. *.EXE match with RARA.EXE) } function OpenForInput(var f:file; filename:string) : Boolean; { Open file for input . Displays ERRMSG and stops the program if any error is found } function OpenForOutput(var f:file; filename:string) : Boolean; { Open file for output . Displays ERRMSG and stops the program if any error is found } function OpenForAppend(var f:file; filename:string) : Boolean; { Open file for append . Displays ERRMSG and stops the program if any error is found } function CloseFile(var f:file) : Boolean; { Close specified file. If any error is appeared, display ERRORMSG onto the screen and stops the program } function EraseFile(var f:file) : Boolean; { Erase specified file. If any error is appeared, display ERRORMSG onto the screen and stops the program } function ExistFile(path:string) : Boolean; { Checks whether the filename is (or is not) the name of an existing file } procedure MakePath(path:String); { Create a full path } implementation procedure MakePath(path:String); var s:string; k:word; begin {$i-} if path[length(path)]='\' then path:=copy(path,1,length(path)-1); if (pos('\',path)=0) or (path[length(path)]=':') then MkDir(Path) else MakePath(onlydir(Path)); MkDir(path); k:=IoResult; InOutRes:=0; end; function FMatch(file1,file2 : string) : Boolean; function EExpand(s:string):string; var r:string; k:byte; begin r:=''; k:=0; delete(s,1,1); repeat inc(k); if length(s)>=k then begin if s[k]='*' then begin r:=r+Strng(3-length(r),63); k:=3; end else r:=r+s[k]; end else begin r:=r+' '; end; until k=3; EExpand:='.'+UCase(r); end; function EMatch(file1,file2 : string) : Boolean; var q:boolean; k:byte; begin file1:=EExpand(OnlyExt(file1)); file2:=EExpand(OnlyExt(file2)); q:=true; k:=0; repeat inc(k); if not((file1[k]=file2[k]) or (file1[k]='?') or (file2[k]='?')) then q:=false; until not q or (k=4); EMatch:=q; end; function Expand(s:string):string; var r:string; k:byte; begin r:=''; k:=0; repeat inc(k); if length(s)>=k then begin if s[k]='*' then begin r:=r+Strng(8-length(r),63); k:=8; end else r:=r+s[k]; end else begin r:=r+' '; end; until k=8; Expand:=UCase(r); end; function NMatch(file1,file2 : string) : Boolean; var q:boolean; k:byte; begin file1:=Expand(OnlyName(file1)); file2:=Expand(OnlyName(file2)); q:=true; k:=0; repeat inc(k); if not((file1[k]=file2[k]) or (file1[k]='?') or (file2[k]='?')) then q:=false; until not q or (k=8); NMatch:=q; end; begin file1:=OnlyFileName(file1); file2:=OnlyFileName(file2); FMatch:=NMatch(file1,file2) and EMatch(file1,file2); end; function onlyname; var d:dirstr; e:extstr; n:namestr; begin fsplit(path,d,n,e); onlyname:=n; end; function onlydir; var d:dirstr; e:extstr; n:namestr; begin fsplit(path,d,n,e); if d<>'' then if d[length(d)]<>'\' then d:=d+'\'; onlydir:=d; end; function onlyext; var d:dirstr; e:extstr; n:namestr; begin fsplit(path,d,n,e); onlyext:=e; end; function onlyfilename; begin onlyfilename:=onlyname(path)+onlyext(path); end; function OpenForInput; begin {$i-} if ioresult=0 then; inoutres:=0; assign(f,filename); filemode:=0; reset(f,1); OpenForInput:=(IOResult=0); end; function OpenForOutput; begin {$i-} if ioresult=0 then; inoutres:=0; assign(f,filename); filemode:=2; rewrite(f,1); OpenForOutput:=(IOResult=0); end; function OpenForAppend; begin {$i-} if ioresult=0 then; inoutres:=0; assign(f,filename); filemode:=2; reset(f,1); OpenForAppend:=(IOResult=0); end; function CloseFile; begin {$i-} if ioresult=0 then; inoutres:=0; close(f); CloseFile:=(IOResult=0); end; function EraseFile; begin {$i-} if ioresult=0 then; inoutres:=0; erase(f); EraseFile:=(IOResult=0); end; function ExistFile; var r:SearchRec; begin findfirst(path,$3F,r); ExistFile:=DosError=0; end; begin OwnPath:=UCase(ParamStr(0)); OwnDirectory:=OnlyDir(OwnPath); OwnFileName:=OnlyFileName(OwnPath); end.
unit nii_label; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses {$IFNDEF FPC} gziod, {$ELSE} gzio2, {$ENDIF} dialogs,Classes, SysUtils, define_types; procedure createLutLabel (var lut: TLUT; lSaturationFrac: single); procedure LoadLabels(lFileName: string; var lLabels: TStrRA; lOffset,lLength: integer); procedure LoadLabelsTxt(lFileName: string; var lLabels: TStrRA); procedure LoadLabelCustomLut(lFileName: string); implementation uses mainunit; var gLabelLUT : TLUT; function makeRGB(r,g,b: byte): TGLRGBQuad; begin result.rgbRed := r; result.rgbGreen := g; result.rgbBlue := b; result.rgbReserved := 64; end; function defaultLut: TLUT; var lut: TLUT; i: integer; begin lut[0] := makeRGB(0,0,0); lut[0].rgbReserved:= 0; lut[1] := makeRGB(71,46,154); lut[2] := makeRGB(33,78,43); lut[3] := makeRGB(192,199,10); lut[4] := makeRGB(32,79,207); lut[5] := makeRGB(195,89,204); lut[6] := makeRGB(208,41,164); lut[7] := makeRGB(173,208,231); lut[8] := makeRGB(233,135,136); lut[9] := makeRGB(202,20,58); lut[10] := makeRGB(25,154,239); lut[11] := makeRGB(210,35,30); lut[12] := makeRGB(145,21,147); lut[13] := makeRGB(89,43,230); lut[14] := makeRGB(87,230,101); lut[15] := makeRGB(245,113,111); lut[16] := makeRGB(246,191,150); lut[17] := makeRGB(38,147,35); lut[18] := makeRGB(3,208,128); lut[19] := makeRGB(25,37,57); lut[20] := makeRGB(57,28,252); lut[21] := makeRGB(167,27,79); lut[22] := makeRGB(245,86,173); lut[23] := makeRGB(86,203,120); lut[24] := makeRGB(227,25,25); lut[25] := makeRGB(208,209,126); lut[26] := makeRGB(81,148,81); lut[27] := makeRGB(64,187,85); lut[28] := makeRGB(90,139,8); lut[29] := makeRGB(199,111,7); lut[30] := makeRGB(140,48,122); lut[31] := makeRGB(48,102,237); lut[32] := makeRGB(212,76,190); lut[33] := makeRGB(180,110,152); lut[34] := makeRGB(70,106,246); lut[35] := makeRGB(120,130,182); lut[36] := makeRGB(9,37,130); lut[37] := makeRGB(192,160,219); lut[38] := makeRGB(245,34,67); lut[39] := makeRGB(177,222,76); lut[40] := makeRGB(65,90,167); lut[41] := makeRGB(157,165,178); lut[42] := makeRGB(9,245,235); lut[43] := makeRGB(193,222,250); lut[44] := makeRGB(100,102,28); lut[45] := makeRGB(181,47,61); lut[46] := makeRGB(125,19,186); lut[47] := makeRGB(145,130,250); lut[48] := makeRGB(62,4,199); lut[49] := makeRGB(8,232,67); lut[50] := makeRGB(108,137,58); lut[51] := makeRGB(36,211,50); lut[52] := makeRGB(140,240,86); lut[53] := makeRGB(237,11,182); lut[54] := makeRGB(242,140,108); lut[55] := makeRGB(248,21,77); lut[56] := makeRGB(161,42,89); lut[57] := makeRGB(189,22,112); lut[58] := makeRGB(41,241,59); lut[59] := makeRGB(114,61,125); lut[60] := makeRGB(65,99,226); lut[61] := makeRGB(121,115,50); lut[62] := makeRGB(97,199,205); lut[63] := makeRGB(50,166,227); lut[64] := makeRGB(238,114,125); lut[65] := makeRGB(149,190,128); lut[66] := makeRGB(44,204,104); lut[67] := makeRGB(214,60,27); lut[68] := makeRGB(124,233,59); lut[69] := makeRGB(167,66,66); lut[70] := makeRGB(40,115,53); lut[71] := makeRGB(167,230,133); lut[72] := makeRGB(127,125,159); lut[73] := makeRGB(178,103,203); lut[74] := makeRGB(231,203,97); lut[75] := makeRGB(30,125,125); lut[76] := makeRGB(173,13,139); lut[77] := makeRGB(244,176,159); lut[78] := makeRGB(193,94,158); lut[79] := makeRGB(203,131,7); lut[80] := makeRGB(204,39,215); lut[81] := makeRGB(238,198,47); lut[82] := makeRGB(139,167,140); lut[83] := makeRGB(135,124,226); lut[84] := makeRGB(71,67,223); lut[85] := makeRGB(234,175,231); lut[86] := makeRGB(234,254,44); lut[87] := makeRGB(217,1,110); lut[88] := makeRGB(66,15,184); lut[89] := makeRGB(14,198,61); lut[90] := makeRGB(129,62,233); lut[91] := makeRGB(19,237,47); lut[92] := makeRGB(97,159,67); lut[93] := makeRGB(165,31,148); lut[94] := makeRGB(112,218,22); lut[95] := makeRGB(244,58,120); lut[96] := makeRGB(35,244,173); lut[97] := makeRGB(73,47,156); lut[98] := makeRGB(192,61,117); lut[99] := makeRGB(12,67,181); lut[100] := makeRGB(149,94,94); for i := 1 to 100 do lut[i+100] := lut[i]; //fill 101..200 for i := 1 to 55 do lut[i+200] := lut[i]; //fill 201..255 result := lut; end; procedure LoadLabelCustomLut(lFileName: string); var fnm: string; i: integer; lF: textfile; lBuff: bytep0; lFData: file; begin gLabelLut := defaultLut(); fnm := changefileext(lFilename, '.lut'); if not fileexists(fnm) then fnm := ChangeFileExtX(lFilename, '.lut'); if not fileexists(fnm) then exit; if FSize(fnm) <> 768 then exit; assignfile(lFdata,fnm); Filemode := 0; reset(lFdata,1); GetMem( lBuff, 768); BlockRead(lFdata, lBuff^, 768); closefile(lFdata); for i := 0 to 255 do gLabelLut[i] := makeRGB(lBuff[i],lBuff[i+256],lBuff[i+512]); gLabelLut[0].rgbReserved:= 0; freemem(lBuff); end; procedure LoadLabelsCore(lInStr: string; var lLabels: TStrRA); var lIndex,lPass,lMaxIndex,lPos,lLength: integer; lStr1: string; lCh: char; begin lLabels := nil; lLength := length(lInStr); lMaxIndex := -1; for lPass := 1 to 2 do begin lPos := 1; if lPass = 2 then begin if lMaxIndex < 1 then exit; SetLength(lLabels,lMaxIndex+1); for lIndex := 0 to lMaxIndex do lLabels[lIndex] := ''; end; while lPos <= lLength do begin lStr1 := ''; repeat lCh := lInStr[lPos]; inc(lPos); if (lCh >= '0') and (lCh <= '9') then lStr1 := lStr1 + lCh; until (lPos > lLength) or (lCh=kCR) or (lCh=UNIXeoln) or (((lCh=kTab)or (lCh=' ')) and (length(lStr1)>0)); if (length(lStr1) > 0) and (lPos <= lLength) then begin lIndex := strtoint(lStr1); if lPass = 1 then begin if lIndex > lMaxIndex then lMaxIndex := lIndex end else if lIndex >= 0 then begin //pass 2 lStr1 := ''; repeat lCh := lInStr[lPos]; inc(lPos); if (lPos > lLength) or (lCh=kCR) or (lCh=UNIXeoln) {or (lCh=kTab) or (lCh=' ')} then // else lStr1 := lStr1 + lCh; until (lPos > lLength) or (lCh=kCR) or (lCh=UNIXeoln) {or (lCh=kTab)or (lCh=' ')}; lLabels[lIndex] := lStr1; end; //if pass 2 end; //if lStr1>0 end; //while not EOF end; //for each pass end; procedure LoadLabels(lFileName: string; var lLabels: TStrRA; lOffset,lLength: integer); var f : file; // untyped file s : string; // string for reading a file sz: int64; ptr: bytep; begin if ExtGZ(lFilename) then begin if (lLength < 1) then exit; SetLength(s, lLength); ptr := @s[1]; UnGZip (lFileName,ptr, lOffset,lLength); end else begin AssignFile(f, lFileName); FileMode := fmOpenRead; reset(f, 1); if lOffset > 0 then seek(f, lOffset); if (lLength < 1) then sz := FileSize(f)-lOffset else sz := lLength; if (lOffset+sz) > FileSize(f) then exit; SetLength(s, sz); BlockRead(f, s[1], length(s)); CloseFile(f); FileMode := fmOpenReadWrite; end; LoadLabelsCore(s, lLabels); //showmessage(lLabels[1]); end; procedure LoadLabelsTxt(lFileName: string; var lLabels: TStrRA); //filename = 'all.nii' will read 'aal.txt' var lLUTname: string; begin lLabels := nil; //empty current labels lLUTname := changefileext(lFileName,'.txt'); if not Fileexists(lLUTname) then begin lLUTname := ParseFileName(lFileName)+'.txt'; //file.nii.gz -> file.txt if not Fileexists(lLUTname) then exit; end; LoadLabels(lLUTname, lLabels,0,-1); end; procedure desaturateRGBA( var lRGBA: TGLRGBQuad; frac: single); var r,g,b: byte; y: single; begin r := lRGBA.rgbRed; g := lRGBA.rgbGreen; b := lRGBA.rgbBlue; //convert RGB->YUV http://en.wikipedia.org/wiki/YUV y := 0.299 * r + 0.587 * g + 0.114 * b; r := round(y * (1-frac) + r * frac); g := round(y * (1-frac) + g * frac); b := round(y * (1-frac) + b * frac); lRGBA.rgbRed := r; lRGBA.rgbGreen := g; lRGBA.rgbBlue := b; end; procedure createLutLabel (var lut: TLUT; lSaturationFrac: single); //lLUT: 0=gray,1=red,2=green,3=blue var i:integer; begin lut := gLabelLut; (*lut[0] := makeRGB(0,0,0); lut[0].rgbReserved:= 0; lut[1] := makeRGB(71,46,154); lut[2] := makeRGB(33,78,43); lut[3] := makeRGB(192,199,10); lut[4] := makeRGB(32,79,207); lut[5] := makeRGB(195,89,204); lut[6] := makeRGB(208,41,164); lut[7] := makeRGB(173,208,231); lut[8] := makeRGB(233,135,136); lut[9] := makeRGB(202,20,58); lut[10] := makeRGB(25,154,239); lut[11] := makeRGB(210,35,30); lut[12] := makeRGB(145,21,147); lut[13] := makeRGB(89,43,230); lut[14] := makeRGB(87,230,101); lut[15] := makeRGB(245,113,111); lut[16] := makeRGB(246,191,150); lut[17] := makeRGB(38,147,35); lut[18] := makeRGB(3,208,128); lut[19] := makeRGB(25,37,57); lut[20] := makeRGB(57,28,252); lut[21] := makeRGB(167,27,79); lut[22] := makeRGB(245,86,173); lut[23] := makeRGB(86,203,120); lut[24] := makeRGB(227,25,25); lut[25] := makeRGB(208,209,126); lut[26] := makeRGB(81,148,81); lut[27] := makeRGB(64,187,85); lut[28] := makeRGB(90,139,8); lut[29] := makeRGB(199,111,7); lut[30] := makeRGB(140,48,122); lut[31] := makeRGB(48,102,237); lut[32] := makeRGB(212,76,190); lut[33] := makeRGB(180,110,152); lut[34] := makeRGB(70,106,246); lut[35] := makeRGB(120,130,182); lut[36] := makeRGB(9,37,130); lut[37] := makeRGB(192,160,219); lut[38] := makeRGB(245,34,67); lut[39] := makeRGB(177,222,76); lut[40] := makeRGB(65,90,167); lut[41] := makeRGB(157,165,178); lut[42] := makeRGB(9,245,235); lut[43] := makeRGB(193,222,250); lut[44] := makeRGB(100,102,28); lut[45] := makeRGB(181,47,61); lut[46] := makeRGB(125,19,186); lut[47] := makeRGB(145,130,250); lut[48] := makeRGB(62,4,199); lut[49] := makeRGB(8,232,67); lut[50] := makeRGB(108,137,58); lut[51] := makeRGB(36,211,50); lut[52] := makeRGB(140,240,86); lut[53] := makeRGB(237,11,182); lut[54] := makeRGB(242,140,108); lut[55] := makeRGB(248,21,77); lut[56] := makeRGB(161,42,89); lut[57] := makeRGB(189,22,112); lut[58] := makeRGB(41,241,59); lut[59] := makeRGB(114,61,125); lut[60] := makeRGB(65,99,226); lut[61] := makeRGB(121,115,50); lut[62] := makeRGB(97,199,205); lut[63] := makeRGB(50,166,227); lut[64] := makeRGB(238,114,125); lut[65] := makeRGB(149,190,128); lut[66] := makeRGB(44,204,104); lut[67] := makeRGB(214,60,27); lut[68] := makeRGB(124,233,59); lut[69] := makeRGB(167,66,66); lut[70] := makeRGB(40,115,53); lut[71] := makeRGB(167,230,133); lut[72] := makeRGB(127,125,159); lut[73] := makeRGB(178,103,203); lut[74] := makeRGB(231,203,97); lut[75] := makeRGB(30,125,125); lut[76] := makeRGB(173,13,139); lut[77] := makeRGB(244,176,159); lut[78] := makeRGB(193,94,158); lut[79] := makeRGB(203,131,7); lut[80] := makeRGB(204,39,215); lut[81] := makeRGB(238,198,47); lut[82] := makeRGB(139,167,140); lut[83] := makeRGB(135,124,226); lut[84] := makeRGB(71,67,223); lut[85] := makeRGB(234,175,231); lut[86] := makeRGB(234,254,44); lut[87] := makeRGB(217,1,110); lut[88] := makeRGB(66,15,184); lut[89] := makeRGB(14,198,61); lut[90] := makeRGB(129,62,233); lut[91] := makeRGB(19,237,47); lut[92] := makeRGB(97,159,67); lut[93] := makeRGB(165,31,148); lut[94] := makeRGB(112,218,22); lut[95] := makeRGB(244,58,120); lut[96] := makeRGB(35,244,173); lut[97] := makeRGB(73,47,156); lut[98] := makeRGB(192,61,117); lut[99] := makeRGB(12,67,181); lut[100] := makeRGB(149,94,94); for i := 1 to 100 do lut[i+100] := lut[i]; //fill 101..200 for i := 1 to 55 do lut[i+200] := lut[i]; //fill 201..255 *) if (lSaturationFrac < 0) or (lSaturationFrac >= 1.0) then exit; for i := 1 to 255 do desaturateRGBA(lut[i], lSaturationFrac); end; end.
{******************************************************************************* 作者: dmzn@163.com 2013-12-04 描述: 模块业务对象 *******************************************************************************} unit UWorkerBusinessCommand; {$I Link.Inc} interface uses Windows, Classes, Controls, DB, ADODB, SysUtils, UBusinessWorker, UBusinessPacker, UBusinessConst, UMgrDBConn, UMgrParam, ZnMD5, ULibFun, UFormCtrl, USysLoger, USysDB, UMITConst; type TMITDBWorker = class(TBusinessWorkerBase) protected FErrNum: Integer; //错误码 FDBConn: PDBWorker; //数据通道 FDataIn,FDataOut: PBWDataBase; //入参出参 FDataOutNeedUnPack: Boolean; //需要解包 procedure GetInOutData(var nIn,nOut: PBWDataBase); virtual; abstract; //出入参数 function VerifyParamIn(var nData: string): Boolean; virtual; //验证入参 function DoDBWork(var nData: string): Boolean; virtual; abstract; function DoAfterDBWork(var nData: string; nResult: Boolean): Boolean; virtual; //数据业务 public function DoWork(var nData: string): Boolean; override; //执行业务 procedure WriteLog(const nEvent: string); //记录日志 end; TWorkerBusinessCommander = class(TMITDBWorker) private FListA,FListB,FListC, FListD: TStrings; //list FIn: TWorkerBusinessCommand; FOut: TWorkerBusinessCommand; protected procedure GetInOutData(var nIn,nOut: PBWDataBase); override; function DoDBWork(var nData: string): Boolean; override; //base funciton function GetServerNow(var nData: string): Boolean; //获取服务器时间 function GetSerailID(var nData: string): Boolean; //获取串号 function IsSystemExpired(var nData: string): Boolean; //系统是否已过期 function SaveTruckIn(var nData: string): Boolean; //保存车辆进厂记录 public constructor Create; override; destructor destroy; override; //new free function GetFlagStr(const nFlag: Integer): string; override; class function FunctionName: string; override; //base function class function CallMe(const nCmd: Integer; const nData,nExt: string; const nOut: PWorkerBusinessCommand): Boolean; //local call end; implementation //------------------------------------------------------------------------------ //Date: 2012-3-13 //Parm: 如参数护具 //Desc: 获取连接数据库所需的资源 function TMITDBWorker.DoWork(var nData: string): Boolean; begin Result := False; FDBConn := nil; with gParamManager.ActiveParam^ do try FDBConn := gDBConnManager.GetConnection(FDB.FID, FErrNum); if not Assigned(FDBConn) then begin nData := '连接数据库失败(DBConn Is Null).'; Exit; end; if not FDBConn.FConn.Connected then FDBConn.FConn.Connected := True; //conn db FDataOutNeedUnPack := True; GetInOutData(FDataIn, FDataOut); FPacker.UnPackIn(nData, FDataIn); with FDataIn.FVia do begin FUser := gSysParam.FAppFlag; FIP := gSysParam.FLocalIP; FMAC := gSysParam.FLocalMAC; FTime := FWorkTime; FKpLong := FWorkTimeInit; end; {$IFDEF DEBUG} WriteLog('Fun: '+FunctionName+' InData:'+ FPacker.PackIn(FDataIn, False)); {$ENDIF} if not VerifyParamIn(nData) then Exit; //invalid input parameter FPacker.InitData(FDataOut, False, True, False); //init exclude base FDataOut^ := FDataIn^; Result := DoDBWork(nData); //execute worker if Result then begin if FDataOutNeedUnPack then FPacker.UnPackOut(nData, FDataOut); //xxxxx Result := DoAfterDBWork(nData, True); if not Result then Exit; with FDataOut.FVia do FKpLong := GetTickCount - FWorkTimeInit; nData := FPacker.PackOut(FDataOut); {$IFDEF DEBUG} WriteLog('Fun: '+FunctionName+' OutData:'+ FPacker.PackOut(FDataOut, False)); {$ENDIF} end else DoAfterDBWork(nData, False); finally gDBConnManager.ReleaseConnection(FDBConn); end; end; //Date: 2012-3-22 //Parm: 输出数据;结果 //Desc: 数据业务执行完毕后的收尾操作 function TMITDBWorker.DoAfterDBWork(var nData: string; nResult: Boolean): Boolean; begin Result := True; end; //Date: 2012-3-18 //Parm: 入参数据 //Desc: 验证入参数据是否有效 function TMITDBWorker.VerifyParamIn(var nData: string): Boolean; begin Result := True; end; //Desc: 记录nEvent日志 procedure TMITDBWorker.WriteLog(const nEvent: string); begin gSysLoger.AddLog(TMITDBWorker, FunctionName, nEvent); end; //------------------------------------------------------------------------------ class function TWorkerBusinessCommander.FunctionName: string; begin Result := sBus_BusinessCommand; end; constructor TWorkerBusinessCommander.Create; begin FListA := TStringList.Create; FListB := TStringList.Create; FListC := TStringList.Create; FListD := TStringList.Create; inherited; end; destructor TWorkerBusinessCommander.destroy; begin FreeAndNil(FListA); FreeAndNil(FListB); FreeAndNil(FListC); FreeAndNil(FListD); inherited; end; function TWorkerBusinessCommander.GetFlagStr(const nFlag: Integer): string; begin Result := inherited GetFlagStr(nFlag); case nFlag of cWorker_GetPackerName : Result := sBus_BusinessCommand; end; end; procedure TWorkerBusinessCommander.GetInOutData(var nIn,nOut: PBWDataBase); begin nIn := @FIn; nOut := @FOut; FDataOutNeedUnPack := False; end; //Date: 2014-09-15 //Parm: 命令;数据;参数;输出 //Desc: 本地调用业务对象 class function TWorkerBusinessCommander.CallMe(const nCmd: Integer; const nData, nExt: string; const nOut: PWorkerBusinessCommand): Boolean; var nStr: string; nIn: TWorkerBusinessCommand; nPacker: TBusinessPackerBase; nWorker: TBusinessWorkerBase; begin nPacker := nil; nWorker := nil; try nIn.FCommand := nCmd; nIn.FData := nData; nIn.FExtParam := nExt; nPacker := gBusinessPackerManager.LockPacker(sBus_BusinessCommand); nPacker.InitData(@nIn, True, False); //init nStr := nPacker.PackIn(@nIn); nWorker := gBusinessWorkerManager.LockWorker(FunctionName); //get worker Result := nWorker.WorkActive(nStr); if Result then nPacker.UnPackOut(nStr, nOut) else nOut.FData := nStr; finally gBusinessPackerManager.RelasePacker(nPacker); gBusinessWorkerManager.RelaseWorker(nWorker); end; end; //Date: 2012-3-22 //Parm: 输入数据 //Desc: 执行nData业务指令 function TWorkerBusinessCommander.DoDBWork(var nData: string): Boolean; begin with FOut.FBase do begin FResult := True; FErrCode := 'S.00'; FErrDesc := '业务执行成功.'; end; case FIn.FCommand of cBC_ServerNow : Result := GetServerNow(nData); cBC_GetSerialNO : Result := GetSerailID(nData); cBC_IsSystemExpired : Result := IsSystemExpired(nData); cBC_SaveTruckIn : Result := SaveTruckIn(nData); else begin Result := False; nData := '无效的业务代码(Invalid Command).'; end; end; end; //Date: 2014-09-05 //Desc: 获取服务器当前时间 function TWorkerBusinessCommander.GetServerNow(var nData: string): Boolean; var nStr: string; begin nStr := 'Select ' + sField_SQLServer_Now; //sql with gDBConnManager.WorkerQuery(FDBConn, nStr) do begin FOut.FData := DateTime2Str(Fields[0].AsDateTime); Result := True; end; end; //Date: 2012-3-25 //Desc: 按规则生成序列编号 function TWorkerBusinessCommander.GetSerailID(var nData: string): Boolean; var nInt: Integer; nStr,nP,nB: string; begin FDBConn.FConn.BeginTrans; try Result := False; FListA.Text := FIn.FData; //param list nStr := 'Update %s Set B_Base=B_Base+1 ' + 'Where B_Group=''%s'' And B_Object=''%s'''; nStr := Format(nStr, [sTable_SerialBase, FListA.Values['Group'], FListA.Values['Object']]); gDBConnManager.WorkerExec(FDBConn, nStr); nStr := 'Select B_Prefix,B_IDLen,B_Base,B_Date,%s as B_Now From %s ' + 'Where B_Group=''%s'' And B_Object=''%s'''; nStr := Format(nStr, [sField_SQLServer_Now, sTable_SerialBase, FListA.Values['Group'], FListA.Values['Object']]); //xxxxx with gDBConnManager.WorkerQuery(FDBConn, nStr) do begin if RecordCount < 1 then begin nData := '没有[ %s.%s ]的编码配置.'; nData := Format(nData, [FListA.Values['Group'], FListA.Values['Object']]); FDBConn.FConn.RollbackTrans; Exit; end; nP := FieldByName('B_Prefix').AsString; nB := FieldByName('B_Base').AsString; nInt := FieldByName('B_IDLen').AsInteger; if FIn.FExtParam = sFlag_Yes then //按日期编码 begin nStr := Date2Str(FieldByName('B_Date').AsDateTime, False); //old date if (nStr <> Date2Str(FieldByName('B_Now').AsDateTime, False)) and (FieldByName('B_Now').AsDateTime > FieldByName('B_Date').AsDateTime) then begin nStr := 'Update %s Set B_Base=1,B_Date=%s ' + 'Where B_Group=''%s'' And B_Object=''%s'''; nStr := Format(nStr, [sTable_SerialBase, sField_SQLServer_Now, FListA.Values['Group'], FListA.Values['Object']]); gDBConnManager.WorkerExec(FDBConn, nStr); nB := '1'; nStr := Date2Str(FieldByName('B_Now').AsDateTime, False); //now date end; System.Delete(nStr, 1, 2); //yymmdd nInt := nInt - Length(nP) - Length(nStr) - Length(nB); FOut.FData := nP + nStr + StringOfChar('0', nInt) + nB; end else begin nInt := nInt - Length(nP) - Length(nB); nStr := StringOfChar('0', nInt); FOut.FData := nP + nStr + nB; end; end; FDBConn.FConn.CommitTrans; Result := True; except FDBConn.FConn.RollbackTrans; raise; end; end; //Date: 2014-09-05 //Desc: 验证系统是否已过期 function TWorkerBusinessCommander.IsSystemExpired(var nData: string): Boolean; var nStr: string; nDate: TDate; nInt: Integer; begin nDate := Date(); //server now nStr := 'Select D_Value,D_ParamB From %s ' + 'Where D_Name=''%s'' and D_Memo=''%s'''; nStr := Format(nStr, [sTable_SysDict, sFlag_SysParam, sFlag_ValidDate]); with gDBConnManager.WorkerQuery(FDBConn, nStr) do if RecordCount > 0 then begin nStr := 'dmzn_stock_' + Fields[0].AsString; nStr := MD5Print(MD5String(nStr)); if nStr = Fields[1].AsString then nDate := Str2Date(Fields[0].AsString); //xxxxx end; nInt := Trunc(nDate - Date()); Result := nInt > 0; if nInt <= 0 then begin nStr := '系统已过期 %d 天,请联系管理员!!'; nData := Format(nStr, [-nInt]); Exit; end; FOut.FData := IntToStr(nInt); //last days if nInt <= 7 then begin nStr := Format('系统在 %d 天后过期', [nInt]); FOut.FBase.FErrDesc := nStr; FOut.FBase.FErrCode := sFlag_ForceHint; end; end; //Date: 2016/8/7 //Parm: 车牌号码(FIn.FData);磁卡编号(FIn.FExtParam) //Desc: 执行抓拍 function TWorkerBusinessCommander.SaveTruckIn(var nData: string): Boolean; var nStr: string; nOut: TWorkerBusinessCommand; begin FDBConn.FConn.BeginTrans; try FListC.Clear; FListC.Values['Group'] :=sFlag_SerailSYS; FListC.Values['Object'] := sFlag_TruckLog; //to get serial no if not CallMe(cBC_GetSerialNO, FListC.Text, sFlag_Yes, @nOut) then raise Exception.Create(nOut.FData); //xxxxx FOut.FData := nOut.FData; //xxxxx nStr := MakeSQLByStr([SF('T_ID', nOut.FData), SF('T_Truck', FIn.FData), SF('T_InTime', sField_SQLServer_Now, sfVal), SF('T_InMan', FIn.FBase.FFrom.FUser), SF('T_OutTime', sField_SQLServer_Now, sfVal), SF('T_OutMan', FIn.FBase.FFrom.FUser) ], sTable_TruckLog, '', True); gDBConnManager.WorkerExec(FDBConn, nStr); //插入门岗记录 nStr := MakeSQLByStr([SF('T_LastTime', sField_SQLServer_Now, sfVal)], sTable_Truck, SF('T_Truck', FIn.FData), False); gDBConnManager.WorkerExec(FDBConn, nStr); //更新车辆时间 FDBConn.FConn.CommitTrans; Result := True; except FDBConn.FConn.RollbackTrans; raise; end; end; initialization gBusinessWorkerManager.RegisteWorker(TWorkerBusinessCommander, sPlug_ModuleBus); end.
unit uFormMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, Vcl.StdCtrls, MidasLib; type TForm1 = class(TForm) Memo1: TMemo; cdsMain: TClientDataSet; cdsMainID: TIntegerField; cdsMainname: TStringField; procedure FormCreate(Sender: TObject); private procedure FillDataSet; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} type TDataSetEnumerator = class private FDataSet: TDataSet; FCounter: Integer; function GetCurrent: Integer; public constructor Create(ADataSet: TDataSet); function MoveNext: Boolean; property Current: Integer read GetCurrent; end; constructor TDataSetEnumerator.Create(ADataSet: TDataSet); begin inherited Create; FDataSet := ADataSet; FCounter := -1; end; function TDataSetEnumerator.GetCurrent: Integer; begin Result := FCounter; end; function TDataSetEnumerator.MoveNext: Boolean; begin if FCounter < 0 then begin FDataSet.First; FCounter := 0; end else begin FDataSet.Next; Inc(FCounter); end; Result := not FDataSet.EoF; end; type TDataSetHelper = class helper for TDataSet public function GetEnumerator: TDataSetEnumerator; end; function TDataSetHelper.GetEnumerator: TDataSetEnumerator; begin Result := TDataSetEnumerator.Create(Self); end; procedure TForm1.FillDataSet; begin cdsMain.CreateDataSet; cdsMain.Append; cdsMain.FieldByName('id').AsInteger := 1; cdsMain.FieldByName('name').AsString := 'name1'; cdsMain.Post; cdsMain.Append; cdsMain.FieldByName('id').AsInteger := 2; cdsMain.FieldByName('name').AsString := 'name2'; cdsMain.Post; cdsMain.Append; cdsMain.FieldByName('id').AsInteger := 3; cdsMain.FieldByName('name').AsString := 'name3'; cdsMain.Post; end; procedure TForm1.FormCreate(Sender: TObject); var recNo: Integer; begin FillDataSet; for recNo in cdsMain do Memo1.Lines.Add(Format('ID: %s NAME: %s', [ cdsMain.FieldByName('id').AsString, cdsMain.FieldByName('name').AsString ])); end; end.
// Designer : Elisabeth Levana (16518128) // Coder : Elisabeth Levana (16518128) // Tester : Morgen Sudyanto (16518380) unit F10; //tambahJumlahBuku interface uses typeList,tools; procedure tambahJumlahBuku(var lbuku:listbuku); {Buku yang sudah ada ditambahkan jumlahnya dalam file buku.csv} implementation procedure tambahJumlahBuku(var lbuku:listbuku); var i,buku_found,idbuku,jumlahbuku : integer; begin write('Masukkan id buku: '); readln(idbuku); write('Masukkan jumlah buku yang ditambahkan: '); readln(jumlahbuku); for i:=1 to lbuku.neff do begin if (idbuku=lbuku.list[i].id_buku) then begin buku_found:=i; lbuku.list[buku_found].jumlah_buku := lbuku.list[buku_found].jumlah_buku + jumlahbuku; end; end; writeln('Pembaharuan jumlah buku berhasil dilakukan, total buku ',lbuku.list[buku_found].judul_buku,' di perpustakaan menjadi ',lbuku.list[buku_found].jumlah_buku); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC FireMonkey script processing form } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.FMXUI.Script; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, FMX.Controls, FMX.Forms, FMX.Types, FMX.ListBox, FMX.Layouts, FMX.TreeView, FMX.Objects, FMX.StdCtrls, FireDAC.Stan.Intf, FireDAC.UI.Intf, FireDAC.FMXUI.OptsBase; type TfrmFDGUIxFMXfScript = class(TfrmFDGUIxFMXOptsBase) pnlPrcLocation: TPanel; tvPrcLocation: TTreeView; pbPrcMain: TProgressBar; Label1: TLabel; lblTotalSize: TLabel; Label3: TLabel; lblTotalDone: TLabel; Label5: TLabel; lblTotalPctDone: TLabel; Label2: TLabel; lblTotalErrors: TLabel; Timer1: TTimer; pnlPrcOutput: TPanel; lbPrcOutput: TListBox; procedure btnCancelClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); private FModalData: Pointer; FIsRunning: Boolean; FRequestStop: Boolean; procedure InternalHide(AImmediately: Boolean); protected FOnProgress: TFDGUIxScriptProgressEvent; FOnOutput: TFDGUIxScriptOutputEvent; FOnInput: TFDGUIxScriptInputEvent; FOnPause: TFDGUIxScriptPauseEvent; FOptions: TFDGUIxScriptOptions; // IFDGUIxScriptDialog procedure Show; procedure Progress(const AInfoProvider: IFDGUIxScriptDialogInfoProvider); procedure Output(const AStr: String); procedure Input(const APrompt: String; var AResult: String); procedure Pause(const APrompt: String); procedure Hide; end; implementation {$R *.fmx} uses System.UITypes, FMX.Dialogs, FMX.DialogService, {$IFNDEF ANDROID} FMX.DialogService.Sync, {$ELSE} FireDAC.Stan.Error, {$ENDIF} FireDAC.Stan.Consts, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs, FireDAC.Stan.Util, FireDAC.UI; {-------------------------------------------------------------------------------} { TfrmFDGUIxFormsfScript } {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Show; var iDeltaH, iPrcLocH, iPrcOutH: Integer; begin btnCancel.Text := 'Cancel'; Timer1.Enabled := False; tvPrcLocation.Clear; lbPrcOutput.Clear; pbPrcMain.Value := 0; FIsRunning := False; FRequestStop := False; iDeltaH := 0; iPrcLocH := Trunc(pnlPrcLocation.Height); iPrcOutH := Trunc(pnlPrcOutput.Height); if ssCallstack in FOptions then begin if not pnlPrcLocation.Visible then begin pnlPrcLocation.Visible := True; iDeltaH := iPrcLocH; end; end else begin if pnlPrcLocation.Visible then begin iDeltaH := - iPrcLocH; pnlPrcLocation.Visible := False; end; end; if ssConsole in FOptions then begin if not pnlPrcOutput.Visible then begin pnlPrcOutput.Visible := True; iDeltaH := iDeltaH + iPrcOutH; end; end else begin if pnlPrcOutput.Visible then begin iDeltaH := iDeltaH - iPrcOutH; pnlPrcOutput.Visible := False; end; end; Height := Height + iDeltaH; if not Visible then begin FDGUIxFMXCancel; FModalData := FDGUIxFMXBeginModal(Self); inherited Show; end; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Output(const AStr: String); var i: Integer; lOnLastItem: Boolean; s: String; begin if not Visible or not pnlPrcOutput.Visible then Exit; lOnLastItem := lbPrcOutput.ItemIndex = lbPrcOutput.Items.Count - 1; s := AStr; for i := 1 to Length(s) do if FDInSet(s[i], [#13, #10, #9]) then s[i] := ' '; lbPrcOutput.Items.Add(s); if lOnLastItem then begin lbPrcOutput.ItemIndex := lbPrcOutput.Items.Count - 1; i := lbPrcOutput.Items.Count - Trunc(lbPrcOutput.Height / lbPrcOutput.ItemHeight) - 1; if i < 0 then i := 0; lbPrcOutput.ItemIndex := i; end; Application.ProcessMessages; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Input(const APrompt: String; var AResult: String); var LResultArr: array [0..0] of string; begin if APrompt <> '' then Output(APrompt); LResultArr[0] := AResult; {$IFDEF ANDROID} FDCapabilityNotSupported(nil, [S_FD_LGUIx, S_FD_LComp_PScr]) {$ELSE} if TDialogServiceSync.InputQuery('SQL Script', [APrompt], LResultArr) then AResult := LResultArr[0]; Output(LResultArr[0]); Output(''); {$ENDIF} end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Pause(const APrompt: String); var s: String; begin s := APrompt; if s <> '' then Output(s) else s := 'Press OK to continue'; {$IFDEF ANDROID} FDCapabilityNotSupported(nil, [S_FD_LGUIx, S_FD_LComp_PScr]) {$ELSE} TDialogServiceSync.ShowMessage('SQL Script paused.' + C_FD_EOL + s); Output(''); {$ENDIF} end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Progress(const AInfoProvider: IFDGUIxScriptDialogInfoProvider); var oItem, oParent: TTreeViewItem; i: Integer; begin if not Visible then Exit; FIsRunning := AInfoProvider.IsRunning; pbPrcMain.Value := AInfoProvider.TotalPct10Done; if pnlPrcLocation.Visible then begin tvPrcLocation.Clear; oItem := nil; oParent := nil; for i := 0 to AInfoProvider.CallStack.Count - 1 do begin oItem := TTreeViewItem.Create(Self); if oParent = nil then oItem.Parent := tvPrcLocation else oItem.Parent := oParent; oItem.Text := AInfoProvider.CallStack[i]; oParent := oItem; end; if oItem <> nil then oItem.IsSelected := True; end; if AInfoProvider.TotalJobSize <= 0 then lblTotalSize.Text := '<unknown>' else if AInfoProvider.TotalJobSize < 1000 then lblTotalSize.Text := Format('%d bytes', [AInfoProvider.TotalJobSize]) else if AInfoProvider.TotalJobSize < 1000000 then lblTotalSize.Text := FormatFloat('0.000 Kb', AInfoProvider.TotalJobSize / 1000) else lblTotalSize.Text := FormatFloat('0.000 Mb', AInfoProvider.TotalJobSize / 1000000); if AInfoProvider.TotalJobDone < 1000 then lblTotalDone.Text := Format('%d bytes', [AInfoProvider.TotalJobDone]) else if AInfoProvider.TotalJobDone < 1000000 then lblTotalDone.Text := FormatFloat('0.000 Kb', AInfoProvider.TotalJobDone / 1000) else lblTotalDone.Text := FormatFloat('0.000 Mb', AInfoProvider.TotalJobDone / 1000000); if AInfoProvider.TotalJobSize <= 0 then lblTotalPctDone.Text := '<unknown>' else lblTotalPctDone.Text := FormatFloat('0.0 %', AInfoProvider.TotalPct10Done / 10); lblTotalErrors.Text := Format('%d', [AInfoProvider.TotalErrors]); if FRequestStop then AInfoProvider.RequestStop; if Assigned(FOnProgress) then FOnProgress(Self, AInfoProvider as TObject); Application.ProcessMessages; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.InternalHide(AImmediately: Boolean); begin if not Visible then Exit; if not AImmediately then Timer1.Enabled := True else begin tvPrcLocation.Clear; lbPrcOutput.Items.Clear; pbPrcMain.Value := 0; inherited Hide; FDGUIxFMXEndModal(FModalData); end; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Hide; begin if ssAutoHide in FOptions then InternalHide(False) else btnCancel.Text := '&Hide'; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.btnCancelClick(Sender: TObject); begin if FIsRunning and not FRequestStop then begin TDialogService.MessageDialog('Do you really want to cancel script execution ?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], TMsgDlgBtn.mbNo, 0, procedure(const AResult:TModalResult) begin if AResult = mrYes then FRequestStop := True; end); end else if not FIsRunning then InternalHide(True); end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFMXfScript.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; InternalHide(True); end; {-------------------------------------------------------------------------------} { TFDGUIxFMXScriptImpl } {-------------------------------------------------------------------------------} type TFDGUIxFMXScriptImpl = class(TFDGUIxVisualScriptImplBase) private FForm: TfrmFDGUIxFMXfScript; protected // IFDGUIxScriptDialog procedure Show; override; procedure Progress(const AInfoProvider: IFDGUIxScriptDialogInfoProvider); override; procedure Output(const AStr: String; AKind: TFDScriptOutputKind); override; procedure Input(const APrompt: String; var AResult: String); override; procedure Pause(const APrompt: String); override; procedure Hide; override; public destructor Destroy; override; end; {-------------------------------------------------------------------------------} destructor TFDGUIxFMXScriptImpl.Destroy; begin FDFreeAndNil(FForm); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDGUIxFMXScriptImpl.Show; begin if FDGUIxSilent() then Exit; if FForm = nil then FForm := TfrmFDGUIxFMXfScript.Create(nil); FForm.OnShow := FOnShow; FForm.OnHide := FOnHide; FForm.FOnProgress := FOnProgress; FForm.FOnOutput := FOnOutput; FForm.FOnInput := FOnInput; FForm.FOnPause := FOnPause; FForm.FOptions := FOptions; FForm.Caption := FCaption; FForm.Show; Application.ProcessMessages; end; {-------------------------------------------------------------------------------} procedure TFDGUIxFMXScriptImpl.Progress( const AInfoProvider: IFDGUIxScriptDialogInfoProvider); begin if FDGUIxSilent() or (FForm = nil) then Exit; FForm.Progress(AInfoProvider); end; {-------------------------------------------------------------------------------} procedure TFDGUIxFMXScriptImpl.Output(const AStr: String; AKind: TFDScriptOutputKind); begin if FDGUIxSilent() or (FForm = nil) then Exit; FForm.Output(AStr); end; {-------------------------------------------------------------------------------} procedure TFDGUIxFMXScriptImpl.Input(const APrompt: String; var AResult: String); begin AResult := ''; if FDGUIxSilent() or (FForm = nil) then Exit; FForm.Input(APrompt, AResult); end; {-------------------------------------------------------------------------------} procedure TFDGUIxFMXScriptImpl.Pause(const APrompt: String); begin if FDGUIxSilent() or (FForm = nil) then Exit; FForm.Pause(APrompt); end; {-------------------------------------------------------------------------------} procedure TFDGUIxFMXScriptImpl.Hide; begin if (FForm <> nil) and FForm.Visible then FForm.Hide; Application.ProcessMessages; end; {-------------------------------------------------------------------------------} var oFact: TFDFactory; initialization oFact := TFDMultyInstanceFactory.Create(TFDGUIxFMXScriptImpl, IFDGUIxScriptDialog, C_FD_GUIxFMXProvider); finalization FDReleaseFactory(oFact); end.
unit QEMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls,StrUtils, shellapi; type QEClass = class (TObject) private procedure FindExclude( workspace : string; i:integer; Shab: TStringList; iscl: string; FindFile: TSearchRec;FindAll: TSearchRec); //поиск исключений procedure CreateD(dir: string); // Создание новой папки с результатом procedure FindFiles(workspace: string; dir: string; Rasch: TStringList; Folders: TStringList; Shab: TStringList; iscl: string); // поиск файла procedure Change(global: integer;workspace: string;i:integer; dir: string; Folders: TStringList; Shab: TStringList; iscl: string;FindFile: TSearchRec;FindAll: TSearchRec);//Основной метод, где все меняется // procedure Create(); //Конструктор public procedure CreateResult(PathDirShab: string;PathDirSource:string;PathDirResult:string); // Старт end; //var //var // //QE: T//QE; //workspace: string; //путь к файлам // i,global: integer; //счетчик открытых фаловж и global для навигации по папкам // i:integer; //f,f2:TFileStream; //файл //FindFile: TSearchRec;//поиск нужного файла //dir: string;// новая папка //iscl: string ; //исключения // Rasch: TStringList;// массив с расширениями //Folders: TStringList;// массив с папками //FindAll: TSearchRec;//поиск всех файла //Shab: TStringList; //шаблон implementation procedure QEClass.FindExclude(workspace: string;i:integer; Shab: TStringList; iscl: string; FindFile: TSearchRec; FindAll: TSearchRec); //поиск исключений var NewName: String;// новое имя файла text,iscl1,iscl2:string; buf:AnsiChar; endEx,startEx,k,kk:integer; Arr : array of Integer; f,f2:TFileStream; begin try f:=TFileStream.Create(workspace +'\'+FindFile.Name, fmOpenRead); // присваиваю файлы // f2:=TFileStream.Create(dir +'\'+NewName, fmCreate); // присваиваю файлы except // ShowMessage('Ошибка в FindIscl '+inttostr(i)+' файла'); // //QE.Log.Lines.Add ('Ошибка в FindIscl '+ inttostr(i)+' файла'); end; try k:=0;//счетчик f.Seek(0,soFromBeginning); repeat f.Read(buf,sizeof(buf)); //читаем text:=text+buf; until f.Position=f.Size ; endEx:=Pos('contains',text); //находим окончание requires startEx:=Pos( 'requires',text);// и его начало if (Pos('requires',text)<>0) then begin iscl1:= text; // нашли все слова из requires Delete(iscl1,endEx,text.Length); Delete(iscl1,1,startEx+8); endEx:=0; startEx:=-1; while startEx<>0 do begin startEx:=PosEx(',',iscl1,startEx+2); //находим все запятые if startEx<>0 then begin inc(endEx); setlength(arr,endEx); arr[endEx-1]:=startEx; end; end; startEx:=PosEx(';',iscl1,startEx+2); if startEx<>0 then begin inc(endEx); setlength(arr,endEx); arr[endEx-1]:=startEx; end; startEx:=-1; k:=0; while startEx<>0 do begin startEx:=PosEx(shab[0],iscl1,startEx+2); //находим все шаблоны if startEx<>0 then for k:=0 to endEx-1 do begin if (arr[k-1]<=startEx) and(arr[k]>=startEx) then iscl:=iscl+' '+copy(iscl1,arr[k-1],arr[k]-arr[k-1]+1); end; end; end; // //QE.Memo1.Lines.Add ('Исключения '+iscl1); // //QE.Log.Lines.Add ('Исключения '+iscl); except // ShowMessage('Ошибка в поиске исключений '+inttostr(i)+' файла'); // //QE.Log.Lines.Add ('Ошибка в поиске исключений'+inttostr(i)+' файла'); end; f.Free; end; procedure QEClass.Change(global: integer;workspace: string;i:integer; dir: string; Folders: TStringList; Shab: TStringList; iscl: string; FindFile: TSearchRec;FindAll: TSearchRec ); //замена в найденном файле var NewName: String;// новое имя файла text,iscl2:string; buf:AnsiChar; BeforeChange: TStringList; //для возвращения исключений на место AfterChange: TStringList; j,l,k,kk,ll:integer; Arr : array of Integer; Arr2 : array of Integer; //позиции исключений f,f2:TFileStream; begin if (Pos(shab[0],FindFile.Name) <> 0 )then begin NewName:=FindFile.Name; // //QE.Memo1.Lines.Add ('NewName до замены '+NewName); NewName:= StringReplace(NewName,shab[0],shab[1], [rfReplaceAll, rfIgnoreCase]); // //QE.Log.Lines.Add ('NewName после замены '+NewName); end else NewName:=FindFile.Name; try f:=TFileStream.Create(workspace +Folders[global] +'\'+FindFile.Name, fmOpenRead); // присваиваю файлы f2:=TFileStream.Create(dir+ Folders[global] + '\'+NewName, fmCreate); // присваиваю файлы except //ShowMessage('Ошибка в Change 2'+inttostr(i)+' файла'); //QE.Log.Lines.Add ('Ошибка в Change 2'+ inttostr(i)+' файла'); end; try f.Seek(0,soFromBeginning); repeat f.Read(buf,sizeof(buf)); //читаем text:=text+buf; until f.Position=f.Size; text:= StringReplace(text,shab[0],shab[1],[rfReplaceAll,rfIgnoreCase]); //замена по шаблону BeforeChange:=TStringList.Create; AfterChange:=TStringList.Create; BeforeChange.Delimiter := ' ' ; AfterChange.Delimiter := ' ' ; BeforeChange.DelimitedText := iscl ; iscl:= StringReplace(iscl,shab[0],shab[1],[rfReplaceAll,rfIgnoreCase]); AfterChange.DelimitedText := iscl ; for j:=0 to AfterChange.Count-1 do text:= StringReplace(text,AfterChange[j],BeforeChange[j],[rfReplaceAll,rfIgnoreCase]);// возвращаю исключения на место // showmessage (text); f2.Seek(0,soFromBeginning); for j :=0 to text.length do f2.Write(text[j],sizeof(ansichar)) ; //QE.Log.Lines.Add ('Успешная замена '+inttostr(i)); except // ShowMessage('Ошибка в замене '+inttostr(i)+' файла'); //QE.Log.Lines.Add ('Ошибка в замене '+inttostr(i)+' файла'); end; f2.Free; f.Free; end; procedure QEClass.CreateD(dir: string); // создание новой папки с измененными файлами begin try if(CreateDir(dir)) then //QE.Log.Lines.Add ('Директория создана '+ dir) else begin //QE.Log.Lines.Add ('Ошибка в создании директории '+ dir); // showmessage('Ошибка в создании директории '+ dir); abort; end; except //QE.Log.Lines.Add ('Ошибка в создании директории '+ dir); // showmessage('Ошибка в создании директории '+ dir); abort; end; end; procedure QEClass.FindFiles(workspace: string;dir: string; Rasch: TStringList; Folders: TStringList; Shab: TStringList; iscl: string); // поиск файла var global, i, j,kk,l,ll: integer; FindFile: TSearchRec; FindAll: TSearchRec; begin CreateD(dir); i:=0; l:=1; try // поиск подпапок FindFirst(workspace + '\*',faDirectory ,FindFile); if (FindFile.Attr and faDirectory) <> 0 then // если найденный файл - папка begin if ((FindFile.Name <>ExtractFileName(dir)) and (FindFile.Name <>'QE') ) then if (FindFile.Name <> '.') and (FindFile.Name <> '..') then // игнорировать служебные папки begin Folders.Add('\'+FindFile.Name); CreateDir(dir+'\'+FindFile.Name); inc(l); end; end; while FindNext(FindFile)=0 do begin if (FindFile.Attr and faDirectory) <> 0 then // если найденный файл - папка begin if ((FindFile.Name <>ExtractFileName(dir)) and (FindFile.Name <>'QE') ) then if (FindFile.Name <> '.') and (FindFile.Name <> '..') then // игнорировать служебные папки begin Folders.Add('\'+FindFile.Name); CreateDir(dir+'\'+FindFile.Name); inc(l); end; end; end; FindClose(FindFile); except // ShowMessage('Ошибка в поиске папок'); //QE.Log.Lines.Add ('Ошибка в поиске папок'); end; FindClose(FindFile); ll:=0; for kk:=0 to Folders.Count-1 do begin try FindFirst(workspace + Folders[kk]+'\*',faAnyFile,FindAll); if (FindAll.Name <> '.') and (FindAll.Name <> '..') then for j:=0 to Rasch.Count-1 do // не копировать файлы с нужными расширениями begin if ('*'+ExtractFileExt(workspace + Folders[kk]+FindAll.Name )= Rasch[j]) or (ExtractFileExt(workspace + Folders[kk]+FindAll.Name )='.dpk') then inc(ll); end; if ll=0 then CopyFile(PWideChar(workspace+ Folders[kk] + '\'+ FindAll.Name), PWideChar(dir+Folders[kk] +'\'+FindAll.Name), false); ll:=0; // kk:=0; while FindNext(FindALL)=0 do begin // inc(kk); if (FindAll.Name <> '.') and (FindAll.Name <> '..') then for j:=0 to Rasch.Count-1 do // не копировать файлы с нужными расширениями begin if ('*'+ExtractFileExt(workspace + Folders[kk]+FindAll.Name )= Rasch[j]) or (ExtractFileExt(workspace + Folders[kk]+FindAll.Name )='.dpk') then inc(ll); end; if ll=0 then CopyFile(PWideChar(workspace+ Folders[kk] + '\'+ FindAll.Name), PWideChar(dir+Folders[kk] +'\'+FindAll.Name), false); ll:=0; // CopyFile(PWideChar(workspace + Folders[kk]+'\'+ FindAll.Name), PWideChar(dir+Folders[kk] +'\'+FindAll.Name), false); end; // end; FindClose(FindAll); except //QE.Log.Lines.Add ('Ошибка копирования'+inttostr(i)+' '+FindFile.Name); end; end; try // поиск исключений FindFirst(workspace + '\*.dpk',faAnyFile,FindFile); inc(i); if FindFile.Name = '' then begin //QE.Log.Lines.Add ('dpk не найден '); //проверка на файлы под условие iscl:=''; end else begin //QE.Log.Lines.Add ('Найден dpk #'+inttostr(i)+' '+FindFile.Name); FindExclude(workspace, i, Shab, iscl, FindFile, FindAll); FindFile.Name:='' ; end; except //ShowMessage('Ошибка в поиске первого файла'); //QE.Log.Lines.Add ('Ошибка в поиске первого файла'); end; for global:=0 to Folders.Count-1 do for j:=0 to Rasch.Count-1 do begin try FindFirst(workspace + Folders[global] +'\*'+Rasch[j],faAnyFile,FindFile); inc(i); if FindFile.Name = '' then begin //QE.Log.Lines.Add ('Ничего не найдено '); //проверка на файлы под условие // exit; end else begin //QE.Log.Lines.Add ('Найден файл #'+inttostr(i)+' '+FindFile.Name); Change(global, workspace, i, dir, Folders, Shab, iscl, FindFile, FindAll); end; except //ShowMessage('Ошибка в поиске первого файла'); //QE.Log.Lines.Add ('Ошибка в поиске первого файла'); end; try while FindNext(FindFile)=0 do begin inc(i); //QE.Log.Lines.Add ('Найден файл #'+inttostr(i)+' '+FindFile.Name); Change(global, workspace, i, dir, Folders, Shab, iscl, FindFile, FindAll); end; except // ShowMessage('Ошибка в поиске '+ inttostr(i) +' файла'); //QE.Log.Lines.Add ('Ошибка в поиске '+ inttostr(i) +' файла'); end; end; //QE.Log.Lines.Add ('Всего найдено файлов '+ inttostr(i)); //добавляем файлы, которые не меняли в новую папку //for kk:=0 to Folders.Count-1 do // begin FindClose(FindFile); end; procedure QEClass.CreateResult(PathDirShab: string;PathDirSource:string;PathDirResult:string); var text:string; buf:AnsiChar; workspace: string; f:TFileStream; dir: string; Rasch: TStringList; Folders: TStringList; Shab: TStringList; iscl: string; begin workspace:=PathDirShab; // Create; Rasch:= TStringList.Create; Rasch.Add('*.pas'); Rasch.Add('*.dcu'); Rasch.Add('*.pas'); Rasch.Add('*.dfm'); Rasch.Add('*.dproj'); Rasch.Add('*.lng'); Rasch.Add('*.rc'); Shab:= TStringList.Create; Shab.Delimiter := ' ' ; Folders:= TStringList.Create; Folders.Add(''); try if DirectoryExists(workspace) then f:=TFileStream.Create(workspace +'\QE.txt', fmOpenRead) else begin // ShowMessage('Ошибка в пути к шаблону '); //QE.Log.Lines.Add ('Ошибка в пути к шаблону'); abort; end except //ShowMessage('Ошибка в Кнопке '); //QE.Log.Lines.Add ('Ошибка в Кнопке '); end; try f.Seek(0,soFromBeginning); repeat f.Read(buf,sizeof(buf)); //читаем text:=text+buf; until f.Position=f.Size ; except //QE.Log.Lines.Add ('Ошибка в Кнопке '); end; workspace:=PathDirSource; if not DirectoryExists(workspace) then begin // ShowMessage('Ошибка в пути к исходнику '); //QE.Log.Lines.Add ('Ошибка в пути к исходнику'); abort; end ; shab.DelimitedText := text ;// шаблон f.Free; // if PathDirResult.Text='' then // dir:=workspace+'\QE' //else dir:= PathDirResult ; FindFiles(workspace, dir, rasch, Folders, Shab, iscl); // OpenResult.Visible:=true; // OpenResult.Enabled:=true; end; //procedure QEClass.Create(); //var //workspace: string; //text:string; //buf:AnsiChar; //begin //i:=0; //Log.Text:=''; //Shab:= TStringList.Create; //Shab.Delimiter := ' ' ; // Folders:= TStringList.Create; //Folders.Add(''); // if ParamStr(1)='/?' then showhelp; { If ParamStr(1) <> '' then begin workspace:=Paramstr(2); try if DirectoryExists(workspace) then f:=TFileStream.Create(workspace +'\//QE.txt', fmOpenRead) else begin // ShowMessage('Ошибка в пути к шаблону '); ShowHelp; end except //ShowMessage('Ошибка в Кнопке '); //QE.Log.Lines.Add ('Ошибка в Кнопке '); end; try f.Seek(0,soFromBeginning); repeat f.Read(buf,sizeof(buf)); //читаем text:=text+buf; until f.Position=f.Size ; except //QE.Log.Lines.Add ('Ошибка в Кнопке '); end; workspace:=Paramstr(1); if not DirectoryExists(workspace) then begin // ShowMessage('Ошибка в пути к исходнику '); Showhelp; end ; shab.DelimitedText := text ;// шаблон f.Free; dir:=ParamStr(3); FindFiles(workspace); end else //QE.Visible:=false } //end; end.
unit ufrmSysGridDefaultOrderFilter; interface {$I ThsERP.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Vcl.StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.Menus, Vcl.Samples.Spin, Vcl.AppEvnts, Ths.Erp.Helper.Edit, Ths.Erp.Helper.Memo, Ths.Erp.Helper.ComboBox, ufrmBase, ufrmBaseInputDB , Ths.Erp.Database.Table.View.SysViewTables ; type TfrmSysGridDefaultOrderFilter = class(TfrmBaseInputDB) cbbKey: TComboBox; chkIsOrder: TCheckBox; edtValue: TEdit; lblIsOrder: TLabel; lblKey: TLabel; lblValue: TLabel; procedure FormCreate(Sender: TObject);override; procedure RefreshData();override; procedure btnAcceptClick(Sender: TObject);override; private vSysViewTables: TSysViewTables; public destructor Destroy; override; protected published procedure FormDestroy(Sender: TObject); override; end; implementation uses Ths.Erp.Database.Singleton , Ths.Erp.Functions , Ths.Erp.Constants , Ths.Erp.Database.Table.SysGridDefaultOrderFilter ; {$R *.dfm} destructor TfrmSysGridDefaultOrderFilter.Destroy; begin if Assigned(vSysViewTables) then vSysViewTables.Free; inherited; end; procedure TfrmSysGridDefaultOrderFilter.FormCreate(Sender: TObject); begin TSysGridDefaultOrderFilter(Table).Key.SetControlProperty(Table.TableName, cbbKey); TSysGridDefaultOrderFilter(Table).Value.SetControlProperty(Table.TableName, edtValue); inherited; cbbKey.CharCase := ecNormal; edtValue.CharCase := ecNormal; vSysViewTables := TSysViewTables.Create(Table.Database); fillComboBoxData(cbbKey, vSysViewTables, vSysViewTables.TableName1.FieldName, ''); end; procedure TfrmSysGridDefaultOrderFilter.FormDestroy(Sender: TObject); begin inherited; end; procedure TfrmSysGridDefaultOrderFilter.RefreshData(); begin //control içeriğini table class ile doldur cbbKey.ItemIndex := cbbKey.Items.IndexOf(TSysGridDefaultOrderFilter(Table).Key.Value); edtValue.Text := TSysGridDefaultOrderFilter(Table).Value.Value; chkIsOrder.Checked := TSysGridDefaultOrderFilter(Table).IsOrder.Value; end; procedure TfrmSysGridDefaultOrderFilter.btnAcceptClick(Sender: TObject); begin if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then begin if (ValidateInput) then begin if cbbKey.Items.IndexOf(cbbKey.Text) = -1 then raise Exception.Create( TranslateText('Listede olmayan bir Tablo Adı giremezsiniz!', '#1', LngMsgError, LngSystem) ); TSysGridDefaultOrderFilter(Table).Key.Value := cbbKey.Text; TSysGridDefaultOrderFilter(Table).Value.Value := edtValue.Text; TSysGridDefaultOrderFilter(Table).IsOrder.Value := chkIsOrder.Checked; inherited; end; end else inherited; end; end.
unit NtUtils.Profiles; interface uses Winapi.WinNt, NtUtils.Exceptions, NtUtils.Security.Sid; type TProfileInfo = record Flags: Cardinal; FullProfile: LongBool; ProfilePath: String; end; TAppContainerInfo = record Name: String; DisplayName: String; IsChild: Boolean; ParentName: String; end; { User profiles } // Enumerate existing profiles on the system function UnvxEnumerateProfiles(out Profiles: TArray<ISid>): TNtxStatus; // Enumerate loaded profiles on the system function UnvxEnumerateLoadedProfiles(out Profiles: TArray<ISid>): TNtxStatus; // Query profile information function UnvxQueryProfile(Sid: PSid; out Info: TProfileInfo): TNtxStatus; { AppContainer profiles } // Create an AppContainer profile function UnvxCreateAppContainer(out Sid: ISid; AppContainerName, DisplayName, Description: String; Capabilities: TArray<TGroup> = nil): TNtxStatus; // Delete an AppContainer profile function UnvxDeleteAppContainer(AppContainerName: String): TNtxStatus; // Query AppContainer information function UnvxQueryAppContainer(UserSid: String; AppContainerSid: PSid; out Info: TAppContainerInfo): TNtxStatus; // Query AppContainer folder location function UnvxQueryFolderAppContainer(AppContainerSid: String; out Path: String): TNtxStatus; // Enumerate AppContainer profiles function UnvxEnumerateAppContainers(UserSid: String; out AppContainers: TArray<ISid>): TNtxStatus; // Enumerate children of AppContainer profile function UnvxEnumerateChildrenAppContainer(UserSid, AppContainerSid: String; out Children: TArray<ISid>): TNtxStatus; implementation uses Ntapi.ntrtl, Winapi.UserEnv, Ntapi.ntstatus, Ntapi.ntregapi, NtUtils.Registry, NtUtils.Ldr, NtUtils.Objects, NtUtils.Security.AppContainer, DelphiUtils.Arrays; const PROFILE_PATH = REG_PATH_MACHINE + '\SOFTWARE\Microsoft\Windows NT\' + 'CurrentVersion\ProfileList'; APPCONTAINER_MAPPING_PATH = '\Software\Classes\Local Settings\Software\' + 'Microsoft\Windows\CurrentVersion\AppContainer\Mappings'; APPCONTAINER_NAME = 'Moniker'; APPCONTAINER_PARENT_NAME = 'ParentMoniker'; APPCONTAINER_DISPLAY_NAME = 'DisplayName'; APPCONTAINER_CHILDREN = '\Children'; { User profiles } function UnvxEnumerateProfiles(out Profiles: TArray<ISid>): TNtxStatus; var hxKey: IHandle; ProfileStrings: TArray<String>; begin // Lookup the profile list in the registry Result := NtxOpenKey(hxKey, PROFILE_PATH, KEY_ENUMERATE_SUB_KEYS); // Each sub-key is a profile SID if Result.IsSuccess then Result := NtxEnumerateSubKeys(hxKey.Handle, ProfileStrings); // Convert strings to SIDs ignoring irrelevant entries if Result.IsSuccess then TArrayHelper.Convert<String, ISid>(ProfileStrings, Profiles, RtlxStringToSidConverter); end; function UnvxEnumerateLoadedProfiles(out Profiles: TArray<ISid>): TNtxStatus; var hxKey: IHandle; ProfileStrings: TArray<String>; begin // Each loaded profile is a sub-key in HKU Result := NtxOpenKey(hxKey, REG_PATH_USER, KEY_ENUMERATE_SUB_KEYS); if Result.IsSuccess then Result := NtxEnumerateSubKeys(hxKey.Handle, ProfileStrings); // Convert strings to SIDs ignoring irrelevant entries if Result.IsSuccess then TArrayHelper.Convert<String, ISid>(ProfileStrings, Profiles, RtlxStringToSidConverter); end; function UnvxQueryProfile(Sid: PSid; out Info: TProfileInfo): TNtxStatus; var hxKey: IHandle; begin // Retrieve the information from the registry Result := NtxOpenKey(hxKey, PROFILE_PATH + '\' + RtlxConvertSidToString(Sid), KEY_QUERY_VALUE); if not Result.IsSuccess then Exit; FillChar(Result, SizeOf(Result), 0); // The only necessary value Result := NtxQueryStringValueKey(hxKey.Handle, 'ProfileImagePath', Info.ProfilePath); if Result.IsSuccess then begin NtxQueryDwordValueKey(hxKey.Handle, 'Flags', Info.Flags); NtxQueryDwordValueKey(hxKey.Handle, 'FullProfile', PCardinal(PLongBool( @Info.FullProfile))^); end; end; { AppContainer profiles } function UnvxCreateAppContainer(out Sid: ISid; AppContainerName, DisplayName, Description: String; Capabilities: TArray<TGroup>): TNtxStatus; var CapArray: TArray<TSidAndAttributes>; i: Integer; Buffer: PSid; begin Result := LdrxCheckModuleDelayedImport(userenv, 'CreateAppContainerProfile'); if not Result.IsSuccess then Exit; SetLength(CapArray, Length(Capabilities)); for i := 0 to High(CapArray) do begin CapArray[i].Sid := Capabilities[i].SecurityIdentifier.Sid; CapArray[i].Attributes := Capabilities[i].Attributes; end; Result.Location := 'CreateAppContainerProfile'; Result.HResult := CreateAppContainerProfile(PWideChar(AppContainerName), PWideChar(DisplayName), PWideChar(Description), CapArray, Length(CapArray), Buffer); if Result.IsSuccess then begin Sid := TSid.CreateCopy(Buffer); RtlFreeSid(Buffer); end; end; function UnvxDeleteAppContainer(AppContainerName: String): TNtxStatus; begin Result := LdrxCheckModuleDelayedImport(userenv, 'DeleteAppContainerProfile'); if not Result.IsSuccess then Exit; Result.Location := 'DeleteAppContainerProfile'; Result.HResult := DeleteAppContainerProfile(PWideChar(AppContainerName)); end; function UnvxQueryFolderAppContainer(AppContainerSid: String; out Path: String): TNtxStatus; var Buffer: PWideChar; begin Result := LdrxCheckModuleDelayedImport(userenv, 'GetAppContainerFolderPath'); if not Result.IsSuccess then Exit; Result.Location := 'GetAppContainerFolderPath'; Result.HResult := GetAppContainerFolderPath(PWideChar(AppContainerSid), Buffer); if Result.IsSuccess then begin Path := String(Buffer); CoTaskMemFree(Buffer); end; end; function RtlxpGetAppContainerRegPath(UserSid, AppContainerSid: String): String; begin Result := REG_PATH_USER + '\' + UserSid + APPCONTAINER_MAPPING_PATH + '\' + AppContainerSid; end; function UnvxQueryAppContainer(UserSid: String; AppContainerSid: PSid; out Info: TAppContainerInfo): TNtxStatus; var hxKey: IHandle; Parent: ISid; begin // Read the AppContainer profile information from the registry // The path depends on whether it is a parent or a child Info.IsChild := (RtlxGetAppContainerType(AppContainerSid) = ChildAppContainerSidType); if Info.IsChild then begin Result := RtlxGetAppContainerParent(AppContainerSid, Parent); // For child AppContainers the path contains both a user and a parent: // HKU\<user>\...\<parent>\Children\<app-container> if Result.IsSuccess then Result := NtxOpenKey(hxKey, RtlxpGetAppContainerRegPath(UserSid, RtlxConvertSidToString(Parent.Sid)) + APPCONTAINER_CHILDREN + '\' + RtlxConvertSidToString(AppContainerSid), KEY_QUERY_VALUE); // Parent's name (aka parent moniker) if Result.IsSuccess then Result := NtxQueryStringValueKey(hxKey.Handle, APPCONTAINER_PARENT_NAME, Info.ParentName); end else Result := NtxOpenKey(hxKey, RtlxpGetAppContainerRegPath(UserSid, RtlxConvertSidToString(AppContainerSid)), KEY_QUERY_VALUE); if not Result.IsSuccess then Exit; // Name (aka moniker) Result := NtxQueryStringValueKey(hxKey.Handle, APPCONTAINER_NAME, Info.Name); if not Result.IsSuccess then Exit; // DisplayName Result := NtxQueryStringValueKey(hxKey.Handle, APPCONTAINER_DISPLAY_NAME, Info.DisplayName); end; function UnvxEnumerateAppContainers(UserSid: String; out AppContainers: TArray<ISid>): TNtxStatus; var hxKey: IHandle; AppContainerStrings: TArray<String>; begin // All registered AppContainers are stored as registry keys Result := NtxOpenKey(hxKey, REG_PATH_USER + '\' + UserSid + APPCONTAINER_MAPPING_PATH, KEY_ENUMERATE_SUB_KEYS); if Result.IsSuccess then Result := NtxEnumerateSubKeys(hxKey.Handle, AppContainerStrings); // Convert strings to SIDs ignoring irrelevant entries if Result.IsSuccess then TArrayHelper.Convert<String, ISid>(AppContainerStrings, AppContainers, RtlxStringToSidConverter); end; function UnvxEnumerateChildrenAppContainer(UserSid, AppContainerSid: String; out Children: TArray<ISid>): TNtxStatus; var hxKey: IHandle; ChildrenStrings: TArray<String>; begin // All registered children are stored as subkeys of a parent profile Result := NtxOpenKey(hxKey, RtlxpGetAppContainerRegPath(UserSid, AppContainerSid) + APPCONTAINER_CHILDREN, KEY_ENUMERATE_SUB_KEYS); if Result.IsSuccess then Result := NtxEnumerateSubKeys(hxKey.Handle, ChildrenStrings); // Convert strings to SIDs ignoring irrelevant entries if Result.IsSuccess then TArrayHelper.Convert<String, ISid>(ChildrenStrings, Children, RtlxStringToSidConverter); end; end.
{ @html(<b>) TCP/IP Client Connection @html(</b>) - Copyright (c) Danijel Tkalcec @html(<br><br>) Introducing the @html(<b>) @Link(TRtcTcpClient) @html(</b>) component: @html(<br>) Client connection component for pure TCP/IP communication using raw data. There will be no special pre-set formatting when sending or receiving data through this client connection component. } unit rtcTcpCli; {$INCLUDE rtcDefs.inc} interface uses rtcConn; type { @Abstract(Client Connection component for TCP/IP communication using raw data) There is no predefined formatting when sending and receiving data through @Link(TRtcTcpClient) connection component. Everything that comes through the connection, will be received exactly as it was sent (byte-wise). The same goes for sending data out through the component. This makes the component universal, so it can be used to write virtualy any TCP/IP Client application. @html(<br><br>) Properties to check first: @html(<br>) @Link(TRtcConnection.ServerAddr) - Address to connect to @html(<br>) @Link(TRtcConnection.ServerPort) - Port to connect to @html(<br><br>) Methods to check first: @html(<br>) @Link(TRtcClient.Connect) - Connect to server @html(<br>) @Link(TRtcConnection.Write) - Write data (send to server) @html(<br>) @Link(TRtcConnection.Read) - Read data (get from server) @html(<br>) @Link(TRtcConnection.Disconnect) - Disconnect from server @html(<br><br>) Events to check first: @html(<br>) @Link(TRtcConnection.OnConnect) - Connected to server @html(<br>) @Link(TRtcConnection.OnDataSent) - Data sent (buffer now empty) @html(<br>) @Link(TRtcConnection.OnDataReceived) - Data received (need to read) @html(<br>) @Link(TRtcConnection.OnDisconnect) - Disconnected from server @html(<br><br>) @html(<b>function Read:string;</b><br>) Use Read to get all the data that is waiting for you in this connection component's receiving buffer. A call to Read will also clear the buffer, which means that you have to store the string received from Read, before you start to process it. @html(<br><br>) Keep in mind that when using TCP/IP, data is received as a stream (or rather peaces of it), without special end-marks for each package sent or received. This means that the server could have sent a big chunk of data in just one call, but the client will receive several smaller packages of different sizes. It could also happen that server sends multiple smaller packages, which your client receives as one big package. A combination of those circumstances is also possible. @html(<br><br>) So, before you start processing the data you receive, make sure that you have received everything you need. You could define a buffer for storing temporary data, so you can react on multiple OnDataReceived events and put all data received inside your buffer, before you actually start processing the data. @html(<br><br>) IMPORTANT: ONLY CALL Read from OnDataReceived event handler. OnDataReceived will be automatically triggered by the connection component, every time new data becomes available. @html(<br><br>) @html(<b>procedure Write(const s:string='');</b><br>) Use Write to send data out. Write will not block your code execution, it will only put the string into sending buffer and return immediatelly. @html(<br><br>) Keep in mind that all the data you put into the sending buffer will remain there until it was sent out or a connection was closed. To avoid filling your buffer with data that will not be sent out for some time, try sending a small peace at a time and then react on the @Link(TRtcConnection.OnDataSent) event to continue and send the next one. Packages you send out at once shouldn't be larger that 64 KB. @html(<br><br>) Check @Link(TRtcClient) and @Link(TRtcConnection) for more info. } TRtcTcpClient = class(TRtcClient) protected { Creates a new connection provider @exclude} function CreateProvider:TObject; override; public { Use this class function to create a new TRtcTcp_Client component at runtime. DO NOT USE the Create constructor. } class function New:TRtcTcpClient; published { This event will be triggered every time this connection component's buffer is completely empty and the other side has just become ready to accept new data. It is good to wait for this event before starting to send data out, even though you can start sending data directly from the @Link(TRtcConnection.OnConnect) event. @html(<br><br>) By responding to this event and sending the data only after it was triggered, you avoid keeping the data in the send buffer, especially if the data you are sending is being read from a file on disk, which wouldn't occupy any memory until loaded. } property OnReadyToSend; { This event will be triggered every time a chunk of your data prepared for sending has just been sent out. To know exactly how much of it is on the way, use the @Link(TRtcConnection.DataOut) property. @html(<br><br>) NOTE: Even though data has been sent out, it doesn't mean that the other side already received it. It could also be that connection will break before this package reaches the other end. } property OnDataOut; { This event will be triggered when all data prepared for sending has been sent out and the sending buffer has become empty again. @html(<br><br>) When sending large data blocks, try slicing them in small chunks, sending a chunk at a time and responding to this event to prepare and send the next chunk. This will keep your memory needs low. } property OnDataSent; { When this event triggers, it means that the other side has sent you some data and you can now read it. Check the connection component's description to see which properties and methods you can use to read the data received. } property OnDataReceived; end; implementation uses SysUtils, rtcWSockCliProv; // WSocket Client Provider type TMyProvider = TRtcWSockClientProvider; class function TRtcTcpClient.New: TRtcTcpClient; begin Result:=Create(nil); end; function TRtcTcpClient.CreateProvider:TObject; begin if not assigned(Con) then begin Con:=TMyProvider.Create; TMyProvider(Con).Proto:=proTCP; SetTriggers; end; Result:=Con; end; end.
unit StoreHouseForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DictonaryForm, RootForm, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, System.Actions, Vcl.ActnList, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, StoreHouseInfoView; type TfrmStoreHouse = class(TfrmDictonary) private FViewStorehouseInfo: TViewStorehouseInfo; { Private declarations } protected procedure ApplyUpdates; override; procedure CancelUpdates; override; procedure ClearFormVariable; override; function HaveAnyChanges: Boolean; override; public constructor Create(AOwner: TComponent); override; property ViewStorehouseInfo: TViewStorehouseInfo read FViewStorehouseInfo; { Public declarations } end; implementation {$R *.dfm} constructor TfrmStoreHouse.Create(AOwner: TComponent); begin inherited; FViewStorehouseInfo := TViewStorehouseInfo.Create(Self); FViewStorehouseInfo.Parent := Panel1; FViewStorehouseInfo.Align := alClient; end; procedure TfrmStoreHouse.ApplyUpdates; begin ViewStorehouseInfo.qStoreHouseList.ApplyUpdates; end; procedure TfrmStoreHouse.CancelUpdates; begin ViewStorehouseInfo.qStoreHouseList.CancelUpdates; end; procedure TfrmStoreHouse.ClearFormVariable; begin inherited; end; function TfrmStoreHouse.HaveAnyChanges: Boolean; begin Result := ViewStorehouseInfo.qStoreHouseList.HaveAnyChanges; end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.BindSource; interface uses System.Classes, System.SysUtils, System.JSON, System.Generics.Collections, REST.JSON, REST.Backend.Providers, Data.Bind.ObjectScope, REST.BindSource, Data.Bind.Components; type // Base class for provider components (with livebindings support) TBackendBindSourceComponent = class(TBaseObjectBindSourceDelegate, IBackendServiceComponent) private FProvider: IBackendProvider; procedure SetProvider(const Value: IBackendProvider); function GetProvider: IBackendProvider; // IBackendServiceComponent protected procedure ProviderChanged; virtual; function GetServiceIID: TGUID; virtual; abstract; // IBackendServiceComponent function CreateService(const AProvider: IBackendProvider): IBackendService; procedure ClearProvider; virtual; procedure UpdateProvider(const AProvider: IBackendProvider); virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; property ServiceIID: TGUID read GetServiceIID; property Provider: IBackendProvider read FProvider write SetProvider; end; TBackendBindSourceComponent<TI: IBackendService; T: Class> = class(TBackendBindSourceComponent) public type TExecuteProc = TProc<T>; TExecuteEvent = procedure(Sender: TObject; AApi: T) of object; TAPIThread = TBackendAPIThread<T>; private FBackendService: TI; FBackendServiceAPI: T; FAPIThread: TAPIThread; function CreateBackendService(const AProvider: IBackendProvider): TI; procedure SetAPIThread(const Value: TAPIThread); protected function GetBackendServiceAPI: T; procedure ClearProvider; override; function GetBackendService: TI; function GetServiceIID: TGUID; override; procedure UpdateProvider(const AValue: IBackendProvider); override; function InternalCreateBackendServiceAPI: T; virtual; abstract; function InternalCreateIndependentBackendServiceAPI: T; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property APIThread: TAPIThread read FAPIThread write SetAPIThread; end; TBackendBindSourceComponentAuth<TI: IBackendService; T: Class> = class(TBackendBindSourceComponent<TI, T>) private FAuth: IBackendAuthReg; FAuthAccess: IAuthAccess; procedure SetAuth(const Value: IBackendAuthReg); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; function CreateAuthAccess: IAuthAccess; virtual; public destructor Destroy; override; property Auth: IBackendAuthReg read FAuth write SetAuth; end; implementation uses System.TypInfo, REST.Utils, REST.Backend.Consts, REST.Backend.Exception; { TBackendBindSourceComponent<TService, TApi> } destructor TBackendBindSourceComponent<TI, T>.Destroy; begin FAPIThread.Free; ClearProvider; inherited; end; constructor TBackendBindSourceComponent<TI, T>.Create(AOwner: TComponent); begin inherited; FAPIThread := TAPIThread.Create; FAPIThread.OnCreateAPI := function: T begin Result := InternalCreateIndependentBackendServiceAPI; end; end; function TBackendBindSourceComponent<TI, T>.CreateBackendService( const AProvider: IBackendProvider): TI; begin Result := TI(inherited CreateService(AProvider)); Assert(Supports(Result, ServiceIID)); end; function TBackendBindSourceComponent<TI, T>.GetBackendServiceAPI: T; begin if FBackendServiceAPI = nil then begin if FBackendService <> nil then FBackendServiceAPI := InternalCreateBackendServiceAPI // TBackendQueryApi.Create(FService.CreateQueryApi) else raise Exception.CreateFmt(sNoBackendService, [Self.ClassName]); end; Result := FBackendServiceAPI; end; function TBackendBindSourceComponent<TI, T>.GetBackendService: TI; begin Result := FBackendService; end; function TBackendBindSourceComponent<TI, T>.GetServiceIID: TGUID; begin Result := GetTypeData(TypeInfo(TI)).Guid; end; function TBackendBindSourceComponent<TI, T>.InternalCreateIndependentBackendServiceAPI: T; begin raise ENotSupportedException.Create('InternalCreateIndependentBackendServiceAPI'); // Do not localize end; procedure TBackendBindSourceComponent<TI, T>.SetAPIThread( const Value: TAPIThread); begin FAPIThread.Assign(Value); end; procedure TBackendBindSourceComponent<TI, T>.ClearProvider; begin inherited; FBackendService := nil; FreeAndNil(FBackendServiceAPI); end; procedure TBackendBindSourceComponent<TI, T>.UpdateProvider(const AValue: IBackendProvider); begin ClearProvider; if AValue <> nil then FBackendService := CreateBackendService(AValue); // May raise an exception end; procedure TBackendBindSourceComponent.SetProvider( const Value: IBackendProvider); begin if FProvider <> Value then begin if FProvider <> nil then begin if FProvider is TComponent then TComponent(FProvider).RemoveFreeNotification(Self); end; UpdateProvider(Value); FProvider := Value; if FProvider <> nil then begin if FProvider is TComponent then TComponent(FProvider).FreeNotification(Self); end; ProviderChanged; end; end; procedure TBackendBindSourceComponent.ClearProvider; begin FProvider := nil; end; constructor TBackendBindSourceComponent.Create(AOwner: TComponent); var LProvider: IBackendProvider; begin inherited; // Find a default provider if not Supports(AOwner, IBackendProvider, LProvider) then if csDesigning in ComponentState then LProvider := TRESTFindDefaultComponent.FindDefaultIntfT<IBackendProvider>(Self); if LProvider <> nil then if TBackendProviders.Instance.FindService(LProvider.ProviderID, ServiceIID) <> nil then // Valid provider Provider := LProvider; end; function TBackendBindSourceComponent.CreateService( const AProvider: IBackendProvider): IBackendService; var LService: TBackendProviders.TService; begin LService := TBackendProviders.Instance.FindService(AProvider.ProviderID, ServiceIID); if LService <> nil then begin Result := LService.FactoryProc(AProvider, ServiceIID) as IBackendService; end else raise EBackendServiceError.CreateFmt(sServiceNotSupportedByProvider, [AProvider.ProviderID]); end; function TBackendBindSourceComponent.GetProvider: IBackendProvider; begin Result := FProvider; end; procedure TBackendBindSourceComponent.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; /// clean up component-references if (Operation = opRemove) then begin if (FProvider is TComponent) and (TComponent(FProvider) = AComponent) then ClearProvider; end; end; procedure TBackendBindSourceComponent.ProviderChanged; begin // end; { TBackendBindSourceComponentAuth<TI, T> } function TBackendBindSourceComponentAuth<TI, T>.CreateAuthAccess: IAuthAccess; begin Result := nil; end; destructor TBackendBindSourceComponentAuth<TI, T>.Destroy; begin Auth := nil; // Unregister for auth inherited; end; procedure TBackendBindSourceComponentAuth<TI, T>.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; /// clean up component-references if (Operation = opRemove) then begin if (FAuth is TComponent) and (TComponent(FAuth) = AComponent) then Auth := nil; end; end; procedure TBackendBindSourceComponentAuth<TI, T>.SetAuth( const Value: IBackendAuthReg); begin if FAuth <> Value then begin if FAuth <> nil then begin if FAuth is TComponent then TComponent(FAuth).RemoveFreeNotification(Self); if FAuthAccess <> nil then try FAuth.UnregisterForAuth(FAuthAccess); finally FAuthAccess := nil; end; end; FAuth := Value; if FAuth <> nil then begin if FAuth is TComponent then TComponent(FAuth).FreeNotification(Self); FAuthAccess := CreateAuthAccess; if FAuthAccess <> nil then FAuth.RegisterForAuth(FAuthAccess); end; end; end; end.
unit UserAuthContentForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, ToolWin, ExtCtrls, StdCtrls, Grids, DBGrids, adodb, db, clsDataConnect, clsGlobal, clsUserAuthContentControl, clsCommFunction, clsClientDtSet; type TState = (dsInsert, dsEdit, dsBrowse, dsCopyFunction); type TfrmUserAuthContent = class(TForm) ToolBar: TToolBar; tbAdd: TToolButton; tbEdit: TToolButton; tbDelete: TToolButton; ilUserAuthContent: TImageList; gbxUserAuthContent1: TGroupBox; gbxUserAuthContent2: TGroupBox; Panel1: TPanel; lblFilterAID: TLabel; cbAID: TComboBox; lblFilterAName: TLabel; cbAName: TComboBox; btnFilter: TButton; ToolButton1: TToolButton; tbCopyFunction: TButton; Panel2: TPanel; gbxAuth: TGroupBox; dbgUserAuthContent1: TDBGrid; Panel3: TPanel; Panel4: TPanel; gbxFunctionList: TGroupBox; dbgUserAuthContent2: TDBGrid; Label1: TLabel; Panel5: TPanel; GroupBox1: TGroupBox; lblID: TLabel; edtID: TEdit; lblName: TLabel; edtName: TEdit; lblDesc: TLabel; edtDesc: TEdit; GroupBox2: TGroupBox; lbSource: TListBox; Panel6: TPanel; Panel7: TPanel; lbDest: TListBox; lblSelectedFunctionList: TLabel; Panel8: TPanel; btnTransAll: TButton; btnTransOne: TButton; btnReverseOne: TButton; btnReverseAll: TButton; btnDone: TButton; btnCancel: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tbAddClick(Sender: TObject); procedure tbEditClick(Sender: TObject); procedure tbDeleteClick(Sender: TObject); procedure btnDoneClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure dbgUserAuthContent1CellClick(Column: TColumn); procedure dbgUserAuthContent1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbgUserAuthContent1DblClick(Sender: TObject); procedure edtIDKeyPress(Sender: TObject; var Key: Char); procedure edtNameKeyPress(Sender: TObject; var Key: Char); procedure btnTransAllClick(Sender: TObject); procedure btnReverseAllClick(Sender: TObject); procedure btnTransOneClick(Sender: TObject); procedure btnReverseOneClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnFilterClick(Sender: TObject); procedure tbCopyFunctionClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure uFillID; procedure uFillName; { Private declarations } public { Public declarations } adsUserAuthContent1: TClientDtSet; adsUserAuthContent2: TClientDtSet; dsUserAuthContent1: TDataSource; dsUserAuthContent2: TDataSource; ctlUserAuthContentControl: TUserAuthContentControl; State: TState; procedure showUserAuthContent; procedure fillin; procedure StateChange; procedure initValue; function uiDataInspection: Boolean; procedure fillRightGrid; procedure ShowGridLabel; end; TFormFreeCallBack = procedure(ACaseName: string = 'MESAuthorization'); stdcall; resourcestring rsAuthContentAddNew = 'Add New'; rsAuthContentEdit = 'Edit'; rsAuthContentBrowse = ''; rsAuthFuncName = 'Function Name'; rsShowBuilder = 'Builder'; rsShowBdate = 'Build Date'; rsShowReviser = 'Reviser'; rsShowRDate = 'Revise Date'; rsAuthid = 'ID'; rsAuthName = 'Name'; rsAuthDesc = 'Description'; rsUserAuthContentCopy = '無資料可復製!'; var frmUserAuthContent: TfrmUserAuthContent; FormFreeCallBack: TFormFreeCallBack; iCallType: integer = 0; //默認0﹕為常規調用﹐為1﹕則為DLL調用 implementation {$R *.dfm} { TfrmFlexField } procedure TfrmUserAuthContent.fillin; var adsTemp: TClientDtSet; strSQL: string; i, j: Integer; begin with adsUserAuthContent1 do begin if Active and (RecordCount > 0) then begin if FieldValues['FID'] <> null then edtID.Text := FieldByName('FID').AsString else edtID.Text := ''; if FieldValues['FName'] <> null then edtName.Text := FieldByName('FName').AsString else edtName.Text := ''; if FieldValues['FDesc'] <> null then edtDesc.Text := FieldByName('FDesc').AsString else edtDesc.Text := ''; end; //end if end; //end with //add listbox destinction adsTemp := TClientDtSet.Create(nil); adsTemp.RemoteServer := objGlobal.objDataConnect.ObjConnection; adsTemp.ProviderName := objGlobal.objDaStProvideName; strSQL := 'SELECT TBLTHRFUNCTIONLIST.FFNAME FROM TBLTHRFUNCTIONLIST Where TBLTHRFUNCTIONLIST.FID in ( select TBLTHRAUTHORIZATIONCONTENT.FFunctionList FROM TBLTHRAUTHORIZATIONCONTENT where TBLTHRAUTHORIZATIONCONTENT.FID=:FID'; strSQL := strSQL + ') order by FFNAME '; adsTemp.CommandText := strSQL; // adsTemp.Params.ParamByName('FID').Value := adsUserAuthContent1.FieldByName('FID').AsString; adsTemp.Open; lbDest.Clear; while not adsTemp.Eof do begin lbDest.Items.Add(adsTemp.FieldByName('FFNAME').AsString); adsTemp.Next; end; adsTemp.Close; adsTemp.Free; //add listbox source strSQL := 'SELECT DISTINCT FFNAME FROM TBLTHRFUNCTIONLIST WHERE FMODULE=9 ORDER BY FFNAME'; adsTemp := ObjGlobal.objDataConnect.DataQuery(strSQL); lbSource.Clear; while not adsTemp.Eof do begin lbSource.Items.Add(adsTemp.FieldByName('FFNAME').AsString); adsTemp.Next; end; adsTemp.Close; adsTemp.Free; for i := lbSource.Count - 1 downto 0 do begin for j := lbDest.Count - 1 downto 0 do begin if lbSource.Items.Strings[i] = lbDest.Items.Strings[j] then begin lbSource.Items.Delete(i); break; end; end; end; end; procedure TfrmUserAuthContent.initValue; var strSQL: string; adsTemp: TClientDtSet; begin case State of dsInsert: begin edtID.Text := ''; edtName.Text := ''; edtDesc.Text := ''; //add listbox source strSQL := 'select distinct FFNAME,FID FROM TBLTHRFUNCTIONLIST where FModule=9 order by FFNAME'; adsTemp := ObjGlobal.objDataConnect.DataQuery(strSQL); lbSource.Clear; while not adsTemp.Eof do begin lbSource.Items.Add(adsTemp.FieldByName('FFNAME').AsString); adsTemp.Next; end; adsTemp.Close; adsTemp.Free; lbDest.Clear; end; //End dsInsert dsEdit: begin end; //end dsEdit end; //end case end; procedure TfrmUserAuthContent.showUserAuthContent; var strSQL: string; begin //show Left DBGrid strSQL := 'select distinct FID,FName,FDesc FROM TBLTHRAUTHORIZATIONCONTENT'; //adsUserAuthContent1.Free; adsUserAuthContent1 := ObjGlobal.objDataConnect.DataQuery(strSQL); dsUserAuthContent1.DataSet := adsUserAuthContent1; if trim(edtID.Text) = '' then begin adsUserAuthContent1.First; end else begin adsUserAuthContent1.Locate('FID', edtID.Text, [loCaseInsensitive, loPartialKey]); end; //show Right DBGrid fillRightGrid; end; procedure TfrmUserAuthContent.StateChange; var i: integer; begin case State of dsInsert: begin // gbxUserAuthContent1.Enabled:=False; cbAID.Enabled := false; cbAName.Enabled := false; btnFilter.Enabled := false; tbAdd.Enabled := false; tbEdit.Enabled := False; tbDelete.Enabled := False; tbCopyFunction.Enabled := False; gbxUserAuthContent2.Caption := rsAuthContentAddNew; gbxUserAuthContent2.Visible := True; gbxUserAuthContent2.Enabled := True; edtID.Enabled := True; edtID.SetFocus; edtName.Enabled := True; edtDesc.Enabled := True; lbSource.Enabled := True; lbDest.Enabled := True; btnTransAll.Enabled := True; btnTransOne.Enabled := True; btnReverseOne.Enabled := True; btnReverseAll.Enabled := True; btnDone.Enabled := True; btnCancel.Enabled := True; initValue; end; dsEdit: begin // gbxUserAuthContent1.Enabled:=False; //fu cbAID.Enabled := false; cbAName.Enabled := false; btnFilter.Enabled := false; tbAdd.Enabled := false; tbEdit.Enabled := False; tbDelete.Enabled := False; tbCopyFunction.Enabled := False; gbxUserAuthContent2.Caption := rsAuthContentEdit; gbxUserAuthContent2.Visible := True; gbxUserAuthContent2.Enabled := True; edtID.Enabled := False; edtName.Enabled := True; edtDesc.Enabled := True; lbSource.Enabled := True; lbDest.Enabled := True; btnTransAll.Enabled := True; btnTransOne.Enabled := True; btnReverseOne.Enabled := True; btnReverseAll.Enabled := True; btnDone.Enabled := True; btnCancel.Enabled := True; initValue; end; dsBrowse: begin cbAID.Enabled := True; cbAName.Enabled := True; btnFilter.Enabled := True; gbxUserAuthContent1.Enabled := True; tbAdd.Enabled := True; tbEdit.Enabled := True; tbDelete.Enabled := True; tbCopyFunction.Enabled := True; gbxUserAuthContent2.Caption := rsAuthContentBrowse; gbxUserAuthContent2.Enabled := False; edtID.Enabled := False; edtName.Enabled := False; edtDesc.Enabled := False; lbSource.Enabled := False; lbDest.Enabled := False; btnTransAll.Enabled := False; btnTransOne.Enabled := False; btnReverseOne.Enabled := False; btnReverseAll.Enabled := False; btnDone.Enabled := False; btnCancel.Enabled := False; end; dsCopyFunction: begin edtID.Text := ''; edtName.Text := ''; edtDesc.Text := ''; cbAID.Enabled := false; cbAName.Enabled := false; btnFilter.Enabled := false; tbAdd.Enabled := false; tbEdit.Enabled := False; tbDelete.Enabled := False; tbCopyFunction.Enabled := False; gbxUserAuthContent2.Caption := rsAuthContentAddNew; gbxUserAuthContent2.Visible := True; gbxUserAuthContent2.Enabled := True; edtID.Enabled := True; edtID.SetFocus; edtName.Enabled := True; edtDesc.Enabled := True; lbSource.Enabled := True; lbDest.Enabled := True; btnTransAll.Enabled := True; btnTransOne.Enabled := True; btnReverseOne.Enabled := True; btnReverseAll.Enabled := True; btnDone.Enabled := True; btnCancel.Enabled := True; end; end; end; procedure TfrmUserAuthContent.FormCreate(Sender: TObject); var strSQL: string; begin lblFilterAID.Caption := lblID.Caption; lblFilterAName.Caption := lblName.Caption; State := dsBrowse; adsUserAuthContent1 := TClientDtSet.Create(self); adsUserAuthContent2 := TClientDtSet.Create(self); dsUserAuthContent1 := TDataSource.Create(self); dsUserAuthContent2 := TDataSource.Create(self); ctlUserAuthContentControl := TUserAuthContentControl.Create; dsUserAuthContent1.DataSet := adsUserAuthContent1; dsUserAuthContent2.DataSet := adsUserAuthContent2; dbgUserAuthContent1.DataSource := dsUserAuthContent1; dbgUserAuthContent2.DataSource := dsUserAuthContent2; ShowGridLabel; gbxUserAuthContent2.Visible := False; gbxUserAuthContent2.Enabled := False; uFillID; uFillName; showUserAuthContent; fillin; fillRightGrid; gbxUserAuthContent2.Enabled := False; gbxUserAuthContent2.Caption := rsAuthContentBrowse; gbxUserAuthContent2.Visible := True; end; procedure TfrmUserAuthContent.FormClose(Sender: TObject; var Action: TCloseAction); begin if adsUserAuthContent1 <> nil then begin adsUserAuthContent1.Close; adsUserAuthContent1.Free; end; if adsUserAuthContent2 <> nil then begin adsUserAuthContent2.Close; adsUserAuthContent2.Free; end; if dsUserAuthContent1 <> nil then dsUserAuthContent1.Free; if dsUserAuthContent2 <> nil then dsUserAuthContent2.Free; frmUserAuthContent:=nil; Action := caFree; end; procedure TfrmUserAuthContent.tbAddClick(Sender: TObject); begin State := dsInsert; StateChange; end; procedure TfrmUserAuthContent.tbEditClick(Sender: TObject); begin if adsUserAuthContent1.RecordCount = 0 then begin showmessage('User authorization Edit Error.'); exit; end; //add by fu State := dsEdit; fillin; StateChange; end; procedure TfrmUserAuthContent.tbDeleteClick(Sender: TObject); var I: integer; begin {if State<>dsBrowse then begin MessageDlg('Please click the cancel button to finish the current action',mtInformation,[mbYes],0); Exit; end; }//Modify by fubalian if MessageDlg('Are you Sure Delete fhe User.', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin if (adsUserAuthContent1.Active = False) or (adsUserAuthContent1.RecordCount < 1) then begin MessageDlg('The User is not exsits', mtInformation, [mbYes], 0) end else begin i := adsUserAuthContent1.RecNo; ctlUserAuthContentControl.RequestToDelete; showUserAuthContent; if (adsUserAuthContent1.RecordCount >= 1) and (I <= adsUserAuthContent1.RecordCount) then adsUserAuthContent1.RecNo := I else adsUserAuthContent1.Last; fillin; //fu // State:=dsBrowse; // stateChange; end; //end if end; //end if end; procedure TfrmUserAuthContent.btnDoneClick(Sender: TObject); begin if uiDataInspection = true then begin if State in [dsInsert, dsEdit, dsCopyFunction] then begin if (State = dsInsert) or (State = dsCopyFunction) then begin ctlUserAuthContentControl.requestToAdd(); showUserAuthContent; edtID.SetFocus; MessageDlg('Append SuccessFully!', mtInformation, [mbOK], 0); edtID.Text := ''; end else begin ctlUserAuthContentControl.requestToEdit(); showUserAuthContent; MessageDlg('Edit Successfully!', mtInformation, [mbOK], 0); State := dsBrowse; stateChange; end; end; end; end; procedure TfrmUserAuthContent.btnCancelClick(Sender: TObject); begin // if MessageDlg('Are you sure to Cancel Edit?',mtConfirmation,[mbYes,mbNo],0)=mrYes then begin //fu State := dsBrowse; StateChange; initValue; // end; //fu end; procedure TfrmUserAuthContent.dbgUserAuthContent1CellClick(Column: TColumn); var strSQL: string; begin if State = dsBrowse then begin StateChange; fillin; fillRightGrid; end; end; procedure TfrmUserAuthContent.dbgUserAuthContent1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin State := dsBrowse; StateChange; fillin; fillRightGrid; end; function TfrmUserAuthContent.uiDataInspection: Boolean; var i, j: integer; checkedEditNull: Boolean; begin Result := False; //check key column<>'' if trim(edtID.Text) = '' then begin ShowMessage('Please input UserID!'); Exit; end; if trim(edtName.Text) = '' then begin ShowMessage('Please input UserName'); Exit; end; //if trim(edtDesc.Text)='' then begin // ShowMessage('Please Key in Description!'); // Exit; //end; checkedEditNull := True; result := True; end; procedure TfrmUserAuthContent.dbgUserAuthContent1DblClick(Sender: TObject); begin if State = dsBrowse then begin State := dsEdit; StateChange; fillin; end; end; procedure TfrmUserAuthContent.edtIDKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin edtName.SetFocus; end end; procedure TfrmUserAuthContent.edtNameKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin edtDesc.SetFocus; end end; procedure TfrmUserAuthContent.btnTransAllClick(Sender: TObject); var i: Integer; begin if lbSource.Count <> 0 then begin for i := 0 to lbSource.Count - 1 do begin lbDest.Items.Add(lbSource.Items.Strings[i]); end; lbSource.Clear; end; end; procedure TfrmUserAuthContent.btnReverseAllClick(Sender: TObject); var i: Integer; begin if lbDest.Count <> 0 then begin for i := 0 to lbDest.Count - 1 do begin lbSource.Items.Add(lbDest.Items.Strings[i]); end; lbDest.Clear; end; end; procedure TfrmUserAuthContent.btnTransOneClick(Sender: TObject); var i: Integer; begin for i := 0 to lbSource.Count - 1 do begin if lbSource.Selected[i] = true then begin lbDest.Items.Add(lbSource.Items.Strings[i]); end; end; lbSource.DeleteSelected; end; procedure TfrmUserAuthContent.btnReverseOneClick(Sender: TObject); var i: Integer; begin for i := 0 to lbDest.Count - 1 do begin if lbDest.Selected[i] = true then begin lbSource.Items.Add(lbDest.Items.Strings[i]); end; end; lbDest.DeleteSelected; end; procedure TfrmUserAuthContent.fillRightGrid; var strSQL: string; // begin strSQL := 'SELECT b.FFNAME,a.FBuilder,a.FBDate,a.FReviser,a.FRDate FROM TBLTHRAUTHORIZATIONCONTENT a , TBLTHRFUNCTIONLIST b'; strSQL := strSQL + ' where a.FID=:FID '; strSQL := strSQL + ' and a.FFunctionList=b.FID order by b.FFNAME'; adsUserAuthContent2 := TClientDtSet.Create(nil); adsUserAuthContent2.RemoteServer := ObjGlobal.objDataConnect.ObjConnection; adsUserAuthContent2.ProviderName := ObjGlobal.objDaStProvideName; adsUserAuthContent2.CommandText := strSQL; adsUserAuthContent2.Params.ParamByName('FID').Value := adsUserAuthContent1.FieldByName('FID').AsString; adsUserAuthContent2.Open; adsUserAuthContent2.First; end; procedure TfrmUserAuthContent.ShowGridLabel; begin dbgUserAuthContent1.Columns[0].Title.Caption := rsAuthid; dbgUserAuthContent1.Columns[1].Title.Caption := rsAuthName; dbgUserAuthContent1.Columns[2].Title.Caption := rsAuthDesc; dbgUserAuthContent2.Columns[0].Title.Caption := rsAuthFuncName; dbgUserAuthContent2.Columns[1].Title.Caption := rsShowBuilder; dbgUserAuthContent2.Columns[2].Title.Caption := rsShowBDate; dbgUserAuthContent2.Columns[3].Title.Caption := rsShowReviser; dbgUserAuthContent2.Columns[4].Title.Caption := rsShowRDate; end; procedure TfrmUserAuthContent.FormShow(Sender: TObject); begin SendMessage(lbSource.Handle, LB_SETHORIZONTALEXTENT, 300, 0); SendMessage(lbDest.Handle, LB_SETHORIZONTALEXTENT, 300, 0); end; procedure TfrmUserAuthContent.btnFilterClick(Sender: TObject); var strSQL: string; begin //show Left DBGrid strSQL := 'SELECT distinct FID,FName,FDesc FROM TBLTHRAUTHORIZATIONCONTENT where 1=1 '; if Trim(cbAID.Text) <> '' then strSQL := strSQL + ' and FID like ' + QuotedStr(Trim(cbAID.Text) + '%'); if Trim(cbAName.Text) <> '' then strSQL := strSQL + ' and FName like ' + QuotedStr(Trim(cbAName.Text) + '%'); adsUserAuthContent1.Free; adsUserAuthContent1 := ObjGlobal.objDataConnect.DataQuery(strSQL); dsUserAuthContent1.DataSet := adsUserAuthContent1; //show Right DBGrid fillRightGrid; end; procedure TfrmUserAuthContent.uFillID; var FtmpDtSet: TClientDtSet; SQLStr: string; begin Screen.Cursor := crHourGlass; try SQLStr := ' SELECT distinct FID FROM TBLTHRAUTHORIZATIONCONTENT'; FtmpDtSet := ObjGlobal.objDataConnect.DataQuery(SQLStr); FillStringsByDB(FtmpDtSet, cbAID.Items, False); FtmpDtSet.Close; FtmpDtSet.Free; finally Screen.Cursor := crDefault; end; end; procedure TfrmUserAuthContent.uFillName; var FtmpDtSet: TClientDtSet; SQLStr: string; begin Screen.Cursor := crHourGlass; try SQLStr := ' SELECT distinct FName FROM TBLTHRAUTHORIZATIONCONTENT'; FtmpDtSet := ObjGlobal.objDataConnect.DataQuery(SQLStr); FillStringsByDB(FtmpDtSet, cbAName.Items, False); FtmpDtSet.Close; FtmpDtSet.Free; finally Screen.Cursor := crDefault; end; end; procedure TfrmUserAuthContent.tbCopyFunctionClick(Sender: TObject); begin if adsUserAuthContent1.RecordCount = 0 then begin showmessage(rsUserAuthContentCopy); exit; end; State := dsCopyFunction; fillin; StateChange; end; procedure TfrmUserAuthContent.FormDestroy(Sender: TObject); begin case iCallType of 0: frmUserAuthContent := nil; 1: FormFreeCallBack; end; end; end.
unit clsTUsuario; {$M+} {$TYPEINFO ON} interface uses System.SysUtils, System.Classes, System.JSON, System.Rtti, REST.JSON, Data.DBXJSON, Data.DBXJSONReflect, clsTUsuarioDTO, clsTUsuarioDAO, libEnumTypes; type TUsuario = class private FMarshal: TJSONMarshal; FUnMarshal: TJSONUnMarshal; FDTO: TUsuarioDTO; FDAO: TUsuarioDAO; procedure RegisterConverters; procedure RegisterReverters; procedure SetDTO(const Value: TUsuarioDTO); function GetDTO: TUsuarioDTO; function Init: Boolean; public constructor Create; overload; constructor Create(pNome, pEmail: String; pNasc: TDateTIme); overload; constructor Create(pID: Integer; pNome, pEmail: String; pNasc: TDateTIme); overload; constructor Create(JSON: String); overload; destructor Destroy; override; published property DTO: TUsuarioDTO read GetDTO write SetDTO; function ToJSON: String; function FromJSON(JSON: string): Boolean; function Persiste(Operacao: TOperacaoDAO): Boolean; end; implementation uses System.DateUtils; { TUsuario } procedure TUsuario.RegisterConverters; begin self.FMarshal.RegisterConverter( TUsuarioDTO, 'Fnasc', function(Data: TObject; Field: string): string var ctx: TRttiContext; date : TDateTime; teste: String; begin date := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<TDateTime>; teste := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsString; Result := FormatDateTime('DD/MM/YYYY HH:NN:SS', date); end); end; procedure TUsuario.RegisterReverters; begin Self.FUnMarshal.RegisterReverter( TUsuarioDTO, 'Fnasc', procedure(Data: TObject; Field: string; Arg: string) var ctx: TRttiContext; datetime: TDateTime; begin datetime := EncodeDateTime(StrToInt(Copy(Arg, 7, 4)), StrToInt(Copy(Arg, 4, 2)), StrToInt(Copy(Arg, 1, 2)), StrToInt(Copy(Arg, 12, 2)), StrToInt(Copy(Arg, 15, 2)), StrToInt(Copy(Arg, 18, 2)), 0); ctx.GetType(Data.ClassType).GetField(Field).SetValue(Data, datetime); end); end; constructor TUsuario.Create(pNome, pEmail: String; pNasc: TDateTIme); begin if Self.Init then begin Self.FDTO.Nome := pNome; Self.FDTO.Nasc := pNasc; Self.FDTO.Email := pEmail; end; end; constructor TUsuario.Create; begin Self.Init; end; constructor TUsuario.Create(JSON: String); begin if Self.Init then begin Self.FromJSON(JSON); end; end; destructor TUsuario.Destroy; begin Self.FDTO.Destroy; Self.FDAO.Destroy; Self.FMarshal.Destroy; Self.FUnMarshal.Destroy; inherited; end; function TUsuario.FromJSON(JSON: string): Boolean; begin Result := False; try Self.FDTO := Self.FUnMarshal.Unmarshal(TJSONObject.ParseJSONValue(JSON)) as TUsuarioDTO; Result := True; except end; end; procedure TUsuario.SetDTO(const Value: TUsuarioDTO); begin Self.FDTO := Value; end; constructor TUsuario.Create(pID: Integer; pNome, pEmail: String; pNasc: TDateTIme); begin if Self.Init then begin Self.FDTO.Nome := pNome; Self.FDTO.Nasc := pNasc; Self.FDTO.Email := pEmail; Self.FDTO.ID := pID; end; end; function TUsuario.GetDTO: TUsuarioDTO; begin Result := Self.FDTO; end; function TUsuario.Init: Boolean; begin Result := False; try Self.FDTO := TUsuarioDTO.Create; Self.FDAO := TUsuarioDAO.Create; Self.FMarshal := TJSONMarshal.Create; Self.FUnMarshal := TJSONUnMarshal.Create; Self.RegisterConverters; Self.RegisterReverters; Result := True; except end; end; function TUsuario.Persiste(Operacao: TOperacaoDAO): Boolean; begin Result := False; case Operacao of todInsert: begin Result := Self.FDAO.Put(Self.FDTO); end; todUpdate: begin Result := Self.FDAO.Post(Self.FDTO.ID, Self.FDTO); end; todDelete: begin Result := Self.FDAO.Delete(Self.FDTO.ID); end; todSelect: begin Self.FDTO := Self.FDAO.Get(Self.FDTO.EMail); Result := Assigned(Self.FDTO); end; end; end; function TUsuario.ToJSON: String; begin Result := Self.FMarshal.Marshal(Self.DTO).ToJSON; end; initialization end.
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.Micron.Old; interface uses SysUtils, BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TOldMicronSMARTSupport = class(TSMARTSupport) private function ModelHasMicronString(const Model: String): Boolean; function SMARTHasMicronCharacteristics( const SMARTList: TSMARTValueList): Boolean; function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; const EntryID = $CA; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TOldMicronSMARTSupport } function TOldMicronSMARTSupport.GetTypeName: String; begin result := 'SmartMicron'; end; function TOldMicronSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TOldMicronSMARTSupport.IsSSD: Boolean; begin result := true; end; function TOldMicronSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := ModelHasMicronString(IdentifyDevice.Model) or SMARTHasMicronCharacteristics(SMARTList); end; function TOldMicronSMARTSupport.ModelHasMicronString(const Model: String): Boolean; var ModelInUpperCase: String; begin ModelInUpperCase := UpperCase(Model); result := Find('CRUCIAL', ModelInUpperCase) or Find('MICRON', ModelInUpperCase) or Find('P600', ModelInUpperCase) or Find('C600', ModelInUpperCase) or Find('M6-', ModelInUpperCase) or Find('M600', ModelInUpperCase) or Find('P500', ModelInUpperCase) or Find('C500', ModelInUpperCase) or Find('M5-', ModelInUpperCase) or Find('M500', ModelInUpperCase) or Find('P400', ModelInUpperCase) or Find('C400', ModelInUpperCase) or Find('M4-', ModelInUpperCase) or Find('M400', ModelInUpperCase) or Find('P300', ModelInUpperCase) or Find('C300', ModelInUpperCase) or Find('C300', ModelInUpperCase) or Find('M3-', ModelInUpperCase) or Find('M300', ModelInUpperCase); end; function TOldMicronSMARTSupport.SMARTHasMicronCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 11) and (SMARTList[0].Id = $01) and (SMARTList[1].Id = $05) and (SMARTList[2].Id = $09) and (SMARTList[3].Id = $0C) and (SMARTList[4].Id = $AA) and (SMARTList[5].Id = $AB) and (SMARTList[6].Id = $AC) and (SMARTList[7].Id = $AD) and (SMARTList[8].Id = $AE) and (SMARTList[9].Id = $B5) and (SMARTList[10].Id = $B7); end; function TOldMicronSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin try result := SMARTList[SMARTList.GetIndexByID($F2)].Current; except on E: EEntryNotFound do result := SMARTList[SMARTList.GetIndexByID($CA)].Current else raise; end; end; function TOldMicronSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TOldMicronSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := IsEntryAvailable(EntryID, SMARTList); end; function TOldMicronSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := false; result.Status := InnerCommonIsError(EntryID, SMARTList).Status; end; function TOldMicronSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold); end; function TOldMicronSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID1 = $F5; WriteID2 = $F6; begin try SMARTList.GetIndexByID(WriteID1); result := true; except result := false; end; if not result then begin try SMARTList.GetIndexByID(WriteID2); result := true; except result := false; end; end; end; function TOldMicronSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $09; ThisErrorType = ReadError; ErrorID = $01; ReplacedSectorsID = $05; begin FillChar(result, SizeOf(result), 0); result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID); result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.ReplacedSectors := SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID); result.TotalWrite := GetTotalWrite(SMARTList); end; function TOldMicronSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID1 = $F5; WriteID2 = $F6; PageToLBA = 16; begin try result.InValue.ValueInMiB := LBAToMB(SMARTList.GetRAWByID(WriteID1) * PageToLBA); result.InValue.TrueHostWriteFalseNANDWrite := NANDWrite; except try result.InValue.ValueInMiB := LBAToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID2)); result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; except result.InValue.ValueInMiB := 0; end; end; end; end.
{ SMIX is Copyright 1995 by Ethan Brodsky. All rights reserved. } unit Detects; interface function GetSettings ( var BaseIO : word; var IRQ : byte; var DMA : byte; var DMA16 : byte ): boolean; {Gets sound card settings from BLASTER environment variable } {Parameters: } { BaseIO: Sound card base IO address } { IRQ: Sound card IRQ } { DMA: Sound card 8-bit DMA channel } { DMA16: Sound card 16-bit DMA channel (0 if none) } {Returns: } { TRUE: Sound card settings found successfully } { FALSE: Sound card settings could not be found } implementation uses DOS; function UpcaseStr(Str: string): string; var i: byte; Temp: string; begin Temp[0] := Str[0]; for i := 1 to Length(Str) do Temp[i] := Upcase(Str[i]); UpcaseStr := Temp; end; function GetSetting(Str: string; ID: char; Hex: boolean): word; var Temp : string; Num : word; Code : integer; begin Temp := Str; if Pos(ID, Temp) <> 0 then begin Delete(Temp, 1, Pos(ID, Temp)); Delete(Temp, Pos(' ', Temp), 255); if Hex then Insert('$', Temp, 1); Val(Temp, Num, Code); if Code = 0 then GetSetting := Num else GetSetting := $FF; end else GetSetting := $FF; end; function GetSettings ( var BaseIO: word; var IRQ: byte; var DMA: byte; var DMA16: byte ): boolean; var BLASTER: string; begin BLASTER := UpcaseStr(GetEnv('BLASTER')); BaseIO := GetSetting(BLASTER, 'A', true); {Hex} IRQ := GetSetting(BLASTER, 'I', false); {Decimal} DMA := GetSetting(BLASTER, 'D', false); {Decimal} DMA16 := GetSetting(BLASTER, 'H', false); {Decimal} GetSettings := true; if BLASTER = '' then GetSettings := false; if BaseIO = $FF then GetSettings := false; if IRQ = $FF then GetSettings := false; if DMA = $FF then GetSettings := false; {We can survive if there isn't a DMA16 channel} end; end.
unit mGMV_PrinterSelector; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls; type TfrGMV_PrinterSelector = class(TFrame) Panel1: TPanel; edTarget: TEdit; lvDevices: TListView; tmDevice: TTimer; gbDevice: TGroupBox; procedure tmDeviceTimer(Sender: TObject); procedure edTargetChange(Sender: TObject); procedure edTargetKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvDevicesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure gbDeviceEnter(Sender: TObject); procedure gbDeviceExit(Sender: TObject); private { Private declarations } public { Public declarations } DeviceIEN, DeviceName:String; procedure ClearSelection; end; implementation {$R *.dfm} uses uGMV_User, uGMV_Engine, uGMV_Common , uGMV_Const ; procedure TfrGMV_PrinterSelector.tmDeviceTimer(Sender: TObject); var s: String; i: Integer; sl: TStringList; LI: TListItem; const SearchDirection = 1; Margin = '80-132'; begin tmDevice.Enabled := False; SL := TStringList.Create; try s := getDeviceList(uppercase(edTarget.Text),Margin,SearchDirection); SL.Text := S; lvDevices.Items.Clear; if sl.Count <> 0 then begin lvDevices.Enabled := True; for i := 0 to SL.Count-1 do begin if piece(SL[i],'^',1) = '' then continue; LI := lvDevices.Items.Add; LI.Caption := piece(SL[i],'^',1); LI.SubItems.Add(piece(SL[i],'^',2)); LI.SubItems.Add(piece(SL[i],'^',4)); LI.SubItems.Add(piece(SL[i],'^',5)); LI.SubItems.Add(piece(SL[i],'^',6)); end; lvDevices.SetFocus; lvDevices.ItemIndex := 0; lvDevices.ItemFocused := lvDevices.Selected; end else lvDevices.Enabled := False; except end; SL.Free; end; procedure TfrGMV_PrinterSelector.edTargetChange(Sender: TObject); begin tmDevice.Enabled := True; ClearSelection; end; procedure TfrGMV_PrinterSelector.ClearSelection; begin DeviceIEN := ''; DeviceName := ''; // lblDevice.Caption := 'No device selected'; GetParentForm(self).Perform(CM_UPDATELOOKUP,0,0); end; procedure TfrGMV_PrinterSelector.edTargetKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then tmDeviceTimer(nil); end; procedure TfrGMV_PrinterSelector.lvDevicesChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if lvDevices.Selected = nil then ClearSelection else try DeviceIEN := lvDevices.Selected.Caption; DeviceName := lvDevices.Selected.SubItems[0]; // lblDevice.Caption := lvDevices.Selected.SubItems[0]+' '+ // lvDevices.Selected.SubItems[1]+' ' + // lvDevices.selected.SubItems[2]+'x' + lvDevices.Selected.SubItems[3]; GetParentForm(self).Perform(CM_UPDATELOOKUP,0,0); except ClearSelection; end; end; procedure TfrGMV_PrinterSelector.gbDeviceEnter(Sender: TObject); begin gbDevice.Font.Style := [fsBold]; lvDevices.Font.Style := []; edTarget.Font.Style := []; end; procedure TfrGMV_PrinterSelector.gbDeviceExit(Sender: TObject); begin gbDevice.Font.Style := []; end; end.
unit uLivroControl; interface uses uLivroModel, System.SysUtils, FireDAC.Comp.Client; type TLivroControl = class private FLivroModel: TLivroModel; public constructor Create; destructor Destroy; override; function Salvar: Boolean; function Obter: TFDQuery; function Buscar: TFDQuery; function ObterDados: TFDQuery; function BuscaAvancado: TFDQuery; property LivroModel: TLivroModel read FLivroModel write FLivroModel; end; implementation { TReservaControl } constructor TLivroControl.Create; begin FLivroModel := TLivroModel.Create; end; destructor TLivroControl.Destroy; begin FLivroModel.Free; inherited; end; function TLivroControl.Obter: TFDQuery; begin Result := FLivroModel.Obter; end; function TLivroControl.ObterDados: TFDQuery; begin Result := FLivroModel.ObterDados; end; function TLivroControl.Buscar: TFDQuery; begin Result := FLivroModel.Buscar; end; function TLivroControl.BuscaAvancado: TFDQuery; begin Result := FLivroModel.BuscaAvancada; end; function TLivroControl.Salvar: Boolean; begin Result := FLivroModel.Salvar; end; end.
unit BlockChain.BaseBlock; interface uses System.SysUtils, App.Types, BlockChain.Types; type TBaseBlock = class abstract protected Header: THeader; public function GetHeader: THeader; function GetSizeBlock: uint64; virtual; abstract; function GetData: TBytes; virtual; abstract; function GetHash: THash; virtual; abstract; procedure SetData(const AData: TBytes); virtual; abstract; end; implementation { TBaseBlock } function TBaseBlock.GetHeader: THeader; begin Result := Header; end; end.
unit fw_vm_constants; interface uses fw_vm_types,fw_system_types; const // Flags de funcionamiento de la VM: Mode_Flags opV_DebugOn =$000001; // 000000001 opV_DebugOff =$FFFFFE; // 111111110 opV_StopOn =$000002; // 000000010 opV_StopOff =$FFFFFD; // 111111101 // Estos son los tipos que puede ver el mundo exterior sobre los datos de una VM opT_None =cardinal($FFFF0001); // Nada //opt_None_AsPointer =pointer(opt_None); opT_Integer =cardinal($FFFF0002); // Entero opT_ExtPChar =cardinal($FFFF0004); // Es un Pchar extendido y gestionado por un GC, es decir el primer cardinal tiene la longitud opt_ConstPchar =cardinal($FFFF0008); // Esto es un Pchar constante opt_Boolean =cardinal($FFFF0010); // Booleano opt_Object =cardinal($FFFF0020); // Objeto opt_ExternF =cardinal($FFFF0040); // ExternF opt_Null =cardinal($FFFF0080); // Null opt_VarList =cardinal($FFFF0100); // Lista de variables opt_Iterator =cardinal($FFFF0200); // Iterador opt_PropCache =cardinal($FFFF0400); // Cache de propiedades // Estos son los tipos que puede ver el mundo exterior sobre el estado y configuracion de una VM opt_Library =cardinal($FFFF8001); opt_Block =cardinal($FFFF8002); // Bloque de codigo opt_JumpR =cardinal($FFFF8003); // Salto de codigo opt_Label =cardinal($FFFF8004); // Label solo se usa en tiempo de compilacion opt_Offset =cardinal($FFFF8005); // Offset opt_Name =cardinal($FFFF8010); // Un nombre opt_Code =cardinal($FFFF8011); // Un programa compilado opt_Context =cardinal($FFFF8012); // Un contexto de ejecucion opt_GC =cardinal($FFFF8013); // Un GC opt_Ivar =cardinal($FFFF8014); // Variable libre o indirecta. EL valor es un puntero a un tRt_Var opt_Runner =cardinal($FFFF8015); // Entorno de ejecucion opt_Compiler =cardinal($FFFF8016); // Entorno de compilacion opt_Debug =cardinal($FFFF8017); // Funcion de debug. Es un ExternF opt_Warning =cardinal($FFFF8018); // Mensaje de Warning opt_Hint =cardinal($FFFF8019); // Hint opt_Info =cardinal($FFFF8020); // Mensaje informativo opt_Source =cardinal($FFFF8021); // Codigo fuente opt_Index =cardinal($FFFF8022); // Index opt_HostData =cardinal($FFFF8023); // Host Object opt_HostControl =cardinal($FFFF8024); // Host Control opt_Buffer =cardinal($FFFF8025); // Un buffer: implementado con b_create en fw_utils opt_Flag =cardinal($FFFF8101); // Flags opt_FrameCall =cardinal($FFFF8102); // Call frame opt_FrameError =cardinal($FFFF8108); // Error frame opt_FrameDetour =cardinal($FFFF8109); // Detour frame opT_Gvar =cardinal($FFFF8110); // Variable global opT_CatchVar =cardinal($FFFF8111); // Variable de catch opt_Var =cardinal($FFFF8114); // Variable local opt_Reg =cardinal($FFFF8115); // Registro opt_Cvar =cardinal($FFFF8118); // Variable capturda por una funcion. EL valor es un indice a la lista de variables libres de la funcion actual opt_Nan =cardinal($FFFF8119); // Not A Number opt_Param =cardinal($FFFF8120); // Parametro enviado opt_Rparam =cardinal($FFFF8121); // Parametro recibido opt_Closure =cardinal($FFFF8122); // Closure List opt_Error =cardinal($FFFF8124); // Objeto Error opt_Unknown =cardinal($FFFF8127); // Variable sin definir ni importar (autogenerada) porque se usa en algun sitio opt_GetSet =cardinal($FFFF8128); // Getter Setter opt_FuncDelayed =cardinal($FFFF8129); // Una funcion delayed - Se utiliza al iniciar el RTL no se crean Objetos de todas las funciones, sino referencias para crearlos en la primera invocacion opt_OwnerShip =cardinal($FFFF8130); // Ajusta la ownership - se utiliza en la transferencia de objetos entre contextos (cuando RUN devuelve un Objeto) opt_Single =cardinal($FFFF8200); // Singleton(s) opS_CurF =longint(1); // Current function opS_This =longint(2); // Current this ops_Result =longint(3); // Resultado // Los opcodes de la maquina virtual op_NOP =$00; // NOP op_Move =$01; // Move op_NewObject =$02; // Crea un objeto op_NewFunc =$03; // Crea un objeto funcion op_CreateParams =$04; // Crea un nuevo Params_Frame op_Call =$05; // Call op_Extern =$06; // Define & get extern value op_Define =$07; // Define value op_GetProperty =$08; // Obtiene la direccion de la propiedad de un objeto, si no la encuentra hereda op_SetProperty =$0A; // Establece la propiedad de un objeto op_Ret =$0B; // Salida de funcion, si estamos dentro de un bloque finally lleva el flag NoEnd, sino lleva el flag End op_Jump =$0E; // Salto op_Link =$0F; // Linkea una variable local con una capturada op_GLink =$10; // Linkea una variable local a un Global op_NewArray =$11; // Crea un objeto Array op_Label =$13; // Es virtual se trata de un label op_JumpR =$14; // Salto RESULT -> Si se produce el salto se activa RESULT sino se queda como esta op_SetOn =$15; // Pone a 0/1 segun el flag que haya op_NewIter =$16; // Obtiene un iterador de objeto (propiedad) op_IterNext =$17; // El siguiente iterador op_Construct =$18; // Este es para borrar !!! a=new F() -> Se debe reescribir a nivel de GenCode como a={};F.call(a); op_PushFrame =$19; // Push Frame op_PopFrame =$1A; // Pop Frame op_DestroyParams =$1B; // Popea los parametros op_PatchFrame =$1C; // Parchea un frame que esta en el stack op_GetCache =$1D; op_SetCache =$1E; op_Throw =$1F; // Interrumpe la ejecucion del programa op_GCVar =$20; // Crea una variable en el GC, hace que el primer parametro apunte a la misma y le da el valor del segundo parametro op_Setter =$21; // Define un setter op_Getter =$22; // Define un getter op_ToObject =$23; // Convierte a Objeto opcode__min =$00; opcode__max =$23; // Los opcodes de operadores son > 100 op_Negative =107; op_Not =104; op_TypeOf =108; op_Times =141; op_Div =142; op_Mod =143; op_add =144; op_Minus =145; op_shiftl =146; op_shiftr =147; op_shiftrz =148; op_Compare =149; // Comparacion normal op_StrictCompare =150; // Comparacion estricta op_Instance =151; // Descriptores de Flags cuando kind=opT_Flag. Los TRUE son pares los negativos NO opF_BADFLAG =-1; opF_NoFlag =00; opF_min =02; opF_Eq =02; opF_NEq =03; opF_Big =04; opF_NBig =05; opF_BigEq =06; opF_NBigEq =07; opF_Less =08; opF_NLess =09; opF_LessEq =10; opF_NLessEq =11; opF_True =12; opF_False =13; opF_InMainBody =16; // Cuando se ejecuta un RET si el primer parametro es este FLAG, dice que el RET corresponde al MAIN BODY del prt_oCode opF_WithReturn =32; // Cuando se ejecuta un RET si el segundo parametro es este FLAG, quiere decir que el RET proviene de un statement RET y que por tanto hay una expresion que devolver // Tipos de frames que podemos cuando en el stack tenemsos un Opt_ErrorFrame opFr_TryFrame =01; // Try Frame opFr_CatchFrame =02; // Catch frame opFr_FinalFrame =03; // FinalFrame // Indicadores en el registro Flags // Tenemos los siguientes flags: // Eq: Binario 001 Decimal 1. Mascara Binario 110 -> Decimal 6 // Big: Binario 010 Decimal 2. Mascara Binario 101 -> Decimal 5 // Less: Binario 100 Decimal 4. Mascara Binario 011 -> Decimal 3 vF_EqOn =1; vF_BigOn =2; vF_LessOn =4; // Flag de salto, refleja el valor de la ultima ejecucion de JUMPR vF_JumpED =8; vf_JumpEDMask =7; vF_EndED =16; vF_EndEDMask =15; opT_MaskNonReal =cardinal($FFFF0000); // Mascara que cumplen todos los NO REAL opt_Mask0NoReal =cardinal($FFFF0000); opt_Mask1Constant =cardinal($FFFFFF00); // Si valor & opt_Mask1Constant = Mask0NoReal se trata de una constante (none,integer,pchar,boolean) opt_Mask2Real =cardinal($FFFF0000); // Si valor & opt_Mask2Real <> opt_Mask2Real se trata de un real // Gestion de Objeto kp_Writable =$0000001; // Si existe se puede escribir kp_Enumerable =$0000002; // Si existe se puede enumerar kp_Configurable =$0000004; // Si exoste se puede cambiar los atributos de la misma kp_DefaultProp =kp_Writable or kp_Enumerable or kp_Configurable; function vm_f2str(k:cardinal):string; function vm_ef2str(k:cardinal):string; function vm_t2str(k:cardinal):string; function vm_o2str(k:cardinal):string; function vm_tv2str(t:cardinal;v:longint):string; function vm_code2str(o:pRt_oOpcode):string; function vm_v2str(v:pRt_Var):string; function vm_text2str(v:pRt_Var):string; function vm_text2strl(v:pRt_Var;i:longint):string; implementation var SingleNames:array[1..3] of string=('{CurF}','{This}','{Result}'); //opS_CurF =longint(1); // Current function //opS_This =longint(2); // Current this //ops_Result =longint(3); // Resultado function s_i2s(i:integer):string; begin Str(i,Result); end; function s_p2s(i:pointer):string; begin Str(longint(i),Result); end; function s_left(s:string;i:integer):string; begin if s<>'' then result:=copy(s,1,i) else result:=''; end; function s_i2h(q:cardinal):string; var r:cardinal; begin result:= ''; while q>0 do begin r:=q mod 16; if r>=10 then result:=chr(55+r)+result else result:=s_i2s(r)+result; q:=q div 16; end; end; function s_spaces(i:longint):string; begin if i<=0 then begin result:='';exit;end; Setlength(result,i); while (i>0) do begin result[i]:=' ';i:=i-1;end; end; function s_rpad(const s:string;i:longint):string; begin result:=s_left(s+s_Spaces(i),i); end; function vm_t2str(k:cardinal):string; begin if k=opT_None then begin result:='none';exit;end; if k=opT_Integer then begin result:='integer';exit;end; if k=opT_ExtPChar then begin result:='ExtPchar';exit;end; if k=opt_Warning then begin result:='Warning';exit;end; if k=opt_Hint then begin result:='Hint';exit;end; if k=opt_Error then begin result:='Error';exit;end; if k=opt_Info then begin result:='Info';exit;end; if k=opt_ConstPchar then begin result:='ConstPchar';exit;end; if k=opT_Flag then begin result:='flag';exit;end; if k=opT_Object then begin result:='object';exit;end; if k=opT_Iterator then begin result:='iter';exit;end; if k=opT_Boolean then begin result:='boolean';exit;end; if k=opT_ExternF then begin result:='externF';exit;end; if k=opt_Context then begin result:='context';exit;end; if k=opt_Unknown then begin result:='unknown';exit;end; if k=opt_Null then begin result:='null';exit;end; if k=opt_GetSet then begin result:='GetSet';exit;end; if k=opt_Library then begin result:='Library';exit;end; if k=opt_GC then begin result:='GC';exit;end; if k=opt_Compiler then begin result:='Compiler';exit;end; if k=opt_Code then begin result:='CODE';exit;end; if k=opT_Var then begin result:='VAR_';exit;end; if k=opt_Debug then begin result:='DEBUG_';exit;end; if k=opt_Name then begin result:='NAME_';exit;end; if k=opt_Source then begin result:='SRC_';exit;end; if k=opT_Block then begin result:='BLOCK_';exit;end; if k=opT_Param then begin result:='PARAM_';exit;end; if k=opT_RParam then begin result:='RPARAM_';exit;end; if k=opT_GVar then begin result:='GVAR_';exit;end; if k=opT_Reg then begin result:='REG_';exit;end; if k=opT_JumpR then begin result:='JUMPR_';exit;end; if k=opT_Label then begin result:='LABEL_';exit;end; if k=opT_Block then begin result:='BLOCK_';exit;end; if k=opt_FrameError then begin result:='ERRFRAME_';exit;end; if k=opt_FrameCall then begin result:='CALLFRAME_';exit;end; if k=opt_Single then begin result:='[Single]';exit;end; if k=opt_CVar then begin result:='CVAR';exit;end; if k=opt_Offset then begin result:='OFFSET_';exit;end; if k=opt_Runner then begin result:='RUNNER_';exit;end; if k=opT_CatchVar then begin result:='CATCHVAR_';exit;end; if k=opt_FuncDelayed then begin result:='FUNC_DELAY_';exit;end; if k=opt_Closure then begin result:='CLLIST_';exit;end; if k=opt_VarList then begin result:='VARLIST_';exit;end; if k=opt_Ivar then begin result:='IVAR_';exit;end; if k=opt_OwnerShip then begin result:='OWNERSHIP_';exit;end; if (k and opt_Mask2Real)<>opt_Mask2Real then begin result:='float';exit;end; result:='NOT KNOWN: '+s_i2s(k)+' ['+s_i2h(k)+']'; end; function vm_v2str(v:pRt_Var):string; begin if v=nil then result:='*** NULL ***' else result:=vm_tv2str(v.kind,v.v_i); end; function vm_FloatToString(k1:cardinal;v1:longint):string; var k:^double; e1,e2,e3:extended; l:array[0..1] of longint; b:boolean; s:string; begin l[0]:=v1;l[1]:=k1; k:=@l[0]; Str(k^,result); e1:=int(k^); // La parte entera result:=''; if e1<0 then begin b:=true;e1:=-e1;end else b:=false; while e1<>0 do begin e2:=trunc(e1/10); // Esto es la division entera e3:=e1-e2*10; // Esto es el resto result:=s_i2s(trunc(e3))+result; // Acumulamos el resto e1:=e2; // Hacemos el shiftr que es equivalente a dividir entre 10 end; if result='' then result:='0'; if b then result:='-'+result; e1:=Frac(k^)*1000; s:=s_i2s(round(e1*100) div 100); while length(s)<3 do s:=s+'0'; result:=result+'.'+s; end; function vm_ef2str(k:cardinal):string; begin if k=opFr_TryFrame then result:='TryFrame' else if k=opFr_CatchFrame then result:='CatchFrame' else if k=opFr_FinalFrame then result:='FinalFrame' else result:='Bad_Error_Frame: '+s_i2s(k)+' '+s_i2h(k); end; function vm_text2str(v:pRt_Var):string; begin result:='';if v=nil then exit; if (v.kind=opt_ConstPchar) or (v.kind=opt_Name) then result:=pchar(v.v_pc) else if (v.kind=opT_ExtPChar) then result:=pchar(@(pRt_ExPchar(v.v_p).data)); if length(result)>63 then result:=s_left(result,60)+'..'; end; function vm_text2strl(v:pRt_Var;i:longint):string; begin result:='';if v=nil then exit; if (v.kind=opt_ConstPchar) or (v.kind=opt_Name) then result:=pchar(v.v_pc) else if (v.kind=opT_ExtPChar) then result:=pchar(@(pRt_ExPchar(v.v_p).data)); if i>0 then begin if length(result)>i+3 then result:=s_left(result,i)+'..'; end; end; function vm_tv2str(t:cardinal;v:longint):string; var s:string; begin result:=vm_t2str(t);if result='' then exit; if (t=opt_Warning) or (t=opt_Hint) or (t=opt_Error) or (t=opt_Info) then exit; if (t=opt_Single) then begin result:=SingleNames[v];exit;end; if (t=opt_FrameError) then begin result:='['+result+':'+vm_ef2str(v)+']';exit;end; if (t=opt_ConstPchar) then begin result:='['+result+':'+s_i2s(v); if v<>0 then s:=pchar(v) else s:=''; if length(s)>43 then s:=s_left(s,40)+'..'; result:=result+' "'+s+'"]'; exit; end; if (t=opt_Name) then begin result:='['+result+':'+s_i2s(v); if v<>0 then s:=pchar(v) else s:=''; if length(s)>43 then s:=s_left(s,40)+'..'; result:=result+' "'+s+'"]'; exit; end; if (t=opT_ExtPChar) then begin result:='['+result+':'+s_i2s(v);s:=''; if (v<>0) then s:=pchar(@(pRt_ExPchar(v).data)); if length(s)>43 then s:=s_left(s,40)+'..'; result:=result+' "'+s+'"]'; exit; end; if (t and opt_Mask2Real)<>opt_Mask2Real then begin result:='['+result+':'+vm_FloatToString(t,v)+']';exit;end; result:='['+result; if result[length(result)]<>'_' then begin result:=s_rpad(result,10); if (t=opt_Library) or (t=opt_Runner) or (t=opt_Compiler) or (t=opt_Debug) or (t=opt_GC) or (t=opt_Block) or (t=opt_ExternF) or (t=opt_Ivar) or (t=opt_Code) then result:=result+' @' else result:=result+' :'; end; result:=result+s_i2s(v)+']'; end; function vm_o2str(k:cardinal):string; begin case k of op_NOP : result:='NOP'; op_Move : result:='MOVE'; op_ToObject : result:='TO_OBJECT'; op_NewObject : result:='OBJECT'; op_NewFunc : result:='FUNCTION'; op_CreateParams : result:='NEW_PARAM_LIST'; op_Setter : result:='SETTER'; op_Getter : result:='GETTER'; op_Call : result:='CALL'; op_GLink : result:='GLINK'; op_GCVar : result:='GC_VAR'; op_Throw : result:='THROW'; op_Extern : result:='DEFINE_EXTERN'; op_Define : result:='DEFINE'; op_GetProperty : result:='GET_PROP'; op_SetProperty : result:='SET_PROP'; op_Ret : result:='RET'; op_Instance : result:='INSTANCE'; op_Compare : result:='CMP'; op_StrictCompare : result:='STRICT_CMP'; op_Jump : result:='JMP'; op_Link : result:='LINK'; //op_BlockInit : result:='BLOCK_INIT'; op_Label : result:='LABEL'; op_JumpR : result:='JMP_R'; op_SetOn : result:='SET'; op_NewIter : result:='ITERATOR'; op_IterNext : result:='ITER_NEXT'; op_Construct : result:='CONSTRUCT'; op_PushFrame : result:='PUSH_FRAME'; op_PopFrame : result:='POP_FRAME'; op_DestroyParams : result:='DESTROY_PARAM_LIST'; op_NewArray : result:='CREATE_ARRAY'; op_PatchFrame : result:='PATCH_FRAME'; op_GetCache : result:='GET_CACHE'; op_SetCache : result:='SET_CACHE'; op_Negative : result:='NEGATIVE'; op_TypeOF : result:='TYPEOF'; op_NOt : result:='NOT'; op_Times : result:='TIMES'; op_Div : result:='DIV'; op_Mod : result:='MOD'; op_Add : result:='ADD'; op_Minus : result:='MINUS'; op_shiftl : result:='SHIFTL'; op_shiftr : result:='SHIFTR'; op_shiftrz : result:='SHIFTRZ'; else result:=s_i2s(k); end; end; function vm_f2str(k:cardinal):string; begin result:=''; if k=opF_Eq then result:='EQ' else if k=opF_NEq then result:='NEQ' else if k=opF_Big then result:='BIG' else if k=opF_Nbig then result:='NBIG' else if k=opF_bigEq then result:='BIGEQ' else if k=opF_NbigEq then result:='NBIGEQ' else if k=opF_Less then result:='LESS' else if k=opF_NLess then result:='NLESS' else if k=opF_LessEq then result:='LESSEQ' else if k=opF_NLessEq then result:='NLESSEQ' else if k=opF_InMainBody then result:='MAIN' else if k=opF_WithReturn then result:='KEEP_RET' else if k=opF_True then result:='FLAG_TRUE' else if k=opF_False then result:='FLAG_FALSE' else result:='**BAD_FLAG**'; end; function vm_code2str(o:pRt_oOpcode):string; begin result:=s_rpad(s_p2s(o),15)+' '+s_rpad(vm_o2str(o.opcode),15); if o.k1<>opT_None then result:=result+vm_tv2str(o.k1,o.v1); if o.k2<>opT_None then result:=result+','+vm_tv2str(o.k2,o.v2); end; end.
unit DocumentTypeDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TDocumentTypeDialogForm = class(TForm) PreviousButton: TBitBtn; CancelButton: TBitBtn; Panel1: TPanel; NextButton: TBitBtn; Notebook: TNotebook; Label1: TLabel; DocumentTypeRadioGroup: TRadioGroup; WordDocumentRadioGroup: TRadioGroup; Label2: TLabel; Label3: TLabel; ExcelSpreadsheetRadioGroup: TRadioGroup; Label4: TLabel; WordPerfectDocumentRadioGroup: TRadioGroup; Label5: TLabel; QuattroProSpreadsheetRadioGroup: TRadioGroup; procedure PreviousButtonClick(Sender: TObject); procedure NextButtonClick(Sender: TObject); procedure DocumentTypeRadioGroupClick(Sender: TObject); private { Private declarations } public { Public declarations } DocumentTypeSelected : Integer; end; var DocumentTypeDialogForm: TDocumentTypeDialogForm; const MainDocumentSelectPage = 0; WordDocumentSelectPage = 1; ExcelSpreadsheetSelectPage = 2; WordPerfectDocumentSelectPage = 3; QuattroProSpreadsheetSelectPage = 4; dtOpenScannedImage = 0; dtOpenWordDocument = 1; dtCreateWordDocument = 2; dtOpenExcelSpreadsheet = 3; dtCreateExcelSpreadsheet = 4; dtOpenWordPerfectDocument = 5; dtCreateWordPerfectDocument = 6; dtOpenQuattroProSpreadsheet = 7; dtCreateQuattroProSpreadsheet = 8; dtOpenApexSketch = 9; dtOpenPDFDocument = 10; implementation {$R *.DFM} {====================================================} Procedure TDocumentTypeDialogForm.DocumentTypeRadioGroupClick(Sender: TObject); begin case DocumentTypeRadioGroup.ItemIndex of 0 : begin NextButton.Caption := '&OK'; PreviousButton.Visible := False; end; 1..4 : begin NextButton.Caption := '&Next >'; PreviousButton.Visible := True; end; end; {case DocumentTypeRadioGroup of} end; {DocumentTypeRadioGroupClick} {====================================================} Procedure TDocumentTypeDialogForm.PreviousButtonClick(Sender: TObject); begin Notebook.PageIndex := 1; end; {======================================================} Procedure TDocumentTypeDialogForm.NextButtonClick(Sender: TObject); begin case Notebook.PageIndex of MainDocumentSelectPage : begin case DocumentTypeRadioGroup.ItemIndex of 0 : begin DocumentTypeSelected := dtOpenScannedImage; ModalResult := mrOK; end; {Scanned document} 1..4 : begin Notebook.PageIndex := DocumentTypeRadioGroup.ItemIndex; PreviousButton.Enabled := True; NextButton.Caption := '&OK'; end; {Other documents} 5 : begin DocumentTypeSelected := dtOpenPDFDocument; ModalResult := mrOK; end; end; {case DocumentTypeRadioGroup.ItemIndex of} end; {First notebook page} WordDocumentSelectPage : begin case WordDocumentRadioGroup.ItemIndex of 0 : DocumentTypeSelected := dtOpenWordDocument; 1 : DocumentTypeSelected := dtCreateWordDocument; end; {case WordDocumentRadioGroup.ItemIndex of} ModalResult := mrOK; end; {Second notebook page} ExcelSpreadsheetSelectPage : begin case ExcelSpreadsheetRadioGroup.ItemIndex of 0 : DocumentTypeSelected := dtOpenExcelSpreadsheet; 1 : DocumentTypeSelected := dtCreateExcelSpreadsheet; end; {case ExcelSpreadsheetRadioGroup.ItemIndex of} ModalResult := mrOK; end; {Third notebook page} WordPerfectDocumentSelectPage : begin case WordPerfectDocumentRadioGroup.ItemIndex of 0 : DocumentTypeSelected := dtOpenWordPerfectDocument; 1 : DocumentTypeSelected := dtCreateWordPerfectDocument; end; {case WordPerfectDocumentRadioGroup.ItemIndex of} ModalResult := mrOK; end; {Fourth notebook page} QuattroProSpreadsheetSelectPage : begin case QuattroProSpreadsheetRadioGroup.ItemIndex of 0 : DocumentTypeSelected := dtOpenQuattroProSpreadsheet; 1 : DocumentTypeSelected := dtCreateQuattroProSpreadsheet; end; {case QuattroProSpreadsheetRadioGroup.ItemIndex of} ModalResult := mrOK; end; {Fifth notebook page} end; {case Notebook.PageIndex of} end; {NextButtonClick} end.
/ ***************************************************************** // ** COMPANY NAME: HPA Systems // ***************************************************************** // ** Application......: // ** // ** Module Name......: LinkedLists.pas // ** Program Name.....: // ** Program Description: Library of Linked List Procedures/Functions. // ** // ** // ** // ** // ** // ** // ** // ** Documentation....: // ** Called By........: // ** Sequence.........: // ** Programs Called..: // ** // ** Create Options...: // ** Object Owner.....: // ** CREATED By.......: RICHARD KNECHTEL // ** Creation Date....: 10/20/2001 // ** // ** // ***************************************************************** // * // * INPUT FILES: // * // * UPDATE FILES: // * // ***************************************************************** // * // * PARAMETERS // * ------------------------------------------------------------ // * // * PARAMETERS PASSED TO THIS PROGRAM: // * // * NAME DESCRIPTION // * ---------- ----------------------------------------------- // * NONE // * // ***************************************************************** // * // * PROGRAMS CALLED // * ------------------------------------------------------------ // * NO PROGRAMS CALLED // * // ***************************************************************** // ***************************************************************** // * License // ***************************************************************** // * // * This program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2 of the License, or // * (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with this program; if not, write to the Free Software // * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // * // ***************************************************************** // * MODIFICATION LOG: * // *===============================================================* // *##|WHO |WHEN |WHAT & (CSR#) * // *===============================================================* // * | | | * // * | | | * // *---------------------------------------------------------------* // ***************************************************************** // ***************************************************************** // ** // ** //*************************************************************************** //** AppendList - Append a item to a Linked List //*************************************************************************** Procedure AppendList(var StartAdr: PtrDataRec; Item: PtrDataRec; Sorted: Boolean); VAR hz: PtrDataRec; //** This will put the item to any place you like Procedure SortItemToList; VAR tmp: PtrDataRec; nz: PtrDataRec; flag: boolean; Begin If StartAdr = Nil Then //** This is the first element of the list, no need to sort StartAdr:= Item Else Begin //** Sort the Linked List //** Sort Criteria - put in ID# order //** of names to keep it easy //** Insert at list begin If Item^.ID < StartAdr^.ID Then Begin //** Store old list begin tmp:= StartAdr; //** List begin is now the new item StartAdr:= Item; //** New item's next points to old list begin Item^.NextRec:= tmp; End Else Begin //** Starting search for proper position at list beginning tmp:= StartAdr; //** Pointer for outlook on next data record nz:= tmp^.NextRec; //** Flag indicating end of search Flag:= False; Repeat If nz = Nil Then //** There are no more items behing this, //** put it to the end Flag:= True Else Begin If nz^.ID > Item^.ID Then //** We have to put our item before the next Flag:= True Else //** no matching position found, search on Begin nz:= nz^.NextRec; tmp:= tmp^.NextRec; End; End; Until Flag; //** Store old pointer to next element nz:= tmp^.NextRec; //** Place Item as next item tmp^.NextRec:= Item; //** Continue list with old next item Item^.NextRec:= nz; End; End; End; //**************** End of SortItemToList() Begin //** AppendList() If Sorted Then SortItemtoList Else Begin If StartAdr = Nil Then //** first element in list, that's all to do StartAdr:= Item Else Begin //** set a temporary pointer to list begin hz:= StartAdr; //** Look for end of list While hz^.NextRec <> Nil Do hz:= hz^.NextRec; //** set pointer to new element //** which is now at the end of the list hz^.NextRec:= Item; End; End; End; //***************************************************************************** //*************************************************************************** //** RemoveItem - Remove an item from a Linked List //*************************************************************************** Procedure RemoveItem(var StartAdr: PtrDataRec; DelItem: PtrDataRec); VAR tmp: PtrDataRec; Begin If StartAdr = nil Then //** List is empty Exit; //** Delete first element If DelItem = StartAdr Then Begin //** Set list begin to second element StartAdr:= StartAdr^.NextRec; //** remove first element Dispose(DelItem); End Else Begin tmp:= StartAdr; //** find previous element While tmp^.NextRec <> DelItem Do tmp:= tmp^.NextRec; //** bypasssing the element to be deleted tmp^.NextRec:= DelItem^.NextRec; //** Finally delete the item - So we don't leave any //** Memory Leaks! Dispose(DelItem); End; End; //**************************************************************************** //*************************************************************************** //** FindItem - Find an item from a Linked List //*************************************************************************** Function FindItem(StartAdr: PtrDataRec; IDNum: Integer): PtrDataRec; VAR tmp: PtrDataRec; Item: PtrDatarec; Begin //** Assuming that the ID# can't be found Item:= Nil; //** Yes, the list has at least one item If StartAdr <> nil Then Begin tmp:= StartAdr; While (tmp^.NextRec <> nil) and (tmp^.ID <> IDNum) Do Begin //** Check the next element tmp:= tmp^.NextRec; End; If tmp^.ID = IDNum Then Item:= tmp; End; //**Giving back a pointer to the first data record with this name } FindItem:= Item; End; //**************************************************************************** //*************************************************************************** //** FindRec - Find an item from a Linked List //*************************************************************************** Procedure FindRec; VAR IDNum: Integer; DspRec: PtrDataRec; Begin Write('Please input the ID# you wish to see: '); Readln(IDNum); Writeln; DspRec:= FindItem(StartRec, IDNum); If DspRec <> Nil Then Begin Write('ID# ', DspRec^.ID, Space, 'has ', DspRec^.Cash:10:2); Write(Space, 'cash on hand.'); Writeln; End Else //** No record exists Writeln('No Record exists for ID# ', IDNum); End; //*************************************************************************** //** CreateRec - Create an item for a Linked List //*************************************************************************** Procedure CreateRec; VAR IDNum: Integer; rlCashOH: Real; NewRec: PtrDataRec; Begin NewRec:=New(PtrDataRec); //** Fill data fields with NewRec^ Do Begin Write('Please input the ID# : '); Readln(IDNum); Writeln; ID:= IDNum; Write('Please Input the Amount of Cash on Hand: '); Readln(rlCashOH); Writeln; Cash:=rlCashOH; NextRec:=nil; End; //** Add the item to the list AppendList(StartRec,NewRec,true); End; //*************************************************************************** //** DspRec - Display all items in the Linked List //*************************************************************************** Procedure DspRec(Item: PtrDatarec); Begin Writeln('The following records are in the List: '); While Item <> Nil Do Begin Writeln('ID ', Item^.ID, Space, 'Has ', Item^.Cash:10:2, ' cash on hand.'); Item:= Item^.NextRec; End; End; //*************************************************************************** //** DelteRec - Delete an item in the Linked List //*************************************************************************** Procedure DeleteRec; VAR IDNumb: Integer; DelRec: PtrDataRec; Begin //** Input ID# to delete Write('Please input the ID# to delete: '); Readln(IDNumb); Writeln; //** Call FindRec w/ID# - get return pointer to record to delete DelRec:= FindItem(StartRec, IDNumb); If DelRec <> Nil Then Begin //** Call RemoveItem - passing Pointer to record to delete RemoveItem(StartRec,DelRec); Writeln('ID# ', IDNumb, Space, ' has been Deleted.'); End Else //** No record exists Writeln('No record exists for ID# ', IDNumb); End;
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Oracle driver } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.Phys.Oracle; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Phys, FireDAC.Phys.OracleWrapper; type [ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)] TFDPhysOracleDriverLink = class(TFDPhysDriverLink) private FTNSAdmin: String; FNLSLang: String; FThreaded: Boolean; protected function GetBaseDriverID: String; override; function IsConfigured: Boolean; override; procedure ApplyTo(const AParams: IFDStanDefinition); override; public constructor Create(AOwner: TComponent); override; class procedure GetOracleHomes(AList: TStrings); static; procedure GetTNSServices(AList: TStrings); published property NLSLang: String read FNLSLang write FNLSLang; property TNSAdmin: String read FTNSAdmin write FTNSAdmin; property Threaded: Boolean read FThreaded write FThreaded default True; end; TFDOracleStartupOperations = set of (stoStart, stoMount, stoOpen, stoOpenPDB); TFDOracleShutdownOperations = set of (shoShutdown, shoClose, shoDismount, shoClosePDB); [ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)] /// <summary> This component is responsible for managing Oracle instance. /// It allows to start and stop Oracle instance, also open and close a /// pluggable database. </summary> TFDOracleAdmin = class(TFDPhysDriverService) private type TAction = (aaStartup, aaShutdown); private FAction: TAction; FStartupOperations: TFDOracleStartupOperations; FStartupFlags: TOCIStartupFlags; FShutdownMode: TOCIShutdownMode; FShutdownOperations: TFDOracleShutdownOperations; FServer: String; FUserName: String; FPassword: String; FPFile: String; FPluggableDB: String; function GetDriverLink: TFDPhysOracleDriverLink; procedure SetDriverLink(const AValue: TFDPhysOracleDriverLink); procedure InternalStartup; procedure InternalShutdown; protected procedure InternalExecute; override; public constructor Create(AOwner: TComponent); override; /// <summary> Starts an Oracle instance, performing steps specified by /// StartupOperations property. Instance is started using specified by /// StartupFlags property flags. </summary> procedure Startup; /// <summary> Shutdowns an Oracle instance, performing steps specified by /// ShutdownOperations property. Instance is stoped using specified by /// ShutdownMode property mode. </summary> procedure Shutdown; published /// <summary> A reference to Oracle driver link component. </summary> property DriverLink: TFDPhysOracleDriverLink read GetDriverLink write SetDriverLink; /// <summary> The steps to perform at Oracle instance startup. </summary> property StartupOperations: TFDOracleStartupOperations read FStartupOperations write FStartupOperations default [stoStart, stoMount, stoOpen]; /// <summary> The additional flags to use at Oracle instance startup. </summary> property StartupFlags: TOCIStartupFlags read FStartupFlags write FStartupFlags default []; /// <summary> The steps to perform at Oracle instance shutdown. </summary> property ShutdownOperations: TFDOracleShutdownOperations read FShutdownOperations write FShutdownOperations default [shoShutdown, shoClose, shoDismount]; /// <summary> The mode to use at Oracle instance shutdown. </summary> property ShutdownMode: TOCIShutdownMode read FShutdownMode write FShutdownMode default smTransactional; /// <summary> The Oracle instance connection string. Note, to startup /// Oracle instance you should connect locally, by specifying Oracle /// instance name. </summary> property Server: String read FServer write FServer; /// <summary> The Oracle user name. Most application may use 'SYS'. /// The user must have SYSDBA privilege. </summary> property UserName: String read FUserName write FUserName; /// <summary> The Oracle user password. </summary> property Password: String read FPassword write FPassword; /// <summary> The Oracle PFILE to use at Oracle istance startup. </summary> property PFile: String read FPFile write FPFile; /// <summary> The Oracle pluggable database to close or open. </summary> property PluggableDB: String read FPluggableDB write FPluggableDB; end; {-------------------------------------------------------------------------------} implementation uses System.Variants, System.SysUtils, Data.DB, Data.SqlTimSt, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Util, FireDAC.Stan.Consts, FireDAC.Stan.SQLTimeInt, FireDAC.Stan.ResStrs, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.OracleCli, FireDAC.Phys.OracleMeta, FireDAC.Phys.OracleDef; type TFDPhysOracleDriver = class; TFDPhysOracleConnection = class; TFDPhysOracleEventAlerter = class; TFDPhysOracleEventAlerter_DBMS_ALERT = class; TFDPhysOracleEventAlerter_DBMS_PIPE = class; TFDPhysOracleEventAlerter_CQN = class; TFDPhysOracleTransaction = class; TFDPhysOracleCommand = class; TFDPhysOracleCliHandles = array [0..8] of pOCIHandle; PFDPhysOracleCliHandles = ^TFDPhysOracleCliHandles; TFDOraCommandHasParams = set of (hpHBlobsRet, hpInput, hpOutput, hpCursors, hpLongData, hpManyVLobs); TFDOraCommandHasFields = set of (hfNChar, hfManyNChars, hfLongData, hfBlob, hfRowIdExp, hfRowIdImp); TFDPhysOracleDriver = class(TFDPhysDriver) private FLib: TOCILib; protected class function GetBaseDriverID: String; override; class function GetBaseDriverDesc: String; override; class function GetRDBMSKind: TFDRDBMSKind; override; class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override; procedure InternalLoad; override; procedure InternalUnload; override; function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override; function GetCliObj: Pointer; override; function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override; public constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override; destructor Destroy; override; end; TFDPhysOracleConnection = class(TFDPhysConnection) private FEnv: TOCIEnv; FService: TOCIService; FSession: TOCISession; FServer: TOCIServer; FCliHandles: TFDPhysOracleCliHandles; FServerVersion: TFDVersion; FUseDBAViews: Boolean; FDecimalSep: Char; FDBCharacterSet, FNDBCharacterSet: String; FBooleanFormat: TOCIVarDataType; {$IFDEF FireDAC_OCI_NLSParams} FNLSParams: TStrings; {$ENDIF} {$IFDEF FireDAC_OCI_Versions} FVersions: TStrings; {$ENDIF} FLastServerOutput: Boolean; FLastServerOutputSize: Integer; procedure ParseAliasConnStr(var AUsr, APwd, ASrv: String; var AAuthMode: ub4); procedure AlterSession; procedure UpdateServerOutput; procedure GetServerOutput; procedure GetPLSQLErrors; procedure UpdateCurrentSchema; protected procedure InternalConnect; override; procedure InternalSetMeta; override; procedure InternalDisconnect; override; function InternalCreateCommand: TFDPhysCommand; override; function InternalCreateTransaction: TFDPhysTransaction; override; function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override; procedure InternalChangePassword(const AUserName, AOldPassword, ANewPassword: String); override; function InternalCreateMetadata: TObject; override; function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override; procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override; procedure InternalPing; override; procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override; function GetItemCount: Integer; override; function GetMessages: EFDDBEngineException; override; function GetCliObj: Pointer; override; function InternalGetCliHandle: Pointer; override; procedure InternalAnalyzeSession(AMessages: TStrings); override; {$IFDEF FireDAC_MONITOR} procedure InternalTracingChanged; override; {$ENDIF} public constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override; end; TFDPhysOracleTransaction = class(TFDPhysTransaction) private FTransaction: TOCITransaction; FInProgress: Boolean; function GetOraConnection: TFDPhysOracleConnection; inline; procedure UpdateInProgress; protected procedure InternalStartTransaction(ATxID: LongWord); override; procedure InternalCommit(ATxID: LongWord); override; procedure InternalRollback(ATxID: LongWord); override; procedure InternalAllocHandle; override; procedure InternalReleaseHandle; override; procedure InternalSelect; override; function GetCliObj: Pointer; override; procedure InternalNotify(ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); override; procedure InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); override; // other procedure UseHandle(AHandle: pOCIHandle); function GetAutoCommit: Boolean; property OraConnection: TFDPhysOracleConnection read GetOraConnection; end; TFDPhysOracleEventAlerter = class(TFDPhysEventAlerter) private FWaitConnection: IFDPhysConnection; FWaitCommand: IFDPhysCommand; FWaitThread: TThread; FSignalCommand: IFDPhysCommand; protected procedure DoFired; virtual; abstract; procedure InternalAllocHandle; override; procedure InternalReleaseHandle; override; procedure InternalRegister; override; procedure InternalUnregister; override; end; TFDPhysOracleEventAlerter_DBMS_ALERT = class(TFDPhysOracleEventAlerter) protected // TFDPhysEventAlerter procedure DoFired; override; procedure InternalRegister; override; procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override; procedure InternalAbortJob; override; procedure InternalUnregister; override; procedure InternalSignal(const AEvent: String; const AArgument: Variant); override; end; TFDPhysOracleEventAlerter_DBMS_PIPE = class(TFDPhysOracleEventAlerter) private FReadCommand, FWriteCommand: IFDPhysCommand; protected // TFDPhysEventAlerter procedure DoFired; override; procedure InternalAllocHandle; override; procedure InternalRegister; override; procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override; procedure InternalAbortJob; override; procedure InternalReleaseHandle; override; procedure InternalSignal(const AEvent: String; const AArgument: Variant); override; end; TFDPhysOracleEventAlerter_CQN = class (TFDPhysEventAlerter) private FNotifier: TOCIQueryNotification; FService: TOCIService; FCurrentChange: TObject; procedure RegisterQuery(AStmt: TOCIStatement); procedure DoQueryChanged(ASender: TOCIQueryNotification; AChange: TOCIChangeDesc); function DoRefreshHandler(const AHandler: IFDPhysChangeHandler): Boolean; protected procedure InternalAllocHandle; override; procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override; procedure InternalReleaseHandle; override; procedure InternalSignal(const AEvent: String; const AArgument: Variant); override; procedure InternalChangeHandlerModified(const AHandler: IFDPhysChangeHandler; const AEventName: String; AOperation: TOperation); override; procedure InternalRefresh(const AHandler: IFDPhysChangeHandler); override; end; PFDOraVarInfoRec = ^TFDOraVarInfoRec; PFDOraCrsDataRec = ^TFDOraCrsDataRec; TFDOraVarInfoRec = record FName, FExtName: String; FPos: sb4; FOSrcType, FOOutputType: TOCIVarDataType; FSrcType, FOutputType, FDestType: TFDDataType; FByteSize, FLogSize: LongWord; FVar: TOCIVariable; // FAttrs moved to here out of odDefine case due to C++Builder 5 incompatibility FAttrs: TFDDataAttributes; case FVarType: TOCIVarType of odDefine: ( FPrec: sb4; FScale: sb4; FADScale: Integer; FCrsInfo: PFDOraCrsDataRec; ); odIn, odOut, odInOut, odRet: ( FArrayLen: ub4; FIsCaseSensitive: Boolean; FIsPLSQLTable: Boolean; FParamType: TParamType; FDataType: TFieldType; ) end; TFDOraCrsDataRec = record FParent: PFDOraCrsDataRec; FStmt: TOCIStatement; FColInfos: array of TFDOraVarInfoRec; FColIndex: Integer; FExecuted: Boolean; FHasFields: TFDOraCommandHasFields; FImplicit: Boolean; FOpFlagsCol: Integer; end; TFDPhysOracleCommand = class(TFDPhysCommand) private FBase: TFDOraCrsDataRec; FCurrentCrsInfo: PFDOraCrsDataRec; FParInfos: array of TFDOraVarInfoRec; FCrsInfos: TFDPtrList; FActiveCrs: Integer; FInfoStack: TFDPtrList; FCursorCanceled: Boolean; FBindVarsDirty: Boolean; FHasParams: TFDOraCommandHasParams; FEventAlerter: TFDPhysOracleEventAlerter_CQN; procedure SQL2FDColInfo(AOraDataType: TOCIVarDataType; AOraSize, AOraPrec, AOraScale: sb4; var AType: TFDDataType; var AAttrs: TFDDataAttributes; var ALen: LongWord; var APrec, AScale: Integer); function FDType2OCIType(AFDType: TFDDataType; AFixedLen, APLSQL, AInput: Boolean): TOCIVarDataType; function GenerateStoredProcCallUsingOCI(const AName: TFDPhysParsedName): String; procedure DefParInfos(const ANm, ATpNm: String; AVt: TOCIVarType; FDt: TOCIVarDataType; ASz, APrec, ASCale: sb4; AIsTable, AIsResult: Boolean); procedure SetParamValues(ATimes, AOffset: Integer; AFromParIndex: Integer; AIntoReturning: Boolean); procedure GetParamValues(ATimes, AOffset: Integer); procedure CreateDefineInfo(ACrsInfo: PFDOraCrsDataRec); procedure CreateBindInfo; procedure DestroyDefineInfo(ACrsInfo: PFDOraCrsDataRec); procedure DestroyBindInfo; procedure ResetDefVars(ACrsInfo: PFDOraCrsDataRec; ARowsetSize: LongWord); function ProcessRowSet(ACrsInfo: PFDOraCrsDataRec; ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; procedure SetupStatement(AStmt: TOCIStatement); function GetActiveCursor: PFDOraCrsDataRec; procedure CloseImplicitCursors; function GetImplicitCursors: Boolean; procedure RebindCursorParams; procedure GetServerFeedback; procedure DestroyCrsInfo; function IsActiveCursorValid: Boolean; function GetRowsetSize(ACrsInfo: PFDOraCrsDataRec; ARowsetSize: LongWord): LongWord; protected procedure InternalAbort; override; procedure InternalClose; override; procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override; function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; override; function InternalOpen(var ACount: TFDCounter): Boolean; override; function InternalNextRecordSet: Boolean; override; procedure InternalPrepare; override; function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; override; function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; override; procedure InternalUnprepare; override; function GetCliObj: Pointer; override; public constructor Create(AConnectionObj: TFDPhysConnection); destructor Destroy; override; end; const S_FD_Normal = 'Normal'; S_FD_SysDBA = 'SysDBA'; S_FD_SysOper = 'SysOper'; S_FD_SysASM = 'SysASM'; S_FD_SysBackup = 'SysBackup'; S_FD_SysDG = 'SysDG'; S_FD_SysKM = 'SysKM'; S_FD_Service = 'Service'; S_FD_Mode = 'Mode'; S_FD_Choose = 'Choose'; S_FD_String = 'String'; S_FD_Integer = 'Integer'; S_FD_NLSDefault = '<NLS_LANG>'; S_FD_UTF8 = 'UTF8'; S_FD_OpFlags = C_FD_SysColumnPrefix + 'OPFLAGS'; ovdt2addt: array [TOCIVarDataType] of TFDDataType = (dtUnknown, dtInt32, dtUInt32, dtInt64, dtUInt64, dtSingle, dtDouble, dtFmtBCD, dtAnsiString, dtAnsiString, dtWideString, dtWideString, dtByteString, dtDateTime, dtMemo, dtWideMemo, dtBlob, dtAnsiString, dtBoolean, dtCursorRef, dtRowSetRef, dtHMemo, dtWideHMemo, dtHBlob, dtHBFile, dtHBFile, dtDateTimeStamp, dtTimeIntervalYM, dtTimeIntervalDS); addt2ovdt: array [TFDDataType] of TOCIVarDataType = ( otUnknown, otUnknown, otInt32, otInt32, otInt32, otInt64, otUInt32, otUInt32, otUInt32, otUInt64, otSingle, otDouble, otDouble, otNumber, otNumber, otNumber, otDateTime, otDateTime, otDateTime, otTimeStamp, otUnknown, otIntervalYM, otIntervalDS, otString, otNString, otRaw, otLongRaw, otLong, otNLong, otNLong, otBLOB, otCLOB, otNCLOB, otBFile, otNestedDataSet, otCursor, otUnknown, otUnknown, otUnknown, otUnknown, otUnknown); pt2vt: array [TParamType] of TOCIVarType = ( odUnknown, odIn, odOut, odInOut, odOut); vt2pt: array [TOCIVarType] of TParamType = ( ptUnknown, ptInput, ptOutput, ptInputOutput, ptOutput, ptUnknown); {-------------------------------------------------------------------------------} { TFDPhysOracleDriverLink } {-------------------------------------------------------------------------------} constructor TFDPhysOracleDriverLink.Create(AOwner: TComponent); begin inherited Create(AOwner); FThreaded := True; end; {-------------------------------------------------------------------------------} function TFDPhysOracleDriverLink.GetBaseDriverID: String; begin Result := S_FD_OraId; end; {-------------------------------------------------------------------------------} class procedure TFDPhysOracleDriverLink.GetOracleHomes(AList: TStrings); begin TOCILib.GetOracleHomeList(AList); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleDriverLink.GetTNSServices(AList: TStrings); begin if FDPhysManager.State = dmsInactive then FDPhysManager.Open; DriverIntf.Employ; try TOCILib(DriverIntf.CliObj).GetTNSServicesList(AList); finally DriverIntf.Vacate; end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleDriverLink.IsConfigured: Boolean; begin Result := inherited IsConfigured or (NLSLang <> '') or (TNSAdmin <> '') or not Threaded; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleDriverLink.ApplyTo(const AParams: IFDStanDefinition); begin inherited ApplyTo(AParams); if NLSLang <> '' then AParams.AsString[S_FD_ConnParam_Oracle_NLS_LANG] := NLSLang; if TNSAdmin <> '' then AParams.AsString[S_FD_ConnParam_Oracle_TNS_ADMIN] := TNSAdmin; if not Threaded then AParams.AsBoolean[S_FD_ConnParam_Oracle_Threaded] := Threaded; end; {-------------------------------------------------------------------------------} { TFDOracleAdmin } {-------------------------------------------------------------------------------} constructor TFDOracleAdmin.Create(AOwner: TComponent); begin inherited Create(AOwner); FStartupOperations := [stoStart, stoMount, stoOpen]; FShutdownOperations := [shoShutdown, shoClose, shoDismount]; FShutdownMode := smTransactional; end; {-------------------------------------------------------------------------------} function TFDOracleAdmin.GetDriverLink: TFDPhysOracleDriverLink; begin Result := inherited DriverLink as TFDPhysOracleDriverLink; end; {-------------------------------------------------------------------------------} procedure TFDOracleAdmin.SetDriverLink(const AValue: TFDPhysOracleDriverLink); begin inherited DriverLink := AValue; end; {-------------------------------------------------------------------------------} procedure TFDOracleAdmin.Startup; begin FAction := aaStartup; Execute; end; {-------------------------------------------------------------------------------} procedure TFDOracleAdmin.Shutdown; begin FAction := aaShutdown; Execute; end; {-------------------------------------------------------------------------------} procedure TFDOracleAdmin.InternalExecute; var oLib: TOCILib; begin oLib := TOCILib(CliObj); if not (Assigned(oLib.OCIDBStartup) and Assigned(oLib.OCIDBShutdown)) then FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_OraId]); case FAction of aaStartup: InternalStartup; aaShutdown: InternalShutdown; end; end; {-------------------------------------------------------------------------------} procedure TFDOracleAdmin.InternalStartup; var oLib: TOCILib; oEnv: TOCIEnv; oSvc: TOCIService; oSrv: TOCIServer; oSes: TOCISession; oAdm: TOCIAdmin; oStmt: TOCIStatement; sSrv: String; begin oLib := TOCILib(CliObj); oEnv := TOCIEnv.Create(oLib, Self); try oEnv.InitEnv('UTF8'); oSvc := TOCIService.Create(oEnv, Self); oSrv := TOCIServer.Create(oSvc); oSes := TOCISession.Create(oSvc); try if CompareText(Server, S_FD_Local) = 0 then sSrv := '' else sSrv := Server; oSrv.Attach(sSrv); if stoStart in StartupOperations then begin oSes.Start(UserName, Password, OCI_SYSDBA or OCI_PRELIM_AUTH); oAdm := TOCIAdmin.Create(oSvc); try if PFile <> '' then oAdm.PFILE := PFile; oAdm.Startup(StartupFlags); finally oAdm.Free; oSes.Stop; end; end; if StartupOperations - [stoStart] <> [] then begin oSes.Start(UserName, Password, OCI_SYSDBA); oStmt := TOCIStatement.Create(oEnv, oSvc, nil, Self); try if stoMount in StartupOperations then begin oStmt.Prepare('ALTER DATABASE MOUNT'); oStmt.Execute(1, 0, False, True); end; if stoOpen in StartupOperations then begin oStmt.Prepare('ALTER DATABASE OPEN'); oStmt.Execute(1, 0, False, True); end; if stoOpenPDB in StartupOperations then begin oStmt.Prepare('ALTER PLUGGABLE DATABASE ' + PluggableDB + ' OPEN'); oStmt.Execute(1, 0, False, True); end; finally oStmt.Free; end; end; finally oSes.Free; oSrv.Free; oSvc.Free; end; finally oEnv.Free; end; end; {-------------------------------------------------------------------------------} procedure TFDOracleAdmin.InternalShutdown; var oLib: TOCILib; oEnv: TOCIEnv; oSvc: TOCIService; oSrv: TOCIServer; oSes: TOCISession; oAdm: TOCIAdmin; oStmt: TOCIStatement; sSrv: String; begin oLib := TOCILib(CliObj); oEnv := TOCIEnv.Create(oLib, Self); try oEnv.InitEnv('UTF8'); oSvc := TOCIService.Create(oEnv, Self); oSrv := TOCIServer.Create(oSvc); oSes := TOCISession.Create(oSvc); try if CompareText(Server, S_FD_Local) = 0 then sSrv := '' else sSrv := Server; oSrv.Attach(sSrv); oSes.Start(UserName, Password, OCI_SYSDBA); if shoShutdown in ShutdownOperations then begin oAdm := TOCIAdmin.Create(oSvc); try oAdm.Shutdown(ShutdownMode); finally oAdm.Free; end; end; if ShutdownMode <> smAbort then begin if ShutdownOperations - [shoShutdown] <> [] then begin oStmt := TOCIStatement.Create(oEnv, oSvc, nil, Self); try if shoClosePDB in ShutdownOperations then begin oStmt.Prepare('ALTER PLUGGABLE DATABASE ' + PluggableDB + ' CLOSE IMMEDIATE'); oStmt.Execute(1, 0, False, True); end; if shoClose in ShutdownOperations then begin oStmt.Prepare('ALTER DATABASE CLOSE NORMAL'); oStmt.Execute(1, 0, False, True); end; if shoDismount in ShutdownOperations then begin oStmt.Prepare('ALTER DATABASE DISMOUNT'); oStmt.Execute(1, 0, False, True); end; finally oStmt.Free; end; end; if shoShutdown in ShutdownOperations then begin oAdm := TOCIAdmin.Create(oSvc); try oAdm.Shutdown(smFinal); finally oAdm.Free; end; end; end; finally oSes.Free; oSrv.Free; oSvc.Free; end; finally oEnv.Free; end; end; {-------------------------------------------------------------------------------} { TFDPhysOracleDriver } {-------------------------------------------------------------------------------} constructor TFDPhysOracleDriver.Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); begin inherited Create(AManager, ADriverDef); FLib := TOCILib.Create(Messages, FDPhysManagerObj); end; {-------------------------------------------------------------------------------} destructor TFDPhysOracleDriver.Destroy; begin inherited Destroy; FDFreeAndNil(FLib); end; {-------------------------------------------------------------------------------} class function TFDPhysOracleDriver.GetBaseDriverID: String; begin Result := S_FD_OraId; end; { ----------------------------------------------------------------------------- } class function TFDPhysOracleDriver.GetBaseDriverDesc: String; begin Result := 'Oracle Server'; end; { ----------------------------------------------------------------------------- } class function TFDPhysOracleDriver.GetRDBMSKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.Oracle; end; { ----------------------------------------------------------------------------- } class function TFDPhysOracleDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass; begin Result := TFDPhysOracleConnectionDefParams; end; { ----------------------------------------------------------------------------- } procedure TFDPhysOracleDriver.InternalLoad; var sHome, sLib, sNLSLang, sTNSAdmin: String; lThreaded: Boolean; begin sHome := ''; sLib := ''; sNLSLang := ''; sTNSAdmin := ''; lThreaded := True; if Params <> nil then begin GetVendorParams(sHome, sLib); sNLSLang := Params.AsString[S_FD_ConnParam_Oracle_NLS_LANG]; sTNSAdmin := Params.AsString[S_FD_ConnParam_Oracle_TNS_ADMIN]; if Params.IsSpecified(S_FD_ConnParam_Oracle_Threaded) then lThreaded := Params.AsBoolean[S_FD_ConnParam_Oracle_Threaded]; end; FLib.Load(sHome, sLib, sNLSLang, sTNSAdmin, lThreaded); end; { ----------------------------------------------------------------------------- } procedure TFDPhysOracleDriver.InternalUnload; begin FLib.Unload; end; { ----------------------------------------------------------------------------- } function TFDPhysOracleDriver.InternalCreateConnection( AConnHost: TFDPhysConnectionHost): TFDPhysConnection; begin Result := TFDPhysOracleConnection.Create(Self, AConnHost); end; { ----------------------------------------------------------------------------- } function TFDPhysOracleDriver.GetCliObj: Pointer; begin Result := FLib; end; {-------------------------------------------------------------------------------} function TFDPhysOracleDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; var oView: TFDDatSView; oList: TFDStringList; begin Result := inherited GetConnParams(AKeys, AParams); oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + ''''); if oView.Rows.Count = 1 then begin Employ; oList := TFDStringList.Create(#0, ';'); try FLib.GetTNSServicesList(oList); oView.Rows[0].BeginEdit; oView.Rows[0].SetValues('Type', oList.DelimitedText); oView.Rows[0].SetValues('Caption', S_FD_Service); oView.Rows[0].SetValues('LoginIndex', 2); oView.Rows[0].EndEdit; finally FDFree(oList); Vacate; end; end; Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_OSAuthent, '@Y', '', S_FD_ConnParam_Common_OSAuthent, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_AuthMode, S_FD_Normal + ';' + S_FD_SysDBA + ';' + S_FD_SysOper + ';' + S_FD_SysASM + ';' + S_FD_SysBackup + ';' + S_FD_SysDG + ';' + S_FD_SysKM, S_FD_Normal, S_FD_Mode, 3]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_ReadTimeout, '@I', '', S_FD_ConnParam_Oracle_ReadTimeout, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_WriteTimeout, '@I', '', S_FD_ConnParam_Oracle_WriteTimeout, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, S_FD_NLSDefault + ';' + S_FD_UTF8, S_FD_NLSDefault, S_FD_ConnParam_Common_CharacterSet, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_BooleanFormat, S_FD_Choose + ';' + S_FD_Integer + ';' + S_FD_String, S_FD_Choose, S_FD_ConnParam_Oracle_BooleanFormat, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ApplicationName, '@S', '', S_FD_ConnParam_Common_ApplicationName, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_OracleAdvanced, '@S', '', S_FD_ConnParam_Oracle_OracleAdvanced, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]); // Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_Distributed, '@L', S_FD_False, S_FD_ConnParam_Oracle_Distributed, -1]); // Result.Rows.Add([Unassigned, S_FD_ConnParam_Oracle_SrvIntName, '@S', '', S_FD_ConnParam_Oracle_SrvIntName, -1]); end; {-------------------------------------------------------------------------------} { TFDPhysOracleConnection } {-------------------------------------------------------------------------------} constructor TFDPhysOracleConnection.Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); begin inherited Create(ADriverObj, AConnHost); end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.InternalCreateCommand: TFDPhysCommand; begin Result := TFDPhysOracleCommand.Create(Self); end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.InternalCreateTransaction: TFDPhysTransaction; begin Result := TFDPhysOracleTransaction.Create(Self); end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; var oConnMeta: IFDPhysConnectionMetadata; begin if CompareText(AEventKind, S_FD_EventKind_Oracle_DBMS_ALERT) = 0 then Result := TFDPhysOracleEventAlerter_DBMS_ALERT.Create(Self, AEventKind) else if CompareText(AEventKind, S_FD_EventKind_Oracle_DBMS_PIPE) = 0 then Result := TFDPhysOracleEventAlerter_DBMS_PIPE.Create(Self, AEventKind) else if CompareText(AEventKind, S_FD_EventKind_Oracle_CQN) = 0 then begin CreateMetadata(oConnMeta); if (FServerVersion >= cvOracle102000) and (TFDPhysOracleDriver(DriverObj).FLib.Version >= cvOracle102000) then Result := TFDPhysOracleEventAlerter_CQN.Create(Self, AEventKind) else Result := nil; end else Result := nil; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.InternalCreateCommandGenerator( const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; begin if ACommand <> nil then Result := TFDPhysOraCommandGenerator.Create(ACommand, FUseDBAViews) else Result := TFDPhysOraCommandGenerator.Create(Self, FUseDBAViews); end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.InternalCreateMetadata: TObject; begin Result := TFDPhysOraMetadata.Create(Self, FServerVersion, TFDPhysOracleDriver(DriverObj).FLib.Version, (FEnv <> nil) and (FEnv.DataEncoder.Encoding in [ecUTF8, ecUTF16])); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.ParseAliasConnStr(var AUsr, APwd, ASrv: String; var AAuthMode: ub4); var oParams: TFDPhysOracleConnectionDefParams; s, sRest, sAuth: String; i1, i2, i3, i4: Integer; begin oParams := ConnectionDef.Params as TFDPhysOracleConnectionDefParams; AUsr := ''; APwd := ''; ASrv := ''; sAuth := ''; sRest := oParams.ExpandedDatabase; i1 := Pos('/', sRest); i2 := Pos('@', sRest); i3 := Pos(' AS ', UpperCase(sRest)); i4 := Pos(':', sRest); if (i2 = 0) and (i3 = 0) or (i4 > 0) then ASrv := sRest else begin if i3 > 0 then Inc(i3); if (i3 <> 0) and ((i3 = 1) or (sRest[i3 - 1] = ' ')) and ((i3 + 2 > Length(sRest)) or (sRest[i3 + 2] = ' ')) then begin sAuth := Trim(Copy(sRest, i3 + 2, Length(sRest))); sRest := Copy(sRest, 1, i3 - 1); end; if i2 <> 0 then begin ASrv := Trim(Copy(sRest, i2 + 1, Length(sRest))); sRest := Copy(sRest, 1, i2 - 1); end; if i1 <> 0 then begin APwd := Trim(Copy(sRest, i1 + 1, Length(sRest))); sRest := Copy(sRest, 1, i1 - 1); end; AUsr := Trim(Copy(sRest, 1, Length(sRest))); end; s := oParams.UserName; if s <> '' then AUsr := s; s := oParams.Password; if s <> '' then APwd := s; if CompareText(ASrv, S_FD_Local) = 0 then ASrv := ''; s := ConnectionDef.AsString[S_FD_ConnParam_Oracle_AuthMode]; if s <> '' then sAuth := s; if CompareText(sAuth, S_FD_SysDBA) = 0 then AAuthMode := OCI_SYSDBA else if CompareText(sAuth, S_FD_SysOper) = 0 then AAuthMode := OCI_SYSOPER else if CompareText(sAuth, S_FD_SysASM) = 0 then AAuthMode := OCI_SYSASM else if CompareText(sAuth, S_FD_SysBackup) = 0 then AAuthMode := OCI_SYSBKP else if CompareText(sAuth, S_FD_SysDG) = 0 then AAuthMode := OCI_SYSDGD else if CompareText(sAuth, S_FD_SysKM) = 0 then AAuthMode := OCI_SYSKMT else AAuthMode := OCI_DEFAULT; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.AlterSession; var oParams: TFDPhysOracleConnectionDefParams; sAdv, sCmd: String; i: Integer; begin oParams := ConnectionDef.Params as TFDPhysOracleConnectionDefParams; sAdv := oParams.OracleAdvanced; sCmd := ''; i := 1; while i <= Length(sAdv) do sCmd := sCmd + ' ' + FDExtractFieldName(sAdv, i); if sCmd <> '' then InternalExecuteDirect('ALTER SESSION SET' + sCmd, nil); sCmd := oParams.ApplicationName; if sCmd <> '' then InternalExecuteDirect('BEGIN DBMS_APPLICATION_INFO.SET_MODULE(' + QuotedStr(sCmd) + ', NULL); END;', nil); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalConnect; var oParams: TFDPhysOracleConnectionDefParams; pCliHandles: PFDPhysOracleCliHandles; iAuthMode: ub4; sCharsetName, sUsr, sPwd, sSrv: String; {$IFDEF FireDAC_MONITOR} oMon: IFDMoniClient; {$ENDIF} begin oParams := ConnectionDef.Params as TFDPhysOracleConnectionDefParams; {$IFDEF FireDAC_MONITOR} if GetTracing then oMon := GetMonitor else oMon := nil; {$ENDIF} case oParams.BooleanFormat of bfChoose: FBooleanFormat := otBoolean; bfInteger: FBooleanFormat := otInt32; bfString: FBooleanFormat := otString; end; if InternalGetSharedCliHandle() <> nil then begin pCliHandles := PFDPhysOracleCliHandles(InternalGetSharedCliHandle()); FEnv := TOCIEnv.CreateUsingHandle(TFDPhysOracleDriver(DriverObj).FLib, Self, pCliHandles^[0], pCliHandles^[5], String(PChar(pCliHandles^[6])), ub2(pCliHandles^[7]), Boolean(pCliHandles^[8]) {$IFDEF FireDAC_MONITOR}, oMon {$ENDIF}); FService := TOCIService.CreateUsingHandle(FEnv, pCliHandles^[1], Self); FServer := TOCIServer.CreateUsingHandle(FService, pCliHandles^[2]); FSession := TOCISession.CreateUsingHandle(FService, pCliHandles^[3]); TFDPhysOracleTransaction(TransactionObj).UseHandle(pCliHandles^[4]); end else begin sCharsetName := ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet]; if CompareText(sCharsetName, S_FD_NLSDefault) = 0 then sCharsetName := ''; FEnv := TOCIEnv.Create(TFDPhysOracleDriver(DriverObj).FLib, Self {$IFDEF FireDAC_MONITOR}, oMon {$ENDIF}); {$IFDEF FireDAC_MONITOR} InternalTracingChanged; {$ENDIF} FEnv.InitEnv(sCharsetName); FService := TOCIService.Create(FEnv, Self); FService.NONBLOCKING_MODE := False; FServer := TOCIServer.Create(FService); if FEnv.Lib.Version >= cvOracle112000 then begin if oParams.ReadTimeout > 0 then FServer.RECEIVE_TIMEOUT := oParams.ReadTimeout * 1000; if oParams.WriteTimeout > 0 then FServer.SEND_TIMEOUT := oParams.WriteTimeout * 1000; end; FSession := TOCISession.Create(FService); sUsr := ''; sPwd := ''; sSrv := ''; iAuthMode := 0; ParseAliasConnStr(sUsr, sPwd, sSrv, iAuthMode); if oParams.OSAuthent then begin sUsr := ''; sPwd := ''; end; FServer.Attach(sSrv); // if oParams.Distributed and (oParams.SrvIntName <> '') then // FServer.INTERNAL_NAME := oParams.SrvIntName; if oParams.NewPassword <> '' then begin FSession.Select; FSession.ChangePassword(sUsr, sPwd, oParams.NewPassword); sPwd := oParams.NewPassword; end; FSession.Start(sUsr, sPwd, iAuthMode); FServerVersion := FServer.ServerVersion; AlterSession; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalSetMeta; var oStmt: TOCIStatement; oVar1, oVar2, oVar3, oVar4, oVar5, oVar6: TOCIVariable; s: String; oFtch: TFDFetchOptions; begin inherited InternalSetMeta; FUseDBAViews := False; FDecimalSep := FormatSettings.DecimalSeparator; FDBCharacterSet := ''; {$IFDEF FireDAC_OCI_NLSParams} FNLSParams := nil; {$ENDIF} {$IFDEF FireDAC_OCI_Versions} FVersions := nil; {$ENDIF} try oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); oVar1 := nil; oVar2 := nil; oVar3 := nil; oVar4 := nil; oVar5 := nil; oVar6 := nil; try oStmt.Prepare( 'BEGIN'#10 + 'SELECT COUNT(*) INTO :PRV FROM SESSION_PRIVS WHERE PRIVILEGE = ''SELECT ANY TABLE'' OR PRIVILEGE = ''SELECT ANY DICTIONARY'';'#10 + 'SELECT VALUE INTO :NUM FROM V$NLS_PARAMETERS WHERE PARAMETER = ''NLS_NUMERIC_CHARACTERS'';'#10 + 'SELECT GREATEST(LENGTH(CHR(2000000000)), LENGTH(CHR(2000000)), LENGTH(CHR(20000))) INTO :BTS FROM SYS.DUAL;'#10 + 'SELECT USER INTO :USR FROM SYS.DUAL;'#10 + 'SELECT VALUE INTO :CHS FROM V$NLS_PARAMETERS WHERE PARAMETER = ''NLS_CHARACTERSET'';'#10 + 'SELECT MAX(VALUE) INTO :NCS FROM V$NLS_PARAMETERS WHERE PARAMETER = ''NLS_NCHAR_CHARACTERSET'';'#10 + 'END;' ); oVar1 := oStmt.AddVar(':PRV', odOut, otInt32); oVar2 := oStmt.AddVar(':NUM', odOut, otNString, 64); oVar3 := oStmt.AddVar(':BTS', odOut, otInt32); oVar4 := oStmt.AddVar(':USR', odOut, otNString, 64); oVar5 := oStmt.AddVar(':CHS', odOut, otNString, 64); oVar6 := oStmt.AddVar(':NCS', odOut, otNString, 64); oStmt.Execute(1, 0, False, True); FUseDBAViews := (oVar1.AsInteger = 2); s := oVar2.AsString; if Length(s) > 0 then FDecimalSep := s[1]; FService.BytesPerChar := ub1(oVar3.AsInteger); if FCurrentSchema = '' then FCurrentSchema := oVar4.AsString; FDBCharacterSet := oVar5.AsString; FNDBCharacterSet := oVar6.AsString; finally FDFree(oVar1); FDFree(oVar2); FDFree(oVar3); FDFree(oVar4); FDFree(oVar5); FDFree(oVar6); FDFree(oStmt); end; {$IFDEF FireDAC_OCI_NLSParams} oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); oVar1 := nil; oVar2 := nil; FNLSParams := TFDStringList.Create; try try oStmt.Prepare('SELECT * FROM V$NLS_PARAMETERS'); oVar1 := oStmt.AddVar(1, odDefine, otNString, 100); oVar2 := oStmt.AddVar(2, odDefine, otNString, 100); oStmt.Execute(1, 0, False, True); while not oStmt.Eof do begin FNLSParams.Add(oVar1.AsString + '=' + oVar2.AsString); oStmt.Fetch(1); end; except // no exceptions visible end; finally FDFree(oVar1); FDFree(oVar2); FDFree(oStmt); end; {$ENDIF} {$IFDEF FireDAC_OCI_Versions} oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); oVar1 := nil; FVersions := TFDStringList.Create; try try oStmt.Prepare('SELECT * FROM V$VERSION'); oVar1 := oStmt.AddVar(1, odDefine, otNString, 100); oStmt.Execute(1, 0, False, True); while not oStmt.Eof do begin FVersions.Add(oVar1.AsString); oStmt.Fetch(1); end; except // no exceptions visible end; finally FDFree(oVar1); FDFree(oStmt); end; {$ENDIF} except on E: EOCINativeException do // The dictionary will be not available, when connecting to the closed database if Pos('ORA-01219', E.Message) > 0 then begin oFtch := GetOptions.FetchOptions; oFtch.Items := oFtch.Items - [fiMeta]; end else raise; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalDisconnect; begin if (FEnv <> nil) and (FEnv.Error <> nil) then FEnv.Error.IgnoreErrors := (FState = csRecovering); {$IFDEF FireDAC_OCI_NLSParams} FDFreeAndNil(FNLSParams); {$ENDIF} {$IFDEF FireDAC_OCI_Versions} FDFreeAndNil(FVersions); {$ENDIF} FDFreeAndNil(FSession); FDFreeAndNil(FServer); FDFreeAndNil(FService); FDFreeAndNil(FEnv); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); var oStmt: TOCIStatement; begin oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); try oStmt.Prepare(ASQL); oStmt.Execute(1, 0, False, False); finally FDFree(oStmt); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalChangePassword(const AUserName, AOldPassword, ANewPassword: String); begin FSession.ChangePassword(FSession.USERNAME, FSession.PASSWORD, ANewPassword); end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.GetItemCount: Integer; begin Result := inherited GetItemCount; if DriverObj.State in [drsLoaded, drsActive] then begin Inc(Result, 5); if FSession <> nil then begin Inc(Result, 7); {$IFDEF FireDAC_OCI_NLSParams} if FNLSParams <> nil then Inc(Result, FNLSParams.Count); {$ENDIF} end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.GetItem(AIndex: Integer; out AName: String; out AValue: Variant; out AKind: TFDMoniAdapterItemKind); {$IFDEF FireDAC_OCI_NLSParams} var i: Integer; {$ENDIF} begin if AIndex < inherited GetItemCount then inherited GetItem(AIndex, AName, AValue, AKind) else case AIndex - inherited GetItemCount of 0: begin AName := 'Home'; if TFDPhysOracleDriver(DriverObj).FLib.FInstantClient then AValue := '<instant client at> ' + TFDPhysOracleDriver(DriverObj).FLib.FOracleHome else AValue := TFDPhysOracleDriver(DriverObj).FLib.FOracleHome; AKind := ikClientInfo; end; 1: begin AName := 'Version'; AValue := Integer(TFDPhysOracleDriver(DriverObj).FLib.Version); AKind := ikClientInfo; end; 2: begin AName := 'OCI DLL name'; AValue := TFDPhysOracleDriver(DriverObj).FLib.DLLName; AKind := ikClientInfo; end; 3: begin AName := 'TNSNAMES dir'; AValue := TFDPhysOracleDriver(DriverObj).FLib.FTNSNames; AKind := ikClientInfo; end; 4: begin AName := 'NLS_LANG'; AValue := TFDPhysOracleDriver(DriverObj).FLib.FNLSLang; AKind := ikClientInfo; end; 5: begin AName := 'Server ver'; {$IFDEF FireDAC_OCI_Versions} AValue := Trim(FVersions.Text); {$ELSE} AValue := AdjustLineBreaks(FServer.ServerVersionStr, tlbsCRLF); {$ENDIF} AKind := ikSessionInfo; end; 6: begin AName := 'Use DBA views'; AValue := FUseDBAViews; AKind := ikSessionInfo; end; 7: begin AName := 'Decimal sep'; AValue := FDecimalSep; AKind := ikSessionInfo; end; 8: begin AName := 'Client character set'; AValue := FEnv.CharsetName; AKind := ikSessionInfo; end; 9: begin AName := 'DB character set'; AValue := FDBCharacterSet; AKind := ikSessionInfo; end; 10: begin AName := 'NDB character set'; AValue := FNDBCharacterSet; AKind := ikSessionInfo; end; 11: begin AName := 'Database bytes/char'; AValue := FService.BytesPerChar; AKind := ikSessionInfo; end; else {$IFDEF FireDAC_OCI_NLSParams} if FNLSParams <> nil then begin i := AIndex - inherited GetItemCount - 11; AName := FNLSParams.KeyNames[i]; AValue := FNLSParams.ValueFromIndex[i]; AKind := ikSessionInfo; end; {$ENDIF} end; end; { ----------------------------------------------------------------------------- } function TFDPhysOracleConnection.GetMessages: EFDDBEngineException; begin if FEnv <> nil then Result := FEnv.Error.Info else Result := nil; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.GetCliObj: Pointer; begin Result := FService; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnection.InternalGetCliHandle: Pointer; begin if FEnv <> nil then begin FCliHandles[0] := FEnv.Handle; FCliHandles[1] := FService.Handle; FCliHandles[2] := FServer.Handle; FCliHandles[3] := FSession.Handle; FCliHandles[4] := TFDPhysOracleTransaction(TransactionObj).FTransaction.Handle; FCliHandles[5] := FEnv.Error.Handle; FCliHandles[6] := pOCIHandle(PChar(FEnv.CharsetName)); FCliHandles[7] := pOCIHandle(FEnv.ExplicitCharsetID); FCliHandles[8] := pOCIHandle(FEnv.ByteSemantic); Result := @FCliHandles; end else Result := nil; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.UpdateServerOutput; var oStmt: TOCIStatement; oVar: TOCIVariable; iSize: Integer; oRes: TFDTopResourceOptions; begin oRes := FOptions.ResourceOptions as TFDTopResourceOptions; if not ((FLastServerOutput <> oRes.ServerOutput) or oRes.ServerOutput and (FLastServerOutputSize <> oRes.ServerOutputSize)) then Exit; oVar := nil; oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); try if oRes.ServerOutput then begin oStmt.Prepare('BEGIN DBMS_OUTPUT.ENABLE(:SIZE); END;'); oVar := oStmt.AddVar(':SIZE', odIn, otInt32); iSize := oRes.ServerOutputSize; oVar.SetData(0, @iSize, 0); end else oStmt.Prepare('BEGIN DBMS_OUTPUT.DISABLE; END;'); oStmt.Execute(1, 0, False, False); FLastServerOutput := oRes.ServerOutput; FLastServerOutputSize := oRes.ServerOutputSize; finally FDFree(oVar); FDFree(oStmt); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.GetServerOutput; var oStmt: TOCIStatement; oVar1: TOCIVariable; oVar2: TOCIVariable; iStatus, i: Integer; oList: TFDStringList; begin if not (FOptions.ResourceOptions as TFDTopResourceOptions).ServerOutput then Exit; oVar1 := nil; oVar2 := nil; oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); oList := TFDStringList.Create; try oStmt.Prepare('BEGIN DBMS_OUTPUT.GET_LINE(:LINE, :STATUS); END;'); oVar1 := oStmt.AddVar(':LINE', odOut, otNString, 256); oVar2 := oStmt.AddVar(':STATUS', odOut, otInt32); repeat oStmt.Execute(1, 0, False, False); iStatus := oVar2.AsInteger; if iStatus = 0 then oList.Add(oVar1.AsString); until iStatus = 1; if oList.Count > 0 then begin FEnv.Error.CheckAllocateInfo; for i := 0 to oList.Count - 1 do FEnv.Error.Info.AppendError(0, 0, oList[i], '', ekServerOutput, -1, -1); end; finally FDFree(oList); FDFree(oVar1); FDFree(oVar2); FDFree(oStmt); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.GetPLSQLErrors; begin if not (FOptions.ResourceOptions as TFDTopResourceOptions).ServerOutput or // ORA-24344 Success with compilation error (FEnv.Error.Info = nil) or (FEnv.Error.Info[0].ErrorCode <> 24344) then Exit; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalPing; begin FService.Ping; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.UpdateCurrentSchema; var oStmt: TOCIStatement; oVar1: TOCIVariable; sUser: String; begin if (FServerVersion >= cvOracle102000) and (FEnv.Lib.Version >= cvOracle102000) then begin FCurrentSchema := FSession.CURRENT_SCHEMA; Exit; end; oStmt := TOCIStatement.Create(FEnv, FService, nil, Self); oVar1 := nil; try if FServerVersion < cvOracle81500 then sUser := 'USER' else sUser := 'SYS_CONTEXT(''USERENV'', ''CURRENT_SCHEMA'')'; oStmt.Prepare('SELECT ' + sUser + ' FROM SYS.DUAL'); oVar1 := oStmt.AddVar(1, odDefine, otNString, 64); oStmt.Execute(1, 0, False, True); FCurrentSchema := oVar1.AsString; finally FDFree(oVar1); FDFree(oStmt); end; end; {$IFDEF FireDAC_MONITOR} {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalTracingChanged; begin if FEnv <> nil then begin FEnv.Monitor := FMonitor; FEnv.Tracing := FTracing; end; end; {$ENDIF} {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnection.InternalAnalyzeSession(AMessages: TStrings); {$IFNDEF NEXTGEN} var saul, sa: AnsiString; sb: TFDByteString; {$ENDIF} begin inherited InternalAnalyzeSession(AMessages); // 2. The low value of minor version number if FEnv.Lib.Version mod 10000 <= 200 then AMessages.Add(Format(S_FD_OracleWarnLowMinVer, [FEnv.Lib.VersionStr])); // 3. < 9.2 client with Unicode Delphi if FEnv.Lib.Version < cvOracle92000 then AMessages.Add(Format(S_FD_OracleWarnUnicode, [FEnv.Lib.VersionStr])); // 4. 10.0 / 10.1 client with > 10.2 servers if (FServerVersion >= cvOracle102000) and (FEnv.Lib.Version < cvOracle102000) and (FEnv.Lib.Version >= cvOracle100000) then AMessages.Add(Format(S_FD_OracleWarnSrvClntVer, [FEnv.Lib.VersionStr, FDVerInt2Str(FServerVersion)])); {$IFNDEF NEXTGEN} // 5. US7ASCII leads to conversion losts for Western Europa languages, eg for a" SetLength(saul, 2); saul[1] := #195; saul[2] := #164; sa := AnsiString(Utf8ToAnsi(saul)); sb := AnsiToUtf8(String(sa)); if (Length(sb) = 2) and (saul[1] = sb[1]) and (saul[2] = sb[2]) and (CompareText(FDBCharacterSet, 'US7ASCII') = 0) then AMessages.Add(S_FD_OracleWarnASCII); {$ENDIF} {$IFDEF MSWINDOWS} // 6. 12.1 client has major resource & memory leak on Windows if (FEnv.Lib.Version >= cvOracle121000) and (FEnv.Lib.Version < cvOracle122000) then AMessages.Add(Format(S_FD_OracleWarnLeak, [FEnv.Lib.VersionStr])); {$ENDIF} end; {-------------------------------------------------------------------------------} { TFDPhysOracleTransaction } {-------------------------------------------------------------------------------} function TFDPhysOracleTransaction.GetOraConnection: TFDPhysOracleConnection; begin Result := TFDPhysOracleConnection(ConnectionObj); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.UseHandle(AHandle: pOCIHandle); begin ASSERT(FTransaction = nil); FTransaction := TOCITransaction.CreateUsingHandle(OraConnection.FService, AHandle); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalAllocHandle; begin ASSERT((FTransaction = nil) or not FTransaction.OwnHandle); if FTransaction = nil then FTransaction := TOCITransaction.Create(OraConnection.FService); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalReleaseHandle; begin FDFreeAndNil(FTransaction); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalSelect; begin if FTransaction <> nil then FTransaction.Select; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalStartTransaction(ATxID: LongWord); const ntisol2oci: array[TFDTxIsolation] of TOCITransactionMode = ( tmDefault, tmReadWrite, tmReadWrite, tmReadWrite, tmReadWrite, tmSerializable); var eMode: TOCITransactionMode; begin if GetOptions.ReadOnly then eMode := tmReadOnly else eMode := ntisol2oci[GetOptions.Isolation]; FTransaction.StartLocal(eMode); UpdateInProgress; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalCommit(ATxID: LongWord); begin FTransaction.Commit; if Retaining then InternalStartTransaction(ATxID); UpdateInProgress; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalRollback(ATxID: LongWord); begin FTransaction.RollBack; if Retaining then InternalStartTransaction(ATxID); UpdateInProgress; end; {-------------------------------------------------------------------------------} function TFDPhysOracleTransaction.GetAutoCommit: Boolean; begin Result := GetOptions.AutoStop and not GetActive; end; {-------------------------------------------------------------------------------} function TFDPhysOracleTransaction.GetCliObj: Pointer; begin Result := FTransaction; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.UpdateInProgress; begin if (OraConnection.FServerVersion >= cvOracle120000) and (OraConnection.FEnv.Lib.Version >= cvOracle120000) then FInProgress := OraConnection.FSession.TRANSACTION_IN_PROGRESS <> 0; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); var lInTx: Boolean; begin if OraConnection.FEnv = nil then Exit; if (OraConnection.FServerVersion >= cvOracle120000) and (OraConnection.FEnv.Lib.Version >= cvOracle120000) then begin lInTx := FInProgress; UpdateInProgress; if (lInTx <> FInProgress) and (GetActive <> FInProgress) then if FInProgress then TransactionStarted else TransactionFinished; end else begin if ASuccess and not GetActive and not GetOptions.AutoCommit then case TFDPhysOracleCommand(ACommandObj).GetCommandKind of skSelectForLock, skDelete, skInsert, skMerge, skUpdate: TransactionStarted; end; inherited InternalCheckState(ACommandObj, ASuccess); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleTransaction.InternalNotify(ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); begin if (ANotification in [cpBeforeCmdPrepare, cpAfterCmdPrepareSuccess, cpAfterCmdPrepareFailure, cpAfterCmdUnprepare]) or // SELECT commands and transactions do not affect somehow each other (TFDPhysOracleCommand(ACommandObj).GetCommandKind = skSelect) then Exit; // SET TRANSACTION requires to turn off auto-commit mode if TFDPhysOracleCommand(ACommandObj).GetCommandKind = skStartTransaction then case ANotification of cpBeforeCmdExecute: LockAutoStop; cpAfterCmdExecuteSuccess, cpAfterCmdExecuteFailure: UnlockAutoStop(True, False); end; inherited InternalNotify(ANotification, ACommandObj); end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventThread } {-------------------------------------------------------------------------------} type TFDPhysOracleEventThread = class(TThread) private [weak] FAlerter: TFDPhysOracleEventAlerter; protected procedure Execute; override; public constructor Create(AAlerter: TFDPhysOracleEventAlerter); destructor Destroy; override; end; {-------------------------------------------------------------------------------} constructor TFDPhysOracleEventThread.Create(AAlerter: TFDPhysOracleEventAlerter); begin inherited Create(False); FAlerter := AAlerter; FreeOnTerminate := True; end; {-------------------------------------------------------------------------------} destructor TFDPhysOracleEventThread.Destroy; begin FAlerter.FWaitThread := nil; inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventThread.Execute; begin while not Terminated and FAlerter.IsRunning do try FAlerter.FWaitCommand.Execute(); if not Terminated then FAlerter.DoFired; except on E: EFDDBEngineException do if E.Kind <> ekCmdAborted then begin Terminate; FAlerter.AbortJob; end; end; end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventAlerter } {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter.InternalAllocHandle; begin FWaitConnection := GetConnection.Clone; if FWaitConnection.State = csDisconnected then FWaitConnection.Open; FWaitConnection.CreateCommand(FWaitCommand); SetupCommand(FWaitCommand); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter.InternalRegister; begin FWaitThread := TFDPhysOracleEventThread.Create(Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter.InternalUnregister; begin FWaitThread := nil; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter.InternalReleaseHandle; begin FSignalCommand := nil; FWaitCommand := nil; FWaitConnection := nil; end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventMessage_DBMS_ALERT } {-------------------------------------------------------------------------------} type TFDPhysOracleEventMessage_DBMS_ALERT = class(TFDPhysEventMessage) private FName, FMessage: String; public constructor Create(const AName, AMessage: String); end; {-------------------------------------------------------------------------------} constructor TFDPhysOracleEventMessage_DBMS_ALERT.Create(const AName, AMessage: String); begin inherited Create; FName := AName; FMessage := AMessage; end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventAlerter_DBMS_ALERT } {-------------------------------------------------------------------------------} const C_WakeUpEvent = C_FD_SysNamePrefix + 'WAKEUP'; procedure TFDPhysOracleEventAlerter_DBMS_ALERT.InternalRegister; var sSQL: String; i: Integer; oPar: TFDParam; begin sSQL := 'BEGIN' + C_FD_EOL + 'SYS.DBMS_ALERT.REGISTER(''' + C_WakeUpEvent + ''');' + C_FD_EOL; for i := 0 to GetNames().Count - 1 do sSQL := sSQL + 'SYS.DBMS_ALERT.REGISTER(' + QuotedStr(Trim(GetNames()[i])) + ');' + C_FD_EOL; sSQL := sSQL + 'END;'; FWaitCommand.Prepare(sSQL); FWaitCommand.Execute(); FWaitCommand.CommandText := 'BEGIN' + C_FD_EOL + 'SYS.DBMS_ALERT.WAITANY(:name, :message, :status, :timeout);' + C_FD_EOL + 'END;'; oPar := FWaitCommand.Params[0]; oPar.ParamType := ptOutput; oPar.DataType := ftString; oPar.Size := 30 * 2; oPar := FWaitCommand.Params[1]; oPar.ParamType := ptOutput; oPar.DataType := ftString; oPar.Size := 1800 * 2; oPar := FWaitCommand.Params[2]; oPar.ParamType := ptOutput; oPar.DataType := ftInteger; oPar := FWaitCommand.Params[3]; oPar.ParamType := ptInput; oPar.DataType := ftInteger; oPar.AsInteger := 86400; FWaitCommand.Prepare(); inherited InternalRegister; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_ALERT.DoFired; begin if (FWaitCommand.Params[2].AsInteger = 0) and (CompareText(FWaitCommand.Params[0].AsString, C_WakeUpEvent) <> 0) then FMsgThread.EnqueueMsg(TFDPhysOracleEventMessage_DBMS_ALERT.Create( FWaitCommand.Params[0].AsString, FWaitCommand.Params[1].AsString)); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_ALERT.InternalHandle(AEventMessage: TFDPhysEventMessage); var oMsg: TFDPhysOracleEventMessage_DBMS_ALERT; begin oMsg := TFDPhysOracleEventMessage_DBMS_ALERT(AEventMessage); InternalHandleEvent(oMsg.FName, oMsg.FMessage); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_ALERT.InternalAbortJob; begin if FWaitThread <> nil then begin FWaitThread.Terminate; InternalSignal(C_WakeUpEvent, Null); FWaitCommand.AbortJob(True); while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do Sleep(1); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_ALERT.InternalUnregister; var sSQL: String; i: Integer; begin inherited InternalUnregister; if FWaitCommand <> nil then try sSQL := 'BEGIN' + C_FD_EOL + 'SYS.DBMS_ALERT.REMOVE(''' + C_WakeUpEvent + ''');' + C_FD_EOL; for i := 0 to GetNames().Count - 1 do sSQL := sSQL + 'SYS.DBMS_ALERT.REMOVE(' + QuotedStr(Trim(GetNames()[i])) + ');' + C_FD_EOL; sSQL := sSQL + 'END;'; FWaitCommand.Prepare(sSQL); FWaitCommand.Execute(); except // hide exception end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_ALERT.InternalSignal(const AEvent: String; const AArgument: Variant); var oPar: TFDParam; begin if FSignalCommand = nil then begin GetConnection.CreateCommand(FSignalCommand); SetupCommand(FSignalCommand); FSignalCommand.CommandText := 'BEGIN SYS.DBMS_ALERT.SIGNAL(:name, :message); END;'; oPar := FSignalCommand.Params[0]; oPar.DataType := ftString; oPar.Size := 30 * 2; oPar := FSignalCommand.Params[1]; oPar.DataType := ftString; oPar.Size := 1800 * 2; FSignalCommand.Prepare(); end; FSignalCommand.Params[0].AsString := AEvent; FSignalCommand.Params[1].AsString := VarToStr(AArgument); FSignalCommand.Execute(); end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventMessage_DBMS_ALERT } {-------------------------------------------------------------------------------} type TFDPhysOracleEventMessage_DBMS_PIPE = class(TFDPhysEventMessage) private FName: String; FValues: Variant; public constructor Create(const AName: String; const AValues: Variant); end; {-------------------------------------------------------------------------------} constructor TFDPhysOracleEventMessage_DBMS_PIPE.Create(const AName: String; const AValues: Variant); begin inherited Create; FName := AName; FValues := AValues; end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventAlerter_DBMS_PIPE } {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.InternalAllocHandle; begin if GetNames().Count > 1 then FDException(Self, [S_FD_LPhys, S_FD_OraId], er_FD_OraPipeAlertToMany, []); inherited InternalAllocHandle; FWaitConnection.CreateCommand(FReadCommand); SetupCommand(FReadCommand); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.InternalRegister; var oPar: TFDParam; begin FWaitCommand.CommandText := 'BEGIN' + C_FD_EOL + ':result := SYS.DBMS_PIPE.RECEIVE_MESSAGE(:name, :timeout);' + C_FD_EOL + 'END;'; oPar := FWaitCommand.Params[0]; oPar.ParamType := ptOutput; oPar.DataType := ftInteger; oPar := FWaitCommand.Params[1]; oPar.ParamType := ptInput; oPar.DataType := ftString; oPar.Size := 128 * 2; oPar := FWaitCommand.Params[2]; oPar.ParamType := ptInput; oPar.DataType := ftInteger; oPar.AsInteger := 86400; FWaitCommand.Prepare(); FWaitCommand.Params[1].AsString := GetNames()[0]; FReadCommand.CommandText := 'BEGIN' + C_FD_EOL + ':tp := SYS.DBMS_PIPE.NEXT_ITEM_TYPE;' + C_FD_EOL + 'IF :tp = 6 THEN' + C_FD_EOL + ' SYS.DBMS_PIPE.UNPACK_MESSAGE(:num);' + C_FD_EOL + 'ELSIF :tp = 9 THEN' + C_FD_EOL + ' SYS.DBMS_PIPE.UNPACK_MESSAGE(:vc2);' + C_FD_EOL + 'ELSIF :tp = 11 THEN' + C_FD_EOL + ' SYS.DBMS_PIPE.UNPACK_MESSAGE_ROWID(:vc2);' + C_FD_EOL + 'ELSIF :tp = 12 THEN' + C_FD_EOL + ' SYS.DBMS_PIPE.UNPACK_MESSAGE(:dt);' + C_FD_EOL + 'ELSIF :tp = 23 THEN' + C_FD_EOL + ' SYS.DBMS_PIPE.UNPACK_MESSAGE_RAW(:vc2);' + C_FD_EOL + 'END IF;' + C_FD_EOL + 'END;'; oPar := FReadCommand.Params[0]; oPar.ParamType := ptOutput; oPar.DataType := ftInteger; oPar := FReadCommand.Params[1]; oPar.ParamType := ptOutput; oPar.DataType := ftFloat; oPar := FReadCommand.Params[2]; oPar.ParamType := ptOutput; oPar.DataType := ftString; oPar.Size := 1024 * 2; oPar := FReadCommand.Params[3]; oPar.ParamType := ptOutput; oPar.DataType := ftDateTime; FReadCommand.Prepare(); inherited InternalRegister; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.DoFired; var i: Integer; vVal: Variant; aValues: Variant; begin case FWaitCommand.Params[0].AsInteger of 0: {success} begin i := 0; aValues := Null; while True do begin FReadCommand.Execute(); case FReadCommand.Params[0].AsInteger of 0: Break; 9 {vc}, 11 {rowid}, 23 {raw}: vVal := FReadCommand.Params[2].AsString; 6 {num}: vVal := FReadCommand.Params[1].AsFloat; 12 {date}: vVal := FReadCommand.Params[3].AsDateTime; else vVal := Null; end; if i = 0 then aValues := VarArrayCreate([0, 0], varVariant) else VarArrayRedim(aValues, i); aValues[i] := vVal; Inc(i); end; FMsgThread.EnqueueMsg(TFDPhysOracleEventMessage_DBMS_PIPE.Create( FWaitCommand.Params[1].AsString, aValues)); end; 1: {timeout} ; else FWaitThread.Terminate; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.InternalHandle( AEventMessage: TFDPhysEventMessage); var oMsg: TFDPhysOracleEventMessage_DBMS_PIPE; begin oMsg := TFDPhysOracleEventMessage_DBMS_PIPE(AEventMessage); InternalHandleEvent(oMsg.FName, oMsg.FValues); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.InternalAbortJob; begin if FWaitThread <> nil then begin FWaitThread.Terminate; InternalSignal(GetNames()[0], Null); FWaitCommand.AbortJob(True); while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do Sleep(1); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.InternalReleaseHandle; begin FReadCommand := nil; FWriteCommand := nil; inherited InternalReleaseHandle; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_DBMS_PIPE.InternalSignal( const AEvent: String; const AArgument: Variant); var i: Integer; oPar: TFDParam; begin if FSignalCommand = nil then begin GetConnection.CreateCommand(FSignalCommand); SetupCommand(FSignalCommand); FSignalCommand.CommandText := 'DECLARE i INTEGER; BEGIN i := SYS.DBMS_PIPE.SEND_MESSAGE(:name); END;'; oPar := FSignalCommand.Params[0]; oPar.DataType := ftString; oPar.Size := 128 * 2; FSignalCommand.Prepare(); GetConnection.CreateCommand(FWriteCommand); SetupCommand(FWriteCommand); FWriteCommand.CommandText := 'BEGIN SYS.DBMS_PIPE.PACK_MESSAGE(:name); END;'; end; if VarIsArray(AArgument) then for i := VarArrayLowBound(AArgument, 1) to VarArrayHighBound(AArgument, 1) do begin FWriteCommand.Disconnect; oPar := FWriteCommand.Params[0]; oPar.Clear(); oPar.DataType := ftUnknown; oPar.Value := AArgument[i]; FWriteCommand.Execute(); end else if not (VarIsNull(AArgument) or VarIsEmpty(AArgument)) then begin FWriteCommand.Disconnect; oPar := FWriteCommand.Params[0]; oPar.Clear(); oPar.DataType := ftUnknown; oPar.Value := AArgument; FWriteCommand.Execute(); end; FSignalCommand.Params[0].AsString := AEvent; FSignalCommand.Execute(); end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventMessage_CQN } {-------------------------------------------------------------------------------} type TRowChange = record public FRowID: String; FOper: TUpdateStatus; end; TTableChange = record public FName: String; FRows: TArray<TRowChange>; end; TQueryChange = class(TObject) public FQueryID: ub8; FTables: TArray<TTableChange>; end; type TFDPhysOracleEventMessage_CQN = class(TFDPhysEventMessage) private FQueryChange: TQueryChange; public constructor Create(AQueryChange: TQueryChange); destructor Destroy; override; end; {-------------------------------------------------------------------------------} constructor TFDPhysOracleEventMessage_CQN.Create(AQueryChange: TQueryChange); begin inherited Create; FQueryChange := AQueryChange; end; {-------------------------------------------------------------------------------} destructor TFDPhysOracleEventMessage_CQN.Destroy; begin FDFreeAndNil(FQueryChange); inherited Destroy; end; {-------------------------------------------------------------------------------} { TFDPhysOracleEventAlerter_CQN } {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.InternalAllocHandle; begin FService := TOCIService(GetConnection.CliObj); FNotifier := TOCIQueryNotification.Create(FService); FNotifier.ROWIDS := 1; FNotifier.CQ_QOSFLAGS := OCI_SUBSCR_CQ_QOS_QUERY; // FNotifier.QOSFLAGS := OCI_SUBSCR_QOS_RELIABLE; FNotifier.OnChange := DoQueryChanged; // Do not use InternalRegister, because it will be performed in // background thread, but below call must be performed in main thread. FNotifier.Register; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.RegisterQuery(AStmt: TOCIStatement); begin AStmt.CHNF_REGHANDLE := FNotifier.Handle; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.DoQueryChanged(ASender: TOCIQueryNotification; AChange: TOCIChangeDesc); function Opf2US(AFlags: ub4): TUpdateStatus; begin if AFlags and OCI_OPCODE_INSERT <> 0 then Result := usInserted else if AFlags and OCI_OPCODE_UPDATE <> 0 then Result := usModified else if AFlags and OCI_OPCODE_DELETE <> 0 then Result := usDeleted else Result := usUnmodified; end; var oChng: TQueryChange; i, j, k: Integer; oQry: TOCIChangeQueryDesc; oTab: TOCIChangeTableDesc; oRow: TOCIChangeRowDesc; begin case AChange.NFYTYPE of OCI_EVENT_QUERYCHANGE: for i := 0 to AChange.Queries.Count - 1 do begin oChng := TQueryChange.Create; try oQry := AChange.Queries[i]; oChng.FQueryID := oQry.QUERYID; SetLength(oChng.FTables, oQry.Tables.Count); for j := 0 to oQry.Tables.Count - 1 do begin oTab := oQry.Tables[j]; oChng.FTables[j].FName := oTab.NAME; if oTab.OPFLAGS and OCI_OPCODE_ALLROWS = 0 then begin SetLength(oChng.FTables[j].FRows, oTab.Rows.Count); for k := 0 to oTab.Rows.Count - 1 do begin oRow := oTab.Rows[k]; oChng.FTables[j].FRows[k].FRowID := oRow.ROWID; oChng.FTables[j].FRows[k].FOper := Opf2US(oRow.OPFLAGS); end; end; end; except FDFree(oChng); raise; end; FMsgThread.EnqueueMsg(TFDPhysOracleEventMessage_CQN.Create(oChng)); end; OCI_EVENT_DEREG: Unregister; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.InternalHandle(AEventMessage: TFDPhysEventMessage); begin FCurrentChange := TFDPhysOracleEventMessage_CQN(AEventMessage).FQueryChange; try InternalHandleEvent('', Unassigned); finally FCurrentChange := nil; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.InternalReleaseHandle; begin try // Do not use InternalUnRegister, because it will be performed in // background thread, but below call must be performed in main thread. FNotifier.Unregister; finally FDFreeAndNil(FNotifier); FService := nil; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.InternalSignal(const AEvent: String; const AArgument: Variant); begin FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_OraId]); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.InternalChangeHandlerModified( const AHandler: IFDPhysChangeHandler; const AEventName: String; AOperation: TOperation); var oCmd: TFDPhysOracleCommand; begin oCmd := AHandler.TrackCommand as TFDPhysOracleCommand; case AOperation of opInsert: oCmd.FEventAlerter := Self; opRemove: oCmd.FEventAlerter := nil; end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleEventAlerter_CQN.DoRefreshHandler(const AHandler: IFDPhysChangeHandler): Boolean; procedure AddRID(var AList: String; const AItem: String); begin if AList <> '' then AList := AList + ', '; AList := AList + '''' + AItem + ''''; end; var oBaseTabs: TFDDatSTableArray; oBaseTab: TFDDatSTable; oChng: TQueryChange; oConnMeta: IFDPhysConnectionMetadata; rName1: TFDPhysParsedName; rName2: TFDPhysParsedName; i, j: Integer; sMod, sIns, sDel, sSQL: String; oView: TFDDatSView; oRow: TFDDatSRow; oCmd: IFDPhysCommand; oSrcMan: TFDDatSManager; oSrcTab: TFDDatSTable; begin Result := False; try if AHandler.MergeManager <> nil then begin oBaseTabs := AHandler.MergeManager.RootTables; if Length(oBaseTabs) = 0 then Exit; oBaseTab := oBaseTabs[0]; end else if AHandler.MergeTable <> nil then oBaseTab := AHandler.MergeTable else Exit; i := oBaseTab.Columns.IndexOfName('ROWID'); if (i = -1) or not (caROWID in oBaseTab.Columns[i].ActualAttributes) then Exit; GetConnection.CreateMetadata(oConnMeta); oChng := TQueryChange(FCurrentChange); sMod := ''; sIns := ''; sDel := ''; oConnMeta.DecodeObjName(AHandler.TrackCommand.SourceObjectName, rName1, nil, [doUnquote]); for i := 0 to Length(oChng.FTables) - 1 do begin oConnMeta.DecodeObjName(oChng.FTables[i].FName, rName2, nil, [doUnquote]); if CompareText(rName1.FObject, rName2.FObject) = 0 then begin for j := 0 to Length(oChng.FTables[i].FRows) - 1 do begin case oChng.FTables[i].FRows[j].FOper of usUnmodified, usModified: AddRID(sMod, oChng.FTables[i].FRows[j].FRowID); usInserted: AddRID(sIns, oChng.FTables[i].FRows[j].FRowID); usDeleted: AddRID(sDel, oChng.FTables[i].FRows[j].FRowID); end; end; end; end; if (sMod = '') and (sIns = '') and (sDel = '') then Exit; if (AHandler.TrackCommand.State = csOpen) and (AHandler.TrackCommand.Options.FetchOptions.AutoFetchAll = afAll) then if AHandler.MergeManager <> nil then AHandler.TrackCommand.Fetch(AHandler.MergeManager, mmRely) else AHandler.TrackCommand.Fetch(AHandler.MergeTable, True, True); if sDel <> '' then begin oView := oBaseTab.Select('ROWID IN (' + sDel + ')'); try for i := oView.Rows.Count - 1 downto 0 do begin oRow := oView.Rows[i]; if GetOptions.MergeData in [dmDataSet, dmDataAppend, dmDataMerge] then FDFree(oRow) else begin if oRow.RowState <> rsUnchanged then oRow.RejectChanges(); oRow.ForceChange(rsDeleted); end; Result := True; end; finally FDFree(oView); end; end; if (sMod <> '') or (sIns <> '') then begin sSQL := ''; if sMod <> '' then sSQL := 'SELECT A.*, ' + IntToStr(Integer(rsModified)) + ' AS ' + S_FD_OpFlags + ' FROM (' + AHandler.TrackCommand.CommandText + ') A WHERE A.ROWID IN (' + sMod + ')'; if sIns <> '' then begin if sSQL <> '' then sSQL := sSQL + #13#10'UNION ALL'#13#10; sSQL := 'SELECT A.*, ' + IntToStr(Integer(rsInserted)) + ' AS ' + S_FD_OpFlags + ' FROM (' + AHandler.TrackCommand.CommandText + ') A WHERE A.ROWID IN (' + sIns + ')'; end; GetConnection.CreateCommand(oCmd); oCmd.Prepare(sSQL); oCmd.SourceObjectName := AHandler.TrackCommand.SourceObjectName; oCmd.SourceRecordSetName := AHandler.TrackCommand.SourceRecordSetName; oCmd.Open(True); if AHandler.MergeManager <> nil then begin oSrcMan := TFDDatSManager.Create; try oSrcMan.Assign(AHandler.MergeManager); oCmd.Fetch(oSrcMan, mmRely); AHandler.MergeManager.Merge(oSrcMan, GetOptions.MergeData, mmNone, []); for i := 0 to oSrcMan.Tables.Count - 1 do if oSrcMan.Tables[i].Rows.Count > 0 then begin Result := True; Break; end; finally FDFree(oSrcMan); end; end else begin oSrcTab := TFDDatSTable.Create; try oSrcTab.Assign(AHandler.MergeTable); oCmd.Fetch(oSrcTab, True, True); AHandler.MergeTable.Merge(oSrcTab, GetOptions.MergeData, mmNone, []); if oSrcTab.Rows.Count > 0 then Result := True; finally FDFree(oSrcTab); end; end; end; finally if Result then begin AHandler.ContentModified := False; AHandler.ResyncContent; end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleEventAlerter_CQN.InternalRefresh(const AHandler: IFDPhysChangeHandler); var i: Integer; oHnlr: IFDPhysChangeHandler; lRefreshed: Boolean; function CheckQueryID(const AHandler: IFDPhysChangeHandler): Boolean; var oCmd: TFDPhysOracleCommand; begin oCmd := AHandler.TrackCommand as TFDPhysOracleCommand; Result := (oCmd.FBase.FStmt <> nil) and (oCmd.FBase.FStmt.CQ_QUERYID = TQueryChange(FCurrentChange).FQueryID); end; begin if (GetSubscriptionName = '') or (FCurrentChange = nil) then begin inherited InternalRefresh(AHandler); Exit; end; lRefreshed := False; if AHandler <> nil then begin if IsRunning and AHandler.ContentModified and CheckQueryID(AHandler) then lRefreshed := DoRefreshHandler(AHandler); end else for i := FChangeHandlers.Count - 1 to 0 do begin if not IsRunning then Break; oHnlr := FChangeHandlers[i] as IFDPhysChangeHandler; if oHnlr.ContentModified and CheckQueryID(oHnlr) then lRefreshed := DoRefreshHandler(oHnlr) or lRefreshed; end; if not lRefreshed and IsRunning then inherited InternalRefresh(AHandler); end; {-------------------------------------------------------------------------------} { TFDPhysOracleCommand } {-------------------------------------------------------------------------------} constructor TFDPhysOracleCommand.Create(AConnectionObj: TFDPhysConnection); begin inherited Create(AConnectionObj); FInfoStack := TFDPtrList.Create; FCrsInfos := TFDPtrList.Create; end; {-------------------------------------------------------------------------------} destructor TFDPhysOracleCommand.Destroy; begin inherited Destroy; FDFreeAndNil(FInfoStack); FDFreeAndNil(FCrsInfos); end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.GetCliObj: Pointer; begin if FCurrentCrsInfo = nil then Result := FBase.FStmt else Result := FCurrentCrsInfo^.FStmt; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.SQL2FDColInfo(AOraDataType: TOCIVarDataType; AOraSize, AOraPrec, AOraScale: sb4; var AType: TFDDataType; var AAttrs: TFDDataAttributes; var ALen: LongWord; var APrec, AScale: Integer); var oFmt: TFDFormatOptions; begin AType := ovdt2addt[AOraDataType]; ALen := 0; APrec := 0; AScale := 0; Exclude(AAttrs, caFixedLen); Exclude(AAttrs, caBlobData); Include(AAttrs, caSearchable); case AOraDataType of otChar, otNChar: begin Include(AAttrs, caFixedLen); ALen := AOraSize; end; otString, otNString, otRaw: ALen := AOraSize; otROWID: begin Include(AAttrs, caFixedLen); Include(AAttrs, caAllowNull); Include(AAttrs, caROWID); ALen := AOraSize; end; otNumber, otDouble: begin APrec := AOraPrec; AScale := AOraScale; oFmt := FOptions.FormatOptions; if (AType = dtFmtBCD) and not oFmt.IsFmtBcd(APrec, AScale) then AType := dtBCD; end; otDateTime: AScale := 1000; otTimeStamp: if (AOraScale >= 0) and (AOraScale < 3) then AScale := C_FD_ScaleFactor[3 - AOraScale]; otIntervalYM, otIntervalDS: begin APrec := AOraPrec; if (AOraScale >= 0) and (AOraScale < 3) then AScale := C_FD_ScaleFactor[3 - AOraScale]; end; otCFile, otBFile: begin Include(AAttrs, caVolatile); Include(AAttrs, caBlobData); Exclude(AAttrs, caSearchable); end; otLong, otNLong, otLongRaw, otCLOB, otNCLOB, otBLOB: begin Include(AAttrs, caBlobData); Exclude(AAttrs, caSearchable); end; otCursor, otNestedDataSet: begin Include(AAttrs, caAllowNull); Exclude(AAttrs, caSearchable); end; end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.FDType2OCIType(AFDType: TFDDataType; AFixedLen, APLSQL, AInput: Boolean): TOCIVarDataType; var oConn: TFDPhysOracleConnection; begin if AFDType = dtBoolean then begin oConn := TFDPhysOracleConnection(FConnectionObj); Result := oConn.FBooleanFormat; if (Result = otBoolean) and not (APLSQL and (oConn.FServerVersion >= cvOracle120000) and (oConn.FEnv.Lib.Version >= cvOracle120000)) then Result := otInt32; end else if AFDType in [dtInt64, dtUInt64] then begin oConn := TFDPhysOracleConnection(FConnectionObj); if not ((oConn.FServerVersion >= cvOracle112000) and (oConn.FEnv.Lib.Version >= cvOracle112000)) then Result := otNumber else Result := addt2ovdt[AFDType]; end else begin Result := addt2ovdt[AFDType]; if AFixedLen and not (APLSQL and AInput) then if Result = otString then Result := otChar else if Result = otNString then Result := otNChar; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.DefParInfos(const ANm, ATpNm: String; AVt: TOCIVarType; FDt: TOCIVarDataType; ASz, APrec, AScale: sb4; AIsTable, AIsResult: Boolean); var oFmt: TFDFormatOptions; oPar: TFDParam; eSrcType, eDestType: TFDDataType; eSrcAttrs: TFDDataAttributes; eDestFldType: TFieldType; iSize: LongWord; iPrec, iScale: Integer; begin oFmt := FOptions.FormatOptions; oPar := GetParams.Add; oPar.Name := ANm; oPar.Position := oPar.Index + 1; if AIsResult then oPar.ParamType := ptResult else oPar.ParamType := vt2pt[AVt]; eSrcAttrs := []; SQL2FDColInfo(FDt, ASz, APrec, AScale, eSrcType, eSrcAttrs, iSize, iPrec, iScale); oFmt.ResolveDataType(ANm, ATpNm, eSrcType, iSize, iPrec, iScale, eDestType, iSize, True); oFmt.ColumnDef2FieldDef(eDestType, iSize, iPrec, iScale, eSrcAttrs, eDestFldType, iSize, iPrec, iScale); oPar.DataType := eDestFldType; oPar.FDDataType := eDestType; oPar.Size := iSize; oPar.Precision := iPrec; oPar.NumericScale := iScale; if AIsTable then oPar.ArrayType := atTable else oPar.ArrayType := atScalar; if (GetCommandKind = skStoredProc) and (FDt in [otCursor, otNestedDataSet]) then SetCommandKind(skStoredProcWithCrs); end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.GenerateStoredProcCallUsingOCI(const AName: TFDPhysParsedName): String; var sPackName, sProcName: String; oDescr: TOCIPLSQLDescriber; begin GetParams.Clear; sProcName := AName.FObject; sPackName := AName.FBaseObject; if AName.FSchema <> '' then if sPackName <> '' then sPackName := AName.FSchema + '.' + sPackName else sProcName := AName.FSchema + '.' + sProcName; if AName.FLink <> '' then if sPackName <> '' then sPackName := sPackName + '@' + AName.FLink else sProcName := sProcName + '@' + AName.FLink; oDescr := TOCIPLSQLDescriber.CreateForProc(TFDPhysOracleConnection(FConnectionObj).FService, sPackName, sProcName, GetOverload, Self); try oDescr.BoolType := FDType2OCIType(dtBoolean, False, True, True); oDescr.BindByName := GetParams.BindMode = pbByName; case oDescr.BoolType of otInt32: begin oDescr.BoolFalse := '0'; oDescr.BoolTrue := '1'; end; otString: begin oDescr.BoolFalse := '''F'''; oDescr.BoolTrue := '''T'''; end; end; oDescr.Describe; oDescr.LocateProc(False); Result := oDescr.BuildSQL(DefParInfos); finally FDFree(oDescr); end; if GetCommandKind = skStoredProc then SetCommandKind(skStoredProcNoCrs); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.CreateDefineInfo(ACrsInfo: PFDOraCrsDataRec); var i, iNChars: Integer; oSelItem: TOCISelectItem; oFmtOpts: TFDFormatOptions; rName: TFDPhysParsedName; oConnMeta: IFDPhysConnectionMetadata; lMetadata: Boolean; iLen: LongWord; iPrec, iScale: Integer; iUnit: ub4; pInfo: PFDOraVarInfoRec; oVar: TOCIVariable; begin FConnection.CreateMetadata(oConnMeta); oFmtOpts := FOptions.FormatOptions; lMetadata := GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone; iNChars := 0; ACrsInfo^.FHasFields := []; ACrsInfo^.FOpFlagsCol := 0; SetLength(ACrsInfo^.FColInfos, ACrsInfo^.FStmt.PARAM_COUNT); for i := 1 to Length(ACrsInfo^.FColInfos) do begin oSelItem := TOCISelectItem.Create(ACrsInfo^.FStmt, ACrsInfo^.FStmt.Service, i); try pInfo := @ACrsInfo^.FColInfos[i - 1]; pInfo^.FName := oSelItem.NAME; pInfo^.FPos := i; pInfo^.FVarType := odDefine; pInfo^.FOSrcType := oSelItem.DataType; pInfo^.FByteSize := oSelItem.DataSize; pInfo^.FLogSize := oSelItem.ColumnSize; pInfo^.FPrec := oSelItem.DataPrecision; pInfo^.FScale := oSelItem.DataScale; if oSelItem.TYPE_NAME <> '' then begin rName.FSchema := oSelItem.SCHEMA_NAME; rName.FObject := oSelItem.TYPE_NAME; pInfo^.FExtName := oConnMeta.EncodeObjName(rName, Self, [eoNormalize]); end; if oSelItem.IsNull then Include(pInfo^.FAttrs, caAllowNull) else if oSelItem.ColProperties and OCI_ATTR_COL_PROPERTY_IS_IDENTITY <> 0 then pInfo^.FAttrs := pInfo^.FAttrs + [caAutoInc, caAllowNull]; if pInfo^.FOSrcType = otROWID then Include(ACrsInfo^.FHasFields, hfRowIdExp) else if CompareText(pInfo^.FName, S_FD_OpFlags) = 0 then begin ACrsInfo^.FOpFlagsCol := i; pInfo^.FOSrcType := otInt32; pInfo^.FAttrs := pInfo^.FAttrs + [caAllowNull, caReadOnly, caInternal]; end; SQL2FDColInfo(pInfo^.FOSrcType, pInfo^.FLogSize, pInfo^.FPrec, pInfo^.FScale, pInfo^.FSrcType, pInfo^.FAttrs, iLen, iPrec, iScale); if lMetadata then // Oracle may return textual metadata columns as VARCHAR, // but FireDAC expects Unicode string if pInfo^.FSrcType = dtAnsiString then pInfo^.FDestType := dtWideString else if pInfo^.FSrcType = dtMemo then pInfo^.FDestType := dtWideMemo else pInfo^.FDestType := pInfo^.FSrcType else // mapping data types oFmtOpts.ResolveDataType(pInfo^.FName, pInfo^.FExtName, pInfo^.FSrcType, iLen, iPrec, iScale, pInfo^.FDestType, iLen, True); pInfo^.FOOutputType := FDType2OCIType(pInfo^.FDestType, pInfo^.FOSrcType in [otChar, otNChar], False, False); // OCI fails to fetch a string data as a long data, when OCIStmtExecute(0) // & OCIStmtFetch(<rowset>) is called instead of Describe & Execute & Fetch if (pInfo^.FOSrcType in [otString, otChar, otNString, otNChar, otRaw]) and (pInfo^.FOOutputType in [otLong, otNLong, otLongRaw]) then pInfo^.FOOutputType := pInfo^.FOSrcType; if pInfo^.FOOutputType <> otUnknown then begin SQL2FDColInfo(pInfo^.FOOutputType, iLen, pInfo^.FPrec, pInfo^.FScale, pInfo^.FOutputType, pInfo^.FAttrs, iLen, iPrec, iScale); if pInfo^.FDestType = pInfo^.FSrcType then pInfo^.FOOutputType := pInfo^.FOSrcType; end else begin SQL2FDColInfo(pInfo^.FOSrcType, iLen, pInfo^.FPrec, pInfo^.FScale, pInfo^.FOutputType, pInfo^.FAttrs, iLen, iPrec, iScale); pInfo^.FOOutputType := pInfo^.FOSrcType; end; pInfo^.FADScale := iScale; // if data type conversion is required and a value will be returned // as string, then use the value display size as a bind size if pInfo^.FOOutputType <> pInfo^.FOSrcType then begin case pInfo^.FDestType of dtByteString: iUnit := SizeOf(Byte); dtAnsiString: iUnit := SizeOf(TFDAnsiChar); dtWideString: iUnit := SizeOf(WideChar); else iUnit := 0; end; if iUnit <> 0 then begin pInfo^.FLogSize := oSelItem.DISP_SIZE; if pInfo^.FLogSize = 0 then pInfo^.FLogSize := iLen; pInfo^.FByteSize := pInfo^.FLogSize * iUnit; end; end; if (pInfo^.FSrcType = dtBCD) and (pInfo^.FOutputType = dtFmtBCD) then pInfo^.FOutputType := dtBCD; if CheckFetchColumn(pInfo^.FSrcType, pInfo^.FAttrs) or (pInfo^.FDestType in [dtRowSetRef, dtCursorRef, dtRowRef, dtArrayRef]) then begin pInfo^.FVar := TOCIVariable.Create(ACrsInfo^.FStmt); oVar := pInfo^.FVar; oVar.VarType := odDefine; oVar.Position := pInfo^.FPos; oVar.DumpLabel := pInfo^.FName; oVar.DataType := pInfo^.FOOutputType; if pInfo^.FOOutputType in [otString, otChar, otNString, otNChar, otRaw] then begin oVar.DataSize := pInfo^.FByteSize; oVar.CharSize := pInfo^.FLogSize; end; if pInfo^.FOOutputType in [otNString, otNChar, otNLong] then begin Include(ACrsInfo^.FHasFields, hfNChar); Inc(iNChars); end else if pInfo^.FOOutputType in otHBlobs then Include(ACrsInfo^.FHasFields, hfBlob) else if oVar.LongData then Include(ACrsInfo^.FHasFields, hfLongData); end else pInfo^.FVar := nil; finally FDFree(oSelItem); end; end; // For SELECT FOR UPDATE statement add an implicit ROWID column // and bind it at Position=0 if (GetCommandKind = skSelectForLock) and (ACrsInfo = @FBase) and not (hfRowIdExp in ACrsInfo^.FHasFields) and (ACrsInfo^.FStmt.Env.Lib.Version >= cvOracle111000) then begin Include(ACrsInfo^.FHasFields, hfRowIdImp); i := Length(ACrsInfo^.FColInfos); SetLength(ACrsInfo^.FColInfos, i + 1); pInfo := @ACrsInfo^.FColInfos[i]; pInfo^.FName := 'ROWID'; pInfo^.FPos := 0; pInfo^.FVarType := odDefine; pInfo^.FOSrcType := otROWID; pInfo^.FOOutputType := otChar; pInfo^.FByteSize := C_RowIdLen; pInfo^.FLogSize := C_RowIdLen; pInfo^.FAttrs := [caSearchable, caAllowNull, caROWID, caInternal]; pInfo^.FSrcType := dtAnsiString; pInfo^.FDestType := dtAnsiString; pInfo^.FOutputType := dtAnsiString; pInfo^.FVar := TOCIVariable.Create(ACrsInfo^.FStmt); oVar := pInfo^.FVar; oVar.VarType := odDefine; oVar.Position := pInfo^.FPos; oVar.DumpLabel := pInfo^.FName; oVar.DataType := pInfo^.FOOutputType; oVar.DataSize := pInfo^.FByteSize; oVar.CharSize := pInfo^.FLogSize; end; if iNChars > 2 then Include(ACrsInfo^.FHasFields, hfManyNChars); if ACrsInfo^.FStmt.Handle <> nil then ResetDefVars(ACrsInfo, GetRowsetSize(ACrsInfo, FOptions.FetchOptions.ActualRowsetSize)); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.DestroyDefineInfo(ACrsInfo: PFDOraCrsDataRec); var i: Integer; pInfo: PFDOraVarInfoRec; begin if Length(ACrsInfo^.FColInfos) <> 0 then try for i := 0 to Length(ACrsInfo^.FColInfos) - 1 do begin pInfo := @ACrsInfo^.FColInfos[i]; if pInfo^.FCrsInfo <> nil then begin try try DestroyDefineInfo(pInfo^.FCrsInfo); finally FDFreeAndNil(pInfo^.FCrsInfo^.FStmt); end; except // no exceptions visible end; FreeMem(pInfo^.FCrsInfo); pInfo^.FCrsInfo := nil; end; if pInfo^.FVar <> nil then begin try pInfo^.FVar.BindOff; except // no exceptions visible end; FDFreeAndNil(pInfo^.FVar); end; end; finally SetLength(ACrsInfo^.FColInfos, 0); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.CreateBindInfo; var i: Integer; oParams: TFDParams; oParam: TFDParam; pInfo: PFDOraVarInfoRec; oFmtOpts: TFDFormatOptions; oResOpts: TFDResourceOptions; eDestFldType: TFieldType; iDestPrec, iDestScale: Integer; lWasVBlob: Boolean; eAttrs: TFDDataAttributes; iPrec, iScale: Integer; iLen: LongWord; iArrSize: Integer; oVar: TOCIVariable; begin FBindVarsDirty := False; FHasParams := []; oParams := GetParams; if oParams.Count = 0 then Exit; oFmtOpts := FOptions.FormatOptions; oResOpts := FOptions.ResourceOptions; lWasVBlob := False; iArrSize := oParams.ArraySize; if iArrSize > oResOpts.ArrayDMLSize then iArrSize := oResOpts.ArrayDMLSize; SetLength(FParInfos, oParams.Count); for i := 0 to Length(FParInfos) - 1 do begin oParam := oParams[i]; pInfo := @FParInfos[i]; // fill in base info case GetParams.BindMode of pbByName: begin pInfo^.FPos := 0; pInfo^.FName := ':' + oParam.Name; if Length(pInfo^.FName) > 30 then pInfo^.FName := Copy(pInfo^.FName, 1, 30 - 1 - Length(IntToStr(i + 1))) + '_' + IntToStr(i + 1); pInfo^.FExtName := pInfo^.FName; end; pbByNumber: begin pInfo^.FPos := oParam.Position; pInfo^.FName := ''; pInfo^.FExtName := IntToStr(pInfo^.FPos); end; end; pInfo^.FIsCaseSensitive := oParam.IsCaseSensitive; pInfo^.FIsPLSQLTable := (oParam.ArrayType = atTable); pInfo^.FParamType := oParam.ParamType; pInfo^.FDataType := oParam.DataType; pInfo^.FVarType := pt2vt[pInfo^.FParamType]; // resolve data type if oParam.DataType = ftUnknown then ParTypeUnknownError(oParam); eDestFldType := ftUnknown; iDestPrec := 0; oFmtOpts.ResolveFieldType('', oParam.DataTypeName, oParam.DataType, oParam.FDDataType, oParam.Size, oParam.Precision, oParam.NumericScale, eDestFldType, pInfo^.FLogSize, iDestPrec, iDestScale, pInfo^.FSrcType, pInfo^.FDestType, False); // Oracle does not support Delphi Currency data type, so map it to BCD if pInfo^.FDestType = dtCurrency then pInfo^.FDestType := dtBCD; pInfo^.FOSrcType := FDType2OCIType(pInfo^.FSrcType, oParam.DataType in [ftFixedChar, ftBytes, ftFixedWideChar], FBase.FStmt.STMT_TYPE in [OCI_STMT_BEGIN, OCI_STMT_DECLARE], oParam.ParamType in [ptInput, ptInputOutput]); pInfo^.FOOutputType := FDType2OCIType(pInfo^.FDestType, eDestFldType in [ftFixedChar, ftBytes, ftFixedWideChar], FBase.FStmt.STMT_TYPE in [OCI_STMT_BEGIN, OCI_STMT_DECLARE], oParam.ParamType in [ptInput, ptInputOutput]); if (pInfo^.FOOutputType = otUnknown) or (eDestFldType = ftBytes) then ParTypeMapError(oParam); eAttrs := []; SQL2FDColInfo(pInfo^.FOOutputType, oParam.Size, oParam.Precision, oParam.NumericScale, pInfo^.FOutputType, eAttrs, iLen, iPrec, iScale); // for driver dtBCD and dtFtmBCD are the same if (pInfo^.FDestType = dtBCD) and (pInfo^.FOutputType = dtFmtBCD) then pInfo^.FOutputType := dtBCD; // limit maximum string parameter size in PL/SQL blocks if (pInfo^.FOOutputType in [otString, otChar, otNString, otNChar, otRaw]) and (pInfo^.FLogSize = 0) and (oFmtOpts.MaxStringSize <> C_FD_DefMaxStrSize) and (GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs, skExecute]) then pInfo^.FLogSize := oFmtOpts.MaxStringSize; // set size in bytes if pInfo^.FOOutputType in [otString, otChar, otLong] then pInfo^.FByteSize := pInfo^.FLogSize * SizeOf(TFDAnsiChar) else if pInfo^.FOOutputType in [otNString, otNChar, otNLong] then pInfo^.FByteSize := pInfo^.FLogSize * SizeOf(WideChar) else pInfo^.FByteSize := pInfo^.FLogSize; // At moment table adapter handles BLOB's in UPDATE and INSERT only // in RETURNING phrase -> MUST BE CHANGED !!!! // Otherwise, INSERT INTO All_types (TCLOB) VALUES (:TCLOB) with // temporary CLOB will not work - "capability not supported" if (pInfo^.FOOutputType in otHBlobs) and (pInfo^.FVarType in [odIn, odOut, odInOut]) and ((TFDPhysOracleConnection(FConnectionObj).FEnv.Lib.Version < cvOracle81000) or oFmtOpts.DataSnapCompatibility) and (FBase.FStmt.STMT_TYPE in [OCI_STMT_UPDATE, OCI_STMT_INSERT]) and (FBase.FStmt.IS_RETURNING <> 0) then begin pInfo^.FVarType := odRet; Include(FHasParams, hpHBlobsRet); end else begin if pInfo^.FVarType in [odUnknown, odIn, odInOut] then Include(FHasParams, hpInput); if pInfo^.FVarType in [odOut, odInOut, odRet] then Include(FHasParams, hpOutput); end; if pInfo^.FOOutputType in otCrsTypes then Include(FHasParams, hpCursors); if pInfo^.FOOutputType in otVBlobs then if lWasVBlob then Include(FHasParams, hpManyVLobs) else lWasVBlob := True; // check if it is array if pInfo^.FIsPLSQLTable then pInfo^.FArrayLen := oParam.ArraySize else pInfo^.FArrayLen := iArrSize; // create OCI variable pInfo^.FVar := TOCIVariable.Create(FBase.FStmt); oVar := pInfo^.FVar; oVar.VarType := pInfo^.FVarType; oVar.Position := pInfo^.FPos; oVar.Name := pInfo^.FName; oVar.DumpLabel := pInfo^.FExtName; oVar.IsCaseSensitive := pInfo^.FIsCaseSensitive; oVar.IsPLSQLTable := pInfo^.FIsPLSQLTable; oVar.DataType := pInfo^.FOOutputType; if (pInfo^.FByteSize <> 0) and ((pInfo^.FOOutputType in [otString, otChar, otNString, otNChar, otRaw]) or (pInfo^.FOOutputType in otVBlobs)) then begin oVar.DataSize := pInfo^.FByteSize; oVar.CharSize := pInfo^.FLogSize; end; oVar.ArrayLen := pInfo^.FArrayLen; oVar.Bind; if oVar.LongData then Include(FHasParams, hpLongData); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.DestroyBindInfo; var i: Integer; pInfo: PFDOraVarInfoRec; begin try for i := 0 to Length(FParInfos) - 1 do begin pInfo := @FParInfos[i]; if pInfo^.FVar <> nil then begin try pInfo^.FVar.BindOff; except // no exceptions visible end; FDFreeAndNil(pInfo^.FVar); end; end; finally SetLength(FParInfos, 0); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.DestroyCrsInfo; var i: Integer; pCrsInfo: PFDOraCrsDataRec; lBaseDestroyed: Boolean; begin lBaseDestroyed := (FCrsInfos.Count > 0) and (FCrsInfos[0] = @FBase); try for i := 0 to FCrsInfos.Count - 1 do begin pCrsInfo := PFDOraCrsDataRec(FCrsInfos[i]); DestroyDefineInfo(pCrsInfo); FDFreeAndNil(pCrsInfo^.FStmt); if pCrsInfo <> @FBase then FreeMem(pCrsInfo, SizeOf(TFDOraCrsDataRec)); end; finally FCrsInfos.Clear; if not lBaseDestroyed then begin DestroyDefineInfo(@FBase); FDFreeAndNil(FBase.FStmt); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.SetupStatement(AStmt: TOCIStatement); var oFmtOpts: TFDFormatOptions; begin oFmtOpts := FOptions.FormatOptions; AStmt.DecimalSep := TFDPhysOracleConnection(FConnectionObj).FDecimalSep; AStmt.PieceBuffLen := C_FD_DefPieceBuffLen; AStmt.StrsTrim := oFmtOpts.StrsTrim; AStmt.StrsEmpty2Null := oFmtOpts.StrsEmpty2Null; AStmt.StrsTrim2Len := oFmtOpts.StrsTrim2Len; AStmt.MapWC2NChar := not oFmtOpts.ADOCompatibility; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.InternalPrepare; var lMetaInfo: Boolean; i: Integer; pParInfo: PFDOraVarInfoRec; pCrsInfo: PFDOraCrsDataRec; hndl: pOCIHandle; uiTmp: ub4; oConnMeta: IFDPhysConnectionMetadata; rName: TFDPhysParsedName; oConn: TFDPhysOracleConnection; begin FInfoStack.Clear; FCurrentCrsInfo := nil; FActiveCrs := -1; FBindVarsDirty := False; FHasParams := []; lMetaInfo := GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone; FillChar(FBase, SizeOf(TFDOraCrsDataRec), 0); // generate metadata SQL command if lMetaInfo then begin GetSelectMetaInfoParams(rName); GenerateSelectMetaInfo(rName); if FDbCommandText = '' then Exit; end // generate stored proc call SQL command else if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin GetConnection.CreateMetadata(oConnMeta); FDbCommandText := ''; if fiMeta in FOptions.FetchOptions.Items then begin oConnMeta.DecodeObjName(Trim(GetCommandText()), rName, Self, [doNormalize]); FDbCommandText := GenerateStoredProcCallUsingOCI(rName); end; if FDbCommandText = '' then begin oConnMeta.DecodeObjName(Trim(GetCommandText()), rName, Self, []); GenerateStoredProcCall(rName, GetCommandKind); end; end; // adjust SQL command GenerateLimitSelect(); GenerateParamMarkers(); oConn := TFDPhysOracleConnection(FConnectionObj); FBase.FStmt := TOCIStatement.Create(oConn.FEnv, oConn.FService, TFDPhysOracleTransaction(FTransactionObj).FTransaction, Self); SetupStatement(FBase.FStmt); FBase.FStmt.Prepare(FDbCommandText); if not (FBase.FStmt.STMT_TYPE in [OCI_STMT_EXPLAIN1, OCI_STMT_EXPLAIN2]) then CreateBindInfo; FCursorCanceled := True; if FBase.FStmt.STMT_TYPE = OCI_STMT_SELECT then begin // CreateDefineInfo is moved to InternalOpen, after a query will be executed. // Otherwise, here FStmt.Describe must be called before CreateDefineInfo call. // Describe leads to SIR-580 and slowdowns simple queries execution. FCrsInfos.Add(@FBase); FActiveCrs := 0; if GetCommandKind = skUnknown then SetCommandKind(skSelect); if not lMetaInfo and (GetCommandKind in [skSelect, skSelectForLock]) and (FBase.FStmt.Env.Lib.Version >= cvOracle111000) and FBase.FStmt.FetchImplRowids() then SetCommandKind(skSelectForLock); end else if FBase.FStmt.STMT_TYPE in [OCI_STMT_BEGIN, OCI_STMT_DECLARE] then begin for i := 0 to Length(FParInfos) - 1 do begin pParInfo := @FParInfos[i]; if (pParInfo^.FOOutputType = otCursor) and (pParInfo^.FVar <> nil) then begin pParInfo^.FVar.GetData(0, @hndl, uiTmp); GetMem(pCrsInfo, SizeOf(TFDOraCrsDataRec)); FillChar(pCrsInfo^, SizeOf(TFDOraCrsDataRec), 0); FCrsInfos.Add(pCrsInfo); pCrsInfo^.FParent := @FBase; pCrsInfo^.FStmt := TOCIStatement.CreateUsingHandle(oConn.FEnv, oConn.FService, nil, hndl); SetupStatement(pCrsInfo^.FStmt); end; end; if FCrsInfos.Count > 0 then begin if GetCommandKind in [skUnknown, skStoredProc] then SetCommandKind(skStoredProcWithCrs); FActiveCrs := 0; end else begin if GetCommandKind in [skUnknown, skStoredProc] then SetCommandKind(skStoredProcNoCrs); end; end else if GetCommandKind = skUnknown then SetCommandKind(skOther); end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.InternalUnprepare; begin if FBase.FStmt = nil then Exit; InternalClose; DestroyBindInfo; DestroyCrsInfo; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.IsActiveCursorValid: Boolean; begin Result := (FActiveCrs >= 0) and (FActiveCrs < FCrsInfos.Count); end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.GetActiveCursor: PFDOraCrsDataRec; begin if not IsActiveCursorValid then begin if (GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]) and (GetParams.Count = 0) and not (fiMeta in FOptions.FetchOptions.Items) then FDException(Self, [S_FD_LPhys, S_FD_OraId], er_FD_OraNoCursorParams, []) else FDException(Self, [S_FD_LPhys, S_FD_OraId], er_FD_OraNoCursor, []); end; Result := PFDOraCrsDataRec(FCrsInfos[FActiveCrs]); end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; var pColInfo: PFDOraVarInfoRec; pParCrs: PFDOraCrsDataRec; hndl: pOCIHandle; uiTmp: ub4; begin Result := OpenBlocked; if Result then if ATabInfo.FSourceID = -1 then begin ATabInfo.FSourceName := GetCommandText; ATabInfo.FSourceID := 1; ATabInfo.FOriginName := ''; FCurrentCrsInfo := GetActiveCursor; FCurrentCrsInfo^.FColIndex := 0; end else begin pColInfo := @FCurrentCrsInfo^.FColInfos[ATabInfo.FSourceID - 1]; ATabInfo.FSourceName := pColInfo^.FName; ATabInfo.FSourceID := ATabInfo.FSourceID; ATabInfo.FOriginName := ''; if pColInfo^.FCrsInfo = nil then begin GetMem(pColInfo^.FCrsInfo, SizeOf(TFDOraCrsDataRec)); FillChar(pColInfo^.FCrsInfo^, SizeOf(TFDOraCrsDataRec), 0); pColInfo^.FVar.GetData(0, @hndl, uiTmp); pColInfo^.FCrsInfo.FStmt := TOCIStatement.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, TFDPhysOracleConnection(FConnectionObj).FService, nil, hndl); // There must be assigned a parent cursor pColInfo^.FCrsInfo^.FParent := @FBase; SetupStatement(pColInfo^.FCrsInfo.FStmt); // A cursor nested into a nested cursor does not work. // Only the first level cursors are supported. pParCrs := pColInfo^.FCrsInfo^.FParent; if not pParCrs^.FExecuted then begin pParCrs^.FExecuted := True; pParCrs^.FStmt.Fetch(GetRowsetSize(pColInfo^.FCrsInfo, FOptions.FetchOptions.ActualRowsetSize)); end; CreateDefineInfo(pColInfo^.FCrsInfo); end; FInfoStack.Add(FCurrentCrsInfo); FCurrentCrsInfo := pColInfo^.FCrsInfo; FCurrentCrsInfo^.FColIndex := 0; end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; var pColInfo: PFDOraVarInfoRec; begin if FCurrentCrsInfo^.FColIndex < Length(FCurrentCrsInfo^.FColInfos) then begin pColInfo := @FCurrentCrsInfo^.FColInfos[FCurrentCrsInfo^.FColIndex]; if pColInfo^.FPos = 0 then AColInfo.FSourceID := Length(FCurrentCrsInfo^.FColInfos) else AColInfo.FSourceID := pColInfo^.FPos; AColInfo.FSourceName := pColInfo^.FName; AColInfo.FSourceTypeName := pColInfo^.FExtName; AColInfo.FSourceType := pColInfo^.FSrcType; AColInfo.FType := pColInfo^.FDestType; AColInfo.FLen := pColInfo^.FLogSize; AColInfo.FPrec := pColInfo^.FPrec; AColInfo.FScale := pColInfo^.FADScale; AColInfo.FAttrs := pColInfo^.FAttrs; AColInfo.FForceAddOpts := []; if caAutoInc in AColInfo.FAttrs then Include(AColInfo.FForceAddOpts, coAfterInsChanged); Inc(FCurrentCrsInfo^.FColIndex); Result := True; end else begin if FInfoStack.Count > 0 then begin FCurrentCrsInfo := PFDOraCrsDataRec(FInfoStack.Last); FInfoStack.Delete(FInfoStack.Count - 1); end; Result := False; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.SetParamValues(ATimes, AOffset: Integer; AFromParIndex: Integer; AIntoReturning: Boolean); var j, i: Integer; uiLen: ub4; oParams: TFDParams; oParam: TFDParam; pParInfo: PFDOraVarInfoRec; oFmtOpts: TFDFormatOptions; iArrSize: Integer; function CreateLocator(AParInfo: PFDOraVarInfoRec; AType: TOCIVarDataType; AIndex: ub4): TOCIIntLocator; var hndl: pOCIHandle; uiTmp: ub4; begin if AType in [otCFile, otBFile] then FDException(Self, [S_FD_LPhys, S_FD_OraId], er_FD_OraCantAssFILE, [AParInfo^.FExtName]); if AParInfo^.FVar.GetData(AIndex, @hndl, uiTmp) then begin Result := TOCIIntLocator.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FService, hndl); Result.National := (AType = otNCLOB); end else begin Result := nil; FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_OraId]); end; end; function CreateTimeStamp(AParInfo: PFDOraVarInfoRec; AIndex: ub4): TOCITimeStamp; var hndl: pOCIHandle; uiTmp: ub4; begin AParInfo^.FVar.SetIsNull(AIndex, False); AParInfo^.FVar.GetData(AIndex, @hndl, uiTmp); Result := TOCITimestamp.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, hndl); end; function CreateTimeInterval(AParInfo: PFDOraVarInfoRec; AIndex: ub4): TOCITimeInterval; var hndl: pOCIHandle; uiTmp: ub4; begin AParInfo^.FVar.SetIsNull(AIndex, False); AParInfo^.FVar.GetData(AIndex, @hndl, uiTmp); Result := TOCITimeInterval.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, hndl, AParInfo^.FOOutputType); end; procedure ProcessArrayItem(AParam: TFDParam; AParInfo: PFDOraVarInfoRec; AVarIndex, AParIndex: Integer); var pData: pUb1; uiSrcDataLen, uiDestDataLen, uiLen: LongWord; oIntLoc: TOCIIntLocator; oTS: TOCITimeStamp; oTI: TOCITimeInterval; lExtStream: Boolean; oIntStr, oExtStr: TStream; begin // if null if (AParam.DataType <> ftStream) and AParam.IsNulls[AParIndex] then AParInfo^.FVar.SetData(AVarIndex, nil, 0) // assign BLOB stream else if AParam.IsStreams[AParIndex] then begin oExtStr := AParam.AsStreams[AParIndex]; lExtStream := (oExtStr <> nil) and not ((oExtStr is TOCILobLocatorStream) and (TOCILobLocatorStream(oExtStr).OwningObj = Self)); if (AParam.DataType <> ftStream) and not lExtStream or not (AParInfo^.FOOutputType in [otCLOB, otNCLOB, otBLOB, otCFile, otBFile]) then UnsupParamObjError(AParam); oIntLoc := CreateLocator(AParInfo, AParInfo^.FOOutputType, AVarIndex); oIntStr := TOCILobLocatorStream.Create(oIntLoc, Self); try if lExtStream then oIntStr.CopyFrom(oExtStr, -1) else AParam.AsStreams[AParIndex] := oIntStr; finally if lExtStream then FDFree(oIntStr); end; end // conversion is not required else if (AParInfo^.FSrcType = AParInfo^.FOutputType) {$IFDEF NEXTGEN} and not (AParInfo^.FOOutputType in [otString, otChar, otLong, otCLOB]) {$ENDIF} then // if byte string data, then optimizing - get data directly case AParInfo^.FOOutputType of otString, otChar, otNString, otNChar, otLong, otNLong, otRaw, otLongRaw, otCLOB, otNCLOB, otBLOB, otCFile, otBFile: begin uiLen := 0; pData := nil; AParam.GetBlobRawData(uiLen, PByte(pData), AParIndex); if AParInfo^.FOOutputType in [otString, otChar, otNString, otNChar, otLong, otNLong, otRaw, otLongRaw] then AParInfo^.FVar.SetData(AVarIndex, pData, uiLen) else if AParInfo^.FOOutputType in [otCLOB, otNCLOB, otBLOB, otCFile, otBFile] then begin oIntLoc := CreateLocator(AParInfo, AParInfo^.FOOutputType, AVarIndex); try if uiLen <> 0 then oIntLoc.Write(pData, uiLen, 1); finally FDFree(oIntLoc); end; end; end; otTimeStamp: begin oTS := CreateTimeStamp(AParInfo, AVarIndex); try FBuffer.Check; AParam.GetData(FBuffer.Ptr, AParIndex); oTS.SetAsSQLTimeStamp(PSQLTimeStamp(FBuffer.Ptr)^); finally FDFree(oTS); end; end; otIntervalYM, otIntervalDS: begin oTI := CreateTimeInterval(AParInfo, AVarIndex); try FBuffer.Check; AParam.GetData(FBuffer.Ptr, AParIndex); oTI.SetAsSQLTimeInterval(PFDSQLTimeInterval(FBuffer.Ptr)^); finally FDFree(oTI); end; end; else FBuffer.Check; AParam.GetData(FBuffer.Ptr, AParIndex); AParInfo^.FVar.SetData(AVarIndex, FBuffer.Ptr, AParam.GetDataLength(AParIndex)); end // conversion is required else begin // calculate buffer size to move param values uiSrcDataLen := AParam.GetDataLength(AParIndex); uiDestDataLen := 0; FBuffer.Extend(uiSrcDataLen, uiDestDataLen, AParInfo^.FSrcType, AParInfo^.FOutputType); // get, convert and set parameter value AParam.GetData(FBuffer.Ptr, AParIndex); oFmtOpts.ConvertRawData(AParInfo^.FSrcType, AParInfo^.FOutputType, FBuffer.Ptr, uiSrcDataLen, FBuffer.FBuffer, FBuffer.Size, uiDestDataLen, TFDPhysOracleConnection(FConnectionObj).FEnv.DataEncoder); case AParInfo^.FOOutputType of otCLOB, otNCLOB, otBLOB, otCFile, otBFile: begin oIntLoc := CreateLocator(AParInfo, AParInfo^.FOOutputType, AVarIndex); try if uiDestDataLen <> 0 then oIntLoc.Write(FBuffer.Ptr, uiDestDataLen, 1); finally FDFree(oIntLoc); end; end; otTimeStamp: begin oTS := CreateTimeStamp(AParInfo, AVarIndex); try oTS.SetAsSQLTimeStamp(PSQLTimeStamp(FBuffer.Ptr)^); finally FDFree(oTS); end; end; otIntervalYM, otIntervalDS: begin oTI := CreateTimeInterval(AParInfo, AVarIndex); try oTI.SetAsSQLTimeInterval(PFDSQLTimeInterval(FBuffer.Ptr)^); finally FDFree(oTI); end; end; else AParInfo^.FVar.SetData(AVarIndex, FBuffer.Ptr, uiDestDataLen); end; end; end; begin oParams := GetParams; if oParams.Count = 0 then Exit; if oParams.Count <> Length(FParInfos) then ParSetChangedError(Length(FParInfos), oParams.Count); oFmtOpts := GetOptions.FormatOptions; iArrSize := oParams.ArraySize; if ATimes < iArrSize then iArrSize := ATimes; for i := 0 to oParams.Count - 1 do begin oParam := oParams[i]; pParInfo := @FParInfos[i]; CheckParamMatching(oParam, pParInfo^.FDataType, pParInfo^.FParamType, 0); if pParInfo^.FVar <> nil then if not AIntoReturning then begin // check that parameter array size matches to bind variable array len if (AFromParIndex = -1) or (oParam.ArrayType <> atScalar) then if pParInfo^.FIsPLSQLTable then uiLen := ub4(oParam.ArraySize) else uiLen := ub4(iArrSize) else uiLen := 1; if pParInfo^.FVar.ArrayLen <> uiLen then begin pParInfo^.FVar.ArrayLen := uiLen; pParInfo^.FVar.Bind; end else if FBindVarsDirty then // if the sizes are the same and variables was modified, then init them if oParam.ArrayType <> atArray then pParInfo^.FVar.ResetBuffer(-1, -1) else pParInfo^.FVar.ResetBuffer(ATimes, AOffset); if pParInfo^.FVarType in [odUnknown, odIn, odInOut] then if oParam.ArrayType = atScalar then ProcessArrayItem(oParam, pParInfo, 0, -1) else if oParam.ArrayType = atTable then begin if uiLen > 0 then for j := 0 to uiLen - 1 do ProcessArrayItem(oParam, pParInfo, j, j); end else if AFromParIndex = -1 then for j := AOffset to ATimes - 1 do ProcessArrayItem(oParam, pParInfo, j, j) else ProcessArrayItem(oParam, pParInfo, 0, AFromParIndex); end else if (pParInfo^.FVarType = odRet) and (pParInfo^.FOOutputType in otHBlobs) then ProcessArrayItem(oParam, pParInfo, 0, -1); end; if not AIntoReturning then FBindVarsDirty := True; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.GetParamValues(ATimes, AOffset: Integer); var i, j: Integer; oParams: TFDParams; oParam: TFDParam; pParInfo: PFDOraVarInfoRec; oFmtOpts: TFDFormatOptions; function CreateLocator(AParInfo: PFDOraVarInfoRec; AType: TOCIVarDataType; AIndex: ub4): TOCILobLocator; var hndl: pOCIHandle; uiTmp: ub4; begin AParInfo^.FVar.GetData(AIndex, @hndl, uiTmp); if AType in [otCLOB, otNCLOB, otBLOB] then begin Result := TOCIIntLocator.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FService, hndl); Result.National := (AType = otNCLOB); end else begin Result := TOCIExtLocator.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FService, hndl); if not Result.IsOpen then Result.Open(True); end; end; function CreateTimeStamp(AParInfo: PFDOraVarInfoRec; AIndex: ub4): TOCITimeStamp; var hndl: pOCIHandle; uiTmp: ub4; begin AParInfo^.FVar.GetData(AIndex, @hndl, uiTmp); Result := TOCITimestamp.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, hndl); end; function CreateTimeInterval(AParInfo: PFDOraVarInfoRec; AIndex: ub4): TOCITimeInterval; var hndl: pOCIHandle; uiTmp: ub4; begin AParInfo^.FVar.GetData(AIndex, @hndl, uiTmp); Result := TOCITimeInterval.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, hndl, AParInfo^.FOOutputType); end; procedure ProcessArrayItem(AParam: TFDParam; AParInfo: PFDOraVarInfoRec; AVarIndex, AParIndex: Integer); var pData: pUb1; uiLen, uiByteLen: ub4; uiDestDataLen: LongWord; oLoc: TOCILobLocator; oTS: TOCITimeStamp; oTI: TOCITimeInterval; oExtStr, oIntStr: TStream; lExtStream: Boolean; begin // null pData := nil; uiLen := 0; if not AParInfo^.FVar.GetData(AVarIndex, pData, uiLen, True) then AParam.Clear(AParIndex) // assign BLOB stream else if AParam.IsStreams[AParIndex] then begin oExtStr := AParam.AsStreams[AParIndex]; lExtStream := (oExtStr <> nil) and not ((oExtStr is TOCILobLocatorStream) and (TOCILobLocatorStream(oExtStr).OwningObj = Self)); if (AParam.DataType <> ftStream) and not lExtStream or not (AParInfo^.FOOutputType in [otCLOB, otNCLOB, otBLOB, otCFile, otBFile]) then UnsupParamObjError(AParam); oLoc := CreateLocator(AParInfo, AParInfo^.FOOutputType, AVarIndex); oIntStr := TOCILobLocatorStream.Create(oLoc, Self); try if lExtStream then oExtStr.CopyFrom(oIntStr, -1) else AParam.AsStreams[AParIndex] := oIntStr; finally if lExtStream then FDFree(oIntStr); end; end // conversion is not required else if (AParInfo^.FOutputType = AParInfo^.FSrcType) {$IFDEF NEXTGEN} and not (AParInfo^.FOOutputType in [otString, otChar, otLong, otCLOB]) {$ENDIF} then // byte string data, then optimizing - get data directly case AParInfo^.FOOutputType of otCLOB, otNCLOB, otBLOB, otCFile, otBFile: begin oLoc := CreateLocator(AParInfo, AParInfo^.FOOutputType, AVarIndex); try uiLen := oLoc.Length; pData := pUb1(AParam.SetBlobRawData(uiLen, nil, AParIndex)); if uiLen > 0 then uiLen := oLoc.Read(pData, uiLen, 1); finally FDFree(oLoc); end; end; otLongRaw: AParam.SetBlobRawData(uiLen, PByte(pData), AParIndex); otString, otChar, otLong, otNChar, otNString, otNLong, otRaw: AParam.SetData(PByte(pData), uiLen, AParIndex); otTimeStamp: begin uiLen := SizeOf(TSQLTimeStamp); oTS := CreateTimeStamp(AParInfo, AVarIndex); try FBuffer.Check(uiLen); oTS.GetAsSQLTimeStamp(PSQLTimeStamp(FBuffer.Ptr)^); AParam.SetData(FBuffer.Ptr, uiLen, AParIndex); finally FDFree(oTS); end; end; otIntervalYM, otIntervalDS: begin uiLen := SizeOf(TFDSQLTimeInterval); oTI := CreateTimeInterval(AParInfo, AVarIndex); try FBuffer.Check(uiLen); oTI.GetAsSQLTimeInterval(PFDSQLTimeInterval(FBuffer.Ptr)^); AParam.SetData(FBuffer.Ptr, uiLen, AParIndex); finally FDFree(oTI); end; end; else FBuffer.Check(uiLen); AParInfo^.FVar.GetData(AVarIndex, FBuffer.Ptr, uiLen); AParam.SetData(FBuffer.Ptr, uiLen, AParIndex); end // conversion is required else begin case AParInfo^.FOOutputType of otCLOB, otNCLOB, otBLOB, otCFile, otBFile: begin oLoc := CreateLocator(AParInfo, AParInfo^.FOOutputType, AVarIndex); try uiLen := oLoc.Length; uiByteLen := uiLen; if oLoc.National then uiByteLen := uiByteLen * SizeOf(WideChar); pData := pUb1(FBuffer.Check(uiByteLen)); if uiLen > 0 then uiLen := oLoc.Read(pData, uiLen, 1); finally FDFree(oLoc); end; end; otTimeStamp: begin uiLen := SizeOf(TSQLTimeStamp); oTS := CreateTimeStamp(AParInfo, AVarIndex); try FBuffer.Check(uiLen); oTS.GetAsSQLTimeStamp(PSQLTimeStamp(FBuffer.Ptr)^); finally FDFree(oTS); end; end; otIntervalYM, otIntervalDS: begin uiLen := SizeOf(TFDSQLTimeInterval); oTI := CreateTimeInterval(AParInfo, AVarIndex); try FBuffer.Check(uiLen); oTI.GetAsSQLTimeInterval(PFDSQLTimeInterval(FBuffer.Ptr)^); finally FDFree(oTI); end; end; else FBuffer.Check(uiLen); AParInfo^.FVar.GetData(AVarIndex, FBuffer.Ptr, uiLen); end; uiDestDataLen := 0; FBuffer.Extend(uiLen, uiDestDataLen, AParInfo^.FOutputType, AParInfo^.FSrcType); uiDestDataLen := 0; oFmtOpts.ConvertRawData(AParInfo^.FOutputType, AParInfo^.FSrcType, FBuffer.Ptr, uiLen, FBuffer.FBuffer, FBuffer.Size, uiDestDataLen, TFDPhysOracleConnection(FConnectionObj).FEnv.DataEncoder); AParam.SetData(FBuffer.Ptr, uiDestDataLen, AParIndex); end; end; begin oParams := GetParams; if oParams.Count = 0 then Exit; if oParams.Count <> Length(FParInfos) then ParSetChangedError(Length(FParInfos), oParams.Count); oFmtOpts := FOptions.FormatOptions; for i := 0 to oParams.Count - 1 do begin oParam := oParams[i]; pParInfo := @FParInfos[i]; CheckParamMatching(oParam, pParInfo^.FDataType, pParInfo^.FParamType, 0); if (pParInfo^.FVar <> nil) and (pParInfo^.FVarType in [odOut, odInOut, odRet]) and not (pParInfo^.FOOutputType in [otCursor, otNestedDataSet]) and (not (pParInfo^.FOOutputType in otHBlobs) or not (pParInfo^.FParamType in [ptUnknown, ptInput])) then if oParam.ArrayType <> atScalar then begin oParam.ArraySize := pParInfo^.FVar.ArrayLen; if pParInfo^.FVar.ArrayLen > 0 then for j := 0 to pParInfo^.FVar.ArrayLen - 1 do ProcessArrayItem(oParam, pParInfo, j, j); end else for j := AOffset to ATimes - 1 do ProcessArrayItem(oParam, pParInfo, j, j); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.CloseImplicitCursors; var i: Integer; pCrsInfo: PFDOraCrsDataRec; begin for i := FCrsInfos.Count - 1 downto 0 do begin pCrsInfo := PFDOraCrsDataRec(FCrsInfos[i]); if pCrsInfo^.FImplicit then begin DestroyDefineInfo(pCrsInfo); FDFreeAndNil(pCrsInfo^.FStmt); FreeMem(pCrsInfo, SizeOf(TFDOraCrsDataRec)); FCrsInfos.Delete(i); end; end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.GetImplicitCursors: Boolean; var i: Integer; hndl: pOCIHandle; pCrsInfo: PFDOraCrsDataRec; oConn: TFDPhysOracleConnection; begin Result := False; oConn := TFDPhysOracleConnection(FConnectionObj); if not ((oConn.FServerVersion >= cvOracle120000) and (oConn.FEnv.Lib.Version >= cvOracle120000)) then Exit; CloseImplicitCursors; for i := 1 to FBase.FStmt.IMPLICIT_RESULT_COUNT do begin hndl := FBase.FStmt.NextResultSet(); if hndl = nil then Break; GetMem(pCrsInfo, SizeOf(TFDOraCrsDataRec)); FillChar(pCrsInfo^, SizeOf(TFDOraCrsDataRec), 0); FCrsInfos.Add(pCrsInfo); pCrsInfo^.FParent := @FBase; pCrsInfo^.FStmt := TOCIStatement.CreateUsingHandle(oConn.FEnv, oConn.FService, nil, hndl); pCrsInfo^.FStmt.Ref := True; pCrsInfo^.FImplicit := True; SetupStatement(pCrsInfo^.FStmt); CreateDefineInfo(pCrsInfo); Result := True; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.RebindCursorParams; var i, j, iCrsInfo: Integer; pParInfo: PFDOraVarInfoRec; pCrsInfo: PFDOraCrsDataRec; pColInfo: PFDOraVarInfoRec; hndl: pOCIHandle; uiTmp: ub4; begin if FCrsInfos.Count = 0 then Exit; iCrsInfo := 0; for i := 0 to Length(FParInfos) - 1 do begin pParInfo := @FParInfos[i]; if (pParInfo^.FOOutputType = otCursor) and (pParInfo^.FVar <> nil) then begin pParInfo^.FVar.GetData(0, @hndl, uiTmp); pCrsInfo := PFDOraCrsDataRec(FCrsInfos[iCrsInfo]); pCrsInfo^.FStmt.Handle := hndl; pCrsInfo^.FExecuted := False; DestroyDefineInfo(pCrsInfo); CreateDefineInfo(pCrsInfo); for j := 0 to Length(pCrsInfo^.FColInfos) - 1 do begin pColInfo := @pCrsInfo^.FColInfos[j]; if pColInfo^.FVar <> nil then begin pColInfo^.FVar.BindOff; pColInfo^.FVar.BindTo(pCrsInfo^.FStmt); end; end; Inc(iCrsInfo); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.GetServerFeedback; begin case FBase.FStmt.SQLFNCODE of // ALTER SESSION 52: TFDPhysOracleConnection(FConnectionObj).UpdateCurrentSchema; // CREATE and ALTER PL/SQL objects 24, 25, 91, 92, 94, 95, 97, 98, 59, 60, 77, 80, 81, 82: TFDPhysOracleConnection(FConnectionObj).GetPLSQLErrors; end; case FBase.FStmt.STMT_TYPE of OCI_STMT_UPDATE, OCI_STMT_DELETE, OCI_STMT_INSERT, OCI_STMT_BEGIN, OCI_STMT_DECLARE: TFDPhysOracleConnection(FConnectionObj).GetServerOutput; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); var i: Integer; oFO: TFDFetchOptions; begin ACount := 0; TFDPhysOracleConnection(FConnectionObj).UpdateServerOutput; try if FEventAlerter <> nil then FEventAlerter.RegisterQuery(FBase.FStmt); oFO := FOptions.FetchOptions; if (hpLongData in FHasParams) and not (GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs, skExecute]) then for i := AOffset to ATimes - 1 do begin if FHasParams <> [] then SetParamValues(1, 0, i, False); FBase.FStmt.Execute(1, 0, oFO.Mode = fmExactRecsMax, TFDPhysOracleTransaction(FTransactionObj).GetAutoCommit); Inc(ACount, FBase.FStmt.LastRowCount); end else begin if FHasParams <> [] then SetParamValues(ATimes, AOffset, -1, False); try FBase.FStmt.Execute(ATimes, AOffset, oFO.Mode = fmExactRecsMax, TFDPhysOracleTransaction(FTransactionObj).GetAutoCommit); finally if FBase.FStmt <> nil then ACount := FBase.FStmt.LastRowCount; end; end; FBase.FExecuted := True; if hpHBlobsRet in FHasParams then SetParamValues(ATimes, AOffset, -1, True); if hpOutput in FHasParams then GetParamValues(ATimes, AOffset); if hpCursors in FHasParams then RebindCursorParams; if GetImplicitCursors then FActiveCrs := -1; except on E: EFDDBEngineException do begin if not (E.Kind in [ekCmdAborted, ekServerGone]) then GetServerFeedback; raise; end; end; GetServerFeedback; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.InternalAbort; begin TFDPhysOracleConnection(FConnectionObj).FService.Break(True); end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.GetRowsetSize(ACrsInfo: PFDOraCrsDataRec; ARowsetSize: LongWord): LongWord; begin Result := ARowsetSize; if (hfNChar in ACrsInfo^.FHasFields) and ([hfLongData, hfBlob] * ACrsInfo^.FHasFields <> []) or (hfManyNChars in ACrsInfo^.FHasFields) then Result := 1; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.InternalOpen(var ACount: TFDCounter): Boolean; var oFO: TFDFetchOptions; pCrsInfo: PFDOraCrsDataRec; lMainCursor, lExactFetch: Boolean; iRowsetSize, iPrefetchRows, iFetchRows: Integer; begin ACount := 0; if not GetNextRecordSet then FActiveCrs := 0; if not FCursorCanceled then begin Result := True; Exit; end; if not IsActiveCursorValid then begin if FCrsInfos.Count = 0 then InternalExecute(GetParams.ArraySize, 0, ACount); Result := InternalNextRecordSet; Exit; end; pCrsInfo := GetActiveCursor; oFO := FOptions.FetchOptions; iPrefetchRows := oFO.ActualRowsetSize; iRowsetSize := GetRowsetSize(pCrsInfo, iPrefetchRows); lMainCursor := (pCrsInfo = @FBase); lExactFetch := (oFO.Mode = fmExactRecsMax); if lMainCursor then begin iFetchRows := 0; if FHasParams <> [] then SetParamValues(1, 0, -1, False); end else begin iFetchRows := iRowsetSize; if not FBase.FExecuted then InternalExecute(1, 0, ACount); end; ResetDefVars(pCrsInfo, iRowsetSize); try if lMainCursor and (FEventAlerter <> nil) then FEventAlerter.RegisterQuery(FBase.FStmt); // When iPrefetchRows will lead to "strange" issues, // then change it back to iRowsetSize if lExactFetch then pCrsInfo^.FStmt.PREFETCH_ROWS := iPrefetchRows + 1 else pCrsInfo^.FStmt.PREFETCH_ROWS := iPrefetchRows; pCrsInfo^.FStmt.Execute(iFetchRows, 0, False, TFDPhysOracleTransaction(FTransactionObj).GetAutoCommit); if lMainCursor then begin // If defines are not yet created, then create them here, // after a query was executed with iFetchRows = 0. if Length(FBase.FColInfos) = 0 then CreateDefineInfo(@FBase); if hpHBlobsRet in FHasParams then SetParamValues(1, 0, -1, True); if hpOutput in FHasParams then GetParamValues(1, 0); GetImplicitCursors; GetServerFeedback; end; FCursorCanceled := False; pCrsInfo^.FExecuted := not lMainCursor; Result := True; except on E: Exception do begin if lExactFetch and (E is EOCINativeException) and (EOCINativeException(E).Kind in [ekNoDataFound, ekTooManyRows]) then // FDQA checks FDCode = er_FD_AccExactFetchMismatch in fmExactRecsMax tests EOCINativeException(E).FDCode := er_FD_AccExactMismatch; FCursorCanceled := True; InternalClose; raise; end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.InternalClose; var pCrsInfo: PFDOraCrsDataRec; begin if IsActiveCursorValid then begin pCrsInfo := GetActiveCursor; if not FCursorCanceled then begin FCursorCanceled := True; if pCrsInfo^.FExecuted then pCrsInfo^.FStmt.CancelCursor; end; pCrsInfo^.FExecuted := False; end; FInfoStack.Clear; FCurrentCrsInfo := nil; if not GetNextRecordSet then begin FBase.FExecuted := False; CloseImplicitCursors; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleCommand.ResetDefVars(ACrsInfo: PFDOraCrsDataRec; ARowsetSize: LongWord); var i: Integer; pInfo: PFDOraVarInfoRec; begin for i := 0 to Length(ACrsInfo^.FColInfos) - 1 do begin pInfo := @ACrsInfo^.FColInfos[i]; if pInfo^.FVar <> nil then if (pInfo^.FVar.Handle = nil) or (pInfo^.FVar.ArrayLen <> ARowsetSize) then begin pInfo^.FVar.ArrayLen := ARowsetSize; pInfo^.FVar.Bind; end else if not ACrsInfo^.FExecuted then pInfo^.FVar.ResetBuffer(-1, -1); end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.ProcessRowSet(ACrsInfo: PFDOraCrsDataRec; ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; var i, j: Integer; oRow: TFDDatSRow; oFmt: TFDFormatOptions; lMetadata: Boolean; [unsafe] oCol: TFDDatSColumn; function CreateLocator(AColInfo: PFDOraVarInfoRec; AType: TOCIVarDataType; AIndex: ub4): TOCILobLocator; var hndl: pOCIHandle; uiTmp: ub4; begin AColInfo^.FVar.GetData(AIndex, @hndl, uiTmp); if AType in [otCLOB, otNCLOB, otBLOB] then begin Result := TOCIIntLocator.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FService, hndl); Result.National := (AType = otNCLOB); end else begin Result := TOCIExtLocator.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FService, hndl); if not Result.IsOpen then Result.Open(True); end; end; function CreateTimeStamp(AColInfo: PFDOraVarInfoRec; AIndex: ub4): TOCITimeStamp; var hndl: pOCIHandle; uiTmp: ub4; begin AColInfo^.FVar.GetData(AIndex, @hndl, uiTmp); Result := TOCITimestamp.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, hndl); end; function CreateTimeInterval(AColInfo: PFDOraVarInfoRec; AIndex: ub4): TOCITimeInterval; var hndl: pOCIHandle; uiTmp: ub4; begin AColInfo^.FVar.GetData(AIndex, @hndl, uiTmp); Result := TOCITimeInterval.CreateUsingHandle( TFDPhysOracleConnection(FConnectionObj).FEnv, hndl, AColInfo^.FOOutputType); end; procedure ProcessColumn(AColIndex: Integer; ARow: TFDDatSRow; AColInfo: PFDOraVarInfoRec; ARowIndex, ARowsetSize: LongWord); var pData: pUb1; uiLen, uiByteLen: ub4; iDestDataLen: LongWord; oLoc: TOCILobLocator; oTS: TOCITimeStamp; oTI: TOCITimeInterval; pCrsInfo: PFDOraCrsDataRec; oNestedTable: TFDDatSTable; i: Integer; iRowsetSize: LongWord; oVar: TOCIVariable; begin pData := nil; uiLen := 0; if (AColInfo^.FVar = nil) or not CheckFetchColumn(AColInfo^.FSrcType, AColInfo^.FAttrs) then Exit // null else if not AColInfo^.FVar.GetData(ARowIndex, pData, uiLen, True) then ARow.SetData(AColIndex, nil, 0) // nested dataset else if AColInfo^.FOOutputType = otNestedDataSet then begin pCrsInfo := AColInfo^.FCrsInfo; iRowsetSize := GetRowsetSize(pCrsInfo, ARowsetSize); pCrsInfo^.FStmt.AttachToHandle(ppOCIHandle(pData)^); for i := 0 to Length(pCrsInfo^.FColInfos) - 1 do begin oVar := pCrsInfo^.FColInfos[i].FVar; oVar.BindOff; oVar.ArrayLen := iRowsetSize; oVar.BindTo(pCrsInfo^.FStmt); end; pCrsInfo^.FExecuted := False; pCrsInfo^.FStmt.Execute(iRowsetSize, 0, False, TFDPhysOracleTransaction(FTransactionObj).GetAutoCommit); pCrsInfo^.FExecuted := True; oNestedTable := ARow.Table.Columns[AColIndex].NestedTable; while ProcessRowSet(pCrsInfo, oNestedTable, ARow, iRowsetSize) = iRowsetSize do ; ARow.Fetched[AColIndex] := True; end // conversion is not required else if (AColInfo^.FOutputType = AColInfo^.FDestType) {$IFDEF NEXTGEN} and not (AColInfo^.FOOutputType in [otString, otChar, otLong, otCLOB]) {$ENDIF} then // byte string data, then optimizing - get data directly case AColInfo^.FOOutputType of otCLOB, otNCLOB, otBLOB, otCFile, otBFile: begin oLoc := CreateLocator(AColInfo, AColInfo^.FOOutputType, ARowIndex); try uiLen := oLoc.Length; pData := pUb1(ARow.BeginDirectWriteBlob(AColIndex, uiLen)); try if uiLen > 0 then uiLen := oLoc.Read(pData, uiLen, 1); finally ARow.EndDirectWriteBlob(AColIndex, uiLen); end; finally FDFree(oLoc); end; end; otTimeStamp: begin oTS := CreateTimeStamp(AColInfo, ARowIndex); try if not oTS.IsNull then begin oTS.GetAsSQLTimeStamp(PSQLTimeStamp(FBuffer.Ptr)^); ARow.SetData(AColIndex, FBuffer.Ptr, SizeOf(TSQLTimeStamp)); end; finally FDFree(oTS); end; end; otIntervalYM, otIntervalDS: begin oTI := CreateTimeInterval(AColInfo, ARowIndex); try if not oTI.IsNull then begin oTI.GetAsSQLTimeInterval(PFDSQLTimeInterval(FBuffer.Ptr)^); ARow.SetData(AColIndex, FBuffer.Ptr, SizeOf(TFDSQLTimeInterval)); end; finally FDFree(oTI); end; end; otString, otNString, otChar, otNChar, otLong, otNLong, otRaw, otLongRaw: ARow.SetData(AColIndex, pData, uiLen); else FBuffer.Check(uiLen); AColInfo^.FVar.GetData(ARowIndex, FBuffer.Ptr, uiLen); ARow.SetData(AColIndex, FBuffer.Ptr, uiLen); end // conversion is required else begin case AColInfo^.FOOutputType of otCLOB, otBLOB, otCFile, otBFile: begin oLoc := CreateLocator(AColInfo, AColInfo^.FOOutputType, ARowIndex); try uiLen := oLoc.Length; uiByteLen := uiLen; if oLoc.National then uiByteLen := uiByteLen * SizeOf(WideChar); pData := pUb1(FBuffer.Check(uiByteLen)); if uiLen > 0 then uiLen := oLoc.Read(pData, uiLen, 1); finally FDFree(oLoc); end; end; else FBuffer.Check(uiLen); AColInfo^.FVar.GetData(ARowIndex, FBuffer.Ptr, uiLen); end; iDestDataLen := 0; oFmt.ConvertRawData(AColInfo^.FOutputType, AColInfo^.FDestType, FBuffer.Ptr, uiLen, FBuffer.FBuffer, FBuffer.Size, iDestDataLen, TFDPhysOracleConnection(FConnectionObj).FEnv.DataEncoder); ARow.SetData(AColIndex, FBuffer.Ptr, iDestDataLen); end; end; procedure ProcessMetaColumn(AColIndex: Integer; ARow: TFDDatSRow; AColInfo: PFDOraVarInfoRec; ARowIndex: LongWord); var pData: pUb1; uiLen: ub4; iDestDataLen: LongWord; oVar, oVar2: TOCIVariable; procedure RemoveDoubleQuotas; begin if AColInfo^.FOOutputType in [otString, otChar] then begin if PFDAnsiString(pData)^ = TFDAnsiChar('"') then begin pData := pUb1(PFDAnsiString(pData) + 1); Dec(uiLen, 2); end; end else begin if PWideChar(pData)^ = '"' then begin pData := pUb1(PWideChar(pData) + 1); Dec(uiLen, 2); end; end; end; begin pData := nil; uiLen := 0; oVar := AColInfo^.FVar; oVar2 := nil; // The mkIndexFields special case COLUMN_EXPRESSION vs COLUMN_NAME if (GetMetaInfoKind = mkIndexFields) and (AColIndex = 5) then begin oVar2 := ACrsInfo^.FColInfos[9].FVar; if oVar2.GetData(ARowIndex, pData, uiLen, True) then oVar := oVar2; end; if oVar = nil then Exit else if AColInfo^.FPos = 1 then ARow.SetData(0, ATable.Rows.Count + 1) else if not oVar.GetData(ARowIndex, pData, uiLen, True) then ARow.SetData(AColIndex, nil, 0) else if AColInfo^.FOOutputType in [otString, otNString, otChar, otNChar] then begin // The mkIndexFields special case COLUMN_EXPRESSION vs COLUMN_NAME if oVar = oVar2 then RemoveDoubleQuotas; if uiLen > ATable.Columns[AColIndex].Size then uiLen := ATable.Columns[AColIndex].Size; ARow.SetData(AColIndex, pData, uiLen); end else if AColInfo^.FOOutputType in [otLong, otNLong, otLongRaw] then ARow.SetData(AColIndex, pData, uiLen) else begin FBuffer.Check(uiLen); oVar.GetData(ARowIndex, FBuffer.Ptr, uiLen); iDestDataLen := 0; if AColInfo^.FDestType in [dtInt32, dtDouble, dtBCD, dtFmtBCD] then oFmt.ConvertRawData(AColInfo^.FOutputType, ATable.Columns[AColIndex].DataType, FBuffer.Ptr, uiLen, FBuffer.FBuffer, FBuffer.Size, iDestDataLen, TFDPhysOracleConnection(FConnectionObj).FEnv.DataEncoder); ARow.SetData(AColIndex, FBuffer.Ptr, iDestDataLen); end; end; procedure ProcessOpFlags(ARow: TFDDatSRow; ACrsInfo: PFDOraCrsDataRec); var eState: TFDDatSRowState; begin eState := TFDDatSRowState(ACrsInfo^.FColInfos[ACrsInfo^.FOpFlagsCol - 1].FVar.AsInteger); if eState in [rsInserted, rsDeleted, rsModified] then oRow.ForceChange(eState); end; begin if not ACrsInfo^.FExecuted then begin ResetDefVars(ACrsInfo, ARowsetSize); ACrsInfo^.FStmt.Fetch(ARowsetSize); end else ACrsInfo^.FExecuted := False; oFmt := FOptions.FormatOptions; lMetadata := GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone; for i := 0 to Integer(ACrsInfo^.FStmt.LastRowCount) - 1 do begin oRow := ATable.NewRow(False); try for j := 0 to ATable.Columns.Count - 1 do begin oCol := ATable.Columns[j]; if oCol.SourceID > 0 then if lMetadata then ProcessMetaColumn(j, oRow, @ACrsInfo^.FColInfos[oCol.SourceID - 1], i) else ProcessColumn(j, oRow, @ACrsInfo^.FColInfos[oCol.SourceID - 1], i, ARowsetSize); end; if AParentRow <> nil then begin oRow.ParentRow := AParentRow; AParentRow.Fetched[ATable.Columns.ParentCol] := True; end; ATable.Rows.Add(oRow); if ACrsInfo^.FOpFlagsCol > 0 then ProcessOpFlags(oRow, ACrsInfo); except FDFree(oRow); raise; end; end; Result := ACrsInfo^.FStmt.LastRowCount; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; var iRowsetSize, iRows: LongWord; pCrsInfo: PFDOraCrsDataRec; begin Result := 0; if (GetMetaInfoKind <> mkNone) and not IsActiveCursorValid then Exit; pCrsInfo := GetActiveCursor; iRowsetSize := GetRowsetSize(pCrsInfo, ARowsetSize); while Result < ARowsetSize do begin iRows := ProcessRowSet(pCrsInfo, ATable, AParentRow, iRowsetSize); Inc(Result, iRows); if iRows <> iRowsetSize then Break; end; end; {-------------------------------------------------------------------------------} function TFDPhysOracleCommand.InternalNextRecordSet: Boolean; var iCount: TFDCounter; begin if not FBase.FExecuted or (FCrsInfos.Count = 0) then begin Result := False; Exit; end; if FActiveCrs < FCrsInfos.Count then Inc(FActiveCrs); if FActiveCrs < FCrsInfos.Count then Result := InternalOpen(iCount) else begin FBase.FExecuted := False; CloseImplicitCursors; Result := False; end; end; {-----------------------------------------------------------------------------} initialization FDRegisterDriverClass(TFDPhysOracleDriver); finalization FDUnregisterDriverClass(TFDPhysOracleDriver); end.
{*******************************************************} { } { Borland Delphi Run-time Library } { Control Panel extension DLL definitions } { } { Copyright (c) 1985-1999, Microsoft Corporation } { } { Translator: Inprise Corporation } { } {*******************************************************} unit CPL; {$HPPEMIT '#include <cpl.h>'} interface uses Messages, Windows; { General rules for being installed in the Control Panel: 1) The DLL must export a function named CPlApplet which will handle the messages discussed below. 2) If the applet needs to save information in CONTROL.INI minimize clutter by using the application name [MMCPL.appletname]. 2) If the applet is refrenced in CONTROL.INI under [MMCPL] use the following form: ... [MMCPL] uniqueName=c:\mydir\myapplet.dll ... The order applet DLL's are loaded by CONTROL.EXE is: 1) MAIN.CPL is loaded from the windows system directory. 2) Installable drivers that are loaded and export the CplApplet() routine. 3) DLL's specified in the [MMCPL] section of CONTROL.INI. 4) DLL's named *.CPL from windows system directory. CONTROL.EXE will answer this message and launch an applet WM_CPL_LAUNCH wParam - window handle of calling app lParam - LPTSTR of name of applet to launch WM_CPL_LAUNCHED wParam - TRUE/FALSE if applet was launched lParam - NULL CONTROL.EXE will post this message to the caller when the applet returns (ie., when wParam is a valid window handle) } const {$EXTERNALSYM WM_CPL_LAUNCH} WM_CPL_LAUNCH = (WM_USER+1000); {$EXTERNALSYM WM_CPL_LAUNCHED} WM_CPL_LAUNCHED = (WM_USER+1001); // The messages CPlApplet() must handle: {$EXTERNALSYM CPL_DYNAMIC_RES} CPL_DYNAMIC_RES = 0; { This constant may be used in place of real resource IDs for the idIcon, idName or idInfo members of the CPLINFO structure. Normally, the system uses these values to extract copies of the resources and store them in a cache. Once the resource information is in the cache, the system does not need to load a CPL unless the user actually tries to use it. CPL_DYNAMIC_RES tells the system not to cache the resource, but instead to load the CPL every time it needs to display information about an item. This allows a CPL to dynamically decide what information will be displayed, but is SIGNIFICANTLY SLOWER than displaying information from a cache. Typically, CPL_DYNAMIC_RES is used when a control panel must inspect the runtime status of some device in order to provide text or icons to display. } {$EXTERNALSYM CPL_INIT} CPL_INIT = 1; { This message is sent to indicate CPlApplet() was found. lParam1 and lParam2 are not defined. Return TRUE or FALSE indicating whether the control panel should proceed. } {$EXTERNALSYM CPL_GETCOUNT} CPL_GETCOUNT = 2; { This message is sent to determine the number of applets to be displayed. lParam1 and lParam2 are not defined. Return the number of applets you wish to display in the control panel window. } {$EXTERNALSYM CPL_INQUIRE} CPL_INQUIRE = 3; { This message is sent for information about each applet. lParam1 is the applet number to register, a value from 0 to(CPL_GETCOUNT - 1). lParam2 is a far ptr to a CPLINFO structure. Fill in CPL_INFO's idIcon, idName, idInfo and lData fields with the resource id for an icon to display, name and description string ids, and a long data item associated with applet #lParam1. } {$EXTERNALSYM CPL_SELECT} CPL_SELECT = 4; { This message is sent when the applet's icon has been clicked upon. lParam1 is the applet number which was selected. lParam2 is the applet's lData value. } {$EXTERNALSYM CPL_DBLCLK} CPL_DBLCLK = 5; { This message is sent when the applet's icon has been double-clicked upon. lParam1 is the applet number which was selected. lParam2 is the applet's lData value. This message should initiate the applet's dialog box. } {$EXTERNALSYM CPL_STOP} CPL_STOP = 6; { This message is sent for each applet when the control panel is exiting. lParam1 is the applet number. lParam2 is the applet's lData value. Do applet specific cleaning up here. } {$EXTERNALSYM CPL_EXIT} CPL_EXIT = 7; { This message is sent just before the control panel calls FreeLibrary. lParam1 and lParam2 are not defined. Do non-applet specific cleaning up here. } {$EXTERNALSYM CPL_NEWINQUIRE} CPL_NEWINQUIRE = 8; { This is the same as CPL_INQUIRE execpt lParam2 is a pointer to a NEWCPLINFO structure. this will be sent before the CPL_INQUIRE and if it is responed to (return != 0) CPL_INQUIRE will not be sent } {$EXTERNALSYM CPL_STARTWPARMS} CPL_STARTWPARMS = 9; { This message parallels CPL_DBLCLK in that the applet should initiate its dialog box. where it differs is that this invocation is coming out of RUNDLL, and there may be some extra directions for execution. lParam1: the applet number. lParam2: an LPSTR to any extra directions that might exist. returns: TRUE if the message was handled; FALSE if not. } {$EXTERNALSYM CPL_SETUP} CPL_SETUP = 200; { This message is internal to the Control Panel and MAIN applets. It is only sent when an applet is invoked from the Command line during system installation. } type //A function prototype for CPlApplet() {$EXTERNALSYM APPLET_PROC} APPLET_PROC = function (hwndCPl: THandle; uMsg: DWORD; lParam1, lParam2: Longint): Longint; stdcall; TCPLApplet = APPLET_PROC; //The data structure CPlApplet() must fill in. PCPLInfo = ^TCPLInfo; {$EXTERNALSYM tagCPLINFO} tagCPLINFO = packed record idIcon: Integer; // icon resource id, provided by CPlApplet() idName: Integer; // name string res. id, provided by CPlApplet() idInfo: Integer; // info string res. id, provided by CPlApplet() lData : Longint; // user defined data end; {$EXTERNALSYM CPLINFO} CPLINFO = tagCPLINFO; TCPLInfo = tagCPLINFO; PNewCPLInfoA = ^TNewCPLInfoA; PNewCPLInfoW = ^TNewCPLInfoW; PNewCPLInfo = PNewCPLInfoA; {$EXTERNALSYM tagNEWCPLINFOA} tagNEWCPLINFOA = packed record dwSize: DWORD; // similar to the commdlg dwFlags: DWORD; dwHelpContext: DWORD; // help context to use lData: Longint; // user defined data hIcon: HICON; // icon to use, this is owned by CONTROL.EXE (may be deleted) szName: array[0..31] of AnsiChar; // short name szInfo: array[0..63] of AnsiChar; // long name (status line) szHelpFile: array[0..127] of AnsiChar; // path to help file to use end; {$EXTERNALSYM tagNEWCPLINFOW} tagNEWCPLINFOW = packed record dwSize: DWORD; // similar to the commdlg dwFlags: DWORD; dwHelpContext: DWORD; // help context to use lData: Longint; // user defined data hIcon: HICON; // icon to use, this is owned by CONTROL.EXE (may be deleted) szName: array[0..31] of WideChar; // short name szInfo: array[0..63] of WideChar; // long name (status line) szHelpFile: array[0..127] of WideChar; // path to help file to use end; {$EXTERNALSYM tagNEWCPLINFO} tagNEWCPLINFO = tagNEWCPLINFOA; {$EXTERNALSYM NEWCPLINFOA} NEWCPLINFOA = tagNEWCPLINFOA; {$EXTERNALSYM NEWCPLINFOW} NEWCPLINFOW = tagNEWCPLINFOW; {$EXTERNALSYM NEWCPLINFO} NEWCPLINFO = NEWCPLINFOA; TNewCPLInfoA = tagNEWCPLINFOA; TNewCPLInfoW = tagNEWCPLINFOW; TNewCPLInfo = TNewCPLInfoA; implementation end.
unit BCEditor.Editor.Selection.Colors; interface uses Classes, Graphics, BCEditor.Consts; type TBCEditorSelectedColor = class(TPersistent) strict private FBackground: TColor; FForeground: TColor; FOnChange: TNotifyEvent; procedure SetBackground(Value: TColor); procedure SetForeground(Value: TColor); public constructor Create; procedure Assign(Source: TPersistent); override; published property Background: TColor read FBackground write SetBackground default clSelectionColor; property Foreground: TColor read FForeground write SetForeground default clHighLightText; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation { TBCEditorSelectedColor } constructor TBCEditorSelectedColor.Create; begin inherited; FBackground := clSelectionColor; FForeground := clHighLightText; end; procedure TBCEditorSelectedColor.Assign(Source: TPersistent); begin if Assigned(Source) and (Source is TBCEditorSelectedColor) then with Source as TBCEditorSelectedColor do begin Self.FBackground := FBackground; Self.FForeground := FForeground; if Assigned(Self.FOnChange) then Self.FOnChange(Self); end else inherited Assign(Source); end; procedure TBCEditorSelectedColor.SetBackground(Value: TColor); begin if FBackground <> Value then begin FBackground := Value; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TBCEditorSelectedColor.SetForeground(Value: TColor); begin if FForeground <> Value then begin FForeground := Value; if Assigned(FOnChange) then FOnChange(Self); end; end; end.