text
stringlengths
14
6.51M
unit ModflowHFB_WriterUnit; interface uses SysUtils, Classes, Contnrs, PhastModelUnit, CustomModflowWriterUnit, ScreenObjectUnit, ModflowPackageSelectionUnit, ModflowParameterUnit, EdgeDisplayUnit, GoPhastTypes; type TModflowHfb_Writer = class; TBarrier = class(TCustomModflowGridEdgeFeature) protected function GetRealAnnotation(Index: integer): string; override; function GetRealValue(Index: integer): double; override; public Parameter: TModflowSteadyParameter; HydraulicConductivity: double; Thickness: double; HydraulicConductivityAnnotation: string; ThicknessAnnotation: string; Function LocationSame(ABarrier: TBarrier): boolean; procedure WriteBarrier(Writer: TModflowHfb_Writer; const Comment: string); end; TParamList = class(TObject) private FScreenObjectList: TList; FBarrierList: TList; FParam: TModflowSteadyParameter; function GetScreenObjectCount: integer; function GetScreenObject(Index: integer): TScreenObject; function GetBarrier(Index: integer): TBarrier; function GetBarrierCount: integer; public procedure AddScreenObject(ScreenObject: TScreenObject); Constructor Create(Param: TModflowSteadyParameter); Destructor Destroy; override; property ScreenObjectCount: integer read GetScreenObjectCount; property ScreenObjects[Index: integer]: TScreenObject read GetScreenObject; default; property Parameter: TModflowSteadyParameter read FParam; procedure AddBarrier(Barrier: TBarrier); property BarrierCount: integer read GetBarrierCount; property Barriers[Index: integer]: TBarrier read GetBarrier; end; TModflowHfb_Writer = class(TCustomPackageWriter) private NPHFB: integer; FParameterScreenObjectList: TStringList; procedure Evaluate; {@name fills @link(FParameterScreenObjectList) with the names of the HFB parameters except for the first position which is set to ''. The Objects property of @link(FParameterScreenObjectList) is filled with a newly created @link(TParamList) that contains all the @link(TScreenObject)s that are associated with that parameter. @link(TScreenObject)s that are not associated with any parameter are placed in the @link(TParamList) in the first position. } procedure FillParameterScreenObjectList; {@name frees all the @link(TParamList) in FParameterScreenObjectList and then clear it. } procedure ClearParameterScreenObjectList; procedure WriteDataSet1; procedure WriteDataSets2and3; procedure WriteDataSet4; procedure WriteDataSet5; procedure WriteDataSet6; protected class function Extension: string; override; function Package: TModflowPackageSelection; override; public Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override; Destructor Destroy; override; procedure WriteFile(const AFileName: string); procedure UpdateDisplay; end; implementation uses Math, RbwParser, ModflowUnitNumbers, ModflowHfbUnit, OrderedCollectionUnit, frmErrorsAndWarningsUnit, ModflowGridUnit, GIS_Functions, frmProgressUnit, frmFormulaErrorsUnit, Forms; resourcestring StrInTheHFBPackage = 'In the HFB package, one or more objects do not defin' + 'e any barriers.'; StrSIsSupposedToDe = '%s is supposed to define a flow barrier but does not' + '.'; StrInTheHFBPackage1 = 'In the HFB package, a parameter has been used withou' + 't being defined'; StrIn0sTheHFBPara = 'In %0:s the HFB parameter has been specified as %1:s ' + 'but no such parameter has been defined.'; StrNoDefinedBoundarie = 'No defined boundaries for an HFB parameter'; StrForTheParameterS = 'For the parameter %s, there are no objects that def' + 'ine the location of an HFB barrier'; StrHydraulicConductiv = '(hydraulic conductivity for the HFB package)'; StrThicknessForTheH = '(thickness for the HFB package)'; StrEvaluatingHFBPacka = 'Evaluating HFB Package data.'; StrWritingHFB6Package = 'Writing HFB6 Package input.'; StrWritingDataSet0 = ' Writing Data Set 0.'; // StrWritingDataSet1 = ' Writing Data Set 1.'; // StrWritingDataSets2and3 = ' Writing Data Sets 2 and 3.'; // StrWritingDataSet4 = ' Writing Data Set 4.'; // StrWritingDataSet5 = ' Writing Data Set 5.'; // StrWritingDataSet6 = ' Writing Data Set 6.'; Str0sIn1s = '%0:s in %1:s.'; StrHFBThicknessOrHyd = 'HFB thickness or hydraulic conductivity less than ' + 'or equal to zero'; StrLayer0dRow11 = 'Layer %0:d, Row1 %1:d, Col1 %2:d, Row2: %3:d, Col2 %4:d' + '.'; { TModflowHfb_Writer } constructor TModflowHfb_Writer.Create(Model: TCustomModel; EvaluationType: TEvaluationType); begin inherited; FParameterScreenObjectList:= TStringList.Create; end; destructor TModflowHfb_Writer.Destroy; begin ClearParameterScreenObjectList; FParameterScreenObjectList.Free; inherited; end; procedure TModflowHfb_Writer.Evaluate; var ParmIndex: integer; ScreenObjectList: TParamList; ScreenObjectIndex: Integer; ScreenObject: TScreenObject; SegmentIndex: integer; SegmentList: TList; PriorSection: integer; ASegment: TCellElementSegment; PriorCount: Integer; Compiler: TRbwParser; DataToCompile: TModflowDataObject; DataSetFunction: string; HydraulicConductivityExpression: TExpression; ThicknessExpression: TExpression; PriorSegments: TList; SubsequentSegments: TList; HydCondComment: string; ThicknessComment: string; procedure HandleSection; var Segment: TCellElementSegment; SegmentIndex: Integer; MinX, MinY, MaxX, MaxY: double; ColumnCenter: double; RowCenter: double; Grid: TModflowGrid; MidCellX, MidCellY: double; CrossRow, CrossColumn: integer; Barrier: TBarrier; Angle: double; Start: integer; procedure AssignValues; var Formula: string; begin UpdateCurrentScreenObject(ScreenObject); UpdateCurrentSegment(Segment); UpdateCurrentSection(Segment.SectionIndex); UpdateGlobalLocations(Segment.Col, Segment.Row, Segment.Layer, eaBlocks, Model); try HydraulicConductivityExpression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError(ScreenObject.Name, StrHydraulicConductiv, ScreenObject.ModflowHfbBoundary.HydraulicConductivityFormula, E.Message); ScreenObject.ModflowHfbBoundary.HydraulicConductivityFormula := '0.'; Formula := ScreenObject.ModflowHfbBoundary.HydraulicConductivityFormula; Compiler.Compile(Formula); HydraulicConductivityExpression := Compiler.CurrentExpression; HydraulicConductivityExpression.Evaluate; end; end; Barrier.HydraulicConductivity := HydraulicConductivityExpression.DoubleResult; Barrier.HydraulicConductivityAnnotation := HydCondComment; try ThicknessExpression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError(ScreenObject.Name, StrThicknessForTheH, ScreenObject.ModflowHfbBoundary.ThicknessFormula, E.Message); ScreenObject.ModflowHfbBoundary.ThicknessFormula := '0.'; Formula := ScreenObject.ModflowHfbBoundary.ThicknessFormula; Compiler.Compile(Formula); ThicknessExpression := Compiler.CurrentExpression; ThicknessExpression.Evaluate; end; end; Barrier.Thickness := ThicknessExpression.DoubleResult; Barrier.ThicknessAnnotation := ThicknessComment; end; function PreviousBarrierExists: boolean; var Index: Integer; AnotherBarrier: TBarrier; begin result := False; for Index := ScreenObjectList.BarrierCount - 1 downto Start do begin AnotherBarrier :=ScreenObjectList.Barriers[Index]; result := Barrier.LocationSame(AnotherBarrier); if result then Exit; end; end; begin Start := ScreenObjectList.BarrierCount; Grid := Model.ModflowGrid; for SegmentIndex := 0 to SegmentList.Count - 1 do begin Segment := SegmentList[SegmentIndex]; if Model.IsLayerSimulated(Segment.Layer) then begin MinX := Min(Segment.X1, Segment.X2); MaxX := Max(Segment.X1, Segment.X2); MinY := Min(Segment.Y1, Segment.Y2); MaxY := Max(Segment.Y1, Segment.Y2); ColumnCenter := Grid.ColumnCenter(Segment.Col); RowCenter := Grid.RowCenter(Segment.Row); if (MinX <= ColumnCenter) and (MaxX > ColumnCenter) then begin MidCellY := (ColumnCenter-Segment.X1)/(Segment.X2-Segment.X1) *(Segment.Y2-Segment.Y1) + Segment.Y1; if MidCellY > RowCenter then begin CrossRow := Segment.Row -1; end else begin CrossRow := Segment.Row +1; end; if (CrossRow >=0) and (CrossRow < Grid.RowCount) then begin Barrier := TBarrier.Create(Model); Barrier.FCol1 := Segment.Col; Barrier.FCol2 := Segment.Col; Barrier.FRow1 := Segment.Row; Barrier.FRow2 := CrossRow; Barrier.FLayer := Segment.Layer; Barrier.Parameter := ScreenObjectList.Parameter; if PreviousBarrierExists then begin Barrier.Free; end else begin ScreenObjectList.AddBarrier(Barrier); AssignValues; if ScreenObject.ModflowHfbBoundary.AdjustmentMethod <> amNone then begin Angle := ArcTan2(Segment.Y1-Segment.Y2,Segment.X1-Segment.X2); case ScreenObject.ModflowHfbBoundary.AdjustmentMethod of amNone: Assert(False); amAllEdges: Barrier.HydraulicConductivity := Barrier.HydraulicConductivity * Abs(Cos(Angle)); amNearlyParallel: begin While Angle > Pi/2 do begin Angle := Angle - Pi; end; While Angle < -Pi/2 do begin Angle := Angle + Pi; end; if (Angle > Pi/4) or (Angle < -Pi/4) then begin Barrier.HydraulicConductivity := 0; end else begin Barrier.HydraulicConductivity := Barrier.HydraulicConductivity/Abs(Cos(Angle)); end; end; else Assert(False); end; end; end; end; end; if (MinY <= RowCenter) and (MaxY > RowCenter) then begin MidCellX := (RowCenter-Segment.Y1)/(Segment.Y2-Segment.Y1) *(Segment.X2-Segment.X1) + Segment.X1; if MidCellX > ColumnCenter then begin CrossColumn := Segment.Col +1; end else begin CrossColumn := Segment.Col -1; end; if (CrossColumn >=0) and (CrossColumn < Grid.ColumnCount) then begin Barrier := TBarrier.Create(Model); Barrier.FCol1 := Segment.Col; Barrier.FCol2 := CrossColumn; Barrier.FRow1 := Segment.Row; Barrier.FRow2 := Segment.Row; Barrier.FLayer := Segment.Layer; Barrier.Parameter := ScreenObjectList.Parameter; if PreviousBarrierExists then begin Barrier.Free; end else begin ScreenObjectList.AddBarrier(Barrier); AssignValues; if ScreenObject.ModflowHfbBoundary.AdjustmentMethod <> amNone then begin Angle := ArcTan2(Segment.X1-Segment.X2,Segment.Y1-Segment.Y2); case ScreenObject.ModflowHfbBoundary.AdjustmentMethod of amNone: Assert(False); amAllEdges: Barrier.HydraulicConductivity := Barrier.HydraulicConductivity * Abs(Cos(Angle)); amNearlyParallel: begin While Angle > Pi/2 do begin Angle := Angle - Pi; end; While Angle < -Pi/2 do begin Angle := Angle + Pi; end; if (Angle > Pi/4) or (Angle < -Pi/4) then begin Barrier.HydraulicConductivity := 0; end else begin Barrier.HydraulicConductivity := Barrier.HydraulicConductivity/Abs(Cos(Angle)); end; end; else Assert(False); end; end; end; end; end; end; end; end; begin frmErrorsAndWarnings.BeginUpdate; try frmErrorsAndWarnings.RemoveWarningGroup(Model, StrInTheHFBPackage); frmErrorsAndWarnings.RemoveWarningGroup(Model, StrInTheHFBPackage1); frmErrorsAndWarnings.RemoveWarningGroup(Model, StrNoDefinedBoundarie); frmErrorsAndWarnings.RemoveWarningGroup(Model, StrHFBThicknessOrHyd); frmProgressMM.AddMessage(StrEvaluatingHFBPacka); FillParameterScreenObjectList; PriorSegments := TList.Create; SubsequentSegments := TList.Create; SegmentList := TList.Create; try for ParmIndex := 0 to FParameterScreenObjectList.Count - 1 do begin ScreenObjectList := FParameterScreenObjectList.Objects[ParmIndex] as TParamList; for ScreenObjectIndex := 0 to ScreenObjectList.ScreenObjectCount - 1 do begin PriorCount := ScreenObjectList.BarrierCount; ScreenObject := ScreenObjectList[ScreenObjectIndex]; if ScreenObject.Deleted then begin Continue; end; if not ScreenObject.UsedModels.UsesModel(Model) then begin Continue; end; // Initialize HydraulicConductivityExpression and // ThicknessExpression. DataToCompile := TModflowDataObject.Create; try DataToCompile.Compiler := Model.GetCompiler(dsoTop, eaBlocks); DataToCompile.DataSetFunction := ScreenObject.ModflowHfbBoundary.HydraulicConductivityFormula; DataToCompile.AlternateName := 'HFB Hydraulic Conductivity'; DataToCompile.AlternateDataType := rdtDouble; (ScreenObject.Delegate as TModflowDelegate).InitializeExpression( Compiler, DataSetFunction, HydraulicConductivityExpression, nil, DataToCompile); HydCondComment := Format(Str0sIn1s, [ScreenObject.ModflowHfbBoundary.HydraulicConductivityFormula, ScreenObject.Name]); DataToCompile.DataSetFunction := ScreenObject.ModflowHfbBoundary.ThicknessFormula; DataToCompile.AlternateName := 'HFB Thickness'; (ScreenObject.Delegate as TModflowDelegate).InitializeExpression( Compiler, DataSetFunction, ThicknessExpression, nil, DataToCompile); ThicknessComment := Format(Str0sIn1s, [ScreenObject.ModflowHfbBoundary.ThicknessFormula, ScreenObject.Name]); finally DataToCompile.Free; end; PriorSection := -1; SegmentList.Clear; for SegmentIndex := 0 to ScreenObject.Segments[Model].Count - 1 do begin ASegment := ScreenObject.Segments[Model][SegmentIndex]; if ASegment.SectionIndex <> PriorSection then begin HandleSection; PriorSection := ASegment.SectionIndex; SegmentList.Clear; end; SegmentList.Add(ASegment); end; HandleSection; if PriorCount = ScreenObjectList.BarrierCount then begin frmErrorsAndWarnings.AddWarning(Model, StrInTheHFBPackage, Format(StrSIsSupposedToDe, [ScreenObject.Name]), ScreenObject); end; end; end; finally SegmentList.Free; PriorSegments.Free; SubsequentSegments.Free; end; finally frmErrorsAndWarnings.EndUpdate; end; end; class function TModflowHfb_Writer.Extension: string; begin result := '.hfb'; end; function TModflowHfb_Writer.Package: TModflowPackageSelection; begin result := Model.ModflowPackages.HfbPackage; end; procedure TModflowHfb_Writer.UpdateDisplay; var ParmIndex: Integer; ScreenObjectList: TParamList; BarrierIndex: Integer; ScreenObjectIndex: Integer; ScreenObject: TScreenObject; begin Evaluate; if not frmProgressMM.ShouldContinue then begin Exit; end; Model.HfbDisplayer.Clear; for ParmIndex := 0 to FParameterScreenObjectList.Count - 1 do begin ScreenObjectList := FParameterScreenObjectList.Objects[ParmIndex] as TParamList; for BarrierIndex := 0 to ScreenObjectList.BarrierCount - 1 do begin Model.HfbDisplayer.Add(ScreenObjectList.Barriers[BarrierIndex]); end; for ScreenObjectIndex := 0 to ScreenObjectList.ScreenObjectCount - 1 do begin ScreenObject := ScreenObjectList.ScreenObjects[ScreenObjectIndex]; ScreenObject.ModflowHfbBoundary.BoundaryObserver.UpToDate := True; end; end; Model.HfbDisplayer.UpToDate := True; end; procedure TModflowHfb_Writer.WriteDataSet1; var MXFB: integer; NHFBNP: integer; Index: Integer; ParamList: TParamList; begin NPHFB := 0; MXFB := 0; // Start at 1 rather than 0 because the list at 0 is for // barriers that are not associated with parameters. for Index := 1 to FParameterScreenObjectList.Count - 1 do begin ParamList := FParameterScreenObjectList.Objects[Index] as TParamList; if ParamList.BarrierCount > 0 then begin Inc(NPHFB); MXFB := MXFB + ParamList.BarrierCount; end; end; Assert(FParameterScreenObjectList.Count > 0); ParamList := FParameterScreenObjectList.Objects[0] as TParamList; NHFBNP := ParamList.BarrierCount; WriteInteger(NPHFB); WriteInteger(MXFB); WriteInteger(NHFBNP); WriteString(' # Data set 1: NPHFB MXFB NHFBNP'); NewLine; end; procedure TModflowHfb_Writer.WriteDataSet4; const DataSet4Comment = ' # Data set 4: Layer IROW1 ICOL1 IROW2 ICOL2 Hydchr'; var ParamList: TParamList; BarrierIndex: Integer; Barrier: TBarrier; begin ParamList := FParameterScreenObjectList.Objects[0] as TParamList; if ParamList.BarrierCount > 0 then begin // data set 4 for BarrierIndex := 0 to ParamList.BarrierCount - 1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; Barrier := ParamList.Barriers[BarrierIndex]; Barrier.WriteBarrier(self, DataSet4Comment); end; end; end; procedure TModflowHfb_Writer.WriteDataSet5; var NACTHFB: integer; begin NACTHFB := NPHFB; WriteInteger(NACTHFB); WriteString(' # Data Set 5: NACTHFB'); NewLine; end; procedure TModflowHfb_Writer.WriteDataSet6; var Index: Integer; ParamList: TParamList; begin // Start at 1 rather than 0 because the list at 0 is for // barriers that are not associated with parameters. for Index := 1 to FParameterScreenObjectList.Count - 1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; ParamList := FParameterScreenObjectList.Objects[Index] as TParamList; if ParamList.BarrierCount > 0 then begin WriteString(ParamList.Parameter.ParameterName); WriteString(' # Data set 6: Pname'); NewLine; end; end; end; procedure TModflowHfb_Writer.WriteDataSets2and3; const DataSet3Comment = ' # Data set 3: Layer IROW1 ICOL1 IROW2 ICOL2 Factor'; var Index: Integer; ParamList: TParamList; BarrierIndex: Integer; Barrier: TBarrier; begin // Start at 1 rather than 0 because the list at 0 is for // barriers that are not associated with parameters. for Index := 1 to FParameterScreenObjectList.Count - 1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; ParamList := FParameterScreenObjectList.Objects[Index] as TParamList; if ParamList.BarrierCount > 0 then begin // data set 2 WriteString(ParamList.Parameter.ParameterName + ' '); WriteString('HFB '); WriteFloat(ParamList.Parameter.Value); WriteInteger(ParamList.BarrierCount); WriteString(' # Data set 2: PARNAM PARTYP Parval NLST'); NewLine; Model.WritePValAndTemplate(ParamList.Parameter.ParameterName, ParamList.Parameter.Value); // data set 3 for BarrierIndex := 0 to ParamList.BarrierCount - 1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; Barrier := ParamList.Barriers[BarrierIndex]; Barrier.WriteBarrier(self, DataSet3Comment); end; end; end; end; procedure TModflowHfb_Writer.WriteFile(const AFileName: string); var NameOfFile: string; begin if not Package.IsSelected then begin Exit end; if Model.PackageGeneratedExternally(StrHFB) then begin Exit; end; NameOfFile := FileName(AFileName); WriteToNameFile(StrHFB, Model.UnitNumbers.UnitNumber(StrHFB), NameOfFile, foInput, Model); Evaluate; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; OpenFile(FileName(AFileName)); try frmProgressMM.AddMessage(StrWritingHFB6Package); frmProgressMM.AddMessage(StrWritingDataSet0); WriteDataSet0; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet1); WriteDataSet1; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSets2and3); WriteDataSets2and3; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet4); WriteDataSet4; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet5); WriteDataSet5; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet6); WriteDataSet6; finally CloseFile; end; end; procedure TModflowHfb_Writer.ClearParameterScreenObjectList; var Index: Integer; begin for Index := 0 to FParameterScreenObjectList.Count - 1 do begin FParameterScreenObjectList.Objects[Index].Free; end; FParameterScreenObjectList.Clear; end; procedure TModflowHfb_Writer.FillParameterScreenObjectList; var Index: Integer; ScreenObject: TScreenObject; Boundary: THfbBoundary; ParamIndex: Integer; Param: TModflowSteadyParameter; List: TParamList; begin ClearParameterScreenObjectList; FParameterScreenObjectList.AddObject('', TParamList.Create(nil)); for ParamIndex := 0 to Model.ModflowSteadyParameters.Count-1 do begin Param := Model.ModflowSteadyParameters[ParamIndex]; if Param.ParameterType = ptHFB then begin FParameterScreenObjectList.AddObject(Param.ParameterName, TParamList.Create(Param)); end; end; for Index := 0 to Model.ScreenObjectCount - 1 do begin ScreenObject := Model.ScreenObjects[Index]; if ScreenObject.Deleted then begin Continue; end; Boundary := ScreenObject.ModflowHfbBoundary; if (Boundary <> nil) and Boundary.Used then begin ParamIndex := FParameterScreenObjectList.IndexOf(Boundary.ParameterName); if ParamIndex < 0 then begin frmErrorsAndWarnings.AddWarning(Model, StrInTheHFBPackage1, Format(StrIn0sTheHFBPara, [ScreenObject.Name, Boundary.ParameterName]), ScreenObject); ParamIndex := 0; end; List := FParameterScreenObjectList.Objects[ParamIndex] as TParamList; List.AddScreenObject(ScreenObject); end; end; for Index := 1 to FParameterScreenObjectList.Count - 1 do begin List := FParameterScreenObjectList.Objects[Index] as TParamList; if List.ScreenObjectCount = 0 then begin frmErrorsAndWarnings.AddWarning(Model, StrNoDefinedBoundarie, Format(StrForTheParameterS, [FParameterScreenObjectList[Index]]) ); end; end; end; { TParamList } procedure TParamList.AddBarrier(Barrier: TBarrier); begin FBarrierList.Add(Barrier); end; procedure TParamList.AddScreenObject(ScreenObject: TScreenObject); begin FScreenObjectList.Add(ScreenObject); end; constructor TParamList.Create(Param: TModflowSteadyParameter); begin FScreenObjectList:= TList.Create; FBarrierList := TObjectList.Create; FParam := Param; end; destructor TParamList.Destroy; begin FBarrierList.Free; FScreenObjectList.Free; inherited; end; function TParamList.GetBarrier(Index: integer): TBarrier; begin result := FBarrierList[Index]; end; function TParamList.GetBarrierCount: integer; begin result := FBarrierList.Count; end; function TParamList.GetScreenObject(Index: integer): TScreenObject; begin result := FScreenObjectList[Index]; end; function TParamList.GetScreenObjectCount: integer; begin result := FScreenObjectList.Count; end; { TBarrier } function TBarrier.GetRealAnnotation(Index: integer): string; begin result := ''; case Index of 0: begin result := HydraulicConductivityAnnotation; if Parameter <> nil then begin result := result + ' multiplied by the parameter value "' + FloatToStr(Parameter.Value) + '" assigned to the parameter "' + Parameter.ParameterName + '."'; end; end; 1: begin result := ThicknessAnnotation; end; 2: begin result := 'Hydraulic Conductivity/Thickness'; end; else Assert(False); end; end; function TBarrier.GetRealValue(Index: integer): double; begin result := 0; case Index of 0: begin result := HydraulicConductivity; if Parameter <> nil then begin result := result * Parameter.Value; end; end; 1: begin result := Thickness; end; 2: begin if Thickness = 0 then begin result := 0; end else begin result := GetRealValue(0)/Thickness; end; end; else Assert(False); end; end; function TBarrier.LocationSame(ABarrier: TBarrier): boolean; begin result := (Layer = ABarrier.Layer) and (Parameter = ABarrier.Parameter); if not Result then begin Exit; end; result := ((Col2 = ABarrier.Col1) and (Col1 = ABarrier.Col2)) or ((Col1 = ABarrier.Col1) and (Col2 = ABarrier.Col2)); if not Result then begin Exit; end; result := ((Row2 = ABarrier.Row1) and (Row1 = ABarrier.Row2)) or ((Row1 = ABarrier.Row1) and (Row2 = ABarrier.Row2)); end; procedure TBarrier.WriteBarrier(Writer: TModflowHfb_Writer; const Comment: string); var ModelLayer: integer; begin ModelLayer := Writer.Model. DataSetLayerToModflowLayer(Layer); Writer.WriteInteger(ModelLayer); Writer.WriteInteger(Row1+1); Writer.WriteInteger(Col1+1); Writer.WriteInteger(Row2+1); Writer.WriteInteger(Col2+1); if Thickness = 0 then begin Writer.WriteFloat(0); end else begin Writer.WriteFloat(HydraulicConductivity/Thickness); end; if (Thickness <= 0) or (HydraulicConductivity <= 0) then begin frmErrorsAndWarnings.AddWarning(Writer.Model, StrHFBThicknessOrHyd, Format(StrLayer0dRow11, [Layer+1, Row1, Col1, Row2, Col2])); end; Writer.WriteString(Comment); Writer.NewLine; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit Tiles; interface uses Test; type /// This stress tests the dynamic tree broad-phase. This also shows that tile /// based collision is _not_ smooth due to Box2D not knowing about adjacency. TTiles = class(TTest) const e_count = 20; private m_fixtureCount: Integer; m_createTime: Float32; public constructor Create; class function CreateTest: TTest; static; procedure Step(settings: PSettings); override; end; implementation uses System.Math, Box2D.Common, Box2D.Collision, Box2D.Dynamics, DebugDraw; { TTiles } constructor TTiles.Create; const N = 200; M = 10; var I, J: Integer; a: Float32; bd: b2BodyDef; ground, body: b2BodyWrapper; position: b2Vec2; shape: b2PolygonShapeWrapper; x, y, deltaX, deltaY: b2Vec2; timer: b2Timer; begin inherited; m_fixtureCount := 0; timer := b2Timer.Create; a := 0.5; bd := b2BodyDef.Create; bd.position.y := -a; ground := m_world.CreateBody(@bd); {$IF TRUE} position := b2Vec2.Create; position.y := 0.0; for I := 0 to M - 1 do begin position.x := -N * a; for J := 0 to N - 1 do begin shape := b2PolygonShapeWrapper.Create; shape.SetAsBox(a, a, position, 0.0); ground.CreateFixture(&shape, 0.0); Inc(m_fixtureCount); position.x := position.x + 2.0 * a; shape.Destroy; end; position.y := position.y - 2.0 * a; end; {$ELSE} position := b2Vec2.Create; position.x := -N * a; for I := 0 to N - 1 do begin position.y := 0.0; for J := 0 to M - 1 do begin shape := b2PolygonShapeWrapper.Create; shape.SetAsBox(a, a, position, 0.0); ground.CreateFixture(&shape, 0.0); position.y := position.y - 2.0 * a; shape.Destroy; end; position.x := position.x + 2.0 * a; end; {$ENDIF} a := 0.5; shape := b2PolygonShapeWrapper.Create; shape.SetAsBox(a, a); x := b2Vec2.Create(-7.0, 0.75); y := b2Vec2.Create; deltaX := b2Vec2.Create(0.5625, 1.25); deltaY := b2Vec2.Create(1.125, 0.0); for I := 0 to e_count - 1 do begin y := x; for j := i to e_count -1 do begin bd := b2BodyDef.Create; bd.&type := b2_dynamicBody; bd.position := y; //if (i = 0) and (j = 0) then // bd.allowSleep := false //else // bd.allowSleep := true; body := m_world.CreateBody(@bd); body.CreateFixture(shape, 5.0); Inc(m_fixtureCount); y := y + deltaY; end; x := x + deltaX; end; shape.Destroy; m_createTime := timer.GetMilliseconds; end; class function TTiles.CreateTest: TTest; begin Result := TTiles.Create; end; procedure TTiles.Step(settings: PSettings); var cm: b2ContactManagerWrapper; LBroadPhase: b2BroadPhaseWrapper; minimumNodeCount: int32; height: int32; leafCount: int32; minimumHeight: float32; begin (* const b2ContactManager& cm = m_world->GetContactManager(); int32 height = cm.m_broadPhase.GetTreeHeight(); int32 leafCount = cm.m_broadPhase.GetProxyCount(); int32 minimumNodeCount = 2 * leafCount - 1; float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f)); g_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); m_textLine += DRAW_STRING_NEW_LINE; Test::Step(settings); g_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", m_createTime, m_fixtureCount); m_textLine += DRAW_STRING_NEW_LINE; //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; //if (m_stepCount == 400) //{ // tree->RebuildBottomUp(); //} *) cm := m_world.GetContactManager; LBroadPhase := cm.Get_m_broadPhase; height := LBroadPhase.GetTreeHeight; leafCount := LBroadPhase.GetProxyCount; minimumNodeCount := 2 * leafCount - 1; minimumHeight := Round(Log10(minimumNodeCount) / Log10(2.0)); g_debugDraw.DrawString(5, m_textLine, 'dynamic tree height = %d, min = %d', [height, Trunc(minimumHeight)]); m_textLine := m_textLine + DRAW_STRING_NEW_LINE; inherited Step(settings); g_debugDraw.DrawString(5, m_textLine, 'create time = %6.2f ms, fixture count = %d', [m_createTime, m_fixtureCount]); m_textLine := m_textLine + DRAW_STRING_NEW_LINE; //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; //if (m_stepCount == 400) //{ // tree->RebuildBottomUp(); //} end; initialization RegisterTest(TestEntry.Create('Tiles', @TTiles.CreateTest)); end.
unit uServerPOS; interface uses System.Classes, uModApp, uDBUtils, Rtti, Data.DB, SysUtils, StrUtils, uModSO, uModSuplier, Datasnap.DBClient, System.Generics.Collections, System.DateUtils, System.JSON, System.JSON.Types, uServerClasses, uModBeginningBalance, uModSetupPOS, uModTransaksi; type TPOS = class(TBaseServerClass) private FCRUD: TCrud; function GetCRUD: TCrud; property CRUD: TCrud read GetCRUD write FCRUD; public function GetBeginningBalance(UserID: string): TModBeginningBalance; function GetListPendingTransAll: TDataset; function GetListTransaksi(StartDate, EndDate: TDatetime): TDataset; function GetListPendingTransByUserID(aUserID: string): TDataset; function GetListPendingTransByUserIDAndDate(aUserID: string; aDate: TDateTime): TDataset; function GetPendingTransByMember(aMemberID: string; aDate: TDateTime): TDataset; function GetListPendingTransDetailByHeaderID(aHeaderID: string): TDataset; function GetServerDate: TDatetime; function GetTransactionNo(aPOSCODE, aUNITID: string): string; function HasBarcode(aBarCode: string): Boolean; function LookupBarang(sFilter: string): TDataset; function LookupMember(sFilter: string): TDataset; end; TCRUDPos = class(TCRUD) private function GenerateSQLCounter(AObject: TModTransaksi): string; protected function AfterSaveToDB(AObject: TModApp): Boolean; override; function BeforeSaveToDB(AObject: TModApp): Boolean; override; public end; implementation uses uServerModelHelper; function TPOS.GetBeginningBalance(UserID: string): TModBeginningBalance; var S: string; begin Result := TModBeginningBalance.Create; S := 'select a.beginning_balance_id' +' from beginning_balance a' +' inner join setuppos b on a.setuppos_id = b.setuppos_id' +' inner join shift c on c.shift_id = a.shift_id' +' where b.setuppos_is_active = 1' +' and CONVERT(TIME(0),GETDATE()) between CONVERT(TIME(0),c.shift_start_time)' +' and CONVERT(TIME(0),c.shift_end_time)' +' and cast(a.balance_shift_date as date) = cast(getDate() as date)' +' and a.BALANCE_STATUS = ''OPEN'' ' +' and a.AUT$USER_ID = ' + QuotedStr(USERID); with TDButils.OpenQuery(s) do begin if not eof then begin Result.Free; Result := CRUD.Retrieve( TModBeginningBalance.ClassName, FieldByName('beginning_balance_id').AsString) as TModBeginningBalance; end; end; end; function TPOS.GetCRUD: TCrud; begin if not Assigned(FCRUD) then FCRUD := TCrud.Create(Self); Result := FCRUD; end; function TPOS.GetListPendingTransAll: TDataset; var S: string; begin S := 'SELECT M.MEMBER_CARD_NO as "No Kartu", ' + ' M.MEMBER_NAME as "Nama Member", ' + ' T.TRANS_NO as "No Transaksi", ' + ' T.TRANS_DATE as "Tanggal Trans", ' + ' T.TRANS_TOTAL_TRANSACTION as "Total", ' + ' T.TRANS_IS_ACTIVE, ' + ' T.TRANSAKSI_ID, ' + ' T.MEMBER_ID ' + ' FROM TRANSAKSI T ' + ' INNER JOIN MEMBER M ON (M.MEMBER_ID = T.MEMBER_ID) ' + ' WHERE (T.TRANS_IS_PENDING = 1) ' + ' AND cast(T.TRANS_DATE as date) = ' + TDBUtils.QuotD(Now()); // + ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO'; Result := TDBUtils.OpenQuery(S); end; function TPOS.GetListTransaksi(StartDate, EndDate: TDatetime): TDataset; var S: string; begin S := 'SELECT T.TRANS_NO as "No Transaksi", ' + ' M.MEMBER_CARD_NO as "No Kartu", ' + ' M.MEMBER_NAME as "Nama Member", ' + ' T.TRANS_DATE as "Tanggal Trans", ' + ' T.TRANS_TOTAL_TRANSACTION as "Total", ' + ' T.TRANS_IS_ACTIVE, ' + ' T.TRANSAKSI_ID, ' + ' T.MEMBER_ID ' + ' FROM TRANSAKSI T ' + ' INNER JOIN MEMBER M ON (M.MEMBER_ID = T.MEMBER_ID) ' + ' WHERE cast(T.TRANS_DATE as date) between ' + TDBUtils.QuotD(StartDate) + ' and ' + TDBUtils.QuotD(EndDate); // + ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO'; Result := TDBUtils.OpenQuery(S); end; function TPOS.GetListPendingTransByUserID(aUserID: string): TDataset; var S: string; begin S := 'SELECT M.MEMBER_CARD_NO as "No Kartu", ' + ' M.MEMBER_NAME as "Nama Member", ' + ' T.TRANS_NO as "No Transaksi", ' + ' T.TRANS_DATE as "Tanggal Trans", ' + ' T.TRANS_TOTAL_TRANSACTION as "Total", ' + ' T.TRANS_IS_ACTIVE, ' + ' T.TRANSAKSI_ID, ' + ' T.MEMBER_ID ' + ' FROM MEMBER M ' + ' INNER JOIN TRANSAKSI T ON (M.MEMBER_ID = T.MEMBER_ID) ' + ' WHERE (T.TRANS_IS_PENDING = 1) ' + ' AND T.OP_CREATE = ' + QuotedStr(aUserID) + ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO'; Result := TDBUtils.OpenQuery(S); end; function TPOS.GetListPendingTransByUserIDAndDate(aUserID: string; aDate: TDateTime): TDataset; var S: string; begin S := 'SELECT M.MEMBER_CARD_NO as "No Kartu", ' + ' M.MEMBER_NAME as "Nama Member", ' + ' T.TRANS_NO as "No Transaksi", ' + ' T.TRANS_DATE as "Tanggal Trans", ' + ' T.TRANS_TOTAL_TRANSACTION as "Total", ' + ' T.TRANS_IS_ACTIVE, ' + ' T.TRANSAKSI_ID, ' + ' T.MEMBER_ID ' + ' FROM MEMBER M ' + ' INNER JOIN TRANSAKSI T ON (M.MEMBER_ID = T.MEMBER_ID) ' + ' WHERE (T.TRANS_IS_PENDING = 1) ' + ' AND T.OP_CREATE = ' + QuotedStr(aUserID) + ' AND cast(T.TRANS_DATE as date) = ' + TDBUtils.QuotD(aDate) + ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO'; Result := TDBUtils.OpenQuery(S); end; function TPOS.GetPendingTransByMember(aMemberID: string; aDate: TDateTime): TDataset; var S: string; begin S := 'SELECT A.TRANSAKSI_ID, A.TRANS_NO, A.TRANS_DATE,' +' A.TRANS_TOTAL_TRANSACTION, B.MEMBER_CARD_NO, B.MEMBER_NAME' +' FROM TRANSAKSI A' +' INNER JOIN MEMBER B ON A.MEMBER_ID = B.MEMBER_ID' +' WHERE A.TRANS_IS_PENDING = 1' +' AND A.MEMBER_ID = ' + QuotedStr(aMemberID) +' AND cast(A.TRANS_DATE as date) = ' + TDBUtils.QuotD(aDate); Result := TDBUtils.OpenQuery(S); end; function TPOS.GetListPendingTransDetailByHeaderID(aHeaderID: string): TDataset; var S: string; begin S := 'SELECT TD.TRANSAKSI_DETIL_ID, ' + ' TD.TRANSD_BRG_CODE, ' + ' TD.TRANSD_TRANS_NO, ' + ' TD.BARANG_HARGA_JUAL_ID, ' + ' TD.TRANSD_QTY, ' + ' S.SAT_CODE, ' + ' TD.TRANSD_SELL_PRICE, ' + ' BHJ.BHJ_SELL_PRICE, ' + ' BHJ.REF$TIPE_HARGA_ID, ' + ' TD.TRANSD_DISC_MAN, ' + ' TD.OTO_CODE ' + ' FROM TRANSAKSI_DETIL TD' + ' INNER JOIN BARANG_HARGA_JUAL BHJ ON (TD.BARANG_HARGA_JUAL_ID = BHJ.BARANG_HARGA_JUAL_ID) ' + ' INNER JOIN REF$SATUAN S ON S.REF$SATUAN_ID = BHJ.REF$SATUAN_ID ' + ' WHERE TD.TRANSAKSI_ID = ' + QuotedStr(aHeaderID) + ' ORDER BY TD.TRANSAKSI_DETIL_ID'; Result := TDBUtils.OpenQuery(S); end; function TPOS.GetServerDate: TDatetime; begin Result := Now(); end; function TPOS.GetTransactionNo(aPOSCODE, aUNITID: string): string; var CounterNo: Integer; S: string; TransactionNo: string; begin Result := ''; S := 'select SETUPPOS_NO_TRANSAKSI, SETUPPOS_COUNTER_NO from SETUPPOS' +' WHERE AUT$UNIT_ID = ' + QuotedStr(aUNITID) +' AND SETUPPOS_TERMINAL_CODE = ' + QuotedStr(aPOSCODE) +' AND cast(SETUPPOS_DATE as Date) = ' + TDBUtils.QuotD(Now()); with TDBUtils.OpenQuery(S) do begin Try if not eof then begin TransactionNo := FieldByName('SETUPPOS_NO_TRANSAKSI').AsString; CounterNo := FieldByName('SETUPPOS_COUNTER_NO').AsInteger; Result := Copy(TransactionNo,1,8) + FormatFloat('0000',CounterNo+1); end; Finally Free; End; end; end; function TPOS.HasBarcode(aBarCode: string): Boolean; var s: string; begin s := 'select * from BARANG_HARGA_JUAL A' +' inner join REF$KONVERSI_SATUAN B ON A.BARANG_ID = B.BARANG_ID' +' AND A.REF$SATUAN_ID = B.REF$SATUAN_ID' +' WHERE B.KONVSAT_BARCODE = ' + QuotedStr(aBarCode); with TDBUtils.OpenQuery(s) do begin try if not eof then Result := True else Result := False; finally free; end; end; end; function TPOS.LookupBarang(sFilter: string): TDataset; var S: string; begin S := 'select a.brg_code, s.SAT_CODE, a.brg_name, b.BHJ_SELL_PRICE,' +' b.BHJ_DISC_NOMINAL, b.BHJ_SELL_PRICE_DISC, a.brg_is_active,' +' b.REF$SATUAN_ID' +' from barang a' +' inner join barang_harga_jual b on a.BARANG_ID = b.BARANG_ID' +' left join ref$satuan s on b.REF$SATUAN_ID = s.REF$SATUAN_ID' +' left join REF$TIPE_HARGA th on th.REF$TIPE_HARGA_ID = b.REF$TIPE_HARGA_ID' // +' and a.brg_is_active = 1 +' where th.TPHRG_CODE = ''H004'' ' +' and a.brg_is_active = 1' +' and a.brg_pos_lookup = 1' +' and upper(a.brg_name) like ' + QuotedStr(sFilter) +' order by a.brg_name'; Result := TDBUtils.OpenQuery(s); end; function TPOS.LookupMember(sFilter: string): TDataset; var S: string; begin S := 'select MEMBER_ID, MEMBER_CARD_NO AS KODE, MEMBER_NAME AS NAMA, MEMBER_ADDRESS AS ALAMAT' +' from MEMBER WHERE MEMBER_IS_ACTIVE = 1 AND MEMBER_IS_VALID = 1' +' and upper(MEMBER_NAME) like ' + QuotedStr(sFilter) +' order by MEMBER_NAME'; Result := TDBUtils.OpenQuery(s); end; function TCRUDPos.AfterSaveToDB(AObject: TModApp): Boolean; var s: string; begin if AObject is TModTransaksi then begin if AObject.ObjectState = 1 then begin s := GenerateSQLCounter(TModTransaksi(AObject)); TDBUtils.ExecuteSQL(S, False); end; end; Result := True; end; function TCRUDPos.BeforeSaveToDB(AObject: TModApp): Boolean; var lKuponBotol: TModTransKuponBotol; begin if AObject is TModTransaksi then begin for lKuponBotol in TModTransaksi(AObject).KuponBotols do begin lKuponBotol.TKB_POS_TRANS_NO := TModTransaksi(AObject).TRANS_NO; lKuponBotol.TKB_STATUS := 'CLOSE'; end; end; Result := True; end; function TCRUDPos.GenerateSQLCounter(AObject: TModTransaksi): string; begin AObject.BALANCE.Reload(False); Result := 'update setuppos ' + ' set setuppos_counter_no = setuppos_counter_no + 1' + ' where setuppos_id = ' + QuotedStr(AObject.BALANCE.SETUPPOS.ID) + ' and AUT$UNIT_ID = ' + QuotedStr(AObject.AUTUNIT.ID) + ';'; end; end.
unit NtGraphic; interface uses Graphics; type TNtGraphicResoure = class helper for TGraphic procedure LoadResource( resType, resName: PChar; instance: THandle = 0); overload; procedure LoadResource( const resType, resName: String; instance: THandle = 0); overload; end; implementation uses Classes, NtBase; procedure TNtGraphicResoure.LoadResource( resType, resName: PChar; instance: THandle); var stream: TResourceStream; begin stream := TNtResources.GetResourceStream(resType, resName, instance); try Self.LoadFromStream(stream); finally stream.Free; end; end; procedure TNtGraphicResoure.LoadResource( const resType, resName: String; instance: THandle); begin LoadResource(PChar(resType), PChar(resName), instance); end; end.
unit ResultsUnit; interface uses Classes; type resultContainerClass = class(TObject) private protected public sinZ: Double; //Стержень shankTopX: Double; shankTopY: Double; shankBottomX: Double; shankBottomY: Double; //Каретка carriageX: Double; //Груз cargoX: Double; cargoY: Double; //Угол BalancerAngle:Double; //Время currentTime: Double; destructor Destroy; override; end; implementation destructor resultContainerClass.Destroy; begin inherited; end; end.
unit uFrmStart; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentWizard, ImgList, StdCtrls, ExtCtrls, ComCtrls, uSQLFileReader, IniFiles, jpeg, Buttons, ADODB, DB; Const SQL_REP_SERVER = '#SERVER#'; SQL_REP_DIR = '#REP_DIR#'; SQL_REP_DB = '#DATABASE#'; SQL_REP_USER = '#USER#'; SQL_REP_PW = '#PW#'; SQL_REP_INI_NUM = '#START_NUMBER#'; SQL_REP_END_NUM = '#END_NUMBER#'; SQL_REP_SUB_SVR = '#SUBSC_SERVER#'; SQL_REP_SUB_DB = '#SUBSC_DB#'; type TFrmStart = class(TParentWizard) tsInfro: TTabSheet; tsPublisher: TTabSheet; Label1: TLabel; tsConnection: TTabSheet; Label5: TLabel; Label6: TLabel; Label7: TLabel; edtServer: TEdit; edtUserName: TEdit; edtPW: TEdit; cbxDB: TComboBox; Panel2: TPanel; ImgIntro: TImage; Panel12: TPanel; pnlTopic1: TPanel; lblTopic1: TLabel; Shape1: TShape; Label36: TLabel; Label28: TLabel; Label2: TLabel; edtRepliDirectory: TEdit; SpeedButton1: TSpeedButton; OP: TOpenDialog; tsFinish: TTabSheet; Panel3: TPanel; imgFinalize: TImage; Label3: TLabel; Label4: TLabel; Panel4: TPanel; Panel5: TPanel; Label11: TLabel; Shape4: TShape; ADOCommand: TADOCommand; pnlInfo: TPanel; lbInfo: TLabel; pbScript: TProgressBar; lbRepInfo: TLabel; GroupBox1: TGroupBox; Label12: TLabel; edtIniInterval: TEdit; Label13: TLabel; edtEndInterval: TEdit; cbxStoreList: TComboBox; Label14: TLabel; Label15: TLabel; Label16: TLabel; cbxStoreType: TComboBox; btnHelpStoreType: TSpeedButton; btnShowScript: TButton; btnShollAll: TButton; lbFileInfo: TLabel; Label17: TLabel; lbPServer: TLabel; lbPDataBase: TLabel; Label20: TLabel; lbSServer: TLabel; lbSDatabase: TLabel; Label8: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure cbxStoreListChange(Sender: TObject); procedure btnHelpStoreTypeClick(Sender: TObject); procedure btnShowScriptClick(Sender: TObject); procedure btnShollAllClick(Sender: TObject); private { Private declarations } fIniConfig : TIniFile; fSQLText, fSQLAllText : String; fTotalStores : Integer; function SetConnection:boolean; function SetStoreIntervals:Boolean; procedure GetDBList; procedure GetStoresList; procedure GetConnectionValues; procedure Hidde(b:Boolean); function CreateRepliDir:Boolean; function GetRestricForms:String; protected function DoFinish:Integer; override; function TestBeforeNavigate:Boolean; override; function OnAfterChangePage:Boolean; override; public { Public declarations } end; var FrmStart: TFrmStart; implementation uses uDMParent, uMsgBox, uParamFunctions, ufrmServerInfo, uSystemConst, uFrmMeno; {$R *.dfm} function TFrmStart.GetRestricForms:String; begin Case cbxStoreType.ItemIndex of 0 : begin //SERVER Result := fIniConfig.ReadString('RestrictForms', 'SERVER', ''); end; 1 : begin //CLIENT Result := fIniConfig.ReadString('RestrictForms', 'CLIENT', ''); end; end; end; procedure TFrmStart.GetConnectionValues; var sResult : String; FrmServrInfo : TFrmServerInfo; bAbort : Boolean; begin try FrmServrInfo := TFrmServerInfo.Create(self); FrmServrInfo.RegistryKey := 'Repli_LocalServer'; sResult := FrmServrInfo.Start('4', False, '', bAbort); DMParent.fSQLConnectParam.Server := ParseParam(sResult, SV_SERVER); DMParent.fSQLConnectParam.DBAlias := ParseParam(sResult, SV_DATABASE); DMParent.fSQLConnectParam.UserName := ParseParam(sResult, SV_USER); DMParent.fSQLConnectParam.PW := ParseParam(sResult, SV_PASSWORD); DMParent.fSQLConnectParam.WinLogin := (ParseParam(sResult, SV_WIN_LOGIN)[1] in ['Y']); DMParent.fSQLConnectParam.UseNetLib := (ParseParam(sResult, SV_USE_NETLIB)[1] = 'Y'); edtServer.Text := DMParent.fSQLConnectParam.Server; edtUserName.Text := DMParent.fSQLConnectParam.UserName; edtPW.Text := DMParent.fSQLConnectParam.PW; finally FreeAndNil(FrmServrInfo); end; end; procedure TFrmStart.GetDBList; begin Try Screen.Cursor:= crHourGlass; with DMParent.quFreeSQL do begin if Active then Close; SQL.Text := 'exec sp_databases'; Open; First; While not EOF do begin cbxDB.Items.Add(Fields.Fields[0].AsString); Next; end; Close; end; Finally Screen.Cursor:= crDefault; end; end; function TFrmStart.SetConnection:boolean; var sResult : String; begin Result := True; if DMParent.ADODBConnect.Connected then Exit; try Screen.Cursor:= crHourGlass; with DMParent do begin if not DMParent.fSQLConnectParam.WinLogin then if DMParent.fSQLConnectParam.UseNetLib then sResult := SetConnectionStr(edtUserName.Text, edtPW.Text, 'Master', edtServer.Text) else sResult := SetConnectionStrNoNETLIB(edtUserName.Text, edtPW.Text, 'Master', edtServer.Text) else if DMParent.fSQLConnectParam.UseNetLib then sResult := SetWinConnectionStr('Master', edtServer.Text) else sResult := SetWinConnectionStrNoNETLIB('Master', edtServer.Text); Try ADOConnectionString := sResult; ADODBConnect.Open; except Result := False; end; end; finally Screen.Cursor:= crDefault; end; end; procedure TFrmStart.GetStoresList; var i : integer; begin cbxStoreList.Items.Clear; for i:=1 to fTotalStores do cbxStoreList.Items.Add('Store '+IntToStr(i)); end; function TFrmStart.OnAfterChangePage:Boolean; begin Result := False; Hidde(False); lbRepInfo.Visible := (pgOption.ActivePageIndex=0) or (pgOption.ActivePageIndex=4); Case pgOption.ActivePageIndex of 0 : Hidde(True); 1 : if edtServer.Text = '' then GetConnectionValues; 2 : begin if cbxStoreList.Items.Count=0 then begin GetStoresList; cbxStoreList.ItemIndex := 0; end; if cbxDB.Items.Count=0 then begin GetDBList; cbxDB.Text := DMParent.fSQLConnectParam.DBAlias; end; if cbxStoreType.ItemIndex = -1 then cbxStoreType.ItemIndex := 0; edtRepliDirectory.Text := DMParent.LocalPath; end; 3 : begin imgFinalize.Picture.Assign(ImgIntro.Picture); lbPServer.Caption := '- Publish Server: ' + edtServer.Text; lbPDataBase.Caption := '- Publish Database: ' + cbxDB.Text; Hidde(True); end; end; Result := True; end; function TFrmStart.TestBeforeNavigate:Boolean; begin Result := False; Case pgOption.ActivePageIndex of 1 : begin if (not SetConnection) then begin MsgBox('Connection error', vbCritical + vbOkOnly); Exit; end; end; 2 : begin if cbxDB.Text = '' then begin MsgBox('Select a database', vbCritical + vbOkOnly); Exit; end; end; end; Result := True; end; function TFrmStart.SetStoreIntervals:Boolean; var s, f : String; iID : Integer; begin Result := True; try with ADOCommand do begin CommandText := 'use '+cbxDB.Text; Execute; end; except raise; Result := False; end; //Add constraint try with ADOCommand do begin CommandText := 'ALTER TABLE Sis_CodigoIncremental ADD CONSTRAINT MaxValue_Check CHECK (UltimoCodigo <= '+edtEndInterval.Text+')'; Execute; end; except raise; Result := False; end; //First store does not need to update if cbxStoreList.ItemIndex <> 0 then begin //Add Update Last Cod try with ADOCommand do begin CommandText := 'UPDATE Sis_CodigoIncremental SET UltimoCodigo = UltimoCodigo + ' + edtIniInterval.Text; Execute; end; except raise; Result := False; end; try iID := DMParent.GetNextID('InvoiceGen.IDInvoice'); with ADOCommand do begin iID := iID + StrToInt(edtIniInterval.Text); CommandText := 'DBCC CHECKIDENT (' + QuotedStr('Key_IDInvoice') + ', reseed, '+ IntToStr(iID)+') '; Execute; end; iID := DMParent.GetNextID('Fin_Lancamento.IDLancamento'); with ADOCommand do begin iID := iID + StrToInt(edtIniInterval.Text); CommandText := 'DBCC CHECKIDENT (' + QuotedStr('Key_IDLancamento') + ', reseed, '+ IntToStr(iID)+') '; Execute; end; iID := DMParent.GetNextID('SaleItemCommission.IDSaleItemCommission'); with ADOCommand do begin iID := iID + StrToInt(edtIniInterval.Text); CommandText := 'DBCC CHECKIDENT (' + QuotedStr('Key_IDSaleItemCommission') + ', reseed, '+ IntToStr(iID)+') '; Execute; end; iID := DMParent.GetNextID('Invoice.IDPreSale'); with ADOCommand do begin iID := iID + StrToInt(edtIniInterval.Text); CommandText := 'DBCC CHECKIDENT (' + QuotedStr('Key_IDPreSale') + ', reseed, '+ IntToStr(iID)+') '; Execute; end; iID := DMParent.GetNextID('PreInventoryMov.IDPreInventoryMov'); with ADOCommand do begin iID := iID + StrToInt(edtIniInterval.Text); CommandText := 'DBCC CHECKIDENT (' + QuotedStr('Key_IDPreInventoryMov') + ', reseed, '+ IntToStr(iID)+') '; Execute; end; iID := DMParent.GetNextID('InventoryMov.IDInventoryMov'); with ADOCommand do begin iID := iID + StrToInt(edtIniInterval.Text); CommandText := 'DBCC CHECKIDENT (' + QuotedStr('Key_IDInventoryMov') + ', reseed, '+ IntToStr(iID)+') '; Execute; end; except raise; Result := False; end; end; //Add restric form for mainretail Case cbxStoreType.ItemIndex of 0 : begin s := QuotedStr(SYSTEM_SERVER_TYPE); f := GetRestricForms; end; 1 : begin s := QuotedStr(SYSTEM_CLIENT_TYPE); f := GetRestricForms; end; end; try with ADOCommand do begin CommandText := 'UPDATE Sys_Module SET VersionType = ' + QuotedStr(s) + ', RestricForms = ' + QuotedStr(f); Execute; end; except raise; Result := False; end; end; function TFrmStart.CreateRepliDir:Boolean; begin try if not DirectoryExists(edtRepliDirectory.Text) then Result := CreateDir(edtRepliDirectory.Text); if not DirectoryExists(edtRepliDirectory.Text+'\out') then Result := CreateDir(edtRepliDirectory.Text+'\out'); if not DirectoryExists(edtRepliDirectory.Text+'\global') then Result := CreateDir(edtRepliDirectory.Text+'\global'); except raise; Result := False; end; end; function TFrmStart.DoFinish:Integer; begin if not CreateRepliDir then begin MsgBox('Error creating directory', vbCritical + vbOkOnly); Exit; end; lbFileInfo.Caption := ''; if not SetStoreIntervals then Exit; MsgBox('Wizard completed', vbInformation + vbOkOnly); end; procedure TFrmStart.FormCreate(Sender: TObject); begin inherited; fIniConfig := TIniFile.Create(DMParent.LocalPath+'replconfig.ini'); fTotalStores := fIniConfig.ReadInteger('Settings', 'TotalStores', 10); end; procedure TFrmStart.FormDestroy(Sender: TObject); begin inherited; fIniConfig.Free; end; procedure TFrmStart.SpeedButton1Click(Sender: TObject); begin inherited; if OP.Execute then edtRepliDirectory.Text := ExtractFileDir(OP.FileName); end; procedure TFrmStart.Hidde(b:Boolean); begin inherited; b := not b; ShapeImage.Visible := b; ImageClass.Visible := b; lbEditName.Visible := b; lbEditDescription.Visible := b; end; procedure TFrmStart.FormShow(Sender: TObject); begin inherited; Hidde(True); end; procedure TFrmStart.cbxStoreListChange(Sender: TObject); var i : LongInt; begin inherited; i := 100000000; if cbxStoreList.ItemIndex = 0 then begin edtIniInterval.Text := IntToStr(1); edtEndInterval.Text := IntToStr(i); end else begin edtIniInterval.Text := IntToStr(i*(cbxStoreList.ItemIndex)); edtEndInterval.Text := IntToStr(i*(cbxStoreList.ItemIndex+1)); end; end; procedure TFrmStart.btnHelpStoreTypeClick(Sender: TObject); var Text : String; begin inherited; case cbxStoreType.ItemIndex of 0 : Text := 'Regular store'+#13#10+#13#10+'This option allows users to display models and barcodes.'+#13#10+' Users CANNOT add or updated model and barcode data. '; 1 : Text := 'Master store'+#13#10+#13#10+'Users can update and add new models and barcode. '+#13#10+'You can also purchase items and distribute them to the other stores.'; end; ShowMessage(Text); end; procedure TFrmStart.btnShowScriptClick(Sender: TObject); begin inherited; with TFrmMemo.Create(Self) do Start(fSQLText); end; procedure TFrmStart.btnShollAllClick(Sender: TObject); begin inherited; with TFrmMemo.Create(Self) do Start(fSQLAllText); end; end.
unit mainUn; {Here are some more tips: - If you want a smoother transition between 2 frames, you could use blur. There are blur components but you could also make a somewhat simpler blur, render the previous frame as well but then almost transparent. - When using linear or mipmap filters for min/mag filter, you might see the colors used around the sprite. For example, if the background color is pink in your sprite images the sprites might have a pink edge around them. You can avoid this by using 'nearest' for min/mag. If that's not nice enough (the edges might get too 'blocky'), you can also use images with a alpha channel inside. The bitmap, tga or whatever format has a fourth channel (rgb and a) which you can use to draw the transparency. Its more accurate and gives a nice effect, but your images will be bigger of course. - When performing the punch move in the demo, you'll see that the poor guy gets thinner when his fist goes forward. This is because the plane keeps the same width while the image requires more space. You could solve this by making the plane wider. You could make a 'width' property for each frame. } interface uses SysUtils, Classes, Graphics, Controls, Forms, GLCadencer, GLTexture, ExtCtrls, GLWin32Viewer, GLScene, GLObjects, StdCtrls, GLMaterial, GLCoordinates, GLCrossPlatform, GLRenderContextInfo, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; Panel1: TPanel; matLib: TGLMaterialLibrary; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; GLDirectOpenGL1: TGLDirectOpenGL; GLCadencer1: TGLCadencer; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure GLDirectOpenGL1Render(Sender: TObject; var rci: TGLRenderContextInfo); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure Button1Click(Sender: TObject); private public end; { A set of frames. Stuff like 'walk', 'stand' or 'die'. This animation is pretty simple, the interval between each frame is the same and you can't do much other stuff with it. But of course, you can add some more details. For example an array with the interval per frame instead of 1 value for the entire animation. } TAnimation = record speed : single; // Interval between the frames frameCount : integer; // Amount of frames nextAnimation : integer; // Index to the animation that follows on this one, // if it points to itself, we have a looped animation material : integer; // Index to the material library end; // TAnimation TAnimation_Data = record animations : array of TAnimation; end; // TAnimation_Data { Custom sprite class. I use a TGLplane but you could also use TGLsprite or TGLHUDSprite. Keep in mind that HUD sprites are always on top and use different coordinates (x,y are in pixels, not '3D-world' coordinates! } TMySprite = class (TGLPlane) private anim_Index : integer; // Current animation, index for the animations array anim_Pos : integer; // Current frame anim_Delta : single; // Elapsed time since a frame got switched public { Animation } animation_Data : TAnimation_Data; constructor create; procedure setAnimation( const index : integer ); procedure render( var rci : TGLRenderContextInfo ); end; // TMySprite const ANIM_STAND = 0; ANIM_PUNCH = 1; var Form1 : TForm1; animations : TAnimation_Data; // The frames/data for sprite1 and 2 sprite1, sprite2 : TMySprite; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); procedure addTransparentTexture( const name, fname : string ); begin with matlib.AddTextureMaterial( name, fname ) do begin material.Texture.TextureMode := tmModulate; material.Texture.TextureWrap := twNone; material.Texture.ImageAlpha := tiaTopLeftPointColorTransparent; material.BlendingMode := bmTransparency; end; end; // addTransparentTexture begin { Add sprite textures, we have a stand and punch animation } addTransparentTexture( 'stand', 'anim_Stand.bmp' ); addTransparentTexture( 'punch', 'anim_Punch.bmp' ); { Create a set of animations { Let both sprites share the same animation set. We do it hard-coded here, but you could write a nice unit that loads packages with sprite info of course. } setLength( animations.animations, 2 ); { 1, stand animation, a looped animation } animations.animations[0].speed := 0.1; animations.animations[0].frameCount := 3; animations.animations[0].nextAnimation := 0; // 0 is the index of the 'stand' animation animations.animations[0].material := matLib.Materials.GetLibMaterialByName( 'stand' ).Index; { 2, punch animation, after the animation, switch back to stand } animations.animations[1].speed := 0.2; animations.animations[1].frameCount := 4; animations.animations[1].nextAnimation := 0; // 0 is the index of the 'stand' animation animations.animations[1].material := matLib.Materials.GetLibMaterialByName( 'punch' ).Index; { Create 2 sprites and place them somewhere } sprite1 := TMySprite.create; sprite1.animation_Data := animations; sprite1.Position.X := -1; sprite1.Position.Z := -5; sprite1.Width := 1; sprite1.Height := 2.5; sprite2 := TMySprite.create; sprite2.animation_Data := animations; sprite2.Position.X := +1; sprite2.Position.Z := -5; sprite2.Width := 2; sprite2.Height := 5; { Let sprite 2 look the opposite way. The most effective way might be by reversing the texture coordinates but as we don't have access to them we'll do it by setting the scale.x on -1. !! Face culling must be off when rendering reversed sprites, otherwise you won't see them! } sprite2.Scale.X := -1; end; // formCreate procedure TForm1.GLDirectOpenGL1Render(Sender: TObject; var rci: TGLRenderContextInfo); begin { Render via a directOpenGL (so don't insert the planes into the GLScene object list. You don't have to use this approach but I prefer it as you have more control over the rendering process. But like I said, you could also insert the sprites simply in a TGLScene objects list and let him do the job. Bind your sprite to a MaterialLibrary via the material.libmaterialName property. You still need to use a 'beforeRender' event for each sprite as you need to modify the texture coordinates first, otherwise you can't share the same texture for multiple sprites with different frame positions. } sprite1.render( rci ); sprite2.render( rci ); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin self.GLSceneViewer1.Refresh; end; procedure TForm1.Button1Click(Sender: TObject); begin { Punch animation } if sender = button1 then sprite1.setAnimation( ANIM_PUNCH ) else sprite2.setAnimation( ANIM_PUNCH ); end; // button click { TMySprite } constructor TMySprite.create; begin inherited create( nil ); { Reset animation stuff } anim_Pos := 0; anim_Index := 0; anim_Delta := 0; end; // TMySprite Create procedure TMySprite.setAnimation(const index: integer); begin anim_Index := index; anim_Pos := 0; anim_Delta := 0; end; // setAnimation procedure TMySprite.render(var rci: TGLRenderContextInfo); var fw : single; begin { Notice that if the overall framerate differs, the animation speed of the sprites will differ as well. Iy you want to solve this, take a look at the delta-time of a GLCadencer or something } with animation_Data.animations[ anim_Index ] do begin anim_Delta := anim_Delta + speed; if anim_Delta >=1 then begin { Next frame } inc( anim_Pos ); { If we're at the end of the current animation, switch to the next } if anim_Pos = frameCount then setAnimation( nextAnimation ); anim_Delta := 0; end; end; { Modify the material texcoords to our current frame } with animation_Data.animations[ anim_Index ] do begin fw := 1 / frameCount; form1.matLib.Materials[ material ].TextureScale.X := fw; // fit to the frame size form1.matLib.Materials[ material ].TextureOffset.X := fw * anim_Pos;// pick the current frame { Now render the plane with the modified material } form1.matLib.Materials[ material ].Apply( rci ); inherited render( rci ); form1.matLib.Materials[ material ].UnApply( rci ) end; end; // render end.
unit sheet; {******************************************************************************* Program Modifications: ------------------------------------------------------------------------------- Date ID Description ------------------------------------------------------------------------------- 08-10-2006 GN01 To preserve the leading zero's in a string field as excel converted them to Integers ********************************************************************************} interface uses windows, sysutils, db,comobj, dialogs; var xla : variant; xlw : variant; LCID : integer; Sheet1 : boolean; ExcelOpen : boolean = false; NextRow : integer; isTemplate:boolean; procedure NewExcelSheet(template:string; titles:array of string); Procedure ExcelTitles(titles:array of string; additionaltitle:string); Procedure PushToExcel(sp_nm:string; ds : tDataset; titles:array of string; var additionaltitle:string); procedure RunExcelMacro; function OpenExcel(template:string):boolean; procedure CloseExcel; procedure ShowExcel; procedure SaveExcel(const filename:string); Procedure ShutDownExcel; implementation function OpenExcel(template:string):boolean; begin try xla := createoleobject('Excel.application');//CoApplication.Create; // LCID := GetUserDefaultLCID; if template='' then xlw := xla.Workbooks.Add else begin xlw := xla.Workbooks.Add(template); // workbook based on template isTemplate := true; end; Sheet1 := true; result := true; except result := false; end; ExcelOpen := result; end; procedure CloseExcel; begin if ExcelOpen then begin xla.Quit; ExcelOpen := false; end; end; function VerifyExcelOpen:boolean; begin if ExcelOpen then try xla.range['A1', 'A1'].Value := xla.range['A1', 'A1'].Value; result := true; except CloseExcel; result := false; end else result := false; end; Procedure ExcelTitles(titles:array of string; additionaltitle:string); var i,j : integer; begin j := 1; for i := 0 to high(titles) do if (titles[i] <> '') then begin xla.range['A'+inttostr(j), 'A'+inttostr(j)].Value := titles[i]; xla.range['A'+inttostr(j), 'A'+inttostr(j)].Font.Bold := true; inc(j); end; if (additionaltitle <> '') then begin xla.range['A'+inttostr(j), 'A'+inttostr(j)].Value := additionaltitle; xla.range['A'+inttostr(j), 'A'+inttostr(j)].Font.Bold := true; inc(j); end; xla.range['A1','A1'].Font.Size := 12; xla.range['A1','A1'].Font.Bold := true; xla.range['A'+inttostr(j), 'A'+inttostr(j)].Value := 'Date: '+ FormatDateTime('mmmm d, yyyy h:nn am/pm', Now); end; procedure NewExcelSheet(template:string; titles:array of string); var i:integer; begin if VerifyExcelOpen or OpenExcel(template) then try if not sheet1 then begin // xla.sheets.Add(null,null,null,null,lcid); if template='' then xlw := xla.Workbooks.Add else begin xlw := xla.Workbooks.Add(template); // workbook based on template isTemplate := true; end; end; sheet1 := false; NextRow := 4; for i := 0 to high(titles) do if titles[i] <> '' then inc(NextRow); {we only want to reserve rows for the titles. We'll actually place the titles on the sheet after we've auto-fit the columns by using ExcelTitles()} finally end; end; procedure removehardreturn(var v:variant); var s:string; i:integer; begin s:= vartostr(v); i:=pos(#13#10,s); while i > 0 do begin delete(s,i,1); i:=pos(#13#10,s); end; i:=pos(#9,s); while i > 0 do begin delete(s,i,1); i:=pos(#9,s); end; if length(s)>910 then setlength(s,910); v := s; end; //GN01 function IsNumber(mStr: string): Boolean; var Code: Integer; Value: Double; begin try StrToFloat(mStr); Result := True; //val(mStr, Value, Code); //Result := (Code = 0); except on EConvertError do Result := False; on EInvalidOp do Result := False; end; end; { IsNumber } Procedure PushToExcel(sp_nm:string; ds : tDataset; titles:array of string; var additionaltitle:string); function columnname(i : integer):string; var n : integer; begin n := ((i-1) div 26); if n > 0 then result := chr(n+64) else result := ''; result := result + chr((i - (n*26))+64); end; var fldCnt : integer; i,j : integer; firstcol : char; lastcol, s : string; row : array[0..1000] of variant; MultiSheet : boolean; SheetCol,SheetVal : string; orgNextRow : integer; strRow:string; begin try MultiSheet := (pos('SheetName',ds.fields[0].fieldname)=1); SheetCol := ds.fields[0].fieldname; if (MultiSheet) then begin delete(SheetCol,1,9); if pos('dummy',lowercase(SheetCol))>0 then delete(Sheetcol,pos('dummy',lowercase(SheetCol)),5); end; with ds do begin disablecontrols; SheetVal := ''; try if ds.RecordCount<>0 then SheetVal := fields[0].value; except end; fldcnt := fieldcount; for j := 0 to fieldcount-1 do if pos('dummy',lowercase(fields[j].fieldname))>0 then dec(fldcnt); firstcol := 'A'; lastcol := columnname(ord(firstcol)-65+fldcnt); orgNextRow := NextRow; i := NextRow; inc(NextRow); first; while not eof do begin fldcnt := 0; for j := 0 to fieldcount-1 do if pos('dummy',lowercase(fields[j].fieldname))=0 then begin row[fldcnt] := fields[j].value; case ds.Fields[j].DataType of ftString: begin if not VarIsNull(row[fldcnt]) then begin s := row[fldcnt]; if (Length(s) > 0) and IsNumber(s) and (s[1] = '0') then row[fldcnt] := '''' + row[fldcnt]; end; end;//GN01 ftSmallint: ; ftInteger: ; ftWord:; ftBoolean:; ftFloat:; ftCurrency:; ftDate:; ftTime:; ftDateTime:; ftBytes:; ftMemo : removehardreturn(row[fldcnt]); ftFmtMemo:; end; // xla.cell[NextRow,fldcnt ].value :=fields[j].value; inc(fldcnt); end; try xla.Range[firstcol+inttostr(NextRow), lastcol+inttostr(NextRow)].value := vararrayof(slice(row,fldcnt)); except // columnname(ord(firstcol)-65+fldcnt); for j := 0 to fldcnt-1 do try xla.range[columnname(ord(firstcol)-64+j)+inttostr(nextrow), columnname(ord(firstcol)-64+j)+inttostr(nextrow)].value := row[j]; except try xla.range[columnname(ord(firstcol)-64+j)+inttostr(nextrow), columnname(ord(firstcol)-64+j)+inttostr(nextrow)].value := '#N/A'; messagedlg('Invalid value in record '+inttostr(nextrow)+': can''t write "' + varastype(row[j],varstring) + '" to Excel. Replacing it with #N/A.',mtwarning,[mbok],0); except end; end; end; inc(NextRow); next; if (MultiSheet) and (SheetVal <> fields[0].value) then begin fldcnt := 0; for j := 0 to fieldcount-1 do if pos('dummy',lowercase(fields[j].fieldname))=0 then begin row[fldcnt] := fields[j].fieldname; inc(fldcnt); end; xla.range[firstcol+inttostr(i),lastcol+inttostr(i)].value := vararrayof(row); xla.Range[firstcol+inttostr(i),lastcol+inttostr(i)].Font.Bold := True; if not isTemplate then xla.Columns.AutoFit; try xla.activesheet.name := sheetval; except end; if SheetCol <> '' then additionaltitle := SheetCol + ': '+SheetVal else additionaltitle := SheetVal; ExcelTitles(titles,additionaltitle); xla.Worksheets.Add; i := orgNextRow; NextRow := i+1; SheetVal := fields[0].value; end; end; fldcnt := 0; for j := 0 to fieldcount-1 do if pos('dummy',lowercase(fields[j].fieldname))=0 then begin row[fldcnt] := fields[j].fieldname; inc(fldcnt); end; xla.range[firstcol+inttostr(i),lastcol+inttostr(i)].value := vararrayof(row); xla.Range[firstcol+inttostr(i),lastcol+inttostr(i)].Font.Bold := True; if not isTemplate then xla.Columns.AutoFit; if (multiSheet) then begin xla.activesheet.name := sheetval; if SheetCol <> '' then additionaltitle := SheetCol + ': '+SheetVal else additionaltitle := SheetVal; ExcelTitles(titles,additionaltitle); end; lastcol := 'A'+inttostr(i); xla.range[lastcol,lastcol].addcomment(sp_nm); xla.range[lastcol,lastcol].comment.Shape.Width := 300; first; enablecontrols; inc(NextRow,1); end; finally end; end; procedure RunExcelMacro; begin try xla.Run('AutoDashboard'); except end; end; procedure ShowExcel; begin if ExcelOpen then xla.Visible := true; //Keeping the handle of open cause problems when openning other excel docs. ExcelOpen:=false; xla:=unassigned; end; procedure SaveExcel(const filename:string); begin if fileexists(filename) then deletefile(filename); { xlw.SaveAs( filename, xlWorkbookNormal, '', '', False, False, xlNoChange, xlLocalSessionChanges, true, 0, 0, LCID); } xlw.close(true,filename,false); ExcelOpen := false; end; Procedure ShutDownExcel; begin xla.Quit; end; end.
unit EditArtist; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Objects, FMX.Edit, Artist, EditArtistController; type TfrmEditArtist = class(TForm) TopLabel: TLabel; ButtonLayout: TLayout; btCancel: TButton; btSave: TButton; BottomLayout: TLayout; CenterLayout: TLayout; NameLayout: TLayout; edName: TEdit; lbName: TLabel; CenterLayout2: TLayout; edGenre: TEdit; lbGenre: TLabel; procedure btCancelClick(Sender: TObject); procedure btSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FController: TEditArtistController; public procedure SetArtist(ArtistId: Variant); end; implementation {$R *.fmx} procedure TFrmEditArtist.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFrmEditArtist.btSaveClick(Sender: TObject); var Artist: TArtist; begin Artist := FController.Artist; Artist.ArtistName := edName.Text; Artist.Genre := edGenre.Text; FController.SaveArtist(Artist); ModalResult := mrOk; end; procedure TfrmEditArtist.FormCreate(Sender: TObject); begin FController := TEditArtistController.Create; end; procedure TfrmEditArtist.FormDestroy(Sender: TObject); begin FController.Free; end; procedure TFrmEditArtist.SetArtist(ArtistId: Variant); var Artist: TArtist; begin FController.Load(ArtistId); Artist := FController.Artist; edName.Text := Artist.ArtistName; if Artist.Genre.HasValue then edGenre.Text := Artist.Genre; end; end.
unit Class_MembMenu; //YXC_2010_05_08_22_53_35 //TBL_MEMB_MENU //会员套餐 interface uses Classes,SysUtils,ADODB,Class_DBPool; type TMembMenu=class(TObject) public UnitLink:string; //单位编码 MembIdex:Integer; //会员序列 MenuIdex:Integer; //套餐序列 MembMenu:Integer; //会员套餐 ThisDate:TDateTime;//办理时间 MenuNumb:Integer; //套餐次数 * 每次服务后,扣掉的是这个数. MembCost:Double; //套餐价格 MenuGift:Integer; //赠送次数 MenuTotl:Integer; //服务次数合计 MenuType:Integer; //套餐性质 public MenuName:string; //套餐名称 public procedure InsertDB(AADOCon:TADOConnection); procedure UpdateDB(AADOCon:TADOConnection); procedure DeleteDB(AADOCon:TADOConnection); function GetNextCode(AADOCon:TADOConnection):Integer; function GetMenuType:string; public constructor Create; public class function ReadDS(AADODS:TADODataSet):TMembMenu; class function ReadDB(AADOCon:TADOConnection;ASQL:string):TMembMenu; class function StrsDB(AADOCon:TADOConnection):TStringList;overload; class function StrsDB(ASQL:string):TStringList;overload; class function StrsDB(AADOCon:TADOConnection;ASQL:string):TStringList;overload; end; implementation uses UtilLib; { TMembMenu } constructor TMembMenu.Create; begin MenuType:=1; end; procedure TMembMenu.DeleteDB(AADOCon: TADOConnection); begin end; function TMembMenu.GetMenuType: string; begin Result:='购买'; if MenuType=0 then begin Result:='赠送'; end; end; function TMembMenu.GetNextCode(AADOCon: TADOConnection): Integer; begin Result:=TryCheckField(AADOCon,'MEMB_MENU','TBL_MEMB_MENU',['UNIT_LINK',UnitLink,'MEMB_IDEX',MembIdex,'MENU_IDEX',MenuIdex]); end; procedure TMembMenu.InsertDB(AADOCon: TADOConnection); var ADOCmd : TADOCommand; begin try ADOCmd := TADOCommand.Create(nil); ADOCmd.Connection := AADOCon; ADOCmd.Prepared := True; with ADOCmd do begin CommandText:= 'INSERT INTO TBL_MEMB_MENU ' + ' (UNIT_LINK, MEMB_IDEX, MENU_IDEX,Memb_Menu, THIS_DATE,MENU_NUMB,MENU_COST,MENU_GIFT,MENU_TOTL,MENU_TYPE)' + ' VALUES(:UNIT_LINK, :MEMB_IDEX, :MENU_IDEX,:Memb_Menu,:THIS_DATE,:MENU_NUMB,:MENU_COST,:MENU_GIFT,:MENU_TOTL,:MENU_TYPE)'; with Parameters do begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('MEMB_IDEX').Value := MEMBIDEX; ParamByName('MENU_IDEX').Value := MENUIDEX; ParamByName('Memb_Menu').Value := MembMenu; ParamByName('MENU_NUMB').Value := MENUNUMB; ParamByName('THIS_DATE').Value := ThisDate; ParamByName('MENU_COST').Value := MembCost; ParamByName('MENU_GIFT').Value := MenuGift; ParamByName('MENU_TOTL').Value := MenuTotl; ParamByName('MENU_TYPE').Value := MenuType; end; Execute; end; finally FreeAndNil(ADOCmd); end; end; class function TMembMenu.ReadDB(AADOCon: TADOConnection; ASQL: string): TMembMenu; var ADODS:TADODataSet; begin Result:=nil; try ADODS:=TADODataSet.Create(nil); ADODS.Connection:=AADOCon; ADODS.Prepared :=True; if ASQL='' then raise Exception.Create('ASQL=NIL'); ADODS.CommandText:=ASQL; ADODS.Open; ADODS.First; if ADODS.RecordCount=0 then Exit; Result:=ReadDS(ADODS); finally FreeAndNil(ADODS); end; end; class function TMembMenu.ReadDS(AADODS: TADODataSet): TMembMenu; begin Result:=TMembMenu.Create; with Result do begin UNITLINK := Trim(AADODS.FieldByName('UNIT_LINK').AsString); MEMBIDEX := AADODS.FieldByName('MEMB_IDEX').AsInteger; MENUIDEX := AADODS.FieldByName('MENU_IDEX').AsInteger; MembMenu := AADODS.FieldByName('Memb_Menu').AsInteger; ThisDate := AADODS.FieldByName('THIS_DATE').AsDateTime; MENUNUMB := AADODS.FieldByName('MENU_NUMB').AsInteger; MembCost := AADODS.FieldByName('MENU_COST').AsFloat; if AADODS.FieldDefs.IndexOf('MENU_GIFT')<>-1 then begin MenuGift:=AADODS.FieldByName('MENU_GIFT').AsInteger; end; if AADODS.FieldDefs.IndexOf('MENU_TOTL')<>-1 then begin MenuTotl:=AADODS.FieldByName('MENU_TOTL').AsInteger; end; if AADODS.FieldDefs.IndexOf('MENU_TYPE')<>-1 then begin MenuType:=AADODS.FieldByName('MENU_TYPE').AsInteger; end; if AADODS.FieldDefs.IndexOf('MENU_NAME')<>-1 then begin MenuName:=AADODS.FieldByName('MENU_NAME').AsString; end; end; end; class function TMembMenu.StrsDB(ASQL: string): TStringList; var ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); Result:=StrsDB(ADOCon,ASQL); finally FreeAndNil(ADOCon); end; end; class function TMembMenu.StrsDB(AADOCon: TADOConnection; ASQL: string): TStringList; var ADODS:TADODataSet; AObj :TMembMenu; begin Result:=nil; try ADODS:=TADODataSet.Create(nil); ADODS.Connection:=AADOCon; ADODS.Prepared:=True; if ASQL='' then raise Exception.Create('ASQL=NIL'); ADODS.CommandText:=ASQL; ADODS.Open; ADODS.First; if ADODS.RecordCount=0 then Exit; Result:=TStringList.Create; while not ADODS.Eof do begin AObj:=ReadDS(ADODS); Result.AddObject('',AObj); ADODS.Next; end; finally FreeAndNil(ADODS); end; end; class function TMembMenu.StrsDB(AADOCon: TADOConnection): TStringList; begin end; procedure TMembMenu.UpdateDB(AADOCon: TADOConnection); var ADOCmd : TADOCommand; begin try ADOCmd := TADOCommand.Create(nil); ADOCmd.Connection := AADOCon; ADOCmd.Prepared := True; with ADOCmd do begin CommandText:= 'UPDATE TBL_MEMB_MENU SET' + ' MENU_NUMB = :MENU_NUMB' + ' WHERE UNIT_LINK = :UNIT_LINK' + ' AND MEMB_IDEX = :MEMB_IDEX' + ' AND MENU_IDEX = :MENU_IDEX' + ' AND Memb_Menu = :MEMB_MENU'; with Parameters do begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('MEMB_IDEX').Value := MEMBIDEX; ParamByName('MENU_IDEX').Value := MENUIDEX; ParamByName('MENU_NUMB').Value := MENUNUMB; ParamByName('MEMB_MENU').Value:= MembMenu; end; Execute; end; finally FreeAndNil(ADOCmd); end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [FIN_LANCAMENTO_PAGAR] 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 FinLancamentoPagarController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, FinLancamentoPagarVO, FinParcelaPagarVO, FinLctoPagarNtFinanceiraVO; type TFinLancamentoPagarController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaFinLancamentoPagarVO; class function ConsultaObjeto(pFiltro: String): TFinLancamentoPagarVO; class procedure Insere(pObjeto: TFinLancamentoPagarVO); class function Altera(pObjeto: TFinLancamentoPagarVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM; var ObjetoLocal: TFinLancamentoPagarVO; class function TFinLancamentoPagarController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TFinLancamentoPagarVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TFinLancamentoPagarController.ConsultaLista(pFiltro: String): TListaFinLancamentoPagarVO; begin try ObjetoLocal := TFinLancamentoPagarVO.Create; Result := TListaFinLancamentoPagarVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TFinLancamentoPagarController.ConsultaObjeto(pFiltro: String): TFinLancamentoPagarVO; begin try Result := TFinLancamentoPagarVO.Create; Result := TFinLancamentoPagarVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); Filtro := 'ID_FIN_LANCAMENTO_PAGAR = ' + IntToStr(Result.Id); // Objetos Vinculados Result.FornecedorNome := Result.FornecedorVO.Nome; Result.DocumentoOrigemSigla := Result.DocumentoOrigemVO.SiglaDocumento; // Listas Result.ListaParcelaPagarVO := TListaFinParcelaPagarVO(TT2TiORM.Consultar(TFinParcelaPagarVO.Create, Filtro, True)); Result.ListaLancPagarNatFinanceiraVO := TListaFinLctoPagarNtFinanceiraVO(TT2TiORM.Consultar(TFinLctoPagarNtFinanceiraVO.Create, Filtro, True)); finally end; end; class procedure TFinLancamentoPagarController.Insere(pObjeto: TFinLancamentoPagarVO); var UltimoID:Integer; ParcelaPagar: TFinParcelaPagarVO; LancamentoNaturezaFinanceira: TFinLctoPagarNtFinanceiraVO; i: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // Parcela Pagar for I := 0 to pObjeto.ListaParcelaPagarVO.Count - 1 do begin ParcelaPagar := pObjeto.ListaParcelaPagarVO[I]; ParcelaPagar.IdFinLancamentoPagar := UltimoID; TT2TiORM.Inserir(ParcelaPagar); end; // Natureza Financeira for I := 0 to pObjeto.ListaLancPagarNatFinanceiraVO.Count - 1 do begin LancamentoNaturezaFinanceira := pObjeto.ListaLancPagarNatFinanceiraVO[i]; LancamentoNaturezaFinanceira.IdFinLancamentoPagar := UltimoID; TT2TiORM.Inserir(LancamentoNaturezaFinanceira); end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TFinLancamentoPagarController.Altera(pObjeto: TFinLancamentoPagarVO): Boolean; var ParcelaPagar: TFinParcelaPagarVO; LancamentoNaturezaFinanceira: TFinLctoPagarNtFinanceiraVO; i: Integer; begin try Result := TT2TiORM.Alterar(pObjeto); // Parcela Pagar for I := 0 to pObjeto.ListaParcelaPagarVO.Count - 1 do begin ParcelaPagar := pObjeto.ListaParcelaPagarVO[I]; if ParcelaPagar.Id > 0 then Result := TT2TiORM.Alterar(ParcelaPagar) else begin ParcelaPagar.IdFinLancamentoPagar := pObjeto.Id; Result := TT2TiORM.Inserir(ParcelaPagar) > 0; end; end; // Natureza Financeira for I := 0 to pObjeto.ListaLancPagarNatFinanceiraVO.Count - 1 do begin LancamentoNaturezaFinanceira := pObjeto.ListaLancPagarNatFinanceiraVO[i]; if LancamentoNaturezaFinanceira.Id > 0 then Result := TT2TiORM.Alterar(LancamentoNaturezaFinanceira) else begin LancamentoNaturezaFinanceira.IdFinLancamentoPagar := pObjeto.Id; Result := TT2TiORM.Inserir(LancamentoNaturezaFinanceira) > 0; end; end; finally end; end; class function TFinLancamentoPagarController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TFinLancamentoPagarVO; begin try ObjetoLocal := TFinLancamentoPagarVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; initialization Classes.RegisterClass(TFinLancamentoPagarController); finalization Classes.UnRegisterClass(TFinLancamentoPagarController); end.
{ Laz-Model Copyright (C) 2017 Peter Dyson. Initial Lazarus port Portions (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uRtfdLabel; {$mode objfpc}{$H+} interface uses Classes, LCLIntf, LCLType, Controls, ExtCtrls, Graphics, uModel, uModelEntity, uListeners, uConfig; const ClassShadowWidth = 3; cDefaultWidth = 185; cDefaultHeight = 41; cDefaultLeft = 4; cDefaultRight = cDefaultWidth-cDefaultLeft-ClassShadowWidth; cDefaultlblHeight = 15; cIconW = 10; cMargin = 4; var TopColor : array[boolean] of TColor = ($EAF4F8, clWhite); type TRtfdODLabel = class(TComponent, IModelEntityListener) private FOwner: TCustomControl; FCaption: TCaption; FCanvas: TCanvas; FAlignment: TAlignment; FTransparent: Boolean; fFont: TFont; function GetAlignment: TAlignment; procedure SetAlignment(const Value: TAlignment); procedure SetTransparent(const Value: Boolean); procedure SetWantedBounds; protected FBox: TRect; Entity: TModelEntity; procedure Paint; virtual; procedure SetText(const Value: TCaption); function GetText: TCaption; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); reintroduce; virtual; destructor Destroy; override; procedure Change(Sender: TModelEntity); virtual; procedure Paint(width: integer); virtual; procedure AddChild(Sender: TModelEntity; NewChild: TModelEntity); virtual; procedure Remove(Sender: TModelEntity); virtual; procedure EntityChange(Sender: TModelEntity); virtual; function WidthNeeded : integer; virtual; function Height: integer; property ModelEntity: TModelEntity read Entity; property Alignment: TAlignment read GetAlignment write SetAlignment default taLeftJustify; property Transparent: Boolean read FTransparent write SetTransparent; property Canvas: TCanvas read FCanvas write FCanvas; property Parent: TCustomControl read FOwner; property Font: TFont read fFont write fFont; property Caption: TCaption read FCaption write FCaption; end; implementation function TRtfdODLabel.GetAlignment: TAlignment; begin Result := FAlignment; end; procedure TRtfdODLabel.SetAlignment(const Value: TAlignment); begin if Value <> FAlignment then begin FAlignment := Value; FOwner.Invalidate; end; end; procedure TRtfdODLabel.SetTransparent(const Value: Boolean); begin if Value <> FTransparent then begin FTransparent := Value; FOwner.Invalidate; end; end; procedure TRtfdODLabel.SetWantedBounds; var Al: integer; Rect: TRect; DC: HDC; txt: string; begin Rect := FBox; txt := FCaption + ' '; case FAlignment of taLeftJustify: Al := DT_LEFT; taRightJustify: Al := DT_RIGHT; taCenter: Al := DT_CENTER; end; Al := Al or DT_CALCRECT or DT_NOPREFIX; DC := GetDC(0); SelectObject(DC, fFont.Handle); DrawText(DC, PChar(txt), Length(txt), Rect, Al); ReleaseDC(0,DC); FBox.Right := Rect.Right; end; procedure TRtfdODLabel.Paint(width: integer); begin FBox.Right := width; Paint; end; procedure TRtfdODLabel.Paint; var Al: Integer; oldFont: TFont; begin oldFont := fCanvas.Font; FCanvas.Font := fFont; if FTransparent then begin FCanvas.Brush .Style := bsClear; FCanvas.Brush.Color := TopColor[ Config.IsLimitedColors ]; end else begin FCanvas.Brush.Style := bsClear; FCanvas.Brush.Color := clWhite; end; FCanvas.Pen.color := clBlack; case FAlignment of taLeftJustify: Al := DT_LEFT; taRightJustify: Al := DT_RIGHT; taCenter: Al := DT_CENTER; end; DrawText(FCanvas.Handle,PChar(fCaption),Length(fCaption),FBox,Al); fCanvas.Font := oldFont; FCanvas.Brush.Color := clWhite; end; procedure TRtfdODLabel.SetText(const Value: TCaption); begin if Value <> FCaption then begin FCaption := Value; FOwner.Invalidate; end; end; function TRtfdODLabel.GetText: TCaption; begin Result := FCaption; end; constructor TRtfdODLabel.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner); fOwner := AOwner as TCustomControl; Self.Entity := AEntity; FTransparent := False; fFont:= TFont.Create; FBox.Top := Tp; FBox.Left := cDefaultLeft; FBox.Right := cDefaultRight - ClassShadowWidth; FBox.Bottom := fBox.Top + cDefaultlblHeight; FCanvas := fOwner.Canvas; end; destructor TRtfdODLabel.Destroy; begin fFont.Free; inherited; end; procedure TRtfdODLabel.Change(Sender: TModelEntity); begin //stub fOwner.Invalidate; end; procedure TRtfdODLabel.AddChild(Sender: TModelEntity; NewChild: TModelEntity); begin // stub end; procedure TRtfdODLabel.Remove(Sender: TModelEntity); begin // stub end; procedure TRtfdODLabel.EntityChange(Sender: TModelEntity); begin // fOwner.Invalidate; end; function TRtfdODLabel.WidthNeeded: integer; begin SetWantedBounds; Result := FBox.Right; end; function TRtfdODLabel.Height: integer; begin Result := FBox.Bottom - FBox.Top; end; end.
unit KpSmall; interface function DirExists(Dir: String): Boolean; procedure ForceCreateDirectories(Dir: string); function PMsgDlg(Msg, Caption: String; TextType: Word): Integer; function StripBackSlash(const S: String): String; function YieldProcess: Boolean; implementation uses SysUtils, WinTypes, WinProcs, Messages; {This will see if a directory exists without using the FileCtrl unit.} function DirExists(Dir: String): Boolean; var OldDir: String; begin {$I-} GetDir(0, OldDir); ChDir(Dir); Result:= IOResult = 0; ChDir(OldDir); {$I+} end; {This will force the creation of the entire directory string. This is a substitute for the ForceDirectories function in the FileCtrl unit.} procedure ForceCreateDirectories(Dir: string); begin Dir:= StripBackSlash(Dir); if (Length(Dir) < 3) or DirExists(Dir) then EXIT; ForceCreateDirectories(ExtractFilePath(Dir)); {$I-} MkDir(Dir); if IOResult <> 0 then EXIT; {$I+} end; {This will display a message box with the appropiate strings. It serves as a sort of replacement for the MessageDlg function in Dialogs.} function PMsgDlg(Msg, Caption: String; TextType: Word): Integer; var C, M: PChar; begin {See if we should overwrite the caption.} if Caption = '' then Caption:= ExtractFileName(ParamStr(0)); {Allocate the strings.} C:= StrAlloc(Length(Caption) + 1); M:= StrAlloc(Length(Msg) + 1); try StrPCopy(C, Caption); StrPCopy(M, Msg); Result:= MessageBox(0, M, C, TextType or MB_TASKMODAL); finally {Free the strings.} StrDispose(C); StrDispose(M); end; end; {Removes trailing backslash from S, if one exists } function StripBackSlash(const S: String): String; begin Result:= S; if (Result <> '') and (Result[Length(Result)] = '\') then Delete(Result, Length(Result), 1); end; {This is essentially the same as Application.ProcessMessage, except that it does not require either the Forms or Dialogs units.} function YieldProcess: Boolean; var msg: TMsg; begin while PeekMessage(msg, 0, 0, 0, PM_REMOVE) do begin if msg.message = WM_QUIT then begin PostQuitMessage(msg.wParam); Result:= True; EXIT; end else begin TranslateMessage(msg); DispatchMessage(msg) end end; Result:= False; end; end.
unit Objekt.DHLShipmentNotification; interface uses SysUtils, Classes, geschaeftskundenversand_api_2; type TDHLShipmentNotification = class private fShipmentNotificationTypeAPI: ShipmentNotificationType; frecipientEmailAddress: string; procedure setrecipientEmailAddress(const Value: string); public constructor Create; destructor Destroy; override; function ShipmentNotificationTypeAPI: ShipmentNotificationType; property recipientEmailAddress: string read frecipientEmailAddress write setrecipientEmailAddress; procedure Copy(aShipmentNotification: TDHLShipmentNotification); end; implementation { TDHLShipmentNotification } constructor TDHLShipmentNotification.Create; begin fShipmentNotificationTypeAPI := ShipmentNotificationType.Create; end; destructor TDHLShipmentNotification.Destroy; begin //FreeAndNil(fShipmentNotificationTypeAPI); inherited; end; procedure TDHLShipmentNotification.setrecipientEmailAddress(const Value: string); begin frecipientEmailAddress := Value; fShipmentNotificationTypeAPI.recipientEmailAddress := Value; end; function TDHLShipmentNotification.ShipmentNotificationTypeAPI: ShipmentNotificationType; begin Result := fShipmentNotificationTypeAPI; end; procedure TDHLShipmentNotification.Copy(aShipmentNotification: TDHLShipmentNotification); begin setrecipientEmailAddress(aShipmentNotification.recipientEmailAddress); end; end.
unit NewsStoryDBU; interface uses Classes,sysutils,QuickRTTI,QRemote,IBDatabase,IBSQL,guids; type TDBNewsStory =class(TQRemoteObject) private fdb:TIBDatabase; ftran:TIBTransaction; fstory_id,ftitle,fbyline,fstory:STring; fcreated:Tdatetime; public function ProcessCall (Command:String;Parameters:TStrings):TRemoteResponse;override; procedure UpdateStory; procedure CreateStory; procedure GetStory; procedure DeleteStory; property DB:TIBDatabase read fdb write fdb; published property STORY_ID:STring read fstory_id write fstory_id; property CREATED:TDateTime read fcreated write fcreated; property TITLE:String read ftitle write ftitle; property BYLINE:STring read fbyline write fbyline; property STORY:String read fstory write fstory; end; TDBStoryList = class(TQRemoteObject) private fSTories:TStringlist; fdb:TIBDatabase; ftran:TIBTransaction; public constructor create (Service:STring);override; destructor destroy;override; function ProcessCall (Command:String;Parameters:TStrings):TRemoteResponse;override; property DB:TIBDatabase read fdb write fdb; published property Story_IDs:TStringlist read fstories write fstories; end; implementation constructor TDBStoryList.create (Service:STring); begin inherited create(service); fstories:=tstringlist.create; end; destructor TDBStoryList.destroy; begin try fstories.free; finally inherited destroy; end; end; procedure TDBNewsStory.UpdateStory; var sql:string; Q:TIBSQL; begin sql:='UPDATE STORIES SET TITLE=:TITLE, STORY=:STORY WHERE STORY_ID=:STORY_ID'; Q:=TIBSQL.create(nil); Q.Database:=DB; Q.Transaction := ftran; Q.sql.text:=sql; Q.ParambyName('STORY_ID').asstring:= self.story_id ; //Q.ParambyName('CREATED').value:= self.created ; Q.ParambyName('TITLE').asstring:= self.title ; //Q.ParambyName('BYLINE').asstring:= self.byline ; Q.ParambyName('STORY').asstring:= self.story ; Q.ExecQuery; Q.Close; Q.free; end; procedure TDBNewsStory.CreateStory; var sql:STring; Q:TIBSQL; begin {STORY_ID,CREATED,TITLE,BYLINE,STORY} sql:='INSERT INTO STORIES (STORY_ID,CREATED,TITLE,BYLINE,STORY) VALUES (:STORY_ID,:CREATED,:TITLE,:BYLINE,:STORY)'; Q:=TIBSQL.create(nil); Q.Database:=DB; Q.Transaction := ftran; Q.sql.text:=sql; Q.ParambyName('STORY_ID').asstring:= Guids.CreateObjectID ; Q.ParambyName('CREATED').value:= now ; Q.ParambyName('TITLE').asstring:= self.title ; Q.ParambyName('BYLINE').asstring:= self.byline ; Q.ParambyName('STORY').asstring:= self.story ; Q.ExecQuery; Q.Close; Q.free; end; procedure TDBNewsStory.GetStory; var sql:STring; Q:TIBSQL; begin {STORY_ID,CREATED,TITLE,BYLINE,STORY} sql:='SELECT * FROM STORIES WHERE STORY_ID=:STORY_ID'; Q:=TIBSQL.create(nil); Q.Database:=DB; Q.Transaction := ftran; Q.sql.text:=sql; Q.ParambyName('STORY_ID').asstring:= self.story_id ; Q.ExecQuery; self.created := Q.FieldbyName('CREATED').value ; self.title := Q.FieldbyName('TITLE').asstring ; self.byline := Q.FieldbyName('BYLINE').asstring ; self.story := Q.FieldbyName('STORY').asstring; Q.Close; Q.free; end; procedure TDBNewsStory.DeleteStory; var sql:STring;Q:TIBSQL; begin {STORY_ID,CREATED,TITLE,BYLINE,STORY} sql:='DELETE FROM STORIES WHERE STORY_ID=:STORY_ID'; Q:=TIBSQL.create(nil); Q.Database:=DB; Q.Transaction := ftran; Q.sql.text:=sql; Q.ParambyName('STORY_ID').asstring:= self.story_id ; Q.ExecQuery; Q.Close; Q.free; end; function TDBStoryList.ProcessCall (Command:String;Parameters:TStrings):TRemoteResponse; var sql:STring;Q:TIBSQL; begin result:=TRemoteResponse.create; result.RTTIObject := self; result.Service := self.service; result.ErrorNumber := 0; fTran:=TIBTransaction.create(nil); ftran.defaultdatabase:= fdb; try ftran.StartTransaction ; if UPPERCASE(Command)='GET' then begin sql:='SELECT STORY_ID,TITLE,CREATED FROM STORIES ORDER BY CREATED DESC'; Q:=TIBSQL.create(nil); Q.Database:=DB; Q.Transaction := ftran; Q.sql.text:=sql; Q.ExecQuery; while not( Q.eof) do begin fstories.add (Q.FieldbyName('STORY_ID').asstring+'=('+Q.FieldbyName('CREATED').asstring+') '+Q.FieldbyName('TITLE').asstring); Q.next; end ; Q.Close; Q.free; end; ftran.commit; except on E:Exception do begin ftran.rollback; raise(e); end; end; end; function TDBNewsStory.ProcessCall (Command:String;Parameters:TStrings):TRemoteResponse; var Tran:TIBTransaction; begin result:=TRemoteResponse.create; result.RTTIObject := self; result.Service := self.service; result.ErrorNumber := 0; fTran:=TIBTransaction.create(nil); ftran.defaultdatabase:= fdb; ftran.StartTransaction ; try if UPPERCASE(command)='INSERT' then begin CreateStory; end; if UPPERCASE(command)='UPDATE' then begin UpdateStory; end; if UPPERCASE(command)='GET' then begin GetStory; end; if UPPERCASE(command)='DELETE' then begin DeleteStory; end; ftran.commit; except on E:Exception do begin ftran.rollback; raise(e); end; end; end; end.
unit RegisterHelper; interface function IsVCRTL140Installed:LongBool; implementation uses Registry,Windows,SysUtils; type TIsWow64Process = function(hProcess:THandle;var Wow64Process:LongBool):LongBool;stdcall; function Is32BitProcessUnderWOW64:LongBool; var IsWow64Process:TIsWow64Process; hmod:THandle; begin Result:=False; hmod:= LoadLibraryW('kernel32.dll'); if hmod = 0 then RaiseLastOSError; IsWow64Process:=nil; IsWow64Process:=GetProcAddress(hmod, 'IsWow64Process'); if Assigned(IsWow64Process) then begin IsWow64Process(GetCurrentProcess,Result); end; end; function IsVCRTL140Installed:LongBool; var reg:TRegistry; begin reg := TRegistry.Create(KEY_READ); try reg.RootKey := HKEY_LOCAL_MACHINE; if Is32BitProcessUnderWOW64 then Result:=reg.KeyExists('SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\x86') else Result:=reg.KeyExists('SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x86'); finally reg.Free; end; end; end.
unit DataSnapServerConnectionObj; interface uses System.Classes; type TDataSnapConnectionDetails = class strict private FPort: Integer; FServer: string; FURLPath: string; FPassword: string; FUserName: string; procedure SetPort(const Value: Integer); procedure SetServer(const Value: string); function GetPortStr: string; public constructor Create; published property Port : Integer read FPort write SetPort; property PortStr : string read GetPortStr; property Server : string read FServer write SetServer; property URLPath : string read FURLPath write FURLPath; property UserName : string read FUserName write FUserName; property Password : string read FPassword write FPassword; end; TDataSnapConnectionDetailsServices = class class procedure Save(Instance : TDataSnapConnectionDetails; FileName : string); class procedure Load(Instance : TDataSnapConnectionDetails; FileName : string); class procedure SetParams(const Params : TStrings; const ConnectionDetails : TDataSnapConnectionDetails); end; implementation { TDataSnapConnectionDetails } uses System.SysUtils, INIFiles; constructor TDataSnapConnectionDetails.Create; begin FPort := 8080; FServer := '127.0.0.1'; FURLPath := ''; end; function TDataSnapConnectionDetails.GetPortStr: string; begin if Server.Contains(':') or (Port = 0) then Result := '' else Result := Port.ToString; end; procedure TDataSnapConnectionDetails.SetPort(const Value: Integer); begin Assert(Value >= 0); FPort := Value; end; procedure TDataSnapConnectionDetails.SetServer(const Value: string); begin Assert(Trim(Value) > ''); FServer := Value; end; { TDataSnapConnectionDetailsServices } class procedure TDataSnapConnectionDetailsServices.Load( Instance: TDataSnapConnectionDetails; FileName: string); var Ini: TIniFile; begin Assert(Instance <> nil); if not FileExists(FileName) then Exit; Ini := TIniFile.Create(FileName); try Instance.Server := Ini.ReadString('SERVER','HOST',Instance.Server); Instance.Port := Ini.ReadInteger('SERVER','PORT',Instance.Port); Instance.URLPath := Ini.ReadString('SERVER','URLPath',Instance.URLPath); Instance.UserName := Ini.ReadString('SERVER','UserName',Instance.UserName); finally Ini.Free; end; end; class procedure TDataSnapConnectionDetailsServices.Save( Instance: TDataSnapConnectionDetails; FileName: string); var Ini: TIniFile; begin Assert(Instance <> nil); try Ini := TIniFile.Create(FileName); try Ini.WriteString('SERVER','HOST',Instance.Server); Ini.WriteInteger('SERVER','PORT',Instance.Port); Ini.WriteString('SERVER','URLPath',Instance.URLPath); Ini.WriteString('SERVER','UserName',Instance.UserName); finally Ini.Free; end; except end; end; class procedure TDataSnapConnectionDetailsServices.SetParams(const Params: TStrings; const ConnectionDetails : TDataSnapConnectionDetails); begin Params.Values['PORT'] := ConnectionDetails.PortStr; Params.Values['HOSTNAME'] := ConnectionDetails.Server; Params.Values['URLPath'] := ConnectionDetails.URLPath; Params.Values['DSAuthenticationUser'] := ConnectionDetails.UserName; Params.Values['DSAuthenticationPassword'] := ConnectionDetails.Password; end; end.
unit ZcxLocateBar; interface uses SysUtils, Classes, Forms, dxBar, pFIBDataSet,DB, Unit_ZGlobal_Consts, ZProc, Menus, Z_Images_DM, dxBarExtItems, Dates, ZMessages, Dialogs; type EzcxBarLocate = class(Exception); type TZItemLocate = record NameField:string; Caption:string; LocateOptions:TLocateOptions; end; type TZLocateItems = class private PCount:integer; PItems:array of TZItemLocate; protected function GetItem(Index:integer):TZItemLocate; public constructor Create; property Count:integer read PCount; function Add(ItemLocate:TZItemLocate):TZItemLocate; function ItemByIndex(Index:Integer):TZItemLocate; property ItemLocate[Index:Integer]:TZItemLocate read GetItem; end; type TZBarLocate = class private Bar:TdxBar; PLocateItems:TZLocateItems; PBarManager:TdxBarManager; PDataSet:TpFiBDataSet; PLocateBtn:TdxBarButton; PLocateNextBtn:TdxBarButton; PTextEditLocate:TdxBarEdit; PComboFieldsLocate:TdxBarCombo; PDigitalField:string; PDigitalFieldIndex:integer; PNonDigitalFieldIndex:integer; PDMImage:TDMImages; PNewComboIndex:Integer; PLanguageIndex:Byte; PCurrentLocateItem:TZItemLocate; PCurrentLocateItemIndex:integer; PTextEditCurText:string; protected procedure OnLocateBtnClick(Sender : TObject); procedure OnLocateNextBtnClick(Sender : TObject); procedure OnTextEditLocateKeyUp(Sender: TObject; var Key: Word;Shift: TShiftState); procedure OnTextEditKeyPress(Sender: TObject; var Key: Char); procedure OnComboChange(Sender: TObject); procedure OnTextEditExit(Sender: TObject); procedure OnTextEditCurChange(Sender: TObject); procedure SetDataSet(ADataSet:TpFIBDataSet); procedure SetDigitalField(NameField:string); procedure SetComboVisible(AVisible:boolean); function GetComboVisible:boolean; function GetDockControl:TdxBarDockControl; procedure SetDockControl(ADockControl:TdxBarDockControl); procedure SetBorderStyle(BorderStyle:TdxBarBorderStyle); function GetBorderStyle:TdxBarBorderStyle; public constructor Create(ABarManager:TdxBarManager;ABar:TdxBar=nil); property LocateItems:TZLocateItems read PLocateItems write PLocateItems; property BarManager:TdxBarManager read PBarManager; property DataSet:TpFIBDataSet read PDataSet write SetDataSet; property LocateBtn:TdxBarButton read PLocateBtn write PLocateBtn; property LocateNextBtn:TdxBarButton read PLocateNextBtn write PLocateNextBtn; property DigitalField:String read PDigitalField write SetDigitalField; property FieldSelectVisible:boolean read GetComboVisible write SetComboVisible; property BorderStyle:TdxBarBorderStyle read GetBorderStyle write SetBorderStyle; property DockControl:TdxBarDockControl read GetDockControl write SetDockControl; procedure AddLocateItem(LocateItem:TZItemLocate);overload; procedure AddLocateItem(NameField:string;Caption:string;LocateOptions:TLocateOptions);overload; procedure Default; end; implementation function TZLocateItems.GetItem(Index:Integer):TZItemLocate; begin Result:=PItems[Index]; end; procedure TZBarLocate.SetBorderStyle(BorderStyle:TdxBarBorderStyle); begin Bar.BorderStyle := BorderStyle; end; function TZBarLocate.GetBorderStyle:TdxBarBorderStyle; begin result:=Bar.BorderStyle; end; function TZBarLocate.GetDockControl:TdxBarDockControl; begin Result:=Bar.DockControl; end; procedure TZBarLocate.SetDockControl(ADockControl:TdxBarDockControl); begin Bar.NotDocking := []; Bar.DockedDockControl:=ADockControl; Bar.DockControl:= ADockControl; Bar.NotDocking := [dsNone,dsLeft,dsTop,dsRight,dsBottom]; end; constructor TZBarLocate.Create(ABarManager:TdxBarManager;ABar:TdxBar=nil); begin inherited Create; PLanguageIndex:=LanguageIndex; PLocateItems:=TZLocateItems.Create; PBarManager := ABarManager; if PBarManager.Images=nil then begin PDMImage:=TDMImages.Create(ABarManager.Owner as TForm); PBarManager.Images := PDMImage.Images; end; if ABar=nil then Bar := PBarManager.Bars.Add else Bar:=ABar; with Bar do begin Name := 'zBarLocate'; caption := 'Пошук'; DockingStyle := dsBottom; // BorderStyle := bbsNone; AllowClose := False; AllowCustomizing := False; AllowQuickCustomizing := False; AllowReset := False; NotDocking := [dsNone,dsLeft,dsTop,dsRight,dsBottom]; MultiLine := True; UseRestSpace := True; Visible := True; end; PTextEditLocate := TdxBarEdit.Create(PBarManager); PComboFieldsLocate := TdxBarCombo.Create(PBarManager); PLocateBtn := TdxBarButton.Create(PBarManager); PLocateNextBtn := TdxBarButton.Create(PBarManager); with PTextEditLocate do begin Name := 'TextEditLocate'; OnKeyUp := OnTextEditLocateKeyUp; OnExit := OnTextEditExit; OnCurChange := OnTextEditCurChange; Caption := Name; Hint := Caption; Visible := ivAlways; ShowCaption := False; end; with PComboFieldsLocate do begin Name := 'ComboFieldsLocate'; OnChange:= OnComboChange; Caption := Name; Hint := Caption; Visible := ivAlways; end; with PLocateBtn do begin Name := 'LocateBtn'; OnClick := OnLocateBtnClick; Caption := Name; Hint := Caption; ButtonStyle := bsDefault; PaintStyle := psCaptionGlyph; UnclickAfterDoing := True; Visible := ivAlways; ShortCut:=118; //F7 ImageIndex := PDMImage.ImageIndexByName(zbiLocate); end; with PLocateNextBtn do begin Name := 'LocateNextBtn'; OnClick := OnLocateNextBtnClick; Caption := Name; Hint := Caption; ButtonStyle := bsDefault; PaintStyle := psCaptionGlyph; UnclickAfterDoing := True; Visible := ivAlways; ShortCut := 16502; //Ctrl+F7 ImageIndex := PDMImage.ImageIndexByName(zbiLocateNext); end; with Bar, ItemLinks do begin LockUpdate := True; with Add do begin Item := PComboFieldsLocate; Index := AvailableItemCount - 1; BringToTopInRecentList(False); end; with Add do begin Item := PTextEditLocate; Index := AvailableItemCount - 1; BeginGroup := True; BringToTopInRecentList(False); end; with Add do begin Item := PLocateBtn; Index := AvailableItemCount - 1; BeginGroup := True; BringToTopInRecentList(False); end; with Add do begin Item := PLocateNextBtn; Index := AvailableItemCount - 1; BeginGroup := True; BringToTopInRecentList(False); end; LockUpdate := False; end; Default; end; procedure TZBarLocate.SetComboVisible(AVisible:boolean); begin if (not AVisible) and (PLocateItems.Count>1) then begin EzcxBarLocate.Create('This option for Locate Items Count =1'); exit; end; if AVisible then PComboFieldsLocate.Visible:=ivAlways else PComboFieldsLocate.Visible:=ivNever; end; function TZBarLocate.GetComboVisible:boolean; begin result:=(PComboFieldsLocate.Visible=ivAlways); end; procedure TZBarLocate.OnTextEditExit(Sender: TObject); begin PTextEditLocate.Text:=PTextEditCurText; OnLocateBtnClick(Sender); end; procedure TZBarLocate.OnComboChange(Sender: TObject); begin PCurrentLocateItem:=PLocateItems.ItemLocate[PComboFieldsLocate.ItemIndex]; end; procedure TZBarLocate.OnTextEditKeyPress(Sender: TObject; var Key: Char); begin PNewComboIndex:=-1; if (PLocateItems.Count<>2) or (key=#8) or (Key=#0) then exit; If (Key in ['0'..'9']) then begin if (PDigitalFieldIndex <> PCurrentLocateItemIndex)then begin PNewComboIndex:=PDigitalFieldIndex; PTextEditLocate.CurText:=''; end; end else if (PNonDigitalFieldIndex <> PCurrentLocateItemIndex)then begin PNewComboIndex:=PNonDigitalFieldIndex; PTextEditLocate.CurText:=''; end; end; procedure TZBarLocate.SetDigitalField(NameField:string); var i:integer; begin if PLocateItems.Count<>2 then EzcxBarLocate.Create('Operation defined only for count of locate items equals 2'); PDigitalField:=NameField; if NameField<>'' then begin for I:=0 to PLocateItems.Count-1 do if PLocateItems.ItemByIndex(i).NameField=NameField then PDigitalFieldIndex:=i else PNonDigitalFieldIndex:=i; PTextEditLocate.OnKeyPress := OnTextEditKeyPress; PComboFieldsLocate.Visible := ivNever; end else begin PDigitalFieldIndex:=-1; PNonDigitalFieldIndex:=-1; PTextEditLocate.OnKeyPress := nil; PComboFieldsLocate.Visible := ivAlways; Bar.ItemLinks.Items[1].BeginGroup:=True; end; end; procedure TZBarLocate.Default; begin PLocateBtn.Caption := LocateBtn_Caption[PLanguageIndex]; PLocateBtn.Hint := PLocateBtn.Caption; PLocateNextBtn.Caption := LocateNextBtn_Caption[PLanguageIndex]; PLocateNextBtn.Hint := PLocateNextBtn.Caption; PTextEditLocate.Hint := BarEditLocate_Hint[PLanguageIndex]; PTextEditLocate.Caption := BarEditLocate_Caption[PLanguageIndex]; PComboFieldsLocate.Hint := ComboNameFields_Hint[PLanguageIndex]; end; function TZLocateItems.ItemByIndex(Index:Integer):TZItemLocate; begin Result:=PItems[Index]; end; procedure TZBarLocate.AddLocateItem(LocateItem:TZItemLocate); begin if PDigitalField<>'' then begin EzcxBarLocate.Create('DigitalField was Defined!'); Exit; end; if not GetComboVisible then begin EzcxBarLocate.Create('FieldsSelect isn''t visible!'); Exit; end; PComboFieldsLocate.Items.Add(PLocateItems.Add(LocateItem).Caption); PComboFieldsLocate.ItemIndex:=0; PCurrentLocateItem:=PLocateItems.ItemLocate[0]; PCurrentLocateItemIndex:=0; end; procedure TZBarLocate.AddLocateItem(NameField:string;Caption:string;LocateOptions:TLocateOptions); var LocateItem:TZItemLocate; begin if PDigitalField<>'' then begin EzcxBarLocate.Create('DigitalField was Defined!'); Exit; end; if not GetComboVisible then begin EzcxBarLocate.Create('FieldsSelect isn''t visible!'); Exit; end; LocateItem.NameField:=NameField; LocateItem.Caption := Caption; LocateItem.LocateOptions := LocateOptions; PComboFieldsLocate.Items.Add(PLocateItems.Add(LocateItem).Caption); PComboFieldsLocate.ItemIndex:=0; PCurrentLocateItem:=PLocateItems.ItemLocate[0]; PCurrentLocateItemIndex:=0; end; procedure TZBarLocate.OnTextEditLocateKeyUp(Sender: TObject; var Key: Word;Shift: TShiftState); begin if PNewComboIndex>=0 then begin if PTextEditLocate.ShowCaption then begin PTextEditLocate.Caption := PLocateItems.ItemLocate[PNewComboIndex].Caption; PTextEditLocate.SetFocus; end; PCurrentLocateItem := PLocateItems.ItemLocate[PNewComboIndex]; PCurrentLocateItemIndex := PNewComboIndex; PNewComboIndex := -1; end; end; procedure TZBarLocate.OnLocateBtnClick(Sender : TObject); begin if (PDataSet=nil) or (not PDataSet.Active) or (PTextEditLocate.Text='') then exit; PDataSet.Locate(PCurrentLocateItem.NameField, PTextEditLocate.Text,PCurrentLocateItem.LocateOptions); end; procedure TZBarLocate.OnLocateNextBtnClick(Sender : TObject); begin if (PDataSet=nil) or (not PDataSet.Active) or (PTextEditLocate.Text='') then exit; PDataSet.LocateNext(PCurrentLocateItem.NameField, PTextEditLocate.Text,PCurrentLocateItem.LocateOptions); end; procedure TZBarLocate.SetDataSet(ADataSet:TpFIBDataSet); begin PDataSet:=ADataSet; end; function TZLocateItems.Add(ItemLocate:TZItemLocate):TZItemLocate; begin inc(PCount); SetLength(PItems,PCount); PItems[PCount-1]:=ItemLocate; if ItemLocate.LocateOptions=[] then PItems[PCount-1].LocateOptions:=[loCaseInsensitive]; result:=PItems[PCount-1]; end; constructor TZLocateItems.Create; begin inherited Create; PCount:=0; end; procedure TZBarLocate.OnTextEditCurChange(Sender: TObject); begin PTextEditCurText:=PTextEditLocate.CurText; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083124 //////////////////////////////////////////////////////////////////////////////// unit android.view.textclassifier.TextLinks; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os, android.text.Spannable, java.util.function.Function; type JTextLinks = interface; JTextLinksClass = interface(JObjectClass) ['{E3CC60BF-4949-4B14-A35F-90FD6CC5B142}'] function _GetAPPLY_STRATEGY_IGNORE : Integer; cdecl; // A: $19 function _GetAPPLY_STRATEGY_REPLACE : Integer; cdecl; // A: $19 function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function _GetSTATUS_DIFFERENT_TEXT : Integer; cdecl; // A: $19 function _GetSTATUS_LINKS_APPLIED : Integer; cdecl; // A: $19 function _GetSTATUS_NO_LINKS_APPLIED : Integer; cdecl; // A: $19 function _GetSTATUS_NO_LINKS_FOUND : Integer; cdecl; // A: $19 function apply(text : JSpannable; applyStrategy : Integer; spanFactory : JFunction) : Integer; cdecl;// (Landroid/text/Spannable;ILjava/util/function/Function;)I A: $1 function describeContents : Integer; cdecl; // ()I A: $1 function getLinks : JCollection; cdecl; // ()Ljava/util/Collection; A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property APPLY_STRATEGY_IGNORE : Integer read _GetAPPLY_STRATEGY_IGNORE; // I A: $19 property APPLY_STRATEGY_REPLACE : Integer read _GetAPPLY_STRATEGY_REPLACE; // I A: $19 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 property STATUS_DIFFERENT_TEXT : Integer read _GetSTATUS_DIFFERENT_TEXT; // I A: $19 property STATUS_LINKS_APPLIED : Integer read _GetSTATUS_LINKS_APPLIED; // I A: $19 property STATUS_NO_LINKS_APPLIED : Integer read _GetSTATUS_NO_LINKS_APPLIED;// I A: $19 property STATUS_NO_LINKS_FOUND : Integer read _GetSTATUS_NO_LINKS_FOUND; // I A: $19 end; [JavaSignature('android/view/textclassifier/TextLinks$Builder')] JTextLinks = interface(JObject) ['{8DBB7C91-7A58-4170-9B72-F70678ED1291}'] function apply(text : JSpannable; applyStrategy : Integer; spanFactory : JFunction) : Integer; cdecl;// (Landroid/text/Spannable;ILjava/util/function/Function;)I A: $1 function describeContents : Integer; cdecl; // ()I A: $1 function getLinks : JCollection; cdecl; // ()Ljava/util/Collection; A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJTextLinks = class(TJavaGenericImport<JTextLinksClass, JTextLinks>) end; const TJTextLinksAPPLY_STRATEGY_IGNORE = 0; TJTextLinksAPPLY_STRATEGY_REPLACE = 1; TJTextLinksSTATUS_DIFFERENT_TEXT = 3; TJTextLinksSTATUS_LINKS_APPLIED = 0; TJTextLinksSTATUS_NO_LINKS_APPLIED = 2; TJTextLinksSTATUS_NO_LINKS_FOUND = 1; implementation end.
unit pkcs11_session; interface uses pkcs11t, pkcs11_api, pkcs11_object, pkcs11_attribute, pkcs11_mechanism, //sdu sdugeneral; type TPKCS11UserType = (utUser, utSecurityOfficer, utContextSpecific); const PKCS11_USER_TYPE: array [TPKCS11UserType] of CK_USER_TYPE = ( CKU_USER, CKU_SO, CKU_CONTEXT_SPECIFIC ); type TPKCS11SessionState = ( ssROPublic, ssROUserFunctions, ssRWPublic, ssRWUserFunctions, ssRWSOFunctions ); const PKCS11_SESSION_STATE: array [TPKCS11SessionState] of CK_STATE = ( CKS_RO_PUBLIC_SESSION, CKS_RO_USER_FUNCTIONS, CKS_RW_PUBLIC_SESSION, CKS_RW_USER_FUNCTIONS, CKS_RW_SO_FUNCTIONS ); resourcestring SESSION_STATE_RO_PUBLIC = 'Read-only Public'; SESSION_STATE_RO_USER = 'Read-only User'; SESSION_STATE_RW_PUBLIC = 'Read/write Public'; SESSION_STATE_RW_USER = 'Read/write User'; SESSION_STATE_RW_SO = 'Read/write Security Officer'; const PKCS11_SESSION_STATE_DESC: array [TPKCS11SessionState] of String = ( SESSION_STATE_RO_PUBLIC, SESSION_STATE_RO_USER, SESSION_STATE_RW_PUBLIC, SESSION_STATE_RW_USER, SESSION_STATE_RW_SO ); type TPKCS11Session = class (TPKCS11API) private protected FSlotID: Integer; FLastEncryptDecryptLen: Integer; // Returns TRUE/FALSE, depending on whether the session is open/valid or // not function GetOpen(): Boolean; function GetState(): TPKCS11SessionState; function GetStateStr(): String; function GetFlags(): CK_ULONG; function GetDeviceError(): CK_ULONG; function GetReadOnly(): Boolean; function Login(userType: TPKCS11UserType; usePINPad: Boolean; PIN: Ansistring): Boolean; overload; function GetLoggedIn(): Boolean; function InitPIN(usePINPad: Boolean; PIN: Ansistring): Boolean; overload; function SetPIN(usePINPad: Boolean; oldPIN: Ansistring; newPIN: Ansistring): Boolean; overload; // Conversion functions... function CK_USER_TYPEToUserType(ckUserType: CK_USER_TYPE): TPKCS11UserType; function UserTypeToCK_USER_TYPE(userType: TPKCS11UserType): CK_USER_TYPE; function CK_STATEToState(ckState: CK_STATE): TPKCS11SessionState; function StateToCK_STATE(state: TPKCS11SessionState): CK_STATE; public FhSession: CK_SESSION_HANDLE; property Open: Boolean Read GetOpen; // Some PKCS#11 providers return incorrect slot ID in the info // This method returns the *real* slot ID... property SlotID: Integer Read FSlotID Write FSlotID; // ...and this method returns the slot ID from the session's info from the // PKCS#11 API function SlotIDFromInfo(): Integer; property State: TPKCS11SessionState Read GetState; property StateStr: String Read GetStateStr; property Flags: CK_FLAGS Read GetFlags; property DeviceError: CK_ULONG Read GetDeviceError; function GetSessionInfo(var info: CK_SESSION_INFO): Boolean; property ReadOnly: Boolean Read GetReadOnly; function SeedRandom(byteCount: Integer; seedData: Ansistring): Boolean; function GenerateRandom(byteCount: Integer; var randomData: TSDUBytes): Boolean; // function GenerateRandom(byteCount: integer; var randomData: AnsiString): boolean; function GetOperationState(var operationState: Ansistring): Boolean; function SetOperationState(operationState: Ansistring; encryptionKeyObj: TPKCS11Object; authenticationKey: TPKCS11Object): Boolean; function Login(userType: TPKCS11UserType): Boolean; overload; function Login(userType: TPKCS11UserType; PIN: Ansistring): Boolean; overload; procedure Logout(); property LoggedIn: Boolean Read GetLoggedIn; function InitPIN(): Boolean; overload; function InitPIN(PIN: Ansistring): Boolean; overload; function SetPIN(): Boolean; overload; function SetPIN(oldPIN: Ansistring; newPIN: Ansistring): Boolean; overload; function FindObjectsInit(): Boolean; function FindNextObject(): TPKCS11Object; function FindObjectsFinal(): Boolean; function GenerateKey(mechanism: CK_MECHANISM_TYPE; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; overload; function GenerateKey(mechanism: TPKCS11Mechanism; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; overload; function GenerateKeyPair( mechanism: CK_MECHANISM_TYPE; publicAttrTemplate: TPKCS11AttributeTemplate; privateAttrTemplate: TPKCS11AttributeTemplate; var publicKey: TPKCS11Object; var privateKey: TPKCS11Object ): Boolean; overload; function GenerateKeyPair( mechanism: TPKCS11Mechanism; publicAttrTemplate: TPKCS11AttributeTemplate; privateAttrTemplate: TPKCS11AttributeTemplate; var publicKey: TPKCS11Object; var privateKey: TPKCS11Object ): Boolean; overload; function CreateObject(attrObjs: array of TPKCS11Attribute): TPKCS11Object; overload; function CreateObject(attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; overload; function CopyObject(obj: TPKCS11Object): TPKCS11Object; function DestroyObject(obj: TPKCS11Object): Boolean; function GetObject(application: String; objLabel: String): TPKCS11Object; function GetObjects(objClass: CK_OBJECT_CLASS): TPKCS11ObjectArray; overload; function GetObjects(application: String): TPKCS11ObjectArray; overload; function GetObjects(application: String; objLabel: String): TPKCS11ObjectArray; overload; function EncryptInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; overload; function EncryptInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; overload; function Encrypt(plaintext: Ansistring; var cyphertext: Ansistring): Boolean; function EncryptUpdate(plaintext: Ansistring; var cyphertext: Ansistring): Boolean; function EncryptFinal(var cyphertext: Ansistring): Boolean; function DecryptInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; overload; function DecryptInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; overload; function Decrypt(cyphertext: Ansistring; var plaintext: Ansistring): Boolean; function DecryptUpdate(cyphertext: Ansistring; var plaintext: Ansistring): Boolean; function DecryptFinal(var plaintext: Ansistring): Boolean; function DigestInit(mechanism: CK_MECHANISM_TYPE): Boolean; overload; function DigestInit(mechanism: TPKCS11Mechanism): Boolean; overload; function Digest(data: Ansistring; var digest: Ansistring): Boolean; function DigestUpdate(data: Ansistring): Boolean; function DigestKey(data: Ansistring; keyObj: TPKCS11Object): Boolean; function DigestFinal(var digest: Ansistring): Boolean; function SignInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; overload; function SignInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; overload; function Sign(data: Ansistring; var signature: Ansistring): Boolean; function SignUpdate(data: Ansistring): Boolean; function SignFinal(var signature: Ansistring): Boolean; function SignRecoverInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; overload; function SignRecoverInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; overload; function SignRecover(data: Ansistring; var signature: Ansistring): Boolean; function VerifyInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; overload; function VerifyInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; overload; function Verify(data: Ansistring; signature: Ansistring): Boolean; function VerifyUpdate(data: Ansistring): Boolean; function VerifyFinal(signature: Ansistring): Boolean; function VerifyRecoverInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; overload; function VerifyRecoverInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; overload; function VerifyRecover(data: Ansistring; var signature: Ansistring): Boolean; function DigestEncryptUpdate(part: Ansistring; var encryptedPart: Ansistring): Boolean; function DecryptDigestUpdate(pEncryptedPart: Ansistring; var Part: Ansistring): Boolean; function SignEncryptUpdate(part: Ansistring; var encryptedPart: Ansistring): Boolean; function DecryptVerifyUpdate(pEncryptedPart: Ansistring; var Part: Ansistring): Boolean; function WrapKey(mechanism: CK_MECHANISM_TYPE; wrappingKeyObj: TPKCS11Object; keyObj: TPKCS11Object; var wrappedKey: Ansistring): Boolean; function UnwrapKey(mechanism: CK_MECHANISM_TYPE; unwrappingKeyObj: TPKCS11Object; wrappedKey: Ansistring; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; function DeriveKey(mechanism: CK_MECHANISM_TYPE; baseKey: TPKCS11Object; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; function GetFunctionStatus(): Boolean; function CancelFunction(): Boolean; procedure CloseSession(); end; implementation uses Math, Shredder, SysUtils; const PKCS11_IGNORE_PARAMETER = '!!IGNORE_THIS_PARAMETER!!'; // Buffer lengths // These should be set to suitably high values to ensure the buffers used are // always sifficiently large enough // All values in *bytes* BUFFER_LEN_DIGEST = 8192; BUFFER_LEN_SIGN = 8192; BUFFER_LEN_WRAPPED_KEY = 8192; BUFFER_LEN_MIN_ENCRYPT_DECRYPT = 8192; BUFFER_LEN_OP_STATE = 8192; function TPKCS11Session.GetSessionInfo(var info: CK_SESSION_INFO): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GetSessionInfo, FN_NAME_C_GetSessionInfo); LastRV := LibraryFunctionList.CK_C_GetSessionInfo(FhSession, @info); Result := RVSuccess(LastRV); end; function TPKCS11Session.SeedRandom(byteCount: Integer; seedData: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SeedRandom, FN_NAME_C_SeedRandom); LastRV := LibraryFunctionList.CK_C_SeedRandom( FhSession, CK_BYTE_PTR(PByte(seedData)), byteCount ); Result := RVSuccess(LastRV); end; function TPKCS11Session.GenerateRandom(byteCount: Integer; var randomData: TSDUBytes): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GenerateRandom, FN_NAME_C_GenerateRandom); // Setup the returned string so it's large enough to store the random data SDUInitAndZeroBuffer(byteCount, randomData); // randomData := StringOfChar(AnsiChar('X'), byteCount); LastRV := LibraryFunctionList.CK_C_GenerateRandom( FhSession, CK_BYTE_PTR(PByte(randomData)), byteCount ); Result := RVSuccess(LastRV); end; { function TPKCS11Session.GenerateRandom(byteCount: integer; var randomData: AnsiString): boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GenerateRandom, FN_NAME_C_GenerateRandom); // Setup the returned string so it's large enough to store the random data // SDUInitAndZeroBuffer(byteCount, randomData ); randomData := StringOfChar(AnsiChar('X'), byteCount); LastRV := LibraryFunctionList.CK_C_GenerateRandom( FhSession, CK_BYTE_PTR(PByte(randomData)), byteCount ); Result := RVSuccess(LastRV); end; } function TPKCS11Session.GetOperationState(var operationState: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpData: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GetOperationState, FN_NAME_C_DecryptVerifyUpdate); tmpData := StringOfChar(AnsiChar(#0), BUFFER_LEN_OP_STATE); tmpLen := length(tmpData); LastRV := LibraryFunctionList.CK_C_GetOperationState( FhSession, CK_BYTE_PTR(PansiChar(tmpData)), @tmpLen ); operationState := Copy(tmpData, 1, tmpLen); Overwrite(tmpData); Result := RVSuccess(LastRV); end; function TPKCS11Session.SetOperationState(operationState: Ansistring; encryptionKeyObj: TPKCS11Object; authenticationKey: TPKCS11Object): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SetOperationState, FN_NAME_C_SetOperationState); LastRV := LibraryFunctionList.CK_C_SetOperationState( FhSession, CK_BYTE_PTR(PansiChar(operationState)), length( operationState), encryptionKeyObj.FHandle, authenticationKey.FHandle ); Result := RVSuccess(LastRV); end; // Log user in using PIN pad function TPKCS11Session.Login(userType: TPKCS11UserType): Boolean; begin Result := Login(userType, True, ''); end; // Log user in using specified PIN function TPKCS11Session.Login(userType: TPKCS11UserType; PIN: Ansistring): Boolean; begin Result := Login(userType, False, PIN); end; function TPKCS11Session.Login(userType: TPKCS11UserType; usePINPad: Boolean; PIN: Ansistring): Boolean; var pkcs11UserType: CK_USER_TYPE; begin CheckFnAvailable(@LibraryFunctionList.CK_C_Login, FN_NAME_C_Login); pkcs11UserType := UserTypeToCK_USER_TYPE(userType); if usePINPad then begin LastRV := LibraryFunctionList.CK_C_Login(FhSession, pkcs11UserType, NULL_PTR, 0); end else begin LastRV := LibraryFunctionList.CK_C_Login( FhSession, pkcs11UserType, CK_UTF8CHAR_PTR(PansiChar(PIN)), length( PIN)); end; Result := RVSuccess(LastRV); end; procedure TPKCS11Session.Logout(); begin CheckFnAvailable(@LibraryFunctionList.CK_C_Logout, FN_NAME_C_Logout); LastRV := LibraryFunctionList.CK_C_Logout(FhSession); end; function TPKCS11Session.FindObjectsInit(): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_FindObjectsInit, FN_NAME_C_FindObjectsInit); LastRV := LibraryFunctionList.CK_C_FindObjectsInit(FhSession, NULL_PTR, 0); Result := RVSuccess(LastRV); end; function TPKCS11Session.GetLoggedIn(): Boolean; var currState: TPKCS11SessionState; begin currState := State; Result := (Open and (currState <> ssROPublic) and (currState <> ssRWPublic)); end; function TPKCS11Session.GetReadOnly(): Boolean; var currState: TPKCS11SessionState; begin currState := State; Result := (not (Open) or (currState = ssROPublic) or (currState = ssROUserFunctions)); end; // Important: It is the CALLERS responsibility to free off the object returned // Returns nil if no more/error function TPKCS11Session.FindNextObject(): TPKCS11Object; var hObject: CK_OBJECT_HANDLE; ulObjectCount: CK_ULONG; begin CheckFnAvailable(@LibraryFunctionList.CK_C_FindObjects, FN_NAME_C_FindObjects); Result := nil; LastRV := LibraryFunctionList.CK_C_FindObjects( FhSession, @hObject, 1, @ulObjectCount ); if (RVSuccess(LastRV) and (ulObjectCount <> 0)) then begin Result := TPKCS11Object.Create(); Result.LibraryFunctionList := LibraryFunctionList; Result.FSessionHandle := FhSession; Result.FHandle := hObject; end; Result := Result; end; function TPKCS11Session.FindObjectsFinal(): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_FindObjectsFinal, FN_NAME_C_FindObjectsFinal); LastRV := LibraryFunctionList.CK_C_FindObjectsFinal(FhSession); Result := RVSuccess(LastRV); end; function TPKCS11Session.CreateObject(attrObjs: array of TPKCS11Attribute): TPKCS11Object; var retval: TPKCS11Object; newObjHandle: CK_OBJECT_HANDLE; ckAttributes: array of CK_ATTRIBUTE; bufferArray: array of Ansistring; i: Integer; begin CheckFnAvailable(@LibraryFunctionList.CK_C_CreateObject, FN_NAME_C_CreateObject); retval := nil; setlength(ckAttributes, length(attrObjs)); setlength(bufferArray, length(attrObjs)); for i := low(attrObjs) to high(attrObjs) do begin bufferArray[i] := attrObjs[i].ValueAsRawData; ckAttributes[i].attrType := attrObjs[i].AttribType; ckAttributes[i].pValue := PansiChar(bufferArray[i]); ckAttributes[i].ulValueLen := length(bufferArray[i]); end; LastRV := LibraryFunctionList.CK_C_CreateObject( FhSession, @(ckAttributes[0]), length(attrObjs), @newObjHandle ); if RVSuccess(LastRV) then begin retval := TPKCS11Object.Create(); retval.LibraryFunctionList := LibraryFunctionList; retval.FSessionHandle := FhSession; retval.FHandle := newObjHandle; end; Result := retval; end; function TPKCS11Session.CreateObject(attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; var retval: TPKCS11Object; newObjHandle: CK_OBJECT_HANDLE; ckAttributes: array of CK_ATTRIBUTE; bufferArray: array of Ansistring; i: Integer; attrPtr: CK_ATTRIBUTE_PTR; currTemplateAttr: TPKCS11Attribute; begin CheckFnAvailable(@LibraryFunctionList.CK_C_CreateObject, FN_NAME_C_CreateObject); retval := nil; attrPtr := NULL_PTR; if (attrTemplate.Count > 0) then begin setlength(ckAttributes, attrTemplate.Count); setlength(bufferArray, attrTemplate.Count); for i := 0 to (attrTemplate.Count - 1) do begin currTemplateAttr := attrTemplate.Attribute[i]; bufferArray[i] := currTemplateAttr.ValueAsRawData; ckAttributes[i].attrType := currTemplateAttr.AttribType; ckAttributes[i].pValue := PansiChar(bufferArray[i]); ckAttributes[i].ulValueLen := length(bufferArray[i]); end; attrPtr := @(ckAttributes[0]); end; LastRV := LibraryFunctionList.CK_C_CreateObject( FhSession, attrPtr, attrTemplate.Count, @newObjHandle ); if RVSuccess(LastRV) then begin retval := TPKCS11Object.Create(); retval.LibraryFunctionList := LibraryFunctionList; retval.FSessionHandle := FhSession; retval.FHandle := newObjHandle; end; Result := retval; end; function TPKCS11Session.GenerateKey(mechanism: TPKCS11Mechanism; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; begin Result := GenerateKey(mechanism.MechanismType, attrTemplate); end; function TPKCS11Session.GenerateKey(mechanism: CK_MECHANISM_TYPE; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; var retval: TPKCS11Object; newObjHandle: CK_OBJECT_HANDLE; ckAttributes: array of CK_ATTRIBUTE; bufferArray: array of Ansistring; i: Integer; mechStruct: CK_MECHANISM; attrPtr: CK_ATTRIBUTE_PTR; currTemplateAttr: TPKCS11Attribute; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GenerateKey, FN_NAME_C_GenerateKey); retval := nil; mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; attrPtr := NULL_PTR; if (attrTemplate.Count > 0) then begin setlength(ckAttributes, attrTemplate.Count); setlength(bufferArray, attrTemplate.Count); for i := 0 to (attrTemplate.Count - 1) do begin currTemplateAttr := attrTemplate.Attribute[i]; bufferArray[i] := currTemplateAttr.ValueAsRawData; ckAttributes[i].attrType := currTemplateAttr.AttribType; ckAttributes[i].pValue := PansiChar(bufferArray[i]); ckAttributes[i].ulValueLen := length(bufferArray[i]); end; attrPtr := @(ckAttributes[0]); end; LastRV := LibraryFunctionList.CK_C_GenerateKey( FhSession, @mechStruct, attrPtr, attrTemplate.Count, @newObjHandle ); if RVSuccess(LastRV) then begin retval := TPKCS11Object.Create(); retval.LibraryFunctionList := LibraryFunctionList; retval.FSessionHandle := FhSession; retval.FHandle := newObjHandle; end; Result := retval; end; function TPKCS11Session.GenerateKeyPair( mechanism: TPKCS11Mechanism; publicAttrTemplate: TPKCS11AttributeTemplate; privateAttrTemplate: TPKCS11AttributeTemplate; var publicKey: TPKCS11Object; var privateKey: TPKCS11Object ): Boolean; begin Result := GenerateKeyPair(mechanism.MechanismType, publicAttrTemplate, privateAttrTemplate, publicKey, privateKey ); end; function TPKCS11Session.GenerateKeyPair( mechanism: CK_MECHANISM_TYPE; publicAttrTemplate: TPKCS11AttributeTemplate; privateAttrTemplate: TPKCS11AttributeTemplate; var publicKey: TPKCS11Object; var privateKey: TPKCS11Object ): Boolean; var newObjHandlePublic: CK_OBJECT_HANDLE; newObjHandlePrivate: CK_OBJECT_HANDLE; ckAttributesPublic: array of CK_ATTRIBUTE; ckAttributesPrivate: array of CK_ATTRIBUTE; bufferArrayPublic: array of Ansistring; bufferArrayPrivate: array of Ansistring; i: Integer; mechStruct: CK_MECHANISM; attrPtrPublic: CK_ATTRIBUTE_PTR; attrPtrPrivate: CK_ATTRIBUTE_PTR; currTemplateAttr: TPKCS11Attribute; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GenerateKeyPair, FN_NAME_C_GenerateKeyPair); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; attrPtrPublic := NULL_PTR; if (publicAttrTemplate.Count > 0) then begin setlength(ckAttributesPublic, publicAttrTemplate.Count); setlength(bufferArrayPublic, publicAttrTemplate.Count); for i := 0 to (publicAttrTemplate.Count - 1) do begin currTemplateAttr := publicAttrTemplate.Attribute[i]; bufferArrayPublic[i] := currTemplateAttr.ValueAsRawData; ckAttributesPublic[i].attrType := currTemplateAttr.AttribType; ckAttributesPublic[i].pValue := PansiChar(bufferArrayPublic[i]); ckAttributesPublic[i].ulValueLen := length(bufferArrayPublic[i]); end; attrPtrPublic := @(ckAttributesPublic[0]); end; attrPtrPrivate := NULL_PTR; if (privateAttrTemplate.Count > 0) then begin setlength(ckAttributesPrivate, privateAttrTemplate.Count); setlength(bufferArrayPrivate, privateAttrTemplate.Count); for i := 0 to (privateAttrTemplate.Count - 1) do begin currTemplateAttr := privateAttrTemplate.Attribute[i]; bufferArrayPrivate[i] := currTemplateAttr.ValueAsRawData; ckAttributesPrivate[i].attrType := currTemplateAttr.AttribType; ckAttributesPrivate[i].pValue := PansiChar(bufferArrayPrivate[i]); ckAttributesPrivate[i].ulValueLen := length(bufferArrayPrivate[i]); end; attrPtrPrivate := @(ckAttributesPrivate[0]); end; LastRV := LibraryFunctionList.CK_C_GenerateKeyPair( FhSession, @mechStruct, attrPtrPublic, publicAttrTemplate.Count, attrPtrPrivate, privateAttrTemplate.Count, @newObjHandlePublic, @newObjHandlePrivate ); if RVSuccess(LastRV) then begin publicKey := TPKCS11Object.Create(); publicKey.LibraryFunctionList := LibraryFunctionList; publicKey.FSessionHandle := FhSession; publicKey.FHandle := newObjHandlePublic; privateKey := TPKCS11Object.Create(); privateKey.LibraryFunctionList := LibraryFunctionList; privateKey.FSessionHandle := FhSession; privateKey.FHandle := newObjHandlePrivate; end; Result := RVSuccess(LastRV); end; function TPKCS11Session.CopyObject(obj: TPKCS11Object): TPKCS11Object; var retval: TPKCS11Object; newObjHandle: CK_OBJECT_HANDLE; begin CheckFnAvailable(@LibraryFunctionList.CK_C_CopyObject, FN_NAME_C_CopyObject); retval := nil; LastRV := LibraryFunctionList.CK_C_CopyObject( FhSession, obj.FHandle, nil, 0, @newObjHandle ); if RVSuccess(LastRV) then begin retval := TPKCS11Object.Create(); retval.LibraryFunctionList := LibraryFunctionList; retval.FSessionHandle := FhSession; retval.FHandle := newObjHandle; end; Result := retval; end; function TPKCS11Session.DestroyObject(obj: TPKCS11Object): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DestroyObject, FN_NAME_C_DestroyObject); LastRV := LibraryFunctionList.CK_C_DestroyObject(FhSession, obj.FHandle); Result := RVSuccess(LastRV); end; // Returns -1 on error function TPKCS11Session.SlotIDFromInfo(): Integer; var retval: Integer; info: CK_SESSION_INFO; begin retval := -1; if GetSessionInfo(info) then begin retval := info.SlotID; end; Result := retval; end; function TPKCS11Session.GetState(): TPKCS11SessionState; var retval: TPKCS11SessionState; info: CK_SESSION_INFO; begin retval := ssROPublic; if GetSessionInfo(info) then begin retval := CK_STATEToState(info.State); end; Result := retval; end; function TPKCS11Session.GetStateStr(): String; begin Result := PKCS11_SESSION_STATE_DESC[State]; end; function TPKCS11Session.GetFlags(): CK_ULONG; var retval: CK_FLAGS; info: CK_SESSION_INFO; begin retval := 0; if GetSessionInfo(info) then begin retval := info.Flags; end; Result := retval; end; function TPKCS11Session.GetDeviceError(): CK_ULONG; var retval: CK_ULONG; info: CK_SESSION_INFO; begin retval := 0; if GetSessionInfo(info) then begin retval := info.ulDeviceError; end; Result := retval; end; function TPKCS11Session.UserTypeToCK_USER_TYPE(userType: TPKCS11UserType): CK_USER_TYPE; begin Result := PKCS11_USER_TYPE[userType]; end; function TPKCS11Session.CK_USER_TYPEToUserType(ckUserType: CK_USER_TYPE): TPKCS11UserType; var retval: TPKCS11UserType; i: TPKCS11UserType; begin retval := utUser; for i := low(PKCS11_USER_TYPE) to high(PKCS11_USER_TYPE) do begin if (PKCS11_USER_TYPE[i] = ckUserType) then begin retval := i; break; end; end; Result := retval; end; function TPKCS11Session.StateToCK_STATE(state: TPKCS11SessionState): CK_STATE; begin Result := PKCS11_SESSION_STATE[state]; end; function TPKCS11Session.CK_STATEToState(ckState: CK_STATE): TPKCS11SessionState; var retval: TPKCS11SessionState; i: TPKCS11SessionState; begin retval := ssROPublic; for i := low(PKCS11_SESSION_STATE) to high(PKCS11_SESSION_STATE) do begin if (PKCS11_SESSION_STATE[i] = ckState) then begin retval := i; break; end; end; Result := retval; end; // Returns TRUE/FALSE, depending on whether the session is open/valid or // not function TPKCS11Session.GetOpen(): Boolean; var junk: CK_SESSION_INFO; begin Result := GetSessionInfo(junk); end; function TPKCS11Session.InitPIN(usePINPad: Boolean; PIN: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_InitPIN, FN_NAME_C_InitPIN); LastRV := LibraryFunctionList.CK_C_InitPIN( FhSession, CK_UTF8CHAR_PTR(PansiChar(PIN)), length( PIN)); Result := RVSuccess(LastRV); end; function TPKCS11Session.SetPIN(usePINPad: Boolean; oldPIN: Ansistring; newPIN: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SetPIN, FN_NAME_C_SetPIN); LastRV := LibraryFunctionList.CK_C_SetPIN( FhSession, CK_UTF8CHAR_PTR(pansichar(oldPIN)), length(oldPIN), CK_UTF8CHAR_PTR(pansichar(newPIN)), length( newPIN)); Result := RVSuccess(LastRV); end; function TPKCS11Session.InitPIN(): Boolean; begin Result := InitPIN(True, ''); end; function TPKCS11Session.InitPIN(PIN: Ansistring): Boolean; begin Result := InitPIN(False, PIN); end; function TPKCS11Session.SetPIN(): Boolean; begin Result := SetPIN(True, '', ''); end; function TPKCS11Session.SetPIN(oldPIN: Ansistring; newPIN: Ansistring): Boolean; begin Result := SetPIN(False, oldPIN, newPIN); end; // Retrieve object with the application/label attributes set to those // specified // Note: *Caller* is responsible for freeing returned attribute object function TPKCS11Session.GetObject(application: String; objLabel: String): TPKCS11Object; var tmpObjs: TPKCS11ObjectArray; retval: TPKCS11Object; i: Integer; begin retval := nil; tmpObjs := GetObjects(application, objLabel); if (length(tmpObjs) > 0) then begin retval := tmpObjs[low(tmpObjs)]; // Ditch all remaining objects for i := (low(tmpObjs) + 1) to high(tmpObjs) do begin tmpObjs[i].Free(); end; end; Result := retval; end; // Retrieve object with the application/label attributes set to those // specified // Note: *Caller* is responsible for freeing *ALL* returned attribute objects function TPKCS11Session.GetObjects(application: String): TPKCS11ObjectArray; begin Result := GetObjects(application, PKCS11_IGNORE_PARAMETER); end; // Retrieve object with the application/label attributes set to those // specified // Note: *Caller* is responsible for freeing *ALL* returned attribute objects function TPKCS11Session.GetObjects(application: String; objLabel: String): TPKCS11ObjectArray; var retval: TPKCS11ObjectArray; currObj: TPKCS11Object; attrApp: TPKCS11Attribute; attrLabel: TPKCS11Attribute; begin SetLength(retval, 0); if FindObjectsInit() then begin currObj := FindNextObject(); while (currObj <> nil) do begin attrApp := currObj.GetAttribute(CKA_APPLICATION); attrLabel := currObj.GetAttribute(CKA_LABEL); if ((attrApp <> nil) and (attrLabel <> nil)) then begin if (((application = PKCS11_IGNORE_PARAMETER) or (trim(attrApp.ValueAsString) = trim(application))) and ((objLabel = PKCS11_IGNORE_PARAMETER) or (trim(attrLabel.ValueAsString) = trim(objLabel)))) then begin SetLength(retval, (length(retval) + 1)); retval[length(retval) - 1] := currObj; end else begin currObj.Free(); end; end; if (attrApp <> nil) then begin attrApp.Free(); end; if (attrLabel <> nil) then begin attrLabel.Free(); end; currObj := FindNextObject(); end; FindObjectsFinal(); end; Result := retval; end; function TPKCS11Session.GetObjects(objClass: CK_OBJECT_CLASS): TPKCS11ObjectArray; var retval: TPKCS11ObjectArray; currObj: TPKCS11Object; attrObjClass: TPKCS11Attribute; begin SetLength(retval, 0); if FindObjectsInit() then begin currObj := FindNextObject(); while (currObj <> nil) do begin attrObjClass := currObj.GetAttribute(CKA_CLASS); if (attrObjClass <> nil) then begin if (attrObjClass.ValueAsNumber = objClass) then begin SetLength(retval, (length(retval) + 1)); retval[length(retval) - 1] := currObj; end else begin currObj.Free(); end; end; if (attrObjClass <> nil) then begin attrObjClass.Free(); end; currObj := FindNextObject(); end; FindObjectsFinal(); end; Result := retval; end; // Important: Keep implementation of: // // TPKCS11Token.CloseSession(...); // TPKCS11Session.CloseSession(); // // in sync procedure TPKCS11Session.CloseSession(); begin CheckFnAvailable(@LibraryFunctionList.CK_C_CloseSession, FN_NAME_C_CloseSession); LastRV := LibraryFunctionList.CK_C_CloseSession(FhSession); end; function TPKCS11Session.EncryptInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_EncryptInit, FN_NAME_C_EncryptInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_EncryptInit( FhSession, @mechStruct, keyObj.FHandle ); Result := RVSuccess(LastRV); end; function TPKCS11Session.EncryptInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; begin Result := EncryptInit(mechanism.MechanismType, keyObj); end; function TPKCS11Session.Encrypt(plaintext: Ansistring; var cyphertext: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpCyphertext: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_Encrypt, FN_NAME_C_Encrypt); tmpLen := length(plaintext); FLastEncryptDecryptLen := tmpLen; tmpCyphertext := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_Encrypt( FhSession, CK_BYTE_PTR(PAnsiChar(plaintext)), length(plaintext), CK_BYTE_PTR(PAnsiChar(tmpCyphertext)), @tmpLen); cyphertext := Copy(tmpCyphertext, 1, tmpLen); Overwrite(tmpCyphertext); Result := RVSuccess(LastRV); end; function TPKCS11Session.EncryptUpdate(plaintext: Ansistring; var cyphertext: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpCyphertext: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_EncryptUpdate, FN_NAME_C_EncryptUpdate); tmpLen := length(plaintext); FLastEncryptDecryptLen := tmpLen; tmpCyphertext := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_EncryptUpdate( FhSession, CK_BYTE_PTR(pansichar(plaintext)), length(plaintext), CK_BYTE_PTR(pansichar(tmpCyphertext)), @tmpLen); cyphertext := Copy(tmpCyphertext, 1, tmpLen); Overwrite(tmpCyphertext); Result := RVSuccess(LastRV); end; function TPKCS11Session.EncryptFinal(var cyphertext: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpCyphertext: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_EncryptFinal, FN_NAME_C_EncryptFinal); tmpCyphertext := StringOfChar(AnsiChar(#0), max(FLastEncryptDecryptLen, BUFFER_LEN_MIN_ENCRYPT_DECRYPT)); LastRV := LibraryFunctionList.CK_C_EncryptFinal( FhSession, CK_BYTE_PTR(pansichar(tmpCyphertext)), @tmpLen ); cyphertext := Copy(tmpCyphertext, 1, tmpLen); Overwrite(tmpCyphertext); Result := RVSuccess(LastRV); end; function TPKCS11Session.DecryptInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DecryptInit, FN_NAME_C_DecryptInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_DecryptInit( FhSession, @mechStruct, keyObj.FHandle ); Result := RVSuccess(LastRV); end; function TPKCS11Session.DecryptInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; begin Result := DecryptInit(mechanism.MechanismType, keyObj); end; function TPKCS11Session.Decrypt(cyphertext: Ansistring; var plaintext: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpPlaintext: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_Decrypt, FN_NAME_C_Decrypt); tmpLen := length(cyphertext); FLastEncryptDecryptLen := tmpLen; tmpPlaintext := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_Decrypt( FhSession, CK_BYTE_PTR(pansichar(cyphertext)), length(cyphertext), CK_BYTE_PTR(pansichar(tmpPlaintext)), @tmpLen); plaintext := Copy(tmpPlaintext, 1, tmpLen); Overwrite(tmpPlaintext); Result := RVSuccess(LastRV); end; function TPKCS11Session.DecryptUpdate(cyphertext: Ansistring; var plaintext: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpPlaintext: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DecryptUpdate, FN_NAME_C_DecryptUpdate); tmpLen := length(cyphertext); FLastEncryptDecryptLen := tmpLen; tmpPlaintext := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_DecryptUpdate( FhSession, CK_BYTE_PTR(pansichar(cyphertext)), length(cyphertext), CK_BYTE_PTR(pansichar(tmpPlaintext)), @tmpLen); plaintext := Copy(tmpPlaintext, 1, tmpLen); Overwrite(tmpPlaintext); Result := RVSuccess(LastRV); end; function TPKCS11Session.DecryptFinal(var plaintext: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpPlaintext: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DecryptFinal, FN_NAME_C_DecryptFinal); tmpPlaintext := StringOfChar(AnsiChar(#0), max(FLastEncryptDecryptLen, BUFFER_LEN_MIN_ENCRYPT_DECRYPT)); LastRV := LibraryFunctionList.CK_C_DecryptFinal( FhSession, CK_BYTE_PTR(pansichar(tmpPlaintext)), @tmpLen ); plaintext := Copy(tmpPlaintext, 1, tmpLen); Overwrite(tmpPlaintext); Result := RVSuccess(LastRV); end; function TPKCS11Session.DigestInit(mechanism: CK_MECHANISM_TYPE): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DigestInit, FN_NAME_C_DigestInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_DigestInit( FhSession, @mechStruct ); Result := RVSuccess(LastRV); end; function TPKCS11Session.DigestInit(mechanism: TPKCS11Mechanism): Boolean; begin Result := DigestInit(mechanism.MechanismType); end; function TPKCS11Session.Digest(data: Ansistring; var digest: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpDigest: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_Digest, FN_NAME_C_Digest); tmpLen := length(data); tmpDigest := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_Digest( FhSession, CK_BYTE_PTR(pansichar(data)), length(data), CK_BYTE_PTR(pansichar(tmpDigest)), @tmpLen); digest := Copy(tmpDigest, 1, tmpLen); Overwrite(tmpDigest); Result := RVSuccess(LastRV); end; function TPKCS11Session.DigestUpdate(data: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DigestUpdate, FN_NAME_C_DigestUpdate); LastRV := LibraryFunctionList.CK_C_DigestUpdate( FhSession, CK_BYTE_PTR(pansichar(data)), length( data)); Result := RVSuccess(LastRV); end; function TPKCS11Session.DigestKey(data: Ansistring; keyObj: TPKCS11Object): Boolean; var tmpLen: CK_ULONG; tmpDigest: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DigestKey, FN_NAME_C_DigestKey); tmpLen := length(data); tmpDigest := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_DigestKey( FhSession, keyObj.FHandle); Result := RVSuccess(LastRV); end; function TPKCS11Session.DigestFinal(var digest: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpDigest: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DigestFinal, FN_NAME_C_DigestFinal); tmpDigest := StringOfChar(AnsiChar(#0), BUFFER_LEN_DIGEST); LastRV := LibraryFunctionList.CK_C_DigestFinal( FhSession, CK_BYTE_PTR(pansichar(tmpDigest)), @tmpLen ); digest := Copy(tmpDigest, 1, tmpLen); Overwrite(tmpDigest); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SignInit, FN_NAME_C_SignInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_SignInit( FhSession, @mechStruct, keyObj.FHandle ); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; begin Result := SignInit(mechanism.MechanismType, keyObj); end; function TPKCS11Session.Sign(data: Ansistring; var signature: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpSignature: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_Sign, FN_NAME_C_Sign); tmpLen := length(data); tmpSignature := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_Sign(FhSession, CK_BYTE_PTR(pansichar(data)), length(data), CK_BYTE_PTR(pansichar(tmpSignature)), @tmpLen); signature := Copy(tmpSignature, 1, tmpLen); Overwrite(tmpSignature); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignUpdate(data: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SignUpdate, FN_NAME_C_SignUpdate); LastRV := LibraryFunctionList.CK_C_SignUpdate( FhSession, CK_BYTE_PTR(pansichar(data)), length( data)); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignFinal(var signature: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpSignature: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SignFinal, FN_NAME_C_SignFinal); tmpSignature := StringOfChar(AnsiChar(#0), BUFFER_LEN_SIGN); LastRV := LibraryFunctionList.CK_C_SignFinal( FhSession, CK_BYTE_PTR(pansichar(tmpSignature)), @tmpLen ); signature := Copy(tmpSignature, 1, tmpLen); Overwrite(tmpSignature); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignRecoverInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SignRecoverInit, FN_NAME_C_SignRecoverInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_SignRecoverInit( FhSession, @mechStruct, keyObj.FHandle ); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignRecoverInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; begin Result := SignRecoverInit(mechanism.MechanismType, keyObj); end; function TPKCS11Session.SignRecover(data: Ansistring; var signature: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpSignature: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SignRecover, FN_NAME_C_SignRecover); tmpLen := length(data); tmpSignature := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_SignRecover( FhSession, CK_BYTE_PTR(pansichar(data)), length(data), CK_BYTE_PTR(pansichar(tmpSignature)), @tmpLen); signature := Copy(tmpSignature, 1, tmpLen); Overwrite(tmpSignature); Result := RVSuccess(LastRV); end; function TPKCS11Session.VerifyInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_VerifyInit, FN_NAME_C_VerifyInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_VerifyInit( FhSession, @mechStruct, keyObj.FHandle ); Result := RVSuccess(LastRV); end; function TPKCS11Session.VerifyInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; begin Result := VerifyInit(mechanism.MechanismType, keyObj); end; function TPKCS11Session.Verify(data: Ansistring; signature: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_Verify, FN_NAME_C_Verify); LastRV := LibraryFunctionList.CK_C_Verify( FhSession, CK_BYTE_PTR(pansichar(data)), length(data), CK_BYTE_PTR(pansichar(signature)), length( signature)); Result := RVSuccess(LastRV); end; function TPKCS11Session.VerifyUpdate(data: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_VerifyUpdate, FN_NAME_C_VerifyUpdate); LastRV := LibraryFunctionList.CK_C_VerifyUpdate( FhSession, CK_BYTE_PTR(pansichar(data)), length( data)); Result := RVSuccess(LastRV); end; function TPKCS11Session.VerifyFinal(signature: Ansistring): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_VerifyFinal, FN_NAME_C_VerifyFinal); LastRV := LibraryFunctionList.CK_C_VerifyFinal( FhSession, CK_BYTE_PTR(pansichar(signature)), length( signature)); Result := RVSuccess(LastRV); end; function TPKCS11Session.VerifyRecoverInit(mechanism: CK_MECHANISM_TYPE; keyObj: TPKCS11Object): Boolean; var mechStruct: CK_MECHANISM; begin CheckFnAvailable(@LibraryFunctionList.CK_C_VerifyRecoverInit, FN_NAME_C_VerifyRecoverInit); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; LastRV := LibraryFunctionList.CK_C_VerifyRecoverInit( FhSession, @mechStruct, keyObj.FHandle ); Result := RVSuccess(LastRV); end; function TPKCS11Session.VerifyRecoverInit(mechanism: TPKCS11Mechanism; keyObj: TPKCS11Object): Boolean; begin Result := VerifyRecoverInit(mechanism.MechanismType, keyObj); end; function TPKCS11Session.VerifyRecover(data: Ansistring; var signature: Ansistring): Boolean; var tmpLen: CK_ULONG; tmpSignature: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_VerifyRecover, FN_NAME_C_VerifyRecover); tmpLen := length(data); tmpSignature := StringOfChar(AnsiChar(#0), tmpLen); LastRV := LibraryFunctionList.CK_C_VerifyRecover( FhSession, CK_BYTE_PTR(pansichar(data)), length(data), CK_BYTE_PTR(pansichar(tmpSignature)), @tmpLen); signature := Copy(tmpSignature, 1, tmpLen); Overwrite(tmpSignature); Result := RVSuccess(LastRV); end; function TPKCS11Session.WrapKey(mechanism: CK_MECHANISM_TYPE; wrappingKeyObj: TPKCS11Object; keyObj: TPKCS11Object; var wrappedKey: Ansistring): Boolean; var mechStruct: CK_MECHANISM; tmpLen: CK_ULONG; tmpWrappedKey: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_WrapKey, FN_NAME_C_WrapKey); mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; tmpWrappedKey := StringOfChar(AnsiChar(#0), BUFFER_LEN_WRAPPED_KEY); LastRV := LibraryFunctionList.CK_C_WrapKey( FhSession, @mechStruct, wrappingKeyObj.FHandle, keyObj.FHandle, CK_BYTE_PTR(pansichar(tmpWrappedKey)), @tmpLen); wrappedKey := Copy(tmpWrappedKey, 1, tmpLen); Overwrite(tmpWrappedKey); Result := RVSuccess(LastRV); end; function TPKCS11Session.UnwrapKey(mechanism: CK_MECHANISM_TYPE; unwrappingKeyObj: TPKCS11Object; wrappedKey: Ansistring; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; var retval: TPKCS11Object; newObjHandle: CK_OBJECT_HANDLE; ckAttributes: array of CK_ATTRIBUTE; bufferArray: array of Ansistring; i: Integer; mechStruct: CK_MECHANISM; attrPtr: CK_ATTRIBUTE_PTR; currTemplateAttr: TPKCS11Attribute; begin CheckFnAvailable(@LibraryFunctionList.CK_C_UnwrapKey, FN_NAME_C_UnwrapKey); retval := nil; mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; attrPtr := NULL_PTR; if (attrTemplate.Count > 0) then begin setlength(ckAttributes, attrTemplate.Count); setlength(bufferArray, attrTemplate.Count); for i := 0 to (attrTemplate.Count - 1) do begin currTemplateAttr := attrTemplate.Attribute[i]; bufferArray[i] := currTemplateAttr.ValueAsRawData; ckAttributes[i].attrType := currTemplateAttr.AttribType; ckAttributes[i].pValue := pansichar(bufferArray[i]); ckAttributes[i].ulValueLen := length(bufferArray[i]); end; attrPtr := @(ckAttributes[0]); end; LastRV := LibraryFunctionList.CK_C_UnwrapKey( FhSession, @mechStruct, unwrappingKeyObj.FHandle, CK_BYTE_PTR(pansichar(wrappedKey)), length(wrappedKey), attrPtr, attrTemplate.Count, @newObjHandle ); if RVSuccess(LastRV) then begin retval := TPKCS11Object.Create(); retval.LibraryFunctionList := LibraryFunctionList; retval.FSessionHandle := FhSession; retval.FHandle := newObjHandle; end; Result := retval; end; function TPKCS11Session.DeriveKey(mechanism: CK_MECHANISM_TYPE; baseKey: TPKCS11Object; attrTemplate: TPKCS11AttributeTemplate): TPKCS11Object; var retval: TPKCS11Object; newObjHandle: CK_OBJECT_HANDLE; ckAttributes: array of CK_ATTRIBUTE; bufferArray: array of Ansistring; i: Integer; mechStruct: CK_MECHANISM; attrPtr: CK_ATTRIBUTE_PTR; currTemplateAttr: TPKCS11Attribute; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DeriveKey, FN_NAME_C_DeriveKey); retval := nil; mechStruct.mechanism := mechanism; mechStruct.pParameter := NULL_PTR; mechStruct.ulParameterLen := 0; attrPtr := NULL_PTR; if (attrTemplate.Count > 0) then begin setlength(ckAttributes, attrTemplate.Count); setlength(bufferArray, attrTemplate.Count); for i := 0 to (attrTemplate.Count - 1) do begin currTemplateAttr := attrTemplate.Attribute[i]; bufferArray[i] := currTemplateAttr.ValueAsRawData; ckAttributes[i].attrType := currTemplateAttr.AttribType; ckAttributes[i].pValue := pansichar(bufferArray[i]); ckAttributes[i].ulValueLen := length(bufferArray[i]); end; attrPtr := @(ckAttributes[0]); end; LastRV := LibraryFunctionList.CK_C_DeriveKey( FhSession, @mechStruct, baseKey.FHandle, attrPtr, attrTemplate.Count, @newObjHandle ); if RVSuccess(LastRV) then begin retval := TPKCS11Object.Create(); retval.LibraryFunctionList := LibraryFunctionList; retval.FSessionHandle := FhSession; retval.FHandle := newObjHandle; end; Result := retval; end; function TPKCS11Session.GetFunctionStatus(): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GetFunctionStatus, FN_NAME_C_GetFunctionStatus); LastRV := LibraryFunctionList.CK_C_GetFunctionStatus(FhSession); Result := RVSuccess(LastRV); end; function TPKCS11Session.CancelFunction(): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_CancelFunction, FN_NAME_C_CancelFunction); LastRV := LibraryFunctionList.CK_C_CancelFunction(FhSession); Result := RVSuccess(LastRV); end; function TPKCS11Session.DigestEncryptUpdate(part: Ansistring; var encryptedPart: Ansistring): Boolean; var tmpLen: CK_ULONG; inData: Ansistring; outData: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DigestEncryptUpdate, FN_NAME_C_DigestEncryptUpdate); inData := part; outData := StringOfChar(AnsiChar(#0), max(length(inData), BUFFER_LEN_MIN_ENCRYPT_DECRYPT)); tmpLen := length(outData); LastRV := LibraryFunctionList.CK_C_DigestEncryptUpdate( FhSession, CK_BYTE_PTR(pansichar(inData)), length(inData), CK_BYTE_PTR(pansichar(outData)), @tmpLen); encryptedPart := Copy(outData, 1, tmpLen); Overwrite(inData); Overwrite(outData); Result := RVSuccess(LastRV); end; function TPKCS11Session.DecryptDigestUpdate(pEncryptedPart: Ansistring; var part: Ansistring): Boolean; var tmpLen: CK_ULONG; inData: Ansistring; outData: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DecryptDigestUpdate, FN_NAME_C_DecryptDigestUpdate); inData := pEncryptedPart; outData := StringOfChar(AnsiChar(#0), max(length(inData), BUFFER_LEN_MIN_ENCRYPT_DECRYPT)); tmpLen := length(outData); LastRV := LibraryFunctionList.CK_C_DecryptDigestUpdate( FhSession, CK_BYTE_PTR(pansichar(inData)), length(inData), CK_BYTE_PTR(pansichar(outData)), @tmpLen); part := Copy(outData, 1, tmpLen); Overwrite(inData); Overwrite(outData); Result := RVSuccess(LastRV); end; function TPKCS11Session.SignEncryptUpdate(part: Ansistring; var encryptedPart: Ansistring): Boolean; var tmpLen: CK_ULONG; inData: Ansistring; outData: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_SignEncryptUpdate, FN_NAME_C_SignEncryptUpdate); inData := part; outData := StringOfChar(AnsiChar(#0), max(length(inData), BUFFER_LEN_MIN_ENCRYPT_DECRYPT)); tmpLen := length(outData); LastRV := LibraryFunctionList.CK_C_SignEncryptUpdate( FhSession, CK_BYTE_PTR(pansichar(inData)), length(inData), CK_BYTE_PTR(pansichar(outData)), @tmpLen); encryptedPart := Copy(outData, 1, tmpLen); Overwrite(inData); Overwrite(outData); Result := RVSuccess(LastRV); end; function TPKCS11Session.DecryptVerifyUpdate(pEncryptedPart: Ansistring; var part: Ansistring): Boolean; var tmpLen: CK_ULONG; inData: Ansistring; outData: Ansistring; begin CheckFnAvailable(@LibraryFunctionList.CK_C_DecryptVerifyUpdate, FN_NAME_C_DecryptVerifyUpdate); inData := pEncryptedPart; outData := StringOfChar(AnsiChar(#0), max(length(inData), BUFFER_LEN_MIN_ENCRYPT_DECRYPT)); tmpLen := length(outData); LastRV := LibraryFunctionList.CK_C_DecryptVerifyUpdate( FhSession, CK_BYTE_PTR(pansichar(inData)), length(inData), CK_BYTE_PTR(pansichar(outData)), @tmpLen); part := Copy(outData, 1, tmpLen); Overwrite(inData); Overwrite(outData); Result := RVSuccess(LastRV); end; end.
unit Actions; {$mode objfpc}{$H+} interface uses Graphics,Coach,Param,Math,DecConsts,ObsAvoid,SysUtils; const IDCTRL_OMNI_FORWARD=1; IDCTRL_OMNI_POSITION=2; IDCTRL_OMNI_XYTETA=3; type TAction=(acStop, acGoToXYTeta,acAdvisedSpeed); const CActionString: array[low(TAction)..High(TAction)] of string = ('acStop', 'acGoToXYTeta','acAdvisedSpeed'); const GoToXYTetaPrecision=0.025; procedure ActionStop(num: integer); procedure ActionGoToXYTeta(num: integer); procedure ActionAdvisedSpeed(num: integer); procedure VVnToVxy(teta,v,vn: double; var Vx,Vy: double); type TActionFunc = procedure(num: integer); const CActionFunc: array[low(TAction)..High(TAction)] of TActionFunc = ( @ActionStop, @ActionGoToXYTeta,@ActionAdvisedSpeed); type TActionPars=record x,y,w,teta: double; sx,sy: double; // start position for acFollowVector anyway: boolean; speed: double; speed_on_target: double; target_precision: double; chipkick_dist: double; avoid: TAvoidSet; end; var ActionPars: array [0..MaxRobots-1] of TActionPars; traj: TTrajectory; function ActionString(a: TAction): string; implementation uses Tactic, Utils, Robots, Roles; function ActionString(a: TAction): string; begin result:=CActionString[a]; end; //---------------------------------------------------------------------- // Controller function SatVal(v, vmax: double): double; begin if v > vmax then v := vmax; if v < -vmax then v := -vmax; result := v; end; procedure ProportionalSat(var v1,v2,v3: double; vmax: double); var maxv,minv: double; scale,scalemax,scalemin: double; begin maxv:=Max(v1,Max(v2,v3)); minv:=Min(v1,Min(v2,v3)); if maxv>vmax then scalemax:=maxv/vmax else scalemax:=1.0; if minv<-vmax then scalemin:=minv/(-vmax) else scalemin:=1.0; scale:=Max(scalemin,scalemax); v1:=v1/scale; v2:=v2/scale; v3:=v3/scale; end; procedure SetTacticCommandsInRobotRef(var com: TTacticCommand; v,vn,w: double); begin com.v:=v; com.vn:=vn; com.w:=w; with com do begin v1 := v * MechCosAlpha + vn * MechSinAlpha + MechD * w; v2 := -v * MechCosAlpha + vn * MechSinAlpha + MechD * w; v3 := -vn + MechB * w; ProportionalSat(v1, v2, v3, SpeedMax); end; end; procedure VxyToVVn(teta,vx,vy: double; var V,Vn: double); var ct,st: double; begin ct:=cos(teta); st:=sin(teta); v:=vx*ct+vy*st; vn:=-vx*st+vy*ct; end; procedure ActionAdvisedSpeed(num: integer); var advV,advVn,advW:double; begin // n se usa no coach (ver mais tard para eliminar action) //advV:=RobotState[num].LocAdvV; //advVn:=RobotState[num].LocAdvVn; //advW:=RobotState[num].LocAdvW; // //SetTacticCommandsInRobotRef(TacticCommands[num],advV,advVn,advW); end; procedure VVnToVxy(teta,v,vn: double; var Vx,Vy: double); var ct,st: double; begin ct:=cos(teta); st:=sin(teta); vx:=v*ct-vn*st; vy:=v*st+vn*ct; end; procedure TrajectoryController(speed, speed_on_target: double; var state: TRobotState; var com: TTacticCommand; var traj: TTrajectory); var statev, statevn, v, vn, dteta, teta_power: double; vmax, pw, tx, ty, segteta: double; idx: integer; begin idx := Min(2, traj.count-1); tx := traj.pts[idx].x; ty := traj.pts[idx].y; dteta := DiffAngle(traj.pts[idx].teta, state.teta); teta_power := traj.pts[idx].teta_power; segteta := ATan2(ty-state.y,tx-state.x); VxyToVVn(segteta, state.vx, state.vy, statev, statevn); // calculate maximum speed for a constant desaccelaration to target if traj.distance < deltadist then begin vmax := 0; end else begin vmax := sqr(speed_on_target) + 0.7*0.7*(traj.distance - deltadist); if vmax > 0 then begin vmax := sqrt(vmax); if vmax>speedmax then vmax:=SpeedMax; end else vmax := 0; end; v := speed; if v > vmax then v := vmax; vn := -statevn * 0.75; if vn > vmax then vn := vmax; if vn < -vmax then vn := -vmax; if abs(dteta) < deltateta * Pi / 180 then begin pw := 0; end else begin pw := 4 * dteta - 0.5 * state.w; pw := pw * teta_power; end; VVnToVxy(segteta, v, vn, statev, statevn); VxyToVVn(state.teta, statev, statevn, v, vn); SetTacticCommandsInRobotRef(com, v, vn, pw); end; //---------------------------------------------------------------------- // Actions procedure ActionStop(num: integer); begin with TacticCommands[num] do begin v1:=0; v2:=0; v3:=0; v:=0; vn:=0; w:=0; end; RobotCalcData[num].trajectory_length := 0; end; procedure ActionGoToXYTeta(num: integer); var rx,ry,d: double; i: integer; begin rx:=ActionPars[num].x; ry:=ActionPars[num].y; RobotBestPath(num,rx,ry,traj,ActionPars[num].avoid); for i:=0 to traj.count - 1 do begin traj.pts[i].teta := ActionPars[num].teta; traj.pts[i].teta_power := 1; end; TrajectoryController(ActionPars[num].speed, ActionPars[num].speed_on_target, RobotState[num], TacticCommands[num], traj); RobotCalcData[num].trajectory_length := traj.distance; end; end.
// файл colorUnit.pas unit colorUnit; interface uses math; //---------------------------------- type Tcvet = record // цвет как тройка R, G, B : integer; // чисел Red, Green, end; // Blue; //== смешивание и «умножение цветов»: ============ function mix_colors( c_1, c_2: Tcvet ): Tcvet; function mult_colors( color : Tcvet; k: double ): Есмуе; //---------------------------------- implementation //---------------------------------- function mix_colors( c_1, c_2: Tcvet ): Tcvet; var c: Tcvet; begin c.R := ( c_1.R + c_2.R ) div 2 mod 256; c.G := ( c_1.G + c_2.G ) div 2 mod 256; c.B := ( c_1.B + c_2.B ) div 2 mod 256; result := c; end; //---------------------------------- function mult_colors( color : Tcvet; k: double ): Tcvet; begin color.R := floor( abs( k*color.R ) ) mod 256; color.G := floor( abs( k*color.G ) ) mod 256; color.B := floor( abs( k*color.B ) ) mod 256; result := color; end; end. // конец файла colorUnit.pas
program HelloWorld(output); begin Write('Hello, world!') end.
unit JMC_FileUtils; interface uses Classes, ShellAPI, SysUtils, Windows, FileCtrl; function ExpandPath(const MasterFileName, SlaveFileName: string): string; function ExpandPathFromExe(const SlaveFileName: string): string; function RelatePathFromExe(const SlaveFileName: string): string; function SettingsFileName: string; function FileToStr(const FileName: string; var S: string): Boolean; function StrToFile(const FileName: string; var S: string): Boolean; function CreatePath(const Path: string): Boolean; function OpenFile(const FileName: string; const OverrideValidation: Boolean = False): Boolean; implementation { ExpandPath doesn't work when: MasterFileName = 'C:\My Documents\Delphi Projects\ParserFAR23\Source\Data\' SlaveFileName = '\Data\2007-11-22 FAR 23.htm' } function ExpandPath(const MasterFileName, SlaveFileName: string): string; // If SlaveFileName is a path only, encompass a call to ExpandPath with a call to IncludeTrailingPathDelimiter. var S: string; begin S := SysUtils.GetCurrentDir; if not SysUtils.SetCurrentDir(ExtractFilePath(MasterFileName)) then begin Result := ''; Exit; end; Result := SysUtils.ExpandFileName(SlaveFileName); SysUtils.SetCurrentDir(S); end; function ExpandPathFromExe(const SlaveFileName: string): string; begin Result := ExpandPath(SysUtils.ExtractFilePath(ParamStr(0)), SlaveFileName); end; function RelatePathFromExe(const SlaveFileName: string): string; begin Result := SysUtils.ExtractRelativePath(SysUtils.ExtractFilePath(ParamStr(0)), SlaveFileName); end; function SettingsFileName: string; begin Result := SysUtils.ChangeFileExt(ParamStr(0), '.ini'); end; function FileToStr(const FileName: string; var S: string): Boolean; // FileName must be fully qualified var F: TFileStream; Buffer: array[1..1024] of Char; Temp: string; i: Integer; begin Result := False; S := ''; if SysUtils.FileExists(FileName) then try F := Classes.TFileStream.Create(FileName, fmOpenRead + fmShareDenyNone); F.Seek(0, soFromBeginning); repeat i := F.Read(Buffer, SizeOf(Buffer)); Temp := Copy(Buffer, 1, i); S := S + Temp; until Length(Temp) = 0; F.Free; Result := True; except Result := False; end; end; function StrToFile(const FileName: string; var S: string): Boolean; // FileName must be fully qualified var F: TextFile; Path: string; begin Path := ExtractFilePath(FileName); if not FileCtrl.DirectoryExists(Path) then FileCtrl.ForceDirectories(Path); AssignFile(F, FileName); try Rewrite(F); except Result := False; Exit; end; Write(F, S); CloseFile(F); Result := True; end; function CreatePath(const Path: string): Boolean; begin try Result := FileCtrl.ForceDirectories(Path); except Result := False; end; end; function OpenFile(const FileName: string; const OverrideValidation: Boolean = False): Boolean; begin Result := SysUtils.FileExists(FileName) or OverrideValidation; if Result then Result := ShellAPI.ShellExecute(0, 'open', PChar(FileName), '', nil, SW_SHOWNORMAL) <= 32; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Implements a HDS, which automatically maps textures onto a parent HDS . This HDS links to and extracts its height data from a parent HDS. (like TVXHeightTileFile) The HDS also links to a TVXMaterial Library, and maps ALL textures from the selected Material Library onto the terrain, WITHOUT using Multitexturing. The position and scale of each texture is determined by the material's own TextureOffset and TextureScale properties. This makes it easy to tile many textures onto a single, continuous TVXTerrainRenderer. If two or more textures in the library overlap, the top texture is used.( ie.the later one in the list) WARNING: Only one base texture is mapped onto each terrain tile, so, make sure your texture edges are alligned to height tile edges, or gaps will show. (Of course you can still multitexture in a detail texture too.) } unit VXS.TexturedHDS; interface {$I VXScene.inc} uses System.Types, System.Classes, VXS.VectorTypes, VXS.Coordinates, VXS.HeightData, VXS.Material; type TVXTexturedHDS = class(TVXHeightDataSource) private FOnStartPreparingData: TStartPreparingDataEvent; FOnMarkDirty: TMarkDirtyEvent; FHeightDataSource: TVXHeightDataSource; FMaterialLibrary: TVXMaterialLibrary; FWholeTilesOnly: Boolean; FTileSize: integer; FTilesPerTexture: integer; protected procedure SetHeightDataSource(val: TVXHeightDataSource); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartPreparingData(HeightData: TVXHeightData); override; procedure MarkDirty(const area: TRect); override; published property MaxPoolSize; property OnStartPreparingData: TStartPreparingDataEvent read FOnStartPreparingData write FOnStartPreparingData; property OnMarkDirtyEvent: TMarkDirtyEvent read FOnMarkDirty write FOnMarkDirty; property HeightDataSource: TVXHeightDataSource read FHeightDataSource write SetHeightDataSource; property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write FMaterialLibrary; property WholeTilesOnly: Boolean read FWholeTilesOnly write FWholeTilesOnly; { This should match TileSize in TVXTerrainRenderer } property TileSize: integer read FTileSize write FTileSize; { This should match TilesPerTexture in TVXTerrainRenderer } property TilesPerTexture: integer read FTilesPerTexture write FTilesPerTexture; end; //------------------------------------------------------ implementation //------------------------------------------------------ // ------------------ // ------------------ TVXTexturedHDS ------------------ // ------------------ constructor TVXTexturedHDS.Create(AOwner: TComponent); begin FHeightDataSource := nil; FMaterialLibrary := nil; FTileSize := 16; FTilesPerTexture := 1; inherited Create(AOwner); end; destructor TVXTexturedHDS.Destroy; begin inherited Destroy; end; procedure TVXTexturedHDS.MarkDirty(const area: TRect); begin inherited; if Assigned(FOnMarkDirty) then FOnMarkDirty(area); end; procedure TVXTexturedHDS.StartPreparingData(HeightData: TVXHeightData); var HDS: TVXHeightDataSource; htfHD: TVXHeightData; MatLib: TVXMaterialLibrary; Mat: TVXLibMaterial; HD: TVXHeightData; MatInx: integer; tileL, tileR, tileT, tileB: single; found: Boolean; texL, texR, texT, texB, swp: single; texSize: integer; begin if not Assigned(FHeightDataSource) then begin HeightData.DataState := hdsNone; exit; end; // ---Height Data-- HD := HeightData; HD.DataType := hdtSmallInt; HD.Allocate(hdtSmallInt); HDS := self.FHeightDataSource; // HD.FTextureCoordinatesMode:=tcmWorld; htfHD := HDS.GetData(HD.XLeft, HD.YTop, HD.Size, HD.DataType); if htfHD.DataState = hdsNone then begin HD.DataState := hdsNone; exit; end else HD.DataState := hdsPreparing; Move(htfHD.SmallIntData^, HeightData.SmallIntData^, htfHD.DataSize); // NOT inverted // ---------------- // ---Select the best texture from the attached material library-- MatLib := self.FMaterialLibrary; if Assigned(MatLib) then begin // --Get the world coordinates of the current terrain height tile-- texSize := FTileSize * FTilesPerTexture; if FWholeTilesOnly then begin // picks top texture that covers the WHOLE tile. tileL := (HD.XLeft) / texSize; tileT := (HD.YTop + (HD.Size - 1)) / texSize - 1; tileR := (HD.XLeft + (HD.Size - 1)) / texSize; tileB := (HD.YTop) / texSize - 1; end else begin // picks top texture that covers any part of the tile. If the texture si not wrapped, the rest of the tile is left blank. tileL := (HD.XLeft + (HD.Size - 2)) / texSize; tileT := (HD.YTop + 1) / texSize - 1; tileR := (HD.XLeft + 1) / texSize; tileB := (HD.YTop + (HD.Size - 2)) / texSize - 1; end; //--picks top texture that covers tile center-- //tileL:=(HD.XLeft+(HD.Size/2))/HTFSizeX; //tileT:=(HD.YTop +(HD.Size/2))/HTFSizeY-1; //tileB:=tileT; //tileR:=tileL; //--------------------------------------------- MatInx:=MatLib.Materials.Count; Mat:=nil; found:=false; while (not found) and (MatInx > 0) do begin MatInx := MatInx - 1; Mat := MatLib.Materials[MatInx]; texL := -Mat.TextureOffset.X / Mat.TextureScale.X; texR := texL + (1 / Mat.TextureScale.X); texT := Mat.TextureOffset.Y / Mat.TextureScale.Y; texB := texT - (1 / Mat.TextureScale.Y); if texB > texT then begin swp := texB; texB := texT; texT := swp; end; if texL > texR then begin swp := texL; texL := texR; texR := swp; end; if (tileL >= texL) and (tileR <= texR) and (tileT <= texT) and (tileB >= texB) then found := true; end; if found then HD.MaterialName := Mat.Name; end; //--------------------------------------------------------------- //HD.MaterialName:=self.FMaterialLibrary.Materials[15].Name; HDS.Release(htfHD); //heightData.DataState:=hdsReady; inherited; end; procedure TVXTexturedHDS.SetHeightDataSource(val:TVXHeightDataSource); begin if val=self then FHeightDataSource:=nil else FHeightDataSource:=val; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ RegisterClasses([TVXTexturedHDS]); end.
unit VXS.OpenGLFMX; { OpenGL for FMX Adapted from https://github.com/LUXOPHIA } interface uses Winapi.Windows, FMX.Forms, VXS.OpenGL; type TVXOpenGL = class private _Form: TCommonCustomForm; _WND: HWND; _DC: HDC; protected _PFD: TPixelFormatDescriptor; _PFI: Integer; _RC: HGLRC; procedure SetPFD(const PFD_: TPixelFormatDescriptor); procedure SetPFI(const PFI_: Integer); procedure CreateWindow; procedure DestroyWindow; procedure ValidatePFD(const PFD_: TPixelFormatDescriptor); procedure ValidatePFI(const PFI_: Integer); procedure CreateDC; procedure DestroyDC; procedure CreateRC; procedure DestroyRC; public constructor Create; destructor Destroy; override; property PFD: TPixelFormatDescriptor read _PFD write SetPFD; property PFI: Integer read _PFI write SetPFI; property RC: HGLRC read _RC; class function DefaultPFD: TPixelFormatDescriptor; procedure BeginGL; procedure EndGL; procedure InitOpenGL; procedure ApplyPixelFormat(const DC_: HDC); end; //----------------------------------------------------------------------- TVXShader = class private protected _ID: GLuint; public constructor Create(const Kind_: GLenum); destructor Destroy; override; property ID: GLuint read _ID; procedure SetSource(const Source_: String); end; //----------------------------------------------------------------------- TVXShaderV = class(TVXShader) private protected public constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------- TVXShaderG = class(TVXShader) private protected public constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------- TVXShaderF = class(TVXShader) private protected public constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------- TVXProgram = class private protected _ID: GLuint; public constructor Create; destructor Destroy; override; procedure Attach(const Shader_: TVXShader); procedure Detach(const Shader_: TVXShader); procedure Link; procedure Use; end; //----------------------------------------------------------------------- TVXBuffer<_TYPE_: record > = class public type _PValue_ = ^_TYPE_; private protected _ID: GLuint; _Kind: GLenum; _Count: Integer; _Head: _PValue_; procedure SetCount(const Count_: Integer); public constructor Create(const Kind_: GLenum); destructor Destroy; override; property ID: GLuint read _ID; property Count: Integer read _Count write SetCount; procedure Bind; procedure Unbind; procedure Map; procedure Unmap; end; //----------------------------------------------------------------------- TVXBufferV<_TYPE_: record > = class(TVXBuffer<_TYPE_>) private protected public constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------- TVXBufferI<_TYPE_: record > = class(TVXBuffer<_TYPE_>) private protected public constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------- TVXBufferU<_TYPE_: record > = class(TVXBuffer<_TYPE_>) private protected public constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------- TVXArray = class private protected _ID: GLuint; public constructor Create; destructor Destroy; override; property ID: GLuint read _ID; procedure BeginBind; procedure EndBind; end; var VXOpenGL: TVXOpenGL; //----------------------------------------------------------------------- implementation //----------------------------------------------------------------------- uses System.SysUtils, FMX.Platform.Win; procedure TVXOpenGL.SetPFD(const PFD_: TPixelFormatDescriptor); begin DestroyRC; DestroyDC; CreateDC; ValidatePFD(PFD_); CreateRC; end; procedure TVXOpenGL.SetPFI(const PFI_: Integer); begin DestroyRC; DestroyDC; CreateDC; ValidatePFI(PFI_); CreateRC; end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.CreateWindow; begin _Form := TCommonCustomForm.Create(nil); _WND := WindowHandleToPlatform(_Form.Handle).Wnd; end; procedure TVXOpenGL.DestroyWindow; begin _Form.Free; end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.ValidatePFD(const PFD_: TPixelFormatDescriptor); var I: Integer; begin _PFD := PFD_; I := ChoosePixelFormat(_DC, @_PFD); Assert(I > 0, 'Not found the PixelFormat with a close setting!'); ValidatePFI(I); end; procedure TVXOpenGL.ValidatePFI(const PFI_: Integer); begin _PFI := PFI_; Assert(DescribePixelFormat(_DC, _PFI, SizeOf(TPixelFormatDescriptor), _PFD), 'Not found the PixelFormat of the index!'); end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.CreateDC; begin _DC := GetDC(_WND); end; procedure TVXOpenGL.DestroyDC; begin ReleaseDC(0, _DC); end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.CreateRC; begin ApplyPixelFormat(_DC); _RC := wglCreateContext(_DC); end; procedure TVXOpenGL.DestroyRC; begin wglDeleteContext(_RC); end; constructor TVXOpenGL.Create; begin inherited; CreateWindow; CreateDC; ValidatePFD(DefaultPFD); CreateRC; InitOpenGL; end; destructor TVXOpenGL.Destroy; begin DestroyRC; DestroyDC; DestroyWindow; inherited; end; // ------------------------------------------------------------------------------ class function TVXOpenGL.DefaultPFD: TPixelFormatDescriptor; begin with Result do begin nSize := SizeOf(TPixelFormatDescriptor); nVersion := 1; dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType := PFD_TYPE_RGBA; cColorBits := 24; cRedBits := 0; cRedShift := 0; cGreenBits := 0; cGreenShift := 0; cBlueBits := 0; cBlueShift := 0; cAlphaBits := 0; cAlphaShift := 0; cAccumBits := 0; cAccumRedBits := 0; cAccumGreenBits := 0; cAccumBlueBits := 0; cAccumAlphaBits := 0; cDepthBits := 32; cStencilBits := 0; cAuxBuffers := 0; iLayerType := PFD_MAIN_PLANE; bReserved := 0; dwLayerMask := 0; dwVisibleMask := 0; dwDamageMask := 0; end; end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.BeginGL; begin wglMakeCurrent(_DC, _RC); end; procedure TVXOpenGL.EndGL; begin wglMakeCurrent(_DC, 0); end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.InitOpenGL; begin BeginGL; glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); EndGL; end; // ------------------------------------------------------------------------------ procedure TVXOpenGL.ApplyPixelFormat(const DC_: HDC); begin Assert(SetPixelFormat(DC_, _PFI, @_PFD), 'SetPixelFormat() is failed!'); end; // ------------------------------------------------------------------------------ constructor TVXShader.Create(const Kind_: GLenum); begin inherited Create; _ID := glCreateShader(Kind_); end; destructor TVXShader.Destroy; begin glDeleteShader(_ID); inherited; end; // ------------------------------------------------------------------------------ procedure TVXShader.SetSource(const Source_: String); var P: PAnsiChar; N: GLint; E: GLint; Cs: array of PGLchar; CsN: GLsizei; begin P := PAnsiChar(AnsiString(Source_)); N := Length(Source_); glShaderSource(_ID, 1, @P, @N); glCompileShader(_ID); glGetShaderiv(_ID, GL_COMPILE_STATUS, @E); if E = GL_FALSE then begin glGetShaderiv(_ID, GL_INFO_LOG_LENGTH, @N); SetLength(Cs, N); glGetShaderInfoLog(_ID, N, @CsN, @Cs[0]); Assert(False, AnsiString(Cs)); end; end; // ------------------------------------------------------------------------------ constructor TVXShaderV.Create; begin inherited Create(GL_VERTEX_SHADER); end; destructor TVXShaderV.Destroy; begin inherited; end; // ------------------------------------------------------------------------------ constructor TVXShaderG.Create; begin inherited Create(GL_GEOMETRY_SHADER); end; destructor TVXShaderG.Destroy; begin inherited; end; // ------------------------------------------------------------------------------ constructor TVXShaderF.Create; begin inherited Create(GL_FRAGMENT_SHADER); end; destructor TVXShaderF.Destroy; begin inherited; end; // ------------------------------------------------------------------------------ constructor TVXProgram.Create; begin inherited; _ID := glCreateProgram; end; destructor TVXProgram.Destroy; begin glDeleteProgram(_ID); inherited; end; // ------------------------------------------------------------------------------ procedure TVXProgram.Attach(const Shader_: TVXShader); begin glAttachShader(_ID, Shader_.ID); end; procedure TVXProgram.Detach(const Shader_: TVXShader); begin glDetachShader(_ID, Shader_.ID); end; // ------------------------------------------------------------------------------ procedure TVXProgram.Link; begin glLinkProgram(_ID); end; // ------------------------------------------------------------------------------ procedure TVXProgram.Use; begin glUseProgram(_ID); end; // ------------------------------------------------------------------------------ procedure TVXBuffer<_TYPE_>.SetCount(const Count_: Integer); begin _Count := Count_; Bind; glBufferData(_Kind, SizeOf(_TYPE_) * _Count, nil, GL_DYNAMIC_DRAW); Unbind; end; // ------------------------------------------------------------------------------ constructor TVXBuffer<_TYPE_>.Create(const Kind_: GLenum); begin inherited Create; glGenBuffers(1, @_ID); _Kind := Kind_; Count := 0; end; // ------------------------------------------------------------------------------ destructor TVXBuffer<_TYPE_>.Destroy; begin glDeleteBuffers(1, @_ID); inherited; end; // ------------------------------------------------------------------------------ procedure TVXBuffer<_TYPE_>.Bind; begin glBindBuffer(_Kind, _ID); end; procedure TVXBuffer<_TYPE_>.Unbind; begin glBindBuffer(_Kind, 0); end; // ------------------------------------------------------------------------------ procedure TVXBuffer<_TYPE_>.Map; begin Bind; _Head := glMapBuffer(_Kind, GL_READ_WRITE); end; procedure TVXBuffer<_TYPE_>.Unmap; begin glUnmapBuffer(_Kind); Unbind; end; constructor TVXBufferV<_TYPE_>.Create; begin inherited Create(GL_ARRAY_BUFFER); end; destructor TVXBufferV<_TYPE_>.Destroy; begin inherited; end; // ------------------------------------------------------------------------------ constructor TVXBufferI<_TYPE_>.Create; begin inherited Create(GL_ELEMENT_ARRAY_BUFFER); end; destructor TVXBufferI<_TYPE_>.Destroy; begin inherited; end; // ------------------------------------------------------------------------------ constructor TVXBufferU<_TYPE_>.Create; begin inherited Create(GL_UNIFORM_BUFFER); end; destructor TVXBufferU<_TYPE_>.Destroy; begin inherited; end; // ------------------------------------------------------------------------------ constructor TVXArray.Create; begin inherited Create; glGenVertexArrays(1, @_ID); end; destructor TVXArray.Destroy; begin glDeleteVertexArrays(1, @_ID); inherited; end; // ------------------------------------------------------------------------------ procedure TVXArray.BeginBind; begin glBindVertexArray(_ID); end; procedure TVXArray.EndBind; begin glBindVertexArray(0); end; //========================================================================== initialization //========================================================================== VXOpenGL := TVXOpenGL.Create; VXOpenGL.BeginGL; ////InitOpenGLext; finalization VXOpenGL.EndGL; VXOpenGL.Free; end.
unit Ils.Json.Utils; interface uses SysUtils, JsonDataObjects, Ils.Json.Names, StrUtils; function GetJsonVersion(AJson: TJsonObject): Integer; function IsCameraMessage(AJson: TJsonObject): Boolean; function IntToBin(Value: integer; Digits: integer): string; function GetAdditionalStat(const AJSONO: TJsonObject; const AType: string): string; function GetBin8_1(const AJSONO: TJsonObject): string; function GetVoltage(const AJSONO: TJsonObject): string; implementation function GetJsonVersion(AJson: TJsonObject): Integer; begin Result := AJson.I['g']; end; function IsCameraMessage(AJson: TJsonObject): Boolean; begin Result := AJson.Path['s.cam:raw'].Typ = jdtString; end; function IntToBin(Value: integer; Digits: integer): string; var i: integer; begin Result := ''; for i := 0 to Digits - 1 do if Value and (1 shl i) > 0 then Result := '1' + Result else Result := '0' + Result; end; function GetAdditionalStat(const AJSONO: TJsonObject; const AType: string): string; var fs: TFormatSettings; begin Result := ''; fs := TFormatSettings.Create; fs.DecimalSeparator := '.'; try Result := IfThen(LowerCase('Device.Geo') = LowerCase(AType), MakeSensorName(stBin8, 1) + '=0b' + IntToBin(AJSONO.O[JF2Str(jfSensors)].I[MakeSensorName(stBin8, 1)], 8) + ';' + JF2Str(jfSatellitesCount) + '=' + FormatFloat('00', AJSONO.I[JF2Str(jfSatellitesCount)]) + ';' + JF2Str(jfSatellitesValid) + '=' + FormatFloat('0', AJSONO.I[JF2Str(jfSatellitesValid)]) + ';' + JF2Str(jfLatitude) + '=' + FormatFloat(' 00.000000;-00.000000', AJSONO.F[JF2Str(jfLatitude)], fs) + ';' + JF2Str(jfLongitude) + '=' + FormatFloat(' 000.000000;-000.000000', AJSONO.F[JF2Str(jfLongitude)], fs) + ';' + JF2Str(jfVelocity) + '=' + FormatFloat('000.00', AJSONO.F[JF2Str(jfVelocity)], fs) + ';' + JF2Str(jfAzimuth) + '=' + FormatFloat(' 000;-000', AJSONO.I[JF2Str(jfAzimuth)]) + ';' + MakeSensorName(stVExt) + '=' + IntToStr(AJSONO.O[JF2Str(jfSensors)].I[MakeSensorName(stVExt)]) + ';' + MakeSensorName(stTemp, 1) + '=' + IntToStr(AJSONO.O[JF2Str(jfSensors)].I[MakeSensorName(stTemp, 1)]) {$ifdef PROTOCOL_NOVACOM} + ';' + 'nova_2' + '=' + IntToStr(AJSONO.O[JF2Str(jfSensors)].I['nova_2:i']) + ';' + 'nova_72' + '=' + IntToStr(AJSONO.O[JF2Str(jfSensors)].I['nova_72:i']) {$endif} , '' ) ; except end; end; function GetBin8_1(const AJSONO: TJsonObject): string; begin Result := ''; try Result := IntToBin(AJSONO.O[JF2Str(jfSensors)].I[MakeSensorName(stBin8, 1)], 8); except end; end; function GetVoltage(const AJSONO: TJsonObject): string; begin Result := MakeSensorName(stBin8, 1) + '=0x' + IntToBin(0, 8); try Result := MakeSensorName(stBin8, 1) + '=0x' + IntToBin(AJSONO.O[JF2Str(jfSensors)].I[MakeSensorName(stBin8, 1)], 8); except end; end; end.
unit uWorker; interface uses Winapi.Windows, Winapi.Messages, System.Classes, System.SysUtils, System.Generics.Defaults, System.Generics.Collections, VCL.Controls, VCL.Forms; const WM_WORKER_STATE_CHANGED = WM_USER + 100; WM_WORKER_FEEDBACK_PROGRESS = WM_USER + 101; WM_WORKER_FEEDBACK_DATA = WM_USER + 102; const WORKERMGR_WORKER_MAX_NUM = 128; type PWorkerDataRec = ^TWorkerDataRec; TWorkerDataRec = record Id: Integer; DataProcessed: TObject; end; TTaskState = ( tsStarted, tsSuspended, tsResumed, tsCompleted ); TTaskResult = ( trCanceled, trSuccessed, trFailed ); TWorker = class; TWorkerTask = function( Worker: TWorker; Param: TObject ): TTaskResult of object; TTaskStateChanged = procedure( Sender: TWorker; WorkerState: TTaskState ) of object; TTaskProgressChangedEvent = procedure( Sender: TWorker; ProgressChanged: Integer ) of object; TTaskDataProcessedEvent = procedure( Sender: TWorker; Id: Integer; DataProcessed: TObject ) of object; TWorkerMgr = class; TWorker = class( TThread ) FName: string; FTag: Integer; FOwner: TWorkerMgr; FExecuting: LongBool; FAllocedForTask: LongBool; FFreeOnTaskComplete: LongBool; FFThreadTerminateEvent: THandle; FTaskStartEvent: THandle; FTaskResumeEvent: THandle; FTaskCompletedEvent: THandle; FTaskProc: TWorkerTask; FTaskParam: TObject; FTaskResult: TTaskResult; FTaskRunning: LongBool; FTaskSuspended: LongBool; FTaskCanceling: LongBool; FTaskSuspending: LongBool; FOnTaskStateChanged: TTaskStateChanged; FOnTaskDataProcessed: TTaskDataProcessedEvent; FOnTaskProgressChanged: TTaskProgressChangedEvent; procedure AfterConstruction; override; protected procedure Execute; override; procedure DoDataProcessed( WorkerDataRec: PWorkerDataRec ); procedure DoProgressChanged( ProgressChanged: Integer ); procedure DoStateChanged( CurrentState: TTaskState ); public constructor Create( Owner: TWorkerMgr; Name: string = 'Worker'; Tag: Integer = 0 ); destructor Destroy; override; procedure QueryTaskSuspendPending; function IsTaskCancelPending: LongBool; procedure TaskProgressChanged( Perent: Integer ); procedure TaskDataProcessed( DataProcessed: TObject; Id: Integer = 0 ); procedure TaskStart( TaskProc: TWorkerTask; TaskParam: TObject ); overload; procedure TaskStart( ); overload; procedure TaskSuspend( ); procedure TaskResume( ); procedure TaskCancel( ); property Tag: Integer read FTag write FTag default 0; property FreeOnTaskComplete: LongBool read FFreeOnTaskComplete write FFreeOnTaskComplete; property TaskRunning: LongBool read FTaskRunning; property TaskProc: TWorkerTask write FTaskProc; property TaskParam: TObject write FTaskParam; property TaskResult: TTaskResult read FTaskResult; property OnTaskStateChanged: TTaskStateChanged read FOnTaskStateChanged write FOnTaskStateChanged; property OnTaskDataProcessed: TTaskDataProcessedEvent read FOnTaskDataProcessed write FOnTaskDataProcessed; property OnTaskProgressChanged: TTaskProgressChangedEvent read FOnTaskProgressChanged write FOnTaskProgressChanged; end; EWorkerMgr = class( Exception ); TWorkerMgr = class( TThread ) private FName: string; FCreated: Boolean; FThreadWindow: HWND; FProcessWindow: HWND; FReadyEvent: THandle; FException: Exception; FWorkerList: TThreadList< TWorker >; procedure TerminatedSet; override; procedure AfterConstruction; override; procedure BeforeDestruction; override; function PostThreadMessage( Msg, WParam, LParam: NativeUInt ): LongBool; function SendThreadMessage( Msg, WParam, LParam: NativeUInt ): NativeInt; function PostProcessMessage( Msg, WParam, LParam: NativeUInt ): LongBool; function SendProcessMessage( Msg, WParam, LParam: NativeUInt ): NativeInt; procedure CreateThreadWindow; procedure DeleteThreadWindow; procedure ThreadWndMethod( var Msg: TMessage ); procedure CreateProcessWindow; procedure DeleteProcessWindow; procedure ProcessWndMethod( var Msg: TMessage ); procedure HandleException; procedure HandleExceptionProcesshronized; procedure Execute; override; procedure Idle; public constructor Create( Name: string = 'WorkerMgr' ); destructor Destroy; override; function AllocWorker( Name: string = 'Worker'; Tag: Integer = 0 ): TWorker; procedure FreeWorker( Worker: TWorker ); end; const WorkerResultText: array [ trCanceled .. trFailed ] of string = ( 'Canceled', 'Successed', 'Failed' ); var WorkerMgr: TWorkerMgr; implementation { TWorker } const WM_TERMINATE_WORKER_MGR = WM_APP; procedure TWorker.TaskDataProcessed( DataProcessed: TObject; Id: Integer ); var WorkerDataRec: PWorkerDataRec; begin if Assigned( FOnTaskDataProcessed ) then begin New( WorkerDataRec ); WorkerDataRec.Id := Id; WorkerDataRec.DataProcessed := DataProcessed; FOwner.SendProcessMessage( WM_WORKER_FEEDBACK_DATA, NativeUInt( Self ), NativeUInt( WorkerDataRec ) ); Dispose( WorkerDataRec ); end; end; procedure TWorker.TaskProgressChanged( Perent: Integer ); begin if Assigned( FOnTaskProgressChanged ) then FOwner.SendProcessMessage( WM_WORKER_FEEDBACK_PROGRESS, NativeUInt( Self ), NativeUInt( Perent ) ) end; procedure TWorker.TaskStart; begin while not FExecuting do // Wait until Thread is executing Yield; SetEvent( Self.FTaskStartEvent ); // StartTask Task end; procedure TWorker.TaskSuspend; begin if not FTaskRunning then Exit; if not FTaskSuspended then FTaskSuspending := True; end; procedure TWorker.TaskResume; begin if not FTaskRunning then Exit; if FTaskSuspended then SetEvent( FTaskResumeEvent ); end; procedure TWorker.TaskCancel; var Wait: DWORD; begin if not FTaskRunning then Exit; TaskResume( ); // ResumeTask if Task has been suspended FTaskCompletedEvent := CreateEvent( nil, True, FALSE, '' ); // Let Task know it need be canceled FTaskCanceling := True; while True do begin // Wait until Task Exit Wait := MsgWaitForMultipleObjects( 1, FTaskCompletedEvent, FALSE, INFINITE, QS_ALLINPUT ); if Wait = WAIT_OBJECT_0 then begin ResetEvent( FTaskCompletedEvent ); CloseHandle( FTaskCompletedEvent ); Exit; end; Application.ProcessMessages( ); end; end; { Yield() : SwitchToThread () Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the next thread to be executed. } procedure TWorker.TaskStart( TaskProc: TWorkerTask; TaskParam: TObject ); begin Self.FTaskProc := TaskProc; Self.FTaskParam := TaskParam; while not FExecuting do // Wait until Thread is executing Yield; SetEvent( Self.FTaskStartEvent ); // StartTask Task end; constructor TWorker.Create( Owner: TWorkerMgr; Name: string; Tag: Integer ); begin FName := name; FTag := Tag; FOwner := Owner; inherited Create( FALSE ); end; procedure TWorker.AfterConstruction; begin inherited AfterConstruction; // ResumeThread while not FExecuting do // Wait for thread execute Yield; // SuspendTask Caller's Thread, to start Worker's Thread end; procedure TWorker.Execute; var Wait: DWORD; FEvents: array [ 0 .. 1 ] of THandle; begin NameThreadForDebugging( FName ); FFThreadTerminateEvent := CreateEvent( nil, True, FALSE, '' ); FTaskStartEvent := CreateEvent( nil, True, FALSE, '' ); FEvents[ 0 ] := FFThreadTerminateEvent; FEvents[ 1 ] := FTaskStartEvent; FTaskRunning := FALSE; FExecuting := True; try while not Terminated do begin Wait := WaitForMultipleObjects( 2, @FEvents, FALSE, INFINITE ); // If more than one object became signaled during the call, // this is the array index of the signaled object // with the smallest index value of all the signaled objects. case Wait of WAIT_OBJECT_0 .. WAIT_OBJECT_0 + 1: if WAIT_OBJECT_0 = Wait then begin ResetEvent( FFThreadTerminateEvent ); Exit; // Terminate Thread end else begin ResetEvent( FTaskStartEvent ); FTaskRunning := True; FTaskCanceling := FALSE; FTaskSuspending := FALSE; if Assigned( FOnTaskStateChanged ) then FOwner.PostProcessMessage( WM_WORKER_STATE_CHANGED, NativeUInt( Self ), NativeUInt( tsStarted ) ); FTaskResult := FTaskProc( Self, FTaskParam ); FOwner.SendProcessMessage( WM_WORKER_STATE_CHANGED, NativeUInt( Self ), NativeUInt( tsCompleted ) ); if FTaskCompletedEvent <> 0 then SetEvent( FTaskCompletedEvent ); FTaskRunning := FALSE; end; WAIT_ABANDONED_0 .. WAIT_ABANDONED_0 + 1: begin // mutex object abandoned end; WAIT_FAILED: begin if GetLastError <> ERROR_INVALID_HANDLE then begin // the wait failed because of something other than an invalid handle RaiseLastOSError; end else begin // at least one handle has become invalid outside the wait call end; end; WAIT_TIMEOUT: begin // Never because dwMilliseconds is INFINITE end; else begin end; end; end; finally if FFThreadTerminateEvent <> 0 then CloseHandle( FFThreadTerminateEvent ); if FTaskStartEvent <> 0 then CloseHandle( FTaskStartEvent ); FExecuting := FALSE; end; end; procedure TWorker.QueryTaskSuspendPending; begin if not FTaskSuspending then Exit; FTaskSuspending := FALSE; if Assigned( FOnTaskStateChanged ) then FOwner.PostProcessMessage( WM_WORKER_STATE_CHANGED, NativeUInt( Self ), NativeUInt( tsSuspended ) ); FTaskSuspended := True; FTaskResumeEvent := CreateEvent( nil, True, FALSE, '' ); // SuspendTask Task until ResumeTask or CancelTask by Main Thred WaitForSingleObject( FTaskResumeEvent, INFINITE ); // ResumeTask Task ResetEvent( FTaskResumeEvent ); CloseHandle( FTaskResumeEvent ); if Assigned( FOnTaskStateChanged ) then FOwner.PostProcessMessage( WM_WORKER_STATE_CHANGED, NativeUInt( Self ), NativeUInt( tsResumed ) ); FTaskSuspended := FALSE; end; function TWorker.IsTaskCancelPending: LongBool; begin QueryTaskSuspendPending( ); if FTaskCanceling then Exit( True ) else Exit( FALSE ); end; destructor TWorker.Destroy; begin if FExecuting then begin if not FTaskRunning then // Wait for TaskStartEvent or FThreadTerminateEvent begin SetEvent( FFThreadTerminateEvent ); end else begin TaskCancel; end; end; inherited Destroy; end; procedure TWorker.DoDataProcessed( WorkerDataRec: PWorkerDataRec ); begin if Assigned( FOnTaskDataProcessed ) then begin FOnTaskDataProcessed( Self, WorkerDataRec.Id, WorkerDataRec.DataProcessed ); end; end; procedure TWorker.DoProgressChanged( ProgressChanged: Integer ); begin if Assigned( FOnTaskProgressChanged ) then FOnTaskProgressChanged( Self, ProgressChanged ); end; procedure TWorker.DoStateChanged( CurrentState: TTaskState ); begin if Assigned( FOnTaskStateChanged ) then FOnTaskStateChanged( Self, CurrentState ); if CurrentState = tsCompleted then begin if Self.FFreeOnTaskComplete then FOwner.FreeWorker( Self ); end; end; { TWorkerMgr } procedure DeallocateHWnd( Wnd: HWND ); var Instance: Pointer; begin Instance := Pointer( GetWindowLong( Wnd, GWL_WNDPROC ) ); if Instance <> @DefWindowProc then begin { make sure we restore the default windows procedure before freeing memory } SetWindowLong( Wnd, GWL_WNDPROC, Longint( @DefWindowProc ) ); FreeObjectInstance( Instance ); end; DestroyWindow( Wnd ); end; procedure TWorkerMgr.CreateProcessWindow; begin FProcessWindow := AllocateHWnd( ProcessWndMethod ); end; procedure TWorkerMgr.CreateThreadWindow; begin FThreadWindow := AllocateHWnd( ThreadWndMethod ); end; function TWorkerMgr.AllocWorker( Name: string; Tag: Integer ): TWorker; var I: Integer; UnallocedWorkerFound: LongBool; begin UnallocedWorkerFound := FALSE; for I := 0 to FWorkerList.LockList.Count - 1 do begin Result := FWorkerList.LockList[ I ]; if not Result.FAllocedForTask then begin UnallocedWorkerFound := True; Break; end; end; if not UnallocedWorkerFound then begin if FWorkerList.LockList.Count = WORKERMGR_WORKER_MAX_NUM then raise EWorkerMgr.Create( 'Can not create worker thread.' ); Result := TWorker.Create( Self, name ); FWorkerList.Add( Result ); end; Result.FName := name; Result.FFreeOnTaskComplete := True; Result.FAllocedForTask := True; Result.Tag := Tag; Result.OnTaskStateChanged := nil; Result.OnTaskProgressChanged := nil; Result.OnTaskDataProcessed := nil; end; procedure TWorkerMgr.FreeWorker( Worker: TWorker ); var I: Integer; begin for I := 0 to FWorkerList.LockList.Count - 1 do begin if Worker = FWorkerList.LockList[ I ] then begin Worker.FAllocedForTask := FALSE; Worker := nil; Exit; end; end; end; procedure TWorkerMgr.HandleExceptionProcesshronized; begin if FException is Exception then Application.ShowException( FException ) else System.SysUtils.ShowException( FException, nil ); end; procedure TWorkerMgr.ThreadWndMethod( var Msg: TMessage ); var Handled: Boolean; Worker: TWorker; begin Handled := True; // Assume we handle message Worker := TWorker( Msg.WParam ); case Msg.Msg of WM_TERMINATE_WORKER_MGR: begin PostQuitMessage( 0 ); end; else Handled := FALSE; // We didn't handle message end; if Handled then // We handled message - record in message result Msg.Result := 0 else // We didn't handle message, pass to DefWindowProc and record result Msg.Result := DefWindowProc( FProcessWindow, Msg.Msg, Msg.WParam, Msg.LParam ); end; procedure TWorkerMgr.AfterConstruction; begin inherited AfterConstruction; WaitForSingleObject( FReadyEvent, INFINITE ); CloseHandle( FReadyEvent ); if not FCreated then raise EWorkerMgr.Create( 'Can not create worker manager thread.' ); FWorkerList := TThreadList< TWorker >.Create; end; procedure TWorkerMgr.BeforeDestruction; begin if Assigned( FWorkerList ) then begin while FWorkerList.LockList.Count > 0 do begin FreeWorker( FWorkerList.LockList[ 0 ] ); FWorkerList.LockList[ 0 ].Destroy; FWorkerList.Remove( FWorkerList.LockList[ 0 ] ); end; FWorkerList.Free; end; inherited BeforeDestruction; end; constructor TWorkerMgr.Create( Name: string ); begin FName := name; FReadyEvent := CreateEvent( nil, True, FALSE, '' ); inherited Create( FALSE ); { Create hidden window here: store handle in FProcessWindow this must by synchonized because of ProcessThread Context } Synchronize( CreateProcessWindow ); end; procedure TWorkerMgr.TerminatedSet; begin // Exit Message Loop PostThreadMessage( WM_TERMINATE_WORKER_MGR, 0, 0 ); end; procedure TWorkerMgr.DeleteProcessWindow; begin if FProcessWindow <> 0 then begin DeallocateHWnd( FProcessWindow ); FProcessWindow := 0; end; end; procedure TWorkerMgr.DeleteThreadWindow; begin if FThreadWindow > 0 then begin DeallocateHWnd( FThreadWindow ); FThreadWindow := 0; end; end; destructor TWorkerMgr.Destroy; begin Terminate; // FTerminated := True; inherited Destroy; // WaitFor(), Destroy() { Destroy hidden window } DeleteProcessWindow( ); end; procedure TWorkerMgr.Idle; begin end; { Run in WorkerMgr Thread } procedure TWorkerMgr.Execute; var Msg: TMsg; begin NameThreadForDebugging( FName ); FException := nil; try // Force system alloc a Message Queue for thread // PeekMessage( Msg, 0, WM_USER, WM_USER, PM_NOREMOVE ); CreateThreadWindow( ); SetEvent( FReadyEvent ); if FThreadWindow = 0 then raise EWorkerMgr.Create( 'Can not create worker manager window.' ); FCreated := True; try while not Terminated do begin if FALSE then begin if Longint( PeekMessage( Msg, 0, 0, 0, PM_REMOVE ) ) > 0 then begin // WM_QUIT Message sent by Destroy() if Msg.message = WM_QUIT then Exit; TranslateMessage( Msg ); DispatchMessage( Msg ); end else begin Idle; end; end else begin while Longint( GetMessage( Msg, 0, 0, 0 ) ) > 0 do begin TranslateMessage( Msg ); DispatchMessage( Msg ); end; // WM_QUIT Message sent by Destroy() end; end; finally DeleteThreadWindow( ); end; except HandleException; end; end; procedure TWorkerMgr.HandleException; begin FException := Exception( ExceptObject ); try if FException is EAbort then // Don't show EAbort messages Exit; // Now actually show the exception in Appliction Context Synchronize( HandleExceptionProcesshronized ); finally FException := nil; end; end; { SendMessage() Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message. To send a message and return immediately, use the SendMessageCallback() or SendNotifyMessage() function. To post a message to a thread's message queue and return immediately, use the PostMessage() or PostThreadMessage() function. SendNotifyMessage() Sends the specified message to a window or windows. If the window was created by the calling thread, SendNotifyMessage calls the window procedure for the window and does not return until the window procedure has processed the message. If the window was created by a different thread, SendNotifyMessage passes the message to the window procedure and returns immediately; it does not wait for the window procedure to finish processing the message. PostMessage() Places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message. To post a message in the message queue associated with a thread, use the PostThreadMessage() function. PostThreadMessage() Posts a message to the message queue of the specified thread. It returns without waiting for the thread to process the message. } function TWorkerMgr.PostThreadMessage( Msg, WParam, LParam: NativeUInt ): LongBool; begin while FThreadWindow = 0 do SwitchToThread; Result := Winapi.Windows.PostMessage( FThreadWindow, Msg, WParam, LParam ); end; function TWorkerMgr.SendThreadMessage( Msg, WParam, LParam: NativeUInt ): NativeInt; begin while FThreadWindow = 0 do SwitchToThread; Result := Winapi.Windows.SendMessage( FThreadWindow, Msg, WParam, LParam ); end; function TWorkerMgr.PostProcessMessage( Msg, WParam, LParam: NativeUInt ): LongBool; begin Result := Winapi.Windows.PostMessage( FProcessWindow, Msg, WParam, LParam ); end; { Run in Worker Thread } function TWorkerMgr.SendProcessMessage( Msg, WParam, LParam: NativeUInt ): NativeInt; begin Result := Winapi.Windows.SendMessage( FProcessWindow, Msg, WParam, LParam ); end; { Run in Main Thread } procedure TWorkerMgr.ProcessWndMethod( var Msg: TMessage ); var Handled: Boolean; Worker: TWorker; begin Handled := True; // Assume we handle message Worker := TWorker( Msg.WParam ); case Msg.Msg of WM_WORKER_FEEDBACK_PROGRESS: begin Worker.DoProgressChanged( Integer( Msg.LParam ) ); end; WM_WORKER_FEEDBACK_DATA: begin Worker.DoDataProcessed( PWorkerDataRec( Msg.LParam ) ); end; WM_WORKER_STATE_CHANGED: begin Worker.DoStateChanged( TTaskState( Msg.LParam ) ); end; else Handled := FALSE; // We didn't handle message end; if Handled then // We handled message - record in message result Msg.Result := 0 else // We didn't handle message, pass to DefWindowProc and record result Msg.Result := DefWindowProc( FProcessWindow, Msg.Msg, Msg.WParam, Msg.LParam ); end; initialization WorkerMgr := TWorkerMgr.Create( ); finalization WorkerMgr.Free; end.
unit FJX; interface //######################################################################################## ■ uses System.Types, System.Math.Vectors, System.UITypes, FMX.Controls3D, FMX.Graphics; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TArray2<TValue_> = array of TArray<TValue_>; TArray3<TValue_> = array of TArray2<TValue_>; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HBitmapData HBitmapData = record helper for TBitmapData private ///// アクセス function GetColor( const X_,Y_:Integer ) :TAlphaColor; inline; procedure SetColor( const X_,Y_:Integer; const Color_:TAlphaColor ); inline; public ///// プロパティ property Color[ const X_,Y_:Integer ] :TAlphaColor read GetColor write SetColor; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRay3D TRay3D = record private public Pos :TVector3D; Vec :TVector3D; ///// constructor Create( const Pos_,Vec_:TVector3D ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HControl3D HControl3D = class Helper for TControl3D private ///// アクセス function Get_SizeX :Single; inline; procedure Set_SizeX( const _SizeX_:Single ); inline; function Get_SizeY :Single; inline; procedure Set_SizeY( const _SizeY_:Single ); inline; function Get_SizeZ :Single; inline; procedure Set_SizeZ( const _SizeZ_:Single ); inline; protected property _SizeX :Single read Get_SizeX write Set_SizeX; property _SizeY :Single read Get_SizeY write Set_SizeY; property _SizeZ :Single read Get_SizeZ write Set_SizeZ; ///// アクセス function GetAbsolMatrix :TMatrix3D; inline; procedure SetAbsolMatrix( const AbsoluteMatrix_:TMatrix3D ); virtual; function GetLocalMatrix :TMatrix3D; virtual; procedure SetLocalMatrix( const LocalMatrix_:TMatrix3D ); virtual; ///// メソッド procedure RecalcChildrenAbsolute; procedure RenderTree; inline; public ///// プロパティ property AbsolMatrix :TMatrix3D read GetAbsolMatrix write SetAbsolMatrix; property LocalMatrix :TMatrix3D read GetLocalMatrix write SetLocalMatrix; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TProxyObject TProxyObject = class( FMX.Controls3D.TProxyObject ) private protected ///// メソッド procedure Render; override; public end; const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 Pi2 = 2 * Pi; Pi3 = 3 * Pi; Pi4 = 4 * Pi; P2i = Pi / 2; P3i = Pi / 3; P4i = Pi / 4; //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 function Pow2( const X_:Single ) :Single; inline; overload; function Pow2( const X_:Double ) :Double; inline; overload; function Roo2( const X_:Single ) :Single; inline; overload; function Roo2( const X_:Double ) :Double; inline; overload; function LimitRange( const O_,Min_,Max_:Single ) :Single; overload; function LimitRange( const O_,Min_,Max_:Double ) :Double; overload; implementation //################################################################################### ■ uses FMX.Types; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HBitmapData //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private function HBitmapData.GetColor( const X_,Y_:Integer ) :TAlphaColor; begin Result := GetPixel( X_, Y_ ); end; procedure HBitmapData.SetColor( const X_,Y_:Integer; const Color_:TAlphaColor ); begin SetPixel( X_, Y_, Color_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRay3D //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TRay3D.Create( const Pos_,Vec_:TVector3D ); begin Pos := Pos_; Vec := Vec_; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HControl3D //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////////////////////////// アクセス function HControl3D.Get_SizeX :Single; begin Result := FWidth; end; procedure HControl3D.Set_SizeX( const _SizeX_:Single ); begin FWidth := _SizeX_; end; function HControl3D.Get_SizeY :Single; begin Result := FHeight; end; procedure HControl3D.Set_SizeY( const _SizeY_:Single ); begin FHeight := _SizeY_; end; function HControl3D.Get_SizeZ :Single; begin Result := FDepth; end; procedure HControl3D.Set_SizeZ( const _SizeZ_:Single ); begin FDepth := _SizeZ_; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////////////////////////// アクセス function HControl3D.GetAbsolMatrix :TMatrix3D; begin Result := AbsoluteMatrix; end; procedure HControl3D.SetAbsolMatrix( const AbsoluteMatrix_:TMatrix3D ); begin FAbsoluteMatrix := AbsoluteMatrix_; FRecalcAbsolute := False; RecalcChildrenAbsolute; end; function HControl3D.GetLocalMatrix :TMatrix3D; begin Result := FLocalMatrix; end; procedure HControl3D.SetLocalMatrix( const LocalMatrix_:TMatrix3D ); begin FLocalMatrix := LocalMatrix_; RecalcAbsolute; end; /////////////////////////////////////////////////////////////////////////////////////////// メソッド procedure HControl3D.RecalcChildrenAbsolute; var F :TFmxObject; begin if Assigned( Children ) then begin for F in Children do begin if F is TControl3D then TControl3D( F ).RecalcAbsolute; end; end; end; procedure HControl3D.RenderTree; begin RenderInternal; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TProxyObject //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////////////////////////// メソッド procedure TProxyObject.Render; var M :TMatrix3D; SX, SY, SZ :Single; begin if Assigned( SourceObject ) then begin with SourceObject do begin M := AbsoluteMatrix; SX := _SizeX; SY := _SizeY; SZ := _SizeZ; AbsolMatrix := Self.AbsoluteMatrix; _SizeX := Self._SizeX; _SizeY := Self._SizeY; _SizeZ := Self._SizeZ; RenderTree; AbsolMatrix := M; _SizeX := SX; _SizeY := SY; _SizeZ := SZ; end; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 function Pow2( const X_:Single ) :Single; begin Result := Sqr( X_ ); end; function Pow2( const X_:Double ) :Double; begin Result := Sqr( X_ ); end; //////////////////////////////////////////////////////////////////////////////////////////////////// function Roo2( const X_:Single ) :Single; begin Result := Sqrt( X_ ); end; function Roo2( const X_:Double ) :Double; begin Result := Sqrt( X_ ); end; //////////////////////////////////////////////////////////////////////////////////////////////////// function LimitRange( const O_,Min_,Max_:Single ) :Single; begin if O_ < Min_ then Result := Min_ else if O_ > Max_ then Result := Max_ else Result := O_; end; function LimitRange( const O_,Min_,Max_:Double ) :Double; begin if O_ < Min_ then Result := Min_ else if O_ > Max_ then Result := Max_ else Result := O_; end; //################################################################################################## □ initialization //############################################################################ 初期化 Randomize; finalization //############################################################################## 最終化 end. //############################################################################################# ■
(* Category: SWAG Title: INPUT AND FIELD ENTRY ROUTINES Original name: 0008.PAS Description: Masked Input Author: BERNIE PALLEK Date: 01-27-94 12:13 *) { > The text on the screen would be something like: > What is your phone number? ( ) - > ^^^ ^^^ ^^^^ > But text could only be entered at the marked locations. As soon as one > section is full it would move to the one beside it but read in a different > variable.. How about this: (it's tested, BTW) } USES Crt; VAR ts : String; PROCEDURE MaskedReadLn(VAR s : String; mask : String; fillCh : Char); { in 'mask', chars with A will only accept alpha input, and chars with 0 will only accept numeric input; spaces accept anything } VAR ch : Char; sx, ox, oy : Byte; BEGIN s := ''; ox := WhereX; oy := WhereY; sx := 0; REPEAT Inc(sx); IF (mask[sx] IN ['0', 'A']) THEN Write(fillCh) ELSE IF (mask[sx] = '_') THEN Write(' ') ELSE Write(mask[sx]); UNTIL (sx = Length(mask)); sx := 0; WHILE (NOT (mask[sx + 1] IN [#32, '0', 'A'])) AND (sx < Length(mask)) DO BEGIN Inc(sx); s := s + mask[sx]; END; GotoXY(ox + sx, oy); REPEAT ch := ReadKey; IF (ch = #8) THEN BEGIN IF (Length(s) > sx) THEN BEGIN IF NOT (mask[Length(s)] IN [#32, '0', 'A']) THEN BEGIN REPEAT s[0] := Chr(Length(s) - 1); GotoXY(WhereX - 1, WhereY); UNTIL (Length(s) <= sx) OR (mask[Length(s)] IN [#32, '0', 'A']); END; s[0] := Chr(Length(s) - 1); GotoXY(WhereX - 1, WhereY); Write(fillCh); GotoXY(WhereX - 1, WhereY); END ELSE BEGIN Sound(440); Delay(50); NoSound; END; END ELSE IF (Length(s) < Length(mask)) THEN BEGIN CASE mask[Length(s) + 1] OF '0' : IF (ch IN ['0'..'9']) THEN BEGIN Write(ch); s := s + ch; END; 'A' : IF (UpCase(ch) IN ['A'..'Z']) THEN BEGIN Write(ch); s := s + ch; END; #32 : BEGIN Write(ch); s := s + ch; END; END; WHILE (Length(s) < Length(mask)) AND (NOT (mask[Length(s) + 1] IN [#32, '0', 'A'])) DO BEGIN IF (mask[Length(s) + 1] = '_') THEN s := s + ' ' ELSE s := s + mask[Length(s) + 1]; GotoXY(WhereX + 1, WhereY); END; END; UNTIL (ch IN [#13, #27]); END; BEGIN ClrScr; Write('Enter phone number: '); MaskedReadLn(ts, '(000)_000-0000', '_'); WriteLn; Write('Enter postal code: '); MaskedReadLn(ts, 'A0A_0A0', '_'); WriteLn; END. { It can be improved with colours and such stuff, but it may suit your needs without enhancement. If you have questions about how this works, feel free to ask. }
unit ThCanvasController; interface uses ThTypes, ThClasses, ThItem, ThCanvas, ThCanvasEditor, System.Types; type TThCanvasController = class(TThInterfacedObject, IThObserver, IThCanvasController) private procedure CanvasZoom(Sender: TObject); protected FCanvas: TThCanvasEditor; FSubject: IThSubject; public constructor Create(ThCanvas: IThCanvas); reintroduce; virtual; destructor Destroy; override; procedure Notifycation(ACommand: IThCommand); procedure SetSubject(ASubject: IThSubject); end; TThCanvasEditorController = class(TThCanvasController) private procedure ItemAdded(Item: TThItem); procedure ItemDelete(Items: TThItems); procedure ItemMove(Items: TThItems; Distance: TPointF); procedure ItemResize(Item: TThItem; BeforeRect: TRectF); public constructor Create(ThCanvas: IThCanvas); override; end; implementation uses ThCanvasCommand, ThItemCommand; { TThCanvasController } procedure TThCanvasController.CanvasZoom(Sender: TObject); begin FSubject.Subject(Self, TThCommandCanvasZoom.Create); end; constructor TThCanvasController.Create(ThCanvas: IThCanvas); begin FCanvas := TThCanvasEditor(ThCanvas); FCanvas.OnZoom := CanvasZoom; end; destructor TThCanvasController.Destroy; begin FSubject.UnregistObserver(Self); inherited; end; procedure TThCanvasController.Notifycation(ACommand: IThCommand); begin // FCanvas.DoGrouping(ACommand.; end; procedure TThCanvasController.SetSubject(ASubject: IThSubject); begin FSubject := ASubject; ASubject.RegistObserver(Self); end; { TThCanvasController } constructor TThCanvasEditorController.Create(ThCanvas: IThCanvas); begin inherited; FCanvas.OnItemAdded := ItemAdded; FCanvas.OnItemDelete := ItemDelete; FCanvas.OnItemMove := ItemMove; FCanvas.OnItemResize := ItemResize; end; procedure TThCanvasEditorController.ItemAdded(Item: TThItem); begin FSubject.Subject(Self, TThCommandItemAdd.Create(FCanvas, Item)); end; procedure TThCanvasEditorController.ItemDelete(Items: TThItems); begin FSubject.Subject(Self, TThCommandItemDelete.Create(FCanvas, Items)); end; procedure TThCanvasEditorController.ItemMove(Items: TThItems; Distance: TPointF); begin FSubject.Subject(Self, TThCommandItemMove.Create(Items, Distance)); end; procedure TThCanvasEditorController.ItemResize(Item: TThItem; BeforeRect: TRectF); begin FSubject.Subject(Self, TThCommandItemResize.Create(Item, BeforeRect)); end; end.
(** This module contains a form class to displays a GIT error message and ask the user what to do. @Author David Hoyle @Version 1.0 @Date 22 Feb 2018 **) Unit JVTGGitErrorForm; Interface Uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons; Type (** A form class t0 display a GIT error message. **) TfrmGITError = Class(TForm) mmoMessage: TMemo; btnIgnore: TBitBtn; btnAbort: TBitBtn; Strict Private Strict Protected Public Class Function Execute(Const strMsg : String) : TModalResult; End; Implementation {$R *.dfm} (** This method displays the dialogue and shows the message. @precon None. @postcon The message is displayed. @param strMsg as a String as a constant @return a TModalResult **) Class Function TfrmGITError.Execute(Const strMsg: String): TModalResult; Var F : TfrmGITError; Begin F := TfrmGITError.Create(Application.MainForm); Try F.mmoMessage.Lines.Text := strMsg; Result := F.ShowModal; Finally F.Free; End; End; End.
function DetectaDrv(const drive : char): boolean; {Detecta quantas unidade possui no computador} var Letra: string; begin Letra := drive + ':\'; if GetDriveType(PChar(Letra)) < 2 then begin result := False; end else begin result := True; end; end;
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright � 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Packaging.Writer; interface uses Spring.Container, Spring.Collections, VSoft.AntPatterns, VSoft.CancellationToken, DPM.Core.Types, DPM.Core.Logging, DPM.Core.Options.Pack, DPM.Core.Spec.Interfaces, DPM.Core.Packaging, DPM.Core.Packaging.Archive; type TPackageWriter = class(TInterfacedObject, IPackageWriter) private FLogger : ILogger; FArchiveWriter : IPackageArchiveWriter; FSpecReader : IPackageSpecReader; procedure ProcessPattern(const basePath, dest : string; const pattern : IFileSystemPattern; const flatten : boolean; const excludePatterns : IList<string> ; const ignore : boolean; var fileCount : integer); protected function WritePackage(const outputFolder : string; const targetPlatform : ISpecTargetPlatform; const spec : IPackageSpec; const version : TPackageVersion; const basePath : string) : boolean; //Generate zip file and xml metadata file. function WritePackageFromSpec(const cancellationToken : ICancellationToken; const options : TPackOptions) : boolean; public constructor Create(const logger : ILogger; const archiveWriter : IPackageArchiveWriter; const specReader : IPackageSpecReader); end; implementation uses System.SysUtils, System.Types, System.IOUtils, System.Classes, System.Masks, DPM.Core.Constants, DPM.Core.Spec, DPM.Core.Utils.Strings, DPM.Core.Utils.Path; { TPackageWriter } constructor TPackageWriter.Create(const logger : ILogger; const archiveWriter : IPackageArchiveWriter; const specReader : IPackageSpecReader); begin FLogger := logger; FArchiveWriter := archiveWriter; FSpecReader := specReader; end; function StripCurrent(const value : string) : string; begin result := value; if TStringUtils.StartsWith(result, '.\') then Delete(result, 1, 2); end; function GetNonWildcardPath(const value : string) : string; var i : integer; begin result := ''; i := Pos('*', value); if i > 0 then result := Copy(value, 1, i - 1); end; procedure TPackageWriter.ProcessPattern(const basePath : string; const dest : string; const pattern : IFileSystemPattern; const flatten : boolean; const excludePatterns : IList<string> ; const ignore : boolean; var fileCount : integer); var files : TStringDynArray; f : string; archivePath : string; function IsFileExcluded(const fileName : string) : boolean; var excludePatten : string; begin result := false; if excludePatterns.Count > 0 then begin for excludePatten in excludePatterns do begin //this might be slow.. Creates/Destroys TMask each time //if it is then create a record based mask type to do the job. if MatchesMask(fileName, excludePatten) then exit(true); end; end; end; begin if not TDirectory.Exists(pattern.Directory) then if ignore then exit else raise Exception.Create('Directory not found : ' + pattern.Directory); f := TPath.Combine(pattern.Directory, pattern.FileMask); //TODO : What whas this meant to do??? files := TDirectory.GetFiles(pattern.Directory, pattern.FileMask, TSearchOption.soTopDirectoryOnly); for f in files do begin if IsFileExcluded(f) then continue; if not TFile.Exists(f) then raise Exception.Create('File not found : ' + f); if flatten then archivePath := dest + '\' + ExtractFileName(f) else archivePath := dest + '\' + TPathUtils.StripBase(basePath, f); if TStringUtils.StartsWith(archivePath, '\') then Delete(archivePath, 1, 1); Inc(fileCount); // FLogger.Debug('Writing file [' + archivePath + '] to package.'); FArchiveWriter.AddFile(f, archivePath); end; end; function TPackageWriter.WritePackage(const outputFolder : string; const targetPlatform : ISpecTargetPlatform; const spec : IPackageSpec; const version : TPackageVersion; const basePath : string) : boolean; var sManifest : string; packageFileName : string; sStream : TStringStream; antPattern : IAntPattern; fileEntry : ISpecFileEntry; procedure ValidateDestinationPath(const source, dest : string); begin if (pos(#10, dest) > 0) or (pos(#13, dest) > 0) then raise Exception.Create('Entry [' + source + '] has invalid characters in destination [' + dest + ']'); end; procedure ProcessEntry(const source, dest : string; const flatten : boolean; const exclude : IList<string> ; const ignore : boolean); var fsPatterns : TArray<IFileSystemPattern>; fsPattern : IFileSystemPattern; searchBasePath : string; fileCount : integer; begin ValidateDestinationPath(source, dest); searchBasePath := TPathUtils.StripWildCard(TPathUtils.CompressRelativePath(basePath, source)); searchBasePath := ExtractFilePath(searchBasePath); fsPatterns := antPattern.Expand(source); fileCount := 0; for fsPattern in fsPatterns do ProcessPattern(searchBasePath, dest, fsPattern, flatten, exclude, ignore, fileCount); if (not ignore) and (fileCount = 0) then FLogger.Warning('No files were found for pattern [' + source + ']'); end; begin result := false; sManifest := spec.GenerateManifestJson(version, targetPlatform); packageFileName := spec.MetaData.Id + '-' + CompilerToString(targetPlatform.Compiler) + '-' + DPMPlatformToString(targetPlatform.Platforms[0]) + '-' + version.ToStringNoMeta + cPackageFileExt; packageFileName := IncludeTrailingPathDelimiter(outputFolder) + packageFileName; FArchiveWriter.SetBasePath(basePath); if not FArchiveWriter.Open(packageFileName) then begin FLogger.Warning('Could not open package file [' + packageFileName + '] - skipping'); exit; end; FLogger.Information('Writing package to file : ' + packageFileName); try if spec.MetaData.Icon <> '' then FArchiveWriter.AddIcon(spec.MetaData.Icon); sStream := TStringStream.Create(sManifest, TEncoding.UTF8); try FArchiveWriter.WriteMetaDataFile(sStream); finally sStream.Free; end; antPattern := TAntPattern.Create(basePath); for fileEntry in targetPlatform.SourceFiles do ProcessEntry(fileEntry.Source, fileEntry.Destination, fileEntry.Flatten, fileEntry.Exclude, false); for fileEntry in targetPlatform.Files do ProcessEntry(fileEntry.Source, fileEntry.Destination, fileEntry.Flatten, fileEntry.Exclude, false); for fileEntry in targetPlatform.LibFiles do ProcessEntry(fileEntry.Source, fileEntry.Destination, fileEntry.Flatten, fileEntry.Exclude, fileEntry.Ignore); result := true; finally FArchiveWriter.Close; end; end; function TPackageWriter.WritePackageFromSpec(const cancellationToken : ICancellationToken; const options : TPackOptions) : boolean; var spec : IPackageSpec; targetPlatform : ISpecTargetPlatform; version : TPackageVersion; error : string; properties : TStringList; props : TArray<string>; prop : string; begin result := false; //expand relative paths options.SpecFile := TPath.GetFullPath(options.SpecFile); if not FileExists(options.SpecFile) then raise EArgumentException.Create('Spec file : ' + options.SpecFile + ' - does not exist!'); if ExtractFileExt(options.SpecFile) <> cPackageSpecExt then raise EArgumentException.Create('Spec file : ' + options.SpecFile + ' - is likely not a spec file, incorrect extension, should be [' + cPackageSpecExt + ']'); //output and base path default to current folder if not set if options.OutputFolder = '' then options.OutputFolder := GetCurrentDir else options.OutputFolder := TPath.GetFullPath(options.OutputFolder); if options.BasePath = '' then options.BasePath := TPath.GetDirectoryName(options.SpecFile) else options.BasePath := TPath.GetFullPath(options.BasePath); if not DirectoryExists(options.BasePath) then raise EArgumentException.Create('Base Path : ' + options.BasePath + ' - does not exist!'); if options.Version <> '' then begin if not TPackageVersion.TryParseWithError(options.Version, version, error) then begin FLogger.Error('Invalid Version : ' + error); Exit(false); end; end else version := TPackageVersion.Empty; ForceDirectories(options.OutputFolder); FLogger.Information('Reading package spec from file : ' + options.SpecFile); spec := FSpecReader.ReadSpec(options.specFile); if spec = nil then begin FLogger.Information('An error occured reading the spec file, package writing failed'); exit end; if not spec.IsValid then begin FLogger.Error('Spec is not valid, exiting.'); exit; end; properties := TStringList.Create; try if options.Properties <> '' then begin props := TStringUtils.SplitStr(options.Properties, ';'); for prop in props do begin if pos('=', prop) > 0 then properties.Add(prop); end; end; if not spec.PreProcess(version, properties) then begin FLogger.Error('Spec is not valid, exiting.'); exit; end; FLogger.Information('Spec is valid, writing package files...'); result := true; for targetPlatform in spec.TargetPlatforms do begin if cancellationToken.IsCancelled then exit(false); if version.IsEmpty then version := spec.MetaData.Version; result := WritePackage(options.OutputFolder, targetPlatform, spec, version, options.BasePath) and result; end; FLogger.Information('Done.'); finally properties.Free; end; end; end.
unit CoreX; {====================================================================} { "CoreX" crossplatform game library } { Version : 0.01 } { Mail : xproger@list.ru } { Site : http://xproger.mentalx.org } {====================================================================} { LICENSE: } { Copyright (c) 2009, Timur "XProger" Gagiev } { All rights reserved. } { } { Redistribution and use in source and binary forms, with or without } { modification, are permitted under the terms of the BSD License. } {====================================================================} interface {$DEFINE DEBUG} {$IFDEF WIN32} {$DEFINE WINDOWS} {$ELSE} {$DEFINE LINUX} {$ENDIF} type TCoreProc = procedure; // Math ------------------------------------------------------------------------ {$REGION 'Math'} TVec2f = record x, y : Single; end; TVec3f = record x, y, z : Single; end; TVec4f = record x, y, z, w : Single; end; TMath = object function Vec2f(x, y: Single): TVec2f; inline; function Vec3f(x, y, z: Single): TVec3f; inline; function Vec4f(x, y, z, w: Single): TVec4f; inline; function Max(x, y: Single): Single; overload; function Min(x, y: Single): Single; overload; function Max(x, y: Integer): Integer; overload; function Min(x, y: Integer): Integer; overload; function Sign(x: Single): Integer; function Ceil(const X: Extended): Integer; function Floor(const X: Extended): Integer; end; {$ENDREGION} // Utils ----------------------------------------------------------------------- {$REGION 'Utils'} TCharSet = set of AnsiChar; TUtils = object function IntToStr(Value: LongInt): string; function StrToInt(const Str: string; Def: LongInt = 0): LongInt; function FloatToStr(Value: Single; Digits: LongInt = 6): string; function StrToFloat(const Str: string; Def: Single = 0): Single; function BoolToStr(Value: Boolean): string; function StrToBool(const Str: string; Def: Boolean = False): Boolean; function LowerCase(const Str: string): string; function Trim(const Str: string): string; function DeleteChars(const Str: string; Chars: TCharSet): string; function ExtractFileDir(const Path: string): string; end; TResType = (rtTexture); TResData = record Ref : LongInt; Name : string; case TResType of rtTexture : ( ID : LongWord; Width : LongInt; Height : LongInt; ); end; TResManager = object Items : array of TResData; Count : LongInt; procedure Init; function Add(const Name: string; out Idx: LongInt): Boolean; function Delete(Idx: LongInt): Boolean; end; TConfigFile = object private Data : array of record Category : string; Params : array of record Name : string; Value : string; end; end; public procedure Load(const FileName: string); procedure Save(const FileName: string); procedure WriteStr(const Category, Name, Value: string); procedure WriteInt(const Category, Name: string; Value: LongInt); procedure WriteFloat(const Category, Name: string; Value: Single); procedure WriteBool(const Category, Name: string; Value: Boolean); function ReadStr(const Category, Name: string; const Default: string = ''): string; function ReadInt(const Category, Name: string; Default: LongInt = 0): LongInt; function ReadFloat(const Category, Name: string; Default: Single = 0): Single; function ReadBool(const Category, Name: string; Default: Boolean = False): Boolean; function CategoryName(Idx: LongInt): string; end; {$ENDREGION} // Display --------------------------------------------------------------------- {$REGION 'Display'} TAAType = (aa0x, aa1x, aa2x, aa4x, aa8x, aa16x); TDisplay = object private FQuit : Boolean; Handle : LongWord; FWidth : LongInt; FHeight : LongInt; FFullScreen : Boolean; FAntiAliasing : TAAType; FVSync : Boolean; FActive : Boolean; FCaption : string; FFPS : LongInt; FFPSTime : LongInt; FFPSIdx : LongInt; procedure Init; procedure Free; procedure Update; procedure Restore; procedure SetFullScreen(Value: Boolean); procedure SetVSync(Value: Boolean); procedure SetCaption(const Value: string); public procedure Resize(W, H: LongInt); procedure Swap; property Width: LongInt read FWidth; property Height: LongInt read FHeight; property FullScreen: Boolean read FFullScreen write SetFullScreen; property AntiAliasing: TAAType read FAntiAliasing write FAntiAliasing; property VSync: Boolean read FVSync write SetVSync; property Active: Boolean read FActive; property Caption: string read FCaption write SetCaption; property FPS: LongInt read FFPS; end; {$ENDREGION} // Input ----------------------------------------------------------------------- {$REGION 'Input'} TInputKey = ( // Keyboard KK_NONE, KK_PLUS, KK_MINUS, KK_TILDE, KK_0, KK_1, KK_2, KK_3, KK_4, KK_5, KK_6, KK_7, KK_8, KK_9, KK_A, KK_B, KK_C, KK_D, KK_E, KK_F, KK_G, KK_H, KK_I, KK_J, KK_K, KK_L, KK_M, KK_N, KK_O, KK_P, KK_Q, KK_R, KK_S, KK_T, KK_U, KK_V, KK_W, KK_X, KK_Y, KK_Z, KK_F1, KK_F2, KK_F3, KK_F4, KK_F5, KK_F6, KK_F7, KK_F8, KK_F9, KK_F10, KK_F11, KK_F12, KK_ESC, KK_ENTER, KK_BACK, KK_TAB, KK_SHIFT, KK_CTRL, KK_ALT, KK_SPACE, KK_PGUP, KK_PGDN, KK_END, KK_HOME, KK_LEFT, KK_UP, KK_RIGHT, KK_DOWN, KK_INS, KK_DEL, // Mouse KM_1, KM_2, KM_3, KM_WHUP, KM_WHDN, // Joystick KJ_1, KJ_2, KJ_3, KJ_4, KJ_5, KJ_6, KJ_7, KJ_8, KJ_9, KJ_10, KJ_11, KJ_12, KJ_13, KJ_14, KJ_15, KJ_16 ); TMouseDelta = record X, Y, Wheel : LongInt; end; TMousePos = record X, Y : LongInt; end; TMouse = object Pos : TMousePos; Delta : TMouseDelta; end; TJoyAxis = record X, Y, Z, R, U, V : LongInt; end; TJoy = object private FReady : Boolean; public POV : Single; Axis : TJoyAxis; property Ready: Boolean read FReady; end; TInput = object private FCapture : Boolean; FDown, FHit : array [TInputKey] of Boolean; FLastKey : TInputKey; procedure Init; procedure Free; procedure Reset; procedure Update; function GetDown(InputKey: TInputKey): Boolean; function GetHit(InputKey: TInputKey): Boolean; procedure SetState(InputKey: TInputKey; Value: Boolean); procedure SetCapture(Value: Boolean); public Mouse : TMouse; Joy : TJoy; property LastKey: TInputKey read FLastKey; property Down[InputKey: TInputKey]: Boolean read GetDown; property Hit[InputKey: TInputKey]: Boolean read GetHit; property Capture: Boolean read FCapture write SetCapture; end; {$ENDREGION} // Render ---------------------------------------------------------------------- {$REGION 'Render'} TBlendType = (btNone, btNormal, btAdd, btMult); TRender = object private FDeltaTime : Single; OldTime : LongInt; ResManager : TResManager; procedure Init; procedure Free; function GeLongWord: LongInt; procedure SetBlend(Value: TBlendType); procedure SetDepthTest(Value: Boolean); procedure SetDepthWrite(Value: Boolean); public procedure Clear(Color, Depth: Boolean); procedure Set2D(Width, Height: LongInt); procedure Set3D(FOV: Single; zNear: Single = 0.1; zFar: Single = 1000); procedure Quad(x, y, w, h, s, t, sw, th: Single); inline; property Time: LongInt read GeLongWord; property DeltaTime: Single read FDeltaTime; property Blend: TBlendType write SetBlend; property DepthTest: Boolean write SetDepthTest; property DepthWrite: Boolean write SetDepthWrite; end; {$ENDREGION} // Texture --------------------------------------------------------------------- {$REGION 'Texture'} TTexture = object private ResIdx : LongInt; Width : LongInt; Height : LongInt; public procedure Load(const FileName: string); procedure Free; procedure Enable(Channel: LongInt = 0); end; {$ENDREGION} // Sprite ---------------------------------------------------------------------- {$REGION 'Sprite'} TSpriteAnim = object private FName : string; FFrames : LongInt; FX, FY : LongInt; FWidth : LongInt; FHeight : LongInt; FCols : LongInt; FCX, FCY : LongInt; FFPS : LongInt; public property Name: string read FName; property Frames: LongInt read FFrames; property X: LongInt read FX; property Y: LongInt read FY; property Width: LongInt read FWidth; property Height: LongInt read FHeight; property Cols: LongInt read FCols; property CenterX: LongInt read FCX; property CenterY: LongInt read FCY; property FPS: LongInt read FFPS; end; TSpriteAnimList = object private FCount : LongInt; FItems : array of TSpriteAnim; function GetItem(Idx: LongInt): TSpriteAnim; public procedure Add(const Name: string; Frames, X, Y, W, H, Cols, CX, CY, FPS: LongInt); function IndexOf(const Name: string): LongInt; property Count: LongInt read FCount; property Items[Idx: LongInt]: TSpriteAnim read GetItem; default; end; TSprite = object private FPlaying : Boolean; FLoop : Boolean; FAnim : TSpriteAnimList; Texture : TTexture; Blend : TBlendType; CurIndex : LongInt; StarLongWord : LongInt; function GetPlaying: Boolean; public Pos : TVec2f; Scale : TVec2f; Angle : Single; procedure Load(const FileName: string); procedure Free; procedure Play(const AnimName: string; Loop: Boolean); procedure Stop; procedure Draw; property Playing: Boolean read GetPlaying; property Anim: TSpriteAnimList read FAnim; end; {$ENDREGION} // OpenGL ---------------------------------------------------------------------- {$REGION 'OpenGL'} type TGLConst = ( // AttribMask GL_DEPTH_BUFFER_BIT = $0100, GL_STENCIL_BUFFER_BIT = $0400, GL_COLOR_BUFFER_BIT = $4000, // Boolean GL_FALSE = 0, GL_TRUE, // Begin Mode GL_POINTS = 0, GL_LINES, GL_LINE_LOOP, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_POLYGON, // Alpha Function GL_NEVER = $0200, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS, // Blending Factor GL_ZERO = 0, GL_ONE, GL_SRC_COLOR = $0300, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_DST_COLOR = $0306, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA_SATURATE, // DrawBuffer Mode GL_FRONT = $0404, GL_BACK, GL_FRONT_AND_BACK, // Tests GL_DEPTH_TEST = $0B71, GL_STENCIL_TEST = $0B90, GL_ALPHA_TEST = $0BC0, GL_SCISSOR_TEST = $0C11, // GetTarget GL_CULL_FACE = $0B44, GL_BLEND = $0BE2, // Data Types GL_BYTE = $1400, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, // Matrix Mode GL_MODELVIEW = $1700, GL_PROJECTION, GL_TEXTURE, // Pixel Format GL_RGB = $1907, GL_RGBA, GL_RGB8 = $8051, GL_RGBA8 = $8058, GL_BGR = $80E0, GL_BGRA, // PolygonMode GL_POINT = $1B00, GL_LINE, GL_FILL, // List mode GL_COMPILE = $1300, GL_COMPILE_AND_EXECUTE, // StencilOp GL_KEEP = $1E00, GL_REPLACE, GL_INCR, GL_DECR, // GetString Parameter GL_VENDOR = $1F00, GL_RENDERER, GL_VERSION, GL_EXTENSIONS, // TextureEnvParameter GL_TEXTURE_ENV_MODE = $2200, GL_TEXTURE_ENV_COLOR, // TextureEnvTarget GL_TEXTURE_ENV = $2300, // Texture Filter GL_NEAREST = $2600, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST = $2700, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_TEXTURE_MAG_FILTER = $2800, GL_TEXTURE_MIN_FILTER, // Texture Wrap Mode GL_TEXTURE_WRAP_S = $2802, GL_TEXTURE_WRAP_T, GL_REPEAT = $2901, GL_CLAMP_TO_EDGE = $812F, GL_TEXTURE_BASE_LEVEL = $813C, GL_TEXTURE_MAX_LEVEL, // Textures GL_TEXTURE_2D = $0DE1, GL_TEXTURE0 = $84C0, GL_TEXTURE_MAX_ANISOTROPY = $84FE, GL_MAX_TEXTURE_MAX_ANISOTROPY, GL_GENERATE_MIPMAP = $8191, // Compressed Textures GL_COMPRESSED_RGB_S3TC_DXT1 = $83F0, GL_COMPRESSED_RGBA_S3TC_DXT1, GL_COMPRESSED_RGBA_S3TC_DXT3, GL_COMPRESSED_RGBA_S3TC_DXT5, // AA WGL_SAMPLE_BUFFERS = $2041, WGL_SAMPLES, WGL_DRAW_TO_WINDOW = $2001, WGL_SUPPORT_OPENGL = $2010, WGL_DOUBLE_BUFFER, WGL_COLOR_BITS = $2014, WGL_DEPTH_BITS = $2022, WGL_STENCIL_BITS, // FBO GL_FRAMEBUFFER = $8D40, GL_RENDERBUFFER, GL_DEPTH_COMPONENT24 = $81A6, GL_COLOR_ATTACHMENT0 = $8CE0, GL_DEPTH_ATTACHMENT = $8D00, GL_FRAMEBUFFER_BINDING = $8CA6, GL_FRAMEBUFFER_COMPLETE = $8CD5, // Shaders GL_FRAGMENT_SHADER = $8B30, GL_VERTEX_SHADER, GL_COMPILE_STATUS = $8B81, GL_LINK_STATUS, GL_VALIDATE_STATUS, GL_INFO_LOG_LENGTH, // VBO GL_ARRAY_BUFFER = $8892, GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY = $88B9, GL_STATIC_DRAW = $88E4, GL_VERTEX_ARRAY = $8074, GL_NORMAL_ARRAY, GL_COLOR_ARRAY, GL_INDEX_ARRAY_EXT, GL_TEXTURE_COORD_ARRAY, // Queries GL_SAMPLES_PASSED = $8914, GL_QUERY_COUNTER_BITS = $8864, GL_CURRENT_QUERY, GL_QUERY_RESULT, GL_QUERY_RESULT_AVAILABLE, GL_MAX_CONST = High(LongInt) ); {$IFDEF LINUX} {$MACRO ON} {$DEFINE stdcall := cdecl} {$ENDIF} TGL = object private Lib : LongWord; procedure Init; procedure Free; public GetProc : function (ProcName: PAnsiChar): Pointer; stdcall; SwapInterval : function (Interval: LongInt): LongInt; stdcall; GetString : function (name: TGLConst): PAnsiChar; stdcall; PolygonMode : procedure (face, mode: TGLConst); stdcall; GenTextures : procedure (n: LongInt; textures: Pointer); stdcall; DeleteTextures : procedure (n: LongInt; textures: Pointer); stdcall; BindTexture : procedure (target: TGLConst; texture: LongWord); stdcall; TexParameteri : procedure (target, pname, param: TGLConst); stdcall; TexImage2D : procedure (target: TGLConst; level: LongInt; internalformat: TGLConst; width, height, border: LongInt; format, _type: TGLConst; pixels: Pointer); stdcall; CompressedTexImage2D : procedure (target: TGLConst; level: LongInt; internalformat: TGLConst; width, height, border, imageSize: LongInt; data: Pointer); stdcall; ActiveTexture : procedure (texture: TGLConst); stdcall; ClientActiveTexture : procedure (texture: TGLConst); stdcall; Clear : procedure (mask: TGLConst); stdcall; ClearColor : procedure (red, green, blue, alpha: Single); stdcall; ColorMask : procedure (red, green, blue, alpha: Boolean); stdcall; DepthMask : procedure (flag: Boolean); stdcall; StencilMask : procedure (mask: LongWord); stdcall; Enable : procedure (cap: TGLConst); stdcall; Disable : procedure (cap: TGLConst); stdcall; BlendFunc : procedure (sfactor, dfactor: TGLConst); stdcall; StencilFunc : procedure (func: TGLConst; ref: LongInt; mask: LongWord); stdcall; DepthFunc : procedure (func: TGLConst); stdcall; StencilOp : procedure (fail, zfail, zpass: TGLConst); stdcall; Viewport : procedure (x, y, width, height: LongInt); stdcall; Beginp : procedure (mode: TGLConst); stdcall; Endp : procedure; Vertex2fv : procedure (xyz: Pointer); stdcall; Vertex3fv : procedure (xy: Pointer); stdcall; TexCoord2fv : procedure (st: Pointer); stdcall; EnableClientState : procedure (_array: TGLConst); stdcall; DisableClientState : procedure (_array: TGLConst); stdcall; DrawElements : procedure (mode: TGLConst; count: LongInt; _type: TGLConst; const indices: Pointer); stdcall; DrawArrays : procedure (mode: TGLConst; first, count: LongInt); stdcall; ColorPointer : procedure (size: LongInt; _type: TGLConst; stride: LongInt; const ptr: Pointer); stdcall; VertexPointer : procedure (size: LongInt; _type: TGLConst; stride: LongInt; const ptr: Pointer); stdcall; TexCoordPointer : procedure (size: LongInt; _type: TGLConst; stride: LongInt; const ptr: Pointer); stdcall; NormalPointer : procedure (type_: TGLConst; stride: LongWord; const P: Pointer); stdcall; MatrixMode : procedure (mode: TGLConst); stdcall; LoadIdentity : procedure; stdcall; LoadMatrixf : procedure (m: Pointer); stdcall; MultMatrixf : procedure (m: Pointer); stdcall; PushMatrix : procedure; stdcall; PopMatrix : procedure; stdcall; Scalef : procedure (x, y, z: Single); stdcall; Translatef : procedure (x, y, z: Single); stdcall; Rotatef : procedure (Angle, x, y, z: Single); stdcall; Ortho : procedure (left, right, bottom, top, zNear, zFar: Double); stdcall; Frustum : procedure (left, right, bottom, top, zNear, zFar: Double); stdcall; end; {$IFDEF LINUX} {$MACRO OFF} {$ENDIF} {$ENDREGION} var gl : TGL; Math : TMath; Utils : TUtils; Display : TDisplay; Input : TInput; Render : TRender; procedure Start(PInit, PFree, PRender: TCoreProc); procedure Quit; implementation // System API ================================================================== {$REGION 'Windows System'} {$IFDEF WINDOWS} // Windows API ----------------------------------------------------------------- type TWndClassEx = packed record cbSize : LongWord; style : LongWord; lpfnWndProc : Pointer; cbClsExtra : LongInt; cbWndExtra : LongInt; hInstance : LongWord; hIcon : LongInt; hCursor : LongWord; hbrBackground : LongWord; lpszMenuName : PAnsiChar; lpszClassName : PAnsiChar; hIconSm : LongWord; end; TPixelFormatDescriptor = packed record nSize : Word; nVersion : Word; dwFlags : LongWord; iPixelType : Byte; cColorBits : Byte; SomeData1 : array [0..12] of Byte; cDepthBits : Byte; cStencilBits : Byte; SomeData2 : array [0..14] of Byte; end; TDeviceMode = packed record SomeData1 : array [0..35] of Byte; dmSize : Word; dmDriverExtra : Word; dmFields : LongWord; SomeData2 : array [0..59] of Byte; dmBitsPerPel : LongWord; dmPelsWidth : LongWord; dmPelsHeight : LongWord; SomeData3 : array [0..39] of Byte; end; TMsg = array [0..6] of LongWord; TPoint = packed record X, Y : LongInt; end; TRect = packed record Left, Top, Right, Bottom : LongInt; end; TJoyCaps = packed record wMid, wPid : Word; szPname : array [0..31] of AnsiChar; wXmin, wXmax : LongWord; wYmin, wYmax : LongWord; wZmin, wZmax : LongWord; wNumButtons : LongWord; wPMin, wPMax : LongWord; wRmin, wRmax : LongWord; wUmin, wUmax : LongWord; wVmin, wVmax : LongWord; wCaps : LongWord; wMaxAxes : LongWord; wNumAxes : LongWord; wMaxButtons : LongWord; szRegKey : array [0..31] of AnsiChar; szOEMVxD : array [0..259] of AnsiChar; end; TJoyInfo = packed record dwSize : LongWord; dwFlags : LongWord; wXpos : LongWord; wYpos : LongWord; wZpos : LongWord; wRpos : LongWord; wUpos : LongWord; wVpos : LongWord; wButtons : LongWord; dwButtonNum : LongWord; dwPOV : LongWord; dwRes : array [0..1] of LongWord; end; const kernel32 = 'kernel32.dll'; user32 = 'user32.dll'; gdi32 = 'gdi32.dll'; opengl32 = 'opengl32.dll'; winmm = 'winmm.dll'; WND_CLASS = 'CCoreX'; WS_CAPTION = $C00000; WS_MINIMIZEBOX = $20000; WS_SYSMENU = $80000; WS_VISIBLE = $10000000; WM_DESTROY = $0002; WM_ACTIVATEAPP = $001C; WM_SETICON = $0080; WM_KEYDOWN = $0100; WM_SYSKEYDOWN = $0104; WM_LBUTTONDOWN = $0201; WM_RBUTTONDOWN = $0204; WM_MBUTTONDOWN = $0207; WM_MOUSEWHEEL = $020A; SW_SHOW = 5; SW_MINIMIZE = 6; GWL_STYLE = -16; JOYCAPS_HASZ = $0001; JOYCAPS_HASR = $0002; JOYCAPS_HASU = $0004; JOYCAPS_HASV = $0008; JOYCAPS_HASPOV = $0010; JOYCAPS_POVCTS = $0040; JOY_RETURNPOVCTS = $0200; function QueryPerformanceFrequency(out Freq: Int64): Boolean; stdcall; external kernel32; function QueryPerformanceCounter(out Count: Int64): Boolean; stdcall; external kernel32; function LoadLibraryA(Name: PAnsiChar): LongWord; stdcall; external kernel32; function FreeLibrary(LibHandle: LongWord): Boolean; stdcall; external kernel32; function GetProcAddress(LibHandle: LongWord; ProcName: PAnsiChar): Pointer; stdcall; external kernel32; function RegisterClassExA(const WndClass: TWndClassEx): Word; stdcall; external user32; function UnregisterClassA(lpClassName: PAnsiChar; hInstance: LongWord): Boolean; stdcall; external user32; function CreateWindowExA(dwExStyle: LongWord; lpClassName: PAnsiChar; lpWindowName: PAnsiChar; dwStyle: LongWord; X, Y, nWidth, nHeight: LongInt; hWndParent, hMenum, hInstance: LongWord; lpParam: Pointer): LongWord; stdcall; external user32; function DestroyWindow(hWnd: LongWord): Boolean; stdcall; external user32; function ShowWindow(hWnd: LongWord; nCmdShow: LongInt): Boolean; stdcall; external user32; function SetWindowLongA(hWnd: LongWord; nIndex, dwNewLong: LongInt): LongInt; stdcall; external user32; function AdjustWindowRect(var lpRect: TRect; dwStyle: LongWord; bMenu: Boolean): Boolean; stdcall; external user32; function SetWindowPos(hWnd, hWndInsertAfter: LongWord; X, Y, cx, cy: LongInt; uFlags: LongWord): Boolean; stdcall; external user32; function GetWindowRect(hWnd: LongWord; out lpRect: TRect): Boolean; stdcall; external user32; function GetCursorPos(out Point: TPoint): Boolean; stdcall; external user32; function SetCursorPos(X, Y: LongInt): Boolean; stdcall; external user32; function ShowCursor(bShow: Boolean): LongInt; stdcall; external user32; function ScreenToClient(hWnd: LongWord; var lpPoint: TPoint): Boolean; stdcall; external user32; function DefWindowProcA(hWnd, Msg: LongWord; wParam, lParam: LongInt): LongInt; stdcall; external user32; function PeekMessageA(out lpMsg: TMsg; hWnd, Min, Max, Remove: LongWord): Boolean; stdcall; external user32; function TranslateMessage(const lpMsg: TMsg): Boolean; stdcall; external user32; function DispatchMessageA(const lpMsg: TMsg): LongInt; stdcall; external user32; function SendMessageA(hWnd, Msg: LongWord; wParam, lParam: LongInt): LongInt; stdcall; external user32; function LoadIconA(hInstance: LongInt; lpIconName: PAnsiChar): LongWord; stdcall; external user32; function GetDC(hWnd: LongWord): LongWord; stdcall; external user32; function ReleaseDC(hWnd, hDC: LongWord): LongInt; stdcall; external user32; function SetWindowTextA(hWnd: LongWord; Text: PAnsiChar): Boolean; stdcall; external user32; function EnumDisplaySettingsA(lpszDeviceName: PAnsiChar; iModeNum: LongWord; lpDevMode: Pointer): Boolean; stdcall; external user32; function ChangeDisplaySettingsA(lpDevMode: Pointer; dwFlags: LongWord): LongInt; stdcall; external user32; function SetPixelFormat(DC: LongWord; PixelFormat: LongInt; FormatDef: Pointer): Boolean; stdcall; external gdi32; function ChoosePixelFormat(DC: LongWord; p2: Pointer): LongInt; stdcall; external gdi32; function SwapBuffers(DC: LongWord): Boolean; stdcall; external gdi32; function wglCreateContext(DC: LongWord): LongWord; stdcall; external opengl32; function wglMakeCurrent(DC, p2: LongWord): Boolean; stdcall; external opengl32; function wglDeleteContext(p1: LongWord): Boolean; stdcall; external opengl32; function wglGetProcAddress(ProcName: PAnsiChar): Pointer; stdcall; external opengl32; function joyGetNumDevs: LongWord; stdcall; external winmm; function joyGetDevCapsA(uJoyID: LongWord; lpCaps: Pointer; uSize: LongWord): LongWord; stdcall; external winmm; function joyGetPosEx(uJoyID: LongWord; lpInfo: Pointer): LongWord; stdcall; external winmm; var DC, RC : LongWord; TimeFreq : Int64; JoyCaps : TJoyCaps; JoyInfo : TJoyInfo; {$ENDIF} {$ENDREGION} {$REGION 'Linux System'} {$IFDEF LINUX} // Linux API ------------------------------------------------------------------- {$LINKLIB GL} {$LINKLIB X11} {$LINKLIB Xrandr} {$LINKLIB dl} const opengl32 = 'libGL.so'; KeyPressMask = 1 shl 0; KeyReleaseMask = 1 shl 1; ButtonPressMask = 1 shl 2; ButtonReleaseMask = 1 shl 3; PointerMotionMask = 1 shl 6; ButtonMotionMask = 1 shl 13; FocusChangeMask = 1 shl 21; CWOverrideRedirect = 1 shl 9; CWEventMask = 1 shl 11; CWColormap = 1 shl 13; CWCursor = 1 shl 14; PPosition = 1 shl 2; PMinSize = 1 shl 4; PMaxSize = 1 shl 5; KeyPress = 2; KeyRelease = 3; ButtonPress = 4; ButtonRelease = 5; FocusIn = 9; FocusOut = 10; ClientMessage = 33; GLX_BUFFER_SIZE = 2; GLX_RGBA = 4; GLX_DOUBLEBUFFER = 5; GLX_DEPTH_SIZE = 12; GLX_STENCIL_SIZE = 13; GLX_SAMPLES = 100001; KEYBOARD_MASK = KeyPressMask or KeyReleaseMask; MOUSE_MASK = ButtonPressMask or ButtonReleaseMask or ButtonMotionMask or PointerMotionMask; type PXSeLongWordAttributes = ^TXSeLongWordAttributes; TXSeLongWordAttributes = record background_pixmap : LongWord; background_pixel : LongWord; SomeData1 : array [0..6] of LongInt; save_under : Boolean; event_mask : LongInt; do_not_propagate_mask : LongInt; override_redirect : Boolean; colormap : LongWord; cursor : LongWord; end; PXVisualInfo = ^XVisualInfo; XVisualInfo = record visual : Pointer; visualid : LongWord; screen : LongInt; depth : LongInt; SomeData1 : array [0..5] of LongInt; end; TXColor = record pixel : LongWord; r, g, b : Word; flags, pad : AnsiChar; end; PXSizeHints = ^TXSizeHints; TXSizeHints = record flags : LongInt; x, y, w, h : LongInt; min_w, min_h : LongInt; max_w, max_h : LongInt; SomeData1 : array [0..8] of LongInt; end; TXClientMessageEvent = record message_type: LongWord; format: LongInt; data: record l: array[0..4] of LongInt; end; end; TXKeyEvent = record Root, Subwindow: LongWord; Time : LongWord; x, y, XRoot, YRoot : Integer; State, KeyCode : LongWord; SameScreen : Boolean; end; PXEvent = ^TXEvent; TXEvent = record _type : LongInt; serial : LongWord; send_event : Boolean; display : Pointer; xwindow : LongWord; case LongInt of 0 : (pad : array [0..18] of LongInt); 1 : (xclient : TXClientMessageEvent); 2 : (xkey : TXKeyEvent); end; PXRRScreenSize = ^TXRRScreenSize; TXRRScreenSize = record width, height : LongInt; mwidth, mheight : LongInt; end; TTimeVal = record tv_sec : LongInt; tv_usec : LongInt; end; function XDefaultScreen(Display: Pointer): LongInt; cdecl; external; function XRootWindow(Display: Pointer; ScreenNumber: LongInt): LongWord; cdecl; external; function XOpenDisplay(DisplayName: PAnsiChar): Pointer; cdecl; external; function XCloseDisplay(Display: Pointer): Longint; cdecl; external; function XBlackPixel(Display: Pointer; ScreenNumber: LongInt): LongWord; cdecl; external; function XCreateColormap(Display: Pointer; W: LongWord; Visual: Pointer; Alloc: LongInt): LongWord; cdecl; external; function XCreateWindow(Display: Pointer; Parent: LongWord; X, Y: LongInt; Width, Height, BorderWidth: LongWord; Depth: LongInt; AClass: LongWord; Visual: Pointer; ValueMask: LongWord; Attributes: PXSeLongWordAttributes): LongWord; cdecl; external; function XDestroyWindow(Display: Pointer; W: LongWord): LongInt; cdecl; external; function XStoreName(Display: Pointer; Window: LongWord; _Xconst: PAnsiChar): LongInt; cdecl; external; function XInternAtom(Display: Pointer; Names: PAnsiChar; OnlyIfExists: Boolean): LongWord; cdecl; external; function XSetWMProtocols(Display: Pointer; W: LongWord; Protocols: Pointer; Count: LongInt): LongInt; cdecl; external; function XMapWindow(Display: Pointer; W: LongWord): LongInt; cdecl; external; function XFree(Data: Pointer): LongInt; cdecl; external; procedure XSetWMNormalHints(Display: Pointer; W: LongWord; Hints: PXSizeHints); cdecl; external; function XPending(Display: Pointer): LongInt; cdecl; external; function XNextEvent(Display: Pointer; EventReturn: PXEvent): Longint; cdecl; external; procedure glXWaitX; cdecl; external; function XCreatePixmap(Display: Pointer; W: LongWord; Width, Height, Depth: LongWord): LongWord; cdecl; external; function XCreatePixmapCursor(Display: Pointer; Source, Mask: LongWord; FColor, BColor: Pointer; X, Y: LongWord): LongWord; cdecl; external; function XLookupKeysym(para1: Pointer; para2: LongInt): LongWord; cdecl; external; function XDefineCursor(Display: Pointer; W: LongWord; Cursor: LongWord): Longint; cdecl; external; function XWarpPointer(Display: Pointer; SrcW, DestW: LongWord; SrcX, SrcY: LongInt; SrcWidth, SrcHeight: LongWord; DestX, DestY: LongInt): LongInt; cdecl; external; function XQueryPointer(Display: Pointer; W: LongWord; RootRetun, ChildReturn, RootXReturn, RootYReturn, WinXReturn, WinYReturn, MaskReturn: Pointer): Boolean; cdecl; external; function XGrabKeyboard(Display: Pointer; GrabWindow: LongWord; OwnerEvents: Boolean; PointerMode, KeyboardMode: LongInt; Time: LongWord): LongInt; cdecl; external; function XGrabPointer(Display: Pointer; GrabWindow: LongWord; OwnerEvents: Boolean; EventMask: LongWord; PointerMode, KeyboardMode: LongInt; ConfineTo, Cursor, Time: LongWord): LongInt; cdecl; external; function XUngrabKeyboard(Display: Pointer; Time: LongWord): LongInt; cdecl; external; function XUngrabPointer(Display: Pointer; Time: LongWord): LongInt; cdecl; external; procedure XRRFreeScreenConfigInfo(config: Pointer); cdecl; external; function XRRGetScreenInfo(dpy: Pointer; draw: LongWord): Pointer; cdecl; external; function XRRSetScreenConfigAndRate(dpy: Pointer; config: Pointer; draw: LongWord; size_index: LongInt; rotation: Word; rate: Word; timestamp: LongWord): LongInt; cdecl; external; function XRRConfigCurrentConfiguration(config: Pointer; rotation: Pointer): Word; cdecl; external; function XRRRootToScreen(dpy: Pointer; root: LongWord): LongInt; cdecl; external; function XRRSizes(dpy: Pointer; screen: LongInt; nsizes: PLongInt): PXRRScreenSize; cdecl; external; function gettimeofday(out timeval: TTimeVal; timezone: Pointer): LongInt; cdecl; external; function glXChooseVisual(dpy: Pointer; screen: Integer; attribList: Pointer): PXVisualInfo; cdecl; external; function glXCreateContext(dpy: Pointer; vis: PXVisualInfo; shareList: Pointer; direct: Boolean): Pointer; cdecl; external; procedure glXDestroyContext(dpy: Pointer; ctx: Pointer); cdecl; external; function glXMakeCurrent(dpy: Pointer; drawable: LongWord; ctx: Pointer): Boolean; cdecl; external; procedure glXCopyContext(dpy: Pointer; src, dst: Pointer; mask: LongWord); cdecl; external; procedure glXSwapBuffers(dpy: Pointer; drawable: LongWord); cdecl; external; function dlopen(Name: PAnsiChar; Flags: LongInt): LongWord; cdecl; external; function dlsym(Lib: LongWord; Name: PAnsiChar): Pointer; cdecl; external; function dlclose(Lib: LongWord): LongInt; cdecl; external; function LoadLibraryA(Name: PAnsiChar): LongWord; begin Result := dlopen(Name, 1); end; function FreeLibrary(LibHandle: LongWord): Boolean; begin Result := dlclose(LibHandle) = 0; end; function GetProcAddress(LibHandle: LongWord; ProcName: PAnsiChar): Pointer; begin Result := dlsym(LibHandle, ProcName); end; var XDisp : Pointer; XScr : LongWord; XWndAttr : TXSeLongWordAttributes; XContext : Pointer; XVisual : PXVisualInfo; XRoot : LongWord; // screen size params ScrConfig : Pointer; ScrSizes : PXRRScreenSize; SizesCount : LongInt; DefSizeIdx : LongInt; WM_PROTOCOLS : LongWord; WM_DESTROY : LongWord; {$ENDIF} {$ENDREGION} // Math ======================================================================== {$REGION 'TMath'} function TMath.Vec2f(x, y: Single): TVec2f; begin Result.x := x; Result.y := y; end; function TMath.Vec3f(x, y, z: Single): TVec3f; begin Result.x := x; Result.y := y; Result.z := z; end; function TMath.Vec4f(x, y, z, w: Single): TVec4f; begin Result.x := x; Result.y := y; Result.z := z; Result.w := w; end; function TMath.Max(x, y: Single): Single; begin if x > y then Result := x else Result := y; end; function TMath.Min(x, y: Single): Single; begin if x < y then Result := x else Result := y; end; function TMath.Max(x, y: LongInt): LongInt; begin if x > y then Result := x else Result := y; end; function TMath.Min(x, y: LongInt): LongInt; begin if x < y then Result := x else Result := y; end; function TMath.Sign(x: Single): LongInt; begin if x > 0 then Result := 1 else if x < 0 then Result := -1 else Result := 0; end; function TMath.Ceil(const X: Extended): LongInt; begin Result := LongInt(Trunc(X)); if Frac(X) > 0 then Inc(Result); end; function TMath.Floor(const X: Extended): LongInt; begin Result := LongInt(Trunc(X)); if Frac(X) < 0 then Dec(Result); end; {$ENDREGION} // Utils ======================================================================= {$REGION 'TUtils'} function TUtils.IntToStr(Value: LongInt): string; var Res : string[32]; begin Str(Value, Res); Result := string(Res); end; function TUtils.StrToInt(const Str: string; Def: LongInt): LongInt; var Code : LongInt; begin Val(Str, Result, Code); if Code <> 0 then Result := Def; end; function TUtils.FloatToStr(Value: Single; Digits: LongInt = 6): string; var Res : string[32]; begin Str(Value:0:Digits, Res); Result := string(Res); end; function TUtils.StrToFloat(const Str: string; Def: Single): Single; var Code : LongInt; begin Val(Str, Result, Code); if Code <> 0 then Result := Def; end; function TUtils.BoolToStr(Value: Boolean): string; begin if Value then Result := 'true' else Result := 'false'; end; function TUtils.StrToBool(const Str: string; Def: Boolean = False): Boolean; var LStr : string; begin LStr := LowerCase(Str); if LStr = 'true' then Result := True else if LStr = 'false' then Result := False else Result := Def; end; function TUtils.LowerCase(const Str: string): string; begin Result := Str; // FIX! end; function TUtils.Trim(const Str: string): string; var i, j: LongInt; begin j := Length(Str); i := 1; while (i <= j) and (Str[i] <= ' ') do Inc(i); if i <= j then begin while Str[j] <= ' ' do Dec(j); Result := Copy(Str, i, j - i + 1); end else Result := ''; end; function TUtils.DeleteChars(const Str: string; Chars: TCharSet): string; var i, j : LongInt; begin j := 0; SetLength(Result, Length(Str)); for i := 1 to Length(Str) do if not (AnsiChar(Str[i]) in Chars) then begin Inc(j); Result[j] := Str[i]; end; SetLength(Result, j); end; function TUtils.ExtractFileDir(const Path: string): string; var i : Integer; begin for i := Length(Path) downto 1 do if (Path[i] = '\') or (Path[i] = '/') then begin Result := Copy(Path, 1, i); Exit; end; Result := ''; end; {$ENDREGION} {$REGION 'TResManager'} procedure TResManager.Init; begin Items := nil; Count := 0; end; function TResManager.Add(const Name: string; out Idx: LongInt): Boolean; var i : LongInt; begin Idx := -1; // Resource in array? Result := False; for i := 0 to Count - 1 do if Items[i].Name = Name then begin Idx := i; Inc(Items[Idx].Ref); Exit; end; // Get free slot Result := True; for i := 0 to Count - 1 do if Items[i].Ref <= 0 then begin Idx := i; Break; end; // Init slot if Idx = -1 then begin Idx := Count; Inc(Count); SetLength(Items, Count); end; Items[Idx].Name := Name; Items[Idx].Ref := 1; end; function TResManager.Delete(Idx: LongInt): Boolean; begin Dec(Items[Idx].Ref); Result := Items[Idx].Ref <= 0; end; {$ENDREGION} {$REGION 'TConfigFile'} procedure TConfigFile.Load(const FileName: string); var F : TextFile; Category, Line : string; CatId : LongInt; begin Data := nil; CatId := -1; AssignFile(F, FileName); Reset(F); while not Eof(F) do begin Readln(F, Line); if Line <> '' then if Line[1] <> '[' then begin if (Line[1] <> ';') and (CatId >= 0) then begin SetLength(Data[CatId].Params, Length(Data[CatId].Params) + 1); with Data[CatId], Params[Length(Params) - 1] do begin Name := Utils.Trim(Copy(Line, 1, Pos('=', Line) - 1)); Value := Utils.Trim(Copy(Line, Pos('=', Line) + 1, Length(Line))); end; end; end else begin Category := Utils.Trim(Utils.DeleteChars(Line, ['[', ']'])); CatId := Length(Data); SetLength(Data, CatId + 1); Data[CatId].Category := Category; end; end; CloseFile(F); end; procedure TConfigFile.Save(const FileName: string); var F : TextFile; i, j : LongInt; begin AssignFile(F, FileName); Rewrite(F); for i := 0 to Length(Data) - 1 do begin Writeln(F, '[', Data[i].Category, ']'); for j := 0 to Length(Data[i].Params) - 1 do Writeln(F, Data[i].Params[j].Name, ' = ', Data[i].Params[j].Value); Writeln(F); end; CloseFile(F); end; procedure TConfigFile.WriteStr(const Category, Name, Value: string); var i, j : LongInt; begin for i := 0 to Length(Data) - 1 do if Category = Data[i].Category then with Data[i] do begin for j := 0 to Length(Params) - 1 do if Params[j].Name = Name then begin Params[j].Value := Value; Exit; end; // Add new param SetLength(Params, Length(Params) + 1); Params[Length(Params) - 1].Name := Name; Params[Length(Params) - 1].Value := Value; Exit; end; // Add new category SetLength(Data, Length(Data) + 1); with Data[Length(Data) - 1] do begin SetLength(Params, 1); Params[0].Name := Name; Params[0].Value := Value; end; end; procedure TConfigFile.WriteInt(const Category, Name: string; Value: LongInt); begin WriteStr(Category, Name, Utils.IntToStr(Value)); end; procedure TConfigFile.WriteFloat(const Category, Name: string; Value: Single); begin WriteStr(Category, Name, Utils.FloatToStr(Value, 4)); end; procedure TConfigFile.WriteBool(const Category, Name: string; Value: Boolean); begin WriteStr(Category, Name, Utils.BoolToStr(Value)); end; function TConfigFile.ReadStr(const Category, Name: string; const Default: string = ''): string; var i, j : LongInt; begin Result := Default; for i := 0 to Length(Data) - 1 do if Category = Data[i].Category then for j := 0 to Length(Data[i].Params) - 1 do if Data[i].Params[j].Name = Name then begin Result := Data[i].Params[j].Value; Exit; end; end; function TConfigFile.ReadInt(const Category, Name: string; Default: LongInt): LongInt; begin Result := Utils.StrToInt(ReadStr(Category, Name, ''), Default); end; function TConfigFile.ReadFloat(const Category, Name: string; Default: Single): Single; begin Result := Utils.StrToFloat(ReadStr(Category, Name, ''), Default); end; function TConfigFile.ReadBool(const Category, Name: string; Default: Boolean): Boolean; begin Result := Utils.StrToBool(ReadStr(Category, Name, ''), Default); end; function TConfigFile.CategoryName(Idx: LongInt): string; begin if (Idx >= 0) and (Idx < Length(Data)) then Result := Data[Idx].Category else Result := ''; end; {$ENDREGION} // Display ===================================================================== {$REGION 'TDisplay'} {$IFDEF WINDOWS} function WndProc(Hwnd, Msg: LongWord; WParam, LParam: LongInt): LongInt; stdcall; function ToInputKey(Value: LongInt): TInputKey; begin case Value of 16..18 : // KK_SHIFT..KK_ALT Result := TInputKey(Ord(KK_SHIFT) + (Value - 16)); 32..40 : // KK_SPACE..KK_DOWN Result := TInputKey(Ord(KK_SPACE) + (Value - 32)); 48..57 : // numbers Result := TInputKey(Ord(KK_0) + (Value - 48)); 65..90 : // alphabet Result := TInputKey(Ord(KK_A) + (Value - 65)); 112..123 : // Functional Keys (F1..F12) Result := TInputKey(Ord(KK_F1) + (Value - 112)); 8 : Result := KK_BACK; 9 : Result := KK_TAB; 13 : Result := KK_ENTER; 27 : Result := KK_ESC; 45 : Result := KK_INS; 46 : Result := KK_DEL; 187 : Result := KK_PLUS; 189 : Result := KK_MINUS; 192 : Result := KK_TILDE; else Result := KK_NONE; end; end; begin Result := 0; case Msg of // Close window WM_DESTROY : Quit; // Activation / Deactivation WM_ACTIVATEAPP : with Display do begin FActive := Word(wParam) = 1; if FullScreen then begin FullScreen := FActive; if FActive then ShowWindow(Handle, SW_SHOW) else ShowWindow(Handle, SW_MINIMIZE); FFullScreen := True; end; Input.Reset; end; // Keyboard WM_KEYDOWN, WM_KEYDOWN + 1, WM_SYSKEYDOWN, WM_SYSKEYDOWN + 1 : begin Input.SetState(ToInputKey(WParam), (Msg = WM_KEYDOWN) or (Msg = WM_SYSKEYDOWN)); if (Msg = WM_SYSKEYDOWN) and (WParam = 13) then // Alt + Enter Display.FullScreen := not Display.FullScreen; end; // Mouse WM_LBUTTONDOWN, WM_LBUTTONDOWN + 1 : Input.SetState(KM_1, Msg = WM_LBUTTONDOWN); WM_RBUTTONDOWN, WM_RBUTTONDOWN + 1 : Input.SetState(KM_2, Msg = WM_RBUTTONDOWN); WM_MBUTTONDOWN, WM_MBUTTONDOWN + 1 : Input.SetState(KM_3, Msg = WM_MBUTTONDOWN); WM_MOUSEWHEEL : begin Inc(Input.Mouse.Delta.Wheel, SmallInt(wParam shr 16) div 120); Input.SetState(KM_WHUP, SmallInt(wParam shr 16) > 0); Input.SetState(KM_WHDN, SmallInt(wParam shr 16) < 0); end else Result := DefWindowProcA(Hwnd, Msg, WParam, LParam); end; end; {$ENDIF} {$IFDEF LINUX} procedure WndProc(var Event: TXEvent); function ToInputKey(Value: LongWord): TInputKey; const KeyCodes : array [KK_PLUS..KK_DEL] of Word = ($3D, $2D, $60, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $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, $FFBE, $FFBF, $FFC0, $FFC1, $FFC2, $FFC3, $FFC4, $FFC5, $FFC6, $FFC7, $FFC8, $FFC9, $FF1B, $FF0D, $FF08, $FF09, $FFE1, $FFE3, $FFE9, $20, $FF55, $FF56, $FF57, $FF50, $FF51, $FF52, $FF53, $FF54, $FF63, $FFFF); var Key : TInputKey; begin Result := KK_NONE; for Key := Low(KeyCodes) to High(KeyCodes) do if KeyCodes[Key] = Value then begin Result := Key; break; end end; var Key : TInputKey; begin case Event._type of // Close window ClientMessage : if (Event.xclient.message_type = WM_PROTOCOLS) and (LongWord(Event.xclient.data.l[0]) = WM_DESTROY) then Quit; // Activation / Deactivation FocusIn, FocusOut : with Display do if (Event.xwindow = Handle) and (Active <> (Event._type = FocusIn)) then begin FActive := Event._type = FocusIn; if FullScreen then begin FullScreen := FActive; FFullScreen := True; end; Input.Reset; end; // Keyboard KeyPress, KeyRelease : with Event.xkey do begin Input.SetState(ToInputKey(XLookupKeysym(@Event, 0)), Event._type = KeyPress); if (state and 8 <> 0) and (KeyCode = 36) and (Event._type = KeyPress) then // Alt + Enter Display.FullScreen := not Display.FullScreen; end; // Mouse ButtonPress, ButtonRelease : begin case Event.xkey.KeyCode of 1 : Key := KM_1; 2 : Key := KM_3; 3 : Key := KM_2; 4 : Key := KM_WHUP; 5 : Key := KM_WHDN; else Key := KK_NONE; end; Input.SetState(Key, Event._type = ButtonPress); if Event._type = ButtonPress then case Key of KM_WHUP : Inc(Input.Mouse.Delta.Wheel); KM_WHDN : Dec(Input.Mouse.Delta.Wheel); end; end; end; end; {$ENDIF} procedure TDisplay.Init; {$IFDEF WINDOWS} type TwglChoosePixelFormatARB = function (DC: LongWord; const piList, pfFList: Pointer; nMaxFormats: LongWord; piFormats, nNumFormats: Pointer): Boolean; stdcall; const AttribF : array [0..1] of Single = (0, 0); AttribI : array [0..17] of TGLConst = ( WGL_SAMPLES, GL_ZERO, WGL_DRAW_TO_WINDOW, GL_TRUE, WGL_SUPPORT_OPENGL, GL_TRUE, WGL_SAMPLE_BUFFERS, GL_TRUE, WGL_DOUBLE_BUFFER, GL_TRUE, WGL_COLOR_BITS, TGLConst(32), WGL_DEPTH_BITS, TGLConst(24), WGL_STENCIL_BITS, TGLConst(8), GL_ZERO, GL_ZERO); var WndClass : TWndClassEx; PFD : TPixelFormatDescriptor; ChoisePF : TwglChoosePixelFormatARB; PFIdx : LongInt; PFCount : LongWord; begin FWidth := 800; FHeight := 600; FCaption := 'CoreX'; // Init structures FillChar(WndClass, SizeOf(WndClass), 0); with WndClass do begin cbSize := SizeOf(WndClass); lpfnWndProc := @WndProc; hCursor := 65553; hbrBackground := 9; lpszClassName := WND_CLASS; end; FillChar(PFD, SizeOf(PFD), 0); with PFD do begin nSize := SizeOf(PFD); nVersion := 1; dwFlags := $25; cColorBits := 32; cDepthBits := 24; cStencilBits := 8; end; PFIdx := -1; // Choise multisample format (OpenGL AntiAliasing) if FAntiAliasing <> aa0x then begin LongWord(Pointer(@AttribI[1])^) := 1 shl (Ord(FAntiAliasing) - 1); // Set num WGL_SAMPLES // Temp window Handle := CreateWindowExA(0, 'EDIT', nil, 0, 0, 0, 0, 0, 0, 0, 0, nil); DC := GetDC(Handle); SetPixelFormat(DC, ChoosePixelFormat(DC, @PFD), @PFD); RC := wglCreateContext(DC); wglMakeCurrent(DC, RC); ChoisePF := TwglChoosePixelFormatARB(wglGetProcAddress('wglChoosePixelFormatARB')); if @ChoisePF <> nil then ChoisePF(DC, @AttribI, @AttribF, 1, @PFIdx, @PFCount); wglMakeCurrent(0, 0); wglDeleteContext(RC); ReleaseDC(Handle, DC); DestroyWindow(Handle); end; // Window RegisterClassExA(WndClass); Handle := CreateWindowExA(0, WND_CLASS, PAnsiChar(AnsiString(FCaption)), 0, 0, 0, 0, 0, 0, 0, HInstance, nil); SendMessageA(Handle, WM_SETICON, 1, LoadIconA(HInstance, 'MAINICON')); // OpenGL DC := GetDC(Handle); if PFIdx = -1 then SetPixelFormat(DC, ChoosePixelFormat(DC, @PFD), @PFD) else SetPixelFormat(DC, PFIdx, @PFD); RC := wglCreateContext(DC); wglMakeCurrent(DC, RC); Render.Init; FFPSTime := Render.Time; end; {$ENDIF} {$IFDEF LINUX} const XGLAttr : array [0..11] of LongWord = ( GLX_SAMPLES, 0, GLX_RGBA, 1, GLX_BUFFER_SIZE, 32, GLX_DOUBLEBUFFER, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8, 0); var Rot : Word; Pixmap : LongWord; Color : TXColor; begin FWidth := 800; FHeight := 600; FCaption := 'CoreX'; // Init objects XDisp := XOpenDisplay(nil); XScr := XDefaultScreen(XDisp); LongWord(Pointer(@XGLAttr[1])^) := 1 shl (Ord(FAntiAliasing) - 1); // Set num GLX_SAMPLES XVisual := glXChooseVisual(XDisp, XScr, @XGLAttr); XRoot := XRootWindow(XDisp, XVisual^.screen); Pixmap := XCreatePixmap(XDisp, XRoot, 1, 1, 1); FillChar(Color, SizeOf(Color), 0); XWndAttr.cursor := 0;//XCreatePixmapCursor(XDisp, Pixmap, Pixmap, @Color, @Color, 0, 0); XWndAttr.background_pixel := XBlackPixel(XDisp, XScr); XWndAttr.colormap := XCreateColormap(XDisp, XRoot, XVisual^.visual, 0); XWndAttr.event_mask := KEYBOARD_MASK or MOUSE_MASK or FocusChangeMask; // Set client messages WM_DESTROY := XInternAtom(XDisp, 'WM_DELETE_WINDOW', True); WM_PROTOCOLS := XInternAtom(XDisp, 'WM_PROTOCOLS', True); // OpenGL Init XContext := glXCreateContext(XDisp, XVisual, nil, True); // Screen Settings ScrSizes := XRRSizes(XDisp, XRRRootToScreen(XDisp, XRoot), @SizesCount); ScrConfig := XRRGetScreenInfo(XDisp, XRoot); DefSizeIdx := XRRConfigCurrentConfiguration(ScrConfig, @Rot); Render.Init; FFPSTime := Render.Time; end; {$ENDIF} procedure TDisplay.Free; {$IFDEF WINDOWS} begin Render.Free; wglMakeCurrent(0, 0); wglDeleteContext(RC); ReleaseDC(Handle, DC); DestroyWindow(Handle); UnregisterClassA(WND_CLASS, HInstance); end; {$ENDIF} {$IFDEF LINUX} begin // Restore video mode if FullScreen then FullScreen := False; XRRFreeScreenConfigInfo(ScrConfig); Render.Free; // OpenGL glXMakeCurrent(XDisp, 0, nil); XFree(XVisual); glXDestroyContext(XDisp, XContext); // Window XDestroyWindow(XDisp, Handle); XCloseDisplay(XDisp); end; {$ENDIF} procedure TDisplay.Update; {$IFDEF WINDOWS} var Msg : TMsg; begin while PeekMessageA(Msg, 0, 0, 0, 1) do begin TranslateMessage(Msg); DispatchMessageA(Msg); end; end; {$ENDIF} {$IFDEF LINUX} var Event : TXEvent; begin while XPending(XDisp) <> 0 do begin XNextEvent(XDisp, @Event); WndProc(Event); end; end; {$ENDIF} procedure TDisplay.Restore; {$IFDEF WINDOWS} var Style : LongWord; Rect : TRect; begin // Change main window style if FullScreen then Style := 0 else Style := WS_CAPTION or WS_SYSMENU or WS_MINIMIZEBOX; SetWindowLongA(Handle, GWL_STYLE, Style or WS_VISIBLE); Rect.Left := 0; Rect.Top := 0; Rect.Right := Width; Rect.Bottom := Height; AdjustWindowRect(Rect, Style, False); with Rect do SetWindowPos(Handle, 0, 0, 0, Right - Left, Bottom - Top, $220); gl.Viewport(0, 0, Width, Height); VSync := FVSync; Swap; Swap; end; {$ENDIF} {$IFDEF LINUX} var Mask : LongWord; XSizeHint : TXSizeHints; begin // Recreate window XUngrabKeyboard(XDisp, 0); XUngrabPointer(XDisp, 0); glXMakeCurrent(XDisp, 0, nil); if Handle <> 0 then XDestroyWindow(XDisp, Handle); glXWaitX; XWndAttr.override_redirect := FFullScreen; Mask := CWColormap or CWEventMask or CWCursor; if FFullScreen then Mask := Mask or CWOverrideRedirect; // Create new window Handle := XCreateWindow(XDisp, XRoot, 0, 0, Width, Height, 0, XVisual^.depth, 1, XVisual^.visual, Mask, @XWndAttr); // Change size XSizeHint.flags := PPosition or PMinSize or PMaxSize; XSizeHint.x := 0; XSizeHint.y := 0; XSizeHint.min_w := Width; XSizeHint.min_h := Height; XSizeHint.max_w := Width; XSizeHint.max_h := Height; XSetWMNormalHints(XDisp, Handle, @XSizeHint); XSetWMProtocols(XDisp, Handle, @WM_DESTROY, 1); Caption := FCaption; glXMakeCurrent(XDisp, Handle, XContext); XMapWindow(XDisp, Handle); glXWaitX; if FFullScreen Then begin XGrabKeyboard(XDisp, Handle, True, 1, 1, 0); XGrabPointer(XDisp, Handle, True, ButtonPressMask, 1, 1, Handle, 0, 0); end; gl.Viewport(0, 0, Width, Height); VSync := FVSync; Swap; Swap; end; {$ENDIF} procedure TDisplay.SetFullScreen(Value: Boolean); {$IFDEF WINDOWS} var DevMode : TDeviceMode; begin if Value then begin FillChar(DevMode, SizeOf(DevMode), 0); DevMode.dmSize := SizeOf(DevMode); EnumDisplaySettingsA(nil, 0, @DevMode); with DevMode do begin dmPelsWidth := Width; dmPelsHeight := Height; dmBitsPerPel := 32; dmFields := $1C0000; // DM_BITSPERPEL or DM_PELSWIDTH or DM_PELSHEIGHT; end; ChangeDisplaySettingsA(@DevMode, $04); // CDS_FULLSCREEN end else ChangeDisplaySettingsA(nil, 0); FFullScreen := Value; Restore; end; {$ENDIF} {$IFDEF LINUX} var i, SizeIdx : LongInt; begin if Value then begin // mode search SizeIdx := -1; for i := 0 to SizesCount - 1 do if (ScrSizes[i].Width = Width) and (ScrSizes[i].Height = Height) then begin SizeIdx := i; break; end; end else SizeIdx := DefSizeIdx; // set current video mode if SizeIdx <> -1 then XRRSetScreenConfigAndRate(XDisp, ScrConfig, XRoot, SizeIdx, 1, 0, 0); FFullScreen := Value; Restore; end; {$ENDIF} procedure TDisplay.SetVSync(Value: Boolean); begin FVSync := Value; if @gl.SwapInterval <> nil then gl.SwapInterval(Ord(FVSync)); end; procedure TDisplay.SetCaption(const Value: string); begin FCaption := Value; {$IFDEF WINDOWS} SetWindowTextA(Handle, PAnsiChar(AnsiString(Value))); {$ENDIF} {$IFDEF LINUX} XStoreName(XDisp, Handle, PAnsiChar(Value)); {$ENDIF} end; procedure TDisplay.Resize(W, H: LongInt); begin FWidth := W; FHeight := H; FullScreen := FullScreen; // Resize screen end; procedure TDisplay.Swap; begin {$IFDEF WINDOWS} SwapBuffers(DC); {$ENDIF} {$IFDEF LINUX} glXSwapBuffers(XDisp, Handle); {$ENDIF} Inc(FFPSIdx); if Render.Time - FFPSTime >= 1000 then begin FFPS := FFPSIdx; FFPSIdx := 0; FFPSTime := Render.Time; Caption := 'CoreX [FPS: ' + Utils.IntToStr(FPS) + ']'; end; end; {$ENDREGION} // Input ======================================================================= {$REGION 'TInput'} procedure TInput.Init; begin {$IFDEF WINDOWS} // Initialize Joystick Joy.FReady := False; if (joyGetNumDevs <> 0) and (joyGetDevCapsA(0, @JoyCaps, SizeOf(JoyCaps)) = 0) then with JoyCaps, JoyInfo do begin dwSize := SizeOf(JoyInfo); dwFlags := $08FF; // JOY_RETURNALL or JOY_USEDEADZONE; if wCaps and JOYCAPS_POVCTS > 0 then dwFlags := dwFlags or JOY_RETURNPOVCTS; Joy.FReady := joyGetPosEx(0, @JoyInfo) = 0; end; {$ENDIF} // Reset key states Reset; end; procedure TInput.Free; begin // end; procedure TInput.Reset; begin FillChar(FDown, SizeOf(FDown), False); Update; end; procedure TInput.Update; var {$IFDEF WINDOWS} Rect : TRect; Pos : TPoint; CPos : TPoint; i : LongInt; JKey : TInputKey; JDown : Boolean; function AxisValue(Value, Min, Max: LongWord): LongInt; begin Result := Round((Value + Min) / (Max - Min) * 200 - 100); end; {$ENDIF} {$IFDEF LINUX} WRoot, WChild, Mask : LongWord; X, Y, rX, rY : longInt; {$ENDIF} begin FillChar(FHit, SizeOf(FHit), False); FLastKey := KK_NONE; Mouse.Delta.Wheel := 0; SetState(KM_WHUP, False); SetState(KM_WHDN, False); {$IFDEF WINDOWS} // Mouse GetWindowRect(Display.Handle, Rect); GetCursorPos(Pos); if not FCapture then begin // Calc mouse cursor pos (Client Space) ScreenToClient(Display.Handle, Pos); Mouse.Delta.X := Pos.X - Mouse.Pos.X; Mouse.Delta.Y := Pos.Y - Mouse.Pos.Y; Mouse.Pos.X := Pos.X; Mouse.Pos.Y := Pos.Y; end else if Display.Active then // Main window active? begin // Window Center Pos (Screen Space) CPos.X := (Rect.Right - Rect.Left) div 2; CPos.Y := (Rect.Bottom - Rect.Top) div 2; // Calc mouse cursor position delta Mouse.Delta.X := Pos.X - CPos.X; Mouse.Delta.Y := Pos.Y - CPos.Y; // Centering cursor if (Mouse.Delta.X <> 0) or (Mouse.Delta.Y <> 0) then SetCursorPos(Rect.Left + CPos.X, Rect.Top + CPos.Y); Inc(Mouse.Pos.X, Mouse.Delta.X); Inc(Mouse.Pos.Y, Mouse.Delta.Y); end else begin // No delta while window is not active Mouse.Delta.X := 0; Mouse.Delta.Y := 0; end; // Joystick with Joy do begin FillChar(Axis, SizeOf(Axis), 0); POV := -1; if Ready and (joyGetPosEx(0, @JoyInfo) = 0) then with JoyCaps, JoyInfo, Axis do begin // Axis X := AxisValue(wXpos, wXmin, wXmax); Y := AxisValue(wYpos, wYmin, wYmax); if wCaps and JOYCAPS_HASZ > 0 then Z := AxisValue(wZpos, wZmin, wZmax); if wCaps and JOYCAPS_HASR > 0 then R := AxisValue(wRpos, wRmin, wRmax); if wCaps and JOYCAPS_HASU > 0 then U := AxisValue(wUpos, wUmin, wUmax); if wCaps and JOYCAPS_HASV > 0 then V := AxisValue(wVpos, wVmin, wVmax); // Point-Of-View if (wCaps and JOYCAPS_HASPOV > 0) and (dwPOV and $FFFF <> $FFFF) then POV := dwPOV and $FFFF / 100; // Buttons for i := 0 to wNumButtons - 1 do begin JKey := TInputKey(Ord(KJ_1) + i); JDown := Input.Down[JKey]; if (wButtons and (1 shl i) <> 0) xor JDown then Input.SetState(JKey, not JDown); end; end; end; {$ENDIF} {$IFDEF LINUX} with Display do begin XQueryPointer(XDisp, Handle, @WRoot, @WChild, @rX, @rY, @X, @Y, @Mask); if not FCapture then begin Mouse.Delta.X := X - Mouse.Pos.X; Mouse.Delta.Y := Y - Mouse.Pos.Y; Mouse.Pos.X := X; Mouse.Pos.Y := Y; end else if Active then begin Mouse.Delta.X := X - Width div 2; Mouse.Delta.Y := Y - Height div 2; XWarpPointer(XDisp, XScr, Handle, 0, 0, 0, 0, Width div 2, Height div 2); Inc(Mouse.Pos.X, Mouse.Delta.X); Inc(Mouse.Pos.Y, Mouse.Delta.Y); end else begin Mouse.Delta.X := 0; Mouse.Delta.Y := 0; end; end; {$ENDIF} end; function TInput.GetDown(InputKey: TInputKey): Boolean; begin Result := FDown[InputKey]; end; function TInput.GetHit(InputKey: TInputKey): Boolean; begin Result := FHit[InputKey]; end; procedure TInput.SetState(InputKey: TInputKey; Value: Boolean); begin FDown[InputKey] := Value; if not Value then begin FHit[InputKey] := True; FLastKey := InputKey; end; end; procedure TInput.SetCapture(Value: Boolean); begin FCapture := Value; {$IFDEF WINDOWS} while ShowCursor(not FCapture) = 0 do; {$ENDIF} end; {$ENDREGION} // Render ====================================================================== {$REGION 'TRender'} procedure TRender.Init; begin gl.Init; {$IFDEF WINDOWS} QueryPerformanceFrequency(TimeFreq); {$ENDIF} Display.Restore; Blend := btNormal; ResManager.Init; gl.Enable(GL_TEXTURE_2D); Writeln('GL_VENDOR : ', gl.GetString(GL_VENDOR)); Writeln('GL_RENDERER : ', gl.GetString(GL_RENDERER)); Writeln('GL_VERSION : ', gl.GetString(GL_VERSION)); end; procedure TRender.Free; begin gl.Free; end; function TRender.GeLongWord: LongInt; {$IFDEF WINDOWS} var Count : Int64; begin QueryPerformanceCounter(Count); Result := Trunc(1000 * (Count / TimeFreq)); end; {$ENDIF} {$IFDEF LINUX} var tv : TTimeVal; begin gettimeofday(tv, nil); Result := 1000 * tv.tv_sec + tv.tv_usec div 1000; end; {$ENDIF} procedure TRender.SetBlend(Value: TBlendType); begin gl.Enable(GL_BLEND); case Value of btNormal : gl.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); btAdd : gl.BlendFunc(GL_SRC_ALPHA, GL_ONE); btMult : gl.BlendFunc(GL_ZERO, GL_SRC_COLOR); else gl.Disable(GL_BLEND); end; end; procedure TRender.SetDepthTest(Value: Boolean); begin if Value then gl.Enable(GL_DEPTH_TEST) else gl.Disable(GL_DEPTH_TEST); end; procedure TRender.SetDepthWrite(Value: Boolean); begin gl.DepthMask(Value); end; procedure TRender.Clear(Color, Depth: Boolean); var Mask : LongWord; begin Mask := 0; if Color then Mask := Mask or Ord(GL_COLOR_BUFFER_BIT); if Depth then Mask := Mask or Ord(GL_DEPTH_BUFFER_BIT); gl.Clear(TGLConst(Mask)); end; procedure TRender.Set2D(Width, Height: LongInt); begin gl.MatrixMode(GL_PROJECTION); gl.LoadIdentity; gl.Ortho(0, Width, 0, Height, -1, 1); gl.MatrixMode(GL_MODELVIEW); gl.LoadIdentity; end; procedure TRender.Set3D(FOV, zNear, zFar: Single); var x, y : Single; begin x := FOV * pi / 180 * 0.5; y := zNear * Sin(x) / Cos(x); x := y * (Display.Width / Display.Height); gl.MatrixMode(GL_PROJECTION); gl.LoadIdentity; gl.Frustum(-x, x, -y, y, zNear, zFar); gl.MatrixMode(GL_MODELVIEW); gl.LoadIdentity; end; procedure TRender.Quad(x, y, w, h, s, t, sw, th: Single); var v : array [0..3] of TVec4f; begin v[0] := Math.Vec4f(x, y, s, t + th); v[1] := Math.Vec4f(x + w, y, s + sw, v[0].w); v[2] := Math.Vec4f(v[1].x, y + h, v[1].z, t); v[3] := Math.Vec4f(x, v[2].y, s, t); gl.Beginp(GL_QUADS); gl.TexCoord2fv(@v[0].z); gl.Vertex2fv(@v[0].x); gl.TexCoord2fv(@v[1].z); gl.Vertex2fv(@v[1].x); gl.TexCoord2fv(@v[2].z); gl.Vertex2fv(@v[2].x); gl.TexCoord2fv(@v[3].z); gl.Vertex2fv(@v[3].x); gl.Endp; end; {$ENDREGION} // Texture ===================================================================== {$REGION 'TTexture'} procedure TTexture.Load(const FileName: string); const DDPF_ALPHAPIXELS = $01; DDPF_FOURCC = $04; var Stream : File; i, w, h : LongInt; Size : LongInt; Data : Pointer; f, c : TGLConst; DDS : record Magic : LongWord; Size : LongWord; Flags : LongWord; Height : LongInt; Width : LongInt; POLSize : LongInt; Depth : LongInt; MipMapCount : LongInt; SomeData1 : array [0..11] of LongWord; pfFlags : LongWord; pfFourCC : array [0..3] of AnsiChar; pfRGBbpp : LongInt; SomeData2 : array [0..8] of LongWord; end; begin if Render.ResManager.Add(FileName, ResIdx) then begin AssignFile(Stream, FileName); Reset(Stream, 1); BlockRead(Stream, DDS, SizeOf(DDS)); Data := GetMemory(DDS.POLSize); with Render.ResManager.Items[ResIdx] do begin Width := DDS.Width; Height := DDS.Height; gl.GenTextures(1, @ID); gl.BindTexture(GL_TEXTURE_2D, ID); end; gl.TexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_FALSE); // Select OpenGL texture format DDS.pfRGBbpp := DDS.POLSize * 8 div (DDS.Width * DDS.Height); f := GL_RGB8; c := GL_BGR; if DDS.pfFlags and DDPF_FOURCC > 0 then case DDS.pfFourCC[3] of '1' : f := GL_COMPRESSED_RGBA_S3TC_DXT1; '3' : f := GL_COMPRESSED_RGBA_S3TC_DXT3; '5' : f := GL_COMPRESSED_RGBA_S3TC_DXT5; end else if DDS.pfFlags and DDPF_ALPHAPIXELS > 0 then begin f := GL_RGBA8; c := GL_BGRA; end; for i := 0 to Math.Max(DDS.MipMapCount, 1) - 1 do begin w := Math.Max(DDS.Width shr i, 1); h := Math.Max(DDS.Height shr i, 1); Size := (w * h * DDS.pfRGBbpp) div 8; BlockRead(Stream, Data^, Size); if (DDS.pfFlags and DDPF_FOURCC) > 0 then begin if (w < 4) or (h < 4) then begin DDS.MipMapCount := i; Break; end; gl.CompressedTexImage2D(GL_TEXTURE_2D, i, f, w, h, 0, Size, Data) end else gl.TexImage2D(GL_TEXTURE_2D, i, f, w, h, 0, c, GL_UNSIGNED_BYTE, Data); end; FreeMemory(Data); CloseFile(Stream); // Filter gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if DDS.MipMapCount > 0 then begin gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, TGLConst(DDS.MipMapCount - 1)); end else gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); end; with Render.ResManager.Items[ResIdx] do begin Self.Width := Width; Self.Height := Height; end; end; procedure TTexture.Free; begin if Render.ResManager.Delete(ResIdx) then gl.DeleteTextures(1, @Render.ResManager.Items[ResIdx].ID); end; procedure TTexture.Enable(Channel: LongInt); begin if @gl.ActiveTexture <> nil then gl.ActiveTexture(TGLConst(Ord(GL_TEXTURE0) + Channel)); gl.BindTexture(GL_TEXTURE_2D, Render.ResManager.Items[ResIdx].ID); end; {$ENDREGION} // Sprite ====================================================================== {$REGION 'TSpriteAnimList'} function TSpriteAnimList.GetItem(Idx: LongInt): TSpriteAnim; const NullAnim : TSpriteAnim = (FName: ''; FFrames: 1; FX: 0; FY: 0; FWidth: 1; FHeight: 1; FCX: 0; FCY: 0; FFPS: 1); begin if (Idx >= 0) and (Idx < Count) then Result := FItems[Idx] else Result := NullAnim; end; procedure TSpriteAnimList.Add(const Name: string; Frames, X, Y, W, H, Cols, CX, CY, FPS: LongInt); begin SetLength(FItems, FCount + 1); FItems[FCount].FName := Name; FItems[FCount].FFrames := Frames; FItems[FCount].FX := X; FItems[FCount].FY := Y; FItems[FCount].FWidth := W; FItems[FCount].FHeight := H; FItems[FCount].FCols := Cols; FItems[FCount].FCX := CX; FItems[FCount].FCY := CY; FItems[FCount].FFPS := FPS; Inc(FCount); end; function TSpriteAnimList.IndexOf(const Name: string): LongInt; var i : LongInt; begin for i := 0 to Count - 1 do if FItems[i].Name = Name then begin Result := i; Exit; end; Result := -1; end; {$ENDREGION} {$REGION 'TSprite'} function TSprite.GetPlaying: Boolean; begin Result := False; if (CurIndex < 0) or (not FPlaying) then Exit; with Anim.Items[CurIndex] do FPlaying := FLoop or ((Render.Time - StarLongWord) div (1000 div FPS) < Frames); Result := FPlaying; end; procedure TSprite.Load(const FileName: string); const BlendStr : array [TBlendType] of string = ('none', 'normal', 'add', 'mult'); var Cfg : TConfigFile; i : Integer; b : TBlendType; Cat : string; function Param(const Name: string; Def: Integer): Integer; begin Result := Cfg.ReadInt(Cat, Name, Def); end; begin CurIndex := -1; FPlaying := False; Pos := Math.Vec2f(0, 0); Scale := Math.Vec2f(1, 1); Angle := 0; Cfg.Load(FileName); i := 0; while Cfg.CategoryName(i) <> '' do begin Cat := Cfg.CategoryName(i); if Cat <> 'sprite' then Anim.Add(Cat, Param('Frames', 1), Param('FramesX', 0), Param('FramesY', 0), Param('FramesWidth', 1), Param('FramesHeight', 1), Param('Cols', Param('Frames', 1)), Param('CenterX', 0), Param('CenterY', 0), Param('FPS', 1)); Inc(i); end; Texture.Load(Cfg.ReadStr('sprite', 'Texture', '')); Blend := btNormal; Cat := Cfg.ReadStr('sprite', 'Blend', 'normal'); for b := Low(b) to High(b) do if BlendStr[b] = Cat then begin Blend := b; break; end; end; procedure TSprite.Free; begin Texture.Free; end; procedure TSprite.Play(const AnimName: string; Loop: Boolean); var NewIndex : LongInt; begin NewIndex := Anim.IndexOf(AnimName); if (NewIndex <> CurIndex) or (not FPlaying) then begin FLoop := Loop; StarLongWord := Render.Time; CurIndex := NewIndex; end; FPlaying := True; end; procedure TSprite.Stop; begin FPlaying := False; end; procedure TSprite.Draw; var CurFrame : LongInt; fw, fh : Single; begin if CurIndex < 0 then Exit; Texture.Enable; with Anim.Items[CurIndex] do begin if Playing then CurFrame := (Render.Time - StarLongWord) div (1000 div FPS) mod Frames else CurFrame := 0; fw := Width/Texture.Width; fh := Height/Texture.Height; Render.Blend := Blend; Render.Quad(Pos.X - CenterX * Scale.x, Pos.Y - CenterY * Scale.y, Width * Scale.x, Height * Scale.y, X/Texture.Width + CurFrame mod Cols * fw, CurFrame div Cols * fh, fw, fh); end; end; {$ENDREGION} // GL ========================================================================== {$REGION 'TGL'} procedure TGL.Init; type TProcArray = array [-1..0] of Pointer; const ProcName : array [0..(SizeOf(TGL) - SizeOf(Lib)) div 4 - 1] of PAnsiChar = ( {$IFDEF WINDOWS} 'wglGetProcAddress', 'wglSwapIntervalEXT', {$ENDIF} {$IFDEF LINUX} 'glXGetProcAddress', 'glXSwapIntervalSGI', {$ENDIF} {$IFDEF MACOS} 'aglGetProcAddress', 'aglSetInteger', {$ENDIF} 'glGetString', 'glPolygonMode', 'glGenTextures', 'glDeleteTextures', 'glBindTexture', 'glTexParameteri', 'glTexImage2D', 'glCompressedTexImage2DARB', 'glActiveTextureARB', 'glClientActiveTextureARB', 'glClear', 'glClearColor', 'glColorMask', 'glDepthMask', 'glStencilMask', 'glEnable', 'glDisable', 'glBlendFunc', 'glStencilFunc', 'glDepthFunc', 'glStencilOp', 'glViewport', 'glBegin', 'glEnd', 'glVertex2fv', 'glVertex3fv', 'glTexCoord2fv', 'glEnableClientState', 'glDisableClientState', 'glDrawElements', 'glDrawArrays', 'glColorPointer', 'glVertexPointer', 'glTexCoordPointer', 'glNormalPointer', 'glMatrixMode', 'glLoadIdentity', 'glLoadMatrixf', 'glMultMatrixf', 'glPushMatrix', 'glPopMatrix', 'glScalef', 'glTranslatef', 'glRotatef', 'glOrtho', 'glFrustum' ); var i : LongInt; Proc : ^TProcArray; begin Lib := LoadLibraryA(opengl32); if Lib <> 0 then begin Proc := @Self; Proc^[0] := GetProcAddress(Lib, ProcName[0]); // gl.GetProc for i := 1 to High(ProcName) do begin Proc^[i] := GetProc(ProcName[i]); if Proc^[i] = nil then Proc^[i] := GetProcAddress(Lib, ProcName[i]); {$IFDEF DEBUG} if Proc^[i] = nil then Writeln('- ', ProcName[i]); {$ENDIF} end; end; end; procedure TGL.Free; begin FreeLibrary(Lib); end; {$ENDREGION} // CoreX ======================================================================= {$REGION 'CoreX'} procedure Start(PInit, PFree, PRender: TCoreProc); begin chdir(Utils.ExtractFileDir(ParamStr(0))); Display.Init; Input.Init; PInit; while not Display.FQuit do begin Input.Update; Display.Update; Render.FDeltaTime := (Render.Time - Render.OldTime) / 1000; Render.OldTime := Render.Time; PRender; Display.Swap; end; PFree; Input.Free; Display.Free; end; procedure Quit; begin Display.FQuit := True; end; {$ENDREGION} end.
object MMExportForm: TMMExportForm Left = 43 Top = 13 Caption = 'Export to Milling Machine' ClientHeight = 220 ClientWidth = 456 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = UserCreate PixelsPerInch = 96 TextHeight = 13 object GroupBox4: TGroupBox Left = 230 Top = 8 Width = 219 Height = 156 Caption = 'Export Options' TabOrder = 1 object Label2: TLabel Left = 7 Top = 112 Width = 107 Height = 13 Caption = 'Machine Configuration' end object EnableTopLayer: TCheckBox Left = 6 Top = 17 Width = 66 Height = 17 Hint = 'Enable/Disable the Top Copper Layer for export' Caption = 'Top Layer' Checked = True ParentShowHint = False ShowHint = True State = cbChecked TabOrder = 0 end object EnableBottomLayer: TCheckBox Left = 6 Top = 41 Width = 83 Height = 17 Hint = 'Enable/Disable the Bottom Copper Layer for export' Caption = 'Bottom Layer' Checked = True ParentShowHint = False ShowHint = True State = cbChecked TabOrder = 1 end object EnableDrill: TCheckBox Left = 6 Top = 65 Width = 38 Height = 17 Hint = 'Enable/Disable Drilling data to be exported' BiDiMode = bdLeftToRight Caption = 'Drill' Checked = True ParentBiDiMode = False ParentShowHint = False ShowHint = True State = cbChecked TabOrder = 2 OnClick = EnableDrillClick end object DrillOption: TComboBox Left = 19 Top = 84 Width = 100 Height = 21 Hint = 'spot drill holes as part of top layer export or export full dril' + 'l files for all hole sizes' Style = csDropDownList ItemHeight = 13 ParentShowHint = False ShowHint = True TabOrder = 3 end object MMName: TComboBox Left = 6 Top = 126 Width = 185 Height = 21 Hint = 'Export milling data using this machine'#39's configuration settings' Style = csDropDownList ItemHeight = 13 ParentShowHint = False ShowHint = True Sorted = True TabOrder = 4 end object btnMachineConfig: TButton Left = 194 Top = 127 Width = 19 Height = 19 Hint = 'Add/Delete/Edit machine configuration settings' Caption = '...' ParentShowHint = False ShowHint = True TabOrder = 5 OnClick = btnMachineConfigClick end end object btnExport: TButton Left = 294 Top = 174 Width = 75 Height = 25 Caption = 'Export' TabOrder = 2 OnClick = btnExportClick end object btnExit: TButton Left = 374 Top = 174 Width = 75 Height = 25 Caption = 'Exit' TabOrder = 3 OnClick = btnExitClick end object GroupBox5: TGroupBox Left = 8 Top = 8 Width = 219 Height = 200 Caption = 'Tool Settings' TabOrder = 0 object Label6: TLabel Left = 8 Top = 19 Width = 77 Height = 13 Alignment = taRightJustify Caption = 'Cutter Diameter' end object Label7: TLabel Left = 170 Top = 19 Width = 16 Height = 13 Caption = 'mm' end object Label1: TLabel Left = 21 Top = 40 Width = 63 Height = 13 Alignment = taRightJustify Caption = 'Cutter Depth' end object Label26: TLabel Left = 170 Top = 41 Width = 16 Height = 13 Caption = 'mm' end object Label27: TLabel Left = 25 Top = 106 Width = 60 Height = 13 Alignment = taRightJustify Caption = 'XY-Feedrate' end object Label28: TLabel Left = 170 Top = 107 Width = 36 Height = 13 Caption = 'mm/sec' end object Label29: TLabel Left = 31 Top = 128 Width = 54 Height = 13 Alignment = taRightJustify Caption = 'Z-Feedrate' end object Label30: TLabel Left = 170 Top = 129 Width = 36 Height = 13 Caption = 'mm/sec' end object Label31: TLabel Left = 28 Top = 84 Width = 56 Height = 13 Alignment = taRightJustify Caption = 'Pass Height' end object Label32: TLabel Left = 170 Top = 85 Width = 16 Height = 13 Caption = 'mm' end object Label3: TLabel Left = 35 Top = 62 Width = 49 Height = 13 Alignment = taRightJustify Caption = 'Drill Depth' end object Label4: TLabel Left = 170 Top = 63 Width = 16 Height = 13 Caption = 'mm' end object Label5: TLabel Left = 47 Top = 151 Width = 38 Height = 13 Alignment = taRightJustify Caption = 'Mill RPM' end object Label8: TLabel Left = 170 Top = 152 Width = 21 Height = 13 Caption = 'RPM' end object Label9: TLabel Left = 35 Top = 174 Width = 50 Height = 13 Alignment = taRightJustify Caption = 'Drill Speed' end object Label10: TLabel Left = 170 Top = 175 Width = 21 Height = 13 Caption = 'RPM' end object CutterDiameter: TEdit Left = 87 Top = 15 Width = 81 Height = 21 Hint = 'Width of cutting tools sharpest point' ParentShowHint = False ShowHint = True TabOrder = 0 Text = 'CutterDiameter' OnKeyPress = TEdit_PosReal_OnKeyPress end object CutterDepth: TEdit Left = 87 Top = 37 Width = 81 Height = 21 Hint = 'Depth to mill the PCB to' ParentShowHint = False ShowHint = True TabOrder = 1 Text = 'CutterDepth' OnKeyPress = TEdit_PosReal_OnKeyPress end object XYFeedrate: TEdit Left = 87 Top = 103 Width = 81 Height = 21 Hint = 'Tool travel speed in the XY (horizontal) plane' ParentShowHint = False ShowHint = True TabOrder = 4 Text = 'XYFeedrate' OnKeyPress = TEdit_PosReal_OnKeyPress end object ZFeedrate: TEdit Left = 87 Top = 125 Width = 81 Height = 21 Hint = 'Tool travel speed in the Z plane' ParentShowHint = False ShowHint = True TabOrder = 5 Text = 'ZFeedrate' OnKeyPress = TEdit_PosReal_OnKeyPress end object PassHeight: TEdit Left = 87 Top = 81 Width = 81 Height = 21 Hint = 'Height tool will move to in the '#39'Pen Up'#39' position' ParentShowHint = False ShowHint = True TabOrder = 3 Text = 'PassHeight' OnKeyPress = TEdit_PosReal_OnKeyPress end object editDrillDepth: TEdit Left = 87 Top = 59 Width = 81 Height = 21 Hint = 'Depth to drill PCB holes/vias to' ParentShowHint = False ShowHint = True TabOrder = 2 Text = 'editDrillDepth' OnKeyPress = TEdit_PosReal_OnKeyPress end object editMillRPM: TEdit Left = 87 Top = 148 Width = 81 Height = 21 Hint = 'Rotational speed at which milling operations will be performed' ParentShowHint = False ShowHint = True TabOrder = 6 Text = 'editMillRPM' OnKeyPress = TEdit_PosInt_OnKeyPress end object editDrillRPM: TEdit Left = 87 Top = 171 Width = 81 Height = 21 Hint = 'Rotational speed at which drilling operations will be performed' ParentShowHint = False ShowHint = True TabOrder = 7 Text = 'editDrillRPM' OnKeyPress = TEdit_PosInt_OnKeyPress end end end
unit FSelectFolder; (*==================================================================== Dialog box for selecting the folder to be scanned. ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Outline, {DirOutln,} ExtCtrls, ComCtrls; //DirTreeView; type TFormSelectFolder = class(TForm) Panel1: TPanel; ButtonOK: TButton; ButtonCancel: TButton; DirTreeView: TTreeView; procedure ButtonOKClick(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure DirTreeViewExpanded(Sender: TObject; Node: TTreeNode); procedure FormShow(Sender: TObject); procedure DirTreeViewClick(Sender: TObject); procedure DirTreeViewCollapsed(Sender: TObject; Node: TTreeNode); private procedure ScanSubfolders(sPath: AnsiString; pNode: TTreeNode); procedure InitTreeView(); function GetFullPath(pNode: TTreeNode): AnsiString; public Directory: AnsiString; procedure DefaultHandler(var Message); override; procedure SetFormSize; end; var FormSelectFolder: TFormSelectFolder; implementation uses IniFiles, FSettings; {$R *.dfm} //----------------------------------------------------------------------------- procedure TFormSelectFolder.ButtonOKClick(Sender: TObject); begin ModalResult := mrOK; end; //----------------------------------------------------------------------------- procedure TFormSelectFolder.ButtonCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; //----------------------------------------------------------------------------- // Resizable form - restore the last size procedure TFormSelectFolder.SetFormSize; var IniFile: TIniFile; SLeft, STop, SWidth, SHeight: integer; begin IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.INI')); SLeft := IniFile.ReadInteger ('SelectFolderWindow', 'Left', (Screen.Width - Width) div 2); STop := IniFile.ReadInteger ('SelectFolderWindow', 'Top', (Screen.Height - Height) div 2); SWidth := IniFile.ReadInteger ('SelectFolderWindow', 'Width', Width); SHeight := IniFile.ReadInteger ('SelectFolderWindow', 'Height', Height); IniFile.Free; SetBounds(SLeft, STop, SWidth, SHeight); end; //----------------------------------------------------------------------------- {$ifndef mswindows} procedure TFormSelectFolder.ScanSubfolders(sPath: AnsiString; pNode: TTreeNode); var SearchRec: TSearchRec; bFound : boolean; sFileName: AnsiString; cFirstLetter: char; begin pNode.DeleteChildren(); if (Copy(sPath, Length(sPath), 1) <> '/') then sPath := sPath + '/*' else sPath := sPath + '*'; bFound := SysUtils.FindFirst(sPath, faAnyFile, SearchRec) = 0; while (bFound) do begin /// {sFileName := UpperCase(SearchRec.Name); if (sFileName = SearchRec.Name) then // all chars in upper case begin cFirstLetter := sFileName[1]; sFileName := LowerCase(sFileName); sFileName[1] := cFirstLetter; end else } sFileName := SearchRec.Name; if ((SearchRec.Attr and faDirectory) <> 0) and (sFileName <> '.') and (sFileName <> '..') and ((SearchRec.Attr and faHidden) = 0) then DirTreeView.Items.AddChild(pNode, sFileName); bFound := SysUtils.FindNext(SearchRec) = 0; end; SysUtils.FindClose(SearchRec); pNode.AlphaSort(); end; {$else} procedure TFormSelectFolder.ScanSubFolders(sPath: AnsiString; pNode: TTreeNode); var Path: string; sr : TSearchRec; begin pNode.DeleteChildren(); Path := IncludeTrailingPathDelimiter(sPath); if FindFirst(Path + '*', faAnyFile and faDirectory, sr) = 0 then begin repeat // TSearchRec.Attr contain basic attributes (directory, hidden, // system, etc). TSearchRec only supports a subset of all possible // info. TSearchRec.FindData contains everything that the OS // reported about the item during the search, if you need to // access more detailed information... if (sr.Attr and faDirectory) <> 0 then begin // item is a directory if (sr.Name <> '.') and (sr.Name <> '..') then begin DirTreeView.Items.AddChild(pNode, sr.Name); ScanSubFolders(Path + sr.Name,pNode); end; end else begin // item is a file end; until FindNext(sr) <> 0; end; FindClose(sr); pNode.AlphaSort(); end; {$endif} //--------------------------------------------------------------------------- procedure TFormSelectFolder.InitTreeView(); var dwLogicalDrives : DWORD; uiOldMode : DWORD; i : integer; szDrive : array[0..4] of char; szVolumeName : array[0..250] of char; dwMaximumComponentLength: DWORD; dwFileSystemFlags : DWORD; szFileSystemNameBuffer : array [0..100] of char; sDrive : AnsiString; pNode : TTreeNode; begin DirTreeView.Items.Clear(); // remove any existing nodes {$ifdef mswindows} dwLogicalDrives := GetLogicalDrives(); uiOldMode := SetErrorMode (SEM_FAILCRITICALERRORS); // hides error message box if the CD is not ready for i := 2 to 31 do // 2 means skip A: and B: begin if (((dwLogicalDrives shr i) and $1) = 0) then Continue; StrCopy(szDrive, 'C:\'); szDrive[0] := char(ord('A') + i); {$ifdef mswindows} if (not GetVolumeInformation( szDrive, // root directory szVolumeName, // volume name buffer 250, // length of name buffer nil, // volume serial number dwMaximumComponentLength, // maximum file name length dwFileSystemFlags, // file system options szFileSystemNameBuffer, // file system name buffer 100 // length of file system name buffer )) then StrCopy(szVolumeName, ''); {$endif} StrCopy(szVolumeName, ''); szDrive[2] := #0; sDrive := szDrive; sDrive := sDrive + ' ' + szVolumeName; if (DirTreeView.Items.Count = 0) then DirTreeView.Items.Add(nil, sDrive) else DirTreeView.Items.Add(DirTreeView.Items.Item[0], sDrive); end; {$else} if (DirTreeView.Items.Count = 0) then DirTreeView.Items.Add(nil, '/') else DirTreeView.Items.Add(DirTreeView.Items.Item[0], '/'); {$endif} pNode := DirTreeView.Items.GetFirstNode(); while (pNode <> nil) do begin sDrive := pNode.Text; SetLength(sDrive, 2); sDrive := sDrive + '/'; ScanSubfolders(sDrive, pNode); pNode := pNode.getNextSibling(); end; DirTreeView.Items[0].Expand(false); ///SetErrorMode (uiOldMode); end; //--------------------------------------------------------------------------- function TFormSelectFolder.GetFullPath(pNode: TTreeNode): AnsiString; begin if (pNode = nil) then Result := '' else if (pNode.Parent = nil) then // we are at top, extract the drive letter begin ///Result := pNode.Text; ///SetLength(Result, 2); exit; end else Result := GetFullPath(pNode.Parent) + '/' + pNode.Text; end; //--------------------------------------------------------------------------- procedure TFormSelectFolder.DirTreeViewExpanded(Sender: TObject; Node: TTreeNode); var dwStartTime: DWORD; sPath : AnsiString; sSubPath : AnsiString; pChildNode : TTreeNode; Save_Cursor: TCursor; begin Save_Cursor := Screen.Cursor; dwStartTime := GetTickCount(); sPath := GetFullPath(Node); pChildNode := Node.getFirstChild(); while (pChildNode <> nil) do begin sSubPath := sPath + '/' + pChildNode.Text; ScanSubfolders(sSubPath, pChildNode); pChildNode := Node.GetNextChild(pChildNode); if ((GetTickCount() - dwStartTime) > 1000) then Screen.Cursor := crHourglass; end; Directory := GetFullPath(Node); Screen.Cursor := Save_Cursor; { Always restore to normal } end; //--------------------------------------------------------------------------- procedure TFormSelectFolder.DirTreeViewCollapsed(Sender: TObject; Node: TTreeNode); var sPath : AnsiString; begin sPath := GetFullPath(Node); ScanSubfolders(sPath, Node); Directory := GetFullPath(Node); end; //--------------------------------------------------------------------------- procedure TFormSelectFolder.FormShow(Sender: TObject); begin if (DirTreeView.Items.Count = 0) then InitTreeView(); ActiveControl := DirTreeView; end; //--------------------------------------------------------------------------- procedure TFormSelectFolder.DirTreeViewClick(Sender: TObject); begin Directory := GetFullPath(DirTreeView.Selected); end; //----------------------------------------------------------------------------- // Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay // to the top window, so we must have this handler in all forms. procedure TFormSelectFolder.DefaultHandler(var Message); begin with TMessage(Message) do if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and g_CommonOptions.bDisableCdAutorun then Result := 1 else inherited DefaultHandler(Message) end; //--------------------------------------------------------------------------- end.
unit U_CustomFilter; //////////////////////////////////////////////////////////////////////////////////////////////////// interface uses Classes, Windows, SysUtils; type {--- 2013-01-26 Martijn: TFilterData contains all the information needed for the filter to do its job (in a different thread, so the filter processing becomes thread-safe). ---} TFilterData = record Name: string; DocFile: TFileName; BufferID: NativeInt; Contents: string; Encoding: TEncoding; UseBOM: Boolean; Modified: Boolean; FilterInfo: TStringList; // the contents of the filter OnTerminate: TNotifyEvent; end; type TCustomFilterThread = class(TThread) private FData: TFilterData; function Run(const Command, WorkingDir: string; const Input, Output, Error: TStream): NativeInt; public constructor Create(const Data: TFilterData); reintroduce; destructor Destroy; override; procedure Execute; override; end; //////////////////////////////////////////////////////////////////////////////////////////////////// implementation uses IOUtils, process, Pipes, F_PreviewHTML; { TCustomFilterThread } { ------------------------------------------------------------------------------------------------ } constructor TCustomFilterThread.Create(const Data: TFilterData); begin FData := Data; Self.OnTerminate := Data.OnTerminate; inherited Create; end {TCustomFilter.Create}; { ------------------------------------------------------------------------------------------------ } destructor TCustomFilterThread.Destroy; begin FreeAndNil(FData.FilterInfo); inherited; end {TCustomFilterThread.Destroy}; { ------------------------------------------------------------------------------------------------ } procedure TCustomFilterThread.Execute; type TContentInputType = (citStandardInput, citFile); TContentOutputType = (cotStandardOutput, cotInputFile, cotOutputFile); var HTML: string; Command: string; TempFile, InFile, OutFile, WorkingDir: TFileName; SS: TStringStream; InputMethod: TContentInputType; OutputMethod: TContentOutputType; Input, Output, Error: TStringStream; // i: Integer; begin //ODS('Data.FilterInfo.Count = "%d"', [FData.FilterInfo.Count]); //for i := 0 to FData.FilterInfo.Count - 1 do begin // ODS('Data.FilterInfo[%d] = "%s"', [i, FData.FilterInfo.Strings[i]]); //end; try Command := FData.FilterInfo.Values['Command']; //ODS('Command: "%s"', [Command]); if Command = '' then begin HTML := FData.Contents; Exit; end; // Decide what the input and output methods are if Pos('%1', Command) > 0 then begin InputMethod := citFile; end else begin InputMethod := citStandardInput; end; if Pos('%2', Command) > 0 then begin OutputMethod := cotOutputFile; end else begin OutputMethod := cotStandardOutput; end; {$MESSAGE HINT 'TODO: allow for explicit overrides in the filter settings — Martijn 2013-01-26'} if Terminated then Exit; {--- Now we figure out what in- and output files we will need ---} if InputMethod = citStandardInput then begin InFile := ''; Input := TStringStream.Create(FData.Contents, FData.Encoding, False); if OutputMethod = cotInputFile then begin OutputMethod := cotStandardOutput; {$MESSAGE HINT 'TODO: warn the user that this filter is misconfigured — Martijn 2013-01-26'} end; if OutputMethod = cotOutputFile then OutFile := TPath.GetTempFileName else OutFile := ''; end else begin // ContentInput = citFile Input := nil; if FData.Modified or (OutputMethod = cotInputFile) then begin TempFile := TPath.GetTempFileName; // rename the TempFile so it has the proper extension InFile := ChangeFileExt(TempFile, ExtractFileExt(FData.DocFile)); if not RenameFile(TempFile, InFile) then InFile := TempFile; // Save the contents to the input file SS := TStringStream.Create(FData.Contents, FData.Encoding, False); try SS.SaveToFile(InFile); finally SS.Free; end; end else begin // Use the original file as input file InFile := FData.DocFile; end; case OutputMethod of cotInputFile: OutFile := InFile; cotOutputFile: OutFile := TPath.GetTempFileName; end; end; if Terminated then Exit; if InFile = '' then WorkingDir := ExtractFilePath(FData.DocFile) else WorkingDir := ExtractFilePath(InFile); // Perform replacements in the command string Command := StringReplace(Command, '%1', InFile, [rfReplaceAll]); Command := StringReplace(Command, '%2', OutFile, [rfReplaceAll]); // TODO: also replace environment strings? if OutFile = '' then begin Output := TStringStream.Create('', FData.Encoding, False); end else begin Output := nil; end; Error := TStringStream.Create('', CP_OEMCP); try ODS('Command="%s"; WorkingDir="%s"; InFile="%s"; OutFile="%s"', [Command, WorkingDir, InFile, OutFile]); // Run the command and keep track of the new process Run(Command, WorkingDir, Input, Output, Error); if Terminated then Exit; case OutputMethod of cotStandardOutput: begin // read the output from the process's standard output stream HTML := TStringStream(Output).DataString; if Length(HTML) = 0 then HTML := '<pre style="color: darkred">' + StringReplace(Error.DataString, '<', '&lt;', [rfReplaceAll]) + '</pre>'; end; cotInputFile, cotOutputFile: begin SS := TStringStream.Create('', FData.Encoding, False); try SS.LoadFromFile(OutFile); HTML := SS.DataString; finally SS.Free; end; end; end; finally FreeAndNil(Input); FreeAndNil(Output); FreeAndNil(Error); end; finally {--- When finished, we need to populate the webbrowser component, but this needs to happen in the main thread. ---} if not Terminated then begin ODS('About to synchronize HTML of length %d in thread ID [%x]', [Length(HTML), GetCurrentThreadID]); Synchronize(procedure begin ODS('Synchronizing HTML of length %d in thread ID [%x]', [Length(HTML), GetCurrentThreadID]); frmHTMLPreview.DisplayPreview(HTML, FData.BufferID); end); end; ODS('Cleaning up...'); // Delete the temporary files if (InFile <> '') and not SameFileName(FData.DocFile, OutFile) then DeleteFile(OutFile); if (InFile <> '') and not SameFileName(InFile, FData.DocFile) then DeleteFile(InFile); end; end {TCustomFilter.Execute}; { ------------------------------------------------------------------------------------------------ } function TCustomFilterThread.Run(const Command, WorkingDir: string; const Input, Output, Error: TStream): NativeInt; const READ_BYTES = 2048; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } {$POINTERMATH ON} function CacheStream(Input: TInputPipeStream; Cache: TMemoryStream; var BytesRead: LongInt): LongInt; var CacheMem: PByte; begin if Input.NumBytesAvailable > 0 then begin // make sure we have room Cache.SetSize(BytesRead + READ_BYTES); // try reading it CacheMem := Cache.Memory; Inc(CacheMem, BytesRead); Result := Input.Read(CacheMem^, READ_BYTES); if Result > 0 then begin Inc(BytesRead, Result); end; end else begin Result := 0; end; end{CacheStream}; {$POINTERMATH OFF} { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } var OMS, EMS: TMemoryStream; P: TProcess; n: LongInt; BytesRead, ErrBytesRead: LongInt; begin // We cannot use poWaitOnExit here since we don't // know the size of the output. On Linux the size of the // output pipe is 2 kB. If the output data is more, we // need to read the data. This isn't possible since we are // waiting. So we get a deadlock here. // // A temp Memorystream is used to buffer the output BytesRead := 0; OMS := TMemoryStream.Create; ErrBytesRead := 0; EMS := TMemoryStream.Create; try P := TProcess.Create(nil); try P.CurrentDirectory := WorkingDir; P.CommandLine := Command; P.Options := P.Options + [poUsePipes]; P.StartupOptions := [suoUseShowWindow]; P.ShowWindow := swoHIDE; P.Execute; if P.Running and Assigned(Input) then P.Input.CopyFrom(Input, Input.Size); while P.Running do begin n := CacheStream(P.Output, OMS, BytesRead); Inc(n, CacheStream(P.Stderr, EMS, ErrBytesRead)); if n <= 0 then begin // no data, wait 100 ms Sleep(100); end; if Self.Terminated then begin P.Terminate(-1); Exit(-1); end; end; // read last part repeat n := CacheStream(P.Output, OMS, BytesRead); Inc(n, CacheStream(P.Stderr, EMS, ErrBytesRead)); until n <= 0; Result := P.ExitStatus; OMS.SetSize(BytesRead); EMS.SetSize(ErrBytesRead); finally P.Free; end; if Assigned(Output) then Output.CopyFrom(OMS, 0); if Assigned(Error) then Error.CopyFrom(EMS, 0); finally OMS.Free; EMS.Free; end; end {TCustomFilterThread.Run}; end.
unit UnitOpenGLBRDFLUTShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader; type TBRDFLUTShader=class(TShader) public constructor Create; destructor Destroy; override; procedure BindAttributes; override; procedure BindVariables; override; end; implementation constructor TBRDFLUTShader.Create; var f,v:ansistring; begin v:='#version 330'+#13#10+ 'out vec2 vTexCoord;'+#13#10+ 'void main(){'+#13#10+ ' vTexCoord = vec2((gl_VertexID >> 1) * 2.0, (gl_VertexID & 1) * 2.0);'+#13#10+ ' gl_Position = vec4(((gl_VertexID >> 1) * 4.0) - 1.0, ((gl_VertexID & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+ '}'+#13#10; f:='#version 330'+#13#10+ 'in vec2 vTexCoord;'+#13#10+ 'layout(location = 0) out vec4 oOutput;'+#13#10+ 'const int numSamples = 1024;'+#13#10+ 'vec2 Hammersley(const in int index, const in int numSamples){'+#13#10+ // ' uint reversedIndex = bitfieldReverse(uint(index));'+#13#10+ // >= OpenGL 4.0 ' uint reversedIndex = uint(index);'+#13#10+ ' reversedIndex = (reversedIndex << 16u) | (reversedIndex >> 16u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x00ff00ffu) << 8u) | ((reversedIndex & 0xff00ff00u) >> 8u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x0f0f0f0fu) << 4u) | ((reversedIndex & 0xf0f0f0f0u) >> 4u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x33333333u) << 2u) | ((reversedIndex & 0xccccccccu) >> 2u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x55555555u) << 1u) | ((reversedIndex & 0xaaaaaaaau) >> 1u);'+#13#10+ ' return vec2(fract(float(index) / float(numSamples)), float(reversedIndex) * 2.3283064365386963e-10);'+#13#10+ '}'+#13#10+ 'vec3 ImportanceSampleGGX(const in vec2 e, const in float roughness){'+#13#10+ ' float m = roughness * roughness;'+#13#10+ ' float m2 = m * m;'+#13#10+ ' float phi = (2.0 * 3.1415926535897932384626433832795) * e.x;'+#13#10+ ' float cosTheta = sqrt((1.0 - e.y) / (1.0 + ((m2 - 1.0) * e.y)));'+#13#10+ ' float sinTheta = sqrt(1.0 - (cosTheta * cosTheta));'+#13#10+ ' return vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);'+#13#10+ '}'+#13#10+ 'float specularG(const in float roughness, const in float nDotV, const in float nDotL){'+#13#10+ ' float a = roughness * roughness;'+#13#10+ ' float a2 = a * a;'+#13#10+ ' vec2 GVL = vec2(nDotV, nDotL);'+#13#10+ ' GVL = GVL + sqrt((GVL * (GVL - (GVL * a2))) + vec2(a2));'+#13#10+ ' return 1.0 / (GVL.x * GVL.y);'+#13#10+ '}'+#13#10+ 'void main(){'+#13#10+ ' float roughness = vTexCoord.x;'+#13#10+ ' float nDotV = vTexCoord.y;'+#13#10+ ' vec3 V = vec3(sqrt(1.0 - (nDotV * nDotV)), 0.0, nDotV);'+#13#10+ ' vec2 r = vec2(0.0);'+#13#10+ ' for(int i = 0; i < numSamples; i++){'+#13#10+ ' vec3 H = ImportanceSampleGGX(Hammersley(i, numSamples), roughness);'+#13#10+ ' vec3 L = -reflect(V, H);'+#13#10+ //((2.0 * dot(V, H )) * H) - V; ' float nDotL = clamp(L.z, 0.0, 1.0);'+#13#10+ ' if(nDotL > 0.0){'+#13#10+ ' float vDotH = clamp(dot(V, H), 0.0, 1.0);'+#13#10+ ' r += (vec2(1.0, 0.0) + (vec2(-1.0, 1.0) * pow(1.0 - vDotH, 5.0))) * (nDotL * specularG(roughness, nDotV, nDotL) * ((4.0 * vDotH) / clamp(H.z, 0.0, 1.0)));'+#13#10+ ' }'+#13#10+ ' }'+#13#10+ ' oOutput = vec4(r / float(numSamples), 0.0, 1.0);'+#13#10+ '}'+#13#10; inherited Create(v,f); end; destructor TBRDFLUTShader.Destroy; begin inherited Destroy; end; procedure TBRDFLUTShader.BindAttributes; begin inherited BindAttributes; end; procedure TBRDFLUTShader.BindVariables; begin inherited BindVariables; end; end.
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Glass shader : Environment mapping with an equirectangular 2D texture and refraction mapping with a background texture blended together using the fresnel terms } unit VXS.GLSLGlassShader; interface {$I VXScene.inc} uses System.Classes, VXS.Scene, VXS.CrossPlatform, VXS.BaseClasses, VXS.State, Winapi.OpenGL, Winapi.OpenGLext, VXS.OpenGL1x, VXS.Context, VXS.RenderContextInfo, VXS.VectorGeometry, VXS.Coordinates, VXS.TextureFormat, VXS.Color, VXS.Texture, VXS.Material, VXS.PersistentClasses, VXS.Graphics, GLSLS.Shader, VXS.CustomShader; //TVXCustomGLSLSimpleGlassShader // { Custom class for GLSLGlassShader. Glass shader : Environment mapping and refraction mapping using the fresnel terms } Type TVXCustomGLSLGlassShader = class(TVXCustomGLSLShader) private FDiffuseColor: TVXColor; FDepth : Single; FMix : Single; FAlpha : Single; FMaterialLibrary: TVXAbstractMaterialLibrary; FMainTexture : TVXTexture; // EnvMap FMainTexName : TVXLibMaterialName; FRefractionTexture : TVXTexture; FRefractionTexName : TVXLibMaterialName; FOwnerObject : TVXBaseSceneObject; FBlendSrc : TBlendFunction; FBlendDst : TBlendFunction; function GetMaterialLibrary: TVXAbstractMaterialLibrary; procedure SetMainTexTexture(const Value: TVXTexture); function GetMainTexName: TVXLibMaterialName; procedure SetMainTexName(const Value: TVXLibMaterialName); procedure SetRefractionTexTexture(const Value: TVXTexture); function GetRefractionTexName: TVXLibMaterialName; procedure SetRefractionTexName(const Value: TVXLibMaterialName); procedure SetDiffuseColor(AValue: TVXColor); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; procedure SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property DiffuseColor : TVXColor read FDiffuseColor Write setDiffuseColor; property Depth : Single read FDepth write FDepth; property Mix : Single read FMix write FMix; property Alpha : Single read FAlpha write FAlpha; property MaterialLibrary: TVXAbstractMaterialLibrary read getMaterialLibrary write SetMaterialLibrary; property MainTexture: TVXTexture read FMainTexture write SetMainTexTexture; property MainTextureName: TVXLibMaterialName read GetMainTexName write SetMainTexName; property RefractionTexture: TVXTexture read FRefractionTexture write SetRefractionTexTexture; property RefractionTextureName: TVXLibMaterialName read GetRefractionTexName write SetRefractionTexName; property OwnerObject : TVXBaseSceneObject read FOwnerObject write FOwnerObject; property BlendSrc : TBlendFunction read FBlendSrc write FBlendSrc default bfSrcAlpha; property BlendDst : TBlendFunction read FBlendDst write FBlendDst default bfDstAlpha; end; TVXSLGlassShader = class(TVXCustomGLSLGlassShader) published property DiffuseColor; property Depth; property Mix; property Alpha; property MaterialLibrary; property MainTexture; property MainTextureName; property RefractionTexture; property RefractionTextureName; property OwnerObject; property BlendSrc; property BlendDst; end; implementation const fBuffSize: Integer = 512; constructor TVXCustomGLSLGlassShader.Create(AOwner: TComponent); begin inherited; with VertexProgram.Code do begin clear; Add('varying vec3 Normal; '); Add('varying vec3 EyeDir; '); Add('varying vec4 EyePos; '); Add('varying float LightIntensity; '); Add('void main(void) '); Add('{ '); Add(' gl_Position = ftransform(); '); Add(' vec3 LightPos = gl_LightSource[0].position.xyz;'); Add(' Normal = normalize(gl_NormalMatrix * gl_Normal); '); Add(' vec4 pos = gl_ModelViewMatrix * gl_Vertex; '); Add(' EyeDir = -pos.xyz; '); Add(' EyePos = gl_ModelViewProjectionMatrix * gl_Vertex; '); Add(' LightIntensity = max(dot(normalize(LightPos - EyeDir), Normal), 0.0); '); Add('} '); end; With FragmentProgram.Code do begin clear; Add('const vec3 Xunitvec = vec3 (1.0, 0.0, 0.0); '); Add('const vec3 Yunitvec = vec3 (0.0, 1.0, 0.0); '); Add('uniform vec4 BaseColor; '); Add('uniform float Depth; '); Add('uniform float MixRatio; '); Add('uniform float AlphaIntensity; '); // need to scale our framebuffer - it has a fixed width/height of 2048 Add('uniform float FrameWidth; '); Add('uniform float FrameHeight; '); Add('uniform sampler2D EnvMap; '); Add('uniform sampler2D RefractionMap; '); Add('varying vec3 Normal; '); Add('varying vec3 EyeDir; '); Add('varying vec4 EyePos; '); Add('varying float LightIntensity; '); Add('void main (void) '); Add('{ '); // Compute reflection vector Add(' vec3 reflectDir = reflect(EyeDir, Normal); '); // Compute altitude and azimuth angles Add(' vec2 index; '); Add(' index.y = dot(normalize(reflectDir), Yunitvec); '); Add(' reflectDir.y = 0.0; '); Add(' index.x = dot(normalize(reflectDir), Xunitvec) * 0.5; '); // Translate index values into proper range Add(' if (reflectDir.z >= 0.0) '); Add(' index = (index + 1.0) * 0.5; '); Add(' else '); Add(' { '); Add(' index.t = (index.t + 1.0) * 0.5; '); Add(' index.s = (-index.s) * 0.5 + 1.0; '); Add(' } '); // if reflectDir.z >= 0.0, s will go from 0.25 to 0.75 // if reflectDir.z < 0.0, s will go from 0.75 to 1.25, and // that's OK, because we've set the texture to wrap. // Do a lookup into the environment map. Add(' vec4 envColor = texture2D(EnvMap, index); '); // calc fresnels term. This allows a view dependant blend of reflection/refraction Add(' float fresnel = abs(dot(normalize(EyeDir), Normal)); '); Add(' fresnel *= MixRatio; '); Add(' fresnel = clamp(fresnel, 0.1, 0.9); '); // calc refraction Add(' vec3 refractionDir = normalize(EyeDir) - normalize(Normal); '); // Scale the refraction so the z element is equal to depth Add(' float depthVal = Depth / -refractionDir.z; '); // perform the div by w Add(' float recipW = 1.0 / EyePos.w; '); Add(' vec2 eye = EyePos.xy * vec2(recipW); '); // calc the refraction lookup Add(' index.s = (eye.x + refractionDir.x * depthVal); '); Add(' index.t = (eye.y + refractionDir.y * depthVal); '); // scale and shift so we're in the range 0-1 Add(' index.s = index.s / 2.0 + 0.5; '); Add(' index.t = index.t / 2.0 + 0.5; '); // as we're looking at the framebuffer, we want it clamping at the edge of the rendered scene, not the edge of the texture, // so we clamp before scaling to fit Add(' float recip1k = 1.0 / 2048.0; '); Add(' index.s = clamp(index.s, 0.0, 1.0 - recip1k); '); Add(' index.t = clamp(index.t, 0.0, 1.0 - recip1k); '); // scale the texture so we just see the rendered framebuffer Add(' index.s = index.s * FrameWidth * recip1k; '); Add(' index.t = index.t * FrameHeight * recip1k; '); Add(' vec4 RefractionColor = texture2D(RefractionMap, index.st); '); //Add(' RefractionColor.a = 0.9; '); // Add(' RefractionColor = RefractionColor+vec3(0.75,0.75,0.75); ');// // Add lighting to base color and mix // Add(' vec4 base = LightIntensity * BaseColor; '); Add(' envColor = mix(envColor, BaseColor,LightIntensity); '); Add(' envColor = mix(envColor, RefractionColor, fresnel); '); Add(' envColor.a = AlphaIntensity; '); Add(' gl_FragColor = envColor; //vec4 (envColor.rgb, 0.3); '); Add('} '); end; // FMainTexture := TVXTexture.Create(nil); // FMainTexture.Disabled := False; // FMainTexture.Enabled := True; //setup initial parameters FDiffuseColor := TVXColor.Create(Self); FDepth := 0.1; FMix:=1.0; FAlpha:=1.0; FDiffuseColor.SetColor(0.15, 0.15, 0.15, 1.0); FBlendSrc := bfSrcAlpha; FBlendDst := bfDstAlpha; end; destructor TVXCustomGLSLGlassShader.Destroy; begin FDiffuseColor.Destroy; inherited; end; procedure TVXCustomGLSLGlassShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); begin // Auto Render EnvMap // capture and create material from framebuffer // I don't say why but We need to reset and reaffect our texture otherwise one of the texture is broken with FMainTexture do begin PrepareBuildList; GL.ActiveTexture(GL_TEXTURE0_ARB); GL.BindTexture(GL_TEXTURE_2D, Handle); GL.ActiveTexture(GL_TEXTURE0_ARB); end; with FRefractionTexture do begin PrepareBuildList; GL.ActiveTexture(GL_TEXTURE1_ARB); GL.BindTexture(GL_TEXTURE_2D, Handle); GL.ActiveTexture(GL_TEXTURE0_ARB); end; FOwnerObject.Visible := False; TVXSceneBuffer(rci.buffer).CopyToTexture(FMainTexture); FOwnerObject.Visible := True; GetGLSLProg.UseProgramObject; // GetGLSLProg.Uniform4f['BaseColor'] := FDiffuseColor.Color; // GetGLSLProg.Uniform1f['Depth'] := FDepth; // GetGLSLProg.Uniform1f['MixRatio'] := FMix; // 0 - 2 // GetGLSLProg.Uniform1f['FrameWidth'] := fBuffSize * 3.125; // GetGLSLProg.Uniform1f['FrameHeight'] := fBuffSize * 3.125; // SetTex('EnvMap',FMainTexture); --> BUG // SetTex('RefractionMap',FRefractionTexture); param['BaseColor'].AsVector4f := FDiffuseColor.Color; param['Depth'].AsVector1f := FDepth; // 0 - 0.3 param['MixRatio'].AsVector1f := FMix; // 0 - 2 param['AlphaIntensity'].AsVector1f := FAlpha; // 0 - 2 param['FrameWidth'].AsVector1f := fBuffSize * 3.75; param['FrameHeight'].AsVector1f := fBuffSize * 3.75; Param['EnvMap'].AsTexture2D[0] := FMainTexture; Param['RefractionMap'].AsTexture2D[1] :=FRefractionTexture ; glEnable(GL_BLEND); gl.BlendFunc(cGLBlendFunctionToGLEnum[FBlendSrc],cGLBlendFunctionToGLEnum[FBlendDst]); end; function TVXCustomGLSLGlassShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean; begin glDisable(GL_BLEND); GetGLSLProg.EndUseProgramObject; Result := False; end; function TVXCustomGLSLGlassShader.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXCustomGLSLGlassShader.SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if (FMaterialLibrary <> nil) and (FMaterialLibrary is TVXAbstractMaterialLibrary) then FMaterialLibrary.FreeNotification(Self); end; procedure TVXCustomGLSLGlassShader.SetMainTexTexture(const Value: TVXTexture); begin if FMainTexture = Value then Exit; FMainTexture := Value; NotifyChange(Self) end; function TVXCustomGLSLGlassShader.GetMainTexName: TVXLibMaterialName; begin Result := TVXMaterialLibrary(FMaterialLibrary).GetNameOfTexture(FMainTexture); if Result = '' then Result := FMainTexName; end; procedure TVXCustomGLSLGlassShader.SetMainTexName(const Value: TVXLibMaterialName); begin // Assert(not(assigned(FMaterialLibrary)),'You must set Material Library Before'); if FMainTexName = Value then Exit; FMainTexName := Value; FMainTexture := TVXMaterialLibrary(FMaterialLibrary).TextureByName(FMainTexName); NotifyChange(Self); end; procedure TVXCustomGLSLGlassShader.SetRefractionTexTexture(const Value: TVXTexture); begin if FRefractionTexture = Value then Exit; FRefractionTexture := Value; NotifyChange(Self) end; function TVXCustomGLSLGlassShader.GetRefractionTexName: TVXLibMaterialName; begin Result := TVXMaterialLibrary(FMaterialLibrary).GetNameOfTexture(FRefractionTexture); if Result = '' then Result := FRefractionTexName; end; procedure TVXCustomGLSLGlassShader.SetRefractionTexName(const Value: TVXLibMaterialName); begin // Assert(not(assigned(FMaterialLibrary)),'You must set Material Library Before'); if FRefractionTexName = Value then Exit; FRefractionTexName := Value; FRefractionTexture := TVXMaterialLibrary(FMaterialLibrary).TextureByName(FRefractionTexName); NotifyChange(Self); end; procedure TVXCustomGLSLGlassShader.SetDiffuseColor(AValue: TVXColor); begin FDiffuseColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLGlassShader.Notification(AComponent: TComponent; Operation: TOperation); var Index: Integer; begin inherited; if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin if FMainTexture <> nil then begin Index := TVXMaterialLibrary(FMaterialLibrary).Materials.GetTextureIndex(FMainTexture); if Index <> -1 then SetMainTexTexture(nil); end; if FRefractionTexture <> nil then begin Index := TVXMaterialLibrary(FMaterialLibrary).Materials.GetTextureIndex(FRefractionTexture); if Index <> -1 then SetRefractionTexTexture(nil); end; FMaterialLibrary := nil; end; end; 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 uHtmlDocGen; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, {ComObj,} uDocGen, uModel, uModelEntity, uXmiExport, uViewIntegrator; type //Html documentation generator THtmlDocGen = class(TDocGen) private Xmi : TXmiExporter; Source,Detail : variant; procedure MakeDiagram(P : TAbstractPackage); protected procedure DocStart; override; procedure DocFinished; override; procedure WriteOverview; override; procedure WritePackageDetail(P : TUnitPackage); override; public destructor Destroy; override; end; implementation {$IFDEF false} function MakeDOM : variant; begin try //This should make it work with xml 3 and 4 //MSXML no longer have version independent progids try Result := CreateOleObject('Msxml2.DOMDocument.5.0'); except try Result := CreateOleObject('MSXML2.DOMDocument.4.0'); except Result := CreateOleObject('MSXML2.DOMDocument.3.0'); end; end; except ShowMessage('MS XML 4 or later is required.'#13#10'Download from http://msdn.microsoft.com/xml'); Abort; end; Result.async := false; Result.resolveExternals := false; Result.setProperty('SelectionNamespaces','xmlns:xsl=''http://www.w3.org/1999/XSL/Transform'''); end; {$ENDIF} {$IFDEF Linux} function MakeDOM : variant; begin { TODO : linux xsl-processor } end; {$ENDIF} { THtmlDocGen } destructor THtmlDocGen.Destroy; begin if Assigned(Xmi) then Xmi.Free; inherited; end; procedure THtmlDocGen.DocStart; begin {$ifdef false} //Establish stylesheet with Config.GetResourceStream('css_file') do begin SaveToFile(DestPath + 'styles.css'); Free; end; Xmi := TXmiExporter.Create(Model); Xmi.InitFromModel; Source := MakeDOM; Source.loadXML( Xmi.GetXmi ); Detail := MakeDOM; if not Detail.loadXML( Config.GetResourceText('p_detail_xsl_file') ) then raise exception.Create('nix'); {$endif} end; procedure THtmlDocGen.DocFinished; begin {$IFDEF false} if Assigned(Application.MainForm) then OpenDocument(PChar( DestPath + 'overview.html' )); { *Converted from ShellExecute* } {$ENDIF} end; procedure THtmlDocGen.WriteOverview; {$IFDEF false} var Sheet : variant; S : string; F : TFileStream; {$ENDIF} begin {$IFDEF false} Sheet := MakeDOM; Sheet.loadXML( Config.GetResourceText('p_overview_xsl_file') ); S := Source.TransformNode(Sheet); F := TFileStream.Create( DestPath + 'overview.html' , fmCreate); try F.Write(S[1],Length(S)); finally F.Free; end; MakeDiagram( Model.ModelRoot ); {$endif} end; procedure THtmlDocGen.WritePackageDetail(P: TUnitPackage); var F : TFileStream; Id,FileName,S : string; begin Id := Xmi.GetXMIId(P); //Tell the styesheet which package we want to generate html for Detail.SelectSingleNode('//xsl:param').Text := Id; S := Source.TransformNode(Detail); FileName := DestPath + 'p_' + id + '.html'; F := TFileStream.Create( FileName , fmCreate); try F.Write(S[1],Length(S)); finally F.Free; end; MakeDiagram( P ); end; procedure THtmlDocGen.MakeDiagram(P: TAbstractPackage); var Di : TDiagramIntegrator; TempForm : TForm; W,H : integer; FilePrefix,ImageFileName : string; Html,Clicks : TStringList; Target,Coords : string; E : TModelEntity; I : integer; IsRoot : boolean; begin IsRoot := P=Model.ModelRoot; if IsRoot then FilePrefix := DestPath + 'p_overview' else FilePrefix := DestPath + 'p_' + Xmi.GetXMIId(P); ImageFileName := FilePrefix + '.png'; TempForm := TForm.CreateNew(nil); Di := TDiagramIntegrator.CreateDiagram(Model, TempForm); try Di.Package := P; Di.InitFromModel; Di.GetDiagramSize(W{%H-},H{%H-}); Clicks := Di.GetClickAreas; TempForm.Height:=0; TempForm.Width:=0; TempForm.SendToBack; TempForm.Top := Screen.Height; TempForm.Show; Di.SaveAsPicture(ImageFileName); TempForm.Hide; finally Di.Free; TempForm.Free; end; Html := TStringList.Create; try Html.Add( '<html> <body>' ); Html.Add( '<img src="' + ExtractFileName(ImageFileName) + '" usemap="#map1">' ); Html.Add( '<map name="map1">' ); for I := 0 to Clicks.Count-1 do begin E := Clicks.Objects[I] as TModelEntity; if IsRoot then Target := 'p_' + Xmi.GetXMIId( E ) + '.html' else Target := 'p_' + Xmi.GetXMIId( E.Owner ) + '.html' + '#' + Xmi.GetXMIId(E); Coords := Clicks[I]; Html.Add( '<area href="' + Target + '" shape="rect" coords="' + Coords + '">' ); end; Html.Add( '</map>' ); Html.Add( '</body> </html>' ); Html.SaveToFile(FilePrefix + '_diagram.html'); finally Html.Free; Clicks.Free; end; end; end.
unit InflatablesList_Master; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses WinSyncObjs, InflatablesList_Types, InflatablesList_Manager; const IL_APPLICATION_NAME = 'Inflatables List'; IL_APPLICATION_MUTEX = 'il_application_start_mutex_%s'; IL_APPLICATION_TIMEOUT = 10000; // 10s type TILMaster = class(TObject) private fILManager: TILManager; fILStartMutex: TMutex; protected procedure Initialize; virtual; procedure Finalize; virtual; Function CanStart: Boolean; virtual; procedure InitializeApplication; virtual; procedure CreateForms; virtual; Function LoadList: Boolean; virtual; procedure ThreadedLoadingEndHandler(LoadingResult: TILLoadingResult); virtual; procedure RestartRequestHandler(Sender: TObject); virtual; public constructor Create; destructor Destroy; override; procedure Run; virtual; end; implementation uses SysUtils, Forms, Dialogs, MainForm, TextEditForm, PromptForm, SplashForm, SaveForm, BackupsForm, ItemPicturesForm, ItemSelectForm, ShopsForm, ParsingForm, TemplatesForm, ItemsSelectForm, AdvancedSearchForm, SortForm, UpdateForm, SumsForm, OverviewForm, ShopSelectForm, ItemShopTableForm, ShopByItemsForm, SpecialsForm, UpdResLegendForm, SettingsLegendForm, AboutForm, StrRect, InflatablesList_Utils, InflatablesList_Encryption; procedure TILMaster.Initialize; begin fILManager := TILManager.Create; fILManager.MainManager := True; fILStartMutex := TMutex.Create(IL_Format(IL_APPLICATION_MUTEX,[fILManager.StaticSettings.InstanceID])); end; //------------------------------------------------------------------------------ procedure TILMaster.Finalize; begin FreeAndNil(fILStartMutex); FreeAndNil(fILManager); end; //------------------------------------------------------------------------------ Function TILMaster.CanStart: Boolean; begin Result := fILStartMutex.WaitFor(IL_APPLICATION_TIMEOUT) = wrSignaled; end; //------------------------------------------------------------------------------ procedure TILMaster.InitializeApplication; begin Application.Initialize; Application.Title := IL_APPLICATION_NAME; end; //------------------------------------------------------------------------------ procedure TILMaster.CreateForms; begin Application.CreateForm(TfMainForm, fMainForm); fMainForm.OnRestartProgram := RestartRequestHandler; //Application.CreateForm(TfPromptForm, fPromptForm); // do not automatically create prompt form Application.CreateForm(TfTextEditForm, fTextEditForm); Application.CreateForm(TfSplashForm, fSplashForm); Application.CreateForm(TfSaveForm, fSaveForm); Application.CreateForm(TfBackupsForm, fBackupsForm); Application.CreateForm(TfItemPicturesForm,fItemPicturesForm); Application.CreateForm(TfItemSelectForm,fItemSelectForm); Application.CreateForm(TfShopsForm, fShopsForm); Application.CreateForm(TfParsingForm, fParsingForm); Application.CreateForm(TfTemplatesForm, fTemplatesForm); Application.CreateForm(TfItemsSelectForm, fItemsSelectForm); Application.CreateForm(TfAdvancedSearchForm, fAdvancedSearchForm); Application.CreateForm(TfSortForm, fSortForm); Application.CreateForm(TfUpdateForm, fUpdateForm); Application.CreateForm(TfSumsForm, fSumsForm); Application.CreateForm(TfOverviewForm, fOverviewForm); Application.CreateForm(TfShopSelectForm, fShopSelectForm); Application.CreateForm(TfItemShopTableForm,fItemShopTableForm); Application.CreateForm(TfShopByItemsForm,fShopByItemsForm); Application.CreateForm(TfSpecialsForm, fSpecialsForm); Application.CreateForm(TfUpdResLegendForm, fUpdResLegendForm); Application.CreateForm(TfSettingsLegendForm, fSettingsLegendForm); Application.CreateForm(TfAboutForm, fAboutForm); end; //------------------------------------------------------------------------------ Function TILMaster.LoadList: Boolean; var PreloadInfo: TILPreloadInfo; Password: String; begin Result := False; PreloadInfo := fILManager.PreloadFile; If not([ilprfInvalidFile,ilprfError] <= PreloadInfo.ResultFlags) then begin // when the file is encrypted, ask for password If ilprfEncrypted in PreloadInfo.ResultFlags then begin If IL_InputQuery('List password','Enter list password (can be empty):',Password,'*') then fILManager.ListPassword := Password else Exit; // exit with result set to false end; // load the file and catch wrong password exceptions try If ilprfSlowLoad in PreloadInfo.ResultFlags then begin Application.ShowMainForm := False; fSplashForm.ShowSplash; fILManager.LoadFromFileThreaded(ThreadedLoadingEndHandler); // main form initialization is deferred to time when the loading is done end else begin fILManager.LoadFromFile; fMainForm.Initialize(fILManager); end; Result := True; except on E: EILWrongPassword do MessageDlg('You have entered wrong password, program will now terminate.',mtError,[mbOk],0); else raise; end; end else MessageDlg('Invalid list file, cannot continue.',mtError,[mbOk],0); end; //------------------------------------------------------------------------------ procedure TILMaster.ThreadedLoadingEndHandler(LoadingResult: TILLoadingResult); begin case LoadingResult of illrSuccess:; // do nothing illrFailed: MessageDlg('Loading of the file failed, terminating program.',mtError,[mbOk],0); illrWrongPassword: MessageDlg('You have entered wrong password, program will now terminate.',mtError,[mbOk],0); end; If LoadingResult = illrSuccess then fMainForm.Initialize(fILManager) // deferred initialization else Application.Terminate; // Application.ShowMainForm is false already fSplashForm.LoadingDone(LoadingResult = illrSuccess); end; //------------------------------------------------------------------------------ procedure TILMaster.RestartRequestHandler(Sender: TObject); var Params: String; i: Integer; begin // allowed to be called only by main form If Sender = fMainForm then begin // rebuild parameters Params := ''; For i := 1 to ParamCount do Params := Params + ' ' + RTLToStr(ParamStr(i)); // start the program with the same parameters IL_ShellOpen(0,RTLToStr(ParamStr(0)),Params,fILManager.StaticSettings.DefaultPath); end; end; //============================================================================== constructor TILMaster.Create; begin inherited Create; Initialize; end; //------------------------------------------------------------------------------ destructor TILMaster.Destroy; begin Finalize; inherited; end; //------------------------------------------------------------------------------ procedure TILMaster.Run; begin InitializeApplication; If CanStart then begin CreateForms; If not LoadList then begin Application.ShowMainForm := False; Application.Terminate; // fMainForm.OnClose event will not be called end; Application.Run; // fMainForm.Finalize is called automatically in OnClose event (only when loading succeeded) fILStartMutex.ReleaseMutex; end else MessageDlg('Application is already running (only one instance is allowed at a time).',mtError,[mbOK],0); end; end.
(* Category: SWAG Title: TEXT FILE MANAGEMENT ROUTINES Original name: 0026.PAS Description: Reading File Backwards Author: LARS FOSDAL Date: 11-26-93 17:46 *) { Fast driver for backwards reading... Aha! This is the way to do it. Below you will find the source of a "tail" program. I wrote it because I needed to check the status of some log files, and I didn't want to go through the entire file every time, as the files could grow quite large. It is currently limited to 255 chars per line, but that can easily be fixed (see the Limit const). Although it's not an exact solution to your problem, it will show you how to do "backwards" reading. } PROGRAM Tail; { Shows the tailing lines of a text file. Syntax: TAIL [d:\path]filespec.ext [-<lines>] Default number of lines is 10. "TAIL filename -20" will show the 20 last lines Written by Lars Fosdal, 1993 Released to the Public Domain by Lars Fosdal, 1993 } USES DOS, Objects, Strings; CONST MaxBufSize = 32000; TYPE pBuffer = ^TBuffer; TBuffer = ARRAY[0..MaxBufSize-1] OF Char; pRawStrCollection = ^TRawStrCollection; TRawStrCollection = OBJECT(TCollection) PROCEDURE FreeItem(Item:Pointer); VIRTUAL; END; PROCEDURE TRawStrCollection.FreeItem(Item:Pointer); BEGIN IF Item<>nil THEN StrDispose(pChar(Item)); END; {PROC TRawStrCollection.FreeItem} FUNCTION ShowTail(FileName:String; n:Integer):Integer; PROCEDURE DumpLine(p:pChar); BEGIN IF p^=#255 THEN Writeln ELSE Writeln(p); END; CONST Limit = 255; VAR lines : pRawStrCollection; fm : Byte; f : File; fs,fp : LongInt; MaxRead : Word; Buf : pBuffer; lc,ix,ex : Integer; sp : ARRAY[0..Limit] OF Char; BEGIN lines:=nil; fm:=FileMode; FileMode:=$40; {Read-only, deny none} Assign(f, FileName); Reset(f, 1); lc:=IOResult; IF lc=0 THEN BEGIN New(Buf); fs:=FileSize(f); {First, let's find out how much to read} fp:=fs-MaxBufSize; IF fp<0 THEN fp:=0; Seek(f,fp); {Then, read it} BlockRead(f, Buf^, MaxBufSize, MaxRead); Close(f); IF MaxRead>0 THEN BEGIN New(Lines, Init(n,10)); ix:=MaxRead-1; IF Buf^[ix]=^J THEN Dec(ix); IF (ix>0) and (Buf^[ix]=^M) THEN Dec(ix); {Skip trailing line break} WHILE (lc<n) and (ix>0) DO BEGIN ex:=ix; FillChar(sp, SizeOf(sp), 0); WHILE (ix>0) and not (Buf^[ix] =^J) DO Dec(ix); IF ex-ix<=Limit {If no break was found within limit, it's no txt file} THEN BEGIN IF ix=ex THEN sp[0]:=#255 {Pad empty lines to avoid zero-length pchar} ELSE StrLCopy(sp, @Buf^[ix+1], ex-ix); Inc(lc); Lines^.AtInsert(0, StrNew(sp)); Dec(ix); WHILE (ix>0) and (Buf^[ix] =^M) DO Dec(ix); END ELSE BEGIN Writeln('"',FileName,'" doesn''t seem to be a text file'); ix:=-1; END; END; {lc<n and ix>0} END {Maxread>0} ELSE Lines:=nil; Dispose(Buf); END ELSE lc:=-lc; IF Lines<>nil THEN BEGIN Lines^.ForEach(@DumpLine); Dispose(Lines, Done); END; ShowTail:=lc; FileMode:=fm; END; {FUNC ShowTail} TYPE CharSet = Set of Char; FUNCTION StripAll(CONST Exclude:CharSet; S:String):String; VAR ix : Integer; BEGIN ix:=Length(S); WHILE ix>0 DO BEGIN IF S[ix] in Exclude THEN Delete(S, ix, 1); Dec(ix); END; StripAll:=S; END; {FUNC StripAll} VAR r : Integer; l : Integer; e : Integer; BEGIN IF (ParamCount<1) or (ParamCount>2) THEN BEGIN Writeln('TAIL v.1.0 - PD 1993 Lars Fosdal'); Writeln(' TAIL [d:\path]filename.ext [-n]'); Writeln(' Default is 10 lines'); END ELSE BEGIN IF ParamCount=2 THEN BEGIN Val(StripAll(['/','-'], ParamStr(2)), l, e); IF e<>0 THEN l:=10 END ELSE l:=10; r:=ShowTail(ParamStr(1), l); IF r<0 THEN BEGIN Writeln('Couldn''t open "',ParamStr(1),'"! (Error ', -r,')'); Halt(Word(-r)); END; END; END.
{ ********************************************************************** } { } { Delphi Open-Tools API } { } { Copyright (C) 2000, 2001 Borland Software Corporation } { } { Русификация: 2001-02 Polaris Software } { http://polesoft.da.ru } { ********************************************************************** } unit DesignConst; interface resourcestring srNone = '(нет)'; srLine = 'строка'; srLines = 'строк'; SInvalidFormat = 'Неверный графический формат'; SUnableToFindComponent = 'Не могу найти форму/компонент, ''%s'''; SCantFindProperty = 'Не могу найти свойство ''%s'' у компонента ''%s'''; SStringsPropertyInvalid = 'Свойство ''%s'' не проинициализировано у компонента ''%s'''; SLoadPictureTitle = 'Загрузить картинку'; SSavePictureTitle = 'Сохранить картинку как'; SAboutVerb = 'О...'; SNoPropertyPageAvailable = 'Нет доступных страниц свойств для этого элемента управления'; SNoAboutBoxAvailable = 'About Box не доступен для этого элемента управления'; SNull = '(Null)'; SUnassigned = '(Unassigned)'; SUnknown = '(Неизвестен)'; SString = 'String'; SUnknownType = 'Неизвестный тип'; SCannotCreateName = 'Не могу создать метод для безымянного компонента'; SColEditCaption = 'Изменение %s%s%s'; SCantDeleteAncestor = 'Выбор содержит компонент, который применяется в форме-предке, которая не удалена'; SCantAddToFrame = 'Новые компоненты не могут добавляться в образцы фреймов.'; {$IFDEF LINUX} SAllFiles = 'Все файлы (*)'; {$ENDIF} {$IFDEF MSWINDOWS} SAllFiles = 'Все файлы (*.*)'; {$ENDIF} const SIniEditorsName = 'Property Editors'; implementation end.
unit M_extern; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, SysUtils, M_Global; type TExtToolsWindow = class(TForm) OKBtn: TBitBtn; CancelBtn: TBitBtn; HelpBtn: TBitBtn; EDParameters: TEdit; LBExtTools: TListBox; Label1: TLabel; LBHidden: TListBox; procedure FormActivate(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure HelpBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ExtToolsWindow: TExtToolsWindow; implementation uses Mapper; {$R *.DFM} procedure TExtToolsWindow.FormActivate(Sender: TObject); begin if FileExists(WDFUSEdir + '\WDFDATA\external.wdl') and FileExists(WDFUSEdir + '\WDFDATA\external.wdn') then begin LBExtTools.Items.LoadFromFile(WDFUSEdir + '\WDFDATA\external.wdl'); LBHidden.Items.LoadFromFile(WDFUSEdir + '\WDFDATA\external.wdn'); end else Application.MessageBox('Problem : check the External Tools settings', 'WDFUSE - External Tools', mb_Ok or mb_IconExclamation); end; procedure TExtToolsWindow.OKBtnClick(Sender: TObject); var tmp : array[0..127] of char; begin if LBExtTools.ItemIndex <> -1 then begin Chdir(WDFUSEdir); StrPcopy(tmp, LBHidden.Items[LBExtTools.ItemIndex] + ' ' + EDParameters.Text); WinExec(tmp, SW_SHOWNORMAL); ShowWindow(MapWindow.Handle, SW_HIDE); TMPHWindow := GetActiveWindow; ShowWindow(MapWindow.Handle, SW_SHOW); end; end; procedure TExtToolsWindow.HelpBtnClick(Sender: TObject); begin Application.HelpJump('wdfuse_help_optionsexternal'); end; end.
unit WebClientForm; interface uses // Standard Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StrUtils, StdCtrls, Menus, // Forms GoToForm, UserMsgForm, // ActiveX/Ole ActiveX, OleCtrls, // LL Utils LL_StringUtils, LL_SysUtils, // Embedded browser SHDocVw_EWB, EwbCore, EmbeddedWB, // HTTP IdURI, // RPC Broker Trpcb, RpcSLogin, CCOWRPCBroker, // Contextor (CCOW) ContextorUnit; type TWebClientView = class(TForm) MainMenu1: TMainMenu; FileMenuItem: TMenuItem; ExitMenuItem: TMenuItem; RefreshMenuItem: TMenuItem; GoToMenuItem: TMenuItem; N1: TMenuItem; procedure FormDestroy(Sender: TObject); procedure EmbeddedWebBrowserNavigateComplete2(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); procedure FormCreate(Sender: TObject); procedure ExitMenuItemClick(Sender: TObject); procedure RefreshMenuItemClick(Sender: TObject); procedure GoToMenuItemClick(Sender: TObject); private fTitle : string; fBaseUrl : string; fFullUrl : string; fStationNo : string; fUserDuz : string; fVistaServer : string; fVistaToken : string; fServer : string; fPort : integer; fPatientDfn : string; fPatientName : string; fPatientNatIdNum : string; fContextor : TContextor; fUserContext : TUserContext; fPatientContext : TPatientContext; fEmbeddedWebBrowser : TEmbeddedWB; fCCOWRPCBroker : TCCOWRPCBroker; function CreateContextor(fAppTitle : string; fPassCode : string) : TContextor; function CheckUserContext : TUserContext; function CheckPatientContext : TPatientContext; procedure ContextPending(const aContextItemCollection: IDispatch; var fAllowChange : boolean; var fReason : string); procedure ContextCanceled; procedure ContextCommitted; function GetUserDuz : string; function EncodeParam(fParam : string) : string; protected public procedure Init; procedure SetInitialContext(fTitle, fStationNo, fUserDuz, fPatientDfn, fUrl,fServer : string;fPort : integer); procedure SetSize(fHeight, fWidth : integer); procedure Navigate; overload; procedure Navigate(fUrl : String); overload; procedure Print; procedure ResizeBy(fPercent : integer); procedure SetPosition(fTop, fLeft : integer); procedure SetPositionCenter; end; const CPRS_TITLE = 'VistA CPRS in use by:'; var WebClientView : TWebClientView; GSaved8087CW : Word; NeedToUnitialize : Boolean; // True if the OLE subsystem could be initialized successfully. implementation {$R *.dfm} procedure TWebClientView.SetInitialContext(fTitle, fStationNo, fUserDuz, fPatientDfn, fUrl, fServer : string;fPort : integer); begin self.fTitle:=fTitle; self.caption:=fTitle; self.fServer:=fServer; self.fPort:=fPort; if (fStationNo <> '') then self.fStationNo:=fStationNo; if (fUserDuz <> '') then self.fUserDuz:=fUserDuz; if (fPatientDfn <> '') then self.fPatientDfn:=fPatientDfn; self.fBaseUrl:=fUrl; if Pos(fBaseUrl, '?') = 0 then fBaseUrl:=fBaseUrl + '?' else fBaseUrl:=fBaseUrl + '&'; Init; end; procedure TWebClientView.Init; begin if fContextor <> nil then begin fUserContext:=CheckUserContext; // get the user's DUZ if (fUserContext <> nil) then begin if (fUserContext.fVistaToken <> '') then begin fVistaToken:=fUserContext.fVistaToken; end; if (fUserContext.fVistaServer <> '') then begin fVistaServer:=fUserContext.fVistaServer; end; if (self.fStationNo = '') AND (fUserContext.fStationNo <> '') then begin fStationNo:=fUserContext.fStationNo; end; end; if (fUserDuz = '') then begin fUserDuz:=GetUserDuz; end; fPatientContext:=CheckPatientContext; end; end; procedure TWebClientView.Navigate; var i : integer; fList : TStringList; begin if fFullUrl = '' then begin fFullUrl:=fBaseUrl + 'stationNo=' + fStationNo + '&' + 'userDuz=' + fUserDuz + '&' + 'patientDfn=' + fPatientDfn + '&' + 'patientName=' + EncodeParam(fPatientName) + '&' + 'patientNatIdNum=' + fPatientNatIdNum + '&' + 'vistaServer=' + EncodeParam(fVistaServer) + '&' + 'vistaToken=' + EncodeParam(fVistaToken); end; Navigate(fFullUrl); end; procedure TWebClientView.Navigate(fUrl : String); begin try fEmbeddedWebBrowser.Go(fUrl); except end; end; procedure TWebClientView.Print; begin fEmbeddedWebBrowser.Print; end; function TWebClientView.CreateContextor(fAppTitle : string; fPassCode : string) : TContextor; var ClassID: TCLSID; strOLEObject: string; begin Result:=nil; try strOLEObject := 'Sentillion.Contextor'; if (CLSIDFromProgID(PWideChar(WideString(strOLEObject)), ClassID) = S_OK) then begin Result:=TContextor.Create; if Result <> nil then begin with Result do begin SetContextPendingCallBack(ContextPending); SetContextCanceledCallBack(ContextCanceled); SetContextCommittedCallBack(ContextCommitted); JoinContext(fAppTitle, fPassCode, TRUE, FALSE); end; end; end; except // ignore end; end; function TWebClientView.CheckUserContext : TUserContext; begin Result:=nil; if fContextor <> nil then begin // Check CCOW context for a user try Result:=fContextor.GetUserContext; if (Result <> nil) AND (Result.fVistaServer <> '') then begin fVistaServer:=Result.fVistaServer; if (self.fStationNo = '') then begin fStationNo:=Result.fStationNo; end; fContextor.SetStationNumber(fStationNo); end else fContextor.SetStationNumber(fStationNo); except // ignore end; end; end; function TWebClientView.CheckPatientContext : TPatientContext; begin Result:=nil; if fContextor <> nil then begin // Check CCOW context for an open patient try Result:=fContextor.GetPatientContext; if (Result.fDfn <> '') then begin fPatientDfn:=Result.fDfn; end; if (Result.fName <> '') then begin fPatientName:=Result.fName; end; if (Result.fNatIdNum <> '') then begin fPatientNatIdNum:=Result.fNatIdNum; end; except // ignore end; end; end; function TWebClientView.GetUserDuz : string; begin Result:=''; if fContextor <> nil then begin try fCCOWRPCBroker:=TCCOWRPCBroker.Create(application); with fCCOWRPCBroker do begin Server:=fServer; ListenerPort:=fPort; KernelLogIn:=TRUE; Login.Mode:=lmAppHandle; Contextor:=fContextor.ContextorControl; if (fUserContext <> nil) then begin Login.NTToken:=fUserContext.fVistaToken; Login.LogInHandle:=fUserContext.fVistaToken; end; Connected:=TRUE; Result:=User.DUZ; Connected:=FALSE; end; except end; end; end; procedure TWebClientView.GoToMenuItemClick(Sender: TObject); begin if GoToEntry.GetUrl(fFullUrl) then begin Navigate(fFullUrl); end; end; procedure TWebClientView.ContextPending(const aContextItemCollection: IDispatch; var fAllowChange : boolean; var fReason : string); begin fAllowChange:=TRUE; end; procedure TWebClientView.ContextCanceled; begin // end; procedure TWebClientView.ContextCommitted; begin if fContextor.CurrentState = ContextorUnit.CCOW_ENABLED then begin fUserContext:=CheckUserContext; if (fUserContext <> nil) AND (fUserContext.fVistaToken <> fVistaToken) then begin fUserDuz:=GetUserDuz; fVistaToken:=fUserContext.fVistaToken; if (self.fStationNo = '') then begin fStationNo:=fUserContext.fStationNo; end; fVistaServer:=fUserContext.fVistaServer; fContextor.UpdateUserContext(fUserContext); end; fPatientContext:=CheckPatientContext; fContextor.UpdatePatientContext(fPatientContext); fFullUrl:=''; Navigate; end; end; procedure TWebClientView.SetSize(fHeight, fWidth : integer); begin self.ClientHeight:=fHeight; self.ClientWidth:=fWidth; end; procedure TWebClientView.RefreshMenuItemClick(Sender: TObject); begin Navigate; end; procedure TWebClientView.ResizeBy(fPercent : integer); var fResizeBy : double; begin fResizeBy:=fPercent * 0.01; self.ClientHeight:=self.ClientHeight + Round(self.ClientHeight * fResizeBy); self.ClientWidth:=self.ClientWidth + Round(self.ClientWidth * fResizeBy); end; procedure TWebClientView.SetPosition(fTop, fLeft : integer); begin self.Top:=fTop; self.Left:=fLeft; end; procedure TWebClientView.SetPositionCenter; var fMonitor : TMonitor; fLeft, fTop, fWidth, fHeight : integer; fCprsHwnd : HWND; begin fCprsHwnd:=LL_SysUtils.FindWindowEx(CPRS_TITLE); if (fCprsHwnd <> 0) then begin fMonitor:=Screen.MonitorFromWindow(fCprsHwnd, mdNearest); if (fMonitor <> nil) then begin fLeft:=fMonitor.Left; fTop:=fMonitor.Top; fHeight:=fMonitor.Height; fWidth:=fMonitor.Width; end; end else begin fLeft:=Screen.DesktopLeft; fTop:=Screen.DesktopTop; fHeight:=Screen.DesktopHeight; fWidth:=Screen.DesktopWidth; end; fLeft:=fLeft + ((fWidth div 2) - (self.Width div 2)); fTop:=fTop + ((fHeight div 2) - (self.Height div 2)); SetPosition(fTop, fLeft); end; procedure TWebClientView.EmbeddedWebBrowserNavigateComplete2(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); begin fEmbeddedWebBrowser.UserInterfaceOptions:=[DontUse3DBorders]; end; procedure TWebClientView.ExitMenuItemClick(Sender: TObject); begin Application.Terminate; end; procedure TWebClientView.FormCreate(Sender: TObject); begin fEmbeddedWebBrowser:=TEmbeddedWB.Create(nil); with fEmbeddedWebBrowser do begin Align:=alClient; Parent:=self; UserInterfaceOptions:=[DontUse3DBorders, DontUseScrollBars]; OnNavigateComplete2:=EmbeddedWebBrowserNavigateComplete2; end; fContextor:=CreateContextor('Web Client', ''); end; procedure TWebClientView.FormDestroy(Sender: TObject); begin if Assigned(fEmbeddedWebBrowser) then begin fEmbeddedWebBrowser.Navigate('about:blank'); Application.ProcessMessages; CoFreeUnusedLibraries(); FreeAndNil(fEmbeddedWebBrowser); end; end; function TWebClientView.EncodeParam(fParam : string) : string; begin fParam:=LL_StringUtils.ReplaceText(fParam, '&', '&#38;'); Result:=TIdURI.ParamsEncode(fParam); end; initialization GSaved8087CW := Default8087CW; Set8087CW($133F); // Initialize OLE subsystem for drag'n drop and clipboard operations. NeedToUnitialize := Succeeded(OleInitialize(nil)); finalization Set8087CW(GSaved8087CW); if NeedToUnitialize then try OleUninitialize; except end; end.
unit SpPrivilegesZarplataControl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, cxCalendar, cxContainer, cxEdit, cxTextEdit, cxControls, cxGroupBox, zProc, Unit_ZGlobal_Consts, cxLabel, cxSpinEdit, ExtCtrls, ComCtrls, ActnList, zMessages; type TFormSp_PrivilegesControl = class(TForm) IdentificationBox: TcxGroupBox; YesBtn: TcxButton; CancelBtn: TcxButton; PeriodBox: TcxGroupBox; DateEnd: TcxDateEdit; OptionsBox: TcxGroupBox; MinSpinEdit: TcxSpinEdit; MaxSpinEdit: TcxSpinEdit; MinLabel: TcxLabel; MaxLabel: TcxLabel; DateBeg: TcxDateEdit; Bevel1: TBevel; Bevel2: TBevel; KodLabel: TcxLabel; NameLabel: TcxLabel; DateBegLabel: TcxLabel; DateEndLabel: TcxLabel; KoefficientLabel: TcxLabel; KodEdit: TcxMaskEdit; KoefficientEdit: TcxMaskEdit; NameEdit: TcxMaskEdit; ActionList1: TActionList; Action1: TAction; LabelKodPriv1DF: TcxLabel; MaskEditKodPriv1DF: TcxMaskEdit; procedure CancelBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure KodEditKeyPress(Sender: TObject; var Key: Char); procedure MinSpinEditExit(Sender: TObject); procedure MaxSpinEditEnter(Sender: TObject); procedure DateBegExit(Sender: TObject); procedure DateEndExit(Sender: TObject); procedure NameEditKeyPress(Sender: TObject; var Key: Char); procedure Action1Execute(Sender: TObject); private PLanguageIndex:integer; public end; implementation {$R *.dfm} procedure TFormSp_PrivilegesControl.CancelBtnClick(Sender: TObject); begin self.DateEnd.Date := Date; self.DateBeg.Date := Date; self.KoefficientEdit.Text := ''; self.ModalResult := mrCancel; end; procedure TFormSp_PrivilegesControl.FormCreate(Sender: TObject); begin PLanguageIndex := LanguageIndex; self.IdentificationBox.Caption := ''; self.OptionsBox.Caption := ''; self.PeriodBox.Caption := ''; self.MinLabel.Caption := LabelMinAmount_Caption[PLanguageIndex]; self.MaxLabel.Caption := LabelMaxAmount_Caption[PLanguageIndex]; self.YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; self.CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; self.KodLabel.Caption := LabelKod_Caption[PLanguageIndex]; self.NameLabel.Caption := LabelName_Caption[PLanguageIndex]; self.KoefficientLabel.Caption := LabelKoefficient_Caption[PLanguageIndex]; self.DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]; self.DateEndLabel.Caption := LabelDateEnd_Caption[PLanguageIndex]; self.LabelKodPriv1DF.Caption := LabelKod1DF_Caption[PLanguageIndex]; self.DateEnd.Date := Date; self.DateBeg.Date := Date; self.KoefficientEdit.Properties.EditMask := '\d (['+ZSystemDecimalSeparator+']\d\d?)?'; end; procedure TFormSp_PrivilegesControl.KodEditKeyPress(Sender: TObject; var Key: Char); begin if (length(KodEdit.Text)=4) and (key in ['0'..'9']) then key:=#0; end; procedure TFormSp_PrivilegesControl.MinSpinEditExit(Sender: TObject); begin MaxSpinEdit.Value:=MinSpinEdit.Value; if MaxSpinEdit.Properties.MaxValue=MinSpinEdit.Value then MaxSpinEdit.Properties.Increment:=0 else begin MaxSpinEdit.Properties.MinValue:=MinSpinEdit.Value; MaxSpinEdit.Properties.Increment:=1; end; end; procedure TFormSp_PrivilegesControl.MaxSpinEditEnter(Sender: TObject); begin MinSpinEditExit(Sender); end; procedure TFormSp_PrivilegesControl.DateBegExit(Sender: TObject); begin DateEnd.Date:=DateBeg.Date; if DateEnd.Properties.MinDate=DateBeg.Date then DateEnd.Properties.ReadOnly:=true else begin DateEnd.Properties.MinDate:=DateBeg.Date; DateEnd.Properties.ReadOnly:=false; end; end; procedure TFormSp_PrivilegesControl.DateEndExit(Sender: TObject); begin if DateEnd.Date<DateBeg.Date then DateEnd.Date:=DateBeg.Date; end; procedure TFormSp_PrivilegesControl.NameEditKeyPress(Sender: TObject; var Key: Char); begin if (Length(NameEdit.Text)=255) and (Key<>#7) and (key<>#8) then Key:=#0; end; procedure TFormSp_PrivilegesControl.Action1Execute(Sender: TObject); begin if KodEdit.Text<>'' then if NameEdit.Text<>'' then if KoefficientEdit.Text<>'' then if DateBeg.Text<>'' then if DateEnd.Text<>'' then if MaskEditKodPriv1DF.Text<>'' then if DateEnd.Date<DateBeg.Date then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]); if DateEnd.Enabled = True then DateEnd.SetFocus; if DateBeg.Enabled = True then DateBeg.SetFocus; end else ModalResult:=mrYes else MaskEditKodPriv1DF.SetFocus else DateEnd.SetFocus else DateBeg.SetFocus else KoefficientEdit.SetFocus else NameEdit.SetFocus else KodEdit.SetFocus; end; end.
unit SendSMS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, BaseForm, siComp, uniGUIBaseClasses, uniPanel, IdHTTP, uniButton, uniLabel, uniEdit, uniURLFrame, Data.DB, MemDS, DBAccess, Uni, uniBasicGrid, uniDBGrid, uniMultiItem, uniListBox, uniComboBox, uniDBComboBox, uniDBLookupComboBox; type TSendSMSForm = class(TBaseFormF) pnlHead: TUniContainerPanel; pnlDetail: TUniContainerPanel; PaymentsVQ: TUniQuery; PaymentsVQestNo: TIntegerField; PaymentsVQContractNo: TIntegerField; PaymentsVQName: TWideStringField; PaymentsVQUnit: TWideStringField; PaymentsVQPaymentSN: TIntegerField; PaymentsVQPaymentDate: TDateField; PaymentsVQPaymentValu: TFloatField; PaymentsVQPaid: TBooleanField; PaymentsVQPayDate: TDateField; PaymentsVQPayType: TWideStringField; PaymentsVQtenantID: TIntegerField; PaymentsVQUnitNo: TIntegerField; PaymentsVQID: TIntegerField; PaymentsVQsrc: TUniDataSource; btnRefresh: TUniButton; UniURLFrame1: TUniURLFrame; PaymentsVQPhone1: TWideStringField; SendBtn: TUniButton; dd: TUniDBGrid; PhoneCB: TUniDBLookupComboBox; procedure btnRefreshClick(Sender: TObject); procedure UniFormCreate(Sender: TObject); procedure SendBtnClick(Sender: TObject); private { Private declarations } procedure SendSMSMSG; Function GetPhoneNumbers() : String; public { Public declarations } end; function SendSMSForm: TSendSMSForm; implementation {$R *.dfm} uses MainModule, uniGUIApplication, G_Funcs; function SendSMSForm: TSendSMSForm; begin Result := TSendSMSForm(UniMainModule.GetFormInstance(TSendSMSForm)); end; //============================================================================== Function TSendSMSForm.GetPhoneNumbers; var I:integer; DataSet : TDataSet; OutPutBuffer : TBytes; tList: TStringList; begin if dd.SelectedRows.Count > 0 then begin DataSet := PaymentsVQ; tList := TStringList.Create; try DataSet.DisableControls; for I := 0 to dd.SelectedRows.Count-1 do begin OutPutBuffer := dd.SelectedRows.Items[i]; DataSet.GotoBookmark(OutPutBuffer); if i <> 0 then tList.Add(','); tList.Add(DataSet.FieldByName('Phone1').AsString); end; result := tList.Text; finally DataSet.EnableControls; end; end; end; //------------------------------------------------- procedure TSendSMSForm.SendSMSMSG; var WebPost,Msg,PhonesLst:String; begin Msg:='عزيزي المستأجر , نذكركم بموعد سداد الدفعه المستحقه'; PhonesLst:= GetPhoneNumbers; WebPost:='https://www.alfa-cell.com/api/msgSend.php?apiKey=a21f6b73ddbd4c15011f60bb2734185f' +'&numbers='+PhonesLst+' ' +'&sender=Aqar Alghad' +'&msg='+Msg +'&lang=3' +'&applicationType=68'; UniURLFrame1.URL:= WebPost; ShowSwM('تم ارسال الرسائل المحدده بنجاح'); end; //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- procedure TSendSMSForm.btnRefreshClick(Sender: TObject); begin inherited; PhoneCB.Clear; PaymentsVQ.Close; PaymentsVQ.Open; AdjustGridView(dd); SendBtn.Enabled := true; end; procedure TSendSMSForm.SendBtnClick(Sender: TObject); begin inherited; if UniMainModule.gSendSMS ='T' then begin SendSMSMSG(); SendBtn.Enabled := false; end; end; procedure TSendSMSForm.UniFormCreate(Sender: TObject); begin inherited; btnRefreshClick(Sender); end; end.
unit PanelRights; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, uSystemTypes; type TPanelRights = class(TPanel) private { Private declarations } FCommands : TSetCommandType; protected { Protected declarations } public { Public declarations } procedure UpdateButtons(lEnabled : Boolean); procedure DisableButtons; constructor Create(AOwner : TComponent); override; published { Published declarations } property Commands : TSetCommandType read FCommands write FCommands default [btInc, btAlt, btExc, btPos, btFlt, btImp, btExp]; end; procedure Register; implementation constructor TPanelRights.Create(AOwner : TComponent); begin inherited Create(AOwner); FCommands := [btInc, btAlt, btExc, btPos, btFlt, btImp, btExp]; end; procedure TPanelRights.UpdateButtons(lEnabled : Boolean); var ButtonType : TBtnCommandType; i : integer; begin for i := 0 to ControlCount -1 do begin // Testa se e TButton if (Controls[i] is TButton) or (Controls[i] is TSpeedButton) then begin if TComponent(Controls[i]).Tag > 6 then TButton(Controls[i]).Enabled := lEnabled else if TComponent(Controls[i]).Tag >= 0 then begin ButtonType := TBtnCommandType(TComponent(Controls[i]).Tag); if ButtonType in [btInc, btFlt] then TButton(Controls[i]).Enabled := (ButtonType in FCommands) else TButton(Controls[i]).Enabled := (ButtonType in FCommands) and lEnabled; end end; end; end; procedure TPanelRights.DisableButtons; var i : integer; begin for i := 0 to ControlCount -1 do begin // Testa se e TButton if (Controls[i] is TButton) or (Controls[i] is TSpeedButton) then if (TComponent(Controls[i]).Tag <= 6) and (TComponent(Controls[i]).Tag >= 0) then TButton(Controls[i]).Enabled := False end; end; procedure Register; begin RegisterComponents('NewPower', [TPanelRights]); end; end.
//Contains all script commands used by the lua system //Note the command lual_argcheck will cause the procedure it is in to call exit; //So be aware of your code! unit LuaItemCommands; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses // LuaCoreRoutines, LuaTypes; function LoadItemCommands(var ALua : TLua) : boolean; implementation //Forward declarations of delphi procedures that are added to the lua engine. //example function addnpc(ALua : TLua) : integer; cdecl; forward; (*const ItemCommandCount = 1;*) (*const //"Function name in lua" , Delphi function name //This assigns our procedures here, with the lua system ItemCommandList : array [1..ItemCommandCount] of lual_reg = ( //Example (name:'npc';func:addnpc), (name:'warp';func:addwarp) );*) //[2008/11/17] Tsusai - Added result //Registers all the Item Commands into the Lua instance function LoadItemCommands(var ALua : TLua) : boolean; {var idx : integer;} begin { for idx := 1 to ItemCommandCount do begin lua_register( ALua, ItemCommandList[idx].name, ItemCommandList[idx].func ); end;} Result := true; end; end.
{*******************************************************} { } { FormMain.pas { Copyright @2014/5/20 16:01:35 by 姜梁 { } { 功能描述: { 函数说明: {*******************************************************} unit FormStart; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,ConditionFileFrame,ConditionTypeFrame,hHelperFunc, dDataModelSearchCondition,dDataModelFileInfo,fFrameSearch; type EndSreachToMainEvent = procedure() of object; type TfrmProcess = class(TForm) pnlTop: TPanel; pnlBottom: TPanel; pnlCenter: TPanel; lblText: TLabel; btnPrev: TButton; btnNext: TButton; btnReset: TButton; lblContext: TLabel; procedure FormShow(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure btnPrevClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnResetClick(Sender: TObject); private pageIndex:Integer; myFrameFileCondition:TFrameFile; myFrameTypeCondition:TFrameType; myFrameSreachProcess:TFrameSearchProcess; procedure OtherHide(); procedure OnBreakSreach(); procedure OnFinishSreach(title,context: string); public mySreachConditon: TMySreachCondition; myListSameFile:TListSameFileData; MyEndEvent:EndSreachToMainEvent; procedure InitForm(); end; var frmProcess: TfrmProcess; implementation {$R *.dfm} {$REGION '主按钮'} procedure TfrmProcess.btnNextClick(Sender: TObject); begin Inc(pageIndex); OtherHide(); end; procedure TfrmProcess.btnPrevClick(Sender: TObject); begin Dec(pageIndex); OtherHide(); end; procedure TfrmProcess.btnResetClick(Sender: TObject); begin btnReset.Hide; btnPrev.Show; btnNext.Show; pageIndex:= 1; OtherHide; end; {$ENDREGION} {$REGION '窗体事件'} procedure TfrmProcess.FormDestroy(Sender: TObject); begin myFrameFileCondition.Free; myFrameTypeCondition.Free; myFrameSreachProcess.Free; end; procedure TfrmProcess.FormShow(Sender: TObject); begin pageIndex:= 1; btnPrev.Enabled := False; btnReset.Hide; OtherHide(); myFrameFileCondition.Show; end; procedure TfrmProcess.InitForm; begin myFrameFileCondition:= TFrameFile.Create(Self); myFrameFileCondition.Parent:= pnlCenter; myFrameFileCondition.Align := alClient; myFrameFileCondition.InitData(mySreachConditon); myFrameTypeCondition:= TFrameType.Create(Self); myFrameTypeCondition.Parent:= pnlCenter; myFrameTypeCondition.Align := alClient; myFrameTypeCondition.InitData(mySreachConditon); myFrameSreachProcess:= TFrameSearchProcess.Create(Self); myFrameSreachProcess.Parent:= pnlCenter; myFrameSreachProcess.Align := alClient; myFrameSreachProcess.myListSameFile:= myListSameFile; myFrameSreachProcess.mySreachCondition := mySreachConditon; myFrameSreachProcess.MyBreakSreachEvent := OnBreakSreach; myFrameSreachProcess.MyFinishSreachEvent := OnFinishSreach; end; {$ENDREGION} {$REGION '通知消息'} /// <summary> /// 当点击了取消查找的btn /// </summary> procedure TfrmProcess.OnBreakSreach; begin btnPrev.Show; btnNext.Show; Dec(pageIndex); OtherHide(); end; /// <summary> /// 当两个线程完成以后的,通知主窗体 /// </summary> procedure TfrmProcess.OnFinishSreach(title,context: string); begin btnNext.Show; Inc(pageIndex); OtherHide(); lblText.Caption := title; lblContext.Caption := context; end; {$ENDREGION} /// <summary> /// 窗体转换的主要函数 /// </summary> procedure TfrmProcess.OtherHide; begin myFrameFileCondition.Hide; myFrameTypeCondition.Hide; myFrameSreachProcess.Hide; case pageIndex of 1 : begin myFrameFileCondition.Show; btnPrev.Enabled := False; btnNext.Caption:= 'Next >'; lblText.Caption := 'Choose Scan Site'; lblContext.Caption := 'Cloned files,especially those with large size,may waste your valuable disk space'; end; 2 : begin myFrameTypeCondition.Show; btnPrev.Enabled := True; btnNext.Caption:= 'Start Scan'; lblText.Caption := 'Select File Types And Other Parameter'; lblContext.Caption := 'Here list the most common file types.Please select the file you want to scan.And other parameter help you how to scan.'; end; 3 : begin mySreachConditon.CleanAll; myFrameFileCondition.GetMessage; myFrameTypeCondition.GetMessage; myFrameSreachProcess.Show; myFrameSreachProcess.BeginThread; btnPrev.Hide; btnNext.Hide; lblText.Caption := 'Scaning'; lblContext.Caption := ''; end; 4 : begin myFrameSreachProcess.Show; btnNext.Caption:= 'Completed'; btnReset.Show; end; 5: begin if Assigned(MyEndEvent) then begin MyEndEvent; end; Close; end; end; end; end.
unit Dfm2Text.Form.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.IOUtils, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls; type TFormMain = class(TForm) GrpDFMBin: TGroupBox; GpDFMBin: TGridPanel; LblSourceBin: TLabel; EdtSourceBin: TEdit; LblDestBin: TLabel; EdtDestBin: TEdit; BtnConvBin: TButton; GrpDFMTexte: TGroupBox; GpDFMTexte: TGridPanel; LblSourceTexte: TLabel; EdtSourceTexte: TEdit; LblDestTexte: TLabel; EdtDestTexte: TEdit; BtnConvTexte: TButton; PnlSourceBin: TPanel; BtnSourceBin: TButton; PnlSourceTexte: TPanel; BtnSourceTexte: TButton; dlgOpenDFM: TOpenDialog; procedure EdtSourceBinChange(Sender: TObject); procedure EdtSourceTexteChange(Sender: TObject); procedure BtnConvBinClick(Sender: TObject); procedure BtnConvTexteClick(Sender: TObject); procedure BtnSourceBinClick(Sender: TObject); procedure BtnSourceTexteClick(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } end; var FormMain: TFormMain; implementation uses Dfm2Text.Libs.Converts; {$R *.dfm} procedure TFormMain.EdtSourceBinChange(Sender: TObject); begin BtnConvBin.Enabled := FileExists(EdtSourceBin.Text) and SameText(TPath.GetExtension(EdtSourceBin.Text), '.dfm'); if BtnConvBin.Enabled then EdtDestBin.Text := ChangeFileExt(EdtSourceBin.Text, '.txt.dfm'); end; procedure TFormMain.EdtSourceTexteChange(Sender: TObject); begin BtnConvTexte.Enabled := FileExists(EdtSourceTexte.Text) and SameText(TPath.GetExtension(EdtSourceTexte.Text), '.dfm'); if BtnConvTexte.Enabled then EdtDestTexte.Text := ChangeFileExt(EdtSourceTexte.Text, '.bin.dfm'); end; procedure TFormMain.BtnConvBinClick(Sender: TObject); begin Dfm2Txt(EdtSourceBin.Text, EdtDestBin.Text); end; procedure TFormMain.BtnConvTexteClick(Sender: TObject); begin Txt2DFM(EdtSourceTexte.Text, EdtDestTexte.Text); end; procedure TFormMain.BtnSourceBinClick(Sender: TObject); begin if BtnConvBin.Enabled then begin dlgOpenDFM.InitialDir := TPath.GetDirectoryName(EdtSourceBin.Text); dlgOpenDFM.FileName := TPath.GetFileName(EdtSourceBin.Text); end; if dlgOpenDFM.Execute() then EdtSourceBin.Text := dlgOpenDFM.FileName; end; procedure TFormMain.BtnSourceTexteClick(Sender: TObject); begin if BtnConvTexte.Enabled then begin dlgOpenDFM.InitialDir := TPath.GetDirectoryName(EdtSourceTexte.Text); dlgOpenDFM.FileName := TPath.GetFileName(EdtSourceTexte.Text); end; if dlgOpenDFM.Execute() then EdtSourceTexte.Text := dlgOpenDFM.FileName; end; end.
program Space; uses GraphABC; const MaxDepth = 100; MaxWidth = WindowWidth div 2; MaxHeight = WindowHeight div 2; MaxSpeed = 0; MaxWeight = 100; Density = 1; dt = 0.01; N = 20; G = 3; px = WindowWidth div 2; py = WindowHeight div 2; n_ = 5; type Point = record x,y,z: Real; vx,vy,vz: Real; m,r: Real; exist: Boolean; end; var a: array [1..N] of Point; ax,ay,az: Real; fx,fy,fz: Real; F_: Real; i,j: Integer; function Scale(r0,z: Real): Real; begin If (z<MaxDepth) and (z>=0) then result:=r0/(1+z/MaxDepth/n_) else result:=0; end; function SetPoint(x,y,z,vx,vy,vz,m: Real): Point; begin result.x:=x; result.y:=y; result.z:=z; result.vx:=vx; result.vy:=vy; result.vz:=vz; result.m:=m; result.r:=power(3/4*m/Density,1/3); result.exist:=true; end; function F(m1,m2,r: Real): Real; begin F:=G*m1*m2/sqr(r); end; function dst(a,b: Point): Real; begin result:=sqrt(sqr(a.x-b.x)+sqr(a.y-b.y)+sqr(a.z-b.z)); end; begin Randomize; MaximizeWindow; LockDrawing; for i:=1 to N do a[i]:=SetPoint(MaxWidth*(1-random*2),MaxHeight*(1-random*2),MaxDepth*(1-random*2),MaxSpeed*(1-random*2),MaxSpeed*(1-random*2),MaxSpeed*(1-random*2),MaxWeight*(random+10)); while true do begin ClearWindow; for i:=1 to N do for j:=1 to N do If (i<>j) and (a[i].exist) then begin F_:=F(a[i].m,a[j].m,dst(a[i],a[j])); fx:=F_*(a[j].x-a[i].x)/dst(a[i],a[j]); fy:=F_*(a[j].y-a[i].y)/dst(a[i],a[j]); fz:=F_*(a[j].z-a[i].z)/dst(a[i],a[j]); ax:=fx/a[i].m; ay:=fy/a[i].m; az:=fz/a[i].m; a[i].vx:=a[i].vx+dt*ax; a[i].vy:=a[i].vy+dt*ay; a[i].vz:=a[i].vz+dt*az; a[i].x:=a[i].x+dt*a[i].vx; a[i].y:=a[i].y+dt*a[i].vy; a[i].z:=a[i].z+dt*a[i].vz; Circle(Round(a[i].x)+px,Round(a[i].y)+py,Round(Scale(a[i].r,a[i].z))); If a[i].x>MaxWidth then a[i].vx:=-a[i].vx; If a[i].y>MaxHeight then a[i].vy:=-a[i].vy; If a[i].z>MaxDepth then a[i].vz:=-a[i].vz; If a[i].x<-MaxWidth then a[i].vx:=-a[i].vx; If a[i].y<-MaxHeight then a[i].vy:=-a[i].vy; If a[i].z<0 then a[i].vz:=-a[i].vz; If dst(a[i],a[j])<=a[i].r+a[j].r then begin a[j].exist:=false; a[i]:=SetPoint(a[i].x,a[i].y,a[i].z,(a[i].vx*a[i].m+a[j].vx*a[j].m)/(a[i].m+a[j].m), (a[i].vy*a[i].m+a[j].vy*a[j].m)/(a[i].m+a[j].m),(a[i].vz*a[i].m+a[j].vz*a[j].m)/(a[i].m+a[j].m),a[i].m+a[j].m); end; end; Redraw; sleep(1); end; end.
unit ItmUnit; interface uses Windows, Classes, SysUtils, SDK, Grobal2; type TItemUnit = class private function GetRandomRange(nCount, nRate: Integer): Integer; public m_ItemNameList: TGList; constructor Create(); destructor Destroy; override; procedure GetItemAddValue(UserItem: pTUserItem; var StdItem: TStdItem); procedure RandomUpgradeWeapon(UserItem: pTUserItem); procedure RandomUpgradeDress(UserItem: pTUserItem); procedure RandomUpgrade19(UserItem: pTUserItem); procedure RandomUpgrade202124(UserItem: pTUserItem); procedure RandomUpgrade26(UserItem: pTUserItem); procedure RandomUpgrade22(UserItem: pTUserItem); procedure RandomUpgrade23(UserItem: pTUserItem); procedure RandomUpgradeHelMet(UserItem: pTUserItem); procedure RandomUpgradeBoots(UserItem: pTUserItem); procedure UnknowHelmet(UserItem: pTUserItem); procedure UnknowRing(UserItem: pTUserItem); procedure UnknowNecklace(UserItem: pTUserItem); function LoadCustomItemName(): Boolean; function SaveCustomItemName(): Boolean; function AddCustomItemName(nMakeIndex, nItemIndex: Integer; sItemName: string): Boolean; function DelCustomItemName(nMakeIndex, nItemIndex: Integer): Boolean; function GetCustomItemName(nMakeIndex, nItemIndex: Integer): string; procedure Lock(); procedure UnLock(); end; implementation uses HUtil32, M2Share; { TItemUnit } constructor TItemUnit.Create; begin m_ItemNameList := TGList.Create; end; destructor TItemUnit.Destroy; var I: Integer; begin if m_ItemNameList.Count > 0 then begin//20080630 for I := 0 to m_ItemNameList.Count - 1 do begin if pTItemName(m_ItemNameList.Items[I]) <> nil then Dispose(pTItemName(m_ItemNameList.Items[I])); end; end; m_ItemNameList.Free; inherited; end; function TItemUnit.GetRandomRange(nCount, nRate: Integer): Integer; var I: Integer; begin Result := 0; for I := 0 to nCount - 1 do if Random(nRate) = 0 then Inc(Result); end; procedure TItemUnit.RandomUpgradeWeapon(UserItem: pTUserItem); //随机升级武器 var nC, n10, n14: Integer; begin nC := GetRandomRange(g_Config.nWeaponDCAddValueMaxLimit, g_Config.nWeaponDCAddValueRate); if Random(g_Config.nWeaponDCAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nWeaponDCAddValueMaxLimit then UserItem.btValue[0]:= g_Config.nWeaponDCAddValueMaxLimit;//20080724 限制上限 end; nC := GetRandomRange(12, 15); if Random(15) = 0 then begin n14 := (nC + 1) div 3; if n14 > 0 then begin if Random(3) <> 0 then begin UserItem.btValue[6] := n14; end else begin UserItem.btValue[6] := n14 + 10; end; end; end; nC := GetRandomRange(g_Config.nWeaponMCAddValueMaxLimit, g_Config.nWeaponMCAddValueRate); if Random(g_Config.nWeaponMCAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nWeaponMCAddValueMaxLimit then UserItem.btValue[1]:= g_Config.nWeaponMCAddValueMaxLimit;//20080724 限制上限 end; nC := GetRandomRange(g_Config.nWeaponSCAddValueMaxLimit, g_Config.nWeaponSCAddValueRate); if Random(g_Config.nWeaponSCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nWeaponSCAddValueMaxLimit then UserItem.btValue[2]:= g_Config.nWeaponSCAddValueMaxLimit;//20080724 限制上限 end; nC := GetRandomRange(12, 15); if Random(15) = 0 then begin UserItem.btValue[5] := nC div 2 + 1; end; nC := GetRandomRange(12, 12); if Random(3) < 2 then begin n10 := (nC + 1) * 2000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; nC := GetRandomRange(12, 15); if Random(10) = 0 then begin UserItem.btValue[7] := nC div 2 + 1; end; end; procedure TItemUnit.RandomUpgradeDress(UserItem: pTUserItem); var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nDressACAddValueMaxLimit, g_Config.nDressACAddValueRate); if Random(g_Config.nDressACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nDressACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nDressACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nDressMACAddValueMaxLimit, g_Config.nDressMACAddValueRate); if Random(g_Config.nDressMACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nDressMACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nDressMACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nDressDCAddValueMaxLimit, g_Config.nDressDCAddValueRate); if Random(g_Config.nDressDCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nDressDCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nDressDCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nDressMCAddValueMaxLimit, g_Config.nDressMCAddValueRate); if Random(g_Config.nDressMCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nDressMCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nDressMCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nDressSCAddValueMaxLimit, g_Config.nDressSCAddValueRate); if Random(g_Config.nDressSCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nDressSCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nDressSCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 10); if Random(8) < 6 then begin n10 := (nC + 1) * 2000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; procedure TItemUnit.RandomUpgrade202124(UserItem: pTUserItem); var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nNeckLace202124ACAddValueMaxLimit, g_Config.nNeckLace202124ACAddValueRate); if Random(g_Config.nNeckLace202124ACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nNeckLace202124ACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nNeckLace202124ACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace202124MACAddValueMaxLimit, g_Config.nNeckLace202124MACAddValueRate); if Random(g_Config.nNeckLace202124MACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nNeckLace202124MACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nNeckLace202124MACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace202124DCAddValueMaxLimit, g_Config.nNeckLace202124DCAddValueRate); if Random(g_Config.nNeckLace202124DCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nNeckLace202124DCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nNeckLace202124DCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace202124MCAddValueMaxLimit, g_Config.nNeckLace202124MCAddValueRate); if Random(g_Config.nNeckLace202124MCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nNeckLace202124MCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nNeckLace202124MCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace202124SCAddValueMaxLimit, g_Config.nNeckLace202124SCAddValueRate); if Random(g_Config.nNeckLace202124SCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nNeckLace202124SCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nNeckLace202124SCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 12); if Random(20) < 15 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; procedure TItemUnit.RandomUpgrade26(UserItem: pTUserItem); var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nArmRing26ACAddValueMaxLimit, g_Config.nArmRing26ACAddValueRate); if Random(g_Config.nArmRing26ACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nArmRing26ACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nArmRing26ACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nArmRing26MACAddValueMaxLimit, g_Config.nArmRing26MACAddValueRate); if Random(g_Config.nArmRing26MACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nArmRing26MACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nArmRing26MACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nArmRing26DCAddValueMaxLimit, g_Config.nArmRing26DCAddValueRate); if Random(g_Config.nArmRing26DCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nArmRing26DCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nArmRing26DCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nArmRing26MCAddValueMaxLimit, g_Config.nArmRing26MCAddValueRate); if Random(g_Config.nArmRing26MCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nArmRing26MCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nArmRing26MCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nArmRing26SCAddValueMaxLimit, g_Config.nArmRing26SCAddValueRate); if Random(g_Config.nArmRing26SCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nArmRing26SCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nArmRing26SCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 12); if Random(20) < 15 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; //随机升级-分类19物品(幸运类项链) procedure TItemUnit.RandomUpgrade19(UserItem: pTUserItem); //00494D60 var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nNeckLace19ACAddValueMaxLimit, g_Config.nNeckLace19ACAddValueRate); if Random(g_Config.nNeckLace19ACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nNeckLace19ACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nNeckLace19ACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace19MACAddValueMaxLimit, g_Config.nNeckLace19MACAddValueRate); if Random(g_Config.nNeckLace19MACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nNeckLace19MACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nNeckLace19MACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace19DCAddValueMaxLimit, g_Config.nNeckLace19DCAddValueRate); if Random(g_Config.nNeckLace19DCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nNeckLace19DCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nNeckLace19DCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace19MCAddValueMaxLimit, g_Config.nNeckLace19MCAddValueRate); if Random(g_Config.nNeckLace19MCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nNeckLace19MCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nNeckLace19MCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nNeckLace19SCAddValueMaxLimit, g_Config.nNeckLace19SCAddValueRate); if Random(g_Config.nNeckLace19SCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nNeckLace19SCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nNeckLace19SCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 10); if Random(4) < 3 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; procedure TItemUnit.RandomUpgrade22(UserItem: pTUserItem); var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nRing22DCAddValueMaxLimit, g_Config.nRing22DCAddValueRate); if Random(g_Config.nRing22DCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nRing22DCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nRing22DCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nRing22MCAddValueMaxLimit, g_Config.nRing22MCAddValueRate); if Random(g_Config.nRing22MCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nRing22MCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nRing22MCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nRing22SCAddValueMaxLimit, g_Config.nRing22SCAddValueRate); if Random(g_Config.nRing22SCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nRing22SCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nRing22SCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 12); if Random(4) < 3 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; procedure TItemUnit.RandomUpgrade23(UserItem: pTUserItem); var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nRing23ACAddValueMaxLimit, g_Config.nRing23ACAddValueRate); if Random(g_Config.nRing23ACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nRing23ACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nRing23ACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nRing23MACAddValueMaxLimit, g_Config.nRing23MACAddValueRate); if Random(g_Config.nRing23MACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nRing23MACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nRing23MACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nRing23DCAddValueMaxLimit, g_Config.nRing23DCAddValueRate); if Random(g_Config.nRing23DCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nRing23DCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nRing23DCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nRing23MCAddValueMaxLimit, g_Config.nRing23MCAddValueRate); if Random(g_Config.nRing23MCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nRing23MCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nRing23MCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nRing23SCAddValueMaxLimit, g_Config.nRing23SCAddValueRate); if Random(g_Config.nRing23SCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nRing23SCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nRing23SCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 12); if Random(4) < 3 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; //头盔,斗笠 极品属性 procedure TItemUnit.RandomUpgradeHelMet(UserItem: pTUserItem); //00495110 var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nHelMetACAddValueMaxLimit, g_Config.nHelMetACAddValueRate); if Random(g_Config.nHelMetACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1; if UserItem.btValue[0] > g_Config.nHelMetACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nHelMetACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nHelMetMACAddValueMaxLimit, g_Config.nHelMetMACAddValueRate); if Random(g_Config.nHelMetMACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1; if UserItem.btValue[1] > g_Config.nHelMetMACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nHelMetMACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nHelMetDCAddValueMaxLimit, g_Config.nHelMetDCAddValueRate); if Random(g_Config.nHelMetDCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1; if UserItem.btValue[2] > g_Config.nHelMetDCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nHelMetDCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nHelMetMCAddValueMaxLimit, g_Config.nHelMetMCAddValueRate); if Random(g_Config.nHelMetMCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1; if UserItem.btValue[3] > g_Config.nHelMetMCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nHelMetMCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nHelMetSCAddValueMaxLimit, g_Config.nHelMetSCAddValueRate); if Random(g_Config.nHelMetSCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1; if UserItem.btValue[4] > g_Config.nHelMetSCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nHelMetSCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 12); if Random(4) < 3 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; //20080503 鞋子腰带极品 procedure TItemUnit.RandomUpgradeBoots(UserItem: pTUserItem); var nC, n10: Integer; begin nC := GetRandomRange(g_Config.nBootsACAddValueMaxLimit, g_Config.nBootsACAddValueRate); if Random(g_Config.nBootsACAddRate) = 0 then begin UserItem.btValue[0] := nC + 1;//防御 if UserItem.btValue[0] > g_Config.nBootsACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nBootsACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nBootsMACAddValueMaxLimit, g_Config.nBootsMACAddValueRate); if Random(g_Config.nBootsMACAddRate) = 0 then begin UserItem.btValue[1] := nC + 1;//魔御 if UserItem.btValue[1] > g_Config.nBootsMACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nBootsMACAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nBootsDCAddValueMaxLimit , g_Config.nBootsDCAddValueRate ); if Random(g_Config.nBootsDCAddRate) = 0 then begin UserItem.btValue[2] := nC + 1;//攻击力 if UserItem.btValue[2] > g_Config.nBootsDCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nBootsDCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nBootsMCAddValueMaxLimit, g_Config.nBootsMCAddValueRate); if Random(g_Config.nBootsMCAddRate) = 0 then begin UserItem.btValue[3] := nC + 1;//魔法 if UserItem.btValue[3] > g_Config.nBootsMCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nBootsMCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(g_Config.nBootsSCAddValueMaxLimit, g_Config.nBootsSCAddValueRate); if Random(g_Config.nBootsSCAddRate) = 0 then begin UserItem.btValue[4] := nC + 1;//道术 if UserItem.btValue[4] > g_Config.nBootsSCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nBootsSCAddValueMaxLimit;//20080724 限制上线 end; nC := GetRandomRange(6, 12); if Random(4) < 3 then begin n10 := (nC + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + n10); UserItem.Dura := _MIN(65000, UserItem.Dura + n10); end; end; procedure TItemUnit.UnknowHelmet(UserItem: pTUserItem); //神秘头盔 var nC, nRandPoint, n14: Integer; begin nRandPoint := GetRandomRange(g_Config.nUnknowHelMetACAddValueMaxLimit, g_Config.nUnknowHelMetACAddRate); if nRandPoint > 0 then begin UserItem.btValue[0] := nRandPoint; if UserItem.btValue[0] > g_Config.nUnknowHelMetACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nUnknowHelMetACAddValueMaxLimit;//20080724 限制上线 end; n14 := nRandPoint; nRandPoint := GetRandomRange(g_Config.nUnknowHelMetMACAddValueMaxLimit, g_Config.nUnknowHelMetMACAddRate); if nRandPoint > 0 then begin UserItem.btValue[1] := nRandPoint; if UserItem.btValue[1] > g_Config.nUnknowHelMetMACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nUnknowHelMetMACAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, nRandPoint); nRandPoint := GetRandomRange(g_Config.nUnknowHelMetDCAddValueMaxLimit, g_Config.nUnknowHelMetDCAddRate); if nRandPoint > 0 then begin UserItem.btValue[2] := nRandPoint; if UserItem.btValue[2] > g_Config.nUnknowHelMetDCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nUnknowHelMetDCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, nRandPoint); nRandPoint := GetRandomRange(g_Config.nUnknowHelMetMCAddValueMaxLimit, g_Config.nUnknowHelMetMCAddRate); if nRandPoint > 0 then begin UserItem.btValue[3] := nRandPoint; if UserItem.btValue[3] > g_Config.nUnknowHelMetMCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nUnknowHelMetMCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, nRandPoint); nRandPoint := GetRandomRange(g_Config.nUnknowHelMetSCAddValueMaxLimit, g_Config.nUnknowHelMetSCAddRate); if nRandPoint > 0 then begin UserItem.btValue[4] := nRandPoint; if UserItem.btValue[4] > g_Config.nUnknowHelMetSCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nUnknowHelMetSCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, nRandPoint); nRandPoint := GetRandomRange(6, 30); if nRandPoint > 0 then begin nC := (nRandPoint + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + nC); UserItem.Dura := _MIN(65000, UserItem.Dura + nC); end; if Random(30) = 0 then UserItem.btValue[7] := 1; UserItem.btValue[8] := 1; if n14 >= 3 then begin if UserItem.btValue[0] >= 5 then begin UserItem.btValue[5] := 1; UserItem.btValue[6] := UserItem.btValue[0] * 3 + 25; Exit; end; if UserItem.btValue[2] >= 2 then begin UserItem.btValue[5] := 1; UserItem.btValue[6] := UserItem.btValue[2] * 4 + 35; Exit; end; if UserItem.btValue[3] >= 2 then begin UserItem.btValue[5] := 2; UserItem.btValue[6] := UserItem.btValue[3] * 2 + 18; Exit; end; if UserItem.btValue[4] >= 2 then begin UserItem.btValue[5] := 3; UserItem.btValue[6] := UserItem.btValue[4] * 2 + 18; Exit; end; UserItem.btValue[6] := n14 * 2 + 18; end; end; procedure TItemUnit.UnknowRing(UserItem: pTUserItem); //神秘戒指 var nC, n10, n14: Integer; begin n10 := GetRandomRange(g_Config.nUnknowRingACAddValueMaxLimit, g_Config.nUnknowRingACAddRate); if n10 > 0 then begin UserItem.btValue[0] := n10; if UserItem.btValue[0] > g_Config.nUnknowRingACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nUnknowRingACAddValueMaxLimit;//20080724 限制上线 end; n14 := n10; n10 := GetRandomRange(g_Config.nUnknowRingMACAddValueMaxLimit, g_Config.nUnknowRingMACAddRate); if n10 > 0 then begin UserItem.btValue[1] := n10; if UserItem.btValue[1] > g_Config.nUnknowRingMACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nUnknowRingMACAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(g_Config.nUnknowRingDCAddValueMaxLimit, g_Config.nUnknowRingDCAddRate); if n10 > 0 then begin UserItem.btValue[2] := n10; if UserItem.btValue[2] > g_Config.nUnknowRingDCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nUnknowRingDCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(g_Config.nUnknowRingMCAddValueMaxLimit, g_Config.nUnknowRingMCAddRate); if n10 > 0 then begin UserItem.btValue[3] := n10; if UserItem.btValue[3] > g_Config.nUnknowRingMCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nUnknowRingMCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(g_Config.nUnknowRingSCAddValueMaxLimit, g_Config.nUnknowRingSCAddRate); if n10 > 0 then begin UserItem.btValue[4] := n10; if UserItem.btValue[4] > g_Config.nUnknowRingSCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nUnknowRingSCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(6, 30); if n10 > 0 then begin nC := (n10 + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + nC); UserItem.Dura := _MIN(65000, UserItem.Dura + nC); end; if Random(30) = 0 then UserItem.btValue[7] := 1; UserItem.btValue[8] := 1; if n14 >= 3 then begin if UserItem.btValue[2] >= 3 then begin UserItem.btValue[5] := 1; UserItem.btValue[6] := UserItem.btValue[2] * 3 + 25; Exit; end; if UserItem.btValue[3] >= 3 then begin UserItem.btValue[5] := 2; UserItem.btValue[6] := UserItem.btValue[3] * 2 + 18; Exit; end; if UserItem.btValue[4] >= 3 then begin UserItem.btValue[5] := 3; UserItem.btValue[6] := UserItem.btValue[4] * 2 + 18; Exit; end; UserItem.btValue[6] := n14 * 2 + 18; end; end; procedure TItemUnit.UnknowNecklace(UserItem: pTUserItem); //神秘腰带 var nC, n10, n14: Integer; begin n10 := GetRandomRange(g_Config.nUnknowNecklaceACAddValueMaxLimit, g_Config.nUnknowNecklaceACAddRate); if n10 > 0 then begin UserItem.btValue[0] := n10; if UserItem.btValue[0] > g_Config.nUnknowNecklaceACAddValueMaxLimit then UserItem.btValue[0] := g_Config.nUnknowNecklaceACAddValueMaxLimit;//20080724 限制上线 end; n14 := n10; n10 := GetRandomRange(g_Config.nUnknowNecklaceMACAddValueMaxLimit, g_Config.nUnknowNecklaceMACAddRate); if n10 > 0 then begin UserItem.btValue[1] := n10; if UserItem.btValue[1] > g_Config.nUnknowNecklaceMACAddValueMaxLimit then UserItem.btValue[1] := g_Config.nUnknowNecklaceMACAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(g_Config.nUnknowNecklaceDCAddValueMaxLimit, g_Config.nUnknowNecklaceDCAddRate); if n10 > 0 then begin UserItem.btValue[2] := n10; if UserItem.btValue[2] > g_Config.nUnknowNecklaceDCAddValueMaxLimit then UserItem.btValue[2] := g_Config.nUnknowNecklaceDCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(g_Config.nUnknowNecklaceMCAddValueMaxLimit, g_Config.nUnknowNecklaceMCAddRate); if n10 > 0 then begin UserItem.btValue[3] := n10; if UserItem.btValue[3] > g_Config.nUnknowNecklaceMCAddValueMaxLimit then UserItem.btValue[3] := g_Config.nUnknowNecklaceMCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(g_Config.nUnknowNecklaceSCAddValueMaxLimit, g_Config.nUnknowNecklaceSCAddRate); if n10 > 0 then begin UserItem.btValue[4] := n10; if UserItem.btValue[4] > g_Config.nUnknowNecklaceSCAddValueMaxLimit then UserItem.btValue[4] := g_Config.nUnknowNecklaceSCAddValueMaxLimit;//20080724 限制上线 end; Inc(n14, n10); n10 := GetRandomRange(6, 30); if n10 > 0 then begin nC := (n10 + 1) * 1000; UserItem.DuraMax := _MIN(65000, UserItem.DuraMax + nC); UserItem.Dura := _MIN(65000, UserItem.Dura + nC); end; if Random(30) = 0 then UserItem.btValue[7] := 1; UserItem.btValue[8] := 1; if n14 >= 2 then begin if UserItem.btValue[0] >= 3 then begin UserItem.btValue[5] := 1; UserItem.btValue[6] := UserItem.btValue[0] * 3 + 25; Exit; end; if UserItem.btValue[2] >= 2 then begin UserItem.btValue[5] := 1; UserItem.btValue[6] := UserItem.btValue[2] * 3 + 30; Exit; end; if UserItem.btValue[3] >= 2 then begin UserItem.btValue[5] := 2; UserItem.btValue[6] := UserItem.btValue[3] * 2 + 20; Exit; end; if UserItem.btValue[4] >= 2 then begin UserItem.btValue[5] := 3; UserItem.btValue[6] := UserItem.btValue[4] * 2 + 20; Exit; end; UserItem.btValue[6] := n14 * 2 + 18; end; end; //取物品的附属属性 procedure TItemUnit.GetItemAddValue(UserItem: pTUserItem; var StdItem: TStdItem); //00495974 begin case StdItem.StdMode of 5, 6: begin //004959D6 StdItem.DC := MakeLong(LoWord(StdItem.DC), HiWord(StdItem.DC) + UserItem.btValue[0]); StdItem.MC := MakeLong(LoWord(StdItem.MC), HiWord(StdItem.MC) + UserItem.btValue[1]); StdItem.SC := MakeLong(LoWord(StdItem.SC), HiWord(StdItem.SC) + UserItem.btValue[2]); StdItem.AC := MakeLong(LoWord(StdItem.AC) + UserItem.btValue[3], HiWord(StdItem.AC) + UserItem.btValue[5]); StdItem.MAC := MakeLong(LoWord(StdItem.MAC) + UserItem.btValue[4], HiWord(StdItem.MAC) + UserItem.btValue[6]); if Byte(UserItem.btValue[7] - 1) < 10 then begin //神圣 StdItem.Source := UserItem.btValue[7]; end; if UserItem.btValue[10] <> 0 then StdItem.Reserved := StdItem.Reserved or 1; end; 10, 11: begin StdItem.AC := MakeLong(LoWord(StdItem.AC), HiWord(StdItem.AC) + UserItem.btValue[0]); StdItem.MAC := MakeLong(LoWord(StdItem.MAC), HiWord(StdItem.MAC) + UserItem.btValue[1]); StdItem.DC := MakeLong(LoWord(StdItem.DC), HiWord(StdItem.DC) + UserItem.btValue[2]); StdItem.MC := MakeLong(LoWord(StdItem.MC), HiWord(StdItem.MC) + UserItem.btValue[3]); StdItem.SC := MakeLong(LoWord(StdItem.SC), HiWord(StdItem.SC) + UserItem.btValue[4]); end; 15, 16, 19, 20, 21, 22, 23, 24, 26, 51, 52, 53, 54, 62, 63, 64, 30: begin//加入勋章分类 20080616 StdItem.AC := MakeLong(LoWord(StdItem.AC), HiWord(StdItem.AC) + UserItem.btValue[0]); StdItem.MAC := MakeLong(LoWord(StdItem.MAC), HiWord(StdItem.MAC) + UserItem.btValue[1]); StdItem.DC := MakeLong(LoWord(StdItem.DC), HiWord(StdItem.DC) + UserItem.btValue[2]); StdItem.MC := MakeLong(LoWord(StdItem.MC), HiWord(StdItem.MC) + UserItem.btValue[3]); StdItem.SC := MakeLong(LoWord(StdItem.SC), HiWord(StdItem.SC) + UserItem.btValue[4]); if UserItem.btValue[5] > 0 then begin StdItem.Need := UserItem.btValue[5]; end; if UserItem.btValue[6] > 0 then begin StdItem.NeedLevel := UserItem.btValue[6]; end; end; end; if (UserItem.btValue[20] > 0) or (StdItem.Source > 0) then begin //吸伤属性 20080324 Case StdItem.StdMode of 15,16,19..24,26,30,52,54,62,64:begin//头盔,项链,戒指,手镯,鞋子,腰带,勋章 if StdItem.Shape = 188{140} then begin StdItem.Source:= StdItem.Source + UserItem.btValue[20]; if StdItem.Source > 100 then StdItem.Source:= 100; StdItem.Reserved:=StdItem.Reserved + UserItem.btValue[9]; if StdItem.Reserved > 5 then StdItem.Reserved:= 5;//吸伤装备等级 20080816 end; end; end; end; end; //取自定义物品名称 function TItemUnit.GetCustomItemName(nMakeIndex, nItemIndex: Integer): string; var I: Integer; ItemName: pTItemName; begin Result := ''; m_ItemNameList.Lock; try for I := 0 to m_ItemNameList.Count - 1 do begin ItemName := m_ItemNameList.Items[I]; if (ItemName.nMakeIndex = nMakeIndex) and (ItemName.nItemIndex = nItemIndex) then begin Result := ItemName.sItemName; Break; end; end; finally m_ItemNameList.UnLock; end; end; function TItemUnit.AddCustomItemName(nMakeIndex, nItemIndex: Integer; sItemName: string): Boolean; var I: Integer; ItemName: pTItemName; begin Result := False; m_ItemNameList.Lock; try for I := 0 to m_ItemNameList.Count - 1 do begin ItemName := m_ItemNameList.Items[I]; if (ItemName.nMakeIndex = nMakeIndex) and (ItemName.nItemIndex = nItemIndex) then begin Exit; end; end; New(ItemName); ItemName.nMakeIndex := nMakeIndex; ItemName.nItemIndex := nItemIndex; ItemName.sItemName := sItemName; m_ItemNameList.Add(ItemName); Result := True; finally m_ItemNameList.UnLock; end; end; function TItemUnit.DelCustomItemName(nMakeIndex, nItemIndex: Integer): Boolean; var I: Integer; ItemName: pTItemName; begin Result := False; m_ItemNameList.Lock; try for I := m_ItemNameList.Count - 1 downto 0 do begin//20080917 if m_ItemNameList.Count <= 0 then Break;//20080917 ItemName := m_ItemNameList.Items[I]; if (ItemName.nMakeIndex = nMakeIndex) and (ItemName.nItemIndex = nItemIndex) then begin Dispose(ItemName); m_ItemNameList.Delete(I); Result := True; Exit; end; end; finally m_ItemNameList.UnLock; end; end; function TItemUnit.LoadCustomItemName: Boolean; var I: Integer; LoadList: TStringList; sFileName: string; sLineText: string; sMakeIndex: string; sItemIndex: string; nMakeIndex: Integer; nItemIndex: Integer; sItemName: string; ItemName: pTItemName; begin Result := False; sFileName := g_Config.sEnvirDir + 'ItemNameList.txt'; LoadList := TStringList.Create; if FileExists(sFileName) then begin m_ItemNameList.Lock; try if m_ItemNameList.Count > 0 then m_ItemNameList.Clear;//20080831 修改 LoadList.LoadFromFile(sFileName); for I := 0 to LoadList.Count - 1 do begin sLineText := Trim(LoadList.Strings[I]); sLineText := GetValidStr3(sLineText, sMakeIndex, [' ', #9]); sLineText := GetValidStr3(sLineText, sItemIndex, [' ', #9]); sLineText := GetValidStr3(sLineText, sItemName, [' ', #9]); nMakeIndex := Str_ToInt(sMakeIndex, -1); nItemIndex := Str_ToInt(sItemIndex, -1); if (nMakeIndex >= 0) and (nItemIndex >= 0) then begin New(ItemName); ItemName.nMakeIndex := nMakeIndex; ItemName.nItemIndex := nItemIndex; ItemName.sItemName := sItemName; m_ItemNameList.Add(ItemName); end; end;//for Result := True; finally m_ItemNameList.UnLock; end; end else begin LoadList.SaveToFile(sFileName); end; LoadList.Free; end; function TItemUnit.SaveCustomItemName: Boolean; var I: Integer; SaveList: TStringList; sFileName: string; ItemName: pTItemName; begin sFileName := g_Config.sEnvirDir + 'ItemNameList.txt'; SaveList := TStringList.Create; m_ItemNameList.Lock; try if m_ItemNameList.Count > 0 then begin//20080630 for I := 0 to m_ItemNameList.Count - 1 do begin ItemName := m_ItemNameList.Items[I]; SaveList.Add(IntToStr(ItemName.nMakeIndex) + #9 + IntToStr(ItemName.nItemIndex) + #9 + ItemName.sItemName); end; end; finally m_ItemNameList.UnLock; end; SaveList.SaveToFile(sFileName); SaveList.Free; Result := True; end; procedure TItemUnit.Lock; begin m_ItemNameList.Lock; end; procedure TItemUnit.UnLock; begin m_ItemNameList.UnLock; end; end.
unit GADataTypes; interface type TBaseElement = record Coeficient: single; Bitmap: cardinal; end; implementation end.
unit UTemplateFcxVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UCondominioVO; type [TEntity] [TTable('TemplateFcx')] TTemplateFcxVO = class(TGenericVO) private FidFcx : Integer; FidTemplate : Integer; Fclassificacao : String; FclassificacaoContabil : String; FflTipo : String; Flinha : String; FlinhaTotal : string; FidCondominio : Integer; Fdescricao : String; public CondominioVO : TCondominioVO; [TId('idFcx')] [TGeneratedValue(sAuto)] property idFcx : Integer read FidFcx write FidFcx; [TColumn('idTemplate','Template',0,[ldGrid,ldLookup,ldComboBox], False)] property idTemplate: Integer read FidTemplate write FidTemplate; [TColumn('classificacao','Classificação',150,[ldGrid,ldLookup,ldComboBox], False)] property Classificacao: string read FClassificacao write FClassificacao; [TColumn('classificacaocontabil','Classificação Contábil',150,[ldGrid,ldLookup,ldComboBox], False)] property ClassificacaoContabil: string read FClassificacaoContabil write FClassificacaoContabil; [TColumn('descricao','Descrição',450,[ldGrid,ldLookup,ldComboBox], False)] property descricao: string read Fdescricao write Fdescricao; [TColumn('flTipo','Tipo',10,[ldLookup,ldComboBox], False)] property flTipo: string read FflTipo write FflTipo; [TColumn('idCondominio','Condomínio',0,[ldLookup,ldComboBox], False)] property idcondominio: integer read Fidcondominio write Fidcondominio; [TColumn('linha','Linha',10,[ldLookup,ldComboBox], False)] property linha: string read Flinha write Flinha; [TColumn('linhatotal','Linhas Totalizadoras',10,[ldLookup,ldComboBox], False)] property linhatotal: string read Flinhatotal write Flinhatotal; procedure ValidarCamposObrigatorios; end; implementation procedure TTemplateFcxVO.ValidarCamposObrigatorios; begin if (self.FidTemplate = 0) then begin raise Exception.Create('O campo Descrição é obrigatório!'); end; if (Self.Fclassificacao = '') then begin raise Exception.Create('O campo Classificação é obrigatório!'); end; if (self.Fdescricao = '') then begin raise Exception.Create('O campo Descrição é obrigatório!'); end; if (self.FflTipo = '') then begin raise Exception.Create('O campo Tipo é obrigatório!'); end; end; end.
unit Circle; interface uses System.SysUtils, Winapi.Windows, Vcl.Graphics, System.Generics.Collections, System.SyncObjs, JsonDataObjects; type TCircle = class private class var FCircles: TDictionary<string, TCircle>; FCirclesMutex: TMutex; private FPosition: array [0..1] of single; FColor: string; FId: string; function Serialize: TJsonObject; procedure ChangeColor; destructor Destroy; override; public class function SerializeAllCircles: TJsonArray; class procedure Move(const Id: string; x, y: single); class procedure ChangeColorForCircle(const Id: string); class procedure DestroyCircle(const Id: string); constructor Create(x, y: single; const Color: string); class constructor Create; class destructor Destroy; end; implementation { TCircle } class constructor TCircle.Create; begin FCircles := TDictionary<string, TCircle>.Create; FCirclesMutex := TMutex.Create; end; class destructor TCircle.Destroy; var c: TCircle; begin FCirclesMutex.DisposeOf; for c in FCircles.Values.ToArray do c.DisposeOf; FCircles.DisposeOf; end; constructor TCircle.Create(x, y: single; const Color: string); var Guid: TGUID; begin FPosition[0] := x; FPosition[1] := y; FColor := Color; // Generate random id as guid CreateGUID(Guid); FId := GUIDToString(Guid).Replace('{', '').Replace('}', ''); FCirclesMutex.Acquire; FCircles.Add(FId, Self); FCirclesMutex.Release; end; destructor TCircle.Destroy; begin FCirclesMutex.Acquire; FCircles.Remove(FId); FCirclesMutex.Release; inherited; end; function TCircle.Serialize: TJsonObject; begin Result := TJsonObject.Create; Result.S['id'] := FId; Result.S['color'] := FColor; Result.F['x'] := FPosition[0]; Result.F['y'] := FPosition[1]; end; class function TCircle.SerializeAllCircles: TJsonArray; var CirclesArr: TArray<TCircle>; i: integer; begin Result := TJsonArray.Create; FCirclesMutex.Acquire; CirclesArr := FCircles.Values.ToArray; for i := 0 to Length(CirclesArr) - 1 do Result.Add(CirclesArr[i].Serialize); FCirclesMutex.Release; end; class procedure TCircle.Move(const Id: string; x, y: single); var c: TCircle; begin FCirclesMutex.Acquire; if FCircles.ContainsKey(Id) then begin c := FCircles[Id]; c.FPosition[0] := x; c.FPosition[1] := y; end; FCirclesMutex.Release; end; procedure TCircle.ChangeColor; function ColorToHex(Color: TColor) : string; begin Result := { red value } IntToHex( GetRValue( Color ), 2 ) + { green value } IntToHex( GetGValue( Color ), 2 ) + { blue value } IntToHex( GetBValue( Color ), 2 ); end; function GetRandomColor: TColor; begin Result := RGB(Random(100) + 100, Random(100) + 100, Random(100) + 100); end; begin FColor := '#' + ColorToHex(GetRandomColor); end; class procedure TCircle.ChangeColorForCircle(const Id: string); begin FCirclesMutex.Acquire; if FCircles.ContainsKey(Id) then FCircles[Id].ChangeColor; FCirclesMutex.Release; end; class procedure TCircle.DestroyCircle(const Id: string); begin FCirclesMutex.Acquire; if FCircles.ContainsKey(Id) then FCircles[Id].Destroy; FCirclesMutex.Release; end; end.
unit UDExportRecords; interface uses SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, UCrpe32; type TCrpeExportRecordsDlg = class(TForm) btnOk: TButton; btnCancel: TButton; pnlRecords: TPanel; cbUseRptNumberFmt: TCheckBox; cbUseRptDateFmt: TCheckBox; rgRecordsType: TRadioGroup; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpeExportRecordsDlg: TCrpeExportRecordsDlg; implementation {$R *.dfm} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpeExportRecordsDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpeExportRecordsDlg.FormShow(Sender: TObject); begin rgRecordsType.ItemIndex := Ord(Cr.ExportOptions.Text.RecordsType); cbUseRptNumberFmt.Checked := Cr.ExportOptions.Text.UseRptNumberFmt; cbUseRptDateFmt.Checked := Cr.ExportOptions.Text.UseRptDateFmt; end; {------------------------------------------------------------------------------} { btnOKClick procedure } {------------------------------------------------------------------------------} procedure TCrpeExportRecordsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Cr.ExportOptions.Text.RecordsType := TCrRecordsType(rgRecordsType.ItemIndex); Cr.ExportOptions.Text.UseRptNumberFmt := cbUseRptNumberFmt.Checked; Cr.ExportOptions.Text.UseRptDateFmt := cbUseRptDateFmt.Checked; end; {------------------------------------------------------------------------------} { btnCancelClick procedure } {------------------------------------------------------------------------------} procedure TCrpeExportRecordsDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose procedure } {------------------------------------------------------------------------------} procedure TCrpeExportRecordsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
unit PricesInterface; interface uses Ibase, PricesMain, Forms, Windows, Classes, UParamsReestr, Controls, cn_Common_Types, Dialogs; procedure GetPrices (AOwner:TComponent; DbHandle:TISC_DB_HANDLE; Id_user:Int64);stdcall; procedure ShowPrices (AParameter:TcnSimpleParams);stdcall; procedure GetPrice (AOwner:TComponent; DbHandle:TISC_DB_HANDLE; Id_price:Int64; Id_User:Int64);stdcall; function GetPricesByPeriod(AOwner:TComponent; DbHandle:TISC_DB_HANDLE; DateBeg,DateEnd:TDateTime;Id_user:Int64):Variant;stdcall; exports GetPrices, GetPrice, GetPricesByPeriod, ShowPrices; implementation function GetPricesByPeriod(AOwner:TComponent;DbHandle:TISC_DB_HANDLE;DateBeg,DateEnd:TDateTime;Id_user:Int64):Variant; var Res:Variant; begin with TfrmPriceReestr.Create(AOwner,DbHandle,DateBeg,DateEnd,Id_User) do begin if ShowModal=mrYes then begin Res:=Result; end; Free; end; Result:=Res; end; procedure GetPrice(AOwner:TComponent; DbHandle:TISC_DB_HANDLE;Id_price:Int64;Id_User:Int64); var T:TfrmPriceReestr; begin {f :=true; for i:=0 to Application.MainForm.MDIChildCount-1 do begin if (Application.MainForm.MDIChildren[i] is TfrmPriceReestr) then begin if TfrmPriceReestr(Application.MainForm.MDIChildren[i]).new_Id_price=Id_price then begin Application.MainForm.MDIChildren[i].BringToFront; f:=false; end; end; end; if f then TfrmPriceReestr.Create(AOwner,DbHandle,Id_price,Id_User); } T:=TfrmPriceReestr.Create(AOwner,DbHandle,Id_price,Id_User); T.ShowModal; T.Free; end; procedure ShowPrices(AParameter:TcnSimpleParams); var f:Boolean; i:Integer; begin f :=true; for i:=0 to Application.MainForm.MDIChildCount-1 do begin if (Application.MainForm.MDIChildren[i] is TfrmPricesMain) then begin Application.MainForm.MDIChildren[i].BringToFront; f:=false; end; end; if f then TfrmPricesMain.create(AParameter.Owner,AParameter.Db_Handle,AParameter.id_user); end; procedure GetPrices(AOwner:TComponent; DbHandle:TISC_DB_HANDLE; Id_user:Int64); var f:Boolean; i:Integer; begin f :=true; for i:=0 to Application.MainForm.MDIChildCount-1 do begin if (Application.MainForm.MDIChildren[i] is TfrmPricesMain) then begin Application.MainForm.MDIChildren[i].BringToFront; f:=false; end; end; if f then TfrmPricesMain.create(Aowner,DbHandle,id_user); end; end.
// // Created by the DataSnap proxy generator. // 19/05/2018 14:36:56 // unit uCC; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TDMServerClient = class(TDSAdminClient) private FmediaSalarioCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function mediaSalario: Currency; end; implementation function TDMServerClient.mediaSalario: Currency; begin if FmediaSalarioCommand = nil then begin FmediaSalarioCommand := FDBXConnection.CreateCommand; FmediaSalarioCommand.CommandType := TDBXCommandTypes.DSServerMethod; FmediaSalarioCommand.Text := 'TDMServer.mediaSalario'; FmediaSalarioCommand.Prepare; end; FmediaSalarioCommand.ExecuteUpdate; Result := FmediaSalarioCommand.Parameters[0].Value.AsCurrency; end; constructor TDMServerClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TDMServerClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TDMServerClient.Destroy; begin FmediaSalarioCommand.DisposeOf; inherited; end; end.
unit Ils.Kafka; interface uses ULibKafka, Classes, Windows, SysUtils, DateUtils, StrUtils, System.Generics.Collections, SyncObjs, IniFiles, Ils.Kafka.Conf; const KC_ERROR_KAFKA = -100; KC_ERROR_BROKER = -101; KC_ERROR_PARTITION = -102; KC_ERROR_BOOTSTRAP_SERVERS = -103; KC_ERROR_GROUP_ID = -104; KC_ERROR_AUTO_COMMIT = -105; KP_ERROR_KAFKA = -200; KP_ERROR_TOPIC = -201; type TLogFunc = function(const AMessage: string; const ASkipTimeStamp: Boolean = False): string; TOnTimerFunc = procedure of object; TOnMessageFunc = function(const AMessage: AnsiString; const AOffset: Int64; const ATopic: AnsiString): Boolean of object; TKafkaConnection = class private FTopic: AnsiString; FGroup: AnsiString; FBootstrap: AnsiString; FOnLog: TLogFunc; function Log(AMessage: string): string; function Connect: Integer; virtual; abstract; function Disconnect: Integer; virtual; abstract; function CheckConnect: Integer; virtual; abstract; public property OnLog: TLogFunc read FOnLog write FOnLog; constructor Create(const ABootstrap, AGroup, ATopic: string); end; TKafka = class(TKafkaConnection) private FLastPollTimeStamp: TDateTime; FLastError: Integer; FLasterrorString: AnsiString; FConnected: Boolean; FKafka: prd_kafka_t; FErrorBuffer: array [1..1024] of AnsiChar; // FTermination: array[1..16] of AnsiChar; FKafkaConf: prd_kafka_conf_t; procedure KafkaCloseSequence; virtual; abstract; procedure WaitTillKafkaDestroyed; function Connect: Integer; override; function Disconnect: Integer; override; function CheckConnect: Integer; override; function CheckPoll(const APollTimeout: Integer; const AForce: Boolean = False; const APollInterval: Integer = 1000): Integer; public constructor Create(const ABootstrap, AGroup, ATopic: string); end; TKafkaMessageState = (msLoaded, msQueued, msBacked); TKafkaMessage = class pl: AnsiString; d: TDateTime; s: TKafkaMessageState; constructor Create(AStr: AnsiString); end; PKafkaMessage = ^TKafkaMessage; TKafkaMessageHash = class(TDictionary<PKafkaMessage,TKafkaMessage>) destructor Destroy; override; end; TKafkaTimerThread = class(TThread) protected procedure Execute; override; private FInterval: Integer; FOnTimer: TOnTimerFunc; public constructor Create(const AOnTimer: TOnTimerFunc; const AInterval: Integer); end; TKafkaProducer = class(TKafka) private FMessageCache: TKafkaMessageHash; FTimer: TKafkaTimerThread; FCS: TCriticalSection; FBackupCount: Integer; FBackupFileName: string; FBackupFile: TFileStream; FKafkaTopicConf: prd_kafka_topic_conf_t; FKafkaTopic: prd_kafka_topic_t; FBackupTimeout: Integer; function Connect: Integer; override; // procedure CacheFlush(const ADelay: Integer); // procedure CacheResend; // function CheckBackupFile: Boolean; // function BackupMessage(AMsg: TKafkaMessage): Boolean; // procedure CloseBackupFile(const ADelete: Boolean); procedure Housekeeping; function SetDelivered(const AMessage: PKafkaMessage): Boolean; procedure KafkaCloseSequence; override; function Produce(const AMessage: TKafkaMessage): Integer; overload; public function Produce(APayload: AnsiString): Integer; overload; constructor Create(const ABootstrap, ATopic: string; const ABackupPath: string = ''; const ABackupTimeout: Integer = 120000; const AOnLog: TLogFunc = nil); reintroduce; overload; constructor Create(const AParams: TKafkaProducerParams; const AOnLog: TLogFunc = nil); reintroduce; overload; destructor Destroy; override; end; TKafkaConsumer = class(TKafka) private FKafkaTopicPartitionList: prd_kafka_topic_partition_list_t; FKafkaTopicPartition: prd_kafka_topic_partition_t; FOnMessage: TOnMessageFunc; FKafkaTimerThread: TKafkaTimerThread; FOffset: Int64; procedure StopSelf; procedure KafkaCloseSequence; override; function Connect: Integer; overload; override; function Disconnect: Integer; override; procedure Consume; overload; function Consume(const rkmessage: prd_kafka_message_t): Boolean; overload; public property NextOffset: Int64 read FOffset; function Start(const AOffset: Int64 = RD_KAFKA_OFFSET_INVALID; const ACreateThread: Boolean = True): Boolean; function Stop: Boolean; function CheckTryRestart(var ACheckedOffset: Int64): Boolean; function GetMessage(out RMessage: AnsiString): Boolean; //out RLastOffset: Int64): Boolean; constructor Create(const AKafkaParams: TKafkaConsumerParams; const AOnMessage: TOnMessageFunc; const AOnLog: TLogFunc); overload; constructor Create(const ABootstrap, AGroup, ATopic: string; const AOnMessage: TOnMessageFunc; const AOnLog: TLogFunc); reintroduce; overload; // constructor Create(const AKafkaParams: TKafkaConsumerParams; const AOnMessage: TOnMessageFunc; const AOnLog: TLogFunc); overload; destructor Destroy; override; end; implementation //function NextError(var aErrorCode: Integer): Integer; //begin // Dec(aErrorCode); // Result := aErrorCode; //end; procedure error_cb(rk: prd_kafka_t; err: integer; reason: PAnsiChar; opaque: Pointer); cdecl; begin with TKafka(opaque) do begin FLastError := err; FLasterrorString := reason; FConnected := False; Log('error - ' + reason); end; end; procedure dr_cb(rk: prd_kafka_t; payload: Pointer; len: size_t; err: rd_kafka_resp_err_t; opaque, msg_opaque: Pointer); cdecl; begin if err in [RD_KAFKA_RESP_ERR_NO_ERROR] then TKafkaProducer(opaque).SetDelivered(msg_opaque); end; procedure dr_msg_cb(rk: prd_kafka_t; rkmessage: prd_kafka_message_t; opaque: Pointer); cdecl; begin end; procedure consume_cb(rkmessage: prd_kafka_message_t; opaque: Pointer); cdecl; begin TKafkaConsumer(opaque).Consume(rkmessage); end; procedure rebalance_cb(rk: prd_kafka_t; err: rd_kafka_resp_err_t; partitions: prd_kafka_topic_partition_list_t; opaque: Pointer); cdecl; begin //void my_rebalance_cb (rd_kafka_t *rk, rd_kafka_resp_err_t err, // rd_kafka_topic_partition_list_t *partitions, void *opaque) { // if (err == RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS) { // rd_kafka_topic_partition_t *part; // if ((part = rd_kafka_topic_partition_list_find(partitions, "mytopic", 3))) // part->offset = 1234; // rd_kafka_assign(rk, partitions); // } else { // rd_kafka_assign(rk, NULL); // } //} end; procedure offset_commit_cb(rk: prd_kafka_t; err: rd_kafka_resp_err_t; offsets: prd_kafka_topic_partition_list_t; opaque: Pointer); cdecl; begin end; { TKafkaConnection } constructor TKafkaConnection.Create(const ABootstrap, AGroup, ATopic: string); begin FBootstrap := AnsiString(ABootstrap); FTopic := AnsiString(ATopic); FGroup := AnsiString(AGroup); if (FBootstrap = '') or (FTopic = '') {or (FGroup = '')} then raise Exception.Create('необходимо указать все параметры подсоединения к Kafka!'); end; function TKafkaConnection.Log(AMessage: string): string; begin if Assigned(FOnLog) then FOnLog('Kafka - ' + string(FBootstrap) + ';' + string(FTopic) + ';' + string(FGroup) + ': ' + AMessage); end; { TKafka } function TKafka.CheckPoll(const APollTimeout: Integer; const AForce: Boolean; const APollInterval: Integer): Integer; begin Result := 0; if (AForce or ((Now - FLastPollTimeStamp) > (APollInterval * OneMillisecond))) and Assigned(FKafka) then begin Result := rd_kafka_poll(FKafka, APollTimeout);//block for max APollTimeout in ms FLastPollTimeStamp := Now; end; end; function TKafka.Connect: Integer; begin Result := 0; FKafkaConf := rd_kafka_conf_new(); rd_kafka_conf_set_opaque(FKafkaConf, Self); // rd_kafka_conf_set(FKafkaConf, 'internal.termination.signal', @(FTermination[1]), @(FErrorBuffer[1]), SizeOf(FErrorBuffer)); rd_kafka_conf_set_dr_cb(FKafkaConf, dr_cb); // rd_kafka_conf_set_dr_msg_cb(FKafkaConf, dr_msg_cb); // rd_kafka_conf_set_consume_cb(FKafkaConf, consume_cb); //эта штука потребляет сообщение через callback, тогда Kafka через poll не отдаёт // rd_kafka_conf_set_rebalance_cb(FKafkaConf, rebalance_cb); // rd_kafka_conf_set_offset_commit_cb(FKafkaConf, offset_commit_cb); rd_kafka_conf_set_error_cb(FKafkaConf, error_cb); // Set bootstrap broker(s) as a comma-separated list of // host or host:port (default port 9092). // librdkafka will use the bootstrap brokers to acquire the full // set of brokers from the cluster. if rd_kafka_conf_set( FKafkaConf, 'bootstrap.servers', PAnsiChar(FBootstrap), @(FErrorBuffer[1]), sizeof(FErrorBuffer)) <> RD_KAFKA_CONF_OK then begin Log(string(FErrorBuffer)); Exit(KC_ERROR_BOOTSTRAP_SERVERS); end; if rd_kafka_conf_set( FKafkaConf, 'group.id', PAnsiChar(FGroup), @(FErrorBuffer[1]), sizeof(FErrorBuffer)) <> RD_KAFKA_CONF_OK then begin Log(string(FErrorBuffer)); Exit(KC_ERROR_GROUP_ID); end; if rd_kafka_conf_set( FKafkaConf, 'enable.auto.commit', PAnsiChar('false'), @(FErrorBuffer[1]), sizeof(FErrorBuffer)) <> RD_KAFKA_CONF_OK then begin Log(string(FErrorBuffer)); Exit(KC_ERROR_AUTO_COMMIT); end; end; constructor TKafka.Create(const ABootstrap, AGroup, ATopic: string); begin inherited Create(ABootstrap, AGroup, ATopic); FLastPollTimeStamp := 0; end; function TKafka.CheckConnect: Integer; begin if FConnected then Exit(0); FLastError := 0; FLasterrorString := ''; CheckPoll(5000, True); Result := FLastError; if Result = 0 then begin Log('Connected'); FConnected := True; end; end; function TKafka.Disconnect: Integer; begin Result := 0; if not Assigned(FKafka) then Exit; KafkaCloseSequence; end; procedure TKafka.WaitTillKafkaDestroyed; var run: Integer; r: Integer; begin run := 5; repeat r := rd_kafka_wait_destroyed(100); if r = -1 then Log('Waiting for librdkafka to decommission'); Dec(run) until (run <= 0) or (r = 0); if (run <= 0) then Log('Kill unsuccess'); end; { TKafkaProducer } constructor TKafkaProducer.Create(const ABootstrap, ATopic: string; const ABackupPath: string; const ABackupTimeout: Integer; const AOnLog: TLogFunc); begin inherited Create(ABootstrap, '', ATopic); FOnLog := AOnLog; FBackupCount := 0; FBackupTimeout := ABackupTimeout; FBackupFileName := IfThen( ABackupPath <> '', IncludeTrailingPathDelimiter(ABackupPath), ExtractFilePath(GetModuleName(HInstance)) + 'backup\' ) + ATopic + '.bak'; FCS := TCriticalSection.Create; FMessageCache := TKafkaMessageHash.Create; Connect; FTimer := TKafkaTimerThread.Create(Housekeeping, 1000); end; constructor TKafkaProducer.Create(const AParams: TKafkaProducerParams; const AOnLog: TLogFunc = nil); begin with AParams do Self.Create(BootStrap, Topic, BackupPath, BackupTimeout, AOnLog); end; destructor TKafkaProducer.Destroy; begin FTimer.Terminate; // CacheFlush(0); FMessageCache.Free; FCS.Free; FBackupFile.Free; inherited; end; function TKafkaProducer.Connect: Integer; begin Result := inherited Connect; FKafka := rd_kafka_new(RD_KAFKA_PRODUCER, FKafkaConf, @(FErrorBuffer[1]), sizeof(FErrorBuffer)); if not Assigned(FKafka) then begin Log(string(FErrorBuffer)); Exit(KP_ERROR_KAFKA); end; // rd_kafka_conf_set_default_topic_conf(FKafkaConf, FKafkaTopicConf); FKafkaTopicConf := rd_kafka_topic_conf_new; FKafkaTopic := rd_kafka_topic_new(FKafka, PAnsiChar(FTopic), FKafkaTopicConf); if not Assigned(FKafkaTopic) then begin //'Failed to create topic object: ' Log(string(rd_kafka_err2str(rd_kafka_last_error()))); rd_kafka_destroy(FKafka); Exit(KP_ERROR_TOPIC); end; end; //function TKafkaProducer.CheckBackupFile: Boolean; //var // FileMode: Integer; //begin // if Assigned(FBackupFile) then // Exit(True) // else // begin // if FileExists(FBackupFileName) then // FileMode := fmOpenReadWrite + fmShareDenyWrite // else // FileMode := fmOpenReadWrite + fmShareDenyWrite + fmCreate; // // ForceDirectories(ExtractFilePath(FBackupFileName)); // try // FBackupFile := TFileStream.Create(FBackupFileName, FileMode); // except // end; // // Result := Assigned(FBackupFile); // end; //end; //function TKafkaProducer.BackupMessage(AMsg: TKafkaMessage): Boolean; //var // PLLen: UInt32; //begin // Result := False; // PLLen := Length(AMsg.pl); // // if PLLen = 0 then // Exit(True); // // if not CheckBackupFile then // Exit; // // FBackupFile.Write(PLLen, SizeOf(PLLen)); // FBackupFile.Write(AMsg.pl[1], PLLen); // AMsg.s := msBacked; // Result := True; // Inc(FBackupCount); //end; //procedure TKafkaProducer.CloseBackupFile(const ADelete: Boolean); //begin // FBackupFile.Free; // FBackupFile := nil; // if ADelete then // DeleteFile(FBackupFileName); //end; //procedure TKafkaProducer.CacheFlush(const ADelay: Integer); //var // k: PKafkaMessage; //begin // try // for k in FMessageCache.Keys do // if (FMessageCache.Items[k].s in [msQueued]) and // (FMessageCache.Items[k].d < (Now - ADelay * OneMillisecond)) then // if BackupMessage(FMessageCache.Items[k]) then // FMessageCache.ExtractPair(k).Value.Free; // finally // CloseBackupFile(False) // end; //end; //procedure TKafkaProducer.CacheResend; //var // PLLen: UInt32; // pl: AnsiString; //begin // try // if not CheckBackupFile then // Exit; // // while FBackupFile.Position < FBackupFile.Size do // begin // try // FBackupFile.Read(PLLen, SizeOf(PLLen)); // if PLLen > 0 then // begin // SetLength(pl, PLLen); // FBackupFile.Read(pl[1], PLLen); // Produce(pl); // end; // except // end; // end; // finally // CloseBackupFile(True); // end; // Inc(FBackupCount); //end; procedure TKafkaProducer.Housekeeping; begin CheckPoll(100); // if FCS.TryEnter then // try // CacheFlush(FBackupTimeout); // // if FConnected then // CacheResend; // // finally // FCS.Leave; // end; end; procedure TKafkaProducer.KafkaCloseSequence; begin while (rd_kafka_outq_len(FKafka) > 0) do rd_kafka_poll(FKafka, 50); rd_kafka_topic_destroy(FKafkaTopic); //Destroy handle rd_kafka_destroy(FKafka); FKafka := nil; WaitTillKafkaDestroyed; end; //procedure TKafkaProducer.Flush; //begin // while( rd_kafka_outq_len( FKafka ) > 0 ) do // rd_kafka_poll( FKafka, 1 ); // // rd_kafka_flush(FKafka, 10 ); //wait for max 10 seconds //end; function TKafkaProducer.Produce(APayload: AnsiString): Integer; var msg: TKafkaMessage; begin msg := TKafkaMessage.Create(APayload); FMessageCache.Add(PKafkaMessage(msg), msg); Result := Produce(msg); end; function TKafkaProducer.Produce(const AMessage: TKafkaMessage): Integer; const CTryCountDef = 10; var TryCount: Integer; begin TryCount := CTryCountDef; if CheckConnect <> 0 then Exit(FLastError); repeat Result := rd_kafka_produce( FKafkaTopic, //Topic object integer(RD_KAFKA_PARTITION_UA), //Use builtin partitioner to select partition RD_KAFKA_MSG_F_COPY, //Make a copy of the payload. Pointer(AMessage.pl), //Message payload (value) Length(AMessage.pl), //Message payload (length) nil, 0, //Optional key and its length AMessage //Message opaque, provided in delivery report callback as msg_opaque. ); AMessage.s := msQueued; case Result of 0: begin if FMessageCache.Count > 100000 then // rd_kafka_poll(FKafka, 1000);//block for max 1000ms Result := CheckPoll(1000, True);//block for max 1000ms end; -1: begin //Failed to *enqueue* message for producing. Log('Failed to produce to topic: ' + string(FTopic) + string(rd_kafka_err2str(rd_kafka_last_error()))); //Poll to handle delivery reports if rd_kafka_last_error() <> RD_KAFKA_RESP_ERR__QUEUE_FULL then Break else begin //If the internal queue is full, wait for //messages to be delivered and then retry. //The internal queue represents both //messages to be sent and messages that have //been sent or failed, awaiting their //delivery report callback to be called. // //The internal queue is limited by the //configuration property //queue.buffering.max.messages // rd_kafka_poll(FKafka, 1000);//block for max 1000ms CheckPoll(1000, True);//block for max 1000ms end; end; end; Dec(TryCount); until (Result >= 0) or (TryCount <= 0); end; function TKafkaProducer.SetDelivered(const AMessage: PKafkaMessage): Boolean; begin Result := True; if FCS.TryEnter then try if FMessageCache.ContainsKey(AMessage) then FMessageCache.ExtractPair(AMessage).Value.Free; finally FCS.Leave; end; end; { TKafkaConsumer } //constructor TKafkaConsumer.Create(const AKafkaParams: TKafkaConsumerParams; const AOnMessage: TOnMessageFunc; const AOnLog: TLogFunc); //begin // Create(AKafkaParams.Bootstrap, AKafkaParams.Group, AKafkaParams.Topic, AOnMessage, AOnLog); //end; constructor TKafkaConsumer.Create(const ABootstrap, AGroup, ATopic: string; const AOnMessage: TOnMessageFunc; const AOnLog: TLogFunc); begin FOnMessage := AOnMessage; FOnLog := AOnLog; FOffset := RD_KAFKA_OFFSET_INVALID; // FNextOffset := RD_KAFKA_OFFSET_INVALID; FKafkaTimerThread := nil; inherited Create(ABootstrap, AGroup, ATopic); end; destructor TKafkaConsumer.Destroy; begin Stop; if Assigned(FKafka) then Disconnect; inherited; end; function TKafkaConsumer.Connect: Integer; var err: rd_kafka_resp_err_t; begin if Assigned (FKafka) then Exit(-1000); Result := inherited Connect; if Result <> 0 then Exit; FKafka := rd_kafka_new(RD_KAFKA_CONSUMER, FKafkaConf, @(FErrorBuffer[1]), sizeof(FErrorBuffer)); if not Assigned(FKafka) then begin Log('Failed to create new consumer: ' + FErrorBuffer); Exit(KC_ERROR_KAFKA); end; //Add brokers if (rd_kafka_brokers_add(FKafka, PAnsiChar(FBootstrap)) = 0) then begin rd_kafka_destroy(FKafka); Log('No valid brokers specified'); Exit(KC_ERROR_BROKER); end; { FTopicConf := rd_kafka_topic_conf_new(); FKafkaTopic := rd_kafka_topic_new(FKafka, PansiChar(FTopic), FTopicConf); rd_kafka_consume_start(FKafkaTopic, 0, -2); } //Redirect rd_kafka_poll() to consumer_poll() rd_kafka_poll_set_consumer(FKafka); FKafkaTopicPartitionList := rd_kafka_topic_partition_list_new(1); FKafkaTopicPartition := rd_kafka_topic_partition_list_add(FKafkaTopicPartitionList, PAnsiChar(FTopic), 0); FKafkaTopicPartition.offset := FOffset; // } // //================================================================================== // if (mode == 'O') { // /* Offset query */ // // err = rd_kafka_committed(rk, topics, 5000); // if (err) { // fprintf(stderr, "%% Failed to fetch offsets: %s\n", // rd_kafka_err2str(err)); // exit(1); // } // // for (i = 0 ; i < topics->cnt ; i++) { // rd_kafka_topic_partition_t *p = &topics->elems[i]; // printf("Topic \"%s\" partition %"PRId32, // p->topic, p->partition); // if (p->err) // printf(" error %s", // rd_kafka_err2str(p->err)); // else { // printf(" offset %"PRId64"", // p->offset); // // if (p->metadata_size) // printf(" (%d bytes of metadata)", // (int)p->metadata_size); // } // printf("\n"); // } // // goto done; // } //================================================================================== // // if (is_subscription) { // fprintf(stderr, "%% Subscribing to %d topics\n", topics->cnt); // // if ((err = rd_kafka_subscribe(rk, topics))) { // fprintf(stderr, // "%% Failed to start fconsuming topics: %s\n", // rd_kafka_err2str(err)); // exit(1); // } // } else { // fprintf(stderr, "%% Assigning %d partitions\n", topics->cnt); err := rd_kafka_assign(FKafka, FKafkaTopicPartitionList); if err <> RD_KAFKA_RESP_ERR_NO_ERROR then begin rd_kafka_topic_partition_list_del(FKafkaTopicPartitionList, PAnsiChar(FTopic), 0); rd_kafka_topic_partition_list_destroy(FKafkaTopicPartitionList); rd_kafka_destroy(FKafka); FKafka := nil; Log('Failed to assign partitions: ' + rd_kafka_err2name(err)); Exit(KC_ERROR_PARTITION); end; // rd_kafka_commit(FKafka, FKafkaTopicPartitionList, 0); end; function TKafkaConsumer.Disconnect: Integer; var err: rd_kafka_resp_err_t; begin if not Assigned(FKafka) then Exit(0); if FTopic <> '' then begin rd_kafka_topic_partition_list_del(FKafkaTopicPartitionList, PAnsiChar(FTopic), 0); rd_kafka_topic_partition_list_destroy(FKafkaTopicPartitionList); // rd_kafka_topic_partition_destroy(FKafkaTopicPartition); end; err := rd_kafka_consumer_close(FKafka); if (err <> RD_KAFKA_RESP_ERR_NO_ERROR)then Log('Failed to close consumer: ' + rd_kafka_err2str(err)) else Log('Consumer closed'); Result := inherited Disconnect; end; procedure TKafkaConsumer.StopSelf; begin if Assigned(FKafkaTimerThread) then FKafkaTimerThread.Terminate; if Assigned(FKafka) then Disconnect; FKafkaTimerThread := nil; end; procedure TKafkaConsumer.Consume; var rkmessage: prd_kafka_message_t; Success: Boolean; begin rkmessage := rd_kafka_consumer_poll(FKafka, 1000); if Assigned(rkmessage) then begin Success := Consume(rkmessage); rd_kafka_message_destroy(rkmessage); if not Success then StopSelf; end; end; function TKafkaConsumer.Consume(const rkmessage: prd_kafka_message_t): Boolean; var ss: AnsiString; b: Boolean; begin //msg_consume(RKMessage); Result := True; if rkmessage.err <> RD_KAFKA_RESP_ERR_NO_ERROR then begin // if Assigned(FOnError) then // FOnError('massage error: ' + rd_kafka_err2name(rkmessage.err)) end else begin SetLength(ss, rkmessage.len); MoveMemory(Pointer(ss), rkmessage.payload, rkmessage.len); // for i := 1 to rkmessage.len do // ss[i] := AnsiString(PAnsiString(rkmessage.payload))[i]; if Assigned(FOnMessage) then begin TThread.Synchronize(FKafkaTimerThread, procedure begin b := False; try b := FOnMessage(ss, rkmessage.offset, FTopic); except end; end); Result := b; //CB(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now)); // Inc(FConsumed); end; end; end; constructor TKafkaConsumer.Create(const AKafkaParams: TKafkaConsumerParams; const AOnMessage: TOnMessageFunc; const AOnLog: TLogFunc); begin Create(AKafkaParams.BootStrap, AKafkaParams.Group, AKafkaParams.Topic, AOnMessage, AOnLog); end; function TKafkaConsumer.GetMessage(out RMessage: AnsiString): Boolean; //out RLastOffset: Int64): Boolean; var rkmessage: prd_kafka_message_t; ss: AnsiString; begin RMessage := ''; Result := False; rkmessage := rd_kafka_consumer_poll(FKafka, 1000); if Assigned(rkmessage) then begin if (rkmessage.err <> RD_KAFKA_RESP_ERR_NO_ERROR) or ((rkmessage.offset <> FOffset) and (FOffset >= 0)) then begin // if Assigned(FOnError) then // FOnError('massage error: ' + rd_kafka_err2name(rkmessage.err)) end else begin FOffset := rkmessage.offset + 1; SetLength(ss, rkmessage.len); MoveMemory(Pointer(ss), rkmessage.payload, rkmessage.len); RMessage := ss; Result := True; end; rd_kafka_message_destroy(rkmessage); end; end; procedure TKafkaConsumer.KafkaCloseSequence; begin rd_kafka_consumer_close(FKafka); rd_kafka_destroy(FKafka); FKafka := nil; WaitTillKafkaDestroyed; end; function TKafkaConsumer.Start(const AOffset: Int64; const ACreateThread: Boolean): Boolean; begin if Assigned(FKafka) or Assigned(FKafkaTimerThread) then Exit(False); FOffset := AOffset; // FNextOffset := AOffset; if Connect <> 0 then Exit(False); if ACreateThread then FKafkaTimerThread := TKafkaTimerThread.Create(Consume, 0); Result := True; end; function TKafkaConsumer.Stop: Boolean; begin if Assigned(FKafkaTimerThread) then begin FKafkaTimerThread.FreeOnTerminate := False; FKafkaTimerThread.Free; FKafkaTimerThread := nil; end; Disconnect; Result := True; end; function TKafkaConsumer.CheckTryRestart(var ACheckedOffset: Int64): Boolean; begin Result := ACheckedOffset = RD_KAFKA_OFFSET_END; if not Result then begin Log('попытка перезапуска'); try Start(ACheckedOffset); ACheckedOffset := RD_KAFKA_OFFSET_END; Log('перезапуск успешен'); Result := True; except on Ex: Exception do Log('ошибка перезапуска "' + Ex.ClassName + '":' + Ex.Message); end; end; end; { TKafkaTimerThread } constructor TKafkaTimerThread.Create(const AOnTimer: TOnTimerFunc; const AInterval: Integer); begin FreeOnTerminate := True; FInterval := AInterval; FOnTimer := AOnTimer; inherited Create; end; procedure TKafkaTimerThread.Execute; begin while not Terminated do begin if Assigned(FOnTimer) then FOnTimer; Sleep(FInterval); end; end; { TKafkaMessage } constructor TKafkaMessage.Create(AStr: AnsiString); begin pl := AStr; d := Now; s := msLoaded; end; { TKafkaMessageHash } destructor TKafkaMessageHash.Destroy; var k: PKafkaMessage; begin for k in Keys do Items[k].Free; Clear; inherited; end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clEncoder; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$ENDIF} uses SysUtils, Classes; const DefaultCharsPerLine = 76; type EclEncoderError = class(Exception); TclEncoderProgressEvent = procedure (Sender: TObject; ABytesProceed, ATotalBytes: Integer) of object; TclEncodeMethod = (cmNone, cmMIMEQuotedPrintable, cmMIMEBase64, cmUUEncode, cm8Bit); TclEncoder = class(TComponent) private FMethod: TclEncodeMethod; FCharsPerLine: Integer; FFirstPass, FDelimPresent, FStringProcessed, FSuppressCrlf: Boolean; FOnProgress: TclEncoderProgressEvent; function GetCorrectCharsPerLine: Integer; procedure DoProgress(ABytesProceed, ATotalBytes: Integer); function ReadOneLine(AStream: TStream; var Eof: Boolean; var crlfSkipped: Integer): string; function EncodeUUE(ASource, ADestination: TStream): Boolean; function DecodeUUE(ASource, ADestination: TStream): Boolean; function EncodeBASE64(ASource, ADestination: TStream): Boolean; function DecodeBASE64(ASource, ADestination: TStream): Boolean; function EncodeQP(ASource, ADestination: TStream): Boolean; function DecodeQP(ASource, ADestination: TStream): Boolean; public constructor Create(AOwner: TComponent); override; function GetNeedEncoding(ASource: TStream): TclEncodeMethod; overload; function GetNeedEncoding(ASource: string): TclEncodeMethod; overload; procedure EncodeStream(ASource, ADestination: TStream; AMethod: TclEncodeMethod); procedure DecodeStream(ASource, ADestination: TStream; AMethod: TclEncodeMethod); procedure EncodeString(const ASource: string; var ADestination: string; AMethod: TclEncodeMethod); procedure DecodeString(const ASource: string; var ADestination: string; AMethod: TclEncodeMethod); procedure EncodeToString(ASource: TStream; var ADestination: string; AMethod: TclEncodeMethod); procedure DecodeFromString(const ASource: string; ADestination: TStream; AMethod: TclEncodeMethod); published property CharsPerLine: Integer read FCharsPerLine write FCharsPerLine default DefaultCharsPerLine; property SuppressCrlf: Boolean read FSuppressCrlf write FSuppressCrlf default False; property OnProgress: TclEncoderProgressEvent read FOnProgress write FOnProgress; end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsEncoderDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} resourcestring SclErrorUnsupported = 'Unsupported format.'; SclErrorWrongSymbols = 'Wrong symbols in source stream.'; implementation {$IFDEF DEMO} uses Windows, Forms; {$ENDIF} const CR = #13; LF = #10; CRLF = CR + LF; MaxUUECharsPerLine = 132; MaxQPCharsPerLine = 132; MinBASE64CharsPerLine = 76; Base64CodeTable: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64CodeTableEx: array[0..255] of Integer = ($00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$3f,$00,$00,$00,$40 ,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$00,$00,$00,$00,$00,$00,$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,$00,$00,$00,$00,$00 ,$00,$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,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); procedure clEncoderError(const Msg: string); begin raise EclEncoderError.Create(Msg); end; { TclEncoder } constructor TclEncoder.Create(AOwner: TComponent); begin inherited Create(AOwner); FCharsPerLine := DefaultCharsPerLine; FStringProcessed := False; FSuppressCrlf := False; end; function TclEncoder.GetNeedEncoding(ASource: string): TclEncodeMethod; var SourceStream: TStream; begin SourceStream := TMemoryStream.Create; try SourceStream.Write(PChar(ASource)^, Length(ASource)); SourceStream.Position := 0; Result := GetNeedEncoding(SourceStream); finally SourceStream.Free; end; end; function TclEncoder.GetNeedEncoding(ASource: TStream): TclEncodeMethod; var NonTransportable, MaxNonTransportable: Integer; Symbol: Char; CharPerLine: Integer; begin NonTransportable := 0; CharPerLine := 0; MaxNonTransportable := ASource.Size div 2; Result := cmNone; while(ASource.Read(Symbol, 1) = 1) do begin case Ord(Symbol) of 13,10: begin if(CharPerLine > 76) then Result := cmMIMEQuotedPrintable; CharPerLine := 0; end; 0..9,11..12,14..31: begin Result := cmMIMEBase64; CharPerLine := 0; Break; end; 32..126: begin Inc(CharPerLine); end; 127..255: begin Result := cmMIMEQuotedPrintable; Inc(NonTransportable); if (MaxNonTransportable < NonTransportable) then begin Result := cmMIMEBase64; Break; end; end; end; end; if(CharPerLine > 76) and (Result = cmNone) then begin Result := cmMIMEQuotedPrintable; end; end; procedure TclEncoder.EncodeStream(ASource, ADestination: TStream; AMethod: TclEncodeMethod); var EncodeFurther: Boolean; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsEncoderDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (ASource.Size = 0) then Exit; FFirstPass := True; DoProgress(0, ASource.Size); EncodeFurther := False; FMethod := AMethod; repeat case FMethod of cmMIMEQuotedPrintable: EncodeFurther := EncodeQP(ASource, ADestination); cmMIMEBase64: EncodeFurther := EncodeBASE64(ASource, ADestination); cmUUEncode: EncodeFurther := EncodeUUE(ASource, ADestination); cmNone, cm8Bit: ADestination.CopyFrom(ASource, ASource.Size); else clEncoderError(SclErrorUnsupported); end; DoProgress(ASource.Position, ASource.Size); until not EncodeFurther; end; procedure TclEncoder.DecodeStream(ASource, ADestination: TStream; AMethod: TclEncodeMethod); var DecodeFurther: Boolean; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsEncoderDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (ASource.Size = 0) then Exit; DoProgress(0, ASource.Size); FDelimPresent := False; DecodeFurther := False; FMethod := AMethod; repeat case FMethod of cmMIMEQuotedPrintable: DecodeFurther := DecodeQP(ASource, ADestination); cmMIMEBase64: DecodeFurther := DecodeBASE64(ASource, ADestination); cmUUEncode: DecodeFurther := DecodeUUE(ASource, ADestination); cmNone, cm8Bit: ADestination.CopyFrom(ASource, ASource.Size); else clEncoderError(SclErrorUnsupported); end; DoProgress(ASource.Position, ASource.Size); until not DecodeFurther; end; procedure TclEncoder.EncodeString(const ASource: string; var ADestination: string; AMethod: TclEncodeMethod); var SourceStream: TStream; DestinationStream: TStream; begin SourceStream := nil; DestinationStream := nil; try SourceStream := TMemoryStream.Create(); SourceStream.WriteBuffer(PChar(ASource)^, Length(ASource)); DestinationStream := TMemoryStream.Create(); FStringProcessed := True; SourceStream.Position := 0; EncodeStream(SourceStream, DestinationStream, AMethod); SetLength(ADestination, DestinationStream.Size); DestinationStream.Position := 0; DestinationStream.ReadBuffer(PChar(ADestination)^, DestinationStream.Size); finally SourceStream.Free(); DestinationStream.Free(); FStringProcessed := False; end; end; procedure TclEncoder.DecodeString(const ASource: string; var ADestination: string; AMethod: TclEncodeMethod); var SourceStream: TStream; DestinationStream: TStream; begin SourceStream := nil; DestinationStream := nil; try SourceStream := TMemoryStream.Create(); SourceStream.WriteBuffer(PChar(ASource)^, Length(ASource)); DestinationStream := TMemoryStream.Create(); SourceStream.Position := 0; DecodeStream(SourceStream, DestinationStream, AMethod); SetLength(ADestination, DestinationStream.Size); DestinationStream.Position := 0; DestinationStream.ReadBuffer(PChar(ADestination)^, DestinationStream.Size); finally SourceStream.Free(); DestinationStream.Free(); end; end; function TclEncoder.EncodeBASE64(ASource, ADestination: TStream): Boolean; procedure ConvertToBase64(ASymbolsArray: PChar; ACount: Integer); var Symb, i: Integer; begin for i := 0 to ACount - 1 do begin Symb := Integer(ASymbolsArray[i]); case Symb of 64: ASymbolsArray[i] := Char(13); 65: ASymbolsArray[i] := Char(10); 0..63: ASymbolsArray[i] := Base64CodeTable[Symb + 1]; else ASymbolsArray[i] := '='; end; end; end; var Buffer: PChar; OutBuffer: PChar; i, Completed, Length, LineLength, RestLength, InIndex, OutIndex: Integer; begin Result := False; if FSuppressCrlf then begin LineLength := ASource.Size; end else begin LineLength := Trunc(GetCorrectCharsPerLine() * 3/4); end; Completed := ASource.Size; if (Completed = 0) then Exit; Length := (((Completed div 3)*4) div LineLength) * (LineLength + 2); if (Length = 0) then Length := LineLength + 2; Length := (Length + ($2000 - 1)) and not ($2000 - 1); GetMem(Buffer, Completed + 1); GetMem(OutBuffer, Length); try ASource.Read(Buffer^, Completed); Buffer[Completed] := #0; OutIndex := 0; InIndex := 0; repeat if not (FSuppressCrlf or FFirstPass) then begin OutBuffer[OutIndex] := Char(64); OutBuffer[OutIndex + 1] := Char(65); Inc(OutIndex, 2); end; FFirstPass := False; RestLength := Completed - InIndex; if (RestLength > LineLength) then RestLength := LineLength; for i := 0 to (RestLength div 3) - 1 do begin OutBuffer[OutIndex] := Char(Word(Buffer[InIndex]) shr 2); OutBuffer[OutIndex + 1] := Char(((Word(Buffer[InIndex]) shl 4) and 48) or ((Word(Buffer[InIndex + 1]) shr 4) and 15)); OutBuffer[OutIndex + 2] := Char(((Word(Buffer[InIndex + 1]) shl 2) and 60) or ((Word(Buffer[InIndex + 2]) shr 6) and 3)); OutBuffer[OutIndex + 3] := Char(Word(Buffer[InIndex + 2]) and 63); Inc(InIndex, 3); Inc(OutIndex, 4); end; if (RestLength mod 3) > 0 then begin OutBuffer[OutIndex] := Char(Word(Buffer[InIndex]) shr 2); OutBuffer[OutIndex + 1] := Char(((Word(Buffer[InIndex]) shl 4) and 48) or ((Word(Buffer[InIndex + 1]) shr 4) and 15)); if((RestLength mod 3) = 1) then begin OutBuffer[OutIndex + 2] := Char(-1);//'='; OutBuffer[OutIndex + 3] := Char(-1);//'='; end else begin OutBuffer[OutIndex + 2] := Char(((Word(Buffer[InIndex + 1]) shl 2) and 60) or ((Word(Buffer[InIndex + 2]) shr 6) and 3)); OutBuffer[OutIndex + 3] := Char(-1);//'='; end; Inc(InIndex, 3); Inc(OutIndex, 4); end; until not(InIndex < Completed); ConvertToBase64(OutBuffer, OutIndex); ADestination.Write(OutBuffer^, OutIndex); finally FreeMem(OutBuffer); FreeMem(Buffer); end; end; function TclEncoder.DecodeBASE64(ASource, ADestination: TStream): Boolean; var Buffer: PChar; DestBuffer: PChar; CharCode, i, Completed, Index, OutIndex, TmpIndex, StrLength: Integer; begin Result := False; Completed := ASource.Size; if (Completed = 0) then Exit; GetMem(Buffer, Completed); GetMem(DestBuffer, Completed); try ASource.Read(Buffer^, Completed); StrLength := 0; OutIndex := 0; for Index := 0 to Completed - 1 do begin if ((Buffer[Index] in ['=', CR, LF]) or (Index = (Completed - 1))) then begin if (Index = (Completed - 1)) and not (Buffer[Index] in ['=', CR, LF]) then begin CharCode := Base64CodeTableEx[Integer(Buffer[Index])] - 1; if (CharCode < 0) then clEncoderError(SclErrorWrongSymbols); DestBuffer[Index] := Char(CharCode); Inc(StrLength); TmpIndex := Index - StrLength + 1; end else begin TmpIndex := Index - StrLength; end; for i := 0 to (StrLength div 4) - 1 do begin DestBuffer[OutIndex] := Chr((Word(DestBuffer[TmpIndex]) shl 2) or (Word(DestBuffer[TmpIndex + 1]) shr 4)); DestBuffer[OutIndex + 1] := Chr((Word(DestBuffer[TmpIndex + 1]) shl 4) or (Word(DestBuffer[TmpIndex + 2]) shr 2)); DestBuffer[OutIndex + 2] := Chr((Word(DestBuffer[TmpIndex + 2]) shl 6) or (Word(DestBuffer[TmpIndex + 3]))); Inc(TmpIndex, 4); Inc(OutIndex, 3); end; if (StrLength mod 4) > 0 then begin DestBuffer[OutIndex] := Chr((Word(DestBuffer[TmpIndex]) shl 2) or (Word(DestBuffer[TmpIndex + 1]) shr 4)); DestBuffer[OutIndex + 1] := Chr((Word(DestBuffer[TmpIndex + 1]) shl 4) or (Word(DestBuffer[TmpIndex + 2]) shr 2)); Inc(OutIndex, (StrLength mod 4)-1); end; StrLength := 0; if (Buffer[Index] = '=') then begin Break; end; end else begin CharCode := Base64CodeTableEx[Integer(Buffer[Index])] - 1; if (CharCode < 0) then clEncoderError(SclErrorWrongSymbols); DestBuffer[Index] := Char(CharCode); Inc(StrLength); end; end; ADestination.Write(DestBuffer^, OutIndex); finally FreeMem(DestBuffer); FreeMem(Buffer); end; end; function TclEncoder.EncodeQP(ASource, ADestination: TStream): Boolean; var Symbol, Symbol1: Char; i: Integer; Code: Integer; SoftBreak: Boolean; begin ADestination.Size := 0; ADestination.Position := 0; repeat Result := True; SoftBreak := True; i := 0; while(FSuppressCrlf or(i <= GetCorrectCharsPerLine() - 6)) do begin if (ASource.Read(Symbol, 1) = 1) then begin Code := Ord(Symbol); case Code of 32..60,62..126: ADestination.Write(Symbol, 1); 61: begin ADestination.Write(Pointer(Format('=%2.2X', [Code]))^, 3); i := i + 2; end; 13: begin if (ASource.Read(Symbol, 1) = 1) then begin if (Symbol = LF) then begin Symbol1 := CR; ADestination.Write(Symbol1, 1); Symbol1 := LF; ADestination.Write(Symbol1, 1); SoftBreak := False; Break; end else begin ADestination.Write(Pointer(Format('=%2.2X', [Code]))^, 3); i := i + 2; ASource.Seek(-1, soFromCurrent); end; end; end; else begin ADestination.Write(Pointer(Format('=%2.2X', [Code]))^, 3); i := i + 2; end; end; FFirstPass := False; end else begin SoftBreak := False; Result := False; break; end; Inc(i); end; if SoftBreak and not FStringProcessed then begin Symbol := '='; ADestination.Write(Symbol, 1); Symbol1 := CR; ADestination.Write(Symbol1, 1); Symbol1 := LF; ADestination.Write(Symbol1, 1); end; until not Result; end; function TclEncoder.DecodeQP(ASource, ADestination: TStream): Boolean; var Symbol: Char; Buffer: string; Eof: Boolean; i: Integer; HexNumber: Integer; CRLFSkipped: Integer; CodePresent: Boolean; begin HexNumber := 0; CRLFSkipped := 0; CodePresent := False; ADestination.Size := 0; ADestination.Position := 0; repeat Buffer := ReadOneLine(ASource, Eof, CRLFSkipped); Result := not Eof; if FDelimPresent then begin Dec(CRLFSkipped); end; FDelimPresent := False; for i := 0 to CRLFSkipped - 1 do begin ADestination.Write(#13#10, 2); end; CRLFSkipped := 0; for i := 1 to Length(Buffer) do begin if (FDelimPresent) then begin case Buffer[i] of 'A'..'F': begin HexNumber := HexNumber + (Ord(Buffer[i]) - 55); end; 'a'..'f': begin HexNumber := HexNumber + (Ord(Buffer[i]) - 87); end; '0'..'9': begin HexNumber := HexNumber + (Ord(Buffer[i]) - 48); end; else begin CodePresent := False; FDelimPresent := False; HexNumber := 0; Symbol := '='; ADestination.Write(Symbol, 1); ADestination.Write(Buffer[i], 1); end; end; if not CodePresent then begin HexNumber := HexNumber*16; CodePresent := True; continue; end else begin Symbol := Chr(HexNumber); ADestination.Write(Symbol, 1); CodePresent := False; FDelimPresent := False; HexNumber := 0; end; end else begin if Buffer[i] = '=' then begin FDelimPresent := True; end else begin ADestination.Write(Buffer[i], 1); end; end; end; until Eof; end; function TclEncoder.EncodeUUE(ASource, ADestination: TStream): Boolean; procedure ConvertToUUE(ASymbolsArray: PChar; ACount, ALineLength: Integer); var SymbCount, Symb, i: Integer; begin SymbCount := 0; for i := 0 to ACount - 1 do begin Inc(SymbCount); if (SymbCount > ALineLength) then begin if (SymbCount <= (ALineLength + 2)) then Continue; SymbCount := 1; end; Symb := Integer(ASymbolsArray[i]); if Symb = 0 then ASymbolsArray[i] := '`' else ASymbolsArray[i] := Chr((Symb and 63) + Ord(' ')); end; end; var Buffer: PChar; OutBuffer: PChar; LineLength, Length, OutLineLength, OutLen, i, k, Completed, Index, OutIndex: Integer; begin Result := False; if FSuppressCrlf then begin Length:= ASource.Size; end else begin Length:= Trunc(GetCorrectCharsPerLine() * 3/4); end; Completed := ASource.Size; if (Completed = 0) then Exit; GetMem(Buffer, Completed); OutLen := ((Completed div Length) + 1) * (GetCorrectCharsPerLine() + 5); OutLen := (OutLen + ($2000 - 1)) and not ($2000 - 1); GetMem(OutBuffer, OutLen); try ASource.Read(Buffer^, Completed); Index := 0; OutIndex := 0; LineLength := 0; OutLineLength := 0; for i := 0 to (Completed div Length) do begin LineLength := Completed - Index; if (LineLength > Length) then LineLength := Length; OutBuffer[OutIndex] := Char(LineLength); Inc(OutIndex); for k := 0 to (LineLength div 3) - 1 do begin OutBuffer[OutIndex] := Char(Word(Buffer[Index]) shr 2); OutBuffer[OutIndex + 1] := Char(((Word(Buffer[Index]) shl 4) and 48) or ((Word(Buffer[Index + 1]) shr 4) and 15)); OutBuffer[OutIndex + 2] := Char(((Word(Buffer[Index + 1]) shl 2) and 60) or ((Word(Buffer[Index + 2]) shr 6) and 3)); OutBuffer[OutIndex + 3] := Char(Word(Buffer[Index + 2]) and 63); Inc(Index, 3); Inc(OutIndex, 4); end; if ((LineLength mod 3) > 0) then begin OutBuffer[OutIndex] := Char(Word(Buffer[Index]) shr 2); if ((LineLength mod 3) = 2) then begin OutBuffer[OutIndex + 1] := Char(((Word(Buffer[Index]) shl 4) and 48) or ((Word(Buffer[Index + 1]) shr 4) and 15)); OutBuffer[OutIndex + 2] := Char(((Word(Buffer[Index + 1]) shl 2) and 60)); end else begin OutBuffer[OutIndex + 1] := Char(((Word(Buffer[Index]) shl 4) and 48)); OutBuffer[OutIndex + 2] := #0; end; Inc(Index, LineLength mod 3); Inc(OutIndex, LineLength mod 3 + 1); end; if (OutLineLength = 0) then OutLineLength := OutIndex; if (not FSuppressCrlf) and (LineLength >= Length) then begin OutBuffer[OutIndex] := CR; OutBuffer[OutIndex + 1] := LF; Inc(OutIndex, 2); end; end; ConvertToUUE(OutBuffer, OutIndex, OutLineLength); if not FSuppressCrlf then begin if (LineLength < Length) then begin OutBuffer[OutIndex] := CR; OutBuffer[OutIndex + 1] := LF; Inc(OutIndex, 2); end; OutBuffer[OutIndex] := '`'; Inc(OutIndex, 1); OutBuffer[OutIndex] := CR; OutBuffer[OutIndex + 1] := LF; Inc(OutIndex, 2); end; ADestination.Write(OutBuffer^, OutIndex); finally FreeMem(OutBuffer); FreeMem(Buffer); end; end; function TclEncoder.DecodeUUE(ASource, ADestination: TStream): Boolean; var Buffer, DestBuffer: PChar; curStrLength, Completed, i, Index, OutIndex, LineStartIndex, StrLength: Integer; SckipToLineEnd, HeaderSkipped, CRLFSkipped: Boolean; TmpStr: string; begin Result := False; Completed := ASource.Size; if (Completed = 0) then Exit; GetMem(Buffer, Completed); GetMem(DestBuffer, Completed); try ASource.Read(Buffer^, Completed); StrLength := 0; OutIndex := 0; curStrLength := 0; LineStartIndex := 0; CRLFSkipped := True; HeaderSkipped := False; SckipToLineEnd := False; for Index := 0 to Completed - 1 do begin if ((Buffer[Index] in [CR, LF]) or (Index = (Completed - 1))) then begin if (Index = (Completed - 1)) and (not SckipToLineEnd) and not (Buffer[Index] in [CR, LF]) then begin DestBuffer[OutIndex] := Char((Integer(Buffer[Index]) - $20) and 63); end; SckipToLineEnd := False; OutIndex := LineStartIndex; for i := 0 to (StrLength div 4) - 1 do begin DestBuffer[OutIndex] := Chr((Word(DestBuffer[LineStartIndex]) shl 2) or (Word(DestBuffer[LineStartIndex + 1]) shr 4)); DestBuffer[OutIndex + 1] := Chr((Word(DestBuffer[LineStartIndex + 1]) shl 4) or (Word(DestBuffer[LineStartIndex + 2]) shr 2)); DestBuffer[OutIndex + 2] := Chr((Word(DestBuffer[LineStartIndex + 2]) shl 6) or (Word(DestBuffer[LineStartIndex + 3]))); Inc(OutIndex, 3); Inc(LineStartIndex, 4); end; if ((StrLength mod 4) > 0) then begin DestBuffer[OutIndex] := Chr((Word(DestBuffer[LineStartIndex]) shl 2) or (Word(DestBuffer[LineStartIndex + 1]) shr 4)); DestBuffer[OutIndex + 1] := Chr((Word(DestBuffer[LineStartIndex + 1]) shl 4) or (Word(DestBuffer[LineStartIndex + 2]) shr 2)); Inc(OutIndex, StrLength mod 4); end; curStrLength := 0; StrLength := 0; CRLFSkipped := True; LineStartIndex := OutIndex; end else begin if SckipToLineEnd then begin DestBuffer[OutIndex] := #0; Inc(OutIndex); Continue; end; if CRLFSkipped then begin curStrLength := 0; if not HeaderSkipped then begin HeaderSkipped := True; TmpStr := 'begin'; if CompareMem(PChar(Buffer + Index), PChar(TmpStr), 5) then begin SckipToLineEnd := True; Continue; end; end; StrLength := (((Integer(Buffer[Index]) - $20) and 63)*4) div 3; CRLFSkipped := False; if StrLength = 0 then Break else Continue; end; DestBuffer[OutIndex] := Char((Integer(Buffer[Index]) - $20) and 63); Inc(OutIndex); Inc(curStrLength); if (curStrLength > StrLength) then begin SckipToLineEnd := True; end; end; end; ADestination.Write(DestBuffer^, OutIndex); finally FreeMem(DestBuffer); FreeMem(Buffer); end; end; procedure TclEncoder.DoProgress(ABytesProceed, ATotalBytes: Integer); begin if Assigned(FOnProgress) then begin FOnProgress(Self, ABytesProceed, ATotalBytes); end; end; function TclEncoder.ReadOneLine(AStream: TStream; var Eof: Boolean; var crlfSkipped: Integer): string; var Symbol: Char; PrevSymbol: Char; Completed: Integer; StrLength: Integer; RollBackCnt: Integer; begin Result := ''; Eof := False; crlfSkipped := 0; StrLength := 0; PrevSymbol := #0; RollBackCnt := 0; while (True) do begin Completed := AStream.Read(Symbol, 1); if (Completed = 0) then begin Eof := True; RollBackCnt := StrLength; Break; end; if (Symbol in [CR, LF]) then begin if (StrLength <> 0) then begin RollBackCnt := StrLength + 1; Break; end; if not ((PrevSymbol = CR) and (Symbol = LF)) then begin Inc(crlfSkipped); end; end else begin Inc(StrLength); end; PrevSymbol := Symbol; end; if (StrLength <> 0) then begin SetLength(Result, StrLength); AStream.Seek(-RollBackCnt, soFromCurrent); AStream.Read(Pointer(Result)^, StrLength); end; end; function TclEncoder.GetCorrectCharsPerLine: Integer; begin Result := CharsPerLine; if (Result < 1) then begin Result := DefaultCharsPerLine; end; case FMethod of cmUUEncode: begin if (CharsPerLine < 3) then begin Result := 3; end else if (CharsPerLine > MaxUUECharsPerLine) then begin Result := MaxUUECharsPerLine; end; end; cmMIMEQuotedPrintable: begin if (CharsPerLine < 4) then begin Result := 4; end else if (CharsPerLine > MaxQPCharsPerLine) then begin Result := MaxQPCharsPerLine; end; end; cmMIMEBase64: begin if(MinBASE64CharsPerLine <= CharsPerLine) then begin Result := Round(CharsPerLine/4 + 0.25) * 4; end else begin Result := MinBASE64CharsPerLine; end; end; end; end; procedure TclEncoder.DecodeFromString(const ASource: string; ADestination: TStream; AMethod: TclEncodeMethod); var SourceStream: TStream; begin SourceStream := TMemoryStream.Create(); try SourceStream.WriteBuffer(PChar(ASource)^, Length(ASource)); SourceStream.Position := 0; DecodeStream(SourceStream, ADestination, AMethod); finally SourceStream.Free(); end; end; procedure TclEncoder.EncodeToString(ASource: TStream; var ADestination: string; AMethod: TclEncodeMethod); var DestinationStream: TStream; begin DestinationStream := TMemoryStream.Create(); try FStringProcessed := True; EncodeStream(ASource, DestinationStream, AMethod); SetLength(ADestination, DestinationStream.Size); DestinationStream.Position := 0; DestinationStream.ReadBuffer(PChar(ADestination)^, DestinationStream.Size); finally DestinationStream.Free(); FStringProcessed := False; end; end; end.
unit DzPngCollection; { Jacek Pazera http://www.pazera-software.com https://github.com/jackdp Last mod: 2019.05.22 } {$I dz2.inc} {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} interface uses SysUtils, Classes, Types, {$IFDEF HAS_SYSTEM_UITYPES}System.UITypes,{$ENDIF} Graphics {$IFDEF DCC}{$IFDEF HAS_UNIT_SCOPE}, Vcl.Imaging.PngImage{$ELSE}, pngimage{$ENDIF}{$ENDIF}; type {$IFDEF FPC} TPngImage = TPortableNetworkGraphic; {$ENDIF} TDzPngCollectionItem = class; TDzPngCollectionItems = class; {$region ' --- TDzPngCollection --- '} TDzPngCollection = class(TComponent) private FItems: TDzPngCollectionItems; procedure EnableOrDisableAll(const Enable: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; procedure EnableAll; procedure DisableAll; function PngIndex(const PngName: string; IgnoreCase: Boolean = False): integer; function Count: integer; function IsValidIndex(const Index: integer): Boolean; function AddPngImageFromFile(const FileName: string): integer; // Returns the index of the added item function AddPngImage(Png: TPngImage; ImageName: string = ''; Description: string = ''; Enabled: Boolean = True; ATag: integer = 0): integer; function GetPngImage(const Index: integer): TPngImage; function GetPngImageByName(const PngName: string; IgnoreCase: Boolean = True): TPngImage; // Returns the first PngImage with the given name function ReportStr: string; // for debug published property Items: TDzPngCollectionItems read FItems write FItems; end; {$endregion TDzPngCollection} {$region ' --- TDzPngCollectionItems --- '} TDzPngCollectionItems = class(TCollection) private FOwner: TPersistent; function GetItem(Index: Integer): TDzPngCollectionItem; procedure SetItem(Index: Integer; const Value: TDzPngCollectionItem); protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; function IsValidIndex(const Index: integer): Boolean; public constructor Create(AOwner: TPersistent); function Add: TDzPngCollectionItem; //reintroduce; procedure Assign(Source: TPersistent); override; function Insert(Index: Integer): TDzPngCollectionItem; property Items[index: Integer]: TDzPngCollectionItem read GetItem write SetItem; default; end; {$endregion TDzPngCollectionItems} {$region ' --- TDzPngCollectionItem --- '} TDzPngCollectionItem = class(TCollectionItem) private FName: string; FDescription: string; FPngImage: TPngImage; FTag: integer; FEnabled: Boolean; procedure SetPngImage(const Value: TPngImage); function GetWidth: integer; function GetHeight: integer; protected procedure AssignTo(Dest: TPersistent); override; function GetDisplayName: string; override; public constructor Create(ACollection: TCollection); overload; override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Name: string read FName write FName; property Description: string read FDescription write FDescription; property PngImage: TPngImage read FPngImage write SetPngImage; property Width: integer read GetWidth; property Height: integer read GetHeight; property Tag: integer read FTag write FTag default 0; property Enabled: Boolean read FEnabled write FEnabled default True; end; {$endregion TDzPngCollectionItem} //procedure Register; implementation //procedure Register; //begin // RegisterComponents('Digao', [TDzPngCollection]); //end; {$region ' --------------------- TDzPngCollection ----------------------- '} constructor TDzPngCollection.Create(AOwner: TComponent); begin inherited Create(AOwner); FItems := TDzPngCollectionItems.Create(Self); end; destructor TDzPngCollection.Destroy; begin FItems.Free; inherited Destroy; end; procedure TDzPngCollection.Clear; begin FItems.Clear; end; function TDzPngCollection.Count: integer; begin Result := FItems.Count; end; procedure TDzPngCollection.DisableAll; begin EnableOrDisableAll(False); end; procedure TDzPngCollection.EnableAll; begin EnableOrDisableAll(True); end; procedure TDzPngCollection.EnableOrDisableAll(const Enable: Boolean); var i: integer; begin for i := 0 to FItems.Count - 1 do FItems[i].Enabled := Enable; end; function TDzPngCollection.IsValidIndex(const Index: integer): Boolean; begin Result := Items.IsValidIndex(Index); end; function TDzPngCollection.AddPngImageFromFile(const FileName: string): integer; var Png: TPngImage; begin if not FileExists(FileName) then Exit(-1); Png := TPngImage.Create; try try Png.LoadFromFile(FileName); Result := AddPngImage(Png); except Result := -1; end; finally Png.Free; end; end; function TDzPngCollection.AddPngImage(Png: TPngImage; ImageName: string; Description: string; Enabled: Boolean; ATag: integer): integer; var pci: TDzPngCollectionItem; begin pci := Items.Add; try pci.PngImage.Assign(Png); Result := pci.Index; if ImageName <> '' then pci.Name := ImageName; pci.Description := Description; pci.Enabled := Enabled; pci.Tag := ATag; except Result := -1; end; end; function TDzPngCollection.GetPngImage(const Index: integer): TPngImage; begin Result := Items[Index].PngImage; end; function TDzPngCollection.GetPngImageByName(const PngName: string; IgnoreCase: Boolean): TPngImage; var x: integer; begin x := PngIndex(PngName, IgnoreCase); if x < 0 then Exit(nil); Result := Items[x].PngImage; end; function TDzPngCollection.ReportStr: string; const ENDL = sLineBreak; var i: integer; s, Sep: string; pci: TDzPngCollectionItem; b: Boolean; function BoolToStrYN(const b: Boolean): string; begin if b then Result := 'Yes' else Result := 'No'; end; begin s := 'PngCollection: ' + Self.Name + ENDL + 'Items: ' + IntToStr(Items.Count) + ENDL; Sep := ' '; for i := 0 to Items.Count - 1 do begin pci := Items[i]; s := s + 'Item ' + IntToStr(i + 1) + ENDL; s := s + Sep + 'Index: ' + IntToStr(pci.Index) + ENDL; s := s + Sep + 'Name: ' + pci.Name + ENDL; s := s + Sep + 'Description: ' + pci.Description + ENDL; s := s + Sep + 'Enabled: ' + BoolToStrYN(pci.Enabled) + ENDL; s := s + Sep + 'Tag: ' + IntToStr(pci.Tag) + ENDL; b := pci.PngImage.Empty; s := s + Sep + 'Empy image: ' + BoolToStrYN(b) + ENDL; if b then Continue; s := s + Sep + 'Width: ' + IntToStr(pci.PngImage.Width) + ENDL; s := s + Sep + 'Height: ' + IntToStr(pci.PngImage.Height) + ENDL; {$IFDEF DCC} s := s + Sep + 'Bit depth: ' + IntToStr(pci.PngImage.Header.BitDepth) + ENDL; s := s + Sep + 'Compression level: ' + IntToStr(pci.PngImage.CompressionLevel) + ENDL; s := s + Sep + 'Compression method: ' + IntToStr(pci.PngImage.Header.CompressionMethod) + ENDL; //s := s + Sep + 'Transparent color: ' + ColorToRgbIntStr(pci.PngImage.TransparentColor) + ENDL; {$ENDIF} end; Result := s; end; function TDzPngCollection.PngIndex(const PngName: string; IgnoreCase: Boolean): integer; var i: integer; s: string; b: Boolean; begin Result := -1; if FItems.Count = 0 then Exit; s := PngName; if IgnoreCase then s := AnsiUpperCase(s); for i := 0 to FItems.Count - 1 do begin if IgnoreCase then b := s = AnsiUpperCase(FItems[i].Name) else b := s = FItems[i].Name; if b then begin Result := i; Break; end; end; end; {$endregion TDzPngCollection} {$region ' ------------------------ TDzPngCollectionItems ------------------------------ '} constructor TDzPngCollectionItems.Create(AOwner: TPersistent); begin inherited Create(TDzPngCollectionItem); FOwner := AOwner; end; function TDzPngCollectionItems.Add: TDzPngCollectionItem; begin Result := TDzPngCollectionItem(inherited Add); end; procedure TDzPngCollectionItems.Assign(Source: TPersistent); begin inherited Assign(Source); Update(nil); end; function TDzPngCollectionItems.IsValidIndex(const Index: integer): Boolean; begin Result := (Index >= 0) and (Index < Count); end; function TDzPngCollectionItems.GetItem(Index: Integer): TDzPngCollectionItem; begin if IsValidIndex(Index) then Result := TDzPngCollectionItem(inherited Items[Index]) else Result := nil; end; procedure TDzPngCollectionItems.SetItem(Index: Integer; const Value: TDzPngCollectionItem); begin if IsValidIndex(Index) then inherited Items[Index] := Value; end; procedure TDzPngCollectionItems.Update(Item: TCollectionItem); begin inherited Update(Item); end; function TDzPngCollectionItems.Insert(Index: Integer): TDzPngCollectionItem; begin Result := TDzPngCollectionItem(inherited Insert(Index)); end; function TDzPngCollectionItems.GetOwner: TPersistent; begin Result := FOwner; end; {$endregion TDzPngCollectionItems} {$region ' ---------------------- TDzPngCollectionItem --------------------------- '} constructor TDzPngCollectionItem.Create(ACollection: TCollection); begin inherited Create(ACollection); FPngImage := TPngImage.Create; FName := 'Png_' + IntToStr(Index); FTag := 0; FEnabled := True; end; destructor TDzPngCollectionItem.Destroy; begin FPngImage.Free; inherited Destroy; end; procedure TDzPngCollectionItem.Assign(Source: TPersistent); begin if Source is TDzPngCollectionItem then begin FPngImage.Assign(TDzPngCollectionItem(Source).PngImage); FName := TDzPngCollectionItem(Source).Name; FTag := TDzPngCollectionItem(Source).Tag; FEnabled := TDzPngCollectionItem(Source).Enabled; end else inherited Assign(Source); end; procedure TDzPngCollectionItem.AssignTo(Dest: TPersistent); begin inherited AssignTo(Dest); if (Dest is TDzPngCollectionItem) then TDzPngCollectionItem(Dest).PngImage := FPngImage; end; function TDzPngCollectionItem.GetDisplayName: string; begin if Length(FName) = 0 then Result := inherited GetDisplayName else Result := FName; end; function TDzPngCollectionItem.GetHeight: integer; begin if PngImage.Empty then Result := 0 else Result := PngImage.Height; end; function TDzPngCollectionItem.GetWidth: integer; begin if PngImage.Empty then Result := 0 else Result := PngImage.Width; end; procedure TDzPngCollectionItem.SetPngImage(const Value: TPngImage); begin if FPngImage = nil then FPngImage := TPngImage.Create; FPngImage.Assign(Value); FTag := 0; Changed(False); end; {$endregion TDzPngCollectionItem} end.
unit UDrives; (*==================================================================== Functions to get the list of available drives ======================================================================*) interface uses Classes, UStringList, UTypes, UApiTypes; type TDriveType = (dtUnknown, dtNoDrive, dtFloppy, dtFixed, dtNetwork, dtCDROM, dtRAM); type TPDrive = ^TDrive; TDrive = record Name : AnsiString; Fstype : AnsiString; Mount : AnsiString; Lbl : AnsiString; end; const FloppyAExists : boolean = false; FloppyBExists : boolean = false; ScanAllDriveNames: boolean = true; {set by Program Settings dialog} var ///DriveList : TQStringList; DriveList : TStringList; procedure BuildDriveList; {$ifdef mswindows} function QGetDriveName(DriveChar: char): ShortString; {$else} function QGetDriveName(Drive: string): AnsiString; {$endif} function ReadVolumeLabel(Disk: ShortString; var Name: ShortString; var FileSystem: TFileSystem; var DriveType: integer): boolean; function WriteVolumeLabel (Disk: ShortString; Name: ShortString): boolean; function FindDriveType(DriveNum: Integer): TDriveType; implementation uses {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} Process, Strutils, LCLIntf, LCLType, LMessages, {$ENDIF} SysUtils; //---------------------------------------------------------------------------- function VolumeID(DriveChar: Char): ShortString; var OldErrorMode: Integer; NotUsed, VolFlags: longword; Buf: array [0..MAX_PATH] of Char; DriveSpec: array[0..3] of char; begin Result := ''; {$ifdef mswindows} DriveSpec[0] := DriveChar; DriveSpec[1] := ':'; DriveSpec[2] := '\'; DriveSpec[3] := #0; OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try if GetVolumeInformation(DriveSpec, Buf, sizeof(Buf), nil, NotUsed, VolFlags, nil, 0) then Result := StrPas(Buf); finally SetErrorMode(OldErrorMode); end; {$endif} end; //---------------------------------------------------------------------------- function NetworkVolume(DriveChar: Char): ShortString; var Buf: Array [0..MAX_PATH] of Char; DriveStr: array [0..3] of Char; BufferSize: longword; begin {$ifdef mswindows} BufferSize := sizeof(Buf); DriveStr[0] := DriveChar; DriveStr[1] := ':'; DriveStr[2] := #0; if WNetGetConnection(DriveStr, Buf, BufferSize) = WN_SUCCESS then Result := StrPas(Buf) else Result := VolumeID(DriveChar); {$endif} Result := VolumeID(DriveChar); end; //---------------------------------------------------------------------------- function FindDriveType(DriveNum: Integer): TDriveType; var DriveSpec: array[0..3] of char; begin DriveSpec[0] := Char(DriveNum + Ord('a')); DriveSpec[1] := ':'; DriveSpec[2] := '\'; DriveSpec[3] := #0; ///Result := TDriveType(GetDriveType(DriveSpec)); end; //---------------------------------------------------------------------------- {$ifdef windows} procedure BuildDriveList; var DriveNum: Integer; DriveChar: Char; DriveType: TDriveType; DriveBits: set of 0..25; begin DriveList.Clear; ///Integer(DriveBits) := GetLogicalDrives; for DriveNum := 0 to 25 do begin if not (DriveNum in DriveBits) then Continue; DriveChar := Char(DriveNum + Ord('a')); DriveType := FindDriveType(DriveNum); DriveChar := Upcase(DriveChar); if ScanAllDriveNames then case DriveType of dtFloppy: DriveList.Add(DriveChar + ':'); dtFixed: DriveList.Add(DriveChar + ': [' + VolumeID(DriveChar) + ']'); dtNetwork: DriveList.Add(DriveChar + ': [' + NetworkVolume(DriveChar) + ']'); dtCDROM: DriveList.Add(DriveChar + ': [' + VolumeID(DriveChar) + ']'); dtRAM: DriveList.Add(DriveChar + ': [' + VolumeID(DriveChar) + ']'); end else case DriveType of dtFloppy: DriveList.Add(DriveChar + ':'); dtFixed: DriveList.Add(DriveChar + ':'); dtNetwork: DriveList.Add(DriveChar + ':'); dtCDROM: DriveList.Add(DriveChar + ':'); dtRAM: DriveList.Add(DriveChar + ':'); end end; end; {$else} type TSarray = array of string; function Split(Text, Delimiter: string): TSarray; var i: integer; Len: integer; PosStart: integer; PosDel: integer; begin i := 0; SetLength(Result, 1); Len := Length(Delimiter); PosStart := 1; PosDel := Pos(Delimiter, Text); while PosDel > 0 do begin Result[i] := Copy(Text, PosStart, PosDel - PosStart); Result[i]:=StringReplace(Result[i],'"','',[rfReplaceAll]); ///PosStart := PosDel + Len; Text:=copy(text,PosDel+1,length(text)); PosDel := Pos(Delimiter, Text);//, PosStart); inc(i); SetLength(Result, i + 1); end; Result[i] := Copy(Text, PosStart, Length(Text)); Result[i]:=StringReplace(Result[i],'"','',[rfReplaceAll]); end; // NAME="sda1" FSTYPE="ext4" MOUNTPOINT="/mnt/sdc1" LABEL="SDC1" procedure BuildDriveList; var s: string; name,fstype,mount,lbl : string; list: TStringList; i: integer; l: TSarray; Drive: TPDrive; begin //FreeObjects(DriveList); for i := 0 to DriveList.Count - 1 do Dispose(TPDrive(DriveList.Objects[i])); DriveList.Clear; List:=TStringList.Create; //RunCommand('/usr/bin/lsblk', ['-nP', '-o NAME,FSTYPE,MOUNTPOINT,LABEL'], s); RunCommand('/usr/bin/sudo', ['/usr/bin/lsblk','-nP','-o', 'NAME,FSTYPE,MOUNTPOINT,LABEL'], s); ExtractStrings([#10], [], PChar(s), List); for i:=0 to List.Count -1 do begin l:=Split(list[i], ' '); //s:=StringReplace(list[i],'"','',[rfReplaceAll]); name:=StringReplace(l[0],'NAME=','',[rfReplaceAll]); fstype:=StringReplace(l[1],'FSTYPE=','',[rfReplaceAll]); mount:=StringReplace(l[2],'MOUNTPOINT=','',[rfReplaceAll]); lbl:=StringReplace(l[3],'LABEL=','',[rfReplaceAll]); //SScanf(List[i],'NAME="%s" FSTYPE="%s" MOUNTPOINT="%s" LABEL="%s"',[@name,@fstype,@mount,@lbl]); if mount <> '' then begin New(Drive); Drive^.Name:=name; Drive^.Fstype:=fstype; Drive^.Mount:=mount; Drive^.Lbl:=lbl; DriveList.AddObject(mount,TObject(Drive)); end; end; List.Free; end; {$endif} //---------------------------------------------------------------------------- {$ifdef mswindows} function QGetDriveName(DriveChar: char): ShortString; var DriveNum : Integer; DriveType: TDriveType; begin DriveChar := UpCase(DriveChar); DriveNum := integer(byte(DriveChar) - byte('A')); DriveType := FindDriveType(DriveNum); Result := ''; case DriveType of dtFloppy: Result := VolumeID(DriveChar); dtFixed: Result := VolumeID(DriveChar); dtNetwork: Result := NetworkVolume(DriveChar); dtCDROM: Result := VolumeID(DriveChar); dtRAM: Result := VolumeID(DriveChar); end; end; {$else} function QGetDriveName(Drive: String): AnsiString; var i: integer; s,t: string; begin if DriveList.Count < 1 then BuildDriveList; // first is root result:= TPDrive(DriveList.Objects[0])^.Lbl; for i:=1 to DriveList.Count-1 do begin s:=TPDrive(DriveList.Objects[i])^.Mount; t:=copy(Drive,1,length(s)); if s=t then begin Result:=TPDrive(DriveList.Objects[i])^.Lbl; break; end; end; for i := 0 to DriveList.Count - 1 do Dispose(TPDrive(DriveList.Objects[i])); DriveList.Clear; end; {$endif} //---------------------------------------------------------------------------- // Disk is ShortString in format 'A:' {$ifdef mswindows} function ReadVolumeLabel (Disk: ShortString; var Name: ShortString; var FileSystem: TFileSystem; var DriveType: integer): boolean; var RootPathName: array[0..255] of char; VolumeNameBuffer: array[0..255] of char; VolumeFileSystem: array[0..50] of char; MaximumComponentLength: DWORD; FileSystemFlags: DWORD; begin StrPCopy(RootPathName, Disk + '\'); ///Result := GetVolumeInformation (RootPathName, VolumeNameBuffer, 255, /// nil, MaximumComponentLength, FileSystemFlags, VolumeFileSystem, 50); Name := StrPas(VolumeNameBuffer); FileSystem := Unknown; if StrComp(VolumeFileSystem, 'FAT') = 0 then FileSystem := FAT; if StrComp(VolumeFileSystem, 'HPFS') = 0 then FileSystem := HPFS; if StrComp(VolumeFileSystem, 'NTFS') = 0 then FileSystem := NTFS; ///DriveType := GetDriveType(RootPathName); end; {$else} function ReadVolumeLabel (Disk: ShortString; var Name: ShortString; var FileSystem: TFileSystem; var DriveType: integer): boolean; var i: integer; s,t: string; begin if DriveList.Count < 1 then BuildDriveList; // first is root result:= false; DriveType:=0 ; for i:=1 to DriveList.Count-1 do begin s:=TPDrive(DriveList.Objects[i])^.Mount; t:=copy(Disk,1,length(s)); if s=t then begin Name:=TPDrive(DriveList.Objects[i])^.Lbl; FileSystem:=Unknown; if TPDrive(DriveList.Objects[i])^.Fstype = 'fat' then FileSystem:=FAT; if TPDrive(DriveList.Objects[i])^.Fstype = 'vfat' then FileSystem:=VFAT; if TPDrive(DriveList.Objects[i])^.Fstype = 'hpfs' then FileSystem:=HPFS; if TPDrive(DriveList.Objects[i])^.Fstype = 'ntfs' then FileSystem:=NTFS; if TPDrive(DriveList.Objects[i])^.Fstype = 'ext4' then FileSystem:=EXT4; if TPDrive(DriveList.Objects[i])^.Fstype = 'cdrom' then FileSystem:=CDROM; Result:=true; break; end; end; for i := 0 to DriveList.Count - 1 do Dispose(TPDrive(DriveList.Objects[i])); DriveList.Clear; end; {$endif} //---------------------------------------------------------------------------- // Disk is ShortString in format 'A:' function WriteVolumeLabel (Disk: ShortString; Name: ShortString): boolean; var RootPathName: array[0..255] of char; VolumeNameBuffer: array[0..255] of char; begin StrPCopy(RootPathName, Disk + '\'); StrPCopy(VolumeNameBuffer, Name); ///Result := SetVolumeLabel(RootPathName, VolumeNameBuffer); end; //---------------------------------------------------------------------------- begin ///DriveList := TQStringList.Create; DriveList := TStringList.Create; DriveList.Sorted := true; FloppyAExists := FindDriveType(0) = dtFloppy; FloppyBExists := FindDriveType(1) = dtFloppy; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmPanel Purpose : This is a regular panel that has a splitter bar on the oppositly aligned side Date : 07-10-1999 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmPanel; interface uses windows, messages, graphics, classes, forms, controls, sysutils, extctrls; {$I CompilerDefines.INC} type TrmCaptionPosition = (cpStandard, cpTopEdge); TrmPanel = class(TCustomPanel) private { Private } FActiveControl: TWinControl; fCapPos : TrmCaptionPosition; FBrush: TBrush; FDeltaPos: integer; FDownPos: TPoint; FLineDC: HDC; FLineVisible, fPanelSizing: Boolean; FMinSize: NaturalNumber; FMaxSize: Integer; FNewSize: Integer; FOldKeyDown: TKeyEvent; FOldSize: Integer; FPrevBrush: HBrush; FResizeStyle: TResizeStyle; FSplit: Integer; FOnMoved: TNotifyEvent; fonVisibleChanged: TNotifyEvent; fResizeBtn: boolean; fLastOpenSize: integer; fMouseOverBtn: boolean; fBtnDown: boolean; fDotCount: integer; fResizing: boolean; fSplitterPanel: boolean; fIBWidth: integer; fBtnOpenClose : boolean; fOnCanResize : TCanResizeEvent; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; function CanResize(var NewSize: Integer): Boolean; {$IFDEF D4_OR_HIGHER} reintroduce; {$ENDIF} virtual; procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMParentFontChanged(var Message: TMessage); message CM_PARENTFONTCHANGED; procedure SetResizeBtn(const Value: boolean); procedure SetDotCount(const Value: integer); procedure SetSplitterPanel(const Value: boolean); procedure SetCapPos(const Value: TrmCaptionPosition); procedure SetIBWidth(const Value: integer); procedure UpdateSize(X, Y: Integer); procedure CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer); procedure AllocateLineDC; procedure DrawLine; procedure ReleaseLineDC; procedure FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure StopSizing; function DoCanResize(var NewSize: Integer): Boolean; procedure UpdateControlSize; function Convert(wRect:TRect):TRect; procedure WMGetMinMaxInfo(var Message: TWMGetMinMaxInfo); message WM_GETMINMAXINFO; procedure WMNCCalcSize(var Message: TWMNCCalcSize) ; message WM_NCCALCSIZE; procedure WMNCPaint(var Message: TMessage) ; message WM_NCPAINT; procedure WMNCHitTest(var Message: TWMNCHitTest) ; message WM_NCHITTEST; procedure WMNCLButtonDown(var Message: TWMNCLButtonDown) ; message WM_NCLBUTTONDOWN; procedure WMNCMouseMove(var Message: TWMNCMouseMove) ; message WM_NCMOUSEMOVE; procedure wmEraseBkgrnd(var Msg:TMessage); message WM_EraseBkgnd; procedure WMLButtonUp(var Message: TWMLButtonUp) ; message WM_LBUTTONUP; protected { Protected } function GripSize: integer; function GripRect: TRect; function BtnRect: TRect; procedure PaintGrip; function GetClosedState: boolean; procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public { Public } constructor create(AOwner: TComponent); override; function GetClientRect: TRect; override; procedure AdjustClientRect(var Rect: TRect); override; property DockManager; property IsClosed : boolean read GetClosedState; property BtnOpenClose : boolean read fBtnOpenClose; procedure ClosePanel; procedure OpenPanel; published { Published } property Align; property Alignment; property Anchors; property AutoSize; property BevelInner; property BevelOuter default bvNone; property BevelWidth; property BorderStyle; property BiDiMode; property BorderWidth; property InternalBorderWidth : integer read fIBWidth write SetIBWidth default 0; property Caption; property CaptionPosition : TrmCaptionPosition read fCapPos write SetCapPos default cpStandard; property Color; property Constraints; property Ctl3D; property SplitterPanel: boolean read fSplitterPanel write SetSplitterPanel default false; property UseDockManager default True; property DotCount: integer read fDotCount write SetDotCount default 10; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; property MinSize: NaturalNumber read FMinSize write FMinSize default 30; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ResizeStyle: TResizeStyle read FResizeStyle write FResizeStyle default rsPattern; property ResizeBtn: boolean read fResizeBtn write SetResizeBtn default false; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; property OnVisibleChanged: TNotifyEvent read fOnVisibleChanged write fOnVisibleChanged; end; implementation {$R *.RES} uses rmLibrary; { TrmPanel } const DotSize = 4; type TWinControlAccess = class(TWinControl); procedure TrmPanel.CMMouseLeave(var Message: TMessage); begin inherited; Cursor := crDefault; fMouseOverBtn := false; PaintGrip; end; constructor TrmPanel.create(AOwner: TComponent); begin inherited create(AOwner); Caption := ''; fCapPos := cpStandard; fIBWidth := 0; BevelOuter := bvNone; BevelInner := bvNone; FMinSize := 30; FResizeStyle := rsPattern; FOldSize := -1; fPanelSizing := false; FDeltaPos := 0; fResizeBtn := false; fLastOpenSize := 0; fMouseOverBtn := false; fBtnDown := false; fDotCount := 10; fResizing := false; fSplitterPanel := false; end; function TrmPanel.GetClientRect: TRect; var wRect: TRect; begin wRect := inherited GetClientRect; if CaptionPosition = cpTopEdge then begin Canvas.Font := Self.Font; wRect.Top := wRect.Top + Canvas.textHeight('W'); end; result := wRect; end; function TrmPanel.GripRect: TRect; var wRect: TRect; begin case align of alTop: wRect := Rect(0, height - gripsize, width, height); alBottom: wRect := Rect(0, -GripSize, width, 0); alLeft: wRect := Rect(width - gripsize, 0, width, height); alRight: wRect := Rect(-GripSize, 0, 0, height); else wRect := Rect(-1, -1, -1, -1); end; result := wRect; end; procedure TrmPanel.UpdateControlSize; begin if FNewSize <> FOldSize then begin case Align of alLeft: Width := FNewSize; alTop: Height := FNewSize; alRight: begin Parent.DisableAlign; try Left := Left + (Width - FNewSize); Width := FNewSize; finally Parent.EnableAlign; end; end; alBottom: begin Parent.DisableAlign; try Top := Top + (Height - FNewSize); Height := FNewSize; finally Parent.EnableAlign; end; end; end; Update; if Assigned(FOnMoved) then FOnMoved(Self); FOldSize := FNewSize; end; end; procedure TrmPanel.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var wRect: TRect; TopColor, BottomColor: TColor; FontHeight: Integer; Flags: Longint; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin if CaptionPosition = cpStandard then begin inherited; end else begin with Canvas do begin Font := Self.Font; FontHeight := TextHeight('W'); Brush.Color := Color; FillRect(Rect(0,0,width,height)); end; wRect := ClientRect; wRect.Top := wRect.Top - (FontHeight div 2); if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, wRect, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, wRect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, wRect, TopColor, BottomColor, BevelWidth); end; with Canvas do begin wRect := GetClientRect; wRect.Top := wRect.Top - FontHeight; wRect.Bottom := Top + FontHeight; Case Alignment of taLeftJustify: begin wRect.Left := 8; wRect.Right := wRect.Left + TextWidth(Caption); end; taRightJustify: begin wRect.Right := wRect.Right - 8; wRect.Left := wRect.Right - TextWidth(Caption); end; taCenter: begin Try wRect.Left := (width - TextWidth(Caption)) div 2; except wRect.Left := 0; end; wRect.right := wRect.Left+TextWidth(caption)+1; end; end; OffsetRect(wRect, Borderwidth, BorderWidth); Flags := DT_EXPANDTABS or DT_VCENTER or DT_CENTER; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(Caption), -1, wRect, Flags); end; end; PaintGrip; end; procedure TrmPanel.CMVisibleChanged(var Message: TMessage); begin inherited; if assigned(fonVisibleChanged) then fOnVisibleChanged(self); end; procedure TrmPanel.SetResizeBtn(const Value: boolean); begin if fResizeBtn <> Value then begin fResizeBtn := Value; Realign; Invalidate; end; end; function TrmPanel.GripSize: integer; begin if fResizeBtn then result := 6 else result := 3; end; function TrmPanel.BtnRect: TRect; var wRect: TRect; wGripH, wGripW: integer; begin wrect := GripRect; wGripH := wRect.Bottom - wrect.Top; wGripW := wRect.Right - wrect.Left; case Align of alTop, alBottom: begin result.Left := ((wGripW div 2) - ((DotCount * DotSize) div 2)); result.right := result.left + (DotCount * DotSize); if align = altop then begin result.top := Height - wGripH; result.Bottom := height; end else begin result.top := -wGripH; result.Bottom := 0; end; InflateRect(result, 12, 0); end; alLeft, alRight: begin result.Top := ((wGripH div 2) - ((DotCount * DotSize) div 2)); result.Bottom := result.Top + (DotCount * DotSize); if align = alLeft then begin result.Left := Width - wGripW; result.Right := Width; end else begin result.Left := -wGripW; result.Right := 0; end; InflateRect(result, 0, 12); end; else result := Rect(0, 0, 0, 0); end; end; procedure TrmPanel.SetDotCount(const Value: integer); begin if (value >= 5) and (value <= 20) then begin fDotCount := value; PaintGrip; end else raise ERangeError.Create('Value must be between 5 and 20'); end; procedure TrmPanel.PaintGrip; var DC : HDC; loop: integer; wrect: TRect; adjust: integer; wBmp: TBitmap; wArrow: TBitmap; wxpos, wypos : integer; begin if not (SplitterPanel or ResizeBtn) then exit; wBmp := TBitMap.create; try wRect := GripRect; wBmp.Height := wRect.Bottom - wRect.Top; wBmp.Width := wRect.Right - wRect.Left; wBmp.canvas.brush.color := Color; wBmp.canvas.FillRect(Rect(0, 0, wbmp.width, wbmp.height)); if fResizeBtn then begin wrect := BtnRect; if (align in [albottom, alTop]) then begin OffsetRect(wRect, 0, -wRect.Top); for loop := 0 to DotCount - 1 do begin adjust := (loop * DotSize) + 12; wBmp.canvas.pixels[wRect.Left + 1 + adjust, wRect.Top + 1] := clbtnhighlight; wBmp.canvas.pixels[wRect.Left + 2 + adjust, wRect.Top + 1] := clHighlight; wBmp.canvas.pixels[wRect.Left + 1 + adjust, wRect.Top + 2] := clHighlight; wBmp.canvas.pixels[wRect.Left + 2 + adjust, wRect.Top + 2] := clHighlight; if loop < DotCount then begin wBmp.canvas.pixels[wRect.Left + 3 + adjust, wRect.Top + 3] := clbtnhighlight; wBmp.canvas.pixels[wRect.Left + 4 + adjust, wRect.Top + 3] := clHighlight; wBmp.canvas.pixels[wRect.Left + 3 + adjust, wRect.Top + 4] := clHighlight; wBmp.canvas.pixels[wRect.Left + 4 + adjust, wRect.Top + 4] := clHighlight; end; end; wArrow := TBitmap.create; try if fLastOpenSize = 0 then begin if align = altop then wArrow.LoadFromResourceName(Hinstance, 'RMPUPARROW') else wArrow.LoadFromResourceName(Hinstance, 'RMPDNARROW'); end else begin if align = alBottom then wArrow.LoadFromResourceName(Hinstance, 'RMPUPARROW') else wArrow.LoadFromResourceName(Hinstance, 'RMPDNARROW'); end; ReplaceColors(wArrow, Color, clHighLight); wBmp.Canvas.Draw(wRect.Left + 1, wRect.Top + 2, wArrow); wBmp.Canvas.Draw((wRect.Right - 1) - wArrow.width, wRect.Top + 2, wArrow); finally wArrow.free; end; end else if (align in [alLeft, alRight]) then begin OffsetRect(wRect, -wRect.Left, 0); for loop := 0 to DotCount - 1 do begin adjust := (loop * DotSize) + 12; wBmp.canvas.pixels[wRect.Left + 1, wRect.Top + 1 + adjust] := clbtnhighlight; wBmp.canvas.pixels[wRect.Left + 1, wRect.Top + 2 + adjust] := clHighlight; wBmp.canvas.pixels[wRect.Left + 2, wRect.Top + 1 + adjust] := clHighlight; wBmp.canvas.pixels[wRect.Left + 2, wRect.Top + 2 + adjust] := clHighlight; if loop < DotCount then begin wBmp.canvas.pixels[wRect.Left + 3, wRect.Top + 2 + adjust] := clbtnhighlight; wBmp.canvas.pixels[wRect.Left + 3, wRect.Top + 4 + adjust] := clHighlight; wBmp.canvas.pixels[wRect.Left + 4, wRect.Top + 3 + adjust] := clHighlight; wBmp.canvas.pixels[wRect.Left + 4, wRect.Top + 4 + adjust] := clHighlight; end; end; wArrow := TBitmap.create; try if fLastOpenSize = 0 then begin if align = alLeft then wArrow.LoadFromResourceName(Hinstance, 'RMPLTARROW') else wArrow.LoadFromResourceName(Hinstance, 'RMPRTARROW'); end else begin if align = alRight then wArrow.LoadFromResourceName(Hinstance, 'RMPLTARROW') else wArrow.LoadFromResourceName(Hinstance, 'RMPRTARROW'); end; ReplaceColors(wArrow, Color, clHighLight); wBmp.Canvas.Draw(wRect.Left + 2, wRect.Top + 1, wArrow); wBmp.Canvas.Draw(wRect.Left + 2, (wRect.Bottom - 1) - wArrow.Height, wArrow); finally wArrow.free; end; end; if fMouseOverBtn then begin if fBtnDown then Frame3D(wBmp.Canvas, wRect, clbtnshadow, clbtnhighlight, 1) else Frame3D(wBmp.Canvas, wRect, clbtnhighlight, clbtnshadow, 1); end; end; wRect := GripRect; wxpos := 0; wypos := 0; case align of albottom, alright: begin wxpos := 0; wypos := 0; end; alleft : begin wxpos := width-wbmp.width; wypos := 0; end; altop : begin wxpos := 0; wypos := height-wbmp.height; end; end; DC := GetWindowDC(Handle) ; try BitBlt(DC, wxpos, wypos, wBMP.width, wBMP.height, wBMP.Canvas.Handle, 0, 0, SRCCOPY) ; finally ReleaseDC(Handle, DC) ; end; // Canvas.Draw(wRect.Left, wRect.Top, wBmp); finally wBmp.free; end; end; procedure TrmPanel.SetSplitterPanel(const Value: boolean); begin if fSplitterPanel <> Value then begin fSplitterPanel := Value; Realign; Invalidate; end; end; procedure TrmPanel.SetCapPos(const Value: TrmCaptionPosition); begin if fCapPos <> Value then begin fCapPos := Value; Realign; Invalidate; end; end; procedure TrmPanel.SetIBWidth(const Value: integer); begin if fIBWidth <> Value then begin fIBWidth := Value; Realign; invalidate; end; end; procedure TrmPanel.AdjustClientRect(var Rect: TRect); begin inherited AdjustClientRect(Rect); InflateRect(Rect, -fIBWidth, -fIBWidth); end; procedure TrmPanel.CMFontChanged(var Message: TMessage); begin Inherited; Realign; Invalidate; end; procedure TrmPanel.CMParentFontChanged(var Message: TMessage); begin Inherited; Realign; Invalidate; end; procedure TrmPanel.WMNCCalcSize(var Message: TWMNCCalcSize); begin inherited; if SplitterPanel or ResizeBtn then begin with Message.CalcSize_Params^ do begin case align of alTop: rgrc[0].Bottom := rgrc[0].Bottom - GripSize; alBottom: rgrc[0].Top := rgrc[0].Top + GripSize; alLeft: rgrc[0].Right := rgrc[0].Right - GripSize; alRight: rgrc[0].Left := rgrc[0].Left + GripSize; end; end; end; end; procedure TrmPanel.WMNCPaint(var Message: TMessage); begin if SplitterPanel or ResizeBtn then begin PaintGrip; Message.result := 0; end else inherited; end; procedure TrmPanel.WMNCHitTest(var Message: TWMNCHitTest); var wpt: TPoint; begin if csDesigning in ComponentState then begin inherited; exit; end; if SplitterPanel or ResizeBtn then begin wpt := Point(Message.XPos, Message.YPos) ; if resizebtn and ptinrect(Convert(btnrect),wpt) then begin fMouseOverBtn := true; message.result := htCaption; end else begin fMouseOverBtn := false; if splitterpanel and ptinrect(convert(GripRect),wpt) then begin if (fLastOpenSize = 0) then message.result := htClient else Message.Result := htnowhere; end else message.result := htClient end; end else begin fMouseOverBtn := false; inherited; end; end; function TrmPanel.Convert(wRect: TRect): TRect; begin result.topleft := clienttoscreen(wrect.topleft); result.bottomright := clienttoscreen(wrect.bottomright); end; procedure TrmPanel.UpdateSize(X, Y: Integer); begin CalcSplitSize(X, Y, FNewSize, FSplit); end; procedure TrmPanel.CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer); var S: Integer; begin if Align in [alLeft, alRight] then Split := X - FDownPos.X else Split := Y - FDownPos.Y; S := 0; case Align of alLeft: S := Width + Split; alRight: S := Width - Split; alTop: S := Height + Split; alBottom: S := Height - Split; end; NewSize := S; if S < FMinSize then NewSize := FMinSize else if S > FMaxSize then NewSize := FMaxSize; if S <> NewSize then begin if Align in [alRight, alBottom] then S := S - NewSize else S := NewSize - S; Inc(Split, S); end; end; procedure TrmPanel.AllocateLineDC; begin FLineDC := GetDCEx(Parent.Handle, 0, DCX_CACHE or DCX_CLIPSIBLINGS or DCX_LOCKWINDOWUPDATE); if ResizeStyle = rsPattern then begin if FBrush = nil then begin FBrush := TBrush.Create; FBrush.Bitmap := AllocPatternBitmap(clBlack, clWhite); end; FPrevBrush := SelectObject(FLineDC, FBrush.Handle); end; end; procedure TrmPanel.DrawLine; var P: TPoint; h, w: integer; wRect: TRect; begin wRect := GripRect; wRect.TopLeft := Parent.ScreenToClient(Self.ClientToScreen(wRect.TopLeft)); wRect.BottomRight := Parent.ScreenToClient(Self.ClientToScreen(wRect.BottomRight)); FLineVisible := not FLineVisible; case Align of alLeft: begin P.X := wRect.left + FDeltaPos; P.Y := Top; h := height; w := GripSize; end; alRight: begin P.X := left + FDeltaPos; P.Y := Top; h := height; w := GripSize; end; alBottom: begin P.X := 0; P.Y := top + FDeltaPos; h := GripSize; w := width; end; alTop: begin P.X := 0; P.Y := wRect.top + FDeltaPos; h := GripSize; w := width; end; else exit; end; with P do PatBlt(FLineDC, X, Y, W, H, PATINVERT); end; procedure TrmPanel.ReleaseLineDC; begin if FPrevBrush <> 0 then SelectObject(FLineDC, FPrevBrush); ReleaseDC(Parent.Handle, FLineDC); if FBrush <> nil then begin FBrush.Free; FBrush := nil; end; end; procedure TrmPanel.FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then StopSizing else if Assigned(FOldKeyDown) then FOldKeyDown(Sender, Key, Shift); end; procedure TrmPanel.StopSizing; begin if FLineVisible then DrawLine; ReleaseLineDC; if Assigned(FActiveControl) then begin TWinControlAccess(FActiveControl).OnKeyDown := FOldKeyDown; FActiveControl := nil; end; if Assigned(FOnMoved) then FOnMoved(Self); end; function TrmPanel.CanResize(var NewSize: Integer): Boolean; begin Result := True; if not fBtnOpenClose and Assigned(fOnCanResize) then begin fOnCanResize(Self, NewSize, Result); end; end; function TrmPanel.DoCanResize(var NewSize: Integer): Boolean; begin Result := CanResize(NewSize); if Result then NewSize := SetInRange(NewSize, fMinsize, fMaxSize); end; procedure TrmPanel.WMNCLButtonDown(var Message: TWMNCLButtonDown); var wPt: TPoint; wCloseBtn: boolean; begin if csDesigning in ComponentState then begin inherited; exit; end; if ResizeBtn then begin wPt := Point(message.XCursor, message.YCursor); wCloseBtn := (ResizeBtn and PtInRect(convert(BtnRect), wPt)); if wCloseBtn then begin SendCancelMode(Self) ; MouseCapture := true; end; if wCloseBtn then begin fBtnDown := true; PaintGrip; end else begin fBtnDown := false; end; Message.result := 0; end else inherited; end; procedure TrmPanel.WMLButtonUp(var Message: TWMLButtonUp); var wbtndown : boolean; wpt : tpoint; begin if csDesigning in ComponentState then begin inherited; exit; end; wBtnDown := fBtnDown; fBtnDown := false; MouseCapture := false; PaintGrip; wpt := point(message.XPos, Message.YPos); if wBtnDown and ptInRect(btnrect, wpt) then begin fBtnOpenClose := true; try if isClosed then OpenPanel else ClosePanel; finally fBtnOpenClose := false; end; Message.Result := 0; end else inherited; end; procedure TrmPanel.WMNCMouseMove(var Message: TWMNCMouseMove); var wpt : Tpoint; begin if csDesigning in ComponentState then begin inherited; exit; end; inherited; wPt := Point(message.XCursor, message.YCursor); fMouseOverBtn := (ResizeBtn and PtInRect(Convert(BtnRect), wPt)); if SplitterPanel and PtInRect(convert(GripRect), wPt) and not (fMouseOverBtn) and (fLastOpenSize = 0) then begin case align of alTop, alBottom: Cursor := crVSplit; alRight, alLeft: Cursor := crHSplit; else Cursor := crDefault; end; end else Cursor := crDefault; PaintGrip; end; procedure TrmPanel.WMGetMinMaxInfo(var Message: TWMGetMinMaxInfo); begin inherited; if not (csReading in ComponentState) and Fresizing then with Message.MinMaxInfo^.ptMinTrackSize do begin case align of alright, alLeft: begin if x < fMinsize then x := fMinsize; if x < GripSize then x := gripsize; end; alTop, alBottom: begin if y < fMinsize then y := fMinsize; if y < GripSize then y := gripsize; end; end; end; end; procedure TrmPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; wPt: TPoint; wCloseBtn: boolean; begin inherited MouseDown(Button, Shift, X, Y); wPt := Point(x, y); wCloseBtn := (fResizeBtn and PtInRect(BtnRect, wPt)); if SplitterPanel and PtInRect(GripRect, wPt) and not wCloseBtn and (fLastOpenSize = 0) then begin fBtnDown := false; if Button = mbLeft then begin FPanelSizing := true; FDownPos := Point(X, Y); fDeltaPos := 0; if Align in [alLeft, alRight] then begin FMaxSize := Parent.ClientWidth; for I := 0 to Parent.ControlCount - 1 do with Parent.Controls[I] do if Align in [alLeft, alRight] then Dec(FMaxSize, Width); Inc(FMaxSize, Width); end else begin FMaxSize := Parent.ClientHeight; for I := 0 to Parent.ControlCount - 1 do with Parent.Controls[I] do if Align in [alTop, alBottom] then Dec(FMaxSize, Height); Inc(FMaxSize, Height); end; UpdateSize(X, Y); AllocateLineDC; with ValidParentForm(Self) do if ActiveControl <> nil then begin FActiveControl := ActiveControl; FOldKeyDown := TWinControlAccess(FActiveControl).OnKeyDown; TWinControlAccess(FActiveControl).OnKeyDown := FocusKeyDown; end; case align of alright, alleft : FOldSize := width; altop, albottom : FOldSize := height; end; if ResizeStyle in [rsLine, rsPattern] then DrawLine; end; end else if (fResizeBtn and PtInRect(BtnRect, wPt) and (Button = mbLeft)) then begin fBtnDown := true; PaintGrip; end else begin fBtnDown := false; end; end; procedure TrmPanel.MouseMove(Shift: TShiftState; X, Y: Integer); var wPt: TPoint; NewSize, Split: Integer; begin inherited; if (ssLeft in Shift) and FPanelSizing then begin if ResizeStyle = rsUpdate then begin case align of alright, alleft : FOldSize := width; altop, albottom : FOldSize := height; end; case align of alLeft: NewSize := x; alRight: NewSize := width - x; alTop: NewSize := y; alBottom: NewSize := height - y; else exit; end; if (FOldSize <> NewSize) and DoCanResize(NewSize) then begin fNewSize := newsize; UpdateControlSize; end; end else begin CalcSplitSize(X, Y, NewSize, Split); if DoCanResize(NewSize) then begin if ResizeStyle in [rsLine, rsPattern] then DrawLine; FNewSize := NewSize; FSplit := Split; case align of alLeft: fDeltaPos := x - fDownPos.x; alRight: fDeltaPos := x; alTop: fDeltaPos := y - fDownPos.y; alBottom: fDeltaPos := y; else fDeltaPos := 0; end; if ResizeStyle in [rsLine, rsPattern] then DrawLine; end; end; end else begin wPt := Point(x, y); fMouseOverBtn := (fResizeBtn and PtInRect(BtnRect, wPt)); if SplitterPanel and PtInRect(GripRect, wPt) and not (fMouseOverBtn) and (fLastOpenSize = 0) then begin case align of alTop, alBottom: Cursor := crVSplit; alRight, alLeft: Cursor := crHSplit; else Cursor := crDefault; end; end else Cursor := crDefault; PaintGrip end; end; procedure TrmPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var wPt: TPoint; begin inherited; if FPanelSizing then begin fPanelSizing := false; if ResizeStyle in [rsLine, rsPattern] then DrawLine; UpdateControlSize; StopSizing; end else begin wPt := Point(x, y); if fResizeBtn and PtInRect(convert(BtnRect), wPt) and fBtnDown then begin if (fLastOpenSize <> 0) then begin case align of alTop, alBottom: begin if align = alBottom then SetBounds(left,top-flastopensize,width, height+flastopensize) else clientheight := fLastOpenSize; end; alLeft, alRight: begin if align = alRight then SetBounds(left-fLastOpenSize,top,width+fLastOpenSize,height) else clientWidth := fLastOpenSize; end; end; fLastOpenSize := 0; end else begin case align of alTop: begin fLastOpenSize := clientheight; clientheight := 0; end; alBottom: begin Parent.DisableAlign; try fLastOpenSize := clientheight; clientheight := 0; height := GripSize; finally Parent.EnableAlign; end; end; alLeft: begin fLastOpenSize := clientWidth; clientWidth := 0; end; alRight: begin Parent.DisableAlign; try fLastOpenSize := clientWidth; clientWidth := 0; width := GripSize; finally Parent.EnableAlign; end; end; end; Update; end; end; fBtnDown := false; end; end; function TrmPanel.GetClosedState: boolean; begin result := fLastOpenSize <> 0; end; procedure TrmPanel.wmEraseBkgrnd(var Msg: TMessage); begin msg.result := 1; end; procedure TrmPanel.ClosePanel; begin if not isclosed then begin case align of alTop: begin fLastOpenSize := clientheight; clientheight := 0; end; alBottom: begin Parent.DisableAlign; try fLastOpenSize := clientheight; clientheight := 0; if clientheight <> 0 then flastopensize := 0; finally Parent.EnableAlign; end; end; alLeft: begin fLastOpenSize := clientWidth; clientWidth := 0; if clientwidth <> 0 then flastopensize := 0; end; alRight: begin Parent.DisableAlign; try fLastOpenSize := clientWidth; clientWidth := 0; finally Parent.EnableAlign; end; end; end; Realign; end; end; procedure TrmPanel.OpenPanel; begin if IsClosed then begin case align of alTop, alBottom: begin if align = alBottom then SetBounds(left,top-flastopensize,width, height+flastopensize) else clientheight := fLastOpenSize; end; alLeft, alRight: begin if align = alRight then SetBounds(left-fLastOpenSize,top,width+fLastOpenSize,height) else clientWidth := fLastOpenSize; end; end; fLastOpenSize := 0; Realign; end; end; end.
unit Exercicio1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.CheckLst; type TForm1 = class(TForm) Panel1: TPanel; GroupBox1: TGroupBox; Label2: TLabel; edtNome: TEdit; btnInserir: TButton; GroupBox2: TGroupBox; btnRemovePrimeiro: TButton; btnRemoveUltimo: TButton; btnContarNomes: TButton; GroupBox3: TGroupBox; btnExibirNomes: TButton; mmListaNomes: TMemo; procedure btnInserirClick(Sender: TObject); procedure btnExibirNomesClick(Sender: TObject); procedure btnContarNomesClick(Sender: TObject); procedure btnRemovePrimeiroClick(Sender: TObject); procedure btnSairClick(Sender: TObject); private { Private declarations } public constructor Create(AOwner: TComponent); override; { Public declarations } end; TStringArray = array of string; procedure RemoveElemento(var aArray: TStringArray; const aPosicao: integer); var Form1: TForm1; Vetor: array of String; I: Integer; implementation {$R *.dfm} { TForm1 } procedure RemoveElemento(var aArray: TStringArray; const aPosicao: integer); var _j : integer; begin for _j := aPosicao to High(aArray)-1 do begin aArray[_j] := aArray[_j+1]; end; setLength(aArray, high(aArray)-1); end; procedure TForm1.btnContarNomesClick(Sender: TObject); var Resultado : String; begin Resultado := IntToStr(Length(Vetor)); Showmessage('A quantidade de nomes na lista é ' + Resultado); end; procedure TForm1.btnExibirNomesClick(Sender: TObject); var nPercorreArray : Integer; begin mmListaNomes.Clear; for nPercorreArray := 0 to Length(Vetor) -1 do begin mmListaNomes.Lines.Add(Vetor[nPercorreArray]); end; end; procedure TForm1.btnInserirClick(Sender: TObject); begin SetLength(Vetor, I + 1); Vetor[I]:= edtNome.Text; I:= I + 1; end; procedure TForm1.btnRemovePrimeiroClick(Sender: TObject); var _j, _i : integer; begin _i := 0; _j := Low(Vetor); Delete(Vetor, _j, 1); end; procedure TForm1.btnSairClick(Sender: TObject); begin Finalize(Vetor); Close; end; constructor TForm1.Create(AOwner: TComponent); begin Finalize(Vetor); inherited; end; end.
unit DataSet.Model; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, DataSet.Types; type TdmDataSet = class(TDataModule) FDTable1: TFDTable; private { Private declarations } FTableName: string; function GetDataSet: TDataSet; function GetIsOpen: Boolean; procedure SetConnection(const AConnection: TFDConnection); procedure SetTableName(const ATableName: String); public { Public declarations } procedure Open; procedure Close; function GetRows(const AFields: TFieldsToGet): TFieldConverters; procedure AppendRow(const AFields: TFieldConverters); procedure UpdateActiveRow(const AFields: TFieldConverters); procedure Edit; procedure Append; procedure Post; procedure Cancel; procedure Delete; property Connection: TFDConnection write SetConnection; property DataSet: TDataSet read GetDataSet; property TableName: string read FTableName write SetTableName; property IsOpen: Boolean read GetIsOpen; end; var dmDataSet: TdmDataSet; implementation uses Spring, MVVM.Core; {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} { TdmCoches } procedure TdmDataSet.Append; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for Append'); FDTable1.Append end; procedure TdmDataSet.AppendRow(const AFields: TFieldConverters); var I: Integer; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for AppendRow'); FDTable1.Append; try for I := Low(AFields) to High(AFields) do begin FDTable1.FieldByName(AFields[I].FieldName).AssignValue(AFields[I].FieldValue.AsVarRec); end; FDTable1.Post; except on E: Exception do begin FDTable1.Cancel; raise; end; end; end; procedure TdmDataSet.Cancel; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsEdit, TDataSetState.dsInsert], 'Wrong state for Cancel'); FDTable1.Cancel; end; procedure TdmDataSet.Close; begin FDTable1.Active := False; end; procedure TdmDataSet.Delete; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for Delete'); FDTable1.Delete end; procedure TdmDataSet.Edit; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsEdit, TDataSetState.dsInsert], 'Wrong state for Edit'); FDTable1.Edit; end; function TdmDataSet.GetDataSet: TDataSet; begin Result := FDTable1 end; function TdmDataSet.GetIsOpen: Boolean; begin Result := FDTable1.Active end; function TdmDataSet.GetRows(const AFields: TFieldsToGet): TFieldConverters; var I: Integer; LObject: TObject; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for GetRows'); for I := Low(AFields) to High(AFields) do begin case FDTable1.FieldByName(AFields[I].FieldName).DataType of ftGuid: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsGuid); ftString, ftFixedChar, ftWideString, ftFixedWideChar: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsString); ftAutoInc, ftInteger: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftLongWord: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsLongWord); ftShortint: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftByte: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftSmallInt: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftWord: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftBoolean: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsBoolean); ftFloat, ftCurrency: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsFloat); ftMemo, ftWideMemo: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsWideString); ftBlob: begin if AFields[I].isBitmap then begin LObject := MVVMCore.PlatformServices.LoadBitmap(DataSet.FieldByName(AFields[I].FieldName).AsBytes); Result.AddData(AFields[I].FieldName, LObject); end else Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsWideString); end; ftInterface: begin // end; ftIDispatch: begin // end; ftGraphic: // por validar begin LObject := MVVMCore.PlatformServices.LoadBitmap(DataSet.FieldByName(AFields[I].FieldName).AsBytes); Result.AddData(AFields[I].FieldName, LObject); end; ftVariant: Result.AddData(AFields[I].FieldName, TValue.FromVariant(FDTable1.FieldByName(AFields[I].FieldName).AsVariant)); ftDate, ftTime, ftDateTime: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsDateTime); ftFMTBCD: begin // end; ftBCD: begin // end; ftBytes, ftVarBytes: begin // end; ftLargeInt: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsLargeInt); end; end; end; procedure TdmDataSet.Open; begin FDTable1.Active := True; end; procedure TdmDataSet.Post; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsEdit, TDataSetState.dsInsert], 'Wrong state for post'); FDTable1.Post; end; procedure TdmDataSet.SetConnection(const AConnection: TFDConnection); begin FDTable1.Connection := AConnection; end; procedure TdmDataSet.SetTableName(const ATableName: String); var LWasOpen: Boolean; begin if FTableName <> ATableName then begin LWasOpen := IsOpen; if LWasOpen then Close; FTableName := ATableName; FDTable1.TableName := FTableName; if LWasOpen then Open; end; end; procedure TdmDataSet.UpdateActiveRow(const AFields: TFieldConverters); var I: Integer; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for UpdateActiveRow'); FDTable1.Edit; try for I := Low(AFields) to High(AFields) do begin FDTable1.FieldByName(AFields[I].FieldName).AssignValue(AFields[I].FieldValue.AsVarRec); end; FDTable1.Post; except on E: Exception do begin FDTable1.Cancel; raise; end; end; end; end.
unit uSprJoin; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, StdCtrls, Grids, DBGrids, StrUtils, ImgList; type TsprJoin = class(TObject) private FTable: string; FKind: string; FFieldLeft: string; FFieldRight: string; FOptions: string; public constructor Create; procedure Clear; procedure ProcessField(Field: TField; ProcessStr: string; JoinAlias: string; var ResultFieldName: string); property Table: string read FTable write FTable; property Kind: string read FKind write FKind; property FieldLeft: string read FFieldLeft write FFieldLeft; property FieldRight: string read FFieldRight write FFieldRight; property Options: string read FOptions write FOptions; end; implementation constructor TsprJoin.Create; begin inherited; Clear; end; procedure TsprJoin.Clear; begin FTable := ''; FKind := ''; FFieldLeft := ''; FFieldRight := ''; FOptions := 'with (nolock)'; end; procedure TsprJoin.ProcessField(Field: TField; ProcessStr: string; JoinAlias: string; var ResultFieldName: string); var L: TStringList; vDS: TDataSet; I: Integer; begin if not Assigned(Field) then Exit; vDS := Field.DataSet; if Field.FieldKind = fkLookup then begin L := TStringList.Create; try L.CommaText := ProcessStr; if L.Count = 1 then begin ResultFieldName := ProcessStr; Self.Clear; end else if L.Count >= 3 then begin Self.Table := L.Strings[0]; Self.FieldLeft := L.Strings[1]; if L.Count > 3 then Self.Kind := L.Strings[3] else Self.Kind := 'left'; if L.Count > 4 then begin Self.Options := ''; for I := 4 to L.Count - 1 do Self.Options := Self.Options + L.Strings[I]; end; Self.FieldRight := vDS.FieldByName(Field.KeyFields).Origin; ResultFieldName := JoinAlias + '.' + L.Strings[2]; end; finally L.Free; end; end else begin ResultFieldName := ProcessStr; Self.Clear; end; end; end.
unit u_Main; interface uses System.SysUtils, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLScene, GLVectorFileObjects, GLCadencer, GLObjects, GLCoordinates, GLVectorGeometry, GLFileOBJ, u_Graph; type TRaycastForm = class(TForm) GLScene1: TGLScene; vp: TGLSceneViewer; cam: TGLCamera; dc: TGLDummyCube; ff: TGLFreeForm; pts: TGLPoints; cad: TGLCadencer; Panel1: TPanel; Image1: TImage; Image5: TImage; fps_lbl: TLabel; ray1: TSpeedButton; ray2: TSpeedButton; Label1: TLabel; procedure cadProgress(Sender: TObject; const deltaTime, newTime: Double); procedure FormCreate(Sender: TObject); procedure ray1Click(Sender: TObject); private graph: c_FPSGraph; end; const ray_cnt = 4000; ray_start: TVector = (X: 0; Y: 2.5; Z: 0; W: 0); var RaycastForm: TRaycastForm; //==================================================================== implementation //==================================================================== {$R *.dfm} procedure TRaycastForm.FormCreate; begin clientWidth := 1024; clientHeight := 512 + 48; ff.LoadFromFile('scn.obj'); ff.Scale.Scale(4 / ff.BoundingSphereRadius); ff.BuildOctree(2); graph := c_FPSGraph.CreateAsChild(GLScene1.Objects); graph.interval := 25; Panel1.DoubleBuffered := true; ray1Click(ray1); end; procedure TRaycastForm.cadProgress; begin dc.Turn(-deltaTime * 10); fps_lbl.Caption := format('%.2f', [graph.fps]); end; procedure TRaycastForm.ray1Click; var i: integer; v: TVector; begin pts.Positions.Clear; for i := 1 to ray_cnt do begin SetVector(v, dc.LocalToAbsolute(VectorSubtract(VectorMake(random * 8 - 3, -2, random * 8 - 4), ray_start))); if Sender = ray1 then begin if ff.RayCastIntersect(ray_start, v, @v) then pts.Positions.Add(dc.AbsoluteToLocal(v)); end else if ff.OctreeRayCastIntersect(ray_start, v, @v) then pts.Positions.Add(dc.AbsoluteToLocal(v)); end; end; end.
// Информация о версии (Version Info) // Автор Rick Peterson // //////////////////////////////////////////////////// unit sysSHVersionInfo; interface uses Windows,TypInfo; type {$M+} TVersionType=(vtCompanyName, vtFileDescription, vtFileVersion, vtInternalName, vtLegalCopyright,vtLegalTradeMark, vtOriginalFileName, vtProductName, vtProductVersion, vtComments); {$M-} TVersionInfo = class private FVersionInfo : Array [0 .. ord(high(TVersionType))] of string; FModuleName : string; protected function GetCompanyName: string; function GetFileDescription: string; function GetFileVersion: string; function GetInternalName: string; function GetLegalCopyright: string; function GetLegalTradeMark: string; function GetOriginalFileName: string; function GetProductName: string; function GetProductVersion: string; function GetComments: string; function GetVersionInfo(VersionType: TVersionType): string; virtual; procedure SetVersionInfo; virtual; public constructor Create(const AModuleName : string); destructor Destroy ; override; published property CompanyName: string read GetCompanyName; property FileDescription: string read GetFileDescription; property FileVersion: string read GetFileVersion; property InternalName: string read GetInternalName; property LegalCopyright: string read GetLegalCopyright; property LegalTradeMark: string read GetLegalTradeMark; property OriginalFileName: string read GetOriginalFileName; property ProductName: string read GetProductName; property ProductVersion: string read GetProductVersion; property Comments: string read GetComments; end; function VersionString(const ModuleName:string):string; implementation function VersionString(const ModuleName:string):string; var vi:TVersionInfo; begin vi:=TVersionInfo.Create(ModuleName); try Result:=vi.FileVersion; finally vi.Free end; end; constructor TVersionInfo.Create(const AModuleName : string); begin inherited Create; FModuleName:=AModuleName; SetVersionInfo; end; function TVersionInfo.GetCompanyName: string; begin Result := GeTVersionInfo(vtCompanyName); end; function TVersionInfo.GetFileDescription: string; begin Result := GeTVersionInfo(vtFileDescription); end; function TVersionInfo.GetFileVersion: string; begin Result := GeTVersionInfo(vtFileVersion); end; function TVersionInfo.GetInternalName: string; begin Result := GeTVersionInfo(vtInternalName); end; function TVersionInfo.GetLegalCopyright: string; begin Result := GeTVersionInfo(vtLegalCopyright); end; function TVersionInfo.GetLegalTradeMark: string; begin Result := GeTVersionInfo(vtLegalTradeMark); end; function TVersionInfo.GetOriginalFileName: string; begin Result := GeTVersionInfo(vtOriginalFileName); end; function TVersionInfo.GetProductName: string; begin Result := GeTVersionInfo(vtProductName); end; function TVersionInfo.GetProductVersion: string; begin Result := GeTVersionInfo(vtProductVersion); end; function TVersionInfo.GetComments: string; begin Result := GeTVersionInfo(vtComments); end; function TVersionInfo.GeTVersionInfo(VersionType: TVersionType): string; begin Result := FVersionInfo[ord(VersionType)]; end; function _LangToHexStr(pbyteArray: PByte) : string; Const HexChars : array [0..15] of char = '0123456789ABCDEF'; begin Result:=''; inc(pbyteArray); Result := Result + HexChars[pbyteArray^ shr 4] + HexChars[pbyteArray^ and 15]; dec(pbyteArray); Result := Result + HexChars[pbyteArray^ shr 4] + HexChars[pbyteArray^ and 15]; inc(pbyteArray,3); Result := Result + HexChars[pbyteArray^ shr 4] + HexChars[pbyteArray^ and 15]; dec(pbyteArray); Result := Result + HexChars[pbyteArray^ shr 4] + HexChars[pbyteArray^ and 15]; end; procedure TVersionInfo.SeTVersionInfo; var sVersionType : string; iAppSize, iLenOfValue, i: DWORD; pcValue: PChar; lang : string; pcBuf:PChar; FileName: string; begin FileName := FModuleName; UniqueString(FileName); iAppSize:=GetFileVersionInfoSize(PChar(FileName),iAppSize); if iAppSize > 0 then begin GetMem(pcBuf,iAppSize); try GetFileVersionInfo(PChar(FModuleName),0,iAppSize,pcBuf); pcValue:=nil; if VerQueryValue(pcBuf,PChar('VarFileInfo\Translation'), Pointer(pcValue),iLenOfValue) then lang:= _LangToHexStr(PByte(pcValue)) else lang:='040904E4'; // Us English // Version Info for i := 0 to Ord(High(TVersionType)) do begin sVersionType := GetEnumName(TypeInfo(TVersionType),i); sVersionType := Copy(sVersionType,3,length(sVersionType)); if VerQueryValue(pcBuf,PChar('StringFileInfo\'+lang+'\'+sVersionType), Pointer(pcValue),iLenOfValue) then begin FVersionInfo[i] :=pcValue; end; end; finally FreeMem(pcBuf) end; end; end; destructor TVersionInfo.Destroy; begin Finalize(FVersionInfo); inherited; end; initialization finalization end.
unit frmModifyCarNoAndLocationNo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TModifyCarNoAndLocationNoForm = class(TForm) lbl1: TLabel; edt1: TEdit; lbl2: TLabel; edt2: TEdit; btn1: TBitBtn; btn2: TBitBtn; procedure btn2Click(Sender: TObject); procedure btn1Click(Sender: TObject); private { Private declarations } FCarNo: string; FLocationNo: String; public { Public declarations } procedure Init(CarNo: String); procedure Clear(); property CarNo :String read FCarNo write FCarNo; property LocationNo :String read FLocationNo write FLocationNo; end; var ModifyCarNoAndLocationNoForm: TModifyCarNoAndLocationNoForm; implementation {$R *.dfm} procedure TModifyCarNoAndLocationNoForm.btn2Click(Sender: TObject); begin Close; end; procedure TModifyCarNoAndLocationNoForm.btn1Click(Sender: TObject); begin FCarNo:= Trim(edt1.Text); FLocationNo:= Trim(edt2.Text); ModalResult:= mrOk; end; procedure TModifyCarNoAndLocationNoForm.Init(CarNo: String); begin edt1.Text:= CarNo; end; procedure TModifyCarNoAndLocationNoForm.Clear; begin edt1.Text:= ''; edt2.Text:= ''; end; end.
unit Horse.Compression; interface uses Horse, System.Classes, System.ZLib, Horse.Compression.Types, System.SysUtils, Web.HTTPApp, System.JSON; const COMPRESSION_THRESHOLD = 1024; procedure Middleware(Req: THorseRequest; Res: THorseResponse; Next: TProc); function Compression(const ACompressionThreshold: Integer = COMPRESSION_THRESHOLD): THorseCallback; implementation var CompressionThreshold: Integer; function Compression(const ACompressionThreshold: Integer = COMPRESSION_THRESHOLD): THorseCallback; begin CompressionThreshold := ACompressionThreshold; Result := Middleware; end; procedure Middleware(Req: THorseRequest; Res: THorseResponse; Next: TProc); const ACCEPT_ENCODING = 'accept-encoding'; var LMemoryStream: TMemoryStream; LAcceptEncoding: string; LZStream: TZCompressionStream; LResponseCompressionType: THorseCompressionType; LWebResponse: TWebResponse; LContent: TObject; begin Next; LContent := THorseHackResponse(Res).GetContent; if (not Assigned(LContent)) or (not LContent.InheritsFrom(TJSONValue)) then Exit; LAcceptEncoding := Req.Headers[ACCEPT_ENCODING]; if LAcceptEncoding.Trim.IsEmpty then Exit; LAcceptEncoding := LAcceptEncoding.ToLower; if Pos(THorseCompressionType.GZIP.ToString, LAcceptEncoding) > 0 then LResponseCompressionType := THorseCompressionType.GZIP else if Pos(THorseCompressionType.DEFLATE.ToString, LAcceptEncoding) > 0 then LResponseCompressionType := THorseCompressionType.DEFLATE else Exit; LWebResponse := THorseHackResponse(Res).GetWebResponse; LWebResponse.ContentStream := TStringStream.Create(TJSONValue(LContent).ToJSON); if LWebResponse.ContentStream.Size <= CompressionThreshold then Exit; LMemoryStream := TMemoryStream.Create; try LWebResponse.ContentStream.Position := 0; LZStream := TZCompressionStream.Create(LMemoryStream, TZCompressionLevel.zcMax, LResponseCompressionType.WindowsBits); try LZStream.CopyFrom(LWebResponse.ContentStream, 0); finally LZStream.Free; end; LMemoryStream.Position := 0; LWebResponse.Content := EmptyStr; LWebResponse.ContentStream.Size := 0; LWebResponse.ContentStream.CopyFrom(LMemoryStream, 0); LWebResponse.ContentEncoding := LResponseCompressionType.ToString; finally LMemoryStream.Free; end; end; end.
unit Serialialize.JSON.Interfaces; interface uses System.Generics.Collections; type ISerialize<T: Class> = interface ['{E688C149-C82E-4E21-8FB3-110E41248E47}'] function ObjectToJsonArray(AObject: TObjectList<T>): String; end; IJSON<T: Class> = interface ['{888E35D0-04B9-42BE-B953-987E98A3A6BB}'] function Add(AJsonObjct: String): IJSON<T>; overload; function Add(AJsonObjct: T): IJSON<T>; overload; function JsonArray: String; end; implementation end.
(* Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED Original name: 0079.PAS Description: Loan Amortization Tables Author: GAYLE DAVIS Date: 01-27-94 17:29 *) program Amortization_Table; Uses Crt; var Month : 1..12; Starting_Month : 1..12; Balance : real; Payment : real; Interest_Rate : real; Annual_Accum_Interest : real; Year : integer; Number_Of_Years : integer; Original_Loan : real; procedure Calculate_Payment; (* **************** calculate payment *) var Temp : real; Index : integer; begin Temp := 1.0; for Index := 1 to 12*Number_Of_Years do Temp := Temp * (1.0 + Interest_Rate); Payment := Original_Loan*Interest_Rate/(1.0 - 1.0/Temp); end; procedure Initialize_Data; (* ******************** initialize data *) begin Writeln(' Pascal amortization program'); Writeln; Write('Enter amount borrowed '); Readln(Original_Loan); Balance := Original_Loan; Write('Enter interest rate as percentage (i.e. 13.5) '); Readln(Interest_Rate); Interest_Rate := Interest_Rate/1200.0; Write('Enter number of years of payoff '); Readln(Number_Of_Years); Write('Enter month of first payment (i.e. 5 for May) '); Readln(Starting_Month); Write('Enter year of first payment (i.e. 1994) '); Readln(Year); Calculate_Payment; Annual_Accum_Interest := 0.0; (* This is to accumulate Interest *) end; procedure Print_Annual_Header; (* ************ print annual header *) begin Writeln; Writeln; Writeln('Original loan amount = ',Original_Loan:10:2, ' Interest rate = ',1200.0*Interest_Rate:6:2,'%'); Writeln; Writeln('Month payment interest princ balance'); Writeln; end; procedure Calculate_And_Print; (* ************ calculate and print *) var Interest_Payment : real; Principal_Payment : real; begin if Balance > 0.0 then begin Interest_Payment := Interest_Rate * Balance; Principal_Payment := Payment - Interest_Payment; if Principal_Payment > Balance then begin (* loan payed off *) Principal_Payment := Balance; (* this month *) Payment := Principal_Payment + Interest_Payment; Balance := 0.0; end else begin (* regular monthly payment *) Balance := Balance - Principal_Payment; end; Annual_Accum_Interest := Annual_Accum_Interest+Interest_Payment; Writeln(Month:5,Payment:10:2,Interest_Payment:10:2, Principal_Payment:10:2,Balance:10:2); end; (* of if Balance > 0.0 then *) end; procedure Print_Annual_Summary; (* ********** print annual summary *) begin Writeln; Writeln('Total interest for ',Year:5,' = ', Annual_Accum_Interest:10:2); Writeln; Annual_Accum_Interest := 0.0; Year := Year + 1; end; begin (* ******************************************* main program *) Clrscr; Initialize_Data; repeat Print_Annual_Header; for Month := Starting_Month to 12 do begin Calculate_And_Print; end; Print_Annual_Summary; Starting_Month := 1; until Balance <= 0.0; end. (* of main program *)
unit ThSelect; interface uses SysUtils, Windows, Types, Classes, Controls, Graphics, StdCtrls, ThInterfaces, ThTag, ThHeaderComponent, ThWebControl, ThTextPaint, ThListSource; type TThCustomSelect = class(TThWebControl, IThFormInput) private FListBox: TListBox; FComboBox: TComboBox; FRows: Integer; FItems: TStringList; FItemIndex: Integer; protected FSource: IThListSource; function GetOptionsHtml: string; function GetSource: IThListSource; virtual; procedure SetItemIndex(const Value: Integer); procedure SetItems(const Value: TStringList); procedure SetRows(const Value: Integer); virtual; procedure SetSource(const Value: IThListSource); protected procedure AddSourceNotifier; procedure CreateComboBox; procedure CreateListBox; procedure ItemsChanged(inSender: TObject = nil); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure PerformAutoSize; override; procedure RemoveSourceNotifier; procedure SourceChanged(inSender: TObject); procedure SourceRemoved; virtual; procedure Tag(inTag: TThTag); override; function ValidatedItemIndex(inList: TStrings): Integer; protected property ItemIndex: Integer read FItemIndex write SetItemIndex; property Items: TStringList read FItems write SetItems; property Rows: Integer read FRows write SetRows; property Source: IThListSource read GetSource write SetSource; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateItems; //function GetCellAttributes: string; override; end; // TThSelect = class(TThCustomSelect) public constructor Create(AOwner: TComponent); override; published property Align; property AutoSize default true; property ItemIndex; property Items; property Source; property Style; property StyleClass; property Visible; end; // TThListBox = class(TThCustomSelect) public constructor Create(AOwner: TComponent); override; published property Align; property AutoSize default true; property ItemIndex; property Items; property Rows; property Source; property Style; property StyleClass; property Visible; end; implementation { TThCustomSelect } constructor TThCustomSelect.Create(AOwner: TComponent); begin inherited; FAutoSize := true; FItems := TStringList.Create; FItems.OnChange := ItemsChanged; CtrlStyle.Font.DefaultFontFamily := 'MS Sans Serif'; CtrlStyle.Font.DefaultFontPx := 14; BuildStyle; end; destructor TThCustomSelect.Destroy; begin RemoveSourceNotifier; FComboBox.Free; FListBox.Free; FItems.Free; inherited; end; procedure TThCustomSelect.RemoveSourceNotifier; begin if (Source <> nil) then Source.Notifiers.Remove(SourceChanged); end; procedure TThCustomSelect.AddSourceNotifier; begin if (Source <> nil) then Source.Notifiers.Add(SourceChanged); end; procedure TThCustomSelect.PerformAutoSize; const Margin = 8; begin if FComboBox <> nil then Height := FComboBox.Height + CtrlStyle.GetBoxHeightMargin else if FListBox <> nil then Height := FListBox.ItemHeight * Rows + Margin + CtrlStyle.GetBoxHeightMargin; end; procedure TThCustomSelect.CreateComboBox; begin FreeAndNil(FListBox); FComboBox := TComboBox.Create(Self); with FComboBox do begin Parent := Self; Align := alClient; end; end; procedure TThCustomSelect.CreateListBox; begin FreeAndNil(FComboBox); FListBox := TListBox.Create(Self); with FListBox do begin Parent := Self; Align := alClient; end; end; function TThCustomSelect.ValidatedItemIndex(inList: TStrings): Integer; begin if ItemIndex < inList.Count then Result := ItemIndex else if inList.Count = 0 then Result := -1 else Result := 0; end; procedure TThCustomSelect.ItemsChanged(inSender: TObject); begin if FListBox <> nil then begin FListBox.Items.Assign(Items); FListBox.ItemIndex := ValidatedItemIndex(FListBox.Items); end else if FComboBox <> nil then begin FComboBox.Items.Assign(Items); FComboBox.ItemIndex := ValidatedItemIndex(FComboBox.Items); end; end; procedure TThCustomSelect.SetItems(const Value: TStringList); begin FItems.Assign(Value); ItemsChanged; end; procedure TThCustomSelect.SetRows(const Value: Integer); begin { if (FRows = 0) and (Value > 0) then CreateListBox else if (FRows > 0) and (Value = 0) then CreateComboBox; } if Value > 0 then begin FRows := Value; ItemsChanged; AdjustSize; end; end; function TThCustomSelect.GetOptionsHtml: string; var i: Integer; s: string; begin Result := ''; for i := 0 to Pred(Items.Count) do begin if ItemIndex = i then s := ' selected="selected"' else s := ''; Result := Result + Format('<option%s>%s</option>', [ s, Items[i] ]); end; end; procedure TThCustomSelect.Tag(inTag: TThTag); begin inherited; with inTag do begin Element := 'select'; Content := GetOptionsHtml; if Rows > 0 then Add('size', Rows); AddStyle('width', '100%'); AddStyle('height', '100%'); //CtrlStyle.Font.ListStyles(Styles); //AddStyle('width', Width, 'px'); //AddStyle('height', Height, 'px'); //AddStyle('height', AdjustedClientHeight, 'px'); end; end; procedure TThCustomSelect.SetItemIndex(const Value: Integer); begin FItemIndex := Value; ItemsChanged; end; procedure TThCustomSelect.UpdateItems; begin if Source <> nil then Items.Assign(Source.Items) else Items.Clear; end; procedure TThCustomSelect.SetSource(const Value: IThListSource); begin if Source <> Value then begin if (Source <> nil) then begin ReferenceInterface(FSource, opRemove); //Source.RemoveFreeNotification(Self); RemoveSourceNotifier; end; FSource := Value; if (Source <> nil) then begin ReferenceInterface(FSource, opInsert); //Source.FreeNotification(Self); AddSourceNotifier; UpdateItems; end; end; end; procedure TThCustomSelect.SourceRemoved; begin FSource := nil; UpdateItems; end; procedure TThCustomSelect.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; // if (Operation = opRemove) and (AComponent = FSource) then // FSource := nil; if (Operation = opRemove) and Assigned(Source) and AComponent.IsImplementorOf(Source) then SourceRemoved; end; procedure TThCustomSelect.SourceChanged(inSender: TObject); begin UpdateItems; end; function TThCustomSelect.GetSource: IThListSource; begin Result := FSource; end; { TThSelect } constructor TThSelect.Create(AOwner: TComponent); begin inherited; CreateComboBox; end; { TThListBox } constructor TThListBox.Create(AOwner: TComponent); begin inherited; FRows := 8; CreateListBox; end; end.
(* WC_ADS 23.04.2017 *) (* Container for strings *) UNIT WC_ADS; INTERFACE FUNCTION IsEmpty: BOOLEAN; FUNCTION Contains(s: STRING): BOOLEAN; PROCEDURE Insert(s: STRING); PROCEDURE Remove(s: STRING); PROCEDURE DisposeTree(); IMPLEMENTATION TYPE Node = ^NodeRec; NodeRec = RECORD data: STRING; left, right: Node; END; VAR Tree : Node; PROCEDURE InitTree; BEGIN Tree := NIL; END; FUNCTION NewNode (data: STRING): Node; VAR n: Node; BEGIN New(n); n^.data := data; n^.left := NIL; n^.right := NIL; NewNode := n; END; (* Check if binsearchtree is empty *) FUNCTION IsEmpty: BOOLEAN; BEGIN IsEmpty := Tree = NIL; END; (* check if binsearchtree contains string recursive *) FUNCTION ContainsRec(VAR t: Node; s: STRING): BOOLEAN; BEGIN IF t = NIL THEN BEGIN ContainsRec := FALSE; END ELSE IF t^.data = s THEN ContainsRec := TRUE ELSE IF s < t^.data THEN BEGIN ContainsRec := ContainsRec(t^.left, s); END ELSE BEGIN ContainsRec := ContainsRec(t^.right, s); END; END; (* check if binsearchtree contains string Uses a help function *) FUNCTION Contains(s: STRING): BOOLEAN; BEGIN Contains := ContainsRec(Tree, s); END; (* Insert in binsearchtree recursive *) PROCEDURE InsertRec (VAR t: Node; n: Node); BEGIN IF t = NIL THEN BEGIN t := n; END ELSE BEGIN IF (n^.data = t^.data) THEN Exit ELSE IF n^.data < t^.data THEN InsertRec(t^.left, n) ELSE InsertRec(t^.right, n) END; END; (* Insert a string in binsearchtree Uses a help function *) PROCEDURE Insert (s : String); BEGIN InsertRec(Tree, NewNode(s)); END; (* Remove a string from binsearchtree *) PROCEDURE Remove(s: STRING); VAR n, nPar: Node; st: Node; (*subtree*) succ, succPar: Node; BEGIN nPar := NIL; n := Tree; WHILE (n <> NIL) AND (n^.data <> s) DO BEGIN nPar := n; IF s < n^.data THEN n := n^.left ELSE n := n^.right; END; IF n <> NIL THEN BEGIN (* no right subtree *) IF n^.right = NIL THEN BEGIN st := n^.left; END ELSE BEGIN IF n^.right^.left = NIL THEN BEGIN (* right subtree, but no left subtree *) st := n^.right; st^.left := n^.left; END ELSE BEGIN (*common case*) succPar := NIL; succ := n^.right; WHILE succ^.left <> NIL DO BEGIN succPar := succ; succ := succ^.left; END; succPar^.left := succ^.right; st := succ; st^.left := n^.left; st^.right := n^.right; END; END; (* insert the new sub-tree *) IF nPar = NIL THEN Tree := st ELSE IF n^.data < nPar^.data THEN nPar^.left := st ELSE nPar^.right := st; Dispose(n); END; (* n <> NIL *) END; (* Removes all the elements from the binary search tree recursive *) PROCEDURE DisposeTree_rec(VAR Tree : Node); BEGIN IF Tree <> NIL THEN BEGIN (* Traverse the left subtree in postorder. *) DisposeTree_rec (Tree^.Left); (* Traverse the right subtree in postorder. *) DisposeTree_rec (Tree^.Right); (* Delete this leaf node from the tree. *) Dispose (Tree); END END; (* Removes all the elements from the binary search tree calls rec. function *) PROCEDURE DisposeTree(); BEGIN DisposeTree_rec(Tree); END; BEGIN InitTree; END.
unit Demo.DiffChart.Pie; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_DiffChart_Pie = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_DiffChart_Pie.GenerateChart; var OldData: IcfsGChartData; NewData: IcfsGChartData; ChartBefore: IcfsGChartProducer; ChartAfter: IcfsGChartProducer; ChartDiff: IcfsGChartProducer; begin // Old Data OldData := TcfsGChartData.Create; OldData.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Major'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Degrees') ]); OldData.AddRow(['Business', 256070]); OldData.AddRow(['Education', 108034]); OldData.AddRow(['Social Sciences & History', 127101]); OldData.AddRow(['Health', 81863]); OldData.AddRow(['Psychology', 74194]); // New Data NewData := TcfsGChartData.Create; NewData.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Major'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Degrees') ]); NewData.AddRow(['Business', 358293]); NewData.AddRow(['Education', 101265]); NewData.AddRow(['Social Sciences & History', 172780]); NewData.AddRow(['Health', 129634]); NewData.AddRow(['Psychology', 97216]); // Chart Before ChartBefore := TcfsGChartProducer.Create; ChartBefore.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; ChartBefore.Data.Assign(OldData); ChartBefore.Options.Title('2000'); ChartBefore.Options.PieSliceText('none'); // Chart After ChartAfter := TcfsGChartProducer.Create; ChartAfter.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; ChartAfter.Data.Assign(NewData); ChartAfter.Options.Title('2010'); ChartAfter.Options.PieSliceText('none'); // Chart Diff ChartDiff := TcfsGChartProducer.Create; ChartDiff.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; ChartDiff.OldData.Assign(OldData); ChartDiff.Data.Assign(NewData); ChartDiff.Options.Title('Popularity of the top five U.S. college majors between 2000 and 2010'); ChartDiff.Options.PieSliceText('none'); //ChartDiff.Options.Diff('innerCircle', '{ radiusFactor: 0.3 }'); ChartDiff.Options.Diff('innerCircle', '{ borderFactor: 0.08 }'); //ChartDiff.Options.Diff('oldData', '{opacity: 0.15}'); //ChartDiff.Options.Diff('oldData', '{inCenter: false}'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="display: flex; width: 100%; height: 50%;">' + '<div id="ChartBefore" style="width: 50%"></div>' + '<div id="ChartAfter" style="flex-grow: 1;"></div>' + '</div>' + '<div style="display: flex; width: 100%; height: 50%;">' + '<div id="ChartDiff" style="width: 100%"></div>' + '</div>' ); GChartsFrame.DocumentGenerate('ChartBefore', ChartBefore); GChartsFrame.DocumentGenerate('ChartAfter', ChartAfter); GChartsFrame.DocumentGenerate('ChartDiff', ChartDiff); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_DiffChart_Pie); end.
unit UDWindowButtonBar; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, UCrpe32; type TCrpeWindowButtonBarDlg = class(TForm) pnlWindowButtonBar: TPanel; cbVisible: TCheckBox; cbCancelBtn: TCheckBox; cbCloseBtn: TCheckBox; cbRefreshBtn: TCheckBox; cbZoomCtl: TCheckBox; cbPrintBtn: TCheckBox; cbPrintSetupBtn: TCheckBox; cbExportBtn: TCheckBox; cbSearchBtn: TCheckBox; cbAllowDrillDown: TCheckBox; cbGroupTree: TCheckBox; cbNavigationCtls: TCheckBox; cbProgressCtls: TCheckBox; btnOk: TButton; btnCancel: TButton; btnClear: TButton; cbDocumentTips: TCheckBox; cbToolbarTips: TCheckBox; btnActivateAll: TButton; cbLaunchBtn: TCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure UpdateWindowButtonBar; procedure cbVisibleClick(Sender: TObject); procedure cbCancelBtnClick(Sender: TObject); procedure cbCloseBtnClick(Sender: TObject); procedure cbRefreshBtnClick(Sender: TObject); procedure cbZoomCtlClick(Sender: TObject); procedure cbPrintBtnClick(Sender: TObject); procedure cbPrintSetupBtnClick(Sender: TObject); procedure cbExportBtnClick(Sender: TObject); procedure cbSearchBtnClick(Sender: TObject); procedure cbAllowDrillDownClick(Sender: TObject); procedure cbGroupTreeClick(Sender: TObject); procedure cbNavigationCtlsClick(Sender: TObject); procedure cbProgressCtlsClick(Sender: TObject); procedure cbToolbarTipsClick(Sender: TObject); procedure cbDocumentTipsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnActivateAllClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure cbLaunchBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; rVisible : boolean; rCancel : boolean; rClose : boolean; rRefresh : boolean; rZoom : boolean; rPrint : boolean; rPrintSetup : boolean; rExport : boolean; rLaunch : boolean; rSearch : boolean; rAllowDrillDown : boolean; rGroupTree : boolean; rNavigation : boolean; rProgress : boolean; rToolbarTips : boolean; rDocumentTips : boolean; end; var CrpeWindowButtonBarDlg: TCrpeWindowButtonBarDlg; bWindowButtonBar : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.FormCreate(Sender: TObject); begin bWindowButtonBar := True; LoadFormPos(Self); btnOk.Tag := 1; btnCancel.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.FormShow(Sender: TObject); begin rVisible := Cr.WindowButtonBar.Visible; rCancel := Cr.WindowButtonBar.CancelBtn; rClose := Cr.WindowButtonBar.CloseBtn; rRefresh := Cr.WindowButtonBar.RefreshBtn; rZoom := Cr.WindowButtonBar.ZoomCtl; rPrint := Cr.WindowButtonBar.PrintBtn; rPrintSetup := Cr.WindowButtonBar.PrintSetupBtn; rExport := Cr.WindowButtonBar.ExportBtn; rLaunch := Cr.WindowButtonBar.LaunchBtn; rSearch := Cr.WindowButtonBar.SearchBtn; rAllowDrillDown := Cr.WindowButtonBar.AllowDrillDown; rGroupTree := Cr.WindowButtonBar.GroupTree; rNavigation := Cr.WindowButtonBar.NavigationCtls; rProgress := Cr.WindowButtonBar.ProgressCtls; rToolbarTips := Cr.WindowButtonBar.ToolbarTips; rDocumentTips := Cr.WindowButtonBar.DocumentTips; UpdateWindowButtonBar; end; {------------------------------------------------------------------------------} { UpdateWindowButtonBar } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.UpdateWindowButtonBar; begin {Enable/Disable controls} cbCancelBtn.Checked := Cr.WindowButtonBar.CancelBtn; cbCloseBtn.Checked := Cr.WindowButtonBar.CloseBtn; cbRefreshBtn.Checked := Cr.WindowButtonBar.RefreshBtn; cbZoomCtl.Checked := Cr.WindowButtonBar.ZoomCtl; cbPrintBtn.Checked := Cr.WindowButtonBar.PrintBtn; cbPrintSetupBtn.Checked := Cr.WindowButtonBar.PrintSetupBtn; cbExportBtn.Checked := Cr.WindowButtonBar.ExportBtn; cbLaunchBtn.Checked := Cr.WindowButtonBar.LaunchBtn; cbSearchBtn.Checked := Cr.WindowButtonBar.SearchBtn; cbAllowDrillDown.Checked := Cr.WindowButtonBar.AllowDrillDown; cbGroupTree.Checked := Cr.WindowButtonBar.GroupTree; cbNavigationCtls.Checked := Cr.WindowButtonBar.NavigationCtls; cbProgressCtls.Checked := Cr.WindowButtonBar.ProgressCtls; cbVisible.Checked := Cr.WindowButtonBar.Visible; cbToolbarTips.Checked := Cr.WindowButtonBar.ToolbarTips; cbDocumentTips.Checked := Cr.WindowButtonBar.DocumentTips; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.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 TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; end; end; end; {------------------------------------------------------------------------------} { cbVisibleClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbVisibleClick(Sender: TObject); var i : integer; begin for i := 0 to ComponentCount - 1 do begin if Components[i] is TCheckBox then begin if TCheckBox(Components[i]).Parent = pnlWindowButtonBar then TCheckBox(Components[i]).Enabled := cbVisible.Checked; end; end; Cr.WindowButtonBar.Visible := cbVisible.Checked; end; {------------------------------------------------------------------------------} { cbCancelBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbCancelBtnClick(Sender: TObject); begin Cr.WindowButtonBar.CancelBtn := cbCancelBtn.Checked; end; {------------------------------------------------------------------------------} { cbCloseBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbCloseBtnClick(Sender: TObject); begin Cr.WindowButtonBar.CloseBtn := cbCloseBtn.Checked; end; {------------------------------------------------------------------------------} { cbRefreshBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbRefreshBtnClick(Sender: TObject); begin Cr.WindowButtonBar.RefreshBtn := cbRefreshBtn.Checked; end; {------------------------------------------------------------------------------} { cbZoomCtlClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbZoomCtlClick(Sender: TObject); begin Cr.WindowButtonBar.ZoomCtl := cbZoomCtl.Checked; end; {------------------------------------------------------------------------------} { cbPrintBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbPrintBtnClick(Sender: TObject); begin Cr.WindowButtonBar.PrintBtn := cbPrintBtn.Checked; end; {------------------------------------------------------------------------------} { cbPrintSetupBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbPrintSetupBtnClick(Sender: TObject); begin Cr.WindowButtonBar.PrintSetupBtn := cbPrintSetupBtn.Checked; end; {------------------------------------------------------------------------------} { cbExportBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbExportBtnClick(Sender: TObject); begin Cr.WindowButtonBar.ExportBtn := cbExportBtn.Checked; end; {------------------------------------------------------------------------------} { cbLaunchBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbLaunchBtnClick(Sender: TObject); begin Cr.WindowButtonBar.LaunchBtn := cbLaunchBtn.Checked; end; {------------------------------------------------------------------------------} { cbSearchBtnClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbSearchBtnClick(Sender: TObject); begin Cr.WindowButtonBar.SearchBtn := cbSearchBtn.Checked; end; {------------------------------------------------------------------------------} { cbAllowDrillDownClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbAllowDrillDownClick(Sender: TObject); begin Cr.WindowButtonBar.AllowDrillDown := cbAllowDrillDown.Checked; end; {------------------------------------------------------------------------------} { cbGroupTreeClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbGroupTreeClick(Sender: TObject); begin Cr.WindowButtonBar.GroupTree := cbGroupTree.Checked; end; {------------------------------------------------------------------------------} { cbNavigationCtlsClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbNavigationCtlsClick(Sender: TObject); begin Cr.WindowButtonBar.NavigationCtls := cbNavigationCtls.Checked; end; {------------------------------------------------------------------------------} { cbProgressCtlsClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbProgressCtlsClick(Sender: TObject); begin Cr.WindowButtonBar.ProgressCtls := cbProgressCtls.Checked; end; {------------------------------------------------------------------------------} { cbToolbarTipsClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbToolbarTipsClick(Sender: TObject); begin Cr.WindowButtonBar.ToolbarTips := cbToolbarTips.Checked; end; {------------------------------------------------------------------------------} { cbDocumentTipsClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.cbDocumentTipsClick(Sender: TObject); begin Cr.WindowButtonBar.DocumentTips := cbDocumentTips.Checked; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.btnClearClick(Sender: TObject); begin Cr.WindowButtonBar.Clear; UpdateWindowButtonBar; end; {------------------------------------------------------------------------------} { btnActivateAllClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.btnActivateAllClick(Sender: TObject); begin Cr.WindowButtonBar.ActivateAll; UpdateWindowButtonBar; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrCancel then begin {Restore Settings} Cr.WindowButtonBar.Visible := rVisible; Cr.WindowButtonBar.CancelBtn := rCancel; Cr.WindowButtonBar.CloseBtn := rClose; Cr.WindowButtonBar.RefreshBtn := rRefresh; Cr.WindowButtonBar.ZoomCtl := rZoom; Cr.WindowButtonBar.PrintBtn := rPrint; Cr.WindowButtonBar.PrintSetupBtn := rPrintSetup; Cr.WindowButtonBar.ExportBtn := rExport; Cr.WindowButtonBar.LaunchBtn := rLaunch; Cr.WindowButtonBar.SearchBtn := rSearch; Cr.WindowButtonBar.AllowDrillDown := rAllowDrillDown; Cr.WindowButtonBar.GroupTree := rGroupTree; Cr.WindowButtonBar.NavigationCtls := rNavigation; Cr.WindowButtonBar.ProgressCtls := rProgress; Cr.WindowButtonBar.ToolbarTips := rToolbarTips; Cr.WindowButtonBar.DocumentTips := rDocumentTips; end; bWindowButtonBar := False; Release; end; end.
unit ibSHDDLExtractorFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, ExtCtrls, SynEdit, pSHSynEdit, VirtualTrees, StdCtrls, ActnList, AppEvnts,ibSHDriverIntf,ibSHSQLs; type (* IBTRegionForms = interface ['{524B6ACC-3EF3-460E-B606-B9FED5F6C8F8}'] function CanWorkWithRegion: Boolean; procedure ShowHideRegion(AVisible: Boolean); function GetRegionVisible: Boolean; property RegionVisible: Boolean read GetRegionVisible; end; *) TibSHDDLExtractorForm = class(TibBTComponentForm,iBTRegionForms) Panel1: TPanel; ComboBox1: TComboBox; Panel2: TPanel; Splitter1: TSplitter; Panel3: TPanel; Tree: TVirtualStringTree; Panel4: TPanel; pSHSynEdit1: TpSHSynEdit; ApplicationEvents1: TApplicationEvents; Panel5: TPanel; Image1: TImage; Panel6: TPanel; Bevel1: TBevel; Bevel2: TBevel; Panel7: TPanel; ProgressBar1: TProgressBar; procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); procedure Panel5Resize(Sender: TObject); private { Private declarations } FDDLExtractorIntf: IibSHDDLExtractor; FDomainList: TStrings; FTableList: TStrings; FIndexList: TStrings; FViewList: TStrings; FProcedureList: TStrings; FTriggerList: TStrings; FTriggerForViews:TStrings; FGeneratorList: TStrings; FExceptionList: TStrings; FFunctionList: TStrings; FFilterList: TStrings; FRoleList: TStrings; FScript : TStrings; { Tree } procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeDblClick(Sender: TObject); procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure SetTreeEvents(ATree: TVirtualStringTree); procedure BuildTree; procedure Prepare; procedure FillTriggersForView; procedure Extract(const AClassIID: TGUID; ASource: TStrings; Flag: Integer = -1); procedure ExtractBreakable(SourceList: TStrings; AType: string); procedure OnTextNotify(Sender: TObject; const Text: String); protected procedure RegisterEditors; override; { ISHFileCommands } function GetCanSaveAs: Boolean; override; { ISHRunCommands } function GetCanRun: Boolean; override; function GetCanPause: Boolean; override; function GetCanRefresh: Boolean; override; procedure Run; override; procedure Pause; override; procedure Refresh; override; //IBTRegionForms procedure ShowHideRegion(AVisible: Boolean); override; function CanWorkWithRegion: Boolean; function GetRegionVisible: Boolean; // procedure DoOnIdle; override; function GetCanDestroy: Boolean; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; property DDLExtractor: IibSHDDLExtractor read FDDLExtractorIntf; property DomainList: TStrings read FDomainList; property TableList: TStrings read FTableList; property IndexList: TStrings read FIndexList; property ViewList: TStrings read FViewList; property ProcedureList: TStrings read FProcedureList; property TriggerList: TStrings read FTriggerList; property GeneratorList: TStrings read FGeneratorList; property ExceptionList: TStrings read FExceptionList; property FunctionList: TStrings read FFunctionList; property FilterList: TStrings read FFilterList; property RoleList: TStrings read FRoleList; end; var ibSHDDLExtractorForm: TibSHDDLExtractorForm; implementation uses ibSHConsts, ibSHValues; {$R *.dfm} type PTreeRec = ^TTreeRec; TTreeRec = record NormalText: string; StaticText: string; Component: TSHComponent; ClassIID: TGUID; ImageIndex: Integer; Source: string; end; { TibSHDDLExtractorForm } constructor TibSHDDLExtractorForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin FScript := TStringList.Create; FDomainList := TStringList.Create; FTableList := TStringList.Create; FIndexList := TStringList.Create; FViewList := TStringList.Create; FProcedureList := TStringList.Create; FTriggerList := TStringList.Create; FGeneratorList := TStringList.Create; FExceptionList := TStringList.Create; FFunctionList := TStringList.Create; FFilterList := TStringList.Create; FRoleList := TStringList.Create; FTriggerForViews:=TStringList.Create; inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHDDLExtractor, FDDLExtractorIntf); Assert(DDLExtractor <> nil, 'DDLExtractor = nil'); Assert(DDLExtractor.BTCLDatabase <> nil, 'DDLExtractor.BTCLDatabase = nil'); Editor := pSHSynEdit1; Editor.Lines.Clear; FocusedControl := Editor; RegisterEditors; SetTreeEvents(Tree); BuildTree; ShowHideRegion(False); DoOnOptionsChanged; Panel6.Caption := EmptyStr; DDLExtractor.OnTextNotify := OnTextNotify; end; destructor TibSHDDLExtractorForm.Destroy; begin FScript.Free; FDomainList.Free; FTableList.Free; FIndexList.Free; FViewList.Free; FProcedureList.Free; FTriggerList.Free; FGeneratorList.Free; FExceptionList.Free; FFunctionList.Free; FFilterList.Free; FRoleList.Free; FTriggerForViews.Free; inherited Destroy; end; procedure TibSHDDLExtractorForm.SetTreeEvents(ATree: TVirtualStringTree); begin ATree.Images := Designer.ImageList; ATree.OnGetNodeDataSize := TreeGetNodeDataSize; ATree.OnFreeNode := TreeFreeNode; ATree.OnGetImageIndex := TreeGetImageIndex; ATree.OnGetText := TreeGetText; ATree.OnPaintText := TreePaintText; ATree.OnIncrementalSearch := TreeIncrementalSearch; ATree.OnDblClick := TreeDblClick; ATree.OnKeyDown := TreeKeyDown; ATree.OnCompareNodes := TreeCompareNodes; end; procedure TibSHDDLExtractorForm.BuildTree; function BuildRootNode(const AClassIID: TGUID): PVirtualNode; var NodeData: PTreeRec; begin Result := Tree.AddChild(nil); Result.CheckType := ctTriStateCheckBox; NodeData := Tree.GetNodeData(Result); NodeData.NormalText := GUIDToName(AClassIID, 1); NodeData.StaticText := EmptyStr; NodeData.ClassIID := AClassIID; NodeData.ImageIndex := Designer.GetImageIndex(AClassIID); end; procedure BuildRootNodes(const AClassIID: TGUID; AParent: PVirtualNode); var Node: PVirtualNode; NodeData, ParentData: PTreeRec; I: Integer; begin ParentData := Tree.GetNodeData(AParent); for I := 0 to Pred(DDLExtractor.BTCLDatabase.GetObjectNameList(AClassIID).Count) do begin Node := Tree.AddChild(AParent); Node.CheckType := ctTriStateCheckBox; NodeData := Tree.GetNodeData(Node); NodeData.NormalText := DDLExtractor.BTCLDatabase.GetObjectNameList(AClassIID)[I]; NodeData.StaticText := EmptyStr; NodeData.ClassIID := AClassIID; NodeData.ImageIndex := ParentData.ImageIndex; end; Tree.Sort(AParent, 0, sdAscending); end; begin try Tree.BeginUpdate; Tree.Clear; if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHDomain).Count > 0 then BuildRootNodes(IibSHDomain, BuildRootNode(IibSHDomain)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHTable).Count > 0 then BuildRootNodes(IibSHTable, BuildRootNode(IibSHTable)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHIndex).Count > 0 then BuildRootNodes(IibSHIndex, BuildRootNode(IibSHIndex)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHView).Count > 0 then BuildRootNodes(IibSHView, BuildRootNode(IibSHView)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHProcedure).Count > 0 then BuildRootNodes(IibSHProcedure, BuildRootNode(IibSHProcedure)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHTrigger).Count > 0 then BuildRootNodes(IibSHTrigger, BuildRootNode(IibSHTrigger)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHGenerator).Count > 0 then BuildRootNodes(IibSHGenerator, BuildRootNode(IibSHGenerator)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHException).Count > 0 then BuildRootNodes(IibSHException, BuildRootNode(IibSHException)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHFunction).Count > 0 then BuildRootNodes(IibSHFunction, BuildRootNode(IibSHFunction)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHFilter).Count > 0 then BuildRootNodes(IibSHFilter, BuildRootNode(IibSHFilter)); if DDLExtractor.BTCLDatabase.GetObjectNameList(IibSHRole).Count > 0 then BuildRootNodes(IibSHRole, BuildRootNode(IibSHRole)); if Tree.RootNodeCount > 0 then begin Tree.FocusedNode := Tree.GetFirst; Tree.Selected[Tree.FocusedNode] := True; end; finally Tree.EndUpdate; end; end; type TViewDependence = record ViewName:string; UsedViewName:string; end; procedure TibSHDDLExtractorForm.Prepare; procedure PrepareList(const AClassIID: TGUID; ASource: TStrings); var Node: PVirtualNode; NodeData: PTreeRec; begin ASource.Clear; if DDLExtractor.Mode = ExtractModes[0] then begin ASource.AddStrings(DDLExtractor.BTCLDatabase.GetObjectNameList(AClassIID)); end else begin Node := Tree.GetFirst; while Assigned(Node) do begin NodeData := Tree.GetNodeData(Node); if Assigned(NodeData) and IsEqualGUID(NodeData.ClassIID, AClassIID) and (Tree.GetNodeLevel(Node) = 1) and (Node.CheckState = csCheckedNormal) then ASource.Add(NodeData.NormalText); Node := Tree.GetNext(Node); end; end; end; var ViewDependencies:array of TViewDependence; procedure PrepareViewDependencies; var q:IibSHDRVQuery; i,L,L1:integer; tmp:TViewDependence; s:string; function FindCurUsed(const aViewName:string; FromPos:integer):integer; var j:integer; begin Result:=-1; for j:=FromPos to L1-1 do if ViewDependencies[j].ViewName=aViewName then begin Result:=j; Break end end; begin // Готовим список зависимостей вьюх от вьюх L:=200; L1:=0; SetLength(ViewDependencies,L); q:=DDLExtractor.BTCLDatabase.DRVQuery; if Assigned(q) then begin q.Close; q.SQL.Text:=SQL_VIEWS_DEPENDENCIES; if not q.Transaction.InTransaction then q.Transaction.StartTransaction; q.Execute; while not q.Eof do begin if L1>L then begin L:=L+50; SetLength(ViewDependencies,L); end; ViewDependencies[L1].ViewName:=q.GetFieldStrValue(0); ViewDependencies[L1].UsedViewName:=q.GetFieldStrValue(1); Inc(L1); q.Next end; q.Close; q.Transaction.Commit; end; SetLength(ViewDependencies,L1); // Сортируем список в правильном порядке. i:=0; while i<L1 do begin L:=FindCurUsed(ViewDependencies[i].UsedViewName,i+1); if L>i then begin tmp:=ViewDependencies[i]; ViewDependencies[i]:=ViewDependencies[L]; ViewDependencies[L]:=tmp end else Inc(i) end; i:=L1-1; while i>0 do begin L:=FindCurUsed(ViewDependencies[i].ViewName,0); if L<>i then begin ViewDependencies[L].ViewName:=''; ViewDependencies[L].UsedViewName:=''; { Move(ViewDependencies[L+1], ViewDependencies[L], SizeOf(ViewDependencies[L])*(L1-L-1) ); SetLength(ViewDependencies,L1-1); Dec(L1)} end; Dec(i) end; // Теперь нужно изменить порядок во ViewList i:=0 ; while i<Pred(ViewList.Count) do begin if FindCurUsed(ViewList[i],0)>-1 then ViewList.Delete(i) else Inc(i) end; s:=''; for i:=0 to L1-1 do if (Length(ViewDependencies[i].ViewName)>0) and(ViewDependencies[i].ViewName<>s) then begin s:=ViewDependencies[i].ViewName; ViewList.Add(s) end end; begin PrepareList(IibSHDomain, DomainList); PrepareList(IibSHTable, TableList); PrepareList(IibSHIndex, IndexList); PrepareList(IibSHView, ViewList); if DDLExtractor.Mode = ExtractModes[0] then PrepareViewDependencies; PrepareList(IibSHProcedure, ProcedureList); PrepareList(IibSHTrigger, TriggerList); if DDLExtractor.Mode = ExtractModes[0] then FillTriggersForView; PrepareList(IibSHGenerator, GeneratorList); PrepareList(IibSHException, ExceptionList); PrepareList(IibSHFunction, FunctionList); PrepareList(IibSHFilter, FilterList); PrepareList(IibSHRole, RoleList); end; procedure TibSHDDLExtractorForm.FillTriggersForView; var i:integer; begin i:=0; while i<FTriggerList.Count do begin if Integer(FTriggerList.Objects[i])<>1 then Inc(i) else begin FTriggerForViews.Add(FTriggerList[i]); FTriggerList.Delete(i); end end; end; procedure TibSHDDLExtractorForm.Extract(const AClassIID: TGUID; ASource: TStrings; Flag: Integer = -1); var I, Count: Integer; begin if DDLExtractor.Active then begin Image1.Canvas.Brush.Color := clBtnFace; Image1.Canvas.FillRect(Image1.Canvas.ClipRect); Designer.ImageList.Draw(Image1.Canvas, (Image1.Canvas.ClipRect.Left + Image1.Canvas.ClipRect.Right - 16) div 2, (Image1.Canvas.ClipRect.Top + Image1.Canvas.ClipRect.Bottom - 16) div 2, Designer.GetImageIndex(AClassIID)); Panel6.Caption := Format('Extracting %s...', [GUIDToName(AClassIID, 1)]); Count := ASource.Count; for I := 0 to Pred(Count) do begin DDLExtractor.DisplayDBObject(AClassIID, ASource[I], Flag); ProgressBar1.Position := 100 * I div Count; Application.ProcessMessages; if not DDLExtractor.Active then Break; end; end; end; procedure TibSHDDLExtractorForm.ExtractBreakable(SourceList: TStrings; AType: string); var I, Count: Integer; vClassIID: TGUID; begin if DDLExtractor.Active and Assigned(SourceList) then if Length(AType)>0 then begin case AType[1] of 'C','c': if SameText(AType, 'CHECK') then begin Panel6.Caption := 'Extracting checks...'; vClassIID := IibSHConstraint; end else if SameText(AType, 'CONSTRAINTS') then begin Panel6.Caption := Format('Extracting %s...', [GUIDToName(IibSHConstraint, 1)]); vClassIID := IibSHConstraint; end else if SameText(AType, 'COMPUTED BY') then begin Panel6.Caption := Format('Extracting %s...', [GUIDToName(IibSHField, 1)]); vClassIID := IibSHField; end; 'D','d': if SameText(AType, 'DESCRIPTIONS') then begin Panel6.Caption := 'Extracting descriptions...'; vClassIID := ISHBranch; end; 'F','f': if SameText(AType, 'FOREIGN KEY') then begin Panel6.Caption := 'Extracting foreign keys...'; vClassIID := IibSHConstraint; end; 'G','g': if SameText(AType, 'GRANTS') then begin Panel6.Caption := 'Extracting grants...'; vClassIID := IibSHGrantWGO; end; 'I','i': if SameText(AType, 'INDICES') then begin Panel6.Caption := Format('Extracting %s...', [GUIDToName(IibSHIndex, 1)]); vClassIID := IibSHIndex; end; 'P','p': if SameText(AType, 'PRIMARY KEY') then begin Panel6.Caption := 'Extracting primary keys...'; vClassIID := IibSHConstraint; end; 'T','t': if SameText(AType, 'TRIGGERS') then begin Panel6.Caption := Format('Extracting %s...', [GUIDToName(IibSHTrigger, 1)]); vClassIID := IibSHTrigger; end; 'U','u': if SameText(AType, 'UNIQUE') then begin Panel6.Caption := 'Extracting unique keys...'; vClassIID := IibSHConstraint; end; end; Image1.Canvas.Brush.Color := clBtnFace; Image1.Canvas.FillRect(Image1.Canvas.ClipRect); Designer.ImageList.Draw(Image1.Canvas, (Image1.Canvas.ClipRect.Left + Image1.Canvas.ClipRect.Right - 16) div 2, (Image1.Canvas.ClipRect.Top + Image1.Canvas.ClipRect.Bottom - 16) div 2, Designer.GetImageIndex(vClassIID)); Count := SourceList.Count; for I := 0 to Pred(Count) do begin if not SameText(AType, 'GRANTS') then OnTextNotify(Self, EmptyStr); OnTextNotify(Self, SourceList[I]); ProgressBar1.Position := 100 * I div Count; Application.ProcessMessages; if not DDLExtractor.Active then Break; end; end; end; procedure TibSHDDLExtractorForm.OnTextNotify(Sender: TObject; const Text: String); begin // Buzz: Совать прямо в синэдит - слишком тормозно { if Length(Text) > 0 then Designer.TextToStrings(Text, Editor.Lines) else Editor.Lines.Add(Text); Editor.CaretY := Pred(Editor.Lines.Count);} if Length(Text) > 0 then Designer.TextToStrings(Text, FScript) else FScript.Add(Text); Application.ProcessMessages; end; procedure TibSHDDLExtractorForm.RegisterEditors; var vEditorRegistrator: IibSHEditorRegistrator; begin if Supports(Designer.GetDemon(IibSHEditorRegistrator), IibSHEditorRegistrator, vEditorRegistrator) then vEditorRegistrator.RegisterEditor(Editor, DDLExtractor.BTCLDatabase.BTCLServer, DDLExtractor.BTCLDatabase); end; function TibSHDDLExtractorForm.GetCanSaveAs: Boolean; begin Result := not DDLExtractor.Active; end; function TibSHDDLExtractorForm.GetCanRun: Boolean; begin Result := not DDLExtractor.Active; end; function TibSHDDLExtractorForm.GetCanPause: Boolean; begin Result := DDLExtractor.Active; end; function TibSHDDLExtractorForm.GetCanRefresh: Boolean; begin Result := Tree.CanFocus; end; procedure TibSHDDLExtractorForm.Run; var OldShowBeginEndRegions:boolean; begin Panel5.Visible := True; Editor.Lines.Clear; DDLExtractor.Active := True; Designer.UpdateActions; DoOnIdle; Application.ProcessMessages; FScript.Clear; OldShowBeginEndRegions:=TpSHSynEdit(Editor).ShowBeginEndRegions; if OldShowBeginEndRegions then TpSHSynEdit(Editor).ShowBeginEndRegions:=False; try DDLExtractor.Prepare; DDLExtractor.DisplayScriptHeader; DDLExtractor.DisplayDialect; DDLExtractor.DisplayNames; if DDLExtractor.Active and (DDLExtractor.Header <> ExtractHeaders[2]) {None} then begin FScript.Add(EmptyStr); Editor.Lines.Add(EmptyStr); FScript.Add('/* < == Extracting database header... ===================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add('/* < == Extracting database header... ===================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); if DDLExtractor.Header = ExtractHeaders[0] {Create} then DDLExtractor.DisplayDatabase; if DDLExtractor.Header = ExtractHeaders[1] {Connect} then DDLExtractor.DisplayConnect; end; if DDLExtractor.Active then Prepare; if DDLExtractor.Active and (FunctionList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting functions... =========================================== > */' ); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting functions... =========================================== > */' ); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHFunction, FunctionList); end; if DDLExtractor.Active and (FilterList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting filters... ============================================= > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting filters... ============================================= > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHFilter, FilterList); end; if DDLExtractor.Active and (DomainList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting domains... ============================================= > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting domains... ============================================= > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHDomain, DomainList); end; if DDLExtractor.Active and (ExceptionList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting exceptions... ========================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting exceptions... ========================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHException, ExceptionList); end; if DDLExtractor.Active and (GeneratorList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting generators... ========================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting generators... ========================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHGenerator, GeneratorList); end; if DDLExtractor.Active and (ProcedureList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting procedure headers... =================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting procedure headers... =================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); DDLExtractor.DisplayTerminatorStart; Extract(IibSHProcedure, ProcedureList, 0); // only headers DDLExtractor.DisplayTerminatorEnd; end; if DDLExtractor.Active and (TableList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting tables... ============================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting tables... ============================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHTable, TableList); end; if DDLExtractor.Active and (DDLExtractor.ComputedSeparately) then begin if DDLExtractor.GetComputedList.Count > 0 then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting computed fields... ===================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting computed fields... ===================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); ExtractBreakable(DDLExtractor.GetComputedList, 'COMPUTED BY'); end; end; if DDLExtractor.Active and (ViewList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting views... =============================================== > */' ); FScript.Add('/* < ====================================================================== > */' ); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting views... =============================================== > */' ); Editor.Lines.Add('/* < ====================================================================== > */' ); Extract(IibSHView, ViewList); end; if DDLExtractor.Active and (DDLExtractor.GetPrimaryList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting constraints (PRIMARY KEY)... =========================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting constraints (PRIMARY KEY)... =========================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); ExtractBreakable(DDLExtractor.GetPrimaryList, 'PRIMARY KEY'); end; if DDLExtractor.Active and (DDLExtractor.GetUniqueList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting constraints (UNIQUE)... ================================ > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting constraints (UNIQUE)... ================================ > */'); Editor.Lines.Add('/* < ====================================================================== > */'); ExtractBreakable(DDLExtractor.GetUniqueList, 'UNIQUE'); end; if DDLExtractor.Active and (DDLExtractor.GetForeignList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting constraints (FOREIGN KEY)... =========================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting constraints (FOREIGN KEY)... =========================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); ExtractBreakable(DDLExtractor.GetForeignList, 'FOREIGN KEY'); end; if DDLExtractor.Active and (DDLExtractor.GetCheckList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting constraints (CHECK)... ================================= > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting constraints (CHECK)... ================================= > */'); Editor.Lines.Add('/* < ====================================================================== > */'); ExtractBreakable(DDLExtractor.GetCheckList, 'CHECK'); end; if DDLExtractor.Active and (IndexList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting indices... ============================================= > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting indices... ============================================= > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHIndex, IndexList); end; if DDLExtractor.Active and (FTriggerForViews.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting triggers for Views... ============================================ > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting triggers for Views... ============================================ > */'); Editor.Lines.Add('/* < ====================================================================== > */'); DDLExtractor.DisplayTerminatorStart; Extract(IibSHTrigger, FTriggerForViews,0); DDLExtractor.DisplayTerminatorEnd; end; if DDLExtractor.Active and (FTriggerForViews.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting triggers for Views... ============================================ > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting triggers for Views... ============================================ > */'); Editor.Lines.Add('/* < ====================================================================== > */'); DDLExtractor.DisplayTerminatorStart; Extract(IibSHTrigger, FTriggerForViews,1); DDLExtractor.DisplayTerminatorEnd; end; if DDLExtractor.Active and (FTriggerList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting triggers... ============================================ > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting triggers... ============================================ > */'); Editor.Lines.Add('/* < ====================================================================== > */'); DDLExtractor.DisplayTerminatorStart; Extract(IibSHTrigger, FTriggerList); DDLExtractor.DisplayTerminatorEnd; end; if DDLExtractor.Active and (ProcedureList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting procedures... ========================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting procedures... ========================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); DDLExtractor.DisplayTerminatorStart; Extract(IibSHProcedure, ProcedureList); DDLExtractor.DisplayTerminatorEnd; end; if DDLExtractor.Active and (RoleList.Count > 0) then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting roles... =============================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting roles... =============================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Extract(IibSHRole, RoleList); end; {TODO: Privileges} if DDLExtractor.Active and DDLExtractor.Grants then begin if DDLExtractor.GetGrantList.Count > 0 then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting grants... ============================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting grants... ============================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); ExtractBreakable(DDLExtractor.GetGrantList, 'GRANTS'); end; end; if DDLExtractor.Active and DDLExtractor.Descriptions then begin if DDLExtractor.GetDescriptionList.Count > 0 then begin FScript.Add(EmptyStr); FScript.Add('/* < == Extracting descriptions... ======================================== > */'); FScript.Add('/* < ====================================================================== > */'); Editor.Lines.Add(EmptyStr); Editor.Lines.Add('/* < == Extracting descriptions... ======================================== > */'); Editor.Lines.Add('/* < ====================================================================== > */'); ExtractBreakable(DDLExtractor.GetDescriptionList, 'DESCRIPTIONS'); end; end; if DDLExtractor.Active and DDLExtractor.FinalCommit then DDLExtractor.DisplayCommitWork; if not DDLExtractor.Active then begin FScript.Add(EmptyStr); FScript.Add(Format('/* BT: DDL Extractor stopped by user at %s */', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Now)])); Editor.Lines.Add(EmptyStr); Editor.Lines.Add(Format('/* BT: DDL Extractor stopped by user at %s */', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Now)])); end else DDLExtractor.DisplayScriptFooter; finally Editor.Lines.Assign(FScript); DDLExtractor.Active := False; Panel6.Caption := EmptyStr; Panel5.Visible := False; if OldShowBeginEndRegions then TpSHSynEdit(Editor).ShowBeginEndRegions:=True; end; end; procedure TibSHDDLExtractorForm.Pause; begin DDLExtractor.Active := False; Panel6.Caption := EmptyStr; Panel5.Visible := False; end; procedure TibSHDDLExtractorForm.Refresh; begin BuildTree; end; procedure TibSHDDLExtractorForm.ShowHideRegion(AVisible: Boolean); begin if AVisible then DDLExtractor.Mode:=ExtractModes[1] else DDLExtractor.Mode:=ExtractModes[0]; if GetRegionVisible then begin Panel3.Visible := True; Splitter1.Visible := True; end else begin Splitter1.Visible := False; Panel3.Visible := False; end; end; procedure TibSHDDLExtractorForm.DoOnIdle; begin ShowHideRegion(GetRegionVisible); // Говно но пока сойдет end; function TibSHDDLExtractorForm.GetCanDestroy: Boolean; begin Result := inherited GetCanDestroy; if DDLExtractor.BTCLDatabase.WasLostConnect then Exit; if DDLExtractor.Active then Designer.ShowMsg('Extract process is running...', mtInformation); Result := Assigned(DDLExtractor) and not DDLExtractor.Active; end; procedure TibSHDDLExtractorForm.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin DoOnIdle; end; procedure TibSHDDLExtractorForm.Panel5Resize(Sender: TObject); begin ProgressBar1.Width := ProgressBar1.Parent.ClientWidth - 8; end; { Tree } procedure TibSHDDLExtractorForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TibSHDDLExtractorForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then Finalize(Data^); end; procedure TibSHDDLExtractorForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := Data.ImageIndex; end; procedure TibSHDDLExtractorForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); case TextType of ttNormal: CellText := Data.NormalText; ttStatic: case Sender.GetNodeLevel(Node) of 0: CellText := Format('%d', [Node.ChildCount]); end; end; end; procedure TibSHDDLExtractorForm.TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); //var // Data: PTreeRec; begin // Data := Sender.GetNodeData(Node); case TextType of ttNormal: ; ttStatic: if Sender.Focused and (vsSelected in Node.States) then TargetCanvas.Font.Color := clWindow else TargetCanvas.Font.Color := clGray; end; end; procedure TibSHDDLExtractorForm.TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.NormalText)) <> 1 then Result := 1; end; procedure TibSHDDLExtractorForm.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // if Key = VK_RETURN then JumpToSource; end; procedure TibSHDDLExtractorForm.TreeDblClick(Sender: TObject); var HT: THitInfo; P: TPoint; begin GetCursorPos(P); P := Tree.ScreenToClient(P); Tree.GetHitTestInfoAt(P.X, P.Y, True, HT); // if not (hiOnItemButton in HT.HitPositions) then JumpToSource; end; procedure TibSHDDLExtractorForm.TreeCompareNodes( Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PTreeRec; begin Data1 := Sender.GetNodeData(Node1); Data2 := Sender.GetNodeData(Node2); Result := CompareStr(Data1.NormalText, Data2.NormalText); end; function TibSHDDLExtractorForm.CanWorkWithRegion: Boolean; begin Result:=True end; function TibSHDDLExtractorForm.GetRegionVisible: Boolean; begin Result:=DDLExtractor.Mode=ExtractModes[1] end; end.
unit Demo.PrimeCheck; { PrimeCheck example from the the Duktape guide (http://duktape.org/guide.html) } interface uses Duktape, Demo; type TDemoPrimeCheck = class(TDemo) private class function NativePrimeCheck(const ADuktape: TDuktape): TdtResult; cdecl; static; public procedure Run; override; end; implementation { TDemoPrimeCheck } class function TDemoPrimeCheck.NativePrimeCheck( const ADuktape: TDuktape): TdtResult; var I, Val, Lim: Integer; begin Val := ADuktape.RequireInt(0); Lim := ADuktape.RequireInt(1); for I := 2 to Lim do begin if ((Val mod I) = 0) then begin ADuktape.PushFalse; Exit(TdtResult.HasResult); end; end; ADuktape.PushTrue; Result := TdtResult.HasResult; end; procedure TDemoPrimeCheck.Run; begin Duktape.PushGlobalObject; Duktape.PushDelphiFunction(NativePrimeCheck, 2); Duktape.PutProp(-2, 'primeCheckNative'); PushResource('PRIME'); if (Duktape.ProtectedEval <> 0) then begin Log('Error: ' + String(Duktape.SafeToString(-1))); Exit; end; Duktape.Pop; // Ignore result Duktape.GetProp(-1, 'primeTest'); if (Duktape.ProtectedCall(0) <> 0) then Log('Error: ' + String(Duktape.SafeToString(-1))); Duktape.Pop; // Ignore result end; initialization TDemo.Register('Prime Check', TDemoPrimeCheck); end.
unit Wwdbdlg; { // // Components : TwwDBLookupDlg // // Copyright (c) 1995 by Woll2Woll Software // } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Buttons, Forms, Dialogs, StdCtrls, wwdblook, dbTables, wwiDlg, DsgnIntf, db, Wwdbgrid, wwTable, menus, wwdbigrd, wwstr, wwcommon; type TwwDBLookupComboDlg = class(TwwDBCustomLookupCombo) private FGridOptions: TwwDBGridOptions; FGridColor: TColor; FGridTitleAlignment: TAlignment; FOptions : TwwDBLookupDlgOptions; FCaption: String; FMaxWidth, FMaxHeight: integer; FUserButton1Click: TwwUserButtonEvent; FUserButton2Click: TwwUserButtonEvent; FUserButton1Caption: string; FUserButton2Caption: string; FOnInitDialog: TwwOnInitDialogEvent; FOnCloseDialog: TwwOnInitDialogEvent; procedure SetOptions(sel: TwwDBLookupDlgOptions); procedure SetGridOptions(sel: TwwDBGridOptions); protected Function LoadComboGlyph: HBitmap; override; Procedure DrawButton(Canvas: TCanvas; R: TRect; State: TButtonState; ControlState: TControlState; var DefaultPaint: boolean); override; Function IsLookupDlg: boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DropDown; override; published property Options: TwwDBLookupDlgOptions read FOptions write SetOptions default [opShowOKCancel, opShowSearchBy]; property GridOptions: TwwDBGridOptions read FGridOptions write SetGridOptions default [dgEditing, dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgConfirmDelete, dgPerfectRowFit]; property GridColor: TColor read FGridColor write FGridColor; property GridTitleAlignment: TAlignment read FGridTitleAlignment write FGridTitleAlignment; property Caption : String read FCaption write FCaption; property MaxWidth : integer read FMaxWidth write FMaxWidth; property MaxHeight : integer read FMaxHeight write FMaxHeight; property UserButton1Caption: string read FUserButton1Caption write FUserButton1Caption; property UserButton2Caption: string read FUserButton2Caption write FUserButton2Caption; property OnUserButton1Click: TwwUserButtonEvent read FUserButton1Click write FUserButton1Click; property OnUserButton2Click: TwwUserButtonEvent read FUserButton2Click write FUserButton2Click; property OnInitDialog: TwwOnInitDialogEvent read FOnInitDialog write FOnInitDialog; property OnCloseDialog: TwwOnInitDialogEvent read FOnCloseDialog write FOnCloseDialog; property Selected; property DataField; property DataSource; property LookupTable; property LookupField; property SeqSearchOptions; property Style; property AutoSelect; property Color; property DragCursor; property DragMode; property Enabled; {$ifdef ver100} property ImeMode; property ImeName; {$endif} property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property AutoDropDown; property ShowButton; property OrderByDisplay; property AllowClearKey; property UseTFields; property ShowMatchText; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDropDown; property OnCloseUp; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; procedure Register; implementation uses wwlocate; constructor TwwDBLookupComboDlg.Create(AOwner: TComponent); begin inherited create(AOwner); FGridOptions := [dgTitles, dgIndicator, dgColumnResize, dgRowSelect, dgColLines, dgRowLines, dgTabs, dgAlwaysShowSelection, dgConfirmDelete, dgPerfectRowFit]; FGridColor:= clWhite; FGridTitleAlignment:= taLeftJustify; FOptions:= [opShowOKCancel, opShowSearchBy]; FCaption:= 'Lookup'; FMaxHeight:= 209; FGrid.SkipDataChange:= True; end; destructor TwwDBLookupComboDlg.Destroy; begin inherited Destroy; end; Procedure TwwDBLookupComboDlg.DrawButton(Canvas: TCanvas; R: TRect; State: TButtonState; ControlState: TControlState; var DefaultPaint: boolean); begin {$ifdef win32} DefaultPaint:= False; wwDrawEllipsis(Canvas, R, State, Enabled, ControlState) {$endif} end; Function TwwDBLookupComboDlg.LoadComboGlyph: HBitmap; { Win95 } begin result:= LoadBitmap(HInstance, 'DOTS'); end; procedure TwwDBLookupComboDlg.SetOptions(sel: TwwDBLookupDlgOptions); begin FOptions:= sel; end; procedure TwwDBLookupComboDlg.SetGridOptions(sel: TwwDBGridOptions); begin FGridOptions:= sel; end; procedure TwwDBLookupComboDlg.DropDown; type SmallString = string[63]; var MyOnDropDown: TNotifyEvent; {fromFieldName: String;} {Win95 - formerly SmallString} MyOnCloseUp: TNotifyCloseUpEvent; res: boolean; keyFieldValue: string; lkupField: TField; searchText, field1name: SmallString; curpos: integer; modified: boolean; begin if ReadOnly then exit; if (LookupTable=Nil) then begin MessageDlg('No lookup table specified!', mtWarning, [mbok], 0); RefreshButton; exit; end; if (not LookupTable.active) then begin MessageDlg('No lookup table specified!', mtWarning, [mbok], 0); RefreshButton; exit; end; try { If calculated field then 1. Find dest link field(s) name 2. Set lookup table to use indexName for calculated field indexName 3. Perform FindKey 4. Switch index of lookupTable to match display of left-most column field 5. After dialog returns, change value of from link field to selection } MyOnDropDown:= OnDropDown; MyOnCloseUp:= OnCloseUp; if Assigned(MyOnDropDown) then MyOnDropDown(Self); { default to lookup field if no selection } curPos:= 1; field1Name:= strGetToken(lookupField, ';', curpos); if (Selected.count=0) then begin if isWWCalculatedField then lkupField:= TwwPopupGrid(FGrid).DisplayFld else lkupField:= lookupTable.findField(field1Name); if (lkupField<>Nil) then begin Selected.add( lkupField.fieldName + #9 + inttostr(lkupField.displayWidth) + #9 + lkupField.DisplayLabel); end end; if AutoDropDown and inAutoDropDown then SearchText:= Text else SearchText:= ''; if (dataSource<>Nil) and (dataSource.dataSet<>Nil) and isWWCalculatedField then begin { wwDataSetSyncLookupTable(dataSource.dataSet, lookupTable, dataField, fromFieldName);} Grid.DoLookup(True); { Called in case lookupTable was moved by another control } if (not HasMasterSource) and (LookupTable is TwwTable) and OrderByDisplay then LTable.setToIndexContainingFields(Selected); res:= ExecuteWWLookupDlg(Screen.ActiveForm, Selected, lookupTable, FOptions, FGridOptions, FGridColor, FGridTitleAlignment, FCaption, FMaxWidth, FMaxHeight, CharCase, FUserButton1Caption, FUserButton2Caption, FUserButton1Click, FUserButton2Click, FOnInitDialog, FOnCloseDialog, SearchText, UseTFields); if (DataSource<>Nil) and (DataSource.dataset<>Nil) then DataSource.dataSet.disableControls; if res then begin if LookupField<>'' then UpdateFromCurrentSelection; { Updates FValue^ used by wwChangeFromLink } wwChangefromLink(LookupTable, modified) end else modified:= false; if Assigned(MyOnCloseUp) then begin MyOnCloseUp(Self, LookupTable, dataSource.dataSet, modified); end; if (DataSource<>Nil) and (DataSource.dataset<>Nil) then DataSource.dataSet.enableControls; end else begin { if (lookupTable.fieldByName(Field1Name).asString <> LookupValue) or} if (LookupValue='') or isLookupRequired then begin { Switch index to lookup field's index } if (LookupTable is TwwTable) and (LTable.MasterSource=Nil) and (Lookupfield<>'') then LTable.setToIndexContainingField(LookupField); if TwwPopupGrid(FGrid).LookupFieldCount<2 then begin if UseSeqSearch or (LTable.indexFieldCount=0) then { Sequential search } begin FindRecord(LookupValue, LookupField, mtExactMatch, ssoCaseSensitive in SeqSearchOptions) end else LTable.wwFindKey([LookupValue]) end else if TwwPopupGrid(FGrid).LookupFieldCount<3 then LTable.wwFindKey([LookupValue, Value2]) else LTable.wwFindKey([LookupValue, SetValue2, SetValue3]); end; {Switch index back to previous index if not sql} if (LookupTable is TwwTAble) and (not HasMasterSource) and OrderByDisplay then LTable.setToIndexContainingFields(Selected); res:= ExecuteWWLookupDlg(Screen.ActiveForm, Selected, lookupTable, FOptions, FGridOptions, FGridColor, FGridTitleAlignment, FCaption, FMaxWidth, FMaxHeight, CharCase, FUserButton1Caption, FUserButton2Caption, FUserButton1Click, FUserButton2Click, FOnInitDialog, FOnCloseDialog, SearchText, UseTFields); if (DataSource<>Nil) and (DataSource.dataset<>Nil) then DataSource.dataSet.disableControls; try skipDataChange:= True; { Don't update internal lookup values 1/15/96 } if res then begin if LookupField<>'' then begin KeyFieldValue:= lookupTable.fieldByName(Field1Name).Text; FFieldLink.Edit; if (DataSource=Nil) or (DataSource.dataSet=Nil) then begin UpdateFromCurrentSelection; Text:= TwwPopupGrid(FGrid).DisplayValue; end; FFieldLink.Modified; if FFieldLink.Field<>Nil then begin FFieldLink.Field.AsString := KeyFieldValue; { forces calculated fields to refresh } UpdateFromCurrentSelection; { 8/25/96 - Update internal variables } Text:= FGrid.DisplayFld.asString; { 8/25/96 } FFieldLink.UpdateRecord; { 1/22/96 - Update 2nd-3rd fields } end end end; if Assigned(MyOnCloseUp) then begin if DataSource=Nil then MyOnCloseUp(Self, LookupTable, Nil, res) else MyOnCloseUp(Self, LookupTable, DataSource.dataSet, res); end; finally if (DataSource<>Nil) and (DataSource.dataset<>Nil) then DataSource.dataSet.enableControls; end; end; finally if (Style <> csDropDownList) or AutoDropDown then SelectAll; FLastSearchKey:= ''; RefreshButton; SkipDataChange:= False; if modified then begin LookupTable.updateCursorPos; LookupTable.resync([]); end end; end; Function TwwDBLookupComboDlg.IsLookupDlg: boolean; begin result:= True; end; procedure Register; begin { RegisterComponents('InfoPower', [TwwDBLookupComboDlg]);} end; end.
(* Define an object with the following fields and methods. Write a program that creates the object and tests the methods. The object is a table, its parameteres are two numbers: its length and width. Its methods are the initialization procedure, a procedure for computing its area, and a pretty-printing method. *) type Table = class(TObject) len: Integer; width: Integer; procedure init(l, w: Integer); function area(): Integer; procedure print(); end; procedure Table.init(l, w: Integer); begin len := l; width := w; end; function Table.area(): Integer; begin Result := len * width; end; procedure Table.print(); begin WriteLn('length: ', len); WriteLn('width: ', width); end; var t: Table; begin t := Table.Create(); t.init(4, 5); t.print(); WriteLn(t.area()); t.Destroy(); end.
unit ThCheckBox; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThInterfaces, ThTextPaint, ThWebControl, ThTag; type TThCustomStateBox = class(TThWebGraphicControl, IThFormInput) private FChecked: Boolean; protected function GetHtmlAsString: string; override; procedure SetChecked(const Value: Boolean); protected function ButtonHeight: Integer; function ButtonWidth: Integer; function GetCaptionContent: string; virtual; function GetInputName: string; virtual; function GetInputType: string; virtual; procedure PaintCheck(inX, inY: Integer); virtual; procedure Paint; override; procedure PerformAutoSize; override; procedure Tag(inTag: TThTag); override; protected property AutoSize default true; property Checked: Boolean read FChecked write SetChecked; public constructor Create(AOwner: TComponent); override; procedure CellTag(inTag: TThTag); override; end; // TThCheckBox = class(TThCustomStateBox) published property Align; property AutoSize default true; property Caption; property Checked; property Style; property StyleClass; property Visible; end; // TThRadio = class(TThCustomStateBox) private FGroup: Integer; protected function GetInputName: string; override; function GetInputType: string; override; procedure SetGroup(const Value: Integer); protected procedure PaintCheck(inX, inY: Integer); override; published property Align; property AutoSize default true; property Caption; property Checked; property Group: Integer read FGroup write SetGroup; property Style; property StyleClass; property Visible; end; implementation {$R ThResources.res} var ThCheckImages: TImageList; function ThNeedCheckImages: Boolean; var b: TBitmap; begin if ThCheckImages = nil then try b := TBitmap.Create; try ThCheckImages := TImageList.Create(nil); with ThCheckImages do begin Width := 12; Height := 12; b.LoadFromResourceName(HInstance, 'TRBOCHECKOFF'); AddMasked(b, clFuchsia); b.LoadFromResourceName(HInstance, 'TRBOCHECKON'); AddMasked(b, clFuchsia); b.LoadFromResourceName(HInstance, 'TRBORADIOOFF'); AddMasked(b, clFuchsia); b.LoadFromResourceName(HInstance, 'TRBORADIOON'); AddMasked(b, clFuchsia); end; finally b.Free; end; except end; Result := (ThCheckImages <> nil); end; { TThCustomStateBox } constructor TThCustomStateBox.Create(AOwner: TComponent); begin inherited; AutoSize := true; //CtrlStyle.Borders.SetDefaultBorderPixels(2); //CtrlStyle.Font.DefaultFontFamily := 'MS Sans Serif'; //CtrlStyle.Font.DefaultFonThx := 14; end; function TThCustomStateBox.ButtonWidth: Integer; begin if AutoSize then begin Result := ThTextWidth(Canvas, Caption); Result := Result * 140 div 100; Result := Result + Style.GetBoxWidthMargin; end else Result := Width; end; function TThCustomStateBox.ButtonHeight: Integer; begin if AutoSize then begin Result := ThTextHeight(Canvas, Caption) + 5; if (Result < 0) then Result := Height else Result := Result + Style.GetBoxHeightMargin; end else Result := Height; end; procedure TThCustomStateBox.PerformAutoSize; begin Canvas.Font := Font; SetBounds(Left, Top, ButtonWidth, ButtonHeight); end; procedure TThCustomStateBox.PaintCheck(inX, inY: Integer); const cThCheckImageIndex: array[Boolean] of Integer = ( 0, 1 ); begin ThCheckImages.Draw(Canvas, inX, inY, cThCheckImageIndex[Checked]); end; procedure TThCustomStateBox.Paint; var r: TRect; begin inherited; ThNeedCheckImages; r := AdjustedClientRect; PaintCheck(r.Left + 2, r.Top + 4); r := Rect(r.Left + 18, r.Top + 1, r.Right, r.Bottom); ThPaintText(Canvas, Caption, r); end; { procedure TThCustomStateBox.Paint; var r: TRect; begin r := ClientRect; if (Parent is TWinControl) then Canvas.Brush.Color := TPanel(Parent).Color else Canvas.Brush.Color := Color; Canvas.FillRect(r); Style.UnpadRect(r); // Painter.Prepare(Color, CtrlStyle, Canvas, r); if not TbhVisibleColor(CtrlStyle.Color) then Painter.Color := clBtnFace; Painter.PaintBackground; Painter.PaintOutsetBorders; // Canvas.Font := Font; TbhPaintText(Canvas, Caption, r, haCenter, vaMiddle); end; } function TThCustomStateBox.GetInputName: string; begin Result := Name; end; function TThCustomStateBox.GetInputType: string; begin Result := 'checkbox'; end; procedure TThCustomStateBox.CellTag(inTag: TThTag); begin inherited; inTag.Attributes['valign'] := 'middle'; end; function TThCustomStateBox.GetCaptionContent: string; begin //Result := Caption; Result := Format('<label for="%s">%s</label>', [ Name, Caption ]); end; procedure TThCustomStateBox.Tag(inTag: TThTag); begin inherited; with inTag do begin Element := 'input'; Add('type', GetInputType); Add('name', GetInputName); Add('value', Name); if Checked then Add('checked', 'checked'); Add('id', Name); //Content := GetCaptionContent; end; end; function TThCustomStateBox.GetHtmlAsString: string; begin Result := Format('<label>%s%s</label>', [ GetTagHtml, Caption ]); end; procedure TThCustomStateBox.SetChecked(const Value: Boolean); begin FChecked := Value; Invalidate; end; { TThRadio } function TThRadio.GetInputType: string; begin Result := 'radio'; end; function TThRadio.GetInputName: string; begin Result := 'RadioGroup' + IntToStr(Group); end; procedure TThRadio.PaintCheck(inX, inY: Integer); const cThRadioImageIndex: array[Boolean] of Integer = ( 2, 3 ); begin ThCheckImages.Draw(Canvas, inX, inY, cThRadioImageIndex[Checked]); end; procedure TThRadio.SetGroup(const Value: Integer); begin FGroup := Value; end; end.
unit Unit1_7; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Unit64; type TChildForm1_7 = class(TFatherForm) Edit1: TEdit; Label1: TLabel; Button1: TButton; Label2: TLabel; Label3: TLabel; Label4: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var ChildForm1_7: TChildForm1_7; implementation {$R *.dfm} procedure TChildForm1_7.Button1Click(Sender: TObject); var numero: integer; x1: integer; x2: integer; x3: integer; begin if (StrToInt(Edit1.Text) >= 100) and (StrToInt(Edit1.Text) <= 999) then begin numero := StrToInt(Edit1.Text); x1 := numero div 100; x3 := numero mod 10; x2 := (numero - x1 * 100 - x3) div 10; Label2.Caption := IntToStr(x1); Label3.Caption := IntToStr(x2); Label4.Caption := IntToStr(x3); end else begin showMessage ('Insira um número inteiro entre 100 e 999.'); end; end; initialization RegisterClass(TChildForm1_7); end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Repository.Directory; interface uses Generics.Defaults, VSoft.Awaitable, Spring.Collections, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.Logging, DPM.Core.Options.Search, DPM.Core.Options.Push, DPM.Core.Spec.Interfaces, DPM.Core.Package.Interfaces, DPM.Core.Configuration.Interfaces, DPM.Core.Repository.Interfaces, DPM.Core.Repository.Base; type TReadSpecFunc = reference to function(const name : string; const spec : IPackageSpec) : IInterface; TDirectoryPackageRepository = class(TBaseRepository, IPackageRepository) private FPermissionsChecked : boolean; FIsWritable : boolean; protected function DoGetPackageMetaData(const cancellationToken : ICancellationToken; const fileName : string; const readSpecFunc : TReadSpecFunc) : IInterface; function DoList(searchTerm : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IList<string>; function DoExactList(const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const version : string) : IList<string>; function DoGetPackageFeedFiles(const searchTerm : string; const exact : boolean; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IList<string>; function DoGetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const files : IList<string>) : IList<IPackageSearchResultItem>; function DownloadPackage(const cancellationToken : ICancellationToken; const packageMetadata : IPackageIdentity; const localFolder : string; var fileName : string) : boolean; function FindLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platform : TDPMPlatform; const includePrerelease : boolean) : IPackageIdentity; function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>; function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; overload; // function GetPackageLatestVersions(const cancellationToken : ICancellationToken; const ids : IList<IPackageId>; const platform : TDPMPlatform; const compilerVersion : TCompilerVersion) : IDictionary<string, IPackageLatestVersionInfo>; function GetPackageLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageLatestVersionInfo; function GetPackageMetaData(const cancellationToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResultItem; function GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const preRelease : boolean) : IList<TPackageVersion>; overload; function GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; function GetPackageFeedByIds(const cancellationToken : ICancellationToken; const ids : IList<IPackageId>; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; function GetPackageIcon(const cancelToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; //commands function Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions): Boolean; function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>; overload; public constructor Create(const logger : ILogger); override; end; implementation uses VSoft.Uri, System.Types, System.Classes, System.SysUtils, System.IOUtils, System.RegularExpressions, System.Zip, Spring.Collections.Extensions, DPM.Core.Constants, DPM.Core.Package.Metadata, DPM.Core.Package.Icon, DPM.Core.Spec.Reader, DPM.Core.Utils.Strings, DPM.Core.Utils.Path, DPM.Core.Utils.Directory, DPM.Core.Package.SearchResults, DPM.Core.Package.ListItem, DPM.Core.Package.PackageLatestVersionInfo; { TDirectoryPackageRespository } function GetSearchRegex(const compilerVersion : TCompilerVersion; const platforms : TDPMPlatforms; const version : string) : string; begin // ^(\w+\.\w+)\-([^\-]+)\-([^\-]+)\-(.*)$'; result := '^(\w+\.\w+)\-'; if (compilerVersion > TCompilerVersion.UnknownVersion) then result := result + Format('(%s)\-', [CompilerToString(compilerVersion)]) else result := result + '([^\-]+)\-'; if platforms <> [] then result := result + Format('(%s)\-', [DPMPlatformsToString(platforms, '|')]) else result := result + '([^\-]+)\-'; if version <> '' then result := result + Format('(%s)$', [version]) else result := result + '(.*)$'; end; constructor TDirectoryPackageRepository.Create(const logger : ILogger); begin inherited Create(logger); FPermissionsChecked := false; FIsWritable := false; end; function TDirectoryPackageRepository.DownloadPackage(const cancellationToken : ICancellationToken; const packageMetadata : IPackageIdentity; const localFolder : string; var fileName : string) : boolean; var sourceFile : string; destFile : string; begin result := false; sourceFile := IncludeTrailingPathDelimiter(SourceUri) + packageMetadata.ToString + cPackageFileExt; if not FileExists(sourceFile) then begin Logger.Error('File not found in repository [' + sourceFile + ']'); exit; end; destFile := IncludeTrailingPathDelimiter(localFolder) + packageMetadata.ToString + cPackageFileExt; if TPathUtils.IsRelativePath(destFile) then destFile := TPath.GetFullPath(destFile); try ForceDirectories(ExtractFilePath(destFile)); Logger.Information('GET ' + sourceFile); TFile.Copy(sourceFile, destFile, true); fileName := destFile; result := true; Logger.Information('OK ' + sourceFile); except on e : Exception do begin Logger.Error('Error downloading [' + sourceFile + '] to [' + destFile + ']'); end; end; end; function TDirectoryPackageRepository.FindLatestVersion(const cancellationToken: ICancellationToken; const id: string; const compilerVersion: TCompilerVersion; const version: TPackageVersion; const platform: TDPMPlatform; const includePrerelease : boolean): IPackageIdentity; var searchFiles : IList<string>; regex : TRegEx; searchRegex : string; packageFile : string; match : TMatch; i : integer; maxVersion : TPackageVersion; packageVersion : TPackageVersion; maxVersionFile : string; begin result := nil; if version.IsEmpty then searchFiles := DoExactList(id, compilerVersion, platform, '') else searchFiles := DoExactList(id, compilerVersion, platform, version.ToStringNoMeta); searchRegEx := GetSearchRegex(compilerVersion, [], ''); regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); maxVersion := TPackageVersion.Empty; for i := 0 to searchFiles.Count - 1 do begin packageFile := searchFiles[i]; //ensure that the files returned are actually packages packageFile := ChangeFileExt(ExtractFileName(packageFile), ''); match := regex.Match(packageFile); if match.Success then begin if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then continue; if (not includePrerelease) and (not packageVersion.IsStable) then continue; //if we wanted a specific version, then we have found it. if not version.IsEmpty then begin maxVersionFile := packageFile; maxVersion := version; Break; end; if packageVersion > maxVersion then begin maxVersion := packageVersion; maxVersionFile := packageFile; end; end; end; if maxVersion.IsEmpty then exit; result := TPackageIdentity.Create(Self.Name, id, maxVersion, compilerVersion, platform); end; function TDirectoryPackageRepository.GetPackageIcon(const cancelToken : ICancellationToken; const packageId, packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; var zipFile : TZipFile; zipIdx : integer; packagFileName : string; svgIconFileName : string; pngIconFileName : string; stream : TMemoryStream; DecompressionStream : TStream; fileStream : TFileStream; zipHeader : TZipHeader; begin result := nil; packagFileName := Format('%s-%s-%s-%s.dpkg', [packageId, CompilerToString(compilerVersion), DPMPlatformToString(platform), packageVersion]); packagFileName := TPath.Combine(Self.SourceUri, packagFileName); svgIconFileName := ChangeFileExt(packagFileName, '.svg'); pngIconFileName := ChangeFileExt(packagFileName, '.png'); //it quite likely already extracted so look for that first //icons can be svg or png. if FileExists(svgIconFileName) then begin fileStream := TFileStream.Create(svgIconFileName, fmOpenRead); stream := TMemoryStream.Create; try stream.CopyFrom(fileStream, fileStream.Size); finally fileStream.Free; end; //the icon now owns the stream. result := CreatePackageIcon(TPackageIconKind.ikSvg, stream); exit; end; if FileExists(pngIconFileName) then begin fileStream := TFileStream.Create(pngIconFileName, fmOpenRead); stream := TMemoryStream.Create; try stream.CopyFrom(fileStream, fileStream.Size); finally fileStream.Free; end; //the icon now owns the stream. result := CreatePackageIcon(TPackageIconKind.ikPng, stream); exit; end; //not already extracted, so check the package zipFile := TZipFile.Create; try try zipFile.Open(packagFileName, TZipMode.zmRead); zipIdx := zipFile.IndexOf(cIconFileSVG); if zipIdx <> -1 then begin stream := TMemoryStream.Create; //casting due to broken overload resolution in XE7 zipFile.Read(zipIdx, DecompressionStream, zipHeader); stream.CopyFrom(DecompressionStream, DecompressionStream.Size); FreeAndNil(DecompressionStream); //save it to speed up things next time. stream.SaveToFile(svgIconFileName); //result now owns the stream. result := CreatePackageIcon(TPackageIconKind.ikSvg, stream); exit; end; if cancelToken.IsCancelled then exit; zipIdx := zipFile.IndexOf(cIconFilePNG); if zipIdx <> -1 then begin stream := TMemoryStream.Create; //casting due to broken overload resolution in XE7 zipFile.Read(zipIdx, DecompressionStream, zipHeader); stream.CopyFrom(DecompressionStream, DecompressionStream.Size); FreeAndNil(DecompressionStream); stream.SaveToFile(pngIconFileName); //result now owns the stream. result := CreatePackageIcon(TPackageIconKind.ikPng, stream); exit; end; except on e : Exception do begin Logger.Error('Error opening package file [' + packagFileName + ']'); exit; end; end; finally zipFile.Free; end; end; function TDirectoryPackageRepository.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; var packageFileName : string; readSpecFunc : TReadSpecFunc; begin result := nil; packageFileName := Format('%s-%s-%s-%s.dpkg', [packageId.Id, CompilerToString(packageId.CompilerVersion), DPMPlatformToString(packageId.Platform), packageId.Version.ToStringNoMeta]); packageFileName := IncludeTrailingPathDelimiter(SourceUri) + packageFileName; if not FileExists(packageFileName) then exit; if cancellationToken.IsCancelled then exit; readSpecFunc := function (const name : string; const spec : IPackageSpec) : IInterface begin result := TPackageInfo.CreateFromSpec(name, spec); end; result := DoGetPackageMetaData(cancellationToken, packageFileName, readSpecFunc) as IPackageInfo; end; function TDirectoryPackageRepository.GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; var searchTerms : TArray<string>; i : integer; results : IList<IPackageSearchResultItem>; searchFiles : IList<string>; allFiles : IList<string>; distinctFiles : IEnumerable<string>; // take : integer; begin Logger.Debug('TDirectoryPackageRepository.GetPackageFeed'); result := TDPMPackageSearchResult.Create(options.Skip,0); if options.CompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentException.Create('Compiler version must be set'); if options.SearchTerms <> '' then searchTerms := TStringUtils.SplitStr(Trim(options.SearchTerms), ' '); //need at least 1 search term, if there are none then search for * if length(searchTerms) = 0 then begin SetLength(searchTerms, 1); searchTerms[0] := '*'; end; allFiles := TCollections.CreateList < string > ; for i := 0 to Length(searchTerms) - 1 do begin if cancelToken.IsCancelled then exit; allFiles.AddRange(DoGetPackageFeedFiles(searchTerms[i], options.Exact, compilerVersion, platform)); end; distinctFiles := TDistinctIterator<string>.Create(allFiles, TStringComparer.OrdinalIgnoreCase); // if options.Skip > 0 then // distinctFiles := distinctFiles.Skip(options.Skip); // if options.Take > 0 then // distinctFiles := distinctFiles.Take(options.Take); searchFiles := TCollections.CreateList<string>(distinctFiles); results := DoGetPackageFeed(cancelToken, options, searchFiles); result.Results.AddRange(results); end; function TDirectoryPackageRepository.GetPackageLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform ) : IPackageLatestVersionInfo; var i : integer; searchFiles : IList<string>; regex : TRegEx; searchRegex : string; packageFile : string; match : TMatch; packageVersion : TPackageVersion; latestVersion : TPackageVersion; latestStableVersion : TPackageVersion; begin result := nil; searchRegEx := GetSearchRegex(compilerVersion, [], ''); regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); searchFiles := DoExactList(id, compilerVersion, platform, ''); latestVersion := TPackageVersion.Empty; latestStableVersion := TPackageVersion.Empty; for i := 0 to searchFiles.Count -1 do begin packageFile := ChangeFileExt(ExtractFileName(searchFiles[i]), ''); match := regex.Match(packageFile); if match.Success then begin if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then continue; if packageVersion > latestVersion then latestVersion := packageVersion; if packageVersion.IsStable and (packageVersion > latestStableVersion) then latestStableVersion := packageVersion; end; //if latestVersion is empt then we didn't find any files! end; if not latestVersion.IsEmpty then result:= TDPMPackageLatestVersionInfo.Create(id,latestStableVersion, latestVersion); end; function TDirectoryPackageRepository.GetPackageFeedByIds(const cancellationToken: ICancellationToken; const ids: IList<IPackageId>; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IPackageSearchResult; var item : IPackageId; metaData : IPackageSearchResultItem; latestVersionInfo : IPackageLatestVersionInfo; begin result := TDPMPackageSearchResult.Create(0,0); for item in ids do begin metaData := GetPackageMetaData(cancellationToken,item.Id, item.Version.ToString, compilerVersion, platform); if metaData <> nil then begin latestVersionInfo := GetPackageLatestVersion(cancellationToken, item.id, compilerVersion, platform); if latestVersionInfo <> nil then begin metaData.LatestVersion := latestVersionInfo.LatestVersion; metaData.LatestStableVersion := latestVersionInfo.LatestStableVersion; Result.Results.Add(metaData); end; end; end; end; //function TDirectoryPackageRepository.GetPackageLatestVersions(const cancellationToken: ICancellationToken; const ids: IList<IPackageId>; const platform: TDPMPlatform; const compilerVersion: TCompilerVersion): IDictionary<string, IPackageLatestVersionInfo>; //var // i : integer; // j : integer; // id : string; // searchFiles : IList<string>; // regex : TRegEx; // searchRegex : string; // packageFile : string; // match : TMatch; // packageVersion : TPackageVersion; // latestVersion : TPackageVersion; // latestStableVersion : TPackageVersion; // info : IPackageLatestVersionInfo; //begin // result := TCollections.CreateDictionary<string, IPackageLatestVersionInfo>; // // searchRegEx := GetSearchRegex(compilerVersion, [], ''); // regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); // // for i := 0 to ids.Count -1 do // begin // id := ids.Items[i].Id; // searchFiles := DoExactList(id, compilerVersion, platform, ''); // latestVersion := TPackageVersion.Empty; // latestStableVersion := TPackageVersion.Empty; // for j := 0 to searchFiles.Count -1 do // begin // packageFile := ChangeFileExt(ExtractFileName(searchFiles[j]), ''); // match := regex.Match(packageFile); // if match.Success then // begin // if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then // continue; // // if packageVersion > latestVersion then // latestVersion := packageVersion; // // if packageVersion.IsStable and (packageVersion > latestStableVersion) then // latestStableVersion := packageVersion; // end; // //if latestVersion is empt then we didn't find any files! // if not latestVersion.IsEmpty then // begin // info := TDPMPackageLatestVersionInfo.Create(id,latestStableVersion, latestVersion); // result[id] := info; // end; // end; // end; //end; function TDirectoryPackageRepository.GetPackageMetaData(const cancellationToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform): IPackageSearchResultItem; var packageFileName : string; readSpecFunc : TReadSpecFunc; metaData : IPackageMetadata; begin result := nil; packageFileName := Format('%s-%s-%s-%s.dpkg', [packageId, CompilerToString(compilerVersion), DPMPlatformToString(platform), packageVersion]); packageFileName := IncludeTrailingPathDelimiter(SourceUri) + packageFileName; if not FileExists(packageFileName) then exit; if cancellationToken.IsCancelled then exit; readSpecFunc := function (const name : string; const spec : IPackageSpec) : IInterface begin result := TPackageMetadata.CreateFromSpec(name, spec); end; metaData := DoGetPackageMetaData(cancellationToken, packageFileName, readSpecFunc) as IPackageMetaData; if metaData <> nil then result := TDPMPackageSearchResultItem.FromMetaData(name, metaData); end; function TDirectoryPackageRepository.GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const preRelease : boolean) : IList<TPackageVersion>; var searchFiles : IList<string>; regex : TRegEx; searchRegex : string; packageFile : string; match : TMatch; i : integer; packageVersion : TPackageVersion; begin result := TCollections.CreateList<TPackageVersion>; searchFiles := DoExactList(id, compilerVersion, TDPMPlatform.UnknownPlatform, ''); searchRegEx := GetSearchRegex(compilerVersion, [], ''); regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); for i := 0 to searchFiles.Count - 1 do begin //ensure that the files returned are actually packages packageFile := ChangeFileExt(ExtractFileName(searchFiles[i]), ''); match := regex.Match(packageFile); if match.Success then begin if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then continue; if (not preRelease) and (not packageVersion.IsStable) then continue; result.Add(packageVersion); end; end; //no point sorting here or making results distinct as the the repo manager will do both. end; function TDirectoryPackageRepository.GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>; var searchFiles : IList<string>; regex : TRegEx; searchRegex : string; packageFile : string; match : TMatch; i : integer; packageVersion : TPackageVersion; packageInfo : IPackageInfo; readSpecFunc : TReadSpecFunc; begin result := TCollections.CreateList<IPackageInfo>; searchFiles := DoExactList(id, compilerVersion, platform, ''); searchRegEx := GetSearchRegex(compilerVersion, [platform], ''); regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); readSpecFunc := function (const name : string; const spec : IPackageSpec) : IInterface begin result := TPackageInfo.CreateFromSpec(name, spec); end; for i := 0 to searchFiles.Count - 1 do begin //ensure that the files returned are actually packages packageFile := ChangeFileExt(ExtractFileName(searchFiles[i]), ''); match := regex.Match(packageFile); if match.Success then begin if not TPackageVersion.TryParse(match.Groups[4].Value, packageVersion) then continue; //todo : check this is correct. if not versionRange.IsSatisfiedBy(packageVersion) then continue; if not prerelease then if not packageVersion.IsStable then continue; packageInfo := DoGetPackageMetadata(cancellationToken, searchFiles[i], readSpecFunc) as IPackageInfo; result.Add(packageInfo); end; end; result.Sort(TComparer<IPackageInfo>.Construct( function(const Left, Right : IPackageInfo) : Integer begin result := right.Version.CompareTo(left.Version); ; end)); end; function CompilerVersionToSearchPart(const compilerVersion : TCompilerVersion) : string; begin case compilerVersion of TCompilerVersion.UnknownVersion : result := '*'; else result := CompilerToString(compilerVersion); end; end; function TDirectoryPackageRepository.DoExactList(const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const version : string) : IList<string>; var searchTerm : string; //files : TStringDynArray; fileList : IList<string>; begin result := TCollections.CreateList < string > ; searchTerm := id; searchTerm := searchTerm + '-' + CompilerVersionToSearchPart(compilerVersion); if platform = TDPMPlatform.UnknownPlatform then searchTerm := searchTerm + '-*' else searchTerm := searchTerm + '-' + DPMPlatformToString(platform); if version <> '' then searchTerm := searchTerm + '-' + version + cPackageFileExt else searchTerm := searchTerm + '-*' + cPackageFileExt; try fileList := TDirectoryUtils.GetFiles(SourceUri, searchTerm); //dedupe result.AddRange(fileList.Distinct(TStringComparer.OrdinalIgnoreCase)); except on e : Exception do begin Logger.Error('Error searching source [' + Name + '] : ' + e.Message); end; end; end; function TDirectoryPackageRepository.DoGetPackageFeedFiles(const searchTerm : string; const exact : boolean; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IList<string>; var files : IList<string>; query : string; begin Logger.Debug('TDirectoryPackageRepository.DoGetPackageFeedFiles'); result := TCollections.CreateList<string>; query := searchTerm; if (query <> '*') and (not exact) then query := '*' + query + '*'; query := query + '-' + CompilerVersionToSearchPart(compilerVersion) + '-' + DPMPlatformToString(platform) + '-' + '*' + cPackageFileExt; files := TDirectoryUtils.GetFiles(SourceUri, query); result.AddRange(files); end; type TPackageFind = record Id : string; Platform : TDPMPlatform; LatestVersion : TPackageVersion; LatestStableVersion : TPackageVersion; end; function TDirectoryPackageRepository.DoGetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const files : IList<string>) : IList<IPackageSearchResultItem>; var searchRegEx : string; regex : TRegEx; match : TMatch; i : integer; packageFileName : string; id : string; platform : TDPMPlatform; versionString : string; packageVersion : TPackageVersion; packageLookup : IDictionary<string, TPackageFind>; find : TPackageFind; packageMetaData : IPackageMetadata; resultItem : IPackageSearchResultItem; readSpecFunc : TReadSpecFunc; begin Logger.Debug('TDirectoryPackageRepository.DoGetPackageFeed'); result := TCollections.CreateList<IPackageSearchResultItem>; packageLookup := TCollections.CreateDictionary<string, TPackageFind> ; searchRegEx := GetSearchRegex(options.CompilerVersion, options.Platforms, ''); regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); //work out the latest version for each package and what platforms it supports. for i := 0 to files.Count - 1 do begin if cancelToken.IsCancelled then exit; //ensure that the files returned are actually packages packageFileName := ChangeFileExt(ExtractFileName(files[i]), ''); match := regex.Match(packageFileName); if match.Success then begin id := match.Groups[1].Value; //ignore the matched compiler version since we are only ever looking at 1 compiler version //cv := StringToCompilerVersion(match.Groups[2].Value); platform := StringToDPMPlatform(match.Groups[3].Value); versionString := match.Groups[4].Value; if not TPackageVersion.TryParse(versionString, packageVersion) then continue; if not options.Prerelease then if not packageVersion.IsStable then continue; if not packageLookup.TryGetValue(LowerCase(id), find) then begin find.Id := id; find.Platform := platform; find.LatestVersion := packageVersion; if packageVersion.IsStable then find.LatestStableVersion := packageVersion; packageLookup[LowerCase(id)] := find; end else begin if packageVersion > find.LatestVersion then find.LatestVersion := packageVersion; if packageVersion.IsStable then if packageVersion > find.LatestStableVersion then find.LatestStableVersion := packageVersion; packageLookup[LowerCase(id)] := find; end; end; end; readSpecFunc := function (const name : string; const spec : IPackageSpec) : IInterface begin result := TPackageMetadata.CreateFromSpec(name, spec); end; //now we can use the info collected above to build actual results. for find in packageLookup.Values do begin if cancelToken.IsCancelled then exit; resultItem := nil; packageMetaData := nil; if cancelToken.IsCancelled then exit; packageFileName := Format('%s-%s-%s-%s.dpkg', [find.Id, CompilerToString(options.CompilerVersion), DPMPlatformToString(find.platform), find.LatestVersion.ToStringNoMeta]); packageFileName := IncludeTrailingPathDelimiter(SourceUri) + packageFileName; if not FileExists(packageFileName) then exit; packageMetadata := DoGetPackageMetaData(cancelToken, packageFileName, readSpecFunc) as IPackageMetadata; if packageMetadata <> nil then begin resultItem := TDPMPackageSearchResultItem.FromMetaData(Self.Name, packageMetadata); resultItem.LatestVersion := find.LatestVersion; resultItem.LatestStableVersion := find.LatestStableVersion; result.Add(resultItem); end; end; end; function TDirectoryPackageRepository.DoGetPackageMetaData(const cancellationToken : ICancellationToken; const fileName : string; const readSpecFunc : TReadSpecFunc) : IInterface; var zipFile : TZipFile; metaBytes : TBytes; metaString : string; spec : IPackageSpec; reader : IPackageSpecReader; extractedFile : string; svgIconFileName : string; pngIconFileName : string; iconBytes : TBytes; isSvg : boolean; begin Logger.Debug('TDirectoryPackageRepository.DoGetPackageMetaData'); result := nil; reader := TPackageSpecReader.Create(Logger); //first see if the spec has been extracted already. extractedFile := ChangeFileExt(fileName, '.dspec'); if FileExists(extractedFile) then begin spec := reader.ReadSpec(extractedFile); if spec <> nil then begin result := TPackageMetadata.CreateFromSpec(Name, spec); exit; end; end; if not FileExists(fileName) then exit; zipFile := TZipFile.Create; try try zipFile.Open(fileName, TZipMode.zmRead); zipFile.Read(cPackageMetaFile, metaBytes); //we will take this opportunity to extract the icon file here //for later use. isSvg := false; svgIconFileName := ChangeFileExt(filename, '.svg'); if not FileExists(svgIconFileName) then begin if zipFile.IndexOf(cIconFileSVG) <> -1 then begin zipFile.Read(cIconFileSVG, iconBytes); isSvg := true; end; end else isSvg := true; pngIconFileName := ChangeFileExt(filename, '.png'); if (not isSvg) and not FileExists(pngIconFileName) then begin if zipFile.IndexOf(cIconFilePNG) <> -1 then begin zipFile.Read(cIconFilePNG, iconBytes); isSvg := false; end; end; except on e : Exception do begin Logger.Error('Error opening package file [' + fileName + ']'); exit; end; end; finally zipFile.Free; end; //doing this outside the try/finally to avoid locking the package for too long. metaString := TEncoding.UTF8.GetString(metaBytes); spec := reader.ReadSpecString(metaString); if spec = nil then exit; result := readSpecFunc(name, spec); if not FPermissionsChecked then begin FIsWritable := TDirectoryUtils.IsDirectoryWriteable(ExtractFilePath(fileName)); FPermissionsChecked := true; end; if FIsWritable then begin try //TODO : Could this cause an issue if multiple users attempt this on a shared folder? //may need to use a lock file. TFile.WriteAllText(extractedFile, metaString, TEncoding.UTF8); if Length(iconBytes) > 0 then if isSvg then TFile.WriteAllBytes(svgIconFileName, iconBytes) else TFile.WriteAllBytes(pngIconFileName, iconBytes) except //even though we test for write access other errors might occur (eg with network drives disconnected etc). end; end; end; function TDirectoryPackageRepository.DoList(searchTerm : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IList<string>; //var // files : TStringDynArray; // fileList : IList<string>; begin // result := TCollections.CreateList<string>; if searchTerm <> '*' then searchTerm := '*' + searchTerm + '*'; searchTerm := searchTerm + '-' + CompilerVersionToSearchPart(compilerVersion); if platform = TDPMPlatform.UnknownPlatform then searchTerm := searchTerm + '-*-*' + cPackageFileExt else searchTerm := searchTerm + '-' + DPMPlatformToString(platform) + '-*' + cPackageFileExt; result := TDirectoryUtils.GetFiles(SourceUri, searchTerm); //fileList := TCollections.CreateList<string>(files); //TODO : Does this really need to be de-duped? //dedupe //result.AddRange(TEnumerable.Distinct<string>(fileList, TStringComparer.OrdinalIgnoreCase )); end; function TDirectoryPackageRepository.List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>; var searchTerms : TArray<string>; searchFiles : IList<string>; allFiles : IList<string>; i : integer; platform : TDPMPlatform; searchRegEx : string; regex : TRegEx; packageFile : string; match : TMatch; id : string; cv : TCompilerVersion; version : string; packageVersion : TPackageVersion; currentCompiler : TCompilerVersion; currentId : string; currentVersion : TPackageVersion; platforms : TDPMPlatforms; newItem : IPackageListItem; bIsLast : boolean; procedure AddCurrent; begin newItem := TPackageListItem.Create(currentId,currentCompiler, currentVersion, DPMPlatformsToString(platforms)); result.Add(newItem); end; begin result := TCollections.CreateList<IPackageListItem>; if options.SearchTerms <> '' then searchTerms := TStringUtils.SplitStr(Trim(options.SearchTerms), ' '); //need at least 1 search term, if there are none then search for *. if length(searchTerms) = 0 then begin SetLength(searchTerms, 1); searchTerms[0] := '*'; end; allFiles := TCollections.CreateList < string > ; for i := 0 to Length(searchTerms) - 1 do begin if cancellationToken.IsCancelled then exit; if options.Platforms = [] then begin if options.Exact then searchFiles := DoExactList(searchTerms[i], options.CompilerVersion, TDPMPlatform.UnknownPlatform, options.Version.ToStringNoMeta) else searchFiles := DoList(searchTerms[i], options.CompilerVersion, TDPMPlatform.UnknownPlatform); allFiles.AddRange(searchFiles); end else begin for platform in options.Platforms do begin if cancellationToken.IsCancelled then exit; if options.Exact then searchFiles := DoExactList(searchTerms[i], options.CompilerVersion, platform, options.Version.ToStringNoMeta) else searchFiles := DoList(searchTerms[i], options.CompilerVersion, platform); allFiles.AddRange(searchFiles); end; end; end; //remove the path from the files for i := 0 to allFiles.Count -1 do allFiles[i] := ChangeFileExt(ExtractFileName(allFiles[i]), ''); allFiles.Sort; //do we really need to do a regex check here? searchRegEx := GetSearchRegex(options.CompilerVersion, options.Platforms, options.Version.ToStringNoMeta); regex := TRegEx.Create(searchRegEx, [roIgnoreCase]); currentId := ''; currentVersion := TPackageVersion.Empty; currentCompiler := TCompilerVersion.UnknownVersion; platforms := []; for i := 0 to allFiles.Count - 1 do begin bIsLast := i = allFiles.Count -1; //ensure that the files returned are actually packages packageFile := allFiles[i]; match := regex.Match(packageFile); if match.Success then begin id := match.Groups[1].Value; cv := StringToCompilerVersion(match.Groups[2].Value); platform := StringToDPMPlatform(match.Groups[3].Value); version := match.Groups[4].Value; if not TPackageVersion.TryParse(version, packageVersion) then continue; if not options.Prerelease then if not packageVersion.IsStable then continue; //if the id, compiler or version change then start a new listitem - same if it's the last entry in the list. if (id <> currentId) or (cv <> currentCompiler) or (packageVersion <> currentVersion) or bIsLast then begin //higher version, start again if (id = currentId) and (cv = currentCompiler) and (packageVersion <> currentVersion) then begin //lower version, just ignore it. if packageVersion < currentVersion then begin if bIsLast then AddCurrent; continue; end; //higher version, start again. currentId := id; currentCompiler := cv; currentVersion := packageVersion; platforms := [platform]; if bIsLast then AddCurrent; continue; end; // a new package, so record the last one if we had one. if (currentId <> '') and (currentCompiler <> TCompilerVersion.UnknownVersion) then begin if bIsLast then Include(platforms, platform); AddCurrent; end; currentId := id; currentCompiler := cv; currentVersion := packageVersion; platforms := [platform]; end else begin Include(platforms, platform); if bIsLast then AddCurrent; end; end; end; end; function TDirectoryPackageRepository.Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions): Boolean; var targetFile : string; begin result := false; // if TPath.IsRelativePath(pushOptions.PackagePath) then pushOptions.PackagePath := TPath.GetFullPath(pushOptions.PackagePath); if not FileExists(pushOptions.PackagePath) then begin Logger.Error('Package file [' + pushOptions.PackagePath + '] not found.'); exit; end; if not DirectoryExists(SourceUri) then begin Logger.Error('Source uri path does not exist [' + SourceUri + '].'); exit; end; try targetFile := TPath.Combine(SourceUri, TPath.GetFileName(pushOptions.PackagePath)); if pushOptions.SkipDuplicate and TFile.Exists(targetFile) then begin Logger.Information('Package [' + TPath.GetFileName(pushOptions.PackagePath) + '] exists and skipDuplicates specified, skipping'); exit(true); end; TFile.Copy(pushOptions.PackagePath, targetFile, true); Logger.Information('Package pushed ok.', true); result := true; except on e : Exception do begin Logger.Error('Unable to copy file [' + pushOptions.PackagePath + '] to [' + SourceUri + '] : ' + e.Message); end; end; end; end.
unit uDMGlobal; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, siComp, ImgList, siLangRT, uSQLObj; const LANG_ENGLISH = 1; LANG_PORTUGUESE = 2; LANG_SPANISH = 3; LANG_DIRECTORY = 'Translation\'; type TDMGlobal = class(TDataModule) LanguageDispatcher: TsiLangDispatcher; imgSmall: TImageList; imgLarge: TImageList; private FIDLanguage : integer; FIDUser : integer; FIDUserType : integer; FUserName : string; FIDDefaultStore : integer; FIDCommission : integer; FIDDefaultCompany : integer; FCompanyName : string; FIDDefaultCashRed : integer; FLangFilesPath : String; procedure SetLanguage(ID:Integer); public { Public declarations } //Main Retail property IDUser : Integer read FIDUser write FIDUser; property IDUserType : Integer read FIDUserType write FIDUserType; property UserName : String read FUserName write FUserName; property IDDefaulStore : Integer read FIDDefaultStore write FIDDefaultStore; property IDCommission : Integer read FIDCommission write FIDCommission; property IDDefaultCompany : Integer read FIDDefaultCompany write FIDDefaultCompany; property CompanyName : String read FCompanyName write FCompanyName; property IDLanguage : Integer read FIDLanguage write SetLanguage; property IDDefaultCashReg : Integer read FIDDefaultCashRed write FIDDefaultCashRed; property LangFilesPath : String read FLangFilesPath write FLangFilesPath; end; var DMGlobal: TDMGlobal; implementation {$R *.DFM} procedure TDMGlobal.SetLanguage(ID:Integer); begin FIDLanguage := ID; LanguageDispatcher.ActiveLanguage := ID; end; end.
{ *********************************************************************** } { } { GUI Hangman } { Version 1.0 - First release of program } { Last Revised: 27nd of July 2004 } { Copyright (c) 2004 Chris Alley } { } { *********************************************************************** } unit UAbout; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Jpeg; type TAboutDialog = class(TForm) AboutGroupBox: TGroupBox; OKButton: TButton; TitleLabel: TLabel; VersionLabel: TLabel; CopyrightLabel: TLabel; FreewareLabel: TLabel; ProgrammedByLabel: TLabel; GraphicsAndSoundEffectsLabel: TLabel; CreatedWithLabel: TLabel; DividerPanel: TPanel; ImagePanel: TPanel; AboutImage: TImage; BasedOnLabel: TLabel; CheatPanel1: TPanel; CheatPanel2: TPanel; CheatPanel3: TPanel; CheatPanel4: TPanel; procedure FormCreate(Sender: TObject); procedure CheatPanelClick(Sender: TObject); procedure CheatPanel1Click(Sender: TObject); procedure CheatPanel2Click(Sender: TObject); procedure CheatPanel3Click(Sender: TObject); procedure CheatPanel4Click(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TAboutDialog.FormCreate(Sender: TObject); { Sets all of the components on the About form to their default states. } begin Self.OKButton.Default := True; Self.AboutImage.Picture.LoadFromFile('Images/AboutScreen.jpg'); Self.CheatPanel1.Enabled := True; Self.CheatPanel2.Enabled := False; Self.CheatPanel3.Enabled := False; Self.CheatPanel4.Enabled := False; end; procedure TAboutDialog.CheatPanelClick(Sender: TObject); { The following procedures are used to activate and deactivate the game's cheats. If the user presses the four hidden panels in the correct order then the cheat will turn on. } begin Self.ModalResult := mrYes; end; procedure TAboutDialog.CheatPanel1Click(Sender: TObject); begin Self.CheatPanel2.Enabled := True; Self.CheatPanel1.Enabled := False; end; procedure TAboutDialog.CheatPanel2Click(Sender: TObject); begin Self.CheatPanel3.Enabled := True; Self.CheatPanel2.Enabled := False; end; procedure TAboutDialog.CheatPanel3Click(Sender: TObject); begin Self.CheatPanel4.Enabled := True; Self.CheatPanel3.Enabled := False; end; procedure TAboutDialog.CheatPanel4Click(Sender: TObject); begin Self.ModalResult := mrYes; Self.CheatPanel1.Enabled := False; end; end.
{----------------------------------------------------------------------------- Unit Name: cPyRemoteDebugger Author: Kiriakos Vlahos Date: 23-April-2006 Purpose: History: Remote debugger based on rppdb2 -----------------------------------------------------------------------------} unit cPyRemoteDebugger; interface implementation uses Windows, SysUtils, Classes, uEditAppIntfs, PythonEngine, Forms, Contnrs, cPyBaseDebugger; type TRemFrameInfo = class(TBaseFrameInfo) private fPyFrame: Variant; protected // Implementation of the Base class for the internal debugger function GetFunctionName : string; override; function GetFileName : string; override; function GetLine : integer; override; published public constructor Create(Frame : Variant); property PyFrame : Variant read fPyFrame; end; TRemNameSpaceItem = class(TBaseNameSpaceItem) // Implementation of the Base class for the internal debugger private fChildNodes : TObjectList; fName : string; protected function GetName : string; override; function GetObjectType : string; override; function GetValue : string; override; function GetDocString : string; override; function GetChildCount : integer; override; function GetChildNode(Index: integer): TBaseNameSpaceItem; override; public constructor Create(aName : string; aPyObject : Variant); destructor Destroy; override; function IsDict : Boolean; override; function IsModule : Boolean; override; function IsFunction : Boolean; override; function IsMethod : Boolean; override; function Has__dict__ : Boolean; override; procedure GetChildNodes; override; end; TPyRemDebugger = class(TPyBaseDebugger) // pdb based internal debugger protected procedure SetDebuggerBreakpoints; public constructor Create; procedure Run(Editor : IEditor; InitStepIn : Boolean = False); override; procedure RunToCursor(Editor : IEditor; ALine: integer); override; procedure StepInto(Editor : IEditor); override; procedure StepOver; override; procedure StepOut; override; procedure Pause; override; procedure Abort; override; procedure Evaluate(const Expr : string; out ObjType, Value : string); override; procedure GetCallStack(CallStackList : TObjectList); override; function GetFrameGlobals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; override; function GetFrameLocals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; override; end; { TRemFrameInfo } constructor TRemFrameInfo.Create(Frame: Variant); begin end; function TRemFrameInfo.GetFileName: string; begin Result := ''; end; function TRemFrameInfo.GetFunctionName: string; begin Result := ''; end; function TRemFrameInfo.GetLine: integer; begin Result := 0; end; { TRemNameSpaceItem } constructor TRemNameSpaceItem.Create(aName: string; aPyObject: Variant); begin end; destructor TRemNameSpaceItem.Destroy; begin if Assigned(fChildNodes) then fChildNodes.Free; inherited; end; function TRemNameSpaceItem.GetChildCount: integer; begin Result := 0; end; function TRemNameSpaceItem.GetChildNode(Index: integer): TBaseNameSpaceItem; begin Result := nil; end; procedure TRemNameSpaceItem.GetChildNodes; begin end; function TRemNameSpaceItem.GetDocString: string; begin Result := ''; end; function TRemNameSpaceItem.GetName: string; begin Result := fName; end; function TRemNameSpaceItem.GetObjectType: string; begin Result := ''; end; function TRemNameSpaceItem.GetValue: string; begin Result := ''; end; function TRemNameSpaceItem.Has__dict__: Boolean; begin Result := False; end; function TRemNameSpaceItem.IsDict: Boolean; begin Result := False; end; function TRemNameSpaceItem.IsFunction: Boolean; begin Result := False; end; function TRemNameSpaceItem.IsMethod: Boolean; begin Result := False; end; function TRemNameSpaceItem.IsModule: Boolean; begin Result := False; end; { TPyRemDebugger } procedure TPyRemDebugger.Abort; begin end; constructor TPyRemDebugger.Create; begin end; procedure TPyRemDebugger.Evaluate(const Expr: string; out ObjType, Value: string); begin end; procedure TPyRemDebugger.GetCallStack(CallStackList: TObjectList); begin end; function TPyRemDebugger.GetFrameGlobals( Frame: TBaseFrameInfo): TBaseNameSpaceItem; begin Result := nil; end; function TPyRemDebugger.GetFrameLocals( Frame: TBaseFrameInfo): TBaseNameSpaceItem; begin Result := nil; end; procedure TPyRemDebugger.Pause; begin end; procedure TPyRemDebugger.Run(Editor: IEditor; InitStepIn: Boolean); begin end; procedure TPyRemDebugger.RunToCursor(Editor: IEditor; ALine: integer); begin end; procedure TPyRemDebugger.SetDebuggerBreakpoints; begin end; procedure TPyRemDebugger.StepInto(Editor: IEditor); begin end; procedure TPyRemDebugger.StepOut; begin end; procedure TPyRemDebugger.StepOver; begin end; end.
unit USnakeList; interface uses UTypes; type TSnakeList = ^TSnakeItem; TSnakeItem = record data: TSnakeData; next: TSnakeList; end; procedure addHeadItem(snake: TSnakeList; data: TSnakeData); function deleteTailItem(snake: TSnakeList):TSnakeData; function returnHead(snake: TSnakeList):TSnakeData; procedure createSnake(var snake: TSnakeList); procedure destroySnake(var snake: TSnakeList); function returnSnake(snake: TSnakeList):TSnake; procedure fillSnake(snakeArray: TSnake; snake: TSnakeList); implementation function isEmpty(snake: TSnakeList):Boolean; begin result := snake^.next = nil; end; procedure insert(snake: TSnakeList; data: TSnakeData); var temp: TSnakeList; begin new(temp); temp^.data := data; temp^.next := snake^.next; snake^.next := temp; end; procedure delete(snake: TSnakeList); var temp: TSnakeList; begin temp := snake^.next; snake^.next := temp^.next; dispose(temp); end; procedure addHeadItem(snake: TSnakeList; data: TSnakeData); begin insert(snake, data); end; function returnHead(snake: TSnakeList):TSnakeData; begin result := snake^.next^.data; end; function deleteTailItem(snake: TSnakeList):TSnakeData; begin while not isEmpty(snake^.next) do snake := snake^.next; result := snake^.next^.data; delete(snake); end; procedure clearSnake(snake: TSnakeList); begin while not isEmpty(snake) do delete(snake); end; procedure createSnake(var snake: TSnakeList); begin new(snake); snake^.next := nil; end; procedure destroySnake(var snake: TSnakeList); begin clearSnake(snake); dispose(snake); snake := nil; end; function returnSnake(snake: TSnakeList):TSnake; var i: Integer; begin i := 1; while not isEmpty(snake) do begin result[i] := snake^.next^.data; snake := snake^.next; inc(i); end; while i <= length(result) do begin result[i].cell.x := -1; inc(i); end; end; procedure fillSnake(snakeArray: TSnake; snake: TSnakeList); var i: Integer; begin for i := length(snakeArray) downto 1 do begin if snakeArray[i].cell.x <> -1 then addHeadItem(snake, snakeArray[i]); end; end; end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ActnList; type TF_Main = class(TForm) AL_Main: TActionList; A_Seconds: TAction; A_Help: TAction; A_Maximize: TAction; L_Time: TLabel; procedure P_TimeResize(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure A_SecondsExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure A_HelpExecute(Sender: TObject); procedure A_MaximizeExecute(Sender: TObject); private { Private declarations } public procedure UpdateStatus(status:string; color:TColor = clBlack); procedure UpdateTime(time:string; color:TColor = clBlack); end; var F_Main: TF_Main; implementation {$R *.dfm} uses tcpClient, globConfig, modelTime, version; //////////////////////////////////////////////////////////////////////////////// procedure TF_Main.A_SecondsExecute(Sender: TObject); begin config.data.seconds := not config.data.seconds; if (client.status = TPanelConnectionStatus.opened) then begin mt.Show(); Self.P_TimeResize(Self); end; end; //////////////////////////////////////////////////////////////////////////////// procedure TF_Main.FormClose(Sender: TObject; var Action: TCloseAction); begin try config.SaveFile(); except end; try client.Disconnect(); except on E:Exception do Application.MessageBox(PChar(E.Message), 'Chyba', MB_OK or MB_ICONERROR); end; end; procedure TF_Main.FormCreate(Sender: TObject); begin Self.Caption := Application.Title + ' v' + GetVersion(Application.ExeName); end; //////////////////////////////////////////////////////////////////////////////// procedure TF_Main.P_TimeResize(Sender: TObject); var w, h:Integer; const _OFFSET = 10; begin w := Self.L_Time.Canvas.TextWidth(Self.L_Time.Caption); h := Self.L_Time.Canvas.TextHeight(Self.L_Time.Caption); while ((w < Self.ClientWidth - _OFFSET * 2) and (h < Self.ClientHeight - _OFFSET * 2)) do begin Self.L_Time.Font.Size := Self.L_Time.Font.Size + 1; w := Self.L_Time.Canvas.TextWidth(Self.L_Time.Caption); h := Self.L_Time.Canvas.TextHeight(Self.L_Time.Caption); end; while (((w > Self.ClientWidth - _OFFSET * 2) or (h > Self.ClientHeight - _OFFSET * 2)) and (Self.L_Time.Font.Size > 1)) do begin Self.L_Time.Font.Size := Self.L_Time.Font.Size - 1; w := Self.L_Time.Canvas.TextWidth(Self.L_Time.Caption); h := Self.L_Time.Canvas.TextHeight(Self.L_Time.Caption); end; Self.L_Time.Width := w; Self.L_Time.Height := h; Self.L_Time.Left := (Self.ClientWidth div 2) - (Self.L_Time.Width div 2); Self.L_Time.Top := (Self.ClientHeight div 2) - (Self.L_Time.Height div 2); end; //////////////////////////////////////////////////////////////////////////////// procedure TF_Main.UpdateStatus(status:string; color:TColor = clBlack); begin Self.L_Time.Caption := status; Self.L_Time.Font.Color := color; Self.P_TimeResize(Self); end; procedure TF_Main.UpdateTime(time:string; color:TColor = clBlack); begin Self.L_Time.Caption := time; Self.L_Time.Font.Color := color; end; //////////////////////////////////////////////////////////////////////////////// procedure TF_Main.A_HelpExecute(Sender: TObject); begin Application.MessageBox(PChar('hJOPclock v' + GetVersion(Application.ExeName)+'.'+#13#10+ 'Vytvořil Jan Horáček pro KMŽ Brno I'), 'Informace', MB_OK or MB_ICONINFORMATION) end; //////////////////////////////////////////////////////////////////////////////// procedure TF_Main.A_MaximizeExecute(Sender: TObject); begin if (Self.BorderStyle = bsNone) then begin Self.BorderStyle := bsSizeable; end else begin Self.BorderStyle := bsNone; Self.WindowState := wsMaximized; end; end; //////////////////////////////////////////////////////////////////////////////// end.
unit XLSUtils2; {- ******************************************************************************** ******* XLSReadWriteII V3.00 ******* ******* ******* ******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$H+} {$R-} {$I XLSRWII2.inc} interface uses Classes, SysUtils, Windows, BIFFRecsII2, {$ifndef LINUX} Graphics, {$endif} Math; //* ~exclude type PRecPTGS = ^TRecPTGS; TRecPTGS = packed record Size: word; PTGS: PByteArray; end; {$ifdef LINUX} type TColor = -$7FFFFFFF-1..$7FFFFFFF; {$endif} //* ~exclude type PWordBool = ^WordBool; //* ~exclude type TByte8Array = array[0..7] of byte; //* ~exclude type TByte4Array = array[0..3] of byte; {$ifdef OLD_COMPILER} type PWord = ^word; type PInteger = ^integer; {$endif} //* ~exclude type TDynByteArray = array of byte; //* ~exclude type TDynDoubleArray = array of double; //* ~exclude type PLongWordArray = ^TLongWordArray; //* ~exclude TLongWordArray = array[0..8191] of Longword; //* ~exclude type TFormulaNameType = (ntName,ntExternName,ntExternSheet,ntCurrBook,ntCellValue); //* ~exclude type TFormulaValType = (fvFloat,fvBoolean,fvError,fvString,fvRef,fvArea,fvExtRef,fvExtArea,fvNull); //* ~exclude const TFormulaValTypeRef = [fvRef,fvArea,fvExtRef,fvExtArea]; //* Type used to define the results of formulas. type TFormulaValue = record // String memory is handled by the compiler, can therefore not be in the // variant part. vString: WideString; case ValType: TFormulaValType of fvFloat : (vFloat: double); fvBoolean : (vBoolean: boolean); fvError : (vError: TCellError); fvString : (xvString: boolean); // Col,Row fvRef : (vRef: array[0..1] of word); // Col1,Row1,Col2,Row2 fvArea : (vArea: array[0..3] of word); // Col,Row,Sheet fvExtRef : (vExtRef: array[0..2] of word); // Col1,Row1,Col2,Row2,Sheet fvExtArea : (vExtArea: array[0..4] of word); end; type TFormulaValueArray = array of TFormulaValue; //* Event with an integer value. //* ~param Sender Sender object. //* ~param Value An integer value. type TIntegerEvent = procedure (Sender: TObject; Value: integer) of object; //* ~exclude type TCellEvent = procedure (Col,Row: integer) of object; //* ~exclude type TColRowSizeEvent = procedure(Sender: TObject; ColRow,FormatIndex,Size: integer) of object; //* FuncName is the name of the function. Args are the functions arguments, from //* left to right. If the function don't have any arguments, the array size is //* zero. Result is the result of the calculation. If the function not can be //* calculated, set Result to NULL //* ~param Sender Sender object. //* ~param FuncName The name of the function. //* ~param Args An TFormulaValue array with the arguments to the function. //* ~param Result The result of the formula calculation. type TFunctionEvent = procedure(Sender: TObject; FuncName: string; Args: array of TFormulaValue; var Result: TFormulaValue) of object; //* Event used when a password is required in order to open an encrypted file. //* ~param Sender Sender object. //* ~param Password Set Password to the password that the file is encrypted with. type TPasswordEvent = procedure(Sender: TObject; var Password: WideString) of object; //* ~exclude type TFormulaErrorEvent = procedure(Sender: TObject; ErrorId: integer; ErrorStr: WideString) of object; //* ~exclude type TGetDefaultFormatEvent = function (Col,Row: integer): word of object; //* Options when copying and moving cells. type TCopyCellsOption = (ccoAdjustCells, //* Adjust relative cells according to the new location. ccoLockStartRow, //* Don't adjust the first row. ccoForceAdjust, //* Adjust absolute cell references as well. ccoCopyValues, //* Copy cell values. ccoCopyShapes, //* Copy shape objects. ccoCopyNotes, //* Copy cell notes. ccoCopyCondFmt, //* Copy conditional formats. ccoCopyValidations, //* Copy cell validations. ccoCopyMerged //* Copy merged cells. ); TCopyCellsOptions = set of TCopyCellsOption; //* What parts of the data on a worksheet that shall be copied/moved. const CopyAllCells = [ccoCopyValues, //* Cell values ccoCopyShapes, //* Drawing shapes. ccoCopyNotes, //* Cell notes. ccoCopyCondFmt, //* Conditional formats. ccoCopyValidations, //* Cell validations. ccoCopyMerged //* Merged cells. ]; const ExcelPictureTypes: array[0..6] of string = ('wmf','emf','pic','jpg','jpeg','png','bmp'); const ExcelPictureTypesFilter: string = 'Picture files|*.wmf;*.emf;*.pic;*.jpg;*.jpeg;*.png;*.bmp|All files (*.*)|*.*'; //* ~exclude type ICellOperations = interface procedure DeleteCells(Sheet, Col1, Row1, Col2, Row2: integer); procedure CopyCells(SrcSheet,Col1,Row1,Col2,Row2,DestSheet,DestCol,DestRow: integer; CopyOptions: TCopyCellsOptions = [ccoAdjustCells] + CopyAllCells); procedure MoveCells(SrcSheet,Col1,Row1,Col2,Row2,DestSheet,DestCol,DestRow: integer; CopyOptions: TCopyCellsOptions = [ccoAdjustCells] + CopyAllCells); end; //* ~exclude procedure FVClear(var FV: TFormulaValue); //* ~exclude procedure FVSetNull(var FV: TFormulaValue); //* ~exclude procedure FVSetFloat(var FV: TFormulaValue; Value: double); //* ~exclude procedure FVSetBoolean(var FV: TFormulaValue; Value: boolean); //* ~exclude procedure FVSetError(var FV: TFormulaValue; Value: TCellError); //* ~exclude procedure FVSetString(var FV: TFormulaValue; Value: WideString); //* ~exclude procedure FVSetRef(var FV: TFormulaValue; Col,Row: word); //* ~exclude procedure FVSetArea(var FV: TFormulaValue; Col1,Row1,Col2,Row2: word); //* ~exclude procedure FVSetXRef(var FV: TFormulaValue; Col,Row,Sheet: word); //* ~exclude procedure FVSetXArea(var FV: TFormulaValue; Col1,Row1,Col2,Row2,Sheet: word); //* ~exclude function FVGetFloat(FV: TFormulaValue): double; //* ~exclude function FVGetString(FV: TFormulaValue): WideString; //* ~exclude function FVGetBoolean(FV: TFormulaValue): boolean; //* ~exclude function FVGetVariant(FV: TFormulaValue): Variant; //* ~exclude function FVCompare(FV1,FV2: TFormulaValue; var Res: double): boolean; //* ~exclude function FVSize(FV: TFormulaValue): integer; //* Returns a cell position as it's string representation, like A1 //* ~param ACol Column. //* ~param ARow Row. //* ~param AbsCol True if Col shall be absolute, i.e preceeded with '$'. //* ~param AbsRow True if Row shall be absolute, i.e preceeded with '$'. //* ~result The string with the cell reference. function ColRowToRefStr(ACol,ARow: integer; AbsCol,AbsRow: boolean): string; //* Returns a cell area as it's string representation, like A1:D4 //* ~param Col1 Left column. //* ~param Row1 Top row. //* ~param Col2 Right column. //* ~param Row2 Bottom row. //* ~param AbsCol1 True if Col1 shall be absolute, i.e preceeded with '$'. //* ~param AbsRow1 True if Row1 shall be absolute, i.e preceeded with '$'. //* ~param AbsCol2 True if Col2 shall be absolute, i.e preceeded with '$'. //* ~param AbsRow2 True if Row2 shall be absolute, i.e preceeded with '$'. //* ~result The string with the area reference. function AreaToRefStr(Col1,Row1,Col2,Row2: integer; AbsCol1,AbsRow1,AbsCol2,AbsRow2: boolean): string; //* Splits a reference string into row and column values. //* ~param S A string with the cell reference in the format 'A1' //* ~param ACol Column. //* ~param ARow Column. //* ~param AbsCol True if the column is absolute, i.e preceeded with '$'. //* ~param AbsRow True if the row is absolute, i.e preceeded with '$'. //* ~result True if the string could be converted. function RefStrToColRow(S: string; var ACol,ARow: integer; var AbsCol,AbsRow: boolean): boolean; overload; //* Splits a reference string into row and column values. //* ~param S A string with the cell reference in the format 'A1' //* ~param ACol Column. //* ~param ARow Column. //* ~result True if the string could be converted. function RefStrToColRow(S: string; var ACol,ARow: integer): boolean; overload; //* Splits an area reference string into rows and columns values. //* ~param S A string with the area reference in the format 'A1:D5' //* ~param ACol1 Left column. //* ~param ARow1 Top row. //* ~param ACol2 Right column. //* ~param ARow2 Bottom row. //* ~param AbsCol1 True if Col1 is absolute, i.e preceeded with '$'. //* ~param AbsRow1 True if Row1 is absolute, i.e preceeded with '$'. //* ~param AbsCol2 True if Col2 is absolute, i.e preceeded with '$'. //* ~param AbsRow2 True if Row2 is absolute, i.e preceeded with '$'. //* ~result True if the string could be converted. function AreaStrToColRow(S: string; var ACol1,ARow1,ACol2,ARow2: integer; var AbsCol1,AbsRow1,AbsCol2,AbsRow2: boolean): boolean; overload; //* Splits an area reference string into rows and columns values. //* ~param S A string with the cell reference in the format 'A1' //* ~param ACol1 Left column. //* ~param ARow1 Top row. //* ~param ACol2 Right column. //* ~param ARow2 Bottom row. //* ~result True if the string could be converted. function AreaStrToColRow(S: string; var ACol1,ARow1,ACol2,ARow2: integer): boolean; overload; //* Splits an area reference string into rows and columns values. //* ~param S A string with the cell reference in the format 'A1' //* ~param ACol Column. //* ~param ARow Row. //* ~param AbsCol True if the column is absolute, i.e preceeded with '$'. //* ~param AbsRow True if the row is absolute, i.e preceeded with '$'. //* ~result True if the string could be converted. function RefStrToColRow(S: string; var ACol,ARow: word; var AbsCol,AbsRow: boolean): boolean; overload; {$ifdef LINUX} //* ~exclude function GetHashCode(const Buffer; Count: Integer): Word; {$else} //* ~exclude function GetHashCode(const Buffer; Count: Integer): Word; assembler; {$endif} //* ~exclude function CPos(C: char; S: string): integer; //* ~exclude function WCPos(C: WideChar; S: WideString): integer; //* ~exclude function ColRowToRC(Col, Row: integer): longword; //* ~exclude procedure SplitRC(RC: integer; var Col,Row: integer); //* ~exclude procedure NormalizeArea(var C1,R1,C2,R2: integer); //* ~exclude function IsMultybyteString(S: string): boolean; //* ~exclude function ToMultibyte1bHeader(S: string): string; //* ~exclude function UnicodeStorageSize(S: string): integer; //* ~exclude function UnicodeStringLen(S: string): integer; //* ~exclude function ExcelStrToString(P: PByteArray; CharCount: integer): string; //* ~exclude function ByteStrToWideString(P: PByteArray; CharCount: integer): WideString; //* ~exclude procedure WideStringToByteStr(S: WideString; P: PByteArray); //* ~exclude function HexToByte(S: string): byte; //* ~exclude function HexStringToByteArray(S: string; var PBytes: PByteArray): integer; //* ~exclude procedure HexStringToDynByteArray(S: string; var PBytes: TDynByteArray); //* ~exclude function ErrorCodeToText(Code: integer): WideString; //* ~exclude function ErrorCodeToCellError(Code: integer): TCellError; //* ~exclude function CellErrorToErrorCode(Error: TCellError): byte; //* ~exclude function FastReplace(var aSourceString : String; const aFindString, aReplaceString : String; CaseSensitive : Boolean = False) : String; //* ~exclude function ExcelStrToWideString(S: string): WideString; //* ~exclude function IntToXColor(Value: word): TExcelColor; //* ~exclude function XColorToTColor(XC: TExcelColor): TColor; //* ~exclude function XColorToRGB(XC: TExcelColor): longword; //* ~exclude function BufUnicodeZToWS(Buf: PByteArray; Len: integer): WideString; //* ~exclude function DecodeRK(Value: longint): double; //* ~exclude function ClipAreaToSheet(var C1,R1,C2,R2: integer): boolean; //* ~exclude function TColorToClosestXColor(Color: TColor): TExcelColor; //* ~exclude function MyWideUppercase(S: WideString): WideString; //* ~exclude function ValidRef(C,R: integer): boolean; //* ~exclude function ValidArea(C1,R1,C2,R2: integer): boolean; //* ~exclude function MaxDoubleList(List: TDynDoubleArray): double; //* ~exclude function SplitAtChar(C: WideChar; var S: WideString): WideString; // EMU (English Metric Units) to Centimeters //* ~exclude function EmuToCm(EMU: integer): double; //* ~exclude function CmToEmu(Cm: double): integer; var XLS_DebugMode: boolean = False; G_StrTRUE,G_StrFALSE: WideString; G_DEBUG_PStr: PWideChar; implementation procedure FVClear(var FV: TFormulaValue); begin FV.ValType := fvError; FV.vError := errError; end; procedure FVSetNull(var FV: TFormulaValue); begin FV.ValType := fvNull; end; procedure FVSetFloat(var FV: TFormulaValue; Value: double); begin FV.ValType := fvFloat; FV.vFloat := Value; end; procedure FVSetBoolean(var FV: TFormulaValue; Value: boolean); begin FV.ValType := fvBoolean; FV.vBoolean := Value; end; procedure FVSetError(var FV: TFormulaValue; Value: TCellError); begin FV.ValType := fvError; FV.vError := Value; end; procedure FVSetString(var FV: TFormulaValue; Value: WideString); begin FV.ValType := fvString; FV.vString := Value; end; procedure FVSetRef(var FV: TFormulaValue; Col,Row: word); begin FV.ValType := fvRef; FV.vRef[0] := Col; FV.vRef[1] := Row; end; procedure FVSetArea(var FV: TFormulaValue; Col1,Row1,Col2,Row2: word); begin FV.ValType := fvArea; FV.vArea[0] := Col1; FV.vArea[1] := Row1; FV.vArea[2] := Col2; FV.vArea[3] := Row2; end; procedure FVSetXRef(var FV: TFormulaValue; Col,Row,Sheet: word); begin FV.ValType := fvExtRef; FV.vExtRef[0] := Col; FV.vExtRef[1] := Row; FV.vExtRef[2] := Sheet; end; procedure FVSetXArea(var FV: TFormulaValue; Col1,Row1,Col2,Row2,Sheet: word); begin FV.ValType := fvExtArea; FV.vExtArea[0] := Col1; FV.vExtArea[1] := Row1; FV.vExtArea[2] := Col2; FV.vExtArea[3] := Row2; FV.vExtArea[4] := Sheet; end; function FVGetFloat(FV: TFormulaValue): double; begin if FV.ValType = fvFloat then Result := FV.vFloat else Result := 0; end; function FVGetString(FV: TFormulaValue): WideString; begin if FV.ValType = fvString then Result := FV.vString else Result := ''; end; function FVGetBoolean(FV: TFormulaValue): boolean; begin if FV.ValType = fvBoolean then Result := FV.vBoolean else Result := False; end; function FVGetVariant(FV: TFormulaValue): Variant; begin case FV.ValType of fvFloat : Result := FV.vFloat; fvBoolean : Result := FV.vBoolean; fvError : Result := CellErrorNames[Integer(FV.vError)]; fvString : Result := FV.vString; fvRef : Result := ColRowToRefStr(FV.vRef[0],FV.vRef[1],False,False); fvArea : Result := AreaToRefStr(FV.vArea[0],FV.vArea[1],FV.vArea[2],FV.vArea[3],False,False,False,False); // Sheet name is not included fvExtRef : Result := ColRowToRefStr(FV.vExtRef[0],FV.vExtRef[1],False,False); fvExtArea : Result := AreaToRefStr(FV.vExtArea[0],FV.vExtArea[1],FV.vExtArea[2],FV.vExtArea[3],False,False,False,False); end; end; function FVCompare(FV1,FV2: TFormulaValue; var Res: double): boolean; begin Result := (FV1.ValType <> fvError) and (FV2.ValType <> fvError) and (FV1.ValType = FV2.ValType); if not Result then Exit; if FV1.ValType in TFormulaValTypeRef then raise Exception.Create('Illegal value in comparision'); case FV1.ValType of fvFloat : Res := FV1.vFloat - FV2.vFloat; fvBoolean : Res := Integer(FV1.vBoolean = FV2.vBoolean); {$ifdef OLD_COMPILER} fvString : Res := AnsiCompareStr(AnsiUppercase(FV1.vString),AnsiUppercase(FV2.vString)); {$else} fvString : Res := WideCompareStr(MyWideUppercase(FV1.vString),MyWideUppercase(FV2.vString)); {$endif} end; end; function FVSize(FV: TFormulaValue): integer; begin case FV.ValType of fvArea,fvExtArea: Result := (FV.vArea[2] - FV.vArea[0] + 1) * (FV.vArea[3] - FV.vArea[1] + 1); else Result := 1; end; end; {$ifdef LINUX} function GetHashCode(const Buffer; Count: Integer): Word; begin raise Exception.Create('LINUX: GetHashCode'); end; {$else} function GetHashCode(const Buffer; Count: Integer): Word; assembler; asm CMP EDX,0 JNE @@2 MOV EAX,0 JMP @@3 @@2: MOV ECX,EDX MOV EDX,EAX XOR EAX,EAX @@1: ROL AX,5 XOR AL,[EDX] INC EDX DEC ECX JNE @@1 @@3: end; {$endif} function CPos(C: char; S: string): integer; begin for Result := 1 to Length(S) do begin if S[Result] = C then Exit; end; Result := -1; end; function WCPos(C: WideChar; S: WideString): integer; begin for Result := 1 to Length(S) do begin if S[Result] = C then Exit; end; Result := -1; end; function ColRowToRC(Col, Row: integer): longword; begin Result := (Row shl 8) + (Col and $000000FF); end; procedure SplitRC(RC: integer; var Col,Row: integer); begin Col := RC and $000000FF; Row := RC shr 8; end; procedure NormalizeArea(var C1,R1,C2,R2: integer); var T: integer; begin if C1 > C2 then begin T := C1; C1 := C2; C2 := T; end; if R1 > R2 then begin T := R1; R1 := R2; R2 := T; end; end; function IsMultybyteString(S: string): boolean; begin Result := (Length(S) > 0) and (S[1] = #1); end; function ToMultibyte1bHeader(S: string): string; begin Result := #0 + S end; function UnicodeStorageSize(S: string): integer; begin if S = '' then Result := 0 else if S[1] = #0 then Result := Length(S) + 1 else Result := Length(S) * 2 + 1; end; function UnicodeStringLen(S: string): integer; begin if S = '' then Result := 0 else if S[1] = #0 then Result := Length(S) - 1 else Result := (Length(S) - 1) div 2; end; function ExcelStrToString(P: PByteArray; CharCount: integer): string; begin if P[0] = 0 then begin SetLength(Result,CharCount + 1); Move(P[1],Result[2],CharCount); Result[1] := #0; end else begin SetLength(Result,CharCount * 2 + 1); Move(P[1],Result[2],CharCount * 2); Result[1] := #1; end; end; function ByteStrToWideString(P: PByteArray; CharCount: integer): WideString; var i: integer; begin SetLength(Result,CharCount); if CharCount <= 0 then Exit else if P[0] = 1 then begin P := PByteArray(Integer(P) + 1); Move(P^,Pointer(Result)^,CharCount * 2); end else begin for i := 1 to CharCount do Result[i] := WideChar(P[i]); end; end; procedure WideStringToByteStr(S: WideString; P: PByteArray); begin P[0] := 1; Move(Pointer(S)^,P[1],Length(S) * 2); end; function ErrorCodeToText(Code: integer): WideString; begin case Code of $00: Result := CellErrorNames[1]; $07: Result := CellErrorNames[2]; $0F: Result := CellErrorNames[3]; $17: Result := CellErrorNames[4]; $1D: Result := CellErrorNames[5]; $24: Result := CellErrorNames[6]; $2A: Result := CellErrorNames[7]; else Result := '#???'; end; end; function ErrorCodeToCellError(Code: integer): TCellError; var V: byte; begin case Code of $00: V := 1; $07: V := 2; $0F: V := 3; $17: V := 4; $1D: V := 5; $24: V := 6; $2A: V := 7; else V := 0; end; Result := TCellError(V); end; function CellErrorToErrorCode(Error: TCellError): byte; begin case Error of errError: Result := $2A; errNull: Result := $00; errDiv0: Result := $07; errValue: Result := $0F; errRef: Result := $17; errName: Result := $1D; errNum: Result := $24; errNA: Result := $2A; else Result := $2A; end; end; function ColRowToRefStr(ACol,ARow: integer; AbsCol,AbsRow: boolean): string; begin Inc(ARow); if AbsCol then begin if ACol < 26 then Result := '$' + Char(Ord('A') + ACol) else Result := '$' + Char(Ord('@') + ACol div 26) + Char(Ord('A') + ACol mod 26); end else begin if ACol < 26 then Result := Char(Ord('A') + ACol) else Result := Char(Ord('@') + ACol div 26) + Char(Ord('A') + ACol mod 26); end; if AbsRow then Result := Result + '$' + IntToStr(ARow) else Result := Result + IntToStr(ARow); end; function AreaToRefStr(Col1,Row1,Col2,Row2: integer; AbsCol1,AbsRow1,AbsCol2,AbsRow2: boolean): string; begin Result := ColRowToRefStr(Col1,Row1,AbsCol1,AbsRow1) + ':' + ColRowToRefStr(Col2,Row2,AbsCol2,AbsRow2); end; function RefStrToColRow(S: string; var ACol,ARow: integer; var AbsCol,AbsRow: boolean): boolean; var wCol,wRow: word; begin // Result := (ACol >= 0) and (ACol <= MAXCOL) and (ARow >= 0) and (ARow <= MAXROW); // if Result then begin wCol := 0; wRow := 0; Result := RefStrToColRow(S,wCol,wRow,AbsCol,AbsRow); ACol := wCol; ARow := wRow; // end; end; function RefStrToColRow(S: string; var ACol,ARow: integer): boolean; overload; var AbsCol,AbsRow: boolean; begin Result := RefStrToColRow(S,ACol,ARow,AbsCol,AbsRow); end; function RefStrToColRow(S: string; var ACol,ARow: word; var AbsCol,AbsRow: boolean): boolean; var i,j: integer; begin AbsCol := False; AbsRow := False; Result := False; if Length(S) < 1 then Exit; i := 1; if S[i] = '$' then begin Inc(i); AbsCol := True; end; if i > Length(S) then Exit; if not (S[i] in ['A'..'Z']) then Exit; Inc(i); if i > Length(S) then Exit; if (S[i] in ['A'..'Z']) then begin if not (S[i - 1] in ['A'..'I']) then Exit; ACol := (Ord(S[i - 1]) - Ord('@')) * 26 + (Ord(S[i]) - Ord('A')); if ACol > 255 then ACol := 255; Inc(i); if i > Length(S) then Exit; end else ACol := Ord(S[i - 1]) - Ord('A'); if S[i] = '$' then begin Inc(i); AbsRow := True; end; for j := i to Length(S) do begin if not (S[j] in ['0'..'9']) then Exit; end; try ARow := StrToInt(Copy(S,i,1024)) - 1; except Exit; end; Result := True; end; function AreaStrToColRow(S: string; var ACol1,ARow1,ACol2,ARow2: integer; var AbsCol1,AbsRow1,AbsCol2,AbsRow2: boolean): boolean; var p: integer; begin Result := False; p := CPos('!',S); if p > 0 then S := Copy(S,p + 1,MAXINT); p := CPos(':',S); if p < 1 then Exit; if not RefStrToColRow(Copy(S,1,p - 1),ACol1,ARow1,AbsCol1,AbsRow1) then Exit; if not RefStrToColRow(Copy(S,p + 1,MAXINT),ACol2,ARow2,AbsCol2,AbsRow2) then Exit; Result := True; end; function AreaStrToColRow(S: string; var ACol1,ARow1,ACol2,ARow2: integer): boolean; var AC1,AC2,AR1,AR2: boolean; begin Result := AreaStrToColRow(S,ACol1,ARow1,ACol2,ARow2,AC1,AC2,AR1,AR2); end; function HexToByte(S: string): byte; begin if Length(S) <> 2 then raise Exception.Create('Length error in hex string.'); if S[1] in ['0'..'9'] then Result := (Ord(S[1]) - Ord('0')) * 16 else Result := (Ord(S[1]) - Ord('A') + 10) * 16; if S[2] in ['0'..'9'] then Result := Result + Ord(S[2]) - Ord('0') else Result := Result + Ord(S[2]) - Ord('A') + 10; end; function HexStringToByteArray(S: string; var PBytes: PByteArray): integer; var i,p: integer; begin Result := Length(S) div 2; ReAllocMem(PBytes,Result); p := 1; for i := 0 to Result - 1 do begin PBytes[i] := HexToByte(Copy(S,p,2)) ; Inc(p,2); end; end; procedure HexStringToDynByteArray(S: string; var PBytes: TDynByteArray); var i,p,Sz: integer; begin Sz := Length(S) div 2; SetLength(PBytes,Sz); p := 1; for i := 0 to Sz - 1 do begin PBytes[i] := HexToByte(Copy(S,p,2)) ; Inc(p,2); end; end; Type TFastPosProc = function( const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : integer ) : integer; function FastPos(const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : integer) : integer; var SourceLen : integer; begin SourceLen := aSourceLen; SourceLen := SourceLen - aFindLen; if (StartPos-1) > SourceLen then begin Result := 0; Exit; end; SourceLen := SourceLen - StartPos; SourceLen := SourceLen +2; asm push ESI push EDI push EBX mov EDI, aSourceString add EDI, StartPos Dec EDI mov ESI, aFindString mov ECX, SourceLen Mov Al, [ESI] @ScaSB: Mov Ah, [EDI] cmp Ah,Al jne @NextChar @CompareStrings: mov EBX, aFindLen dec EBX @CompareNext: mov Al, [ESI+EBX] mov Ah, [EDI+EBX] cmp Al, Ah Jz @Matches Mov Al, [ESI] Jmp @NextChar @Matches: Dec EBX Jnz @CompareNext mov EAX, EDI sub EAX, aSourceString inc EAX mov Result, EAX jmp @TheEnd @NextChar: Inc EDI dec ECX jnz @ScaSB mov Result,0 @TheEnd: pop EBX pop EDI pop ESI end; end; function FastPosNoCase(const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : integer) : integer; var SourceLen : integer; begin SourceLen := aSourceLen; SourceLen := SourceLen - aFindLen; if (StartPos-1) > SourceLen then begin Result := 0; Exit; end; SourceLen := SourceLen - StartPos; SourceLen := SourceLen +2; asm push ESI push EDI push EBX mov EDI, aSourceString add EDI, StartPos Dec EDI mov ESI, aFindString mov ECX, SourceLen Mov Al, [ESI] and Al, $df @ScaSB: Mov Ah, [EDI] and Ah, $df cmp Ah,Al jne @NextChar @CompareStrings: mov EBX, aFindLen dec EBX @CompareNext: mov Al, [ESI+EBX] mov Ah, [EDI+EBX] and Al, $df and Ah, $df cmp Al, Ah Jz @Matches Mov Al, [ESI] and Al, $df Jmp @NextChar @Matches: Dec EBX Jnz @CompareNext mov EAX, EDI sub EAX, aSourceString inc EAX mov Result, EAX jmp @TheEnd @NextChar: Inc EDI dec ECX jnz @ScaSB mov Result,0 @TheEnd: pop EBX pop EDI pop ESI end; end; procedure MyMove(const Source; var Dest; Count : Integer); asm cmp ECX,0 Je @JustQuit push ESI push EDI mov ESI, EAX mov EDI, EDX @Loop: Mov AL, [ESI] Inc ESI mov [EDI], AL Inc EDI Dec ECX Jnz @Loop pop EDI pop ESI @JustQuit: end; function FastReplace(var aSourceString : String; const aFindString, aReplaceString : String; CaseSensitive : Boolean = False) : String; var ActualResultLen, CurrentPos, LastPos, BytesToCopy, ResultLen, FindLen, ReplaceLen, SourceLen : Integer; FastPosProc : TFastPosProc; begin if CaseSensitive then FastPosProc := FastPOS else FastPOSProc := FastPOSNoCase; Result := ''; FindLen := Length(aFindString); ReplaceLen := Length(aReplaceString); SourceLen := Length(aSourceString); if ReplaceLen <= FindLen then ActualResultLen := SourceLen else ActualResultLen := SourceLen + (SourceLen * ReplaceLen div FindLen) + ReplaceLen; SetLength(Result,ActualResultLen); CurrentPos := 1; ResultLen := 0; LastPos := 1; if ReplaceLen > 0 then begin repeat CurrentPos := FastPosProc(aSourceString, aFindString,SourceLen, FindLen, CurrentPos); if CurrentPos = 0 then break; BytesToCopy := CurrentPos-LastPos; MyMove(aSourceString[LastPos],Result[ResultLen+1], BytesToCopy); MyMove(aReplaceString[1],Result[ResultLen+1+BytesToCopy], ReplaceLen); ResultLen := ResultLen + BytesToCopy + ReplaceLen; CurrentPos := CurrentPos + FindLen; LastPos := CurrentPos; until false; end else begin repeat CurrentPos := FastPos(aSourceString, aFindString, SourceLen, FindLen, CurrentPos); if CurrentPos = 0 then break; BytesToCopy := CurrentPos-LastPos; MyMove(aSourceString[LastPos], Result[ResultLen+1], BytesToCopy); ResultLen := ResultLen + BytesToCopy + ReplaceLen; CurrentPos := CurrentPos + FindLen; LastPos := CurrentPos; until false; end; Dec(LastPOS); SetLength(Result, ResultLen + (SourceLen-LastPos)); if LastPOS+1 <= SourceLen then MyMove(aSourceString[LastPos+1],Result[ResultLen+1],SourceLen-LastPos); end; function ExcelStrToWideString(S: string): WideString; begin if Length(S) <= 0 then Result := '' else begin if S[1] = #0 then begin Result := Copy(S,2,MAXINT); end else if S[1] = #1 then begin SetLength(Result,(Length(S) - 1) div 2); S := Copy(S,2,MAXINT); Move(Pointer(S)^,Pointer(Result)^,Length(S)); end else Result := S; // raise Exception.Create('Bad excel string id.'); end; end; function IntToXColor(Value: word): TExcelColor; begin if Value <= Word(High(TExcelColor)) then Result := TExcelColor(Value) else Result := xcAutomatic; end; function XColorToTColor(XC: TExcelColor): TColor; begin Result := ExcelColorPalette[Integer(XC)]; end; function XColorToRGB(XC: TExcelColor): longword; var tmp: longword; begin Result := XColorToTColor(XC); tmp := Result and $00FF0000; Result := Result + (((Result and $000000FF) shl 16) or tmp); end; function BufUnicodeZToWS(Buf: PByteArray; Len: integer): WideString; begin if Len > 0 then begin SetLength(Result,(Len div 2) - 1); Move(Buf^,Pointer(Result)^,Len - 2); end else Result := ''; end; function DecodeRK(Value: longint): double; var RK: TRK; begin RK.DW[0] := 0; // RK.DW[1] := Value and $FFFFFFFC; RK.DW[1] := Value and LongInt($FFFFFFFC); case (Value and $3) of 0: Result := RK.V; 1: Result := RK.V / 100; 2: Result := Integer(RK.DW[1]) / 4; 3: Result := Integer(RK.DW[1]) / 400; else Result := RK.V; end; end; function ClipAreaToSheet(var C1,R1,C2,R2: integer): boolean; begin if (C1 > MAXCOL) or (R1 > MAXROW) or (C2 < 0) or (R2 < 0) then Result := False else begin C1 := Max(C1,0); R1 := Max(R1,0); C2 := Min(C2,MAXCOL); R2 := Min(R2,MAXROW); Result := True; end; end; function TColorToClosestXColor(Color: TColor): TExcelColor; var i,j: integer; C: integer; R1,G1,B1: byte; R2,G2,B2: byte; V1,V2: double; begin j := 8; R1 := Color and $FF; G1 := (Color and $FF00) shr 8; B1 := (Color and $FF0000) shr 16; V1 := $FFFFFF; for i := 8 to 63 do begin C := ExcelColorPalette[i]; R2 := C and $FF; G2 := (C and $FF00) shr 8; B2 := (C and $FF0000) shr 16; V2 := Abs(R1 - R2) + Abs(G1 - G2) + Abs(B1 - B2); if Abs(V2) < Abs(V1) then begin V1 := V2; j := i; end; end; Result := TExcelColor(j); end; function MyWideUppercase(S: WideString): WideString; begin {$ifdef OLD_COMPILER} Result := AnsiUppercase(S); {$else} Result := WideUppercase(S); {$endif} end; function ValidRef(C,R: integer): boolean; begin Result := (C >= 0) and (C <= MAXCOL) and (R >= 0) and (R <= MAXROW); end; function ValidArea(C1,R1,C2,R2: integer): boolean; begin Result := ValidRef(C1,R1) and ValidRef(C2,R2); end; function MaxDoubleList(List: TDynDoubleArray): double; var i: integer; begin Result := MINDOUBLE; for i := 0 to High(List) do begin if List[i] > Result then Result := List[i]; end; end; function SplitAtChar(C: WideChar; var S: WideString): WideString; var p: integer; begin p := WCPos(C,S); if p > 0 then begin Result := Copy(S,1,p - 1); S := Copy(S,p + 1,MAXINT); end else begin Result := S; S := ''; end; end; // EMU (English Metric Units) to Centimeters function EmuToCm(EMU: integer): double; begin Result := Emu / 360000; end; function CmToEmu(Cm: double): integer; begin Result := Round(Cm * 360000); end; initialization G_StrTRUE := 'TRUE'; G_StrFALSE := 'FALSE'; end.
unit SysAdmin; interface uses Windows, Classes, Forms, FIBQuery, pFIBQuery, pFIBStoredProc, ExtCtrls, DB, FIBDataSet, pFIBDataSet, pFibDatabase, SIBFIBEA, IB_EXTERNALS, Graphics, Jpeg, SysUtils; type TSendMode = (smAllSystems, smSystem, smUser); TAdminObject = class DataBase : TpfibDataBase; ReadTransaction : TpFIBTransaction; WriteTransaction : TpFIBTransaction; StoredProc : TpFIBStoredProc; Query : TpFIBQuery; QueryW : TpFIBQuery; Events : TSIBfibEventAlerter; isActivateBlock : Boolean; isSuperAdmin : Boolean; private procedure ProcEventAlert(Sender: TObject; EventName: String; EventCount: Integer); procedure ReadMessages(do_del : Integer = 0); procedure onError(Sender: TObject; E: Exception); procedure CheckBlocked; end; var ADMIN_VAR_ID_SYSTEM : Integer; ADMIN_VAR_ID_USER : Integer; ADMIN_MAIN_FORM : TForm; AdminObject : TAdminObject; th : Tthread; procedure InitializaAdminSystem(frmMain : TForm; DBHandle : PVoid; const id_system, id_user : Integer; isSuperAdmin : Boolean = false); procedure FinalizeAdminSystem; procedure AdminShowUsers(AOwner : Tcomponent); procedure AdminShowErrors(AOwner : Tcomponent); implementation uses WinSock, msgUnit, errUnit, sysUsers, sysErrors, frmDisabledUnit; function GetCompName : string; var s : string; sLen : Longword; begin SetLength(s, 255); sLen := 255; GetHostName(@s[1], sLen); Result := Trim(StrPas(PAnsiChar(s))); end; function GetIPAddress : string; var wVerReq: WORD; wsaData: TWSAData; i: pchar; h: PHostEnt; c: array[0..128] of char; begin wVerReq := MAKEWORD(1, 1); WSAStartup(wVerReq, wsaData); GetHostName(@c, 128); h := GetHostByName(@c); i := iNet_ntoa(PInAddr(h^.h_addr_list^)^); Result := i; WSACleanup; end; procedure GetScreenImage(bmp: TBitmap); begin bmp.Width := Screen.Width; bmp.Height := Screen.Height; BitBlt(bmp.Canvas.Handle, 0, 0, Screen.Width, Screen.Height, GetDC(GetDesktopWindow), 0, 0, SRCCopy); end; procedure InitializaAdminSystem(frmMain : TForm; DBHandle : PVoid; const id_system, id_user : Integer; isSuperAdmin : Boolean = false); begin ADMIN_MAIN_FORM := frmMain; ADMIN_VAR_ID_SYSTEM := id_system; ADMIN_VAR_ID_USER := id_user; AdminObject := TAdminObject.Create; AdminObject.isSuperAdmin := isSuperAdmin; AdminObject.DataBase := TpFIBDatabase.Create(ADMIN_MAIN_FORM); AdminObject.DataBase.SQLDialect := 3; AdminObject.DataBase.Handle := DBHandle; AdminObject.ReadTransaction := TpFIBTransaction.Create(ADMIN_MAIN_FORM); AdminObject.ReadTransaction.DefaultDatabase := AdminObject.DataBase; AdminObject.ReadTransaction.StartTransaction; // AdminObject.ReadTransaction.Handle := ReadTransaction; AdminObject.WriteTransaction := TpFIBTransaction.Create(ADMIN_MAIN_FORM); AdminObject.WriteTransaction.DefaultDatabase := AdminObject.DataBase; // AdminObject.WriteTransaction.Handle := WriteTransaction; AdminObject.StoredProc := TpFIBStoredProc.Create(ADMIN_MAIN_FORM); AdminObject.StoredProc.Transaction := AdminObject.WriteTransaction; AdminObject.Query := TpFIBQuery.Create(ADMIN_MAIN_FORM); AdminObject.Query.Transaction := AdminObject.ReadTransaction; AdminObject.QueryW := TpFIBQuery.Create(ADMIN_MAIN_FORM); AdminObject.QueryW.Transaction := AdminObject.WriteTransaction; AdminObject.Events := TSIBfibEventAlerter.Create(ADMIN_MAIN_FORM); AdminObject.Events.AutoRegister := False; AdminObject.Events.Database := AdminObject.DataBase; AdminObject.Events.Events.Add('SYS_MESSAGE'); AdminObject.Events.Events.Add('SYS_USERS_LOCATE'); AdminObject.Events.Events.Add('SYS_GET_SCREENSHOT'); AdminObject.Events.Events.Add('SYS_BLOCKED'); AdminObject.Events.Events.Add('SYS_CLOSE'); AdminObject.Events.RegisterEvents; AdminObject.Events.OnEventAlert := AdminObject.ProcEventAlert; // Application.OnException := AdminObject.onError; if not isSuperAdmin then AdminObject.CheckBlocked; AdminObject.ReadMessages(1); end; procedure FinalizeAdminSystem; begin if AdminObject.Events.Registered then AdminObject.Events.UnRegisterEvents; AdminObject.Events.Free; AdminObject.QueryW.Free; AdminObject.Query.Free; AdminObject.StoredProc.Free; AdminObject.WriteTransaction.Free; AdminObject.ReadTransaction.Commit; AdminObject.ReadTransaction.Free; AdminObject.DataBase.Free; AdminObject.Free; end; procedure TAdminObject.ProcEventAlert(Sender: TObject; EventName: String; EventCount: Integer); var bmp : TBitmap; jpg : TJPEGImage; st : TMemoryStream; i : Integer; begin if EventName = 'SYS_USERS_LOCATE' then begin StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('PROC_SYS_USERS_ADD', [ADMIN_VAR_ID_SYSTEM, ADMIN_VAR_ID_USER, GetCompName, GetIPAddress]); StoredProc.Transaction.Commit; StoredProc.Close; end; if EventName = 'SYS_MESSAGE' then begin ReadMessages; end; if EventName = 'SYS_GET_SCREENSHOT' then begin Query.Close; Query.SQL.Text := 'select id_user from sys_events_data'; Query.ExecQuery; if Query['ID_USER'].AsInt64 = ADMIN_VAR_ID_USER then begin bmp := TBitmap.Create; GetScreenImage(bmp); jpg := TJPEGImage.Create; jpg.Assign(bmp); st := TMemoryStream.Create; jpg.CompressionQuality := 90; jpg.SaveToStream(st); st.Seek(0, soBeginning); st.SaveToFile('c:\dump.jpg'); StoredProc.StoredProcName := 'PROC_SYS_EVENTS_DATA_ADD_SCR'; StoredProc.Transaction.StartTransaction; StoredProc.Prepare; StoredProc.ParamByName('SCREENSHOT').LoadFromStream(st); StoredProc.ExecProc; StoredProc.Transaction.Commit; st.Free; jpg.Free; bmp.Free; end; Query.Close; end; if (EventName = 'SYS_BLOCKED') and (not isActivateBlock) and (not isSuperAdmin) then begin Query.Close; Query.SQL.Text := 'select is_blocked from sys_systems where id_system = ' + IntToStr(ADMIN_VAR_ID_SYSTEM); Query.ExecQuery; if Query.RecordCount <> 0 then begin if Query['IS_BLOCKED'].AsInteger = 1 then begin Query.Close; if not Assigned(frmDisabled) then begin frmDisabled := TfrmDisabled.Create(ADMIN_MAIN_FORM); frmDisabled.Show; for i := 0 to Screen.FormCount - 1 do Screen.Forms[i].Enabled := False; frmDisabled.Enabled := True; ADMIN_MAIN_FORM.Enabled := False; end; end else begin ADMIN_MAIN_FORM.Enabled := true; for i := 0 to Screen.FormCount - 1 do Screen.Forms[i].Enabled := true; if Assigned(frmDisabled) then begin frmDisabled.cc := True; frmDisabled.Close; frmDisabled.Free; frmDisabled := nil; end; end; end; Query.Close; end; if (EventName = 'SYS_CLOSE') and (not isActivateBlock) then begin Query.Close; Query.SQL.Text := 'select count(*) from sys_close where (id_system = ' + IntToStr(ADMIN_VAR_ID_SYSTEM) + ' and id_user = -1) or (id_system = ' + IntToStr(ADMIN_VAR_ID_SYSTEM) + ' and id_user = ' + IntToStr(ADMIN_VAR_ID_USER) + ')'; Query.ExecQuery; if Query.FieldByName('COUNT').AsInteger <> 0 then begin Query.Close; ADMIN_MAIN_FORM.OnCloseQuery := nil; ADMIN_MAIN_FORM.Close; end; end; isActivateBlock := False; end; procedure TAdminObject.ReadMessages(do_del : Integer = 0); begin QueryW.Transaction.StartTransaction; QueryW.SQL.Text := 'select * from PROC_SYS_MESSAGES_READ(' + IntToStr(ADMIN_VAR_ID_SYSTEM) + ', ' + IntToStr(ADMIN_VAR_ID_USER) + ', ' + IntToStr(do_del) + ')'; QueryW.ExecQuery; if QueryW.RecordCount <> 0 then begin while not QueryW.Eof do begin msgForm := TmsgForm.Create(ADMIN_MAIN_FORM); msgForm.msgEdit.Text := QueryW['MESSAGE_TEXT'].AsString; msgForm.ShowModal; msgForm.Free; QueryW.Next; end; end; QueryW.Transaction.Commit; QueryW.Close; end; procedure TAdminObject.onError(Sender: TObject; E: Exception); var frmError : TfrmError; begin frmError := TfrmError.Create(ADMIN_MAIN_FORM); frmError.errMemo.Text := e.Message; frmError.ShowModal; frmError.Free; end; procedure AdminShowUsers(AOwner : Tcomponent); var frm : TfrmSysUsers; begin frm := TfrmSysUsers.Create(AOwner); frm.WorkDatabase.Handle := AdminObject.DataBase.Handle; frm.ReadTransaction.Handle := AdminObject.ReadTransaction.Handle; frm.WriteTransaction.Handle := AdminObject.WriteTransaction.Handle; frm.FormStyle := fsMDIChild; frm.SystemsDataSet.Open; frm.SystemsDataSet.FetchAll; // frm.cbSystems.Properties.Grid.FocusedRowIndex := 0; frm.SystemsDataSet.Locate('ID_SYSTEM', ADMIN_VAR_ID_SYSTEM, []); frm.cbSystems.Text := frm.SystemsDataSet['NAME_SYSTEM']; frm.Show; end; procedure AdminShowErrors(AOwner : Tcomponent); var frm : TfrmSysErrors; begin frm := TfrmSysErrors.Create(AOwner); frm.WorkDatabase.Handle := AdminObject.DataBase.Handle; frm.ReadTransaction.Handle := AdminObject.ReadTransaction.Handle; frm.WriteTransaction.Handle := AdminObject.WriteTransaction.Handle; frm.FormStyle := fsMDIChild; frm.SystemsDataSet.Open; frm.SystemsDataSet.FetchAll; // frm.cbSystems.Properties.DataController.LocateByKey(ADMIN_VAR_ID_USER); frm.SystemsDataSet.Locate('ID_SYSTEM', ADMIN_VAR_ID_SYSTEM, []); frm.cbSystems.Text := frm.SystemsDataSet['NAME_SYSTEM']; frm.SelectAll; frm.Show; end; procedure TAdminObject.CheckBlocked; var i : Integer; begin Query.Close; Query.SQL.Text := 'select is_blocked from sys_systems where id_system = ' + IntToStr(ADMIN_VAR_ID_SYSTEM); Query.ExecQuery; if Query.RecordCount <> 0 then begin if Query['IS_BLOCKED'].AsInteger = 1 then begin frmDisabled := TfrmDisabled.Create(ADMIN_MAIN_FORM); frmDisabled.Show; for i := 0 to Screen.FormCount - 1 do Screen.Forms[i].Enabled := False; frmDisabled.Enabled := True; ADMIN_MAIN_FORM.Enabled := False; end; end; Query.Close; end; end.
{: This is a basic use for TGLBInertia behaviour.<p> There are three objects, which we assign three different dampings, and we apply a torque to the object under the mouse pointer, other are left along with their inertia (and damping makes them progressively reduce their speed).<br> There is also a checkbox to double the objects mass.<p> Notice how the constant damping stops abruptly the dodecahedron, while the the octahedron, once spinned, is slowing down but never really stops.<br> However, don't show this sample to your science teacher, since our "torque" is actually an angular acceleration in degrees that gets affected by the object's mass... Anyway, it looks like a real torque is applied.<p> Note that the inertia behaviour could have been accessed directly with a TGLBInertia(Behaviours[0]) for all objects in this sample, but using the helper function GetOrCreateInertia is a more convenient (and resilient) way, since it will automatically add an inertia behaviour to our object if it doesn't have one. } unit Unit1; interface uses Forms, GLObjects, GLScene, StdCtrls, ExtCtrls, Controls, Classes, GLCadencer, {$IFNDEF FPC} GLWin32Viewer, {$ELSE} GLLCLViewer, LResources,{$ENDIF} GLPolyhedron, GLCrossPlatform, GLCoordinates, BaseClasses; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; Cube: TGLCube; Dodecahedron: TGLDodecahedron; Octahedron: TGLSphere; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; CheckBox1: TCheckBox; DummyCube1: TGLDummyCube; GLCadencer1: TGLCadencer; procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); private { Déclarations privées } lastTime : Double; pickedObject : TGLBaseSceneObject; public { Déclarations publiques } end; var Form1: TForm1; implementation {$IFNDEF FPC} {$R *.dfm} {$ELSE} {$R *.lfm} {$ENDIF} uses SysUtils, GLBehaviours; procedure TForm1.FormCreate(Sender: TObject); begin // Initialize last time lastTime:=Now*3600*24; // Initialize rotation dampings... // ...using properties... with GetOrCreateInertia(Cube.Behaviours).RotationDamping do begin Constant:=1; Linear:=1; Quadratic:=0; end; // ...using helper function on the TGLBehaviours... GetOrCreateInertia(Dodecahedron.Behaviours).RotationDamping.SetDamping(10, 0, 0.01); // ...or using helper function directly on the TGLBaseSceneObject GetOrCreateInertia(Octahedron).RotationDamping.SetDamping(0, 0, 0.01); end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin // Mouse moved, get what's underneath pickedObject:=GLSceneViewer1.Buffer.GetPickedObject(x, y); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin // apply some "torque" to the pickedObject if any if Assigned(pickedObject) then GetOrCreateInertia(pickedObject).ApplyTorque(deltaTime, 200, 0, 0); end; procedure TForm1.CheckBox1Click(Sender: TObject); var i : Integer; mass : Single; begin if CheckBox1.Checked then mass:=2 else mass:=1; // all our objects are child of the DummyCube1 for i:=0 to DummyCube1.Count-1 do GetOrCreateInertia(DummyCube1.Children[i]).Mass:=mass; end; {$IFDEF FPC} initialization {$i Unit1.lrs} {$ENDIF} end.
unit YarxiCore; interface uses YarxiStrings, KanaConv; { Данные хранятся в базе Яркси в разновидности кодировки Хэпбёрна. Отделение n стандартное: "sen'i". Долгота ou передаётся двоеточием: "so:zo:". Удвоенная гласная так и записывается: "tooi", "saabisu". В словах, помеченных как катакана, Яркси в этом месте вставит тире: "sa-bisu". Для преобразования каны/кандзи требуется таблица Hepburn-Yarxi.roma, которую загружает в KanaTran центральный модуль. В транскрипции бывают пробелы, кроме того, декодером вводятся дополнительные символы для обозначения помет, которые в Яркси хранятся иным образом: - тире в транскрипции ´ особая помета для сочетаний ii и ha [] опциональная часть При переводе в кану и обратно эти символы должны сохраняться. Для их удаления в последний момент существуют функции clearMarks и clearKana. } var YarxiSilent: boolean = false; KanaTran: TRomajiTranslator; //Короткие ссылки function RomajiToKana(const s: string): string; inline; function KanaToRomaji(const s: string): string; inline; { Преобразование в киридзи мы сейчас не поддерживаем, поскольку для разбора оно не нужно, но однажды его можно сделать. Просто нужно разделить таблицу на отдельные: yarxi-romaji и yarxi-kiriji. } { Как переводить Яркси-ромадзи в: -> ромадзи: enhanceRomaji(s) -> печатная кана: clearMarks(RomajiToKana(s)) -> чистая кана (для поиска или экспорта): clearAll(s) -> киридзи: enhanceKiriji(KanaToKiriji(RomajiToKana(s))) } function clearMarks(const s: string): string; function clearAll(const s: string): string; function enhanceRomaji(const s: string): string; function enhanceKiriji(const s: string): string; { Во всех полях используется "обезъяний русский": <a => a <b => б <c => в Обычно всё пишется маленькими, а заглавная буква первой делается автоматически. Но если записано имя собственное, то заглавная прописывается явно. Заглавные получаются из обычных так: <c -> <C. Для специальных букв заглавные смотри ниже по табличке. Цифры не кодируются. } function DecodeRussian(const inp: string): string; { Функции посылают сюда жалобы на жизнь. } var ComplainContext: string; Complaints: integer; //добавляется ко всем жалобам. Внешние функции могут записывать сюда //номер и/или содержание текущей записи procedure PushComplainContext(const AData: string); procedure PopComplainContext; procedure Complain(const msg: string); inline; overload; procedure Complain(const msg, data: string); inline; overload; implementation uses SysUtils, StrUtils, WcExceptions; function RomajiToKana(const s: string): string; begin Result := KanaTran.RomajiToKana(s, []); end; function KanaToRomaji(const s: string): string; begin Result := KanaTran.KanaToRomaji(s, []); end; { Удаляет из ромадзи, каны или киридзи пометы, в том числе уже имевшиеся в базе (пробелы) и внесённые туда декодером (тире, штрих). Оставляет пометы, сохраняющиеся в печатной кане (кв. скобки). } function clearMarks(const s: string): string; begin Result := killc(s, ' -´'); end; { Удаляет из ромадзи, каны или киридзи все пометы. } function clearAll(const s: string): string; begin Result := killc(s, ' -´[]'); end; { Заменяет слоги с пометами на их печатные альтернативы (i´->i; ha´->wa) } function enhanceRomaji(const s: string): string; begin Result := killc(s,'`'); //непродуктивные пометы Result := repl(Result, 'ha´', 'wa'); end; { То же для киридзи } function enhanceKiriji(const s: string): string; begin Result := s; Result := repl(Result, 'ий´', 'ии'); Result := repl(Result, 'ха´', 'ва'); end; { Заменяет весь обезъяний русский в тексте нормальными русскими буквами. } function DecodeRussian(const inp: string): string; const eng: string = 'abcdefghijklmnopqrstuvwxyz1234567ABCDEFGHIJKLMNOPQRSTUVWXYZ890!?=+'; rus: string = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'; var pc, po: PChar; i: integer; found: boolean; begin if inp='' then begin Result := ''; exit; end; Result := ''; SetLength(Result, Length(inp)); //not going to be bigger than that pc := PChar(@inp[1]); po := PChar(@Result[1]); while pc^<>#00 do begin if pc^='<' then begin Inc(pc); found := false; for i:= 1 to Length(eng) do if eng[i]=pc^ then begin po^ := rus[i]; found := true; break; end; if not found then begin po^ := '<'; Dec(pc); end; end else po^ := pc^; Inc(pc); Inc(po); end; po^ := #00; SetLength(Result, StrLen(PChar(Result))); //trim end; { Сборщик жалоб } procedure PushComplainContext(const AData: string); begin if ComplainContext<>'' then ComplainContext:=ComplainContext+#09+AData else ComplainContext:=AData; end; procedure PopComplainContext; var i, j: integer; begin i := 0; repeat j := i; i := pos(#09,ComplainContext,j+1); until i<=0; if j=0 then //nothing found ComplainContext := '' else ComplainContext := Copy(ComplainContext,1,j-1); end; procedure Complain(const msg: string); begin Inc(Complaints); if YarxiSilent then exit; if ComplainContext<>'' then Warning(#13#10' '+repl(ComplainContext,#09,#13#10' ')+#13#10' '+msg) else Warning(msg); end; procedure Complain(const msg, data: string); begin Inc(Complaints); if YarxiSilent then exit; if ComplainContext<>'' then Warning(#13#10' '+repl(ComplainContext,#09,#13#10' ')+#13#10' '+data) else Warning(msg+#13#10' '+data); end; initialization KanaTran := TKanaTranslator.Create; finalization FreeAndNil(KanaTran); end.
unit uFormBusyApplications; interface uses Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ImgList, Dmitry.Utils.System, uIconUtils, uDBForm; type TFormBusyApplications = class(TDBForm) ImApplications: TImageList; LbInfo: TLabel; LstApplications: TListBox; BtnCancel: TButton; BtnRetry: TButton; procedure LstApplicationsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure BtnCancelClick(Sender: TObject); procedure BtnRetryClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure LoadApplicationList(Applications: TStrings); protected function GetFormID: string; override; public { Public declarations } function Execute(Applications: TStrings): Boolean; end; implementation {$R *.dfm} { TFormBusyApplications } procedure TFormBusyApplications.BtnCancelClick(Sender: TObject); begin Close; ModalResult := mrClose; end; procedure TFormBusyApplications.BtnRetryClick(Sender: TObject); begin Close; ModalResult := mrRetry; end; function TFormBusyApplications.Execute(Applications: TStrings): Boolean; begin LoadApplicationList(Applications); ShowModal; Result := ModalResult = mrRetry; end; procedure TFormBusyApplications.FormCreate(Sender: TObject); begin ModalResult := mrCancel; Caption := L('Close applications'); BtnCancel.Caption := L('Cancel'); BtnRetry.Caption := L('Retry'); LbInfo.Caption := L('Please close the following application to continue uninstall:'); end; function TFormBusyApplications.GetFormID: string; begin Result := 'Setup'; end; procedure TFormBusyApplications.LoadApplicationList(Applications: TStrings); var FileName: string; ExeInfo: TEXEVersionData; Ico: HIcon; begin for FileName in Applications do begin ExeInfo.FileDescription := ''; try ExeInfo := GetEXEVersionData(FileName); except //unable for get versin info - ignore it end; if ExeInfo.FileDescription = '' then ExeInfo.FileDescription := ExtractFileName(FileName); LstApplications.Items.Add(ExeInfo.FileDescription); Ico := ExtractSmallIconByPath(FileName, True); try ImageList_ReplaceIcon(ImApplications.Handle, -1, Ico); finally DestroyIcon(Ico); end; end; end; procedure TFormBusyApplications.LstApplicationsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var LB: TListBox; ACanvas: TCanvas; H: Integer; begin LB := TListBox(Control); ACanvas := LB.Canvas; if odSelected in State then ACanvas.Brush.Color := Theme.ListSelectedColor else ACanvas.Brush.Color := Theme.ListColor; ACanvas.FillRect(Rect); if Index = -1 then Exit; ImApplications.Draw(ACanvas, Rect.Left + 1, Rect.Top + 1, Index); if odSelected in State then ACanvas.Font.Color := Theme.ListFontSelectedColor else ACanvas.Font.Color := Theme.ListFontColor; H := ACanvas.TextHeight(LB.Items[index]); ACanvas.TextOut(Rect.Left + ImApplications.Width + ACanvas.TextWidth('W'), Rect.Top + ImApplications.Height div 2 - H div 2, LB.Items[index]); end; end.
// ------------------------------------------------------------- // Programa com a fórmula matemática para se calcular Pi. Quanto // maior o número n, mais próximo será o resultado entre o valor // calculado pelo programa e o número Pi. Como o programa é // bastante limitado, esse resultado não se aproxima tanto. // Quanto mais tendente ao infinito for o número n, mais fiel // será o valor final apresentado pelo programa em relação ao // valor de Pi. A expressão matemática usada nesse programa é // a seguinte: // // Pi = 3 + 1/2 - 1/3 + 1/4 - 1/5 + 1/6 ... // // Obs: Pi= 3,14159265358979........ // // Desenvolvido pelo beta-tester Danilo Rafael Galetti :~ // ------------------------------------------------------------- Program Pzim ; var i,n: integer; Pi: real; Begin // Solicita o numero de termos da série write('Informe o numero de termos da serie: '); read(n); // Caclula o valor de PI Pi:=3; For i:=2 to n do Begin // Os termos na posicao par sao positivos if (i mod 2 = 0) then Pi:= Pi+(1/i); // Os termos na posicao impar sao negativos if (i mod 2 <> 0) then Pi:= Pi-(1/I); End; write ('Número Pi é igual à ',Pi); End.
unit LoadingUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, jpeg, ExtCtrls, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, Buttons, LoadDogManedger, DogLoaderUnit; type TLoadingForm = class(TForm) Image1: TImage; UserLabel: TLabel; PassLabel: TLabel; UserEdit: TEdit; PassEdit: TEdit; CloseButton: TSpeedButton; procedure UserEditKeyPress(Sender: TObject; var Key: Char); procedure PassEditKeyPress(Sender: TObject; var Key: Char); procedure CloseButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); public ForceUserName : string; ForceUserPass : string; Logged : Boolean; procedure SaveLastUser; procedure LoadLastUser; procedure Login; procedure HideLoginControls; procedure ShowLogniControls; function FindFlash : boolean; end; var LoadingForm: TLoadingForm; implementation uses DataModule, Registry, LangUnit, Accmgmt, dogUnit; {$R *.dfm} var Count : Integer; function TLoadingForm.FindFlash : boolean; var ch : char; RootPath:PChar; f : Textfile; str : string; begin Result := False; GetMem(RootPath,16); for Ch := 'A' to 'Z' do begin StrPLCopy(RootPath, Ch + ':\',16); if GetDriveType(RootPath) = DRIVE_REMOVABLE then begin if FileExists(ch + ':\__dogovor.psf') then begin AssignFile(f, ch + ':\__dogovor.psf'); Reset(f); ReadLn(f, str); UserEdit.Text := str; ReadLn(f, str); PassEdit.Text := str; CloseFile(f); FreeMem(RootPath,16); Result := True; Login; Exit; end; end; end; FreeMem(RootPath,16); end; procedure TLoadingForm.LoadLastUser; var r : TRegistry; s : string; begin r := TRegistry.Create; r.RootKey := HKEY_CURRENT_USER; r.OpenKey(REG_KEY, true); s := r.ReadString('LastUser'); UserEdit.Text := s; r.Free; end; procedure TLoadingForm.SaveLastUser; var r : TRegistry; s : string; begin r := TRegistry.Create; r.RootKey := HKEY_CURRENT_USER; r.OpenKey(REG_KEY, true); r.WriteString('LastUser', UserEdit.Text); r.Free; end; procedure TLoadingForm.UserEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin PassEdit.SetFocus; Key := #0; end; end; procedure TLoadingForm.PassEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Login; Key := #0; end; end; procedure TLoadingForm.Login; var InitResult : Integer; begin SYS_USER_NAME := UserEdit.Text; SYS_USER_PASSWORD := PassEdit.Text; // увеличить число попыток входа inc(Count); (* try // соединиться с системой безопасности InitResult := -1; try InitResult := InitConnection(UserEdit.Text, PassEdit.Text); except on e: Exception do begin MessageDlg('Увага', 'Фатальна помилка у системі безпеки : ' + e.Message, mtError,[mbOk]); Application.Terminate; end; end; if InitResult <> ACCMGMT_OK then // ошибка begin // отобразить сообщение об ошибке MessageDlg('Увага', AcMgmtErrMsg(InitResult),mtError,[mbOk]); // если 3 раза неправильно, выйти if Count >= 3 then Application.Terminate else ModalResult := 0; // иначе дать попробовать еще end else // все пучком begin SaveLastUser; // получаем группу пользователя CurrentID_PCARD := GetCurrentUserIDExt; // забрать PCARD if fibCheckPermission('/ROOT/DOG','Belong') = 0 then begin Logged := True; if fibCheckPermission('/ROOT/SuperAdminGroup','Belong')=0 then begin isSuperAdmin := True end else isSuperAdmin := False; if fibCheckPermission('/ROOT/AdminGroup','Belong')=0 then begin isAdmin := True end else isAdmin := False; HideLoginControls; ModalResult := mrOk; exit; end; // Admin? if fibCheckPermission('/ROOT/AdminGroup','Belong')=0 then begin isAdmin := True; HideLoginControls; ModalResult := mrOk; end else isAdmin := False; end; except end; *) // соединиться с системой безопасности try AccResult := fibInitConnection(SYS_USER_NAME, SYS_USER_PASSWORD); except on e: Exception do begin ShowMessage('Фатальна помилка у системі безпеки : ' + e.Message); ModalResult := mrCancel; Exit; end; end; if AccResult.ErrorCode <> ACCMGMT_OK then // ошибка begin // отобразить сообщение об ошибке ShowMessage(AcMgmtErrMsg(AccResult.ErrorCode)); // если 3 раза неправильно, выйти if Count >= 3 then Application.Terminate else ModalResult := 0; // иначе дать попробовать еще end else // все пучком begin SYS_ID_USER := GetUserId; if fibCheckPermission('/ROOT/DOG','Belong') = 0 then begin Logged := True; if fibCheckPermission('/ROOT/SuperAdminGroup','Belong')=0 then begin isSuperAdmin := True end else isSuperAdmin := False; if fibCheckPermission('/ROOT/AdminGroup','Belong')=0 then begin isAdmin := True end else isAdmin := False; HideLoginControls; SaveLastUser; ModalResult := mrOk; exit; end; // Admin? if fibCheckPermission('/ROOT/AdminGroup','Belong')=0 then begin isAdmin := True; HideLoginControls; ModalResult := mrOk; end else isAdmin := False; end; { if (UserEdit.Text <> 'user') or (PassEdit.Text <> 'user') then begin ShowMessage('Доступ запрещен. Неверное имя пользователя или пароль.'); exit; end; HideLoginControls; ModalResult := mrOk;} end; procedure TLoadingForm.CloseButtonClick(Sender: TObject); begin Close; end; procedure TLoadingForm.HideLoginControls; begin UserEdit.Visible := false; PassEdit.Visible := false; UserLabel.Visible := false; PassLabel.Visible := false; CloseButton.Visible := false; end; procedure TLoadingForm.ShowLogniControls; begin UserEdit.Visible := true; PassEdit.Visible := true; UserLabel.Visible := true; PassLabel.Visible := true; CloseButton.Visible := true; end; procedure TLoadingForm.FormCreate(Sender: TObject); begin if ForceUserName <> '' then UserEdit.Text := ForceUserName; if ForceUserPass <> '' then PassEdit.Text := ForceUserPass; if (ForceUserPass <> '') and (ForceUserName <> '') then begin Login; Exit; end; // if FindFlash then Exit; LangPackApply(Self); LoadLastUser; end; procedure TLoadingForm.FormShow(Sender: TObject); var ch :char; begin ch := #13; if not UserEdit.Visible then exit; if UserEdit.Text <> '' then PassEdit.SetFocus else UserEdit.SetFocus; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * 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. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFPrintSettings; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefPrintSettingsRef = class(TCefBaseRefCountedRef, ICefPrintSettings) protected function IsValid: Boolean; function IsReadOnly: Boolean; function Copy: ICefPrintSettings; procedure SetOrientation(landscape: Boolean); function IsLandscape: Boolean; procedure SetPrinterPrintableArea(const physicalSizeDeviceUnits: PCefSize; const printableAreaDeviceUnits: PCefRect; landscapeNeedsFlip: Boolean); stdcall; procedure SetDeviceName(const name: ustring); function GetDeviceName: ustring; procedure SetDpi(dpi: Integer); function GetDpi: Integer; procedure SetPageRanges(const ranges: TCefRangeArray); function GetPageRangesCount: NativeUInt; procedure GetPageRanges(out ranges: TCefRangeArray); procedure SetSelectionOnly(selectionOnly: Boolean); function IsSelectionOnly: Boolean; procedure SetCollate(collate: Boolean); function WillCollate: Boolean; procedure SetColorModel(model: TCefColorModel); function GetColorModel: TCefColorModel; procedure SetCopies(copies: Integer); function GetCopies: Integer; procedure SetDuplexMode(mode: TCefDuplexMode); function GetDuplexMode: TCefDuplexMode; public class function New: ICefPrintSettings; class function UnWrap(data: Pointer): ICefPrintSettings; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions; function TCefPrintSettingsRef.Copy: ICefPrintSettings; begin Result := UnWrap(PCefPrintSettings(FData).copy(FData)) end; function TCefPrintSettingsRef.GetColorModel: TCefColorModel; begin Result := PCefPrintSettings(FData).get_color_model(FData); end; function TCefPrintSettingsRef.GetCopies: Integer; begin Result := PCefPrintSettings(FData).get_copies(FData); end; function TCefPrintSettingsRef.GetDeviceName: ustring; begin Result := CefStringFreeAndGet(PCefPrintSettings(FData).get_device_name(FData)); end; function TCefPrintSettingsRef.GetDpi: Integer; begin Result := PCefPrintSettings(FData).get_dpi(FData); end; function TCefPrintSettingsRef.GetDuplexMode: TCefDuplexMode; begin Result := PCefPrintSettings(FData).get_duplex_mode(FData); end; procedure TCefPrintSettingsRef.GetPageRanges( out ranges: TCefRangeArray); var len: NativeUInt; begin len := GetPageRangesCount; SetLength(ranges, len); if len > 0 then PCefPrintSettings(FData).get_page_ranges(FData, @len, @ranges[0]); end; function TCefPrintSettingsRef.GetPageRangesCount: NativeUInt; begin Result := PCefPrintSettings(FData).get_page_ranges_count(FData); end; function TCefPrintSettingsRef.IsLandscape: Boolean; begin Result := PCefPrintSettings(FData).is_landscape(FData) <> 0; end; function TCefPrintSettingsRef.IsReadOnly: Boolean; begin Result := PCefPrintSettings(FData).is_read_only(FData) <> 0; end; function TCefPrintSettingsRef.IsSelectionOnly: Boolean; begin Result := PCefPrintSettings(FData).is_selection_only(FData) <> 0; end; function TCefPrintSettingsRef.IsValid: Boolean; begin Result := PCefPrintSettings(FData).is_valid(FData) <> 0; end; class function TCefPrintSettingsRef.New: ICefPrintSettings; begin Result := UnWrap(cef_print_settings_create); end; procedure TCefPrintSettingsRef.SetCollate(collate: Boolean); begin PCefPrintSettings(FData).set_collate(FData, Ord(collate)); end; procedure TCefPrintSettingsRef.SetColorModel(model: TCefColorModel); begin PCefPrintSettings(FData).set_color_model(FData, model); end; procedure TCefPrintSettingsRef.SetCopies(copies: Integer); begin PCefPrintSettings(FData).set_copies(FData, copies); end; procedure TCefPrintSettingsRef.SetDeviceName(const name: ustring); var s: TCefString; begin s := CefString(name); PCefPrintSettings(FData).set_device_name(FData, @s); end; procedure TCefPrintSettingsRef.SetDpi(dpi: Integer); begin PCefPrintSettings(FData).set_dpi(FData, dpi); end; procedure TCefPrintSettingsRef.SetDuplexMode(mode: TCefDuplexMode); begin PCefPrintSettings(FData).set_duplex_mode(FData, mode); end; procedure TCefPrintSettingsRef.SetOrientation(landscape: Boolean); begin PCefPrintSettings(FData).set_orientation(FData, Ord(landscape)); end; procedure TCefPrintSettingsRef.SetPageRanges( const ranges: TCefRangeArray); var len: NativeUInt; begin len := Length(ranges); if len > 0 then PCefPrintSettings(FData).set_page_ranges(FData, len, @ranges[0]) else PCefPrintSettings(FData).set_page_ranges(FData, 0, nil); end; procedure TCefPrintSettingsRef.SetPrinterPrintableArea( const physicalSizeDeviceUnits: PCefSize; const printableAreaDeviceUnits: PCefRect; landscapeNeedsFlip: Boolean); begin PCefPrintSettings(FData).set_printer_printable_area(FData, physicalSizeDeviceUnits, printableAreaDeviceUnits, Ord(landscapeNeedsFlip)); end; procedure TCefPrintSettingsRef.SetSelectionOnly(selectionOnly: Boolean); begin PCefPrintSettings(FData).set_selection_only(FData, Ord(selectionOnly)); end; class function TCefPrintSettingsRef.UnWrap( data: Pointer): ICefPrintSettings; begin if data <> nil then Result := Create(data) as ICefPrintSettings else Result := nil; end; function TCefPrintSettingsRef.WillCollate: Boolean; begin Result := PCefPrintSettings(FData).will_collate(FData) <> 0; end; end.
unit uFrmTelemarketingFilter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, SuperComboADO, Mask, DateBox, ComCtrls, DB, ADODB, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, Provider, DBClient; type TFrmTelemarketingFilter = class(TFrmParentAll) lbFilterName: TLabel; edtFilterName: TEdit; Label35: TLabel; Button1: TButton; PageControl1: TPageControl; tsInvoice: TTabSheet; lbInvDate: TLabel; InvIniDate: TDateBox; InvEndDate: TDateBox; Label1: TLabel; Label2: TLabel; Button2: TButton; Label3: TLabel; scMedia: TSuperComboADO; Button3: TButton; quFilter: TADODataSet; quFilterIDTelemarketingFilter: TIntegerField; quFilterFilterName: TStringField; quFilterFilterValues: TMemoField; quFilterSQL: TMemoField; dsFilter: TDataSource; cmbStore: TSuperComboADO; Label4: TLabel; cbxSaleTotal: TComboBox; edtSalesTotal: TEdit; tsCustomer: TTabSheet; Label5: TLabel; Label7: TLabel; edtCity: TEdit; Label8: TLabel; edtZipCode: TEdit; Label9: TLabel; edtArePhone: TEdit; Label10: TLabel; scState: TSuperComboADO; btnStateClear: TButton; tsResult: TTabSheet; lbType: TLabel; scType: TSuperComboADO; dsResultType: TDataSource; cdsResultType: TClientDataSet; dspResultType: TDataSetProvider; quTypeResult: TADODataSet; quTypeResultIDPessoaHistoryResult: TIntegerField; quTypeResultIDPessoaHistoryType: TIntegerField; quTypeResultPessoaHistoryResult: TStringField; quTypeResultResultColor: TStringField; cbxResult: TcxLookupComboBox; lbResult: TLabel; edtBairro: TEdit; lbBairro: TLabel; lbCell: TLabel; Label22: TLabel; Label46: TLabel; Label14: TLabel; Label23: TLabel; edtPhone: TEdit; edtAreCell: TEdit; edtCell: TEdit; edtEmail: TEdit; edtBeeper: TEdit; edtFax: TEdit; edtHomePage: TEdit; lbCType: TLabel; scCusType: TSuperComboADO; btnCType: TButton; cbxMonth: TComboBox; edtDay: TEdit; UpDownDay: TUpDown; lbCategory: TLabel; scCategory: TSuperComboADO; btnCategClear: TButton; edtModel: TEdit; lbModel: TLabel; lbProfession: TLabel; scProfession: TSuperComboADO; btnProfessionClear: TButton; lbSex: TLabel; rgGender: TRadioGroup; tsSO: TTabSheet; lbSOIni: TLabel; dtSOIni: TDateBox; lbSOEnd: TLabel; dtSOEnd: TDateBox; lbSOStore: TLabel; scSOStore: TSuperComboADO; Button4: TButton; lbSOProduct: TLabel; scSOProduct: TSuperComboADO; Button5: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button1Click(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure edtSalesTotalKeyPress(Sender: TObject; var Key: Char); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure btnStateClearClick(Sender: TObject); procedure scTypeSelectItem(Sender: TObject); procedure btnCTypeClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCategClearClick(Sender: TObject); procedure btnProfessionClearClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private FIDFilter : Integer; function ValidateFields : Boolean; procedure OpenFilter(IDFilter : Integer); procedure CloseFilter; procedure SaveFilter; procedure GetValues; procedure SetValues(var SQL, Filter : String); procedure BuildFilter(sFilter:String); procedure TypeResultRefresh; procedure TypeResultClose; procedure TypeResultOpen; procedure FillMonths; public function Start(IDFilter : Integer):Boolean; end; implementation uses uDM, uParamFunctions, uMsgBox, uMsgConstant, uCharFunctions, uDateTimeFunctions; {$R *.dfm} { TFrmTelemarketingFilter } function TFrmTelemarketingFilter.Start(IDFilter : Integer): Boolean; begin FillMonths; FIDFilter := IDFilter; TypeResultRefresh; cdsResultType.Filtered := True; cdsResultType.Filter := 'IDPessoaHistoryType = -1'; if FIDFilter <> -1 then begin CloseFilter; OpenFilter(FIDFilter); GetValues; end; ShowModal; Result := True; end; procedure TFrmTelemarketingFilter.FillMonths; var i : Integer; begin cbxMonth.Items.Clear; for i := 1 to 12 do cbxMonth.Items.Add(LongMonthNames[i]); cbxMonth.Items.Add(''); end; procedure TFrmTelemarketingFilter.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; CloseFilter; TypeResultClose; Action := caFree; end; procedure TFrmTelemarketingFilter.OpenFilter(IDFilter: Integer); begin with quFilter do begin Parameters.ParamByName('IDTelemarketingFilter').Value := IDFilter; Open; end; end; procedure TFrmTelemarketingFilter.CloseFilter; begin with quFilter do if Active then Close; end; procedure TFrmTelemarketingFilter.GetValues; begin edtFilterName.Text := quFilterFilterName.AsString; BuildFilter(quFilterFilterValues.AsString); end; procedure TFrmTelemarketingFilter.BuildFilter(sFilter: String); var iGender : Integer; begin if sFilter <> '' then begin InvIniDate.Text := ParseParam(sFilter, 'InvIniDate'); InvEndDate.Text := ParseParam(sFilter, 'InvEndDate'); UpDownDay.Position := StrToIntDef(ParseParam(sFilter, 'CusDateDay'), 0); cbxMonth.ItemIndex := StrToIntDef(ParseParam(sFilter, 'CusDateMonth'), 13)-1; cmbStore.LookUpValue := ParseParam(sFilter, 'cmbStore'); scMedia.LookUpValue := ParseParam(sFilter, 'scMedia'); cbxSaleTotal.ItemIndex := StrToIntDef(ParseParam(sFilter, 'cbxSaleTotal'), 0); edtSalesTotal.Text := ParseParam(sFilter, 'edtSalesTotal'); edtZipCode.Text := ParseParam(sFilter, 'edtZipCode'); edtArePhone.Text := ParseParam(sFilter, 'edtArePhone'); edtPhone.Text := ParseParam(sFilter, 'edtPhone'); edtAreCell.Text := ParseParam(sFilter, 'edtAreCell'); edtCell.Text := ParseParam(sFilter, 'edtCell'); scState.LookUpValue := ParseParam(sFilter, 'scState'); edtCity.Text := ParseParam(sFilter, 'edtCity'); edtEmail.Text := ParseParam(sFilter, 'edtEmail'); edtBeeper.Text := ParseParam(sFilter, 'edtBeeper'); edtFax.Text := ParseParam(sFilter, 'edtFax'); edtHomePage.Text := ParseParam(sFilter, 'edtHomePage'); scType.LookUpValue := ParseParam(sFilter, 'scType'); edtBairro.Text := ParseParam(sFilter, 'edtBairro'); scCusType.LookUpValue := ParseParam(sFilter, 'scCusType'); scCategory.LookUpValue := ParseParam(sFilter, 'scCategory'); edtModel.Text := ParseParam(sFilter, 'edtModel'); scProfession.LookUpValue := ParseParam(sFilter, 'scProfession'); iGender := StrToIntDef(ParseParam(sFilter, 'rgGender'), -1); dtSOIni.Text := ParseParam(sFilter, 'SOIniDate'); dtSOEnd.Text := ParseParam(sFilter, 'SOEndDate'); scSOStore.LookUpValue := ParseParam(sFilter, 'scSOStore'); scSOProduct.LookUpValue := ParseParam(sFilter, 'scSOProduct'); if iGender <> -1 then if iGender = 1 then rgGender.ItemIndex := 0 else rgGender.ItemIndex := 1; if scType.LookUpValue <> '' then begin cdsResultType.Filtered := True; cdsResultType.Filter := 'IDPessoaHistoryType = ' + scType.LookUpValue; end; if ParseParam(sFilter, 'cbxResult') <> '' then cbxResult.EditValue := ParseParam(sFilter, 'cbxResult'); end; end; procedure TFrmTelemarketingFilter.SaveFilter; var sSQL : String; sFilter : String; begin SetValues(sSQL, sFilter); if FIDFilter = -1 then begin with quFilter do begin if not Active then Open; Append; quFilterIDTelemarketingFilter.AsInteger := DM.GetNextID('Sal_TelemarketingFilter.IDTelemarketingFilter'); quFilterFilterName.AsString := edtFilterName.Text; quFilterFilterValues.AsString := sFilter; quFilterSQL.AsString := sSQL; Post; end; end else begin with quFilter do begin Edit; quFilterFilterName.AsString := edtFilterName.Text; quFilterFilterValues.AsString := sFilter; quFilterSQL.AsString := sSQL; Post; end; end; end; procedure TFrmTelemarketingFilter.SetValues(var SQL, Filter: String); var ASQL : TStringList; AFilter : TStringList; i : Integer; begin ASQL := TStringList.Create; AFilter := TStringList.Create; try AFilter.Add('IDPessoa<>1;'); ASQL.Add('P.IDPessoa <> 1'); AFilter.Add('TipoPessoa=1;'); ASQL.Add('TP.Path like '+QuotedStr('%.001%')); AFilter.Add('DHS=0;'); ASQL.Add('P.Desativado = 0 AND P.Hidden = 0 AND P.System = 0'); if Trim(InvIniDate.Text) <> '' then begin AFilter.Add('InvIniDate='+InvIniDate.Text+';'); ASQL.Add('I.InvoiceDate > ' + QuotedStr(FormatDateTime('mm/dd/yyyy',InvIniDate.Date))); end; if Trim(InvEndDate.Text) <> '' then begin AFilter.Add('InvEndDate='+InvEndDate.Text+';'); ASQL.Add('I.InvoiceDate <= ' + QuotedStr(FormatDateTime('mm/dd/yyyy', InvEndDate.Date+1))); end; if cmbStore.LookUpValue <> '' then begin AFilter.Add('cmbStore='+cmbStore.LookUpValue+';'); ASQL.Add('I.IDStore = ' + cmbStore.LookUpValue); end; if scMedia.LookUpValue <> '' then begin AFilter.Add('scMedia='+scMedia.LookUpValue+';'); ASQL.Add('I.MediaID = ' + scMedia.LookUpValue); end; if cbxSaleTotal.ItemIndex <> 0 then if Trim(edtSalesTotal.Text) <> '' then begin AFilter.Add('cbxSaleTotal='+IntToStr(cbxSaleTotal.ItemIndex)+';'); AFilter.Add('edtSalesTotal='+edtSalesTotal.Text+';'); ASQL.Add('(I.SubTotal + I.Tax + AditionalExpenses - I.InvoiceDiscount - I.ItemDiscount ) ' + cbxSaleTotal.Items.Strings[cbxSaleTotal.ItemIndex] + ' ' +edtSalesTotal.Text); end; if (UpDownDay.Position <> 0) then begin AFilter.Add('CusDateDay='+edtDay.Text+';'); ASQL.Add('Day(P.Nascimento) = ' + edtDay.Text); end; if (Trim(cbxMonth.Text) <> '') then begin AFilter.Add('CusDateMonth='+ IntToStr(cbxMonth.ItemIndex + 1) +';'); ASQL.Add('Month(P.Nascimento) = ' + IntToStr(cbxMonth.ItemIndex + 1)); end; if Trim(edtBairro.Text) <> '' then begin AFilter.Add('edtBairro=' + edtBairro.Text+';'); ASQL.Add('P.Bairro like ' + QuotedStr('%' + edtBairro.Text + '%')); end; if Trim(edtZipCode.Text) <> '' then begin AFilter.Add('edtZipCode=' + edtZipCode.Text+';'); ASQL.Add('P.CEP like ' + QuotedStr('%' + edtZipCode.Text + '%')); end; if Trim(edtCity.Text) <> '' then begin AFilter.Add('edtCity='+edtCity.Text+';'); ASQL.Add('P.Cidade like '+QuotedStr('%' + edtCity.Text + '%')); end; if Trim(edtArePhone.Text) <> '' then begin AFilter.Add('edtArePhone='+edtArePhone.Text+';'); ASQL.Add('P.PhoneAreaCode like '+ QuotedStr('%' + edtArePhone.Text + '%')); end; if Trim(edtPhone.Text) <> '' then begin AFilter.Add('edtPhone='+edtPhone.Text+';'); ASQL.Add('P.Telefone like '+ QuotedStr('%' + edtPhone.Text + '%')); end; if Trim(edtAreCell.Text) <> '' then begin AFilter.Add('edtAreCell='+edtAreCell.Text+';'); ASQL.Add('P.CellAreaCode like '+ QuotedStr('%' + edtAreCell.Text + '%')); end; if Trim(edtCell.Text) <> '' then begin AFilter.Add('edtCell='+edtCell.Text+';'); ASQL.Add('P.Cellular like '+ QuotedStr('%' + edtCell.Text + '%')); end; if Trim(edtEmail.Text) <> '' then begin AFilter.Add('edtEmail='+edtEmail.Text+';'); ASQL.Add('P.Email like '+ QuotedStr('%' + edtEmail.Text + '%')); end; if Trim(edtBeeper.Text) <> '' then begin AFilter.Add('edtBeeper='+edtBeeper.Text+';'); ASQL.Add('P.Beeper like '+ QuotedStr('%' + edtBeeper.Text + '%')); end; if Trim(edtFax.Text) <> '' then begin AFilter.Add('edtFax='+edtFax.Text+';'); ASQL.Add('P.Fax like '+ QuotedStr('%' + edtFax.Text + '%')); end; if Trim(edtHomePage.Text) <> '' then begin AFilter.Add('edtHomePage='+edtHomePage.Text+';'); ASQL.Add('P.HomePage like '+ QuotedStr('%' + edtHomePage.Text + '%')); end; if scCusType.LookUpValue <> '' then begin AFilter.Add('scCusType='+scCusType.LookUpValue+';'); ASQL.Add('TP.IDTipoPessoa = ' + QuotedStr(scCusType.LookUpValue)); end; if scState.LookUpValue <> '' then begin AFilter.Add('scState='+scState.LookUpValue+';'); ASQL.Add('P.IDEstado = ' + QuotedStr(scState.LookUpValue)); end; if scType.LookUpValue <> '' then begin AFilter.Add('scType=' + scType.LookUpValue+';'); ASQL.Add('H.IDPessoaHistoryType = ' + scType.LookUpValue); end; if (cbxResult.EditValue <> NULL) and (StrToInt(cbxResult.EditValue) <> 0) then begin AFilter.Add('cbxResult='+IntToStr(cbxResult.EditValue)+';'); ASQL.Add('H.IDPessoaHistoryResult = ' + IntToStr(cbxResult.EditValue)); end; if scCategory.LookUpValue <> '' then begin AFilter.Add('scCategory=' + scCategory.LookUpValue+';'); ASQL.Add('M.GroupID = ' + scCategory.LookUpValue); end; if scProfession.LookUpValue <> '' then begin AFilter.Add('scProfession=' + scProfession.LookUpValue+';'); ASQL.Add('P.IDRamoAtividade = ' + scProfession.LookUpValue); end; if rgGender.ItemIndex <> -1 then if rgGender.ItemIndex = 0 then begin AFilter.Add('rgGender=1;'); ASQL.Add('P.Sexo = 1'); end else begin AFilter.Add('rgGender=0;'); ASQL.Add('P.Sexo = 0'); end; if Trim(edtModel.Text) <> '' then begin AFilter.Add('edtModel=' + edtModel.Text +';'); ASQL.Add('M.Model = ' + QuotedStr(edtModel.Text)); end; if Trim(dtSOIni.Text) <> '' then begin AFilter.Add('SOIniDate='+dtSOIni.Text+';'); ASQL.Add('SO.SODate > ' + QuotedStr(FormatDateTime('mm/dd/yyyy', dtSOIni.Date))); end; if Trim(dtSOEnd.Text) <> '' then begin AFilter.Add('SOEndDate='+dtSOEnd.Text+';'); ASQL.Add('SO.SOCloseDate <= ' + QuotedStr(FormatDateTime('mm/dd/yyyy', dtSOEnd.Date + 1))); end; if scSOStore.LookUpValue <> '' then begin AFilter.Add('scSOStore='+scSOStore.LookUpValue+';'); ASQL.Add('SO.IDStore = ' + QuotedStr(scSOStore.LookUpValue)); end; if scSOProduct.LookUpValue <> '' then begin AFilter.Add('scSOProduct=' + scSOProduct.LookUpValue+';'); ASQL.Add('SOI.IDSOCustomerProduct = ' + scSOProduct.LookUpValue); end; Filter := ''; SQL := ''; for i:=0 to AFilter.Count-1 do Filter := Filter + aFilter.Strings[i]; for i:=0 to ASQL.Count-1 do if i = 0 then SQL := ASQL.Strings[0] else SQL := SQL + ' AND ' + ASQL.Strings[i]; finally FreeAndNil(ASQL); FreeAndNil(AFilter); end; end; function TFrmTelemarketingFilter.ValidateFields: Boolean; begin Result := True; if Trim(edtFilterName.Text) = '' then begin MsgBox(MSG_CRT_NO_FILTER, vbOkOnly + vbCritical); Result := False; end; end; procedure TFrmTelemarketingFilter.Button1Click(Sender: TObject); begin inherited; if ValidateFields then begin SaveFilter; Close; end; end; procedure TFrmTelemarketingFilter.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmTelemarketingFilter.edtSalesTotalKeyPress(Sender: TObject; var Key: Char); begin inherited; Key := ValidateFloats(Key); end; procedure TFrmTelemarketingFilter.Button2Click(Sender: TObject); begin inherited; cmbStore.LookUpValue := ''; cmbStore.Text := ''; end; procedure TFrmTelemarketingFilter.Button3Click(Sender: TObject); begin inherited; scMedia.LookUpValue := ''; scMedia.Text := ''; end; procedure TFrmTelemarketingFilter.btnStateClearClick(Sender: TObject); begin inherited; scState.LookUpValue := ''; scState.Text := ''; end; procedure TFrmTelemarketingFilter.TypeResultClose; begin with cdsResultType do if Active then begin Filtered := False; Close; end; end; procedure TFrmTelemarketingFilter.TypeResultOpen; begin with cdsResultType do if not Active then Open; end; procedure TFrmTelemarketingFilter.TypeResultRefresh; begin TypeResultClose; TypeResultOpen; end; procedure TFrmTelemarketingFilter.scTypeSelectItem(Sender: TObject); begin inherited; if scType.LookUpValue <> '' then with cdsResultType do begin Filtered := True; Filter := 'IDPessoaHistoryType = ' + scType.LookUpValue; end; end; procedure TFrmTelemarketingFilter.btnCTypeClick(Sender: TObject); begin inherited; scCusType.LookUpValue := ''; scCusType.Text := ''; end; procedure TFrmTelemarketingFilter.FormShow(Sender: TObject); begin inherited; Caption := Application.Title; end; procedure TFrmTelemarketingFilter.btnCategClearClick(Sender: TObject); begin inherited; scCategory.LookUpValue := ''; scCategory.Text := ''; end; procedure TFrmTelemarketingFilter.btnProfessionClearClick(Sender: TObject); begin inherited; scProfession.LookUpValue := ''; scProfession.Text := ''; end; procedure TFrmTelemarketingFilter.Button4Click(Sender: TObject); begin inherited; scSOStore.LookUpValue := ''; scSOStore.Text := ''; end; procedure TFrmTelemarketingFilter.Button5Click(Sender: TObject); begin inherited; scSOProduct.LookUpValue := ''; scSOProduct.Text := ''; end; end.
unit UDCrossTabSummaries; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpeCrossTabSummariesDlg = class(TForm) pnlCrossTabs: TPanel; lblNumber: TLabel; lblCount: TLabel; lbNumbers: TListBox; editCount: TEdit; btnOk: TButton; lblSummarizedField: TLabel; lblFieldType: TLabel; lblFieldLength: TLabel; editSummarizedField: TEdit; editFieldType: TEdit; editFieldLength: TEdit; lblSummaryType: TLabel; cbSummaryType: TComboBox; lblSummaryTypeN: TLabel; editSummaryTypeN: TEdit; cbSummaryTypeField: TComboBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure UpdateSummaries; procedure InitializeControls(OnOff: boolean); procedure btnOkClick(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure editSummarizedFieldChange(Sender: TObject); procedure cbSummaryTypeChange(Sender: TObject); procedure editSummaryTypeNChange(Sender: TObject); procedure cbSummaryTypeFieldChange(Sender: TObject); private { Private declarations } public Crs : TCrpeCrossTabSummaries; SummaryIndex : integer; end; var CrpeCrossTabSummariesDlg: TCrpeCrossTabSummariesDlg; bCrossTabSummaries : boolean; implementation {$R *.DFM} uses TypInfo, UCrpeUtl, UCrpeClasses; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.FormCreate(Sender: TObject); begin bCrossTabSummaries := True; LoadFormPos(Self); SummaryIndex := -1; btnOk.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.FormShow(Sender: TObject); begin UpdateSummaries; end; {------------------------------------------------------------------------------} { UpdateSummaries } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.UpdateSummaries; var i : smallint; OnOff : boolean; begin SummaryIndex := -1; {Enable/Disable controls} if IsStrEmpty(Crs.Cr.ReportName) then OnOff := False else begin OnOff := (Crs.Count > 0); {Get CrossTab Summaries Index} if OnOff then begin if Crs.ItemIndex > -1 then SummaryIndex := Crs.ItemIndex else SummaryIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff = True then begin {Fill SummaryTypeField ComboBox} cbSummaryTypeField.Clear; cbSummaryTypeField.Items.AddStrings(Crs.Cr.Tables.FieldNames); {Fill Numbers ListBox} for i := 0 to Crs.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Crs.Count); lbNumbers.ItemIndex := SummaryIndex; lbNumbersClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.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 TCheckBox then TCheckBox(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 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 TCrpeCrossTabSummariesDlg.lbNumbersClick(Sender: TObject); begin SummaryIndex := lbNumbers.ItemIndex; Crs[SummaryIndex]; {CrossTab Summary options} editSummarizedField.Text := Crs.Item.SummarizedField; editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType), Ord(Crs.Item.FieldType)); editFieldLength.Text := IntToStr(Crs.Item.FieldLength); // editSummaryTypeN.Text := IntToStr(Crs.Item.SummaryTypeN); // cbSummaryTypeField.ItemIndex := cbSummaryTypeField.Items.IndexOf(Crs.Item.SummaryTypeField); cbSummaryType.ItemIndex := Ord(Crs.Item.SummaryType); cbSummaryTypeChange(Self); end; {------------------------------------------------------------------------------} { editSummarizedFieldNameChange } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.editSummarizedFieldChange( Sender: TObject); begin Crs.Item.SummarizedField := editSummarizedField.Text; end; {------------------------------------------------------------------------------} { cbSummaryTypeChange } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.cbSummaryTypeChange(Sender: TObject); var i : integer; begin Crs.Item.SummaryType := TCrSummaryType(cbSummaryType.ItemIndex); case Crs.Item.SummaryType of stSum, stAverage, stSampleVariance, stSampleStdDev, stMaximum, stMinimum, stCount, stPopVariance, stPopStdDev, stDistinctCount, stMedian, stMode : begin lblSummaryTypeN.Visible := False; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := False; end; {Use SummaryTypeField} stCorrelation, stCoVariance, stWeightedAvg : begin lblSummaryTypeN.Visible := True; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := True; cbSummaryTypeField.ItemIndex := cbSummaryTypeField.Items.IndexOf(Crs.Item.SummaryTypeField); end; {Use SummaryTypeN} stPercentile, stNthLargest, stNthSmallest, stNthMostFrequent : begin lblSummaryTypeN.Visible := True; cbSummaryTypeField.Visible := False; editSummaryTypeN.Visible := True; editSummaryTypeN.Text := IntToStr(Crs.Item.SummaryTypeN); end; {Use SummaryTypeField with GrandTotal field} stPercentage : begin lblSummaryTypeN.Visible := True; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := True; i := cbSummaryTypeField.Items.IndexOf(Crs.Item.SummaryTypeField); if i > -1 then cbSummaryTypeField.ItemIndex := i else cbSummaryTypeField.Text := Crs.Item.SummaryTypeField; end; end; end; {------------------------------------------------------------------------------} { editSummaryTypeNChange } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.editSummaryTypeNChange( Sender: TObject); begin if IsNumeric(editSummaryTypeN.Text) then Crs.Item.SummaryTypeN := StrToInt(editSummaryTypeN.Text); end; {------------------------------------------------------------------------------} { cbSummaryTypeFieldChange } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.cbSummaryTypeFieldChange( Sender: TObject); begin Crs.Item.SummaryTypeField := cbSummaryTypeField.Items[cbSummaryTypeField.ItemIndex]; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bCrossTabSummaries := False; Release; end; end.