text
stringlengths
14
6.51M
unit MetrickMakkeiba_3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, StrUtils, Grids; const numberWords=20; numberUsefullWords=4; type TAdjacencyMatrix=array [1..numberWords,1..numberWords] of boolean; TarrayCodeString=array [1..numberWords] of string; TUsefullWords=array [1..numberUsefullWords] of string; TUsefullSet = set of char; pointerTypeRecord=^recordStack; recordStack=record data:string; index:word; next:pointerTypeRecord; end; TMetriickMakkeiba = class(TForm) MemoCodeText: TMemo; ButtonOk: TButton; EditCountTops: TEdit; LabelCountTops: TLabel; LabelCountDest: TLabel; EditCountDest: TEdit; MatrixAdjacency: TStringGrid; LabelCountNumberMakkeib: TLabel; EditCountNumberMakkeib: TEdit; procedure FormCreate(Sender: TObject); procedure ButtonOkClick(Sender: TObject); private { Private declarations } public { Public declarations } end; const UsefullWords:TUsefullWords = ('new','xor','or','and'); var CodeFile:Text; codeString:string; words:TarrayCodeString; AdjacencyMatrix : TAdjacencyMatrix; countArcs, i, j :word; countTops:integer; setUsefullSym:TUsefullSet; stack:pointerTypeRecord; MetriickMakkeiba: TMetriickMakkeiba; implementation {$R *.dfm} procedure TMetriickMakkeiba.FormCreate(Sender: TObject); begin MemoCodeText.Clear; EditCountTops.Text:=''; EditCountDest.Text:=''; EditCountNumberMakkeib.Text:=''; end; procedure DivisionIntoWords(var codeString:string; var words:TarrayCodeString); type SetSeparSymbols=set of char; var i,j:word; SeparSymbols:SetSeparSymbols; begin SeparSymbols:=[' ',',','.',';','(',')']; for i:=1 to numberWords do words[i]:=''; j:=1; for i:=1 to length(codeString) do begin if (not (codeString[i] in SeparSymbols)) and (codeString[i+1] in SeparSymbols) then begin words[j]:=words[j]+codeString[i]; inc(j); end else if not(codeString[i] in SeparSymbols) then words[j]:=words[j]+codeString[i]; end; end; procedure DeleteComments(var codeString:string); const numberComment=4; numberComments=2; type TarraySymbols=array[1..numberComment] of string[2]; const symbol:TarraySymbols = ('#','//','/*','*/'); var i,position,distance:word; subString:string; begin for i:=1 to numberComments do begin position:=Pos(symbol[i],codeString); if position <> 0 then begin dec(position); distance:=length(codeString)-position; inc(position); delete(codeString,position,distance); end; end; position:=Pos(symbol[i],codeString); if position<>0 then begin while (Pos(symbol[numberComment],codeString)=0) do begin dec(position); distance:=length(codeString)-position; inc(position); delete(codeString,position,distance); if length(codeString)<>0 then begin subString:=codeString; position:=1; end; readln(CodeFile,codeString); MetriickMakkeiba.MemoCodeText.Lines.Add(codeString); end; if Pos(symbol[numberComment],codeString)<>0 then begin distance:=Pos(symbol[numberComment],codeString); inc(distance); position:=1;; delete(codeString,position,distance); codeString:=subString+' '+codeString; end; end; end; procedure DeleteOutput(var codeString:string); const number=2; type TarraySymbols=array[1..number] of string[2]; TarrayPositions=array[1..number] of integer; const symbol:TarraySymbols = ('''','"'); var i,position,j:word; arrayPos:TarrayPositions; begin if length(codeString)<>0 then begin position:=0; j:=0; for i:=1 to number do begin repeat position:=PosEx(symbol[i],codeString,position); if position<>0 then begin inc(j); arrayPos[j]:=position; inc(position); end; until position=0; if j=number then begin inc(arrayPos[number]); delete(codeString,arrayPos[1],arrayPos[number]-arrayPos[1]); end; end; end; end; procedure Push(var stack:pointerTypeRecord; conditionalString:string; var countTops,previosIndex:integer; var AdjacencyMatrix:TAdjacencyMatrix); var pointerNew:pointerTypeRecord; begin if conditionalString='else' then begin inc(countTops); AdjacencyMatrix[previosIndex,countTops]:=true; AdjacencyMatrix[previosIndex,countTops-1]:=true; end else begin if countTops<> 0 then begin if (countTops=1) and (countTops = stack^.index) then AdjacencyMatrix[stack^.index,countTops+1]:=true else begin if stack=nil then AdjacencyMatrix[countTops-1,countTops]:=true else AdjacencyMatrix[stack^.index,countTops]:=true; end; end; inc(countTops); end; new(pointerNew); pointerNew^.data:=conditionalString; pointerNew^.index:=countTops; pointerNew^.next:=stack; stack:=pointerNew; end; procedure Pop(var stack:pointerTypeRecord; var countTops,previosIndex:integer; var AdjacencyMatrix:TAdjacencyMatrix); var pointerDelete:pointerTypeRecord; begin if stack<>nil then begin if stack^.data<>'else' then begin inc(countTops); AdjacencyMatrix[stack^.index,countTops]:=true; AdjacencyMatrix[countTops,countTops+1]:=true; inc(countTops); AdjacencyMatrix[stack^.index,countTops]:=true; previosIndex:=stack^.index; end; pointerDelete:=stack; stack:=stack^.next; dispose(pointerDelete); end; end; procedure MakingAdjacencyMatrix(const codeString:string; var countTops:integer; var AdjacencyMatrix:TAdjacencyMatrix); const number=8; type TarraySpecialWords=array[1..number] of string; const arraySpecialWords:TarraySpecialWords = ('function','for','while','foreach','do','elseif','else','if'); var i,j,position:word; previosIndex:integer; begin for i:=1 to number do for j:=1 to numberWords do begin if arraySpecialWords[i]=words[j] then begin Push(stack,arraySpecialWords[i],countTops,previosIndex, AdjacencyMatrix); end; end; for i:=1 to length(codeString) do begin if codeString[i]='}' then Pop(stack,countTops,previosIndex,AdjacencyMatrix); end; end; procedure TMetriickMakkeiba.ButtonOkClick(Sender: TObject); begin AssignFile(CodeFile,'input_1.txt'); Reset(CodeFile); countTops:=0; countArcs:=0; while (not(EoF(CodeFile))) do begin readln(CodeFile,codeString); MemoCodeText.Lines.Add(codeString); codeString:=trim(codeString); DeleteOutput(codeString); DeleteComments(codeString); if length(codeString) <> 0 then begin DivisionIntoWords(codeString,words); MakingAdjacencyMatrix(codeString,countTops,AdjacencyMatrix); end; end; MatrixAdjacency.RowCount:=countTops+1; MatrixAdjacency.ColCount:=countTops+1; for i:=1 to countTops do begin MatrixAdjacency.Cells[0,i]:= IntToStr(i); MatrixAdjacency.Cells[i,0]:= IntToStr(i); for j:=1 to countTops do begin if AdjacencyMatrix[i,j] = true then begin MatrixAdjacency.Cells[j,i]:= '+'; inc(countArcs); end; end; end; MatrixAdjacency.Visible:=true; EditCountTops.Text:=IntToStr(countTops); EditCountDest.Text:=IntToStr(countArcs); EditCountNumberMakkeib.Text:=IntToStr(countArcs-countTops+2); CloseFile(CodeFile); end; end.
object Form1: TForm1 AlignWithMargins = True Left = 0 Top = 0 Align = alClient AlphaBlend = True BorderStyle = bsSingle Caption = 'DEJOTA EDITOR' ClientHeight = 494 ClientWidth = 726 Color = clGrayText TransparentColorValue = clNone Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poDesktopCenter WindowState = wsMaximized PixelsPerInch = 96 TextHeight = 13 object Panel2: TPanel AlignWithMargins = True Left = 3 Top = 3 Width = 190 Height = 464 Align = alLeft Caption = 'Panel2' TabOrder = 0 end object Panel4: TPanel Left = 0 Top = 470 Width = 726 Height = 24 Align = alBottom Caption = 'Panel4' TabOrder = 1 ExplicitTop = 440 ExplicitWidth = 716 end object Panel5: TPanel Left = 196 Top = 0 Width = 530 Height = 470 Align = alClient Caption = 'Panel5' TabOrder = 2 ExplicitLeft = 151 ExplicitTop = -6 ExplicitWidth = 578 object Panel1: TPanel Left = 1 Top = 1 Width = 528 Height = 32 Align = alTop Caption = 'Panel1' TabOrder = 0 ExplicitWidth = 582 end end end
{ ------------------------------------------------------------------------------- Unit Name: cGLSimulationGrids Author: Aaron Hochwimmer (hochwimmera@pbworld.com) Purpose: visual classes for rendering TOUGH/MULKOM/TETRAD grids with GLScene. Updates: TETRAD Grid Support ------------------------------------------------------------------------------- } unit cGLSimulationGrids; interface uses System.Classes, System.SysUtils, System.Variants, Vcl.Graphics, GLScene, GLobjects, GLGeomobjects, GLVectorFileObjects, GLVectorTypes, GLVectorGeometry, GLTexture, GLGraphics, GLExtrusion, GLMaterial, GLColor, // glData cSimulationGrids, cUtilities, cColourSpectrum, cIsoSurfaceMC; type TGLGridLayer = class; TGLGridLayers = class; TGLSimulationGrid = class; TGLBlock = class(TGridBlock) private fBlock: TGLExtrusionSolid; fDummyCube: TGLDummyCube; fLayer: TGLGridLayer; fIsVisible: boolean; procedure SetParamColour(iMode: integer); protected procedure ConstructBlock; function GetScaleX: single; function GetScaleY: single; function GetScaleZ: single; function GetShowBlock: boolean; procedure SetShowBlock(bValue: boolean); public constructor Create(aLayer: TGLGridLayer; aDummyCube: TGLDummyCube); destructor Destroy; override; procedure ColourBlock; procedure RenderBlock; property Block: TGLExtrusionSolid read fBlock; property Layer: TGLGridLayer read fLayer; property ScaleX: single read GetScaleX; property ScaleY: single read GetScaleY; property ScaleZ: single read GetScaleZ; property ShowBlock: boolean read GetShowBlock write SetShowBlock; end; TGLGridLayer = class(TGridLayer) private fDummyCube: TGLDummyCube; fBlockBottom: boolean; fBlockTop: boolean; fBlockOutside: boolean; fVertexPoints: TGLPoints; fAlpha: single; procedure UpdateBlockSection(part: TExtrusionSolidPart; bValue: boolean); function GetMaxProperty(iProp: integer; dMax, dStart: double; bMax: boolean): double; function GetMinProperty(iProp: integer; dMin, dStart: double; bMin: boolean): double; function GetMaxPorosity: double; function GetMinPorosity: double; function GetMaxPermeabilityX: double; function GetMinPermeabilityX: double; function GetMaxPermeabilityY: double; function GetMinPermeabilityY: double; function GetMaxPermeabilityZ: double; function GetMinPermeabilityZ: double; function GetMaxPressure: double; function GetMinPressure: double; function GetMaxTemperature: double; function GetMinTemperature: double; function GetMaxSaturation: double; function GetMinSaturation: double; procedure SetBlockBottom(bValue: boolean); procedure SetBlockOutside(bValue: boolean); procedure SetBlockTop(bValue: boolean); procedure SetAlpha(dAlpha: single); public constructor Create(aParent: TGLGridLayers); destructor Destroy; override; procedure AddBlock(sBlockName: string; dLocationE, dLocationN: double); override; procedure AddTETRADBlock(sBlockName: string; dLocationE, dLocationN, dElevation, dTHickness, dX, dY: double; iRow, iCol: integer; bActive: boolean); override; procedure ClearBlocks; override; procedure HideAllBlocks; procedure HideBlockByName(sBlock: string); procedure RenderAllBlocks; procedure RenderVertices; procedure ColourAllBlocks; procedure ShowAllBlocks; procedure ResetAllBlocks; // resets visibility based on constraints procedure ShowBlockByName(sBlock: string); property MaxPorosity: double read GetMaxPorosity; // move to TGridLayer? property MinPorosity: double read GetMinPorosity; property MaxPermeabilityX: double read GetMaxPermeabilityX; property MinPermeabilityX: double read GetMinPermeabilityX; property MaxPermeabilityY: double read GetMaxPermeabilityY; property MinPermeabilityY: double read GetMinPermeabilityY; property MaxPermeabilityZ: double read GetMaxPermeabilityZ; property MinPermeabilityZ: double read GetMinPermeabilityZ; property MaxPressure: double read GetMaxPressure; property MinPressure: double read GetMinPressure; property MaxSaturation: double read GetMaxSaturation; property MinSaturation: double read GetMinSaturation; property MaxTemperature: double read GetMaxTemperature; property MinTemperature: double read GetMinTemperature; property BlockBottom: boolean read fBlockBottom write SetBlockBottom; property BlockOutside: boolean read fBlockOutside write SetBlockOutside; property BlockTop: boolean read fBlockTop write SetBlockTop; property Alpha: single read fAlpha write SetAlpha; property VertexPoints: TGLPoints read fVertexPoints; end; TGLGridLayers = class(TGridLayers) private fGrid: TGLSimulationGrid; fColourMode: integer; fMaxPaletteValue: double; fMinPaletteValue: double; fManualLimits: boolean; fShowInActiveBlocks: boolean; fRowList: TStringlist; fColumnList: TStringlist; function GetGLLayer(iIndex: integer): TGLGridLayer; function GetMinPropertyVis(iProp: integer; dStart: double): double; function GetMaxPropertyVis(iProp: integer; dStart: double): double; function GetMinPorosityVis: double; function GetMaxPorosityVis: double; function GetMinPermeabilityXVis: double; function GetMaxPermeabilityXVis: double; function GetMinPermeabilityyVis: double; function GetMaxPermeabilityyVis: double; function GetMinPermeabilityzVis: double; function GetMaxPermeabilityzVis: double; function GetMinPressureVis: double; function GetMaxPressureVis: double; function GetMinTemperatureVis: double; function GetMaxTemperatureVis: double; function GetMinSaturationVis: double; function GetMaxSaturationVis: double; procedure SetColourMode(iMode: integer); procedure SetShowInActiveBlocks(bShow: boolean); procedure SetMaxPaletteValue(dValue: double); procedure SetMinPaletteValue(dValue: double); procedure SetManualLimits(bValue: boolean); public constructor Create(aGrid: TGLSimulationGrid); destructor Destroy; override; procedure AddLayer(sLayerName, sLayerType: string; dElevation, dTHickness: single); override; procedure AddTETRADLayer(sLayerName: string); procedure ClearLayers; override; function GetGLLayerByName(sLayer: string): TGLGridLayer; procedure RenderAll; procedure RenderVertices; procedure DeleteLayer(iIndex: integer); override; procedure ResetAllBlocks; property MinPorosityVis: double read GetMinPorosityVis; property MaxPorosityVis: double read GetMaxPorosityVis; property MinPermeabilityXVis: double read GetMinPermeabilityXVis; property MaxPermeabilityXVis: double read GetMaxPermeabilityXVis; property MinPermeabilityYVis: double read GetMinPermeabilityyVis; property MaxPermeabilityYVis: double read GetMaxPermeabilityyVis; property MinPermeabilityZVis: double read GetMinPermeabilityzVis; property MaxPermeabilityZVis: double read GetMaxPermeabilityzVis; property MinPressureVis: double read GetMinPressureVis; property MaxPressureVis: double read GetMaxPressureVis; property MinTemperatureVis: double read GetMinTemperatureVis; property MaxTemperatureVis: double read GetMaxTemperatureVis; property MinSaturationVis: double read GetMinSaturationVis; property MaxSaturationVis: double read GetMaxSaturationVis; property ColourMode: integer read fColourMode write SetColourMode; property GLLayer[iIndex: integer]: TGLGridLayer read GetGLLayer; property Grid: TGLSimulationGrid read fGrid; property ShowInActiveBlocks: boolean read fShowInActiveBlocks write SetShowInActiveBlocks; property RowList: TStringlist read fRowList write fRowList; property ColumnList: TStringlist read fColumnList write fColumnList; property MaxPaletteValue: double read fMaxPaletteValue write SetMaxPaletteValue; property MinPaletteValue: double read fMinPaletteValue write SetMinPaletteValue; property ManualLimits: boolean read fManualLimits write SetManualLimits; end; TGLSimulationGrid = class(TSimulationGrid) private fColpalette: TColourSpectrum; fFreeForm: TGLFreeForm; fDummyCube: TGLDummyCube; fGridLayers: TGLGridLayers; fScaleX: single; fScaleY: single; fScaleZ: single; fIsoArray: array of array of array of single; fIsoMode: integer; fIsoNX: integer; fIsoNY: integer; fIsoNZ: integer; fXMin: double; fXMax: double; fYMin: double; fYMax: double; fZMin: double; fZMax: double; protected procedure SetScaleX(dValue: single); procedure SetScaleY(dValue: single); procedure SetScaleZ(dValue: single); public constructor CreateWithDummy(aDummyCube: TGLDummyCube); destructor Destroy; override; function ObtainVal(x, y, z: double): single; function ObtainValue(x, y, z: integer; var bNull: boolean): single; procedure EvaluateGridBounds; {:Generate Isosurface using Matching Cube algorithm} procedure GenerateIsoSurfaceMC(isovalue: double); procedure SetupIsoArray; property ColPalette: TColourSpectrum read fColpalette write fColpalette; property DummyCube: TGLDummyCube read fDummyCube; property FreeForm: TGLFreeForm read fFreeForm write fFreeForm; property GridLayers: TGLGridLayers read fGridLayers; property IsoMode: integer read fIsoMode write fIsoMode; property IsoNX: integer read fIsoNX write fIsoNX; property IsoNY: integer read fIsoNY write fIsoNY; property IsoNZ: integer read fIsoNZ write fIsoNZ; property ScaleX: single read fScaleX write SetScaleX; property ScaleY: single read fScaleY write SetScaleY; property ScaleZ: single read fScaleZ write SetScaleZ; property XMin: double read fXMin; property XMax: double read fXMax; property YMin: double read fYMin; property YMax: double read fYMax; property ZMin: double read fZMin; property ZMax: double read fZMax; end; implementation // ============================================================================= // TGLGridBlock Implementation // ============================================================================= // ----- TGLGRidBlock.ConstructBlock ------------------------------------------- procedure TGLBlock.ConstructBlock; var gv: TGridVertex; i: integer; dX, dY: double; begin // top face with Block do begin Position.x := ScaleX * LocationE; Position.y := ScaleY * locationN; Position.z := ScaleZ * (Elevation - 0.5 * Thickness); // z position = top of layer Height := ScaleZ * Thickness; MinSmoothAngle := 0.0; Contours.Clear; // LineWidth :=TGLSimulationGrid(self.Layer.Parent.Grid).LineWidth; if TETRAD then begin Name := 'Block_' + BlockName + '_Layer_' + Layer.LayerName; dX := StrToFloat(self.Vertices.Strings[0]); dY := StrToFloat(self.Vertices.Strings[1]); // four nodes - TETRAD blocks are rectangular with Contours.Add.Nodes do begin // bottom left AddNode(self.ScaleX * -0.5 * dX, self.ScaleY * -0.5 * dY, 0); // bottom right AddNode(self.ScaleX * 0.5 * dX, self.ScaleY * -0.5 * dY, 0); // top right AddNode(self.ScaleX * 0.5 * dX, self.ScaleY * 0.5 * dY, 0); // top left AddNode(self.ScaleX * -0.5 * dX, self.ScaleY * 0.5 * dY, 0); end; end else begin Name := 'Block_' + BlockName + '_Layer_' + Layer.LayerName; with Contours.Add.Nodes do begin for i := Vertices.Count - 1 downto 0 do begin gv := TGLSimulationGrid(self.Layer.Parent.Grid) .GetVertexByLabel(self.Vertices.Strings[i]); AddNode(self.ScaleX * (gv.LocationE - self.LocationE), self.ScaleY * (gv.locationN - self.locationN), 0); // relative position? end; end; end; Contours.Items[0].SplineMode := lsmLines; StructureChanged; end; end; // ----- TGLGridBlock.GetScaleX ------------------------------------------------ function TGLBlock.GetScaleX: single; begin result := TGLSimulationGrid(self.Layer.Parent.Grid).ScaleX; end; // ----- TGLGridBlock.GetScaleY ------------------------------------------------ function TGLBlock.GetScaleY: single; begin result := TGLSimulationGrid(self.Layer.Parent.Grid).ScaleY; end; // ----- TGLGridBlock.GetScaleZ ------------------------------------------------ function TGLBlock.GetScaleZ: single; begin result := TGLSimulationGrid(self.Layer.Parent.Grid).ScaleZ; end; // ----- TGLGridBlock.GetShowBlock --------------------------------------------- function TGLBlock.GetShowBlock: boolean; begin result := fIsVisible; end; // ----- TGLGridBlock.SetShowBlock --------------------------------------------- procedure TGLBlock.SetShowBlock(bValue: boolean); var sTemp: boolean; begin sTemp := bValue; fIsVisible := bValue; if sTemp then begin if (self.InActive and (not TGLGridLayers(self.Layer.Parent) .ShowInActiveBlocks)) then sTemp := false; if (TGLGridLayers(self.Layer.Parent).RowList.IndexOf(IntToStr(self.Row)) = -1) then sTemp := false; if (TGLGridLayers(self.Layer.Parent).ColumnList.IndexOf (IntToStr(self.Column)) = -1) then sTemp := false; end; Block.Visible := sTemp; end; // ----- TGLGridBlock.Create --------------------------------------------------- constructor TGLBlock.Create(aLayer: TGLGridLayer; aDummyCube: TGLDummyCube); begin inherited Create(TGridLayer(aLayer)); fLayer := aLayer; fDummyCube := TGLDummyCube(aDummyCube.AddNewChild(TGLDummyCube)); fBlock := TGLExtrusionSolid(fDummyCube.AddNewChild(TGLExtrusionSolid)); with fBlock do begin Visible := false; if aLayer.BlockOutside then Parts := Parts + [espOutside]; if aLayer.BlockTop then Parts := Parts + [espStopPolygon]; if aLayer.BlockBottom then Parts := Parts + [espStartPolygon]; if aLayer.Alpha < 1.0 then Material.BlendingMode := bmTransparency else Material.BlendingMode := bmOpaque; Material.MaterialOptions := Material.MaterialOptions + [moNoLighting]; end; end; // ----- TGLGridBlock.Destroy -------------------------------------------------- destructor TGLBlock.Destroy; begin fBlock.Free; fDummyCube.Free; inherited Destroy; end; // ----- TGLGridBlock.SetParamColour ------------------------------------------- procedure TGLBlock.SetParamColour(iMode: integer); var cv: TColorVector; dVal: double; begin case iMode of 1: dVal := Porosity; 2: dVal := PermeabilityX; 3: dVal := PermeabilityY; 4: dVal := PermeabilityZ; // need to add thermal condutivity, specific heat... 5: dVal := Pr; 6: dVal := Te; 7: dVal := Sv; else dVal := Porosity; end; with TGLGridLayers(Layer.Parent).Grid.colpalette do begin begin case SpectrumMode of 0: cv := GetColourVector(dVal, true); 1: cv := GetColourVector(dVal, true); 2, 3: cv := GetColourVector(dVal, (SpectrumMode = 2)); // rainbow and inverse rainbow spectrum 4, 5: cv := GetColourVector(dVal, (SpectrumMode = 4)); // using a palette end; end; with Block.Material do begin FrontProperties.Ambient.Color := cv; FrontProperties.Diffuse.Color := cv; FrontProperties.Emission.Color := cv; FrontProperties.Diffuse.Alpha := Layer.Alpha; end; end; end; // ----- TGLGridBlock.ColourBlock ---------------------------------------------- procedure TGLBlock.ColourBlock; var rt: TRockType; col: TColor; begin if self.InActive then begin with Block.Material do begin FrontProperties.Ambient.AsWinColor := clBlack; FrontProperties.Diffuse.AsWinColor := clBlack; FrontProperties.Emission.AsWinColor := clBlack; FrontProperties.Diffuse.Alpha := Layer.Alpha; end; end else begin case TGLGridLayers(Layer.Parent).ColourMode of // rock-type 0: begin rt := self.Layer.Parent.Grid.GetRockTypeByName(RockTypeCode); if rt <> nil then col := HexToColor(rt.ColourCode) else col := clBlack; // should be a property with Block.Material do begin FrontProperties.Ambient.AsWinColor := col; FrontProperties.Diffuse.AsWinColor := col; FrontProperties.Emission.AsWinColor := col; FrontProperties.Diffuse.Alpha := Layer.Alpha; end; end; 1, 2, 3, 4, 5, 6, 7: SetParamColour(TGLGridLayers(Layer.Parent).ColourMode); end; end; end; // ----- TGLGridBlock.RenderBlock ---------------------------------------------- procedure TGLBlock.RenderBlock; begin ConstructBlock; ColourBlock; end; // ============================================================================= // TGLGridLayer Implementation // ============================================================================= // ----- TGLGridLayer.HideAllBlocks -------------------------------------------- procedure TGLGridLayer.HideAllBlocks; var i: integer; begin for i := 0 to BlockList.Count - 1 do TGLBlock(BlockList.Objects[i]).ShowBlock := false; end; // ----- TGLGridLayer.HideBlockByName ------------------------------------------ procedure TGLGridLayer.HideBlockByName(sBlock: string); begin if (BlockList.IndexOf(sBlock) <> -1) then TGLBlock(BlockList.Objects[BlockList.IndexOf(sBlock)]) .ShowBlock := false; end; // ----- TGLGridLayer.ShowAllBlocks -------------------------------------------- procedure TGLGridLayer.ShowAllBlocks; var i: integer; begin for i := 0 to BlockList.Count - 1 do with TGLBlock(BlockList.Objects[i]) do ShowBlock := true; end; // ----- TGLGridLayer.ResetAllBlocks ------------------------------------------- procedure TGLGridLayer.ResetAllBlocks; var i: integer; begin for i := 0 to BlockList.Count - 1 do with TGLBlock(BlockList.Objects[i]) do ShowBlock := ShowBlock; end; // ----- TGLGridLayer.ColourAllBlocks ------------------------------------------ procedure TGLGridLayer.ColourAllBlocks; var i: integer; begin for i := 0 to BlockList.Count - 1 do TGLBlock(BlockList.Objects[i]).ColourBlock; end; // ----- TGLGridLayer.ShowBlockByName ------------------------------------------ procedure TGLGridLayer.ShowBlockByName(sBlock: string); begin if (BlockList.IndexOf(sBlock) <> -1) then TGLBlock(BlockList.Objects[BlockList.IndexOf(sBlock)]) .ShowBlock := true; end; // ----- TGLGridLayer.Create --------------------------------------------------- constructor TGLGridLayer.Create(aParent: TGLGridLayers); begin inherited Create(aParent); // dummy cube for this layer fDummyCube := TGLDummyCube(TGLSimulationGrid(Parent.Grid) .DummyCube.AddNewChild(TGLDummyCube)); // add glpoints fVertexPoints := TGLPoints(fDummyCube.AddNewChild(TGLPoints)); fBlockTop := true; fBlockOutside := true; fBlockBottom := true; fAlpha := 1.0; end; // ----- TGLGridLayer.Destroy -------------------------------------------------- destructor TGLGridLayer.Destroy; begin fVertexPoints.Free; fDummyCube.Free; inherited Destroy; end; // ----- TGLGridLayer.AddBlock ------------------------------------------------- procedure TGLGridLayer.AddBlock(sBlockName: string; dLocationE, dLocationN: double); var iIndex: integer; Block: TGLBlock; begin // check to see if this block is already in the list... if (BlockList.IndexOf(sBlockName) = -1) then begin Block := TGLBlock.Create(self, fDummyCube); BlockList.AddObject(sBlockName, Block); iIndex := BlockList.IndexOf(sBlockName); with TGLBlock(BlockList.Objects[iIndex]) do begin BlockName := sBlockName; LocationE := dLocationE; locationN := dLocationN; end; end; end; procedure TGLGridLayer.AddTETRADBlock(sBlockName: string; dLocationE, dLocationN, dElevation, dTHickness, dX, dY: double; iRow, iCol: integer; bActive: boolean); var iIndex: integer; Block: TGLBlock; begin // check to see if this block is already in the list... if (BlockList.IndexOf(sBlockName) = -1) then begin Block := TGLBlock.Create(self, fDummyCube); BlockList.AddObject(sBlockName, Block); iIndex := BlockList.IndexOf(sBlockName); with TGLBlock(BlockList.Objects[iIndex]) do begin TETRAD := true; BlockName := sBlockName; LocationE := dLocationE; locationN := dLocationN; Elevation := dElevation; Thickness := dTHickness; Row := iRow; Column := iCol; Vertices.Add(FloatToStr(dX)); Vertices.Add(FloatToStr(dY)); InActive := not bActive; end; end; end; // ----- TGLGridLayer.ClearBlocks ---------------------------------------------- procedure TGLGridLayer.ClearBlocks; begin while (BlockList.Count > 0) do begin TGLBlock(BlockList.Objects[0]).Free; BlockList.Delete(0); end; BlockList.Clear; end; // ----- TGLGridLayer.RenderVertices ------------------------------------------- procedure TGLGridLayer.RenderVertices; var Grid: TGLSimulationGrid; i: integer; x, y: single; begin Grid := TGLSimulationGrid(Parent.Grid); VertexPoints.Positions.Clear; VertexPoints.Colors.Add(clrBlack); for i := 0 to Grid.VertexCount - 1 do begin x := TGridVertex(Grid.Vertex[i]).LocationE; y := TGridVertex(Grid.Vertex[i]).locationN; // scale vertices here? VertexPoints.Positions.Add(x, y, Elevation); end; end; // ----- TGLGridLayer.RenderAllBlocks ------------------------------------------ procedure TGLGridLayer.RenderAllBlocks; var i: integer; begin for i := 0 to BlockList.Count - 1 do TGLBlock(BlockList.Objects[i]).RenderBlock; end; // ----- TGLGridLayer.GetMaxProperty ------------------------------------------- function TGLGridLayer.GetMaxProperty(iProp: integer; dMax, dStart: double; bMax: boolean): double; var i: integer; dValue: double; begin result := dStart; // start value - min if (BlockList.Count > 0) then begin for i := 0 to BlockList.Count - 1 do begin with TGLBlock(BlockList.Objects[i]) do begin case iProp of 0: dValue := Porosity; 1: dValue := PermeabilityX; 2: dValue := PermeabilityY; 3: dValue := PermeabilityZ; 4: dValue := Pr; 5: dValue := Te; 6: dValue := Sv; else dValue := Porosity; end; if (Block.Visible) and (dValue > result) then if bMax then begin if (dValue <= dMax) then result := dValue; end else result := dValue; end; end; end; end; // ----- TGLGridLayer.GetMinProperty ------------------------------------------- function TGLGridLayer.GetMinProperty(iProp: integer; dMin, dStart: double; bMin: boolean): double; var i: integer; dValue: double; begin result := dStart; // start value - min if (BlockList.Count > 0) then begin for i := 0 to BlockList.Count - 1 do begin with TGLBlock(BlockList.Objects[i]) do begin case iProp of 0: dValue := Porosity; 1: dValue := PermeabilityX; 2: dValue := PermeabilityY; 3: dValue := PermeabilityZ; 4: dValue := Pr; 5: dValue := Te; 6: dValue := Sv; else dValue := Porosity; end; if (Block.Visible) and (dValue < result) then if bMin then begin if (dValue >= dMin) then result := dValue; end else result := dValue; end; end; end; end; // ----- TGridLayer.GetMaxPorosity --------------------------------------------- function TGLGridLayer.GetMaxPorosity: double; begin result := GetMaxProperty(0, 1.0, 0.0, true); end; // ----- TGridLayer.GetMinPorosity --------------------------------------------- function TGLGridLayer.GetMinPorosity: double; begin result := GetMinProperty(0, 0.0, 1.0, true); end; // ----- TGLGridLayer.GetMaxPermeabilityX -------------------------------------- function TGLGridLayer.GetMaxPermeabilityX: double; begin result := GetMaxProperty(1, 0.0, -1.0, false); end; // ----- TGLGridLayer.GetMinPermeabilityX -------------------------------------- function TGLGridLayer.GetMinPermeabilityX: double; begin result := GetMinProperty(1, 0.0, 1.0, false); end; // ----- TGLGridLayer.GetMaxPermeabilityy -------------------------------------- function TGLGridLayer.GetMaxPermeabilityY: double; begin result := GetMaxProperty(2, 0.0, -1.0, false); end; // ----- TGLGridLayer.GetMinPermeabilityX -------------------------------------- function TGLGridLayer.GetMinPermeabilityY: double; begin result := GetMinProperty(2, 0.0, 1.0, false); end; // ----- TGLGridLayer.GetMaxPermeabilityz -------------------------------------- function TGLGridLayer.GetMaxPermeabilityZ: double; begin result := GetMaxProperty(3, 0.0, -1.0, false); end; // ----- TGLGridLayer.GetMinPermeabilityz -------------------------------------- function TGLGridLayer.GetMinPermeabilityZ: double; begin result := GetMinProperty(3, 0.0, 1.0, false); end; // ----- TGLGridLayer.GetMaxPressure ------------------------------------------- function TGLGridLayer.GetMaxPressure: double; begin result := GetMaxProperty(4, 0.0, 0.0, false); end; // ----- TGLGridLayer.GetMinPressure ------------------------------------------- function TGLGridLayer.GetMinPressure: double; begin result := GetMinProperty(4, 0.0, 1E20, false); end; // ----- TGLGridLayer.GetMaxTemperature ---------------------------------------- function TGLGridLayer.GetMaxTemperature: double; begin result := GetMaxProperty(5, 0.0, 0.0, false); end; // ----- TGLGridLayer.GetMinTemperature ---------------------------------------- function TGLGridLayer.GetMinTemperature: double; begin result := GetMinProperty(5, 0.0, 1E5, false); end; // ----- TGLGridLayer.GetMaxSaturation ----------------------------------------- function TGLGridLayer.GetMaxSaturation: double; begin result := GetMaxProperty(6, 1.0, 0.0, true); end; // ----- TGLGridLayer.GetMinSaturation ----------------------------------------- function TGLGridLayer.GetMinSaturation: double; begin result := GetMinProperty(6, 0.0, 1.0, false); end; // ----- TGLGridLayer.UpdateBlockSection --------------------------------------- procedure TGLGridLayer.UpdateBlockSection(part: TExtrusionSolidPart; bValue: boolean); var i: integer; begin for i := 0 to BlockList.Count - 1 do begin with TGLBlock(BlockList.Objects[i]) do begin if bValue then Block.Parts := Block.Parts + [part] else Block.Parts := Block.Parts - [part]; end; end; end; // ----- TGLGridLayer.SetBlockBottom ------------------------------------------- procedure TGLGridLayer.SetBlockBottom(bValue: boolean); begin if (fBlockBottom <> bValue) then begin fBlockBottom := bValue; UpdateBlockSection(espStartPolygon, bValue); end; end; // ----- TGLGridLayer.SetBlockOutside ------------------------------------------ procedure TGLGridLayer.SetBlockOutside(bValue: boolean); begin if (fBlockOutside <> bValue) then begin fBlockOutside := bValue; UpdateBlockSection(espOutside, bValue); end; end; // ----- TGLGridLayer.SetBlockTop ---------------------------------------------- procedure TGLGridLayer.SetBlockTop(bValue: boolean); begin if (fBlockTop <> bValue) then begin fBlockTop := bValue; UpdateBlockSection(espStopPolygon, bValue); end; end; // ----- TGLGridLayer.SetAlpha ------------------------------------------------- procedure TGLGridLayer.SetAlpha(dAlpha: single); var i: integer; begin if (dAlpha <> fAlpha) then begin fAlpha := dAlpha; for i := 0 to BlockList.Count - 1 do begin with TGLBlock(BlockList.Objects[i]) do begin if dAlpha >= 1.0 then begin Block.Material.BlendingMode := bmOpaque; Block.Material.FrontProperties.Diffuse.Alpha := 1.0; end else begin Block.Material.BlendingMode := bmTransparency; Block.Material.FrontProperties.Diffuse.Alpha := dAlpha; end; end; end; end; end; // ============================================================================= // TGLGridLayers Implementation // ============================================================================= // ----- TGLGridLayers.SetColourMode ------------------------------------------- procedure TGLGridLayers.SetColourMode(iMode: integer); var i: integer; begin // if iMode <> fColourMode then // begin fColourMode := iMode; if ManualLimits then begin Grid.colpalette.MinValue := MinPaletteValue; Grid.colpalette.MaxValue := MaxPaletteValue; end else begin case iMode of 1: begin Grid.colpalette.MinValue := MinPorosityVis; Grid.colpalette.MaxValue := MaxPorosityVis; end; 2: begin Grid.colpalette.MinValue := MinPermeabilityXVis; Grid.colpalette.MaxValue := MaxPermeabilityXVis; end; 3: begin Grid.colpalette.MinValue := MinPermeabilityYVis; Grid.colpalette.MaxValue := MaxPermeabilityYVis; end; 4: begin Grid.colpalette.MinValue := MinPermeabilityZVis; Grid.colpalette.MaxValue := MaxPermeabilityZVis; end; 5: begin Grid.colpalette.MinValue := MinPressureVis; Grid.colpalette.MaxValue := MaxPressureVis; end; 6: begin Grid.colpalette.MinValue := MinTemperatureVis; Grid.colpalette.MaxValue := MaxTemperatureVis; end; 7: begin Grid.colpalette.MinValue := MinSaturationVis; Grid.colpalette.MaxValue := MaxSaturationVis; end; end; end; for i := 0 to LayerList.Count - 1 do TGLGridLayer(LayerList.Objects[i]).ColourAllBlocks; // end; end; // ----- TGLGridLayers.SetShowActiveBlocks ------------------------------------- procedure TGLGridLayers.SetShowInActiveBlocks(bShow: boolean); var i: integer; begin if (bShow <> fShowInActiveBlocks) then begin fShowInActiveBlocks := bShow; for i := 0 to LayerList.Count - 1 do TGLGridLayer(LayerList.Objects[i]).ResetAllBlocks; end; end; procedure TGLGridLayers.ResetAllBlocks; var i: integer; begin for i := 0 to LayerList.Count - 1 do TGLGridLayer(LayerList.Objects[i]).ResetAllBlocks; end; // ----- TGLGridLayers.SetMaxPaletteValue -------------------------------------- procedure TGLGridLayers.SetMaxPaletteValue(dValue: double); begin if (dValue <> fMaxPaletteValue) then begin fMaxPaletteValue := dValue; SetColourMode(fColourMode); // force redraw end; end; // ----- TGLGridLayers.SetMinPaletteValue -------------------------------------- procedure TGLGridLayers.SetMinPaletteValue(dValue: double); begin if (dValue <> fMinPaletteValue) then begin fMinPaletteValue := dValue; SetColourMode(fColourMode); // force redraw end; end; // ----- TGLGridLayers.SetManualLimits ----------------------------------------- procedure TGLGridLayers.SetManualLimits(bValue: boolean); begin if (bValue <> fManualLimits) then begin fManualLimits := bValue; SetColourMode(fColourMode); // force redraw end; end; // ----- TGLGridLayers.RenderAll ----------------------------------------------- procedure TGLGridLayers.RenderAll; var i: integer; begin for i := 0 to LayerList.Count - 1 do TGLGridLayer(LayerList.Objects[i]).RenderAllBlocks; end; // ----- TGLGridLayers.GetGLLayer ---------------------------------------------- function TGLGridLayers.GetGLLayer(iIndex: integer): TGLGridLayer; begin if (iIndex >= 0) and (iIndex < LayerList.Count) then result := TGLGridLayer(LayerList.Objects[iIndex]) else result := nil; end; // ----- TGLGridLayers.GetMaxPropertyVis --------------------------------------- function TGLGridLayers.GetMaxPropertyVis(iProp: integer; dStart: double): double; var i: integer; dValue: double; begin result := dStart; for i := 0 to LayerList.Count - 1 do begin with TGLGridLayer(LayerList.Objects[i]) do begin case iProp of 0: dValue := MaxPorosity; 1: dValue := MaxPermeabilityX; 2: dValue := MaxPermeabilityY; 3: dValue := MaxPermeabilityZ; 4: dValue := MaxPressure; 5: dValue := MaxTemperature; 6: dValue := MaxSaturation; else dValue := MaxPorosity; end; if (dValue > result) then result := dValue; end; end; end; // ----- TGLGridLayers.GetMinPropertyVis --------------------------------------- function TGLGridLayers.GetMinPropertyVis(iProp: integer; dStart: double): double; var i: integer; dValue: double; begin result := dStart; for i := 0 to LayerList.Count - 1 do begin with TGLGridLayer(LayerList.Objects[i]) do begin case iProp of 0: dValue := MinPorosity; 1: dValue := MinPermeabilityX; 2: dValue := MinPermeabilityY; 3: dValue := MinPermeabilityZ; 4: dValue := MinPressure; 5: dValue := MinTemperature; 6: dValue := MinSaturation; else dValue := MinPorosity; end; if (dValue < result) then result := dValue; end; end; end; // ----- TGLGridLayers.GetMaxPorosityVis --------------------------------------- function TGLGridLayers.GetMaxPorosityVis: double; begin result := GetMaxPropertyVis(0, 0.0); end; // ----- TGLGridLayers.GetMinPorosityVis --------------------------------------- function TGLGridLayers.GetMinPorosityVis: double; begin result := GetMinPropertyVis(0, 1.0); end; // ----- TGLGridLayers.GetMaxPermeabilityXVis ---------------------------------- function TGLGridLayers.GetMaxPermeabilityXVis: double; begin result := GetMaxPropertyVis(1, -1.0); end; // ----- TGLGridLayers.GetMinPermeabilityXVis ---------------------------------- function TGLGridLayers.GetMinPermeabilityXVis: double; begin result := GetMinPropertyVis(1, 1.0); end; // ----- TGLGridLayers.GetMaxPermeabilityyVis ---------------------------------- function TGLGridLayers.GetMaxPermeabilityyVis: double; begin result := GetMaxPropertyVis(2, -1.0); end; // ----- TGLGridLayers.GetMinPermeabilityyVis ---------------------------------- function TGLGridLayers.GetMinPermeabilityyVis: double; begin result := GetMinPropertyVis(2, 1.0); end; // ----- TGLGridLayers.GetMaxPermeabilityzVis ---------------------------------- function TGLGridLayers.GetMaxPermeabilityzVis: double; begin result := GetMaxPropertyVis(3, -1.0); end; // ----- TGLGridLayers.GetMinPermeabilityzVis ---------------------------------- function TGLGridLayers.GetMinPermeabilityzVis: double; begin result := GetMinPropertyVis(3, 1.0); end; // ----- TGLGridLayers.GetMinPressureVis --------------------------------------- function TGLGridLayers.GetMinPressureVis: double; begin result := GetMinPropertyVis(4, 1E10); end; // ----- TGLGridLayers.GetMaxPressureVis --------------------------------------- function TGLGridLayers.GetMaxPressureVis: double; begin result := GetMaxPropertyVis(4, 0.0); end; // ----- TGLGridLayers.GetMinTemperatureVis ------------------------------------ function TGLGridLayers.GetMinTemperatureVis: double; begin result := GetMinPropertyVis(5, 1E5); end; // ----- TGLGridLayers.GetMaxTemperatureVis ------------------------------------ function TGLGridLayers.GetMaxTemperatureVis: double; begin result := GetMaxPropertyVis(5, 0.0); end; // ----- TGLGridLayers.GetMinSaturationVis ------------------------------------- function TGLGridLayers.GetMinSaturationVis: double; begin result := GetMinPropertyVis(6, 1.0); end; // ----- TGLGridLayers.GetMaxSaturationVis ------------------------------------- function TGLGridLayers.GetMaxSaturationVis: double; begin result := GetMaxPropertyVis(6, 0.0); end; // ----- TGLGridLayers.Create -------------------------------------------------- constructor TGLGridLayers.Create(aGrid: TGLSimulationGrid); begin inherited Create(aGrid); // passed in as a TSimulationGrid? fGrid := aGrid; fColourMode := 0; fManualLimits := true; fMaxPaletteValue := 1.0; fMinPaletteValue := 0.0; fShowInActiveBlocks := false; fRowList := TStringlist.Create; fColumnList := TStringlist.Create; end; // ----- TGLGridLayers.Destroy ------------------------------------------------- destructor TGLGridLayers.Destroy; begin fRowList.Free; fColumnList.Free; inherited Destroy; end; // ----- TGLGRidLayers.AddLayer ------------------------------------------------ procedure TGLGridLayers.AddLayer(sLayerName, sLayerType: string; dElevation, dTHickness: single); var iIndex: integer; Layer: TGLGridLayer; begin // check to see if this layer is already in the list... if (LayerList.IndexOf(sLayerName) = -1) then begin Layer := TGLGridLayer.Create(self); LayerList.AddObject(sLayerName, Layer); iIndex := LayerList.IndexOf(sLayerName); with TGLGridLayer(LayerList.Objects[iIndex]) do begin LayerName := sLayerName; LayerType := sLayerType; Elevation := dElevation; Thickness := dTHickness; end; end; end; // ----------------------------------------------------------------------------- procedure TGLGridLayers.AddTETRADLayer(sLayerName: string); var iIndex: integer; Layer: TGLGridLayer; begin // check to see if this layer is already in the list... if (LayerList.IndexOf(sLayerName) = -1) then begin Layer := TGLGridLayer.Create(self); LayerList.AddObject(sLayerName, Layer); iIndex := LayerList.IndexOf(sLayerName); with TGLGridLayer(LayerList.Objects[iIndex]) do begin LayerName := sLayerName; end; end; end; // ----- TGLGridLayers.ClearLayers --------------------------------------------- procedure TGLGridLayers.ClearLayers; begin while (LayerList.Count > 0) do begin TGLGridLayer(LayerList.Objects[0]).Free; LayerList.Delete(0); end; LayerList.Clear; end; // ----- TGLGridLayers.GetGLLayerByName ---------------------------------------- function TGLGridLayers.GetGLLayerByName(sLayer: string): TGLGridLayer; begin result := GetGLLayer(LayerList.IndexOf(sLayer)); end; // ----- TGLGridLayers.DeleteLayer --------------------------------------------- procedure TGLGridLayers.DeleteLayer(iIndex: integer); begin if (iIndex >= 0) and (iIndex < LayerList.Count) then begin TGLGridLayer(LayerList.Objects[iIndex]).Free; LayerList.Delete(iIndex); end; end; // ----- TGLGridLayers.RenderVertices ------------------------------------------ procedure TGLGridLayers.RenderVertices; var i: integer; begin for i := 0 to LayerList.Count - 1 do TGLGridLayer(LayerList.Objects[i]).RenderVertices; end; // ============================================================================= // TGLSimulationGrid Implementation // ============================================================================= // ----- TGLSimulationGrid.SetScaleX ------------------------------------------- procedure TGLSimulationGrid.SetScaleX(dValue: single); begin fScaleX := dValue; // propogate to visual objects or maybe not end; // ----- TGLSimulationGrid.SetScaleY ------------------------------------------- procedure TGLSimulationGrid.SetScaleY(dValue: single); begin fScaleY := dValue; // propogate to visual objects or maybe not end; // ----- TGLSimulationGrid.SetScaleZ ------------------------------------------- procedure TGLSimulationGrid.SetScaleZ(dValue: single); begin fScaleZ := dValue; // propogate to visual objects or maybe not end; // ----- TGLSimulationGRid.CreateWithDummy ------------------------------------- constructor TGLSimulationGrid.CreateWithDummy(aDummyCube: TGLDummyCube); var mo: TMeshObject; begin inherited Create; fGridLayers := TGLGridLayers.Create(self); fDummyCube := aDummyCube; fFreeForm := TGLFreeForm(fDummyCube.AddNewChild(TGLFreeForm)); fFreeForm.Material.FaceCulling := fcNoCull; mo := TMeshObject.CreateOwned(fFreeForm.MeshObjects); fScaleX := 1.0; fScaleY := 1.0; fScaleZ := 1.0; fIsoNX := 30; fIsoNY := 30; fIsoNZ := 30; fIsoMode := 5; end; // ----- TGLSimulationGrid.Destroy --------------------------------------------- destructor TGLSimulationGrid.Destroy; begin fGridLayers.Free; fFreeForm.MeshObjects.Clear; fFreeForm.Free; inherited Destroy; end; // ----- TGLSimulationGrid.SetupIsoArray --------------------------------------- procedure TGLSimulationGrid.SetupIsoArray; var iRow, iCol: integer; i, j, k: integer; locE, locN, dex, dey, delev, dthick: double; x, y, z, xdelta, ydelta, zdelta: double; begin SetLength(fIsoArray, fIsoNX + 1, fIsoNY + 1, fIsoNZ + 1); xdelta := (XMax - XMin) / fIsoNX; ydelta := (YMax - YMin) / fIsoNY; zdelta := (ZMax - ZMin) / fIsoNZ; z := ZMin; for k := 0 to fIsoNZ do begin x := XMin; For i := 0 To fIsoNX Do Begin y := YMin; For j := 0 To fIsoNY Do Begin fIsoArray[i, j, k] := ObtainVal(x, y, z); y := y + ydelta; End; x := x + xdelta; End; z := z + zdelta; End; end; // ----- TGLSimulationGrid.ObtainVal ----------------------------------------- function TGLSimulationGrid.ObtainValue(x, y, z: integer; var bNull: boolean): single; begin result := fIsoArray[x, y, z]; bNull := (fIsoArray[x, y, z] = -1); end; // ----- TGLSimulationGrid.ObtainVal ----------------------------------------- // obtains for TETRAD function TGLSimulationGrid.ObtainVal(x, y, z: double): single; var iRow, iCol: integer; i, j: integer; locE, locN, dex, dey, delev, dthick: double; begin iRow := -1; // not found iCol := -1; // not found result := -1; if (GridLayers.LayerList.Count = 0) then exit; with TGLGridLayer(GridLayers.LayerList.Objects[0]) do begin for i := 0 to BlockList.Count - 1 do begin with TGLBlock(BlockList.Objects[i]) do begin locE := LocationE; locN := locationN; dex := StrToFloat(Vertices[0]); dey := StrToFloat(Vertices[1]); if (not InActive) and (((x >= locE - 0.5 * dex) and (x <= locE + 0.5 * dex)) and ((y >= locN - 0.5 * dey) and (y <= locN + 0.5 * dey))) then begin iRow := Row; iCol := Column; break; end; end; end; end; if (iRow = -1) or (iCol = -1) then exit; for i := 0 to GridLayers.LayerList.Count - 1 do begin with TGLGridLayer(GridLayers.LayerList.Objects[i]) do begin for j := 0 to BlockList.Count - 1 do begin if (iRow = TGLBlock(BlockList.Objects[j]).Row) and (iCol = TGLBlock(BlockList.Objects[j]).Column) then begin delev := TGLBlock(BlockList.Objects[j]).Elevation; dthick := TGLBlock(BlockList.Objects[j]).Thickness; if ((z >= delev - 0.5 * dthick) and (z <= delev + 0.5 * dthick)) then begin case IsoMode of 5: result := TGLBlock(BlockList.Objects[j]).Te; 6: result := TGLBlock(BlockList.Objects[j]).Pr; 7: result := TGLBlock(BlockList.Objects[j]).Sv; end; exit; end; end; end; end; end; end; // ----- TGLSimulationGrid.EvaluateGridBounds ---------------------------------- procedure TGLSimulationGrid.EvaluateGridBounds; var i: integer; xl, xr, yl, yr, zl, zr: double; begin // grab one layer (they are the same) fXMin := 1.7E+308; fXMax := 5.0E-324; fYMin := 1.7E+308; fYMax := 5.0E-324; fZMin := 1.7E+308; fZMax := 5.0E-324; if GridLayers.LayerList.Count > 0 then begin with TGLGridLayer(GridLayers.LayerList.Objects[0]) do begin for i := 0 to BlockList.Count - 1 do begin // xbounds: xl := TGLBlock(BlockList.Objects[i]).LocationE - StrToFloat(TGLBlock(BlockList.Objects[i]).Vertices[0]); xr := TGLBlock(BlockList.Objects[i]).LocationE + StrToFloat(TGLBlock(BlockList.Objects[i]).Vertices[0]); if (xl < fXMin) then fXMin := xl; if (xr > fXMax) then fXMax := xr; // ybounds: yl := TGLBlock(BlockList.Objects[i]).locationN - StrToFloat(TGLBlock(BlockList.Objects[i]).Vertices[1]); yr := TGLBlock(BlockList.Objects[i]).locationN + StrToFloat(TGLBlock(BlockList.Objects[i]).Vertices[1]); if (yl < fYMin) then fYMin := yl; if (yr > fYMax) then fYMax := yr; // zbounds: zl := TGLBlock(BlockList.Objects[i]).Elevation - 0.5 * TGLBlock(BlockList.Objects[i]).Thickness; zr := TGLBlock(BlockList.Objects[i]).Elevation + 0.5 * TGLBlock(BlockList.Objects[i]).Thickness; if (zl < fZMin) then fZMin := zl; if (zr > fZMax) then fZMax := zr; end; end; end; end; // ----- TGLSimulationGrid.GenerateIsoSurfaceMC -------------------------------- procedure TGLSimulationGrid.GenerateIsoSurfaceMC(isovalue: double); type TDataPlane = array of array of single; PDataPlane = ^TDataPlane; TBlankPlane = array of array of boolean; PBlankPlane = ^TBlankPlane; const SMALL = 1E-8; var xdelta, ydelta, zdelta: double; PlaneAData, PlaneBData: TDataPlane; PlaneA, PlaneB: PDataPlane; PlaneABlank, PlaneBBlank: TBlankPlane; BlankA, BLankB: PBlankPlane; i, j, k, m: integer; x, y, z: double; Cubeidx: Word; CV0, CV1, CV2, CV3, CV4, CV5, CV6, CV7: TVector3f; // Cube vertex coordinates VV0, VV1, VV2, VV3, VV4, VV5, VV6, VV7: double; // Values at Cube Vertices bV0, bV1, bV2, bV3, bV4, bV5, bV6, bv7: boolean; // null at vertices; Verts: Array [0 .. 11] of TVector3f; blanks: array [0 .. 11] of boolean; Vertex1, Vertex2, Vertex3: TVector3f; function Interpolate(Const CVA, CVB: TVector3f; Const VVA, VVB: double) : TVector3f; Var Mu: double; Begin If (Abs(isovalue - VVA) < SMALL) Then Begin result := CVA; exit; End; If (Abs(isovalue - VVB) < SMALL) Then Begin result := CVB; exit; End; If (Abs(VVA - VVB) < SMALL) Then Begin result.X := 0.5 * (CVA.V[0] + CVB.V[0]); result.Y := 0.5 * (CVA.V[1] + CVB.V[1]); result.Z := 0.5 * (CVA.V[2] + CVB.V[2]); exit; End; Mu := (isovalue - VVA) / (VVB - VVA); result.X := CVA.V[0] + (CVB.V[0] - CVA.V[0]) * Mu; result.Y := CVA.V[1] + (CVB.V[1] - CVA.V[1]) * Mu; result.Z := CVA.V[2] + (CVB.V[2] - CVA.V[2]) * Mu; End; // Swap the data planes Procedure SwapPlanes; Var P: PDataPlane; PB: PBlankPlane; Begin P := PlaneA; PlaneA := PlaneB; PlaneB := P; PB := BlankA; BlankA := BLankB; BLankB := PB; End; // Fill PlaneB with new data Procedure EvaluatePlane(Const z: double; const n: integer); Var i, j: integer; x, y: single; bNull: boolean; Begin x := XMin; For i := 0 To fIsoNX Do Begin y := YMin; For j := 0 To fIsoNY Do Begin PlaneB^[i, j] := ObtainValue(i, j, n, bNull); BLankB^[i, j] := bNull; y := y + ydelta; End; x := x + xdelta; End; End; begin xdelta := (XMax - XMin) / fIsoNX; ydelta := (YMax - YMin) / fIsoNY; zdelta := (ZMax - ZMin) / fIsoNZ; // Allocate planes (for min storage pick smallest plane) SetLength(PlaneAData, fIsoNX + 1, fIsoNY + 1); SetLength(PlaneBData, fIsoNX + 1, fIsoNY + 1); PlaneA := @PlaneAData; PlaneB := @PlaneBData; SetLength(PlaneABlank, fIsoNX + 1, fIsoNY + 1); SetLength(PlaneBBlank, fIsoNX + 1, fIsoNY + 1); BlankA := @PlaneABlank; BLankB := @PlaneBBlank; FreeForm.MeshObjects[0].Vertices.Clear; FreeForm.MeshObjects[0].Mode := momTriangles; // build z := ZMin; EvaluatePlane(z, 0); for k := 0 to fIsoNZ - 1 do begin SwapPlanes; EvaluatePlane(z + zdelta, k + 1); y := YMin; for j := 0 To fIsoNY - 1 Do begin x := XMin; for i := 0 To fIsoNX - 1 Do begin // Values at cube vertices VV0 := PlaneA^[i, j]; bV0 := BlankA^[i, j]; VV1 := PlaneA^[i + 1, j]; bV1 := BlankA^[i + 1, j]; VV2 := PlaneB^[i + 1, j]; bV2 := BLankB^[i + 1, j]; VV3 := PlaneB^[i, j]; bV3 := BLankB^[i, j]; VV4 := PlaneA^[i, j + 1]; bV4 := BlankA^[i, j + 1]; VV5 := PlaneA^[i + 1, j + 1]; bV5 := BlankA^[i + 1, j + 1]; VV6 := PlaneB^[i + 1, j + 1]; bV6 := BLankB^[i + 1, j + 1]; VV7 := PlaneB^[i, j + 1]; bv7 := BLankB^[i, j + 1]; // Evaluate cube index Cubeidx := 0; If (VV0 < isovalue) Then Cubeidx := Cubeidx Or 1; If (VV1 < isovalue) Then Cubeidx := Cubeidx Or 2; If (VV2 < isovalue) Then Cubeidx := Cubeidx Or 4; If (VV3 < isovalue) Then Cubeidx := Cubeidx Or 8; If (VV4 < isovalue) Then Cubeidx := Cubeidx Or 16; If (VV5 < isovalue) Then Cubeidx := Cubeidx Or 32; If (VV6 < isovalue) Then Cubeidx := Cubeidx Or 64; If (VV7 < isovalue) Then Cubeidx := Cubeidx Or 128; // the edge table tells us which vertices are inside/outside the surface If (EdgeTable[Cubeidx] <> 0) Then Begin SetVector(CV0, x, y, z); SetVector(CV1, x + xdelta, y, z); SetVector(CV2, x + xdelta, y, z + zdelta); SetVector(CV3, x, y, z + zdelta); SetVector(CV4, x, y + ydelta, z); SetVector(CV5, x + xdelta, y + ydelta, z); SetVector(CV6, x + xdelta, y + ydelta, z + zdelta); SetVector(CV7, x, y + ydelta, z + zdelta); // find the vertices where the surface intersects the cube, using interpolate If (EdgeTable[Cubeidx] And 1) <> 0 then begin Verts[0] := Interpolate(CV0, CV1, VV0, VV1); blanks[0] := bV0 or bV1; end; If (EdgeTable[Cubeidx] And 2) <> 0 Then begin Verts[1] := Interpolate(CV1, CV2, VV1, VV2); blanks[1] := bV1 or bV2; end; If (EdgeTable[Cubeidx] And 4) <> 0 Then begin Verts[2] := Interpolate(CV2, CV3, VV2, VV3); blanks[2] := bV2 or bV3; end; If (EdgeTable[Cubeidx] And 8) <> 0 Then begin Verts[3] := Interpolate(CV3, CV0, VV3, VV0); blanks[3] := bV3 or bV0; end; If (EdgeTable[Cubeidx] And 16) <> 0 Then begin Verts[4] := Interpolate(CV4, CV5, VV4, VV5); blanks[4] := bV4 or bV5; end; If (EdgeTable[Cubeidx] And 32) <> 0 Then begin Verts[5] := Interpolate(CV5, CV6, VV5, VV6); blanks[5] := bV5 or bV6; end; If (EdgeTable[Cubeidx] And 64) <> 0 Then begin Verts[6] := Interpolate(CV6, CV7, VV6, VV7); blanks[6] := bV6 or bv7; end; If (EdgeTable[Cubeidx] And 128) <> 0 Then begin Verts[7] := Interpolate(CV7, CV4, VV7, VV4); blanks[7] := bv7 or bV4; end; If (EdgeTable[Cubeidx] And 256) <> 0 Then begin Verts[8] := Interpolate(CV0, CV4, VV0, VV4); blanks[8] := bV0 or bV4; end; If (EdgeTable[Cubeidx] And 512) <> 0 Then begin Verts[9] := Interpolate(CV1, CV5, VV1, VV5); blanks[9] := bV1 or bV5; end; If (EdgeTable[Cubeidx] And 1024) <> 0 Then begin Verts[10] := Interpolate(CV2, CV6, VV2, VV6); blanks[10] := bV2 or bV6; end; If (EdgeTable[Cubeidx] And 2048) <> 0 Then begin Verts[11] := Interpolate(CV3, CV7, VV3, VV7); blanks[11] := bV3 or bv7; end; m := 0; While TriTable[Cubeidx, m] <> -1 do Begin Vertex1 := Verts[TriTable[Cubeidx][m]]; Vertex2 := Verts[TriTable[Cubeidx][m + 1]]; Vertex3 := Verts[TriTable[Cubeidx][m + 2]]; if not(blanks[TriTable[Cubeidx][m]] or blanks[TriTable[Cubeidx][m + 1]] or blanks[TriTable[Cubeidx][m + 2]]) then FreeForm.MeshObjects[0].Vertices.Add(Vertex1, Vertex2, Vertex3); m := m + 3; End; End; // if edgetable.. x := x + xdelta; End; y := y + ydelta; End; z := z + zdelta; End; end; // ============================================================================= end.
unit htAttributeList; interface uses SysUtils, Classes, Graphics; type ThtAttributeList = class(TStringList) private function GetThisList: ThtAttributeList; function GetAttribute(const inName: string): string; procedure SetAttribute(const inName, Value: string); procedure SetBoolean(const inName: string; const Value: Boolean); procedure SetColor(const inName: string; const Value: TColor); procedure SetInteger(const inName: string; const Value: Integer); protected function GetHtmlAttributes: string; public procedure Add(const inName, inValue: string); reintroduce; overload; procedure Add(const inName: string; inValue: Integer); reintroduce; overload; procedure Add(const inName: string; inValue: Boolean); reintroduce; overload; procedure AddColor(const inName: string; inValue: TColor); procedure Remove(const inName: string); public property Attribute[const inName: string]: string read GetAttribute write SetAttribute; default; property Color[const inName: string]: TColor write SetColor; property Boolean[const inName: string]: Boolean write SetBoolean; property Integer[const inName: string]: Integer write SetInteger; property HtmlAttributes: string read GetHtmlAttributes; property ThisList: ThtAttributeList read GetThisList; end; implementation uses htUtils; { ThtAttributeList } procedure ThtAttributeList.SetAttribute(const inName, Value: string); begin // if IndexOfName(inName) < 0 then // Add(inName, ''); // Values[inName] := '"' + Value + '"'; Values[inName] := Value; end; procedure ThtAttributeList.SetBoolean(const inName: string; const Value: Boolean); begin if Value then Values[inName] := inName; end; procedure ThtAttributeList.SetColor(const inName: string; const Value: TColor); begin if htVisibleColor(Value) then Values[inName] := htColorToHtml(Value) else Values[inName] := ''; end; procedure ThtAttributeList.SetInteger(const inName: string; const Value: Integer); begin Values[inName] := IntToStr(Value); end; procedure ThtAttributeList.Add(const inName, inValue: string); begin if inValue <> '' then Attribute[inName] := inValue; end; procedure ThtAttributeList.Add(const inName: string; inValue: Integer); begin Add(inName, IntToStr(inValue)); end; procedure ThtAttributeList.Add(const inName: string; inValue: Boolean); begin if inValue then Add(inName, inName); end; procedure ThtAttributeList.AddColor(const inName: string; inValue: TColor); begin if htVisibleColor(inValue) then Add(inName, htColorToHtml(inValue)); end; procedure ThtAttributeList.Remove(const inName: string); //var // i: Integer; begin Values[inName] := ''; // i := IndexOfName(inName); // if i >= 0 then // Delete(i); end; function ThtAttributeList.GetAttribute(const inName: string): string; begin // if IndexOfName(inName) < 0 then // Result := '' // else // Result := Values[inName]; Result := Values[inName]; end; function ThtAttributeList.GetHtmlAttributes: string; var i: System.Integer; begin // Result := ''; // for i := 0 to Pred(Count) do // Result := Result + ' ' + Strings[i]; Result := ''; for i := 0 to Pred(Count) do Result := Result + ' ' + Names[i] + '="' + ValueFromIndex[i] + '"'; end; function ThtAttributeList.GetThisList: ThtAttributeList; begin Result := Self; end; end.
unit uDMImportInventory; interface uses SysUtils, Classes, uContentClasses, variants, ADODB, uDMCalcPrice; type TDMImportInventory = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FSQLConnection: TADOConnection; FLog: TStringList; FDMCalcPrice : TDMCalcPrice; function FindCategory(Category: TCategory): Boolean; function FindModelGroup(ModelGroup: TModelGroup): Boolean; function FindModelSubGroup(ModelSubGroup: TModelSubGroup): Boolean; function FindVendor(Vendor: TVendor): Boolean; function ImportCategory(Category: TCategory): Boolean; function ImportModelGroup(ModelGroup: TModelGroup): Boolean; function ImportModelSubGroup(ModelSubGroup: TModelSubGroup): Boolean; function ImportVendor(Vendor: TVendor): Boolean; function InsertCategory(Category: TCategory): Boolean; function InsertModelGroup(ModelGroup: TModelGroup): Boolean; function InsertModelSubGroup(ModelSubGroup: TModelSubGroup): Boolean; function InsertVendor(Vendor: TVendor): Boolean; function ImportBarcode(Barcode: TBarcode; UseQty: Boolean; UpdateQty: Boolean; IDStore: Variant): Boolean; function ImportModel(Model: TModel): Boolean; function InsertModel(Model: TModel): Boolean; function SetVendorPriority(Model: TModel; Vendor: TVendor): Boolean; function SetVendorModelCode(VendorModelCode: TVendorModelCode): Boolean; function ImportModelInventoryAdd(Model: TModel; IDStore: Integer): Boolean; function ImportModelInventoryUpd(Model: TModel; IDStore: Integer): Boolean; function DoInventoryMov(Model: TModel; IDStore: Integer; QtyMov: Double; Aumentar: Boolean): Boolean; function FindManufacturer(Manufacturer: TManufacturer): Boolean; function ImportManufacturer(Manufacturer: TManufacturer): Boolean; function InsertManufacturer(Manufacturer: TManufacturer): Boolean; function SetModelManufacturer(Model: TModel; Manufacturer: TManufacturer): Boolean; function UpdateModel(Model: TModel): Boolean; procedure UpdateKitPromoPrice(IDModel: Integer; CostPrice: Currency); public function FindModel(Model: TModel): Boolean; function FindBarcode(Barcode: TBarcode): Boolean; function InsertBarcode(Barcode: TBarcode; UseQty: Boolean; UpdateQty: Boolean): Boolean; function ImportBarcodes(lstBarcodes: TList; UseQty: Boolean; UpdateQty: Boolean; IDStore: Variant): Boolean; function PrepareModelList(lstBarcodes: TList): TList; property Log: TStringList read FLog write FLog; property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection; end; implementation uses uDMGlobal, uNumericFunctions, uObjectServices, Math; {$R *.dfm} function TDMImportInventory.ImportBarcode(Barcode: TBarcode; UseQty: Boolean; UpdateQty: Boolean; IDStore: Variant): Boolean; var Model : TModel; Category: TCategory; ModelGroup: TModelGroup; ModelSubGroup: TModelSubGroup; Vendor: TVendor; Manufacturer: TManufacturer; VendorModelCode: TVendorModelCode; begin Result := True; try Model := Barcode.Model; if Model = nil then begin Category := nil; ModelGroup := nil; ModelSubGroup := nil; Vendor := nil; Manufacturer := nil; VendorModelCode := nil; end else begin Category := Model.Category; ModelGroup := Model.ModelGroup; ModelSubGroup := Model.ModelSubGroup; Vendor := Model.Vendor; Manufacturer := Model.Manufacturer; VendorModelCode := Model.VendorModelCode; end; if Category <> nil then begin ImportCategory(Category); if ModelGroup <> nil then begin ModelGroup.IDGroup := Category.IDGroup; ImportModelGroup(ModelGroup); if ModelSubGroup <> nil then begin ModelSubGroup.IDModelGroup := ModelGroup.IDModelGroup; ImportModelSubGroup(ModelSubGroup); end; end; end; if Model <> nil then ImportModel(Model); if Manufacturer <> nil then if ImportManufacturer(Manufacturer) then SetModelManufacturer(Model, Manufacturer); if Vendor <> nil then if ImportVendor(Vendor) then begin SetVendorPriority(Model, Vendor); if (VendorModelCode <> nil) and (Model.VendorModelCode.VendorCode <> '') then begin VendorModelCode.IDModel := Model.IDModel; VendorModelCode.IDVendor := Model.Vendor.IDVendor; SetVendorModelCode(VendorModelCode); end; end; if (Vendor <> nil) and (VendorModelCode <> nil) and (Model.VendorModelCode.VendorCode <> '') then begin VendorModelCode.IDModel := Model.IDModel; VendorModelCode.IDVendor := Model.Vendor.IDVendor; SetVendorModelCode(VendorModelCode); end; if Barcode.IDBarcode <> null then if FindBarcode(Barcode) then {} else Result := InsertBarcode(Barcode, UseQty, UpdateQty); except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; end; function TDMImportInventory.FindBarcode(Barcode: TBarcode): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add(Format('SELECT IDBarcode FROM Barcode WHERE IDBarcode = %S', [QuotedStr(VarToStr(Barcode.IDBarcode))])); qryBusca.Open; Result := not qryBusca.IsEmpty; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.InsertBarcode(Barcode: TBarcode; UseQty: Boolean; UpdateQty: Boolean): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO Barcode'); qryBusca.SQL.Add(' (IDModel, IDBarcode, BarcodeOrder)'); qryBusca.SQL.Add(' (SELECT ' + VarToStr(Barcode.Model.IDModel) + ' , ' + QuotedStr(Trim(VarToStr(Barcode.IDBarcode))) + ' , IsNull(Max(BarcodeOrder),0) + 1 FROM Barcode WHERE IDMODEL = ' + VarToStr(Barcode.Model.IDModel) + ' )'); qryBusca.ExecSQL; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.ImportModel(Model: TModel): Boolean; begin if Model.IDModel = null then begin if FindModel(Model) then begin Result := UpdateModel(Model); UpdateKitPromoPrice(Model.IDModel, Model.VendorCost); end else Result := InsertModel(Model); end else Result := True; end; procedure TDMImportInventory.UpdateKitPromoPrice(IDModel: Integer; CostPrice: Currency); var KitModelService: TMRKitModelService; KitModel: TKitModel; qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); with qryBusca do try if Active then Close; Connection := FSQLConnection; SQL.Text := ' SELECT Qty, MarginPerc FROM KitModel WHERE IDModel = ' + IntToStr(IDModel) + ' AND ISNULL(MarginPerc, 0) <> 0 '; Open; if not(IsEmpty) then try KitModelService := TMRKitModelService.Create(); KitModel := TKitModel.Create(); FDMCalcPrice := TDMCalcPrice.Create(Self); KitModelService.SQLConnection := FSQLConnection; First; While not Eof do begin // Campos necessários KitModel.IDModel := IDModel; KitModel.Qty := FieldByName('Qty').AsFloat; if not DMGlobal.IsClientServer(FSQLConnection) then KitModel.SellingPrice := FDMCalcPrice.GetMarginPrice(CostPrice, FieldByName('MarginPerc').AsFloat); KitModel.MarginPerc := FieldByName('MarginPerc').AsFloat; //Update KitModelService.Update(KitModel); Next; end; finally FreeAndNil(KitModel); FreeAndNil(KitModelService); FreeAndNil(FDMCalcPrice); end; finally Close; end; end; function TDMImportInventory.FindModel(Model: TModel): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add(Format('SELECT IDModel FROM Model WHERE Model = %S', [QuotedStr(Model.Model)])); qryBusca.Open; Result := not qryBusca.IsEmpty; if Result then Model.IDModel := qryBusca.FieldByName('IDModel').AsInteger; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.InsertModel(Model: TModel): Boolean; var tmpID: Integer; qryBusca : TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('Model', 'IDModel', FSQLConnection); qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO Model'); qryBusca.SQL.Add(' (IDModel, Model, Description, GroupID, VendorCost, SellingPrice, DateLastCost, DateLastSellingPrice, IDUserLastSellingPrice, CaseQty, IDModelGroup, IDModelSubGroup) '); qryBusca.SQL.Add('VALUES (:IDModel, :Model, :Description, :GroupID, :VendorCost, :SellingPrice, GetDate(), GetDate(), :IDUserLastSellingPrice, :CaseQty, :IDModelGroup, :IDModelSubGroup) '); qryBusca.Parameters.ParamByName('IDModel').Value := tmpID; qryBusca.Parameters.ParamByName('Model').Value := Model.Model; qryBusca.Parameters.ParamByName('Description').Value := Model.Description; qryBusca.Parameters.ParamByName('GroupID').Value := Model.Category.IDGroup; if (Model.ModelGroup <> nil) then qryBusca.Parameters.ParamByName('IDModelGroup').Value := Model.ModelGroup.IDModelGroup else qryBusca.Parameters.ParamByName('IDModelGroup').Value := null; if (Model.ModelSubGroup <> nil) then qryBusca.Parameters.ParamByName('IDModelSubGroup').Value := Model.ModelSubGroup.IDModelSubGroup else qryBusca.Parameters.ParamByName('IDModelSubGroup').Value := null; qryBusca.Parameters.ParamByName('VendorCost').Value := Model.VendorCost; if not DMGlobal.IsClientServer(SQLConnection) then qryBusca.Parameters.ParamByName('SellingPrice').Value := Model.SellingPrice else qryBusca.Parameters.ParamByName('SellingPrice').Value := 0; qryBusca.Parameters.ParamByName('IDUserLastSellingPrice').Value := Model.IDUserLastSellingPrice; qryBusca.Parameters.ParamByName('CaseQty').Value := Model.CaseQty; qryBusca.ExecSQL; Model.IDModel := tmpID; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.UpdateModel(Model: TModel): Boolean; var qryBusca : TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add(' UPDATE Model'); qryBusca.SQL.Add(' SET VendorCost = ' + MyFormatCur(Model.VendorCost, '.')); if not DMGlobal.IsClientServer(SQLConnection) then qryBusca.SQL.Add(' , SellingPrice = ' + MyFormatCur(Model.SellingPrice, '.')); qryBusca.SQL.Add(' , DateLastCost = GetDate(), DateLastSellingPrice = GetDate(), IDUserLastSellingPrice = ' + Model.IDUserLastSellingPrice + ', CaseQty = ' + MyFormatDouble(Model.CaseQty, '.')); qryBusca.SQL.Add(' WHERE IDModel = ' + VarToStr(Model.IDModel)); qryBusca.ExecSQL; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.ImportCategory(Category: TCategory): Boolean; begin if Category.IDGroup = null then begin if FindCategory(Category) then Result := True else Result := InsertCategory(Category) end else Result := True; end; function TDMImportInventory.FindCategory(Category: TCategory): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add(Format('SELECT IDGroup FROM TabGroup WHERE Name = %S', [QuotedStr(Category.TabGroup)])); qryBusca.Open; Result := not qryBusca.IsEmpty; if Result then Category.IDGroup := qryBusca.FieldByName('IDGroup').AsInteger; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.InsertCategory(Category: TCategory): Boolean; var tmpID: integer; qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('TabGroup', 'IDGroup', FSQLConnection); qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO TabGroup'); qryBusca.SQL.Add(' (IDGroup, Name)'); qryBusca.SQL.Add('VALUES'); qryBusca.SQL.Add( Format(' (%D, %S)', [tmpID, QuotedStr(Category.TabGroup) ] ) ); qryBusca.ExecSQL; Category.IDGroup := tmpID; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.ImportVendor(Vendor: TVendor): Boolean; begin if Vendor.IDVendor = null then begin if FindVendor(Vendor) then Result := True else Result := InsertVendor(Vendor); end else Result := True; end; function TDMImportInventory.FindVendor(Vendor: TVendor): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('SELECT'); qryBusca.SQL.Add(' IDPessoa'); qryBusca.SQL.Add('FROM'); qryBusca.SQL.Add(' Pessoa P INNER JOIN'); qryBusca.SQL.Add(' TipoPessoa TP ON'); qryBusca.SQL.Add(' (P.IDTipoPessoa = TP.IDTipoPessoa)'); qryBusca.SQL.Add('WHERE'); qryBusca.SQL.Add(' P.IDTipoPessoa = 2'); qryBusca.SQL.Add(' AND'); qryBusca.SQL.Add(' TP.Path LIKE ' + QuotedStr('.002%')); qryBusca.SQL.Add(' AND'); qryBusca.SQL.Add(Format(' P.Pessoa = %S', [QuotedStr(Vendor.Vendor)])); qryBusca.Open; Result := not qryBusca.IsEmpty; if Result then Vendor.IDVendor := qryBusca.FieldByName('IDPessoa').AsInteger; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.InsertVendor(Vendor: TVendor): Boolean; var tmpID: Integer; qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('Pessoa', 'IDPessoa', FSQLConnection); qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO Pessoa'); qryBusca.SQL.Add(' (IDPessoa, IDTipoPessoa, Pessoa, IDTipoPessoaRoot)'); qryBusca.SQL.Add('VALUES'); qryBusca.SQL.Add( Format(' (%D, 2, %S, 2)', [tmpID, QuotedStr(Vendor.Vendor) ] ) ); qryBusca.ExecSQL; Vendor.IDVendor := tmpID; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.ImportManufacturer(Manufacturer: TManufacturer): Boolean; begin if Manufacturer.IDManufacturer = null then begin if FindManufacturer(Manufacturer) then Result := True else Result := InsertManufacturer(Manufacturer); end else Result := True; end; function TDMImportInventory.FindManufacturer(Manufacturer: TManufacturer): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('SELECT'); qryBusca.SQL.Add(' IDPessoa'); qryBusca.SQL.Add('FROM'); qryBusca.SQL.Add(' Pessoa P INNER JOIN'); qryBusca.SQL.Add(' TipoPessoa TP ON'); qryBusca.SQL.Add(' (P.IDTipoPessoa = TP.IDTipoPessoa)'); qryBusca.SQL.Add('WHERE'); qryBusca.SQL.Add(' P.IDTipoPessoa = 7'); qryBusca.SQL.Add(' AND'); qryBusca.SQL.Add(' TP.Path LIKE ' + QuotedStr('.004%')); qryBusca.SQL.Add(' AND'); qryBusca.SQL.Add(Format(' P.Pessoa = %S', [QuotedStr(Manufacturer.Manufacturer)])); qryBusca.Open; Result := not qryBusca.IsEmpty; if Result then Manufacturer.IDManufacturer := qryBusca.FieldByName('IDPessoa').AsInteger; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.InsertManufacturer(Manufacturer: TManufacturer): Boolean; var tmpID: Integer; qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('Pessoa', 'IDPessoa', FSQLConnection); qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO Pessoa'); qryBusca.SQL.Add(' (IDPessoa, IDTipoPessoa, Pessoa, IDTipoPessoaRoot)'); qryBusca.SQL.Add('VALUES'); qryBusca.SQL.Add( Format(' (%D, 7, %S, 7)', [tmpID, QuotedStr(Manufacturer.Manufacturer) ] ) ); qryBusca.ExecSQL; Manufacturer.IDManufacturer := tmpID; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.SetModelManufacturer(Model: TModel; Manufacturer: TManufacturer): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('UPDATE MODEL'); qryBusca.SQL.Add(Format('SET IDFabricante = %S', [VarToStr(Manufacturer.IDManufacturer)])); qryBusca.SQL.Add(Format('WHERE IDModel = %S', [VarToStr(Model.IDModel)])); qryBusca.ExecSQL; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.SetVendorPriority(Model:TModel; Vendor: TVendor): Boolean; var qryBusca : TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('SELECT'); qryBusca.SQL.Add(' IDModel'); qryBusca.SQL.Add('FROM'); qryBusca.SQL.Add(' Inv_ModelVendor'); qryBusca.SQL.Add('WHERE'); qryBusca.SQL.Add(Format(' IDModel = %S AND IDPessoa = %S', [VarToStr(Model.IDModel), VarToStr(Vendor.IDVendor)])); qryBusca.Open; if qryBusca.IsEmpty then begin qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT'); qryBusca.SQL.Add(' Inv_ModelVendor (IDModel, IDPessoa, VendorOrder)'); qryBusca.SQL.Add(' SELECT'); qryBusca.SQL.Add(Format(' %S,', [VarToStr(Model.IDModel)])); qryBusca.SQL.Add(Format(' %S,', [VarToStr(Vendor.IDVendor)])); qryBusca.SQL.Add(' IsNull(MAX(IMV.VendorOrder),0) + 1'); qryBusca.SQL.Add(' FROM'); qryBusca.SQL.Add(' Inv_ModelVendor IMV'); qryBusca.SQL.Add(' WHERE'); qryBusca.SQL.Add(Format(' IMV.IDModel = %S', [VarToStr(Model.IDModel)])); qryBusca.ExecSQL; end; Result := True; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.ImportBarcodes(lstBarcodes: TList; UseQty: Boolean; UpdateQty: Boolean; IDStore: Variant): Boolean; var I: Integer; Barcode: TBarcode; lstModel: TList; begin Result := False; for I := 0 to lstBarcodes.Count - 1 do begin Barcode := lstBarcodes[I]; Result := ImportBarcode(Barcode, UseQty, UpdateQty, IDStore); end; lstModel := PrepareModelList(lstBarcodes); try if UseQty then if UpdateQty then for I := 0 to lstModel.Count - 1 do begin if TModel(lstModel[I]).Qty <> 0 then ImportModelInventoryUpd(lstModel[I], IDStore); end else for I := 0 to lstModel.Count - 1 do begin if TModel(lstModel[I]).Qty <> 0 then ImportModelInventoryAdd(lstModel[I], IDStore); end; finally FreeAndNil(lstModel); end; end; function TDMImportInventory.ImportModelInventoryAdd(Model: TModel; IDStore: Integer): Boolean; var Qty: Double; begin if Model.CaseQty <> 0 then Qty := (Model.Qty * Model.CaseQty) else Qty := Model.Qty; Result := DoInventoryMov(Model, IDStore, Abs(Qty), Qty >= 0); end; function TDMImportInventory.ImportModelInventoryUpd(Model: TModel; IDStore: Integer): Boolean; var qryBusca: TADOQuery; QtyOnHand, QtyAtualizar, Qty: Double; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('SELECT'); qryBusca.SQL.Add(' IsNull(QtyOnHand, 0) AS QtyOnHand'); qryBusca.SQL.Add('FROM'); qryBusca.SQL.Add(' Inventory'); qryBusca.SQL.Add('WHERE'); qryBusca.SQL.Add(Format(' ModelID = %S', [VarToStr(Model.IDModel)])); qryBusca.SQL.Add(' AND'); qryBusca.SQL.Add(Format(' StoreID = %D', [IDStore])); qryBusca.Open; if qryBusca.IsEmpty then QtyOnHand := 0 else QtyOnHand := qryBusca.FieldByName('QtyOnHand').AsFloat; if Model.CaseQty <> 0 then Qty := (Model.Qty * Model.CaseQty) else Qty := Model.Qty; QtyAtualizar := Qty - QtyOnHand; if QtyAtualizar = 0 then Result := True else Result := DoInventoryMov(Model, IDStore, ABS(Qty - QtyOnHand), ((Qty - QtyOnHand) >= 0)); except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.DoInventoryMov(Model: TModel; IDStore: Integer; QtyMov: Double; Aumentar: Boolean): Boolean; var tmpID: Integer; qryBusca: TADOQuery; IDInventMovType: Integer; begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('InventoryMov', 'IDInventoryMov', FSQLConnection); if Aumentar then IDInventMovType := 21 else IDInventMovType := 22; qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO InventoryMov'); qryBusca.SQL.Add(' (IDInventoryMov, StoreID,'); qryBusca.SQL.Add(' ModelID, InventMovTypeID,'); qryBusca.SQL.Add(' DocumentID, IDUser, MovDate, Qty)'); qryBusca.SQL.Add('VALUES'); qryBusca.SQL.Add(Format(' (%D, %D, %S, %D, %D, 0, GetDate(), %S)', [tmpID, IDStore, VarToStr(Model.IDModel), IDInventMovType, tmpID, FormatFloat('0.#####', QtyMov)])); qryBusca.ExecSQL; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; function TDMImportInventory.PrepareModelList(lstBarcodes: TList): TList; var I : Integer; Model: TModel; begin Result := TList.Create; for I := 0 to lstBarcodes.Count - 1 do begin Model := TBarcode(lstBarcodes[I]).Model; if Result.IndexOf(Model) = -1 then Result.Add(Model); end; end; function TDMImportInventory.SetVendorModelCode(VendorModelCode: TVendorModelCode): Boolean; var qryBusca : TADOQuery; IDVendorModelCode: Integer; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add('SELECT'); qryBusca.SQL.Add(' IDModel'); qryBusca.SQL.Add('FROM'); qryBusca.SQL.Add(' VendorModelCode'); qryBusca.SQL.Add('WHERE'); qryBusca.SQL.Add(Format(' IDModel = %S AND IDPessoa = %S', [VarToStr(VendorModelCode.IDModel), VarToStr(VendorModelCode.IDVendor)])); qryBusca.Open; if qryBusca.IsEmpty then begin IDVendorModelCode := DMGlobal.GetNextCode('VendorModelCode', 'IDVendorModelCode', FSQLConnection); qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Text := 'INSERT INTO VendorModelCode (IDVendorModelCode, IDModel, IDPessoa, VendorCode) '+ ' VALUES (' + InttoStr(IDVendorModelCode) + ' , ' + Format(' %S,', [VarToStr(VendorModelCode.IDModel)]) + Format(' %S,', [VarToStr(VendorModelCode.IDVendor)]) + QuotedStr(VarToStr(VendorModelCode.VendorCode)) + ' ) '; qryBusca.ExecSQL; end; Result := True; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.ImportModelGroup( ModelGroup: TModelGroup): Boolean; begin if ModelGroup.IDModelGroup = null then begin if FindModelGroup(ModelGroup) then Result := True else Result := InsertModelGroup(ModelGroup) end else Result := True; end; function TDMImportInventory.FindModelGroup( ModelGroup: TModelGroup): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add(Format('SELECT IDModelGroup FROM ModelGroup WHERE ModelGroup = %S', [QuotedStr(ModelGroup.ModelGroup)])); qryBusca.Open; Result := not qryBusca.IsEmpty; if Result then ModelGroup.IDModelGroup := qryBusca.FieldByName('IDModelGroup').AsInteger; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.FindModelSubGroup( ModelSubGroup: TModelSubGroup): Boolean; var qryBusca: TADOQuery; begin qryBusca := TADOQuery.Create(Self); try qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; qryBusca.SQL.Clear; qryBusca.SQL.Add(Format('SELECT IDModelSubGroup FROM ModelSubGroup WHERE ModelSubGroup = %S', [QuotedStr(ModelSubGroup.ModelSubGroup)])); qryBusca.Open; Result := not qryBusca.IsEmpty; if Result then ModelSubGroup.IDModelSubGroup := qryBusca.FieldByName('IDModelSubGroup').AsInteger; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Close; qryBusca.Free; end; end; function TDMImportInventory.InsertModelGroup( ModelGroup: TModelGroup): Boolean; var tmpID, CanCreate: integer; qryBusca: TADOQuery; begin CanCreate := DMGlobal.GetSvrParam(93, FSQLConnection); if (CanCreate = 1) then begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('ModelGroup', 'IDModelGroup', FSQLConnection); qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO ModelGroup'); qryBusca.SQL.Add(' (IDModelGroup, IDGroup, ModelGroup)'); qryBusca.SQL.Add('VALUES'); qryBusca.SQL.Add(' (:IDModelGroup, :IDGroup, :ModelGroup)'); qryBusca.Parameters.ParamByName('IDModelGroup').Value := tmpID; qryBusca.Parameters.ParamByName('IDGroup').Value := ModelGroup.IDGroup; qryBusca.Parameters.ParamByName('ModelGroup').Value := ModelGroup.ModelGroup; qryBusca.ExecSQL; ModelGroup.IDModelGroup := tmpID; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; end; function TDMImportInventory.ImportModelSubGroup( ModelSubGroup: TModelSubGroup): Boolean; begin if ModelSubGroup.IDModelSubGroup = null then begin if FindModelSubGroup(ModelSubGroup) then Result := True else Result := InsertModelSubGroup(ModelSubGroup) end else Result := True; end; function TDMImportInventory.InsertModelSubGroup( ModelSubGroup: TModelSubGroup): Boolean; var tmpID, CanCreate: integer; qryBusca: TADOQuery; begin CanCreate := DMGlobal.GetSvrParam(93, FSQLConnection); if (CanCreate = 1) then begin qryBusca := TADOQuery.Create(Self); try Result := True; qryBusca.Connection := FSQLConnection; try if qryBusca.Active then qryBusca.Close; tmpID := DMGlobal.GetNextCode('ModelSubGroup', 'IDModelSubGroup', FSQLConnection); qryBusca.SQL.Clear; qryBusca.SQL.Add('INSERT INTO ModelSubGroup'); qryBusca.SQL.Add(' (IDModelSubGroup, IDModelGroup, ModelSubGroup)'); qryBusca.SQL.Add('VALUES'); qryBusca.SQL.Add(' (:IDModelGroup, :IDGroup, :ModelGroup)'); qryBusca.Parameters.ParamByName('IDModelGroup').Value := tmpID; qryBusca.Parameters.ParamByName('IDGroup').Value := ModelSubGroup.IDModelGroup; qryBusca.Parameters.ParamByName('ModelGroup').Value := ModelSubGroup.ModelSubGroup; qryBusca.ExecSQL; ModelSubGroup.IDModelSubGroup := tmpID; except on E: Exception do begin Log.Add(E.Message); Result := False; end; end; finally qryBusca.Free; end; end; end; procedure TDMImportInventory.DataModuleCreate(Sender: TObject); begin FLog := TStringList.Create; end; procedure TDMImportInventory.DataModuleDestroy(Sender: TObject); begin FreeAndNil(FLog); end; end.
Unit ColumnForm; Interface Uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Generics.Collections, ListModel, IRPMonRequest; Type TColumnFrm = Class (TForm) LowerPanel: TPanel; MainPanel: TPanel; StornoButton: TButton; OkButton: TButton; ColumnListView: TListView; procedure StornoButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure OkButtonClick(Sender: TObject); Private FModel : TListModel<TDriverRequest>; FCancelled : Boolean; FChecked : TList<Boolean>; Public Constructor Create(AOwner:TComponent; AModel:TListModel<TDriverRequest>); Reintroduce; Destructor Destroy; Override; Property Checked : TList<Boolean> Read FChecked; Property Cancelled : Boolean Read FCancelled; end; Implementation Constructor TColumnFrm.Create(AOwner:TComponent; AModel:TListModel<TDriverRequest>); begin FCancelled := True; FModel := AModel; FChecked := TList<Boolean>.Create; Inherited Create(AOwner); end; Destructor TColumnFrm.Destroy; begin FChecked.Free; Inherited Destroy; end; {$R *.DFM} Procedure TColumnFrm.FormCreate(Sender: TObject); Var I : Integer; c : TListModelColumn; begin For I := 0 To FModel.ColumnCount - 1 Do begin c := FModel.Columns[I]; With ColumnListView.Items.Add Do begin Caption := c.Caption; Checked := c.Visible; FChecked.Add(Checked); end; end; end; Procedure TColumnFrm.OkButtonClick(Sender: TObject); Var I : Integer; begin For I := 0 To COlumnListView.Items.Count - 1 Do FChecked[I] := ColumnListView.Items[I].Checked; FCancelled := False; Close; end; Procedure TColumnFrm.StornoButtonClick(Sender: TObject); begin Close; end; End.
unit AdvancedSearchForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, InflatablesList_Types, InflatablesList_Manager; type TfAdvancedSearchForm = class(TForm) leTextToFind: TLabeledEdit; btnSearch: TButton; grbSearchSettings: TGroupBox; cbPartialMatch: TCheckBox; cbCaseSensitive: TCheckBox; cbTextsOnly: TCheckBox; cbEditablesOnly: TCheckBox; cbSearchCalculated: TCheckBox; cbIncludeUnits: TCheckBox; cbSearchShops: TCheckBox; cbDeepScan: TCheckBox; bvlHorSplit: TBevel; lblSearchResults: TLabel; meSearchResults: TMemo; btnSaveReport: TButton; diaReportSave: TSaveDialog; procedure FormShow(Sender: TObject); procedure leTextToFindKeyPress(Sender: TObject; var Key: Char); procedure btnSearchClick(Sender: TObject); procedure cbSearchShopsClick(Sender: TObject); procedure meSearchResultsKeyPress(Sender: TObject; var Key: Char); procedure btnSaveReportClick(Sender: TObject); private { Private declarations } fILManager: TILManager; procedure CreateReport(SearchResults: TILAdvSearchResults); public { Public declarations } procedure Initialize(ILManager: TILManager); procedure Finalize; procedure ShowAdvancedSearch; end; var fAdvancedSearchForm: TfAdvancedSearchForm; implementation uses InflatablesList_Utils; {$R *.dfm} procedure TfAdvancedSearchForm.CreateReport(SearchResults: TILAdvSearchResults); var i,j: Integer; ISR: TILAdvItemSearchResult; SSR: TILAdvShopSearchResult; Temp: String; begin Screen.Cursor := crHourGlass; try meSearchResults.Lines.BeginUpdate; try meSearchResults.Lines.Add(IL_Format('Search report %s',[IL_FormatDateTime('yyyy-mm-dd hh:nn:ss',Now)])); meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_Format(' Searched string: "%s"',[leTextToFind.Text])); meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(' Search settings:'); meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_Format(' %s Allow partial match',[IL_BoolToStr(cbPartialMatch.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Case sensitive comparisons',[IL_BoolToStr(cbCaseSensitive.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Search only textual values',[IL_BoolToStr(cbTextsOnly.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Search only editable values',[IL_BoolToStr(cbEditablesOnly.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Search calculated values',[IL_BoolToStr(cbSearchCalculated.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Include unit symbols',[IL_BoolToStr(cbIncludeUnits.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Search item shops',[IL_BoolToStr(cbSearchShops.Checked,'-','+')])); meSearchResults.Lines.Add(IL_Format(' %s Deep scan',[IL_BoolToStr(cbDeepScan.Checked,'-','+')])); meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_Format('Found in %d item(s)...',[Length(SearchResults)])); meSearchResults.Lines.Add(''); If Length(SearchResults) > 0 then meSearchResults.Lines.Add(IL_StringOfChar('-',60)); For i := Low(SearchResults) to High(SearchResults) do begin If i > 0 then begin meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_StringOfChar('-',60)); end; meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_Format('[%d] Item #%d - %s', [i,SearchResults[i].ItemIndex + 1,fILManager[SearchResults[i].ItemIndex].TitleStr])); // item values If SearchResults[i].ItemValue <> [] then begin meSearchResults.Lines.Add(''); Temp := ''; For ISR := Low(TILAdvItemSearchResult) to High(TILAdvItemSearchResult) do If ISR in SearchResults[i].ItemValue then begin If Length(Temp) > 0 then Temp := IL_Format('%s, %s',[Temp,fILManager.DataProvider.GetAdvancedItemSearchResultString(ISR)]) else Temp := fILManager.DataProvider.GetAdvancedItemSearchResultString(ISR); end; meSearchResults.Lines.Add(' ' + Temp); end; // item shop values If Length(SearchResults[i].Shops) > 0 then begin meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_Format('Found in shops(%d):',[Length(SearchResults[i].Shops)])); meSearchResults.Lines.Add(''); For j := Low(SearchResults[i].Shops) to High(SearchResults[i].Shops) do begin If j > 0 then meSearchResults.Lines.Add(''); meSearchResults.Lines.Add(IL_Format(' [%d] Shop #%d - %s',[j,SearchResults[i].Shops[j].ShopIndex, fILManager[SearchResults[i].ItemIndex][SearchResults[i].Shops[j].ShopIndex].Name])); If SearchResults[i].Shops[j].ShopValue <> [] then begin meSearchResults.Lines.Add(''); Temp := ''; // values For SSR := Low(TILAdvShopSearchResult) to High(TILAdvShopSearchResult) do If SSR in SearchResults[i].Shops[j].ShopValue then begin If Length(Temp) > 0 then Temp := IL_Format('%s, %s',[Temp,fILManager.DataProvider.GetAdvancedShopSearchResultString(SSR)]) else Temp := fILManager.DataProvider.GetAdvancedShopSearchResultString(SSR); end; meSearchResults.Lines.Add(' ' + Temp); end; end; end; end; finally meSearchResults.Lines.EndUpdate; end; finally Screen.Cursor := crDefault; end; end; //============================================================================== procedure TfAdvancedSearchForm.Initialize(ILManager: TILManager); begin fILManager := ILManager; end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.Finalize; begin // nothing to do atm. end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.ShowAdvancedSearch; begin ShowModal; end; //============================================================================== procedure TfAdvancedSearchForm.FormShow(Sender: TObject); begin leTextToFind.SetFocus; end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.leTextToFindKeyPress(Sender: TObject; var Key: Char); begin If Key = #13{return} then begin Key := #0; btnSearch.OnClick(nil); end; end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.btnSearchClick(Sender: TObject); var SearchSettings: TILAdvSearchSettings; SearchResults: TILAdvSearchResults; begin If Length(leTextToFind.Text) > 0 then begin // create in-place search settings SearchSettings.Text := leTextToFind.Text; SearchSettings.PartialMatch := cbPartialMatch.Checked; SearchSettings.CaseSensitive := cbCaseSensitive.Checked; SearchSettings.TextsOnly := cbTextsOnly.Checked; SearchSettings.EditablesOnly := cbEditablesOnly.Checked; SearchSettings.SearchCalculated := cbSearchCalculated.Checked; SearchSettings.IncludeUnits := cbIncludeUnits.Checked; SearchSettings.SearchShops := cbSearchShops.Checked; SearchSettings.DeepScan := cbDeepScan.Checked; // init result array SetLength(SearchResults,0); // do the search Screen.Cursor := crHourGlass; try fILManager.FindAll(SearchSettings,SearchResults); finally Screen.Cursor := crDefault; end; // show the results meSearchResults.Lines.Clear; If Length(SearchResults) > 0 then CreateReport(SearchResults) else MessageDlg('No match was found.',mtInformation,[mbOk],0); end else MessageDlg('Cannot search for an empty string.',mtInformation,[mbOk],0); end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.cbSearchShopsClick(Sender: TObject); begin cbDeepScan.Enabled := cbSearchShops.Checked; end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.meSearchResultsKeyPress(Sender: TObject; var Key: Char); begin If Key = ^A then begin meSearchResults.SelectAll; Key := #0; end; end; //------------------------------------------------------------------------------ procedure TfAdvancedSearchForm.btnSaveReportClick(Sender: TObject); begin If diaReportSave.Execute then meSearchResults.Lines.SaveToFile(diaReportSave.FileName); end; end.
unit ufrmDialogCustomerAgreement; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, uInterface, StdCtrls, Mask, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, System.Actions, Vcl.ActnList, ufraFooterDialog3Button; type TFormMode = (fmAdd, fmEdit); TfrmDialogCustomerAgreement = class(TfrmMasterDialog, ICRUDAble) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; edtNo: TEdit; dtDate: TcxDateEdit; dtDueDate: TcxDateEdit; jvcuredtTotal: TcxCurrencyEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtNoKeyPress(Sender: TObject; var Key: Char); procedure footerDialogMasterbtnSaveClick(Sender: TObject); private FFormMode: TFormMode; FCustAgreementId: Integer; FIsProcessSuccessfull: boolean; procedure SetFormMode(const Value: TFormMode); procedure SetCustAgreementId(const Value: Integer); procedure SetIsProcessSuccessfull(const Value: boolean); procedure showDataEdit(Id: Integer); procedure prepareAddData; function SaveData: boolean; function UpdateData: boolean; public procedure LoadData(AID : String); { Public declarations } published property FormMode: TFormMode read FFormMode write SetFormMode; property CustAgreementId: Integer read FCustAgreementId write SetCustAgreementId; property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull; end; var frmDialogCustomerAgreement: TfrmDialogCustomerAgreement; implementation uses uTSCommonDlg, uConn, ufrmCustomerAgreement, DB; {$R *.dfm} procedure TfrmDialogCustomerAgreement.SetFormMode(const Value: TFormMode); begin FFormMode := Value; end; procedure TfrmDialogCustomerAgreement.SetCustAgreementId(const Value: Integer); begin FCustAgreementId:=Value; end; procedure TfrmDialogCustomerAgreement.SetIsProcessSuccessfull( const Value: boolean); begin FIsProcessSuccessfull := Value; end; procedure TfrmDialogCustomerAgreement.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogCustomerAgreement.FormDestroy(Sender: TObject); begin inherited; frmDialogCustomerAgreement := nil; end; procedure TfrmDialogCustomerAgreement.prepareAddData; begin edtNo.Clear; dtDate.Date:= Now; jvcuredtTotal.Value:= 0; dtDueDate.Date:= Now; end; procedure TfrmDialogCustomerAgreement.showDataEdit(Id: Integer); var data: TDataSet; arr: TArr; begin SetLength(arr,1); arr[0].tipe:= ptInteger; arr[0].data:= Id; // if not assigned(CustomerAgreement) then // CustomerAgreement := TCustomerAgreement.Create; // data:= CustomerAgreement.GetListCustomerAgreement(arr); edtNo.Text:= data.fieldbyname('AGRV_NO').AsString; dtDate.Date:= data.fieldbyname('AGRV_DATE').AsDateTime; jvcuredtTotal.Value:= data.fieldbyname('AGRV_TOTAL').AsCurrency; dtDueDate.Date:= data.fieldbyname('AGRV_DUE_DATE').AsDateTime; end; procedure TfrmDialogCustomerAgreement.FormShow(Sender: TObject); begin inherited; if (FFormMode = fmEdit) then showDataEdit(FCustAgreementId) else prepareAddData(); edtNo.SetFocus; end; procedure TfrmDialogCustomerAgreement.edtNoKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = Chr(VK_RETURN) then begin if(Sender.ClassType=TEdit)and((Sender as TEdit).Name='edtNo') then dtDate.SetFocus else if(Sender.ClassType=TcxDateEdit)and((Sender as TcxDateEdit).Name='dtDate')then jvcuredtTotal.SetFocus else if(Sender.ClassType=TcxCurrencyEdit)and((Sender as TcxCurrencyEdit).Name='edtTotal')then dtDueDate.SetFocus else footerDialogMaster.btnSave.SetFocus; end; end; function TfrmDialogCustomerAgreement.SaveData: boolean; var arrParam: TArr; begin // if not assigned(CustomerAgreement) then // CustomerAgreement := TCustomerAgreement.Create; SetLength(arrParam,7); arrParam[0].tipe := ptString; arrParam[0].data := edtNo.Text; arrParam[1].tipe := ptDateTime; arrParam[1].data := dtDate.Date; arrParam[2].tipe := ptString; arrParam[2].data := frmCustomerAgreement.edtCode.Text; arrParam[3].tipe := ptCurrency; arrParam[3].data := jvcuredtTotal.Value; arrParam[4].tipe := ptDateTime; arrParam[4].data := dtDueDate.Date; arrParam[5].tipe := ptString; arrParam[5].data := 'OPEN'; arrParam[6].tipe := ptInteger; arrParam[6].data := FLoginId; try // Result:= CustomerAgreement.InputCustomerAgreement(arrParam); except Result:= False; end; end; function TfrmDialogCustomerAgreement.UpdateData: boolean; var arrParam: TArr; begin // if not assigned(CustomerAgreement) then // CustomerAgreement := TCustomerAgreement.Create; SetLength(arrParam,6); arrParam[0].tipe := ptString; arrParam[0].data := edtNo.Text; arrParam[1].tipe := ptDateTime; arrParam[1].data := dtDate.Date; arrParam[2].tipe := ptCurrency; arrParam[2].data := jvcuredtTotal.Value; arrParam[3].tipe := ptDateTime; arrParam[3].data := dtDueDate.Date; arrParam[4].tipe := ptInteger; arrParam[4].data := FLoginId; arrParam[5].tipe := ptInteger; arrParam[5].data := CustAgreementId; try // Result:= CustomerAgreement.UpdateCustomerAgreement(arrParam); except Result:= False; end; end; procedure TfrmDialogCustomerAgreement.footerDialogMasterbtnSaveClick( Sender: TObject); begin inherited; if edtNo.Text='' then begin CommonDlg.ShowErrorEmpty(lbl1.Caption); edtNo.SetFocus; Exit; end; if (FormMode = fmAdd) then begin FIsProcessSuccessfull := SaveData; if FIsProcessSuccessfull then Close; end else begin FIsProcessSuccessfull := UpdateData; if FIsProcessSuccessfull then Close; end; // end if end; procedure TfrmDialogCustomerAgreement.LoadData(AID : String); begin // ClearByTag([0,1]); // edNoBukti.Text := 'Otomatis'; // FreeAndNil(FCI); // if AID = '' then // Exit; // // FCI := TModCustomerInvoice(DMClient.CrudCustomerInvoiceClient.Retrieve(TModCustomerInvoice.ClassName, AID)); // if FCI = nil then // Exit; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0043.PAS Description: Pascal Triangle Author: LOU DUCHEZ Date: 11-02-93 10:30 *) { LOU DUCHEZ >Also, does anyone have anycode to do Pascal's Triangle? The pattern is: 1 1 1 2 1 1 3 3 1 1 4 6 4 1 where each element = the sum of the two above it. Arrange it like this: 0110 -- The zeros are needed so that the algorithm can process the 1's. 01210 013310 0146410 I'd have two Arrays: one shows the last row's figures, and the other holds the current row's figures. Each "new" element (call the index "i") = the sum of "previous" element "i" + "previous" element "i - 1". } Procedure CalcPascalRow(r : Word); { which row to calculate } Var prows : Array[0..1, 0..100] of Word;{ your two Arrays } thisrow, lastrow : Byte; { point to this row & last row } i, j : Word; { counters } begin lastrow := 0; { set up "which row is which" } thisrow := 1; prows[lastrow, 0] := 0; { set up row "1": 0110 } prows[lastrow, 1] := 1; prows[lastrow, 2] := 1; prows[lastrow, 3] := 0; For j := 2 to r do begin { generate each "line" starting w/2 } prows[thisrow, 0] := 0; For i := 1 to j + 1 do begin { each "new" element = sum of "old" } prows[thisrow, i] := { element + predecessor to "old" } prows[lastrow, i] + { element } prows[lastrow, i - 1]; end; prows[thisrow, j + 2] := 0; lastrow := thisrow; { prepare For next iteration } thisrow := (thisrow + 1) mod 2; end; For i := 1 to r + 1 do { Write each element of desired line } Write(prows[lastrow, i] : 4); Writeln; end; {-- Test program, added by Nacho, 2017 --} var i, rows: integer; begin rows := 7; for i := 1 to rows do CalcPascalRow(i); end.
unit WebJS_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // $Rev: 41960 $ // File generated on 11.03.2012 21:14:10 from Type Library described below. // ************************************************************************ // // Type Lib: D:\Dmitry\Delphi exe\Photo Database\PhotoDB\Units\WebJS\WebJS (1) // LIBID: {517F7078-5E73-4E5A-B8A2-8F0FF14EF21B} // LCID: 0 // Helpfile: // HelpString: WebJS Library // DepndLst: // (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb) // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Windows, ActiveX, Classes, Graphics, StdVCL, Variants; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions WebJSMajorVersion = 1; WebJSMinorVersion = 0; LIBID_WebJS: TGUID = '{517F7078-5E73-4E5A-B8A2-8F0FF14EF21B}'; IID_IWebJSExternal: TGUID = '{4F995D09-CF9E-4042-993E-C71A8AED661E}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IWebJSExternal = interface; IWebJSExternalDisp = dispinterface; // *********************************************************************// // Interface: IWebJSExternal // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {4F995D09-CF9E-4042-993E-C71A8AED661E} // *********************************************************************// IWebJSExternal = interface(IDispatch) ['{4F995D09-CF9E-4042-993E-C71A8AED661E}'] function SaveLocation(Lat: Double; Lng: Double; const FileName: WideString): Shortint; safecall; procedure ZoomPan(Lat: Double; Lng: Double; Zoom: SYSINT); safecall; procedure UpdateEmbed; safecall; procedure MapStarted; safecall; function CanSaveLocation(Lat: Double; Lng: Double; Value: Shortint): Shortint; safecall; end; // *********************************************************************// // DispIntf: IWebJSExternalDisp // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {4F995D09-CF9E-4042-993E-C71A8AED661E} // *********************************************************************// IWebJSExternalDisp = dispinterface ['{4F995D09-CF9E-4042-993E-C71A8AED661E}'] function SaveLocation(Lat: Double; Lng: Double; const FileName: WideString): Shortint; dispid 201; procedure ZoomPan(Lat: Double; Lng: Double; Zoom: SYSINT); dispid 202; procedure UpdateEmbed; dispid 203; procedure MapStarted; dispid 204; function CanSaveLocation(Lat: Double; Lng: Double; Value: Shortint): Shortint; dispid 205; end; implementation uses ComObj; end.
unit SubListPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, uParentSub; type TOnDataChange = procedure of object; TOnSelectData = procedure (AParams: String) of object; TOnGetFchParam = function(): String of object; TOnGetSQLEnvent = function(): String of object; TOnTestFillEvent = function(): boolean of object; TAfterParamChanged = procedure(Changes: String) of object; TSubListPanel = class(TPanel) private FOnGetSQL: TOnGetSQLEnvent; FParam: String; FButtonNewEnabled, FButtonOpenEnabled, FButtonRemoveEnabled: Boolean; FOnDataChange: TOnDataChange; FOnGetFchParam: TOnGetFchParam; FOnTestFillEvent: TOnTestFillEvent; FFilterFields : TStringList; { campos do filtro } FFilterValues : TStringList; { valores do filtro } FSubListClassName: String; FSubListForm: TForm; FAfterParamChanged: TAfterParamChanged; FOnSelectData: TOnSelectData; function GetDatasetIsEmpty: boolean; function GetDatasetCount: integer; function GetCurrentKey: integer; procedure SetOnGetSQL(Value:TOnGetSQLEnvent); procedure SetParam(Value: String); procedure SetButtonNewEnabled(Value : boolean); procedure SetButtonOpenEnabled(Value : boolean); procedure SetButtonRemoveEnabled(Value : boolean); procedure SetSubListClassName(Value : String); procedure SetCaption; procedure SetColor; procedure FreeFch; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure CreateSubList; procedure DataSetOpen; procedure DataSetClose; procedure DataSetNew; procedure SubListRefresh; procedure DoParamChanged(Changes: String); procedure SetSubListProperties; procedure GetSubListProperties; function GetSubListInfo(InfoString: String): String; published property Param : String read FParam write SetParam; property ButtonNewEnabled : Boolean read FButtonNewEnabled write SetButtonNewEnabled default True; property ButtonOpenEnabled : Boolean read FButtonOpenEnabled write SetButtonOpenEnabled default True; property ButtonRemoveEnabled : Boolean read FButtonRemoveEnabled write SetButtonRemoveEnabled default True; property CurrentKey : integer read GetCurrentKey; property DatasetCount : integer read GetDatasetCount; property DatasetIsEmpty : Boolean read GetDatasetIsEmpty; property OnGetSQL : TOnGetSQLEnvent read FOnGetSQL write SetOnGetSQL; property OnDataChange : TOnDataChange read FOnDataChange write FOnDataChange; property OnSelectData : TOnSelectData read FOnSelectData write FOnSelectData; property OnGetFchParam : TOnGetFchParam read FOnGetFchParam write FOnGetFchParam; property OnTestFillEvent : TOnTestFillEvent read FOnTestFillEvent write FOnTestFillEvent; property SubListClassName : String read FSubListClassName write SetSubListClassName; property FilterFields : TStringList read FFilterFields write FFilterFields; //SetFilterFields; property FilterValues : TStringList read FFilterValues write FFilterValues; //SetFilterValues; property AfterParamChanged: TAfterParamChanged read FAfterParamChanged write fAfterParamChanged; end; procedure Register; implementation uses uCriarForm; procedure Register; begin RegisterComponents('NewPower', [TSubListPanel]); end; constructor TSubListPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FFilterFields := TStringList.Create; FFilterValues := TStringList.Create; FButtonNewEnabled := True; FButtonOpenEnabled := True; FButtonRemoveEnabled := True; BevelOuter := bvNone; SetCaption; SetColor; end; destructor TSubListPanel.Destroy; begin FFilterFields.Free; FFilterValues.Free; inherited Destroy; end; procedure TSubListPanel.SetSubListClassName(Value : String); begin if Value <> FSubListClassName then begin FSubListClassName := Value; FreeFch; SetCaption; SetColor; end; end; procedure TSubListPanel.FreeFch; begin if FSubListForm <> nil then begin FSubListForm.Free; FSubListForm := nil; end; end; procedure TSubListPanel.CreateSubList; begin if FSubListForm = nil then FSubListForm := CriaForm(Owner, FSubListClassName); if FSubListForm <> nil then try LockWindowUpdate(Handle); with TParentSub(FSubListForm) do begin Parent := Self; Top := 0; Left := 0; BorderStyle := bsNone; Align := alClient; FilterFields := FFilterFields; FilterValues := FFilterValues; SetButtonNewEnabled(FButtonNewEnabled); SetButtonOpenEnabled(FButtonOpenEnabled); SetButtonRemoveEnabled(FButtonRemoveEnabled); Param := FParam; if Assigned(Self.FOnGetSQL) then OnGetSQL := Self.FOnGetSQL; if Assigned(Self.FOnGetFchParam) then TParentSub(FSubListForm).OnGetFchParam := Self.FOnGetFchParam; if Assigned(Self.FOnTestFillEvent) then TParentSub(FSubListForm).OnTestFillEvent := Self.FOnTestFillEvent; if Assigned(Self.FOnDataChange) then TParentSub(FSubListForm).OnDataChange := Self.FOnDataChange; if Assigned(Self.FOnSelectData) then TParentSub(FSubListForm).OnSelectData := Self.FOnSelectData; Show; end; finally LockWindowUpdate(0); end; end; procedure TSubListPanel.SetCaption; begin if FSubListClassName <> '' then Caption := '' else Caption := 'SubListClassName Undefined !'; end; procedure TSubListPanel.SetColor; begin if FSubListClassName = '' then Color := clRed; end; procedure TSubListPanel.DataSetOpen; begin if FSubListForm <> nil then TParentSub(FSubListForm).DataSetOpen; end; procedure TSubListPanel.DataSetClose; begin if FSubListForm <> nil then TParentSub(FSubListForm).DataSetClose; end; function TSubListPanel.GetDatasetIsEmpty: boolean; begin Result := True; if FSubListForm <> nil then if FSublistForm is TParentSub then Result := TParentSub(FSublistForm).GetDatasetIsEmpty; end; procedure TSubListPanel.DataSetNew; begin if FSubListForm <> nil then if FSublistForm is TParentSub then TParentSub(FSublistForm).DataSetNew; end; function TSubListPanel.GetDatasetCount: integer; begin Result := -1; if FSubListForm <> nil then if FSublistForm is TParentSub then Result := TParentSub(FSublistForm).GetRecordCount; end; function TSubListPanel.GetCurrentKey: integer; begin Result := -1; if FSubListForm <> nil then if FSublistForm is TParentSub then Result := TParentSub(FSublistForm).GetCurrentKey; end; procedure TSubListPanel.SetButtonNewEnabled(Value: boolean); begin if FSubListForm <> nil then if FSublistForm is TParentSub then TParentSub(FSublistForm).SetButtonNewEnabled(Value); end; procedure TSubListPanel.SetButtonOpenEnabled(Value: boolean); begin if FSubListForm <> nil then if FSublistForm is TParentSub then TParentSub(FSublistForm).SetButtonOpenEnabled(Value); end; procedure TSubListPanel.SetButtonRemoveEnabled(Value: boolean); begin if FSubListForm <> nil then if FSublistForm is TParentSub then TParentSub(FSublistForm).SetButtonRemoveEnabled(Value); end; procedure TSubListPanel.SetParam(Value: String); begin if FSubListForm <> nil then if FSublistForm is TParentSub then TParentSub(FSubListForm).Param := Value; end; procedure TSubListPanel.SetOnGetSQL(Value: TOnGetSQLEnvent); begin FOnGetSQL := Value; if FSubListForm <> nil then if FSublistForm is TParentSub then TParentSub(FSubListForm).OnGetSQL := Value; end; procedure TSubListPanel.SubListRefresh; begin if FSubListForm <> nil then TParentSub(FSubListForm).SubListRefresh; end; procedure TSubListPanel.DoParamChanged(Changes: String); begin if Assigned(FAfterParamChanged) then FAfterParamChanged(Changes); end; function TSubListPanel.GetSubListInfo(InfoString: String) : String; begin Result := TParentSub(FSubListForm).GiveInfo(InfoString); end; procedure TSubListPanel.SetSubListProperties; begin TParentSub(FSubListForm).SetLayoutProperties; end; procedure TSubListPanel.GetSubListProperties; begin TParentSub(FSubListForm).GetLayoutProperties; end; end.
unit Grijjy.FacebookAPI; { Http Rest interface for Facebook API } interface uses Grijjy.FBSDK.Types; type TFacebook = class private FClientId: String; FClientSecret: String; FAccessToken: String; private { Http } function Get(const AUrl: String; out AResponse: String): Integer; public { Helpers } class function ValueForParam(const AParams, AName: String): String; class function ExistsParam(const AParams, AName: String): Boolean; public { Login & authentication flow } function OAuth2_Url: String; public function DebugToken(const AInputToken: String; out ADebugAccessToken: String; out AAppId, AUserId: String; out AIsShortLived: Boolean): Integer; function ExchangeToken(const AInputToken: String; out ALongLivedAccessToken: String): Integer; function DebugGetUser(const AInputToken: String; out AAppId, AId, AName, AEmail: String): Integer; public function GetUser(const AUserId: String; out AUser: TFacebookUser): Integer; function GetUserFriendsCount(const AUserId: String; out AFriendsCount: Integer): Integer; function GetUserFriends(const AUserId: String; out AFriends: TFacebookUsers): Integer; public constructor Create(const AClientId: String = ''; const AClientSecret: String = ''); destructor Destroy; override; public property AccessToken: String read FAccessToken write FAccessToken; end; implementation uses System.SysUtils, System.NetEncoding, Grijjy.Http, Grijjy.Bson, Grijjy.Bson.IO; constructor TFacebook.Create(const AClientId, AClientSecret: String); begin FClientId := AClientId; FClientSecret := AClientSecret; end; destructor TFacebook.Destroy; begin inherited; end; class function TFacebook.ValueForParam(const AParams, AName: String): String; var Strings: TArray<String>; S: String; Index: Integer; begin Strings := AParams.Split(['&']); for S in Strings do begin Index := S.IndexOf(AName); if Index = 0 then begin Result := S.Substring(Index + Length(AName) + 1); Break; end; end; end; class function TFacebook.ExistsParam(const AParams, AName: String): Boolean; var Strings: TArray<String>; S: String; Index: Integer; begin Result := False; Strings := AParams.Split(['&']); for S in Strings do begin Index := S.IndexOf(AName); if Index = 0 then begin Result := True; Break; end; end; end; function TFacebook.OAuth2_Url: String; begin Result := 'https://www.facebook.com/dialog/oauth' + '?client_id=' + TNetEncoding.URL.Encode(FClientId) + '&response_type=token' + '&redirect_uri=' + TNetEncoding.URL.Encode('https://www.facebook.com/connect/login_success.html'); end; function TFacebook.DebugToken(const AInputToken: String; out ADebugAccessToken: String; out AAppId, AUserId: String; out AIsShortLived: Boolean): Integer; var HTTP: TgoHTTPClient; Doc, DataDoc: TgoBsonDocument; Value: TgoBsonValue; Response: String; begin HTTP := TgoHTTPClient.Create; try ADebugAccessToken := HTTP.Get('https://graph.facebook.com/oauth/access_token?' + 'client_id=' + FClientId + '&client_secret=' + FClientSecret + '&grant_type=client_credentials'); Result := HTTP.ResponseStatusCode; if Result = 200 then begin Response := HTTP.Get('https://graph.facebook.com/debug_token?' + 'input_token=' + AInputToken + '&' + ADebugAccessToken); Result := HTTP.ResponseStatusCode; if Result = 200 then begin Doc := TgoBsonDocument.Parse(Response); DataDoc := Doc['data'].AsBsonDocument; AAppId := DataDoc['app_id']; AUserId := DataDoc['user_id']; AIsShortLived := not DataDoc.TryGetValue('issued_at', Value); end; end; finally HTTP.Free; end; end; function TFacebook.ExchangeToken(const AInputToken: String; out ALongLivedAccessToken: String): Integer; var HTTP: TgoHTTPClient; begin HTTP := TgoHTTPClient.Create; try ALongLivedAccessToken := HTTP.Get('https://graph.facebook.com/oauth/access_token?' + 'client_id=' + FClientId + '&client_secret=' + FClientSecret + '&grant_type=fb_exchange_token' + '&fb_exchange_token=' + AInputToken); Result := HTTP.ResponseStatusCode; finally HTTP.Free; end; end; function TFacebook.DebugGetUser(const AInputToken: String; out AAppId, AId, AName, AEmail: String): Integer; var Doc: TgoBsonDocument; Response: String; DebugAccessToken: String; ShortLived: Boolean; begin Result := DebugToken(AInputToken, DebugAccessToken, AAppId, AId, ShortLived); if Result = 200 then begin Result := Get('https://graph.facebook.com/' + AId + '?fields=name,email&' + DebugAccessToken, Response); if Result = 200 then begin Doc := TgoBsonDocument.Parse(Response); AName := Doc['name']; AEmail:= Doc['email']; end; end; end; function TFacebook.Get(const AUrl: String; out AResponse: String): Integer; var HTTP: TgoHTTPClient; begin HTTP := TgoHTTPClient.Create; try AResponse := HTTP.Get(AUrl); Result := HTTP.ResponseStatusCode; finally HTTP.Free; end; end; function TFacebook.GetUser(const AUserId: String; out AUser: TFacebookUser): Integer; var Doc: TgoBsonDocument; Response: String; begin Result := Get('https://graph.facebook.com/' + AUserId + '?fields=id,name,email&access_token=' + FAccessToken, Response); if Result = 200 then begin Doc := TgoBsonDocument.Parse(Response); AUser.Id := Doc['id']; AUser.Name := Doc['name']; AUser.Email:= Doc['email']; end; end; function TFacebook.GetUserFriendsCount(const AUserId: String; out AFriendsCount: Integer): Integer; var Url: String; Doc, Friends, Summary: TgoBsonDocument; Response: String; begin Url := 'https://graph.facebook.com/' + AUserId + '?fields=friends.limit(0)&access_token=' + FAccessToken; Result := Get(Url, Response); if Result = 200 then begin Doc := TgoBsonDocument.Parse(Response); Friends := Doc['friends'].ToBsonDocument; Summary := Friends['summary'].ToBsonDocument; AFriendsCount := Summary['total_count']; end; end; function TFacebook.GetUserFriends(const AUserId: String; out AFriends: TFacebookUsers): Integer; var Url: String; Doc, User, Paging, Picture, PictureData: TgoBsonDocument; Data: TgoBsonArray; Value: TgoBsonValue; I, Index: Integer; Response: String; begin Index := 0; Url := 'https://graph.facebook.com/' + AUserId + '/friends?fields=id,name,picture.type(large)&access_token=' + FAccessToken; repeat Result := Get(Url, Response); if Result = 200 then begin Doc := TgoBsonDocument.Parse(Response); Data := Doc['data'].ToBsonArray; SetLength(AFriends, Length(AFriends) + Data.Count); for I := 0 to Data.Count - 1 do begin User := Data[I].AsBsonDocument; AFriends[Index].Id := User['id']; AFriends[Index].Name := User['name']; Picture := User['picture'].AsBsonDocument; if not Picture.IsNil then begin PictureData := Picture['data'].AsBsonDocument; if not PictureData.IsNil then AFriends[Index].ImageUrl := PictureData['url']; end; Inc(Index); end; { next page } if Doc.TryGetValue('paging', Value) then begin Paging := Value.AsBsonDocument; Url := Paging['next']; end else Break; end; until (Url = 'null') or (Result <> 200); end; end.
unit f1df_AddReportm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, ActnList, cxCheckBox, IBase, Unit_ZGlobal_Consts, zMessages, ZProc, DB, FIBDataSet, pFIBDataSet, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxRadioGroup, cxGroupBox; type TFAddReport = class(TForm) SpinEditKvartal: TcxSpinEdit; SpinEditYear: TcxSpinEdit; LabelYear: TcxLabel; LabelKvartal: TcxLabel; Bevel1: TBevel; YesBtn: TcxButton; CancelBtn: TcxButton; DB: TpFIBDatabase; StProcTransaction: TpFIBTransaction; StProc: TpFIBStoredProc; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; CheckBoxPTin: TcxCheckBox; LookupComboBoxTypes: TcxLookupComboBox; LabelType: TcxLabel; DSetTypes: TpFIBDataSet; ReadTransaction: TpFIBTransaction; DSourceTypes: TDataSource; CheckBoxWork: TcxCheckBox; CheckBoxStud: TcxCheckBox; DSetFirm: TpFIBDataSet; DSourceFirm: TDataSource; CheckBoxAll: TcxCheckBox; BoxShifr: TcxGroupBox; LabelShifr: TcxLabel; LookupComboBoxFirm: TcxLookupComboBox; procedure ActionYesExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure CheckBoxAllPropertiesChange(Sender: TObject); private PId_1Df:Integer; PLanguageIndex:Byte; PDb_Handle:TISC_DB_HANDLE; public constructor Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE);reintroduce; property Id_1Df:Integer read PId_1Df; end; function ShowFormAddReport(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE):integer; implementation {$R *.dfm} function ShowFormAddReport(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE):integer; var Form:TFAddReport; begin Result:=0; Form := TFAddReport.Create(AOwner,ADB_handle); if Form.ShowModal=mrYes then Result:=Form.Id_1Df; Form.Destroy; end; constructor TFAddReport.Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE); begin inherited Create(AOwner); PDb_Handle := ADB_handle; PLanguageIndex := LanguageIndex; Caption := Caption_Form[PLanguageIndex]; LabelYear.Caption := LabelYear_Caption[PLanguageIndex]; LabelKvartal.Caption := LabelKvartal_Caption[PLanguageIndex]; LabelType.Caption := LabelType_Caption[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; CheckBoxPTin.Properties.Caption := LabelNotTinPeople_Caption[PLanguageIndex]; SpinEditKvartal.Value:=IfThen(((ValueFieldZSetup(PDb_Handle,'MONTH_SET')-1)div 3)=0,4,(ValueFieldZSetup(PDb_Handle,'MONTH_SET')-1)div 3); SpinEditYear.Value:=IfThen(SpinEditKvartal.Value=4,ValueFieldZSetup(PDb_Handle,'YEAR_SET')-1,ValueFieldZSetup(PDb_Handle,'YEAR_SET')); DB.Handle := PDb_Handle; DSetTypes.SQLs.SelectSQL.Text := 'SELECT * FROM Z_1DF_INI_TYPE_REPORT'; DSetTypes.Open; LookupComboBoxTypes.EditValue := 1; DSetFirm.SQLs.SelectSQL.Text := 'SELECT ID_1DF_FIRM, FIRM_NAME FROM Z_1DF_FIRM'; DSetFirm.Open; LookupComboBoxFirm.EditValue := 1; CheckBoxWork.EditValue:='T'; CheckBoxStud.EditValue:='T'; if(ValueFieldZSetup(PDb_Handle,'IS_UNIVER')='F')then begin CheckBoxWork.Visible:=false; CheckBoxStud.Visible:=false; CheckBoxWork.EditValue:='T'; CheckBoxStud.EditValue:='F'; end; end; procedure TFAddReport.ActionYesExecute(Sender: TObject); begin try self.Enabled := False; PId_1Df := 0; with StProc do try Transaction.StartTransaction; StoredProcName := 'Z_1DF_HEADERS_I'; Prepare; ParamByName('YEAR_1DF').AsInteger := SpinEditYear.EditValue; ParamByName('KVARTAL_1DF').AsInteger := SpinEditKvartal.EditValue; ParamByName('IS_INN').AsString := CheckBoxPTin.EditValue; ParamByName('ID_TYPE').AsInteger := LookupComboBoxTypes.EditValue; ParamByName('IS_WORK_INCLUDE').AsString := CheckBoxWork.EditValue; ParamByName('IS_STUD_INCLUDE').AsString := CheckBoxStud.EditValue; if(CheckBoxAll.Checked=true)then ParamByName('ID_1DF_FIRM').AsInteger := LookupComboBoxFirm.EditValue else ParamByName('ID_1DF_FIRM').AsInteger := -1; ExecProc; PId_1Df := ParamByName('ID').AsInteger; Transaction.Commit; if ReadTransaction.InTransaction then ReadTransaction.Commit; ModalResult := mrYes; except on E:Exception do begin zShowMessage(Error_Caption[PLanguageIndex],e.Message,mtInformation,[mbOK]); Transaction.Rollback; end; end; finally self.Enabled := True; end; end; procedure TFAddReport.ActionCancelExecute(Sender: TObject); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; ModalResult:=mrCancel; end; procedure TFAddReport.CheckBoxAllPropertiesChange(Sender: TObject); begin BoxShifr.Enabled:=CheckBoxAll.Checked; LabelShifr.Enabled:=CheckBoxAll.Checked; LookupComboBoxFirm.Enabled:=CheckBoxAll.Checked; end; end.
unit uPrintWorker; interface uses Classes, SysUtils, Windows, cmbtls28, cmbtll28, L28, ADODB, DB; type TPrintWorker = class(TThread) private procedure DesignerPrintPreview(); procedure DefineCurrentRecord(); function GetTempFile(): string; protected procedure Execute; override; procedure UpdateCaption(); public printInstance: TL28_; projectFile: string; originalProjectFile: string; controlHandle: Cardinal; eventHandle: Cardinal; pageCount: integer; doExport: boolean; FCount: integer; Terminated: boolean; IsPrinting: boolean; procedure FinalizePrinting(); procedure ReleasePreviewControl(alsoEmptyPreviewControl: integer); procedure Abort(); end; implementation uses uDesignerPreview; { PrintWorker } {D: Diese Prozedure übergibt den aktuellen Datensatz an List & Label. } { Hier können Sie ansetzen, um ganz andere Datenquellen zu verwenden } {US: This procedure passes the current record to List & Label. Customize} { it in order to pass completely different data } procedure TPrintWorker.Abort; begin {D: Druck der Tabelle beenden, angehängte Objekte drucken US: Finish printing the table, print linked objects} while printInstance.LlPrintFieldsEnd = LL_WRN_REPEAT_DATA do; {D: Druck beenden} {US: Stop printing} printInstance.LlPrintEnd(0); Terminated := True; end; procedure TPrintWorker.DefineCurrentRecord(); var i: integer; begin {D: Wiederholung für alle Datensatzfelder } {US: Loop through all fields in the present recordset} For i:= 0 to (frmDesignerPreview.Customers.FieldCount-1) do {D: Umsetzung der Datenbank-Feldtypen in List & Label Feldtypen } {US: Transform database field types into List & Label field types} printInstance.LlDefineFieldFromTField(frmDesignerPreview.Customers.Fields[i]); end; procedure TPrintWorker.DesignerPrintPreview; var Ret: integer; tempFileName: string; printPages: integer; begin // D: Aktualisierung der Echtdatenvorschau Toolbar: // US: Update the real data preview toolbar: PostMessage(controlHandle, LS_VIEWERCONTROL_UPDATE_TOOLBAR, 0, 0); // D: Temporäres List & Label Projekt für den Druck übergeben: // US: Set temp List & Label project file for printing: tempFileName := GetTempFile(); printInstance.LlSetOptionString(LL_OPTIONSTR_PREVIEWFILENAME, ExtractFileName(tempFileName)); printInstance.LlPreviewSetTempPath(ExtractFilePath(tempFileName)); printInstance.IncrementalPreview := 1; printInstance.NoNoTableCheck := Yes; SetEvent(eventHandle); printInstance.LlSetOptionString(LL_OPTIONSTR_ORIGINALPROJECTFILENAME, originalProjectFile); if not doExport then begin // D: Aufruf, damit das Vorschau-Control die Kontrolle über die Vorschaudatei erhält: // US: Set the preview control as master for the preview file: printInstance.LlAssociatePreviewControl(controlHandle, 1); end; frmDesignerPreview.Customers.First(); DefineCurrentRecord(); try if not doExport then begin printInstance.LlPrintWithBoxStart(LL_PROJECT_LIST, projectFile, LL_PRINT_PREVIEW, LL_BOXTYPE_STDABORT, controlHandle, ''); if pageCount > 0 then // D: Maximalzahl der auzugebenen Vorschauseiten: // US: Set the page count for the preview: printInstance.LlPrintSetOption(LL_OPTION_LASTPAGE, pageCount); end else begin // D: Fortschrittsanzeige während des Exports anzeigen: // US: Show the status box during the export: printInstance.LlPrintWithBoxStart(LL_PROJECT_LIST, projectFile, LL_PRINT_EXPORT, LL_BOXTYPE_STDABORT, controlHandle, 'Exporting report...'); if printInstance.LlPrintOptionsDialog(controlHandle, '')=LL_ERR_USER_ABORTED then begin printInstance.LlPrintEnd(0); exit; end; end; printPages := 1; //D: Erste Seite des Drucks initalisieren, um sicherzustellen, dass ein Seitenumbruch vor der Tabelle erfolgt //US: Initialize first page. A page wrap may occur already caused by objects which are printed before the table while printInstance.LlPrint = LL_WRN_REPEAT_DATA do begin inc(printPages); end; IsPrinting := true; while not frmDesignerPreview.Customers.EOF do begin {D: Jetzt Echtdaten für aktuellen Datensatz übergeben} {US: pass data for current record} DefineCurrentRecord(); {D: Tabellenzeile ausgeben, auf Rückgabewert prüfen und ggf. Seitenumbruch oder Abbruch auslösen {US: Print table line, check return value and abort printing or wrap pages if neccessary} Ret:=printInstance.LlPrintFields; if Ret = LL_ERR_USER_ABORTED then begin {D: Benutzerabbruch} {US: User aborted} printInstance.LlPrintEnd(0); exit; end; {D: Seitenumbruch auslösen, bis Datensatz vollständig gedruckt wurde US: Wrap pages until record was fully printed} while Ret = LL_WRN_REPEAT_DATA do begin printInstance.LlPrint(); inc(printPages); Ret := printInstance.LlPrintFields; end; if (printPages > pageCount) and (pageCount <> 0) then begin // D: Maximale Seitenanzahl erreicht, Druckvorgang abbrechen: // US: Maximum page count reached, abort print job: printInstance.LlPrintAbort; {D: Druck beenden} {US: Stop printing} printInstance.LlPrintEnd(0); exit; end; {D: Fortschrittsanzeige aktualisieren} {US: Refresh progress meter} printInstance.LlPrintSetBoxText('Printing report...',Round(frmDesignerPreview.Customers.RecNo/frmDesignerPreview.Customers.RecordCount*100)); frmDesignerPreview.Customers.Next; end; {D: Druck der Tabelle beenden, angehängte Objekte drucken US: Finish printing the table, print linked objects} while printInstance.LlPrintFieldsEnd = LL_WRN_REPEAT_DATA do; {D: Druck beenden} {US: Stop printing} printInstance.LlPrintEnd(0); finally DeleteFile(PChar(projectFile)); printInstance.LlAssociatePreviewControl(0,1); Terminated := true; end; end; procedure TPrintWorker.Execute; begin IsPrinting := false; Synchronize( DesignerPrintPreview ); end; procedure TPrintWorker.FinalizePrinting(); begin Abort(); ReleasePreviewControl(0); end; function TPrintWorker.GetTempFile: string; var Buffer: PXChar; begin GetMem(Buffer, (MAX_PATH+1)*sizeof(XChar)); LlGetTempFileName('~', 'll', Buffer, MAX_PATH+1, 0); result:=String(Buffer); FreeMem(Buffer); end; procedure TPrintWorker.ReleasePreviewControl(alsoEmptyPreviewControl: integer); begin printInstance.LlAssociatePreviewControl(controlHandle, alsoEmptyPreviewControl) end; procedure TPrintWorker.UpdateCaption(); begin // frmDesignerPreview.Memo1.Lines.Add('Updated in a thread: ' + myMessage); end; end.
//****************************************************************************** // Проект "" // Справочник типов водомеров // // последние изменения //****************************************************************************** unit uHydrometerType_main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxTextEdit, cxCheckBox, Placemnt, Menus, cxGridTableView, ImgList, dxBar, dxBarExtItems, cxGridLevel, cxGridCustomTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, dxStatusBar, uCommon_Funcs, uConsts, uHydrometerType_DM, uHydrometerType_AE, uCommon_Messages, uConsts_Messages, uCommon_Types, cxTimeEdit, AccMGMT, cxContainer, cxLabel, cxDBLabel, ExtCtrls, StdCtrls; type TfrmHydrometerType_Main = class(TForm) StatusBar: TdxStatusBar; Grid: TcxGrid; GridDBView: TcxGridDBTableView; name_hydrometer_type: TcxGridDBColumn; caliber_hydrometer: TcxGridDBColumn; GridLevel: TcxGridLevel; BarManager: TdxBarManager; AddButton: TdxBarLargeButton; EditButton: TdxBarLargeButton; DeleteButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; ExitButton: TdxBarLargeButton; SelectButton: TdxBarLargeButton; PopupImageList: TImageList; LargeImages: TImageList; DisabledLargeImages: TImageList; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; Default_StyleSheet: TcxGridTableViewStyleSheet; DevExpress_Style: TcxGridTableViewStyleSheet; PopupMenu1: TPopupMenu; AddPop: TMenuItem; EditPop: TMenuItem; DeletePop: TMenuItem; RefreshPop: TMenuItem; ExitPop: TMenuItem; bsFormStorage: TFormStorage; id_unit_meas: TcxGridDBColumn; capacity_hydrometer: TcxGridDBColumn; accuracy_hydrometer: TcxGridDBColumn; Panel1: TPanel; FactoryDBLabel: TcxDBLabel; NoteDBLabel: TcxDBLabel; FactoryLabel: TLabel; NoteLabel: TLabel; procedure AddPopClick(Sender: TObject); procedure EditPopClick(Sender: TObject); procedure DeletePopClick(Sender: TObject); procedure RefreshPopClick(Sender: TObject); procedure ExitPopClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure ExitButtonClick(Sender: TObject); procedure SelectButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure GridDBViewDblClick(Sender: TObject); private PLanguageIndex: byte; DM : THydrometerType_DM; procedure FormIniLanguage; public res:Variant; Is_admin:Boolean; constructor Create(AParameter:TbsSimpleParams);reintroduce; end; { frmHydrometerType_Main: TfrmHydrometerType_Main; } implementation {$R *.dfm} constructor TfrmHydrometerType_Main.Create(AParameter:TbsSimpleParams); begin Screen.Cursor:=crHourGlass; inherited Create(AParameter.Owner); self.Is_admin := AParameter.is_admin; DM:=THydrometerType_DM.Create(Self); DM.DB.Handle := AParameter.Db_Handle; DM.DB.Connected := True; DM.ReadTransaction.StartTransaction; GridDBView.DataController.DataSource := DM.DataSource; FactoryDBLabel.DataBinding.DataSource := DM.DataSource; NoteDBLabel.DataBinding.DataSource := DM.DataSource; DM.DataSet.Close; DM.DataSet.SQLs.SelectSQL.Text := 'select * from BS_SP_HYDROMETER_TYPE_SEL'; DM.DataSet.Open; if AParameter.ID_Locate <> null then DM.DataSet.Locate('id_hydrometer_type', AParameter.ID_Locate, [] ); FormIniLanguage(); Screen.Cursor:=crDefault; bsFormStorage.RestoreFormPlacement; end; procedure TfrmHydrometerType_Main.FormIniLanguage; begin PLanguageIndex:= uCommon_Funcs.bsLanguageIndex(); //кэпшн формы Caption:= uConsts.bs_sp_hydrometer_type[PLanguageIndex]; //названия кнопок AddButton.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex]; EditButton.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex]; DeleteButton.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex]; RefreshButton.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex]; SelectButton.Caption := uConsts.bs_SelectBtn_Caption[PLanguageIndex]; ExitButton.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex]; // попап AddPop.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex]; EditPop.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex]; DeletePop.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex]; RefreshPop.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex]; ExitPop.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex]; //грид name_hydrometer_type.Caption := uConsts.bs_name_hydrometer_type[PLanguageIndex]; caliber_hydrometer.Caption := uConsts.bs_caliber_hydrometer[PLanguageIndex]; id_unit_meas.Caption := uConsts.bs_id_unit_meas[PLanguageIndex]; capacity_hydrometer.Caption := uConsts.bs_capacity_hydrometer[PLanguageIndex]; accuracy_hydrometer.Caption := uConsts.bs_accuracy_hydrometer[PLanguageIndex]; NoteLabel.caption := uConsts.bs_note_hydrometer[PLanguageIndex]; FactoryLabel.caption := uConsts.bs_factory_hydrometer[PLanguageIndex]; //статусбар StatusBar.Panels[0].Text:= uConsts.bs_InsertBtn_ShortCut[PLanguageIndex] + uConsts.bs_InsertBtn_Caption[PLanguageIndex]; StatusBar.Panels[1].Text:= uConsts.bs_EditBtn_ShortCut[PLanguageIndex] + uConsts.bs_EditBtn_Caption[PLanguageIndex]; StatusBar.Panels[2].Text:= uConsts.bs_DeleteBtn_ShortCut[PLanguageIndex] + uConsts.bs_DeleteBtn_Caption[PLanguageIndex]; StatusBar.Panels[3].Text:= uConsts.bs_RefreshBtn_ShortCut[PLanguageIndex] + uConsts.bs_RefreshBtn_Caption[PLanguageIndex]; StatusBar.Panels[4].Text:= uConsts.bs_EnterBtn_ShortCut[PLanguageIndex] + uConsts.bs_SelectBtn_Caption[PLanguageIndex]; StatusBar.Panels[5].Text:= uConsts.bs_ExitBtn_ShortCut[PLanguageIndex] + uConsts.bs_ExitBtn_Caption[PLanguageIndex]; end; procedure TfrmHydrometerType_Main.FormClose(Sender: TObject; var Action: TCloseAction); begin bsFormStorage.SaveFormPlacement; if FormStyle = fsMDIChild then action:=caFree else DM.Free; end; procedure TfrmHydrometerType_Main.FormShow(Sender: TObject); begin if FormStyle = fsMDIChild then SelectButton.Visible:=ivNever; end; procedure TfrmHydrometerType_Main.GridDBViewDblClick(Sender: TObject); begin if FormStyle = fsNormal then SelectButtonClick(Sender) else EditButtonClick(Sender); end; procedure TfrmHydrometerType_Main.AddPopClick(Sender: TObject); begin AddButtonClick(Sender); end; procedure TfrmHydrometerType_Main.EditPopClick(Sender: TObject); begin EditButtonClick(Sender); end; procedure TfrmHydrometerType_Main.DeletePopClick(Sender: TObject); begin DeleteButtonClick(Sender); end; procedure TfrmHydrometerType_Main.RefreshPopClick(Sender: TObject); begin RefreshButtonClick(Sender); end; procedure TfrmHydrometerType_Main.ExitPopClick(Sender: TObject); begin ExitButtonClick(Sender); end; procedure TfrmHydrometerType_Main.AddButtonClick(Sender: TObject); var ViewForm : TfrmHydrometerType_AE; begin if not Is_Admin then if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_HydrType','Add') <> 0 then begin messagebox(handle, pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex] +#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]), pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok); exit; end; ViewForm := TfrmHydrometerType_AE.Create(Self, PLanguageIndex); ViewForm.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex]; if ViewForm.ShowModal = mrOk then begin with DM.StProc do begin Transaction.StartTransaction; StoredProcName := 'BS_SP_HYDROMETER_TYPE_INS'; Prepare; ParamByName('name_hydrometer_type').AsString := ViewForm.NameEdit.Text; ParamByName('caliber_hydrometer').AsFloat := strtofloat(ViewForm.CalibrEdit.Text); ParamByName('id_unit_meas').AsInteger := strtoint(ViewForm.MeasCalibrEdit.Text); ParamByName('capacity_hydrometer').AsInteger := strtoint(ViewForm.CapacityEdit.Text); ParamByName('accuracy_hydrometer').AsInteger := strtoint(ViewForm.AccuracyEdit.Text); ParamByName('note_hydrometer').AsString := ViewForm.NoteMemo.Text; ParamByName('factory_hydrometer').AsString := ViewForm.FactoryEdit.Text; ExecProc; try Transaction.Commit; except on E:Exception do begin LogException; bsShowMessage('Error',e.Message,mtError,[mbOK]); Transaction.Rollback; raise; end; end; end; RefreshButtonClick(self); end; end; procedure TfrmHydrometerType_Main.EditButtonClick(Sender: TObject); var ViewForm : TfrmHydrometerType_AE; begin if not Is_Admin then if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_HydrType','Edit') <> 0 then begin messagebox(handle, pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex] +#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]), pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok); exit; end; If GridDBView.DataController.RecordCount = 0 then Exit; ViewForm:= TfrmHydrometerType_AE.Create(Self, PLanguageIndex); ViewForm.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex]; ViewForm.NameEdit.Text := DM.DataSet['name_hydrometer_type']; ViewForm.CalibrEdit.Text := DM.DataSet['caliber_hydrometer']; ViewForm.MeasCalibrEdit.Text := DM.DataSet['id_unit_meas']; ViewForm.CapacityEdit.Text := DM.DataSet['capacity_hydrometer']; ViewForm.AccuracyEdit.Text := DM.DataSet['accuracy_hydrometer']; ViewForm.NoteMemo.Text := DM.DataSet['note_hydrometer']; ViewForm.FactoryEdit.Text := DM.DataSet['factory_hydrometer']; if ViewForm.ShowModal = mrOk then begin with DM.StProc do Begin Transaction.StartTransaction; StoredProcName := 'BS_SP_HYDROMETER_TYPE_UPD'; Prepare; ParamByName('id_hydrometer_type').AsInt64 := DM.DataSet['id_hydrometer_type']; ParamByName('name_hydrometer_type').AsString := ViewForm.NameEdit.Text; ParamByName('caliber_hydrometer').AsFloat := strtofloat(ViewForm.CalibrEdit.Text); ParamByName('id_unit_meas').AsInteger := strtoint(ViewForm.MeasCalibrEdit.Text); ParamByName('capacity_hydrometer').AsInteger := strtoint(ViewForm.CapacityEdit.Text); ParamByName('accuracy_hydrometer').AsInteger := strtoint(ViewForm.AccuracyEdit.Text); ParamByName('note_hydrometer').AsString := ViewForm.NoteMemo.Text; ParamByName('factory_hydrometer').AsString := ViewForm.FactoryEdit.Text;; ExecProc; try Transaction.Commit; except on E:Exception do begin LogException; bsShowMessage('Error',e.Message,mtError,[mbOK]); Transaction.Rollback; end; end; end; RefreshButtonClick(self); end; end; procedure TfrmHydrometerType_Main.DeleteButtonClick(Sender: TObject); var i: byte; begin if not Is_Admin then if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_HydrType','Del') <> 0 then begin messagebox(handle, pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex] +#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]), pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok); exit; end; If GridDBView.DataController.RecordCount = 0 then Exit; i:= uCommon_Messages.bsShowMessage(uConsts.bs_Confirmation_Caption[PLanguageIndex], uConsts_Messages.bs_hydrometer_type_del[PLanguageIndex]+' '+DM.DataSet['name_hydrometer_type']+'?', mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit; with DM.StProc do begin Transaction.StartTransaction; StoredProcName := 'BS_SP_HYDROMETER_TYPE_DEL'; Prepare; ParamByName('id_hydrometer_type').AsInt64 := DM.DataSet['id_hydrometer_type']; ExecProc; Transaction.Commit; try except on E:Exception do begin LogException; bsShowMessage('Error',e.Message,mtError,[mbOK]); Transaction.Rollback; end; end; end; RefreshButtonClick(self); end; procedure TfrmHydrometerType_Main.RefreshButtonClick(Sender: TObject); begin Screen.Cursor := crHourGlass; DM.DataSet.Close; DM.DataSet.Open; Screen.Cursor := crDefault; end; procedure TfrmHydrometerType_Main.ExitButtonClick(Sender: TObject); begin close; end; procedure TfrmHydrometerType_Main.SelectButtonClick(Sender: TObject); var id_sp: int64; begin if GridDBView.datacontroller.recordcount = 0 then exit; Res:=VarArrayCreate([0,3],varVariant); id_sp:= DM.DataSet['id_hydrometer_type']; Res[0]:= id_sp; Res[1]:=DM.DataSet['name_hydrometer_type']; ModalResult:=mrOk; end; end.
unit Form.StringSortTest; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls; type TFormStringSortTest = class(TForm) PageControlMain: TPageControl; PanelBottom: TPanel; ButtonInitialize: TButton; TabSheetData: TTabSheet; TabSheetStringList: TTabSheet; TabSheetListView: TTabSheet; MemoData: TMemo; MemoStringList: TMemo; ButtonSort: TButton; RadioGroupSortType: TRadioGroup; ListView1: TListView; TabSheetListViewGroup: TTabSheet; ListView2: TListView; procedure FormCreate(Sender: TObject); procedure ButtonInitializeClick(Sender: TObject); procedure ButtonSortClick(Sender: TObject); procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn); procedure ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); private { Private declarations } FColumnToSort: Integer; FAsc: Boolean; procedure InitData; procedure DoTestStringList; procedure DoTestListView; procedure DoTestListViewGroup; public { Public declarations } end; var FormStringSortTest: TFormStringSortTest; implementation uses CommCtrl, Sort.StringCompare; {$R *.dfm} procedure TFormStringSortTest.ButtonInitializeClick(Sender: TObject); var I: Integer; ListItem: TListItem; ListGroup: TListGroup; begin case PageControlMain.ActivePageIndex of 0: InitData; 1: MemoStringList.Clear; 2: begin ListView1.Clear; for I := 0 to MemoData.Lines.Count - 1 do begin ListItem := ListView1.Items.Add; ListItem.Caption := MemoData.Lines.Strings[I]; ListItem.SubItems.Add( MemoData.Lines.Strings[I] ); ListItem.SubItems.Add( MemoData.Lines.Strings[I] ); end; end; 3: begin ListView2.Clear; ListView2.Items.BeginUpdate; for I := 0 to MemoData.Lines.Count - 1 do begin ListGroup := ListView2.Groups.Add; ListGroup.Header := MemoData.Lines.Strings[I]; ListGroup.Footer := ''; ListItem := ListView2.Items.Add; ListItem.Caption := MemoData.Lines.Strings[I]; ListItem.GroupID := ListGroup.ID; end; ListView2.Items.EndUpdate; end; end; end; procedure TFormStringSortTest.ButtonSortClick(Sender: TObject); begin case PageControlMain.ActivePageIndex of 0: begin end; 1: DoTestStringList; 2: DoTestListView; 3: DoTestListViewGroup; end; end; procedure TFormStringSortTest.DoTestListView; begin FColumnToSort := 0; ListView1.AlphaSort; FAsc := not FAsc; end; function ListView_GroupSort(Group1_ID: Integer; Group2_ID: Integer; pvData: Pointer): Integer; stdcall; var GroupSortData: PGroupSortData; Str1, Str2: string; CompareResult: Integer; begin Result := 0; GroupSortData := PGroupSortData(pvData); Str1 := GroupSortData.ListView.Groups.Items[Group1_ID].Header; Str2 := GroupSortData.ListView.Groups.Items[Group2_ID].Header; case FormStringSortTest.RadioGroupSortType.ItemIndex of 0: Result := NaturalOrderCompareString( Str1, Str2, True ); 1: Result := CompareStr( Str1, Str2 ); 2: begin CompareResult := CompareString( LOCALE_USER_DEFAULT, 0, PWideChar(Str1), Length(Str1), PWideChar(Str2), Length(Str2) ); case CompareResult of CSTR_LESS_THAN: Result := -1; CSTR_GREATER_THAN: Result := 1; CSTR_EQUAL: Result := 0; end; end; 3: Result := StrCmpLogicalW( PWideChar(Str1), PWideChar(Str2) ); end; if GroupSortData.Ascend then Result := -Result; end; procedure TFormStringSortTest.DoTestListViewGroup; var GroupSortData: TGroupSortData; begin GroupSortData.ListView := ListView2; GroupSortData.Ascend := FAsc; ListView_SortGroups( ListView2.Handle, ListView_GroupSort, @GroupSortData ); FAsc := not FAsc; end; procedure TFormStringSortTest.DoTestStringList; var StringList: TStringList; begin StringList := TStringList.Create; try StringList.Assign( MemoData.Lines ); if FAsc then begin case RadioGroupSortType.ItemIndex of 0: StringList.CustomSort( TStringListSortCompareDesc.DoNatural ); 1: StringList.CustomSort( TStringListSortCompareDesc.DoCompareStr ); 2: StringList.CustomSort( TStringListSortCompareDesc.DoWinAPI ); 3: StringList.CustomSort( TStringListSortCompareDesc.DoStrCmpLogicalW ); end; end else begin case RadioGroupSortType.ItemIndex of 0: StringList.CustomSort( TStringListSortCompare.DoNatural ); 1: StringList.CustomSort( TStringListSortCompare.DoCompareStr ); 2: StringList.CustomSort( TStringListSortCompare.DoWinAPI ); 3: StringList.CustomSort( TStringListSortCompare.DoStrCmpLogicalW ); end; end; FAsc := not FAsc; MemoStringList.Lines.Assign( StringList ); finally StringList.Free; end; end; procedure TFormStringSortTest.FormCreate(Sender: TObject); begin Caption := Application.Title; PageControlMain.ActivePageIndex := 0; InitData; FAsc := True; end; procedure TFormStringSortTest.InitData; begin MemoData.Clear; MemoData.Lines.Add( '20 - Twenty' ); MemoData.Lines.Add( '1 - One' ); MemoData.Lines.Add( '10 - Ten (1)' ); MemoData.Lines.Add( '2 - Two' ); MemoData.Lines.Add( '20 - Twenty' ); MemoData.Lines.Add( '15 - Fifteen' ); MemoData.Lines.Add( '1 - One (b)' ); MemoData.Lines.Add( '10 - Ten (2)' ); MemoData.Lines.Add( '3 - Three' ); MemoData.Lines.Add( '10 - Ten (100)' ); MemoData.Lines.Add( '1-2' ); MemoData.Lines.Add( '1-02' ); MemoData.Lines.Add( '1-20' ); MemoData.Lines.Add( '10-20' ); MemoData.Lines.Add( 'fred' ); MemoData.Lines.Add( 'jane' ); MemoData.Lines.Add( 'pic01",' ); MemoData.Lines.Add( 'pic2' ); MemoData.Lines.Add( 'pic02' ); MemoData.Lines.Add( 'pic02a' ); MemoData.Lines.Add( 'pic3' ); MemoData.Lines.Add( 'pic4' ); MemoData.Lines.Add( 'pic 4 else' ); MemoData.Lines.Add( 'pic 5' ); MemoData.Lines.Add( 'pic05' ); MemoData.Lines.Add( 'pic 5",' ); MemoData.Lines.Add( 'pic 5 something' ); MemoData.Lines.Add( 'pic 6' ); MemoData.Lines.Add( 'pic 7' ); MemoData.Lines.Add( 'pic100' ); MemoData.Lines.Add( 'pic100a' ); MemoData.Lines.Add( 'pic120' ); MemoData.Lines.Add( 'pic121",' ); MemoData.Lines.Add( 'pic02000' ); MemoData.Lines.Add( 'tom' ); MemoData.Lines.Add( 'x2-g8' ); MemoData.Lines.Add( 'x2-y7' ); MemoData.Lines.Add( 'x2-y08' ); MemoData.Lines.Add( 'x8-y8"' ); MemoData.Lines.Add( 'a - 1' ); MemoData.Lines.Add( 'a - 10' ); MemoData.Lines.Add( 'a - 99' ); MemoData.Lines.Add( 'a - 9' ); MemoData.Lines.Add( 'a - 10000' ); end; procedure TFormStringSortTest.ListView1ColumnClick(Sender: TObject; Column: TListColumn); begin FColumnToSort := Column.Index; (Sender as TCustomListView).AlphaSort; FAsc := not FAsc; end; procedure TFormStringSortTest.ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); var S1, S2: string; CompareResult: Integer; Index: Integer; begin if FColumnToSort = 0 then begin S1 := Item1.Caption; S2 := Item2.Caption; end else begin Index := FColumnToSort - 1; S1 := Item1.SubItems.Strings[Index]; S2 := Item2.SubItems.Strings[Index]; end; case RadioGroupSortType.ItemIndex of 0: Compare := NaturalOrderCompareString( S1, S2, True ); 1: Compare := CompareStr( S1, S2 ); 2: begin CompareResult := CompareString( LOCALE_USER_DEFAULT, 0, PWideChar(S1), Length(S1), PWideChar(S2), Length(S2) ); case CompareResult of CSTR_LESS_THAN: Compare := -1; CSTR_GREATER_THAN: Compare := 1; CSTR_EQUAL: Compare := 0; end; end; 3: Compare := StrCmpLogicalW( PWideChar(S1), PWideChar(S2) ); end; if FAsc then Compare := -Compare; end; end.
unit uMsgConstant; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, siComp, siLangRT; const //EXCLAMATION MSG_EXC_SELECT_A_MODEL: string = ''; (* Please select a model! *) MSG_EXC_BARCODE_EXISTE: string = ''; (* Barcode already in use! *) MSG_EXC_NO_DEFAULT_CASREG: string = ''; (* There is no default Cash Register for this terminal! *) MSG_EXC_NO_ASSOCIETE_CASREG: string = ''; (* The associated CashRegister does not have correspondent in DataBase._Call Administrator! *) MSG_EXC_QTY_BIGGER: string = ''; (* Qty is greater than Qty avaiable in Store plus Open Holds! *) MSG_EXC_MODULE_DISABLE: string = ''; (* Module not included in Current Package. *) MSG_EXC_BARCODE_EXIST_PO: string = ''; (* Model # already exists in this Purchase Order! *) MSG_EXC_NO_MORE_ROWS_RETRIVE: string = ''; (* No more rows to retrieve *) MSG_EXC_INVALID_HOLD_NUMBER: string = ''; (* is not a valid Hold number! *) //EXCLAMATION PARTIAL MSG_EXC_PART1_NO_HOLD_NUMBER: string = ''; (* This Hold number *) MSG_EXC_PART2_NO_HOLD_NUMBER: string = ''; (* does not exist! *) MSG_EXC_PART1_NO_MORE_SERIAL: string = ''; (* Cannot enter more than *) MSG_EXC_PART2_NO_MORE_SERIAL: string = ''; (* serial number(s)! *) //END EXCLAMATION ############################################################ //INFORMATION MSG_INF_FILETER_CLEARED: string = ''; (* Filter(s) cleared. *) MSG_INF_FILETER_SAVED: string = ''; (* Filter(s) saved! *) MSG_INF_NO_FILETER_APPENDED: string = ''; (* No Filter(s) appended. *) MSG_INF_NO_DATA_FOUND: string = ''; (* No Data Found. *) MSG_INF_BARCODE_NOT_DEL: string = ''; (* Barcode cannot be deleted. *) MSG_INF_INVOICE_NOT_FOND: string = ''; (* Invoice # not found. *) MSG_INF_WRONG_QTY: string = ''; (* Wrong Qty. *) MSG_INF_ADJUSTMENT: string = ''; (* Adjustment complete. *) MSG_INF_CSR_IS_CLOSED: string = ''; (* Close Cash Register error. *) MSG_INF_PASSWORD_CANNOT_BE_NULL:string = ''; (* Password cannot be blank *) MSG_INF_INVALID_PASSWORD: string = ''; (* Invalid password. *) MSG_INF_INVALID_USER_PASSWORD: string = ''; (* User or Password is invalid. *) MSG_INF_CHOOSE_NAME: string = ''; (* Name cannot be blank! *) MSG_INF_RESTORED_SUCESSFULY: string = ''; (* request(s) successfully restored. *) MSG_INF_DATA_SUCESSFULY: string = ''; (* Data successfully transfered. *) MSG_INF_ERROR: string = ''; (* Error! *) MSG_INF_SUPPLU_ADJ_DATE: string = ''; (* You must supply an adjustment date. *) MSG_INF_CANNOT_ACCESS_MODULE: string = ''; (* You do not have access to this module. *) MSG_INF_NO_ASSOC_COMMITION: string = ''; (* Incomplete user information. Operation aborted! *) MSG_INF_ONE_OPEN_PO_VENDOR: string = ''; (* You should have at least one Open PO for this Vendor. *) MSG_INF_ONE_OPEN_CASREG_MANAGER:string = ''; (* Function unauthorized for this user. *) MSG_INF_MANAGER_TONEGATIVE_DISC:string = ''; (* You cannot make negative refunds._Try inserting new item first. *) MSG_INF_COUNT_ITEMS: string = ''; (* You should count all items *) MSG_INF_SELECT_USER: string = ''; (* You must select user name. *) MSG_INF_NOT_CHANGE_ITEMS: string = ''; (* You cannot change items not inserted by yourself. *) MSG_INF_NOT_DELETE_ITEMS: string = ''; (* You cannot delete items not inserted by yourself. *) MSG_INF_NOT_DEL_ITEMS_LAYAWAY: string = ''; (* You cannot delete items on layaway. *) MSG_INF_NOT_MANAGE_CR: string = ''; (* You cannot manage Reconciled Registers._You must uncheck first. *) MSG_INF_NOT_EMPTY_VALUES: string = ''; (* You cannot pay empty values. *) MSG_INF_NOT_GIVE_GIFTS: string = ''; (* You cannot give Gifts. *) MSG_INF_NOT_REFUND_ITEM: string = ''; (* You cannot give refunds._Call Manager. *) MSG_INF_NOT_SELL_BELLOW_COST: string = ''; (* You cannot sell below cost price. *) MSG_INF_NOT_DUPLICATED_QTY: string = ''; (* Qty cannot be duplicated. *) MSG_INF_REBUILD_IDT: string = ''; (* Rebuild Identity completed. *) MSG_INF_NOT_QTY_SMALLER_1: string = ''; (* Qty should be greater than 1. *) MSG_INF_NOT_RECEIVE_HOLD: string = ''; (* Error detected. Please try again. *) MSG_INF_MODEL_DELETED: string = ''; (* Model was successfully deleted. *) MSG_INF_CHANGES_SYS: string = ''; (* Changes will take effect next time you enter system. *) MSG_INF_TRY_ADD_ROUTES: string = ''; (* You added a route(s) with less Pax than minimum required. Number has been changed to *) MSG_INF_NOT_DESCRIPTION_EMPTY: string = ''; (* Description cannot be empty. *) MSG_INF_NOT_EXCEL_ITEMS: string = ''; (* There is no item(s) to export to Spreadsheet. *) MSG_INF_NOT_MANEGER_PASWORD: string = ''; (* Not a valid Manager Password. *) MSG_INF_NOT_CASHIER_PASWORD: string = ''; (* Not a valid Cashier Password. *) MSG_INF_HOLD_PAYING: string = ''; (* Hold is being paid at this moment._Cannot be modified. *) MSG_INF_HOLD_PAYING_NO_DELETE: string = ''; (* Hold is being paid at this moment._Cannot be deleted. *) MSG_INF_INVOICE_NOT_REACH: string = ''; (* Invoice did not reach minimun for this Payment type. *) MSG_INF_INVOICE_NOT_HAVE_ITEM: string = ''; (* Invoice does not contain this item. *) MSG_INF_INVOICE_NOT_REACH_DATE: string = ''; (* Invoice Total did not reach minimun for this Deposit date. *) MSG_INF_PAYTYPE_NOT_THIS_DATE: string = ''; (* Payment Type does not allow this Deposit Date. *) MSG_INF_INVOICE_REC_ONLY_CASH: string = ''; (* This Invoice is cash only. *) MSG_INF_VENDOR_EXIST: string = ''; (* Vendor already exists in this quote. *) MSG_INF_MODEL_EXIST: string = ''; (* Model already exists in this quote. *) MSG_INF_INVOICE_HAS_SETUP: string = ''; (* Invoice had already been setup for a postdate Payment. *) MSG_INF_MODEL_ORDERED: string = ''; (* Model is already on order. *) MSG_INF_PO_OPEN: string = ''; (* Vendor does not have an open PO._A new PO has been created. *) MSG_INF_PO_CREATED: string = ''; (* A PO for this Purchase Order was created. *) MSG_INF_MANAGER_CAN_REMOV_HOLD: string = ''; (* Only Manager can remove this Hold. *) MSG_INF_CASH_IN_DEPOSIT: string = ''; (* Cash should not exceed Max Cash Deposit. *) MSG_INF_TOTAL_SMALLER_PRE_SALE: string = ''; (* Amount received is less than Invoice Amount. *) MSG_INF_GIFT_REGIST: string = ''; (* gift has been registered. *) MSG_INF_HOLD_IS_LOCK: string = ''; (* This Hold is LOCKED. Verify there are no open users before unlocking. *) MSG_INF_HOLD_IS_USING: string = ''; (* Hold in use by another terminal._You may continue. *) MSG_INF_HOLD_CANNOT_DELETE: string = ''; (* Hold in use by another terminal._Cannot be deleted. *) MSG_INF_CLOCK_IN: string = ''; (* Clock In. *) MSG_INF_CLOCK_OUT: string = ''; (* Clock Out. *) MSG_INF_TIME_ENTERED: string = ''; (* You have already Clocked Out. *) MSG_INF_EXPIRED_TIME: string = ''; (* Time limit to CLOCK OUT expired._Check with manager. *) MSG_INF_ITEM_HAS_POS_QTY: string = ''; (* This item has a positive Qty. and cannot be deleted. *) MSG_INF_NO_DEL_TOUR: string = ''; (* This Agency has been active and cannot be deleted. *) MSG_INF_LAYAWAY_HAS_HIST: string = ''; (* Layaway has payment history and cannot be deleted. *) MSG_INF_PO_CREATED_VENDOR: string = ''; (* A new PO has been created for vendor: *) MSG_INF_CHOOSE_PAYTYPE: string = ''; (* Choose a payment type. *) MSG_INF_CHOOSE_BANK: string = ''; (* Choose a bank account. *) MSG_INF_INV_CLEANED: string = ''; (* Inventory Qtys. have been reset to zero. *) MSG_INF_DIFER_STORE: string = ''; (* From/To Store cannot be the same. *) MSG_INF_REPRINT_INVOICE: string = ''; (* Invoice can be reprinted in "Cash Register-Invoice History" *) MSG_INF_MODEL_RESTORED: string = ''; (* Model has been Restored._Please, update Inventory qty. *) MSG_INF_ACCOUNT_EXPIRED: string = ''; (* Your account expired._Applications Network - www.mainretail.com *) MSG_INF_DICTIONARI_NOT_FOUND: string = ''; (* Main Retail dictionary file for this module was not found._You can download the dictionary at www.mainretail.com. Main Retail will run on the default language (English).*) MSG_INF_NOT_TRANS_TO_RECONCILE: string = ''; (* There is not transaction to be reconciled._Right-Click on a transaction line and select "Mark for reconciliation". *) MSG_INF_NOT_DEL_SYSREP: string = ''; (* System Report cannot be delete. *) MSG_INF_NOT_EDIT_SYSREP: string = ''; (* System Report cannot be modified._Make a copy of system report. *) MSG_INF_SELECT_VENDOR_FOR_TERM: string = ''; (* You must choose a vendor before import terms. *) MSG_INF_NOT_PAY_DIFFER_ENTITY: string = ''; (* Cannot pay multiple for different Entity._Select documents for the same entity. *) MSG_INF_FREQUENCY_DELETED: string = ''; (* Frequency deleted. *) MSG_INF_SELECT_OPP_TYPE: string = ''; (* Select an operation type. *) MSG_INF_SELECT_SOFTWARE: string = ''; (* Select a software from the list. *) MSG_INF_SELECT_FILE_TYPE: string = ''; (* Select a file type. *) MSG_INF_SELECT_TRANS_TYPE: string = ''; (* Select a transaction type. *) MSG_INF_NO_INFO_TO_IMPORT: string = ''; (* File does not contain information to import. *) MSG_INF_NO_DATA_TO_EXPORT: string = ''; (* There is not data to export. *) MSG_INF_NO_QUICKTIME_AVAILABLE: string = ''; (* There is not quickinfo available. *) MSG_INF_CHANGE_CURRENCY_RECALC: string = ''; (* Do you wish to set this currency as default?_All quotation will be recalculated. *) MSG_INF_LOGIN_EXPIRED: string = ''; (* You expared the chances to log in the System. *) MSG_INF_NOT_VALID_CATEG_TYPE: string = ''; (* Invalid category type._1 - Field must be filled with I - Income or E - Expenses. *) MSG_INF_NOT_DEL_TRANS_SPLITED: string = ''; (* Transaction split cannot be deleted._Delete parent transaction! *) MSG_INF_SELECT_DB: string = ''; (* Select a database. *) MSG_INF_SELECT_FILE: string = ''; (* Select a file name. *) MSG_INF_BACKUP_ZIPPED: string = ''; (* Back up completed and zipped!*) MSG_INF_BACKUP_COMPLETED: string = ''; (* Back up completed!*) MSG_INF_RESTORE_COMPLETED: string = ''; (* Restore completed!*) MSG_INF_TOTAL_VALUE_REACHED: string = ''; (* The total value already was reached! *) //INFORMATION PARITAL MSG_INF_PART1_USE_MR: string = ''; (* You have *) MSG_INF_PART2_USE_MR: string = ''; (* minutes left of use._Applications Network - www.mainretail.com *) MSG_INF_PART_PETTYCASH_MAX: string = ''; (* Total Petty cannot exceed maximun of : *) MSG_INF_PART1_PO_CREATE_MR: string = ''; (* A PO for *) MSG_INF_PART2_PO_CREATE_MR: string = ''; (* was created. *) MSG_INF_PART1_COMMISS_PAIED: string = ''; (* A commission payment of *) MSG_INF_PART2_COMMISS_PAIED: string = ''; (* has been sucessuful registered. *) MSG_INF_PART_ITEM_SOLD_FOR: string = ''; (* This Item was sold for *) MSG_INF_PART_NEW_HOLD_NUMBER: string = ''; (* The new Hold number is *) MSG_INF_PART_NO_DUPLICATED: string = ''; (* cannot be duplicated. *) MSG_INF_PART_FILTER_APPENDED: string = ''; (* Filter(s) appended._ *) MSG_INF_PART1_RECONCILED_OK: string = ''; (* Congratulations!_Your account is balanced. *) MSG_INF_PART2_RECONCILED_OK: string = ''; (* The items you have marked have been reconciled in your system. *) MSG_INF_PART_ROWS_IMPORTED: string = ''; (* row(s) imported. *) MSG_INF_PART_FILE_CREATED_AT: string = ''; (* File successful created._Path : *) MSG_INF_PART1_INVALID_FILE_NAME:string = ''; (* Invalid filename._1 - Filename cannot be empty *) MSG_INF_PART2_INVALID_FILE_NAME:string = ''; (* 2 - File extension must filled. *) MSG_INF_PART1_SELECT_GL: string = ''; (* Select a General Ledger - Chart of Account._ *) MSG_INF_PART2_SELECT_GL: string = ''; (* All entities on the list will be associated with the selected G/L on Peach Tree *) //END INFORMATION ############################################################ //QUESTION MSG_QST_UNSAVE_CHANGES: string = ''; (* Cancel changes ? *) MSG_QST_SAVE_UNSAVE_CHANGES: string = ''; (* Save changes ? *) MSG_QST_PRICE_BELLOW: string = ''; (* Price entered is lower than cost price. Do you wish to continue ? *) MSG_QST_AMOUN_NOT_REACH_MIN: string = ''; (* Invoice total below minimum for this deposit date. Do you wish to continue ? *) MSG_QST_QTYARV_BIGGER_QTYORDED: string = ''; (* Qty received is greater than Qty ordered. Do you wish to continue ? *) MSG_QST_COSTARV_BIGGER_CSTORDED:string = ''; (* Cost received is higher than Cost ordered. Do you wish to continue ? *) MSG_QST_COSTARV_DIFFER_CSTORDED:string = ''; (* Cost received is higher than last cost. Do you wish to continue ? *) MSG_QST_ONE_OPEN_MANAGER_CONTUE:string = ''; (* Cash Register has been opened by another user. Do you wish to continue? *) MSG_QST_DELETE_MODEL_FROM_QUOT: string = ''; (* Delete Model from this quote ? *) MSG_QST_DELETE_VENDOR_FROM_QUOT:string = ''; (* Delete Vendor from this quote ? *) MSG_QST_DELETE_REQUEST: string = ''; (* Delete Request ? *) MSG_QST_NEW_COST_IN_INVENTORY: string = ''; (* Insert new "COST" into Inventory ? *) MSG_QST_DISCOUNT_REACHED: string = ''; (* Deleting this item will reset discount ranges. Do you wish to continue ? *) MSG_QST_DISCOUNT_WAS_REACHED: string = ''; (* Discount limit has been reached. Do you wish to continue ? *) MSG_QST_ERASE_ALL_DISCOUNT: string = ''; (* Deleting this item will remove existing discounts. Do you wish to continue ? *) MSG_QST_ERASE_ALL_DISCOUNT_ADD: string = ''; (* Adding a new item will remove existing discounts. Do you wish to continue ? *) MSG_QST_ERASE_ALL_DISCOUNT_MOD: string = ''; (* Modifying this item will remove existing discounts. Do you wish to continue ? *) MSG_QTS_REBUILD_IDT: string = ''; (* Confirm Rebuild Identity ?_Rebuild Identity will check and fix errors in your Database. *) MSG_QST_DELETE: string = ''; (* Delete ? *) MSQ_QST_RETORE: string = ''; (* Restore ? *) MSG_QST_DELETE_PERMANENT: string = ''; (* Confirm permanent deletion? *) MSG_QST_CONFIRM: string = ''; (* Confirm Operation ? *) MSG_QST_CONFIRM_RESTORE: string = ''; (* Confirm restore for this payment ? *) MSG_QST_CONFIRM_PETTY_CASH: string = ''; (* Confirm Petty Cash ? *) MSG_QST_CONFIRM_REPRINT: string = ''; (* Confirm Reprint ? *) MSG_QST_CONFIRM_UNLOCK_PRESALE: string = ''; (* Confirm UnLock Hold ? *) MSG_QST_CONFIRM_DEPOSIT_CASHREG:string = ''; (* Confirm Deposit Cash Register ? *) MSG_QST_CONFIRM_CHANGE_LOCAL: string = ''; (* Confirm changes to Local Parameters ? *) MSG_QST_CONFIRM_PAYMENT: string = ''; (* Confirm Payment ? *) MSG_QST_CONFIRM_HOLD: string = ''; (* Confirm new Hold ? *) MSG_QST_CONFIRM_PURCHASE: string = ''; (* Confirm new Purchase ? *) MSG_QST_CONFIRM_RECEVE_PURCHASE:string = ''; (* Confirm receiving this Purchase ? *) MSG_QST_CONFIRM_RECEVE_LAYAWAY: string = ''; (* Confirm receiving this Layaway ? *) MSG_QST_CONFIRM_RECEVE_HOLD: string = ''; (* Confirm receiving this Hold ? *) MSG_QST_CONFIRM_TAX_ISENTION: string = ''; (* Confirm Tax exemption ? *) MSG_QST_CONFIRM_ADJUST_INV: string = ''; (* Confirm Adjustment in Inventory ? *) MSG_QST_DELETE_MODEL: string = ''; (* Confirm deletion for this model ? *) MSG_QST_DELETE_SERIALNUMBER: string = ''; (* Confirm deletion for this Serial Number ? *) MSG_QST_DELETE_COST: string = ''; (* Confirm deletion for this cost ? *) MSG_QST_CONFIRM_CLOSE_REGISTER: string = ''; (* Close Cash Register ? *) MSG_QST_PRINT_STATEMENT: string = ''; (* Print statement ? *) MSG_QST_PRINT_STATEMENT_DET: string = ''; (* Print statement detail ? *) MSG_QST_RESTORE_TAX: string = ''; (* Restore Tax ? *) MSG_QST_SURE: string = ''; (* Are you sure ? *) MSG_QST_CLEAN_UP_INVENTORY: string = ''; (* This operation will reset all inventory Qtys. to zero. Are You Sure ? *) MSG_QST_RESTORE_INVENTORY: string = ''; (* This operation will discard your reset records. Are You Sure ? *) MSG_QST_NOT_MODEL_STORE: string = ''; (* Qty transferred is greater than Qty on hand. Continue transfer ? *) MSG_QST_INVOICE_DONOT_HAVE_ITEM:string = ''; (* Invoice does not contain this item. Do you wish to continue ? *) MSG_QST_CASH_IS_IN_USER: string = ''; (* Associated Cash Register already in use. Select another. *) MSG_QST_PAYTYPE_NOT_ALLOW_DATE: string = ''; (* Payment Type does not allow this Deposit Date. Do you wish to continue ? *) MSG_QST_INVOICE_ONLY_CASH: string = ''; (* This Invoice is cash only. Do you wish to continue ? *) MSG_QST_PO_OPEN_SAVE: string = ''; (* These items have already been entered in PO for this vendor. Do you wish to reenter them ? *) MSG_QST_OPEN_CASH_LESS_MONEY: string = ''; (* Confirm opening cash register below *) MSG_QST_CONF_TRANSFER: string = ''; (* Confirm New Transfer ? *) MSG_QST_INV_NEGATIVE: string = ''; (* Negative Inventory. Do you wish to continue ? *) MSG_QST_CLOSE_LAYAWAY: string = ''; (* Close Layaway ? *) MSG_QST_CONTINUE: string = ''; (* Do you wish to continue ? *) MSQ_QST_CHANGE_RECONCILED_TRANS:string = ''; (* You will change a reconciled transaction._The system will recalculate the reconciled total. Continue ? *) MSG_QST_SAVE_REPORT: string = ''; (* Save report changes ? *) MSG_QST_CHANGE_PO_PRICE: string = ''; (* The new Cost Price is different than Inventory. Change Our Price ? *) MSG_QST_DEL_OTHER_DOC_PAYMENT: string = ''; (* The record was paid with another document. Delete payment ?_If yes, all document payments will also be deleted. *) MSG_QST_OVERRIDE_VENDOR_TERMS: string = ''; (* Importing vendor terms again will erase all previews term._Continue? *) MSG_QST_DOC_SPLITED_PAY_ALL: string = ''; (* Document was splited. Add all parts of the document?_If yes, all disbursements of the document will be included to be paid. Otherwise, only a part of the document will be included. *) MSG_QST_EXIT: string = ''; (* Do you want to exit now? *) MSG_QST_CONFIRM_CHANGE_LANG: string = ''; (* Translat default MainRetail values ?_if yes, the system will override the values on the MainRetail fields *) MSG_QST_ADD_ANOTHER_CATEG: string = ''; (* Would you like add another Category?*) MSG_QST_ADD_ANOTHER_MODEL: string = ''; (* Would you like add another Model?*) //QUESTION PARTIAL MSG_QST_PART_CONFIRM: string = ''; (* Confirm *) MSG_QST_PART_CRIATE_REP_COPY: string = ''; (* Criate copy of Report *) MSG_QST_PART_REMOVE_REPORT: string = ''; (* Remove report *) MSG_QST_PART1_CONFIRM_ADJST: string = ''; (* Confirm a adjust of *) MSG_QST_PART2_CONFIRM_ADJST: string = ''; (* on the commission ? *) MSG_QST_PART1_MOVE_INVOICE_ITEM:string = ''; (* You will move the *) MSG_QST_PART2_MOVE_INVOICE_ITEM:string = ''; (* items. Confirm operation? *) MSG_QST_PART1_QUERY_RETURN: string = ''; (* Query will return more than *) MSG_QST_PART2_QUERY_RETURN: string = ''; (* lines, continue? *) MSG_QST_PART1_DELETE_PERMANENT: string = ''; (* Confirm permanent deletion of *) MSG_QST_PART2_DELETE_PERMANENT: string = ''; (* line(s) ? *) MSG_QST_PART1_DELETE_LINES: string = ''; (* Delete *) MSG_QST_PART2_DELETE_LINES: string = ''; (* line(s) ? *) MSQ_QST_PART1_RETORE_LINES: string = ''; (* Restore *) MSQ_QST_PART2_RETORE_LINES: string = ''; (* line(s) ? *) MSQ_QST_PART1_DIFFER_RECONC_BAL:string = ''; (* Different Total! Do you want to Adjust balance now ?_The total of the items you have marked is different than bank statement end balance. *) MSQ_QST_PART2_DIFFER_RECONC_BAL:string = ''; (* You may have Office Manager enter a balance adjust. *) MSQ_QST_PART1_CHECK_USES: string = ''; (* The Check Number " *) MSQ_QST_PART2_CHECK_USES: string = ''; (* " was already used. Continue? *) MSG_QST_PART_ADD_ANOTHER: string = ''; (* Would you like to add another *) //END QUESTION ############################################################ //CRITICAL MSG_CRT_QTY_BIGGER_0: string = ''; (* Enter a quantity greater than Zero *) MSG_CRT_NO_ITEM: string = ''; (* There are no Items! *) MSG_CRT_THERE_IS_NO_VENDOR: string = ''; (* There is no Vendor! *) MSG_CRT_FILE_ERROR: string = ''; (* File Error! *) MSG_CRT_CREATIBG_FILE_ERROR: string = ''; (* Error creating file.! *) MSG_CRT_CREATING_DATA_ERROR: string = ''; (* Error creating data. *) MSG_CRT_INVENTORY_WILL_BE_NEG: string = ''; (* Negative Inventory. To proceed, call Manager! *) MSG_CRT_NO_FAX_NUMBER: string = ''; (* Fax number cannot be empty! *) MSG_CRT_NO_CUSTUMER: string = ''; (* Customer cannot be empty! *) MSG_CRT_NO_DATE: string = ''; (* Date cannot be empty! *) MSG_CRT_NO_SERIALNUMBER: string = ''; (* Serial Number cannot be empty! *) MSG_CRT_NO_AUTHORIZANUMBER: string = ''; (* Authorization # cannot be empty! *) MSG_CRT_NO_ORG_STORE: string = ''; (* Originating Store cannot be empty! *) MSG_CRT_NO_DES_STORE: string = ''; (* Destination Store cannot be empty! *) MSG_CRT_NO_DOCUMENT_CUSTUMER: string = ''; (* Customer documents cannot be empty! *) MSG_CRT_NO_MODEL: string = ''; (* Model cannot be empty! *) MSG_CRT_NO_VENDOR: string = ''; (* Vendor cannot be empty! *) MSG_CRT_NO_FIRST_NAME: string = ''; (* First Name cannot be empty! *) MSG_CRT_NO_LAST_NAME: string = ''; (* Last Name cannot be empty! *) MSG_CRT_NO_RA: string = ''; (* RA cannot be empty! *) MSG_CRT_NO_NUMBER: string = ''; (* Number cannot be empty! *) MSG_CRT_NO_DEL_PAYMENT: string = ''; (* Payment cannot be deleted. *) MSG_CRT_NO_DEL_SYSTEM_PAYMENT: string = ''; (* System payment cannot be deleted. *) MSG_CRT_NO_DEL_RECORD: string = ''; (* Record cannot be deleted. *) MSG_CRT_NO_DEL_RECORD_DETAIL: string = ''; (* Record cannot be deleted._Delete detail first. *) MSG_CRT_NO_PAYMENT_ZERO: string = ''; (* Payment cannot be zero! *) MSG_CRT_NO_PAYMENT_TYPE: string = ''; (* Payment Type cannot be empty! *) MSG_CRT_NO_AMOUNT: string = ''; (* Amount received cannot be empty! *) MSG_CRT_NO_TOTAL_AMOUNT: string = ''; (* Amount cannot be empty! *) MSG_CRT_NO_PARENT: string = ''; (* New Parent cannot be empty! *) MSG_CRT_NO_QTY_EMPTY: string = ''; (* Quantity cannot be empty! *) MSG_CRT_NO_DEL_CATEGORY: string = ''; (* Category cannot be deleted! Category is not empty. *) MSG_CRT_NO_DEL_TRASNFER: string = ''; (* Transfer cannot be deleted! transfer is not empty. *) MSG_CRT_NO_SEND_BY: string = ''; (* "Sent by" cannot be empty *) MSG_CRT_NOT_RETURN_ITEM: string = ''; (* Cannot return an item before sent to vendor! *) MSG_CRT_NO_QTY_ORDER_EMPTY: string = ''; (* Quantity on Order cannot be empty! *) MSG_CRT_NO_QTY_REPAIR_EMPTY: string = ''; (* Quantity on Repair cannot be empty! *) MSG_CRT_NO_QTY_PERPUR_EMPTY: string = ''; (* Quantity on PrePurchase cannot be empty! *) MSG_CRT_NO_DIFFERRENCE_EMPTY: string = ''; (* Adjust. Qty. cannot be empty! *) MSG_CRT_NO_INVOICE_NUM_EMPTY: string = ''; (* Invoice number cannot be empty! *) MSG_CRT_NO_SALESPERSON_EMPTY: string = ''; (* Sales Person cannot be empty! *) MSG_CRT_NO_PP_LICENC_EMPTY: string = ''; (* Passport or TaxID # cannot be empty! *) MSG_CRT_NO_FROM_AGENCY: string = ''; (* "From Agency" cannot be empty! *) MSG_CRT_NO_FROM_GUIDE: string = ''; (* "From Agent" cannot be empty! *) MSG_CRT_NO_TO_AGENCY: string = ''; (* "To Agency" cannot be empty! *) MSG_CRT_NO_TO_GUIDE: string = ''; (* "To Agent" cannot be empty! *) MSG_CRT_NO_DUE_DATE: string = ''; (* Due date cannot be empty! *) MSG_CRT_DUEDATE_SMALER_ISSUE: string = ''; (* Due date cannot be smaller than Issue Date. *) MSG_CRT_NO_CHANGE_DOC_AMOUNT: string = ''; (* Document amount cannot be changed._Please remove payments. *) MSG_CRT_NO_DOC_DISBURSEMENT: string = ''; (* This document must have at least one disbursement. *) MSG_CRT_NO_ACCESS: string = ''; (* Access denied! *) MSG_CRT_NO_MODEL_SELECTED: string = ''; (* Select a model! *) MSG_CRT_NO_MODEL_INFORMTION: string = ''; (* Invalid Module Information. *) MSG_CRT_NO_RECORD_REPORT: string = ''; (* The selection returned 0 item(s)! *) MSG_CRT_NO_REAL_QTY: string = ''; (* "Qty. Counted" cannot be empty! *) MSG_CRT_NO_DEL_FREQUENCY: string = ''; (* One or more frequencies could not be deleted._Only frequency without payments can be deleted. *) MSG_CRT_ERROR_OCURRED: string = ''; (* An error has ocurred ! *) MSG_CRT_NO_HELP: string = ''; (* Help File not found! *) MSG_CRT_NO_FINANCE: string = ''; (* Module "Office Manager" not found! *) MSG_CRT_NO_WEEKDAY: string = ''; (* You must choose a week day! *) MSG_CRT_NO_YEAR: string = ''; (* You must choose a year! *) MSG_CRT_NO_RECORD: string = ''; (* You must choose a record! *) MSG_CRT_NO_RECORD_TO_PRINT: string = ''; (* You must choose a record before print! *) MSG_CRT_NO_SERIAL_NUMBER: string = ''; (* Serial Number(s) cannot be empty._You must enter a serial number for each checked S/N item! *) MSG_CRT_NO_MEDIA: string = ''; (* You must select a Media! *) MSG_CRT_NO_GUIDE: string = ''; (* You must select an Outside Agent! *) MSG_CRT_NO_STORE_SELECTED: string = ''; (* You must select a Store! *) MSG_CRT_NO_COMPANY_SELECTED: string = ''; (* You must select a Company! *) MSG_CRT_NO_AGENCY_SELECTED: string = ''; (* You must select an Agency! *) MSG_CRT_NO_MEDIA_SELECTED: string = ''; (* You must select a Media! *) MSG_CRT_QTY_POSITIVE: string = ''; (* Qty must be positive! *) MSG_CRT_COST_POSITIVE: string = ''; (* Cost must be positive! *) MSG_CRT_NO_VALID_DATE: string = ''; (* Invalid date! *) MSG_CRT_NO_VALID_DAY: string = ''; (* Invalid day! *) MSG_CRT_NO_VALID_FREQUENCY: string = ''; (* Invalid frequency! *) MSG_CRT_NO_VALID_INV_DATE: string = ''; (* Invalid invoice date! *) MSG_CRT_NO_VALID_DUE_DATE: string = ''; (* Invalid due date! *) MSG_CRT_NO_VALID_SELECTION: string = ''; (* Invalid selection! *) MSG_CRT_NO_VALID_AMOUNT: string = ''; (* Invalid payment amount! *) MSG_CRT_NO_VALID_INIDATE: string = ''; (* Invalid start date! *) MSG_CRT_NO_VALID_FIMDATE: string = ''; (* Invalid end date! *) MSG_CRT_NO_VALID_YEAR: string = ''; (* Invalid Year! *) MSG_CRT_NO_VALID_HOLD: string = ''; (* Invalid Hold # *) MSG_CRT_NO_PAY_DATE: string = ''; (* Invalid Payment Date! *) MSG_CRT_NO_BARCODE: string = ''; (* Invalid Barcode! *) MSG_CRT_INVAL_COST_PRICE: string = ''; (* Invalid Cost Price! *) MSG_CRT_INVAL_DATE_RECEIVE: string = ''; (* Invalid "receive date"! *) MSG_CRT_NO_VALID_TRIAL_INFO: string = ''; (* Invalid information about Trial Counter._Applications Network - www.mainretail.com *) MSG_CRT_NO_VALID_WIZARD: string = ''; (* Could not initialize Main Retail Setup Wizard._Check for "Wizard.exe" in your MainRetail directory. *) MSG_CRT_NO_CONNECT_SERVER: string = ''; (* Unabled to connect the server._Check Server connection. *) MSG_CRT_NO_VPN_SERVER: string = ''; (* Unabled to connect the server._Check VPN connection. *) MSG_CRT_NO_PARAM_SERVER: string = ''; (* Unabled to connect the server._Check Server parameters. *) MSG_CRT_NO_FOUND_HOLD: string = ''; (* Hold not found! *) MSG_CRT_HOLD_PAID: string = ''; (* Hold already paid! *) MSG_CRT_NO_POITEM: string = ''; (* There are no items to add in PO! *) MSG_CRT_QUOTE: string = ''; (* Quote does not exist! *) MSG_CRT_NO_SERIALNUMBER_INV: string = ''; (* Serial Number not found *) MSG_CRT_EXIST_SERIALNUMBER: string = ''; (* Serial Number Already exists! *) MSG_CRT_SERIALNUMBER_INV: string = ''; (* Serial Number Error._a)SN already exists, b)Qty on Hand is 0, or c)invalid store *) MSG_CRT_NO_VALID_TIME: string = ''; (* Error! *) MSG_CRT_NO_VALID_EMAIL: string = ''; (* E-mail not found! *) MSG_CRT_NO_DELETE_REPAIR: string = ''; (* Repair cannot be deleted!_This is not the last status *) MSG_CRT_NO_CONECTION: string = ''; (* Connection Error ! *) MSG_CRT_NOT_REMOV_PO: string = ''; (* PO cannot be deleted. *) MSG_CRT_NOT_EMPTY_USER: string = ''; (* User cannot be empty! *) MSG_CRT_NOT_EMPTY_CATEGORY: string = ''; (* Category cannot be empty! *) MSG_CRT_NOT_EMPTY_MANUF: string = ''; (* Manufacturer cannot be empty! *) MSG_CRT_CHOOSE_VENDOR_BEFORE: string = ''; (* You must choose a Vendor before adding Items ! *) MSG_CRT_NOT_DEL_PURCHASE: string = ''; (* This item cannot be deleted! *) MSG_CRT_ERROR_PRINT: string = ''; (* Printer Error! *) MSG_CRT_NO_ITEM_PAY: string = ''; (* Invoice empty, cannot receive! *) MSG_CRT_NO_INVOICE_UNPAY: string = ''; (* Invoice cannot be unpayed! *) MSG_CRT_QTY_NO_ZERO: string = ''; (* Qty cannot be ZERO. *) MSG_CRT_ERROR_ADD_COLOR: string = ''; (* Error adding Color *) MSG_CRT_NO_COLOR: string = ''; (* You must choose a color ! *) MSG_CRT_ERROR_ADD_SIZE: string = ''; (* Error adding Size! *) MSG_CRT_NO_SIZE: string = ''; (* You must choose a size ! *) MSG_CRT_ERROR_VALUE: string = ''; (* Invalid "SvrValue". *) MSG_CRT_ERROR_ADDING: string = ''; (* Error adding record. *) MSG_CRT_ERROR_DELETING: string = ''; (* Error deleting item. *) MSG_CRT_ERROR_SAVING: string = ''; (* Error saving data. Transaction Rollback. *) MSG_CRT_ERROR_BALANCE_CHANGE: string = ''; (* Error changing balance. *) MSG_CRT_ERROR_RECONCILING: string = ''; (* Reconcile Error. *) MSG_CRT_NO_EMPTY_REASON: string = ''; (* Reason can not be empty *) MSG_CRT_NO_AGENT: string = ''; (* There are no Outside Agent! *) MSG_CRT_ERROR_DEPOSIT_ACC: string = ''; (* Invalid Deposit Account information._Please, enter a Bank Account for each Store. *) MSG_CRT_ERROR_PAYMENT_TYPE: string = ''; (* Invalid Payment Type information._Please, enter Bank Account for each Payment Type. *) MSG_CRT_ERROR_TAX_CATEG: string = ''; (* Invalid Tax information._Please, enter tax for each category. *) MSG_CRT_ERROR_TAX_STORE: string = ''; (* Invalid Tax information._Please, enter tax for each store. *) MSG_CRT_ERROR_STACK_SIZE: string = ''; (* You enter an invalid Stack Size *) MSG_CRT_ERROR_DEL_PURCHASE: string = ''; (* Select purchase was payed. Only unpaid purchases can be deleted._If you want to delete this purchase, first delete the payments in Office Manager. *) MSG_CRT_ERROR_PRINTING: string = ''; (* Printer Error! Do you wish to try again?_Make sure the printer is ON and click on YES to try again. *) MSG_CRT_ERROR_PW_NOT_MATCH: string = ''; (* The new password does not match with the old password! *) MSG_CRT_ERROR_PW_NOT_CONFIRM: string = ''; (* Confirm password does not match with password. *) MSG_CRT_NO_DUPLICATE_PASSWORD: string = ''; (* Password cannot be duplicated. *) MSG_CRT_NO_EMPTY_STORE_NAME: string = ''; (* Store Name cannot be empty. *) MSG_CRT_NO_EMPTY_TAX_DESC: string = ''; (* Tax Description cannot be empty.*) MSG_CRT_NO_EMPTY_TAX_VALUE: string = ''; (* Tax Value cannot be empty.*) MSG_CRT_NO_EMPTY_CASH_REG: string = ''; (* Cash Register Name cannot be empty.*) MSG_CRT_NO_EMPTY_OPEN_CASH: string = ''; (* Opening cash drawer amount cannot be empty.*) MSG_CRT_NO_DUPLICATE_CATEGORY: string = ''; (* Category cannot be duplicated.*) MSG_CRT_NO_EMPTY_COST: string = ''; (* Cost Price cannot be empty.*) MSG_CRT_NO_EMPTY_SELLING: string = ''; (* Selling Price cannot be empty. *) MSG_CRT_NO_DUPLICATE_MODEL: string = ''; (* Model cannot be duplicated.*) MSG_CRT_INVALID_FILE: string = ''; (* Invalid file! *) MSG_CRT_ERROR_BACKUP: string = ''; (* Back up Error! *) MSG_CRT_ERROR_ZIPPING_BACKUP: string = ''; (* Zipping Back up file Error! *) MSG_CRT_ERROR_RESTORE: string = ''; (* Restore Error! *) MSG_CRT_ERROR_INVALID_KEY: string = ''; (* Invalid Key*) MSG_CRT_MUST_SAVE: string = ''; (* You must save the data *) MSG_CRT_AMOUNT_CANNOT_ZERO: string = ''; (* Amount cannot be zero. *) MSG_CRT_SA_PAYMENT: string = ''; (* Store Account Payment should be received in MainRetail. *) //CRITICAL PARTIAL MSG_CRT_PART_ERROR_SAVE_REPORT: string = ''; (* Error saving report *) MSG_CRT_PART_ERROR_SAVE_REPFILE:string = ''; (* Error saving report file *) MSG_CRT_PART_FIELDS_NO_EMPTY: string = ''; (* _In this form, the field(s) can not be empty : *) MSG_CRT_PART_CLASS_NOT_DEFINED: string = ''; (* FormClass not defined._OnCreateFch. *) MSG_CRT_PART1_ERROR_DEL_PAYMENT:string = ''; (* Payment cannot be deleted. It has *) MSG_CRT_PART2_ERROR_DEL_PAYMENT:string = ''; (* record(s). *) MSG_CRT_PART1_ERROR_DEL_RECORD: string = ''; (* Record cannot be deleted._It has *) MSG_CRT_PART2_ERROR_DEL_RECORD: string = ''; (* payment(s) registered. *) MSG_CRT_PART3_ERROR_DEL_RECORD: string = ''; (* Delete the payment(s) first. *) MSG_CRT_PART_INSERT_REC_NUM: string = ''; (* Error including record number *) MSG_CRT_PART1_NO_FILE_HEADER: string = ''; (* Invalid file header!_ *) MSG_CRT_PART2_NO_FILE_HEADER: string = ''; (* Please verify if the file you are trying to import has header or a valid header. *) MSG_CRT_AMOUNT_NOT_LESS_THAN: string = ''; (* Amount cannot be less then than *) MSG_CRT_AMOUNT_NOT_GREATER_THAN:string = ''; (* Amount cannot be greater then than *) //END CRITICAL ############################################################ type TFrmMsgConstant = class(TForm) siLang: TsiLangRT; procedure FormCreate(Sender: TObject); procedure siLangChangeLanguage(Sender: TObject); procedure UpdateStrings; private { Private declarations } public { Public declarations } end; var FrmMsgConstant : TFrmMsgConstant; implementation uses uDMGlobal; {$R *.DFM} procedure TFrmMsgConstant.FormCreate(Sender: TObject); begin UpdateStrings; end; procedure TFrmMsgConstant.siLangChangeLanguage(Sender: TObject); begin UpdateStrings; end; procedure TFrmMsgConstant.UpdateStrings; begin MSG_CRT_SA_PAYMENT := siLang.GetText('strMSG_CRT_SA_PAYMENT'); MSG_CRT_AMOUNT_CANNOT_ZERO := siLang.GetText('strMSG_CRT_AMOUNT_CANNOT_ZERO'); MSG_CRT_AMOUNT_NOT_LESS_THAN := siLang.GetText('strMSG_CRT_AMOUNT_NOT_LESS_THAN'); MSG_CRT_AMOUNT_NOT_GREATER_THAN := siLang.GetText('strMSG_CRT_AMOUNT_NOT_GREATER_THAN'); MSG_CRT_PART2_NO_FILE_HEADER := siLang.GetText('strMSG_CRT_PART2_NO_FILE_HEADER'); MSG_CRT_PART1_NO_FILE_HEADER := siLang.GetText('strMSG_CRT_PART1_NO_FILE_HEADER'); MSG_CRT_PART_INSERT_REC_NUM := siLang.GetText('strMSG_CRT_PART_INSERT_REC_NUM'); MSG_CRT_PART3_ERROR_DEL_RECORD := siLang.GetText('strMSG_CRT_PART3_ERROR_DEL_RECORD'); MSG_CRT_PART2_ERROR_DEL_RECORD := siLang.GetText('strMSG_CRT_PART2_ERROR_DEL_RECORD'); MSG_CRT_PART1_ERROR_DEL_RECORD := siLang.GetText('strMSG_CRT_PART1_ERROR_DEL_RECORD'); MSG_CRT_PART2_ERROR_DEL_PAYMENT := siLang.GetText('strMSG_CRT_PART2_ERROR_DEL_PAYMENT'); MSG_CRT_PART1_ERROR_DEL_PAYMENT := siLang.GetText('strMSG_CRT_PART1_ERROR_DEL_PAYMENT'); MSG_CRT_PART_CLASS_NOT_DEFINED := siLang.GetText('strMSG_CRT_PART_CLASS_NOT_DEFINED'); MSG_CRT_PART_FIELDS_NO_EMPTY := siLang.GetText('strMSG_CRT_PART_FIELDS_NO_EMPTY'); MSG_CRT_PART_ERROR_SAVE_REPFILE := siLang.GetText('strMSG_CRT_PART_ERROR_SAVE_REPFILE'); MSG_CRT_PART_ERROR_SAVE_REPORT := siLang.GetText('strMSG_CRT_PART_ERROR_SAVE_REPORT'); MSG_CRT_ERROR_PW_NOT_CONFIRM := siLang.GetText('strMSG_CRT_ERROR_PW_NOT_CONFIRM'); MSG_CRT_NO_DUPLICATE_PASSWORD := siLang.GetText('strMSG_CRT_NO_DUPLICATE_PASSWORD'); MSG_CRT_NO_EMPTY_STORE_NAME := siLang.GetText('strMSG_CRT_NO_EMPTY_STORE_NAME'); MSG_CRT_NO_EMPTY_TAX_DESC := siLang.GetText('strMSG_CRT_NO_EMPTY_TAX_DESC'); MSG_CRT_NO_EMPTY_TAX_VALUE := siLang.GetText('strMSG_CRT_NO_EMPTY_TAX_VALUE'); MSG_CRT_NO_EMPTY_CASH_REG := siLang.GetText('strMSG_CRT_NO_EMPTY_CASH_REG'); MSG_CRT_NO_EMPTY_OPEN_CASH := siLang.GetText('strMSG_CRT_NO_EMPTY_OPEN_CASH'); MSG_CRT_NO_DUPLICATE_CATEGORY := siLang.GetText('strMSG_CRT_NO_DUPLICATE_CATEGORY'); MSG_CRT_NO_EMPTY_COST := siLang.GetText('strMSG_CRT_NO_EMPTY_COST'); MSG_CRT_NO_EMPTY_SELLING := siLang.GetText('strMSG_CRT_NO_EMPTY_SELLING'); MSG_CRT_NO_DUPLICATE_MODEL := siLang.GetText('strMSG_CRT_NO_DUPLICATE_MODEL'); MSG_CRT_INVALID_FILE := siLang.GetText('strMSG_CRT_INVALID_FILE'); MSG_CRT_ERROR_BACKUP := siLang.GetText('strMSG_CRT_ERROR_BACKUP'); MSG_CRT_ERROR_ZIPPING_BACKUP := siLang.GetText('strMSG_CRT_ERROR_ZIPPING_BACKUP'); MSG_CRT_ERROR_RESTORE := siLang.GetText('strMSG_CRT_ERROR_RESTORE'); MSG_CRT_ERROR_INVALID_KEY := siLang.GetText('strMSG_CRT_ERROR_INVALID_KEY'); MSG_CRT_MUST_SAVE := siLang.GetText('strMSG_CRT_MUST_SAVE'); MSG_CRT_ERROR_PW_NOT_MATCH := siLang.GetText('strMSG_CRT_ERROR_PW_NOT_MATCH'); MSG_CRT_ERROR_PRINTING := siLang.GetText('strMSG_CRT_ERROR_PRINTING'); MSG_CRT_ERROR_DEL_PURCHASE := siLang.GetText('strMSG_CRT_ERROR_DEL_PURCHASE'); MSG_CRT_ERROR_STACK_SIZE := siLang.GetText('strMSG_CRT_ERROR_STACK_SIZE'); MSG_CRT_ERROR_TAX_STORE := siLang.GetText('strMSG_CRT_ERROR_TAX_STORE'); MSG_CRT_ERROR_TAX_CATEG := siLang.GetText('strMSG_CRT_ERROR_TAX_CATEG'); MSG_CRT_ERROR_PAYMENT_TYPE := siLang.GetText('strMSG_CRT_ERROR_PAYMENT_TYPE'); MSG_CRT_ERROR_DEPOSIT_ACC := siLang.GetText('strMSG_CRT_ERROR_DEPOSIT_ACC'); MSG_CRT_NO_AGENT := siLang.GetText('strMSG_CRT_NO_AGENT'); MSG_CRT_NO_EMPTY_REASON := siLang.GetText('strMSG_CRT_NO_EMPTY_REASON'); MSG_CRT_ERROR_RECONCILING := siLang.GetText('strMSG_CRT_ERROR_RECONCILING'); MSG_CRT_ERROR_BALANCE_CHANGE := siLang.GetText('strMSG_CRT_ERROR_BALANCE_CHANGE'); MSG_CRT_ERROR_SAVING := siLang.GetText('strMSG_CRT_ERROR_SAVING'); MSG_CRT_ERROR_DELETING := siLang.GetText('strMSG_CRT_ERROR_DELETING'); MSG_CRT_ERROR_ADDING := siLang.GetText('strMSG_CRT_ERROR_ADDING'); MSG_CRT_ERROR_VALUE := siLang.GetText('strMSG_CRT_ERROR_VALUE'); MSG_CRT_NO_SIZE := siLang.GetText('strMSG_CRT_NO_SIZE'); MSG_CRT_ERROR_ADD_SIZE := siLang.GetText('strMSG_CRT_ERROR_ADD_SIZE'); MSG_CRT_NO_COLOR := siLang.GetText('strMSG_CRT_NO_COLOR'); MSG_CRT_ERROR_ADD_COLOR := siLang.GetText('strMSG_CRT_ERROR_ADD_COLOR'); MSG_CRT_QTY_NO_ZERO := siLang.GetText('strMSG_CRT_QTY_NO_ZERO'); MSG_CRT_NO_INVOICE_UNPAY := siLang.GetText('strMSG_CRT_NO_INVOICE_UNPAY'); MSG_CRT_NO_ITEM_PAY := siLang.GetText('strMSG_CRT_NO_ITEM_PAY'); MSG_CRT_ERROR_PRINT := siLang.GetText('strMSG_CRT_ERROR_PRINT'); MSG_CRT_NOT_DEL_PURCHASE := siLang.GetText('strMSG_CRT_NOT_DEL_PURCHASE'); MSG_CRT_CHOOSE_VENDOR_BEFORE := siLang.GetText('strMSG_CRT_CHOOSE_VENDOR_BEFORE'); MSG_CRT_NOT_EMPTY_MANUF := siLang.GetText('strMSG_CRT_NOT_EMPTY_MANUF'); MSG_CRT_NOT_EMPTY_CATEGORY := siLang.GetText('strMSG_CRT_NOT_EMPTY_CATEGORY'); MSG_CRT_NOT_EMPTY_USER := siLang.GetText('strMSG_CRT_NOT_EMPTY_USER'); MSG_CRT_NOT_REMOV_PO := siLang.GetText('strMSG_CRT_NOT_REMOV_PO'); MSG_CRT_NO_CONECTION := siLang.GetText('strMSG_CRT_NO_CONECTION'); MSG_CRT_NO_DELETE_REPAIR := siLang.GetText('strMSG_CRT_NO_DELETE_REPAIR'); MSG_CRT_NO_VALID_EMAIL := siLang.GetText('strMSG_CRT_NO_VALID_EMAIL'); MSG_CRT_NO_VALID_TIME := siLang.GetText('strMSG_CRT_NO_VALID_TIME'); MSG_CRT_SERIALNUMBER_INV := siLang.GetText('strMSG_CRT_SERIALNUMBER_INV'); MSG_CRT_EXIST_SERIALNUMBER := siLang.GetText('strMSG_CRT_EXIST_SERIALNUMBER'); MSG_CRT_NO_SERIALNUMBER_INV := siLang.GetText('strMSG_CRT_NO_SERIALNUMBER_INV'); MSG_CRT_QUOTE := siLang.GetText('strMSG_CRT_QUOTE'); MSG_CRT_NO_POITEM := siLang.GetText('strMSG_CRT_NO_POITEM'); MSG_CRT_HOLD_PAID := siLang.GetText('strMSG_CRT_HOLD_PAID'); MSG_CRT_NO_FOUND_HOLD := siLang.GetText('strMSG_CRT_NO_FOUND_HOLD'); MSG_CRT_NO_PARAM_SERVER := siLang.GetText('strMSG_CRT_NO_PARAM_SERVER'); MSG_CRT_NO_VPN_SERVER := siLang.GetText('strMSG_CRT_NO_VPN_SERVER'); MSG_CRT_NO_CONNECT_SERVER := siLang.GetText('strMSG_CRT_NO_CONNECT_SERVER'); MSG_CRT_NO_VALID_WIZARD := siLang.GetText('strMSG_CRT_NO_VALID_WIZARD'); MSG_CRT_NO_VALID_TRIAL_INFO := siLang.GetText('strMSG_CRT_NO_VALID_TRIAL_INFO'); MSG_CRT_INVAL_DATE_RECEIVE := siLang.GetText('strMSG_CRT_INVAL_DATE_RECEIVE'); MSG_CRT_INVAL_COST_PRICE := siLang.GetText('strMSG_CRT_INVAL_COST_PRICE'); MSG_CRT_NO_BARCODE := siLang.GetText('strMSG_CRT_NO_BARCODE'); MSG_CRT_NO_PAY_DATE := siLang.GetText('strMSG_CRT_NO_PAY_DATE'); MSG_CRT_NO_VALID_HOLD := siLang.GetText('strMSG_CRT_NO_VALID_HOLD'); MSG_CRT_NO_VALID_YEAR := siLang.GetText('strMSG_CRT_NO_VALID_YEAR'); MSG_CRT_NO_VALID_FIMDATE := siLang.GetText('strMSG_CRT_NO_VALID_FIMDATE'); MSG_CRT_NO_VALID_INIDATE := siLang.GetText('strMSG_CRT_NO_VALID_INIDATE'); MSG_CRT_NO_VALID_AMOUNT := siLang.GetText('strMSG_CRT_NO_VALID_AMOUNT'); MSG_CRT_NO_VALID_SELECTION := siLang.GetText('strMSG_CRT_NO_VALID_SELECTION'); MSG_CRT_NO_VALID_DUE_DATE := siLang.GetText('strMSG_CRT_NO_VALID_DUE_DATE'); MSG_CRT_NO_VALID_INV_DATE := siLang.GetText('strMSG_CRT_NO_VALID_INV_DATE'); MSG_CRT_NO_VALID_FREQUENCY := siLang.GetText('strMSG_CRT_NO_VALID_FREQUENCY'); MSG_CRT_NO_VALID_DAY := siLang.GetText('strMSG_CRT_NO_VALID_DAY'); MSG_CRT_NO_VALID_DATE := siLang.GetText('strMSG_CRT_NO_VALID_DATE'); MSG_CRT_COST_POSITIVE := siLang.GetText('strMSG_CRT_COST_POSITIVE'); MSG_CRT_QTY_POSITIVE := siLang.GetText('strMSG_CRT_QTY_POSITIVE'); MSG_CRT_NO_MEDIA_SELECTED := siLang.GetText('strMSG_CRT_NO_MEDIA_SELECTED'); MSG_CRT_NO_AGENCY_SELECTED := siLang.GetText('strMSG_CRT_NO_AGENCY_SELECTED'); MSG_CRT_NO_STORE_SELECTED := siLang.GetText('strMSG_CRT_NO_STORE_SELECTED'); MSG_CRT_NO_COMPANY_SELECTED := siLang.GetText('strMSG_CRT_NO_COMPANY_SELECTED'); MSG_CRT_NO_GUIDE := siLang.GetText('strMSG_CRT_NO_GUIDE'); MSG_CRT_NO_MEDIA := siLang.GetText('strMSG_CRT_NO_MEDIA'); MSG_CRT_NO_SERIAL_NUMBER := siLang.GetText('strMSG_CRT_NO_SERIAL_NUMBER'); MSG_CRT_NO_RECORD_TO_PRINT := siLang.GetText('strMSG_CRT_NO_RECORD_TO_PRINT'); MSG_CRT_NO_RECORD := siLang.GetText('strMSG_CRT_NO_RECORD'); MSG_CRT_NO_YEAR := siLang.GetText('strMSG_CRT_NO_YEAR'); MSG_CRT_NO_WEEKDAY := siLang.GetText('strMSG_CRT_NO_WEEKDAY'); MSG_CRT_NO_FINANCE := siLang.GetText('strMSG_CRT_NO_FINANCE'); MSG_CRT_NO_HELP := siLang.GetText('strMSG_CRT_NO_HELP'); MSG_CRT_ERROR_OCURRED := siLang.GetText('strMSG_CRT_ERROR_OCURRED'); MSG_CRT_NO_DEL_FREQUENCY := siLang.GetText('strMSG_CRT_NO_DEL_FREQUENCY'); MSG_CRT_NO_REAL_QTY := siLang.GetText('strMSG_CRT_NO_REAL_QTY'); MSG_CRT_NO_RECORD_REPORT := siLang.GetText('strMSG_CRT_NO_RECORD_REPORT'); MSG_CRT_NO_MODEL_INFORMTION := siLang.GetText('strMSG_CRT_NO_MODEL_INFORMTION'); MSG_CRT_NO_MODEL_SELECTED := siLang.GetText('strMSG_CRT_NO_MODEL_SELECTED'); MSG_CRT_NO_ACCESS := siLang.GetText('strMSG_CRT_NO_ACCESS'); MSG_CRT_NO_DOC_DISBURSEMENT := siLang.GetText('strMSG_CRT_NO_DOC_DISBURSEMENT'); MSG_CRT_NO_CHANGE_DOC_AMOUNT := siLang.GetText('strMSG_CRT_NO_CHANGE_DOC_AMOUNT'); MSG_CRT_DUEDATE_SMALER_ISSUE := siLang.GetText('strMSG_CRT_DUEDATE_SMALER_ISSUE'); MSG_CRT_NO_DUE_DATE := siLang.GetText('strMSG_CRT_NO_DUE_DATE'); MSG_CRT_NO_TO_GUIDE := siLang.GetText('strMSG_CRT_NO_TO_GUIDE'); MSG_CRT_NO_TO_AGENCY := siLang.GetText('strMSG_CRT_NO_TO_AGENCY'); MSG_CRT_NO_FROM_GUIDE := siLang.GetText('strMSG_CRT_NO_FROM_GUIDE'); MSG_CRT_NO_FROM_AGENCY := siLang.GetText('strMSG_CRT_NO_FROM_AGENCY'); MSG_CRT_NO_PP_LICENC_EMPTY := siLang.GetText('strMSG_CRT_NO_PP_LICENC_EMPTY'); MSG_CRT_NO_SALESPERSON_EMPTY := siLang.GetText('strMSG_CRT_NO_SALESPERSON_EMPTY'); MSG_CRT_NO_INVOICE_NUM_EMPTY := siLang.GetText('strMSG_CRT_NO_INVOICE_NUM_EMPTY'); MSG_CRT_NO_DIFFERRENCE_EMPTY := siLang.GetText('strMSG_CRT_NO_DIFFERRENCE_EMPTY'); MSG_CRT_NO_QTY_PERPUR_EMPTY := siLang.GetText('strMSG_CRT_NO_QTY_PERPUR_EMPTY'); MSG_CRT_NO_QTY_REPAIR_EMPTY := siLang.GetText('strMSG_CRT_NO_QTY_REPAIR_EMPTY'); MSG_CRT_NO_QTY_ORDER_EMPTY := siLang.GetText('strMSG_CRT_NO_QTY_ORDER_EMPTY'); MSG_CRT_NOT_RETURN_ITEM := siLang.GetText('strMSG_CRT_NOT_RETURN_ITEM'); MSG_CRT_NO_SEND_BY := siLang.GetText('strMSG_CRT_NO_SEND_BY'); MSG_CRT_NO_DEL_TRASNFER := siLang.GetText('strMSG_CRT_NO_DEL_TRASNFER'); MSG_CRT_NO_DEL_CATEGORY := siLang.GetText('strMSG_CRT_NO_DEL_CATEGORY'); MSG_CRT_NO_QTY_EMPTY := siLang.GetText('strMSG_CRT_NO_QTY_EMPTY'); MSG_CRT_NO_PARENT := siLang.GetText('strMSG_CRT_NO_PARENT'); MSG_CRT_NO_TOTAL_AMOUNT := siLang.GetText('strMSG_CRT_NO_TOTAL_AMOUNT'); MSG_CRT_NO_AMOUNT := siLang.GetText('strMSG_CRT_NO_AMOUNT'); MSG_CRT_NO_PAYMENT_TYPE := siLang.GetText('strMSG_CRT_NO_PAYMENT_TYPE'); MSG_CRT_NO_PAYMENT_ZERO := siLang.GetText('strMSG_CRT_NO_PAYMENT_ZERO'); MSG_CRT_NO_DEL_RECORD_DETAIL := siLang.GetText('strMSG_CRT_NO_DEL_RECORD_DETAIL'); MSG_CRT_NO_DEL_RECORD := siLang.GetText('strMSG_CRT_NO_DEL_RECORD'); MSG_CRT_NO_DEL_PAYMENT := siLang.GetText('strMSG_CRT_NO_DEL_PAYMENT'); MSG_CRT_NO_DEL_SYSTEM_PAYMENT := siLang.GetText('strMSG_CRT_NO_DEL_SYSTEM_PAYMENT'); MSG_CRT_NO_NUMBER := siLang.GetText('strMSG_CRT_NO_NUMBER'); MSG_CRT_NO_RA := siLang.GetText('strMSG_CRT_NO_RA'); MSG_CRT_NO_LAST_NAME := siLang.GetText('strMSG_CRT_NO_LAST_NAME'); MSG_CRT_NO_FIRST_NAME := siLang.GetText('strMSG_CRT_NO_FIRST_NAME'); MSG_CRT_NO_VENDOR := siLang.GetText('strMSG_CRT_NO_VENDOR'); MSG_CRT_NO_MODEL := siLang.GetText('strMSG_CRT_NO_MODEL'); MSG_CRT_NO_DOCUMENT_CUSTUMER := siLang.GetText('strMSG_CRT_NO_DOCUMENT_CUSTUMER'); MSG_CRT_NO_DES_STORE := siLang.GetText('strMSG_CRT_NO_DES_STORE'); MSG_CRT_NO_ORG_STORE := siLang.GetText('strMSG_CRT_NO_ORG_STORE'); MSG_CRT_NO_AUTHORIZANUMBER := siLang.GetText('strMSG_CRT_NO_AUTHORIZANUMBER'); MSG_CRT_NO_SERIALNUMBER := siLang.GetText('strMSG_CRT_NO_SERIALNUMBER'); MSG_CRT_NO_DATE := siLang.GetText('strMSG_CRT_NO_DATE'); MSG_CRT_NO_CUSTUMER := siLang.GetText('strMSG_CRT_NO_CUSTUMER'); MSG_CRT_NO_FAX_NUMBER := siLang.GetText('strMSG_CRT_NO_FAX_NUMBER'); MSG_CRT_INVENTORY_WILL_BE_NEG := siLang.GetText('strMSG_CRT_INVENTORY_WILL_BE_NEG'); MSG_CRT_CREATING_DATA_ERROR := siLang.GetText('strMSG_CRT_CREATING_DATA_ERROR'); MSG_CRT_CREATIBG_FILE_ERROR := siLang.GetText('strMSG_CRT_CREATIBG_FILE_ERROR'); MSG_CRT_FILE_ERROR := siLang.GetText('strMSG_CRT_FILE_ERROR'); MSG_CRT_THERE_IS_NO_VENDOR := siLang.GetText('strMSG_CRT_THERE_IS_NO_VENDOR'); MSG_CRT_NO_ITEM := siLang.GetText('strMSG_CRT_NO_ITEM'); MSG_CRT_QTY_BIGGER_0 := siLang.GetText('strMSG_CRT_QTY_BIGGER_0'); MSQ_QST_PART2_CHECK_USES := siLang.GetText('strMSQ_QST_PART2_CHECK_USES'); MSG_QST_PART_ADD_ANOTHER := siLang.GetText('strMSG_QST_PART_ADD_ANOTHER'); MSQ_QST_PART1_CHECK_USES := siLang.GetText('strMSQ_QST_PART1_CHECK_USES'); MSQ_QST_PART2_DIFFER_RECONC_BAL := siLang.GetText('strMSQ_QST_PART2_DIFFER_RECONC_BAL'); MSQ_QST_PART1_DIFFER_RECONC_BAL := siLang.GetText('strMSQ_QST_PART1_DIFFER_RECONC_BAL'); MSQ_QST_PART2_RETORE_LINES := siLang.GetText('strMSQ_QST_PART2_RETORE_LINES'); MSQ_QST_PART1_RETORE_LINES := siLang.GetText('strMSQ_QST_PART1_RETORE_LINES'); MSG_QST_PART2_DELETE_LINES := siLang.GetText('strMSG_QST_PART2_DELETE_LINES'); MSG_QST_PART1_DELETE_LINES := siLang.GetText('strMSG_QST_PART1_DELETE_LINES'); MSG_QST_PART2_DELETE_PERMANENT := siLang.GetText('strMSG_QST_PART2_DELETE_PERMANENT'); MSG_QST_PART1_DELETE_PERMANENT := siLang.GetText('strMSG_QST_PART1_DELETE_PERMANENT'); MSG_QST_PART2_QUERY_RETURN := siLang.GetText('strMSG_QST_PART2_QUERY_RETURN'); MSG_QST_PART1_QUERY_RETURN := siLang.GetText('strMSG_QST_PART1_QUERY_RETURN'); MSG_QST_PART2_MOVE_INVOICE_ITEM := siLang.GetText('strMSG_QST_PART2_MOVE_INVOICE_ITEM'); MSG_QST_PART1_MOVE_INVOICE_ITEM := siLang.GetText('strMSG_QST_PART1_MOVE_INVOICE_ITEM'); MSG_QST_PART2_CONFIRM_ADJST := siLang.GetText('strMSG_QST_PART2_CONFIRM_ADJST'); MSG_QST_PART1_CONFIRM_ADJST := siLang.GetText('strMSG_QST_PART1_CONFIRM_ADJST'); MSG_QST_PART_REMOVE_REPORT := siLang.GetText('strMSG_QST_PART_REMOVE_REPORT'); MSG_QST_PART_CRIATE_REP_COPY := siLang.GetText('strMSG_QST_PART_CRIATE_REP_COPY'); MSG_QST_PART_CONFIRM := siLang.GetText('strMSG_QST_PART_CONFIRM'); MSG_QST_EXIT := siLang.GetText('strMSG_QST_EXIT'); MSG_QST_CONFIRM_CHANGE_LANG := siLang.GetText('strMSG_QST_CONFIRM_CHANGE_LANG'); MSG_QST_ADD_ANOTHER_CATEG := siLang.GetText('strMSG_QST_ADD_ANOTHER_CATEG'); MSG_QST_ADD_ANOTHER_MODEL := siLang.GetText('strMSG_QST_ADD_ANOTHER_MODEL'); MSG_QST_DOC_SPLITED_PAY_ALL := siLang.GetText('strMSG_QST_DOC_SPLITED_PAY_ALL'); MSG_QST_OVERRIDE_VENDOR_TERMS := siLang.GetText('strMSG_QST_OVERRIDE_VENDOR_TERMS'); MSG_QST_DEL_OTHER_DOC_PAYMENT := siLang.GetText('strMSG_QST_DEL_OTHER_DOC_PAYMENT'); MSG_QST_CHANGE_PO_PRICE := siLang.GetText('strMSG_QST_CHANGE_PO_PRICE'); MSG_QST_SAVE_REPORT := siLang.GetText('strMSG_QST_SAVE_REPORT'); MSQ_QST_CHANGE_RECONCILED_TRANS := siLang.GetText('strMSQ_QST_CHANGE_RECONCILED_TRANS'); MSG_QST_CONTINUE := siLang.GetText('strMSG_QST_CONTINUE'); MSG_QST_CLOSE_LAYAWAY := siLang.GetText('strMSG_QST_CLOSE_LAYAWAY'); MSG_QST_INV_NEGATIVE := siLang.GetText('strMSG_QST_INV_NEGATIVE'); MSG_QST_CONF_TRANSFER := siLang.GetText('strMSG_QST_CONF_TRANSFER'); MSG_QST_OPEN_CASH_LESS_MONEY := siLang.GetText('strMSG_QST_OPEN_CASH_LESS_MONEY'); MSG_QST_PO_OPEN_SAVE := siLang.GetText('strMSG_QST_PO_OPEN_SAVE'); MSG_QST_INVOICE_ONLY_CASH := siLang.GetText('strMSG_QST_INVOICE_ONLY_CASH'); MSG_QST_PAYTYPE_NOT_ALLOW_DATE := siLang.GetText('strMSG_QST_PAYTYPE_NOT_ALLOW_DATE'); MSG_QST_CASH_IS_IN_USER := siLang.GetText('strMSG_QST_CASH_IS_IN_USER'); MSG_QST_INVOICE_DONOT_HAVE_ITEM := siLang.GetText('strMSG_QST_INVOICE_DONOT_HAVE_ITEM'); MSG_QST_NOT_MODEL_STORE := siLang.GetText('strMSG_QST_NOT_MODEL_STORE'); MSG_QST_RESTORE_INVENTORY := siLang.GetText('strMSG_QST_RESTORE_INVENTORY'); MSG_QST_CLEAN_UP_INVENTORY := siLang.GetText('strMSG_QST_CLEAN_UP_INVENTORY'); MSG_QST_SURE := siLang.GetText('strMSG_QST_SURE'); MSG_QST_RESTORE_TAX := siLang.GetText('strMSG_QST_RESTORE_TAX'); MSG_QST_PRINT_STATEMENT_DET := siLang.GetText('strMSG_QST_PRINT_STATEMENT_DET'); MSG_QST_PRINT_STATEMENT := siLang.GetText('strMSG_QST_PRINT_STATEMENT'); MSG_QST_CONFIRM_CLOSE_REGISTER := siLang.GetText('strMSG_QST_CONFIRM_CLOSE_REGISTER'); MSG_QST_DELETE_COST := siLang.GetText('strMSG_QST_DELETE_COST'); MSG_QST_DELETE_SERIALNUMBER := siLang.GetText('strMSG_QST_DELETE_SERIALNUMBER'); MSG_QST_DELETE_MODEL := siLang.GetText('strMSG_QST_DELETE_MODEL'); MSG_QST_CONFIRM_ADJUST_INV := siLang.GetText('strMSG_QST_CONFIRM_ADJUST_INV'); MSG_QST_CONFIRM_TAX_ISENTION := siLang.GetText('strMSG_QST_CONFIRM_TAX_ISENTION'); MSG_QST_CONFIRM_RECEVE_HOLD := siLang.GetText('strMSG_QST_CONFIRM_RECEVE_HOLD'); MSG_QST_CONFIRM_RECEVE_LAYAWAY := siLang.GetText('strMSG_QST_CONFIRM_RECEVE_LAYAWAY'); MSG_QST_CONFIRM_RECEVE_PURCHASE := siLang.GetText('strMSG_QST_CONFIRM_RECEVE_PURCHASE'); MSG_QST_CONFIRM_PURCHASE := siLang.GetText('strMSG_QST_CONFIRM_PURCHASE'); MSG_QST_CONFIRM_HOLD := siLang.GetText('strMSG_QST_CONFIRM_HOLD'); MSG_QST_CONFIRM_PAYMENT := siLang.GetText('strMSG_QST_CONFIRM_PAYMENT'); MSG_QST_CONFIRM_CHANGE_LOCAL := siLang.GetText('strMSG_QST_CONFIRM_CHANGE_LOCAL'); MSG_QST_CONFIRM_DEPOSIT_CASHREG := siLang.GetText('strMSG_QST_CONFIRM_DEPOSIT_CASHREG'); MSG_QST_CONFIRM_UNLOCK_PRESALE := siLang.GetText('strMSG_QST_CONFIRM_UNLOCK_PRESALE'); MSG_QST_CONFIRM_REPRINT := siLang.GetText('strMSG_QST_CONFIRM_REPRINT'); MSG_QST_CONFIRM_PETTY_CASH := siLang.GetText('strMSG_QST_CONFIRM_PETTY_CASH'); MSG_QST_CONFIRM_RESTORE := siLang.GetText('strMSG_QST_CONFIRM_RESTORE'); MSG_QST_CONFIRM := siLang.GetText('strMSG_QST_CONFIRM'); MSG_QST_DELETE_PERMANENT := siLang.GetText('strMSG_QST_DELETE_PERMANENT'); MSQ_QST_RETORE := siLang.GetText('strMSQ_QST_RETORE'); MSG_QST_DELETE := siLang.GetText('strMSG_QST_DELETE'); MSG_QTS_REBUILD_IDT := siLang.GetText('strMSG_QTS_REBUILD_IDT'); MSG_QST_ERASE_ALL_DISCOUNT_MOD := siLang.GetText('strMSG_QST_ERASE_ALL_DISCOUNT_MOD'); MSG_QST_ERASE_ALL_DISCOUNT_ADD := siLang.GetText('strMSG_QST_ERASE_ALL_DISCOUNT_ADD'); MSG_QST_ERASE_ALL_DISCOUNT := siLang.GetText('strMSG_QST_ERASE_ALL_DISCOUNT'); MSG_QST_DISCOUNT_WAS_REACHED := siLang.GetText('strMSG_QST_DISCOUNT_WAS_REACHED'); MSG_QST_DISCOUNT_REACHED := siLang.GetText('strMSG_QST_DISCOUNT_REACHED'); MSG_QST_NEW_COST_IN_INVENTORY := siLang.GetText('strMSG_QST_NEW_COST_IN_INVENTORY'); MSG_QST_DELETE_REQUEST := siLang.GetText('strMSG_QST_DELETE_REQUEST'); MSG_QST_DELETE_VENDOR_FROM_QUOT := siLang.GetText('strMSG_QST_DELETE_VENDOR_FROM_QUOT'); MSG_QST_DELETE_MODEL_FROM_QUOT := siLang.GetText('strMSG_QST_DELETE_MODEL_FROM_QUOT'); MSG_QST_ONE_OPEN_MANAGER_CONTUE := siLang.GetText('strMSG_QST_ONE_OPEN_MANAGER_CONTUE'); MSG_QST_COSTARV_DIFFER_CSTORDED := siLang.GetText('strMSG_QST_COSTARV_DIFFER_CSTORDED'); MSG_QST_COSTARV_BIGGER_CSTORDED := siLang.GetText('strMSG_QST_COSTARV_BIGGER_CSTORDED'); MSG_QST_QTYARV_BIGGER_QTYORDED := siLang.GetText('strMSG_QST_QTYARV_BIGGER_QTYORDED'); MSG_QST_AMOUN_NOT_REACH_MIN := siLang.GetText('strMSG_QST_AMOUN_NOT_REACH_MIN'); MSG_QST_PRICE_BELLOW := siLang.GetText('strMSG_QST_PRICE_BELLOW'); MSG_QST_SAVE_UNSAVE_CHANGES := siLang.GetText('strMSG_QST_SAVE_UNSAVE_CHANGES'); MSG_QST_UNSAVE_CHANGES := siLang.GetText('strMSG_QST_UNSAVE_CHANGES'); MSG_INF_PART2_SELECT_GL := siLang.GetText('strMSG_INF_PART2_SELECT_GL'); MSG_INF_PART1_SELECT_GL := siLang.GetText('strMSG_INF_PART1_SELECT_GL'); MSG_INF_PART2_INVALID_FILE_NAME := siLang.GetText('strMSG_INF_PART2_INVALID_FILE_NAME'); MSG_INF_PART1_INVALID_FILE_NAME := siLang.GetText('strMSG_INF_PART1_INVALID_FILE_NAME'); MSG_INF_PART_FILE_CREATED_AT := siLang.GetText('strMSG_INF_PART_FILE_CREATED_AT'); MSG_INF_PART_ROWS_IMPORTED := siLang.GetText('strMSG_INF_PART_ROWS_IMPORTED'); MSG_INF_PART2_RECONCILED_OK := siLang.GetText('strMSG_INF_PART2_RECONCILED_OK'); MSG_INF_PART1_RECONCILED_OK := siLang.GetText('strMSG_INF_PART1_RECONCILED_OK'); MSG_INF_PART_FILTER_APPENDED := siLang.GetText('strMSG_INF_PART_FILTER_APPENDED'); MSG_INF_PART_NO_DUPLICATED := siLang.GetText('strMSG_INF_PART_NO_DUPLICATED'); MSG_INF_PART_NEW_HOLD_NUMBER := siLang.GetText('strMSG_INF_PART_NEW_HOLD_NUMBER'); MSG_INF_PART_ITEM_SOLD_FOR := siLang.GetText('strMSG_INF_PART_ITEM_SOLD_FOR'); MSG_INF_PART2_COMMISS_PAIED := siLang.GetText('strMSG_INF_PART2_COMMISS_PAIED'); MSG_INF_PART1_COMMISS_PAIED := siLang.GetText('strMSG_INF_PART1_COMMISS_PAIED'); MSG_INF_PART2_PO_CREATE_MR := siLang.GetText('strMSG_INF_PART2_PO_CREATE_MR'); MSG_INF_PART1_PO_CREATE_MR := siLang.GetText('strMSG_INF_PART1_PO_CREATE_MR'); MSG_INF_PART_PETTYCASH_MAX := siLang.GetText('strMSG_INF_PART_PETTYCASH_MAX'); MSG_INF_PART2_USE_MR := siLang.GetText('strMSG_INF_PART2_USE_MR'); MSG_INF_PART1_USE_MR := siLang.GetText('strMSG_INF_PART1_USE_MR'); MSG_INF_NOT_DEL_TRANS_SPLITED := siLang.GetText('strMSG_INF_NOT_DEL_TRANS_SPLITED'); MSG_INF_SELECT_DB := siLang.GetText('strMSG_INF_SELECT_DB'); MSG_INF_SELECT_FILE := siLang.GetText('strMSG_INF_SELECT_FILE'); MSG_INF_BACKUP_ZIPPED := siLang.GetText('strMSG_INF_BACKUP_ZIPPED'); MSG_INF_BACKUP_COMPLETED := siLang.GetText('strMSG_INF_BACKUP_COMPLETED'); MSG_INF_RESTORE_COMPLETED := siLang.GetText('strMSG_INF_RESTORE_COMPLETED'); MSG_INF_TOTAL_VALUE_REACHED := siLang.GetText('strMSG_INF_TOTAL_VALUE_REACHED'); MSG_INF_NOT_VALID_CATEG_TYPE := siLang.GetText('strMSG_INF_NOT_VALID_CATEG_TYPE'); MSG_INF_LOGIN_EXPIRED := siLang.GetText('strMSG_INF_LOGIN_EXPIRED'); MSG_INF_CHANGE_CURRENCY_RECALC := siLang.GetText('strMSG_INF_CHANGE_CURRENCY_RECALC'); MSG_INF_NO_QUICKTIME_AVAILABLE := siLang.GetText('strMSG_INF_NO_QUICKTIME_AVAILABLE'); MSG_INF_NO_DATA_TO_EXPORT := siLang.GetText('strMSG_INF_NO_DATA_TO_EXPORT'); MSG_INF_NO_INFO_TO_IMPORT := siLang.GetText('strMSG_INF_NO_INFO_TO_IMPORT'); MSG_INF_SELECT_TRANS_TYPE := siLang.GetText('strMSG_INF_SELECT_TRANS_TYPE'); MSG_INF_SELECT_FILE_TYPE := siLang.GetText('strMSG_INF_SELECT_FILE_TYPE'); MSG_INF_SELECT_SOFTWARE := siLang.GetText('strMSG_INF_SELECT_SOFTWARE'); MSG_INF_SELECT_OPP_TYPE := siLang.GetText('strMSG_INF_SELECT_OPP_TYPE'); MSG_INF_FREQUENCY_DELETED := siLang.GetText('strMSG_INF_FREQUENCY_DELETED'); MSG_INF_NOT_PAY_DIFFER_ENTITY := siLang.GetText('strMSG_INF_NOT_PAY_DIFFER_ENTITY'); MSG_INF_SELECT_VENDOR_FOR_TERM := siLang.GetText('strMSG_INF_SELECT_VENDOR_FOR_TERM'); MSG_INF_NOT_EDIT_SYSREP := siLang.GetText('strMSG_INF_NOT_EDIT_SYSREP'); MSG_INF_NOT_DEL_SYSREP := siLang.GetText('strMSG_INF_NOT_DEL_SYSREP'); MSG_INF_NOT_TRANS_TO_RECONCILE := siLang.GetText('strMSG_INF_NOT_TRANS_TO_RECONCILE'); MSG_INF_DICTIONARI_NOT_FOUND := siLang.GetText('strMSG_INF_DICTIONARI_NOT_FOUND'); MSG_INF_ACCOUNT_EXPIRED := siLang.GetText('strMSG_INF_ACCOUNT_EXPIRED'); MSG_INF_MODEL_RESTORED := siLang.GetText('strMSG_INF_MODEL_RESTORED'); MSG_INF_REPRINT_INVOICE := siLang.GetText('strMSG_INF_REPRINT_INVOICE'); MSG_INF_DIFER_STORE := siLang.GetText('strMSG_INF_DIFER_STORE'); MSG_INF_INV_CLEANED := siLang.GetText('strMSG_INF_INV_CLEANED'); MSG_INF_CHOOSE_BANK := siLang.GetText('strMSG_INF_CHOOSE_BANK'); MSG_INF_CHOOSE_PAYTYPE := siLang.GetText('strMSG_INF_CHOOSE_PAYTYPE'); MSG_INF_PO_CREATED_VENDOR := siLang.GetText('strMSG_INF_PO_CREATED_VENDOR'); MSG_INF_LAYAWAY_HAS_HIST := siLang.GetText('strMSG_INF_LAYAWAY_HAS_HIST'); MSG_INF_NO_DEL_TOUR := siLang.GetText('strMSG_INF_NO_DEL_TOUR'); MSG_INF_ITEM_HAS_POS_QTY := siLang.GetText('strMSG_INF_ITEM_HAS_POS_QTY'); MSG_INF_EXPIRED_TIME := siLang.GetText('strMSG_INF_EXPIRED_TIME'); MSG_INF_TIME_ENTERED := siLang.GetText('strMSG_INF_TIME_ENTERED'); MSG_INF_CLOCK_OUT := siLang.GetText('strMSG_INF_CLOCK_OUT'); MSG_INF_CLOCK_IN := siLang.GetText('strMSG_INF_CLOCK_IN'); MSG_INF_HOLD_CANNOT_DELETE := siLang.GetText('strMSG_INF_HOLD_CANNOT_DELETE'); MSG_INF_HOLD_IS_USING := siLang.GetText('strMSG_INF_HOLD_IS_USING'); MSG_INF_HOLD_IS_LOCK := siLang.GetText('strMSG_INF_HOLD_IS_LOCK'); MSG_INF_GIFT_REGIST := siLang.GetText('strMSG_INF_GIFT_REGIST'); MSG_INF_TOTAL_SMALLER_PRE_SALE := siLang.GetText('strMSG_INF_TOTAL_SMALLER_PRE_SALE'); MSG_INF_CASH_IN_DEPOSIT := siLang.GetText('strMSG_INF_CASH_IN_DEPOSIT'); MSG_INF_MANAGER_CAN_REMOV_HOLD := siLang.GetText('strMSG_INF_MANAGER_CAN_REMOV_HOLD'); MSG_INF_PO_CREATED := siLang.GetText('strMSG_INF_PO_CREATED'); MSG_INF_PO_OPEN := siLang.GetText('strMSG_INF_PO_OPEN'); MSG_INF_MODEL_ORDERED := siLang.GetText('strMSG_INF_MODEL_ORDERED'); MSG_INF_INVOICE_HAS_SETUP := siLang.GetText('strMSG_INF_INVOICE_HAS_SETUP'); MSG_INF_MODEL_EXIST := siLang.GetText('strMSG_INF_MODEL_EXIST'); MSG_INF_VENDOR_EXIST := siLang.GetText('strMSG_INF_VENDOR_EXIST'); MSG_INF_INVOICE_REC_ONLY_CASH := siLang.GetText('strMSG_INF_INVOICE_REC_ONLY_CASH'); MSG_INF_PAYTYPE_NOT_THIS_DATE := siLang.GetText('strMSG_INF_PAYTYPE_NOT_THIS_DATE'); MSG_INF_INVOICE_NOT_REACH_DATE := siLang.GetText('strMSG_INF_INVOICE_NOT_REACH_DATE'); MSG_INF_INVOICE_NOT_HAVE_ITEM := siLang.GetText('strMSG_INF_INVOICE_NOT_HAVE_ITEM'); MSG_INF_INVOICE_NOT_REACH := siLang.GetText('strMSG_INF_INVOICE_NOT_REACH'); MSG_INF_HOLD_PAYING_NO_DELETE := siLang.GetText('strMSG_INF_HOLD_PAYING_NO_DELETE'); MSG_INF_HOLD_PAYING := siLang.GetText('strMSG_INF_HOLD_PAYING'); MSG_INF_NOT_CASHIER_PASWORD := siLang.GetText('strMSG_INF_NOT_CASHIER_PASWORD'); MSG_INF_NOT_MANEGER_PASWORD := siLang.GetText('strMSG_INF_NOT_MANEGER_PASWORD'); MSG_INF_NOT_EXCEL_ITEMS := siLang.GetText('strMSG_INF_NOT_EXCEL_ITEMS'); MSG_INF_NOT_DESCRIPTION_EMPTY := siLang.GetText('strMSG_INF_NOT_DESCRIPTION_EMPTY'); MSG_INF_TRY_ADD_ROUTES := siLang.GetText('strMSG_INF_TRY_ADD_ROUTES'); MSG_INF_CHANGES_SYS := siLang.GetText('strMSG_INF_CHANGES_SYS'); MSG_INF_MODEL_DELETED := siLang.GetText('strMSG_INF_MODEL_DELETED'); MSG_INF_NOT_RECEIVE_HOLD := siLang.GetText('strMSG_INF_NOT_RECEIVE_HOLD'); MSG_INF_NOT_QTY_SMALLER_1 := siLang.GetText('strMSG_INF_NOT_QTY_SMALLER_1'); MSG_INF_REBUILD_IDT := siLang.GetText('strMSG_INF_REBUILD_IDT'); MSG_INF_NOT_DUPLICATED_QTY := siLang.GetText('strMSG_INF_NOT_DUPLICATED_QTY'); MSG_INF_NOT_SELL_BELLOW_COST := siLang.GetText('strMSG_INF_NOT_SELL_BELLOW_COST'); MSG_INF_NOT_REFUND_ITEM := siLang.GetText('strMSG_INF_NOT_REFUND_ITEM'); MSG_INF_NOT_GIVE_GIFTS := siLang.GetText('strMSG_INF_NOT_GIVE_GIFTS'); MSG_INF_NOT_EMPTY_VALUES := siLang.GetText('strMSG_INF_NOT_EMPTY_VALUES'); MSG_INF_NOT_MANAGE_CR := siLang.GetText('strMSG_INF_NOT_MANAGE_CR'); MSG_INF_NOT_DEL_ITEMS_LAYAWAY := siLang.GetText('strMSG_INF_NOT_DEL_ITEMS_LAYAWAY'); MSG_INF_NOT_DELETE_ITEMS := siLang.GetText('strMSG_INF_NOT_DELETE_ITEMS'); MSG_INF_NOT_CHANGE_ITEMS := siLang.GetText('strMSG_INF_NOT_CHANGE_ITEMS'); MSG_INF_SELECT_USER := siLang.GetText('strMSG_INF_SELECT_USER'); MSG_INF_COUNT_ITEMS := siLang.GetText('strMSG_INF_COUNT_ITEMS'); MSG_INF_MANAGER_TONEGATIVE_DISC := siLang.GetText('strMSG_INF_MANAGER_TONEGATIVE_DISC'); MSG_INF_ONE_OPEN_CASREG_MANAGER := siLang.GetText('strMSG_INF_ONE_OPEN_CASREG_MANAGER'); MSG_INF_ONE_OPEN_PO_VENDOR := siLang.GetText('strMSG_INF_ONE_OPEN_PO_VENDOR'); MSG_INF_NO_ASSOC_COMMITION := siLang.GetText('strMSG_INF_NO_ASSOC_COMMITION'); MSG_INF_CANNOT_ACCESS_MODULE := siLang.GetText('strMSG_INF_CANNOT_ACCESS_MODULE'); MSG_INF_SUPPLU_ADJ_DATE := siLang.GetText('strMSG_INF_SUPPLU_ADJ_DATE'); MSG_INF_ERROR := siLang.GetText('strMSG_INF_ERROR'); MSG_INF_DATA_SUCESSFULY := siLang.GetText('strMSG_INF_DATA_SUCESSFULY'); MSG_INF_RESTORED_SUCESSFULY := siLang.GetText('strMSG_INF_RESTORED_SUCESSFULY'); MSG_INF_CHOOSE_NAME := siLang.GetText('strMSG_INF_CHOOSE_NAME'); MSG_INF_INVALID_USER_PASSWORD := siLang.GetText('strMSG_INF_INVALID_USER_PASSWORD'); MSG_INF_INVALID_PASSWORD := siLang.GetText('strMSG_INF_INVALID_PASSWORD'); MSG_INF_PASSWORD_CANNOT_BE_NULL := siLang.GetText('strMSG_INF_PASSWORD_CANNOT_BE_NULL'); MSG_INF_CSR_IS_CLOSED := siLang.GetText('strMSG_INF_CSR_IS_CLOSED'); MSG_INF_ADJUSTMENT := siLang.GetText('strMSG_INF_ADJUSTMENT'); MSG_INF_WRONG_QTY := siLang.GetText('strMSG_INF_WRONG_QTY'); MSG_INF_INVOICE_NOT_FOND := siLang.GetText('strMSG_INF_INVOICE_NOT_FOND'); MSG_INF_BARCODE_NOT_DEL := siLang.GetText('strMSG_INF_BARCODE_NOT_DEL'); MSG_INF_NO_DATA_FOUND := siLang.GetText('strMSG_INF_NO_DATA_FOUND'); MSG_INF_NO_FILETER_APPENDED := siLang.GetText('strMSG_INF_NO_FILETER_APPENDED'); MSG_INF_FILETER_SAVED := siLang.GetText('strMSG_INF_FILETER_SAVED'); MSG_INF_FILETER_CLEARED := siLang.GetText('strMSG_INF_FILETER_CLEARED'); MSG_EXC_PART2_NO_MORE_SERIAL := siLang.GetText('strMSG_EXC_PART2_NO_MORE_SERIAL'); MSG_EXC_PART1_NO_MORE_SERIAL := siLang.GetText('strMSG_EXC_PART1_NO_MORE_SERIAL'); MSG_EXC_PART2_NO_HOLD_NUMBER := siLang.GetText('strMSG_EXC_PART2_NO_HOLD_NUMBER'); MSG_EXC_PART1_NO_HOLD_NUMBER := siLang.GetText('strMSG_EXC_PART1_NO_HOLD_NUMBER'); MSG_EXC_INVALID_HOLD_NUMBER := siLang.GetText('strMSG_EXC_INVALID_HOLD_NUMBER'); MSG_EXC_NO_MORE_ROWS_RETRIVE := siLang.GetText('strMSG_EXC_NO_MORE_ROWS_RETRIVE'); MSG_EXC_BARCODE_EXIST_PO := siLang.GetText('strMSG_EXC_BARCODE_EXIST_PO'); MSG_EXC_MODULE_DISABLE := siLang.GetText('strMSG_EXC_MODULE_DISABLE'); MSG_EXC_QTY_BIGGER := siLang.GetText('strMSG_EXC_QTY_BIGGER'); MSG_EXC_NO_ASSOCIETE_CASREG := siLang.GetText('strMSG_EXC_NO_ASSOCIETE_CASREG'); MSG_EXC_NO_DEFAULT_CASREG := siLang.GetText('strMSG_EXC_NO_DEFAULT_CASREG'); MSG_EXC_BARCODE_EXISTE := siLang.GetText('strMSG_EXC_BARCODE_EXISTE'); MSG_EXC_SELECT_A_MODEL := siLang.GetText('strMSG_EXC_SELECT_A_MODEL'); end; end.
unit VirtualShellContainers; // Version 1.3.0 // // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the // specific language governing rights and limitations under the License. // // The initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- // // Classes to help with storing TNamespaces interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, VirtualShellUtilities; type TVirtualNameSpaceList = class; // Forward TObjectList = class(TList) private FOwnsObjects: Boolean; protected function GetItem(Index: Integer): TObject; procedure SetItem(Index: Integer; AObject: TObject); public constructor Create; overload; constructor Create(AOwnsObjects: Boolean); overload; function Add(AObject: TObject): Integer; {$IFDEF DELPHI_5_UP} function Extract(Item: TObject): TObject; {$ENDIF} function Remove(AObject: TObject): Integer; function IndexOf(AObject: TObject): Integer; function FindInstanceOf(AClass: TClass; AExact: Boolean = True; AStartAt: Integer = 0): Integer; procedure Insert(Index: Integer; AObject: TObject); function First: TObject; function Last: TObject; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; property Items[Index: Integer]: TObject read GetItem write SetItem; default; end; {$IFDEF DELPHI_5_UP} TVirtualNamespaceListNotifyEvent = procedure(Sender: TVirtualNameSpaceList; Namespace: TNamespace; Action: TListNotification); {$ELSE} TVirtualNamespaceListNotifyEvent = procedure(Sender: TVirtualNameSpaceList; Namespace: TNamespace); {$ENDIF} TVirtualNameSpaceList = class(TObjectList) FOnChanged : TVirtualNamespaceListNotifyEvent; protected {$IFDEF DELPHI_5_UP} procedure Notify(Ptr: Pointer; Action: TListNotification); override; {$ENDIF} function GetItems(Index: Integer): TNameSpace; procedure SetItems(Index: Integer; ANameSpace: TNameSpace); public function Add(ANameSpace: TNamespace): Integer; {$IFDEF DELPHI_5_UP} function Extract(Item: TNameSpace): TNameSpace; {$ENDIF DELPHI_5_UP} procedure FillArray(var NamespaceArray: TNamespaceArray); function First: TNameSpace; procedure FreeNamespaces; function IndexOf(ANameSpace: TNameSpace): Integer; procedure Insert(Index: Integer; ANameSpace: TNameSpace); function Last: TNameSpace; function Remove(ANameSpace: TNameSpace): Integer; property Items[Index: Integer]: TNamespace read GetItems write SetItems; default; property OnChanged: TVirtualNamespaceListNotifyEvent read FOnChanged write FOnChanged; end; implementation { TObjectList } function TObjectList.Add(AObject: TObject): Integer; begin Result := inherited Add(AObject); end; constructor TObjectList.Create; begin inherited Create; FOwnsObjects := True; end; constructor TObjectList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; {$IFDEF DELPHI_5_UP} function TObjectList.Extract(Item: TObject): TObject; begin Result := TObject(inherited Extract(Item)); end; {$ENDIF DELPHI_5_UP} function TObjectList.FindInstanceOf(AClass: TClass; AExact: Boolean; AStartAt: Integer): Integer; var I: Integer; begin Result := -1; for I := AStartAt to Count - 1 do if (AExact and (Items[I].ClassType = AClass)) or (not AExact and Items[I].InheritsFrom(AClass)) then begin Result := I; break; end; end; function TObjectList.First: TObject; begin Result := TObject(inherited First); end; function TObjectList.GetItem(Index: Integer): TObject; begin Result := inherited Items[Index]; end; function TObjectList.IndexOf(AObject: TObject): Integer; begin Result := inherited IndexOf(AObject); end; procedure TObjectList.Insert(Index: Integer; AObject: TObject); begin inherited Insert(Index, AObject); end; function TObjectList.Last: TObject; begin Result := TObject(inherited Last); end; function TObjectList.Remove(AObject: TObject): Integer; begin Result := inherited Remove(AObject); end; procedure TObjectList.SetItem(Index: Integer; AObject: TObject); begin inherited Items[Index] := AObject; end; { TVirtualNameSpaceList } function TVirtualNameSpaceList.Add(ANameSpace: TNameSpace): Integer; begin Result := inherited Add(ANameSpace); end; {$IFDEF DELPHI_5_UP} function TVirtualNameSpaceList.Extract(Item: TNameSpace): TNameSpace; begin Result := TNamespace( inherited Extract(Item)) end; {$ENDIF DELPHI_5_UP} procedure TVirtualNameSpaceList.FillArray(var NamespaceArray: TNamespaceArray); begin SetLength(NamespaceArray, Count); MoveMemory(@NamespaceArray[0], List, SizeOf(TNamespace)*Count); end; function TVirtualNameSpaceList.First: TNameSpace; begin Result := TNamespace( inherited First) end; procedure TVirtualNameSpaceList.FreeNamespaces; var i: integer; begin for i := 0 to Count - 1 do begin TObject(Items[i]).Free; Items[i] := nil end; end; function TVirtualNameSpaceList.GetItems (Index: Integer): TNameSpace; begin Result := TNameSpace(inherited Items[Index]); end; function TVirtualNameSpaceList.IndexOf (ANameSpace: TNameSpace): Integer; begin Result := inherited IndexOf(ANameSpace); end; procedure TVirtualNameSpaceList.Insert (Index: Integer; ANameSpace: TNameSpace); begin inherited Insert(Index, ANameSpace); end; function TVirtualNameSpaceList.Last: TNameSpace; begin Result := TNamespace( inherited Last) end; {$IFDEF DELPHI_5_UP} procedure TVirtualNameSpaceList.Notify(Ptr: Pointer; Action: TListNotification); begin if Assigned(FOnChanged) then FOnChanged(Self, TNamespace(Ptr), Action); inherited; end; {$ENDIF} function TVirtualNameSpaceList.Remove (ANameSpace: TNameSpace): Integer; begin Result := inherited Remove(ANameSpace); end; procedure TVirtualNameSpaceList.SetItems (Index: Integer; ANameSpace: TNameSpace); begin inherited Items[Index] := ANameSpace; end; end.
{ *************************************************************************** } { } { EControl Syntax Editor SDK } { } { Copyright (c) 2004 - 2015 EControl Ltd., Zaharov Michael } { www.econtrol.ru } { support@econtrol.ru } { Ported to Lazarus: Alexey T., UVviewsoft.com } { } { *************************************************************************** } {$mode delphi} unit ec_SyntAnal; interface uses Classes, Graphics, Controls, ExtCtrls, Contnrs, LazUTF8Classes, //TFileStreamUTF8 ec_RegExpr, ec_StrUtils, ec_Lists, ec_SyntGramma, ATStringProc_TextBuffer, ec_proc_StreamComponent; type IecSyntClient = interface ['{045EAD6D-5584-4A60-849E-6B8994AA5B8F}'] procedure FormatChanged; // Lexer properties changed (update without clear) procedure Finished; // Compleat analysis end; TecLineBreakPos = (lbTop, lbBottom); TecLineBreakBound = set of TecLineBreakPos; // for user blocks TecVertAlignment = (vaTop, vaCenter, vaBottom); TecFormatType = (ftCustomFont, // Any customizing ftFontAttr, // Except custom font ftColor, // Any color ftBackGround);// Only background color TecSyntAnalyzer = class; TecParserResults = class; TecClientSyntAnalyzer = class; TecTagBlockCondition = class; TecSyntaxManager = class; TecSyntaxFormat = class; TecSubAnalyzerRule = class; TecTextRange = class; TOnMatchToken = procedure(Sender: TObject; Client: TecParserResults; const Text: ecString; APos: integer; var MatchLen: integer) of object; TOnBlockCheck = procedure(Sender: TObject; Client: TecClientSyntAnalyzer; const Text: ecString; var RefIdx: integer; var Accept: Boolean) of object; TBoundDefEvent = procedure(Sender: TecClientSyntAnalyzer; Range: TecTextRange; var sIdx, eIdx: integer) of object; TSyntCollectionItem = class(TCollectionItem) private FName: string; FEnabled: Boolean; procedure SetEnabled(const Value: Boolean); protected procedure AssignTo(Dest: TPersistent); override; function GetItemBaseName: string; virtual; function GetDisplayName: string; override; procedure SetDisplayName(const Value: string); override; procedure Loaded; virtual; function GetIsInvalid: Boolean; virtual; public constructor Create(Collection: TCollection); override; property IsInvalid: Boolean read GetIsInvalid; published property DisplayName; property Enabled: Boolean read FEnabled write SetEnabled default True; end; TSyntItemChanged = procedure(Sender: TCollection; Item: TSyntCollectionItem) of object; TSyntCollection = class(TCollection) private FSyntOwner: TecSyntAnalyzer; FOnChange: TSyntItemChanged; function GetItems(Index: integer): TSyntCollectionItem; protected procedure Update(Item: TCollectionItem); override; function GetOwner: TPersistent; override; procedure Loaded; public constructor Create(ItemClass: TCollectionItemClass); function ItemByName(const AName: string): TSyntCollectionItem; function ValidItem(Item: TSyntCollectionItem): Boolean; function GetUniqueName(const Base: string): string; property SyntOwner: TecSyntAnalyzer read FSyntOwner write FSyntOwner; property Items[Index: integer]: TSyntCollectionItem read GetItems; default; property OnChange: TSyntItemChanged read FOnChange write FOnChange; end; TRuleCollectionItem = class(TSyntCollectionItem) private FStyleName: string; FBlockName: string; FFormat: TecSyntaxFormat; FBlock: TecTagBlockCondition; FStrictParent: Boolean; FNotParent: Boolean; FAlwaysEnabled: Boolean; FStatesAbsent: integer; FStatesAdd: integer; FStatesRemove: integer; FStatesPresent: integer; function GetStyleName: string; procedure SetStyleName(const Value: string); function GetBlockName: string; procedure SetBlockName(const Value: string); procedure SetNotParent(const Value: Boolean); procedure SetStrictParent(const Value: Boolean); procedure SetAlwaysEnabled(const Value: Boolean); function GetSyntOwner: TecSyntAnalyzer; procedure SetStatesAdd(const Value: integer); procedure SetStatesAbsent(const Value: integer); procedure SetStatesRemove(const Value: integer); procedure SetStatesPresent(const Value: integer); protected function ValidStyleName(const AStyleName: string; AStyle: TecSyntaxFormat): string; function ValidSetStyle(const AStyleName: string; var AStyleField: string; var AStyle: TecSyntaxFormat): string; procedure AssignTo(Dest: TPersistent); override; procedure Loaded; override; public property Style: TecSyntaxFormat read FFormat write FFormat; property Block: TecTagBlockCondition read FBlock write FBlock; property SyntOwner: TecSyntAnalyzer read GetSyntOwner; published property StyleName: string read GetStyleName write SetStyleName; property BlockName: string read GetBlockName write SetBlockName; property StrictParent: Boolean read FStrictParent write SetStrictParent default False; property NotParent: Boolean read FNotParent write SetNotParent default False; property AlwaysEnabled: Boolean read FAlwaysEnabled write SetAlwaysEnabled default False; property StatesAdd: integer read FStatesAdd write SetStatesAdd default 0; property StatesRemove: integer read FStatesRemove write SetStatesRemove default 0; property StatesPresent: integer read FStatesPresent write SetStatesPresent default 0; property StatesAbsent: integer read FStatesAbsent write SetStatesAbsent default 0; end; // ******************************************************************* // Format for syntax output // ******************************************************************* TecBorderLineType = (blNone, blSolid, blDash, blDot, blDashDot, blDashDotDot, blSolid2, blSolid3, blWavyLine, blDouble); TecFormatFlag = (ffBold, ffItalic, ffUnderline, ffStrikeOut, ffReadOnly, ffHidden, ffFontName, ffFontSize, ffFontCharset, ffVertAlign); TecFormatFlags = set of TecFormatFlag; TecChangeCase = (ccNone, ccUpper, ccLower, ccToggle, ccTitle); TecSyntaxFormat = class(TSyntCollectionItem) private FIsBlock: Boolean; FFont: TFont; FBgColor: TColor; FVertAlign: TecVertAlignment; FFormatType: TecFormatType; FOnChange: TNotifyEvent; FHidden: Boolean; FBorderTypes: array[0..3] of TecBorderLineType; FBorderColors: array[0..3] of TColor; FMultiLineBorder: Boolean; FReadOnly: Boolean; FChangeCase: TecChangeCase; FFormatFlags: TecFormatFlags; procedure SetFont(const Value: TFont); procedure SetBgColor(const Value: TColor); procedure FontChanged(Sender: TObject); procedure SetVertAlign(const Value: TecVertAlignment); procedure SetFormatType(const Value: TecFormatType); procedure SetHidden(const Value: Boolean); function GetBorderColor(Index: Integer): TColor; function GetBorderType(Index: Integer): TecBorderLineType; procedure SetBorderColor(Index: Integer; const Value: TColor); procedure SetBorderType(Index: Integer; const Value: TecBorderLineType); procedure SetMultiLineBorder(const Value: Boolean); procedure SetReadOnly(const Value: Boolean); procedure SetChangeCase(const Value: TecChangeCase); procedure SetFormatFlags(const Value: TecFormatFlags); function GetHidden: Boolean; protected procedure AssignTo(Dest: TPersistent); override; function GetItemBaseName: string; override; procedure Change; dynamic; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function HasBorder: Boolean; procedure ApplyTo(Canvas: TCanvas; AllowChangeFont: Boolean = True); function IsEqual(Other: TecSyntaxFormat): Boolean; // Merges style above this style procedure Merge(Over: TecSyntaxFormat); // Save only common properties procedure Intersect(Over: TecSyntaxFormat); property OnChange: TNotifyEvent read FOnChange write FOnChange; property BorderTypes[Index: integer]: TecBorderLineType read GetBorderType write SetBorderType; property BorderColors[Index: integer]: TColor read GetBorderColor write SetBorderColor; published property Font: TFont read FFont write SetFont; property BgColor: TColor read FBgColor write SetBgColor default clNone; property VertAlignment: TecVertAlignment read FVertAlign write SetVertAlign default vaCenter; property FormatType: TecFormatType read FFormatType write SetFormatType default ftFontAttr; property Hidden: Boolean read GetHidden write SetHidden default False; property BorderTypeLeft: TecBorderLineType index 0 read GetBorderType write SetBorderType default blNone; property BorderColorLeft: TColor index 0 read GetBorderColor write SetBorderColor default clBlack; property BorderTypeTop: TecBorderLineType index 1 read GetBorderType write SetBorderType default blNone; property BorderColorTop: TColor index 1 read GetBorderColor write SetBorderColor default clBlack; property BorderTypeRight: TecBorderLineType index 2 read GetBorderType write SetBorderType default blNone; property BorderColorRight: TColor index 2 read GetBorderColor write SetBorderColor default clBlack; property BorderTypeBottom: TecBorderLineType index 3 read GetBorderType write SetBorderType default blNone; property BorderColorBottom: TColor index 3 read GetBorderColor write SetBorderColor default clBlack; property MultiLineBorder: Boolean read FMultiLineBorder write SetMultiLineBorder default False; property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; property ChangeCase: TecChangeCase read FChangeCase write SetChangeCase default ccNone; property FormatFlags: TecFormatFlags read FFormatFlags write SetFormatFlags default [ffBold, ffItalic, ffUnderline, ffStrikeOut, ffReadOnly, ffHidden, ffFontName, ffFontSize, ffFontCharset, ffVertAlign]; end; TecStylesCollection = class(TSyntCollection) private function GetItem(Index: integer): TecSyntaxFormat; public function Synchronize(Source: TecStylesCollection): integer; constructor Create; function Add: TecSyntaxFormat; property Items[Index: integer]: TecSyntaxFormat read GetItem; default; end; // ******************************************************************* // description classes of text contents // ******************************************************************* { TecSyntToken } TecSyntToken = record private function GetStyle: TecSyntaxFormat; public Range: TRange; TokenType: integer; Rule: TRuleCollectionItem; constructor Create(ARule: TRuleCollectionItem; AStartPos, AEndPos: integer; const APointStart, APointEnd: TPoint); function GetStr(const Source: ecString): ecString; property Style: TecSyntaxFormat read GetStyle; class operator =(const A,B: TecSyntToken): boolean; end; TecTextRange = class(TSortedItem) private FCondIndex: integer; FEndCondIndex: integer; function GetLevel: integer; function GetIsClosed: Boolean; protected function GetKey: integer; override; public StartPos: integer; StartIdx, EndIdx: integer; IdentIdx: integer; Rule: TecTagBlockCondition; Parent: TecTextRange; Index: integer; constructor Create(AStartIdx, AStartPos: integer); property Level: integer read GetLevel; property IsClosed: Boolean read GetIsClosed; end; { TecSubLexerRange } TecSubLexerRange = record public Range: TRange; Rule: TecSubAnalyzerRule; // Rule reference CondEndPos: integer; // Start pos of the start condition CondStartPos: integer; // End pos of the end condition class operator =(const a, b: TecSubLexerRange): boolean; end; // ******************************************************************* // Rules for syntax interpretation // ******************************************************************* TecTagConditionType = (tcEqual, tcNotEqual, tcMask, tcSkip, tcStrictMask); TecSingleTagCondition = class(TCollectionItem) private FTagList: TStrings; FCondType: TecTagConditionType; FTokenTypes: DWORD; procedure SetTagList(const Value: TStrings); procedure SetIgnoreCase(const Value: Boolean); procedure SetTokenTypes(const Value: DWORD); procedure SetCondType(const Value: TecTagConditionType); procedure TagListChanged(Sender: TObject); function GetIgnoreCase: Boolean; protected procedure AssignTo(Dest: TPersistent); override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function CheckToken(const Source: ecString; const Token: TecSyntToken): Boolean; published property TagList: TStrings read FTagList write SetTagList; property CondType: TecTagConditionType read FCondType write SetCondType default tcEqual; property TokenTypes: DWORD read FTokenTypes write SetTokenTypes default 0; property IgnoreCase: Boolean read GetIgnoreCase write SetIgnoreCase default False; end; TecConditionCollection = class(TCollection) private FOwner: TecTagBlockCondition; FOnChange: TNotifyEvent; function GetItem(Index: integer): TecSingleTagCondition; protected procedure Update(Item: TCollectionItem); override; function GetOwner: TPersistent; override; public constructor Create(AOwner: TecTagBlockCondition); function Add: TecSingleTagCondition; property Items[Index: integer]: TecSingleTagCondition read GetItem; default; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TecTagBlockType = (btTagDetect, btLineBreak, btRangeStart, btRangeEnd); TecHighlightPos = (cpAny, cpBound, cpBoundTag, cpRange, cpBoundTagBegin, cpOutOfRange); TecDynamicHighlight = (dhNone, dhBound, dhRangeNoBound, dhRange); TecAutoCloseMode = (acmDisabled, acmCloseNearest, acmCloseOpened); TecTagBlockCondition = class(TRuleCollectionItem) private FConditions: TecConditionCollection; FIdentIndex: integer; FLinePos: TecLineBreakPos; FBlockOffset: integer; FBlockEndCond: TecTagBlockCondition; FBlockType: TecTagBlockType; FBlockEndName: string; FEndOfTextClose: Boolean; FNotCollapsed: Boolean; FSameIdent: Boolean; FInvertColors: Boolean; FHighlight: Boolean; FDisplayInTree: Boolean; FNameFmt: ecString; FGroupFmt: ecString; FRefToCondEnd: Boolean; FDynHighlight: TecDynamicHighlight; FHighlightPos: TecHighlightPos; FDynSelectMin: Boolean; FCancelNextRules: Boolean; FOnBlockCheck: TOnBlockCheck; FDrawStaple: Boolean; FGroupIndex: integer; FCollapseFmt: ecString; FSelfClose: Boolean; FNoEndRule: Boolean; FGrammaRuleName: string; FGrammaRule: TParserRule; FTokenType: integer; FTreeItemStyle: string; FTreeItemStyleObj: TecSyntaxFormat; FTreeGroupStyle: string; FTreeGroupStyleObj: TecSyntaxFormat; FTreeGroupImage: integer; FTreeItemImage: integer; FUseCustomPen: Boolean; FPen: TPen; FIgnoreAsParent: Boolean; FAutoCloseText: ecString; FAutoCloseMode: TecAutoCloseMode; procedure ConditionsChanged(Sender: TObject); function GetBlockEndName: string; procedure SetBlockEndName(const Value: string); procedure SetBlockType(const Value: TecTagBlockType); procedure SetConditions(const Value: TecConditionCollection); procedure SetBlockEndCond(const Value: TecTagBlockCondition); procedure SetLinePos(const Value: TecLineBreakPos); procedure SetIdentIndex(const Value: integer); procedure SetBlockOffset(const Value: integer); procedure SetEndOfTextClose(const Value: Boolean); procedure SetNotCollapsed(const Value: Boolean); procedure SetSameIdent(const Value: Boolean); procedure SetHighlight(const Value: Boolean); procedure SetInvertColors(const Value: Boolean); procedure SetDisplayInTree(const Value: Boolean); procedure SetCancelNextRules(const Value: Boolean); procedure SetDynHighlight(const Value: TecDynamicHighlight); procedure SetDynSelectMin(const Value: Boolean); procedure SetGroupFmt(const Value: ecString); procedure SetHighlightPos(const Value: TecHighlightPos); procedure SetNameFmt(const Value: ecString); procedure SetRefToCondEnd(const Value: Boolean); procedure SetDrawStaple(const Value: Boolean); procedure SetCollapseFmt(const Value: ecString); procedure SetSelfClose(const Value: Boolean); procedure SetNoEndRule(const Value: Boolean); procedure SetGrammaRuleName(const Value: string); procedure SetTokenType(const Value: integer); function GetTreeItemStyle: string; procedure SetTreeItemStyle(const Value: string); function GetTreeGroupStyle: string; procedure SetTreeGroupStyle(const Value: string); procedure SetTreeGroupImage(const Value: integer); procedure SetTreeItemImage(const Value: integer); procedure SetPen(const Value: TPen); procedure SetUseCustomPen(const Value: Boolean); procedure SetIgnoreAsParent(const Value: Boolean); procedure SetAutoCloseText(Value: ecString); procedure SetAutoCloseMode(const Value: TecAutoCloseMode); protected procedure AssignTo(Dest: TPersistent); override; function GetItemBaseName: string; override; procedure Loaded; override; function CheckOffset: integer; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function Check(const Source: ecString; Tags: TecClientSyntAnalyzer; N: integer; var RefIdx: integer): Boolean; property BlockEndCond: TecTagBlockCondition read FBlockEndCond write SetBlockEndCond; property TreeItemStyleObj: TecSyntaxFormat read FTreeItemStyleObj; property TreeGroupStyleObj: TecSyntaxFormat read FTreeGroupStyleObj; published property BlockType: TecTagBlockType read FBlockType write SetBlockType default btRangeStart; property ConditionList: TecConditionCollection read FConditions write SetConditions; property IdentIndex: integer read FIdentIndex write SetIdentIndex default 0; property LinePos: TecLineBreakPos read FLinePos write SetLinePos default lbTop; property BlockOffset: integer read FBlockOffset write SetBlockOffset default 0; property BlockEnd: string read GetBlockEndName write SetBlockEndName; property EndOfTextClose: Boolean read FEndOfTextClose write SetEndOfTextClose default False; property NotCollapsed: Boolean read FNotCollapsed write SetNotCollapsed default False; property SameIdent: Boolean read FSameIdent write SetSameIdent default False; property Highlight: Boolean read FHighlight write SetHighlight default False; property InvertColors: Boolean read FInvertColors write SetInvertColors default False; property DisplayInTree: Boolean read FDisplayInTree write SetDisplayInTree default True; property NameFmt: ecString read FNameFmt write SetNameFmt; property GroupFmt: ecString read FGroupFmt write SetGroupFmt; property RefToCondEnd: Boolean read FRefToCondEnd write SetRefToCondEnd default False; property DynHighlight: TecDynamicHighlight read FDynHighlight write SetDynHighlight default dhNone; property HighlightPos: TecHighlightPos read FHighlightPos write SetHighlightPos; property DynSelectMin: Boolean read FDynSelectMin write SetDynSelectMin default False; property CancelNextRules: Boolean read FCancelNextRules write SetCancelNextRules default False; property DrawStaple: Boolean read FDrawStaple write SetDrawStaple default False; property GroupIndex: integer read FGroupIndex write FGroupIndex default 0; property CollapseFmt: ecString read FCollapseFmt write SetCollapseFmt; property OnBlockCheck: TOnBlockCheck read FOnBlockCheck write FOnBlockCheck; property SelfClose: Boolean read FSelfClose write SetSelfClose default False; // New in v2.20 property NoEndRule: Boolean read FNoEndRule write SetNoEndRule default False; property GrammaRuleName: string read FGrammaRuleName write SetGrammaRuleName; property TokenType: integer read FTokenType write SetTokenType default -1; property TreeItemStyle: string read GetTreeItemStyle write SetTreeItemStyle; property TreeGroupStyle: string read GetTreeGroupStyle write SetTreeGroupStyle; property TreeItemImage: integer read FTreeItemImage write SetTreeItemImage default -1; property TreeGroupImage: integer read FTreeGroupImage write SetTreeGroupImage default -1; // New in 2.40 property Pen: TPen read FPen write SetPen; property UseCustomPen: Boolean read FUseCustomPen write SetUseCustomPen default False; property IgnoreAsParent: Boolean read FIgnoreAsParent write SetIgnoreAsParent; // New in 2.50 property AutoCloseMode: TecAutoCloseMode read FAutoCloseMode write SetAutoCloseMode default acmDisabled; property AutoCloseText: ecString read FAutoCloseText write SetAutoCloseText; end; TecBlockRuleCollection = class(TSyntCollection) private function GetItem(Index: integer): TecTagBlockCondition; public constructor Create; function Add: TecTagBlockCondition; property Items[Index: integer]: TecTagBlockCondition read GetItem; default; end; // Token identification rule TecTokenRule = class(TRuleCollectionItem) private FRegExpr: TecRegExpr; FTokenType: integer; FOnMatchToken: TOnMatchToken; FColumnTo: integer; FColumnFrom: integer; function GetExpression: ecString; procedure SetExpression(const Value: ecString); procedure SetTokenType(const Value: integer); procedure SetColumnFrom(const Value: integer); procedure SetColumnTo(const Value: integer); protected procedure AssignTo(Dest: TPersistent); override; function GetItemBaseName: string; override; function GetIsInvalid: Boolean; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function Match(const Source: ecString; Pos: integer): integer; published property TokenType: integer read FTokenType write SetTokenType default 0; property Expression: ecString read GetExpression write SetExpression; property ColumnFrom: integer read FColumnFrom write SetColumnFrom; property ColumnTo: integer read FColumnTo write SetColumnTo; property OnMatchToken: TOnMatchToken read FOnMatchToken write FOnMatchToken; end; TecTokenRuleCollection = class(TSyntCollection) private function GetItem(Index: integer): TecTokenRule; public constructor Create; function Add: TecTokenRule; property Items[Index: integer]: TecTokenRule read GetItem; default; end; TecSubAnalyzerRule = class(TRuleCollectionItem) private FStartRegExpr: TecRegExpr; FEndRegExpr: TecRegExpr; FSyntAnalyzer: TecSyntAnalyzer; FFromTextBegin: Boolean; FToTextEnd: Boolean; FIncludeBounds: Boolean; function GetEndExpression: string; function GetStartExpression: string; procedure SetEndExpression(const Value: string); procedure SetStartExpression(const Value: string); procedure SetSyntAnalyzer(const Value: TecSyntAnalyzer); procedure SetFromTextBegin(const Value: Boolean); procedure SetToTextEnd(const Value: Boolean); procedure SetIncludeBounds(const Value: Boolean); protected procedure AssignTo(Dest: TPersistent); override; function GetItemBaseName: string; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function MatchStart(const Source: ecString; Pos: integer): integer; function MatchEnd(const Source: ecString; Pos: integer): integer; published property StartExpression: string read GetStartExpression write SetStartExpression; property EndExpression: string read GetEndExpression write SetEndExpression; property SyntAnalyzer: TecSyntAnalyzer read FSyntAnalyzer write SetSyntAnalyzer; property FromTextBegin: Boolean read FFromTextBegin write SetFromTextBegin default False; property ToTextEnd: Boolean read FToTextEnd write SetToTextEnd default False; property IncludeBounds: Boolean read FIncludeBounds write SetIncludeBounds default False; end; TecSubAnalyzerRules = class(TSyntCollection) private function GetItem(Index: integer): TecSubAnalyzerRule; public constructor Create; function Add: TecSubAnalyzerRule; property Items[Index: integer]: TecSubAnalyzerRule read GetItem; default; end; { TecCodeTemplate } TecCodeTemplate = class(TCollectionItem) private FName: string; FDescription: string; FAdvanced: boolean; FCode: TStrings; protected function GetDisplayName: string; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; published property Name: string read FName write FName; property Description: string read FDescription write FDescription; property Advanced: Boolean read FAdvanced write FAdvanced; property Code: TStrings read FCode; end; TecCodeTemplates = class(TOwnedCollection) private function GetItem(Index: integer): TecCodeTemplate; public constructor Create(AOwner: TPersistent); function Add: TecCodeTemplate; property Items[Index: integer]: TecCodeTemplate read GetItem; default; end; // ******************************************************************* // Parser classes // // ******************************************************************* // ******************************************************************* // Syntax analizer for single client // container of description objects // ******************************************************************* TecTokenList = GRangeList<TecSyntToken>; TecSubLexerRanges = GRangeList<TecSubLexerRange>; { TecParserResults } TecParserResults = class(TTokenHolder) private FBuffer: TATStringBuffer; FClient: IecSyntClient; FOwner: TecSyntAnalyzer; FFinished: Boolean; FSubLexerBlocks: TecSubLexerRanges; FTagList: TecTokenList; FCurState: integer; FStateChanges: TRangeList; function GetLastPos(const Source: ecString): integer; function ExtractTag(const Source: ecString; var FPos: integer; IsIdle: Boolean): Boolean; function GetTags(Index: integer): TecSyntToken; function GetSubLexerRangeCount: integer; function GetSubLexerRange(Index: integer): TecSubLexerRange; procedure SetTags(Index: integer; const AValue: TecSyntToken); protected function GetTokenCount: integer; override; function GetTokenStr(Index: integer): ecString; override; function GetTokenType(Index: integer): integer; override; procedure CloseAtEnd(StartTagIdx: integer); virtual; abstract; protected FLastAnalPos: integer; procedure Finished; virtual; function IsEnabled(Rule: TRuleCollectionItem; OnlyGlobal: Boolean): Boolean; virtual; procedure ApplyStates(Rule: TRuleCollectionItem); procedure SaveState; procedure RestoreState; public constructor Create(AOwner: TecSyntAnalyzer; ABuffer: TATStringBuffer; const AClient: IecSyntClient); virtual; destructor Destroy; override; procedure Clear; virtual; function AnalyzerAtPos(Pos: integer): TecSyntAnalyzer; function ParserStateAtPos(TokenIndex: integer): integer; property Owner: TecSyntAnalyzer read FOwner; property Buffer: TATStringBuffer read FBuffer; property IsFinished: Boolean read FFinished; property TagStr[Index: integer]: ecString read GetTokenStr; property TagCount: integer read GetTokenCount; property Tags[Index: integer]: TecSyntToken read GetTags write SetTags; default; property SubLexerRangeCount: integer read GetSubLexerRangeCount; property SubLexerRanges[Index: integer]: TecSubLexerRange read GetSubLexerRange; property ParserState: integer read FCurState write FCurState; //property TagIndexes[Index: integer]: TRangeListIndex read GetTagIndexes; end; { TecClientSyntAnalyzer } TecClientSyntAnalyzer = class(TecParserResults) private FRanges: TSortedList; FOpenedBlocks: TSortedList; // Opened ranges (without end) FTimerIdleMustStop: Boolean; FTimerIdleIsBusy: Boolean; FTimerIdle: TTimer; FStartSepRangeAnal: integer; FDisableIdleAppend: Boolean; FRepeateAnalysis: Boolean; function GetRangeCount: integer; function GetRanges(Index: integer): TecTextRange; function GetOpened(Index: integer): TecTextRange; function GetOpenedCount: integer; procedure SetDisableIdleAppend(const Value: Boolean); procedure DoStopTimer(AndWait: boolean); protected procedure AddRange(Range: TecTextRange); function HasOpened(Rule: TRuleCollectionItem; Parent: TecTagBlockCondition; Strict: Boolean): Boolean; function IsEnabled(Rule: TRuleCollectionItem; OnlyGlobal: Boolean): Boolean; override; procedure Finished; override; procedure TimerIdleTick(Sender: TObject); procedure CloseAtEnd(StartTagIdx: integer); override; public constructor Create(AOwner: TecSyntAnalyzer; SrcProc: TATStringBuffer; const AClient: IecSyntClient); override; destructor Destroy; override; procedure Clear; override; procedure ChangedAtPos(APos: integer); function PriorTokenAt(Pos: integer): integer; function RangeFormat(const FmtStr: ecString; Range: TecTextRange): ecString; function GetRangeName(Range: TecTextRange): ecString; function GetRangeGroup(Range: TecTextRange): ecString; function GetCollapsedText(Range: TecTextRange): ecString; procedure Stop; procedure TextChanged(Pos, Count: integer); procedure AppendToPos(APos: integer; AUseTimer: boolean= true); // Requires analyzed to APos procedure Analyze(ResetContent: Boolean = True); // Requires analyzed all text procedure IdleAppend; // Start idle analysis procedure CompleteAnalysis; function CloseRange(Cond: TecTagBlockCondition; RefTag: integer): Boolean; function DetectTag(Rule: TecTagBlockCondition; RefTag: integer): Boolean; property OpenCount: integer read GetOpenedCount; property Opened[Index: integer]: TecTextRange read GetOpened; property RangeCount: integer read GetRangeCount; property Ranges[Index: integer]: TecTextRange read GetRanges; property DisableIdleAppend: Boolean read FDisableIdleAppend write SetDisableIdleAppend; end; // ******************************************************************* // Syntax analizer // container of syntax rules // ******************************************************************* TLoadableComponent = class(TComponent) private FSkipNewName: Boolean; FFileName: string; FIgnoreAll: Boolean; FSaving: Boolean; protected procedure OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); virtual; function NotStored: Boolean; public procedure SaveToFile(const FileName: string); virtual; procedure SaveToStream(Stream: TStream); virtual; procedure LoadFromFile(const FileName: string); virtual; procedure LoadFromResourceID(Instance: Cardinal; ResID: Integer; ResType: string); virtual; procedure LoadFromResourceName(Instance: Cardinal; const ResName: string; ResType: string); virtual; procedure LoadFromStream(const Stream: TStream); virtual; protected procedure SetName(const NewName: TComponentName); override; property FileName: string read FFileName write LoadFromFile; end; TParseTokenEvent = procedure(Client: TecParserResults; const Text: ecString; Pos: integer; var TokenLength: integer; var Rule: TecTokenRule) of object; { TecSyntAnalyzer } TecSyntAnalyzer = class(TLoadableComponent) private FClientList: TList; FMasters: TList; // Master lexer, i.e. lexers that uses it FOnChange: TNotifyEvent; FSampleText: TStrings; FFormats: TecStylesCollection; FTokenRules: TecTokenRuleCollection; FBlockRules: TecBlockRuleCollection; FCodeTemplates: TecCodeTemplates; FExtentions: string; FLexerName: string; FCoping: Boolean; FSkipSpaces: Boolean; FSubAnalyzers: TecSubAnalyzerRules; FTokenTypeNames: TStrings; FFullRefreshSize: integer; FMarkedBlock: TecSyntaxFormat; FMarkedBlockName: string; FSearchMatch: TecSyntaxFormat; FSearchMatchName: string; FCurrentLine: TecSyntaxFormat; FCurrentLineName: string; FDefStyle: TecSyntaxFormat; FDefStyleName: string; FCollapseStyle: TecSyntaxFormat; FCollapseStyleName: string; FNotes: TStrings; FInternal: boolean; FRestartFromLineStart: Boolean; FParseEndOfLine: Boolean; FGrammaParser: TGrammaAnalyzer; FLineComment: ecString; FCharset: TFontCharSet; FSeparateBlocks: integer; FAlwaysSyncBlockAnal: Boolean; // Indicates that blocks analysis may after tokens FOnGetCollapseRange: TBoundDefEvent; FOnCloseTextRange: TBoundDefEvent; FIdleAppendDelayInit: Cardinal; FIdleAppendDelay: Cardinal; FOnParseToken: TParseTokenEvent; procedure SetSampleText(const Value: TStrings); procedure FormatsChanged(Sender: TCollection; Item: TSyntCollectionItem); procedure TokenRuleChanged(Sender: TCollection; Item: TSyntCollectionItem); procedure BlocksChanged(Sender: TCollection; Item: TSyntCollectionItem); procedure SubLexRuleChanged(Sender: TCollection; Item: TSyntCollectionItem); procedure SetBlockRules(const Value: TecBlockRuleCollection); procedure SetCodeTemplates(const Value: TecCodeTemplates); procedure SetTokenRules(const Value: TecTokenRuleCollection); procedure SetFormats(const Value: TecStylesCollection); function GetUniqueName(const Base: string): string; procedure SetSkipSpaces(const Value: Boolean); procedure SetSubAnalyzers(const Value: TecSubAnalyzerRules); procedure SetTokenTypeNames(const Value: TStrings); function GetStyleName(const AName: string; const AStyle: TecSyntaxFormat): string; procedure SetMarkedBlock(const Value: TecSyntaxFormat); function GetMarkedBlockName: string; procedure SetMarkedBlockName(const Value: string); procedure SetSearchMatch(const Value: TecSyntaxFormat); function GetSearchMatchStyle: string; procedure SetSearchMatchStyle(const Value: string); procedure SetCurrentLine(const Value: TecSyntaxFormat); function GetCurrentLineStyle: string; procedure SetCurrentLineStyle(const Value: string); procedure SetNotes(const Value: TStrings); procedure SetInternal(const Value: boolean); procedure SetRestartFromLineStart(const Value: Boolean); procedure SetParseEndOfLine(const Value: Boolean); procedure TokenNamesChanged(Sender: TObject); procedure CompileGramma; procedure SetGrammar(const Value: TGrammaAnalyzer); procedure GrammaChanged(Sender: TObject); procedure SetDefStyle(const Value: TecSyntaxFormat); function GetDefaultStyleName: string; procedure SetDefaultStyleName(const Value: string); procedure SetLineComment(const Value: ecString); procedure DetectBlockSeparate; procedure SetAlwaysSyncBlockAnal(const Value: Boolean); function GetCollapseStyleName: string; procedure SetCollapseStyleName(const Value: string); procedure SetCollapseStyle(const Value: TecSyntaxFormat); function GetSeparateBlocks: Boolean; protected function GetToken(Client: TecParserResults; const Source: ecString; APos: integer; OnlyGlobal: Boolean): TecSyntToken; virtual; procedure HighlightKeywords(Client: TecParserResults; const Source: ecString; OnlyGlobal: Boolean); virtual; procedure SelectTokenFormat(Client: TecParserResults; const Source: ecString; OnlyGlobal: Boolean; N: integer = -1); virtual; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Change; dynamic; property SeparateBlockAnalysis: Boolean read GetSeparateBlocks; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; //function AddClient(const Client: IecSyntClient; ABuffer: TATStringBuffer): TecClientSyntAnalyzer; procedure ClearClientContents; procedure UpdateClients; procedure AddMasterLexer(SyntAnal: TecSyntAnalyzer); procedure RemoveMasterLexer(SyntAnal: TecSyntAnalyzer); property MarkedBlock: TecSyntaxFormat read FMarkedBlock write SetMarkedBlock; property SearchMatch: TecSyntaxFormat read FSearchMatch write SetSearchMatch; property CurrentLine: TecSyntaxFormat read FCurrentLine write SetCurrentLine; property DefStyle: TecSyntaxFormat read FDefStyle write SetDefStyle; property CollapseStyle: TecSyntaxFormat read FCollapseStyle write SetCollapseStyle; published property Formats: TecStylesCollection read FFormats write SetFormats; property TokenRules: TecTokenRuleCollection read FTokenRules write SetTokenRules; property BlockRules: TecBlockRuleCollection read FBlockRules write SetBlockRules; property CodeTemplates: TecCodeTemplates read FCodeTemplates write SetCodeTemplates; property SubAnalyzers: TecSubAnalyzerRules read FSubAnalyzers write SetSubAnalyzers; property SampleText: TStrings read FSampleText write SetSampleText; property TokenTypeNames: TStrings read FTokenTypeNames write SetTokenTypeNames; property Gramma: TGrammaAnalyzer read FGrammaParser write SetGrammar; property MarkedBlockStyle: string read GetMarkedBlockName write SetMarkedBlockName; property SearchMatchStyle: string read GetSearchMatchStyle write SetSearchMatchStyle; property CurrentLineStyle: string read GetCurrentLineStyle write SetCurrentLineStyle; property DefaultStyleName: string read GetDefaultStyleName write SetDefaultStyleName; property CollapseStyleName: string read GetCollapseStyleName write SetCollapseStyleName; property Extentions: string read FExtentions write FExtentions; property LexerName: string read FLexerName write FLexerName; property SkipSpaces: Boolean read FSkipSpaces write SetSkipSpaces default True; property FullRefreshSize: integer read FFullRefreshSize write FFullRefreshSize default 0; property Notes: TStrings read FNotes write SetNotes; property Internal: boolean read FInternal write SetInternal default False; property RestartFromLineStart: Boolean read FRestartFromLineStart write SetRestartFromLineStart default False; property ParseEndOfLine: Boolean read FParseEndOfLine write SetParseEndOfLine default False; property LineComment: ecString read FLineComment write SetLineComment; property Charset: TFontCharSet read FCharset write FCharset; //AT property AlwaysSyncBlockAnal: Boolean read FAlwaysSyncBlockAnal write SetAlwaysSyncBlockAnal default False; property IdleAppendDelay: Cardinal read FIdleAppendDelay write FIdleAppendDelay default 200; property IdleAppendDelayInit: Cardinal read FIdleAppendDelayInit write FIdleAppendDelayInit default 50; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnGetCollapseRange: TBoundDefEvent read FOnGetCollapseRange write FOnGetCollapseRange; property OnCloseTextRange: TBoundDefEvent read FOnCloseTextRange write FOnCloseTextRange; property OnParseToken: TParseTokenEvent read FOnParseToken write FOnParseToken; end; TLibSyntAnalyzer = class(TecSyntAnalyzer) protected FParent: TecSyntaxManager; // function GetChildParent: TComponent; override; // procedure SetName(const NewName: TComponentName); override; procedure SetParentComponent(Value: TComponent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadFromStream(const Stream: TStream); override; function GetParentComponent: TComponent; override; function HasParent: Boolean; override; end; TecSyntaxManager = class(TLoadableComponent) private FOnChange: TNotifyEvent; FList: TList; FCurrentLexer: TecSyntAnalyzer; FOnLexerChanged: TNotifyEvent; FModified: Boolean; function GeItem(Index: integer): TecSyntAnalyzer; function GetCount: integer; procedure SetCurrentLexer(const Value: TecSyntAnalyzer); protected procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Changed; dynamic; procedure OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadFromFile(const FileName: string); override; procedure SaveToFile(const FileName: string); override; function FindAnalyzer(const LexerName: string): TecSyntAnalyzer; function AddAnalyzer: TecSyntAnalyzer; procedure Clear; procedure Move(CurIndex, NewIndex: Integer); property AnalyzerCount: integer read GetCount; property Analyzers[Index: integer]: TecSyntAnalyzer read GeItem; property FileName; property CurrentLexer: TecSyntAnalyzer read FCurrentLexer write SetCurrentLexer; property Modified: Boolean read FModified write FModified; published property OnLexerChanged: TNotifyEvent read FOnLexerChanged write FOnLexerChanged stored NotStored; property OnChange: TNotifyEvent read FOnChange write FOnChange stored NotStored; end; TecSyntStyles = class(TLoadableComponent) private FStyles: TecStylesCollection; procedure SetStyles(const Value: TecStylesCollection); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Styles: TecStylesCollection read FStyles write SetStyles; end; implementation uses SysUtils, Forms, Dialogs, Math; const SecDefaultTokenTypeNames = 'Unknown' + #13#10 + 'Comment' + #13#10 + 'Id' + #13#10 + 'Symbol' + #13#10 + 'String' + #13#10 + 'Number' + #13#10 + 'Preprocessor'; //local copy of ecUpCase. it is faster, uses AnsiChar UpCase. function ecUpCase(ch: WideChar): char; begin Result:= system.UpCase(char(ch)); end; procedure SetDefaultModifiers(RE: TecRegExpr); begin RE.ModifierI := True; RE.ModifierG := True; RE.ModifierS := False; RE.ModifierM := True; RE.ModifierX := True; RE.ModifierR := False; end; { TecSubLexerRange } class operator TecSubLexerRange.=(const a, b: TecSubLexerRange): boolean; begin Result := false; end; { TecSyntToken } constructor TecSyntToken.Create(ARule: TRuleCollectionItem; AStartPos, AEndPos: integer; const APointStart, APointEnd: TPoint); begin Range:= TRange.Create(AStartPos, AEndPos, APointStart, APointEnd); Rule := ARule; if Assigned(ARule) then TokenType := TecTokenRule(ARule).TokenType; end; function TecSyntToken.GetStr(const Source: ecString): ecString; begin with Range do Result := Copy(Source, StartPos + 1, EndPos - StartPos); end; class operator TecSyntToken.=(const A, B: TecSyntToken): boolean; begin Result:= (A.Range=B.Range) and (A.Rule=B.Rule); end; function TecSyntToken.GetStyle: TecSyntaxFormat; begin if Rule = nil then Result := nil else Result := Rule.Style; end; { TecTextRange } constructor TecTextRange.Create(AStartIdx, AStartPos: integer); begin inherited Create; StartIdx := AStartIdx; StartPos := AStartPos; EndIdx := -1; FEndCondIndex := -1; Index := -1; end; function TecTextRange.GetIsClosed: Boolean; begin Result := EndIdx <> -1; end; function TecTextRange.GetKey: integer; begin Result := StartPos; end; function TecTextRange.GetLevel: integer; var prn: TecTextRange; begin prn := Parent; Result := 0; while prn <> nil do begin inc(Result); prn := prn.Parent; end; end; { TSyntCollectionItem } procedure TSyntCollectionItem.AssignTo(Dest: TPersistent); begin if Dest is TSyntCollectionItem then begin (Dest as TSyntCollectionItem).DisplayName := DisplayName; (Dest as TSyntCollectionItem).Enabled := Enabled; end; end; constructor TSyntCollectionItem.Create(Collection: TCollection); var NewName: string; n: integer; begin inherited; FEnabled := True; if Collection = nil then Exit; n := 1; repeat NewName := GetItemBaseName + ' ' + IntToStr(n); inc(n); until TSyntCollection(Collection).ItemByName(NewName) = nil; FName := NewName; end; function TSyntCollectionItem.GetDisplayName: string; begin Result := FName; end; function TSyntCollectionItem.GetIsInvalid: Boolean; begin Result := False; end; function TSyntCollectionItem.GetItemBaseName: string; begin Result := 'Item'; end; procedure TSyntCollectionItem.Loaded; begin end; procedure TSyntCollectionItem.SetDisplayName(const Value: string); var i: integer; begin if Collection <> nil then for i := 0 to Collection.Count - 1 do if Collection.Items[i] <> Self then if Collection.Items[i].DisplayName = Value then Exit; FName := Value; end; procedure TSyntCollectionItem.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; Changed(False); end; end; { TSyntCollection } constructor TSyntCollection.Create(ItemClass: TCollectionItemClass); begin if not ItemClass.InheritsFrom(TSyntCollectionItem) then raise Exception.Create('Allow only TSyntCollectionItem Class'); inherited; end; function TSyntCollection.GetItems(Index: integer): TSyntCollectionItem; begin Result := (inherited Items[Index]) as TSyntCollectionItem; end; function TSyntCollection.GetOwner: TPersistent; begin Result := FSyntOwner; end; function TSyntCollection.GetUniqueName(const Base: string): string; var n: integer; begin Result := Base; n := 0; while ItemByName(Result) <> nil do begin Inc(n); Result := Base + IntToStr(n); end; end; function TSyntCollection.ItemByName(const AName: string): TSyntCollectionItem; var i: integer; begin for i := 0 to Count - 1 do if Items[i].DisplayName = AName then begin Result := Items[i] as TSyntCollectionItem; Exit; end; Result := nil; end; procedure TSyntCollection.Loaded; var i: integer; begin for i := 0 to Count - 1 do Items[i].Loaded; end; procedure TSyntCollection.Update(Item: TCollectionItem); begin inherited; if Assigned(FOnChange) then FOnChange(Self, TSyntCollectionItem(Item)); end; function TSyntCollection.ValidItem(Item: TSyntCollectionItem): Boolean; var i: integer; begin Result := True; if Item <> nil then for i := 0 to Count - 1 do if Items[i] = Item then Exit; Result := False; end; { TecSyntaxFormat } constructor TecSyntaxFormat.Create(Collection: TCollection); var i: integer; begin FIsBlock := False; FFont := TFont.Create; FFont.Name := 'Courier New'; FFont.Size := 10; FBgColor := clNone; FVertAlign := vaCenter; FFormatType := ftFontAttr; for i := 0 to 3 do begin FBorderTypes[i] := blNone; FBorderColors[i] := clBlack; end; FFormatFlags := [ffBold, ffItalic, ffUnderline, ffStrikeOut, ffReadOnly, ffHidden, ffFontName, ffFontSize, ffFontCharset, ffVertAlign]; inherited; FFont.OnChange := FontChanged; end; destructor TecSyntaxFormat.Destroy; begin FreeAndNil(FFont); inherited; end; procedure TecSyntaxFormat.AssignTo(Dest: TPersistent); var i: integer; begin inherited; if Dest is TecSyntaxFormat then with Dest as TecSyntaxFormat do begin FBgColor := Self.BgColor; FFont.Assign(Self.Font); FVertAlign := Self.FVertAlign; FIsBlock := Self.FIsBlock; FFormatType := Self.FFormatType; Hidden := Self.Hidden; ReadOnly := Self.ReadOnly; MultiLineBorder := Self.MultiLineBorder; FChangeCase := Self.ChangeCase; for i := 0 to 3 do begin FBorderTypes[i] := Self.FBorderTypes[i]; FBorderColors[i] := Self.FBorderColors[i]; end; FFormatFlags := Self.FFormatFlags; end; end; procedure TecSyntaxFormat.SetBgColor(const Value: TColor); begin FBgColor := Value; Change; end; procedure TecSyntaxFormat.SetFont(const Value: TFont); begin FFont.Assign(Value); Change; end; procedure TecSyntaxFormat.FontChanged(Sender: TObject); begin Change; end; procedure TecSyntaxFormat.SetVertAlign(const Value: TecVertAlignment); begin FVertAlign := Value; Change; end; function TecSyntaxFormat.GetItemBaseName: string; begin Result := 'Style'; end; procedure TecSyntaxFormat.SetFormatType(const Value: TecFormatType); begin FFormatType := Value; Change; end; procedure TecSyntaxFormat.Change; begin Changed(False); if Assigned(FOnChange) then FOnChange(Self); end; procedure TecSyntaxFormat.SetHidden(const Value: Boolean); begin FHidden := Value; Change; end; function TecSyntaxFormat.GetBorderColor(Index: Integer): TColor; begin if (Index >= 0) and (Index <= 3) then Result := FBorderColors[Index] else Result := clBlack; end; function TecSyntaxFormat.GetBorderType(Index: Integer): TecBorderLineType; begin if (Index >= 0) and (Index <= 3) then Result := FBorderTypes[Index] else Result := blNone; end; procedure TecSyntaxFormat.SetBorderColor(Index: Integer; const Value: TColor); begin if (Index >= 0) and (Index <= 3) then begin FBorderColors[Index] := Value; Change; end; end; procedure TecSyntaxFormat.SetBorderType(Index: Integer; const Value: TecBorderLineType); begin if (Index >= 0) and (Index <= 3) then begin FBorderTypes[Index] := Value; Change; end; end; procedure TecSyntaxFormat.SetMultiLineBorder(const Value: Boolean); begin FMultiLineBorder := Value; Change; end; procedure TecSyntaxFormat.SetReadOnly(const Value: Boolean); begin FReadOnly := Value; Change; end; procedure TecSyntaxFormat.SetChangeCase(const Value: TecChangeCase); begin FChangeCase := Value; Change; end; function TecSyntaxFormat.HasBorder: Boolean; var i: integer; begin for i := 0 to 3 do if FBorderTypes[i] <> blNone then begin Result := True; Exit; end; Result := False; end; procedure TecSyntaxFormat.SetFormatFlags(const Value: TecFormatFlags); begin if FFormatFlags <> Value then begin FFormatFlags := Value; Change; end; end; procedure TecSyntaxFormat.ApplyTo(Canvas: TCanvas; AllowChangeFont: Boolean); var fs: TFontStyles; procedure SwitchFontFlag(ff: TecFormatFlag; f: TFontStyle); begin if ff in FormatFlags then if f in Font.Style then Include(fs, f) else Exclude(fs, f); end; begin if not Enabled then Exit; if BgColor <> clNone then Canvas.Brush.Color := BgColor; if FormatType = ftBackGround then Exit else begin if Font.Color <> clNone then Canvas.Font.Color := Font.Color; if FormatType <> ftColor then begin fs := Canvas.Font.Style; SwitchFontFlag(ffBold, fsBold); SwitchFontFlag(ffItalic, fsItalic); SwitchFontFlag(ffUnderline, fsUnderline); SwitchFontFlag(ffStrikeOut, fsStrikeOut); if Canvas.Font.Style <> fs then Canvas.Font.Style := fs; if (FormatType = ftCustomFont) and AllowChangeFont then begin if ffFontName in FormatFlags then Canvas.Font.Name := Font.Name; if ffFontCharset in FormatFlags then Canvas.Font.Charset := Font.Charset; if ffFontSize in FormatFlags then Canvas.Font.Size := Font.Size; end; end; end; end; function TecSyntaxFormat.IsEqual(Other: TecSyntaxFormat): Boolean; begin Result := (BgColor = Other.BgColor) and (FormatType = Other.FormatType) and (FormatFlags = Other.FormatFlags) and (Hidden = Other.Hidden) and (ReadOnly = Other.ReadOnly) and (ChangeCase = Other.ChangeCase) and (VertAlignment = Other.VertAlignment); if Result and (FormatType <> ftBackGround) then begin Result := Font.Color = Other.Font.Color; if Result and (FormatType <> ftColor) then begin Result := Font.Style = Other.Font.Style; if Result and (FormatType <> ftFontAttr) then begin Result := (not (ffFontName in FormatFlags) or (Font.Name = Other.Font.Name)) and (not (ffFontSize in FormatFlags) or (Font.Size = Other.Font.Size)) and (not (ffFontCharSet in FormatFlags) or (Font.Charset = Other.Font.Charset)); end; end; end; end; procedure TecSyntaxFormat.Merge(Over: TecSyntaxFormat); var fs: TFontStyles; procedure SwitchFontFlag(ff: TecFormatFlag; f: TFontStyle); begin if ff in Over.FormatFlags then begin Include(FFormatFlags, ff); if f in Over.Font.Style then Include(fs, f) else Exclude(fs, f); end; end; begin if ffVertAlign in Over.FormatFlags then VertAlignment := Over.VertAlignment; if ffHidden in Over.FormatFlags then Hidden := Over.Hidden; if ffReadOnly in Over.FormatFlags then ReadOnly := Over.ReadOnly; if Over.BgColor <> clNone then BgColor := Over.BgColor; if Over.ChangeCase <> ccNone then ChangeCase := Over.ChangeCase; if Over.FormatType <> ftBackGround then begin if Over.Font.Color <> clNone then Font.Color := Over.Font.Color; if Over.FormatType <> ftColor then begin fs := Font.Style; SwitchFontFlag(ffBold, fsBold); SwitchFontFlag(ffItalic, fsItalic); SwitchFontFlag(ffUnderline, fsUnderline); SwitchFontFlag(ffStrikeOut, fsStrikeOut); Font.Style := fs; if Over.FormatType <> ftFontAttr then begin if ffFontName in Over.FormatFlags then Font.Name := Over.Font.Name; if ffFontCharset in Over.FormatFlags then Font.Charset := Over.Font.Charset; if ffFontSize in Over.FormatFlags then Font.Size := Over.Font.Size; end; end; end; FormatFlags := FormatFlags + Over.FormatFlags; end; function TecSyntaxFormat.GetHidden: Boolean; begin Result := FHidden and (ffHidden in FFormatFlags); end; procedure TecSyntaxFormat.Intersect(Over: TecSyntaxFormat); begin FormatFlags := Over.FormatFlags * FormatFlags; if Over.FormatType < FormatType then FormatType := Over.FormatType; if (ffVertAlign in FormatFlags) and (VertAlignment <> Over.VertAlignment) then FormatFlags := FormatFlags - [ffVertAlign]; if (ffReadOnly in FormatFlags) and (ReadOnly <> Over.ReadOnly) then FormatFlags := FormatFlags - [ffReadOnly]; if (ffHidden in FormatFlags) and (Hidden <> Over.Hidden) then FormatFlags := FormatFlags - [ffHidden]; if Over.ChangeCase <> ChangeCase then ChangeCase := ccNone; if BgColor <> Over.BgColor then BgColor := clNone; if FormatType = ftBackGround then Exit; if Font.Color <> Over.Font.Color then Font.Color := clNone; if FormatType = ftColor then Exit; if (ffBold in FormatFlags) and ((fsBold in Font.Style) <> (fsBold in Over.Font.Style)) then FormatFlags := FormatFlags - [ffBold]; if (ffItalic in FormatFlags) and ((fsItalic in Font.Style) <> (fsItalic in Over.Font.Style)) then FormatFlags := FormatFlags - [ffItalic]; if (ffUnderline in FormatFlags) and ((fsUnderline in Font.Style) <> (fsUnderline in Over.Font.Style)) then FormatFlags := FormatFlags - [ffUnderline]; if (ffStrikeOut in FormatFlags) and ((fsStrikeOut in Font.Style) <> (fsStrikeOut in Over.Font.Style)) then FormatFlags := FormatFlags - [ffStrikeOut]; if FormatType = ftFontAttr then Exit; if (ffFontName in FormatFlags) and (not SameText(Font.Name, Over.Font.Name)) then FormatFlags := FormatFlags - [ffFontName]; if (ffFontSize in FormatFlags) and (Font.Size <> Over.Font.Size) then FormatFlags := FormatFlags - [ffFontSize]; if (ffFontCharset in FormatFlags) and (Font.Charset <> Over.Font.Charset) then FormatFlags := FormatFlags - [ffFontCharset]; end; { TecStylesCollection } function TecStylesCollection.Add: TecSyntaxFormat; begin Result := (inherited Add) as TecSyntaxFormat; end; constructor TecStylesCollection.Create; begin inherited Create(TecSyntaxFormat); end; function TecStylesCollection.GetItem(Index: integer): TecSyntaxFormat; begin Result := (inherited Items[Index]) as TecSyntaxFormat; end; function TecStylesCollection.Synchronize(Source: TecStylesCollection): integer; var j: integer; f: TecSyntaxFormat; begin Result := 0; for j := 0 to Count - 1 do begin f := TecSyntaxFormat(Source.ItemByName(Items[j].DisplayName)); if f <> nil then begin Inc(Result); Items[j].Assign(f); end; end; end; { TecSingleTagCondition } procedure TecSingleTagCondition.AssignTo(Dest: TPersistent); var dst: TecSingleTagCondition; begin if Dest is TecSingleTagCondition then begin dst := Dest as TecSingleTagCondition; dst.CondType := CondType; dst.TokenTypes := TokenTypes; dst.FTagList.Assign(FTagList); dst.IgnoreCase := IgnoreCase; end; end; function TecSingleTagCondition.CheckToken(const Source: ecString; const Token: TecSyntToken): Boolean; var s: ecString; i, N: integer; RE: TecRegExpr; begin Result := False; if FTokenTypes <> 0 then begin Result := ((1 shl Token.TokenType) and FTokenTypes) <> 0; if FCondType = tcSkip then Exit; if not Result then case FCondType of tcStrictMask, tcMask, tcEqual: Exit; tcNotEqual: begin Result := True; Exit; end; end; end; if FTagList.Count > 0 then begin s := Token.GetStr(Source); s := Trim(s); //AT if FCondType in [tcMask, tcStrictMask] then begin RE := TecRegExpr.Create; SetDefaultModifiers(RE); try for i := 0 to FTagList.Count - 1 do begin RE.Expression := FTagList[i]; if FCondType = tcMask then Result := RE.MatchLength(s, 1) > 0 else begin N := 1; Result := RE.Match(s, N); if Result then Result := N > Length(S); end; if Result then break; end; except end; FreeAndNil(RE); end else begin Result := FTagList.IndexOf(s) <> -1; if FCondType = tcNotEqual then Result := not Result; end; end else Result := FCondType <> tcNotEqual; end; constructor TecSingleTagCondition.Create(Collection: TCollection); begin inherited; FCondType := tcEqual; FTagList := TStringList.Create; TStringList(FTagList).Sorted := true; TStringList(FTagList).Delimiter := ' '; TStringList(FTagList).Duplicates := dupIgnore; TStringList(FTagList).CaseSensitive := True; TStringList(FTagList).OnChange := TagListChanged; TStringList(FTagList).QuoteChar := ' '; end; destructor TecSingleTagCondition.Destroy; begin FreeAndNil(FTagList); inherited; end; procedure TecSingleTagCondition.SetIgnoreCase(const Value: Boolean); begin TStringList(FTagList).CaseSensitive := not Value; end; function TecSingleTagCondition.GetIgnoreCase: Boolean; begin Result := not TStringList(FTagList).CaseSensitive; end; procedure TecSingleTagCondition.SetTagList(const Value: TStrings); begin TStringList(FTagList).DelimitedText := Value.Text; Changed(False); end; procedure TecSingleTagCondition.SetTokenTypes(const Value: DWORD); begin FTokenTypes := Value; Changed(False); end; procedure TecSingleTagCondition.SetCondType(const Value: TecTagConditionType); begin FCondType := Value; Changed(False); end; procedure TecSingleTagCondition.TagListChanged(Sender: TObject); begin Changed(False); end; { TecConditionCollection } function TecConditionCollection.Add: TecSingleTagCondition; begin Result := (inherited Add) as TecSingleTagCondition; end; constructor TecConditionCollection.Create(AOwner: TecTagBlockCondition); begin inherited Create(TecSingleTagCondition); FOwner := AOwner; PropName := 'Conditions'; end; function TecConditionCollection.GetItem(Index: integer): TecSingleTagCondition; begin Result := (inherited Items[Index]) as TecSingleTagCondition; end; function TecConditionCollection.GetOwner: TPersistent; begin Result := FOwner; end; procedure TecConditionCollection.Update(Item: TCollectionItem); begin inherited; if Assigned(FOnChange) then FOnChange(Self); end; { TecTagBlockCondition } constructor TecTagBlockCondition.Create(Collection: TCollection); begin inherited; FConditions := TecConditionCollection.Create(Self); FConditions.OnChange := ConditionsChanged; FBlockType := btRangeStart; FLinePos := lbTop; FDisplayInTree := True; // FHighlightPos := cpBound; FTokenType := -1; FTreeItemImage := -1; FTreeGroupImage := -1; FPen := TPen.Create; FPen.OnChange := ConditionsChanged; end; procedure TecTagBlockCondition.AssignTo(Dest: TPersistent); var dst: TecTagBlockCondition; begin inherited; if Dest is TecTagBlockCondition then begin dst := Dest as TecTagBlockCondition; dst.ConditionList := ConditionList; dst.FIdentIndex := IdentIndex; dst.FLinePos := LinePos; dst.FBlockOffset := BlockOffset; dst.FBlockType := BlockType; dst.BlockEnd := BlockEnd; dst.FEndOfTextClose := FEndOfTextClose; dst.FNotCollapsed := FNotCollapsed; dst.FSameIdent := FSameIdent; dst.Highlight := Highlight; dst.InvertColors := InvertColors; dst.DisplayInTree := DisplayInTree; dst.NameFmt := NameFmt; dst.GroupFmt := GroupFmt; dst.RefToCondEnd := RefToCondEnd; dst.DynHighlight := DynHighlight; dst.HighlightPos := HighlightPos; dst.DynSelectMin := DynSelectMin; dst.CancelNextRules := CancelNextRules; dst.DrawStaple := DrawStaple; dst.GroupIndex := GroupIndex; dst.OnBlockCheck := OnBlockCheck; dst.CollapseFmt := CollapseFmt; dst.FSelfClose := SelfClose; dst.FNoEndRule := NoEndRule; dst.GrammaRuleName := GrammaRuleName; dst.TokenType := TokenType; dst.TreeItemStyle := TreeItemStyle; dst.TreeGroupStyle := TreeGroupStyle; dst.TreeItemImage := TreeItemImage; dst.TreeGroupImage := TreeGroupImage; dst.Pen := Pen; dst.UseCustomPen := UseCustomPen; dst.IgnoreAsParent := IgnoreAsParent; dst.AutoCloseText := AutoCloseText; dst.AutoCloseMode := AutoCloseMode; end; end; function TecTagBlockCondition.Check(const Source: ecString; Tags: TecClientSyntAnalyzer; N: integer; var RefIdx: integer): Boolean; var i, offs, idx, skipped, skip_cond: integer; begin Result := False; offs := CheckOffset; skipped := 0; skip_cond := 0; i := 0; while i < ConditionList.Count do begin idx := N - 1 - i - offs - skipped + skip_cond; if (ConditionList[i].CondType = tcSkip) and (i < ConditionList.Count - 1) and (ConditionList[i+1].CondType <> tcSkip) then begin inc(i); inc(skip_cond); while (idx >= 0) and not ConditionList[i].CheckToken(Source, Tags[idx]) do begin if not ConditionList[i - 1].CheckToken(Source, Tags[idx]) then Exit; dec(idx); inc(skipped); end; if idx < 0 then Exit; end; with ConditionList[i] do if (idx < 0) or not CheckToken(Source, Tags[idx]) then Exit; inc(i); end; Result := ConditionList.Count > 0; // if FRefToCondEnd then RefIdx := N - ConditionList.Count - offs - skipped + skip_cond; // else // RefIdx := N - 1 - offs; end; destructor TecTagBlockCondition.Destroy; begin FreeAndNil(FConditions); FreeAndNil(FPen); inherited; end; function TecTagBlockCondition.GetItemBaseName: string; begin Result := 'Tag block rule'; end; function TecTagBlockCondition.GetBlockEndName: string; var FSynt: TecSyntAnalyzer; begin FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if csLoading in FSynt.ComponentState then Result := FBlockEndName else if Assigned(FBlockEndCond) then Result := FBlockEndCond.DisplayName else Result := ''; end; procedure TecTagBlockCondition.SetBlockEndName(const Value: string); var FSynt: TecSyntAnalyzer; begin FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if csLoading in FSynt.ComponentState then FBlockEndName := Value else FBlockEndCond := TecTagBlockCondition(TecBlockRuleCollection(Collection).ItemByName(Value)); Changed(False); end; procedure TecTagBlockCondition.Loaded; var FSynt: TecSyntAnalyzer; begin inherited; FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if FBlockEndName <> '' then FBlockEndCond := TecTagBlockCondition(FSynt.FBlockRules.ItemByName(FBlockEndName)); if FTreeItemStyle <> '' then FTreeItemStyleObj := TecSyntaxFormat(FSynt.Formats.ItemByName(FTreeItemStyle)); if FTreeGroupStyle <> '' then FTreeGroupStyleObj := TecSyntaxFormat(FSynt.Formats.ItemByName(FTreeGroupStyle)); end; function TecTagBlockCondition.CheckOffset: integer; begin Result := 0; if FRefToCondEnd then Exit; if FIdentIndex < 0 then Result := -FIdentIndex; if (FBlockOffset < 0) and (FBlockOffset < FIdentIndex) then Result := -FBlockOffset; end; procedure TecTagBlockCondition.SetBlockType(const Value: TecTagBlockType); begin FBlockType := Value; if FBlockType in [btTagDetect, btLineBreak] then begin FBlockOffset := 0; FBlockEndCond := nil; end; Changed(False); end; procedure TecTagBlockCondition.SetConditions( const Value: TecConditionCollection); begin FConditions.Assign(Value); end; procedure TecTagBlockCondition.ConditionsChanged(Sender: TObject); begin Changed(False); end; procedure TecTagBlockCondition.SetBlockEndCond( const Value: TecTagBlockCondition); begin if FBlockEndCond <> Value then begin FBlockEndCond := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetLinePos(const Value: TecLineBreakPos); begin if FLinePos <> Value then begin FLinePos := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetIdentIndex(const Value: integer); begin if FIdentIndex <> Value then begin FIdentIndex := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetBlockOffset(const Value: integer); begin if FBlockOffset <> Value then begin FBlockOffset := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetEndOfTextClose(const Value: Boolean); begin if FEndOfTextClose <> Value then begin FEndOfTextClose := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetNotCollapsed(const Value: Boolean); begin if FNotCollapsed <> Value then begin FNotCollapsed := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetSameIdent(const Value: Boolean); begin if FSameIdent <> Value then begin FSameIdent := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetHighlight(const Value: Boolean); begin if FHighlight <> Value then begin FHighlight := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetInvertColors(const Value: Boolean); begin if FInvertColors <> Value then begin FInvertColors := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetDisplayInTree(const Value: Boolean); begin if FDisplayInTree <> Value then begin FDisplayInTree := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetCancelNextRules(const Value: Boolean); begin if FCancelNextRules <> Value then begin FCancelNextRules := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetDynHighlight( const Value: TecDynamicHighlight); begin if FDynHighlight <> Value then begin FDynHighlight := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetDynSelectMin(const Value: Boolean); begin if FDynSelectMin <> Value then begin FDynSelectMin := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetGroupFmt(const Value: ecString); begin if FGroupFmt <> Value then begin FGroupFmt := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetHighlightPos(const Value: TecHighlightPos); begin if FHighlightPos <> Value then begin FHighlightPos := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetNameFmt(const Value: ecString); begin if FNameFmt <> Value then begin FNameFmt := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetRefToCondEnd(const Value: Boolean); begin if FRefToCondEnd <> Value then begin FRefToCondEnd := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetDrawStaple(const Value: Boolean); begin if FDrawStaple <> Value then begin FDrawStaple := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetCollapseFmt(const Value: ecString); begin if FCollapseFmt <> Value then begin FCollapseFmt := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetSelfClose(const Value: Boolean); begin if FSelfClose <> Value then begin FSelfClose := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetNoEndRule(const Value: Boolean); begin if FNoEndRule <> Value then begin FNoEndRule := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetGrammaRuleName(const Value: string); begin if FGrammaRuleName <> Value then begin FGrammaRuleName := Value; FGrammaRule := TSyntCollection(Collection).SyntOwner.Gramma.ParserRuleByName(Value); end; end; procedure TecTagBlockCondition.SetTokenType(const Value: integer); begin if FTokenType <> Value then begin FTokenType := Value; Changed(False); end; end; function TecTagBlockCondition.GetTreeItemStyle: string; begin Result := ValidStyleName(FTreeItemStyle, FTreeItemStyleObj); end; procedure TecTagBlockCondition.SetTreeItemStyle(const Value: string); begin ValidSetStyle(Value, FTreeItemStyle, FTreeItemStyleObj); end; function TecTagBlockCondition.GetTreeGroupStyle: string; begin Result := ValidStyleName(FTreeGroupStyle, FTreeGroupStyleObj); end; procedure TecTagBlockCondition.SetTreeGroupStyle(const Value: string); begin ValidSetStyle(Value, FTreeGroupStyle, FTreeGroupStyleObj); end; procedure TecTagBlockCondition.SetTreeGroupImage(const Value: integer); begin if FTreeGroupImage <> Value then begin FTreeGroupImage := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetTreeItemImage(const Value: integer); begin if FTreeItemImage <> Value then begin FTreeItemImage := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetPen(const Value: TPen); begin FPen.Assign(Value); end; procedure TecTagBlockCondition.SetUseCustomPen(const Value: Boolean); begin if FUseCustomPen <> Value then begin FUseCustomPen := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetIgnoreAsParent(const Value: Boolean); begin if FIgnoreAsParent <> Value then begin FIgnoreAsParent := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetAutoCloseText(Value: ecString); begin if Value = sLineBreak then Value := ''; if FAutoCloseText <> Value then begin FAutoCloseText := Value; Changed(False); end; end; procedure TecTagBlockCondition.SetAutoCloseMode(const Value: TecAutoCloseMode); begin if FAutoCloseMode <> Value then begin FAutoCloseMode := Value; Changed(False); end; end; { TecBlockRuleCollection } function TecBlockRuleCollection.Add: TecTagBlockCondition; begin Result := inherited Add as TecTagBlockCondition; end; constructor TecBlockRuleCollection.Create; begin inherited Create(TecTagBlockCondition); end; function TecBlockRuleCollection.GetItem(Index: integer): TecTagBlockCondition; begin Result := inherited Items[Index] as TecTagBlockCondition; end; { TecTokenRule } procedure TecTokenRule.AssignTo(Dest: TPersistent); var dst: TecTokenRule; begin inherited; if Dest is TecTokenRule then begin dst := Dest as TecTokenRule; dst.FTokenType := FTokenType; dst.FRegExpr.Expression := Expression; dst.OnMatchToken := OnMatchToken; dst.ColumnFrom := ColumnFrom; dst.ColumnTo := ColumnTo; end; end; constructor TecTokenRule.Create(Collection: TCollection); begin inherited; FBlock := nil; FFormat := nil; FRegExpr := TecRegExpr.Create; SetDefaultModifiers(FRegExpr); end; destructor TecTokenRule.Destroy; begin FreeAndNil(FRegExpr); inherited; end; function TecTokenRule.GetExpression: ecString; begin Result := FRegExpr.Expression; end; function TecTokenRule.GetIsInvalid: Boolean; begin Result := FRegExpr.IsInvalid; end; function TecTokenRule.GetItemBaseName: string; begin Result := 'Token rule'; end; function TecTokenRule.Match(const Source: ecString; Pos: integer): integer; begin try Result := FRegExpr.MatchLength(Source, Pos); except Result := 0; end; end; procedure TecTokenRule.SetColumnFrom(const Value: integer); begin if FColumnFrom <> Value then begin FColumnFrom := Value; Changed(False); end; end; procedure TecTokenRule.SetColumnTo(const Value: integer); begin if FColumnTo <> Value then begin FColumnTo := Value; Changed(False); end; end; procedure TecTokenRule.SetExpression(const Value: ecString); begin try FRegExpr.Expression := Value; except Application.HandleException(Self); end; Changed(False); end; procedure TecTokenRule.SetTokenType(const Value: integer); begin if FTokenType <> Value then begin FTokenType := Value; Changed(False); end; end; { TRuleCollectionItem } function TRuleCollectionItem.ValidStyleName(const AStyleName: string; AStyle: TecSyntaxFormat): string; var FSynt: TecSyntAnalyzer; begin FSynt := TSyntCollection(Collection).SyntOwner; Result := ''; if not Assigned(FSynt) then Exit; if csLoading in FSynt.ComponentState then Result := AStyleName else if Assigned(AStyle) then Result := AStyle.DisplayName; end; function TRuleCollectionItem.ValidSetStyle(const AStyleName: string; var AStyleField: string; var AStyle: TecSyntaxFormat): string; var FSynt: TecSyntAnalyzer; begin Result := ''; FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if csLoading in FSynt.ComponentState then AStyleField := AStyleName else AStyle := TecSyntaxFormat(FSynt.FFormats.ItemByName(AStyleName)); Changed(False); end; function TRuleCollectionItem.GetStyleName: string; begin Result := ValidStyleName(FStyleName, FFormat); end; procedure TRuleCollectionItem.SetStyleName(const Value: string); begin ValidSetStyle(Value, FStyleName, FFormat); end; procedure TRuleCollectionItem.Loaded; var FSynt: TecSyntAnalyzer; begin FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if FStyleName <> '' then FFormat := TecSyntaxFormat(FSynt.FFormats.ItemByName(FStyleName)); if FBlockName <> '' then FBlock := TecTagBlockCondition(FSynt.BlockRules.ItemByName(FBlockName)); end; function TRuleCollectionItem.GetBlockName: string; var FSynt: TecSyntAnalyzer; begin FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if csLoading in FSynt.ComponentState then Result := FBlockName else if Assigned(FBlock) then Result := FBlock.DisplayName else Result := ''; end; procedure TRuleCollectionItem.SetBlockName(const Value: string); var FSynt: TecSyntAnalyzer; begin FSynt := TSyntCollection(Collection).SyntOwner; if not Assigned(FSynt) then Exit; if csLoading in FSynt.ComponentState then FBlockName := Value else begin // FBlock := TecTagBlockCondition(FSynt.BlockRules.ItemByName(Value)); FBlock := TecTagBlockCondition(FSynt.BlockRules.ItemByName(Value)); Changed(False); end; end; procedure TRuleCollectionItem.AssignTo(Dest: TPersistent); var dst: TRuleCollectionItem; begin inherited; if Dest is TRuleCollectionItem then begin dst := Dest as TRuleCollectionItem; dst.StyleName := StyleName; dst.BlockName := BlockName; dst.StrictParent := StrictParent; dst.NotParent := NotParent; dst.AlwaysEnabled := AlwaysEnabled; dst.StatesAbsent := StatesAbsent; dst.StatesAdd := StatesAdd; dst.StatesRemove := StatesRemove; dst.StatesPresent := StatesPresent; end; end; procedure TRuleCollectionItem.SetNotParent(const Value: Boolean); begin if FNotParent <> Value then begin FNotParent := Value; Changed(False); end; end; procedure TRuleCollectionItem.SetStrictParent(const Value: Boolean); begin if FStrictParent <> Value then begin FStrictParent := Value; Changed(False); end; end; procedure TRuleCollectionItem.SetAlwaysEnabled(const Value: Boolean); begin if FAlwaysEnabled <> Value then begin FAlwaysEnabled := Value; Changed(False); end; end; function TRuleCollectionItem.GetSyntOwner: TecSyntAnalyzer; begin Result := TSyntCollection(Collection).SyntOwner; end; procedure TRuleCollectionItem.SetStatesAdd(const Value: integer); begin if FStatesAdd <> Value then begin FStatesAdd := Value; Changed(False); end; end; procedure TRuleCollectionItem.SetStatesAbsent(const Value: integer); begin if FStatesAbsent <> Value then begin FStatesAbsent := Value; Changed(False); end; end; procedure TRuleCollectionItem.SetStatesRemove(const Value: integer); begin if FStatesRemove <> Value then begin FStatesRemove := Value; Changed(False); end; end; procedure TRuleCollectionItem.SetStatesPresent(const Value: integer); begin if FStatesPresent <> Value then begin FStatesPresent := Value; Changed(False); end; end; { TecTokenRuleCollection } function TecTokenRuleCollection.Add: TecTokenRule; begin Result := inherited Add as TecTokenRule; end; constructor TecTokenRuleCollection.Create; begin inherited Create(TecTokenRule); end; function TecTokenRuleCollection.GetItem(Index: integer): TecTokenRule; begin Result := inherited Items[Index] as TecTokenRule; end; { TecParserResults } constructor TecParserResults.Create(AOwner: TecSyntAnalyzer; ABuffer: TATStringBuffer; const AClient: IecSyntClient); begin inherited Create; if ABuffer = nil then raise Exception.Create('TextBuffer not passed to parser'); FOwner := AOwner; FBuffer := ABuffer; FClient := AClient; FTagList := TecTokenList.Create(False); FSubLexerBlocks := TecSubLexerRanges.Create; FOwner.FClientList.Add(Self); FCurState := 0; FStateChanges := TRangeList.Create; end; destructor TecParserResults.Destroy; begin FOwner.FClientList.Remove(Self); FreeAndNil(FTagList); FreeAndNil(FSubLexerBlocks); FreeAndNil(FStateChanges); inherited; end; procedure TecParserResults.Clear; begin FTagList.Clear; FSubLexerBlocks.Clear; FStateChanges.Clear; FCurState := 0; end; procedure TecParserResults.Finished; begin FFinished := True; // Performs Gramma parsing //AnalyzeGramma; //FTagList.UpdateIndexer; //AT end; function TecParserResults.IsEnabled(Rule: TRuleCollectionItem; OnlyGlobal: Boolean): Boolean; begin Result := Rule.Enabled and (not OnlyGlobal or Rule.AlwaysEnabled) and ((Rule.StatesPresent = 0) or ((FCurState and Rule.StatesPresent) = Rule.StatesPresent)) and ((Rule.StatesAbsent = 0) or ((FCurState and Rule.StatesAbsent) = 0)); end; function TecParserResults.GetTokenCount: integer; begin Result := FTagList.Count; end; function TecParserResults.GetTags(Index: integer): TecSyntToken; begin Result := FTagList[Index]; end; function TecParserResults.GetTokenStr(Index: integer): ecString; begin if Index >= 0 then with Tags[Index] do Result := FBuffer.SubString(Range.StartPos + 1, Range.EndPos - Range.StartPos) else Result := ''; end; function TecParserResults.GetLastPos(const Source: ecString): integer; begin if FTagList.Count = 0 then Result := 1 else Result := FTagList[FTagList.Count - 1].Range.EndPos + 1; if FLastAnalPos > Result then Result := FLastAnalPos; end; procedure TecParserResults.SaveState; var b: Boolean; begin if FStateChanges.Count = 0 then b := FCurState <> 0 else b := FCurState <> TRange(FStateChanges.Last).EndPos; if b then FStateChanges.Add(TRange.Create(FTagList.Count, FCurState)); end; // True if end of the text function TecParserResults.ExtractTag(const Source: ecString; var FPos: integer; IsIdle: Boolean): Boolean; var N: integer; p: TecSyntToken; own: TecSyntAnalyzer; // Select current lexer procedure GetOwner; var i, N: integer; Sub: TecSubLexerRange; begin own := FOwner; for i := FSubLexerBlocks.Count - 1 downto 0 do begin Sub:= FSubLexerBlocks[i]; if FPos > Sub.Range.StartPos then if Sub.Range.EndPos = -1 then begin // try close sub lexer // if Rule.ToTextEnd then N := 0 else N := Sub.Rule.MatchEnd(Source, FPos); if N > 0 then begin if Sub.Rule.IncludeBounds then begin // New mode in v2.35 Sub.Range.EndPos := FPos - 1 + N; Sub.Range.PointEnd := FBuffer.StrToCaret(Sub.Range.EndPos); Sub.CondEndPos := Sub.Range.EndPos; own := Sub.Rule.SyntAnalyzer; end else begin Sub.Range.EndPos := FPos - 1; Sub.Range.PointEnd := FBuffer.StrToCaret(Sub.Range.EndPos); Sub.CondEndPos := Sub.Range.EndPos + N; end; // Close ranges which belongs to this sub-lexer range CloseAtEnd(FTagList.PriorAt(Sub.Range.StartPos)); FSubLexerBlocks[i] := Sub; // Write back to list end else begin own := Sub.Rule.SyntAnalyzer; Exit; end; end else if FPos < Sub.Range.EndPos then begin own := Sub.Rule.SyntAnalyzer; Exit; end; end; end; procedure CheckIntersect; var i: integer; Sub: TecSubLexerRange; begin for i := FSubLexerBlocks.Count - 1 downto 0 do begin Sub := FSubLexerBlocks[i]; if (p.Range.EndPos > Sub.Range.StartPos) and (p.Range.StartPos < Sub.Range.StartPos) then begin p.Range.EndPos := Sub.Range.StartPos; p.Range.PointEnd := FBuffer.StrToCaret(p.Range.EndPos); Exit; end; end; end; function CanOpen(Rule: TecSubAnalyzerRule): Boolean; var N: integer; sub: TecSubLexerRange; begin Result := IsEnabled(Rule, False) and (Rule.SyntAnalyzer <> nil); if not Result then Exit; Result := Rule.FromTextBegin and (FPos = 1); if Result then N := 0 else N := Rule.MatchStart(Source, FPos); Result := Result or (N > 0); if not Result then Exit; // To prevent repeated opening if FSubLexerBlocks.Count > 0 then begin sub := FSubLexerBlocks.Last; if (sub.Range.EndPos = FPos - 1) and (sub.Rule = Rule) then Exit; end; ApplyStates(Rule); FillChar(sub, SizeOf(sub), 0); sub.Rule := Rule; sub.CondStartPos := FPos - 1; if Rule.IncludeBounds then sub.Range.StartPos := FPos - 1 else sub.Range.StartPos := FPos + N - 1; sub.Range.EndPos := -1; sub.Range.PointStart := FBuffer.StrToCaret(sub.Range.StartPos); sub.CondEndPos := -1; FSubLexerBlocks.Add(sub); end; procedure TryOpenSubLexer; var i: integer; begin for i := 0 to own.SubAnalyzers.Count - 1 do if CanOpen(own.SubAnalyzers[i]) then Exit; if own <> FOwner then for i := 0 to FOwner.SubAnalyzers.Count - 1 do if FOwner.SubAnalyzers[i].AlwaysEnabled and CanOpen(FOwner.SubAnalyzers[i]) then Exit; end; begin GetOwner; TryOpenSubLexer; if own.SkipSpaces then begin if own.ParseEndOfLine then N := SkipSpacesNoLineBreak(Source, FPos) else N := SkipSpaces(Source, FPos); end else if FPos > Length(Source) then N := -1 else N := 0; TryOpenSubLexer; GetOwner; Result := N = -1; if Result then Exit; p := FOwner.GetToken(Self, Source, FPos, own <> FOwner); if (own <> FOwner) and (p.Range.StartPos < 0) then p := own.GetToken(Self, Source, FPos, False); if p.Range.StartPos < 0 then // no token begin Inc(FPos); end else begin CheckIntersect; SaveState; FTagList.Add(p); if not FOwner.SeparateBlockAnalysis then begin FOwner.SelectTokenFormat(Self, Source, own <> FOwner); if own <> FOwner then own.SelectTokenFormat(Self, Source, False); end else // if not IsIdle then begin // Only for first iteration of analysis FOwner.HighlightKeywords(Self, Source, own <> FOwner); if own <> FOwner then own.HighlightKeywords(Self, Source, False); end; FPos := p.Range.EndPos + 1; end; FLastAnalPos := FPos; end; function TecParserResults.AnalyzerAtPos(Pos: integer): TecSyntAnalyzer; var i: integer; begin Result := FOwner; if Pos >= 0 then for i := 0 to FSubLexerBlocks.Count - 1 do with FSubLexerBlocks[i] do if Pos < Range.StartPos then Break else if (Range.EndPos = -1) or (Pos < Range.EndPos) then Result := Rule.SyntAnalyzer; end; function TecParserResults.GetSubLexerRangeCount: integer; begin Result := FSubLexerBlocks.Count; end; function TecParserResults.GetSubLexerRange(Index: integer): TecSubLexerRange; begin Result := FSubLexerBlocks[Index]; end; procedure TecParserResults.SetTags(Index: integer; const AValue: TecSyntToken); begin FTagList[Index] := AValue end; function TecParserResults.GetTokenType(Index: integer): integer; begin Result := Tags[Index].TokenType; end; procedure TecParserResults.ApplyStates(Rule: TRuleCollectionItem); begin if Rule.StatesRemove <> 0 then FCurState := FCurState and not Rule.StatesRemove; if Rule.StatesAdd <> 0 then FCurState := FCurState or Rule.StatesAdd; end; procedure TecParserResults.RestoreState; var i: integer; begin for i := FStateChanges.Count - 1 downto 0 do if TRange(FStateChanges.Last).StartPos >= TagCount then FStateChanges.Delete(FStateChanges.Count - 1) else Break; if FStateChanges.Count > 0 then FCurState := TRange(FStateChanges.Last).EndPos else FCurState := 0; end; function TecParserResults.ParserStateAtPos(TokenIndex: integer): integer; var i: integer; begin for i := FStateChanges.Count - 1 downto 0 do if TRange(FStateChanges[i]).StartPos <= TokenIndex then begin Result := TRange(FStateChanges[i]).EndPos; Exit; end; Result := 0; end; { TecClientSyntAnalyzer } constructor TecClientSyntAnalyzer.Create(AOwner: TecSyntAnalyzer; SrcProc: TATStringBuffer; const AClient: IecSyntClient); begin inherited Create( AOwner, SrcProc, AClient); FRanges := TSortedList.Create(True); FOpenedBlocks := TSortedList.Create(False); FTimerIdle := TTimer.Create(nil); FTimerIdle.OnTimer := TimerIdleTick; FTimerIdle.Enabled := False; FTimerIdle.Interval := 100; IdleAppend; end; destructor TecClientSyntAnalyzer.Destroy; begin if Assigned(FTimerIdle) then begin DoStopTimer(true); FreeAndNil(FTimerIdle); end; FreeAndNil(FRanges); FreeAndNil(FOpenedBlocks); inherited; end; procedure TecClientSyntAnalyzer.Stop; begin FFinished := true; DoStopTimer(true); end; procedure TecClientSyntAnalyzer.Clear; begin inherited; FRepeateAnalysis := False; FTagList.Clear; FRanges.Clear; FOpenedBlocks.Clear; DoStopTimer(false); FFinished := False; FLastAnalPos := 0; FStartSepRangeAnal := 0; IdleAppend; end; procedure TecClientSyntAnalyzer.AddRange(Range: TecTextRange); begin Range.Index := FRanges.Count; FRanges.Add(Range); if FOpenedBlocks.Count > 0 then Range.Parent := TecTextRange(FOpenedBlocks[FOpenedBlocks.Count - 1]); if Range.EndIdx = -1 then FOpenedBlocks.Add(Range); end; function IndentOf(const S: ecString): Integer; var i: Integer; begin Result:= 0; for i:= 1 to Length(S) do case S[i] of ' ': Inc(Result); #9: Inc(Result, 4); else Break; end; end; function TecClientSyntAnalyzer.CloseRange(Cond: TecTagBlockCondition; RefTag: integer): Boolean; var j: integer; b: boolean; begin for j := FOpenedBlocks.Count - 1 downto 0 do with TecTextRange(FOpenedBlocks[j]) do if Assigned(Rule) then begin if Cond.BlockType = btRangeStart then b := Cond.SelfClose and (Rule = Cond) else b := (Rule.FBlockEndCond = Cond) or (Rule = Cond.FBlockEndCond); if b then begin if Cond.SameIdent and not SameText(TagStr[RefTag - Cond.IdentIndex] , TagStr[IdentIdx]) then Continue; EndIdx := RefTag - Cond.BlockOffset; if (Rule = Cond) and (EndIdx > 0) then Dec(EndIdx); // for self closing FEndCondIndex := RefTag; if Assigned(Owner.OnCloseTextRange) then Owner.OnCloseTextRange(Self, TecTextRange(FOpenedBlocks[j]), StartIdx, EndIdx); FOpenedBlocks.Delete(j); Result := True; Exit; end; end; Result := False; end; function TecClientSyntAnalyzer.HasOpened(Rule: TRuleCollectionItem; Parent: TecTagBlockCondition; Strict: Boolean): Boolean; var i: integer; prn: TecTagBlockCondition; begin if Strict then begin if FOpenedBlocks.Count > 0 then begin i := FOpenedBlocks.Count - 1; prn := TecTextRange(FOpenedBlocks[i]).Rule; if (Rule is TecTagBlockCondition) and TecTagBlockCondition(Rule).SelfClose and (prn = Rule) then Dec(i); repeat if i < 0 then begin Result := False; Exit; end; prn := TecTextRange(FOpenedBlocks[i]).Rule; Dec(i); until not prn.IgnoreAsParent; Result := prn = Parent; end else Result := Parent = nil; end else begin Result := True; if Parent = nil then Exit; for i := FOpenedBlocks.Count - 1 downto 0 do if TecTextRange(FOpenedBlocks[i]).Rule = Parent then Exit; Result := False; end; end; procedure TecClientSyntAnalyzer.Finished; var i: integer; Sub: TecSubLexerRange; begin if FFinished then Exit; inherited Finished; // Close SubLexers at the End of Text for i := FSubLexerBlocks.Count - 1 downto 0 do begin Sub := FSubLexerBlocks[i]; if (Sub.Range.EndPos = -1) and Sub.Rule.ToTextEnd then begin Sub.Range.EndPos := FBuffer.TextLength{ - 1}; Sub.Range.PointEnd := Point( FBuffer.LineLength(FBuffer.Count-1), FBuffer.Count-1); //at end Sub.CondEndPos := Sub.Range.EndPos; FSubLexerBlocks[i] := Sub; end; end; // Close blocks at the end of text CloseAtEnd(0); FRepeateAnalysis := True; end; procedure TecClientSyntAnalyzer.TimerIdleTick(Sender: TObject); var FPos, tmp, i: integer; own: TecSyntAnalyzer; begin if FTimerIdleIsBusy or FDisableIdleAppend then Exit; FTimerIdle.Enabled := False; FTimerIdleMustStop := False; FTimerIdleIsBusy := True; FPos := 0; try while not FTimerIdleMustStop and not FFinished do begin tmp := GetLastPos(FBuffer.FText); if tmp > FPos then FPos := tmp; if ExtractTag(FBuffer.FText, FPos, True) then begin if FOwner.SeparateBlockAnalysis then for i := FStartSepRangeAnal + 1 to TagCount do begin own := Tags[i - 1].Rule.SyntOwner; FOwner.SelectTokenFormat(Self, FBuffer.FText, own <> FOwner, i); if own <> FOwner then own.SelectTokenFormat(Self, FBuffer.FText, False, i); Application.ProcessMessages; if Application.Terminated then Exit; if FTimerIdleMustStop then Exit; end; Finished; end else begin Application.ProcessMessages; if Application.Terminated then Exit; if FTimerIdleMustStop then Exit; end; end; finally FTimerIdleIsBusy := False; end; end; procedure TecClientSyntAnalyzer.IdleAppend; begin //sets FTimerIdle interval and restarts it if not FFinished then begin FTimerIdle.Enabled := False; if FRepeateAnalysis then FTimerIdle.Interval := Owner.IdleAppendDelay else FTimerIdle.Interval := Owner.IdleAppendDelayInit; FTimerIdle.Enabled := True; end; end; procedure TecClientSyntAnalyzer.AppendToPos(APos: integer; AUseTimer: boolean=true); var FPos: integer; begin if FBuffer.TextLength = 0 then Exit; if FFinished then Exit; FPos := GetLastPos(FBuffer.FText); while FPos - 1 <= APos + 1 do begin if ExtractTag(FBuffer.FText, FPos, False) then begin if not FOwner.SeparateBlockAnalysis then Finished else if not FTimerIdleIsBusy then if AUseTimer then IdleAppend else TimerIdleTick(nil); Break; end; end; end; procedure TecClientSyntAnalyzer.ChangedAtPos(APos: integer); var i, N: integer; Sub: TecSubLexerRange; procedure CleanRangeList(List: TSortedList; IsClosed: Boolean); var i: integer; begin for i := List.Count - 1 downto 0 do with TecTextRange(List[i]) do if (FCondIndex >= N) or (StartIdx >= N) or IsClosed and ((FEndCondIndex >= N) or (EndIdx >= N)) then List.Delete(i); end; begin { if FBuffer.TextLength <= Owner.FullRefreshSize then begin Clear; Exit; end;} FFinished := False; Dec(APos); DoStopTimer(false); if FBuffer.TextLength <= Owner.FullRefreshSize then APos := 0 else if Owner.RestartFromLineStart then APos := Min(APos, FBuffer.OffsetToOffsetOfLineStart(APos + 1)); // Check sub lexer ranges for i := FSubLexerBlocks.Count - 1 downto 0 do begin Sub:= FSubLexerBlocks[i]; if APos < Sub.Range.StartPos then begin if APos > Sub.CondStartPos then APos := Sub.CondStartPos; FSubLexerBlocks.Delete(i); // remove sub lexer end else if APos < Sub.CondEndPos then begin if APos > Sub.Range.EndPos then APos := Sub.Range.EndPos; Sub.Range.EndPos := -1; // open sub lexer Sub.CondEndPos := -1; FSubLexerBlocks[i] := Sub; end; end; // Remove tokens FTagList.ClearFromPos(APos); FLastAnalPos := 0; // Reset current position N := FTagList.Count; FStartSepRangeAnal := N; // Remove text ranges from service containers CleanRangeList(FOpenedBlocks, False); // Remove text ranges from main storage for i := FRanges.Count - 1 downto 0 do with TecTextRange(FRanges[i]) do if (FCondIndex >= N) or (StartIdx >= N) then FRanges.Delete(i) else if (FEndCondIndex >= N) or (EndIdx >= N) then begin EndIdx := -1; FEndCondIndex := -1; FOpenedBlocks.Add(FRanges[i]); end; // Restore parser state RestoreState; IdleAppend; end; function TecClientSyntAnalyzer.PriorTokenAt(Pos: integer): integer; begin Result := FTagList.PriorAt(Pos); end; function TecClientSyntAnalyzer.GetRangeCount: integer; begin Result := FRanges.Count; end; function TecClientSyntAnalyzer.GetRanges(Index: integer): TecTextRange; begin Result := TecTextRange(FRanges[Index]); end; procedure TecClientSyntAnalyzer.Analyze(ResetContent: Boolean); var OldSep: integer; begin if IsFinished then Exit; if ResetContent then begin OldSep := FOwner.FSeparateBlocks; FOwner.FSeparateBlocks := 2; // disanle separation analysis Clear; AppendToPos(FBuffer.TextLength); FOwner.FSeparateBlocks := OldSep; end else begin AppendToPos(FBuffer.TextLength); end; end; procedure TecClientSyntAnalyzer.CompleteAnalysis; var own: TecSyntAnalyzer; i: integer; begin AppendToPos(FBuffer.TextLength); if FOwner.SeparateBlockAnalysis then for i := FStartSepRangeAnal + 1 to TagCount do begin own := Tags[i - 1].Rule.SyntOwner; FOwner.SelectTokenFormat(Self, FBuffer.FText, own <> FOwner, i); if own <> FOwner then own.SelectTokenFormat(Self, FBuffer.FText, False, i); DoStopTimer(true); Finished; end; end; function TecClientSyntAnalyzer.RangeFormat(const FmtStr: ecString; Range: TecTextRange): ecString; var i, j, idx, N, to_idx: integer; rng: TecTextRange; LineMode: integer; { HAW: hans@werschner.de [Oct'07] ......... additions to formatting token parts ...... I have added syntax to each single ".... %xyz ...." clause processing a) %(S|E)P*(L|Z)?[0-9]+ may be expanded to %(S|E)P*([\[]<token>[\]]<offset>?)? where <token> is a specific token that is "searched from the specified starting point (S for first token in the range , or E for the last token) towards the respective range end (up- or downwards). The search-direction is kept in the variable "rngdir" which is set in the "S" , "E" decision. example: line(s) is/are ".... for x = 1 to 12 do ...... end ; ..." 0 1 2 3 4 5 6 ... 27 28 range-start = "for", range-end = "end" then "...%s[to] ..." will skip forward to the token "to" (with index 4). The token values are searched on a "asis" basis, there is no case-insensitivity option yet. A "numeric number following the token value will define an <offset> relative to the found token. For this clause, the variable "idx" is not set by taking the static numeric value as in "...%s2 ..." , instead the "found token index" is kept. For "%S..." the search starts at idx=0 up to max 28. ---> rngdir = +1; For "%E..." the search starts at idx=28 downto min 0. ---> rngdir = -1; The options L or Z introduced in V2.35 will not combine with the new (range) specifying options --> somebody else may find a use for such extended ranges. Notes: Avoid to search for tokens that can occur at multiple places (for example a ";" between statements). The above syntax is simple as it allows to identify the block-start-tokens "for x = 1 to 12 do" block-body anything after block-start tokens up to block-end-tokens "end ;" but many syntax formats do not trivially support this separation. The current implementation does not provide the information where "block-start", "block-body" and "block-end" are beginning/ending. A "%B0..." for the "block-body" portion and a "ignore block-body tokens" option may be nice !? b) any such clause (either absolute or given by token value) can "start a token range" by additionally specifying: %(S|E)...~(S|E)P*[0-9]+ or %(S|E)...~(S|E)P*([\[]<token>[\]]<offset>?)? or %(S|E)...~[\[]<token>[\]] The first form uses the static index specification to define the end-range: "%s0~s3" results in "for x = 1" (tokens 0, 1, ... 3) The 2nd form uses the new syntax to "search for an end-token beginning at the starting range index (idx) up- or down-wards. "%s0~s[do]" results in "for x = 1 to 12 do" (tokens 0, 1, ... 6) if a search is not satisfied, the complete range up to "e0" is taken. Because of the same "S", the search starts with "TagStr[idx]" ... "s0~e[do]" results in the same string, but starts at the final "end" of the block and scanning downwards. Caution: This may produce WRONG results if nested loops are scanned ! I could not find a valid representation of "range-start" token- streams, the range-body alone and/or the range-end token-stream. Such information may be helpful to better display blocks and/or collapse display of the "block-body" alone. The 3rd form is an abbreviation where the S/E indicators are taken to be identical as the starting point "S1~[do]1" results in "x = 1 to 12" (tokens 1, 2, ... 5) The <offset> "1" will here skip back by 1 from the found token "do". The range-end is kept in the variable "to_idx". The "token-value" to search for can not be whitespace #00..#20. Leading and trailing whitespace withing the "...[vvvvvvv] ..." enclosed by [ and ] characters sequence is removed before searching. the "vvvvvv" can contain escaped characters like "... [\]] ..." to allow "[" and/or "]" to be part of the value. The \r, \n, \f ...escapes are not supported here. The token accumulation simply (?) takes all tokens from "idx" ... "to_idx" and builds a string by appending all tokens with ONE " " (blank) as separating delimiter. There is no process to keep the original token positions within the source line(s) and any whitepace including cr/lf's there. This may be an addition but I currently do not see a need for it. c) "ranges as specified above may accumulate many tokens and it may be desirable to "limit" the result string. This can be done by using another operand syntax %(S|E)...~[0-9]+ or %(S|E)...~(S|E)([\[]<token>[\]]<offset>?)?~[0-9]+ or %(S|E)...~[\[]<token>[\]]~[0-9]+ In all three forms the "~" is immediately followed by a numeric value which is interpreted as "maximum number of tokens in the substituted string", if the range takes MORE than this maximum The value is internally kept in the variable "rngmax" below. When the result string is accumulated (taking all tokens between "idx" up- resp. down-to "to_idx") the number of appended tokens can not go beyond "rngmax". If this happens the result will be created in the form "t-1 t-2 -- t-max ..." with the ellipsis string " ..." appended. d) There is another addition to the token clause syntax which is NOT YET operational: I am not too happy that the collapsed string displayed is completely in "grey" colour. As I want to have some control over "highlighting" in this string also, I tried to add some style-reference information to the token clause. *** I currently do not yet understand HOW to activate such a style within the results of this formatting, but I will TRY !! OK, the added syntax for styles for future use ;-) .... %:<style>:(S|E) .... where the <style> is the alphanumeric name of a style as defined in the lexer definition and this style-name is "enclosed" with the ":" characters. The code keeps the found style-name in the variable "rngstyle" for any later use. This addition only assigns styles to the token substitution parts, but not to any text outside and/or the total "collapsed" text formatting. This may be some enhancement to define in the lexer GUI. Hans L. Werschner, Oct '07 } var rngstyle: string; // HAW: add style identifier to range expression rngtoken, rngResult: string; // a few more vars swp_idx, rngdir, rngoffset, rngmax: integer; to_rng: TecTextRange; function RangeNumber( const FmtStrNumber: string; var gotnbr: integer ): boolean; begin N := 0; Result := false; while (j + N) <= length( FmtStrNumber ) do if (FmtStrNumber[j + N] >= '0') and (FmtStrNumber[j + N] <= '9') or (N = 0) and ((FmtStrNumber[j + N] = '+') or (FmtStrNumber[j + N] = '-')) then inc(N) else Break; if N > 0 then begin gotnbr := StrToInt( copy( FmtStrNumber, j, N ) ); inc( j, N ); Result := true; end; end; //var S_: string; begin idx := 0; Result := FmtStr; try // HAW: obsolete -> to_idx := Length(Result); // the variable "j" is now always pointing to the next character to process. // Only during numeric sub-operand scan, the "N" will keep the found digits // count. After such number, the var "j" is immediately adjusted again. for i := Length(Result) - 1 downto 1 do if Result[i] = '%' then begin j := i + 1; rngstyle := ''; // HAW: keep style name if Result[j] = ':' then begin // HAW: begin of embedded style name inc( j ); while (j <= length( Result )) and (Result[j] <> ':') do begin if Result[j] > ' ' then rngstyle := rngstyle+Result[j]; inc( j ); end; if (j > length( Result )) or (Result[j] <> ':') then continue; inc( j ); // now we have a style name, and can resume after "%:ssssss:" end; rng := Range; rngdir := 1; // HAW: positive increment (for "%..e..") // negative for "..e.." clauses rngmax := 1000000000; // HAW: allow a great amount of tokens while ecUpCase(Result[j]) = 'P' do begin rng := rng.Parent; if (rng = nil) or (j = Length(Result)) then Continue; inc(j); end; case ecUpCase(Result[j]) of 'S': idx := rng.StartIdx + rng.Rule.BlockOffset; 'E': begin rngdir := -1; // HAW: mark downwards direction if (rng.EndIdx <> -1) and Assigned(rng.Rule.BlockEndCond) then idx := rng.EndIdx + rng.Rule.BlockEndCond.BlockOffset else idx := 1000000000; end; else continue; end; inc(j); case ecUpCase(Result[j]) of // <== v2.35 'L': LineMode := 1; // from start of line 'Z': LineMode := 2; // to end of line else LineMode := 0; end; if LineMode <> 0 then Inc(j); // HAW: check for "...s[token]..." instead of numeric index if LineMode = 0 then if (j < length( Result )) and (Result[j] = '[') then begin inc( j ); rngtoken := ''; while (j < length( Result )) and (Result[j] <> ']') do begin if Result[j] = '\' then inc( j ); rngtoken := rngtoken + Result[j]; inc( j ); end; if j > length( Result ) then continue; while (rngtoken <> '') and (rngtoken[length( rngtoken )] < ' ') do rngtoken := copy( rngtoken, 1, length( rngtoken )-1 ); while (rngtoken <> '') and (rngtoken[1] < ' ') do rngtoken := copy( rngtoken, 2, length( rngtoken )-1 ); if rngtoken = '' then continue; inc( j ); if rngdir > 0 then begin // upwards search while idx <= (rng.EndIdx + rng.Rule.BlockEndCond.BlockOffset) do begin if rngtoken = TagStr[idx] then break; inc( idx ); end; end else if rngdir < 0 then // downwards search while idx >= (rng.StartIdx + rng.Rule.BlockOffset) do begin if rngtoken = TagStr[idx] then break; dec( idx ); end; rngdir := 0; // allow for missing <offset> end; if not RangeNumber( Result, rngoffset ) then begin if rngdir <> 0 then Continue; end else idx := idx - rngoffset; to_idx := idx; to_rng := rng; // HAW: now allow an explicit "to_idx" range by using "%from-idx~to-idx" if (j < length( Result )) and (Result[j] = '~') then // a numeric value alone sets just the maximum tokens to use if (Result[j+1] >= '0') and (Result[j+1] <= '9') then begin // only positive values ! to_idx := to_rng.EndIdx + to_rng.Rule.BlockEndCond.BlockOffset; LineMode := 3; end else begin if LineMode <> 0 then // not a good combination continue; // ... otherwise we have a real end-token clause inc( j ); // skip over the [ rngdir := 1; if Result[j] <> '[' then begin // to_rng := Range; // be sure that we start with the range itself while ecUpCase(Result[j]) = 'P' do begin to_rng := rng.Parent; if (to_rng = nil) or (j = Length(Result)) then Continue; inc(j); end; case ecUpCase(Result[j]) of 'S': to_idx := to_rng.StartIdx + to_rng.Rule.BlockOffset; 'E': begin rngdir := -1; // HAW: mark downwards direction if (to_rng.EndIdx <> -1) and Assigned(to_rng.Rule.BlockEndCond) then to_idx := to_rng.EndIdx + to_rng.Rule.BlockEndCond.BlockOffset else to_idx := 1000000000; end; else continue; end; inc(j); end; if (j < length( Result )) and (Result[j] = '[') then begin inc( j ); rngtoken := ''; while (j < length( Result )) and (Result[j] <> ']') do begin if Result[j] = '\' then inc( j ); rngtoken := rngtoken + Result[j]; inc( j ); end; if j > length( Result ) then continue; while (rngtoken <> '') and (rngtoken[length( rngtoken )] < ' ') do rngtoken := copy( rngtoken, 1, length( rngtoken )-1 ); while (rngtoken <> '') and (rngtoken[1] < ' ') do rngtoken := copy( rngtoken, 2, length( rngtoken )-1 ); if rngtoken = '' then continue; inc( j ); if rngdir > 0 then begin // upwards search while to_idx <= (rng.EndIdx + rng.Rule.BlockEndCond.BlockOffset) do begin if rngtoken = TagStr[to_idx] then break; inc( to_idx ); end; end else if rngdir < 0 then // downwards search while to_idx >= (rng.StartIdx + rng.Rule.BlockOffset) do begin if rngtoken = TagStr[to_idx] then break; dec( to_idx ); end; rngdir := 0; // allow for missing <offset> end; if not RangeNumber( Result, rngoffset ) then begin if rngdir <> 0 then Continue; end else to_idx := to_idx - rngoffset; LineMode := 3; // enforce new mode as we have an explicit range end; if (j < length( Result )) and (Result[j] = '~') and (Result[j+1] >= '0') and (Result[j+1] <= '9') // only positive values ! then begin // we hav a "maximum" range value attached inc( j ); if not RangeNumber( Result, rngmax ) then Continue; end; // HAW: ... end of added range checking , // variable "j" points to first character AFTER all clauses Delete(Result, i, j - i); if (idx >= 0) and (idx < FTagList.Count) then case LineMode of 0: Insert(TagStr[idx], Result, i); 1: begin N := FBuffer.OffsetToOffsetOfLineStart(Tags[idx].Range.StartPos); to_idx := Tags[idx].Range.EndPos; Insert(FBuffer.SubString(N, to_idx - N + 1), Result, i); end; 2: begin to_idx := FBuffer.OffsetToOffsetOfLineEnd(Tags[idx].Range.EndPos); N := Tags[idx].Range.StartPos; Insert(FBuffer.SubString(N+1, to_idx - N + 1), Result, i); //AT: fixed substring offset/len (2 patches) end; // HAW: new mode = 3 --- explicit range idx...to_idx 3: if (to_idx >= 0) and (to_idx < FTagList.Count) then begin if to_idx < idx then begin swp_idx := idx; idx := to_idx; to_idx := swp_idx; end; rngResult := ''; while idx <= to_idx do begin if rngmax <= 0 then begin rngResult := rngResult+' ...'; break; end; if (rngResult <> '') and (idx > 0) and (Tags[idx-1].Range.EndPos <> Tags[idx].Range.StartPos) then //MZ fix rngResult := rngResult + ' '; rngResult := rngResult + TagStr[idx]; inc( idx ); dec( rngmax ); end; Insert(rngResult, Result, i); end; // HAW: ... end of token range accumulation mode end; // HAW: I am currently not sure how to handle the "stylename" property here // ... will be added, when available end; Exit; except Result := ''; end; end; function TecClientSyntAnalyzer.GetRangeName(Range: TecTextRange): ecString; begin Result := ''; if Assigned(Range.Rule) and (Range.Rule.NameFmt <> '') then Result := RangeFormat(Range.Rule.NameFmt, Range); if Result = '' then Result := TagStr[Range.IdentIdx]; end; function TecClientSyntAnalyzer.GetRangeGroup(Range: TecTextRange): ecString; begin Result := RangeFormat(Range.Rule.GroupFmt, Range); end; function TecClientSyntAnalyzer.GetCollapsedText(Range: TecTextRange): ecString; begin Result := RangeFormat(Range.Rule.CollapseFmt, Range); end; function TecClientSyntAnalyzer.IsEnabled(Rule: TRuleCollectionItem; OnlyGlobal: Boolean): Boolean; begin Result := inherited IsEnabled(Rule, OnlyGlobal) and (HasOpened(Rule, Rule.Block, Rule.StrictParent) xor Rule.NotParent); end; procedure TecClientSyntAnalyzer.TextChanged(Pos, Count: integer); //AT: Line, LineChange were not used, deled begin if Pos = -1 then Clear else begin ChangedAtPos(Pos); end; end; function TecClientSyntAnalyzer.GetOpened(Index: integer): TecTextRange; begin Result := TecTextRange(FOpenedBlocks[Index]); end; function TecClientSyntAnalyzer.GetOpenedCount: integer; begin Result := FOpenedBlocks.Count; end; procedure TecClientSyntAnalyzer.SetDisableIdleAppend(const Value: Boolean); begin if FDisableIdleAppend <> Value then begin FDisableIdleAppend := Value; if not IsFinished then TimerIdleTick(nil); end; end; procedure TecClientSyntAnalyzer.DoStopTimer(AndWait: boolean); begin FTimerIdleMustStop := True; FTimerIdle.Enabled := False; if FTimerIdleIsBusy then if AndWait then Sleep(100) else Sleep(20); end; function TecClientSyntAnalyzer.DetectTag(Rule: TecTagBlockCondition; RefTag: integer): Boolean; var Tag: TecSyntToken; begin Tag := Tags[RefTag]; Tag.Rule := Rule; if Rule.TokenType >= 0 then Tag.TokenType := Rule.TokenType; Tags[RefTag] := Tag; Result := True; end; procedure TecClientSyntAnalyzer.CloseAtEnd(StartTagIdx: integer); const cSpecIndentID = 20; //special number for "Group index" lexer property, which activates indent-based folding for a rule cSpecTokenStart: char = '1'; //special char - must be first of token's type name (e.g. "1keyword"); //Also such tokens must contain spaces+tabs at the beginning (use parser regex like "^[\x20\x09]*\w+") var i, j, Ind: integer; Range: TecTextRange; s: string; begin for i := FOpenedBlocks.Count - 1 downto 0 do begin Range := TecTextRange(FOpenedBlocks[i]); if Range.Rule.EndOfTextClose and ((StartTagIdx = 0) or (Range.StartIdx >= StartTagIdx)) then begin Range.EndIdx := TagCount - 1; if Range.Rule.GroupIndex = cSpecIndentID then begin Ind := IndentOf(TagStr[Range.StartIdx]); for j := Range.StartIdx+1 to TagCount-1 do begin s := ''; if Range.Rule.SyntOwner<>nil then s := Range.Rule.SyntOwner.TokenTypeNames[Tags[j].TokenType]; if (s<>'') and (s[1] = cSpecTokenStart) and (IndentOf(TagStr[j]) <= Ind) then begin Range.EndIdx := j-1; Break end; end; end; FOpenedBlocks.Delete(i); end; end; end; { TecSyntAnalyzer } constructor TecSyntAnalyzer.Create(AOwner: TComponent); begin inherited; FClientList := TList.Create; FMasters := TList.Create; FSampleText := TStringList.Create; FTokenTypeNames := TStringList.Create; FTokenTypeNames.Text := SecDefaultTokenTypeNames; TStringList(FTokenTypeNames).OnChange := TokenNamesChanged; FFormats := TecStylesCollection.Create; FFormats.OnChange := FormatsChanged; FFormats.SyntOwner := Self; FTokenRules := TecTokenRuleCollection.Create; FTokenRules.OnChange := TokenRuleChanged; FTokenRules.SyntOwner := Self; FBlockRules := TecBlockRuleCollection.Create; FBlockRules.OnChange := BlocksChanged; FBlockRules.SyntOwner := Self; FSubAnalyzers := TecSubAnalyzerRules.Create; FSubAnalyzers.SyntOwner := Self; FSubAnalyzers.OnChange := SubLexRuleChanged; FMarkedBlock := FFormats.Add as TecSyntaxFormat; FMarkedBlock.BgColor := clHighlight; FMarkedBlock.Font.Color := clHighlightText; FMarkedBlock.FormatType := ftColor; FMarkedBlock.DisplayName := 'Marked block'; FMarkedBlock.FIsBlock := True; FCodeTemplates := TecCodeTemplates.Create(Self); FSkipSpaces := True; FNotes := TStringList.Create; FGrammaParser := TGrammaAnalyzer.Create; FGrammaParser.OnChange := GrammaChanged; FIdleAppendDelayInit := 50; FIdleAppendDelay := 200; end; destructor TecSyntAnalyzer.Destroy; begin FBlockRules.OnChange := nil; FTokenRules.OnChange := nil; FFormats.OnChange := nil; FSubAnalyzers.OnChange := nil; TStringList(FTokenTypeNames).OnChange:= nil; FGrammaParser.OnChange := nil; FreeAndNil(FFormats); FreeAndNil(FMasters); FreeAndNil(FSampleText); FreeAndNil(FBlockRules); FreeAndNil(FTokenRules); FreeAndNil(FCodeTemplates); FreeAndNil(FTokenTypeNames); FreeAndNil(FSubAnalyzers); FreeAndNil(FNotes); FreeAndNil(FGrammaParser); inherited; FreeAndNil(FClientList); end; procedure TecSyntAnalyzer.Assign(Source: TPersistent); var Src: TecSyntAnalyzer; i: integer; begin if not (Source is TecSyntAnalyzer) then Exit; Src := Source as TecSyntAnalyzer; // ClearClientContents; FCoping := True; try FAlwaysSyncBlockAnal := Src.FAlwaysSyncBlockAnal; Extentions := Src.Extentions; LexerName := Src.LexerName; SkipSpaces := Src.SkipSpaces; SampleText := Src.SampleText; FullRefreshSize := Src.FullRefreshSize; Formats := Src.Formats; MarkedBlockStyle := Src.MarkedBlockStyle; SearchMatchStyle := Src.SearchMatchStyle; CurrentLineStyle := Src.CurrentLineStyle; DefaultStyleName := Src.DefaultStyleName; CollapseStyleName := Src.CollapseStyleName; BlockRules := Src.BlockRules; TokenRules := Src.TokenRules; CodeTemplates := Src.CodeTemplates; SubAnalyzers := Src.SubAnalyzers; // DefaultStyle := Src.DefaultStyle; TokenTypeNames := Src.TokenTypeNames; Notes := Src.Notes; Internal := Src.Internal; Gramma := Src.Gramma; RestartFromLineStart := Src.RestartFromLineStart; ParseEndOfLine := Src.ParseEndOfLine; LineComment := Src.LineComment; FIdleAppendDelayInit := Src.FIdleAppendDelayInit; FIdleAppendDelay := Src.FIdleAppendDelay; for i := 0 to BlockRules.Count - 1 do begin BlockRules[i].BlockEnd := Src.BlockRules[i].BlockEnd; BlockRules[i].BlockName := Src.BlockRules[i].BlockName; end; finally FCoping := False; ClearClientContents; end; UpdateClients; for i := 0 to FClientList.Count - 1 do TecClientSyntAnalyzer(FClientList[i]).IdleAppend; end; procedure TecSyntAnalyzer.HighlightKeywords(Client: TecParserResults; const Source: ecString; OnlyGlobal: Boolean); var i, N, ki, RefIdx: integer; Accept: Boolean; Tag: TecSyntToken; begin N := Client.TagCount; for i := 0 to FBlockRules.Count - 1 do with FBlockRules[i] do if Enabled and (BlockType = btTagDetect) and (Block = nil) and (FGrammaRule = nil) then begin if OnlyGlobal and not AlwaysEnabled then Continue; RefIdx := 0; Accept := Check(Source, TecClientSyntAnalyzer(Client), N, RefIdx); if Assigned(OnBlockCheck) then OnBlockCheck(FBlockRules[i], TecClientSyntAnalyzer(Client), Source, RefIdx, Accept); if Accept then begin if FRefToCondEnd then ki := RefIdx - IdentIndex else ki := N - 1 - CheckOffset - IdentIndex; Tag := TecClientSyntAnalyzer(Client).Tags[ki]; Tag.Rule := FBlockRules[i]; if TokenType >= 0 then Tag.TokenType := TokenType; TecClientSyntAnalyzer(Client).Tags[ki] := Tag; if CancelNextRules then Exit; // 2.27 end; end; end; procedure TecSyntAnalyzer.SelectTokenFormat(Client: TecParserResults; const Source: ecString; OnlyGlobal: Boolean; N: integer); var i, li, ki, strt, RefIdx: integer; Range: TecTextRange; Accept: Boolean; RClient: TecClientSyntAnalyzer; function CheckIndex(Idx: integer): Boolean; begin Result := (Idx >= 0) and (Idx < N); end; begin if N = -1 then N := Client.TagCount; if not (Client is TecClientSyntAnalyzer) then Exit; RClient := TecClientSyntAnalyzer(Client); RClient.FStartSepRangeAnal := N + 1; try for i := 0 to FBlockRules.Count - 1 do with FBlockRules[i] do if not SeparateBlockAnalysis or (BlockType <> btTagDetect) or (Block = nil) or (FGrammaRule = nil) then if Client.IsEnabled(FBlockRules[i], OnlyGlobal) then begin RefIdx := 0; if FGrammaRule <> nil then begin RefIdx := FGrammaParser.TestRule(N - 1, FGrammaRule, Client); Accept := RefIdx <> -1; end else Accept := Check(Source, RClient, N, RefIdx); if Assigned(OnBlockCheck) then OnBlockCheck(FBlockRules[i], RClient, Source, RefIdx, Accept); if Accept then begin Client.ApplyStates(FBlockRules[i]); if FRefToCondEnd then strt := RefIdx else strt := N - 1 - CheckOffset; // strt := N - 1 - CheckOffset; ki := strt - IdentIndex; if CheckIndex(ki) then case BlockType of btTagDetect: // Tag detection if not RClient.DetectTag(FBlockRules[i], ki) then Continue; btRangeStart: // Start of block begin if FBlockRules[i].SelfClose then RClient.CloseRange(FBlockRules[i], strt); li := strt - BlockOffset; if CheckIndex(li) then begin Range := TecTextRange.Create(li, RClient.Tags[li].Range.StartPos); Range.IdentIdx := ki; Range.Rule := FBlockRules[i]; Range.FCondIndex := N - 1; if NoEndRule then begin Range.EndIdx := N - 1 - CheckOffset; Range.FEndCondIndex := N - 1; Range.StartIdx := RefIdx - BlockOffset; end; RClient.AddRange(Range); end; end; btRangeEnd: // End of block if not RClient.CloseRange(FBlockRules[i], strt) then Continue; btLineBreak: begin //AT: deleted support for line separators end; end; if CancelNextRules then Break; end; end; except Application.HandleException(Self); end; end; { function TecSyntAnalyzer.AddClient( const Client: IecSyntClient; ABuffer: TATStringBuffer): TecClientSyntAnalyzer; begin Result := TecClientSyntAnalyzer.Create(Self, ABuffer, Client); //skipped: adding Client to list of clients end; } procedure TecSyntAnalyzer.SetSampleText(const Value: TStrings); begin FSampleText.Assign(Value); end; function TecSyntAnalyzer.GetToken(Client: TecParserResults; const Source: ecString; APos: integer; OnlyGlobal: Boolean): TecSyntToken; var i, N, lp: integer; Rule: TecTokenRule; PntStart, PntEnd: TPoint; begin Result := TecSyntToken.Create(nil, -1, -1, Point(-1, -1), Point(-1, -1)); if Assigned(FOnParseToken) then begin N := 0; Rule := nil; FOnParseToken(Client, Source, APos, N, Rule); if Assigned(Rule) then Result := TecSyntToken.Create(Rule, APos - 1, APos + N - 1, Client.Buffer.StrToCaret(APos-1), Client.Buffer.StrToCaret(APos+N-1) ); Exit; end; lp := 0; for i := 0 to FTokenRules.Count - 1 do begin Rule := FTokenRules[i]; if Client.IsEnabled(Rule, OnlyGlobal) then with Rule do begin if (ColumnFrom > 0) or (ColumnTo > 0) then begin if lp = 0 then lp := Client.FBuffer.OffsetToDistanceFromLineStart(APos - 1)+1; if (ColumnFrom > 0) and (lp < ColumnFrom) or (ColumnTo > 0) and (lp > ColumnTo) then Continue; end; N := Match(Source, APos); if Assigned(OnMatchToken) then OnMatchToken(Rule, Client, Source, APos, N); if N > 0 then begin Client.ApplyStates(Rule); PntStart := Client.Buffer.StrToCaret(APos-1); //optimization: if token is short, get PntEnd simpler if PntStart.X + N >= Client.Buffer.LineLength(PntStart.Y) then PntEnd := Client.Buffer.StrToCaret(APos+N-1) else begin PntEnd.Y := PntStart.Y; PntEnd.X := PntStart.X + N; end; Result := TecSyntToken.Create(Rule, APos - 1, APos + N - 1, PntStart, PntEnd ); Exit; end; end; end; end; procedure TecSyntAnalyzer.FormatsChanged(Sender: TCollection; Item: TSyntCollectionItem); var i: integer; begin ClearClientContents; if Item = nil then begin if not FFormats.ValidItem(FMarkedBlock) then FMarkedBlock := nil; if not FFormats.ValidItem(FCurrentLine) then FCurrentLine := nil; if not FFormats.ValidItem(FDefStyle) then FDefStyle := nil; if not FFormats.ValidItem(FSearchMatch) then FSearchMatch := nil; for i := 0 to FBlockRules.Count - 1 do begin if not FFormats.ValidItem(FBlockRules[i].Style) then FBlockRules[i].Style := nil; if not FFormats.ValidItem(FBlockRules[i].TreeItemStyleObj) then FBlockRules[i].FTreeItemStyleObj := nil; if not FFormats.ValidItem(FBlockRules[i].TreeGroupStyleObj) then FBlockRules[i].FTreeGroupStyleObj := nil; end; for i := 0 to FTokenRules.Count - 1 do if not FFormats.ValidItem(FTokenRules[i].Style) then FTokenRules[i].Style := nil; for i := 0 to FSubAnalyzers.Count - 1 do if not FFormats.ValidItem(FSubAnalyzers[i].Style) then FSubAnalyzers[i].Style := nil; end; // UpdateClients; Change; end; procedure TecSyntAnalyzer.BlocksChanged(Sender: TCollection; Item: TSyntCollectionItem); var i: integer; begin ClearClientContents; if Item = nil then begin for i := 0 to FBlockRules.Count - 1 do begin if not FBlockRules.ValidItem(FBlockRules[i].Block) then FBlockRules[i].Block := nil; if not FBlockRules.ValidItem(FBlockRules[i].BlockEndCond) then FBlockRules[i].BlockEndCond := nil; end; for i := 0 to FTokenRules.Count - 1 do if not FBlockRules.ValidItem(FTokenRules[i].Block) then FTokenRules[i].Block := nil; for i := 0 to FSubAnalyzers.Count - 1 do if not FSubAnalyzers.ValidItem(FSubAnalyzers[i].Block) then FSubAnalyzers[i].Block := nil; end; // UpdateClients; Change; end; procedure TecSyntAnalyzer.ClearClientContents; var i:integer; begin if FCoping then Exit; FCoping := True; try for i := 0 to FClientList.Count - 1 do with TecClientSyntAnalyzer(FClientList[i]) do begin Clear; IdleAppend; end; for i := 0 to FMasters.Count - 1 do TecSyntAnalyzer(FMasters[i]).ClearClientContents; finally FCoping := False; end; UpdateClients; end; procedure TecSyntAnalyzer.UpdateClients; var i:integer; begin if FCoping then Exit; FCoping := True; try for i := 0 to FClientList.Count - 1 do with TecClientSyntAnalyzer(FClientList[i]) do if FClient <> nil then FClient.FormatChanged; for i := 0 to FMasters.Count - 1 do TecSyntAnalyzer(FMasters[i]).UpdateClients; finally FCoping := False; end; end; procedure TecSyntAnalyzer.Loaded; var i: integer; begin inherited; MarkedBlockStyle := FMarkedBlockName; SearchMatchStyle := FSearchMatchName; CurrentLineStyle := FCurrentLineName; CollapseStyleName := FCollapseStyleName; DefaultStyleName := FDefStyleName; FFormats.Loaded; FBlockRules.Loaded; FTokenRules.Loaded; FSubAnalyzers.Loaded; CompileGramma; DetectBlockSeparate; for i := 0 to FMasters.Count - 1 do TecSyntAnalyzer(FMasters[i]).DetectBlockSeparate; end; procedure TecSyntAnalyzer.SetBlockRules(const Value: TecBlockRuleCollection); begin FBlockRules.Assign(Value); ClearClientContents; end; procedure TecSyntAnalyzer.SetCodeTemplates(const Value: TecCodeTemplates); begin FCodeTemplates.Assign(Value); ClearClientContents; end; procedure TecSyntAnalyzer.SetTokenRules(const Value: TecTokenRuleCollection); begin FTokenRules.Assign(Value); ClearClientContents; end; procedure TecSyntAnalyzer.SetFormats(const Value: TecStylesCollection); begin FFormats.Assign(Value); end; function TecSyntAnalyzer.GetUniqueName(const Base: string): string; var n: integer; begin n := 1; if Owner = nil then Result := Base + '1' else repeat Result := Base + IntToStr(n); inc(n); until Owner.FindComponent(Result) = nil; end; procedure TecSyntAnalyzer.SetSkipSpaces(const Value: Boolean); begin if FSkipSpaces <> Value then begin FSkipSpaces := Value; ClearClientContents; end; end; procedure TecSyntAnalyzer.SetSubAnalyzers(const Value: TecSubAnalyzerRules); begin FSubAnalyzers.Assign(Value); ClearClientContents; end; procedure TecSyntAnalyzer.Notification(AComponent: TComponent; Operation: TOperation); var i: integer; begin inherited; if (Operation = opRemove) and (AComponent <> Self) and (aComponent is TecSyntAnalyzer) and Assigned(FSubAnalyzers) and Assigned(FMasters) then begin for i := 0 to FSubAnalyzers.Count - 1 do if FSubAnalyzers[i].FSyntAnalyzer = AComponent then FSubAnalyzers[i].FSyntAnalyzer := nil; FMasters.Remove(AComponent); end; end; procedure TecSyntAnalyzer.SubLexRuleChanged(Sender: TCollection; Item: TSyntCollectionItem); begin DetectBlockSeparate; ClearClientContents; Change; end; procedure TecSyntAnalyzer.AddMasterLexer(SyntAnal: TecSyntAnalyzer); begin if Assigned(SyntAnal) and (SyntAnal <> Self) and (FMasters.IndexOf(SyntAnal) = -1) then begin FMasters.Add(SyntAnal); SyntAnal.FreeNotification(Self); end; end; procedure TecSyntAnalyzer.RemoveMasterLexer(SyntAnal: TecSyntAnalyzer); begin FMasters.Remove(SyntAnal); end; procedure TecSyntAnalyzer.TokenRuleChanged(Sender: TCollection; Item: TSyntCollectionItem); begin DetectBlockSeparate; ClearClientContents; Change; end; procedure TecSyntAnalyzer.SetTokenTypeNames(const Value: TStrings); begin FTokenTypeNames.Assign(Value); end; procedure TecSyntAnalyzer.Change; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TecSyntAnalyzer.SetSearchMatch(const Value: TecSyntaxFormat); begin if FSearchMatch = Value then Exit; FSearchMatch := Value; UpdateClients; Change; end; procedure TecSyntAnalyzer.SetMarkedBlock(const Value: TecSyntaxFormat); begin if FMarkedBlock = Value then Exit; FMarkedBlock := Value; UpdateClients; Change; end; procedure TecSyntAnalyzer.SetCurrentLine(const Value: TecSyntaxFormat); begin if FCurrentLine = Value then Exit; FCurrentLine := Value; UpdateClients; Change; end; procedure TecSyntAnalyzer.SetDefStyle(const Value: TecSyntaxFormat); begin if FDefStyle = Value then Exit; FDefStyle := Value; UpdateClients; Change; end; function TecSyntAnalyzer.GetStyleName(const AName: string; const AStyle: TecSyntaxFormat): string; begin if csLoading in ComponentState then Result := AName else if Assigned(AStyle) then Result := AStyle.DisplayName else Result := ''; end; function TecSyntAnalyzer.GetMarkedBlockName: string; begin Result := GetStyleName(FMarkedBlockName, FMarkedBlock); end; procedure TecSyntAnalyzer.SetMarkedBlockName(const Value: string); begin if csLoading in ComponentState then FMarkedBlockName := Value else MarkedBlock := TecSyntaxFormat(FFormats.ItemByName(Value)); end; function TecSyntAnalyzer.GetSearchMatchStyle: string; begin Result := GetStyleName(FSearchMatchName, FSearchMatch); end; procedure TecSyntAnalyzer.SetSearchMatchStyle(const Value: string); begin if csLoading in ComponentState then FSearchMatchName := Value else FSearchMatch := TecSyntaxFormat(FFormats.ItemByName(Value)); end; function TecSyntAnalyzer.GetCurrentLineStyle: string; begin Result := GetStyleName(FCurrentLineName, FCurrentLine); end; procedure TecSyntAnalyzer.SetCurrentLineStyle(const Value: string); begin if csLoading in ComponentState then FCurrentLineName := Value else FCurrentLine := TecSyntaxFormat(FFormats.ItemByName(Value)); end; function TecSyntAnalyzer.GetDefaultStyleName: string; begin Result := GetStyleName(FDefStyleName, FDefStyle); end; procedure TecSyntAnalyzer.SetDefaultStyleName(const Value: string); begin if csLoading in ComponentState then FDefStyleName := Value else FDefStyle := TecSyntaxFormat(FFormats.ItemByName(Value)); end; procedure TecSyntAnalyzer.SetNotes(const Value: TStrings); begin FNotes.Assign(Value); end; procedure TecSyntAnalyzer.SetInternal(const Value: boolean); begin FInternal := Value; end; procedure TecSyntAnalyzer.SetRestartFromLineStart(const Value: Boolean); begin FRestartFromLineStart := Value; end; procedure TecSyntAnalyzer.SetParseEndOfLine(const Value: Boolean); begin if FParseEndOfLine <> Value then begin FParseEndOfLine := Value; ClearClientContents; end; end; procedure TecSyntAnalyzer.CompileGramma; var i: integer; begin FGrammaParser.CompileGramma(FTokenTypeNames); for i := 0 to FBlockRules.Count - 1 do FBlockRules[i].FGrammaRule := FGrammaParser.ParserRuleByName(FBlockRules[i].FGrammaRuleName); end; procedure TecSyntAnalyzer.TokenNamesChanged(Sender: TObject); begin CompileGramma; Change; end; procedure TecSyntAnalyzer.SetGrammar(const Value: TGrammaAnalyzer); begin FGrammaParser.Assign(Value); CompileGramma; end; procedure TecSyntAnalyzer.GrammaChanged(Sender: TObject); begin CompileGramma; end; procedure TecSyntAnalyzer.SetLineComment(const Value: ecString); begin FLineComment := Value; end; function TecSyntAnalyzer.GetSeparateBlocks: Boolean; function HasStateModif(List: TCollection): Boolean; var i: integer; begin for i := 0 to List.Count - 1 do with TRuleCollectionItem(List.Items[i]) do if (StatesAdd <> 0) or (StatesRemove <> 0) then begin Result := True; Exit; end; Result := False; end; var i: integer; begin if FSeparateBlocks = 0 then begin Result := not FAlwaysSyncBlockAnal and not HasStateModif(FBlockRules) and not HasStateModif(FSubAnalyzers); if Result then for i := 0 to TokenRules.Count - 1 do if TokenRules[i].Block <> nil then begin Result := False; Break; end; if Result then for i := 0 to SubAnalyzers.Count - 1 do if (SubAnalyzers[i].SyntAnalyzer <> nil) and not SubAnalyzers[i].SyntAnalyzer.SeparateBlockAnalysis then begin Result := False; Break; end; if Result then FSeparateBlocks := 1 else FSeparateBlocks := 2; end else Result := FSeparateBlocks = 1; end; procedure TecSyntAnalyzer.DetectBlockSeparate; begin FSeparateBlocks := 0; end; procedure TecSyntAnalyzer.SetAlwaysSyncBlockAnal(const Value: Boolean); begin FAlwaysSyncBlockAnal := Value; if FAlwaysSyncBlockAnal and SeparateBlockAnalysis then begin DetectBlockSeparate; ClearClientContents; end; end; function TecSyntAnalyzer.GetCollapseStyleName: string; begin Result := GetStyleName(FCollapseStyleName, FCollapseStyle); end; procedure TecSyntAnalyzer.SetCollapseStyleName(const Value: string); begin if csLoading in ComponentState then FCollapseStyleName := Value else FCollapseStyle := TecSyntaxFormat(FFormats.ItemByName(Value)); end; procedure TecSyntAnalyzer.SetCollapseStyle(const Value: TecSyntaxFormat); begin if FCollapseStyle <> Value then begin FCollapseStyle := Value; UpdateClients; Change; end; end; { TecCodeTemplate } constructor TecCodeTemplate.Create(Collection: TCollection); begin inherited; FName:= ''; FDescription:= ''; FAdvanced:= false; FCode:= TStringList.Create; end; destructor TecCodeTemplate.Destroy; begin FreeAndNil(FCode); inherited; end; function TecCodeTemplate.GetDisplayName: string; begin Result := FName; end; { TecCodeTemplates } function TecCodeTemplates.Add: TecCodeTemplate; begin Result := TecCodeTemplate(inherited Add); end; constructor TecCodeTemplates.Create(AOwner: TPersistent); begin inherited Create(AOwner, TecCodeTemplate); end; function TecCodeTemplates.GetItem(Index: integer): TecCodeTemplate; begin Result := TecCodeTemplate(inherited Items[Index]); end; { TecSyntaxManager } function TecSyntaxManager.AddAnalyzer: TecSyntAnalyzer; begin Result := TLibSyntAnalyzer.Create(Owner); Result.Name := Result.GetUniqueName('SyntAnal'); Result.SetParentComponent(Self); FModified := True; end; procedure TecSyntaxManager.Clear; begin while FList.Count > 0 do begin TObject(FList[0]).Free; end; Changed; FModified := True; end; constructor TecSyntaxManager.Create(AOwner: TComponent); begin inherited; FList := TList.Create; FModified := False; end; destructor TecSyntaxManager.Destroy; begin FOnChange := nil; Clear; FreeAndNil(FList); inherited; end; procedure TecSyntaxManager.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; function TecSyntaxManager.GeItem(Index: integer): TecSyntAnalyzer; begin Result := TecSyntAnalyzer(FList[Index]); end; procedure TecSyntaxManager.GetChildren(Proc: TGetChildProc; Root: TComponent); var i: integer; begin if not (csDestroying in ComponentState) then for i := 0 to FList.Count - 1 do Proc(TComponent(FList[i])); end; function TecSyntaxManager.GetCount: integer; begin Result := FList.Count; end; procedure TecSyntaxManager.LoadFromFile(const FileName: string); begin Clear; inherited; Changed; FModified := False; end; procedure TecSyntaxManager.SaveToFile(const FileName: string); begin inherited; FModified := False; end; procedure TecSyntaxManager.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); FModified := True; end; procedure TecSyntaxManager.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; end; procedure TecSyntaxManager.SetCurrentLexer(const Value: TecSyntAnalyzer); begin if (FCurrentLexer <> Value) and ((Value = nil) or (FList.IndexOf(value) <> -1)) then begin FCurrentLexer := Value; end; end; function TecSyntaxManager.FindAnalyzer( const LexerName: string): TecSyntAnalyzer; var i: integer; begin for i := 0 to GetCount - 1 do if SameText(Analyzers[i].LexerName, LexerName) then begin Result := Analyzers[i]; Exit; end; Result := nil; end; procedure TecSyntaxManager.OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); var S: string; begin if not FIgnoreAll then begin if AnalyzerCount > 0 then S := 'Error in lexer: '+Analyzers[AnalyzerCount - 1].Name +'. ' else S := ''; S := S + Message; inherited OnReadError(Reader, S, Handled); end else inherited; end; { TLibSyntAnalyzer } constructor TLibSyntAnalyzer.Create(AOwner: TComponent); begin if Assigned(AOwner) and (AOwner is TecSyntaxManager) then inherited Create((AOwner as TecSyntaxManager).Owner) else inherited Create(AOwner); end; destructor TLibSyntAnalyzer.Destroy; begin if FParent <> nil then begin FParent.FList.Remove(Self); FParent := nil; end; inherited; end; function TLibSyntAnalyzer.GetParentComponent: TComponent; begin Result := FParent; end; function TLibSyntAnalyzer.HasParent: Boolean; begin Result := True; end; procedure TLibSyntAnalyzer.LoadFromStream(const Stream: TStream); begin inherited LoadFromStream(Stream); end; procedure TLibSyntAnalyzer.SetParentComponent(Value: TComponent); begin if FParent = Value then Exit; if FSkipNewName and (Value = nil) then Exit; if FParent <> nil then FParent.FList.Remove(Self); if (Value <> nil) and (Value is TecSyntaxManager) then begin FParent := TecSyntaxManager(Value); FParent.FList.Add(Self); end else FParent := nil; end; { TLoadableComponent } var CheckExistingName: Boolean = False; procedure TLoadableComponent.LoadFromFile(const FileName: string); var Stream: TFileStreamUTF8; begin FFileName := FileName; //AT Stream := TFileStreamUTF8.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally FreeAndNil(Stream); end; end; procedure TLoadableComponent.LoadFromResourceID(Instance: Cardinal; ResID: Integer; ResType: string); var Stream: TResourceStream; begin Stream := TResourceStream.CreateFromID(Instance, ResID, PChar(ResType)); try LoadFromStream(Stream); finally FreeAndNil(Stream); end; end; procedure TLoadableComponent.LoadFromResourceName(Instance: Cardinal; const ResName: string; ResType: string); var Stream: TResourceStream; begin Stream := TResourceStream.Create(Instance, ResName, PChar(ResType)); try LoadFromStream(Stream); finally FreeAndNil(Stream); end; end; procedure TLoadableComponent.LoadFromStream(const Stream: TStream); begin FSkipNewName := True; CheckExistingName := True; try FIgnoreAll := False; LoadComponentFromStream(Self, Stream, OnReadError); finally FSkipNewName := False; CheckExistingName := False; FFileName := FileName; end; end; function TLoadableComponent.NotStored: Boolean; begin Result := not FSaving; end; procedure TLoadableComponent.OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); begin // Handled := True; Handled := FIgnoreAll; if not Handled then case MessageDlg(Message + sLineBreak + 'Ignore this error?', mtError, [mbYes, mbNo, mbAll], 0) of mrYes: Handled := True; mrAll: begin Handled := True; FIgnoreAll := True; end; end; end; procedure TLoadableComponent.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStreamUTF8.Create(FileName, fmCreate); try SaveToStream(Stream); finally FreeAndNil(Stream); end; FFileName := FileName; end; procedure TLoadableComponent.SaveToStream(Stream: TStream); begin FSaving := True; try SaveComponentToStream(Self, Stream); finally FSaving := False; end; end; procedure TLoadableComponent.SetName(const NewName: TComponentName); var Base: string; n:integer; begin if not FSkipNewName then if CheckExistingName and (Owner.FindComponent(NewName) <> nil) then begin Base := ClassName; Delete(Base, 1, 1); n := 1; while Owner.FindComponent(Base + IntToStr(n)) <> nil do Inc(n); inherited SetName(Base + IntToStr(n)); end else inherited; end; { TecSubAnalyzerRule } constructor TecSubAnalyzerRule.Create(Collection: TCollection); begin inherited; FStartRegExpr := TecRegExpr.Create; FEndRegExpr := TecRegExpr.Create; SetDefaultModifiers(FStartRegExpr); SetDefaultModifiers(FEndRegExpr); end; destructor TecSubAnalyzerRule.Destroy; begin FreeAndNil(FStartRegExpr); FreeAndNil(FEndRegExpr); inherited; end; procedure TecSubAnalyzerRule.AssignTo(Dest: TPersistent); begin inherited; if Dest is TecSubAnalyzerRule then with Dest as TecSubAnalyzerRule do begin StartExpression := Self.StartExpression; EndExpression := Self.EndExpression; SyntAnalyzer := Self.SyntAnalyzer; FromTextBegin := Self.FromTextBegin; ToTextEnd := Self.ToTextEnd; IncludeBounds := Self.IncludeBounds; end; end; function TecSubAnalyzerRule.GetEndExpression: string; begin Result := FEndRegExpr.Expression; end; function TecSubAnalyzerRule.GetItemBaseName: string; begin Result := 'Sub lexer rule'; end; function TecSubAnalyzerRule.GetStartExpression: string; begin Result := FStartRegExpr.Expression; end; function TecSubAnalyzerRule.MatchStart(const Source: ecString; Pos: integer): integer; begin try Result := FStartRegExpr.MatchLength(Source, Pos); except Result := 0; end; end; function TecSubAnalyzerRule.MatchEnd(const Source: ecString; Pos: integer): integer; begin try Result := FEndRegExpr.MatchLength(Source, Pos); except Result := 0; end; end; procedure TecSubAnalyzerRule.SetEndExpression(const Value: string); begin FEndRegExpr.Expression := Value; Changed(False); end; procedure TecSubAnalyzerRule.SetStartExpression(const Value: string); begin FStartRegExpr.Expression := Value; Changed(False); end; procedure TecSubAnalyzerRule.SetSyntAnalyzer(const Value: TecSyntAnalyzer); var own: TecSyntAnalyzer; function IsLinked(SAnal: TecSyntAnalyzer): Boolean; var i: integer; begin for i := 0 to Collection.Count - 1 do if (Collection.Items[i] <> Self) and ((Collection.Items[i] as TecSubAnalyzerRule).SyntAnalyzer = SAnal) then begin Result := True; Exit; end; Result := False; end; begin if FSyntAnalyzer <> Value then begin own := (Collection as TSyntCollection).SyntOwner; if Assigned(FSyntAnalyzer) and (FSyntAnalyzer <> own) and not IsLinked(FSyntAnalyzer) then FSyntAnalyzer.RemoveMasterLexer(own); FSyntAnalyzer := Value; if Assigned(FSyntAnalyzer) and (FSyntAnalyzer <> own) and not IsLinked(FSyntAnalyzer) then FSyntAnalyzer.AddMasterLexer(own); Changed(False); end; end; procedure TecSubAnalyzerRule.SetFromTextBegin(const Value: Boolean); begin FFromTextBegin := Value; Changed(False); end; procedure TecSubAnalyzerRule.SetToTextEnd(const Value: Boolean); begin FToTextEnd := Value; Changed(False); end; procedure TecSubAnalyzerRule.SetIncludeBounds(const Value: Boolean); begin FIncludeBounds := Value; Changed(False); end; { TecSubAnalyzerRules } function TecSubAnalyzerRules.Add: TecSubAnalyzerRule; begin Result := TecSubAnalyzerRule(inherited Add); end; constructor TecSubAnalyzerRules.Create; begin inherited Create(TecSubAnalyzerRule); end; function TecSubAnalyzerRules.GetItem(Index: integer): TecSubAnalyzerRule; begin Result := TecSubAnalyzerRule(inherited Items[Index]); end; { TecSyntStyles } constructor TecSyntStyles.Create(AOwner: TComponent); begin inherited; FStyles := TecStylesCollection.Create; end; destructor TecSyntStyles.Destroy; begin FreeAndNil(FStyles); inherited; end; procedure TecSyntStyles.SetStyles(const Value: TecStylesCollection); begin FStyles.Assign(Value); end; initialization Classes.RegisterClass(TLibSyntAnalyzer); end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uJavaClass; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uError; type TConstBase = class; TConstArray = array of TConstBase; TConstBase = class private tag : integer; public procedure Read(Input : TStream); virtual; abstract; procedure set_ref(const objAry : TConstArray); virtual; function getString : string; virtual; end; TConstPool = class private constPoolCnt : integer; constPool : TConstArray; public constructor Create(Input : TStream); destructor Destroy; override; function ConstPoolElem(ix : integer) : TConstBase; private function allocConstEntry(tag : integer) : TConstBase; procedure resolveConstPool; procedure readConstPool(Input : TStream); end; TConstUtf8 = class(TConstBase) private str : string; public procedure Read(Input : TStream); override; function GetString : string; override; end; TConstClass_or_String = class(TConstBase) private index : integer; Utf8 : TConstUtf8; public procedure Read(Input : TStream); override; procedure set_ref(const objAry : TConstArray); override; function GetString : string; override; end; TConstLongConvert = class(TConstBase) private function toLong(h,l : integer) : int64; protected function readLong(Input : TStream) : int64; end; TConstDouble = class(TConstLongConvert) private d : double; public procedure Read(Input : TStream); override; end; TConstFloat = class(TConstBase) private f : single; public procedure Read(Input : TStream); override; end; TConstInt = class(TConstBase) private val : integer; public procedure Read(Input : TStream); override; end; TConstLong = class(TConstLongConvert) private longVal : int64; public procedure Read(Input : TStream); override; end; TConstName_and_Type_info = class(TConstClass_or_String) private descriptor_index : integer; descriptor_Utf8 : TConstUtf8; public procedure Read(Input : TStream); override; procedure set_ref(const objAry : TConstArray); override; end; TConstRef = class(TConstBase) private index,name_and_type_index : integer; class_ref : TConstClass_or_String; name_ref : TConstName_and_Type_info; public procedure Read(Input : TStream); override; procedure set_ref(const objAry : TConstArray); override; end; TAccData = class public class function isPublic(Val : integer) : boolean; class function isPrivate(Val : integer) : boolean; class function isProtected(Val : integer) : boolean; class function isStatic(Val : integer) : boolean; class function isFinal(Val : integer) : boolean; class function isSync(Val : integer) : boolean; class function isSuper(Val : integer) : boolean; class function isVolatile(Val : integer) : boolean; class function isTransient(Val : integer) : boolean; class function isNative(Val : integer) : boolean; class function isInterface(Val : integer) : boolean; class function isAbstract(Val : integer) : boolean; class function isStrict(Val : integer) : boolean; end; TObjNameFormat = class public class function ToDotSeparator(SlashName : string) : string; end; TAttrInfo = class private AttrName : string; Len : integer; public constructor Create(Name : string; Length : integer); function GetName : string; end; TAttrInfoArray = array of TAttrInfo; TAttrFactory = class private class procedure Skip_data(len : integer; Input : TStream); public class function AllocAttr(Input : TStream; constPoolSec : TConstPool) : TAttrInfo; end; TClassFileHeader = class private magic : longword; minor_version : shortint; major_version : shortint; public constructor Create(Input : TStream); end; TClassDeclSec = class public accessFlags : integer; thisClass : TConstBase; superClass : TConstBase; interfaces : TConstArray; public constructor Create(Input : TStream; ConstPoolSec : TConstPool); function GetClassName : string; end; TFieldInfo = class public access_flags : integer; name : TConstUtf8; descriptor : TConstUtf8 ; attributes : TAttrInfoArray; public constructor Create(Input : TStream; constPoolSec : TConstPool); end; TFieldInfoArray = array of TFieldInfo; TClassFieldSec = class public classFields : TFieldInfoArray; public constructor Create(Input : TStream; constPoolSec : TConstPool); end; TMethodInfo = class public access_flags : integer; name : TConstUtf8 ; descriptor : TConstUtf8 ; attributes : TAttrInfoArray; public constructor Create(Input : TStream; constPoolSec : TConstPool); function isConstructor : boolean; end; TMethodInfoArray = array of TMethodInfo; TClassMethodSec = class public classMethods : TMethodInfoArray; public constructor Create(Input : TStream; constPoolSec : TConstPool; AClassName : string); destructor Destroy; override; end; TClassAttrSec = class private classAttrTab : TAttrInfoArray; public constructor Create(Input : TStream; constPoolSec : TConstPool); end; TClassFile = class public header : TClassFileHeader; classConstPool : TConstPool; classDecl : TClassDeclSec; classFields : TClassFieldSec; classMethods : TClassMethodSec; classAttrs : TClassAttrSec; clsName : string; public constructor Create(Input : TStream); destructor Destroy; override; end; implementation const ACC_PUBLIC : word = $0001; ACC_PRIVATE : word = $0002; ACC_PROTECTED : word = $0004; ACC_STATIC : word = $0008; ACC_FINAL : word = $0010; ACC_SYNC : word = $0020; ACC_VOLATILE : word = $0040; ACC_TRANSIENT : word = $0080; ACC_NATIVE : word = $0100; ACC_INTERFACE : word = $0200; ACC_ABSTRACT : word = $0400; ACC_STRICT : word = $0800; CONSTANT_Class = 7; CONSTANT_Fieldref = 9; CONSTANT_Methodref = 10; CONSTANT_InterfaceMethodref = 11; CONSTANT_String = 8; CONSTANT_Integer = 3; CONSTANT_Float = 4; CONSTANT_Long = 5; CONSTANT_Double = 6; CONSTANT_NameAndType = 12; CONSTANT_Utf8 = 1; function ReadU1(Input: TStream): integer; var ByteVal : byte; begin Input.Read(ByteVal,1); Result := ByteVal; end; function ReadU2(Input: TStream): integer; var tmp : array[0..1] of byte; begin Input.Read(tmp{%H-},2); Result := (tmp[0] shl 8) or tmp[1]; end; function ReadU4(Input: TStream): longword; var tmp : array[0..3] of byte; begin // $BEBAFECA Input.Read(tmp{%H-},4); Result := (tmp[0] shl 24) or (tmp[1] shl 16) or (tmp[2] shl 8) or tmp[3]; end; { TClassFileHeader } constructor TClassFileHeader.Create(Input: TStream); begin magic := readU4( Input ); Assert(Magic=$CAFEBABE); minor_version := readU2( Input ); major_version := readU2( Input ); end; { TClassDeclSec } constructor TClassDeclSec.Create(Input: TStream; ConstPoolSec: TConstPool); var thisClassIx, superClassIx, interfaceCnt, ix, i : integer; begin accessFlags := readU2( Input ); thisClassIx := readU2( Input ); superClassIx := readU2( Input ); thisClass := constPoolSec.constPoolElem( thisClassIx ); superClass := constPoolSec.constPoolElem( superClassIx ); interfaceCnt := readU2( Input ); if (interfaceCnt > 0) then begin SetLength(interfaces,interfaceCnt); for I := 0 to interfaceCnt-1 do begin ix := readU2( Input ); interfaces[ i ] := constPoolSec.constPoolElem( ix ); end; end; end; function TClassDeclSec.GetClassName: string; var name : string; begin if Assigned(thisClass) then if (thisClass is TConstClass_or_String) then name := TObjNameFormat.toDotSeparator( thisClass.getString ); Result := Name; end; { TFieldInfo } constructor TFieldInfo.Create(Input: TStream; constPoolSec: TConstPool); var name_index,desc_index,attr_cnt,I : integer; obj : TConstBase; begin access_flags := readU2( Input ); name_index := readU2( Input ); desc_index := readU2( Input ); attr_cnt := readU2( Input ); obj := constPoolSec.constPoolElem( name_index ); if Assigned(obj) and (obj is TConstUtf8) then Name := obj as TConstUtf8; obj := constPoolSec.constPoolElem( desc_index ); if Assigned(obj) and (obj is TConstUtf8) then descriptor := obj as TConstUtf8; if (attr_cnt > 0) then begin SetLength(attributes,attr_cnt); for I := 0 to attr_cnt-1 do attributes[i] := TAttrFactory.allocAttr( Input, constPoolSec ); end; end; { TClassFieldSec } constructor TClassFieldSec.Create(Input: TStream; constPoolSec: TConstPool); var field_cnt,i : integer; begin field_cnt := readU2( Input ); if (field_cnt > 0) then SetLength(classFields,field_cnt); for I := 0 to field_cnt-1 do classFields[i] := TFieldInfo.Create( Input, constPoolSec ); end; { TMethodInfo } constructor TMethodInfo.Create(Input: TStream; constPoolSec: TConstPool); var name_index,desc_index,attr_cnt,I : integer; obj : TConstBase; begin access_flags := readU2( Input ); name_index := readU2( Input ); desc_index := readU2( Input ); attr_cnt := readU2( Input ); obj := constPoolSec.constPoolElem( name_index ); if Assigned(obj) and (obj is TConstUtf8) then name := obj as TConstUtf8; obj := constPoolSec.constPoolElem( desc_index ); if Assigned(obj) and (obj is TConstUtf8) then descriptor := obj as TConstUtf8; if (attr_cnt > 0) then begin SetLength(attributes,attr_cnt); for I := 0 to attr_cnt-1 do attributes[i] := TAttrFactory.allocAttr( Input, constPoolSec ); end; end; function TMethodInfo.isConstructor: boolean; begin Result := (name.getString()='<init>'); end; { TClassMethodSec } constructor TClassMethodSec.Create(Input: TStream; constPoolSec: TConstPool; AClassName: string); var methodCnt,I : integer; begin methodCnt := readU2(Input); if (methodCnt > 0) then SetLength(classMethods,methodCnt); for I := 0 to methodCnt-1 do classMethods[i] := TMethodInfo.Create( Input, constPoolSec ); end; destructor TClassMethodSec.Destroy; var I : integer; begin for I := 0 to High(classMethods) do if Assigned(ClassMethods[I]) then FreeAndNil(ClassMethods[I]); inherited; end; { TClassAttrSec } constructor TClassAttrSec.Create(Input: TStream; constPoolSec: TConstPool); var numAttr,I : integer; begin numAttr := readU2( Input ); if (numAttr > 0) then begin SetLength(classAttrTab,numAttr); for I := 0 to numAttr-1 do classAttrTab[i] := TAttrFactory.allocAttr( Input, constPoolSec ); end; end; { TClassFile } constructor TClassFile.Create(Input: TStream); begin try header := TClassFileHeader.Create( Input ); classConstPool := TConstPool.Create( Input ); classDecl := TClassDeclSec.Create( Input, classConstPool ); classFields := TClassFieldSec.Create(Input, classConstPool); clsName := classDecl.getClassName; classMethods := TClassMethodSec.Create(Input, classConstPool, clsName ); classAttrs := TClassAttrSec.Create(Input, classConstPool); finally Input.Free; end; end; destructor TClassFile.Destroy; begin if Assigned(Header) then FreeAndNil(header); if Assigned(classConstPool) then FreeAndNil(classConstPool); if Assigned(classDecl) then FreeAndNil(classDecl); if Assigned(classFields) then FreeAndNil(classFields); if Assigned(classMethods) then FreeAndNil(classMethods); if Assigned(classAttrs) then FreeAndNil(classAttrs); inherited; end; { TAttrInfo } constructor TAttrInfo.Create(Name: string; Length: integer); begin attrName := Name; len := length; end; function TAttrInfo.GetName: string; begin Result := attrName; end; { TAttrFactory } class function TAttrFactory.allocAttr(Input: TStream; constPoolSec: TConstPool): TAttrInfo; var length : integer; retObj : TAttrInfo; begin retObj := nil; ReadU2(Input); length := ReadU4(Input); //Skip all attributes skip_data(length,Input); Result := retObj; end; class procedure TAttrFactory.skip_data(len: integer; Input: TStream); begin if (Input.Position>=Input.Size) and (Len<>0) then raise Exception.Create('Unexpected end of file'); Input.Position := Input.Position + Len; end; { TConstBase } function TConstBase.getString: string; begin Result := '**noname'; end; procedure TConstBase.set_ref(const objAry: TConstArray); begin //nothing end; { TConstPool } function TConstPool.allocConstEntry(tag: integer): TConstBase; begin Result := nil; case Tag of CONSTANT_Utf8: Result := TConstUtf8.Create; CONSTANT_Integer: Result := TConstInt.Create; CONSTANT_Float: Result := TConstFloat.Create; CONSTANT_Long: Result := TConstLong.Create; CONSTANT_Double: Result := TConstDouble.Create; CONSTANT_Class, CONSTANT_String: Result := TConstClass_or_String.Create; CONSTANT_Fieldref, CONSTANT_Methodref, CONSTANT_InterfaceMethodref: Result := TConstRef.Create; CONSTANT_NameAndType: Result := TConstName_and_Type_info.Create; else ErrorHandler.Trace('allocConstEntry: bad tag value = ' + IntToStr(tag)); end; if Assigned(Result) then Result.Tag := Tag; end; function TConstPool.ConstPoolElem(ix: integer): TConstBase; begin Result := nil; if (ix>0) and (ix<Length(constPool)) then Result := constPool[ix]; end; constructor TConstPool.Create(Input: TStream); begin constPoolCnt := readU2(Input); SetLength(constPool,constPoolCnt); readConstPool(Input); resolveConstPool; end; destructor TConstPool.Destroy; var I : integer; begin for I:=0 to High(ConstPool) do if Assigned(ConstPool[I]) then FreeAndNil(ConstPool[I]); inherited; end; procedure TConstPool.readConstPool(Input: TStream); var i,tag : integer; constObj : TConstBase; begin I := 1; while I<constPoolCnt do begin Tag := ReadU1(Input); if (Tag > 0) then begin constObj := allocConstEntry( tag ); constObj.read( Input ); constPool[i] := constObj; if (constObj is TConstLong) or (constObj is TConstDouble) then begin Inc(I); constPool[i] := nil; end; end else ; //ErrorHandler.Trace('tag == 0'); Inc(I); end; end; procedure TConstPool.resolveConstPool; var I : integer; begin //Index 0 is not used for I:=1 to constPoolCnt-1 do if Assigned(constPool[I]) then constPool[I].set_ref(constPool); end; { TConstClass_or_String } function TConstClass_or_String.GetString: string; begin Result := Utf8.GetString; end; procedure TConstClass_or_String.Read(Input: TStream); begin index := readU2( Input ); end; procedure TConstClass_or_String.set_ref(const objAry: TConstArray); var tmp : TConstBase; begin tmp := objAry[ index ]; if (tmp is TConstUtf8) then Utf8 := tmp as TConstUtf8 else ;//ErrorHandler.Trace('not utf8'); end; { TConstLongConvert } function TConstLongConvert.readLong(Input: TStream): int64; var h,l : integer; begin h := readU4(Input); l := readU4(Input); Result := toLong(h,l); end; function TConstLongConvert.toLong(h, l: integer): int64; begin Result := (h shl 32) or l; end; { TConstDouble } procedure TConstDouble.Read(Input: TStream); var I : int64; begin //Is this cast ok? I := ReadLong(Input); Move(I,D,SizeOf(D)); end; { TConstFloat } procedure TConstFloat.Read(Input: TStream); var L : longword; begin L := ReadU4(Input); //Is this cast ok? Move(L,F,SizeOf(F)); end; { TConstInt } procedure TConstInt.Read(Input: TStream); var L : longword; begin L := ReadU4(Input); Val := L; end; { TConstLong } procedure TConstLong.Read(Input: TStream); begin longVal := ReadLong(Input); end; { TConstName_and_Type_info } procedure TConstName_and_Type_info.Read(Input: TStream); begin inherited read(Input); descriptor_index := readU2(Input); end; procedure TConstName_and_Type_info.set_ref(const objAry: TConstArray); var tmp : TConstBase; begin inherited set_ref( objAry ); Tmp := objAry[ descriptor_index ]; if (tmp is TConstUtf8) then descriptor_Utf8 := tmp as TConstUtf8 else ; //ErrorHandler.Trace('utf8'); end; { TConstRef } procedure TConstRef.Read(Input: TStream); begin index := readU2( Input ); name_and_type_index := readU2( Input ); end; procedure TConstRef.set_ref(const objAry: TConstArray); var tmp : TConstBase; begin Tmp := objAry[ index ]; if (tmp is TConstClass_or_String) then class_ref := tmp as TconstClass_or_String else ; //ErrorHandler.Trace('nix'); Tmp := objAry[ name_and_type_index ]; if (tmp is TConstName_and_Type_info) then name_ref := tmp as TConstName_and_Type_info else ;//ErrorHandler.Trace('nix'); end; { TConstUtf8 } procedure TConstUtf8.Read(Input: TStream); var one_char : word; len, charCnt : integer; one_byte,first_byte : byte; tmp : word; begin len := readU2( Input ); charCnt := 0; while (charCnt < len) do begin one_byte := readU1( Input ); Inc(charCnt); if ((one_byte shr 7) = 1) then begin tmp := (one_byte and $3f); // Bits 5..0 (six bits) first_byte := one_byte; one_byte := readU1( Input ); Inc(charCnt); tmp := (tmp or ((one_byte and $3f) shl 6)); if ((first_byte shr 4) = 2+4+8) then begin one_byte := readU1( Input ); Inc(charCnt); one_byte := (one_byte and $0F); tmp := (tmp or (one_byte shl 12)); end; one_char := tmp; end else one_char := one_byte; Str := Str + char(Lo(One_Char)); end; end; function TConstUtf8.GetString: string; begin Result := str; end; { TAccData } class function TAccData.isAbstract(Val: integer): boolean; begin Result := (Val and ACC_ABSTRACT) <> 0; end; class function TAccData.isFinal(Val: integer): boolean; begin Result := (Val and ACC_FINAL) <> 0; end; class function TAccData.isInterface(Val: integer): boolean; begin Result := (Val and ACC_INTERFACE) <> 0; end; class function TAccData.isNative(Val: integer): boolean; begin Result := (Val and ACC_NATIVE) <> 0; end; class function TAccData.isPrivate(Val: integer): boolean; begin Result := (Val and ACC_PRIVATE) <> 0; end; class function TAccData.isProtected(Val: integer): boolean; begin Result := (Val and ACC_PROTECTED) <> 0; end; class function TAccData.isPublic(Val: integer): boolean; begin Result := (Val and ACC_PUBLIC) <> 0; end; class function TAccData.isStatic(Val: integer): boolean; begin Result := (Val and ACC_STATIC) <> 0; end; class function TAccData.isStrict(Val: integer): boolean; begin Result := (Val and ACC_STRICT) <> 0; end; class function TAccData.isSuper(Val: integer): boolean; begin Result := (Val and ACC_SYNC) <> 0; //sync and super share the same bit-flag end; class function TAccData.isSync(Val: integer): boolean; begin Result := (Val and ACC_SYNC) <> 0; end; class function TAccData.isTransient(Val: integer): boolean; begin Result := (Val and ACC_TRANSIENT) <> 0; end; class function TAccData.isVolatile(Val: integer): boolean; begin Result := (Val and ACC_VOLATILE) <> 0; end; { TObjNameFormat } class function TObjNameFormat.toDotSeparator(slashName: string): string; var I : integer; Ch : char; begin Result := ''; for I:=1 to Length(SlashName) do begin ch := SlashName[I]; if ch='/' then Result := Result + '.' else if ch<>';' then Result := Result + ch; end; end; end.
unit LrTreeData; interface uses SysUtils, Classes, Contnrs; type TLrTreeLeaf = class; TLrSaveItemEvent = procedure(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean) of object; // TLrTreeLeaf = class(TComponent) private FDisplayName: string; FOnChange: TNotifyEvent; FOnSaveItem: TLrSaveItemEvent; FParent: TLrTreeLeaf; FUpdating: Integer; FUpdateChange: Boolean; protected function GetCount: Integer; virtual; function GetDisplayName: string; virtual; function GetItems(inIndex: Integer): TLrTreeLeaf; virtual; procedure Change; virtual; procedure SetDisplayName(const Value: string); virtual; procedure SetOnChange(const Value: TNotifyEvent); procedure SetParent(const Value: TLrTreeLeaf); public constructor Create(inOwner: TComponent); overload; override; constructor Create; reintroduce; overload; virtual; procedure BeginUpdate; procedure EndUpdate; procedure LoadFromFile(const inFilename: string); virtual; procedure LoadFromStream(inStream: TStream); virtual; procedure SaveToFile(const inFilename: string); virtual; procedure SaveToStream(inStream: TStream); virtual; property Count: Integer read GetCount; property Items[inIndex: Integer]: TLrTreeLeaf read GetItems; default; property OnChange: TNotifyEvent read FOnChange write SetOnChange; property OnSaveItem: TLrSaveItemEvent read FOnSaveItem write FOnSaveItem; property Parent: TLrTreeLeaf read FParent write SetParent; published property DisplayName: string read GetDisplayName write SetDisplayName; end; // TLrTreeNode = class(TLrTreeLeaf) protected function GetChildOwner: TComponent; override; function GetCount: Integer; override; function GetItems(inIndex: Integer): TLrTreeLeaf; override; function ShouldWriteItem(inIndex: Integer): Boolean; virtual; procedure Clear; virtual; procedure DoOnSaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); procedure ItemChange(inSender: TObject); virtual; procedure ItemSaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; public function Find(const inName: string): TLrTreeLeaf; function GetUniqueName(const inName: string): string; procedure Add(inItem: TLrTreeLeaf); virtual; procedure LoadFromStream(inStream: TStream); override; procedure Remove(inItem: TLrTreeLeaf); virtual; procedure SaveToStream(inStream: TStream); override; end; // TLrTree = class(TLrTreeNode) end; implementation uses LrVclUtils; { TLrTreeLeaf } procedure TLrTreeLeaf.BeginUpdate; begin Inc(FUpdating); end; procedure TLrTreeLeaf.Change; begin FUpdateChange := (FUpdating > 0); if not FUpdateChange and Assigned(OnChange) then OnChange(Self); end; constructor TLrTreeLeaf.Create; begin inherited Create(nil); end; constructor TLrTreeLeaf.Create(inOwner: TComponent); begin Create; // In general, inOnwer <> nil only when streaming if (inOwner <> nil) and (inOwner is TLrTreeNode) then TLrTreeNode(inOwner).Add(Self); end; procedure TLrTreeLeaf.EndUpdate; begin Dec(FUpdating); if FUpdateChange and (FUpdating = 0) then Change; end; function TLrTreeLeaf.GetCount: Integer; begin Result := 0; end; function TLrTreeLeaf.GetDisplayName: string; begin Result := FDisplayName end; function TLrTreeLeaf.GetItems(inIndex: Integer): TLrTreeLeaf; begin Result := nil; end; procedure TLrTreeLeaf.LoadFromFile(const inFilename: string); var s: TFileStream; begin if FileExists(inFilename) then begin s := TFileStream.Create(inFilename, fmOpenRead); try LoadFromStream(s); finally s.Free; end; end; end; procedure TLrTreeLeaf.LoadFromStream(inStream: TStream); begin // end; procedure TLrTreeLeaf.SaveToFile(const inFilename: string); var s: TFileStream; begin s := TFileStream.Create(inFilename, fmCreate); try SaveToStream(s); finally s.Free; end; end; procedure TLrTreeLeaf.SaveToStream(inStream: TStream); begin // end; procedure TLrTreeLeaf.SetDisplayName(const Value: string); begin FDisplayName := Value; end; procedure TLrTreeLeaf.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TLrTreeLeaf.SetParent(const Value: TLrTreeLeaf); begin FParent := Value; end; { TLrTreeNode } procedure TLrTreeNode.Clear; begin DestroyComponents; end; procedure TLrTreeNode.DoOnSaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); begin if Assigned(OnSaveItem) then OnSaveItem(inSender, inIndex, inAllow); end; function TLrTreeNode.ShouldWriteItem(inIndex: Integer): Boolean; begin Result := true; DoOnSaveItem(Self, inIndex, Result); end; procedure TLrTreeNode.GetChildren(Proc: TGetChildProc; Root: TComponent); var i: Integer; begin for i := 0 to Pred(Count) do if ShouldWriteItem(i) then Proc(Items[i]); end; function TLrTreeNode.GetChildOwner: TComponent; begin Result := Self; end; procedure TLrTreeNode.SaveToStream(inStream: TStream); begin LrSaveComponentToStream(Self, inStream); end; procedure TLrTreeNode.LoadFromStream(inStream: TStream); begin Clear; LrLoadComponentFromStream(Self, inStream); end; function TLrTreeNode.GetCount: Integer; begin Result := ComponentCount; end; function TLrTreeNode.GetItems(inIndex: Integer): TLrTreeLeaf; begin Result := TLrTreeLeaf(Components[inIndex]); end; procedure TLrTreeNode.Add(inItem: TLrTreeLeaf); function RandomIdent: string; begin Result := '_' + IntToHex(Random($FFFF), 4); end; begin while (inItem.Name = '') or (Find(inItem.Name) <> nil) do inItem.Name := RandomIdent; inItem.Parent := Self; inItem.OnChange := ItemChange; inItem.OnSaveItem := ItemSaveItem; InsertComponent(inItem); Change; end; procedure TLrTreeNode.Remove(inItem: TLrTreeLeaf); begin inItem.Parent := nil; inItem.OnChange := nil; RemoveComponent(inItem); Change; end; procedure TLrTreeNode.ItemChange(inSender: TObject); begin Change; end; procedure TLrTreeNode.ItemSaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); begin DoOnSaveItem(inSender, inIndex, inAllow); end; function TLrTreeNode.Find(const inName: string): TLrTreeLeaf; var i: Integer; begin Result := TLrTreeLeaf(FindComponent(inName)); if Result = nil then for i := 0 to Pred(Count) do if Items[i] is TLrTreeNode then begin Result := TLrTreeNode(Items[i]).Find(inName); if Result <> nil then break; end; end; function TLrTreeNode.GetUniqueName(const inName: string): string; var i: Integer; begin if Find(inName) = nil then Result := inName else begin i := 0; repeat Inc(i); Result := inName + IntToStr(i); until Find(Result) = nil; end; end; end.
unit HomeLibrary_EditorForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, MySkinCtrls, MySkinEditors, MySkinListView, HomeLibrary_Query, ActnList, MySkinButtons, MySkinGroups, MySkinEngine; type { TEditorForm } TEditorForm = class(TMyForm) slbBookInfo: TMySkinLabel; slbName: TMySkinLabel; seName: TMySkinEdit; slbYear: TMySkinLabel; ssYear: TMySkinSpin; slbAuthor: TMySkinLabel; scbAuthor: TMySkinComboBox; slbPublisher: TMySkinLabel; scbPublisher: TMySkinComboBox; slbGroup: TMySkinLabel; scbGroup: TMySkinComboBox; slbPlace: TMySkinLabel; sePlace: TMySkinEdit; spButtons: TMySkinPanel; sbOK: TMySkinButton; sbCancel: TMySkinButton; alEditorKeys: TActionList; actEnter: TAction; actEscape: TAction; siLeft: TMySkinImage; procedure FormCreate(Sender: TObject); procedure seNameChange(Sender: TObject); procedure sbOKClick(Sender: TObject); procedure actEnterExecute(Sender: TObject); procedure actEscapeExecute(Sender: TObject); private procedure UpdateOkButton; public { Public declarations } end; var EditorForm: TEditorForm; implementation {$R *.dfm} uses HomeLibrary_MainForm; { TEditorForm } procedure TEditorForm.actEnterExecute(Sender: TObject); begin if sbOk.Enabled then sbOk.OnClick(Sender); end; procedure TEditorForm.actEscapeExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TEditorForm.FormCreate(Sender: TObject); var AItem: TMySkinListViewItem; begin Color := MainForm.stMain.ContentColor; MainForm.PopulateDistinctive(scbAuthor, 2); MainForm.PopulateDistinctive(scbPublisher, 4); MainForm.PopulateDistinctive(scbGroup, 6); if MainForm.FMode = emModify then begin AItem := MainForm.slvMain.Selected; seName.Text := AItem.Strings[0]; scbAuthor.Text := AItem.Strings[1]; ssYear.Value := StrToInt(AItem.Strings[2]); scbPublisher.Text := AItem.Strings[3]; sePlace.Text := AItem.Strings[4]; scbGroup.Text := AItem.Strings[5]; end; UpdateOkButton; end; procedure TEditorForm.sbOKClick(Sender: TObject); var AQuery, S: WideString; begin if MainForm.FMode = emInsert then S := SQL_InsertValue else S := SQL_UpdateValue; AQuery := Format(S, [seName.Text, scbAuthor.Text, ssYear.Value, scbPublisher.Text, sePlace.Text, scbGroup.Text]); if MainForm.FMode = emModify then AQuery := AQuery + IntToStr(MainForm.slvMain.Selected.Tag) + ';'; if MainForm.FBase.ExecQuery(AQuery) then MainForm.PopulateAll; ModalResult := mrOk; end; procedure TEditorForm.seNameChange(Sender: TObject); begin UpdateOkButton; end; procedure TEditorForm.UpdateOkButton; begin sbOK.Enabled := (seName.Text <> ''); end; end.
{ ****************************************************************************** } { * GBK media Data writen by QQ 600585@qq.com * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit GBKMediaCenter; {$INCLUDE zDefine.inc} interface uses Classes, DoStatusIO, CoreClasses, PascalStrings, UPascalStrings, MemoryStream64, ListEngine, TextDataEngine, UnicodeMixedLib, ObjectData, ObjectDataManager, ItemStream; type TDictStyle = (dsChar, dsPY, dsS2T, dsT2HK, dsT2S, dsT2TW, dsWordPart, dsWillVec, dsWordVec, dsBadEmotion, dsBadRep, dsGoodEmotion, dsGoodRep, dsBigKey, dsBigWord ); const cDictName: array [TDictStyle] of string = ( ('KEY-CHARACTER'), ('KEY-PY'), ('KEY-S2T'), ('KEY-T2HONGKONG'), ('KEY-T2S'), ('KEY-T2TW'), ('INI-WORDPART'), ('INI-WILL'), ('INI-VEC'), ('TEXT-BADEMOTION'), ('TEXT-DSBADREP'), ('TEXT-DSGOODEMOTION'), ('TEXT-DSGOODREP'), ('BIG-KEY'), ('BIG-TEXT')); procedure WaitGBKMediaInit; function GBKIsBusy: Boolean; function LoadAndMergeDict(const ROOT_: TPascalString): NativeInt; overload; function LoadAndMergeDict(const DBEng_: TObjectDataManager): NativeInt; overload; procedure InitEmptyDBFile(const dbFile: TPascalString); function InitEmptyDBStream: TMemoryStream64; function MergeTo(data: THashStringList; DestDict: TDictStyle): Integer; overload; function MergeTo(data: THashTextEngine; DestDict: TDictStyle): Integer; overload; function MergeTo(data: THashList; DestDict: TDictStyle): Integer; overload; function GBKStorePath(const ROOT_: TPascalString; const dict_: TDictStyle): TPascalString; function GBKDBStorePath(const ROOT_: TPascalString; const dict_: TDictStyle): TPascalString; function LoadDBPath(const dbEng: TObjectDataManager; const Path_, fileFilter: TPascalString; const mergeTo_: THashStringList): NativeInt; overload; function LoadDBPath(const dbEng: TObjectDataManager; const Path_, fileFilter: TPascalString; const mergeTo_: THashList): NativeInt; overload; function LoadDBPath(const dbEng: TObjectDataManager; const Path_, fileFilter: TPascalString; const mergeTo_: THashTextEngine): NativeInt; overload; function LoadPath(const Path_, fileFilter: TPascalString; const mergeTo_: THashStringList): NativeInt; overload; function LoadPath(const Path_, fileFilter: TPascalString; const mergeTo_: THashList): NativeInt; overload; function LoadPath(const Path_, fileFilter: TPascalString; const mergeTo_: THashTextEngine): NativeInt; overload; var // GBK base dict CharDict, PYDict, S2TDict, T2HKDict, T2SDict, T2TWDict: THashStringList; // word part WordPartDict: THashTextEngine; // will vec WillVecDict: THashTextEngine; // word vec WordVecDict: THashTextEngine; // bad emotion and rep dict BadEmotionDict, BadRepDict: THashList; // good emotion and rep dict GoodEmotionDict, GoodRepDict: THashList; // big key bigKeyDict: THashStringList; // big word bigWordDict: THashList; implementation uses Types; {$RESOURCE GBK.RES} var GBKMediaInited: TAtomBool; GBKProgressInfo: TAtomString; const cAllDict = [dsChar, dsPY, dsS2T, dsT2HK, dsT2S, dsT2TW, dsWordPart, dsWillVec, dsWordVec, dsBadEmotion, dsBadRep, dsGoodEmotion, dsGoodRep, dsBigKey, dsBigWord]; function MergeTo(data: THashStringList; DestDict: TDictStyle): Integer; begin Result := 0; case DestDict of dsChar: data.MergeTo(CharDict); dsPY: data.MergeTo(PYDict); dsS2T: data.MergeTo(S2TDict); dsT2HK: data.MergeTo(T2HKDict); dsT2S: data.MergeTo(T2SDict); dsT2TW: data.MergeTo(T2TWDict); dsBigKey: data.MergeTo(bigKeyDict); end; end; function MergeTo(data: THashTextEngine; DestDict: TDictStyle): Integer; begin Result := 0; case DestDict of dsWordPart: WordPartDict.Merge(data); dsWillVec: WillVecDict.Merge(data); dsWordVec: WordVecDict.Merge(data); end; end; function MergeTo(data: THashList; DestDict: TDictStyle): Integer; begin Result := 0; case DestDict of dsBadEmotion: data.MergeTo(BadEmotionDict); dsBadRep: data.MergeTo(BadRepDict); dsGoodEmotion: data.MergeTo(GoodEmotionDict); dsGoodRep: data.MergeTo(GoodRepDict); dsBigWord: data.MergeTo(bigWordDict); end; end; function GBKStorePath(const ROOT_: TPascalString; const dict_: TDictStyle): TPascalString; begin Result := umlCombinePath(ROOT_, cDictName[dict_]); end; function GBKDBStorePath(const ROOT_: TPascalString; const dict_: TDictStyle): TPascalString; begin Result := umlCombineUnixPath(ROOT_, cDictName[dict_]); end; function LoadDBPath(const dbEng: TObjectDataManager; const Path_, fileFilter: TPascalString; const mergeTo_: THashStringList): NativeInt; var ori: NativeInt; rs: TItemRecursionSearch; itmHnd: TItemHandle; m64: TMemoryStream64; begin Result := 0; if not dbEng.FieldExists(Path_) then exit; if dbEng.RecursionSearchFirst(Path_, '*', rs) then begin repeat if rs.ReturnHeader.ID = DB_Header_Item_ID then if umlMultipleMatch(fileFilter, rs.ReturnHeader.Name) then begin dbEng.ItemFastOpen(rs.ReturnHeader.CurrentHeader, itmHnd); m64 := TMemoryStream64.Create; dbEng.ItemReadToStream(itmHnd, m64); m64.Position := 0; // merge now ori := mergeTo_.Count; mergeTo_.LoadFromStream(m64); inc(Result, mergeTo_.Count - ori); disposeObject(m64); dbEng.ItemClose(itmHnd) end; until not dbEng.RecursionSearchNext(rs); end; end; function LoadDBPath(const dbEng: TObjectDataManager; const Path_, fileFilter: TPascalString; const mergeTo_: THashList): NativeInt; var j: Integer; ori: NativeInt; rs: TItemRecursionSearch; itmHnd: TItemHandle; m64: TMemoryStream64; lst: TListPascalString; begin Result := 0; if not dbEng.FieldExists(Path_) then exit; if dbEng.RecursionSearchFirst(Path_, '*', rs) then begin repeat if rs.ReturnHeader.ID = DB_Header_Item_ID then if umlMultipleMatch(fileFilter, rs.ReturnHeader.Name) then begin dbEng.ItemFastOpen(rs.ReturnHeader.CurrentHeader, itmHnd); m64 := TMemoryStream64.Create; dbEng.ItemReadToStream(itmHnd, m64); m64.Position := 0; // merge now lst := TListPascalString.Create; lst.LoadFromStream(m64); for j := 0 to lst.Count - 1 do mergeTo_.Add(lst[j], nil, True); disposeObject(lst); inc(Result, mergeTo_.Count - ori); disposeObject(m64); dbEng.ItemClose(itmHnd) end; until not dbEng.RecursionSearchNext(rs); end; end; function LoadDBPath(const dbEng: TObjectDataManager; const Path_, fileFilter: TPascalString; const mergeTo_: THashTextEngine): NativeInt; var ori: NativeInt; rs: TItemRecursionSearch; itmHnd: TItemHandle; m64: TMemoryStream64; te: THashTextEngine; begin Result := 0; if not dbEng.FieldExists(Path_) then exit; if dbEng.RecursionSearchFirst(Path_, '*', rs) then begin repeat if rs.ReturnHeader.ID = DB_Header_Item_ID then if umlMultipleMatch(fileFilter, rs.ReturnHeader.Name) then begin dbEng.ItemFastOpen(rs.ReturnHeader.CurrentHeader, itmHnd); m64 := TMemoryStream64.Create; dbEng.ItemReadToStream(itmHnd, m64); m64.Position := 0; // merge now te := THashTextEngine.Create; te.LoadFromStream(m64); mergeTo_.Merge(te); disposeObject(te); inc(Result, mergeTo_.TotalCount - ori); disposeObject(m64); dbEng.ItemClose(itmHnd) end; until not dbEng.RecursionSearchNext(rs); end; end; function LoadPath(const Path_, fileFilter: TPascalString; const mergeTo_: THashStringList): NativeInt; var fArry: U_StringArray; pArry: U_StringArray; i: Integer; ori: NativeInt; begin Result := 0; if not umlDirectoryExists(Path_) then exit; fArry := umlGetFileListWithFullPath(Path_); for i := low(fArry) to high(fArry) do if umlMultipleMatch(fileFilter, umlGetFileName(fArry[i])) then begin ori := mergeTo_.Count; mergeTo_.LoadFromFile(fArry[i]); inc(Result, mergeTo_.Count - ori); end; SetLength(fArry, 0); pArry := umlGetDirListWithFullPath(Path_); for i := low(pArry) to high(pArry) do inc(Result, LoadPath(pArry[i], fileFilter, mergeTo_)); SetLength(pArry, 0); end; function LoadPath(const Path_, fileFilter: TPascalString; const mergeTo_: THashList): NativeInt; var fArry: U_StringArray; pArry: U_StringArray; i, j: Integer; lst: TListPascalString; ori: NativeInt; begin Result := 0; if not umlDirectoryExists(Path_) then exit; fArry := umlGetFileListWithFullPath(Path_); for i := low(fArry) to high(fArry) do if umlMultipleMatch(fileFilter, umlGetFileName(fArry[i])) then begin ori := mergeTo_.Count; lst := TListPascalString.Create; lst.LoadFromFile(fArry[i]); for j := 0 to lst.Count - 1 do mergeTo_.Add(lst[j], nil, True); disposeObject(lst); inc(Result, mergeTo_.Count - ori); end; SetLength(fArry, 0); pArry := umlGetDirListWithFullPath(Path_); for i := low(pArry) to high(pArry) do inc(Result, LoadPath(pArry[i], fileFilter, mergeTo_)); SetLength(pArry, 0); end; function LoadPath(const Path_, fileFilter: TPascalString; const mergeTo_: THashTextEngine): NativeInt; var fArry: U_StringArray; pArry: U_StringArray; te: THashTextEngine; i: Integer; ori: NativeInt; begin Result := 0; if not umlDirectoryExists(Path_) then exit; fArry := umlGetFileListWithFullPath(Path_); for i := low(fArry) to high(fArry) do if umlMultipleMatch(fileFilter, umlGetFileName(fArry[i])) then begin ori := mergeTo_.TotalCount; te := THashTextEngine.Create; te.LoadFromFile(fArry[i]); mergeTo_.Merge(te); disposeObject(te); inc(Result, mergeTo_.TotalCount - ori); end; SetLength(fArry, 0); pArry := umlGetDirListWithFullPath(Path_); for i := low(pArry) to high(pArry) do inc(Result, LoadPath(pArry[i], fileFilter, mergeTo_)); SetLength(pArry, 0); end; function LoadAndMergeDict(const ROOT_: TPascalString): NativeInt; var dict_: TDictStyle; r: NativeInt; ph: TPascalString; begin WaitGBKMediaInit; GBKMediaInited.V := False; Result := 0; try for dict_ in cAllDict do begin ph := GBKStorePath(ROOT_, dict_); if not umlDirectoryExists(ph) then umlCreateDirectory(ph); r := 0; case dict_ of dsChar: r := LoadPath(ph, '*.txt', CharDict); dsPY: r := LoadPath(ph, '*.txt', PYDict); dsS2T: r := LoadPath(ph, '*.txt', S2TDict); dsT2HK: r := LoadPath(ph, '*.txt', T2HKDict); dsT2S: r := LoadPath(ph, '*.txt', T2SDict); dsT2TW: r := LoadPath(ph, '*.txt', T2TWDict); dsWordPart: r := LoadPath(ph, '*.ini;*.txt', WordPartDict); dsWillVec: r := LoadPath(ph, '*.ini;*.txt', WillVecDict); dsWordVec: r := LoadPath(ph, '*.ini;*.txt', WordVecDict); dsBadEmotion: r := LoadPath(ph, '*.txt', BadEmotionDict); dsBadRep: r := LoadPath(ph, '*.txt', BadRepDict); dsGoodEmotion: r := LoadPath(ph, '*.txt', GoodEmotionDict); dsGoodRep: r := LoadPath(ph, '*.txt', GoodRepDict); dsBigKey: r := LoadPath(ph, '*.txt', bigKeyDict); dsBigWord: r := LoadPath(ph, '*.txt', bigWordDict); end; DoStatus('%s loaded %d ...', [cDictName[dict_], r]); inc(Result, r); end; finally GBKMediaInited.V := True; end; end; function LoadAndMergeDict(const DBEng_: TObjectDataManager): NativeInt; var dict_: TDictStyle; r: NativeInt; ph: TPascalString; begin WaitGBKMediaInit; GBKMediaInited.V := False; Result := 0; try for dict_ in cAllDict do begin ph := GBKDBStorePath('/', dict_); if not DBEng_.FieldExists(ph) then DBEng_.CreateField(ph, ''); r := 0; case dict_ of dsChar: r := LoadDBPath(DBEng_, ph, '*.txt', CharDict); dsPY: r := LoadDBPath(DBEng_, ph, '*.txt', PYDict); dsS2T: r := LoadDBPath(DBEng_, ph, '*.txt', S2TDict); dsT2HK: r := LoadDBPath(DBEng_, ph, '*.txt', T2HKDict); dsT2S: r := LoadDBPath(DBEng_, ph, '*.txt', T2SDict); dsT2TW: r := LoadDBPath(DBEng_, ph, '*.txt', T2TWDict); dsWordPart: r := LoadDBPath(DBEng_, ph, '*.ini;*.txt', WordPartDict); dsWillVec: r := LoadDBPath(DBEng_, ph, '*.ini;*.txt', WillVecDict); dsWordVec: r := LoadDBPath(DBEng_, ph, '*.ini;*.txt', WordVecDict); dsBadEmotion: r := LoadDBPath(DBEng_, ph, '*.txt', BadEmotionDict); dsBadRep: r := LoadDBPath(DBEng_, ph, '*.txt', BadRepDict); dsGoodEmotion: r := LoadDBPath(DBEng_, ph, '*.txt', GoodEmotionDict); dsGoodRep: r := LoadDBPath(DBEng_, ph, '*.txt', GoodRepDict); dsBigKey: r := LoadDBPath(DBEng_, ph, '*.txt', bigKeyDict); dsBigWord: r := LoadDBPath(DBEng_, ph, '*.txt', bigWordDict); end; DoStatus('%s loaded %d ...', [cDictName[dict_], r]); inc(Result, r); end; finally GBKMediaInited.V := True; end; end; procedure InitEmptyDBFile(const dbFile: TPascalString); var m64: TMemoryStream64; begin with InitEmptyDBStream() do begin SaveToFile(dbFile); Free; end; end; function InitEmptyDBStream: TMemoryStream64; var dbEng: TObjectDataManager; dict_: TDictStyle; begin Result := TMemoryStream64.CustomCreate($FFFF); dbEng := TObjectDataManagerOfCache.CreateAsStream($FF, Result, '', DBmarshal.ID, False, True, False); for dict_ in cAllDict do dbEng.CreateField(GBKDBStorePath('/', dict_), ''); disposeObject(dbEng); end; function GetGBKTextEngineDict(dbEng: TObjectDataManagerOfCache; fn: U_String; hashSiz: NativeInt): THashTextEngine; var stream: TMemoryStream64; begin {$IFDEF initializationStatus} DoStatusNoLn('Load INI Dict %s', [fn.Text]); {$ENDIF initializationStatus} stream := TMemoryStream64.Create; dbEng.ItemReadToStream('/', fn, stream); stream.Position := 0; Result := THashTextEngine.Create(hashSiz); Result.LoadFromStream(stream); disposeObject(stream); {$IFDEF initializationStatus} DoStatusNoLn(' done.'); DoStatusNoLn; {$ENDIF initializationStatus} end; function GetGBKHashStringDict(dbEng: TObjectDataManagerOfCache; fn: U_String; hashSiz: NativeInt): THashStringList; var stream: TMemoryStream64; begin {$IFDEF initializationStatus} DoStatusNoLn('Load Hash Dict %s', [fn.Text]); {$ENDIF initializationStatus} stream := TMemoryStream64.Create; dbEng.ItemReadToStream('/', fn, stream); stream.Position := 0; Result := THashStringList.CustomCreate(hashSiz); Result.LoadFromStream(stream); disposeObject(stream); {$IFDEF initializationStatus} DoStatusNoLn(' done.'); DoStatusNoLn; {$ENDIF initializationStatus} end; function GetGBKHashDict(dbEng: TObjectDataManagerOfCache; fn: U_String; hashSiz: NativeInt): THashList; var stream: TMemoryStream64; lst: TListPascalString; i: Integer; begin {$IFDEF initializationStatus} DoStatusNoLn('Load Big Dict %s', [fn.Text]); {$ENDIF initializationStatus} stream := TMemoryStream64.Create; dbEng.ItemReadToStream('/', fn, stream); stream.Position := 0; Result := THashList.CustomCreate(hashSiz); lst := TListPascalString.Create; lst.LoadFromStream(stream); disposeObject(stream); for i := 0 to lst.Count - 1 do Result.Add(lst[i], nil, True); disposeObject(lst); {$IFDEF initializationStatus} DoStatusNoLn(' done.'); DoStatusNoLn; {$ENDIF initializationStatus} end; procedure InitGBKMediaThread(th: TCompute); var dbEng: TObjectDataManagerOfCache; rs: TCoreClassResourceStream; tmpStream_: TMemoryStream64; begin rs := TCoreClassResourceStream.Create(HInstance, 'GBK', RT_RCDATA); tmpStream_ := TMemoryStream64.Create; DecompressStream(rs, tmpStream_); disposeObject(rs); dbEng := TObjectDataManagerOfCache.CreateAsStream(tmpStream_, '', DBmarshal.ID, True, False, True); // base gbk dict CharDict := GetGBKHashStringDict(dbEng, 'CharDict.BuildIn', 20000); PYDict := GetGBKHashStringDict(dbEng, 'PYDict.BuildIn', 20000); S2TDict := GetGBKHashStringDict(dbEng, 'S2T.BuildIn', 20000); T2HKDict := GetGBKHashStringDict(dbEng, 'T2HK.BuildIn', 20000); T2SDict := GetGBKHashStringDict(dbEng, 'T2S.BuildIn', 20000); T2TWDict := GetGBKHashStringDict(dbEng, 'T2TW.BuildIn', 20000); // word part dict WordPartDict := GetGBKTextEngineDict(dbEng, 'WordPart.BuildIn', 50000); // will vec dict WillVecDict := GetGBKTextEngineDict(dbEng, 'WillVec.BuildIn', 5000); WordVecDict := GetGBKTextEngineDict(dbEng, 'WordVec.BuildIn', 5000); // emotion and rep dict BadEmotionDict := GetGBKHashDict(dbEng, 'BadEmotion.BuildIn', 20000); BadRepDict := GetGBKHashDict(dbEng, 'BadRep.BuildIn', 20000); GoodEmotionDict := GetGBKHashDict(dbEng, 'GoodEmotion.BuildIn', 20000); GoodRepDict := GetGBKHashDict(dbEng, 'GoodRep.BuildIn', 20000); // big key bigKeyDict := GetGBKHashStringDict(dbEng, 'MiniKey.BuildIn', 200 * 10000); // big word bigWordDict := GetGBKHashDict(dbEng, 'MiniDict.BuildIn', 200 * 10000); disposeObject(dbEng); GBKMediaInited.V := True; end; procedure FreeGBKMedia; begin WaitGBKMediaInit; disposeObject([WordPartDict]); disposeObject([WillVecDict, WordVecDict]); disposeObject([BadEmotionDict, BadRepDict, GoodEmotionDict, GoodRepDict]); disposeObject([CharDict, PYDict, S2TDict, T2HKDict, T2SDict, T2TWDict]); disposeObject(bigKeyDict); disposeObject(bigWordDict); end; procedure WaitGBKMediaInit; begin while not GBKMediaInited.V do CoreClasses.CheckThreadSynchronize(10); end; function GBKIsBusy: Boolean; begin Result := not GBKMediaInited.V; end; initialization GBKMediaInited := TAtomBool.Create(False); GBKProgressInfo := TAtomString.Create(''); TCompute.RunC({$IFDEF FPC}@{$ENDIF FPC}InitGBKMediaThread); finalization FreeGBKMedia; DisposeObjectAndNil(GBKMediaInited); DisposeObjectAndNil(GBKProgressInfo); end.
namespace com.example.android.jetboy; {* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *} interface uses android.app, android.os, android.util, android.view, android.widget; // Android JET demonstration code: // See the JetBoyView.java file for examples on the use of the JetPlayer class. type JetBoy = public class(Activity, View.OnClickListener) private // A handle to the thread that's actually running the animation. var mJetBoyThread: JetBoyThread; // A handle to the View in which the game is running. var mJetBoyView: JetBoyView; // the play start button var mButton: Button; // used to hit retry var mButtonRetry: Button; // the window for instructions and such var mTextView: TextView; // game window timer var mTimerView: TextView; public method onCreate(savedInstanceState: Bundle); override; method onPause; override; method onClick(v: View); method onKeyDown(keyCode: Integer; msg: KeyEvent): Boolean; override; method onKeyUp(keyCode: Integer; msg: KeyEvent): Boolean; override; method onTouchEvent(evt: MotionEvent): Boolean; override; end; implementation /// <summary> /// Required method from parent class /// </summary> /// <param name="savedInstanceState">The previous instance of this app</param> method JetBoy.onCreate(savedInstanceState: Bundle); begin inherited onCreate(savedInstanceState); ContentView := R.layout.main; // get handles to the JetView from XML and the JET thread. mJetBoyView := JetBoyView(findViewById(R.id.JetBoyView)); mJetBoyThread := mJetBoyView.getThread; // look up the happy shiny button mButton := Button(findViewById(R.id.Button01)); mButton.OnClickListener := self; mButtonRetry := Button(findViewById(R.id.Button02)); mButtonRetry.OnClickListener := self; // set up handles for instruction text and game timer text mTextView := TextView(findViewById(R.id.text)); mTimerView := TextView(findViewById(R.id.timer)); mJetBoyView.setTimerView(mTimerView); mJetBoyView.SetButtonView(mButtonRetry); mJetBoyView.SetTextView(mTextView); Log.w(&Class.Name, 'onCreate'); end; /// <summary> /// Called when activity is exiting /// </summary> method JetBoy.onPause; begin inherited; mJetBoyThread.pause end; /// <summary> /// Handles component interaction /// </summary> /// <param name="v">The object which has been clicked</param> method JetBoy.onClick(v: View); begin // this is the first screen if mJetBoyThread.getGameState = JetBoyThread.STATE_START then begin mButton.Text := 'PLAY!'; mTextView.Visibility := View.VISIBLE; mTextView.Text := R.string.helpText; mJetBoyThread.setGameState(JetBoyThread.STATE_PLAY) end else if mJetBoyThread.getGameState = JetBoyThread.STATE_PLAY then begin mButton.Visibility := View.INVISIBLE; mTextView.Visibility := View.INVISIBLE; mTimerView.Visibility := View.VISIBLE; mJetBoyThread.setGameState(JetBoyThread.STATE_RUNNING) end else if mButtonRetry.&equals(v) then begin mTextView.Text := R.string.helpText; mButton.Text := 'PLAY!'; mButtonRetry.Visibility := View.INVISIBLE; // mButtonRestart.Visibility := View.INVISIBLE; mTextView.Visibility := View.VISIBLE; mButton.Text := 'PLAY!'; mButton.Visibility := View.VISIBLE; mJetBoyThread.setGameState(JetBoyThread.STATE_PLAY) end else begin Log.d('JB VIEW', 'unknown click ' + v.Id); Log.d('JB VIEW', 'state is ' + mJetBoyThread.mState) end end; /// <summary> /// Standard override to get key-press events. /// </summary> /// <param name="keyCode"></param> /// <param name="msg"></param> /// <returns></returns> method JetBoy.onKeyDown(keyCode: Integer; msg: KeyEvent): Boolean; begin //NOTE: the original demo code did not check for the volume keys so they //were ignored during gameplay and the media volume could therefore not //be adjusted if keyCode in [KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_MUTE] then exit inherited onKeyDown(keyCode, msg) else exit mJetBoyThread.doKeyDown(keyCode, msg) end; /// <summary> /// Standard override for key-up. /// </summary> /// <param name="keyCode"></param> /// <param name="msg"></param> /// <returns></returns> method JetBoy.onKeyUp(keyCode: Integer; msg: KeyEvent): Boolean; begin if keyCode = KeyEvent.KEYCODE_BACK then exit inherited onKeyUp(keyCode, msg) else exit mJetBoyThread.doKeyUp(keyCode, msg) end; method JetBoy.onTouchEvent(evt: MotionEvent): Boolean; begin var action := evt.ActionMasked; if action in [MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP] then begin var key: Integer := KeyEvent.KEYCODE_DPAD_CENTER; if action = MotionEvent.ACTION_DOWN then onKeyDown(key, new KeyEvent(KeyEvent.ACTION_DOWN, key)) else //MotionEvent.ACTION_UP onKeyUp(key, new KeyEvent(KeyEvent.ACTION_UP, key)) end; exit true end; end.
{******************************************************************************} { } { Delphi JOSE Library } { Copyright (c) 2015-2021 Paolo Rossi } { https://github.com/paolo-rossi/delphi-jose-jwt } { } {******************************************************************************} { } { 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 JOSE.Signing.Base; interface uses System.SysUtils, System.StrUtils, IdGlobal, IdCTypes, IdSSLOpenSSLHeaders, JOSE.OpenSSL.Headers, JOSE.Encoding.Base64; type ESignException = class(Exception); TSigningBase = class protected //CERT const PEM_X509_CERTIFICATE: RawByteString = '-----BEGIN CERTIFICATE-----'; protected //RSA const PEM_PUBKEY_PKCS1: RawByteString = '-----BEGIN RSA PUBLIC KEY-----'; protected //ECDSA const PEM_PUBKEY: RawByteString = '-----BEGIN PUBLIC KEY-----'; const PEM_PRVKEY_PKCS8: RawByteString = '-----BEGIN PRIVATE KEY-----'; const PEM_PRVKEY_PKCS1: RawByteString = '-----BEGIN EC PRIVATE KEY-----'; class function LoadCertificate(const ACertificate: TBytes): PX509; public class procedure LoadOpenSSL; class function VerifyCertificate(const ACertificate: TBytes; AObjectID: Integer): Boolean; end; implementation class function TSigningBase.LoadCertificate(const ACertificate: TBytes): PX509; var LBio: PBIO; begin if not CompareMem(@PEM_X509_CERTIFICATE[1], @ACertificate[0], Length(PEM_X509_CERTIFICATE)) then raise ESignException.Create('[SSL] Not a valid X509 certificate'); LBio := BIO_new(BIO_s_mem); try BIO_write(LBio, @ACertificate[0], Length(ACertificate)); Result := PEM_read_bio_X509(LBio, nil, nil, nil); if Result = nil then raise ESignException.Create('[SSL] Error loading X509 certificate'); finally BIO_free(LBio); end; end; class procedure TSigningBase.LoadOpenSSL; begin if not IdSSLOpenSSLHeaders.Load then raise ESignException.Create('[SSL] Unable to load OpenSSL libraries'); if not JoseSSL.Load then raise ESignException.Create('[SSL] Unable to load OpenSSL libraries'); if @EVP_DigestVerifyInit = nil then raise ESignException.Create('[SSL] Please, use OpenSSL 1.0.0 or newer!'); end; class function TSigningBase.VerifyCertificate(const ACertificate: TBytes; AObjectID: Integer): Boolean; var LCer: PX509; LKey: PEVP_PKEY; LAlg: Integer; begin LoadOpenSSL; LCer := LoadCertificate(ACertificate); try LKey := X509_PUBKEY_get(LCer.cert_info.key); try LAlg := OBJ_obj2nid(LCer.cert_info.key.algor.algorithm); Result := Assigned(LCer) and Assigned(LKey) and (LAlg = AObjectID); finally EVP_PKEY_free(LKey); end; finally X509_free(LCer); end; end; end.
unit Chapter09._08_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, DeepStar.Utils; /// 300. Longest Increasing Subsequence /// https://leetcode.com/problems/longest-increasing-subsequence/description/ /// 记忆化搜索 /// 时间复杂度: O(n^2) /// 空间复杂度: O(n) type TSolution = class(TObject) public function LengthOfLIS(nums: TArr_int): integer; end; procedure Main; implementation procedure Main; begin with TSolution.Create do begin WriteLn(LengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])); Free; end; end; { TSolution } function TSolution.LengthOfLIS(nums: TArr_int): integer; var memo: TArr_int; // 以 nums[index] 为结尾的最长上升子序列的长度 function __getMaxLength__(index: integer): integer; var res, i: integer; begin if memo[index] <> -1 then Exit(memo[index]); res := 1; for i := 0 to index - 1 do begin if nums[index] > nums[i] then res := Max(res, 1 + __getMaxLength__(i)); end; memo[index] := res; Result := res; end; var res, i: integer; begin if Length(nums) = 0 then Exit(0); SetLength(memo, Length(nums)); TArrayUtils_int.FillArray(memo, -1); res := 1; for i := 0 to High(nums) do res := Max(res, __getMaxLength__(i)); Result := res; end; end.
// *************************************************************************** } // // Delphi MVC Framework // // Copyright (c) 2010-2020 Daniele Teti and the DMVCFramework Team // // https://github.com/danieleteti/delphimvcframework // // *************************************************************************** // // 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 EntitiesU; interface uses MVCFramework.Serializer.Commons, MVCFramework.ActiveRecord, System.Classes; type [MVCNameCase(ncLowerCase)] [MVCTable('Album')] TAlbum = class(TMVCActiveRecord) private [MVCTableField('AlbumId', [foPrimaryKey, foAutoGenerated])] fAlbumid: Integer; [MVCTableField('Title')] fTitle: String; [MVCTableField('ArtistId')] fArtistid: Integer; [MVCTableField('Column1')] fColumn1: TStream; public constructor Create; override; destructor Destroy; override; [MVCNameAs('AlbumId')] property Albumid: Integer read fAlbumid write fAlbumid; [MVCNameAs('Title')] property Title: String read fTitle write fTitle; [MVCNameAs('ArtistId')] property Artistid: Integer read fArtistid write fArtistid; [MVCNameAs('Column1')] property Column1: TStream read fColumn1 write fColumn1; end; [MVCNameCase(ncLowerCase)] [MVCTable('Artist')] TArtist = class(TMVCActiveRecord) private [MVCTableField('ArtistId', [foPrimaryKey, foAutoGenerated])] fArtistid: Integer; [MVCTableField('Name')] fName: String; public constructor Create; override; destructor Destroy; override; [MVCNameAs('ArtistId')] property Artistid: Integer read fArtistid write fArtistid; [MVCNameAs('Name')] property Name: String read fName write fName; end; [MVCNameCase(ncLowerCase)] [MVCTable('Customer')] TCustomer = class(TMVCActiveRecord) private [MVCTableField('CustomerId', [foPrimaryKey, foAutoGenerated])] fCustomerid: Integer; [MVCTableField('FirstName')] fFirstname: String; [MVCTableField('LastName')] fLastname: String; [MVCTableField('Company')] fCompany: String; [MVCTableField('Address')] fAddress: String; [MVCTableField('City')] fCity: String; [MVCTableField('State')] fState: String; [MVCTableField('Country')] fCountry: String; [MVCTableField('PostalCode')] fPostalcode: String; [MVCTableField('Phone')] fPhone: String; [MVCTableField('Fax')] fFax: String; [MVCTableField('Email')] fEmail: String; [MVCTableField('SupportRepId')] fSupportrepid: Integer; public constructor Create; override; destructor Destroy; override; [MVCNameAs('CustomerId')] property Customerid: Integer read fCustomerid write fCustomerid; [MVCNameAs('FirstName')] property Firstname: String read fFirstname write fFirstname; [MVCNameAs('LastName')] property Lastname: String read fLastname write fLastname; [MVCNameAs('Company')] property Company: String read fCompany write fCompany; [MVCNameAs('Address')] property Address: String read fAddress write fAddress; [MVCNameAs('City')] property City: String read fCity write fCity; [MVCNameAs('State')] property State: String read fState write fState; [MVCNameAs('Country')] property Country: String read fCountry write fCountry; [MVCNameAs('PostalCode')] property Postalcode: String read fPostalcode write fPostalcode; [MVCNameAs('Phone')] property Phone: String read fPhone write fPhone; [MVCNameAs('Fax')] property Fax: String read fFax write fFax; [MVCNameAs('Email')] property Email: String read fEmail write fEmail; [MVCNameAs('SupportRepId')] property Supportrepid: Integer read fSupportrepid write fSupportrepid; end; [MVCNameCase(ncLowerCase)] [MVCTable('Employee')] TEmployee = class(TMVCActiveRecord) private [MVCTableField('EmployeeId', [foPrimaryKey, foAutoGenerated])] fEmployeeid: Integer; [MVCTableField('LastName')] fLastname: String; [MVCTableField('FirstName')] fFirstname: String; [MVCTableField('Title')] fTitle: String; [MVCTableField('ReportsTo')] fReportsto: Integer; [MVCTableField('BirthDate')] fBirthdate: TDateTime; [MVCTableField('HireDate')] fHiredate: TDateTime; [MVCTableField('Address')] fAddress: String; [MVCTableField('City')] fCity: String; [MVCTableField('State')] fState: String; [MVCTableField('Country')] fCountry: String; [MVCTableField('PostalCode')] fPostalcode: String; [MVCTableField('Phone')] fPhone: String; [MVCTableField('Fax')] fFax: String; [MVCTableField('Email')] fEmail: String; public constructor Create; override; destructor Destroy; override; [MVCNameAs('EmployeeId')] property Employeeid: Integer read fEmployeeid write fEmployeeid; [MVCNameAs('LastName')] property Lastname: String read fLastname write fLastname; [MVCNameAs('FirstName')] property Firstname: String read fFirstname write fFirstname; [MVCNameAs('Title')] property Title: String read fTitle write fTitle; [MVCNameAs('ReportsTo')] property Reportsto: Integer read fReportsto write fReportsto; [MVCNameAs('BirthDate')] property Birthdate: TDateTime read fBirthdate write fBirthdate; [MVCNameAs('HireDate')] property Hiredate: TDateTime read fHiredate write fHiredate; [MVCNameAs('Address')] property Address: String read fAddress write fAddress; [MVCNameAs('City')] property City: String read fCity write fCity; [MVCNameAs('State')] property State: String read fState write fState; [MVCNameAs('Country')] property Country: String read fCountry write fCountry; [MVCNameAs('PostalCode')] property Postalcode: String read fPostalcode write fPostalcode; [MVCNameAs('Phone')] property Phone: String read fPhone write fPhone; [MVCNameAs('Fax')] property Fax: String read fFax write fFax; [MVCNameAs('Email')] property Email: String read fEmail write fEmail; end; [MVCNameCase(ncLowerCase)] [MVCTable('EmpView')] TEmpview = class(TMVCActiveRecord) private [MVCTableField('EmployeeId')] fEmployeeid: Integer; [MVCTableField('LastName')] fLastname: String; [MVCTableField('FirstName')] fFirstname: String; [MVCTableField('Title')] fTitle: String; [MVCTableField('ReportsTo')] fReportsto: Integer; [MVCTableField('BirthDate')] fBirthdate: TDateTime; [MVCTableField('HireDate')] fHiredate: TDateTime; [MVCTableField('Address')] fAddress: String; [MVCTableField('City')] fCity: String; [MVCTableField('State')] fState: String; [MVCTableField('Country')] fCountry: String; [MVCTableField('PostalCode')] fPostalcode: String; [MVCTableField('Phone')] fPhone: String; [MVCTableField('Fax')] fFax: String; [MVCTableField('Email')] fEmail: String; public constructor Create; override; destructor Destroy; override; [MVCNameAs('EmployeeId')] property Employeeid: Integer read fEmployeeid write fEmployeeid; [MVCNameAs('LastName')] property Lastname: String read fLastname write fLastname; [MVCNameAs('FirstName')] property Firstname: String read fFirstname write fFirstname; [MVCNameAs('Title')] property Title: String read fTitle write fTitle; [MVCNameAs('ReportsTo')] property Reportsto: Integer read fReportsto write fReportsto; [MVCNameAs('BirthDate')] property Birthdate: TDateTime read fBirthdate write fBirthdate; [MVCNameAs('HireDate')] property Hiredate: TDateTime read fHiredate write fHiredate; [MVCNameAs('Address')] property Address: String read fAddress write fAddress; [MVCNameAs('City')] property City: String read fCity write fCity; [MVCNameAs('State')] property State: String read fState write fState; [MVCNameAs('Country')] property Country: String read fCountry write fCountry; [MVCNameAs('PostalCode')] property Postalcode: String read fPostalcode write fPostalcode; [MVCNameAs('Phone')] property Phone: String read fPhone write fPhone; [MVCNameAs('Fax')] property Fax: String read fFax write fFax; [MVCNameAs('Email')] property Email: String read fEmail write fEmail; end; [MVCNameCase(ncLowerCase)] [MVCTable('foo')] TFoo = class(TMVCActiveRecord) private [MVCTableField('bar')] fBar: Integer; [MVCTableField('baz')] fBaz: String; public constructor Create; override; destructor Destroy; override; property Bar: Integer read fBar write fBar; property Baz: String read fBaz write fBaz; end; [MVCNameCase(ncLowerCase)] [MVCTable('Genre')] TGenre = class(TMVCActiveRecord) private [MVCTableField('GenreId', [foPrimaryKey, foAutoGenerated])] fGenreid: Integer; [MVCTableField('Name')] fName: String; public constructor Create; override; destructor Destroy; override; [MVCNameAs('GenreId')] property Genreid: Integer read fGenreid write fGenreid; [MVCNameAs('Name')] property Name: String read fName write fName; end; [MVCNameCase(ncLowerCase)] [MVCTable('Invoice')] TInvoice = class(TMVCActiveRecord) private [MVCTableField('InvoiceId', [foPrimaryKey, foAutoGenerated])] fInvoiceid: Integer; [MVCTableField('CustomerId')] fCustomerid: Integer; [MVCTableField('InvoiceDate')] fInvoicedate: TDateTime; [MVCTableField('BillingAddress')] fBillingaddress: String; [MVCTableField('BillingCity')] fBillingcity: String; [MVCTableField('BillingState')] fBillingstate: String; [MVCTableField('BillingCountry')] fBillingcountry: String; [MVCTableField('BillingPostalCode')] fBillingpostalcode: String; [MVCTableField('Total')] fTotal: Currency; public constructor Create; override; destructor Destroy; override; [MVCNameAs('InvoiceId')] property Invoiceid: Integer read fInvoiceid write fInvoiceid; [MVCNameAs('CustomerId')] property Customerid: Integer read fCustomerid write fCustomerid; [MVCNameAs('InvoiceDate')] property Invoicedate: TDateTime read fInvoicedate write fInvoicedate; [MVCNameAs('BillingAddress')] property Billingaddress: String read fBillingaddress write fBillingaddress; [MVCNameAs('BillingCity')] property Billingcity: String read fBillingcity write fBillingcity; [MVCNameAs('BillingState')] property Billingstate: String read fBillingstate write fBillingstate; [MVCNameAs('BillingCountry')] property Billingcountry: String read fBillingcountry write fBillingcountry; [MVCNameAs('BillingPostalCode')] property Billingpostalcode: String read fBillingpostalcode write fBillingpostalcode; [MVCNameAs('Total')] property Total: Currency read fTotal write fTotal; end; [MVCNameCase(ncLowerCase)] [MVCTable('InvoiceLine')] TInvoiceline = class(TMVCActiveRecord) private [MVCTableField('InvoiceLineId', [foPrimaryKey, foAutoGenerated])] fInvoicelineid: Integer; [MVCTableField('InvoiceId')] fInvoiceid: Integer; [MVCTableField('TrackId')] fTrackid: Integer; [MVCTableField('UnitPrice')] fUnitprice: Currency; [MVCTableField('Quantity')] fQuantity: Integer; public constructor Create; override; destructor Destroy; override; [MVCNameAs('InvoiceLineId')] property Invoicelineid: Integer read fInvoicelineid write fInvoicelineid; [MVCNameAs('InvoiceId')] property Invoiceid: Integer read fInvoiceid write fInvoiceid; [MVCNameAs('TrackId')] property Trackid: Integer read fTrackid write fTrackid; [MVCNameAs('UnitPrice')] property Unitprice: Currency read fUnitprice write fUnitprice; [MVCNameAs('Quantity')] property Quantity: Integer read fQuantity write fQuantity; end; [MVCNameCase(ncLowerCase)] [MVCTable('MediaType')] TMediatype = class(TMVCActiveRecord) private [MVCTableField('MediaTypeId', [foPrimaryKey, foAutoGenerated])] fMediatypeid: Integer; [MVCTableField('Name')] fName: String; public constructor Create; override; destructor Destroy; override; [MVCNameAs('MediaTypeId')] property Mediatypeid: Integer read fMediatypeid write fMediatypeid; [MVCNameAs('Name')] property Name: String read fName write fName; end; [MVCNameCase(ncLowerCase)] [MVCTable('Playlist')] TPlaylist = class(TMVCActiveRecord) private [MVCTableField('PlaylistId', [foPrimaryKey, foAutoGenerated])] fPlaylistid: Integer; [MVCTableField('Name')] fName: String; public constructor Create; override; destructor Destroy; override; [MVCNameAs('PlaylistId')] property Playlistid: Integer read fPlaylistid write fPlaylistid; [MVCNameAs('Name')] property Name: String read fName write fName; end; [MVCNameCase(ncLowerCase)] [MVCTable('PlaylistTrack')] TPlaylisttrack = class(TMVCActiveRecord) private [MVCTableField('PlaylistId', [foPrimaryKey, foAutoGenerated])] fPlaylistid: Integer; [MVCTableField('TrackId', [foPrimaryKey, foAutoGenerated])] fTrackid: Integer; public constructor Create; override; destructor Destroy; override; [MVCNameAs('PlaylistId')] property Playlistid: Integer read fPlaylistid write fPlaylistid; [MVCNameAs('TrackId')] property Trackid: Integer read fTrackid write fTrackid; end; [MVCNameCase(ncLowerCase)] [MVCTable('test')] TTest = class(TMVCActiveRecord) private [MVCTableField('ct')] fCT: String; public constructor Create; override; destructor Destroy; override; property CT: String read fCT write fCT; end; [MVCNameCase(ncLowerCase)] [MVCTable('Track')] TTrack = class(TMVCActiveRecord) private [MVCTableField('TrackId', [foPrimaryKey, foAutoGenerated])] fTrackid: Integer; [MVCTableField('Name')] fName: String; [MVCTableField('AlbumId')] fAlbumid: Integer; [MVCTableField('MediaTypeId')] fMediatypeid: Integer; [MVCTableField('GenreId')] fGenreid: Integer; [MVCTableField('Composer')] fComposer: String; [MVCTableField('Milliseconds')] fMilliseconds: Integer; [MVCTableField('Bytes')] fBytes: Integer; [MVCTableField('UnitPrice')] fUnitprice: Currency; public constructor Create; override; destructor Destroy; override; [MVCNameAs('TrackId')] property Trackid: Integer read fTrackid write fTrackid; [MVCNameAs('Name')] property Name: String read fName write fName; [MVCNameAs('AlbumId')] property Albumid: Integer read fAlbumid write fAlbumid; [MVCNameAs('MediaTypeId')] property Mediatypeid: Integer read fMediatypeid write fMediatypeid; [MVCNameAs('GenreId')] property Genreid: Integer read fGenreid write fGenreid; [MVCNameAs('Composer')] property Composer: String read fComposer write fComposer; [MVCNameAs('Milliseconds')] property Milliseconds: Integer read fMilliseconds write fMilliseconds; [MVCNameAs('Bytes')] property Bytes: Integer read fBytes write fBytes; [MVCNameAs('UnitPrice')] property Unitprice: Currency read fUnitprice write fUnitprice; end; implementation constructor TAlbum.Create; begin inherited Create; fColumn1 := TMemoryStream.Create; end; destructor TAlbum.Destroy; begin fColumn1.Free; inherited; end; constructor TArtist.Create; begin inherited Create; end; destructor TArtist.Destroy; begin inherited; end; constructor TCustomer.Create; begin inherited Create; end; destructor TCustomer.Destroy; begin inherited; end; constructor TEmployee.Create; begin inherited Create; end; destructor TEmployee.Destroy; begin inherited; end; constructor TEmpview.Create; begin inherited Create; end; destructor TEmpview.Destroy; begin inherited; end; constructor TFoo.Create; begin inherited Create; end; destructor TFoo.Destroy; begin inherited; end; constructor TGenre.Create; begin inherited Create; end; destructor TGenre.Destroy; begin inherited; end; constructor TInvoice.Create; begin inherited Create; end; destructor TInvoice.Destroy; begin inherited; end; constructor TInvoiceline.Create; begin inherited Create; end; destructor TInvoiceline.Destroy; begin inherited; end; constructor TMediatype.Create; begin inherited Create; end; destructor TMediatype.Destroy; begin inherited; end; constructor TPlaylist.Create; begin inherited Create; end; destructor TPlaylist.Destroy; begin inherited; end; constructor TPlaylisttrack.Create; begin inherited Create; end; destructor TPlaylisttrack.Destroy; begin inherited; end; constructor TTest.Create; begin inherited Create; end; destructor TTest.Destroy; begin inherited; end; constructor TTrack.Create; begin inherited Create; end; destructor TTrack.Destroy; begin inherited; end; initialization ActiveRecordMappingRegistry.AddEntity('album',TAlbum); ActiveRecordMappingRegistry.AddEntity('artist',TArtist); ActiveRecordMappingRegistry.AddEntity('customer',TCustomer); ActiveRecordMappingRegistry.AddEntity('employee',TEmployee); ActiveRecordMappingRegistry.AddEntity('empview',TEmpview); ActiveRecordMappingRegistry.AddEntity('foo',TFoo); ActiveRecordMappingRegistry.AddEntity('genre',TGenre); ActiveRecordMappingRegistry.AddEntity('invoice',TInvoice); ActiveRecordMappingRegistry.AddEntity('invoiceline',TInvoiceline); ActiveRecordMappingRegistry.AddEntity('mediatype',TMediatype); ActiveRecordMappingRegistry.AddEntity('playlist',TPlaylist); ActiveRecordMappingRegistry.AddEntity('playlisttrack',TPlaylisttrack); ActiveRecordMappingRegistry.AddEntity('test',TTest); ActiveRecordMappingRegistry.AddEntity('track',TTrack); end.
program HowToMoveSpriteUsingAnimation; uses SwinGame, sgTypes; procedure DoWalking(sprt: Sprite; key: KeyCode;const animationName: String; dx, dy: Single); begin if KeyDown(key) then begin SpriteStartAnimation(sprt, animationName); SpriteSetDX(sprt, dx); SpriteSetDY(sprt, dy); end; end; procedure Main(); var myFrog: Sprite; begin OpenAudio(); OpenGraphicsWindow('Moving Sprite Using Animation', 800, 600); LoadResourceBundle('dance_bundle.txt'); myFrog := CreateSprite(BitmapNamed('FrogBmp'), AnimationScriptNamed('WalkingScript')); SpriteStartAnimation(myFrog, 'StandFront'); SpriteSetX(myFrog, 382); SpriteSetY(myFrog, 274); repeat ClearScreen(ColorWhite); DrawSprite(myFrog); RefreshScreen(60); UpdateSprite(myFrog); ProcessEvents(); if SpriteAnimationHasEnded(myFrog) then begin SpriteSetDX(myFrog, 0); SpriteSetDY(myFrog, 0); DoWalking(myFrog, UPKey, 'WalkBack', 0, -0.25); DoWalking(myFrog, DOWNKey, 'WalkFront', 0, +0.25); DoWalking(myFrog, LEFTKey, 'WalkLeft', -0.25, 0); DoWalking(myFrog, RIGHTKey, 'WalkRight', +0.25, 0); DoWalking(myFrog, WKey, 'MoonWalkBack', 0, -0.25); DoWalking(myFrog, SKey, 'MoonWalkFront', 0, +0.25); DoWalking(myFrog, AKey, 'MoonWalkLeft', -0.25, 0); DoWalking(myFrog, DKey, 'MoonWalkRight', +0.25, 0); end; until WindowCloseRequested(); FreeSprite(myFrog); CloseAudio(); ReleaseAllResources(); end; begin Main(); end.
unit WavFiles; interface uses Windows, Classes, acm, Text2Speech; type TWavFile = class(TObject) private FPcmStream: TMemoryStream; public function GetSize: Integer; function GetPosition: Integer; procedure SetPosition(Value: Integer); function GetBuffer(Buffer: PAnsiChar; BufLen: Integer): Integer; Procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: AnsiString); constructor Create(const AFileName: AnsiString); constructor CreateFromBuf(Buf:PAnsiChar; Len:Integer); destructor Destroy; override; end; TWavStream = class(TObject) private FPcmStream: TMemoryStream; protected function GetSize: Integer; function GetPosition: Integer; procedure Setposition(Value: Integer); function GetBuffer(Buffer: PAnsiChar; BufLen: Integer): Integer; Procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: AnsiString); public constructor Create(const AText: String; VoiceIndex:Integer); constructor CreateFromStream(const AStream: TStream); destructor Destroy; override; end; procedure PcmToGsm (PcmStm, GsmStm: TStream); procedure GsmToWav (PcmStm, WavStm: TStream); procedure PcmToWav (PcmStm, WavStm: TStream); procedure GetPcmFromWavFile (SrcStm, DstStm: TStream; DstBPS: Longint; DstSPS: Longint); implementation uses CodecGSM; const WAVE_FORMAT_GSM610 = $31; WAVE_FORMAT_PCM = $01; type TWaveHeader = record riff: array[1..4] of AnsiChar; filesize: Longint; wave: array[1..4] of AnsiChar; fmt: array[1..4] of AnsiChar; schunk: Longint; wtype: Word; mono_stereo: Word; sample_rate: Longint; byte_sec: Longint; blockal: Word; bits_sample: Word; data: array[1..4] of AnsiChar; datasize: Longint; end; TWave49Header = record riff: array[1..4] of AnsiChar; filesize: Longint; wave: array[1..4] of AnsiChar; fmt: array[1..4] of AnsiChar; schunk: Longint; wtype: Word; mono_stereo: Word; sample_rate: Longint; byte_sec: Longint; blockal: Word; w1,w2,w3: Word; data: array[1..4] of AnsiChar; datasize: Longint; end; procedure PcmToGsm (PcmStm, GsmStm: TStream); var gsmblock: TGsmBlock; pcmblock: TPcmBlock; has: THandle; sf: TWAVEFORMATEX; df: TWAVEFORMATGSM; hdr: TACMSTREAMHEADER; const WAVE_FORMAT_GSM610 = $31; WAVE_FORMAT_PCM = $01; Begin InitFormatEx(sf, WAVE_FORMAT_PCM, 1, 8000, 16000, 2, 16, 0); InitFormatEx(TWAVEFORMATEX(df), WAVE_FORMAT_GSM610, 1, 8000, 1625, 65, 0, 2); df.unpackedBlockSize := Length(pcmblock); InitAcmHeader(hdr,@pcmblock,SizeOf(pcmblock),SizeOf(pcmblock),@gsmblock,SizeOf(gsmblock),SizeOf(gsmblock),0); if acmFormatSuggest(0,@sf,@df,SizeOf(df),ACM_FORMATSUGGESTF_WFORMATTAG)=0 Then Begin if acmStreamOpen(@has,0,@sf,@df,Nil,0,0,ACM_STREAMOPENF_NONREALTIME)=0 Then Begin if acmStreamPrepareHeader(has,@hdr,0)=0 Then Begin GsmStm.Seek(0,soFromBeginning); PcmStm.Seek(0,soFromBeginning); while PcmStm.Read(pcmblock,SizeOf(pcmblock))=SizeOf(pcmblock) Do Begin if acmStreamConvert(has,@hdr,ACM_STREAMCONVERTF_BLOCKALIGN)<>0 then Break; GsmStm.Write(gsmblock,SizeOf(gsmblock)); end; GsmStm.Seek(0,soFromBeginning); PcmStm.Seek(0,soFromBeginning); acmStreamUnprepareHeader(has,@hdr,0); end; acmStreamClose(has,0); end; end else MessageBoxEx(0,'Make sure that GSM 6.10 codec is installed on your computer', 'Can''t convert GSM to PCM',MB_ICONHAND,0); end; procedure GsmToWav (PcmStm, WavStm: TStream); var header:TWave49Header; Begin with header do begin Move('RIFF', riff, 4); Move('WAVE', wave, 4); Move('fmt ', fmt, 4); schunk := $14; wtype := WAVE_FORMAT_GSM610; mono_stereo := 1; sample_rate := 8000; byte_sec := 1625; blockal := High(TGsmFrames); w1:=0; w2:=2; w3:=High(TPcmBlock); Move('data', data, 4); datasize := 0; end; header.datasize := PcmStm.Size; header.filesize := header.datasize + sizeof(header) - 8; PcmStm.Seek(0, soFromBeginning); WavStm.Seek(0, soFromBeginning); WavStm.Write(header, sizeof(header)); WavStm.CopyFrom(PcmStm, PcmStm.Size); PcmStm.Seek(0, soFromBeginning); WavStm.Seek(0, soFromBeginning); end; procedure PcmToWav(PcmStm, WavStm: TStream); var header: TWaveHeader; begin with header do begin Move('RIFF', riff, 4); Move('WAVE', wave, 4); Move('fmt ', fmt, 4); schunk := $10; wtype := 1; mono_stereo := 1; sample_rate := 8000; byte_sec := 8000 * 2; blockal := 2; bits_sample := 16; Move('data', data, 4); datasize := 0; end; header.datasize := PcmStm.Size; header.filesize := header.datasize + sizeof(header) - 8; PcmStm.Seek(0, soFromBeginning); WavStm.Seek(0, soFromBeginning); WavStm.Write(header, sizeof(header)); WavStm.CopyFrom(PcmStm, PcmStm.Size); PcmStm.Seek(0, soFromBeginning); WavStm.Seek(0, soFromBeginning); end; procedure ReadFileType(WavStm: TStream; var WavFormat, BitsPerSample, SamplesPerSec, DataPos, DataSize: Longint); var Pos, SPos, SN, RIFF: Longint; WF: TWAVEFORMATEX; const SN_DATA = $61746164; // data SN_FMT = $20746D66; // fmt RIFF_ID = $46464952; // RIFF begin WavStm.Seek(0, soFromBeginning); WavStm.Read(RIFF, 4); if RIFF <> RIFF_ID then begin WavStm.Seek(0, soFromBeginning); WavFormat := 100000; DataSize := WavStm.Size; DataPos := 0; Exit; end; WavStm.Seek(12, soFromBeginning); while SN <> SN_DATA do begin WavStm.Read(SN, 4); WavStm.Read(Pos, 4); if SN = SN_FMT then begin SPos := WavStm.Position; WavStm.Read(WF, SizeOf(WF)); WavFormat := WF.wFormatTag; BitsPerSample := WF.wBitsPerSample; SamplesPerSec := WF.nSamplesPerSec; WavStm.Seek(SPos, soFromBeginning); end; if SN <> SN_DATA then WavStm.Seek(Pos, soFromCurrent) else begin DataPos := WavStm.Position; DataSize := Pos; end; end; end; procedure GsmToPcm (GsmStm, PcmStm: TStream); var gsmblock: TGsmBlock; pcmblock: TPcmBlock; has: THandle; df: TWAVEFORMATEX; sf: TWAVEFORMATGSM; hdr: TACMSTREAMHEADER; Begin InitFormatEx(TWAVEFORMATEX(sf), WAVE_FORMAT_GSM610, 1, 8000, 1625, SizeOf(TGsmBlock), 0, 2); sf.unpackedBlockSize := Length(pcmblock); InitFormatEx(df, WAVE_FORMAT_PCM, 1, 8000, 16000, 2, 16, 0); FillChar(hdr,SizeOf(hdr),0); InitAcmHeader(hdr,@gsmblock,SizeOf(gsmblock),SizeOf(gsmblock),@pcmblock,SizeOf(pcmblock),SizeOf(pcmblock),0); if acmFormatSuggest(0,@sf,@df,SizeOf(df),ACM_FORMATSUGGESTF_WFORMATTAG)=0 Then Begin if acmStreamOpen(@has,0,@sf,@df,Nil,0,0,ACM_STREAMOPENF_NONREALTIME)=0 Then Begin if acmStreamPrepareHeader(has,@hdr,0)=0 Then Begin GsmStm.Seek(0,soFromBeginning); PcmStm.Seek(0,soFromBeginning); while GsmStm.Read(gsmblock,SizeOf(gsmblock))=SizeOf(gsmblock) Do Begin if acmStreamConvert(has,@hdr,ACM_STREAMCONVERTF_BLOCKALIGN)<>0 then Break; PcmStm.Write(pcmblock,SizeOf(pcmblock)); end; GsmStm.Seek(0,soFromBeginning); PcmStm.Seek(0,soFromBeginning); acmStreamUnprepareHeader(has,@hdr,0); end; acmStreamClose(has,0); end; end; PcmStm.Position:=0; end; procedure GetPcmFromWavFile (SrcStm, DstStm: TStream; DstBPS: Longint; DstSPS: Longint); var src, dst: array[1..65535] of Byte; // should be in HEAP has: THandle; sf: TWAVEFORMATEX; df: TWAVEFORMATEX; hdr: TACMSTREAMHEADER; SrcLen, DstLen, BytesRead: Longint; WavFormat, SrcBPS, SrcSPS, DataPos, DataSize: Longint; m: TMemoryStream; Begin ReadFileType(SrcStm,WavFormat,SrcBPS,SrcSPS,DataPos,DataSize); if WavFormat=WAVE_FORMAT_GSM610 Then Begin m:=TMemoryStream.Create; try SrcStm.Position:=DataPos; m.CopyFrom(SrcStm,DataSize); m.Position:=0; GsmToPcm(m,DstStm); DstStm.Position:=0; Finally m.Free; end; end; if (SrcBPS = DstBPS)and(SrcSPS = DstSPS) Then Begin SrcStm.Seek(DataPos,soFromBeginning); DstStm.CopyFrom(SrcStm,DataSize); Exit; end; SrcLen := ((SrcBPS div 8) * SrcSPS) div 2; DstLen := ((DstBPS div 8) * DstSPS) div 2; InitFormatEx(sf,WAVE_FORMAT_PCM,1,SrcSPS,(SrcBPS div 8)*SrcSPS,SrcBPS Div 8,SrcBPS,0); InitFormatEx(df,WAVE_FORMAT_PCM,1,DstSPS,(DstBPS div 8)*DstSPS,DstBPS div 8,DstBPS,0); InitAcmHeader(hdr,@src,SrcLen,SrcLen,@dst,DstLen,DstLen,0); FillChar(dst,SizeOf(dst),127); if acmStreamOpen(@has,0,@sf,@df,Nil,0,0,ACM_STREAMOPENF_NONREALTIME)=0 Then Begin if acmStreamPrepareHeader(has,@hdr,0)=0 Then Begin DstStm.Seek(0,soFromBeginning); while SrcStm.Position<SrcStm.Size do Begin BytesRead:=SrcStm.Read(src,SrcLen); if acmStreamConvert(has,@hdr,ACM_STREAMCONVERTF_BLOCKALIGN)<>0 then Break; if BytesRead=SrcLen then DstStm.Write(dst,DstLen) Else DstStm.Write(dst, Round(BytesRead*(DstLen/SrcLen)/(DstBPS div 8))*(DstBPS div 8)); end; DstStm.Seek(0,soFromBeginning); SrcStm.Seek(0,soFromBeginning); acmStreamUnprepareHeader(has,@hdr,0); end; acmStreamClose(has,0); end; end; { TWavFile } constructor TWavFile.Create(const AFileName: AnsiString); var m, pcm: TMemoryStream; sl: TStringList; s: AnsiString; i: Integer; begin inherited Create; FPcmStream := TMemoryStream.Create; sl:=TStringList.Create; for i:=1 To Length(AFileName) do Case AFileName[i] of ',', ';': if Length(s)>0 then begin sl.Add(s); s:=''; End; else s:=s+AFileName[i]; End; if Length(s)>0 then sl.Add(s); m := TMemoryStream.Create; pcm:=TMemoryStream.Create; try for i:=0 To sl.Count-1 do Begin m.LoadFromFile(sl[i]); m.Position := 0; GetPcmFromWavFile(m, pcm, 16, 8000); pcm.Position := 0; FPcmStream.CopyFrom(pcm,pcm.Size); pcm.Clear; m.Clear; end; finally sl.Free; m.Free; pcm.Free; end; FPcmStream.Position:=0; end; Constructor TWavFile.CreateFromBuf(Buf:PAnsiChar; Len:Integer); var m:TMemoryStream; Begin Inherited Create; FPcmStream:=TMemoryStream.Create; m:=TMemoryStream.Create; Try m.WriteBuffer(Buf^,Len); m.Position:=0; GetPcmFromWavFile(m,FPcmStream,16,8000); FPcmStream.Position:=0; Finally m.Free; End; end; destructor TWavFile.Destroy; begin FPcmStream.Free; inherited; end; function TWavFile.GetBuffer(Buffer: PAnsiChar; BufLen: Integer): Integer; begin Result := FPcmStream.Read(Buffer^, BufLen); end; function TWavFile.GetSize: Integer; begin Result := FPcmStream.Size; end; function TWavFile.GetPosition: Integer; begin Result := FPcmStream.Position; end; procedure TWavFile.SetPosition(Value: Integer); begin FPcmStream.Position := Value; end; Procedure TWavFile.SaveToStream(Stream:TStream); var ms:TMemoryStream; Begin ms:=TMemoryStream.Create; try FPcmStream.Position:=0; PcmToGsm(FPcmStream,ms); FPcmStream.Clear; ms.Position:=0; GsmToWav(ms,FPcmStream); FPcmStream.SaveToStream(Stream); Finally ms.Free; End; FPcmStream.Clear; end; procedure TWavFile.SaveToFile(const FileName: AnsiString); var ms:TMemoryStream; Begin ms:=TMemoryStream.Create; try FPcmStream.Position:=0; SaveToStream(ms); ms.SaveToFile(FileName); Finally ms.Free; end; end; { TWavStream } constructor TWavStream.Create(const AText: String; VoiceIndex:Integer); const MCW_EM = DWord($133f); begin inherited Create; FPcmStream := TMemoryStream.Create; Set8087CW(MCW_EM); Text2Wav(AText, VoiceIndex, FPcmStream,0); FPcmStream.Position:=0; end; destructor TWavStream.Destroy; begin FPcmStream.Free; inherited; end; function TWavStream.GetBuffer(Buffer: PAnsiChar; BufLen: Integer): Integer; begin Result := FPcmStream.Read(Buffer^, BufLen); end; function TWavStream.GetSize: Integer; begin Result := FPcmStream.Size; end; function TWavStream.GetPosition: Integer; begin Result := FPcmStream.Position; end; procedure TWavStream.SetPosition(Value: Integer); begin FPcmStream.Position := Value; end; constructor TWavStream.CreateFromStream(const AStream: TStream); begin inherited Create; FPcmStream := TMemoryStream.Create; FPcmStream.LoadFromStream(AStream); end; procedure TWavstream.SaveToFile(const FileName: AnsiString); var ms:TMemoryStream; Begin ms:=TMemoryStream.Create; try FPcmStream.Position:=0; SaveToStream(ms); ms.SaveToFile(FileName); Finally ms.Free; End; end; procedure TWavStream.SaveToStream(Stream:TStream); var ms:TMemoryStream; Begin ms:=TMemoryStream.Create; try FPcmStream.Position:=0; PcmToGsm(FPcmStream,ms); FPcmStream.Clear; ms.Position:=0; GsmToWav(ms,FPcmStream); FPcmStream.SaveToStream(Stream); Finally ms.Free; end; FPcmStream.Clear; end; end.
unit uAssociations; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uModelEntity, uDocumentation; type // this may or may not go TAssociationType =( atOwnedMember, atMemberReference, // pointer members declared ^Thing atDirectInheritance, atInterfaceInheritance, atSpecializeInheritance, ); // this could be a record but as a class a nil value can be assigned when it is member of a class to indicate absence. // May be expanded for model checking purposes. // BNF // <multiplicity> ::= <multiplicity-range> [ [ ‘{‘ <order-designator> [‘,’ <uniqueness-designator> ] ‘}’ ] | // [ ‘{‘ <uniqueness-designator> [‘,’ <order-designator> ] ‘}’ ] ] // <multiplicity-range> ::= [ <lower> ‘..’ ] <upper> // <lower> ::= <value-specification> // <upper> ::= <value-specification> // <order-designator> ::= ‘ordered’ | ‘unordered’ // <uniqueness-designator> ::= ‘unique’ | ‘nonunique’ TMultiplicty = class lower : string; // specs say this should be non-negative integer but pascal allows ordinal strings,( EnumLiterals, Constants) which does actually fulfill the constraint lower_is_integer 7.8.8.8 although pascal differentiates between integer and ordinal. upper : string; // Unlimited Natural defined as positive integers + *, as for lower, ordinal strings are allowed. isOrdered: boolean; isUnique: boolean; end; { UML abstract Relationship in Figure 7.1 Root. True abstract relationship would be an attribute of a base UML Primitive DataType i.e. ThisItem: String; There is no requirement to create a directed relationship for Primitive DataTypes. However most other nodeling tools seem to have Language base packages, presumably so there can be a relationship for all members Primitive or not, and allow for Language Specific primitives. This would seem like a reasonable idea. Arrays could be a Template DataType where cardinallity is in the Association End and the Array Type would be the binding association. Similar notation could be used for Set of Enum. And allow for Array of Array of DataType as unbound template chain. Conclusion: This class remains abstract and can only be included in DirectedRelationships. Create DirectedRelationShips for all members. We required DataType Templates. } TAssociationEnd = class Cardinality: TMultipicity; Name: string; // this is the name that the other end uses as its internal identifier. nil string for absence Entity: TModelEntity; // the entity this end of the DirectedAssociation is linked to. Navigable: boolean; // default is navigable from Owner -> Target. end; TBinding = class BoundName: string; // <T> <T1,T1>??? BindTo: TModelEntity; end; { Enumerate, classify or Subclass UML/XMI Associations?? Common 36 Association Types Values 19 Association Types Classification 47 Association Types Classifiers 16 Association Types Structuredd Classifiers 35 Association Types Packages 14 Association Types Common Behaviour 12 Association Types State Machines 32 Association Types Activities 34 Association Types Actions 109 Association Types Interactions 38 Association Types Use Cases 8 Association Types Deployments 10 Association Types Information Flows 8 Association Types -------------------- ---- 418 All the above are required for correct xmi generation. A class diagram can use everything up to Common Behaviour in the above list. Below that are other diagram types which may or may not use the above. Possible solution generate enumeration via XSLT from UML.xmi. Saves a lot of work and would enable easier migration to later versions. UML.xmi also contains field isDerived for a uml:Association.Need to investigate more. Will fix up ancestors when we attach to ModelEntity subclasses and have to worry about lifetimes, dangling pointers etc. Probably should have its own listeners heirarchy so it can remove references to itself. } TDirectedAssociation = class(TModelEntity) StereoType: string; // works for now. OwnedEnd: TAssociationEnd; // source in 7.2.3.3 TargetEnd: TAssociationEnd; Constraint: TDocumentation; // works for now. ModelEntity should really have this? end; TBindAssociation = class(TDirectedAssociation) Bindings: end; implementation end.
unit UsuarioDAO; interface uses Classes, DBXCommon, SqlExpr, Usuario, SysUtils; type {$MethodInfo ON} TUsuarioDAO = class(TPersistent) private FComm: TDBXCommand; procedure PrepareCommand; public function List: TDBXReader; function Insert(usuario: TUsuario): Boolean; function Update(usuario: TUsuario; oldLogin: string): Boolean; function Delete(usuario: TUsuario): Boolean; function AtualizaAcesso(usuario: TUsuario): Boolean; function FindByLoginAndSenha(Login, Senha: string): TUsuario; end; implementation uses uSCPrincipal, StringUtils; { TUsuarioDAO } procedure TUsuarioDAO.PrepareCommand; begin if not(Assigned(FComm)) then begin if not(SCPrincipal.ConnTopCommerce.Connected) then SCPrincipal.ConnTopCommerce.Open; FComm := SCPrincipal.ConnTopCommerce.DBXConnection.CreateCommand; FComm.CommandType := TDBXCommandTypes.DbxSQL; if not(FComm.IsPrepared) then FComm.Prepare; end; end; function TUsuarioDAO.List: TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT * FROM USUARIOS'; Result := FComm.ExecuteQuery; end; function TUsuarioDAO.Insert(usuario: TUsuario): Boolean; begin PrepareCommand; FComm.Text := 'INSERT INTO USUARIOS (LOGIN, SENHA) VALUES ('''+usuario.Login+''','''+usuario.Senha+''')'; try FComm.ExecuteUpdate; Result := True; except Result := False; end; end; function TUsuarioDAO.Update(usuario: TUsuario; oldLogin: string): Boolean; begin PrepareCommand; FComm.Text := 'UPDATE USUARIOS SET LOGIN = '''+usuario.Login+''', SENHA = '''+usuario.Senha+''''+ ' WHERE LOGIN = '''+oldLogin+''''; try FComm.ExecuteUpdate; Result := True; except Result := False; end; end; function TUsuarioDAO.Delete(usuario: TUsuario): Boolean; begin PrepareCommand; FComm.Text := 'DELETE FROM USUARIOS WHERE LOGIN = '''+usuario.Login+''''; try FComm.ExecuteUpdate; Result := True; except Result := False; end; end; function TUsuarioDAO.AtualizaAcesso(usuario: TUsuario): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; try query.SQL.Text := 'UPDATE USUARIOS SET ULTIMO_ACESSO = :ULTIMOACESSO'+ ' WHERE LOGIN = :LOGIN'; query.ParamByName('ULTIMOACESSO').AsDateTime := Now; query.ParamByName('LOGIN').AsString := usuario.Login; query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TUsuarioDAO.FindByLoginAndSenha(Login, Senha: string): TUsuario; var query: TSQLQuery; begin Result := Default(TUsuario); query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT * FROM USUARIOS WHERE LOGIN = ''' + Login + ''' AND SENHA = ''' + Senha + ''''; query.Open; if not( query.IsEmpty ) then begin Result := TUsuario.Create(query.FieldByName('LOGIN').AsString, query.FieldByName('SENHA').AsString); AtualizaAcesso( Result ); end; finally query.Free; end; end; end.
unit fInitial; interface uses Winapi.Windows, System.SysUtils, System.IniFiles, Vcl.Forms, Vcl.Graphics, Vcl.Menus, Vcl.Actnlist, GnuGettext; type TInitialForm = class(TForm) procedure FormCreate(Sender: TObject); private public IniFile : TIniFile; procedure ReadIniFile; virtual; procedure WriteIniFile; virtual; procedure SetLanguage; end; var InitialForm: TInitialForm; LangID : Word; implementation {$R *.dfm} //Here goes a translation of all component strings procedure TInitialForm.FormCreate(Sender: TObject); begin inherited; SetLanguage; TranslateComponent(Self); end; procedure TInitialForm.SetLanguage; var LocalePath : TFileName; IniFile : TIniFile; begin LocalePath := ExtractFileDir(ParamStr(0)); // Path to GLSViewer LocalePath := LocalePath + PathDelim + 'Locale' + PathDelim; Textdomain('glsviewer'); BindTextDomain ('glsviewer', LocalePath); ReadIniFile; if (LangID <> LANG_ENGLISH) then begin case LangID of LANG_RUSSIAN: begin UseLanguage('ru'); Application.HelpFile := UpperCase(LocalePath + 'ru'+ PathDelim+'GLSViewer.chm'); end; LANG_SPANISH: begin UseLanguage('es'); Application.HelpFile := UpperCase(LocalePath + 'es'+ PathDelim+'GLSViewer.chm'); end; LANG_GERMAN: begin UseLanguage('de'); Application.HelpFile := UpperCase(LocalePath + 'de'+ PathDelim+'GLSViewer.chm'); end; LANG_FRENCH: begin UseLanguage('fr'); Application.HelpFile := UpperCase(LocalePath + 'fr'+ PathDelim+'GLSViewer.chm'); end else begin UseLanguage('en'); Application.HelpFile := UpperCase(LocalePath + 'en'+ PathDelim+'GLSViewer.chm'); end; end; end else begin UseLanguage('en'); Application.HelpFile := UpperCase(LocalePath + 'en'+ PathDelim+'GLSViewer.chm'); end; TP_IgnoreClass(TFont); TranslateComponent(Self); //TP_GlobalIgnoreClass(TGLLibMaterial); //TP_GlobalIgnoreClass(TGLMaterialLibrary); //TP_GlobalIgnoreClass(TListBox); //TP_GlobalIgnoreClassProperty(TAction, 'Category'); //LoadNewResourceModule(Language);//when using ITE, ENU for English USA end; procedure TInitialForm.ReadIniFile; begin IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); with IniFile do try LangID := ReadInteger('GLOptions', 'RadioGroupLanguage', 0); finally IniFile.Free; end; end; procedure TInitialForm.WriteIniFile; begin // end; end.
unit VoxelEngine; interface uses System.SysUtils, System.Classes; type Colour = record R: Byte; G: Byte; B: Byte; A: Byte; end; type MagicaVoxelData = record x: Byte; y: Byte; z: Byte; color: Byte; end; type VoxData = record FStream: TMemoryStream; Map_X, Map_Y, Map_Z: Integer; // SIZE MAP TO X Y Z; Map: array of MagicaVoxelData; // array X Y Z Color; Palette: array [0 .. 255] of Colour; // MAP Palette RGB; _MagicaVoxelData: MagicaVoxelData; magic: array [0 .. 3] of AnsiChar; // 'VOX ' chunkID: array [0 .. 3] of AnsiChar; // CHUNK NAME MAIN RGBA XYZI SIZE PACK Version: Integer; // 150 ChunkSize: Integer; // - ChunkChild: Integer; // - NumModels: Integer; // Voxel count ChunkName: string; // CHUNK NAME MAIN RGBA XYZI SIZE PACK end; type VoxManager = class constructor Create(FileName: String); class function ExtractMap(): VoxData; end; implementation var _VoxData: VoxData; constructor VoxManager.Create(FileName: String); begin _VoxData.FStream := TMemoryStream.Create; _VoxData.FStream.LoadFromFile(FileName); end; class function VoxManager.ExtractMap(): VoxData; var i: Integer; begin _VoxData.FStream.Read(_VoxData.magic, 4); _VoxData.FStream.Read(_VoxData.Version, 4); if _VoxData.magic = 'VOX ' then begin while (_VoxData.FStream.Position < _VoxData.FStream.Size) do begin _VoxData.FStream.Read(_VoxData.chunkID, 4); _VoxData.FStream.Read(_VoxData.ChunkSize, 4); _VoxData.FStream.Read(_VoxData.ChunkChild, 4); _VoxData.ChunkName := _VoxData.chunkID; if (_VoxData.ChunkName = 'SIZE') then begin _VoxData.FStream.Read(_VoxData.Map_X, 4); _VoxData.FStream.Read(_VoxData.Map_Y, 4); _VoxData.FStream.Read(_VoxData.Map_Z, 4); end else if (_VoxData.ChunkName = 'XYZI') then begin _VoxData.FStream.Read(_VoxData.NumModels, 4); SetLength(_VoxData.Map, _VoxData.NumModels); for i := 0 to _VoxData.NumModels - 1 do begin _VoxData.FStream.Read(_VoxData.Map[i].x, 1); _VoxData.FStream.Read(_VoxData.Map[i].y, 1); _VoxData.FStream.Read(_VoxData.Map[i].z, 1); _VoxData.FStream.Read(_VoxData.Map[i].color, 1); end; end else if (_VoxData.ChunkName = 'RGBA') then begin for i := 0 to 255 do begin _VoxData.FStream.Read(_VoxData.Palette[i].R, 1); _VoxData.FStream.Read(_VoxData.Palette[i].G, 1); _VoxData.FStream.Read(_VoxData.Palette[i].B, 1); _VoxData.FStream.Read(_VoxData.Palette[i].A, 1); end; end else if (_VoxData.ChunkName = 'PACK') then begin _VoxData.FStream.Read(_VoxData.ChunkSize, 4); end; end; end; Result := _VoxData; end; end.
unit uDMValidateTextFile; interface uses SysUtils, Classes, ADODB, DBClient, DB; type TDMValidateTextFile = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FSQLConnection: TADOConnection; FTextFile: TClientDataSet; FLinkedColumns: TStringList; FImpExpConfig: TStringList; FLog: TStringList; public function Validate: Boolean; virtual; abstract; property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection; property TextFile: TClientDataSet read FTextFile write FTextFile; property LinkedColumns: TStringList read FLinkedColumns write FLinkedColumns; property ImpExpConfig: TStringList read FImpExpConfig write FImpExpConfig; property Log: TStringList read FLog write FLog; end; implementation {$R *.dfm} procedure TDMValidateTextFile.DataModuleCreate(Sender: TObject); begin FTextFile := TClientDataSet.Create(nil); FLinkedColumns := TStringList.Create; FImpExpConfig := TStringList.Create; FLog := TStringList.Create; end; procedure TDMValidateTextFile.DataModuleDestroy(Sender: TObject); begin FreeAndNil(FTextFile); FreeAndNil(FLinkedColumns); FreeAndNil(FImpExpConfig); FreeAndNil(FLog); end; end.
unit VertexTransformationUtils; // This class is a split from ClassTextureGenerator and it should be used to // project a plane out of a vector and find the position of another vector in // this plane. Boring maths stuff. interface uses Geometry, BasicMathsTypes, GLConstants, Math; {$INCLUDE source/Global_Conditionals.inc} type TVertexTransformationUtils = class public // Constructors and Destructors constructor Create; destructor Destroy; override; procedure Initialize; procedure Reset; procedure Clear; // Transform Matrix Operations function GetTransformMatrixFromVector(_Vector: TVector3f): TMatrix; function GetTransformMatrixFromAngles(_AngX, _AngY: single): TMatrix; function GetRotationMatrixFromVector(_Vector: TVector3f): TMatrix; function GetUVCoordinates(const _Position: TVector3f; _TransformMatrix: TMatrix): TVector2f; // Angle Detector function GetRotationX(const _Vector: TVector3f): single; function GetRotationY(const _Vector: TVector3f): single; function GetRotationXZ(const _Vector: TVector3f): single; // Angle Operators function CleanAngle(Angle: single): single; function CleanAngleRadians(Angle: single): single; function CleanAngle90Radians(Angle: single): single; // Tangent Plane Detector procedure GetTangentPlaneFromNormalAndDirection(var _AxisX,_AxisY: TVector3f; const _Normal,_Direction: TVector3f); function ProjectVectorOnTangentPlane(const _Normal,_Vector: TVector3f): TVector3f; function GetArcCosineFromTangentPlane(const _Vector, _AxisX, _AxisY: TVector3f): single; function GetArcCosineFromAngleOnTangentSpace(_VI,_V1,_V2: TVector3f; _VertexNormal: TVector3f): single; // Misc function IsPointInsideTriangle(const _V1,_V2,_V3,_P : TVector2f): boolean; end; implementation uses GlobalVars, SysUtils, Math3d, BasicFunctions; constructor TVertexTransformationUtils.Create; begin Initialize; end; destructor TVertexTransformationUtils.Destroy; begin Clear; inherited Destroy; end; procedure TVertexTransformationUtils.Initialize; begin // do nothing end; procedure TVertexTransformationUtils.Clear; begin // do nothing end; procedure TVertexTransformationUtils.Reset; begin Clear; Initialize; end; // Transform Matrix Operations // This function should be deprecated as it is inaucurate. function TVertexTransformationUtils.GetTransformMatrixFromVector(_Vector: TVector3f): TMatrix; const C_ANG_X = 0; C_ANG_Y = 0; var AngX,AngY : single; begin // Get the angles from the normal vector. AngX := GetRotationY(_Vector); AngY := GetRotationXZ(_Vector); // Now we get the transform matrix Result := GetTransformMatrixFromAngles(CleanAngleRadians(-AngX),CleanAngleRadians(-AngY)); end; function TVertexTransformationUtils.GetTransformMatrixFromAngles(_AngX, _AngY: single): TMatrix; const ANG90 = Pi * 0.5; begin Result := IdentityMatrix; // first of all, we align our world with the direction z = -1. if _AngX <> 0 then begin Result := MatrixMultiply(Result,CreateRotationMatrixY(sin(_AngX),cos(_AngX))); end; // now we vertically rotate our world to y = 0. if _AngY <> 0 then begin Result := MatrixMultiply(Result,CreateRotationMatrixX(sin(_AngY),cos(_AngY))); end; end; // This should be used instead. Based on glRotate. function TVertexTransformationUtils.GetRotationMatrixFromVector(_Vector: TVector3f): TMatrix; var Ang, Cossine, Sine : single; OrtogonalVector: TVector3f; begin if _Vector.Z <> 0 then begin Ang := CleanAngleRadians(arccos(-_Vector.Z)); end else begin Ang := 0.5 * pi; end; OrtogonalVector := CrossProduct(_Vector,SetVector(0,0,-1)); Normalize(OrtogonalVector); Cossine := Cos(Ang); Sine := Sin(Ang); Result := IdentityMatrix; Result[0,0] := (OrtogonalVector.X * OrtogonalVector.X)*(1 - Cossine) + Cossine; Result[0,1] := (OrtogonalVector.X * OrtogonalVector.Y)*(1 - Cossine) - (OrtogonalVector.Z * Sine); Result[0,2] := (OrtogonalVector.X * OrtogonalVector.Z)*(1 - Cossine) + (OrtogonalVector.Y * Sine); Result[1,0] := (OrtogonalVector.Y * OrtogonalVector.X)*(1 - Cossine) + (OrtogonalVector.Z * Sine); Result[1,1] := (OrtogonalVector.Y * OrtogonalVector.Y)*(1 - Cossine) + Cossine; Result[1,2] := (OrtogonalVector.Y * OrtogonalVector.Z)*(1 - Cossine) - (OrtogonalVector.X * Sine); Result[2,0] := (OrtogonalVector.Z * OrtogonalVector.X)*(1 - Cossine) - (OrtogonalVector.Y * Sine); Result[2,1] := (OrtogonalVector.Z * OrtogonalVector.Y)*(1 - Cossine) + (OrtogonalVector.X * Sine); Result[2,2] := (OrtogonalVector.Z * OrtogonalVector.Z)*(1 - Cossine) + Cossine; end; function TVertexTransformationUtils.GetUVCoordinates(const _Position: TVector3f; _TransformMatrix: TMatrix): TVector2f; begin Result.U := (_Position.X * _TransformMatrix[0,0]) + (_Position.Y * _TransformMatrix[0,1]) + (_Position.Z * _TransformMatrix[0,2]); Result.V := (_Position.X * _TransformMatrix[1,0]) + (_Position.Y * _TransformMatrix[1,1]) + (_Position.Z * _TransformMatrix[1,2]); end; // Angle Detector // GetRotationX has been deprecated (use XZ instead) function TVertexTransformationUtils.GetRotationX(const _Vector: TVector3f): single; begin if _Vector.Y <> 0 then begin Result := CleanAngleRadians((-1 * (_Vector.Y) / (Abs(_Vector.Y))) * arccos(sqrt((_Vector.X * _Vector.X) + (_Vector.Z * _Vector.Z)))); end else begin Result := 0; end; end; // Horizontal rotation. (Rotation is 0 if it points to z = 1) function TVertexTransformationUtils.GetRotationY(const _Vector: TVector3f): single; begin if (_Vector.X <> 0) then begin Result := CleanAngleRadians(((_Vector.X) / (Abs(_Vector.X))) * arccos(abs(_Vector.Z) / sqrt((_Vector.X * _Vector.X) + (_Vector.Z * _Vector.Z)))); end else if (_Vector.Z >= 0) then begin Result := 0; end else begin Result := Pi; end; end; // Vertical rotation. (Rotation is 0 if y = 0) function TVertexTransformationUtils.GetRotationXZ(const _Vector: TVector3f): single; begin if _Vector.Y <> 0 then begin if _Vector.Y = 1 then begin Result := Pi * 0.5; end else if _Vector.Y = -1 then begin Result := Pi * 1.5; end else begin if _Vector.Z = max(abs(_Vector.Z),abs(_Vector.X)) then begin Result := CleanAngleRadians(((_Vector.Z) / (Abs(_Vector.Z))) * arcsin(_Vector.Y / sqrt((_Vector.Y * _Vector.Y) + (_Vector.Z * _Vector.Z)))); end else begin Result := CleanAngleRadians(((_Vector.X) / (Abs(_Vector.X))) * arcsin(_Vector.Y / sqrt((_Vector.X * _Vector.X) + (_Vector.Y * _Vector.Y)))); end; end; end else begin Result := 0; end; end; // Angle Operators function TVertexTransformationUtils.CleanAngle(Angle: single): single; begin Result := Angle; if Result < 0 then Result := Result + 360; if Result >= 360 then Result := Result - 360; end; function TVertexTransformationUtils.CleanAngleRadians(Angle: single): single; const C_2PI = 2 * Pi; begin Result := Angle; if Result < 0 then Result := Result + C_2Pi; if Result >= C_2Pi then Result := Result - C_2Pi; end; function TVertexTransformationUtils.CleanAngle90Radians(Angle: single): single; const C_2PI = 2 * Pi; C_PIDiv2 = Pi / 2; C_3PIDiv2 = 1.5 * Pi; begin Result := Angle; // Ensure that it is between 0 and 2Pi. if Result < 0 then Result := Result + C_2Pi; if Result > C_2Pi then Result := Result - C_2Pi; // Now we ensure that it will be either between (0, Pi/2) and (3Pi/2 and 2Pi). if (Result > C_PIDiv2) and (Result <= Pi) then Result := Pi - Result else if (Result > Pi) and (Result < C_3PIDiv2) then Result := C_2Pi - (Result - Pi); end; // Tangent Plane Detector procedure TVertexTransformationUtils.GetTangentPlaneFromNormalAndDirection(var _AxisX,_AxisY: TVector3f; const _Normal,_Direction: TVector3f); var Direction: TVector3f; begin Direction := SetVector(_Direction); Normalize(Direction); _AxisY := CrossProduct(_Normal,Direction); Normalize(_AxisY); _AxisX := CrossProduct(_Normal,_AxisY); Normalize(_AxisX); end; function TVertexTransformationUtils.ProjectVectorOnTangentPlane(const _Normal,_Vector: TVector3f): TVector3f; begin // Result := _Vector - Dot(_Vector,_Normal)*_Normal; Result := SubtractVector(_Vector,ScaleVector(_Normal,DotProduct(_Vector,_Normal))); end; function TVertexTransformationUtils.GetArcCosineFromTangentPlane(const _Vector, _AxisX, _AxisY: TVector3f): single; var Signal : single; Angle: single; begin Signal := Epsilon(DotProduct(_Vector,_AxisY)); if Signal >= 0 then begin Signal := 1; end else if Signal < 0 then begin Signal := -1; end; Angle := DotProduct(_Vector,_AxisX); if Angle > 1 then Angle := 1 else if Angle < -1 then Angle := -1; Result := Signal * ArcCos(Angle); end; function TVertexTransformationUtils.GetArcCosineFromAngleOnTangentSpace(_VI,_V1,_V2: TVector3f; _VertexNormal: TVector3f): single; var Direction1,Direction2: TVector3f; begin // Get the projection of the edges on Tangent Plane {$ifdef SMOOTH_TEST} //GlobalVars.SmoothFile.Add('VI: (' + FloatToStr(_VI.X) + ', ' + FloatToStr(_VI.Y) + ', ' + FloatToStr(_VI.Z) + '), V1: (' + FloatToStr(_V1.X) + ', ' + FloatToStr(_V1.Y) + ', ' + FloatToStr(_V1.Z) + ') and V2: (' + FloatToStr(_V2.X) + ', ' + FloatToStr(_V2.Y) + ', ' + FloatToStr(_V2.Z) + ').'); {$endif} Direction1 := SubtractVector(_V1,_VI); Normalize(Direction1); {$ifdef SMOOTH_TEST} //GlobalVars.SmoothFile.Add('Direction 1: (' + FloatToStr(Direction1.X) + ', ' + FloatToStr(Direction1.Y) + ', ' + FloatToStr(Direction1.Z) + ')'); {$endif} Direction1 := ProjectVectorOnTangentPlane(_VertexNormal,Direction1); Normalize(Direction1); Direction2 := SubtractVector(_V2,_VI); Normalize(Direction2); {$ifdef SMOOTH_TEST} //GlobalVars.SmoothFile.Add('Direction 2: (' + FloatToStr(Direction2.X) + ', ' + FloatToStr(Direction2.Y) + ', ' + FloatToStr(Direction2.Z) + ')'); {$endif} Direction2 := ProjectVectorOnTangentPlane(_VertexNormal,Direction2); Normalize(Direction2); {$ifdef SMOOTH_TEST} //GlobalVars.SmoothFile.Add('Projected Direction 1: (' + FloatToStr(Direction1.X) + ', ' + FloatToStr(Direction1.Y) + ', ' + FloatToStr(Direction1.Z) + ') and Projected Direction 2: (' + FloatToStr(Direction2.X) + ', ' + FloatToStr(Direction2.Y) + ', ' + FloatToStr(Direction2.Z) + ') at VertexNormal: (' + FloatToStr(_VertexNormal.X) + ', ' + FloatToStr(_VertexNormal.Y) + ', ' + FloatToStr(_VertexNormal.Z) + ')'); {$endif} // Return dot product. Result := CleanAngleRadians(ArcCos(DotProduct(Direction1,Direction2))); {$ifdef SMOOTH_TEST} //GlobalVars.SmoothFile.Add('Resulting Angle is: ' + FloatToStr(Result) + '.'); {$endif} end; function TVertexTransformationUtils.IsPointInsideTriangle(const _V1,_V2,_V3,_P : TVector2f): boolean; var V0,V1,V2: TVector2f; dot00,dot01,dot02,dot11,dot12,invDenom,u,v: single; begin // Compute vectors v0.U := _V3.U - _V1.U; v0.V := _V3.V - _V1.V; v1.U := _V2.U - _V1.U; v1.V := _V2.V - _V1.V; v2.U := _P.U - _V1.U; v2.V := _P.V - _V1.V; // Compute dot products dot00 := DotProduct(v0, v0); dot01 := DotProduct(v0, v1); dot02 := DotProduct(v0, v2); dot11 := DotProduct(v1, v1); dot12 := DotProduct(v1, v2); // Compute barycentric coordinates invDenom := 1 / ((dot00 * dot11) - (dot01 * dot01)); u := ((dot11 * dot02) - (dot01 * dot12)) * invDenom; v := ((dot00 * dot12) - (dot01 * dot02)) * invDenom; // Check if point is in triangle Result := ((u > 0) and (v > 0) and ((u + v) < 1)); end; end.
unit MeshUnsharpMaskingCommand; interface uses ControllerDataTypes, ActorActionCommandBase, Actor; {$INCLUDE source/Global_Conditionals.inc} type TMeshUnsharpMaskingCommand = class (TActorActionCommandBase) public constructor Create(var _Actor: TActor; var _Params: TCommandParams); override; procedure Execute; override; end; implementation uses StopWatch, MeshUnsharpMasking, GlobalVars, SysUtils; constructor TMeshUnsharpMaskingCommand.Create(var _Actor: TActor; var _Params: TCommandParams); begin FCommandName := 'Mesh Unsharp Masking Method'; inherited Create(_Actor,_Params); end; procedure TMeshUnsharpMaskingCommand.Execute; var Operation : TMeshUnsharpMasking; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} Operation := TMeshUnsharpMasking.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD]); Operation.Execute; Operation.Free; {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('Mesh Unsharp Masking for LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; end.
unit uTPLb_XXTEA; {* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} interface uses uTPLb_StreamCipher, uTPLb_BlockCipher, Classes, Types, uTPLb_Decorators; type {$IF compilerversion >= 21} [DesignDescription( 'XXTEA is implemented here with the following options set so:'#13#10 + '(*) The encoding of longwords is little-endien.'#13#10 + '(*) Empty plaintext message maps to empty ciphertext message.'#13#10 + '(*) For plaintext messages less than or equal to 199 bytes:'#13#10 + '(**) The end of the plaintext is padded out PKCS7 style (RFC 3852) to 4-byte alignment;'#13#10 + '(**) 8 bytes of salt is appended to the plaintext;'#13#10 + '(**) The resultant extended plaintext is encrypted in XXTEA long block mode -'#13#10 + ' That is to say, the block size is set to be the message size.'#13#10 + '(*) For plaintext messages more than or equal to 200 bytes:'#13#10 + '(**) 12 random bytes are appended to the plaintext;'#13#10 + '(**) The block size is fixed to 212 bytes;'#13#10 + '(**) Normal block-cipher encryption applies according to your selected'#13#10 + ' chaining mode. As usual, this includes 64 bits of automatic salting,'#13#10 + ' and smart block quantisation (Ciphertext stealing or key-streaming,'#13#10 + ' as appropriate to the chaining mode).' )] {$ENDIF} TXXTEA_LargeBlock = class( TInterfacedObject, IStreamCipher, ICryptoGraphicAlgorithm, IControlObject) private FChaining: IBlockChainingModel; function DisplayName: string; function ProgId: string; function Features: TAlgorithmicFeatureSet; function DefinitionURL: string; function WikipediaReference: string; function GenerateKey( Seed: TStream): TSymetricKey; function LoadKeyFromStream( Store: TStream): TSymetricKey; function SeedByteSize: integer; function Parameterize( const Params: IInterface): IStreamCipher; function Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; function Start_Decrypt( Key: TSymetricKey; PlainText : TStream): IStreamDecryptor; function ControlObject: TObject; public constructor Create; end; TTEA_Key = packed array[ 0.. 3 ] of longword; procedure XXTEA_Encrypt( // Corrected Block TEA encryption primitive. const Key: TTEA_Key; const Plaintext: TLongWordDynArray; // At least 2 var Ciphertext: TLongWordDynArray); // Same length as Plaintext procedure XXTEA_Decrypt( // Corrected Block TEA encryption primitive. const Key: TTEA_Key; const Ciphertext: TLongWordDynArray; // At least 2 var Plaintext : TLongWordDynArray); // Same length as Ciphertext implementation uses SysUtils, Math, uTPLb_StreamUtils, uTPLb_Constants, uTPLb_StreamToBlock, uTPLb_PointerArithmetic, uTPLb_I18n, uTPLb_CBC, uTPLb_Random {$IF compilerversion <= 17} , uTPLb_D7Compatibility {$ENDIF} ; type TXXTEA_LE_Key = class( TSymetricKey) public FNativeKey: TTEA_Key; constructor Create( Seed: TStream; isStore: boolean); {Above: False=from password or random seed; True=from SaveToStream} procedure SaveToStream( Stream: TStream); override; procedure Burn; override; end; TXXTEA_LargeBlock_LE_Encryptor = class( TInterfacedObject, IStreamEncryptor, IBlockCipherSelector) public constructor Create( Owner1: TXXTEA_LargeBlock; Key: TXXTEA_LE_Key; CipherText: TStream); destructor Destroy; override; private FOwner: TXXTEA_LargeBlock; FKey: TXXTEA_LE_Key; FCipherText: TStream; FBuffer: TBytes; FBufLen: integer; FisBuffering: boolean; FFixedCipher: IStreamCipher; FFixedEnc: IStreamEncryptor; function GetBlockCipher : IBlockCipher; function GetChainMode : IBlockChainingModel; procedure Encrypt( const Plaintext: TStream); procedure End_Encrypt; procedure Reset; end; TAbbrieviatingStream = class( TStream) private FOutputStream: TStream; FClipAmount: integer; FBuffer: TBytes; FBufLen: integer; protected function GetSize: int64; override; procedure SetSize( const NewSize: int64); override; public constructor Create( OutputStream1: TStream; ClipAmount1: integer); function Read ( var Buffer; Count: Longint): Longint; override; function Write( const Buffer; Count: Longint): Longint; override; function Seek ( const Offset: Int64; Origin: TSeekOrigin): int64; override; procedure EndStreaming; end; TXXTEA_LargeBlock_LE_Decryptor = class( TInterfacedObject, IStreamDecryptor, IBlockCipherSelector) public constructor Create( Owner1: TXXTEA_LargeBlock; Key: TXXTEA_LE_Key; PlainText: TStream); destructor Destroy; override; private FOwner: TXXTEA_LargeBlock; FKey: TXXTEA_LE_Key; FPlainText: TStream; FBuffer: TBytes; FBufLen: integer; FisBuffering: boolean; FFixedCipher: IStreamCipher; FFixedDec: IStreamDecryptor; FOutputBuffer: TAbbrieviatingStream; function GetBlockCipher : IBlockCipher; function GetChainMode : IBlockChainingModel; procedure Decrypt( const Ciphertext: TStream); procedure End_Decrypt; procedure Reset; end; TXXTEA_Block = class( TInterfacedObject, IBlockCipher, ICryptoGraphicAlgorithm) private FBlockSize: integer; function DisplayName: string; function ProgId: string; function Features: TAlgorithmicFeatureSet; function DefinitionURL: string; function WikipediaReference: string; function GenerateKey( Seed: TStream): TSymetricKey; function LoadKeyFromStream( Store: TStream): TSymetricKey; function BlockSize: integer; // in units of bits. Must be a multiple of 8. function KeySize: integer; // in units of bits. function SeedByteSize: integer; // Size that the input of the GenerateKey must be. function MakeBlockCodec( Key: TSymetricKey): IBlockCodec; function SelfTest_Key: TBytes; function SelfTest_Plaintext: TBytes; function SelfTest_Ciphertext: TBytes; public constructor Create( BlockSize1: integer); end; TXXTEA_BlockCodec = class( TInterfacedObject, IBlockCodec) private FBlockSize_InBytes: integer; FKey: TXXTEA_LE_Key; FPlaintext_Longs: TLongWordDynArray; FCiphertext_Longs: TLongWordDynArray; procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream); procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream); procedure Reset; procedure Burn; public constructor Create( Key1: TXXTEA_LE_Key; BlockSize1: integer); end; //type // TTEA_Key = array[ 0.. 3 ] of longword; // TLongs = array of longword; // XXTEA primitives // In the following comment section, read ")-" as "}". { The original formulation of the Corrected Block TEA algorithm, published by David Wheeler and Roger Needham, is as follows: #define MX (z>>5^y<<2) + (y>>3^z<<4)^(sum^y) + (k[p&3^e]^z); long btea(long* v, long n, long* k) { unsigned long z=v[n-1], y=v[0], sum=0, e, DELTA=0x9e3779b9; long p, q ; if (n > 1) { /* Coding Part */ q = 6 + 52/n; while (q-- > 0) { sum += DELTA; e = (sum >> 2) & 3; for (p=0; p<n-1; p++) y = v[p+1], z = v[p] += MX; y = v[0]; z = v[n-1] += MX; )- return 0 ; )- else if (n < -1) { /* Decoding Part */ n = -n; q = 6 + 52/n; sum = q*DELTA ; while (sum != 0) { e = (sum >> 2) & 3; for (p=n-1; p>0; p--) z = v[p-1], y = v[p] -= MX; z = v[n-1]; y = v[0] -= MX; sum -= DELTA; )- return 0; )- return 1; )- According to Needham and Wheeler: BTEA will encode or decode n words as a single block where n > 1 * v is the n word data vector * k is the 4 word key * n is negative for decoding * if n is zero result is 1 and no coding or decoding takes place, otherwise the result is zero * assumes 32 bit 'long' and same endian coding and decoding } const DELTA = $9e3779b9; // For Little-endien implementations only. function Mx( const z, y, sum: longword; const k: TTEA_Key; const p, e: longword): longword; {$IF CompilerVersion >= 17.0} inline; {$ENDIF} begin result := (((z shr 5) xor (y shl 2)) + ((y shr 3) xor (z shl 4))) xor ((sum xor y) + (k[(p and 3) xor e] xor z)) end; procedure XXTEA_Encrypt( // Corrected Block TEA encryption primitive. const Key: TTEA_Key; const Plaintext : TLongWordDynArray; // At least 2 var Ciphertext: TLongWordDynArray); // Same length as Plaintext var n: integer; z, sum: longword; e, q, p: LongWord; begin n := Length( Plaintext); Assert( n >= 2, 'Plaintext too short'); z := Plaintext[ n-1]; if Length( Ciphertext) <> n then SetLength( Ciphertext, n); Move( Plaintext[0], Ciphertext[0], n * SizeOf( longword)); sum := 0; for q := 5 + (52 div n) downto 0 do begin Inc( sum, DELTA); e := (sum shr 2) and 3; for p := 0 to n - 2 do begin z := Ciphertext[ p] + MX( z, Ciphertext[ p + 1], sum, Key, p, e); // z = v[p] += MX Ciphertext[ p] := z end; z := Ciphertext[ n-1] + MX( z, Ciphertext[ 0], sum, Key, n - 1, e); Ciphertext[ n-1] := z end end; procedure XXTEA_Decrypt( // Corrected Block TEA decryption primitive. const Key: TTEA_Key; const Ciphertext: TLongWordDynArray; // At least 2 var Plaintext : TLongWordDynArray); // Same length as Ciphertext var n: integer; y: LongWord; sum: LongWord; e: LongWord; p: LongWord; begin n := Length( Ciphertext); Assert( n >= 2, 'Ciphertext too short'); if Length( Plaintext) <> n then SetLength( Plaintext, n); Move( Ciphertext[0], Plaintext[0], n * SizeOf( longword)); sum := (6 + (52 div Cardinal(n))) * DELTA; y := Plaintext[0]; while sum <> 0 do begin e := (sum shr 2) and 3; for p := n - 1 downto 1 do begin y := Plaintext[p] - Mx( Plaintext[p - 1], y, sum, Key, p, e); Plaintext[p] := y end; y := Plaintext[0] - Mx( Plaintext[n-1], y, sum, Key, 0, e); Plaintext[0] := y; Dec( sum, DELTA) end end; { TXXTEA_LargeBlock } function TXXTEA_LargeBlock.ControlObject: TObject; begin result := self end; constructor TXXTEA_LargeBlock.Create; begin end; function TXXTEA_LargeBlock.DefinitionURL: string; begin result := 'http://www.movable-type.co.uk/scripts/xxtea.pdf' end; function TXXTEA_LargeBlock.DisplayName: string; begin result := 'XXTEA (large block; little-endien)' end; function TXXTEA_LargeBlock.Features: TAlgorithmicFeatureSet; begin result := [afCryptographicallyWeak, afDoesNotNeedSalt, afOpenSourceSoftware] end; function TXXTEA_LargeBlock.GenerateKey( Seed: TStream): TSymetricKey; begin result := TXXTEA_LE_Key.Create( Seed, False) end; function TXXTEA_LargeBlock.LoadKeyFromStream( Store: TStream): TSymetricKey; begin result := TXXTEA_LE_Key.Create( Store, True) end; function TXXTEA_LargeBlock.Parameterize( const Params: IInterface): IStreamCipher; var BlockCipherSelector: IBlockCipherSelector; Chaining: IBlockChainingModel; Newbie: TXXTEA_LargeBlock; begin result := nil; if assigned( FChaining) then exit; if Supports( Params, IBlockCipherSelector, BlockCipherSelector) then Chaining := BlockCipherSelector.GetChainMode; if not assigned( Chaining) then exit; Newbie := TXXTEA_LargeBlock.Create; Newbie.FChaining := Chaining; result := Newbie end; function TXXTEA_LargeBlock.ProgId: string; begin result := XXTEA_Large_ProgId end; function TXXTEA_LargeBlock.SeedByteSize: integer; begin result := 128 end; function TXXTEA_LargeBlock.Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; begin result := TXXTEA_LargeBlock_LE_Encryptor .Create( self, Key as TXXTEA_LE_Key, Ciphertext) end; function TXXTEA_LargeBlock.Start_Decrypt( Key: TSymetricKey; PlainText: TStream): IStreamDecryptor; begin result := TXXTEA_LargeBlock_LE_Decryptor .Create( self, Key as TXXTEA_LE_Key, Plaintext) end; function TXXTEA_LargeBlock.WikipediaReference: string; begin result := 'XXTEA' end; { TXXTEA_LE_Key } procedure TXXTEA_LE_Key.Burn; begin FillChar( FNativeKey, SizeOf( FNativeKey), 0) end; constructor TXXTEA_LE_Key.Create( Seed: TStream; isStore: boolean); begin Seed.ReadBuffer( FNativeKey, SizeOf( FNativeKey)) end; procedure TXXTEA_LE_Key.SaveToStream( Stream: TStream); begin Stream.WriteBuffer( FNativeKey, SizeOf( FNativeKey)) end; const EncryptionBufferSize = 200; LargeMessageSaltTailLength = 12; DecryptionBufferSize = EncryptionBufferSize + LargeMessageSaltTailLength; BlockSize_InBytes = 212; // 212 bytes or 53 longwords. // This does not have to be 53 longwords. It is fairly arbitary. // Lower values would be valid, and perhaps more appropriate for // 8-bit chaining modes. BlockSize_InBits = BlockSize_InBytes * 8; { TXXTEA_LargeBlock_LE_Encryptor } constructor TXXTEA_LargeBlock_LE_Encryptor.Create( Owner1: TXXTEA_LargeBlock; Key: TXXTEA_LE_Key; CipherText: TStream); begin FOwner := Owner1; FKey := Key; FCiphertext := CipherText; SetLength( FBuffer, EncryptionBufferSize); FBufLen := 0; FisBuffering := True end; destructor TXXTEA_LargeBlock_LE_Encryptor.Destroy; begin SetLength( FBuffer, 0); inherited end; { XXTEA is a variable block length cipher. So how does that fit into our model of block ciphers being of fixed block length? Apply the following strategy. Let n = Size of the plaintext payload (before salting, padding etc) in bytes. c = Size of the ciphertext message in bytes. B = Size of the XXTEA block in bytes. 1. ENCRYPTION ============= Upon encryption buffer up to 200 bytes. 1.1 Case One: An empty plaintext maps to an empty ciphertext. n = 0 ==> c := 0 1.2 Small message case: For a small message, just encrypt the whole thing directly in one block. Salt and pad as required. n <= 199 ==> 1.2.1 Pad the message out at the tail to make it align to quad-byte. The last pad byte value should be equal to the count of pad bytes, in esse 1 to 4. There must be at least 1 pad byte. 1.2.2 Salt the plaintext. That is to say inject 8 random bytes at the tail of the plaintext. Due to the cyclic nature of XXTEA, the salt does not need to be at the head. 1.2.3 Encrypt the salted padded message as one XXTEA block. c in [n+9 .. n+12] c <= 211 B = c 1.3 Large message case: For a large message, to be practical we must set reasonable block sizes. Append 12 bytes of salt at the tail; and use normal block-to-stream adaption with a block size of 212 bytes or 53 longwords. n >= 200 ==> 1.3.1 Append 12 random bytes to the end. 1.3.2 Set block size to fixed 212 bytes. 1.3.3 Encrypt using StreamToBlock adapter with XXTEA and the user's requested chaining mode. This will intrinsically include 8 bytes of salt (unless the mode is ECB), and block quantisation most appropriate to the selected chaining mode. c >= n + 12 c >= 212 B = 212 2. DECRYPTION ============= Upon decryption buffer up to 212 bytes. 2.1 Case One: An empty ciphertext maps to an empty plaintext. c = 0 ==> n := 0 2.2 Small message case: For a small message, just decrypt the whole thing directly in one block. Remove salt and de-pad as required. c <= 211 ==> 2.2.1 Decrypt the message as one XXTEA block. 2.2.2 De-salt the decrypted plaintext. That is to say discard the last 8 bytes at the head of the decrypted plaintext. 2.2.3 De-pad the message out at the tail. The number of pad bytes to remove is the value of the last byte. B := c n in [c - 12 .. c - 9] n <= 199 2.3 Large message case: For a large message, decrypt with a normal block-to-stream adaption. Strip 12 bytes off from the tail; and use a block size of 212 bytes. c >= 212 ==> 3.3.1 Set block size to fixed 212 bytes. 3.3.2 Decrypt using StreamToBlock adapter with XXTEA and the user's requested chaining mode. This will intrinsically include 8 bytes of salt (unless the mode is ECB), and block quantisation most appropriate to the selected chaining mode. 3.3.3 Discard 12 bytes at the end. c >= n + 12 n >= 200 B := 212 } procedure TXXTEA_LargeBlock_LE_Encryptor.Encrypt( const Plaintext: TStream); var Amnt: integer; Tmp: IStreamCipher; PTCopy: TStream; begin Amnt := -1; if FisBuffering then begin // At this point we are not sure if it going to be large message // or short message case. Amnt := EncryptionBufferSize - FBufLen; Amnt := Plaintext.Read( FBuffer[FBufLen], Amnt); Inc( FBufLen, Amnt); if FBufLen >= EncryptionBufferSize then begin // Large message case, switch to adapter. FFixedCipher := TStreamToBlock_Adapter.Create; Tmp := FFixedCipher.Parameterize( self); // The above line casts this to IBlockCipherSelector then calls: // GetBlockCipher; and // GetChainMode if assigned( Tmp) then FFixedCipher := Tmp; FFixedEnc := FFixedCipher.Start_Encrypt( FKey, FCipherText); PTCopy := TMemoryStream.Create; try PTCopy.Write( FBuffer[0], FBufLen); PTCopy.Position := 0; FFixedEnc.Encrypt( PTCopy) finally PTCopy.Free end ; FBufLen := 0; FisBuffering := False end end; if (not FisBuffering) and (Amnt <> 0) then FFixedEnc.Encrypt( Plaintext) end; procedure TXXTEA_LargeBlock_LE_Encryptor.End_Encrypt; var RequiredSizeIncrease, RequiredSize: integer; j, L: integer; PlaintextArray, CiphertextArray: TLongWordDynArray; PTCopy: TMemoryStream; begin if FisBuffering then begin if FBufLen = 0 then exit; // n <= 199 ==> // 1.2.1 Pad the message out at the tail to make it align to quad-byte. // The last pad byte value should be equal to the count of pad bytes, // in esse 1 to 4. There must be at least 1 pad byte. // 1.2.2 Salt the plaintext. That is to say inject 8 random bytes at the // tail of the plaintext. Due to the cyclic nature of XXTEA, the // salt does not need to be at the head. // 1.2.3 Encrypt the salted padded message as one XXTEA block. RequiredSizeIncrease := 4 - (FBufLen mod 4); RequiredSize := FBufLen + RequiredSizeIncrease; // How much padding is needed? for j := FBufLen to FBufLen + RequiredSizeIncrease - 1 do FBuffer[j] := RequiredSizeIncrease; // Pad it out. L := (RequiredSize div 4) + 2; SetLength( PlaintextArray, L); // Setup longword array. Move( FBuffer[0], PlaintextArray[0], RequiredSize); // Convert padded payload to longwords. TRandomStream.Instance.Read( PlaintextArray[L-2], 8); // Salting. SetLength( CiphertextArray, L); XXTEA_Encrypt( FKey.FNativeKey, PlaintextArray, CiphertextArray); // One-block encryption. FCipherText.Write( CiphertextArray[0], L * 4) end else begin PTCopy := TMemoryStream.Create; try PTCopy.Size := LargeMessageSaltTailLength; TRandomStream.Instance.Read( PTCopy.Memory^, LargeMessageSaltTailLength); // 12 random bytes PTCopy.Position := 0; FFixedEnc.Encrypt( PTCopy) finally PTCopy.Free end ; FFixedEnc.End_Encrypt end; FFixedEnc := nil; FFixedCipher := nil end; function TXXTEA_LargeBlock_LE_Encryptor.GetBlockCipher: IBlockCipher; begin result := TXXTEA_Block.Create( BlockSize_InBits) end; function TXXTEA_LargeBlock_LE_Encryptor.GetChainMode: IBlockChainingModel; begin // Called by Parameterize. result := FOwner.FChaining; if not assigned( result) then result := TCBC.Create end; procedure TXXTEA_LargeBlock_LE_Encryptor.Reset; begin FBufLen := 0; FisBuffering := True; FFixedCipher := nil; FFixedEnc := nil end; { TXXTEA_LargeBlock_LE_Decryptor } constructor TXXTEA_LargeBlock_LE_Decryptor.Create( Owner1: TXXTEA_LargeBlock; Key: TXXTEA_LE_Key; PlainText: TStream); begin FOwner := Owner1; FKey := Key; FPlaintext := PlainText; SetLength( FBuffer, DecryptionBufferSize); FBufLen := 0; FisBuffering := True end; procedure TXXTEA_LargeBlock_LE_Decryptor.Decrypt( const Ciphertext: TStream); var Amnt: integer; Tmp: IStreamCipher; PTCopy: TStream; begin Amnt := -1; if FisBuffering then begin // At this point we are not sure if it going to be large message // or short message case. Amnt := DecryptionBufferSize - FBufLen; Amnt := Ciphertext.Read( FBuffer[FBufLen], Amnt); Inc( FBufLen, Amnt); if FBufLen >= DecryptionBufferSize then begin // Large message case, switch to adapter. FFixedCipher := TStreamToBlock_Adapter.Create; Tmp := FFixedCipher.Parameterize( self); // The above line casts this to IBlockCipherSelector then calls: // GetBlockCipher; and // GetChainMode if assigned( Tmp) then FFixedCipher := Tmp; FreeAndNil( FOutputBuffer); FOutputBuffer := TAbbrieviatingStream .Create( FPlainText, LargeMessageSaltTailLength); FFixedDec := FFixedCipher.Start_Decrypt( FKey, FOutputBuffer); PTCopy := TMemoryStream.Create; try PTCopy.Write( FBuffer[0], FBufLen); PTCopy.Position := 0; FFixedDec.Decrypt( PTCopy) finally PTCopy.Free end ; FBufLen := 0; FisBuffering := False end end; if (not FisBuffering) and (Amnt <> 0) then FFixedDec.Decrypt( Ciphertext) end; destructor TXXTEA_LargeBlock_LE_Decryptor.Destroy; begin FFixedDec := nil; FFixedCipher := nil; FreeAndNil( FOutputBuffer); inherited end; procedure TXXTEA_LargeBlock_LE_Decryptor.End_Decrypt; var RequiredSizeDecrease: integer; L: integer; PlaintextArray, CiphertextArray: TLongWordDynArray; begin if FisBuffering then begin if FBufLen = 0 then exit; // c <= 211 ==> // 2.2.1 Decrypt the message as one XXTEA block. // 2.2.2 De-salt the decrypted plaintext. That is to say discard the last // 8 bytes at the head of the decrypted plaintext. // 2.2.3 De-pad the message out at the tail. The number of pad bytes to // remove is the value of the last byte. L := FBufLen div 4; SetLength( CiphertextArray, L); // Setup longword array. SetLength( PlaintextArray , L); if L >= 2 then begin // XXTEA only valid if blocksize is at least 2 longwords. // With the padding, this should ALWAYS be the case. // Otherwise the ciphertext message is invalid. Move( FBuffer[0], CiphertextArray[0], FBufLen); // Convert padded message to longwords. XXTEA_Decrypt( FKey.FNativeKey, CiphertextArray, PlaintextArray); // One-block encryption. end; if FBufLen >= 8 then Dec( FBufLen, 8) // de-salt else FBufLen := 0; if FBufLen > 0 then // Calculate pad. RequiredSizeDecrease := FBuffer[FBufLen-1] else RequiredSizeDecrease := 0; if FBufLen >= RequiredSizeDecrease then Dec( FBufLen, RequiredSizeDecrease) // de-pad else FBufLen := 0; if L > 0 then FPlainText.Write( CiphertextArray[0], L * 4) end else begin FFixedDec.End_Decrypt; FOutputBuffer.EndStreaming; // Discard last 12 bytes FreeAndNil( FOutputBuffer) end; FFixedDec := nil; FFixedCipher := nil end; function TXXTEA_LargeBlock_LE_Decryptor.GetBlockCipher: IBlockCipher; begin result := TXXTEA_Block.Create( BlockSize_InBits) end; function TXXTEA_LargeBlock_LE_Decryptor.GetChainMode: IBlockChainingModel; begin result := FOwner.FChaining; if not assigned( result) then result := TCBC.Create end; procedure TXXTEA_LargeBlock_LE_Decryptor.Reset; begin FBufLen := 0; FisBuffering := True; FFixedCipher := nil; FFixedDec := nil; FreeAndNil( FOutputBuffer) end; { TXXTEA_Block } function TXXTEA_Block.BlockSize: integer; begin result := FBlockSize end; constructor TXXTEA_Block.Create( BlockSize1: integer); begin FBlockSize := BlockSize1 end; function TXXTEA_Block.DefinitionURL: string; begin result := '' // Not used. end; function TXXTEA_Block.DisplayName: string; begin result := '' // Not used. end; function TXXTEA_Block.Features: TAlgorithmicFeatureSet; begin result := [afCryptographicallyWeak, afForRunTimeOnly, afOpenSourceSoftware] end; function TXXTEA_Block.GenerateKey( Seed: TStream): TSymetricKey; begin result := nil // Not used. end; function TXXTEA_Block.KeySize: integer; begin // Not used result := SizeOf( TTEA_Key) * 8 end; function TXXTEA_Block.LoadKeyFromStream( Store: TStream): TSymetricKey; begin result := nil // Not used. end; function TXXTEA_Block.MakeBlockCodec( Key: TSymetricKey): IBlockCodec; begin result := TXXTEA_BlockCodec.Create( Key as TXXTEA_LE_Key, FBlockSize) end; function TXXTEA_Block.ProgId: string; begin result := '' // Not used end; function TXXTEA_Block.SeedByteSize: integer; begin result := -1 // Not used end; function TXXTEA_Block.SelfTest_Ciphertext: TBytes; begin result := nil // Not used end; function TXXTEA_Block.SelfTest_Key: TBytes; begin result := nil // Not used end; function TXXTEA_Block.SelfTest_Plaintext: TBytes; begin result := nil // Not used end; function TXXTEA_Block.WikipediaReference: string; begin result := '' // Not used end; { TXXTEA_BlockCodec } procedure TXXTEA_BlockCodec.Burn; begin // Not used end; constructor TXXTEA_BlockCodec.Create( Key1: TXXTEA_LE_Key; BlockSize1: integer); begin FKey := Key1; FBlockSize_InBytes := BlockSize1 div 8; SetLength( FPlaintext_Longs, FBlockSize_InBytes div 4); // At least 2 longwords SetLength( FCiphertext_Longs, Length( FPlaintext_Longs)) end; procedure TXXTEA_BlockCodec.Decrypt_Block( Plaintext, Ciphertext: TMemoryStream); begin Move( Ciphertext.Memory^, FCiphertext_Longs[0], FBlockSize_InBytes); XXTEA_Decrypt( FKey.FNativeKey, FCiphertext_Longs, FPlaintext_Longs); Move( FPlaintext_Longs[0], Plaintext.Memory^, FBlockSize_InBytes) end; procedure TXXTEA_BlockCodec.Encrypt_Block( Plaintext, Ciphertext: TMemoryStream); begin Move( Plaintext.Memory^, FPlaintext_Longs[0], FBlockSize_InBytes); XXTEA_Encrypt( FKey.FNativeKey, FPlaintext_Longs, FCiphertext_Longs); Move( FCiphertext_Longs[0], Ciphertext.Memory^, FBlockSize_InBytes) end; procedure TXXTEA_BlockCodec.Reset; begin // Not used BurnMemory( FPlaintext_Longs [0], FBlockSize_InBytes); BurnMemory( FCiphertext_Longs[0], FBlockSize_InBytes) end; { TAbbrieviatingStream } constructor TAbbrieviatingStream.Create( OutputStream1: TStream; ClipAmount1: integer); begin FOutputStream := OutputStream1; FClipAmount := ClipAmount1; SetLength( FBuffer, FClipAmount + 1024); FBufLen := 0 end; procedure TAbbrieviatingStream.EndStreaming; begin SetLength( FBuffer, 0) end; function TAbbrieviatingStream.GetSize: int64; begin result := 0 // Not used end; function TAbbrieviatingStream.Read( var Buffer; Count: Integer): Longint; begin result := 0 // Not used end; function TAbbrieviatingStream.Seek( const Offset: Int64; Origin: TSeekOrigin): int64; begin result := 0 // Not used end; procedure TAbbrieviatingStream.SetSize( const NewSize: int64); begin // Not used end; function TAbbrieviatingStream.Write( const Buffer; Count: Integer): Longint; var Amnt, Succeeded: integer; P: PByte; begin P := @Buffer; result := 0; while Count > 0 do begin // 1. Buffer in as much as we can. Amnt := FClipAmount - Length( FBuffer); if Amnt < Count then Amnt := Count; if Amnt > 0 then begin Move( P^, FBuffer[FBufLen], Amnt); Inc( P, Amnt); Inc( FBufLen, Amnt); Dec( Count, Amnt); Inc( result, Amnt) end; // 2. Pass-out our excess above the clip amount. Amnt := FBufLen - FClipAmount; if Amnt > 0 then begin if assigned( FOutputStream) then Succeeded := FOutputStream.Write( FBuffer, Amnt) else Succeeded := 0; if Succeeded > 0 then begin Dec( FBufLen, Succeeded); if FBufLen > 0 then Move( FBuffer[Succeeded], FBuffer[0], FBufLen) end; if Succeeded <> Amnt then break // Fail. Don't go further. end end end; end.
unit OnesComplementOpTest; interface uses DUnitX.TestFramework, uIntXLibTypes, uConstants, uIntX; type [TestFixture] TOnesComplementOpTest = class(TObject) public [Test] procedure ShouldOnesComplementIntX(); [Test] procedure ShouldOnesComplementNegativeIntX(); [Test] procedure ShouldOnesComplementZero(); [Test] procedure ShouldOnesComplementBigIntX(); end; implementation [Test] procedure TOnesComplementOpTest.ShouldOnesComplementIntX(); var value, result: TIntX; val: UInt32; begin val := 11; value := TIntX.Create(11); result := not value; Assert.IsTrue(result = -not val); end; [Test] procedure TOnesComplementOpTest.ShouldOnesComplementNegativeIntX(); var value, result: TIntX; val: UInt32; begin val := 11; value := TIntX.Create(-11); result := not value; Assert.IsTrue(result = not val); end; [Test] procedure TOnesComplementOpTest.ShouldOnesComplementZero(); var value, result: TIntX; begin value := TIntX.Create(0); result := not value; Assert.IsTrue(result = 0); end; [Test] procedure TOnesComplementOpTest.ShouldOnesComplementBigIntX(); var temp1, temp2: TIntXLibUInt32Array; value, result: TIntX; begin SetLength(temp1, 3); temp1[0] := 3; temp1[1] := 5; temp1[2] := TConstants.MaxUInt32Value; SetLength(temp2, 2); temp2[0] := UInt32(not UInt32(3)); temp2[1] := UInt32(not UInt32(5)); value := TIntX.Create(temp1, False); result := not value; Assert.IsTrue(result = TIntX.Create(temp2, True)); end; initialization TDUnitX.RegisterTestFixture(TOnesComplementOpTest); end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : D:\DonnU\SourcesSVN\FMAS-WIN\Contingent_Student\Sources\WSDL\EDBOGuidesToFMASService.wsdl // Encoding : UTF-8 // Version : 1.0 // (12.03.2014 11:31:33 - 1.33.2.5) // ************************************************************************ // unit EDBOGuidesToFMASService; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema" // !:int - "http://www.w3.org/2001/XMLSchema" // !:dateTime - "http://www.w3.org/2001/XMLSchema" // !:boolean - "http://www.w3.org/2001/XMLSchema" // !:decimal - "http://www.w3.org/2001/XMLSchema" ExtensionDataObject = class; { "http://edboservice.ua/" } dAcademicYears = class; { "http://edboservice.ua/" } dLastError = class; { "http://edboservice.ua/" } dUniversities = class; { "http://edboservice.ua/" } dLanguages = class; { "http://edboservice.ua/" } dUniversityFacultets = class; { "http://edboservice.ua/" } dUniversityFacultetSpecialities = class; { "http://edboservice.ua/" } dUniversityFacultetSpecialities2 = class; { "http://edboservice.ua/" } dCourses = class; { "http://edboservice.ua/" } dSpec = class; { "http://edboservice.ua/" } dSpecDirections = class; { "http://edboservice.ua/" } dSpecDirections2 = class; { "http://edboservice.ua/" } dKOATUU = class; { "http://edboservice.ua/" } dStreetTypes = class; { "http://edboservice.ua/" } dUniversityFacultetsRequests = class; { "http://edboservice.ua/" } dUniversityFacultetsRequests2 = class; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // ExtensionDataObject = class(TRemotable) private published end; // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dAcademicYears = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_AcademicYear: Integer; FAcademicYearName: WideString; FAcademicYearDescription: WideString; FAcademicYearDateBegin: TXSDateTime; FAcademicYearDateEnd: TXSDateTime; FAcademicYearDatelLastChange: TXSDateTime; FAcademicYearIsActive: Integer; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_AcademicYear: Integer read FId_AcademicYear write FId_AcademicYear; property AcademicYearName: WideString read FAcademicYearName write FAcademicYearName; property AcademicYearDescription: WideString read FAcademicYearDescription write FAcademicYearDescription; property AcademicYearDateBegin: TXSDateTime read FAcademicYearDateBegin write FAcademicYearDateBegin; property AcademicYearDateEnd: TXSDateTime read FAcademicYearDateEnd write FAcademicYearDateEnd; property AcademicYearDatelLastChange: TXSDateTime read FAcademicYearDatelLastChange write FAcademicYearDatelLastChange; property AcademicYearIsActive: Integer read FAcademicYearIsActive write FAcademicYearIsActive; end; ArrayOfDAcademicYears = array of dAcademicYears; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dLastError = class(TRemotable) private FExtensionData: ExtensionDataObject; FLastErrorCode: Integer; FLastErrorDescription: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property LastErrorCode: Integer read FLastErrorCode write FLastErrorCode; property LastErrorDescription: WideString read FLastErrorDescription write FLastErrorDescription; end; ArrayOfDLastError = array of dLastError; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dUniversities = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_University: Integer; FUniversityKode: WideString; FUniversityDateBegin: TXSDateTime; FUniversityDateEnd: TXSDateTime; FEDRPO: WideString; FDateRegistration: TXSDateTime; FUniversityPhone: WideString; FUniversityEMail: WideString; FWebsite: WideString; FUniversityBossPhone: WideString; FUniversityBossEMail: WideString; FId_UniversityName: Integer; FUniversityFullName: WideString; FUniversityShortName: WideString; FKOATUUCode: WideString; FPostIndex: WideString; FKOATUUFullName: WideString; FId_StreetType: Integer; FStreetTypeFullName: WideString; FStreetTypeShortName: WideString; FUniversityAdress: WideString; FHouceNum: WideString; FUniversityBossLastName: WideString; FUniversityBossFirstName: WideString; FUniversityBossMidleName: WideString; FId_EducationType: Integer; FId_EducationClass: Integer; FEducationOrganizationFullTypeName: WideString; FEducationOrganizationShortTypeName: WideString; FEducationOrganizationClassName: WideString; FId_Language: Integer; FId_UniversityAcreditatin: Integer; FId_UniversityAcreditatinType: Integer; FUniversitiyAcreditatinTypeCode: WideString; FIsUniversityVerifed: Integer; FExistNeedVerification: Integer; FId_UniversityGovernanceType: Integer; FUniversityGovernanceTypeName: WideString; FId_UniversityRegistration: Integer; FId_UniversityRegistrationType: Integer; FUniversityRegistrationTypeName: WideString; FId_RegulationDocument: Integer; FUniversityRegistrationDateBegin: TXSDateTime; FUniversityRegistrationDateEnd: TXSDateTime; FUniversityRegistrationDateLastChange: TXSDateTime; FUniversityRegistrationIsActive: Integer; FUniversityRegistrationusersCount: Integer; FId_UniversityTypeOfFinansing: Integer; FUniversityTypeOfFinansingName: WideString; FUniversityKodeParent: WideString; FId_UniversityPanent: Integer; FUniversityFullNameParent: WideString; FKOATUUCodeU: WideString; FPostIndexU: WideString; FUniversityAdressU: WideString; FId_StreetTypeU: Integer; FHouceNumU: WideString; FId_KOATUUU: Integer; FKOATUUFullNameU: WideString; FStreetTypeFullNameU: WideString; FClosed: Integer; FAllowAccessFromParetn: Integer; FUniverityFacultetNumberKode: Integer; FUniversityFacultetFullName: WideString; FId_UniversityJuristicalType: Integer; FUniversityJuristicalTypeName: WideString; FId_UniversityBossOperatedType: Integer; FUniversityBossOperatedTypeName: WideString; FBossPost: WideString; FWarrantNumber: WideString; FWarrantDate: TXSDateTime; FId_UniversityCloseStatusTypes: Integer; FUniversityCloseStatusTypesName: WideString; FGive23Nk: Integer; FGiveRaiting: Integer; FId_UniversityType: Integer; FUniversityTypeName: WideString; FPtnzLevel: Integer; FIsPerepidgotovka: Integer; FParentOrganisationKode: WideString; FId_UniversityParentOrganisation: Integer; FUniversityFullNameParentOrganisation: WideString; FId_UniversityRoleType: Integer; FUniversityRoleTypeName: WideString; FIsResech: Integer; FUniversityFullNameEn: WideString; FUniversityShortNameEn: WideString; FEnableEducationalCycles: Integer; FIsMONGiveBudget: Integer; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_University: Integer read FId_University write FId_University; property UniversityKode: WideString read FUniversityKode write FUniversityKode; property UniversityDateBegin: TXSDateTime read FUniversityDateBegin write FUniversityDateBegin; property UniversityDateEnd: TXSDateTime read FUniversityDateEnd write FUniversityDateEnd; property EDRPO: WideString read FEDRPO write FEDRPO; property DateRegistration: TXSDateTime read FDateRegistration write FDateRegistration; property UniversityPhone: WideString read FUniversityPhone write FUniversityPhone; property UniversityEMail: WideString read FUniversityEMail write FUniversityEMail; property Website: WideString read FWebsite write FWebsite; property UniversityBossPhone: WideString read FUniversityBossPhone write FUniversityBossPhone; property UniversityBossEMail: WideString read FUniversityBossEMail write FUniversityBossEMail; property Id_UniversityName: Integer read FId_UniversityName write FId_UniversityName; property UniversityFullName: WideString read FUniversityFullName write FUniversityFullName; property UniversityShortName: WideString read FUniversityShortName write FUniversityShortName; property KOATUUCode: WideString read FKOATUUCode write FKOATUUCode; property PostIndex: WideString read FPostIndex write FPostIndex; property KOATUUFullName: WideString read FKOATUUFullName write FKOATUUFullName; property Id_StreetType: Integer read FId_StreetType write FId_StreetType; property StreetTypeFullName: WideString read FStreetTypeFullName write FStreetTypeFullName; property StreetTypeShortName: WideString read FStreetTypeShortName write FStreetTypeShortName; property UniversityAdress: WideString read FUniversityAdress write FUniversityAdress; property HouceNum: WideString read FHouceNum write FHouceNum; property UniversityBossLastName: WideString read FUniversityBossLastName write FUniversityBossLastName; property UniversityBossFirstName: WideString read FUniversityBossFirstName write FUniversityBossFirstName; property UniversityBossMidleName: WideString read FUniversityBossMidleName write FUniversityBossMidleName; property Id_EducationType: Integer read FId_EducationType write FId_EducationType; property Id_EducationClass: Integer read FId_EducationClass write FId_EducationClass; property EducationOrganizationFullTypeName: WideString read FEducationOrganizationFullTypeName write FEducationOrganizationFullTypeName; property EducationOrganizationShortTypeName: WideString read FEducationOrganizationShortTypeName write FEducationOrganizationShortTypeName; property EducationOrganizationClassName: WideString read FEducationOrganizationClassName write FEducationOrganizationClassName; property Id_Language: Integer read FId_Language write FId_Language; property Id_UniversityAcreditatin: Integer read FId_UniversityAcreditatin write FId_UniversityAcreditatin; property Id_UniversityAcreditatinType: Integer read FId_UniversityAcreditatinType write FId_UniversityAcreditatinType; property UniversitiyAcreditatinTypeCode: WideString read FUniversitiyAcreditatinTypeCode write FUniversitiyAcreditatinTypeCode; property IsUniversityVerifed: Integer read FIsUniversityVerifed write FIsUniversityVerifed; property ExistNeedVerification: Integer read FExistNeedVerification write FExistNeedVerification; property Id_UniversityGovernanceType: Integer read FId_UniversityGovernanceType write FId_UniversityGovernanceType; property UniversityGovernanceTypeName: WideString read FUniversityGovernanceTypeName write FUniversityGovernanceTypeName; property Id_UniversityRegistration: Integer read FId_UniversityRegistration write FId_UniversityRegistration; property Id_UniversityRegistrationType: Integer read FId_UniversityRegistrationType write FId_UniversityRegistrationType; property UniversityRegistrationTypeName: WideString read FUniversityRegistrationTypeName write FUniversityRegistrationTypeName; property Id_RegulationDocument: Integer read FId_RegulationDocument write FId_RegulationDocument; property UniversityRegistrationDateBegin: TXSDateTime read FUniversityRegistrationDateBegin write FUniversityRegistrationDateBegin; property UniversityRegistrationDateEnd: TXSDateTime read FUniversityRegistrationDateEnd write FUniversityRegistrationDateEnd; property UniversityRegistrationDateLastChange: TXSDateTime read FUniversityRegistrationDateLastChange write FUniversityRegistrationDateLastChange; property UniversityRegistrationIsActive: Integer read FUniversityRegistrationIsActive write FUniversityRegistrationIsActive; property UniversityRegistrationusersCount: Integer read FUniversityRegistrationusersCount write FUniversityRegistrationusersCount; property Id_UniversityTypeOfFinansing: Integer read FId_UniversityTypeOfFinansing write FId_UniversityTypeOfFinansing; property UniversityTypeOfFinansingName: WideString read FUniversityTypeOfFinansingName write FUniversityTypeOfFinansingName; property UniversityKodeParent: WideString read FUniversityKodeParent write FUniversityKodeParent; property Id_UniversityPanent: Integer read FId_UniversityPanent write FId_UniversityPanent; property UniversityFullNameParent: WideString read FUniversityFullNameParent write FUniversityFullNameParent; property KOATUUCodeU: WideString read FKOATUUCodeU write FKOATUUCodeU; property PostIndexU: WideString read FPostIndexU write FPostIndexU; property UniversityAdressU: WideString read FUniversityAdressU write FUniversityAdressU; property Id_StreetTypeU: Integer read FId_StreetTypeU write FId_StreetTypeU; property HouceNumU: WideString read FHouceNumU write FHouceNumU; property Id_KOATUUU: Integer read FId_KOATUUU write FId_KOATUUU; property KOATUUFullNameU: WideString read FKOATUUFullNameU write FKOATUUFullNameU; property StreetTypeFullNameU: WideString read FStreetTypeFullNameU write FStreetTypeFullNameU; property Closed: Integer read FClosed write FClosed; property AllowAccessFromParetn: Integer read FAllowAccessFromParetn write FAllowAccessFromParetn; property UniverityFacultetNumberKode: Integer read FUniverityFacultetNumberKode write FUniverityFacultetNumberKode; property UniversityFacultetFullName: WideString read FUniversityFacultetFullName write FUniversityFacultetFullName; property Id_UniversityJuristicalType: Integer read FId_UniversityJuristicalType write FId_UniversityJuristicalType; property UniversityJuristicalTypeName: WideString read FUniversityJuristicalTypeName write FUniversityJuristicalTypeName; property Id_UniversityBossOperatedType: Integer read FId_UniversityBossOperatedType write FId_UniversityBossOperatedType; property UniversityBossOperatedTypeName: WideString read FUniversityBossOperatedTypeName write FUniversityBossOperatedTypeName; property BossPost: WideString read FBossPost write FBossPost; property WarrantNumber: WideString read FWarrantNumber write FWarrantNumber; property WarrantDate: TXSDateTime read FWarrantDate write FWarrantDate; property Id_UniversityCloseStatusTypes: Integer read FId_UniversityCloseStatusTypes write FId_UniversityCloseStatusTypes; property UniversityCloseStatusTypesName: WideString read FUniversityCloseStatusTypesName write FUniversityCloseStatusTypesName; property Give23Nk: Integer read FGive23Nk write FGive23Nk; property GiveRaiting: Integer read FGiveRaiting write FGiveRaiting; property Id_UniversityType: Integer read FId_UniversityType write FId_UniversityType; property UniversityTypeName: WideString read FUniversityTypeName write FUniversityTypeName; property PtnzLevel: Integer read FPtnzLevel write FPtnzLevel; property IsPerepidgotovka: Integer read FIsPerepidgotovka write FIsPerepidgotovka; property ParentOrganisationKode: WideString read FParentOrganisationKode write FParentOrganisationKode; property Id_UniversityParentOrganisation: Integer read FId_UniversityParentOrganisation write FId_UniversityParentOrganisation; property UniversityFullNameParentOrganisation: WideString read FUniversityFullNameParentOrganisation write FUniversityFullNameParentOrganisation; property Id_UniversityRoleType: Integer read FId_UniversityRoleType write FId_UniversityRoleType; property UniversityRoleTypeName: WideString read FUniversityRoleTypeName write FUniversityRoleTypeName; property IsResech: Integer read FIsResech write FIsResech; property UniversityFullNameEn: WideString read FUniversityFullNameEn write FUniversityFullNameEn; property UniversityShortNameEn: WideString read FUniversityShortNameEn write FUniversityShortNameEn; property EnableEducationalCycles: Integer read FEnableEducationalCycles write FEnableEducationalCycles; property IsMONGiveBudget: Integer read FIsMONGiveBudget write FIsMONGiveBudget; end; ArrayOfDUniversities = array of dUniversities; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dLanguages = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_Language: Integer; FCode: WideString; FNameLanguage: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_Language: Integer read FId_Language write FId_Language; property Code: WideString read FCode write FCode; property NameLanguage: WideString read FNameLanguage write FNameLanguage; end; ArrayOfDLanguages = array of dLanguages; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dUniversityFacultets = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_UniversityFacultet: Integer; FUniversityKode: WideString; FUniversityFacultetKode: WideString; FUniversityFacultetDateBegin: TXSDateTime; FUniversityFacultetDateEnd: TXSDateTime; FId_UniversityFacultetName: Integer; FUniversityFacultetFullName: WideString; FUniversityFacultetShortName: WideString; FDescription: WideString; FId_Language: Integer; FIsAvailableForReceiptOfRequest: Boolean; FIsAvailableForBindStudentPersons: Boolean; FIsAvailableForBindStaffPersons: Boolean; FId_UniversityFacultetType: Integer; FUniversityFacultetTypeName: WideString; FId_UniversityFacultet_Parent: Integer; FHId_UniversityFacultet: WideString; FHId_UniversityFacultet_String: WideString; FFacultetPostIndex: WideString; FKOATUUCode: WideString; FKOATUUName: WideString; FKOATUUFullName: WideString; FFacultetStreetName: WideString; FFacultetHouseNumbers: WideString; FMovedToAnowerUniversity: Integer; FBlock: Integer; FBlockDescription: WideString; FIsPerepidgotovka: Integer; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_UniversityFacultet: Integer read FId_UniversityFacultet write FId_UniversityFacultet; property UniversityKode: WideString read FUniversityKode write FUniversityKode; property UniversityFacultetKode: WideString read FUniversityFacultetKode write FUniversityFacultetKode; property UniversityFacultetDateBegin: TXSDateTime read FUniversityFacultetDateBegin write FUniversityFacultetDateBegin; property UniversityFacultetDateEnd: TXSDateTime read FUniversityFacultetDateEnd write FUniversityFacultetDateEnd; property Id_UniversityFacultetName: Integer read FId_UniversityFacultetName write FId_UniversityFacultetName; property UniversityFacultetFullName: WideString read FUniversityFacultetFullName write FUniversityFacultetFullName; property UniversityFacultetShortName: WideString read FUniversityFacultetShortName write FUniversityFacultetShortName; property Description: WideString read FDescription write FDescription; property Id_Language: Integer read FId_Language write FId_Language; property IsAvailableForReceiptOfRequest: Boolean read FIsAvailableForReceiptOfRequest write FIsAvailableForReceiptOfRequest; property IsAvailableForBindStudentPersons: Boolean read FIsAvailableForBindStudentPersons write FIsAvailableForBindStudentPersons; property IsAvailableForBindStaffPersons: Boolean read FIsAvailableForBindStaffPersons write FIsAvailableForBindStaffPersons; property Id_UniversityFacultetType: Integer read FId_UniversityFacultetType write FId_UniversityFacultetType; property UniversityFacultetTypeName: WideString read FUniversityFacultetTypeName write FUniversityFacultetTypeName; property Id_UniversityFacultet_Parent: Integer read FId_UniversityFacultet_Parent write FId_UniversityFacultet_Parent; property HId_UniversityFacultet: WideString read FHId_UniversityFacultet write FHId_UniversityFacultet; property HId_UniversityFacultet_String: WideString read FHId_UniversityFacultet_String write FHId_UniversityFacultet_String; property FacultetPostIndex: WideString read FFacultetPostIndex write FFacultetPostIndex; property KOATUUCode: WideString read FKOATUUCode write FKOATUUCode; property KOATUUName: WideString read FKOATUUName write FKOATUUName; property KOATUUFullName: WideString read FKOATUUFullName write FKOATUUFullName; property FacultetStreetName: WideString read FFacultetStreetName write FFacultetStreetName; property FacultetHouseNumbers: WideString read FFacultetHouseNumbers write FFacultetHouseNumbers; property MovedToAnowerUniversity: Integer read FMovedToAnowerUniversity write FMovedToAnowerUniversity; property Block: Integer read FBlock write FBlock; property BlockDescription: WideString read FBlockDescription write FBlockDescription; property IsPerepidgotovka: Integer read FIsPerepidgotovka write FIsPerepidgotovka; end; ArrayOfDUniversityFacultets = array of dUniversityFacultets; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dUniversityFacultetSpecialities = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_UniversitySpecialities: Integer; FUniversitySpecialitiesKode: WideString; FUniversitySpecialitiesDateBegin: TXSDateTime; FUniversitySpecialitiesDateEnd: TXSDateTime; FUniversityKode: WideString; FUniversityFullName: WideString; FUniversityShortName: WideString; FUniversityFacultetKode: WideString; FUniversityFacultetFullName: WideString; FUniversityFacultetShortName: WideString; FSpecCode: WideString; FSpecClasifierCode: WideString; FId_Language: Integer; FSpecIndastryCode: WideString; FSpecIndastryName: WideString; FSpecDirectionsCode: WideString; FSpecDirectionName: WideString; FSpecSpecialityCode: WideString; FSpecSpecialityName: WideString; FSpecSpecializationCode: WideString; FSpecSpecializationName: WideString; FUniversitySpecialitiesLicenseCount: Integer; FUniversitySpecialitiesContractCount: Integer; FId_PersonRequestSeasons: Integer; FNameRequestSeasons: WideString; FId_PersonRequestSeasonDetails: Integer; FId_PersonEducationForm: Integer; FPersonEducationFormName: WideString; FDateBeginPersonRequestSeason: TXSDateTime; FDateEndPersonRequestSeason: TXSDateTime; FId_Qualification: Integer; FQualificationName: WideString; FSubjects: WideString; FSpecSpecialityClasifierCode: WideString; FQuotas: WideString; FId_Course: Integer; FDurationEducation: TXSDecimal; FCourseName: WideString; FUniversitySpecialitiesLicenseCountOld: Integer; FEducationDateBegin: TXSDateTime; FEducationDateEnd: TXSDateTime; FIsSecondEducation: Integer; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_UniversitySpecialities: Integer read FId_UniversitySpecialities write FId_UniversitySpecialities; property UniversitySpecialitiesKode: WideString read FUniversitySpecialitiesKode write FUniversitySpecialitiesKode; property UniversitySpecialitiesDateBegin: TXSDateTime read FUniversitySpecialitiesDateBegin write FUniversitySpecialitiesDateBegin; property UniversitySpecialitiesDateEnd: TXSDateTime read FUniversitySpecialitiesDateEnd write FUniversitySpecialitiesDateEnd; property UniversityKode: WideString read FUniversityKode write FUniversityKode; property UniversityFullName: WideString read FUniversityFullName write FUniversityFullName; property UniversityShortName: WideString read FUniversityShortName write FUniversityShortName; property UniversityFacultetKode: WideString read FUniversityFacultetKode write FUniversityFacultetKode; property UniversityFacultetFullName: WideString read FUniversityFacultetFullName write FUniversityFacultetFullName; property UniversityFacultetShortName: WideString read FUniversityFacultetShortName write FUniversityFacultetShortName; property SpecCode: WideString read FSpecCode write FSpecCode; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property Id_Language: Integer read FId_Language write FId_Language; property SpecIndastryCode: WideString read FSpecIndastryCode write FSpecIndastryCode; property SpecIndastryName: WideString read FSpecIndastryName write FSpecIndastryName; property SpecDirectionsCode: WideString read FSpecDirectionsCode write FSpecDirectionsCode; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property SpecSpecialityCode: WideString read FSpecSpecialityCode write FSpecSpecialityCode; property SpecSpecialityName: WideString read FSpecSpecialityName write FSpecSpecialityName; property SpecSpecializationCode: WideString read FSpecSpecializationCode write FSpecSpecializationCode; property SpecSpecializationName: WideString read FSpecSpecializationName write FSpecSpecializationName; property UniversitySpecialitiesLicenseCount: Integer read FUniversitySpecialitiesLicenseCount write FUniversitySpecialitiesLicenseCount; property UniversitySpecialitiesContractCount: Integer read FUniversitySpecialitiesContractCount write FUniversitySpecialitiesContractCount; property Id_PersonRequestSeasons: Integer read FId_PersonRequestSeasons write FId_PersonRequestSeasons; property NameRequestSeasons: WideString read FNameRequestSeasons write FNameRequestSeasons; property Id_PersonRequestSeasonDetails: Integer read FId_PersonRequestSeasonDetails write FId_PersonRequestSeasonDetails; property Id_PersonEducationForm: Integer read FId_PersonEducationForm write FId_PersonEducationForm; property PersonEducationFormName: WideString read FPersonEducationFormName write FPersonEducationFormName; property DateBeginPersonRequestSeason: TXSDateTime read FDateBeginPersonRequestSeason write FDateBeginPersonRequestSeason; property DateEndPersonRequestSeason: TXSDateTime read FDateEndPersonRequestSeason write FDateEndPersonRequestSeason; property Id_Qualification: Integer read FId_Qualification write FId_Qualification; property QualificationName: WideString read FQualificationName write FQualificationName; property Subjects: WideString read FSubjects write FSubjects; property SpecSpecialityClasifierCode: WideString read FSpecSpecialityClasifierCode write FSpecSpecialityClasifierCode; property Quotas: WideString read FQuotas write FQuotas; property Id_Course: Integer read FId_Course write FId_Course; property DurationEducation: TXSDecimal read FDurationEducation write FDurationEducation; property CourseName: WideString read FCourseName write FCourseName; property UniversitySpecialitiesLicenseCountOld: Integer read FUniversitySpecialitiesLicenseCountOld write FUniversitySpecialitiesLicenseCountOld; property EducationDateBegin: TXSDateTime read FEducationDateBegin write FEducationDateBegin; property EducationDateEnd: TXSDateTime read FEducationDateEnd write FEducationDateEnd; property IsSecondEducation: Integer read FIsSecondEducation write FIsSecondEducation; end; ArrayOfDUniversityFacultetSpecialities = array of dUniversityFacultetSpecialities; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dUniversityFacultetSpecialities2 = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_UniversitySpecialities: Integer; FUniversitySpecialitiesKode: WideString; FUniversitySpecialitiesDateBegin: TXSDateTime; FUniversitySpecialitiesDateEnd: TXSDateTime; FUniversityKode: WideString; FUniversityFullName: WideString; FUniversityShortName: WideString; FUniversityFacultetKode: WideString; FUniversityFacultetFullName: WideString; FUniversityFacultetShortName: WideString; FSpecCode: WideString; FSpecClasifierCode: WideString; FId_Language: Integer; FSpecIndastryCode: WideString; FSpecIndastryName: WideString; FSpecDirectionsCode: WideString; FSpecDirectionName: WideString; FSpecSpecialityCode: WideString; FSpecSpecialityName: WideString; FSpecSpecializationCode: WideString; FSpecSpecializationName: WideString; FUniversitySpecialitiesLicenseCount: Integer; FUniversitySpecialitiesContractCount: Integer; FId_PersonRequestSeasons: Integer; FNameRequestSeasons: WideString; FId_PersonRequestSeasonDetails: Integer; FId_PersonEducationForm: Integer; FPersonEducationFormName: WideString; FDateBeginPersonRequestSeason: TXSDateTime; FDateEndPersonRequestSeason: TXSDateTime; FId_Qualification: Integer; FQualificationName: WideString; FSubjects: WideString; FSpecSpecialityClasifierCode: WideString; FQuotas: WideString; FPublishInEz: Integer; Ffdel: Integer; FUniversitySpecialitiesOldBudjetCountCount: Integer; FId_Course: Integer; FDurationEducation: TXSDecimal; FCourseName: WideString; FUniversitySpecialitiesLicenseCountOld: Integer; FEducationDateBegin: TXSDateTime; FEducationDateEnd: TXSDateTime; FIsSecondEducation: Integer; FId_UniversityFacultet: Integer; FId_EntranceExamination: Integer; FUniversitySpecialitiesName: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_UniversitySpecialities: Integer read FId_UniversitySpecialities write FId_UniversitySpecialities; property UniversitySpecialitiesKode: WideString read FUniversitySpecialitiesKode write FUniversitySpecialitiesKode; property UniversitySpecialitiesDateBegin: TXSDateTime read FUniversitySpecialitiesDateBegin write FUniversitySpecialitiesDateBegin; property UniversitySpecialitiesDateEnd: TXSDateTime read FUniversitySpecialitiesDateEnd write FUniversitySpecialitiesDateEnd; property UniversityKode: WideString read FUniversityKode write FUniversityKode; property UniversityFullName: WideString read FUniversityFullName write FUniversityFullName; property UniversityShortName: WideString read FUniversityShortName write FUniversityShortName; property UniversityFacultetKode: WideString read FUniversityFacultetKode write FUniversityFacultetKode; property UniversityFacultetFullName: WideString read FUniversityFacultetFullName write FUniversityFacultetFullName; property UniversityFacultetShortName: WideString read FUniversityFacultetShortName write FUniversityFacultetShortName; property SpecCode: WideString read FSpecCode write FSpecCode; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property Id_Language: Integer read FId_Language write FId_Language; property SpecIndastryCode: WideString read FSpecIndastryCode write FSpecIndastryCode; property SpecIndastryName: WideString read FSpecIndastryName write FSpecIndastryName; property SpecDirectionsCode: WideString read FSpecDirectionsCode write FSpecDirectionsCode; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property SpecSpecialityCode: WideString read FSpecSpecialityCode write FSpecSpecialityCode; property SpecSpecialityName: WideString read FSpecSpecialityName write FSpecSpecialityName; property SpecSpecializationCode: WideString read FSpecSpecializationCode write FSpecSpecializationCode; property SpecSpecializationName: WideString read FSpecSpecializationName write FSpecSpecializationName; property UniversitySpecialitiesLicenseCount: Integer read FUniversitySpecialitiesLicenseCount write FUniversitySpecialitiesLicenseCount; property UniversitySpecialitiesContractCount: Integer read FUniversitySpecialitiesContractCount write FUniversitySpecialitiesContractCount; property Id_PersonRequestSeasons: Integer read FId_PersonRequestSeasons write FId_PersonRequestSeasons; property NameRequestSeasons: WideString read FNameRequestSeasons write FNameRequestSeasons; property Id_PersonRequestSeasonDetails: Integer read FId_PersonRequestSeasonDetails write FId_PersonRequestSeasonDetails; property Id_PersonEducationForm: Integer read FId_PersonEducationForm write FId_PersonEducationForm; property PersonEducationFormName: WideString read FPersonEducationFormName write FPersonEducationFormName; property DateBeginPersonRequestSeason: TXSDateTime read FDateBeginPersonRequestSeason write FDateBeginPersonRequestSeason; property DateEndPersonRequestSeason: TXSDateTime read FDateEndPersonRequestSeason write FDateEndPersonRequestSeason; property Id_Qualification: Integer read FId_Qualification write FId_Qualification; property QualificationName: WideString read FQualificationName write FQualificationName; property Subjects: WideString read FSubjects write FSubjects; property SpecSpecialityClasifierCode: WideString read FSpecSpecialityClasifierCode write FSpecSpecialityClasifierCode; property Quotas: WideString read FQuotas write FQuotas; property PublishInEz: Integer read FPublishInEz write FPublishInEz; property fdel: Integer read Ffdel write Ffdel; property UniversitySpecialitiesOldBudjetCountCount: Integer read FUniversitySpecialitiesOldBudjetCountCount write FUniversitySpecialitiesOldBudjetCountCount; property Id_Course: Integer read FId_Course write FId_Course; property DurationEducation: TXSDecimal read FDurationEducation write FDurationEducation; property CourseName: WideString read FCourseName write FCourseName; property UniversitySpecialitiesLicenseCountOld: Integer read FUniversitySpecialitiesLicenseCountOld write FUniversitySpecialitiesLicenseCountOld; property EducationDateBegin: TXSDateTime read FEducationDateBegin write FEducationDateBegin; property EducationDateEnd: TXSDateTime read FEducationDateEnd write FEducationDateEnd; property IsSecondEducation: Integer read FIsSecondEducation write FIsSecondEducation; property Id_UniversityFacultet: Integer read FId_UniversityFacultet write FId_UniversityFacultet; property Id_EntranceExamination: Integer read FId_EntranceExamination write FId_EntranceExamination; property UniversitySpecialitiesName: WideString read FUniversitySpecialitiesName write FUniversitySpecialitiesName; end; ArrayOfDUniversityFacultetSpecialities2 = array of dUniversityFacultetSpecialities2; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dCourses = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_Course: Integer; FCourseName: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_Course: Integer read FId_Course write FId_Course; property CourseName: WideString read FCourseName write FCourseName; end; ArrayOfDCourses = array of dCourses; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dSpec = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_Spec: Integer; FSpecCode: WideString; FSpecClasifierCode: WideString; FSpecDateBegin: TXSDateTime; FSpecDateEnd: TXSDateTime; FId_SpecRedactions: Integer; FSpecRedactionCode: WideString; FSpecRedactionName: WideString; FId_SpecIndastry: Integer; FSpecIndastryCode: WideString; FSpecIndastryDateBegin: TXSDateTime; FSpecIndastryDateEnd: TXSDateTime; FId_SpecIndastryName: Integer; FSpecIndastryName: WideString; FId_SpecDirections: Integer; FSpecDirectionsCode: WideString; FSpecDirectionsDateBegin: TXSDateTime; FSpecDirectionsDateEnd: TXSDateTime; FId_SpecDirectionName: Integer; FSpecDirectionName: WideString; FId_SpecSpeciality: Integer; FSpecSpecialityCode: WideString; FSpecSpecialityDateBegin: TXSDateTime; FSpecSpecialityDateEnd: TXSDateTime; FId_SpecSpecialityName: Integer; FSpecSpecialityName: WideString; FId_Language: Integer; FId_SpecSpecialization: Integer; FSpecSpecializationCode: WideString; FId_SpecSpecializationName: Integer; FSpecSpecializationName: WideString; FSpecCodeDateLastChange: TXSDateTime; FSpecIndastryClasifierCode: WideString; FSpecSpecialityClasifierCode: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_Spec: Integer read FId_Spec write FId_Spec; property SpecCode: WideString read FSpecCode write FSpecCode; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property SpecDateBegin: TXSDateTime read FSpecDateBegin write FSpecDateBegin; property SpecDateEnd: TXSDateTime read FSpecDateEnd write FSpecDateEnd; property Id_SpecRedactions: Integer read FId_SpecRedactions write FId_SpecRedactions; property SpecRedactionCode: WideString read FSpecRedactionCode write FSpecRedactionCode; property SpecRedactionName: WideString read FSpecRedactionName write FSpecRedactionName; property Id_SpecIndastry: Integer read FId_SpecIndastry write FId_SpecIndastry; property SpecIndastryCode: WideString read FSpecIndastryCode write FSpecIndastryCode; property SpecIndastryDateBegin: TXSDateTime read FSpecIndastryDateBegin write FSpecIndastryDateBegin; property SpecIndastryDateEnd: TXSDateTime read FSpecIndastryDateEnd write FSpecIndastryDateEnd; property Id_SpecIndastryName: Integer read FId_SpecIndastryName write FId_SpecIndastryName; property SpecIndastryName: WideString read FSpecIndastryName write FSpecIndastryName; property Id_SpecDirections: Integer read FId_SpecDirections write FId_SpecDirections; property SpecDirectionsCode: WideString read FSpecDirectionsCode write FSpecDirectionsCode; property SpecDirectionsDateBegin: TXSDateTime read FSpecDirectionsDateBegin write FSpecDirectionsDateBegin; property SpecDirectionsDateEnd: TXSDateTime read FSpecDirectionsDateEnd write FSpecDirectionsDateEnd; property Id_SpecDirectionName: Integer read FId_SpecDirectionName write FId_SpecDirectionName; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property Id_SpecSpeciality: Integer read FId_SpecSpeciality write FId_SpecSpeciality; property SpecSpecialityCode: WideString read FSpecSpecialityCode write FSpecSpecialityCode; property SpecSpecialityDateBegin: TXSDateTime read FSpecSpecialityDateBegin write FSpecSpecialityDateBegin; property SpecSpecialityDateEnd: TXSDateTime read FSpecSpecialityDateEnd write FSpecSpecialityDateEnd; property Id_SpecSpecialityName: Integer read FId_SpecSpecialityName write FId_SpecSpecialityName; property SpecSpecialityName: WideString read FSpecSpecialityName write FSpecSpecialityName; property Id_Language: Integer read FId_Language write FId_Language; property Id_SpecSpecialization: Integer read FId_SpecSpecialization write FId_SpecSpecialization; property SpecSpecializationCode: WideString read FSpecSpecializationCode write FSpecSpecializationCode; property Id_SpecSpecializationName: Integer read FId_SpecSpecializationName write FId_SpecSpecializationName; property SpecSpecializationName: WideString read FSpecSpecializationName write FSpecSpecializationName; property SpecCodeDateLastChange: TXSDateTime read FSpecCodeDateLastChange write FSpecCodeDateLastChange; property SpecIndastryClasifierCode: WideString read FSpecIndastryClasifierCode write FSpecIndastryClasifierCode; property SpecSpecialityClasifierCode: WideString read FSpecSpecialityClasifierCode write FSpecSpecialityClasifierCode; end; ArrayOfDSpec = array of dSpec; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dSpecDirections = class(TRemotable) private FExtensionData: ExtensionDataObject; FSpecDirectionsCode: WideString; FSpecDirectionName: WideString; FSpecClasifierCode: WideString; Folddta: Integer; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property SpecDirectionsCode: WideString read FSpecDirectionsCode write FSpecDirectionsCode; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property olddta: Integer read Folddta write Folddta; end; ArrayOfDSpecDirections = array of dSpecDirections; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dSpecDirections2 = class(TRemotable) private FExtensionData: ExtensionDataObject; FSpecDirectionsCode: WideString; FSpecDirectionName: WideString; FSpecClasifierCode: WideString; Folddta: Integer; FSpecDirectionNameEn: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property SpecDirectionsCode: WideString read FSpecDirectionsCode write FSpecDirectionsCode; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property olddta: Integer read Folddta write Folddta; property SpecDirectionNameEn: WideString read FSpecDirectionNameEn write FSpecDirectionNameEn; end; ArrayOfDSpecDirections2 = array of dSpecDirections2; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dKOATUU = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_KOATUU: Integer; FKOATUUCode: WideString; FType_: WideString; FId_KOATUUName: Integer; FKOATUUName: WideString; FKOATUUFullName: WideString; FKOATUUDateBegin: TXSDateTime; FKOATUUDateEnd: TXSDateTime; FId_Language: Integer; FKOATUUCodeL1: WideString; FKOATUUCodeL2: WideString; FKOATUUCodeL3: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_KOATUU: Integer read FId_KOATUU write FId_KOATUU; property KOATUUCode: WideString read FKOATUUCode write FKOATUUCode; property Type_: WideString read FType_ write FType_; property Id_KOATUUName: Integer read FId_KOATUUName write FId_KOATUUName; property KOATUUName: WideString read FKOATUUName write FKOATUUName; property KOATUUFullName: WideString read FKOATUUFullName write FKOATUUFullName; property KOATUUDateBegin: TXSDateTime read FKOATUUDateBegin write FKOATUUDateBegin; property KOATUUDateEnd: TXSDateTime read FKOATUUDateEnd write FKOATUUDateEnd; property Id_Language: Integer read FId_Language write FId_Language; property KOATUUCodeL1: WideString read FKOATUUCodeL1 write FKOATUUCodeL1; property KOATUUCodeL2: WideString read FKOATUUCodeL2 write FKOATUUCodeL2; property KOATUUCodeL3: WideString read FKOATUUCodeL3 write FKOATUUCodeL3; end; ArrayOfDKOATUU = array of dKOATUU; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dStreetTypes = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_StreetType: Integer; FId_StreetTypeName: Integer; FStreetTypeFullName: WideString; FStreetTypeShortName: WideString; FId_Language: Integer; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_StreetType: Integer read FId_StreetType write FId_StreetType; property Id_StreetTypeName: Integer read FId_StreetTypeName write FId_StreetTypeName; property StreetTypeFullName: WideString read FStreetTypeFullName write FStreetTypeFullName; property StreetTypeShortName: WideString read FStreetTypeShortName write FStreetTypeShortName; property Id_Language: Integer read FId_Language write FId_Language; end; ArrayOfDStreetTypes = array of dStreetTypes; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dUniversityFacultetsRequests = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_PersonRequest: Integer; FId_PersonRequestSeasons: Integer; FPersonCodeU: WideString; FFIO: WideString; FUniversitySpecialitiesKode: WideString; FNameRequestSeason: WideString; FRequestPerPerson: Integer; FId_UniversitySpecialities: Integer; FUniversitySpecialitiesDateBegin: TXSDateTime; FUniversitySpecialitiesDateEnd: TXSDateTime; FUniversityKode: WideString; FUniversityFullName: WideString; FUniversityShortName: WideString; FUniversityFacultetKode: WideString; FUniversityFacultetFullName: WideString; FUniversityFacultetShortName: WideString; FSpecCode: WideString; FSpecClasifierCode: WideString; FSpecIndastryName: WideString; FSpecDirectionName: WideString; FSpecSpecialityName: WideString; FId_Language: Integer; FSpecScecializationCode: WideString; FSpecScecializationName: WideString; FOriginalDocumentsAdd: Integer; FId_PersonRequestStatus: Integer; FId_PersonRequestStatusType: Integer; FPersonRequestStatusCode: WideString; FId_PersonRequestStatusTypeName: Integer; FPersonRequestStatusTypeName: WideString; FDescryption: WideString; FDateLastChange: TXSDateTime; FIsNeedHostel: Integer; FCodeOfBusiness: WideString; FId_PersonEnteranceTypes: Integer; FPersonEnteranceTypeName: WideString; FId_PersonRequestExaminationCause: Integer; FPersonRequestExaminationCauseName: WideString; FIsContract: Integer; FIsBudget: Integer; FId_PersonEducationForm: Integer; FPersonEducationFormName: WideString; FKonkursValue: TXSDecimal; FKonkursValueSource: WideString; FPriorityRequest: Integer; FKonkursValueCorrectValue: TXSDecimal; FKonkursValueCorrectValueDescription: WideString; FDateCreate: TXSDateTime; FId_PersonRequestSeasonDetails: Integer; FId_Qualification: Integer; FQualificationName: WideString; FId_PersonDocumentType: Integer; FPersonDocumentTypeName: WideString; FId_PersonDocument: Integer; FEntrantDocumentSeries: WideString; FEntrantDocumentNumbers: WideString; FEntrantDocumentDateGet: TXSDateTime; FEntrantDocumentIssued: WideString; FEntrantDocumentValue: TXSDecimal; FIsCheckForPaperCopy: Integer; FIsNotCheckAttestat: Integer; FIsForeinghEntrantDocumet: Integer; FRequestEnteranseCodes: WideString; FId_UniversityEntrantWave: Integer; FRequestStatusIsBudejt: Integer; FRequestStatusIsContract: Integer; FUniversityEntrantWaveName: WideString; FIsHigherEducation: Integer; FSkipDocumentValue: Integer; FId_EntrantDocumentAwardType: Integer; FEntrantDocumentAwardTypeName: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_PersonRequest: Integer read FId_PersonRequest write FId_PersonRequest; property Id_PersonRequestSeasons: Integer read FId_PersonRequestSeasons write FId_PersonRequestSeasons; property PersonCodeU: WideString read FPersonCodeU write FPersonCodeU; property FIO: WideString read FFIO write FFIO; property UniversitySpecialitiesKode: WideString read FUniversitySpecialitiesKode write FUniversitySpecialitiesKode; property NameRequestSeason: WideString read FNameRequestSeason write FNameRequestSeason; property RequestPerPerson: Integer read FRequestPerPerson write FRequestPerPerson; property Id_UniversitySpecialities: Integer read FId_UniversitySpecialities write FId_UniversitySpecialities; property UniversitySpecialitiesDateBegin: TXSDateTime read FUniversitySpecialitiesDateBegin write FUniversitySpecialitiesDateBegin; property UniversitySpecialitiesDateEnd: TXSDateTime read FUniversitySpecialitiesDateEnd write FUniversitySpecialitiesDateEnd; property UniversityKode: WideString read FUniversityKode write FUniversityKode; property UniversityFullName: WideString read FUniversityFullName write FUniversityFullName; property UniversityShortName: WideString read FUniversityShortName write FUniversityShortName; property UniversityFacultetKode: WideString read FUniversityFacultetKode write FUniversityFacultetKode; property UniversityFacultetFullName: WideString read FUniversityFacultetFullName write FUniversityFacultetFullName; property UniversityFacultetShortName: WideString read FUniversityFacultetShortName write FUniversityFacultetShortName; property SpecCode: WideString read FSpecCode write FSpecCode; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property SpecIndastryName: WideString read FSpecIndastryName write FSpecIndastryName; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property SpecSpecialityName: WideString read FSpecSpecialityName write FSpecSpecialityName; property Id_Language: Integer read FId_Language write FId_Language; property SpecScecializationCode: WideString read FSpecScecializationCode write FSpecScecializationCode; property SpecScecializationName: WideString read FSpecScecializationName write FSpecScecializationName; property OriginalDocumentsAdd: Integer read FOriginalDocumentsAdd write FOriginalDocumentsAdd; property Id_PersonRequestStatus: Integer read FId_PersonRequestStatus write FId_PersonRequestStatus; property Id_PersonRequestStatusType: Integer read FId_PersonRequestStatusType write FId_PersonRequestStatusType; property PersonRequestStatusCode: WideString read FPersonRequestStatusCode write FPersonRequestStatusCode; property Id_PersonRequestStatusTypeName: Integer read FId_PersonRequestStatusTypeName write FId_PersonRequestStatusTypeName; property PersonRequestStatusTypeName: WideString read FPersonRequestStatusTypeName write FPersonRequestStatusTypeName; property Descryption: WideString read FDescryption write FDescryption; property DateLastChange: TXSDateTime read FDateLastChange write FDateLastChange; property IsNeedHostel: Integer read FIsNeedHostel write FIsNeedHostel; property CodeOfBusiness: WideString read FCodeOfBusiness write FCodeOfBusiness; property Id_PersonEnteranceTypes: Integer read FId_PersonEnteranceTypes write FId_PersonEnteranceTypes; property PersonEnteranceTypeName: WideString read FPersonEnteranceTypeName write FPersonEnteranceTypeName; property Id_PersonRequestExaminationCause: Integer read FId_PersonRequestExaminationCause write FId_PersonRequestExaminationCause; property PersonRequestExaminationCauseName: WideString read FPersonRequestExaminationCauseName write FPersonRequestExaminationCauseName; property IsContract: Integer read FIsContract write FIsContract; property IsBudget: Integer read FIsBudget write FIsBudget; property Id_PersonEducationForm: Integer read FId_PersonEducationForm write FId_PersonEducationForm; property PersonEducationFormName: WideString read FPersonEducationFormName write FPersonEducationFormName; property KonkursValue: TXSDecimal read FKonkursValue write FKonkursValue; property KonkursValueSource: WideString read FKonkursValueSource write FKonkursValueSource; property PriorityRequest: Integer read FPriorityRequest write FPriorityRequest; property KonkursValueCorrectValue: TXSDecimal read FKonkursValueCorrectValue write FKonkursValueCorrectValue; property KonkursValueCorrectValueDescription: WideString read FKonkursValueCorrectValueDescription write FKonkursValueCorrectValueDescription; property DateCreate: TXSDateTime read FDateCreate write FDateCreate; property Id_PersonRequestSeasonDetails: Integer read FId_PersonRequestSeasonDetails write FId_PersonRequestSeasonDetails; property Id_Qualification: Integer read FId_Qualification write FId_Qualification; property QualificationName: WideString read FQualificationName write FQualificationName; property Id_PersonDocumentType: Integer read FId_PersonDocumentType write FId_PersonDocumentType; property PersonDocumentTypeName: WideString read FPersonDocumentTypeName write FPersonDocumentTypeName; property Id_PersonDocument: Integer read FId_PersonDocument write FId_PersonDocument; property EntrantDocumentSeries: WideString read FEntrantDocumentSeries write FEntrantDocumentSeries; property EntrantDocumentNumbers: WideString read FEntrantDocumentNumbers write FEntrantDocumentNumbers; property EntrantDocumentDateGet: TXSDateTime read FEntrantDocumentDateGet write FEntrantDocumentDateGet; property EntrantDocumentIssued: WideString read FEntrantDocumentIssued write FEntrantDocumentIssued; property EntrantDocumentValue: TXSDecimal read FEntrantDocumentValue write FEntrantDocumentValue; property IsCheckForPaperCopy: Integer read FIsCheckForPaperCopy write FIsCheckForPaperCopy; property IsNotCheckAttestat: Integer read FIsNotCheckAttestat write FIsNotCheckAttestat; property IsForeinghEntrantDocumet: Integer read FIsForeinghEntrantDocumet write FIsForeinghEntrantDocumet; property RequestEnteranseCodes: WideString read FRequestEnteranseCodes write FRequestEnteranseCodes; property Id_UniversityEntrantWave: Integer read FId_UniversityEntrantWave write FId_UniversityEntrantWave; property RequestStatusIsBudejt: Integer read FRequestStatusIsBudejt write FRequestStatusIsBudejt; property RequestStatusIsContract: Integer read FRequestStatusIsContract write FRequestStatusIsContract; property UniversityEntrantWaveName: WideString read FUniversityEntrantWaveName write FUniversityEntrantWaveName; property IsHigherEducation: Integer read FIsHigherEducation write FIsHigherEducation; property SkipDocumentValue: Integer read FSkipDocumentValue write FSkipDocumentValue; property Id_EntrantDocumentAwardType: Integer read FId_EntrantDocumentAwardType write FId_EntrantDocumentAwardType; property EntrantDocumentAwardTypeName: WideString read FEntrantDocumentAwardTypeName write FEntrantDocumentAwardTypeName; end; ArrayOfDUniversityFacultetsRequests = array of dUniversityFacultetsRequests; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // ************************************************************************ // dUniversityFacultetsRequests2 = class(TRemotable) private FExtensionData: ExtensionDataObject; FId_PersonRequest: Integer; FId_PersonRequestSeasons: Integer; FPersonCodeU: WideString; FFIO: WideString; FUniversitySpecialitiesKode: WideString; FNameRequestSeason: WideString; FRequestPerPerson: Integer; FId_UniversitySpecialities: Integer; FUniversitySpecialitiesDateBegin: TXSDateTime; FUniversitySpecialitiesDateEnd: TXSDateTime; FUniversityKode: WideString; FUniversityFullName: WideString; FUniversityShortName: WideString; FUniversityFacultetKode: WideString; FUniversityFacultetFullName: WideString; FUniversityFacultetShortName: WideString; FSpecCode: WideString; FSpecClasifierCode: WideString; FSpecIndastryName: WideString; FSpecDirectionName: WideString; FSpecSpecialityName: WideString; FId_Language: Integer; FSpecScecializationCode: WideString; FSpecScecializationName: WideString; FOriginalDocumentsAdd: Integer; FId_PersonRequestStatus: Integer; FId_PersonRequestStatusType: Integer; FPersonRequestStatusCode: WideString; FId_PersonRequestStatusTypeName: Integer; FPersonRequestStatusTypeName: WideString; FDescryption: WideString; FDateLastChange: TXSDateTime; FIsNeedHostel: Integer; FCodeOfBusiness: WideString; FId_PersonEnteranceTypes: Integer; FPersonEnteranceTypeName: WideString; FId_PersonRequestExaminationCause: Integer; FPersonRequestExaminationCauseName: WideString; FIsContract: Integer; FIsBudget: Integer; FId_PersonEducationForm: Integer; FPersonEducationFormName: WideString; FKonkursValue: TXSDecimal; FKonkursValueSource: WideString; FPriorityRequest: Integer; FKonkursValueCorrectValue: TXSDecimal; FKonkursValueCorrectValueDescription: WideString; FDateCreate: TXSDateTime; FId_PersonRequestSeasonDetails: Integer; FId_Qualification: Integer; FQualificationName: WideString; FId_PersonDocumentType: Integer; FPersonDocumentTypeName: WideString; FId_PersonDocument: Integer; FEntrantDocumentSeries: WideString; FEntrantDocumentNumbers: WideString; FEntrantDocumentDateGet: TXSDateTime; FEntrantDocumentIssued: WideString; FEntrantDocumentValue: TXSDecimal; FIsCheckForPaperCopy: Integer; FIsNotCheckAttestat: Integer; FIsForeinghEntrantDocumet: Integer; FRequestEnteranseCodes: WideString; FId_UniversityEntrantWave: Integer; FRequestStatusIsBudejt: Integer; FRequestStatusIsContract: Integer; FUniversityEntrantWaveName: WideString; FIsHigherEducation: Integer; FSkipDocumentValue: Integer; FId_EntrantDocumentAwardType: Integer; FEntrantDocumentAwardTypeName: WideString; FSpecSpecialityClasifierCode: WideString; FExistBenefitsPershocherg: Integer; FExistBenefitsPozacherg: Integer; FZNOSubjects: WideString; FId_LanguageEx: Integer; FLanguageExName: WideString; FIsEz: Integer; FIsForeignWay: Integer; FId_ForeignType: Integer; FForeignTypeName: WideString; FId_Course: Integer; FExistQuotasCiloviy: Integer; FId_PersonSex: Integer; FResident: Integer; FKoatuType: WideString; FCountryName: WideString; FBirthday: TXSDateTime; FContactPhone: WideString; FContactMobile: WideString; FEntranceCodes: WideString; public destructor Destroy; override; published property ExtensionData: ExtensionDataObject read FExtensionData write FExtensionData; property Id_PersonRequest: Integer read FId_PersonRequest write FId_PersonRequest; property Id_PersonRequestSeasons: Integer read FId_PersonRequestSeasons write FId_PersonRequestSeasons; property PersonCodeU: WideString read FPersonCodeU write FPersonCodeU; property FIO: WideString read FFIO write FFIO; property UniversitySpecialitiesKode: WideString read FUniversitySpecialitiesKode write FUniversitySpecialitiesKode; property NameRequestSeason: WideString read FNameRequestSeason write FNameRequestSeason; property RequestPerPerson: Integer read FRequestPerPerson write FRequestPerPerson; property Id_UniversitySpecialities: Integer read FId_UniversitySpecialities write FId_UniversitySpecialities; property UniversitySpecialitiesDateBegin: TXSDateTime read FUniversitySpecialitiesDateBegin write FUniversitySpecialitiesDateBegin; property UniversitySpecialitiesDateEnd: TXSDateTime read FUniversitySpecialitiesDateEnd write FUniversitySpecialitiesDateEnd; property UniversityKode: WideString read FUniversityKode write FUniversityKode; property UniversityFullName: WideString read FUniversityFullName write FUniversityFullName; property UniversityShortName: WideString read FUniversityShortName write FUniversityShortName; property UniversityFacultetKode: WideString read FUniversityFacultetKode write FUniversityFacultetKode; property UniversityFacultetFullName: WideString read FUniversityFacultetFullName write FUniversityFacultetFullName; property UniversityFacultetShortName: WideString read FUniversityFacultetShortName write FUniversityFacultetShortName; property SpecCode: WideString read FSpecCode write FSpecCode; property SpecClasifierCode: WideString read FSpecClasifierCode write FSpecClasifierCode; property SpecIndastryName: WideString read FSpecIndastryName write FSpecIndastryName; property SpecDirectionName: WideString read FSpecDirectionName write FSpecDirectionName; property SpecSpecialityName: WideString read FSpecSpecialityName write FSpecSpecialityName; property Id_Language: Integer read FId_Language write FId_Language; property SpecScecializationCode: WideString read FSpecScecializationCode write FSpecScecializationCode; property SpecScecializationName: WideString read FSpecScecializationName write FSpecScecializationName; property OriginalDocumentsAdd: Integer read FOriginalDocumentsAdd write FOriginalDocumentsAdd; property Id_PersonRequestStatus: Integer read FId_PersonRequestStatus write FId_PersonRequestStatus; property Id_PersonRequestStatusType: Integer read FId_PersonRequestStatusType write FId_PersonRequestStatusType; property PersonRequestStatusCode: WideString read FPersonRequestStatusCode write FPersonRequestStatusCode; property Id_PersonRequestStatusTypeName: Integer read FId_PersonRequestStatusTypeName write FId_PersonRequestStatusTypeName; property PersonRequestStatusTypeName: WideString read FPersonRequestStatusTypeName write FPersonRequestStatusTypeName; property Descryption: WideString read FDescryption write FDescryption; property DateLastChange: TXSDateTime read FDateLastChange write FDateLastChange; property IsNeedHostel: Integer read FIsNeedHostel write FIsNeedHostel; property CodeOfBusiness: WideString read FCodeOfBusiness write FCodeOfBusiness; property Id_PersonEnteranceTypes: Integer read FId_PersonEnteranceTypes write FId_PersonEnteranceTypes; property PersonEnteranceTypeName: WideString read FPersonEnteranceTypeName write FPersonEnteranceTypeName; property Id_PersonRequestExaminationCause: Integer read FId_PersonRequestExaminationCause write FId_PersonRequestExaminationCause; property PersonRequestExaminationCauseName: WideString read FPersonRequestExaminationCauseName write FPersonRequestExaminationCauseName; property IsContract: Integer read FIsContract write FIsContract; property IsBudget: Integer read FIsBudget write FIsBudget; property Id_PersonEducationForm: Integer read FId_PersonEducationForm write FId_PersonEducationForm; property PersonEducationFormName: WideString read FPersonEducationFormName write FPersonEducationFormName; property KonkursValue: TXSDecimal read FKonkursValue write FKonkursValue; property KonkursValueSource: WideString read FKonkursValueSource write FKonkursValueSource; property PriorityRequest: Integer read FPriorityRequest write FPriorityRequest; property KonkursValueCorrectValue: TXSDecimal read FKonkursValueCorrectValue write FKonkursValueCorrectValue; property KonkursValueCorrectValueDescription: WideString read FKonkursValueCorrectValueDescription write FKonkursValueCorrectValueDescription; property DateCreate: TXSDateTime read FDateCreate write FDateCreate; property Id_PersonRequestSeasonDetails: Integer read FId_PersonRequestSeasonDetails write FId_PersonRequestSeasonDetails; property Id_Qualification: Integer read FId_Qualification write FId_Qualification; property QualificationName: WideString read FQualificationName write FQualificationName; property Id_PersonDocumentType: Integer read FId_PersonDocumentType write FId_PersonDocumentType; property PersonDocumentTypeName: WideString read FPersonDocumentTypeName write FPersonDocumentTypeName; property Id_PersonDocument: Integer read FId_PersonDocument write FId_PersonDocument; property EntrantDocumentSeries: WideString read FEntrantDocumentSeries write FEntrantDocumentSeries; property EntrantDocumentNumbers: WideString read FEntrantDocumentNumbers write FEntrantDocumentNumbers; property EntrantDocumentDateGet: TXSDateTime read FEntrantDocumentDateGet write FEntrantDocumentDateGet; property EntrantDocumentIssued: WideString read FEntrantDocumentIssued write FEntrantDocumentIssued; property EntrantDocumentValue: TXSDecimal read FEntrantDocumentValue write FEntrantDocumentValue; property IsCheckForPaperCopy: Integer read FIsCheckForPaperCopy write FIsCheckForPaperCopy; property IsNotCheckAttestat: Integer read FIsNotCheckAttestat write FIsNotCheckAttestat; property IsForeinghEntrantDocumet: Integer read FIsForeinghEntrantDocumet write FIsForeinghEntrantDocumet; property RequestEnteranseCodes: WideString read FRequestEnteranseCodes write FRequestEnteranseCodes; property Id_UniversityEntrantWave: Integer read FId_UniversityEntrantWave write FId_UniversityEntrantWave; property RequestStatusIsBudejt: Integer read FRequestStatusIsBudejt write FRequestStatusIsBudejt; property RequestStatusIsContract: Integer read FRequestStatusIsContract write FRequestStatusIsContract; property UniversityEntrantWaveName: WideString read FUniversityEntrantWaveName write FUniversityEntrantWaveName; property IsHigherEducation: Integer read FIsHigherEducation write FIsHigherEducation; property SkipDocumentValue: Integer read FSkipDocumentValue write FSkipDocumentValue; property Id_EntrantDocumentAwardType: Integer read FId_EntrantDocumentAwardType write FId_EntrantDocumentAwardType; property EntrantDocumentAwardTypeName: WideString read FEntrantDocumentAwardTypeName write FEntrantDocumentAwardTypeName; property SpecSpecialityClasifierCode: WideString read FSpecSpecialityClasifierCode write FSpecSpecialityClasifierCode; property ExistBenefitsPershocherg: Integer read FExistBenefitsPershocherg write FExistBenefitsPershocherg; property ExistBenefitsPozacherg: Integer read FExistBenefitsPozacherg write FExistBenefitsPozacherg; property ZNOSubjects: WideString read FZNOSubjects write FZNOSubjects; property Id_LanguageEx: Integer read FId_LanguageEx write FId_LanguageEx; property LanguageExName: WideString read FLanguageExName write FLanguageExName; property IsEz: Integer read FIsEz write FIsEz; property IsForeignWay: Integer read FIsForeignWay write FIsForeignWay; property Id_ForeignType: Integer read FId_ForeignType write FId_ForeignType; property ForeignTypeName: WideString read FForeignTypeName write FForeignTypeName; property Id_Course: Integer read FId_Course write FId_Course; property ExistQuotasCiloviy: Integer read FExistQuotasCiloviy write FExistQuotasCiloviy; property Id_PersonSex: Integer read FId_PersonSex write FId_PersonSex; property Resident: Integer read FResident write FResident; property KoatuType: WideString read FKoatuType write FKoatuType; property CountryName: WideString read FCountryName write FCountryName; property Birthday: TXSDateTime read FBirthday write FBirthday; property ContactPhone: WideString read FContactPhone write FContactPhone; property ContactMobile: WideString read FContactMobile write FContactMobile; property EntranceCodes: WideString read FEntranceCodes write FEntranceCodes; end; ArrayOfDUniversityFacultetsRequests2 = array of dUniversityFacultetsRequests2; { "http://edboservice.ua/" } // ************************************************************************ // // Namespace : http://edboservice.ua/ // soapAction: http://edboservice.ua/%operationName% // transport : http://schemas.xmlsoap.org/soap/http // binding : EDBOGuidesSoap // service : EDBOGuides // port : EDBOGuidesSoap // URL : http://ias.donnu.edu.ua/EDBOdata/EDBOGuidesToFMASService.asmx // ************************************************************************ // EDBOGuidesSoap = interface(IInvokable) ['{3388FE85-720C-04EE-2F43-F032C77ACE1C}'] function AcademicYearsGet(const SessionGUID: WideString; const Id_Language: Integer): ArrayOfDAcademicYears; stdcall; function Login(const User: WideString; const Password: WideString; const ClearPreviewSession: Integer; const ApplicationKey: WideString): WideString; stdcall; function GetLastError(const GUIDSession: WideString): ArrayOfDLastError; stdcall; function CheckUser(const SessionGUID: WideString): Integer; stdcall; function UniversitiesGet(const SessionGUID: WideString; const UniversityKode: WideString; const Id_Language: Integer; const ActualDate: WideString; const UniversityName: WideString): ArrayOfDUniversities; stdcall; function UniversitiesGet2(const SessionGUID: WideString; const UniversityKode: WideString; const Id_Language: Integer; const ActualDate: WideString; const UniversityName: WideString; const KOATUUL1: WideString; const KOATUUL2: WideString; const SpecDirectionsCode: WideString; const Id_UniversityType: Integer): ArrayOfDUniversities; stdcall; function LanguagesGet(const SessionGUID: WideString): ArrayOfDLanguages; stdcall; function UniversityFacultetsGet(const SessionGUID: WideString; const UniversityKode: WideString; const UniversityFacultetKode: WideString; const Id_Language: Integer; const ActualDate: WideString; const FacultetGetMode: Integer; const Id_UniversityFacultetTypes: WideString; const IsAvailableForReceiptOfRequest: Integer; const IsAvailableForBindStudentPersons: Integer; const Id_UniversityFacultet: Integer; const IsAvailableForBindStaffPersons: Integer): ArrayOfDUniversityFacultets; stdcall; function UniversityFacultetSpecialitiesGet(const SessionGUID: WideString; const UniversityKode: WideString; const UniversityFacultetKode: WideString; const SpecCode: WideString; const Id_Language: Integer; const ActualDate: WideString; const Id_PersonRequestSeasons: Integer; const Id_PersonEducationForm: Integer; const UniversitySpecialitiesKode: WideString; const SpecDirectionsCode: WideString; const SpecSpecialityCode: WideString; const Filters: WideString): ArrayOfDUniversityFacultetSpecialities; stdcall; function UniversityFacultetSpecialitiesGet2(const SessionGUID: WideString; const UniversityKode: WideString; const UniversityFacultetKode: WideString; const SpecCode: WideString; const Id_Language: Integer; const ActualDate: WideString; const Id_PersonRequestSeasons: Integer; const Id_PersonEducationForm: Integer; const UniversitySpecialitiesKode: WideString; const SpecDirectionsCode: WideString; const SpecSpecialityCode: WideString; const Filters: WideString): ArrayOfDUniversityFacultetSpecialities2; stdcall; function CoursesGet(const SessionGUID: WideString; const Id_Language: Integer): ArrayOfDCourses; stdcall; function SpecGet(const SessionGUID: WideString; const SpecRedactionCode: WideString; const SpecIndastryCode: WideString; const SpecDirectionsCode: WideString; const SpecSpecialityCode: WideString; const SpecCode: WideString; const Id_Language: Integer; const ActualDate: WideString; const SpecClasifierCode: WideString): ArrayOfDSpec; stdcall; function SpecDirectionsGet(const SessionGUID: WideString; const Id_Language: Integer; const ActualDate: WideString; const SpecIndastryClasifierCode: WideString; const SpecClasifierCode: WideString; const CodeMask: WideString; const DictType: Integer): ArrayOfDSpecDirections; stdcall; function SpecDirectionsGet2(const SessionGUID: WideString; const Id_Language: Integer; const ActualDate: WideString; const SpecIndastryClasifierCode: WideString; const SpecClasifierCode: WideString; const CodeMask: WideString; const DictType: Integer): ArrayOfDSpecDirections2; stdcall; function KOATUUGet(const SessionGUID: WideString; const ActualDate: WideString; const Id_Language: Integer; const KOATUUCode: WideString; const Hundred: Integer; const NameMask: WideString; const FullNameMask: WideString; const WitchRegions: Integer): ArrayOfDKOATUU; stdcall; function KOATUUGetL1(const SessionGUID: WideString; const ActualDate: WideString; const Id_Language: Integer): ArrayOfDKOATUU; stdcall; function KOATUUGetL2(const SessionGUID: WideString; const ActualDate: WideString; const Id_Language: Integer; const KOATUUCodeL1: WideString): ArrayOfDKOATUU; stdcall; function KOATUUGetL3(const SessionGUID: WideString; const ActualDate: WideString; const Id_Language: Integer; const KOATUUCodeL2: WideString; const NameMask: WideString): ArrayOfDKOATUU; stdcall; function StreetTypesGet(const SessionGUID: WideString; const Id_Language: Integer): ArrayOfDStreetTypes; stdcall; function UniversityFacultetsGetRequests(const SessionGUID: WideString; const Id_PersonRequestSeasons: Integer; const UniversityFacultetKode: WideString; const UniversitySpecialitiesKode: WideString; const Id_Language: Integer; const ActualDate: WideString; const PersonCodeU: WideString; const Hundred: Integer; const MinDate: WideString; const Id_PersonRequestStatusType1: Integer; const Id_PersonRequestStatusType2: Integer; const Id_PersonRequestStatusType3: Integer; const Id_PersonEducationForm: Integer; const UniversityKode: WideString; const Id_Qualification: Integer; const Filters: WideString): ArrayOfDUniversityFacultetsRequests; stdcall; function UniversityFacultetsGetRequests2(const SessionGUID: WideString; const Id_PersonRequestSeasons: Integer; const UniversityFacultetKode: WideString; const UniversitySpecialitiesKode: WideString; const Id_Language: Integer; const ActualDate: WideString; const PersonCodeU: WideString; const Hundred: Integer; const MinDate: WideString; const Id_PersonRequestStatusType1: Integer; const Id_PersonRequestStatusType2: Integer; const Id_PersonRequestStatusType3: Integer; const Id_PersonEducationForm: Integer; const UniversityKode: WideString; const Id_Qualification: Integer; const Filters: WideString): ArrayOfDUniversityFacultetsRequests2; stdcall; end; function GetEDBOGuidesSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): EDBOGuidesSoap; implementation function GetEDBOGuidesSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): EDBOGuidesSoap; const defWSDL = 'D:\DonnU\SourcesSVN\FMAS-WIN\Contingent_Student\Sources\WSDL\EDBOGuidesToFMASService.wsdl'; defURL = 'http://ias.donnu.edu.ua/EDBOdata/EDBOGuidesToFMASService.asmx'; defSvc = 'EDBOGuides'; defPrt = 'EDBOGuidesSoap'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as EDBOGuidesSoap); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor dAcademicYears.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FAcademicYearDateBegin) then FAcademicYearDateBegin.Free; if Assigned(FAcademicYearDateEnd) then FAcademicYearDateEnd.Free; if Assigned(FAcademicYearDatelLastChange) then FAcademicYearDatelLastChange.Free; inherited Destroy; end; destructor dLastError.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; inherited Destroy; end; destructor dUniversities.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FUniversityDateBegin) then FUniversityDateBegin.Free; if Assigned(FUniversityDateEnd) then FUniversityDateEnd.Free; if Assigned(FDateRegistration) then FDateRegistration.Free; if Assigned(FUniversityRegistrationDateBegin) then FUniversityRegistrationDateBegin.Free; if Assigned(FUniversityRegistrationDateEnd) then FUniversityRegistrationDateEnd.Free; if Assigned(FUniversityRegistrationDateLastChange) then FUniversityRegistrationDateLastChange.Free; if Assigned(FWarrantDate) then FWarrantDate.Free; inherited Destroy; end; destructor dLanguages.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; inherited Destroy; end; destructor dUniversityFacultets.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FUniversityFacultetDateBegin) then FUniversityFacultetDateBegin.Free; if Assigned(FUniversityFacultetDateEnd) then FUniversityFacultetDateEnd.Free; inherited Destroy; end; destructor dUniversityFacultetSpecialities.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FUniversitySpecialitiesDateBegin) then FUniversitySpecialitiesDateBegin.Free; if Assigned(FUniversitySpecialitiesDateEnd) then FUniversitySpecialitiesDateEnd.Free; if Assigned(FDateBeginPersonRequestSeason) then FDateBeginPersonRequestSeason.Free; if Assigned(FDateEndPersonRequestSeason) then FDateEndPersonRequestSeason.Free; if Assigned(FDurationEducation) then FDurationEducation.Free; if Assigned(FEducationDateBegin) then FEducationDateBegin.Free; if Assigned(FEducationDateEnd) then FEducationDateEnd.Free; inherited Destroy; end; destructor dUniversityFacultetSpecialities2.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FUniversitySpecialitiesDateBegin) then FUniversitySpecialitiesDateBegin.Free; if Assigned(FUniversitySpecialitiesDateEnd) then FUniversitySpecialitiesDateEnd.Free; if Assigned(FDateBeginPersonRequestSeason) then FDateBeginPersonRequestSeason.Free; if Assigned(FDateEndPersonRequestSeason) then FDateEndPersonRequestSeason.Free; if Assigned(FDurationEducation) then FDurationEducation.Free; if Assigned(FEducationDateBegin) then FEducationDateBegin.Free; if Assigned(FEducationDateEnd) then FEducationDateEnd.Free; inherited Destroy; end; destructor dCourses.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; inherited Destroy; end; destructor dSpec.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FSpecDateBegin) then FSpecDateBegin.Free; if Assigned(FSpecDateEnd) then FSpecDateEnd.Free; if Assigned(FSpecIndastryDateBegin) then FSpecIndastryDateBegin.Free; if Assigned(FSpecIndastryDateEnd) then FSpecIndastryDateEnd.Free; if Assigned(FSpecDirectionsDateBegin) then FSpecDirectionsDateBegin.Free; if Assigned(FSpecDirectionsDateEnd) then FSpecDirectionsDateEnd.Free; if Assigned(FSpecSpecialityDateBegin) then FSpecSpecialityDateBegin.Free; if Assigned(FSpecSpecialityDateEnd) then FSpecSpecialityDateEnd.Free; if Assigned(FSpecCodeDateLastChange) then FSpecCodeDateLastChange.Free; inherited Destroy; end; destructor dSpecDirections.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; inherited Destroy; end; destructor dSpecDirections2.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; inherited Destroy; end; destructor dKOATUU.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FKOATUUDateBegin) then FKOATUUDateBegin.Free; if Assigned(FKOATUUDateEnd) then FKOATUUDateEnd.Free; inherited Destroy; end; destructor dStreetTypes.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; inherited Destroy; end; destructor dUniversityFacultetsRequests.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FUniversitySpecialitiesDateBegin) then FUniversitySpecialitiesDateBegin.Free; if Assigned(FUniversitySpecialitiesDateEnd) then FUniversitySpecialitiesDateEnd.Free; if Assigned(FDateLastChange) then FDateLastChange.Free; if Assigned(FKonkursValue) then FKonkursValue.Free; if Assigned(FKonkursValueCorrectValue) then FKonkursValueCorrectValue.Free; if Assigned(FDateCreate) then FDateCreate.Free; if Assigned(FEntrantDocumentDateGet) then FEntrantDocumentDateGet.Free; if Assigned(FEntrantDocumentValue) then FEntrantDocumentValue.Free; inherited Destroy; end; destructor dUniversityFacultetsRequests2.Destroy; begin if Assigned(FExtensionData) then FExtensionData.Free; if Assigned(FUniversitySpecialitiesDateBegin) then FUniversitySpecialitiesDateBegin.Free; if Assigned(FUniversitySpecialitiesDateEnd) then FUniversitySpecialitiesDateEnd.Free; if Assigned(FDateLastChange) then FDateLastChange.Free; if Assigned(FKonkursValue) then FKonkursValue.Free; if Assigned(FKonkursValueCorrectValue) then FKonkursValueCorrectValue.Free; if Assigned(FDateCreate) then FDateCreate.Free; if Assigned(FEntrantDocumentDateGet) then FEntrantDocumentDateGet.Free; if Assigned(FEntrantDocumentValue) then FEntrantDocumentValue.Free; if Assigned(FBirthday) then FBirthday.Free; inherited Destroy; end; initialization InvRegistry.RegisterInterface(TypeInfo(EDBOGuidesSoap), 'http://edboservice.ua/', 'UTF-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(EDBOGuidesSoap), 'http://edboservice.ua/%operationName%'); InvRegistry.RegisterInvokeOptions(TypeInfo(EDBOGuidesSoap), ioDocument); RemClassRegistry.RegisterXSClass(ExtensionDataObject, 'http://edboservice.ua/', 'ExtensionDataObject'); RemClassRegistry.RegisterXSClass(dAcademicYears, 'http://edboservice.ua/', 'dAcademicYears'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDAcademicYears), 'http://edboservice.ua/', 'ArrayOfDAcademicYears'); RemClassRegistry.RegisterXSClass(dLastError, 'http://edboservice.ua/', 'dLastError'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDLastError), 'http://edboservice.ua/', 'ArrayOfDLastError'); RemClassRegistry.RegisterXSClass(dUniversities, 'http://edboservice.ua/', 'dUniversities'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDUniversities), 'http://edboservice.ua/', 'ArrayOfDUniversities'); RemClassRegistry.RegisterXSClass(dLanguages, 'http://edboservice.ua/', 'dLanguages'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDLanguages), 'http://edboservice.ua/', 'ArrayOfDLanguages'); RemClassRegistry.RegisterXSClass(dUniversityFacultets, 'http://edboservice.ua/', 'dUniversityFacultets'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDUniversityFacultets), 'http://edboservice.ua/', 'ArrayOfDUniversityFacultets'); RemClassRegistry.RegisterXSClass(dUniversityFacultetSpecialities, 'http://edboservice.ua/', 'dUniversityFacultetSpecialities'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDUniversityFacultetSpecialities), 'http://edboservice.ua/', 'ArrayOfDUniversityFacultetSpecialities'); RemClassRegistry.RegisterXSClass(dUniversityFacultetSpecialities2, 'http://edboservice.ua/', 'dUniversityFacultetSpecialities2'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDUniversityFacultetSpecialities2), 'http://edboservice.ua/', 'ArrayOfDUniversityFacultetSpecialities2'); RemClassRegistry.RegisterXSClass(dCourses, 'http://edboservice.ua/', 'dCourses'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDCourses), 'http://edboservice.ua/', 'ArrayOfDCourses'); RemClassRegistry.RegisterXSClass(dSpec, 'http://edboservice.ua/', 'dSpec'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDSpec), 'http://edboservice.ua/', 'ArrayOfDSpec'); RemClassRegistry.RegisterXSClass(dSpecDirections, 'http://edboservice.ua/', 'dSpecDirections'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDSpecDirections), 'http://edboservice.ua/', 'ArrayOfDSpecDirections'); RemClassRegistry.RegisterXSClass(dSpecDirections2, 'http://edboservice.ua/', 'dSpecDirections2'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDSpecDirections2), 'http://edboservice.ua/', 'ArrayOfDSpecDirections2'); RemClassRegistry.RegisterXSClass(dKOATUU, 'http://edboservice.ua/', 'dKOATUU'); RemClassRegistry.RegisterExternalPropName(TypeInfo(dKOATUU), 'Type_', 'Type'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDKOATUU), 'http://edboservice.ua/', 'ArrayOfDKOATUU'); RemClassRegistry.RegisterXSClass(dStreetTypes, 'http://edboservice.ua/', 'dStreetTypes'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDStreetTypes), 'http://edboservice.ua/', 'ArrayOfDStreetTypes'); RemClassRegistry.RegisterXSClass(dUniversityFacultetsRequests, 'http://edboservice.ua/', 'dUniversityFacultetsRequests'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDUniversityFacultetsRequests), 'http://edboservice.ua/', 'ArrayOfDUniversityFacultetsRequests'); RemClassRegistry.RegisterXSClass(dUniversityFacultetsRequests2, 'http://edboservice.ua/', 'dUniversityFacultetsRequests2'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDUniversityFacultetsRequests2), 'http://edboservice.ua/', 'ArrayOfDUniversityFacultetsRequests2'); end.
unit FieldEdit; {$MODE Delphi} interface uses Grids, Classes, StdCtrls; {TFieldEdit pseudo control For Sector/Wall/Vertex/Object editors } type TVarType=(vtString,vtDouble,vtInteger,vtDword); TFieldInfo=class Private Grid:TStringGrid; row:Integer; olds:string; Function GetS:String; Procedure SetS(const s:String); Procedure BadValueMsg; Public id:Integer; changed:boolean; vtype:TVarType; Constructor Create(aGrid:TStringGrid;arow:integer); Property s:String read GetS write SetS; Procedure ReadString(var st:String); Procedure ReadInteger(var i:Integer); Procedure Read0to31(var b:Byte); Procedure ReadDword(var d:longint); Procedure ReadDouble(var d:Double); end; TFEHandler=Procedure(Fi:TFieldInfo) of object; TFEChangeHandler=Function(Fi:TFieldInfo):boolean of object; TDoneEdit=procedure of object; TFieldEdit=class Private grid:TStringGrid; fl:TList; oldRow:integer; Function GetField(n:Integer):TFieldInfo; Function GetCurField:TFieldInfo; Procedure Changed(row:integer); Procedure CallDoneEdit; Public FieldCount:Integer; ONDblClick:TFEHandler; ONChange:TFEChangeHandler; OnDoneEdit:TDoneEdit; Constructor Create(aGrid:TStringGrid); Destructor Destroy;override; Procedure Clear; Procedure DeactivateHandler; Property CurrentField:TFieldInfo read GetCurField; Property Fields[n:integer]:TFieldInfo read GetField; procedure SelectHandler(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); procedure DblClickHandler(Sender: TObject); procedure SetTextHandler(Sender: TObject; ACol, ARow: Longint; const Text: string); function AddField(const Name:String;ID:Integer;vartype:TVarType):TFieldInfo; Procedure AddFieldInt(const Name:string;ID,V:Integer); Procedure AddFieldHex(const Name:string;ID:Integer;V:longint); Procedure AddFieldFloat(const Name:string;ID:Integer;v:double); Procedure AddFieldStr(const Name:string;ID:Integer;const v:string); Function GetFieldByID(ID:Integer):TFieldInfo; procedure KeyDown(Sender: TObject; var Key: Word;Shift: TShiftState); Procedure DoneAdding; end; TVIChange=function (const s:string):boolean of object; TValInput=class eb:TEdit; cb:TComboBox; OldS:string; OnChange:TVIChange; changed:boolean; Constructor Create(aEb:TEdit); Constructor CreateFromCB(aCB:TComboBox); procedure ChangeHandler(Sender: TObject); Procedure SetAsInt(i:integer); Function GetS:String; Procedure SetAsFloat(d:double); Procedure SetAsString(s:string); Property S:string read GetS; Function AsInt:Integer; Function AsFloat:Double; Private Procedure SetS(const s:string); Function IntChange(const s:string):boolean; Function FloatChange(const s:string):boolean; end; Function feValDouble(const s:string;var d:double):boolean; Function feValInt(const s:string;var i:Integer):boolean; implementation uses Misc_Utils, SysUtils, Windows, Messages, Forms; Constructor TFieldInfo.Create(aGrid:TStringGrid;arow:integer); begin Grid:=aGrid; Row:=arow; end; Function TFieldInfo.GetS:String; begin Result:=Grid.Cells[1,row]; end; Procedure TFieldInfo.SetS(const s:String); begin Changed:=true; Grid.Cells[1,row]:=s; {if Grid.Cells[1,row]=olds then} end; Procedure TFieldInfo.BadValueMsg; begin MsgBox(s+' is not a valid value for '+Grid.Cells[0,row], 'Field Editor',mb_ok); end; Procedure TFieldInfo.ReadString(var st:String); begin st:=s; end; Procedure TFieldInfo.ReadInteger(var i:Integer); var v,a:Integer; begin Val(s,v,a); if a=0 then i:=v else BadValueMsg; end; Procedure TFieldInfo.Read0to31(var b:Byte); var v,a:Integer; begin Val(s,v,a); if (a=0) and (v>=-31) and (v<=31) then b:=v else BadValueMsg; end; Procedure TFieldInfo.ReadDword(var d:longint); begin Try d:=StrToDword(s); except On EConvertError do BadValueMsg; end; end; Procedure TFieldInfo.ReadDouble(var d:Double); var a:Integer; v:Double; begin Val(s,v,a); if a=0 then d:=v else BadValueMsg; end; Constructor TFieldEdit.Create(aGrid:TStringGrid); begin grid:=aGrid; fl:=TList.Create; Grid.OnDblclick:=DblClickHandler; Grid.OnSelectCell:=SelectHandler; Grid.OnSetEditText:=SetTextHandler; Grid.OnKeyDown:=KeyDown; end; Destructor TFieldEdit.Destroy; begin Grid.OnDblclick:=nil; Grid.OnSelectCell:=nil; Clear; FL.Free; end; Procedure TFieldEdit.Clear; var i:integer; begin For i:=0 to FieldCount-1 do begin Grid.Cells[0,i]:=''; Grid.Cells[1,i]:=''; Fields[i].Free; end; FL.Clear; FieldCount:=0; OldRow:=0; end; Function TFieldEdit.GetField(n:Integer):TFieldInfo; begin Result:=TFieldInfo(FL.List[n]); end; Function TFieldEdit.GetFieldByID(ID:Integer):TFieldInfo; var i:Integer; begin Result:=nil; for i:=0 to FieldCount-1 do if Fields[i].ID=ID then begin Result:=Fields[i]; exit; end; end; Function TFieldEdit.GetCurField:TFieldInfo; begin if Grid.Row<>-1 then Result:=TFieldInfo(FL.List[Grid.Row]) else Result:=nil; end; procedure TFieldEdit.SelectHandler(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); var fi:TFieldInfo; begin if (col<>1) or (row>=FieldCount) then CanSelect:=false else begin fi:=Fields[Row]; if fi=nil then CanSelect:=false else if fi.id=-1 then CanSelect:=false else CanSelect:=true; fi:=Fields[OldRow]; if fi.s<>fi.olds then Changed(oldRow); oldRow:=row; end; end; procedure TFieldEdit.DblClickHandler(Sender: TObject); var fi:TFieldInfo; begin With Grid do begin if (col<>1) or (row>=FieldCount) then exit; fi:=Fields[row]; end; if (fi<>nil) and (Assigned(OnDblClick)) then OnDblClick(fi); end; Function IsValid(const s:string;vt:TVarType):Boolean; var a:Integer; i:Integer; d:Double; begin a:=-1; Case vt of vtString: a:=0; vtInteger: Val(s,i,a); vtDouble: Val(s,d,a); vtDword: begin a:=0; Try i:=StrToDword(s); except On EConvertError do a:=-1; end; end; end; Result:=a=0; end; procedure TFieldEdit.SetTextHandler(Sender: TObject; ACol, ARow: Longint; const Text: string); var Fi:TFieldInfo; s:string; begin { if (ACol<>1) or (Arow>=FieldCount) then exit; fi:=Fields[aRow]; if fi<>nil then begin s:=fi.olds; if Assigned(OnChange) then if not OnChange(fi) then begin if fi.s<>s then fi.s:=s; end else fi.changed:=true; end;} end; Procedure TFieldEdit.DoneAdding; begin Grid.Enabled:=false; Grid.Enabled:=true; end; function TFieldEdit.AddField(const Name:String;ID:Integer;vartype:TVarType):TFieldInfo; var fi:TFieldInfo; begin fi:=TFieldInfo.Create(Grid,FieldCount); fi.id:=ID; fi.vtype:=varType; Grid.Cells[0,FieldCount]:=Name; FL.Add(fi); Inc(FieldCount); Grid.RowCount:=FieldCount; {Grid.row:=0; Grid.col:=1;} result:=fi; end; Procedure TFieldEdit.AddFieldHex(const Name:string;ID:Integer;V:longint); begin With AddField(Name,ID,vtInteger) do begin olds:=Format('%x',[v]); s:=olds; end; end; Procedure TFieldEdit.AddFieldInt(const Name:string;ID,V:Integer); begin With AddField(Name,ID,vtInteger) do begin olds:=IntToStr(v); s:=olds; end; end; Procedure TFieldEdit.AddFieldFloat(const Name:string;ID:Integer;v:double); begin With AddField(Name,ID,vtInteger) do begin olds:=DoubleToStr(v); s:=olds; end; end; Procedure TFieldEdit.AddFieldStr(const Name:string;ID:Integer;const v:string); begin With AddField(Name,ID,vtInteger) do begin olds:=v; s:=olds; end; end; Procedure TFieldEdit.DeactivateHandler; begin if Grid.Row>=FieldCount then exit; With Fields[Grid.Row] do begin if s<>olds then Self.Changed(Grid.Row); end; end; Procedure TFieldEdit.Changed(row:integer); var fi:TFieldInfo; begin if not Assigned(OnChange) then exit; if row>=FieldCount then exit; fi:=Fields[row]; if not OnChange(fi) then fi.s:=fi.olds else begin fi.changed:=true; fi.olds:=fi.s; end; end; Procedure TFieldEdit.CallDoneEdit; begin if Assigned(OnDoneEdit) then OnDoneEdit; end; procedure TFieldEdit.KeyDown(Sender: TObject; var Key: Word;Shift: TShiftState); var fi:TFieldInfo; begin if shift<>[] then exit; if Grid.Row>=FieldCount then exit; fi:=Fields[Grid.Row]; Case Key of VK_Escape: begin fi.s:=fi.Olds; CallDoneEdit; end; VK_Return: begin Changed(Grid.Row); CallDoneEdit; end; VK_F10: if (fi<>nil) and (Assigned(OnDblClick)) then OnDblClick(fi); end; end; Constructor TVAlInput.Create(aEb:TEdit); begin eb:=aEb; eb.OnChange:=ChangeHandler; olds:=eb.text; end; Constructor TVAlInput.CreateFromCB(aCB:TComboBox); begin cb:=aCB; cb.OnChange:=ChangeHandler; olds:=cb.Text; end; Procedure TVAlInput.SetS(const s:string); begin if eb<>nil then begin eb.Onchange:=nil; olds:=s; eb.text:=s; eb.OnChange:=ChangeHandler; exit; end; cb.Onchange:=nil; olds:=s; cb.text:=s; cb.OnChange:=ChangeHandler; end; procedure TVAlInput.ChangeHandler(Sender: TObject); begin changed:=true; if not Assigned(OnChange) then exit; if eb<>nil then begin if OnChange(eb.Text) then olds:=eb.text else SetS(olds); exit; end; if OnChange(cb.Text) then olds:=cb.text else SetS(olds); end; Procedure TVAlInput.SetAsInt(i:integer); begin SetS(IntToStr(i)); OnChange:=IntChange; changed:=false; end; Procedure TVAlInput.SetAsFloat(d:double); begin SetS(DoubleToStr(d)); OnChange:=FloatChange; changed:=false; end; Procedure TVAlInput.SetAsString(s:string); begin SetS(s); OnChange:=nil; changed:=false; end; Function TVAlInput.IntChange(const s:string):boolean; var i:integer; w:string; begin getWord(s,1,w); Result:=feValInt(w,i); end; Function TVAlInput.GetS:String; begin if eb<>nil then Result:=eb.text else Result:=cb.text; end; Function TVAlInput.AsInt:Integer; var w:string; begin getWord(s,1,w); if not feValInt(w,Result) then Result:=0; end; Function TVAlInput.AsFloat:Double; begin if not feValDouble(s,Result) then Result:=0; end; Function feValDouble(const s:string;var d:double):boolean; var st:string; begin st:=s; if s='-' then begin result:=true; d:=0; exit; end; if (st<>'') and (st[length(st)]='.') then SetLength(st,length(st)-1); result:=ValDouble(st,d); end; Function feValInt(const s:string;var i:Integer):boolean; var st:string; begin st:=s; if s='-' then begin result:=true; i:=0; exit; end; result:=ValInt(st,i); end; Function TVAlInput.FloatChange(const s:string):boolean; var d:double; begin Result:=feValDouble(s,d); end; end.
unit NewFrontiers.Reflection; interface uses System.Rtti, Generics.Collections, System.TypInfo; type TClassOfAttribute = class of TCustomAttribute; /// <summary> /// Der Reflection Manager kapselt Zugriffe auf die Rtti und hält den /// Context über die ganze Laufzeit am Leben. /// </summary> TReflectionManager = class protected _context: TRttiContext; _classes: TDictionary<TClass, TRttiInstanceType>; constructor Create; class function getProperty(aInstance: TObject; aPropertyName: string): TRttiProperty; public destructor Destroy; override; /// <summary> /// Der verwendete RttiContext /// </summary> property Context: TRttiContext read _context; /// <summary> /// Ein Dictionary mit den Rtti-Informationen aller Klassen, die /// bisher abgefragt wurden. Wurde aus Performancegründen eingeführt. /// Ob das Abrufen der Rtti-Informationen tatsächlich so teuer ist, /// dass sich ein puffern lohnt wurde noch nicht geprüft. /// </summary> property Classes: TDictionary<TClass, TRttiInstanceType> read _classes; /// <summary> /// Gibt die aktuelle Instanz zurück - Singleton /// </summary> class function getInstance: TReflectionManager; /// <summary> /// Gibt die Rtti-Informationen für die übergebene Klasse zurück. /// </summary> class function getInfoForClass(aClass: TClass): TRttiInstanceType; /// <summary> /// Gibt den Wert einer Property zurück /// </summary> class function getPropertyValue(aInstance: TObject; aPropertyName: string): TValue; /// <summary> /// Setzt den Wert einer Property /// </summary> class procedure setPropertyValue(aInstance: TObject; aPropertyName: string; aValue: TValue); /// <summary> /// Gibt den Typ einer Property zurück. /// </summary> class function getPropertyKind(aInstance: TObject; aPropertyName: string): TTypeKind; /// <summary> /// Gibt den Rtti-Zeiger auf eine Methode innerhalb einer Instanz /// zurück /// </summary> class function getMethod(aInstance: TObject; aMethodName: string): TRttiMethod; /// <summary> /// Gibt eine Liste aller Properties einer Klasse zurück, die ein /// bestimmtes Attribut haben /// </summary> class function getPropertiesWithAttribute(aClass: TClass; aAttribute: TClassOfAttribute): TList<TRttiProperty>; /// <summary> /// Gibt eine LIste aller Felder einer Klasse zurück, die ein /// bestimmtes Attribut haben /// </summary> class function getFieldsWithAttribute(aClass: TCLass; aAttribute: TClassOfAttribute): TList<TRttiField>; /// <summary> /// Gibt den Wert eines Feldes innerhalb einer Klasse zurück. Falls /// vorhanden wird der entsprechende Getter aufgerufen /// </summary> class function getFieldValue(aInstance: TObject; aFieldName: string): TValue; /// <summary> /// Setzt den Wert eines Feldes innerhalb einer Klasse. Falls /// vorhanden wird der entsprechende Setter aufgerufen /// </summary> class procedure setFieldValue(aInstance: TObject; aFieldName: string; aValue: TValue); /// <summary> /// Gibt zurück ob die übergebene Instanz eine Property mit dem Namen /// hat /// </summary> class function hasProperty(aInstance: TObject; aPropertyName: string): boolean; /// <summary> /// Gibt zurück ob die übergebene Instanz ein Feld mit dem Namen hat /// </summary> class function hasField(aInstance: TObject; aFieldName: string): Boolean; end; implementation uses SysUtils, NewFrontiers.Utility.Exceptions, Vcl.Dialogs, NewFrontiers.Reflection.ValueConvert, NewFrontiers.Utility.StringUtil; var _instance: TReflectionManager; { TReflectionManager } constructor TReflectionManager.Create; begin _context := TRttiContext.Create; _classes := TObjectDictionary<TClass, TRttiInstanceType>.Create([doOwnsValues]); end; destructor TReflectionManager.Destroy; begin _context.Free; _classes.Free; inherited; end; class function TReflectionManager.getFieldsWithAttribute(aClass: TCLass; aAttribute: TClassOfAttribute): TList<TRttiField>; var typeInfo: TRttiInstanceType; curField: TRttiField; curAttribute: TCustomAttribute; begin result := TList<TRttiField>.Create; typeInfo := getInstance.Context.getType(aClass) as TRttiInstanceType; for curField in typeInfo.GetFields do begin for curAttribute in curField.GetAttributes do begin if (curAttribute is aAttribute) then Result.add(curField); end; end; end; class function TReflectionManager.getFieldValue(aInstance: TObject; aFieldName: string): TValue; var fieldName, path: string; tempField: TRttiField; getterName: string; getter: TRttiMethod; begin // Falls es ein Binding-Path ist, erst aufteilen und dann auswerten if (TStringUtil.Contains('.', aFieldName)) then begin TStringUtil.stringParts(aFieldName, '.', fieldName, path); result := TReflectionManager.getFieldValue(aInstance, fieldName); if (result.AsObject = nil) then result := TValue.From<string>('') else result := TReflectionManager.getFieldValue(result.AsObject, path); end // Eindeutiges Feld -> Auswerten else begin // 1. Versuch der Getter getterName := 'get' + aFieldName; getter := TReflectionManager.getMethod(aInstance, getterName); if (getter <> nil) then begin result := getter.Invoke(aInstance, []); end else begin // 2. Versuch, das Feld direkt tempField := TReflectionManager.getInfoForClass(aInstance.ClassType).GetField(aFieldName); if (tempField = nil) then raise Exception.Create('Feld ' + aFieldName + ' existiert in übergebener Instanz nicht'); result := tempField.GetValue(aInstance); end; end; end; class function TReflectionManager.getInfoForClass(aClass: TClass): TRttiInstanceType; var typeInfo: TRttiInstanceType; begin if (not getInstance.Classes.ContainsKey(aClass)) then begin typeInfo := getInstance.Context.getType(aClass) as TRttiInstanceType; getInstance.Classes.add(aClass, typeInfo); end; result := getInstance.Classes[aClass]; end; class function TReflectionManager.getInstance: TReflectionManager; begin if (_instance = nil) then _instance := TReflectionManager.Create; result := _instance; end; class function TReflectionManager.getMethod(aInstance: TObject; aMethodName: string): TRttiMethod; begin result := TReflectionManager.getInfoForClass(aInstance.ClassType).GetMethod(aMethodName); end; class function TReflectionManager.getPropertiesWithAttribute(aClass: TClass; aAttribute: TClassOfAttribute): TList<TRttiProperty>; var typeInfo: TRttiInstanceType; curProperty: TRttiProperty; curAttribute: TCustomAttribute; begin result := TList<TRttiProperty>.Create; typeInfo := getInstance.Context.getType(aClass) as TRttiInstanceType; for curProperty in typeInfo.GetProperties do begin for curAttribute in curProperty.GetAttributes do begin if (curAttribute is aAttribute) then Result.add(curProperty); end; end; end; class function TReflectionManager.getProperty(aInstance: TObject; aPropertyName: string): TRttiProperty; var propertyName, path: string; begin if (TStringUtil.Contains('.', aPropertyName)) then begin TStringUtil.stringParts(aPropertyName, '.', propertyName, path); result := TReflectionManager.getProperty(aInstance, propertyName); end else begin result := getInstance.Classes.Items[aInstance.ClassType].GetProperty(aPropertyName); end; end; class function TReflectionManager.getPropertyKind(aInstance: TObject; aPropertyName: string): TTypeKind; begin result := getProperty(aInstance, aPropertyName).PropertyType.Handle.Kind; end; class function TReflectionManager.getPropertyValue(aInstance: TObject; aPropertyName: string): TValue; var propertyName, path: string; tempProp: TRttiProperty; begin // Falls es ein Binding-Path ist, erst aufteilen und dann auswerten if (TStringUtil.Contains('.', aPropertyName)) then begin TStringUtil.stringParts(aPropertyName, '.', propertyName, path); result := TReflectionManager.getPropertyValue(aInstance, propertyName); if (result.AsObject = nil) then result := TValue.From<string>('') else result := TReflectionManager.getPropertyValue(result.AsObject, path); end // Eindeutige Property -> Auswerten else begin if (not getInstance.Classes.ContainsKey(aInstance.ClassType)) then TReflectionManager.getInfoForClass(aInstance.ClassType); tempProp := getInstance.Classes.Items[aInstance.ClassType].GetProperty(aPropertyName); if (tempProp = nil) then raise Exception.Create('Property ' + aPropertyName + ' existiert in übergebener Instanz nicht'); result := tempProp.GetValue(aInstance); end; end; class function TReflectionManager.hasField(aInstance: TObject; aFieldName: string): Boolean; begin raise Exception.Create('not implemented yet'); end; class function TReflectionManager.hasProperty(aInstance: TObject; aPropertyName: string): boolean; begin if (not getInstance.Classes.ContainsKey(aInstance.ClassType)) then TReflectionManager.getInfoForClass(aInstance.ClassType); result := getInstance.Classes.Items[aInstance.ClassType].GetProperty(aPropertyName) <> nil; end; class procedure TReflectionManager.setFieldValue(aInstance: TObject; aFieldName: string; aValue: TValue); var fieldName, path: string; tempField: TRttiField; setterName: string; setter: TRttiMethod; targetValue: TValue; begin // Falls es ein Binding-Path ist, erst aufteilen und dann auswerten if (TStringUtil.Contains('.', aFieldName)) then begin TStringUtil.stringParts(aFieldName, '.', fieldName, path); targetValue := TReflectionManager.getFieldValue(aInstance, fieldName); if (targetValue.AsObject <> nil) then TReflectionManager.setFieldValue(targetValue.AsObject, path, aValue); end // Eindeutiges Feld -> Auswerten else begin // 1. Versuch der Setter setterName := 'set' + aFieldName; setter := TReflectionManager.getMethod(aInstance, setterName); if (setter <> nil) then begin setter.Invoke(aInstance, [aValue]); end else begin // 2. Versuch, das Feld direkt tempField := TReflectionManager.getInfoForClass(aInstance.ClassType).GetField(aFieldName); if (tempField = nil) then raise Exception.Create('Feld ' + aFieldName + ' existiert in übergebener Instanz nicht'); tempField.SetValue(aInstance, aValue); end; end; end; class procedure TReflectionManager.setPropertyValue(aInstance: TObject; aPropertyName: string; aValue: TValue); var targetProperty: TRttiProperty; targetValue: TValue; propertyName, path: string; begin if (not getInstance.Classes.ContainsKey(aInstance.ClassType)) then TReflectionManager.getInfoForClass(aInstance.ClassType); // Falls es ein Binding-Path ist, erst aufteilen und dann auswerten if (TStringUtil.Contains('.', aPropertyName)) then begin TStringUtil.stringParts(aPropertyName, '.', propertyName, path); targetProperty := getInstance.Classes.Items[aInstance.ClassType].GetProperty(propertyName); if (targetProperty.getValue(aInstance).AsObject <> nil) then TReflectionManager.setPropertyValue(targetProperty.GetValue(aInstance).asObject, path, aValue); end else begin targetProperty := getInstance.Classes.Items[aInstance.ClassType].GetProperty(aPropertyName); targetValue := TValueConverter.convertTo(aValue, targetProperty.PropertyType.Handle); targetProperty.SetValue(aInstance, targetValue); end; end; end.
unit SotrListFilterFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxMRUEdit, cxLookAndFeelPainters, cxButtons, SotrListConsts, packageLoad, IBase, Ztypes; type TSotrListFilterForm = class(TForm) TNMaskEdit: TcxMaskEdit; TnLabel: TLabel; FamiliaEditMask: TcxMaskEdit; FamiliaLabel: TLabel; INKMaskEdit: TcxMaskEdit; InkLabel: TLabel; DepartmentMRUEdit: TcxMRUEdit; DepartmentLabel: TLabel; OkButton: TcxButton; CancelButton: TcxButton; procedure FormCreate(Sender: TObject); procedure TNMaskEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OkButtonClick(Sender: TObject); procedure DepartmentMRUEditPropertiesButtonClick(Sender: TObject); private DB_handle:TISC_DB_HANDLE; public Fam:string; Tn:Integer; Ink:String; Id_Department : Integer; CanSelect:Boolean; constructor Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE);reintroduce; end; var SotrListFilterForm: TSotrListFilterForm; implementation {$R *.dfm} constructor TSotrListFilterForm.Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE); begin inherited Create(AOwner); DB_handle := ADB_handle; end; procedure TSotrListFilterForm.FormCreate(Sender: TObject); begin //Инициализация меток Self.Caption:=Form_SotrFilterCaption; TnLabel.Caption:=Tn_Label_Caption; FamiliaLabel.Caption:= 'Прізвище'; //Familia_Label_Caption; InkLabel.Caption:= 'Ідентифікаційний номер';//Ink_Label_Caption; DepartmentLabel.Caption:=Department_Label_Caption; Id_Department:=-1; OkButton.Caption:=YesBtn_Caption; CancelButton.Caption:=CancelBtn_Caption; // OkButton.SetFocus; end; procedure TSotrListFilterForm.TNMaskEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=vk_return then self.OkButtonClick(SEnder); end; procedure TSotrListFilterForm.OkButtonClick(Sender: TObject); begin Fam:=Self.FamiliaEditMask.Text; if (Self.TNMaskEdit.Text='') then Tn:=-1 else Tn:=StrToInt(Self.TNMaskEdit.Text); Ink:=Self.INKMaskEdit.Text; ModalResult:=mrOk; end; procedure TSotrListFilterForm.DepartmentMRUEditPropertiesButtonClick( Sender: TObject); var Department:variant; begin Department := LoadDepartment(self,DB_handle,zfsModal); if VarArrayDimCount(Department)> 0 then if Department[0]<> NULL then begin DepartmentMRUEdit.Text := varToStr(Department[1]); Id_Department := Department[0]; end; end; end.
unit PhpCodeDesigner; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, TypInfo, dcsystem, dcparser, dcstring, dccommon, dcmemo, dccdes, dcdsgnstuff; type TPhpCodeDesigner = class(TJSCodeDesigner) protected function GetClassEnd: Integer; function SkipToToken(inToken: string): Boolean; public function CreateEventName(const EventName: string; TypeData: PTypeData; OnlyType: boolean): string; override; function GetMethodStart(const pt: TPoint): TPoint; override; function GetSyntaxParserClass : TSimpleParserClass; override; function TypeToString(TypeCode: integer): string; override; procedure CreateMethod(const AMethodName: string; TypeData: PTypeData); override; procedure GetMethodTemplate(const AMethodName: string; TypeData: PTypeData; S: TStrings); override; procedure ValidateObjectEventProperties(inObject: TObject); procedure ValidateEventProperties(inContainer: TWinControl); end; implementation uses TpControls; { TPhpCodeDesigner } function TPhpCodeDesigner.GetSyntaxParserClass: TSimpleParserClass; begin Result := inherited GetSyntaxParserClass; end; function TPhpCodeDesigner.SkipToToken(inToken: string): Boolean; begin with GetParser do begin while not ParserEof and (TokenString <> inToken) do NextToken; Result := Token <> tokEof; end; end; function TPhpCodeDesigner.GetClassEnd: Integer; var c: Integer; // tname: string; begin Result := -1; { if ModuleOwner = nil then exit; tname := BuildClassName(ModuleOwner.Name); } with GetParser do if SkipToToken('class') then if SkipToToken('{') then begin c := 1; while not ParserEof and (c > 0) do begin NextToken; if IsTokenChar('{') then Inc(c) else if IsTokenChar('}') then Dec(c); end; if not ParserEof then Result := LinePos end; end; function TPhpCodeDesigner.CreateEventName(const EventName: string; TypeData: PTypeData; OnlyType: boolean): string; begin Result := 'function ' + EventName + '(&$inSender)'; end; procedure TPhpCodeDesigner.GetMethodTemplate(const AMethodName: string; TypeData: PTypeData; S: TStrings); begin with S do begin Add(' ' + CreateEventName(AMethodName, TypeData, false)); Add(' ' + '{'); Add(' ' + ''); Add(' ' + '}'); // Add(' ' + ''); end; //inherited; end; procedure TPhpCodeDesigner.CreateMethod(const AMethodName: string; TypeData: PTypeData); var mtemplate: TStringList; i, l: integer; begin with Strings do begin BeginUpdate; try //l := Count - 1; l := GetClassEnd; if (l < 0) then l := 0; mtemplate := TStringList.Create; try GetMethodTemplate(AMethodName, TypeData, mtemplate); for i := 0 to Pred(mtemplate.Count) do Insert(l + i, mtemplate[i]); //Insert(Count - 1, ''); finally mtemplate.Free; end; finally EndUpdate; end; ShowSource(4, l + 2); end; end; function TPhpCodeDesigner.TypeToString(TypeCode: integer): string; begin Result := ''; end; function TPhpCodeDesigner.GetMethodStart(const pt: TPoint): TPoint; begin Result := Point(4, pt.y + 2); end; procedure TPhpCodeDesigner.ValidateObjectEventProperties(inObject: TObject); var c, i: Integer; propList: PPropList; m: string; begin c := GetPropList(inObject, propList); for i := 0 to Pred(c) do if PropertyIsPhpEvent(propList[i].Name) then begin m := GetStrProp(inObject, propList[i]); if (m <> '') and (not MethodExists(m)) then SetStrProp(inObject, propList[i], ''); end; end; procedure TPhpCodeDesigner.ValidateEventProperties(inContainer: TWinControl); var i: Integer; begin for i := 0 to Pred(inContainer.ComponentCount) do begin ValidateObjectEventProperties(inContainer.Components[i]); if inContainer.Components[i] is TWinControl then ValidateEventProperties(TWinControl(inContainer.Components[i])); end; { for i := 0 to Pred(inContainer.ControlCount) do begin ValidateObjectEventProperties(inContainer.Controls[i]); if inContainer.Controls[i] is TWinControl then ValidateEventProperties(TWinControl(inContainer.Controls[i])); end; } end; end.
unit Strings; {----} interface {----} uses CRT; type StringType = array [0..255] of Char; var StringResult : StringType; ByteResult : Byte; Pos : Integer; procedure StringLength (var AString : StringType); procedure ClearStringResult; procedure StringWriteLn (var AString : StringType); procedure StringReadLn; {----} implementation {----} procedure StringLength (var AString : StringType); begin ByteResult := 255; while ((not (ByteResult < 0)) and (AString [ByteResult] = Chr (0))) do begin Dec (ByteResult); end; end; procedure ClearStringResult; begin for Pos := 0 to 255 do begin StringResult [Pos] := Chr (0); end; end; procedure StringWriteLn (var AString : StringType); begin StringLength (AString); for Pos := 0 to ByteResult do begin Write (AString [Pos]); end; Write (Chr (13)); end; procedure StringReadLn; begin Pos := 0; ClearStringResult; repeat StringResult [Pos] := ReadKey; if (not (StringResult [Pos] = Chr (13))) then begin Write (StringResult [Pos]); Inc (Pos); end; until (StringResult [Pos] = Chr (13)); { Write (Chr (13));} WriteLn; end; begin end.
UNIT NewDelay; { Improved Delay routine For TP 6.0 and TP/BP 7.00/7.01 (real and protected mode). Version 1.00, released 29-09-97 (Note: The code itself has NOT changed since version 0.96! I just thought it was about time to finish beta stage and make a version 1.00) Please send any BUG REPORTS, COMMENTS and other FEEDBACK to me: heckenb(at)mi.uni-erlangen.de or fjf(at)gmx.de Especially the accuracy probably still is to be improved a little. If someone wants to do that (using a high-precision timer - NOT the Bios system timer, or the GetTime procedure), please send me the results. The code is uncommented (as you will see yourself...), and I admit, some parts of it are probably not so easy to understand. If someone urgently needs some comments, I might write some. Copyright: Partially based on the Delay routine in the unit Crt, Copyright (C) 1988,91 Borland International. Any changes made are copyright 1996 by Frank Heckenbach; free for non-commercial use, only for people not affiliated with Microsoft in any way. You may change the code below for your own use (e.g. remove the "IFDEF"ed parts you don't need), but don't give away modified versions of it. If you think you made an improvement, please contact me at the address shown above. You may not remove or modify these comments from the beginning up to "***"! Disclaimer: This code is provided "as is", and comes WITHOUT ANY WARRANTY, expressed or implied; without even the implied warranty of fitness for a particular purpose. I shall not be liable for any damages, whether direct, indirect, special, incidental or consequential arising from the use of the software or from the inability to use the software or from a failure of the software to operate in a manner desired by the user. In short: Use this code totally at your own risk! Features: * DelayCnt changed from Word to Longint to avoid overflow on a 200+ MHz CPU. * No init code necessary (unlike Crt) - at least for BP 7.0, if you don't use runtime patching (see below). Delay is initialized when first called. This saves about 1/18s and some bytes in programs that don't use Delay. Thus, the first delay will be a bit inaccurate (+/- 1/36.4 s). You can call Delay(0) at the start of the program to initialize Delay and avoid this inaccuracy. * Tries to avoid busy waiting by giving up timeslices via INT $2F,$1680 when running on a 80386 or above in a multitasking environment (as Windoze or Linux). E.g., in Linux, the CPU usage during a Delay dropped from about 90% with the old Delay code to under 0.1% with this replacement. In such an environment, of course, the delay may get inaccurate, especially longer than intended (with the old code as well as with this replacement). Credits to Walter Koch (walterk@ddorf.rhein-ruhr.de) for pointing me to this interrupt function. * Can patch Crt at runtime and prevent a runtime error caused by Crt's init code on a fast CPU. * Tested under NWDOS 7.0, Windoze 3.1 and the Linux DosEmu by the author. Dan Dumbrill <73170.1423@CompuServe.COM> says: "... on a PPro200 with Windows 95 ... the code seems to work fine with both protected and real modes." Michael Hermann <hermann@fmi.uni-passau.de> says: "I tried the fix, and it works also under OS/2 and Win95." Further feedback about the behaviour under OS/2 and Win95 is wanted. History: 0.90 06-10-96 First release 0.91 20-10-96 Minor improvement in Delay 0.92 16-11-96 TP 6.0 compatibility added 0.93 18-11-96 Crt patching added 0.94 27-11-96 Added comments confirming OS/2 and Win95 compatibility 0.95 00-00-00 Skipped this version number! :-) 0.96 21-01-97 Added comments about using Make to modify Crt 1.00 29-09-97 Added comments about Linux (DosEmu) compatibility Officially ended beta stage Bug (possibly): Ralf Brown's interrupt list says about INT $2F,$1680: 'When called very often without intermediate screen output under WIN 3+, the VM will go into an idle-state and will not receive the next slice before 8 seconds. This time can be changed in SYSTEM.INI through "IdleVMWakeUpTime=<seconds>". Setting to zero results in a long wait.' However, I could not see this effect, so my routine does nothing to prevent this problem. If you encounter this problem, please contact me (address: see above). *** Using this unit together with Crt Choose one of the three solutions described below: FIRST solution + Easiest - Requires changing all your units and programs - Does not fix the 200 MHz problem Use NewDelay AFTER Crt in the uses clause ("Uses ...,Crt,NewDelay,...") of the main program and of ALL units that use Crt, otherwise Crt's Delay routine will be used instead of the new one. On a 200+ MHz CPU, Crt's init code related to Delay will produce a runtime error. Using this unit in this way won't help against that. SECOND solution + "Clean" solution + No programs or other units have to be modified + Other units don't even have to be recompiled - only for BP 7.0 - Needs RTL source - Most work Modify Crt and rebuild your RTL. (Even if you are not afraid of the 200 MHz problem, it might be a good idea to change Crt, if you have the RTL source.) This is done as follows (Note: since Crt is copyrighted by Borland, I cannot distribute a modified version of it, nor will you be allowed to give away your modified version.): Preparations: * Read all of the following steps before you start. If there's anything you don't understand, don't start! * Of course you will make BACKUPS of any files you change during the following process (BEFORE you change anything)! * You must have BP7.0 with the RTL sources. If you only have TP 6.0 or TP 7.0, you can't use this solution. * Did I mention BACKUPS already? * You should have a bit more than basic experience working with BP, or have someone experienced to assist you in case of unexpected problems. * If you lose some important data without having made BACKUPS, you'll get some problems - so make BACKUPS NOW! Main part: * Remove all delay related parts from CRT.ASM (in the RTL\CRT directory). (Search for the string "delay" in the file, and keep your eyes open! Note: In the procedure "Initialize" it's the part from the line "MOV ES,Seg0040" to the line "MOV DelayCnt,AX", inclusively.) * Insert the implementation part of this unit - up to, but not including the line with "$IFDEF PATCHCRT" - into the implementation of CRT.PAS (same directory), and remove the line "procedure Delay; external;" from it. Don't change anything in the interface part of CRT.PAS. * Instead of the next two or three steps, you can change into the RTL directory and call "make \bp\rtl\bin\tpu\crt.tpu" and "make \bp\rtl\bin\tpu\crt.tpp" or simply "make", respectively. However, this may not work if your directories aren't set up exactly as the makefile expects them to. * Assemble CRT.ASM (with -d_DPMI_ to CRT.OBP for protected mode, and without this switch to CRT.OBJ for real mode) with TASM. * Compile CRT.PAS to CRT.TPU and CRT.TPP with BPC. * Update CRT.TPU and CRT.TPP in TURBO.TPL and TPP.TPL, respectively, with TPUMOVER (or, alternatively: remove them from TURBO/TPP.TPL and include the path to either CRT.PAS or CRT.TP? into your unit directories, and in the former case also the path to CRT.OB? into your object directories). * After modifying Crt this way, you don't have to use NewDelay in your programs, of course. THIRD solution + Easy + No RTL source needed + Only the program - no other units - has to be modified and recompiled - Kind of a workaround - Not for protected mode This method patches Crt at runtime, i.e. the code in the Crt unit is modified whenever a program compiled with this unit is started. However, Crt's Delay procedure is not really fixed, just "redirected" to this unit's Delay procedure. Therefore, two versions of Delay will exist in the executable file, making it bigger than actually necessary. Additionally, an interrupt handler is installed to trap the "division by zero" error caused by Crt's init code. This works only for real mode. However, Windoze does not have Crt at all (and WinCrt does not have Delay), and protected mode is only available with BP 7.0 which comes with the RTL source, so you can use the second solution in this case. It should be obvious that installing a (temporary) interrupt handler is also not a very "clean" solution, and makes the executable bigger than necessary, but anyway it works. How to do it: * Define the symbol PATCHCRT in this unit, i.e. remove the # in the following line: } {$DEFINE PATCHCRT} { * Use NewDelay IMMEDIATELY BEFORE Crt, and before any units that use Crt in the uses clause of the main program ("Uses NewDelay,Crt...") * Insert the following line at the start of the main program: PatchCrt(Crt.Delay); } {$IFDEF WINDOWS} This unit is not for Windoze! {$ENDIF} INTERFACE {$IFDEF PATCHCRT} USES {$IFDEF WINDOWS}WinProcs{$ELSE}Dos{$ENDIF}; TYPE TCrtDelay=PROCEDURE(ms:Word); PROCEDURE PatchCrt(CrtDelay:TCrtDelay); {$ENDIF} {$IFDEF VER60} CONST Seg0040:Word=$40; Test8086:Byte=0; {Will be set to 2 if processor is 80386 or above} {$ENDIF} PROCEDURE Delay(ms:Word); IMPLEMENTATION CONST TimeSlice=100; {Threshold (in ms), above which Delay tries to give up time slices. Can be changed.} PROCEDURE DelayLoop; NEAR; ASSEMBLER; {Internal!} ASM @1:SUB AX,1 SBB DX,0 JC @2 CMP BL,ES:[DI] JE @1 @2: END; PROCEDURE Delay(ms:Word); ASSEMBLER; TYPE LongRec=RECORD Lo,Hi:Word END; CONST DelayCnt:Longint=0; {0 means unitialized} CONST op32=$66; {Prefix for 32bit operations} ASM MOV ES,Seg0040 MOV CX,ms MOV SI,$6C MOV AX,DelayCnt.LongRec.Lo OR AX,DelayCnt.LongRec.Hi JNE @2 MOV DI,SI MOV BL,ES:[DI] @1:CMP BL,ES:[DI] JE @1 MOV BL,ES:[DI] MOV AX,-28 CWD CALL DelayLoop NOT AX NOT DX MOV BX,AX MOV AX,DX XOR DX,DX MOV CX,55 DIV CX MOV DelayCnt.LongRec.Hi,AX MOV AX,BX DIV CX MOV DelayCnt.LongRec.Lo,AX MOV CX,ms SUB CX,83 JBE @x @2:JCXZ @x XOR DI,DI MOV BL,ES:[DI] CMP Test8086,2 JNB @4 @3:XOR SI,SI @4:MOV BH,ES:[SI] @5:MOV AX,DelayCnt.LongRec.Lo MOV DX,DelayCnt.LongRec.Hi CALL DelayLoop CMP BH,ES:[SI] JNE @7 @6:LOOP @5 JMP @x @7:CMP CX,TimeSlice JB @6 DB op32;MOV DX,ES:[SI] @8:MOV AX,$1680 INT $2F OR AL,AL JNZ @3 DB op32;MOV AX,DX DB op32;MOV DX,ES:[SI] DB op32;SUB AX,DX JBE @9 DB op32;MOV AX,DX JMP @a @9:DB op32;NEG AX @a:DB op32;CMP AX,$4A7;DW 0 {CMP EAX,$10000 DIV 55} JA @x PUSH DX PUSH CX MOV CX,55 MUL CX POP CX POP DX SUB CX,AX JBE @x CMP CX,TimeSlice JNB @8 JMP @3 @x: END; {$IFDEF PATCHCRT} PROCEDURE Patch(OldProc,NewProc:Pointer); {General patch procedure. Patch writes a far jump to NewProc at the beginning of OldProc, thus directing all calls to OldProc to NewProc. OldProc and NewProc must both be pointers to far procedures/functions with the same number, order and type of parameters and the same return type (if functions). If they are different, no immediate error is generated, but most likely the program will crash when OldProc is called. Should also work with procedures/functions in overlaid units.} TYPE TFarJmp=RECORD OpCode:Byte; Operand:Pointer END; BEGIN {Get a writeable pointer to OldProc} {$IFDEF DPMI} OldProc:=Ptr(Seg(OldProc^)+SelectorInc,Ofs(OldProc^)); {$ENDIF} {$IFDEF WINDOWS} OldProc:=Ptr(AllocCStoDSAlias(Seg(OldProc^)),Ofs(OldProc^)); {$ENDIF} WITH TFarJmp(OldProc^) DO BEGIN OpCode:=$EA; {JMP FAR PTR} Operand:=NewProc END; {$IFDEF WINDOWS} FreeSelector(Seg(OldProc^)) {$ENDIF} END; {$IFDEF MSDOS} CONST OldInt0P:Pointer=NIL; VAR OldInt0:PROCEDURE(Flags:Word) ABSOLUTE OldInt0P; {"CONST OldInt0:PROCEDURE(Flags:Word)=NIL" is not possible in TP 6.0!} {$ENDIF} PROCEDURE PatchCrt(CrtDelay:TCrtDelay); BEGIN Patch(@CrtDelay,@Delay); {$IFDEF MSDOS} IF @OldInt0<>NIL THEN SetIntVec(0,@OldInt0) {No init bug has occurred!} {$ENDIF} END; {$IFDEF MSDOS} PROCEDURE NewInt0(Flags,CS,IP,AX,BX,CX,DX,SI,DI,DS,ES,BP:Word); INTERRUPT; BEGIN IF MemW[CS:IP]=$F1F7 {DIV CX} {Not a foolproof check, but should be sufficient, since NewDelay should be used IMMEDIATELY before Crt} THEN BEGIN Writeln('Crt init bug trapped!'); SetIntVec(0,@OldInt0); @OldInt0:=NIL; DX:=CX-1 END ELSE OldInt0(Flags) END; BEGIN GetIntVec(0,@OldInt0); SetIntVec(0,@NewInt0); {$ENDIF} {$ENDIF} {$IFDEF VER60} BEGIN ASM {Check for 80386} PUSHF POP AX OR AH,$F0 PUSH AX POPF PUSHF POP AX AND AH,$F0 JE @1 MOV Test8086,2 @1: END {$IFDEF PATCHCRT} {$IFDEF MSDOS} END {$ENDIF} {$ENDIF} {$ENDIF} END. 
unit UDEmbeddedFields; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpeEmbeddedFieldsDlg = class(TForm) pnlEmbeddedFields: TPanel; lblNames: TLabel; lblFieldName: TLabel; lblFieldType: TLabel; lblTextStart: TLabel; lblCount: TLabel; lbNumbers: TListBox; editFieldName: TEdit; editFieldType: TEdit; editTextStart: TEdit; btnBorder: TButton; btnFormat: TButton; editCount: TEdit; btnOk: TButton; btnClear: TButton; btnInsert: TButton; btnDelete: TButton; Label1: TLabel; editFieldObjectType: TEdit; lblTextEnd: TLabel; editTextEnd: TEdit; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure btnBorderClick(Sender: TObject); procedure btnFormatClick(Sender: TObject); procedure btnInsertClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure InitializeControls(OnOff: boolean); procedure UpdateEmbeddedFields; private { Private declarations } public { Public declarations } Cr : TCrpe; FIndex : integer; CursorPos : integer; end; var CrpeEmbeddedFieldsDlg: TCrpeEmbeddedFieldsDlg; bEmbeddedFields : boolean; implementation {$R *.DFM} uses TypInfo, UCrpeUtl, UDBorder, UDFormat, UDFieldSelect, UCrpeClasses; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); btnOk.Tag := 1; btnInsert.Tag := 1; FIndex := -1; bEmbeddedFields := True; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.FormShow(Sender: TObject); begin UpdateEmbeddedFields; end; {------------------------------------------------------------------------------} { UpdateTextObjects } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.UpdateEmbeddedFields; var OnOff : boolean; i : integer; begin FIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then begin OnOff := False; btnInsert.Enabled := False; end else begin OnOff := (Cr.TextObjects.Item.EmbeddedFields.Count > 0); btnInsert.Enabled := True; {Get EmbeddedFields Index} if OnOff then begin if Cr.TextObjects.Item.EmbeddedFields.ItemIndex > -1 then FIndex := Cr.TextObjects.Item.EmbeddedFields.ItemIndex else FIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff then begin {Fill Numbers ListBox} for i := 0 to Cr.TextObjects.Item.EmbeddedFields.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.TextObjects.Item.EmbeddedFields.Count); lbNumbers.ItemIndex := FIndex; lbNumbersClick(Self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TMemo then begin TMemo(Components[i]).Clear; TMemo(Components[i]).Color := ColorState(OnOff); TMemo(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.lbNumbersClick(Sender: TObject); begin FIndex := lbNumbers.ItemIndex; editFieldName.Text := Cr.TextObjects.Item.EmbeddedFields[FIndex].FieldName; editFieldObjectType.Text := GetEnumName(TypeInfo(TCrFieldObjectType), Ord(Cr.TextObjects.Item.EmbeddedFields.Item.FieldObjectType)); editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType), Ord(Cr.TextObjects.Item.EmbeddedFields.Item.FieldType)); editTextStart.Text := IntToStr(Cr.TextObjects.Item.EmbeddedFields.Item.TextStart); editTextEnd.Text := IntToStr(Cr.TextObjects.Item.EmbeddedFields.Item.TextEnd); end; {------------------------------------------------------------------------------} { btnBorderClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.btnBorderClick(Sender: TObject); begin CrpeBorderDlg := TCrpeBorderDlg.Create(Application); CrpeBorderDlg.Border := Cr.TextObjects.Item.EmbeddedFields.Item.Border; CrpeBorderDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnFormatClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.btnFormatClick(Sender: TObject); begin CrpeFormatDlg := TCrpeFormatDlg.Create(Application); CrpeFormatDlg.Format := Cr.TextObjects.Item.EmbeddedFields.Item.Format; CrpeFormatDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnInsertClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.btnInsertClick(Sender: TObject); begin CrpeFieldSelectDlg := TCrpeFieldSelectDlg.Create(Application); CrpeFieldSelectDlg.Cr := Cr; CrpeFieldSelectDlg.EFSelect := True; CrpeFieldSelectDlg.ShowModal; if CrpeFieldSelectDlg.ModalResult = mrOk then begin Cr.TextObjects.Item.EmbeddedFields.Insert(Cr.Tables.Item.Fields.Item.FullName, CursorPos); end; UpdateEmbeddedFields; end; {------------------------------------------------------------------------------} { btnDeleteClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.btnDeleteClick(Sender: TObject); begin Cr.TextObjects.Item.EmbeddedFields.Delete(FIndex); UpdateEmbeddedFields; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.btnClearClick(Sender: TObject); begin Cr.TextObjects.Item.EmbeddedFields.Clear; UpdateEmbeddedFields; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeEmbeddedFieldsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bEmbeddedFields := False; Release; end; end.
namespace RemObjects.Elements.System; uses java.util, java.util.concurrent.atomic; type ParallelLoopState = public class private public property IsStopped: Boolean read private write; method &Break; begin if not IsStopped then IsStopped := True; end; end; &Parallel = static public class public class method &For(fromInclusive: Integer; toExclusive: Integer; body: Action2<Integer,ParallelLoopState>); begin var lthreadcnt := Runtime.getRuntime().availableProcessors(); var lcurrTasks := new AtomicInteger(); var levent := new Object; var ls:= new ParallelLoopState(); for m: Integer := fromInclusive to toExclusive - 1 do begin while lcurrTasks.get >= lthreadcnt do begin if ls.IsStopped then Break; locking levent do levent.wait; end; if ls.IsStopped then Break; lcurrTasks.incrementAndGet; var temp := m; new Task(-> begin body(temp, ls); lcurrTasks.decrementAndGet; locking levent do levent.notifyAll; end).Start; end; while lcurrTasks.get > 0 do begin locking levent do levent.wait; end; end; class method &For(fromInclusive: Int64; toExclusive: Int64; body: Action2<Int64,ParallelLoopState>); begin var lthreadcnt := Runtime.getRuntime().availableProcessors(); var lcurrTasks := new AtomicInteger(); var levent := new Object; var ls:= new ParallelLoopState(); for m: Int64 := fromInclusive to toExclusive - 1 do begin while lcurrTasks.get >= lthreadcnt do begin if ls.IsStopped then Break; locking levent do levent.wait; end; if ls.IsStopped then Break; lcurrTasks.incrementAndGet; var temp := m; new Task(-> begin body(temp, ls); lcurrTasks.decrementAndGet; locking levent do levent.notifyAll; end).Start; end; while lcurrTasks.get > 0 do begin locking levent do levent.wait; end; end; class method ForEach<T>(source: Iterable<T>; body: Action3<T,ParallelLoopState, Int64>); begin var lthreadcnt := Runtime.getRuntime().availableProcessors(); var lcurrTasks := new AtomicInteger(); var levent := new Object; var ls:= new ParallelLoopState(); for m in source index n do begin while lcurrTasks.get >= lthreadcnt do begin if ls.IsStopped then Break; locking levent do levent.wait; end; if ls.IsStopped then Break; lcurrTasks.incrementAndGet; var temp := m; var tempi := n; new Task(-> begin body(temp, ls, tempi); lcurrTasks.decrementAndGet; locking levent do levent.notifyAll; end).Start; end; while lcurrTasks.get > 0 do begin locking levent do levent.wait; end; end; end; end.
unit uTSBaseClass; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs; type TSBaseClassClass = class Of TSBaseClass; TComponentMode = (csNone, csCreated, csLoaded); TSBaseClass = class(TComponent) private FMode: TComponentMode; published property Mode: TComponentMode read FMode write FMode; property State: TComponentMode read FMode write FMode; public constructor Create(aOwner : TComponent); override; function ExportToXML: WideString; dynamic; end; implementation constructor TSBaseClass.Create(aOwner : TComponent); begin inherited Create(aOwner); State := csNone; end; function TSBaseClass.ExportToXML: WideString; begin Result := ''; ShowMessage('Export to XML'); end; end.
unit UCidadeVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,UPaisVO, UEstadoVO; type [TEntity] [TTable('Cidade')] TCidadeVO = class(TGenericVO) private FIdCidade: Integer; FnomeCidade: String; FIdEstado : Integer; FIdPais : Integer; // Atributos Transientes FNomeEstado : String; // ---------------------- public PaisVO: TPAISVO; EstadoVO : TESTADOVO; [TId('idCidade')] [TGeneratedValue(sAuto)] property idCidade: Integer read FIdCidade write FIdCidade; [TColumn('nome','Cidade',250,[ldGrid], False)] property NomeCidade: String read FnomeCidade write FnomeCidade; [TColumn('idEstado','idEstado',0,[ldLookup,ldComboBox], False)] property idEstado: integer read FIdEstado write FIdEstado; [TColumn('idPais','idPais',0,[ldLookup,ldComboBox], False)] property idPais: integer read FIdPais write FIdPais; // Atributos Transientes [TColumn('NOMEESTADO','Estado',0,[ldGrid], True, 'Estado', 'idEstado', 'idEstado')] property NomeEstado: string read FNomeEstado write FNomeEstado; // ---------------------- function ValidarCamposObrigatorios:boolean; end; implementation { TCidadeVO } function TCidadeVO.ValidarCamposObrigatorios: boolean; begin Result := true; if (Self.FnomeCidade = '') then begin raise Exception.Create('O campo Nome é obrigatório!'); Result := false; end end; end.
unit uEstoqueDAOClient; interface uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Estoque, DBXJSONReflect; type TEstoqueDAOClient = class(TDSAdminClient) private FListCommand: TDBXCommand; FInsertCommand: TDBXCommand; FUpdateCommand: TDBXCommand; FDeleteCommand: TDBXCommand; FRelatorioEstoqueCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function List: TDBXReader; function Insert(Estoque: TEstoque): Boolean; function Update(Estoque: TEstoque): Boolean; function Delete(Estoque: TEstoque): Boolean; function RelatorioEstoque(Estoque: Integer): TDBXReader; end; implementation function TEstoqueDAOClient.List: TDBXReader; begin if FListCommand = nil then begin FListCommand := FDBXConnection.CreateCommand; FListCommand.CommandType := TDBXCommandTypes.DSServerMethod; FListCommand.Text := 'TEstoqueDAO.List'; FListCommand.Prepare; end; FListCommand.ExecuteUpdate; Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TEstoqueDAOClient.Insert(Estoque: TEstoque): Boolean; begin if FInsertCommand = nil then begin FInsertCommand := FDBXConnection.CreateCommand; FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsertCommand.Text := 'TEstoqueDAO.Insert'; FInsertCommand.Prepare; end; if not Assigned(Estoque) then FInsertCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Estoque), True); if FInstanceOwner then Estoque.Free finally FreeAndNil(FMarshal) end end; FInsertCommand.ExecuteUpdate; Result := FInsertCommand.Parameters[1].Value.GetBoolean; end; function TEstoqueDAOClient.Update(Estoque: TEstoque): Boolean; begin if FUpdateCommand = nil then begin FUpdateCommand := FDBXConnection.CreateCommand; FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod; FUpdateCommand.Text := 'TEstoqueDAO.Update'; FUpdateCommand.Prepare; end; if not Assigned(Estoque) then FUpdateCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Estoque), True); if FInstanceOwner then Estoque.Free finally FreeAndNil(FMarshal) end end; FUpdateCommand.ExecuteUpdate; Result := FUpdateCommand.Parameters[1].Value.GetBoolean; end; function TEstoqueDAOClient.Delete(Estoque: TEstoque): Boolean; begin if FDeleteCommand = nil then begin FDeleteCommand := FDBXConnection.CreateCommand; FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDeleteCommand.Text := 'TEstoqueDAO.Delete'; FDeleteCommand.Prepare; end; if not Assigned(Estoque) then FDeleteCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Estoque), True); if FInstanceOwner then Estoque.Free finally FreeAndNil(FMarshal) end end; FDeleteCommand.ExecuteUpdate; Result := FDeleteCommand.Parameters[1].Value.GetBoolean; end; function TEstoqueDAOClient.RelatorioEstoque(Estoque: Integer): TDBXReader; begin if FRelatorioEstoqueCommand = nil then begin FRelatorioEstoqueCommand := FDBXConnection.CreateCommand; FRelatorioEstoqueCommand.CommandType := TDBXCommandTypes.DSServerMethod; FRelatorioEstoqueCommand.Text := 'TEstoqueDAO.RelatorioEstoque'; FRelatorioEstoqueCommand.Prepare; end; FRelatorioEstoqueCommand.Parameters[0].Value.SetInt32(Estoque); FRelatorioEstoqueCommand.ExecuteUpdate; Result := FRelatorioEstoqueCommand.Parameters[1].Value.GetDBXReader(FInstanceOwner); end; constructor TEstoqueDAOClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TEstoqueDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TEstoqueDAOClient.Destroy; begin FreeAndNil(FListCommand); FreeAndNil(FInsertCommand); FreeAndNil(FUpdateCommand); FreeAndNil(FDeleteCommand); FreeAndNil(FRelatorioEstoqueCommand); inherited; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmMDIBackground Purpose : To allow an image to be placed with in the workspace area of an MDI Form. Background colors are also available. Date : 04-24-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmMDIBackground; interface {$I CompilerDefines.INC} uses Windows, Messages, Classes, Forms, graphics; type TrmBMPDisplayStyle = (dsTiled, dsStretched, dsCentered, dsNone) ; TrmMDIBackground = class(TComponent) private OldWndProc: TFarProc; NewWndProc: Pointer; OldMDIWndProc: TFarProc; NewMDIWndProc: Pointer; fBitmap: TBitmap; fstyle: TrmBMPDisplayStyle; fColor: TColor; fBuffer: TBitmap; fLastRect: TRect; procedure SetBitmap(const Value: tBitmap) ; procedure SetDStyle(const Value: TrmBMPDisplayStyle) ; procedure SetMDIColor(const Value: TColor) ; { Private declarations } protected { Protected declarations } procedure HookWndProc(var AMsg: TMessage) ; procedure HookWnd; procedure UnHookWnd; procedure HookMDIWndProc(var AMsg: TMessage) ; procedure HookMDIWin; procedure UnhookMDIWin; procedure PaintImage; public { Public declarations } constructor create(AOwner: TComponent) ; override; destructor destroy; override; published { Published declarations } property Bitmap: tBitmap read fBitmap write SetBitmap; property DisplayStyle: TrmBMPDisplayStyle read fstyle write SetDStyle default dsNone; property Color: TColor read fColor write SetMDIColor default clappWorkspace; end; implementation uses rmGlobalComponentHook; { TrmMDIBackground } constructor TrmMDIBackground.create(AOwner: TComponent) ; begin inherited; NewWndProc := nil; OldWndProc := nil; OldMDIWndProc := nil; NewMDIWndProc := nil; fBitmap := tBitmap.create; fbuffer := tbitmap.create; fColor := clAppWorkSpace; fstyle := dsNone; fLastRect := rect(0, 0, 0, 0) ; HookWnd; end; destructor TrmMDIBackground.destroy; begin UnHookWnd; fBitmap.free; fbuffer.free; inherited; end; procedure TrmMDIBackground.HookMDIWin; begin if csdesigning in componentstate then exit; if not assigned(NewMDIWndProc) then begin OldMDIWndProc := TFarProc(GetWindowLong(TForm(Owner) .ClientHandle, GWL_WNDPROC) ) ; {$ifdef D6_or_higher} NewMDIWndProc := Classes.MakeObjectInstance(HookMDIWndProc) ; {$else} NewMDIWndProc := MakeObjectInstance(HookMDIWndProc) ; {$endif} SetWindowLong(TForm(Owner) .ClientHandle, GWL_WNDPROC, LongInt(NewMDIWndProc) ) ; end; end; procedure TrmMDIBackground.HookMDIWndProc(var AMsg: TMessage) ; begin with AMsg do begin Result := CallWindowProc(OldMDIWndProc, TForm(Owner) .ClientHandle, Msg, wParam, lParam) ; if (msg = WM_NCPaint) or (msg = wm_Paint) then PaintImage; end; end; procedure TrmMDIBackground.HookWnd; begin if csdesigning in componentstate then exit; if TForm(Owner) .formstyle <> fsMDIForm then exit; if not assigned(NewWndProc) then begin OldWndProc := TFarProc(GetWindowLong(TForm(Owner) .handle, GWL_WNDPROC) ) ; {$ifdef D6_or_higher} NewWndProc := Classes.MakeObjectInstance(HookWndProc) ; {$else} NewWndProc := MakeObjectInstance(HookWndProc) ; {$endif} SetWindowLong(TForm(Owner) .handle, GWL_WNDPROC, LongInt(NewWndProc) ) ; PushOldProc(TForm(Owner) , OldWndProc) ; HookMDIWin; end; end; procedure TrmMDIBackground.HookWndProc(var AMsg: TMessage) ; begin case AMsg.msg of WM_DESTROY: begin AMsg.Result := CallWindowProc(OldWndProc, Tform(Owner) .handle, AMsg.Msg, AMsg.wParam, AMsg.lParam) ; UnHookWnd; exit; end; wm_EraseBKGND: begin aMsg.Result := 1; exit; end; end; AMsg.Result := CallWindowProc(OldWndProc, Tform(Owner) .handle, AMsg.Msg, AMsg.wParam, AMsg.lParam) ; case aMsg.Msg of WM_PAINT, // WM_ERASEBKGND, WM_NCPaint: PaintImage; end; end; procedure TrmMDIBackground.PaintImage; var DC: HDC; Brush: HBrush; cx, cy: integer; wRect: TRect; x, y: integer; begin if csdesigning in componentstate then exit; if TForm(Owner) .FormStyle <> fsMDIForm then exit; GetWindowRect(TForm(Owner) .ClientHandle, wRect) ; DC := GetDC(TForm(Owner) .clienthandle) ; try case fstyle of dsTiled, dsStretched, dsCentered: begin case fStyle of dsTiled: begin cx := (wRect.right - wRect.left) ; cy := (wRect.bottom - wRect.top) ; y := 0; while y < cy do begin x := 0; while x < cx do begin bitBlt(DC, x, y, fBitmap.width, fBitmap.height, fBitmap.canvas.Handle, 0, 0, srccopy) ; inc(x, fBitmap.width) ; end; inc(y, fBitmap.Height) ; end; end; dsStretched: begin cx := (wRect.right - wRect.left) ; cy := (wRect.bottom - wRect.top) ; StretchBlt(DC, 0, 0, cx, cy, fBitmap.Canvas.Handle, 0, 0, fBitmap.width, fBitmap.height, srccopy) ; end; dsCentered: begin fBuffer.width := wRect.right - wRect.left; fBuffer.height := wRect.bottom - wRect.top; Brush := CreateSolidBrush(ColorToRGB(fcolor) ) ; try FillRect(fBuffer.canvas.handle, rect(0, 0, fBuffer.width, fBuffer.height) , brush) ; finally DeleteObject(Brush) ; end; cx := (fBuffer.width div 2) - (fBitmap.width div 2) ; cy := (fBuffer.height div 2) - (fbitmap.height div 2) ; bitBlt(fBuffer.Canvas.handle, cx, cy, fBitmap.width, fBitmap.height, fBitmap.Canvas.Handle, 0, 0, srccopy) ; bitBlt(DC, 0, 0, fBuffer.width, fBuffer.height, fBuffer.Canvas.Handle, 0, 0, srccopy) ; end; end; end; dsNone: begin Brush := CreateSolidBrush(ColorToRGB(fcolor) ) ; try FillRect(DC, TForm(Owner) .ClientRect, brush) ; finally DeleteObject(Brush) ; end; end; end; fLastRect := wRect; finally ReleaseDC(TForm(Owner) .clienthandle, DC) ; end; end; procedure TrmMDIBackground.SetBitmap(const Value: tBitmap) ; begin fBitmap.assign(Value) ; end; procedure TrmMDIBackground.SetDStyle(const Value: TrmBMPDisplayStyle) ; begin if fstyle <> Value then begin fstyle := Value; PaintImage; end; end; procedure TrmMDIBackground.SetMDIColor(const Value: TColor) ; begin if fColor <> Value then begin fColor := Value; PaintImage; end; end; procedure TrmMDIBackground.UnhookMDIWin; begin if csdesigning in componentstate then exit; if assigned(NewMDIWndProc) then begin SetWindowLong(TForm(Owner) .ClientHandle, GWL_WNDPROC, LongInt(OldMDIWndProc) ) ; if assigned(NewMDIWndProc) then {$ifdef D6_or_higher} Classes.FreeObjectInstance(NewMDIWndProc) ; {$else} FreeObjectInstance(NewMDIWndProc) ; {$endif} NewMDIWndProc := nil; OldMDIWndProc := nil; end; end; procedure TrmMDIBackground.UnHookWnd; begin if csdesigning in componentstate then exit; if assigned(NewWndProc) then begin SetWindowLong(TForm(Owner) .handle, GWL_WNDPROC, LongInt(PopOldProc(TForm(Owner) ) ) ) ; if assigned(NewWndProc) then {$ifdef D6_or_higher} Classes.FreeObjectInstance(NewWndProc) ; {$else} FreeObjectInstance(NewWndProc) ; {$endif} NewWndProc := nil; OldWndProc := nil; end; UnHookMDIWin; end; end.
unit frmCypherInfo; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, OTFEFreeOTFE_U, OTFEFreeOTFEBase_U, SDUForms; type TfrmCypherInfo = class(TSDUForm) gbCypherDriver: TGroupBox; gbCypher: TGroupBox; edDriverDeviceName: TEdit; lblDeviceName: TLabel; lblDeviceUserModeName: TLabel; lblDeviceKernelModeName: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; edDriverDeviceUserModeName: TEdit; edDriverDeviceKernelModeName: TEdit; edDriverTitle: TEdit; edDriverVersionID: TEdit; edDriverCypherCount: TEdit; edCypherGUID: TEdit; edCypherTitle: TEdit; edCypherMode: TEdit; edCypherBlockSize: TEdit; edCypherVersionID: TEdit; pbClose: TButton; Label12: TLabel; edDriverGUID: TEdit; edCypherKeySize: TEdit; Label13: TLabel; procedure pbCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public OTFEFreeOTFEObj: TOTFEFreeOTFEBase; // These two items uniquely identify which should be shown ShowDriverName: string; ShowGUID: TGUID; end; implementation {$R *.DFM} uses SDUi18n, ComObj, // Required for GUIDToString(...) ActiveX, // Required for IsEqualGUID SDUGeneral, OTFEFreeOTFE_DriverCypherAPI, OTFEFreeOTFEDLL_U; resourcestring RS_UNABLE_LOCATE_CYPHER_DRIVER = '<Unable to locate correct cypher driver>'; RS_UNABLE_LOCATE_CYPHER = '<Unable to locate cypher>'; procedure TfrmCypherInfo.pbCloseClick(Sender: TObject); begin Close(); end; procedure TfrmCypherInfo.FormShow(Sender: TObject); var cypherDrivers: array of TFreeOTFECypherDriver; i, j: integer; currCypherDriver: TFreeOTFECypherDriver; currCypher: TFreeOTFECypher_v3; tmpString: string; begin // Blank out in case none found edDriverGUID.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edDriverDeviceName.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edDriverDeviceKernelModeName.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edDriverDeviceUserModeName.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edDriverTitle.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edDriverVersionID.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edDriverCypherCount.Text := RS_UNABLE_LOCATE_CYPHER_DRIVER; edCypherGUID.Text := RS_UNABLE_LOCATE_CYPHER; edCypherTitle.Text := RS_UNABLE_LOCATE_CYPHER; edCypherMode.Text := RS_UNABLE_LOCATE_CYPHER; edCypherVersionID.Text := RS_UNABLE_LOCATE_CYPHER; edCypherKeySize.Text := RS_UNABLE_LOCATE_CYPHER; edCypherBlockSize.Text := RS_UNABLE_LOCATE_CYPHER; if (OTFEFreeOTFEObj is TOTFEFreeOTFEDLL) then begin lblDeviceName.caption := _('Library:'); lblDeviceUserModeName.visible := FALSE; edDriverDeviceUserModeName.visible := FALSE; lblDeviceKernelModeName.visible := FALSE; edDriverDeviceKernelModeName.visible := FALSE; end; SetLength(cypherDrivers, 0); if OTFEFreeOTFEObj.GetCypherDrivers(TFreeOTFECypherDriverArray(cypherDrivers)) then begin for i:=low(cypherDrivers) to high(cypherDrivers) do begin currCypherDriver := cypherDrivers[i]; if ( (currCypherDriver.LibFNOrDevKnlMdeName = ShowDriverName) OR (currCypherDriver.DeviceUserModeName = ShowDriverName) ) then begin edDriverGUID.Text := GUIDToString(currCypherDriver.DriverGUID); if (OTFEFreeOTFEObj is TOTFEFreeOTFEDLL) then begin edDriverDeviceName.Text := currCypherDriver.LibFNOrDevKnlMdeName; end else begin edDriverDeviceName.Text := currCypherDriver.DeviceName; edDriverDeviceKernelModeName.Text := currCypherDriver.LibFNOrDevKnlMdeName; edDriverDeviceUserModeName.Text := currCypherDriver.DeviceUserModeName; end; edDriverTitle.Text := currCypherDriver.Title; edDriverVersionID.Text := OTFEFreeOTFEObj.VersionIDToStr(currCypherDriver.VersionID); edDriverCypherCount.Text := inttostr(currCypherDriver.CypherCount); for j:=low(cypherDrivers[i].Cyphers) to high(cypherDrivers[i].Cyphers) do begin currCypher := cypherDrivers[i].Cyphers[j]; if (IsEqualGUID(currCypher.CypherGUID, ShowGUID)) then begin edCypherGUID.Text := GUIDToString(currCypher.CypherGUID); edCypherTitle.Text := currCypher.Title; edCypherMode.Text := FreeOTFECypherModeTitle(currCypher.Mode); tmpString := SDUParamSubstitute(COUNT_BITS, [currCypher.KeySizeUnderlying]); if (currCypher.KeySizeUnderlying = 0) then begin tmpString := tmpString + ' '+ _('(null key only)'); end else if (currCypher.KeySizeUnderlying = -1) then begin tmpString := tmpString + ' '+ _('(arbitary keysize allowed)'); end; edCypherKeySize.Text := tmpString; tmpString := SDUParamSubstitute(COUNT_BITS, [currCypher.BlockSize]); if (currCypher.BlockSize = -1) then begin tmpString := tmpString + ' '+ _('(arbitary blocksize allowed)'); end; edCypherBlockSize.Text := tmpString; edCypherVersionID.Text := OTFEFreeOTFEObj.VersionIDToStr(currCypher.VersionID); end; end; end; end; end; end; END.
program HP_Calculator (input, output); type OperationType = ( opUnknown, opError, opValue, opQuit, opAdd, opSub, opMul, opDiv, opSign, opExp, opLn, opSin, opCos, opArcTg, op10x, opFix, opClear, opPush, opRollUp, opRollDown, opSwapXY ); ValueKind = (theNumber, theError); ValueType = record case Kind : ValueKind of theNumber : (number : real); theError : (); end; RegisterNames = (x, y, z, t); HP_Type = array[RegisterNames]of ValueType; var HP : HP_Type; OutputLeng : integer := 10; OutputPrec : integer := 3; QuitProgram : boolean; {-----------------------------------------------------------------------} { Value operations } {-----------------------------------------------------------------------} procedure ValueSetAsNumber(var value : ValueType; aNumber : real); begin { ValueSetAsNumber } value.Kind := theNumber; value.number := aNumber; end; { ValueSetAsNumber } procedure ValueSetAsError(var value : ValueType); begin {ValueSetAsError } value.Kind := theError; end; {ValueSetAsError } {-----------------------------------------------------------------------} { HP ADT operations } {-----------------------------------------------------------------------} { Fill all HP ADT by 0 } procedure HP_Create; var counter : RegisterNames; begin { HP_Create } for counter := x to t do ValueSetAsNumber(HP[counter], 0); end; { HP_Create } { Print HP ADT contents on the screen } procedure HP_Print; var counter : RegisterNames; procedure WriteValue(value : ValueType); begin { WriteValue } case value.kind of theNumber : begin if (abs(value.number) > exp((OutputLeng-OutputPrec-2) * ln(10))) or (abs(value.number) < exp(-OutputPrec * ln(10))) and (value.number <> 0) then write(value.number:OutputLeng) else write(value.number:OutputLeng:OutputPrec); end; theError : write('error':OutputLeng); end; end; { WriteValue } begin { HP_Print } writeln; writeln('x':(OutputLeng div 2), 'y':(OutputLeng+1), 'z':(OutputLeng+1), 't':(OutputLeng+1)); for counter := x to t do begin WriteValue(HP[counter]); write(' '); end; writeln; writeln; end; { HP_Print } procedure HP_Pop(var value : ValueType); var counter : RegisterNames; begin { HP_Pop } value := HP[x]; for counter := x to z do HP[counter] := HP[succ(counter)]; end; { HP_Pop } procedure HP_Push(value : ValueType); var counter : RegisterNames; begin { HP_Push } for counter := t downto y do HP[counter] := HP[pred(counter)]; HP[x] := value; end; { HP_Push } procedure HP_RollUp; var value : ValueType; begin { HP_RollUp } HP_Pop(value); HP[t] := value; end; { HP_RollUp } procedure HP_RollDown; begin { HP_RollDown } HP_Push(HP[t]); end; { HP_RollDown } procedure HP_SwapXY; { Exchange values of X and Y registers } var value : ValueType; begin { HP_SwapXY } value := HP[x]; HP[x] := HP[y]; HP[y] := value; end; { HP_SwapXY } procedure HP_Clear; { Clears the value of X register } var zero : ValueType; begin { HP_Clear } HP_pop(zero); ValueSetAsNumber(zero, 0); HP_push(zero); end; { HP_Clear } procedure HP_PerformBinaryOperation(operation : OperationType); var valueX, valueY : ValueType; begin { HP_PerformBinaryOperation } HP_Pop(valueX); HP_Pop(valueY); if (valueX.Kind = theError) or (valueY.Kind = theError) then ValueSetAsError(valueY) else case operation of opAdd : valueY.number := valueY.number + valueX.number; opSub : valueY.number := valueY.number - valueX.number; opMul : valueY.number := valueY.number * valueX.number; opDiv : if valueX.number = 0 then ValueSetAsError(valueY) else valueY.number := valueY.number / valueX.number; end; HP_Push(valueY); end; { HP_PerformBinaryOperation } procedure HP_PerformUnaryOperation(operation : OperationType); var value : ValueType; i : integer; begin { HP_PerformUnaryOperation } HP_Pop(value); if value.Kind = theNumber then case operation of opSign : value.number := -value.number; opSin : value.number := sin(value.number); opCos : value.number := cos(value.number); opArcTg: value.number := arctan(value.number); opExp : value.number := exp(value.number); op10x : value.number := exp(value.number*ln(10)); opLn : if (value.number > 0) then value.number := ln(value.number) else ValueSetAsError(value); opFix : if (value.number >= 1) and (trunc(value.number) <= (OutputLeng-3)) then OutputPrec := trunc(value.number) else ValueSetAsError(value); end; HP_Push(value); end; { HP_PerformUnaryOperation } function GetOperation(var number : real) : OperationType; { Prompts user for next command or for value of X register } { Read the string, convert all characters into upper case } { and chooses whether it is some command or real number. } const sgQuit = '#'; sgRollUp = '<'; sgHelp = '?'; sgPi = 'P'; sgAdd = '+'; sgRollDown = '>'; sgPush = ' '; sgSub = '-'; sgSwapXY = '%'; sg10x = '^'; sgMul = '*'; sgSign = '~'; sgFix = 'F'; sgDiv = '/'; sgClear = 'C'; sgE = 'E'; type StringType = packed array[1..80]of char; var operation : OperationType; InputString : StringType; procedure UpString(var str : StringType); { Convert all characters of string "str" into upper case } var i : integer; begin { UpString } for i := 1 to length(str) do if str[i] in ['a'..'z'] then str[i] := chr(ord(str[i])-ord('a')+ord('A')); end; { UpString } procedure Help; { Prints the help on the screen. } begin { Help } writeln; writeln; writeln('**************************** Help '); write (sgAdd, ' -- addition '); write (sgQuit, ' -- quit '); write ( 'Exp -- exp(x) '); writeln (sg10x, ' -- 10 at x extent '); write (sgSub, ' -- substraction '); write (sgSwapXY, ' -- swap X and Y '); write ( 'Ln -- ln(x) '); writeln (sgFix, ' -- precision '); write (sgMul, ' -- multiplication '); write (sgRollUp, ' -- roll up '); write ( 'Sin -- sin(x) '); writeln (sgE, ' -- e constant '); write (sgDiv, ' -- division '); write (sgRollDown,' -- roll down '); write ( 'Cos -- cos(x) '); writeln (sgPi, ' -- pi constant '); write (sgSign, ' -- change sign '); write (sgClear, ' -- clear '); write ( 'ArcTg -- arctg(x) '); writeln ('<RETURN> -- push'); writeln('**************************** Help '); writeln; end; { Help } begin { GetOperation } operation := opUnknown; repeat HP_Print; write('Input X or command (input ', sgHelp, ' for help)>> '); readln(InputString); readv(InputString, number, ERROR := CONTINUE); if statusv = 0 then operation := opValue else begin UpString(InputString); case InputString[1] of sgQuit : operation := opQuit; sgAdd : operation := opAdd; sgSub : operation := opSub; sgMul : operation := opMul; sgDiv : operation := opDiv; sgSign : operation := opSign; sgPush : operation := opPush; sgSwapXY : operation := opSwapXY; sgClear : if InputString[2] = 'O' then operation := opCos else operation := opClear; 'S' : operation := opSin; 'A' : operation := opArcTg; sgFix : operation := opFix; sgE : if InputString[2] = 'X' then operation := opExp else begin operation := opValue; number := exp(1); end; sgPi : begin operation := opValue; number := 4*arctan(1); end; 'L' : operation := opLn; sg10x : operation := op10x; sgRollUp : operation := opRollUp; sgRollDown : operation := opRollDown; sgHelp : Help; otherwise operation := opError; end; end; until operation <> opUnknown; GetOperation := operation; end; { GetOperation } procedure Run(var quit : boolean); var operation : OperationType; number : real; value : ValueType; begin { Run } operation := GetOperation(number); case operation of opQuit : begin writeln('Good bye!'); quit := TRUE; end; opAdd..opDiv: HP_PerformBinaryOperation(operation); opSign..opFix : HP_PerformUnaryOperation(operation); opPush : begin HP_Pop(value); HP_Push(value); HP_Push(value); end; opRollUp : HP_RollUp; opRollDown : HP_RollDown; opSwapXY : HP_SwapXY; opClear : HP_Clear; opValue : begin ValueSetAsNumber(value, number); HP_Push(value); end; opError : begin ValueSetAsError(value); HP_Push(value); end; end; end; { Run } begin { Main program } HP_Create; QuitProgram := FALSE; repeat Run(QuitProgram); until QuitProgram; end. { Main program }
unit FMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, Grijjy.Social; type TFormMain = class(TForm) ButtonLoginFacebook: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ButtonLoginFacebookClick(Sender: TObject); private { Private declarations } Social: TgoSocial; procedure SocialLoginMessageListener(const Sender: TObject; const M: TMessage); public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} uses Grijjy.FBSDK.Types; procedure TFormMain.FormCreate(Sender: TObject); begin Social := TgoSocial.Create; TMessageManager.DefaultManager.SubscribeToMessage(TgoSocialLoginMessage, SocialLoginMessageListener); end; procedure TFormMain.FormDestroy(Sender: TObject); begin TMessageManager.DefaultManager.Unsubscribe(TgoSocialLoginMessage, SocialLoginMessageListener); Social.Free; end; procedure TFormMain.SocialLoginMessageListener(const Sender: TObject; const M: TMessage); var SocialLoginMessage: TgoSocialLoginMessage; begin SocialLoginMessage := M as TgoSocialLoginMessage; { since the callback may be from another thread than the main thread} TThread.Synchronize(Nil, procedure begin if SocialLoginMessage.Value.Result then ShowMessage( 'Success Id = ' + SocialLoginMessage.Value.Id + ' AccessToken = ' + SocialLoginMessage.Value.AccessToken) else ShowMessage('Failed'); end); end; procedure TFormMain.ButtonLoginFacebookClick(Sender: TObject); begin Social.Login(TgoSocialNetwork.Facebook); end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXSAPIA0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* Demonstrates how to use the AskFor methods in the *} {* TApdSapiPhone component. *} {*********************************************************} unit ExSapiA0; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AdTapi, AdSapiPh, OoMisc, AdSapiEn, ExtCtrls; type TListRequest = (lrPlanet, lrColor); TForm1 = class(TForm) ApdSapiEngine1: TApdSapiEngine; ApdSapiPhone1: TApdSapiPhone; Label1: TLabel; lblDate: TLabel; lblExtension: TLabel; btnDate: TButton; btnExtension: TButton; btnPlanet: TButton; btnColor: TButton; btnPhoneNumber: TButton; btnSpelling: TButton; btnTime: TButton; btnYesNo: TButton; lblPlanet: TLabel; lblColor: TLabel; lblPhoneNumber: TLabel; lblSpelling: TLabel; lblTime: TLabel; lblYesNo: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Memo1: TMemo; Label10: TLabel; Shape1: TShape; procedure btnDateClick(Sender: TObject); procedure btnExtensionClick(Sender: TObject); procedure btnPlanetClick(Sender: TObject); procedure btnColorClick(Sender: TObject); procedure btnPhoneNumberClick(Sender: TObject); procedure btnSpellingClick(Sender: TObject); procedure btnTimeClick(Sender: TObject); procedure btnYesNoClick(Sender: TObject); procedure ApdSapiPhone1AskForDateFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String); procedure ApdSapiPhone1AskForExtensionFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data, SpokenData: String); procedure ApdSapiPhone1AskForListFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: Integer; SpokenData: String); procedure ApdSapiPhone1AskForPhoneNumberFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data, SpokenData: String); procedure ApdSapiPhone1AskForSpellingFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data, SpokenData: String); procedure ApdSapiPhone1AskForTimeFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String); procedure ApdSapiPhone1AskForYesNoFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: Boolean; SpokenData: String); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ApdSapiEngine1SRError(Sender: TObject; Error: Integer; const Details, Message: String); procedure ApdSapiEngine1SRWarning(Sender: TObject; Error: Integer; const Details, Message: String); procedure ApdSapiEngine1SSError(Sender: TObject; Error: Integer; const Details, Message: String); procedure ApdSapiEngine1SSWarning(Sender: TObject; Error: Integer; const Details, Message: String); procedure ApdSapiEngine1Interference(Sender: TObject; InterferenceType: TApdSRInterferenceType); procedure ApdSapiEngine1PhraseFinish(Sender: TObject; const Phrase: String); private ListRequest : TListRequest; ColorList : TStringList; PlanetList : TStringList; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.btnDateClick(Sender: TObject); begin ApdSapiPhone1.AskForDate ('Say a date'); end; procedure TForm1.btnExtensionClick(Sender: TObject); begin ApdSapiPhone1.NumDigits := 3; ApdSapiPhone1.AskForExtension ('Say an extension'); end; procedure TForm1.btnPlanetClick(Sender: TObject); begin ListRequest := lrPlanet; ApdSapiPhone1.AskForList (PlanetList, 'Say a planet'); end; procedure TForm1.btnColorClick(Sender: TObject); begin ListRequest := lrColor; ApdSapiPhone1.AskForList (ColorList, 'Say a color'); end; procedure TForm1.btnPhoneNumberClick(Sender: TObject); begin ApdSapiPhone1.AskForPhoneNumber ('Say a phone number'); end; procedure TForm1.btnSpellingClick(Sender: TObject); begin ApdSapiPhone1.AskForSpelling ('Spell something. Say done when you are finished'); end; procedure TForm1.btnTimeClick(Sender: TObject); begin ApdSapiPhone1.AskForTime ('Say a time'); end; procedure TForm1.btnYesNoClick(Sender: TObject); begin ApdSapiPhone1.AskForYesNo ('Say yes or no'); end; procedure TForm1.ApdSapiPhone1AskForDateFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String); begin case Reply of prOk : begin Memo1.Lines.Add ('DATE --> ' + FormatDateTime ('dddddd', Data) + ' (' + SpokenData + ')'); lblDate.Caption := FormatDateTime ('dddddd', Data); end; prCheck : begin Memo1.Lines.Add ('DATE --> ' + FormatDateTime ('dddddd', Data) + '? (' + SpokenData + ')'); lblDate.Caption := FormatDateTime ('dddddd', Data); end; prOperator : Memo1.Lines.Add ('DATE --> [operator]'); prHangup : Memo1.Lines.Add ('DATE --> [hangup]'); prBack : Memo1.Lines.Add ('DATE --> [back]'); end; end; procedure TForm1.ApdSapiPhone1AskForExtensionFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data, SpokenData: String); begin case Reply of prOk : begin Memo1.Lines.Add ('EXT --> ' + Data); lblExtension.Caption := Data; end; prOperator : Memo1.Lines.Add ('EXT --> [operator]'); prHangup : Memo1.Lines.Add ('EXT --> [hangup]'); prBack : Memo1.Lines.Add ('EXT --> [back]'); end; end; procedure TForm1.ApdSapiPhone1AskForListFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: Integer; SpokenData: String); begin case Reply of prOk : begin if Data >= 0 then case ListRequest of lrPlanet : if (Data <= 1) then lblPlanet.Caption := PlanetList[Data] + ' (not really a planet' else lblPlanet.Caption := PlanetList[Data]; lrColor : begin lblColor.Caption := ColorList[Data]; case Data of 0 : Shape1.Brush.Color := clRed; 1 : Shape1.Brush.Color := clBlue; 2 : Shape1.Brush.Color := clYellow; 3 : Shape1.Brush.Color := clGreen; 4 : Shape1.Brush.Color := $007FFF; 5 : Shape1.Brush.Color := clPurple; 6 : Shape1.Brush.Color := clPurple; 7 : Shape1.Brush.Color := $00003399; 8 : Shape1.Brush.Color := clBlack; 9 : Shape1.Brush.Color := $00FFFFFF; 10 : Shape1.Brush.Color := clGray; 11 : Shape1.Brush.Color := clMaroon; 12 : Shape1.Brush.Color := clOlive; 13 : Shape1.Brush.Color := clNavy; 14 : Shape1.Brush.Color := clTeal; 15 : Shape1.Brush.Color := clSilver; 16 : Shape1.Brush.Color := clLime; 17 : Shape1.Brush.Color := clFuchsia; 18 : Shape1.Brush.Color := clAqua; end; end; end; Memo1.Lines.Add ('LIST --> ' + IntToStr (Data) + ' (' + SpokenData + ')'); end; prOperator : Memo1.Lines.Add ('LIST --> [operator]'); prHangup : Memo1.Lines.Add ('LIST --> [hangup]'); prBack : Memo1.Lines.Add ('LIST --> [back]'); end; end; procedure TForm1.ApdSapiPhone1AskForPhoneNumberFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data, SpokenData: String); begin case Reply of prOk : begin Memo1.Lines.Add ('PHONE --> ' + Data + ' (' + SpokenData + ')'); lblPhoneNumber.Caption := Data; end; prOperator : Memo1.Lines.Add ('PHONE --> [operator]'); prHangup : Memo1.Lines.Add ('PHONE --> [hangup]'); prBack : Memo1.Lines.Add ('PHONE --> [back]'); end; end; procedure TForm1.ApdSapiPhone1AskForSpellingFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data, SpokenData: String); begin case Reply of prOk : begin Memo1.Lines.Add ('SPELL --> ' + Data); lblSpelling.Caption := Data; end; prOperator : Memo1.Lines.Add ('SPELL --> [operator]'); prHangup : Memo1.Lines.Add ('SPELL --> [hangup]'); prBack : Memo1.Lines.Add ('SPELL --> [back]'); end; end; procedure TForm1.ApdSapiPhone1AskForTimeFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String); begin case Reply of prOk : begin Memo1.Lines.Add ('TIME --> ' + FormatDateTime ('tt', Data) + '(' + SpokenData + ')'); lblTime.Caption := FormatDateTime ('tt', Data); end; prOperator : Memo1.Lines.Add ('TIME -> [operator]'); prHangup : Memo1.Lines.Add ('TIME --> [hangup]'); prBack : Memo1.Lines.Add ('TIME --> [back]'); end; end; procedure TForm1.ApdSapiPhone1AskForYesNoFinish(Sender: TObject; Reply: TApdSapiPhoneReply; Data: Boolean; SpokenData: String); begin case Reply of prOk : if Data then begin Memo1.Lines.Add ('YES/NO ---> Yes'); lblYesNo.Caption := 'Yes' end else begin Memo1.Lines.Add ('YES/NO ---> No'); lblYesNo.Caption := 'No'; end; prOperator : Memo1.Lines.Add ('YES/NO --> [operator]'); prHangup : Memo1.Lines.Add ('YES/NO --> [hangup]'); prBack : Memo1.Lines.Add ('YES/NO --> [back]'); end; end; procedure TForm1.FormCreate(Sender: TObject); begin if (not ApdSapiEngine1.IsSapi4Installed) then begin ShowMessage ('SAPI 4 is not installed.'); end; ColorList := TStringList.Create; ColorList.Add ('red'); ColorList.Add ('blue'); ColorList.Add ('yellow'); ColorList.Add ('green'); ColorList.Add ('orange'); ColorList.Add ('purple'); ColorList.Add ('violet'); ColorList.Add ('brown'); ColorList.Add ('black'); ColorList.Add ('white'); ColorList.Add ('gray'); ColorList.Add ('maroon'); ColorList.Add ('olive'); ColorList.Add ('navy'); ColorList.Add ('teal'); ColorList.Add ('silver'); ColorList.Add ('lime'); ColorList.Add ('fuchsia'); ColorList.Add ('aqua'); PlanetList := TStringList.Create; PlanetList.Add ('[opt] the sun'); PlanetList.Add ('[opt] the moon'); PlanetList.Add ('mercury'); PlanetList.Add ('venus'); PlanetList.Add ('[opt] the earth'); PlanetList.Add ('mars'); PlanetList.Add ('jupiter'); PlanetList.Add ('saturn'); PlanetList.Add ('neptune'); PlanetList.Add ('uranus'); PlanetList.Add ('pluto'); PlanetList.Add ('rupert'); end; procedure TForm1.FormDestroy(Sender: TObject); begin ColorList.Free; PlanetList.Free; end; procedure TForm1.ApdSapiEngine1SRError(Sender: TObject; Error: Integer; const Details, Message: String); begin Memo1.Lines.Add ('SR Error: ' + Message); end; procedure TForm1.ApdSapiEngine1SRWarning(Sender: TObject; Error: Integer; const Details, Message: String); begin Memo1.Lines.Add ('SR Warning: ' + Message); end; procedure TForm1.ApdSapiEngine1SSError(Sender: TObject; Error: Integer; const Details, Message: String); begin Memo1.Lines.Add ('SS Error: ' + Message); end; procedure TForm1.ApdSapiEngine1SSWarning(Sender: TObject; Error: Integer; const Details, Message: String); begin Memo1.Lines.Add ('SS Warning: ' + Message); end; procedure TForm1.ApdSapiEngine1Interference(Sender: TObject; InterferenceType: TApdSRInterferenceType); begin case InterferenceType of itAudioStarted : Memo1.Lines.Add('*** Interference - Audio Started ***'); itAudioStopped : Memo1.Lines.Add('*** Interference - Audio Stopped ***'); itDeviceOpened : Memo1.Lines.Add('*** Interference - Device Opened ***'); itDeviceClosed : Memo1.Lines.Add('*** Interference - Device Closed ***'); itNoise : Memo1.Lines.Add('*** Interference - Noise ***'); itTooLoud : Memo1.Lines.Add('*** Interference - Too Loud ***'); itTooQuiet : Memo1.Lines.Add('*** Interference - Too Quiet ***'); itUnknown : Memo1.Lines.Add('*** Interference - Unknown ***'); end; end; procedure TForm1.ApdSapiEngine1PhraseFinish(Sender: TObject; const Phrase: String); begin Memo1.Lines.Add ('REPLY --> ' + Phrase); end; end.
//______________________________________________________________________________ //-----------------------------------Salimov Artem----------------------10.11.12 //----------Последние изменение : Литовченко Дмитрий Николаевич-------22.12.2009 unit SpWorkMode; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxLookAndFeelPainters, StdCtrls, cxButtons, cxCheckBox, cxSpinEdit, cxTimeEdit, cxLabel, ExtCtrls,WorkMode_Dm,TuCommonLoader, TuMessages,TuCommonProc, TuCommonTypes, Qt, ActnList, cxDropDownEdit, cxCalendar,dates, cxGroupBox, cxMemo, cxRadioGroup, cxButtonEdit, cxCurrencyEdit,AccMGMT; type TForm1 = class(TForm) pnl1: TPanel; pnl2: TPanel; ButtonOK: TcxButton; ButtonCancel: TcxButton; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; cxGroupBox1: TcxGroupBox; CheckBoxZm: TcxCheckBox; EditFinish: TcxTimeEdit; Label5: TcxLabel; EditStart: TcxTimeEdit; Label4: TcxLabel; cxGroupBox2: TcxGroupBox; EditDb: TcxDateEdit; cxLabel1: TcxLabel; Label1: TcxLabel; EditNum: TcxMaskEdit; Label2: TcxLabel; EditName: TcxMaskEdit; EditShortName: TcxMaskEdit; Label3: TcxLabel; cxLabel2: TcxLabel; EditDe: TcxDateEdit; CheckBoxTypeViewYes: TcxRadioButton; CheckBoxTypeViewNo: TcxRadioButton; EditCaption: TcxMemo; cxLabel3: TcxLabel; cxGroupBox3: TcxGroupBox; CheckBoxNoWM: TcxCheckBox; CheckBoxBranch: TcxCheckBox; EditParent: TcxButtonEdit; cxLabel4: TcxLabel; EditCOEFFICIENT: TcxCurrencyEdit; procedure ButtonOKClick(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure CheckBoxZmPropertiesChange(Sender: TObject); procedure EditParentPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure CheckBoxBranchPropertiesChange(Sender: TObject); private { Private declarations } public id:Variant; IdParent:Variant; PCFStyle:TTuControlFormStyle; constructor Create(PParameter:TTuWorkModeEditParam);reintroduce; end; function View_SpWorkModeEdit(AParameter:TObject):Variant;stdcall; exports View_SpWorkModeEdit; implementation uses FIBQuery; {$R *.dfm} function View_SpWorkModeEdit(AParameter:TObject):Variant;stdcall; var Form:TForm1; begin Form:=TForm1.Create(TTuWorkModeEditParam(AParameter)); Form.PCFStyle:=TTuWorkModeEditParam(AParameter).CFStyle; if (((fibCheckPermission('/ROOT/TimeKeeping/TU_MainMenu/TU_Work/TU_WorkMode','Del')<>0) and (fibCheckPermission('/ROOT/TimeKeeping/TU_MainMenu/TU_Work','Del')<>0)) and (Form.PCFStyle=tcfsDelete)) or (((fibCheckPermission('/ROOT/TimeKeeping/TU_MainMenu/TU_Work/TU_WorkMode','Add')<>0) and (fibCheckPermission('/ROOT/TimeKeeping/TU_MainMenu/TU_Work','Add')<>0)) and (Form.PCFStyle=tcfsInsert)) or(((fibCheckPermission('/ROOT/TimeKeeping/TU_MainMenu/TU_Work/TU_WorkMode','Edit')<>0) and (fibCheckPermission('/ROOT/TimeKeeping/TU_MainMenu/TU_Work','Edit')<>0)) and (Form.PCFStyle=tcfsDelete)) then begin //yes MessageBox(null, 'Ви не маєте прав до цієї дії!','Увага!', MB_OK or MB_ICONWARNING); result:=null; exit end ; result:=TTuWorkModeEditParam(AParameter).id; if Form.PCFStyle=tcfsDelete then begin if TuShowMessage(GetConst('Delete','Error'),GetConst('DeleteText','Error'), mtWarning, [mbYes,mbNo])=6 then begin dm.StProc.Transaction.Active:=true; dm.StProc.StoredProcName:='DT_WORK_MODE_DELETE'; dm.StProc.Prepare; dm.StProc.ParamByName('ID_WORK_MODE').asinteger:=TTuWorkModeEditParam(AParameter).id; dm.StProc.ExecProc; DM.StProc.Transaction.Commit; end else result:=null; Exit; end; if not VarIsNull(TTuWorkModeEditParam(AParameter).id) then begin dm.StProc.Transaction.Active:=true; dm.StProc.StoredProcName:='DT_WORK_MODE_SELECT_BY_KEY'; dm.StProc.Prepare; dm.StProc.ParamByName('ID_WORK_MODE_IN').asinteger:=TTuWorkModeEditParam(AParameter).id; dm.StProc.ExecProc; form.EditNum.Text := dm.StProc.ParamByName('NOMER').AsString; form.EditName.Text := dm.StProc.ParamByName('NAME').AsString; form.EditShortName.Text := dm.StProc.ParamByName('NAME_SHORT').AsString; form.EditStart.Time := dm.StProc.ParamByName('NIGHT_BEG').AsTime ; form.EditFinish.Time := dm.StProc.ParamByName('NIGHT_END').AsTime ; form.EditDB.Date := dm.StProc.ParamByName('Date_BEG').AsDate ; form.EditDe.Date := dm.StProc.ParamByName('DATE_END').AsDate ; form.EditCaption.text := dm.StProc.ParamByName('CAPTION').AsString ; form.EditParent.text := dm.StProc.ParamByName('NAME_parent').AsString ; form.EditCOEFFICIENT.Value:=dm.StProc.ParamByName('COEFFICIENT').AsExtended ; if dm.StProc.ParamByName('IS_SMENA').AsString='T' then begin Form.CheckBoxZm.Checked:=True; Form.CheckBoxTypeViewYes.Checked:=True; end ; if dm.StProc.ParamByName('TYPE_VIEW').AsInteger=1 then Form.CheckBoxTypeViewYes.Checked:=True else form.IdParent:=dm.StProc.ParamByName('id_parent').Asinteger; if form.IdParent<>-1 then Form.CheckBoxBranch.Checked:=false; Form.CheckBoxNoWM.EditValue:=dm.StProc.ParamByName('is_work_mode').Asinteger; DM.StProc.Transaction.Commit; end; if Form.PCFStyle=tcfsInsert then begin dm.StProc.Transaction.StartTransaction; dm.StProc.StoredProcName:='TU_WORK_MODE_NUM_BY_PARENT'; dm.StProc.Prepare; dm.StProc.ParamByName('ID_PARENT').asinteger:=form.IdParent; dm.StProc.ExecProc; form.EditNum.Text:=dm.StProc.ParamByName('NOMER').AsString; form.EditCOEFFICIENT.Value:=1; DM.StProc.Transaction.Commit; end; if Form.ShowModal=mrYes then begin dm.StProc.Transaction.StartTransaction; if Form.PCFStyle=tcfsInsert then dm.StProc.StoredProcName:='TU_WORK_MODE_INSERT' else dm.StProc.StoredProcName:='TU_WORK_MODE_UPDATE'; dm.StProc.Prepare; dm.StProc.ParamByName('NOMER').asinteger :=strtoint(Form.EditNum.text); dm.StProc.ParamByName('NAME').AsString :=Form.EditName.text; dm.StProc.ParamByName('NAME_SHORT').AsString :=Form.EditShortName.text; dm.StProc.ParamByName('NIGHT_BEG').AsTime :=Form.EditStart.Time; dm.StProc.ParamByName('NIGHT_END').AsTime :=Form.EditFinish.Time; dm.StProc.ParamByName('date_beg').Asdate :=Form.Editdb.date; dm.StProc.ParamByName('date_END').Asdate :=Form.Editde.date; dm.StProc.ParamByName('CAPTION').AsString :=Form.EditCaption.text; dm.StProc.ParamByName('COEFFICIENT').AsExtended :=Form.EditCOEFFICIENT.Value; if not Form.CheckBoxBranch.Checked then dm.StProc.ParamByName('id_parent').asInteger:=Form.IdParent else dm.StProc.ParamByName('id_parent').asInteger:= -1; dm.StProc.ParamByName('is_work_mode').asInteger:=Form.CheckBoxNoWM.EditValue; if Form.CheckBoxZm.Checked then dm.StProc.ParamByName('IS_SMENA').AsString:='T' else dm.StProc.ParamByName('IS_SMENA').AsString:='F'; if Form.CheckBoxTypeViewYes.Checked then dm.StProc.ParamByName('TYPE_VIEW').Asinteger :=1 else dm.StProc.ParamByName('TYPE_VIEW').Asinteger :=0; if Form.PCFStyle=tcfsUpdate then dm.StProc.ParamByName('ID_WORK_MODE').asinteger:=TTuWorkModeEditParam(AParameter).id; dm.StProc.ExecProc; if Form.PCFStyle=tcfsInsert then result:=dm.StProc.ParamByName('ID').asinteger; DM.StProc.Transaction.Commit; end else result:=null; end; //****************************************************************************** constructor TForm1.Create(PParameter:TTuWorkModeEditParam); begin inherited Create(PParameter.Owner); Dm:=TDM.create(self); Dm.DB.Handle:=PParameter.Db_Handle; Dm.DB.Connected:=True; Id:=PParameter.id; EditDb.date:=strtodate(KodSetupToPeriod(PParameter.KodSetup,6)); //------------------------------------------------------------------------------ if PParameter.CFStyle=tcfsInsert then Caption:= GetConst('Insert','Button')+' '+GetConst('WorkMode','Form') else Caption:= GetConst('Update','Button')+' '+GetConst('WorkMode','Form'); Label1.Caption:= GetConst('Nomer','Label')+':'; Label2.Caption:= GetConst('Name','Label')+':'; Label3.Caption:= GetConst('ShortName','Label')+':'; Label4.Caption:= GetConst('StartTime','Label')+':'; Label5.Caption:= GetConst('FinishTime','Label')+':'; CheckBoxZm.Properties.Caption:=GetConst('Change','CheckBox'); // CheckBoxTypeViewYes.Properties.Caption:=GetConst('TypeView','CheckBox'); ButtonOK.Caption:=GetConst('Yes','Button'); ButtonCancel.Caption:=GetConst('Cancel','Button'); ButtonOK.Enabled:=True; EditStart.Text end; procedure TForm1.ButtonOKClick(Sender: TObject); begin if (Length( EditNum.Text)=0 ) or(Length( EditName.Text)=0 ) or(Length( EditShortName.Text)=0) or (Length(EditCOEFFICIENT.text)=0) then begin TuShowMessage(GetConst('Caption','Error'),GetConst('EmptyData','Error'), mtError, [mbOK]); Exit; end; ModalResult:=mrYes; end; procedure TForm1.ButtonCancelClick(Sender: TObject); begin ModalResult:=mrNo; end; procedure TForm1.FormShow(Sender: TObject); begin EditNum.SetFocus; end; procedure TForm1.CheckBoxZmPropertiesChange(Sender: TObject); begin CheckBoxTypeViewYes.Checked:= CheckBoxZm.Checked; CheckBoxTypeViewNo.Checked:= not CheckBoxZm.Checked; end; procedure TForm1.EditParentPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Parameter:TTuSimpleParam; res:variant; begin Parameter := TTuSimpleParam.Create; Parameter.DB_Handle := DM.DB.Handle; Parameter.Owner := self; Parameter.CFStyle:=tfsModalParent; if PCFStyle=tcfsUpdate then Parameter.id:= id else Parameter.id:=null; res:=DoFunctionFromPackage(Parameter,Tu_SpWorkMode_Pack); if VarIsArray(res)then begin IdParent:=res[0]; EditParent.Text:=res[1]; end; Parameter.Destroy; end; procedure TForm1.CheckBoxBranchPropertiesChange(Sender: TObject); begin EditParent.Enabled:= not CheckBoxBranch.Checked; end; end.
Unit Dcache; { * Dcache : * * * * Unidad encargada dl mantenimiento del cache de nombres a * * traves del arbol de dentrys del sistema . Es utilizada * * por la unida namei.pas * * * * Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> * * All Rights Reserved * * * * Version : * * * * 10 / 10 / 2005 : Corregido bug en Alloc_dentry() * * 03 / 10 / 2005 : Corregido error en Find_in_Dentry * * 20 / 08 / 2005 : Corregido bug en Enqueue_dentry() * * 29 / 06 / 2005 : Primera version * * * *************************************************************** } interface {$I ../include/toro/procesos.inc} {$I ../include/toro/buffer.inc} {$I ../include/head/buffer.h} {$I ../include/head/asm.h} {$I ../include/head/inodes.h} {$I ../include/head/open.h} {$I ../include/head/procesos.h} {$I ../include/head/scheduler.h} {$I ../include/head/read_write.h} {$I ../include/head/devices.h} {$I ../include/head/printk_.h} {$I ../include/head/malloc.h} {define debug} {$DEFINE Use_Tail } {$DEFINE nodo_struct := p_dentry} {$DEFINE next_nodo := next_dentry } {$DEFINE prev_nodo := prev_dentry } {Macros creados solo para comodidad} {$DEFINE Push_Dentry := Push_Node } {$DEFINE Pop_Dentry:= Pop_Node } {dentrys sin uso} const Free_dentrys : p_dentry = nil ; var dentry_root : p_dentry ; Max_dentrys : dword ; implementation {$I ../include/head/string.h} {$I ../include/head/list.h} {$I ../include/head/lock.h} procedure Init_dentry (dt : p_dentry); begin with dt^ do begin ino := nil ; flags := 0 ; count := 0 ; name[0] := char(0) ; down_tree := nil ; next_dentry := nil ; prev_dentry := nil ; down_mount_Tree := nil; down_tree := nil; parent := nil ; l_count := 0 ; end; end; { * encola un dentry en su padre * } procedure Enqueue_dentry (dt : p_dentry ); begin Push_dentry (dt,dt^.parent^.down_tree); dt^.parent^.l_count += 1; end; { * quita un dentry de su padre * } procedure Remove_queue_dentry (dt :p_dentry );inline; begin Pop_dentry (dt,dt^.parent^.down_tree); dt^.parent^.l_count -= 1; end; { * busca un nombre dentro de un dentry y devuelve un puntero dentry * } function Find_in_Dentry (const name : string ; dt : p_dentry ) : p_dentry ; var tmp : p_dentry ; begin tmp := dt^.down_tree; if tmp = nil then exit(nil); repeat if dword(name[0]) <> dword(tmp^.name[0]) then exit(nil); if chararraycmp(@name[1], @tmp^.name[1],dword(tmp^.name[0])) Then exit(tmp); tmp := tmp^.next_dentry; until (tmp = dt^.down_tree) ; exit(nil); end; { * Alloc_dentry : * * * * name : Nombre de la entrada * * * * Esta funcion devuelve un estructura dentry libre , primero tratara * * de crear y si no hay memoria suficiente tomara una estrutura de la * * cola de libres , y si en este caso no puede devuelve nil * * * *********************************************************************** } function Alloc_dentry (const name : string ) : p_dentry ;[public , alias :'ALLOC_DENTRY']; var tmp : p_dentry ; label _exit,_lru ; begin if Max_dentrys = 0 then begin _lru : if Free_dentrys = nil then exit(nil); {se toma el menos utilizado} tmp := free_dentrys^.prev_dentry ; goto _exit ; end; tmp := kmalloc (sizeof(dentry)); if tmp = nil then goto _lru ; Max_dentrys -= 1; _exit : init_dentry (tmp); memcopy (@name[0],@tmp^.name[0],dword(name[0])); tmp^.len := byte(tmp^.name[0]); tmp^.name[0] := char(tmp^.len); exit (tmp); end; { * Alloc_Entry : * * * * ino_p : puntero al inodo directorio padre * * name : nombre de la entrada * * * * Esta funcion es bastante compleja , lo que hace primeramente es * * buscar name en el arbol del padre , si la encuentra aumenta el * * contador del dentry y devuelve la dentry . Si fuese una entrada * * vacia hace un lookup sobre el ino_p para traer el inodo a memoria * * . Llena la dentry con el inodo y el driver devera puntear el * * campo i_dentry del inodo al dentry que se le pasa como parametro * * Si no estubiese trata de crear la estruc. busca un dentry libre * * y hace un lookup con name , es encolada y devera ser devuelta con * * Put_dentry * * * *********************************************************************** } const DIR : pchar = '.'; DIR_PREV : pchar = '..'; function Alloc_Entry ( ino_p : p_inode_t ; const name : string ) : p_dentry ;[public , alias :'ALLOC_ENTRY']; var tmp :p_dentry ; label _1 ; begin Inode_Lock (@ino_p^.wait_on_inode); {entradas estandart} if chararraycmp(@name[1],@DIR[1],1) then begin tmp := ino_p^.i_dentry ; goto _1; end else if chararraycmp(@name[1],@DIR_PREV[1],2) then begin tmp := ino_p^.i_dentry^.parent ; goto _1 ; end; tmp := find_in_dentry (name,ino_p^.i_dentry); if tmp <> nil then begin _1: {esta encache} if (tmp^.state = st_incache) then begin tmp^.count += 1; {esta en cache pero el inodo esta en lru} if tmp^.ino^.count = 0 then begin get_inode (tmp^.ino^.sb,tmp^.ino^.ino); tmp^.ino^.count := 1 ; end; {$IFDEF debug} printk('/Vdcache/n : entrada en cache %p\n',[name],[]); {$ENDIF} Inode_Unlock (@ino_p^.wait_on_inode); exit (tmp); end; {entrada zombie} if (tmp^.state = st_vacio) then begin {una parte del arbol esta invalidado por que fue eliminada una entrada fisica} if ino_p^.op^.lookup (ino_p , tmp) = nil then Panic ('VFS : Arbol invalido!!!!'); {se trae el inodo al cache de inodos} {lookup deve llenar el campo ino del cache y poner al campo count en 1} tmp^.state := st_incache; tmp^.flags := tmp^.ino^.flags; tmp^.l_count := 0 ; tmp^.count := 1; Inode_Unlock (@ino_p^.wait_on_inode); exit(tmp ); end; end; tmp := alloc_dentry (name) ; {no se puede seguir la ruta!!!} if tmp = nil then begin Inode_Unlock (@ino_p^.wait_on_inode); exit(nil); end; {no existe la dentry!!!??} if ino_p^.op^.lookup (ino_p,tmp) = nil then begin Push_dentry (free_dentrys,tmp); Inode_Unlock (@ino_p^.wait_on_inode); exit(nil); end; tmp^.state := st_incache; tmp^.parent := ino_p^.i_dentry ; tmp^.flags := tmp^.ino^.flags ; tmp^.count := 1 ; tmp^.ino^.i_dentry := tmp; {se pone en la cola del padre} Enqueue_Dentry (tmp); {$IFDEF DEBUG} printk('/Vdcache/n : nueva entrada %p\n',[name],[]); {$ENDIF} Inode_Unlock (@ino_p^.wait_on_inode); exit(tmp); end; { * Put_dentry : * * * * dt : puntero al dentry * * * * Decrementa el uso de una dentry si no posee mas usuarios se devuelve * * el inodo al cache . Cuando un inodo quitado totalmente del sistema * * si no posee enlaces se libera la estructura , si posee se vuelve un * * dentry vacio puesto que podra ser utilizada en una futura busqueda * * Las que poseen enlaces son enlazadas ya que es muy posible que se * * vuelven totalmente obsoletas , proc. sync rastrea esta cola en busca * * de dentrys obsoletas y las coloca en la cola de libres * * (no implementado) * * * ************************************************************************ } procedure Put_dentry (dt : p_dentry ) ; [public , alias : 'PUT_DENTRY']; begin dt^.count -= 1; if dt^.count = 0 then put_inode (dt^.ino); end; { * Llamada que quita un dentry y la coloca como libre * } procedure Free_Dentry ( dt : p_dentry ) ; [public ,alias :'FREE_DENTRY']; begin Remove_queue_dentry (dt); Push_Dentry (Free_dentrys,dt); end; end.
{Le joueur est caractérisé par un nombre nommé "place" compris entre 0 et 66. Il situe sa position sur le Jeu de l'Oie, sachant qu'après jet des deux dés, on applique les règles suivantes : On avance du nombre de cases indiqués par la somme des dés. Si on arrive juste sur la case 66, le jeu est terminé. Sinon on recule du nombre de points en trop. Une Oie toutes les neufs cases sauf en 63 double le déplacement. Une tête de mort case 58 renvoie en position de départ, case 0. On s'efforcera d'utiliser au maximum des CONSTANTES. Il faut produire un Algo, et un code lisible et clair. Il faut insérer des commentaires. Il faut vérifier si le jet est valide (valeurs entre 2 et 12). Il est conseillée d'utiliser l'opérateur MODULO pour vérifier si une case est un multiple de 9. Algorithme Jeu_de_l'oie Algorithme:Jeu-de-l'oie //But:Simuler le jeu de l'oie pour 1 joueur //Principe:On lance le dé aléatoirement et déplace le joueur tout en respectant les règles écrites au dessus //Entrée:Un joueur souhaitant jouer seul au jeu de l'oie //Sortie:Une partie joué/jouable par le joueur * CONST fin <--66; min <--2; pdbl <--63; mort <--58; alea <--13; VAR: jet,place:ENTIER DEBUT ECRIRE "Appuyez sur entrer pour commencer la partie." LIRE() place <-- 0 jet <-- 0 TANTQUE (place <> 66) FAIRE //déroulemet de la partie ECRIRE ( "Pressez entrer pour lancer les dés.") // déclaration des phrases pour informer le joueur sur le déplacement de la partie LIRE() REPETER jet <-- RANDOM(12) //Jet du dé de manière aléatoire JUSQU'A jet >= 2 ECRIRE ( "Votre jet de dés vaut: ",jet) place <-- place + jet SI (place MOD 9 = 0) ET (place <> 63) ALORS //test pour doubler la valeur du jet si la case est un mutiple de 9 ECRIRE ("Vous êtes tombé sur une case qui est multiple de 9 votre jet de dés est doublé,votre jet de dés vaut: ",jet*2) place<-- place + jet FINSI SI (place>66) ALORS// au cas ou le joueur dépasse la case 66 il recule de la différence entre sa position et la case 66 place <-- place-(place-66) ECRIRE ("Vous avez dépassé la case 66 vous reculez et vosu retrouvez à la case " , place) FINSI SI place= 58 ALORS ECRIRE ("Vous êtes tombé sur la case 58 , retournez à la case départ.") place=0 FINSI ECRIRE ("Vous êtes sur la case: ",place) FINTANTQUE ECRIRE ("Vous avez gagné la partie vous avez atteint la case 66. ") FIN } USES crt; CONST fin =66; min =2; pdbl =63; mort =58; alea =13; VAR jet,place:INTEGER; BEGIN Randomize;// très utile car Randomize initialise le générateur de nombres aléatoires de Free Pascal,calculée avec l'horloge système. clrscr; Writeln('Appuyez sur entrer pour commencer la partie.'); Readln(); place := 0; jet:=0; While (place <> fin) do BEGIN Writeln('Pressez entrer pour lancer les des.'); Readln(); Repeat jet := random(alea);//13 car il simule un entier entre 0 et n-1 UNTIL (jet >= min); Writeln('Votre jet de des vaut: ',jet); place := place+jet; IF(place MOD 9 = 0) AND (place <> pdbl) THEN BEGIN Writeln('Vous etes tombe sur une case qui est multiple de 9 votre jet de das est double,votre jet de des vaut: ',jet*2); place:= place + jet ; END; if (place > fin) THEN// au cas ou le joueur dépasse la case 66 il recule de la différence entre sa position et la case 66 BEGIN place:=fin-(place-fin); Writeln('Vous avez depasse la case 66 vous reculez et vous retrouvez a la case ',place); END; if (place = mort ) THEN BEGIN Writeln('Vous etes tombe sur la case 58 , retournez a la case depart.'); place:=0; END; Writeln('Vous etes sur la case: ',place); END; Writeln('Vous avez gagne la partie,vous avez atteint la case 66. '); Readln(); END.
unit Objekt.DHLReceiverNativeAddress; interface uses SysUtils, Classes, geschaeftskundenversand_api_2, Objekt.DHLOrigin; type TDHLReceiverNativeAddress = class private fReceiverNativeAdressTypeAPI: ReceiverNativeAddressType; fStreetName: string; fZip: string; fStreetNumber: string; fName1: string; fCity: string; fName3: string; fDispatchingInformation: string; fAddressAdditionArray: Array_Of_addressAddition2; fAddressAddition: string; fOrigin: TDHLOrigin; procedure setCity(const Value: string); procedure setName2(const Value: string); procedure setName3(const Value: string); procedure setStreetName(const Value: string); procedure setStreetNumber(const Value: string); procedure setZip(const Value: string); procedure setDispatchingInformation(const Value: string); procedure setAddressAddition(const Value: string); public constructor Create; destructor Destroy; override; function ReceiverNativeAddressTypeAPI: ReceiverNativeAddressType; property Name2: string read fName1 write setName2; property Name3: string read fName3 write setName3; property StreetName: string read fStreetName write setStreetName; property StreetNumber: string read fStreetNumber write setStreetNumber; property DispatchingInformation: string read fDispatchingInformation write setDispatchingInformation; property AddressAddition: string read fAddressAddition write setAddressAddition; property Zip: string read fZip write setZip; property City: string read fCity write setCity; property Origin: TDHLOrigin read fOrigin write fOrigin; end; implementation { TDHLReceiverNativeAddress } constructor TDHLReceiverNativeAddress.Create; begin fOrigin := TDHLOrigin.Create; setLength(fAddressAdditionArray, 1); fReceiverNativeAdressTypeAPI := ReceiverNativeAddressType.Create; fReceiverNativeAdressTypeAPI.addressAddition := fAddressAdditionArray; fReceiverNativeAdressTypeAPI.Origin := fOrigin.OriginAPI; end; destructor TDHLReceiverNativeAddress.Destroy; begin FreeAndNil(fReceiverNativeAdressTypeAPI); FreeAndNil(fOrigin); inherited; end; function TDHLReceiverNativeAddress.ReceiverNativeAddressTypeAPI: ReceiverNativeAddressType; begin Result := fReceiverNativeAdressTypeAPI; end; procedure TDHLReceiverNativeAddress.setAddressAddition(const Value: string); begin fAddressAddition := Value; fAddressAdditionArray[0] := value; end; procedure TDHLReceiverNativeAddress.setCity(const Value: string); begin fCity := Value; fReceiverNativeAdressTypeAPI.city := Value; end; procedure TDHLReceiverNativeAddress.setDispatchingInformation(const Value: string); begin fDispatchingInformation := Value; fReceiverNativeAdressTypeAPI.dispatchingInformation := Value; end; procedure TDHLReceiverNativeAddress.setName2(const Value: string); begin fName1 := Value; fReceiverNativeAdressTypeAPI.name2 := Value; end; procedure TDHLReceiverNativeAddress.setName3(const Value: string); begin fName3 := Value; fReceiverNativeAdressTypeAPI.name3 := Value; end; procedure TDHLReceiverNativeAddress.setStreetName(const Value: string); begin fStreetName := Value; fReceiverNativeAdressTypeAPI.streetName := Value; end; procedure TDHLReceiverNativeAddress.setStreetNumber(const Value: string); begin fStreetNumber := Value; fReceiverNativeAdressTypeAPI.streetNumber := value; end; procedure TDHLReceiverNativeAddress.setZip(const Value: string); begin fZip := Value; fReceiverNativeAdressTypeAPI.zip := Value; end; end.
{ @abstract Implements localization routines. The routines are grouped into following static classes: @link(TNtResource), @link(TNtLocale) and @link(TNtMap). These routines are low level routines. Normally you do not call them but you use @link(TNtLanguageDialog.Select) to change a language. However if you want to build your own user interface to select a new language you have to use routines of this unit. See @italic(Samples\Delphi\VCL\CustomSelect) or @italic(Samples\Delphi\FMX\CustomSelect) samples to see how to use the unit. } unit NtLocalization; {$I NtVer.inc} interface uses Windows, Classes, NtBase; const { Procedure address data size. } PROCEDURE_DATA_SIZE = 6; type { @abstract Static class that manipulates resource DLLs. } TNtResource = class public { Get the locale of the currently loaded resources. @return The locale code. } class function GetActiveLocale: String; { Check if the version of the loaded resource DLL matches the version of the application. @return @true if the version match, @false if not. } class function DoesVersionMatch: Boolean; overload; { Check if the version of given resource instance matches the version of the application. @return @true if the version match, @false if not. } class function DoesVersionMatch(resInstance: THandle): Boolean; overload; { Check if the version of resource DLL of the give language code matches the version of the application. @return @true if the version match, @false if not. } class function DoesLocaleVersionMatch(const code: String): Boolean; { Check if the version of resource DLL of the given DLL file matches the version of the application. @return @true if the version match, @false if not. } class function DoesLocaleVersionMatchFile(const fileName: String): Boolean; end; { @abstract Static class that contains locale routines. } TNtLocale = class private class function GetPreviousLocale: String; public class procedure CheckLocaleVariables; class procedure UpdateFormatSettings(locale: String); overload; class procedure UpdateFormatSettings(locale: Integer); overload; { Convert resource DLL extension into to locale id. @param value Extension to be converted. It can be with or without leading period. @return Locale id. } class function ExtensionToLocale(const value: String): Integer; { Get the code page matching the given locale id. @param locale Locale to be checked. @return Code page. } class function LocaleToCodePage(locale: Integer): Integer; { Convert locale id into ISO code. @param locale Locale to be converted. @return ISO code. } class function LocaleToIso639(locale: Integer): String; { Check if the active locale is Asian. @return @true if the previous active is Asian, @false if not. } class function IsActiveLocaleAsian: Boolean; { Check if the active locale is bi-directional. @return @true if the previous active is bi-directional, @false if not. } class function IsActiveLocaleBidi: Boolean; { Check if the previous locale was bi-directional. @return @true if the previous locale was bi-directional, @false if not. } class function IsPreviousLocaleBidi: Boolean; { Get the language or locale of the form. @return Language or locale id. If 0 the form locale is neutral. } class function GetFormLocale: Integer; { Check if the locale is Asian. @param locale Locale to be checked. @return @true if the locale is Asian, @false if not. } class function IsLocaleAsian(value: String): Boolean; { Check if the locale is bi-directional. @param locale Locale to be checked. @return @true if the locale is bi-directional, @false if not. } class function IsLocaleBidi(value: String): Boolean; { Convert locale id into ISO code. It contains language code and optional country code separated by - character. @param locale Locale to be converted. @return ISO code. } class function LocaleToIso(locale: Integer): String; end; { @abstract Record that stores information about function pointer. } TNtProcedureData = record Address: Pointer; Data: array[0..PROCEDURE_DATA_SIZE] of Byte; end; { @abstract Static class that contains routines for function mapping. } TNtMap = class public { Replace a function with another. This has effection only on 32-bit applications. @param oldProc Pointer to exisiting function. @param newProc Pointer to a new function that replaces the old one. @param data Structure that stores information of the replaced function. } class procedure RemapProcedure(oldProc, newProc: Pointer; var data: TNtProcedureData); { Restores a replaced function. This has effection only on 32-bit applications. @param data Structure that stores information of the replaced function. } class procedure RestoreProcedure(data: TNtProcedureData); end; implementation uses SysUtils, Registry; var FFormResourceLocale: Integer; type TVersionInfo = record wLength: Word; wValueLength: Word; wType: Word; szKey: array[0..14] of WideChar; padding1: array[0..1] of Word; value: TVSFixedFileInfo; padding2: array[0..1] of Word; end; PVersionInfo = ^TVersionInfo; {$IFNDEF DELPHIXE5} function EnumEraNames(names: PChar): Integer; stdcall; var i: Integer; begin Result := 0; i := Low(EraNames); while EraNames[I] <> '' do begin if (i = High(EraNames)) then Exit else Inc(i); end; EraNames[i] := names; Result := 1; end; function EnumEraYearOffsets(yearOffsets: PChar): Integer; stdcall; var i: Integer; begin Result := 0; i := Low(EraYearOffsets); while EraYearOffsets[i] <> -1 do begin if (i = High(EraYearOffsets)) then Exit else Inc(I); end; EraYearOffsets[i] := StrToIntDef(yearOffsets, 0); Result := 1; end; {$ENDIF} class function TNtLocale.LocaleToCodePage(locale: Integer): Integer; begin if locale = LANG_CHINESE then Result := 936 else Result := StrToInt(GetLocaleStr(locale, LOCALE_IDEFAULTANSICODEPAGE, '0')); end; class function TNtLocale.LocaleToIso639(locale: Integer): String; begin Result := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, ''); if TNtBase.LocaleToSub(locale) <> SUBLANG_NEUTRAL then Result := Result + LOCALE_SEPARATOR + GetLocaleStr(locale, LOCALE_SISO3166CTRYNAME, ''); end; {$IFNDEF UNICODE} function CharInSet(c: AnsiChar; const charSet: TSysCharSet): Boolean; begin Result := c in charSet; end; {$ENDIF} function TranslateDateFormat( locale: Integer; const formatStr: String): String; var i, l: Integer; calendarType: CALTYPE; begin //FI:C101 i := 1; Result := ''; calendarType := StrToIntDef(GetLocaleStr(locale, LOCALE_ICALENDARTYPE, '1'), 1); if not (calendarType in [CAL_JAPAN, CAL_TAIWAN, CAL_KOREA]) then begin if SysLocale.PriLangID in [LANG_JAPANESE, LANG_CHINESE, LANG_KOREAN] then begin while i <= Length(formatStr) do begin if not CharInSet(formatStr[i], ['g', 'G']) then Result := Result + formatStr[i]; Inc(i); end; end else Result := formatStr; Exit; end; while i <= Length(formatStr) do begin if CharInSet(formatStr[i], LeadBytes) then begin l := CharLength(formatStr, i); Result := Result + Copy(formatStr, i, l); Inc(i, l); end else begin if StrLIComp(@formatStr[i], 'gg', 2) = 0 then begin Result := Result + 'ggg'; Inc(i, 1); end else if StrLIComp(@formatStr[i], 'yyyy', 4) = 0 then begin Result := Result + 'eeee'; Inc(i, 4 - 1); end else if StrLIComp(@formatStr[i], 'yy', 2) = 0 then begin Result := Result + 'ee'; Inc(i, 2 - 1); end else if CharInSet(formatStr[i], ['y', 'Y']) then Result := Result + 'e' else Result := Result + formatStr[i]; Inc(i); end; end; end; {$IFNDEF DELPHI2006} function LcidToCodePage(locale: LCID): Integer; var buffer: array [0..6] of Char; begin GetLocaleInfo(locale, LOCALE_IDEFAULTANSICODEPAGE, buffer, SizeOf(buffer)); Result:= StrToIntDef(buffer, GetACP); end; procedure InitSysLocale(locale: Integer); var i: Integer; defaultLangID: LANGID; ansiCPInfo: TCPInfo; pcharA: PAnsiChar; bufferA: array[128..255] of Char; bufferW: array[128..256] of Word; procedure InitLeadBytes; var i: Integer; j: Byte; begin GetCPInfo(LcidToCodePage(SysLocale.DefaultLCID), ansiCPInfo); with ansiCPInfo do begin i := 0; while (i < MAX_LEADBYTES) and ((LeadByte[i] or LeadByte[i + 1]) <> 0) do begin for j := LeadByte[i] to LeadByte[i + 1] do Include(LeadBytes, Char(j)); Inc(i, 2); end; end; end; function IsWesternGroup: Boolean; type TLanguage = $00..$1D; const NEUTRAL = TLanguage($00); DANISH = TLanguage($06); DUTCH = TLanguage($13); ENGLISH = TLanguage($09); FINNISH = TLanguage($0B); FRENCH = TLanguage($0C); GERMAN = TLanguage($07); ITALIAN = TLanguage($10); NORWEGIAN = TLanguage($14); PORTUGUSE = TLanguage($16); SPANISH = TLanguage($0A); SWEDISH = TLanguage($1D); begin Result := SysLocale.PriLangID in [ NEUTRAL, DANISH, DUTCH, ENGLISH, FINNISH, FRENCH, GERMAN, ITALIAN, NORWEGIAN, PORTUGUSE, SPANISH, SWEDISH ]; end; begin SysLocale.DefaultLCID := $0409; SysLocale.PriLangID := LANG_ENGLISH; SysLocale.SubLangID := SUBLANG_ENGLISH_US; if locale <> 0 then SysLocale.DefaultLCID := locale; defaultLangID := Word(locale); if defaultLangID <> 0 then begin SysLocale.PriLangID := defaultLangID and $03FF; SysLocale.SubLangID := defaultLangID shr 10; end; LeadBytes := []; if Win32Platform = VER_PLATFORM_WIN32_NT then begin if IsWesternGroup then begin SysLocale.MiddleEast := False; SysLocale.FarEast := False; end else begin InitLeadBytes; SysLocale.FarEast := LeadBytes <> []; if SysLocale.FarEast then begin SysLocale.MiddleEast := False; Exit; end; for i := Low(bufferA) to High(bufferA) do bufferA[I] := Char(i); pcharA := @bufferA; GetStringTypeExA( SysLocale.DefaultLCID, CT_CTYPE2, pcharA, High(bufferA) - Low(bufferA) + 1, bufferW); for i := Low(bufferA) to High(bufferA) do begin SysLocale.MiddleEast := bufferW[i] = C2_RIGHTTOLEFT; if SysLocale.MiddleEast then Exit; end; end; end else begin SysLocale.MiddleEast := GetSystemMetrics(SM_MIDEASTENABLED) <> 0; SysLocale.FarEast := GetSystemMetrics(SM_DBCSENABLED) <> 0; if SysLocale.FarEast then InitLeadBytes; end; end; {$ENDIF} class procedure TNtLocale.CheckLocaleVariables; begin if LoadedResourceLocale <> '' then UpdateFormatSettings(ExtensionToLocale(LoadedResourceLocale)); end; class procedure TNtLocale.UpdateFormatSettings(locale: String); begin if locale = '' then locale := DefaultLocale; UpdateFormatSettings(TNtLocale.ExtensionToLocale(locale)); end; class procedure TNtLocale.UpdateFormatSettings(locale: Integer); function LocalGetLocaleStr(localeType: Integer; const default: String): String; begin Result := GetLocaleStr(locale, localeType, default); end; var i, day: Integer; hourFormat, timePrefix, timePostfix: String; {$IFNDEF DELPHIXE5} j: Integer; calendarType: CALTYPE; {$ENDIF} begin //FI:C101 if locale = LANG_CHINESE then locale := TNtBase.MakeLangId(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED); {$IFNDEF DELPHI2006} InitSysLocale(locale); {$ENDIF} {$IFNDEF DELPHIXE5} if SysLocale.FarEast then begin calendarType := StrToIntDef(GetLocaleStr( locale, LOCALE_IOPTIONALCALENDAR, '1'), 1); if calendarType in [CAL_JAPAN, CAL_TAIWAN, CAL_KOREA] then begin EnumCalendarInfo(@EnumEraNames, locale, calendarType, CAL_SERASTRING); for j := Low(EraYearOffsets) to High(EraYearOffsets) do EraYearOffsets[j] := -1; EnumCalendarInfo( @EnumEraYearOffsets, locale, CalendarType, CAL_IYEAROFFSETRANGE); end; end; {$ENDIF} for i := 1 to 12 do begin {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ShortMonthNames[i] := LocalGetLocaleStr( LOCALE_SABBREVMONTHNAME1 + i - 1, {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ShortMonthNames[i]); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}LongMonthNames[i] := LocalGetLocaleStr( LOCALE_SMONTHNAME1 + i - 1, {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}LongMonthNames[i]); end; for i := 1 to 7 do begin day := (I + 5) mod 7; {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ShortDayNames[i] := LocalGetLocaleStr( LOCALE_SABBREVDAYNAME1 + day, {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ShortDayNames[i]); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}LongDayNames[i] := LocalGetLocaleStr( LOCALE_SDAYNAME1 + day, {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}LongDayNames[i]); end; {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}CurrencyString := GetLocaleStr(locale, LOCALE_SCURRENCY, ''); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}CurrencyFormat := StrToIntDef(GetLocaleStr(locale, LOCALE_ICURRENCY, '0'), 0); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}NegCurrFormat := StrToIntDef(GetLocaleStr(locale, LOCALE_INEGCURR, '0'), 0); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ThousandSeparator := GetLocaleChar(locale, LOCALE_STHOUSAND, ','); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}DecimalSeparator := GetLocaleChar(locale, LOCALE_SDECIMAL, '.'); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}CurrencyDecimals := StrToIntDef(GetLocaleStr(locale, LOCALE_ICURRDIGITS, '0'), 0); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}DateSeparator := GetLocaleChar(locale, LOCALE_SDATE, '/'); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ShortDateFormat := TranslateDateFormat( locale, GetLocaleStr(locale, LOCALE_SSHORTDATE, 'm/d/yy')); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}LongDateFormat := TranslateDateFormat( locale, GetLocaleStr(locale, LOCALE_SLONGDATE, 'mmmm d, yyyy')); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}TimeSeparator := GetLocaleChar(locale, LOCALE_STIME, ':'); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}TimeAMString := GetLocaleStr(locale, LOCALE_S1159, 'am'); {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}TimePMString := GetLocaleStr(locale, LOCALE_S2359, 'pm'); TimePrefix := ''; TimePostfix := ''; if StrToIntDef(GetLocaleStr(locale, LOCALE_ITLZERO, '0'), 0) = 0 then HourFormat := 'h' else HourFormat := 'hh'; if StrToIntDef(GetLocaleStr(locale, LOCALE_ITIME, '0'), 0) = 0 then begin if StrToIntDef(GetLocaleStr(locale, LOCALE_ITIMEMARKPOSN, '0'), 0) = 0 then TimePostfix := ' AMPM' else TimePrefix := 'AMPM '; end; {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ShortTimeFormat := TimePrefix + HourFormat + ':mm' + TimePostfix; {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}LongTimeFormat := TimePrefix + HourFormat + ':mm:ss' + TimePostfix; {$IFDEF DELPHIXE}FormatSettings.{$ENDIF}ListSeparator := GetLocaleChar(locale, LOCALE_SLIST, ','); FirstDayOfWeek := TNtDayOfWeek(StrToInt(GetLocaleStr( locale, LOCALE_IFIRSTDAYOFWEEK, '0'))); FirstWeekOfYear := TNtFirstWeekOfYear(StrToInt(GetLocaleStr( locale, LOCALE_IFIRSTWEEKOFYEAR, '0'))); end; function GetLocaleStr(locale, localeType: Integer; const default: UnicodeString): UnicodeString; var l: Integer; buffer: array[0..255] of WideChar; begin l := GetLocaleInfoW(locale, localeType, buffer, SizeOf(buffer)); if l > 0 then SetString(Result, buffer, l - 1) else Result := default; end; var enumLocale: Integer; enumExtension: String; function LocaleEnumProc(localeString: PChar): Integer; stdcall; var locale: Integer; str, extension1:String; {$IFDEF DELPHI2010} extension2: String; {$ENDIF} begin str := localeString; locale := StrToInt('$' + str); extension1 := GetLocaleStr(locale, LOCALE_SABBREVLANGNAME, ''); {$IFDEF DELPHI2010} extension2 := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, '') + '-' + GetLocaleStr(locale, LOCALE_SISO3166CTRYNAME, ''); {$ENDIF} if SameText(extension1, enumExtension) {$IFDEF DELPHI2010}or SameText(extension2, enumExtension){$ENDIF} then begin enumLocale := locale; Result := 0; end else Result := 1; end; function LanguageEnumProc(localeString: PChar): Integer; stdcall; var locale: Integer; str, extension1:String; {$IFDEF DELPHI2010} extension2: String; {$ENDIF} begin str := localeString; locale := StrToInt('$' + str); extension1 := GetLocaleStr(locale, LOCALE_SABBREVLANGNAME, ''); Delete(extension1, Length(extension1), 1); {$IFDEF DELPHI2010} extension2 := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, ''); {$ENDIF} if SameText(extension1, enumExtension) {$IFDEF DELPHI2010}or SameText(extension2, enumExtension){$ENDIF} then begin enumLocale := TNtBase.LocaleToPrimary(locale); Result := 0; end else Result := 1; end; class function TNtLocale.ExtensionToLocale(const value: String): Integer; begin Result := 0; if value = '' then Exit; enumExtension := value; if enumExtension[1] = '.' then Delete(enumExtension, 1, 1); enumLocale := 0; EnumSystemLocales(@LocaleEnumProc, LCID_SUPPORTED); if enumLocale = 0 then EnumSystemLocales(@LanguageEnumProc, LCID_SUPPORTED); Result := enumLocale; end; class function TNtResource.GetActiveLocale: String; begin if TNtBase.IsLoaded then Result := LoadedResourceLocale else Result := TNtLocale.LocaleToIso(TNtLocale.GetFormLocale); if Result = '' then Result := DefaultLocale; end; var languageIds: TList; function EnumResourceLanguagesProc( instance: THandle; //FI:O804 resType: PChar; //FI:O804 resName: PChar; //FI:O804 languageId: Word; param: DWord): Bool; stdcall; //FI:O804 begin languageIds.Add(Pointer(languageId)); Result := True; end; function EnumResourceNamesProc( instance: THandle; resType: PChar; resName: PChar; param: DWord): Bool; stdcall; //FI:O804 var i, id, windowsLocale: Integer; reader: TReader; stream: TResourceStream; header: array[0..3] of AnsiChar; begin //FI:C101 Result := True; stream := TResourceStream.Create(instance, resName, resType); reader := TReader.Create(stream, stream.Size); try if stream.Size < 4 then Exit; reader.Read(header, 4); if header = VCL_FORM_HEADER then begin languageIds := TList.Create; try EnumResourceLanguages(HInstance, resType, resName, @EnumResourceLanguagesProc, 0); if languageIds.Count > 0 then begin Result := False; if languageIds.Count = 1 then FFormResourceLocale := Integer(languageIds[0]) else begin windowsLocale := TNtBase.GetUserLanguage; for i := 0 to languageIds.Count - 1 do begin id := Integer(languageIds[i]); if windowsLocale = id then begin FFormResourceLocale := id; Exit; end; end; windowsLocale := TNtBase.LocaleToPrimary(TNtBase.GetUserLanguage); for i := 0 to languageIds.Count - 1 do begin id := Integer(languageIds[i]); if windowsLocale = id then begin FFormResourceLocale := id; Exit; end; end; end; end; finally languageIds.Free; end; end; finally reader.Free; stream.Free; end; end; class function TNtLocale.GetFormLocale: Integer; begin if FFormResourceLocale = 0 then EnumResourceNames(HInstance, PChar(RT_RCDATA), @EnumResourceNamesProc, 0); Result := FFormResourceLocale; end; class function TNtLocale.IsActiveLocaleBidi: Boolean; begin Result := IsLocaleBiDi(TNtResource.GetActiveLocale); end; class function TNtLocale.GetPreviousLocale: String; begin if PreviouslyLoadedResourceLocale <> '' then Result := PreviouslyLoadedResourceLocale else Result := TNtbase.LocaleToExtension(GetFormLocale); end; class function TNtLocale.IsPreviousLocaleBidi: Boolean; begin Result := IsLocaleBiDi(GetPreviousLocale); end; class function TNtLocale.IsActiveLocaleAsian: Boolean; begin Result := IsLocaleAsian(TNtResource.GetActiveLocale); end; var enumFound: Boolean; enumVersion1, enumVersion2, enumVersion3, enumVersion4: Integer; function EnumEnumVersionProcLanguagesProc( module: THandle; resType: PChar; resName: PChar; language: Word; //FI:O804 param: Integer): Bool; stdcall; //FI:O804 var resource: HRSRC; versionInfo: PVersionInfo; begin resource := FindResource(module, resName, resType); versionInfo := LockResource(LoadResource(module, resource)); enumVersion1 := versionInfo.value.dwFileVersionMS shr 16; enumVersion2 := $FF and versionInfo.value.dwFileVersionMS; enumVersion3 := versionInfo.value.dwFileVersionLS shr 16; enumVersion4 := $FF and versionInfo.value.dwFileVersionLS; enumFound := True; Result := Bool(0); end; function EnumVersionProc( module: THandle; resType: PChar; resName: PChar; param: Integer): Bool; stdcall; //FI:O804 begin EnumResourceLanguages(module, resType, resName, @EnumEnumVersionProcLanguagesProc, 0); Result := Bool(0); end; class function TNtResource.DoesVersionMatch(resInstance: THandle): Boolean; var exeVersion1, exeVersion2, exeVersion3, exeVersion4: Integer; begin Result := True; enumFound := False; EnumResourceNames(HInstance, RT_VERSION, @EnumVersionProc, 0); if not enumFound then Exit; exeVersion1 := enumVersion1; exeVersion2 := enumVersion2; exeVersion3 := enumVersion3; exeVersion4 := enumVersion4; enumFound := False; EnumResourceNames(resInstance, RT_VERSION, @EnumVersionProc, 0); if not enumFound then Exit; Result := (exeVersion1 = enumVersion1) and (exeVersion2 = enumVersion2) and (exeVersion3 = enumVersion3) and (exeVersion4 = enumVersion4); end; class function TNtResource.DoesVersionMatch: Boolean; begin if TNtBase.IsLoaded then Result := DoesVersionMatch(LibModuleList.ResInstance) else Result := True; end; class function TNtResource.DoesLocaleVersionMatch(const code: String): Boolean; var instance: THandle; begin instance := LoadLibraryEx( PChar(TNtBase.GetLanguageFile(TNtBase.GetRunningFileName, code)), 0, LOAD_LIBRARY_AS_DATAFILE); try Result := DoesVersionMatch(instance); finally FreeLibrary(instance); end; end; class function TNtResource.DoesLocaleVersionMatchFile(const fileName: String): Boolean; var instance: THandle; begin instance := LoadLibraryEx( PChar(fileName), 0, LOAD_LIBRARY_AS_DATAFILE); try Result := DoesVersionMatch(instance); finally FreeLibrary(instance); end; end; procedure SetInitialResourceLocale; function CheckLocale(fileName: String; locale: String; tryPrimary: Boolean): String; var ext: String; begin ext := '.' + locale; if FileExists(ChangeFileExt(fileName, ext)) then Result := locale else if (Length(locale) > 2) or tryPrimary then begin Delete(ext, Length(ext), 1); if FileExists(ChangeFileExt(fileName, ext)) then begin Result := locale; Delete(Result, Length(Result), 1); end else Result := ''; end else Result := ''; end; {$IFDEF DELPHI2010} function CheckLocales(fileName: String; locales: String): String; var p, lang: PChar; begin p := PChar(locales); while p^ <> #0 do begin lang := p; while (p^ <> ',') and (p^ <> #0) do Inc(p); if p^ = ',' then begin p^ := #0; Inc(p); end; Result := CheckLocale(fileName, lang, False); if Result <> '' then begin Result := UpperCase(Result); Exit; end; end; Result := ''; end; {$ENDIF} var buffer: array[0..260] of Char; begin PreviouslyLoadedResourceLocale := ''; if (LoadedResourceLocale = '') and (GetModuleFileName(LibModuleList.Instance, buffer, SizeOf(buffer)) > 0) then begin {$IFDEF DELPHIXE} LoadedResourceLocale := GetLocaleOverride(buffer); {$ELSE} LoadedResourceLocale := CheckLocale(buffer, TNtLocaleRegistry.GetCurrentDefaultLocale, False); if LoadedResourceLocale <> '' then Exit; {$IFDEF DELPHI2010} LoadedResourceLocale := CheckLocales(buffer, GetUILanguages(GetUserDefaultUILanguage)); if LoadedResourceLocale <> '' then Exit; if (GetVersion and $000000FF) < 6 then LoadedResourceLocale := CheckLocales(buffer, GetUILanguages(GetSystemDefaultUILanguage)); if LoadedResourceLocale <> '' then Exit; LoadedResourceLocale := CheckLocale(buffer, TNtBase.LocaleToExtension(GetUserDefaultUILanguage), True); {$ELSE} LoadedResourceLocale := CheckLocale(buffer, TNtBase.LocaleToExtension(GetThreadLocale), True); {$ENDIF} {$ENDIF} end; end; class function TNtLocale.IsLocaleBidi(value: String): Boolean; begin if Length(value) > 2 then value := Copy(value, 1, 2); value := LowerCase(value); Result := (value = 'ar') or (value = 'he') or (value = 'fa'); end; class function TNtLocale.IsLocaleAsian(value: String): Boolean; begin if Length(value) > 2 then value := Copy(value, 1, 2); value := LowerCase(value); Result := (value = 'jp') or (value = 'ch') or (value = 'ko'); end; class function TNtLocale.LocaleToIso(locale: Integer): String; begin if locale = 0 then Result := '' else begin Result := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, ''); if TNtBase.LocaleToSub(locale) <> SUBLANG_NEUTRAL then Result := Result + '_' + GetLocaleStr(locale, LOCALE_SISO3166CTRYNAME, ''); end; end; // TNtMap class procedure TNtMap.RemapProcedure(oldProc, newProc: Pointer; var data: TNtProcedureData); {$IFDEF WIN32} var i: Integer; p: Pointer; protect1, protect2: DWord; address: PAnsiChar; {$ENDIF} begin {$IFDEF WIN32} if data.Address <> nil then Exit; if not VirtualProtect(oldProc, PROCEDURE_DATA_SIZE, PAGE_EXECUTE_READWRITE, @protect1) then RaiseLastOSError; p := oldProc; if Word(p^) = $25FF then begin Inc(Integer(p), 2); p := Pointer(Pointer(p^)^); if not VirtualProtect(oldProc, PROCEDURE_DATA_SIZE, protect1, @protect2) then RaiseLastOSError; oldProc := p; if not VirtualProtect(oldProc, PROCEDURE_DATA_SIZE, PAGE_EXECUTE_READWRITE, @protect1) then RaiseLastOSError; end; Move(oldProc^, data.Data, PROCEDURE_DATA_SIZE); data.Address := oldProc; i := NativeInt(newProc) - NativeInt(p) - PROCEDURE_DATA_SIZE + 1; address := PAnsiChar(oldProc); address[0] := AnsiChar($E9); address[1] := AnsiChar(i and 255); address[2] := AnsiChar((i shr 8) and 255); address[3] := AnsiChar((i shr 16) and 255); address[4] := AnsiChar((i shr 24) and 255); if not VirtualProtect(address, PROCEDURE_DATA_SIZE, protect1, @protect2) then RaiseLastOSError; {$ENDIF} end; class procedure TNtMap.RestoreProcedure(data: TNtProcedureData); {$IFDEF WIN32} var protect1, protect2: Cardinal; {$ENDIF} begin {$IFDEF WIN32} if data.Address = nil then Exit; if not VirtualProtect(data.Address, PROCEDURE_DATA_SIZE, PAGE_EXECUTE_READWRITE, @protect1) then RaiseLastOSError; Move(data.Data, data.Address^, PROCEDURE_DATA_SIZE); if not VirtualProtect(data.Address, PROCEDURE_DATA_SIZE, protect1, @protect2) then RaiseLastOSError; {$ENDIF} end; initialization FFormResourceLocale := 0; SetInitialResourceLocale; end.
unit NewFrontiers.Tapi; interface type /// <summary> /// Der Record TTapiResult kapselt Ergebnisse einer Operation. Tritt ein /// Fehler auf, wird der Fehler in der Eigenschaft error zur Verfügung /// gestellt. /// </summary> TTapiResult = record /// <summary> /// true, falls der Aufruf erfolgreich war /// </summary> result: boolean; /// <summary> /// Schlug der Aufruf fehl, steht in error der Fehlergrund /// </summary> error: string; end; /// <summary> /// Interface für die verschiedenen TapiProvider implementierunngen. Der /// Aufruf der Funktionen wird von der konkerten Implementierung getrennt /// </summary> ITapiProvider = interface /// <summary> /// Tätigt einen Anruf über das eingestellte Gerät /// </summary> function anrufen(aNummer: string): TTapiResult; end; /// <summary> /// Klasse, die die Tapi-Dienstleistungen zur Verfügung stellt /// </summary> TTapi = class private _provider: ITapiProvider; public property Provider: ITapiProvider read _provider write _provider; class function normalisieren(aNummer: string): string; end; implementation uses System.SysUtils; { TTapi } class function TTapi.normalisieren(aNummer: string): string; var i: integer; begin result := ''; for i := 1 to length(aNummer) do begin if (CharInSet(aNummer[i], ['0' .. '9'])) then result := result + aNummer[i] else if (aNummer[i] = '+') then result := result + '00'; end; end; end.
//*********************************************************************** //* Проект "Студгородок" * //* Справочник категорий - добавление источников финансирования * //*********************************************************************** unit uPrices_services_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxTextEdit, cxLabel, cxControls, cxContainer, cxEdit, cxGroupBox, cxCurrencyEdit, cxMaskEdit, cxButtonEdit, uPrices_DM, GlobalSPR, DB, FIBDataSet, pFIBDataSet, ActnList, Math, st_ConstUnit, st_common_funcs, iBase, st_common_types, st_common_loader, st_Consts_Messages, cxCheckBox, cxDropDownEdit; type TfrmPrices_services_AE = class(TForm) cxGroupBox1: TcxGroupBox; OKButton: TcxButton; CancelButton: TcxButton; ReadDataSet: TpFIBDataSet; Category_ActionList: TActionList; Add_Action: TAction; Edit_Action: TAction; Delete_Action: TAction; Ok_Action: TAction; cxLabel7: TcxLabel; serves_ButtonEdit: TcxButtonEdit; cxLabel3: TcxLabel; Smeta_Edit: TcxButtonEdit; Smeta_Label: TcxLabel; cxLabel2: TcxLabel; KEKV_Edit: TcxButtonEdit; kekv_Label: TcxLabel; ComboBox_type_norm: TcxComboBox; cxLabel1: TcxLabel; procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OKButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Persent_Subs_EditKeyPress(Sender: TObject; var Key: Char); procedure Smeta_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure Smeta_EditPropertiesEditValueChanged(Sender: TObject); procedure Kekv_EditKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure serves_ButtonEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure KEKV_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure KEKV_EditPropertiesEditValueChanged(Sender: TObject); procedure serves_ButtonEditKeyPress(Sender: TObject; var Key: Char); private Cur_date: string; PLanguageIndex: byte; //CURRENT_TIMESTAMP : TDateTime; procedure FormIniLanguage(); public id_smeta : int64; id_kekv : Int64; is_admin : Boolean; aHandle : TISC_DB_HANDLE; id_serves : Int64; id_type_norma : Int64; id_options : Int64; sm_kod, kekv_kod : string; date_beg, date_end : tdate; DM : Tfrm_price_DM; end; var frmPrices_services_AE: TfrmPrices_services_AE; const kav = ''''; // это кавычки implementation {$R *.dfm} procedure TfrmPrices_services_AE.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) PLanguageIndex:= stLanguageIndex; //названия кнопок OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex]; CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex]; // смета cxLabel3.Caption := st_ConstUnit.st_Smeta[PLanguageIndex]; end; procedure TfrmPrices_services_AE.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmPrices_services_AE.FormClose(Sender: TObject; var Action: TCloseAction); begin // Action := caFree; end; procedure TfrmPrices_services_AE.OKButtonClick(Sender: TObject); begin if serves_ButtonEdit.Text = '' then begin ShowMessage('Неодхідно обрати послугу!'); serves_ButtonEdit.SetFocus; Exit; end; if Smeta_Edit.Text = '' then begin ShowMessage(pchar(st_ConstUnit.st_2[PLanguageIndex])); Smeta_Edit.SetFocus; exit; end; if not IntegerCheck(Smeta_Edit.Text) then begin ShowMessage(pchar(st_ConstUnit.st_mess_Code_need[PLanguageIndex])); Smeta_Label.Clear; Smeta_Label.Visible:=false; Smeta_Edit.SetFocus; exit; end; ModalResult := mrOK; end; procedure TfrmPrices_services_AE.FormShow(Sender: TObject); var i : integer; begin serves_ButtonEdit.SetFocus; ReadDataSet.Close; ReadDataSet.SelectSQL.Clear; ReadDataSet.SelectSQL.Text := 'select * from ST_INI_TYPE_NORM'; ReadDataSet.Open; ReadDataSet.FetchAll; ReadDataSet.First; ComboBox_type_norm.Properties.Items.Clear; For i := 0 to ReadDataSet.RecordCount - 1 do Begin ComboBox_type_norm.Properties.Items.Add(ReadDataSet['NAME_TYPE_NORMA']); ReadDataSet.Next; end; if ReadDataSet.RecordCount > 0 then Begin if id_type_norma <> -1 then ComboBox_type_norm.ItemIndex := id_type_norma - 1 else ComboBox_type_norm.ItemIndex := 0; end; ReadDataSet.Close; end; procedure TfrmPrices_services_AE.Persent_Subs_EditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then Smeta_Edit.SetFocus; end; procedure TfrmPrices_services_AE.Smeta_EditPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var id:variant; begin id:=GlobalSPR.GetSmets(self, aHandle, StrToDate(Cur_date), psmRazdSt); if VarArrayDimCount(id)>0 //- проверка на то что id вариантный массив then begin if id[0]<>NULL then begin // id[0] -идентификатор сметы // id[1] -идентификатор раздела // id[2] -идентификатор статьи // id[3] -идентификатор группы смет // id[4] -наименование раздела // id[5] -наименование статьи // id[6] -наименование сметы // id[7] -номер раздела // id[8] -номер статьи // id[9] -код сметы // id[10] -наименование группы смет id_smeta := id[0]; Smeta_Edit.Text:=vartostr(id[9]); Smeta_Label.Caption:=vartostr(id[6]); Smeta_Label.Visible:=true; end; end; end; procedure TfrmPrices_services_AE.Smeta_EditPropertiesEditValueChanged( Sender: TObject); begin if Smeta_Edit.Text = '' then exit; if not IntegerCheck(Smeta_Edit.Text) then begin ShowMessage(pchar(st_ConstUnit.st_NotCorrectCode[PLanguageIndex])); Smeta_Label.Clear; Smeta_Label.Visible:=false; Smeta_Edit.SetFocus; exit; end; ReadDataSet.Close; ReadDataSet.SelectSQL.Clear; ReadDataSet.SelectSQL.Text := 'select ID_OBJECT, TITLE_OBJECT from PUB_GET_NAME_BUDG_BY_KOD ( '+Smeta_Edit.Text+','+kav+Cur_date+kav+',' +'1)'; ReadDataSet.Open; if ReadDataSet['ID_OBJECT']<> null then begin id_smeta := ReadDataSet['ID_OBJECT']; if ReadDataSet['TITLE_OBJECT']<> null then begin Smeta_Label.Caption:= ReadDataSet['TITLE_OBJECT']; Smeta_Label.Visible:=true; sm_kod := Smeta_Edit.Text; end else begin Smeta_Label.Clear; Smeta_Label.Visible:=false; sm_kod := ''; end end else begin ShowMessage(pchar(st_ConstUnit.st_NotCorrectSmeta[PLanguageIndex])); Smeta_Label.Clear; Smeta_Label.Visible:=false; Smeta_Edit.SetFocus; ReadDataSet.Close; exit; end; ReadDataSet.Close; end; procedure TfrmPrices_services_AE.Kekv_EditKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then OKButton.SetFocus; end; procedure TfrmPrices_services_AE.FormCreate(Sender: TObject); begin ReadDataSet.Close; ReadDataSet.SelectSQL.Clear; ReadDataSet.SelectSQL.Text := 'select CUR_DATE from ST_GET_CURRENT_DATE'; ReadDataSet.Open; Cur_date:= ReadDataSet['CUR_DATE']; ReadDataSet.Close; FormIniLanguage(); end; procedure TfrmPrices_services_AE.serves_ButtonEditPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var aParameter : TstSimpleParams; res : Variant; begin aParameter := TstSimpleParams.Create; aParameter.Owner := self; aParameter.Db_Handle := aHandle; AParameter.Formstyle := fsNormal; AParameter.WaitPakageOwner := self; aParameter.is_admin := is_admin; res := RunFunctionFromPackage(aParameter, 'Studcity\st_services.bpl', 'getServices'); If VarArrayDimCount(res) <> 0 then begin id_serves := res[0]; serves_ButtonEdit.Text := res[1]; id_options := res[3]; end; aParameter.Free; end; procedure TfrmPrices_services_AE.KEKV_EditPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var id:variant; begin id := GlobalSPR.GetKEKVSpr(self, aHandle, FSNormal, StrToDate(Cur_date), DEFAULT_ROOT_ID); if VarArrayDimCount(id)>0 //- проверка на то что id вариантный массив then begin if VarArrayDimCount(id) > 0 then begin if id[0][0] <> NULL then begin // id[0][0] - идентификатор КЕКВа // id[0][1] - наименование КЕКВа // id[0][2] - код КЕКВа ID_KEKV := id[0][0]; Kekv_Edit.Text := id[0][2]; kekv_Label.Caption := id[0][1]; kekv_Label.Visible := True; end; end; end; end; procedure TfrmPrices_services_AE.KEKV_EditPropertiesEditValueChanged( Sender: TObject); begin if Kekv_Edit.Text= '' then exit; if not IntegerCheck(Kekv_Edit.Text) then begin ShowMessage('Введен неверный код.'); kekv_Label.Clear; Kekv_Label.Visible:=false; Kekv_Edit.SetFocus; exit; end; ReadDataSet.Close; ReadDataSet.SQLs.SelectSQL.Text := 'select ID_KEKV, KEKV_TITLE from PUB_SPR_KEKV_INFO_EX2 ( '+Kekv_Edit.Text+','+kav + Cur_date+kav+')'; ReadDataSet.Open; If ReadDataSet['ID_KEKV'] <> null then begin ID_KEKV := ReadDataSet['ID_KEKV']; if ReadDataSet['KEKV_TITLE']<> null then begin Kekv_Label.Caption:= ReadDataSet['KEKV_TITLE']; Kekv_Label.Visible:=true; kekv_kod := KEKV_Edit.Text; end else begin Kekv_Label.Clear; Kekv_Label.Visible:=false; kekv_kod := ''; end end else begin ShowMessage(st_Consts_Messages.st_warningVvod_Kekv[PLanguageIndex]); Kekv_Label.Clear; Kekv_Label.Visible:=false; Kekv_Edit.SetFocus; ReadDataSet.close; exit; end; ReadDataSet.close; end; procedure TfrmPrices_services_AE.serves_ButtonEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Smeta_Edit.SetFocus; end; end.
unit ufrmDialogMerchandiseGroup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, StdCtrls, ufraFooterDialog2Button, ExtCtrls, uNewMerchandize, uRetnoUnit, System.Actions, Vcl.ActnList, ufraFooterDialog3Button ; type TFormMode = (fmAdd, fmEdit); TfrmDialogMerchandiseGroup = class(TfrmMasterDialog) procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure footerDialogMasterbtnSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private FIsProcessSuccessfull: boolean; FFormMode: TFormMode; FnewMerchan: TNewMerchadize; FMerchanGroupId: integer; IDLokal: Integer; procedure SetFormMode(const Value: TFormMode); procedure SetIsProcessSuccessfull(const Value: boolean); procedure SetMerchanGroupId(const Value: integer); procedure prepareAddData; public procedure LoadListCbpPpn; { Public declarations } published property FormMode: TFormMode read FFormMode write SetFormMode; property MerchanGroupId: integer read FMerchanGroupId write SetMerchanGroupId; property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull; end; var frmDialogMerchandiseGroup: TfrmDialogMerchandiseGroup; implementation uses uTSCommonDlg, ufrmMerchandiseGroup; {$R *.dfm} procedure TfrmDialogMerchandiseGroup.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogMerchandiseGroup.FormDestroy(Sender: TObject); begin inherited; frmDialogMerchandiseGroup := nil; end; procedure TfrmDialogMerchandiseGroup.SetFormMode(const Value: TFormMode); begin FFormMode := Value; end; procedure TfrmDialogMerchandiseGroup.SetIsProcessSuccessfull( const Value: boolean); begin FIsProcessSuccessfull := Value; end; procedure TfrmDialogMerchandiseGroup.footerDialogMasterbtnSaveClick( Sender: TObject); var aPajak_ID: Integer; begin if edtCode.Text = '' then begin CommonDlg.ShowError('Kode Belum didisi'); edtCode.SetFocus; Exit; end; if edtName.Text = '' then begin CommonDlg.ShowError('Nama Belum diisi'); edtName.SetFocus; Exit; end; if FnewMerchan.isKodeExits(edtCode.Text, FnewMerchan.ID) then begin CommonDlg.ShowError('Code ' + edtCode.Text + ' Sudah Ada'); edtCode.SetFocus; Exit; end; aPajak_ID := cGetIDfromCombo(cbbPpn); FnewMerchan.UpdateData(IDLokal,edtCode.Text,edtName.Text, aPajak_ID); try if FnewMerchan.ExecuteGenerateSQL then begin cCommitTrans; CommonDlg.ShowMessage(' Data Sudah Disimpan'); frmMerchandiseGroup.actRefreshMerchanGroupExecute(nil); Close; end else begin cRollBackTrans; CommonDlg.ShowMessage('Data gagal disimpan'); Exit; end; finally cRollBackTrans; end; frmMerchandiseGroup.actRefreshMerchanGroupExecute(Sender); { if (FormMode = fmAdd) then begin FIsProcessSuccessfull := SaveMerchanGroup; if FIsProcessSuccessfull then Close; end else begin FIsProcessSuccessfull := UpdateMerchanGroup; if FIsProcessSuccessfull then Close; end; // end if } end; procedure TfrmDialogMerchandiseGroup.SetMerchanGroupId( const Value: integer); begin FMerchanGroupId := Value; end; procedure TfrmDialogMerchandiseGroup.prepareAddData; begin edtCode.Clear; edtName.Clear; end; procedure TfrmDialogMerchandiseGroup.FormShow(Sender: TObject); begin inherited; LoadListCbpPpn; if (FFormMode = fmEdit) then begin IDLokal := MerchanGroupId; if FnewMerchan.LoadByID(IDLokal) then begin edtCode.Text := FnewMerchan.Kode; edtName.Text := FnewMerchan.Nama; cSetItemAtComboObject(cbbPpn, FnewMerchan.PjkId); end end else begin IDLokal := 0; prepareAddData(); end; end; procedure TfrmDialogMerchandiseGroup.FormCreate(Sender: TObject); begin inherited; FnewMerchan := TNewMerchadize.Create(Self); end; procedure TfrmDialogMerchandiseGroup.LoadListCbpPpn; var sSQL: string; begin sSQL := ' SELECT PJK_ID, PJK_NAME ' + ' FROM REF$PAJAK ' + ' ORDER BY PJK_CODE '; cQueryToComboObject(cbbPpn, sSQL); end; end.
unit uFreeImageIO; interface uses Classes, FreeImage; procedure SetStreamFreeImageIO(var IO: FreeImageIO); implementation function StreamFI_ReadProc(buffer: Pointer; size, count: Cardinal; handle: fi_handle): Cardinal; stdcall; begin Result := Cardinal(TStream(handle).Read(buffer^, size * count)); end; function StreamFI_WriteProc(buffer: Pointer; size, count: Cardinal; handle: fi_handle): Cardinal; stdcall; begin Result := TStream(handle).Write(buffer^, size * count); end; function StreamFI_SeekProc(handle: fi_handle; offset: LongInt; origin: Integer): Integer; stdcall; begin Result := TStream(handle).Seek(offset, origin); end; function StreamFI_TellProc(handle: fi_handle): LongInt; stdcall; begin Result := LongInt(TStream(handle).Position); end; procedure SetStreamFreeImageIO(var IO: FreeImageIO); begin IO.read_proc := StreamFI_ReadProc; IO.write_proc := StreamFI_WriteProc; IO.seek_proc := StreamFI_SeekProc; IO.tell_proc := StreamFI_TellProc; end; end.
{-Almacenar en una vector K números reales, se sabe que existen elementos nulos. Generar un nuevo arreglo donde cada uno de sus elementos sean la suma de los valores previos a un cero. Ejemplos: K= 11, (2, 6, 0, 1, 0, 4, 7,-2,0, 8, 4)  (8, 1, 9) (0, 2, 6, 0, 1, 0, 4, 7, -2, 3, 0) (0, 8, 10) } Program eje4; Type TV = array[1..100] of real; Procedure LeeVector(Var V:TV; Var K:byte); Var i:byte; arch:text; begin assign(arch,'Eje4.txt');reset(arch); readln(arch,K); For i:= 1 to K do readln(arch,V[i]); end; Procedure GenerarArray(V:TV; K:byte; Var VSum:TV; Var N:byte); Var i:byte; begin N:= 0; For i:= 1 to K do begin If (V[i] = 0) then begin N:= N + 1; VSum[N]:= V[i]; end; end; end; Procedure Suma(var V:TV; K:byte; Var VSum:TV; Var N:byte); Var i:byte; Sum:real; begin Sum:= 0; For i:= 1 to K do begin If (V[i] <> 0) then Sum:= Sum + V[i] Else begin VSum[N]:= Sum; writeln(VSum[N]:2:0); Sum:= 0; end; end; end; Var V,VSum:TV; K,N:byte; Begin LeeVector(V,K); GenerarArray(V,K,VSum,N); Suma(V,K,VSum,N); end.
{В m файлах создать сведения о студентах m групп. Формат сведений: № группы, порядковый номер, фамилия, имя, отчество. Выбрать всех однофамильцев из всех групп и сформировать из них последовательность. Обеспечить вывод сведений о каждой группе и результаты поиска однофамильцев. Сортировка сведений выполняется методом всатвок.} program Project1; {$APPTYPE CONSOLE} uses SysUtils; type student = record groupNumber: integer; studentNumber: integer; surname: string[255]; name: string[255]; patronymic: string[255]; end; ff_rec = file of student; var groupList: ff_rec; fileName : string[20]; person, tmp: student; forReading: ff_rec; i, j, k, count, numberOfGroups: integer; sort: array[1..100] of student; Procedure Enter(groupNum, Nomer: integer); begin with Person do begin groupNumber:=groupNum; studentNumber:=Nomer; writeln('Enter student surname:'); readln(surname); writeln('Enter student name:'); readln(name); writeln('Enter student patronymic:'); readln(patronymic); write(groupList, Person); end; end; Procedure fillingFile(grNum: integer); var quantity, i: integer; begin writeln('Enter the file name'); readln(fileName); assign(groupList, fileName); writeln('Enter the number of students:'); readln(quantity); rewrite(groupList); for i:=1 to quantity do Enter(grNum, i); close(groupList); readln; end; begin writeln('Enter the number of groups:'); readln(numberOfGroups); count:= 0; for k:=1 to numberOfGroups do begin fillingFile(k); end; for k:=1 to numberOfGroups do begin writeln('Enter the name of the file you want to open:'); readln(fileName); assign(forReading, fileName); reset(forReading); while not Eof(forReading) do begin read(forReading, person); writeln(person.groupNumber, ' ', person.studentNumber, ' ', person.surname, ' ', person.name, ' ', person.patronymic); count:= count+1; sort[count]:= person; end; end; writeln; for i:=1 to count do begin for j:=i downto 1 do if (sort[j-1].surname > sort[j].surname) then begin tmp:=sort[j-1]; sort[j-1]:=sort[j]; sort[j]:=tmp; end; end; {for i:=1 to count do writeln(sort[i].groupNumber, ' ', sort[i].studentNumber, ' ', sort[i].surname, ' ',sort[i].name, ' ', sort[i].patronymic); //для проверки сортировки, при сдаче этот вывод не нужен writeln;} writeln('List of the namesakes:'); if(sort[1].surname=sort[2].surname) then writeln(sort[1].groupNumber, ' ', sort[1].studentNumber, ' ', sort[1].surname, ' ',sort[1].name, ' ', sort[1].patronymic); for i:=2 to count do begin if(sort[i].surname=sort[i-1].surname) or (sort[i].surname=sort[i+1].surname) then writeln(sort[i].groupNumber, ' ', sort[i].studentNumber, ' ', sort[i].surname, ' ',sort[i].name, ' ', sort[i].patronymic); end; readln; end.
unit Form.PDFMemoryLeak; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, frxClass, frxRich, gtClasses3, gtCstDocEng, gtCstPlnEng, gtCstPDFEng, gtExPDFEng, gtPDFEng, gtFrxportIntf; type Tfrm_PDFMemoryLeak = class(TForm) frxRichObject1: TfrxRichObject; frxReport1: TfrxReport; btn_Print: TButton; btn_PDF: TButton; Button1: TButton; procedure btn_PrintClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btn_PDFClick(Sender: TObject); procedure Button1Click(Sender: TObject); private FPath: string; FFullFileName: string; procedure ExportPDF(aPDFName: string; aOpenAfterCreate: Boolean); public end; var frm_PDFMemoryLeak: Tfrm_PDFMemoryLeak; implementation {$R *.dfm} procedure Tfrm_PDFMemoryLeak.FormCreate(Sender: TObject); begin FPath := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))); FFullFileName := FPath + 'Test.fr3'; end; procedure Tfrm_PDFMemoryLeak.btn_PDFClick(Sender: TObject); begin ExportPDF('Test.PDF', true); end; procedure Tfrm_PDFMemoryLeak.btn_PrintClick(Sender: TObject); begin frxReport1.LoadFromFile(FFullFileName); frxReport1.ShowReport; end; procedure Tfrm_PDFMemoryLeak.ExportPDF(aPDFName: string; aOpenAfterCreate: Boolean); var PDFEngine : TgtPDFEngine; ExportInterface: TgtFRExportInterface; begin PDFEngine := TgtPDFEngine.Create(nil); ExportInterface := TgtFRExportInterface.Create(nil); try PDFEngine.Preferences.EmbedTrueTypeFonts := etfSubset; PDFEngine.Preferences.OpenAfterCreate := aOpenAfterCreate; PDFEngine.Preferences.ShowSetupDialog := false; ExportInterface.Engine := PDFEngine; IgtDocumentEngine(ExportInterface.Engine).FileName := FPath + aPDFName; IgtDocumentEngine(ExportInterface.Engine).Preferences.ShowSetupDialog := false; ExportInterface.ShowSaveDialog := false; frxReport1.LoadFromFile(FFullFileName); ExportInterface.RenderDocument(frxReport1, false, false); finally FreeAndNil(PDFEngine); FreeAndNil(ExportInterface); end; end; procedure Tfrm_PDFMemoryLeak.Button1Click(Sender: TObject); var i1: Integer; begin for i1 := 0 to 1000 do begin caption := IntToStr(i1); Application.ProcessMessages; ExportPDF('Test' + FormatDateTime('yyyymmddhhnnsszzz', now) + '.pdf' , false); end; ShowMessage('Ready'); end; end.
{ Font info WDX plugin. Copyright (c) 2015-2023 Daniel Plakhotich This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. } library fi_wdx; {$INCLUDE calling.inc} uses fi_common, fi_info_reader, fi_afm_sfd, fi_bdf, fi_eot, fi_inf, fi_pcf, fi_pfm, fi_ps, fi_ttc_otc, fi_ttf_otf, fi_utils, fi_winfnt, fi_woff, {$IFDEF ENABLE_WOFF2} fi_woff2, {$ENDIF} wdxplugin, classes, strutils, sysutils, zstream; procedure ContentGetDetectString( detectString: PAnsiChar; maxLen: Integer); dcpcall; var s, ext: String; begin s := 'EXT="GZ"'; for ext in GetSupportedExtensions do s := s + '|EXT="' + UpperCase(Copy(ext, 2, Length(ext) - 1)) + '"'; StrPLCopy(detectString, s, maxLen - 1); end; type TFieldIndex = ( IDX_FAMILY, IDX_STYLE, IDX_FULL_NAME, IDX_PS_NAME, IDX_VERSION, IDX_COPYRIGHT, IDX_UNIQUE_ID, IDX_TRADEMARK, IDX_MANUFACTURER, IDX_DESIGNER, IDX_DESCRIPTION, IDX_VENDOR_URL, IDX_DESIGNER_URL, IDX_LICENSE, IDX_LICENSE_URL, IDX_FORMAT, IDX_VARIATION_AXIS_TAGS, IDX_NUM_FONTS ); TFieldInfo = record name: String; fieldType: Integer; end; const FieldInfo: array [TFieldIndex] of TFieldInfo = ( (name: 'Family'; fieldType: FT_STRING), (name: 'Style'; fieldType: FT_STRING), (name: 'Full Name'; fieldType: FT_STRING), (name: 'PostScript Name'; fieldType: FT_STRING), (name: 'Version'; fieldType: FT_STRING), (name: 'Copyright'; fieldType: FT_STRING), (name: 'Unique ID'; fieldType: FT_STRING), (name: 'Trademark'; fieldType: FT_STRING), (name: 'Manufacturer'; fieldType: FT_STRING), (name: 'Designer'; fieldType: FT_STRING), (name: 'Description'; fieldType: FT_STRING), (name: 'Vendor URL'; fieldType: FT_STRING), (name: 'Designer URL'; fieldType: FT_STRING), (name: 'License'; fieldType: FT_STRING), (name: 'License URL'; fieldType: FT_STRING), (name: 'Format'; fieldType: FT_STRING), (name: 'Variation Axis Tags'; fieldType: FT_STRING), (name: 'Number of Fonts'; fieldType: FT_NUMERIC_32) ); function ContentGetSupportedField( fieldIndex: Integer; fieldName: PAnsiChar; units: PAnsiChar; maxLen: Integer): Integer; dcpcall; begin StrPCopy(units, EmptyStr); if fieldIndex > Ord(High(TfieldIndex)) then exit(FT_NOMOREFIELDS); StrPLCopy( fieldName, FieldInfo[TfieldIndex(fieldIndex)].name, maxLen - 1); result := FieldInfo[TfieldIndex(fieldIndex)].fieldType; end; function Put( const str: String; fieldValue: PByte; maxLen: Integer): Integer; begin if str = '' then exit(FT_FIELDEMPTY); {$IFDEF WINDOWS} StrPLCopy( PWideChar(fieldValue), UTF8Decode(str), (maxLen - 1) div SizeOf(WideChar)); result := FT_STRINGW; {$ELSE} StrPLCopy(PAnsiChar(fieldValue), str, maxLen - 1); result := FT_STRING; {$ENDIF} end; function TagsToString(const tags: array of LongWord): String; var tag: LongWord; begin result := ''; for tag in tags do begin if result <> '' then result := result + ','; result := result + TagToString(tag); end; end; function Put(int: LongInt; fieldValue: PByte): Integer; begin PLongint(fieldValue)^ := int; result := FT_NUMERIC_32; end; function Put( constref info: TFontInfo; fieldIndex: TFieldIndex; fieldValue: PByte; maxLen: Integer): Integer; begin case fieldIndex of IDX_FAMILY: result := Put(info.family, fieldValue, maxLen); IDX_STYLE: result := Put(info.style, fieldValue, maxLen); IDX_FULL_NAME: result := Put(info.fullName, fieldValue, maxLen); IDX_PS_NAME: result := Put(info.psName, fieldValue, maxLen); IDX_VERSION: result := Put(info.version, fieldValue, maxLen); IDX_COPYRIGHT: result := Put(info.copyright, fieldValue, maxLen); IDX_UNIQUE_ID: result := Put(info.uniqueId, fieldValue, maxLen); IDX_TRADEMARK: result := Put(info.trademark, fieldValue, maxLen); IDX_MANUFACTURER: result := Put(info.manufacturer, fieldValue, maxLen); IDX_DESIGNER: result := Put(info.designer, fieldValue, maxLen); IDX_DESCRIPTION: result := Put(info.description, fieldValue, maxLen); IDX_VENDOR_URL: result := Put(info.vendorUrl, fieldValue, maxLen); IDX_DESIGNER_URL: result := Put(info.designerUrl, fieldValue, maxLen); IDX_LICENSE: result := Put(info.license, fieldValue, maxLen); IDX_LICENSE_URL: result := Put(info.licenseUrl, fieldValue, maxLen); IDX_FORMAT: result := Put(info.format, fieldValue, maxLen); IDX_VARIATION_AXIS_TAGS: result := Put( TagsToString(info.variationAxisTags), fieldValue, maxLen); IDX_NUM_FONTS: result := Put(info.numFonts, fieldValue); else result := FT_NOSUCHFIELD; end; end; procedure Reset(out info: TFontInfo); begin info := Default(TFontInfo); info.numFonts := 1; end; function ReadFontInfo(const fileName: String; var info: TFontInfo): Boolean; const VERSION_PREFIX = 'Version '; var ext: String; gzipped: Boolean = FALSE; stream: TStream; reader: TInfoReader; begin ext := LowerCase(ExtractFileExt(fileName)); if ext = '.gz' then begin gzipped := TRUE; ext := LowerCase(ExtractFileExt( Copy(fileName, 1, Length(fileName) - Length(ext)))); end; reader := FindReader(ext); if reader = NIL then exit(FALSE); try if gzipped then stream := TGZFileStream.Create(fileName, gzOpenRead) else stream := TFileStream.Create( fileName, fmOpenRead or fmShareDenyNone); Reset(info); try reader(stream, info); finally stream.Free; end; except on E: EStreamError do begin {$IFDEF DEBUG} WriteLn(StdErr, 'fontinfo "', fileName, '": ', E.Message); {$ENDIF} exit(FALSE); end; end; Assert( info.format <> '', 'Font format was not set for ' + fileName); if StartsText(VERSION_PREFIX, info.version) then info.version := Copy( info.version, Length(VERSION_PREFIX) + 1, Length(info.version) - Length(VERSION_PREFIX)); result := TRUE; end; var lastFileName: String; infoCache: TFontInfo; // infoCacheValid is TRUE if TFontInfo was loaded without errors infoCacheValid: Boolean; function ContentGetValue( fileName: PAnsiChar; fieldIndex, unitIndex: Integer; fieldValue: PByte; maxLen, flags: Integer): Integer; dcpcall; var fileNameStr: String; begin if fieldIndex > Ord(High(TFieldIndex)) then exit(FT_NOSUCHFIELD); fileNameStr := String(fileName); if lastFileName <> fileNameStr then begin if flags and CONTENT_DELAYIFSLOW <> 0 then exit(FT_DELAYED); infoCacheValid := ReadFontInfo(fileNameStr, infoCache); lastFileName := fileNameStr; end; if not infoCacheValid then exit(FT_FILEERROR); result := Put( infoCache, TFieldIndex(fieldIndex), fieldValue, maxLen); end; exports ContentGetDetectString, ContentGetSupportedField, ContentGetValue; end.
unit uImportaCadastro; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, StdCtrls, fCtrls, ComCtrls, fDBCtrls, Dialogs, db, funcoes, funcsql, ADODB, funcDatas; type TfmExportaEmp = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; cbDemitidos: TfsCheckBox; Memo1: TMemo; Button1: TButton; Label2: TLabel; dtAdmissao: TDateTimePicker; cbDataAdmissao: TfsCheckBox; procedure selecionarEmpregados2(base, filiais:String; impDemitidos:boolean); procedure preparaCadastroParaservidor(); procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormActivate(Sender: TObject); procedure copiaRegistroDeFerias(); procedure copiaRegistroAfastamentos; procedure desativaDemitidos(); private { Private declarations } public { Public declarations } end; var fmExportaEmp: TfmExportaEmp; implementation uses UmanBat, uUtil; {$R *.dfm} // procedure TfmExportaEmp.copiaRegistroAfastamentos; var ds:TDataSet; strDataInicio, cmd:String; qtInseridos:integer; begin qtInseridos := 0; if ( cbDataAdmissao.Checked = true) then strDataInicio := ' ' else strDataInicio := ' where afa_dataAfastamento >=' + funcDATAS.DateTimeToSqlDateTime(dtAdmissao.date, ''); cmd := 'select afa_matricula, afa_dataAfastamento, afa_dataRetorno, ''A'' ' + 'from afastamentos ' + strDataInicio; ds := funcsql.getDataSetQ(cmd, Form2.Conexao ); ds.First(); while (ds.Eof = false) do begin if (uUtil.insereRegistroFerias('A', ds.fieldByName('afa_matricula').AsString, ds.fieldByName('afa_dataAfastamento').AsDateTime, ds.fieldByName('afa_dataRetorno').AsDateTime) = true) then inc(qtInseridos); ds.Next(); end; ds.Close(); Memo1.Lines.Add('Afastamentos inseridos: ' + intToStr(qtInseridos)); end; procedure TfmExportaEmp.copiaRegistroDeFerias; var ds:TDataSet; strDataInicio, cmd:String; qtInseridos:integer; begin qtInseridos := 0; if ( cbDataAdmissao.Checked = true) then strDataInicio := ' ' else strDataInicio := ' and rel_dataref1 >=' + funcDATAS.DateTimeToSqlDateTime(dtAdmissao.date, ''); cmd := 'select rel_matricula, rel_dataref1, rel_dataref2, ''F'' ' + 'from Relatorios where REL_GRUPO =''Férias'' ' + strDataInicio; ds := funcsql.getDataSetQ(cmd, Form2.Conexao ); ds.First(); while (ds.Eof = false) do begin if (uUtil.insereRegistroFerias('F', ds.fieldByName('rel_matricula').AsString, ds.fieldByName('rel_dataRef1').AsDateTime, ds.fieldByName('rel_dataref2').AsDateTime) = true) then inc(qtInseridos); ds.Next(); end; ds.Close(); Memo1.Lines.Add('Ferias inseridas: ' + intToStr(qtInseridos)); end; procedure TfmExportaEmp.selecionarEmpregados2(base, filiais: String;impDemitidos: boolean); var strData, cmd:String; tbEmp:TADOTable; begin if (cbDataAdmissao.Checked = false) then strData := funcDatas.DateTimeToSqlDateTime(dtAdmissao.Date,'') else strData := funcDatas.DateTimeToSqlDateTime('01/01/1900',''); funcsql.getTable(form2.Conexao, tbEmp, 'base int, estabelecimento int, matricula varchar(08), cartaoPonto varchar(08), nome varchar(50), funcao varchar(30), dataAdmissao smallDateTime '); cmd :=' insert ' + tbEmp.TableName + ' select distinct ' + quotedStr(base) + ', e.emp_estabelecimento, e.emp_matricula, e.emp_cartaoDePonto, e.emp_nome, f.fun_descricao, e.emp_dataAdmissao ' + ' from empregados e ' + ' inner join funcoes f on e.emp_funcao = f.fun_referencia ' + ' where (e.emp_cartaodeponto <> '''') '; if (impDemitidos = false) then cmd := cmd + ' and (e.EMP_STATUS = 1) ' else cmd := cmd + '( (e.EMP_STATUS IN (1,2) ) '; cmd := cmd + 'and e.emp_estabelecimento in ( ' + filiais + ') ' + ' and e.emp_DataAdmissao >= '+ strData + ' order by e.emp_nome'; funcsql.execSQL(cmd, Form2.Conexao); tbEmp.Close; tbEmp.Open(); uUtil.opendb(); gravaLog('Quantidade de empregados da empresa ' + base +' ' + intTostr(tbEmp.RecordCount-1)); tbEmp.First(); while (tbEmp.Eof = false) do begin if ( uUtil.isPontoCadastrado(tbEmp.fieldByName('cartaoPonto').AsString) = true) then begin gravaLog('Verificando: ' + tbEmp.fieldByName('matricula').AsString +' ' +tbEmp.fieldByName('nome').AsString + ' - Já existe'); tbEmp.Delete(); end else begin gravaLog('Verificando: ' + tbEmp.fieldByName('matricula').AsString +' ' +tbEmp.fieldByName('nome').AsString + ' - incluir.'); tbEmp.Next(); end; end; memo1.lines.add('Quantidade de empregados a incluir na empresa ' + base + ': ' + intToStr( tbEmp.RecordCount) ); try tbEmp.First; while (tbEmp.Eof = false) do begin memo1.lines.add(tbEmp.fieldByName('matricula').AsString + ' - ' + tbEmp.fieldByName('nome').AsString ); uUtil.insereEmpregado( base, tbEmp.fieldByName('matricula').AsString, tbEmp.fieldByName('cartaoPonto').AsString, tbEmp.fieldByName('nome').AsString, tbEmp.fieldByName('funcao').AsString, tbEmp.fieldByName('dataAdmissao').AsString, '0','0','0', '') ; tbEmp.Next(); end; except on e: exception do begin msgTela('','Erro ao exportar o cadastro, no empregado ' + tbEmp.fieldByName('matricula').AsString + ' - ' + tbEmp.fieldByName('nome').AsString , 0); tbEmp.Last(); end; end; end; procedure TfmExportaEmp.FormClose(Sender: TObject; var Action: TCloseAction); begin action := caFree; fmExportaEmp := nil; end; procedure TfmExportaEmp.FormActivate(Sender: TObject); begin memo1.Lines.add('Ultima carga em: ' + uUtil.lerParametroBD('ponto.dataUltCarga') ); end; procedure TfmExportaEmp.desativaDemitidos; var ds:TdataSet; strData, cmd:String; begin Memo1.Lines.Add('Empregados desativados:'); if (cbDataAdmissao.Checked = false) then strData := funcDatas.DateTimeToSqlDateTime(dtAdmissao.Date,'') else strData := funcDatas.DateTimeToSqlDateTime('01/10/2010',''); cmd := 'select distinct '+ 'relatorios.rel_matricula, empregados.emp_nome, '+ 'relatorios.rel_dataref1 ' + 'from relatorios '+ 'inner join empregados on empregados.emp_matricula = relatorios.rel_matricula ' + 'where relatorios.rel_grupo = ''Rescisão'' ' + 'and relatorios.rel_dataref1 >= ' + strData; ds := funcSQL.getDataSetQ(cmd, form2.Conexao); ds.First(); while (ds.Eof = false) do begin if (uUtil.desativaEmpregado(ds.fieldByName('rel_matricula').AsString, ds.fieldByName('rel_dataref1').AsDateTime ) = true )then Memo1.Lines.Add( ds.fieldByName('emp_nome').AsString +' '+ ds.fieldByName('rel_dataref1').AsString); ds.Next(); end; end; procedure TfmExportaEmp.PreparaCadastroParaservidor(); var i:integer; estabelecimentos:array[1..3] of String; mnEmpresa:array[1..3] of String; begin estabelecimentos[1] := ' ''000'' , ''002'', ''003'' '; estabelecimentos[2] := ' ''000'' , ''005'' , ''006'' , ''007'' , ''009'' , ''010'' , ''011'', ''012'', ''017'', ''018'' '; estabelecimentos[3] := ' ''008'' '; mnEmpresa[1] := 'Empregados CF'; mnEmpresa[2] := 'Empregados PFM'; mnEmpresa[3] := 'Empregados CF'; for i:=1 to 3 do begin Form2.ConectarAoBd(intToStr(i)); selecionarEmpregados2( intToStr(i), estabelecimentos[i], cbDemitidos.Checked ); copiaRegistroDeFerias(); copiaRegistroAfastamentos(); desativaDemitidos(); end; uUtil.setParamBD('ponto.dataUltCarga','', dateToStr(now)); end; procedure TfmExportaEmp.Button1Click(Sender: TObject); begin preparaCadastroParaservidor(); end; end.
unit TextureAtlasExtractorOrigamiGPU; interface uses BasicMathsTypes, BasicDataTypes, TextureAtlasExtractorOrigami, MeshPluginBase, NeighborDetector, Math, IntegerList, VertexTransformationUtils, Math3d, NeighborhoodDataPlugin, SysUtils, Mesh, TextureAtlasExtractorBase, OpenCLLauncher; {$INCLUDE source/Global_Conditionals.inc} type CTextureAtlasExtractorOrigamiGPU = class (CTextureAtlasExtractorOrigami) protected OCL : TOpenClLauncher; // Aux functions function IsValidUVPoint(const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; override; function IsValidUVTriangle(const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; override; public procedure Initialize; override; // Executes procedure Execute(); override; procedure ExecuteWithDiffuseTexture(_Size: integer); override; end; implementation uses GlobalVars, TextureGeneratorBase, DiffuseTextureGenerator, MeshBRepGeometry, GLConstants, ColisionCheck, BasicFunctions; procedure CTextureAtlasExtractorOrigamiGPU.Initialize(); begin OCL := TOpenCLLauncher.Create(); end; procedure CTextureAtlasExtractorOrigamiGPU.Execute(); var i : integer; Seeds: TSeedSet; VertsSeed : TInt32Map; NeighborhoodPlugin: PMeshPluginBase; ProgramNames: AString; begin // First, we'll build the texture atlas. SetLength(VertsSeed,High(FLOD.Mesh)+1); SetLength(Seeds,0); ProgramNames[0] := 'are2DTrianglesColidingEdges'; ProgramNames[1] := 'are2DTrianglesOverlapping'; OCL.LoadProgram(ExtractFilePath(ParamStr(0)) + 'opencl/origami.cl', ProgramNames); ProgramNames[0] := ''; ProgramNames[1] := ''; SetLength(ProgramNames, 0); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); NeighborhoodPlugin := FLOD.Mesh[i].GetPlugin(C_MPL_NEIGHBOOR); FLOD.Mesh[i].Geometry.GoToFirstElement; FLOD.Mesh[i].TexCoords := GetMeshSeeds(i,FLOD.Mesh[i].Vertices,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Normals,FLOD.Mesh[i].Normals,FLOD.Mesh[i].Colours,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Faces,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,Seeds,VertsSeed[i],NeighborhoodPlugin); if NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(NeighborhoodPlugin^).DeactivateQuadFaces; end; end; MergeSeeds(Seeds); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin GetFinalTextureCoordinates(Seeds,VertsSeed[i],FLOD.Mesh[i].TexCoords); end; // Free memory. for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); end; OCL.Free; SetLength(VertsSeed,0); end; procedure CTextureAtlasExtractorOrigamiGPU.ExecuteWithDiffuseTexture(_Size: integer); var i : integer; Seeds: TSeedSet; VertsSeed : TInt32Map; TexGenerator: CTextureGeneratorBase; NeighborhoodPlugin: PMeshPluginBase; ProgramNames: AString; begin // First, we'll build the texture atlas. SetLength(VertsSeed,High(FLOD.Mesh)+1); SetLength(Seeds,0); SetLength(ProgramNames, 2); ProgramNames[0] := 'are2DTrianglesColidingEdges'; ProgramNames[1] := 'are2DTrianglesOverlapping'; OCL.LoadProgram(ExtractFilePath(ParamStr(0)) + 'opencl/origami.cl', ProgramNames); ProgramNames[0] := ''; ProgramNames[1] := ''; SetLength(ProgramNames, 0); TexGenerator := CDiffuseTextureGenerator.Create(FLOD,_Size,0,0); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); NeighborhoodPlugin := FLOD.Mesh[i].GetPlugin(C_MPL_NEIGHBOOR); FLOD.Mesh[i].Geometry.GoToFirstElement; FLOD.Mesh[i].TexCoords := GetMeshSeeds(i,FLOD.Mesh[i].Vertices,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Normals,FLOD.Mesh[i].Normals,FLOD.Mesh[i].Colours,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Faces,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,Seeds,VertsSeed[i],NeighborhoodPlugin); if NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(NeighborhoodPlugin^).DeactivateQuadFaces; end; end; MergeSeeds(Seeds); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin GetFinalTextureCoordinates(Seeds,VertsSeed[i],FLOD.Mesh[i].TexCoords); end; // Now we build the diffuse texture. TexGenerator.Execute(); // Free memory. for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); end; SetLength(VertsSeed,0); OCL.Free; TexGenerator.Free; end; function CTextureAtlasExtractorOrigamiGPU.IsValidUVPoint(const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; var EdgeSizeInMesh,EdgeSizeInUV,Scale,SinProjectionSizeInMesh,SinProjectionSizeInUV,ProjectionSizeInMesh,ProjectionSizeInUV: single; EdgeDirectionInUV,PositionOfTargetAtEdgeInUV,SinDirectionInUV: TVector2f; EdgeDirectionInMesh,PositionOfTargetAtEdgeInMesh: TVector3f; SourceSide: single; InputData: apointer; InputSize, InputUnitSize: auint32; OutputSource: aint32; GlobalWorkSize: auint32; EdgeIDs: aint32; TriangleData: afloat; Output: integer; begin Result := false; // Get edge size in mesh EdgeSizeInMesh := VectorDistance(_Vertices[_Edge0],_Vertices[_Edge1]); if EdgeSizeInMesh > 0 then begin // Get the direction of the edge (Edge0 to Edge1) in Mesh and UV space EdgeDirectionInMesh := SubtractVector(_Vertices[_Edge1],_Vertices[_Edge0]); EdgeDirectionInUV := SubtractVector(_TexCoords[_Edge1],_TexCoords[_Edge0]); // Get edge size in UV space. EdgeSizeInUV := Sqrt((EdgeDirectionInUV.U * EdgeDirectionInUV.U) + (EdgeDirectionInUV.V * EdgeDirectionInUV.V)); // Directions must be normalized. Normalize(EdgeDirectionInMesh); Normalize(EdgeDirectionInUV); Scale := EdgeSizeInUV / EdgeSizeInMesh; // Get the size of projection of (Vertex - Edge0) at the Edge, in mesh ProjectionSizeInMesh := DotProduct(SubtractVector(_Vertices[_Target],_Vertices[_Edge0]),EdgeDirectionInMesh); // Obtain the position of this projection at the edge, in mesh PositionOfTargetatEdgeInMesh := AddVector(_Vertices[_Edge0],ScaleVector(EdgeDirectionInMesh,ProjectionSizeInMesh)); // Now we can use the position obtained previously to find out the // distance between that and the _Target in mesh. SinProjectionSizeInMesh := VectorDistance(_Vertices[_Target],PositionOfTargetatEdgeInMesh); // Rotate the edge in 90' in UV space. SinDirectionInUV := Get90RotDirectionFromDirection(EdgeDirectionInUV); // We need to make sure that _Target and _OriginVert are at opposite sides // the universe, if it is divided by the Edge0 to Edge1. SourceSide := Get2DOuterProduct(_TexCoords[_OriginVert],_TexCoords[_Edge0],_TexCoords[_Edge1]); if SourceSide > 0 then begin SinDirectionInUV := ScaleVector(SinDirectionInUV,-1); end; // Now we use the same logic applied in mesh to find out the final position // in UV space ProjectionSizeInUV := ProjectionSizeInMesh * Scale; PositionOfTargetatEdgeInUV := AddVector(_TexCoords[_Edge0],ScaleVector(EdgeDirectionInUV,ProjectionSizeInUV)); SinProjectionSizeInUV := SinProjectionSizeInMesh * Scale; // Write the UV Position _UVPosition := AddVector(PositionOfTargetatEdgeInUV,ScaleVector(SinDirectionInUV,SinProjectionSizeInUV)); // Let's check if this UV Position will hit another UV project face. SetLength(TriangleData, 2); TriangleData[0] := _UVPosition.U; TriangleData[1] := _UVPosition.V; SetLength(EdgeIDs, 2); EdgeIDs[0] := _Edge0; EdgeIDs[1] := _Edge1; Output := 0; SetLength(InputData,6); InputData[0] := Addr(TriangleData[0]); InputData[1] := Addr(EdgeIDs[0]); InputData[2] := Addr(_CheckFace[0]); InputData[3] := Addr(_TexCoords[0]); InputData[4] := Addr(_Faces[0]); InputData[5] := Addr(Output); SetLength(InputSize,6); InputSize[0] := 2; InputSize[1] := 2; InputSize[2] := High(_CheckFace) + 1; InputSize[3] := 2 * (High(_TexCoords) + 1); InputSize[4] := High(_Faces) + 1; InputSize[5] := 1; SetLength(InputUnitSize,6); InputUnitSize[0] := sizeof(single); InputUnitSize[1] := sizeof(integer); InputUnitSize[2] := sizeof(boolean); InputUnitSize[3] := sizeof(single); InputUnitSize[4] := sizeof(integer); InputUnitSize[5] := sizeof(integer); SetLength(OutputSource,1); OutputSource[0] := 5; SetLength(GlobalWorkSize,1); GlobalWorkSize[0] := High(_CheckFace) + 1; OCL.RunKernel(InputData,InputSize,InputUnitSize,OutputSource,1,GlobalWorkSize,nil); if output = 1 then begin Result := false; end else begin Result := true; end; SetLength(TriangleData, 0); SetLength(EdgeIDs, 0); SetLength(InputData, 0); SetLength(InputSize, 0); SetLength(InputUnitSize, 0); SetLength(OutputSource, 0); SetLength(GlobalWorkSize, 0); end; end; function CTextureAtlasExtractorOrigamiGPU.IsValidUVTriangle(const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; const C_MIN_ANGLE = pi / 6; C_HALF_MIN_ANGLE = C_MIN_ANGLE / 2; var InputData: apointer; InputSize, InputUnitSize: auint32; OutputSource: aint32; GlobalWorkSize: auint32; EdgeIDs: aint32; TriangleData: afloat; Output: integer; DirTE0,DirE1T,DirE0E1: TVector2f; Ang0,Ang1,AngTarget: single; begin // Do we have a valid triangle? DirTE0 := SubtractVector(_TexCoords[_Edge0], _TexCoords[_Target]); if Epsilon(Normalize(DirTE0)) = 0 then begin Result := false; exit; end; DirE1T := SubtractVector(_TexCoords[_Target], _TexCoords[_Edge1]); if Epsilon(Normalize(DirE1T)) = 0 then begin Result := false; exit; end; // Is the orientation correct? if Epsilon(Get2DOuterProduct(_TexCoords[_Target],_TexCoords[_Edge0],_TexCoords[_Edge1])) > 0 then begin Result := false; exit; end; DirE0E1 := SubtractVector(_TexCoords[_Edge1], _TexCoords[_Edge0]); Normalize(DirE0E1); // Are angles acceptable? Ang0 := ArcCos(-1 * DotProduct(DirTE0, DirE0E1)); Ang1 := ArcCos(-1 * DotProduct(DirE0E1, DirE1T)); AngTarget := ArcCos(-1 * DotProduct(DirE1T, DirTE0)); if Epsilon(abs(DotProduct(DirTE0,DirE1T)) - 1) = 0 then begin Result := false; exit; end; // Are all angles above threshold? if Ang0 < C_MIN_ANGLE then begin Result := false; exit; end; if Ang1 < C_MIN_ANGLE then begin Result := false; exit; end; if AngTarget < C_MIN_ANGLE then begin Result := false; exit; end; // Let's check if this UV Position will hit another UV project face. SetLength(TriangleData, 2); TriangleData[0] := _TexCoords[_Target].U; TriangleData[1] := _TexCoords[_Target].V; SetLength(EdgeIDs, 2); EdgeIDs[0] := _Edge0; EdgeIDs[1] := _Edge1; Output := 0; SetLength(InputData,6); InputData[0] := Addr(TriangleData[0]); InputData[1] := Addr(EdgeIDs[0]); InputData[2] := Addr(_CheckFace[0]); InputData[3] := Addr(_TexCoords[0]); InputData[4] := Addr(_Faces[0]); InputData[5] := Addr(Output); SetLength(InputSize,6); InputSize[0] := 2; InputSize[1] := 2; InputSize[2] := High(_CheckFace) + 1; InputSize[3] := 2 * (High(_TexCoords) + 1); InputSize[4] := High(_Faces) + 1; InputSize[5] := 1; SetLength(InputUnitSize,6); InputUnitSize[0] := sizeof(single); InputUnitSize[1] := sizeof(integer); InputUnitSize[2] := sizeof(boolean); InputUnitSize[3] := sizeof(single); InputUnitSize[4] := sizeof(integer); InputUnitSize[5] := sizeof(integer); SetLength(OutputSource,1); OutputSource[0] := 5; SetLength(GlobalWorkSize,1); GlobalWorkSize[0] := High(_CheckFace) + 1; OCL.CurrentKernel := 1; OCL.RunKernel(InputData,InputSize,InputUnitSize,OutputSource,1,GlobalWorkSize,nil); if output = 1 then begin Result := false; end else begin Result := true; end; OCL.CurrentKernel := 0; SetLength(TriangleData, 0); SetLength(EdgeIDs, 0); SetLength(InputData, 0); SetLength(InputSize, 0); SetLength(InputUnitSize, 0); SetLength(OutputSource, 0); SetLength(GlobalWorkSize, 0); end; end.
unit MatrixG; {----------------------------------------------------------------------------} {- -} {- Turbo Pascal Numerical Methods Toolbox -} {- Copyright (c) 1986, 87 by Borland International, Inc. -} {- -} {- This unit provides procedures for dealing with systems of linear -} {- equations. -} {- -} {----------------------------------------------------------------------------} {$I Float.inc} { Determines the setting of the $N compiler directive } interface {$IFOPT N+} type Float = Double; { 8 byte real, requires 8087 math chip } const TNNearlyZero = 1E-015; {$ELSE} type Float = real; { 6 byte real, no math chip required } const TNNearlyZero = 1E-07; {$ENDIF} TNArraySize = 30; { Size of the matrix } type TNvector = array[1..TNArraySize] of Float; TNmatrix = array[1..TNArraySize] of TNvector; procedure Determinant(Dimen : integer; Data : TNmatrix; var Det : Float; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Data -} {- Output: Det, Error -} {- -} {- Purpose : Calculate the determinant of a matrix by -} {- making it upper-triangular and then -} {- taking the product of the diagonal elements. -} {- -} {- User-defined Types : TNvector = array[1..TNArraySize] of real; -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimension of the square matrix -} {- Data : TNmatrix; Square matrix -} {- Det : real; Determinant of Data -} {- Error : integer; Flags if something goes wrong -} {- -} {- Errors : 0: No errors; -} {- 1: Dimen < 1 -} {- -} {----------------------------------------------------------------------------} procedure Inverse(Dimen : integer; Data : TNmatrix; var Inv : TNmatrix; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Data -} {- Output: Inv, Error -} {- -} {- Purpose : calculate the inverse of a matrix with -} {- Gauss-Jordan elimination. -} {- -} {- User-defined Types : TNvector = array[1..TNArraySize] of real; -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimension of the square matrix -} {- Data : TNmatrix; Square matrix -} {- Inv : TNmatrix; Inverse of Data -} {- Error : integer; Flags if something goes wrong -} {- -} {- Errors : 0: No errors; -} {- 1: Dimen < 1 -} {- 2: no inverse exists -} {- -} {----------------------------------------------------------------------------} procedure Gaussian_Elimination(Dimen : integer; Coefficients : TNmatrix; Constants : TNvector; var Solution : TNvector; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Coefficients, Constants -} {- Output: Solution, Error -} {- -} {- Purpose : Calculate the solution of a linear set of -} {- equations using Gaussian elimination and -} {- backwards substitution. -} {- -} {- User-defined Types : TNvector = array[1..TNArraySize] of real -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimension of the square -} {- matrix -} {- Coefficients : TNmatrix; Square matrix -} {- Constants : TNvector; Constants of each equation-} {- Solution : TNvector; Unique solution to the -} {- set of equations -} {- Error : integer; Flags if something goes -} {- wrong. -} {- -} {- Errors: 0: No errors; -} {- 1: Dimen < 1 -} {- 2: no solution exists -} {- -} {- -} {----------------------------------------------------------------------------} procedure Partial_Pivoting(Dimen : integer; Coefficients : TNmatrix; Constants : TNvector; var Solution : TNvector; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Coefficients, Constants -} {- Output: Solution, Error -} {- -} {- Purpose : Calculate the solution of a linear set of -} {- equations using Gaussian elimination, maximal -} {- pivoting and backwards substitution. -} {- -} {- User-defined Types : TNvector = array[1..TNArraySize] of real; -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimen of the square -} {- matrix -} {- Coefficients : TNmatrix; Square matrix -} {- Constants : TNvector; Constants of each equation-} {- Solution : TNvector; Unique solution to the -} {- set of equations -} {- Error : integer; Flags if something goes -} {- wrong. -} {- -} {- Errors : 0: No errors; -} {- 1: Dimen < 2 -} {- 2: no solution exists -} {- -} {----------------------------------------------------------------------------} procedure LU_Decompose(Dimen : integer; Coefficients : TNmatrix; var Decomp : TNmatrix; var Permute : TNmatrix; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Coefficients -} {- Output: Decomp, Permute, Error -} {- -} {- Purpose : Decompose a square matrix into an upper -} {- triangular and lower triangular matrix such that -} {- the product of the two triangular matrices is -} {- the original matrix. This procedure also returns -} {- a permutation matrix which records the -} {- permutations resulting from partial pivoting. -} {- -} {- User-defined Types : TNvector = array[1..TNArraySize] of real -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimen of the coefficients -} {- Matrix -} {- Coefficients : TNmatrix; Coefficients matrix -} {- Decomp : TNmatrix; Decomposition of -} {- Coefficients matrix -} {- Permute : TNmatrix; Record of partial -} {- Pivoting -} {- Error : integer; Flags if something goes -} {- wrong. -} {- -} {- Errors : 0: No errors; -} {- 1: Dimen < 1 -} {- 2: No decomposition possible; singular matrix -} {- -} {----------------------------------------------------------------------------} procedure LU_Solve(Dimen : integer; var Decomp : TNmatrix; Constants : TNvector; var Permute : TNmatrix; var Solution : TNvector; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Decomp, Constants, Permute -} {- Output: Solution, Error -} {- -} {- Purpose : Calculate the solution of a linear set of -} {- equations using an LU decomposed matrix, a -} {- permutation matrix and backwards and forward -} {- substitution. -} {- -} {- User_defined Types : TNvector = array[1..TNArraySize] of real -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimen of the square -} {- matrix -} {- Decomp : TNmatrix; Decomposition of -} {- coefficient matrix -} {- Constants : TNvector; Constants of each equation -} {- Permute : TNmatrix; Permutation matrix from -} {- partial pivoting -} {- Solution : TNvector; Unique solution to the -} {- set of equations -} {- Error : integer; Flags if something goes -} {- wrong. -} {- -} {- Errors : 0: No errors; -} {- 1: Dimen < 1 -} {- -} {----------------------------------------------------------------------------} procedure Gauss_Seidel(Dimen : integer; Coefficients : TNmatrix; Constants : TNvector; Tol : Float; MaxIter : integer; var Solution : TNvector; var Iter : integer; var Error : byte); {----------------------------------------------------------------------------} {- -} {- Input: Dimen, Coefficients, Constants, Tol, MaxIter -} {- Output: Solution, Iter, Error -} {- -} {- Purpose : Calculate the solution of a linear set of -} {- equations using Gauss - Seidel iteration. -} {- -} {- User-defined Types : TNvector = array[1..TNArraySize] of real -} {- TNmatrix = array[1..TNArraySize] of TNvector -} {- -} {- Global Variables : Dimen : integer; Dimen of the square -} {- matrix -} {- Coefficients : TNmatrix; Square matrix -} {- Constants : TNvector; Constants of each equation-} {- Tol : real; Tolerance in answer -} {- MaxIter : integer; Maximum number of -} {- iterations allowed -} {- Solution : TNvector; Unique solution to the -} {- set of equations -} {- Iter : integer; Number of iterations -} {- Error : integer; Flags if something goes -} {- wrong. -} {- -} {- Errors : 0: No errors; -} {- 1: Iter >= MaxIter and matrix not -} {- diagonally dominant -} {- 2: Iter >= MaxIter -} {- 3: Dimen < 1 -} {- 4: Tol <= 0 -} {- 5: MaxIter < 0 -} {- 6: Zero on the diagonal of -} {- the Coefficients matrix -} {- 7: Diverging -} {- -} {- Note: If the Gauss-Seidel iterative method is -} {- applied to an underdetermined system of equations -} {- (i.e. one of the equations is a linear -} {- superposition of the others) it will converge -} {- to a (non-unique) solution. The Gauss-Seidel -} {- method is unable to distinguish between unique -} {- and non-unique solutions. -} {- If you are concerned that your equations -} {- may be underdetermined, solve them with -} {- Gaussian elimination (GAUSELIM.INC or -} {- PARTPIVT.INC -} {- -} {----------------------------------------------------------------------------} implementation {$I Matrix.inc} end. { Matrix } 
{: GLFileDXF<p> Support-Code to load DXF (Drawing eXchange Files) TGLFreeForm or TGLActor Components in GLScene.<p> Note that you must manually add this unit to one of your project's uses to enable support for DXF at run-time.<p> Turn on TwoSideLighting in your Buffer! DXF-Faces have no defined winding order <b>History : </b><font size=-1><ul> <li>08/01/06 - JCD - Now works with MaterialLibrary=NIL. (will not load any material, still assigns materialnames to meshobj) <li>04/01/06 - JCD - Layer conversion code, material creation, code cleanup</li> <li>24/04/04 - JCD - some basic stream code copied from GLScene Wavefront OBJ-Importer (09/09/03)</li> </ul><p> (c) 2004-2006 Jörn Daub http://www.daubnet.com<p> surrendered to Mozilla Public License for use in GLScene. Original author (Jörn Daub) retains the right to make changes without surrendering the modified code. } unit glfiledxf; interface uses classes,sysutils, applicationfileio, GLVectorGeometry, GLVectorLists, glscene, gltexture, glvectorfileObjects; type TGLDXFVectorFile = class (TVectorFile) private FSourceStream : TStream; { Load from this stream } FBuffer : String; { Buffer and current line } FLineNo : Integer; { current Line number - for error messages } FEof : Boolean; { Stream done? } FBufPos : Integer; { Position in the buffer } HasPushedCode : Boolean; PushedCode : INTEGER; FLayers :TStringList; FBlocks :TStringList; FLastpercentdone:BYTE; protected procedure PushCode(code:INTEGER); function GetCode :INTEGER; procedure SkipTable; procedure SkipSection; // procedure DoProgress (Stage: TGLProgressStage; PercentDone: single; RedrawNow: Boolean; const Msg: string); function NeedMesh (basemesh:TGLBaseMesh;layer:STRING):TMeshObject; function NeedFaceGroup (m:TMeshObject;fgmode:TFaceGroupMeshMode;fgmat:STRING):TFGVertexIndexList; procedure NeedMeshAndFaceGroup (basemesh:TGLBaseMesh;layer:STRING;fgmode:TFaceGroupMeshMode;fgmat:STRING; var m:TMeshObject;var fg:TFGVertexIndexList); function ReadLine:STRING; // Read a single line of text from the source stream, set FEof to true when done. function ReadInt:integer; function ReadDouble:double; procedure ReadTables; procedure ReadLayer; procedure ReadLayerTable; procedure ReadBlocks; procedure ReadInsert (basemesh:TGLBaseMesh); procedure ReadEntity3Dface (basemesh:TGLBaseMesh); procedure ReadEntityPolyLine (basemesh:TGLBaseMesh); procedure ReadEntities (basemesh:TGLBaseMesh); public class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream:TStream); override; end; implementation procedure BuildNormals (m:TMeshObject); FORWARD; const DXFcolorsRGB : ARRAY [1..255] OF LONGINT = ( $FF0000, $FFFF00, $00FF00, $00FFFF, $0000FF, $FF00FF, $000000, $000000, $000000, $FF0000, $FF8080, $A60000, $A65353, $800000, $804040, $4D0000, $4D2626, $260000, $261313, $FF4000, $FF9F80, $A62900, $A66853, $802000, $805040, $4D1300, $4D3026, $260A00, $261813, $FF8000, $FFBF80, $A65300, $A67C53, $804000, $806040, $4D2600, $4D3926, $261300, $261D13, $FFBF00, $FFDF80, $A67C00, $A69153, $806000, $807040, $4D3900, $4D4326, $261D00, $262113, $FFFF00, $FFFF80, $A6A600, $A6A653, $808000, $808040, $4D4D00, $4D4D26, $262600, $262613, $BFFF00, $DFFF80, $7CA600, $91A653, $608000, $708040, $394D00, $434D26, $1D2600, $212613, $80FF00, $BFFF80, $53A600, $7CA653, $408000, $608040, $264D00, $394D26, $132600, $1D2613, $40FF00, $9FFF80, $29A600, $68A653, $208000, $508040, $134D00, $304D26, $0A2600, $182613, $00FF00, $80FF80, $00A600, $53A653, $008000, $408040, $004D00, $264D26, $002600, $132613, $00FF40, $80FF9F, $00A629, $53A668, $008020, $408050, $004D13, $264D30, $00260A, $132618, $00FF80, $80FFBF, $00A653, $53A67C, $008040, $408060, $004D26, $264D39, $002613, $13261D, $00FFBF, $80FFDF, $00A67C, $53A691, $008060, $408070, $004D39, $264D43, $00261D, $132621, $00FFFF, $80FFFF, $00A6A6, $53A6A6, $008080, $408080, $004D4D, $264D4D, $002626, $132626, $00BFFF, $80DFFF, $007CA6, $5391A6, $006080, $407080, $00394D, $26434D, $001D26, $132126, $0080FF, $80BFFF, $0053A6, $537CA6, $004080, $406080, $00264D, $26394D, $001326, $131D26, $0040FF, $809FFF, $0029A6, $5368A6, $002080, $405080, $00134D, $26304D, $000A26, $131826, $0000FF, $8080FF, $0000A6, $5353A6, $000080, $404080, $00004D, $26264D, $000026, $131326, $4000FF, $9F80FF, $2900A6, $6853A6, $200080, $504080, $13004D, $30264D, $0A0026, $181326, $8000FF, $BF80FF, $5300A6, $7C53A6, $400080, $604080, $26004D, $39264D, $130026, $1D1326, $BF00FF, $DF80FF, $7C00A6, $9153A6, $600080, $704080, $39004D, $43264D, $1D0026, $211326, $FF00FF, $FF80FF, $A600A6, $A653A6, $800080, $804080, $4D004D, $4D264D, $260026, $261326, $FF00BF, $FF80DF, $A6007C, $A65391, $800060, $804070, $4D0039, $4D2643, $26001D, $261321, $FF0080, $FF80BF, $A60053, $A6537C, $800040, $804060, $4D0026, $4D2639, $260013, $26131D, $FF0040, $FF809F, $A60029, $A65368, $800020, $804050, $4D0013, $4D2630, $26000A, $261318, $545454, $767676, $989898, $BBBBBB, $DDDDDD, $FFFFFF ); const BufSize = 65536; { Load input data in chunks of BufSize Bytes. } LineLen = 100; { Allocate memory for the current line in chunks} function RGB2BGR(bgr:LONGINT):LONGINT; begin result:= ((bgr SHR 16) and $FF) or (bgr AND $FF00) or ((bgr SHL 16) and $FF0000) end; function StreamEOF(S : TStream) : Boolean; begin { Is the stream at its end? } Result:=(S.Position>=S.Size); end; class function TGLDXFVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead]; end; function TGLDXFVectorFile.ReadLine:STRING; var j : Integer; FLine:STRING; NewlineChar:CHAR; procedure FillBuffer; var l : Integer; begin l:=FSourceStream.Size-FSourceStream.Position; if l>BufSize then l:=BufSize; SetLength(FBuffer, l); FSourceStream.Read(FBuffer[1], l); FBufPos:=1; end; begin Inc(FLineNo); if FBufPos<1 then FillBuffer; j:=1; while True do begin if FBufPos>Length(FBuffer) then begin if StreamEof(FSourceStream) then begin FEof:=True; break; end else FillBuffer end else begin case FBuffer[FBufPos] of #10, #13 : begin NewLineChar:=FBuffer[FBufPos]; Inc(FBufPos); if FBufPos>Length(FBuffer) then if StreamEof(FSourceStream) then break else FillBuffer; if ((FBuffer[FBufPos]=#10) or (FBuffer[FBufPos]=#13)) and (FBuffer[FBufPos]<>NewLineChar) then Inc(FBufPos); break; end; else if j>Length(FLine) then SetLength(FLine, Length(FLine)+LineLen); if FBuffer[FBufPos]=#9 then FLine[j]:=#32 else FLine[j]:=FBuffer[FBufPos]; Inc(FBufPos); Inc(j); end; end; end; SetLength(FLine,j-1); ReadLine:=Trim(FLine); end; {procedure TGLDXFVectorFile.DoProgress (Stage: TGLProgressStage; PercentDone: single; RedrawNow: Boolean; const Msg: string); var perc:BYTE; begin // If the following line stops your compiler, just comment this function if @owner.OnProgress<>NIL then begin perc:=round(percentdone); if (perc<>Flastpercentdone) or (msg<>'') or redrawnow then owner.OnProgress (owner,stage,perc,redrawnow,msg); Flastpercentdone:=perc; end; end;} procedure TGLDXFVectorFile.PushCode(code:INTEGER); begin PushedCode:=code; HasPushedCode:=TRUE; end; function TGLDXFVectorFile.GetCode:INTEGER; var s:STRING; begin if HasPushedCode then begin Getcode:=PushedCode; HasPushedCode:=FALSE; end else begin s:=ReadLine; Result:=StrToIntDef(s,-1); if result=-1 then raise Exception.create ('Invalid DXF Code '+s+' on Line #'+IntToStr(FLineNo)); end; end; function TGLDXFVectorFile.ReadDouble:double; var s:STRING; c:CHAR; begin c:=DecimalSeparator; DecimalSeparator:='.'; s:=Trim(readline); result:=StrToFloat(s); DecimalSeparator:=c; end; function TGLDXFVectorFile.ReadInt:integer; var s:STRING; begin s:=Trim(readline); result:=StrToInt(s); end; procedure TGLDXFVectorFile.SkipSection; var s:STRING; code:INTEGER; begin repeat code:=GetCode; s:=ReadLine; until (code=0) and (s='ENDSEC'); end; procedure TGLDXFVectorFile.SkipTable; var s:STRING; code:INTEGER; begin repeat code:=GetCode; s:=ReadLine; until (code=0) and (s='ENDTAB'); end; procedure TGLDXFVectorFile.ReadLayer; var layername,color:STRING; code:INTEGER; begin color:='1'; repeat code:=GetCode; case code of 0 :; 2 :layername:=ReadLine; 70:ReadLine; // freeze and lock flags 62:color :=ReadLine; else ReadLine; end; until code=0; PushCode(0); FLayers.AddObject(layername,POINTER(StrToIntDef(color,1))); end; procedure TGLDXFVectorFile.ReadLayerTable; var s:STRING; code:INTEGER; begin repeat code:=GetCode; s:=ReadLine; if (code=0) and (s='LAYER') then ReadLayer; until (code=0) and (s='ENDTAB'); end; procedure TGLDXFVectorFile.ReadTables; var s:STRING; code:INTEGER; begin repeat code:=GetCode; s:=ReadLine; if (code=0) and (s='TABLE') then begin code:=GetCode; s:=ReadLine; if (code=2) then if s='LAYER' then ReadLayerTable else SkipTable; // LTYPE, STYLE, UCS, and more currently skipped end until (code=0) and (s='ENDSEC'); end; procedure TGLDXFVectorFile.ReadBlocks; var s:STRING; code:INTEGER; blockname:STRING; blockmesh:TGLFreeForm; begin // This code reads blocks into orphaned TGLFreeForms. // ReadInsert then either copies or parents this object to its parent // unused blocks are freed upon completion repeat code:=GetCode; s:=ReadLine; if (code=0) and (s='BLOCK') then begin blockmesh:=TGLFreeForm.Create(owner); blockmesh.IgnoreMissingTextures :=TRUE; blockmesh.MaterialLibrary := owner.MaterialLibrary; blockmesh.OnProgress := NIL; blockname:='DXFBLOCK'+IntToStr(FBlocks.count); repeat code:=GetCode; case code of 0:; 2: BlockName :=ReadLine; else s:=ReadLine; end; until code=0; pushcode(0); FBlocks.AddObject(blockname,blockmesh); ReadEntities(blockmesh); // basemesh.Direction.SetVector(0,1,0); // code:=GetCode; // s:=ReadLine; // asm nop end; end; until (code=0) and (s='ENDSEC'); end; procedure TGLDXFVectorFile.ReadInsert (basemesh:TGLBaseMesh); var code,idx,indexoffset:INTEGER; i,j,k:INTEGER; BlockName,s:STRING; pt, insertpoint,scale :TAffineVector; blockmesh :TGLBaseMesh; blockproxy :TGLProxyObject; mo_block :TMeshObject; mo_base :TMeshObject; fg_block, fg_base :TFGVertexIndexList; begin BlockName:=''; insertpoint:=NullVector; scale :=XYZvector; repeat // see ReadBlocks for details code:=GetCode; case code of 0 :; 2 : BlockName:=ReadLine; 10: insertpoint[0] := ReadDouble; 20: insertpoint[1] := ReadDouble; 30: insertpoint[2] := ReadDouble; 41: scale[0] := ReadDouble; 42: scale[1] := ReadDouble; 43: scale[2] := ReadDouble; else s:=ReadLine; end; until code=0; idx:=FBlocks.IndexOf(BlockName); if idx>=0 then begin blockmesh:=FBlocks.Objects[idx] as TGLBaseMesh; // FLAT STRUCTURES // Insert a block into its parent by copying the contents. // the blockmesh will be freed upon completion, leaving only the copies. for i:=0 to blockmesh.MeshObjects.Count-1 do begin mo_block:=blockmesh.meshobjects[i]; mo_base :=NeedMesh (basemesh,mo_block.name); indexoffset:=mo_base.vertices.count; for j:=0 to mo_block.Vertices.Count-1 do begin pt:=mo_block.vertices[j]; ScaleVector(pt,scale); AddVector(pt,insertpoint); mo_base.Vertices.Add(pt); end; for j:=0 to mo_block.FaceGroups.Count-1 do begin fg_block:=mo_block.facegroups[j] as TFGVertexIndexList; fg_base :=NeedFaceGroup (mo_base,fg_block.mode,fg_block.MaterialName); for k:=0 to fg_block.VertexIndices.count-1 do begin fg_base.VertexIndices.Add(fg_block.VertexIndices[k]+IndexOffset); end; end; end; // TREE STRUCTURES // Instead of copying the contents of the block, they are parented to the // base mesh. If the block already has a parent, a proxy object is created. // WARNING: THE CODE BELOW DOES NOT WORK. (* if blockmesh.Parent =NIL then begin blockmesh.Position.AsAffineVector:=insertpoint; blockmesh.ShowAxes:=TRUE; basemesh.AddChild(blockmesh); for i:=0 to blockmesh.MeshObjects.Count-1 do BuildNormals(blockmesh.MeshObjects[i]); end else begin blockproxy:=TGLproxyObject.CreateAsChild(basemesh); blockproxy.MasterObject:=blockmesh; blockproxy.Position.AsAffineVector:=insertpoint; blockproxy.ShowAxes:=TRUE; end; *) end; PushCode(0); end; function TGLDXFVectorFile.NeedMesh (basemesh:TGLBaseMesh;layer:STRING):TMeshObject; var i:INTEGER; begin i:=0; while (i<basemesh.MeshObjects.Count) and not (basemesh.MeshObjects[i].name =layer) do inc(i); if i<basemesh.MeshObjects.Count then result:=basemesh.MeshObjects[i] else begin result:=TMeshObject.CreateOwned(basemesh.MeshObjects); result.Mode:=momFaceGroups; result.Name :=layer; end; end; function TGLDXFVectorFile.NeedFaceGroup (m:TMeshObject;fgmode:TFaceGroupMeshMode;fgmat:STRING):TFGVertexIndexList; var i:INTEGER; acadcolor:LONGINT; libmat:TGLLibMaterial; fg:TFGVertexIndexList; begin i:=0; while (i<m.FaceGroups.Count) and not ((m.FaceGroups[i] is TFGVertexIndexList) and ((m.FaceGroups[i] as TFGVertexIndexList).mode=fgmode) and (m.FaceGroups[i].MaterialName =fgmat)) do inc(i); if i<m.FaceGroups.Count then fg:=m.FaceGroups[i] as TFGVertexIndexList else begin fg:=TFGVertexIndexList.createowned (m.FaceGroups); fg.Mode :=fgmode; fg.MaterialName :=fgmat; if owner.MaterialLibrary<>NIL then begin libmat:=owner.MaterialLibrary.Materials.GetLibMaterialByName(fgmat); if libmat=NIL then // create a colored material begin acadcolor:=StrToIntDef(fgmat,0); if acadcolor in [1..255] then begin libmat:=owner.MaterialLibrary.Materials.Add; libmat.Name :=fgmat; libmat.Material.FrontProperties.Diffuse.AsWinColor :=rgb2bgr(dxfcolorsrgb[acadcolor]); libmat.Material.BackProperties.Diffuse.AsWinColor :=rgb2bgr(dxfcolorsrgb[acadcolor]); libmat.Material.FaceCulling := fcNoCull; end; end; end; end; result:=fg; end; procedure TGLDXFVectorFile.NeedMeshAndFaceGroup (basemesh:TGLBaseMesh;layer:STRING;fgmode:TFaceGroupMeshMode;fgmat:STRING; var m:TMeshObject;var fg:TFGVertexIndexList); begin m :=NeedMesh (basemesh,layer); fg:=NeedFaceGroup (m,fgmode,fgmat); end; procedure TGLDXFVectorFile.ReadEntity3Dface(basemesh:TGLBaseMesh); var code,i:INTEGER; pts:ARRAY[0..3] of TAffineVector; isquad:BOOLEAN; fg:TFGVertexIndexList; color,layer:STRING; m:TMeshObject; begin color:=''; layer:=''; isquad:=FALSE; for i:=0 to 3 do pts[i]:=NullVector; repeat code:=GetCode; case code of 0:; 8: layer:=ReadLine; // Layer 10: pts[0][0] := ReadDouble; 11: pts[1][0] := ReadDouble; 12: pts[2][0] := ReadDouble; 13: begin pts[3][0] := ReadDouble; isquad:=TRUE end; 20: pts[0][1] := ReadDouble; 21: pts[1][1] := ReadDouble; 22: pts[2][1] := ReadDouble; 23: begin pts[3][1] := ReadDouble; isquad:=TRUE end; 30: pts[0][2] := ReadDouble; 31: pts[1][2] := ReadDouble; 32: pts[2][2] := ReadDouble; 33: begin pts[3][2] := ReadDouble; isquad:=TRUE end; 62: Color:=ReadLine; // Color else ReadLine; end; until code=0; PushCode(0); isquad:=isquad and ((pts[2][0]<>pts[3][0]) or (pts[2][1]<>pts[3][1]) or (pts[2][2]<>pts[3][2])); if isquad then NeedMeshAndFaceGroup (basemesh,layer,fgmmQuads,color,m,fg) else NeedMeshAndFaceGroup (basemesh,layer,fgmmTriangles,color,m,fg); fg.Add(m.Vertices.FindOrAdd(pts[0])); fg.Add(m.Vertices.FindOrAdd(pts[1])); fg.Add(m.Vertices.FindOrAdd(pts[2])); if isquad then fg.Add(m.Vertices.FindOrAdd(pts[3])); end; procedure TGLDXFVectorFile.ReadEntityPolyLine(basemesh:TGLBaseMesh); procedure ReadPolylineVertex (m:TMeshObject;vertexindexbase:INTEGER); var Color:STRING; pt:TAffineVector; fg:TFGVertexIndexList; code,idx, i70,i71,i72,i73,i74:INTEGER; begin color:=''; pt :=NullVector; i70:=0; i71:=0; i72:=0; i73:=0; i74:=0; repeat code:=GetCode; case code of 0 :; 5 : ReadLine; // ID :=ReadHex16; 8 : ReadLine; // ignore per vertex layer. Polyline vertices cannot cross layers! 10 : pt[0]:=ReadDouble; 20 : pt[1]:=ReadDouble; 30 : pt[2]:=ReadDouble; 62 : Color:=ReadLine; 70 : i70 := ReadInt; 71 : i71 := abs(ReadInt); // negative values should hide points... we cannot 72 : i72 := abs(ReadInt); 73 : i73 := abs(ReadInt); 74 : i74 := abs(ReadInt); 100: ReadLine; // Subclass Marker 330: ReadLine; // Soft Pointer? else ReadLine; end; until code=0; PushCode(0); if (color='') or (color='256') or (color='BYLAYER') then begin idx:=FLayers.IndexOf(m.name); if idx>=0 then color:=IntToStr (LONGINT(FLayers.Objects[idx])); end; if i70 and 192 =192 then begin m.Vertices.add(pt); end else if i70 and 192=128 then begin i71:= i71-1+vertexindexbase; i72:= i72-1+vertexindexbase; i73:= i73-1+vertexindexbase; if i74=0 then begin fg:=NeedFaceGroup (m,fgmmTriangles,Color); fg.Add(i71); fg.Add(i72); fg.Add(i73); end else begin i74:= i74-1+vertexindexbase; fg:=NeedFaceGroup (m,fgmmQuads,Color); fg.Add(i71); fg.Add(i72); fg.Add(i73); fg.Add(i74); end end else // hmm? end; var m:TMeshObject; code, vertexindexbase:INTEGER; s,layer:STRING; begin m:=NIL; vertexindexbase:=0; repeat code:=GetCode; s:=ReadLine; if (code=8) then begin layer:=s; m:=NeedMesh (basemesh,Layer); vertexindexbase:=m.Vertices.Count; end; if (code=0) and (s='VERTEX') and (m<>NIL) then ReadPolylineVertex (m,vertexindexbase); until (code=0) and (s='SEQEND'); repeat code:=GetCode; if code<>0 then readline; until (code=0); PushCode(0); end; procedure TGLDXFVectorFile.ReadEntities(basemesh:TGLBaseMesh); var code:integer; s:STRING; begin repeat code:=GetCode; // DoProgress (psRunning,FSourceStream.Position/FSourceStream.Size*100,false,''); case code of 0: begin s:=ReadLine; if s='POLYLINE' then ReadEntityPolyLine (basemesh) else if s='3DFACE' then ReadEntity3Dface (basemesh) else if s='INSERT' then ReadInsert (basemesh) else if s='ENDSEC' then begin end else if s='ENDBLK' then begin end else asm nop end (* put breakpoint here to catch other entities *) end; else s:=ReadLine; end; until (code=0) and ((s='ENDSEC') or (s='ENDBLK')); end; // build normals procedure BuildNormals (m:TMeshObject); var i,j:INTEGER; v1,v2,v3,v4,n:TAffineVector; begin for i:=0 to m.Vertices.Count-1 do m.Normals.Add(0,0,0); for i:=0 to m.FaceGroups.Count-1 do if m.FaceGroups[i] is TFGVertexIndexList then with m.FaceGroups[i] as TFGVertexIndexList do case mode of fgmmTriangles: begin for j:=0 to (VertexIndices.count div 3)-1 do begin v1:= m.Vertices[ VertexIndices[j*3 ] ]; v2:= m.Vertices[ VertexIndices[j*3+1] ]; v3:= m.Vertices[ VertexIndices[j*3+2] ]; n:=CalcPlaneNormal(v1,v2,v3); m.Normals.items[ VertexIndices[j*3 ] ]:=VectorAdd (m.Normals.items[VertexIndices[j*3 ]],n); m.Normals.items[ VertexIndices[j*3+1] ]:=VectorAdd (m.Normals.items[VertexIndices[j*3+1]],n); m.Normals.items[ VertexIndices[j*3+2] ]:=VectorAdd (m.Normals.items[VertexIndices[j*3+2]],n); end; end; fgmmQuads : begin for j:=0 to (VertexIndices.count div 4)-1 do begin v1:= m.Vertices[ VertexIndices[j*4 ] ]; v2:= m.Vertices[ VertexIndices[j*4+1] ]; v3:= m.Vertices[ VertexIndices[j*4+2] ]; v4:= m.Vertices[ VertexIndices[j*4+3] ]; n:=CalcPlaneNormal(v1,v2,v3); m.Normals.items[ VertexIndices[j*4 ] ]:=VectorAdd (m.Normals.items[VertexIndices[j*4 ]],n); m.Normals.items[ VertexIndices[j*4+1] ]:=VectorAdd (m.Normals.items[VertexIndices[j*4+1]],n); m.Normals.items[ VertexIndices[j*4+2] ]:=VectorAdd (m.Normals.items[VertexIndices[j*4+2]],n); m.Normals.items[ VertexIndices[j*4+3] ]:=VectorAdd (m.Normals.items[VertexIndices[j*4+3]],n); end; end; end; for i:=0 to m.Normals.Count-1 do m.Normals.items[i]:=VectorNormalize(m.Normals.items[i]); end; procedure TGLDXFVectorFile.LoadFromStream(aStream:TStream); var s :STRING; code ,i :INTEGER; begin FLastPercentDone:=1; // DoProgress (psStarting,0,false,'Starting'); FEof :=False; FSourceStream:=aStream; FLineNo :=0; HasPushedCode:=FALSE; FLayers :=TStringList.create; FBlocks :=TStringList.create; while not FEof do begin // DoProgress (psStarting,FSourceStream.Position/FSourceStream.Size*90,false,''); code:=GetCode; if (code=0) then begin s:=ReadLine; if s='EOF' then break else if s='SECTION' then begin code:=GetCode; if code<>2 then raise Exception.create ('Name must follow Section'+' on Line #'+IntToStr(FLineNo)) else begin s:=ReadLine; if s='HEADER' then SkipSection else if s='BLOCKS' then ReadBlocks else if s='ENTITIES' then ReadEntities (owner) else if s='CLASSES' then SkipSection else if s='TABLES' then ReadTables else if s='OBJECTS' then SkipSection else SkipSection; end end else if s='ENDSEC' then raise Exception.create ('SECTION/ENDSEC Mismatch'+' on Line #'+IntToStr(FLineNo)) end else s:=ReadLine; // raise Exception.create ('Invalid Group Code'); end; // calc normals FLayers.free; for i:=fblocks.count-1 downto 0 do (FBlocks.objects[i] as TGLFreeForm).free; FBlocks.Free; for i:=0 to owner.MeshObjects.Count-1 do BuildNormals(owner.MeshObjects[i]); // DoProgress (psEnding,100,false,''); end; initialization RegisterVectorFileFormat('dxf','Drawing Exchange Format' ,TGLDXFVectorFile); end.
unit St_sp_Category_Class_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, ToolWin, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, FIBQuery, pFIBQuery, pFIBStoredProc, ActnList, FIBDataSet, pFIBDataSet, cxContainer, cxLabel, ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, Menus; type TClassCategoryForm = class(TForm) ToolBar1: TToolBar; AddButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; RefreshButton: TToolButton; SelectButton: TToolButton; ExitButton: TToolButton; ImageListOfCategory: TImageList; cxGrid1: TcxGrid; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1DBTableView1DBColumn1: TcxGridDBColumn; cxGrid1DBTableView1ID_CATEGORY_CLASS: TcxGridDBColumn; cxGrid1DBTableView1NAME_CATEGORY_CLASS: TcxGridDBColumn; cxGrid1DBTableView1PEOPLE: TcxGridDBColumn; cxGrid1DBTableView1PLACES: TcxGridDBColumn; cxGrid1Level1: TcxGridLevel; Panel1: TPanel; cxLabel1: TcxLabel; PeopleLabel: TcxLabel; cxLabel2: TcxLabel; PlaceLabel: TcxLabel; DataSet: TpFIBDataSet; DataSource: TDataSource; WriteProc: TpFIBStoredProc; ReadDataSet: TpFIBDataSet; ActionList1: TActionList; AddAction: TAction; EditAction: TAction; DeleteAction: TAction; RefreshAction: TAction; ExitAction: TAction; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; PopupMenu1: TPopupMenu; N1: TMenuItem; N2: TMenuItem; DeleteAction1: TMenuItem; RefreshAction1: TMenuItem; SearchButton_Naim: TToolButton; N3: TMenuItem; procedure ExitButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DataSetAfterScroll(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure DataSetAfterOpen(DataSet: TDataSet); procedure SelectButtonClick(Sender: TObject); procedure cxGrid1DBTableView1DblClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure SearchButton_NaimClick(Sender: TObject); private { Private declarations } public KeyField : string; // AllowMultiSelect : boolean; MultiResult:Variant; constructor Create(Aowner:TComponent;FormST:TFormStyle);overload; function GetMultiValue():variant; procedure SelectAll; end; var ClassCategoryForm: TClassCategoryForm; implementation uses DataModule1_Unit, St_sp_Category_Class_Form_Add, MAIN, Search_LgotUnit, Search_Unit; {$R *.dfm} constructor TClassCategoryForm.Create(Aowner:TComponent;FormST:TFormStyle); begin Inherited Create(Aowner); FormStyle:=FormST; SelectButton.Enabled:=true; cxGrid1DBTableView1.OptionsSelection.MultiSelect:=true; end; function TClassCategoryForm.GetMultiValue():variant; begin ShowModal; GetMultiValue:=MultiResult; end; procedure TClassCategoryForm.SelectAll; begin DataSet.Close; DataSet.Open; end; procedure TClassCategoryForm.ExitButtonClick(Sender: TObject); begin close; end; procedure TClassCategoryForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; if MainForm.N6.Enabled = false then MainForm.N6.Enabled := true; MainForm.CloseAllWindows; end; procedure TClassCategoryForm.DataSetAfterScroll(DataSet: TDataSet); begin if DataSet.RecordCount = 0 then exit; PeopleLabel.Caption := IntToStr(DataSet['PEOPLE']); PlaceLabel.Caption := FloatToStr(DataSet['PLACES']); end; procedure TClassCategoryForm.FormCreate(Sender: TObject); begin KeyField := 'ID_CATEGORY_CLASS'; end; procedure TClassCategoryForm.FormShow(Sender: TObject); begin // cxGrid1DBTableView1.Items[0].DataBinding.ValueTypeClass := TcxIntegerValueType; //if AllowMultiSelect then cxGrid1DBTableView1.Columns[0].Visible := true; if not DataSet.Active then SelectAll; end; procedure TClassCategoryForm.DataSetAfterOpen(DataSet: TDataSet); begin if DataSet.RecordCount = 0 then begin EditButton.Enabled := false; DeleteButton.Enabled := false; // SelectButton.Enabled := false; end else begin EditButton.Enabled := true; DeleteButton.Enabled := true; // SelectButton.Enabled := true; end; end; procedure TClassCategoryForm.SelectButtonClick(Sender: TObject); var i : integer; RecMultiSelected : integer; begin if cxGrid1DBTableView1.OptionsSelection.MultiSelect=true then begin RecMultiSelected:=cxGrid1DBTableView1.DataController.GetSelectedCount; MultiResult:=VarArrayCreate([0,RecMultiSelected-1],varVariant); for i:=0 to cxGrid1DBTableView1.DataController.GetSelectedCount-1 do begin MultiResult[i]:=cxGrid1DBTableView1.Controller.SelectedRecords[i].Values[1]; end; end; ModalResult := mrOK; end; procedure TClassCategoryForm.cxGrid1DBTableView1DblClick(Sender: TObject); begin ModalResult:=mrOk; end; procedure TClassCategoryForm.AddButtonClick(Sender: TObject); var ActionStr : string; new_id : integer; begin ActionStr := 'Добавить'; ClassCategoryFormAdd := TClassCategoryFormAdd.Create(Self); ClassCategoryFormAdd.Caption := ActionStr + ' ' + ClassCategoryFormAdd.Caption; ClassCategoryFormAdd.OKButton.Caption := ActionStr; if ClassCategoryFormAdd.ShowModal = mrOK then begin WriteProc.StoredProcName := 'ST_INI_CATEGORY_CLASS_INSERT'; WriteProc.Transaction.StartTransaction; WriteProc.Prepare; WriteProc.ParamByName('NAME_CATEGORY_CLASS').AsString := ClassCategoryFormAdd.NameEdit.Text; WriteProc.ParamByName('PEOPLE').AsInteger := StrToInt(ClassCategoryFormAdd.PeopleEdit.Text); WriteProc.ParamByName('PLACES').AsFloat := StrToFloat(ClassCategoryFormAdd.PlaceEdit.Text); WriteProc.ExecProc; new_id := WriteProc[KeyField].AsInteger; WriteProc.Transaction.Commit; WriteProc.Close; SelectAll; DataSet.Locate(KeyField, new_id, []); end; ClassCategoryFormAdd.Free; end; procedure TClassCategoryForm.EditButtonClick(Sender: TObject); var ActionStr, ActionKeyStr : string; id : integer; begin id := DataSet[KeyField]; ActionStr := 'Изменить'; ActionKeyStr:='Принять'; ClassCategoryFormAdd := TClassCategoryFormAdd.Create(Self); ClassCategoryFormAdd.Caption := ActionStr + ' ' + ClassCategoryFormAdd.Caption; ClassCategoryFormAdd.OKButton.Caption := ActionKeyStr; ClassCategoryFormAdd.NameEdit.Text := DataSet['NAME_CATEGORY_CLASS']; ClassCategoryFormAdd.PeopleEdit.Text := IntToStr(DataSet['PEOPLE']); ClassCategoryFormAdd.PlaceEdit.Text := FloatToStr(DataSet['PLACES']); if ClassCategoryFormAdd.ShowModal = mrOK then begin WriteProc.StoredProcName := 'ST_INI_CATEGORY_CLASS_UPDATE'; WriteProc.Transaction.StartTransaction; WriteProc.Prepare; WriteProc.ParamByName(KeyField).AsInteger := id; WriteProc.ParamByName('NAME_CATEGORY_CLASS').AsString := ClassCategoryFormAdd.NameEdit.Text; WriteProc.ParamByName('PEOPLE').AsInteger := StrToInt(ClassCategoryFormAdd.PeopleEdit.Text); WriteProc.ParamByName('PLACES').AsFloat := StrToFloat(ClassCategoryFormAdd.PlaceEdit.Text); WriteProc.ExecProc; WriteProc.Transaction.Commit; WriteProc.Close; SelectAll; DataSet.Locate(KeyField, id, []); end; ClassCategoryFormAdd.Free; end; procedure TClassCategoryForm.DeleteButtonClick(Sender: TObject); var selected : integer; begin //if MessageBox(Handle,PChar('Вы действительно хотите удалить класс категории "' + DataSet.FieldByName('NAME_CATEGORY_CLASS').AsString + ' "?'),'Подтвердите ...',MB_YESNO or MB_ICONQUESTION)= mrNo then exit; if MessageBox(Handle,PChar('Вы действительно хотите удалить запись ?'),'Подтверждение удаления ...',MB_YESNO or MB_ICONQUESTION)= mrNo then exit; ReadDataSet.SelectSQL.Clear; ReadDataSet.SelectSQL.Text:='select CAN from ST_INI_CATEGORY_CLASS_CAN_DELET('+ inttostr(DataSet[KeyField])+')'; ReadDataSet.Open; if ReadDataSet['Can']=0 then begin ShowMessage('Невозможно удалить . Данное наименование используется.'); ReadDataSet.Close; exit; end; ReadDataSet.Close; WriteProc.StoredProcName := 'ST_INI_CATEGORY_CLASS_DELETE'; WriteProc.Transaction.StartTransaction; WriteProc.Prepare; WriteProc.ParamByName(KeyField).AsInteger := DataSet[KeyField]; WriteProc.ExecProc; WriteProc.Transaction.Commit; WriteProc.Close; selected := cxGrid1DBTableView1.DataController.FocusedRowIndex-1; SelectAll; cxGrid1DBTableView1.DataController.FocusedRowIndex := selected; end; procedure TClassCategoryForm.RefreshButtonClick(Sender: TObject); var selected : integer; begin selected := -1; if DataSet.RecordCount <> 0 then selected := DataSet[KeyField]; SelectAll; DataSet.Locate(KeyField, selected, []); end; procedure TClassCategoryForm.SearchButton_NaimClick(Sender: TObject); begin if PopupMenu1.Items[4].Checked= true then begin Search_LgotForm := TSearch_LgotForm.Create(Self); while Search_LgotForm.FindFlag = false do begin if Search_LgotForm.FindClosed = true then begin Search_LgotForm.Free; exit; end; if Search_LgotForm.ShowModal = mrOk then begin if Search_LgotForm.FindFlag = true then begin cxGrid1DBTableView1NAME_CATEGORY_CLASS.SortOrder:=soAscending; DataSet.Locate('NAME_CATEGORY_CLASS', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); Search_LgotForm.Free; exit; end else begin cxGrid1DBTableView1NAME_CATEGORY_CLASS.SortOrder:=soAscending; DataSet.Locate('NAME_CATEGORY_CLASS', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); Search_LgotForm.showModal; end; end; end; if Search_LgotForm.FindFlag = true then begin cxGrid1DBTableView1NAME_CATEGORY_CLASS.SortOrder:=soAscending; DataSet.Locate('NAME_CATEGORY_CLASS', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); Search_LgotForm.Free; end; end else begin Search_Form:= TSearch_Form.create(self); if Search_Form.ShowModal = mrOk then begin DataSet.Locate('NAME_CATEGORY_CLASS', Search_Form.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); end; end; end; end.
unit PaiDeForms; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, siComp, siLangRT; type TFrmParentForms = class(TForm) siLang: TsiLangRT; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } protected fLangLoaded : Boolean; procedure LoadLangFile; public { Public declarations } end; var FrmParentForms: TFrmParentForms; implementation uses uDM, uMsgBox, uMsgConstant, uDMGlobal; {$R *.DFM} procedure TFrmParentForms.LoadLangFile; begin //Setup Language if (not fLangLoaded) and (siLang.StorageFile <> '') then begin if FileExists(DMGlobal.LangFilesPath + siLang.StorageFile) then siLang.LoadAllFromFile(DMGlobal.LangFilesPath + siLang.StorageFile, True) else MsgBox(MSG_INF_DICTIONARI_NOT_FOUND ,vbOKOnly + vbInformation); fLangLoaded := True; end; end; procedure TFrmParentForms.FormCreate(Sender: TObject); begin fLangLoaded := (DMGlobal.IDLanguage = LANG_ENGLISH); Caption := Application.Title; end; procedure TFrmParentForms.FormShow(Sender: TObject); begin LoadLangFile; end; procedure TFrmParentForms.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // amfsouza 01.28.2011 - if user press shift + F10, supports knows the name of form. if ( ssShift in Shift ) and ( key = VK_F10 ) then showMessage(self.Name); end; end.
{ ****************************************************** EMI Background Viewer Copyright (c) 2004 - 2010 Bgbennyboy Http://quick.mixnmojo.com ****************************************************** } unit uLABManager; interface uses classes, sysutils, Contnrs, forms, uFileReader, ZLibExGz; type EInvalidFile = class(exception); TDebugEvent = procedure(DebugText: string) of object; TProgressEvent = procedure(ProgressMax: integer; ProgressPos: integer) of object; TOnDoneLoading = procedure(FileNamesCount: integer) of object; TLABType = (Grim, EMI); TLABChildFile = class FileName: string; Size: integer; Offset: integer; end; type TLABManager = class protected fBundle: TExplorerFileStream; fBundleFileName: string; fLabType: TLABType; fonDoneLoading: TOnDoneLoading; fonProgress: TProgressEvent; fonDebug: TDebugEvent; function DetectBundle: boolean; function GetFilesCount: integer; function GetFileName(Index: integer): string; function GetFileSize(Index: integer): integer; function GetFileOffset(Index: integer): integer; function IsZipped: boolean; procedure Log(Text: string); public BundleFiles: TObjectList; constructor Create(ResourceFile: string); destructor Destroy; override; procedure ParseFiles; procedure SaveFile(FileNo: integer; DestDir, FileName: string); procedure SaveFileToStream(FileNo: integer; DestStream: TStream; Unzip: boolean = false); procedure SaveFiles(DestDir: string); property Count: integer read GetFilesCount; property FileName[Index: integer]: string read GetFileName; property FileSize[Index: integer]: integer read GetFileSize; property FileOffset[Index: integer]: integer read GetFileOffset; property LABType: TLABType read fLabType; end; const strErrInvalidFile: string = 'Not a valid LAB File'; strErrFileSize: string = 'File size <=0! Save cancelled.'; strErrFileNo: string = 'Invalid file number! Save cancelled.'; strSavingFile: string = 'Saving file '; implementation constructor TLABManager.Create(ResourceFile: string); begin try fBundle := TExplorerFileStream.Create(ResourceFile); except on E: EInvalidFile do raise ; end; fBundleFileName := ExtractFileName(ResourceFile); BundleFiles := TObjectList.Create(true); if DetectBundle = false then raise EInvalidFile.Create(strErrInvalidFile); end; destructor TLABManager.Destroy; begin if BundleFiles <> nil then begin BundleFiles.Free; BundleFiles := nil; end; if fBundle <> nil then fBundle.Free; inherited; end; function TLABManager.DetectBundle: boolean; var BlockName: string; begin Result := false; BlockName := fBundle.ReadBlockName; if BlockName = 'LABN' then begin Result := true; fBundle.Seek(16, soFromBeginning); if fBundle.ReadDWord = 0 then fLabType := Grim else fLabType := EMI; end; end; function TLABManager.GetFileName(Index: integer): string; begin if (not assigned(BundleFiles)) or (index < 0) or (index > GetFilesCount) then Result := '' else Result := TLABChildFile(BundleFiles.Items[Index]).FileName; end; function TLABManager.GetFileOffset(Index: integer): integer; begin if (not assigned(BundleFiles)) or (index < 0) or (index > GetFilesCount) then Result := -1 else Result := TLABChildFile(BundleFiles.Items[Index]).Offset; end; function TLABManager.GetFilesCount: integer; begin if BundleFiles <> nil then Result := BundleFiles.Count else Result := 0; end; function TLABManager.GetFileSize(Index: integer): integer; begin if (not assigned(BundleFiles)) or (index < 0) or (index > GetFilesCount) then Result := -1 else Result := TLABChildFile(BundleFiles.Items[Index]).Size; end; function TLABManager.IsZipped: boolean; begin if fBundle.ReadDWord = 559903 then result:=true else result:=false; fBundle.Seek(-4, soFromCurrent); end; procedure TLABManager.Log(Text: string); begin if assigned(fonDebug) then fonDebug(Text); end; procedure TLABManager.ParseFiles; var numFiles, NameDirSize, NameDirOffset, i, CurrFile: integer; FileObject: TLABChildFile; TempByte: byte; TempFilename: string; begin fBundle.Seek(8, soFromBeginning); numFiles := fBundle.ReadDWord; // Number of files in LAB NameDirSize := fBundle.ReadDWord; // Size of Name Directory if fLabType = EMI then NameDirOffset := fBundle.ReadDWord - 81167 else NameDirOffset := 16 + (16 * numFiles); // Parse files for i := 0 to numFiles - 1 do begin FileObject := TLABChildFile.Create; fBundle.Seek(4, sofromcurrent); // Offset in Name Directory FileObject.Offset := fBundle.ReadDWord; FileObject.Size := fBundle.ReadDWord; fBundle.Seek(4, sofromcurrent); // 4 zero bytes BundleFiles.Add(FileObject); end; // Add names fBundle.Seek(NameDirOffset, soFromBeginning); //Parse namedir and extract the null terminated filenames CurrFile := 0; for i := 0 to NameDirSize - 1 do begin TempByte:=fBundle.readbyte; if TempByte=0 then //Because the filenames are null terminated begin TLABChildFile(BundleFiles[CurrFile]).Filename := TempFilename; TempFilename:=''; inc(CurrFile); end else TempFilename:=TempFilename + chr(TempByte xor $96); //do the xoring here - if we do it in filereader then tempbyte doesnt =0 because its already xor'ed end; if (assigned(fonDoneLoading)) then fonDoneLoading(numFiles); end; procedure TLABManager.SaveFile(FileNo: integer; DestDir, FileName: string); var SaveFile: TFileStream; begin if TLABChildFile(BundleFiles.Items[FileNo]).Size <= 0 then begin Log(strErrFileSize); exit; end; if (FileNo < 0) or (FileNo > BundleFiles.Count) then begin Log(strErrFileNo); exit; end; Log(strSavingFile + FileName); SaveFile := TFileStream.Create(IncludeTrailingPathDelimiter(DestDir) + FileName, fmOpenWrite or fmCreate); try SaveFileToStream(FileNo, SaveFile); finally SaveFile.Free; end; end; procedure TLABManager.SaveFiles(DestDir: string); var i: integer; SaveFile: TFileStream; begin for i := 0 to BundleFiles.Count - 1 do begin ForceDirectories(extractfilepath(IncludeTrailingPathDelimiter(DestDir) + TLABChildFile(BundleFiles.Items[i]).FileName)); SaveFile := TFileStream.Create(IncludeTrailingPathDelimiter(DestDir) + TLABChildFile(BundleFiles.Items[i]).FileName, fmOpenWrite or fmCreate); try SaveFileToStream(i, SaveFile); finally SaveFile.Free; if assigned(fonProgress) then fonProgress(GetFilesCount - 1, i); Application.Processmessages; end; end; end; procedure TLABManager.SaveFileToStream(FileNo: integer; DestStream: TStream; Unzip: boolean = false); var Ext: string; TempStream: TMemoryStream; begin if TLABChildFile(BundleFiles.Items[FileNo]).Size <= 0 then begin Log(strErrFileSize); exit; end; if (FileNo < 0) or (FileNo > BundleFiles.Count) then begin Log(strErrFileNo); exit; end; Ext := Uppercase(ExtractFileExt(TLABChildFile(BundleFiles.Items[FileNo]).FileName)); fBundle.Seek(TLABChildFile(BundleFiles.Items[FileNo]).Offset, soFromBeginning); if (Unzip) and (IsZipped) then begin TempStream := TMemoryStream.Create; try TempStream.CopyFrom(fBundle, TLABChildFile(BundleFiles.Items[FileNo]).Size); TempStream.Position := 0; GZDecompressStream(TempStream, DestStream); finally TempStream.Free; end; end else DestStream.CopyFrom(fBundle, TLABChildFile(BundleFiles.Items[FileNo]).Size); DestStream.Position := 0; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Console.Command.Help; interface uses VSoft.CancellationToken, DPM.Core.Configuration.Interfaces, DPM.Core.Logging, DPM.Console.Writer, DPM.Console.ExitCodes, DPM.Console.Command, DPM.Console.Command.Base; type THelpCommand = class(TBaseCommand) private FConsole : IConsoleWriter; protected function Execute(const cancellationToken : ICancellationToken) : TExitCode;override; public constructor Create(const console : IConsoleWriter; const logger : ILogger; const configurationManager : IConfigurationManager);reintroduce; end; implementation uses Generics.Defaults, VSoft.CommandLine.Options, DPM.Console.Banner, DPM.Console.Types, DPM.Console.Options; { THelpCommand } constructor THelpCommand.Create(const console: IConsoleWriter; const logger: ILogger; const configurationManager : IConfigurationManager); begin inherited Create(logger, configurationManager); FConsole := console; end; function THelpCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode; begin result := TExitCode.OK; if THelpOptions.HelpCommand = TDPMCommand.None then begin FConsole.WriteLine; FConsole.WriteLine('Type ''dpm help <command>'' for help on a specific command.'); TOptionsRegistry.DescriptionTab := 43; TOptionsRegistry.PrintUsage( procedure(const value : string) begin FConsole.WriteLine(value); end); FConsole.WriteLine; end else begin FConsole.WriteLine; TOptionsRegistry.DescriptionTab := 43; TOptionsRegistry.PrintUsage(CommandString[THelpOptions.HelpCommand], procedure (const value : string) begin FConsole.WriteLine(value); end); FConsole.WriteLine; end; end; end.
{En un Torneo de Arquería se presentan un conjunto de participantes y tienen todos N oportunidades. Del torneo se conoce:  Nombre del arquero (***=fin de datos)  Coordenadas del punto de impacto P(x,y) de los N tiros El Blanco tiene centro en las coordenadas C(0,0). La zona A (más cercana) tiene un radio de 5 y la B un radio de 12. Se pide ingresar la información, calcular e informar : a) Para cada participante, porcentaje de aciertos en cada Zona. b) Cuántos participantes dieron por lo menos una vez en la zona A más cercana al blanco. Desarrollar una función EnZona que a partir del punto P(x,y) obtenga la distancia del impacto al Centro y determine en qué zona cayó. (Distancia=Sqrt( Sqr(X-X0)+Sqr(Y-Y0)) )} Program arqueria; Function EnZona(x,y:byte):real; begin EnZona:= sqrt( sqr(0 - x) + sqr(0 - y)); end; Var Nom:string[10]; x,y:byte; i,N,ContA,ContB,ContC,ContMax:word; PorcA,PorcB,PorC,zon:real; Begin ContMax:= 0; write('Ingrese el nombre del arquero: ');readln(Nom); While (Nom <> '***') do begin ContA:= 0; ContB:= 0; ContC:= 0; write('Ingrese la cantidad de oportunidades: ');readln(N); For i:= 1 to N do begin write('Ingrese la coordenada x del lanzamiento: ');readln(x); write('Ingrese la coordenada y del lanzamiento: ');readln(y); zon:= EnZona(x,y); If (zon <= 5) then begin writeln('El disparo cayo en el radio de A'); ContA:= ContA + 1; end Else if (zon <= 12) then begin writeln('El disparo cayo en el radio de B '); ContB:= ContB + 1; end Else begin writeln('El disparo cayo en el radio de C'); ContC:= ContC + 1; end; writeln; end; If (x <= 5) then ContMax:= ContMax + 1 Else if (y <= 5) then ContMax:= ContMax + 1; writeln; PorcA:= (ContA / N) * 100; PorcB:= (ContB / N) * 100; PorC:= (ContC / N) * 100; writeln('a- ',Nom,' tuvo un porcentaje de acierto en los blancos A: ',PorcA:2:0,' % B: ',PorcB:2:0,' % C: ',PorC:2:0,' %'); writeln; writeln('Si desea finalizar escriba *** en lugar del nombre'); write('Ingrese el nombre del arquero: ');readln(Nom); end; writeln('b- La cantidad de participantes que dieron en la zona A mas cercana del blanco son: ',ContMax); end.
unit DatabaseConnection; interface uses SqlExpr, SimpleDs, DB, Classes; type // Enumerator of suported comand types TSqlCommandType = (sqcSelect, sqcOther); // Class to implement a list of SQL parameters TSqlParams = class private paramCount : Integer; params : Array of TParam; // Sets the params list to a given size procedure SetParamsCount(newCount : Integer); // Adds a variant parameter procedure Add(name : String; value : Variant); overload; // Gets a parameter in the given index function Get(index : Integer) : TParam; public // Creates a new instance constructor Create; // Destroy the current instance destructor Destroy; override; // Cears the current list of parameters procedure Clear; // Adds an integer parameter procedure AddInteger(name : String; value : Integer); overload; // Adds a double parameter procedure AddDouble(name : String; value : Double); overload; // Adds a DateTime parameter procedure AddDateTime(name : String; value : TDateTime); overload; // Adds a string parameter procedure AddString(name : String; value : String); overload; // Adds a boolean parameter procedure AddBoolean(name : String; value : Boolean); overload; // Adds a null value parameter procedure AddNullValue(name : String); overload; // Gets the list of parameters in the current instance property Items[index: Integer]: TParam read Get; default; // Gets the parameters count property Count : Integer read paramCount; end; // Class to implement a connection to a SQL database TDatabaseConnection = class(TSQLConnection) private // Sets parameters from the list to a dataset procedure SetParameters(dataSet : TSimpleDataSet; sqlStatementParams : TSqlParams); // Executes a SQL command returning the dataset used to execute command function ExecuteCommand(sqlCommand : String; params : TSqlParams; comandType : TSqlCommandType) : TSimpleDataSet; overload; virtual; public // Executes a SQL Select command with no parameters function ExecuteSelect(sqlCommand : String) : TSimpleDataSet; overload; virtual; // Executes a SQL Select command with given parameters function ExecuteSelect(sqlCommand : String; params : TSqlParams) : TSimpleDataSet; overload; virtual; // Executes a SQL command without output (E.g.: Insert, update, delete) // with no parameters function Execute(sqlCommand : String) : Boolean; overload; virtual; // Executes a SQL command without output (E.g.: Insert, update, delete) // with given parameters function Execute(sqlCommand : String; params : TSqlParams) : Boolean; overload; virtual; // Connects the current instance to database function Connect : Boolean; // Disconnects the current instance from database function Disconnect : Boolean; end; implementation uses SysUtils, Variants; { TDatabaseConnection } function TDatabaseConnection.Execute(sqlCommand: String): Boolean; begin Result := self.Execute(sqlCommand, nil); end; function TDatabaseConnection.ExecuteSelect(sqlCommand: String): TSimpleDataSet; begin Result := self.ExecuteSelect(sqlCommand, nil); end; function TDatabaseConnection.Execute(sqlCommand: String; params: TSqlParams): Boolean; var commandResult : TSimpleDataSet; begin Result := False; commandResult := self.ExecuteCommand(sqlCommand, params, sqcOther); if Assigned(commandResult) then begin commandResult.Close; FreeAndNil(commandResult); Result := True; end; end; function TDatabaseConnection.ExecuteSelect(sqlCommand: String; params: TSqlParams): TSimpleDataSet; begin Result := self.ExecuteCommand(sqlCommand, params, sqcSelect); end; function TDatabaseConnection.Connect: Boolean; begin Result := True; try self.Open; except on e : Exception do begin Result := False; // TODO: Write log end; end; end; function TDatabaseConnection.Disconnect : Boolean; begin Result := False; if self.ConnectionState <> csStateOpen then begin // TODO: write log Exit; end; try self.Close; except on e : Exception do begin // TODO: Write log Exit; end; end; Result := True; end; procedure TDatabaseConnection.SetParameters(dataSet: TSimpleDataSet; sqlStatementParams: TSqlParams); var i : Integer; begin if not Assigned(sqlStatementParams) then Exit; for i := 0 to sqlStatementParams.Count - 1 do begin dataSet.Params.AddParam(sqlStatementParams[i]); end; end; function TDatabaseConnection.ExecuteCommand(sqlCommand: String; params: TSqlParams; comandType: TSqlCommandType): TSimpleDataSet; var commandDataSet : TSimpleDataSet; begin commandDataSet := TSimpleDataSet.Create(self); commandDataSet.Connection := self; commandDataSet.DataSet.CommandType := ctQuery; commandDataSet.DataSet.CommandText := sqlCommand; commandDataSet.Params.Clear; self.SetParameters(commandDataSet, params); try if comandType = sqcSelect then commandDataSet.Open else commandDataSet.Execute; except on e : Exception do begin FreeAndNil(commandDataSet); // TODO: Write log end; end; Result := commandDataSet; end; { TSqlParams } procedure TSqlParams.Add(name: String; value: Variant); var newParam : TParam; begin self.SetParamsCount(self.paramCount + 1); newParam := TParam.Create(nil); newParam.Name := name; newParam.Value := value; self.params[self.paramCount - 1] := newParam; end; procedure TSqlParams.AddDouble(name: String; value: Double); begin self.Add(name, Variant(value)); end; procedure TSqlParams.AddInteger(name: String; value: Integer); begin self.Add(name, Variant(value)); end; procedure TSqlParams.AddString(name, value: String); begin self.Add(name, Variant(value)); end; procedure TSqlParams.AddDateTime(name: String; value: TDateTime); begin self.Add(name, Variant(value)); end; procedure TSqlParams.AddBoolean(name: String; value: Boolean); begin self.Add(name, Variant(value)); end; procedure TSqlParams.AddNullValue(name: String); begin self.Add(name, Null); end; procedure TSqlParams.Clear; var i : Integer; begin self.SetParamsCount(0); end; constructor TSqlParams.Create; begin self.Clear; end; destructor TSqlParams.Destroy; begin self.Clear; inherited; end; function TSqlParams.Get(index: Integer): TParam; begin Result := self.params[index]; end; procedure TSqlParams.SetParamsCount(newCount: Integer); begin self.paramCount := newCount; SetLength(self.params, self.paramCount); end; end.
//------------------------------------------------------------------------------ //The contents of this file are subject to the Mozilla Public License //Version 1.1 (the "License"); you may not use this file except in compliance //with the License. You may obtain a copy of the License at //http://www.mozilla.org/MPL/ Software distributed under the License is //distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express //or implied. See the License for the specific language governing rights and //limitations under the License. // //The Original Code is MercDev.pas. // //The Initial Developer of the Original Code is Alex Shovkoplyas, VE3NEA. //Portions created by Alex Shovkoplyas are //Copyright (C) 2008 Alex Shovkoplyas. All Rights Reserved. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // TUsbDevice -> TFx2LpDevice -> TMercuryDevice: Mercury hardware ctrl functions //------------------------------------------------------------------------------ unit MercDev; interface uses Windows, Messages, SysUtils, Classes, Forms, SyncObjs, UsbDev, Fx2LpDev, SndTypes; const OZY_IN_EP = $86; OZY_OUT_EP = $02; VRQ_FPGA_LOAD = 2; VRQ_I2C_WRITE = $08; VRQ_I2C_READ = $81; FL_BEGIN = 0; FL_XFER = 1; FL_END = 2; WM_RX_DATA = WM_USER + 45; USB_BLOCK_SIZE = 4096; type TByteKind = (bkUnk, bkC0, bkC1, bkC2, bkC3, bkC4, bkI0, bkI1, bkI2, bkQ0, bkQ1, bkQ2, bkM0, bkM1); TProgressEvent = procedure(Sender: TObject; Current, Total: integer) of object; TMercuryDevice = class; TMercuryThread = class(TThread) private procedure SendFrequency; procedure SendCtrlBytes; public Papa: TMercuryDevice; TempRxData, RxData: TDataBufferF; SampleIdx: integer; ByteKind: TByteKind; IntValue: integer; RxDataReady: boolean; procedure Execute; override; procedure ProcessInputBlock(Buf: TByteArray); procedure InputBlockReady; end; TMercuryDevice = class(TFx2LpDevice) private FOnFpgaProgress: TProgressEvent; FOnData: TNotifyEvent; FLoFrequency: integer; Thr: TMercuryThread; WinH: THandle; procedure WriteI2C(Addr: integer; Data: TByteArray); procedure WriteI2C_TwoBytes(Addr: integer; Byte1, Byte2: Byte); procedure SetLoFrequency(const Value: integer); procedure MercWndProc(var Msg: TMessage); procedure GetRxData; protected procedure CloseDevice; override; procedure Start; procedure SendFpgaCommand(AIdx: integer; AData: TByteArray); procedure DoData(AData: TByteArray; var ADone: boolean); override; public FirmwareFileName, OzyFpgaFileName, MercFpgaFileName: TFileName; SamplesPerBuf, InputSamplingRate: integer; RxData: TDataBufferF; InCritSect, SettCritSect: TCriticalSection; InCtrlBytes: array[bkC0..bkC4] of Byte; OutCtrlBytes: array[bkC1..bkC4] of Byte; FreqChanged, CtrlBytesChanged: boolean; constructor Create; destructor Destroy; override; procedure Open; procedure OpenNoThread; procedure Close; procedure ReadData(AControlPoint: integer; var ABuf: TByteArray); procedure WriteData(AControlPoint: integer; var ABuf: TByteArray); procedure LoadOzyFpga(FileName: TFileName); function ListJtagDevices: string; procedure LoadMercuryFpga(AFileName: TFileName; DevIdx: integer); property LoFrequency: integer read FLoFrequency write SetLoFrequency; property OnFpgaProgress: TProgressEvent read FOnFpgaProgress write FOnFpgaProgress; property OnData: TNotifyEvent read FOnData write FOnData; end; implementation { TMercuryThread } procedure TMercuryThread.Execute; var Buf: TByteArray; begin Priority := tpTimeCritical; //init vars ByteKind := bkUnk; IntValue := 0; SampleIdx := 0; //create buffers SetLength(TempRxData, 2, Papa.SamplesPerBuf); SetLength(RxData, 2, Papa.SamplesPerBuf); SetLength(Buf, USB_BLOCK_SIZE); //ctrl bytes need to be sent on startup Papa.CtrlBytesChanged := true; Papa.FreqChanged := true; //read data in a loop repeat if Terminated then Exit; try if Papa.CtrlBytesChanged then SendCtrlBytes else if Papa.FreqChanged then SendFrequency; Papa.ReadDataInternal(OZY_IN_EP, Buf); ProcessInputBlock(Buf); except on E: Exception do begin Papa.FStatusText := E.Message; Terminate; end; end; if Terminated then Break; until false; end; procedure TMercuryThread.SendCtrlBytes; var Buf: TByteArray; SamplingRateBits: Byte; begin SetLength(Buf, 512); Buf[0] := $7F; Buf[1] := $7F; Buf[2] := $7F; Buf[3] := $00; case Papa.InputSamplingRate of 48000: SamplingRateBits := 0; 96000: SamplingRateBits := 1; 192000: SamplingRateBits := 2; end; Papa.SettCritSect.Enter; try Papa.CtrlBytesChanged := false; Buf[4] := (Papa.OutCtrlBytes[bkC1] and $FC) or SamplingRateBits; Buf[5] := Papa.OutCtrlBytes[bkC2]; Buf[6] := Papa.OutCtrlBytes[bkC3] or $10{rand}; Buf[7] := Papa.OutCtrlBytes[bkC4]; finally Papa.SettCritSect.Leave; end; Papa.WriteData(OZY_OUT_EP, Buf); end; procedure TMercuryThread.SendFrequency; var Freq: array[0..3] of Byte; Buf: TByteArray; begin //read frequency safely Papa.SettCritSect.Enter; try Papa.FreqChanged := false; PInteger(@Freq)^ := Papa.FLoFrequency; finally Papa.SettCritSect.Leave; end; //send frequency to the radio SetLength(Buf, 512); Buf[0] := $7F; Buf[1] := $7F; Buf[2] := $7F; Buf[3] := 2; Buf[4] := Freq[3]; Buf[5] := Freq[2]; Buf[6] := Freq[1]; Buf[7] := Freq[0]; Papa.WriteData(OZY_OUT_EP, Buf); end; procedure TMercuryThread.ProcessInputBlock(Buf: TByteArray); var i: integer; begin for i:=0 to High(Buf) do if (i > 1) and (Buf[i] = $7F) and (Buf[i-1] = $7F) and (Buf[i-2] = $7F) then //synchronize begin IntValue := 0; ByteKind := bkC0; end else //read case ByteKind of bkC0..bkC4: begin Papa.InCtrlBytes[ByteKind] := Buf[i]; Inc(ByteKind); end; bkI0, bkI1, bkQ0, bkQ1: begin IntValue := (IntValue or Buf[i]) shl 8; Inc(ByteKind); end; bkI2: begin IntValue := (IntValue or Buf[i]) shl 8; TempRxData[0, SampleIdx] := IntValue div 256; IntValue := 0; Inc(ByteKind); end; bkQ2: begin IntValue := (IntValue or Buf[i]) shl 8; TempRxData[1, SampleIdx] := IntValue div 256; Inc(SampleIdx); if SampleIdx = Papa.SamplesPerBuf then begin InputBlockReady; SampleIdx := 0; end; IntValue := 0; Inc(ByteKind); end; bkM0: Inc(ByteKind); bkM1: ByteKind := bkI0; end; end; procedure TMercuryThread.InputBlockReady; begin Papa.InCritSect.Enter; try RxData[0] := Copy(TempRxData[0]); RxData[1] := Copy(TempRxData[1]); RxDataReady := true; finally Papa.InCritSect.Leave; end; PostMessage(Papa.WinH, WM_RX_DATA, 0, 0); end; //------------------------------------------------------------------------------ // init //------------------------------------------------------------------------------ constructor TMercuryDevice.Create; begin inherited; InCritSect := TCriticalSection.Create; SettCritSect := TCriticalSection.Create; WinH := AllocateHWnd(MercWndProc); FVendorId := $FFFE; FProductId := 7; InputSamplingRate := 48000; SamplesPerBuf := 512; OutCtrlBytes[bkC1] := $D8; OutCtrlBytes[bkC2] := $00; OutCtrlBytes[bkC3] := $10; OutCtrlBytes[bkC4] := $00; //default file names FirmwareFileName := ExtractFilePath(ParamStr(0)) + 'Ozy_firmware.hex'; OzyFpgaFileName := ExtractFilePath(ParamStr(0)) + 'Ozy_fpga.rbf'; MercFpgaFileName := ExtractFilePath(ParamStr(0)) + 'Merc_fpga.rbf'; end; destructor TMercuryDevice.Destroy; begin CloseDevice; DeallocateHWnd(WinH); SettCritSect.Free; InCritSect.Free; end; //------------------------------------------------------------------------------ // open/close //------------------------------------------------------------------------------ procedure TMercuryDevice.OpenNoThread; begin try Start; //fails if firmware is not loaded except LoadFirmware(FirmwareFileName); Sleep(1500); LoadOzyFpga(OzyFpgaFileName); Sleep(1500); Start; end; end; procedure TMercuryDevice.Open; begin OpenNoThread; Thr := TMercuryThread.Create(true); Thr.Papa := Self; Thr.Resume; end; procedure TMercuryDevice.Start; begin OpenDevice; if FunUsbSetConfiguration(FHandle, 1) < 0 then Err('usb_set_configuration failed'); if FunUsbClaimInterface(FHandle, 0) < 0 then Err('usb_claim_interface failed'); if FunUsbSetAltInterface(FHandle, 0) < 0 then Err('usb_set_altinterface failed'); if FunUsbClearHalt(FHandle, OZY_IN_EP) < 0 then Err('usb_clear_halt(OZY_IN_EP) failed'); if FunUsbClearHalt(FHandle, OZY_OUT_EP) < 0 then Err('usb_clear_halt(OZY_OUT_EP) failed'); end; procedure TMercuryDevice.Close; begin CloseDevice; end; procedure TMercuryDevice.CloseDevice; begin if Thr <> nil then begin Thr.Terminate; Thr.WaitFor; FreeAndNil(Thr); end; if FHandle <> nil then FunUsbReleaseInterface(FHandle, 0); inherited; end; //------------------------------------------------------------------------------ // fpga //------------------------------------------------------------------------------ procedure TMercuryDevice.LoadOzyFpga(FileName: TFileName); var Data: TByteArray; begin if not FInitialized then Err('LoadOzyFpga failed: ' + FStatusText); if not FileExists(FileName) then Err('File not found: ' + FileName); OpenDevice; try SendFpgaCommand(FL_BEGIN, nil); with TFileStream.Create(FileName, fmOpenRead) do try repeat SetLength(Data, MAX_EP0_PACKET_SIZE); SetLength(Data, Read(Data[0], MAX_EP0_PACKET_SIZE)); if Data = nil then Break; SendFpgaCommand(FL_XFER, Data); if Assigned(FOnFpgaProgress) then FOnFpgaProgress(Self, Position, Size); until false; finally Free; if Assigned(FOnFpgaProgress) then FOnFpgaProgress(Self, -1, -1); end; SendFpgaCommand(FL_END, nil); finally CloseDevice; end; end; procedure TMercuryDevice.SendFpgaCommand(AIdx: integer; AData: TByteArray); var Data: TByteArray; begin if AData = nil then SetLength(Data, 1) else Data := AData; if FunUsbControlMsg(FHandle, VRT_VENDOR_OUT, VRQ_FPGA_LOAD, 0, AIdx, Data[0], Length(AData), 1000) <> Length(AData) then Err('SendFpgaCommand failed'); end; //------------------------------------------------------------------------------ // data //------------------------------------------------------------------------------ procedure TMercuryDevice.DoData(AData: TByteArray; var ADone: boolean); begin end; procedure TMercuryDevice.ReadData(AControlPoint: integer; var ABuf: TByteArray); begin inherited ReadData(AControlPoint, ABuf); end; procedure TMercuryDevice.WriteI2C(Addr: integer; Data: TByteArray); begin if (Data = nil) or (Length(Data) > MAX_EP0_PACKET_SIZE) then Err('Bad data passed to WriteI2C'); if FunUsbControlMsg(FHandle, VRT_VENDOR_OUT, VRQ_I2C_WRITE, Addr, 0, Data[0], Length(Data), 1000) <> Length(Data) then Err('WriteI2C failed'); end; procedure TMercuryDevice.WriteI2C_TwoBytes(Addr: integer; Byte1, Byte2: Byte); var Data: TByteArray; begin SetLength(Data, 2); Data[0] := Byte1; Data[1] := Byte2; WriteI2C(Addr, Data); end; procedure TMercuryDevice.WriteData(AControlPoint: integer; var ABuf: TByteArray); begin inherited WriteData(AControlPoint, ABuf); end; procedure TMercuryDevice.SetLoFrequency(const Value: integer); begin SettCritSect.Enter; try begin FLoFrequency := Value; FreqChanged := true; end; finally SettCritSect.Leave; end; end; procedure TMercuryDevice.MercWndProc(var Msg: TMessage); begin try if Msg.Msg = WM_RX_DATA then GetRxData else Msg.Result := DefWindowProc(WinH, Msg.Msg, Msg.wParam, Msg.lParam); except Application.HandleException(Self); end end; procedure TMercuryDevice.GetRxData; begin if Thr = nil then Exit; InCritSect.Enter; try if not Thr.RxDataReady then Exit; SetLength(RxData, 2); RxData[0] := Copy(Thr.RxData[0]); RxData[1] := Copy(Thr.RxData[1]); Thr.RxDataReady := false; if Assigned(FOnData) then FOnData(Self); finally InCritSect.Leave; end; end; const VRQ_JTAG_FUNC = $0F; JF_PORT = 0; JF_LIST_DEV = 1; JF_START_CFG = 2; JF_XFER_CFG = 3; JF_END_CFG = 4; function TMercuryDevice.ListJtagDevices: string; var rc: integer; Buf: TByteArray; begin if FHandle = nil then Err('ListJtagDevices failed: device not open'); SetLength(Buf, 22); rc := FunUsbControlMsg(FHandle, VRT_VENDOR_IN, VRQ_JTAG_FUNC, 0, JF_LIST_DEV, Buf[0], 22, 1000); Result := (Format('rc=%d err=%d cnt=%d id= $%.8x $%.8x $%.8x $%.8x $%.8x', [rc, Buf[0], Buf[1], PInteger(@Buf[2])^, PInteger(@Buf[6])^, PInteger(@Buf[10])^, PInteger(@Buf[14])^, PInteger(@Buf[18])^ ])); end; procedure TMercuryDevice.LoadMercuryFpga(AFileName: TFileName; DevIdx: integer); var Dummy, rc: integer; Data: TByteArray; begin if not FInitialized then Err('LoadMercuryFpga failed: ' + FStatusText); if FHandle = nil then Err('LoadMercuryFpga failed: device not open'); if not FileExists(AFileName) then Err('File not found: ' + AFileName); rc := FunUsbControlMsg(FHandle, VRT_VENDOR_OUT, VRQ_JTAG_FUNC, DevIdx, JF_START_CFG, Dummy, 0, 1000); if rc < 0 then Err('JF_START_CFG failed'); with TFileStream.Create(AFileName, fmOpenRead) do try repeat SetLength(Data, MAX_EP0_PACKET_SIZE); SetLength(Data, Read(Data[0], MAX_EP0_PACKET_SIZE)); if Data = nil then Break; rc := FunUsbControlMsg(FHandle, VRT_VENDOR_OUT, VRQ_JTAG_FUNC, DevIdx, JF_XFER_CFG, Data[0], Length(Data), 1000); if Assigned(FOnFpgaProgress) then FOnFpgaProgress(Self, Position, Size); until false; finally Free; if Assigned(FOnFpgaProgress) then FOnFpgaProgress(Self, -1, -1); end; rc := FunUsbControlMsg(FHandle, VRT_VENDOR_OUT, VRQ_JTAG_FUNC, DevIdx, JF_END_CFG, Dummy, 0, 1000); end; end.
unit uControllerThread; interface uses System.Classes, System.SysUtils, Vcl.Forms, DateUtils, uController, uModbus, IniFiles; //, uLogger; type TJobError = procedure(AMessage: string) of object; TControllerThread = class(TThread) private FController: TController; FTurnList: TStringList; FCodeList: TStringList; FUseCodeList: TStringList; FJobError: string; FOnJobError: TJobError; procedure DoJobError; procedure JobError(AMessage: string); protected procedure Execute; override; public constructor Create(Port: byte; TurnList, CodeList: TStrings); destructor Destroy; override; property OnJobError: TJobError read FOnJobError write FOnJobError; end; implementation { TControllerThread } constructor TControllerThread.Create(Port: byte; TurnList, CodeList: TStrings); begin inherited Create(true); FreeOnTerminate := true; Priority := tpNormal; FTurnList := TStringList.Create; FCodeList := TStringList.Create; FUseCodeList := TStringList.Create; FTurnList.Assign(TurnList); FCodeList.Assign(CodeList); FController := TController.Create; try if not FController.Open(Port, 115200) then FJobError := 'Немогу подключиться к COM' + IntToStr(Port); except end; resume; end; destructor TControllerThread.Destroy; begin FController.Close; FController := nil; FTurnList.Free; FCodeList.Free; FUseCodeList.Free; inherited; end; procedure TControllerThread.DoJobError; begin if Assigned(FOnJobError) then FOnJobError(FJobError); end; procedure TControllerThread.Execute; var i, l: integer; IsNew: boolean; Card: Tar; count: word; code: string; n: word; index: integer; ini: TIniFile; s, s1: string; er: TModbusError; begin if FController = nil then Terminate; if FJobError <> '' then JobError(FJobError); try while not Terminated do begin for i := 0 to FTurnList.Count - 1 do begin try if FController = nil then exit; FController.GetEnterCard(StrToInt(FTurnList[i]), IsNew, Card, count); if (count > 0) and (IsNew) then begin FController.GetEnter(StrToInt(FTurnList[i]), n); if n = 0 then begin code := ''; for l := 0 to count - 1 do begin try code := code + chr(Card[l]); except end; end; code := trim(code); index := FCodeList.IndexOf(code); if (index <> -1) and (FCodeList.Count > 0) then begin try er := FController.SetEnter(StrToInt(FTurnList[i]), 1); except end; try FUseCodeList.Add(code + ';' + FTurnList[i] + ' ' + TimeToStr(time)); except end; try FCodeList.Delete(index); except end; end else FController.SetEnterRed(StrToInt(FTurnList[i]), 1, 1, 4); end; end; except end; try if FController = nil then exit; FController.GetExitCard(StrToInt(FTurnList[i]), IsNew, Card, count); if (count > 0) and (IsNew) then begin FController.GetExit(StrToInt(FTurnList[i]), n); if n = 0 then begin er := FController.SetExit(StrToInt(FTurnList[i]), 1); code := ''; for l := 0 to count - 1 do begin try code := code + chr(Card[l]); except end; end; code := trim(code); index := FCodeList.IndexOf(code); if (index <> -1) and (FCodeList.Count > 0) then begin try er := FController.SetExit(StrToInt(FTurnList[i]), 1); except end; try FUseCodeList.Add(code + ';' + FTurnList[i] + ' ' + TimeToStr(time)); except end; try FCodeList.Delete(index); except end; end else FController.SetExitRed(StrToInt(FTurnList[i]), 1, 1, 4); end; end; except end; sleep(30); end; end; if Terminated then begin ini := TIniFile.Create(ExtractFilePath(Application.Exename) + 'UsedCode.ini'); try for i := 0 to FUseCodeList.Count - 1 do begin s := FUseCodeList[i]; s1 := copy(s, 1, pos(';', s) - 1); delete(s, 1, pos(';', s)); ini.WriteString('code', s1, s); end; finally ini.Free; end; end; except end; end; procedure TControllerThread.JobError(AMessage: string); begin DoJobError; end; end.
program hello_triangle_exercise2; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, gl, GLext, glfw31; const // settings SCR_WIDTH = 800; SCR_HEIGHT = 600; // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- procedure processInput(window: pGLFWwindow); cdecl; begin if glfwGetKey(window, GLFW_KEY_ESCAPE) = GLFW_PRESS then begin glfwSetWindowShouldClose(window, GLFW_TRUE); end; end; // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- procedure framebuffer_size_callback(window: pGLFWwindow; width, height: Integer); cdecl; begin // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); end; procedure showError(error: GLFW_INT; description: PChar); cdecl; begin Writeln(description); end; var window: pGLFWwindow; // set up vertex data // ------------------ firstTriangle: array [0..8] of GLfloat = ( -0.9, -0.5, 0.0, // left -0.0, -0.5, 0.0, // right -0.45, 0.5, 0.0 // top ); secondTriangle: array [0..8] of GLfloat = ( // second triangle 0.0, -0.5, 0.0, // left 0.9, -0.5, 0.0, // right 0.45, 0.5, 0.0 // top ); VBOs, VAOs: array[0..1] of GLuint; vertexShader: GLuint; vertexShaderSource: PGLchar; fragmentShader: GLuint; fragmentShaderSource: PGLchar; shaderProgram: GLuint; success: GLint; infoLog : array [0..511] of GLchar; begin // glfw: initialize and configure // ------------------------------ glfwInit; glfwSetErrorCallback(@showError); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- window := glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, 'LearnOpenGL', nil, nil); if window = nil then begin Writeln('Failed to create GLFW window'); glfwTerminate; Exit; end; glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, @framebuffer_size_callback); // GLext: load all OpenGL function pointers // ---------------------------------------- if Load_GL_version_3_3_CORE = false then begin Writeln('OpenGL 3.3 is not supported!'); glfwTerminate; Exit; end; // build and compile our shader program // ------------------------------------ // vertex shader vertexShaderSource := '#version 330 core' + #10 + 'layout (location = 0) in vec3 position;' + #10 + ' ' + #10 + 'void main()' + #10 + '{' + #10 + ' gl_Position = vec4(position.x, position.y, position.z, 1.0);' + #10 + '}' + #10; vertexShader := glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, @vertexShaderSource, nil); glCompileShader(vertexShader); // check for shader compile errors glGetShaderiv(vertexShader, GL_COMPILE_STATUS, @success); if success <> GL_TRUE then begin glGetShaderInfoLog(vertexShader, 512, nil, @infoLog); Writeln('ERROR::SHADER::VERTEX::COMPILATION_FAILED'); Writeln(infoLog); end; // fragment shader fragmentShaderSource := '#version 330 core' + #10 + 'out vec4 color;' + #10 + '' + #10 + 'void main()' + #10 + '{' + #10 + ' color = vec4(1.0f, 0.5f, 0.2f, 1.0f);' + #10 + '}' + #10; fragmentShader := glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, @fragmentShaderSource, nil); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, @success); if success <> GL_TRUE then begin glGetShaderInfoLog(fragmentShader, 512, nil, @infoLog); Writeln('ERROR::SHADER::FRAGMENT::COMPILATION_FAILED'); Writeln(infoLog); end; // link shaders shaderProgram := glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for link errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, @success); if success <> GL_TRUE then begin glGetProgramInfoLog(shaderProgram, 512, nil, @infoLog); Writeln('ERROR::SHADER::PROGRAM::LINKING_FAILED'); Writeln(infoLog); end; glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // set up buffer(s) and configure vertex attributes // ------------------------------------------------ // VBOs & VAOs glGenVertexArrays(2, VAOs); // we can also generate multiple VAOs or buffers at the same time glGenBuffers(2, VBOs); // first triangle setup // -------------------- glBindVertexArray(VAOs[0]); glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), @firstTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), PGLvoid(0)); glEnableVertexAttribArray(0); //glBindVertexArray(0);// no need to unbind at all as we directly bind a different VAOs the next few lines glBindVertexArray(VAOs[1]); glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), @secondTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), PGLvoid(0)); glEnableVertexAttribArray(0); // glBindVertexArray(0); // not really necessary as well, but beware of calls that could affect VAOs while this one is bound (like binding element buffer objects, or enabling/disabling vertex attributes) // uncomment this call to draw in wireframe polygons. // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop // ----------- while glfwWindowShouldClose(window) = GLFW_FALSE do begin // input // ----- processInput(window); // render // ------ glClearColor(0.2, 0.3, 0.3, 1.0); glClear(GL_COLOR_BUFFER_BIT); // draw our first triangle glUseProgram(shaderProgram); // draw first triangle using the data from the first VAOs glBindVertexArray(VAOs[0]); glDrawArrays(GL_TRIANGLES, 0, 3); // then we draw the second triangle using the data from the second VAOs glBindVertexArray(VAOs[1]); glDrawArrays(GL_TRIANGLES, 0, 3); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents; end; // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(2, VAOs); glDeleteBuffers(2, VBOs); glDeleteProgram(shaderProgram); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate; end.
unit InflatablesList_Utils; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Windows, SysUtils, Graphics, Classes, AuxTypes, AuxClasses, InflatablesList_Types; //============================================================================== //- string functions redirection ----------------------------------------------- Function IL_CompareText(const A,B: String): Integer; Function IL_CompareStr(const A,B: String): Integer; Function IL_SameText(const A,B: String): Boolean; Function IL_SameStr(const A,B: String): Boolean; Function IL_ContainsText(const Text,SubText: String): Boolean; Function IL_ContainsStr(const Text,SubText: String): Boolean; Function IL_Format(const FormatStr: String; Args: array of const; const FormatSettings: TFormatSettings): String; overload; Function IL_Format(const FormatStr: String; Args: array of const): String; overload; Function IL_StringOfChar(Ch: Char; Count: Integer): String; Function IL_MultiLineText(const Strs: array of String): String; Function IL_UpperCase(const Str: String): String; Function IL_LowerCase(const Str: String): String; Function IL_FormatDateTime(const FormatStr: String; DateTIme: TDateTIme): String; Function IL_ReplaceText(const Text, FromText, ToText: String): String; Function IL_ReplaceStr(const Text, FromText, ToText: String): String; //============================================================================== //- comparison functions used in sorting --------------------------------------- Function IL_SortCompareBool(A,B: Boolean): Integer; Function IL_SortCompareInt32(A,B: Int32): Integer; Function IL_SortCompareUInt32(A,B: UInt32): Integer; Function IL_SortCompareInt64(A,B: Int64): Integer; Function IL_SortCompareFloat(A,B: Double): Integer; Function IL_SortCompareDateTime(A,B: TDateTime): Integer; Function IL_SortCompareText(const A,B: String): Integer; Function IL_SortCompareStr(const A,B: String): Integer; Function IL_SortCompareGUID(const A,B: TGUID): Integer; //============================================================================== //- files/directories ---------------------------------------------------------- Function IL_PathRelative(const Base,Path: String; PrependDot: Boolean = True): String; Function IL_PathAbsolute(const Base,Path: String): String; Function IL_IncludeTrailingPathDelimiter(const Path: String): String; Function IL_ExcludeTrailingPathDelimiter(const Path: String): String; Function IL_ExtractFileDir(const FileName: String): String; Function IL_ExtractFilePath(const FileName: String): String; Function IL_ExtractFileNameNoExt(const FileName: String): String; Function IL_ExtractFileExt(const FileName: String): String; Function IL_ChangeFileExt(const FileName,NewExt: String): String; Function IL_ExpandFileName(const FileName: String): String; Function IL_MinimizeName(const FileName: String; Canvas: TCanvas; MaxLen: Integer): String; procedure IL_CreateDirectory(const Directory: String); procedure IL_CreateDirectoryPath(const Path: String); procedure IL_CreateDirectoryPathForFile(const FileName: String); Function IL_FileExists(const FileName: String): Boolean; Function IL_DeleteFile(const FileName: String): Boolean; Function IL_DeleteDir(const Dir: String): Boolean; procedure IL_CopyFile(const Source,Destination: String); procedure IL_MoveFile(const Source,Destination: String); // non-recursive enumeration of files within give folder procedure IL_EnumFiles(const BaseFolder: String; List: TStrings); //============================================================================== //- event handler assignment checking ------------------------------------------ Function IL_CheckHandler(Handler: TNotifyEvent): TNotifyEvent; overload; Function IL_CheckHandler(Handler: TILObjectL1Event): TILObjectL1Event; overload; Function IL_CheckHandler(Handler: TILObjectL2Event): TILObjectL2Event; overload; Function IL_CheckHandler(Handler: TILIndexedObjectL1Event): TILIndexedObjectL1Event; overload; Function IL_CheckHandler(Handler: TILIndexedObjectL2Event): TILIndexedObjectL2Event; overload; Function IL_CheckHandler(Handler: TILPasswordRequest): TILPasswordRequest; overload; //============================================================================== //- pictures manipulation ------------------------------------------------------ procedure IL_PicShrink(Large,Small: TBitmap; Factor: Integer); //============================================================================== //- others --------------------------------------------------------------------- Function IL_CharInSet(C: Char; CharSet: TSysCharSet): Boolean; Function IL_IndexWrap(Index,Low,High: Integer): Integer; Function IL_NegateValue(Value: Integer; Negate: Boolean): Integer; Function IL_BoolToStr(Value: Boolean; FalseStr, TrueStr: String): String; Function IL_BoolToNum(Value: Boolean): Integer; procedure IL_ShellOpen(WindowHandle: HWND; const Path: String; const Params: String = ''; const Directory: String = ''); Function IL_SelectDirectory(const Title: String; var Directory: String): Boolean; Function IL_GetTempPath: String; //============================================================================== //- roatated text drawing ------------------------------------------------------ Function IL_LogFontAssign(Src: TFont): TLogFont; // just auxiliary for following Function IL_GetRotatedTextRect(Canvas: TCanvas; const Text: String; Angle: Integer; out Rect: TRect): Boolean; Function IL_GetRotatedTextSize(Canvas: TCanvas; const Text: String; Angle: Integer; out Size: TSize): Boolean; Function IL_DrawRotatedText(Canvas: TCanvas; const Text: String; Angle: Integer; X,Y: Integer): Boolean; implementation uses StrUtils, ShellAPI, Math, {$WARN UNIT_PLATFORM OFF}FileCtrl,{$WARN UNIT_PLATFORM ON} StrRect; //============================================================================== //- string functions redirection ----------------------------------------------- Function IL_CompareText(const A,B: String): Integer; begin Result := AnsiCompareText(A,B); end; //------------------------------------------------------------------------------ Function IL_CompareStr(const A,B: String): Integer; begin Result := AnsiCompareStr(A,B); end; //------------------------------------------------------------------------------ Function IL_SameText(const A,B: String): Boolean; begin Result := AnsiSameText(A,B); end; //------------------------------------------------------------------------------ Function IL_SameStr(const A,B: String): Boolean; begin Result := AnsiSameStr(A,B); end; //------------------------------------------------------------------------------ Function IL_ContainsText(const Text,SubText: String): Boolean; begin Result := AnsiContainsText(Text,SubText); end; //------------------------------------------------------------------------------ Function IL_ContainsStr(const Text,SubText: String): Boolean; begin Result := AnsiContainsStr(Text,SubText); end; //------------------------------------------------------------------------------ var ILLocalFormatSettings: TFormatSettings; // never make this public Function IL_Format(const FormatStr: String; Args: array of const; const FormatSettings: TFormatSettings): String; begin Result := Format(FormatStr,Args,FormatSettings); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function IL_Format(const FormatStr: String; Args: array of const): String; begin Result := IL_Format(FormatStr,Args,ILLocalFormatSettings); end; //------------------------------------------------------------------------------ Function IL_StringOfChar(Ch: Char; Count: Integer): String; begin Result := StringOfChar(Ch,Count); end; //------------------------------------------------------------------------------ Function IL_MultiLineText(const Strs: array of String): String; var i: Integer; begin with TStringList.Create do try For i := Low(Strs) to High(Strs) do Add(Strs[i]); Result := Text; finally Free; end; end; //------------------------------------------------------------------------------ Function IL_UpperCase(const Str: String): String; begin Result := AnsiUpperCase(Str); end; //------------------------------------------------------------------------------ Function IL_LowerCase(const Str: String): String; begin Result := AnsiLowerCase(Str); end; //------------------------------------------------------------------------------ Function IL_FormatDateTime(const FormatStr: String; DateTIme: TDateTIme): String; begin Result := FormatDateTIme(FormatStr,DateTime,ILLocalFormatSettings); end; //------------------------------------------------------------------------------ Function IL_ReplaceText(const Text, FromText, ToText: String): String; begin Result := AnsiReplaceText(Text,FromText,ToText); end; //------------------------------------------------------------------------------ Function IL_ReplaceStr(const Text, FromText, ToText: String): String; begin Result := AnsiReplaceStr(Text,FromText,ToText); end; //============================================================================== //- comparison functions, used in sorting -------------------------------------- Function IL_SortCompareBool(A,B: Boolean): Integer; begin If A <> B then begin If A = True then Result := -1 else Result := +1; end else Result := 0; end; //------------------------------------------------------------------------------ Function IL_SortCompareInt32(A,B: Int32): Integer; begin If A <> B then begin If A > B then Result := -1 else Result := +1; end else Result := 0; end; //------------------------------------------------------------------------------ Function IL_SortCompareUInt32(A,B: UInt32): Integer; begin If A <> B then begin If A > B then Result := -1 else Result := +1; end else Result := 0; end; //------------------------------------------------------------------------------ Function IL_SortCompareInt64(A,B: Int64): Integer; begin If A <> B then begin If A > B then Result := -1 else Result := +1; end else Result := 0; end; //------------------------------------------------------------------------------ Function IL_SortCompareFloat(A,B: Double): Integer; begin If A <> B then begin If A > B then Result := -1 else Result := +1; end else Result := 0; end; //------------------------------------------------------------------------------ Function IL_SortCompareDateTime(A,B: TDateTime): Integer; begin If A <> B then begin If A > B then Result := -1 else Result := +1; end else Result := 0; end; //------------------------------------------------------------------------------ Function IL_SortCompareText(const A,B: String): Integer; begin Result := IL_CompareText(A,B); If Result <> 0 then begin If Result > 0 then Result := -1 else Result := +1; end; end; //------------------------------------------------------------------------------ Function IL_SortCompareStr(const A,B: String): Integer; begin Result := IL_CompareStr(A,B); If Result <> 0 then begin If Result > 0 then Result := -1 else Result := +1; end; end; //------------------------------------------------------------------------------ Function IL_SortCompareGUID(const A,B: TGUID): Integer; begin Result := IL_CompareText(GUIDToString(A),GUIDToString(B)); If Result <> 0 then begin If Result > 0 then Result := -1 else Result := +1; end; end; //============================================================================== //- files/directories ---------------------------------------------------------- Function IL_PathRelative(const Base,Path: String; PrependDot: Boolean = True): String; begin // path can be a filename, so watch for trailing delimiter (must be present when it is a directory) Result := RTLToStr(ExtractRelativePath(IncludeTrailingPathDelimiter(StrToRTL(Base)),StrToRTL(Path))); { if the paths are the same, it is assumed the path cannot be relativized, for example when it is on a different disk } If PrependDot and not IL_SameText(Result,Path) then Result := '.' + PathDelim + Result; end; //------------------------------------------------------------------------------ Function IL_PathAbsolute(const Base,Path: String): String; begin If Length(Path) > 0 then Result := RTLToStr(ExpandFileName(IncludeTrailingPathDelimiter(StrToRTL(Base)) + StrToRTL(Path))) else Result := ''; end; //------------------------------------------------------------------------------ Function IL_IncludeTrailingPathDelimiter(const Path: String): String; begin Result := RTLToStr(IncludeTrailingPathDelimiter(StrToRTL(Path))); end; //------------------------------------------------------------------------------ Function IL_ExcludeTrailingPathDelimiter(const Path: String): String; begin Result := RTLToStr(ExcludeTrailingPathDelimiter(StrToRTL(Path))); end; //------------------------------------------------------------------------------ Function IL_ExtractFileDir(const FileName: String): String; begin Result := RTLToStr(ExtractFileDir(StrToRTL(FileName))); end; //------------------------------------------------------------------------------ Function IL_ExtractFilePath(const FileName: String): String; begin Result := RTLToStr(ExtractFilePath(StrToRTL(FileName))); end; //------------------------------------------------------------------------------ Function IL_ExtractFileNameNoExt(const FileName: String): String; begin Result := IL_ChangeFileExt(RTLToStr(ExtractFileName(StrToRTL(FileName))),''); end; //------------------------------------------------------------------------------ Function IL_ExtractFileExt(const FileName: String): String; begin Result := RTLToStr(ExtractFileExt(StrToRTL(FileName))); end; //------------------------------------------------------------------------------ Function IL_ExpandFileName(const FileName: String): String; begin Result := RTLToStr(ExpandFileName(StrToRTL(FileName))); end; //------------------------------------------------------------------------------ Function IL_MinimizeName(const FileName: String; Canvas: TCanvas; MaxLen: Integer): String; begin Result := RTLToStr(MinimizeName(StrToRTL(FileName),Canvas,MaxLen)); end; //------------------------------------------------------------------------------ Function IL_ChangeFileExt(const FileName,NewExt: String): String; begin Result := RTLToStr(ChangeFileExt(StrToRTL(FileName),StrToRTL(NewExt))); end; //------------------------------------------------------------------------------ procedure IL_CreateDirectory(const Directory: String); begin ForceDirectories(StrToRTL(Directory)); end; //------------------------------------------------------------------------------ procedure IL_CreateDirectoryPath(const Path: String); begin IL_CreateDirectory(RTLToStr(ExcludeTrailingPathDelimiter(StrToRTL(Path)))); end; //------------------------------------------------------------------------------ procedure IL_CreateDirectoryPathForFile(const FileName: String); begin IL_CreateDirectory(RTLToStr(ExtractFileDir(StrToRTL(FileName)))); end; //------------------------------------------------------------------------------ Function IL_FileExists(const FileName: String): Boolean; begin Result := FileExists(StrToRTL(FileName)); end; //------------------------------------------------------------------------------ Function IL_DeleteFile(const FileName: String): Boolean; begin Result := DeleteFile(StrToRTL(FileName)); end; //------------------------------------------------------------------------------ Function IL_DeleteDir(const Dir: String): Boolean; var FileOp: TSHFileOpStruct; TempStr: String; begin TempStr := IL_ExcludeTrailingPathDelimiter(Dir) + #0; FillChar(FileOp,SizeOf(TSHFileOpStruct),0); FileOp.Wnd := 0; FileOp.wFunc := FO_DELETE; FileOp.pFrom := PChar(TempStr); FileOp.pTo := nil; FileOp.fFlags := FOF_NOCONFIRMATION or FOF_NOERRORUI or FOF_SILENT; FileOp.lpszProgressTitle := nil; Result := SHFileOperation(FileOp) = 0; end; //------------------------------------------------------------------------------ procedure IL_CopyFile(const Source,Destination: String); begin CopyFile(PChar(StrToWin(Source)),PChar(StrToWin(Destination)),False); end; //------------------------------------------------------------------------------ procedure IL_MoveFile(const Source,Destination: String); begin MoveFileEx(PChar(StrToWin(Source)),PChar(StrToWin(Destination)), MOVEFILE_COPY_ALLOWED or MOVEFILE_REPLACE_EXISTING or MOVEFILE_WRITE_THROUGH); end; //------------------------------------------------------------------------------ procedure IL_EnumFiles(const BaseFolder: String; List: TStrings); var FoldersList: TStringList; CurrentLevel: TStringList; i: Integer; procedure ListFolder(const Folder: String; Files,Folders: TStrings); var SearchRec: TSearchRec; begin If FindFirst(IL_IncludeTrailingPathDelimiter(Folder) + '*.*',faAnyFile,SearchRec) = 0 then begin repeat If (SearchRec.Attr and faDirectory) <> 0 then begin If (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then Folders.Add(IL_IncludeTrailingPathDelimiter(Folder) + SearchRec.Name) end else begin {$WARN SYMBOL_PLATFORM OFF} If (SearchRec.Attr and faHidden) = 0 then {$WARN SYMBOL_PLATFORM ON} Files.Add(SearchRec.Name); // add only file names, not full paths end; until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; end; begin FoldersList := TStringList.Create; try CurrentLevel := TStringList.Create; try FoldersList.Add(IL_IncludeTrailingPathDelimiter(BaseFolder)); repeat CurrentLevel.Assign(FoldersList); FoldersList.Clear; For i := 0 to Pred(CurrentLevel.Count) do ListFolder(CurrentLevel[i],List,FoldersList); until FoldersList.Count <= 0; finally CurrentLevel.Free; end; finally FoldersList.Free; end; end; //============================================================================== //- event handler assignment checking ------------------------------------------ Function IL_CheckHandler(Handler: TNotifyEvent): TNotifyEvent; begin If Assigned(Handler) then Result := Handler else raise Exception.Create('IL_CheckAndAssign(TNotifyEvent): Handler not assigned'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function IL_CheckHandler(Handler: TILObjectL1Event): TILObjectL1Event; begin If Assigned(Handler) then Result := Handler else raise Exception.Create('IL_CheckAndAssign(TILObjectL1Event): Handler not assigned'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function IL_CheckHandler(Handler: TILObjectL2Event): TILObjectL2Event; begin If Assigned(Handler) then Result := Handler else raise Exception.Create('IL_CheckAndAssign(TILObjectL2Event): Handler not assigned'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function IL_CheckHandler(Handler: TILIndexedObjectL1Event): TILIndexedObjectL1Event; begin If Assigned(Handler) then Result := Handler else raise Exception.Create('IL_CheckAndAssign(TILIndexedObjectL1Event): Handler not assigned'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function IL_CheckHandler(Handler: TILIndexedObjectL2Event): TILIndexedObjectL2Event; begin If Assigned(Handler) then Result := Handler else raise Exception.Create('IL_CheckAndAssign(TILIndexedObjectL2Event): Handler not assigned'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function IL_CheckHandler(Handler: TILPasswordRequest): TILPasswordRequest; begin If Assigned(Handler) then Result := Handler else raise Exception.Create('IL_CheckAndAssign(TILPasswordRequest): Handler not assigned'); end; //============================================================================== //- pictures manipulation ------------------------------------------------------ procedure IL_PicShrink(Large,Small: TBitmap; Factor: Integer); type TRGBTriple = packed record rgbtRed, rgbtGreen, rgbtBlue: Byte; end; TRGBTripleArray = array[0..$FFFF] of TRGBTriple; PRGBTripleArray = ^TRGBTripleArray; var LargeH: Boolean; SmallH: Boolean; Y,X: Integer; Lines: array of PRGBTripleArray; LineR: PRGBTripleArray; R,G,B: UInt32; i,j: Integer; begin LargeH := Large.HandleAllocated; SmallH := Small.HandleAllocated; // ensure GDI handle is allocated in both bitmaps Large.Handle; Small.Handle; SetLength(Lines,Factor); For Y := 0 to Pred(Large.Height div Factor) do begin For i := 0 to Pred(Factor) do Lines[i] := Large.ScanLine[(Y * Factor) + i]; For X := 0 to Pred(Large.Width div Factor) do begin R := 0; G := 0; B := 0; For i := 0 to Pred(Factor) do For j := 0 to Pred(Factor) do begin Inc(R,Sqr(Integer(Lines[i]^[(X * Factor) + j].rgbtRed))); Inc(G,Sqr(Integer(Lines[i]^[(X * Factor) + j].rgbtGreen))); Inc(B,Sqr(Integer(Lines[i]^[(X * Factor) + j].rgbtBlue))); end; LineR := Small.ScanLine[Y]; LineR^[X].rgbtRed := Trunc(Sqrt(R / Sqr(Factor))); LineR^[X].rgbtGreen := Trunc(Sqrt(G / Sqr(Factor))); LineR^[X].rgbtBlue := Trunc(Sqrt(B / Sqr(Factor))); end; end; If not LargeH then Large.Dormant; If not SmallH then Small.Dormant; end; //============================================================================== //- others --------------------------------------------------------------------- Function IL_CharInSet(C: Char; CharSet: TSysCharSet): Boolean; begin {$IFDEF Unicode} If Ord(C) > 255 then Result := False else {$ENDIF} Result := AnsiChar(C) in CharSet; end; //------------------------------------------------------------------------------ Function IL_IndexWrap(Index,Low,High: Integer): Integer; begin If (Index < Low) then Result := High else If Index > High then Result := Low else Result := Index; end; //------------------------------------------------------------------------------ Function IL_NegateValue(Value: Integer; Negate: Boolean): Integer; begin If Negate then Result := -Value else Result := Value; end; //------------------------------------------------------------------------------ Function IL_BoolToStr(Value: Boolean; FalseStr, TrueStr: String): String; begin If Value then Result := TrueStr else Result := FalseStr; end; //------------------------------------------------------------------------------ Function IL_BoolToNum(Value: Boolean): Integer; begin If Value then Result := 1 else Result := 0; end; //------------------------------------------------------------------------------ procedure IL_ShellOpen(WindowHandle: HWND; const Path: String; const Params: String = ''; const Directory: String = ''); begin If Length(Path) > 0 then ShellExecute(WindowHandle,'open',PChar(StrToWin(Path)),PChar(StrToWin(Params)),PChar(StrToWin(Directory)),SW_SHOWNORMAL); end; //------------------------------------------------------------------------------ Function IL_SelectDirectory(const Title: String; var Directory: String): Boolean; begin Result := SelectDirectory(Title,'',Directory); end; //------------------------------------------------------------------------------ Function IL_GetTempPath: String; begin Result := ''; SetLength(Result,GetTempPath(0,nil)); SetLength(Result,GetTempPath(Length(Result),PChar(Result))); end; //============================================================================== //- roatated text drawing ------------------------------------------------------ Function IL_LogFontAssign(Src: TFont): TLogFont; begin FillChar(Result,SizeOf(TLogFont),0); Result.lfHeight := Src.Height; If fsBold in Src.Style then Result.lfWeight := FW_BOLD else Result.lfWeight := FW_NORMAL; Result.lfItalic := IL_BoolToNum(fsItalic in Src.Style); Result.lfUnderline := IL_BoolToNum(fsUnderline in Src.Style); Result.lfStrikeOut := IL_BoolToNum(fsStrikeOut in Src.Style); Result.lfQuality := DEFAULT_QUALITY; Result.lfCharSet := Src.Charset; StrLCopy(Result.lfFaceName,PChar(Src.Name),Length(Src.Name)); end; //------------------------------------------------------------------------------ Function IL_GetRotatedTextRect(Canvas: TCanvas; const Text: String; Angle: Integer; out Rect: TRect): Boolean; var Font: TLogFont; BackgroundMode: Integer; CurrFont,OldFont: HFONT; TextSize: TSize; // corners of the bounding box - first, text origin, is ignored, others are taken ccw PointsIn,PointsOut: array[0..2] of TPoint; SinAngle,CosAngle: Double; i: Integer; begin Result := False; If Assigned(Canvas) and (Length(Text) > 0) then begin Font := IL_LogFontAssign(Canvas.Font); Font.lfEscapement := Angle * 10; Font.lfOrientation := Angle * 10; BackgroundMode := SetBkMode(Canvas.Handle,TRANSPARENT); try CurrFont := CreateFontIndirect(Font); try OldFont := SelectObject(Canvas.Handle,CurrFont); try If GetTextExtentPoint32(Canvas.Handle,PChar(Text),Length(Text),TextSize) then begin If (Angle mod 360) <> 0 then begin PointsIn[0] := Point(0,TextSize.cy); PointsIn[1] := Point(TextSize.cx,TextSize.cy); PointsIn[2] := Point(TextSize.cx,0); SinAngle := Sin(DegToRad(Angle)); CosAngle := Cos(DegToRad(Angle)); For i := Low(PointsIn) to High(PointsIn) do begin PointsOut[i].X := Round(CosAngle * PointsIn[i].X + SinAngle * PointsIn[i].Y); PointsOut[i].Y := Round(-(SinAngle * PointsIn[i].X) + CosAngle * PointsIn[i].Y) end; Rect.Left := MinIntValue([0,PointsOut[0].X,PointsOut[1].X,PointsOut[2].X]); Rect.Top := MinIntValue([0,PointsOut[0].Y,PointsOut[1].Y,PointsOut[2].Y]); Rect.Right := MaxIntValue([0,PointsOut[0].X,PointsOut[1].X,PointsOut[2].X]); Rect.Bottom := MaxIntValue([0,PointsOut[0].Y,PointsOut[1].Y,PointsOut[2].Y]); end else begin Rect.Left := 0; Rect.Top := 0; Rect.Right := TextSize.cx; Rect.Bottom := TextSize.cy; end; Result := True; end; finally SelectObject(Canvas.Handle,OldFont); end; finally DeleteObject(CurrFont); end; finally SetBkMode(Canvas.Handle,BackgroundMode); end; end; end; //------------------------------------------------------------------------------ Function IL_GetRotatedTextSize(Canvas: TCanvas; const Text: String; Angle: Integer; out Size: TSize): Boolean; var TextRect: TRect; begin If IL_GetRotatedTextRect(Canvas,Text,Angle,TextRect) then begin Size.cx := TextRect.Right - TextRect.Left; Size.cy := TextRect.Bottom - TextRect.Top; Result := True; end else Result := False; end; //------------------------------------------------------------------------------ Function IL_DrawRotatedText(Canvas: TCanvas; const Text: String; Angle: Integer; X,Y: Integer): Boolean; var Font: TLogFont; BackgroundMode: Integer; CurrFont,OldFont: HFONT; begin Result := False; If Assigned(Canvas) and (Length(Text) > 0) then begin Font := IL_LogFontAssign(Canvas.Font); Font.lfEscapement := Angle * 10; Font.lfOrientation := Angle * 10; BackgroundMode := SetBkMode(Canvas.Handle,TRANSPARENT); try CurrFont := CreateFontIndirect(Font); try OldFont := SelectObject(Canvas.Handle,CurrFont); try Result := TextOut(Canvas.Handle,X,Y,PChar(Text),Length(Text)); finally SelectObject(Canvas.Handle,OldFont); end; finally DeleteObject(CurrFont); end; finally SetBkMode(Canvas.Handle,BackgroundMode); end; end; end; //============================================================================== initialization {$WARN SYMBOL_PLATFORM OFF} {$IF not Defined(FPC) and (CompilerVersion >= 18)} // Delphi 2006+ ILLocalFormatSettings := TFormatSettings.Create(LOCALE_USER_DEFAULT); {$ELSE} GetLocaleFormatSettings(LOCALE_USER_DEFAULT,ILLocalFormatSettings); {$IFEND} {$WARN SYMBOL_PLATFORM ON} end.
unit Beacon; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TBeacon = class(TPanel) Shape: TShape; Timer: TTimer; private FEnabled: boolean; FTimeOn: integer; FTimeOff: integer; FColorOn: TColor; FColorOff: TColor; { Private declarations } protected Procedure SetColorOn(AColor: TColor); Procedure SetColorOff(AColor: TColor); { Protected declarations } public Constructor Create (AOwner: TCompoment); override; { Public declarations } published Property Enabled: Boolean read FEnabled write FEnabled default False; Property TimeOn: integer read FTimeOn write FTimeOn default 1000; Property TimeOff: integer read FTimeOff write FTimeOff default 1000; Property ColorOn: TColor read FColorOn write SetColorOn default clWhite; Property ColorOff: TColor read FColorOff write SetColorOff default clMenu; { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TBeacon]); end; Constructor TBeacon.Create(AOwner: TCompoment); begin Inherited Create(AOwner); FEnabled:=False; FTimeOn:=1000; FTimeOff:=1000; FColorOn:=clWhite; FColorOff:=clMenu; end; Procedure SetColorOn(AColor: TColor); begin FColorOn:=AColor; Invalidate; end; Procedure SetColorOff(AColor: TColor); begin FColorOff:=AColor; Invalidate; end; end.
program HowToRespondToMouseClickAndPosition; uses SwinGame, sgTypes, sysutils; procedure Main(); var str : String; mPos : Point2D; begin OpenGraphicsWindow('Mouse Click And Position', 400, 220); LoadDefaultColors(); repeat // The game loop... ProcessEvents(); ClearScreen(ColorWhite); if KeyTyped(hKey) then HideMouse(); if KeyTyped(sKey) then ShowMouse(); if MouseShown () then DrawText('visible', ColorBlue, 'Arial', 14, 120, 90); if NOT MouseShown () then DrawText('not visible', ColorBlue, 'Arial', 14, 120, 90); if MouseClicked(LeftButton) then str := FloatToStr(MouseX()) + ',' + FloatToStr(MouseY()); if MouseDown(LeftButton) then DrawText('is down', ColorBlue, 'Arial', 14, 200, 140); if MouseUp(LeftButton) then DrawText('is up', ColorBlue, 'Arial', 14, 200, 140); if MouseDown(RightButton) then DrawText('is down', ColorBlue, 'Arial', 14, 200, 165); if MouseUp(RightButton) then DrawText('is up', ColorBlue, 'Arial', 14, 200, 165); if KeyDown(DOWNKey) then begin mPos := MousePosition(); mPos.y += 1; MoveMouse(mPos); end; if KeyDown(UPKey) then begin mPos := MousePosition(); if mPos.y > 0 then begin mPos.y -= 1; MoveMouse(mPos); end; end; if KeyDown(LEFTKey) then begin mPos := MousePosition(); if mPos.x > 0 then begin mPos.x -= 1; MoveMouse(mPos); end; end; if KeyDown(RIGHTKey) then begin mPos := MousePosition(); mPos.x += 1; MoveMouse(mPos); end; DrawText('Mouse Click And Position', ColorRed, 'Arial', 18, 115, 15); DrawText('Press H to hide the cursor', ColorBlue, 'Arial', 14, 20, 40); DrawText('Press S to show the cursor', ColorBlue, 'Arial', 14, 20, 65); DrawText('Cursor status :', ColorBlue, 'Arial', 14, 20, 90); DrawText('Mouse Position at: ' + FloatToStr(MousePosition.x) + ',' + FloatToStr(MouseY()), ColorGreen, 'Arial', 10, 0, 0); DrawText('Mouse last click at position : ' + str, ColorBlue, 'Arial', 14, 20, 115); DrawText('Mouse LeftButton status :', ColorBlue, 'Arial', 14, 20, 140); DrawText('Mouse RightButton status :', ColorBlue, 'Arial', 14, 20, 165); DrawText('Use Up, Down, Left, Right to move the mouse cursor', ColorBlue, 'Arial', 14, 20, 190); RefreshScreen(60); until WindowCloseRequested() OR KeyTyped(ESCAPEKey) OR KeyTyped(QKey); ReleaseAllResources(); end; begin Main(); end.
unit UUsuario; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Generics.Collections, UUsuarioController, UUsuarioVO, UPessoa, UPessoasVo, UPessoasController, UEmpresaTrab; type TFTelaCadastroUsuario = class(TFTelaCadastro) Label1: TLabel; LabeledEditLogin: TEdit; Label5: TLabel; LabeledEditSenha: TEdit; Label6: TLabel; LabeledEditPessoa: TEdit; BitBtn3: TBitBtn; LabeledEditNomePessoa: TEdit; GroupBox3: TGroupBox; RadioButtonPessoa: TRadioButton; function DoSalvar: boolean; override; function MontaFiltro: string; procedure DoConsultar; override; function DoExcluir: boolean; override; procedure BitBtnNovoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BitBtn3Click(Sender: TObject); procedure LabeledEditPessoaExit(Sender: TObject); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; function EditsToObject(Usuario: TUsuarioVO): TUsuarioVO; end; var FTelaCadastroUsuario: TFTelaCadastroUsuario; ControllerUsuario: TUsuarioController; implementation {$R *.dfm} { TFTelaCadastroUsuario } procedure TFTelaCadastroUsuario.BitBtn3Click(Sender: TObject); var FormPessoaConsulta: TFTelaCadastroPessoa; begin FormPessoaConsulta := TFTelaCadastroPessoa.Create(nil); FormPessoaConsulta.FechaForm := true; FormPessoaConsulta.ShowModal; if (FormPessoaConsulta.ObjetoRetornoVO <> nil) then begin LabeledEditPessoa.Text := IntToStr(TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).idpessoa); LabeledEditNomePessoa.Text := TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).nome; end; FormPessoaConsulta.Release; end; procedure TFTelaCadastroUsuario.BitBtnNovoClick(Sender: TObject); begin inherited; LabeledEditPessoa.setFocus; end; procedure TFTelaCadastroUsuario.DoConsultar; var listaUsuario: TObjectList<TUsuarioVO>; filtro: string; begin filtro := MontaFiltro; listaUsuario := ControllerUsuario.Consultar(filtro); PopulaGrid<TUsuarioVO>(listaUsuario); end; function TFTelaCadastroUsuario.DoExcluir: boolean; var Usuario: TUsuarioVO; begin try try Usuario := TUsuarioVO.Create; Usuario.idUsuario := CDSGrid.FieldByName('IDUSUARIO').AsInteger; ControllerUsuario.Excluir(Usuario); except on E: Exception do begin ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 + E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroUsuario.DoSalvar: boolean; var Usuario: TUsuarioVO; begin Usuario:=EditsToObject(TUsuarioVO.Create); try try Usuario.ValidarCamposObrigatorios(); if (StatusTela = stInserindo) then begin ControllerUsuario.Inserir(Usuario); result := true; end else if (StatusTela = stEditando) then begin Usuario := ControllerUsuario.ConsultarPorId(CDSGrid.FieldByName('IDUSUARIO') .AsInteger); Usuario := EditsToObject(Usuario); ControllerUsuario.Alterar(Usuario); Result := true; end except on E: Exception do begin ShowMessage(E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroUsuario.EditsToObject(Usuario: TUsuarioVO): TUsuarioVO; begin if (LabeledEditPessoa.Text <> '') then Usuario.idPessoa := strtoint(LabeledEditPessoa.Text); if (LabeledEditLogin.Text<> '') then Usuario.login := LabeledEditLogin.Text; if (LabeledEditSenha.Text<>'') then Usuario.senha := LabeledEditSenha.Text; Result := Usuario; end; procedure TFTelaCadastroUsuario.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(ControllerUsuario); end; procedure TFTelaCadastroUsuario.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TUsuarioVO; RadioButtonPessoa.Checked := true; ControllerUsuario := TUsuarioController.Create; inherited; end; procedure TFTelaCadastroUsuario.GridParaEdits; var Usuario: TUsuarioVO; begin inherited; Usuario := nil; if not CDSGrid.IsEmpty then Usuario := ControllerUsuario.ConsultarPorId(CDSGrid.FieldByName('IDUSUARIO') .AsInteger); if Usuario <> nil then begin if usuario.PessoaVO <> nil then begin LabeledEditPessoa.Text := IntToStr(Usuario.PessoaVO.idPessoa); LabeledEditNomePessoa.Text := Usuario.PessoaVO.nome; end; LabeledEditLogin.Text := Usuario.Login; LabeledEditSenha.Text := Usuario.senha; end; end; procedure TFTelaCadastroUsuario.LabeledEditPessoaExit(Sender: TObject); var PessoaController:TPessoasController; PessoaVO: TPessoasVO; begin if LabeledEditPessoa.Text <> '' then begin try PessoaController := TPessoasController.Create; PessoaVO := PessoaController.ConsultarPorId(StrToInt(LabeledEditPessoa.Text)); labeledEditNomePessoa.Text := PessoaVO.nome; LabeledEditPessoa.Text := inttostr(PessoaVO.idPessoa); PessoaController.Free; except raise Exception.Create('Código Inválido'); end; end; end; function TFTelaCadastroUsuario.MontaFiltro: string; begin // Result := ''; if formEmpresaTrab.idUsuario = 1 then begin if (RadioButtonPessoa.Checked = true) then begin if (editBusca.Text <> '') then begin Result := '( UPPER(LOGIN) LIKE ' + QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) '; end; end; end else if(RadioButtonPessoa.Checked = true) then begin Result:=' usuario.idusuario = '+IntToStr(FormEmpresaTrab.idUsuario); if (editBusca.Text <> '') then begin Result := result + ' AND ( UPPER(LOGIN) LIKE ' +QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' )'; end; end; end; end.
{ BitmapSpeedButton component for FireMonkey. See documentation at http://monkeystyler.com/wiki/TBitmapSpeedButton Brought to you by the author of MonkeyStyler - FireMonkey style designer. http://monkeystyler.com You are free to use this code for any purpose provided: * You do not charge for source code * If you fork this project please keep this header intact. * You are free to use the compiled code from this file in commercial projects. } unit Solent.BitmapSpeedButton; interface uses FMX.Controls, FMX.Layouts, FMX.Objects, FMX.Types, Classes, FMX.StdCtrls, FMX.Graphics; type TToolTipPopup = class(TPopup) private procedure SetText(const Value: String); protected FText: String; procedure ApplyStyle;override; procedure UpdateText; public constructor Create(AOwner: TComponent); override; procedure Popup(const AShowModal: Boolean = False);override; procedure ClosePopup;override; published property Text: String read FText write SetText; end; type TImageAlign = (iaTop, iaLeft, iaRight, iaBottom, iaCenter); //Whether to get the image from the Bitmap property of the ImageStyleLookup property TImageType = (itBitmap, itStyleLookup); type TBitmapSpeedButton = class(TSpeedButton) private FImageAlign: TImageAlign; FTextVisible: Boolean; FImageHeight: Single; FImageWidth: Single; FImagePadding: Single; FImageType: TImageType; FImageStyleLookup: String; FShowingToolTip: Boolean; FToolTip: String; procedure SetImageAlign(const Value: TImageAlign); procedure SetTextVisible(const Value: Boolean); procedure SetImageHeight(const Value: Single); procedure SetImagePadding(const Value: Single); procedure SetImageWidth(const Value: Single); procedure SetImageStyleLookup(const Value: String); procedure SetImageType(const Value: TImageType); procedure SetToolTip(const Value: String); procedure SetToolTipPlacement(const Value: TPlacement); function GetToolTipPlacement: TPlacement; protected FImageLayout: TLayout; FImage: TImage; FBitmap: TBitmap; FToolTipPopup: TToolTipPopup; //Show ToolTip once this timer trips FToolTipTimer: TTimer; //Show toolip immediately if another button has ShowingToolTip = True. //ShowingToolTip will be set to False once this timer expires (it is enabled on MouseLeave). FNoToolTipTimer: TTimer; procedure ApplyStyle;override; procedure EVBitmapChange(Sender: TObject); procedure UpdateImageLayout; procedure UpdateImage; procedure DoMouseEnter;override; procedure DoMouseLeave;override; procedure EVToolTipTimer(Sender: TObject); procedure EVNoToolTipTimer(Sender: TObject); public constructor Create(AOwner: TComponent);override; destructor Destroy;override; property ShowingToolTip: Boolean read FShowingToolTip; published property ImageAlign: TImageAlign read FImageAlign write SetImageAlign default iaCenter; property TextVisible: Boolean read FTextVisible write SetTextVisible; property ImageType: TImageType read FImageType write SetImageType; property Bitmap: TBitmap read FBitmap write FBitmap; property ImageStyleLookup: String read FImageStyleLookup write SetImageStyleLookup; property ImageWidth: Single read FImageWidth write SetImageWidth; property ImageHeight: Single read FImageHeight write SetImageHeight; property ImagePadding: Single read FImagePadding write SetImagePadding; property ToolTip: String read FToolTip write SetToolTip; property ToolTipPlacement: TPlacement read GetToolTipPlacement write SetToolTipPlacement default TPlacement.TopCenter; end; procedure Register; implementation uses FMX.Ani, FMX.Forms, SysUtils{$IFNDEF VER230}, FMX.Styles{$ENDIF}; procedure Register; begin RegisterComponents('SolentFMX', [TBitmapSpeedButton]); end; { TToolTipPopup } procedure TToolTipPopup.ApplyStyle; begin inherited; UpdateText; end; procedure TToolTipPopup.ClosePopup; begin //If we close popup while our 'showing' animation is in effect we'll get an error due to an FM bug, //so explicitly stop the animation. StopPropertyAnimation('Opacity'); inherited; end; constructor TToolTipPopup.Create(AOwner: TComponent); begin inherited; Placement := TPlacement.TopCenter; end; procedure TToolTipPopup.Popup(const AShowModal: Boolean); begin if (FText = '') or IsOpen then EXIT; Opacity := 0; //HACK: Inherited calls ApplyPlacement before it calls ApplyStyle. //Since we are setting the size from ApplyStyle (because we don't know how big the text will be //until we know how it is being displayed), this causes placement errors. //And explicitly calling ApplyPlacement causes an AV (or improper placement, I forget which). //So, show the popup (wrong placement), hide it, then show it again (now with correct placement). //As far as I can tell this all happens before the display gets updated, so our animation still works. inherited; ClosePopup; inherited; TAnimator.AnimateFloat(Self, 'Opacity', 1, 0.2); end; procedure TToolTipPopup.SetText(const Value: String); begin FText := Value; UpdateText; end; type THackText = class(TText) end; procedure TToolTipPopup.UpdateText; var T: TFMXObject; TT: TText; begin T := FindStyleResource('Text'); if T is TText then begin TT := TText(T); TT.Text := FText; //Under XE3 setting Text doesn't realign the contents (bug). And Realign is protected so we need to hack around it. THackText(TT).Realign; Width := TT.Width+TT.Padding.Left+TT.Padding.Right; Height := TT.Height+TT.Padding.Top+TT.Padding.Bottom; end; end; { TBitmapSpeedButton } procedure TBitmapSpeedButton.ApplyStyle; var T: TFMXObject; begin inherited; T := FindStyleResource('imagelayout'); if (T <> nil) and (T is TLayout) then FImageLayout := TLayout(T); T := FindStyleResource('image'); if (T <> nil) and (T is TImage) then begin FImage := TImage(T); UpdateImage; end; SetTextVisible(FTextVisible); UpdateImageLayout; end; constructor TBitmapSpeedButton.Create(AOwner: TComponent); begin inherited; FBitmap := TBitmap.Create(0,0); FBitmap.OnChange := EVBitmapChange; FImageAlign := iaCenter; Height := 28; Width := 28; ImageWidth := 24; ImageHeight := 24; ImagePadding := 2; FToolTipTimer := TTimer.Create(Self); FToolTipTimer.Enabled := False; FToolTipTimer.Interval := 2000; FToolTipTimer.OnTimer := EVToolTipTimer; FNoToolTipTimer := TTimer.Create(Self); FNoToolTipTimer.Enabled := False; FNoToolTipTimer.Interval := 2000; FNoToolTipTimer.OnTimer := EVNoToolTipTimer; if not (csDesigning in ComponentState) then begin FToolTipPopup := TToolTipPopup.Create(Self); FToolTipPopup.Parent := Self; end; ToolTipPlacement := TPlacement.TopCenter; end; destructor TBitmapSpeedButton.Destroy; begin FToolTipTimer.Free; FNoToolTipTimer.Free; FreeAndNil(FToolTipPopup); FBitmap.Free; inherited; end; procedure TBitmapSpeedButton.DoMouseEnter; var Showing: Boolean; I: Integer; begin inherited; FNoToolTipTimer.Enabled := False; //Find if any other components have been showing a tooltip recently... Showing := False; if Parent <> nil then for I := 0 to Parent.ChildrenCount-1 do if Parent.Children[I] is TBitmapSpeedButton then Showing := Showing or TBitmapSpeedButton(Parent.Children[I]).ShowingToolTip; //... if show show our tooltip immediately... if Showing then if Assigned(FToolTipPopup) then begin FToolTipPopup.Popup; FShowingToolTip := True; end else //... otherwise start a timer before showing tooltip. else FToolTipTimer.Enabled := True; end; procedure TBitmapSpeedButton.DoMouseLeave; begin inherited; FToolTipTimer.Enabled := False; if Assigned(FToolTipPopup) then begin FToolTipPopup.ClosePopup; FNoToolTipTimer.Enabled := False; FNoToolTipTimer.Enabled := True; end; end; procedure TBitmapSpeedButton.EVBitmapChange(Sender: TObject); begin UpdateImage; end; procedure TBitmapSpeedButton.EVNoToolTipTimer(Sender: TObject); begin if Assigned(FToolTipPopup) and not FToolTipPopup.IsOpen then FShowingToolTip := False; end; procedure TBitmapSpeedButton.EVToolTipTimer(Sender: TObject); begin if IsMouseOver and Assigned(FToolTipPopup) then begin FToolTipPopup.Popup; FShowingToolTip := True; end; end; function TBitmapSpeedButton.GetToolTipPlacement: TPlacement; begin if FToolTipPopup <> nil then Result := FToolTipPopup.Placement else Result := TPlacement.TopCenter; end; procedure TBitmapSpeedButton.SetImageAlign(const Value: TImageAlign); begin FImageAlign := Value; UpdateImageLayout; end; procedure TBitmapSpeedButton.SetImageHeight(const Value: Single); begin FImageHeight := Value; if FImage <> nil then FImage.Height := Value; UpdateImageLayout; end; procedure TBitmapSpeedButton.SetImagePadding(const Value: Single); begin FImagePadding := Value; UpdateImageLayout; end; procedure TBitmapSpeedButton.SetImageStyleLookup(const Value: String); begin FImageStyleLookup := Value; if FImageType = itStyleLookup then UpdateImage; end; procedure TBitmapSpeedButton.SetImageType(const Value: TImageType); var Changed: Boolean; begin Changed := FImageType <> Value; FImageType := Value; if Changed then UpdateImage; end; procedure TBitmapSpeedButton.SetImageWidth(const Value: Single); begin FImageWidth := Value; UpdateImageLayout; end; procedure TBitmapSpeedButton.SetToolTipPlacement(const Value: TPlacement); begin if Assigned(FToolTipPopup) then FToolTipPopup.Placement := Value; end; procedure TBitmapSpeedButton.SetTextVisible(const Value: Boolean); begin FTextVisible := Value; if ({$IFDEF VER230}FTextObject{$ELSE}TextObject{$ENDIF} <> nil) and ({$IFDEF VER230}FTextObject{$ELSE}TextObject{$ENDIF} is TText) then TText({$IFDEF VER230}FTextObject{$ELSE}TextObject{$ENDIF}).Visible := Value; end; procedure TBitmapSpeedButton.SetToolTip(const Value: String); begin FToolTip := Value; if Assigned(FToolTipPopup) then FToolTipPopup.Text := Value; end; procedure TBitmapSpeedButton.UpdateImage; var Obj: TFMXObject; begin if FImageType = itBitmap then if FImage <> nil then FImage.Bitmap.Assign(FBitmap) else else //itResource begin Obj := nil; if (FScene <> nil) and (FScene.GetStyleBook <> nil) and (FScene.GetStyleBook.Root <> nil) then Obj := TControl(FScene.GetStyleBook.{$IFDEF VER230}Root{$ELSE}Style{$ENDIF}.FindStyleResource(FImageStyleLookup)); if Obj = nil then {$IFDEF VER230} if Application.DefaultStyles <> nil then Obj := TControl(Application.DefaultStyles.FindStyleResource(FImageStyleLookup)); {$ELSE} if TStyleManager.ActiveStyle(nil) <> nil then Obj := TControl(TStyleManager.ActiveStyle(nil).FindStyleResource(FImageStyleLookup)); {$ENDIF} if (Obj <> nil) and (Obj is TImage) and (FImage <> nil) then FImage.Bitmap.Assign(TImage(Obj).Bitmap); end; end; procedure TBitmapSpeedButton.UpdateImageLayout; begin if FImage <> nil then begin FImage.Width := ImageWidth; FImage.Height := ImageHeight; case ImageAlign of iaLeft:FImageLayout.Align := TAlignLAyout.Left; iaTop: FImageLayout.Align := TAlignLAyout.Top; iaRight: FImageLayout.Align := TAlignLAyout.Right; iaBottom: FImageLayout.Align := TAlignLAyout.Bottom; else FImageLayout.Align := TAlignLayout.Center; end; end; if FImageLayout <> nil then if ImageAlign in [iaLeft, iaRight] then FImageLayout.Width := FImageWidth+FImagePadding*2 else if ImageAlign in [iaTop, iaBottom] then FImageLayout.Height := FImageHeight+FImagePadding*2; end; initialization RegisterFMXClasses([TBitmapSpeedButton, TToolTipPopup]); end.
unit UBiblioDataSet; interface uses Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls; procedure InitDataset(pDataSet: TClientDataSet); overload; procedure InitDataset(pDataSet: Array of TClientDataSet); overload; procedure AddDataset(pDataSet: TClientDataSet; pFields1: array of string; pFields2: array of Integer); implementation procedure InitDataset(pDataSet: TClientDataSet); begin InitDataset([pDataSet]); end; procedure InitDataset(pDataSet: Array of TClientDataSet); var I: Integer; begin for I := 0 to Length(pDataSet) - 1 do begin if pDataSet[I].active then pDataSet[I].Close; pDataSet[I].FieldDefs.Clear; pDataSet[I].FieldDefs.Add('Field1', ftString, 20); pDataSet[I].FieldDefs.Add('Field2', ftInteger); pDataSet[I].CreateDataSet; end; end; procedure AddDataset(pDataSet: TClientDataSet; pFields1: array of string; pFields2: array of Integer); var I: Integer; begin if Length(pFields1) = 0 then ShowMessage('Não foi informado nenhum valor para o primeiro campo') else if Length(pFields2) = 0 then ShowMessage('Não foi informado nenhum valor para o segundo campo') else if Length(pFields1) <> Length(pFields2) then ShowMessage('Tamanho do Field 1 difere do Field 2') else begin for I := 0 to Length(pFields1) - 1 do begin pDataSet.Append; pDataSet.FieldByName('Field1').AsString := pFields1[I]; pDataSet.FieldByName('Field2').AsInteger := pFields2[I]; pDataSet.Post; end; end; end; end.
program boxconsole; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch FirmOS Business Solutions GmbH www.openfirmos.org New Style BSD Licence (OSI) Copyright (c) 2001-2009, FirmOS Business Solutions GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } {$mode objfpc}{$H+} {$LIBRARYPATH ../../lib} // ./fre_testdatafeed -U root -H 10.220.251.10 -u feeder@system -p a1234 // lazarus+debugger: => ./fre_testdatafeed -U root -H 10.220.251.10 -D {.$DEFINE FOS_WITH_CONSOLE} // ******************************************** // TODO: // COREDUMP Configurieren -> /opt/local/fre/system_coredump // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ uses //cmem, {$IFDEF UNIX} cthreads, {$ENDIF} Classes, SysUtils, CustApp, FRE_SYSTEM,FOS_DEFAULT_IMPLEMENTATION,FOS_TOOL_INTERFACES,FOS_FCOM_TYPES,FRE_APS_INTERFACE,FRE_DB_INTERFACE,fre_aps_comm_impl, FRE_DB_CORE,fos_interlocked,fre_process, {$IFDEF FOS_WITH_CONSOLE} fos_ocrt, {$ENDIF} fos_firmboxfeed_client, fre_basefeed_app; {$IFDEF FOS_WITH_CONSOLE} const cFrameBorder=Blue*16+Blue; cMenuBack=Cyan; cMenuFrame=Cyan; {$ENDIF} {$I fos_version_helper.inc} type { TFRE_BOXCONSOLE_FEED } TFRE_BOXCONSOLE_FEED = class(TFRE_BASEDATA_FEED) private {$IFDEF FOS_WITH_CONSOLE} cBannerHeader : string; cBannerVersion : string; cBannerCopyright : string; cInfoHeader : string; FTerminateGUI : Boolean; BannerWin,Infowin : tnWindow; Menu : tnMenu; procedure BuildScreen; procedure MainMenuSelect; procedure ShowInformation; procedure MenuAppliance; procedure MenuNetwork; procedure MenuLicence; procedure ShowHelp; procedure SystemRestart; procedure SystemShutdown; procedure ShowNetwork; procedure ResetNetwork; procedure UpdateLicence; procedure ShowLicence; function Confirm: boolean; {$ENDIF} public procedure MyRunMethod; override; procedure WriteVersion; override; end; {$IFDEF FOS_WITH_CONSOLE} procedure TFRE_BOXCONSOLE_FEED.BuildScreen; begin cBannerHeader :='FirmOS Firmbox StorageHypervisor Console'; cInfoHeader :='Information'; cBannerCopyright :='FirmOS Business Solutions GmbH 2013'; cBannerVersion :='Developer Edition V 0.9'; TextColor(White); TextBackground(DarkGray); // ClrScr; With BannerWin Do Begin Init(1,1,nStdScr.Cols,5,31,true,cFrameBorder); Show; // ClrScr; TextColor(White); TextBackground(Blue); Fwrite(2,1,GetColor,0,cBannerHeader); Fwrite(2,2,GetColor,0,cBannerCopyright); Fwrite(2,3,GetColor,0,cBannerVersion); End; With Infowin Do Begin Init(1,9,nStdScr.Cols,nstdScr.Rows,31,true,cFrameBorder); Show; // ClrScr; TextColor(White); TextBackground(Blue); FWrite(10,1,Getcolor,0,cInfoHeader); End; With Menu Do Begin Init(3,7,nStdScr.Cols-4,1,5,cMenuBack*16,0,0,false,1); Add('Information'); Add('Appliance'); Add('Network'); Add('Licence'); Add('Help'); Post; SetColor(cMenuBack*16+DarkGray); SetCursorColor(cMenuBack*16+white); Show; End; end; procedure TFRE_BOXCONSOLE_FEED.MainMenuSelect; begin Menu.Start; Infowin.FWrite(10,10,InfoWin.GetColor,0,inttostr(menu.Index)); case menu.Index of 1: ShowInformation; 2: MenuAppliance; 3: MenuNetwork; 4: MenuLicence; 5: ShowHelp; else with InfoWin do begin ClrScr; end; end; end; procedure TFRE_BOXCONSOLE_FEED.ShowInformation; begin with InfoWin do begin ClrScr; FWrite(5,3,GetColor,0,'Information'); end; end; procedure TFRE_BOXCONSOLE_FEED.MenuAppliance; var SubMenu : tnMenu; begin with InfoWin do begin ClrScr; FWrite(5,5,GetColor,0,'Restart for immediate restarting'); FWrite(5,7,GetColor,0,'Shutdown for immediate shutdown'); end; with SubMenu do begin Init(14,8,0,3,1,cMenuBack*16,79,8,true,cMenuFrame*16+cMenuFrame); Add('Restart '); Add('Shutdown '); Add('Cancel'); Post; Start; Case Index of 1 : SystemRestart; 2 : SystemShutdown; End; Hide; End; SubMenu.Done; end; procedure TFRE_BOXCONSOLE_FEED.MenuNetwork; var SubMenu : tnMenu; begin with InfoWin do begin ClrScr; FWrite(5,5,GetColor,0,''); FWrite(5,7,GetColor,0,''); end; with SubMenu do begin Init(26,8,0,3,1,cMenuBack*16,79,8,true,cMenuFrame*16+cMenuFrame); Add('Show Configuration'); Add('Reset Configuration'); Add('Cancel'); Post; Start; Case Index of 1 : ShowNetwork; 2 : ResetNetwork; End; Hide; End; SubMenu.Done; end; procedure TFRE_BOXCONSOLE_FEED.MenuLicence; var SubMenu : tnMenu; begin with InfoWin do begin ClrScr; FWrite(5,5,GetColor,0,''); FWrite(5,7,GetColor,0,''); end; with SubMenu do begin Init(38,8,0,3,1,cMenuBack*16,79,8,true,cMenuFrame*16+cMenuFrame); Add('Show Licence Information'); Add('Update Licence Information'); Add('Cancel'); Post; Start; Case Index of 1 : ShowLicence; 2 : UpdateLicence; End; Hide; End; SubMenu.Done; end; procedure TFRE_BOXCONSOLE_FEED.ShowHelp; begin with InfoWin do begin ClrScr; FWrite(5,3,GetColor,0,'Ctrl+Alt+F1 StorageHypervisor Console'); FWrite(5,5,GetColor,0,'Ctrl+Alt+F2 System Log'); FWrite(5,7,GetColor,0,'Ctrl+Alt+F3 Shell Access'); end; end; procedure TFRE_BOXCONSOLE_FEED.SystemRestart; begin if Confirm then begin writeln('RESTART'); end; end; procedure TFRE_BOXCONSOLE_FEED.SystemShutdown; begin if Confirm then begin FTerminateGUI := true; writeln('YUHu uHu'); //GFRE_BT.CriticalAbort('JACK'); end; end; procedure TFRE_BOXCONSOLE_FEED.ShowNetwork; begin end; procedure TFRE_BOXCONSOLE_FEED.ResetNetwork; begin Confirm; end; procedure TFRE_BOXCONSOLE_FEED.UpdateLicence; begin end; procedure TFRE_BOXCONSOLE_FEED.ShowLicence; begin end; function TFRE_BOXCONSOLE_FEED.Confirm: boolean; var SecMenu : tnMenu; begin result :=false; with SecMenu do begin Init(30,14,0,1,2,cMenuBack*16,79,8,true,cMenuFrame*16+cMenuFrame); Add('Confirm'); Add('Cancel'); Post; Start; Case Index of 1 : result :=true; End; Hide; End; SecMenu.Done; end; {$ENDIF} procedure TFRE_BOXCONSOLE_FEED.MyRunMethod; begin {$IFDEF FOS_WITH_CONSOLE} FTerminateGUI:=false; FOS_Init_OCRT; BuildScreen; repeat MainMenuSelect; until FTerminateGUI; nExit; GFRE_SC.RequestTerminate; {$ENDIF} inherited MyRunMethod; end; procedure TFRE_BOXCONSOLE_FEED.WriteVersion; begin writeln(GFOS_VHELP_GET_VERSION_STRING); end; var Application : TFRE_BOXCONSOLE_FEED; begin cFRE_MACHINE_NAME := 'CoreBox'; //cFRE_MACHINE_IP := '10.1.0.119'; { Testbox SSD } cFRE_SUBFEEDER_IP := '127.0.0.1'; { Subfeeder Local } //cFRE_SUBFEEDER_IP := '10.1.0.119'; { Subfeeder SSD } Application:=TFRE_BOXCONSOLE_FEED.Create(nil,TFRE_BOX_FEED_CLIENT.Create); Application.Run; Application.Free; end.
unit CatLogger; { Catarinka Debug Logger class with elapsed time calculation functions Copyright (c) 2003-2020 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} {$DEFINE USEDIAGNOSTICS} System.Classes, System.SysUtils, Vcl.Controls, System.Diagnostics, System.TimeSpan; {$ELSE} Classes, SysUtils, Controls, Windows; {$ENDIF} type {$IFDEF USEDIAGNOSTICS} // uses high precision stop watch TCatStopWatch = TStopWatch; {$ELSE} TCatStopWatch = record StartTime: Cardinal; end; {$ENDIF} type TCatElapsedTime = record AsString: string; AsStringFriendly: string; MsAsString: string; Ms: Double; end; type TCatLoggerOnLog = procedure(const msg: string) of object; TCatLoggerOnDebug = procedure(const msg: string) of object; type TCatLogger = class private fLastWatchedDebugMsg: string; fMessages: TStringList; fDebugMessages: TStringList; fDurationLog: TStringList; fOnLog: TCatLoggerOnLog; fOnDebug: TCatLoggerOnDebug; fStarted: boolean; fWatch: TCatStopWatch; procedure HandleDebugMessage(const msg: string; const IsStop:boolean); procedure WatchReset; function GetDurationLogText:string; public procedure Clear; procedure Debug(const msg: string); procedure DebugW(const msg: string); procedure Log(const msg: string); constructor Create; destructor Destroy; override; // properties property Messages: TStringList read fMessages; property DebugMessages: TStringList read fDebugMessages; property Durations: string read GetDurationLogText; property DurationLog: TStringList read fDurationLog; // events property OnDebug: TCatLoggerOnDebug read fOnDebug write fOnDebug; property OnLog: TCatLoggerOnLog read fOnLog write fOnLog; end; function CatStopWatchNew: TCatStopWatch; function ElapsedTimeToFriendlyTime(el:TTimeSpan):string; function GetStopWatchElapsedTime(sw: TCatStopWatch): TCatElapsedTime; implementation uses CatStrings; {$IFDEF USEDIAGNOSTICS} function ElapsedTimeToFriendlyTime(el:TTimeSpan):string; begin result := emptystr; if el.Hours <> 0 then result := result + IntToStr(el.Hours)+'h'; if el.Minutes<>0 then result := result + IntToStr(el.Minutes)+'min'; if el.Seconds <> 0 then result := result + IntToStr(el.Seconds)+'sec'; result := result + IntToStr(el.Milliseconds)+'ms'; end; function GetStopWatchElapsedTime(sw: TCatStopWatch): TCatElapsedTime; var el: TTimeSpan; begin el := sw.Elapsed; result.Ms := el.TotalMilliseconds; result.MsAsString := FloatToStr(el.TotalMilliseconds) + ' ms'; result.AsString := el.ToString; result.AsStringFriendly := ElapsedTimeToFriendlyTime(el); end; function CatStopWatchNew: TCatStopWatch; begin result := TStopWatch.StartNew; end; {$ELSE} function GetStopWatchElapsedTime(sw: TCatStopWatch): TCatElapsedTime; var t: Cardinal; Ms: Double; begin t := GetTickCount; Ms := (t - sw.StartTime) / 1000; result.Ms := t; result.MsAsString := FloatToStr(Ms) + ' ms'; result.AsString := result.MsAsString; end; function CatStopWatchNew: TCatStopWatch; begin result.StartTime := GetTickCount; end; {$ENDIF} procedure TCatLogger.HandleDebugMessage(const msg: string; const IsStop:boolean); begin if IsStop = true then fDurationLog.Add(msg); fDebugMessages.Add(msg); if Assigned(fOnDebug) then fOnDebug(msg); end; function TCatLogger.GetDurationLogText:string; begin result := '[['+crlf+fDurationLog.Text+']]'; end; // Standard logging procedure TCatLogger.Log(const msg: string); begin fMessages.add(msg); if Assigned(fOnLog) then fOnLog(msg); end; // Debug logging procedure TCatLogger.Debug(const msg: string); begin HandleDebugMessage(msg, false); end; // Debug logging with StopWatch procedure TCatLogger.DebugW(const msg:string); begin // Logs and starts (if not started yet) or resets the watcher if fStarted = false then begin fStarted := true; fLastWatchedDebugMsg := msg; fWatch := CatStopWatchNew; HandleDebugMessage('started: '+msg, true); end else begin WatchReset; fLastWatchedDebugMsg := msg; end; end; procedure TCatLogger.WatchReset; var et: TCatElapsedTime; begin et := GetStopWatchElapsedTime(fWatch); HandleDebugMessage(et.AsStringFriendly+': '+fLastWatchedDebugMsg, true); {$IFDEF USEDIAGNOSTICS} fWatch.Start; {$ELSE} fWatch := CatStopWatchNew; {$ENDIF} end; procedure TCatLogger.Clear; begin fStarted := false; fMessages.Clear; fDebugMessages.Clear; fDurationLog.Clear; fLastWatchedDebugMsg := emptystr; end; constructor TCatLogger.Create; begin inherited Create; fMessages := TStringList.Create; fDebugMessages := TStringList.Create; fDurationLog := TStringList.Create; Clear; end; destructor TCatLogger.Destroy; begin fDebugMessages.Free; fDurationLog.Free; fMessages.Free; inherited; end; // ------------------------------------------------------------------------// end.
unit adot.Tools; {$OVERFLOWCHECKS OFF} {$IFNDEF Debug} { $Define UseInline} {$ENDIF} { Definition of classes/record types: TArrayStream<T: record> = class Makes any array of ordinal type to be accessable as stream of bytes. TArrayUtils = record Fill/fillRandom/Randomize and other tools for arrays. TBuffer = record Simple and fast managed analog of TMemoryStream. TCachable = class Basic class for objects with data caching/other read optimizations. TComponentUtils = class Enumeration and other component-specific tools. TCurrencyUtils = class Currency type utils. TCustomHash = class Abstract class for hashes. TCustomStreamExt = class Extensions of TStream. TDateTimeRec = record Record type to define TDateTime compatible constants in readable way. TDateTimeUtils = class Check TDateTime correctness, convert to string etc. TDelegatedMemoryStream = class Readonly stream for specified memory block. TFileUtils = class File manipulation utils. TGUIDUtils = class IsValid and other utils. THashes = class Simple API for hashing functions (including CRC32/Adler32) THex = class Set of functions for HEX conversion. TIfThen = class Generic implementation of IfThen (to accept virtually any type). Example: A := TIfThen.Get(Visible, fsMDIChild, fsNormal); TIndexBackEnumerator = record Index enumerator "from last to first". TInterfacedObject<T: class> = class Wrapper class to make any class type available through interface (that means that lifetime of the class will be controlled by reference counter) TNullable<T> = record Extends any type by IsNull property. TPIReader = class Platform independent stream reader. TPIWriter = class Platform independent stream writer. TRLE = class PDF-compatible RLE codec. TReader = record Stream block reader (ReadNext to get next block of data from stream as array of byte) TStreamUtils = class Block reader and other utils. TTimeOut = record Allows to avoid of some operations to be executed too often. TTiming = class Time measuring functions (recursive Start/Stop etc) } interface uses adot.Types, adot.Collections, adot.Collections.Sets, adot.Collections.Maps, adot.Arithmetic, adot.Tools.Rtti, {$If Defined(MSWindows)} { Option "$HINTS OFF" doesn't hide following hint (Delphi 10.2.1), we add Windows here to suppress it: H2443 Inline function 'RenameFile' has not been expanded because unit 'Winapi.Windows' is not specified in USES list } Winapi.Windows, {$EndIf} {$If Defined(POSIX)} Posix.Unistd, Posix.Stdio, {$EndIf} System.DateUtils, System.Types, System.Rtti, System.Math, System.IOUtils, System.Generics.Collections, System.Generics.Defaults, System.Hash, System.Classes, System.SysUtils, System.StrUtils, System.Character, System.TimeSpan, System.Diagnostics, { TStopwatch } System.SyncObjs, { TInterlocked.* } System.Variants, System.ZLib, System.SysConst; type { Set of functions for HEX conversion } THex = class protected const { System.SysUtils.TwoHexLookup is hidden behind implementation section, so we have to reintroduce it. } TwoHexLookup : packed array[0..255] of array[0..1] of Char = ('00','01','02','03','04','05','06','07','08','09','0A','0B','0C','0D','0E','0F', '10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F', '20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F', '30','31','32','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F', '40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F', '50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F', '60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F', '70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F', '80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F', '90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F', 'A0','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF', 'B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF', 'C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF', 'D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF', 'E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF', 'F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'); H2B: packed array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, { 0..9 } -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, { a..f } -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); { A..F } public class function EncodedSizeChars(SourceSizeBytes: integer): integer; static; class function DecodedSizeBytes(EncodedSizeChars: integer): integer; static; class function Encode(const Buf; ByteBufSize: integer): String; overload; static; class function Encode<T: Record>(const Value: T): String; overload; static; class function Encode(const s: TBytes):String; overload; static; class function Encode(const s: string): string; overload; static; class function Encode(const s: string; utf8: boolean): string; overload; static; {$If Defined(MSWindows)} class function EncodeAnsiString(const s: AnsiString):String; static; {$EndIf} class function EncodeByteH(Src: byte): char; static; class function EncodeByteL(Src: byte): char; static; class procedure Decode(const HexEncodedStr: String; var Buf); overload; static; class function Decode<T: Record>(const HexEncodedStr: String): T; overload; static; class function DecodeBytes(const HexEncodedStr: String):TBytes; static; class function DecodeString(const HexEncodedStr: string): string; overload; static; class function DecodeString(const HexEncodedStr: string; utf8: boolean): string; overload; static; {$If Defined(MSWindows)} class function DecodeAnsiString(const HexEncodedStr: String):AnsiString; static; {$EndIf} class function DecodeByte(H,L: Char): byte; static; class function DecodeHexChar(HexChar: Char): byte; static; class function IsValid(const HexEncodedStr: String):Boolean; overload; static; class function IsValid(const HexEncodedStr: String; ZeroBasedStartIdx,Len: integer):Boolean; overload; static; class function IsValid(const C: Char):Boolean; overload; static; { Int64ToHex(Value) <> Encode(Value, SizeOf(Value)) for x86-compatible CPU family, because lower bytes of integers are stored by lower addresses. When we translate integer/pointer to hex we would like to use regular notation, when higher digits are shown first. } class function Int64ToHex(s: Int64): string; static; class function UInt64ToHex(s: UInt64): string; static; class function NativeIntToHex(s: NativeInt): string; static; class function NativeUIntToHex(s: NativeUInt): string; static; class function PointerToHex(s: Pointer): string; static; class function CardinalToHex(s: cardinal): string; static; class function WordToHex(s: word): string; static; class function HexToInt64(const HexEncodedInt: String):Int64; static; class function HexToUInt64(const HexEncodedInt: String):UInt64; static; class function HexToNativeInt(const HexEncodedInt: String):NativeInt; static; class function HexToNativeUInt(const HexEncodedInt: String):NativeUInt; static; class function HexToPointer(const HexEncodedPointer: String):Pointer; static; class function HexToCardinal(const HexEncodedCardinal: String):Cardinal; static; class function HexToWord(const HexEncodedWord: String):Word; static; end; THashData = TArray<byte>; { Abstract class for hashes } TCustomHash = class abstract protected { used by CRC/Adler to transform 32bit hash to TBytes } class function Hash32ToBytes(Hash: Cardinal): TBytes; static; { single call } class function DoEncode(const Buf; ByteBufSize: integer): TBytes; overload; virtual; abstract; class function DoEncode(S: TStream): TBytes; overload; virtual; abstract; { streaming } class procedure DoInit(out Hash: THashData); virtual; abstract; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); virtual; abstract; class function DoDone(var Hash: THashData): TBytes; virtual; abstract; public { single call functions } class function Encode(const Buf; ByteBufSize: integer): TBytes; overload; class function Encode(S: TStream): TBytes; overload; class function Encode(const S: TBytes; StartIndex,Count: integer): TBytes; overload; class function Encode(const S: TBytes): TBytes; overload; class function Encode(const S: string): TBytes; overload; {$If Defined(MSWindows)} class function EncodeAnsiString(const S: AnsiString): TBytes; {$EndIf} class function EncodeFile(const AFileName: string): TBytes; overload; { streaming functions } class procedure Init(out Hash: THashData); { for values with fixed length, hash will be generated from data only } class procedure Update(const Value; ValueByteSize: integer; var Hash: THashData); overload; class procedure Update(const Value: integer; var Hash: THashData); overload; class procedure Update(const Value: double; var Hash: THashData); overload; { for values with variable length, hash will be generated from length and data } class procedure Update(const Value: TArray<byte>; var Hash: THashData); overload; class procedure Update(const Value: string; var Hash: THashData); overload; class function Done(var Hash: THashData): TBytes; end; THashClass = class of TCustomHash; { AH: Don't use THashMD5/THashSHA1 directly, implementation in XE8 has serious bugs: http://qc.embarcadero.com/wc/qcmain.aspx?d=132100 AH (update from 05.04.2016): The issue is fixed, in Delphi 10 Seattle it works correctly. Why we still keep THashes class: - For now Delphi doesn't have CRC/Adler (usefull for files, but can be replaced by THashBobJenkins) - In object model it is much easier to introduce new functions (like hash file/stream etc) - If other issues will be discovered in Delphi lib, we can fix it without changes in the code Simple API for hashing functions (including CRC32/Adler32). Example: function GetHash(L: TList<TRec>): string; var H: THashClass; D: THashData; I: Integer; begin H := THashUtils.Strong; H.Init(D); for I := 0 to List.Count-1 do H.Update(L[I], SizeOf(L[I]), D); result := THashUtils.HashToString(H.Done(D)); end; Same example without THashClass: function GetHash(L: TList<TRec>): string; var D: THashData; I: Integer; begin THashUtils.Strong.Init(D); for I := 0 to List.Count-1 do THashUtils.Strong.Update(L[I], SizeOf(L[I]), D); result := THashUtils.HashToString(THashUtils.Strong.Done(D)); end; } THashUtils = class public const StreamingBufSize = 64*1024; type MD5 = class(TCustomHash) protected class function DoEncode(const Buf; ByteBufSize: integer): TBytes; override; class function DoEncode(S: TStream): TBytes; override; class procedure DoInit(out Hash: THashData); override; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); override; class function DoDone(var Hash: THashData): TBytes; override; end; SHA1 = class(TCustomHash) protected class function DoEncode(const Buf; ByteBufSize: integer): TBytes; override; class function DoEncode(S: TStream): TBytes; override; class procedure DoInit(out Hash: THashData); override; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); override; class function DoDone(var Hash: THashData): TBytes; override; end; { we use default 256bit hash (use THashSHA2 directly for other options - 224bit,384bit,...) } SHA2 = class(TCustomHash) protected class function DoEncode(const Buf; ByteBufSize: integer): TBytes; override; class function DoEncode(S: TStream): TBytes; override; class procedure DoInit(out Hash: THashData); override; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); override; class function DoDone(var Hash: THashData): TBytes; override; end; CRC32 = class(TCustomHash) protected class function DoEncode(const Buf; ByteBufSize: integer): TBytes; override; class function DoEncode(S: TStream): TBytes; override; class procedure DoInit(out Hash: THashData); override; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); override; class function DoDone(var Hash: THashData): TBytes; override; end; Adler32 = class(TCustomHash) protected class function DoEncode(const Buf; ByteBufSize: integer): TBytes; override; class function DoEncode(S: TStream): TBytes; override; class procedure DoInit(out Hash: THashData); override; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); override; class function DoDone(var Hash: THashData): TBytes; override; end; BobJenkins32 = class(TCustomHash) protected class function DoEncode(const Buf; ByteBufSize: integer): TBytes; override; class function DoEncode(S: TStream): TBytes; override; class procedure DoInit(out Hash: THashData); override; class procedure DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); override; class function DoDone(var Hash: THashData): TBytes; override; end; { Strong hash for critical parts (password checksum etc). MD5 is outdated for use in cryptography, but for other tasks it's still good enough } Strong = MD5; { Fast hash with good avalanche effect (hash tables etc). } Fast = BobJenkins32; { Fastest hash for detection of modifications in massive data arrays (file checksum etc). We use Adler32, it's two times faster than Crc32 and still quite good. } Fastest = Adler32; { general } class function Mix(const HashA,HashB: integer): integer; overload; static; {$IFDEF UseInline}inline;{$ENDIF} class function Mix(const HashA,HashB,HashC: integer): integer; overload; static; class function Mix(const HashA,HashB: TBytes): TBytes; overload; static; class function Mix(const Hashes: array of integer): integer; overload; static; class function Mix(const Hashes: array of TBytes): TBytes; overload; static; class function HashToString(const AHash: TBytes): string; static; class function GetHash32(const Hash: TBytes): integer; static; class function GetHash24(const Hash: TBytes): integer; static; class function GetHash16(const Hash: TBytes): integer; static; end; THashes = THashUtils; TInvertedComparer<TValueType> = class(TInterfacedObject, IComparer<TValueType>) protected FExtComparer: IComparer<TValueType>; public constructor Create(AExtComparer: IComparer<TValueType>); function Compare(const Left, Right: TValueType): Integer; end; { Examples: const Date1 : TDateTimeRec = (Year:2009; Month:05; Day:11); Date2 : TDateTimeRec = (Year:2009; Month:05; Day:11; Hour:05); } { Record type to define TDateTime compatible constants in readable way } TDateTimeRec = record Year, Month, Day, Hour, Minute, Second, Millisecond : Word; class operator Implicit(const ADateTime : TDateTimeRec): TDateTime; class operator Implicit(const ADateTime : TDateTime): TDateTimeRec; class operator Implicit(const ADateTime : TDateTimeRec): String; class operator Implicit(const ADateTime : String): TDateTimeRec; end; { Extensions of TStream } TCustomStreamExt = class(TStream) public procedure Clear; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure LoadFromFile(const FileName: string); end; { Readonly stream for specified memory block } TDelegatedMemoryStream = class(TCustomMemoryStream) public constructor Create(Buf: pointer; Size: integer); overload; procedure SetMemory(Buf: pointer; Size: integer); procedure SetSize(const NewSize: Int64); override; procedure SetSize(NewSize: Longint); override; function Write(const Buffer; Count: Longint): Longint; override; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override; end; { Makes any array of ordinal type to be accessable as stream of bytes } TArrayStream<T: record> = class(TCustomStreamExt) protected FItems: TArray<T>; FPos: integer; FSize: integer; FCapacity: integer; procedure SetItems(const Value: TArray<T>); procedure SetCapacity(NewByteCapacity: integer); public constructor Create(const AItems: TArray<T>); overload; function Read(var Buffer; Count: Longint): Longint; override; function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; procedure SetSize(const NewSize: Int64); override; procedure SetSize(NewSize: Longint); override; function Write(const Buffer; Count: Longint): Longint; override; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override; property Items: TArray<T> read FItems write SetItems; end; { Basic class for readonly streams. All Write/Seek methods will generate exception.} TCustomReadOnlyStream = class(TStream) protected function GetSize: Int64; override; procedure SetSize(NewSize: Longint); override; procedure SetSize(const NewSize: Int64); override; public function Write(const Buffer; Count: Longint): Longint; override; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; { methods to be implemented in descendants } //function Read(var Buffer; Count: Longint): Longint; override; //function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override; end; TFuncConst<T,TResult> = reference to function (const Arg1: T): TResult; TFuncConst<T1,T2,TResult> = reference to function (const Arg1: T1; const Arg2: T2): TResult; TFuncConst<T1,T2,T3,TResult> = reference to function (const Arg1: T1; const Arg2: T2; const Arg3: T3): TResult; { Fill/fillRandom/Randomize and other tools for arrays } TArrayUtils = record public class procedure SaveToFileAsText<T>(const Arr: TArray<T>; const AFileName: string); static; class procedure SaveToFileAsBin<T>(const Arr: TArray<T>; const AFileName: string); static; class function Get<T>(const Arr: array of T):TArray<T>; overload; static; class function Get(const Arr: TStringDynArray):TArray<string>; overload; static; class procedure Randomize<T>(var Arr: TArray<T>); static; class procedure Inverse<T>(var Arr: TArray<T>; AStartIndex: integer = 0; ACount: integer = -1); static; class procedure Delete<T>(var Arr: TArray<T>; AFilter: TFuncConst<T,Boolean>); overload; static; class procedure Delete<T>(var Arr: TArray<T>; Index: integer); overload; static; class function Add<T>(const A,B: TArray<T>): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>; StartIndex,Count: integer): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>; ACopyFilter: TFuncConst<T,Boolean>): TArray<T>; overload; static; class function Equal<T>(const A,B: TArray<T>; AComparer: IEqualityComparer<T> = nil): Boolean; overload; static; class function Equal<T>(const A,B: TArray<T>; IndexA,IndexB,Count: integer; AComparer: IEqualityComparer<T> = nil): Boolean; overload; static; class procedure Append<T>(var Dst: TArray<T>; const Src: T); overload; static; class procedure Append<T>(var Dst: TArray<T>; const Src: TArray<T>); overload; static; class procedure Append<T>(var Dst: TArray<T>; const Src: TEnumerable<T>); overload; static; class procedure FillRandom(var Dst: TArray<byte>; Count: integer; AValRangeFrom,AValRangeTo: byte); overload; static; class procedure FillRandom(var Dst: TArray<integer>; Count: integer; AValRangeFrom,AValRangeTo: integer); overload; static; class procedure FillRandom(var Dst: TArray<double>; Count: integer; AValRangeFrom,AValRangeTo: double); overload; static; class procedure FillRandom(var Dst: TArray<string>; Count,ValMaxLen: integer); overload; static; class procedure Fill(var Dst: TArray<byte>; Count: integer; AValueStart,AValueInc: integer); overload; static; class procedure Fill(var Dst: TArray<integer>; Count: integer; AValueStart,AValueInc: integer); overload; static; class procedure Fill(var Dst: TArray<double>; Count: integer; AValueStart,AValueInc: double); overload; static; class procedure StableSort<T>(var Dst: TArray<T>; StartIndex,Count: integer; Comparer: IComparer<T>); static; class function Cut<T>(var Dst: TArray<T>; Capacity,StartIndex,Count: integer): integer; overload; static; class function Cut<T>(var Dst: TArray<T>; StartIndex,Count: integer): integer; overload; static; class function Slice<T>(const Src: TArray<T>; Capacity,StartIndex,Count: integer): TArray<T>; overload; static; class function Slice<T>(const Src: TArray<T>; StartIndex,Count: integer): TArray<T>; overload; static; class function Slice<T>(const Src: TArray<T>; CopyValue: TFunc<T,boolean>): TArray<T>; overload; static; { 9 1 7 2 5 8 -> [1-2] [5] [7-9] } class function Ranges(Src: TArray<integer>): TRangeEnumerable; overload; static; class function Ranges(Src: TEnumerable<integer>): TRangeEnumerable; overload; static; class function IndexOf<T>(const Item: T; const Src: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil): integer; overload; static; class function IndexOf<T>(const Item: T; const Src: TArray<T>; AComparer: IEqualityComparer<T> = nil): integer; overload; static; class function IndexOf<T>(const Template, Data: TArray<T>; AComparer: IEqualityComparer<T> = nil): integer; overload; static; class function GetPtr<T>(const Src: TArray<T>): pointer; static; class function GetFromDynArray(const Src: TStringDynArray): TArray<string>; static; class function Sum(var Arr: double; Count: integer): double; overload; static; class function Sum(var Arr: integer; Count: integer): int64; overload; static; class function Sum(var Arr: int64; Count: integer): int64; overload; static; class function StartWith<T>(const Data,Template: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function EndsWith<T>(const Data,Template: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function Contains<T>(const Template: T; const Data: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function Contains<T>(const Template,Data: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function Sorted<T>(const Arr: TArray<T>; AComparer: IComparer<T> = nil): boolean; overload; static; class function Sorted<T>(const Arr: TArray<T>; AStartIndex,ACount: integer; AComparer: IComparer<T> = nil): boolean; overload; static; class procedure Sort<T>(var Arr: TArray<T>; AComparer: TComparison<T>); static; end; { Check TDateTime correctness, convert to string etc } TDateTimeUtils = class public const NoDateStr = ''; class function IsCorrectDate(const t: TDateTime): boolean; static; class function ToStr(const t: TDateTime; ANoDateStr: string = NoDateStr): string; static; end; { Wrapper class to make any class type available through interface (that means that lifetime of the class will be controlled by reference counter) } TInterfacedObject<T: class> = class(TInterfacedObject, IInterfacedObject<T>) protected FData: T; function GetData: T; procedure SetData(const AData: T); function GetRefCount: integer; public constructor Create(AData: T); destructor Destroy; override; function Extract: T; property Data: T read GetData write SetData; end; { TInterfacedType provides interfaced access to any type. Unlike TInterfacedObject it will not destroy inner object (if T is object type). } TInterfacedType<T> = class(TInterfacedObject, IInterfacedObject<T>) protected FData: T; function GetData: T; procedure SetData(const AData: T); function GetRefCount: integer; public constructor Create(AData: T); function Extract: T; end; { IsValid and other utils } TGUIDUtils = class public const NullGuid: TGUID = '{00000000-0000-0000-0000-000000000000}'; class function IsValid(const S: string): Boolean; static; class function TryStrToGuid(const S: string; out Dst: TGUID): boolean; static; class function StrToGuid(const S: string): TGUID; static; class function StrToGuidDef(const S: string; const Def: TGUID): TGUID; overload; static; class function StrToGuidDef(const S: string): TGUID; overload; static; class function IntToGuid(N: integer): TGUID; static; class function GuidToInt(const Src: TGUID): integer; static; class function GetNew: TGUID; static; class function GetNewAsString: string; static; end; { Block reader and other utils } TStreamUtils = class public type { Stream block reader (ReadNext to get next block of data from stream as array of byte) } TReader = record private AutoFreeCollection: TAutoFreeCollection; Stream: TStream; BytesToRead: int64; public Bytes: TArray<Byte>; Count: integer; procedure Init(Src: TStream; AOwnsStream: Boolean; BufSize: integer; FromBeginning: boolean = True); function ReadNext: Boolean; end; class procedure StringToStream(const S: string; Dst: TStream; Encoding: TEncoding = nil); static; { Copy stream functions (from simple to feature-rich): 1. TStreamUtils.Copy: uses standard Delphi streams, UI will freeze until operation is complete. 2. TVCLStreamUtils.Copy: uses standard Delphi streams, UI will not freeze. } class function Copy(Src,Dst: TStream; Count,BufSize: integer; ProgressProc: TCopyStreamProgressProc): int64; overload; static; class function Copy(Src,Dst: TStream; ProgressProc: TCopyStreamProgressProc): int64; overload; static; class function Copy(Src,Dst: TStream): int64; overload; static; end; TDelegatedOnFile = reference to procedure(const APath: string; const AFile: TSearchRec; var ABreak: Boolean); { File manipulation utils } TFileUtils = class public { remove incorrect chars } class function RemoveInvalidChars(const AFileName: string): string; static; class function FileModeToString(AMode: Integer): string; static; class function AccessAllowed(const AFileName: string; ADesiredAccess: word = fmOpenReadWrite or fmShareExclusive): boolean; static; class function GetOpenFiles(const AMasks,Exceptions: array of string; Recursive: boolean): TArray<string>; overload; static; class function GetOpenFiles(const AMasks,Exceptions: array of string; Recursive: boolean; Delim: string): string; overload; static; class function GetSize(const AFileName: string): int64; static; { enumerate files with callback function and posibility to break/stop } class procedure EnumFiles(const AFileNamePattern: string; AOnfile: TDelegatedOnFile); static; { simple API to clean up old files and keep used space in some ranges (log files, temp files etc) } class procedure CleanUpOldFiles( const AFileNamePattern : string; const AMaxAllowedTotalSize, AMaxAllowedCount : int64; AChanceToRun : Double = 1 { 1 = 100%, 0.3=30% etc }); static; class function DeleteFile(const AFileName: string; out AErrorMessage: string): boolean; static; class function RenameFile(const ASrcFileName,ADstFileName: string; out AErrorMessage: string): boolean; static; { Copy file functions (from simple to feature-rich): 1. TFileUtils.CopyFile: uses standard Delphi streams, UI will freeze until operation is complete. 2. TWinFileUtils.CopyFile: uses Windows function CopyFileEx, UI will freeze until operation is complete. 3. TVCLFileUtils.Copyfile: uses standard Delphi streams, UI will not freeze. 4. TCopyFileProgressDlg.CopyFile: uses either Delphi streams or CopyFileEx, UI will not freeze, progress bar with cancel command will be available for long operations). } class function CopyFile(const SrcFileName,DstFileName: string; out ErrorMessage: string; ProgressProc: TCopyFileProgressProc): boolean; overload; class function CopyFile(const SrcFileName,DstFileName: string; out ErrorMessage: string): boolean; overload; class procedure Load<T: record>(const FileName: string; var Dst: TArray<T>); overload; class procedure Save<T: record>(const FileName: string; const Src: TArray<T>; Index,Count: integer); overload; class procedure Save<T: record>(const FileName: string; const Src: TArray<T>); overload; { Encode disabled chars (hex), check disabled names ("COM1", "PRN", "NUL" etc). } class function StringToFilename(const AStr: string): string; static; { When we check all/lot of files for existance in some folder, it is faster to list files than call FileExists. It is especially true for network drives. Example of timings for network folder with many files: FileExists for every file : 31.65 sec Enumerate all files : 4.19 sec } { Preload list of files into cache } class procedure ExistsBuildCache(const CacheFolder: string; var Cache: TSet<string>; Recursive: boolean = True); static; { Will use preloaded Cache when possible and FileExists function otherwise } class function Exists(const FullFileName,CacheFolder: string; var Cache: TSet<string>): boolean; static; end; { Deprecated, use Sys.IfThen instead } { Generic implementation of IfThen (to accept virtually any type). Example: A := TIfThen.Get(Visible, fsMDIChild, fsNormal); } TIfThen = class public class function Get<T>(ACondition: Boolean; AValueTrue,AValueFalse: T):T; static; end; TFun = class public { Generic IfThen, compatible with any type. Example: Rect := Sys.IfThen(Condition, Rect1, Rect2); } class function IfThen<T>(ACondition: Boolean; AValueTrue,AValueFalse: T):T; static; { Generic swap function, compatible with any type. Example: Sys.Exchange(Rect1,Rect2); } class procedure Exchange<T>(var A,B: T); static; {$IFDEF UseInline}inline;{$ENDIF} { Generic version of FreeAndNil. Much safe than regular FreeAndNil, it accepts classes only and wrong use with other type will be reported as error in compile time. Example: Sys.FreeAndNil(Obj); } class procedure FreeAndNil<T: class>(var Obj: T); static; { Safe generic implementation of FillChar(A,SizeOf(A),0) : - Strictly typified, size is calculated by compiler. - Supports managed types (strings, interfaces, dynamic arrays and other managed types will be freed correctly) } class procedure Clear<T>(var R: T); static; { Generic function to check if value is withing range } class function ValueInRange<T>(AValue, AValueFrom, AValueTo: T): boolean; static; { Type specific functions to check if value is withing range (more efficient than generic ValueInRange) } class function InRange(const AValue, AValueFrom, AValueTo: integer): boolean; overload; static; class function InRange(const AValue, AValueFrom, AValueTo: double): boolean; overload; static; { Type specific functions to check if two ranges are overlapped } class function Overlapped(const AFrom,ATo, BFrom,BTo: integer): boolean; overload; static; class function Overlapped(const AFrom,ATo, BFrom,BTo: double): boolean; overload; static; class function Min(const A,B: integer): integer; overload; static; class function Min(const A,B,C: integer): integer; overload; static; class function Min(const Values: array of integer): integer; overload; static; class function Min(const Values: TArray<integer>): integer; overload; static; class function Max(const A,B: integer): integer; overload; static; class function Max(const A,B,C: integer): integer; overload; static; class function Max(const Values: array of integer): integer; overload; static; class function Max(const Values: TArray<integer>): integer; overload; static; class function Min(const A,B: double): double; overload; static; class function Min(const A,B,C: double): double; overload; static; class function Min(const Values: array of double): double; overload; static; class function Min(const Values: TArray<double>): double; overload; static; class function Max(const A,B: double): double; overload; static; class function Max(const A,B,C: double): double; overload; static; class function Max(const Values: array of double): double; overload; static; class function Max(const Values: TArray<double>): double; overload; static; class function GetPtr(const Values: TArray<byte>): pointer; overload; static; end; { Shortcut to TFun ("Sys.FreeAndNil" looks more natural than "TFun.FreeAndNil"). } Sys = TFun; { Can be used as default enumerator in indexable containers (to implement "for I in XXX do" syntax), example: function TListExt.GetEnumerator: TIndexBackEnumerator; begin result := TIndexBackEnumerator.Create(LastIndex, StartIndex); end; } { Index enumerator "from last to first". } TIndexBackEnumerator = record private FCurrentIndex, FToIndex: integer; public procedure Init(AIndexFrom, AIndexTo: integer); function GetCurrent: Integer; function MoveNext: Boolean; property Current: Integer read GetCurrent; end; { Simple API for time measuring (supports recursion and calculates sum time). Example: TTiming.Start; <do something> OpTime := TTiming.Stop; Caption := Format('Execution time: %.2f seconds, [OpTime.TotalSeconds]); or OpTime := TTiming.Stop('TMyForm.LoadData', TotalTime); Caption := Format('Execution time: %.2f seconds (total: %.2f), [OpTime.TotalSeconds, TotalTime.TotalSeconds]); } { Time measuring functions (recursive Start/Stop etc) } TTiming = class protected type TTotalStat = record private Span: TTimeSpan; Calls: int64; public procedure Init(const ASpan: TTimeSpan; const ACalls: int64); end; class var FTimeStack: TStack<TStopwatch>; FTotalTimes: TDictionary<string, TTotalStat>; class function GetTimeStack: TStack<TStopwatch>; static; class function GetTotalTimes: TDictionary<string, TTotalStat>; static; class destructor DestroyClass; static; class property TimeStack: TStack<TStopwatch> read GetTimeStack; class property TotalTimes: TDictionary<string, TTotalStat> read GetTotalTimes; public class procedure Start; static; class function Stop: TTimeSpan; overload; static; class function Stop(const OpId: string; out ATotalStat: TTotalStat): TTimeSpan; overload; static; class function StopAndGetCaption(const OpId: string): string; overload; static; class function StopAndGetCaption(const OpId,Msg: string): string; overload; static; end; { Simple API to perform periodical actions. Example: T.StartSec(1, 10); Timeout is 1 sec, check for timeout every 10th iteration. for i := 0 to Count-1 do if T.Timedout then Break else ProcessItem(I); } { Allows to avoid of some operations to be executed too often } TTimeOut = record private FOpTimedOut: Boolean; FCounter: integer; FCheckPeriod: integer; FStartTime: TDateTime; FMaxTimeForOp: TDateTime; function GetTimedOut: Boolean; public procedure Init; { If we check for timeout every iteration, usually (when iterations are short) it is too often and our checks may consume more time then usefull work itself. To check only 1 time for N iterations set ACheckPeriod=N. } procedure Start(AMaxTimeForOp: TDateTime; ACheckPeriod: integer = 0); procedure StartSec(AMaxTimeForOpSec: double; ACheckPeriod: integer = 0); procedure StartInfinite; procedure Restart; { If set True manually, then it will be constantly True until next Start* } property TimedOut: Boolean read GetTimedOut write FOpTimedOut; property StartTime: TDateTime read FStartTime; end; { Currency type utils } TCurrencyUtils = class public class function ToString(const Value: Currency; FractionalPart: boolean = False): string; reintroduce; static; end; { Delphi 10 Seattle doesn't have 100% platform independent reader/writer (inherited from TFiler or any other). But TWriter class has set of platform independent functions WriteVar. We write wrapper around TWriter in order to expose only platform independent functionality (and extend it for other basic types). } { Platform independent stream writer } TPIWriter = class protected Writer: TWriter; public constructor Create(ADst: TStream); destructor Destroy; override; { mapped to TWriter } procedure Write(const Value: Char); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Int64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: UInt64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Single); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Double); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: Extended); overload; {$IFDEF UseInline}inline;{$ENDIF} { extentions } procedure Write(const Buf; Count: integer); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Write(const Value: TBytes); overload; procedure Write(const Value: string); overload; end; { Platform independent stream reader } TPIReader = class protected Reader: TReader; public constructor Create(ASrc: TStream); destructor Destroy; override; { mapped to TReader } procedure Read(out Value: Char); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt8); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt16); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt32); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Int64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: UInt64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Single); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Double); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Read(out Value: Extended); overload; {$IFDEF UseInline}inline;{$ENDIF} { extentions } procedure Read(var Buf; Count: integer); overload; procedure Read(out Value: TBytes); overload; procedure Read(out Value: string); overload; end; { Extends any type by IsNull property. Compare operator will use case insensitive comparer for strings (unlike default comparer for strings in Delphi). } TBox<T> = record private type PT = ^T; var FValue: T; FHasValue: string; { AH: all "inline" directives are commented, because Delphi failed to compile it in release configuration (internal error). Reproduced in Delphi 10.1 } function GetValue: T; procedure SetValue(const AValue: T); function GetEmpty: boolean; function GetPointer: PT; public procedure Init; overload; procedure Init(const AValue: T); overload; procedure Clear; function Extract: T; { assign operators } class operator Implicit(const AValue: TBox<T>): T; class operator Implicit(const AValue: T): TBox<T>; { We can't disable assigning of variant to TBox and some wrong assignments will not be checked in compile time. Delphi has different rules for conversion of Null (exception generated) and Unassigned (converted to default value). We rely on Delphi in such conversion to keep default behaviour. //class operator Implicit(const AValue: Variant): TBox<T>; { compare operators } class operator Equal(const Left, Right: TBox<T>): Boolean; class operator Equal(const Left: TBox<T>; const Right: T): Boolean; class operator Equal(const Left: T; const Right: TBox<T>): Boolean; class operator NotEqual(const Left, Right: TBox<T>): Boolean; class operator LessThan(const Left,Right: TBox<T>): Boolean; class operator LessThanOrEqual(const Left,Right: TBox<T>): Boolean; class operator GreaterThan(const Left,Right: TBox<T>): Boolean; class operator GreaterThanOrEqual(const Left,Right: TBox<T>): Boolean; { basic math operators (available for numeric types) } class operator Add(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Subtract(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Multiply(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Divide(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator IntDivide(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Negative(Value: TBox<T>): TBox<T>; property Value: T read GetValue write SetValue; property Empty: boolean read GetEmpty; property ValuePtr: PT read GetPointer; end; { Simple generic class to keep record as object } TEnvelop<T> = class public Value: T; constructor Create; overload; constructor Create(AValue: T); overload; end; { PDF-compatible RLE codec } TRLE = class public class function MaxEncodedSize(ASrcSize: cardinal): cardinal; class function Encode(const ASrc; ASrcSize: cardinal; var ADest): cardinal; class function DecodedSize(const ASrc; APackedSize: cardinal): cardinal; class procedure Decode(const ASrc; APackedSize: cardinal; var ADest; AUnpackedSize: cardinal); end; TForEachComponentBreakProc = reference to procedure(AComponent: TComponent; var ABreak: boolean); { Enumeration and other component-specific tools } TComponentUtils = class public { Enumerates all child components recursively. Returns True if canceled (ACancel is set True by ACallback) } class function ForEach(AStart: TComponent; ACallback: TProcVar1<TComponent, Boolean>): Boolean; overload; static; { Enumerates child components of type T recursively. Returns True if canceled (ACancel is set True by ACallback) } class function ForEach<T: class>(AStart: TComponent; ACallback: TProcVar1<T, Boolean>): Boolean; overload; static; { Enumerates all child components recursively } class procedure ForEach(AStart: TComponent; ACallback: TProc<TComponent>); overload; static; { Enumerates all child components of type T recursively } class procedure ForEach<T: class>(AStart: TComponent; ACallback: TProc<T>); overload; static; { Get all child components recursively } class function GetAll(AStart: TComponent): TArray<TComponent>; overload; static; { Get all child components of type T recursively } class function GetAll<T: class>(AStart: TComponent): TArray<T>; overload; static; { Generates unique component name } class function GetUniqueName: string; static; { Creates copy of the component } class function Copy<T: TComponent>(Src: T): T; static; end; { Executes custom action (procedure/method) when last instance goes out of scope (automatic finalization etc). } TOutOfScopeAction = record private FProc: IInterfacedObject<TObject>; public procedure Init(AProc: TProc); end; { Executes custom action (procedure/method) with specific parameter when last instance goes out of scope. } TOutOfScopeAction<T> = record private type TRunOnDestroy = class private FProc: TProc<T>; FValue: T; public constructor Create(AProc: TProc<T>; AValue: T); destructor Destroy; override; end; var FProc: IInterfacedObject<TRunOnDestroy>; public procedure Init(AProc: TProc<T>; AValue: T); end; { Lightweight and managed analog of TBytesStream. Has mixed set of methods - byte and string-compatible. Check also TStringBuffer from *.Strings unit. } TBuffer = record private FData: TArray<Byte>; FSize: integer; FPosition: integer; procedure SetSize(Value: integer); function GetCapacity: integer; {$IFDEF UseInline}inline;{$ENDIF} procedure SetCapacity(Value: integer); {$IFDEF UseInline}inline;{$ENDIF} procedure CheckCapacity(MinCapacity: integer); {$IFDEF UseInline}inline;{$ENDIF} function GetLeft: integer; {$IFDEF UseInline}inline;{$ENDIF} procedure SetLeft(Value: integer); {$IFDEF UseInline}inline;{$ENDIF} function GetCurrentData: pointer; {$IFDEF UseInline}inline;{$ENDIF} function GetEOF: boolean; {$IFDEF UseInline}inline;{$ENDIF} function GetText: string; procedure SetText(const Value: string); function GetEmpty: Boolean; {$IFDEF UseInline}inline;{$ENDIF} procedure SetData(AData: TArray<Byte>); public procedure Init; { writes bytes from Src to current position. } procedure Write(const Src; ByteCount: integer); overload; { writes characters from Src to the buffer (usually 1 char = 2 bytes). } procedure Write(const Src: string; CharOffset,CharCount: integer); overload; { writes all characters from Src to the buffer (usually 1 char = 2 bytes). } procedure Write(const Src: string); overload; { Reads bytes from the buffer to Dst. } procedure Read(var Dst; ByteCount: integer); overload; { Reads characters from the buffer to specific position of Dst (usually 1 char = 2 bytes). } procedure Read(var Dst: string; DstCharOffset,CharCount: integer); overload; { Reads characters from the buffer to Dst (usually 1 char = 2 bytes). } procedure Read(var Dst: string; CharCount: integer); overload; { Removes part of data from the buffer. } procedure Cut(Start,Len: integer); { Returns range of the buffer as array of bytes. } function Slice(Start,Len: integer): TArray<byte>; { Makes sure that Capacity is equal to Size. After that Data field can be used directly. } procedure TrimExcess; procedure Clear; procedure LoadFromFile(const FileName: string); procedure SaveToFile(const FileName: string); property Size: integer read FSize write SetSize; property Capacity: integer read GetCapacity write SetCapacity; property Position: integer read FPosition write FPosition; property Left: integer read GetLeft write SetLeft; property CurrentData: pointer read GetCurrentData; property EOF: boolean read GetEOF; property Empty: boolean read GetEmpty; property Text: string read GetText write SetText; property Data: TArray<Byte> read FData write SetData; end; TEventUtils = class public class function IsSameHandler(const A,B: TNotifyEvent): Boolean; overload; static; class function IsSameHandler(const A,B: TActionEvent): Boolean; overload; static; class function Equal<T>(const A,B: T): boolean; static; end; TDataSize = record private FSize: int64; function GetGb: double; function GetKb: double; function GetMb: double; function GetTb: double; procedure SetGb(const Value: double); procedure SetKb(const Value: double); procedure SetMb(const Value: double); procedure SetTb(const Value: double); function GetAsString: string; public const Kb = int64(1024); Mb = int64(1024)*Kb; Gb = int64(1024)*Mb; Tb = int64(1024)*Gb; procedure Init(const AValue: int64); procedure InitMb(const AValue: double); class function SizeToString(const AValue: int64): string; static; class operator Implicit(const AValue: TDataSize): int64; class operator Implicit(const AValue: int64): TDataSize; class operator Equal(const Left, Right: TDataSize): Boolean; class operator NotEqual(const Left, Right: TDataSize): Boolean; class operator LessThan(const Left,Right: TDataSize): Boolean; class operator LessThanOrEqual(const Left,Right: TDataSize): Boolean; class operator GreaterThan(const Left,Right: TDataSize): Boolean; class operator GreaterThanOrEqual(const Left,Right: TDataSize): Boolean; class operator Add(Left: TDataSize; Right: TDataSize): TDataSize; class operator Subtract(Left: TDataSize; Right: TDataSize): TDataSize; class operator Multiply(Left: TDataSize; Right: TDataSize): TDataSize; class operator Divide(Left: TDataSize; Right: TDataSize): TDataSize; class operator IntDivide(Left: TDataSize; Right: TDataSize): TDataSize; class operator Negative(Value: TDataSize): TDataSize; property SizeBytes: int64 read FSize write FSize; property SizeKb: double read GetKb write SetKb; property SizeMb: double read GetMb write SetMb; property SizeGb: double read GetGb write SetGb; property SizeTb: double read GetTb write SetTb; property AsString: string read GetAsString; end; { Summed area table. Precalculates sums for very fast calculation of SUM of any area [x1,y1,x2,y2]. https://en.wikipedia.org/wiki/Summed_area_table} TIntegralImageInt64 = record private procedure BuildLine(ADst: PInt64Array); function GetLine(y: integer): PInt64Array; function GetSum(x1, y1, x2, y2: integer): int64; function GetAvg(x1, y1, x2, y2: integer): int64; public Image: TArray<int64>; Width,Height: integer; procedure Init; procedure SetSize(AWidth,AHeight: integer); procedure Build; { release memory etc } procedure Clear; { usefull to fill with initial values } property Lines[y: integer]: PInt64Array read GetLine; { Fastest, no range checks etc } property Sum[x1,y1,x2,y2: integer]:int64 read GetSum; { positions are adjusted to be inside of the image } property Avg[x1,y1,x2,y2: integer]:int64 read GetAvg; default; end; TInterpolation_Int64Custom = class public type TPt = record X,Y: int64; end; protected FPoints: TArray<TPt>; FUpdateCnt: integer; FComparer: IComparer<TPt>; procedure DoBeginUpdate; virtual; procedure DoEndUpdate; virtual; function DoGetValue(const X: int64):int64; virtual; abstract; function GetPointCount: integer; function GetPoint(i: integer): TPt; procedure SetPoint(i: integer; const Value: TPt); public constructor Create(PointCount: integer); virtual; procedure BeginUpdate; procedure EndUpdate; property PointCount: integer read GetPointCount; property Points[i: integer]: TPt read GetPoint write SetPoint; property Values[const x: int64]: int64 read DoGetValue; default; end; TLinearInterpolation_Int64 = class(TInterpolation_Int64Custom) protected function DoGetValue(const X: int64):int64; override; end; TDebugUtils = class public { returns True if application is started from IDE for example } class function DebuggerIsAttached: boolean; static; end; TEventStat = class private FEvents: TMap<string, int64>; public procedure Reg(const EventCategory: string); overload; procedure Reg(const EventCategory: string; Count: int64); overload; procedure UnReg(const EventCategory: string); overload; procedure UnReg(const EventCategory: string; Count: int64); overload; procedure Add(const Src: TArray<TPair<string, int64>>); procedure Clear; function GetStat: TArray<TPair<string, int64>>; end; implementation Uses adot.Strings, adot.Collections.Vectors; { THex } class function THex.EncodedSizeChars(SourceSizeBytes: integer): integer; begin Assert(SourceSizeBytes>=0); result := SourceSizeBytes shl 1; end; class function THex.EncodeByteH(Src: byte): char; begin result := TwoHexLookup[Src][0]; end; class function THex.EncodeByteL(Src: byte): char; begin result := TwoHexLookup[Src][1]; end; class function THex.DecodedSizeBytes(EncodedSizeChars: integer): integer; begin Assert(EncodedSizeChars and 1=0); result := EncodedSizeChars shr 1; end; class function THex.DecodeHexChar(HexChar: Char): byte; begin Assert(IsValid(HexChar)); result := H2B[HexChar]; end; {$IF Defined(NEXTGEN)} class function THex.Encode(const Buf; ByteBufSize: integer): String; const B2HConvert: array[0..15] of Byte = ($30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $41, $42, $43, $44, $45, $46); var I: Integer; begin SetLength(result, EncodedSizeChars(ByteBufSize)); for I := 0 to ByteBufSize - 1 do begin Result[Low(Result) + I*2 ] := Char(B2HConvert[PByte(@Buf)[I] shr 4]); Result[Low(Result) + I*2 + 1] := Char(B2HConvert[PByte(@Buf)[I] and $0F]); end; end; {$Else} class function THex.Encode(const Buf; ByteBufSize: integer): String; begin SetLength(result, EncodedSizeChars(ByteBufSize)); BinToHex(@Buf, PChar(result), ByteBufSize); end; {$EndIF} {$If Defined(MSWindows)} class function THex.EncodeAnsiString(const s: AnsiString): String; begin { need this check only to range check error (when "check range check" is on) } if s='' then result := '' else result := Encode(s[Low(s)], length(s)*SizeOf(s[Low(s)])); end; {$EndIf} class function THex.Encode<T>(const Value: T): String; begin Result := Encode(Value, SizeOf(Value)); end; class function THex.Encode(const s: TBytes): String; begin { need this check only to range check error (when "check range check" is on) } if Length(s)=0 then result := '' else result := Encode(s[0], length(s)); end; class function THex.Encode(const s: string): string; begin { need this check only to range check error (when "check range check" is on) } if s='' then result := '' else result := Encode(s[Low(s)], length(s)*SizeOf(s[Low(s)])); end; class function THex.Encode(const s: string; utf8: boolean): string; begin if utf8 then result := Encode(TEncoding.UTF8.GetBytes(s)) else result := Encode(s); end; {$IF Defined(NEXTGEN)} class procedure THex.Decode(const HexEncodedStr: String; var Buf); const H2BValidSet = ['0'..'9','A'..'F','a'..'f']; H2BConvert: array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); var I: Integer; C1,C2: Char; begin for I := 0 to DecodedSizeBytes(length(HexEncodedStr)) - 1 do begin C1 := HexEncodedStr[Low(String) + I * 2 ]; C2 := HexEncodedStr[Low(String) + I * 2 + 1]; if (C1 >= Low(H2BConvert)) and (C1 <= High(H2BConvert)) and (H2BConvert[C1] >=0 ) and (C2 >= Low(H2BConvert)) and (C2 <= High(H2BConvert)) and (H2BConvert[C2] >=0 ) then PByte(@Buf)[I] := (H2BConvert[C1] shl 4) or H2BConvert[C2] else Break; end; end; {$Else} class procedure THex.Decode(const HexEncodedStr: String; var Buf); begin HexToBin(PChar(HexEncodedStr), Buf, DecodedSizeBytes(length(HexEncodedStr))); end; {$EndIf} class function THex.Decode<T>(const HexEncodedStr: String): T; begin Decode(HexEncodedStr, Result); end; {$If Defined(MSWindows)} class function THex.DecodeAnsiString(const HexEncodedStr: String): AnsiString; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then Result := '' else begin SetLength(Result, DecodedSizeBytes(length(HexEncodedStr))); { AnsiString is always 1 byte per char } Decode(HexEncodedStr, result[Low(result)]); end; end; {$EndIf} class function THex.DecodeByte(H, L: Char): byte; begin result := (DecodeHexChar(H) shl 4) or DecodeHexChar(L); end; class function THex.DecodeBytes(const HexEncodedStr: String): TBytes; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then SetLength(result, 0) else begin SetLength(Result, DecodedSizeBytes(length(HexEncodedStr))); Decode(HexEncodedStr, Result[Low(Result)]); end; end; {$IF SizeOf(Char)=2} class function THex.DecodeString(const HexEncodedStr: string): string; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then result := '' else begin Assert(length(HexEncodedStr) and 3=0); SetLength(Result, length(HexEncodedStr) shr 2); Decode(HexEncodedStr, Result[Low(Result)]); end; end; {$ELSE} class function THex.DecodeString(const HexEncodedStr: string): string; var SizeInBytes: Integer; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then result := '' else begin SizeInBytes := DecodedSizeBytes(length(HexEncodedStr)); Assert(SizeInBytes mod SizeOf(Result[Low(Result)]) = 0); SetLength(Result, SizeInBytes div SizeOf(Result[Low(Result)])); Decode(HexEncodedStr, Result[Low(Result)]); end; end; {$IFEND} class function THex.DecodeString(const HexEncodedStr: string; utf8: boolean): string; begin if utf8 then result := TEncoding.UTF8.GetString( DecodeBytes(HexEncodedStr) ) else result := DecodeString(HexEncodedStr); end; class function THex.IsValid(const C: Char): Boolean; begin result := (c>=Low(H2B)) and (c<=High(H2B)) and (H2B[c]>=0); end; class function THex.IsValid(const HexEncodedStr: String; ZeroBasedStartIdx, Len: integer): Boolean; var i: Integer; begin for i := ZeroBasedStartIdx to ZeroBasedStartIdx+Len-1 do if not IsValid(HexEncodedStr.Chars[i]) then Exit(False); Result := True; end; class function THex.IsValid(const HexEncodedStr: String): Boolean; begin Result := IsValid(HexEncodedStr, 0,Length(HexEncodedStr)); end; class function THex.HexToInt64(const HexEncodedInt: String):Int64; var i: Integer; begin assert(IsValid(HexEncodedInt)); result := 0; for i := Low(HexEncodedInt) to High(HexEncodedInt) do result := (result shl 4) or H2B[HexEncodedInt[i]]; end; class function THex.HexToUInt64(const HexEncodedInt: String):UInt64; begin result := UInt64(HexToInt64(HexEncodedInt)); end; class function THex.HexToNativeInt(const HexEncodedInt: String):NativeInt; var i: Integer; begin assert(IsValid(HexEncodedInt)); result := 0; for i := Low(HexEncodedInt) to High(HexEncodedInt) do result := (result shl 4) or H2B[HexEncodedInt[i]]; end; class function THex.HexToNativeUInt(const HexEncodedInt: String):NativeUInt; begin result := NativeUInt(HexToNativeInt(HexEncodedInt)); end; class function THex.HexToPointer(const HexEncodedPointer: String): Pointer; begin result := Pointer(HexToNativeUInt(HexEncodedPointer)); end; class function THex.HexToCardinal(const HexEncodedCardinal: String):Cardinal; var i: Integer; begin assert(IsValid(HexEncodedCardinal)); result := 0; for i := Low(HexEncodedCardinal) to High(HexEncodedCardinal) do result := (result shl 4) or Cardinal(H2B[HexEncodedCardinal[i]]); end; class function THex.HexToWord(const HexEncodedWord: String):Word; begin result := Word(HexToCardinal(HexEncodedWord)); end; class function THex.Int64ToHex(s: Int64): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := High(result) shr 1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; class function THex.UInt64ToHex(s: UInt64): string; begin result := Int64ToHex(Int64(s)); end; class function THex.NativeIntToHex(s: NativeInt): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := SizeOf(s)-1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; class function THex.NativeUIntToHex(s: NativeUInt): string; begin result := NativeIntToHex(NativeInt(s)); end; class function THex.PointerToHex(s: Pointer): string; begin result := NativeIntToHex(NativeInt(s)); end; class function THex.CardinalToHex(s: cardinal): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := SizeOf(s)-1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; class function THex.WordToHex(s: word): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := SizeOf(s)-1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; { TInvertedComparer<TValue> } constructor TInvertedComparer<TValueType>.Create(AExtComparer: IComparer<TValueType>); begin inherited Create; FExtComparer := AExtComparer; if FExtComparer=nil then FExtComparer := TComparer<TValueType>.Default; end; function TInvertedComparer<TValueType>.Compare(const Left, Right: TValueType): Integer; begin result := -FExtComparer.Compare(Left, Right); end; { TDateTimeRec } class operator TDateTimeRec.Implicit(const ADateTime: TDateTime): TDateTimeRec; begin with Result do DecodeDateTime(ADateTime, Year, Month, Day, Hour, Minute, Second, Millisecond); end; class operator TDateTimeRec.Implicit(const ADateTime: TDateTimeRec): TDateTime; begin with ADateTime do Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); end; class operator TDateTimeRec.Implicit(const ADateTime: String): TDateTimeRec; begin Result := StrToDateTime(ADateTime); end; class operator TDateTimeRec.Implicit(const ADateTime: TDateTimeRec): String; begin Result := DateTimeToStr(ADateTime); end; { TDelegatedMemoryStream } constructor TDelegatedMemoryStream.Create(Buf: pointer; Size: integer); begin inherited Create; SetPointer(Buf, Size); end; procedure TDelegatedMemoryStream.SetMemory(Buf: pointer; Size: integer); begin SetPointer(Buf, Size); Position := 0; end; procedure TDelegatedMemoryStream.SetSize(NewSize: Longint); begin raise Exception.Create('Error'); end; procedure TDelegatedMemoryStream.SetSize(const NewSize: Int64); begin raise Exception.Create('Error'); end; function TDelegatedMemoryStream.Write(const Buffer; Count: Longint): Longint; begin raise Exception.Create('Error'); end; function TDelegatedMemoryStream.Write(const Buffer: TBytes; Offset, Count: Longint): Longint; begin raise Exception.Create('Error'); end; { TCustomStreamExt } procedure TCustomStreamExt.Clear; begin Size := 0; end; procedure TCustomStreamExt.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TCustomStreamExt.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TCustomStreamExt.LoadFromStream(Stream: TStream); var P: Int64; begin Size := Stream.Size; P := Stream.Position; try Stream.Position := 0; CopyFrom(Stream, Stream.Size); finally Stream.Position := P; end; end; procedure TCustomStreamExt.SaveToStream(Stream: TStream); var P: Int64; begin P := Position; try Position := 0; Stream.CopyFrom(Self, Size); finally Position := P; end; end; { TArrayStream<T> } constructor TArrayStream<T>.Create(const AItems: TArray<T>); begin inherited Create; Items := AItems; end; procedure TArrayStream<T>.SetItems(const Value: TArray<T>); begin FItems := Value; FPos := 0; FCapacity := Length(FItems)*SizeOf(T); FSize := FCapacity; end; procedure TArrayStream<T>.SetCapacity(NewByteCapacity: integer); begin if NewByteCapacity mod SizeOf(T)<>0 then raise Exception.Create('Error'); SetLength(FItems, NewByteCapacity div SizeOf(T)); FCapacity := NewByteCapacity; if FSize>FCapacity then FSize := FCapacity; if FPos>FCapacity then FPos := FCapacity; end; function TArrayStream<T>.Read(var Buffer; Count: Longint): Longint; begin if (FPos >= 0) and (Count >= 0) then begin Result := FSize - FPos; if Result > 0 then begin if Result > Count then Result := Count; Move((PByte(FItems) + FPos)^, Buffer, Result); Inc(FPos, Result); Exit; end; end; Result := 0; end; function TArrayStream<T>.Read(Buffer: TBytes; Offset, Count: Longint): Longint; begin Result := Read(Buffer[Offset], Count); end; procedure TArrayStream<T>.SetSize(const NewSize: Int64); var OldPosition: Longint; begin OldPosition := FPos; SetCapacity(NewSize); { Will check that NewSize mod SizeOf(T)=0 } FSize := NewSize; if OldPosition > NewSize then Seek(0, soEnd); end; procedure TArrayStream<T>.SetSize(NewSize: Longint); begin SetSize(Int64(NewSize)); end; function TArrayStream<T>.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin case Origin of soBeginning : FPos := Offset; soCurrent : Inc(FPos, Offset); soEnd : FPos := FSize + Offset; end; if FPos<0 then FPos := 0; Result := FPos; end; function TArrayStream<T>.Write(const Buffer; Count: Longint): Longint; var P: integer; begin if (FPos >= 0) and (Count >= 0) then begin P := FPos + Count; if P > 0 then begin if P > FSize then begin if P > FCapacity then SetCapacity(P); FSize := P; end; System.Move(Buffer, (PByte(FItems) + FPos)^, Count); FPos := P; Result := Count; Exit; end; end; Result := 0; end; function TArrayStream<T>.Write(const Buffer: TBytes; Offset, Count: Longint): Longint; begin Result := Write(Buffer[Offset], Count); end; { TArrayUtils } class function TArrayUtils.Copy<T>(const Src: TArray<T>): TArray<T>; begin result := Copy<T>(Src, 0, Length(Src)); end; class function TArrayUtils.Copy<T>(const Src: TArray<T>; StartIndex, Count: integer): TArray<T>; var i: Integer; begin SetLength(result, Count); if Count > 0 then if TRttiUtils.IsOrdinal<T> then System.Move(Src[StartIndex], Result[0], Count*SizeOf(T)) else for i := 0 to Count-1 do result[i] := Src[i + StartIndex]; end; class function TArrayUtils.Copy<T>(const Src: TArray<T>; ACopyFilter: TFuncConst<T, Boolean>): TArray<T>; var i,j: Integer; begin SetLength(result, Length(Src)); j := 0; for i := 0 to High(Src) do if ACopyFilter(Src[i]) then begin result[j] := Src[i]; inc(j); end; SetLength(result, j); end; class procedure TArrayUtils.Append<T>(var Dst: TArray<T>; const Src: T); var i: integer; begin i := Length(Dst); SetLength(Dst, i+1); Dst[i] := Src; end; class procedure TArrayUtils.Append<T>(var Dst: TArray<T>; const Src: TArray<T>); var i,j: integer; begin j := Length(Dst); SetLength(Dst, j + Length(Src)); for I := 0 to High(Src) do Dst[I+J] := Src[I]; end; class function TArrayUtils.Add<T>(const A, B: TArray<T>): TArray<T>; var I,J: Integer; begin SetLength(Result, Length(A) + Length(B)); for I := 0 to Length(A)-1 do Result[I] := A[I]; J := Length(A); for I := 0 to Length(B)-1 do Result[I+J] := B[I]; end; class procedure TArrayUtils.Append<T>(var Dst: TArray<T>; const Src: TEnumerable<T>); var I: integer; Value: T; begin I := 0; for Value in Src do inc(I); SetLength(dst, Length(dst) + I); I := Length(dst) - I; for Value in Src do begin Dst[I] := Value; inc(I); end; Assert(I=Length(Dst)); end; class function TArrayUtils.Contains<T>(const Template: T; const Data: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := IndexOf<T>(Template, Data, AComparer) >= 0; end; class function TArrayUtils.Contains<T>(const Template, Data: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := IndexOf<T>(Template, Data, AComparer) >= 0; end; class function TArrayUtils.Sorted<T>(const Arr: TArray<T>; AComparer: IComparer<T> = nil): boolean; begin result := Sorted<T>(Arr, 0, Length(Arr), AComparer); end; class procedure TArrayUtils.Sort<T>(var Arr: TArray<T>; AComparer: TComparison<T>); var C: IComparer<T>; begin C := TDelegatedComparer<T>.Create(AComparer); TArray.Sort<T>(Arr, C); end; class function TArrayUtils.Sorted<T>(const Arr: TArray<T>; AStartIndex,ACount: integer; AComparer: IComparer<T> = nil): boolean; var I: Integer; begin if ACount <= 0 then Exit(True); if AComparer = nil then AComparer := TComparerUtils.DefaultComparer<T>; Assert((AStartIndex >= 0) and (AStartIndex + ACount - 1 < Length(Arr))); for I := AStartIndex to AStartIndex + ACount - 2 do if AComparer.Compare(Arr[I], Arr[I+1]) > 0 then Exit(False); result := True; end; class procedure TArrayUtils.Delete<T>(var Arr: TArray<T>; AFilter: TFuncConst<T, Boolean>); var i,j: Integer; begin j := -1; for i := 0 to High(Arr) do if AFilter(Arr[i]) then begin j := i; Break; end; if j<0 then Exit; for i := j+1 to High(Arr) do if not AFilter(Arr[i]) then begin Arr[j] := Arr[i]; inc(j); end; SetLength(Arr, j); end; class procedure TArrayUtils.Delete<T>(var Arr: TArray<T>; Index: integer); var I: Integer; begin if (Index >= Low(Arr)) and (Index <= High(Arr)) then begin for I := Index to High(Arr)-1 do Arr[I] := Arr[I+1]; SetLength(Arr, Length(Arr)-1); end; end; class function TArrayUtils.Equal<T>(const A, B: TArray<T>; IndexA, IndexB, Count: integer; AComparer: IEqualityComparer<T>): Boolean; var I,J: Integer; begin if (Length(A)-IndexA < Count) or (Length(B)-IndexB < Count) then Exit(False); if Count <= 0 then Exit(True); if TRttiUtils.IsOrdinal<T> and (AComparer=nil) then { A & B are not empty -> it is safe to use @A[0] / @B[0] } result := CompareMem(@A[IndexA], @B[IndexB], Count*SizeOF(T)) else begin if AComparer=nil then AComparer := TEqualityComparer<T>.Default; for i := 0 to Count-1 do if not AComparer.Equals(A[i+IndexA], B[i+IndexB]) then Exit(False); result := True; end; end; class function TArrayUtils.Equal<T>(const A, B: TArray<T>; AComparer: IEqualityComparer<T>): Boolean; var i: Integer; begin result := Length(A)=Length(B); if result and (Length(A) > 0) then if TRttiUtils.IsOrdinal<T> and (AComparer=nil) then { A & B are not empty -> it is safe to use @A[0] / @B[0] } result := CompareMem(@A[0], @B[0], Length(A)*SizeOF(T)) else begin if AComparer=nil then AComparer := TEqualityComparer<T>.Default; for i := 0 to High(A) do if not AComparer.Equals(A[i], B[i]) then Exit(False); end; end; class procedure TArrayUtils.Fill(var Dst: TArray<byte>; Count, AValueStart, AValueInc: integer); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do begin Dst[I] := AValueStart; inc(AValueStart, AValueInc); end; end; class procedure TArrayUtils.Fill(var Dst: TArray<integer>; Count, AValueStart, AValueInc: integer); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do begin Dst[I] := AValueStart; inc(AValueStart, AValueInc); end; end; class procedure TArrayUtils.Fill(var Dst: TArray<double>; Count: integer; AValueStart, AValueInc: double); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do begin Dst[I] := AValueStart; AValueStart := AValueStart + AValueInc; end; end; class procedure TArrayUtils.FillRandom(var Dst: TArray<byte>; Count: integer; AValRangeFrom, AValRangeTo: byte); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do Dst[I] := AValRangeFrom + Random(integer(AValRangeTo)-integer(AValRangeFrom)+1); end; class procedure TArrayUtils.FillRandom(var Dst: TArray<integer>; Count, AValRangeFrom, AValRangeTo: integer); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do Dst[I] := AValRangeFrom + Random(AValRangeTo-AValRangeFrom+1); end; class procedure TArrayUtils.FillRandom(var Dst: TArray<string>; Count, ValMaxLen: integer); var i: Integer; begin if Count >=0 then SetLength(Dst, Count); if ValMaxLen <= 0 then ValMaxLen := 10; for i := 0 to High(Dst) do Dst[i] := TStr.Random(System.Random(ValMaxLen), 'a','z'); end; class procedure TArrayUtils.FillRandom(var Dst: TArray<double>; Count: integer; AValRangeFrom, AValRangeTo: double); var i: Integer; begin if Count >=0 then SetLength(Dst, Count); for I := 0 to High(Dst) do Dst[I] := AValRangeFrom + Random*(AValRangeTo-AValRangeFrom); end; class function TArrayUtils.Get(const Arr: TStringDynArray): TArray<string>; var I: Integer; begin SetLength(result, Length(Arr)); for I := Low(Arr) to High(Arr) do result[I] := Arr[I]; end; class function TArrayUtils.Get<T>(const Arr: array of T): TArray<T>; var i: Integer; begin SetLength(result, Length(Arr)); for i := 0 to High(result) do result[i] := Arr[i]; end; class function TArrayUtils.GetFromDynArray(const Src: TStringDynArray): TArray<string>; var I: Integer; begin SetLEngth(result, Length(Src)); for I := Low(Src) to High(Src) do result[I] := Src[I]; end; class function TArrayUtils.GetPtr<T>(const Src: TArray<T>): pointer; begin if Length(Src)=0 then result := nil else result := @Src[0]; end; class function TArrayUtils.IndexOf<T>(const Item: T; const Src: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil): integer; var V: T; begin if AComparer = nil then AComparer := TComparerUtils.DefaultEqualityComparer<T>; result := 0; for V in Src do if AComparer.Equals(V, Item) then Exit else inc(result); result := -1; end; class function TArrayUtils.IndexOf<T>(const Item: T; const Src: TArray<T>; AComparer: IEqualityComparer<T> = nil): integer; var I: integer; begin if AComparer = nil then AComparer := TComparerUtils.DefaultEqualityComparer<T>; for I := 0 to High(Src) do if AComparer.Equals(Src[I], Item) then Exit(I); result := -1; end; class function TArrayUtils.IndexOf<T>(const Template, Data: TArray<T>; AComparer: IEqualityComparer<T>): integer; var I,J: integer; begin result := -1; if (Length(Data)=0) or (Length(Data) < Length(Template)) then Exit; if AComparer = nil then AComparer := TComparerUtils.DefaultEqualityComparer<T>; for I := 0 to Length(Data)-Length(Template) do if AComparer.Equals(Data[I], Template[0]) then begin result := I; for J := 1 to High(Template) do if not AComparer.Equals(Data[I+J], Template[J]) then begin result := -1; break; end; if result >= 0 then break; end; end; class procedure TArrayUtils.Inverse<T>(var Arr: TArray<T>; AStartIndex, ACount: integer); var i,EndIndex: Integer; Value: T; begin if ACount < 0 then ACount := Length(Arr); EndIndex := AStartIndex + ACount - 1; for i := 0 to ACount div 2-1 do begin Value := Arr[AStartIndex]; Arr[AStartIndex] := Arr[EndIndex]; Arr[EndIndex] := Value; inc(AStartIndex); dec(EndIndex); end; end; class procedure TArrayUtils.Randomize<T>(var Arr: TArray<T>); var I,J,N: Integer; V: T; begin N := Length(Arr); for I := 0 to N-1 do begin J := Random(N); V := Arr[I]; Arr[I] := Arr[J]; Arr[J] := V; end; end; class function TArrayUtils.Ranges(Src: TEnumerable<integer>): TRangeEnumerable; begin result := Ranges(Src.ToArray); end; class function TArrayUtils.Ranges(Src: TArray<integer>): TRangeEnumerable; begin result.Init(Src); end; class procedure TArrayUtils.SaveToFileAsBin<T>(const Arr: TArray<T>; const AFileName: string); var Stream: TFileStream; begin Stream := TFileStream.Create(AFileName, fmCreate); try Stream.Write(Arr[Low(Arr)], SizeOf(T)*Length(Arr)) finally Stream.Free; end; end; class procedure TArrayUtils.SaveToFileAsText<T>(const Arr: TArray<T>; const AFileName: string); var Stream: TFileStream; Writer: TStreamWriter; Value: T; begin Stream := nil; Writer := nil; try Stream := TFileStream.Create(AFileName, fmCreate); Writer := TStreamWriter.Create(Stream); for Value in Arr do Writer.Write( TValue.From(Value).ToString ); finally Writer.Free; Stream.Free; end; end; class procedure TArrayUtils.StableSort<T>(var Dst: TArray<T>; StartIndex, Count: integer; Comparer: IComparer<T>); var Idx: TArray<integer>; Src,Tmp: TArray<T>; Cmp: IComparer<integer>; I: Integer; begin SetLength(Idx, Count); for I := 0 to High(Idx) do Idx[I] := I + StartIndex; Src := Dst; Cmp := TDelegatedComparer<integer>.Create( function(const A,B: integer): integer begin result := Comparer.Compare(Src[Idx[A]], Src[Idx[B]]); if result=0 then result := Idx[B]-Idx[A]; end); TArray.Sort<integer>(Idx, Cmp); SetLength(Tmp, Count); for I := 0 to High(Tmp) do Tmp[I] := Dst[Idx[I]]; for I := 0 to High(Tmp) do Dst[I+StartIndex] := Tmp[I]; end; class function TArrayUtils.StartWith<T>(const Data, Template: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := (Length(Data) >= Length(Template)) and TArrayUtils.Equal<T>(Data, Template, 0, 0, Length(Template), AComparer); end; class function TArrayUtils.EndsWith<T>(const Data, Template: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := (Length(Data) >= Length(Template)) and TArrayUtils.Equal<T>(Data, Template, Length(Data)-Length(Template), 0, Length(Template), AComparer); end; class function TArrayUtils.Sum(var Arr: integer; Count: integer): int64; var p: ^integer; begin p := @Arr; result := 0; while Count > 0 do begin dec(Count); inc(result, p^); inc(p); end; end; class function TArrayUtils.Sum(var Arr: int64; Count: integer): int64; var p: ^int64; begin p := @Arr; result := 0; while Count > 0 do begin dec(Count); inc(result, p^); inc(p); end; end; class function TArrayUtils.Sum(var Arr: double; Count: integer): double; var p: ^double; begin p := @Arr; result := 0; while Count > 0 do begin dec(Count); result := result + p^; inc(p); end; end; class function TArrayUtils.Cut<T>(var Dst: TArray<T>; Capacity,StartIndex,Count: integer): integer; var I: Integer; begin if StartIndex >= Capacity then Exit(0); result := Count; if StartIndex < 0 then begin inc(result, StartIndex); StartIndex := 0; end; result := Max(Min(result, Capacity-StartIndex), 0); if result = 0 then Exit; if TRttiUtils.IsOrdinal<T> then System.Move(Dst[StartIndex+result], Dst[StartIndex], (Capacity-StartIndex-result)*SizeOf(T)) else for I := 0 to result-1 do Dst[I+StartIndex] := Dst[I+StartIndex+result]; end; class function TArrayUtils.Cut<T>(var Dst: TArray<T>; StartIndex,Count: integer): integer; begin result := Cut<T>(Dst, Length(Dst), StartIndex, Count); end; class function TArrayUtils.Slice<T>(const Src: TArray<T>; Capacity,StartIndex,Count: integer): TArray<T>; var I: Integer; begin if StartIndex >= Capacity then Count := 0 else begin if StartIndex < 0 then begin inc(Count, StartIndex); StartIndex := 0; end; Count := Min(Count, Capacity-StartIndex); end; if Count <= 0 then SetLength(result, 0) else begin SetLength(result, Count); if TRttiUtils.IsOrdinal<T> then System.Move(Src[StartIndex], result[0], Count*SizeOf(T)) else for I := 0 to Count-1 do result[I] := Src[I+StartIndex]; end; end; class function TArrayUtils.Slice<T>(const Src: TArray<T>; StartIndex,Count: integer): TArray<T>; begin result := Slice<T>(Src, Length(Src), StartIndex, Count); end; class function TArrayUtils.Slice<T>(const Src: TArray<T>; CopyValue: TFunc<T, boolean>): TArray<T>; var V: TArr<T>; I: Integer; begin V.Clear; for I := Low(Src) to High(Src) do if CopyValue(Src[I]) then V.Add(Src[I]); V.TrimExcess; result := V.Items; end; { TDateTimeUtils } class function TDateTimeUtils.IsCorrectDate(const t: TDateTime): boolean; begin result := (Trunc(t)<>0) and { 0 (30.12.1899) as empty value } (YearOf(t)>0); { -700000 (00.00.0000) as empty value + Delphi supports only "01.01.01" and later } end; class function TDateTimeUtils.ToStr(const t: TDateTime; ANoDateStr: string): string; begin if IsCorrectDate(t) then result := DateToStr(t) else result := ANoDateStr; end; { TInterfacedObject<T> } constructor TInterfacedObject<T>.Create(AData: T); begin inherited Create; FData := AData; end; destructor TInterfacedObject<T>.Destroy; begin Sys.FreeAndNil(FData); inherited; end; function TInterfacedObject<T>.Extract: T; begin result := FData; FData := nil; end; function TInterfacedObject<T>.GetData: T; begin result := FData; end; procedure TInterfacedObject<T>.SetData(const AData: T); begin if (FData<>nil) and (FData<>AData) then Sys.FreeAndNil(FData); FData := AData; end; function TInterfacedObject<T>.GetRefCount: integer; begin result := RefCount; end; { TGUIDUtils } class function TGUIDUtils.IntToGuid(N: integer): TGUID; begin {$If SizeOf(integer)<>4} {$MESSAGE ERROR 'unexpected size of integer type' } {$EndIf} result := Default(TGUID); result.D1 := cardinal(N); end; class function TGUIDUtils.GuidToInt(const Src: TGUID): integer; begin {$If SizeOf(integer)<>4} {$MESSAGE ERROR 'unexpected size of integer type' } {$EndIf} result := integer(Src.D1); end; class function TGUIDUtils.IsValid(const S: string): Boolean; var i: Integer; begin (* {41D3CDB4-1249-41CF-91E8-52D2C2EDC314} *) i := Length(S); result := (i = 38) and (S.Chars[ 0] = '{') and (S.Chars[i-1] = '}') and (S.Chars[ 9] = '-') and (S.Chars[ 14] = '-') and (S.Chars[ 19] = '-') and (S.Chars[ 24] = '-') and THex.IsValid(S, 1, 8) and THex.IsValid(S, 10, 4) and THex.IsValid(S, 15, 4) and THex.IsValid(S, 20, 4) and THex.IsValid(S, 25,12); end; class function TGUIDUtils.GetNew: TGUID; begin CreateGUID(Result); end; class function TGUIDUtils.GetNewAsString: string; var G: TGUID; begin CreateGUID(G); result := GuidToString(G); end; class function TGUIDUtils.TryStrToGuid(const S: string; out Dst: TGUID): boolean; begin result := IsValid(S); if result then Dst := StringToGuid(S); end; class function TGUIDUtils.StrToGuid(const S: string): TGUID; begin result := StringToGuid(S); end; class function TGUIDUtils.StrToGuidDef(const S: string): TGUID; begin result := StrToGuidDef(S, NullGuid); end; class function TGUIDUtils.StrToGuidDef(const S: string; const Def: TGUID): TGUID; begin if IsValid(S) then result := StringToGuid(S) else result := Def; end; { TStreamUtils.TReader } procedure TStreamUtils.TReader.Init(Src: TStream; AOwnsStream: Boolean; BufSize: integer; FromBeginning: boolean); begin Self := Default(TStreamUtils.TReader); Stream := Src; if AOwnsStream then AutoFreeCollection.Add(Stream); SetLength(Bytes, BufSize); if not FromBeginning then BytesToRead := Stream.Size - Stream.Position else begin Stream.Position := 0; BytesToRead := Stream.Size; end; end; function TStreamUtils.TReader.ReadNext: Boolean; begin Result := BytesToRead > 0; if Result then begin Count := Min(BytesToRead, Length(Bytes)); Stream.ReadBuffer(Bytes, Count); Dec(BytesToRead, Count); end else begin SetLength(Bytes, 0); Count := 0; end; end; { TStreamUtils } class function TStreamUtils.Copy(Src, Dst: TStream; Count,BufSize: integer; ProgressProc: TCopyStreamProgressProc): int64; var N: Integer; Buffer: TBytes; LastOnProgressTime: TDateTime; Cancel: Boolean; begin { check TVCLStreamUtils.Copy if you don't want UI to freeze until operation is complete } { based on TStream.CopyFrom, but provides time-based callback ProgressProc } Result := 0; LastOnProgressTime := 0; if Count <= 0 then begin Src.Position := 0; Count := Src.Size; end; if BufSize=0 then BufSize := 65536 else BufSize := Max(BufSize, 4096); SetLength(Buffer, BufSize); Cancel := False; if Assigned(ProgressProc) then begin ProgressProc(0, Cancel); LastOnProgressTime := Now; end; while (Count <> 0) and not Cancel do begin N := Min(Count, BufSize); Src.ReadBuffer(Buffer, N); Dst.WriteBuffer(Buffer, N); Dec(Count, N); Inc(Result, N); if Assigned(ProgressProc) and (MilliSecondsBetween(Now, LastOnProgressTime)>=50) then begin ProgressProc(Result, Cancel); LastOnProgressTime := Now; end; end; if Assigned(ProgressProc) then ProgressProc(Result, Cancel); end; class function TStreamUtils.Copy(Src, Dst: TStream; ProgressProc: TCopyStreamProgressProc): int64; begin { check TVCLStreamUtils.Copy if you don't want UI to freeze until operation is complete } result := Copy(Src, Dst, 0,0,ProgressProc); end; class function TStreamUtils.Copy(Src, Dst: TStream): int64; begin { check TVCLStreamUtils.Copy if you don't want UI to freeze until operation is complete } result := Copy(Src, Dst, 0,0,nil); end; class procedure TStreamUtils.StringToStream(const S: string; Dst: TStream; Encoding: TEncoding); var B: TArray<Byte>; begin if Encoding=nil then Encoding := TEncoding.UTF8; B := Encoding.GetBytes(S); if Length(B) > 0 then Dst.WriteBuffer(B[0], Length(B)); end; { TFileUtils } class procedure TFileUtils.CleanUpOldFiles(const AFileNamePattern: string; const AMaxAllowedTotalSize, AMaxAllowedCount: int64; AChanceToRun: Double); type TFileInfo = record Name: string; Size: int64; Age: TDateTime; end; var List: TList<TFileInfo>; Comparer: IComparer<TFileInfo>; TotalSize: Int64; TotalCount: Integer; FilePath: string; i: Integer; begin if (Random>AChanceToRun) or (AMaxAllowedTotalSize<0) and (AMaxAllowedCount<0) then Exit; List := TList<TFileInfo>.Create; try FilePath := ExtractFilePath(AFileNamePattern); EnumFiles(AFileNamePattern, procedure(const APath: string; const AFile: TSearchRec; var ABreak: Boolean) var R: TFileInfo; begin R.Name := AFile.Name; R.Size := AFile.Size; R.Age := AFile.TimeStamp; List.Add(R); end); Comparer := TDelegatedComparer<TFileInfo>.Create( function(const A,B: TFileInfo): Integer begin result := Sign(A.Age-B.Age); end); List.Sort(Comparer); TotalCount := List.Count; TotalSize := 0; for i := 0 to List.Count-1 do inc(TotalSize, List[i].Size); for i := 0 to List.Count-1 do if not ( (AMaxAllowedTotalSize>=0) and (TotalSize>AMaxAllowedTotalSize) or (AMaxAllowedCount>=0) and (TotalCount>AMaxAllowedCount) ) then Break else if System.SysUtils.DeleteFile(FilePath+List[i].Name) then begin Dec(TotalSize, List[i].Size); Dec(TotalCount); end; finally Sys.FreeAndNil(List); end; end; class function TFileUtils.CopyFile(const SrcFileName, DstFileName: string; out ErrorMessage: string; ProgressProc: TCopyFileProgressProc): boolean; var AutoFreeCollection: TAutoFreeCollection; CI: TCopyFileInfo; Src,Dst: TStream; begin { check TVCLFileUtils.CopyFile if you don''t want UI to freeze until operation is complete } try Result := True; Src := AutoFreeCollection.Add(TFileStream.Create(SrcFileName, fmOpenRead or fmShareDenyWrite)); Dst := AutoFreeCollection.Add(TFileStream.Create(DstFileName, fmCreate)); if not Assigned(ProgressProc) then TStreamUtils.Copy(Src, Dst) else begin CI.FileSize := Src.Size; CI.SrcFileName := SrcFileName; CI.DstFileName := DstFileName; TStreamUtils.Copy(Src, Dst, procedure(const Transferred: int64; var Cancel: boolean) begin CI.Copied := Transferred; ProgressProc(CI, Cancel); end); end; except on e: exception do begin Result := True; ErrorMessage := Format('Can''t copy file "%s" to "%s": %s', [SrcFileName, DstFileName, SysErrorMessage(GetLastError)]); end; end; end; class function TFileUtils.CopyFile(const SrcFileName, DstFileName: string; out ErrorMessage: string): boolean; begin { check TVCLFileUtils.CopyFile if you don''t want UI to freeze until operation is complete } result := CopyFile(SrcFileName, DstFileName, ErrorMessage, nil); end; class function TFileUtils.DeleteFile(const AFileName: string; out AErrorMessage: string): boolean; begin result := System.SysUtils.DeleteFile(AFileName); if not result then AErrorMessage := Format('Can''t delete file "%s" (%s)', [AFileName, SysErrorMessage(GetLastError)]); end; class function TFileUtils.RenameFile(const ASrcFileName, ADstFileName: string; out AErrorMessage: string): boolean; begin result := System.SysUtils.RenameFile(ASrcFileName, ADstFileName); if not result then AErrorMessage := Format('Can''t rename file "%s" to "%s" (%s)', [ASrcFileName, ADstFileName, SysErrorMessage(GetLastError)]); end; class procedure TFileUtils.EnumFiles(const AFileNamePattern: string; AOnfile: TDelegatedOnFile); var F: System.SysUtils.TSearchRec; B: Boolean; P: string; begin if System.SysUtils.FindFirst(AFileNamePattern, faAnyfile, F)=0 then try P := ExtractFilePath(AFileNamePattern); B := False; repeat if (F.Attr and faDirectory<>0) then Continue; AOnFile(P, F, B); until B or (System.SysUtils.FindNext(F)<>0); finally System.SysUtils.FindClose(F); end; end; class function TFileUtils.FileModeToString(AMode: Integer): string; const OpenMode : array[0..3] of string = ('fmOpenRead', 'fmOpenWrite', 'fmOpenReadWrite', 'unknown_open_mode'); begin {$WARN SYMBOL_PLATFORM OFF} result := '{' + OpenMode[AMode and 3]; if AMode and fmShareExclusive = fmShareExclusive then result := result + ', fmShareExclusive'; if AMode and fmShareDenyWrite = fmShareDenyWrite then result := result + ', fmShareDenyWrite'; {$IFDEF MSWINDOWS} if AMode and fmShareDenyRead = fmShareDenyRead then result := result + ', fmShareDenyRead'; {$EndIf} if AMode and fmShareDenyNone = fmShareDenyNone then result := result + ', fmShareDenyNone'; result := result + '}'; {$WARN SYMBOL_PLATFORM ON} end; class function TFileUtils.AccessAllowed(const AFileName: string; ADesiredAccess: word): boolean; var F: TFileStream; begin try F := TFileStream.Create(AFileName, ADesiredAccess); F.Free; result := True; except result := False; end; end; class procedure TFileUtils.Load<T>(const FileName: string; var Dst: TArray<T>); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead); try SetLength(Dst, Stream.Size div SizeOf(T)); if Length(Dst)>0 then Stream.ReadBuffer(Dst[0], Length(Dst)*SizeOf(T)); finally Stream.Free; end; end; class procedure TFileUtils.Save<T>(const FileName: string; const Src: TArray<T>; Index,Count: integer); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmCreate); try Stream.WriteBuffer(Src[Index], Count*SizeOf(T)); finally Stream.Free; end; end; class procedure TFileUtils.Save<T>(const FileName: string; const Src: TArray<T>); begin Save<T>(FileName, Src, 0, Length(Src)); end; class function TFileUtils.StringToFilename(const AStr: string): string; const DisabledNames: array[0..21] of string = ( 'CON', 'PRN', 'AUX', 'NUL', 'COM1','COM2','COM3','COM4','COM5','COM6','COM7','COM8','COM9', 'LPT1','LPT2','LPT3','LPT4','LPT5','LPT6','LPT7','LPT8','LPT9' ); DisabledChars = [0..31, Byte('<'), Byte('>'), Byte(':'), Byte('"'), Byte('/'), Byte('\'), Byte('|'), Byte('?'), Byte('*')]; var i: Integer; c: Char; Path,Name: string; begin { Trailing spaces. Windows allows filenames with spaces: " 1.txt", " 1 .txt", " 1 . txt" and even " .txt" but does not allow "1.txt ", so only trailing spaces are not allowed http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx "Do not end a file or directory name with a space or a period." } Path := ExtractFilePath(AStr); Name := TrimRight(ExtractFileName(AStr)); { Disabled chars: http://stackoverflow.com/questions/960772/how-can-i-sanitize-a-string-for-use-as-a-filename } result := ''; for i := Low(Name) to High(Name) do begin c := Name[i]; if (c<#127) and (Byte(c) in DisabledChars) then result := result + '%' + THex.Encode(c, SizeOf(c)) else result := result + c; end; { Disabled names } for i := Low(DisabledNames) to High(DisabledNames) do if AnsiSameText(result, DisabledNames[i]) then begin result := result + '_'; Break; end; result := Path + Name; end; procedure FindOpenFiles( const AFilesMask : string; AExceptions : TSet<string>; ARecursive : boolean; ADst : TList<string>); var Files,Subdirs: TStringDynArray; Dir,FileName,Subdir: string; begin try Dir := ExtractFilePath(AFilesMask); if not TDirectory.Exists(Dir) then Exit; Files := TDirectory.GetFiles(Dir, ExtractFileName(AFilesMask)); for FileName in Files do if not (FileName in AExceptions) and not TFileUtils.AccessAllowed(FileName) then ADst.Add(FileName); if ARecursive then begin Subdirs := TDirectory.GetDirectories(Dir); for Subdir in Subdirs do FindOpenFiles(Subdir + '\' + ExtractFileName(AFilesMask), AExceptions, True, ADst); end; except end; end; class function TFileUtils.GetOpenFiles(const AMasks,Exceptions: array of string; Recursive: boolean): TArray<string>; var FilesMask: string; Exc: TSet<string>; FoundFiles: TList<string>; begin FoundFiles := TList<string>.Create; try Exc.Add(Exceptions); for FilesMask in AMasks do FindOpenFiles(FilesMask, Exc, Recursive, FoundFiles); result := FoundFiles.ToArray; finally Sys.FreeAndNil(FoundFiles); end; end; class function TFileUtils.GetOpenFiles(const AMasks, Exceptions: array of string; Recursive: boolean; Delim: string): string; var FoundFiles: TArray<string>; i: Integer; begin FoundFiles := GetOpenFiles(AMasks, Exceptions, Recursive); if Length(FoundFiles)=0 then result := '' else result := FoundFiles[0]; for i := 1 to High(FoundFiles) do result := result + Delim + FoundFiles[i]; end; class function TFileUtils.GetSize(const AFileName: string): int64; var F: TSearchRec; begin if FindFirst(AFileName, faAnyfile, F)<>0 then result := 0 else begin result := F.Size; FindClose(F); end; end; class function TFileUtils.RemoveInvalidChars(const AFileName: string): string; var I: Integer; vPath, vFile: string; begin Result := ''; vPath := ExtractFilePath(AFileName); vFile := ExtractFileName(AFileName); for I := Low(vPath) to High(vPath) do if TPath.IsValidPathChar(vPath[I]) then Result := Result + vPath[I]; Result := IncludeTrailingPathDelimiter(Result); for I := Low(vFile) to High(vFile) do if TPath.IsValidFileNameChar(vFile[I]) then Result := Result + vFile[I]; end; class procedure TFileUtils.ExistsBuildCache(const CacheFolder: string; var Cache: TSet<string>; Recursive: boolean = True); var SearchOption: TSearchOption; begin Cache.Clear; if Recursive then SearchOption := TSearchOption.soAllDirectories else SearchOption := TSearchOption.soTopDirectoryOnly; if TDirectory.Exists(CacheFolder) then Cache.Add(TDirectory.GetFiles(IncludeTrailingPathDelimiter(TrimRight(CacheFolder)), '*.*', SearchOption)); end; class function TFileUtils.Exists(const FullFileName,CacheFolder: string; var Cache: TSet<string>): boolean; begin if not AnsiLowerCase(FullFileName).StartsWith(AnsiLowerCase(IncludeTrailingPathDelimiter(TrimRight(CacheFolder)))) then result := FileExists(FullFileName) else begin { We check files when they should exist, non existing file is very rare case. To make check robust/reliable we use two different aproaches in different time: - We check file in preloaded list of files. It is very fast, if file is here, then check is done. - If file is not in the list, then we check with FixeExists function. We report non existing file after double check only. } result := FullFileName in Cache; if not result then result := FileExists(FullFileName); end; end; { TIfThen } class function TIfThen.Get<T>(ACondition: Boolean; AValueTrue, AValueFalse: T): T; begin if ACondition then result := AValueTrue else result := AValueFalse; end; { TIndexBackEnumerator } procedure TIndexBackEnumerator.Init(AIndexFrom, AIndexTo: integer); begin Self := Default(TIndexBackEnumerator); FCurrentIndex := AIndexFrom; FToIndex := AIndexTo; end; function TIndexBackEnumerator.MoveNext: Boolean; begin result := FCurrentIndex>=FToIndex; if result then dec(FCurrentIndex); end; function TIndexBackEnumerator.GetCurrent: Integer; begin result := FCurrentIndex+1; end; { TTiming.TTotalStat } procedure TTiming.TTotalStat.Init(const ASpan: TTimeSpan; const ACalls: int64); begin Self := Default(TTiming.TTotalStat); Span := ASpan; Calls := ACalls; end; { TTiming } class destructor TTiming.DestroyClass; begin Sys.FreeAndNil(FTimeStack); Sys.FreeAndNil(FTotalTimes); end; class function TTiming.GetTimeStack: TStack<TStopwatch>; begin if FTimeStack=nil then FTimeStack := TStack<TStopwatch>.Create; result := FTimeStack; end; class function TTiming.GetTotalTimes: TDictionary<string, TTotalStat>; begin if FTotalTimes=nil then FTotalTimes := TDictionary<string, TTotalStat>.Create(TOrdinalIStringComparer.Ordinal); result := FTotalTimes; end; class procedure TTiming.Start; begin TimeStack.Push(TStopwatch.StartNew); end; class function TTiming.Stop: TTimeSpan; begin Result := TimeStack.Pop.Elapsed; end; class function TTiming.Stop(const OpId: string; out ATotalStat: TTotalStat): TTimeSpan; begin result := Stop; if not TotalTimes.TryGetValue(OpId, ATotalStat) then ATotalStat.Init(TTimeSpan.Create(0), 0); ATotalStat.Span := ATotalStat.Span + result; inc(ATotalStat.Calls); TotalTimes.AddOrSetValue(OpId, ATotalStat); end; class function TTiming.StopAndGetCaption(const OpId, Msg: string): string; var OpTime: TTimeSpan; TotalStat: TTotalStat; begin OpTime := Stop(OpId, TotalStat); result := Format('%s (%s): %.2f sec (total: %.2f sec; calls: %d)', [ OpId, Msg, OpTime.TotalSeconds, TotalStat.Span.TotalSeconds, TotalStat.Calls]); end; class function TTiming.StopAndGetCaption(const OpId: string): string; var OpTime: TTimeSpan; TotalStat: TTotalStat; begin OpTime := Stop(OpId, TotalStat); result := Format('%s: %.2f sec (total: %.2f sec; calls: %d)', [ OpId, OpTime.TotalSeconds, TotalStat.Span.TotalSeconds, TotalStat.Calls]); end; { TTimeOut } procedure TTimeOut.Init; begin Self := Default(TTimeOut); end; procedure TTimeOut.Start(AMaxTimeForOp: TDateTime; ACheckPeriod: integer = 0); begin FMaxTimeForOp:= AMaxTimeForOp; FCheckPeriod := ACheckPeriod; Restart; end; procedure TTimeOut.StartSec(AMaxTimeForOpSec: double; ACheckPeriod: integer = 0); begin Start(AMaxTimeForOpSec/SecsPerDay, ACheckPeriod); end; procedure TTimeOut.StartInfinite; begin Start(-1); { negative MaxTimeForOp means that .TimedOut is constantly False } end; procedure TTimeOut.Restart; begin FStartTime := Now; FCounter := FCheckPeriod; FOpTimedOut := FMaxTimeForOp = 0; end; function TTimeOut.GetTimedOut: Boolean; begin { negative value = infinite (never timed out) } if FMaxTimeForOp < 0 then Result := False else { already timed out } if FOpTimedOut then Result := True else { check for timeout } begin Dec(FCounter); if FCounter > 0 then Result := False else begin FCounter := FCheckPeriod; Result := Now-FStartTime>FMaxTimeForOp; FOpTimedOut := Result; end; end; end; { TCurrencyUtils } class function TCurrencyUtils.ToString(const Value: currency; FractionalPart: boolean): string; begin result := FormatCurr( IfThen(FractionalPart, '#,##', '#,'), Value); end; { TPIWriter } constructor TPIWriter.Create(ADst: TStream); begin inherited Create; Writer := TWriter.Create(ADst, 4096); end; destructor TPIWriter.Destroy; begin Sys.FreeAndNil(Writer); inherited; end; procedure TPIWriter.Write(const Value: Int16); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt16); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Int32); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Char); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Int8); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt8); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Extended); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Double); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Int64); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt32); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: Single); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Value: UInt64); begin Writer.WriteVar(Value, SizeOf(Value)); end; procedure TPIWriter.Write(const Buf; Count: integer); begin Writer.Write(Buf, Count); end; procedure TPIWriter.Write(const Value: TBytes); var i: Integer; begin i := Length(Value); Write(i); if i>0 then Write(Value[0], i); end; procedure TPIWriter.Write(const Value: string); begin Write(TEncoding.UTF8.GetBytes(Value)); end; { TPIReader } constructor TPIReader.Create(ASrc: TStream); begin inherited Create; Reader := TReader.Create(ASrc, 4096); end; destructor TPIReader.Destroy; begin Sys.FreeAndNil(Reader); inherited; end; procedure TPIReader.Read(out Value: Int16); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt16); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Int32); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Char); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Int8); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt8); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Single); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Double); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Extended); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt32); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: Int64); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(out Value: UInt64); begin Reader.ReadVar(Value, SizeOf(Value)); end; procedure TPIReader.Read(var Buf; Count: integer); begin Reader.Read(Buf, Count); end; procedure TPIReader.Read(out Value: TBytes); var i: integer; begin Read(i); SetLength(Value, i); if i>0 then Read(Value[0], i); end; procedure TPIReader.Read(out Value: string); var Bytes: TBytes; begin Read(Bytes); Value := TEncoding.UTF8.GetString(Bytes); end; { TBox<T> } procedure TBox<T>.Init; begin Self := Default(TBox<T>); end; procedure TBox<T>.Init(const AValue: T); begin Self := Default(TBox<T>); Value := AValue; end; procedure TBox<T>.Clear; begin Self := Default(TBox<T>); end; function TBox<T>.GetValue: T; begin if Empty then raise EInvalidOperation.Create('No value to read'); result := FValue; end; procedure TBox<T>.SetValue(const AValue: T); begin FValue := AValue; FHasValue := '1'; end; function TBox<T>.GetEmpty: boolean; begin result := FHasValue=''; end; function TBox<T>.GetPointer: PT; begin result := @FValue; end; class operator TBox<T>.GreaterThan(const Left, Right: TBox<T>): Boolean; begin { we have LessThan implementation already } Result := Right < Left; end; class operator TBox<T>.GreaterThanOrEqual(const Left, Right: TBox<T>): Boolean; begin { we have LessThanOrEqual implementation already } result := Right <= Left; end; class operator TBox<T>.Equal(const Left, Right: TBox<T>): Boolean; var Comparer: IEqualityComparer<T>; begin if Left.Empty or Right.Empty then Result := Left.Empty = Right.Empty else begin Comparer := TComparerUtils.DefaultEqualityComparer<T>; Result := Comparer.Equals(Left.Value, Right.Value); end; end; class operator TBox<T>.Equal(const Left: TBox<T>; const Right: T): Boolean; var Comparer: IEqualityComparer<T>; begin if Left.Empty then result := False else begin Comparer := TComparerUtils.DefaultEqualityComparer<T>; Result := Comparer.Equals(Left.Value, Right); end end; class operator TBox<T>.Equal(const Left: T; const Right: TBox<T>): Boolean; begin { We have implementation for (Left: TBox<T>; Right: T) already. } Result := Right=Left; end; function TBox<T>.Extract: T; begin Assert(not Empty); result := Value; Clear; end; class operator TBox<T>.NotEqual(const Left, Right: TBox<T>): Boolean; begin result := not (Left=Right); end; class operator TBox<T>.Implicit(const AValue: T): TBox<T>; begin result.Init(AValue); end; class operator TBox<T>.Implicit(const AValue: TBox<T>): T; begin result := AValue.Value; end; class operator TBox<T>.LessThan(const Left, Right: TBox<T>): Boolean; var C: IComparer<T>; begin { Null < any real value } if Left.Empty then result := not Right.Empty else if Right.Empty then Result := False else begin C := TComparerUtils.DefaultComparer<T>; result := C.Compare(Left.Value, Right.Value) < 0; end; end; class operator TBox<T>.LessThanOrEqual(const Left, Right: TBox<T>): Boolean; var C: IComparer<T>; begin { Null < any real value } if Left.Empty then Result := True else if Right.Empty then Result := False else begin C := TComparerUtils.DefaultComparer<T>; result := C.Compare(Left.Value, Right.Value) <= 0; end; end; class operator TBox<T>.Add(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Add(Left, Right); end; class operator TBox<T>.Divide(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Divide(Left, Right); end; class operator TBox<T>.IntDivide(Left, Right: TBox<T>): TBox<T>; begin result := Left / Right; end; class operator TBox<T>.Subtract(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Subtract(Left, Right); end; class operator TBox<T>.Multiply(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Multiply(Left, Right); end; class operator TBox<T>.Negative(Value: TBox<T>): TBox<T>; begin if Value.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Negative(Value); end; { TRLE } class function TRLE.MaxEncodedSize(ASrcSize: cardinal): cardinal; begin result := ASrcSize + ASrcSize div 64 + 16; end; (* RunLengthEncoding according to PDF specification. Stream of bytes encoded as stream of packets. The packet contains ocntrol byte (length) and optional string of bytes. Allowed values for control byte: 0..127: next N+1 bytes (1..128) should be writtens as is 128: EOF (decoding finished) 129..255: next byte should be repeated 257-N times (2..128) At every step we have current state described in following variables: S[1.2...N][1.2..M] N-number of uncompressable bytes M-number of items in sequance of equal (potentially compressable) *) class function TRLE.Encode(const ASrc; ASrcSize: cardinal; var ADest): cardinal; var Src, Dst: PByte; M,N: cardinal; PrevChar: byte; { 0 1 [2 3 4] [5 6] (7) N=3 M=2 CurPos } procedure COPY_N; begin assert((N>=1) and (N<=128)); inc(result,N+1); Dst^ := N-1; { copy N (1..128) bytes as is } inc(Dst); system.move((Src-M-N)^, Dst^, N); inc(Dst, N); end; { M=0! } procedure COPY_128; begin assert(N>=128); inc(result,129); Dst^ := 127; { copy N (1..128) bytes as is } inc(Dst); system.move((Src-N)^, Dst^, 128); inc(Dst, 128); dec(N, 128); end; { 257-x=M -> x=257-M } procedure PACK_M; begin assert((M>=2) and (M<=128)); inc(result,2); dst^ := 257-M; { copy folowing byte 257-x times } inc(dst); dst^ := PrevChar; inc(dst); end; function Init:longword; begin //ADest := AllocMem(ASrcSize + ASrcSize div 64 + 16); Src := @ASrc; Dst := @ADest; result := 0; // too short chain if ASrcSize<3 then begin result := ASrcSize; if result>0 then begin inc(result); // + 1 byte command dst^ := ASrcSize-1; // command (copy ASourceCount bytes) inc(dst); system.move(Src^, Dst^, ASrcSize); inc(dst, ASrcSize); end; // end of data inc(result); dst^ := 128; inc(dst); exit; end; end; procedure Finish; begin // short repeated chain we join to "as is" chain (M must be greater than 1) if M<2 then begin inc(N, M); if N>128 then COPY_128; M := 0; end; // out "as is" chain if N>0 then begin COPY_N; N := 0; end; // out "repeated" chain if M>0 then begin PACK_M; M := 0; end; // out "end of data" marker inc(result); dst^ := 128; inc(dst); end; begin // initialize result := Init; if result>0 then exit; // read src N := 0; M := 0; repeat if M=0 then begin PrevChar := Src^; inc(M); end else begin if Src^=PrevChar then inc(M); // two folowing conditions never met at same time if (Src^<>PrevChar) or (M=128) then if N>0 then if M>=4 then if M=128 then begin // N>0, M=128, Src^=PrevChar inc(Src); COPY_N; PACK_M; dec(Src); N := 0; M := 0; end else begin // N>0, M=[4..127], Src^<>PrevChar COPY_N; PACK_M; N := 0; M := 1; PrevChar := Src^; end else begin // N>0, M<4, Src^<>PrevChar inc(N,M); if N>128 then COPY_128; M := 1; PrevChar := Src^; end else if M>=3 then begin if M=128 then begin // N=0, M=128, Src^=PrevChar inc(Src); PACK_M; dec(Src); M := 0; end else begin // N=0, M=[3..127], Src^<>PrevChar PACK_M; M := 1; PrevChar := Src^; end end else begin // N=0, M=[1..2], Src^<>PrevChar N := M; M := 1; PrevChar := Src^; end end; dec(ASrcSize); inc(Src); until ASrcSize=0; // finish uncompleted chain finish; // assert(result<(ASrcSize + ASrcSize div 64 + 16)); end; class function TRLE.DecodedSize(const ASrc; APackedSize: cardinal): cardinal; var src: PByte; n: byte; begin Src := @ASrc; result := 0; while APackedSize>0 do begin n := Src^; inc(Src); dec(APackedSize); // copy if n<128 then begin inc(n); if APackedSize<n then raise exception.create('RLDecode error'); inc(result, n); inc(Src, n); dec(APackedSize, n); continue; end; // stop if n=128 then break; // repeat n := 257-n; if APackedSize<1 then raise exception.create('RLDecode error'); inc(result, n); inc(Src); dec(APackedSize); end; end; class procedure TRLE.Decode(const ASrc; APackedSize: cardinal; var ADest; AUnpackedSize: cardinal); var src,dst: PByte; n: byte; begin Src := @ASrc; Dst := @ADest; while APackedSize>0 do begin n := Src^; inc(Src); dec(APackedSize); // copy if n<128 then begin inc(n); if (APackedSize<n) or (AUnpackedSize<n) then raise exception.create('RLDecode error'); system.move(Src^, dst^, n); dec(AUnpackedSize, n); inc(Src, n); dec(APackedSize, n); inc(dst, n); continue; end; // stop if n=128 then break; // repeat n := 257-n; if (APackedSize<1) or (AUnpackedSize<1) then raise exception.create('RLDecode error'); FillChar(dst^, n, Src^); dec(AUnpackedSize, n); inc(Src); dec(APackedSize); inc(dst, n); end; if (AUnpackedSize<>0) then raise exception.create('RLDecode error'); end; { TComponentUtils } class function TComponentUtils.ForEach(AStart: TComponent; ACallback: TProcVar1<TComponent, Boolean>): Boolean; var i: Integer; begin if AStart<>nil then begin { check if canceled by callback function } result := False; ACallback(AStart, result); if result then Exit(False); { check if any subsearch canceled } for i := AStart.ComponentCount-1 downto 0 do if not ForEach(AStart.Components[i], ACallback) then Exit(False); end; result := True; end; class function TComponentUtils.Copy<T>(Src: T): T; var MemoryStream: TMemoryStream; begin MemoryStream := TMemoryStream.Create; try MemoryStream.WriteComponent(Src); MemoryStream.Seek(0, TSeekOrigin.soBeginning); Result := MemoryStream.ReadComponent(nil) as T; finally MemoryStream.free; end; end; class procedure TComponentUtils.ForEach(AStart: TComponent; ACallback: TProc<TComponent>); var i: Integer; begin if AStart=nil then Exit; ACallback(AStart); for i := AStart.ComponentCount-1 downto 0 do ForEach(AStart.Components[i], ACallback); end; class function TComponentUtils.ForEach<T>(AStart: TComponent; ACallback: TProcVar1<T, Boolean>): Boolean; begin result := ForEach(AStart, procedure(C: TComponent; var Break: boolean) begin if C is T then ACallback(T(C), Break); end); end; class procedure TComponentUtils.ForEach<T>(AStart: TComponent; ACallback: TProc<T>); begin ForEach(AStart, procedure(C: TComponent) begin if C is T then ACallback(T(C)); end); end; class function TComponentUtils.GetAll(AStart: TComponent): TArray<TComponent>; var V: TArr<TComponent>; begin V.Clear; V.Capacity := AStart.ComponentCount; ForEach(AStart, procedure(C: TComponent) begin V.Add(C); end); V.TrimExcess; Result := V.Items; end; class function TComponentUtils.GetAll<T>(AStart: TComponent): TArray<T>; var V: TArr<T>; begin V.Clear; V.Capacity := AStart.ComponentCount; ForEach(AStart, procedure(C: TComponent) begin if C is T then V.Add(T(C)); end); V.TrimExcess; result := V.Items; end; class function TComponentUtils.GetUniqueName: string; begin result := GuidToString(TGUIDUtils.GetNew).Replace('-','', [rfReplaceAll]); result := 'G' + result.Substring(1, Length(result)-2); end; { TCustomHash } class function TCustomHash.Encode(const Buf; ByteBufSize: integer): TBytes; begin result := DoEncode(Buf, ByteBufSize); end; class function TCustomHash.Encode(S: TStream): TBytes; begin result := DoEncode(S); end; class function TCustomHash.Encode(const S: TBytes; StartIndex,Count: integer): TBytes; begin Assert((StartIndex >= 0) and (StartIndex + Count <= Length(S))); if Count <= 0 then result := DoEncode(nil^, 0) else result := DoEncode(S[StartIndex], Count); end; class function TCustomHash.Encode(const S: TBytes): TBytes; begin result := Encode(S, 0, Length(S)); end; class function TCustomHash.Encode(const S: string): TBytes; begin if Length(S)=0 then result := DoEncode(nil^, 0) else result := DoEncode(S[Low(S)], length(S)*SizeOf(S[Low(S)])); end; {$If Defined(MSWindows)} class function TCustomHash.EncodeAnsiString(const S: AnsiString): TBytes; begin if Length(S)=0 then result := DoEncode(nil^, 0) else result := DoEncode(S[Low(S)], length(S)*SizeOf(S[Low(S)])); end; {$EndIf} class function TCustomHash.EncodeFile(const AFileName: string): TBytes; var S: TFileStream; begin S := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); try Result := DoEncode(S); finally S.Free; end; end; class function TCustomHash.Hash32ToBytes(Hash: Cardinal): TBytes; begin SetLength(Result, 4); PCardinal(@Result[0])^ := System.Hash.THash.ToBigEndian(Hash); end; class procedure TCustomHash.Init(out Hash: TArray<byte>); begin DoInit(Hash); end; class procedure TCustomHash.Update(const Value; ValueByteSize: integer; var Hash: THashData); begin DoUpdate(Value, ValueByteSize, Hash); end; class procedure TCustomHash.Update(const Value: integer; var Hash: THashData); begin DoUpdate(Value, SizeOf(Value), Hash); end; class procedure TCustomHash.Update(const Value: double; var Hash: THashData); begin DoUpdate(Value, SizeOf(Value), Hash); end; class procedure TCustomHash.Update(const Value: TArray<byte>; var Hash: THashData); begin { Length must be included in hash, otherwise arrays [a, ab] and [aa, b] will produce same hash } Update(Length(Value), Hash); if Length(Value) > 0 then DoUpdate(Value[0], Length(Value), Hash); end; class procedure TCustomHash.Update(const Value: string; var Hash: THashData); begin { Length must be included in hash, otherwise arrays ["a", "ab"] and ["aa", "b"] will produce same hash } Update(Length(Value), Hash); if Value <> '' then DoUpdate(Value[Low(Value)], Length(Value)*SizeOf(Char), Hash); end; class function TCustomHash.Done(var Hash: TArray<byte>): TBytes; begin result := DoDone(Hash); end; { TMD5 } class function THashUtils.MD5.DoEncode(const Buf; ByteBufSize: integer): TBytes; var Hash: THashMD5; begin Hash := THashMD5.Create; { Create may have params and is not equal to Reset } Hash.Update(Buf, ByteBufSize); Result := Hash.HashAsBytes; end; class function THashUtils.MD5.DoEncode(S: TStream): TBytes; var Reader: TStreamUtils.TReader; Hash: THashMD5; begin Reader.Init(S, False, StreamingBufSize, True); Hash := THashMD5.Create; { Create may have params and is not equal to Reset } while Reader.ReadNext do Hash.Update(Reader.Bytes, Reader.Count); Result := Hash.HashAsBytes; end; class procedure THashUtils.MD5.DoInit(out Hash: THashData); begin SetLength(Hash, SizeOf(THashMD5)); THashMD5((@Hash[0])^) := THashMD5.Create; end; class procedure THashUtils.MD5.DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); begin Assert(Length(Hash)=SizeOf(THashMD5)); THashMD5((@Hash[0])^).Update(Buf, ByteBufSize); end; class function THashUtils.MD5.DoDone(var Hash: THashData): TBytes; begin Assert(Length(Hash)=SizeOf(THashMD5)); result := THashMD5((@Hash[0])^).HashAsBytes; THashMD5((@Hash[0])^) := Default(THashMD5); SetLength(Hash, 0); end; { THashUtils.SHA1 } class function THashUtils.SHA1.DoEncode(const Buf; ByteBufSize: integer): TBytes; var Hash: THashSHA1; begin Hash := THashSHA1.Create; Hash.Update(Buf, ByteBufSize); Result := Hash.HashAsBytes; end; class function THashUtils.SHA1.DoEncode(S: TStream): TBytes; var Reader: TStreamUtils.TReader; Hash: THashSHA1; begin Reader.Init(S, False, StreamingBufSize, True); Hash := THashSHA1.Create; while Reader.ReadNext do Hash.Update(Reader.Bytes, Reader.Count); Result := Hash.HashAsBytes; end; class procedure THashUtils.SHA1.DoInit(out Hash: THashData); begin SetLength(Hash, SizeOf(THashSHA1)); THashSHA1((@Hash[0])^) := THashSHA1.Create; end; class procedure THashUtils.SHA1.DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); begin Assert(Length(Hash)=SizeOf(THashSHA1)); THashSHA1((@Hash[0])^).Update(Buf, ByteBufSize); end; class function THashUtils.SHA1.DoDone(var Hash: THashData): TBytes; begin Assert(Length(Hash)=SizeOf(THashSHA1)); result := THashSHA1((@Hash[0])^).HashAsBytes; THashSHA1((@Hash[0])^) := Default(THashSHA1); SetLength(Hash, 0); end; { THashUtils.SHA2 } class function THashUtils.SHA2.DoEncode(const Buf; ByteBufSize: integer): TBytes; var Hash: THashSHA2; begin Hash := THashSHA2.Create; Hash.Update(Buf, ByteBufSize); Result := Hash.HashAsBytes; end; class function THashUtils.SHA2.DoEncode(S: TStream): TBytes; var Reader: TStreamUtils.TReader; Hash: THashSHA2; begin Reader.Init(S, False, StreamingBufSize, True); Hash := THashSHA2.Create; while Reader.ReadNext do Hash.Update(Reader.Bytes, Reader.Count); Result := Hash.HashAsBytes; end; class procedure THashUtils.SHA2.DoInit(out Hash: THashData); begin SetLength(Hash, SizeOf(THashSHA2)); THashSHA2((@Hash[0])^) := THashSHA2.Create; end; class procedure THashUtils.SHA2.DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); begin Assert(Length(Hash)=SizeOf(THashSHA2)); THashSHA2((@Hash[0])^).Update(Buf, ByteBufSize); end; class function THashUtils.SHA2.DoDone(var Hash: THashData): TBytes; begin Assert(Length(Hash)=SizeOf(THashSHA2)); result := THashSHA2((@Hash[0])^).HashAsBytes; THashSHA2((@Hash[0])^) := Default(THashSHA2); SetLength(Hash, 0); end; { THashUtils.CRC32 } class function THashUtils.CRC32.DoEncode(const Buf; ByteBufSize: integer): TBytes; var Crc: Cardinal; begin Crc := System.ZLib.crc32(0, nil, 0); Crc := System.ZLib.crc32(Crc, @Buf, ByteBufSize); Result := Hash32ToBytes(Crc); end; class function THashUtils.CRC32.DoEncode(S: TStream): TBytes; var Reader: TStreamUtils.TReader; Crc: Cardinal; begin Reader.Init(S, False, StreamingBufSize, True); Crc := System.ZLib.crc32(0, nil, 0); while Reader.ReadNext do Crc := System.ZLib.crc32(Crc, @Reader.Bytes[0], Reader.Count); Result := Hash32ToBytes(Crc); end; class procedure THashUtils.CRC32.DoInit(out Hash: THashData); begin SetLength(Hash, SizeOf(cardinal)); cardinal((@Hash[0])^) := System.ZLib.crc32(0, nil, 0); end; class procedure THashUtils.CRC32.DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); begin Assert(Length(Hash)=SizeOf(cardinal)); cardinal((@Hash[0])^) := System.ZLib.crc32(cardinal((@Hash[0])^), @Buf, ByteBufSize); end; class function THashUtils.CRC32.DoDone(var Hash: THashData): TBytes; begin Assert(Length(Hash)=SizeOf(cardinal)); Result := Hash32ToBytes(cardinal((@Hash[0])^)); cardinal((@Hash[0])^) := Default(cardinal); SetLength(Hash, 0); end; { THashUtils.Adler32 } class function THashUtils.Adler32.DoEncode(const Buf; ByteBufSize: integer): TBytes; var Crc: Cardinal; begin Crc := System.ZLib.adler32(0, nil, 0); Crc := System.ZLib.adler32(Crc, @Buf, ByteBufSize); Result := Hash32ToBytes(Crc); end; class function THashUtils.Adler32.DoEncode(S: TStream): TBytes; var Reader: TStreamUtils.TReader; Crc: Cardinal; begin Reader.Init(S, False, StreamingBufSize, True); Crc := System.ZLib.adler32(0, nil, 0); while Reader.ReadNext do Crc := System.ZLib.adler32(Crc, @Reader.Bytes[0], Reader.Count); Result := Hash32ToBytes(Crc); end; class procedure THashUtils.Adler32.DoInit(out Hash: THashData); begin SetLength(Hash, SizeOf(cardinal)); cardinal((@Hash[0])^) := System.ZLib.adler32(0, nil, 0); end; class procedure THashUtils.Adler32.DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); begin Assert(Length(Hash)=SizeOf(cardinal)); cardinal((@Hash[0])^) := System.ZLib.adler32(cardinal((@Hash[0])^), @Buf, ByteBufSize); end; class function THashUtils.Adler32.DoDone(var Hash: THashData): TBytes; begin Assert(Length(Hash)=SizeOf(cardinal)); Result := Hash32ToBytes(cardinal((@Hash[0])^)); cardinal((@Hash[0])^) := Default(cardinal); SetLength(Hash, 0); end; { THashUtils.BobJenkins32 } class function THashUtils.BobJenkins32.DoEncode(const Buf; ByteBufSize: integer): TBytes; var h: THashBobJenkins; begin h := THashBobJenkins.Create; h.Update(Buf, ByteBufSize); Result := h.HashAsBytes; end; class function THashUtils.BobJenkins32.DoEncode(S: TStream): TBytes; var Reader: TStreamUtils.TReader; Hash: THashBobJenkins; begin Reader.Init(S, False, StreamingBufSize, True); Hash := THashBobJenkins.Create; while Reader.ReadNext do Hash.Update(Reader.Bytes, Reader.Count); Result := Hash.HashAsBytes; end; class procedure THashUtils.BobJenkins32.DoInit(out Hash: THashData); begin SetLength(Hash, SizeOf(THashBobJenkins)); THashBobJenkins((@Hash[0])^) := THashBobJenkins.Create; end; class procedure THashUtils.BobJenkins32.DoUpdate(const Buf; ByteBufSize: integer; var Hash: THashData); begin Assert(Length(Hash)=SizeOf(THashBobJenkins)); THashBobJenkins((@Hash[0])^).Update(Buf, ByteBufSize); end; class function THashUtils.BobJenkins32.DoDone(var Hash: THashData): TBytes; begin Assert(Length(Hash)=SizeOf(THashBobJenkins)); Result := THashBobJenkins((@Hash[0])^).HashAsBytes; THashBobJenkins((@Hash[0])^) := Default(THashBobJenkins); SetLength(Hash, 0); end; { THashUtils } class function THashUtils.Mix(const HashA, HashB, HashC: integer): integer; begin result := Mix(Mix(HashA, HashB), HashC); end; class function THashUtils.Mix(const HashA, HashB: integer): integer; begin result := (HashA*1103515245 + 12345) xor HashB; end; class function THashUtils.Mix(const HashA, HashB: TBytes): TBytes; var V,L1,L2,LR: Integer; Src1,Src2,Dst: pointer; begin L1 := Length(HashA); L2 := Length(HashB); LR := Max(L1, L2); SetLength(result, LR); if LR = 0 then Exit; Dst := @result[0]; if L1>0 then Src1 := @HashA[0] else Src1 := nil; if L2>0 then Src2 := @HashB[0] else Src2 := nil; V := 0; while LR >= SizeOf(integer) do begin { read from HashA } if L1 >= SizeOf(integer) then begin V := (V*1103515245 + 12345) xor integer(Src1^); inc(PByte(Src1), SizeOf(integer)); dec(L1, SizeOf(integer)); end else while L1 > 0 do begin V := (V*1103515245 + 12345) xor PByte(Src1)^; inc(PByte(Src1)); dec(L1); end; { read from HashB } if L2 >= SizeOf(integer) then begin V := (V*1103515245 + 12345) xor integer(Src2^); inc(PByte(Src2), SizeOf(integer)); dec(L2, SizeOf(integer)); end else while L2 > 0 do begin V := (V*1103515245 + 12345) xor PByte(Src2)^; inc(PByte(Src2)); dec(L2); end; integer(Dst^) := V; dec(LR, SizeOf(integer)); end; while LR > 0 do begin if L1 > 0 then begin V := (V*1103515245 + 12345) xor byte(Src1^); inc(PByte(Src1)); dec(L1); end; if L2 > 0 then begin V := (V*1103515245 + 12345) xor byte(Src2^); inc(PByte(Src2)); dec(L2); end; Byte(Dst^) := V; dec(LR); end; end; class function THashUtils.HashToString(const AHash: TBytes): string; begin Result := THex.Encode(AHash); end; class function THashUtils.GetHash32(const Hash: TBytes): integer; begin if Length(Hash) = 0 then result := 0 else if Length(Hash) = 4 then result := (integer(Hash[0]) shl 24) or (integer(Hash[1]) shl 16) or (integer(Hash[2]) shl 8) or (integer(Hash[3])) else result := GetHash32(CRC32.Encode(Hash,0,Length(Hash))); end; class function THashUtils.GetHash24(const Hash: TBytes): integer; begin if Length(Hash) = 0 then result := 0 else if Length(Hash) = 4 then result := (integer(Hash[0]) shl 16) or (integer(Hash[1]) shl 8) or (integer(Hash[2]) xor integer(Hash[3])) else result := GetHash24(CRC32.Encode(Hash,0,Length(Hash))); end; class function THashUtils.GetHash16(const Hash: TBytes): integer; begin if Length(Hash) = 0 then result := 0 else if Length(Hash) = 4 then result := ((integer(Hash[0]) xor integer(Hash[1])) shl 8) or (integer(Hash[2]) xor integer(Hash[3])) else result := GetHash16(CRC32.Encode(Hash,0,Length(Hash))); end; class function THashUtils.Mix(const Hashes: array of integer): integer; var I: Integer; begin result := 0; for I := Low(Hashes) to High(Hashes) do result := Mix(result, Hashes[I]); end; class function THashUtils.Mix(const Hashes: array of TBytes): TBytes; var I: Integer; begin SetLength(result, 0); for I := Low(Hashes) to High(Hashes) do result := Mix(result, Hashes[I]); end; { TBuffer } procedure TBuffer.Clear; begin Size := 0; Capacity := Size; end; function TBuffer.GetCapacity: integer; begin result := Length(FData); end; function TBuffer.GetCurrentData: pointer; begin result := @FData[Position]; end; function TBuffer.GetEmpty: Boolean; begin result := Size=0; end; function TBuffer.GetEOF: boolean; begin result := Position >= Size; end; function TBuffer.GetLeft: integer; begin result := Size-Position; end; procedure TBuffer.SetText(const Value: string); begin Clear; Write(Value); Position := 0; end; function TBuffer.GetText: string; var P: Integer; begin P := Position; Position := 0; Read(Result, Size div SizeOf(Char)); Position := P; end; procedure TBuffer.Init; begin Self := Default(TBuffer); end; procedure TBuffer.LoadFromFile(const FileName: string); begin TFileUtils.Load<Byte>(FileName, FData); FSize := Length(FData); FPosition := 0; end; procedure TBuffer.SaveToFile(const FileName: string); begin TFileUtils.Save<Byte>(FileName, FData, 0,Size); end; procedure TBuffer.SetLeft(Value: integer); begin Size := Position + Value; end; procedure TBuffer.SetCapacity(Value: integer); begin Assert(Value >= Size); SetLength(FData, Value); end; procedure TBuffer.CheckCapacity(MinCapacity: integer); begin if Capacity < MinCapacity then Capacity := TFun.Max(MinCapacity, Capacity shl 1, 16); end; procedure TBuffer.SetSize(Value: integer); begin CheckCapacity(Value); FSize := Value; FPosition := Max(Min(FPosition, FSize), 0); end; procedure TBuffer.TrimExcess; begin Capacity := Size; end; procedure TBuffer.Read(var Dst; ByteCount: integer); begin Assert(Position + ByteCount <= Size); System.Move(FData[Position], Dst, ByteCount); inc(FPosition, ByteCount); end; procedure TBuffer.Read(var Dst: string; DstCharOffset, CharCount: integer); begin Read(Dst[DstCharOffset+Low(Dst)], CharCount*SizeOf(Char)); end; procedure TBuffer.Read(var Dst: string; CharCount: integer); begin SetLength(Dst, CharCount); Read(Dst[Low(Dst)], CharCount*SizeOf(Char)); end; procedure TBuffer.Write(const Src; ByteCount: integer); begin CheckCapacity(Position + ByteCount); System.Move(Src, FData[Position], ByteCount); inc(FPosition, ByteCount); if FPosition > FSize then FSize := FPosition; end; procedure TBuffer.Write(const Src: string; CharOffset,CharCount: integer); begin if CharCount<>0 then Write(Src[CharOffset+Low(Src)], CharCount*SizeOf(Char)); end; procedure TBuffer.Write(const Src: string); begin if Src<>'' then Write(Src[Low(Src)], Length(Src)*SizeOf(Char)); end; procedure TBuffer.Cut(Start, Len: integer); begin Len := TArrayUtils.Cut<byte>(FData, Size, Start, Len); dec(FSize, Len); if Position > Size then Position := Size; end; function TBuffer.Slice(Start, Len: integer): TArray<byte>; begin result := TArrayUtils.Slice<byte>(FData, Size, Start, Len); end; procedure TBuffer.SetData(AData: TArray<Byte>); begin FData := AData; FSize := Length(FData); FPosition := 0; end; { TOutOfScopeAction.TOnDestroyRunner } type TOnDestroyRunner = class private FProc: TProc; constructor Create(AProc: TProc); destructor Destroy; override; end; constructor TOnDestroyRunner.Create(AProc: TProc); begin FProc := AProc; end; destructor TOnDestroyRunner.Destroy; begin if Assigned(FProc) then FProc; inherited; end; { TOutOfScopeAction } procedure TOutOfScopeAction.Init(AProc: TProc); begin Self := Default(TOutOfScopeAction); FProc := TInterfacedObject<TObject>.Create(TOnDestroyRunner.Create(AProc)); end; { TOutOfScopeAction<T> } procedure TOutOfScopeAction<T>.Init(AProc: TProc<T>; AValue: T); begin Self := Default(TOutOfScopeAction<T>); FProc := TInterfacedObject<TRunOnDestroy>.Create(TRunOnDestroy.Create(AProc, AValue)); end; { TOutOfScopeAction<T>.TRunOnDestroy } constructor TOutOfScopeAction<T>.TRunOnDestroy.Create(AProc: TProc<T>; AValue: T); begin FProc := AProc; FValue := AValue; end; destructor TOutOfScopeAction<T>.TRunOnDestroy.Destroy; begin FProc(FValue); inherited; end; { TEventUtils } class function TEventUtils.IsSameHandler(const A, B: TNotifyEvent): Boolean; begin result := CompareMem(@A, @B, SizeOF(TNotifyEvent)); end; class function TEventUtils.Equal<T>(const A, B: T): boolean; begin result := CompareMem(@A, @B, SizeOF(T)); end; class function TEventUtils.IsSameHandler(const A, B: TActionEvent): Boolean; begin result := CompareMem(@A, @B, SizeOF(TActionEvent)); end; { TFun } class procedure TFun.Clear<T>(var R: T); begin R := Default(T); end; class procedure TFun.Exchange<T>(var A, B: T); var C: T; begin C := A; A := B; B := C; end; class procedure TFun.FreeAndNil<T>(var Obj: T); begin {$IF Defined(AUTOREFCOUNT)} Obj := nil; {$ELSE} { unlike SysUtils.FreeAndNil we call destructor first and only after set to nil } if Obj<>nil then begin Obj.Destroy; Obj := nil; end; {$ENDIF} end; class function TFun.GetPtr(const Values: TArray<byte>): pointer; begin if Length(Values)=0 then result := nil else result := @Values[0]; end; class function TFun.IfThen<T>(ACondition: Boolean; AValueTrue, AValueFalse: T): T; begin if ACondition then result := AValueTrue else result := AValueFalse; end; class function TFun.InRange(const AValue, AValueFrom, AValueTo: integer): boolean; begin if AValueFrom <= AValueTo then result := (AValue >= AValueFrom) and (AValue <= AValueTo) else result := (AValue >= AValueTo) and (AValue <= AValueFrom); end; class function TFun.InRange(const AValue, AValueFrom, AValueTo: double): boolean; begin if AValueFrom <= AValueTo then result := (AValue >= AValueFrom) and (AValue <= AValueTo) else result := (AValue >= AValueTo) and (AValue <= AValueFrom); end; class function TFun.ValueInRange<T>(AValue, AValueFrom, AValueTo: T): boolean; var Comparer: IComparer<T>; begin Comparer := TComparerUtils.DefaultComparer<T>; if Comparer.Compare(AValueFrom, AValueTo) <= 0 then Result := (Comparer.Compare(AValue, AValueFrom) >= 0) and (Comparer.Compare(AValue, AValueTo) <= 0) else Result := (Comparer.Compare(AValue, AValueTo) >= 0) and (Comparer.Compare(AValue, AValueFrom) <= 0); end; class function TFun.Max(const A, B, C: double): double; begin Result := A; if B > Result then Result := B; if C > Result then Result := C; end; class function TFun.Max(const A, B: double): double; begin if A >= B then result := A else result := B; end; class function TFun.Max(const A, B: integer): integer; begin if A >= B then result := A else result := B; end; class function TFun.Min(const Values: array of integer): integer; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] < result then result := Values[I]; end; class function TFun.Min(const Values: TArray<integer>): integer; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] < result then result := Values[I]; end; class function TFun.Max(const Values: array of integer): integer; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] > result then result := Values[I]; end; class function TFun.Max(const Values: TArray<integer>): integer; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] > result then result := Values[I]; end; class function TFun.Max(const A, B, C: integer): integer; begin Result := A; if B > Result then Result := B; if C > Result then Result := C; end; class function TFun.Min(const A, B, C: double): double; begin Result := A; if B < Result then Result := B; if C < Result then Result := C; end; class function TFun.Min(const A, B: double): double; begin if A <= B then result := A else result := B; end; class function TFun.Min(const A, B: integer): integer; begin if A <= B then result := A else result := B; end; class function TFun.Min(const A, B, C: integer): integer; begin Result := A; if B < Result then Result := B; if C < Result then Result := C; end; class function TFun.Overlapped(const AFrom, ATo, BFrom, BTo: integer): boolean; begin if AFrom <= ATo then if BFrom <= BTo then result := (AFrom <= BTo) and (BFrom <= ATo) else result := (AFrom <= BFrom) and (BTo <= ATo) else if BFrom <= BTo then result := (ATo <= BTo) and (BFrom <= AFrom) else result := (ATo <= BFrom) and (BTo <= AFrom); end; class function TFun.Overlapped(const AFrom, ATo, BFrom, BTo: double): boolean; begin if AFrom <= ATo then if BFrom <= BTo then result := (AFrom <= BTo) and (BFrom <= ATo) else result := (AFrom <= BFrom) and (BTo <= ATo) else if BFrom <= BTo then result := (ATo <= BTo) and (BFrom <= AFrom) else result := (ATo <= BFrom) and (BTo <= AFrom); end; class function TFun.Min(const Values: array of double): double; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] < result then result := Values[I]; end; class function TFun.Min(const Values: TArray<double>): double; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] < result then result := Values[I]; end; class function TFun.Max(const Values: array of double): double; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] > result then result := Values[I]; end; class function TFun.Max(const Values: TArray<double>): double; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] > result then result := Values[I]; end; { TDataSize } procedure TDataSize.Init(const AValue: int64); begin Self := Default(TDataSize); FSize := AValue; end; procedure TDataSize.InitMb(const AValue: double); begin Self := Default(TDataSize); SizeMb := AValue; end; class operator TDataSize.Add(Left, Right: TDataSize): TDataSize; begin result := Left.FSize+right.FSize; end; class operator TDataSize.Divide(Left, Right: TDataSize): TDataSize; begin result := Left.FSize div Right.FSize; end; class operator TDataSize.Equal(const Left, Right: TDataSize): Boolean; begin result := Left.FSize=Right.FSize; end; function TDataSize.GetAsString: string; begin {case FSize of 0 .. Kb-1 : result := Format('%d', [FSize]); Kb .. Mb-1 : result := Format('%.1f Kb', [FSize/Kb]); Mb .. Gb-1 : result := Format('%.1f Mb', [FSize/Mb]); Gb .. Tb-1 : result := Format('%.1f Gb', [FSize/Gb]); else result := Format('%.1f Tb', [FSize/Tb]); end;} if FSize<Mb then if FSize<Kb then result := Format('%d', [FSize]) else result := Format('%.2f Kb', [FSize/Kb]) else if FSize<Gb then result := Format('%.2f Mb', [FSize/Mb]) else if FSize<Tb then result := Format('%.2f Gb', [FSize/Gb]) else result := Format('%.2f Tb', [FSize/Tb]); end; function TDataSize.GetGb: double; begin result := FSIze / Gb; end; function TDataSize.GetKb: double; begin result := FSIze / Kb; end; function TDataSize.GetMb: double; begin result := FSIze / Mb; end; function TDataSize.GetTb: double; begin result := FSIze / Tb; end; class operator TDataSize.GreaterThan(const Left, Right: TDataSize): Boolean; begin result := Left.FSize>Right.FSize; end; class operator TDataSize.GreaterThanOrEqual(const Left, Right: TDataSize): Boolean; begin result := Left.FSize>=Right.FSize; end; class operator TDataSize.Implicit(const AValue: int64): TDataSize; begin result.FSize := AValue; end; class operator TDataSize.IntDivide(Left, Right: TDataSize): TDataSize; begin result := Left.FSize div Right.FSize; end; class operator TDataSize.LessThan(const Left, Right: TDataSize): Boolean; begin result := Left.FSize<Right.FSize; end; class operator TDataSize.LessThanOrEqual(const Left, Right: TDataSize): Boolean; begin result := Left.FSize<=Right.FSize; end; class operator TDataSize.Multiply(Left, Right: TDataSize): TDataSize; begin result := Left.FSize*Right.FSize; end; class operator TDataSize.Negative(Value: TDataSize): TDataSize; begin result := -Value.FSize; end; class operator TDataSize.NotEqual(const Left, Right: TDataSize): Boolean; begin result := Left.FSize<>Right.FSize; end; class operator TDataSize.Implicit(const AValue: TDataSize): int64; begin result := AValue.FSize; end; procedure TDataSize.SetGb(const Value: double); begin FSize := Trunc(Value*Gb); end; procedure TDataSize.SetKb(const Value: double); begin FSize := Trunc(Value*Kb); end; procedure TDataSize.SetMb(const Value: double); begin FSize := Trunc(Value*Mb); end; procedure TDataSize.SetTb(const Value: double); begin FSize := Trunc(Value*Tb); end; class function TDataSize.SizeToString(const AValue: int64): string; var S: TDataSize; begin S.Init(AValue); result := S.AsString; end; class operator TDataSize.Subtract(Left, Right: TDataSize): TDataSize; begin result := Left.FSize-Right.FSize; end; { TIntegralImageInt64 } procedure TIntegralImageInt64.Init; begin Self := Default(TIntegralImageInt64); end; procedure TIntegralImageInt64.SetSize(AWidth, AHeight: integer); begin Width := AWidth; Height := AHeight; SetLength(Image, 0); SetLength(Image, Width*Height); end; procedure TIntegralImageInt64.Build; var x,y: Integer; begin for x := 1 to Width-1 do Inc(Image[x],Image[x-1]); for y := 1 to Height-1 do Inc(Image[y*Width],Image[(y-1)*Width]); for y := 1 to Height-1 do BuildLine(@Image[y*Width+1]); end; (* ##### # # ####? *) procedure TIntegralImageInt64.BuildLine(ADst: PInt64Array); var x: Integer; begin for x := 0 to Width-2 do inc(ADst[x], ADst[x-1]+ADst[x-Width]-ADst[x-Width-1]); end; procedure TIntegralImageInt64.Clear; begin SetSize(0,0); end; function TIntegralImageInt64.GetLine(y: integer): PInt64Array; begin result := @Image[y*Width]; end; function TIntegralImageInt64.GetSum(x1, y1, x2, y2: integer): int64; begin Result := Image[x2+y2*Width]; if x1>0 then begin if y1>0 then Inc(Result, Image[x1-1+(y1-1)*Width]); dec(Result, Image[x1-1+y2*Width]); end; if y1>0 then dec(Result, Image[x2+(y1-1)*Width]); end; function TIntegralImageInt64.GetAvg(x1, y1, x2, y2: integer): int64; begin assert((x2>=x1) and (y2>=y1)); if x2-x1+1>width then x2 := x1+width-1; if y2-y1+1>height then y2 := y1+height-1; if x1<0 then begin dec(x2, x1); x1 := 0; end; if y1<0 then begin dec(y2, y1); y1 := 0; end; if x2>=width then begin dec(x1,x2-width+1); x2 := width-1; end; if y2>=height then begin dec(y1,y2-height+1); y2 := height-1; end; result := Sum[x1,y1,x2,y2] div ((x2-x1+1)*(y2-y1+1)); end; { TInterpolation_Int64Custom } constructor TInterpolation_Int64Custom.Create(PointCount: integer); begin SetLength(FPoints, PointCount); FComparer := TDelegatedComparer<TPt>.Create( function (const A, B: TPt): integer begin if A.X < B.X then result := -1 else if A.X = B.X then result := 0 else result := 1; end); end; procedure TInterpolation_Int64Custom.BeginUpdate; begin inc(FUpdateCnt); if FUpdateCnt=1 then DoBeginUpdate; end; procedure TInterpolation_Int64Custom.EndUpdate; begin dec(FUpdateCnt); if FUpdateCnt=0 then DoEndUpdate; end; procedure TInterpolation_Int64Custom.DoBeginUpdate; begin end; procedure TInterpolation_Int64Custom.DoEndUpdate; var I: Integer; begin { reorder if necessary } for I := 0 to High(FPoints)-1 do if FPoints[I].X > FPoints[I+1].X then begin TArray.Sort<TPt>(FPoints, FComparer); Break; end; { It is not allowed to have Xi=Xj for any i<>j, items are ordered, so we can check it eficiently. } for I := 0 to High(FPoints)-1 do if FPoints[I].X=FPoints[I+1].X then raise Exception.Create('Error'); end; function TInterpolation_Int64Custom.GetPoint(i: integer): TPt; begin result := FPoints[i]; end; procedure TInterpolation_Int64Custom.SetPoint(i: integer; const Value: TPt); begin Assert((FUpdateCnt>0) and (i>=0) and (i<=High(FPoints))); FPoints[i] := Value; end; function TInterpolation_Int64Custom.GetPointCount: integer; begin result := Length(FPoints); end; { TLinearInterpolation_Int64 } function TLinearInterpolation_Int64.DoGetValue(const X: int64): int64; var Item: TPt; FoundIndex: Integer; begin Assert(Length(FPoints)>0); Item.X := X; Item.Y := 0; if TArray.BinarySearch<TPt>(FPoints, Item, FoundIndex, FComparer) then result := FPoints[FoundIndex].Y else { If not found, FoundIndex contains the index of the first entry larger than Item } if FoundIndex = 0 then result := FPoints[0].Y else if FoundIndex > High(FPoints) then result := FPoints[High(FPoints)].Y else { Xi<>Xj for any i<>j (check DoEndUpdate), so div by zero is not possible here. } result := FPoints[FoundIndex-1].Y + (X-FPoints[FoundIndex-1].X) * (FPoints[FoundIndex].Y-FPoints[FoundIndex-1].Y) div (FPoints[FoundIndex].X-FPoints[FoundIndex-1].X); end; { TDebugUtils } class function TDebugUtils.DebuggerIsAttached: boolean; begin {$WARN SYMBOL_PLATFORM OFF} result := DebugHook <> 0; {$WARN SYMBOL_PLATFORM DEFAULT} end; { TInterfacedType<T> } constructor TInterfacedType<T>.Create(AData: T); begin inherited Create; FData := AData; end; function TInterfacedType<T>.Extract: T; begin result := FData; FData := Default(T); end; function TInterfacedType<T>.GetData: T; begin result := FData; end; function TInterfacedType<T>.GetRefCount: integer; begin result := RefCount; end; procedure TInterfacedType<T>.SetData(const AData: T); begin FData := AData; end; { TCustomReadOnlyStream } function TCustomReadOnlyStream.GetSize: Int64; begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Seek(Offset: Longint; Origin: Word): Longint; begin raise EAbstractError.CreateRes(@SAbstractError); end; procedure TCustomReadOnlyStream.SetSize(const NewSize: Int64); begin raise EAbstractError.CreateRes(@SAbstractError); end; procedure TCustomReadOnlyStream.SetSize(NewSize: Longint); begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Write(const Buffer; Count: Longint): Longint; begin raise EAbstractError.CreateRes(@SAbstractError); end; function TCustomReadOnlyStream.Write(const Buffer: TBytes; Offset, Count: Longint): Longint; begin raise EAbstractError.CreateRes(@SAbstractError); end; { TEventStat } procedure TEventStat.Reg(const EventCategory: string); begin Reg(EventCategory, 1); end; procedure TEventStat.Reg(const EventCategory: string; Count: int64); var C: int64; begin if not FEvents.TryGetValue(EventCategory, C) then C:= 0; inc(C, Count); FEvents.AddOrSetValue(EventCategory, C); end; procedure TEventStat.UnReg(const EventCategory: string); begin UnReg(EventCategory, 1); end; procedure TEventStat.UnReg(const EventCategory: string; Count: int64); var C: int64; begin if FEvents.TryGetValue(EventCategory, C) then begin dec(C, Count); if C <=0 then FEvents.Remove(EventCategory) else FEvents.AddOrSetValue(EventCategory, C); end; end; procedure TEventStat.Add(const Src: TArray<TPair<string, int64>>); var I: Integer; begin for I := Low(Src) to High(Src) do Reg(Src[I].Key, Src[I].Value); end; function TEventStat.GetStat: TArray<TPair<string, int64>>; var C: IComparer<TPair<string, int64>>; S: IComparer<string>; begin result := FEvents.ToArray; S := TIStringComparer.Ordinal; C := TDelegatedComparer<TPair<string, int64>>.Create( function (const A,B: TPair<string, int64>): integer begin result := S.Compare(A.Key, B.Key); if result = 0 then if A.Key < B.Key then result := -1 else if A.Key = B.Key then result := 0 else result := 1 else end); TArray.Sort<TPair<string, int64>>(result, C); end; procedure TEventStat.Clear; begin FEvents.Clear; end; { TEnvelop<T> } constructor TEnvelop<T>.Create; begin end; constructor TEnvelop<T>.Create(AValue: T); begin Value := AValue; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Implements basic shadow volumes support. Be aware that only objects that support silhouette determination have a chance to cast correct shadows. Transparent/blended/shader objects among the receivers or the casters will be rendered incorrectly. } unit VXS.ShadowVolume; interface {$I VXScene.inc} uses System.SysUtils, System.Classes, VXS.OpenGL, VXS.Scene, VXS.PipelineTransformation, VXS.VectorLists, VXS.State, VXS.VectorTypes, VXS.VectorGeometry, VXS.Context, VXS.Silhouette, VXS.PersistentClasses, VXS.GeometryBB, VXS.Color, VXS.RenderContextInfo; type TVXShadowVolume = class; { Determines when a shadow volume should generate a cap at the beginning and end of the volume. This is ONLY necessary when there's a chance that the camera could end up inside the shadow _or_ between the light source and the camera. If those two situations can't occur then not using capping is the best option. Note that if you use the capping, you must either set the depth of view of your camera to something very large (f.i. 1e9), or you could use the infinite mode (csInfinitePerspective) of your camera. svcDefault : Default behaviour svcAlways : Always generates caps svcNever : Never generates caps } TVXShadowVolumeCapping = (svcDefault, svcAlways, svcNever); { Determines when a caster should actually produce a shadow; scmAlways : Caster always produces a shadow, ignoring visibility scmVisible : Caster casts shadow if the object has visible=true scmRecursivelyVisible : Caster casts shadow if ancestors up the hierarchy all have visible=true scmParentVisible : Caster produces shadow if parent has visible=true scmParentRecursivelyVisible : Caster casts shadow if ancestors up the hierarchy all have visible=true, starting from the parent (ignoring own visible setting) } TVXShadowCastingMode = (scmAlways, scmVisible, scmRecursivelyVisible, scmParentVisible, scmParentRecursivelyVisible); { Specifies an individual shadow caster. Can be a light or an opaque object. } TVXShadowVolumeCaster = class(TCollectionItem) private FCaster: TVXBaseSceneObject; FEffectiveRadius: Single; FCapping: TVXShadowVolumeCapping; FCastingMode: TVXShadowCastingMode; protected procedure SetCaster(const val: TVXBaseSceneObject); function GetGLShadowVolume: TVXShadowVolume; procedure RemoveNotification(aComponent: TComponent); function GetDisplayName: string; override; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; { Shadow casting object. Can be an opaque object or a lightsource. } property Caster: TVXBaseSceneObject read FCaster write SetCaster; property GLShadowVolume: TVXShadowVolume read GetGLShadowVolume; published { Radius beyond which the caster can be ignored. Zero (default value) means the caster can never be ignored. } property EffectiveRadius: Single read FEffectiveRadius write FEffectiveRadius; { Specifies if the shadow volume should be capped. Capping helps solve shadowing artefacts, at the cost of performance. } property Capping: TVXShadowVolumeCapping read FCapping write FCapping default svcDefault; { Determines when an object should cast a shadow or not. Typically, objects should only cast shadows when recursively visible. But if you're using dummy shadow casters which are less complex than their parent objects, you should use scmParentRecursivelyVisible.} property CastingMode: TVXShadowCastingMode read FCastingMode write FCastingMode default scmRecursivelyVisible; end; { Specifies an individual shadow casting occluder. } TVXShadowVolumeOccluder = class(TVXShadowVolumeCaster) published property Caster; end; { Specifies an individual shadow casting light. } TVXShadowVolumeLight = class(TVXShadowVolumeCaster) private FSilhouettes: TPersistentObjectList; protected function GetLightSource: TVXLightSource; procedure SetLightSource(const ls: TVXLightSource); function GetCachedSilhouette(AIndex: Integer): TVXSilhouette; inline; procedure StoreCachedSilhouette(AIndex: Integer; ASil: TVXSilhouette); { Compute and setup scissor clipping rect for the light. Returns true if a scissor rect was setup } function SetupScissorRect(worldAABB: PAABB; var rci: TVXRenderContextInfo): Boolean; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure FlushSilhouetteCache; published { Shadow casting lightsource. } property LightSource: TVXLightSource read GetLightSource write SetLightSource; end; { Collection of TVXShadowVolumeCaster. } TVXShadowVolumeCasters = class(TOwnedCollection) protected function GetItems(index: Integer): TVXShadowVolumeCaster; procedure RemoveNotification(aComponent: TComponent); public function AddCaster(obj: TVXBaseSceneObject; effectiveRadius: Single = 0; CastingMode: TVXShadowCastingMode = scmRecursivelyVisible): TVXShadowVolumeCaster; procedure RemoveCaster(obj: TVXBaseSceneObject); function IndexOfCaster(obj: TVXBaseSceneObject): Integer; property Items[index: Integer]: TVXShadowVolumeCaster read GetItems; default; end; { Shadow volume rendering options/optimizations. svoShowVolumes : make the shadow volumes visible svoDesignVisible : the shadow are visible at design-time svoCacheSilhouettes : cache shadow volume silhouettes, beneficial when some objects are static relatively to their light(s) svoScissorClips : use scissor clipping per light, beneficial when lights are attenuated and don't illuminate the whole scene svoWorldScissorClip : use scissor clipping for the world, beneficial when shadow receivers don't cover the whole viewer surface } TVXShadowVolumeOption = (svoShowVolumes, svoCacheSilhouettes, svoScissorClips, svoWorldScissorClip, svoDesignVisible); TVXShadowVolumeOptions = set of TVXShadowVolumeOption; { Shadow rendering modes. svmAccurate : will render the scene with ambient lighting only, then for each light will make a diffuse+specular pass svmDarkening : renders the scene with lighting on as usual, then darkens shadowed areas (i.e. inaccurate lighting, but will "shadow" objects that don't honour to diffuse or specular lighting) svmOff : no shadowing will take place } TVXShadowVolumeMode = (svmAccurate, svmDarkening, svmOff); { Simple shadow volumes. Shadow receiving objects are the ShadowVolume's children, shadow casters (opaque objects or lights) must be explicitly specified in the Casters collection. Shadow volumes require that the buffer allows stencil buffers, VXSceneViewer.Buffer.ContextOptions contain roStencinBuffer. Without stencil buffers, shadow volumes will not work properly. Another issue to look out for is the fact that shadow volume capping requires that the camera depth of view is either very high (fi 1e9) or that the camera style is csInfinitePerspective. } TVXShadowVolume = class(TVXImmaterialSceneObject) private FActive: Boolean; FRendering: Boolean; FLights: TVXShadowVolumeCasters; FOccluders: TVXShadowVolumeCasters; FCapping: TVXShadowVolumeCapping; FOptions: TVXShadowVolumeOptions; FMode: TVXShadowVolumeMode; FDarkeningColor: TVXColor; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetActive(const val: Boolean); procedure SetLights(const val: TVXShadowVolumeCasters); procedure SetOccluders(const val: TVXShadowVolumeCasters); procedure SetOptions(const val: TVXShadowVolumeOptions); procedure SetMode(const val: TVXShadowVolumeMode); procedure SetDarkeningColor(const val: TVXColor); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; procedure Assign(Source: TPersistent); override; procedure FlushSilhouetteCache; published { Determines if shadow volume rendering is active. When set to false, children will be rendered without any shadowing or multipass lighting. } property Active: Boolean read FActive write SetActive default True; { Lights that cast shadow volumes. } property Lights: TVXShadowVolumeCasters read FLights write SetLights; { Occluders that cast shadow volumes. } property Occluders: TVXShadowVolumeCasters read FOccluders write SetOccluders; { Specifies if the shadow volume should be capped. Capping helps solve shadowing artefacts, at the cost of performance. } property Capping: TVXShadowVolumeCapping read FCapping write FCapping default svcAlways; { Shadow volume rendering options. } property Options: TVXShadowVolumeOptions read FOptions write SetOptions default [svoCacheSilhouettes, svoScissorClips]; { Shadow rendering mode. } property Mode: TVXShadowVolumeMode read FMode write SetMode default svmAccurate; { Darkening color used in svmDarkening mode. } property DarkeningColor: TVXColor read FDarkeningColor write SetDarkeningColor; end; //------------------------------------------------------------- implementation //------------------------------------------------------------- // ------------------ // ------------------ TVXShadowVolumeCaster ------------------ // ------------------ constructor TVXShadowVolumeCaster.Create(ACollection: TCollection); begin inherited Create(ACollection); FCapping := svcDefault; FCastingMode := scmRecursivelyVisible; end; type // Required for Delphi 5 support. THackOwnedCollection = class(TOwnedCollection); // GetGLShadowVolume // function TVXShadowVolumeCaster.GetGLShadowVolume: TVXShadowVolume; begin Result := TVXShadowVolume(THackOwnedCollection(Collection).GetOwner); end; destructor TVXShadowVolumeCaster.Destroy; begin if Assigned(FCaster) then FCaster.RemoveFreeNotification(GLShadowVolume); inherited; end; procedure TVXShadowVolumeCaster.Assign(Source: TPersistent); begin if Source is TVXShadowVolumeCaster then begin FCaster := TVXShadowVolumeCaster(Source).FCaster; FEffectiveRadius := TVXShadowVolumeCaster(Source).FEffectiveRadius; FCapping := TVXShadowVolumeCaster(Source).FCapping; GetGLShadowVolume.StructureChanged; end; inherited; end; procedure TVXShadowVolumeCaster.SetCaster(const val: TVXBaseSceneObject); begin if FCaster <> val then begin if FCaster <> nil then FCaster.RemoveFreeNotification(GLShadowVolume); FCaster := val; if FCaster <> nil then FCaster.FreeNotification(GLShadowVolume); GetGLShadowVolume.StructureChanged; end; end; procedure TVXShadowVolumeCaster.RemoveNotification(aComponent: TComponent); begin if aComponent = FCaster then begin // No point in keeping the TVXShadowVolumeCaster once the FCaster has been // destroyed. FCaster := nil; Free; end; end; function TVXShadowVolumeCaster.GetDisplayName: string; begin if Assigned(FCaster) then begin if FCaster is TVXLightSource then Result := '[Light]' else Result := '[Object]'; Result := Result + ' ' + FCaster.Name; if EffectiveRadius > 0 then Result := Result + Format(' (%.1f)', [EffectiveRadius]); end else Result := 'nil'; end; // ------------------ // ------------------ TVXShadowVolumeLight ------------------ // ------------------ constructor TVXShadowVolumeLight.Create(ACollection: TCollection); begin inherited Create(ACollection); FSilhouettes := TPersistentObjectList.Create; end; destructor TVXShadowVolumeLight.Destroy; begin FlushSilhouetteCache; FSilhouettes.Free; inherited; end; procedure TVXShadowVolumeLight.FlushSilhouetteCache; begin FSilhouettes.Clean; end; function TVXShadowVolumeLight.GetLightSource: TVXLightSource; begin Result := TVXLightSource(Caster); end; procedure TVXShadowVolumeLight.SetLightSource(const ls: TVXLightSource); begin SetCaster(ls); end; function TVXShadowVolumeLight.GetCachedSilhouette(AIndex: Integer): TVXSilhouette; begin if AIndex < FSilhouettes.Count then Result := TVXSilhouette(FSilhouettes[AIndex]) else Result := nil; end; procedure TVXShadowVolumeLight.StoreCachedSilhouette(AIndex: Integer; ASil: TVXSilhouette); begin while AIndex >= FSilhouettes.Count do FSilhouettes.Add(nil); if ASil <> FSilhouettes[AIndex] then begin if assigned(FSilhouettes[AIndex]) then FSilhouettes[AIndex].Free; FSilhouettes[AIndex] := ASil; end; end; function TVXShadowVolumeLight.SetupScissorRect(worldAABB: PAABB; var rci: TVXRenderContextInfo): Boolean; var mvp: TMatrix; ls: TVXLightSource; aabb: TAABB; clipRect: TClipRect; begin ls := LightSource; if (EffectiveRadius <= 0) or (not ls.Attenuated) then begin // non attenuated lights can't be clipped if not Assigned(worldAABB) then begin Result := False; Exit; end else aabb := worldAABB^; end else begin aabb := BSphereToAABB(ls.AbsolutePosition, EffectiveRadius); if Assigned(worldAABB) then aabb := AABBIntersection(aabb, worldAABB^); end; if PointInAABB(rci.cameraPosition, aabb) then begin // camera inside light volume radius, can't clip Result := False; Exit; end; // Calculate the window-space bounds of the light's bounding box. mvp := rci.PipelineTransformation.ViewProjectionMatrix^; clipRect := AABBToClipRect(aabb, mvp, rci.viewPortSize.cx, rci.viewPortSize.cy); if (clipRect.Right < 0) or (clipRect.Left > rci.viewPortSize.cx) or (clipRect.Top < 0) or (clipRect.Bottom > rci.viewPortSize.cy) then begin Result := False; Exit; end; with clipRect do glScissor(Round(Left), Round(Top), Round(Right - Left), Round(Bottom - Top)); Result := True; end; // ------------------ // ------------------ TVXShadowVolumeCasters ------------------ // ------------------ procedure TVXShadowVolumeCasters.RemoveNotification(aComponent: TComponent); var i: Integer; begin for i := Count - 1 downto 0 do Items[i].RemoveNotification(aComponent); end; function TVXShadowVolumeCasters.GetItems(index: Integer): TVXShadowVolumeCaster; begin Result := TVXShadowVolumeCaster(inherited Items[index]); end; function TVXShadowVolumeCasters.AddCaster(obj: TVXBaseSceneObject; effectiveRadius: Single = 0; CastingMode: TVXShadowCastingMode = scmRecursivelyVisible): TVXShadowVolumeCaster; var newCaster: TVXShadowVolumeCaster; begin newCaster := TVXShadowVolumeCaster(Add); newCaster.Caster := obj; newCaster.EffectiveRadius := effectiveRadius; newCaster.CastingMode := CastingMode; result := newCaster; end; procedure TVXShadowVolumeCasters.RemoveCaster(obj: TVXBaseSceneObject); var i: Integer; begin i := IndexOfCaster(obj); if i >= 0 then Delete(i); end; function TVXShadowVolumeCasters.IndexOfCaster(obj: TVXBaseSceneObject): Integer; var i: Integer; begin for i := 0 to Count - 1 do begin if Items[i].Caster = obj then begin Result := i; Exit; end; end; Result := -1; end; // ------------------ // ------------------ TVXShadowVolume ------------------ // ------------------ constructor TVXShadowVolume.Create(AOwner: Tcomponent); begin inherited Create(AOwner); ObjectStyle := ObjectStyle - [osDirectDraw] + [osNoVisibilityCulling]; FActive := True; FLights := TVXShadowVolumeCasters.Create(self, TVXShadowVolumeLight); FOccluders := TVXShadowVolumeCasters.Create(self, TVXShadowVolumeOccluder); FCapping := svcAlways; FMode := svmAccurate; FOptions := [svoCacheSilhouettes, svoScissorClips]; FDarkeningColor := TVXColor.CreateInitialized(Self, VectorMake(0, 0, 0, 0.5)); end; destructor TVXShadowVolume.Destroy; begin inherited; FDarkeningColor.Free; FLights.Free; FOccluders.Free; end; procedure TVXShadowVolume.Notification(AComponent: TComponent; Operation: TOperation); begin if Operation = opRemove then begin FLights.RemoveNotification(AComponent); FOccluders.RemoveNotification(AComponent); end; inherited; end; procedure TVXShadowVolume.Assign(Source: TPersistent); begin if Assigned(Source) and (Source is TVXShadowVolume) then begin FLights.Assign(TVXShadowVolume(Source).Lights); FOccluders.Assign(TVXShadowVolume(Source).Occluders); FCapping := TVXShadowVolume(Source).FCapping; StructureChanged; end; inherited Assign(Source); end; procedure TVXShadowVolume.FlushSilhouetteCache; var i: Integer; begin for i := 0 to Lights.Count - 1 do (Lights[i] as TVXShadowVolumeLight).FlushSilhouetteCache; end; procedure TVXShadowVolume.SetActive(const val: Boolean); begin if FActive <> val then begin FActive := val; StructureChanged; end; end; procedure TVXShadowVolume.SetLights(const val: TVXShadowVolumeCasters); begin Assert(val.ItemClass = TVXShadowVolumeLight); FLights.Assign(val); StructureChanged; end; procedure TVXShadowVolume.SetOccluders(const val: TVXShadowVolumeCasters); begin Assert(val.ItemClass = TVXShadowVolumeOccluder); FOccluders.Assign(val); StructureChanged; end; procedure TVXShadowVolume.SetOptions(const val: TVXShadowVolumeOptions); begin if FOptions <> val then begin FOptions := val; if not (svoCacheSilhouettes in FOptions) then FlushSilhouetteCache; StructureChanged; end; end; procedure TVXShadowVolume.SetMode(const val: TVXShadowVolumeMode); begin if FMode <> val then begin FMode := val; StructureChanged; end; end; procedure TVXShadowVolume.SetDarkeningColor(const val: TVXColor); begin FDarkeningColor.Assign(val); end; procedure TVXShadowVolume.DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); // Function that determines if an object is "recursively visible". It halts when // * it finds an invisible ancestor (=> invisible) // * it finds the root (=> visible) // * it finds the shadow volume as an ancestor (=> visible) // // This does _not_ mean that the object is actually visible on the screen function DirectHierarchicalVisibility(obj: TVXBaseSceneObject): boolean; var p: TVXBaseSceneObject; begin if not Assigned(obj) then begin Result := True; exit; end; if not obj.Visible then begin Result := False; Exit; end; p := obj.Parent; while Assigned(p) and (p <> obj) and (p <> Self) do begin if not p.Visible then begin Result := False; Exit; end; p := p.Parent; end; Result := True; end; var i, k: Integer; lightSource: TVXLightSource; lightCaster: TVXShadowVolumeLight; sil: TVXSilhouette; lightID: Cardinal; obj: TVXBaseSceneObject; caster: TVXShadowVolumeCaster; opaques, opaqueCapping: TList; silParams: TVXSilhouetteParameters; worldAABB: TAABB; pWorldAABB: PAABB; PM: TMatrix; begin if not Active then begin inherited; Exit; end; if FRendering then Exit; if not (ARenderSelf or ARenderChildren) then Exit; ClearStructureChanged; if ((csDesigning in ComponentState) and not (svoDesignVisible in Options)) or (Mode = svmOff) or (ARci.drawState = dsPicking) then begin inherited; Exit; end; if svoWorldScissorClip in Options then begin // compute shadow receiving world AABB in absolute coordinates worldAABB := Self.AxisAlignedBoundingBox; AABBTransform(worldAABB, AbsoluteMatrix); pWorldAABB := @worldAABB; end else pWorldAABB := nil; opaques := TList.Create; opaqueCapping := TList.Create; FRendering := True; try // collect visible casters for i := 0 to Occluders.Count - 1 do begin caster := Occluders[i]; obj := caster.Caster; if Assigned(obj) and // Determine when to render this object or not ( (Caster.CastingMode = scmAlways) or ((Caster.CastingMode = scmVisible) and obj.Visible) or ((Caster.CastingMode = scmRecursivelyVisible) and DirectHierarchicalVisibility(obj)) or ((Caster.CastingMode = scmParentRecursivelyVisible) and DirectHierarchicalVisibility(obj.Parent)) or ((Caster.CastingMode = scmParentVisible) and (not Assigned(obj.Parent) or obj.Parent.Visible)) ) and ((caster.EffectiveRadius <= 0) or (obj.DistanceTo(ARci.cameraPosition) < caster.EffectiveRadius)) then begin opaques.Add(obj); opaqueCapping.Add(Pointer(Cardinal(ord((caster.Capping = svcAlways) or ((caster.Capping = svcDefault) and (Capping = svcAlways)))))); end else begin opaques.Add(nil); opaqueCapping.Add(nil); end; end; // render the shadow volumes with ARci.VxStates do begin if Mode = svmAccurate then begin // first turn off all the shadow casting lights diffuse and specular for i := 0 to Lights.Count - 1 do begin lightCaster := TVXShadowVolumeLight(Lights[i]); lightSource := lightCaster.LightSource; if Assigned(lightSource) and (lightSource.Shining) then begin lightID := lightSource.LightID; LightDiffuse[lightID] := NullHmgVector; LightSpecular[lightID] := NullHmgVector; end; end; end; // render shadow receivers with ambient lighting // DanB - not sure why this doesn't render properly with these statements // where they were originally (after the RenderChildren call). Self.RenderChildren(0, Count - 1, ARci); ARci.ignoreBlendingRequests := True; ARci.ignoreDepthRequests := True; DepthWriteMask := False; Enable(stDepthTest); SetBlendFunc(bfSrcAlpha, bfOne); Disable(stAlphaTest); Enable(stStencilTest); // Disable all client states if GL_ARB_vertex_buffer_object then begin VertexArrayBinding := 0; ArrayBufferBinding := 0; ElementBufferBinding := 0; end; // turn off *all* lights for i := 0 to TVXScene(ARci.scene).Lights.Count - 1 do begin lightSource := (TVXScene(ARci.scene).Lights.Items[i]) as TVXLightSource; if Assigned(lightSource) and lightSource.Shining then LightEnabling[lightSource.LightID] := False; end; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @NullHmgPoint); ARci.PipelineTransformation.Push; // render contribution of all shadow casting lights for i := 0 to Lights.Count - 1 do begin lightCaster := TVXShadowVolumeLight(lights[i]); lightSource := lightCaster.LightSource; if (not Assigned(lightSource)) or (not lightSource.Shining) then Continue; lightID := lightSource.LightID; SetVector(silParams.LightDirection, lightSource.SpotDirection.DirectVector); case lightSource.LightStyle of lsParallel: silParams.Style := ssParallel else silParams.Style := ssOmni; end; silParams.CappingRequired := True; if Assigned(pWorldAABB) or (svoScissorClips in Options) then begin if lightCaster.SetupScissorRect(pWorldAABB, ARci) then Enable(stScissorTest) else Disable(stScissorTest); end; // clear the stencil and prepare for shadow volume pass glClear(GL_STENCIL_BUFFER_BIT); SetStencilFunc(cfAlways, 0, 255); DepthFunc := cfLess; if svoShowVolumes in Options then begin glColor3f(0.05 * i, 0.1, 0); Enable(stBlend); end else begin SetColorWriting(False); Disable(stBlend); end; Enable(stCullFace); Disable(stLighting); glEnableClientState(GL_VERTEX_ARRAY); SetPolygonOffset(1, 1); // for all opaque shadow casters for k := 0 to opaques.Count - 1 do begin obj := TVXBaseSceneObject(opaques[k]); if obj = nil then Continue; SetVector(silParams.SeenFrom, obj.AbsoluteToLocal(lightSource.AbsolutePosition)); sil := lightCaster.GetCachedSilhouette(k); if (not Assigned(sil)) or (not CompareMem(@sil.Parameters, @silParams, SizeOf(silParams))) then begin sil := obj.GenerateSilhouette(silParams); sil.Parameters := silParams; // extrude vertices to infinity sil.ExtrudeVerticesToInfinity(silParams.SeenFrom); end; if Assigned(sil) then try // render the silhouette ARci.PipelineTransformation.SetModelMatrix(obj.AbsoluteMatrix); glVertexPointer(4, GL_FLOAT, 0, sil.Vertices.List); if Boolean(Cardinal(opaqueCapping[k])) then begin // z-fail if GL_EXT_compiled_vertex_array then glLockArraysEXT(0, sil.Vertices.Count); CullFaceMode := cmFront; SetStencilOp(soKeep, soIncr, soKeep); with sil do begin glDrawElements(GL_QUADS, Indices.Count, GL_UNSIGNED_INT, Indices.List); Enable(stPolygonOffsetFill); glDrawElements(GL_TRIANGLES, CapIndices.Count, GL_UNSIGNED_INT, CapIndices.List); Disable(stPolygonOffsetFill); end; CullFaceMode := cmBack; SetStencilOp(soKeep, soDecr, soKeep); with sil do begin glDrawElements(GL_QUADS, Indices.Count, GL_UNSIGNED_INT, Indices.List); Enable(stPolygonOffsetFill); glDrawElements(GL_TRIANGLES, CapIndices.Count, GL_UNSIGNED_INT, CapIndices.List); Disable(stPolygonOffsetFill); end; if GL_EXT_compiled_vertex_array then glUnlockArraysEXT; end else begin // z-pass CullFaceMode := cmBack; SetStencilOp(soKeep, soKeep, soIncr); glDrawElements(GL_QUADS, sil.Indices.Count, GL_UNSIGNED_INT, sil.Indices.List); CullFaceMode := cmFront; SetStencilOp(soKeep, soKeep, soDecr); glDrawElements(GL_QUADS, sil.Indices.Count, GL_UNSIGNED_INT, sil.Indices.List); end; finally if (svoCacheSilhouettes in Options) and (not (osDirectDraw in ObjectStyle)) then lightCaster.StoreCachedSilhouette(k, sil) else sil.Free; end; end; glDisableClientState(GL_VERTEX_ARRAY); // re-enable light's diffuse and specular, but no ambient LightEnabling[LightID] := True; LightAmbient[LightID] := NullHmgVector; LightDiffuse[LightID] := lightSource.Diffuse.Color; LightSpecular[LightID] := lightSource.Specular.Color; SetColorWriting(True); SetStencilOp(soKeep, soKeep, soKeep); Enable(stBlend); CullFaceMode := cmBack; if Mode = svmAccurate then begin SetStencilFunc(cfEqual, 0, 255); DepthFunc := cfEqual; Self.RenderChildren(0, Count - 1, ARci); end else begin SetStencilFunc(cfNotEqual, 0, 255); DepthFunc := cfAlways; SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha); glPushMatrix; glLoadIdentity; glMatrixMode(GL_PROJECTION); glPushMatrix; PM := CreateOrthoMatrix(0, 1, 1, 0, -1, 1); glLoadMatrixf(PGLFloat(@PM)); glColor4fv(FDarkeningColor.AsAddress); glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2f(0, 1); glVertex2f(1, 1); glVertex2f(1, 0); glEnd; glPopMatrix; glMatrixMode(GL_MODELVIEW); glPopMatrix; SetBlendFunc(bfSrcAlpha, bfOne); end; // disable light, but restore its ambient component LightEnabling[lightID] := False; LightAmbient[lightID] := lightSource.Ambient.Color; end; // for i ARci.PipelineTransformation.Pop; // restore OpenGL state glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @ARci.sceneAmbientColor); Scene.SetupLights(ARci.VXStates.MaxLights); Disable(stStencilTest); SetPolygonOffset(0, 0); ARci.ignoreBlendingRequests := False; ARci.ignoreDepthRequests := False; end; // of with finally FRendering := False; opaques.Free; opaqueCapping.Free; end; end; //------------------------------------------------------------- initialization //------------------------------------------------------------- RegisterClasses([TVXShadowVolume]); end.
unit track_simplify; { https://sourceforge.net/p/simdesign-os/code/HEAD/tree/trunk/simlib/geometry/sdSimplifyPolylineDouglasPeucker.pas Implementation of the famous Douglas-Peucker polyline simplification algorithm. This file contains a 3D floating point implementation, for spatial polylines Permalink: http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm Loosely based on C code from SoftSurfer (www.softsurfer.com) https://github.com/jjgreen/dp-simplify/blob/master/dp-simplify.c References: David Douglas & Thomas Peucker, "Algorithms for the reduction of the number of points required to represent a digitized line or its caricature", The Canadian Cartographer 10(2), 112-122 (1973) Delphi code by Nils Haeck (c) 2003 Simdesign (www.simdesign.nl) http://www.simdesign.nl/components/douglaspeucker.html **************************************************************** The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. } interface uses define_types; type // Generalized float and int types TFloat = single; { PolySimplifyFloat3D: Approximates the polyline with 3D float vertices in Orig, with a simplified version that will be returned in Simple. The maximum deviation from the original line is given in Tol. Input: Tol = approximation tolerance Orig[] = polyline array of vertex points Output: Simple[] = simplified polyline vertices. This array must initially have the same length as Orig Return: the number of points in Simple } function PolySimplifyFloat3D(Tol: TFloat; const Orig: array of TPoint3f; var Simple: array of TPoint3f): integer; { PolySimplifyInt2D: Approximates the polyline with 2D integer vertices in Orig, with a simplified version that will be returned in Simple. The maximum deviation from the original line is given in Tol. Input: Tol = approximation tolerance Orig[] = polyline array of vertex points Output: Simple[] = simplified polyline vertices. This array must initially have the same length as Orig Return: the number of points in Simple } implementation function VecMinFloat3D(const A, B: TPoint3f): TPoint3f; // Result = A - B begin Result.X := A.X - B.X; Result.Y := A.Y - B.Y; Result.Z := A.Z - B.Z; end; function DotProdFloat3D(const A, B: TPoint3f): TFloat; // Dotproduct = A * B begin Result := A.X * B.X + A.Y * B.Y + A.Z * B. Z; end; function NormSquaredFloat3D(const A: TPoint3f): TFloat; // Square of the norm |A| begin Result := A.X * A.X + A.Y * A.Y + A.Z * A.Z; end; function DistSquaredFloat3D(const A, B: TPoint3f): TFloat; // Square of the distance from A to B begin Result := NormSquaredFloat3D(VecMinFloat3D(A, B)); end; procedure SimplifyFloat3D(var Tol2: TFloat; const Orig: array of TPoint3f; var Marker: array of boolean; j, k: integer); // Simplify polyline in OrigList between j and k. Marker[] will be set to True // for each point that must be included var i, MaxI: integer; // Index at maximum value MaxD2: TFloat; // Maximum value squared CU, CW, B: TFloat; DV2: TFloat; P0, P1, PB, U, W: TPoint3f; begin // Is there anything to simplify? if k <= j + 1 then exit; P0 := Orig[j]; P1 := Orig[k]; U := VecMinFloat3D(P1, P0); // Segment vector CU := DotProdFloat3d(U, U); // Segment length squared MaxD2 := 0; MaxI := 0; // Loop through points and detect the one furthest away for i := j + 1 to k - 1 do begin W := VecMinFloat3D(Orig[i], P0); CW := DotProdFloat3D(W, U); // Distance of point Orig[i] from segment if CW <= 0 then begin // Before segment DV2 := DistSquaredFloat3D(Orig[i], P0) end else begin if CW > CU then begin // Past segment DV2 := DistSquaredFloat3D(Orig[i], P1); end else begin // Fraction of the segment try B := CW / CU; except B := 0; // in case CU = 0 end; PB.X := P0.X + B * U.X; PB.Y := P0.Y + B * U.Y; PB.Z := P0.Z + B * U.Z; DV2 := DistSquaredFloat3D(Orig[i], PB); end; end; // test with current max distance squared if DV2 > MaxD2 then begin // Orig[i] is a new max vertex MaxI := i; MaxD2 := DV2; end; end; // If the furthest point is outside tolerance we must split if MaxD2 > Tol2 then begin // error is worse than the tolerance // split the polyline at the farthest vertex from S Marker[MaxI] := True; // mark Orig[maxi] for the simplified polyline // recursively simplify the two subpolylines at Orig[maxi] SimplifyFloat3D(Tol2, Orig, Marker, j, MaxI); // polyline Orig[j] to Orig[maxi] SimplifyFloat3D(Tol2, Orig, Marker, MaxI, k); // polyline Orig[maxi] to Orig[k] end; end; function PolySimplifyFloat3D(Tol: TFloat; const Orig: array of TPoint3f; var Simple: array of TPoint3f): integer; var i, N: integer; Marker: array of boolean; Tol2: TFloat; begin Result := 0; N := Length(Orig); //Simple := Copy(Orig, Low(Orig), Length(Orig)); if length(Orig) < 2 then exit; if Tol = 0 then begin result := N; for i := 0 to N - 1 do Simple[i] := Orig[i]; exit; end; Tol2 := sqr(Tol); // Create a marker array SetLength(Marker, N); // Include first and last point Marker[0] := True; Marker[N - 1] := True; // Exclude intermediate for now for i := 1 to N - 2 do Marker[i] := False; // Simplify SimplifyFloat3D(Tol2, Orig, Marker, 0, N - 1); // Copy to resulting list for i := 0 to N - 1 do begin if Marker[i] then begin Simple[Result] := Orig[i]; inc(Result); end; end; //setlength(Simple,Result); end; end.
unit RXUtils; //Some functions from RX's VCLUtils.Pas; {$IFNDEF VER80} {-- Delphi 1.0 } {$IFNDEF VER90} {-- Delphi 2.0 } {$IFNDEF VER93} {-- C++Builder 1.0 } {$DEFINE RX_D3} { Delphi 3.0 or higher } {$ENDIF} {$ENDIF} {$ENDIF} {$P+,W-,R-,V-} interface {$IFDEF WIN32} uses Windows, Classes, Graphics; {$ELSE} uses WinTypes, WinProcs, Classes, Graphics; {$ENDIF} { Windows resources (bitmaps and icons) VCL-oriented routines } procedure DrawBitmapTransparent(Dest: TCanvas; DstX, DstY: Integer; Bitmap: TBitmap; TransparentColor: TColor); { Service routines } function Max(X, Y: Integer): Integer; function Min(X, Y: Integer): Integer; { Standard Windows colors that are not defined by Delphi } const {$IFNDEF WIN32} clInfoBk = TColor($02E1FFFF); clNone = TColor($02FFFFFF); {$ENDIF} clCream = TColor($A6CAF0); clMoneyGreen = TColor($C0DCC0); clSkyBlue = TColor($FFFBF0); implementation { Service routines } function Max(X, Y: Integer): Integer; begin if X > Y then Result := X else Result := Y; end; function Min(X, Y: Integer): Integer; begin if X < Y then Result := X else Result := Y; end; function PaletteColor(Color: TColor): Longint; const { TBitmap.GetTransparentColor from GRAPHICS.PAS use this value } PaletteMask = $02000000; begin Result := ColorToRGB(Color) or PaletteMask; end; { Transparent bitmap } procedure StretchBltTransparent(DstDC: HDC; DstX, DstY, DstW, DstH: Integer; SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; Palette: HPalette; TransparentColor: TColorRef); var Color: TColorRef; bmAndBack, bmAndObject, bmAndMem, bmSave: HBitmap; bmBackOld, bmObjectOld, bmMemOld, bmSaveOld: HBitmap; MemDC, BackDC, ObjectDC, SaveDC: HDC; palDst, palMem, palSave, palObj: HPalette; begin { Create some DCs to hold temporary data } BackDC := CreateCompatibleDC(DstDC); ObjectDC := CreateCompatibleDC(DstDC); MemDC := CreateCompatibleDC(DstDC); SaveDC := CreateCompatibleDC(DstDC); { Create a bitmap for each DC } bmAndObject := CreateBitmap(SrcW, SrcH, 1, 1, nil); bmAndBack := CreateBitmap(SrcW, SrcH, 1, 1, nil); bmAndMem := CreateCompatibleBitmap(DstDC, DstW, DstH); bmSave := CreateCompatibleBitmap(DstDC, SrcW, SrcH); { Each DC must select a bitmap object to store pixel data } bmBackOld := SelectObject(BackDC, bmAndBack); bmObjectOld := SelectObject(ObjectDC, bmAndObject); bmMemOld := SelectObject(MemDC, bmAndMem); bmSaveOld := SelectObject(SaveDC, bmSave); { Select palette } palDst := 0; palMem := 0; palSave := 0; palObj := 0; if Palette <> 0 then begin palDst := SelectPalette(DstDC, Palette, True); RealizePalette(DstDC); palSave := SelectPalette(SaveDC, Palette, False); RealizePalette(SaveDC); palObj := SelectPalette(ObjectDC, Palette, False); RealizePalette(ObjectDC); palMem := SelectPalette(MemDC, Palette, True); RealizePalette(MemDC); end; { Set proper mapping mode } SetMapMode(SrcDC, GetMapMode(DstDC)); SetMapMode(SaveDC, GetMapMode(DstDC)); { Save the bitmap sent here } BitBlt(SaveDC, 0, 0, SrcW, SrcH, SrcDC, SrcX, SrcY, SRCCOPY); { Set the background color of the source DC to the color, } { contained in the parts of the bitmap that should be transparent } Color := SetBkColor(SaveDC, PaletteColor(TransparentColor)); { Create the object mask for the bitmap by performing a BitBlt() } { from the source bitmap to a monochrome bitmap } BitBlt(ObjectDC, 0, 0, SrcW, SrcH, SaveDC, 0, 0, SRCCOPY); { Set the background color of the source DC back to the original } SetBkColor(SaveDC, Color); { Create the inverse of the object mask } BitBlt(BackDC, 0, 0, SrcW, SrcH, ObjectDC, 0, 0, NOTSRCCOPY); { Copy the background of the main DC to the destination } BitBlt(MemDC, 0, 0, DstW, DstH, DstDC, DstX, DstY, SRCCOPY); { Mask out the places where the bitmap will be placed } StretchBlt(MemDC, 0, 0, DstW, DstH, ObjectDC, 0, 0, SrcW, SrcH, SRCAND); { Mask out the transparent colored pixels on the bitmap } BitBlt(SaveDC, 0, 0, SrcW, SrcH, BackDC, 0, 0, SRCAND); { XOR the bitmap with the background on the destination DC } StretchBlt(MemDC, 0, 0, DstW, DstH, SaveDC, 0, 0, SrcW, SrcH, SRCPAINT); { Copy the destination to the screen } BitBlt(DstDC, DstX, DstY, DstW, DstH, MemDC, 0, 0, SRCCOPY); { Restore palette } if Palette <> 0 then begin SelectPalette(MemDC, palMem, False); SelectPalette(ObjectDC, palObj, False); SelectPalette(SaveDC, palSave, False); SelectPalette(DstDC, palDst, True); end; { Delete the memory bitmaps } DeleteObject(SelectObject(BackDC, bmBackOld)); DeleteObject(SelectObject(ObjectDC, bmObjectOld)); DeleteObject(SelectObject(MemDC, bmMemOld)); DeleteObject(SelectObject(SaveDC, bmSaveOld)); { Delete the memory DCs } DeleteDC(MemDC); DeleteDC(BackDC); DeleteDC(ObjectDC); DeleteDC(SaveDC); end; procedure StretchBitmapTransparent(Dest: TCanvas; Bitmap: TBitmap; TransparentColor: TColor; DstX, DstY, DstW, DstH, SrcX, SrcY, SrcW, SrcH: Integer); var CanvasChanging: TNotifyEvent; Temp: TBitmap; begin if DstW <= 0 then DstW := Bitmap.Width; if DstH <= 0 then DstH := Bitmap.Height; if (SrcW <= 0) or (SrcH <= 0) then begin SrcX := 0; SrcY := 0; SrcW := Bitmap.Width; SrcH := Bitmap.Height; end; if not Bitmap.Monochrome then SetStretchBltMode(Dest.Handle, STRETCH_DELETESCANS); CanvasChanging := Bitmap.Canvas.OnChanging; try Bitmap.Canvas.OnChanging := nil; Temp := Bitmap; try if TransparentColor = clNone then begin StretchBlt(Dest.Handle, DstX, DstY, DstW, DstH, Temp.Canvas.Handle, SrcX, SrcY, SrcW, SrcH, Dest.CopyMode); end else begin {$IFDEF RX_D3} if TransparentColor = clDefault then TransparentColor := Temp.Canvas.Pixels[0, Temp.Height - 1]; {$ENDIF} if Temp.Monochrome then TransparentColor := clWhite else TransparentColor := ColorToRGB(TransparentColor); StretchBltTransparent(Dest.Handle, DstX, DstY, DstW, DstH, Temp.Canvas.Handle, SrcX, SrcY, SrcW, SrcH, Temp.Palette, TransparentColor); end; finally end; finally Bitmap.Canvas.OnChanging := CanvasChanging; end; end; procedure DrawBitmapTransparent(Dest: TCanvas; DstX, DstY: Integer; Bitmap: TBitmap; TransparentColor: TColor); begin StretchBitmapTransparent(Dest, Bitmap, TransparentColor, DstX, DstY, Bitmap.Width, Bitmap.Height, 0, 0, Bitmap.Width, Bitmap.Height); end; end.
{ ----------------------------------------------------------------------------- Unit Name: cUsersSettings Author: Aaron Hochwimmer Purpose: Stores the user's settings $Id: cUsersSettings.pas,v 1.25 2004/07/08 09:54:53 hochwimmera Exp $ ----------------------------------------------------------------------------- } unit cUsersSettings; interface uses System.Sysutils, System.Win.Registry, Vcl.Forms, Vcl.Graphics, GLTexture, GLVectorgeometry, GLColor, // gldata units cColourSpectrum, cUtilities; const CREGISTRYKEY = '\Software\glData'; type TColourScaleOptions = class(TObject) private fAlpha: double; fRegPath: string; fContinuous: boolean; fVisible: boolean; fBorder: boolean; fPoints: integer; fScaleFormat: string; fScaleSteps: boolean; fShowContourPoints: boolean; fColourScaleType: integer; public constructor Create; destructor Destroy; override; procedure LoadFromRegistry; procedure SaveToRegistry; property Alpha: double read fAlpha write fAlpha; property RegPath: string read fRegPath write fRegPath; property Border: boolean read fBorder write fBorder; property Continuous: boolean read fContinuous write fContinuous; property Points: integer read fPoints write fPoints; property ScaleSteps: boolean read fScaleSteps write fScaleSteps; property Scaleformat: string read fScaleFormat write fScaleFormat; property ShowContourPoints: boolean read fShowContourPoints write fShowContourPoints; property ColourScaleType: integer read fColourScaleType write fColourScaleType; property Visible: boolean read fVisible write fVisible; end; TVectorFieldOptions = class(TObject) private fBoxLineAA: boolean; fBoxLineColour: TColor; fBoxLinePattern: integer; fBoxLineSmooth: boolean; fColPalette: TColourSpectrum; fMaxArrowHeadHeight: double; fMaxArrowHeadRadius: double; fMaxArrowLength: double; fMaxArrowRadius: double; fMinArrowHeadHeight: double; fMinArrowHeadRadius: double; fMinArrowLength: double; fMinArrowRadius: double; fRegPath: string; fSlices: integer; fStacks: integer; public constructor Create; destructor Destroy; override; procedure LoadFromRegistry; procedure SaveToRegistry; property BoxLineAA: boolean read fBoxLineAA write fBoxLineAA; property BoxLineColour: TColor read fBoxLineColour write fBoxLineColour; property BoxLinePattern: integer read fBoxLinePattern write fBoxLinePattern; property BoxLineSmooth: boolean read fBoxLineSmooth write fBoxLineSmooth; property ColPalette: TColourSpectrum read fColPalette write fColPalette; property MaxArrowHeadHeight: double read fMaxArrowHeadHeight write fMaxArrowHeadHeight; property MaxArrowHeadRadius: double read fMaxArrowHeadRadius write fMaxArrowHeadRadius; property MaxArrowLength: double read fMaxArrowLength write fMaxArrowLength; property MaxArrowRadius: double read fMaxArrowRadius write fMaxArrowRadius; property MinArrowHeadHeight: double read fMinArrowHeadHeight write fMinArrowHeadHeight; property MinArrowHeadRadius: double read fMinArrowHeadRadius write fMinArrowHeadRadius; property MinArrowLength: double read fMinArrowLength write fMinArrowLength; property MinArrowRadius: double read fMinArrowRadius write fMinArrowRadius; property Slices: integer read fSlices write fSlices; property Stacks: integer read fStacks write fStacks; property RegPath: string read fRegPath write fRegPath; end; TGridOptions = class(TObject) private fAlpha: double; fColourMode: integer; fColPalette: TColourSpectrum; fColsBlank: TGLColor; // when initially loading a grid it is shown/hidden based on CreateVisible fCreateVisible: boolean; fDefaultDir: string; fglCol_Bottom: TGLColor; fglCol_Top: TGLColor; fModified: boolean; fName: string; fPolygonMode: integer; fPromptTexture: boolean; fRegPath: string; fSilentImport: boolean; fSilentLoad: boolean; fTileX: integer; fTileY: integer; fTwoSidedMesh: boolean; public constructor Create; destructor Destroy; override; procedure LoadFromRegistry; procedure SaveToRegistry; function GetSpectrum(dRatio, dValue: double): TColorVector; property Alpha: double read fAlpha write fAlpha; property ColourMode: integer read fColourMode write fColourMode; property ColPalette: TColourSpectrum read fColPalette write fColPalette; property ColsBlank: TGLColor read fColsBlank write fColsBlank; property CreateVisible: boolean read fCreateVisible write fCreateVisible; property Modified: boolean read fModified write fModified; property DefaultDir: string read fDefaultDir write fDefaultDir; property glCol_Bottom: TGLColor read fglCol_Bottom write fglCol_Bottom; property glCol_Top: TGLColor read fglCol_Top write fglCol_Top; property Name: string read fName write fName; property PolygonMode: integer read fPolygonMode write fPolygonMode; property PromptTexture: boolean read fPromptTexture write fPromptTexture; property RegPath: string read fRegPath write fRegPath; property SilentImport: boolean read fSilentImport write fSilentImport; property SilentLoad: boolean read fSilentLoad write fSilentLoad; property TileX: integer read fTileX write fTileX; property TileY: integer read fTileY write fTileY; property TwoSidedMesh: boolean read fTwoSidedMesh write fTwoSidedMesh; end; TGLDataUserSettings = class(TObject) private fAntialiasing: integer; fGeoColPalette: TColourSpectrum; fGeoModified: boolean; fArcInfoGrid: TGridOptions; fSurferGrid: TGridOptions; fColPalette: TColourSpectrum; fColourScaleOptions: TColourScaleOptions; fAutoFocusGrids: boolean; fAutoFocusPoints: boolean; fAutoProcess: boolean; faValue: double; fBackGroundColour: TColor; fCameraDepthOfView: double; fCameraFocalLength: double; fCameraNearPlaneBias: double; fCameraStyle: integer; fDisplayAxes: boolean; fDisplayLines: boolean; fDisplayMarkers: boolean; fDisplayPipe: boolean; fDisplayPoints: boolean; fInvertMouseWheel: boolean; fLighting: boolean; fLighting2: boolean; fLineColour: TColor; fLineMode: integer; fMarkerBoxLineAA: boolean; fMarkerBoxLineColour: TColor; fMarkerBoxLinePattern: integer; fMarkerBoxLineSmooth: boolean; fMarkerColour: TColor; fMarkerRadius: double; fMarkerWireFrame: boolean; fPointColourNull: TGLColor; fPointStyle: integer; fRenderNullPoints: boolean; fPipeRadius: double; fScaleHUD: boolean; fFocusStatus: boolean; fCameraStatus: boolean; fScaleX: double; fScaleY: double; fScaleZ: double; fShadeModel: integer; // 0 = default, 1 = flat, 2 = smooth fTwoSideLighting: boolean; // vector field properties fVectorFieldOptions: TVectorFieldOptions; public constructor Create; destructor Destroy; override; function GetScalarSpectrum(dRatio, dValue: double): TColorVector; procedure LoadFromRegistry; procedure SaveToRegistry; // 0 = colpalette procedure UpdatePalette(iMode: integer); property AntiAliasing: integer read fAntialiasing write fAntialiasing; property ColPalette: TColourSpectrum read fColPalette write fColPalette; property geocolpalette: TColourSpectrum read fGeoColPalette write fGeoColPalette; property GeoModified: boolean read fGeoModified write fGeoModified; property VectorFieldOptions: TVectorFieldOptions read fVectorFieldOptions write fVectorFieldOptions; property ColourScaleOptions: TColourScaleOptions read fColourScaleOptions write fColourScaleOptions; property ArcInfoGrid: TGridOptions read fArcInfoGrid write fArcInfoGrid; property AutoFocusGrids: boolean read fAutoFocusGrids write fAutoFocusGrids; property AutoFocusPoints: boolean read fAutoFocusPoints write fAutoFocusPoints; property AutoProcess: boolean read fAutoProcess write fAutoProcess; property aValue: double read faValue write faValue; property BackGroundColour: TColor read fBackGroundColour write fBackGroundColour; property CameraDepthOfView: double read fCameraDepthOfView write fCameraDepthOfView; property CameraFocalLength: double read fCameraFocalLength write fCameraFocalLength; property CameraNearPlaneBias: double read fCameraNearPlaneBias write fCameraNearPlaneBias; property CameraStyle: integer read fCameraStyle write fCameraStyle; property DisplayAxes: boolean read fDisplayAxes write fDisplayAxes; property DisplayLines: boolean read fDisplayLines write fDisplayLines; property DisplayMarkers: boolean read fDisplayMarkers write fDisplayMarkers; property DisplayPipe: boolean read fDisplayPipe write fDisplayPipe; property DisplayPoints: boolean read fDisplayPoints write fDisplayPoints; property InvertMouseWheel: boolean read fInvertMouseWheel write fInvertMouseWheel; property FocusStatus: boolean read fFocusStatus write fFocusStatus; property CameraStatus: boolean read fCameraStatus write fCameraStatus; property Lighting: boolean read fLighting write fLighting; property Lighting2: boolean read fLighting2 write fLighting2; property LineColour: TColor read fLineColour write fLineColour; property LineMode: integer read fLineMode write fLineMode; property MarkerBoxLineAA: boolean read fMarkerBoxLineAA write fMarkerBoxLineAA; property MarkerBoxLineColour: TColor read fMarkerBoxLineColour write fMarkerBoxLineColour; property MarkerBoxLinePattern: integer read fMarkerBoxLinePattern write fMarkerBoxLinePattern; property MarkerBoxLineSmooth: boolean read fMarkerBoxLineSmooth write fMarkerBoxLineSmooth; property MarkerColour: TColor read fMarkerColour write fMarkerColour; property MarkerRadius: double read fMarkerRadius write fMarkerRadius; property MarkerWireFrame: boolean read fMarkerWireFrame write fMarkerWireFrame; property PointColourNull: TGLColor read fPointColourNull write fPointColourNull; property PointStyle: integer read fPointStyle write fPointStyle; property PipeRadius: double read fPipeRadius write fPipeRadius; property RenderNullPoints: boolean read fRenderNullPoints write fRenderNullPoints; property ScaleHUD: boolean read fScaleHUD write fScaleHUD; property ScaleX: double read fScaleX write fScaleX; property ScaleY: double read fScaleY write fScaleY; property ScaleZ: double read fScaleZ write fScaleZ; property ShadeModel: integer read fShadeModel write fShadeModel; property SurferGrid: TGridOptions read fSurferGrid write fSurferGrid; property TwoSideLighting: boolean read fTwoSideLighting write fTwoSideLighting; end; function ReadRegBool(myReg: TRegistry; sEntry: string; bDefault: boolean): boolean; function ReadRegColour(myReg: TRegistry; sEntry: string; dCol: TColor): TColor; function ReadRegFloat(myReg: TRegistry; sEntry: string; dDefault: double): double; function ReadRegInteger(myReg: TRegistry; sEntry: string; iDefault: integer): integer; function ReadRegString(myReg: TRegistry; sEntry, sDefault: string): string; implementation // ----- ReadRegBool ----------------------------------------------------------- function ReadRegBool(myReg: TRegistry; sEntry: string; bDefault: boolean): boolean; begin if myReg.ValueExists(sEntry) then result := myReg.ReadBool(sEntry) else result := bDefault; end; // ----- ReadRegColour --------------------------------------------------------- function ReadRegColour(myReg: TRegistry; sEntry: string; dCol: TColor): TColor; begin if myReg.ValueExists(sEntry) then result := HexToColor(myReg.ReadString(sEntry)) else result := dCol; end; // ----- ReadRegFloat ---------------------------------------------------------- function ReadRegFloat(myReg: TRegistry; sEntry: string; dDefault: double): double; begin if myReg.ValueExists(sEntry) then result := myReg.ReadFloat(sEntry) else result := dDefault; end; // ----- ReadRegInteger -------------------------------------------------------- function ReadRegInteger(myReg: TRegistry; sEntry: string; iDefault: integer): integer; begin if myReg.ValueExists(sEntry) then result := myReg.ReadInteger(sEntry) else result := iDefault; end; // ----- ReadRegString --------------------------------------------------------- { ** reads the registry string defined by sEntry. Returns sDefault if not present Note myReg is assumed to be opened on the correct key } function ReadRegString(myReg: TRegistry; sEntry, sDefault: string): string; begin if myReg.ValueExists(sEntry) then result := myReg.ReadString(sEntry) else result := sDefault; end; // ============================================================================= // TColourScaleOptions Implementation // ============================================================================= constructor TColourScaleOptions.Create; begin inherited Create; end; // ----- TColourScaleOptions.Destroy ------------------------------------------- destructor TColourScaleOptions.Destroy; begin inherited Destroy; end; // ----- TColourScaleOptions.LoadFromRegistry ---------------------------------- procedure TColourScaleOptions.LoadFromRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.CreateKey(RegPath); myReg.OpenKey(RegPath, false); fVisible := ReadRegBool(myReg, 'visible', false); fPoints := ReadRegInteger(myReg, 'points', 10); fScaleSteps := ReadRegBool(myReg, 'scalesteps', true); fContinuous := ReadRegBool(myReg, 'continuous', true); fBorder := ReadRegBool(myReg, 'border', true); fScaleFormat := ReadRegString(myReg, 'scaleformat', '%5.2g'); fShowContourPoints := ReadRegBool(myReg, 'showcontourpoints', false); fAlpha := ReadRegFloat(myReg, 'alpha', 1.0); fColourScaleType := ReadRegInteger(myReg, 'scaletype', 0); myReg.CloseKey; myReg.Free; end; // ----- TColourScaleOptions.SaveToRegistry ------------------------------------ procedure TColourScaleOptions.SaveToRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.OpenKey(RegPath, false); myReg.WriteBool('visible', fVisible); myReg.WriteInteger('points', fPoints); myReg.WriteBool('scalesteps', fScaleSteps); myReg.WriteBool('continuous', fContinuous); myReg.WriteBool('border', fBorder); myReg.WriteBool('showcontourpoints', fShowContourPoints); myReg.WriteString('scaleformat', fScaleFormat); myReg.WriteFloat('alpha', fAlpha); myReg.WriteInteger('scaletype', fColourScaleType); myReg.CloseKey; myReg.Free; end; // ============================================================================= // TVectorFieldOptions Implementation // ============================================================================= // ----- TVectorFieldOptions.Create -------------------------------------------- constructor TVectorFieldOptions.Create; begin inherited Create; fColPalette := TColourSpectrum.Create; LoadFromRegistry; end; // ----- TVectorFieldOptions.Destroy ------------------------------------------- destructor TVectorFieldOptions.Destroy; begin fColPalette.Free; inherited Destroy; end; // ----- TVectorFieldOptions.LoadFromRegistry ---------------------------------- procedure TVectorFieldOptions.LoadFromRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.CreateKey(RegPath); myReg.OpenKey(RegPath, false); fBoxLineAA := ReadRegBool(myReg, 'boxlineAA', false); fBoxLineColour := ReadRegColour(myReg, 'boxlinecolour', clGray); fBoxLinePattern := ReadRegInteger(myReg, 'boxlinepattern', 65535); fBoxLineSmooth := ReadRegBool(myReg, 'boxlinesmooth', false); fMinArrowLength := ReadRegFloat(myReg, 'minarrowlength', 0.0); fMaxArrowLength := ReadRegFloat(myReg, 'maxarrowlength', 1.0); fMinArrowRadius := ReadRegFloat(myReg, 'minarrowradius', 0.0); fMaxArrowRadius := ReadRegFloat(myReg, 'maxarrowradius', 0.1); fMinArrowHeadRadius := ReadRegFloat(myReg, 'minarrowheadradius', 0.0); fMaxArrowHeadRadius := ReadRegFloat(myReg, 'maxarrowheadradius', 0.2); fMinArrowHeadHeight := ReadRegFloat(myReg, 'minarrowheadheight', 0.0); fMaxArrowHeadHeight := ReadRegFloat(myReg, 'maxarrowheadheight', 0.5); fSlices := ReadRegInteger(myReg, 'slices', 4); fStacks := ReadRegInteger(myReg, 'stacks', 1); ColPalette.SpectrumFile := ReadRegString(myReg, 'clr', ''); ColPalette.SingleColour := ReadRegColour(myReg, 'coloursingle', clGreen); ColPalette.MinColour := ReadRegColour(myReg, 'colourmin', clBlue); ColPalette.MaxColour := ReadRegColour(myReg, 'colourmax', clFuchsia); ColPalette.SpectrumMode := ReadRegInteger(myReg, 'spectrummode', 2); myReg.CloseKey; myReg.Free; end; // ----- TVectorFieldOptions.SaveToRegistry ------------------------------------ procedure TVectorFieldOptions.SaveToRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.OpenKey(RegPath, false); myReg.WriteBool('boxlineAA', fBoxLineAA); myReg.WriteString('boxlinecolour', ColorToHex(fBoxLineColour)); myReg.WriteBool('boxlinesmooth', fBoxLineSmooth); myReg.WriteInteger('boxlinepattern', fBoxLinePattern); myReg.WriteFloat('minarrowlength', fMinArrowLength); myReg.WriteFloat('maxarrowlength', fMaxArrowLength); myReg.WriteFloat('minarrowradius', fMinArrowRadius); myReg.WriteFloat('minarrowradius', fMinArrowRadius); myReg.WriteFloat('minarrowheadradius', fMinArrowHeadRadius); myReg.WriteFloat('maxarrowheadradius', fMaxArrowHeadRadius); myReg.WriteFloat('minarrowheadheight', fMinArrowHeadHeight); myReg.WriteFloat('maxarrowheadheight', fMaxArrowHeadHeight); myReg.WriteInteger('slices', fSlices); myReg.WriteInteger('stacks', fStacks); myReg.WriteString('clr', ColPalette.SpectrumFile); myReg.WriteString('coloursingle', ColorToHex(ColPalette.SingleColour)); myReg.WriteString('colourmin', ColorToHex(ColPalette.MinColour)); myReg.WriteString('colourmax', ColorToHex(ColPalette.MaxColour)); myReg.WriteInteger('spectrummode', ColPalette.SpectrumMode); myReg.CloseKey; myReg.Free; end; // ============================================================================= // TGridOptions Implementation // ============================================================================= // ----- TGridOptions.Create --------------------------------------------------- constructor TGridOptions.Create; begin inherited Create; fColPalette := TColourSpectrum.Create; fglCol_Bottom := TGLColor.Create(nil); fglCol_Top := TGLColor.Create(nil); fColsBlank := TGLColor.Create(nil); fModified := true; end; // ----- TGridOptions.Destroy -------------------------------------------------- destructor TGridOptions.Destroy; begin fColPalette.Free; fglCol_Bottom.Free; fglCol_Top.Free; fColsBlank.Free; inherited Destroy; end; // ----- TGridOptions.LoadFromRegistry ----------------------------------------- procedure TGridOptions.LoadFromRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.CreateKey(RegPath); myReg.OpenKey(RegPath, false); fAlpha := ReadRegFloat(myReg, 'alpha', 1.0); fCreateVisible := ReadRegBool(myReg, 'createvisible', true); fTileX := ReadRegInteger(myReg, 'tilex', 1); fTileY := ReadRegInteger(myReg, 'tiley', 1); fPromptTexture := ReadRegBool(myReg, 'prompttexture', true); fColourMode := ReadRegInteger(myReg, 'colourmode', 1); fTwoSidedMesh := ReadRegBool(myReg, 'twosidedmesh', true); fDefaultDir := ReadRegString(myReg, 'defaultdir', ExtractFilePath(ParamStr(0)) + 'samples\' + fName + '\'); fSilentImport := ReadRegBool(myReg, 'silentimport', false); fSilentLoad := ReadRegBool(myReg, 'silentload', true); ColPalette.SpectrumFile := ReadRegString(myReg, 'clr', ''); ColPalette.SingleColour := ReadRegColour(myReg, 'coloursingle', clGreen); ColPalette.MinColour := ReadRegColour(myReg, 'colourmin', clBlue); ColPalette.MaxColour := ReadRegColour(myReg, 'colourmax', clFuchsia); ColPalette.SpectrumMode := ReadRegInteger(myReg, 'spectrummode', 2); fColsBlank.AsWinColor := ReadRegColour(myReg, 'colourblank', clSilver); fPolygonMode := ReadRegInteger(myReg, 'polygonmode', 0); myReg.CloseKey; myReg.Free; end; // ----- TGridOptions.SaveToRegistry ------------------------------------------- procedure TGridOptions.SaveToRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.OpenKey(RegPath, false); myReg.WriteFloat('alpha', fAlpha); myReg.WriteBool('createvisible', fCreateVisible); myReg.WriteInteger('tilex', fTileX); myReg.WriteInteger('tiley', fTileY); myReg.WriteBool('prompttexture', fPromptTexture); myReg.WriteInteger('colourmode', fColourMode); myReg.WriteBool('twosidedmesh', fTwoSidedMesh); myReg.WriteString('defaultdir', fDefaultDir); myReg.WriteBool('silentimport', fSilentImport); myReg.WriteBool('silentload', fSilentLoad); myReg.WriteString('clr', ColPalette.SpectrumFile); myReg.WriteString('coloursingle', ColorToHex(ColPalette.SingleColour)); myReg.WriteString('colourmin', ColorToHex(ColPalette.MinColour)); myReg.WriteString('colourmax', ColorToHex(ColPalette.MaxColour)); myReg.WriteString('colourblank', ColorToHex(fColsBlank.AsWinColor)); myReg.WriteInteger('spectrummode', ColPalette.SpectrumMode); myReg.WriteInteger('polygonmode', fPolygonMode); myReg.CloseKey; myReg.Free; end; // ----- TGridOptions.GetSpectrum ---------------------------------------------- function TGridOptions.GetSpectrum(dRatio, dValue: double): TColorVector; begin case ColPalette.SpectrumMode of // single colour 0: result := ColPalette.GetColourVector(dValue, true); // simple minimum/maximum 1: result := ColPalette.GetColourVector(dValue, true); // rainbow/inverse rainbow 2, 3: result := ColPalette.GetColourVector(dValue, (ColPalette.SpectrumMode = 2)); // palettee 4, 5: result := ColPalette.GetColourVector(dValue, (ColPalette.SpectrumMode = 4)); end; end; // ============================================================================= // ----- TGLDataUserSettings.Create -------------------------------------------- constructor TGLDataUserSettings.Create; begin inherited Create; SurferGrid := TGridOptions.Create; SurferGrid.Name := 'surfer'; SurferGrid.RegPath := CREGISTRYKEY + '\grids\surfer'; ArcInfoGrid := TGridOptions.Create; ArcInfoGrid.Name := 'arcinfo'; ArcInfoGrid.RegPath := CREGISTRYKEY + '\grids\arcinfo'; ColourScaleOptions := TColourScaleOptions.Create; ColourScaleOptions.RegPath := CREGISTRYKEY + '\display\colourscale'; PointColourNull := TGLColor.Create(nil); ColPalette := TColourSpectrum.Create; // geothermal stuff should be put in a different class geocolpalette := TColourSpectrum.Create; fGeoModified := true; VectorFieldOptions := TVectorFieldOptions.Create; VectorFieldOptions.RegPath := CREGISTRYKEY + '\vectorfield'; end; // ----- TGLDataUserSettings.Destroy ------------------------------------------- destructor TGLDataUserSettings.Destroy; begin VectorFieldOptions.Free; SurferGrid.Free; ArcInfoGrid.Free; ColourScaleOptions.Free; PointColourNull.Free; ColPalette.Free; geocolpalette.Free; inherited Destroy; end; // ----- TGLDataUserSettings.GetScalarSpectrum ------------------------------- function TGLDataUserSettings.GetScalarSpectrum(dRatio, dValue: double) : TColorVector; begin case ColPalette.SpectrumMode of // single colour 0: result := ColPalette.GetColourVector(dValue, true); // simple minimum/maximum 1: result := ColPalette.GetColourVector(dValue, true); // rainbow and inverse rainbow spectrum 2, 3: result := ColPalette.GetColourVector(dValue, (ColPalette.SpectrumMode = 2)); // using a palette 4, 5: result := ColPalette.GetColourVector(dValue, (ColPalette.SpectrumMode = 4)) end; end; // ----- TGLDataUserSettings.LoadFromRegistry ---------------------------------- procedure TGLDataUserSettings.LoadFromRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; myReg.OpenKey(CREGISTRYKEY + '\general', true); fAutoProcess := ReadRegBool(myReg, 'autoprocess', true); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\interface', true); fFocusStatus := ReadRegBool(myReg, 'focusstatus', true); fCameraStatus := ReadRegBool(myReg, 'camerastatus', true); fInvertMouseWheel := ReadRegBool(myReg, 'invertmousewheel', false); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\coordinates', true); faValue := ReadRegFloat(myReg, 'aValue', 1.0); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\display', true); fAntialiasing := ReadRegInteger(myReg, 'antialiasing', 1); // default fBackGroundColour := ReadRegColour(myReg, 'backgroundcolour', clWhite); fTwoSideLighting := ReadRegBool(myReg, 'twosidelighting', false); fShadeModel := ReadRegInteger(myReg, 'shademodel', 0); // default myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\display\axes', true); fDisplayAxes := ReadRegBool(myReg, 'displayaxes', true); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\display\camera', true); fCameraStyle := ReadRegInteger(myReg, 'camerastyle', 2); fCameraFocalLength := ReadRegFloat(myReg, 'focallength', 50.0); fCameraDepthOfView := ReadRegFloat(myReg, 'depthofview', 100.0); fCameraNearPlaneBias := ReadRegFloat(myReg, 'nearplanebias', 1.0); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\display\lighting', true); fLighting := ReadRegBool(myReg, 'enabled', true); fLighting2 := ReadRegBool(myReg, 'enabled2', true); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\data\markers', true); fDisplayMarkers := ReadRegBool(myReg, 'displaymarkers', true); fDisplayPoints := ReadRegBool(myReg, 'displaypoints', true); fMarkerBoxLineAA := ReadRegBool(myReg, 'markerboxlineaa', false); fMarkerBoxLineColour := ReadRegColour(myReg, 'markerboxlinecolour', clGray); fMarkerBoxLinePattern := ReadRegInteger(myReg, 'markerboxlinepattern', 65535); fMarkerBoxLineSmooth := ReadRegBool(myReg, 'markerboxlinesmooth', false); fMarkerRadius := ReadRegFloat(myReg, 'radius', 0.01); fMarkerColour := ReadRegColour(myReg, 'markercolour', clRed); fMarkerWireFrame := ReadRegBool(myReg, 'wireframe', false); fAutoFocusPoints := ReadRegBool(myReg, 'autofocus', true); // obtain spectrum file first ! ColPalette.SpectrumFile := ReadRegString(myReg, 'clr', ''); ColPalette.SingleColour := ReadRegColour(myReg, 'pointcoloursingle', clGreen); ColPalette.MinColour := ReadRegColour(myReg, 'pointcolourmin', clBlue); ColPalette.MaxColour := ReadRegColour(myReg, 'pointcolourmax', clRed); ColPalette.SpectrumMode := ReadRegInteger(myReg, 'pointspectrummode', 2); fPointColourNull.AsWinColor := ReadRegColour(myReg, 'pointcolournull', clBlack); fRenderNullPoints := ReadRegBool(myReg, 'rendernullpoints', true); fPointStyle := ReadRegInteger(myReg, 'pointstyle', 3); myReg.CloseKey; // geothermal grid spectrum file myReg.OpenKey(CREGISTRYKEY + '\geothermal', true); geocolpalette.SpectrumFile := ReadRegString(myReg, 'clr', ''); geocolpalette.SingleColour := ReadRegColour(myReg, 'pointcoloursingle', clGreen); geocolpalette.MinColour := ReadRegColour(myReg, 'pointcolourmin', clBlue); geocolpalette.MaxColour := ReadRegColour(myReg, 'pointcolourmax', clRed); geocolpalette.SpectrumMode := ReadRegInteger(myReg, 'pointspectrummode', 2); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\data\lines', true); fDisplayLines := ReadRegBool(myReg, 'displaylines', true); fLineColour := ReadRegColour(myReg, 'linecolour', clBlue); fLineMode := ReadRegInteger(myReg, 'linemode', 1); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\data\pipe', true); fDisplayPipe := ReadRegBool(myReg, 'displaypipe', false); fPipeRadius := ReadRegFloat(myReg, 'radius', 0.01); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\display\scale', true); fScaleX := ReadRegFloat(myReg, 'scaleX', 1.0); fScaleY := ReadRegFloat(myReg, 'scaleY', 1.0); fScaleZ := ReadRegFloat(myReg, 'scaleZ', 1.0); fScaleHUD := ReadRegBool(myReg, 'scaleHUD', true); myReg.CloseKey; myReg.OpenKey(CREGISTRYKEY + '\display\scale', true); fAutoFocusGrids := ReadRegBool(myReg, 'autofocus', true); myReg.CloseKey; myReg.Free; ArcInfoGrid.LoadFromRegistry; SurferGrid.LoadFromRegistry; ColourScaleOptions.LoadFromRegistry; VectorFieldOptions.LoadFromRegistry; end; // ----- TGLDataUserSettings.SaveToRegistry ------------------------------------ procedure TGLDataUserSettings.SaveToRegistry; var myReg: TRegistry; begin myReg := TRegistry.Create; with myReg do begin // general options OpenKey(CREGISTRYKEY + '\general', true); WriteBool('autoprocess', fAutoProcess); CloseKey; // interface options OpenKey(CREGISTRYKEY + '\interface', true); WriteBool('invertmousewheel', fInvertMouseWheel); WriteBool('focusstatus', fFocusStatus); WriteBool('camerastatus', fCameraStatus); CloseKey; // co-ordinates options OpenKey(CREGISTRYKEY + '\coordinates', true); WriteFloat('aValue', faValue); CloseKey; // display options OpenKey(CREGISTRYKEY + '\display', true); WriteInteger('antialiasing', fAntialiasing); WriteString('backgroundcolour', ColorToHex(fBackGroundColour)); WriteBool('twosidelighting', fTwoSideLighting); WriteInteger('shademodel', fShadeModel); CloseKey; OpenKey(CREGISTRYKEY + '\display\axes', true); WriteBool('displayaxes', fDisplayAxes); CloseKey; OpenKey(CREGISTRYKEY + '\display\camera', true); WriteInteger('camerastyle', fCameraStyle); WriteFloat('focallength', fCameraFocalLength); WriteFloat('depthofview', fCameraDepthOfView); WriteFloat('nearplanebias', fCameraNearPlaneBias); CloseKey; OpenKey(CREGISTRYKEY + '\display\lighting', true); WriteBool('enabled', fLighting); WriteBool('enabled2', fLighting2); CloseKey; OpenKey(CREGISTRYKEY + '\display\scale', true); WriteFloat('scaleX', fScaleX); WriteFloat('scaleY', fScaleY); WriteFloat('scaleZ', fScaleZ); WriteBool('scalehud', fScaleHUD); CloseKey; // data options OpenKey(CREGISTRYKEY + '\data\markers', true); WriteBool('markerboxlineaa', fMarkerBoxLineAA); WriteString('markerboxlinecolour', ColorToHex(fMarkerBoxLineColour)); WriteInteger('markerboxlinepattern', fMarkerBoxLinePattern); WriteBool('markerboxlinesmooth', fMarkerBoxLineSmooth); WriteBool('displaymarkers', fDisplayMarkers); WriteBool('displaypoints', fDisplayPoints); WriteFloat('radius', fMarkerRadius); WriteString('markercolour', ColorToHex(fMarkerColour)); WriteBool('wireframe', fMarkerWireFrame); WriteBool('autofocus', fAutoFocusPoints); WriteBool('rendernullpoints', fRenderNullPoints); WriteString('pointcolournull', ColorToHex(fPointColourNull.AsWinColor)); WriteString('pointcoloursingle', ColorToHex(ColPalette.SingleColour)); WriteString('pointcolourmin', ColorToHex(ColPalette.MinColour)); WriteString('pointcolourmax', ColorToHex(ColPalette.MaxColour)); WriteInteger('pointspectrummode', ColPalette.SpectrumMode); WriteInteger('pointstyle', fPointStyle); WriteString('clr', ColPalette.SpectrumFile); CloseKey; OpenKey(CREGISTRYKEY + '\data\lines', true); WriteBool('displaylines', fDisplayLines); WriteString('linecolour', ColorToHex(fLineColour)); WriteInteger('linemode', fLineMode); CloseKey; OpenKey(CREGISTRYKEY + '\data\pipe', true); WriteBool('displaypipe', fDisplayPipe); WriteFloat('radius', fPipeRadius); CloseKey; // grid options OpenKey(CREGISTRYKEY + '\grids', true); WriteBool('autofocus', fAutoFocusGrids); CloseKey; // geothermal options OpenKey(CREGISTRYKEY + '\geothermal', true); WriteString('pointcoloursingle', ColorToHex(geocolpalette.SingleColour)); WriteString('pointcolourmin', ColorToHex(geocolpalette.MinColour)); WriteString('pointcolourmax', ColorToHex(geocolpalette.MaxColour)); WriteInteger('pointspectrummode', geocolpalette.SpectrumMode); WriteString('clr', geocolpalette.SpectrumFile); CloseKey; Free; end; ArcInfoGrid.SaveToRegistry; SurferGrid.SaveToRegistry; ColourScaleOptions.SaveToRegistry; VectorFieldOptions.SaveToRegistry; end; // 0 = colpalette // ----- TGLDataUserSettings.UpdatePalette ------------------------------------- procedure TGLDataUserSettings.UpdatePalette(iMode: integer); begin case iMode of // for scalar points 0: begin ColPalette.Continuous := ColourScaleOptions.Continuous; ColPalette.Border := ColourScaleOptions.Border; ColPalette.ScaleWithContours := ColourScaleOptions.ShowContourPoints; ColPalette.LabelFormat := ColourScaleOptions.Scaleformat; ColPalette.CLRLegend := not ColourScaleOptions.ScaleSteps; ColPalette.LabelCount := ColourScaleOptions.Points; ColPalette.MakePalette; end; // vector points 1: begin VectorFieldOptions.ColPalette.Continuous := ColourScaleOptions.Continuous; VectorFieldOptions.ColPalette.Border := ColourScaleOptions.Border; VectorFieldOptions.ColPalette.ScaleWithContours := ColourScaleOptions.ShowContourPoints; VectorFieldOptions.ColPalette.LabelFormat := ColourScaleOptions.Scaleformat; VectorFieldOptions.ColPalette.CLRLegend := not ColourScaleOptions.ScaleSteps; VectorFieldOptions.ColPalette.LabelCount := ColourScaleOptions.Points; VectorFieldOptions.ColPalette.MakePalette; end; // surfer grid 2: begin SurferGrid.ColPalette.Continuous := ColourScaleOptions.Continuous; SurferGrid.ColPalette.Border := ColourScaleOptions.Border; SurferGrid.ColPalette.ScaleWithContours := ColourScaleOptions.ShowContourPoints; SurferGrid.ColPalette.LabelFormat := ColourScaleOptions.Scaleformat; SurferGrid.ColPalette.CLRLegend := not ColourScaleOptions.ScaleSteps; SurferGrid.ColPalette.LabelCount := ColourScaleOptions.Points; SurferGrid.ColPalette.MakePalette; end; // arcinfo grid 3: begin ArcInfoGrid.ColPalette.Continuous := ColourScaleOptions.Continuous; ArcInfoGrid.ColPalette.Border := ColourScaleOptions.Border; ArcInfoGrid.ColPalette.ScaleWithContours := ColourScaleOptions.ShowContourPoints; ArcInfoGrid.ColPalette.LabelFormat := ColourScaleOptions.Scaleformat; ArcInfoGrid.ColPalette.CLRLegend := not ColourScaleOptions.ScaleSteps; ArcInfoGrid.ColPalette.LabelCount := ColourScaleOptions.Points; ArcInfoGrid.ColPalette.MakePalette; end; // geothermal 4: begin geocolpalette.Continuous := ColourScaleOptions.Continuous; geocolpalette.Border := ColourScaleOptions.Border; geocolpalette.ScaleWithContours := ColourScaleOptions.ShowContourPoints; geocolpalette.LabelFormat := ColourScaleOptions.Scaleformat; geocolpalette.CLRLegend := not ColourScaleOptions.ScaleSteps; geocolpalette.LabelCount := ColourScaleOptions.Points; geocolpalette.MakePalette; end; end; end; // ============================================================================= end.
unit uFrmExport; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, cxLookAndFeelPainters, cxButtons, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTP; type TFrmExport = class(TForm) pnlComple: TPanel; lblResultado: TLabel; pbExportacao: TProgressBar; chkEstoque: TCheckBox; chkFabricante: TCheckBox; PTitle: TPanel; ShapeImage: TShape; lblTitulo: TLabel; ImageClass: TImage; mmDescricao: TMemo; chkQuantidade: TCheckBox; Image11: TImage; Image2: TImage; Image10: TImage; imgLine: TImage; Image1: TImage; chkCategoria: TCheckBox; chkProduto: TCheckBox; chkSKU: TCheckBox; btnExportar: TcxButton; btnFechar: TcxButton; procedure btnExportarClick(Sender: TObject); procedure btnFecharClick(Sender: TObject); procedure chkEstoqueClick(Sender: TObject); procedure Button1Click(Sender: TObject); private function FormatarTextoLink(ATexto: String): String; function FormatarTextoDescricao(ATexto: String): String; procedure SincronizarCategoria; procedure SincronizarProduto; procedure SincronizarSKU; public function Start: Boolean; procedure SincronizarFabricante; procedure SincronizarEstoque; procedure SincronizarQuantidade; end; var FrmExport: TFrmExport; implementation uses uDM, uEplataformaSyncClasses, uEplataformaEntidadeClasses, DB, ADODB, uFrmLog; {$R *.dfm} { TFrmExport } function TFrmExport.Start: Boolean; begin DM.OpenConnection; chkEstoqueClick(Self); ShowModal; DM.CloseConnection; Result := True; end; procedure TFrmExport.SincronizarCategoria; var epCategoria: TepCategoria; epCategoriaSync: TepCategoriaSync; begin epCategoriaSync := TepCategoriaSync.Create; try epCategoriaSync.Init(DM.HTTPReqRespCatalog, DM.ECommerceInfo.FURL, DM.ECommerceInfo.FUser, DM.ECommerceInfo.FPW); with DM.quCategory do try if Active then Close; Open; First; lblResultado.Caption := 'Sincronizando Categorias...'; pbExportacao.Position := 0; pbExportacao.Max := RecordCount; Application.ProcessMessages; epCategoria := TepCategoria.Create; try while not EOF do begin try pbExportacao.Position := pbExportacao.Position + 1; Application.ProcessMessages; epCategoria.IDCategoria := DM.quCategory.FieldByName('IDGroup').AsInteger; if epCategoriaSync.Verificar(epCategoria) then begin epCategoria := TepCategoria(epCategoriaSync.Obter(epCategoria)); { if DM.ECommerceInfo.FExportarDepartamento then begin epCategoria.Nome := DM.quCategory.FieldByName('Department').AsString; epCategoria.FlagAtiva := not DM.quCategory.FieldByName('DepDesativado').AsBoolean; end else begin epCategoria.Nome := DM.quCategory.FieldByName('Name').AsString; epCategoria.FlagAtiva := not DM.quCategory.FieldByName('CatDesativado').AsBoolean; end; } epCategoria.Nome := DM.quCategory.FieldByName('Name').AsString; epCategoria.FlagAtiva := not DM.quCategory.FieldByName('CatDesativado').AsBoolean; epCategoriaSync.Alterar(epCategoria); end else if (not DM.quCategory.FieldByName('DepDesativado').AsBoolean) and (not DM.quCategory.FieldByName('CatDesativado').AsBoolean) then begin { if DM.ECommerceInfo.FExportarDepartamento then begin epCategoria.IDCategoria := DM.quCategory.FieldByName('IDDepartment').AsInteger; epCategoria.Nome := DM.quCategory.FieldByName('Department').AsString; epCategoria.FlagAtiva := not DM.quCategory.FieldByName('DepDesativado').AsBoolean; end else begin epCategoria.IDCategoria := DM.quCategory.FieldByName('IDGroup').AsInteger; epCategoria.Nome := DM.quCategory.FieldByName('Name').AsString; epCategoria.FlagAtiva := not DM.quCategory.FieldByName('CatDesativado').AsBoolean; end; } epCategoria.IDCategoria := DM.quCategory.FieldByName('IDGroup').AsInteger; epCategoria.Nome := DM.quCategory.FieldByName('Name').AsString; epCategoria.FlagAtiva := not DM.quCategory.FieldByName('CatDesativado').AsBoolean; epCategoria.IDDepartamento := 0; epCategoria.Ordem := 0; epCategoria.FlagMenu := True; epCategoria.Texto := ''; epCategoria.MargemLucro := 0; epCategoria.PalavraChave := ''; epCategoria.TituloSite := ''; epCategoria.ModoExibicaoProduto := ''; epCategoria.FlagExisteProduto := False; epCategoria.FlagFiltroMarca := False; epCategoria.FlagAtivaMenuLink := True; epCategoriaSync.Criar(epCategoria); end; except on E: Exception do DM.SaveToLog(epCategoria.IDCategoria, E.Message); end; Next; end; finally FreeAndNil(epCategoria); end; Close; except raise; end; finally FreeAndNil(epCategoriaSync); end; end; procedure TFrmExport.btnExportarClick(Sender: TObject); var bResult : Boolean; begin if chkFabricante.Checked or chkEstoque.Checked or chkQuantidade.Checked then try DM.AppendLog('Exportação.'); Cursor := crHourGlass; lblResultado.Caption := ''; lblResultado.Visible := True; pbExportacao.Visible := True; try if chkFabricante.Checked then SincronizarFabricante; if chkEstoque.Checked then SincronizarEstoque; if chkQuantidade.Checked then SincronizarQuantidade; bResult := True; except on E: Exception do begin bResult := False; DM.PostLog('Erro Exportação: ' + E.Message); DM.SendEmailLogText(DM.ECommerceInfo.FURL, 'Erro Exportação', ''); end; end; finally Cursor := crDefault; lblResultado.Visible := False; pbExportacao.Visible := False; if bResult then begin DM.PostLog('Exportação.'); MessageDlg('Exportação concluída com sucesso!', mtConfirmation, [mbOK], 0); end; end else ShowMessage('Nenhuma opção foi marcada!'); end; procedure TFrmExport.btnFecharClick(Sender: TObject); begin Close; end; procedure TFrmExport.SincronizarFabricante; var epMarca: TepMarca; epMarcaSync: TepMarcaSync; begin epMarcaSync := TepMarcaSync.Create; try epMarcaSync.Init(DM.HTTPReqRespCatalog, DM.ECommerceInfo.FURL, DM.ECommerceInfo.FUser, DM.ECommerceInfo.FPW); with DM.quManufacturer do try if Active then Close; Open; First; lblResultado.Caption := 'Sincronizando Fabricantes...'; pbExportacao.Position := 0; pbExportacao.Max := RecordCount; Application.ProcessMessages; epMarca := TepMarca.Create; try while not EOF do begin try pbExportacao.Position := pbExportacao.Position + 1; Application.ProcessMessages; epMarca.IDMarca := DM.quManufacturer.FieldByName('IDPessoa').AsInteger; if epMarcaSync.Verificar(epMarca) then begin epMarca := TepMarca(epMarcaSync.Obter(epMarca)); epMarca.Nome := DM.quManufacturer.FieldByName('Pessoa').AsString; epMarca.FlagAtiva := not DM.quManufacturer.FieldByName('Desativado').AsBoolean; epMarcaSync.Alterar(epMarca); end else if not DM.quManufacturer.FieldByName('Desativado').AsBoolean then begin epMarca.Nome := DM.quManufacturer.FieldByName('Pessoa').AsString; epMarca.FlagAtiva := not DM.quManufacturer.FieldByName('Desativado').AsBoolean; epMarcaSync.Criar(epMarca); end; except on E: Exception do DM.SaveToLog(epMarca.IDMarca, E.Message); end; Next; end; finally FreeAndNil(epMarca); end; Close; except raise; end; finally FreeAndNil(epMarcaSync); end; end; procedure TFrmExport.SincronizarProduto; var epProduto: TepProduto; epProdutoSync: TepProdutoSync; begin epProdutoSync := TepProdutoSync.Create; try epProdutoSync.Init(DM.HTTPReqRespCatalog, DM.ECommerceInfo.FURL, DM.ECommerceInfo.FUser, DM.ECommerceInfo.FPW); with DM.quProduct do try if Active then Close; Parameters.ParamByName('IDStore').Value := DM.MRInfo.FIDStore; Open; First; lblResultado.Caption := 'Sincronizando Produtos...'; pbExportacao.Position := 0; pbExportacao.Max := RecordCount; Application.ProcessMessages; epProduto := TepProduto.Create; try while not EOF do begin epProduto.IDProduto := DM.quProduct.FieldByName('IDModel').AsInteger; if DM.quProduct.FieldByName('IDFabricante').AsInteger > 0 then begin try pbExportacao.Position := pbExportacao.Position + 1; Application.ProcessMessages; //epProduto.IDProduto := DM.quProduct.FieldByName('IDModel').AsInteger; if epProdutoSync.Verificar(epProduto) then begin TepEntidade(epProduto) := epProdutoSync.Obter(epProduto); epProduto.Nome := FormatarTextoDescricao(DM.quProduct.FieldByName('Description').AsString); epProduto.TextoLink := FormatarTextoLink(DM.quProduct.FieldByName('Description').AsString)+'-'+InttoStr(epProduto.IDProduto); { if DM.ECommerceInfo.FExportarDepartamento then begin epProduto.IDCategoria := DM.quProduct.FieldByName('IDDepartment').AsInteger; epProduto.TextoCategoria := DM.quProduct.FieldByName('Department').AsString; end else begin epProduto.IDCategoria := DM.quProduct.FieldByName('IDCategoria').AsInteger; epProduto.TextoCategoria := DM.quProduct.FieldByName('Categoria').AsString; end; } { SOMENTE ATUALIZA A CATEGORIA SE A OPÇÃO "Enviar todos os produtos para uma única categoria." NÃO ESTIVER SELECIONADA } if not DM.ECommerceInfo.FProdutoUnicaCategoria then begin epProduto.IDCategoria := DM.quProduct.FieldByName('IDCategoria').AsInteger; epProduto.TextoCategoria := DM.quProduct.FieldByName('Categoria').AsString; end; epProduto.IDMarca := DM.quProduct.FieldByName('IDFabricante').AsInteger; epProduto.PrecoSkuAte := DM.quProduct.FieldByName('SellingPrice').AsCurrency; epProduto.TextoMarca := DM.quProduct.FieldByName('Fabricante').AsString; epProduto.CodigoReferencia := FormatarTextoDescricao(DM.quProduct.FieldByName('Model').AsString); epProduto.FlagAtiva := not DM.quProduct.FieldByName('Desativado').AsBoolean; epProduto.Skus := TepSKULista.Create; epProdutoSync.Alterar(epProduto); end else if not DM.quProduct.FieldByName('Desativado').AsBoolean then begin epProduto.Nome := FormatarTextoDescricao(DM.quProduct.FieldByName('Description').AsString); epProduto.Texto := FormatarTextoDescricao(DM.quProduct.FieldByName('Description').AsString); epProduto.TextoLink := FormatarTextoLink(DM.quProduct.FieldByName('Description').AsString)+'-'+InttoStr(epProduto.IDProduto); { if DM.ECommerceInfo.FExportarDepartamento then begin epProduto.IDCategoria := DM.quProduct.FieldByName('IDDepartment').AsInteger; epProduto.TextoCategoria := DM.quProduct.FieldByName('Department').AsString; end else begin epProduto.IDCategoria := DM.quProduct.FieldByName('IDCategoria').AsInteger; epProduto.TextoCategoria := DM.quProduct.FieldByName('Categoria').AsString; end; } if DM.ECommerceInfo.FProdutoUnicaCategoria then begin epProduto.IDCategoria := DM.ECommerceInfo.FCategoriaUnica; epProduto.TextoCategoria := DM.ECommerceInfo.FDescCategoriaUnica; end else begin epProduto.IDCategoria := DM.quProduct.FieldByName('IDCategoria').AsInteger; epProduto.TextoCategoria := DM.quProduct.FieldByName('Categoria').AsString; end; epProduto.IDMarca := DM.quProduct.FieldByName('IDFabricante').AsInteger; epProduto.PrecoSkuDe := DM.quProduct.FieldByName('SellingPrice').AsCurrency; epProduto.PrecoSkuAte := DM.quProduct.FieldByName('SellingPrice').AsCurrency; epProduto.TextoMarca := DM.quProduct.FieldByName('Fabricante').AsString; epProduto.TextoCategoria := DM.quProduct.FieldByName('Categoria').AsString; epProduto.CodigoReferencia := FormatarTextoDescricao(DM.quProduct.FieldByName('Model').AsString); epProduto.IDProdutoEdicao := 0; epProduto.PalavraChave := ''; epProduto.TituloSite := ''; epProduto.IDAdministradorEdicao := 0; epProduto.IDAdministradorAprovado := 0; epProduto.IDFornecedor := 0; epProduto.IDDepartamento := 0; epProduto.IDLinha := 0; epProduto.FlagExibe := False; epProduto.FlagSorteiaSku := False; epProduto.FlagAtiva := False; epProduto.Prioridade := 0; epProduto.PalavraChaveMarca := ''; epProduto.Ordenacao := ''; epProduto.TextoDepartamento := ''; epProduto.NomeCompleto := ''; epProduto.Skus := TepSKULista.Create; epProdutoSync.Criar(epProduto); end; except on E: Exception do DM.SaveToLog(epProduto.IDProduto, E.Message); end; end //FIM if DM.quProduct.FieldByName('IDFabricante').AsInteger > 0 then else begin //PRODUTO SEM FABRICANTE - GERO LOG DE ERRO. if not DM.quProduct.FieldByName('Desativado').AsBoolean then DM.SaveToLog(epProduto.IDProduto, 'Não foi possível criar/atualizar o produto. Motivo: PRODUTO SEM FABRICANTE RELACIONADO.'); end; Next; end; finally FreeAndNil(epProduto); end; Close; except raise; end; finally FreeAndNil(epProdutoSync); end; end; procedure TFrmExport.SincronizarSKU; var epSKU: TepSKU; epSKUSync: TepSKUSync; begin epSKUSync := TepSKUSync.Create; try epSKUSync.Init(DM.HTTPReqRespCatalog, DM.ECommerceInfo.FURL, DM.ECommerceInfo.FUser, DM.ECommerceInfo.FPW); with DM.quSKU do try if Active then Close; Parameters.ParamByName('IDStore').Value := DM.MRInfo.FIDStore; Open; First; lblResultado.Caption := 'Sincronizando SKUs...'; pbExportacao.Position := 0; pbExportacao.Max := RecordCount; Application.ProcessMessages; epSKU := TepSKU.Create; try while not EOF do begin epSKU.IDSku := DM.quSKU.FieldByName('IDModel').AsInteger; if DM.quSKU.FieldByName('IDFabricante').AsInteger > 0 then begin try pbExportacao.Position := pbExportacao.Position + 1; Application.ProcessMessages; //epSKU.IDSku := DM.quSKU.FieldByName('IDModel').AsInteger; if epSKUSync.Verificar(epSKU) then begin TepEntidade(epSKU) := epSKUSync.Obter(epSKU); if DM.quSKU.FieldByName('IDModelParent').AsInteger = 0 then begin epSKU.IDProduto := DM.quSKU.FieldByName('IDModel').AsInteger; epSKU.Nome := FormatarTextoDescricao(DM.quSKU.FieldByName('Description').AsString); end else epSKU.IDProduto := DM.quSKU.FieldByName('IDModelParent').AsInteger; epSKU.Nome := FormatarTextoDescricao(DM.quSKU.FieldByName('SizeName').AsString) + '-' + (DM.quSKU.FieldByName('Color').AsString); epSKU.Texto := FormatarTextoDescricao(DM.quSKU.FieldByName('Description').AsString); epSKU.PrecoVenda := DM.quSKU.FieldByName('SellingPrice').AsCurrency; epSKU.PrecoCusto := DM.quSKU.FieldByName('VendorCost').AsCurrency; epSKU.CodigoReferencia := FormatarTextoDescricao(DM.quSKU.FieldByName('Model').AsString); epSKU.Ean13 := DM.quSKU.FieldByName('Barcode').AsString; epSKU.FlagAtiva := not DM.quSKU.FieldByName('Desativado').AsBoolean; epSKU.FlagAtivaERP := not DM.quSKU.FieldByName('Desativado').AsBoolean; epSKUSync.Alterar(epSKU); end else if not DM.quSKU.FieldByName('Desativado').AsBoolean then begin if DM.quSKU.FieldByName('IDModelParent').AsInteger = 0 then begin epSKU.IDProduto := DM.quSKU.FieldByName('IDModel').AsInteger; epSKU.Nome := FormatarTextoDescricao(DM.quSKU.FieldByName('Description').AsString); end else epSKU.IDProduto := DM.quSKU.FieldByName('IDModelParent').AsInteger; epSKU.Nome := FormatarTextoDescricao(DM.quSKU.FieldByName('SizeName').AsString) + '-' + (DM.quSKU.FieldByName('Color').AsString); epSKU.Texto := FormatarTextoDescricao(DM.quSKU.FieldByName('Description').AsString); epSKU.PrecoAnterior := DM.quSKU.FieldByName('SellingPrice').AsCurrency; epSKU.PrecoVenda := DM.quSKU.FieldByName('SellingPrice').AsCurrency; epSKU.PrecoCusto := DM.quSKU.FieldByName('VendorCost').AsCurrency; epSKU.CodigoReferencia := FormatarTextoDescricao(DM.quSKU.FieldByName('Model').AsString); epSKU.Ean13 := DM.quSKU.FieldByName('Barcode').AsString; epSKU.FlagAtiva := False; //not DM.quSKU.FieldByName('Desativado').AsBoolean; epSKU.FlagAtivaERP := True; //not DM.quSKU.FieldByName('Desativado').AsBoolean; epSKU.IDSkuEdicao := 0; epSKU.IDAdministradorEdicao := 0; epSKU.IDAdministradorAprovado := 0; epSKU.IDFreteModalTipo := 1; epSKU.FlagKit := False; epSKU.Peso := 0; epSKU.Altura := 0; epSKU.Largura := 0; epSKU.Comprimento := 0; epSKU.PesoCubico := 0; epSKU.DataCadastro := 0; epSKU.PesoReal := 0; epSKU.AlturaReal := 0; epSKU.LarguraReal := 0; epSKU.ComprimentoReal := 0; epSKU.DepartamentoGerencial := ''; epSKU.SetorGerencial := ''; epSKU.IDSkuCondicaoComercial := 0; epSKUSync.Criar(epSKU); end; except on E: Exception do DM.SaveToLog(epSKU.IDSku, E.Message); end; end //FIM if DM.quSKU.FieldByName('IDFabricante').AsInteger > 0 then else begin //PRODUTO SEM FABRICANTE - GERO LOG DE ERRO. if not DM.quSKU.FieldByName('Desativado').AsBoolean then DM.SaveToLog(epSKU.IDSku, 'Não foi possível criar/atualizar o SKU. Motivo: PRODUTO SEM FABRICANTE RELACIONADO.'); end; Next; end; finally FreeAndNil(epSKU); end; Close; except raise; end; finally FreeAndNil(epSKUSync); end; end; procedure TFrmExport.SincronizarQuantidade; var epSaldoSKU: TepSaldoSKU; epEstoqueSync: TepEstoqueSync; begin epEstoqueSync := TepEstoqueSync.Create; try epEstoqueSync.Init(DM.HTTPReqRespCatalog, DM.ECommerceInfo.FURL, DM.ECommerceInfo.FUser, DM.ECommerceInfo.FPW); with DM.quInventory do try if Active then Close; Parameters.ParamByName('IDStore').Value := DM.MRInfo.FIDInventoryStore; Open; First; lblResultado.Caption := 'Sincronizando Quantidades...'; pbExportacao.Position := 0; pbExportacao.Max := RecordCount; Application.ProcessMessages; epSaldoSKU := TepSaldoSKU.Create; try while not EOF do begin try pbExportacao.Position := pbExportacao.Position + 1; Application.ProcessMessages; epSaldoSKU.IdEstoque := DM.ECommerceInfo.FEstoque; epSaldoSKU.IdSku := FieldByName('ModelID').AsInteger; epSaldoSKU.QuantidadeTotal := FieldByName('QtyOnHand').AsInteger; epSaldoSKU.QuantidadeReservada := FieldByName('QtyOnPreSale').AsInteger; epSaldoSKU.QuantidadeDisponivel := epSaldoSKU.QuantidadeTotal - epSaldoSKU.QuantidadeReservada; epEstoqueSync.Atualizar(epSaldoSKU); except on E: Exception do DM.SaveToLog(epSaldoSKU.IdEstoque, E.Message); end; Next; end; finally FreeAndNil(epSaldoSKU); end; Close; except raise; end; finally FreeAndNil(epEstoqueSync); end; end; procedure TFrmExport.SincronizarEstoque; begin if chkCategoria.Checked then SincronizarCategoria; if chkProduto.Checked then SincronizarProduto; if chkSKU.Checked then SincronizarSKU; end; procedure TFrmExport.chkEstoqueClick(Sender: TObject); begin chkCategoria.Enabled := chkEstoque.Checked; chkProduto.Enabled := chkEstoque.Checked; chkSKU.Enabled := chkEstoque.Checked; end; function TFrmExport.FormatarTextoLink(ATexto: String): String; begin Result := StringReplace(ATexto, ' ', '-', [rfReplaceAll]); Result := StringReplace(Result, '!', '', [rfReplaceAll]); Result := StringReplace(Result, '?', '', [rfReplaceAll]); Result := StringReplace(Result, '@', '', [rfReplaceAll]); Result := StringReplace(Result, '#', '', [rfReplaceAll]); Result := StringReplace(Result, '$', '', [rfReplaceAll]); Result := StringReplace(Result, '%', '', [rfReplaceAll]); Result := StringReplace(Result, '&', '', [rfReplaceAll]); Result := StringReplace(Result, '+', '', [rfReplaceAll]); Result := StringReplace(Result, '*', '', [rfReplaceAll]); Result := StringReplace(Result, 'á', 'a', [rfReplaceAll]); Result := StringReplace(Result, 'Á', 'A', [rfReplaceAll]); Result := StringReplace(Result, 'à', 'a', [rfReplaceAll]); Result := StringReplace(Result, 'À', 'A', [rfReplaceAll]); Result := StringReplace(Result, 'ã', 'a', [rfReplaceAll]); Result := StringReplace(Result, 'Ã', 'A', [rfReplaceAll]); Result := StringReplace(Result, 'â', 'a', [rfReplaceAll]); Result := StringReplace(Result, 'Â', 'A', [rfReplaceAll]); Result := StringReplace(Result, 'é', 'e', [rfReplaceAll]); Result := StringReplace(Result, 'É', 'E', [rfReplaceAll]); Result := StringReplace(Result, 'è', 'e', [rfReplaceAll]); Result := StringReplace(Result, 'È', 'E', [rfReplaceAll]); Result := StringReplace(Result, 'ê', 'e', [rfReplaceAll]); Result := StringReplace(Result, 'Ê', 'E', [rfReplaceAll]); Result := StringReplace(Result, 'í', 'i', [rfReplaceAll]); Result := StringReplace(Result, 'Í', 'I', [rfReplaceAll]); Result := StringReplace(Result, 'ì', 'i', [rfReplaceAll]); Result := StringReplace(Result, 'Ì', 'I', [rfReplaceAll]); Result := StringReplace(Result, 'î', 'i', [rfReplaceAll]); Result := StringReplace(Result, 'Î', 'I', [rfReplaceAll]); Result := StringReplace(Result, 'ó', 'o', [rfReplaceAll]); Result := StringReplace(Result, 'Ó', 'O', [rfReplaceAll]); Result := StringReplace(Result, 'ò', 'o', [rfReplaceAll]); Result := StringReplace(Result, 'Ò', 'O', [rfReplaceAll]); Result := StringReplace(Result, 'õ', 'o', [rfReplaceAll]); Result := StringReplace(Result, 'Õ', 'O', [rfReplaceAll]); Result := StringReplace(Result, 'ô', 'o', [rfReplaceAll]); Result := StringReplace(Result, 'Ô', 'O', [rfReplaceAll]); Result := StringReplace(Result, 'ú', 'u', [rfReplaceAll]); Result := StringReplace(Result, 'Ú', 'U', [rfReplaceAll]); Result := StringReplace(Result, 'ù', 'u', [rfReplaceAll]); Result := StringReplace(Result, 'Ù', 'U', [rfReplaceAll]); Result := StringReplace(Result, 'û', 'u', [rfReplaceAll]); Result := StringReplace(Result, 'Û', 'U', [rfReplaceAll]); Result := StringReplace(Result, 'ç', 'c', [rfReplaceAll]); Result := StringReplace(Result, 'Ç', 'C', [rfReplaceAll]); end; procedure TFrmExport.Button1Click(Sender: TObject); begin FrmLog.ShowModal; end; function TFrmExport.FormatarTextoDescricao(ATexto: String): String; begin Result := StringReplace(ATexto, '&', 'e', [rfReplaceAll]); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFCE_CONFIGURACAO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfceConfiguracaoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, NfceResolucaoVO, NfceCaixaVO, EmpresaVO, NfceConfiguracaoBalancaVO, NfceConfiguracaoLeitorSerVO; type TNfceConfiguracaoVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FID_NFCE_CAIXA: Integer; FID_NFCE_RESOLUCAO: Integer; FMENSAGEM_CUPOM: String; FTITULO_TELA_CAIXA: String; FCAMINHO_IMAGENS_PRODUTOS: String; FCAMINHO_IMAGENS_MARKETING: String; FCAMINHO_IMAGENS_LAYOUT: String; FCOR_JANELAS_INTERNAS: String; FMARKETING_ATIVO: String; FCFOP: Integer; FDECIMAIS_QUANTIDADE: Integer; FDECIMAIS_VALOR: Integer; FQUANTIDADE_MAXIMA_PARCELA: Integer; FIMPRIME_PARCELA: String; FNfceResolucaoVO: TNfceResolucaoVO; FNfceCaixaVO: TNfceCaixaVO; FEmpresaVO: TEmpresaVO; FNfceConfiguracaoBalancaVO: TNfceConfiguracaoBalancaVO; FNfceConfiguracaoLeitorSerVO: TNfceConfiguracaoLeitorSerVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property IdNfceCaixa: Integer read FID_NFCE_CAIXA write FID_NFCE_CAIXA; property IdNfceResolucao: Integer read FID_NFCE_RESOLUCAO write FID_NFCE_RESOLUCAO; property MensagemCupom: String read FMENSAGEM_CUPOM write FMENSAGEM_CUPOM; property TituloTelaCaixa: String read FTITULO_TELA_CAIXA write FTITULO_TELA_CAIXA; property CaminhoImagensProdutos: String read FCAMINHO_IMAGENS_PRODUTOS write FCAMINHO_IMAGENS_PRODUTOS; property CaminhoImagensMarketing: String read FCAMINHO_IMAGENS_MARKETING write FCAMINHO_IMAGENS_MARKETING; property CaminhoImagensLayout: String read FCAMINHO_IMAGENS_LAYOUT write FCAMINHO_IMAGENS_LAYOUT; property CorJanelasInternas: String read FCOR_JANELAS_INTERNAS write FCOR_JANELAS_INTERNAS; property MarketingAtivo: String read FMARKETING_ATIVO write FMARKETING_ATIVO; property Cfop: Integer read FCFOP write FCFOP; property DecimaisQuantidade: Integer read FDECIMAIS_QUANTIDADE write FDECIMAIS_QUANTIDADE; property DecimaisValor: Integer read FDECIMAIS_VALOR write FDECIMAIS_VALOR; property QuantidadeMaximaParcela: Integer read FQUANTIDADE_MAXIMA_PARCELA write FQUANTIDADE_MAXIMA_PARCELA; property ImprimeParcela: String read FIMPRIME_PARCELA write FIMPRIME_PARCELA; property NfceResolucaoVO: TNfceResolucaoVO read FNfceResolucaoVO write FNfceResolucaoVO; property NfceCaixaVO: TNfceCaixaVO read FNfceCaixaVO write FNfceCaixaVO; property EmpresaVO: TEmpresaVO read FEmpresaVO write FEmpresaVO; property NfceConfiguracaoBalancaVO: TNfceConfiguracaoBalancaVO read FNfceConfiguracaoBalancaVO write FNfceConfiguracaoBalancaVO; property NfceConfiguracaoLeitorSerVO: TNfceConfiguracaoLeitorSerVO read FNfceConfiguracaoLeitorSerVO write FNfceConfiguracaoLeitorSerVO; end; TListaNfceConfiguracaoVO = specialize TFPGObjectList<TNfceConfiguracaoVO>; implementation constructor TNfceConfiguracaoVO.Create; begin inherited; FNfceResolucaoVO := TNfceResolucaoVO.Create; FNfceCaixaVO := TNfceCaixaVO.Create; FEmpresaVO := TEmpresaVO.Create; FNfceConfiguracaoBalancaVO := TNfceConfiguracaoBalancaVO.Create; FNfceConfiguracaoLeitorSerVO := TNfceConfiguracaoLeitorSerVO.Create; end; destructor TNfceConfiguracaoVO.Destroy; begin FreeAndNil(FNfceResolucaoVO); FreeAndNil(FNfceCaixaVO); FreeAndNil(FEmpresaVO); FreeAndNil(FNfceConfiguracaoBalancaVO); FreeAndNil(FNfceConfiguracaoLeitorSerVO); inherited; end; initialization Classes.RegisterClass(TNfceConfiguracaoVO); finalization Classes.UnRegisterClass(TNfceConfiguracaoVO); end.
unit WriteSettings; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Simplex.Types; type TfrmWriteSettings = class(TForm) GroupBox1: TGroupBox; btnOK: TButton; btnCancel: TButton; lblWriteValue: TLabel; edtWriteValue: TEdit; private { Private declarations } public { Public declarations } end; function GetWriteSettings(AOwner: TComponent; AValue: SpxVariant; out AWriteValue: SpxVariant): Boolean; implementation {$R *.dfm} uses Client; function GetWriteSettings(AOwner: TComponent; AValue: SpxVariant; out AWriteValue: SpxVariant): Boolean; var frmWriteSettings: TfrmWriteSettings; begin Result := False; frmWriteSettings := TfrmWriteSettings.Create(AOwner); try frmWriteSettings.lblWriteValue.Caption := Format('Write value (%s)', [TypeToStr(AValue)]); frmWriteSettings.edtWriteValue.Text := ValueToStr(AValue); if (frmWriteSettings.ShowModal() <> mrOK) then Exit; if not StrToValue(AValue.BuiltInType, frmWriteSettings.edtWriteValue.Text, AWriteValue) then begin ShowMessage('Incorrect value'); Exit; end; Result := True; finally FreeAndNil(frmWriteSettings); end; end; end.
unit uMediaEncryption; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Win.Registry, Dmitry.Utils.System, uConstants, uTransparentEncryption, uFormInterfaces, uSettings, uRuntime, uMediaPlayers, uTranslate, uShellIntegration, uAssociations, uSessionPasswords; type TMachineType = (mtUnknown, mt32Bit, mt64Bit, mtOther); function ShellPlayEncryptedMediaFile(const FileName: string): Boolean; function GetLibMachineType(const AFileName: string): TMachineType; function GetFileBindings(FileName: string): string; implementation function GetFileBindings(FileName: string): string; var Extension: string; begin Extension := ExtractFileExt(FileName); Result := AppSettings.ReadString(cMediaAssociationsData + '\' + Extension, ''); if Result = cMediaPlayerDefaultId then Result := GetPlayerInternalPath; end; function ShellPlayEncryptedMediaFile(const FileName: string): Boolean; var Executable, TransparentDecryptor, Password: string; ExecutableType: TMachineType; Si: TStartupInfo; P: TProcessInformation; begin Result := False; if ValidEnryptFileEx(FileName) then begin Password := SessionPasswords.FindForFile(FileName); if (Password = '') then Password := RequestPasswordForm.ForImage(FileName); if Password = '' then //play started but user don't know password - it's OK Exit(True); end; if FolderView then begin if not IsGraphicFile(FileName) and (Password <> '') then MessageBoxDB(0, TA('Transparent encryption isn''t available on mobile verison.', 'System'), TA('Information'), TD_BUTTON_OK, TD_ICON_WARNING); Exit; end; Executable := GetFileBindings(FileName); if Executable = '' then Executable := GetShellPlayerForFile(FileName); if Executable <> '' then begin Executable := ExpandEnvironment(Executable); ExecutableType := GetLibMachineType(Executable); if ExecutableType in [mt32Bit, mt64Bit] then begin TransparentDecryptor := ExtractFilePath(ParamStr(0)) + 'PlayEncryptedMedia'; if ExecutableType = mt64Bit then TransparentDecryptor := TransparentDecryptor + '64'; TransparentDecryptor := TransparentDecryptor + '.exe'; FillChar(Si, SizeOf(Si), 0); with Si do begin Cb := SizeOf(Si); DwFlags := STARTF_USESHOWWINDOW; WShowWindow := SW_SHOW; end; if CreateProcess(PChar(TransparentDecryptor), PWideChar('"' + TransparentDecryptor + '" "' + Executable + '" "' + FileName + '"'), nil, nil, False, CREATE_DEFAULT_ERROR_MODE, nil, nil, Si, P) then Result := True; end; end; end; function GetLibMachineType(const AFileName: string): TMachineType; var oFS: TFileStream; iPeOffset: Integer; iPeHead: LongWord; iMachineType: Word; begin Result := mtUnknown; // http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v8.doc // Offset to PE header is always at 0x3C. // PE header starts with "PE\0\0" = 0x50 0x45 0x00 0x00, // followed by 2-byte machine type field (see document above for enum). try oFS := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); try oFS.Seek($3C, soFromBeginning); oFS.Read(iPeOffset, SizeOf(iPeOffset)); oFS.Seek(iPeOffset, soFromBeginning); oFS.Read(iPeHead, SizeOf(iPeHead)); // "PE\0\0", little-endian then if iPeHead <> $00004550 then Exit; oFS.Read(iMachineType, SizeOf(iMachineType)); case iMachineType of $8664, // AMD64 $0200: // IA64 Result := mt64Bit; $014C: // I386 Result := mt32Bit; else Result := mtOther; end; finally oFS.Free; end; except // none end; end; end.
{************************************************************* Author: Stéphane Vander Clock (SVanderClock@Arkadia.com) www: http://www.arkadia.com EMail: SVanderClock@Arkadia.com product: Alcinoe HTML function Version: 3.05 Description: Function to work on Html Tag (extract Text, HTML encode, HTML decode, etc. the function ALHTMLdecode and ALHTMLEncode is to encode decode HTML entity like &nbsp; Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Know bug : History : 19/10/2005: Make The code independant of the current local and work with UTF-8 encoding; Also build a most complete list of HTML entities Link : Please send all your feedback to SVanderClock@Arkadia.com **************************************************************} unit AlFcnHTML; interface uses Classes; {Html Tag function} procedure ALANSIExtractHTMLText(HtmlContent: String; Var LstExtractedResourceText : Tstrings; Const DecodeHTMLText: Boolean = True); procedure ALUTF8ExtractHTMLText(HtmlContent: UTF8String; Var LstExtractedResourceText : Tstrings; Const DecodeHTMLText: Boolean = True); function ALXMLTextElementEncode(Src: string): string; function ALXMLTextElementDecode(Src: string): string; function ALANSIHTMLEncode(Src: string; Const EncodeASCIIHtmlEntities: Boolean = True): string; function ALUTF8HTMLEncode(Src: UTF8String; Const EncodeASCIIHtmlEntities: Boolean = True): UTF8String; function ALANSIHTMLDecode(Src: string): string; function ALUTF8HTMLDecode(Src: Utf8string): Utf8string; {for internal use} procedure ALHideHtmlUnwantedTagForHTMLHandleTagfunct(Var HtmlContent: String; Const DeleteBodyOfUnwantedTag: Boolean = False; const ReplaceUnwantedTagCharBy: Char = #1); procedure ALInitHtmlEntitiesLst(aLstHtmlEntities: Tstrings); implementation uses sysutils, alFcnString, ALQuickSortList; Var vALhtml_LstEntities: Tstrings; {*********************************************************} procedure ALInitHtmlEntitiesLst(aLstHtmlEntities: Tstrings); Begin aLstHtmlEntities.Clear; aLstHtmlEntities.AddObject('zwnj',pointer(8204)); // zero width non-joiner, U+200C NEW RFC 2070 --> aLstHtmlEntities.AddObject('zwj',pointer(8205)); // zero width joiner, U+200D NEW RFC 2070 --> aLstHtmlEntities.AddObject('zeta',pointer(950)); // greek small letter zeta, U+03B6 ISOgrk3 --> aLstHtmlEntities.AddObject('Zeta',pointer(918)); // greek capital letter zeta, U+0396 --> aLstHtmlEntities.AddObject('yuml',pointer(255)); // latin small letter y with diaeresis, U+00FF ISOlat1 --> aLstHtmlEntities.AddObject('Yuml',pointer(376)); // latin capital letter Y with diaeresis, U+0178 ISOlat2 --> aLstHtmlEntities.AddObject('yen',pointer(165)); // yen sign = yuan sign, U+00A5 ISOnum --> aLstHtmlEntities.AddObject('yacute',pointer(253)); // latin small letter y with acute, U+00FD ISOlat1 --> aLstHtmlEntities.AddObject('Yacute',pointer(221)); // latin capital letter Y with acute, U+00DD ISOlat1 --> aLstHtmlEntities.AddObject('xi',pointer(958)); // greek small letter xi, U+03BE ISOgrk3 --> aLstHtmlEntities.AddObject('Xi',pointer(926)); // greek capital letter xi, U+039E ISOgrk3 --> aLstHtmlEntities.AddObject('weierp',pointer(8472)); // script capital P = power set = Weierstrass p, U+2118 ISOamso --> aLstHtmlEntities.AddObject('uuml',pointer(252)); // latin small letter u with diaeresis, U+00FC ISOlat1 --> aLstHtmlEntities.AddObject('Uuml',pointer(220)); // latin capital letter U with diaeresis, U+00DC ISOlat1 --> aLstHtmlEntities.AddObject('upsilon',pointer(965)); // greek small letter upsilon, U+03C5 ISOgrk3 --> aLstHtmlEntities.AddObject('Upsilon',pointer(933)); // greek capital letter upsilon, U+03A5 ISOgrk3 --> aLstHtmlEntities.AddObject('upsih',pointer(978)); // greek upsilon with hook symbol, U+03D2 NEW --> aLstHtmlEntities.AddObject('uml',pointer(168)); // diaeresis = spacing diaeresis, U+00A8 ISOdia --> aLstHtmlEntities.AddObject('ugrave',pointer(249)); // latin small letter u with grave, U+00F9 ISOlat1 --> aLstHtmlEntities.AddObject('Ugrave',pointer(217)); // latin capital letter U with grave, U+00D9 ISOlat1 --> aLstHtmlEntities.AddObject('ucirc',pointer(251)); // latin small letter u with circumflex, U+00FB ISOlat1 --> aLstHtmlEntities.AddObject('Ucirc',pointer(219)); // latin capital letter U with circumflex, U+00DB ISOlat1 --> aLstHtmlEntities.AddObject('uArr',pointer(8657)); // upwards double arrow, U+21D1 ISOamsa --> aLstHtmlEntities.AddObject('uarr',pointer(8593)); // upwards arrow, U+2191 ISOnum--> aLstHtmlEntities.AddObject('uacute',pointer(250)); // latin small letter u with acute, U+00FA ISOlat1 --> aLstHtmlEntities.AddObject('Uacute',pointer(218)); // latin capital letter U with acute, U+00DA ISOlat1 --> aLstHtmlEntities.AddObject('trade',pointer(8482)); // trade mark sign, U+2122 ISOnum --> aLstHtmlEntities.AddObject('times',pointer(215)); // multiplication sign, U+00D7 ISOnum --> aLstHtmlEntities.AddObject('tilde',pointer(732)); // small tilde, U+02DC ISOdia --> aLstHtmlEntities.AddObject('thorn',pointer(254)); // latin small letter thorn, U+00FE ISOlat1 --> aLstHtmlEntities.AddObject('THORN',pointer(222)); // latin capital letter THORN, U+00DE ISOlat1 --> aLstHtmlEntities.AddObject('thinsp',pointer(8201)); // thin space, U+2009 ISOpub --> aLstHtmlEntities.AddObject('thetasym',pointer(977)); // greek small letter theta symbol, U+03D1 NEW --> aLstHtmlEntities.AddObject('theta',pointer(952)); // greek small letter theta, U+03B8 ISOgrk3 --> aLstHtmlEntities.AddObject('Theta',pointer(920)); // greek capital letter theta, U+0398 ISOgrk3 --> aLstHtmlEntities.AddObject('there4',pointer(8756)); // therefore, U+2234 ISOtech --> aLstHtmlEntities.AddObject('tau',pointer(964)); // greek small letter tau, U+03C4 ISOgrk3 --> aLstHtmlEntities.AddObject('Tau',pointer(932)); // greek capital letter tau, U+03A4 --> aLstHtmlEntities.AddObject('szlig',pointer(223)); // latin small letter sharp s = ess-zed, U+00DF ISOlat1 --> aLstHtmlEntities.AddObject('supe',pointer(8839)); // superset of or equal to, U+2287 ISOtech --> aLstHtmlEntities.AddObject('sup3',pointer(179)); // superscript three = superscript digit three = cubed, U+00B3 ISOnum --> aLstHtmlEntities.AddObject('sup2',pointer(178)); // superscript two = superscript digit two = squared, U+00B2 ISOnum --> aLstHtmlEntities.AddObject('sup1',pointer(185)); // superscript one = superscript digit one, U+00B9 ISOnum --> aLstHtmlEntities.AddObject('sup',pointer(8835)); // superset of, U+2283 ISOtech --> aLstHtmlEntities.AddObject('sum',pointer(8721)); // n-ary sumation, U+2211 ISOamsb --> aLstHtmlEntities.AddObject('sube',pointer(8838)); // subset of or equal to, U+2286 ISOtech --> aLstHtmlEntities.AddObject('sub',pointer(8834)); // subset of, U+2282 ISOtech --> aLstHtmlEntities.AddObject('spades',pointer(9824)); // black spade suit, U+2660 ISOpub --> aLstHtmlEntities.AddObject('sim',pointer(8764)); // tilde operator = varies with = similar to, U+223C ISOtech --> aLstHtmlEntities.AddObject('sigmaf',pointer(962)); // greek small letter final sigma, U+03C2 ISOgrk3 --> aLstHtmlEntities.AddObject('sigma',pointer(963)); // greek small letter sigma, U+03C3 ISOgrk3 --> aLstHtmlEntities.AddObject('Sigma',pointer(931)); // greek capital letter sigma, U+03A3 ISOgrk3 --> aLstHtmlEntities.AddObject('shy',pointer(173)); // soft hyphen = discretionary hyphen, U+00AD ISOnum --> aLstHtmlEntities.AddObject('sect',pointer(167)); // section sign, U+00A7 ISOnum --> aLstHtmlEntities.AddObject('sdot',pointer(8901)); // dot operator, U+22C5 ISOamsb --> aLstHtmlEntities.AddObject('scaron',pointer(353)); // latin small letter s with caron, U+0161 ISOlat2 --> aLstHtmlEntities.AddObject('Scaron',pointer(352)); // latin capital letter S with caron, U+0160 ISOlat2 --> aLstHtmlEntities.AddObject('sbquo',pointer(8218)); // single low-9 quotation mark, U+201A NEW --> aLstHtmlEntities.AddObject('rsquo',pointer(8217)); // right single quotation mark, U+2019 ISOnum --> aLstHtmlEntities.AddObject('rsaquo',pointer(8250)); // single right-pointing angle quotation mark, U+203A ISO proposed --> aLstHtmlEntities.AddObject('rlm',pointer(8207)); // right-to-left mark, U+200F NEW RFC 2070 --> aLstHtmlEntities.AddObject('rho',pointer(961)); // greek small letter rho, U+03C1 ISOgrk3 --> aLstHtmlEntities.AddObject('Rho',pointer(929)); // greek capital letter rho, U+03A1 --> aLstHtmlEntities.AddObject('rfloor',pointer(8971)); // right floor, U+230B ISOamsc --> aLstHtmlEntities.AddObject('reg',pointer(174)); // registered sign = registered trade mark sign, U+00AE ISOnum --> aLstHtmlEntities.AddObject('real',pointer(8476)); // blackletter capital R = real part symbol, U+211C ISOamso --> aLstHtmlEntities.AddObject('rdquo',pointer(8221)); // right double quotation mark, U+201D ISOnum --> aLstHtmlEntities.AddObject('rceil',pointer(8969)); // right ceiling, U+2309 ISOamsc --> aLstHtmlEntities.AddObject('rArr',pointer(8658)); // rightwards double arrow, U+21D2 ISOtech --> aLstHtmlEntities.AddObject('rarr',pointer(8594)); // rightwards arrow, U+2192 ISOnum --> aLstHtmlEntities.AddObject('raquo',pointer(187)); // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum --> aLstHtmlEntities.AddObject('rang',pointer(9002)); // right-pointing angle bracket = ket, U+232A ISOtech --> aLstHtmlEntities.AddObject('radic',pointer(8730)); // square root = radical sign, U+221A ISOtech --> aLstHtmlEntities.AddObject('quot',pointer(34)); // quotation mark = APL quote, U+0022 ISOnum --> aLstHtmlEntities.AddObject('psi',pointer(968)); // greek small letter psi, U+03C8 ISOgrk3 --> aLstHtmlEntities.AddObject('Psi',pointer(936)); // greek capital letter psi, U+03A8 ISOgrk3 --> aLstHtmlEntities.AddObject('prop',pointer(8733)); // proportional to, U+221D ISOtech --> aLstHtmlEntities.AddObject('prod',pointer(8719)); // n-ary product = product sign, U+220F ISOamsb --> aLstHtmlEntities.AddObject('Prime',pointer(8243)); // double prime = seconds = inches, U+2033 ISOtech --> aLstHtmlEntities.AddObject('prime',pointer(8242)); // prime = minutes = feet, U+2032 ISOtech --> aLstHtmlEntities.AddObject('pound',pointer(163)); // pound sign, U+00A3 ISOnum --> aLstHtmlEntities.AddObject('plusmn',pointer(177)); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum --> aLstHtmlEntities.AddObject('piv',pointer(982)); // greek pi symbol, U+03D6 ISOgrk3 --> aLstHtmlEntities.AddObject('pi',pointer(960)); // greek small letter pi, U+03C0 ISOgrk3 --> aLstHtmlEntities.AddObject('Pi',pointer(928)); // greek capital letter pi, U+03A0 ISOgrk3 --> aLstHtmlEntities.AddObject('phi',pointer(966)); // greek small letter phi, U+03C6 ISOgrk3 --> aLstHtmlEntities.AddObject('Phi',pointer(934)); // greek capital letter phi, U+03A6 ISOgrk3 --> aLstHtmlEntities.AddObject('perp',pointer(8869)); // up tack = orthogonal to = perpendicular, U+22A5 ISOtech --> aLstHtmlEntities.AddObject('permil',pointer(8240)); // per mille sign, U+2030 ISOtech --> aLstHtmlEntities.AddObject('part',pointer(8706)); // partial differential, U+2202 ISOtech --> aLstHtmlEntities.AddObject('para',pointer(182)); // pilcrow sign = paragraph sign, U+00B6 ISOnum --> aLstHtmlEntities.AddObject('ouml',pointer(246)); // latin small letter o with diaeresis, U+00F6 ISOlat1 --> aLstHtmlEntities.AddObject('Ouml',pointer(214)); // latin capital letter O with diaeresis, U+00D6 ISOlat1 --> aLstHtmlEntities.AddObject('otimes',pointer(8855)); // circled times = vector product, U+2297 ISOamsb --> aLstHtmlEntities.AddObject('otilde',pointer(245)); // latin small letter o with tilde, U+00F5 ISOlat1 --> aLstHtmlEntities.AddObject('Otilde',pointer(213)); // latin capital letter O with tilde, U+00D5 ISOlat1 --> aLstHtmlEntities.AddObject('oslash',pointer(248)); // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 --> aLstHtmlEntities.AddObject('Oslash',pointer(216)); // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 --> aLstHtmlEntities.AddObject('ordm',pointer(186)); // masculine ordinal indicator, U+00BA ISOnum --> aLstHtmlEntities.AddObject('ordf',pointer(170)); // feminine ordinal indicator, U+00AA ISOnum --> aLstHtmlEntities.AddObject('or',pointer(8744)); // logical or = vee, U+2228 ISOtech --> aLstHtmlEntities.AddObject('oplus',pointer(8853)); // circled plus = direct sum, U+2295 ISOamsb --> aLstHtmlEntities.AddObject('omicron',pointer(959)); // greek small letter omicron, U+03BF NEW --> aLstHtmlEntities.AddObject('Omicron',pointer(927)); // greek capital letter omicron, U+039F --> aLstHtmlEntities.AddObject('omega',pointer(969)); // greek small letter omega, U+03C9 ISOgrk3 --> aLstHtmlEntities.AddObject('Omega',pointer(937)); // greek capital letter omega, U+03A9 ISOgrk3 --> aLstHtmlEntities.AddObject('oline',pointer(8254)); // overline = spacing overscore, U+203E NEW --> aLstHtmlEntities.AddObject('ograve',pointer(242)); // latin small letter o with grave, U+00F2 ISOlat1 --> aLstHtmlEntities.AddObject('Ograve',pointer(210)); // latin capital letter O with grave, U+00D2 ISOlat1 --> aLstHtmlEntities.AddObject('oelig',pointer(339)); // latin small ligature oe, U+0153 ISOlat2 --> aLstHtmlEntities.AddObject('OElig',pointer(338)); // latin capital ligature OE, U+0152 ISOlat2 --> aLstHtmlEntities.AddObject('ocirc',pointer(244)); // latin small letter o with circumflex, U+00F4 ISOlat1 --> aLstHtmlEntities.AddObject('Ocirc',pointer(212)); // latin capital letter O with circumflex, U+00D4 ISOlat1 --> aLstHtmlEntities.AddObject('oacute',pointer(243)); // latin small letter o with acute, U+00F3 ISOlat1 --> aLstHtmlEntities.AddObject('Oacute',pointer(211)); // latin capital letter O with acute, U+00D3 ISOlat1 --> aLstHtmlEntities.AddObject('nu',pointer(957)); // greek small letter nu, U+03BD ISOgrk3 --> aLstHtmlEntities.AddObject('Nu',pointer(925)); // greek capital letter nu, U+039D --> aLstHtmlEntities.AddObject('ntilde',pointer(241)); // latin small letter n with tilde, U+00F1 ISOlat1 --> aLstHtmlEntities.AddObject('Ntilde',pointer(209)); // latin capital letter N with tilde, U+00D1 ISOlat1 --> aLstHtmlEntities.AddObject('nsub',pointer(8836)); // not a subset of, U+2284 ISOamsn --> aLstHtmlEntities.AddObject('notin',pointer(8713)); // not an element of, U+2209 ISOtech --> aLstHtmlEntities.AddObject('not',pointer(172)); // not sign, U+00AC ISOnum --> aLstHtmlEntities.AddObject('ni',pointer(8715)); // contains as member, U+220B ISOtech --> aLstHtmlEntities.AddObject('ne',pointer(8800)); // not equal to, U+2260 ISOtech --> aLstHtmlEntities.AddObject('ndash',pointer(8211)); // en dash, U+2013 ISOpub --> aLstHtmlEntities.AddObject('nbsp',pointer(160)); // no-break space = non-breaking space, U+00A0 ISOnum --> aLstHtmlEntities.AddObject('nabla',pointer(8711)); // nabla = backward difference, U+2207 ISOtech --> aLstHtmlEntities.AddObject('mu',pointer(956)); // greek small letter mu, U+03BC ISOgrk3 --> aLstHtmlEntities.AddObject('Mu',pointer(924)); // greek capital letter mu, U+039C --> aLstHtmlEntities.AddObject('minus',pointer(8722)); // minus sign, U+2212 ISOtech --> aLstHtmlEntities.AddObject('middot',pointer(183)); // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum --> aLstHtmlEntities.AddObject('micro',pointer(181)); // micro sign, U+00B5 ISOnum --> aLstHtmlEntities.AddObject('mdash',pointer(8212)); // em dash, U+2014 ISOpub --> aLstHtmlEntities.AddObject('macr',pointer(175)); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia --> aLstHtmlEntities.AddObject('lt',pointer(60)); // less-than sign, U+003C ISOnum --> aLstHtmlEntities.AddObject('lsquo',pointer(8216)); // left single quotation mark, U+2018 ISOnum --> aLstHtmlEntities.AddObject('lsaquo',pointer(8249)); // single left-pointing angle quotation mark, U+2039 ISO proposed --> aLstHtmlEntities.AddObject('lrm',pointer(8206)); // left-to-right mark, U+200E NEW RFC 2070 --> aLstHtmlEntities.AddObject('loz',pointer(9674)); // lozenge, U+25CA ISOpub --> aLstHtmlEntities.AddObject('lowast',pointer(8727)); // asterisk operator, U+2217 ISOtech --> aLstHtmlEntities.AddObject('lfloor',pointer(8970)); // left floor = apl downstile, U+230A ISOamsc --> aLstHtmlEntities.AddObject('le',pointer(8804)); // less-than or equal to, U+2264 ISOtech --> aLstHtmlEntities.AddObject('ldquo',pointer(8220)); // left double quotation mark, U+201C ISOnum --> aLstHtmlEntities.AddObject('lceil',pointer(8968)); // left ceiling = apl upstile, U+2308 ISOamsc --> aLstHtmlEntities.AddObject('lArr',pointer(8656)); // leftwards double arrow, U+21D0 ISOtech --> aLstHtmlEntities.AddObject('larr',pointer(8592)); // leftwards arrow, U+2190 ISOnum --> aLstHtmlEntities.AddObject('laquo',pointer(171)); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum --> aLstHtmlEntities.AddObject('lang',pointer(9001)); // left-pointing angle bracket = bra, U+2329 ISOtech --> aLstHtmlEntities.AddObject('lambda',pointer(955)); // greek small letter lambda, U+03BB ISOgrk3 --> aLstHtmlEntities.AddObject('Lambda',pointer(923)); // greek capital letter lambda, U+039B ISOgrk3 --> aLstHtmlEntities.AddObject('kappa',pointer(954)); // greek small letter kappa, U+03BA ISOgrk3 --> aLstHtmlEntities.AddObject('Kappa',pointer(922)); // greek capital letter kappa, U+039A --> aLstHtmlEntities.AddObject('iuml',pointer(239)); // latin small letter i with diaeresis, U+00EF ISOlat1 --> aLstHtmlEntities.AddObject('Iuml',pointer(207)); // latin capital letter I with diaeresis, U+00CF ISOlat1 --> aLstHtmlEntities.AddObject('isin',pointer(8712)); // element of, U+2208 ISOtech --> aLstHtmlEntities.AddObject('iquest',pointer(191)); // inverted question mark = turned question mark, U+00BF ISOnum --> aLstHtmlEntities.AddObject('iota',pointer(953)); // greek small letter iota, U+03B9 ISOgrk3 --> aLstHtmlEntities.AddObject('Iota',pointer(921)); // greek capital letter iota, U+0399 --> aLstHtmlEntities.AddObject('int',pointer(8747)); // integral, U+222B ISOtech --> aLstHtmlEntities.AddObject('infin',pointer(8734)); // infinity, U+221E ISOtech --> aLstHtmlEntities.AddObject('image',pointer(8465)); // blackletter capital I = imaginary part, U+2111 ISOamso --> aLstHtmlEntities.AddObject('igrave',pointer(236)); // latin small letter i with grave, U+00EC ISOlat1 --> aLstHtmlEntities.AddObject('Igrave',pointer(204)); // latin capital letter I with grave, U+00CC ISOlat1 --> aLstHtmlEntities.AddObject('iexcl',pointer(161)); // inverted exclamation mark, U+00A1 ISOnum --> aLstHtmlEntities.AddObject('icirc',pointer(238)); // latin small letter i with circumflex, U+00EE ISOlat1 --> aLstHtmlEntities.AddObject('Icirc',pointer(206)); // latin capital letter I with circumflex, U+00CE ISOlat1 --> aLstHtmlEntities.AddObject('iacute',pointer(237)); // latin small letter i with acute, U+00ED ISOlat1 --> aLstHtmlEntities.AddObject('Iacute',pointer(205)); // latin capital letter I with acute, U+00CD ISOlat1 --> aLstHtmlEntities.AddObject('hellip',pointer(8230)); // horizontal ellipsis = three dot leader, U+2026 ISOpub --> aLstHtmlEntities.AddObject('hearts',pointer(9829)); // black heart suit = valentine, U+2665 ISOpub --> aLstHtmlEntities.AddObject('hArr',pointer(8660)); // left right double arrow, U+21D4 ISOamsa --> aLstHtmlEntities.AddObject('harr',pointer(8596)); // left right arrow, U+2194 ISOamsa --> aLstHtmlEntities.AddObject('gt',pointer(62)); // greater-than sign, U+003E ISOnum --> aLstHtmlEntities.AddObject('ge',pointer(8805)); // greater-than or equal to, U+2265 ISOtech --> aLstHtmlEntities.AddObject('gamma',pointer(947)); // greek small letter gamma, U+03B3 ISOgrk3 --> aLstHtmlEntities.AddObject('Gamma',pointer(915)); // greek capital letter gamma, U+0393 ISOgrk3 --> aLstHtmlEntities.AddObject('frasl',pointer(8260)); // fraction slash, U+2044 NEW --> aLstHtmlEntities.AddObject('frac34',pointer(190)); // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum --> aLstHtmlEntities.AddObject('frac14',pointer(188)); // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum --> aLstHtmlEntities.AddObject('frac12',pointer(189)); // vulgar fraction one half = fraction one half, U+00BD ISOnum --> aLstHtmlEntities.AddObject('forall',pointer(8704)); // for all, U+2200 ISOtech --> aLstHtmlEntities.AddObject('fnof',pointer(402)); // latin small f with hook = function = florin, U+0192 ISOtech --> aLstHtmlEntities.AddObject('exist',pointer(8707)); // there exists, U+2203 ISOtech --> aLstHtmlEntities.AddObject('euro',pointer(8364)); // euro sign, U+20AC NEW --> aLstHtmlEntities.AddObject('euml',pointer(235)); // latin small letter e with diaeresis, U+00EB ISOlat1 --> aLstHtmlEntities.AddObject('Euml',pointer(203)); // latin capital letter E with diaeresis, U+00CB ISOlat1 --> aLstHtmlEntities.AddObject('eth',pointer(240)); // latin small letter eth, U+00F0 ISOlat1 --> aLstHtmlEntities.AddObject('ETH',pointer(208)); // latin capital letter ETH, U+00D0 ISOlat1 --> aLstHtmlEntities.AddObject('eta',pointer(951)); // greek small letter eta, U+03B7 ISOgrk3 --> aLstHtmlEntities.AddObject('Eta',pointer(919)); // greek capital letter eta, U+0397 --> aLstHtmlEntities.AddObject('equiv',pointer(8801)); // identical to, U+2261 ISOtech --> aLstHtmlEntities.AddObject('epsilon',pointer(949)); // greek small letter epsilon, U+03B5 ISOgrk3 --> aLstHtmlEntities.AddObject('Epsilon',pointer(917)); // greek capital letter epsilon, U+0395 --> aLstHtmlEntities.AddObject('ensp',pointer(8194)); // en space, U+2002 ISOpub --> aLstHtmlEntities.AddObject('emsp',pointer(8195)); // em space, U+2003 ISOpub --> aLstHtmlEntities.AddObject('empty',pointer(8709)); // empty set = null set = diameter, U+2205 ISOamso --> aLstHtmlEntities.AddObject('egrave',pointer(232)); // latin small letter e with grave, U+00E8 ISOlat1 --> aLstHtmlEntities.AddObject('Egrave',pointer(200)); // latin capital letter E with grave, U+00C8 ISOlat1 --> aLstHtmlEntities.AddObject('ecirc',pointer(234)); // latin small letter e with circumflex, U+00EA ISOlat1 --> aLstHtmlEntities.AddObject('Ecirc',pointer(202)); // latin capital letter E with circumflex, U+00CA ISOlat1 --> aLstHtmlEntities.AddObject('eacute',pointer(233)); // latin small letter e with acute, U+00E9 ISOlat1 --> aLstHtmlEntities.AddObject('Eacute',pointer(201)); // latin capital letter E with acute, U+00C9 ISOlat1 --> aLstHtmlEntities.AddObject('divide',pointer(247)); // division sign, U+00F7 ISOnum --> aLstHtmlEntities.AddObject('diams',pointer(9830)); // black diamond suit, U+2666 ISOpub --> aLstHtmlEntities.AddObject('delta',pointer(948)); // greek small letter delta, U+03B4 ISOgrk3 --> aLstHtmlEntities.AddObject('Delta',pointer(916)); // greek capital letter delta, U+0394 ISOgrk3 --> aLstHtmlEntities.AddObject('deg',pointer(176)); // degree sign, U+00B0 ISOnum --> aLstHtmlEntities.AddObject('dArr',pointer(8659)); // downwards double arrow, U+21D3 ISOamsa --> aLstHtmlEntities.AddObject('darr',pointer(8595)); // downwards arrow, U+2193 ISOnum --> aLstHtmlEntities.AddObject('Dagger',pointer(8225)); // double dagger, U+2021 ISOpub --> aLstHtmlEntities.AddObject('dagger',pointer(8224)); // dagger, U+2020 ISOpub --> aLstHtmlEntities.AddObject('curren',pointer(164)); // currency sign, U+00A4 ISOnum --> aLstHtmlEntities.AddObject('cup',pointer(8746)); // union = cup, U+222A ISOtech --> aLstHtmlEntities.AddObject('crarr',pointer(8629)); // downwards arrow with corner leftwards = carriage return, U+21B5 NEW --> aLstHtmlEntities.AddObject('copy',pointer(169)); // copyright sign, U+00A9 ISOnum --> aLstHtmlEntities.AddObject('cong',pointer(8773)); // approximately equal to, U+2245 ISOtech --> aLstHtmlEntities.AddObject('clubs',pointer(9827)); // black club suit = shamrock, U+2663 ISOpub --> aLstHtmlEntities.AddObject('circ',pointer(710)); // modifier letter circumflex accent, U+02C6 ISOpub --> aLstHtmlEntities.AddObject('chi',pointer(967)); // greek small letter chi, U+03C7 ISOgrk3 --> aLstHtmlEntities.AddObject('Chi',pointer(935)); // greek capital letter chi, U+03A7 --> aLstHtmlEntities.AddObject('cent',pointer(162)); // cent sign, U+00A2 ISOnum --> aLstHtmlEntities.AddObject('cedil',pointer(184)); // cedilla = spacing cedilla, U+00B8 ISOdia --> aLstHtmlEntities.AddObject('ccedil',pointer(231)); // latin small letter c with cedilla, U+00E7 ISOlat1 --> aLstHtmlEntities.AddObject('Ccedil',pointer(199)); // latin capital letter C with cedilla, U+00C7 ISOlat1 --> aLstHtmlEntities.AddObject('cap',pointer(8745)); // intersection = cap, U+2229 ISOtech --> aLstHtmlEntities.AddObject('bull',pointer(8226)); // bullet = black small circle, U+2022 ISOpub --> aLstHtmlEntities.AddObject('brvbar',pointer(166)); // broken bar = broken vertical bar, U+00A6 ISOnum --> aLstHtmlEntities.AddObject('beta',pointer(946)); // greek small letter beta, U+03B2 ISOgrk3 --> aLstHtmlEntities.AddObject('Beta',pointer(914)); // greek capital letter beta, U+0392 --> aLstHtmlEntities.AddObject('bdquo',pointer(8222)); // double low-9 quotation mark, U+201E NEW --> aLstHtmlEntities.AddObject('auml',pointer(228)); // latin small letter a with diaeresis, U+00E4 ISOlat1 --> aLstHtmlEntities.AddObject('Auml',pointer(196)); // latin capital letter A with diaeresis, U+00C4 ISOlat1 --> aLstHtmlEntities.AddObject('atilde',pointer(227)); // latin small letter a with tilde, U+00E3 ISOlat1 --> aLstHtmlEntities.AddObject('Atilde',pointer(195)); // latin capital letter A with tilde, U+00C3 ISOlat1 --> aLstHtmlEntities.AddObject('asymp',pointer(8776)); // almost equal to = asymptotic to, U+2248 ISOamsr --> aLstHtmlEntities.AddObject('aring',pointer(229)); // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 --> aLstHtmlEntities.AddObject('Aring',pointer(197)); // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 --> aLstHtmlEntities.AddObject('ang',pointer(8736)); // angle, U+2220 ISOamso --> aLstHtmlEntities.AddObject('and',pointer(8743)); // logical and = wedge, U+2227 ISOtech --> aLstHtmlEntities.AddObject('amp',pointer(38)); // ampersand, U+0026 ISOnum --> aLstHtmlEntities.AddObject('alpha',pointer(945)); // greek small letter alpha, U+03B1 ISOgrk3 --> aLstHtmlEntities.AddObject('Alpha',pointer(913)); // greek capital letter alpha, U+0391 --> aLstHtmlEntities.AddObject('alefsym',pointer(8501)); // alef symbol = first transfinite cardinal, U+2135 NEW --> aLstHtmlEntities.AddObject('agrave',pointer(224)); // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 --> aLstHtmlEntities.AddObject('Agrave',pointer(192)); // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 --> aLstHtmlEntities.AddObject('aelig',pointer(230)); // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 --> aLstHtmlEntities.AddObject('AElig',pointer(198)); // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 --> aLstHtmlEntities.AddObject('acute',pointer(180)); // acute accent = spacing acute, U+00B4 ISOdia --> aLstHtmlEntities.AddObject('acirc',pointer(226)); // latin small letter a with circumflex, U+00E2 ISOlat1 --> aLstHtmlEntities.AddObject('Acirc',pointer(194)); // latin capital letter A with circumflex, U+00C2 ISOlat1 --> aLstHtmlEntities.AddObject('aacute',pointer(225)); // latin small letter a with acute, U+00E1 ISOlat1 --> aLstHtmlEntities.AddObject('Aacute',pointer(193)); // latin capital letter A with acute, U+00C1 ISOlat1 --> end; {******************************************************} procedure ALUTF8ExtractHTMLText(HtmlContent: UTF8String; Var LstExtractedResourceText : Tstrings; Const DecodeHTMLText: Boolean = True); {-----------------------------------------------------------} procedure intenalAdd2LstExtractedResourceText(S: utf8String); Begin If DecodeHTMLText then Begin S := alUTF8HtmlDecode(trim(S)); S := AlStringReplace( S, #13, ' ', [rfreplaceAll] ); S := AlStringReplace( S, #10, ' ', [rfreplaceAll] ); S := AlStringReplace( S, #9, ' ', [rfreplaceAll] ); While AlPos(' ',S) > 0 Do S := AlStringReplace( S, ' ', ' ', [rfreplaceAll] ); s := Trim(S); end; If s <> '' then LstExtractedResourceText.add(S); end; Var P1: integer; Begin ALHideHtmlUnwantedTagForHTMLHandleTagfunct(string(HtmlContent), True); HtmlContent := ALFastTagReplace( HtmlContent, '<', '>', #2, {this char is not use in html} [rfreplaceall] ); HtmlContent := ALStringReplace( HtmlContent, #1, {default ReplaceUnwantedTagCharBy use by ALHideHtmlUnwantedTagForHTMLHandleTagfunct ; this char is not use in html} '<', [rfreplaceall] ); LstExtractedResourceText.Clear; P1 := ALpos(#2,HtmlContent); While P1 > 0 do begin If P1 > 1 then intenalAdd2LstExtractedResourceText( ALCopyStr( HtmlContent, 1, p1-1 ) ); delete(HtmlContent,1,P1); P1 := ALpos(#2,HtmlContent); end; intenalAdd2LstExtractedResourceText(HtmlContent); end; {**************************************************} procedure ALANSIExtractHTMLText(HtmlContent: String; Var LstExtractedResourceText : Tstrings; Const DecodeHTMLText: Boolean = True); Var I: Integer; Begin ALUTF8ExtractHTMLText( AnsiToUTF8(HtmlContent), LstExtractedResourceText, DecodeHTMLText ); For i := 0 to LstExtractedResourceText.count - 1 do LstExtractedResourceText[I] := UTF8ToAnsi(LstExtractedResourceText[i]); End; {***************************************************} function ALXMLTextElementEncode(Src: string): string; var i, l: integer; Buf, P: PChar; ch: Integer; begin Result := ''; L := Length(src); if L = 0 then exit; GetMem(Buf, L * 12); // to be on the *very* safe side try P := Buf; for i := 1 to L do begin ch := Ord(src[i]); case ch of 34: begin // quot " ALMove('&quot;', P^, 6); Inc(P, 6); end; 38: begin // amp & ALMove('&amp;', P^, 5); Inc(P, 5); end; 39: begin // apos ' ALMove('&apos;', P^, 6); Inc(P, 6); end; 60: begin // lt < ALMove('&lt;', P^, 4); Inc(P, 4); end; 62: begin // gt > ALMove('&gt;', P^, 4); Inc(P, 4); end; else Begin P^:= Char(ch); Inc(P); end; end; end; SetString(Result, Buf, P - Buf); finally FreeMem(Buf); end; end; {***************************************************} function ALXMLTextElementDecode(Src: string): string; var CurrentSrcPos, CurrentResultPos : Integer; j: integer; Entity : String; SrcLength: integer; {--------------------------------------} procedure CopyCurrentSrcPosCharToResult; Begin result[CurrentResultPos] := src[CurrentSrcPos]; inc(CurrentResultPos); inc(CurrentSrcPos); end; {-----------------------------------------------------------------} procedure CopyCharToResult(aChar: Char; NewCurrentSrcPos: integer); Begin result[CurrentResultPos] := aChar; inc(CurrentResultPos); CurrentSrcPos := NewCurrentSrcPos; end; begin {init var} CurrentSrcPos := 1; CurrentResultPos := 1; SrcLength := Length(src); Entity := ''; SetLength(Result,SrcLength); {start loop} while (CurrentSrcPos <= SrcLength) do begin {HTMLentity detected} If src[CurrentSrcPos]='&' then begin {extract the HTML entity} j := CurrentSrcPos; while (J <= SrcLength) and (src[j] <> ';') and (j-CurrentSrcPos<=12) do inc(j); {HTML entity is valid} If (J<=SrcLength) and (j-CurrentSrcPos<=12) then Begin //amp Entity := ALCopyStr( Src, CurrentSrcPos+1, j-CurrentSrcPos-1 ); If Entity ='quot' then CopyCharToResult('"', J+1) else if Entity = 'apos' then CopyCharToResult('''', J+1) else if Entity = 'amp' then CopyCharToResult('&', J+1) else if Entity = 'lt' then CopyCharToResult('<', J+1) else if Entity = 'gt' then CopyCharToResult('>', J+1) else CopyCurrentSrcPosCharToResult; end else CopyCurrentSrcPosCharToResult; end else CopyCurrentSrcPosCharToResult; end; setLength(Result,CurrentResultPos-1); end; {****************************************************************************************************} function ALUTF8HTMLEncode(Src: UTF8String; Const EncodeASCIIHtmlEntities: Boolean = True): UTF8String; var i, k, l: integer; Buf, P: PChar; aEntityStr: String; aEntityInt: Integer; aTmpWideString: WideString; LstUnicodeEntitiesNumber: TALIntegerList; begin Result := ''; If Src='' then Exit; LstUnicodeEntitiesNumber := TALIntegerList.create; Try LstUnicodeEntitiesNumber.Duplicates := DupIgnore; LstUnicodeEntitiesNumber.Sorted := True; For i := 0 to vALhtml_LstEntities.Count - 1 do LstUnicodeEntitiesNumber.AddObject(integer(vALhtml_LstEntities.Objects[i]),pointer(i)); aTmpWideString := UTF8Decode(Src); L := length(aTmpWideString); If L=0 then Exit; GetMem(Buf, length(Src) * 12); // to be on the *very* safe side try P := Buf; For i := 1 to L do begin aEntityInt := Integer(aTmpWideString[i]); Case aEntityInt of 34: begin // quot " If EncodeASCIIHtmlEntities then begin ALMove('&quot;', P^, 6); Inc(P, 6); end else Begin P^ := '"'; Inc(P, 1); end end; 38: begin // amp & If EncodeASCIIHtmlEntities then begin ALMove('&amp;', P^, 5); Inc(P, 5); end else Begin P^ := '&'; Inc(P, 1); end end; 60: begin // lt < If EncodeASCIIHtmlEntities then begin ALMove('&lt;', P^, 4); Inc(P, 4); end else Begin P^ := '<'; Inc(P, 1); end; end; 62: begin // gt > If EncodeASCIIHtmlEntities then begin ALMove('&gt;', P^, 4); Inc(P, 4); end else Begin P^ := '>'; Inc(P, 1); end; end; else begin if (aEntityInt > 127) then begin aEntityInt := LstUnicodeEntitiesNumber.IndexOf(aEntityInt); If aEntityInt >= 0 Then begin aEntityStr := vALhtml_LstEntities[integer(LstUnicodeEntitiesNumber.Objects[aEntityInt])]; If aEntityStr <> '' then aEntityStr := '&' + aEntityStr + ';' else aEntityStr := UTF8Encode(aTmpWideString[i]); end else aEntityStr := UTF8Encode(aTmpWideString[i]); end else aEntityStr := aTmpWideString[i]; for k := 1 to Length(aEntityStr) do begin P^ := aEntityStr[k]; Inc(P) end; end; end; end; SetString(Result, Buf, P - Buf); finally FreeMem(Buf); end; finally LstUnicodeEntitiesNumber.free; end; end; {*********************************************} function ALANSIHTMLEncode(Src: string; Const EncodeASCIIHtmlEntities: Boolean = True): string; Begin Result := Utf8toAnsi( ALUTF8HTMLEncode( AnsiToUTF8(Src), EncodeASCIIHtmlEntities ) ); end; {*****************************************************} function ALUTF8HTMLDecode(Src: Utf8string): Utf8string; var CurrentSrcPos, CurrentResultPos : Integer; j: integer; aTmpInteger: Integer; SrcLength: integer; {--------------------------------------} procedure CopyCurrentSrcPosCharToResult; Begin result[CurrentResultPos] := src[CurrentSrcPos]; inc(CurrentResultPos); inc(CurrentSrcPos); end; {---------------------------------------------------------------------------------} procedure CopyCharToResult(aUnicodeOrdEntity: Integer; aNewCurrentSrcPos: integer); Var aUTF8String: UTF8String; K: integer; Begin aUTF8String := UTF8Encode(WideChar(aUnicodeOrdEntity)); For k := 1 to length(aUTF8String) do begin result[CurrentResultPos] := aUTF8String[k]; inc(CurrentResultPos); end; CurrentSrcPos := aNewCurrentSrcPos; end; begin {init var} CurrentSrcPos := 1; CurrentResultPos := 1; SrcLength := Length(src); SetLength(Result,SrcLength); {start loop} while (CurrentSrcPos <= SrcLength) do begin {HTMLentity detected} If src[CurrentSrcPos]='&' then begin {extract the HTML entity} j := CurrentSrcPos; while (J <= SrcLength) and (src[j] <> ';') and (j-CurrentSrcPos<=12) do inc(j); {HTML entity is valid} If (J<=SrcLength) and (j-CurrentSrcPos<=12) then Begin {HTML entity is numeric} IF (Src[CurrentSrcPos+1] = '#') then begin {numeric HTML entity is valid} if trystrtoint( ALCopyStr( Src, CurrentSrcPos+2, j-CurrentSrcPos-2 ), aTmpInteger ) then CopyCharToResult(aTmpInteger, J+1) else CopyCurrentSrcPosCharToResult; end {HTML entity is litteral} else begin aTmpInteger := vALhtml_LstEntities.IndexOf( ALCopyStr( Src, CurrentSrcPos+1, j-CurrentSrcPos-1 ) ); If aTmpInteger >= 0 then CopyCharToResult(integer(vALhtml_LstEntities.Objects[aTmpInteger]),J+1) else CopyCurrentSrcPosCharToResult; end; end else CopyCurrentSrcPosCharToResult; end else CopyCurrentSrcPosCharToResult; end; setLength(Result,CurrentResultPos-1); end; {*********************************************} function ALANSIHTMLDecode(Src: string): string; Begin Result := Utf8toAnsi( ALUTF8HTMLDecode( AnsiToUTF8(Src) ) ); end; {***************************************************************************} procedure ALHideHtmlUnwantedTagForHTMLHandleTagfunct(Var HtmlContent: String; Const DeleteBodyOfUnwantedTag: Boolean = False; const ReplaceUnwantedTagCharBy: Char = #1); {this char is not use in html} Var InDoubleQuote : Boolean; InSimpleQuote : Boolean; P1, P2 : integer; X1 : Integer; Str1 : String; Begin P1 := 1; While P1 <= length(htmlContent) do If HtmlContent[P1] = '<' then begin X1 := P1; Str1 := ''; while (X1 <= length(Htmlcontent)) and (not (htmlContent[X1] in ['>',' ',#13,#10,#9])) do begin Str1 := Str1 + HtmlContent[X1]; inc(X1); end; InSimpleQuote := false; InDoubleQuote := false; {hide script content tag} if ALlowercase(str1) = '<script' then begin inc(P1, 7); While (P1 <= length(htmlContent)) do begin If (htmlContent[P1] = '''') and (not inDoubleQuote) then InSimpleQuote := Not InSimpleQuote else If (htmlContent[P1] = '"') and (not inSimpleQuote) then InDoubleQuote := Not InDoubleQuote else if (HtmlContent[P1] = '>') and (not InSimpleQuote) and (not InDoubleQuote) then break; inc(P1); end; IF P1 <= length(htmlContent) then inc(P1); P2 := P1; While (P1 <= length(htmlContent)) do begin if (HtmlContent[P1] = '<') then begin if (length(htmlContent) >= P1+8) and (HtmlContent[P1+1]='/') and (ALlowercase(HtmlContent[P1+2])='s') and (ALlowercase(HtmlContent[P1+3])='c') and (ALlowercase(HtmlContent[P1+4])='r') and (ALlowercase(HtmlContent[P1+5])='i') and (ALlowercase(HtmlContent[P1+6])='p') and (ALlowercase(HtmlContent[P1+7])='t') and (HtmlContent[P1+8]='>') then break else HtmlContent[P1] := ReplaceUnwantedTagCharBy; end; inc(P1); end; IF P1 <= length(htmlContent) then dec(P1); If DeleteBodyOfUnwantedTag then begin delete(htmlContent,P2,P1-P2 + 1); P1 := P2; end; end {hide script content tag} else if ALlowercase(str1) = '<style' then begin inc(P1, 6); While (P1 <= length(htmlContent)) do begin If (htmlContent[P1] = '''') and (not inDoubleQuote) then InSimpleQuote := Not InSimpleQuote else If (htmlContent[P1] = '"') and (not inSimpleQuote) then InDoubleQuote := Not InDoubleQuote else if (HtmlContent[P1] = '>') and (not InSimpleQuote) and (not InDoubleQuote) then break; inc(P1); end; IF P1 <= length(htmlContent) then inc(P1); P2 := P1; While (P1 <= length(htmlContent)) do begin if (HtmlContent[P1] = '<') then begin if (length(htmlContent) >= P1+7) and (HtmlContent[P1+1]='/') and (ALlowercase(HtmlContent[P1+2])='s') and (ALlowercase(HtmlContent[P1+3])='t') and (ALlowercase(HtmlContent[P1+4])='y') and (ALlowercase(HtmlContent[P1+5])='l') and (ALlowercase(HtmlContent[P1+6])='e') and (HtmlContent[P1+7]='>') then break else HtmlContent[P1] := ReplaceUnwantedTagCharBy; end; inc(P1); end; IF P1 <= length(htmlContent) then dec(P1); If DeleteBodyOfUnwantedTag then begin delete(htmlContent,P2,P1-P2 + 1); P1 := P2; end; end {hide comment content tag} else if str1 = '<!--' then begin P2 := P1; HtmlContent[P1] := ReplaceUnwantedTagCharBy; inc(P1,4); While (P1 <= length(htmlContent)) do begin if (HtmlContent[P1] = '>') and (P1>2) and (HtmlContent[P1-1]='-') and (HtmlContent[P1-2]='-') then break else if (HtmlContent[P1] = '<') then HtmlContent[P1] := ReplaceUnwantedTagCharBy; inc(P1); end; IF P1 <= length(htmlContent) then inc(P1); If DeleteBodyOfUnwantedTag then begin delete(htmlContent,P2,P1-P2); P1 := P2; end; end {hide text < tag} else if str1 = '<' then begin HtmlContent[P1] := ReplaceUnwantedTagCharBy; inc(P1); end else begin inc(P1, length(str1)); While (P1 <= length(htmlContent)) do begin If (htmlContent[P1] = '''') and (not inDoubleQuote) then InSimpleQuote := Not InSimpleQuote else If (htmlContent[P1] = '"') and (not inSimpleQuote) then InDoubleQuote := Not InDoubleQuote else if (HtmlContent[P1] = '>') and (not InSimpleQuote) and (not InDoubleQuote) then break; inc(P1); end; IF P1 <= length(htmlContent) then inc(P1); end; end else inc(p1); end; Initialization vALhtml_LstEntities := TstringList.create; With (vALhtml_LstEntities as TstringList) do begin CaseSensitive := True; Duplicates := DupAccept; Sorted := True; end; ALInitHtmlEntitiesLst(vALhtml_LstEntities); Finalization vALhtml_LstEntities.Free; end.
Program Example7; uses Crt; { Program to demonstrate the WhereX and WhereY functions. } begin Writeln('Cursor postion: X=',WhereX,' Y=',WhereY); end. {http://www.freepascal.org/docs-html/rtl/crt/wherex.html}