text
stringlengths
14
6.51M
unit CA2Tree; interface uses SysUtils, Classes, CARules2, BuildTree; type TDecNeib = array of integer; CA3Build = class(TreeBuilder) FCARul : LocRul2CA; constructor Create(CA : LocRul2CA); function CalcCells(var Cells : TLocCells) : XCell; override; end; CA3BuildDec = class(TreeBuilder) FCARul : LocRul2CA; Decod : TDecNeib; constructor Create(CA : LocRul2CA; var ADec : TDecNeib); function CalcCells(var Cells : TLocCells) : XCell; override; end; TNeibDecoder = class function DecodeCells(CA : LocRul2CA; var Cells : TLocCells) : XCell; virtual; abstract; end; CA3BuildDecoder = class(TreeBuilder) FCARul : LocRul2CA; Decoder : TNeibDecoder; constructor Create(CA : LocRul2CA; NSt : integer; var ADecod : TNeibDecoder); destructor Destroy; override; function CalcCells(var Cells : TLocCells) : XCell; override; end; procedure CreateTree(var Tr: CAIntMatrix; CA : LocRul2CA); procedure CreateDecTree(var Tr: CAIntMatrix; CA : LocRul2CA; var ADec : TDecNeib); overload; procedure CreateDecTree(var Tr: CAIntMatrix; CA : LocRul2CA; NSt : integer; ADecoder : TNeibDecoder); overload; implementation { CA3Build } function CA3Build.CalcCells(var Cells: TLocCells): XCell; begin FCARul.CalcLocCells(Result,Cells) end; constructor CA3Build.Create(CA: LocRul2CA); begin inherited Create(CA.Ns,Ca.Nx); FCARul := CA; end; procedure CreateTree(var Tr: CAIntMatrix; CA : LocRul2CA); var CA3B : CA3Build; begin try CA3B := CA3Build.Create(CA); CA3B.BuildLists; CA3B.ConvListsToTree(Tr); finally CA3B.Free end; end; { CA3BuildDec } function CA3BuildDec.CalcCells(var Cells: TLocCells): XCell; var LCells : TLocCells; i : integer; begin for i := 0 to Length(Decod) - 1 do LCells[Decod[i]] := Cells[i]; FCARul.CalcLocCells(Result,LCells) end; constructor CA3BuildDec.Create(CA: LocRul2CA; var ADec: TDecNeib); begin inherited Create(CA.Ns,Ca.Nx); FCARul := CA; Decod := ADec; end; procedure CreateDecTree(var Tr: CAIntMatrix; CA : LocRul2CA; var ADec : TDecNeib); var CA3B : CA3BuildDec; begin try CA3B := CA3BuildDec.Create(CA,ADec); CA3B.BuildLists; CA3B.ConvListsToTree(Tr); finally CA3B.Free end; end; { CA3BuildDecoder } function CA3BuildDecoder.CalcCells(var Cells: TLocCells): XCell; begin Result := Decoder.DecodeCells(FCARul,Cells); end; constructor CA3BuildDecoder.Create(CA: LocRul2CA; NSt : integer; var ADecod: TNeibDecoder); begin inherited Create(Nst,Ca.Nx); FCARul := CA; Decoder := ADecod; end; destructor CA3BuildDecoder.Destroy; begin Decoder.Free; inherited Destroy; end; procedure CreateDecTree(var Tr: CAIntMatrix; CA : LocRul2CA; NSt : integer; ADecoder : TNeibDecoder); var CA3B : CA3BuildDecoder; begin try CA3B := CA3BuildDecoder.Create(CA,NSt,ADecoder); CA3B.BuildLists; CA3B.ConvListsToTree(Tr); finally CA3B.Free end; end; end.
unit caRandom; {$INCLUDE ca.inc} interface uses // Standard Delphi units SysUtils, Windows, // ca units caClasses, caUtils; const cAdditiveRandomSize = 55; cShuffleRandomSize = 97; cCombinedMaxInt1 = MaxInt - 84; cCombinedMaxInt2 = MaxInt - 248; type PcaRandomTable = ^TcaRandomTable; TcaRandomTable = array[0..0] of Double; TcaRandomizeType = (rtSystem, rtMinStandard, rtCombined, rtAdditive, rtShuffle); //--------------------------------------------------------------------------- // IcaRandom //--------------------------------------------------------------------------- IcaRandom = interface ['{31542E2B-B33F-4AEB-A273-8DDF444B24BB}'] // Property methods function GetAsDouble: Double; function GetAsInteger: Integer; function GetLowerBound: Double; function GetLowerIntBound: Integer; function GetRandomizeType: TcaRandomizeType; function GetSeed: Integer; function GetUpperBound: Double; function GetUpperIntBound: Integer; procedure SetLowerBound(const Value: Double); procedure SetLowerIntBound(const Value: Integer); procedure SetSeed(const AValue: Integer); procedure SetUpperBound(const Value: Double); procedure SetUpperIntBound(const Value: Integer); // Properties property AsDouble: Double read GetAsDouble; property AsInteger: Integer read GetAsInteger; property Seed: Integer read GetSeed write SetSeed; property LowerBound: Double read GetLowerBound write SetLowerBound; property LowerIntBound: Integer read GetLowerIntBound write SetLowerIntBound; property RandomizeType: TcaRandomizeType read GetRandomizeType; property UpperBound: Double read GetUpperBound write SetUpperBound; property UpperIntBound: Integer read GetUpperIntBound write SetUpperIntBound; end; //--------------------------------------------------------------------------- // TcaBaseRandom //--------------------------------------------------------------------------- TcaBaseRandom = class(TcaInterfacedPersistent, IcaRandom) private // Property fields FLowerBound: Double; FLowerIntBound: Integer; FMathUtils: IcaMathUtils; FRandomizeType: TcaRandomizeType; FSeed: Integer; FUpperBound: Double; FUpperIntBound: Integer; // Property methods function GetAsDouble: Double; function GetAsInteger: Integer; function GetLowerBound: Double; function GetLowerIntBound: Integer; function GetRandomizeType: TcaRandomizeType; function GetUpperBound: Double; function GetUpperIntBound: Integer; procedure SetLowerBound(const Value: Double); procedure SetLowerIntBound(const Value: Integer); procedure SetUpperBound(const Value: Double); procedure SetUpperIntBound(const Value: Integer); protected // Protected property methods function GetSeed: Integer; virtual; procedure SetSeed(const AValue: Integer); virtual; // Protected static methods function GetAdjustedSeed(ASeed: Integer; AMaxInt: Integer = MaxInt): Integer; procedure SetRandomizeType(ARandomizeType: TcaRandomizeType); // Protected virtual methods procedure DoAdjustSeed; virtual; procedure DoGetDouble(var ADouble: Double); virtual; abstract; // Protected properties property Seed: Integer read GetSeed write SetSeed; public constructor Create(ASeed: Integer = 0); virtual; // Properties property AsDouble: Double read GetAsDouble; property AsInteger: Integer read GetAsInteger; property LowerBound: Double read GetLowerBound write SetLowerBound; property LowerIntBound: Integer read GetLowerIntBound write SetLowerIntBound; property RandomizeType: TcaRandomizeType read GetRandomizeType; property UpperBound: Double read GetUpperBound write SetUpperBound; property UpperIntBound: Integer read GetUpperIntBound write SetUpperIntBound; end; //--------------------------------------------------------------------------- // TcaMinStandardRandom //--------------------------------------------------------------------------- TcaMinStandardRandom = class(TcaBaseRandom) protected // Protected virtual methods procedure DoGetDouble(var ADouble: Double); override; public // Virtual public methods procedure AfterConstruction; override; // Promoted properties property Seed; end; //--------------------------------------------------------------------------- // IcaSystemRandom //--------------------------------------------------------------------------- IcaSystemRandom = interface ['{2C2A7FDA-3837-4148-8F39-74BB2DE8A276}'] // Public methods procedure Randomize; end; //--------------------------------------------------------------------------- // TcaSystemRandom //--------------------------------------------------------------------------- TcaSystemRandom = class(TcaBaseRandom, IcaSystemRandom) protected // Protected virtual methods procedure DoAdjustSeed; override; procedure DoGetDouble(var ADouble: Double); override; public // Virtual public methods procedure AfterConstruction; override; // Public methods procedure Randomize; // Promoted properties property Seed; end; //--------------------------------------------------------------------------- // IcaCombinedRandom //--------------------------------------------------------------------------- IcaCombinedRandom = interface ['{AA27D4CA-F5AB-4003-87B8-41F63E26EE45}'] // Property methods function GetSeed1: Integer; function GetSeed2: Integer; procedure SetSeed1(const Value: Integer); procedure SetSeed2(const Value: Integer); // Properties property Seed1: Integer read GetSeed1 write SetSeed1; property Seed2: Integer read GetSeed2 write SetSeed2; end; //--------------------------------------------------------------------------- // TcaCombinedRandom //--------------------------------------------------------------------------- TcaCombinedRandom = class(TcaBaseRandom, IcaCombinedRandom) private FSeed1: Integer; FSeed2: Integer; // Property methods function GetSeed1: Integer; function GetSeed2: Integer; procedure SetSeed1(const Value: Integer); procedure SetSeed2(const Value: Integer); protected // Protected virtual methods procedure DoGetDouble(var ADouble: Double); override; public constructor Create(ASeed1: Integer = 0; ASeed2: Integer = 0); reintroduce; // Virtual public methods procedure AfterConstruction; override; // Properties property Seed1: Integer read GetSeed1 write SetSeed1; property Seed2: Integer read GetSeed2 write SetSeed2; end; //--------------------------------------------------------------------------- // TcaDelegatedRandom //--------------------------------------------------------------------------- TcaDelegatedRandom = class(TcaBaseRandom) private // Property fields FStdRandom: TcaMinStandardRandom; FTable: PcaRandomTable; protected // Protected property methods function GetSeed: Integer; override; procedure SetSeed(const AValue: Integer); override; // Protected virtual methods function GetTableSize: Integer; virtual; abstract; procedure DoInitializeTable; virtual; // Protected properties property StdRandom: TcaMinStandardRandom read FStdRandom; property Table: PcaRandomTable read FTable; public constructor Create(ASeed: Integer = 0); override; destructor Destroy; override; end; //--------------------------------------------------------------------------- // TcaAdditiveRandom //--------------------------------------------------------------------------- TcaAdditiveRandom = class(TcaDelegatedRandom) private // Private fields FIndex1: Integer; FIndex2: Integer; protected // Protected virtual methods function GetTableSize: Integer; override; procedure DoGetDouble(var ADouble: Double); override; public constructor Create(ASeed: Integer = 0); override; // Virtual public methods procedure AfterConstruction; override; // Promoted properties property Seed; end; //--------------------------------------------------------------------------- // TcaShuffleRandom //--------------------------------------------------------------------------- TcaShuffleRandom = class(TcaDelegatedRandom) private FAux: Double; protected // Protected virtual methods function GetTableSize: Integer; override; procedure DoGetDouble(var ADouble: Double); override; procedure DoInitializeTable; override; public // Virtual public methods procedure AfterConstruction; override; // Promoted properties property Seed; end; //--------------------------------------------------------------------------- // IcaRandomTest //--------------------------------------------------------------------------- TcaRandomTestType = (ttCoupon, ttGap, ttPoker, ttUniformity); IcaRandomTest = interface ['{53267511-E7B7-4DDF-9354-0DE600604D58}'] // Property methods function GetChiScore: Double; function GetCurrentTestType: TcaRandomTestType; function GetDegsFreedom: Integer; function GetRandom: IcaRandom; procedure SetRandom(const Value: IcaRandom); // Properties property ChiScore: Double read GetChiScore; property DegsFreedom: Integer read GetDegsFreedom; property CurrentTestType: TcaRandomTestType read GetCurrentTestType; property Random: IcaRandom read GetRandom write SetRandom; end; //--------------------------------------------------------------------------- // IcaRandomCouponCollectorsTest //--------------------------------------------------------------------------- IcaRandomCouponCollectorsTest = interface(IcaRandomTest) ['{66159770-ADAA-4FB7-9130-7F4634961814}'] // Public methods procedure Run; end; //--------------------------------------------------------------------------- // IcaRandomGapTest //--------------------------------------------------------------------------- IcaRandomGapTest = interface(IcaRandomTest) ['{1818C8EA-3C90-4066-903C-4BEE709AA1E5}'] // Property methods function GetLowerBound: Double; function GetUpperBound: Double; procedure SetLowerBound(const Value: Double); procedure SetUpperBound(const Value: Double); // Public methods procedure Run; // Properties property LowerBound: Double read GetLowerBound write SetLowerBound; property UpperBound: Double read GetUpperBound write SetUpperBound; end; //--------------------------------------------------------------------------- // IcaRandomPokerTest //--------------------------------------------------------------------------- IcaRandomPokerTest = interface(IcaRandomTest) ['{44F7F081-199B-4480-AAAC-2F2E88C94512}'] // Public methods procedure Run; end; //--------------------------------------------------------------------------- // IcaRandomUniformityTest //--------------------------------------------------------------------------- IcaRandomUniformityTest = interface(IcaRandomTest) ['{73025B1E-CCFD-4074-9A9B-4AE3E38A4C19}'] // Public methods procedure Run; end; //--------------------------------------------------------------------------- // TcaRandomTest //--------------------------------------------------------------------------- TcaRandomTest = class(TcaInterfacedPersistent, IcaRandomTest, IcaRandomCouponCollectorsTest, IcaRandomGapTest, IcaRandomPokerTest, IcaRandomUniformityTest) private // Private fields FMathUtils: IcaMathUtils; // Property fields FChiScore: Double; FCurrentTestType: TcaRandomTestType; FDegsFreedom: Integer; FLowerBound: Double; FRandom: IcaRandom; FUpperBound: Double; // Private methods procedure RunCouponCollectorsTest; procedure RunGapTest; procedure RunPokerTest; procedure RunUniformityTest; // Property methods function GetChiScore: Double; function GetCurrentTestType: TcaRandomTestType; function GetDegsFreedom: Integer; function GetLowerBound: Double; function GetRandom: IcaRandom; function GetUpperBound: Double; procedure SetLowerBound(const Value: Double); procedure SetRandom(const Value: IcaRandom); procedure SetUpperBound(const Value: Double); public // Virtual public methods procedure AfterConstruction; override; // Method resolution clauses procedure IcaRandomCouponCollectorsTest.Run = RunCouponCollectorsTest; procedure IcaRandomGapTest.Run = RunGapTest; procedure IcaRandomPokerTest.Run = RunPokerTest; procedure IcaRandomUniformityTest.Run = RunUniformityTest; // Properties property ChiScore: Double read GetChiScore; property CurrentTestType: TcaRandomTestType read GetCurrentTestType; property DegsFreedom: Integer read GetDegsFreedom; property LowerBound: Double read GetLowerBound write SetLowerBound; property Random: IcaRandom read GetRandom write SetRandom; property UpperBound: Double read GetUpperBound write SetUpperBound; end; implementation //--------------------------------------------------------------------------- // TcaBaseRandom //--------------------------------------------------------------------------- constructor TcaBaseRandom.Create(ASeed: Integer = 0); begin inherited Create; FMathUtils := Utils as IcaMathUtils; FSeed := ASeed; DoAdjustSeed; end; // Protected virtual methods procedure TcaBaseRandom.DoAdjustSeed; begin FSeed := GetAdjustedSeed(FSeed); end; // Protected static methods function TcaBaseRandom.GetAdjustedSeed(ASeed: Integer; AMaxInt: Integer = MaxInt): Integer; begin if ASeed > 0 then Result := ASeed else Result := Integer(GetTickCount); while Result >= (AMaxInt - 1) do Result := Result - AMaxInt; end; procedure TcaBaseRandom.SetRandomizeType(ARandomizeType: TcaRandomizeType); begin FRandomizeType := ARandomizeType; end; // Protected property methods function TcaBaseRandom.GetSeed: Integer; begin Result := FSeed; end; procedure TcaBaseRandom.SetSeed(const AValue: Integer); begin FSeed := AValue; DoAdjustSeed; end; // Property methods function TcaBaseRandom.GetAsDouble: Double; begin DoGetDouble(Result); if (FLowerBound <> 0) or (FUpperBound <> 0) then Result := (Result * (FUpperBound - FLowerBound)) + FLowerBound; end; function TcaBaseRandom.GetAsInteger: Integer; var ADouble: Double; LowerInt: Integer; UpperInt: Integer; begin DoGetDouble(ADouble); if (FLowerIntBound <> 0) or (FUpperIntBound <> 0) then begin LowerInt := FLowerIntBound + 1; UpperInt := FUpperIntBound + 2; ADouble := (ADouble * (UpperInt - LowerInt)) + LowerInt; end; Result := FMathUtils.Trunc(ADouble) + 1; if Result > FUpperIntBound then Result := FLowerIntBound + Ord(Odd(Result)); if Result > FUpperIntBound then Dec(Result); end; function TcaBaseRandom.GetLowerBound: Double; begin Result := FLowerBound; end; function TcaBaseRandom.GetLowerIntBound: Integer; begin Result := FLowerIntBound; end; function TcaBaseRandom.GetRandomizeType: TcaRandomizeType; begin Result := FRandomizeType; end; function TcaBaseRandom.GetUpperBound: Double; begin Result := FUpperBound; end; function TcaBaseRandom.GetUpperIntBound: Integer; begin Result := FUpperIntBound; end; procedure TcaBaseRandom.SetLowerBound(const Value: Double); begin FLowerBound := Value; end; procedure TcaBaseRandom.SetLowerIntBound(const Value: Integer); begin FLowerIntBound := Value; end; procedure TcaBaseRandom.SetUpperBound(const Value: Double); begin FUpperBound := Value; end; procedure TcaBaseRandom.SetUpperIntBound(const Value: Integer); begin FUpperIntBound := Value; end; //--------------------------------------------------------------------------- // TcaMinStandardRandom //--------------------------------------------------------------------------- // Virtual public methods procedure TcaMinStandardRandom.AfterConstruction; begin inherited; SetRandomizeType(rtMinStandard); end; // Protected methods procedure TcaMinStandardRandom.DoGetDouble(var ADouble: Double); const cA = 16807; cQ = MaxInt div cA; cR = MaxInt mod cA; cOneOverM = 1 / MaxInt; var K: Integer; ASeed: Integer; begin ASeed := Seed; K := ASeed div cQ; ASeed := (cA * (ASeed - (K * cQ))) - (K * cR); if (ASeed < 0) then Inc(ASeed, MaxInt); ADouble := ASeed * cOneOverM; Seed := ASeed; end; //--------------------------------------------------------------------------- // TcaSystemRandom //--------------------------------------------------------------------------- // Public methods procedure TcaSystemRandom.Randomize; begin Seed := Integer(GetTickCount); end; // Virtual public methods procedure TcaSystemRandom.AfterConstruction; begin inherited; SetRandomizeType(rtSystem); end; // Protected virtual methods procedure TcaSystemRandom.DoAdjustSeed; begin // Bypass ancestor DoAdjustSeed methods end; procedure TcaSystemRandom.DoGetDouble(var ADouble: Double); var SavedSeed: Integer; begin SavedSeed := System.RandSeed; System.RandSeed := Seed; ADouble := System.Random; Seed := System.RandSeed; System.RandSeed := SavedSeed; end; //--------------------------------------------------------------------------- // TcaCombinedRandom //--------------------------------------------------------------------------- constructor TcaCombinedRandom.Create(ASeed1: Integer = 0; ASeed2: Integer = 0); begin inherited Create(0); SetSeed1(ASeed1); SetSeed2(ASeed2); end; // Virtual public methods procedure TcaCombinedRandom.AfterConstruction; begin inherited; SetRandomizeType(rtCombined); end; // Protected virtual methods procedure TcaCombinedRandom.DoGetDouble(var ADouble: Double); const cA1 = 40014; cQ1 = cCombinedMaxInt1 div cA1; cR1 = cCombinedMaxInt1 mod cA1; cOneOverM1 = 1 / cCombinedMaxInt1; cA2 = 40692; cQ2 = cCombinedMaxInt2 div cA2; cR2 = cCombinedMaxInt2 mod cA2; var K: Integer; SeedDiff: Integer; begin // Advance first generator K := FSeed1 div cQ1; FSeed1 := (cA1 * (FSeed1 - (K * cQ1))) - (K * cR1); if (FSeed1 < 0) then Inc(FSeed1, cCombinedMaxInt1); // Advance second generator K := FSeed2 div cQ2; FSeed2 := (cA2 * (FSeed2 - (K * cQ2))) - (K * cR2); if (FSeed2 < 0) then Inc(FSeed2, cCombinedMaxInt2); // Combine the two seeds SeedDiff := FSeed1 - FSeed2; if (SeedDiff <= 0) then SeedDiff := SeedDiff + cCombinedMaxInt1 - 1; ADouble := SeedDiff * cOneOverM1; end; // Property methods function TcaCombinedRandom.GetSeed1: Integer; begin Result := FSeed1; end; function TcaCombinedRandom.GetSeed2: Integer; begin Result := FSeed2; end; procedure TcaCombinedRandom.SetSeed1(const Value: Integer); begin FSeed1 := GetAdjustedSeed(Value, cCombinedMaxInt1); end; procedure TcaCombinedRandom.SetSeed2(const Value: Integer); begin FSeed2 := GetAdjustedSeed(Value, cCombinedMaxInt2); end; //--------------------------------------------------------------------------- // TcaDelegatedRandom //--------------------------------------------------------------------------- constructor TcaDelegatedRandom.Create(ASeed: Integer = 0); begin inherited Create(ASeed); GetMem(FTable, GetTableSize * SizeOf(Double)); FStdRandom := TcaMinStandardRandom.Create(ASeed); DoInitializeTable; end; destructor TcaDelegatedRandom.Destroy; begin FStdRandom.Free; FreeMem(FTable); inherited; end; procedure TcaDelegatedRandom.DoInitializeTable; var Index: Integer; begin for Index := Pred(GetTableSize) downto 0 do FTable^[Index] := StdRandom.AsDouble; end; // Protected property methods function TcaDelegatedRandom.GetSeed: Integer; begin Result := FStdRandom.Seed; end; procedure TcaDelegatedRandom.SetSeed(const AValue: Integer); begin FStdRandom.Seed := AValue; DoInitializeTable; end; //--------------------------------------------------------------------------- // TcaAdditiveRandom //--------------------------------------------------------------------------- constructor TcaAdditiveRandom.Create(ASeed: Integer = 0); begin inherited Create(ASeed); FIndex1 := Pred(cAdditiveRandomSize); FIndex2 := 23; end; // Virtual public methods procedure TcaAdditiveRandom.AfterConstruction; begin inherited; SetRandomizeType(rtAdditive); end; // Protected virtual methods function TcaAdditiveRandom.GetTableSize: Integer; begin Result := cAdditiveRandomSize; end; procedure TcaAdditiveRandom.DoGetDouble(var ADouble: Double); begin ADouble := FTable[FIndex1] + FTable[FIndex2]; if ADouble >= 1.0 then ADouble := ADouble - 1.0; FTable[FIndex1] := ADouble; Inc(FIndex1); if FIndex1 >= cAdditiveRandomSize then FIndex1 := 0; Inc(FIndex2); if FIndex2 >= cAdditiveRandomSize then FIndex2 := 0; end; //--------------------------------------------------------------------------- // TcaShuffleRandom //--------------------------------------------------------------------------- // Virtual public methods procedure TcaShuffleRandom.AfterConstruction; begin inherited; SetRandomizeType(rtShuffle); end; // Protected virtual methods function TcaShuffleRandom.GetTableSize: Integer; begin Result := cShuffleRandomSize; end; procedure TcaShuffleRandom.DoGetDouble(var ADouble: Double); var Index: Integer; begin Index := FMathUtils.Trunc(FAux * cShuffleRandomSize); ADouble := FTable[Index]; FAux := ADouble; FTable[Index] := StdRandom.AsDouble; end; procedure TcaShuffleRandom.DoInitializeTable; begin inherited; FAux := StdRandom.AsDouble; end; //--------------------------------------------------------------------------- // TcaRandomTest //--------------------------------------------------------------------------- const cUniformityCount = 30000; cUniformityIntervals = 100; cGapBucketCount = 10; cGapsCount = 30000; cPokerCount = 30000; cCouponCount = 30000; // Public methods // The coupon collectors test //--------------------------- // The random numbers are read one by one, converted into a number from // 0 to 4. The length of the sequence required to get a complete set of // the digits 0..4 is counted, this will vary from 5 upwards. Once a full // set is obtained, start over. Bucket the lengths of these sequences. // Apply Chi-Squared test to the buckets. // Virtual public methods procedure TcaRandomTest.AfterConstruction; begin inherited; FMathUtils := Utils as IcaMathUtils; end; // Private methods procedure TcaRandomTest.RunCouponCollectorsTest; var Bucket: array [5..20] of Integer; ChiSqVal: Double; Expected: Double; Index: Integer; LenSeq: Integer; NewVal: Integer; NumSeqs: Integer; NumVals: Integer; Occurs: array [0..4] of Boolean; Probs: array [5..20] of Double; begin // Calculate probabilities for each bucket, algorithm from Knuth Probs[20] := 1.0; for Index := 5 to 19 do begin Probs[Index] := (120.0 * FMathUtils.Stirling2(Index - 1, 4)) / FMathUtils.IntPower(5.0, Index); Probs[20] := Probs[20] - Probs[Index]; end; // an alternative to calculate the last probability value: // Probs[last] := 1.0 - ((120.0 * Stirling(Last - 1, 5)) / IntPower(5.0, Last - 1)); NumSeqs := 0; FillChar(Bucket, SizeOf(Bucket), 0); while (NumSeqs < cCouponCount) do begin // keep getting coupons (ie random numbers) until we have collected all five LenSeq := 0; NumVals := 0; FillChar(Occurs, SizeOf(Occurs), 0); repeat Inc(LenSeq); NewVal := FMathUtils.Trunc(FRandom.AsDouble * 5); if not Occurs[NewVal] then begin Occurs[NewVal] := True; Inc(NumVals); end; until NumVals = 5; // update the relevant bucket depending on the number of coupons we had to collect if LenSeq > 20 then LenSeq := 20; Inc(Bucket[LenSeq]); Inc(NumSeqs); end; // Calculate ChiSquare value} ChiSqVal := 0.0; for Index := 5 to 20 do begin Expected := Probs[Index] * NumSeqs; ChiSqVal := ChiSqVal + (FMathUtils.Sqr(Expected - Bucket[Index]) / Expected); end; // Return results FChiScore := ChiSqVal; FDegsFreedom := 15; FCurrentTestType := ttCoupon; end; // The gap test //------------- // Each random number is tested to be in the range Lower..Upper. If it // is a value of 1 is assigned, if not 0 is assigned. You'll get a stream // of 0's and 1's. The lengths of the runs of 0's are then counted. These // lengths are then bucketed, you'll get lengths of 0 upwards. These // lengths are the 'gaps' between 1's. Apply Chi-Squared test to the // buckets. procedure TcaRandomTest.RunGapTest; var BoundDiff: Double; Bucket: array [0..Pred(cGapBucketCount)] of integer; ChiSqVal: Double; Expected: Double; GapLen: Integer; Index: Integer; NumGaps: Integer; RandValue: Double; begin // Calculate gaps and fill buckets FillChar(Bucket, SizeOf(Bucket), 0); GapLen := 0; NumGaps := 0; while (NumGaps < cGapsCount) do begin RandValue := FRandom.AsDouble; if (FLowerBound <= RandValue) and (RandValue < FUpperBound) then begin if (GapLen >= cGapBucketCount) then GapLen := Pred(cGapBucketCount); Inc(Bucket[GapLen]); Inc(NumGaps); GapLen := 0; end else begin if (GapLen < cGapBucketCount) then Inc(GapLen); end; end; BoundDiff := FUpperBound - FLowerBound; ChiSqVal := 0.0; // Do all but the last bucket for Index := 0 to cGapBucketCount - 2 do begin Expected := BoundDiff * FMathUtils.IntPower(1 - BoundDiff, Index) * NumGaps; ChiSqVal := ChiSqVal + (FMathUtils.Sqr(Expected - Bucket[Index]) / Expected); end; // Do the last bucket} Index := Pred(cGapBucketCount); Expected := FMathUtils.IntPower(1 - BoundDiff, Index) * NumGaps; ChiSqVal := ChiSqVal + (FMathUtils.Sqr(Expected - Bucket[Index]) / Expected); // Return results FChiScore := ChiSqVal; FDegsFreedom := Pred(cGapBucketCount); FCurrentTestType := ttGap; end; // The poker test //--------------- // The random numbers are grouped into 'hands' of 5, and the numbers are // converted into a digit from 0..9. The number of different digits in // each hand is then counted (1..5), and this result is bucketed. Because // the probability of only one digit repeated 5 times is so low, it is // grouped into the 2-different-digit category. Apply Chi-Squared test to // the buckets. procedure TcaRandomTest.RunPokerTest; var Accum: Double; Bucket: array [0..4] of Integer; BucketNumber: Integer; ChiSqVal: Double; Divisor: Double; Expected: Double; Flag: array [0..9] of Boolean; FlagIndex: Integer; Index: Integer; NumFives: Integer; Probs: array [0..4] of Double; begin // Prepare FillChar(Bucket, SizeOf(Bucket), 0); NumFives := cPokerCount div 5; // Calculate probabilities for each bucket, algorithm from Knuth Accum := 1.0; Divisor := FMathUtils.IntPower(10.0, 5); for Index := 0 to 4 do begin Accum := Accum * (10.0 - Index); Probs[Index] := Accum * FMathUtils.Stirling2(5, Succ(Index)) / Divisor; end; // For each group of five random numbers, convert all five to a // number between 1 and 10, count the number of different digits for Index := 1 to NumFives do begin FillChar(Flag, SizeOf(Flag), 0); for FlagIndex := 1 to 5 do Flag[FMathUtils.Trunc(FRandom.AsDouble * 10.0)] := True; BucketNumber := -1; for FlagIndex := 0 to 9 do if Flag[FlagIndex] then Inc(BucketNumber); Inc(Bucket[BucketNumber]); end; // Accumulate the first bucket into the second, do calc separately - // it'll be the sum of the 'all the same' and 'two different digits' buckets Inc(Bucket[1], Bucket[0]); Expected := (Probs[0] + Probs[1]) * NumFives; ChiSqVal := FMathUtils.Sqr(Expected - Bucket[1]) / Expected; // Write the other buckets for Index := 2 to 4 do begin Expected := Probs[Index] * NumFives; ChiSqVal := ChiSqVal + (FMathUtils.Sqr(Expected - Bucket[Index]) / Expected); end; // Return values FChiScore := ChiSqVal; FDegsFreedom := 3; FCurrentTestType := ttPoker; end; // The uniformity test //-------------------- // The random numbers are partitioned into a number of equally sized // buckets between 0.0 and 1.0. On the average, each bucket should have // the same number of random numbers; ie they should be evenly spread // over the range [0.0, 0.1). Apply Chi-Squared test to the buckets. procedure TcaRandomTest.RunUniformityTest; var Bucket: array [0..Pred(cUniformityIntervals)] of Integer; BucketNumber: Integer; ChiSqVal: Double; Expected: Double; Index: Integer; begin // Fill buckets FillChar(Bucket, SizeOf(Bucket), 0); for Index := 0 to Pred(cUniformityCount) do begin BucketNumber := FMathUtils.Trunc(FRandom.AsDouble * cUniformityIntervals); Inc(Bucket[BucketNumber]); end; // Calculate chi squared Expected := cUniformityCount / cUniformityIntervals; ChiSqVal := 0.0; for Index := 0 to Pred(cUniformityIntervals) do ChiSqVal := ChiSqVal + (FMathUtils.Sqr(Expected - Bucket[Index]) / Expected); // Return values FChiScore := ChiSqVal; FDegsFreedom := Pred(cUniformityIntervals); FCurrentTestType := ttUniformity; end; // Property methods function TcaRandomTest.GetChiScore: Double; begin Result := FChiScore; end; function TcaRandomTest.GetCurrentTestType: TcaRandomTestType; begin Result := FCurrentTestType; end; function TcaRandomTest.GetDegsFreedom: Integer; begin Result := FDegsFreedom; end; function TcaRandomTest.GetLowerBound: Double; begin Result := FLowerBound; end; function TcaRandomTest.GetRandom: IcaRandom; begin Result := FRandom; end; function TcaRandomTest.GetUpperBound: Double; begin Result := FUpperBound; end; procedure TcaRandomTest.SetLowerBound(const Value: Double); begin FLowerBound := Value; end; procedure TcaRandomTest.SetRandom(const Value: IcaRandom); begin FRandom := Value; end; procedure TcaRandomTest.SetUpperBound(const Value: Double); begin FUpperBound := Value; end; end.
(*!------------------------------------------------------------ * [[APP_NAME]] ([[APP_URL]]) * * @link [[APP_REPOSITORY_URL]] * @copyright Copyright (c) [[COPYRIGHT_YEAR]] [[COPYRIGHT_HOLDER]] * @license [[LICENSE_URL]] ([[LICENSE]]) *------------------------------------------------------------- *) program app; uses cthreads, SysUtils, fano, bootstrap; var appInstance : IWebApplication; cliParams : ICliParams; svrConfig : TMhdSvrConfig; begin cliParams := (TGetOptsParams.create() as ICliParamsFactory) .addOption('host', 1) .addOption('port', 1) .build(); scrConfig := default(TMhdSvrConfig); svrConfig.host := cliParams.getOption('host', '127.0.0.1'); svrConfig.port := cliParams.getOption('port', 8080); writeln('Starting application at ', svrConfig.host, ':', svrConfig.port); svrConfig.documentRoot := getCurrentDir() + '/public'; svrConfig.serverName := 'http.fano'; svrConfig.serverAdmin := 'admin@http.fano'; svrConfig.serverSoftware := 'Fano Framework Web App'; svrConfig.timeout := 120; (*!----------------------------------------------- * Bootstrap MicroHttpd application * * @author AUTHOR_NAME <author@email.tld> *------------------------------------------------*) appInstance := TDaemonWebApplication.create( TMhdAppServiceProvider.create( TAppServiceProvider.create(), svrConfig ), TAppRoutes.create() ); appInstance.run(); end.
unit Vigilante.Build.Service.Impl; interface uses System.JSON, Vigilante.Build.Service, Vigilante.Build.Model, Vigilante.Build.Repositorio, Vigilante.Build.Event; type TBuildService = class(TInterfacedObject, IBuildService) private FBuildRepositorio: IBuildRepositorio; FBuildEvent: IBuildEvent; function TratarURL(const AURL: string): string; protected procedure LancarEvento(const ABuildModel: IBuildModel); public constructor Create(const BuildRepositorio: IBuildRepositorio; const BuildEvent: IBuildEvent); function AtualizarBuild(const BuildModel: IBuildModel): IBuildModel; end; implementation uses System.SysUtils, System.StrUtils, ContainerDI; constructor TBuildService.Create(const BuildRepositorio: IBuildRepositorio; const BuildEvent: IBuildEvent); begin FBuildRepositorio := BuildRepositorio; FBuildEvent := BuildEvent; end; function TBuildService.AtualizarBuild(const BuildModel: IBuildModel) : IBuildModel; var _url: string; _novoBuild: IBuildModel; begin Result := nil; _url := BuildModel.URL; _url := TratarURL(_url); _novoBuild := FBuildRepositorio.BuscarBuild(_url); if not Assigned(_novoBuild) then Exit; _novoBuild.DefinirID(BuildModel.Id); if not _novoBuild.Equals(BuildModel) then LancarEvento(_novoBuild); Result := _novoBuild; end; procedure TBuildService.LancarEvento(const ABuildModel: IBuildModel); begin if not Assigned(FBuildEvent) then Exit; FBuildEvent.Notificar(ABuildModel); end; function TBuildService.TratarURL(const AURL: string): string; begin Result := AURL; if not AURL.EndsWith('api/json', True) then Result := AURL + '/api/json'; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Datasnap.DSHTTPCommon; interface uses System.JSON, System.Classes, Data.DBXCommon, Data.DbxDatasnap, Data.DBXPlatform, DataSnap.DSService, Datasnap.DSCommon, System.Generics.Collections, System.SysUtils; type /// <summary>Enumerates the HTTP command types processed by /// DataSnap.</summary> TDSHTTPCommandType = (hcUnknown, hcGET, hcPOST, hcDELETE, hcPUT, hcOther); TDSHTTPRequest = class; TDSHTTPResponse = class; TDSHTTPContext = class; /// <summary>Encapsulates objects involved in dispatching HTTP /// requests.</summary> TDSHTTPDispatch = class public type TOwnedObjects = class private FDictionary: TDictionary<string, TObject>; function GetItem(const AName: string): TObject; public constructor Create; destructor Destroy; override; procedure Add(const AObject: TObject); overload; procedure Add(const AName: string; const AObject: TObject); overload; procedure Remove(const AName: string); function Extract(const AName: string): TPair<string, TObject>; function TryGetValue(const AName: string; out AValue: TObject): Boolean; property Items[const I: string]: TObject read GetItem; end; private FOwnedObjects: TOwnedObjects; FRequest: TDSHTTPRequest; FResponse: TDSHTTPResponse; FContext: TDSHTTPContext; function GetOwnedObjects: TOwnedObjects; public constructor Create(const AContext: TDSHTTPContext; const ARequest: TDSHTTPRequest; const AResponse: TDSHTTPResponse); destructor Destroy; override; property Context: TDSHTTPContext read FContext; property Request: TDSHTTPRequest read FRequest; property Response: TDSHTTPResponse read FResponse; /// <summary>Objects that should be destroyed after the request is dispatched. /// </summary> property OwnedObjects: TOwnedObjects read GetOwnedObjects; end; /// <summary>Abstract DataSnap HTTP Context /// </summary> TDSHTTPContext = class public function Connected: Boolean; virtual; abstract; end; /// <summary>Abstract DataSnap HTTP Request /// </summary> TDSHTTPRequest = class protected function GetCommand: string; virtual; abstract; function GetCommandType: TDSHTTPCommandType; virtual; abstract; function GetDocument: string; virtual; abstract; function GetParams: TStrings; virtual; abstract; function GetPostStream: TStream; virtual; abstract; function GetAuthUserName: string; virtual; abstract; function GetAuthPassword: string; virtual; abstract; function GetURI: string; virtual; abstract; function GetPragma: string; virtual; abstract; function GetAccept: string; virtual; abstract; function GetRemoteIP: string; virtual; abstract; function GetUserAgent: string; virtual; abstract; function GetProtocolVersion: string; virtual; abstract; public property CommandType: TDSHTTPCommandType read GetCommandType; property Document: string read GetDocument; // writable for isapi compatibility. Use with care property Params: TStrings read GetParams; property PostStream: TStream read GetPostStream; property AuthUserName: string read GetAuthUserName; property AuthPassword: string read GetAuthPassword; property Command: string read GetCommand; property URI: string read GetURI; property Pragma: string read GetPragma; property Accept: string read GetAccept; property RemoteIP: string read GetRemoteIP; property UserAgent: string read GetUserAgent; property ProtocolVersion: string read GetProtocolVersion; end; /// <summary>Abstract DataSnap HTTP Response /// </summary> TDSHTTPResponse = class protected function GetContentStream: TStream; virtual; abstract; function GetResponseNo: Integer; virtual; abstract; function GetResponseText: string; virtual; abstract; procedure SetContentStream(const Value: TStream); virtual; abstract; procedure SetResponseNo(const Value: Integer); virtual; abstract; procedure SetResponseText(const Value: string); virtual; abstract; function GetContentText: string; virtual; abstract; procedure SetContentText(const Value: string); virtual; abstract; function GetContentLength: Int64; virtual; abstract; procedure SetContentLength(const Value: Int64); virtual; abstract; function GetCloseConnection: Boolean; virtual; abstract; procedure SetCloseConnection(const Value: Boolean); virtual; abstract; function GetPragma: string; virtual; abstract; procedure SetPragma(const Value: string); virtual; abstract; function GetContentType: string; virtual; abstract; procedure SetContentType(const Value: string); virtual; abstract; function GetFreeContentStream: Boolean; virtual; abstract; procedure SetFreeContentStream(const Value: Boolean); virtual; abstract; public procedure SetHeaderAuthentication(const Value: string; const Realm: string); virtual; abstract; property FreeContentStream: Boolean read GetFreeContentStream write SetFreeContentStream; property ResponseNo: Integer read GetResponseNo write SetResponseNo; property ResponseText: string read GetResponseText write SetResponseText; property ContentType: string read GetContentType write SetContentType; property ContentStream: TStream read GetContentStream write SetContentStream; property ContentText: string read GetContentText write SetContentText; property ContentLength: Int64 read GetContentLength write SetContentLength; property CloseConnection: Boolean read GetCloseConnection write SetCloseConnection; property Pragma: string read GetPragma write SetPragma; end; /// <summary> User event for logging http requests /// </summary> TDSHTTPServiceTraceEvent = procedure(Sender: TObject; AContext: TDSHTTPContext; ARequest: TDSHTTPRequest; AResponse: TDSHTTPResponse) of object; /// <summary> User event for capturing and optionally modifying REST results before they are returned. /// </summary> /// <remarks>The JSON value passed in is not wrapped in a 'result' object. If Handled is set to false, /// then the caller will wrap the value of ResultVal like this: {'result':ResultVal}. /// Note also that the value passed in may (and probably will) be a JSON Array, containing /// one or more return values, depending on the method having been invoked. /// If you change the value held by ResultVal, the new value will be returned. /// </remarks> /// <param name="Sender">The instance invoking the event.</param> /// <param name="ResultVal">The JSON value being returned</param> /// <param name="Command">The command being executed</param> /// <param name="Handled">Set to true if the event handled the formatting of the result.</param> TDSRESTResultEvent = procedure(Sender: TObject; var ResultVal: TJSONValue; const Command: TDBXCommand; var Handled: Boolean) of object; /// <summary>Wrapper for an execution response. It can manage a command /// populated with either results or an error message.</summary> TDSExecutionResponse = class protected FCommand: TDBXCommand; FDBXConnection: TDBXConnection; FErrorMessage: string; FLocalConnection: Boolean; public constructor Create(Command: TDBXCommand; DBXConnection: TDBXConnection; LocalConnection: Boolean); overload; virtual; constructor Create(ErrorMessage: string); overload; virtual; destructor Destroy; override; property Command: TDBXCommand read FCommand; property ErrorMessage: string read FErrorMessage; end; /// <summary>Abstract class for common functionality of response handlers. It /// uses the result of a TDBXCommand to populate a TDSHTTPResponse object /// appropriately.</summary> TDSServiceResponseHandler = class abstract(TRequestCommandHandler) public type TParsingRequestEvent = procedure(Sender: TObject; const ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings; var AHandled: Boolean) of object; TParseRequestEvent = procedure(Sender: TObject; const ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings) of object; protected FCommandType: TDSHTTPCommandType; FCommandList: TList<TDSExecutionResponse>; FLocalConnection: Boolean; FForceResultArray: Boolean; FParsingRequestEvent: TParsingRequestEvent; FParseRequestEvent: TParseRequestEvent; function ByteContent(JsonValue: TJSONValue): TArray<Byte>; virtual; /// <summary> Returns the number of output parameters/errors combined in all of the managed commands. /// </summary> function GetResultCount: Integer; virtual; /// <summary> Populates errors into the response, if any. Returning true if errors were populated. /// </summary> function GetOKStatus: Integer; virtual; public constructor Create(CommandType: TDSHTTPCommandType; LocalConnection: Boolean); overload; virtual; destructor Destroy; override; procedure DoParsingRequest(Sender: TObject; const ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings; var AHandled: Boolean); virtual; procedure DoParseRequest(Sender: TObject; ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings); virtual; /// <summary> Adds an error message to the handler. /// </summary> procedure AddCommandError(ErrorMessage: string); override; /// <summary> Adds a TDBXCommand for this handler to use when populating the response. /// </summary> /// <remarks> Multiple commands will exist if a batch execution was done instead fo a single invocation. /// This assumes ownership of the commands. /// </remarks> procedure AddCommand(Command: TDBXCommand; DBXConnection: TDBXConnection); override; /// <summary> Clears the stored commands/errors /// </summary> procedure ClearCommands; override; /// <summary> Populates either Response or ResponseStream /// </summary> procedure GetResponse(out Response: TJSONValue; out ResponseStream: TStream; out ContainsErrors: Boolean); virtual; abstract; /// <summary> Populate the given response using the previously specified command and any /// appropriate invocation metadata passed in. /// </summary> procedure PopulateResponse(AResponseInfo: TDSHTTPResponse; InvokeMetadata: TDSInvocationMetadata); virtual; abstract; /// <summary> Handles the closing, or transitioning of the response handler. /// </summary> /// <remarks> Calling this releases the holder of responsibility to manage the memory of this instance /// any further. However, there is no guarantee that the instance will be destroyed when this is called. /// </remarks> procedure Close; virtual; abstract; /// <summary> True to pass the result object back in an array even if there was only one command executed, /// false to only pass back the result objects in an array if there was more than one command executed. /// Defaults to false. /// </summary> property ForceResultArray: Boolean read FForceResultArray write FForceResultArray; property OnParseRequest: TParseRequestEvent read FParseRequestEvent write FParseRequestEvent; property OnParsingRequest: TParsingRequestEvent read FParsingRequestEvent write FParsingRequestEvent; end; /// <summary>Base class for response handlers that will translate the DBX /// commands into JSON.</summary> TDSJsonResponseHandler = class abstract(TDSServiceResponseHandler) protected FDSService: TDSService; FServiceInstanceOwner: Boolean; FAllowStream: Boolean; FResultEvent: TDSRESTResultEvent; procedure GetCommandResponse(Command: TDBXCommand; out Response: TJSONValue; out ResponseStream: TStream); /// <summary> Allows subclasses to handle each parameter as they see fit, or return False and allow /// the base class to transform the parameter into a JSON representation. /// </summary> function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; virtual; abstract; procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); virtual; abstract; procedure ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand); virtual; public constructor Create(CommandType: TDSHTTPCommandType; DSService: TDSService; ServiceInstanceOwner: Boolean = True); overload; virtual; destructor Destroy; override; procedure GetResponse(out Response: TJSONValue; out ResponseStream: TStream; out ContainsErrors: Boolean); override; procedure PopulateResponse(ResponseInfo: TDSHTTPResponse; InvokeMetadata: TDSInvocationMetadata); override; /// <summary>Event to call when a REST call is having its result built, to be returned.</summary> property ResultEvent: TDSRESTResultEvent read FResultEvent write FResultEvent; end; /// <summary>Used internally for TResultCommandHandler /// implementations.</summary> TDSCommandComplexParams = class private [Weak]FCommand: TDBXCommand; FParameters: TList<TDBXParameter>; public constructor Create(Command: TDBXCommand); virtual; destructor Destroy; override; function GetParameterCount: Integer; function GetParameter(Index: Integer): TDBXParameter; function AddParameter(Parameter: TDBXParameter): Integer; property Command: TDBXCommand read FCommand; end; /// <summary>Wraps an instance of TRequestCommandHandler that wants to make /// itself cacheable.</summary> TDSCacheResultCommandHandler = class(TResultCommandHandler) protected FCommandWrapper: TRequestCommandHandler; FCacheCommands: TList<TDSCommandComplexParams>; public constructor Create(CommandWrapper: TRequestCommandHandler); virtual; destructor Destroy; override; function GetCommandCount: Integer; override; function GetParameterCount(Index: Integer): Integer; override; function GetCommand(Index: Integer): TDBXCommand; override; function GetCommandParameter(CommandIndex: Integer; ParameterIndex: Integer): TDBXParameter; overload; override; function GetCommandParameter(Command: TDBXCommand; Index: Integer): TDBXParameter; overload; override; property CacheCommands: TList<TDSCommandComplexParams> read FCacheCommands write FCacheCommands; end; /// <summary>Implementation of a request handler used when you don't care /// about getting a response from an execution.</summary> TDSNullResponseHandler = class(TDSJsonResponseHandler) protected function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; override; procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); override; public constructor Create(DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean = True); procedure Close; override; end; implementation uses Data.DBXClientResStrs, Data.DBXJSONCommon; const CMD_ERROR = 'error'; CHANNEL_NAME = 'ChannelName'; CLIENT_CHANNEL_ID = 'ClientChannelId'; SECURITY_TOKEN = 'SecurityToken'; AUTH_USER = 'AuthUserName'; AUTH_PASSWORD = 'AuthPassword'; { TDSServiceResponseHandler } constructor TDSServiceResponseHandler.Create(CommandType: TDSHTTPCommandType; LocalConnection: Boolean); begin FCommandType := CommandType; FCommandList := TObjectList<TDSExecutionResponse>.Create; FLocalConnection := LocalConnection; ForceResultArray := False; end; destructor TDSServiceResponseHandler.Destroy; begin try ClearCommands; try FreeAndNil(FCommandList); except end; finally inherited; end; end; procedure TDSServiceResponseHandler.DoParseRequest(Sender: TObject; ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings); begin if Assigned(FParseRequestEvent) then FParseRequestEvent(Sender, ARequest, ASegments, ADSMethodName, AParamValues); end; procedure TDSServiceResponseHandler.DoParsingRequest(Sender: TObject; const ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings; var AHandled: Boolean); begin if Assigned(FParsingRequestEvent) then FParsingRequestEvent(Sender, ARequest, ASegments, ADSMethodName, AParamValues, AHandled); end; function TDSServiceResponseHandler.GetOKStatus: Integer; begin case FCommandType of hcGET, hcDELETE, hcPOST: Result := 200; hcPUT: Result := 201; else Result := 501; end; end; function TDSServiceResponseHandler.GetResultCount: Integer; var CommandWrapper: TDSExecutionResponse; Command: TDBXCommand; Count: Integer; ParamDirection: TDBXParameterDirection; I: Integer; begin Count := 0; TMonitor.Enter(FCommandList); // Do we need a lock here? try for CommandWrapper in FCommandList do begin if CommandWrapper.Command = nil then Inc(Count) else begin Command := CommandWrapper.Command; for I := 0 to Command.Parameters.Count - 1 do begin // select the output and return parameters for the response ParamDirection := Command.Parameters[I].ParameterDirection; if (ParamDirection = TDBXParameterDirections.OutParameter) or (ParamDirection = TDBXParameterDirections.InOutParameter) or (ParamDirection = TDBXParameterDirections.ReturnParameter) then begin Inc(Count); end; end; end; end; finally TMonitor.Exit(FCommandList); Result := Count; end; end; procedure TDSServiceResponseHandler.AddCommand(Command: TDBXCommand; DBXConnection: TDBXConnection); begin if (Command <> nil) and (DBXConnection <> nil) then begin TMonitor.Enter(FCommandList); try FCommandList.Add(TDSExecutionResponse.Create(Command, DBXConnection, FLocalConnection)); finally TMonitor.Exit(FCommandList); end; end; end; procedure TDSServiceResponseHandler.ClearCommands; begin TMonitor.Enter(FCommandList); try FCommandList.Clear; finally TMonitor.Exit(FCommandList); end; end; procedure TDSServiceResponseHandler.AddCommandError(ErrorMessage: string); begin if (ErrorMessage <> '') then begin TMonitor.Enter(FCommandList); try FCommandList.Add(TDSExecutionResponse.create(ErrorMessage)); finally TMonitor.Exit(FCommandList); end; end; end; function TDSServiceResponseHandler.ByteContent(JsonValue: TJSONValue): TArray<Byte>; var Buffer: TArray<Byte>; begin if Assigned(JsonValue) then begin SetLength(Buffer, JsonValue.EstimatedByteSize); SetLength(Buffer, JsonValue.ToBytes(Buffer, 0)); end; Result := Buffer; end; { TDSExecutionResponse } constructor TDSExecutionResponse.Create(Command: TDBXCommand; DBXConnection: TDBXConnection; LocalConnection: Boolean); begin FCommand := Command; FDBXConnection := DBXConnection; FLocalConnection := LocalConnection; FErrorMessage := ''; end; constructor TDSExecutionResponse.Create(ErrorMessage: string); begin FCommand := nil; FDBXConnection := nil; FErrorMessage := ErrorMessage; end; destructor TDSExecutionResponse.Destroy; begin if FCommand <> nil then FCommand.Close; if FDBXConnection <> nil then FDBXConnection.Close; FCommand.Free; // if FLocalConnection and (FDBXConnection <> nil) then // TDSServerConnection(FDBXConnection).ServerConnectionHandler.Free // else FDBXConnection.Free; inherited; end; { TDSJsonResponseHandler } constructor TDSJsonResponseHandler.Create(CommandType: TDSHTTPCommandType; DSService: TDSService; ServiceInstanceOwner: Boolean); begin if not Assigned(DSService) then Raise TDSServiceException.Create(SRESTServiceMissing); inherited Create(CommandType, DSService.LocalConnection); FDSService := DSService; FServiceInstanceOwner := ServiceInstanceOwner; end; destructor TDSJsonResponseHandler.Destroy; begin if FServiceInstanceOwner then FreeAndNil(FDSService); inherited; end; procedure TDSJsonResponseHandler.GetCommandResponse(Command: TDBXCommand; out Response: TJSONValue; out ResponseStream: TStream); var JsonParams: TJSONArray; JsonParam: TJSONValue; I: Integer; ParamDirection: TDBXParameterDirection; OwnParams: Boolean; ConvList: TObjectList<TDBXRequestFilter>; ResponseObj: TJSONObject; Handled: Boolean; begin JsonParams := nil; OwnParams := false; ConvList := nil; ResponseStream := nil; Handled := False; try // collect the output/return parameters JsonParams := TJSONArray.Create; OwnParams := true; ConvList := TObjectList<TDBXRequestFilter>.Create(false); for I := 0 to Command.Parameters.Count - 1 do begin // select the output and return parameters for the response ParamDirection := Command.Parameters[I].ParameterDirection; if (ParamDirection = TDBXParameterDirections.OutParameter) or (ParamDirection = TDBXParameterDirections.InOutParameter) or (ParamDirection = TDBXParameterDirections.ReturnParameter) then begin JsonParam := nil; ConvList.Clear; {If a subclass doesn't handle the parameter themselves, then manage the parameter by either applying a filter on the result, or passing back the pure JSON representation} if not HandleParameter(Command, Command.Parameters[I], JsonParam, ResponseStream) then begin FDSService.FiltersForCriteria([I], I = Command.Parameters.Count - 1, ConvList); if ConvList.Count = 1 then begin if not ConvList.Items[0].CanConvert(Command.Parameters[I].Value) then Raise TDSServiceException.Create(Format(SCannotConvertParam, [I, ConvList.Items[0].Name])); JsonParam := ConvList.Items[0].ToJSON(Command.Parameters[I].Value, FDSService.LocalConnection); end else begin JsonParam := TDBXJSONTools.DBXToJSON(Command.Parameters[I].Value, Command.Parameters[I].DataType, FDSService.LocalConnection); end; end; if JsonParam <> nil then JsonParams.AddElement(JsonParam); end; end; //Store the result array as a JSON Value, to make it more generic for the event and result object JsonParam := JsonParams; if Assigned(FResultEvent) then FResultEvent(Self, JsonParam, Command, Handled); if not Handled then begin ResponseObj := TJSONObject.Create(TJSONPair.Create(TJSONString.Create('result'), JsonParam)); //allow subclasses to add to the result object if they wish ProcessResultObject(ResponseObj, Command); Response := ResponseObj; end else Response := JsonParam; OwnParams := false; finally FreeAndNil(ConvList); if OwnParams then JsonParams.Free; end; end; procedure TDSJsonResponseHandler.GetResponse(out Response: TJSONValue; out ResponseStream: TStream; out ContainsErrors: Boolean); var CommandWrapper: TDSExecutionResponse; Command: TDBXCommand; SubResponse: TJSONValue; ResultArr: TJSONArray; ErrObj: TJSONObject; begin ContainsErrors := false; ResponseStream := nil; ResultArr := nil; if ForceResultArray or (FCommandList.Count > 1) then begin ResultArr := TJSONArray.Create; end; try for CommandWrapper in FCommandList do begin //handle error message if CommandWrapper.Command = nil then begin ContainsErrors := True; ErrObj := TJSONObject.Create; ErrObj.AddPair(TJSONPair.Create(CMD_ERROR, CommandWrapper.ErrorMessage)); if ResultArr <> nil then begin ResultArr.AddElement(ErrObj); end else begin Response := ErrObj; //there is only one command if ResultArr is nil but break here anyway just to be clear break; end; end //handle DBXCommand with results populated else begin SubResponse := nil; Command := CommandWrapper.Command; try GetCommandResponse(Command, SubResponse, ResponseStream); except on E: Exception do begin ContainsErrors := True; SubResponse := TJSONString.Create(E.Message); end; end; if ResponseStream <> nil then begin //ignore the content returned and free it, because the response content will be a stream FreeAndNil(SubResponse); end else begin if ResultArr <> nil then begin if SubResponse <> nil then ResultArr.AddElement(SubResponse); end else begin Response := SubResponse; //there is only one command if ResultArr is nil but break here anyway just to be clear break; end; end; end; end; finally if (ResponseStream = nil) and (ResultArr <> nil) then begin Response := ResultArr; end else begin ResultArr.Free; end; end; end; procedure TDSJsonResponseHandler.PopulateResponse(ResponseInfo: TDSHTTPResponse; InvokeMetadata: TDSInvocationMetadata); var JsonResponse: TJSONValue; ResponseStream: TStream; ContainsErrors: Boolean; begin JsonResponse := nil; ContainsErrors := False; FAllowStream := (GetResultCount = 1); if (not Assigned(FCommandList)) or (FCommandList.Count = 0) then raise TDSServiceException.Create(SCommandUnassigned); try // only parse the Command for output if no content is specified in the invocation metadata if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseContent <> '') then begin if (InvokeMetadata.ResponseContent = ' ') then InvokeMetadata.ResponseContent := ''; ResponseInfo.ContentLength := ResponseInfo.ContentText.Length; // setting ContentText may (ISAPI, Apache) override ContentLength by bytes length // of ContentText using current response encoding ResponseInfo.ContentText := InvokeMetadata.ResponseContent; if ResponseInfo.ContentLength = 0 then ResponseInfo.ContentLength := ResponseInfo.ContentText.Length; end else begin GetResponse(JsonResponse, ResponseStream, ContainsErrors); PopulateContent(ResponseInfo, JsonResponse, ResponseStream); end; if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseCode <> 0) then ResponseInfo.ResponseNo := InvokeMetadata.ResponseCode else if ContainsErrors then ResponseInfo.ResponseNo := 500 else ResponseInfo.ResponseNo := GetOKStatus; if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseMessage <> '') then ResponseInfo.ResponseText := InvokeMetadata.ResponseMessage; if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseContentType <> '') then ResponseInfo.ContentType := InvokeMetadata.ResponseContentType; finally FreeAndNil(JsonResponse); end; end; procedure TDSJsonResponseHandler.ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand); begin //default implementation does nothing end; { TDSCommandComplexParams } constructor TDSCommandComplexParams.Create(Command: TDBXCommand); begin if Command = nil then Raise TDSServiceException.Create(SCommandUnassigned); FCommand := Command; FParameters := TList<TDBXParameter>.Create; end; destructor TDSCommandComplexParams.Destroy; begin //Parameters in the list are managed by externally FParameters.Clear; FreeAndNil(FParameters); inherited; end; function TDSCommandComplexParams.AddParameter(Parameter: TDBXParameter): Integer; begin Result := FParameters.Count; FParameters.Add(Parameter); end; function TDSCommandComplexParams.GetParameter(Index: Integer): TDBXParameter; begin if (Index > -1) and (Index < FParameters.Count) then begin Result := FParameters[Index]; end else Exit(nil); end; function TDSCommandComplexParams.GetParameterCount: Integer; begin Result := FParameters.Count; end; { TDSCacheResultCommandHandler } constructor TDSCacheResultCommandHandler.Create(CommandWrapper: TRequestCommandHandler); begin Assert(CommandWrapper <> nil); FCommandWrapper := CommandWrapper; FCacheCommands := TObjectList<TDSCommandComplexParams>.Create; end; destructor TDSCacheResultCommandHandler.Destroy; begin FCacheCommands.Clear; FreeAndNil(FCacheCommands); FreeAndNil(FCommandWrapper); inherited; end; function TDSCacheResultCommandHandler.GetCommand(Index: Integer): TDBXCommand; begin if (Index > -1) and (Index < GetCommandCount) then Exit(FCacheCommands[Index].Command) else Exit(nil); end; function TDSCacheResultCommandHandler.GetCommandCount: Integer; begin Result := FCacheCommands.Count; end; function TDSCacheResultCommandHandler.GetCommandParameter(Command: TDBXCommand; Index: Integer): TDBXParameter; var Ccp: TDSCommandComplexParams; begin Result := nil; if (Command <> nil) and (Index > -1) then begin //Search for the ComplexParams item wrapping the given Command for Ccp in FCacheCommands do begin //Command cound, break the loop, regardless of if parameter is found or not if Ccp.Command = Command then begin if Index < Ccp.GetParameterCount then begin Exit(Ccp.GetParameter(Index)); end; Break; end; end; end; end; function TDSCacheResultCommandHandler.GetCommandParameter(CommandIndex, ParameterIndex: Integer): TDBXParameter; var PList: TDSCommandComplexParams; begin if (CommandIndex > -1) and (CommandIndex < GetCommandCount) then begin PList := FCacheCommands[CommandIndex]; Exit(PList.GetParameter(ParameterIndex)); end; Exit(nil); end; function TDSCacheResultCommandHandler.GetParameterCount(Index: Integer): Integer; begin if GetCommand(Index) <> nil then begin Exit(FCacheCommands[Index].GetParameterCount); end; Exit(0); end; { TDSNullResponseHandler } procedure TDSNullResponseHandler.Close; begin //do nothing end; constructor TDSNullResponseHandler.Create(DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean); begin inherited Create(CommandType, DSService, ServiceInstanceOwner); end; function TDSNullResponseHandler.HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; begin Result := False; end; procedure TDSNullResponseHandler.PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); begin //do nothing end; { TDSHTTPDispatch.TOwnedObjects } procedure TDSHTTPDispatch.TOwnedObjects.Add(const AName: string; const AObject: TObject); begin FDictionary.Add(AName, AObject); end; procedure TDSHTTPDispatch.TOwnedObjects.Add(const AObject: TObject); begin Add(AObject.ClassName, AObject); end; constructor TDSHTTPDispatch.TOwnedObjects.Create; begin inherited; FDictionary := TObjectDictionary<string, TObject>.Create([doOwnsValues]); end; destructor TDSHTTPDispatch.TOwnedObjects.Destroy; begin FDictionary.Free; inherited; end; function TDSHTTPDispatch.TOwnedObjects.Extract(const AName: string): TPair<string, TObject>; begin Result := FDictionary.ExtractPair(AName); end; procedure TDSHTTPDispatch.TOwnedObjects.Remove(const AName: string); begin FDictionary.Remove(AName); end; function TDSHTTPDispatch.TOwnedObjects.TryGetValue(const AName: string; out AValue: TObject): Boolean; begin Result := FDictionary.TryGetValue(AName, AValue); end; function TDSHTTPDispatch.TOwnedObjects.GetItem(const AName: string): TObject; begin Result := FDictionary.Items[AName]; end; { TDSHTTPDispatch } constructor TDSHTTPDispatch.Create(const AContext: TDSHTTPContext; const ARequest: TDSHTTPRequest; const AResponse: TDSHTTPResponse); begin inherited Create; FContext := AContext; FRequest := ARequest; FResponse := AResponse; end; destructor TDSHTTPDispatch.Destroy; begin FOwnedObjects.Free; inherited; end; function TDSHTTPDispatch.GetOwnedObjects: TOwnedObjects; begin if FOwnedObjects = nil then FOwnedObjects := TOwnedObjects.Create; Result := FOwnedObjects; end; end.
unit Fillrate; interface uses Bitmaps,Render,Points,EngineTypes; procedure Fill (var SI: ShowSectorInfo; F : PFace; const L1,L2 : ScreenLine); var opId : integer = 0; implementation uses Textures; function GetRenderFuncValue (const R : RenderFunc; x,y : integer) : float; begin Result := R.vplt + R.vdx*x + R.vdy*y; end; procedure CorrectRenderFunc (var R : RenderFunc; sx,sy : integer); begin R.vdx := R.vdx / sx; R.vdy := R.vdy / sy; R.vplt := R.vplt + R.vdx*1.0 + R.vdy*0.5; end; type RenderPoint = record x,y : integer; w,tx,ty,txw,tyw : float; end; procedure ShiftRenderPoint(var P: RenderPoint; dx : integer; dw,dtx,dty : float); begin Inc(P.x, dx); P.w := P.w + dw; P.tx := P.tx + dtx; P.ty := P.ty + dty; end; procedure MakeRenderPoint(var P : RenderPoint; const R : RenderInfo; x,y : integer); begin P.x := x; P.y := y; P.w := GetRenderFuncValue(R.w , x, y); P.tx := GetRenderFuncValue(R.tx, x, y); P.ty := GetRenderFuncValue(R.ty, x, y); end; procedure PrecomputeRenderPoint (var P: RenderPoint); var z : float; const minw = 0.0001; begin if P.w<minw then z := 1/minw else z := 1/P.w; P.txw := P.tx*z; P.tyw := P.ty*z; end; {$IFOPT Q+} {$DEFINE OLD_Q} {$Q-} {$ENDIF} procedure LoopDith ( Px : PColor; w, dw :integer; Pixels : PAInt; cnt : integer; tx,dtx,ty,dty,odx,ody,mx,my,sx : integer); var i : integer; begin for i := 0 to cnt-1 do begin Px^ := FogTable[w shr 16, Pixels[ (((tx+odx) shr 16)and mx) + (((ty+odx) shr 16)and my) shl sx ] ]; Inc(tx,dtx); Inc(ty,dty); Inc(w, dw); odx := odx xor $8000; Inc(Px); end; end; procedure LoopNoDith ( Px : PColor; w, dw :integer; Pixels : PAInt; cnt : integer; tx,dtx,ty,dty,mx,my,sx : integer); var i : integer; begin // фиксируем уровень тумана // выглядит странновато, зато сэкономили ещё 10% от скорости заливки for i := 0 to cnt-1 do begin Px^ := FogTable[w shr 16, Pixels[ ((tx shr 16)and mx) + ((ty shr 16)and my) shl sx ] ]; Inc(tx,dtx); Inc(ty,dty); Inc(w, dw); Inc(Px); end; end; {$IFDEF OLD_Q} {$Q+} {$UNDEF OLD_Q} {$ENDIF} function trunc16 (f : single) : integer; // for floor(f*65536) // FUCKING HACK var d : integer absolute f; e,m : integer; begin e := (d shr 23) and $FF; if e<>0 then m := (d and $7FFFFF) or $800000 else m := (d and $7FFFFF) shr 1; e := 134-e; // 127 + 23 - 16 - e if e>=32 then result := 0 else if e>0 then result := m shr e else result := m shl (-e); if d<0 then result := -result; end; procedure RenderLine (var p1, p2 : RenderPoint; withTail : integer; const R : RenderInfo; Px : PColor); var w,dw,tx,ty,dtx,dty : integer; dx : float; odx,ody : integer; { w1,w2,t : float; nx : integer; Mid : RenderPoint; good : boolean; } const MaxAff = 1.1; begin Inc(opID); { if p1.x>=p2.x+withTail then exit; // diff-depth test w1 := p1.w; if withTail=1 then w2 := p2.w else w2 := p2.w - R.w.vdx; if p1.x<p2.x+withTail-1 then dx := 1/(p2.x-p1.x) else dx := 0; nx := p1.x+1; if (p1.x+32<p2.x+withTail) and ((w1*MaxAff<w2) or (w2*MaxAff<w1)) then begin nx := p1.x + round( (p2.x-p1.x) * p1.w/(p1.w+p2.w);// (sqrt(p1.w*p2.w)-p1.w) / (p2.w-p1.w) ; if nx<=p1.x then nx := p1.x+1; MakeRenderPoint(Mid, R, nx, p1.y); PrecomputeRenderPoint(Mid); t := (nx-p1.x)*dx; good := ((abs(Mid.txw - (p1.txw + (p2.txw-p1.txw)*t))<0.4) and (abs(Mid.tyw - (p1.tyw + (p2.tyw-p1.tyw)*t))<0.4)); end else good := true; if good then begin } {$IFOPT Q+} {$DEFINE OLD_Q} {$Q-} {$ENDIF} // один хуй, оно по модулю if p1.x<p2.x+withTail-1 then begin dx := 1/(p2.x-p1.x); dtx := trunc16((p2.txw-p1.txw)*dx); dty := trunc16((p2.tyw-p1.tyw)*dx); dw := trunc16((p2.w-p1.w)*dx*32); end else begin dtx := 0; dty := 0; dw := 0; end; // p[i].w<=8 w := trunc16(p1.w*32) + R.Light shl 14; if w< 0 then w := 0; if w>=$1400000 then w := $13FFFFF; // а это блядозащита while w+(p2.x+withTail-p1.x-1)*dw < 0 do inc(dw); while w+(p2.x+withTail-p1.x-1)*dw >= $1400000 do dec(dw); tx := trunc16(p1.txw); ty := trunc16(p1.tyw); odx := (p1.x+p1.y) and 1 shl 15; ody := (p1.y+p1.x) and 1 shl 15; if R.Txr.Dithering then LoopDith(Px, w, dw, R.Txr.Pixels, p2.x+withTail-p1.x, tx,dtx,ty,dty,odx,ody,R.Txr.maskx,R.Txr.masky,R.Txr.shlx) else LoopNoDith(Px, w, dw, R.Txr.Pixels, p2.x+withTail-p1.x, tx,dtx,ty,dty,R.Txr.maskx,R.Txr.masky,R.Txr.shlx); //Px^ := $FF; {$IFDEF OLD_Q} {$Q+} {$UNDEF OLD_Q} {$ENDIF} { end else begin RenderLine(p1, Mid, 0 , R, Px); Inc(Px, nx-p1.x); RenderLine(Mid, p2, WithTail, R, Px); end; } end; procedure Fill (var SI: ShowSectorInfo; F : PFace; const L1,L2 : ScreenLine); var // заполнение i: integer; Line : PAColor; y1,y2 : integer; P1,P2 : RenderPoint; ONTest : Point; den : float; badLine : boolean; Px : PColor; nx : integer; LAL : integer; Mid : RenderPoint; RL1, RL2 : ScreenLine; { ldx : integer; ldw,ldtx,ldty : float; } begin Assert((L1.y1=L2.y1) and (L1.y2=L2.y2), 'Borders incompatible!'); if L1.y1>L2.y1 then y1 := L1.y1 else y1 := L2.y1; if L1.y2<L2.y2 then y2 := L1.y2 else y2 := L2.y2; Assert((y1>y2) or ((y1>=0) and (y2<SI.B.SizeY))); while (y1<=y2) and (L1.x[y1]>=L2.x[y1]) do Inc(y1); while (y2>=y1) and (L1.x[y2]>=L2.x[y2]) do Dec(y2); if SI.B.sizeX<=400 then LAL :=16 else LAL := 32; if y1<=y2 then begin if F.NextSector=nil then begin Line := PAColor(@SI.B.Pixels[y1*SI.B.stride]); if not F.inProcess then begin den := 1/(F.INormC-Dot(SI.NTest,F.INorm)); F.RI.w .vdx := Dot(SI.DX , F.INorm)*den; F.RI.w .vdy := Dot(SI.DY , F.INorm)*den; F.RI.w .vplt := Dot(SI.PLT, F.INorm)*den; F.RI.tx.vdx := Dot(SI.NTest, F.VTx)*F.RI.w.vdx + Dot(SI.DX ,F.VTx) - F.VTxc*F.RI.w.vdx; F.RI.tx.vdy := Dot(SI.NTest, F.VTx)*F.RI.w.vdy + Dot(SI.DY ,F.VTx) - F.VTxc*F.RI.w.vdy; F.RI.tx.vplt := Dot(SI.NTest, F.VTx)*F.RI.w.vplt + Dot(SI.PLT,F.VTx) - F.VTxc*F.RI.w.vplt; F.RI.ty.vdx := Dot(SI.NTest, F.VTy)*F.RI.w.vdx + Dot(SI.DX ,F.VTy) - F.VTyc*F.RI.w.vdx; F.RI.ty.vdy := Dot(SI.NTest, F.VTy)*F.RI.w.vdy + Dot(SI.DY ,F.VTy) - F.VTyc*F.RI.w.vdy; F.RI.ty.vplt := Dot(SI.NTest, F.VTy)*F.RI.w.vplt + Dot(SI.PLT,F.VTy) - F.VTyc*F.RI.w.vplt; CorrectRenderFunc(F.RI.w , SI.B.sizeX, SI.B.sizeY); CorrectRenderFunc(F.RI.tx, SI.B.sizeX, SI.B.sizeY); CorrectRenderFunc(F.RI.ty, SI.B.sizeX, SI.B.sizeY); F.RI.Txr := F.Texture; F.RI.Light := F.Light; F.inProcess := True; Inc(SI.CPF); SI.PF[SI.CPF-1] := F; end; for i := y1 to y2 do begin Assert((L1.x[i]>=0) and (L2.x[i]<=SI.B.sizeX)); if L1.x[i]<L2.x[i] then begin MakeRenderPoint(P1, F.RI, L1.x[i] , i); MakeRenderPoint(P2, F.RI, L2.x[i]-1, i); badLine := false; while (P1.w<0) or (P1.w>8) do begin // 0.125 - минимальная глубина в поле зрения Inc(P1.x); if P1.x>P2.x then begin badLine := True; break; end; P1.w := P1.w + F.RI.w .vdx; P1.tx := P1.tx + F.RI.tx.vdx; P1.ty := P1.ty + F.RI.ty.vdx; end; if not badLine then begin while (P2.w<0) or (P2.w>8) do begin Dec(P2.x); if P1.x>P2.x then begin badLine := True; break; end; P2.w := P2.w - F.RI.w .vdx; P2.tx := P2.tx - F.RI.tx.vdx; P2.ty := P2.ty - F.RI.ty.vdx; end; if not badLine then begin PrecomputeRenderPoint(P1); PrecomputeRenderPoint(P2); Px := @Line[P1.x]; { ldx := LAL; ldw := F.RI.w .vdx*LAL; ldtx := F.RI.tx.vdx*LAL; ldty := F.RI.ty.vdx*LAL; } if SI.OnlyAff then RenderLine(P1,P2,1,F.RI,Px) else repeat nx := (p1.x+LAL) and not (LAL-1); if nx<=P2.x then begin {if nx=P1.x+LAL then begin Mid := P1; ShiftRenderPoint(Mid, ldx,ldw,ldtx,ldty); end else } MakeRenderPoint(Mid, F.RI, nx, p1.y); PrecomputeRenderPoint(Mid); RenderLine(P1, Mid, 0, F.RI, Px); Inc(Px, nx-p1.x); P1 := Mid; end else begin RenderLine(P1,P2,1,F.RI,Px); break; end; until false; end; end; end; Line := PAColor(@Line[SI.B.stride]); end; end else begin if F.NextSector.inProcess=0 then begin // тадададам RL1 := L1; RL2 := L2; RL1.y1 := y1; RL1.y2 := y2; RL2.y1 := y1; RL2.y2 := y2; if F.NextSector.Skybox then begin ONTest := SI.NTest; SI.NTest := ToPoint(0,0,0); ShowSector(SI, F.NextSector^, RL1, RL2); SI.NTest := ONTest; end else begin ShowSector(SI, F.NextSector^, RL1, RL2); end; end; end; end; end; end.
unit UfrmCalculadora; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TOperacoes = (toNone, toAdicao, toSubtracao, toMultiplicacao, toDivisao); TfrmCalculadora = class(TForm) edtValor1: TEdit; edtValor2: TEdit; edtResultado: TEdit; btnSoma: TButton; btnSubtracao: TButton; btnDivisao: TButton; btnMultiplicacao: TButton; btnCalcular: TButton; lblFuncaoAcionada: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure btnSomaClick(Sender: TObject); procedure btnSubtracaoClick(Sender: TObject); procedure btnDivisaoClick(Sender: TObject); procedure btnMultiplicacaoClick(Sender: TObject); procedure btnCalcularClick(Sender: TObject); procedure FormShow(Sender: TObject); private FOperacao : TOperacoes; procedure validacaoBeforeGravacao(); public { Public declarations } end; var frmCalculadora: TfrmCalculadora; implementation uses UFuncaoCalculadora; {$R *.dfm} procedure TfrmCalculadora.btnCalcularClick(Sender: TObject); begin validacaoBeforeGravacao(); try case FOperacao of toAdicao : edtResultado.Text := FloatToStr(TFuncaoCalculadora.soma(StrToFloat(edtValor1.Text),StrToFloat(edtValor2.Text))); toSubtracao : edtResultado.Text := FloatToStr(TFuncaoCalculadora.subtrair(StrToFloat(edtValor1.Text),StrToFloat(edtValor2.Text))); toMultiplicacao : edtResultado.Text := FloatToStr(TFuncaoCalculadora.multiplicar(StrToFloat(edtValor1.Text),StrToFloat(edtValor2.Text))); toDivisao : edtResultado.Text := FloatToStr(TFuncaoCalculadora.dividir(StrToFloat(edtValor1.Text),StrToFloat(edtValor2.Text))); end; except on e:Exception do begin ShowMessage('Erro de conversão de valores. Verifique!'); end; end; end; procedure TfrmCalculadora.btnDivisaoClick(Sender: TObject); begin FOperacao := toDivisao; lblFuncaoAcionada.Caption := 'Operação de divisão'; end; procedure TfrmCalculadora.btnMultiplicacaoClick(Sender: TObject); begin FOperacao := toMultiplicacao; lblFuncaoAcionada.Caption := 'Operação de multiplicação'; end; procedure TfrmCalculadora.btnSomaClick(Sender: TObject); begin FOperacao := toAdicao; lblFuncaoAcionada.Caption := 'Operação de soma'; end; procedure TfrmCalculadora.btnSubtracaoClick(Sender: TObject); begin FOperacao := toSubtracao; lblFuncaoAcionada.Caption := 'Operação de subtração'; end; procedure TfrmCalculadora.FormShow(Sender: TObject); begin FOperacao := toNone; end; procedure TfrmCalculadora.validacaoBeforeGravacao; begin if edtValor1.Text = '' then begin ShowMessage('Valor 1 não informado'); edtValor1.SetFocus; Abort; end; if edtValor2.Text = '' then begin ShowMessage('Valor 2 não informado'); edtValor2.SetFocus; Abort; end; if FOperacao = toNone then begin ShowMessage('Informe a operação'); Abort; end; end; end.
unit SHL_XaMusic; // SemVersion: 0.2.0 // Contains TXaDecoder unfinished class. // Changelog: // 0.1.0 - test version // 0.2.0 - class functions interface // SpyroHackingLib is licensed under WTFPL uses SysUtils, Classes, SHL_Types, SHL_WaveStream, SHL_IsoReader; type TXaDecoder = class(TStream) private FImage: TIsoReader; FQuality: Boolean; FInStereo: Boolean; FOutStereo: Boolean; FSector: Integer; FStride: Integer; FWaveSize: Integer; FSamples: Integer; FExtra: array[0..31] of Byte; FBuffer: PDataChar; FCount: Integer; FPos: Integer; FVolume: Double; public function Start(Image: TIsoReader; Quality, InStereo, OutStereo: Boolean; Sector, Stride: Integer; Count: Integer = 0; Volume: Double = 1.0): Boolean; function DecodeSector(WaveOut: Pointer; Volume: Double = 1.0): Boolean; function SaveSector(Stream: TStream; Volume: Double = 1.0): Boolean; function Write(const Buffer; Count: Longint): Longint; override; function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; property Image: TIsoReader read FImage; property Quality: Boolean read FQuality; property InStereo: Boolean read FInStereo; property OutStereo: Boolean read FOutStereo; property Sector: Integer read FSector; property Stride: Integer read FStride; property Samples: Integer read FSamples; property WaveSize: Integer read FWaveSize; public class function TrackInfoByXa(XaHeader: Integer; out Channel: Byte; out Stereo: Boolean; out HiQuality: Boolean; out MinStride: Byte): Boolean; overload; class function TrackInfoByXa(XaHeader: Pointer): Boolean; overload; class function DecodeXaData(SectorData: Pointer; SaveWave: Pointer; HiQuality: Boolean; InStereo: Boolean; OutStereo: Boolean; SpecialStuff: Pointer; Volume: Double = 1.0): Boolean; class procedure XaEmprySector(WriteBodyTo: Pointer); end; implementation function TXaDecoder.Start(Image: TIsoReader; Quality, InStereo, OutStereo: Boolean; Sector, Stride: Integer; Count: Integer = 0; Volume: Double = 1.0): Boolean; begin ZeroMemory(@FExtra[0], 32); FImage := Image; FQuality := Quality; FInStereo := InStereo; FOutStereo := OutStereo; FSector := Sector; FStride := Stride; FImage.SeekToSector(FSector); if FInStereo = FOutStereo then FWaveSize := 8064 else begin if FInStereo then FWaveSize := 4032 else FWaveSize := 16128; end; if FQuality then FSamples := 37800 else FSamples := 18900; if FImage.Body > 2336 then begin FImage := nil; Result := False; end else Result := True; if Count > 0 then if FBuffer = nil then GetMem(FBuffer, 16128); FCount := Count; FPos := FWaveSize; FVolume := Volume; end; function TXaDecoder.DecodeSector(WaveOut: Pointer; Volume: Double = 1.0): Boolean; var Buffer: array[0..3000] of Byte; Next: Integer; begin if FImage = nil then begin Result := False; Exit; end; Next := FImage.Sector + FStride; ZeroMemory(@Buffer[0], 3000); FImage.ReadSectors(@Buffer[0]); FImage.SeekToSector(Next); Result := DecodeXaData(@Buffer[8], WaveOut, FQuality, FInStereo, FOutStereo, @FExtra[0], Volume); end; function TXaDecoder.SaveSector(Stream: TStream; Volume: Double = 1.0): Boolean; var Buffer: array[0..16127] of Byte; begin Result := DecodeSector(@Buffer[0], Volume); Stream.WriteBuffer(Buffer, FWaveSize); end; function TXaDecoder.Write(const Buffer; Count: Longint): Longint; begin Result := 0; end; function TXaDecoder.Read(var Buffer; Count: Longint): Longint; var Have: Integer; Save: PDataChar; begin Result := 0; if FCount = 0 then Exit; Save := @Buffer; while Count > 0 do begin Have := FWaveSize - FPos; if Have <= 0 then begin if FCount <= 0 then Exit; DecodeSector(FBuffer, FVolume); Dec(FCount); FPos := 0; Have := FWaveSize; end; if Count < Have then Have := Count; Move((FBuffer + FPos)^, Save^, Have); Inc(FPos, Have); Inc(Save, Have); Inc(Result, Have); Dec(Count, Have); end; end; function TXaDecoder.Seek(Offset: Longint; Origin: Word): Longint; begin Result := 0; end; class function TXaDecoder.TrackInfoByXa(XaHeader: Integer; out Channel: Byte; out Stereo: Boolean; out HiQuality: Boolean; out MinStride: Byte): Boolean; begin Result := False; Channel := 255; if XaHeader = -1 then Exit; Channel := (XaHeader shr 8) and 255; Result := (((XaHeader shr 16) and 255) = 100); XaHeader := XaHeader shr 24; Stereo := (XaHeader and 1) > 0; HiQuality := (XaHeader and 4) = 0; MinStride := 16; if Stereo or HiQuality then MinStride := 8; if Stereo and HiQuality then MinStride := 4; end; class function TXaDecoder.TrackInfoByXa(XaHeader: Pointer): Boolean; var Header: PInteger; Data: Integer; Channel, MinStride: Byte; Stereo, HiQuality: Boolean; begin Result := False; Header := Pinteger(XaHeader); Data := Header^; Inc(Header); if Data <> Header^ then Exit; Result := TrackInfoByXa(Data, Channel, Stereo, HiQuality, MinStride); end; class function TXaDecoder.DecodeXaData(SectorData: Pointer; SaveWave: Pointer; HiQuality: Boolean; InStereo: Boolean; OutStereo: Boolean; SpecialStuff: Pointer; Volume: Double = 1.0): Boolean; const k0: array[0..3] of Single = (0.0, 0.9375, 1.796875, 1.53125); k1: array[0..3] of Single = (0.0, 0.0, -0.8125, -0.859375); var Data: PChar; Save: PSmallInt; Stuff: PDouble; a, b, c, d: Double; x, y: array[0..1] of Double; f, r: array[0..1] of Integer; Loop, Cnt, Index, Temp, Sec: Integer; DoCopy, DoMix: Boolean; begin Result := False; Data := SectorData; Save := SaveWave; if (SectorData = nil) or (SaveWave = nil) or (SpecialStuff = nil) then Exit; DoCopy := not InStereo and OutStereo; DoMix := InStereo and not OutStereo; if DoMix then Volume := Volume / 2; Stuff := SpecialStuff; x[0] := Stuff^; Inc(Stuff); y[0] := Stuff^; if InStereo then begin Inc(Stuff); x[1] := Stuff^; Inc(Stuff); y[1] := Stuff^; end; for Loop := 1 to 18 do begin Cnt := 0; while Cnt < 8 do begin Temp := Ord(Data[4 + Cnt]); r[0] := Temp and 15; f[0] := (Temp shr 4) and 3; if InStereo then begin Temp := Ord(Data[4 + Cnt + 1]); r[1] := Temp and 15; f[1] := (Temp shr 4) and 3; end; for Index := 0 to 27 do begin Sec := 0; while True do begin a := 1 shl (12 - r[Sec]); Temp := (Ord(Data[16 + ((Cnt + Sec) shr 1) + (Index shl 2)]) shr (((Cnt + Sec) and 1) shl 2)) and 15; if Temp > 7 then b := (Temp - 16) * a else b := Temp * a; c := k0[f[Sec]] * x[Sec]; d := k1[f[Sec]] * y[Sec]; y[Sec] := x[Sec]; x[Sec] := b + c + d; if Sec = 0 then begin if not DoMix then begin Temp := Round(Volume * x[0]); if Temp < -32768 then Temp := -32768 else if Temp > 32767 then Temp := 32767; if Temp <> 0 then Result := True; Save^ := Temp; Inc(Save); if DoCopy then begin Save^ := Temp; Inc(Save); end; end; if InStereo then begin Sec := 1; Continue; end; end else begin if DoMix then Temp := Round(Volume * (x[0] + x[1])) else Temp := Round(Volume * x[1]); if Temp < -32768 then Temp := -32768 else if Temp > 32767 then Temp := 32767; if Temp <> 0 then Result := True; Save^ := Temp; Inc(Save); end; Break; end; end; if InStereo then Inc(Cnt, 2) else Inc(Cnt); end; Inc(Data, 128); end; Stuff := SpecialStuff; Stuff^ := x[0]; Inc(Stuff); Stuff^ := y[0]; if InStereo then begin Inc(Stuff); Stuff^ := x[1]; Inc(Stuff); Stuff^ := y[1]; end; end; class procedure TXaDecoder.XaEmprySector(WriteBodyTo: Pointer); var Block: Integer; Data: PInteger; begin Data := PInteger(WriteBodyTo); ZeroMemory(Data, 2328); for Block := 1 to 18 do begin Data^ := $0C0C0C0C; Inc(Data); Data^ := $0C0C0C0C; Inc(Data); Data^ := $0C0C0C0C; Inc(Data); Data^ := $0C0C0C0C; Inc(Data, 29); end; end; end.
program g2048; uses GraphABC, ABCObjects, ABCButtons, timers, controlUtils; const /// размер поля n = 4; ///размер фишки tile = 100; /// зазор между фишками zz = 5; /// отступ от левого и правого краев x0 = 5; /// отступ от верхнего и нижнего краев y0 = 5; ///Степень округления углов у фигурок roundRate = 5; ///заголовок окна windowTitle = '2048 Game!'; //Настройки цветов ///фоновый цвет! backgroundColor = RGB(187, 173, 160); ///фон пустой клетки emptySquareColor = RGB(205, 193, 180); ///интервал таймера анимационного animTimerInterval = 1; ///на сколько менять размер клеточки при анимации animDelta = 6; var ///ходил ли игрок? (это нужно будет для того, чтобы если ход не совершён, не создавать новую клеточку в таком случае) moved: boolean := false; ///анимационный таймер animationTimer: Timer; ///экземпляр класса для работы с диалогами dialogs: TDialogs; type ///возможные направления движения TDirection = (tdUp, tdDown, tdLeft, tdRight); ///наш класс на основе SquareABC, чтобы хранить тут дополнительные переменные TSquare = class(RoundRectABC) ///значение клеточки value: integer = 0; changed: boolean = false; //если произошло изменение значения (используется для анимации) ///фукция для установки значения клеточки, заодно нужных цветов procedure setNumber(number: integer); end; ///запись для хранения настроек цветов TSquareColor = record bColor, FontColor: color; end; var gField: array [1..n, 1..n] of TSquare; //наше поле состоит из наших доделанных SquareABC! ///счёт, пожалуйста! score: integer = 0; {**********************************************} //добавить очков procedure addScore(add_score: integer); begin score := score + add_score; moved := true; //раз очки прибавились, значит был совершён ход end; //обнулить количество очков procedure clearScore(); begin score := 0; end; //тут можно вывести куда-то количество очков procedure updateScore(); begin window.Title := windowTitle + '; Score: ' + IntToStr(score); end; //получить случайное начальное число (двойку или четвёрку) function getRandomNumber(): integer; begin result := Random(100) > 85 ? 4 : 2; //делаем большую вероятность выпадения именно двойки end; //вспомогательная функция для создания записи TSquareColor из фонового цвета и цвета шрифта function createColor(bColor, FontColor: Color): TSquareColor; begin result.bColor := bColor; result.FontColor := FontColor; end; procedure clearSquare(var square: TSquare); begin square.Color := emptySquareColor; square.Text := ''; square.value := 0; end; //получить клетку по позиции её function getSquareByPos(x, y: integer): TSquare; begin result := gField[x, y]; end; //получить цвет в зависимости от цифры function getSquareColorByNumber(num: integer): TSquareColor; begin case num of 2: result := createColor(rgb(238, 228, 218), rgb(119, 110, 101)); 4: result := createColor(rgb(237, 224, 200), rgb(119, 110, 101)); 8: result := createColor(rgb(242, 177, 121), rgb(249, 246, 242)); 16: result := createColor(rgb(245, 149, 99), rgb(249, 246, 242)); 32: result := createColor(rgb(246, 124, 95), rgb(249, 246, 242)); 64: result := createColor(rgb(246, 94, 59), rgb(249, 246, 242)); 128: result := createColor(rgb(237, 207, 114), rgb(249, 246, 242)); 256: result := createColor(rgb(237, 204, 97), rgb(249, 246, 242)); 512: result := createColor(rgb(237, 200, 80), rgb(249, 246, 242)); 1024: result := createColor(rgb(237, 197, 63), rgb(249, 246, 242)); 2048: result := createColor(rgb(237, 194, 46), rgb(249, 246, 242)); 4096: result := createColor(rgb(60, 58, 50), rgb(249, 246, 242)); else result := createColor(rgb(238, 228, 218), rgb(119, 110, 101)); end; end; procedure animateSquare(sq: TSquare; bigger: boolean); begin sq.changed := true; if (bigger) then begin sq.left -= animDelta; sq.Top -= animDelta; sq.Width += animDelta; sq.Height += animDelta; end else begin sq.left += animDelta; sq.Top += animDelta; sq.Width -= animDelta; sq.Height -= animDelta; end; end; procedure TSquare.setNumber(number: integer); var sc: TSquareColor; begin value := number; sc := getSquareColorByNumber(value); //получаем цвет клеточки и цвет шрифта в зависимости от номера Color := sc.bColor; //устанавливаем цвет клеточки FontColor := sc.FontColor; //устанавливаем цвет текста Text := IntToStr(value); //пишем цифру animateSquare(self, value > 2); //анимация клеточки в зависимости от значения end; //заполнить клеточку начальными пустыми значениями и параметрами procedure createSquare(var square: TSquare); begin square.Bordered := false; square.TextScale := 0.7; //размер текста? square.value := 0; end; // создаём массив квадратиков procedure CreateFields; var sq: TSquare; begin for var x := 1 to n do for var y := 1 to n do begin sq := new TSquare(x0 + (x - 1) * (tile + zz), y0 + (y - 1) * (tile + zz), tile, tile, roundRate, emptySquareColor); //создаём клетку с указанными размерами и координатами и цветом createSquare(sq); //заполним клетку начальными значениями gField[y, x] := sq; //заносим экземпляр клетки в массив end; end; procedure clearAllFields;//очистить все клетки!!!!! begin for var x := 1 to n do for var y := 1 to n do clearSquare(gField[x, y]); end; //проверяет, можно ли ходить куда-то function canMove(): boolean; var field: TSquare; begin result := false; //сначала проверка чисел по вертикалям for var x := 1 to n do begin for var y := 2 to n do begin field := gField[x, y]; //если есть хоть одна пустая клетка, то игрок уж точно может ходить ) if (field.value = 0) then begin result := true; exit; end; //Если можно сложить хоть одну пару клеток if (field.value = gField[x, y - 1].value) then begin result := true; //то значит можно ходить! exit; //И нужно выйти, ведь дальше незачем цикл гонять end; end; end; //а теперь проверка чисел по горизонталям for var y := 1 to n do begin for var x := 2 to n do begin field := gField[x, y]; //снова проверка на пустую клетку if (field.value = 0) then begin result := true; exit; end; //снова проверка, можно ли сложить два числа по горизонтали if (field.value = gField[x - 1, y].value) then begin result := true; exit; end; end; end; end; //получить случайную пустую клетку function getRandomEmptyField(): TSquare; var positions: array[0..n * n] of Point; //массив, куда будут складываться позиции свободных клеток available_count: integer = 0; begin result := nil; //по умолчанию результат будет НИЧЕГО for var x := 1 to n do for var y := 1 to n do begin if (gField[x, y].value = 0) then //если клетка свободна, то нужно добавить её в массив begin //сохраняем координаты очередной найденой пустой клетки positions[available_count].x := x; positions[available_count].y := y; inc(available_count); //увеличиваем счётчик количества свободных клеточек end; end; if (available_count > 0) then //если есть свободные клетки, begin var pos := positions[Random(available_count)]; //то выбираем одну из них случайным образом result := gField[pos.x, pos.y]; //и выдаём её в результат end; end; //есть ли ещё пустые клетки? function emptyFieldsExists(): boolean; begin result := false; for var x := 1 to n do for var y := 1 to n do begin if gField[x, y].value = 0 then //да, есть хоть одна пустая клетка! begin result := true; break; //незачем дальше цикл гонять, раз есть хоть одна свободная клетка end; end; end; //создать случайное число (2 или 4) в случайный пустой квадратик procedure putRandomSquare(); var sq: TSquare; begin sq := getRandomEmptyField(); //получаем случайный пустой квадрат if (sq = nil) then //Если nil, значит нет пустых клеток! begin //сначала проверить, есть ли возможность ходить куда-то if (canMove()) then begin exit; end; //Иначе, раз нельзя уже ходить, то типа игра окончена и всё такое. //согласен, что не очень правильно, что этот код находится в этой процедуре, но да ладно ( dialogs.showInfo('Игра окончена! Счёт: ' + IntToStr(score)); exit; end; sq.setNumber(getRandomNumber()); //устанавливаем случайный номер (2 или 4) клеточке end; //поменять местами две клеточки между собой procedure replaceSquares(square1, square2: TSquare); var c, f: Color; t: String; v: Integer; begin //запомним параметры первой клетки c := square1.Color; f := square1.FontColor; t := square1.Text; v := square1.value; //поменяем параметры первой клетки на параметры второй square1.Color := square2.Color; square1.Text := square2.Text; square1.value := square2.value; square1.FontColor := square2.FontColor; //поменяем параметры второй клетки на заранее сохранённые параметры первой square2.value := v; square2.Text := t; square2.Color := c; square2.FontColor := f; //system.Console.Writeline('MOVED! ' + t); moved := true; //установим флаг, что ход был совершён! end; {**} procedure moveUp(); var sq, new_sq: TSquare; begin for var x := 1 to n do for var y := 2 to n do begin sq := gField[y, x]; //sleep(100); //sq.Color := clBlue; if (sq.value <> 0) then begin for var i := y - 1 downto 1 do //пробежимся циклом вверх по Y до начала. begin new_sq := gField[i, x]; if (new_sq.value <> 0) then //если вдруг встретилась не пустая клетка, надо проверить, вдруг она складываемая! begin if (new_sq.value <> sq.value) then //если значения разные, то begin replaceSquares(sq, getSquareByPos(i + 1, x)); //передвинуть клеточку рядом с той, что выше break; //и просто АСТАНАВИТЕСЬ end else //если совпало значение, то объединить их! begin new_sq.setNumber(new_sq.value * 2); //установить новое значение для клеточки addScore(new_sq.value); //добавить это значение к количеству очков clearSquare(sq); //очистить ту клеточку, которая сложилась с первой break; end; end; if (i = 1) then replaceSquares(sq, new_sq); //дошли до начала, значит, просто поменять местами клетки) end; end; end; end; procedure moveDown(); var sq, new_sq: TSquare; begin for var x := 1 to n do for var y := n - 1 downto 1 do begin sq := gField[y, x]; if (sq.value <> 0) then begin for var i := y + 1 to n do //пробежимся циклом вниз до конца по этому же столбцу Y begin new_sq := gField[i, x]; if (new_sq.value <> 0) then //если вдруг встретилась не пустая клетка, надо проверить, вдруг она складываемая! begin if (new_sq.value <> sq.value) then //если значения разные, то begin replaceSquares(sq, getSquareByPos(i - 1, x)); //передвинуть клеточку к той, которая имеет значение иное break; //и просто АСТАНАВИТЕСЬ end else //если совпало значение, то объединить их! begin new_sq.setNumber(new_sq.value * 2); //установить новое значение для клеточки addScore(new_sq.value); //добавить это значение к количеству очков clearSquare(sq); //очистить ту клеточку, которая сложилась с первой break; end; end; if (i = n) then replaceSquares(sq, new_sq); //дошли до начала, значит, просто поменять местами клетки) end; end; end; end; procedure moveLeft(); var sq, new_sq: TSquare; begin for var x := 2 to n do for var y := 1 to n do begin sq := gField[y, x]; if (sq.value <> 0) then begin for var i := x - 1 downto 1 do //пробежимся циклом влево по текущей строке X begin new_sq := gField[y, i]; if (new_sq.value <> 0) then //если вдруг встретилась не пустая клетка, надо проверить, вдруг она складываемая! begin if (new_sq.value <> sq.value) then //если значения разные, то begin replaceSquares(sq, getSquareByPos(y, i + 1)); //передвинуть клеточку к той, которая имеет значение иное break; //и просто АСТАНАВИТЕСЬ end else //если совпало значение, то объединить их! begin new_sq.setNumber(new_sq.value * 2); //установить новое значение для клеточки addScore(new_sq.value); //добавить это значение к количеству очков clearSquare(sq); //очистить ту клеточку, которая сложилась с первой break; end; end; if (i = 1) then replaceSquares(sq, new_sq); //дошли до начала, значит, просто поменять местами клетки) end; end; end; end; procedure moveRight(); var sq, new_sq: TSquare; begin for var x := n - 1 downto 1 do for var y := 1 to n do begin sq := gField[y, x]; if (sq.value <> 0) then begin for var i := x + 1 to n do //пробежимся циклом влево по текущей строке X begin new_sq := gField[y, i]; if (new_sq.value <> 0) then //если вдруг встретилась не пустая клетка, надо проверить, вдруг она складываемая! begin if (new_sq.value <> sq.value) then //если значения разные, то begin replaceSquares(sq, getSquareByPos(y, i - 1)); //передвинуть клеточку к той, которая имеет значение иное break; //и просто АСТАНАВИТЕСЬ end else //если совпало значение, то объединить их! begin new_sq.setNumber(new_sq.value * 2); //установить новое значение для клеточки addScore(new_sq.value); //добавить это значение к количеству очков clearSquare(sq); //очистить ту клеточку, которая сложилась с первой break; end; end; if (i = n) then replaceSquares(sq, new_sq); //дошли до начала, значит, просто поменять местами клетки) end; end; end; end; procedure move(direction: TDirection); begin moved := false; //сбросим флаг сделанного хода //выполнить ход в нужную сторону case direction of tdUP: moveUp(); tdDown: moveDown(); tdLeft: moveLeft(); tdRight: moveRight(); end; //обновить в заголовке окна количество очков после очередного хода updateScore(); //Если ход был освершён, то добавить ещё клеточку if moved then putRandomSquare(); end; procedure newGame(); begin clearAllFields(); //При нажатии на Esc можно сделать что-то вроде меню и т.д. clearScore(); putRandomSquare(); putRandomSquare(); end; procedure KeyDown(Key: integer); begin //если открыто какое-то диалоговое окно! if dialogs.modalVisible then begin case Key of VK_RETURN: dialogs.pressOK; VK_ESCAPE: dialogs.closeLastDialog(); end; exit; end; //если нет открытого диалогового окна case Key of VK_UP: move(tdUp); VK_DOWN: move(tdDown); VK_LEFT: move(tdLeft); VK_RIGHT: move(tdRight); VK_Escape: dialogs.showConfirm('Вы действительно хотите начать заново?', newGame); end; end; //анимационный таймер procedure animTimerProc; var sq: TSquare; begin //плавное изменение размеров обратно до изначального for var x := 1 to n do for var y := 1 to n do begin sq := gField[x, y]; if (sq.changed) then begin if (sq.Width > tile) then //если размер больше, надо уменьшать begin sq.left += 1; sq.Top += 1; sq.Width -= 1; sq.Height -= 1; end else //иначе увеличивать наоборот ) begin sq.left -= 1; sq.Top -= 1; sq.Width += 1; sq.Height += 1; end; end; if (sq.Width = tile) then //если размер стал изначальным, begin sq.changed := false; //то пометить клетку, как нормальную, не изменённую, чтобы таймер больше не трогал её пока continue; end; end; end; //обработчики событий для кнопок меню procedure onNewGameClick; begin newGame(); end; var cu: TControlUtils; begin Randomize(); //инициализация генератора случайных чисел Window.Title := windowTitle; //заголовок окошка OnKeyDown := KeyDown; //зададим наш обработчик нажатия кнопок SetWindowSize(2 * x0 + (tile + zz) * n - zz, 2 * y0 + (tile + zz) * n - zz); //задаём размер окошка, учитывая размеры всех клеток и отступов Window.IsFixedSize := True; //чтобы нельзя было менять размер окошка Window.Clear(backgroundColor); //"очистим" окно фоновым цветом Window.CenterOnScreen(); //окно пусть будет по центру экрана CreateFields(); //создадим поля-полюшки //создаём и запускаем таймер, отвечающий за анимации animationTimer := new Timer(animTimerInterval, animTimerProc); animationTimer.start; //создаём объект для работы с диалоговыми окошками dialogs := new TDialogs; { cu := new TControlUtils(); cu.addMenuButton('Новая игра', onNewGameClick); cu.addMenuButton('LOL?!', onTestGameClick); cu.setToCenter(); } //начинается всё с двух клеток putRandomSquare(); putRandomSquare(); end.
unit nkResizer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TnkResizer } TnkResizer = class(TImage) private FTopForm:TForm; FResizing:boolean; FPos:TPoint; protected procedure Loaded;override; procedure _onMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure _onMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure _onMouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer); public constructor Create(AOwner:TComponent);override; published end; procedure Register; implementation procedure Register; begin RegisterComponents('Additional',[TnkResizer]); end; { TnkResizer } procedure TnkResizer.Loaded; begin inherited Loaded; if Self.GetTopParent is TForm then FTopForm:=(Self.GetTopParent as TForm) else FTopForm:=nil; end; procedure TnkResizer._onMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FTopForm<>nil then begin if FTopForm.WindowState=wsNormal then begin if mbLeft = Button then begin FResizing:=True; FPos.x:=Mouse.CursorPos.x; FPos.y:=Mouse.CursorPos.y; end; end; end; end; procedure TnkResizer._onMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var m:TPoint; begin if ssLeft in Shift then begin m.x:=Mouse.CursorPos.x;m.y:=Mouse.CursorPos.y; if(m.x<>FPos.x) or (m.y<>FPos.Y) then begin FTopForm.Width:=FTopForm.Width+(m.x-FPos.X); FTopForm.Height:=FTopForm.Height+(m.y-FPos.Y); end; FPos.x:=m.x; FPos.y:=m.y; end; end; procedure TnkResizer._onMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FResizing:=False; end; constructor TnkResizer.Create(AOwner: TComponent); begin inherited Create(AOwner); Self.OnMouseDown:=@_onMouseDown; Self.OnMouseMove:=@_onMouseMove; Self.OnMouseUp:=@_onMouseUp; end; end.
{ Copyright (C) 1998-2008, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium WEB: http://www.scalabium.com Const strings for localization freeware SMComponent library - SMComponents Danish Language File translated by Hüseyin Aliz, haliz@consit.dk } unit SMCnst; interface {English strings} const strMessage = 'Udskriv...'; strSaveChanges = 'Er du sikker på at du vil gemme ændringer på Database Serveren?'; strErrSaveChanges = 'Kan ikke gemme data! Check forbindelsen til serveren eller at data er valideret.'; strDeleteWarning = 'Er du sikker på at du vil slette tabellen %s?'; strEmptyWarning = 'Er du sikker på at du vil tømme tabellen %s?'; const PopUpCaption: array [0..24] of string = ('Tilføj række', 'Indsæt række', 'Rediger række', 'Slet række', '-', 'Udskriv ...', 'Eksporter ...', 'Filtrere ...', 'Søg ...', '-', 'Gem ændringer', 'Forkast ændringer', 'Opfrisk', '-', 'Vælg/Fravælg rækker', 'Vælg række', 'Vælg Alle rækker', '-', 'FraVælg række', 'FraVælg Alle rækker', '-', 'Gem kolonne layout', 'Genopret kolonne layout', '-', 'Konfigurere...'); const //for TSMSetDBGridDialog SgbTitle = ' Title '; SgbData = ' Data '; STitleCaption = 'Tekst:'; STitleAlignment = 'Justering:'; STitleColor = 'Baggrund:'; STitleFont = 'Font:'; SWidth = 'Bredde:'; SWidthFix = 'tegn'; SAlignLeft = 'venstre'; SAlignRight = 'højre'; SAlignCenter = 'center'; const //for TSMDBFilterDialog strEqual = 'lig med'; strNonEqual = 'ikke lig med'; strNonMore = 'ikke større'; strNonLess = 'ikke mindre'; strLessThan = 'mindre end'; strLargeThan = 'større end'; strExist = 'tomt'; strNonExist = 'ikke tomt'; strIn = 'er i liste'; strBetween = 'mellem'; strLike = 'ligner'; strOR = 'ELLER'; strAND = 'OG'; strField = 'Felt'; strCondition = 'Betingelse'; strValue = 'Værdi'; strAddCondition = ' Definer venligst en yderligere betingelse:'; strSelection = ' Vælg poster via følgende betingelser:'; strAddToList = 'Tilføj til liste'; strEditInList = 'Rediger i liste'; strDeleteFromList = 'Slet fra liste'; strTemplate = 'Filter skabelon dialog'; strFLoadFrom = 'Hent fra...'; strFSaveAs = 'Gem som..'; strFDescription = 'Beskrivelse'; strFFileName = 'Fil navn'; strFCreate = 'Oprettet: %s'; strFModify = 'Ændret: %s'; strFProtect = 'Skrivebeskyttet'; strFProtectErr = 'Filen er beskyttet!'; const //for SMDBNavigator SFirstRecord = 'Første række'; SPriorRecord = 'Forrige række'; SNextRecord = 'Næste række'; SLastRecord = 'Sidste række'; SInsertRecord = 'Indsæt række'; SCopyRecord = 'Kopier række'; SDeleteRecord = 'Slet række'; SEditRecord = 'Rediger række'; SFilterRecord = 'Filtrere betingelser'; SFindRecord = 'Søgning af række'; SPrintRecord = 'Udskrift af rækker'; SExportRecord = 'Eksport af rækker'; SImportRecord = 'Import af rækker'; SPostEdit = 'Gem ændringer'; SCancelEdit = 'Fortryd ændringer'; SRefreshRecord = 'Genopfrisk data'; SChoice = 'Vælg en række'; SClear = 'Vælg en række til nulstilling'; SDeleteRecordQuestion = 'Slet en række?'; SDeleteMultipleRecordsQuestion = 'Vil du virkelig slette valgte rækker?'; SRecordNotFound = 'Række er ikke fundet'; SFirstName = 'Første'; SPriorName = 'Forrige'; SNextName = 'Næste'; SLastName = 'Sidste'; SInsertName = 'Indsæt'; SCopyName = 'Kopier'; SDeleteName = 'Slet'; SEditName = 'Rediger'; SFilterName = 'Filtrere'; SFindName = 'Søg'; SPrintName = 'Udskriv'; SExportName = 'Eksport'; SImportName = 'Import'; SPostName = 'Gem'; SCancelName = 'Afbryd'; SRefreshName = 'Genopfrisk'; SChoiceName = 'Vælg'; SClearName = 'Nulstil'; SBtnOk = '&OK'; SBtnCancel = '&Afbryd'; SBtnLoad = 'Hent'; SBtnSave = 'Gem'; SBtnCopy = 'Kopier'; SBtnPaste = 'Sæt ind'; SBtnClear = 'Nulstil'; SRecNo = 'ræk.'; SRecOf = ' af '; const //for EditTyped etValidNumber = 'gyldig nummer'; etValidInteger = 'gyldig heltals nummer'; etValidDateTime = 'gyldig dato/tid'; etValidDate = 'gyldig dato'; etValidTime = 'gyldig tid'; etValid = 'gyldig'; etIsNot = 'er ikke'; etOutOfRange = 'Værdi %s er uden for interval %s..%s'; SApplyAll = 'Sæt ind for alle'; SNoDataToDisplay = '<Ingen data at vise>'; implementation end.
unit ncaFrmProduto_PrecoAuto; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, StdCtrls, cxRadioGroup, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxCheckBox, cxTextEdit, cxCurrencyEdit, cxLabel, cxPCdxBarPopupMenu, cxPC, ExtCtrls, dxBarBuiltInMenu; type TFrmProd_PrecoAuto = class(TForm) panPri: TLMDSimplePanel; panInner: TLMDSimplePanel; panPreco: TLMDSimplePanel; lbPreco: TcxLabel; cbAuto: TcxCheckBox; edPreco: TcxCurrencyEdit; panCustoMargem: TLMDSimplePanel; panCusto: TLMDSimplePanel; lbCusto: TcxLabel; edCusto: TcxCurrencyEdit; panMargem: TLMDSimplePanel; lbMargem: TcxLabel; edMargem: TcxCurrencyEdit; pgMargem: TcxPageControl; tsMargemPadrao: TcxTabSheet; cbMargemPadrao: TcxCheckBox; tsDefMargemPadrao: TcxTabSheet; lbDefMargemPadrao: TcxLabel; cbAlteraPreco: TcxCheckBox; procedure FormCreate(Sender: TObject); procedure cbAutoClick(Sender: TObject); procedure cbMargemPadraoClick(Sender: TObject); procedure edPrecoPropertiesChange(Sender: TObject); procedure edPrecoPropertiesEditValueChanged(Sender: TObject); procedure edCustoPropertiesChange(Sender: TObject); procedure edCustoPropertiesEditValueChanged(Sender: TObject); procedure edMargemPropertiesChange(Sender: TObject); procedure edMargemPropertiesEditValueChanged(Sender: TObject); procedure edPrecoFocusChanged(Sender: TObject); procedure edPrecoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edCustoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edMargemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lbCustoClick(Sender: TObject); procedure lbPrecoClick(Sender: TObject); procedure lbMargemClick(Sender: TObject); procedure lbDefMargemPadraoClick(Sender: TObject); procedure cbAutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbAlteraPrecoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FOnFocusNext : TNotifyEvent; FOnChange : TNotifyEvent; FSavePreco: Currency; FSaveMargem: Double; FIniciando : Boolean; FMargem : Variant; FPreco : Currency; FCusto : Currency; function GetCusto: Currency; function GetMargem: Variant; function GetPrecoAuto: Boolean; function GetPrecoVenda: Currency; procedure SetCusto(const Value: Currency); procedure SetMargem(const Value: Variant); procedure SetPrecoAuto(const Value: Boolean); procedure SetPrecoVenda(const Value: Currency); procedure AtualizaTela; procedure CalcPrecoMargem; procedure CheckEsc(var aKey: Word); procedure FocusNext; { Private declarations } public procedure FocusFirst; function PodeAlterarPreco: Boolean; procedure InitData(aPreco, aCusto: Currency; aMargem: Variant; aPrecoAuto, aAlteraPreco: Boolean); property OnChange: TNotifyEvent read FOnChange write FOnChange; property PrecoAuto: Boolean read GetPrecoAuto write SetPrecoAuto; property Preco: Currency read GetPrecoVenda write SetPrecoVenda; property Custo: Currency read GetCusto write SetCusto; property Margem: Variant read GetMargem write SetMargem; property OnFocusNext: TNotifyEvent read FOnFocusNext write FOnFocusNext; { Public declarations } end; var FrmProd_PrecoAuto: TFrmProd_PrecoAuto; implementation uses ncaFrmPri, ncClassesBase, ncaFrmConfigPrecoAuto, ncaFrmOpcoes, ncIDRecursos, ncaDM, ncaFrmProduto; {$R *.dfm} { TFrmProd_PrecoAuto } procedure TFrmProd_PrecoAuto.AtualizaTela; begin if gConfig.Margem<0.01 then pgMargem.ActivePage := tsDefMargemPadrao else pgMargem.ActivePage := tsMargemPadrao; if PrecoAuto then begin edPreco.Enabled := False; panPreco.Color := clBtnFace; lbPreco.Enabled := False; pgMargem.Visible := True; end else begin pgMargem.Visible := False; edPreco.Enabled := True; panPreco.Color := clWhite; lbPreco.Enabled := True; end; if cbMargemPadrao.Checked or (not cbAuto.Checked) then begin edMargem.Enabled := False; panMargem.Color := clBtnFace; lbMargem.Enabled := False; end else begin edMargem.Enabled := True; panMargem.Color := clWhite; lbMargem.Enabled := True; end; if pgMargem.Visible then begin if cbMargemPadrao.Checked then begin FMargem := gConfig.Margem; edMargem.Value := FMargem; end; end; CalcPrecoMargem; end; procedure TFrmProd_PrecoAuto.CalcPrecoMargem; begin if cbAuto.Checked then begin if (FCusto > 0) then edPreco.Value := gConfig.CalcPreco(Margem, FCusto) else edPreco.Clear; end else if (FCusto>0.0001) and (FPreco>0.0001) then begin FMargem := ((FPreco / FCusto) * 100) - 100; edMargem.Value := FMargem; end; if Assigned(FOnChange) then FOnChange(Self); end; procedure TFrmProd_PrecoAuto.cbAlteraPrecoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckEsc(Key); if Key=13 then FocusNext; end; procedure TFrmProd_PrecoAuto.cbAutoClick(Sender: TObject); begin if FIniciando then Exit; if cbAuto.Checked then FSavePreco := edPreco.Value else edPreco.Value := FSavePreco; AtualizaTela; if cbAuto.Checked then begin if panCustoMargem.Visible and panCustoMargem.Enabled then edCusto.SetFocus; end else edPreco.SetFocus; end; procedure TFrmProd_PrecoAuto.cbAutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckEsc(Key); if Key = 13 then if panCustoMargem.Visible and panCustoMargem.Enabled then edCusto.SetFocus else FocusNext; end; procedure TFrmProd_PrecoAuto.cbMargemPadraoClick(Sender: TObject); begin if FIniciando then Exit; if cbMargemPadrao.Checked then begin FSaveMargem := edMargem.Value; Margem := null; edCusto.SetFocus; end else begin edMargem.Value := FSaveMargem; edMargem.Enabled := True; edMargem.SetFocus; end; AtualizaTela; end; procedure TFrmProd_PrecoAuto.CheckEsc(var aKey: Word); begin if aKey = Key_ESC then begin aKey := 0; // TFrmProduto(Owner).edPreco.DroppedDown := False; end; if aKey = Key_F2 then begin aKey := 0; // TFrmProduto(Owner).TentaGravar; end; end; procedure TFrmProd_PrecoAuto.edCustoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckEsc(Key); if Key = 13 then begin Key := 0; if edMargem.Enabled and (panCustoMargem.Enabled and panCustoMargem.Visible) then edMargem.SetFocus else cbAlteraPreco.SetFocus; end; end; procedure TFrmProd_PrecoAuto.edCustoPropertiesChange(Sender: TObject); begin edCusto.PostEditValue; end; procedure TFrmProd_PrecoAuto.edCustoPropertiesEditValueChanged(Sender: TObject); begin if VarIsNull(edCusto.EditValue) then Custo := 0 else Custo := edCusto.EditValue; end; procedure TFrmProd_PrecoAuto.edMargemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckEsc(Key); if Key = 13 then begin Key := 0; cbAlteraPreco.SetFocus; end; end; procedure TFrmProd_PrecoAuto.edMargemPropertiesChange(Sender: TObject); begin edMargem.PostEditValue; end; procedure TFrmProd_PrecoAuto.edMargemPropertiesEditValueChanged( Sender: TObject); begin if VarIsNull(edMargem.EditValue) then Margem := 0 else Margem := edMargem.EditValue; end; procedure TFrmProd_PrecoAuto.edPrecoFocusChanged(Sender: TObject); begin with TcxCustomEdit(Sender) do if Focused then TLMDSimplePanel(Parent).Bevel.BorderColor := clBlue else TLMDSimplePanel(Parent).Bevel.BorderColor := clSilver; end; procedure TFrmProd_PrecoAuto.edPrecoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin CheckEsc(Key); if (key = 13) and (panCustoMargem.Enabled and panCustoMargem.Visible) then begin edCusto.SetFocus; Key := 0; end; end; procedure TFrmProd_PrecoAuto.edPrecoPropertiesChange(Sender: TObject); begin edPreco.PostEditValue; end; procedure TFrmProd_PrecoAuto.edPrecoPropertiesEditValueChanged(Sender: TObject); begin if VarIsNull(edPreco.EditValue) then Preco := 0 else Preco := edPreco.EditValue; end; procedure TFrmProd_PrecoAuto.FocusFirst; begin if cbAuto.Checked then begin if panCustoMargem.Visible and panCustoMargem.Enabled then edCusto.SetFocus else SetFocus; end else edPreco.SetFocus; end; procedure TFrmProd_PrecoAuto.FocusNext; begin if Assigned(FOnFocusNext) then FOnFocusNext(Self); end; procedure TFrmProd_PrecoAuto.FormCreate(Sender: TObject); begin FIniciando := False; FOnFocusNext := nil; FOnChange := nil; FSavePreco := 0; FSaveMargem := 0; FCusto := 0; FPreco := 0; panCustoMargem.Visible := Permitido(daVerCusto); panCustoMargem.Enabled := Permitido(daAlterarCusto); edPreco.Properties.ReadOnly := not Permitido(daProEditarPreco); cbAuto.Properties.ReadOnly := not Permitido(daProEditarPreco); cbAlteraPreco.Properties.ReadOnly := not Permitido(daProEditarPreco); end; function TFrmProd_PrecoAuto.GetCusto: Currency; begin Result := FCusto; end; function TFrmProd_PrecoAuto.GetMargem: Variant; begin if cbAuto.Checked then begin if cbMargemPadrao.Checked then Result := null else Result := FMargem; end else Result := FMargem; end; function TFrmProd_PrecoAuto.GetPrecoAuto: Boolean; begin Result := cbAuto.Checked; end; function TFrmProd_PrecoAuto.GetPrecoVenda: Currency; begin Result := FPreco; end; procedure TFrmProd_PrecoAuto.InitData(aPreco, aCusto: Currency; aMargem: Variant; aPrecoAuto, aAlteraPreco: Boolean); begin FIniciando := True; try FSavePreco := aPreco; FMargem := aMargem; if aMargem<>null then begin FSaveMargem := aMargem; edMargem.Value := aMargem; end else edMargem.Clear; FCusto := aCusto; FPreco := aPreco; edCusto.Value := aCusto; edPreco.Value := aPreco; cbAlteraPreco.Checked := aAlteraPreco; cbAuto.Checked := aPrecoAuto; cbMargemPadrao.Checked := (aMargem=null) and (gConfig.Margem>0.001); AtualizaTela; finally FIniciando := False; end; end; procedure TFrmProd_PrecoAuto.lbCustoClick(Sender: TObject); begin edCusto.SetFocus; end; procedure TFrmProd_PrecoAuto.lbDefMargemPadraoClick(Sender: TObject); begin TFrmConfigPrecoAuto.Create(Self).ShowModal; AtualizaTela; end; procedure TFrmProd_PrecoAuto.lbMargemClick(Sender: TObject); begin if edMargem.Enabled then edMargem.SetFocus; end; procedure TFrmProd_PrecoAuto.lbPrecoClick(Sender: TObject); begin if edPreco.Enabled then edPreco.SetFocus; end; function TFrmProd_PrecoAuto.PodeAlterarPreco: Boolean; begin Result := cbAlteraPreco.Checked; end; procedure TFrmProd_PrecoAuto.SetCusto(const Value: Currency); begin if Value=FCusto then Exit; FCusto := Value; if not edCusto.Focused then edCusto.Value := Value; CalcPrecoMargem; end; procedure TFrmProd_PrecoAuto.SetMargem(const Value: Variant); begin if Value = Margem then Exit; FMargem := Value; if not edMargem.Focused then begin if Value=null then edMargem.Clear else edMargem.Value := Value; end; CalcPrecoMargem; end; procedure TFrmProd_PrecoAuto.SetPrecoAuto(const Value: Boolean); begin cbAuto.Checked := Value; AtualizaTela; end; procedure TFrmProd_PrecoAuto.SetPrecoVenda(const Value: Currency); begin if Value = FPreco then Exit; FPreco := Value; if not edPreco.Focused then edPreco.Value := FPreco; CalcPrecomargem; end; end.
unit uAtributosCustomizados; interface type TCampoTabelaExterna = class(TCustomAttribute) private FNome: string; public constructor Create(const psNome: string); property Nome: string read FNome; end; implementation { TCampoTabelaExterna } constructor TCampoTabelaExterna.Create(const psNome: string); begin FNome := psNome; end; end.
unit main; {$mode objfpc}{$H+} interface uses {$IFDEF LINUX}clocale,{$ENDIF} Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Spin, StdCtrls, Grids, ExtCtrls, ComCtrls, JvYearGrid; type { TMainForm } TMainForm = class(TForm) btnFont: TButton; cmbAutoSize: TCheckBox; cmbMonthFormat: TComboBox; cmbDayNamesAlignment: TComboBox; cmbDayFormat: TComboBox; cmbMonthNamesAlignment: TComboBox; cmbDaysAlignment: TComboBox; cmbFlat: TCheckBox; FontDialog1: TFontDialog; JvYearGrid1: TJvYearGrid; edLeftMargin: TSpinEdit; edRightMargin: TSpinEdit; edTopMargin: TSpinEdit; edBottomMargin: TSpinEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; lblYear: TLabel; Panel1: TPanel; rgAutoSize: TCheckGroup; udYear: TUpDown; procedure btnFontClick(Sender: TObject); procedure cmbAutoSizeChange(Sender: TObject); procedure cmbDayFormatChange(Sender: TObject); procedure cmbDayNamesAlignmentChange(Sender: TObject); procedure cmbDaysAlignmentChange(Sender: TObject); procedure cmbFlatChange(Sender: TObject); procedure cmbMonthFormatChange(Sender: TObject); procedure cmbMonthNamesAlignmentChange(Sender: TObject); procedure edMarginChange(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure rgAutoSizeItemClick(Sender: TObject; Index: integer); procedure udYearClick(Sender: TObject; Button: TUDBtnType); private public end; var MainForm: TMainForm; implementation {$R *.lfm} uses DateUtils; { TMainForm } procedure TMainForm.cmbDayNamesAlignmentChange(Sender: TObject); begin JvYearGrid1.DayNamesAlignment := TAlignment(cmbDayNamesAlignment.ItemIndex); end; procedure TMainForm.cmbDayFormatChange(Sender: TObject); begin JvYearGrid1.DayFormat := TJvDayFormat(cmbDayFormat.ItemIndex); end; procedure TMainForm.cmbDaysAlignmentChange(Sender: TObject); begin JvYearGrid1.DaysAlignment := TAlignment(cmbDaysAlignment.ItemIndex); end; procedure TMainForm.btnFontClick(Sender: TObject); begin FontDialog1.Font.Assign(JvYearGrid1.Font); if FontDialog1.Execute then JvYearGrid1.Font.Assign(FontDialog1.Font); end; procedure TMainForm.cmbAutoSizeChange(Sender: TObject); begin JvYearGrid1.AutoSize := cmbAutoSize.Checked; rgAutoSize.Enabled := JvYearGrid1.AutoSize; end; procedure TMainForm.cmbFlatChange(Sender: TObject); begin JvYearGrid1.Flat := cmbFlat.Checked; end; procedure TMainForm.cmbMonthFormatChange(Sender: TObject); begin JvYearGrid1.MonthFormat := TJvMonthFormat(cmbMonthFormat.ItemIndex); end; procedure TMainForm.cmbMonthNamesAlignmentChange(Sender: TObject); begin JvYearGrid1.MonthNamesAlignment := TAlignment(cmbMonthNamesAlignment.ItemIndex); end; procedure TMainForm.edMarginChange(Sender: TObject); begin if Sender = edLeftMargin then JvYearGrid1.CellMargins.Left := edLeftMargin.Value; if Sender = edRightMargin then JvYearGrid1.CellMargins.Right := edRightMargin.Value; if Sender = edTopMargin then JvYearGrid1.CellMargins.Top := edTopMargin.Value; if Sender = edBottomMargin then JvYearGrid1.CellMargins.Bottom := edBottomMargin.Value; end; procedure TMainForm.FormActivate(Sender: TObject); begin // Doing this in the OnCreate event would mean that the scaled values are // not ready, yet. edLeftMargin.Value := JvYearGrid1.CellMargins.Left; edRightMargin.Value := JvYearGrid1.CellMargins.Right; edTopMargin.Value := JvYearGrid1.CellMargins.Top; edBottomMargin.Value := JvYearGrid1.CellMargins.Bottom; edLeftMargin.OnChange := @edMarginChange; edRightMargin.OnChange := @edMarginChange; edTopMargin.OnChange := @edMarginChange; edBottomMargin.OnChange := @edMarginChange; end; procedure TMainForm.FormCreate(Sender: TObject); begin JvYearGrid1.Year := YearOf(Date); cmbDayNamesAlignment.ItemIndex := ord(JvYearGrid1.DayNamesAlignment); cmbMonthNamesAlignment.ItemIndex := ord(JvYearGrid1.MonthNamesAlignment); cmbDaysAlignment.ItemIndex := ord(JvYearGrid1.DaysAlignment); cmbDayFormat.ItemIndex := ord(JvYearGrid1.DayFormat); cmbMonthFormat.ItemIndex := ord(JvYearGrid1.MonthFormat); cmbMonthFormatChange(nil); udYear.Position := JvYearGrid1.Year; cmbFlat.Checked := JvYearGrid1.Flat; cmbAutoSize.Checked := JvYearGrid1.AutoSize; rgAutoSize.Checked[ord(aoGrid)] := aoGrid in JvYearGrid1.AutosizeOptions; rgAutoSize.Checked[ord(aoFirstColumn)] := aoFirstColumn in JvYearGrid1.AutosizeOptions; rgAutoSize.Checked[ord(aoFirstRow)] := aoFirstRow in JvYearGrid1.AutosizeOptions; rgAutoSize.Checked[ord(aoColumns)] := aoColumns in JvYearGrid1.AutosizeOptions; rgAutoSize.Checked[ord(aoRows)] := aoRows in JvYearGrid1.AutosizeOptions; end; procedure TMainForm.rgAutoSizeItemClick(Sender: TObject; Index: integer); begin if rgAutoSize.Checked[ord(aoGrid)] then JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions + [aoGrid] else JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions - [aoGrid]; if rgAutoSize.Checked[ord(aoFirstColumn)] then JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions + [aoFirstColumn] else JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions - [aoFirstColumn]; if rgAutoSize.Checked[ord(aoFirstRow)] then JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions + [aoFirstRow] else JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions - [aoFirstRow]; if rgAutoSize.Checked[ord(aoColumns)] then JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions + [aoColumns] else JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions - [aoColumns]; if rgAutoSize.Checked[ord(aoRows)] then JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions + [aoRows] else JvYearGrid1.AutoSizeOptions := JvYearGrid1.AutoSizeOptions - [aoRows]; end; procedure TMainForm.udYearClick(Sender: TObject; Button: TUDBtnType); begin JvYearGrid1.Year := udYear.Position; end; end.
type tACString = String[20]; tStrings = array[1..maxString] of String[255]; tStrIdx = array[1..maxString] of Word; tInFlag = ( { Input flags for "dReadString" } inNormal, { No case conversion is performed. } inCapital, { First letter capitallized. } inUpper, { All characters are converted to upper case } inLower, { All characters are converted to lower case } inMixed, { Mixed case. AKA: word Auto-Capitalization } inWeird, { All vowels are lowered (ie. MiKe FRiCKeR) } inWarped, { All constants are lowered (ie. mIkE frIckEr) } inCool, { Only "I"s are lowered (ie. FiEND) } inHandle); { reserved for alias format } tInChar = set of Char; { node configuration structure - node??.dat, single record } tModemRec = record ComDevice : Byte; { 0/none 1/uart 2/int14 3=fosl 4/digi } ComPort : Byte; { device comport # } BaudRate : LongInt; { device baud rate } Parity : Char; { parity (n/e/o) } StopBits : Byte; { stop bits, usually 1 } DataBits : Byte; { data bits, usually 8 } RecvBuff : Word; { receive buffer size } SendBuff : Word; { transmit buffer size } LockedPort : Boolean; { locked port? } MultiRing : Boolean; { use select-ring detection } irqNumber : Byte; { com irq } baseAddr : String[4]; { uart base address } sInit1 : String[45]; sInit2 : String[45]; sInit3 : String[45]; sExitStr : String[45]; sAnswer : String[45]; sHangup : String[45]; sOffhook : String[45]; sDialPrefix : String[45]; rError : String[45]; rNoCarrier : String[45]; rOK : String[45]; rRing : String[45]; rBusy : String[45]; rNoDialTone : String[45]; c300 : String[45]; c1200 : String[45]; c2400 : String[45]; c4800 : String[45]; c7200 : String[45]; c9600 : String[45]; c14400 : String[45]; c16800 : String[45]; c19200 : String[45]; c21600 : String[45]; c24000 : String[45]; c26400 : String[45]; c28800 : String[45]; c31200 : String[45]; c33600 : String[45]; c38400 : String[45]; c57600 : String[45]; c64000 : String[45]; c115200 : String[45]; Reserved : array[1..1024] of Byte; end; tColorRec = record Fore : Byte; Back : Byte; Blink : Boolean; end; tColor = array[0..maxColor] of tColorRec; tNetAddressRec = record Zone : Word; Net : Word; Node : Word; Point : Word; end; tMacros = array[1..10] of String[255]; { main bbs configuration structure - iniquity.dat, single record } tCfgRec = record bbsName : String[40]; { name of bbs } bbsPhone : String[13]; { bbs phone number "(xxx)xxx-xxxx" } SysOpAlias : String[36]; { sysop's handle } SysOpName : String[36]; { sysop's real name } SystemPW : String[20]; { sysop access password } acsSysOp : tACString; { bbs sysop acs } acsCoSysOp : tACString; { bbs co-sysop acs } DirectWrites : Boolean; { use direct video writes? } SnowChecking : Boolean; { check for cga snow? } OverlayToEMS : Boolean; { load overlays to ems if possible? } RealNameSystem : Boolean; { use only real names on this bbs? } ShowPwLocal : Boolean; { display password input locally? } StatOnDefault : Boolean; { status bar on when user logs in? } StatBarOn : Boolean; { is the status bar currently on? } StatType : Byte; { 1 (sbBot) = bottom, 2 (sbTop) = top } StatBar : Byte; { current sb display (1-maxStatBar) } StatLo : Byte; { status bar low color attribute } StatTxt : Byte; { status bar normal color attrib } StatHi : Byte; { status bar bright color attrib } DefaultCol : tColor; { default bbs generic colors } Address : array[1..maxAddress] of tNetAddressRec; { ^^ bbs net addresses } ESCtoExit : Boolean; { allow wfc termination w/ escape? } OffhookLocal : Boolean; { offhook modem w/ local login? } VgaEffects : Boolean; { use vga effects? soon to be gone.. } ScreenSaver : Byte; { scrn saver (1=none,2=blank,3=morph) } BlankSeconds : Word; { # secs before initiating scrn saver } DefWFCstat : Byte; { default wfc stats display (1-8) } pathData : String[40]; { path to iniquity's data files } pathText : String[40]; { path to text/infoform files } pathMenu : String[40]; { path to menu files } pathMsgs : String[40]; { path to message area data files } pathSwap : String[40]; { path to swapfile directory } pathDoor : String[40]; { path to door *.bat & drop files } pathProt : String[40]; { path to external protocols } pathTemp : String[40]; { path to temporary work directory } pathDnld : String[40]; { download directory - future use } pathLogs : String[40]; { path to log file directory } NoBBSlogging : Boolean; { disable all bbs logging? } LogLineChat : Boolean; { log line chat mode text & users? } LogSplitChat : Boolean; { log split-screen chat text/users? } LogMicroDOS : Boolean; { log microdos activity? } SwapInShell : Boolean; { swap out memory when shelling? } SwapToEMS : Boolean; { use ems for swapping if available? } ProtocolSwap : Boolean; { swap before executing protocols? } BbsAccessPw : String[20]; { pw needed to login to bbs (unused) } NoBaudPW : String[20]; { pw needed to login w/banned baud } SysOpAutoLogin : Boolean; { auto-login as user #1 if local? } MatrixLogin : Boolean; { use matrix.mnu as a prelogon menu? } AskApply : Boolean; { offer unknown users chance to apply?} TimeLimitPerCall : Boolean; { is time limit per/call? or per/day } acsSystemPWLogin : tACString; { acs to force user to enter sysop pw } CallsBirth : Byte; { # of calls before birthdate check } CallsPhone : Byte; { # of calls before phone # check } LoginTrys : Byte; { max login attempts before booting } Origin : array[1..maxOrigin] of String[75]; { ^^ echo/netmail origin lines } NoChatPW : String[20]; { pw needed to page sysop w/not avail } ChatPageNoise : Boolean; { use chat pager noise at all? } maxPageTimes : Byte; { maximum page attempts p/call } maxPageBeeps : Byte; { number of times to beep when paging } PwEchoChar : Char; { password echo character } RemovePause : Boolean; { backspace over pause/cont? prompts? } AddLocalCalls : Boolean; { record local calls to bbs stats? } numLastCalls : Byte; { # of calls to show in last callers } acsPostEmail : tACString; { acs required to post email } acsAnonymous : tACString; { acs needed to post anonymous msgs } acsAnonAutoMsg : tACString; { acs needed to post an anon automsg } acsUploadMessage : tACString; { acs required to upload a msg } acsAutoSigUse : tACString; { acs required to use autosigs } AbortMandOk : Boolean; { allow quit reading mandatory msgs? } AskPrivateMsg : Boolean; { prompt private msg when posting? } AskPrivateReply : Boolean; { prompt private msg when replying? } AskPostInArea : Boolean; { ask post in msgarea when reading? } AskUploadReply : Boolean; { ask upload message when replying? } AskUploadEmail : Boolean; { ask upload message in email? } AskKillMsg : Boolean; { ask delete email msg after reply? } AskKillAllMsg : Boolean; { ask delete all email after read? } NewUserPW : String[20]; { new user password } AliasFormat : Byte; { new user alias format type (1-8) } DefaultPageLen : Byte; { default page length for new users } NewExpert : Boolean; { default new user expert mode? } NewYesNoBars : Boolean; { default new user yes/no bars? } NewHotKeys : Boolean; { default new user hot keys? } NewAskExpert : Boolean; { ask new user expert mode? } NewAskYesNoBars : Boolean; { ask new user yes/no bars? } NewAskHotKeys : Boolean; { ask new user hot keys? } NewAskPageLen : Boolean; { ask new user page length? } StartMenu : String[8]; { default startup menu for new users } Macro : tMacros; { bbs function key macros } pathArch : String[40]; { path to archiver programs } ArchiverSwap : Boolean; { swap before executing archivers? } NewPause : Boolean; { default new user screen pausing? } NewQuote : Boolean; { default new user autoquote? } NewAskPause : Boolean; { ask new user screen pausing? } NewAskQuote : Boolean; { ask new user autoquote? } AskAutoQuote : Boolean; { ask autoquote when replying? } DefaultQuoteNum : Boolean; { use default quote #s w/no aquote? } MaxQuoteLines : Byte; { # of lines to autoquote from msg } iniqAsDoor : Boolean; { run iniquity as a door? } pathAtch : String[40]; { path to file attach directory } acsAttachPublic : tACString; { acs needed to attach a file public } acsAttachEmail : tACString; { acs req to attach a file in email } confIgnoreMsg : Boolean; { ignore msg conf in mandatory scan? } compMsgAreas : Boolean; { compress message listing area #s } compFileAreas : Boolean; { compress file listing area #s } RestoreChatTime : Boolean; { restore users time elapsed in chat? } kbPerFilePoint : Word; { 1 file point = ?? kb } useFilePoints : Boolean; { use file point system on bbs? } importDescs : Boolean; { import file descriptons from archs? } useDLlimit : Boolean; { use daily download limits? } useDLkbLimit : Boolean; { use daily download-kb limits? } bbsLocation : String[40]; { bbs location (city, state/prov) } qwkFilename : String[8]; { qwk filename prefix } qwkWelcome : String[12]; { qwk welcome textfile (in text dir) } qwkNews : String[12]; { qwk news textfile (in text dir) } qwkGoodbye : String[12]; { qwk goodbye textfile (in text dir) } qwkLocalPath : String[40]; { local qwk download path } qwkIgnoreTime : Boolean; { ignore time remaining to xfer qwk? } qwkStripSigs : Boolean; { strip autosigs when exporting msgs? } noDescLine : String[50]; { "no file description" string } waitConnect : Word; { # secs to wait for modem to answer } modemReInit : Word; { # secs before re-initializing modem } lightChar : Char; { wavefile [lit] light character } lightCharOk : Char; { light "ok" character } lightCharFail : Char; { light "error" character } virusScan : String[50]; { virus scanner command } virusOk : Byte; { scanner "ok" errorlevel } maxFileAge : Byte; { oldest file in years to allow pass } strictAge : Boolean; { use "strict" age file tester? } delFile : String[12]; { file list (data dir) to remove } addFile : String[12]; { file list (data dir) to add } comFile : String[12]; { file comment (data dir) to apply } extMaint : Boolean; { external maintenence when testing? } ulSearch : Byte; { upload search type (1-4) } autoValidate : Boolean; { auto-validate uploaded files } filePtsPer : Word; { file point return % w/uploads } useUlDlratio : Boolean; { use upload/download ratio? } useKbRatio : Boolean; { use upload/download-kb ratio? } fileDesc1 : String[13]; { primary file description filename } fileDesc2 : String[13]; { secondary file description name } useTextLibs : Boolean; { use textfile libraries? } pathLibs : String[40]; { path to textfile libraries *.tfl } echomailLev : Byte; { posted echomail exit errorlevel } newConfig : Boolean; { use newuser configuration screen? } newVerify : Boolean; { prompt newuser to proceed w/app? } pmtYes : String[30]; { default "(Y/n)" prompt } pmtNo : String[30]; { default "(y/N)" prompt } pmtYesWord : String[20]; { default "Yes" string } pmtNoWord : String[20]; { default "No" string } pmtYesBar : String[30]; { default "[yes] no " bar prompt } pmtNoBar : String[30]; { default " yes [no]" bar prompt } descWrap : Boolean; { wrap +1page descs to multi-page? } chatStart : String[5]; { chat avail start time (hh:mm) } chatEnd : String[5]; { chat avail end time (hh:mm) } chatOverAcs : tACString; { acs needed to override availability } advFileBar : Boolean; { advance file listing bar w/ flag } inactTime : Boolean; { use inactivity timeout? } inactInChat : Boolean; { use inactivity timeout in chatmode? } inactSeconds : Word; { inactivity timeout seconds } inactWarning : Word; { seconds before warning inact user } ansiString : String[75]; { "ansi codes detected" quote string } pageAskEmail : Boolean; { ask leave email to sysop w/no page } soundRestrict : Boolean; { restrict local sound to avail hours } inactLocal : Boolean; { inactivity timeout w/ local login? } allowBlind : Boolean; { allow blind file uploads? } nuvVotesYes : Byte; { nuv votes required to validate } nuvVotesNo : Byte; { nuv votes required to delete } nuvAccess : tACString; { acs for users to be voted on } nuvVoteAccess : tACString; { acs needed to vote } nuvInitials : Boolean; { display initials beside comments? } nuvUserLevel : Char; { nuv validated user level } nuvValidation : Boolean; { use new user voting on bbs? } MultiNode : Boolean; { is this a multinode bbs? } pathIPLx : String[40]; { path to ipl executables *.ipx } askXferHangup : Boolean; { prompt for 'autologout after xfer'? } xferAutoHangup : Byte; { # of secs to wait before autohangup } ifNoAnsi : Byte; { no ansi? 1=hangup/2=ask/3=continue } minBaud : LongInt; { minimum allowed connection baudrate } newUserLogin : Boolean; { auto-login new users from matrix? } SysopPwCheck : Boolean; { check sysop pw on *? command use? } SupportRIP : Boolean; { support remote imaging protocol } SupportTextFX : Boolean; { allow textfx extended emulation? } tfxFontTweaking : Boolean; { tweak textmode fonts to 8bit planar } tfxResetOnClear : Boolean; { reset console on non-TFX clear code } tfxFullReset : Boolean; { full video mode reset required? } Reserved : array[1..3953] of Byte; { reserved space for future variables } end; tUserACflag = ( acAnsi, acAvatar, acRip, acYesNoBar, acDeleted, acExpert, acHotKey, acPause, acQuote ); tScanRec = record scnMsg : Boolean; ptrMsg : LongInt; end; tAutoSig = array[1..maxSigLines] of String[80]; tUserFlags = set of 'A'..'Z'; tUserRec = record Number : Integer; UserName : String[36]; RealName : String[36]; Password : String[20]; PhoneNum : String[13]; BirthDate : String[8]; Location : String[40]; Address : String[36]; UserNote : String[40]; Sex : Char; SL : Byte; DSL : Byte; BaudRate : LongInt; TotalCalls : Word; curMsgArea : Word; curFileArea : Word; acFlag : set of tUserACflag; Color : tColor; LastCall : String[8]; PageLength : Word; EmailWaiting : Word; Level : Char; timeToday : Word; timePerDay : Word; AutoSigLns : Byte; AutoSig : tAutoSig; confMsg : Byte; confFile : Byte; FirstCall : String[8]; StartMenu : String[8]; fileScan : String[8]; SysOpNote : String[40]; Posts : Word; Email : Word; oldUploads : Word; oldDownloads : Word; oldUploadKb : Word; oldDownloadKb : Word; CallsToday : Word; Flag : tUserFlags; filePts : Word; postCall : Word; limitDL : Word; limitDLkb : Word; todayDL : Word; todayDLkb : Word; lastQwkDate : LongInt; uldlRatio : Word; kbRatio : Word; textLib : Byte; zipCode : String[10]; voteYes : Byte; voteNo : Byte; Uploads : LongInt; Downloads : LongInt; UploadKb : LongInt; DownloadKb : LongInt; Reserved : array[1..364] of Byte; end; tMenuRec = record mType : Byte; MenuName : String[255]; PromptName : String[60]; HelpFile : String[8]; Prompt : String[255]; Acs : tACString; Password : String[20]; Fallback : String[8]; Expert : Byte; GenColumns : Byte; HotKey : Byte; ClearBefore : Boolean; CenterTtl : Boolean; ShowPrompt : Boolean; PauseBefore : Boolean; GlobalUse : Boolean; InputUp : Boolean; Reserved : array[1..100] of Byte; end; tCommandRec = record Desc : String[35]; Help : String[70]; Keys : String[14]; Acs : tACString; Command : String[2]; Param : String[70]; Hidden : Boolean; end; tCommands = array[1..maxMenuCmd] of tCommandRec; tMsgStatusFlag = (msgDeleted, msgSent, msgAnonymous, msgEchoMail, msgPrivate, msgForwarded); tNetAttribFlag = (nPrivate, nCrash, nReceived, nSent, nFileAttached, nInTransit, nOrphan, nKillSent, nLocal, nHold, nUnused, nFileRequest, nReturnReceiptRequest, nIsReturnReceipt, nAuditRequest, nFileUpdateRequest); tMsgInfoRec = record UserNum : Word; Alias : String[36]; Realname : String[36]; Name : String[36]; UserNote : String[40]; Address : tNetAddressRec; end; pMsgHeaderRec = ^tMsgHeaderRec; tMsgHeaderRec = record FromInfo : tMsgInfoRec; ToInfo : tMsgInfoRec; Pos : LongInt; Size : Word; Date : LongInt; Status : set of tMsgStatusFlag; Replies : Word; Subject : String[40]; NetFlag : set of tNetAttribFlag; SigPos : Word; incFile : Word; msgTag : Word; Reserved : array[1..54] of Byte; end; tMsgAreaFlag = (maUnhidden, maRealName, maPrivate, maMandatory, maAnonymous); tMsgAreaRec = record Name : String[40]; Filename : String[8]; MsgPath : String[40]; Sponsor : String[36]; Acs : tACString; PostAcs : tACString; MaxMsgs : Word; Msgs : Word; Password : String[20]; Flag : set of tMsgAreaFlag; AreaType : Byte; Origin : Byte; Address : Byte; qwkName : String[16]; Reserved : array[1..83] of Byte; end; pMessage = ^tMessage; tMessage = array[1..maxMsgLines] of String[80]; tBBSlistRec = record Name : String[40]; SysOp : String[36]; Phone : String[13]; Baud : LongInt; Software : String[12]; Storage : String[20]; Info : String[75]; WhoAdded : String[36]; end; tMenuItemRec = record Txt : String; HiCol : tColorRec; LoCol : tColorRec; X, Y : Byte; end; tLevelRec = record Desc : String[40]; SL : Byte; DSL : Byte; timeLimit : Word; filePts : Word; PostCall : Word; limitDL : Word; limitDLkb : Word; UserNote : String[40]; uldlRatio : Word; kbRatio : Word; Reserved : array[1..196] of Byte; end; tLevels = array['A'..'Z'] of tLevelRec; tProtFlag = ( protActive, protBatch, protBiDir); tProtFlagSet = set of tProtFlag; { protocol description structure - protocol.dat, 26 records total } tProtRec = record Desc : String[36]; { name of this protocol on list } Flag : tProtFlagSet; { protocol flags (see above) } Key : Char; { menu key to select this protocol } Acs : tACString; { access required to use this } Log : String[25]; { external- log filename } cmdUL : String[78]; { external- receive command } cmdDL : String[78]; { external- transmit command } cmdEnv : String[60]; { environment variable } codeUL : array[1..6] of String[6]; { ext- receive log result codes } codeDL : array[1..6] of String[6]; { ext- transmit log result codes } codeIs : Byte; { external- what result means } listDL : String[25]; { external- batch list } posFile : Word; { external- log file filename column } posStat : Word; { external- log file status column } ptype : Byte; { protocol type } Reserved : array[1..49] of Byte; { reserved space } end; { today's caller records - callers.dat, multiple records } tCallRec = record CallNum : LongInt; { call number } Username : String[36]; { user's username } Usernum : Word; { user number } Location : String[40]; { user's location } Baud : LongInt; { baudrate connected @ } Date : String[8]; { date called } Time : String[7]; { time called } NewUser : Boolean; { was this a new user? } AreaCode : String[3]; { area code calling from } end; { system statistics structure - stats.dat, single record } tStatRec = record FirstDay : String[8]; { mm/dd/yy - first day loaded } Calls : Word; { total number of calls to your bbs } Posts : Word; { total number of messages posted } Email : Word; { total number of email sent } Uploads : LongInt; { number of uploads to the bbs } Downloads : LongInt; { number of downloads from the bbs } UploadKb : LongInt; { total uploaded kilobytes } DownloadKb : LongInt; { total downloaded kilobytes } Reserved : array[1..1024] of Byte; { reserved space for new vars } end; { daily history data structure - history.dat, multiple records } tHistoryRec = record Date : String[8]; { date of this entry } Calls : Word; { number of calls this day } NewUsers : Word; { # of new users this day } Posts : Word; { # of posts this day } Email : Word; { total email sent this day } Uploads : Word; { uploads on this day } Downloads : Word; { # of downloads } UploadKb : Word; { uploaded kb this day } DownloadKb : Word; { downloaded kb } end; tFileAreaRec = record Name : String[40]; Filename : String[8]; Path : String[40]; Sponsor : String[36]; acs : tACString; acsUL : tACString; acsDL : tACString; Password : String[20]; Files : Word; SortType : Byte; SortAcen : Boolean; Reserved : array[1..100] of Byte; end; tFileDescLn = String[maxDescLen]; tFileDesc = array[1..maxDescLns] of tFileDescLn; pFileDesc = ^tFileDesc; tFileRec = record Filename : String[12]; Size : LongInt; Date : String[8]; Downloads : Word; filePts : Word; Uploader : String[36]; ulDate : String[8]; DescPtr : LongInt; DescLns : Byte; Valid : Boolean; Reserved : array[1..40] of Byte; end; tUserIndexRec = record UserName : String[36]; RealName : String[36]; Deleted : Boolean; end; tDateTimeRec = record Day, Hour, Min, Sec : LongInt; end; tArchiverRec = record Active : Boolean; Extension : String[3]; fileSig : String[20]; cmdZip : String[40]; cmdUnzip : String[40]; cmdTest : String[40]; cmdComment : String[40]; cmdDelete : String[40]; listChar : Char; Viewer : Byte; okErrLevel : Byte; CheckEL : Boolean; Reserved : array[1..200] of Byte; end; tEventRec = record Active : Boolean; Desc : String[30]; Time : String[5]; Force : Boolean; RunMissed : Boolean; OffHook : Boolean; Node : Word; Command : String[200]; lastExec : Word; end; tConfRec = record Desc : String[30]; Acs : tACString; Key : Char; end; tRepAnsiBuf = array[1..maxRepeatBuf] of Byte; tAttachRec = record Desc : String[70]; Filename : String[12]; ulDate : String[8]; size : LongInt; end; pFileScanIdx = ^tFileScanIdx; tFileScanIdx = array[1..maxFiles] of Word; tTextLibIndex = record fileName : String[13]; filePos : LongInt; fileSize : Word; end; tTextLibIndexList = array[1..maxTextLib] of tTextLibIndex; tTextLib = record Desc : String[36]; Author : String[36]; numLib : Byte; tIndex : ^tTextLibIndexList; end; tTextLibRec = record Filename : String[8]; end; tTetrisHiRec = record Name : String[36]; Level : Byte; Lines : Word; Score : LongInt; end; tInfoIdxRec = record Pos : LongInt; Size : Word; end; tInfoformRec = record Desc : String[40]; Filename : String[13]; Mand : Boolean; Nuv : Boolean; Acs : tACString; end; tNodeRec = record NodeNum : Byte; Username : String[36]; Realname : String[36]; Usernum : Word; Sex : Char; Baudrate : LongInt; Login : tDateTimeRec; Bdate : String[8]; Status : String[50]; Data : LongInt; end; tNodePtrList = array[1..maxNode] of LongInt; tNodeBufList = array[1..maxNodeBuf] of Byte;
unit DataSetConverter4D.Util; interface uses System.SysUtils, System.DateUtils, System.JSON, Data.DB, DataSetConverter4D; function NewDataSetField(dataSet: TDataSet; const fieldType: TFieldType; const fieldName: string; const size: Integer = 0; const origin: string = ''; const displaylabel: string = ''; const Key: Boolean = False): TField; function BooleanToJSON(const value: Boolean): TJSONValue; function BooleanFieldToType(const booleanField: TBooleanField): TBooleanFieldType; function DataSetFieldToType(const dataSetField: TDataSetField): TDataSetFieldType; function MakeValidIdent(const s: string): string; implementation function TimeToISOTime(const time: TTime): string; begin Result := TimeToISOTime(time); end; function ISOTimeStampToDateTime(const dateTime: string): TDateTime; begin Result := ISO8601ToDate(dateTime); end; function ISODateToDate(const date: string): TDate; begin Result := ISODateToDate(date) end; function ISOTimeToTime(const time: string): TTime; begin Result := ISOTimeToTime(time) end; function NewDataSetField(dataSet: TDataSet; const fieldType: TFieldType; const fieldName: string; const size: Integer = 0; const origin: string = ''; const displaylabel: string = ''; const Key: Boolean = False): TField; begin Result := DefaultFieldClasses[fieldType].Create(dataSet); Result.fieldName := fieldName; if (Result.fieldName = '') then Result.fieldName := 'Field' + IntToStr(dataSet.FieldCount + 1); Result.FieldKind := fkData; Result.dataSet := dataSet; Result.Name := MakeValidIdent(dataSet.Name + Result.fieldName); Result.size := size; Result.origin := origin; if not (displaylabel.IsEmpty) then Result.displaylabel := displaylabel; if Key then Result.ProviderFlags := [pfInKey]; if (fieldType in [ftString, ftWideString]) and (size <= 0) then raise EDataSetConverterException.CreateFmt('Size not defined for field "%s".', [fieldName]); end; function BooleanToJSON(const value: Boolean): TJSONValue; begin if value then Result := TJSONTrue.Create else Result := TJSONFalse.Create; end; function BooleanFieldToType(const booleanField: TBooleanField): TBooleanFieldType; const DESC_BOOLEAN_FIELD_TYPE: array [TBooleanFieldType] of string = ('Unknown', 'Boolean', 'Integer'); var index: Integer; origin: string; begin Result := bfUnknown; origin := Trim(booleanField.origin); for index := Ord(Low(TBooleanFieldType)) to Ord(High(TBooleanFieldType)) do if (LowerCase(DESC_BOOLEAN_FIELD_TYPE[TBooleanFieldType(index)]) = LowerCase(origin)) then Exit(TBooleanFieldType(index)); end; function DataSetFieldToType(const dataSetField: TDataSetField): TDataSetFieldType; const DESC_DATASET_FIELD_TYPE: array [TDataSetFieldType] of string = ('Unknown', 'JSONObject', 'JSONArray'); var index: Integer; origin: string; begin Result := dfUnknown; origin := Trim(dataSetField.origin); for index := Ord(Low(TDataSetFieldType)) to Ord(High(TDataSetFieldType)) do if (LowerCase(DESC_DATASET_FIELD_TYPE[TDataSetFieldType(index)]) = LowerCase(origin)) then Exit(TDataSetFieldType(index)); end; function MakeValidIdent(const s: string): string; var x: Integer; c: Char; begin SetLength(Result, Length(s)); x := 0; for c in s do begin if CharInSet(c, ['A' .. 'Z', 'a' .. 'z', '0' .. '9', '_']) then begin Inc(x); Result[x] := c; end; end; SetLength(Result, x); if x = 0 then Result := '_' else if CharInSet(Result[1], ['0' .. '9']) then Result := '_' + Result; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.EMSFireDACConsts; interface resourcestring sResourceMustNotBeBlank = 'Resource must not be blank'; sSchemaAdapterIsRequired = 'SchemaAdapter is required'; sSchemaAdapterHasNoData = 'SchemaAdapter "%s" has no data'; sUnexpectedContentType = 'Unexpected content type: %s'; sResponseHasNoContent = 'Response has no content'; sProviderIsRequired = '"%s" must have a Provider'; sErrorsOnApplyUpdates = 'Unexpected errors applying updates:' + sLineBreak + '%s'; implementation end.
unit DAO_Membro; interface uses PRFWK_DAO, PRFWK_Atributo, DB, Classes, PRFWK_Modelo, SysUtils, StrUtils, MD_Membro, PRFWK_Utilidades; type TDAO_Membro = class(TPRFWK_DAO) private public constructor Create(); override; destructor Destroy; override; function obterOrdemNome(ordem: String = 'nome'; direcaoOrdem:String = 'ASC'):TList; published end; implementation uses uFrmPrincipal; { TGR_Membro } {** * Construtor *} constructor TDAO_Membro.Create(); begin //define conexão e entidade conexao := uFrmPrincipal.gConexao; nomeTabela := 'membros'; //herda construtor inherited; //adiciona mapeamentos adicionarMapeamento('nome'); end; {** * Destrutor *} destructor TDAO_Membro.Destroy; begin inherited; end; {** * Obtém as entidades pela pesquisa *} function TDAO_Membro.obterOrdemNome(ordem: String = 'nome'; direcaoOrdem:String = 'ASC'):TList; var lParametros : String; lOrdem : String; lDirecaoOrdem : String; begin //cria parâmetros lParametros := ' WHERE 1=1 '; //cria ordem lOrdem := ' ORDER BY ' + ordem + ' '; lDirecaoOrdem := ' ' + direcaoOrdem + ' '; //define sql defineSql('SELECT * FROM ' + nomeTabela + lParametros + lOrdem + lDirecaoOrdem); //percorre o dataSet if aClientDataSet.RecordCount > 0 then begin //cria lista de resultados Result := TList.Create; while not aClientDataSet.Eof do begin //monta entidade adicionando na lista Result.Add( TMD_Membro.NewInstance ); //monta entidade apartir do dataSet montarEntidade( Result[Result.Count-1] ); //próximo registro aClientDataSet.Next; end; end else Result := nil; end; end.
unit U_POWER_ANALYSIS_FUN; interface uses U_POWER_LIST_INFO, U_CKM_DEVICE; /// <summary> /// 功率状态转成成功率信息 /// </summary> procedure PowerStatusToInfo(APstatus : TPOWER_STATUS; APInfo : TObject); implementation procedure PowerStatusToInfo(APstatus : TPOWER_STATUS; APInfo : TObject); function GetAngle(dValue : Double) : Double; begin if dValue >= 360 then dValue := dValue - 360; if dValue <= -360 then dValue := dValue + 360; if dValue >= 360 then dValue := dValue - 360; if dValue <= -360 then dValue := dValue + 360; Result := dValue; end; begin if not (Assigned(APstatus) and Assigned(APInfo)) then Exit; if APstatus.PowerType = ptThree then begin if APInfo is TThreePower then begin TThreePower(APInfo).U12 := APstatus.U1*100; TThreePower(APInfo).U32 := APstatus.U3*100; TThreePower(APInfo).I1 := APstatus.I1*5; TThreePower(APInfo).I3 := APstatus.I3*5; TThreePower(APInfo).U12i1 := GetAngle(APstatus.O1); TThreePower(APInfo).U32i3 := GetAngle(APstatus.O3); TThreePower(APInfo).U12u32 := GetAngle(APstatus.OU1U3); end; end else begin if APInfo is TFourPower then begin TFourPower(APInfo).U1 := APstatus.U1*220; TFourPower(APInfo).U2 := APstatus.U2*220; TFourPower(APInfo).U3 := APstatus.U3*220; TFourPower(APInfo).I1 := APstatus.I1*5; TFourPower(APInfo).I2 := APstatus.I2*5; TFourPower(APInfo).I3 := APstatus.I3*5; TFourPower(APInfo).U1i1 := GetAngle(APstatus.O1); TFourPower(APInfo).U2i2 := GetAngle(APstatus.O2); TFourPower(APInfo).U3i3 := GetAngle(APstatus.O3); TFourPower(APInfo).U1u2 := GetAngle(APstatus.OU1U2); TFourPower(APInfo).U1u3 := GetAngle(APstatus.OU1U3); TFourPower(APInfo).U2u3 := GetAngle(APstatus.OU1U3- APstatus.OU1U2); end; end; end; end.
{***********************************<_INFO>************************************} { <Проект> Медиа-сервер } { } { <Область> 16:Медиа-контроль } { } { <Задача> Медиа-источник, предоставляющий возможность объединять данные } { из нескольких других источников } { } { <Автор> Фадеев Р.В. } { } { <Дата> 14.01.2011 } { } { <Примечание> Нет примечаний. } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaServer.Stream.Source.InPointsMultiplexer; interface uses Windows, SysUtils, Classes, SyncObjs, Types, MediaServer.Stream.Source, MediaProcessing.Definitions,MediaServer.Definitions, MediaServer.InPoint; type //Класс, выполняющий непосредственно получение данных (видеопотока) из камеры TMediaServerSourceInPointsMultiplexer = class (TMediaServerSource) private FInPoints: TMediaServerInPointArray; //FInPointSinks : array of IMediaStreamDataSink; FOpened: boolean; function GetInPoint(index: integer): TMediaServerInPoint; procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal); protected function GetStreamType(aMediaType: TMediaType): TStreamType; override; public constructor Create(aInPoints: TMediaServerInPointArray); overload; destructor Destroy; override; procedure DoOpen(aSync: boolean); override; procedure DoClose; override; procedure WaitWhileConnecting(aTimeout: integer); override; function Opened: Boolean; override; function Name: string; override; function DeviceType: string; override; function ConnectionString: string; override; function StreamInfo: TBytes; override; function PtzSupported: boolean; override; property InPoints[index: integer]: TMediaServerInPoint read GetInPoint; function InPointCount: integer; class function ParseConnectionString(const aConnectionString: string): TStringDynArray; end; implementation uses Math,Forms,MediaServer.Workspace,uTrace,uBaseUtils, MediaStream.FramerFactory; type TMediaStreamDataSink = class (TInterfacedObject,IMediaStreamDataSink) private FOwner: TMediaServerSourceInPointsMultiplexer; FInPoint:TMediaServerInPoint; FChannel: integer; public constructor Create(aOwner: TMediaServerSourceInPointsMultiplexer; aInPoint:TMediaServerInPoint; aChannel: integer); destructor Destroy; override; procedure OnData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); end; { TMediaServerSourceInPointsMultiplexer } constructor TMediaServerSourceInPointsMultiplexer.Create(aInPoints: TMediaServerInPointArray); var i: Integer; aSink: IMediaStreamDataSink; begin Create(-1); //UsePrebuffer:=false; FInPoints:=aInPoints; //SetLength(FInPointSinks,Length(FInPoints)); for i := 0 to High(FInPoints) do begin aSink:=TMediaStreamDataSink.Create(self,FInPoints[i],i); FInPoints[i].DataSinks.AddSink(aSink); end; end; destructor TMediaServerSourceInPointsMultiplexer.Destroy; begin inherited; FInPoints:=nil; //FInPointSinks:=nil; end; function TMediaServerSourceInPointsMultiplexer.DeviceType: string; begin result:='Мультиплексор'; end; function TMediaServerSourceInPointsMultiplexer.Name: string; begin result:='Input Point Multiplexer'; end; procedure TMediaServerSourceInPointsMultiplexer.OnFrameReceived( const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal); begin DoDataReceived(aFormat, aData,aDataSize, aInfo,aInfoSize); end; procedure TMediaServerSourceInPointsMultiplexer.DoOpen(aSync: boolean); var I: Integer; begin if Opened then exit; for I := 0 to High(FInPoints) do FInPoints[i].Open(aSync); FOpened:=true; if Assigned(OnConnectionOk) then OnConnectionOk(self); end; procedure TMediaServerSourceInPointsMultiplexer.DoClose; begin FOpened:=false; end; function TMediaServerSourceInPointsMultiplexer.GetInPoint(index: integer): TMediaServerInPoint; begin result:=FInPoints[index]; end; function TMediaServerSourceInPointsMultiplexer.InPointCount: integer; begin result:=Length(FInPoints); end; function TMediaServerSourceInPointsMultiplexer.GetStreamType(aMediaType: TMediaType): TStreamType; begin result:=0; if Length(FInPoints)>0 then result:=FInPoints[0].StreamTypes[aMediaType]; end; function TMediaServerSourceInPointsMultiplexer.ConnectionString: string; var i: Integer; begin for i := 0 to High(FInPoints) do result:=result+FInPoints[i].Name+'; '; if result<>'' then SetLength(Result,Length(result)-2); end; function TMediaServerSourceInPointsMultiplexer.Opened: Boolean; begin result:=FOpened; end; function TMediaServerSourceInPointsMultiplexer.StreamInfo: TBytes; begin result:=nil; end; class function TMediaServerSourceInPointsMultiplexer.ParseConnectionString(const aConnectionString: string): TStringDynArray; var aList: TStringList; i: Integer; begin aList:=TStringList.Create; try fsiBaseUtils.SplitString(aConnectionString,aList,';'); SetLength(result,aList.Count); for i := 0 to aList.Count - 1 do result[i]:=aList[i]; finally aList.Free; end; end; function TMediaServerSourceInPointsMultiplexer.PtzSupported: boolean; begin result:=false; end; procedure TMediaServerSourceInPointsMultiplexer.WaitWhileConnecting(aTimeout: integer); begin inherited; //TODO ждать всех или нет? end; { TMediaStreamDataSink } constructor TMediaStreamDataSink.Create(aOwner: TMediaServerSourceInPointsMultiplexer; aInPoint: TMediaServerInPoint; aChannel: integer); begin inherited Create; FOwner:=aOwner; FInPoint:=aInPoint; FChannel:=aChannel; end; destructor TMediaStreamDataSink.Destroy; begin FOwner:=nil; FInPoint:=nil; inherited; end; procedure TMediaStreamDataSink.OnData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); var aFormat2: TMediaStreamDataHeader; begin if FOwner<>nil then if FInPoint<>nil then begin aFormat2:=aFormat; aFormat2.Channel:=FChannel; if FOwner.FOpened then FOwner.OnFrameReceived(aFormat2,aData,aDataSize,aInfo,aInfoSize); end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, XLSReadWriteII5, StdCtrls, ExtCtrls, IniFiles, ShellApi, // XLSReadWriteII5 units XLSComment5, XLSDrawing5, Xc12Utils5, Xc12DataStyleSheet5, XLSSheetData5, XLSCmdFormat5, XPMan; // ***************************************************************************** // ***** FORMATTING CELLS ***** // ***** ***** // ***** Cell formats in Excel files are not stored in the cells ***** // ***** themself. Instead is a global list with formats common to ***** // ***** many cells used. The cells stores an index into this list. ***** // ***** The max size of the format list is 65536 items. This means ***** // ***** that the formats list has to be maintained, and searched for ***** // ***** existing matching formats when a cell is formatted. ***** // ***** ***** // ***** There are 3 differnet ways of formatting cells. ***** // ***** ***** // ***** 1. Using the Cell object of the worksheet, XLS[0].Cell[Col,Row] ***** // ***** There must be a cell(value) before the Cell can be uses, so ***** // ***** at least add a blank cell. The Cell object is most usefull ***** // ***** for reading the formatting of a single cell. Creating formats ***** // ***** with the Cell object is extremly slow and reallly only usefull ***** // ***** for just a few cells. ***** // ***** ***** // ***** 2. Using the CmdFormat object of the workbook, XLS.CmdFormat. ***** // ***** The CmdFormat works like the Format Cells dialog in Excel with ***** // ***** child objects for Number, Alignment, Font, Border, Fill and ***** // ***** Protection properties. While Excel always merges formats when ***** // ***** a cell is formatted (that is, if you put a border around a ***** // ***** cell and the cell allready has a backgroud color, that color ***** // ***** is preserved), XLSReadWriteII also have the option to replace ***** // ***** any existing format. The advatage of this is that the format ***** // ***** list don't have to searched and hence it's much faster. About ***** // ***** ten times faster. If you format an empty worksheet this is ***** // ***** always the best option. ***** // ***** ***** // ***** 4. Creating a default format. A default format, if assigned, is ***** // ***** used when new cells are added. You can have several default ***** // ***** formats and swithch between them. This is the fastest method. ***** // ***** ***** // ***************************************************************************** type TfrmMain = class(TForm) dlgSave: TSaveDialog; XLS: TXLSReadWriteII5; btnWrite: TButton; edWriteFilename: TEdit; btnDlgSave: TButton; btnSingleCell: TButton; btnAreas: TButton; btnClose: TButton; btnDefaultFormat: TButton; btnExcel: TButton; btnProtect: TButton; btnColumns: TButton; btnRows: TButton; Label1: TLabel; edPassword: TEdit; XPManifest1: TXPManifest; Button1: TButton; procedure btnCloseClick(Sender: TObject); procedure btnWriteClick(Sender: TObject); procedure btnDlgSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSingleCellClick(Sender: TObject); procedure btnDefaultFormatClick(Sender: TObject); procedure btnAreasClick(Sender: TObject); procedure btnExcelClick(Sender: TObject); procedure edWriteFilenameChange(Sender: TObject); procedure btnProtectClick(Sender: TObject); procedure btnColumnsClick(Sender: TObject); procedure btnRowsClick(Sender: TObject); procedure Button1Click(Sender: TObject); private public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.btnSingleCellClick(Sender: TObject); begin // Formats a single cell. Use only this method for very few cells as it is // extremly slow. The cell properties can however be usefull for reading // formatting properties of cells. XLS[0].AsFloat[2,3] := 125.5; XLS[0].Cell[2,3].FillPatternForeColorRGB := $AFAFAF; XLS[0].Cell[2,3].NumberFormat := '0.000'; XLS[0].Cell[2,3].BorderLeftStyle := cbsThick; XLS[0].Cell[2,3].BorderLeftColor := xcRed; XLS[0].Cell[2,3].BorderRightStyle := cbsThick; XLS[0].Cell[2,3].BorderRightColor := xcRed; XLS[0].Cell[2,3].BorderTopStyle := cbsThick; XLS[0].Cell[2,3].BorderTopColor := xcRed; XLS[0].Cell[2,3].BorderBottomStyle := cbsThick; XLS[0].Cell[2,3].BorderBottomColor := xcRed; end; procedure TfrmMain.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmMain.btnWriteClick(Sender: TObject); begin XLS.Filename := edWriteFilename.Text; XLS.Write; end; procedure TfrmMain.btnDlgSaveClick(Sender: TObject); begin dlgSave.InitialDir := ExtractFilePath(Application.ExeName); dlgSave.FileName := edWriteFilename.Text; if dlgSave.Execute then edWriteFilename.Text := dlgSave.FileName; end; procedure TfrmMain.FormCreate(Sender: TObject); var S: string; Ini: TIniFile; begin S := ChangeFileExt(Application.ExeName,'.ini'); Ini := TIniFile.Create(S); try edWriteFilename.Text := Ini.ReadString('Files','Write',''); finally Ini.Free; end; end; procedure TfrmMain.FormDestroy(Sender: TObject); var S: string; Ini: TIniFile; begin S := ChangeFileExt(Application.ExeName,'.ini'); Ini := TIniFile.Create(S); try Ini.WriteString('Files','Write',edWriteFilename.Text); finally Ini.Free; end; end; procedure TfrmMain.btnDefaultFormatClick(Sender: TObject); var R: integer; DefFmt_F3: TXLSDefaultFormat; begin // Create first default format. // The sheet parameter of BeginFormat is Nil, as it's not assigned to any // particular worksheet. XLS.CmdFormat.BeginEdit(Nil); XLS.CmdFormat.Fill.BackgroundColor.RGB := $7F7F10; XLS.CmdFormat.Font.Name := 'Courier new'; XLS.CmdFormat.AddAsDefault('F1'); // Create second default format. XLS.CmdFormat.BeginEdit(Nil); XLS.CmdFormat.Fill.BackgroundColor.RGB := $FF1010; XLS.CmdFormat.Font.Name := 'Ariel Black'; XLS.CmdFormat.Border.Color.IndexColor := xcBlack; XLS.CmdFormat.Border.Style := cbsThick; XLS.CmdFormat.Border.Preset(cbspOutline); XLS.CmdFormat.AddAsDefault('F2'); // Create third default format. XLS.CmdFormat.BeginEdit(Nil); XLS.CmdFormat.Fill.BackgroundColor.RGB := $10F040; XLS.CmdFormat.Font.Name := 'Times New Roman'; XLS.CmdFormat.Font.Style := [xfsBold,xfsItalic]; DefFmt_F3 := XLS.CmdFormat.AddAsDefault('F3'); // The default formats are in the XLS.CmdFormat.Defaults property. for R := 2 to 100 do begin if (R mod 4) = 0 then // Assign format by name. XLS.DefaultFormat := XLS.CmdFormat.Defaults.Find('F2') else if (R mod 7) = 0 then // Assign format by variable. XLS.DefaultFormat := DefFmt_F3 else // Assign format by index. We know that format 'F1' has index #0 as the // list was empty. XLS.DefaultFormat := XLS.CmdFormat.Defaults[0]; XLS[0].AsFloat[2,R] := 525; end; // Reset the default format. XLS.DefaultFormat := Nil; end; procedure TfrmMain.btnAreasClick(Sender: TObject); begin // There are two formatting modes, Merge and Replace. Merge will merge the // assigned properies with any existing cells. This is how Excel works. // Replace will replace any existing formats with the new format. // The Replace mode is about 10 times faster than merge, as merging formats // means that for every cell the format lists has to be searched for the // combination of the new and the old format. // Merge is the default mode. XLS.CmdFormat.Mode := xcfmMerge; // XLS.CmdFormat.Mode := xcfmReplace; // Begin formatting on sheet #0. XLS.CmdFormat.BeginEdit(XLS[0]); // Set background color. XLS.CmdFormat.Fill.BackgroundColor.RGB := $7F7F10; // Border color and style. XLS.CmdFormat.Border.Color.RGB := $7F1010; XLS.CmdFormat.Border.Style := cbsThick; // Set the border outline of the cells. XLS.CmdFormat.Border.Preset(cbspOutline); // Border style of lines inside. XLS.CmdFormat.Border.Style := cbsThin; XLS.CmdFormat.Border.Preset(cbspInside); // Apply format. XLS.CmdFormat.Apply(2,2,10,30); // Formats can also be applied on the current selection XLS[0].SelectedAreas[0].Col1 := 12; XLS[0].SelectedAreas[0].Row1 := 2; XLS[0].SelectedAreas[0].Col2 := 15; XLS[0].SelectedAreas[0].Row2 := 30; // Without arguments Apply will apply the format on the selected cells. XLS.CmdFormat.Apply; end; procedure TfrmMain.btnExcelClick(Sender: TObject); begin ShellExecute(Handle,'open', 'excel.exe',PwideChar(edWriteFilename.Text), nil, SW_SHOWNORMAL); end; procedure TfrmMain.edWriteFilenameChange(Sender: TObject); begin btnExcel.Enabled := edWriteFilename.Text <> ''; end; procedure TfrmMain.btnProtectClick(Sender: TObject); begin XLS[0].AsString[4,3] := 'Unprotected cells'; // Protect cells on sheet #0. XLS.CmdFormat.BeginEdit(XLS[0]); // Create an area of unprotected cells, that is, the cells are not locked. XLS.CmdFormat.Fill.BackgroundColor.RGB := $AFAFAF; XLS.CmdFormat.Protection.Locked := False; XLS.CmdFormat.Apply(4,4,4,10); // Set the password of the worksheet. XLS[0].Protection.Password := edPassword.Text; end; procedure TfrmMain.btnColumnsClick(Sender: TObject); begin XLS.CmdFormat.BeginEdit(XLS[0]); XLS.CmdFormat.Border.Color.RGB := $0000FF; XLS.CmdFormat.Border.Style := cbsThick; XLS.CmdFormat.Border.Side[cbsLeft] := True; XLS.CmdFormat.Border.Side[cbsRight] := True; XLS.CmdFormat.ApplyCols(1,5); end; procedure TfrmMain.btnRowsClick(Sender: TObject); begin XLS.CmdFormat.BeginEdit(XLS[0]); XLS.CmdFormat.Border.Color.RGB := $FF0000; XLS.CmdFormat.Border.Style := cbsThick; XLS.CmdFormat.Border.Side[cbsTop] := True; XLS.CmdFormat.Border.Side[cbsBottom] := True; XLS.CmdFormat.ApplyRows(1,5); end; procedure TfrmMain.Button1Click(Sender: TObject); begin // Shows how to set individual borders for cells XLS.CmdFormat.BeginEdit(XLS[0]); // Border color and style must be set first. XLS.CmdFormat.Border.Color.IndexColor := xcRed; XLS.CmdFormat.Border.Style := cbsThick; // Apply the color and style on selected sides. XLS.CmdFormat.Border.Side[cbsTop] := True; XLS.CmdFormat.Border.Side[cbsBottom] := True; XLS.CmdFormat.Apply(11,3,18,3); end; end.
unit ReflectorsU; interface uses System.Generics.Collections, System.IniFiles, Winapi.Windows, Winapi.Messages, Winapi.ShlObj, System.SysUtils, System.Variants, System.Classes, IdBaseComponent, IdMappedPortTCP, IdUDPBase, IdMappedPortUDP, IdSocketHandle, IdContext, ToolsU; type EReflectorException = class(Exception); TReflectorType = (refTCP, refUDP); type TReflectorBinding = class private FPort: integer; FIP: string; procedure SetIP(const Value: string); procedure SetPort(const Value: integer); public property IP: string read FIP write SetIP; property Port: integer read FPort write SetPort; end; TReflectorBindings = TObjectList<TReflectorBinding>; TReflectorSettings = class(TPersistent) private FReflectorBindings: TReflectorBindings; FMappedPort: integer; FMappedHost: string; FReflectorType: TReflectorType; FEnabled: boolean; FReflectorName: string; procedure SetMappedHost(const Value: string); procedure SetMappedPort(const Value: integer); procedure SetReflectorType(const Value: TReflectorType); procedure SetEnabled(const Value: boolean); procedure SetReflectorName(const Value: string); procedure Load(AINIFile: TINIFile); procedure Save(AINIFile: TINIFile); procedure Reset(APreserveName: boolean = false); public constructor Create; reintroduce; destructor Destroy; override; procedure AddBindings(AIP: string; APort: integer); property Enabled: boolean read FEnabled write SetEnabled; property ReflectorName: string read FReflectorName write SetReflectorName; property Bindings: TReflectorBindings read FReflectorBindings; property ReflectorType: TReflectorType read FReflectorType write SetReflectorType; property MappedHost: string read FMappedHost write SetMappedHost; property MappedPort: integer read FMappedPort write SetMappedPort; end; TReflector = class(TObject) private FIdMappedPortTCP: TIdMappedPortTCP; FIdMappedPortUDP: TIdMappedPortUDP; FLogFile: TFileName; procedure RotateFile(AFileName: TFileName; AMaxRotations: integer = 5); function IsLogRotationRequired(AFileName: TFileName): boolean; function GetLogFolder: string; protected property IdMappedPortTCP: TIdMappedPortTCP read FIdMappedPortTCP; property IdMappedPortUDP: TIdMappedPortUDP read FIdMappedPortUDP; procedure IdMappedPortConnect(AContext: TIdContext); procedure IdMappedPortDisconnect(AContext: TIdContext); procedure Log(AMessage: string; APrefix: string = 'LOG'); procedure Error(AMessage: string); overload; procedure Error(AException: Exception; AMessage: string = ''); overload; procedure Warning(AMessage: string); public constructor Create; reintroduce; destructor Destroy; override; function Start(AReflectorSettings: TReflectorSettings): boolean; function Stop: boolean; end; TReflectorList = TObjectList<TReflector>; TReflectorSettingsList = TObjectList<TReflectorSettings>; TReflectors = class(TComponent) private FReflectorList: TReflectorList; FReflectorSettingsList: TReflectorSettingsList; FFileName: TFileName; procedure SetFileName(const Value: TFileName); protected property ReflectorList: TReflectorList read FReflectorList; function GetDefaultSettingsFolder: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Settings: TReflectorSettingsList read FReflectorSettingsList; property FileName: TFileName read FFileName write SetFileName; procedure LoadSettings; procedure SaveSettings(AFileName: TFileName); overload; procedure SaveSettings; overload; function RunCount: integer; function IsRunning: boolean; function Start: boolean; function Stop: boolean; end; implementation uses System.DateUtils; { TReflectors } constructor TReflectors.Create(AOwner: TComponent); begin inherited Create(AOwner); FReflectorList := TReflectorList.Create(True); FReflectorSettingsList := TReflectorSettingsList.Create(True); FFileName := GetDefaultSettingsFolder + 'reflectors.ini'; end; destructor TReflectors.Destroy; begin try Stop; FreeAndNil(FReflectorSettingsList); FreeAndNil(FReflectorList); finally inherited; end; end; function TReflectors.GetDefaultSettingsFolder: string; begin Result := IncludeTrailingPathDelimiter (IncludeTrailingPathDelimiter(GetShellFolderPath(CSIDL_COMMON_APPDATA)) + 'NetReflector'); CheckDirectoryExists(Result, True); end; function TReflectors.IsRunning: boolean; begin Result := FReflectorList.Count > 0; end; procedure TReflectors.LoadSettings; var LINIFile: TINIFile; LSettingsList: TStringList; LIdx: integer; LReflectorSettings: TReflectorSettings; begin Stop; LINIFile := TINIFile.Create(FFileName); LSettingsList := TStringList.Create; FReflectorSettingsList.Clear; try LINIFile.ReadSection('Reflectors', LSettingsList); for LIdx := 0 to Pred(LSettingsList.Count) do begin LReflectorSettings := TReflectorSettings.Create; LReflectorSettings.ReflectorName := LSettingsList[LIdx]; LReflectorSettings.Load(LINIFile); FReflectorSettingsList.Add(LReflectorSettings); end; finally FreeAndNil(LINIFile); FreeAndNil(LSettingsList); end; end; function TReflectors.RunCount: integer; begin Result := FReflectorList.Count; end; procedure TReflectors.SaveSettings(AFileName: TFileName); var LINIFile: TINIFile; LReflectorSettings: TReflectorSettings; begin if FileExists(AFileName) then begin DeleteFile(AFileName); end; LINIFile := TINIFile.Create(AFileName); try for LReflectorSettings in FReflectorSettingsList do begin LReflectorSettings.Save(LINIFile); end; finally FreeAndNil(LINIFile); end; end; procedure TReflectors.SaveSettings; begin SaveSettings(FFileName); end; procedure TReflectors.SetFileName(const Value: TFileName); begin if not SameText(FFileName, Value) then begin FFileName := Value; end; end; function TReflectors.Start: boolean; var LReflectorSettings: TReflectorSettings; LReflector: TReflector; begin Stop; for LReflectorSettings in FReflectorSettingsList do begin LReflector := TReflector.Create; if LReflectorSettings.Enabled then begin if LReflector.Start(LReflectorSettings) then begin FReflectorList.Add(LReflector); end else begin FreeAndNil(LReflector); end; end; end; Result := FReflectorList.Count > 0; end; function TReflectors.Stop: boolean; var LIdx: integer; begin Result := false; try for LIdx := 0 to Pred(FReflectorList.Count) do begin FReflectorList[LIdx].Stop; end; FReflectorList.Clear; Result := True; except on E: Exception do begin // Error(E); end; end; end; { TReflector } constructor TReflector.Create; begin inherited; end; destructor TReflector.Destroy; begin try Stop; finally inherited; end; end; procedure TReflector.Error(AException: Exception; AMessage: string); begin Log(AException.Message + ', Message: ' + AMessage, 'ERROR'); end; procedure TReflector.Error(AMessage: string); begin Log(AMessage, 'ERROR'); end; procedure TReflector.IdMappedPortConnect(AContext: TIdContext); begin Log('Connect: ' + AContext.Binding.PeerIP + ': ' + IntToStr(AContext.Binding.PeerPort)); end; procedure TReflector.IdMappedPortDisconnect(AContext: TIdContext); begin Log('Disconnect: ' + AContext.Binding.PeerIP + ': ' + IntToStr(AContext.Binding.PeerPort)); end; function TReflector.GetLogFolder: string; begin Result := IncludeTrailingPathDelimiter (GetShellFolderPath(CSIDL_COMMON_APPDATA)); Result := IncludeTrailingPathDelimiter(Result + 'NetReflector'); Result := IncludeTrailingPathDelimiter(Result + 'log'); CheckDirectoryExists(Result, True); end; function TReflector.IsLogRotationRequired(AFileName: TFileName): boolean; const MaxLogFileSize = 1048576; var LFileSize: Int64; begin Result := false; if FileExists(AFileName) then begin LFileSize := ToolsU.GetFileSize(AFileName); Result := LFileSize >= MaxLogFileSize; end; end; procedure TReflector.RotateFile(AFileName: TFileName; AMaxRotations: integer); var LIdx: integer; LFileName: TFileName; ANewFileName: TFileName; begin try for LIdx := AMaxRotations downto 1 do begin LFileName := AFileName + '.' + IntToStr(LIdx); if FileExists(LFileName) then begin if LIdx < AMaxRotations then begin ANewFileName := ChangeFileExt(LFileName, '.' + IntToStr(LIdx + 1)); RenameFile(LFileName, ANewFileName); end else begin DeleteFile(LFileName); end; end; end; LFileName := AFileName; if FileExists(LFileName) then begin ANewFileName := LFileName + '.1'; RenameFile(LFileName, ANewFileName); end; except on E: Exception do begin end; end; end; procedure TReflector.Log(AMessage, APrefix: string); var LLogFile: TextFile; LFolder, LMessage: string; begin try LFolder := ExtractFilePath(FLogFile); LMessage := Format('%s|%s|%s', [FormatDateTime('yyyymmddhhnnss', Now), APrefix, AMessage]); LMessage := StripExtraSpaces(LMessage, True, True); if CheckDirectoryExists(LFolder, True) then begin if IsLogRotationRequired(FLogFile) then begin RotateFile(FLogFile); end; AssignFile(LLogFile, FLogFile); if FileExists(FLogFile) then begin Append(LLogFile); end else begin Rewrite(LLogFile); end; WriteLn(LLogFile, LMessage); Flush(LLogFile); CloseFile(LLogFile); end else begin raise EReflectorException.CreateFmt('Failed to create log file "%s"', [LFolder]); end; except on E: Exception do begin OutputDebugString(PChar(E.Message + ', LogFile: ' + FLogFile + ', Message:' + LMessage)); end; end; end; function TReflector.Start(AReflectorSettings: TReflectorSettings): boolean; var LIdx: integer; begin Result := false; try FLogFile := GetLogFolder + ValidateFileName(AReflectorSettings.ReflectorName + '.log'); Log('Starting ' + AReflectorSettings.ReflectorName); case AReflectorSettings.ReflectorType of refTCP: begin FIdMappedPortTCP := TIdMappedPortTCP.Create(nil); FIdMappedPortTCP.OnConnect := IdMappedPortConnect; FIdMappedPortTCP.OnDisconnect := IdMappedPortDisconnect; FIdMappedPortTCP.MappedHost := AReflectorSettings.MappedHost; FIdMappedPortTCP.MappedPort := AReflectorSettings.MappedPort; if AReflectorSettings.Bindings.Count > 0 then begin for LIdx := 0 to Pred(AReflectorSettings.Bindings.Count) do begin with FIdMappedPortTCP.Bindings.Add do begin IP := AReflectorSettings.Bindings[LIdx].IP; Port := AReflectorSettings.Bindings[LIdx].Port; end; end; end else begin with FIdMappedPortTCP.Bindings.Add do begin IP := '0.0.0.0'; Port := AReflectorSettings.MappedPort; end; end; FIdMappedPortTCP.Active := True; Result := FIdMappedPortTCP.Active; end; refUDP: begin FIdMappedPortUDP := TIdMappedPortUDP.Create(nil); FIdMappedPortUDP.MappedHost := AReflectorSettings.MappedHost; FIdMappedPortUDP.MappedPort := AReflectorSettings.MappedPort; if AReflectorSettings.Bindings.Count > 0 then begin for LIdx := 0 to Pred(AReflectorSettings.Bindings.Count) do begin with FIdMappedPortUDP.Bindings.Add do begin IP := AReflectorSettings.Bindings[LIdx].IP; Port := AReflectorSettings.Bindings[LIdx].Port; end; end; end else begin with FIdMappedPortUDP.Bindings.Add do begin IP := '0.0.0.0'; Port := AReflectorSettings.MappedPort; end; end; FIdMappedPortUDP.Active := True; Result := FIdMappedPortUDP.Active; end; end; except on E: Exception do begin Error(E.Message); end; end; end; function TReflector.Stop: boolean; begin Result := false; try if Assigned(FIdMappedPortTCP) then begin FIdMappedPortTCP.Active := false; FreeAndNil(FIdMappedPortTCP); end; if Assigned(FIdMappedPortUDP) then begin FIdMappedPortUDP.Active := false; FreeAndNil(FIdMappedPortUDP); end; except on E: Exception do begin Error(E.Message); end; end; end; procedure TReflector.Warning(AMessage: string); begin Log(AMessage, 'WARNING'); end; { TReflectorSettings } procedure TReflectorSettings.AddBindings(AIP: string; APort: integer); var LReflectorBinding: TReflectorBinding; begin LReflectorBinding := TReflectorBinding.Create; LReflectorBinding.Port := APort; LReflectorBinding.IP := AIP; FReflectorBindings.Add(LReflectorBinding); end; constructor TReflectorSettings.Create; begin FReflectorBindings := TReflectorBindings.Create(True); Reset; end; destructor TReflectorSettings.Destroy; begin try FreeAndNil(FReflectorBindings); finally inherited; end; end; procedure TReflectorSettings.Load(AINIFile: TINIFile); var LBindingSections: TStringList; LIdx: integer; LBinding: TReflectorBinding; begin Reset(True); if not IsEmptyString(FReflectorName) then begin LBindingSections := TStringList.Create; try FEnabled := AINIFile.ReadBool(FReflectorName, 'Enabled', True); FReflectorType := TReflectorType(AINIFile.ReadInteger(FReflectorName, 'Type', integer(refTCP))); FMappedPort := AINIFile.ReadInteger(FReflectorName, 'MappedPort', 0); FMappedHost := AINIFile.ReadString(FReflectorName, 'MappedHost', ''); AINIFile.ReadSection(FReflectorName + '.Bindings', LBindingSections); for LIdx := 0 to Pred(LBindingSections.Count) do begin LBinding := TReflectorBinding.Create; LBinding.IP := AINIFile.ReadString(LBindingSections[LIdx], 'IP', '0.0.0.0'); LBinding.Port := AINIFile.ReadInteger(LBindingSections[LIdx], 'Port', FMappedPort); Bindings.Add(LBinding); end; finally FreeAndNil(LBindingSections); end; end else begin raise EReflectorException.Create('Name has not been specified'); end; end; procedure TReflectorSettings.Reset(APreserveName: boolean); begin if not APreserveName then begin FReflectorName := ''; end; FEnabled := True; FReflectorType := refTCP; FMappedPort := 0; FMappedHost := 'localhost'; FReflectorBindings.Clear; end; procedure TReflectorSettings.Save(AINIFile: TINIFile); var LIdx: integer; LBindingSectionName: string; begin if not IsEmptyString(FReflectorName) then begin AINIFile.WriteString('Reflectors', FReflectorName, ''); AINIFile.WriteBool(FReflectorName, 'Enabled', FEnabled); AINIFile.WriteInteger(FReflectorName, 'Type', integer(FReflectorType)); AINIFile.WriteInteger(FReflectorName, 'MappedPort', FMappedPort); AINIFile.WriteString(FReflectorName, 'MappedHost', FMappedHost); AINIFile.EraseSection(FReflectorName + '.Bindings'); for LIdx := 0 to Pred(FReflectorBindings.Count) do begin LBindingSectionName := FReflectorName + '.Bindings' + '.' + IntToStr(LIdx); AINIFile.WriteString(FReflectorName + '.Bindings', LBindingSectionName, ''); AINIFile.WriteString(LBindingSectionName, 'IP', Bindings[LIdx].IP); AINIFile.WriteInteger(LBindingSectionName, 'Port', Bindings[LIdx].Port); end; end else begin raise EReflectorException.Create('Name has not been specified'); end; end; procedure TReflectorSettings.SetEnabled(const Value: boolean); begin FEnabled := Value; end; procedure TReflectorSettings.SetMappedHost(const Value: string); begin FMappedHost := Value; end; procedure TReflectorSettings.SetMappedPort(const Value: integer); begin FMappedPort := Value; end; procedure TReflectorSettings.SetReflectorName(const Value: string); begin FReflectorName := Value; end; procedure TReflectorSettings.SetReflectorType(const Value: TReflectorType); begin FReflectorType := Value; end; { TReflectorBinding } procedure TReflectorBinding.SetIP(const Value: string); begin FIP := Value; end; procedure TReflectorBinding.SetPort(const Value: integer); begin FPort := Value; end; end.
unit Test_FIToolkit.Runner.Tasks; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.SysUtils, FIToolkit.Runner.Tasks; type // Test methods for class TTaskRunner TestTTaskRunner = class (TGenericTestCase) private const STR_OUTPUT_FILENAME_NO_EXT = 'test_output'; STR_OUTPUT_FILENAME_EXT = '.ext'; STR_OUTPUT_FILENAME = STR_OUTPUT_FILENAME_NO_EXT + STR_OUTPUT_FILENAME_EXT; STR_PROJECT_FILENAME_NO_EXT = 'test_input'; STR_PROJECT_FILENAME = STR_PROJECT_FILENAME_NO_EXT + '.ext'; strict private FTaskRunner : TTaskRunner; public procedure SetUp; override; procedure TearDown; override; published procedure TestExecute; end; // Test methods for class TTaskManager TestTTaskManager = class (TGenericTestCase) private const ARR_FILE_NAMES : array of TFileName = [String.Empty, String.Empty]; strict private FTaskManager : TTaskManager; public procedure SetUp; override; procedure TearDown; override; published procedure TestRunAndGetOutput; end; implementation uses System.Threading, System.IOUtils, System.Generics.Collections, TestUtils, FIToolkit.Config.FixInsight, FIToolkit.Commons.Utils, FIToolkit.Runner.Exceptions; procedure TestTTaskRunner.SetUp; var FIO : TFixInsightOptions; begin FIO := TFixInsightOptions.Create; try FIO.OutputFileName := STR_OUTPUT_FILENAME; FIO.ProjectFileName := STR_PROJECT_FILENAME; FTaskRunner := TTaskRunner.Create(String.Empty, FIO); finally FIO.Free; end; end; procedure TestTTaskRunner.TearDown; begin FreeAndNil(FTaskRunner); end; procedure TestTTaskRunner.TestExecute; var ReturnValue : ITask; S : String; begin ReturnValue := FTaskRunner.Execute; CheckAggregateException( procedure begin ReturnValue.Wait; end, ECreateProcessError, 'CheckAggregateException::ECreateProcessError' ); S := FTaskRunner.OutputFileName; CheckTrue(TPath.IsApplicableFileName(S), 'IsApplicableFileName(%s)', [S]); CheckEquals(TestDataDir, TPath.GetDirectoryName(S, True), 'GetDirectoryName(S) = TestDataDir'); CheckTrue(TPath.GetFileName(S).StartsWith(STR_OUTPUT_FILENAME_NO_EXT), 'GetFileName(S).StartsWith(%s)', [STR_OUTPUT_FILENAME_NO_EXT]); CheckTrue(S.EndsWith(STR_OUTPUT_FILENAME_EXT), 'S.EndsWith(%s)', [STR_OUTPUT_FILENAME_EXT]); CheckTrue(S.Contains(STR_PROJECT_FILENAME_NO_EXT), 'S.Contains(%s)', [STR_PROJECT_FILENAME_NO_EXT]); CheckFalse(S.Contains(STR_PROJECT_FILENAME), 'S.Contains(%s)', [STR_PROJECT_FILENAME]); S := FTaskRunner.InputFileName; CheckEquals(STR_PROJECT_FILENAME, S, 'InputFileName = STR_PROJECT_FILENAME'); end; procedure TestTTaskManager.SetUp; var FIO : TFixInsightOptions; begin FIO := TFixInsightOptions.Create; try FTaskManager := TTaskManager.Create(String.Empty, FIO, ARR_FILE_NAMES, TestDataDir); finally FIO.Free; end; end; procedure TestTTaskManager.TearDown; begin FreeAndNil(FTaskManager); end; procedure TestTTaskManager.TestRunAndGetOutput; var ReturnValue: TArray<TPair<TFileName, TFileName>>; begin CheckException( procedure begin ReturnValue := FTaskManager.RunAndGetOutput; end, ESomeTasksFailed, 'CheckException::ESomeTasksFailed' ); end; initialization // Register any test cases with the test runner RegisterTest(TestTTaskRunner.Suite); RegisterTest(TestTTaskManager.Suite); end.
unit ImageAltercationUnit; //////////////////////////////////////////////////////////////////////////////// // // // Description: Routines for processing images and returning a specific type // // // // ResizeImage // // The work horse. Takes an image and resizes it // // // // ResizeImageBMP // // Resizes image, passing out a bitmap // // // // ResizeImageJPEG // // Resizes image, passing out a JPEG // // // //////////////////////////////////////////////////////////////////////////////// interface uses Windows, Graphics, JPEG; function ResizeImage(imgOld: TGraphic; iHeight, iWidth: integer): TBitmap; function ResizeImageBMP(imgOld: TGraphic; iHeight, iWidth: integer): TBitmap; function ResizeImageJPEG(imgOld: TGraphic; iHeight, iWidth: integer): TJPEGImage; /////////////////////////// // Not implemented yet : // /////////////////////////// { function ResizeImageGIF function ResizeImagePNG } implementation uses Classes, SysUtils; function ResizeImage(imgOld: TGraphic; iHeight, iWidth: integer): TBitmap; /////////////////////////////////////////////////////////////////// // Preconditions : // // imgOld is a valid TGraphic // // iHeight and iWidth are valid height and width integer values // // // // Output : // // TBitmap of imgOld, resized to iHeight and iWidth values // /////////////////////////////////////////////////////////////////// var imgBMP: TBitmap; rectProxyRect: TRect; begin imgBMP := TBitmap.Create; try rectProxyRect := Rect(0, 0, iWidth, iHeight); with imgBMP do begin Height := iHeight; Width := iWidth; if Height = 0 then Height := 1; if Width = 0 then Width := 1; Canvas.StretchDraw(rectProxyRect, imgOld); end; Result := imgBMP; except on E:Exception do Raise Exception.Create('Error resizing image: ' + E.Message); end; // try..except end; function ResizeImageBMP(imgOld: TGraphic; iHeight, iWidth: integer): TBitmap; /////////////////////////////////////////////////////////////////// // Preconditions : // // imgOld is a valid TGraphic // // iHeight and iWidth are valid height and width integer values // // // // Output : // // TBitmap of imgOld, resized to iHeight and iWidth values // /////////////////////////////////////////////////////////////////// begin Result := ResizeImage(imgOld, iHeight, iWidth); end; function ResizeImageJPEG(imgOld: TGraphic; iHeight, iWidth: integer): TJPEGImage; /////////////////////////////////////////////////////////////////// // Preconditions : // // imgOld is a valid TGraphic // // iHeight and iWidth are valid height and width integer values // // // // Output : // // TJPEGImage of imgOld, resized to iHeight and iWidth values // /////////////////////////////////////////////////////////////////// var imgBMP: TBitmap; imgJPEG: TJPEGImage; begin imgJPEG := TJPEGImage.Create; imgBMP := ResizeImage(imgOld, iHeight, iWidth); if imgBMP <> nil then begin imgJPEG.Assign(imgBMP); Result := imgJPEG; end else Result := nil; FreeAndNil(imgBMP); end; end.
unit untStdRegEditors; interface uses DesignIntf, DesignEditors, DB, dxorgchr, dxdborgc, dxorgced, SqlEdit, Windows, Classes, Forms, ShellApi, cxDBShellComboBox, cxEditPropEditors, cxEditRepositoryEditor, cxExtEditConsts, cxShellBrowserDialog, cxShellComboBox, cxShellCommon, cxShellEditRepositoryItems, cxShellListView, cxShellTreeView, cxLookAndFeels, AdoConEd, ADODB, TypInfo, DBCommon, ColnEdit; const cxShellBrowserEditorVerb = 'Test Browser...'; dxdbcVersion = '1.52'; dxotcVersion = '1.52'; type { TcxShellBrowserEditor } TcxShellBrowserEditor = class(TcxEditorsLibraryComponentEditorEx) protected function GetEditItemCaption: string; override; procedure ExecuteEditAction; override; public procedure ExecuteVerb(Index: Integer); override; end; TFieldProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; TdxDBOrgChartEditor = class(TComponentEditor) function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TdxOrgChartEditor = class(TComponentEditor) procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; { TADOConnectionEditor } { TADOConnectionEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; { TCommandTextProperty } { TCommandTextProperty = class(TDBStringProperty) private FCommandType: TCommandType; FConnection: TADOConnection; public procedure Activate; override; function AutoFill: Boolean; override; procedure Edit; override; procedure EditSQLText; virtual; function GetAttributes: TPropertyAttributes; override; function GetConnection(Opened: Boolean): TADOConnection; procedure GetValueList(List: TStrings); override; property CommandType: TCommandType read FCommandType write FCommandType; end; { TTableNameProperty } { TTableNameProperty = class(TCommandTextProperty) public procedure Activate; override; end; { TProviderProperty } { TProviderProperty = class(TDBStringProperty) public procedure GetValueList(List: TStrings); override; end; { TConnectionStringProperty } { TConnectionStringProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; { TProcedureNameProperty } { TProcedureNameProperty = class(TCommandTextProperty) public procedure Activate; override; end; { TParametersProperty } { TParametersProperty = class(TCollectionProperty) public procedure Edit; override; end; { TADOIndexNameProperty } { TADOIndexNameProperty = class(TDBStringProperty) public procedure GetValueList(List: TStrings); override; end; } implementation uses Dialogs, Consts, DsnDBCst; function EditFileName(ADataSet: TADODataSet; LoadData: Boolean): Boolean; begin with TOpenDialog.Create(nil) do try Title := sOpenFileTitle; DefaultExt := 'adtg'; Filter := SADODataFilter; Result := Execute; if Result then if LoadData then ADataSet.LoadFromFile(FileName) else ADataSet.CommandText := FileName; finally Free; end; end; function TFieldProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect,paValueList,paSortList]; end; procedure TFieldProperty.GetValues(Proc: TGetStrProc); var Table: TDataSet; List: TStringList; I: Integer; begin Table := (GetComponent(0) as TdxDbOrgChart).DataSet; if Table=nil then Exit; List := TStringList.Create; Table.GetFieldNames(List); for I:=0 to List.Count-1 do Proc(List[I]); List.Free; end; function TdxDBOrgChartEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'ExpressDBOrgChart ' + dxdbcVersion; 1: Result := 'Developer Express Inc.'; end; end; function TdxDBOrgChartEditor.GetVerbCount: Integer; begin Result := 2; end; { TcxShellBrowserEditor } procedure TcxShellBrowserEditor.ExecuteVerb(Index: Integer); begin if Index = 4 then ShellExecute(0, 'OPEN', 'http://www.devexpress.com', nil, nil, SW_SHOWMAXIMIZED) else inherited ExecuteVerb(Index); end; function TcxShellBrowserEditor.GetEditItemCaption: string; begin Result := cxShellBrowserEditorVerb; end; procedure TcxShellBrowserEditor.ExecuteEditAction; var ADialog: TcxShellBrowserDialog; begin ADialog := Component as TcxShellBrowserDialog; with TcxShellBrowserDialog.Create(Application) do try if Length(ADialog.Title) > 0 then Title := ADialog.Title; if Length(ADialog.FolderLabelCaption) > 0 then FolderLabelCaption := ADialog.FolderLabelCaption; Options.ShowFolders := ADialog.Options.ShowFolders; Options.ShowToolTip := ADialog.Options.ShowToolTip; Options.TrackShellChanges := ADialog.Options.TrackShellChanges; Options.ContextMenus := ADialog.Options.ContextMenus; Options.ShowNonFolders := ADialog.Options.ShowNonFolders; Options.ShowHidden := ADialog.Options.ShowHidden; Root.BrowseFolder := ADialog.Root.BrowseFolder; Root.CustomPath := ADialog.Root.CustomPath; LookAndFeel.Kind := ADialog.LookAndFeel.Kind; LookAndFeel.NativeStyle := ADialog.LookAndFeel.NativeStyle; LookAndFeel.SkinName := ADialog.LookAndFeel.SkinName; ShowButtons := ADialog.ShowButtons; ShowInfoTips := ADialog.ShowInfoTips; ShowLines := ADialog.ShowLines; ShowRoot := ADialog.ShowRoot; Path := ADialog.Path; Execute; finally Free; end; end; procedure TdxOrgChartEditor.ExecuteVerb(Index: Integer); begin case Index of 0: if ShowOrgChartEditor(TdxOrgChart(Component)) then Designer.Modified; end; end; function TdxOrgChartEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Items Editor...'; 1: Result := '-'; 2: Result := 'ExpressOrgChart ' + dxotcVersion; 3: Result := 'Developer Express Inc.'; end; end; function TdxOrgChartEditor.GetVerbCount: Integer; begin Result := 4; end; { TADOConnectionEditor } {procedure TADOConnectionEditor.ExecuteVerb(Index: Integer); var I: Integer; begin I := inherited GetVerbCount; if Index < I then inherited else begin case Index - I of 0: if EditConnectionString(Component) then Designer.Modified; end; end; end; function TADOConnectionEditor.GetVerb(Index: Integer): string; var I: Integer; begin I := inherited GetVerbCount; if Index < I then Result := inherited GetVerb(Index) else case Index - I of 0: Result := 'Á¬½ÓÊý¾Ý¿â'; end; end; function TADOConnectionEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount + 1; end; { TTableNameProperty } {procedure TTableNameProperty.Activate; begin CommandType := cmdTable; end; { TCommandTextProperty } {function TCommandTextProperty.GetAttributes: TPropertyAttributes; begin if CommandType in [cmdTable, cmdTableDirect, cmdStoredProc] then Result := [paValueList, paSortList, paMultiSelect] else {Drop down list for name list} { Result := [paMultiSelect, paRevertable, paDialog]; {SQL or File} {end; procedure TCommandTextProperty.Activate; var PropInfo: PPropInfo; Component: TComponent; begin Component := GetComponent(0) as TComponent; PropInfo := TypInfo.GetPropInfo(Component.ClassInfo, 'CommandType'); { do not localize } { if Assigned(PropInfo) then CommandType := TCommandType(GetOrdProp(Component, PropInfo)) else CommandType := cmdText; end; procedure TCommandTextProperty.EditSQLText; var Command: string; Connection: TADOConnection; TableName: string; begin if paDialog in GetAttributes then begin Command := GetStrValue; Connection := GetConnection(True); try if Command <> '' then TableName := GetTableNameFromSQL(Command); if EditSQL(Command, Connection.GetTableNames, Connection.GetFieldNames, TableName) then SetStrValue(Command); finally FConnection.Free; FConnection := nil; end; end; end; procedure TCommandTextProperty.Edit; begin case CommandType of cmdText, cmdUnknown: EditSQLText; cmdFile: EditFileName(GetComponent(0) as TADODataSet, False); else inherited; end; end; function TCommandTextProperty.GetConnection(Opened: Boolean): TADOConnection; var Component: TComponent; ConnectionString: string; begin Component := GetComponent(0) as TComponent; Result := TObject(GetOrdProp(Component, TypInfo.GetPropInfo(Component.ClassInfo, 'Connection'))) as TADOConnection; { do not localize } { if not Opened then Exit; if not Assigned(Result) then begin ConnectionString := TypInfo.GetStrProp(Component, TypInfo.GetPropInfo(Component.ClassInfo, 'ConnectionString')); { do not localize } { if ConnectionString = '' then Exit; FConnection := TADOConnection.Create(nil); FConnection.ConnectionString := ConnectionString; FConnection.LoginPrompt := False; Result := FConnection; end; Result.Open; end; procedure TCommandTextProperty.GetValueList(List: TStrings); var Connection: TADOConnection; begin Connection := GetConnection(True); if Assigned(Connection) then try case CommandType of cmdTable, cmdTableDirect: Connection.GetTableNames(List); cmdStoredProc: Connection.GetProcedureNames(List); end; finally FConnection.Free; FConnection := nil; end; end; function TCommandTextProperty.AutoFill: Boolean; var Connection: TADOConnection; begin Connection := GetConnection(False); Result := Assigned(Connection) and Connection.Connected; end; { TConnectionStringProperty } {function TConnectionStringProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; procedure TConnectionStringProperty.Edit; begin if EditConnectionString(GetComponent(0) as TComponent) then Modified; end; { TProviderProperty } {procedure TProviderProperty.GetValueList(List: TStrings); begin GetProviderNames(List); end; { TProcedureNameProperty } {procedure TProcedureNameProperty.Activate; begin CommandType := cmdStoredProc; end; { TParametersProperty } {procedure TParametersProperty.Edit; var Parameters: TParameters; begin try Parameters := TParameters(GetOrdValue); if Parameters.Count = 0 then Parameters.Refresh; except { Ignore any error when trying to refresh the params } { end; inherited Edit; end; { TADOIndexNameProperty } {procedure TADOIndexNameProperty.GetValueList(List: TStrings); var IndexDefs: TIndexDefs; begin if GetComponent(0) is TADODataSet then IndexDefs := TADODataSet(GetComponent(0)).IndexDefs else IndexDefs := TADOTable(GetComponent(0)).IndexDefs; IndexDefs.Updated := False; IndexDefs.Update; IndexDefs.GetItemNames(List); end; } end.
unit uAbout; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, xFunction, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation; type TfAbout = class(TForm) img1: TImage; lstInfo: TListBox; btnClose: TButton; lblNumbers: TLabel; lblName: TLabel; pnl1: TPanel; imgMoreInfo: TImage; pnlCode: TPanel; lbl3: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } /// <summary> /// 版权信息 /// </summary> /// <param name="FormYear">版权起始年份,如1998</param> /// <param name="ToYear">版权终止年份,如2000</param> procedure SetCopyRight(FromYear: string; ToYear: string = ''); /// <summary> /// 设置公司名称 /// </summary> procedure SetCompanyName(sName: string); /// <summary> /// 设置公司网址 /// </summary> procedure SetWebSite(aWebSite: string); /// <summary> /// 导入图片 /// </summary> /// <param name="sPicName">图片的完整名称,包括完整路径和扩展名,大小为470x130</param> procedure LoadPicture(sPicName: string); /// <summary> /// 添加显示版本信息 /// </summary> procedure SetVersion(sFileName: string); /// <summary> /// 添加字符串信息 /// </summary> procedure AddStrInfo(sStr : string); /// <summary> /// 显示版本信息 /// </summary> /// <param name="sModel">型号 如CKM-S21</param> /// <param name="sName">程序全名 如10/0.4KV 配电仿真系统</param> procedure ShowAboutInfo( sModel, sName : string; aFontColor: TAlphaColor = TAlphaColorRec.White ); /// <summary> /// 显示二维码信息 /// </summary> procedure ShowCode2(sFileName : string); end; var fAbout: TfAbout; implementation {$R *.fmx} { TForm2 } procedure TfAbout.SetVersion(sFileName: string); begin lstInfo.Items.Add('版本:' + GetFileVersion); end; procedure TfAbout.AddStrInfo(sStr: string); begin if sStr <> '' then lstInfo.Items.Add(sStr); end; procedure TfAbout.FormCreate(Sender: TObject); begin inherited; lstInfo.Items.Clear; end; procedure TfAbout.LoadPicture(sPicName: string); begin if FileExists( sPicName ) then img1.Bitmap.LoadFromFile(sPicName); end; procedure TfAbout.SetCompanyName(sName: string); begin if sName <> '' then lstInfo.Items.Add('公司:' + sName); end; procedure TfAbout.SetCopyRight(FromYear, ToYear: string); var sFrom, sTo : string; begin if FromYear = '' then sFrom := FormatDateTime('YYYY', Now) else sFrom := FromYear; if ToYear = '' then sTo := FormatDateTime('YYYY', Now) else sTo := ToYear; if sFrom = sTo then lstInfo.Items.Add('版权所有:'+ sFrom) else lstInfo.Items.Add('版权所有:'+ sFrom + ' - ' + sTo); end; procedure TfAbout.SetWebSite(aWebSite: string); begin if aWebSite <> '' then lstInfo.Items.Add('网址:' + aWebSite); end; procedure TfAbout.ShowAboutInfo(sModel, sName: string; aFontColor: TAlphaColor); begin lblNumbers.Text := sModel; lblName.Text := sName; lblNumbers.FontColor := aFontColor; lblName.FontColor := aFontColor; ShowModal; end; procedure TfAbout.ShowCode2(sFileName: string); begin pnlCode.Visible := FileExists(sFileName); if pnlCode.Visible then begin imgMoreInfo.Bitmap.LoadFromFile(sFileName); end; end; end.
unit Threads.Pool; interface uses Windows, Classes, GMGlobals, Generics.Collections, Threads.Base, GmSqlQuery, Threads.ReqSpecDevTemplate, SysUtils, GMConst, GM485; type TMultiObjectRequestThread = class(TGMThread) private FThreadPool: TGMThreadPool<TRequestSpecDevices>; procedure UpdateOneObjectThread(q: TGMSqlQuery; obj: pointer); procedure DropOddThreads; procedure DropUpdateFlag; procedure AddMissingThreads; function CreateRequestThread(objType, id_obj: int): TRequestSpecDevices; function CheckOutputChannelIds(id_prm: int; channelIds: TChannelIds): bool; function SendRemoteCommand(ID_Prm: int; value: double; const userName: string = ''): bool; function SetChannelValue_Geomer(channelIds: TChannelIds; fVal: double; TimeHold: UINT; const userName: string = ''): bool; procedure DropStoppedThreads; protected procedure SafeExecute(); override; procedure UpdateThreadList; virtual; property ThreadPool: TGMThreadPool<TRequestSpecDevices> read FThreadPool; public constructor Create(); destructor Destroy(); override; function SetChannelValue(id_prm: int; Val: double; timeHold: int = 0; age: int = -1): bool; function FindThread(objType, ID_Obj: int): TRequestSpecDevices; end; implementation uses Threads.GMCOM, Threads.TCP, Threads.GMK104, Threads.MainSrvDataPicker, UsefulQueries, GMSocket, ProgramLogFile, System.StrUtils; { TMultiObjectRequestThread } const THREAD_TAG_UP_TO_DATE = 0; THREAD_TAG_ODD = 1; constructor TMultiObjectRequestThread.Create(); begin inherited Create(); FThreadPool := TGMThreadPool<TRequestSpecDevices>.Create(); end; destructor TMultiObjectRequestThread.Destroy; begin FThreadPool.Free(); inherited; end; function TMultiObjectRequestThread.CreateRequestThread(objType, id_obj: int): TRequestSpecDevices; begin case objType of OBJ_TYPE_COM: Result := TRequestCOMDevices.Create(id_obj); OBJ_TYPE_TCP: Result := TRequestTCPDevices.Create(id_obj); OBJ_TYPE_K104: Result := TRequestK104Devices.Create(id_obj); OBJ_TYPE_REMOTE_MAIN: Result := TMainSrvDataPicker.Create(id_obj); else Result := nil; end; if Result <> nil then FThreadPool.Add(Result); end; procedure TMultiObjectRequestThread.UpdateOneObjectThread(q: TGMSqlQuery; obj: pointer); var thr: TGMThread; id_obj: int; objType: int; begin id_obj := q.FieldByName('ID_Obj').AsInteger; objType := q.FieldByName('ObjType').AsInteger; thr := FindThread(objType, id_obj); if thr = nil then thr := CreateRequestThread(objType, id_obj); if thr <> nil then thr.Tag := THREAD_TAG_UP_TO_DATE; end; procedure TMultiObjectRequestThread.AddMissingThreads(); begin ReadFromQuery('select * from Objects', UpdateOneObjectThread); end; procedure TMultiObjectRequestThread.DropUpdateFlag(); var thr: TGMThread; begin for thr in FThreadPool do thr.Tag := THREAD_TAG_ODD; end; procedure TMultiObjectRequestThread.DropOddThreads(); var i: int; begin for i := FThreadPool.Count - 1 downto 0 do if FThreadPool[i].Tag = THREAD_TAG_ODD then FThreadPool.DropThread(i); end; procedure TMultiObjectRequestThread.DropStoppedThreads(); var i: int; begin for i := FThreadPool.Count - 1 downto 0 do if FThreadPool[i].Finished then FThreadPool.DropThread(i); end; procedure TMultiObjectRequestThread.UpdateThreadList(); begin DropUpdateFlag(); DropStoppedThreads(); AddMissingThreads(); DropOddThreads(); end; procedure TMultiObjectRequestThread.SafeExecute; begin while not Terminated do begin UpdateThreadList(); SleepThread(5000); end; FThreadPool.Terminate(); FThreadPool.WaitFor(); end; function TMultiObjectRequestThread.FindThread(objType, ID_Obj: int): TRequestSpecDevices; var thr: TRequestSpecDevices; begin Result := nil; for thr in FThreadPool do if (thr.ObjType = objType) and (thr.ID_Obj = ID_Obj) then begin Result := thr; Exit; end; end; function TMultiObjectRequestThread.CheckOutputChannelIds(id_prm: int; channelIds: TChannelIds): bool; begin // id_prm передается на случай, когда канал не найден. Тогда channelIds.ID_Prm не информативен Result := false; if channelIds.ID_Prm <= 0 then ProgramLog.AddError(Format('SetChannelValue ID_Prm = %d not found', [id_prm])) else if not (channelIds.RealSrc() in OutputParamTypes) then ProgramLog.AddError(Format('SetChannelValue ID_Prm = %d type mismatch', [id_prm])) else Result := true; end; function TMultiObjectRequestThread.SendRemoteCommand(ID_Prm: int; value: double; const userName: string = ''): bool; begin try SQLReq_SetChannel(ID_Prm, value, userName); ProgramLog.AddMessage(Format('SetOutputParam ID_Prm = %d to remote queue', [id_prm])); Result := true; except on e: Exception do begin Result := false; ProgramLog.AddException('SetOutputParam ID_Prm = %d sql error'); end; end; end; function TMultiObjectRequestThread.SetChannelValue_Geomer(channelIds: TChannelIds; fVal: double; TimeHold: UINT; const userName: string = ''): bool; var Sckt: TGeomerSocket; begin Sckt := lstSockets.SocketByIdObj(channelIds.ID_Obj); if Sckt = nil then begin ProgramLog.AddError(Format('SetOutputParam ID_Prm = %d Line not found', [channelIds.ID_Prm])); Exit(false); end; SQLReq_SetChannel(channelIds.ID_Prm, fVal, userName, TimeHold); { Sckt.Geomer_SetOutputChannel(channelIds.N_Src, fVal, TimeHold); Sckt.RequestInfo0(2); ProgramLog.AddMessage(Format('SetOutputParam ID_Prm = %d done', [channelIds.ID_Prm])); } Result := true; end; function TMultiObjectRequestThread.SetChannelValue(id_prm: int; Val: double; timeHold: int = 0; age: int = -1): bool; var channelIds: TChannelIds; sql: string; res: ArrayOfString; N_Src_Age: int; id_prm_age: int; begin Result := false; channelIds := LoadChannelIds(id_prm); if not CheckOutputChannelIds(id_prm, channelIds) then Exit; sql := Format('select BaudRate, RemoteSrv, RemotePort, AgeAddr from DeviceSystem where ID_Prm = %d', [id_prm]); res := QueryResultArray_FirstRow(sql); if Length(res) < 4 then Exit; if channelIds.RemoteName <> '' then Exit(SendRemoteCommand(channelIds.ID_Prm, Val)); if (channelIds.ObjType = OBJ_TYPE_GM) and (channelIds.ID_DevType in GeomerFamily) then // Геомер - особый случай Exit(SetChannelValue_Geomer(channelIds, Val, TimeHold)); Result := true; SQLReq_SetChannel(channelIds.ID_Prm, Val, '', TimeHold); N_Src_Age := StrToIntDef(res[3], -1); if (age < 0) or (N_Src_Age <= 0) then Exit; id_prm_age := StrToIntDef( QueryResultFmt('select ID_Prm from Params where ID_Device = %d and PrmRealSrc(ID_Prm) = %d and %d in (N_Src, CurrentsAddr) limit 1', [channelIds.ID_Device, SRC_AO, N_Src_Age]), 0); if id_prm_age > 0 then SQLReq_SetChannel(id_prm_age, age); end; end.
PROGRAM ListRec; TYPE ListNodePtr = ^ListNode; ListNode = RECORD val: integer; next: ListNodePtr; END; List = ListNodePtr; PROCEDURE AppendRec(var l: List; n: ListNodePtr); BEGIN (* AppendRec *) if l = NIL then l := n else AppendRec(l^.next, n); END; (* AppendRec *) BEGIN (* ListRec *) END. (* ListRec *)
unit PascalCoin.URI; interface uses PascalCoin.Utils.Interfaces; type TPascalCoinURI = class(TInterfacedObject, IPascalCoinURI) private FAccountNumber: String; FAmount: Currency; FPayload: string; FPayloadEncode: TPayloadEncode; FPayloadEncrypt: TPayloadEncryption; FPassword: string; protected function GetAccountNumber: string; procedure SetAccountNumber(const Value: string); function GetAmount: Currency; procedure SetAmount(const Value: Currency); function GetPayload: string; procedure SetPayload(const Value: string); function GetPayLoadEncode: TPayloadEncode; procedure SetPayloadEncode(const Value: TPayloadEncode); function GetPayloadEncrypt: TPayloadEncryption; procedure SetPayloadEncrypt(const Value: TPayloadEncryption); function GetPassword: string; procedure SetPassword(const Value: string); function GetURI: string; procedure SetURI(const Value: string); end; implementation uses System.SysUtils; { TPascalCoinURI } function TPascalCoinURI.GetAccountNumber: string; begin result := FAccountNumber; end; function TPascalCoinURI.GetAmount: Currency; begin result := FAmount; end; function TPascalCoinURI.GetPassword: string; begin result := FPassword; end; function TPascalCoinURI.GetPayload: string; begin result := FPayload; end; function TPascalCoinURI.GetPayLoadEncode: TPayloadEncode; begin result := FPayloadEncode; end; function TPascalCoinURI.GetPayloadEncrypt: TPayloadEncryption; begin result := FPayloadEncrypt; end; function TPascalCoinURI.GetURI: string; begin result := 'pasc://pay?account' + FAccountNumber; if FAmount > 0 then result := result + '&amount=' + CurrToStrF(FAmount, ffCurrency, 4); if FPayload = '' then Exit; result := result + '&payload=' + FPayload + '&payloadencode=' + PayloadEncodeCode[FPayloadEncode] + '&payloadencryption=' + PayloadEncryptionCode[FPayloadEncrypt]; if FPayloadEncrypt = TPayloadEncryption.Password then result := result + '&password=' + FPassword; end; procedure TPascalCoinURI.SetAccountNumber(const Value: string); begin FAccountNumber := Value; end; procedure TPascalCoinURI.SetAmount(const Value: Currency); begin FAmount := Value; end; procedure TPascalCoinURI.SetPassword(const Value: string); begin FPassword := Value; end; procedure TPascalCoinURI.SetPayload(const Value: string); begin FPayload := Value; end; procedure TPascalCoinURI.SetPayloadEncode(const Value: TPayloadEncode); begin FPayloadEncode := Value; end; procedure TPascalCoinURI.SetPayloadEncrypt(const Value: TPayloadEncryption); begin FPayloadEncrypt := Value; end; procedure TPascalCoinURI.SetURI(const Value: string); begin end; end.
unit BrickCamp.TService; interface uses MARS.Core.Engine, MARS.http.Server.Indy, MARS.Core.Application, BrickCamp.IService; type TCbdService = class(TInterfacedObject, IBrickCampService) private FEngine: TMARSEngine; FServer: TMARShttpServerIndy; procedure RegisterClasses; procedure InitLogger; procedure InitREST; function GetLoggerFileName: string; public destructor Destroy; override; procedure Run; end; implementation uses System.SysUtils, System.Classes, Spring.Container, Spring.Logging, Spring.Logging.Loggers, Spring.Logging.Controller, Spring.Logging.Appenders, Spring.Logging.Configuration, MARS.Utils.Parameters.IniFile, BrickCamp.TSettings, BrickCamp.TDB, BrickCamp.services, BrickCamp.Resources.TEmployee, BrickCamp.Model.TEmployee, BrickCamp.Repositories.TEmployee, BrickCamp.Repositories.TProduct, BrickCamp.Resources.TProduct, BrickCamp.Model.TProduct, BrickCamp.Repositories.TAnswer, BrickCamp.Resources.TAnswer, BrickCamp.Model.TAnswer, BrickCamp.Repositories.TUser, BrickCamp.Resources.TUser, BrickCamp.Model.TUser, BrickCamp.Repositories.TQuestion, BrickCamp.Resources.TQuestion, BrickCamp.Model.TQuestion, Brickcamp.Repository.Redis ; { TCbdService } destructor TCbdService.Destroy; begin FServer.Free; FEngine.Free; inherited; end; function TCbdService.GetLoggerFileName: string; var FileNameFormat: TFormatSettings; LogDir: string; begin FileNameFormat := TFormatSettings.Create; FileNameFormat.TimeSeparator := '_'; FileNameFormat.DateSeparator := '-'; FileNameFormat.LongDateFormat := 'DD-MM-yy'; FileNameFormat.LongTimeFormat := 'HH_MM_SS'; FileNameFormat.ShortDateFormat := 'DD-MM-yy'; LogDir := ExtractFilePath(ParamStr(0)) + 'logs\'; ForceDirectories(LogDir); Result := LogDir + Format('logger-%s.log', [DateTimeToStr(Now, FileNameFormat)]); Result := LogDir + 'logger.log'; end; procedure TCbdService.InitLogger; var FileApp: TFileLogAppender; begin GlobalContainer.RegisterType<ILoggerController, TLoggerController>.AsSingleton; // GlobalContainer.RegisterType<TLoggingConfiguration>.Implements<TLoggingConfiguration>.AsSingleton; GlobalContainer.RegisterType<Spring.Logging.ILogger, Spring.Logging.Loggers.TLogger>.AsSingleton.AsDefault; GlobalContainer.Build; FileApp := TFileLogAppender.Create; FileApp.FileName := GetLoggerFileName; FileApp.Levels := LOG_ALL_LEVELS; FileApp.EntryTypes := LOG_ALL_ENTRY_TYPES; FileApp.Enabled := True; GlobalContainer.Resolve<Spring.Logging.ILoggerController>.AddAppender(FileApp); TLoggerController(GlobalContainer.Resolve<Spring.Logging.ILoggerController>).EntryTypes := LOG_ALL_ENTRY_TYPES; TLoggerController(GlobalContainer.Resolve<Spring.Logging.ILoggerController>).Levels := LOG_ALL_LEVELS; Spring.Logging.Loggers.TLogger(CbLog).Levels := LOG_ALL_LEVELS; Spring.Logging.Loggers.TLogger(CbLog).Enabled := True; Spring.Logging.Loggers.TLogger(CbLog).EntryTypes := LOG_ALL_ENTRY_TYPES; end; procedure TCbdService.InitREST; begin // MARS-Curiosity Engine FEngine := TMARSEngine.Create; try FEngine.Parameters.LoadFromIniFile; FEngine.AddApplication('DefaultApp', '/cb', ['BrickCamp.Resources.*']); // http server implementation FServer := TMARShttpServerIndy.Create(FEngine); try FServer.Active := True; except FServer.Free; raise; end; except FEngine.Free; raise; end; end; procedure TCbdService.RegisterClasses; begin GlobalContainer.RegisterType<TCbdSettings>; GlobalContainer.RegisterType<TCbdDB>; GlobalContainer.RegisterType<TEmployeeResource>; GlobalContainer.RegisterType<TEmployee>; GlobalContainer.RegisterType<TEmployeeRepository>; GlobalContainer.RegisterType<TProductResource>; GlobalContainer.RegisterType<TProduct>; GlobalContainer.RegisterType<TProductRepository>; GlobalContainer.RegisterType<TAnswerResource>; GlobalContainer.RegisterType<TAnswer>; GlobalContainer.RegisterType<TAnswerRepository>; GlobalContainer.RegisterType<TUserResource>; GlobalContainer.RegisterType<TUser>; GlobalContainer.RegisterType<TUserRepository>; GlobalContainer.RegisterType<TQuestionResource>; GlobalContainer.RegisterType<TQuestion>; GlobalContainer.RegisterType<TQuestionRepository>; GlobalContainer.RegisterType<TMARSEngine>; GlobalContainer.RegisterType<TMARShttpServerIndy>; GlobalContainer.RegisterType<TRedisClientProvider>; GlobalContainer.RegisterType<TRedisRepository>; GlobalContainer.Build; end; procedure TCbdService.Run; begin InitREST; InitLogger; RegisterClasses; end; end.
{ Map Viewer Download Engine for Synapse library Copyright (C) 2011 Maciej Kaczkowski / keit.co License: modified LGPL with linking exception (like RTL, FCL and LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL } unit mvDLESynapse; {$mode objfpc}{$H+} interface uses mvDownloadEngine, SysUtils, Classes, ssl_openssl, httpsend; type { TMvDESynapse } TMvDESynapse = class(TMvCustomDownloadEngine) private FProxyHost: string; FProxyPassword: string; FProxyPort: Integer; FProxyUsername: string; FUseProxy: Boolean; public procedure DownloadFile(const Url: string; str: TStream); override; published property UseProxy: Boolean read FUseProxy write FUseProxy default false; property ProxyHost: string read FProxyHost write FProxyHost; property ProxyPort: Integer read FProxyPort write FProxyPort default 0; property ProxyUsername: string read FProxyUsername write FProxyUsername; property ProxyPassword: string read FProxyPassword write FProxyPassword; end; procedure Register; implementation uses mvTypes; procedure Register; begin RegisterComponents(PALETTE_PAGE, [TMvDESynapse]); end; { TMvDESynapse } procedure TMvDESynapse.DownloadFile(const Url: string; str: TStream); var FHttp: THTTPSend; realURL: String; i: Integer; begin FHttp := THTTPSend.Create; try if FUseProxy then begin FHTTP.ProxyHost := FProxyHost; FHTTP.ProxyPort := IntToStr(FProxyPort); FHTTP.ProxyUser := FProxyUsername; FHTTP.ProxyPass := FProxyPassword; end; if FHTTP.HTTPMethod('GET', Url) then begin // If its a 301 or 302 we need to do more processing if (FHTTP.ResultCode = 301) or (FHTTP.ResultCode = 302) then begin // Check the headers for the Location header for i := 0 to FHTTP.Headers.Count -1 do begin // Extract the URL if Copy(FHTTP.Headers[i], 1, 8) = 'Location' then realURL := copy(FHTTP.Headers[i], 11, Length(FHTTP.Headers[i]) - 10); //11); end; // If we have a URL, run it through the same function if Length(realURL) > 1 then DownloadFile(realURL, str); end else begin str.Seek(0, soFromBeginning); str.CopyFrom(FHTTP.Document, 0); str.Position := 0; end; end; finally FHttp.Free; end; end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.DAO.QueryGenerator Description : DAODatabase ADO Provider Author : Kike Pérez Version : 1.0 Created : 22/06/2018 Modified : 02/07/2019 This file is part of QuickDAO: https://github.com/exilon/QuickDAO *************************************************************************** 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 Quick.DAO.Factory.QueryGenerator; {$i QuickDAO.inc} interface uses System.SysUtils, Quick.DAO, Quick.DAO.QueryGenerator.MSSQL, Quick.DAO.QueryGenerator.MSAccess, Quick.DAO.QueryGenerator.SQLite, Quick.DAO.QueryGenerator.MySQL; type TDAOQueryGeneratorFactory = class public class function Create(aDBProvider : TDBProvider) : IDAOQueryGenerator; end; EDAOQueryGeneratorError = class(Exception); implementation { TDAOQueryGeneratorFactory } class function TDAOQueryGeneratorFactory.Create(aDBProvider : TDBProvider) : IDAOQueryGenerator; begin case aDBProvider of TDBProvider.daoMSAccess2000 : Result := TMSAccessQueryGenerator.Create; TDBProvider.daoMSAccess2007 : Result := TMSAccessQueryGenerator.Create; TDBProvider.daoMSSQL : Result := TMSSQLQueryGenerator.Create; TDBProvider.daoMySQL : Result := TMySQLQueryGenerator.Create; TDBProvider.daoSQLite : Result := TSQLiteQueryGenerator.Create; //TDAODBType.daoFirebase : Result := TFireBaseQueryGenerator.Create; else raise EDAOQueryGeneratorError.Create('No valid QueryGenerator provider specified!'); end; end; end.
{ (c) 2014 ti_dic@hotmail.com Parts of this component are based on : Map Viewer Copyright (C) 2011 Maciej Kaczkowski / keit.co License: modified LGPL with linking exception (like RTL, FCL and LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL } unit mvEngine; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IntfGraphics, Controls, mvTypes, mvJobQueue, mvMapProvider, mvDownloadEngine, mvCache, mvDragObj; const EARTH_RADIUS = 6378137; MIN_LATITUDE = -85.05112878; MAX_LATITUDE = 85.05112878; MIN_LONGITUDE = -180; MAX_LONGITUDE = 180; SHIFT = 2 * pi * EARTH_RADIUS / 2.0; Type TDrawTileEvent = Procedure (const TileId: TTileId; X,Y: integer; TileImg: TLazIntfImage) of object; TTileIdArray = Array of TTileId; TDistanceUnits = (duMeters, duKilometers, duMiles); { TMapWindow } TMapWindow = Record MapProvider: TMapProvider; X: Int64; Y: Int64; Center: TRealPoint; Zoom: integer; Height: integer; Width: integer; end; { TMapViewerEngine } TMapViewerEngine = Class(TComponent) private DragObj : TDragObj; Cache : TPictureCache; FActive: boolean; FDownloadEngine: TMvCustomDownloadEngine; FDrawTitleInGuiThread: boolean; FOnCenterMove: TNotifyEvent; FOnChange: TNotifyEvent; FOnDrawTile: TDrawTileEvent; FOnZoomChange: TNotifyEvent; lstProvider : TStringList; Queue : TJobQueue; MapWin : TMapWindow; function GetCacheOnDisk: Boolean; function GetCachePath: String; function GetCenter: TRealPoint; function GetHeight: integer; function GetMapProvider: String; function GetUseThreads: Boolean; function GetWidth: integer; function GetZoom: integer; function IsValidTile(const aWin: TMapWindow; const aTile: TTIleId): boolean; procedure MoveMapCenter(Sender: TDragObj); procedure SetActive(AValue: boolean); procedure SetCacheOnDisk(AValue: Boolean); procedure SetCachePath(AValue: String); procedure SetCenter(aCenter: TRealPoint); procedure SetDownloadEngine(AValue: TMvCustomDownloadEngine); procedure SetHeight(AValue: integer); procedure SetMapProvider(AValue: String); procedure SetUseThreads(AValue: Boolean); procedure SetWidth(AValue: integer); procedure SetZoom(AValue: integer); function LonLatToMapWin(const aWin: TMapWindow; aPt: TRealPoint): TPoint; Function MapWinToLonLat(const aWin: TMapWindow; aPt : TPoint) : TRealPoint; Procedure CalculateWin(var aWin: TMapWindow); Procedure Redraw(const aWin: TmapWindow); function CalculateVisibleTiles(const aWin: TMapWindow) : TArea; function IsCurrentWin(const aWin: TMapWindow) : boolean; protected procedure ConstraintZoom(var aWin: TMapWindow); function GetTileName(const Id: TTileId): String; procedure evDownload(Data: TObject; Job: TJob); procedure TileDownloaded(Data: PtrInt); Procedure DrawTile(const TileId: TTileId; X,Y: integer; TileImg: TLazIntfImage); Procedure DoDrag(Sender: TDragObj); public constructor Create(aOwner: TComponent); override; destructor Destroy; override; function AddMapProvider(OpeName: String; Url: String; MinZoom, MaxZoom, NbSvr: integer; GetSvrStr: TGetSvrStr = nil; GetXStr: TGetValStr = nil; GetYStr: TGetValStr = nil; GetZStr: TGetValStr = nil): TMapProvider; procedure CancelCurrentDrawing; procedure ClearMapProviders; procedure GetMapProviders(AList: TStrings); function LonLatToScreen(aPt: TRealPoint): TPoint; function LonLatToWorldScreen(aPt: TRealPoint): TPoint; function ReadProvidersFromXML(AFileName: String; out AMsg: String): Boolean; procedure Redraw; Procedure RegisterProviders; function ScreenToLonLat(aPt: TPoint): TRealPoint; procedure SetSize(aWidth, aHeight: integer); function WorldScreenToLonLat(aPt: TPoint): TRealPoint; procedure WriteProvidersToXML(AFileName: String); procedure DblClick(Sender: TObject); procedure MouseDown(Sender: TObject; Button: TMouseButton; {%H-}Shift: TShiftState; X, Y: Integer); procedure MouseMove(Sender: TObject; {%H-}Shift: TShiftState; X, Y: Integer); procedure MouseUp(Sender: TObject; Button: TMouseButton; {%H-}Shift: TShiftState; X, Y: Integer); procedure MouseWheel(Sender: TObject; {%H-}Shift: TShiftState; WheelDelta: Integer; {%H-}MousePos: TPoint; var Handled: Boolean); procedure ZoomOnArea(const aArea: TRealArea); property Center: TRealPoint read GetCenter write SetCenter; published property Active: Boolean read FActive write SetActive default false; property CacheOnDisk: Boolean read GetCacheOnDisk write SetCacheOnDisk; property CachePath: String read GetCachePath write SetCachePath; property DownloadEngine: TMvCustomDownloadEngine read FDownloadEngine write SetDownloadEngine; property DrawTitleInGuiThread: boolean read FDrawTitleInGuiThread write FDrawTitleInGuiThread; property Height: integer read GetHeight write SetHeight; property JobQueue: TJobQueue read Queue; property MapProvider: String read GetMapProvider write SetMapProvider; property UseThreads: Boolean read GetUseThreads write SetUseThreads; property Width: integer read GetWidth write SetWidth; property Zoom: integer read GetZoom write SetZoom; property OnCenterMove: TNotifyEvent read FOnCenterMove write FOnCenterMove; property OnChange: TNotifyEvent Read FOnChange write FOnchange; //called when visiable area change property OnDrawTile: TDrawTileEvent read FOnDrawTile write FOnDrawTile; property OnZoomChange: TNotifyEvent read FOnZoomChange write FOnZoomChange; end; function CalcGeoDistance(Lat1, Lon1, Lat2, Lon2: double; AUnits: TDistanceUnits = duKilometers): double; function GPSToDMS(Angle: Double): string; function LatToStr(ALatitude: Double; DMS: Boolean): String; function LonToStr(ALongitude: Double; DMS: Boolean): String; function TryStrToGps(const AValue: String; out ADeg: Double): Boolean; procedure SplitGps(AValue: Double; out ADegs, AMins, ASecs: Double); var HERE_AppID: String = ''; HERE_AppCode: String = ''; OpenWeatherMap_ApiKey: String = ''; implementation uses Math, Forms, laz2_xmlread, laz2_xmlwrite, laz2_dom, mvJobs, mvGpsObj; type { TLaunchDownloadJob } TLaunchDownloadJob = class(TJob) private AllRun: boolean; Win: TMapWindow; Engine: TMapViewerEngine; FRunning: boolean; FTiles: TTileIdArray; FStates: Array of integer; protected function pGetTask: integer; override; procedure pTaskStarted(aTask: integer); override; procedure pTaskEnded(aTask: integer; aExcept: Exception); override; public procedure ExecuteTask(aTask: integer; FromWaiting: boolean); override; function Running: boolean; override; public constructor Create(Eng: TMapViewerEngine; const Tiles: TTileIdArray; const aWin: TMapWindow); end; { TEnvTile } TEnvTile = Class(TBaseTile) private Tile: TTileId; Win: TMapWindow; public constructor Create(const aTile: TTileId; const aWin: TMapWindow);reintroduce; end; { TMemObj } TMemObj = Class private FWin: TMapWindow; public constructor Create(const aWin: TMapWindow); end; constructor TMemObj.Create(const aWin: TMapWindow); begin FWin := aWin; end; { TLaunchDownloadJob } function TLaunchDownloadJob.pGetTask: integer; var i: integer; begin if not AllRun and not Cancelled then begin for i:=Low(FStates) to High(FStates) do if FStates[i] = 0 then begin Result := i + 1; Exit; end; AllRun := True; end; Result := ALL_TASK_COMPLETED; for i := Low(FStates) to High(FStates) do if FStates[i] = 1 then begin Result := NO_MORE_TASK; Exit; end; end; procedure TLaunchDownloadJob.pTaskStarted(aTask: integer); begin FRunning := True; FStates[aTask-1] := 1; end; procedure TLaunchDownloadJob.pTaskEnded(aTask: integer; aExcept: Exception); begin if Assigned(aExcept) then FStates[aTask - 1] := 3 Else FStates[aTask - 1] := 2; end; procedure TLaunchDownloadJob.ExecuteTask(aTask: integer; FromWaiting: boolean); var iTile: integer; lJob: TEventJob; lTile: TEnvTile; begin iTile := aTask - 1; lTile:=TEnvTile.Create(FTiles[iTile], Win); lJob := TEventJob.Create ( @Engine.evDownload, lTile, false, // owns data Engine.GetTileName(FTiles[iTile]) ); if not Queue.AddUniqueJob(lJob , Launcher ) then begin FreeAndNil(lJob); FreeAndNil(lTile); end; end; function TLaunchDownloadJob.Running: boolean; begin Result := FRunning; end; constructor TLaunchDownloadJob.Create(Eng: TMapViewerEngine; const Tiles: TTileIdArray; const aWin: TMapWindow); var i: integer; begin Engine := Eng; SetLength(FTiles, Length(Tiles)); For i:=Low(FTiles) to High(FTiles) do FTiles[i] := Tiles[i]; SetLength(FStates, Length(Tiles)); AllRun := false; Name := 'LaunchDownload'; Win := aWin; end; { TEnvTile } constructor TEnvTile.Create(const aTile: TTileId; const aWin: TMapWindow); begin inherited Create(aWin.MapProvider); Tile := aTile; Win := aWin; end; { TMapViewerEngine } constructor TMapViewerEngine.Create(aOwner: TComponent); begin DrawTitleInGuiThread := true; DragObj := TDragObj.Create; DragObj.OnDrag := @DoDrag; Cache := TPictureCache.Create(self); lstProvider := TStringList.Create; RegisterProviders; Queue := TJobQueue.Create(8); Queue.OnIdle := @Cache.CheckCacheSize; inherited Create(aOwner); ConstraintZoom(MapWin); CalculateWin(mapWin); end; destructor TMapViewerEngine.Destroy; begin ClearMapProviders; FreeAndNil(DragObj); FreeAndNil(lstProvider); FreeAndNil(Cache); FreeAndNil(Queue); inherited Destroy; end; function TMapViewerEngine.AddMapProvider(OpeName: String; Url: String; MinZoom, MaxZoom, NbSvr: integer; GetSvrStr: TGetSvrStr; GetXStr: TGetValStr; GetYStr: TGetValStr; GetZStr: TGetValStr): TMapProvider; var idx :integer; Begin idx := lstProvider.IndexOf(OpeName); if idx = -1 then begin Result := TMapProvider.Create(OpeName); lstProvider.AddObject(OpeName, Result); end else Result := TMapProvider(lstProvider.Objects[idx]); Result.AddUrl(Url, NbSvr, MinZoom, MaxZoom, GetSvrStr, GetXStr, GetYStr, GetZStr); end; function TMapViewerEngine.CalculateVisibleTiles(const aWin: TMapWindow): TArea; var MaxX, MaxY, startX, startY: int64; begin MaxX := (Int64(aWin.Width) div TILE_SIZE) + 1; MaxY := (Int64(aWin.Height) div TILE_SIZE) + 1; startX := -aWin.X div TILE_SIZE; startY := -aWin.Y div TILE_SIZE; Result.Left := startX; Result.Right := startX + MaxX; Result.Top := startY; Result.Bottom := startY + MaxY; end; procedure TMapViewerEngine.CalculateWin(var aWin: TMapWindow); var mx, my: Extended; res: Extended; px, py: Int64; begin mx := aWin.Center.Lon * SHIFT / 180.0; my := ln( tan((90 - aWin.Center.Lat) * pi / 360.0 )) / (pi / 180.0); my := my * SHIFT / 180.0; res := (2 * pi * EARTH_RADIUS) / (TILE_SIZE * (1 shl aWin.Zoom)); px := Round((mx + shift) / res); py := Round((my + shift) / res); aWin.X := aWin.Width div 2 - px; aWin.Y := aWin.Height div 2 - py; end; procedure TMapViewerEngine.CancelCurrentDrawing; var Jobs: TJobArray; begin Jobs := Queue.CancelAllJob(self); Queue.WaitForTerminate(Jobs); end; procedure TMapViewerEngine.ClearMapProviders; var i: Integer; begin for i:=0 to lstProvider.Count-1 do TObject(lstProvider.Objects[i]).Free; lstProvider.Clear; end; procedure TMapViewerEngine.ConstraintZoom(var aWin: TMapWindow); var zMin, zMax: integer; begin if Assigned(aWin.MapProvider) then begin aWin.MapProvider.GetZoomInfos(zMin, zMax); if aWin.Zoom < zMin then aWin.Zoom := zMin; if aWin.Zoom > zMax then aWin.Zoom := zMax; end; end; procedure TMapViewerEngine.DblClick(Sender: TObject); var pt: TPoint; begin pt.X := DragObj.MouseX; pt.Y := DragObj.MouseY; SetCenter(ScreenToLonLat(pt)); end; procedure TMapViewerEngine.DoDrag(Sender: TDragObj); begin if Sender.DragSrc = self then MoveMapCenter(Sender); end; procedure TMapViewerEngine.DrawTile(const TileId: TTileId; X, Y: integer; TileImg: TLazIntfImage); begin if Assigned(FOnDrawTile) then FOnDrawTile(TileId, X, Y, TileImg); end; procedure TMapViewerEngine.evDownload(Data: TObject; Job: TJob); var Id: TTileId; Url: String; Env: TEnvTile; MapO: TMapProvider; lStream: TMemoryStream; begin Env := TEnvTile(Data); Id := Env.Tile; MapO := Env.Win.MapProvider; if Assigned(MapO) then begin if not Cache.InCache(MapO, Id) then begin if Assigned(FDownloadEngine) then begin Url := MapO.GetUrlForTile(Id); if Url <> '' then begin lStream := TMemoryStream.Create; try try FDownloadEngine.DownloadFile(Url, lStream); Cache.Add(MapO, Id, lStream); except end; finally FreeAndNil(lStream); end; end; end; end; end; if Job.Cancelled then Exit; if DrawTitleInGuiThread then Queue.QueueAsyncCall(@TileDownloaded, PtrInt(Env)) else TileDownloaded(PtrInt(Env)); end; function TMapViewerEngine.GetCacheOnDisk: Boolean; begin Result := Cache.UseDisk; end; function TMapViewerEngine.GetCachePath: String; begin Result := Cache.BasePath; end; function TMapViewerEngine.GetCenter: TRealPoint; begin Result := MapWin.Center; end; function TMapViewerEngine.GetHeight: integer; begin Result := MapWin.Height end; function TMapViewerEngine.GetMapProvider: String; begin if Assigned(MapWin.MapProvider) then Result := MapWin.MapProvider.Name else Result := ''; end; procedure TMapViewerEngine.GetMapProviders(AList: TStrings); begin AList.Assign(lstProvider); end; function TMapViewerEngine.GetTileName(const Id: TTileId): String; begin Result := IntToStr(Id.X) + '.' + IntToStr(Id.Y) + '.' + IntToStr(Id.Z); end; function TMapViewerEngine.GetUseThreads: Boolean; begin Result := Queue.UseThreads; end; function TMapViewerEngine.GetWidth: integer; begin Result := MapWin.Width; end; function TMapViewerEngine.GetZoom: integer; begin Result := MapWin.Zoom; end; function TMapViewerEngine.IsCurrentWin(const aWin: TMapWindow): boolean; begin Result := (aWin.Zoom = MapWin.Zoom) and (aWin.Center.Lat = MapWin.Center.Lat) and (aWin.Center.Lon = MapWin.Center.Lon) and (aWin.Width = MapWin.Width) and (aWin.Height = MapWin.Height); end; function TMapViewerEngine.IsValidTile(const aWin: TMapWindow; const aTile: TTileId): boolean; var tiles: int64; begin tiles := 1 shl aWin.Zoom; Result := (aTile.X >= 0) and (aTile.X <= tiles-1) and (aTile.Y >= 0) and (aTile.Y <= tiles-1); end; function TMapViewerEngine.LonLatToMapWin(const aWin: TMapWindow; aPt: TRealPoint): TPoint; var tiles: Int64; circumference: Int64; res: Extended; tmpX,tmpY : Double; begin tiles := 1 shl aWin.Zoom; circumference := tiles * TILE_SIZE; tmpX := ((aPt.Lon+ 180.0)*circumference)/360.0; res := (2 * pi * EARTH_RADIUS) / circumference; tmpY := -aPt.Lat; tmpY := ln(tan((degToRad(tmpY) + pi / 2.0) / 2)) *180 / pi; tmpY:= (((tmpY / 180.0) * SHIFT) + SHIFT) / res; tmpX := tmpX + aWin.X; tmpY := tmpY + aWin.Y; Result.X := trunc(tmpX); Result.Y := trunc(tmpY); end; function TMapViewerEngine.LonLatToScreen(aPt: TRealPoint): TPoint; Begin Result := LonLatToMapWin(MapWin, aPt); end; function TMapViewerEngine.LonLatToWorldScreen(aPt: TRealPoint): TPoint; begin Result := LonLatToScreen(aPt); Result.X := Result.X + MapWin.X; Result.Y := Result.Y + MapWin.Y; end; function TMapViewerEngine.MapWinToLonLat(const aWin: TMapWindow; aPt: TPoint): TRealPoint; var tiles: Int64; circumference: Int64; lat: Extended; res: Extended; mPoint : TPoint; begin tiles := 1 shl aWin.Zoom; circumference := tiles * TILE_SIZE; mPoint.X := aPt.X - aWin.X; mPoint.Y := aPt.Y - aWin.Y; if mPoint.X < 0 then mPoint.X := 0 else if mPoint.X > circumference then mPoint.X := circumference; if mPoint.Y < 0 then mPoint.Y := 0 else if mPoint.Y > circumference then mPoint.Y := circumference; Result.Lon := ((mPoint.X * 360.0) / circumference) - 180.0; res := (2 * pi * EARTH_RADIUS) / circumference; lat := ((mPoint.Y * res - SHIFT) / SHIFT) * 180.0; lat := radtodeg (2 * arctan( exp( lat * pi / 180.0)) - pi / 2.0); Result.Lat := -lat; if Result.Lat > MAX_LATITUDE then Result.Lat := MAX_LATITUDE else if Result.Lat < MIN_LATITUDE then Result.Lat := MIN_LATITUDE; if Result.Lon > MAX_LONGITUDE then Result.Lon := MAX_LONGITUDE else if Result.Lon < MIN_LONGITUDE then Result.Lon := MIN_LONGITUDE; end; procedure TMapViewerEngine.MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then DragObj.MouseDown(self,X,Y); end; procedure TMapViewerEngine.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin DragObj.MouseMove(X,Y); end; procedure TMapViewerEngine.MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then DragObj.MouseUp(X,Y); end; procedure TMapViewerEngine.MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); var Val: Integer; nZoom: integer; begin Val := 0; if WheelDelta > 0 then Val := 1; if WheelDelta < 0 then Val := -1; nZoom := Zoom + Val; if (nZoom > 0) and (nZoom < 20) then Zoom := nZoom; Handled := true; end; procedure TMapViewerEngine.MoveMapCenter(Sender: TDragObj); var old: TMemObj; nCenter: TRealPoint; aPt: TPoint; Begin if Sender.LnkObj = nil then Sender.LnkObj := TMemObj.Create(MapWin); old := TMemObj(Sender.LnkObj); aPt.X := old.FWin.Width DIV 2-Sender.OfsX; aPt.Y := old.FWin.Height DIV 2-Sender.OfsY; nCenter := MapWinToLonLat(old.FWin,aPt); SetCenter(nCenter); end; function TMapViewerEngine.ReadProvidersFromXML(AFileName: String; out AMsg: String): Boolean; function GetSvrStr(AName: String): TGetSvrStr; var lcName: String; begin lcName := LowerCase(AName); case lcName of 'letter': Result := @GetLetterSvr; 'yahoo': Result := @GetYahooSvr; else Result := nil; end; end; function GetValStr(AName: String): TGetValStr; var lcName: String; begin lcName := Lowercase(AName); case lcName of 'quadkey': Result := @GetQuadKey; 'yahooy': Result := @GetYahooY; 'yahooz': Result := @GetYahooZ; else Result := nil; end; end; function GetAttrValue(ANode: TDOMNode; AttrName: String): String; var node: TDOMNode; begin Result := ''; if ANode.HasAttributes then begin node := ANode.Attributes.GetNamedItem(AttrName); if Assigned(node) then Result := node.NodeValue; end; end; var stream: TFileStream; doc: TXMLDocument = nil; node, layerNode: TDOMNode; providerName: String; url: String; minZoom: Integer; maxZoom: Integer; svrCount: Integer; s: String; svrProc: String; xProc: String; yProc: String; zProc: String; first: Boolean; begin Result := false; AMsg := ''; stream := TFileStream.Create(AFileName, fmOpenread or fmShareDenyWrite); try ReadXMLFile(doc, stream, [xrfAllowSpecialCharsInAttributeValue, xrfAllowLowerThanInAttributeValue]); node := doc.FindNode('map_providers'); if node = nil then begin AMsg := 'No map providers in file.'; exit; end; first := true; node := node.FirstChild; while node <> nil do begin providerName := GetAttrValue(node, 'name'); layerNode := node.FirstChild; while layerNode <> nil do begin url := GetAttrValue(layerNode, 'url'); if url = '' then continue; s := GetAttrValue(layerNode, 'minZom'); if s = '' then minZoom := 0 else minZoom := StrToInt(s); s := GetAttrValue(layerNode, 'maxZoom'); if s = '' then maxzoom := 9 else maxZoom := StrToInt(s); s := GetAttrValue(layerNode, 'serverCount'); if s = '' then svrCount := 1 else svrCount := StrToInt(s); svrProc := GetAttrValue(layerNode, 'serverProc'); xProc := GetAttrValue(layerNode, 'xProc'); yProc := GetAttrValue(layerNode, 'yProc'); zProc := GetAttrValue(layerNode, 'zProc'); layerNode := layerNode.NextSibling; end; if first then begin ClearMapProviders; first := false; end; AddMapProvider(providerName, url, minZoom, maxZoom, svrCount, GetSvrStr(svrProc), GetValStr(xProc), GetValStr(yProc), GetValStr(zProc) ); node := node.NextSibling; end; Result := true; finally stream.Free; doc.Free; end; end; procedure TMapViewerEngine.Redraw; begin Redraw(MapWin); end; procedure TMapViewerEngine.Redraw(const aWin: TmapWindow); var TilesVis: TArea; x, y : Integer; //int64; Tiles: TTileIdArray = nil; iTile: Integer; begin if not(Active) then Exit; Queue.CancelAllJob(self); TilesVis := CalculateVisibleTiles(aWin); SetLength(Tiles, (TilesVis.Bottom - TilesVis.Top + 1) * (TilesVis.Right - TilesVis.Left + 1)); iTile := Low(Tiles); for y := TilesVis.Top to TilesVis.Bottom do for X := TilesVis.Left to TilesVis.Right do begin Tiles[iTile].X := X; Tiles[iTile].Y := Y; Tiles[iTile].Z := aWin.Zoom; if IsValidTile(aWin, Tiles[iTile]) then iTile += 1; end; SetLength(Tiles, iTile); if Length(Tiles) > 0 then Queue.AddJob(TLaunchDownloadJob.Create(self, Tiles, aWin), self); end; procedure TMapViewerEngine.RegisterProviders; var HERE1, HERE2: String; begin // AddMapProvider('Aucun','',0,30, 0); ??? AddMapProvider('Google Normal', 'http://mt%serv%.google.com/vt/lyrs=m@145&v=w2.104&x=%x%&y=%y%&z=%z%', 0, 19, 4, nil); AddMapProvider('Google Hybrid', 'http://mt%serv%.google.com/vt/lyrs=h@145&v=w2.104&x=%x%&y=%y%&z=%z%', 0, 19, 4, nil); AddMapProvider('Google Physical', 'http://mt%serv%.google.com/vt/lyrs=t@145&v=w2.104&x=%x%&y=%y%&z=%z%', 0, 19, 4, nil); { AddMapProvider('Google Hybrid','http://khm%d.google.com/kh/v=82&x=%x%&y=%y%&z=%z%&s=Ga',4); AddMapProvider('Google Hybrid','http://mt%d.google.com/vt/lyrs=h@145&v=w2.104&x=%d&y=%d&z=%z%',4); AddMapProvider('Google physical','http://mt%d.google.com/vt/lyrs=t@145&v=w2.104&x=%d&y=%d&z=%z%',4); AddMapProvider('Google Physical Hybrid','http://mt%d.google.com/vt/lyrs=t@145&v=w2.104&x=%x%&y=%y%&z=%z%',4); AddMapProvider('Google Physical Hybrid','http://mt%d.google.com/vt/lyrs=h@145&v=w2.104&x=%x%&y=%y%&z=%z%',4); } //AddMapProvider('OpenStreetMap Osmarender','http://%serv%.tah.openstreetmap.org/Tiles/tile/%z%/%x%/%y%.png',0,20,3, @getLetterSvr); // [Char(Ord('a')+Random(3)), Z, X, Y])); //AddMapProvider('Yahoo Normal','http://maps%serv%.yimg.com/hx/tl?b=1&v=4.3&.intl=en&x=%x%&y=%y%d&z=%d&r=1' , 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //(Z+1])); //AddMapProvider('Yahoo Satellite','http://maps%serv%.yimg.com/ae/ximg?v=1.9&t=a&s=256&.intl=en&x=%d&y=%d&z=%d&r=1', 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //[Random(3)+1, X, YahooY(Y), Z+1])); //AddMapProvider('Yahoo Hybrid','http://maps%serv%.yimg.com/ae/ximg?v=1.9&t=a&s=256&.intl=en&x=%x%&y=%y%&z=%z%&r=1', 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //[Random(3)+1, X, YahooY(Y), Z+1])); //AddMapProvider('Yahoo Hybrid','http://maps%serv%.yimg.com/hx/tl?b=1&v=4.3&t=h&.intl=en&x=%x%&y=%y%&z=%z%&r=1' , 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //[Random(3)+1, X, YahooY(Y), Z+1])); // opeName, Url, MinZoom, MaxZoom, NbSvr, GetSvrStr, GetXStr, GetYStr, GetZStr MapWin.MapProvider := AddMapProvider('OpenStreetMap Mapnik', 'http://%serv%.tile.openstreetmap.org/%z%/%x%/%y%.png', 0, 19, 3, @GetLetterSvr); AddMapProvider('Open Cycle Map', 'http://%serv%.tile.opencyclemap.org/cycle/%z%/%x%/%y%.png', 0, 18, 3, @getLetterSvr); AddMapProvider('Open Topo Map', 'http://%serv%.tile.opentopomap.org/%z%/%x%/%y%.png', 0, 19, 3, @getLetterSvr); AddMapProvider('Virtual Earth Bing', 'http://ecn.t%serv%.tiles.virtualearth.net/tiles/r%x%?g=671&mkt=en-us&lbl=l1&stl=h&shading=hill', 1, 19, 8, nil, @GetQuadKey); AddMapProvider('Virtual Earth Road', 'http://r%serv%.ortho.tiles.virtualearth.net/tiles/r%x%.png?g=72&shading=hill', 1, 19, 4, nil, @GetQuadKey); AddMapProvider('Virtual Earth Aerial', 'http://a%serv%.ortho.tiles.virtualearth.net/tiles/a%x%.jpg?g=72&shading=hill', 1, 19, 4, nil, @GetQuadKey); AddMapProvider('Virtual Earth Hybrid', 'http://h%serv%.ortho.tiles.virtualearth.net/tiles/h%x%.jpg?g=72&shading=hill', 1, 19, 4, nil, @GetQuadKey); if (HERE_AppID <> '') and (HERE_AppCode <> '') then begin // Registration required to access HERE maps: // https://developer.here.com/?create=Freemium-Basic&keepState=true&step=account // Store the APP_ID and APP_CODE obtained after registration in the // ini file of the demo under key [HERE] as items APP_ID and APP_CODE and // restart the demo. HERE1 := 'http://%serv%.base.maps.api.here.com/maptile/2.1/maptile/newest/'; HERE2 := '/%z%/%x%/%y%/256/png8?app_id=' + HERE_AppID + '&app_code=' + HERE_AppCode; AddMapProvider('Here Maps', HERE1 + 'normal.day' + HERE2, 1, 19, 4, @GetYahooSvr); AddMapProvider('Here Maps Grey', HERE1 + 'normal.day.grey' + HERE2, 1, 19, 4, @GetYahooSvr); AddMapProvider('Here Maps Reduced', HERE1 + 'reduced.day' + HERE2, 1, 19, 4, @GetYahooSvr); AddMapProvider('Here Maps Transit', HERE1 + 'normal.day.transit' + HERE2, 1, 19, 4, @GetYahooSvr); AddMapProvider('Here POI Maps', HERE1 + 'normal.day' + HERE2 + '&pois', 1, 19, 4, @GetYahooSvr); AddMapProvider('Here Pedestrian Maps', HERE1 + 'pedestrian.day' + HERE2, 1, 19, 4, @GetYahooSvr); AddMapProvider('Here DreamWorks Maps', HERE1 + 'normal.day' + HERE2 + '&style=dreamworks', 1, 19, 4, @GetYahooSvr); end; if (OpenWeatherMap_ApiKey <> '') then begin // Registration required to access OpenWeatherMaps // https://home.openweathermap.org/users/sign_up // Store the API key found on the website in the ini file of the demo under // key [OpenWeatherMap] and API_Key and restart the demo AddMapProvider('OpenWeatherMap Clouds', 'https://tile.openweathermap.org/map/clouds_new/%z%/%x%/%y%.png?appid=' + OpenWeatherMap_ApiKey, 1, 19, 1, nil); AddMapProvider('OpenWeatherMap Precipitation', 'https://tile.openweathermap.org/map/precipitation_new/%z%/%x%/%y%.png?appid=' + OpenWeatherMap_ApiKey, 1, 19, 1, nil); AddMapProvider('OpenWeatherMap Pressure', 'https://tile.openweathermap.org/map/pressure_new/%z%/%x%/%y%.png?appid=' + OpenWeatherMap_ApiKey, 1, 19, 1, nil); AddMapProvider('OpenWeatherMap Temperature', 'https://tile.openweathermap.org/map/temp_new/%z%/%x%/%y%.png?appid=' + OpenWeatherMap_ApiKey, 1, 19, 1, nil); AddMapProvider('OpenWeatherMap Wind', 'https://tile.openweathermap.org/map/wind_new/%z%/%x%/%y%.png?appid=' + OpenWeatherMap_ApiKey, 1, 19, 1, nil); end; { The Ovi Maps (former Nokia maps) are no longer available. AddMapProvider('Ovi Normal', 'http://%serv%.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/normal.day/%z%/%x%/%y%/256/png8', 0, 20, 5, @GetLetterSvr); AddMapProvider('Ovi Satellite', 'http://%serv%.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/satellite.day/%z%/%x%/%y%/256/png8', 0, 20, 5, @GetLetterSvr); AddMapProvider('Ovi Hybrid', 'http://%serv%.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/hybrid.day/%z%/%x%/%y%/256/png8', 0, 20, 5, @GetLetterSvr); AddMapProvider('Ovi Physical', 'http://%serv%.maptile.maps.svc.ovi.com/maptiler/v2/maptile/newest/terrain.day/%z%/%x%/%y%/256/png8', 0, 20, 5, @GetLetterSvr); } { AddMapProvider('Yahoo Normal','http://maps%serv%.yimg.com/hx/tl?b=1&v=4.3&.intl=en&x=%x%&y=%y%d&z=%d&r=1' , 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //(Z+1])); AddMapProvider('Yahoo Satellite','http://maps%serv%.yimg.com/ae/ximg?v=1.9&t=a&s=256&.intl=en&x=%d&y=%d&z=%d&r=1', 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //[Random(3)+1, X, YahooY(Y), Z+1])); AddMapProvider('Yahoo Hybrid','http://maps%serv%.yimg.com/ae/ximg?v=1.9&t=a&s=256&.intl=en&x=%x%&y=%y%&z=%z%&r=1', 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //[Random(3)+1, X, YahooY(Y), Z+1])); AddMapProvider('Yahoo Hybrid','http://maps%serv%.yimg.com/hx/tl?b=1&v=4.3&t=h&.intl=en&x=%x%&y=%y%&z=%z%&r=1' , 0,20,3,@GetYahooSvr, nil, @getYahooY, @GetYahooZ); //[Random(3)+1, X, YahooY(Y), Z+1])); } end; function TMapViewerEngine.ScreenToLonLat(aPt: TPoint): TRealPoint; begin Result := MapWinToLonLat(MapWin, aPt); end; procedure TMapViewerEngine.SetActive(AValue: boolean); begin if FActive = AValue then Exit; FActive := AValue; if not(FActive) then Queue.CancelAllJob(self) else begin if Cache.UseDisk then ForceDirectories(Cache.BasePath); Redraw(MapWin); end; end; procedure TMapViewerEngine.SetCacheOnDisk(AValue: Boolean); begin if Cache.UseDisk = AValue then Exit; Cache.UseDisk := AValue; end; procedure TMapViewerEngine.SetCachePath(AValue: String); begin Cache.BasePath := aValue; end; procedure TMapViewerEngine.SetCenter(aCenter: TRealPoint); begin if (MapWin.Center.Lon <> aCenter.Lon) and (MapWin.Center.Lat <> aCenter.Lat) then begin Mapwin.Center := aCenter; CalculateWin(MapWin); Redraw(MapWin); if assigned(OnCenterMove) then OnCenterMove(Self); if Assigned(OnChange) then OnChange(Self); end; end; procedure TMapViewerEngine.SetDownloadEngine(AValue: TMvCustomDownloadEngine); begin if FDownloadEngine = AValue then Exit; FDownloadEngine := AValue; if Assigned(FDownloadEngine) then FDownloadEngine.FreeNotification(self); end; procedure TMapViewerEngine.SetHeight(AValue: integer); begin if MapWin.Height = AValue then Exit; MapWin.Height := AValue; CalculateWin(MapWin); Redraw(MapWin); end; procedure TMapViewerEngine.SetMapProvider(AValue: String); var idx: integer; begin idx := lstProvider.IndexOf(aValue); if not ((aValue = '') or (idx <> -1)) then raise Exception.Create('Unknow Provider: ' + aValue); if Assigned(MapWin.MapProvider) and (MapWin.MapProvider.Name = AValue) then Exit; if idx <> -1 then begin MapWin.MapProvider := TMapProvider(lstProvider.Objects[idx]); ConstraintZoom(MapWin); end else MapWin.MapProvider := nil; if Assigned(MapWin.MapProvider) then Redraw(MapWin); end; procedure TMapViewerEngine.SetSize(aWidth, aHeight: integer); begin if (MapWin.Width = aWidth) and (MapWin.Height = aHeight) then Exit; CancelCurrentDrawing; MapWin.Width := aWidth; MapWin.Height := aHeight; CalculateWin(MapWin); Redraw(MapWin); if Assigned(OnChange) then OnChange(Self); end; procedure TMapViewerEngine.SetUseThreads(AValue: Boolean); begin if Queue.UseThreads = AValue then Exit; Queue.UseThreads := AValue; Cache.UseThreads := AValue; end; procedure TMapViewerEngine.SetWidth(AValue: integer); begin if MapWin.Width = AValue then Exit; MapWin.Width := AValue; CalculateWin(MapWin); Redraw(MapWin); end; procedure TMapViewerEngine.SetZoom(AValue: integer); begin if MapWin.Zoom = AValue then Exit; MapWin.Zoom := AValue; ConstraintZoom(MapWin); CalculateWin(MapWin); Redraw(MapWin); if Assigned(OnZoomChange) then OnZoomChange(Self); if Assigned(OnChange) then OnChange(Self); end; procedure TMapViewerEngine.TileDownloaded(Data: PtrInt); var EnvTile: TEnvTile; img: TLazIntfImage; X, Y: integer; begin EnvTile := TEnvTile(Data); try if IsCurrentWin(EnvTile.Win)then begin Cache.GetFromCache(EnvTile.Win.MapProvider, EnvTile.Tile, img); X := EnvTile.Win.X + EnvTile.Tile.X * TILE_SIZE; // begin of X Y := EnvTile.Win.Y + EnvTile.Tile.Y * TILE_SIZE; // begin of X DrawTile(EnvTile.Tile, X, Y, img); end; finally FreeAndNil(EnvTile); end; end; function TMapViewerEngine.WorldScreenToLonLat(aPt: TPoint): TRealPoint; begin aPt.X := aPt.X - MapWin.X; aPt.Y := aPt.Y - MapWin.Y; Result := ScreenToLonLat(aPt); end; procedure TMapViewerEngine.WriteProvidersToXML(AFileName: String); var doc: TXMLDocument; root: TDOMNode; i: Integer; prov: TMapProvider; begin doc := TXMLDocument.Create; try root := doc.CreateElement('map_providers'); doc.AppendChild(root); for i := 0 to lstProvider.Count - 1 do begin prov := TMapProvider(lstProvider.Objects[i]); prov.ToXML(doc, root); end; WriteXMLFile(doc, AFileName); finally doc.Free; end; end; procedure TMapViewerEngine.ZoomOnArea(const aArea: TRealArea); var tmpWin: TMapWindow; visArea: TRealArea; TopLeft, BottomRight: TPoint; begin tmpWin := MapWin; tmpWin.Center.Lon := (aArea.TopLeft.Lon + aArea.BottomRight.Lon) / 2; tmpWin.Center.Lat := (aArea.TopLeft.Lat + aArea.BottomRight.Lat) / 2; tmpWin.Zoom := 18; TopLeft.X := 0; TopLeft.Y := 0; BottomRight.X := tmpWin.Width; BottomRight.Y := tmpWin.Height; Repeat CalculateWin(tmpWin); visArea.TopLeft := MapWinToLonLat(tmpWin, TopLeft); visArea.BottomRight := MapWinToLonLat(tmpWin, BottomRight); if AreaInsideArea(aArea, visArea) then break; dec(tmpWin.Zoom); until (tmpWin.Zoom = 2); MapWin := tmpWin; Redraw(MapWin); end; //------------------------------------------------------------------------------ procedure SplitGps(AValue: Double; out ADegs, AMins: Double); begin AValue := abs(AValue); AMins := frac(AValue) * 60; ADegs := trunc(AValue); end; procedure SplitGps(AValue: Double; out ADegs, AMins, ASecs: Double); begin SplitGps(AValue, ADegs, AMins); ASecs := frac(AMins) * 60; AMins := trunc(AMins); end; function GPSToDMS(Angle: Double): string; var deg, min, sec: Double; begin SplitGPS(Angle, deg, min, sec); Result := Format('%.0f° %.0f'' %.1f"', [deg, min, sec]); end; function LatToStr(ALatitude: Double; DMS: Boolean): String; begin if DMS then Result := GPSToDMS(abs(ALatitude)) else Result := Format('%.6f°',[abs(ALatitude)]); if ALatitude > 0 then Result := Result + ' N' else if ALatitude < 0 then Result := Result + 'E'; end; function LonToStr(ALongitude: Double; DMS: Boolean): String; begin if DMS then Result := GPSToDMS(abs(ALongitude)) else Result := Format('%.6f°', [abs(ALongitude)]); if ALongitude > 0 then Result := Result + ' E' else if ALongitude < 0 then Result := Result + ' W'; end; { Combines up to three parts of a GPS coordinate string (degrees, minutes, seconds) to a floating-point degree value. The parts are separated by non-numeric characters: three parts ---> d m s ---> d and m must be integer, s can be float two parts ---> d m ---> d must be integer, s can be float one part ---> d ---> d can be float Each part can exhibit a unit identifier, such as °, ', or ". BUT: they are ignored. This means that an input string 50°30" results in the output value 50.5 although the second part is marked as seconds, not minutes! Hemisphere suffixes ('N', 'S', 'E', 'W') are supported at the end of the input string. } function TryStrToGps(const AValue: String; out ADeg: Double): Boolean; const NUMERIC_CHARS = ['0'..'9', '.', ',', '-', '+']; var mins, secs: Double; i, j, len: Integer; n: Integer; s: String = ''; res: Integer; sgn: Double; begin Result := false; ADeg := NaN; mins := 0; secs := 0; if AValue = '' then exit; len := Length(AValue); i := len; while (i >= 1) and (AValue[i] = ' ') do dec(i); sgn := 1.0; if (AValue[i] in ['S', 's', 'W', 'w']) then sgn := -1; // skip leading non-numeric characters i := 1; while (i <= len) and not (AValue[i] in NUMERIC_CHARS) do inc(i); // extract first value: degrees SetLength(s, len); j := 1; n := 0; while (i <= len) and (AValue[i] in NUMERIC_CHARS) do begin if AValue[i] = ',' then s[j] := '.' else s[j] := AValue[i]; inc(i); inc(j); inc(n); end; if n > 0 then begin SetLength(s, n); val(s, ADeg, res); if res <> 0 then exit; end; // skip non-numeric characters between degrees and minutes while (i <= len) and not (AValue[i] in NUMERIC_CHARS) do inc(i); // extract second value: minutes SetLength(s, len); j := 1; n := 0; while (i <= len) and (AValue[i] in NUMERIC_CHARS) do begin if AValue[i] = ',' then s[j] := '.' else s[j] := AValue[i]; inc(i); inc(j); inc(n); end; if n > 0 then begin SetLength(s, n); val(s, mins, res); if (res <> 0) or (mins < 0) then exit; end; // skip non-numeric characters between minutes and seconds while (i <= len) and not (AValue[i] in NUMERIC_CHARS) do inc(i); // extract third value: seconds SetLength(s, len); j := 1; n := 0; while (i <= len) and (AValue[i] in NUMERIC_CHARS) do begin if AValue[i] = ',' then s[j] := '.' else s[j] := AValue[i]; inc(i); inc(j); inc(n); end; if n > 0 then begin SetLength(s, n); val(s, secs, res); if (res <> 0) or (secs < 0) then exit; end; // If the string contains seconds then minutes and deegrees must be integers if (secs <> 0) and ((frac(ADeg) > 0) or (frac(mins) > 0)) then exit; // If the string does not contain seconds then degrees must be integer. if (secs = 0) and (mins <> 0) and (frac(ADeg) > 0) then exit; // If the string contains minutes, but no seconds, then the degrees must be integer. Result := (mins >= 0) and (mins < 60) and (secs >= 0) and (secs < 60); // A similar check should be made for the degrees range, but since this is // different for latitude and longitude the check is skipped here. if Result then ADeg := sgn * (abs(ADeg) + mins / 60 + secs / 3600); end; { Returns the direct distance (air-line) between two geo coordinates If latitude NOT between -90°..+90° and longitude NOT between -180°..+180° the function returns -1. Usage: FindDistance(51.53323, -2.90130, 51.29442, -2.27275, duKilometers); } function CalcGeoDistance(Lat1, Lon1, Lat2, Lon2: double; AUnits: TDistanceUnits = duKilometers): double; const EPS = 1E-12; var d_radians: double; // distance in radians lat1r, lon1r, lat2r, lon2r: double; arg: Double; begin // Validate if (Lat1 < -90.0) or (Lat1 > 90.0) then exit(NaN); // if (Lon1 < -180.0) or (Lon1 > 180.0) then exit(NaN); if (Lat2 < -90.0) or (Lat2 > 90.0) then exit(NaN); // if (Lon2 < -180.0) or (Lon2 > 180.0) then exit(NaN); // Turn lat and lon into radian measures lat1r := (PI / 180.0) * Lat1; lon1r := (PI / 180.0) * Lon1; lat2r := (PI / 180.0) * Lat2; lon2r := (PI / 180.0) * Lon2; // calc arg := sin(lat1r) * sin(lat2r) + cos(lat1r) * cos(lat2r) * cos(lon1r - lon2r); if (arg < -1) or (arg > +1) then exit(NaN); if SameValue(abs(Lon1-Lon2), 360, EPS) and SameValue(abs(arg), 1.0, EPS) then d_radians := PI * 2.0 else d_radians := arccos(arg); Result := EARTH_RADIUS * d_radians; case AUnits of duMeters: ; duKilometers: Result := Result * 1E-3; duMiles: Result := Result * 0.62137E-3; end; end; end.
unit TblMgrUnt; interface uses DdeExlUnt, Types, Classes, Math, Controls, Sysutils; type TTableChangeEvent = procedure(Topic: string; NewCells: TVariantTable; NewAddr: TRect) of object; TqkTable = class SubScriber: TTableChangeEvent; NewAddr: TRect; Active: Boolean; end; TTableManager = class(TWinControl) private fTables: TStringList; procedure DdePoke(Topic: string; var Action: TPokeAction); procedure DdeData(Topic: string; Cells: TRect; Data: TVariantTable); function GetActive(index: string): boolean; procedure SetActive(index: string; Value: boolean); protected public constructor Create(AOwner: TComponent);override; destructor Destroy;override; function AddTable(AName: string; ASubscriber: TTableChangeEvent): integer; procedure DelTable(AName: string); property Active[TableName: string]: boolean read GetActive write SetActive; published end; var TableMgr: TTableManager; implementation constructor TTableManager.Create; begin inherited; fTables := TStringList.Create; DdeExcel := TDdeExcel.Create(AOwner); DdeExcel.OnPoke := DdePoke; DdeExcel.OnData := DdeData; end; destructor TTablemanager.Destroy; var i: integer; begin fTables.Clear; inherited; end; function TTableManager.AddTable(AName: string; ASubscriber: TTableChangeEvent): integer; var t: TqkTable; i: integer; begin If fTables.IndexOf(AName) > -1 then begin result := -1; Exit; end; t := TqkTable.Create; t.Active := true; t.SubScriber := ASubscriber; i := fTables.AddObject(AName, t); If i < 0 then begin t.Free; result := -2; end else result := i end; procedure TTableManager.DelTable(AName: string); var i: integer; begin i := fTables.IndexOf(AName); If i > -1 then begin fTables.Delete(i); end; end; procedure TTableManager.DdePoke(Topic: string; var Action: TPokeAction); var i: integer; begin i := fTables.IndexOf(Topic); If i < 0 then Action := paReject else If TqkTable(fTables.Objects[i]).Active then Action := paAccept else Action := paPass; end; procedure TTableManager.DdeData(Topic: string; Cells: TRect; Data: TVariantTable); var t: TqkTable; i, j: integer; rc, cc: integer; begin i := fTables.IndexOf(Topic); If i < 0 then Exit; t := TqkTable(fTables.Objects[i]); // Вызываем подписчика If Assigned(t.Subscriber) then t.SubScriber(Topic, Data, Cells); end; function TTableManager.GetActive(index: string): boolean; var n: integer; begin n := fTables.IndexOf(index); If n < 0 then Exit; result := TqkTable(fTables.Objects[n]).Active; end; procedure TTableManager.SetActive(index: string; Value: boolean); var n: integer; begin n := fTables.IndexOf(index); If n < 0 then Exit; TqkTable(fTables.Objects[n]).Active := Value; end; end.
{$INCLUDE ..\cDefines.inc} unit cURL; { } { URL Utilities 3.07 } { } { This unit is copyright © 2000-2004 by David J Butler } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cURL.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { Revision history: } { 17/10/2000 1.01 Unit cInternetStandards. } { 22/12/2001 1.02 Unit cMIME. } { 12/12/2002 3.03 Unit cInternetUtils. } { 21/02/2004 3.04 Added URL protocol base class. } { 22/02/2004 3.05 Added URL File Protocol implementation class. } { 05/03/2004 3.06 Unit cURL. } { 12/03/2004 3.07 Added asynchronous URL content functions. } { } interface uses { Delphi } SysUtils, { Fundamentals } cReaders, cThreads; { } { URL protocol } { URL protocol implementations must use AURLProtocol as their base class. } { URL protocol implementations must call RegisterURLProtocol to register } { the implementation object. } { } type AURLProtocol = class public { URL } function DecodeURL(const URL: String; var Protocol, Host, Path: String): Boolean; virtual; { Content } function IsContentSupported(const Protocol, Host, Path: String): Boolean; virtual; function GetContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; virtual; function GetContentString(const Protocol, Host, Path: String; var Content, ContentType: String): Boolean; virtual; end; EURLProtocol = class(Exception); procedure RegisterURLProtocol(const Handler: AURLProtocol); { } { URL string } { } const protoHTTP = 'http'; protoNNTP = 'news'; protoFTP = 'ftp'; protoGopher = 'gopher'; protoEMail = 'mailto'; protoHTTPS = 'https'; protoIRC = 'irc'; protoFile = 'file'; protoTelnet = 'telnet'; procedure DecodeURL(const URL: String; var Protocol, Host, Path: String); function EncodeURL(const Protocol, Host, Path: String): String; { } { URL content (blocking functions) } { } function GetURLProtocolContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; function GetURLProtocolContentString(const Protocol, Host, Path: String; var Content, ContentType: String): Boolean; function GetURLContentReader(const URL: String; var ContentType: String): AReaderEx; function GetURLContentString(const URL: String; var Content, ContentType: String): Boolean; function RequireURLProtocolContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; function RequireURLProtocolContentString(const Protocol, Host, Path: String; var ContentType: String): String; function RequireURLContentReader(const URL: String; var ContentType: String): AReaderEx; function RequireURLContentString(const URL: String; var ContentType: String): String; { } { URL content (asynchronous functions) } { Call GetURLContentAsync to retrieve URL content asynchronously. } { Caller must free the returned TURLContentAsync object. } { } type TURLContentAsync = class; TURLContentNotifyEvent = procedure (const URLContent: TURLContentAsync; const Data: Pointer) of object; TURLContentProgressEvent = procedure (const URLContent: TURLContentAsync; const Data: Pointer; const Buffer; const Size: Integer; var Abort: Boolean) of object; TURLContentMode = ( ucGetContentString, // Return content in ContentString property ucSaveContentFile, // Save content to ContentFileName ucNotifyContentBlocks); // Call OnProgress with content blocks TURLContentAsync = class(TThreadEx) private FProtocol : String; FHost : String; FPath : String; FContentMode : TURLContentMode; FContentFileName : String; FData : Pointer; FOnProgress : TURLContentProgressEvent; FOnFinished : TURLContentNotifyEvent; FFinished : Boolean; FSuccess : Boolean; FErrorMessage : String; FContentSize : Integer; FContentProgress : Integer; FContentType : String; FContentString : String; protected procedure TriggerProgress(const Buffer; const Size: Integer; var Abort: Boolean); virtual; procedure TriggerFinished; virtual; procedure Execute; override; public constructor Create( const Protocol, Host, Path: String; const ContentMode: TURLContentMode = ucGetContentString; const ContentFileName: String = ''; const Data: Pointer = nil; const OnProgress: TURLContentProgressEvent = nil; const OnFinished: TURLContentNotifyEvent = nil); property Protocol: String read FProtocol; property Host: String read FHost; property Path: String read FPath; property ContentMode: TURLContentMode read FContentMode; property ContentFileName: String read FContentFileName; property Data: Pointer read FData; property Finished: Boolean read FFinished; property Success: Boolean read FSuccess; property ErrorMessage: String read FErrorMessage; property ContentSize: Integer read FContentSize; property ContentProgress: Integer read FContentProgress; property ContentType: String read FContentType; property ContentString: String read FContentString; end; function GetURLProtocolContentAsync( const Protocol, Host, Path: String; const ContentMode: TURLContentMode = ucGetContentString; const ContentFileName: String = ''; const Data: Pointer = nil; const OnProgress: TURLContentProgressEvent = nil; const OnFinished: TURLContentNotifyEvent = nil): TURLContentAsync; function GetURLContentAsync( const URL: String; const ContentMode: TURLContentMode = ucGetContentString; const ContentFileName: String = ''; const Data: Pointer = nil; const OnProgress: TURLContentProgressEvent = nil; const OnFinished: TURLContentNotifyEvent = nil): TURLContentAsync; { } { URL file protocol } { } type TURLFileProtocol = class(AURLProtocol) public function IsContentSupported(const Protocol, Host, Path: String): Boolean; override; function GetContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; override; function GetContentString(const Protocol, Host, Path: String; var Content, ContentType: String): Boolean; override; end; procedure RegisterURLFileProtocol; { } { Self-testing code } { } procedure SelfTest; implementation uses { Fundamentals } cUtils, cStrings, cWriters, cStreams, cFileUtils, cInternetUtils; { } { AURLProtocol } { } function AURLProtocol.DecodeURL(const URL: String; var Protocol, Host, Path: String): Boolean; begin Protocol := ''; Host := ''; Path := ''; Result := False; end; function AURLProtocol.IsContentSupported(const Protocol, Host, Path: String): Boolean; begin Result := False; end; function AURLProtocol.GetContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; begin ContentType := ''; Result := nil; end; function AURLProtocol.GetContentString(const Protocol, Host, Path: String; var Content, ContentType: String): Boolean; begin Content := ''; ContentType := ''; Result := False; end; { } { URL Protocol implementations } { } var URLProtocols : Array of AURLProtocol = nil; procedure RegisterURLProtocol(const Handler: AURLProtocol); begin if not Assigned(Handler) then raise EURLProtocol.Create('URL protocol handler required'); Append(ObjectArray(URLProtocols), Handler); end; { } { URL string } { } function urlDecodeHTTP(const S: String; var Protocol, Host, Path: String): Boolean; var I, J: Integer; begin Protocol := ''; Host := ''; Path := ''; if StrMatchLeft(S, 'http:', False) then Protocol := protoHTTP else if StrMatchLeft(S, 'https:', False) then Protocol := protoHTTPS; Result := Protocol <> ''; if not Result then exit; I := PosChar(':', S); Assert(I > 0, 'I > 0'); if StrMatch(S, '//', I + 1) then Inc(I, 2); J := PosChar('/', S, I + 1); if J = 0 then Host := CopyFrom(S, I + 1) else begin Host := CopyRange(S, I + 1, J - 1); Path := CopyFrom(S, J); end; end; function urlDecodeEMail(const S: String; var Protocol, Host, Path: String): Boolean; begin Protocol := ''; Host := ''; Path := ''; if StrMatchLeft(S, 'mailto:', False) then begin Protocol := protoEMail; Host := CopyFrom(S, 8); end else if (PosChar([':', '/', '\'], S) = 0) and (PosChar('@', S) > 1) then begin Protocol := protoEMail; Host := S; end; Result := Protocol <> ''; if not Result then exit; TrimInPlace(Host, SPACE); end; function urlDecodeFile(const S: String; var Protocol, Host, Path: String): Boolean; begin Protocol := ''; Host := ''; Path := ''; if S <> '' then if StrMatchLeft(S, 'file:', False) then begin Protocol := protoFile; Path := CopyFrom(S, 6); end else if (PChar(S)^ = '\') or (PathHasDriveLetter(S) and StrMatch(S, '\', 3)) then begin Protocol := protoFile; Path := S; end; Result := Protocol <> ''; end; function urlDecodeKnownProtocol(const S: String; var Protocol, Host, Path: String): Boolean; begin Result := urlDecodeHTTP(S, Protocol, Host, Path); if Result then exit; Result := urlDecodeEMail(S, Protocol, Host, Path); if Result then exit; Result := urlDecodeFile(S, Protocol, Host, Path); if Result then exit; end; function urlDecodePath(const S: String; var Protocol, Host, Path: String): Boolean; var I: Integer; begin Protocol := ''; Host := ''; Path := ''; Result := False; // special cases if (S = '') or (S = '*') or (S = '/') then begin Path := S; Result := True; end else // relative path if StrMatchLeft(S, '../') or StrMatchLeft(S, './') then begin Path := S; Result := True; end else // "/" prefix if PChar(S)^ = '/' then begin if StrMatchLeft(S, '//') then begin // "//"host["/"path] I := PosChar('/', S, 3); if I = 0 then // "//"host Host := CopyFrom(S, 3) else begin // "//"host"/"path Host := CopyRange(S, 3, I - 1); Path := CopyFrom(S, I); end; end else // "/"path Path := S; Result := True; end; end; procedure urlDecodeGeneral(const S: String; var Protocol, Host, Path: String); var I, J : Integer; T : String; begin Protocol := ''; Host := ''; Path := ''; I := PosStr('://', S); J := PosChar('/', S); if (I > 0) and (J = I + 1) then begin // protocol"://" Protocol := Trim(CopyLeft(S, I - 1), SPACE); J := PosChar('/', S, I + 3); if J = 0 then begin Host := Trim(CopyFrom(S, I + 3), SPACE); Path := ''; end else begin Host := Trim(CopyRange(S, I + 3, J - 1), SPACE); Path := Trim(CopyFrom(S, J), SPACE); end; exit; end; I := PosChar(':', S); if (I = 0) or ((I > 0) and (J > 0) and (J < I)) then begin // no protocol Path := S; exit; end; // check text between ":" and "/" if J > 0 then T := CopyRange(S, I + 1, J - 1) else T := CopyFrom(S, I + 1); if StrIsNumeric(T) then begin // address":"port/path if J = 0 then Host := S else begin Host := CopyLeft(S, J - 1); Path := CopyFrom(S, J); end; exit; end; // protocol":"host"/"path Protocol := Trim(CopyLeft(S, I - 1), SPACE); if J = 0 then Host := CopyFrom(S, I + 1) else begin Host := CopyRange(S, I + 1, J - 1); Path := CopyFrom(S, J); end; end; procedure DecodeURL(const URL: String; var Protocol, Host, Path: String); const KnownProtocols = 3; KnownProtocol: Array [1..KnownProtocols] of String = (protoEMail, protoNNTP, protoFile); var S : String; I : Integer; begin Protocol := ''; Host := ''; Path := ''; // clean URL S := Trim(URL, SPACE); if S = '' then exit; // check if url is a path only if urlDecodePath(S, Protocol, Host, Path) then exit; // check url protocol handlers For I := 0 to Length(URLProtocols) - 1 do if URLProtocols[I].DecodeURL(URL, Protocol, Host, Path) then exit; // check known protocol if urlDecodeKnownProtocol(S, Protocol, Host, Path) then exit; // check general format urlDecodeGeneral(S, Protocol, Host, Path); end; function EncodeURL(const Protocol, Host, Path: String): String; begin Result := ''; if Protocol <> '' then if StrEqualNoCase(protoHTTP, Protocol) or StrEqualNoCase(protoHTTPS, Protocol) then Result := Protocol + '://' else Result := Protocol + ':'; Result := Result + Host; if Path <> '' then if not (Path [1] in [':', '/', '\', '@', ',']) then Result := Result + '/' + Path else Result := Result + Path; end; { } { URL content (blocking functions) } { } function GetURLProtocolContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; var I : Integer; P : AURLProtocol; S : String; begin For I := 0 to Length(URLProtocols) - 1 do begin P := URLProtocols[I]; if P.IsContentSupported(Protocol, Host, Path) then begin Result := P.GetContentReader(Protocol, Host, Path, ContentType); if Assigned(Result) then exit; if P.GetContentString(Protocol, Host, Path, S, ContentType) then begin Result := TStringReader.Create(S); exit; end; end; end; ContentType := ''; Result := nil; end; function GetURLProtocolContentString(const Protocol, Host, Path: String; var Content, ContentType: String): Boolean; var I : Integer; P : AURLProtocol; R : AReaderEx; begin For I := 0 to Length(URLProtocols) - 1 do begin P := URLProtocols[I]; if P.IsContentSupported(Protocol, Host, Path) then begin Result := P.GetContentString(Protocol, Host, Path, Content, ContentType); if Result then exit; R := P.GetContentReader(Protocol, Host, Path, ContentType); if Assigned(R) then begin try Content := R.GetToEOF; finally R.Free; end; Result := True; exit; end; end; end; Content := ''; ContentType := ''; Result := False; end; function GetURLContentReader(const URL: String; var ContentType: String): AReaderEx; var Protocol, Host, Path : String; begin if URL = '' then raise EURLProtocol.Create('URL required'); DecodeURL(URL, Protocol, Host, Path); Result := GetURLProtocolContentReader(Protocol, Host, Path, ContentType); end; function GetURLContentString(const URL: String; var Content, ContentType: String): Boolean; var Protocol, Host, Path : String; begin if URL = '' then raise EURLProtocol.Create('URL required'); DecodeURL(URL, Protocol, Host, Path); Result := GetURLProtocolContentString(Protocol, Host, Path, Content, ContentType); end; function RequireURLProtocolContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; begin Result := GetURLProtocolContentReader(Protocol, Host, Path, ContentType); if not Assigned(Result) then raise EURLProtocol.Create('URL not supported'); end; function RequireURLProtocolContentString(const Protocol, Host, Path: String; var ContentType: String): String; begin if not GetURLProtocolContentString(Protocol, Host, Path, Result, ContentType) then raise EURLProtocol.Create('URL not supported'); end; function RequireURLContentReader(const URL: String; var ContentType: String): AReaderEx; begin Result := GetURLContentReader(URL, ContentType); if not Assigned(Result) then raise EURLProtocol.Create('URL not supported'); end; function RequireURLContentString(const URL: String; var ContentType: String): String; begin if not GetURLContentString(URL, Result, ContentType) then raise EURLProtocol.Create('URL not supported'); end; { } { URL content (asynchronous functions) } { } const ProgressBlockSize = 4096; constructor TURLContentAsync.Create( const Protocol, Host, Path: String; const ContentMode: TURLContentMode; const ContentFileName: String; const Data: Pointer; const OnProgress: TURLContentProgressEvent; const OnFinished: TURLContentNotifyEvent); begin FProtocol := Protocol; FHost := Host; FPath := Path; FContentMode := ContentMode; FContentFileName := ContentFileName; FData := Data; FOnProgress := OnProgress; FOnFinished := OnFinished; FreeOnTerminate := False; inherited Create(False); end; procedure TURLContentAsync.TriggerProgress(const Buffer; const Size: Integer; var Abort: Boolean); begin if Assigned(FOnProgress) then FOnProgress(self, FData, Buffer, Size, Abort); end; procedure TURLContentAsync.TriggerFinished; begin if Assigned(FOnFinished) then FOnFinished(self, FData); end; procedure TURLContentAsync.Execute; var Reader : AReaderEx; Writer : TFileWriter; Buf : Array[0..ProgressBlockSize - 1] of Byte; I : Integer; A : Boolean; begin FErrorMessage := ''; try try if FContentMode = ucGetContentString then begin FContentString := RequireURLProtocolContentString(FProtocol, FHost, FPath, FContentType); FContentSize := Length(FContentString); FSuccess := True; end else if FContentMode in [ucNotifyContentBlocks, ucSaveContentFile] then begin Reader := RequireURLProtocolContentReader(FProtocol, FHost, FPath, FContentType); try FContentSize := Reader.Size; if FContentMode = ucSaveContentFile then begin if FContentFileName = '' then raise EURLProtocol.Create('Filename required'); Writer := TFileWriter.Create(FContentFileName, fwomCreate) end else Writer := nil; try A := False; While not Reader.EOF and not Terminated do begin I := Reader.Read(Buf[0], ProgressBlockSize); if (I = 0) and not Reader.EOF then raise EURLProtocol.Create('Read error'); Inc(FContentProgress, I); if Terminated then exit; TriggerProgress(Buf[0], I, A); if A then raise EURLProtocol.Create('Aborted'); if Assigned(Writer) then Writer.WriteBuffer(Buf[0], I); end; finally Writer.Free; end; finally Reader.Free; end; FContentSize := FContentProgress; FSuccess := True; end; except on E : Exception do FErrorMessage := E.Message; end; finally FFinished := True; TriggerFinished; end; end; function GetURLProtocolContentAsync(const Protocol, Host, Path: String; const ContentMode: TURLContentMode; const ContentFileName: String; const Data: Pointer; const OnProgress: TURLContentProgressEvent; const OnFinished: TURLContentNotifyEvent): TURLContentAsync; begin Result := TURLContentAsync.Create(Protocol, Host, Path, ContentMode, ContentFileName, Data, OnProgress, OnFinished); end; function GetURLContentAsync( const URL: String; const ContentMode: TURLContentMode; const ContentFileName: String; const Data: Pointer; const OnProgress: TURLContentProgressEvent; const OnFinished: TURLContentNotifyEvent): TURLContentAsync; var Protocol, Host, Path : String; begin DecodeURL(URL, Protocol, Host, Path); Result := GetURLProtocolContentAsync(Protocol, Host, Path, ContentMode, ContentFileName, Data, OnProgress, OnFinished); end; { } { URL File Protocol } { } function TURLFileProtocol.IsContentSupported(const Protocol, Host, Path: String): Boolean; begin Result := StrEqualNoCase(Protocol, protoFile) and (Host = '') and (Path <> ''); end; function TURLFileProtocol.GetContentReader(const Protocol, Host, Path: String; var ContentType: String): AReaderEx; begin ContentType := MIMEContentTypeFromExtention(ExtractFileExt(Path)); Result := TFileReader.Create(Path); end; function TURLFileProtocol.GetContentString(const Protocol, Host, Path: String; var Content, ContentType: String): Boolean; begin Content := ReadFileToStr(Path); ContentType := MIMEContentTypeFromExtention(ExtractFileExt(Path)); Result := True; end; var URLFileProtocol : AURLProtocol = nil; procedure RegisterURLFileProtocol; begin if Assigned(URLFileProtocol) then exit; URLFileProtocol := TURLFileProtocol.Create; RegisterURLProtocol(URLFileProtocol); end; { } { Self-testing code } { } {$ASSERTIONS ON} procedure SelfTest; var P, M, U : String; begin { DecodeURL } DecodeURL('http://abc.com/index.html', P, M, U); Assert((P = protoHTTP) and (M = 'abc.com') and (U = '/index.html'), 'DecodeURL'); DecodeURL('a://b.c/1/2/3', P, M, U); Assert((P = 'a') and (M = 'b.c') and (U = '/1/2/3'), 'DecodeURL'); DecodeURL('http://b:80/i.html', P, M, U); Assert((P = protoHTTP) and (M = 'b:80') and (U = '/i.html'), 'DecodeURL'); DecodeURL('mailto:a@b', P, M, U); Assert((P = protoEMail) and (M = 'a@b') and (U = ''), 'DecodeURL'); { EncodeURL } Assert(EncodeURL('http', 'abc.com', '/') = 'http://abc.com/', 'EncodeURL'); Assert(EncodeURL('news', 'a.b', '') = 'news:a.b', 'EncodeURL'); Assert(EncodeURL('https', 'abc.com', '/') = 'https://abc.com/', 'EncodeURL'); end; initialization finalization FreeAndNil(URLFileProtocol); end.
unit uInfoForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Buttons, StdCtrls, ComCtrls, ShellAPI, uFileVersion; type TInfoForm = class(TForm) sBackground: TShape; sbOk: TSpeedButton; iLogo: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; LbleMail: TLabel; LblWeb: TLabel; LblVersion: TLabel; Shape1: TShape; Shape2: TShape; Label5: TLabel; Label6: TLabel; Timer: TTimer; pInfo: TPanel; reLicense: TRichEdit; reHistory: TRichEdit; procedure sbOkClick(Sender: TObject); procedure LbleMailMouseEnter(Sender: TObject); procedure LbleMailMouseLeave(Sender: TObject); procedure LblWebMouseEnter(Sender: TObject); procedure LblWebMouseLeave(Sender: TObject); procedure LblWebClick(Sender: TObject); procedure LbleMailClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private _CanClose: Boolean; public procedure ShowInfo; procedure ShowSplash; end; implementation {$R *.dfm} procedure TInfoForm.sbOkClick(Sender: TObject); begin Close; end; procedure TInfoForm.LbleMailMouseEnter(Sender: TObject); begin LbleMail.Font.Color:= clBlue; LbleMail.Font.Style:= [fsUnderline]; end; procedure TInfoForm.LbleMailMouseLeave(Sender: TObject); begin LbleMail.Font.Color:= clBlack; LbleMail.Font.Style:= []; end; procedure TInfoForm.LblWebMouseEnter(Sender: TObject); begin LblWeb.Font.Color:= clBlue; LblWeb.Font.Style:= [fsUnderline]; end; procedure TInfoForm.LblWebMouseLeave(Sender: TObject); begin LblWeb.Font.Color:= clBlack; LblWeb.Font.Style:= []; end; procedure TInfoForm.LblWebClick(Sender: TObject); begin ShellExecute(Handle,'open','https://github.com/agebhar1/sim8008','','',SW_MAXIMIZE); end; procedure TInfoForm.LbleMailClick(Sender: TObject); begin ShellExecute(Handle,'open','mailto:agebhar1@googlemail.com?subject=SIM8008 Version 2','','',SW_NORMAL); end; procedure TInfoForm.FormCreate(Sender: TObject); var Major, Minor: Word; Release, Build: Word; begin Timer.Enabled:= false; GetFileVersion(PChar(Application.ExeName),Major,Minor,Release,Build); LblVersion.Caption:= 'Version '+IntToStr(Major)+'.'+IntToStr(Minor)+'.'+ IntToStr(Release)+'.'+IntToStr(Build); end; procedure TInfoForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:= _CanClose; end; procedure TInfoForm.TimerTimer(Sender: TObject); begin Timer.Enabled:= false; _CanClose:= true; Close; end; procedure TInfoForm.ShowInfo; begin AutoSize:= false; pInfo.Visible:= true; AutoSize:= true; Top:= (Screen.DesktopHeight - Height) div 2; Left:= (Screen.DesktopWidth - Width) div 2; _CanClose:= true; ShowModal; end; procedure TInfoForm.ShowSplash; begin AutoSize:= false; pInfo.Visible:= false; AutoSize:= true; Top:= (Screen.DesktopHeight - Height) div 2; Left:= (Screen.DesktopWidth - Width) div 2; _CanClose:= false; Timer.Enabled:= true; ShowModal; end; end.
unit uPrincipal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, System.Net.HttpClient, System.JSON, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient; type TForm2 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; memoToken: TMemo; memoMensagem: TMemo; memoLog: TMemo; Button1: TButton; IdTCPClient1: TIdTCPClient; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; Button2: TButton; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure IdSSLIOHandlerSocketOpenSSL1GetPassword(var Password: string); procedure FormCreate(Sender: TObject); private function HexToAscii(const AStrHexa: AnsiString): AnsiString; function GetMessage(const ADeviceToken, APayLoad: AnsiString): AnsiString; { Private declarations } public { Public declarations } Badge: integer; end; var Form2: TForm2; implementation {$R *.fmx} procedure TForm2.Button1Click(Sender: TObject); var vHttpClient : THttpClient; v_JSON : TJSONObject; v_JsonData : TJSONObject; v_RegisterIDs : TJSONArray; v_Data : TStringStream; v_Response : TStringStream; Token : String; CodigoProjeto : String; API : String; Link : String; RegisterIDs : TJSONArray; begin // Token := memoToken.Lines.Text; CodigoProjeto := '271332362079'; API := 'AIzaSyDgjOcWTVmmL9_JhVoXfo5Axngosqi-UoQ'; Link := 'https://android.googleapis.com/gcm/send'; try RegisterIDs := TJSONArray.Create; RegisterIDs.Add(Token); v_JsonData := TJSONObject.Create; v_JsonData.AddPair('id', CodigoProjeto); //obrigatório v_JsonData.AddPair('message', memoMensagem.Lines.Text); //obrigatório v_JsonData.AddPair('campo_extra', '123456'); v_JSON := TJSONObject.Create; v_JSON.AddPair('registration_ids', RegisterIDs); v_JSON.AddPair('data', v_JsonData); vHttpClient := THTTPClient.Create; vHttpClient.ContentType := 'application/json'; vHttpClient.CustomHeaders['Authorization'] := 'key=' + API; memoLog.Lines.Clear; memoLog.Lines.Add(v_JSON.ToString); v_Data := TStringStream.Create(v_JSON.ToString); v_Data.Position := 0; v_Response := TStringStream.Create; //Envio do Push vHttpClient.Post(Link, v_Data, v_Response); v_Response.Position := 0; memoLog.Lines.Add(v_Response.DataString); finally end; end; procedure TForm2.Button2Click(Sender: TObject); begin if not IdTCPClient1.Connected then begin IdTCPClient1.Connect; memoLog.Lines.Add('Conectado'); end; end; function TForm2.HexToAscii(const AStrHexa : AnsiString): AnsiString; var strLen : Integer; I: Integer; begin strLen := Length(AStrHexa) div 2; Result := ''; for I := 0 to strLen -1 do begin Result := Result + AnsiChar(Byte(StrToInt('$'+Copy(AStrHexa, (I*2)+1, 2)))); end; end; procedure TForm2.IdSSLIOHandlerSocketOpenSSL1GetPassword(var Password: string); begin Password := '0S6a3235'; end; procedure TForm2.Button3Click(Sender: TObject); var sToken : string; sMsg : AnsiString; StreamMsg : TStringStream; function GetPayLoad(const AAlert: AnsiString; const ABadge: Integer; const ASound: AnsiString): String; var AJsonAps : TJSONObject; AJsonPayLoad : TJSONObject; begin AJsonAps := TJSONObject.Create; AJsonAps.AddPair('alert', AAlert); AJsonAps.AddPair('badge', TJSONNumber.Create(ABadge)); AJsonAps.AddPair('sound', ASound); AJsonAps.AddPair('mensagem', AAlert); //AJsonAps.AddPair('extras', 'aaa'); AJsonPayLoad := TJSONObject.Create; AJsonPayLoad.AddPair('aps', AJsonAps); Result := AJsonPayLoad.ToString(); end; begin sToken := memoToken.Lines.Text; sMsg := memoMensagem.Lines.Text; if not IdTCPClient1.Connected then begin IdTCPClient1.Connect; memoLog.Lines.Add('Conectado'); end; sMsg := GetMessage(sToken, GetPayLoad(PAnsiChar(UTF8Encode(sMsg)), 1, 'default')); StreamMsg := TStringStream.Create(sMsg); IdTCPClient1.IOHandler.Write(StreamMsg); memoLog.Lines.Add('Enviado'); if IdTCPClient1.Connected then begin IdTCPClient1.Disconnect; memoLog.Lines.Add('Desconectado') end; end; function TForm2.GetMessage(const ADeviceToken : AnsiString; const APayLoad : AnsiString): AnsiString; begin Result := AnsiChar(0) + AnsiChar(0) + AnsiChar(32); // Cabecera del Mensaje Result := Result + HexToAscii(ADeviceToken) + AnsiChar(0) + AnsiChar(Length(APayLoad)) + APayLoad; end; procedure TForm2.Button4Click(Sender: TObject); begin if IdTCPClient1.Connected then begin IdTCPClient1.Disconnect; memoLog.Lines.Add('Desconectado') end; end; procedure TForm2.FormCreate(Sender: TObject); begin Badge := 1; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSRedBlackTree <p> USAGE The TRedBlackTree generic class behaves somewhat like a TList: it stores _Value_ by _Key_ and uses the same comparison function as TList.Sort (TListSortCompare). Functions Clear, Add, Delete, First and Last are equivalent, except that First and Last return a _Key_ so they can be used for comparisons in loops. All _Key_ occur only once in the tree if DuplicateKeys if False: when the same value is added twice, the second one is not stored. When DuplicateKeys is enabled the second comparison function is used for sort _Value_ and it duplicates not allowed. To be able to manage the tree, the Create constructor has a argument specifying the comparison function that should be used. The function Find can be used to find a _Value_ that was put in the tree, it searches for the given _Key_ using the comparison function given at time of object creation. The functions NextKey and PrevKey can be used to "walk" through the tree: given a _Key_, NextKey replace it with the smallest key that is larger than _Key_, PrevKey returns the largest key that is smaller than _Key_. For Last and First key result not returned. <b>History : </b><font size=-1><ul> <li>05/05/11 - Yar - Fugfixed method Add for Lazarus (unclear node's fields) <li>04/12/10 - Yar - Improved duplicate keys storing <li>04/08/10 - Yar - Fixed field section for FPC 2.5.1 (Bugtracker ID = 3039424) <li>19/04/10 - Yar - Creation (based on grbtree jzombi aka Jani Matyas) </ul></font><p> } unit GLSRedBlackTree; interface {$I GLScene.inc} uses Classes, GLCrossPlatform; type TRBColor = (clRed, clBlack); // TRedBlackTree // {$IFDEF GLS_GENERIC_PREFIX} generic {$ENDIF} GRedBlackTree < TKey, TValue > = class { Public Declarations } public type TKeyCompareFunc = function(const Item1, Item2: TKey): Integer; TValueCompareFunc = function(const Item1, Item2: TValue): Boolean; TForEachProc = procedure (AKey: TKey; AValue: TValue; out AContinue: Boolean); { Private Declarations } TRBNode = class Key: TKey; Left, Right, Parent, Twin: TRBNode; Color: TRBColor; Value: TValue; end; var FRoot: TRBNode; FLeftmost: TRBNode; FRightmost: TRBNode; FLastFound: TRBNode; FLastNode: TRBNode; FCount: Integer; FKeyCompareFunc: TKeyCompareFunc; FDuplicateKeys: Boolean; FValueCompareFunc: TValueCompareFunc; FOnChange: TNotifyEvent; function FindNode(const key: TKey): TRBNode; procedure RotateLeft(var x: TRBNode); procedure RotateRight(var x: TRBNode); function Minimum(var x: TRBNode): TRBNode; function Maximum(var x: TRBNode): TRBNode; function GetFirst: TKey; function GetLast: TKey; procedure SetDuplicateKeys(Value: Boolean); class procedure FastErase(x: TRBNode); public { Public Declarations } constructor Create(KeyCompare: TKeyCompareFunc; ValueCompare: TValueCompareFunc); destructor Destroy; override; procedure Clear; {: Find value by key. } function Find(const key: TKey; out Value: TValue): Boolean; function NextKey(var key: TKey; out Value: TValue): Boolean; function PrevKey(var key: TKey; out Value: TValue): Boolean; function NextDublicate(out Value: TValue): Boolean; procedure Add(const key: TKey; const Value: TValue); procedure Delete(const key: TKey); procedure ForEach(AProc: TForEachProc); property Count: Integer read FCount; property First: TKey read GetFirst; property Last: TKey read GetLast; property DuplicateKeys: Boolean read FDuplicateKeys write SetDuplicateKeys; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; function CompareInteger(const Item1, Item2: Integer): Integer; implementation function CompareInteger(const Item1, Item2: Integer): Integer; begin if Item1 < Item2 then begin Result := -1; end else if (Item1 = Item2) then begin Result := 0; end else begin Result := 1; end end; constructor GRedBlackTree < TKey, TValue > .Create(KeyCompare: TKeyCompareFunc; ValueCompare: TValueCompareFunc); begin inherited Create; Assert(Assigned(KeyCompare)); FKeyCompareFunc := KeyCompare; FValueCompareFunc := ValueCompare; FRoot := nil; FLeftmost := nil; FRightmost := nil; FDuplicateKeys := Assigned(ValueCompare); end; destructor GRedBlackTree < TKey, TValue >.Destroy; begin Clear; inherited Destroy; end; class procedure GRedBlackTree < TKey, TValue > .FastErase(x: TRBNode); var y: TRBNode; begin if (x.left <> nil) then FastErase(x.left); if (x.right <> nil) then FastErase(x.right); repeat y := x; x := x.Twin; y.Destroy; until x = nil; end; procedure GRedBlackTree < TKey, TValue > .Clear; begin if (FRoot <> nil) then FastErase(FRoot); FRoot := nil; FLeftmost := nil; FRightmost := nil; FCount := 0; if Assigned(FOnChange) then FOnChange(Self); end; function GRedBlackTree < TKey, TValue > .Find(const key: TKey; out Value: TValue): Boolean; begin FLastFound := FindNode(key); Result := Assigned(FLastFound); if Result then Value := FLastFound.Value; end; function GRedBlackTree < TKey, TValue > .FindNode(const key: TKey): TRBNode; var cmp: integer; begin Result := FRoot; while (Result <> nil) do begin cmp := FKeyCompareFunc(Result.Key, key); if cmp < 0 then begin Result := Result.right; end else if cmp > 0 then begin Result := Result.left; end else begin break; end; end; end; function GRedBlackTree < TKey, TValue > .NextDublicate(out Value: TValue): Boolean; begin if Assigned(FLastFound) then begin if Assigned(FLastFound.Twin) then begin FLastFound := FLastFound.Twin; Value := FLastFound.Value; exit(True); end; end; Result := False; end; procedure GRedBlackTree < TKey, TValue > .RotateLeft(var x: TRBNode); var y: TRBNode; begin y := x.right; x.right := y.left; if (y.left <> nil) then begin y.left.parent := x; end; y.parent := x.parent; if (x = FRoot) then begin FRoot := y; end else if (x = x.parent.left) then begin x.parent.left := y; end else begin x.parent.right := y; end; y.left := x; x.parent := y; end; procedure GRedBlackTree < TKey, TValue > .RotateRight(var x: TRBNode); var y: TRBNode; begin y := x.left; x.left := y.right; if (y.right <> nil) then begin y.right.parent := x; end; y.parent := x.parent; if (x = FRoot) then begin FRoot := y; end else if (x = x.parent.right) then begin x.parent.right := y; end else begin x.parent.left := y; end; y.right := x; x.parent := y; end; function GRedBlackTree < TKey, TValue > .Minimum(var x: TRBNode): TRBNode; begin Result := x; while (Result.left <> nil) do Result := Result.left; end; function GRedBlackTree < TKey, TValue > .Maximum(var x: TRBNode): TRBNode; begin Result := x; while (Result.right <> nil) do Result := Result.right; end; procedure GRedBlackTree < TKey, TValue > .Add(const key: TKey; const Value: TValue); var x, y, z, zpp: TRBNode; cmp: Integer; begin z := TRBNode.Create; { Initialize fields in new node z } z.Key := key; z.left := nil; z.right := nil; z.color := clRed; z.Value := Value; z.Twin := nil; { Maintain FLeftmost and FRightmost nodes } if ((FLeftmost = nil) or (FKeyCompareFunc(key, FLeftmost.Key) < 0)) then begin FLeftmost := z; end; if ((FRightmost = nil) or (FKeyCompareFunc(FRightmost.Key, key) < 0)) then begin FRightmost := z; end; {: Insert node z } y := nil; x := FRoot; while (x <> nil) do begin y := x; cmp := FKeyCompareFunc(key, x.Key); if cmp < 0 then x := x.left else if cmp > 0 then x := x.right else begin {: Key already exists in tree. } if FDuplicateKeys then begin {: Check twins chain for value dublicate. } repeat if FValueCompareFunc(Value, x.Value) then begin y := nil; break; end; y := x; x := x.Twin; until x = nil; if Assigned(y) then begin {: Add dublicate key to end of twins chain. } y.Twin := z; Inc(FCount); if Assigned(FOnChange) then FOnChange(Self); exit; end; {: Value already exists in tree. } end; z.Destroy; //a jzombi: memory leak: if we don't put it in the tree, we shouldn't hold it in the memory exit; end; end; z.parent := y; if (y = nil) then begin FRoot := z; end else if (FKeyCompareFunc(key, y.Key) < 0) then begin y.left := z; end else begin y.right := z; end; { Rebalance tree } while ((z <> FRoot) and (z.parent.color = clRed)) do begin zpp := z.parent.parent; if (z.parent = zpp.left) then begin y := zpp.right; if ((y <> nil) and (y.color = clRed)) then begin z.parent.color := clBlack; y.color := clBlack; zpp.color := clRed; z := zpp; end else begin if (z = z.parent.right) then begin z := z.parent; rotateLeft(z); end; z.parent.color := clBlack; zpp.color := clRed; rotateRight(zpp); end; end else begin y := zpp.left; if ((y <> nil) and (y.color = clRed)) then begin z.parent.color := clBlack; y.color := clBlack; zpp.color := clRed; //c jzombi: zpp.color := clRed; z := zpp; end else begin if (z = z.parent.left) then begin z := z.parent; rotateRight(z); end; z.parent.color := clBlack; zpp.color := clRed; //c jzombi: zpp.color := clRed; rotateLeft(zpp); end; end; end; FRoot.color := clBlack; Inc(FCount); if Assigned(FOnChange) then FOnChange(Self); end; procedure GRedBlackTree < TKey, TValue > .Delete(const key: TKey); var w, x, y, z, x_parent: TRBNode; tmpcol: TRBColor; begin z := FindNode(key); if z = nil then exit; y := z; x := nil; x_parent := nil; if (y.left = nil) then begin { z has at most one non-null child. y = z. } x := y.right; { x might be null. } end else begin if (y.right = nil) then begin { z has exactly one non-null child. y = z. } x := y.left; { x is not null. } end else begin { z has two non-null children. Set y to } y := y.right; { z's successor. x might be null. } while (y.left <> nil) do begin y := y.left; end; x := y.right; end; end; if (y <> z) then begin { "copy y's sattelite data into z" } { relink y in place of z. y is z's successor } z.left.parent := y; y.left := z.left; if (y <> z.right) then begin x_parent := y.parent; if (x <> nil) then begin x.parent := y.parent; end; y.parent.left := x; { y must be a child of left } y.right := z.right; z.right.parent := y; end else begin x_parent := y; end; if (FRoot = z) then begin FRoot := y; end else if (z.parent.left = z) then begin z.parent.left := y; end else begin z.parent.right := y; end; y.parent := z.parent; tmpcol := y.color; y.color := z.color; z.color := tmpcol; y := z; { y now points to node to be actually deleted } end else begin { y = z } x_parent := y.parent; if (x <> nil) then begin x.parent := y.parent; end; if (FRoot = z) then begin FRoot := x; end else begin if (z.parent.left = z) then begin z.parent.left := x; end else begin z.parent.right := x; end; end; if (FLeftmost = z) then begin if (z.right = nil) then begin { z.left must be null also } FLeftmost := z.parent; end else begin FLeftmost := minimum(x); end; end; if (FRightmost = z) then begin if (z.left = nil) then begin { z.right must be null also } FRightmost := z.parent; end else begin { x == z.left } FRightmost := maximum(x); end; end; end; { Rebalance tree } if (y.color = clBlack) then begin while ((x <> FRoot) and ((x = nil) or (x.color = clBlack))) do begin if (x = x_parent.left) then begin w := x_parent.right; if (w.color = clRed) then begin w.color := clBlack; x_parent.color := clRed; rotateLeft(x_parent); w := x_parent.right; end; if (((w.left = nil) or (w.left.color = clBlack)) and ((w.right = nil) or (w.right.color = clBlack))) then begin w.color := clRed; x := x_parent; x_parent := x_parent.parent; end else begin if ((w.right = nil) or (w.right.color = clBlack)) then begin w.left.color := clBlack; w.color := clRed; rotateRight(w); w := x_parent.right; end; w.color := x_parent.color; x_parent.color := clBlack; if (w.right <> nil) then begin w.right.color := clBlack; end; rotateLeft(x_parent); x := FRoot; { break; } end end else begin { same as above, with right <. left. } w := x_parent.left; if (w.color = clRed) then begin w.color := clBlack; x_parent.color := clRed; rotateRight(x_parent); w := x_parent.left; end; if (((w.right = nil) or (w.right.color = clBlack)) and ((w.left = nil) or (w.left.color = clBlack))) then begin w.color := clRed; x := x_parent; x_parent := x_parent.parent; end else begin if ((w.left = nil) or (w.left.color = clBlack)) then begin w.right.color := clBlack; w.color := clRed; rotateLeft(w); w := x_parent.left; end; w.color := x_parent.color; x_parent.color := clBlack; if (w.left <> nil) then begin w.left.color := clBlack; end; rotateRight(x_parent); x := FRoot; { break; } end; end; end; if (x <> nil) then begin x.color := clBlack; end; end; while Assigned(y.Twin) do begin z := y; y := y.Twin; z.Destroy; end; y.Destroy; Dec(FCount); if Assigned(FOnChange) then FOnChange(Self); end; function GRedBlackTree < TKey, TValue > .NextKey(var key: TKey; out Value: TValue): Boolean; var x, y: TRBNode; begin if Assigned(FLastNode) and (FKeyCompareFunc(FLastNode.Key, key) = 0) then x := FLastNode else x := FindNode(key); if x = nil then exit; if (x.right <> nil) then begin x := x.right; while (x.left <> nil) do begin x := x.left; end; end else if (x.parent <> nil) then begin y := x.parent; while Assigned(y) and (x = y.right) do begin x := y; y := y.parent; end; if (x.right <> y) then x := y; end else x := FRoot; if x = nil then exit(False); key := x.Key; FLastNode := x; Value := x.Value; Result := True; end; function GRedBlackTree < TKey, TValue > .PrevKey(var key: TKey; out Value: TValue): Boolean; var x, y: TRBNode; begin if Assigned(FLastNode) and (FKeyCompareFunc(FLastNode.Key, key) = 0) then x := FLastNode else x := FindNode(key); if x = nil then exit(False); if (x.left <> nil) then begin y := x.left; while (y.right <> nil) do begin y := y.right; end; x := y; end else if (x.parent <> nil) then begin y := x.parent; while (x = y.left) do begin x := y; y := y.parent; end; x := y; end else x := FRoot; if x = nil then exit(False); key := x.Key; FLastNode := x; Value := x.Value; Result := True; end; function GRedBlackTree < TKey, TValue > .GetFirst: TKey; begin Result := FLeftMost.Key; end; function GRedBlackTree < TKey, TValue > .GetLast: TKey; begin Result := FRightMost.Key; end; procedure GRedBlackTree < TKey, TValue > .ForEach(AProc: TForEachProc); var x, y, z: TRBNode; cont: Boolean; begin if Assigned(FLeftMost) then begin x := FLeftMost; repeat z := x; repeat AProc(z.Key, z.Value, cont); if not cont then exit; z := z.Twin; until z = nil; // Next node if (x.right <> nil) then begin x := x.right; while (x.left <> nil) do begin x := x.left; end; end else if (x.parent <> nil) then begin y := x.parent; while (x = y.right) do begin x := y; y := y.parent; end; if (x.right <> y) then x := y; end else x := FRoot; until x = FRightMost; if cont and (FLeftMost <> FRightMost) then AProc(FRightMost.Key, FRightMost.Value, cont); end; end; procedure GRedBlackTree < TKey, TValue > .SetDuplicateKeys(Value: Boolean); begin if Value and Assigned(FValueCompareFunc) then FDuplicateKeys := True else FDuplicateKeys := False; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.DbxCompressionFilter; interface uses Data.DBXTransport, System.SysUtils, Data.DBXPlatform ; type TTransportCompressionFilter = class(TTransportFilter) private FMinThreshold: Integer; protected function GetParameters: TDBXStringArray; override; function GetUserParameters: TDBXStringArray; override; public constructor Create; override; function ProcessInput(const Data: TArray<Byte>): TArray<Byte>; override; function ProcessOutput(const Data: TArray<Byte>): TArray<Byte>; override; function Id: string; override; function SetConfederateParameter(const ParamName: string; const ParamValue: string): Boolean; override; function GetParameterValue(const ParamName: string): string; override; function SetParameterValue(const ParamName: string; const ParamValue: string): Boolean; override; property MinThreshold: Integer read FMinThreshold write FMinThreshold; end; implementation uses System.Classes, System.ZLib ; { TTransportCompressionFilter } const cFilterUnit = 'FilterUnit'; cCompressionKickIn = 'CompressMoreThan'; cUnitName = 'DbxCompressionFilter'; cCompressedData = 1; cNoCompression = 2; cThreshold = 1024; constructor TTransportCompressionFilter.Create; begin inherited; FMinThreshold := cThreshold; end; function TTransportCompressionFilter.GetParameters: TDBXStringArray; begin SetLength(Result, 2); Result[0] := cFilterUnit; Result[1] := cCompressionKickIn; end; function TTransportCompressionFilter.GetParameterValue( const ParamName: string): string; begin if SameText(ParamName, cFilterUnit) then Result := cUnitName else if SameText(ParamName, cCompressionKickIn) then Result := IntToStr(FMinThreshold) else Result := EmptyStr; end; function TTransportCompressionFilter.GetUserParameters: TDBXStringArray; begin SetLength(Result, 1); Result[0] := cCompressionKickIn; end; function TTransportCompressionFilter.Id: string; begin Result := 'ZLibCompression' end; function TTransportCompressionFilter.ProcessOutput(const Data: TArray<Byte>): TArray<Byte>; var InStream: TBytesStream; ZStream: TDecompressionStream; Len: Int64; Buff: TArray<Byte>; begin Len := Length(Data)-1; if Data[0] = cCompressedData then begin SetLength(Buff, Len); Move(Data[1], Buff[0], Len); InStream := TBytesStream.Create(Buff); try InStream.Position := 0; ZStream := TDecompressionStream.Create(InStream); try Len := ZStream.Size; SetLength(Result, Len); ZStream.ReadBuffer(Result[0], Len); finally ZStream.Free; end; finally InStream.Free; end; end else begin SetLength(Result, Len); Move(Data[1], Result[0], Len); end; end; function TTransportCompressionFilter.ProcessInput(const Data: TArray<Byte>): TArray<Byte>; var OutStream: TMemoryStream; ZStream: TCompressionStream; Len: Int64; begin if Length(Data) > MinThreshold then begin OutStream := TMemoryStream.Create; try ZStream := TCompressionStream.Create(clFastest, OutStream); try ZStream.WriteBuffer(Data[0], Length(Data)); finally ZStream.Free; end; Len := OutStream.Size; SetLength(Result, Len+1); OutStream.Position := 0; OutStream.ReadBuffer(Result[1], Len); Result[0] := cCompressedData; finally OutStream.Free; end; end else begin SetLength(Result, Length(Data)+1); Move(Data[0], Result[1], Length(Data)); Result[0] := cNoCompression; end; end; function TTransportCompressionFilter.SetConfederateParameter(const ParamName, ParamValue: string): Boolean; begin Result := SetParameterValue(ParamName, ParamValue); end; function TTransportCompressionFilter.SetParameterValue(const ParamName, ParamValue: string): Boolean; begin if SameText(ParamName, cCompressionKickIn) then begin FMinThreshold := StrToInt(ParamValue); Result := true; end else Result := SameText(ParamName, cFilterUnit) and SameText(ParamValue, cUnitName); end; initialization TTransportFilterFactory.RegisterFilter(TTransportCompressionFilter); finalization TTransportFilterFactory.UnregisterFilter(TTransportCompressionFilter); end.
unit U_Temp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, U_Multi, U_Disp, U_Protocol, U_MyFunction, ExtCtrls, Spin; type TF_Temp = class(TForm) scrlbx0: TScrollBox; scrlbx1: TGroupBox; btn_write_param: TButton; scrlbx2: TGroupBox; btn_read_param: TBitBtn; scrlbx3: TGroupBox; chk_power_up_write: TCheckBox; chk_power_low_write: TCheckBox; chk_fan_up_write: TCheckBox; cbb_fan_up_write: TComboBox; chk_fan_low_write: TCheckBox; cbb_fan_low_write: TComboBox; chk_all_write: TCheckBox; edt_power_up_write: TEdit; edt_power_low_write: TEdit; chk_power_up_read: TCheckBox; chk_power_low_read: TCheckBox; chk_fan_up_read: TCheckBox; chk_fan_low_read: TCheckBox; chk_all_read: TCheckBox; edt_power_up_read: TEdit; edt_power_low_read: TEdit; edt_fan_up_read: TEdit; edt_fan_low_read: TEdit; chk_power_factor_read: TCheckBox; edt_power_factor_read: TEdit; chk_power_factor_write: TCheckBox; edt_power_factor_write: TEdit; chk_fan_limit_write: TCheckBox; cbb_fan_limit_write: TComboBox; chk_fan_limit_read: TCheckBox; edt_fan_limit_read: TEdit; procedure btn_read_paramClick(Sender: TObject); procedure btn_write_paramClick(Sender: TObject); procedure edt_ParamInput(Sender: TObject; var Key: Char); procedure chk_all_readClick(Sender: TObject); procedure chk_all_writeClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var F_Temp: TF_Temp; implementation uses U_Main; {$R *.dfm} procedure TF_Temp.btn_read_paramClick(Sender: TObject); var len, i, temp, data:Integer; p:PByte; strTmp:String; tmp_buf:array[0..24] of Byte; begin F_Temp.btn_read_param.Enabled := FALSE; // -------------------------------------------------------------------------- { 读电压上限 } if F_Temp.chk_power_up_read.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $07; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $01; //控制字 tmp_buf[6] := $00; //命令 tmp_buf[7] := $24; tmp_buf[8] := $00; tmp_buf[9] := $00; temp := 0; for i:=0 to 9 do begin temp := temp + tmp_buf[i]; end; tmp_buf[10] := temp and $ff; //CRC tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := $16; //尾 CommMakeFrame2(@tmp_buf, 13); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('读电压上限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; F_Temp.edt_power_up_read.Clear; //清除文本框 if tmp_buf[5] = $81 then //读操作成功 begin data := tmp_buf[10] or (tmp_buf[11] shl 8) or (tmp_buf[12] shl 16) or (tmp_buf[13] shl 24); strTmp := inttostr(data); F_Temp.edt_power_up_read.Text := strTmp; end else begin g_disp.DispLog('读电压上限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 读电压下限 } if F_Temp.chk_power_low_read.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $07; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $01; //控制字 tmp_buf[6] := $01; //命令 tmp_buf[7] := $24; tmp_buf[8] := $00; tmp_buf[9] := $00; temp := 0; for i:=0 to 9 do begin temp := temp + tmp_buf[i]; end; tmp_buf[10] := temp and $ff; //CRC tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := $16; //尾 CommMakeFrame2(@tmp_buf, 13); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('读电压下限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; F_Temp.edt_power_low_read.Clear; //清除文本框 if tmp_buf[5] = $81 then //读操作成功 begin data := tmp_buf[10] or (tmp_buf[11] shl 8) or (tmp_buf[12] shl 16) or (tmp_buf[13] shl 24); strTmp := inttostr(data); F_Temp.edt_power_low_read.Text := strTmp; end else begin g_disp.DispLog('读电压下限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 读温度(风扇)上限 } if F_Temp.chk_fan_up_read.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $07; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $01; //控制字 tmp_buf[6] := $00; //命令 tmp_buf[7] := $28; tmp_buf[8] := $00; tmp_buf[9] := $00; temp := 0; for i:=0 to 9 do begin temp := temp + tmp_buf[i]; end; tmp_buf[10] := temp and $ff; //CRC tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := $16; //尾 CommMakeFrame2(@tmp_buf, 13); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('读温度(风扇)上限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; F_Temp.edt_fan_up_read.Clear; //清除文本框 if tmp_buf[5] = $81 then //读操作成功 begin data := tmp_buf[10] or (tmp_buf[11] shl 8) or (tmp_buf[12] shl 16) or (tmp_buf[13] shl 24); strTmp := inttostr(data); F_Temp.edt_fan_up_read.Text := strTmp; end else begin g_disp.DispLog('读温度(风扇)上限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 读温度(风扇)下限 } if F_Temp.chk_fan_low_read.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $07; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $01; //控制字 tmp_buf[6] := $01; //命令 tmp_buf[7] := $28; tmp_buf[8] := $00; tmp_buf[9] := $00; temp := 0; for i:=0 to 9 do begin temp := temp + tmp_buf[i]; end; tmp_buf[10] := temp and $ff; //CRC tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := $16; //尾 CommMakeFrame2(@tmp_buf, 13); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('读温度(风扇)下限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; F_Temp.edt_fan_low_read.Clear; //清除文本框 if tmp_buf[5] = $81 then //读操作成功 begin data := tmp_buf[10] or (tmp_buf[11] shl 8) or (tmp_buf[12] shl 16) or (tmp_buf[13] shl 24); strTmp := inttostr(data); F_Temp.edt_fan_low_read.Text := strTmp; end else begin g_disp.DispLog('读温度(风扇)下限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 读温度(风扇)极限 } if F_Temp.chk_fan_limit_read.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $07; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $01; //控制字 tmp_buf[6] := $02; //命令 tmp_buf[7] := $28; tmp_buf[8] := $00; tmp_buf[9] := $00; temp := 0; for i:=0 to 9 do begin temp := temp + tmp_buf[i]; end; tmp_buf[10] := temp and $ff; //CRC tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := $16; //尾 CommMakeFrame2(@tmp_buf, 13); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('读温度(风扇)极限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; F_Temp.edt_fan_limit_read.Clear; //清除文本框 if tmp_buf[5] = $81 then //读操作成功 begin data := tmp_buf[10] or (tmp_buf[11] shl 8) or (tmp_buf[12] shl 16) or (tmp_buf[13] shl 24); strTmp := inttostr(data); F_Temp.edt_fan_limit_read.Text := strTmp; end else begin g_disp.DispLog('读温度(风扇)极限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 读电源电压校正因子 } if F_Temp.chk_power_factor_read.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $07; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $01; //控制字 tmp_buf[6] := $02; //命令 tmp_buf[7] := $24; tmp_buf[8] := $00; tmp_buf[9] := $00; temp := 0; for i:=0 to 9 do begin temp := temp + tmp_buf[i]; end; tmp_buf[10] := temp and $ff; //CRC tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := $16; //尾 CommMakeFrame2(@tmp_buf, 13); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('读电源电压校正因子'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; F_Temp.edt_power_factor_read.Clear; //清除文本框 if tmp_buf[5] = $81 then //读操作成功 begin data := tmp_buf[10] or (tmp_buf[11] shl 8) or (tmp_buf[12] shl 16) or (tmp_buf[13] shl 24); strTmp := inttostr(data); F_Temp.edt_power_factor_read.Text := strTmp; end else begin g_disp.DispLog('读电源电压校正因子失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- F_Temp.btn_read_param.Enabled := TRUE; end; procedure TF_Temp.btn_write_paramClick(Sender: TObject); var p:PByte; i, temp, len:Integer; tmp_buf:array[0..24] of Byte; begin F_Temp.btn_write_param.Enabled := FALSE; // -------------------------------------------------------------------------- { 写电压上限 } if F_Temp.chk_power_up_write.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $0B; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $04; //控制字 tmp_buf[6] := $00; //命令 tmp_buf[7] := $24; tmp_buf[8] := $00; tmp_buf[9] := $00; if edt_power_up_write.Text = '' then begin g_disp.DispLog('输入非法'); F_Temp.btn_write_param.Enabled := TRUE; Abort(); //中止程序的运行 end; temp := strtoint(edt_power_up_write.Text); //数据 tmp_buf[10] := temp and $ff; tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := (temp shr 16) and $ff; tmp_buf[13] := (temp shr 24) and $ff; temp := 0; for i:=0 to 12 do begin temp := temp + tmp_buf[i]; end; tmp_buf[14] := temp and $ff; //CRC tmp_buf[15] := (temp shr 8) and $ff; tmp_buf[16] := $16; //尾 CommMakeFrame2(@tmp_buf, 17); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('写电压上限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; if tmp_buf[5] = $84 then //写操作成功 begin g_disp.DispLog('写电压上限成功'); end else begin g_disp.DispLog('写电压上限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 写电压下限 } if F_Temp.chk_power_low_write.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $0B; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $04; //控制字 tmp_buf[6] := $01; //命令 tmp_buf[7] := $24; tmp_buf[8] := $00; tmp_buf[9] := $00; if edt_power_low_write.Text = '' then begin g_disp.DispLog('输入非法'); F_Temp.btn_write_param.Enabled := TRUE; Abort(); //中止程序的运行 end; temp := strtoint(edt_power_low_write.Text); //数据 tmp_buf[10] := temp and $ff; tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := (temp shr 16) and $ff; tmp_buf[13] := (temp shr 24) and $ff; temp := 0; for i:=0 to 12 do begin temp := temp + tmp_buf[i]; end; tmp_buf[14] := temp and $ff; //CRC tmp_buf[15] := (temp shr 8) and $ff; tmp_buf[16] := $16; //尾 CommMakeFrame2(@tmp_buf, 17); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('写电压下限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; if tmp_buf[5] = $84 then //写操作成功 begin g_disp.DispLog('写电压下限成功'); end else begin g_disp.DispLog('写电压下限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 写温度(风扇)上限 } if F_Temp.chk_fan_up_write.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $0B; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $04; //控制字 tmp_buf[6] := $00; //命令 tmp_buf[7] := $28; tmp_buf[8] := $00; tmp_buf[9] := $00; if cbb_fan_up_write.Text = '' then begin g_disp.DispLog('输入非法'); F_Temp.btn_write_param.Enabled := TRUE; Abort(); //中止程序的运行 end; temp := strtoint(cbb_fan_up_write.Text); //数据 tmp_buf[10] := temp and $ff; tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := (temp shr 16) and $ff; tmp_buf[13] := (temp shr 24) and $ff; temp := 0; for i:=0 to 12 do begin temp := temp + tmp_buf[i]; end; tmp_buf[14] := temp and $ff; //CRC tmp_buf[15] := (temp shr 8) and $ff; tmp_buf[16] := $16; //尾 CommMakeFrame2(@tmp_buf, 17); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('写温度(风扇)上限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; if tmp_buf[5] = $84 then //写操作成功 begin g_disp.DispLog('写温度(风扇)上限成功'); end else begin g_disp.DispLog('写温度(风扇)上限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 写温度(风扇)下限 } if F_Temp.chk_fan_low_write.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $0B; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $04; //控制字 tmp_buf[6] := $01; //命令 tmp_buf[7] := $28; tmp_buf[8] := $00; tmp_buf[9] := $00; if cbb_fan_low_write.Text = '' then begin g_disp.DispLog('输入非法'); F_Temp.btn_write_param.Enabled := TRUE; Abort(); //中止程序的运行 end; temp := strtoint(cbb_fan_low_write.Text); //数据 tmp_buf[10] := temp and $ff; tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := (temp shr 16) and $ff; tmp_buf[13] := (temp shr 24) and $ff; temp := 0; for i:=0 to 12 do begin temp := temp + tmp_buf[i]; end; tmp_buf[14] := temp and $ff; //CRC tmp_buf[15] := (temp shr 8) and $ff; tmp_buf[16] := $16; //尾 CommMakeFrame2(@tmp_buf, 17); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('写温度(风扇)下限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; if tmp_buf[5] = $84 then //写操作成功 begin g_disp.DispLog('写温度(风扇)下限成功'); end else begin g_disp.DispLog('写温度(风扇)下限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 写温度(风扇)极限 } if F_Temp.chk_fan_limit_write.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $0B; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $04; //控制字 tmp_buf[6] := $02; //命令 tmp_buf[7] := $28; tmp_buf[8] := $00; tmp_buf[9] := $00; if cbb_fan_limit_write.Text = '' then begin g_disp.DispLog('输入非法'); F_Temp.btn_write_param.Enabled := TRUE; Abort(); //中止程序的运行 end; temp := strtoint(cbb_fan_limit_write.Text); //数据 tmp_buf[10] := temp and $ff; tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := (temp shr 16) and $ff; tmp_buf[13] := (temp shr 24) and $ff; temp := 0; for i:=0 to 12 do begin temp := temp + tmp_buf[i]; end; tmp_buf[14] := temp and $ff; //CRC tmp_buf[15] := (temp shr 8) and $ff; tmp_buf[16] := $16; //尾 CommMakeFrame2(@tmp_buf, 17); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('写温度(风扇)极限'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; if tmp_buf[5] = $84 then //写操作成功 begin g_disp.DispLog('写温度(风扇)极限成功'); end else begin g_disp.DispLog('写温度(风扇)极限失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- { 写电源电压校正因子 } if F_Temp.chk_power_factor_write.Checked then begin tmp_buf[0] := $68; //头 tmp_buf[1] := $0B; //长度 tmp_buf[2] := $00; tmp_buf[3] := $00; //地址 tmp_buf[4] := $00; tmp_buf[5] := $04; //控制字 tmp_buf[6] := $02; //命令 tmp_buf[7] := $24; tmp_buf[8] := $00; tmp_buf[9] := $00; if edt_power_factor_write.Text = '' then begin g_disp.DispLog('输入非法'); F_Temp.btn_write_param.Enabled := TRUE; Abort(); //中止程序的运行 end; temp := strtoint(edt_power_factor_write.Text); //数据 tmp_buf[10] := temp and $ff; tmp_buf[11] := (temp shr 8) and $ff; tmp_buf[12] := (temp shr 16) and $ff; tmp_buf[13] := (temp shr 24) and $ff; temp := 0; for i:=0 to 12 do begin temp := temp + tmp_buf[i]; end; tmp_buf[14] := temp and $ff; //CRC tmp_buf[15] := (temp shr 8) and $ff; tmp_buf[16] := $16; //尾 CommMakeFrame2(@tmp_buf, 17); if F_Main.SendDataAuto() and CommWaitForResp() then begin g_disp.DispLog('写电源电压校正因子'); if CommRecved = True then begin CommRecved := False; p := GetCommRecvBufAddr(); len := GetCommRecvDataLen(); for i:=0 to len do begin tmp_buf[i] := p^; Inc(p); end; if tmp_buf[5] = $84 then //写操作成功 begin g_disp.DispLog('写电源电压校正因子成功'); end else begin g_disp.DispLog('写电源电压校正因子失败'); end; end else begin g_disp.DispLog('串口接收无数据'); end; end; end; // -------------------------------------------------------------------------- F_Temp.btn_write_param.Enabled := TRUE; end; procedure TF_Temp.edt_ParamInput(Sender: TObject; var Key: Char); begin if not(key in ['0'..'9', #8]) then //0 - 9, BackSpace begin key := #0; //输入置空 Beep(); //调用系统声音 end; end; procedure TF_Temp.chk_all_readClick(Sender: TObject); begin if F_Temp.chk_all_read.Checked then begin F_Temp.chk_power_up_read.Checked := TRUE; F_Temp.chk_power_low_read.Checked := TRUE; F_Temp.chk_fan_up_read.Checked := TRUE; F_Temp.chk_fan_low_read.Checked := TRUE; F_Temp.chk_fan_limit_read.Checked := TRUE; F_Temp.chk_power_factor_read.Checked := TRUE; end else begin F_Temp.chk_power_up_read.Checked := FALSE; F_Temp.chk_power_low_read.Checked := FALSE; F_Temp.chk_fan_up_read.Checked := FALSE; F_Temp.chk_fan_low_read.Checked := FALSE; F_Temp.chk_fan_limit_read.Checked := FALSE; F_Temp.chk_power_factor_read.Checked := FALSE; end; end; procedure TF_Temp.chk_all_writeClick(Sender: TObject); begin if F_Temp.chk_all_write.Checked then begin F_Temp.chk_power_up_write.Checked := TRUE; F_Temp.chk_power_low_write.Checked := TRUE; F_Temp.chk_fan_up_write.Checked := TRUE; F_Temp.chk_fan_low_write.Checked := TRUE; F_Temp.chk_fan_limit_write.Checked := TRUE; F_Temp.chk_power_factor_write.Checked := TRUE; end else begin F_Temp.chk_power_up_write.Checked := FALSE; F_Temp.chk_power_low_write.Checked := FALSE; F_Temp.chk_fan_up_write.Checked := FALSE; F_Temp.chk_fan_low_write.Checked := FALSE; F_Temp.chk_fan_limit_write.Checked := FALSE; F_Temp.chk_power_factor_write.Checked := FALSE; end; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.Helpers.Android; interface uses System.UITypes, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, FMX.Graphics; { Dialogs } procedure ShowDialog(ADialog: JDialog; const ADialogID: Integer); procedure HideDialog(ADialog: JDialog; const ADialogID: Integer); { Conversionse } function AlphaColorToJColor(const AColor: TAlphaColor): Integer; function BitmapToJBitmap(const ABitmap: TBitmap): JBitmap; function GetNativeTheme(const AOwner: TObject): Integer; implementation uses System.Classes, FMX.Helpers.Android, FMX.Platform.Android, FMX.Surfaces, FMX.Forms, FMX.Styles, FMX.Controls, FGX.Asserts, System.SysUtils; procedure ShowDialog(ADialog: JDialog; const ADialogID: Integer); begin if IsGingerbreadDevice then MainActivity.showDialog(ADialogID, ADialog) else ADialog.show; end; procedure HideDialog(ADialog: JDialog; const ADialogID: Integer); begin if IsGingerbreadDevice then begin MainActivity.dismissDialog(ADialogID); MainActivity.removeDialog(ADialogID); end else ADialog.dismiss; end; function AlphaColorToJColor(const AColor: TAlphaColor): Integer; begin Result := TJColor.JavaClass.argb(TAlphaColorRec(AColor).A, TAlphaColorRec(AColor).R, TAlphaColorRec(AColor).G, TAlphaColorRec(AColor).B) end; function BitmapToJBitmap(const ABitmap: TBitmap): JBitmap; var BitmapSurface: TBitmapSurface; begin AssertIsNotNil(ABitmap); Result := TJBitmap.JavaClass.createBitmap(ABitmap.Width, ABitmap.Height, TJBitmap_Config.JavaClass.ARGB_8888); BitmapSurface := TBitmapSurface.Create; try BitmapSurface.Assign(ABitmap); if not SurfaceToJBitmap(BitmapSurface, Result) then Result := nil; finally BitmapSurface.Free; end; end; function FindForm(const AOwner: TObject): TCommonCustomForm; var OwnerTmp: TComponent; begin Result := nil; if AOwner is TComponent then begin OwnerTmp := TComponent(AOwner); while not (OwnerTmp is TCommonCustomForm) and (OwnerTmp <> nil) do OwnerTmp := OwnerTmp.Owner; if OwnerTmp is TCommonCustomForm then Result := TCommonCustomForm(OwnerTmp); end; end; const ANDROID_LIGHT_THEME = '[LIGHTSTYLE]'; ANDROID_DARK_THEME = '[DARKSTYLE]'; function IsGingerbreadDevice: Boolean; begin Result := TOSVersion.Major = 2; end; function GetThemeFromDescriptor(ADescriptor: TStyleDescription): Integer; begin Result := 0; if ADescriptor <> nil then begin if ADescriptor.PlatformTarget.Contains(ANDROID_LIGHT_THEME) then Result := TJAlertDialog.JavaClass.THEME_HOLO_LIGHT; if ADescriptor.PlatformTarget.Contains(ANDROID_DARK_THEME) then Result := TJAlertDialog.JavaClass.THEME_HOLO_DARK; end; end; function GetNativeTheme(const AOwner: TObject): Integer; var Form: TCommonCustomForm; LStyleDescriptor: TStyleDescription; begin Form := FindForm(AOwner); if Form <> nil then begin if Form.StyleBook <> nil then LStyleDescriptor := TStyleManager.FindStyleDescriptor(Form.StyleBook.Style) else LStyleDescriptor := TStyleManager.FindStyleDescriptor(TStyleManager.ActiveStyleForScene(Form as IScene)); Result := GetThemeFromDescriptor(LStyleDescriptor); end else Result := TJAlertDialog.JavaClass.THEME_HOLO_LIGHT; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FMX.FontGlyphs.iOS; interface {$SCOPEDENUMS ON} uses System.Types, System.Classes, System.SysUtils, System.UITypes, System.UIConsts, System.Generics.Collections, System.Generics.Defaults, Macapi.ObjectiveC, Macapi.CoreFoundation, iOSapi.CocoaTypes, iOSapi.CoreGraphics, iOSapi.Foundation, iOSapi.CoreText, iOSapi.UIKit, FMX.Types, FMX.Surfaces, FMX.FontGlyphs; type TIOSFontGlyphManager = class(TFontGlyphManager) const BoundsLimit = $FFFF; private FColorSpace: CGColorSpaceRef; FFontRef: CTFontRef; FDefaultBaseline: Single; FDefaultVerticalAdvance: Single; procedure GetDefaultBaseline; function GetPostScriptFontName: CFStringRef; protected procedure LoadResource; override; procedure FreeResource; override; function DoGetGlyph(const Char: UCS4Char; const Settings: TFontGlyphSettings): TFontGlyph; override; function DoGetBaseline: Single; override; public constructor Create; destructor Destroy; override; end; implementation uses System.Math, System.Character, System.Math.Vectors, FMX.Graphics, FMX.Consts, FMX.Utils, Macapi.Helpers; { TIOSFontGlyphManager } constructor TIOSFontGlyphManager.Create; begin inherited Create; FColorSpace := CGColorSpaceCreateDeviceRGB; end; destructor TIOSFontGlyphManager.Destroy; begin CGColorSpaceRelease(FColorSpace); inherited; end; procedure TIOSFontGlyphManager.LoadResource; const //Rotating matrix to simulate Italic font attribute ItalicMatrix: CGAffineTransform = ( a: 1; b: 0; c: 0.176326981; //~tan(10 degrees) d: 1; tx: 0; ty: 0 ); var NewFontRef: CTFontRef; Matrix: PCGAffineTransform; begin Matrix := nil; FFontRef := CTFontCreateWithName(GetPostScriptFontName, CurrentSettings.Size * CurrentSettings.Scale, nil); try if TFontStyle.fsItalic in CurrentSettings.Style then begin NewFontRef := CTFontCreateCopyWithSymbolicTraits(FFontRef, 0, nil, kCTFontItalicTrait, kCTFontItalicTrait); if NewFontRef <> nil then begin CFRelease(FFontRef); FFontRef := NewFontRef; end else begin Matrix := @ItalicMatrix; //Font has no Italic version, applying transform matrix NewFontRef := CTFontCreateWithName(GetPostScriptFontName, CurrentSettings.Size * CurrentSettings.Scale, @ItalicMatrix); if NewFontRef <> nil then begin CFRelease(FFontRef); FFontRef := NewFontRef; end; end; end; if TFontStyle.fsBold in CurrentSettings.Style then begin NewFontRef := CTFontCreateCopyWithSymbolicTraits(FFontRef, 0, Matrix, kCTFontBoldTrait, kCTFontBoldTrait); if NewFontRef <> nil then begin CFRelease(FFontRef); FFontRef := NewFontRef; end; end; // GetDefaultBaseline; except CFRelease(FFontRef); end; end; procedure TIOSFontGlyphManager.FreeResource; begin if FFontRef <> nil then CFRelease(FFontRef); end; procedure TIOSFontGlyphManager.GetDefaultBaseline; var Chars: string; Str: CFStringRef; Frame: CTFrameRef; Attr: CFMutableAttributedStringRef; Path: CGMutablePathRef; Bounds: CGRect; FrameSetter: CTFramesetterRef; // Metrics Line: CTLineRef; Lines: CFArrayRef; Runs: CFArrayRef; Run: CTRunRef; Ascent, Descent, Leading: CGFloat; BaseLinePos: CGPoint; begin Path := CGPathCreateMutable(); Bounds := CGRectMake(0, 0, BoundsLimit, BoundsLimit); CGPathAddRect(Path, nil, Bounds); if TOSVersion.Check(9) then // yangyxd Chars := 'жа' else Chars := 'a'; Str := CFStringCreateWithCharacters(kCFAllocatorDefault, PChar(Chars), 1); Attr := CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); CFAttributedStringReplaceString(Attr, CFRangeMake(0, 0), Str); CFAttributedStringBeginEditing(Attr); try // Font if FFontRef <> nil then CFAttributedStringSetAttribute(Attr, CFRangeMake(0, 1), kCTFontAttributeName, FFontRef); finally CFAttributedStringEndEditing(Attr); end; FrameSetter := CTFramesetterCreateWithAttributedString(CFAttributedStringRef(Attr)); CFRelease(Attr); Frame := CTFramesetterCreateFrame(FrameSetter, CFRangeMake(0, 0), Path, nil); CFRelease(FrameSetter); CFRelease(Str); // Metrics Lines := CTFrameGetLines(Frame); Line := CTLineRef(CFArrayGetValueAtIndex(Lines, 0)); Runs := CTLineGetGlyphRuns(Line); Run := CFArrayGetValueAtIndex(Runs, 0); CTRunGetTypographicBounds(Run, CFRangeMake(0, 1), @Ascent, @Descent, @Leading); CTFrameGetLineOrigins(Frame, CFRangeMake(0, 0), @BaseLinePos); FDefaultBaseline := BoundsLimit - BaseLinePos.y; FDefaultVerticalAdvance := FDefaultBaseline + Descent; CFRelease(Frame); CFRelease(Path); end; function TIOSFontGlyphManager.GetPostScriptFontName: CFStringRef; var LUIFont: UIFont; LocalObject: ILocalObject; begin Result := nil; LUIFont := TUIFont.Wrap(TUIFont.OCClass.fontWithName(StrToNSStr(CurrentSettings.Family), CurrentSettings.Size * CurrentSettings.Scale)); if Supports(LUIFont, ILocalObject, LocalObject) then Result := CTFontCopyPostScriptName(LocalObject.GetObjectID); if Result = nil then //In case there is no direct name for the requested font returns source name and let CoreText to select appropriate font Result := CFSTR(CurrentSettings.Family); end; procedure PathApplierFunction(info: Pointer; const element: PCGPathElement); cdecl; var P, P1, P2: PCGPoint; begin P := element^.points; case element.type_ of kCGPathElementMoveToPoint: TPathData(info).MoveTo(TPointF.Create(P.x, P.y)); kCGPathElementAddLineToPoint: TPathData(info).LineTo(TPointF.Create(P.x, P.y)); kCGPathElementAddQuadCurveToPoint: begin P1 := P; Inc(P1); TPathData(info).QuadCurveTo(TPointF.Create(P.x, P.y), TPointF.Create(P1.x, P1.y)); end; kCGPathElementAddCurveToPoint: begin P1 := P; Inc(P1); P2 := P1; Inc(P2); TPathData(info).CurveTo(TPointF.Create(P.x, P.y), TPointF.Create(P1.x, P1.y), TPointF.Create(P2.x, P2.y)); end; kCGPathElementCloseSubpath: TPathData(info).ClosePath; end; end; function TIOSFontGlyphManager.DoGetBaseline: Single; begin Result := FDefaultBaseline; end; function TIOSFontGlyphManager.DoGetGlyph(const Char: UCS4Char; const Settings: TFontGlyphSettings): TFontGlyph; var CharsString: string; CharsStringLength: Integer; Str: CFStringRef; Frame: CTFrameRef; Attr: CFMutableAttributedStringRef; Path: CGMutablePathRef; Bounds: CGRect; Rgba: array [0..3] of CGFloat; TextColor: CGColorRef; FrameSetter: CTFramesetterRef; Context: CGContextRef; I, J: Integer; Color: TAlphaColorRec; C: Byte; GlyphRect: TRect; // Metrics Line: CTLineRef; Lines: CFArrayRef; Runs: CFArrayRef; Run: CTRunRef; Ascent, Descent, Leading: CGFloat; Size: CGSize; GlyphStyle: TFontGlyphStyles; BaseLinePos: CGPoint; BaseLineOffset: Single; // RunGlyphCount: CFIndex; glyph: CGGlyph; glyphMatrix: CGAffineTransform; position: CGPoint; glyphPath: CGPathRef; M: TMatrix; LImageChar: Boolean; Bits: PAlphaColorRecArray; ContextSize: TSize; begin LImageChar := ((Char >= $1F000) and (Char <= $1F0FF)) or ((Char >= $1F170) and (Char <= $1F19F)) or ((Char >= $1F200) and (Char <= $1F2FF)) or ((Char >= $1F300) and (Char <= $1F5FF)) or ((Char >= $1F600) and (Char <= $1F64F)) or ((Char >= $1F680) and (Char <= $1F6FF)) or ((Char >= $1F700) and (Char <= $1F77F)) or (Char = $2139) or ((Char >= $2190) and (Char <= $21FF)) or ((Char >= $2300) and (Char <= $23FF)) or ((Char >= $2460) and (Char <= $24FF)) or ((Char >= $25A0) and (Char <= $25FF)) or ((Char >= $2600) and (Char <= $26FF)) or ((Char >= $2700) and (Char <= $27BF)) or ((Char >= $27C0) and (Char <= $27EF)) or ((Char >= $27F0) and (Char <= $27FF)) or ((Char >= $2900) and (Char <= $297F)) or ((Char >= $2B00) and (Char <= $2BFF)) or ((Char >= $3200) and (Char <= $32FF)); Path := CGPathCreateMutable(); Bounds := CGRectMake(0, 0, BoundsLimit, BoundsLimit); CGPathAddRect(Path, nil, Bounds); CharsString := System.Char.ConvertFromUtf32(Char); CharsStringLength := CharsString.Length; Str := CFStringCreateWithCharacters(kCFAllocatorDefault, PChar(CharsString), CharsStringLength); Attr := CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); CFAttributedStringReplaceString(Attr, CFRangeMake(0, 0), Str); CFAttributedStringBeginEditing(Attr); try // Font if FFontRef <> nil then CFAttributedStringSetAttribute(Attr, CFRangeMake(0, CharsStringLength), kCTFontAttributeName, FFontRef); // Color Rgba[0] := 1; Rgba[1] := 1; Rgba[2] := 1; Rgba[3] := 1; TextColor := CGColorCreate(FColorSpace, @Rgba[0]); try CFAttributedStringSetAttribute(Attr, CFRangeMake(0, CharsStringLength), kCTForegroundColorAttributeName, TextColor); finally CFRelease(TextColor); end; finally CFAttributedStringEndEditing(Attr); end; FrameSetter := CTFramesetterCreateWithAttributedString(CFAttributedStringRef(Attr)); CFRelease(Attr); Frame := CTFramesetterCreateFrame(FrameSetter, CFRangeMake(0, 0), Path, nil); CFRelease(FrameSetter); CFRelease(Str); // Metrics Context := CGBitmapContextCreate(nil, 1, 1, 8, 4, FColorSpace, kCGImageAlphaPremultipliedLast); try Lines := CTFrameGetLines(Frame); Line := CTLineRef(CFArrayGetValueAtIndex(Lines, 0)); Runs := CTLineGetGlyphRuns(Line); Run := CFArrayGetValueAtIndex(Runs, 0); Bounds := CTRunGetImageBounds(Run, Context, CFRangeMake(0, 1)); CTRunGetAdvances(Run, CFRangeMake(0, 1), @Size); CTRunGetTypographicBounds(Run, CFRangeMake(0, 1), @Ascent, @Descent, @Leading); GlyphRect := Rect(Trunc(Bounds.origin.x), Max(Trunc(Ascent - Bounds.origin.y - Bounds.size.height) - 1, 0), Ceil(Bounds.origin.x + Bounds.size.width), Round(Ascent + Descent + Descent)); CTFrameGetLineOrigins(Frame, CFRangeMake(0, 0), @BaseLinePos); BaseLineOffset := BoundsLimit - BaseLinePos.y; GlyphStyle := []; if ((Bounds.size.width = 0) and (Bounds.size.height = 0)) or not HasGlyph(Char) then GlyphStyle := [TFontGlyphStyle.NoGlyph]; if TFontGlyphSetting.Path in Settings then GlyphStyle := GlyphStyle + [TFontGlyphStyle.HasPath]; if LImageChar then GlyphStyle := GlyphStyle + [TFontGlyphStyle.ColorGlyph]; finally CGContextRelease(Context); end; Result := TFontGlyph.Create(Point(GlyphRect.Left, GlyphRect.Top), Size.width, Round(FDefaultVerticalAdvance), GlyphStyle); if (TFontGlyphSetting.Bitmap in Settings) and (HasGlyph(Char) or ((Bounds.size.width > 0) and (Bounds.size.height > 0))) then begin ContextSize := TSize.Create(Max(GlyphRect.Right, GlyphRect.Width), GlyphRect.Bottom); Context := CGBitmapContextCreate(nil, ContextSize.Width, ContextSize.Height, 8, ContextSize.Width * 4, FColorSpace, kCGImageAlphaPremultipliedLast); try Bits := PAlphaColorRecArray(CGBitmapContextGetData(Context)); if GlyphRect.Left < 0 then CGContextTranslateCTM(Context, -GlyphRect.Left, 0); CGContextTranslateCTM(Context, 0, -(BoundsLimit - ContextSize.Height)); if not SameValue(FDefaultBaseline - BaseLineOffset, 0, TEpsilon.Position) then CGContextTranslateCTM(Context, 0, -Abs(FDefaultBaseline - BaseLineOffset)); CTFrameDraw(Frame, Context); Result.Bitmap.SetSize(GlyphRect.Width, GlyphRect.Height, TPixelFormat.BGRA); if TFontGlyphSetting.PremultipliedAlpha in Settings then begin for I := GlyphRect.Top to GlyphRect.Bottom - 1 do Move(Bits^[I * ContextSize.Width + Max(GlyphRect.Left, 0)], Result.Bitmap.GetPixelAddr(0, I - GlyphRect.Top)^, Result.Bitmap.Pitch); end else for I := GlyphRect.Left to GlyphRect.Right - 1 do for J := GlyphRect.Top to GlyphRect.Bottom - 1 do begin Color := Bits[J * ContextSize.Width + Max(I, 0)]; if Color.R > 0 then begin C := (Color.R + Color.G + Color.B) div 3; Result.Bitmap.Pixels[I - GlyphRect.Left, J - GlyphRect.Top] := MakeColor($FF, $FF, $FF, C); end end; finally CGContextRelease(Context); end; end; //Path if TFontGlyphSetting.Path in Settings then begin RunGlyphCount := CTRunGetGlyphCount(Run); for I := 0 to RunGlyphCount - 1 do begin CTRunGetGlyphs(Run, CFRangeMake(I, 1), @glyph); CTRunGetPositions(run, CFRangeMake(I, 1), @position); glyphMatrix := CGAffineTransformTranslate(CGAffineTransformIdentity, position.x, position.y); glyphPath := CTFontCreatePathForGlyph(FFontRef, glyph, @glyphMatrix); if glyphPath <> nil then begin CGPathApply(glyphPath, Result.Path, @PathApplierFunction); CFRelease(glyphPath); end; end; M := TMatrix.Identity; M.m22 := -1; Result.Path.ApplyMatrix(M); end; CFRelease(Frame); CFRelease(Path); end; end.
unit TestClasses; interface uses Generics.Collections, Classes; type TQuizPart = (qpnone, qpListening, qpWriting, qpSpeaking, qpReading); TTest = class private public Idx: integer; Title: string; end; TQuizNumber = class private public QuizNumber: integer; end; TQuiz = class(TQuizNumber) private public Quiz: string; end; TLRQuiz = class(TQuiz) private public QuizIdx: Integer; A, B, C, D: string; Answer: string; end; TReading = class private public ExampleIdx: Integer; TestIdx: Integer; ExampleNumber: Integer; ExampleText: string; QuizList: TObjectList<TQuiz>; constructor Create; destructor Destroy; override; end; TListening = class(TLRQuiz) private public Idx: integer; SoundAdress: string; end; TSpeaking = class(TQuiz) private public Idx: integer; // test_idx ?? quiz_idx QuizIdx: Integer; // quiz_idx; SoundAdress: string; ResponseTime : integer; end; TWriting = class(TQuiz) private public Idx: integer; ExampleText: string; SoundAdress: string; end; const //qpnone, qpListening, qpWriting, qpSpeaking, qpReading PartName : array [0..4] of string = ('Invalid','Listening', 'Writing', 'Speaking', 'Reading'); implementation { TReading } constructor TReading.Create; begin QuizList := TObjectList<TQuiz>.Create; end; destructor TReading.Destroy; begin QuizList.Free; inherited; end; end.
unit UProperties; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Controls, StdCtrls, typinfo, Spin, ExtCtrls, UFigures; const PenStyles: array [0..4] of TPenStyle = (psSolid, psDash, psDot, psDashDot, psDashDotDot); BrushStyles: array [0..7] of TBrushStyle = (bsClear, bsSolid, bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross); type TInvalidateEvent = procedure of object; { TProperty } TProperty = class class procedure SetDefaultProperties(AFigures: array of TFigure); virtual; abstract; class procedure CreateLabel(AOwner: TPanel; ACaption: String); class procedure CreateControls(AOwner: TPanel); virtual; abstract; end; { TPenProperty } TPenProperty = class(TProperty) private class var FPenColor: TColor; FPenSize: Integer; FPenStyle: TPenStyle; class procedure PenSizeChanged(Sender: TObject); class procedure PenStyleChanged(Sender: TObject); class procedure DrawComboBoxPenItem(Control: TWinControl; index: Integer; ARect: TRect; State: TOwnerDrawState); public class procedure SetDefaultProperties(AFigures: array of TFigure); override; class procedure SetPenColor(AColor: TColor); class procedure SetPenSize(ASize: Integer); class procedure SetPenStyle(AStyle: TPenStyle); class procedure CreateControls(AOwner: TPanel); override; end; { TBrushProperty } TBrushProperty = class(TProperty) private class var FBrushColor: TColor; FBrushStyle: TBrushStyle; class procedure BrushStyleChanged(Sender: TObject); class procedure DrawComboBoxBrushItem(Control: TWinControl; index: Integer; ARect: TRect; State: TOwnerDrawState); public class procedure SetDefaultProperties(AFigures: array of TFigure); override; class procedure SetBrushColor(AColor: TColor); class procedure SetBrushStyle(AStyle: TBrushStyle); class procedure CreateControls(AOwner: TPanel); override; end; { TRoundProperty } TRoundProperty = class(TProperty) private class var FX, FY: Integer; class procedure XChanged(Sender: TObject); class procedure YChanged(Sender: TObject); public class procedure SetX(AX: Integer); class procedure SetY(AY: Integer); class procedure SetDefaultProperties(AFigures: array of TFigure); override; class procedure CreateControls(AOwner: TPanel); override; end; procedure ResetIndentY; procedure InitProperties; var Indent: TPoint; ValidEvent: TInvalidateEvent; implementation procedure SetProperty(AFigure: TFigure; APropName: String; AValue: Variant); begin if (IsPublishedProp(AFigure, APropName)) then SetPropValue(AFigure, APropName, AValue); end; { TProperty } class procedure TProperty.CreateLabel(AOwner: TPanel; ACaption: String); begin with TLabel.Create(AOwner) do begin Parent := AOwner; Top := 10 + Indent.y * 30; Left := 10; Caption := ACaption; Indent.x := Width; end; end; { TPenProperty } class procedure TPenProperty.CreateControls(AOwner: TPanel); var i: Integer; begin CreateLabel(AOwner, 'Тип кисти: '); with TComboBox.Create(AOwner) do begin Parent := AOwner; Top := 10 + Indent.y * 30; Left := 20 + Indent.x; Width := 130; OnChange := @PenStyleChanged; Style := csOwnerDrawFixed; ReadOnly := True; OnDrawItem := @DrawComboBoxPenItem; for i := 0 to High(PenStyles) do Items.Add(''); for i := 0 to High(PenStyles) do if (PenStyles[i] = FPenStyle) then ItemIndex := i else ItemIndex := 0; Name := 'PenComboBox'; end; Inc(Indent.y); CreateLabel(AOwner, 'Толщина: '); with TSpinEdit.Create(AOwner) do begin Parent := AOwner; Top := 10 + Indent.y * 30; Left := 30 + Indent.x; Width := 121; Value := FPenSize; OnChange := @PenSizeChanged; Name := 'PenSizeSpin'; end; Inc(Indent.y); end; class procedure TPenProperty.SetPenColor(AColor: TColor); var F: TFigure; begin FPenColor := AColor; for F in Figures do if (F.Selected) then SetProperty(F, 'PenColor', FPenColor); ValidEvent; end; class procedure TPenProperty.SetPenSize(ASize: Integer); var F: TFigure; begin FPenSize := ASize; for F in Figures do if (F.Selected) then SetProperty(F, 'PenSize', FPenSize); ValidEvent; end; class procedure TPenProperty.SetPenStyle(AStyle: TPenStyle); var F: TFigure; begin FPenStyle := AStyle; for F in Figures do if (F.Selected) then SetProperty(F, 'PenStyle', FPenStyle); ValidEvent; end; class procedure TPenProperty.PenSizeChanged(Sender: TObject); begin with Sender as TSpinEdit do SetPenSize(Value); end; class procedure TPenProperty.PenStyleChanged(Sender: TObject); begin with Sender as TComboBox do SetPenStyle(PenStyles[ItemIndex]); end; class procedure TPenProperty.DrawComboBoxPenItem(Control: TWinControl; index: Integer; ARect: TRect; State: TOwnerDrawState); begin with (Control as TComboBox) do begin with Canvas do begin FillRect(ARect); Pen.Style := PenStyles[index]; Pen.Color := clBlack; Line(ARect.Left, ARect.Top + (ARect.Bottom - ARect.Top) div 2, ARect.Right, ARect.Top + (ARect.Bottom - ARect.Top) div 2); end; end; end; class procedure TPenProperty.SetDefaultProperties(AFigures: array of TFigure); var F: TFigure; begin for F in AFigures do begin if (F.Selected) then begin SetProperty(F, 'PenColor', FPenColor); SetProperty(F, 'PenSize', FPenSize); SetProperty(F, 'PenStyle', FPenStyle); end; end; ValidEvent; end; { TBrushProperty } class procedure TBrushProperty.CreateControls(AOwner: TPanel); var i: Integer; begin CreateLabel(AOwner, 'Тип заливки: '); with TComboBox.Create(AOwner) do begin Parent := AOwner; Top := 10 + Indent.y * 30; Left := 20 + Indent.x; Width := 117; Style := csOwnerDrawFixed; ReadOnly := True; OnChange := @BrushStyleChanged; OnDrawItem := @DrawComboBoxBrushItem; for i := 0 to High(BrushStyles) do Items.Add(''); for i := 0 to High(BrushStyles) do if (BrushStyles[i] = FBrushStyle) then ItemIndex := i else ItemIndex := 0; Name := 'BrushComboBox'; end; Inc(Indent.y); end; class procedure TBrushProperty.SetBrushColor(AColor: TColor); var F: TFigure; begin FBrushColor := AColor; for F in Figures do if (F.Selected) then SetProperty(F, 'BrushColor', FBrushColor); ValidEvent; end; class procedure TBrushProperty.SetBrushStyle(AStyle: TBrushStyle); var F: TFigure; begin FBrushStyle := AStyle; for F in Figures do if (F.Selected) then SetProperty(F, 'BrushStyle', FBrushStyle); ValidEvent; end; class procedure TBrushProperty.BrushStyleChanged(Sender: TObject); begin with Sender as TComboBox do SetBrushStyle(BrushStyles[ItemIndex]); end; class procedure TBrushProperty.DrawComboBoxBrushItem(Control: TWinControl; index: Integer; ARect: TRect; State: TOwnerDrawState); begin with (Control as TComboBox) do begin with Canvas do begin FillRect(ARect); Brush.Style := BrushStyles[index]; if (BrushStyles[index] <> bsClear) then Brush.Color := clBlack; FillRect(ARect); end; end; end; class procedure TBrushProperty.SetDefaultProperties(AFigures: array of TFigure); var F: TFigure; begin for F in AFigures do begin if (F.Selected) then begin SetProperty(F, 'BrushColor', FBrushColor); SetProperty(F, 'BrushStyle', FBrushStyle); end; end; end; { TRoundProperty } class procedure TRoundProperty.CreateControls(AOwner: TPanel); begin CreateLabel(AOwner, 'Скругление (Х, Y): '); with TSpinEdit.Create(AOwner) do begin MinValue := 1; MaxValue := 100; Value := FX; Parent := AOwner; Top := 10 + Indent.y * 30; Left := 20 + Indent.x; Width := 45; Indent.x += Width; OnChange := @XChanged; Name := 'RXSpinBox'; end; with TSpinEdit.Create(AOwner) do begin MinValue := 1; MaxValue := 100; Value := FY; Parent := AOwner; Top := 10 + Indent.y * 30; Left := 20 + Indent.x; Width := 45; OnChange := @YChanged; Name := 'RYSpinBox'; end; Inc(Indent.y); end; class procedure TRoundProperty.XChanged(Sender: TObject); begin with Sender as TSpinEdit do SetX(Value); end; class procedure TRoundProperty.YChanged(Sender: TObject); begin with Sender as TSpinEdit do SetY(Value); end; class procedure TRoundProperty.SetX(AX: Integer); var F: TFigure; begin FX := AX; for F in Figures do if (F.Selected) then SetProperty(F, 'RX', FX); ValidEvent; end; class procedure TRoundProperty.SetY(AY: Integer); var F: TFigure; begin FY := AY; for F in Figures do if (F.Selected) then SetProperty(F, 'RY', FY); ValidEvent; end; class procedure TRoundProperty.SetDefaultProperties(AFigures: array of TFigure); var F: TFigure; begin for F in AFigures do begin if (F.Selected) then begin SetProperty(F, 'RX', FX); SetProperty(F, 'RY', FY); end; end; ValidEvent; end; procedure ResetIndentY; begin Indent.y := 0; end; procedure InitProperties; begin with TPenProperty do begin SetPenColor(clBlack); SetPenSize(3); SetPenStyle(psSolid); end; with TBrushProperty do begin SetBrushColor(clWhite); SetBrushStyle(bsSolid); end; TRoundProperty.SetX(35); TRoundProperty.SetY(35); end; end.
{: GLStarRecord<p> Unit to interface with simple star records aimed for background skies.<p> <b>History : </b><font size=-1><ul> <li>05/07/03 - EG - Creation </ul></font> } unit GLStarRecord; interface uses GLVectorGeometry; type TGLStarRecord = packed record RA : Word; // x100 builtin factor, degrees DEC : SmallInt; // x100 builtin factor, degrees BVColorIndex : Byte; // x100 builtin factor VMagnitude : Byte; // x10 builtin factor end; PGLStarRecord = ^TGLStarRecord; {: Computes position on the unit sphere of a star record (Z=up). } function StarRecordPositionZUp(const starRecord : TGLStarRecord) : TAffineVector; {: Computes position on the unit sphere of a star record (Y=up). } function StarRecordPositionYUp(const starRecord : TGLStarRecord) : TAffineVector; {: Computes star color from BV index (RGB) and magnitude (alpha). } function StarRecordColor(const starRecord : TGLStarRecord; bias : Single) : TVector; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation uses GLVectorTypes; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // StarRecordPositionYUp // function StarRecordPositionYUp(const starRecord : TGLStarRecord) : TAffineVector; var f : Single; begin SinCosine(starRecord.DEC*(0.01*PI/180), Result.V[1], f); SinCosine(starRecord.RA*(0.01*PI/180), f, Result.V[0], Result.V[2]); end; // StarRecordPositionZUp // function StarRecordPositionZUp(const starRecord : TGLStarRecord) : TAffineVector; var f : Single; begin SinCosine(starRecord.DEC*(0.01*PI/180), Result.V[2], f); SinCosine(starRecord.RA*(0.01*PI/180), f, Result.V[0], Result.V[1]); end; // StarRecordColor // function StarRecordColor(const starRecord : TGLStarRecord; bias : Single) : TVector; const // very *rough* approximation cBVm035 : TVector = (X:0.7; Y:0.8; Z:1.0; W:1); cBV015 : TVector = (X:1.0; Y:1.0; Z:1.0; W:1); cBV060 : TVector = (X:1.0; Y:1.0; Z:0.7; W:1); cBV135 : TVector = (X:1.0; Y:0.8; Z:0.7; W:1); var bvIndex100 : Integer; begin bvIndex100:=starRecord.BVColorIndex-50; // compute RGB color for B&V index if bvIndex100<-035 then Result:=cBVm035 else if bvIndex100<015 then VectorLerp(cBVm035, cBV015, (bvIndex100+035)*(1/(015+035)), Result) else if bvIndex100<060 then VectorLerp(cBV015, cBV060, (bvIndex100-015)*(1/(060-015)), Result) else if bvIndex100<135 then VectorLerp(cBV060, cBV135, (bvIndex100-060)*(1/(135-060)), Result) else Result:=cBV135; // compute transparency for VMag // the actual factor is 2.512, and not used here Result.V[3]:=PowerSingle(1.2, -(starRecord.VMagnitude*0.1-bias)); end; end.
unit ncaDMDemonstrativoDeb; interface uses Forms, System.SysUtils, System.Classes, frxClass, frxDBSet, Data.DB, kbmMemTable, ncDebito, nxdb, frxDMPExport, Windows, frxDesgn; type TdmDemonstrativoDeb = class(TDataModule) mtCab: TkbmMemTable; mtItem: TkbmMemTable; mtItemCodigo: TStringField; mtItemDescr: TStringField; mtItemDataCompra: TDateTimeField; mtItemQuant: TFloatField; mtItemValorCompra: TCurrencyField; mtItemValorDeb: TCurrencyField; mtCabCliente: TStringField; repBob_pt: TfrxReport; dbCab: TfrxDBDataset; dbItem: TfrxDBDataset; tMovEst: TnxTable; tMovEstID: TUnsignedAutoIncField; tMovEstID_ref: TLongWordField; tMovEstTran: TLongWordField; tMovEstProduto: TLongWordField; tMovEstQuant: TFloatField; tMovEstUnitario: TCurrencyField; tMovEstTotal: TCurrencyField; tMovEstCustoU: TCurrencyField; tMovEstItem: TByteField; tMovEstDesconto: TCurrencyField; tMovEstPago: TCurrencyField; tMovEstPagoPost: TCurrencyField; tMovEstDescPost: TCurrencyField; tMovEstDataHora: TDateTimeField; tMovEstPend: TBooleanField; tMovEstIncluidoEm: TDateTimeField; tMovEstEntrada: TBooleanField; tMovEstCancelado: TBooleanField; tMovEstAjustaCusto: TBooleanField; tMovEstEstoqueAnt: TFloatField; tMovEstCliente: TLongWordField; tMovEstCaixa: TIntegerField; tMovEstCategoria: TStringField; tMovEstNaoControlaEstoque: TBooleanField; tMovEstITran: TIntegerField; tMovEstTipoTran: TByteField; tMovEstSessao: TIntegerField; tMovEstComissao: TCurrencyField; tMovEstComissaoPerc: TFloatField; tMovEstComissaoLucro: TBooleanField; tMovEstPermSemEstoque: TBooleanField; tMovEstFidResgate: TBooleanField; tMovEstFidPontos: TFloatField; tMovEstRecVer: TLongWordField; dmExp: TfrxDotMatrixExport; repFolha_pt: TfrxReport; Designer: TfrxDesigner; repBob_en: TfrxReport; repBob_es: TfrxReport; repFolha_en: TfrxReport; repFolha_es: TfrxReport; private { Private declarations } procedure Load(aDeb: TncDebito); procedure ImprimeBob; procedure _Imprime(aDeb: TncDebito; aBobina: Boolean); public class procedure Imprime(aDeb: TncDebito); function repBob: TfrxReport; function repfolha: TfrxReport; { Public declarations } end; var dmDemonstrativoDeb: TdmDemonstrativoDeb; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses ncaDM, ncPrintFile, ncaConfigRecibo, ncClassesBase, uNexTransResourceStrings_PT; {$R *.dfm} { TdmDemonstrativoDeb } class procedure TdmDemonstrativoDeb.Imprime(aDeb: TncDebito); begin if not Assigned(dmDemonstrativoDeb) then Application.CreateForm(TdmDemonstrativoDeb, dmDemonstrativoDeb); dmDemonstrativoDeb._Imprime(aDeb, gRecibo.DemDebBob); end; procedure TdmDemonstrativoDeb._Imprime(aDeb: TncDebito; aBobina: Boolean); begin Load(aDeb); if aBobina then ImprimeBob else begin repFolha.ReportOptions.Name := 'Débitos de '+mtCabCliente.Value; repFolha.PrintOptions.Printer := gRecibo.Impressora[tipodoc_demdeb]; repFolha.PrepareReport; repFolha.Print; end; end; procedure TdmDemonstrativoDeb.ImprimeBob; begin repBob.PrepareReport; dmExp.FileName := ExtractFilePath(ParamStr(0))+'Debitos_temp_'+IntToStr(Random(9999999))+'.txt'; repBob.Export(dmExp); PrintFile(gRecibo.Impressora[tipodoc_demdeb], dmExp.FileName, gRecibo.DirectPrintFormat); Windows.DeleteFile(PChar(dmExp.FileName)); end; procedure TdmDemonstrativoDeb.Load(aDeb: TncDebito); var I : Integer; var S1, S2 : String; begin mtCab.Active := False; mtItem.Active := False; mtCab.Open; mtItem.Open; mtCab.Append; if dados.tbCli.Locate('ID', aDeb.Cliente, []) then mtCabCliente.Value := dados.tbCliNome.Value; mtCab.Post; S1 := Dados.tbPro.IndexName; S2 := Dados.tbMovEst.IndexName; with Dados, aDeb do try tbPro.IndexName := 'IID'; tbMovEst.IndexName := 'IID'; for I := 0 to Itens.Count-1 do begin mtItem.Append; mtItemDataCompra.Value := itens[I].idDataCompra; mtItemValorDeb.Value := itens[i].idTotal; if itens[i].idTipoItem=itFrete then begin mtItemQuant.Value := 1; mtItemDescr.Value := rsTaxaEntregaFrete; if tbTran.Locate('ID', itens[i].idItemID, []) then mtItemValorCompra.Value := tbTranFrete.Value; end else if tbMovEst.FindKey([itens[i].idItemID]) then begin mtItemQuant.Value := tbMovEstQuant.Value; mtItemValorCompra.Value := tbMovEstTotal.Value - tbMovEstDesconto.Value; if tbPro.FindKey([tbMovEstProduto.Value]) then mtItemDescr.Value := tbProDescricao.Value; end; mtItem.Post; end; finally Dados.tbPro.IndexName := S1; Dados.tbMovEst.IndexName := S2; end; mtItem.First; end; function TdmDemonstrativoDeb.repBob: TfrxReport; begin if LinguaPT then Result := repBob_pt else if SameText(SLingua, 'es') then Result := repBob_es else Result := repBob_en; end; function TdmDemonstrativoDeb.repfolha: TfrxReport; begin if LinguaPT then Result := repFolha_pt else if SameText(SLingua, 'es') then Result := repFolha_es else Result := repFolha_en; end; end.
{ 25/05/2007 10:26:30 (GMT+1:00) > [Akadamia] checked in } { 25/05/2007 10:26:12 (GMT+1:00) > [Akadamia] checked out /} { 14/02/2007 08:26:50 (GMT+0:00) > [Akadamia] checked in } { 14/02/2007 08:26:39 (GMT+0:00) > [Akadamia] checked out /} { 12/02/2007 10:10:28 (GMT+0:00) > [Akadamia] checked in } { 08/02/2007 14:05:57 (GMT+0:00) > [Akadamia] checked in } {----------------------------------------------------------------------------- Unit Name: ATU Author: ken.adam Date: 15-Jan-2007 Purpose: Translation of AI Traffic example to Delphi Adds AI aircraft to make the flight from Yakima to Spokane busy. First start the user aircraft at Yakima (or load the Yakima to Spokane flight plan used by the AI aircraft - then drive off the runway to view the goings on). Press the Z key to add six AI aircraft Press the X key to give the parked aircraft the Yakima to Spokane flight plan Both keys can only work once. The creation of the 747 shguld fail - as Yakima airport is not large enough for this aircraft. History: -----------------------------------------------------------------------------} unit ATU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls, ActnList, ComCtrls, SimConnect, StdActns; const // Define a user message for message driven version of the example WM_USER_SIMCONNECT = WM_USER + 2; var ParkedBoeingID : DWORD = SIMCONNECT_OBJECT_ID_USER; ParkedMooneyID : DWORD = SIMCONNECT_OBJECT_ID_USER; type // Use enumerated types to create unique IDs as required TEventID = (EventSimStart, EventZ, EventX, EventAddedAircraft, EventRemovedAircraft); TDataRequestId = (RequestBOEING737, RequestBOEING747, RequestBARON, RequestLEARJET, RequestBOEING737_PARKED, RequestMOONEY_PARKED, RequestBOEING737_PARKED_FLIGHTPLAN, RequestMOONEY_PARKED_FLIGHTPLAN); TGroupId = (GroupZX); TInputId = (InputZX); // The form TAITrafficForm = class(TForm) StatusBar: TStatusBar; ActionManager: TActionManager; ActionToolBar: TActionToolBar; Images: TImageList; Memo: TMemo; StartPoll: TAction; FileExit: TFileExit; StartEvent: TAction; procedure StartPollExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure SimConnectMessage(var Message: TMessage); message WM_USER_SIMCONNECT; procedure StartEventExecute(Sender: TObject); private { Private declarations } RxCount: integer; // Count of Rx messages Quit: boolean; // True when signalled to quit hSimConnect: THandle; // Handle for the SimConection PlansSent: boolean; AircraftCreated: boolean; public { Public declarations } procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); procedure SendFlightPlans; procedure SetUpAIAircraft; end; var AITrafficForm : TAITrafficForm; implementation uses SimConnectSupport; resourcestring StrRx6d = 'Rx: %6d'; {$R *.dfm} {----------------------------------------------------------------------------- Procedure: MyDispatchProc Wraps the call to the form method in a simple StdCall procedure Author: ken.adam Date: 11-Jan-2007 Arguments: pData: PSimConnectRecv cbData: DWORD pContext: Pointer -----------------------------------------------------------------------------} procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); stdcall; begin AITrafficForm.DispatchHandler(pData, cbData, pContext); end; {----------------------------------------------------------------------------- Procedure: DispatchHandler Handle the Dispatched callbacks in a method of the form. Note that this is used by both methods of handling the interface. Author: ken.adam Date: 11-Jan-2007 Arguments: pData: PSimConnectRecv cbData: DWORD pContext: Pointer -----------------------------------------------------------------------------} procedure TAITrafficForm.DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); var hr : HRESULT; Evt : PSimconnectRecvEvent; OpenData : PSimConnectRecvOpen; EvtAr : PSimConnectRecvEventObjectAddRemove; pObjData : PSimConnectRecvAssignedObjectId; begin // Maintain a display of the message count Inc(RxCount); StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]); // Only keep the last 200 lines in the Memo while Memo.Lines.Count > 200 do Memo.Lines.Delete(0); // Handle the various types of message case TSimConnectRecvId(pData^.dwID) of SIMCONNECT_RECV_ID_EXCEPTION: Memo.Lines.Add(SimConnectException(PSimConnectRecvException(pData))); SIMCONNECT_RECV_ID_OPEN: begin StatusBar.Panels[0].Text := 'Opened'; OpenData := PSimConnectRecvOpen(pData); with OpenData^ do begin Memo.Lines.Add(''); Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName, dwApplicationVersionMajor, dwApplicationVersionMinor, dwApplicationBuildMajor, dwApplicationBuildMinor])); Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect', dwSimConnectVersionMajor, dwSimConnectVersionMinor, dwSimConnectBuildMajor, dwSimConnectBuildMinor])); Memo.Lines.Add(''); end; end; SIMCONNECT_RECV_ID_EVENT: begin evt := PSimconnectRecvEvent(pData); case TEventId(evt^.uEventID) of EventSimStart: begin // Make the call for data every second, but only when it changes and // only that data that has changed // Turn the ctrl-shift-A input event on now hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputZX), Ord(SIMCONNECT_STATE_ON)); end; EventZ: if not aircraftCreated then begin SetUpAIAircraft; AircraftCreated := True; end; EventX: if not PlansSent and AircraftCreated then begin SendFlightPlans; PlansSent := True; end; end; end; SIMCONNECT_RECV_ID_EVENT_OBJECT_ADDREMOVE: begin EvtAr := PSimConnectRecvEventObjectAddRemove(pData); case TEventId(EvtAR^.uEventID) of EventAddedAircraft: Memo.Lines.Add(Format('AI object added: Type=%s, ObjectID=%d', [SimConnectSimObjectTypeNames[evtAr^.eObjType], evtAr^.dwData])); EventRemovedAircraft: Memo.Lines.Add(Format('AI object removed: Type=%s, ObjectID=%d', [SimConnectSimObjectTypeNames[evtAr^.eObjType], evtAr^.dwData])); end; end; SIMCONNECT_RECV_ID_ASSIGNED_OBJECT_ID: begin pObjData := PSimConnectRecvAssignedObjectId(pData); case TDataRequestId(pObjData^.dwRequestID) of // Do nothing specific in these cases, as the aircraft already have their flight plans RequestBOEING737: Memo.Lines.Add(Format('Created Boeing 737 id = %d', [pObjData^.dwObjectID])); RequestBOEING747: Memo.Lines.Add(Format('Created Boeing 747 id = %d', [pObjData^.dwObjectID])); RequestBARON: Memo.Lines.Add(Format('Created Beech Baron id = %d', [pObjData^.dwObjectID])); RequestLEARJET: Memo.Lines.Add(Format('Created Learjet id = %d', [pObjData^.dwObjectID])); RequestBOEING737_PARKED: begin // Record the object ID, so the flightplan can be sent out later ParkedBoeingID := pObjData^.dwObjectID; Memo.Lines.Add(Format('Created parked Boeing %d', [pObjData^.dwObjectID])); end; RequestMOONEY_PARKED: begin // Record the object ID, so the flightplan can be sent out later ParkedMooneyID := pObjData^.dwObjectID; Memo.Lines.Add(Format('Created parked Mooney %d', [pObjData^.dwObjectID])); end else Memo.Lines.Add(Format('Unknown creation %d', [pObjData^.dwRequestID])); end; end; SIMCONNECT_RECV_ID_QUIT: begin Quit := True; StatusBar.Panels[0].Text := 'FS X Quit'; end else Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID])); end; end; {----------------------------------------------------------------------------- Procedure: FormCloseQuery Ensure that we can signal "Quit" to the busy wait loop Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject var CanClose: Boolean Result: None -----------------------------------------------------------------------------} procedure TAITrafficForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Quit := True; CanClose := True; end; {----------------------------------------------------------------------------- Procedure: FormCreate We are using run-time dynamic loading of SimConnect.dll, so that the program will execute and fail gracefully if the DLL does not exist. Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject Result: None -----------------------------------------------------------------------------} procedure TAITrafficForm.FormCreate(Sender: TObject); begin if InitSimConnect then StatusBar.Panels[2].Text := 'SimConnect.dll Loaded' else begin StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND'; StartPoll.Enabled := False; StartEvent.Enabled := False; end; Quit := False; hSimConnect := 0; PlansSent:= false; AircraftCreated:= false; StatusBar.Panels[0].Text := 'Not Connected'; RxCount := 0; StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]); end; {----------------------------------------------------------------------------- Procedure: SendFlightPlans Author: ken.adam Date: 19-Jan-2007 Arguments: None Result: None -----------------------------------------------------------------------------} procedure TAITrafficForm.SendFlightPlans; var hr : HRESULT; begin if (ParkedBoeingID <> SIMCONNECT_OBJECT_ID_USER) then hr := SimConnect_AISetAircraftFlightPlan(hSimConnect, ParkedBoeingID, 'IFR Yakima Air Term Mcallister to Spokane Intl', Ord(RequestBOEING737_PARKED_FLIGHTPLAN)); if (ParkedMooneyID <> SIMCONNECT_OBJECT_ID_USER) then hr := SimConnect_AISetAircraftFlightPlan(hSimConnect, ParkedMooneyID, 'IFR Yakima Air Term Mcallister to Spokane Intl', Ord(RequestMOONEY_PARKED_FLIGHTPLAN)); end; procedure TAITrafficForm.SetUpAIAircraft; var hr : HRESULT; begin // Add some AI controlled aircraft hr := SimConnect_AICreateEnrouteATCAircraft(hSimConnect, 'Boeing 737-800', 'N100', 100, 'IFR Yakima Air Term Mcallister to Spokane Intl', 0.0, false, Ord(RequestBOEING737)); hr := SimConnect_AICreateEnrouteATCAircraft(hSimConnect, 'Boeing 747-400', 'N101', 101, 'IFR Yakima Air Term Mcallister to Spokane Intl', 0.0, false, Ord(RequestBOEING747)); hr := SimConnect_AICreateEnrouteATCAircraft(hSimConnect, 'Beech Baron 58', 'N200', 200, 'IFR Yakima Air Term Mcallister to Spokane Intl', 0.0, false, Ord(RequestBARON)); hr := SimConnect_AICreateEnrouteATCAircraft(hSimConnect, 'Learjet 45', 'N201', 201, 'IFR Yakima Air Term Mcallister to Spokane Intl', 0.0, false, Ord(RequestLEARJET)); // Park a few aircraft hr := SimConnect_AICreateParkedATCAircraft(hSimConnect, 'Boeing 737-800', 'N102', 'KYKM', Ord(RequestBOEING737_PARKED)); hr := SimConnect_AICreateParkedATCAircraft(hSimConnect, 'Mooney Bravo', 'N202', 'KYKM', Ord(RequestMOONEY_PARKED)); end; {----------------------------------------------------------------------------- Procedure: SimConnectMessage This uses CallDispatch, but could probably avoid the callback and use SimConnect_GetNextDispatch instead. Author: ken.adam Date: 11-Jan-2007 Arguments: var Message: TMessage -----------------------------------------------------------------------------} procedure TAITrafficForm.SimConnectMessage(var Message: TMessage); begin SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil); end; {----------------------------------------------------------------------------- Procedure: StartEventExecute Opens the connection for Event driven handling. If successful sets up the data requests and hooks the system event "SimStart". Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject -----------------------------------------------------------------------------} procedure TAITrafficForm.StartEventExecute(Sender: TObject); var hr : HRESULT; begin if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle, WM_USER_SIMCONNECT, 0, 0))) then begin StatusBar.Panels[0].Text := 'Connected'; // Create some private events hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventZ)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventX)); // Link the private events to keyboard keys, and ensure input events are off hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'Z', Ord(EventZ)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'X', Ord(EventX)); hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputZX), Ord(SIMCONNECT_STATE_OFF)); // Sign up for notifications hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventZ)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventX)); // Request a simulation start event hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart), 'SimStart'); // Subscribe to system events notifying the client that objects have been added or removed hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventAddedAircraft), 'ObjectAdded'); hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventRemovedAircraft), 'ObjectRemoved'); StartEvent.Enabled := False; StartPoll.Enabled := False; end; end; {----------------------------------------------------------------------------- Procedure: StartPollExecute Opens the connection for Polled access. If successful sets up the data requests and hooks the system event "SimStart", and then loops indefinitely on CallDispatch. Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject -----------------------------------------------------------------------------} procedure TAITrafficForm.StartPollExecute(Sender: TObject); var hr : HRESULT; begin if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then begin StatusBar.Panels[0].Text := 'Connected'; // Create some private events hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventZ)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventX)); // Link the private events to keyboard keys, and ensure input events are off hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'Z', Ord(EventZ)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'X', Ord(EventX)); hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputZX), Ord(SIMCONNECT_STATE_OFF)); // Sign up for notifications hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventZ)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventX)); // Request a simulation start event hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart), 'SimStart'); // Subscribe to system events notifying the client that objects have been added or removed hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventAddedAircraft), 'ObjectAdded'); hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventRemovedAircraft), 'ObjectRemoved'); StartEvent.Enabled := False; StartPoll.Enabled := False; while not Quit do begin SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil); Application.ProcessMessages; Sleep(1); end; hr := SimConnect_Close(hSimConnect); end; end; end.
unit IdDayTime; {*******************************************************} { } { Indy QUOTD Client TIdDayTime } { } { Copyright (C) 2000 Winshoes WOrking Group } { Started by J. Peter Mugaas } { 2000-April-23 } { } {*******************************************************} {2000-April-30 J. Peter Mugaas changed to drop control charactors and spaces from result to ease parsing} interface uses Classes, IdAssignedNumbers, IdTCPClient; type TIdDayTime = class(TIdTCPClient) protected Function GetDayTimeStr : String; public constructor Create(AOwner: TComponent); override; Property DayTimeStr : String read GetDayTimeStr; published property Port default IdPORT_DAYTIME; end; implementation uses SysUtils; { TIdDayTime } constructor TIdDayTime.Create(AOwner: TComponent); begin inherited; Port := IdPORT_DAYTIME; end; function TIdDayTime.GetDayTimeStr: String; begin Result := Trim ( ConnectAndGetAll ); end; end.
{ Copyright (c) 2010, Loginov Dmitry Sergeevich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } unit AttribControls; interface uses Windows, Messages, Classes, SysUtils, SHDocVw, MSHTML, Graphics, Controls, Forms, Grids, StdCtrls, ExtCtrls, HTMLGlobal, Spin; type TBaseAttribControl = class(TComponent) protected FControl: TControl; function GetAsText: string; virtual; procedure SetAsText(const Value: string); virtual; procedure DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); virtual; public property AsText: string read GetAsText write SetAsText; procedure ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); virtual; procedure DrawOnCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure HideControl; virtual; end; TTextComboBox = class(TBaseAttribControl) private protected function GetAsText: string; override; procedure SetAsText(const Value: string); override; procedure DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); override; procedure ControlOnExit(Sender: TObject); public FTranslateList: TStringList; FComboBox: TComboBox; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetTranslateStr(S: string); procedure ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); override; end; THTMLColorComboBox = class(TBaseAttribControl) private FColorBox: TColorBox; FNoneColor: TColor; procedure ControlOnExit(Sender: TObject); procedure OnColorSelect(Sender: TObject); protected function GetAsText: string; override; procedure SetAsText(const Value: string); override; procedure DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); override; end; THTMLTextEditor = class(TBaseAttribControl) private FEditor: TEdit; procedure ControlOnExit(Sender: TObject); protected function GetAsText: string; override; procedure SetAsText(const Value: string); override; procedure DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); override; end; THTMLSizeEditor = class(TBaseAttribControl) private FEditor: TEdit; procedure ControlOnExit(Sender: TObject); protected function GetAsText: string; override; procedure SetAsText(const Value: string); override; procedure DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); override; public FComboBox: TComboBox; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); override; procedure HideControl; override; end; THTMLIntValueEditor = class(TBaseAttribControl) private procedure ControlOnExit(Sender: TObject); procedure OnSpinKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected function GetAsText: string; override; procedure SetAsText(const Value: string); override; procedure DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); override; public FEditor: TSpinEdit; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); override; end; procedure RegisterAttrControl(ARow: Integer; AControl: TBaseAttribControl); function GetControlForCell(ARow: Integer; AGrid: TComponent): TBaseAttribControl; procedure HideAllControls; procedure ClearControlList; function CreateAttribControl(AOwner: TComponent; AStyle: THTMLAttribType; ARow: Integer; AText: string): TBaseAttribControl; implementation var FControlList: TStringList; function CreateAttribControl(AOwner: TComponent; AStyle: THTMLAttribType; ARow: Integer; AText: string): TBaseAttribControl; var AList: TStringList; I: Integer; S: string; begin case AStyle of atHAlign: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('left=Влево;center=По центру;'+ 'right=Вправо;justify=По ширине'); end; atImgAlign: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('bottom=По низу строку;'+ 'left=По левому краю;middle=По середине строки;right=По правому краю;'+ 'top=По верху строки'); end; atCSSVAlign: //atVAlign begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('top=Верх;middle=Середина;bottom=Низ;'+ 'baseline=Базовая линия;sub=Подстрочный;super=Надстрочный;'+ 'text-top=По верху строки;text-bottom=По низу строки'); end; atVAlign: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('top=Верх;middle=Середина;bottom=Низ;'+ 'baseline=Базовая линия'); end; atULType: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('disc=Круг;circle=Окружность;square=Кдадрат'); end; atOLType: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).FTranslateList.CaseSensitive := True; TTextComboBox(Result).SetTranslateStr('A=Латинская заглавная буква;a=Латинская строчная буква;'+ 'I=Римская заглавная буква;i=Римская строчная буква;1=Арабские цифры'); end; atCSSFontStyle: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('normal=Обычное;italic=Курсив;oblique=Наклонный'); end; atCSSFontWeight: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('bold=Полужирный;bolder=Жирный;'+ 'lighter=Светлый;normal=Нормальный;100=100 ед.;200=200 ед.;'+ '300=300 ед.;400=400 ед.;500=500 ед.;600=600 ед.;700=700 ед.;800=800 ед.;900=900 ед.'); end; atCSSBorderStyle: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('none=Нет;dotted=Точечная;'+ 'dashed=Пунктирная;solid=Сплошная;double=Двойная;groove=Вдавленная;'+ 'ridge=Рельефная;inset=Трехмерная 1;outset=Трехмерная 2'); end; atLinkTarget: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('_blank=В новом окне;_self=В этом же окне;'+ '_parent=В родительском фрейме;_top=Без фрейма'); end; atCharSet: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('windows-1251=Русская (1251);utf-8=UTF-8'); end; atInputType: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('button=Кнопка;checkbox=Флажок;file=Файл;'+ 'hidden=Скрытый;image=Кнопка с изображением;password=Поле с паролем;'+ 'radio=Переключатель;reset=Кнопка сброса;submit=Кнопка "Отправить";'+ 'text=Поле для ввода текста'); end; atMethod: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('GET=GET;POST=POST'); end; atMrqDir: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('down=Сверху вниз;left=Справа налево;'+ 'right=Слева направо;up=Снизу вверх'); end; atMrqBehav: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('alternate=Туда-сюда;scroll=По кругу;slide=Один раз'); end; atCSSWritingMode: begin Result := TTextComboBox.Create(AOwner); // В IE поддерживается только один вариант данного стиля (tb-rl). Остальные не поддерживаются! // В FireFox стиль tb-rl не действует! TTextComboBox(Result).SetTranslateStr('tb-rl=ВЕРХ->НИЗ / ПРАВ->ЛЕВ'); end; atCSSPageBreak: begin Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('always=Обычный разрыв;left=Сделать левой;right=Сделать правой;auto=По умолчанию'); end; atFontName: begin Result := TTextComboBox.Create(AOwner); AList := TStringList.Create; try AList.Assign(Screen.Fonts); AList.Insert(0, 'Times New Roman'); for I := 0 to AList.Count - 1 do AList[I] := AList[I] + '=' + AList[I]; S := StringReplace(AList.Text, #13#10, ';', [rfReplaceAll]); TTextComboBox(Result).SetTranslateStr(S); finally AList.Free; end; end; atColor: begin Result := THTMLColorComboBox.Create(AOwner); end; atBoolean: begin if (AText = '') or (AText = '0') then AText := '' else AText := '1'; Result := TTextComboBox.Create(AOwner); TTextComboBox(Result).SetTranslateStr('1=Да'); end; atCount, atPxSize: begin Result := THTMLIntValueEditor.Create(AOwner); THTMLIntValueEditor(Result).FEditor.MinValue := 0; end; atCount1: begin Result := THTMLIntValueEditor.Create(AOwner); THTMLIntValueEditor(Result).FEditor.MinValue := 1; end; atCountFromMinus1: begin Result := THTMLIntValueEditor.Create(AOwner); THTMLIntValueEditor(Result).FEditor.MinValue := -1; end; atCSSSize: begin Result := THTMLSizeEditor.Create(AOwner); end; atSize: begin Result := THTMLSizeEditor.Create(AOwner); THTMLSizeEditor(Result).FComboBox.Clear; THTMLSizeEditor(Result).FComboBox.Items.Add(''); THTMLSizeEditor(Result).FComboBox.Items.Add('px'); THTMLSizeEditor(Result).FComboBox.Items.Add('%'); if Trim(AText) <> '' then if Pos('%', AText) = 0 then AText := AText + 'px'; end; else begin Result := THTMLTextEditor.Create(AOwner); end; end; RegisterAttrControl(ARow, Result); Result.AsText := AText; end; procedure RegisterAttrControl(ARow: Integer; AControl: TBaseAttribControl); begin if Assigned(AControl) then FControlList.AddObject(AControl.Owner.Name + '_' + IntToStr(ARow), AControl); end; function GetControlForCell(ARow: Integer; AGrid: TComponent): TBaseAttribControl; var Index: Integer; begin Result := nil; Index := FControlList.IndexOf(AGrid.Name + '_' + IntToStr(ARow)); if Index >= 0 then Result := TBaseAttribControl(FControlList.Objects[Index]); end; procedure HideAllControls; var I: Integer; cntrl: TBaseAttribControl; begin for I := 0 to FControlList.Count - 1 do begin cntrl := TBaseAttribControl(FControlList.Objects[I]); cntrl.HideControl; end; end; procedure ClearControlList; var I: Integer; cntrl: TBaseAttribControl; begin for I := 0 to FControlList.Count - 1 do begin cntrl := TBaseAttribControl(FControlList.Objects[I]); cntrl.Free; end; FControlList.Clear; end; { TBaseAttribControl } constructor TBaseAttribControl.Create(AOwner: TComponent); begin inherited; FControl.Visible := False; FControl.Parent := TWinControl(AOwner).Parent; end; destructor TBaseAttribControl.Destroy; begin FControl.Free; inherited; end; procedure TBaseAttribControl.SetAsText(const Value: string); begin end; procedure TBaseAttribControl.DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); begin end; procedure TBaseAttribControl.DrawOnCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin DoDrawOnCell(TStringGrid(Sender), Rect, State); end; function TBaseAttribControl.GetAsText: string; begin end; procedure TBaseAttribControl.HideControl; begin FControl.Hide; end; procedure TBaseAttribControl.ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); var ARect: TRect; begin ARect := AGrid.CellRect(ACol, ARow); with ARect do begin Inc(Left); Inc(Top); Inc(Right, 2); end; FControl.BoundsRect := ARect; FControl.Visible := True; end; { TTextComboBox } procedure TTextComboBox.ControlOnExit(Sender: TObject); begin FComboBox.Visible := False end; constructor TTextComboBox.Create(AOwner: TComponent); begin FComboBox := TComboBox.Create(AOwner); FControl := FComboBox; inherited; FComboBox.Style := csDropDownList; FComboBox.OnExit := ControlOnExit; FTranslateList := TStringList.Create; end; destructor TTextComboBox.Destroy; begin FTranslateList.Free; inherited; end; procedure TTextComboBox.DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); var S: string; begin Sender.Canvas.FillRect(Rect); S := FComboBox.Text; Sender.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S); end; procedure TTextComboBox.SetAsText(const Value: string); var Index: Integer; S: string; begin if Trim(Value) = '' then Index := 0 else begin S := FTranslateList.Values[Value]; Index := FComboBox.Items.IndexOf(S); end; FComboBox.ItemIndex := Index; end; function TTextComboBox.GetAsText: string; var I: Integer; S: string; begin S := FComboBox.Text; Result := ''; for I := 0 to FTranslateList.Count - 1 do if FTranslateList.ValueFromIndex[I] = S then begin Result := FTranslateList.Names[I]; Exit; end; end; procedure TTextComboBox.SetTranslateStr(S: string); var I: Integer; begin FTranslateList.Text := StringReplace(S, ';', #13#10, [rfReplaceAll]); FComboBox.Clear; FComboBox.Items.Add(' '); for I := 0 to FTranslateList.Count - 1 do FComboBox.Items.Add(FTranslateList.ValueFromIndex[I]); end; procedure TTextComboBox.ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); begin inherited; FComboBox.SetFocus; end; { THTMLColorComboBox } procedure THTMLColorComboBox.ControlOnExit(Sender: TObject); begin FColorBox.Hide; end; constructor THTMLColorComboBox.Create(AOwner: TComponent); begin FColorBox := TColorBox.Create(AOwner); FControl := FColorBox; inherited; FColorBox.OnExit := ControlOnExit; FColorBox.OnSelect := OnColorSelect; FColorBox.Style := [cbCustomColors]; FNoneColor := RGB(254, 255, 255); ListFillColorNames(FColorBox.Items); FColorBox.Items.InsertObject(0, SNoneColor, TObject(FNoneColor)); //procedure cbFontBgColorGetColors(Sender: TCustomColorBox; Items: TStrings); //FComboBox.Style := csDropDownList; //FComboBox.OnExit := ControlOnExit; end; destructor THTMLColorComboBox.Destroy; begin inherited; end; procedure THTMLColorComboBox.DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); var S: string; begin if FColorBox.ItemIndex >= 0 then begin Sender.Canvas.FillRect(Rect); Sender.Canvas.Brush.Color := FColorBox.Selected; Sender.Canvas.FillRect(Classes.Rect(Rect.Left + 2, Rect.Top + 2, Rect.Left + 15, Rect.Top + 15)); Sender.Canvas.Brush.Style := bsClear; S := FColorBox.Items[FColorBox.ItemIndex]; if S <> SNoneColor then Sender.Canvas.TextOut(Rect.Left + 20, Rect.Top + 2, S); end; end; function THTMLColorComboBox.GetAsText: string; begin if (FColorBox.ItemIndex < 0) or (FColorBox.Selected = FNoneColor) then Result := '' else Result := ConvertColorToHtml(FColorBox.Selected); end; procedure THTMLColorComboBox.OnColorSelect(Sender: TObject); var IsCancel: Boolean; begin HTMLColorBoxGetColor(FColorBox, HTMLColorDialog, IsCancel); end; procedure THTMLColorComboBox.SetAsText(const Value: string); var IColor, Index: Integer; SValue: string; function IsDigital(S: string): Boolean; var I: Integer; begin Result := False; if S = '' then Exit; for I := 1 to Length(S) do if not(S[I] in ['0'..'9', '-']) then Exit; Result := True; end; function IsHex(S: string): Boolean; var I: Integer; begin Result := False; if S = '' then Exit; for I := 1 to Length(S) do if not(S[I] in ['0'..'9', 'A'..'F']) then Exit; Result := True; end; begin inherited; SValue := UpperCase(Value); IColor := FNoneColor; if SValue = 'BLACK' then IColor := clBlack else if SValue = 'GRAY' then IColor := clGray else if SValue = 'SILVER' then IColor := clSilver else if SValue = 'WHITE' then IColor := clWhite else if SValue = 'MAROON' then IColor := clMaroon else if SValue = 'RED' then IColor := clRed else if SValue = 'ORANGE' then IColor := TColor($00A5FF) else if SValue = 'YELLOW' then IColor := clYellow else if SValue = 'OLIVE' then IColor := clOlive else if SValue = 'LIME' then IColor := clLime else if SValue = 'TEAL' then IColor := clTeal else if SValue = 'AQUA' then IColor := clAqua else if SValue = 'BLUE' then IColor := clBlue else if SValue = 'NAVY' then IColor := clNavy else if SValue = 'PURPLE' then IColor := clPurple else if SValue = 'FUСHSIA' then IColor := clFuchsia else if SValue = 'THISTLE' then IColor := TColor($D8BFD8) else if IsDigital(SValue) then begin IColor := StrToInt(SValue) end else if Pos('#', SValue) > 0 then begin SValue := StringReplace(SValue, '#', '', []); if IsHex(SValue) then begin if Length(SValue) = 3 then SValue := SValue[1] + SValue[1] + SValue[2] + SValue[2] + SValue[3] + SValue[3]; if Length(SValue) = 6 then begin IColor := Windows.RGB(StrToInt('$' + SValue[1] + SValue[2]), StrToInt('$' + SValue[3] + SValue[4]), StrToInt('$' + SValue[5] + SValue[6])); //IColor := StrToIntDef('$' + SValue, FNoneColor); end; end; end else if Pos('RGB', SValue) > 0 then begin SValue := StringReplace(SValue, 'RGB', '', [rfReplaceAll]); SValue := StringReplace(SValue, '(', '', [rfReplaceAll]); SValue := StringReplace(SValue, ')', '', [rfReplaceAll]); while Pos(' ', SValue) > 0 do SValue := StringReplace(SValue, ' ', '', [rfReplaceAll]); with TStringList.Create do try Text := StringReplace(SValue, ',', #13#10, [rfReplaceAll]); if Count > 2 then begin try IColor := Windows.RGB(StrToInt(Strings[0]), StrToInt(Strings[1]), StrToInt(Strings[0])); except IColor := FNoneColor; end; end; finally Free; end; end; Index := FColorBox.Items.IndexOfObject(TObject(IColor)); if Index >= 0 then FColorBox.ItemIndex := Index else begin Index := FColorBox.Items.IndexOf(SSelectColor); if Index >= 0 then begin FColorBox.Items.Objects[Index] := TObject(IColor); FColorBox.ItemIndex := Index; end; end; { ColBox.Enabled := True; AColor := StrToIntDef(S, 0); Index := ColBox.Items.IndexOfObject(TObject(AColor)); if Index >= 0 then ColBox.ItemIndex := Index else begin Index := ColBox.Items.IndexOf(SSelectColor); if Index >= 0 then ColBox.Items.Objects[Index] := TObject(AColor); end;} end; procedure THTMLColorComboBox.ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); begin inherited; //GetParentForm(FColorBox).ActiveControl := FColorBox; FColorBox.SetFocus; end; { THTMLTextEditor } procedure THTMLTextEditor.ControlOnExit(Sender: TObject); begin FEditor.Hide; end; constructor THTMLTextEditor.Create(AOwner: TComponent); begin FEditor := TEdit.Create(AOwner); FControl := FEditor; inherited; FEditor.OnExit := ControlOnExit; end; destructor THTMLTextEditor.Destroy; begin inherited; end; procedure THTMLTextEditor.DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); var S: string; begin Sender.Canvas.FillRect(Rect); S := FEditor.Text; Sender.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S); end; function THTMLTextEditor.GetAsText: string; begin Result := FEditor.Text; end; procedure THTMLTextEditor.SetAsText(const Value: string); begin inherited; FEditor.Text := Value; end; procedure THTMLTextEditor.ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); begin inherited; FEditor.SetFocus; end; { THTMLIntValueEditor } procedure THTMLIntValueEditor.ControlOnExit(Sender: TObject); begin FEditor.Hide; end; constructor THTMLIntValueEditor.Create(AOwner: TComponent); begin FEditor := TSpinEdit.Create(AOwner); FControl := FEditor; inherited; FEditor.OnExit := ControlOnExit; FEditor.OnKeyDown := OnSpinKeyDown; FEditor.MinValue := -1; FEditor.MaxValue := MaxWord; end; destructor THTMLIntValueEditor.Destroy; begin inherited; end; procedure THTMLIntValueEditor.DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); var S: string; begin Sender.Canvas.FillRect(Rect); S := FEditor.Text; Sender.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S); end; function THTMLIntValueEditor.GetAsText: string; begin {if (StrToIntDef(FEditor.Text, -2) < FEditor.MinValue) or then Result := 1 else } if FEditor.Text = '' then Result := '' else Result := IntToStr(FEditor.Value) //Result := FEditor.Text; end; procedure THTMLIntValueEditor.OnSpinKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var AForm: TCustomForm; Btn: TButton; begin if Key = VK_RETURN then begin HideControl; AForm := Forms.GetParentForm(TControl(Sender)); if Assigned(AForm) then begin Btn := TButton(AForm.FindComponent('btnOK')); if Assigned(Btn) then Btn.Click; end; end; end; procedure THTMLIntValueEditor.SetAsText(const Value: string); begin inherited; FEditor.Text := Value; end; procedure THTMLIntValueEditor.ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); begin inherited; FEditor.SetFocus; end; { THTMLSizeEditor } procedure THTMLSizeEditor.ControlOnExit(Sender: TObject); begin if (Sender = FEditor) and FComboBox.Focused then Exit; if (Sender = FComboBox) and FEditor.Focused then Exit; FEditor.Hide; FComboBox.Hide; end; constructor THTMLSizeEditor.Create(AOwner: TComponent); begin FEditor := TEdit.Create(AOwner); FComboBox := TComboBox.Create(AOwner); FComboBox.Parent := TWinControl(AOwner).Parent; FComboBox.Visible := False; FComboBox.Style := csDropDownList; FComboBox.Items.Add(''); FComboBox.Items.Add('px'); FComboBox.Items.Add('%'); FComboBox.Items.Add('cm'); FComboBox.Items.Add('em'); FComboBox.Items.Add('pt'); FControl := FEditor; inherited; FEditor.OnExit := ControlOnExit; FComboBox.OnExit := ControlOnExit; end; destructor THTMLSizeEditor.Destroy; begin FComboBox.Free; inherited; end; procedure THTMLSizeEditor.DoDrawOnCell(Sender: TStringGrid; Rect: TRect; State: TGridDrawState); var S: string; begin Sender.Canvas.FillRect(Rect); if Trim(FEditor.Text) <> '' then S := FEditor.Text + FComboBox.Text; Sender.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S); end; function THTMLSizeEditor.GetAsText: string; var S, SCh: string; V: Extended; begin Result := ''; SCh := StringReplace(Trim(FEditor.Text), ',', DecimalSeparator, [rfReplaceAll]); SCh := StringReplace(SCh, '.', DecimalSeparator, [rfReplaceAll]); if TryStrToFloat(SCh, V) then begin if (V >= 0) and (V < MaxWord) then begin S := FloatToStr(V); S := StringReplace(S, ',', '.', [rfReplaceAll]); Result := S + FComboBox.Text; end; end; end; procedure THTMLSizeEditor.HideControl; begin inherited; FComboBox.Hide; end; procedure THTMLSizeEditor.SetAsText(const Value: string); var I, Index: Integer; S, S1, S2: string; begin inherited; S1 := Trim(LowerCase(Value)); S1 := StringReplace(S1, ' ', '', [rfReplaceAll]); for I := 1 to Length(S1) do if S1[I] in ['0'..'9', '.'] then S := S + S1[I] else Break; if Pos('cm', S1) > 0 then S2 := 'cm' else if Pos('em', S1) > 0 then S2 := 'em' else if Pos('pt', S1) > 0 then S2 := 'pt' else if Pos('%', S1) > 0 then S2 := '%' else if Pos('px', S1) > 0 then S2 := 'px'; FEditor.Text := S; Index := FComboBox.Items.IndexOf(S2); if Index >= 0 then FComboBox.ItemIndex := Index; end; procedure THTMLSizeEditor.ShowOnGrid(AGrid: TStringGrid; ACol, ARow: Integer); var ARect: TRect; begin ARect := AGrid.CellRect(ACol, ARow); with ARect do begin Inc(Left); Inc(Top); Right := Right - 50; end; FEditor.BoundsRect := ARect; FEditor.Visible := True; with ARect do begin Left := Right + 2; Right := Left + 50; end; FComboBox.BoundsRect := ARect; FComboBox.Visible := True; FEditor.SetFocus; end; initialization FControlList := TStringList.Create; finalization FControlList.Free; end.
unit uGMV_ScrollListBox; interface uses StdCtrls , Windows , Messages; type // List Box without vertical scrollbar TNoVScrolllistbox = class( Tlistbox ) private procedure WMNCCalcSize( Var msg: TMessage ); message WM_NCCALCSIZE; procedure WMVScroll (var Message: TWMVScroll); message WM_VSCROLL; public SearchTarget:String; end; implementation //////////////////////////////////////////////////////////////////////////////// procedure TNoVScrolllistbox.WMNCCalcSize(var msg: TMessage); //var // style: Integer; begin (* uncomment to hide scroll bar style := getWindowLong( handle, GWL_STYLE ); If (style and WS_VSCROLL) <> 0 Then SetWindowLong( handle, GWL_STYLE, style and not WS_VSCROLL ); *) inherited; end; (* Unit QForms type TScrollCode = (scLineUp, scLineDown, scPageUp, scPageDown, scPosition, scTrack, scTop, scBottom, scEndScroll); scLineUp User clicked the top or left scroll arrow or pressed the Up or Left arrow key. scLineDown User clicked the bottom or right scroll arrow or pressed the Down or Right arrow key. scPageUp User clicked the area to the left of the thumb tab or pressed the PgUp key. scPageDown User clicked the area to the right of the thumb tab or pressed the PgDn key. scPosition User positioned the thumb tab and released it. scTrack User is moving the thumb tab. scTop User moved the thumb tab to the top or far left on the scroll bar. scBottom User moved the thumb tab to the bottom or far right on the scroll bar. scEndScroll User finished moving the thumb tab on the scroll bar. *) procedure TNoVScrolllistbox.WMVScroll(var Message: TWMVScroll); var i: Integer; begin inherited; case Message.ScrollCode of 0:SendMessage(Handle, WM_KEYDOWN, VK_Up, 1); 1:SendMessage(Handle, WM_KEYDOWN, VK_Down, 1); 2:SendMessage(Handle, WM_KEYDOWN, SB_PAGEUP, 1); 3:SendMessage(Handle, WM_KEYDOWN, SB_PAGEDOWN, 1); 4:begin i := Height div ItemHeight; if (TopIndex + i >= Items.Count - 1 ) then SendMessage(Handle, WM_KEYDOWN, SB_BOTTOM, 1) else if (TopIndex = 0) then begin SearchTarget := Items[0]; SendMessage(Handle, WM_KEYDOWN, SB_TOP, 1); end; end; SB_TOP:SendMessage(Handle, WM_KEYDOWN, SB_TOP, 1); end; end; //////////////////////////////////////////////////////////////////////////////// { Want to scroll a windows control with Delphi code? Like a listbox, memo, etc, here's how to do it: To scroll a windows control up use: SendMessage(Memo1.Handle, WM_KEYDOWN, VK_UP, 1); To scroll a windows control down use: SendMessage(Memo1.Handle, WM_KEYDOWN, VK_DOWN, 1); Simply replace the "Memo1" part with the name of the control you want to scroll. } (* procedure WMVScroll (var Message: TWMVScroll); message WM_VSCROLL; procedure TfrmGMV_PatientSelector.WMVScroll(var Message: TWMVScroll); begin inherited; // if Message.ScrollCode = SB_ENDSCROLL then uItemTip.Hide; case Message.ScrollCode of sB_LineUp: ScrollUp; sB_LineDown: ScrollDown; end; end; *) (* From: Peter Below (TeamB) - view profile Date: Wed, Jul 24 2002 8:54 am Email: "Peter Below (TeamB)" <100113.1...@compuXXserve.com> Groups: borland.public.delphi.objectpascal Not yet rated Rating: show options Reply | Reply to Author | Forward | Print | Individual Message | Show original | Report Abuse | Find messages by this author In article <3d3e13a0_1@dnews>, Gary H wrote: > Does anyone know how to turn off the scroll bar in a > TlistBox? I've looked at the component refrence book and can't seem to find > any property that I can set to hide it. I would like to do a Ownerdraw list > box and then control scrolling through code but I need to hide the scroll > bar first. > any tips would be appreciated. Derive a new class from Tlistbox, like this: type TNoVScrolllistbox = Class( Tlistbox ) private Procedure WMNCCalcSize( Var msg: TMessage ); message WM_NCCALCSIZE; end; procedure TNoVScrolllistbox.WMNCCalcSize(var msg: TMessage); var style: Integer; begin style := getWindowLong( handle, GWL_STYLE ); If (style and WS_VSCROLL) <> 0 Then SetWindowLong( handle, GWL_STYLE, style and not WS_VSCROLL ); inherited; end; -- *) end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Classes, Forms, ActiveX, DirectShow9; const WM_GRAPH_NOTIFY = WM_USER + 1; type EDirectShowPlayerException = class(Exception) private FErrorCode: HRESULT; public constructor Create(ErrorCode: HRESULT); property ErrorCode: HRESULT read FErrorCode; end; TDirectShowEventProc = procedure(EventCode, Param1, Param2: Integer) of object; TDirectShowPlayerState = ( dspsUninitialized, dspsInitialized, dspsPlaying, dspsPaused ); TDirectShowPlayer = class strict private FLastError: HRESULT; FWindowHandle: HWND; FPlayerState: TDirectShowPlayerState; FEventCallback: TDirectShowEventProc; FBasicAudio: IBasicAudio; FVideoWindow: IVideoWindow; FGraphBuilder: IGraphBuilder; FMediaEventEx: IMediaEventEx; FMediaControl: IMediaControl; procedure HandleEvents; function ErrorCheck(Value: HRESULT): HRESULT; procedure InitializeMediaPlay(FileName: PWideChar); procedure FinalizeMediaPlay; procedure InitializeFilterGraph; procedure FinalizeFilterGraph; procedure InitializeVideoWindow(WindowHandle: HWND; var Width, Height: Integer); procedure FinalizeVideoWindow; procedure WndProc(var AMessage: TMessage); public constructor Create; destructor Destroy; override; function InitializeAudioFile(FileName: PWideChar; CallbackProc: TDirectShowEventProc): HRESULT; function InitializeVideoFile(FileName: PWideChar; WindowHandle: HWND; var Width, Height: Integer; CallbackProc: TDirectShowEventProc): HRESULT; function PlayMediaFile: HRESULT; function StopMediaPlay: HRESULT; function PauseMediaPlay: HRESULT; function SetVolume(Value: LongInt): HRESULT; function SetBalance(Value: LongInt): HRESULT; property LastError: HRESULT read FLastError; end; function DSGetLastError(var ErrorText: PWideChar): HRESULT; stdcall; function DSInitializeAudioFile(FileName: PWideChar; CallbackProc: TDirectShowEventProc): Boolean; stdcall; function DSInitializeVideoFile(const FileName: PWideChar; WindowHandle: HWND; var Width, Height: Integer; CallbackProc: TDirectShowEventProc): Boolean; stdcall; function DSPlayMediaFile: Boolean; stdcall; function DSStopMediaPlay: Boolean; stdcall; function DSPauseMediaPlay: Boolean; stdcall; function DSSetVolume(Value: LongInt): Boolean; stdcall; function DSSetBalance(Value: LongInt): Boolean; stdcall; var DirectShowPlayer: TDirectShowPlayer; implementation { EDirectShowPlayerException } constructor EDirectShowPlayerException.Create(ErrorCode: HRESULT); begin FErrorCode := ErrorCode; inherited Create(''); end; { TDirectShowPlayer } constructor TDirectShowPlayer.Create; begin inherited Create; FPlayerState := dspsUninitialized; FWindowHandle := AllocateHWnd(WndProc); end; destructor TDirectShowPlayer.Destroy; begin StopMediaPlay; DeallocateHWnd(FWindowHandle); inherited; end; function TDirectShowPlayer.ErrorCheck(Value: HRESULT): HRESULT; var DirectShowPlayerException: EDirectShowPlayerException; begin Result := Value; FLastError := Value; if Failed(Value) then begin DirectShowPlayerException := EDirectShowPlayerException.Create(Value); raise DirectShowPlayerException; end; end; procedure TDirectShowPlayer.InitializeMediaPlay(FileName: PWideChar); begin ErrorCheck(FGraphBuilder.RenderFile(FileName, nil)); end; procedure TDirectShowPlayer.FinalizeMediaPlay; begin if Assigned(FMediaControl) then ErrorCheck(FMediaControl.Stop); end; procedure TDirectShowPlayer.InitializeFilterGraph; begin ErrorCheck(CoCreateInstance(CLSID_FilterGraph, nil, CLSCTX_INPROC_SERVER, IID_IFilterGraph2, FGraphBuilder)); ErrorCheck(FGraphBuilder.QueryInterface(IBasicAudio, FBasicAudio)); ErrorCheck(FGraphBuilder.QueryInterface(IMediaControl, FMediaControl)); ErrorCheck(FGraphBuilder.QueryInterface(IMediaEventEx, FMediaEventEx)); ErrorCheck(FMediaEventEx.SetNotifyFlags(0)); ErrorCheck(FMediaEventEx.SetNotifyWindow(FWindowHandle, WM_GRAPH_NOTIFY, ULONG(FMediaEventEx))); FPlayerState := dspsInitialized; end; procedure TDirectShowPlayer.FinalizeFilterGraph; begin FBasicAudio := nil; FMediaEventEx := nil; FMediaControl := nil; FGraphBuilder := nil; FPlayerState := dspsUninitialized; end; procedure TDirectShowPlayer.InitializeVideoWindow(WindowHandle: HWND; var Width, Height: Integer); begin ErrorCheck(FGraphBuilder.QueryInterface(IVideoWindow, FVideoWindow)); ErrorCheck(FVideoWindow.put_Owner(WindowHandle)); ErrorCheck(FVideoWindow.put_MessageDrain(WindowHandle)); ErrorCheck(FVideoWindow.put_WindowStyle(WS_CHILD or WS_CLIPSIBLINGS)); ErrorCheck(FVideoWindow.put_Left(0)); ErrorCheck(FVideoWindow.put_Top(0)); if (Width = 0) or (Height = 0) then begin FVideoWindow.get_Width(Width); FVideoWindow.get_Height(Height); end else begin FVideoWindow.put_Width(Width); FVideoWindow.put_Height(Height); end; end; procedure TDirectShowPlayer.FinalizeVideoWindow; begin if Assigned(FVideoWindow) then begin ErrorCheck(FVideoWindow.put_Visible(False)); ErrorCheck(FVideoWindow.put_Owner(0)); FVideoWindow := nil; end; end; function TDirectShowPlayer.InitializeAudioFile(FileName: PWideChar; CallbackProc: TDirectShowEventProc): HRESULT; begin Result := S_FALSE; try FEventCallback := CallbackProc; if FPlayerState in [dspsPlaying, dspsPaused] then FinalizeMediaPlay; if FPlayerState <> dspsUninitialized then begin FinalizeVideoWindow; FinalizeFilterGraph; end; InitializeFilterGraph; InitializeMediaPlay(FileName); except Result := FLastError; FinalizeVideoWindow; FinalizeFilterGraph; end; end; function TDirectShowPlayer.InitializeVideoFile(FileName: PWideChar; WindowHandle: HWND; var Width, Height: Integer; CallbackProc: TDirectShowEventProc): HRESULT; begin Result := S_FALSE; try FEventCallback := CallbackProc; if FPlayerState in [dspsPlaying, dspsPaused] then FinalizeMediaPlay; if FPlayerState <> dspsUninitialized then begin FinalizeVideoWindow; FinalizeFilterGraph; end; InitializeFilterGraph; InitializeMediaPlay(FileName); InitializeVideoWindow(WindowHandle, Width, Height); except Result := FLastError; FinalizeVideoWindow; FinalizeFilterGraph; end; end; function TDirectShowPlayer.PlayMediaFile: HRESULT; begin Result := S_FALSE; try if FPlayerState = dspsInitialized then Result := ErrorCheck(FMediaControl.Run); FPlayerState := dspsPlaying; except Result := FLastError; end; end; function TDirectShowPlayer.StopMediaPlay: HRESULT; begin Result := S_FALSE; try if FPlayerState in [dspsPlaying, dspsPaused] then FinalizeMediaPlay; if FPlayerState <> dspsUninitialized then begin FinalizeVideoWindow; FinalizeFilterGraph; end; except Result := FLastError; end; end; function TDirectShowPlayer.PauseMediaPlay: HRESULT; begin Result := S_FALSE; try if FPlayerState = dspsInitialized then Result := ErrorCheck(FMediaControl.Pause); FPlayerState := dspsPaused; except Result := FLastError; end; end; function TDirectShowPlayer.SetVolume(Value: LongInt): HRESULT; begin try Result := ErrorCheck(FBasicAudio.put_Volume(Value)); except Result := FLastError; end; end; function TDirectShowPlayer.SetBalance(Value: LongInt): HRESULT; begin try Result := ErrorCheck(FBasicAudio.put_Balance(Value)); except Result := FLastError; end; end; procedure TDirectShowPlayer.WndProc(var AMessage: TMessage); begin if AMessage.Msg = WM_GRAPH_NOTIFY then try HandleEvents; except Application.HandleException(Self); end else AMessage.Result := DefWindowProc(FWindowHandle, AMessage.Msg, AMessage.WParam, AMessage.LParam); end; procedure TDirectShowPlayer.HandleEvents; var EventCode, Param1, Param2: Integer; begin if Assigned(FMediaEventEx) then begin while Succeeded(FMediaEventEx.GetEvent(EventCode, Param1, Param2, 0)) do begin FEventCallback(EventCode, Param1, Param2); FMediaEventEx.FreeEventParams(EventCode, Param1, Param2); end; end; end; function DSGetLastError(var ErrorText: PWideChar): HRESULT; begin Result := DirectShowPlayer.LastError; AMGetErrorText(Result, ErrorText, 256); end; function DSInitializeAudioFile(FileName: PWideChar; CallbackProc: TDirectShowEventProc): Boolean; begin Result := Succeeded(DirectShowPlayer.InitializeAudioFile(FileName, CallbackProc)); end; function DSInitializeVideoFile(const FileName: PWideChar; WindowHandle: HWND; var Width, Height: Integer; CallbackProc: TDirectShowEventProc): Boolean; begin Result := Succeeded(DirectShowPlayer.InitializeVideoFile(FileName, WindowHandle, Width, Height, CallbackProc)); end; function DSPlayMediaFile: Boolean; begin Result := Succeeded(DirectShowPlayer.PlayMediaFile); end; function DSStopMediaPlay: Boolean; begin Result := Succeeded(DirectShowPlayer.StopMediaPlay); end; function DSPauseMediaPlay: Boolean; begin Result := Succeeded(DirectShowPlayer.PauseMediaPlay); end; function DSSetVolume(Value: LongInt): Boolean; begin Result := Succeeded(DirectShowPlayer.SetVolume(Value)); end; function DSSetBalance(Value: LongInt): Boolean; begin Result := Succeeded(DirectShowPlayer.SetBalance(Value)); end; initialization DirectShowPlayer := TDirectShowPlayer.Create; finalization DirectShowPlayer.Free; end.
unit UnitStats; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Gauges, ExtCtrls, Math, AudioIO; type TFormStats = class(TForm) Label1: TLabel; TimerRefresh: TTimer; LbZeroTime: TLabel; Label2: TLabel; LbTimeProgress: TLabel; Label3: TLabel; LbVolInMax: TLabel; GaAudioInMaxLv: TGauge; Label4: TLabel; GaAudioLvMax: TGauge; LbMax: TLabel; GaFftMax: TGauge; Label5: TLabel; LbFftMax: TLabel; Label7: TLabel; GaFftSr: TGauge; Label8: TLabel; GaFftSrMax: TGauge; LbFftSrMax: TLabel; LbFftSr: TLabel; Label6: TLabel; LbAmplify: TLabel; BtAbout: TButton; Gauge1: TGauge; Label9: TLabel; Gauge2: TGauge; Label10: TLabel; procedure TimerRefreshTimer(Sender: TObject); procedure BtAboutClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormStats: TFormStats; implementation uses UnitMainForm, UnitAbout; {$R *.dfm} procedure TFormStats.TimerRefreshTimer(Sender: TObject); begin if FormStats.Visible = True then begin LbTimeProgress.Caption := TimeToStr(GetTime - StartTime); GaAudioLvMax.Progress := Round(OscMaxLv); LbMax.Caption := CurrToStr(OscMaxLv); GaAudioInMaxLv.Progress := ABS(AudioInMaxLv); if AudioInMaxLv > 32000 then GaAudioInMaxLv.ForeColor := clRed else GaAudioInMaxLv.ForeColor := clLime; // Poziom sygnału wejściowego LbVolInMax.Caption := IntToStr(AudioInMaxLv); GaFftMax.Progress := FftMaxLv; LbFftMax.Caption := IntToStr(FftMaxLv); GaFftSr.Progress := Round(FftSr); LbFftSr.Caption := IntToStr(Round(FftSr)); GaFftSrMax.Progress := Round(FftSrMax); LbFftSrMax.Caption := IntToStr(Round(FftSrMax)); LbAmplify.Caption := IntToStr(Round((aAmplify-1)*100)) + '%'; Label9.Caption := 'Czas przerwy: ' + Inttostr(CzasPrzerwy); Gauge1.Progress := CzasPrzerwy; end; end; procedure TFormStats.BtAboutClick(Sender: TObject); begin FormAbout.ShowModal; end; end.
unit FIToolkit.Commons.StateMachine; interface uses FIToolkit.Commons.Exceptions{, FIToolkit.Commons.FiniteStateMachine.FSM}; type EStateMachineError = class (ECustomException); //TODO: implement {F2084 Internal Error: URW1175} // IStateMachine<TState, TCommand> = interface (IFiniteStateMachine<TState, TCommand, EStateMachineError>) // end; // // TStateMachine<TState, TCommand> = class (TFiniteStateMachine<TState, TCommand, EStateMachineError>, // IStateMachine<TState, TCommand>); implementation uses FIToolkit.Commons.Consts; initialization RegisterExceptionMessage(EStateMachineError, RSStateMachineError); end.
{ ****************************************************************************** ___ __ ____ _ _ _ ____ __ ____ ____ ____ / __)/ \( _ \( \/ ) / ) ( _ \ / _\ / ___)(_ _)( __) ( (__( O )) __/ ) / / / ) __// \\___ \ )( ) _) \___)\__/(__) (__/ (_/ (__) \_/\_/(____/ (__) (____) Extended Controls unit Components: TCollapseBtn = Extend the TButton class TSelectorBox = Extend the TListBox class TTrackOnlyItem = The collection item for the MonitorCollection TTrackOnlyCollection = The collection that will hold the items we want to track TCopyPasteThread = Thread used to task off the lookup when pasting { ****************************************************************************** } unit U_CPTExtended; interface uses Winapi.Windows, Classes, Vcl.StdCtrls, Vcl.Graphics, Vcl.Controls, Winapi.Messages, U_CPTCommon, System.SysUtils, Vcl.Clipbrd, Vcl.ComCtrls, Vcl.Forms, Vcl.ExtCtrls; Type // -------- OverWrite Classes --------// TCollapseBtn = class(TButton) public procedure Click; override; end; TSelectorBox = class(TListBox) private fSelectorColor: TColor; fLinkedRichEdit: TRichEdit; procedure OurDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKilFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; public procedure Click; override; constructor Create(AOwner: TComponent); override; Property SelectorColor: TColor Read fSelectorColor write fSelectorColor; Property LinkedRichEdit: TRichEdit read fLinkedRichEdit write fLinkedRichEdit; end; TTrackOnlyItem = class(TCollectionItem) private FObject: TCustomEdit; FOurOrigWndProc: TWndMethod; procedure SetTrackObject(const Value: TCustomEdit); procedure OurWndProc(var Message: TMessage); protected function GetDisplayName: String; override; procedure SetCollection(Value: TCollection); override; public procedure Assign(Source: TPersistent); override; Property TrackObjectOrigWndProc: TWndMethod read FOurOrigWndProc write FOurOrigWndProc; published property TrackObject: TCustomEdit read FObject write SetTrackObject; end; TTrackOnlyCollection = class(TCollection) private FOwner: TComponent; procedure SetObjectToMonitor(TrackItem: TTrackOnlyItem); protected function GetOwner: TPersistent; override; procedure SetItem(Index: Integer; Value: TTrackOnlyItem); procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TComponent); destructor Destroy(); override; procedure Delete(Index: Integer); function Add: TTrackOnlyItem; function GetItem(Index: Integer): TTrackOnlyItem; function Insert(Index: Integer): TTrackOnlyItem; property Items[Index: Integer]: TTrackOnlyItem read GetItem write SetItem; default; end; // -------- Threads --------// TCopyPasteThread = class(TThread) private fAppMonitor: TComponent; fEdtMonitor: TObject; fItemIEN: Int64; fPasteDetails: String; fPasteText: String; fClipInfo: tClipInfo; protected procedure Execute; override; public constructor Create(PasteText, PasteDetails: string; ItemIEN: Int64; AppMonitor: TComponent; EditMonitor: TObject; ClipInfo: tClipInfo); destructor Destroy; override; property TheadOwner: Int64 read fItemIEN; end; TCopyPasteThreadArry = Array of TCopyPasteThread; implementation Uses U_CPTAppMonitor, U_CPTEditMonitor, U_CPTPasteDetails, WinApi.RichEdit, System.SyncObjs; {$REGION 'Thread'} constructor TCopyPasteThread.Create(PasteText, PasteDetails: String; ItemIEN: Int64; AppMonitor: TComponent; EditMonitor: TObject; ClipInfo: tClipInfo); begin inherited Create(true); FreeOnTerminate := true; fAppMonitor := AppMonitor; fEdtMonitor := EditMonitor; fPasteText := PasteText; fPasteDetails := PasteDetails; fClipInfo := ClipInfo; fItemIEN := ItemIEN; TCopyApplicationMonitor(fAppMonitor).LogText('THREAD', 'Thread created'); end; destructor TCopyPasteThread.Destroy; var I: Integer; procedure DeleteX(const Index: Cardinal); var ALength: Cardinal; x: Integer; begin with TCopyApplicationMonitor(fAppMonitor) do begin TCopyApplicationMonitor(fAppMonitor).CriticalSection.Enter; try ALength := Length(fCopyPasteThread); for x := Index + 1 to ALength - 1 do fCopyPasteThread[x - 1] := fCopyPasteThread[x]; SetLength(fCopyPasteThread, ALength - 1); finally TCopyApplicationMonitor(fAppMonitor).CriticalSection.Leave; end; end; end; begin inherited; with TCopyApplicationMonitor(fAppMonitor) do begin TCopyApplicationMonitor(fAppMonitor).CriticalSection.Enter; try for I := high(fCopyPasteThread) downto low(fCopyPasteThread) do begin if fCopyPasteThread[I] = Self then begin DeleteX(I); LogText('THREAD', 'Thread deleted'); end; end; Finally TCopyApplicationMonitor(fAppMonitor).CriticalSection.Leave; end; end; end; procedure TCopyPasteThread.Execute; begin TCopyApplicationMonitor(fAppMonitor).LogText('THREAD', 'Looking for matches'); TCopyApplicationMonitor(fAppMonitor).PasteToCopyPasteClipboard(fPasteText, fPasteDetails, fItemIEN, fClipInfo); end; {$ENDREGION} {$REGION 'TCollapseBtn'} procedure TCollapseBtn.Click; begin inherited; TCopyPasteDetails(Self.owner).CloseInfoPanel(Self); // Do not put any code past this line (event is triggered above) end; {$ENDREGION} {$REGION 'TSelectorBox'} constructor TSelectorBox.Create(AOwner: TComponent); begin inherited Create(AOwner); if not (csDesigning in ComponentState) then begin Self.Style := lbOwnerDrawFixed; OnDrawItem := OurDrawItem; end; end; procedure TSelectorBox.Click; begin inherited; if not (csDesigning in ComponentState) then TCopyPasteDetails(Self.owner).lbSelectorClick(Self); end; procedure TSelectorBox.WMSetFocus(var Message: TWMSetFocus); begin if not (csDesigning in ComponentState) then SelectorColor := clHighlight; inherited; end; procedure TSelectorBox.WMKilFocus(var Message: TWMKillFocus); begin if not (csDesigning in ComponentState) then SelectorColor := clLtGray; inherited; end; procedure TSelectorBox.OurDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin with Self.Canvas do begin if odSelected in State then Brush.Color := Self.SelectorColor; FillRect(Rect); TextOut(Rect.Left, Rect.Top, Self.Items[Index]); if odFocused In State then begin Brush.Color := Self.Color; DrawFocusRect(Rect); end; end; end; procedure TSelectorBox.CMFontChanged(var Message: TMessage); var ResetMask: Integer; begin inherited; //grab the font canvas.font := font; with Self.Canvas do begin if ItemHeight <> TextHeight('Az') then begin //If font adjusted then update the item height ItemHeight := TextHeight('Az'); Invalidate; if Assigned(fLinkedRichEdit) then begin ResetMask := fLinkedRichEdit.Perform(EM_GETEVENTMASK, 0, 0); fLinkedRichEdit.Perform(EM_SETEVENTMASK, 0, 0); fLinkedRichEdit.Perform(WM_SETREDRAW, Ord(False), 0); try fLinkedRichEdit.SelAttributes.Size := font.Size; fLinkedRichEdit.font.Size := font.Size; finally fLinkedRichEdit.Perform(WM_SETREDRAW, Ord(true), 0); InvalidateRect(fLinkedRichEdit.Handle, NIL, true); fLinkedRichEdit.Perform(EM_SETEVENTMASK, 0, ResetMask); end; end; end; end; end; {$ENDREGION} {$REGION 'TTrackOnlyItem'} procedure TTrackOnlyItem.Assign(Source: TPersistent); begin if Source is TTrackOnlyItem then TrackObject := TTrackOnlyItem(Source).TrackObject else inherited; // raises an exception end; function TTrackOnlyItem.GetDisplayName: String; begin if Assigned(FObject) then Result := FObject.Name else Result := Format('Track Edit %d', [Index]); end; procedure TTrackOnlyItem.SetTrackObject(const Value: TCustomEdit); // var // CollOwner: TComponent; begin FObject := Value; if not (csDesigning in Application.ComponentState) then begin // CollOwner := TTrackOnlyCollection(Collection).FOwner; if Assigned(Value) then begin FOurOrigWndProc := FObject.WindowProc; FObject.WindowProc := OurWndProc; end; end; end; procedure TTrackOnlyItem.OurWndProc(var Message: TMessage); var ShiftState: TShiftState; FireMessage: Boolean; Procedure PerformPaste(EditMonitorObj: TCopyEditMonitor; TheEdit: TCustomEdit); var ClpInfo: tClipInfo; begin if Clipboard.HasFormat(CF_TEXT) then begin ClpInfo := EditMonitorObj.CopyMonitor.GetClipSource; EditMonitorObj.PasteToMonitor(Self, TheEdit, true, ClpInfo); end; end; Procedure PerformCopyCut(EditMonitorObj: TCopyEditMonitor; TheEdit: TCustomEdit; CMsg: Cardinal); begin EditMonitorObj.CopyToMonitor(TheEdit, true, CMsg); end; begin FireMessage := true; if Assigned(TTrackOnlyCollection(Collection).FOwner) then begin if Assigned(TCopyEditMonitor(TTrackOnlyCollection(Collection).FOwner) .CopyMonitor) then begin if TCopyEditMonitor(TTrackOnlyCollection(Collection).FOwner).CopyMonitor.Enabled then begin case Message.Msg of WM_PASTE: begin PerformPaste(TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject); FireMessage := false; end; WM_COPY: begin PerformCopyCut(TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject, Message.Msg); FireMessage := false; end; WM_CUT: begin PerformCopyCut(TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject, Message.Msg); FireMessage := false; end; WM_KEYDOWN: begin if (FObject is TRichEdit) then begin ShiftState := KeyDataToShiftState(Message.WParam); if (ssCtrl in ShiftState) then begin if (Message.WParam = Ord('V')) then begin PerformPaste (TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject); FireMessage := false; end else if (Message.WParam = Ord('C')) then begin PerformCopyCut (TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject, Message.Msg); FireMessage := false; end else if (Message.WParam = Ord('X')) then begin PerformCopyCut (TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject, Message.Msg); FireMessage := false; end else if (Message.WParam = VK_INSERT) then begin PerformPaste (TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject); FireMessage := false; end; end else if (ssShift in ShiftState) then begin if (Message.WParam = VK_INSERT) then begin PerformPaste (TCopyEditMonitor(TTrackOnlyCollection(Collection) .FOwner), FObject); FireMessage := false; end; end; end; end; end; end; end; end; if FireMessage then FOurOrigWndProc(Message); end; {$ENDREGION} {$REGION 'TTrackOnlyCollection'} function TTrackOnlyCollection.Add: TTrackOnlyItem; begin Result := TTrackOnlyItem(inherited Add); SetObjectToMonitor(Result); end; constructor TTrackOnlyCollection.Create(AOwner: TComponent); begin inherited Create(TTrackOnlyItem); FOwner := AOwner; end; destructor TTrackOnlyCollection.Destroy(); begin inherited Destroy; end; procedure TTrackOnlyCollection.Delete(Index: Integer); begin // TTrackOnlyItem(GetItem(Index)).FObject.WindowProc := TTrackOnlyItem(GetItem(Index)).FOurOrigWndProc; inherited Delete(Index); end; function TTrackOnlyCollection.GetItem(Index: Integer): TTrackOnlyItem; begin Result := TTrackOnlyItem(inherited GetItem(Index)); end; function TTrackOnlyCollection.GetOwner: TPersistent; begin Result := FOwner; end; function TTrackOnlyCollection.Insert(Index: Integer): TTrackOnlyItem; begin Result := TTrackOnlyItem(inherited Insert(Index)); SetObjectToMonitor(Result); end; procedure TTrackOnlyCollection.SetItem(Index: Integer; Value: TTrackOnlyItem); begin inherited SetItem(Index, Value); SetObjectToMonitor(Value); end; procedure TTrackOnlyCollection.Update(Item: TCollectionItem); begin inherited Update(Item); end; procedure TTrackOnlyCollection.SetObjectToMonitor(TrackItem: TTrackOnlyItem); begin end; { procedure TTrackOnlyCollection.RemoveItem(Item: TCollectionItem); begin if Item is TTrackOnlyItem then begin TTrackOnlyItem(Item).FObject.WindowProc := TTrackOnlyItem(Item).FOurOrigWndProc; end; inherited; end; } procedure TTrackOnlyItem.SetCollection(Value: TCollection); begin // if (Collection <> Value) and assigned(Collection) then // FObject.WindowProc := FOurOrigWndProc; inherited; end; {$ENDREGION} end.
unit rMisc; interface uses SysUtils, Windows, Classes, Forms, Controls, ComCtrls, Grids, ORFn, ORNet, Menus, Contnrs, StrUtils; const MAX_TOOLITEMS = 30; type TToolMenuItem = class public Caption: string; Caption2: string; Action: string; MenuID: string; SubMenuID: string; MenuItem: TMenuItem; end; TDLL_Return_Type = (DLL_Success, DLL_Missing, DLL_VersionErr); TDllRtnRec = Record DLLName: string; LibName: string; DLL_HWND: HMODULE; Return_Type: TDLL_Return_Type; Return_Message: String; End; var uToolMenuItems: TObjectList = nil; type {An Object of this Class is Created to Hold the Sizes of Controls(Forms) while the app is running, thus reducing calls to RPCs SAVESIZ and LOADSIZ} TSizeHolder = class(TObject) private FSizeList,FNameList: TStringList; public constructor Create; destructor Destroy; override; function GetSize(AName: String): String; procedure SetSize(AName,ASize: String); procedure AddSizesToStrList(theList: TStringList); end; SettingSizeArray = array of integer; function DetailPrimaryCare(const DFN: string): TStrings; //*DFN* procedure GetToolMenu; procedure ListSymbolTable(Dest: TStrings); function MScalar(const x: string): string; deprecated; procedure SetShareNode(const DFN: string; AHandle: HWND); //*DFN* function ServerHasPatch(const x: string): Boolean; function SiteSpansIntlDateLine: boolean; function RPCCheck(aRPC: TStrings):Boolean; function ServerVersion(const Option, VerClient: string): string; function PackageVersion(const Namespace: string): string; function ProgramFilesDir: string; function ApplicationDirectory: string; function VistaCommonFilesDirectory: string; function DropADir(DirName: string): string; function RelativeCommonFilesDirectory: string; function FindDllDir(DllName: string): string; function LoadDll(DllName: string): TDllRtnRec; function DllVersionCheck(DllName: string; DLLVersion: string): string; function GetMOBDLLName(): string; procedure SaveUserBounds(AControl: TControl); procedure SaveUserSizes(SizingList: TStringList); procedure SetFormPosition(AForm: TForm); procedure SetUserBounds(var AControl: TControl); procedure SetUserBounds2(AName: string; var v1, v2, v3, v4: integer); //procedure SetUserBoundsArray(AName: string; var SettingArray: SettingSizeArray); procedure SetUserWidths(var AControl: TControl); procedure SetUserColumns(var AControl: TControl); procedure SetUserString(StrName: string; var Str: string); function StrUserBounds(AControl: TControl): string; function StrUserBounds2(AName: string; v1, v2, v3, v4: integer): string; function StrUserBoundsArray(AName: string; SizeArray: SettingSizeArray): string; function StrUserWidth(AControl: TControl): string; function StrUserColumns(AControl: TControl): string; function StrUserString(StrName: string; Str: string): string; function UserFontSize: integer; procedure SaveUserFontSize( FontSize: integer); var SizeHolder : TSizeHolder; implementation uses TRPCB, fOrders, math, Registry, ORSystem, rCore, System.Generics.Collections; var uBounds, uWidths, uColumns: TStringList; function DetailPrimaryCare(const DFN: string): TStrings; //*DFN* begin CallV('ORWPT1 PCDETAIL', [DFN]); Result := RPCBrokerV.Results; end; const SUBMENU_KEY = 'SUBMENU'; SUBMENU_KEY_LEN = length(SUBMENU_KEY); SUB_LEFT = '['; SUB_RIGHT = ']'; MORE_ID = 'MORE^'; MORE_NAME = 'More...'; procedure GetToolMenu; var i, p, LastIdx, count, MenuCount, SubCount: Integer; id, x: string; LastItem, item: TToolMenuItem; caption, action: string; CurrentMenuID: string; MenuIDs: TStringList; begin if not assigned(uToolMenuItems) then uToolMenuItems := TObjectList.Create else uToolMenuItems.Clear; CallV('ORWU TOOLMENU', [nil]); MenuIDs := TStringList.Create; try for i := 0 to RPCBrokerV.Results.Count - 1 do begin x := Piece(RPCBrokerV.Results[i], U, 1); item := TToolMenuItem.Create; Caption := Piece(x, '=', 1); Action := Copy(x, Pos('=', x) + 1, Length(x)); item.Caption2 := Caption; if UpperCase(copy(Action,1,SUBMENU_KEY_LEN)) = SUBMENU_KEY then begin id := UpperCase(Trim(Copy(Action, SUBMENU_KEY_LEN+1, MaxInt))); if (LeftStr(id,1) = SUB_LEFT) and (RightStr(id,1) = SUB_RIGHT) then id := copy(id, 2, length(id)-2); item.MenuID := id; Action := ''; if MenuIDs.IndexOf(item.MenuID) < 0 then MenuIDs.Add(item.MenuID) else begin item.SubMenuID := item.MenuID; item.MenuID := ''; end; end; if RightStr(Caption, 1) = SUB_RIGHT then begin p := length(Caption) - 2; while (p > 0) and (Caption[p] <> SUB_LEFT) do dec(p); if (p > 0) and (Caption[p] = SUB_LEFT) then begin item.SubMenuID := UpperCase(Trim(copy(Caption,p+1, length(Caption)-1-p))); Caption := copy(Caption,1,p-1); end; end; item.Caption := Caption; item.Action := Action; uToolMenuItems.add(item); end; // see if all child menu items have parents for I := 0 to uToolMenuItems.Count - 1 do begin item := TToolMenuItem(uToolMenuItems[i]); if MenuIDs.IndexOf(item.SubMenuID) < 0 then begin item.SubMenuID := ''; item.Caption := item.Caption2; end; end; // see if there are more than MAX_TOOLITEMS in the root menu // if there are, add automatic sub menus // SubCount tracks items for sub menus and is used as offsent when inserting // More... into the list of menu items LastIdx := (MAX_TOOLITEMS - 1); count := 0; CurrentMenuID := ''; i := 0; LastItem := nil; MenuCount := 0; SubCount := 0; repeat item := TToolMenuItem(uToolMenuItems[i]); if item.SubMenuID <> '' then inc(SubCount); if item.SubMenuID = '' then begin item.SubMenuID := CurrentMenuID; inc(count); if Count > MAX_TOOLITEMS then begin item.SubMenuID := ''; inc(MenuCount); item := TToolMenuItem.Create; item.Caption := MORE_NAME; item.MenuID := MORE_ID + IntToStr(MenuCount); item.SubMenuID := CurrentMenuID; CurrentMenuID := item.MenuID; LastItem.SubMenuID := CurrentMenuID; uToolMenuItems.Insert(LastIdx + SubCount, item); inc(LastIdx,MAX_TOOLITEMS); Count := 1; end; LastItem := item; end; inc(i); until i >= uToolMenuItems.Count; finally MenuIDs.Free; end; end; procedure ListSymbolTable(Dest: TStrings); var i: Integer; x: string; begin Dest.Clear; CallV('ORWUX SYMTAB', [nil]); i := 0; with RPCBrokerV.Results do while i < Count do begin x := Strings[i] + '='; Inc(i); if i < Count then x := x + Strings[i]; Dest.Add(x); Inc(i); end; end; function MScalar(const x: string): string; begin LockBroker; try with RPCBrokerV do begin ClearParameters := True; RemoteProcedure := 'XWB GET VARIABLE VALUE'; Param[0].Value := x; Param[0].PType := reference; CallBroker; Result := Results[0]; end; finally UnlockBroker; end; end; function ServerHasPatch(const x: string): Boolean; begin Result := sCallV('ORWU PATCH', [x]) = '1'; end; function SiteSpansIntlDateLine: boolean; begin Result := sCallV('ORWU OVERDL', []) = '1'; end; function RPCCheck(aRPC: TStrings):Boolean; //aRPC format array of RPC's Name^Version //All RPC's in the list must come back true/active var i: integer; begin Result := false; CallV('XWB ARE RPCS AVAILABLE',['L',aRPC]); if RPCBrokerV.Results.Count > 0 then for i := 0 to RPCBrokerV.Results.Count - 1 do begin if RPCBrokerV.Results[i] = '1' then Result := true else begin Result := false; Break; end; end; end; function ServerVersion(const Option, VerClient: string): string; begin Result := sCallV('ORWU VERSRV', [Option, VerClient]); end; function PackageVersion(const Namespace: string): string; begin Result := sCallV('ORWU VERSION', [Namespace]); end; function UserFontSize: integer; begin Result := StrToIntDef(sCallV('ORWCH LDFONT', [nil]),8); If Result = 24 then Result := 18; // CQ #12322 removed 24 pt font if Result = 18 then Result := 14; // Same thing as before, can't handle font size anymore end; procedure LoadSizes; var i, p: Integer; begin uBounds := TStringList.Create; uWidths := TStringList.Create; uColumns := TStringList.Create; CallV('ORWCH LOADALL', [nil]); with RPCBrokerV do begin for i := 0 to Results.Count - 1 do // change '^' to '=' begin p := Pos(U, Results[i]); if p > 0 then Results[i] := Copy(Results[i], 1, p - 1) + '=' + Copy(Results[i], p + 1, Length(Results[i])); end; ExtractItems(uBounds, RPCBrokerV.Results, 'Bounds'); ExtractItems(uWidths, RPCBrokerV.Results, 'Widths'); ExtractItems(uColumns, RPCBrokerV.Results, 'Columns'); end; end; procedure SetShareNode(const DFN: string; AHandle: HWND); //*DFN* begin // sets node that allows other apps to see which patient is currently selected sCallV('ORWPT SHARE', [DottedIPStr, IntToHex(AHandle, 8), DFN]); end; function GetControlName(var AControl: TControl): string; begin Result := ''; try if assigned(AControl) then begin Result := AControl.Name; if (not (AControl is TForm)) and Assigned(AControl.Owner) then Result := AControl.Owner.Name + '.' + Result; end; except Result := ''; end; end; procedure SetUserBounds(var AControl: TControl); var x: string; begin x := GetControlName(AControl); if x = '' then exit; if uBounds = nil then LoadSizes; x := uBounds.Values[x]; if (x = '0,0,0,0') and (AControl is TForm) then TForm(AControl).WindowState := wsMaximized else begin AControl.Left := HigherOf(StrToIntDef(Piece(x, ',', 1), AControl.Left), 0); AControl.Top := HigherOf(StrToIntDef(Piece(x, ',', 2), AControl.Top), 0); if (AControl is TForm) then TForm(AControl).MakeFullyVisible; if Assigned( AControl.Parent ) then begin AControl.Width := LowerOf(StrToIntDef(Piece(x, ',', 3), AControl.Width), AControl.Parent.Width - AControl.Left); AControl.Height := LowerOf(StrToIntDef(Piece(x, ',', 4), AControl.Height), AControl.Parent.Height - AControl.Top); end else begin AControl.Width := StrToIntDef(Piece(x, ',', 3), AControl.Width); AControl.Height := StrToIntDef(Piece(x, ',', 4), AControl.Height); end; end; //if (x = '0,0,' + IntToStr(Screen.Width) + ',' + IntToStr(Screen.Height)) and // (AControl is TForm) then TForm(AControl).WindowState := wsMaximized; end; procedure SetUserBounds2(AName: string; var v1, v2, v3, v4: integer); var x: string; begin if uBounds = nil then LoadSizes; x := uBounds.Values[AName]; v1 := StrToIntDef(Piece(x, ',', 1), 0); v2 := StrToIntDef(Piece(x, ',', 2), 0); v3 := StrToIntDef(Piece(x, ',', 3), 0); v4 := StrToIntDef(Piece(x, ',', 4), 0); end; { procedure SetUserBoundsArray(AName: string; var SettingArray: SettingSizeArray); var i: integer; x: string; begin if uBounds = nil then LoadSizes; x := uBounds.Values[AName]; SetLength(SettingArray, uBounds.Count); for i := 0 to (uBounds.Count - 1) do begin SettingArray[i] := StrToIntDef(Piece(x, ',', i), 0); end; end; } procedure SetUserWidths(var AControl: TControl); var x: string; begin x := GetControlName(AControl); if x = '' then exit; if uWidths = nil then LoadSizes; x := uWidths.Values[x]; if Assigned (AControl.Parent) then AControl.Width := LowerOf(StrToIntDef(x, AControl.Width), AControl.Parent.Width - AControl.Left) else AControl.Width := StrToIntDef(x, AControl.Width); end; procedure SetUserColumns(var AControl: TControl); var x: string; i, AWidth: Integer; couldSet: boolean; begin x := GetControlName(AControl); if x = '' then exit; couldSet := False; if uColumns = nil then LoadSizes; if AnsiCompareText(x,'frmOrders.hdrOrders')=0 then couldSet := True; x := uColumns.Values[x]; if AControl is THeaderControl then with THeaderControl(AControl) do for i := 0 to Sections.Count - 1 do begin //Make sure all of the colmumns fit, even if it means scrunching the last ones. AWidth := LowerOf(StrToIntDef(Piece(x, ',', i + 1), 0), HigherOf(ClientWidth - (Sections.Count - i)*5 - Sections.Items[i].Left, 5)); if AWidth > 0 then Sections.Items[i].Width := AWidth; if couldSet and (i=0) and (AWidth>0) then frmOrders.EvtColWidth := AWidth; end; if AControl is TCustomGrid then {nothing for now}; end; procedure SetUserString(StrName: string; var Str: string); begin Str := uColumns.Values[StrName]; end; procedure SaveUserBounds(AControl: TControl); var x, n: string; NewHeight: integer; begin n := GetControlName(AControl); if n = '' then exit; if (AControl is TForm) and (TForm(AControl).WindowState = wsMaximized) then x := '0,0,0,0' else with AControl do begin //Done to remove the adjustment for Window XP style before saving the form size NewHeight := Height - (GetSystemMetrics(SM_CYCAPTION) - 19); x := IntToStr(Left) + ',' + IntToStr(Top) + ',' + IntToStr(Width) + ',' + IntToStr(NewHeight); end; // CallV('ORWCH SAVESIZ', [AControl.Name, x]); SizeHolder.SetSize(n, x); end; procedure SaveUserSizes(SizingList: TStringList); begin CallV('ORWCH SAVEALL', [SizingList]); end; procedure SaveUserFontSize( FontSize: integer); begin CallV('ORWCH SAVFONT', [IntToStr(FontSize)]); end; procedure SetFormPosition(AForm: TForm); var x: string; Rect: TRect; begin // x := sCallV('ORWCH LOADSIZ', [AForm.Name]); x := SizeHolder.GetSize(AForm.Name); if x = '' then Exit; // allow default bounds to be passed in, else screen center? if (x = '0,0,0,0') then AForm.WindowState := wsMaximized else begin AForm.SetBounds(StrToIntDef(Piece(x, ',', 1), AForm.Left), StrToIntDef(Piece(x, ',', 2), AForm.Top), StrToIntDef(Piece(x, ',', 3), AForm.Width), StrToIntDef(Piece(x, ',', 4), AForm.Height)); Rect := AForm.BoundsRect; ForceInsideWorkArea(Rect); AForm.BoundsRect := Rect; end; end; function StrUserBounds(AControl: TControl): string; var x: string; begin x := GetControlName(AControl); if x = '' then Result := '' else begin with AControl do Result := 'B' + U + x + U + IntToStr(Left) + ',' + IntToStr(Top) + ',' + IntToStr(Width) + ',' + IntToStr(Height); if (AControl is TForm) and (TForm(AControl).WindowState = wsMaximized) then Result := 'B' + U + x + U + '0,0,0,0'; end; end; function StrUserBounds2(AName: string; v1, v2, v3, v4: integer): string; begin Result := 'B' + U + AName + U + IntToStr(v1) + ',' + IntToStr(v2) + ',' + IntToStr(v3) + ',' + IntToStr(v4); end; function StrUserBoundsArray(AName: string; SizeArray: SettingSizeArray): string; var i: integer; begin Result := 'B' + U + AName + U; for i := 0 to (Length(SizeArray) - 1) do begin Result := Result + ',' + IntToStr(SizeArray[i]); end; end; function StrUserWidth(AControl: TControl): string; var x: string; begin x := GetControlName(AControl); if x = '' then Result := '' else begin with AControl do Result := 'W' + U + x + U + IntToStr(Width); end; end; function StrUserColumns(AControl: TControl): string; var x: string; i: Integer; shouldSave: boolean; begin x := GetControlName(AControl); if x = '' then Result := '' else begin shouldSave := False; if AnsiCompareText(x,'frmOrders.hdrOrders') = 0 then shouldSave := True; Result := 'C' + U + x + U; if AControl is THeaderControl then with THeaderControl(AControl) do for i := 0 to Sections.Count - 1 do begin if shouldSave and (i = 0) then Result := Result + IntToStr(frmOrders.EvtColWidth) + ',' else Result := Result + IntToStr(Sections.Items[i].Width) + ','; end; if AControl is TCustomGrid then {nothing for now}; if CharAt(Result, Length(Result)) = ',' then Result := Copy(Result, 1, Length(Result) - 1); end; end; function StrUserString(StrName: string; Str: string): string; begin Result := 'C' + U + StrName + U + Str; end; { TSizeHolder } procedure TSizeHolder.AddSizesToStrList(theList: TStringList); {Adds all the Sizes in the TSizeHolder Object to theList String list parameter} var i: integer; begin for i := 0 to FNameList.Count-1 do theList.Add('B' + U + FNameList[i] + U + FSizeList[i]); end; constructor TSizeHolder.Create; begin inherited; FNameList := TStringList.Create; FSizeList := TStringList.Create; end; destructor TSizeHolder.Destroy; begin FNameList.Free; FSizeList.Free; inherited; end; function TSizeHolder.GetSize(AName: String): String; {Fuctions returns a String of the Size(s) Of the Name parameter passed, if the Size(s) are already loaded into the object it will return those, otherwise it will make the apropriate RPC call to LOADSIZ} var rSizeVal: String; //return Size value nameIndex: integer; begin rSizeVal := ''; nameIndex := FNameList.IndexOf(AName); if nameIndex = -1 then //Currently Not in the NameList begin rSizeVal := sCallV('ORWCH LOADSIZ', [AName]); if rSizeVal <> '' then begin FNameList.Add(AName); FSizeList.Add(rSizeVal); end; end else //Currently is in the NameList rSizeVal := FSizeList[nameIndex]; result := rSizeVal; end; procedure TSizeHolder.SetSize(AName, ASize: String); {Store the Size(s) Of the ASize parameter passed, Associate it with the AName Parameter. This only stores the sizes in the objects member variables. to Store on the MUMPS Database call SendSizesToDB()} var nameIndex: integer; begin nameIndex := FNameList.IndexOf(AName); if nameIndex = -1 then //Currently Not in the NameList begin FNameList.Add(AName); FSizeList.Add(ASize); end else //Currently is in the NameList FSizeList[nameIndex] := ASize; end; function ProgramFilesDir: string; var Registry: TRegistry; begin Result := ''; Registry := TRegistry.Create; try Registry.RootKey := HKEY_LOCAL_MACHINE; Registry.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion'); if (TOSVersion.Architecture = arIntelX64) then begin Result := Registry.ReadString('ProgramFilesDir (x86)'); end else begin Result := Registry.ReadString('ProgramFilesDir'); end; Registry.CloseKey; Result := IncludeTrailingPathDelimiter(Result); finally Registry.Free; end; end; function ApplicationDirectory: string; begin Result := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)); end; function VistaCommonFilesDirectory: string; begin Result := ProgramFilesDir + 'Vista\Common Files\'; end; function DropADir(DirName: string): string; var i: integer; begin Result := DirName; i := Length(Result) - 1; while (i > 0) and (Result[i] <> '\') do dec(i); if (i = 0) then Result := '' else Result := IncludeTrailingPathDelimiter(copy(Result, 1, i)); end; function RelativeCommonFilesDirectory: string; begin Result := DropADir(ApplicationDirectory) + 'Common Files\'; end; function FindDllDir(DllName: string): string; begin if FileExists(ApplicationDirectory + DllName) then begin Result := ApplicationDirectory + DllName; end else if FileExists(RelativeCommonFilesDirectory + DllName) then begin Result := RelativeCommonFilesDirectory + DllName; end else if FileExists(VistaCommonFilesDirectory + DllName) then begin Result := VistaCommonFilesDirectory + DllName; end else begin Result := ''; end; end; var ConfigureLoadOnce: boolean = True; LoadOnce: boolean = False; LoadedDLLs: TList<TDllRtnRec> = nil; function LoadDll(DllName: string): TDllRtnRec; var LibName, TmpStr, HelpTxt: string; i: integer; procedure ConfigLoadOnce; begin if ConfigureLoadOnce then begin ConfigureLoadOnce := False; LoadOnce := GetUserParam('OR CPRS DISABLE DLL LOAD ONCE') <> '1'; if LoadOnce then LoadedDLLs := TList<TDllRtnRec>.Create; end; end; function LoadLib(Rec: TDllRtnRec): HMODULE; begin if Rec.LibName = '' then Result := LoadLibrary(PWideChar(Rec.DllName)) else Result := LoadLibrary(PWideChar(Rec.LibName)); end; procedure IncReferenceCount; begin if Result.Return_Type = DLL_Success then LoadLib(Result); end; begin ConfigLoadOnce; if LoadOnce then begin for i := 0 to LoadedDLLs.count - 1 do if LoadedDLLs[i].DLLName = DLLName then begin Result := LoadedDLLs[i]; IncReferenceCount; exit; end; end; LibName := FindDllDir(DllName); Result.DLLName := DLLName; Result.LibName := LibName; Result.DLL_HWND := LoadLib(Result); if Result.DLL_HWND <> 0 then Begin // DLL exist Result.Return_Type := DLL_Success; // Now check for the version string TmpStr := DllVersionCheck(DLLName, ClientVersion(LibName)); if Piece(TmpStr, U, 1) = '-1' then begin Result.Return_Message := StringReplace(Piece(TmpStr, U, 2), '#13', CRLF, [rfReplaceAll]); // DLL version mismatch Result.Return_Type := DLL_VersionErr; end else Result.Return_Message := ''; end else begin Result.Return_Type := DLL_Missing; HelpTxt := GetUserParam('OR CPRS HELP DESK TEXT'); if Trim(HelpTxt) <> '' then HelpTxt := CRLF + CRLF + 'Please contact ' + HelpTxt + ' to obtain this file.'; TmpStr := 'File must be located in one of these directories:' + CRLF + ApplicationDirectory + CRLF + RelativeCommonFilesDirectory + CRLF + VistaCommonFilesDirectory; Result.Return_Message := DLLName + ' was not found. ' + HelpTxt + CRLF + CRLF + TmpStr; end; if LoadOnce then begin LoadedDLLs.Add(Result); IncReferenceCount; end; end; function DllVersionCheck(DllName: string; DLLVersion: string): string; begin Result := sCallV('ORUTL4 DLL', [DllName, DllVersion]); end; function GetMOBDLLName(): string; begin Result := GetUserParam('OR MOB DLL NAME'); end; initialization // nothing for now finalization if uBounds <> nil then uBounds.Free; if uWidths <> nil then uWidths.Free; if uColumns <> nil then uColumns.Free; if assigned(uToolMenuItems) then FreeAndNil(uToolMenuItems); if assigned(LoadedDLLs) then FreeAndNil(LoadedDLLs); end.
unit GameLibrary_ServerAccess; {$I RemObjects.inc} interface uses {$IFDEF DELPHIXE2UP}System.SysUtils{$ELSE}SysUtils{$ENDIF}, {$IFDEF DELPHIXE2UP}System.Classes{$ELSE}Classes{$ENDIF}, uROComponent, uROMessage, uROBaseConnection, uROTransportChannel, uROBinMessage, uROBaseHTTPClient, uROIndyHTTPChannel, GameLibrary_Intf, System.TypInfo, uROClientIntf, uROAsync, uROServerLocator; type { Forward declarations } TServerAccess_GameLibrary = class; TServerAccess_GameLibrary = class(TDataModule) private fServerUrl: String; function get__ServerUrl: String; function get__GameService: IGameService; function get__GameService_Async: IGameService_Async; function get__GameService_AsyncEx: IGameService_AsyncEx; public property ServerUrl: String read get__ServerUrl; property GameService: IGameService read get__GameService; property GameService_Async: IGameService_Async read get__GameService_Async; property GameService_AsyncEx: IGameService_AsyncEx read get__GameService_AsyncEx; published Message: TROBinMessage; Channel: TROIndyHTTPChannel; procedure DataModuleCreate(Sender: TObject); end; function ServerAccess: TServerAccess_GameLibrary; implementation {$IFDEF DELPHIXE2} {%CLASSGROUP 'System.Classes.TPersistent'} {$ENDIF} {$R *.dfm} const SERVER_URL = 'http://localhost:8099/bin'; var fServerAccess: TServerAccess_GameLibrary; function ServerAccess: TServerAccess_GameLibrary; begin if not assigned(fServerAccess) then begin fServerAccess := TServerAccess_GameLibrary.Create(nil); end; result := fServerAccess; exit; end; procedure TServerAccess_GameLibrary.DataModuleCreate(Sender: TObject); begin Self.fServerUrl := SERVER_URL; Self.Channel.TargetUrl := Self.fServerUrl; end; function TServerAccess_GameLibrary.get__ServerUrl: String; begin result := Self.fServerUrl; exit; end; function TServerAccess_GameLibrary.get__GameService: IGameService; begin result := CoGameService.Create(Self.Message, Self.Channel); exit; end; function TServerAccess_GameLibrary.get__GameService_Async: IGameService_Async; begin result := CoGameService_Async.Create(Self.Message, Self.Channel); exit; end; function TServerAccess_GameLibrary.get__GameService_AsyncEx: IGameService_AsyncEx; begin result := CoGameService_AsyncEx.Create(Self.Message, Self.Channel); exit; end; initialization finalization fServerAccess.Free(); end.
unit CryptChat; {$mode objfpc}{$H+} interface uses Classes, SysUtils, MailCrypt, ExtCtrls, StdCtrls, Graphics, Dialogs, Controls, CryptMessage, FileUtil, Forms, Menus, ComCtrls, MainCrypt // My controls {$IFDEF WINDOWS} , Windows {$ENDIF WINDOWS} ; type TFiles = pointer; type TPageContact = record FriendID: integer; FriendName: string; Scroll: TScrollBox; Panel: TPanel; Memo: TMemo; MyFace: TImage; FriendFace: TImage; SendBtn: TButton; AtachBtn: TButton; FileList: TStringList; FileLabel: TLabel; Tab: TTabSheet; fMsg: array of TMessages; end; type TMsgState = set of (INCOMING, OUTCOMING); type { TLeftWidget } TLeftWidget = class(TPageControl) public procedure DoCloseTabClicked(APage: TCustomPage); override; end; type { TCryptChat } { TCustomCryptChat } TCustomCryptChat = class(TMailCrypt) private fLeftWidget: TLeftWidget; fListBox: TListBox; //fMsg: array of TMessages; //* ======================================================================== *// fPages: array of TPageContact; // Добавить сообщение function Add(AFriendID: integer; AText: string; ADate: TDate; Avatar: string; AFiles: TFiles; State: TMsgState): boolean; procedure NewPage(AFriendId: integer); // Обработка событий procedure MemoKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); procedure ContactDblClick(Sender: TObject); procedure SendThisMsg(Sender: TObject); procedure AttachFiles(Sender: TObject); procedure CloseTab(Sender: TObject); procedure fUpdateContactList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //* ======================================================================== *// // Если не указан AFriendID, то работа ведётся с активной вкладкой //* ======================================================================== *// procedure Recv(AFriendID: integer; AText: string; ADate: TDateTime; AFiles: TFiles); overload; procedure Send(AFriendID: integer; AText: string; ADate: TDateTime; AFiles: TFiles); overload; procedure Recv(AText: string; ADate: TDateTime; AFiles: TFiles); overload; procedure Send(AText: string; ADate: TDateTime; AFiles: TFiles); overload; //* ======================================================================== *// // Некоторые вещи придёться вытащить в зону видимости для отладки =( //* ======================================================================== *// procedure GlobalUpdate; virtual; function LoginUser(AEMail, APassword: string): boolean; overload; override; function LoginUser(AUser: TUserEntry): boolean; overload; override; end; implementation { TLeftWidget } procedure TLeftWidget.DoCloseTabClicked(APage: TCustomPage); begin tag:= APage.PageIndex; inherited DoCloseTabClicked(APage); end; { TCryptChat } {$IFDEF WINDOWS} function WinTemp: string; begin SetLength(Result, MAX_PATH); SetLength(Result, GetTempPath(MAX_PATH, PChar(Result))); end; {$ENDIF WINDOWS} function TCustomCryptChat.Add(AFriendID: integer; AText: string; ADate: TDate; Avatar: string; AFiles: TFiles; State: TMsgState): boolean; var i, CurrentIndex, CountMsg: integer; begin Result := False; CurrentIndex := -1; for i := 0 to High(fPages) do if fPages[i].FriendID = AFriendId then begin CurrentIndex := i; end; if CurrentIndex = -1 then Exit; Result := True; // Выделяем память with fPages[CurrentIndex] do begin CountMsg := High(fMsg); if CountMsg = -1 then SetLength(fMsg, 1) else SetLength(fMsg, CountMsg + 2); CountMsg := High(fMsg); // Создаём элемент fmsg[CountMsg] := TMessages.Create(Scroll); fmsg[CountMsg].Parent := Scroll; // ??? fmsg[CountMsg].OnMouseWheel:= Scroll.OnMouseWheel; fmsg[CountMsg].OnMouseWheelDown:= Scroll.OnMouseWheelDown; fmsg[CountMsg].OnMouseWheelUp:= Scroll.OnMouseWheelUp; // Выставляем позицию сообщения if CountMsg > 0 then fmsg[CountMsg].Top := fmsg[CountMsg - 1].Top + fmsg[CountMsg - 1].Height + 10 else fmsg[CountMsg].Top := 0; fmsg[CountMsg].Align := alTop; //fmsg[CountMsg].ReAlign; // Содержимое диалога fMsg[CountMsg].Date := ADate; if State = [INCOMING] then fMsg[CountMsg].User := Friend[AFriendID].NickName else fMsg[CountMsg].User := GetUserInfo.NickName; fMsg[CountMsg].Text := AText; fMsg[CountMsg].LoadImage(Avatar); Scroll.VertScrollBar.Position := Scroll.VertScrollBar.Range; // ? Ошибка ? end; end; procedure TCustomCryptChat.NewPage(AFriendId: integer); var I: integer; begin // Если диалог уже открыт, просто активируем его страницу for i := 0 to High(fPages) do if fPages[i].FriendID = AFriendId then begin fLeftWidget.ActivePage := fPages[i].Tab; Exit; end; // Выделяем память if High(fPages) = -1 then SetLength(fPages, 1) else SetLength(fPages, High(fPages) + 2); // Дополнительные компоненты with fPages[High(fPages)] do begin FriendID := AFriendId; Tab := fLeftWidget.AddTabSheet; fLeftWidget.ActivePage := Tab; Tab.Caption := Friend[AFriendId].NickName + '< ' + Friend[AFriendId].Email + ' >'; Scroll := TScrollBox.Create(Tab); Scroll.Parent := Tab; Scroll.VertScrollBar.Tracking:= True; // Панелька Panel := TPanel.Create(Tab); Panel.Parent := Tab; Panel.Height := 120; Panel.Align := alBottom; // Ввод текста Memo := TMemo.Create(Panel); Memo.Parent := Panel; Memo.OnKeyUp := @MemoKeyUp; // Моя фотка MyFace := TImage.Create(Panel); MyFace.Parent := Panel; {$IFDEF UNIX} MyFace.Picture.LoadFromFile('/tmp/usr.png'); {$ENDIF UNIX} {$IFDEF WINDOWS} MyFace.Picture.LoadFromFile(WinTemp + 'usr.png'); {$ENDIF WINDOWS} // Фотка собеседника FriendFace := TImage.Create(Panel); FriendFace.Parent := Panel; {$IFDEF UNIX} if not GetFriendImage(AFriendID, '/tmp/friend.png') then CopyFile(PChar(ExtractFilePath(ParamStr(0))+'Data/def_fava.png'), PChar('/tmp/friend.png'), TRUE); FriendFace.Picture.LoadFromFile('/tmp/friend.png'); {$ENDIF UNIX} {$IFDEF WINDOWS} raise Exception.Create('Не написан код для загрузки авы товарища'); { TODO : Под виндой не загрузиться ава друга } {$ENDIF WINDOWS} // Расположение Scroll.Align := alClient; Scroll.AutoScroll := True; MyFace.Top := 4; FriendFace.Top := 4; MyFace.Left := 4; // Положение фотки собеседника FriendFace.Left := Panel.Width - 70; FriendFace.Width := 64; FriendFace.Proportional := True; FriendFace.Anchors := [akRight, akTop]; FriendFace.Stretch := True; // Моего лица MyFace.Width := 64; MyFace.Stretch := True; MyFace.Proportional := True; // Положение окна ввода текста Memo.Left := 74; Memo.Top := 4; Memo.Height := Panel.Height - 38; Memo.Width := Panel.Width - 152; Memo.Anchors := [akTop, akRight, akBottom, akLeft]; // Кнопочки SendBtn := TButton.Create(Panel); with SendBtn do begin Parent := Panel; Top := Panel.Height - 32; Left := 74; Width := 94; Height := 26; Caption := 'Отправить'; OnClick := @SendThisMsg; end; AtachBtn := TButton.Create(Panel); with AtachBtn do begin Parent := Panel; Top := Panel.Height - 32; Left := 174; Width := 94; Height := 26; Caption := 'Прикрепить'; OnClick := @AttachFiles; end; // Список файлов FileList := TStringList.Create; FileLabel := TLabel.Create(Panel); with FileLabel do begin Parent := Panel; Caption := 'Прикреплённые файлы (0)'; Top := Panel.Height - 28; Left := Memo.Width + 74 - FileLabel.Width; Height := 26; font.Color := clNavy; Anchors := [akRight, akTop]; end; end; end; procedure TCustomCryptChat.MemoKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); const VK_RETURN = 13; begin if (ssCtrl in Shift) and (Key = VK_RETURN) then SendThisMsg(Sender); end; procedure TCustomCryptChat.ContactDblClick(Sender: TObject); var i: integer; begin for i := 0 to GetCountFriend - 1 do with Friend[i] do begin if fListBox.Items[fListBox.ItemIndex] = (NickName + '< ' + Email + ' >') then NewPage(i); end; end; procedure TCustomCryptChat.Recv(AFriendID: integer; AText: string; ADate: TDateTime; AFiles: TFiles); var Path: string; defAva: string; begin {$IFDEF UNIX} Path:= '/tmp/friend.png'; defAva:= 'Data/def_fava.png'; {$ENDIF UNIX} {$IFDEF WINDOWS} Path:= WinTemp + 'friend.png'; defAva:= 'Data\def_fava.png'; {$ENDIF WINDOWS} if not GetFriendImage(AFriendID, Path) then CopyFile(PChar(ExtractFilePath(ParamStr(0)) + defAva), PChar(Path), True); if not Add(AFriendID, AText, ADate, Path, AFiles, [INCOMING]) then raise Exception.Create('Ошибка получения сообщения'); end; procedure TCustomCryptChat.Send(AFriendID: integer; AText: string; ADate: TDateTime; AFiles: TFiles); var i: integer; Path: string; begin if (AText = '') and (AFiles = nil) then exit; {$IFDEF UNIX} Path:= '/tmp/usr.png'; {$ENDIF UNIX} {$IFDEF WINDOWS} Path:= WinTemp + 'usr.png'; {$ENDIF WINDOWS} if Add(AFriendID, AText, ADate, Path, AFiles, [OUTCOMING]) then begin for i := 0 to High(fPages) do if fPages[i].FriendID = AFriendID then begin fPages[i].Memo.Clear; Break; end; end else raise Exception.Create('Ошибка отправки сообщения'); end; procedure TCustomCryptChat.SendThisMsg(Sender: TObject); var i: integer; begin for i := 0 to High(fPages) do if fPages[I].Tab = fLeftWidget.ActivePage then Send(fPages[i].Memo.Text, now, nil); end; procedure TCustomCryptChat.Send(AText: string; ADate: TDateTime; AFiles: TFiles); var i: integer; begin for i := 0 to GetCountFriend - 1 do with Friend[i] do begin // i = index of friend != fpages index if fLeftWidget.ActivePage.Caption = NickName + '< ' + Email + ' >' then Send(i, AText, ADate, AFiles); end; end; procedure TCustomCryptChat.Recv(AText: string; ADate: TDateTime; AFiles: TFiles); var i: integer; begin for i := 0 to GetCountFriend - 1 do with Friend[i] do begin if fLeftWidget.ActivePage.Caption = NickName + '< ' + Email + ' >' then Recv(i, AText, ADate, AFiles); end; end; procedure TCustomCryptChat.AttachFiles(Sender: TObject); begin // ??? { TODO : Не сделано добавление файлов к сообщениям } end; procedure TCustomCryptChat.CloseTab(Sender: TObject); var ClosedIndex, i: integer; begin ClosedIndex:= fLeftWidget.Tag; fLeftWidget.ActivePageIndex:= ClosedIndex; //ClosedIndex := fLeftWidget.TabIndexAtClientPos(ScreenToClient(Mouse.CursorPos)); if (ClosedIndex = -1) or (ClosedIndex = -2) then exit; // destroy messages for i := 0 to High(fPages[ClosedIndex].fMsg) do fPages[ClosedIndex].fMsg[i].Free; // Free Page with fPages[ClosedIndex] do begin try if Assigned(AtachBtn) then FreeAndNil(AtachBtn); if Assigned(FileLabel) then FreeAndNil(FileLabel); if Assigned(FileList) then FreeAndNil(FileList); if Assigned(FriendFace) then FreeAndNil(FriendFace); if Assigned(Memo) then FreeAndNil(Memo); if Assigned(MyFace) then FreeAndNil(MyFace); if Assigned(Panel) then FreeAndNil(Panel); if Assigned(Scroll) then FreeAndNil(Scroll); if Assigned(SendBtn) then begin SendBtn.OnClick:= nil; try { TODO : Проблемы с уничтожением SendBtn } //FreeAndNil(SendBtn); /// ???? SendBtn:= nil; // AV при free ??? except end; end; finally //fLeftWidget.ActivePage.Free; if Assigned(Tab) then FreeAndNil(Tab); end; end; // correct array for i := ClosedIndex to High(fPages) - 1 do fPages[i] := fPages[i + 1]; SetLength(fPages, High(fPages)); end; procedure TCustomCryptChat.fUpdateContactList; var i: integer; begin or i := 0 to GetCountFriend - 1 do with Friend[i] do begin fListBox.Items.Add(NickName + '< ' + Email + ' >'); // Нужно установить для каждого элемента теги end; end; constructor TCustomCryptChat.Create(AOwner: TComponent); begin inherited Create(AOwner); Height := 400; Width := 400; // Всё что слева fLeftWidget := TLeftWidget.Create(self); fLeftWidget.Options := [nboShowCloseButtons]; fLeftWidget.OnCloseTabClicked := @CloseTab; fLeftWidget.Parent := self; fLeftWidget.Height := 100; fLeftWidget.Align := alClient; fLeftWidget.TabPosition := tpBottom; //fLeftWidget.AddTabSheet.Caption := 'Test'; // Всё что справа fListBox := TListBox.Create(Self); with fListBox do begin Height := 30; Left := 100; Top := 100; Width := 200; Align := alRight; Parent := Self; OnDblClick := @ContactDblClick; end; Align := alClient; end; destructor TCustomCryptChat.Destroy; var i, j: integer; begin for i := 0 to High(fPages) do for j := 0 to High(fPages[i].fMsg) do fPages[i].fMsg[j].Free; inherited Destroy; end; procedure TCustomCryptChat.GlobalUpdate; begin fListBox.Clear; fUpdateContactList; { TODO : Проверить есть ли входящие } { TODO : Провести чтение входящих } { TODO : Отобразить изменения } end; function TCustomCryptChat.LoginUser(AEMail, APassword: string): boolean; var Path: string; slash: char; begin Result := inherited LoginUser(AEMail, APassword); if Result then begin {$IFDEF UNIX} Path:= '/tmp/usr.png'; slash:= '/'; {$ENDIF UNIX} {$IFDEF WINDOWS} Path:= WinTemp + 'usr.png'; slash:= '\'; {$endif WINDOWS} if not GetUserImage(GetUserInfo.ID_USER, Path) then CopyFile(PChar(ExtractFilePath(ParamStr(0)) + 'Data' + slash + 'def_ava.png'), PChar(Path), True); end; end; function TCustomCryptChat.LoginUser(AUser: TUserEntry): boolean; var Path: string; slash: char; begin Result := inherited LoginUser(AUser); if Result then begin {$IFDEF UNIX} Path:= '/tmp/usr.png'; slash:= '/'; {$ENDIF UNIX} {$IFDEF WINDOWS} Path:= WinTemp + 'usr.png'; slash:= '\'; {$endif WINDOWS} if not GetUserImage(GetUserInfo.ID_USER, Path) then CopyFile(PChar(ExtractFilePath(ParamStr(0)) + 'Data' + slash + 'def_ava.png'), PChar(Path), True); end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLProjectedTextures<p> Implements projected textures through a GLScene object. <b>History : </b><font size=-1><ul> <li>10/11/12 - PW - Added CPP compatibility: changed const cBase matrix <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>22/04/10 - Yar - Fixes after GLState revision <li>05/03/10 - DanB - More state added to TGLStateCache <li>30/03/07 - DaStr - Added $I GLScene.inc <li>28/03/07 - DaStr - Renamed parameters in some methods (thanks Burkhard Carstens) (Bugtracker ID = 1678658) <li>15/06/05 - Mathx - Added the Style property and inverse rendering <li>07/05/05 - Mathx - Support for tmBlend textures (by Ruben Javier) <li>01/10/04 - SG - Initial (by Matheus Degiovani) </ul></font> } unit GLProjectedTextures; interface {$I GLScene.inc} uses Classes, GLScene, GLTexture, OpenGLTokens, GLVectorGeometry, XOpenGL, GLRenderContextInfo, GLState; type {: Possible styles of texture projection. Possible values:<ul> <li>ptsOriginal: Original projection method (first pass, is default scene render, second pass is texture projection). <li>ptsInverse: Inverse projection method (first pass is texture projection, sencond pass is regular scene render). This method is useful if you want to simulate lighting only through projected textures (the textures of the scene are "masked" into the white areas of the projection textures). </ul> } TGLProjectedTexturesStyle = (ptsOriginal, ptsInverse); TGLProjectedTextures = class; // TGLTextureEmmiter // {: A projected texture emmiter.<p> It's material property will be used as the projected texture. Can be places anywhere in the scene. } TGLTextureEmitter = class(TGLSceneObject) private { Private Declarations } FFOVy: single; FAspect: single; protected { Protected Declarations } {: Sets up the base texture matrix for this emitter<p> Should be called whenever a change on its properties is made.} procedure SetupTexMatrix(var ARci: TRenderContextInfo); public { Public Declarations } constructor Create(AOwner: TComponent); override; published { Published Declarations } {: Indicates the field-of-view of the projection frustum.} property FOVy: single read FFOVy write FFOVy; {: x/y ratio. For no distortion, this should be set to texture.width/texture.height.} property Aspect: single read FAspect write FAspect; end; // TGLTextureEmitterItem // {: Specifies an item on the TGLTextureEmitters collection. } TGLTextureEmitterItem = class(TCollectionItem) private { Private Declarations } FEmitter: TGLTextureEmitter; protected { Protected Declarations } procedure SetEmitter(const val: TGLTextureEmitter); procedure RemoveNotification(aComponent: TComponent); function GetDisplayName: string; override; public { Public Declarations } constructor Create(ACollection: TCollection); override; procedure Assign(Source: TPersistent); override; published { Published Declarations } property Emitter: TGLTextureEmitter read FEmitter write SetEmitter; end; // TGLTextureEmitters // {: Collection of TGLTextureEmitter. } TGLTextureEmitters = class(TCollection) private { Private Declarations } FOwner: TGLProjectedTextures; protected { Protected Declarations } function GetOwner: TPersistent; override; function GetItems(index: Integer): TGLTextureEmitterItem; procedure RemoveNotification(aComponent: TComponent); public { Public Declarations } procedure AddEmitter(texEmitter: TGLTextureEmitter); property Items[index: Integer]: TGLTextureEmitterItem read GetItems; default; end; // TGLProjectedTexture // {: Projected Textures Manager.<p> Specifies active texture Emitters (whose texture will be projected) and receivers (children of this object). } TGLProjectedTextures = class(TGLImmaterialSceneObject) private { Private Declarations } FEmitters: TGLTextureEmitters; FStyle: TGLProjectedTexturesStyle; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoRender(var ARci: TRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; published { Published Declarations } {: List of texture emitters. } property Emitters: TGLTextureEmitters read FEmitters write FEmitters; {: Indicates the style of the projected textures. } property Style: TGLProjectedTexturesStyle read FStyle write FStyle; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- uses GLContext; // ------------------ // ------------------ TGLTextureEmitter ------------------ // ------------------ // Create // constructor TGLTextureEmitter.Create(aOwner: TComponent); begin inherited Create(aOwner); FFOVy := 90; FAspect := 1; end; // SetupTexMatrix // procedure TGLTextureEmitter.SetupTexMatrix(var ARci: TRenderContextInfo); const cBaseMat: TMatrix = (V:((X:0.5; Y:0; Z:0; W:0), (X:0; Y:0.5; Z:0; W:0), (X:0; Y:0; Z:1; W:0), (X:0.5; Y:0.5; Z:0; W:1))); var PM: TMatrix; begin // Set the projector's "perspective" (i.e. the "spotlight cone"):. PM := MatrixMultiply(CreatePerspectiveMatrix(FFOVy, FAspect, 0.1, 1), cBaseMat); PM := MatrixMultiply(invAbsoluteMatrix, PM); Arci.GLStates.SetGLTextureMatrix(PM); end; // ------------------ // ------------------ TGLTextureEmitterItem ------------------ // ------------------ // Create // constructor TGLTextureEmitterItem.Create(ACollection: TCollection); begin inherited Create(ACollection); end; // Assign // procedure TGLTextureEmitterItem.Assign(Source: TPersistent); begin if Source is TGLTextureEmitterItem then begin FEmitter := TGLTextureEmitterItem(Source).FEmitter; TGLProjectedTextures(TGLTextureEmitters(Collection).GetOwner).StructureChanged; end; inherited; end; // SetCaster // procedure TGLTextureEmitterItem.SetEmitter(const val: TGLTextureEmitter); begin if FEmitter <> val then begin FEmitter := val; TGLProjectedTextures(TGLTextureEmitters(Collection).GetOwner).StructureChanged; end; end; // RemoveNotification // procedure TGLTextureEmitterItem.RemoveNotification(aComponent: TComponent); begin if aComponent = FEmitter then FEmitter := nil; end; // GetDisplayName // function TGLTextureEmitterItem.GetDisplayName: string; begin if Assigned(FEmitter) then begin Result := '[TexEmitter] ' + FEmitter.Name; end else Result := 'nil'; end; // ------------------ // ------------------ TGLTextureEmitters ------------------ // ------------------ // GetOwner // function TGLTextureEmitters.GetOwner: TPersistent; begin Result := FOwner; end; // GetItems // function TGLTextureEmitters.GetItems(index: Integer): TGLTextureEmitterItem; begin Result := TGLTextureEmitterItem(inherited Items[index]); end; // RemoveNotification // procedure TGLTextureEmitters.RemoveNotification(aComponent: TComponent); var i: Integer; begin for i := 0 to Count - 1 do Items[i].RemoveNotification(aComponent); end; // AddEmitter // procedure TGLTextureEmitters.AddEmitter(texEmitter: TGLTextureEmitter); var item: TGLTextureEmitterItem; begin item := TGLTextureEmitterItem(self.Add); item.Emitter := texEmitter; end; // ------------------ // ------------------ TGLProjectedTextures ------------------ // ------------------ // Create // constructor TGLProjectedTextures.Create(AOwner: TComponent); begin inherited Create(aOWner); FEmitters := TGLTextureEmitters.Create(TGLTextureEmitterItem); FEmitters.FOwner := self; end; // Destroy // destructor TGLProjectedTextures.Destroy; begin FEmitters.Free; inherited destroy; end; // DoRender // procedure TGLProjectedTextures.DoRender(var ARci: TRenderContextInfo; ARenderSelf, ARenderChildren: boolean); const PS: array[0..3] of GLfloat = (1, 0, 0, 0); PT: array[0..3] of GLfloat = (0, 1, 0, 0); PR: array[0..3] of GLfloat = (0, 0, 1, 0); PQ: array[0..3] of GLfloat = (0, 0, 0, 1); var i: integer; emitter: TGLTextureEmitter; begin if not (ARenderSelf or ARenderChildren) then Exit; if (csDesigning in ComponentState) then begin inherited; Exit; end; //First pass of original style: render regular scene if Style = ptsOriginal then self.RenderChildren(0, Count - 1, ARci); //generate planes GL.TexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); GL.TexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); GL.TexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); GL.TexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); GL.TexGenfv(GL_S, GL_EYE_PLANE, @PS); GL.TexGenfv(GL_T, GL_EYE_PLANE, @PT); GL.TexGenfv(GL_R, GL_EYE_PLANE, @PR); GL.TexGenfv(GL_Q, GL_EYE_PLANE, @PQ); //options Arci.GLStates.Disable(stLighting); Arci.GLStates.DepthFunc := cfLEqual; Arci.GLStates.Enable(stBlend); GL.Enable(GL_TEXTURE_GEN_S); GL.Enable(GL_TEXTURE_GEN_T); GL.Enable(GL_TEXTURE_GEN_R); GL.Enable(GL_TEXTURE_GEN_Q); //second pass (original) first pass (inverse): for each emiter, //render projecting the texture summing all emitters for i := 0 to Emitters.Count - 1 do begin emitter := Emitters[i].Emitter; if not assigned(emitter) then continue; if not emitter.Visible then continue; emitter.Material.Apply(ARci); ARci.GLStates.Enable(stBlend); if Style = ptsOriginal then begin //on the original style, render blending the textures if emitter.Material.Texture.TextureMode <> tmBlend then ARci.GLStates.SetBlendFunc(bfDstColor, bfOne) else ARci.GLStates.SetBlendFunc(bfDstColor, bfZero); end else begin //on inverse style: the first texture projector should //be a regular rendering (i.e. no blending). All others //are "added" together creating an "illumination mask" if i = 0 then Arci.GLStates.SetBlendFunc(bfOne, bfZero) else ARci.GLStates.SetBlendFunc(bfOne, bfOne); end; //get this emitter's tex matrix emitter.SetupTexMatrix(ARci); repeat ARci.ignoreMaterials := true; Self.RenderChildren(0, Count - 1, ARci); ARci.ignoreMaterials := false; until not emitter.Material.UnApply(ARci); end; // LoseTexMatrix ARci.GLStates.SetBlendFunc(bfOne, bfZero); GL.Disable(GL_TEXTURE_GEN_S); GL.Disable(GL_TEXTURE_GEN_T); GL.Disable(GL_TEXTURE_GEN_R); GL.Disable(GL_TEXTURE_GEN_Q); GL.MatrixMode(GL_TEXTURE); GL.LoadIdentity; GL.MatrixMode(GL_MODELVIEW); ARci.GLStates.DepthFunc := cfLEqual; //second pass (inverse): render regular scene, blending it //with the "mask" if Style = ptsInverse then begin Arci.GLStates.Enable(stBlend); ARci.GLStates.SetBlendFunc(bfDstColor, bfSrcColor); //second pass: render everything, blending with what is //already there ARci.ignoreBlendingRequests := true; self.RenderChildren(0, Count - 1, ARci); ARci.ignoreBlendingRequests := false; end; end; initialization RegisterClasses([TGLTextureEmitter, TGLProjectedTextures]); end.
unit uXML; { ================================================================================ * * Application: CliO * Revision: $Revision: 1 $ $Modtime: 12/20/07 12:44p $ * Developer: doma.user@domain.ext * Site: Hines OIFO * * Description: Contains global XML text utilities. * * * Notes: * * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSUTILS/uXML.pas $ * * $History: uXML.pas $ * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 8/12/09 Time: 8:29a * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 3/09/09 Time: 3:39p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/13/09 Time: 1:26p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/14/07 Time: 10:30a * Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:44p * Created in $/Vitals/VITALS-5-0-18/VitalsUtils * GUI v. 5.0.18 updates the default vital type IENs with the local * values. * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:33p * Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsUtils * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/24/05 Time: 5:04p * Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsUtils * * ***************** Version 4 ***************** * User: Zzzzzzpetitd Date: 10/27/04 Time: 9:05a * Updated in $/CP Modernization/CliO/Source Code * Completed initial work for the renal controller. * * ***************** Version 3 ***************** * User: Zzzzzzpetitd Date: 10/13/04 Time: 2:33p * Updated in $/CP Modernization/CliO/Source Code * Finished base Insert Update and Query functions. * * ***************** Version 2 ***************** * User: Zzzzzzpetitd Date: 10/07/04 Time: 4:49p * Updated in $/CP Modernization/CliO/Source Code * Finished preliminary work on Insert and have it functioning with both * ADO and the VistABroker connections * * ***************** Version 1 ***************** * User: Zzzzzzpetitd Date: 10/02/04 Time: 9:46a * Created in $/CP Modernization/CliO/Source Code * Initial check in * * * * ================================================================================ } interface uses SysUtils, Classes, XMLIntf, XMLDoc; function XMLHeader(const AName: string): string; overload; function XMLHeader(const AName: string; AIdentifierNames, AIdentifierValues: array of string): string; overload; function XMLFooter(const AName: string): string; function XMLElement(const ATag: string; const AValue: string): string; overload; function XMLElement(const ATag: string; const AValue: Integer): string; overload; function XMLElement(const ATag: string; const AValue: Double; const ADecimals: integer): string; overload; function XMLElement(const ATag: string; const AValue: Boolean): string; overload; function XMLElement(const ATag: string; const AValue: TDateTime): string; overload; function XMLStream(const AXML: string): TStringStream; function XMLDocument(const AXML: string): IXMLDocument; function XMLDateTime(const ADateTime: TDateTime): string; function XMLNodeValue(const AXMLDoc: IXMLDocument; const ATag: string): string; function XMLFieldValue(AXMLCurrentRecordNode: IXMLNode; AFieldName: string): string; function XMLFirstRecord(AXMLResultsDocument: IXMLDocument): IXMLNode; function XMLNextRecord(AXMLCurrentRecordNode: IXMLNode): IXMLNode; function XMLErrorMessage(const aErrorMsgText: string): string; function XMLSuccessMessage(const aMsgText: string): string; function XMLString(aString: string): string; function GetXMLStatusValue(aXMLString: string): string; function GetXMLNodeValue(aXMLString, aXMLNodeName: string): string; const XML_DATE = 'YYYY-MM-DD'; XML_DATETIME = 'YYYY-MM-DD hh:mm:ss'; XML_VERSION = '<?xml version="1.0"?>'; XML_STATUS_OK = '<RESULT><STATUS>OK</STATUS></RESULT>'; XML_STATUS_ERROR = '<RESULT><STATUS>ERROR</STATUS><DB_ENGINE_ERROR_MESSAGE>%s</DB_ENGINE_ERROR_MESSAGE></RESULT>'; implementation uses StrUtils; function BuildElement(const ATag: string; const AValue: string): string; {Used internally once the element value is formatted to a string} begin Result := Format('<%s>%s</%s>', [ATag, AValue, ATag]) + #13; end; function XMLHeader(const AName: string): string; overload; begin Result := XMLHeader(AName, [], []); end; function XMLHeader(const AName: string; AIdentifierNames, AIdentifierValues: array of string): string; var i: integer; begin Result := AName; if High(AIdentifierNames) > -1 then begin Result := Format('%s', [Result]); i := 0; while i <= High(AIdentifierNames) do begin Result := Format('%s %s=%s', [Result, AIdentifierNames[i], AnsiQuotedStr(AIdentifierValues[i], '''')]); inc(i); end; end; Result := Format('<%s>', [Result]) + #13; end; function XMLFooter(const AName: string): string; begin Result := Format('</%s>', [AName]) + #13; end; function XMLElement(const ATag: string; const AValue: string): string; overload; begin Result := BuildElement(ATag, AValue); end; function XMLElement(const ATag: string; const AValue: Integer): string; overload; begin Result := BuildElement(ATag, Format('%d', [AValue])); end; function XMLElement(const ATag: string; const AValue: Double; const ADecimals: integer): string; overload; begin Result := BuildElement(ATag, Format(Format('%%0.%df', [ADecimals]), [AValue])); end; function XMLElement(const ATag: string; const AValue: Boolean): string; overload; begin Result := BuildElement(ATag, BoolToStr(AValue, True)); end; function XMLElement(const ATag: string; const AValue: TDateTime): string; overload; begin Result := BuildElement(ATag, FormatDateTime(XML_DATETIME, AValue)); end; function XMLDateTime(const ADateTime: TDateTime): string; begin Result := FormatDateTime(XML_DATETIME, ADateTime); end; function XMLStream(const AXML: string): TStringStream; begin Result := TStringStream.Create(AXML); end; function XMLDocument(const AXML: string): IXMLDocument; begin Result := NewXMLDocument; Result.LoadFromStream(XMLStream(AXML)); Result.Active := True; end; function XMLNodeValue(const AXMLDoc: IXMLDocument; const ATag: string): string; var XMLNode: IXMLNode; begin Result := ''; XMLNode := AXMLDoc.DocumentElement.ChildNodes.FindNode(ATag); if XMLNode <> nil then if XMLNode.IsTextElement then Result := XMLNode.NodeValue; end; function XMLFieldValue(AXMLCurrentRecordNode: IXMLNode; AFieldName: string): string; begin Result := ''; if AXMLCurrentRecordNode.ChildNodes.FindNode(AFieldName) <> nil then if AXMLCurrentRecordNode.ChildNodes.FindNode(AFieldName).IsTextElement then Result := AXMLCurrentRecordNode.ChildNodes.FindNode(AFieldName).NodeValue; end; function XMLFirstRecord(AXMLResultsDocument: IXMLDocument): IXMLNode; begin Result := AXMLResultsDocument.DocumentElement.ChildNodes.FindNode('RECORD'); end; function XMLNextRecord(AXMLCurrentRecordNode: IXMLNode): IXMLNode; begin Result := AXMLCurrentRecordNode.NextSibling; end; function XMLErrorMessage(const aErrorMsgText: string): string; begin Result := XMLHeader('RESULTS') + XMLElement('STATUS', 'ERROR') + XMLElement('MESSAGE', aErrorMsgText) + XMLFooter('RESULTS'); end; function XMLSuccessMessage(const aMsgText: string): string; begin Result := XMLHeader('RESULTS') + XMLElement('STATUS', 'OK') + XMLElement('MESSAGE', aMsgText) + XMLFooter('RESULTS'); end; function XMLString(aString: string): string; begin Result := aString; Result := AnsiReplaceStr(Result, '&', '&amp;'); Result := AnsiReplaceStr(Result, '<', '&lt;'); Result := AnsiReplaceStr(Result, '>', '&gt;'); Result := AnsiReplaceStr(Result, '''', '&apos;'); Result := AnsiReplaceStr(Result, '"', '&quot;'); end; function GetXMLStatusValue(aXMLString: string): string; begin Result := GetXMLNodeValue(aXMLString, 'STATUS'); end; function GetXMLNodeValue(aXMLString, aXMLNodeName: string): string; begin try with LoadXMLData(aXMLString).DocumentElement do Result := ChildValues[aXMLNodeName]; except on E: Exception do Result := ''; end; end; end.
unit ncDebCredSaver; interface type TncDebCredSaverData = class public Cliente: Integer; Cancelado: Boolean; Debito: Currency; DebitoPago: Currency; Credito: Currency; CreditoUsado: Currency; constructor Create; function Igual(B: TncDebCredSaverData): Boolean; function MovDebito: Currency; function MovCredito: Currency; end; TncDebCredSaver = class public Old : TncDebCredSaverData; New : TncDebCredSaverData; constructor Create; destructor Destroy; override; function Alterou: Boolean; function AlterouCli: Boolean; function AlterouOld: Boolean; function AlterouNew: Boolean; function DifDebito_Old: Currency; function DifDebito_New: Currency; function DifCredito_Old: Currency; function DifCredito_New: Currency; end; { TncDebCredSaverData } implementation constructor TncDebCredSaverData.Create; begin Cliente := 0; Cancelado := False; Debito := 0; DebitoPago := 0; Credito := 0; CreditoUsado := 0; end; function TncDebCredSaverData.Igual(B: TncDebCredSaverData): Boolean; begin Result := (Cliente<>B.Cliente) or (Cancelado<>B.Cancelado) or (Debito<>B.Debito) or (Credito<>B.Credito) or (CreditoUsado<>B.CreditoUsado); end; function TncDebCredSaverData.MovCredito: Currency; begin if (Cliente=0) or Cancelado then Result := 0 else Result := Credito - CreditoUsado; end; function TncDebCredSaverData.MovDebito: Currency; begin if (Cliente=0) or Cancelado then Result := 0 else Result := Debito - DebitoPago; end; { TncDebCredSaver } function TncDebCredSaver.Alterou: Boolean; begin Result := (not Old.Cancelado) and (not Old.Igual(New)); end; function TncDebCredSaver.AlterouCli: Boolean; begin Result := (Old.Cliente <> New.Cliente); end; function TncDebCredSaver.AlterouNew: Boolean; begin Result := (Abs(DifDebito_New)>0) or (Abs(DifCredito_New)>0); end; function TncDebCredSaver.AlterouOld: Boolean; begin Result := (Abs(DifDebito_Old)>0) or (Abs(DifCredito_Old)>0); end; constructor TncDebCredSaver.Create; begin Old := TncDebCredSaverData.Create; New := TncDebCredSaverData.Create; end; destructor TncDebCredSaver.Destroy; begin Old.Free; New.Free; inherited; end; function TncDebCredSaver.DifCredito_New: Currency; begin if AlterouCli then Result := New.MovCredito else Result := New.MovCredito - Old.MovCredito; end; function TncDebCredSaver.DifCredito_Old: Currency; begin if AlterouCli then Result := Old.MovCredito * -1 else Result := 0; end; function TncDebCredSaver.DifDebito_New: Currency; begin if AlterouCli then Result := New.MovDebito else Result := New.MovDebito - Old.MovDebito; end; function TncDebCredSaver.DifDebito_Old: Currency; begin if AlterouCli then Result := Old.MovDebito * -1 else Result := 0; end; end.
unit vr_timer; {$mode delphi}{$H+} interface //ToD0 ? use TFPTimer(fptimer.pp) -> default NOT WINDOW //{$IFNDEF WINDOWS}{$DEFINE LCL_TIMER}{$ENDIF} uses {$IFDEF WINDOWS}Windows,{$ENDIF}Classes, SysUtils, vr_fpclasses, vr_SysUtils {$IFDEF LCL_TIMER}, CustomTimer{$ENDIF}; type {$IFDEF LCL_TIMER} TCustomTimer = CustomTimer.TCustomTimer; {$ELSE} TTimerHandle = {$IFDEF WINDOWS}UINT_PTR{$ELSE}THandle{$ENDIF}; { TCustomTimer } TCustomTimer = class(TComponent) private FInterval : Cardinal; //FOnStartTimer: TNotifyEvent; //FOnStopTimer: TNotifyEvent; FHandle : TTimerHandle; FOnTimer : TNotifyEvent; FEnabled : Boolean; class var FList: TThreadList; procedure Timer; class procedure DoOnTimer(const AHandle: TTimerHandle); protected procedure SetEnabled(AValue: Boolean); //virtual; procedure SetInterval(AValue: Cardinal); //virtual; procedure SetOnTimer(AValue: TNotifyEvent); //virtual; public //constructor Create(AOwner: TComponent); override; constructor CreateAlt(AOwner: TComponent; const AOnTimer: TNotifyEvent; const AEnabled: Boolean = True; const AInterval: Integer = 1000); destructor Destroy; override; property Enabled: Boolean read FEnabled write SetEnabled default True; property Interval: Cardinal read FInterval write SetInterval default 1000; property OnTimer: TNotifyEvent read FOnTimer write SetOnTimer; //property OnStartTimer: TNotifyEvent read FOnStartTimer write FOnStartTimer; //property OnStopTimer: TNotifyEvent read FOnStopTimer write FOnStopTimer; end; {$ENDIF} implementation {$IFNDEF LCL_TIMER} {$IFDEF WINDOWS} procedure _WinTimerProc({%H-}AWnd: HWnd; {%H-}AMsg: UINT; AIdEvent: UINT_PTR; {%H-}AInterval: DWord); stdcall; begin //if AMsg <> WM_TIMER then Exit; TCustomTimer.DoOnTimer(AIdEvent); end; {$ENDIF} { TCustomTimer } procedure TCustomTimer.Timer; begin end; procedure TCustomTimer.SetEnabled(AValue: Boolean); begin if FEnabled = AValue then Exit; FEnabled := AValue; {$IFDEF WINDOWS} if AValue then begin FHandle := SetTimer(0, UINT_PTR(Self), FInterval, _WinTimerProc); TThreadList.LockedCreateIfNil(FList, Self); end else begin TThreadList.LockedFreeAndNilIfEmpty(FList, Self); if FHandle <> 0 then begin KillTimer(0, UINT_PTR(FHandle)); //if hWnd<>0 in SetTimer() then KillTimer(0, UINT_PTR(Self)); FHandle := 0; end; end; {$ELSE} raise Exception.Create('<vr_timer.pas>TCustomTimer.SetEnabled(): define global LCL_TIMER (not implemented)'); {$ENDIF} end; procedure TCustomTimer.SetInterval(AValue: Cardinal); begin if FInterval = AValue then Exit; FInterval := AValue; if Enabled then begin Enabled := False; if AValue > 0 then Enabled := True; end; end; procedure TCustomTimer.SetOnTimer(AValue: TNotifyEvent); begin if (TMethod(AValue).Data = TMethod(FOnTimer).Data) and (TMethod(AValue).Code = TMethod(FOnTimer).Code) then Exit; FOnTimer := AValue; if Enabled then begin Enabled := False; if Assigned(AValue) then Enabled := True; end; end; class procedure TCustomTimer.DoOnTimer(const AHandle: TTimerHandle); var lst: TList; i: Integer; t: TCustomTimer; begin if TThreadList.LockedGet(FList, lst) then try for i := 0 to lst.Count - 1 do begin t := TCustomTimer(lst[i]); if t.FHandle = AHandle then begin if Assigned(t.FOnTimer) then t.FOnTimer(t); Exit; end; end; finally FList.UnlockList; end; end; constructor TCustomTimer.CreateAlt(AOwner: TComponent; const AOnTimer: TNotifyEvent; const AEnabled: Boolean; const AInterval: Integer); begin Create(AOwner); FOnTimer := AOnTimer; FInterval := AInterval; Enabled := AEnabled; end; destructor TCustomTimer.Destroy; begin Enabled := False; TThreadList.LockedFreeAndNilIfEmpty(FList, Self); inherited Destroy; end; {$ENDIF NOT LCL_TIMER} end.
unit Teste.Build.Adapter; interface uses DUnitX.TestFramework, System.JSON, Vigilante.Infra.Build.JSONDataAdapter; type [TestFixture] TBuildJSONDataAdapterTest = class private FJson: TJsonObject; FBuildAdapter: IBuildJSONDataAdapter; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure CarregouNome; [Test] procedure CarregouBuilding; end; implementation uses System.Classes, System.IOUtils, System.SysUtils, Vigilante.Infra.Build.JSONDataAdapter.Impl, Teste.Build.JSONData; procedure TBuildJSONDataAdapterTest.CarregouBuilding; begin Assert.IsFalse(FBuildAdapter.Building); end; procedure TBuildJSONDataAdapterTest.CarregouNome; begin Assert.AreEqual('NOME-DA-VERSAO-COMPILACAO', FBuildAdapter.Nome); end; procedure TBuildJSONDataAdapterTest.Setup; begin FJson := TJSONBuildMock.CarregarJSONDoArquivo<TJsonObject>(ARQUIVO_BUILDPARADO_ULTIMOOK); FBuildAdapter := TBuildJSONDataAdapter.Create(FJson); end; procedure TBuildJSONDataAdapterTest.TearDown; begin FJson.Free; end; initialization TDUnitX.RegisterTestFixture(TBuildJSONDataAdapterTest); end.
unit CH341PTDLL; interface // 2005.07.28 //**************************************** //** Copyright (C) W.ch 1999-2005 ** //** Web: http://www.winchiphead.com ** //**************************************** //** DLL for USB interface chip CH341 ** //** C, VC5.0 ** //**************************************** // // USB总线接口芯片CH341端口应用层接口库 V1.0 // 南京沁恒电子有限公司 作者: W.ch 2005.07 // CH341-Port-DLL V1.0 // 运行环境: Windows 98/ME, Windows 2000/XP // support USB chip: CH341, CH341A // USB => Serial, Parallel // const MAX_DEVICE_PATH_SIZE = 128 ; // 设备名称的最大字符数 MAX_DEVICE_ID_SIZE= 64 ; // 设备ID的最大字符数 Function CH341PtGetVersion( ):cardinal;stdcall; external 'CH341PT.DLL'; // 获得DLL版本号,返回版本号 Function CH341PtHandleIsCH341( // 检查已经打开的端口是否为CH341端口 iPortHandle:cardinal ):boolean;stdcall; external 'CH341PT.DLL'; // 指定已经打开的端口句柄 Function CH341PtNameIsCH341( // 检查指定名称的端口是否为CH341端口 iPortName:PCHAR ):boolean;stdcall; external 'CH341PT.DLL'; // 指定端口名称,例如"COM3","COM15"等,该端口必须未被占用(指未被其它程序打开) type mPCH341PT_NOTIFY_ROUTINE=Procedure ( // 端口设备事件通知回调程序 iDevIndexAndEvent:integer );stdcall; // 端口设备序号和事件及当前状态(参考下行说明) // iDevIndexAndEvent: 正数说明是设备插入事件/已经插入, 负数说明是设备拔出事件/已经拔出, 其绝对值是设备序号(1到255) Function CH341PtSetDevNotify( // 设定端口设备事件通知程序 iDeviceID:PCHAR; // 可选参数,指向以\0终止的字符串,指定被监控的设备的ID或者不含序号的主名称,对于串口该参数必须为NULL或者"COM" iNotifyRoutine:mPCH341PT_NOTIFY_ROUTINE):boolean;stdcall; external 'CH341PT.DLL'; // 指定端口设备事件回调程序,为NULL则取消事件通知,否则在检测到事件时调用该程序 {/* 即插即用设备的应用程序编程参考 1. 主程序启动,默认是禁止数据传输的,只有在确定有CH341端口可用并且打开端口后才进行数据传输 2. 调用CH341PtSetDevNotify设置插拔监视,如果将来发生CH341端口的插拔事件DLL将会自动调用iNotifyRoutine所指定的子程序或者函数 3. 从端口1到端口255(正常到20即可)逐个调用CH341PtNameIsCH341确定是否为CH341端口,如果返回是则记忆其端口号并打开后开始传输,如果返回否则休息 4. 如果iNotifyRoutine收到事件通知,那么可以在保存事件参数后通知主程序处理,也可以在该子程序中处理, 分析事件参数,如果是正数则说明有一个端口插入,需要打开时应该首先用CH341PtNameIsCH341判断是否为CH341端口,是则记忆其端口号并打开后开始传输, 如果是负数则说明有一个端口拔出,判断其端口号(用0减去该负数得端口号)是否与记忆的已打开的端口号相同,是则应该及时关闭 5. 当前已经打开的端口号应该保存为全局变量, 如果端口未打开或者被关闭,那么应用程序应该停止数据传输 6. 如果事先未用CH341PtNameIsCH341确定是否为CH341端口,那么在端口已经打开后,也可以调用CH341PtHandleIsCH341判断是否为CH341端口 */} implementation end.
unit u_xpl_settings; {============================================================================== UnitDesc = xPL Registry and Global Settings management unit UnitCopyright = GPL by Clinique / xPL Project ============================================================================== 0.97 : Application creates a registry key "HKLM\Software\xPL\[vendorid]\[deviceid]" and a string value "Version" within that key. Because the software is non-device, you'll have to come up with a 'virtual' unique device ID. 0.98 : Added proxy information detecting capability 0.99 : Modification to Registry reading behaviour to allow lazarus reg.xml compatibility 1.10 : Added elements to limitate needed access rights and detect errors if we don't have enough rights } {$i xpl.inc} interface uses Registry , Classes , u_xpl_collection ; type // TxPLSettings ========================================================== TxPLSettings = class(TComponent) private fProxyEnable : boolean; fProxyServer, fBroadCastAddress, fListenOnAddress , fListenToAddresses : string; function GetListenOnAll : boolean; function GetListenToAny : boolean; function GetListenToLocal : boolean; public constructor Create(AOwner: TComponent); override; //destructor Destroy; override; procedure InitComponent; virtual; abstract; function IsValid : boolean; published property ListenToAny : boolean read GetListenToAny; property ListenToLocal : boolean read GetListenToLocal; property ListenOnAll : boolean read GetListenOnAll; property ListenOnAddress : string read fListenOnAddress; property ListenToAddresses : string read fListenToAddresses; property BroadCastAddress : string read fBroadCastAddress; property ProxyEnable : boolean read fProxyEnable; property ProxyServer : string read fProxyServer; end; // TxPLCommandLineSettings ============================================== TxPLCommandLineSettings = class(TxPLSettings) public procedure InitComponent; override; end; // TxPLRegistrySettings ================================================== TxPLRegistrySettings = class(TxPLSettings) private fRegistry : TRegistry; function ReadKeyString (const aKeyName : string; const aDefault : string = '') : string; procedure WriteKeyString(const aKeyName : string; const aValue : string); procedure SetListenOnAll (const bValue : boolean); procedure SetListenToLocal (const bValue : boolean); procedure SetListenToAny (const bValue : boolean); procedure SetListenOnAddress (const AValue: string); procedure SetListenToAddresses(const AValue: string); procedure SetBroadCastAddress (const AValue: string); public procedure InitComponent; override; destructor Destroy; override; function GetxPLAppList : TxPLCustomCollection; procedure GetAppDetail(const aVendor, aDevice : string; out aPath, aVersion, aProdName : string); procedure SetAppDetail(const aVendor, aDevice, aVersion: string); function Registry : TRegistry; published property ListenToAny : boolean read GetListenToAny write SetListenToAny; property ListenToLocal : boolean read GetListenToLocal write SetListenToLocal; property ListenOnAll : boolean read GetListenOnAll write SetListenOnAll; property ListenOnAddress : string read fListenOnAddress write SetListenOnAddress; property ListenToAddresses : string read fListenToAddresses write SetListenToAddresses; property BroadCastAddress : string read fBroadCastAddress write SetBroadCastAddress; end; implementation // ============================================================= uses SysUtils , StrUtils , u_xpl_application , uxPLConst , uIP , fpc_delphi_compat , lin_win_compat , CustApp {$ifndef fpc} , windows // Needed on delphi to define KEY_READ {$endif} ; const // Registry Key and values constants ==================================== K_XPL_ROOT_KEY = '\Software\xPL\'; K_XPL_FMT_APP_KEY = K_XPL_ROOT_KEY + '%s\%s\'; // \software\xpl\vendor\device\ K_LOG_INFO = 'xPL settings loaded : %s,%s,%s'; K_XPL_REG_VERSION_KEY = 'version'; K_XPL_REG_PRODUCT_NAME = 'productname'; K_XPL_REG_PATH_KEY = 'path'; K_XPL_SETTINGS_NETWORK_ANY = 'ANY'; K_XPL_SETTINGS_NETWORK_LOCAL = 'ANY_LOCAL'; K_REGISTRY_BROADCAST = 'BroadcastAddress'; K_REGISTRY_LISTENON = 'ListenOnAddress'; K_REGISTRY_LISTENTO = 'ListenToAddresses'; // TxPLSettings ================================================================= constructor TxPLSettings.Create(aOwner : TComponent); begin inherited; InitComponent; TxPLApplication(Owner).Log(etInfo,K_LOG_INFO, [fBroadCastAddress,fListenOnAddress,fListenToAddresses]); GetProxySettings(fProxyEnable,fProxyServer); // Stub to load informations depending upon the OS end; function TxPLSettings.GetListenToLocal : boolean; begin result := (ListenToAddresses = K_XPL_SETTINGS_NETWORK_LOCAL) end; function TxPLSettings.GetListenToAny : boolean; begin result := (ListenToAddresses = K_XPL_SETTINGS_NETWORK_ANY) end; function TxPLSettings.GetListenOnAll : boolean; begin result := AnsiIndexStr( ListenOnAddress, [K_XPL_SETTINGS_NETWORK_ANY,K_XPL_SETTINGS_NETWORK_LOCAL] ) <> -1 ; end; function TxPLSettings.IsValid: Boolean; // Just checks that all basic values begin // have been initialized result := (length(BroadCastAddress ) * length(ListenOnAddress ) * length(ListenToAddresses)) <>0; end; // TxPLCommandLineSettings ==================================================== procedure TxPLCommandLineSettings.InitComponent; var AddrObj : TIPAddress = nil; OptionValue : string; begin OptionValue := TxPLApplication(Owner).Application.GetOptionValue('i'); AddrObj := LocalIPAddresses.GetByIntName(OptionValue); if Assigned(AddrObj) and AddrObj.IsValid then begin fBroadCastAddress := AddrObj.BroadCast; fListenOnAddress := AddrObj.Address; fListenToAddresses := K_XPL_SETTINGS_NETWORK_ANY; end else TxPLApplication(Owner).Log(etError,'Invalid interface name specified (%s)',[OptionValue]); end; // TxPLRegistrySettings ======================================================= function TxPLRegistrySettings.Registry: TRegistry; begin if not Assigned(fRegistry) then fRegistry := TRegistry.Create(KEY_READ); Result := fRegistry; end; procedure TxPLRegistrySettings.InitComponent; begin fBroadCastAddress := ReadKeyString(K_REGISTRY_BROADCAST,'255.255.255.255'); fListenOnAddress := ReadKeyString(K_REGISTRY_LISTENON,K_XPL_SETTINGS_NETWORK_ANY); fListenToAddresses:= ReadKeyString(K_REGISTRY_LISTENTO,K_XPL_SETTINGS_NETWORK_ANY); end; destructor TxPLRegistrySettings.Destroy; begin if Assigned(Registry) then begin Registry.CloseKey; Registry.Free; end; inherited; end; function TxPLRegistrySettings.ReadKeyString(const aKeyName : string; const aDefault : string = '') : string; begin Registry.RootKey := HKEY_LOCAL_MACHINE; Registry.OpenKey(K_XPL_ROOT_KEY,True); Result := Registry.ReadString(aKeyName); if Result = '' then Result := aDefault; end; procedure TxPLRegistrySettings.WriteKeyString(const aKeyName : string; const aValue : string); begin Registry.Access := KEY_WRITE; with Registry do try RootKey := HKEY_LOCAL_MACHINE; OpenKey(K_XPL_ROOT_KEY,True); try WriteString(aKeyName,aValue); // Try to write the value except end; finally Access := KEY_READ; end; end; procedure TxPLRegistrySettings.SetListenToLocal(const bValue : boolean); begin ListenToAddresses := IfThen(bValue,K_XPL_SETTINGS_NETWORK_LOCAL); end; procedure TxPLRegistrySettings.SetListenToAny(const bValue : boolean); begin ListenToAddresses := IfThen(bValue,K_XPL_SETTINGS_NETWORK_ANY) ; end; procedure TxPLRegistrySettings.SetListenOnAll(const bValue : boolean); begin ListenOnAddress := IfThen(bValue,K_XPL_SETTINGS_NETWORK_LOCAL); end; procedure TxPLRegistrySettings.SetListenToAddresses(const AValue: string); begin fListenToAddresses := aValue; WriteKeyString(K_REGISTRY_LISTENTO,aValue); end; procedure TxPLRegistrySettings.SetListenOnAddress(const AValue: string); begin fListenOnAddress := aValue; WriteKeyString(K_REGISTRY_LISTENON,aValue); end; procedure TxPLRegistrySettings.SetBroadCastAddress(const AValue: string); begin fBroadCastAddress := aValue; WriteKeyString(K_REGISTRY_BROADCAST,aValue); end; function TxPLRegistrySettings.GetxPLAppList : TxPLCustomCollection; var aVendorListe, aAppListe : TStringList; vendor, app : string; item : TxPLCollectionItem; begin aVendorListe := TStringList.Create; aAppListe := TStringList.Create; result := TxPLCustomCollection.Create(nil); Registry.RootKey := HKEY_LOCAL_MACHINE; Registry.OpenKey(K_XPL_ROOT_KEY ,True); Registry.GetKeyNames(aVendorListe); for vendor in aVendorListe do begin Registry.OpenKey(K_XPL_ROOT_KEY,False); Registry.OpenKey(vendor,False); Registry.GetKeyNames(aAppListe); for app in aAppListe do begin item := Result.Add(app); item.Value := vendor; end; end; aVendorListe.Free; aAppListe.Free; end; procedure TxPLRegistrySettings.GetAppDetail(const aVendor, aDevice : string; out aPath, aVersion, aProdName: string); begin with Registry do begin RootKey := HKEY_LOCAL_MACHINE; OpenKey (K_XPL_ROOT_KEY, False); OpenKey (aVendor, True); // At the time, you can't read this OpenKey (aDevice, False); aVersion := ReadString(K_XPL_REG_VERSION_KEY); // if you don't have admin rights under Windows aPath := ReadString(K_XPL_REG_PATH_KEY); aProdName:= ReadString(K_XPL_REG_PRODUCT_NAME); end; end; procedure TxPLRegistrySettings.SetAppDetail(const aVendor, aDevice, aVersion: string); begin Registry.Access := KEY_WRITE; with Registry do try RootKey := HKEY_LOCAL_MACHINE; OpenKey(Format(K_XPL_FMT_APP_KEY,[aVendor,aDevice]),True); try WriteString(K_XPL_REG_VERSION_KEY,aVersion); WriteString(K_XPL_REG_PATH_KEY,ParamStr(0)); WriteString(K_XPL_REG_PRODUCT_NAME,GetProductName); except end; finally Access := KEY_READ; end; end; end.
unit uParserBase; interface uses classes, Generics.Collections, uIntfaceFull; type TParserBase = class(TObject) private protected //class var FMaxId: Int64; FList: TList; FMapProp: TDictionary<String, String>; FMapColumn: TDictionary<String, String>; FColumns: TStrings; FFormName: string; FIntfaceFull: TIntfaceFull; // FOnLine: TGetStrProc; FOnResultLine: TGetStrProc; procedure doOnLine(const S: string); procedure doOnResultLine(const S: string); // procedure setContent(const strs: TStrings); virtual; abstract; procedure setColumn(const str: String); // function reqToConditionStr(const IntfaceFull: TIntfaceFull; const strsReq: TStrings): string; function reqToParamStr(const IntfaceFull: TIntfaceFull; const strsReq: TStrings): string; function reqToVarStr(const IntfaceFull: TIntfaceFull; const strsReq: TStrings): string; public FTableName: string; FComment: string; procedure initial(const S: string); public class constructor Create; constructor Create; destructor Destroy; override; public property List: TList read FList write FList; property MapProp: TDictionary<String, String> read FMapProp write FMapProp; property MapColumn: TDictionary<String, String> read FMapColumn write FMapColumn; property Context: TStrings write setContent; property Columns: String write setColumn; property OnLine: TGetStrProc read FOnLine write FOnLine; property OnResultLine: TGetStrProc read FOnResultLine write FOnResultLine; end; implementation uses SysUtils, uCharSplit; { TCarBrand } class constructor TParserBase.Create; begin //FMaxId := 67541628411220000; end; constructor TParserBase.Create; begin //inherited Create; FFormName := 'form1'; FIntfaceFull := TIntfaceFull.Create; FList := TList.Create; FColumns := TStringList.Create; FMapProp := TDictionary<String, String>.Create; FMapColumn:= TDictionary<String, String>.Create; end; destructor TParserBase.Destroy; begin FIntfaceFull.Free; FList.Free; FMapProp.Free; FColumns.Free; FMapColumn.Free; end; procedure TParserBase.doOnLine(const S: string); begin if Assigned(FOnLine) then begin FOnLine(S); end; end; procedure TParserBase.doOnResultLine(const S: string); begin if Assigned(FOnResultLine) then begin FOnResultLine(S); end; end; procedure TParserBase.initial(const S: string); begin self.FMapProp.Add('序号', 'type="index"'); end; procedure TParserBase.setColumn(const str: String); var i: integer; ss: TStrings; S: string; begin FMapColumn.Clear; FColumns.Clear; ss := TStringList.Create(); try TCharSplit.SplitChar(str, #9, ss); for I := 0 to ss.Count - 1 do begin s := ss[I]; FMapColumn.AddOrSetValue(S, S); FColumns.Add(S); end; finally ss.Free; end; end; function TParserBase.reqToVarStr(const IntfaceFull: TIntfaceFull; const strsReq: TStrings): string; function doOneIt(const S: string): string; const SS = ' %s: %s, ' + #13#10; var key: string; begin key := TCharSplit.getSplitIdx(S, #9, 0); Result := format(SS, [key, QuotedStr('')]); end; var i: integer; S: string; begin Result := #13#10; Result := Result + ' ' + FFormName + ' {' + #13#10; for I := 0 to strsReq.Count - 1 do begin S := strsReq[I]; Result := result + doOneIt(S); end; Result := Result + ' ' + '},'; end; function TParserBase.reqToParamStr(const IntfaceFull: TIntfaceFull; const strsReq: TStrings): string; function doOneIt(const S: string): string; const SS = ' %s: this.%s.%s, ' + #13#10; var key: string; begin key := TCharSplit.getSplitIdx(S, #9, 0); Result := format(SS, [key, FFormName, key]); end; var i: integer; S: string; begin Result := #13#10; for I := 0 to strsReq.Count - 1 do begin S := strsReq[I]; Result := result + doOneIt(S); end; end; function TParserBase.reqToConditionStr(const IntfaceFull: TIntfaceFull; const strsReq: TStrings): string; function doOneIt(const S: string): string; const llbeg = ' <el-form-item label="%s" prop="%s">'; const input_edt = ' <el-input v-model="%s.%s" placeholder="%s" width="150" align="center"/>'; const llend = ' </el-form-item>'; var key, val: string; itemBeg, inputStr, itemEnd: string; begin key := TCharSplit.getSplitIdx(S, #9, 0); val := TCharSplit.getSplitIdx(S, #9, 1); itemBeg := format(llbeg, [val, key]); inputStr := format(input_edt, [FFormName, key, '请输入' + val]); itemEnd := llend; Result := itemBeg + #13#10 + inputStr + #13#10 + itemEnd; end; var i: integer; S: string; begin Result := #13#10; Result := Result + ' //查询条件' + #13#10; S := ' <el-form :inline="true" :model="%s">'; S := format(s, [FFormName]); Result := Result + S; for I := 0 to strsReq.Count - 1 do begin S := strsReq[I]; Result := result + #13#10 + doOneIt(S); end; Result := Result + #13#10 + ' </el-form>'; end; end.
unit Amazon.Client; interface uses Amazon.Interfaces, {$IFNDEF FPC} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} Amazon.Credentials, Amazon.Utils, Amazon.Response, //System.Rtti, Amazon.Request, Amazon.SignatureV4; type TAmazonClient = class(TInterfacedObject, IAmazonClient) protected FAmazonRESTClient: IAmazonRESTClient; FAmazonCredentials: tAmazonCredentials; fsendpoint: UTF8String; fsservice: UTF8String; fshost: UTF8String; fsAuthorization_header: UTF8String; private function getsecret_key: UTF8String; procedure setsecret_key(value: UTF8String); function getaccess_key: UTF8String; procedure setaccess_key(value: UTF8String); function getregion: UTF8String; procedure setregion(value: UTF8String); function getprofile: UTF8String; procedure setprofile(value: UTF8String); function getcredential_file: UTF8String; procedure setcredential_file(value: UTF8String); function getendpoint: UTF8String; procedure setendpoint(value: UTF8String); function getservice: UTF8String; procedure setservice(value: UTF8String); function gethost: UTF8String; procedure sethost(value: UTF8String); public constructor Create; overload; constructor Create(aAmazonRESTClient: IAmazonRESTClient); overload; constructor Create(aAmazonRESTClient: IAmazonRESTClient; asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String); overload; constructor Create(aAmazonRESTClient: IAmazonRESTClient; aprofile: UTF8String); overload; constructor Create(aAmazonRESTClient: IAmazonRESTClient; aprofile: UTF8String; asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String); overload; destructor Destory; procedure InitClient(aprofile: UTF8String; asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String); virtual; property profile: UTF8String read getprofile write setprofile; property credential_file: UTF8String read getcredential_file write setcredential_file; property region: UTF8String read getregion write setregion; property secret_key: UTF8String read getsecret_key write setsecret_key; property access_key: UTF8String read getaccess_key write setaccess_key; property endpoint: UTF8String read getendpoint write setendpoint; property service: UTF8String read getservice write setservice; property host: UTF8String read gethost write sethost; function MakeRequest(aAmazonRequest: IAmazonRequest; aAmazonRESTClient: IAmazonRESTClient): IAmazonResponse; function execute(aAmazonRequest: IAmazonRequest; aAmazonSignature: IAmazonSignature; aAmazonRESTClient: IAmazonRESTClient) : IAmazonResponse; virtual; end; implementation constructor TAmazonClient.Create; begin InitClient('', '', '', ''); end; constructor TAmazonClient.Create(aAmazonRESTClient: IAmazonRESTClient); begin FAmazonRESTClient := aAmazonRESTClient; InitClient('', '', '', ''); end; constructor TAmazonClient.Create(aAmazonRESTClient: IAmazonRESTClient;asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String); begin FAmazonRESTClient := aAmazonRESTClient; InitClient('', asecret_key, aaccess_key, aregion); end; constructor TAmazonClient.Create(aAmazonRESTClient: IAmazonRESTClient; aprofile: UTF8String); begin FAmazonRESTClient := aAmazonRESTClient; InitClient(aprofile, '', '', ''); end; constructor TAmazonClient.Create(aAmazonRESTClient: IAmazonRESTClient; aprofile: UTF8String; asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String); begin FAmazonRESTClient := aAmazonRESTClient; InitClient(aprofile, asecret_key, aaccess_key, aregion); end; destructor TAmazonClient.Destory; begin FreeandNil(FAmazonCredentials); end; procedure TAmazonClient.InitClient(aprofile: UTF8String; asecret_key: UTF8String; aaccess_key: UTF8String; aregion: UTF8String); begin FAmazonCredentials := tAmazonCredentials.Create; fsendpoint := ''; fsservice := ''; fshost := ''; FAmazonCredentials.profile := aprofile; FAmazonCredentials.access_key := aaccess_key; FAmazonCredentials.secret_key := asecret_key; FAmazonCredentials.region := aregion; if (aaccess_key = '') and (asecret_key = '') then begin if FAmazonCredentials.Iscredential_file then begin if FAmazonCredentials.profile = '' then FAmazonCredentials.profile := 'default'; FAmazonCredentials.Loadcredential_file; end else FAmazonCredentials.GetEnvironmentVariables; end; end; function TAmazonClient.getregion: UTF8String; begin result := ''; if Assigned(FAmazonCredentials) then result := FAmazonCredentials.region; end; procedure TAmazonClient.setregion(value: UTF8String); begin if Assigned(FAmazonCredentials) then FAmazonCredentials.region := value; end; function TAmazonClient.getaccess_key: UTF8String; begin result := ''; if Assigned(FAmazonCredentials) then result := FAmazonCredentials.access_key; end; procedure TAmazonClient.setaccess_key(value: UTF8String); begin if Assigned(FAmazonCredentials) then FAmazonCredentials.access_key := value; end; function TAmazonClient.getsecret_key: UTF8String; begin result := ''; if Assigned(FAmazonCredentials) then result := FAmazonCredentials.secret_key; end; procedure TAmazonClient.setsecret_key(value: UTF8String); begin if Assigned(FAmazonCredentials) then FAmazonCredentials.secret_key := value; end; function TAmazonClient.getprofile: UTF8String; begin result := ''; if Assigned(FAmazonCredentials) then result := FAmazonCredentials.profile; end; procedure TAmazonClient.setprofile(value: UTF8String); begin if Assigned(FAmazonCredentials) then FAmazonCredentials.profile := value; end; function TAmazonClient.getcredential_file: UTF8String; begin result := ''; if Assigned(FAmazonCredentials) then result := FAmazonCredentials.credential_file; end; procedure TAmazonClient.setcredential_file(value: UTF8String); begin if Assigned(FAmazonCredentials) then FAmazonCredentials.credential_file := value; end; function TAmazonClient.getendpoint: UTF8String; begin result := fsendpoint; end; procedure TAmazonClient.setendpoint(value: UTF8String); begin fsendpoint := value; end; function TAmazonClient.getservice: UTF8String; begin result := fsservice; end; procedure TAmazonClient.setservice(value: UTF8String); begin fsservice := value; end; function TAmazonClient.gethost: UTF8String; begin result := fshost; end; procedure TAmazonClient.sethost(value: UTF8String); begin fshost := value; end; function TAmazonClient.execute(aAmazonRequest: IAmazonRequest; aAmazonSignature: IAmazonSignature; aAmazonRESTClient: IAmazonRESTClient) : IAmazonResponse; var amz_date: UTF8String; date_stamp: UTF8String; content_type: UTF8String; fsresponse: UTF8String; FAmazonResponse: tAmazonResponse; begin result := NIL; if (secret_key = '') or (access_key = '') then raise Exception.Create('secret_key or access_key not assigned.'); if Not Assigned(aAmazonRESTClient) then raise Exception.Create('IAmazonRESTClient not assigned.'); if region = '' then raise Exception.Create('region not assigned.'); Try GetAWSDate_Stamp(UTCNow, amz_date, date_stamp); content_type := aAmazonSignature.GetContent_type; aAmazonRequest.secret_key := secret_key; aAmazonRequest.access_key := access_key; aAmazonRequest.service := service; aAmazonRequest.endpoint := endpoint; if host = '' then aAmazonRequest.host := GetAWSHost(aAmazonRequest.endpoint) else aAmazonRequest.host := host; aAmazonRequest.region := region; aAmazonRequest.amz_date := amz_date; aAmazonRequest.date_stamp := date_stamp; aAmazonSignature.Sign(aAmazonRequest); aAmazonRESTClient.content_type := content_type; aAmazonRESTClient.AddHeader('X-Amz-Date', amz_date); aAmazonRESTClient.AddHeader('X-Amz-Target', aAmazonRequest.target); aAmazonRESTClient.AddHeader('Authorization', aAmazonSignature.Authorization_header); fsresponse := ''; aAmazonRESTClient.Post(endpoint, aAmazonRequest.request_parameters, fsresponse); Finally FAmazonResponse := tAmazonResponse.Create; FAmazonResponse.Response := fsresponse; FAmazonResponse.ResponseCode := aAmazonRESTClient.ResponseCode; FAmazonResponse.ResponseText := aAmazonRESTClient.ResponseText; result := FAmazonResponse; End; end; function TAmazonClient.MakeRequest(aAmazonRequest: IAmazonRequest; aAmazonRESTClient: IAmazonRESTClient): IAmazonResponse; var // FAmazonRESTClient: TAmazonRESTClient; FAmazonSignatureV4: TAmazonSignatureV4; begin Try FAmazonSignatureV4 := TAmazonSignatureV4.Create; // FAmazonRESTClient := TAmazonRESTClient.Create; result := execute(aAmazonRequest, FAmazonSignatureV4, aAmazonRESTClient); Finally FAmazonSignatureV4 := NIL; // FAmazonRESTClient := NIL; End; end; end.
namespace RemObjects.Elements.System; interface type LCMapStringTransformMode = assembly enum (None, Upper, Lower); String = public class(Object) assembly {$HIDE H6} fLength: Integer; fFirstChar: Char;{$SHOW H6} method get_Item(i: Integer): Char; constructor; empty; // not callable method IndexOf(Value: String; aStartFromIndex: Integer): Int32; {$IFDEF WINDOWS} method doLCMapString(aInvariant: Boolean := false; aMode:LCMapStringTransformMode := LCMapStringTransformMode.None):String; {$ENDIF} method TestChar(c: Char; Arr : array of Char): Boolean; method MakeInvariantString: String; class method RaiseError(aMessage: String); method CheckIndex(aIndex: integer); assembly {$IFDEF POSIX} class var fUTF16ToCurrent, fCurrentToUtf16: rtl.iconv_t; {$ENDIF} class method AllocString(aLen: Integer): String; public class constructor; //constructor(aArray: array of Char); //constructor(c: ^Char; aCharCount: Integer): String; class method FromCharArray(aArray: array of Char): String; class method FromPChar(c: ^Char; aCharCount: Integer): String; class method FromPChar(c: ^Char): String; class method FromPAnsiChars(c: ^AnsiChar; aCharCount: Integer): String; class method FromPAnsiChars(c: ^AnsiChar): String; class method FromRepeatedChar(c: Char; aCharCount: Integer): String; class method FromChar(c: Char): String; class method IsNullOrEmpty(value: String):Boolean; method ToAnsiChars(aNullTerminate: Boolean := false): array of AnsiChar; method ToCharArray(aNullTerminate: Boolean := false): array of Char; property Length: Integer read fLength; property Item[i: Integer]: Char read get_Item; default; property FirstChar: ^Char read @fFirstChar; method CompareTo(Value: String): Integer; method CompareToIgnoreCase(Value: String): Integer; method &Equals(Value: String): Boolean; method EqualsIgnoreCase(Value: String): Boolean; class method &Join(Separator: String; Value: array of String): String; class method &Join(Separator: String; Value: IEnumerable<String>): String; class method &Join<T>(Separator: String; Value: IEnumerable<T>): String; class method &Join(Separator: String; Value: array of String; StartIndex: Integer; Count: Integer): String; class method &Join(Separator: String; Value: array of Object): String; method Contains(Value: String): Boolean; method IndexOf(Value: String): Int32; method LastIndexOf(Value: String): Int32; method Substring(StartIndex: Int32): not nullable String; method Substring(StartIndex: Int32; aLength: Int32): not nullable String; method Split(Separator: String): array of String; method Replace(OldValue, NewValue: String): not nullable String; method ToLower(aInvariant: Boolean := false): String; method ToUpper(aInvariant: Boolean := false): String; method Trim: String; method Trim(aChars: array of Char): String; method TrimStart: String; method TrimStart(aChars: array of Char): String; method TrimEnd: String; method TrimEnd(aChars: array of Char): String; method StartsWith(Value: String; aInvariant: Boolean := false): Boolean; method EndsWith(Value: String; aInvariant: Boolean := false): Boolean; class method Format(aFormat: String; params aArguments: array of Object): String; class method Compare(aLeft, aRight: String): Integer; class operator Add(aLeft, aRight: String): String; class operator Add(aLeft: String; aChar: Char): String; class operator Add(aLeft: Char; aRight: String): String; class operator Add(aLeft: String; aRight: Object): String; class operator Add(aLeft: Object; aRight: String): String; class operator Implicit(Value: Char): String; class operator Greater(Value1, Value2: String): Boolean; class operator Less(Value1, Value2: String): Boolean; class operator GreaterOrEqual(Value1, Value2: String): Boolean; class operator LessOrEqual(Value1, Value2: String): Boolean; class operator Equal(Value1, Value2: String): Boolean; class operator NotEqual(Value1, Value2: String): Boolean; method ToString: String; override; method GetHashCode: Integer; override; end; String_Constructors = public extension class(String) constructor(aArray: array of Char); constructor(c: ^Char; aCharCount: Integer); constructor(c: ^Char); constructor(c: Char; aCharCount: Integer); constructor(c: Char); constructor(c: ^AnsiChar; aCharCount: Integer); constructor(c: ^AnsiChar); end; {$IFDEF POSIX} method iconv_helper(cd: rtl.iconv_t; inputdata: ^AnsiChar; inputdatalength: rtl.size_t; suggestedlength: Integer; out aresult: ^ansichar): integer; public; {$ENDIF} implementation class method String.FromPChar(c: ^Char; aCharCount: Integer): String; begin result := AllocString(aCharCount); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@result.ffirstChar, c, aCharCount * 2); end; {$IFDEF POSIX} method iconv_helper(cd: rtl.iconv_t; inputdata: ^AnsiChar; inputdatalength: rtl.size_t; suggestedlength: Integer; out aresult: ^ansichar): integer; begin var outputdata := ^AnsiChar(rtl.malloc(suggestedlength)); if outputdata = nil then begin exit -1; end; var inpos := inputdata; var outpos := outputdata; var left: rtl.size_t := inputdatalength; var outleft: rtl.size_t := suggestedlength; retry:; var count := rtl.iconv(cd, @inpos, @left, @outpos, @outleft); if (count = rtl.size_t(- 1)) and (rtl.errno = 7) then begin suggestedlength := suggestedlength + 16; var cu := outpos - outputdata; outputdata := ^ansichar(rtl.realloc(outputdata, suggestedlength)); outpos := outputdata + cu; goto retry; end; if (count = rtl.size_t(-1)) then begin rtl.free(outputdata); exit -1; end; aresult := outputdata; result := suggestedlength - outleft; end; {$ENDIF} class method String.FromPAnsiChars(c: ^AnsiChar; aCharCount: Integer): String; begin {$IFDEF WINDOWS} var len := rtl.MultiByteToWideChar(rtl.CP_ACP, 0, c, aCharCount, nil, 0); result := AllocString(len); rtl.MultiByteToWideChar(rtl.CP_ACP, 0, c, aCharCount, @result.fFirstChar, len); {$ELSE} var lNewData: ^AnsiChar := nil; var lNewLen: rtl.size_t := iconv_helper(String.fCurrentToUtf16, c, aCharCount, aCharCount * 2 + 5, out lNewData); // method iconv_helper(cd: rtl.iconv_t; inputdata: ^AnsiChar; inputdatalength: rtl.size_t;outputdata: ^^AnsiChar; outputdatalength: ^rtl.size_t; suggested_output_length: Integer): Integer; if lNewLen <> -1 then begin result := String.FromPChar(^Char(lNewData), lNewLen / 2); rtl.free(lNewData); end; {$ENDIF} end; method String.ToAnsiChars(aNullTerminate: Boolean := false): array of AnsiChar; begin {$IFDEF WINDOWS} var len := rtl.WideCharToMultiByte(rtl.CP_ACP, 0, @self.fFirstChar, length, nil, 0, nil, nil); result := new AnsiChar[len+ if aNullTerminate then 1 else 0]; rtl.WideCharToMultiByte(rtl.CP_ACP, 0, @self.fFirstChar, length, rtl.LPSTR(@result[0]), len, nil, nil); {$ELSE} var lNewData: ^AnsiChar := nil; var lNewLen: rtl.size_t := iconv_helper(String.fUTF16ToCurrent, ^AnsiChar(@fFirstChar), Length * 2, Length + 5, out lNewData); if lNewLen <> -1 then begin result := new AnsiChar[lNewLen+ if aNullTerminate then 1 else 0]; rtl.memcpy(@result[0], lNewData, lNewLen); rtl.free(lNewData); end; {$ENDIF} end; method String.get_Item(i: Integer): Char; begin CheckIndex(i); exit (@self.fFirstChar)[i]; end; class operator String.Add(aLeft, aRight: String): String; begin if (Object(aLeft) = nil) or (aLeft.Length = 0) then exit aRight; if (Object(aRight) = nil) or (aRight.Length = 0) then exit aLeft; result := AllocString(aLeft.Length + aRight.Length); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@result.fFirstChar, @aLeft.fFirstChar, aLeft.Length * 2); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy((@result.fFirstChar) + aLeft.Length, @aRight.fFirstChar, aRight.Length * 2); end; class operator String.Add(aLeft: String; aChar: Char): String; begin if (Object(aLeft) = nil) or (aLeft.Length = 0) then exit aChar; result := AllocString(aLeft.Length + 1); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@result.fFirstChar, @aLeft.fFirstChar, aLeft.Length * 2); (@result.fFirstChar)[aLeft.Length] := aChar; end; class operator String.Add(aLeft: Char; aRight: String): String; begin if (Object(aRight) = nil) or (aRight.Length = 0) then exit aLeft; result := AllocString(aRight.Length + 1); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy((@result.fFirstChar) + 1, @aRight.fFirstChar, aRight.Length * 2); (@result.fFirstChar)[0] := aLeft; end; class operator String.Add(aLeft: String; aRight: Object): String; begin exit aLeft + (aRight:ToString); end; class operator String.Add(aLeft: Object; aRight: String): String; begin exit (aLeft:ToString) + aRight; end; class operator String.Implicit(Value: Char): String; begin result := AllocString(1); result.fFirstChar := Value; end; class method String.AllocString(aLen: Integer): String; begin result := InternalCalls.Cast<String>(Utilities.NewInstance(InternalCalls.GetTypeInfo<String>(), (sizeof(Object) + sizeof(Integer)) + 2 * aLen)); result.fLength := aLen; end; method String.ToString: String; begin exit self; end; method String.GetHashCode: Integer; begin exit Utilities.CalcHash(@fFirstChar, fLength*2); end; method String.Trim: String; begin if String.IsNullOrEmpty(self) then exit self; var lresult := new array of Char(self.Length); var pos:=0; for i: integer := 0 to self.Length-1 do if self.Item[i] > ' ' then begin lresult[pos] := self.Item[i]; inc(pos); end; exit String.FromPChar(@lresult,pos); end; method String.Trim(aChars: array of Char): String; begin if String.IsNullOrEmpty(self) then exit self; var lresult := ''; for i: integer := 0 to self.Length-1 do if not TestChar(self.Item[i], aChars) then lresult := lresult + self.Item[i]; exit lresult; end; method String.TrimStart: String; begin if String.IsNullOrEmpty(self) then exit self; var i: integer := 0; while (i < self.Length) and (self.Item[i] <= ' ') do i:=i+1; if i < self.Length then exit self.Substring(i) else exit ''; end; method String.TrimStart(aChars: array of Char): String; begin if String.IsNullOrEmpty(self) then exit self; var i: integer := 0; while (i < self.Length) and TestChar(self.Item[i], aChars) do i:=i+1; if i < self.Length then exit self.Substring(i) else exit ''; end; method String.TrimEnd: String; begin if String.IsNullOrEmpty(self) then exit self; var i: Integer := self.Length-1; while (i >= 0) and (self.Item[i] <=' ') do i:=i-1; if i < 0 then exit '' else exit self.Substring(0,i+1); end; method String.TrimEnd(aChars: array of Char): String; begin if String.IsNullOrEmpty(self) then exit self; var i: Integer := self.Length-1; while (i >= 0) and TestChar(self.Item[i], aChars) do i:=i-1; if i < 0 then exit '' else exit self.Substring(0,i+1); end; method String.Substring(StartIndex: Int32): not nullable String; begin CheckIndex(StartIndex); exit Substring(StartIndex, self.Length - StartIndex) end; method String.Substring(StartIndex: Int32; aLength: Int32): not nullable String; begin CheckIndex(StartIndex); if aLength = 0 then exit ''; {$HIDE W46} exit String.FromPChar(@(@fFirstChar)[StartIndex], aLength); {$SHOW W46} end; method String.&Equals(Value: String): Boolean; begin exit self = Value; end; method String.EqualsIgnoreCase(Value: String): Boolean; begin exit self:ToLower() = Value:ToLower(); end; class operator String.Equal(Value1, Value2: String): Boolean; begin // (value1 = value2) = true if (Object(Value1) = nil) and (Object(Value2) = nil) then exit true; if ((Object(Value1) = nil) and (Object(Value2) <> nil)) or ((Object(Value1) <> nil) and (Object(Value2) = nil)) then exit false; if Value1.Length <> Value2.Length then exit false; for i: Integer :=0 to Value1.Length-1 do if Value1.item[i] <> Value2.item[i] then exit false; exit true; end; class operator String.NotEqual(Value1, Value2: String): Boolean; begin exit not Value1.Equals(Value2); end; method String.Contains(Value: String): Boolean; begin exit self.IndexOf(Value) > -1; end; method String.IndexOf(Value: String; aStartFromIndex: Integer): Int32; begin var Value_Length := Value.Length; if Value_Length > Self.Length then exit -1; if Value_Length = 0 then exit -1; for i: Integer := aStartFromIndex to Self.Length-Value_Length do begin var lfound:= true; for j: Integer :=0 to Value_Length-1 do begin lfound:=lfound and (self.Item[i+j] = Value.Item[j]); if not lfound then break; end; if lfound then exit i; end; exit -1; end; method String.LastIndexOf(Value: String): Int32; begin var Value_Length := Value.Length; if Value_Length > Self.Length then exit -1; if Value_Length = 0 then exit -1; for i: Integer := Self.Length-Value_Length downto 0 do begin var lfound:= true; for j: Integer := 0 to Value_Length-1 do begin lfound := lfound and (self.Item[i+j] = Value.Item[j]); if not lfound then break; end; if lfound then exit i; end; exit -1; end; method String.IndexOf(Value: String): Int32; begin exit self.IndexOf(Value,0); end; method String.Replace(OldValue, NewValue: String): not nullable String; begin result := self; var oldValue_Length := OldValue.Length; var lstart:=0; repeat lstart := result.IndexOf(OldValue, lstart); if lstart <> -1 then begin var lrest : not nullable String := ''; if lstart+oldValue_Length < result.Length then lrest := result.Substring(lstart+oldValue_Length); result := result.Substring(0, lstart)+NewValue+lrest; end; until lstart = -1; end; class operator String.Greater(Value1, Value2: String): Boolean; begin // Value1 > Value2 = true if (Object(Value1) = nil) then exit false; // nil > ???? if (Object(Value2) = nil) then exit true; // not nil > nil var min_length := iif(Value1.Length > Value2.Length, Value2.Length, Value1.Length); for i: Integer := 0 to min_length-1 do if Value1.item[i] <= Value2.item[i] then exit false; // a <= b exit Value1.Length > Value2.Length; // xxxy > xxx end; class operator String.Less(Value1, Value2: String): Boolean; begin // Value1 < Value2 = true if (Object(Value2) = nil) then exit false; // ???? < nil if (Object(Value1) = nil) then exit true; // nil < not nil var min_length := iif(Value1.Length > Value2.Length, Value2.Length, Value1.Length); for i: Integer :=0 to min_length-1 do if Value1.item[i] >= Value2.item[i] then exit false; // b >= a exit Value1.Length < Value2.Length; // xxx < xxxy end; class operator String.GreaterOrEqual(Value1, Value2: String): Boolean; begin // Value1 >= Value2 = true if (Object(Value2) = nil) then exit true; // ???? >= nil if (Object(Value1) = nil) then exit false; // nil >= ???? var min_length := iif(Value1.Length > Value2.Length, Value2.Length, Value1.Length); for i: Integer :=0 to min_length-1 do if Value1.item[i] < Value2.item[i] then exit false; // a <= b exit Value1.Length >= Value2.Length; // xxxy > xxx end; class operator String.LessOrEqual(Value1, Value2: String): Boolean; begin // Value1 <= Value2 = true if (Object(Value1) = nil) then exit true; // nil <= ???? if (Object(Value2) = nil) then exit false; // ???? <= nil var min_length := iif(Value1.Length > Value2.Length, Value2.Length, Value1.Length); for i: Integer :=0 to min_length-1 do if Value1.item[i] > Value2.item[i] then exit false; // b > a exit Value1.Length <= Value2.Length; // xxx <= xxxy end; method String.TestChar(c: Char; Arr : array of Char): Boolean; begin for d: Char in Arr do if d = c then exit true; exit false; end; class method String.Compare(aLeft, aRight: String): Integer; begin if (Object(aLeft) = nil) and (Object(aRight) = nil) then exit 0; if (Object(aLeft) = nil) then exit -1; if (Object(aRight) = nil) then exit 1; var min_length := iif(aLeft.Length > aRight.Length, aRight.Length, aLeft.Length); for i: Integer :=0 to min_length-1 do begin if aLeft.item[i] > aRight.item[i] then exit 1; if aLeft.item[i] < aRight.item[i] then exit -1; end; exit aLeft.Length - aRight.Length; end; method String.StartsWith(Value: String; aInvariant: Boolean := false): Boolean; begin if Value.Length > self.Length then exit false; var s1 := iif(aInvariant, self.MakeInvariantString(), self); var s2 := iif(aInvariant, Value.MakeInvariantString(), Value); exit s1.IndexOf(s2,0) = 0; end; method String.EndsWith(Value: String; aInvariant: Boolean := false): Boolean; begin if Value.Length > self.Length then exit false; var s1 := iif(aInvariant, self.MakeInvariantString(), self); var s2 := iif(aInvariant, Value.MakeInvariantString(), Value); var pos := self.Length-Value.Length; exit s1.IndexOf(s2, pos) = pos; end; method String.CompareTo(Value: String): Integer; begin exit String.Compare(self,Value); end; method String.CompareToIgnoreCase(Value: String): Integer; begin exit String.Compare(self:ToLower(), Value:ToLower()); end; method String.Split(Separator: String): array of String; begin if (Separator = nil) or (Separator = '') then begin result := new String[1]; result[0] := self; exit result; end; // detect array dimension var Sep_len := Separator.Length; var self_len := Self.Length; var len := 0; var i := 0; repeat i := self.IndexOf(Separator, i); if i <> -1 then begin len := len+1; i := i + Sep_len; if i >= self_len then break; end; until i = -1; result := new String[len+1]; if len = 0 then begin result[0] := self; exit result; end; // fill array i := 0; var old_i:=0; len:=0; repeat i := self.IndexOf(Separator, old_i); if i <> -1 then begin result[len]:= self.Substring(old_i, i-old_i); i := i + Sep_len; len := len+1; old_i:=i; end; until i = -1; if old_i < self_len then result[len] := self.Substring(old_i, self_len -old_i); end; {$IFDEF WINDOWS} method String.doLCMapString(aInvariant: Boolean := false; aMode:LCMapStringTransformMode := LCMapStringTransformMode.None):String; const LANG_INVARIANT = $007F; LOCALE_USER_DEFAULT = $0400; LCMAP_LOWERCASE = $00000100; LCMAP_UPPERCASE = $00000200; begin if self.Length = 0 then exit self; var locale : UInt32 := iif(aInvariant, LANG_INVARIANT, LOCALE_USER_DEFAULT); var options: UInt32; if aMode = LCMapStringTransformMode.Lower then options := LCMAP_LOWERCASE else if aMode = LCMapStringTransformMode.Upper then options := LCMAP_UPPERCASE else aMode := 0; var buf := @self.ffirstChar; var lrequired_size := rtl.LCMapStringW(locale, options,buf, self.Length, nil, 0); if (lrequired_size = 0) and (rtl.GetLastError <> 0) then RaiseError('Problem with calling LCMapString (1st call)'); result := AllocString(lrequired_size); lrequired_size := rtl.LCMapStringW(locale, options,@self.ffirstChar, self.Length, @result.ffirstChar, lrequired_size); if (lrequired_size = 0) and (rtl.GetLastError <> 0) then RaiseError('Problem with calling LCMapString (2nd call)'); end; {$ENDIF} method String.ToLower(aInvariant: Boolean := false): String; begin {$IFDEF WINDOWS} exit doLCMapString(aInvariant, LCMapStringTransformMode.Lower); {$ELSEIF POSIX} raise new NotImplementedException; {$ELSE}{$ERROR} {$ENDIF} end; method String.ToUpper(aInvariant: Boolean := false): String; begin {$IFDEF WINDOWS} exit doLCMapString(aInvariant, LCMapStringTransformMode.Upper); {$ELSEIF POSIX} raise new NotImplementedException; {$ELSE}{$ERROR} {$ENDIF} end; method String.MakeInvariantString: String; begin {$IFDEF WINDOWS} exit doLCMapString(true, LCMapStringTransformMode.None); {$ELSEIF POSIX} exit self; {$WARNING POSIX: implement MakeInvariantString} {$ELSE}{$ERROR} {$ENDIF} end; class method String.IsNullOrEmpty(value: String):Boolean; begin Result := (Object(value) = nil) or (value.Length = 0); end; method String.ToCharArray(aNullTerminate: Boolean := false): array of Char; begin var r := new array of Char(fLength + if aNullTerminate then 1 else 0); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@r[0], @ffirstChar, fLength * 2); if aNullTerminate then r[fLength] := #0; exit r; end; class method String.RaiseError(aMessage: String); begin raise new Exception(aMessage); end; method String.CheckIndex(aIndex: Integer); begin if (aIndex < 0) or (aIndex >= fLength) then raise new ArgumentOutOfRangeException('Index was out of range.'); end; class method String.FromPChar(c: ^Char): String; begin exit FromPChar(c, {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}wcslen(c)); end; class method String.FromChar(c: Char): String; begin exit FromPChar(@c, 1); end; class method String.FromRepeatedChar(c: Char; aCharCount: Integer): String; begin result := AllocString(aCharCount); for i: Integer := 0 to aCharCount-1 do (@result.fFirstChar)[i] := c; end; class method String.FromPAnsiChars(c: ^AnsiChar): String; begin exit FromPAnsiChars(c, {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}strlen(c)); end; class constructor String; begin {$IFDEF POSIX} rtl.setlocale(rtl.LC_ALL, ""); fUTF16ToCurrent := rtl.iconv_open("", "UTF-16LE"); fCurrentToUtf16 := rtl.iconv_open("UTF-16LE", ""); {$ENDIF} end; class method String.Format(aFormat: String; params aArguments: array of Object): String; begin if aFormat = nil then raise new ArgumentNullException('aFormat is nil'); if aArguments = nil then raise new ArgumentNullException('aArguments is nil'); var arg_count := aArguments.Length; var sb := new StringBuilder(aFormat.Length + aArguments.Length*8); var cur_pos := 0; var old_pos := 0; while cur_pos < aFormat.Length do begin case aFormat[cur_pos] of '{': begin sb.Append(aFormat, old_pos, cur_pos - old_pos); if (cur_pos < aFormat.Length-1) and (aFormat[cur_pos+1] = '{') then begin old_pos := cur_pos+1; inc(cur_pos,2); continue; end; // parses format specifier of form: // {N,[\ +[-]M][:F]} inc(cur_pos); // N = argument number (non-negative integer) var N: integer := 0; var fl:= true; while cur_pos < aFormat.Length-1 do begin if (aFormat[cur_pos] >='0') and (aFormat[cur_pos] <='9') then begin fl:= false; N:= N*10+ ord(aFormat[cur_pos])- ord('0'); inc(cur_pos); end else begin if fl then RaiseError('format error'); break; end; end; if n >= arg_count then raise new ArgumentOutOfRangeException('Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'); while (cur_pos < aFormat.Length-1) and (aFormat[cur_pos] = ' ') do begin inc(cur_pos);// skip spaces end; var sign := False; var width : Integer := 0; fl:= true; if aFormat[cur_pos] = ',' then begin inc(cur_pos); while (cur_pos < aFormat.Length-1) and (aFormat[cur_pos] = ' ') do begin inc(cur_pos);// skip spaces end; while (cur_pos < aFormat.Length-1) and (aFormat[cur_pos] = '-') do begin sign := True; inc(cur_pos);// skip any spaces end; while cur_pos < aFormat.Length-1 do begin if (aFormat[cur_pos] >='0') and (aFormat[cur_pos] <='9') then begin fl:= false; width:= width*10+ ord(aFormat[cur_pos])- ord('0'); inc(cur_pos); end else begin if fl then RaiseError('format error'); break; end; end; while (cur_pos < aFormat.Length-1) and (aFormat[cur_pos] = ' ') do begin inc(cur_pos);// skip spaces end; end else begin width := 0; sign := False; end; var sb1 := new StringBuilder; if aFormat[cur_pos] = ':' then begin inc(cur_pos); while true do begin case aFormat[cur_pos] of '{': begin if (cur_pos < aFormat.Length-1) and (aFormat[cur_pos+1] = '{') then begin inc(cur_pos); // '{{' case end else RaiseError('format error'); end; '}': begin if (cur_pos < aFormat.Length-1) and (aFormat[cur_pos+1] = '}') then begin inc(cur_pos); //`}}` case end else begin break; end; end; end; sb1.Append(aFormat[cur_pos]); inc(cur_pos); end; dec(cur_pos); {$HINT 'string.Format: custom format aren''t supported yet'} RaiseError('string.Format: custom format aren''t supported yet'); end; if aFormat[cur_pos] <> '}' then RaiseError('format error'); var arg_format := aArguments[n].ToString; var t := width - arg_format.Length; if not sign and (t>0) then sb.Append(' ',t); sb.Append(arg_format); if sign and (t>0) then sb.Append(' ',t); old_pos := cur_pos+1; end; '}': begin if (cur_pos < aFormat.Length-1) and (aFormat[cur_pos+1] = '}') then begin sb.Append(aFormat, old_pos, cur_pos - old_pos+1); old_pos := cur_pos+1; inc(cur_pos,2); continue; end else begin RaiseError('format error'); end; end; end; inc(cur_pos); end; exit sb.ToString; end; /*constructor String(aArray: array of Char); begin constructor(if aArray = nil then nil else @aArray[0], if aArray = nil then nil else aArray.Length); end;*/ class method String.FromCharArray(aArray: array of Char): String; begin if aArray = nil then exit FromPChar(nil,0) else exit FromPChar(@aArray[0], aArray.Length); end; class method String.Join(Separator: String; Value: array of String): String; begin if Value = nil then raise new ArgumentNullException('Value is nil.'); exit String.Join(Separator, Value, 0, length(Value)); end; class method String.Join(Separator: String; Value: array of String; StartIndex: Integer; Count: Integer): String; begin if Value = nil then raise new ArgumentNullException('Value is nil.'); if StartIndex < 0 then raise new ArgumentOutOfRangeException('StartIndex is less than 0.'); if Count < 0 then raise new ArgumentOutOfRangeException('Count is less than 0.'); if StartIndex + Count > length(Value) then raise new ArgumentOutOfRangeException('StartIndex plus Count is greater than the number of elements in Value.'); if String.IsNullOrEmpty(Separator) then Separator := ''; var str:= new StringBuilder; var len := Length(Value); if len > StartIndex then str.Append(Value[StartIndex]); for i: Integer := StartIndex+1 to StartIndex+Count-1 do begin str.Append(Separator); str.Append(Value[i]); end; exit str.ToString; end; class method String.Join(Separator: String; Value: array of Object): String; begin if Value = nil then raise new ArgumentNullException('Value is nil.'); if String.IsNullOrEmpty(Separator) then Separator := ''; var str:= new StringBuilder; var len := Length(Value); if len >0 then str.Append(Value[0].ToString); for i: Integer := 1 to len-1 do begin str.Append(Separator); str.Append(Value[i].ToString); end; exit str.ToString; end; class method String.Join(Separator: String; Value: IEnumerable<String>): String; begin if Value = nil then raise new ArgumentNullException('Value is nil.'); if String.IsNullOrEmpty(Separator) then Separator := ''; var str:= new StringBuilder; var lenum := Value.GetEnumerator; if lenum.MoveNext then str.Append(lenum.Current); while lenum.MoveNext do begin str.Append(Separator); str.Append(lenum.Current); end; exit str.ToString; end; class method String.Join<T>(Separator: String; Value: IEnumerable<T>): String; begin if Value = nil then raise new ArgumentNullException('Value is nil.'); if String.IsNullOrEmpty(Separator) then Separator := ''; var str:= new StringBuilder; var lenum := Value.GetEnumerator; if lenum.MoveNext then str.Append(lenum.Current.ToString); while lenum.MoveNext do begin str.Append(Separator); str.Append(lenum.Current.ToString); end; exit str.ToString; end; { String_Constructors } constructor String_Constructors(aArray: array of Char); begin result := String.FromCharArray(aArray); end; constructor String_Constructors(c: ^Char; aCharCount: Integer); begin result := String.FromPChar(c, aCharCount); end; constructor String_Constructors(c: ^Char); begin result := String.FromPChar(c); end; constructor String_Constructors(c: Char; aCharCount: Integer); begin result := String.FromRepeatedChar(c, aCharCount); end; constructor String_Constructors(c: Char); begin result := String.FromChar(c); end; constructor String_Constructors(c: ^AnsiChar; aCharCount: Integer); begin result := String.FromPAnsiChars(c, aCharCount); end; constructor String_Constructors(c: ^AnsiChar); begin result := String.FromPAnsiChars(c); end; end.
{ ************************************************************** Package: XWB - Kernel RPCBroker Date Created: Sept 18, 1997 (Version 1.1) Site Name: Oakland, OI Field Office, Dept of Veteran Affairs Developers: Danila Manapsal, Don Craven, Joel Ivey Description: Contains TRPCBroker and related components. Unit: RpcbErr error handling for TRPC Broker. Current Release: Version 1.1 Patch 65 *************************************************************** } { ************************************************** Changes in v1.1.65 (HGW 06/23/2016) XWB*1.1*65 1. Added error XWB_BadToken for SSOi testing. Changes in v1.1.60 (HGW 12/18/2013) XWB*1.1*60 1. None. Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50 1. None. ************************************************** } unit RpcbErr; interface uses {System} Classes, SysUtils, {WinApi} Winsock2, WinProcs, {VA} Trpcb, {Vcl} Forms, Controls, StdCtrls, Buttons, ExtCtrls, Graphics; type TfrmRpcbError = class(TForm) BitBtn1: TBitBtn; BitBtn3: TBitBtn; Label1: TLabel; Bevel1: TBevel; Symbol: TImage; Label2: TLabel; Label3: TLabel; lblAction: TLabel; lblCode: TLabel; lblMessage: TLabel; procedure FormCreate(Sender: TObject); end; var frmRpcbError: TfrmRpcbError; procedure ShowBrokerError(BrokerError: EBrokerError); procedure NetError(Action: string; ErrType: integer); const XWBBASEERR = {WSABASEERR + 1} 20000; {Broker Application Error Constants} XWB_NO_HEAP = XWBBASEERR + 1; XWB_M_REJECT = XWBBASEERR + 2; XWB_BadSignOn = XWBBASEERR + 4; XWB_BldConnectList = XWBBASEERR + 5; XWB_NullRpcVer = XWBBASEERR + 6; XWB_BadToken = XWBBASEERR + 7; XWB_ExeNoMem = XWBBASEERR + 100; XWB_ExeNoFile = XWB_ExeNoMem + 2; XWB_ExeNoPath = XWB_ExeNoMem + 3; XWB_ExeShare = XWB_ExeNoMem + 5; XWB_ExeSepSeg = XWB_ExeNoMem + 6; XWB_ExeLoMem = XWB_ExeNoMem + 8; XWB_ExeWinVer = XWB_ExeNoMem + 10; XWB_ExeBadExe = XWB_ExeNoMem + 11; XWB_ExeDifOS = XWB_ExeNoMem + 12; XWB_RpcNotReg = XWBBASEERR + 201; implementation uses {VA} Wsockc; {$R *.DFM} procedure ShowBrokerError(BrokerError: EBrokerError); begin try Application.CreateForm(TfrmRpcbError, frmRpcbError); with frmRpcbError do begin lblAction.Caption := BrokerError.Action; lblCode.Caption := IntToStr(BrokerError.Code); lblMessage.Caption := BrokerError.Mnemonic; ShowModal; end finally frmRpcbError.Release; end; end; procedure TfrmRpcbError.FormCreate(Sender: TObject); var FIcon: TIcon; begin FIcon := TIcon.Create; try FIcon.Handle := LoadIcon(0, IDI_HAND); Symbol.Picture.Graphic := FIcon; Symbol.BoundsRect := Bounds(Symbol.Left, Symbol.Top, FIcon.Width, FIcon.Height); finally FIcon.Free; end; end; //Can this be redone to use the procedure TXWBWinsock.NetError in Wsockc.pas and remove redundant code? procedure NetError(Action : String; ErrType: integer); var x,s: string; r: integer; BrokerError: EBrokerError; begin Screen.Cursor := crDefault; r := 0; if ErrType > 0 then r := ErrType; if ErrType = 0 then begin r := WSAGetLastError; // if r = WSAEINTR then xFlush := True; // if WSAIsBlocking = True then WSACancelBlockingCall; end; Case r of WSAEINTR : x := 'WSAEINTR'; WSAEBADF : x := 'WSAEINTR'; WSAEFAULT : x := 'WSAEFAULT'; WSAEINVAL : x := 'WSAEINVAL'; WSAEMFILE : x := 'WSAEMFILE'; WSAEWOULDBLOCK : x := 'WSAEWOULDBLOCK'; WSAEINPROGRESS : x := 'WSAEINPROGRESS'; WSAEALREADY : x := 'WSAEALREADY'; WSAENOTSOCK : x := 'WSAENOTSOCK'; WSAEDESTADDRREQ : x := 'WSAEDESTADDRREQ'; WSAEMSGSIZE : x := 'WSAEMSGSIZE'; WSAEPROTOTYPE : x := 'WSAEPROTOTYPE'; WSAENOPROTOOPT : x := 'WSAENOPROTOOPT'; WSAEPROTONOSUPPORT : x := 'WSAEPROTONOSUPPORT'; WSAESOCKTNOSUPPORT : x := 'WSAESOCKTNOSUPPORT'; WSAEOPNOTSUPP : x := 'WSAEOPNOTSUPP'; WSAEPFNOSUPPORT : x := 'WSAEPFNOSUPPORT'; WSAEAFNOSUPPORT : x := 'WSAEAFNOSUPPORT'; WSAEADDRINUSE : x := 'WSAEADDRINUSE'; WSAEADDRNOTAVAIL : x := 'WSAEADDRNOTAVAIL'; WSAENETDOWN : x := 'WSAENETDOWN'; WSAENETUNREACH : x := 'WSAENETUNREACH'; WSAENETRESET : x := 'WSAENETRESET'; WSAECONNABORTED : x := 'WSAECONNABORTED'; WSAECONNRESET : x := 'WSAECONNRESET'; WSAENOBUFS : x := 'WSAENOBUFS'; WSAEISCONN : x := 'WSAEISCONN'; WSAENOTCONN : x := 'WSAENOTCONN'; WSAESHUTDOWN : x := 'WSAESHUTDOWN'; WSAETOOMANYREFS : x := 'WSAETOOMANYREFS'; WSAETIMEDOUT : x := 'WSAETIMEDOUT'; WSAECONNREFUSED : x := 'WSAECONNREFUSED'; WSAELOOP : x := 'WSAELOOP'; WSAENAMETOOLONG : x := 'WSAENAMETOOLONG'; WSAEHOSTDOWN : x := 'WSAEHOSTDOWN'; WSAEHOSTUNREACH : x := 'WSAEHOSTUNREACH'; WSAENOTEMPTY : x := 'WSAENOTEMPTY'; WSAEPROCLIM : x := 'WSAEPROCLIM'; WSAEUSERS : x := 'WSAEUSERS'; WSAEDQUOT : x := 'WSAEDQUOT'; WSAESTALE : x := 'WSAESTALE'; WSAEREMOTE : x := 'WSAEREMOTE'; WSASYSNOTREADY : x := 'WSASYSNOTREADY'; WSAVERNOTSUPPORTED : x := 'WSAVERNOTSUPPORTED'; WSANOTINITIALISED : x := 'WSANOTINITIALISED'; WSAHOST_NOT_FOUND : x := 'WSAHOST_NOT_FOUND'; WSATRY_AGAIN : x := 'WSATRY_AGAIN'; WSANO_RECOVERY : x := 'WSANO_RECOVERY'; WSANO_DATA : x := 'WSANO_DATA'; XWB_NO_HEAP : x := 'Insufficient Heap'; XWB_M_REJECT : x := 'M Error - Use ^XTER'; XWB_BadSignOn : x := 'Sign-on was not completed.'; XWB_ExeNoMem : x := 'System was out of memory, executable file was corrupt, or relocations were invalid.'; XWB_ExeNoFile : x := 'File was not found.'; XWB_ExeNoPath : x := 'Path was not found.'; XWB_ExeShare : x := 'Attempt was made to dynamically link to a task,' + ' or there was a sharing or network-protection error.'; XWB_ExeSepSeg : x := 'Library required separate data segments for each task.'; XWB_ExeLoMem : x := 'There was insufficient memory to start the application.'; XWB_ExeWinVer : x := 'Windows version was incorrect.'; XWB_ExeBadExe : x := 'Executable file was invalid.' + ' Either it was not a Windows application or there was an error in the .EXE image.'; XWB_ExeDifOS : x := 'Application was designed for a different operating system.'; XWB_RpcNotReg : X := 'Remote procedure not registered to application.'; XWB_BldConnectList : x := 'BrokerConnections list could not be created'; XWB_NullRpcVer : x := 'RpcVersion cannot be empty.' + #13 + 'Default is 0 (zero).'; XWB_BadToken : x := 'Could not log on using STS token.'; else x := IntToStr(r); end; s := 'Error encountered.' + chr(13)+chr(10) + 'Function was: ' + Action + chr(13)+chr(10) + 'Error was: ' + x; BrokerError := EBrokerError.Create(s); BrokerError.Action := Action; BrokerError.Code := r; BrokerError.Mnemonic := x; raise BrokerError; end; end.
unit sanPersistence; { Abstract persistent object classes v. 0.01 (c) 2002 Andrey V. Sorokin St-Petersburg, Russia anso@mail.ru, anso@paycash.ru http://anso.virtualave.net } interface type TsanOID = integer; TsanClassID = byte; TsanObject = class; isanObject = interface; TsanObjectStorage = class protected function GetObject (AID : TsanOID) : isanObject; virtual; ABSTRACT; public function AddObject (AObject : isanObject; AObjectClass : TsanClassID = 0) : TsanOID; virtual; ABSTRACT; procedure DeleteObject (AID : TsanOID); virtual; ABSTRACT; property Objects [AID : TsanOID] : isanObject read GetObject; DEFAULT; // returns object by object ID end; isanObject = interface (IUnknown) procedure Modify; // Start modification. end; TsanObject = class (TObject, isanObject) protected fTieCount: Integer; fStorage : TsanObjectStorage; fID : TsanOID; private function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create (AStorage : TsanObjectStorage; AID : TsanOID); virtual; destructor Destroy; override; procedure AfterConstruction; override; procedure BeforeDestruction; override; class function NewInstance: TObject; override; property TieCount: Integer read fTieCount; procedure Modify; end; implementation uses Windows, SysUtils, Forms; {============================================================} {====================== TabObject ===========================} constructor TsanObject.Create (AStorage : TsanObjectStorage; AID : TsanOID); begin inherited Create; fStorage := AStorage; fID := AID; end; { of constructor TsanObject.Create --------------------------------------------------------------} destructor TsanObject.Destroy; begin inherited; end; { of destructor TsanObject.Destroy --------------------------------------------------------------} procedure TsanObject.AfterConstruction; begin // Release the constructor's implicit refcount InterlockedDecrement (fTieCount); end; { of procedure TsanObject.AfterConstruction --------------------------------------------------------------} procedure TsanObject.BeforeDestruction; begin if TieCount <> 0 then raise Exception.Create ('Destruction of untied TsanObject'); end; { of procedure TsanObject.BeforeDestruction --------------------------------------------------------------} // Set an implicit refcount so that tiecounting // during construction won't destroy the object. class function TsanObject.NewInstance: TObject; begin Result := inherited NewInstance; TsanObject (Result).fTieCount := 1; end; { of function TsanObject.NewInstance --------------------------------------------------------------} function TsanObject.QueryInterface (const IID: TGUID; out Obj): HResult; const E_NOINTERFACE = HResult($80004002); begin if GetInterface (IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; { of function TsanObject.QueryInterface --------------------------------------------------------------} function TsanObject._AddRef: Integer; begin Result := InterlockedIncrement (fTieCount); end; { of function TsanObject._AddRef --------------------------------------------------------------} function TsanObject._Release: Integer; begin Result := InterlockedDecrement (fTieCount); if Result = 0 then Application.MessageBox ('', 'TsanObject.TieCount=0', 0); // then Destroy; end; { of function TsanObject._Release --------------------------------------------------------------} (* Collection is_emty, is_ordered, allows_duplicates contains_element (e) insert_element (e) remove_element (e) remove_all create_iterator begin, end - spec.iterators select_element (OQL) : e select (OQL) : e query (Collection, OQL) : errcode Collection-List retrive_first_element retrive_last_element retrive_element_at (pos) == op[] find_element (e, var pos) : bool remove_element_at replace_element_at insert_element (to end) insert_element_first insert_element_last insert_element_after (e, pos) insert_element_before (e, pos) concat Iterator reset (first) advance, not_done, get_element next (element) : bool - while next (e) do with e op * *) end.
unit Utils; interface uses System.Types; type IStrArrayIterator = interface ['{BDDEE013-5FD0-4049-8F96-23F3FAA2F175}'] function Next(var Line: string): Boolean; end; function BuildStrArrayIteratorNonEmptyLines(Arr: TStringDynArray): IStrArrayIterator; procedure SaveStrToFile(const FilePath, Content: string); implementation uses System.SysUtils, System.Classes; procedure SaveStrToFile(const FilePath, Content: string); var ss: TStringStream; begin ss := TStringStream.Create; try ss.WriteString(Content); ss.SaveToFile(FilePath); finally ss.Free; end; end; { TStrArrayIterator } type TStrArrayIteratorNonEmptyLines = class(TInterfacedObject, IStrArrayIterator) private FArr: TStringDynArray; Idx: Integer; public constructor Create(Arr: TStringDynArray); function Next(var Line: string): Boolean; end; constructor TStrArrayIteratorNonEmptyLines.Create(Arr: TStringDynArray); begin inherited Create; FArr := Arr; Idx := 0; end; function TStrArrayIteratorNonEmptyLines.Next(var Line: string): Boolean; begin while Idx < Length(FArr) do begin Line := Trim(FArr[Idx]); Inc(Idx); if Line.Length > 0 then Exit(True); end; Result := Idx < Length(FArr); end; function BuildStrArrayIteratorNonEmptyLines(Arr: TStringDynArray): IStrArrayIterator; begin Result := TStrArrayIteratorNonEmptyLines.Create(Arr); end; end.
unit uStackForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Grids, Menus, uResourceStrings, uProcessor, uView, Buttons, StdCtrls, uEditForm, Registry, uMisc; type TStackPointerUpdateRequestEvent = procedure(Value: Byte) of object; TStackUpdateRequestEvent = procedure(Index: Byte; Value: Word) of object; TStackForm = class(TForm, IStack, ILanguage, IRadixView, IRegistry) PopupMenu: TPopupMenu; miClose: TMenuItem; N1: TMenuItem; miStayOnTop: TMenuItem; iStackPointer: TImage; sgStack: TStringGrid; procedure miCloseClick(Sender: TObject); procedure miStayOnTopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure sgStackDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure sgStackDblClick(Sender: TObject); procedure sgStackSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgStackKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private _StackPointer: Integer; _ARow: Integer; _ACol: Integer; _Radix: TRadix; _View: TView; _OnSPUpdateRequest: TStackPointerUpdateRequestEvent; _OnStackUpdateRequest: TStackUpdateRequestEvent; procedure RefreshObject(Sender: TObject); procedure Reset(Sender: TObject); procedure SPChanged(Sender: TObject; SP: Byte); procedure Change(Sender: TObject; Index: Byte; Value: Word); procedure Push(Sender: TObject; Index: Byte; Value: Word); procedure Pop(Sender: TObject; Index: Byte; Value: Word); procedure LoadData(RegistryList: TRegistryList); procedure SaveData(RegistryList: TRegistryList); public procedure LoadLanguage; procedure RadixChange(Radix: TRadix; View: TView); property OnStackPointerUpdateRequest: TStackPointerUpdateRequestEvent read _OnSPUpdateRequest write _OnSPUpdateRequest; property OnStackUpdateRequest: TStackUpdateRequestEvent read _OnStackUpdateRequest write _OnStackUpdateRequest; end; var StackForm: TStackForm; implementation {$R *.dfm} procedure TStackForm.FormCreate(Sender: TObject); var i: Integer; begin _ARow:= 0; _ACol:= 0; _StackPointer:= -1; _Radix:= rOctal; _View:= vShort; sgStack.ColCount:= 3; sgStack.RowCount:= Ti8008Stack.Size+1; for i:= 1 to sgStack.RowCount do sgStack.Cells[0,i]:= IntToStr(i-1); sgStack.ColWidths[0]:= 50; sgStack.ColWidths[1]:= 100; sgStack.ColWidths[2]:= 24; sgStack.Width:= 174; sgStack.Height:= sgStack.RowHeights[0] * (sgStack.RowCount + 1); sgStack.Canvas.CopyMode:= cmMergeCopy; AutoSize:= true; LoadLanguage; end; procedure TStackForm.miCloseClick(Sender: TObject); begin Close; end; procedure TStackForm.miStayOnTopClick(Sender: TObject); begin if miStayOnTop.Checked then FormStyle:= fsNormal else FormStyle:= fsStayOnTop; miStayOnTop.Checked:= not miStayOnTop.Checked; end; procedure TStackForm.sgStackDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (ARow = 0) or (ACol = 0) then sgStack.Canvas.Brush.Color:= sgStack.FixedColor else sgStack.Canvas.Brush.Color:= sgStack.Color; sgStack.Canvas.FillRect(Rect); if ACol < 2 then begin Rect.Top:= Rect.Top + ((sgStack.RowHeights[ARow] - sgStack.Canvas.TextHeight(sgStack.Cells[ACol,ARow]))) div 2; if ARow = 0 then Rect.Left:= Rect.Left + (sgStack.ColWidths[ACol] - sgStack.Canvas.TextWidth(sgStack.Cells[ACol,ARow])) div 2 else Rect.Left:= Rect.Right - 4 - sgStack.Canvas.TextWidth(sgStack.Cells[ACol,ARow]); sgStack.Canvas.TextOut(Rect.Left,Rect.Top,sgStack.Cells[ACol,ARow]); end else if (ARow-1) = _StackPointer then sgStack.Canvas.CopyRect(Rect,iStackPointer.Canvas,Bounds(0,0,24,24)); end; procedure TStackForm.sgStackSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin _ARow:= ARow; _ACol:= ACol; end; procedure TStackForm.sgStackDblClick(Sender: TObject); var C: Boolean; P: TPoint; begin if _ARow > 0 then case _ACol of 1: begin P.X:= Mouse.CursorPos.X; P.Y:= Mouse.CursorPos.Y; EditForm.Value:= RadixToWord(sgStack.Cells[_ACol,_ARow],_Radix,_View,C); if (EditForm.ShowModal(_Radix,_View,14,P) = mrOk) and Assigned(OnStackUpdateRequest) then OnStackUpdateRequest(_ARow-1,EditForm.Value); end; 2: if Assigned(OnStackPointerUpdateRequest) then OnStackPointerUpdateRequest(_ARow-1); end; end; procedure TStackForm.sgStackKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then sgStackDblClick(Sender); end; procedure TStackForm.RefreshObject(Sender: TObject); var i: Integer; begin if Sender is Ti8008Stack then begin _StackPointer:= (Sender as Ti8008Stack).StackPointer; for i:= 1 to sgStack.RowCount do sgStack.Cells[1,i]:= WordToRadix((Sender as Ti8008Stack).Items[i-1],_Radix,_View,14); end; end; procedure TStackForm.Reset(Sender: TObject); var i: Integer; begin if Sender is Ti8008Stack then begin _StackPointer:= (Sender as Ti8008Stack).StackPointer; for i:= 1 to sgStack.RowCount do sgStack.Cells[1,i]:= WordToRadix((Sender as Ti8008Stack).Items[i-1],_Radix,_View,14); end; end; procedure TStackForm.SPChanged(Sender: TObject; SP: Byte); begin _StackPointer:= SP; sgStack.Invalidate; end; procedure TStackForm.Change(Sender: TObject; Index: Byte; Value: Word); begin sgStack.Cells[1,Index+1]:= WordToRadix(Value,_Radix,_View,14); end; procedure TStackForm.Push(Sender: TObject; Index: Byte; Value: Word); begin sgStack.Cells[1,Index+1]:= WordToRadix(Value,_Radix,_View,14); end; procedure TStackForm.Pop(Sender: TObject; Index: Byte; Value: Word); begin sgStack.Cells[1,Index+1]:= WordToRadix(Value,_Radix,_View,14); end; procedure TStackForm.LoadData(RegistryList: TRegistryList); begin if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,false) then RegistryList.LoadFormSettings(Self,false); end; procedure TStackForm.SaveData(RegistryList: TRegistryList); begin if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then RegistryList.SaveFormSettings(Self,false); end; procedure TStackForm.LoadLanguage; begin sgStack.Cells[0,0]:= getString(rsAddress); sgStack.Cells[1,0]:= getString(rsValue); miClose.Caption:= getString(rsClose); miStayOnTop.Caption:= getString(rsStayOnTop); end; procedure TStackForm.RadixChange(Radix: TRadix; View: TView); begin if Radix = rDecimalNeg then Radix:= rDecimal; _Radix:= Radix; _View:= View; end; end.
unit uZipUtils; interface uses Windows, Classes, Messages, SysUtils, JclCompression; function ExtractZip(aZip, aDir:string; const progressEvt: TJclCompressionProgressEvent=nil):boolean; function ExtractZipPath (aZip:string):string; implementation uses uCommonProc, uPrintException; function ExtractZip(aZip, aDir:string; const progressEvt: TJclCompressionProgressEvent=nil):boolean; var AFormat: TJclDecompressArchiveClass; FArchive: TJclCompressionArchive; begin result := false; try AFormat := GetArchiveFormats.FindDecompressFormat(aZip); if AFormat <> nil then begin FArchive := AFormat.Create(aZip, 0); FArchive.OnProgress := progressEvt; if FArchive is TJclDecompressArchive then begin TJclDecompressArchive(FArchive).ListFiles; ForceDirectories(aDir); TJclDecompressArchive(FArchive).ExtractAll(aDir, True); result := true; end; FArchive.free; end; except raise eNexUnzipError.create(aZip); end; end; function ExtractZipPath (aZip:string):string; var AFormat: TJclDecompressArchiveClass; FArchive: TJclCompressionArchive; begin result := ''; try AFormat := GetArchiveFormats.FindDecompressFormat(aZip); if AFormat <> nil then begin FArchive := AFormat.Create(aZip, 0); if FArchive is TJclDecompressArchive then with TJclDecompressArchive(FArchive) do begin ListFiles; if ItemCount>0 then result := NormalizarFilePath(TJclDecompressArchive(FArchive).Items[0].PackedName); end; FArchive.free; end; except raise eNexUnzipError.create(aZip); end; end; end.
unit UnPetiscoDashboardView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvExExtCtrls, JvExtComponent, JvPanel, ExtCtrls, ToolWin, JvExForms, JvScrollPanel, DateUtils, JvExControls, JvButton, JvTransparentButton, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, StdCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvCheckedMaskEdit, JvDatePickerEdit, ImgList, TeEngine, Series, TeeProcs, Chart, DB, { helsonsant } Util, DataUtil, UnFabricaDeModelos, UnFabricaDeAplicacoes, Componentes, Configuracoes, UnAplicacao, SearchUtil, UnPetiscoDashBoardModelo, ContasPagarAplicacao, VclTee.TeeGDIPlus, System.ImageList, Vcl.ComCtrls; type TPetiscoDashBoardView = class(TForm, IResposta) pnlTitulo: TPanel; pnlFundo: TPanel; pnlDesktop: TJvPanel; Splitter1: TSplitter; btnFecharAplicacao: TJvTransparentButton; pnlResumo: TPanel; Panel1: TPanel; gContasPagar: TJvDBUltimGrid; Panel2: TPanel; Splitter2: TSplitter; lblDia: TLabel; lblDataCompleta: TLabel; pnlFiltroData: TPanel; GroupBox1: TGroupBox; txtDataInicial: TJvDatePickerEdit; GroupBox2: TGroupBox; txtDataFinal: TJvDatePickerEdit; Images: TImageList; Chart: TChart; GroupBox3: TGroupBox; lblTOTAL: TLabel; Serie: TBarSeries; pnlResultado: TPanel; Label1: TLabel; Shape1: TShape; Shape2: TShape; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; lblReceitasValor: TLabel; lblImpostosValor: TLabel; lblDespesasFixaValor: TLabel; lblDespesasVariaveisValor: TLabel; lblResultadoFinalValor: TLabel; procedure FormCreate(Sender: TObject); procedure btnFecharAplicacaoClick(Sender: TObject); procedure txtDataInicialChange(Sender: TObject); procedure gContasPagarDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure txtDataFinalChange(Sender: TObject); procedure gContasPagarDblClick(Sender: TObject); private FConfiguracoes: TConfiguracoes; FDataUtil: TDataUtil; FFabricaDeAplicacoes: TFabricaDeAplicacoes; FFabricaDeModelos: TFabricaDeModelos; FModelo: TPetiscoDashBoardModelo; FUtil: TUtil; protected procedure CarregarRegumoExecutivo; procedure MontarPainelDeAplicacoes; public function Preparar: TPetiscoDashBoardView; procedure Responder(const Chamada: TChamada); published procedure ProcessarSelecaoDeAplicacao(Sender: TObject); end; var PetiscoDashBoardView: TPetiscoDashBoardView; implementation {$R *.dfm} { TPetiscoDashBoardView } function TPetiscoDashBoardView.Preparar: TPetiscoDashBoardView; begin Self.FUtil := TUtil.Create; Self.FDataUtil := TDataUtil.Create; Self.FConfiguracoes := TConfiguracoes.Create('.\system\setup.sys'); Self.FModelo := TPetiscoDashBoardModelo.Create(nil); Self.FDataUtil.GetOIDGenerator(Self.FModelo.SqlProcessor); Self.FFabricaDeModelos := TFabricaDeModelos.Create(Self.FModelo.cnn) .Util(Self.FUtil) .DataUtil(Self.FDataUtil) .Configuracoes(Self.FConfiguracoes) .Preparar; Self.FFabricaDeAplicacoes := TFabricaDeAplicacoes.Create .FabricaDeModelos(Self.FFabricaDeModelos) .Util(Self.FUtil) .DataUtil(Self.FDataUtil) .Configuracoes(Self.FConfiguracoes) .Preparar; TConstrutorDePesquisas.FabricaDeModelos(Self.FFabricaDeModelos); Self.lblDia.Caption := IntToStr(DayOfTheMonth(Date)); Self.lblDataCompleta.Caption := FormatDateTime('dd "de" mmmm "de" yyyy.', Date); Self.txtDataInicial.Date := Date - 7; Self.txtDataFinal.Date := Date + 7; Self.MontarPainelDeAplicacoes; Self.CarregarRegumoExecutivo; Result := Self; end; procedure TPetiscoDashBoardView.FormCreate(Sender: TObject); begin Self.BorderStyle := bsNone; Self.Preparar; end; procedure TPetiscoDashBoardView.ProcessarSelecaoDeAplicacao( Sender: TObject); var _aplicacao: TAplicacao; begin _aplicacao := Self.FFabricaDeAplicacoes.ObterAplicacao( (Sender as TComponent).Name); try _aplicacao .Controlador(Self) .AtivarAplicacao; finally _aplicacao.Descarregar; end; end; procedure TPetiscoDashBoardView.Responder(const Chamada: TChamada); var _aplicacao: TAplicacao; begin _aplicacao := Self.FFabricaDeAplicacoes.ObterAplicacao('FechamentoDeConta'); try _aplicacao.AtivarAplicacao(Chamada); finally _aplicacao.Descarregar; end; end; procedure TPetiscoDashBoardView.MontarPainelDeAplicacoes; begin TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('Cliente') .Legenda('Clientes') .Dica('Acesso ao cadastro dos clientes') .Container(Self.pnlDesktop) .Cor(AMARELO) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('Produto') .Legenda('Produtos') .Dica('Acesso ao cadastro dos produtos') .Container(Self.pnlDesktop) .Cor(VERDE) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('MovimentoDeCaixa') .Legenda('Caixa') .Dica('Controle de caixa') .Container(Self.pnlDesktop) .Cor(ROSA) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('ContasPagar') .Legenda('Contas ' + #13 + ' a ' + #13 + 'Pagar') .Dica('Acesso ao controle de contas a pagar') .Container(Self.pnlDesktop) .Cor(AZUL) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('ContasReceber') .Legenda('Contas ' + #13 + ' a ' + #13 + 'Receber') .Dica('Acesso ao controle de contas a receber') .Container(Self.pnlDesktop) .Cor(VERDE) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('ContaCorrente') .Legenda('Contas Correntes') .Dica('Acesso ao cadastro de contas correntes') .Container(Self.pnlDesktop) .Cor(TEAL) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('MovimentoDeContaCorrente') .Legenda('Movimentos de Conta Corrente') .Dica('Acesso aos registros de movimentos de contas correntes') .Container(Self.pnlDesktop) .Cor(VERMELHO) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('Relatorio') .Legenda('Relatórios') .Dica('Acesso aos relatórios gerenciais do sistema') .Container(Self.pnlDesktop) .Cor(AMARELO) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('Usuario') .Legenda('Usuários') .Dica('Acesso ao controle de usuários e senhas de acesso ao sistema') .Container(Self.pnlDesktop) .Cor(ROSA) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('Fornecedor') .Legenda('Fornecedores') .Dica('Acesso ao controle de fornecedores') .Container(Self.pnlDesktop) .Cor(TEAL) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('CentroDeResultado') .Legenda('Centros de Resultado') .Dica('Acesso ao cadastro de centros de resultado') .Container(Self.pnlDesktop) .Cor(AZUL) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; TAplicacaoBloco.Create(Self.pnlDesktop) .Aplicacao('Categoria') .Legenda('Categorias de Movimentação Financeira') .Dica('Acesso ao cadastro das categorias utilizadas para classificar as ' + 'movimentações financeiras') .Container(Self.pnlDesktop) .Cor(AMARELO) .AoSelecionarAplicacao(Self.ProcessarSelecaoDeAplicacao) .Preparar; end; procedure TPetiscoDashBoardView.btnFecharAplicacaoClick(Sender: TObject); begin if TMessages.Confirma('Sair da aplicação') then Self.Close; end; procedure TPetiscoDashBoardView.CarregarRegumoExecutivo; var _valorMaximo, _resultado: Real; _dataSet: TDataSet; begin Self.FModelo.CarregarContasPagar(Self.txtDataInicial.Date, Self.txtDataFinal.Date); Self.gContasPagar.DataSource := Self.FModelo.dsr; if Self.FModelo.cds.FieldByName('TOTAL').AsString <> '' then Self.lblTOTAL.Caption := FormatFloat('R$ #,##0.00', StrToFloat(Self.FModelo.cds.FieldByName('TOTAL').AsString)) else Self.lblTOTAL.Caption := '0,00'; _valorMaximo := 0; _dataSet := Self.FModelo.SqlProcessor; Serie.Clear; _dataSet.First; while not _dataSet.Eof do begin if _dataSet.FieldByName('TOTAL').AsFloat > _valorMaximo then _valorMaximo := _dataSet.FieldByName('TOTAL').AsFloat; Serie.Add(_dataSet.FieldByName('TOTAL').AsFloat, FormatDateTime('dd"/"mmm', _dataSet.FieldByName('TIT_VENC').AsDateTime)); _dataSet.Next; end; Serie.GetVertAxis.SetMinMax(0, _valorMaximo * 1.25); Self.FModelo.CarregarResultado(Self.txtDataInicial.Date, Self.txtDataFinal.Date); _dataSet := Self.FModelo.cds_resultado; Self.lblReceitasValor.Caption := FormatFloat('R$ #,##0.00', _dataSet.FieldByName('RECEITAS').AsCurrency); Self.lblImpostosValor.Caption := FormatFloat('R$ #,##0.00', _dataSet.FieldByName('IMPOSTOS').AsCurrency); Self.lblDespesasFixaValor.Caption := FormatFloat('R$ #,##0.00', _dataSet.FieldByName('DESPESAS_FIXAS').AsCurrency); Self.lblDespesasVariaveisValor.Caption := FormatFloat('R$ #,##0.00', _dataSet.FieldByName('DESPESAS_VARIAVEIS').AsCurrency); _resultado := _dataSet.FieldByName('RECEITAS').AsCurrency - _dataSet.FieldByName('IMPOSTOS').AsCurrency - _dataSet.FieldByName('DESPESAS_FIXAS').AsCurrency - _dataSet.FieldByName('DESPESAS_VARIAVEIS').AsCurrency; Self.lblResultadoFinalValor.Caption := FormatFloat('R$ #,##0.00', _resultado); if _resultado >= 0 then Self.lblResultadoFinalValor.Font.Color := clNavy else Self.lblResultadoFinalValor.Font.Color := clMaroon; end; procedure TPetiscoDashBoardView.txtDataInicialChange(Sender: TObject); begin Self.CarregarRegumoExecutivo; end; procedure TPetiscoDashBoardView.gContasPagarDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var _indice: Integer; _grid: TDBGrid; _dataSet: TDataSet; begin inherited; _grid := (Sender as TDBGrid); _dataSet := _grid.DataSource.DataSet; if (Column.Index > 0) then _grid.DefaultDrawColumnCell(Rect, DataCol, Column, State) else begin if _dataSet.FieldByName('TIT_VENC').AsDatetime < Date then _indice := 2 else if _dataSet.FieldByName('TIT_VENC').AsDatetime < (Date + 7) then _indice := 1 else _indice := 0; _grid.Canvas.FillRect(Rect); Self.Images.Draw(_grid.Canvas,Rect.Left + 1, Rect.Top + 1, _indice); end; end; procedure TPetiscoDashBoardView.txtDataFinalChange(Sender: TObject); begin Self.CarregarRegumoExecutivo; end; procedure TPetiscoDashBoardView.gContasPagarDblClick(Sender: TObject); var _aplicacao: TContasPagarAplicacao; _chamada: TChamada; begin _aplicacao := (Self.FFabricaDeAplicacoes.ObterAplicacao('ContasPagar') as TContasPagarAplicacao); _chamada := TChamada.Create .Chamador(Self) .Parametros(TMap.Create .Gravar('acao', Ord(adrCarregar)) .Gravar('oid', Self.gContasPagar.DataSource.DataSet.FieldByName('tit_oid').AsString) ); _aplicacao.Responder(_chamada); Self.CarregarRegumoExecutivo; end; end.
Unit WlanBssEntry; Interface Uses Windows, WlanNetwork, WlanAPI; Type TWlanBssEntry = Class Private FSSID : WideString; FMacAddress : DOT11_MAC_ADDRESS; FBssType : TWlanNetworkBssType; FLinkQuality : ULONG; FFrequency : ULONG; Public Class Function NewInstance(ARecord:PWLAN_BSS_ENTRY):TWlanBssEntry; Class Function MACToSTr(AMAC:DOT11_MAC_ADDRESS):WideSTring; Property SSID : WideString Read FSSID; Property MacAddress : DOT11_MAC_ADDRESS Read FMacAddress; Property BssType : TWlanNetworkBssType Read FBssType; Property LinkQuality : ULONG Read FLinkQuality; Property Frequency : ULONG Read FFrequency; end; Implementation Uses SysUtils; Class Function TWlanBssEntry.NewInstance(ARecord:PWLAN_BSS_ENTRY):TWlanBssEntry; begin Try Result := TWlanBssEntry.Create; Except Result := Nil; end; If Assigned(Result) Then begin Result.FSSID := Copy(AnsiString(PAnsiChar(@ARecord.dot11Ssid.ucSSID)), 1, ARecord.dot11Ssid.uSSIDLength); Result.FMacAddress := ARecord.dot11Bssid; Result.FBssType := TWlanNetworkBssType(ARecord.dot11BssType); Result.FLinkQuality := ARecord.uLinkQuality; Result.FFrequency := ARecord.ulChCenterFrequency; end; end; Class Function TWlanBssEntry.MACToSTr(AMAC:DOT11_MAC_ADDRESS):WideSTring; begin Result := IntToHex(AMAC[0], 2) + '-' + IntToHex(AMAC[1], 2) + '-' + IntToHex(AMAC[2], 2) + '-' + IntToHex(AMAC[3], 2) + '-' + IntToHex(AMAC[4], 2) + '-' + IntToHex(AMAC[5], 2); end; End.
unit NtUtils.Objects.Security; interface uses Winapi.WinNt, NtUtils.Exceptions, NtUtils.Security.Acl, NtUtils.Security.Sid; type TAce = NtUtils.Security.Acl.TAce; IAcl = NtUtils.Security.Acl.IAcl; TAcl = NtUtils.Security.Acl.TAcl; ISid = NtUtils.Security.Sid.ISid; { Query security } // Query security descriptor of an object. Free it with FreeMem after use. function NtxQuerySecurityObject(hObject: THandle; SecurityInformation: TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus; // Query owner of an object function NtxQueryOwnerObject(hObject: THandle; out Owner: ISid): TNtxStatus; // Query primary group of an object function NtxQueryPrimaryGroupObject(hObject: THandle; out PrimaryGroup: ISid): TNtxStatus; // Query DACL of an object function NtxQueryDaclObject(hObject: THandle; out Dacl: IAcl): TNtxStatus; // Query SACL of an object function NtxQuerySaclObject(hObject: THandle; out Sacl: IAcl): TNtxStatus; // Query mandatory label of an object function NtxQueryLabelObject(hObject: THandle; out Sacl: IAcl): TNtxStatus; { Set security } // Set security descriptor function NtxSetSecurityObject(hObject: THandle; SecInfo: TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus; // Set owner of an object function NtxSetOwnerObject(hObject: THandle; Owner: ISid): TNtxStatus; // Set primary group of an object function NtxSetPrimaryGroupObject(hObject: THandle; Group: ISid): TNtxStatus; // Set DACL of an object function NtxSetDaclObject(hObject: THandle; Dacl: IAcl): TNtxStatus; // Set SACL of an object function NtxSetSaclObject(hObject: THandle; Sacl: IAcl): TNtxStatus; // Set mandatory label of an object function NtxSetLabelObject(hObject: THandle; Sacl: IAcl): TNtxStatus; implementation uses Ntapi.ntrtl, Ntapi.ntobapi; { Query security functions } // Security sescriptor function NtxQuerySecurityObject(hObject: THandle; SecurityInformation: TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus; var BufferSize, Required: Cardinal; begin Result.Location := 'NtQuerySecurityObject'; Result.LastCall.Expects(RtlxComputeReadAccess(SecurityInformation), @NonSpecificAccessType); BufferSize := 0; repeat SecDesc := AllocMem(BufferSize); Required := 0; Result.Status := NtQuerySecurityObject(hObject, SecurityInformation, SecDesc, BufferSize, Required); if not Result.IsSuccess then begin FreeMem(SecDesc); SecDesc := nil; end; until not NtxExpandBuffer(Result, BufferSize, Required); end; // Owner function NtxQueryOwnerObject(hObject: THandle; out Owner: ISid): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := NtxQuerySecurityObject(hObject, OWNER_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetOwnerSD(pSD, Owner); FreeMem(pSD); end; // Primary group function NtxQueryPrimaryGroupObject(hObject: THandle; out PrimaryGroup: ISid): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := NtxQuerySecurityObject(hObject, GROUP_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetPrimaryGroupSD(pSD, PrimaryGroup); FreeMem(pSD); end; // DACL function NtxQueryDaclObject(hObject: THandle; out Dacl: IAcl): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := NtxQuerySecurityObject(hObject, DACL_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetDaclSD(pSD, Dacl); FreeMem(pSD); end; // SACL function NtxQuerySaclObject(hObject: THandle; out Sacl: IAcl): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := NtxQuerySecurityObject(hObject, SACL_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetSaclSD(pSD, Sacl); FreeMem(pSD); end; // Mandatiry laber function NtxQueryLabelObject(hObject: THandle; out Sacl: IAcl): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := NtxQuerySecurityObject(hObject, LABEL_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetSaclSD(pSD, Sacl); FreeMem(pSD); end; { Set security funtions } function NtxSetSecurityObject(hObject: THandle; SecInfo: TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus; begin Result.Location := 'NtSetSecurityObject'; Result.LastCall.Expects(RtlxComputeWriteAccess(SecInfo), @NonSpecificAccessType); Result.Status := NtSetSecurityObject(hObject, SecInfo, SecDesc); end; // Owner function NtxSetOwnerObject(hObject: THandle; Owner: ISid): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareOwnerSD(SD, Owner); if Result.IsSuccess then Result := NtxSetSecurityObject(hObject, OWNER_SECURITY_INFORMATION, SD); end; // Primary group function NtxSetPrimaryGroupObject(hObject: THandle; Group: ISid): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPreparePrimaryGroupSD(SD, Group); if Result.IsSuccess then Result := NtxSetSecurityObject(hObject, GROUP_SECURITY_INFORMATION, SD); end; // DACL function NtxSetDaclObject(hObject: THandle; Dacl: IAcl): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareDaclSD(SD, Dacl); if Result.IsSuccess then Result := NtxSetSecurityObject(hObject, DACL_SECURITY_INFORMATION, SD); end; // SACL function NtxSetSaclObject(hObject: THandle; Sacl: IAcl): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareSaclSD(SD, Sacl); if Result.IsSuccess then Result := NtxSetSecurityObject(hObject, SACL_SECURITY_INFORMATION, SD); end; // Mandatory label function NtxSetLabelObject(hObject: THandle; Sacl: IAcl): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareSaclSD(SD, Sacl); if Result.IsSuccess then Result := NtxSetSecurityObject(hObject, LABEL_SECURITY_INFORMATION, SD); end; end.
unit dao; {$mode objfpc}{$H+} interface uses Classes, SysUtils, model, sqldb, sqlite3conn, IBConnection; type TDAO = class public constructor Create(ConnParams: String); destructor CleanUp(); function FindUser(Nickname: String): PUser; private AConnection : TSQLite3Connection; end; {$I sqlite_schema.inc} implementation function CreateQuery(pConnection: TSQLConnection; pTransaction: TSQLTransaction): TSQLQuery; begin result := TSQLQuery.Create(nil); result.Database := pConnection; result.Transaction := pTransaction end; constructor TDAO.Create(ConnParams: String); var newFile: boolean; ATransaction: TSQLTransaction; begin inherited Create; self.AConnection := TSQLite3Connection.Create(nil); with self.AConnection do begin DatabaseName := ConnParams; end; newFile := not FileExists(self.AConnection.DatabaseName); if newFile then begin self.AConnection.Open(); ATransaction := TSQLTransaction.Create(nil); ATransaction.Database := self.AConnection; self.AConnection.ExecuteDirect(String(Schema)); ATransaction.Commit; WriteLn('Database created'); self.AConnection.Close; ATransaction.Free; end; end; destructor TDAO.CleanUp(); begin inherited; if AConnection <> Nil then begin AConnection.Close; AConnection.Free; end; end; function TDAO.FindUser(Nickname: String): PUser; var ATransaction: TSQLTransaction; Query: TSQLQuery; User: PUser; begin self.AConnection.Open(); ATransaction := TSQLTransaction.Create(nil); ATransaction.Database := self.AConnection; Query := CreateQuery(self.AConnection, ATransaction); Query.SQL.Text := 'select * from User where nickname = :NICKNAME'; Query.Params.ParamByName('Nickname').AsString := Nickname; Query.Open; user := new(PUser); if not Query.EOF then begin with User^ do begin ID := Query.FieldByName('ID').AsInteger; Nickname := Query.FieldByName('Nickname').AsString; FirstName := Query.FieldByName('FirstName').AsString; LastName := Query.FieldByName('LastName').AsString; end; end; Query.Close; self.AConnection.Close; Query.Free; ATransaction.Free; Result := User; end; end.
unit Vigilante.Controller.Base; interface uses Module.ValueObject.URL; type IBaseController = interface(IInterface) ['{1298B18E-98D1-42C8-A613-3CB39BF0D30C}'] procedure AdicionarNovaURL(const AURL: IURL); procedure VisualizadoPeloUsuario(const AID: TGUID); procedure BuscarAtualizacoes; function PodeNotificarUsuario(const AID: TGUID): boolean; end; implementation end.
unit Ownership; interface uses System.SysUtils, System.SyncObjs, System.Rtti, System.TypInfo; type IRcContainer<T> = Interface function Unwrap : T; function Move : T; End; TRcDeleter = reference to procedure(Data : Pointer); //TRcDeleter<T> = procedure(data : T)にすると内部エラーが出るので致し方なし TRcContainer<T> = class(TInterfacedObject, IRcContainer<T>) private FData : T; FDeleter : TRcDeleter; public constructor Create(Data : T; Deleter : TRcDeleter = nil); destructor Destroy; override; function Unwrap : T; function Move : T; // 所有権を移動させる/移動したことを示す状態にする(FDeleterをnilにする。) ※TObjectに対しても有効 end; ERcDroppedException = class(Exception) end; TRcUnwrapProc<T> = reference to procedure(const data : T); // 参照カウント型スマートポインタ // classのインスタンスを管理する場合はDeleter指定不要。自動的にFreeが呼ばれる // ポインターを管理する場合は独自のDeleterを指定する。(nilもしくは省略すると何もしない) // New()したレコードへのポインターを管理する場合、DeleterにDefaultRecordDisposer()を指定する必要あり // ※Deleterを指定しないとメモリリークが発生する // (ここに記述している内容は実際にはI/TRcContainer<>が処理している) // 2021.7.24 保持しているデータの型を検査するメソッドを追加(IsType, ClassType, Typeinfo) // これを使って、格納している型が異なるTUniq<>からTRc<>に移動できるようになる // 例) var obj : TObject; // obj := TStringList.Create; // var uniq := TUniq.Wrap(obj); // -> uniq is TUniq<TObject> // var rc : TRc<TStringList>; // // // rc := uniq.MoveTo; // NG: IRcContainer<TStringList>とIRcContainer<TObject>は互換性がないため // if uniq.ClassType is rc.ClassType then // 格納している型の互換性チェック // begin // rc := TRc.Wrap( TStringList(uniq.RleaseOwnership) ); // 内部処理:uniqからMoveToでインターフェイスを取り出す。この時点でuniqの管理から外れる。インターフェイスのMoveでデータを取り出す。この時点でインターフェイスの管理からも外れるので再Wrap可能となる // //rc := TRc.Wrap( TStringList(uniq.MoveTo.Unwrap) ); // NG: この書き方だとUnwrap直後にインターフェイスが解放されてデータも解放されてしまう // end; TRc<T> = record private FStrongRef : IRcContainer<T>; public class function Wrap(Data : T; Deleter : TRcDeleter = nil) : TRc<T>; inline; static; class operator Implicit(const Src : IRcContainer<T>) : TRc<T>; overload; class operator Finalize(var Dest : TRc<T>); class operator Positive(Src : TRc<T>) : T; class operator Negative(Src : TRc<T>) : IRcContainer<T>; function Unwrap : T; overload; procedure Unwrap(func : TRcUnwrapProc<T>); overload; function IsNone() : Boolean; // Wrap()するまでの期間はNoneの可能性があるので復活 function IsType(typ : TClass) : Boolean; overload; function IsType(typ : Pointer) : Boolean; overload; function IsType<U>() : Boolean; overload; function ClassType : TClass; function TypeInfo : Pointer; function DefaultT : T; // procedure Drop; // Drop後にUnwrapされるのを防ぎようがないのでコメントアウトしておく。意図したタイミングで解放したい場合はbegin/endでスコープを作る end; // TWeak<T>からTRc<T>に昇格させる場合、既に解放済のケースがあるので解放済(IsNone)を表現可能なTOptionRc<T>に昇格させる TOptionRc<T> = record private FStrongRef : IRcContainer<T>; public class function Wrap(Data : T; Deleter : TRcDeleter = nil) : TOptionRc<T>; static; class operator Finalize(var Dest : TOptionRc<T>); class operator Negative(Src : TOptionRc<T>) : IRcContainer<T>; function IsNone() : Boolean; function TryUnwrap(Func : TRcUnwrapProc<T>) : Boolean; overload; function TryUnwrap(out Data : T) : Boolean; overload; function TryUnwrap(out Data : TRc<T>) : Boolean; overload; function IsType(typ : TClass) : Boolean; overload; function IsType(typ : Pointer) : Boolean; overload; function IsType<U>() : Boolean; overload; procedure Drop; end; ENewWrapException = class(Exception) public class constructor Create(); end; TRcUpgradeProc<T> = reference to procedure(const rc : TRc<T>); // TRc<>で管理しているオブジェクトへの弱い参照を管理する // 保持している参照は既に存在しない場合があるため // オブジェクトにアクセスするためにはTryUpgadeでTRc<>に昇格する必要がある TWeak<T> = record private [Weak] FWeakRef : IRcContainer<T>; public class operator Implicit(const Src : TRc<T>) : TWeak<T>; overload; class operator Implicit(const Src : IRcContainer<T>) : TWeak<T>; overload; class operator Positive(Src : TWeak<T>) : TOptionRc<T>; function TryUpgrade(var Dest : TRc<T>) : Boolean; overload; function TryUpgrade(func : TRcUpgradeProc<T>) : Boolean; overload; function Upgrade() : TOptionRc<T>; procedure Drop; end; // TRc<>を少ない記述量で生成するための関数群 TRc = class public class function Wrap<T>(Data : T; Deleter : TRcDeleter = nil) : TRc<T>; static; class function NewWrap<PT,T>(Deleter : TRcDeleter = nil) : TRc<PT>; static; class function CreateWrap<T:class, constructor>() : TRc<T>; static; end; // 参照を唯一のオーナーが持つスマートポインタ // ※ただしTryUnwrapしたものを保持されてしまうことは防げない・・・ // 他のTUniq<>への代入(コピー)は許されない(強制的に移動になる) // TRc<>(IRcContainer経由)への移動は許される。TWeak<>にも移動できるが無意味 // 参照が移動されている可能性があるため、保持しているオブジェクトにアクセスする場合はTryUnwrap // をもちいる // Assign()が使用されている場合は例外を出してコピーを禁止する方法を試してみたが // Moveを実装しようとするとAssign()が使われてしまうのでどうにもならなかった // 2021.7.24 保持しているデータの型を検査するメソッドを追加(IsType, ClassType, Typeinfo) TUniq<T> = record private FStrongRef : IRcContainer<T>; public class function Wrap(Data : T; Deleter : TRcDeleter = nil) : TUniq<T>; static; class operator Finalize(var Dest : TUniq<T>); class operator Assign(var Dest : TUniq<T>; var Src : TUniq<T>); function IsNone() : Boolean; function TryUnwrap(var Data: T): Boolean; overload; function TryUnwrap(Func: TRcUnwrapProc<T>): Boolean; overload; function MoveTo : IRcContainer<T>; function RleaseOwnership : T; procedure Drop; // TRc<>とは違い、TryUnwarpでしか取り出せないのでDropも有効にした。 function IsType(typ : TClass) : Boolean; overload; function IsType(typ : Pointer) : Boolean; overload; function IsType<U>() : Boolean; overload; function ClassType : TClass; function TypeInfo : Pointer; function DefaultT : T; end; TUniq = class public class function Wrap<T>(Data : T; Deleter : TRcDeleter = nil) : TUniq<T>; static; end; TRcLockedContainer<T> = class(TInterfacedObject, IRcContainer<T>) private FLock : TLightweightMREW; FData : T; FDeleter : TRcDeleter; public constructor Create(Data : T; Deleter : TRcDeleter = nil); destructor Destroy; override; function Unwrap : T; function Move : T; end; TMuxtexGuardW<T> = record private FData : TRcLockedContainer<T>; public class operator Finalize(var Dest : TMuxtexGuardW<T>); function Unwrap : T; inline; procedure ReWrap(data : T); inline; end; TMuxtexGuardR<T> = record private FData : TRcLockedContainer<T>; public class operator Finalize(var Dest : TMuxtexGuardR<T>); function Unwrap : T; inline; end; TArcMutex<T> = record private FStrongRef : IRcContainer<T>; public class function Wrap(Data : T; Deleter : TRcDeleter = nil) : TArcMutex<T>; static; class operator Implicit(const Src : IRcContainer<T>) : TArcMutex<T>; overload; class operator Finalize(var Dest : TArcMutex<T>); function LockW : TMuxtexGuardW<T>; function LockR : TMuxtexGuardR<T>; end; TArcMutex = class public class function Wrap<T>(Data : T; Deleter : TRcDeleter = nil) : TArcMutex<T>; static; end; procedure DefaultRecordDisposer(p : Pointer); procedure DefaultObjectDeleter(Data : Pointer); implementation procedure DefaultRecordDisposer(p : Pointer); begin Dispose(p); end; procedure DefaultObjectDeleter(Data : Pointer); begin TObject(Data).Free; end; { TRcContainer<T> } constructor TRcContainer<T>.Create(Data: T; Deleter: TRcDeleter); begin FData := data; if GetTypeKind(T) = tkClass then begin if not Assigned(Deleter) then FDeleter := DefaultObjectDeleter else FDeleter := Deleter; end else begin FDeleter := deleter; end; end; destructor TRcContainer<T>.Destroy; var p : TObject; o : T absolute p; begin o := FData; if Assigned(FDeleter) then FDeleter(Pointer(p)); inherited; end; function TRcContainer<T>.Move : T; begin result := FData; FDeleter := nil; end; function TRcContainer<T>.Unwrap: T; begin result := FData; end; { TRc<T> } // Drop後にUnwrapされるのを防ぎようがないのでコメントアウトしておく { procedure TRc<T>.Drop; begin FStrongRef := nil; // ref -- end; } function TRc<T>.ClassType: TClass; var p : TObject; o : T absolute p; begin if GetTypeKind(T) = tkClass then begin o := (FStrongRef as TRcContainer<T>).FData; result := p.ClassType; end else begin result := nil; end; end; function TRc<T>.DefaultT: T; begin result := Default(T); end; class operator TRc<T>.Finalize(var Dest: TRc<T>); begin Dest.FStrongRef := nil; // ref -- end; class operator TRc<T>.Implicit(const Src: IRcContainer<T>): TRc<T>; begin result.FStrongRef := Src; end; function TRc<T>.IsNone: Boolean; begin result := FStrongRef = nil; end; function TRc<T>.IsType(typ: Pointer): Boolean; begin result := System.TypeInfo(T) = typ; end; function TRc<T>.IsType<U>(): Boolean; begin result := System.TypeInfo(T) = System.TypeInfo(U); end; function TRc<T>.IsType(typ: TClass): Boolean; var p : TObject; o : T absolute p; begin if GetTypeKind(T) = tkClass then begin o := (FStrongRef as TRcContainer<T>).FData; result := p is typ; end else begin result := false; end; end; class operator TRc<T>.Negative(Src: TRc<T>): IRcContainer<T>; begin result := Src.FStrongRef; end; class operator TRc<T>.Positive(Src: TRc<T>): T; begin if Src.FStrongRef = nil then raise ERcDroppedException.Create('Unable to unwrap dropped references!'); result := Src.FStrongRef.Unwrap; end; function TRc<T>.TypeInfo: Pointer; begin result := System.TypeInfo(T); end; function TRc<T>.Unwrap: T; begin if FStrongRef = nil then raise ERcDroppedException.Create('Unable to unwrap dropped references!'); result := FStrongRef.Unwrap; end; procedure TRc<T>.Unwrap(func: TRcUnwrapProc<T>); begin if FStrongRef = nil then raise ERcDroppedException.Create('Unable to unwrap dropped references!'); func(FStrongRef.Unwrap); end; class function TRc<T>.Wrap(Data: T; Deleter: TRcDeleter): TRc<T>; begin result.FStrongRef := TRcContainer<T>.Create(Data, Deleter); // ref ++ end; { TOptionRc<T> } procedure TOptionRc<T>.Drop; begin FStrongRef := nil; // ref -- end; class operator TOptionRc<T>.Finalize(var Dest: TOptionRc<T>); begin Dest.FStrongRef := nil; // ref -- end; function TOptionRc<T>.IsNone: Boolean; begin result := FStrongRef = nil; end; function TOptionRc<T>.IsType(typ: TClass): Boolean; var p : TObject; o : T absolute p; begin if GetTypeKind(T) = tkClass then begin o := (FStrongRef as TRcContainer<T>).FData; result := p is typ; end else begin result := false; end; end; function TOptionRc<T>.IsType(typ: Pointer): Boolean; begin result := System.TypeInfo(T) = typ; end; function TOptionRc<T>.IsType<U>: Boolean; begin result := System.TypeInfo(T) = System.TypeInfo(U); end; class operator TOptionRc<T>.Negative(Src: TOptionRc<T>): IRcContainer<T>; begin result := Src.FStrongRef; end; function TOptionRc<T>.TryUnwrap(out Data: TRc<T>): Boolean; begin result := FStrongRef <> nil; if result then data.FStrongRef := FStrongRef; end; function TOptionRc<T>.TryUnwrap(Func: TRcUnwrapProc<T>): Boolean; begin result := FStrongRef <> nil; if result then func(FStrongRef.Unwrap); end; function TOptionRc<T>.TryUnwrap(out Data: T): Boolean; begin result := FStrongRef <> nil; if result then data := FStrongRef.Unwrap; end; class function TOptionRc<T>.Wrap(Data: T; Deleter: TRcDeleter): TOptionRc<T>; begin result.FStrongRef := TRcContainer<T>.Create(Data, Deleter); // ref ++ end; { TRc } class function TRc.CreateWrap<T>(): TRc<T>; begin var obj := T.Create(); result := TRc<T>.Wrap(obj, nil); end; class function TRc.NewWrap<PT,T>(Deleter: TRcDeleter): TRc<PT>; type PR = ^T; var p : PR; d : PT absolute p; begin if GetTypeKind(PT) = tkPointer then begin System.New(p); p^ := Default(T); if Assigned(Deleter) then result := TRc<PT>.Wrap(d, Deleter) else result := TRc<PT>.Wrap(d, DefaultRecordDisposer); end else begin raise ENewWrapException.Create('TRc.NewWrap<PT,T>() PT must be record pointer! '); end; end; class function TRc.Wrap<T>(Data: T; Deleter: TRcDeleter): TRc<T>; begin result := TRc<T>.Wrap(data, Deleter); end; { TWeak<T> } procedure TWeak<T>.Drop; begin FWeakRef := nil; end; class operator TWeak<T>.Implicit(const Src: TRc<T>): TWeak<T>; begin result.FWeakRef := Src.FStrongRef; // ref +-0 end; class operator TWeak<T>.Implicit(const Src: IRcContainer<T>): TWeak<T>; begin result.FWeakRef := Src; // ref +-0 end; class operator TWeak<T>.Positive(Src: TWeak<T>): TOptionRc<T>; begin result.FStrongRef := Src.FWeakRef; end; function TWeak<T>.TryUpgrade(var Dest: TRc<T>): Boolean; begin Dest.FStrongRef := FWeakRef; // ref++ result := Dest.FStrongRef <> nil; end; function TWeak<T>.TryUpgrade(func: TRcUpgradeProc<T>): Boolean; begin var rc : TRc<T>; if TryUpgrade(rc) then begin func(rc); result := true; end else begin result := false; end; end; function TWeak<T>.Upgrade: TOptionRc<T>; begin result.FStrongRef := FWeakRef; end; { TUniq<T> } class operator TUniq<T>.Assign(var Dest: TUniq<T>; var Src: TUniq<T>); begin Dest.FStrongRef := Src.FStrongRef; Src.FStrongRef := nil; end; function TUniq<T>.ClassType: TClass; var p : TObject; o : T absolute p; begin if GetTypeKind(T) = tkClass then begin o := (FStrongRef as TRcContainer<T>).FData; result := p.ClassType; end else begin result := nil; end; end; function TUniq<T>.DefaultT: T; begin result := Default(T); end; procedure TUniq<T>.Drop; begin FStrongRef := nil; // ref -- end; class operator TUniq<T>.Finalize(var Dest: TUniq<T>); begin Dest.FStrongRef := nil; // ref -- end; function TUniq<T>.IsNone: Boolean; begin result := FStrongRef = nil; end; function TUniq<T>.IsType(typ: TClass): Boolean; var p : TObject; o : T absolute p; begin if GetTypeKind(T) = tkClass then begin o := (FStrongRef as TRcContainer<T>).FData; result := p is typ; end else begin result := false; end; end; function TUniq<T>.IsType(typ: Pointer): Boolean; begin result := System.TypeInfo(T) = typ; end; function TUniq<T>.IsType<U>: Boolean; begin result := System.TypeInfo(T) = System.TypeInfo(U); end; function TUniq<T>.RleaseOwnership: T; begin var intf := MoveTo; if intf <> nil then result := intf.Move else result := Default(T); end; function TUniq<T>.MoveTo: IRcContainer<T>; begin result := FStrongRef; // ref++ FStrongRef := nil; // ref -- end; function TUniq<T>.TryUnwrap(var Data: T): Boolean; begin result := FStrongRef <> nil; if result then Data := FStrongRef.Unwrap; end; function TUniq<T>.TryUnwrap(Func: TRcUnwrapProc<T>): Boolean; begin result := FStrongRef <> nil; if result then func(FStrongRef.Unwrap); end; function TUniq<T>.TypeInfo: Pointer; begin result := System.TypeInfo(T); end; class function TUniq<T>.Wrap(Data: T; Deleter: TRcDeleter): TUniq<T>; begin result.FStrongRef := TRcContainer<T>.Create(Data, Deleter); // ref ++ end; { TUniq } class function TUniq.Wrap<T>(Data: T; Deleter: TRcDeleter): TUniq<T>; begin result := TUniq<T>.Wrap(Data, Deleter); end; { ENewWrapException } class constructor ENewWrapException.Create; begin raise Exception.Create('TRc.NewWrap<PT,T>() PT must be record pointer! '); end; { TArcMutex<T> } class operator TArcMutex<T>.Finalize(var Dest: TArcMutex<T>); begin Dest.FStrongRef := nil; end; class operator TArcMutex<T>.Implicit(const Src: IRcContainer<T>): TArcMutex<T>; begin result.FStrongRef := Src; end; function TArcMutex<T>.LockR: TMuxtexGuardR<T>; begin result.FData := FStrongRef as TRcLockedContainer<T>; result.FData.FLock.BeginRead; end; function TArcMutex<T>.LockW: TMuxtexGuardW<T>; begin result.FData := FStrongRef as TRcLockedContainer<T>; result.FData.FLock.BeginWrite; end; class function TArcMutex<T>.Wrap(Data: T; Deleter: TRcDeleter): TArcMutex<T>; begin result.FStrongRef := TRcLockedContainer<T>.Create(Data, Deleter); end; { TRcLockedContainer<T> } constructor TRcLockedContainer<T>.Create(Data: T; Deleter: TRcDeleter); begin FData := Data; if GetTypeKind(T) = tkClass then begin if not Assigned(Deleter) then FDeleter := DefaultObjectDeleter else FDeleter := Deleter; end else begin FDeleter := Deleter; end; end; destructor TRcLockedContainer<T>.Destroy; var p : TObject; o : T absolute p; begin o := FData; if Assigned(FDeleter) then FDeleter(Pointer(p)); inherited; end; function TRcLockedContainer<T>.Move: T; begin result := FData; FDeleter := nil; end; function TRcLockedContainer<T>.Unwrap: T; begin result := Default(T); end; { TMuxtexGuardW<T> } class operator TMuxtexGuardW<T>.Finalize(var Dest: TMuxtexGuardW<T>); begin Dest.FData.FLock.EndWrite; end; procedure TMuxtexGuardW<T>.ReWrap(data: T); begin FData.FData := data; end; function TMuxtexGuardW<T>.Unwrap: T; begin result := FData.FData; end; { TMuxtexGuardR<T> } class operator TMuxtexGuardR<T>.Finalize(var Dest: TMuxtexGuardR<T>); begin Dest.FData.FLock.EndRead; end; function TMuxtexGuardR<T>.Unwrap: T; begin result := FData.FData; end; { TArcMutex } class function TArcMutex.Wrap<T>(Data: T; Deleter: TRcDeleter): TArcMutex<T>; begin result.FStrongRef := TRcLockedContainer<T>.Create(Data, Deleter); end; end.
unit PascalCoin.RPC.Client; interface uses System.JSON, PascalCoin.RPC.Interfaces, PascalCoin.Utils.Interfaces; type TPascalCoinRPCClient = Class(TInterfacedObject, IPascalCoinRPCClient) private FNodeURI: string; FHTTPClient: IRPCHTTPRequest; FResultStr: String; FResultObj: TJSONObject; FError: boolean; FErrorData: String; FCallId: string; FNextId: Integer; function NextId: String; protected function GetResult: TJSONObject; function GetResultStr: string; function RPCCall(const AMethod: String; const AParams: Array of TParamPair): boolean; function GetNodeURI: String; procedure SetNodeURI(const Value: string); public constructor Create(AHTTPClient: IRPCHTTPRequest); End; implementation uses System.SysUtils, System.IOUtils; { TPascalCoinRPCClient } constructor TPascalCoinRPCClient.Create(AHTTPClient: IRPCHTTPRequest); begin inherited Create; FHTTPClient := AHTTPClient; FError := True; end; function TPascalCoinRPCClient.GetNodeURI: String; begin result := FNodeURI; end; function TPascalCoinRPCClient.GetResult: TJSONObject; begin if Not FError then result := TJSONObject.ParseJSONValue(FResultStr) As TJSONObject else result := TJSONObject.ParseJSONValue(FErrorData) As TJSONObject; end; function TPascalCoinRPCClient.GetResultStr: string; begin if Not FError then result := FResultStr else result := FErrorData; end; function TPascalCoinRPCClient.NextId: String; begin Inc(FNextId); result := FNextId.ToString; end; // {"jsonrpc": "2.0", "method": "XXX", "id": YYY, "params":{"p1":" ","p2":" "}} function TPascalCoinRPCClient.RPCCall(const AMethod: String; const AParams: Array of TParamPair): boolean; var lObj, lErrObj, lParams, lErr, lAObj: TJSONObject; lArr: TJSONArray; lParam: TParamPair; lValue, lElem, lErrElem: TJSONValue; FAErrors: String; begin lErr := nil; lParams := nil; FCallId := NextId; lObj := TJSONObject.Create; try lObj.AddPair('jsonrpc', '2.0'); lObj.AddPair('id', FCallId); lObj.AddPair('method', AMethod); lParams := TJSONObject.Create; for lParam in AParams do begin lParams.AddPair(lParam.Key, lParam.Value); end; lObj.AddPair('params', lParams); result := FHTTPClient.Post(FNodeURI, lObj.ToJSON); FError := not result; if FError then begin lObj.Free; lObj := TJSONObject.Create; lObj.AddPair('StatusCode', FHTTPClient.StatusCode.ToString); lObj.AddPair('StatusMessage', FHTTPClient.StatusText); lObj.AddPair('ErrorSource', 'HTTPClient'); FErrorData := lObj.ToJSON; lObj.Free; end { TODO : Test that return Id matches call id } else begin FResultStr := FHTTPClient.ResponseStr; FResultObj := (TJSONObject.ParseJSONValue(FResultStr) as TJSONObject); lValue := FResultObj.FindValue('error'); if lValue <> nil then begin lErrObj := lValue as TJSONObject; lErr := TJSONObject.Create; lErr.AddPair('StatusCode', lErrObj.Values['code'].AsType<string>); lErr.AddPair('StatusMessage', lErrObj.Values['message'].AsType<string>); lErr.AddPair('ErrorSource', 'RemoteRPC'); FErrorData := lErr.ToJSON; lErr.Free; FResultStr := ''; result := False; FError := True; Exit; end; lValue := FResultObj.FindValue('result'); if lValue is TJSONArray then begin FAErrors := ''; lArr := lValue as TJSONArray; for lElem in lArr do begin lAObj := lElem as TJSONObject; lErrElem := lAObj.FindValue('errors'); if lErrElem <> nil then begin FAErrors := FAErrors + lErrElem.AsType<String> + ';'; end; end; if FAErrors <> '' then begin lErr := TJSONObject.Create; lErr.AddPair('StatusCode', '-1'); lErr.AddPair('StatusMessage', FAErrors); lErr.AddPair('ErrorSource', 'RemoteRPC'); FErrorData := lErr.ToJSON; lErr.Free; FResultStr := ''; Result := False; FError := True; end else begin Result := True; FError := False; end; end else if lValue is TJSONObject then begin Result := True; FError := False; end; end; finally lObj.Free; end; end; procedure TPascalCoinRPCClient.SetNodeURI(const Value: string); begin FNodeURI := Value; end; end.
unit f12_statistik; interface uses user_handler, buku_handler; { DEKLARASI FUNGSI DAN PROSEDUR } procedure getStatistik(data_user: tabel_user; data_buku: tabel_buku); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure getStatistik(data_user: tabel_user; data_buku: tabel_buku); { DESKRIPSI : Mencetak statistik dari data yang ada } { PARAMETER : data user dan data buku } { KAMUS LOKAL } var cnt_admin, cnt_pengunjung, total_user, i, cnt_sastra, cnt_sains, cnt_manga, cnt_sejarah, cnt_programming, total_buku: integer; { ALGORITMA } begin cnt_admin := 0; cnt_pengunjung := 0; for i:=1 to data_user.sz-1 do begin if(data_user.t[i].Role='Admin') then cnt_admin := cnt_admin+1 else cnt_pengunjung := cnt_pengunjung+1; end; total_user := cnt_admin + cnt_pengunjung; cnt_sastra := 0; cnt_sains := 0; cnt_manga := 0; cnt_sejarah := 0; cnt_programming := 0; for i:=1 to data_buku.sz-1 do begin case data_buku.t[i].Kategori of 'sastra': cnt_sastra := cnt_sastra+1; 'sains': cnt_sains := cnt_sains+1; 'manga': cnt_manga := cnt_manga+1; 'sejarah': cnt_sejarah := cnt_sejarah+1; else cnt_programming := cnt_programming+1; end; end; total_buku := cnt_sastra + cnt_sains + cnt_manga + cnt_sejarah + cnt_programming; writeln('Pengguna:'); writeln('Admin | ', cnt_admin); writeln('Pengunjung | ', cnt_pengunjung); writeln('Total | ', total_user); writeln('Buku:'); writeln('sastra | ', cnt_sastra); writeln('sains | ', cnt_sains); writeln('manga | ', cnt_manga); writeln('sejarah | ', cnt_sejarah); writeln('programming | ', cnt_programming); writeln('Total | ', total_buku); end; end.
// // Created by the DataSnap proxy generator. // unit UDBAccess; interface uses DBXCommon, DBXJSON, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, DBClient, Variants; type TDBAccess = class(TComponent) private FConnection: TDBXConnection; FInstanceOwner: Boolean; FErrorCode: string; FErrorText: string; function CreateCommand(Text: string): TDBXCommand; function GetConnected: Boolean; procedure SetConnected(const Value: Boolean); public // 对象创建及释放 constructor Create(AOwner: TComponent; ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; constructor Create(AOwner: TComponent; ADBXConnection: TDBXConnection); overload; destructor Destroy; override; function EchoString(Value: string): string; // 获取错误信息 function GetLastError: string; function GetLastErrorCode: string; // 获取服务器信息函数 function GetServerDateTime(var Value: TDateTime): Boolean; procedure GetServerLastError(var ErrorCode, ErrorText: string); // 数据操作(DML)语句 function ReadDataSet(AStrSql: string; Cds: TClientDataSet): Boolean; function ReadTableHead(TableName: string; var Data: OleVariant): Boolean; function QueryData(AStrSql: string; APageSize, APageNo: Integer; Cds: TClientDataSet): Boolean; function GetSQLStringValue(AStrSql: string): string; function GetSQLIntegerValue(AStrSql: string): Integer; function DataSetIsEmpty(AStrSql: string): Integer; function ApplyUpdates(TableName: string; Delta: OleVariant; var ErrorCount: Integer): Boolean; overload; function ApplyUpdates(TableName: string; Delta: OleVariant): Boolean; overload; function ExecuteSQL(AStrSql: string): Boolean; function ExecuteBatchSQL(AList: TStrings): Boolean; published property Connected: Boolean read GetConnected write SetConnected; property Connection: TDBXConnection read FConnection write FConnection; end; var DBAccess: TDBAccess; implementation function TDBAccess.CreateCommand(Text: string): TDBXCommand; begin Result := FConnection.CreateCommand; Result.CommandType := TDBXCommandTypes.DSServerMethod; Result.Text := Text; Result.Prepare; end; function TDBAccess.EchoString(Value: string): string; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.EchoString'); try lCommand.Parameters[0].Value.SetWideString(Value); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetWideString; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetConnected: Boolean; begin end; function TDBAccess.GetLastError: string; begin Result := FErrorText; FErrorText := ''; end; procedure TDBAccess.GetServerLastError(var ErrorCode, ErrorText: string); var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.GetServerLastError'); try lCommand.Parameters[0].Value.SetWideString(ErrorCode); lCommand.Parameters[1].Value.SetWideString(ErrorText); lCommand.ExecuteUpdate; ErrorCode := lCommand.Parameters[0].Value.GetWideString; ErrorText := lCommand.Parameters[1].Value.GetWideString; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetLastErrorCode: string; begin Result := FErrorCode; FErrorCode := ''; end; function TDBAccess.ReadDataSet(AStrSql: string; Cds: TClientDataSet): Boolean; var lData: OleVariant; lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.ReadDataSet'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.AsVariant := lData; lCommand.ExecuteUpdate; Result := lCommand.Parameters[2].Value.AsBoolean; if Result then begin lData := lCommand.Parameters[1].Value.AsVariant; Cds.Data := lData; end; finally FreeAndNil(lCommand); end; end; function TDBAccess.ReadTableHead(TableName: string; var Data: OleVariant): Boolean; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.ReadTableHead'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Data; lCommand.ExecuteUpdate; Result := lCommand.Parameters[2].Value.AsBoolean; if Result then Data := lCommand.Parameters[1].Value.AsVariant; finally FreeAndNil(lCommand); end; end; function TDBAccess.ApplyUpdates(TableName: string; Delta: OleVariant; var ErrorCount: Integer): Boolean; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.ApplyUpdates'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Delta; lCommand.Parameters[2].Value.SetInt32(ErrorCount); lCommand.ExecuteUpdate; ErrorCount := lCommand.Parameters[2].Value.AsInt32; Result := lCommand.Parameters[3].Value.AsBoolean; finally FreeAndNil(lCommand); end; end; function TDBAccess.ApplyUpdates(TableName: string; Delta: OleVariant): Boolean; var lErrCount: Integer; lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.ApplyUpdates'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Delta; lErrCount := 0; lCommand.Parameters[2].Value.SetInt32(lErrCount); lCommand.ExecuteUpdate; //lErrCount := lCommand.Parameters[2].Value.GetInt32; Result := lCommand.Parameters[3].Value.AsBoolean; finally FreeAndNil(lCommand); end; end; function TDBAccess.DataSetIsEmpty(AStrSql: string): Integer; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.DataSetIsEmpty'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetInt32; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetServerDateTime(var Value: TDateTime): Boolean; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.GetServerDateTime'); try lCommand.Parameters[0].Value.AsDateTime := Value; lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.AsBoolean; if Result then Value := lCommand.Parameters[0].Value.AsDateTime; finally FreeAndNil(lCommand); end; end; procedure TDBAccess.SetConnected(const Value: Boolean); begin end; function TDBAccess.GetSQLStringValue(AStrSql: string): string; var lCommand: TDBXCommand; lValue: string; begin lCommand := CreateCommand('TServerMethods.GetSQLStringValue'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.SetWideString(lValue); lCommand.ExecuteUpdate; if lCommand.Parameters[2].Value.AsBoolean then Result := lCommand.Parameters[1].Value.GetWideString else Result := ''; finally FreeAndNil(lCommand); end; end; function TDBAccess.QueryData(AStrSql: string; APageSize, APageNo: Integer; Cds: TClientDataSet): Boolean; var lCommand: TDBXCommand; lData: OleVariant; begin lCommand := CreateCommand('TServerMethods.QueryData'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.AsInt32 := APageSize; lCommand.Parameters[2].Value.AsInt32 := APageNo; lCommand.Parameters[3].Value.AsVariant := lData; lCommand.ExecuteUpdate; Result := lCommand.Parameters[4].Value.AsBoolean; if Result then begin lData := lCommand.Parameters[3].Value.AsVariant; Cds.Data := lData; end; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetSQLIntegerValue(AStrSql: string): Integer; var lCommand: TDBXCommand; Value: Integer; begin lCommand := CreateCommand('TServerMethods.GetSQLIntegerValue'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.SetInt32(Value); lCommand.ExecuteUpdate; if lCommand.Parameters[2].Value.AsBoolean then Value := lCommand.Parameters[1].Value.AsInt32 else Value := -1; finally FreeAndNil(lCommand); end; end; function TDBAccess.ExecuteBatchSQL(AList: TStrings): Boolean; var lCommand: TDBXCommand; lStream: TStream; begin lCommand := CreateCommand('TServerMethods.ExecuteBatchSQL'); lStream := TStream.Create; try AList.SaveToStream(lStream); lCommand.Parameters[0].Value.SetStream(lStream, False); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetBoolean; finally lStream.Free; FreeAndNil(lCommand); end; end; function TDBAccess.ExecuteSQL(AStrSql: string): Boolean; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.ExecuteSQL'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetBoolean; finally FreeAndNil(lCommand); end; end; constructor TDBAccess.Create(AOwner: TComponent; ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(AOwner); if ADBXConnection = nil then raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.'); FConnection := ADBXConnection; FInstanceOwner := AInstanceOwner; end; constructor TDBAccess.Create(AOwner: TComponent; ADBXConnection: TDBXConnection); begin inherited Create(AOwner); if ADBXConnection = nil then raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.'); FConnection := ADBXConnection; FInstanceOwner := True; end; destructor TDBAccess.Destroy; begin inherited; end; end.
function WordNumberCase(Number: Integer; IfOne, IfTwo, IfFive: String; AddNumber: Boolean = False): String; var Num, m: Integer; begin Num := Number; If Number < 0 then Num := -Number; m := Num mod 10; Case m of 1: Result:=IfOne; 2..4: Result:=IfTwo; Else Result:=IfFive; End; If m in [1..4] then if Num mod 100 in [11..14] then Result:=IfFive; If AddNumber then Result := IntToStr(Number) + Result; end;
unit Unit5; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs,Grids,StdCtrls, Types; type { TForm5 } TForm5 = class(TForm) Button1:TButton; StringGrid1:TStringGrid; procedure Button1Click(Sender:TObject); procedure FormCreate(Sender:TObject); procedure StringGrid1DrawCell(Sender:TObject; aCol,aRow:Integer; aRect:TRect; aState:TGridDrawState); private public end; const ARR_SIZE_N = 4; ARR_SIZE_M = 4; var Form5: TForm5; z : array[0..ARR_SIZE_N,0..ARR_SIZE_M] of Integer; generatedOnce:Boolean; calculatedColIndex:Integer; colIndexLock:Boolean; implementation {$R *.lfm} { TForm5 } procedure TForm5.Button1Click(Sender:TObject); var i,j:Integer; maxSum,sum:Integer; colIndex:Integer; begin colIndexLock := true; Randomize(); for i := 0 to ARR_SIZE_N - 1 do for j := 0 to ARR_SIZE_M - 1 do z[i,j] := random(5); maxSum := 0; for i := 0 to ARR_SIZE_N - 1 do Begin sum := 0; for j := 0 to ARR_SIZE_M do sum := sum + z[i,j]; StringGrid1.Cells[i,0] := IntToStr(sum); If sum > maxSum then Begin maxSum := sum; colIndex:=i; end; end; calculatedColIndex := colIndex; for i := 0 to ARR_SIZE_N - 1 do for j := 1 to ARR_SIZE_M do StringGrid1.Cells[i,j] := IntToStr(z[i,j - 1]); colIndexLock:=false; StringGrid1.Repaint(); end; procedure TForm5.FormCreate(Sender:TObject); begin colIndexLock:=true; StringGrid1.ColCount:=ARR_SIZE_N; StringGrid1.FixedCols:=0; StringGrid1.RowCount:=ARR_SIZE_M + 1; StringGrid1.FixedRows:=1; end; procedure TForm5.StringGrid1DrawCell(Sender:TObject; aCol,aRow:Integer; aRect:TRect; aState:TGridDrawState); var rAlign:TTextStyle; begin If (not colIndexLock) then Begin if (ACol = calculatedColIndex) and (ARow > 0) then begin with TStringGrid(Sender) do begin rAlign := Canvas.TextStyle; rAlign.Alignment:=taRightJustify; Canvas.TextStyle := rAlign; Canvas.Brush.Color := clGreen; Canvas.FillRect(aRect); Canvas.TextRect(aRect,aRect.Left+2,aRect.Top+2,Cells[ACol, ARow] + ' ',rAlign); end; end; end; Begin with TStringGrid(Sender) do begin rAlign := Canvas.TextStyle; rAlign.Alignment:=taRightJustify; Canvas.TextStyle := rAlign; Canvas.FillRect(aRect); Canvas.TextRect(aRect,aRect.Left+2,aRect.Top+2,Cells[ACol, ARow] + ' ',rAlign); end; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLMeshLines<p> Line implementation by means of a Triangle strip.<p> <b>History : </b><font size=-1><ul> <li>05/14/07 - PVD - initial unit proposal (thanks Lord CRC for help) } unit GLMeshLines; interface uses System.Classes, System.SysUtils, //GLS GLScene, GLObjects, GLTexture, GLVectorFileObjects, GLCoordinates, OpenGLTokens, GLContext, GLMaterial, GLColor, GLState, GLNodes, GLVectorGeometry, GLSpline, GLVectorTypes, GLVectorLists, GLRenderContextInfo; type // TLineNode // {: Specialized Node for use in a TGLLines objects.<p> Adds a Width property } TLineNode = class(TGLNode) private FData: Pointer; protected public constructor Create(Collection : TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property Data: Pointer read FData write FData; published end; // TLineNodes // {: Specialized collection for Nodes in TGLMeshLines objects.<p> Stores TLineNode items. } TLineNodes = class(TGLNodes) public { Public Declarations } constructor Create(AOwner : TComponent); overload; destructor destroy; override; procedure NotifyChange; override; function IndexOf(LineNode: TLineNode): Integer; end; TLineItem = class(TCollectionItem) private FName: String; FBreakAngle: Single; FDivision: Integer; FNodes: TLineNodes; FSplineMode: TLineSplineMode; FTextureLength: Single; FWidth: Single; FTextureCorrection: Boolean; FHide: Boolean; FData: Pointer; procedure SetHide(const Value: Boolean); procedure SetTextureCorrection(const Value: Boolean); procedure SetBreakAngle(const Value: Single); procedure SetDivision(const Value: Integer); procedure SetNodes(const Value: TLineNodes); procedure SetSplineMode(const Value:TLineSplineMode); procedure SetTextureLength(const Value: Single); procedure SetWidth(const Value: Single); protected procedure DoChanged; virtual; public property Data: Pointer read FData write FData; published constructor Create(Collection: TCollection); override; destructor Destroy; override; property Hide: Boolean read FHide write SetHide; property Name: String read FName write FName; property TextureCorrection: Boolean read FTextureCorrection write SetTextureCorrection; property BreakAngle: Single read FBreakAngle write SetBreakAngle; property Division: Integer read FDivision write SetDivision; property Nodes : TLineNodes read FNodes write SetNodes; property SplineMode: TLineSplineMode read FSplineMode write SetSplineMode; property TextureLength: Single read FTextureLength write SetTextureLength; property Width: Single read FWidth write SetWidth; end; TLineCollection = class(TOwnedCollection) private procedure SetItems(Index: Integer; const Val: TLineItem); function GetItems(Index: Integer): TLineItem; protected public function Add: TLineItem; overload; function Add(Name: String): TLineItem; overload; property Items[Index: Integer]: TLineItem read GetItems write SetItems; default; published end; TLightmapBounds = class(TGLCustomCoordinates) private function GetLeft: TGLFloat; function GetTop: TGLFloat; function GetRight: TGLFloat; function GetBottom: TGLFloat; function GetWidth: TGLFloat; function GetHeight: TGLFloat; procedure SetLeft(const value: TGLFloat); procedure SetTop(const value: TGLFloat); procedure SetRight(const value: TGLFloat); procedure SetBottom(const value: TGLFloat); published property Left: TGLFloat read GetLeft write SetLeft stored False; property Top: TGLFloat read GetTop write SetTop stored False; property Right: TGLFloat read GetRight write SetRight stored False; property Bottom: TGLFloat read GetBottom write SetBottom stored False; property Width: TGLFloat read GetWidth; property Height: TGLFloat read GetHeight; end; TGLMeshLines = class(TGLFreeForm) private FLines: TLineCollection; FMesh: TMeshObject; FLightmapBounds: TLightmapBounds; FLightmapIndex: Integer; FLightmapMaterialName: String; FFaceGroup: TFGVertexIndexList; FIndex: Integer; FNoZWrite: boolean; FShowNodes: Boolean; FUpdating: Integer; FSelectedLineItem: TLineItem; FSelectedNode: TLineNode; FNode1,FNode2: TLineNode; function GetUpdating: Boolean; function PointNearLine(const LineItem: TLineItem; const X,Z: Single; Tolerance: single = 1): boolean; function PointNearSegment(const StartNode, EndNode: TLineNode; const X,Z: Single; LineWidth: single; Tolerance: single = 1): boolean; procedure StitchStrips(idx: TIntegerList); procedure AddStitchMarker(idx: TIntegerList); procedure SetShowNodes(const Value: Boolean); procedure SetNoZWrite(const Value: Boolean); procedure SetLightmapIndex(const value: Integer); procedure SetLightmapMaterialName(const value: String); procedure SetLightmapBounds(const value: TLightmapBounds); procedure DoChanged; procedure AddIndex; procedure AddVertices(Up, Inner, Outer: TAffineVector; S: Single; Correction: Single; UseDegenerate: Boolean; LineItem: TLineItem); procedure BuildLineItem(LineItem: TLineItem); procedure BuildGeometry; procedure DrawNode(var rci : TRenderContextInfo; Node: TLineNode; LineWidth: Single); procedure DrawCircle(Radius: Single); function SelectNode(LineItem: TLineItem; X,Z: Single):TLineNode; protected procedure Loaded; override; public procedure BeginUpdate; procedure EndUpdate; procedure Clear; function SelectLineItem(const X,Z: Single; Tolerance: single = 1): TLineItem; overload; function SelectLineItem(LineItem: TLineItem): TLineItem; overload; function SelectLineItem(LineNode: TLineNode): TLineItem; overload; procedure DeselectLineItem; procedure DeselectLineNode; procedure BuildList(var rci : TRenderContextInfo); override; procedure DoRender(var rci : TRenderContextInfo; renderSelf, renderChildren : Boolean); override; procedure NotifyChange(Sender : TObject); override; property SelectedLineItem: TLineItem read FSelectedLineItem; property SelectedNode: TLineNode read FSelectedNode; property Node1: TLineNode read FNode1; property Node2: TLineNode read FNode2; published constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Updating: Boolean Read GetUpdating; property Lines: TLineCollection read FLines; property Material; property LightmapBounds: TLightmapBounds read FLightmapBounds write SetLightmapBounds; property LightmapIndex: Integer read FLightmapIndex write SetLightmapIndex; property LightmapMaterialName: String read FLightmapMaterialName write SetLightmapMaterialName; property NoZWrite: boolean read FNoZWrite write SetNoZWrite; property ShowNodes: Boolean read FSHowNodes write SetShowNodes; end; //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- implementation //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- const CIRCLESEGMENTS = 32; // TLineNode // constructor TLineNode.Create(Collection : TCollection); begin inherited Create(Collection); end; destructor TLineNode.Destroy; begin inherited Destroy; end; procedure TLineNode.Assign(Source: TPersistent); begin if Source is TLineNode then begin FData := TLineNode(Source).FData; end; inherited; end; // TLineNodes // constructor TLineNodes.Create(AOwner : TComponent); begin inherited Create(AOwner, TLineNode); end; destructor TLineNodes.destroy; begin inherited; end; procedure TLineNodes.NotifyChange; begin if (GetOwner<>nil) then TGLMeshLines((GetOwner as TLineItem).Collection.Owner).StructureChanged; end; function TLineNodes.IndexOf(LineNode: TLineNode): Integer; var i: Integer; begin result := -1; if assigned(LineNode) then begin for i := 0 to Count - 1 do begin if LineNode = Items[i] then begin Result := i; break; end; end; end; end; // TLineCollection // function TLineCollection.GetItems(index: Integer): TLineItem; begin Result:=TLineItem(inherited Items[index]); end; procedure TLineCollection.SetItems(index: Integer; const val: TLineItem); begin inherited Items[index]:=val; end; function TLineCollection.Add: TLineItem; begin result := TLineItem.Create(self); end; function TLineCollection.Add(Name: String): TLineItem; begin Result := Add; Result.Name := Name; end; // TMeshLine // constructor TLineItem.Create(Collection: TCollection); begin inherited; FNodes:=TLineNodes.Create(Self, TLineNode); FBreakAngle := 30; FDivision := 10; FSplineMode := lsmLines; FTextureLength := 1; FWidth := 1; FTextureCorrection := False; end; destructor TLineItem.Destroy; begin if TGLMeshLines(Collection.Owner).SelectedLineItem = self then TGLMeshLines(Collection.Owner).DeSelectLineItem; FNodes.Free; inherited; end; procedure TLineItem.SetHide(const Value: Boolean); begin FHide := Value; DoChanged; end; procedure TLineItem.SetTextureCorrection(const Value: Boolean); begin FTextureCorrection := Value; DoChanged; end; procedure TLineItem.SetBreakAngle(const Value: Single); begin FBreakAngle := Value; DoChanged; end; procedure TLineItem.SetDivision(const Value: Integer); begin FDivision := Value; DoChanged; end; procedure TLineItem.SetNodes(const Value: TLineNodes); begin FNodes.Assign(Value); DoChanged; end; procedure TLineItem.SetSplineMode(const Value:TLineSplineMode); begin FSplineMode := Value; DoChanged; end; procedure TLineItem.SetTextureLength(const Value: Single); begin FTextureLength := Value; DoChanged; end; procedure TLineItem.SetWidth(const Value: Single); begin FWidth := Value; DoChanged; end; procedure TLineItem.DoChanged; begin //Notify parent of change because the mesh needs to be regenerated if (GetOwner<>nil) then TGLMeshLines(Collection.Owner).NotifyChange(Self); end; { TLightmapBounds } function TLightmapBounds.GetLeft: TGLFloat; begin Result := X; end; function TLightmapBounds.GetTop: TGLFloat; begin Result := Y; end; function TLightmapBounds.GetRight: TGLFloat; begin Result := Z; end; function TLightmapBounds.GetBottom: TGLFloat; begin Result := W; end; function TLightmapBounds.GetWidth: TGLFloat; begin Result := Z - X; end; function TLightmapBounds.GetHeight: TGLFloat; begin Result := W - Y; end; procedure TLightmapBounds.SetLeft(const value: TGLFloat); begin X := Value; end; procedure TLightmapBounds.SetTop(const value: TGLFloat); begin Y := Value; end; procedure TLightmapBounds.SetRight(const value: TGLFloat); begin Z := Value; end; procedure TLightmapBounds.SetBottom(const value: TGLFloat); begin W := Value; end; // TGLMeshLine // constructor TGLMeshLines.Create(AOwner: TComponent); begin inherited; FLines := TLineCollection.Create(self,TLineItem); FLightmapBounds := TLightmapBounds.Create(Self); end; destructor TGLMeshLines.Destroy; begin FLines.Free; FLightmapBounds.Free; inherited; end; procedure TGLMeshLines.Loaded; begin DoChanged; end; procedure TGLMeshLines.BeginUpdate; begin inc(FUpdating); end; procedure TGLMeshLines.EndUpdate; begin Dec(FUpdating); if FUpdating < 1 then begin FUpdating := 0; DoChanged; end; end; procedure TGLMeshLines.Clear; begin FSelectedLineItem := nil; FSelectedNode := nil; FLines.Clear; MeshObjects.Clear; StructureChanged; end; procedure TGLMeshLines.BuildList(var rci : TRenderContextInfo); var i,j: Integer; begin inherited; if FShowNodes then begin for i:= 0 to Lines.Count - 1 do begin if Lines[i] = FSelectedLineItem then begin for j := 0 to Lines[i].Nodes.Count-1 do DrawNode(rci, TLineNode(Lines[i].Nodes[j]),Lines[i].Width); end; end; end; end; procedure TGLMeshLines.DoRender(var rci : TRenderContextInfo; renderSelf, renderChildren : Boolean); begin if FNoZWrite then begin GL.Disable(GL_Depth_Test); inherited; GL.Enable(GL_Depth_Test); end else inherited; end; procedure TGLMeshLines.SetShowNodes(const Value: Boolean); begin FShowNodes := Value; DoChanged; end; procedure TGLMeshLines.SetNoZWrite(const Value: Boolean); begin FNoZWrite := Value; DoChanged; end; procedure TGLMeshLines.SetLightmapIndex(const value: Integer); begin FLightmapIndex := Value; DoChanged; end; procedure TGLMeshLines.SetLightmapMaterialName(const value: String); var lLibMaterial: TGLLibMaterial; begin if Value <> '' then begin if assigned(LightmapLibrary) then begin lLibMaterial := LightmapLibrary.Materials.GetLibMaterialByName(Value); if assigned(lLibMaterial) then begin FLightmapIndex := lLibMaterial.ID; FLightmapMaterialName := Value; DoChanged; end; end; end; end; procedure TGLMeshLines.SetLightmapBounds( const value: TLightmapBounds ); begin FLightmapBounds.SetVector(value.X, value.Y,value.Z,value.W); DoChanged; end; procedure TGLMeshLines.DoChanged; begin if Updating then exit; BuildGeometry; StructureChanged; end; procedure TGLMeshLines.BuildGeometry; var i: Integer; lFirstLineDone: Boolean; lVertex: TAffineVector; lTextPoint: TTexPoint; begin if Updating then exit; //clear the mesh FMeshObjects.Clear; lFirstLineDone := False; FMesh := TMeshObject.CreateOwned(FMeshObjects); FMesh.Mode := momFaceGroups; FFaceGroup := TFGVertexIndexList.CreateOwned(FMesh.FaceGroups); FFaceGroup.Mode := fgmmTriangleStrip; FFaceGroup.LightMapIndex := FLightmapIndex; FIndex := 0; for i := 0 to Lines.Count - 1 do begin if not FLines.Items[i].Hide then begin if lFirstLineDone then AddStitchMarker(FFaceGroup.VertexIndices); if TLineItem(FLines.Items[i]).Nodes.Count > 0 then begin BuildLineItem(TLineItem(FLines.Items[i])); lFirstLineDone := True; end; end; end; StitchStrips(FFaceGroup.VertexIndices); //Calculate lightmapping if assigned(LightmapLibrary) and (LightmapIndex <> -1 ) then for i := 0 to FMesh.Vertices.Count - 1 do begin lVertex := FMesh.Vertices.Items[i]; lTextPoint.s := (lVertex.X - FLightmapBounds.Left) / FLightmapBounds.Width; lTextPoint.t := (lVertex.Z - FLightmapBounds.Top) / FLightmapBounds.Height; FMesh.LightMapTexCoords.Add(lTextPoint); end; end; procedure TGLMeshLines.DrawNode(var rci : TRenderContextInfo; Node: TLineNode; LineWidth: Single); var lNodeSize: Single; begin lNodeSize := LineWidth* 0.7; GL.PushMatrix; GL.Translatef(Node.x,Node.y,Node.z); if lNodeSize <>1 then begin GL.PushMatrix; GL.Scalef(lNodeSize, lNodeSize, lNodeSize); /// rci.GLStates.UnSetGLState(stTexture2D); rci.GLStates.UnSetGLState(stColorMaterial); rci.GLStates.UnSetGLState(stBlend); if Node = FSelectedNode then rci.GLStates.SetGLMaterialColors(cmFRONT, clrBlack, clrGray20, clrYellow, clrBlack, 0) else rci.GLStates.SetGLMaterialColors(cmFRONT, clrBlack, clrGray20, clrGreen, clrBlack, 0); DrawCircle(lNodeSize); GL.PopMatrix; end else begin if Node = FSelectedNode then rci.GLStates.SetGLMaterialColors(cmFRONT, clrBlack, clrGray20, clrYellow, clrBlack, 0) else rci.GLStates.SetGLMaterialColors(cmFRONT, clrBlack, clrGray20, clrGreen, clrBlack, 0); DrawCircle(lNodeSize); end; GL.PopMatrix; end; procedure TGLMeshLines.DrawCircle(Radius: Single); var inner,outer,p1,p2: TVector; i: Integer; a: Single; lUp: TAffineVector; begin inner := VectorMake(1, 0, 0); outer := VectorMake(1.3, 0, 0); GL.Begin_(GL_TRIANGLE_STRIP); for i:= 0 to CIRCLESEGMENTS do begin a := i * 2 * pi / CIRCLESEGMENTS; p1 := outer; p2 := inner; lUp := Up.AsAffineVector; RotateVector(p1,lUp, a); RotateVector(p2,lUp, a); GL.Vertex3fv(@p1.X); GL.Vertex3fv(@p2.X); end; GL.End_(); end; function TGLMeshLines.SelectNode(LineItem: TLineItem; X,Z: Single): TLineNode; var i: Integer; lRange: Single; length: single; begin Result := nil; lRange := LineItem.Width * 0.88; for i := 0 to LineItem.Nodes.count - 1 do begin length := 1/RLength((X - LineItem.Nodes[i].X),(Z - LineItem.Nodes[i].Z)); if length < lRange then begin Result := TLineNode(LineItem.Nodes[i]); Break; end; end; end; function TGLMeshLines.SelectLineItem(LineItem: TLineItem): TLineItem; begin Result := nil; FSelectedLineItem := LineItem; FSelectedNode := nil; DoChanged; end; function TGLMeshLines.SelectLineItem(LineNode: TLineNode): TLineItem; begin FSelectedLineItem := TLineItem(LineNode.Collection.Owner); FSelectedNode := LineNode; Result := FSelectedLineItem; DoChanged; end; procedure TGLMeshLines.DeselectLineItem; begin FSelectedLineItem := nil; FSelectedNode := nil; DoChanged; end; procedure TGLMeshLines.DeselectLineNode; begin FSelectedNode := nil; DoChanged; end; function TGLMeshLines.SelectLineItem(const X,Z: Single; Tolerance: single = 1): TLineItem; var i: Integer; lStartPoint: Integer; lNode: TLineNode; lNodeWasSelected: Boolean; begin Result := nil; if Assigned(FSelectedLineItem) and not lNodeWasSelected then lStartPoint := FSelectedLineItem.ID + 1 else lStartPoint := 0; for i := lStartPoint to FLines.Count - 1 do begin if (FLines[i] <> FSelectedLineItem) or lNodeWasSelected then begin if PointNearLine(FLines[i],X,Z,Tolerance) then begin Result := FLines[i]; lNode := SelectNode(FLines[i], X,Z); if lNode <> FSelectedNode then begin FSelectedNode := lNode; end; break; end; end; end; if not Assigned(Result) then begin for i := 0 to lStartPoint - 1 do begin if FLines[i] <> FSelectedLineItem then begin if PointNearLine(FLines[i],X,Z,Tolerance) then begin Result := FLines[i]; break; end; end; end; end; FSelectedLineItem := Result; if not assigned(FSelectedLineItem) then begin FSelectedNode := nil; FNode1 := nil; FNode2 := nil; end; DoChanged; end; function TGLMeshLines.GetUpdating: Boolean; begin Result := FUpdating > 0; end; function TGLMeshLines.PointNearLine(const LineItem: TLineItem; const X,Z: Single; Tolerance: single = 1): boolean; var i: Integer; lStartNode,lEndNode: TLineNode; begin Result := False; for i := 0 to LineItem.Nodes.Count - 2 do begin lStartNode := TLineNode(LineItem.Nodes[i]); lEndNode := TLineNode(LineItem.Nodes[i+1]); if PointNearSegment(lStartNode,lEndNode,X,Z,LineItem.Width,Tolerance) then begin Result := True; FNode1 := lStartNode; FNode2 := lEndNode; break; end; end; end; function TGLMeshLines.PointNearSegment(const StartNode, EndNode: TLineNode; const X,Z: Single; LineWidth: single; Tolerance: single = 1): boolean; var xt, yt, u, len: single; xp, yp: single; lDist: Single; begin Result:= false; lDist := (LineWidth/2) * Tolerance; xt:= EndNode.X - StartNode.X; yt:= EndNode.Z - StartNode.Z; len:= sqrt(xt*xt + yt*yt); xp:= (X - StartNode.X); yp:= (Z - StartNode.Z); u:= (xp * xt + yp * yt) / len; // point beyond line if (u < -lDist) or (u > len+lDist) then exit; u:= u / len; // get the point on the line that's pependicular to the point in question xt:= StartNode.X + xt * u; yt:= StartNode.Z + yt * u; // find the distance to the line, and see if it's closer than the specified distance Result:= sqrt(sqr(xt - X) + sqr(yt - Z)) <= lDist; end; procedure TGLMeshLines.StitchStrips(idx: TIntegerList); var i: integer; i0, i1, i2: integer; begin for i := idx.Count - 1 downto 0 do begin if idx[i] = -1 then begin i0:= idx[i-1]; i1:= idx[i+4]; i2:= idx[i+5]; idx[i]:= i0; idx[i+1]:= i1; idx[i+2]:= i1; idx[i+3]:= i2; end; end; end; procedure TGLMeshLines.AddStitchMarker(idx: TIntegerList); begin idx.Add(-1); idx.Add(-2); idx.Add(-2); idx.Add(-2); end; procedure TGLMeshLines.NotifyChange(Sender : TObject); begin inherited; DoChanged; end; procedure TGLMeshLines.AddIndex; begin FFaceGroup.Add(FIndex); inc(FIndex); end; procedure TGLMeshLines.AddVertices(Up,Inner,Outer: TAffineVector; S: Single; Correction: Single; UseDegenerate: Boolean; LineItem: TLineItem); begin if not LineItem.TextureCorrection then Correction := 0 else Correction := Correction / (LineItem.TextureLength / LineItem.width); FMesh.Normals.Add(Up); FMesh.Vertices.Add(Outer); FMesh.TexCoords.Add(S-Correction,1); AddIndex; FMesh.Normals.Add(Up); FMesh.TexCoords.Add(S+Correction,0); FMesh.Vertices.Add(Inner); AddIndex; if LineItem.TextureCorrection then begin FMesh.Normals.Add(Up); FMesh.Vertices.Add(Outer); FMesh.TexCoords.Add(S+Correction,1); AddIndex; FMesh.Normals.Add(Up); FMesh.TexCoords.Add(S-Correction,0); FMesh.Vertices.Add(Inner); AddIndex; end; end; procedure TGLMeshLines.BuildLineItem(LineItem: TLineItem); var Seg1: TAffineVector; Seg2: TAffineVector; NSeg1: TAffineVector; NSeg2: TAffineVector; N1,N2,N3: TAffineVector; Inner: TAffineVector; Outer: TAffineVector; lUp: TAffineVector; lAngle: Single; lAngleOffset: Single; lTotalAngleChange: Single; lBreakAngle: Single; i: Integer; Flip: Boolean; s: single; lSpline: TCubicSpline; lCount: Integer; f : Single; a, b, c : Single; lHalfLineWidth: single; begin inherited; lTotalAngleChange := 0; lHalfLineWidth := LineItem.Width/2; lBreakAngle := DegToRadian(LineItem.BreakAngle); try N1 := AffineVectorMake(0,0,0); N2 := AffineVectorMake(0,0,0); N3 := AffineVectorMake(0,0,0); s:= 0; f := 0; lSpline := nil; lUp := Up.AsAffineVector; lCount := 0; if LineItem.SplineMode = lsmLines then lCount := LineItem.Nodes.Count - 1 else if LineItem.Nodes.Count > 1 then begin lCount := (LineItem.Nodes.Count-1) * LineItem.Division; lSpline := LineItem.Nodes.CreateNewCubicSpline; f:=1/LineItem.Division; end; for i := 0 to lCount do begin if LineItem.SplineMode = lsmLines then begin N3 := LineItem.Nodes.Items[i].AsAffineVector end else begin if lCount > 1 then begin lSpline.SplineXYZ(i*f, a, b, c); N3 := AffineVectorMake(a,b,c); end; end; if i > 0 then begin Seg1 := Seg2; Seg2 := VectorSubtract(N3,N2); end; if (i = 1) and not VectorEQuals(Seg2,NullVector)then begin //Create start vertices //this makes the assumption that these vectors are different which not always true Inner := VectorCrossProduct(Seg2, lUp); NormalizeVector(Inner); ScaleVector(Inner,lHalfLineWidth); Outer := VectorNegate(Inner); AddVector(Inner,N2); AddVector(Outer,N2); AddVertices(lUp,Inner, Outer,S,0,False,LineItem); s := s + VectorLength(Seg2)/LineItem.TextureLength; end; if i > 1 then begin lUp := VectorCrossProduct(Seg2,Seg1); if VectorEquals(lUp, NullVector) then lUp := Up.AsAffineVector; Flip := VectorAngleCosine(lUp,Self.up.AsAffineVector) < 0; if Flip then NegateVector(lUp); NSeg1 := VectorNormalize(Seg1); NSeg2 := VectorNormalize(Seg2); if VectorEquals(NSeg1,NSeg2) then begin Inner := VectorCrossProduct(Seg2, lUp); lAngle := 0; end else begin Inner := VectorSubtract(NSeg2,NSeg1); lAngle := (1.5707963 - ArcCosine(VectorLength(Inner)/2)); end; lTotalAngleChange := lTotalAngleChange + (lAngle * 2); //Create intermediate vertices if (lTotalAngleChange > lBreakAngle) or (LineItem.BreakAngle = -1 )then begin lTotalAngleChange := 0; //Correct width for angles less than 170 if lAngle < 1.52 then lAngleOffset := lHalfLineWidth * sqrt(sqr(Tangent(lAngle))+1) else lAngleOffset := lHalfLineWidth; NormalizeVector(Inner); ScaleVector(Inner,lAngleOffset); Outer := VectorNegate(Inner); AddVector(Inner,N2); AddVector(Outer,N2); if not Flip then AddVertices(lUp,Inner, Outer,S,-Tangent(lAngle)/2,True, LineItem) else AddVertices(lUp,Outer, Inner,S,Tangent(lAngle)/2,True, LineItem); end; s:= s + VectorLength(seg2)/LineItem.TextureLength; end; //Create last vertices if (lCount > 0) and (i = lCount) and not VectorEQuals(Seg2,NullVector) then begin lUp := Up.AsAffineVector; Inner := VectorCrossProduct(Seg2, lUp); NormalizeVector(Inner); ScaleVector(Inner,lHalfLineWidth); Outer := VectorNegate(Inner); AddVector(Inner,N3); AddVector(Outer,N3); AddVertices(lUp,Inner, Outer,S,0,False, LineItem); end; N1 := N2; N2 := N3; end; except on e: Exception do raise exception.Create(e.Message); end; if assigned(lSpline) then lSpline.Free; end; initialization RegisterClasses([TGLMeshLines]); end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/primitives/transaction.h // Bitcoin file: src/primitives/transaction.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_SerializeTransaction; interface implementation template<typename Stream, typename TxType> inline void SerializeTransaction(const TxType& tx, Stream& s) { const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS); s << tx.nVersion; unsigned char flags = 0; // Consistency check if (fAllowWitness) { /* Check whether witnesses need to be serialized. */ if (tx.HasWitness()) { flags |= 1; } } if (flags) { /* Use extended format in case witnesses are to be serialized. */ std::vector<CTxIn> vinDummy; s << vinDummy; s << flags; } s << tx.vin; s << tx.vout; if (flags & 1) { for (size_t i = 0; i < tx.vin.size(); i++) { s << tx.vin[i].scriptWitness.stack; } } s << tx.nLockTime; } end.
unit MainCrypt; {$mode objfpc}{$H+} interface uses Classes, Controls, CustomCrypt, Dialogs, ExtCtrls, FileUtil, Forms, Graphics, md5, Menus, SQLiteWrap, SysUtils; const // Названия столбцов таблиц SQL_COL_ID_USER = 'ID_USER'; SQL_COL_ID_FRIEND = 'ID_FRIEND'; SQL_COL_AUTH = 'AUTH'; SQL_COL_UUID = 'UUID'; SQL_COL_NICK_NAME = 'NNAME'; SQL_COL_EMAIL = 'EMAIL'; SQL_COL_AVATAR = 'ADATA'; SQL_COL_RESP_DATE = 'RDATE'; SQL_COL_XID = 'XID'; SQL_COL_IS_MYMSG = 'ISMY'; SQL_COL_OPEN_KEY = 'OPEN'; SQL_COL_SECRET_KEY = 'SECRET'; SQL_COL_BF_KEY = 'BF'; SQL_COL_ZIP_DATA = 'ZDATA'; SQL_COL_HASH = 'HASH'; SQL_COL_MESSAGE = 'MESSAGE'; // Таблицы SQL_TBL_USERS = 'USERS'; SQL_TBL_FRIENDS = 'FRIENDS'; SQL_TBL_MESSAGES = 'MESSAGES'; // Сообщения о ошибках ERROR_SQL_LOGIN = 'Ошибка аутентификации =('; type TUserEntry = record // Первичные Ключи ID_USER: integer; // Ник, Имя, Фамилия, Эл. почта, Хэш SHA1 от пароля и Ава NickName, Email, HashPwd: string; Avatar: TPicture; end; TFriendEntry = record // Первичные Ключи ID_USER, ID_FRIEND: integer; Auth: boolean; // У каждого друга свой UUID UUID, // Ник, Имя, Фамилия, Эл. почта и Ава NickName, Email: string; Avatar: TPicture; end; TMessageEntry = record // Первичные Ключи ID_USER, ID_FRIEND: integer; // Время отправки / получения Date: TDateTime; // Порядковый номер сообщения XID: integer; // True если отправляли мы IsMyMsg: boolean; // Криптографические Ключи OpenKey, SecretKey, BFKey, // Сообщение Message, // Файлы Files: string; end; type { TMainCrypt } TMainCrypt = class(TCustomCrypt) {* Графический компонент + Вход в систему (шифровка\расшифровка полей БД при верном пароле) + Аутентификация (Запрос аутентификация и отлов подтверждения) + Отправка и чтение сообщений + Нужно замутить что-то вроде *} private fLogin: boolean; // Залогинились или не? fUser: TUserEntry; // Информация о себе fPathDb: string; //* ======================================================================== *// SQLDataBase: TSqliteDatabase; SQLTable: TSqliteTable; procedure CreateDataBaseTables; //* ======================================================================== *// function GetFriendEntry(Index: integer): TFriendEntry; function GetUserEntry(Index: integer): TUserEntry; procedure SetFriendEntry(Index: integer; AFriend: TFriendEntry); public function TextReadFile(FileName: string): string; function Base64ReadFile(FileName: string): string; procedure CreateAndWrite(FilePath, AData: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //* ======================================================================== *// function OpenDB(FileName: string): boolean; // Создание базы данных function WriteDB(ASQL: string): boolean; // Запись в базу данных function GetDBFilePath: string; function AssignDB: boolean; //* ======================================================================== *// function GetUserInfo: TUserEntry; // Получение данных пользователя function AddUser(AUser: TUserEntry): boolean; // Добавление нового пользователя function GetCountUsers: integer; // Количество пользователей function ExistUser(AEMail: string): boolean; // Проверка на наличие function LoginUser(AUser: TUserEntry): boolean; overload; virtual; function LoginUser(AEMail, APassword: string): boolean; overload; virtual; function UpdateUser(AUser: TUserEntry): boolean; procedure SetUserImage(AUser: integer; AFileName: string); function GetUserImage(AUser: integer; AFileName: string): boolean; property Users[Index: integer]: TUserEntry read GetUserEntry; //* ======================================================================== *// function AddFriend(AFriend: TFriendEntry): boolean; virtual; function GetCountFriend: integer; function ExistFriend(AEMail: string): boolean; function DeleteFriend(Index: integer): boolean; function UpdateFriend(AFriend: TFriendEntry): boolean; procedure SetFriendImage(AFriendID: integer; AFileName: string); function GetFriendImage(AFriendID: integer; AFileName: string): boolean; property Friend[Index: integer]: TFriendEntry read GetFriendEntry write SetFriendEntry; default; //* ======================================================================== *// function AddMessage(AMsg: TMessageEntry): boolean; function GetCountMessage(AFriendID: integer): integer; function GetMaxXid(AFriendID: integer): integer; function GetMessageEntry(Index, AFriendID: integer): TMessageEntry; // Найти последний открытый ключ товарища function GetLastOpenKey(AFriendID: integer): string; // Найти свой последний закрытый ключ function GetLastPrivateKey(AFriendID: integer): string; //* ======================================================================== *// { TODO : Нужно будет перенести функции из MainCrypt в MailCrypt, а именно MakeFirstMail, ReadFirstMail, MakeMail, ReadMail } function MakeFirstMail(AFolder: string; AFriendID: integer): boolean; function ReadFirstMail(AFolder: string; AFriendID: integer): boolean; function MakeMail(AFolder, AText, AFiles: string; AFriendID: integer): boolean; function ReadMail(AFolder: string; AFriendID: integer): boolean; function ReadMail(AFolder: string; AFriendID: integer; ADate: TDateTime): boolean; procedure DeleteCryptFiles(AFolder: string); published property isUserLogin: boolean read fLogin; end; implementation { TMainCrypt } procedure TMainCrypt.CreateAndWrite(FilePath, AData: string); var hFile: TextFile; szBuf: string; ch: char; begin AssignFile(hFile, FilePath); Rewrite(hFile); szBuf := ''; for ch in AData do begin if ch = #13 then szBuf += #10 else szBuf += ch; end; Write(hFile, szBuf); CloseFile(hFile); end; function TMainCrypt.Base64ReadFile(FileName: string): string; var hFile: TextFile; Buf: string; begin Result := ''; Base64Encode(FileName, FileName + '.b64'); AssignFile(hFile, FileName + '.b64'); Reset(hFile); while not EOF(hFile) do begin ReadLn(hFile, Buf); Result := Result + Buf + #10; end; CloseFile(hFile); DeleteFile(FileName + '.b64'); Result := trim(Result); end; function TMainCrypt.TextReadFile(FileName: string): string; var hFile: TextFile; Buf: string; begin Result := ''; AssignFile(hFile, FileName); Reset(hFile); while not EOF(hFile) do begin ReadLn(hFile, Buf); Result := Result + Buf + #10; end; CloseFile(hFile); Result := trim(Result); end; constructor TMainCrypt.Create(AOwner: TComponent); begin inherited Create(AOwner); fPathDb := ''; fLogin := False; end; function TMainCrypt.OpenDB(FileName: string): boolean; begin Result := True; if Assigned(SQLDataBase) then SQLDataBase.Free; try SQLDataBase := TSqliteDatabase.Create(FileName); fPathDb := FileName; fLogin := False; CreateDataBaseTables; except Result := False; end; end; function TMainCrypt.WriteDB(ASQL: string): boolean; begin Result := True; try SQLDataBase.ExecSQL(ASQL); except Result := False; end; end; function TMainCrypt.GetDBFilePath: string; begin Result := fPathDb; end; function TMainCrypt.AssignDB: boolean; begin Result := (fPathDb <> ''); end; function TMainCrypt.GetUserInfo: TUserEntry; begin Result := fUser; end; function TMainCrypt.ExistUser(AEMail: string): boolean; begin Result := False; try SQLTable := SQLDataBase.GetTable('SELECT EMAIL FROM USERS'); try while not SQLTable.EOF do begin if AEMail = SQLTable.FieldAsString(SQLTable.FieldIndex['EMAIL']) then Result := True; SQLTable.Next; end; finally SQLTable.Free; end; finally end; end; function TMainCrypt.GetUserEntry(Index: integer): TUserEntry; begin Result.ID_USER := -1; try SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_USERS); try while not SQLTable.EOF do begin if (int64(Index) + 1) = SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]) then begin Result.ID_USER := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]); Result.NickName := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_NICK_NAME]); Result.Email := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_EMAIL]); Result.HashPwd := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_HASH]); end; SQLTable.Next; end; finally SQLTable.Free; end; finally end; end; function TMainCrypt.LoginUser(AUser: TUserEntry): boolean; begin Result := False; try SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_USERS); try while not SQLTable.EOF do begin if (AUser.Email = SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_EMAIL])) and (MD5Print(MD5String(AUser.HashPwd)) = SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_HASH])) then begin fUser.ID_USER := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]); fUser.NickName := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_NICK_NAME]); fUser.Email := AUser.Email; fUser.HashPwd := AUser.HashPwd; Result := True; fLogin := True; end; SQLTable.Next; end; finally SQLTable.Free; end; finally end; end; function TMainCrypt.LoginUser(AEMail, APassword: string): boolean; var TmpUser: TUserEntry; begin TmpUser.Email := AEMail; TmpUser.HashPwd := APassword; Result := LoginUser(TmpUser); end; function TMainCrypt.UpdateUser(AUser: TUserEntry): boolean; begin // UPDATE USERS SET NNAME = "RCode", FNAME = "Anton" WHERE ID_USER = 2; Result := False; try SQLTable := SQLDataBase.GetTable('UPDATE ' + SQL_TBL_USERS + ' SET ' + SQL_COL_EMAIL + ' = "' + AUser.Email + '", ' + SQL_COL_NICK_NAME + ' = "' + AUser.NickName + '"' + ' WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(fUser.ID_USER) + '";'); SQLTable.Free; if LoginUser(AUser.Email, fUser.HashPwd) then Result := True; except raise Exception.Create('Не могу найти пользователя...'); end; end; procedure TMainCrypt.SetUserImage(AUser: integer; AFileName: string); begin WriteDB('UPDATE ' + SQL_TBL_USERS + ' SET ' + SQL_COL_AVATAR + ' = "' + Base64ReadFile(AFileName) + '" WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(AUser + 1) + '";'); end; function TMainCrypt.GetUserImage(AUser: integer; AFileName: string): boolean; var hFile: TextFile; ch: char; szBuf, szBase: string; begin try szBase := ''; Result := True; SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_USERS + ' WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(AUser + 1) + '";'); try AssignFile(hFile, AFileName + '.cr'); ReWrite(hFile); szBase := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_AVATAR]); if szBase = '' then begin Result := False; exit; end; szBuf := ''; for ch in szBase do begin if ch = #13 then szBuf += #10 else szBuf += ch; end; Write(hFile, szBuf); Close(hFile); Base64Decode(AFileName + '.cr', AFileName); finally SQLTable.Free; end; finally DeleteFile(AFileName + '.cr'); end; end; procedure TMainCrypt.SetFriendImage(AFriendID: integer; AFileName: string); begin WriteDB('UPDATE ' + SQL_TBL_FRIENDS + ' SET ' + SQL_COL_AVATAR + ' = "' + Base64ReadFile(AFileName) + '" WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '" AND ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriendID + 1) + '";'); end; function TMainCrypt.GetFriendImage(AFriendID: integer; AFileName: string): boolean; var hFile: TextFile; ch: char; szBuf, szBase: string; begin try szBase := ''; Result := True; SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_FRIENDS + ' WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '" AND ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriendID + 1) + '";'); try AssignFile(hFile, AFileName + '.cr'); ReWrite(hFile); szBase := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_AVATAR]); if szBase = '' then begin Result := False; exit; end; szBuf := ''; for ch in szBase do begin if ch = #13 then szBuf += #10 else szBuf += ch; end; Write(hFile, szBuf); Close(hFile); Base64Decode(AFileName + '.cr', AFileName); finally SQLTable.Free; end; finally DeleteFile(AFileName + '.cr'); end; end; function TMainCrypt.AddFriend(AFriend: TFriendEntry): boolean; var FCount: integer; Res: HResult; Uid: TGuid; begin // INSERT INTO FRIENDS VALUES (1, 2, "86AE072A-941F-408A-BD99-4C2E4845C291", "ANNA", "ANNA", "SINICYANA", "ANNA@MAIL.RU", ""); Result := True; Res := CreateGUID(Uid); if Res = S_OK then begin FCount := GetCountFriend() + 1; WriteDB('INSERT INTO ' + SQL_TBL_FRIENDS + ' VALUES ("' + IntToStr(FCount) + '", "' + IntToStr(GetUserInfo.ID_USER) + '", ' + '"' + GUIDToString(Uid) + '", ' + '"' + AFriend.NickName + '", ' + '"' + AFriend.EMail + '", "");'); end else Result := False; end; function TMainCrypt.GetCountFriend: integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_FRIENDS + ' WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); try while not SQLTable.EOF do begin Inc(Result, 1); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create('Не могу узнать количество Ваших контактов...'); end; end; function TMainCrypt.ExistFriend(AEMail: string): boolean; var i: integer; begin Result := False; for i := 0 to GetCountFriend - 1 do if GetFriendEntry(i).Email = AEMail then Result := True; end; function TMainCrypt.DeleteFriend(Index: integer): boolean; var FCount, i: integer; begin Result := False; try FCount := GetCountFriend; if Index > FCount - 1 then exit; if Index < 0 then Exit; // 1. Удалить друга и сообщения WriteDB('DELETE FROM ' + SQL_TBL_MESSAGES + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(Index + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); WriteDB('DELETE FROM ' + SQL_TBL_FRIENDS + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(Index + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); // 2. Скорректировать индексы for I := Index + 2 to FCount do begin //WriteDB('UPDATE '+SQL_TBL_MESSAGES+' WHERE '+SQL_COL_ID_FRIEND+' = '+IntToStr(I-1)); WriteDB('UPDATE ' + SQL_TBL_FRIENDS + ' SET ' + SQL_COL_ID_FRIEND + ' = ' + IntToStr(I - 1) + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(I) + '";'); // Надо проверить на сообщениях WriteDB('UPDATE ' + SQL_TBL_MESSAGES + ' SET ' + SQL_COL_ID_FRIEND + ' = ' + IntToStr(I - 1) + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(I) + '";'); end; Result := True; except Result := False; end; end; function TMainCrypt.UpdateFriend(AFriend: TFriendEntry): boolean; begin // UPDATE USERS SET NNAME = "RCode", FNAME = "Anton" WHERE ID_USER = 2; // ID Friend меньше на единицу чем в таблице, таким образом от 0 до count - 1 Result := False; try SQLTable := SQLDataBase.GetTable('UPDATE ' + SQL_TBL_FRIENDS + ' SET ' + SQL_COL_EMAIL + ' = "' + AFriend.Email + '", ' + SQL_COL_NICK_NAME + ' = "' + AFriend.NickName + '"' + ' WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '" AND ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriend.ID_FRIEND + 1) + '";'); SQLTable.Free; Result := True; except raise Exception.Create('Не могу изменить информацию о друге...'); end; end; function TMainCrypt.AddMessage(AMsg: TMessageEntry): boolean; var szIsMy: string; begin Result := True; try if AMsg.IsMyMsg then szIsMy := 'TRUE' else szIsMy := 'FALSE'; WriteDB('INSERT INTO ' + SQL_TBL_MESSAGES + ' VALUES("' + IntToStr(AMsg.ID_FRIEND) + '", "' + IntToStr(GetUserInfo.ID_USER) + '", ' + '"' + DateTimeToStr(AMsg.Date) + '", ' + '"' + IntToStr(AMsg.XID) + '", ' + '"' + szIsMy + '", ' + '"' + AMsg.OpenKey + '", ' + '"' + AMsg.SecretKey + '", ' + '"' + AMsg.BFKey + '", ' + '"' + AMsg.Message + '", ' + '"' + AMsg.Files + '");'); except Result := False; end; end; function TMainCrypt.GetCountMessage(AFriendID: integer): integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_MESSAGES + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriendID + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); try while not SQLTable.EOF do begin Inc(Result, 1); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create('Не могу узнать количество сообщений...'); end; end; function TMainCrypt.GetMaxXid(AFriendID: integer): integer; var aMax: integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_MESSAGES + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriendID + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); try while not SQLTable.EOF do begin aMax := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_XID]); if aMax > Result then Result := aMax; SQLTable.Next; end; finally SQLTable.Free; Result := aMax; end; except raise Exception.Create('Не могу узнать XID сообщений...'); end; end; function TMainCrypt.AddUser(AUser: TUserEntry): boolean; var Count: integer; begin if fPathDb = '' then begin Result := False; Exit; end; Result := True; try Count := GetCountUsers() + 1; if not ExistUser(AUser.Email) then begin WriteDB('INSERT INTO ' + SQL_TBL_USERS + ' VALUES ("' + IntToStr(Count) + '", "' + AUser.NickName + '", "' + AUser.EMail + '", "' + MD5Print(MD5String(AUser.HashPwd)) + '", "");'); end else Result := False; except Result := False; end; end; function TMainCrypt.GetCountUsers: integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_USERS); try while not SQLTable.EOF do begin Inc(Result, 1); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create('Не могу узнать количество пользователей программы...'); end; end; procedure TMainCrypt.CreateDataBaseTables; begin // Таблица users SQLDataBase.ExecSQL('CREATE TABLE IF NOT EXISTS ' + SQL_TBL_USERS + '(' + SQL_COL_ID_USER + ' INTEGER, ' + SQL_COL_NICK_NAME + ', ' + SQL_COL_EMAIL + ', ' + SQL_COL_HASH + ' TEXT, ' + SQL_COL_AVATAR + ' BLOB);'); // Таблица friends SQLDataBase.ExecSQL('CREATE TABLE IF NOT EXISTS ' + SQL_TBL_FRIENDS + '(' + SQL_COL_ID_FRIEND + ', ' + SQL_COL_ID_USER + ' INTEGER, ' + SQL_COL_UUID + ', ' + SQL_COL_NICK_NAME + ', ' + SQL_COL_EMAIL + ' TEXT, ' + SQL_COL_AVATAR + ' BLOB);'); // Таблица messages SQLDataBase.ExecSQL('CREATE TABLE IF NOT EXISTS ' + SQL_TBL_MESSAGES + '(' + SQL_COL_ID_FRIEND + ' INTEGER,' + SQL_COL_ID_USER + ' INTEGER, ' + SQL_COL_RESP_DATE + ' TEXT, ' + SQL_COL_XID + ' INTEGER, ' + SQL_COL_IS_MYMSG + ', ' + SQL_COL_OPEN_KEY + ', ' + SQL_COL_SECRET_KEY + ',' + SQL_COL_BF_KEY + ',' + SQL_COL_MESSAGE + ', ' + SQL_COL_ZIP_DATA + ' TEXT);'); { // Таблица users SQLDataBase.ExecSQL ('CREATE TABLE IF NOT EXISTS '+SQL_TBL_USERS+'('+ SQL_COL_ID_USER+' INTEGER, '+SQL_COL_NICK_NAME+', '+ SQL_COL_EMAIL+', '+SQL_COL_HASH+ ' TEXT, '+SQL_COL_AVATAR+' BLOB, PRIMARY KEY('+SQL_COL_ID_USER+'));'); // Таблица friends SQLDataBase.ExecSQL ('CREATE TABLE IF NOT EXISTS '+SQL_TBL_FRIENDS+ '('+SQL_COL_ID_FRIEND+', '+ SQL_COL_ID_USER+' INTEGER, '+SQL_COL_UUID+', ' + SQL_COL_NICK_NAME + ', '+SQL_COL_EMAIL+' TEXT, '+SQL_COL_AVATAR+' BLOB, PRIMARY KEY('+ SQL_COL_ID_FRIEND+'), FOREIGN KEY (' + SQL_COL_ID_USER+ ') REFERENCES '+SQL_TBL_USERS+'('+SQL_COL_ID_USER+'));'); // Таблица messages SQLDataBase.ExecSQL ('CREATE TABLE IF NOT EXISTS ' + SQL_TBL_MESSAGES + '('+SQL_COL_ID_FRIEND+' INTEGER,' + SQL_COL_ID_USER+' INTEGER, '+ SQL_COL_RESP_DATE+' TEXT, '+SQL_COL_XID+' INTEGER, '+ SQL_COL_IS_MYMSG+', '+SQL_COL_OPEN_KEY+', '+SQL_COL_SECRET_KEY+ ','+SQL_COL_BF_KEY+',' + SQL_COL_MESSAGE+', '+SQL_COL_ZIP_DATA+ ' TEXT, FOREIGN KEY ('+SQL_COL_ID_FRIEND+ ') REFERENCES FRIENDS('+SQL_COL_ID_FRIEND+'));'); } end; function TMainCrypt.GetMessageEntry(Index, AFriendID: integer): TMessageEntry; var szIsMy: string; CurrInd: integer; begin Result.ID_FRIEND := -1; try if (Index < 0) or (Index > GetCountMessage(AFriendID)) then exit; if (AFriendID < 0) or (AFriendID > GetCountFriend) then exit; SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_MESSAGES + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriendID + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); try CurrInd := -1; while not SQLTable.EOF do begin Inc(CurrInd, 1); if CurrInd = Index then begin Result.ID_FRIEND := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_FRIEND]); Result.ID_USER := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]); Result.Date := StrToDateTime(SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_RESP_DATE])); Result.XID := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_XID]); szIsMy := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_IS_MYMSG]); Result.IsMyMsg := (szIsMy = 'TRUE'); Result.Message := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_MESSAGE]); Result.Files := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_ZIP_DATA]); Result.OpenKey := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_OPEN_KEY]); Result.SecretKey := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_SECRET_KEY]); Result.BFKey := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_BF_KEY]); end; SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create('Не могу найти сообщение...'); end; end; function TMainCrypt.GetLastOpenKey(AFriendID: integer): string; var i, Count: integer; Msg: TMessageEntry; begin Result := ''; Count := GetCountMessage(AFriendID); for i := Count downto 0 do begin Msg := GetMessageEntry(i, AFriendID); if not Msg.IsMyMsg then Result := trim(Msg.OpenKey); end; end; function TMainCrypt.GetLastPrivateKey(AFriendID: integer): string; var i, Count: integer; Msg: TMessageEntry; begin Result := ''; Count := GetCountMessage(AFriendID); for i := Count downto 0 do begin Msg := GetMessageEntry(i, AFriendID); if Msg.IsMyMsg then Result := trim(Msg.SecretKey); end; end; function TMainCrypt.MakeFirstMail(AFolder: string; AFriendID: integer): boolean; var AMsg: TMessageEntry; begin Result := False; try // Создаём ключи GenRsaKeys(AFolder + 'Priv.key', AFolder + 'Pub.key', 2048); GenBfPassword(AFolder + 'BFKEY.TXT'); // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND := AFriendID + 1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.IsMyMsg := True; AMsg.XID := 1; AMsg.Message := ''; AMsg.OpenKey := TextReadFile(AFolder + 'Pub.key'); AMsg.SecretKey := Base64ReadFile(AFolder + 'Priv.key'); AMsg.BFKey := TextReadFile(AFolder + 'BFKEY.TXT'); AMsg.Files := ''; AddMessage(AMsg); if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOK, mbCancel], 0) = mrOk then begin DeleteFile(AFolder + 'Pub.key'); DeleteFile(AFolder + 'Priv.key'); DeleteFile(AFolder + 'Priv.key.b64'); DeleteFile(AFolder + 'BFKEY.TXT'); end; finally Result := True; end; end; function TMainCrypt.ReadFirstMail(AFolder: string; AFriendID: integer): boolean; var AMsg: TMessageEntry; begin Result := False; try // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND := AFriendID + 1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.IsMyMsg := False; AMsg.XID := 1; AMsg.Message := ''; AMsg.OpenKey := TextReadFile(AFolder + 'Pub.key'); AMsg.SecretKey := ''; AMsg.BFKey := TextReadFile(AFolder + 'BFKEY.TXT'); AMsg.Files := ''; AddMessage(AMsg); if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOK, mbCancel], 0) = mrOk then begin DeleteFile(AFolder + 'Pub.key'); DeleteFile(AFolder + 'BFKEY.TXT'); end; finally Result := True; end; end; function TMainCrypt.MakeMail(AFolder, AText, AFiles: string; AFriendID: integer): boolean; var StringList: TStringList; i: integer; AMsg: TMessageEntry; begin Result := False; try // Создаём ключи GenRsaKeys(AFolder + 'Priv.key', AFolder + 'Pub.key', 2048); GenBfPassword(AFolder + 'BFKEY.TXT'); CreateAndWrite(AFolder + 'friend.pem', GetLastOpenKey(AFriendID)); // Подготавливаем файлы CreateAndWrite(AFolder + 'MSG.TXT', AText); StringList := TStringList.Create; StringList.Text := AFiles; for i := 0 to StringList.Count - 1 do begin MakeBz2(StringList[i], AFolder + 'FILES.bz2'); //ShowMessage('StringList: ' + StringList[i]); //ShowMessage('Path to BZ: ' + AFolder+'FILES.bz2'); end; // Шифруем все файлы BlowFish, в том числе и свой новый публичный ключ EncryptFileBf(AFolder + 'BFKEY.TXT', AFolder + 'FILES.bz2', AFolder + 'FILES.enc'); EncryptFileBf(AFolder + 'BFKEY.TXT', AFolder + 'MSG.TXT', AFolder + 'MSG.enc'); EncryptFileBf(AFolder + 'BFKEY.TXT', AFolder + 'Pub.key', AFolder + 'Pub.enc'); // Нужно получить последний открытый ключ от друга // из истории переписки и им зашифровать ключ BlowFish EncryptFile(AFolder + 'friend.pem', AFolder + 'BFKEY.TXT', AFolder + 'BFKEY.enc'); // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND := AFriendID + 1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.IsMyMsg := True; AMsg.XID := GetMaxXid(AFriendID) + 1; AMsg.Message := TextReadFile(AFolder + 'MSG.TXT'); AMsg.OpenKey := TextReadFile(AFolder + 'Pub.key'); AMsg.SecretKey := Base64ReadFile(AFolder + 'Priv.key'); AMsg.BFKey := TextReadFile(AFolder + 'BFKEY.TXT'); AMsg.Files := Base64ReadFile(AFolder + 'FILES.bz2'); AddMessage(AMsg); // Чистим за собой //ShowMessage('Сча всё удалю'); StringList.Free; //if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOk, mbCancel], 0) = mrOK then begin DeleteFile(AFolder + 'FILES.bz2.b64'); DeleteFile(AFolder + 'MSG.TXT.b64'); DeleteFile(AFolder + 'Pub.key.b64'); DeleteFile(AFolder + 'Priv.key.b64'); DeleteFile(AFolder + 'FILES.bz2'); DeleteFile(AFolder + 'MSG.TXT'); DeleteFile(AFolder + 'Pub.key'); DeleteFile(AFolder + 'Priv.key'); DeleteFile(AFolder + 'friend.pem'); DeleteFile(AFolder + 'BFKEY.TXT'); end; finally Result := True; end; end; function TMainCrypt.ReadMail(AFolder: string; AFriendID: integer): boolean; begin Result := ReadMail(AFolder, AFriendID, Now); end; function TMainCrypt.ReadMail(AFolder: string; AFriendID: integer; ADate: TDateTime): boolean; var AMsg: TMessageEntry; begin Result := False; try // Создаём ключи CreateAndWrite(AFolder + 'MyPrivate.KEY', GetLastPrivateKey(AFriendID)); Base64Decode(AFolder + 'MyPrivate.KEY', AFolder + 'Private.KEY'); DecryptFile(AFolder + 'Private.KEY', AFolder + 'BFKEY.enc', AFolder + 'BFKEY.TXT'); DecryptFileBf(AFolder + 'BFKEY.TXT', AFolder + 'FILES.enc', AFolder + 'FILES.bz2'); DecryptFileBf(AFolder + 'BFKEY.TXT', AFolder + 'MSG.enc', AFolder + 'MSG.TXT'); DecryptFileBf(AFolder + 'BFKEY.TXT', AFolder + 'Pub.enc', AFolder + 'Pub.key'); // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND := AFriendID + 1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := ADate; AMsg.IsMyMsg := False; AMsg.XID := GetMaxXid(AFriendID); AMsg.Message := TextReadFile(AFolder + 'MSG.TXT'); AMsg.OpenKey := TextReadFile(AFolder + 'Pub.key'); AMsg.SecretKey := ''; AMsg.BFKey := TextReadFile(AFolder + 'BFKEY.TXT'); AMsg.Files := Base64ReadFile(AFolder + 'FILES.bz2'); AddMessage(AMsg); // Чистим за собой //ShowMessage('Сча всё удалю'); finally //Exception.Create('Чтение файлов - не завершено'); Result := True; end; end; procedure TMainCrypt.DeleteCryptFiles(AFolder: string); begin DeleteFile(AFolder + 'FILES.bz2.b64'); DeleteFile(AFolder + 'MSG.TXT.b64'); DeleteFile(AFolder + 'Pub.key.b64'); DeleteFile(AFolder + 'Priv.key.b64'); DeleteFile(AFolder + 'FILES.bz2'); DeleteFile(AFolder + 'MSG.TXT'); DeleteFile(AFolder + 'Pub.key'); DeleteFile(AFolder + 'Priv.key'); DeleteFile(AFolder + 'FriendPub.KEY'); DeleteFile(AFolder + 'BFKEY.TXT'); end; function TMainCrypt.GetFriendEntry(Index: integer): TFriendEntry; begin Result.ID_FRIEND := -1; try if (Index < 0) or (Index > GetCountFriend) then exit; SQLTable := SQLDataBase.GetTable('SELECT * FROM ' + SQL_TBL_FRIENDS + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(Index + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '";'); try while not SQLTable.EOF do begin Result.ID_USER := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]); Result.ID_FRIEND := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_FRIEND]); Result.Email := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_EMAIL]); Result.NickName := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_NICK_NAME]); Result.UUID := SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_UUID]); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create('Не могу найти пользователя...'); end; end; procedure TMainCrypt.SetFriendEntry(Index: integer; AFriend: TFriendEntry); begin // UPDATE USERS SET NNAME = "RCode", FNAME = "Anton" WHERE ID_USER = 2; try SQLTable := SQLDataBase.GetTable('UPDATE ' + SQL_TBL_FRIENDS + ' SET ' + SQL_COL_EMAIL + ' = "' + AFriend.Email + '", ' + SQL_COL_NICK_NAME + ' = "' + AFriend.NickName + '", ' + ' WHERE ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(Index + 1) + '" AND ' + SQL_COL_ID_USER + ' = "' + IntToStr(fUser.ID_USER) + '";'); SQLTable.Free; except raise Exception.Create('Не могу найти пользователя...'); end; end; destructor TMainCrypt.Destroy; begin inherited Destroy; end; end.
{ Copyright (c) 2005-2006, Loginov Dmitry Sergeevich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } unit FindPath; interface uses Windows, Types, Lists, Matrix; type TFindPathProc = procedure(Row, Col: Integer); TFindPath = class(TObject) private function GetMapEl(Row, Col: Integer): Boolean; procedure SetMapEl(Row, Col: Integer; const Value: Boolean); function GetCMap(Row, Col: Integer): Real; procedure SetCMap(Row, Col: Integer; const Value: Real); function GetMMap(Row, Col: Integer): Real; procedure SetMMap(Row, Col: Integer; const Value: Real); private Ws: TWorkspace; // Собственная рабочая область mIdx, aIdx, m2Idx: Integer; // Индексы массивов iMapRows, iMapCols: Integer;// Размеры карты TempList, ListBegin, ListEnd: TPointList; // Списки {Определяет, существует ли прямолинейный путь} function LinePathExists(Row1, Col1, Row2, Col2: Integer): Boolean; {Определяет наличие точки} function PointExists(Row, Col: Integer): Boolean; {Поиск ключевых точек пути} function FindKey(KeyIndex: Integer; MarkNum1, MarkNum2: Integer): Boolean; {Оптимизация найденного пути} procedure Optimize; {Дополнительный массив} property AMap[Row, Col: Integer]: Real read GetCMap write SetCMap; {Карта с маркерными элементами} property MMap[Row, Col: Integer]: Real read GetMMap write SetMMap; public PathList: TPointList; // После поиска будет хранить точки пути SearchTime: DWORD; // Время поиска в миллисекундах {Создание объекта и матрицы карты} constructor Create(MapRows, MapCols: Integer); overload; destructor Destroy; override; {Создание матрицы карты} procedure CreateNewMap(MapRows, MapCols: Integer); {Функция ищет точки пути и возвращает True, если путь найден} function Find(bRow, bCol, eRow, eCol: Integer; Proc: TFindPathProc=nil): Boolean; {Сохранение карты в текстовый файл} procedure SaveMapToFile(FileName: String); {Загрузка карты из текстового файла} procedure LoadMapFromFile(FileName: String); {Карта с обозначением препятствий} property Map[Row, Col: Integer]: Boolean read GetMapEl write SetMapEl; property MapRows: Integer read iMapRows; // Определение числа строк карты property MapCols: Integer read iMapCols; // Определение числа столбцов end; implementation uses SysUtils; { TFindPath } constructor TFindPath.Create(MapRows, MapCols: Integer); begin inherited Create; Ws:= TWorkspace.Create('MapArrays'); mIdx := Ws.NewArray('Map', MapRows, MapCols); aIdx := Ws.NewArray('AMap', MapRows, MapCols); m2Idx := Ws.NewArray('MMap', MapRows, MapCols); iMapRows := MapRows; iMapCols := MapCols; PathList := TPointList.Create; TempList := TPointList.Create; ListBegin:= TPointList.Create; ListEnd := TPointList.Create; end; procedure TFindPath.CreateNewMap(MapRows, MapCols: Integer); begin mIdx := Ws.NewArray('Map', MapRows, MapCols); aIdx := Ws.NewArray('AMap', MapRows, MapCols); m2Idx := Ws.NewArray('MMap', MapRows, MapCols); iMapRows := MapRows; iMapCols := MapCols; end; destructor TFindPath.Destroy; begin Ws.Free; PathList.Free; TempList.Free; ListBegin.Free; ListEnd.Free; inherited Destroy; end; function TFindPath.Find(bRow, bCol, eRow, eCol: Integer; Proc: TFindPathProc=nil): Boolean; var I, MarkNum1, MarkNum2, Index: Integer; begin SearchTime := GetTickCount; Result := False; Ws.FillAr('AMap', 0, 0); Ws.FillAr('MMap', 0, 0); PathList.Clear; PathList.Add(Point(bRow, bCol)); PathList.Add(Point(eRow, eCol)); MarkNum1 := 1; MarkNum2 := 2; while True do Begin Index := -1; for I := 0 to PathList.Count-2 do if (abs(PathList.Items[I+1].X-PathList.Items[I].X)>1)or (abs(PathList.Items[I+1].Y-PathList.Items[I].Y)>1) then begin Index:=I; Break; end; if Index<0 then Break; // Путь уже найден if not FindKey(Index,MarkNum1, MarkNum2) then begin SearchTime := GetTickCount - SearchTime; Exit; end; Inc(MarkNum1,2); Inc(MarkNum2,2); end; // while Optimize; SearchTime := GetTickCount - SearchTime; if @Proc <> nil then for I := 1 to PathList.Count-2 do Proc(PathList.Items[I].X, PathList.Items[I].Y); Result := True; end; function TFindPath.FindKey(KeyIndex, MarkNum1, MarkNum2: Integer): Boolean; var I, J: Integer; X1,Y1,X2,Y2: Integer; begin Result := False; // Если найден кратчайший прямой путь между ключевыми точками, то // Вставляем в список ключевых точек найденные точки if LinePathExists(PathList.Items[KeyIndex].X, PathList.Items[KeyIndex].Y, PathList.Items[KeyIndex+1].X, PathList.Items[KeyIndex+1].Y) then begin for I := 0 to TempList.Count-1 do PathList.Insert(KeyIndex+1+I, TempList.Items[I]); Result := True; Exit; end; ListBegin.Clear; ListEnd.Clear; ListBegin.Add(PathList.Items[KeyIndex]); ListEnd.Add(PathList.Items[KeyIndex+1]); while True do begin if ListBegin.Count=0 then Exit; X1 := ListBegin.Items[0].X; Y1 := ListBegin.Items[0].Y; ListBegin.Delete(0); if MMap[X1,Y1]=MarkNum2 then begin PathList.Insert(KeyIndex+1, Point(X1, Y1)); Result := True; Exit; end; if ((X1=PathList.Items[KeyIndex].X) AND (Y1=PathList.Items[KeyIndex].Y)) OR ((X1=PathList.Items[KeyIndex+1].X)AND (Y1=PathList.Items[KeyIndex+1].Y)) then else MMap[X1,Y1] := MarkNum1; for I := X1 - 1 to X1 + 1 do // 1 0 1 for J := Y1 - 1 to Y1 + 1 do begin // 0 0 0 if (I<>X1) AND (J<>Y1) then Continue; // 1 0 1 if not PointExists(I, J) then Continue; if Map[I, J] then Continue; if (MMap[I, J] = MarkNum1) then Continue; if (MMap[I, J] = MarkNum2) then begin PathList.Insert(KeyIndex+1,Point(I, J)); Result := True; Exit; end; if AMap[I, J] = MarkNum1 then Continue; ListBegin.Add(Point(I, J)); AMap[I, J] := MarkNum1; end; for I := X1 - 1 to X1 + 1 do // 0 1 0 for J := Y1 - 1 to Y1 + 1 do begin // 1 0 1 if (I=X1) or (J=Y1) then Continue; // 0 1 0 if not PointExists(I, J) then Continue; if Map[I, J] then Continue; if (MMap[I, J] = MarkNum1) then Continue; if (MMap[I, J] = MarkNum2) then begin PathList.Insert(KeyIndex+1,Point(I, J)); Result := True; Exit; end; if AMap[I, J] = MarkNum1 then Continue; ListBegin.Add(Point(I, J)); AMap[I, J] := MarkNum1; end; if ListBegin.Count=0 then Exit; if ListEnd.Count=0 then Exit; X2 := ListEnd.Items[0].X; Y2 := ListEnd.Items[0].Y; ListEnd.Delete(0); if (MMap[X2,Y2]=MarkNum1) then begin PathList.Insert(KeyIndex+1,Point(X2, Y2)); Result := True; Exit; end; if ((X2=PathList.Items[KeyIndex].X) AND (Y2=PathList.Items[KeyIndex].Y)) OR ((X2=PathList.Items[KeyIndex+1].X)AND (Y2= PathList.Items[KeyIndex+1].Y)) then else MMap[X2,Y2] := MarkNum2; for I := X2 - 1 to X2 + 1 do for J := Y2 - 1 to Y2 + 1 do begin if (I<>X2) AND (J<>Y2) then Continue; if not PointExists(I, J) then Continue; if Map[I, J] then Continue; if (MMap[I, J] = MarkNum2) then Continue; if (MMap[I, J] = MarkNum1) then begin PathList.Insert(KeyIndex+1,Point(I, J)); Result := True; Exit; end; if AMap[I, J] = MarkNum2 then Continue; ListEnd.Add(Point(I, J)); AMap[I, J] := MarkNum2; end; for I := X2 - 1 to X2 + 1 do for J := Y2 - 1 to Y2 + 1 do begin if (I=X2) or (J=Y2) then Continue; if not PointExists(I, J) then Continue; if Map[I, J] then Continue; if (MMap[I, J] = MarkNum2) then Continue; if (MMap[I, J] = MarkNum1) then begin PathList.Insert(KeyIndex+1,Point(I, J)); Result := True; Exit; end; if AMap[I, J] = MarkNum2 then Continue; ListEnd.Add(Point(I, J)); AMap[I, J] := MarkNum2; end; if ListEnd.Count=0 then Exit; end; // while end; function TFindPath.GetCMap(Row, Col: Integer): Real; begin Result := Ws.ElemI[aIdx, Row, Col]; end; function TFindPath.GetMapEl(Row, Col: Integer): Boolean; begin if (Row<1) or (Col<1) or (Row>iMapRows) or (Col>iMapCols) then Ws.DoError(matBadCoords); Result := (Ws.ElemI[mIdx, Row, Col]=1); end; function TFindPath.GetMMap(Row, Col: Integer): Real; begin Result := Ws.ElemI[m2Idx, Row, Col]; end; function TFindPath.LinePathExists(Row1, Col1, Row2, Col2: Integer): Boolean; var dX, dY: Integer; XisLoopDir: Boolean; I: Integer; X, Y: Integer; begin TempList.Clear; Result := False; dX := Row2-Row1; dY := Col2-Col1; if abs(dX)>=abs(dY) then XisLoopDir := True else XisLoopDir := False; if XisLoopDir then begin // Если поиск по горизонтали if Row2>=Row1 then for I := Row1+1 to Row2-1 do begin // Ищем слева направо Y := Round((I-Row1)*(dY/abs(dX)))+Col1; if not Map[I, Y] then TempList.Add(Point(I,Y )) else Exit; end else for I := Row1-1 downto Row2+1 do begin // Ищем справа налево Y := Round((Row1-I)*(dY/abs(dX)))+Col1; if not Map[I, Y] then TempList.Add(Point(I,Y )) else Exit; end; // if2 end; // if1 if not XisLoopDir then begin // Если поиск по Вертикали if Col2>=Col1 then for I := Col1+1 to Col2-1 do begin // Ищем сверху вниз X := Round((I-Col1)*(dX/abs(dY)))+Row1; if not Map[X, I] then TempList.Add(Point(X,I )) else Exit; end else for I := Col1-1 downto Col2+1 do begin // Ищем снизу вверх X := Round((Col1-I)*(dX/abs(dY)))+Row1; if not Map[X, I] then TempList.Add(Point(X,I )) else Exit; end; // if2 end; // if1 Result := True; end; procedure TFindPath.LoadMapFromFile(FileName: String); begin Ws.LoadFromTextFile(FileName); mIdx := Ws.GetSize('Map', iMapRows, iMapCols); aIdx := Ws.NewArray('AMap', iMapRows, iMapCols); m2Idx := Ws.NewArray('MMap', iMapRows, iMapCols); end; procedure TFindPath.Optimize; var I, C: Integer; begin C := PathList.Count; for I := C-2 downto 1 do if (abs(PathList.Items[I+1].X - PathList.Items[I-1].X)<2) and (abs(PathList.Items[I+1].Y - PathList.Items[I-1].Y)<2) then PathList.Delete(I); end; function TFindPath.PointExists(Row, Col: Integer): Boolean; begin Result := True; if (Row<1) or (Col<1) or (Row>iMapRows) or (Col>iMapCols) then Result := False; end; procedure TFindPath.SaveMapToFile(FileName: String); begin if FileExists(FileName) then DeleteFile(FileName); Ws.SaveToTextFile(FileName, 'Map'); end; procedure TFindPath.SetCMap(Row, Col: Integer; const Value: Real); begin Ws.ElemI[aIdx, Row, Col] := Value; end; procedure TFindPath.SetMapEl(Row, Col: Integer; const Value: Boolean); begin if (Row<1) or (Col<1) or (Row>iMapRows) or (Col>iMapCols) then Ws.DoError(matBadCoords); Ws.ElemI[mIdx, Row, Col] := Byte(Value); end; procedure TFindPath.SetMMap(Row, Col: Integer; const Value: Real); begin Ws.ElemI[m2Idx, Row, Col] := Value; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit DSServerClassWizardPage; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, WizardAPI, StdCtrls, DSMrWizardCommon, DSServerFeatures, ExpertsUIWizard; type TDSServerClassFrame = class(TFrame, IExpertsWizardPageFrame) rbTComponent: TRadioButton; rbDataModule: TRadioButton; rbDSServerModule: TRadioButton; procedure OnButtonClick(Sender: TObject); private FPage: TCustomExpertsFrameWizardPage; function GetSelectedClassName: TDSServerClassName; procedure SetSelectedClassName(const Value: TDSServerClassName); function GetLeftMargin: Integer; procedure SetLeftMargin(const Value: Integer); function GetWizardInfo: string; { Private declarations } property LeftMargin: Integer read GetLeftMargin write SetLeftMargin; protected { IExpertsWizardPageFrame } function ExpertsFrameValidatePage(ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean; procedure ExpertsFrameUpdateInfo(ASender: TCustomExpertsWizardPage; var AHandled: Boolean); procedure ExpertsFrameCreated(APage: TCustomExpertsFrameWizardPage); procedure ExpertsFrameEnterPage(APage: TCustomExpertsFrameWizardPage); public { Public declarations } // class function CreateFrame(AOwner: TComponent): TDSServerClassFrame; static; property SelectedClassName: TDSServerClassName read GetSelectedClassName write SetSelectedClassName; end; implementation {$R *.dfm} uses DSServerDsnResStrs; procedure TDSServerClassFrame.ExpertsFrameCreated( APage: TCustomExpertsFrameWizardPage); begin LeftMargin := ExpertsUIWizard.cExpertsLeftMargin; FPage := APage; FPage.Title := sClassWizardPageTitle; FPage.Description := sClassWizardPageDescription; end; procedure TDSServerClassFrame.ExpertsFrameEnterPage( APage: TCustomExpertsFrameWizardPage); begin //APage.UpdateInfo; end; procedure TDSServerClassFrame.ExpertsFrameUpdateInfo( ASender: TCustomExpertsWizardPage; var AHandled: Boolean); begin AHandled := True; ASender.WizardInfo := GetWizardInfo; end; function TDSServerClassFrame.GetWizardInfo: string; begin case SelectedClassName of scComponent: Result := sComponentInfo; scDataModule: Result := sDataModuleInfo; scDSServerModule: Result := sDSServerModuleInfo; else Assert(False); end; end; function TDSServerClassFrame.ExpertsFrameValidatePage( ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean; begin AHandled := True; Result := True; // Always valid end; function TDSServerClassFrame.GetLeftMargin: Integer; begin Result := rbTComponent.Left; end; function TDSServerClassFrame.GetSelectedClassName: TDSServerClassName; begin if rbTComponent.Checked then Result := TDSServerClassName.scComponent else if rbDataModule.Checked then Result := TDSServerClassName.scDataModule else if rbDSServerModule.Checked then Result := TDSServerClassName.scDSServerModule else begin Result := scComponent; Assert(False); end; end; procedure TDSServerClassFrame.OnButtonClick(Sender: TObject); begin if FPage <> nil then begin FPage.DoOnFrameOptionsChanged; FPage.UpdateInfo; end; end; procedure TDSServerClassFrame.SetLeftMargin(const Value: Integer); begin rbTComponent.Left := Value; rbDataModule.Left := Value; rbDSServerModule.Left := Value; end; procedure TDSServerClassFrame.SetSelectedClassName( const Value: TDSServerClassName); begin case Value of scComponent: rbTComponent.Checked := True; scDataModule: rbDataModule.Checked := True; scDSServerModule: rbDSServerModule.Checked := True; end; end; end.
unit ejb_sidl_javax_ejb_impl; {This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file sidl.idl. } {Delphi Pascal unit : ejb_sidl_javax_ejb_impl } {derived from IDL module : ejb } interface uses SysUtils, CORBA, ejb_sidl_javax_ejb_i, ejb_sidl_javax_ejb_c; type TEJBHome = class; TEJBObject = class; TEJBHome = class(TInterfacedObject, ejb_sidl_javax_ejb_i.EJBHome) protected {******************************} {*** User variables go here ***} {******************************} public constructor Create; function getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData; procedure remove ( const primaryKey : ANY); function getSimplifiedIDL : AnsiString; end; TEJBObject = class(TInterfacedObject, ejb_sidl_javax_ejb_i.EJBObject) protected {******************************} {*** User variables go here ***} {******************************} public constructor Create; function getEJBHome : ejb_sidl_javax_ejb_i.EJBHome; function getPrimaryKey : ANY; procedure remove ; end; implementation constructor TEJBHome.Create; begin inherited; { *************************** } { *** User code goes here *** } { *************************** } end; function TEJBHome.getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData; begin { *************************** } { *** User code goes here *** } { *************************** } end; procedure TEJBHome.remove ( const primaryKey : ANY); begin { *************************** } { *** User code goes here *** } { *************************** } end; function TEJBHome.getSimplifiedIDL : AnsiString; begin { *************************** } { *** User code goes here *** } { *************************** } end; constructor TEJBObject.Create; begin inherited; { *************************** } { *** User code goes here *** } { *************************** } end; function TEJBObject.getEJBHome : ejb_sidl_javax_ejb_i.EJBHome; begin { *************************** } { *** User code goes here *** } { *************************** } end; function TEJBObject.getPrimaryKey : ANY; begin { *************************** } { *** User code goes here *** } { *************************** } end; procedure TEJBObject.remove ; begin { *************************** } { *** User code goes here *** } { *************************** } end; initialization end.
unit caHTMLParser; {$INCLUDE ca.inc} interface uses // Standard Delphi units Windows, SysUtils, Classes, // ca units caClasses, caUtils; type TcaOnHTMLTagEvent = procedure(Sender: TObject; const ATag: string; AParams: Tstrings) of Object; TcaOnHTMLTextEvent = procedure(Sender: TObject; const AText: string) of Object; //--------------------------------------------------------------------------- // IcaHTMLParser //--------------------------------------------------------------------------- IcaHTMLParser = interface ['{0F50D1DA-E006-4DD0-8AF0-6DDF76CA7669}'] // Property methods function GetOnTag: TcaOnHTMLTagEvent; function GetOnText: TcaOnHTMLTextEvent; procedure SetOnTag(const Value: TcaOnHTMLTagEvent); procedure SetOnText(const Value: TcaOnHTMLTextEvent); // Interface methods procedure Parse(AHTML: TStream); // Event properties property OnTag: TcaOnHTMLTagEvent read GetOnTag write SetOnTag; property OnText: TcaOnHTMLTextEvent read GetOnText write SetOnText; end; //--------------------------------------------------------------------------- // TcaHTMLParser //--------------------------------------------------------------------------- TcaHTMLParser = class(TcaInterfacedPersistent, IcaHTMLParser) private // Private fields FOnTag: TcaOnHTMLTagEvent; FOnText: TcaOnHTMLTextEvent; // Private methods function GetTagName(const AText: string): string; function RemoveCRLFChars(const Ch: Char): string; function RemoveNonBreakingSpaces(const AText: string): string; function RemoveQuotes(const AText: string): string; procedure ParseTagParams(const AText: string; AParams: Tstrings); procedure ProcessText(const AText: string); procedure ToLower(var AText: string); protected // Property methods function GetOnTag: TcaOnHTMLTagEvent; function GetOnText: TcaOnHTMLTextEvent; procedure SetOnTag(const Value: TcaOnHTMLTagEvent); procedure SetOnText(const Value: TcaOnHTMLTextEvent); // Event triggers procedure DoTag(const ATag: string; AParams: Tstrings); virtual; procedure DoText(const AText: string); virtual; public // Interface methods procedure Parse(AHTML: TStream); published // Event properties property OnTag: TcaOnHTMLTagEvent read GetOnTag write SetOnTag; property OnText: TcaOnHTMLTextEvent read GetOnText write SetOnText; end; implementation // Interface methods procedure TcaHTMLParser.Parse(AHTML: TStream); var Ch: Char; ParsedStr: string; TagName: string; Params: Tstrings; OnStr: Boolean; begin if AHTML.Size > 0 then begin AHTML.Seek(0, soFromBeginning); ParsedStr := ''; Ch := #0; OnStr := False; repeat AHTML.Read(Ch, 1); if Ch= '"' then OnStr := not OnStr; if (Ch = '<') and (not OnStr) then begin if Length(ParsedStr) > 0 then ProcessText(ParsedStr); ParsedStr := ''; end; ParsedStr := ParsedStr + RemoveCRLFChars(Ch); if (Ch = '>') and (not OnStr) then begin if Length(ParsedStr) > 0 then begin TagName := GetTagName(ParsedStr); if Copy(TagName, 1, 1) <> '!' then begin Params := TstringList.Create; try ParseTagParams(ParsedStr, Params); DoTag(GetTagName(ParsedStr), Params); finally Params.Free; end; end else ProcessText(ParsedStr); end; ParsedStr := ''; end; until AHTML.Size <= AHTML.Position; end; end; // Event triggers procedure TcaHTMLParser.DoTag(const ATag: string; AParams: Tstrings); begin if Assigned(FOnTag) then FOnTag(Self, ATag, AParams); end; procedure TcaHTMLParser.DoText(const AText: string); begin if Assigned(FOnText) then FOnText(Self, AText); end; // Private methods function TcaHTMLParser.GetTagName(const AText: string): string; var EndPos: Integer; begin EndPos := Pos(#32, AText); if EndPos = 0 then EndPos := Pos('>', AText); Result := Copy(AText, 2, EndPos - 2); end; function TcaHTMLParser.RemoveCRLFChars(const Ch: Char): string; const CRLFChars: set of Char = [#13,#10]; begin if (Ch in CRLFChars) then Result := '' else Result := Ch; end; function TcaHTMLParser.RemoveNonBreakingSpaces(const AText: string): string; begin Result := AText; Utils.Replace(Result, '&nbsp;', ''); end; function TcaHTMLParser.RemoveQuotes(const AText: string): string; begin Result := AText; Utils.StripChar('"', Result); Utils.StripChar('''', Result); end; procedure TcaHTMLParser.ParseTagParams(const AText: string; AParams: Tstrings); const StartStop: set of Char = [' ', '<', '>']; Equals: set of Char = ['=']; var Ch: Char; Index: Integer; InQuote: Boolean; TagParam: string; begin TagParam := ''; AParams.Clear; InQuote := False; for Index := 1 to Length(AText) do begin Ch := AText[Index]; if Ch = '"' then InQuote := not InQuote; if (Ch in StartStop) and (not InQuote) then begin if Length(TagParam) > 0 then begin ToLower(TagParam); AParams.Add(RemoveQuotes(TagParam)); end; TagParam := ''; end else TagParam := TagParam + Ch; end; end; procedure TcaHTMLParser.ProcessText(const AText: string); var OutText: string; begin OutText := RemoveNonBreakingSpaces(AText); if OutText <> '' then DoText(OutText); end; procedure TcaHTMLParser.ToLower(var AText: string); var Index: Integer; begin for Index := 1 to Length(AText) do begin if AText[Index] = '=' then Break; AText[Index] := AnsiLowerCase(AText[Index])[1]; end; end; // Property methods function TcaHTMLParser.GetOnTag: TcaOnHTMLTagEvent; begin Result := FOnTag; end; function TcaHTMLParser.GetOnText: TcaOnHTMLTextEvent; begin Result := FOnText; end; procedure TcaHTMLParser.SetOnTag(const Value: TcaOnHTMLTagEvent); begin FOnTag := Value; end; procedure TcaHTMLParser.SetOnText(const Value: TcaOnHTMLTextEvent); begin FOnText := Value; end; end.
unit uAppSettings; interface type TmyVKApp = record class function ID: string; static; class function Key: string; static; class function OAuthURL: string; static; class function RedirectURL: string; static; class function BaseURL: string; static; class function Scope: string; static; class function APIVersion: string; static; end; implementation { TmyVKApp } class function TmyVKApp.APIVersion: string; begin Result := '5.53'; end; class function TmyVKApp.BaseURL: string; begin Result := 'https://api.vk.com/method/'; end; class function TmyVKApp.ID: string; begin Result := '5627868'; end; class function TmyVKApp.Key: string; begin Result := '5k7aL5MbVTkVevhqfQ9R'; end; class function TmyVKApp.OAuthURL: string; begin Result := 'https://oauth.vk.com/authorize'; end; class function TmyVKApp.RedirectURL: string; begin Result := ''; end; class function TmyVKApp.Scope: string; begin Result := 'wall,photos'; end; end.
unit AConhecimentoTransporte; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Componentes1, Localizacao, ComCtrls, Buttons, ExtCtrls, PainelGradiente, Grids, DBGrids, Tabela, DBKeyViolation, DB, DBClient, UnNotasFiscaisFor; type TFConhecimentoTransporte = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; Label1: TLabel; Label4: TLabel; SpeedButton8: TSpeedButton; LTransportadora: TLabel; CPeriodo: TCheckBox; EDatInicio: TCalendario; EDatFim: TCalendario; ETransportadora: TEditLocaliza; Grade: TGridIndice; PanelColor3: TPanelColor; BFechar: TBitBtn; localiza: TConsultaPadrao; BCadastrar: TBitBtn; BAlterar: TBitBtn; BtExcluir: TBitBtn; BConsulta: TBitBtn; CONHECIMENTOTRANSPORTE: TSQL; DataCONHECIMENTOTRANSPORTE: TDataSource; EFilial: TRBEditLocaliza; Label2: TLabel; SpeedButton1: TSpeedButton; Label3: TLabel; CONHECIMENTOTRANSPORTENUMCONHECIMENTO: TFMTBCDField; CONHECIMENTOTRANSPORTEDATCONHECIMENTO: TSQLTimeStampField; CONHECIMENTOTRANSPORTEVALCONHECIMENTO: TFMTBCDField; CONHECIMENTOTRANSPORTEVALBASEICMS: TFMTBCDField; CONHECIMENTOTRANSPORTEVALICMS: TFMTBCDField; CONHECIMENTOTRANSPORTEPESFRETE: TFMTBCDField; CONHECIMENTOTRANSPORTEVALNAOTRIBUTADO: TFMTBCDField; CONHECIMENTOTRANSPORTEC_NOM_CLI: TWideStringField; CONHECIMENTOTRANSPORTEI_NRO_NOT: TFMTBCDField; CONHECIMENTOTRANSPORTENOMTIPODOCUMENTOFISCAL: TWideStringField; Label5: TLabel; Econhecimento: TEditColor; CONHECIMENTOTRANSPORTEI_COD_CLI: TFMTBCDField; CONHECIMENTOTRANSPORTECODFILIALNOTA: TFMTBCDField; CONHECIMENTOTRANSPORTESEQNOTASAIDA: TFMTBCDField; CONHECIMENTOTRANSPORTESEQCONHECIMENTO: TFMTBCDField; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BCadastrarClick(Sender: TObject); procedure EDatFimExit(Sender: TObject); procedure BConsultaClick(Sender: TObject); procedure BAlterarClick(Sender: TObject); procedure BtExcluirClick(Sender: TObject); private FunNotaFor : TFuncoesNFFor; procedure AtualizaConsulta; procedure AdicionaFiltros(VpaSelect : TStrings); public { Public declarations } end; var FConhecimentoTransporte: TFConhecimentoTransporte; implementation uses AConhecimentoTransporteSaida, FunSql, APrincipal, Constantes, FunData, AConhecimentoTransporteEntrada, ConstMsg; {$R *.DFM} { **************************************************************************** } procedure TFConhecimentoTransporte.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } FunNotaFor := TFuncoesNFFor.criar(self,FPrincipal.BaseDados); EDatInicio.Date:= PrimeiroDiaMesAnterior; EDatFim.Date:= UltimoDiaMesAnterior; EFilial.AInteiro:= varia.CodigoEmpFil; Efilial.Atualiza; AtualizaConsulta; end; { *************************************************************************** } procedure TFConhecimentoTransporte.AdicionaFiltros(VpaSelect: TStrings); begin if EFilial.AInteiro <> 0 then VpaSelect.Add(' AND CON.CODFILIALNOTA = ' + IntToStr(EFilial.AInteiro)); if ETransportadora.AInteiro <> 0 then VpaSelect.Add(' AND CON.CODTRANSPORTADORA = ' + IntToStr(ETransportadora.AInteiro)); if Econhecimento.AInteiro <> 0 then VpaSelect.Add(' AND CON.NUMCONHECIMENTO = ' + IntToStr(Econhecimento.AInteiro)); if CPeriodo.Checked then VpaSelect.add(SQLTextoDataEntreAAAAMMDD('CON.DATCONHECIMENTO',EDatInicio.Date,EDatFim.Date,TRUE)); end; { *************************************************************************** } procedure TFConhecimentoTransporte.AtualizaConsulta; var VpfPosicao : TBookmark; begin VpfPosicao := CONHECIMENTOTRANSPORTE.GetBookmark; CONHECIMENTOTRANSPORTE.Close; LimpaSQLTabela(CONHECIMENTOTRANSPORTE); AdicionaSQLTabela(CONHECIMENTOTRANSPORTE, 'SELECT CON.NUMCONHECIMENTO, CON.DATCONHECIMENTO, CON.VALCONHECIMENTO, CON.SEQNOTASAIDA, ' + ' CON.VALBASEICMS, CON.VALICMS, CON.PESFRETE, CON.VALNAOTRIBUTADO, CON.CODFILIALNOTA, CON.SEQCONHECIMENTO, ' + ' CLI.C_NOM_CLI, CLI.I_COD_CLI, ' + ' NOF.I_NRO_NOT, ' + ' TIP.NOMTIPODOCUMENTOFISCAL ' + ' FROM CONHECIMENTOTRANSPORTE CON, CADCLIENTES CLI, CADNOTAFISCAIS NOF, TIPODOCUMENTOFISCAL TIP ' + ' WHERE CON.CODTRANSPORTADORA = CLI.I_COD_CLI ' + ' AND CON.SEQNOTASAIDA = NOF.I_SEQ_NOT ' + ' AND CON.CODMODELODOCUMENTO = TIP.CODTIPODOCUMENTOFISCAL ' + ' AND CON.SEQNOTASAIDA IS NOT NULL '); AdicionaFiltros(CONHECIMENTOTRANSPORTE.SQL); CONHECIMENTOTRANSPORTE.sql.add('order by CON.DATCONHECIMENTO, CON.NUMCONHECIMENTO'); CONHECIMENTOTRANSPORTE.open; try CONHECIMENTOTRANSPORTE.GotoBookmark(VpfPosicao); CONHECIMENTOTRANSPORTE.FreeBookmark(VpfPosicao); except try CONHECIMENTOTRANSPORTE.Last; CONHECIMENTOTRANSPORTE.GotoBookmark(VpfPosicao); finally CONHECIMENTOTRANSPORTE.FreeBookmark(VpfPosicao); end; end; end; { *************************************************************************** } procedure TFConhecimentoTransporte.BAlterarClick(Sender: TObject); begin FConhecimentoTransporteEntrada := TFConhecimentoTransporteEntrada.CriarSDI(self,'',true); if FConhecimentoTransporteEntrada.ConsultarConhecimento(CONHECIMENTOTRANSPORTEI_COD_CLI.AsInteger, CONHECIMENTOTRANSPORTECODFILIALNOTA.AsInteger, CONHECIMENTOTRANSPORTESEQNOTASAIDA.AsInteger, false) then AtualizaConsulta; FConhecimentoTransporteEntrada.Free; end; { *************************************************************************** } procedure TFConhecimentoTransporte.BCadastrarClick(Sender: TObject); begin FConhecimentoTransporteSaida := TFConhecimentoTransporteSaida.CriarSDI(self,'',true); if FConhecimentoTransporteSaida.NovoConhecimento then AtualizaConsulta; FConhecimentoTransporteSaida.Free; end; { *************************************************************************** } procedure TFConhecimentoTransporte.BConsultaClick(Sender: TObject); begin FConhecimentoTransporteEntrada := TFConhecimentoTransporteEntrada.CriarSDI(self,'',true); FConhecimentoTransporteEntrada.ConsultarConhecimento(CONHECIMENTOTRANSPORTEI_COD_CLI.AsInteger, CONHECIMENTOTRANSPORTECODFILIALNOTA.AsInteger, CONHECIMENTOTRANSPORTESEQNOTASAIDA.AsInteger, false); FConhecimentoTransporteEntrada.Free; end; { *************************************************************************** } procedure TFConhecimentoTransporte.BFecharClick(Sender: TObject); begin Close; end; { *************************************************************************** } procedure TFConhecimentoTransporte.BtExcluirClick(Sender: TObject); var VpfResultado: String; begin if Confirmacao('Deseja realmente excluir o conhecimento : ' + IntToStr(CONHECIMENTOTRANSPORTENUMCONHECIMENTO.AsInteger)+ ' - ' + CONHECIMENTOTRANSPORTEC_NOM_CLI.AsString) then VpfResultado:= FunNotaFor.ExcluiConhecimentoTransporte(CONHECIMENTOTRANSPORTECODFILIALNOTA.AsInteger, CONHECIMENTOTRANSPORTESEQCONHECIMENTO.AsInteger, CONHECIMENTOTRANSPORTEI_COD_CLI.AsInteger); if VpfResultado <> '' then aviso(VpfResultado); AtualizaConsulta; end; { *************************************************************************** } procedure TFConhecimentoTransporte.EDatFimExit(Sender: TObject); begin AtualizaConsulta; end; { *************************************************************************** } procedure TFConhecimentoTransporte.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunNotaFor.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFConhecimentoTransporte]); end.
unit URepositorioAgente; interface uses UAgente , UEntidade , URepositorioDB , SqlExpr ; type TRepositorioAgente = class(TRepositorioDB<TAGENTE>) private public constructor Create; //destructor Destroy; override; procedure AtribuiDBParaEntidade(const coAGENTE: TAGENTE); override; procedure AtribuiEntidadeParaDB(const coAGENTE: TAGENTE; const coSQLQuery: TSQLQuery); override; procedure GravaHashSenha(const csLogin: String;const csSenha: String); function RetornaPeloLogin(const csLogin: String): TAGENTE; end; implementation uses UDM , SysUtils , StrUtils , IdHashMessageDigest ; const CNT_SELECT_PELO_LOGIN = 'select * from AGENTE where login = :login'; { TRepositorioAgente } constructor TRepositorioAGENTE.Create; begin inherited Create(TAGENTE, TBL_AGENTE, FLD_ENTIDADE_ID, STR_AGENTE); end; procedure TRepositorioAgente.GravaHashSenha(const csLogin, csSenha: String); var SenhaHash : String; HashMessageDigest5: TIdHashMessageDigest5; begin //HashMessageDigest5 := TIdHashMessageDigest5.Create; //SenhaHash := HashMessageDigest5.HashStringAsHex(edSenha.Text); end; function TRepositorioAgente.RetornaPeloLogin(const csLogin: String): TAGENTE; begin FSQLSelect.Close; FSQLSelect.CommandText := CNT_SELECT_PELO_LOGIN; FSQLSelect.Prepared := True; FSQLSelect.ParamByName(FLD_LOGIN).AsString := csLogin; FSQLSelect.Open; Result := nil; if not FSQLSelect.Eof then begin Result := TAGENTE.Create; AtribuiDBParaEntidade(Result); end; end; procedure TRepositorioAGENTE.AtribuiDBParaEntidade(const coAGENTE: TAGENTE); begin inherited; with FSQLSelect do begin coAGENTE.AGENTE_NOME := FieldByName(FLD_AGENTE_NOME).AsString ; coAGENTE.LOGIN := FieldByName(FLD_LOGIN).AsString ; coAGENTE.SENHA := FieldByName(FLD_SENHA).AsString; coAGENTE.AGENTE_EMAIL := FieldByName(FLD_AGENTE_EMAIL).AsString ; coAGENTE.AGENTE_COREN := FieldByName(FLD_AGENTE_COREN).AsString ; coAGENTE.AGENTE_ESPECIFICACAO := FieldByName(FLD_AGENTE_ESPECIFICACAO).AsString ; coAGENTE.AGENTE_DATA_NASC := FieldByName(FLD_AGENTE_DATA_NASC).AsDateTime; coAGENTE.AGENTE_TURNO := FieldByName(FLD_AGENTE_TURNO).AsString ; coAGENTE.AGENTE_TELEFONE := FieldByName(FLD_AGENTE_TELEFONE).AsString ; end; end; procedure TRepositorioAGENTE.AtribuiEntidadeParaDB(const coAGENTE: TAGENTE; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_AGENTE_COREN).AsString := coAGENTE.AGENTE_COREN; ParamByName(FLD_AGENTE_NOME).AsString := coAGENTE.AGENTE_NOME; ParamByName(FLD_LOGIN).AsString := coAGENTE.LOGIN ; ParamByName(FLD_AGENTE_EMAIL).AsString := coAGENTE.AGENTE_EMAIL; ParamByName(FLD_SENHA).AsString := coAGENTE.SENHA; ParamByName(FLD_AGENTE_DATA_NASC).AsDate := coAGENTE.AGENTE_DATA_NASC ; ParamByName(FLD_AGENTE_ESPECIFICACAO).AsString := coAGENTE.AGENTE_ESPECIFICACAO; ParamByName(FLD_AGENTE_TURNO).AsString := coAGENTE.AGENTE_TURNO; ParamByName(FLD_AGENTE_TELEFONE).AsString := coAGENTE.AGENTE_TELEFONE; end; end; end.
// auteur : Djebien Tarik // date : Janvier 2010 // objet : Compter les opérations dans un algorithme (* Question 4 *) PROGRAM TP1_partie2; uses U_Tableaux, U_Element; // Nombre de test pour une taille fixée const Nb_Test=10; var tab : TABLEAU; m : ELEMENT; nb_comp, nbc_max, nbc_min, taille,i: CARDINAL; nbc_moy : REAL; //Fonction max qui calcule la valeur maximale d'un tableau //d'élements passé en paramètre. function max(var t: TABLEAU): ELEMENT; var i: CARDINAL; m: ELEMENT; begin m:= t[low(t)]; for i:= low(t)+1 to high(t) do begin nb_comp:= nb_comp + 1; if inferieur(m,t[i]) then m:= t[i]; end;//for max:= m; end{max}; //Programme Principal BEGIN writeln; writeln('*****COMPTER LES OPERATIONS DANS UN ALGORITHME*****'); writeln;writeln; For taille:=10 to 100 do begin nbc_min:= high(CARDINAL); // + infinity nbc_max:= low(CARDINAL); // - infinity nbc_moy:= 0.0; for i:=1 to Nb_Test do begin tab:= tableauAleatoire(taille); nb_comp:=0; m:= max(tab); if nb_comp < nbc_min then nbc_min:= nb_comp; if nb_comp > nbc_max then nbc_max:= nb_comp; nbc_moy:= nbc_moy + (nb_comp/ Nb_Test); end;//for writeln('taille = ', taille,', nbc_min = ',nbc_min,', nbc_max = ',nbc_max,', nbc_moy = ',nbc_moy,'.'); end;//For END.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/primitives/block.h // Bitcoin file: src/primitives/block.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TBlockLocator; interface type // /** Describes a place in the block chain to another node such that if the // * other node doesn't have the same branch, it can find a recent common trunk. // * The further back it is, the further before the fork it may be. // */ TBlockLocator = record std::vector<uint256> vHave; constructor Create; constructor Create(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {} SERIALIZE_METHODS(CBlockLocator, obj) { int nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(nVersion); READWRITE(obj.vHave); } procedure SetNull(); function IsNull() : boolean; end; implementation constructor TBlockLocator.Create; begin end; constructor TBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) begin end; SERIALIZE_METHODS(CBlockLocator, obj) { int nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(nVersion); READWRITE(obj.vHave); } procedure TBlockLocator.SetNull(); begin vHave.clear(); end; function TBlockLocator.IsNull() : boolean; begin result := vHave.empty(); end; end.
{ Copyright (C) 1998-2018, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium.com WEB: http://www.scalabium.com In this unit I described the visual dialog for Dataset's Filter/Where clause property editing. } unit SMDBFltr; interface {$I SMVersion.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, DB, IniFiles, Buttons; type TSMFilterMode = (fmFilterDataset, fmExpression); TSMFilterOption = (foLoadFrom, foSaveAs); TSMFilterOptions = set of TSMFilterOption; TSMDBFilterItem = class FieldIndex: Integer; FieldName: string; FieldCaption: string; end; TfrmFilterDialog = class; TSMDBFExpression = procedure(Sender: TObject; IsFirstRow, boolCondition: Boolean; intField, intCondition: Integer; Value: string; var Expression: string) of object; TSMDBFValue = procedure(Sender: TObject; intField, intCondition: Integer; var Value: string) of object; {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMDBFilterDialog = class(TComponent) private { Private declarations } FCaption: TCaption; FDataset: TDataset; FAllowedFields: TStrings; FCaptionsFields: TStrings; FFilterMode: TSMFilterMode; FExpression: string; FOptions: TSMFilterOptions; FOnBeforeExecute: TNotifyEvent; FOnAfterExecute: TNotifyEvent; FOnShow: TNotifyEvent; FOnLoadFilter: TNotifyEvent; FOnSaveFilter: TNotifyEvent; FOnExpression: TSMDBFExpression; FOnValue: TSMDBFValue; FWildCard: string; FIsSQLBased: Boolean; frmFilterDialog: TfrmFilterDialog; procedure SetAllowedFields(Value: TStrings); procedure SetCaptionsFields(Value: TStrings); protected { Protected declarations } function GetItemCaption(item: TSMDBFilterItem): string; virtual; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetCurrentFilter: string; procedure SetCurrentFilter(Value: string); function Execute: Boolean; published { Published declarations } property Caption: TCaption read FCaption write FCaption; property Dataset: TDataset read FDataset write FDataset; property AllowedFields: TStrings read FAllowedFields write SetAllowedFields; property CaptionsFields: TStrings read FCaptionsFields write SetCaptionsFields; property FilterMode: TSMFilterMode read FFilterMode write FFilterMode; property Expression: string read FExpression write FExpression; property Options: TSMFilterOptions read FOptions write FOptions default [foLoadFrom, foSaveAs]; property WildCard: string read FWildCard write FWildCard; property IsSQLBased: Boolean read FIsSQLBased write FIsSQLBased default True; property OnBeforeExecute: TNotifyEvent read FOnBeforeExecute write FOnBeforeExecute; property OnAfterExecute: TNotifyEvent read FOnAfterExecute write FOnAfterExecute; property OnShow: TNotifyEvent read FOnShow write FOnShow; property OnExpression: TSMDBFExpression read FOnExpression write FOnExpression; property OnValue: TSMDBFValue read FOnValue write FOnValue; property OnLoadFilter: TNotifyEvent read FOnLoadFilter write FOnLoadFilter; property OnSaveFilter: TNotifyEvent read FOnSaveFilter write FOnSaveFilter; end; TfrmFilterDialog = class(TForm) lblFilter: TLabel; lbFilter: TListView; btnFilterAdd: TButton; btnFilterDelete: TButton; lblAddFilter: TLabel; rbAND: TRadioButton; rbOR: TRadioButton; cbFilterField: TComboBox; cbFilterCondition: TComboBox; edFilterValue: TEdit; lblFilterValue: TLabel; lblFilterCondition: TLabel; lblFilterField: TLabel; btnOk: TButton; btnCancel: TButton; bvlButton: TBevel; btnClear: TButton; btnFilterLoad: TSpeedButton; btnFilterSave: TSpeedButton; btnFilterEdit: TButton; procedure btnFilterAddClick(Sender: TObject); procedure btnFilterDeleteClick(Sender: TObject); procedure lbFilterChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure cbFilterFieldChange(Sender: TObject); procedure btnFilterSaveClick(Sender: TObject); procedure btnFilterLoadClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure lbFilterClick(Sender: TObject); private { Private declarations } fltFile: string; procedure AddFilter(EditLI: TListItem; IsUserTyped, boolCondition: Boolean; intField, intCondition: Integer; Value: string); public { Public declarations } OnExpression: TSMDBFExpression; OnValue: TSMDBFValue; FDefWildCard: string; FDefIsSQLBased: Boolean; end; procedure Register; implementation {$R *.DFM} //{$R SMDBFltr.Dcr} uses SMCnst, SMDBFltrFile; procedure Register; begin RegisterComponents('SMComponents', [TSMDBFilterDialog]); end; var ASignStr: array[0..10] of string = ('', '', '', '', '', '', '', '', '', '', ''); ASign: array[0..10] of string = ('=', '<>', '<=', '>=', '<', '>', 'IS NULL', 'IS NOT NULL', 'IN', '', '='{'LIKE'}); ACondition: array[Boolean, Boolean] of string = ((' OR ', 'OR'), (' AND ', 'AND')); { TSMDBFilterDialog } constructor TSMDBFilterDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); FCaption := 'Filter setup dialog'; FDataset := nil; FAllowedFields := TStringList.Create; FCaptionsFields := TStringList.Create; FOptions := [foLoadFrom, foSaveAs]; FWildCard := '%'; FIsSQLBased := True; end; destructor TSMDBFilterDialog.Destroy; begin FAllowedFields.Free; FCaptionsFields.Free; inherited Destroy; end; procedure TSMDBFilterDialog.SetAllowedFields(Value: TStrings); begin FAllowedFields.Assign(Value); end; procedure TSMDBFilterDialog.SetCaptionsFields(Value: TStrings); begin FCaptionsFields.Assign(Value); end; function TSMDBFilterDialog.GetItemCaption(item: TSMDBFilterItem): string; begin Result := {item.FieldName + ' : ' + }item.FieldCaption; end; function GetIndexBySignStr(str: string): Integer; var i: Integer; begin Result := 0; str := Trim(str); for i := 0 to High(ASignStr) do if ASignStr[i] = str then begin Result := i; break end; end; function GetIndexByName(str: string; lst: TStrings): Integer; var i, Code: Integer; begin Result := -1; Val(str, i, Code); if Code = 0 then begin for i := 0 to lst.Count-1 do if (TSMDBFilterItem(lst.Objects[i]).FieldIndex = Result) then begin Result := i; break end end else begin for i := 0 to lst.Count-1 do if (TSMDBFilterItem(lst.Objects[i]).FieldName = str) then begin Result := i; break end; end; end; function TSMDBFilterDialog.GetCurrentFilter: string; var i: Integer; begin Result := ''; if not Assigned(frmFilterDialog) then exit; for i := 0 to frmFilterDialog.lbFilter.Items.Count-1 do Result := Result + PAnsiString(frmFilterDialog.lbFilter.Items[i].Data)^; if (Result <> '') then Result := ' AND ' + Result; if (Result <> '') then Result := Copy(Result, 6, Length(Result)-5); end; procedure TSMDBFilterDialog.SetCurrentFilter(Value: string); function GetIndexBySign(str, AValue: string): Integer; var i, j: Integer; IsFirst: Boolean; begin str := Trim(str); Result := 0; IsFirst := True; for i := 0 to High(ASign) do if (ASign[i] = str) then begin Result := i; j := Pos(FWildCard, AValue); if (j < 1) then break else if IsFirst then IsFirst := False else break end; end; function FindSign(str: string): Integer; var i, j: Integer; begin Result := 0; for i := 0 to High(ASign) do begin j := Length(ASign[i])+1; if (ASign[i] + ' ' = UpperCase(Copy(str, 1, j))) then begin Result := j+1; break end end; end; var i, j, k: Integer; str, strExtracted, strSign: string; boolANDOR: Boolean; begin if not Assigned(frmFilterDialog) or (Value = '') then exit; while (Value <> '') do begin Value := Trim(Value); if (Copy(Value, 1, 4) = 'OR ') then begin Delete(Value, 1, 4); boolANDOR := False; end else begin if (Copy(Value, 1, 4) = 'AND ') then Delete(Value, 1, 4); boolANDOR := True; end; j := Pos(' AND ', Value); k := Pos(' OR ', Value); if (j = 0) and (k = 0) then j := Length(Value)+1 else if ((k < j) or (j = 0)) and (k > 0) then j := k; if j > 0 then begin str := Copy(Value, 1, j-1); Delete(Value, 1, j); {extract a fieldname} j := Pos(' ', str); strExtracted := Copy(str, 2, j-2); Delete(str, 1, j); i := GetIndexByName(strExtracted, frmFilterDialog.cbFilterField.Items); {extract a condition sign} // j := Pos(' ', str); j := FindSign(str); strSign := Copy(str, 1, j-1); str := Copy(str, j, Length(str)-j{-1}); if (str <> '') then begin {remove quote in start and end of value} if (str[1] = '''') then Delete(str, 1, 1); j := Length(str); if (str[j] = '''') then Delete(str, j, 1); {remove () in start and end of value} if (str[1] = '(') then Delete(str, 1, 1); j := Length(str); if (str[j] = ')') then Delete(str, j, 1); {Tomasz <tomcmok@polbox.com>: remove wildcards in start and end of value} if (str[1] = WildCard) then Delete(str, 1, 1); j := Length(str); if (str[j] = WildCard) then Delete(str, j, 1); end; // str := Copy(str, j+2, Length(str)-j-3); frmFilterDialog.AddFilter(nil, False, boolANDOR, i, GetIndexBySign(strSign, str), str); end end; end; function TSMDBFilterDialog.Execute: Boolean; var i, j: Integer; item: TSMDBFilterItem; strFilter: string; begin if Assigned(FOnBeforeExecute) then FOnBeforeExecute(Self); // Result := False; if not Assigned(frmFilterDialog) then frmFilterDialog := TfrmFilterDialog.Create(Self{Application}); with frmFilterDialog do try OnExpression := Self.OnExpression; OnValue := Self.OnValue; Caption := FCaption; FDefWildCard := FWildCard; FDefIsSQLBased := IsSQLBased; if IsSQLBased then ASign[10] := 'LIKE' else ASign[10] := '='; {fill the native strings} ASignStr[0] := strEqual; ASignStr[1] := strNonEqual; ASignStr[2] := strNonMore; ASignStr[3] := strNonLess; ASignStr[4] := strLessThan; ASignStr[5] := strLargeThan; ASignStr[6] := strExist; ASignStr[7] := strNonExist; ASignStr[8] := strIn; ASignStr[9] := strBetween; ASignStr[10] := strLike; for i := 0 to 10 do cbFilterCondition.Items.Add(ASignStr[i]); ACondition[False, True] := strOR; rbOR.Caption := strOR; ACondition[True, True] := strAND; rbAND.Caption := strAND; lblFilterField.Caption := strField; lbFilter.Columns.Items[1].Caption := strField; lblFilterCondition.Caption := strCondition; lbFilter.Columns.Items[2].Caption := strCondition; lblFilterValue.Caption := strValue; lbFilter.Columns.Items[3].Caption := strValue; btnFilterAdd.Caption := strAddToList; btnFilterEdit.Caption := strEditInList; btnFilterDelete.Caption := strDeleteFromList; lblAddFilter.Caption := strAddCondition; lblFilter.Caption := strSelection; {New constants by Arpad Toth} btnFilterSave.Hint := strFSaveAs; btnFilterLoad.Hint := strFLoadFrom; btnClear.Caption := SBtnClear; btnOk.Caption := SBtnOk; btnCancel.Caption := SBtnCancel; if Assigned(FOnShow) then FOnShow(Self); {fill the field list} if Assigned(Dataset) then begin for i := 0 to DataSet.FieldCount - 1 do begin if (AllowedFields.Count = 0) or (AllowedFields.IndexOf(DataSet.Fields[i].FieldName) > -1) then begin item := TSMDBFilterItem.Create; item.FieldIndex := cbFilterField.Items.Count; item.FieldName := DataSet.Fields[i].FieldName; item.FieldCaption := FCaptionsFields.Values[item.FieldName]; if item.FieldCaption = '' then item.FieldCaption := DataSet.Fields[i].DisplayLabel; cbFilterField.Items.AddObject(GetItemCaption(item), item); end end end; {fill the filtered conditions} case FilterMode of fmFilterDataset: strFilter := DataSet.Filter; fmExpression: strFilter := Expression; end; SetCurrentFilter(strFilter); btnFilterSave.Enabled := (lbFilter.Items.Count>0); j := 0; if foLoadFrom in Options then begin btnFilterLoad.Visible := True; Inc(j); if Assigned(OnLoadFilter) then btnFilterLoad.OnClick := OnLoadFilter end; if foSaveAs in Options then begin btnFilterSave.Visible := True; Inc(j); if Assigned(OnSaveFilter) then btnFilterSave.OnClick := OnSaveFilter end else if foLoadFrom in Options then btnFilterLoad.Left := btnFilterSave.Left; lblFilter.Width := lblFilter.Width - j*btnFilterLoad.Width; if j > 0 then lblFilter.Width := lblFilter.Width - 5; Result := (ShowModal = mrOk); if Result then begin if btnFilterAdd.Enabled and (lbFilter.Items.Count = 0) then btnFilterAdd.Click; {fill a filter string} strFilter := GetCurrentFilter(); case FilterMode of fmFilterDataset: begin DataSet.Filtered := False; DataSet.Filter := strFilter; DataSet.Filtered := True; end; fmExpression: Expression := strFilter; end; end; finally {release field items} for i := cbFilterField.Items.Count-1 downto 0 do begin if Assigned(cbFilterField.Items.Objects[i]) then cbFilterField.Items.Objects[i].Free; end; Free; frmFilterDialog := nil; end; if Assigned(FOnAfterExecute) then FOnAfterExecute(Self); end; procedure TfrmFilterDialog.btnFilterAddClick(Sender: TObject); begin if (TComponent(Sender).Tag = 1) then begin {Tomasz: List index out of bounds fixed} if (lbFilter.Selected.Index > -1) and (lbFilter.Items.Count > 0) then // if (lbFilter.Selected.Index = 0) and (lbFilter.Items.Count > 0) then begin AddFilter(lbFilter.Selected, True, rbAND.Checked, cbFilterField.ItemIndex, cbFilterCondition.ItemIndex, edFilterValue.Text); btnFilterSave.Enabled := (lbFilter.Items.Count>0); end; end else AddFilter(nil, True, rbAND.Checked, cbFilterField.ItemIndex, cbFilterCondition.ItemIndex, edFilterValue.Text); rbAND.Checked := True; cbFilterField.ItemIndex := -1; cbFilterCondition.ItemIndex := -1; edFilterValue.Text := ''; end; procedure TfrmFilterDialog.btnFilterDeleteClick(Sender: TObject); var strWhere: string; IsChanged: Boolean; intLen: Integer; begin with lbFilter do begin if (Selected.Index = 0) and (Items.Count > 1) then begin {we need remove AND/OR clause from WHERE in second item (that will be a first after delete)} strWhere := PAnsiString(Items[1].Data)^; IsChanged := False; intLen := Length(ACondition[True, False]); if (Copy(strWhere, 1, intLen) = ACondition[True, False]) then begin IsChanged := True; Delete(strWhere, 1, intLen) end else begin intLen := Length(ACondition[False, False]); if (Copy(strWhere, 1, intLen) = ACondition[False, False]) then begin IsChanged := True; Delete(strWhere, 1, intLen) end end; if IsChanged then begin {free a memory for previous string} DisposeStr(PAnsiString(Items[1].Data)); {add a new string} Items[1].Data := TObject(LongInt(NewStr(strWhere))); end; end; Items.Delete(Selected.Index); end; btnFilterSave.Enabled := (lbFilter.Items.Count>0); rbAND.Checked := True; cbFilterField.ItemIndex := -1; cbFilterCondition.ItemIndex := -1; edFilterValue.Text := ''; end; procedure TfrmFilterDialog.lbFilterChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin btnFilterEdit.Enabled := Assigned(lbFilter.Selected); btnFilterDelete.Enabled := Assigned(lbFilter.Selected); end; procedure TfrmFilterDialog.cbFilterFieldChange(Sender: TObject); begin btnFilterAdd.Enabled := (cbFilterField.ItemIndex > -1) and (cbFilterCondition.ItemIndex > -1) and ((edFilterValue.Text <> '') or (cbFilterCondition.ItemIndex in [6, 7])); btnFilterSave.Enabled := (lbFilter.Items.Count>0); end; procedure TfrmFilterDialog.AddFilter(EditLI: TListItem; IsUserTyped, boolCondition: Boolean; intField, intCondition: Integer; Value: string); var ListItem: TListItem; strFieldName, strCondition, s1, s2: string; intPos: Integer; begin if (intField < 0) then exit; strFieldName := TSMDBFilterItem(cbFilterField.Items.Objects[intField]).FieldName; strCondition := '(' + strFieldName + ' ' + ASign[intCondition]; if (Assigned(EditLI) and (EditLI.Index > 0)) or (not Assigned(EditLI) and (lbFilter.Items.Count > 0)) then strCondition := ACondition[boolCondition, False] + strCondition; if {IsUserTyped and }Assigned(OnValue) then OnValue(Owner, intField, intCondition, Value); case intCondition of {'NOT IS NULL', 'IS NULL'} 6, 7: strCondition := strCondition + ' )'; // 6, 7: strCondition := strCondition + ')'; {'IN'} 8: strCondition := strCondition + ' (' + Value + '))'; {'BETWEEN'} 9: begin intPos := Pos(' ', Value); if intPos > 0 then begin s1 := Copy(Value, 1, intPos-1); s2 := Copy(Value, intPos+1, Length(Value)- intPos); end else begin s1 := Value; s2 := '" "'; end; strCondition := strCondition + '>= ' + s1 + ') AND (' + strFieldName + ' <= ' + s2 + ')'; end; 10: begin //LIKE if FDefIsSQLBased then strCondition := strCondition + ' ''' + FDefWildCard + Value + FDefWildCard + ''')' else strCondition := strCondition + ' ''' + Value + FDefWildCard + ''')'; end else strCondition := strCondition + ' ''' + Value + ''')'; end; if {IsUserTyped and }Assigned(OnExpression) then OnExpression(Owner, (lbFilter.Items.Count < 1), boolCondition, intField, intCondition, Value, strCondition); if Assigned(EditLI) then begin {delete previos assigned string} DisposeStr(PAnsiString(EditLI.Data)); EditLI.ImageIndex := intField; EditLI.Caption := ACondition[boolCondition, True]; EditLI.SubItems[0] := cbFilterField.Items[intField]; EditLI.SubItems[1] := cbFilterCondition.Items[intCondition]; EditLI.SubItems[2] := Value; EditLI.Data := TObject(LongInt(NewStr(strCondition))); EditLI.Update end else begin ListItem := lbFilter.Items.Add; ListItem.ImageIndex := intField; ListItem.Caption := ACondition[boolCondition, True]; ListItem.SubItems.Add(cbFilterField.Items[intField]); ListItem.SubItems.Add(cbFilterCondition.Items[intCondition]); ListItem.SubItems.Add(Value); ListItem.Data := TObject(LongInt(NewStr(strCondition))); end end; procedure TfrmFilterDialog.btnFilterSaveClick(Sender: TObject); var i: Integer; s, strIndex: string; begin if frmFilterFileDialog.Execute(fltFile, True) then with TIniFile.Create(fltFile) do try EraseSection('Filter'); for i := 0 to lbFilter.Items.Count-1 do begin s := lbFilter.Items[i].Caption; if s = strAND then s := 'AND' else s := 'OR'; strIndex := IntToStr(i); WriteString('Filter', 'AndOr' + strIndex, s); s := TSMDBFilterItem(cbFilterField.Items.Objects[lbFilter.Items[i].ImageIndex]).FieldName; WriteString('Filter', 'Field' + strIndex, s); WriteInteger('Filter','Condition' + strIndex, GetIndexBySignStr(lbFilter.Items[i].SubItems[1])); WriteString('Filter', 'Value' + strIndex, lbFilter.Items[i].SubItems[2]); end; finally Free; end; end; procedure TfrmFilterDialog.btnFilterLoadClick(Sender: TObject); var i: Integer; lst: TStrings; AndOr: Boolean; begin if frmFilterFileDialog.Execute(fltFile, False) then begin lst := TStringList.Create; with TIniFile.Create(fltFile) do try ReadSection('Filter', lst); lbFilter.Items.Clear; i := 0; while i < (lst.Count-1) do begin AndOr := (ReadString('Filter', lst[i], '') = 'AND'); AddFilter(nil, False, AndOr, GetIndexByName(ReadString('Filter', lst[i+1], ''), cbFilterField.Items), GetIndexBySignStr(ASignStr[ReadInteger('Filter', lst[i+2], 0)]), ReadString('Filter', lst[i+3], '')); i := i + 4; end; lbFilter.Refresh; finally lst.Free; Free; btnFilterSave.Enabled := (lbFilter.Items.Count>0); end; end end; procedure TfrmFilterDialog.btnClearClick(Sender: TObject); begin lbFilter.Items.Clear; end; procedure TfrmFilterDialog.lbFilterClick(Sender: TObject); begin {load selected row to controls} if Assigned(lbFilter.Selected) then begin cbFilterField.ItemIndex := lbFilter.Selected.ImageIndex; cbFilterCondition.ItemIndex := cbFilterCondition.Items.IndexOf(lbFilter.Selected.SubItems[1]); edFilterValue.Text := lbFilter.Selected.SubItems[2]; if (lbFilter.Selected.Caption = ACondition[True, True]) then begin rbAND.Checked := True; rbOR.Checked := False; end else begin rbAND.Checked := False; rbOR.Checked := True; end end; end; end.
{******************************************} { TDBChart Component } { Copyright (c) 1995-2004 by David Berneda } { All rights Reserved } {******************************************} unit DBChart; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QMenus, QForms, QDialogs, QExtCtrls, QStdCtrls, {$ELSE} Graphics, Controls, Menus, Forms, Dialogs, ExtCtrls, StdCtrls, {$ENDIF} Chart, DB, TeeProcs, TeCanvas, TeEngine; type DBChartException=class(Exception); TTeeDBGroup=(dgHour,dgDay,dgWeek,dgWeekDay,dgMonth,dgQuarter,dgYear,dgNone); TListOfDataSources=class(TList) private procedure Put(Index:Integer; Value:TDataSource); function Get(Index:Integer):TDataSource; public Procedure Clear; override; property DataSource[Index:Integer]:TDataSource read Get write Put; default; end; TCustomDBChart=class; TProcessRecordEvent=Procedure(Sender:TCustomDBChart; DataSet:TDataSet) of object; TCustomDBChart = class(TCustomChart) private FAutoRefresh : Boolean; FRefreshInterval : Integer; FShowGlassCursor : Boolean; FOnProcessRecord : TProcessRecordEvent; { internal } IUpdating : Boolean; ITimer : TTimer; IDataSources : TListOfDataSources; Procedure DataSourceCheckDataSet(ADataSet:TDataSet); Procedure DataSourceCloseDataSet(ADataSet:TDataSet); Procedure CheckDataSet(ADataSet:TDataSet; ASeries:TChartSeries=nil); Procedure CheckNewDataSource(ADataSet:TDataSet; SingleRow:Boolean); Procedure SetRefreshInterval(Value:Integer); Procedure CheckTimer; Procedure OnRefreshTimer(Sender:TObject); protected procedure RemovedDataSource( ASeries: TChartSeries; AComponent: TComponent ); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Procedure CheckDatasource(ASeries:TChartSeries); override; Function IsValidDataSource(ASeries:TChartSeries; AComponent:TComponent):Boolean; override; Procedure FillValueSourceItems( AValueList:TChartValueList; Proc:TGetStrProc); override; Procedure FillSeriesSourceItems( ASeries:TChartSeries; Proc:TGetStrProc); override; Procedure RefreshDataSet(ADataSet:TDataSet; ASeries:TChartSeries); Procedure RefreshData; { properties } property AutoRefresh:Boolean read FAutoRefresh write FAutoRefresh default True; property RefreshInterval:Integer read FRefreshInterval write SetRefreshInterval default 0; property ShowGlassCursor:Boolean read FShowGlassCursor write FShowGlassCursor default True; { events } property OnProcessRecord:TProcessRecordEvent read FOnProcessRecord write FOnProcessRecord; published end; TDBChart=class(TCustomDBChart) published { TCustomDBChart properties } property AutoRefresh; property RefreshInterval; property ShowGlassCursor; { TCustomDBChart events } property OnProcessRecord; { TCustomChart Properties } property AllowPanning; property BackImage; property BackImageInside; property BackImageMode; property BackImageTransp; property BackWall; property Border; property BorderRound; property BottomWall; property Foot; property Gradient; property LeftWall; property MarginBottom; property MarginLeft; property MarginRight; property MarginTop; property MarginUnits; property PrintProportional; property RightWall; property SubFoot; property SubTitle; property Title; { TCustomChart Events } property OnAllowScroll; property OnClickAxis; property OnClickBackground; property OnClickLegend; property OnClickSeries; property OnClickTitle; property OnGetLegendPos; property OnGetLegendRect; property OnScroll; property OnUndoZoom; property OnZoom; { TCustomAxisPanel properties } property AxisBehind; property AxisVisible; property BottomAxis; property Chart3DPercent; property ClipPoints; property CustomAxes; property DepthAxis; property DepthTopAxis; property Frame; property LeftAxis; property Legend; property MaxPointsPerPage; property Monochrome; property Page; property RightAxis; property ScaleLastPage; property SeriesList; property Shadow; property TopAxis; property View3D; property View3DOptions; property View3DWalls; property Zoom; { TCustomAxisPanel events } property OnAfterDraw; property OnBeforeDrawAxes; property OnBeforeDrawChart; property OnBeforeDrawSeries; property OnGetAxisLabel; property OnGetLegendText; property OnGetNextAxisLabel; property OnPageChange; { TPanel properties } property Align; property BevelInner; property BevelOuter; property BevelWidth; {$IFDEF CLX} property Bitmap; {$ENDIF} property BorderWidth; property Color; {$IFNDEF CLX} property DragCursor; {$ENDIF} property DragMode; property Enabled; property ParentColor; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property Anchors; {$IFNDEF CLX} property AutoSize; {$ENDIF} property Constraints; {$IFNDEF CLX} property DragKind; property Locked; {$ENDIF} { TPanel events } property OnClick; {$IFDEF D5} property OnContextPopup; {$ENDIF} property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnStartDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; {$IFNDEF CLX} property OnCanResize; {$ENDIF} property OnConstrainedResize; {$IFNDEF CLX} property OnDockDrop; property OnDockOver; property OnEndDock; property OnGetSiteInfo; property OnStartDock; property OnUnDock; {$ENDIF} {$IFDEF K3} property OnMouseEnter; property OnMouseLeave; {$ENDIF} end; TTeeFieldType=(tftNumber,tftDateTime,tftText,tftNone); { given a VCL "database field type", this function returns a more simplified "type": (number, date, text) } Function TeeFieldType(AType:TFieldType):TTeeFieldType; { Returns the ISO- Week number (from 1 to 52) of a given "ADate" parameter, and decrements "Year" if it's the first week of the year. } Function DateToWeek(ADate:TDateTime; Var Year:Word):Integer; { same as DateToWeek, using a different algorithm (compatible with TeeChart version 4 } Function DateToWeekOld(Const ADate:TDateTime; Var Year:Word):Integer; { internal, used by DBChart Summary feature } Function TeeGetDBPart(Num:Integer; St:String):String; Function StrToDBGroup(St:String):TTeeDBGroup; Function StrToDBOrder(St:String):TChartListOrder; type TCheckDataSetEvent=procedure(DataSet:TDataSet) of object; TDBChartDataSource=class(TDataSource) private FDBChart : TCustomDBChart; FWasActive : Boolean; Procedure DataSourceRowChange(Sender:TObject; Field:TField); Procedure DataSourceStateChange(Sender:TObject); Procedure DataSourceUpdateData(Sender:TObject); protected OnCheckDataSet : TCheckDataSetEvent; OnCloseDataSet : TCheckDataSetEvent; Procedure SetDataSet(Value:TDataSet; SingleRow:Boolean=False); end; Procedure FillDataSetFields(DataSet:TDataSet; Proc:TGetStrProc); implementation Uses TeeConst, TypInfo; {$IFDEF CLR} type TBookMark=IntPtr; // Pending fix in Borland.VclDBRtl.dll {$ENDIF} { TDBChartDataSource } Procedure TDBChartDataSource.SetDataSet(Value:TDataSet; SingleRow:Boolean=False); Begin DataSet:=Value; FWasActive:=DataSet.Active; {$IFDEF CLR} Include(OnStateChange,DataSourceStateChange); Include(OnUpdateData,DataSourceUpdateData); if SingleRow then Include(OnDataChange,DataSourceRowChange); {$ELSE} OnStateChange:=DataSourceStateChange; OnUpdateData:=DataSourceUpdateData; if SingleRow then OnDataChange:=DataSourceRowChange; {$ENDIF} end; Procedure TDBChartDataSource.DataSourceRowChange(Sender:TObject; Field:TField); begin if Assigned(FDBChart) then if not FDBChart.IUpdating then With TDBChartDataSource(Sender) do OnCheckDataSet(DataSet); end; Procedure TDBChartDataSource.DataSourceUpdateData(Sender:TObject); Begin With TDBChartDataSource(Sender) do if State= {$IFDEF CLR}TDataSetState.{$ENDIF}dsBrowse then OnCheckDataSet(DataSet) else FWasActive:=False; End; Procedure TDBChartDataSource.DataSourceStateChange(Sender:TObject); Begin With TDBChartDataSource(Sender) do if State={$IFDEF CLR}TDataSetState.{$ENDIF}dsInactive then Begin FWasActive:=False; if Assigned(OnCloseDataSet) then OnCloseDataSet(DataSet); end else if (State={$IFDEF CLR}TDataSetState.{$ENDIF}dsBrowse) and (not FWasActive) then Begin OnCheckDataSet(DataSet); FWasActive:=True; end; end; { TListOfDataSources } Procedure TListOfDataSources.Clear; var t : Integer; begin for t:=0 to Count-1 do DataSource[t].Free; inherited; end; procedure TListOfDataSources.Put(Index:Integer; Value:TDataSource); begin inherited Items[Index]:=Value; end; function TListOfDataSources.Get(Index:Integer):TDataSource; begin result:=TDataSource(inherited Items[Index]); end; { TDBChart } Constructor TCustomDBChart.Create(AOwner: TComponent); begin inherited; IDataSources:=TListOfDataSources.Create; FAutoRefresh:=True; FShowGlassCursor:=True; ITimer:=nil; IUpdating:=False; end; Destructor TCustomDBChart.Destroy; begin ITimer.Free; IDataSources.Free; inherited; end; // When "AComponent" source is removed from ASeries DataSourceList, // this method also removes AComponent from internal IDataSources list. procedure TCustomDBChart.RemovedDataSource( ASeries: TChartSeries; AComponent: TComponent ); var t : Integer; tmp : TDataSet; begin inherited; if AComponent is TDataSet then for t:=0 to IDataSources.Count-1 do begin tmp:=IDataSources[t].DataSet; if (not Assigned(tmp)) or (tmp=AComponent) then begin IDataSources[t].Free; IDataSources.Delete(t); break; end; end; end; Procedure TCustomDBChart.CheckTimer; Begin if Assigned(ITimer) then ITimer.Enabled:=False; if (FRefreshInterval>0) and (not (csDesigning in ComponentState) ) then Begin if not Assigned(ITimer) then Begin ITimer:=TTimer.Create(Self); ITimer.Enabled:=False; ITimer.OnTimer:=OnRefreshTimer; end; ITimer.Interval:=FRefreshInterval*1000; ITimer.Enabled:=True; end; End; Procedure TCustomDBChart.OnRefreshTimer(Sender:TObject); var t : Integer; Begin ITimer.Enabled:=False; { no try..finally here ! } for t:=0 to IDataSources.Count-1 do With IDataSources[t] do if DataSet.Active then Begin DataSet.Refresh; CheckDataSet(DataSet); end; ITimer.Enabled:=True; end; Procedure TCustomDBChart.SetRefreshInterval(Value:Integer); Begin if (Value<0) or (Value>60) then Raise DBChartException.Create(TeeMsg_RefreshInterval); FRefreshInterval:=Value; CheckTimer; End; Function TCustomDBChart.IsValidDataSource(ASeries:TChartSeries; AComponent:TComponent):Boolean; Begin result:=inherited IsValidDataSource(ASeries,AComponent); if not Result then result:=(AComponent is TDataSet) or (AComponent is TDataSource); end; Procedure TCustomDBChart.CheckNewDataSource(ADataSet:TDataSet; SingleRow:Boolean); Var tmpDataSource : TDBChartDataSource; Begin if IDataSources.IndexOf(ADataSet)=-1 then begin tmpDataSource:=TDBChartDataSource.Create(nil); { 5.02 } With tmpDataSource do begin SetDataSet(ADataSet,SingleRow); OnCheckDataSet:=DataSourceCheckDataSet; OnCloseDataSet:=DataSourceCloseDataSet; end; IDataSources.Add(tmpDataSource); end; end; Procedure TCustomDBChart.CheckDatasource(ASeries:TChartSeries); Begin if Assigned(ASeries) then With ASeries do if ParentChart=Self then Begin if Assigned(DataSource) then Begin ASeries.Clear; if DataSource is TDataSet then Begin CheckNewDataSource(TDataSet(DataSource),False); CheckDataSet(TDataSet(DataSource),ASeries); end else if (DataSource is TDataSource) and Assigned(TDataSource(DataSource).DataSet) then begin CheckNewDataSource(TDataSource(DataSource).DataSet,True); CheckDataSet(TDataSource(DataSource).DataSet,ASeries); end else inherited; end else inherited; end else Raise ChartException.Create(TeeMsg_SeriesParentNoSelf); end; Procedure TCustomDBChart.CheckDataSet(ADataSet:TDataSet; ASeries:TChartSeries=nil); Begin if FAutoRefresh then RefreshDataSet(ADataSet,ASeries); end; Procedure TCustomDBChart.DataSourceCheckDataSet(ADataSet:TDataSet); begin CheckDataSet(ADataSet); end; Procedure TCustomDBChart.DataSourceCloseDataSet(ADataSet:TDataSet); var t : Integer; begin if FAutoRefresh then for t:=0 to SeriesCount-1 do if Series[t].DataSource=ADataSet then Series[t].Clear; end; type TValueListAccess=class(TChartValueList); TDBChartAgg=(dcaNone, dcaSum, dcaCount, dcaHigh, dcaLow, dcaAverage); TDBChartSeries=packed record ASeries : TChartSeries; YManda : Boolean; MandaList : TChartValueList; LabelSort : TChartListOrder; LabelField : TField; ColorField : TField; MandaField : TField; NumFields : Integer; GroupPrefix : TTeeDBGroup; AggPrefix : TDBChartAgg; end; TDBChartSeriesList=Array of TDBChartSeries; Procedure TCustomDBChart.RefreshDataSet(ADataSet:TDataSet; ASeries:TChartSeries); Var HasAnyDataSet : Boolean; Procedure ProcessRecord(const tmpSeries:TDBChartSeries); var tmpxLabel : String; tmpColor : TColor; tmpNotMand: Double; tmpMand : Double; Procedure AddToSeries(const DestSeries:TDBChartSeries); Var t : Integer; tmpIndex : Integer; begin With DestSeries do if AggPrefix<>dcaNone then begin tmpIndex:=ASeries.Labels.IndexOfLabel(tmpXLabel); if tmpIndex=-1 then { new point } begin if AggPrefix=dcaCount then tmpMand:=1 else if AggPrefix=dcaAverage then tmpColor:=1; ASeries.Add(tmpMand,tmpXLabel,tmpColor); end else { existing point, do aggregation } With MandaList do Case AggPrefix of dcaSum: Value[tmpIndex]:=Value[tmpIndex]+tmpMand; dcaCount: Value[tmpIndex]:=Value[tmpIndex]+1; dcaHigh: if tmpMand>Value[tmpIndex] then Value[tmpIndex]:=tmpMand; dcaLow: if tmpMand<Value[tmpIndex] then Value[tmpIndex]:=tmpMand; dcaAverage: begin Value[tmpIndex]:=Value[tmpIndex]+tmpMand; { trick: use the color as temporary count for average } ASeries.ValueColor[tmpIndex]:=ASeries.ValueColor[tmpIndex]+1; end; end; end else With DestSeries.ASeries do begin With ValuesList do for t:=2 to Count-1 do {$IFDEF CLR} if Assigned(TValueListAccess(ValueList[t]).IData) then TValueListAccess(ValueList[t]).TempValue:=TField(TValueListAccess(ValueList[t]).IData).AsFloat else TValueListAccess(ValueList[t]).TempValue:=0; {$ELSE} With TValueListAccess(ValueList[t]) do if Assigned(IData) then TempValue:=TField(IData).AsFloat else TempValue:=0; {$ENDIF} if NotMandatoryValueList.ValueSource='' then if YManda then AddY(tmpMand,tmpXLabel,tmpColor) else AddX(tmpMand,tmpXLabel,tmpColor) else if YManda then { 5.01 } AddXY(tmpNotMand,tmpMand,tmpXLabel,tmpColor) else AddXY(tmpMand,tmpNotMand,tmpXLabel,tmpColor); end; end; Function GetFieldValue(AField:TField):Double; begin {$IFDEF CLR} result:=AField.AsFloat; {$ELSE} With AField do if FieldKind=fkAggregate then result:=Value else result:=AsFloat; {$ENDIF} end; Procedure AddSingleRecord; var t : Integer; tmpName : String; begin With tmpSeries do for t:=1 to NumFields do begin tmpName:=TeeExtractField(MandaList.ValueSource,t); if ASeries.XLabelsSource='' then tmpXLabel:=tmpName; if tmpName='' then tmpMand:=0 else tmpMand:=GetFieldValue(ADataSet.FieldByName(tmpName)); AddToSeries(tmpSeries); end; end; Function CalcXPos:String; { from DateTime to Label } var Year : Word; Month : Word; Day : Word; Hour : Word; Minute : Word; Second : Word; MSecond : Word; begin result:=''; DecodeDate(tmpNotMand,Year,Month,Day); Case tmpSeries.GroupPrefix of dgHour: begin DecodeTime(tmpNotMand,Hour,Minute,Second,MSecond); result:=FormatDateTime('dd hh:nn',Trunc(tmpNotMand)+Hour/24.0); // 5.02 end; dgDay: result:=FormatDateTime('dd/MMM',Trunc(tmpNotMand)); // 5.02 dgWeek: result:=TeeStr(DateToWeek(tmpNotMand,Year))+'/'+TeeStr(Year); dgWeekDay: result:=ShortDayNames[DayOfWeek(tmpNotMand)]; dgMonth: result:=FormatDateTime('MMM/yy',EncodeDate(Year,Month,1)); dgQuarter: result:=TeeStr(1+((Month-1) div 3))+'/'+TeeStr(Year); // 5.02 dgYear: result:=FormatDateTime('yyyy',EncodeDate(Year,1,1)); end; end; var tmpData : TObject; Begin With tmpSeries do Begin if GroupPrefix=dgNone then if Assigned(LabelField) then tmpXLabel:=LabelField.DisplayText else tmpXLabel:='' else begin tmpNotMand:=LabelField.AsFloat; tmpXLabel:=CalcXPos; end; if AggPrefix<>dcaNone then tmpColor:=clTeeColor else if Assigned(ColorField) then tmpColor:=ColorField.AsInteger else {$IFNDEF CLX} // CLX limitation if Assigned(MandaField) and MandaField.IsNull then tmpColor:=clNone else {$ENDIF} tmpColor:=clTeeColor; if NumFields=1 then begin if (not HasAnyDataSet) and (not Assigned(LabelField)) then tmpXLabel:=MandaList.ValueSource; tmpData:=TValueListAccess(ASeries.NotMandatoryValueList).IData; if Assigned(tmpData) then tmpNotMand:=TField(tmpData).AsFloat // ADataSet.GetFieldData(TField(tmpData), @tmpNotMand) // v7 speed opt. else tmpNotMand:=0; if Assigned(MandaField) then tmpMand:=GetFieldValue(MandaField) else tmpMand:=0; // add summary point AddToSeries(tmpSeries); end else AddSingleRecord end; end; Var FListSeries : TDBChartSeriesList; Procedure FillTempSeriesList; Function GetDataSet(ASeries:TChartSeries):TDataSet; begin With ASeries do if DataSource is TDataSet then result:=TDataSet(DataSource) else if DataSource is TDataSource then result:=TDataSource(DataSource).DataSet else result:=nil; end; Function IsDataSet(ASeries:TChartSeries):Boolean; var tmp : TDataSet; begin tmp:=GetDataSet(ASeries); if Assigned(tmp) then begin result:=tmp=ADataSet; HasAnyDataSet:=ASeries.DataSource is TDataSet; end else result:=False; end; Procedure AddList(tmpSeries:TChartSeries); var tmp : TDataSet; Function GetAField(Const FieldName:String):TField; begin if FieldName='' then result:=nil else result:=tmp.FieldByName(FieldName); end; Function GetAFieldPrefix(St:String; Var Prefix:String):TField; begin Prefix:=TeeGetDBPart(1,St); if Prefix<>'' then St:=TeeGetDBPart(2,St); result:=GetAField(St); end; var t : Integer; tmpAgg : String; tmpGroup : String; {$IFNDEF CLR} tmpV : TValueListAccess; {$ENDIF} begin SetLength(FListSeries,Length(FListSeries)+1); With FListSeries[Length(FListSeries)-1] do begin ASeries :=tmpSeries; YManda :=ASeries.YMandatory; MandaList :=ASeries.MandatoryValueList; NumFields :=TeeNumFields(MandaList.ValueSource); tmp:=GetDataSet(ASeries); if Assigned(tmp) then With ASeries do begin LabelField:=GetAFieldPrefix(XLabelsSource,tmpGroup); // try to find #SORTASC# or #SORTDESC# in label grouping LabelSort:=StrToDBOrder(tmpGroup); if LabelSort=loNone then GroupPrefix:=StrToDBGroup(tmpGroup) // find #HOUR# etc else GroupPrefix:=dgNone; ColorField:=GetAField(ColorSource); MandaField:=GetAFieldPrefix(TeeExtractField(MandaList.ValueSource,1),tmpAgg); if tmpAgg<>'' then begin tmpAgg:=UpperCase(tmpAgg); if tmpAgg='SUM' then AggPrefix:=dcaSum else if tmpAgg='COUNT' then AggPrefix:=dcaCount else if tmpAgg='HIGH' then AggPrefix:=dcaHigh else if tmpAgg='LOW' then AggPrefix:=dcaLow else if tmpAgg='AVG' then AggPrefix:=dcaAverage else AggPrefix:=dcaNone; end else begin AggPrefix:=dcaNone; for t:=0 to ValuesList.Count-1 do begin {$IFDEF CLR} if ValuesList[t]<>MandaList then TValueListAccess(ValuesList[t]).IData:=GetAField(ValuesList[t].ValueSource); {$ELSE} tmpV:=TValueListAccess(ValuesList[t]); if tmpV<>MandaList then tmpV.IData:=GetAField(tmpV.ValueSource); {$ENDIF} end; end; end; end; end; var t : Integer; tmpSeries : TChartSeries; begin FListSeries:=nil; if Assigned(ASeries) then begin AddList(ASeries); HasAnyDataSet:=ASeries.DataSource=ADataSet; end else for t:=0 to SeriesCount-1 do Begin tmpSeries:=Series[t]; if IsDataSet(tmpSeries) and (tmpSeries.MandatoryValueList.ValueSource<>'') then AddList(tmpSeries); end; end; Procedure TraverseDataSet; Var b : TBookMark; t : Integer; tt: Integer; begin With ADataSet do begin DisableControls; try b:=GetBookMark; try First; While not EOF do try if Assigned(FOnProcessRecord) then FOnProcessRecord(Self,ADataSet); for t:=0 to Length(FListSeries)-1 do if FListSeries[t].ASeries.DataSource=ADataSet then ProcessRecord(FListSeries[t]); Next; except on EAbort do break; { <-- exit while loop !!! } end; for t:=0 to Length(FListSeries)-1 do With FListSeries[t] do begin if AggPrefix=dcaAverage then begin for tt:=0 to ASeries.Count-1 do begin MandaList.Value[tt]:=MandaList.Value[tt]/ASeries.ValueColor[tt]; ASeries.ValueColor[tt]:=clTeeColor; end; end; if (AggPrefix<>dcaNone) and (LabelSort<>loNone) then ASeries.SortByLabels(LabelSort); end; finally try GotoBookMark(b); finally FreeBookMark(b); end; end; finally EnableControls; end; end; end; Var OldCursor : TCursor; t : Integer; OldPaint : Boolean; Begin if not IUpdating then With ADataSet do if Active then Begin IUpdating:=True; FListSeries:=nil; HasAnyDataSet:=False; try FillTempSeriesList; if Length(FListSeries)>0 then Begin OldCursor:=Screen.Cursor; if FShowGlassCursor then Screen.Cursor:=crHourGlass; OldPaint:=AutoRepaint; AutoRepaint:=False; try for t:=0 to Length(FListSeries)-1 do FListSeries[t].ASeries.Clear; if HasAnyDataSet then TraverseDataSet else begin {$IFDEF TEEOCX} ADataSet.Resync([]); {$ENDIF} if Assigned(FOnProcessRecord) then FOnProcessRecord(Self,ADataSet); for t:=0 to Length(FListSeries)-1 do if TDataSource(FListSeries[t].ASeries.DataSource).DataSet=ADataSet then begin ProcessRecord(FListSeries[t]); end; end; for t:=0 to Length(FListSeries)-1 do begin FListSeries[t].ASeries.CheckOrder; FListSeries[t].ASeries.RefreshSeries; end; finally AutoRepaint:=OldPaint; Invalidate; if FShowGlassCursor then Screen.Cursor:=OldCursor; end; end; finally FListSeries:=nil; IUpdating:=False; end; end; end; Procedure TCustomDBChart.RefreshData; var t : Integer; Begin for t:=0 to IDataSources.Count-1 do RefreshDataSet(IDataSources[t].DataSet,nil); End; Procedure FillDataSetFields(DataSet:TDataSet; Proc:TGetStrProc); var t : Integer; begin with DataSet do begin if FieldCount > 0 then for t:=0 to FieldCount-1 do Proc(Fields[t].FieldName) else Begin FieldDefs.Update; for t:=0 to FieldDefs.Count-1 do Proc(FieldDefs[t].Name); end; end; end; Procedure TCustomDBChart.FillSeriesSourceItems(ASeries:TChartSeries; Proc:TGetStrProc); Begin With ASeries do if Assigned(DataSource) then begin if DataSource is TDataSource then FillDataSetFields(TDataSource(DataSource).DataSet,Proc) else if DataSource is TDataSet then FillDataSetFields(TDataSet(DataSource),Proc); end; end; Procedure TCustomDBChart.FillValueSourceItems(AValueList:TChartValueList; Proc:TGetStrProc); Begin With AValueList.Owner do if Assigned(DataSource) then Begin if (DataSource is TDataSet) or (DataSource is TDataSource) then FillSeriesSourceItems(AValueList.Owner,Proc) else inherited; end; end; Procedure TCustomDBChart.Assign(Source:TPersistent); begin if Source is TCustomDBChart then With TCustomDBChart(Source) do begin Self.AutoRefresh :=AutoRefresh; Self.RefreshInterval:=RefreshInterval; Self.ShowGlassCursor:=ShowGlassCursor; end; inherited; end; { 5.01 Reported by : Timo Goebel <timo.goebel@pipedoc.de> } Function DateToWeek(ADate:TDateTime; Var Year:Word):Integer; const FirstWeekDay = 2; // 2: Monday (ISO-8601) FirstWeekDate = 4; // 4: First four day-week (ISO-8601) var Month : Word; Day : Word; begin ADate:=ADate-((DayOfWeek(ADate)-FirstWeekDay+7) mod 7)+ 7-FirstWeekDate; DecodeDate(ADate,Year,Month,Day); Result:=(Trunc(ADate-EncodeDate(Year,1,1)) div 7)+1; end; Function DateToWeekOld(Const ADate:TDateTime; Var Year:Word):Integer; Const FirstDay=0; { Monday } Var d,m,y,j,j0,j1,Week : Word; begin DecodeDate(ADate,y,m,d); if (m < 3) then j := 1461*(y-1) div 4 + (153*(m+9)+2) div 5 + d else j := 1461*y div 4 + (153*(m-3)+2) div 5 + d; j0:=1461*(y-1) DIV 4 + 310; j0:=j0-(j0-FirstDay) MOD 7; If (j<j0) then begin j0 := 1461*(y-2) DIV 4 + 310; j0 := j0 - (j0-FirstDay) MOD 7; Week:=1 + (j-j0) DIV 7; Year:=y-1; end else begin j1 := 1461*y div 4 + 310; j1 := j1 - (j1-FirstDay) mod 7; if j<j1 then begin Week:=1 + (j-j0) div 7; Year:=y; end else begin Week:=1; Year:=y+1; end; end; result:=Week; End; Function TeeFieldType(AType:TFieldType):TTeeFieldType; begin // Pending fix in VCLDBRtl.dll ... Case AType of {$IFDEF CLR}TFieldType.{$ENDIF}ftAutoInc, {$IFDEF CLR}TFieldType.{$ENDIF}ftCurrency, {$IFDEF CLR}TFieldType.{$ENDIF}ftFloat, {$IFDEF CLR}TFieldType.{$ENDIF}ftInteger, {$IFDEF CLR}TFieldType.{$ENDIF}ftLargeInt, {$IFDEF CLR}TFieldType.{$ENDIF}ftSmallint, {$IFDEF CLR}TFieldType.{$ENDIF}ftWord, {$IFDEF CLR}TFieldType.{$ENDIF}ftBCD : result:=tftNumber; {$IFDEF CLR}TFieldType.{$ENDIF}ftDate, {$IFDEF CLR}TFieldType.{$ENDIF}ftTime, {$IFDEF D7} {$IFDEF CLR}TFieldType.{$ENDIF}ftTimeStamp, {$ENDIF} {$IFDEF CLR}TFieldType.{$ENDIF}ftDateTime : result:=tftDateTime; {$IFDEF CLR}TFieldType.{$ENDIF}ftString, {$IFDEF CLR}TFieldType.{$ENDIF}ftFixedChar, {$IFDEF CLR}TFieldType.{$ENDIF}ftWideString : result:=tftText; else result:=tftNone; end; end; Function TeeGetDBPart(Num:Integer; St:String):String; var i : Integer; begin result:=''; if Copy(St,1,1)='#' then begin Delete(St,1,1); i:=Pos('#',St); if i>0 then if Num=1 then result:=Copy(St,1,i-1) else if Num=2 then result:=Copy(St,i+1,Length(St)-i); end; end; Function StrToDBGroup(St:String):TTeeDBGroup; begin St:=UpperCase(St); if St='HOUR' then result:=dgHour else if St='DAY' then result:=dgDay else if St='WEEK' then result:=dgWeek else if St='WEEKDAY' then result:=dgWeekDay else if St='MONTH' then result:=dgMonth else if St='QUARTER' then result:=dgQuarter else if St='YEAR' then result:=dgYear else result:=dgNone; end; Function StrToDBOrder(St:String):TChartListOrder; begin St:=UpperCase(St); if St='SORTASC' then result:=loAscending else if St='SORTDES' then result:=loDescending else result:=loNone; end; end.
unit HexToInt_1; interface implementation function TryHexToInt64(const Hex: string; out Value: Int64): Boolean; function Multiplier(Position: Int32): Int64; inline; var I: Int32; begin Result := 1; for I := 1 to Position do Result := 16 * Result; end; var A, B, I: Int32; M: Int64; begin B := 0; Value := 0; for I := High(Hex) downto Low(Hex) do begin A := Ord(Hex[I]); M := Multiplier(B); case A of 48: ; // '0' -- Do nothing. 49..57: Value := Value + (A - 48) * M; // '1'..'9' 65..70: Value := Value + (A - 55) * M; // 'A'..'F' 97..102: Value := Value + (A - 87) * M; // 'a'..'f' else Exit(False); end; Inc(B); end; Result := True; end; var G0, G1, G2, G3, G4, G5, G6, G7, G8, G9, G10, G11, G12, G13, G14, G15: Int64; procedure Test; begin TryHexToInt64('A', G0); TryHexToInt64('AB', G1); TryHexToInt64('ABC', G2); TryHexToInt64('ABCD', G3); TryHexToInt64('ABCDE', G4); TryHexToInt64('ABCDEF', G5); TryHexToInt64('ABCDEF1', G6); TryHexToInt64('ABCDEF12', G7); TryHexToInt64('ABCDEF123', G8); TryHexToInt64('ABCDEF1234', G9); TryHexToInt64('ABCDEF12345', G10); TryHexToInt64('ABCDEF123456', G11); TryHexToInt64('ABCDEF1234567', G12); TryHexToInt64('ABCDEF12345678', G13); TryHexToInt64('ABCDEF123456789', G14); TryHexToInt64('ABCDEF1234567890', G15); end; initialization Test(); finalization Assert(G0 = $A); Assert(G1 = $AB); Assert(G2 = $ABC); Assert(G3 = $ABCD); Assert(G4 = $ABCDE); Assert(G5 = $ABCDEF); Assert(G6 = $ABCDEF1); Assert(G7 = $ABCDEF12); Assert(G8 = $ABCDEF123); Assert(G9 = $ABCDEF1234); Assert(G10 = $ABCDEF12345); Assert(G11 = $ABCDEF123456); Assert(G12 = $ABCDEF1234567); Assert(G13 = $ABCDEF12345678); Assert(G14 = $ABCDEF123456789); Assert(G15 = $ABCDEF1234567890); {} end.
unit int_32_1; interface uses System; var G1, G2: Int32; implementation procedure Test; begin G1 := MinInt32; G2 := MaxInt32; end; initialization Test(); finalization Assert(G1 = MinInt32); Assert(G2 = MaxInt32); end.
unit ncClassesBase; { ResourceString: Dario 12/03/13 } interface {$I NEX.INC} uses cxFormats, Classes, CacheProp, ClasseCS, SysUtils, Messages, Windows, Dialogs, DB, uFaixaInteger, uLicEXECryptor, ncMsgCom, SyncObjs, Variants, uThreadStringList, ncErros, uNexTransResourceStrings_PT, System.StrUtils; const cEstados : Array[1..27] of String = ( 'AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MG', 'MS', 'MT', 'PA', 'PB', 'PE', 'PI', 'PR', 'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO'); type Estados = class public class function porID(aID: Byte): String; class function porUF(aUF: String): Byte; end; const incluir_marca = '{AA7D6FDC-C1EB-4910-AE16-6AA37A4D9CEA}'; idtb_Caixa = 01; idtb_Card = 02; idtb_Credito = 03; idtb_Categoria = 04; idtb_Cliente = 05; idtb_Config = 06; idtb_Debito = 07; idtb_ITran = 08; idtb_Layout = 09; idtb_MovEst = 10; idtb_NCM = 11; idtb_Produto = 12; idtb_Tran = 13; idtb_Usuario = 14; idtb_infoCampanha = 15; idtb_temp = 16; idtb_PostMS = 17; idtb_Unidade = 18; idtb_Especie = 19; idtb_PagEspecies = 20; idtb_IOrcamento = 21; idtb_Orcamento = 22; idtb_syslog = 23; idtb_Doc = 24; idtb_br_cest = 25; idtb_Terminal = 26; idtb_RecDel = 27; idtb_CFOP = 28; idtb_MunBr = 29; idtb_NFCONFIG = 30; idtb_NFE = 31; idtb_CCE = 32; idtb_BRTrib = 33; idtb_ConvUnid = 34; idtb_ProdFor = 35; idtb_tax = 36; idtb_tax_itens = 37; idtb_movest_tax = 38; idtb_post_nexapp = 39; idtb_endereco = 40; idtb_tipotran = 41; idtb_BRTrib_Tipo = 42; idtb_bk_control = 43; idtb_bk_process = 44; idtb_bk_upload = 45; idtb_LinkXML = 46; idtb_Marca = 47; idtb_xmls_compra = 48; idtb_cfop_dev = 49; idtb_DadosFiscais = 50; idtb_SolicitacoesSped = 51; idtb_Sped_C190 = 52; idtb_Sped_E210 = 53; idtb_movEstSped = 54; bk_status_criar_json = 0; bk_status_enviar = 1; bk_status_enviado = 2; wm_registrapag = wm_user; wm_processacotas = wm_user + 1; wm_abreserv = wm_user + 3; wm_alterouchorario = wm_user + 4; wm_abreaba = wm_user + 6; wm_removesession = wm_user + 7; wm_salvatranpopup = wm_user + 8; wm_DownloadIntInfo = wm_user + 9; wm_autoprintpdf = wm_user + 10; wm_refreshurls = wm_user + 11; wm_refreshnfconfig = wm_user + 12; wm_nfeupdated = wm_user + 13; wm_updatenfconfig = wm_user + 14; wm_newcanc = wm_user + 15; wm_newtrans = wm_user + 16; wm_instaladepend = wm_user + 17; wm_newgerar = wm_user + 18; wm_newpostms = wm_user + 19; wm_sinaliza_nexapp = wm_user + 20; wm_newconsulta = wm_user + 21; wm_newcce = wm_user + 22; wm_sinaliza_bk = wm_user + 23; wm_startadmin = wm_user + 24; wm_startstep = wm_user + 25; card_status_criar_json = 0; card_status_enviar_json = 1; card_status_json_enviado = 2; card_type_venda = 0; card_type_caixa = 1; card_type_estoque = 2; card_type_faturamento = 3; card_type_aberturacx = 4; card_type_produto = 5; card_type_orcamento = 6; card_type_devolucao = 7; card_type_resync = 255; card_array_cards = 0; card_array_produtos = 1; card_array_name : array[card_array_cards..card_array_produtos] of String = ('cards', 'products'); http_method_reset_store = 0; http_method_post = 1; http_method_put = 2; http_method_delete = 3; //status para lançamento das transações processdas do SPED.... statusProcSped_NaoGera = 0; statusProcSped_Pendente = 1; statusProcSped_OK = 2; statusProcSped_Erro = 3; //status para lançamento das transações processdas do SPED.... statusGeracaoSped_pendente = 0; statusGeracaoSped_ok = 1; statusGeracaoSped_Salvo = 2; statusGeracaoSped_erro = 3; versaoSped = 1; card_type_estoque_min = 201; card_type_estoque_fim = 202; statuscont_enviar = 0; statuscont_chavedif = 1; statuscont_chaveigual = 2; statuscont_ok_chavenormal = 3; statuscont_ok_chavecont = 4; statuscont_erro = 5; nfetran_naoemitir = 0; nfetran_gerar = 1; nfetran_transmitir = 2; nfetran_contingencia = 20; nfetran_consultar = 30; nfetran_erro = 50; nfetran_ok = 100; nfetran_ok_cont = 101; nfestatus_transmitir = 2; nfestatus_contingencia = 20; nfestatus_consultar = 30; nfestatus_erro = 50; nfestatus_ok = 100; nfestatus_ok_cont = 101; //Rodrigo tiponfe_nenhum = 0; tiponfe_nfce = 1; tiponfe_sat = 2; tiponfe_nfe = 3; tipofor_produtos = 0; tipofor_transp = 1; tipofor_entregador = 2; peso_vol_nao_enviar = 0; peso_vol_auto = 1; peso_vol_manual = 2; DocParams_pt : Array[0..17] of String = ( 'RecNomeLoja', 'RecRodape', 'DocParam_Email', 'DocParam_Tel', 'DocParam_Tel2', 'DocParam_Cidade', 'DocParam_End', 'DocParam_CEP', 'DocParam_CNPJ', 'DocParam_IE', 'DocParam_Site', 'DocParam_Facebook', 'DocParam_Instagram', 'DocParam_Whats', 'DocParam_Whats2', 'DocParam_InfoExtra', 'DocParam_Logo', 'DocParam_Logo2'); DocParams_en : Array[0..17] of String = ( 'RecStoreName', 'RecFooter', 'DocParam_Email', 'DocParam_Phone', 'DocParam_Phone2', 'DocParam_City', 'DocParam_Address', 'DocParam_PostCode', 'DocParam_CNPJ', 'DocParam_DocId', 'DocParam_Website', 'DocParam_Facebook', 'DocParam_Instagram', 'DocParam_WhatsApp', 'DocParam_WhatsApp2', 'DocParam_ExtraInfo', 'DocParam_Logo', 'DocParam_Logo2'); tipo_opest_venda = 1; tipo_opest_devvenda = 2; tipo_opest_compra = 3; tipo_opest_devcompra = 4; tipo_opest_outros_ent = 98; tipo_opest_outros_sai = 99; sat_outros = 0; sat_bematech = 1; sat_dimep = 2; sat_elgin = 3; sat_kryptus = 4; sat_sweda = 5; sat_tanca = 6; sat_nitere = 7; sat_ultimo = sat_nitere; sat_strings : array[0..sat_ultimo] of string = ( 'Outros', 'Bematech', 'Dimep', 'Elgin', 'Kryptus', 'Sweda', 'Tanca', 'Nitere'); tipocert_a1 = 0; tipocert_a3 = 2; nfcfg_nfce = 0; nfcfg_sat = 2; statuscanc_nfe_processarnfe = 1; statuscanc_nfe_processatran = 2; statuscanc_nfe_rej = 3; statuscanc_nfe_erro = 4; statuscanc_nfe_ok = 5; statusinut_nfe_processar = 1; statusinut_nfe_rej = 2; statusinut_nfe_erro = 3; statusinut_nfe_ok = 4; statuscce_enviar = 0; statuscce_ok = 1; statuscce_erro = 2; // Posição da barra de login do NexGuard poslogin_centro = 0; poslogin_topo = 1; poslogin_rodape = 2; orcamento_pendente = 0; orcamento_aprovado = 1; orcamento_vendido = 2; orcamento_recusado = 3; orcamento_expirado = 4; tipodoc_venda = 0; tipodoc_orcamento = 1; tipodoc_etiqueta = 2; tipodoc_pgdebito = 3; tipodoc_nfce = 4; tipodoc_sat = 5; tipodoc_pedido = 6; tipodoc_nfe = 7; tipodoc_demdeb = 99; idtab_tran = 1; idtab_orcamento = 2; idtab_transp = 3; satAmb = 1; const uf_br : array[0..26] of string[2] = ('AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO'); classid_TncTaxItem = 10; classid_TncMovEst = 11; classid_TncTaxItens = 13; classid_TncPagEspecie = 13; classid_TncPagEspecies = 14; classid_TncTransacao = 15; classid_TncItemMovEst = 20; classid_TncItensMovEst = 21; classid_TncTransacoes = 25; classid_TncItemDebito = 30; classid_TncItensDebito = 31; wm_biometria = wm_user + 100; wm_infocampanha = wm_user + 101; wm_atualizadireitosconfig = wm_user + 102; // Modo de exibir o cronômetro nas máquinas clientes quando o cliente possui créditos mecApenasCredValidos = 0; mecMostrarTotal = 1; prefixo_versao = 'C'; nomeprog = 'Nex'; pagesp_misto = High(Word); // tamanho tela tamTelaNormal = 0; tamTelaPDV1 = 1; // conteudo do caixa por e-amil cceMovEstoque = 0; cceEstoqueAbaixoMin = 1; cceTransacoesDesc = 2; cceTransacoesCanc = 3; cceTransacoesObs = 4; cceTodasTran = 5; // opção de censura horário opchSemCensura = 1; opchCHorario = 2; opchCensuraEsp = 3; TicksPorSegundo = 1000; TicksPorMinuto = 60 * TicksPorSegundo; TicksPorHora = 60 * TicksPorMinuto; TicksPorDia = 24 * TicksPorHora; opcota_liberarauto = 0; opcota_confirmar = 1; printeng_adobe = 0; printeng_clprint = 1; printeng_gnostice = 2; opexcesso_cancelarauto = 0; opexcesso_confirmar = 1; // Opcao de repetição de tarifa rtUltima = 0; rtTodas = 1; rtDesde = 2; // Direitos da Maquina dmNenhum = 0; dmFree = 1; dmPremium = 2; dmDef = 3; dmParcial = 4; // Opcao de Tipo de Divisao de Tarifa por Minuto tdtPorTempo = 0; tdtPorValor = 1; eppPausarAcesso = 0; eppEncerrarAcesso = 1; SessionUser = 'admin'; SessionPass = 'delphi9856'; PortaKBMMW = 41592; BitsH : Array[0..23] of Cardinal = ( $1, $2, $4, $8, $10, $20, $40, $80, $100, $200, $400, $800, $1000, $2000, $4000, $8000, $10000, $20000, $40000, $80000, $100000, $200000, $400000, $800000); // Opções de Bloqueio quando cair a rede obPermitePrePago = 0; obPermitePosPago = 1; obBloqueioTotal = 2; obFecharCMGuard = 3; // Status de Impressão siPausado = 0; siProcessando = 1; siRegistrou = 2; BoolStr : Array[Boolean] of Char = ('0', '1'); BoolString : Array[Boolean] of String = ('False', 'True'); mdDemo = -1; mdLiberado = 0; MinCreditoLoginMS = 5000; HorasSemana = 7 * 24; SegundosPorDia = 60 * 60 * 24; MSPorDia = SegundosPorDia * 1000; MSPorSemana = MSPorDia * 7; operLogoff = 0; operShutdown = 1; operReboot = 2; operFecharNex = 3; // Controle de Impressoes ciDesativado = 0; ciMonitorar = 1; ciRegistrar = 2; // Tipos de Transação { ttAcesso = 0; ttVendaPacote = 1; ttCreditoTempo = 2; ttManutencao = 3; ttAcessoVenda = 4; ttDebitoTempo = 5; ttSinal = 6; ttEstVenda = 7; ttEstCompra = 8; ttEstEntrada = 9; ttEstSaida = 10; ttPagtoDebito = 11; ttSuprimentoCaixa = 12; ttSangriaCaixa = 13; ttVendaPassaporte = 14;} trAddCredito = 2; trRemCredito = 3; trEstVenda = 4; trEstCompra = 5; trEstEntrada = 6; trEstSaida = 7; trPagDebito = 8; trCaixaEnt = 9; trCaixaSai = 10; trCorrDataCx = 13; trAjustaFid = 14; trAjustaCusto = 16; trZerarEstoque = 17; trEstDevolucao = 18; trEstDevFor = 19; trEstTransf = 20; trEstTransfEnt = 21; trEstOutEntr = 22; trMax = trEstOutEntr; itMovEst = 1; itCredito = 2; itTran = 3; itAjustaFid = 5; itFrete = 6; // Tipo de Operação Fidelidade tofNenhum = 0; tofAcumulo = 1; tofResgate = 2; tofCorrecao = 3; // Tipo Prêmio Automático tpaPac = 0; tpaPassaporte = 1; // Tipo Cliente tcNormal = 0; tcCliGratis = 1; tcManutencao = 2; // Tipos de Crédito de Tempo tctPrevisao = 0; tctAvulso = 1; tctPassaporte = 2; tctPacote = 3; tctCartaoTempo= 4; tctLivre = 5; tctDiv = 6; tctDiv2 = 7; // Modos de Pagamento mpgTelaPagtoAutomatica = 0; mpgDuploCliqueMaq = 1; mpgSomenteTransacoes = 2; clAzulNEX = $B76311; { StTipoTransacao : Array[trInicioSessao..trAjustaFid] of String = ( 'Inicio de Sessão', 'Fim de Sessão', 'Crédito Tempo', 'Débito Tempo', 'Venda', 'Compra', 'Entrada Estoque', 'Saida Estoque', 'Pagamento Débito', 'Suprimento Caixa', 'Sangria Caixa', 'Impressão', 'Transf.Máquina', 'Correção Data Caixa', 'Correção Pontos Fid'); AbrevTipoTransacao : Array[trInicioSessao..trAjustaFid] of String = ( 'Inicio', 'Fim', 'Cred.Tempo', 'Déb.Tempo', 'Venda', 'Compra', 'Entrada Est', 'Saida Est.', 'Pg.Débito', 'Suprimento', 'Sangria', 'Impressão', 'Transf.Máq', 'Corr.Data.Cx', 'Corr.Pontos'); } // Tipos de Cadastros tipocad_nenhum = 0; tipocad_cliente = 1; tipocad_fornecedor = 2; tipocad_filial = 3; // Tipos de Classes tcCliente = 2; tcUsuario = 4; tcConfig = 6; tcMovEst = 10; tcEspecie = 14; tcTipoTran = 15; ProxyUsername = 'proxy'; ProxySenha = 'proxypass'; // Tipo Expiração teNunca = 0; teDias = 1; teHoras = 2; teAcessos = 3; teDataMarcada = 4; // Operacao Salvar osNenhuma = 0; osIncluir = 1; osAlterar = 2; osExcluir = 3; osCancelar = 4; // Tipos de Tipos de Acesso ttaServico = 0; ttaCliente = 1; ttaMaquina = 2; // Opcoes para Chat ochJanelaVisivel = 0; ochJanelaEscondida = 1; ochDesabilitar = 2; // PM_CalcValorCli pm_cvc_Intervalo = 0; pm_cvc_Minimo = 1; pm_cvc_Maximo = 2; // JOb Control jc_pause = 0; jc_resume = 1; jc_delete = 2; BoolToString : Array[Boolean] of String[5] = ('False', 'True'); chFldDelim = #1'nexflddelim'; chListaDelim = #2'nexlistdelim'; recurso_vendadireta = 1; recurso_vendabalcao = 2; recurso_alimentacao = 3; type TInfoCampanha = class icCampanha : String; icutmccn : String; icutmctr : String; icutmcct : String; icutmcmd : String; icutmcsr : String; end; TSessionSocket = record ssSession : Integer; ssSocket : Integer; end; TFaixaIntItem = record fiDe, fiAte: Integer; end; TArraySessionSocket = Array of TSessionSocket; TArrayTempo = Array[0..23] of Double; TArrayTipoTran = Array[0..trAjustaFid] of Boolean; PArrayTipoTran = ^TArrayTipoTran; ncPString = ^String; EErroNexCafe = class(Exception) public CodigoErro: Integer; ErroSocket: Integer; constructor Create(CE: Integer); end; TncDadosCliente = object dcCodigo: Integer; dcNome : String; end; TncServidorBase = class; TncClasse = class; TncCliente = class; TncUsuario = class; TTipoNotificacao = (tnCriacao, tnAlteracao, tnDestruicao); TProcNotificacao = procedure (Obj: TncClasse; TipoNot: TTipoNotificacao) of object; TncClasse = class ( TClasseCS ) private FProcNotificar: TProcNotificacao; protected property ProcNotificar: TProcNotificacao read FProcNotificar write FProcNotificar; public constructor Create; destructor Destroy; override; procedure Notificar(TipoNot: TTipoNotificacao); function TipoClasse: Integer; virtual; abstract; end; TncCodBarBalInfo = object Codigo : String; PesoValor : Double; BalValor : Boolean; procedure Clear; function IsEmpty: Boolean; end; {$METHODINFO ON} TncConfig = class ( TncClasse ) private FEndereco_Loja : TGuid; FManterSaldoCaixa : Boolean; FEscondeTextoBotoes : Boolean; FRecImprimir : Byte; // 0=Nao Imprimir, 1=Imprimir Todos, 2=Imprimir Alguns FRecTipoImpressora : String; FRecMatricial : Boolean; FRecPorta : String; FRecSalto : Byte; FRecLargura : Byte; FRecCortaFolha : Boolean; FRecRodape : String; FRecNomeLoja : String; FRecImprimeMeioPagto : Boolean; FRecPrefixoMeioPagto : String; FNomeCodigo2 : String; FPais : String; Ftax_id_default : Cardinal; FDocParam_Email : String; FDocParam_Tel : String; FDocParam_Tel2 : String; FDocParam_Cidade : String; FDocParam_End : String; FDocParam_CEP : String; FDocParam_CNPJ : String; FDocParam_IE : String; FDocParam_Site : String; FDocParam_Facebook : String; FDocParam_Instagram : String; FDocParam_Whats : String; FDocParam_Whats2 : String; FDocParam_InfoExtra : String; FRecAddObsItem : Boolean; FEmailIdent : String; FCampoLocalizaCli : Byte; FLimitePadraoDebito : Double; FConta : String; FCodEquip : String; FQtdLic : Integer; FStatusConta : TStatusConta; FVerPri : Word; FFreePremium : Boolean; FPro : Boolean; FDataLic : TDateTime; FDVA : TDateTime; FProxAvisoAss : TDatetime; FPreLib : Boolean; FAlertaAssinatura : Boolean; FJaFoiPremium : Boolean; FMeioPagto : Byte; FEmailEnviarCaixa : Boolean; FEmailDestino : String; FEmailConteudo : String; FRelCaixaAuto : Boolean; FNaoVenderAlemEstoque : Boolean; FAutoSortGridCaixa : Boolean; FFidAtivo : Boolean; FFidVendaValor : Currency; FFidVendaPontos : Integer; FFidParcial : Boolean; FFidAutoPremiar : Boolean; FFidAutoPremiarValor : Currency; FFidAutoPremiarPontos : Integer; FFidMostrarSaldoAdmin : Boolean; FFidMsg : Boolean; FFidMsgTitulo : String; FFidMsgTexto : String; FAutoObsAoCancelar : Boolean; FPastaDownload : String; FExigeDadosMinimos : Boolean; FCidadePadrao : String; FUFPadrao : String; FDadosMinimos : String; FPedirSaldoI : Boolean; FPedirSaldoF : Boolean; FCamposCliCC : TStrings; fAutoCad : boolean; fQuickCad : boolean; fCodProdutoDuplicados : boolean; fMargem : double; fPrecoAuto : boolean; FServerDir : String; FBanners : String; FBotoes : String; FRecursos : String; FConfirmarDebito : Boolean; FComissaoPerc : Double; FComissaoLucro : Boolean; FCodBarBal : Boolean; FCodBarBalTam : Byte; FCodBarBalIdent : String; FCodBarBalInicioCod : Byte; FCodBarBalTamCod : Byte; FCodBarBalValor : Boolean; FCodBarBalPPInicio : Byte; FCodBarBalPPTam : Byte; FCodBarBalPPDig : Byte; FCodBarMaxQtdDig : Byte; FCodBarArredondar : Byte; FTelaPosVenda_Mostrar : Boolean; FTelaPosVenda_BtnDef : Byte; FTamCodigoAuto : Byte; Ffmt_moeda : Boolean; Ffmt_decimais : Byte; Ffmt_simbmoeda : string; Ffmt_sep_decimal : string; Ffmt_sep_milhar : string; FLastApplyFmtMoeda : String; FExigirVendedor : Boolean; FValOrc_Tempo : Word; FValOrc_UTempo : Byte; FEmailOrc_Enviar : Boolean; FEmailOrc_FromName : String; FEmailOrc_FromEmail : String; FEmailOrc_Subject : String; FEmailOrc_Body : String; FDocOrc_Imprimir : Boolean; FDocOrc_NomeLoja : String; FObsPadraoOrcamento : String; FTrocoMax : Currency; FObsNF : Boolean; FslFlags : TStrings; FUrls : String; FTranspEntPadrao : Cardinal; FFretePadrao : Currency; FDesativarFrete : Boolean; FDesativarTranspEnt : Boolean; FmodFretePadrao : Byte; function GetCamposCliCCText: String; procedure SetCamposCliCCText(const Value: String); function GetServerDir: String; function GetRecursoOn(aIndex: Integer): Boolean; procedure SetRecursoOn(aIndex: Integer; const Value: Boolean); function GetRecBobina: Boolean; procedure SetRecBobina(const Value: Boolean); procedure SetConta(const Value: String); function GetDTol: Byte; procedure SetDTol(const Value: Byte); function GetUrls: String; procedure SetUrls(const Value: String); function GetFlags: String; procedure SetFlags(const Value: String); function GetEndereco_Loja: String; procedure SetEndereco_Loja(const Value: String); protected function GetChave: Variant; override; procedure SetVerPri(const Value: Word); public function TipoClasse: Integer; override; function CalcPontos(aValor: Currency): Double; constructor Create; destructor Destroy; override; procedure AssignConfig(C : TncConfig); procedure ApplyFmtMoeda; function cxMaskUnitario: String; property slFlags: TStrings read FslFlags; function cce(acce: Integer): Boolean; function FidAutoPremiarAtivo: Boolean; function FidPremiarAutomaticamente(aPontos: Double): Boolean; function CodLojaInt: Integer; function DadosMinOk(T: TDataset): Boolean; function IsPremium: Boolean; function TrialPremium: Boolean; function TrialPro: Boolean; function IsFree: Boolean; function OnTrial: Boolean; function TolerandoPor: Integer; function TolDiasRestantes: Integer; function TrialDiasRestantes: Integer; function TrialVencido: Boolean; function CalcPreco(aMargem: Variant; aCusto: Currency): Currency; function DecodeCodBarBalanca(aCodigo: String; var aInfo: TncCodBarBalInfo): Boolean; function PrecisaoBalanca(aValor: Extended): Extended; function RecPrinterGeneric: Boolean; function ImpOutras: Boolean; function PodeFidelidade: Boolean; function PaisNorm: String; function PaisBrasil: Boolean; property End_Loja_Nativo: TGuid read FEndereco_Loja write FEndereco_Loja; property RecursoOn[aIndex: Integer]: Boolean read GetRecursoOn write SetRecursoOn; property slCamposCliCC: TStrings read FCamposCliCC; property RecBobina: Boolean read GetRecBobina write SetRecBobina; published property TamCodigoAuto: Byte read FTamCodigoAuto write FTamCodigoAuto; property fmt_moeda: Boolean read Ffmt_moeda write Ffmt_moeda; property fmt_decimais: Byte read Ffmt_decimais write Ffmt_decimais; property fmt_simbmoeda: string read Ffmt_simbmoeda write Ffmt_simbmoeda; property fmt_sep_decimal: string read Ffmt_sep_decimal write Ffmt_sep_decimal; property fmt_sep_milhar: string read Ffmt_sep_milhar write Ffmt_sep_milhar; property Endereco_Loja: String read GetEndereco_Loja write SetEndereco_Loja; property ValOrc_Tempo: Word read FValOrc_Tempo write FValOrc_Tempo; property ValOrc_UTempo: Byte read FValOrc_UTempo write FValOrc_UTempo; property ObsPadraoOrcamento: String read FObsPadraoOrcamento write FObsPadraoOrcamento; property ObsNF: Boolean read FObsNF write FObsNF; property EmailOrc_Enviar : Boolean read FEmailOrc_Enviar write FEmailOrc_Enviar; property EmailOrc_FromName: String read FEmailOrc_FromName write FEmailOrc_FromName; property EmailOrc_FromEmail: String read FEmailOrc_FromEmail write FEmailOrc_FromEmail; property EmailOrc_Subject: String read FEmailOrc_Subject write FEmailOrc_Subject; property EmailOrc_Body: String read FEmailOrc_Body write FEmailOrc_Body; property DocOrc_Imprimir : Boolean read FDocOrc_Imprimir write FDocOrc_Imprimir; property DocOrc_NomeLoja : String read FDocOrc_NomeLoja write FDocOrc_NomeLoja; property CodProdutoDuplicados: boolean read fCodProdutoDuplicados write fCodProdutoDuplicados; property AutoCad: boolean read fAutoCad write fAutoCad; property QuickCad: boolean read fQuickCad write fQuickCad; property Margem: double read fMargem write fMargem; property PrecoAuto: boolean read fPrecoAuto write fPrecoAuto; property ComissaoPerc: Double read FComissaoPerc write FComissaoPerc; property ComissaoLucro: Boolean read FComissaoLucro write FComissaoLucro; property CodBarBal: Boolean read FCodBarBal write FCodBarBal; property CodBarBalTam: Byte read FCodBarBalTam write FCodBarBalTam; property CodBarBalIdent: String read FCodBarBalIdent write FCodBarBalIdent; property CodBarBalInicioCod: Byte read FCodBarBalInicioCod write FCodBarBalInicioCod; property CodBarBalTamCod: Byte read FCodBarBalTamCod write FCodBarBalTamCod; property CodBarBalValor: Boolean read FCodBarBalValor write FCodBarBalValor; property CodBarBalPPInicio: Byte read FCodBarBalPPInicio write FCodBarBalPPInicio; property CodBarBalPPTam: Byte read FCodBarBalPPTam write FCodBarBalPPTam; property CodBarBalPPDig: Byte read FCodBarBalPPDig write FCodBarBalPPDig; property CodBarMaxQtdDig: Byte read FCodBarMaxQtdDig write FCodBarMaxQtdDig; property CodBarArredondar: Byte read FCodBarArredondar write FCodBarArredondar; property RecImprimir: Byte read FRecImprimir write FRecImprimir; property RecTipoImpressora: String read FRecTipoImpressora write FRecTipoImpressora; property RecMatricial: Boolean read FRecMatricial write FRecMatricial; property RecPorta: String read FRecPorta write FRecPorta; property RecSalto: Byte read FRecSalto write FRecSalto; property RecLargura : Byte read FRecLargura write FRecLargura; property RecCortaFolha : Boolean read FRecCortaFolha write FRecCortaFolha; property RecRodape: String read FRecRodape write FRecRodape; property RecNomeLoja: String read FRecNomeLoja write FRecNomeLoja; property RecImprimeMeioPagto: Boolean read FREcImprimeMeioPagto write FRecImprimeMeioPagto; property RecPrefixoMeioPagto: String read FRecPrefixoMeioPagto write FRecPrefixoMeioPagto; property DocParam_Email: String read FDocParam_Email write FDocParam_Email; property DocParam_Tel: String read FDocParam_Tel write FDocParam_Tel; property DocParam_Tel2: String read FDocParam_Tel2 write FDocParam_Tel2; property DocParam_Cidade: String read FDocParam_Cidade write FDocParam_Cidade; property DocParam_End: String read FDocParam_End write FDocParam_End; property DocParam_CEP: String read FDocParam_CEP write FDocParam_CEP; property DocParam_CNPJ: String read FDocParam_CNPJ write FDocParam_CNPJ; property DocParam_IE: String read FDocParam_IE write FDocParam_IE; property DocParam_Site: String read FDocParam_Site write FDocParam_Site; property DocParam_Facebook: String read FDocParam_Facebook write FDocParam_Facebook; property DocParam_Instagram: String read FDocParam_Instagram write FDocParam_Instagram; property DocParam_Whats: String read FDocParam_Whats write FDocParam_Whats; property DocParam_Whats2: String read FDocParam_Whats2 write FDocParam_Whats2; property DocParam_InfoExtra: String read FDocParam_InfoExtra write FDocParam_InfoExtra; property RecAddObsItem: Boolean read FRecAddObsItem write FRecAddObsItem; property ManterSaldoCaixa: Boolean read FManterSaldoCaixa write FManterSaldoCaixa; property EscondeTextoBotoes: Boolean read FEscondeTextoBotoes write FEscondeTextoBotoes; property CampoLocalizaCli: Byte read FCampoLocalizaCli write FCampoLocalizaCli; property LimitePadraoDebito: Double read FLimitePadraoDebito write FLimitePadraoDebito; property Conta: String read FConta write SetConta; property FreePremium: Boolean read FFreePremium write FFreePremium; property Pro: Boolean read FPro write FPro; property DVA: TDateTime read FDVA write FDVA; property DTol: Byte read GetDTol write SetDTol; property PreLib: Boolean read FPreLib write FPreLib; property ProxAvisoAss: TDateTime read FProxAvisoAss write FProxAvisoAss; property DataLic: TDateTime read FDataLic write FDataLic; property MeioPagto: Byte read FMeioPagto write FMeioPagto; property AlertaAssinatura: Boolean read FAlertaAssinatura write FAlertaAssinatura; property JaFoiPremium: Boolean read FJaFoiPremium write FJaFoiPremium; property CodEquip: String read FCodEquip write FCodEquip; property QtdLic: Integer read FQtdLic write FQtdLic; property StatusConta: TStatusConta read FStatusConta write FStatusConta; property VerPri: Word read FVerPri write SetVerPri; property EmailEnviarCaixa: Boolean read FEmailEnviarCaixa write FEmailEnviarCaixa; property EmailIdent: String read FEmailIdent write FEmailIdent; property EmailDestino: String read FEmailDestino write FEmailDestino; property EmailConteudo: String read FEmailConteudo write FEmailConteudo; property RelCaixaAuto: Boolean read FRelCaixaAuto write FRelCaixaAuto; property NaoVenderAlemEstoque: Boolean read FNaoVenderAlemEstoque write FNaoVenderAlemEstoque; property AutoSortGridCaixa : Boolean read FAutoSortGridCaixa write FAutoSortGridCaixa; property AutoObsAoCancelar: Boolean read FAutoObsAoCancelar write FAutoObsAoCancelar; property FidAtivo: Boolean read FFidAtivo write FFidAtivo; property FidVendaValor: Currency read FFidVendaValor write FFidVendaValor; property FidVendaPontos: Integer read FFidVendaPontos write FFidVendaPontos; property FidParcial: Boolean read FFidParcial write FFidParcial; property FidAutoPremiar : Boolean read FFidAutoPremiar write FFidAutoPremiar; property FidAutoPremiarValor: Currency read FFidAutoPremiarValor write FFidAutoPremiarValor; property FidAutoPremiarPontos: Integer read FFidAutoPremiarPontos write FFidAutoPremiarPontos; property FidMostrarSaldoAdmin: Boolean read FFidMostrarSaldoAdmin write FFidMostrarSaldoAdmin; property FidMsg: Boolean read FFidMsg write FFidMsg; property FidMsgTitulo: String read FFidMsgTitulo write FFidMsgTitulo; property FidMsgTexto: String read FFidMsgTexto write FFidMsgTexto; property PastaDownload: String read FPastaDownload write FPastaDownload; property ExigeDadosMinimos: Boolean read FExigeDadosMinimos write FExigeDadosMinimos; property CidadePadrao: String read FCidadePadrao write FCidadePadrao; property UFPadrao: String read FUFPadrao write FUFPadrao; property DadosMinimos: String read FDadosMinimos write FDadosMinimos; property PedirSaldoI: Boolean read FPedirSaldoI write FPedirSaldoI; property PedirSaldoF: Boolean read FPedirSaldoF write FPedirSaldoF; property CamposCliCC: String read GetCamposCliCCText write SetCamposCliCCText; property ServerDir: String read GetServerDir write FServerDir; property Banners: String read FBanners write FBanners; property Botoes: String read FBotoes write FBotoes; property Recursos: String read FRecursos write FRecursos; property ConfirmarDebito: Boolean read FConfirmarDebito write FConfirmarDebito; property ExigirVendedor: Boolean read FExigirVendedor write FExigirVendedor; property TelaPosVenda_Mostrar: Boolean read FTelaPosVenda_Mostrar write FTelaPosVenda_Mostrar; property TelaPosVenda_BtnDef: Byte read FTelaPosVenda_BtnDef write FTelaPosVenda_BtnDef; property Urls: String read GetUrls write SetUrls; property TrocoMax: Currency read FTrocoMax write FTrocoMax; property Flags: String read GetFlags write SetFlags; property Pais: String read FPais write FPais; property NomeCodigo2: String read FNomeCodigo2 write FNomeCodigo2; property tax_id_def: Cardinal read Ftax_id_default write Ftax_id_default; property TranspEntPadrao : Cardinal read FTranspEntPadrao write FTranspEntPadrao; property FretePadrao : Currency read FFretePadrao write FFretePadrao; property modFretePadrao: Byte read FmodFretePadrao write FmodFretePadrao; property DesativarFrete : Boolean read FDesativarFrete write FDesativarFrete; property DesativarTranspEnt : Boolean read FDesativarTranspEnt write FDesativarTranspEnt; end; {$METHODINFO OFF} TncCliente = class ( TncClasse ) private FHandle : Integer; FRemoto : Boolean; FUsername : String; FWndHandle : HWND; FProxyHandle: Integer; FSocket : Integer; FInicio : TDateTime; FSessionID : Integer; protected function GetChave: Variant; override; public constructor Create; function TipoClasse: Integer; override; function Proxy: Boolean; published property Handle: Integer read FHandle write FHandle; property Remoto: Boolean read FRemoto write FRemoto; property UserName: String read FUserName write FUserName; property WndHandle: HWND read FWndHandle write FWndHandle; property ProxyHandle: Integer read FProxyHandle write FProxyHandle; property Socket: Integer read FSocket write FSocket; property Inicio: TDateTime read FInicio Write FInicio; property SessionID: Integer read FSessionID write FSessionID; end; TncUsuario = class ( TncClasse ) private FNumClientes : Integer; // número de clientes atualmente conectados nesse usuário FUsername : String; FAdmin : Boolean; FInativo : Boolean; FSenha : String; FDireitos : String; FNome : String; FEmail : String; FLimiteDesc : Double; protected function GetChave: Variant; override; procedure SetNumClientes(Valor: Integer); virtual; procedure SetUsername(Valor: String); virtual; procedure SetAdmin(Valor: Boolean); virtual; procedure SetSenha(Valor: String); virtual; procedure SetDireitos(Valor: String); virtual; procedure SetNome(Valor: String); virtual; public constructor Create; function TipoClasse: Integer; override; function PodeDesconto(aTotal, aDesc: Currency): Boolean; function LimiteDescOk(aPerc: Double): Boolean; published property NumClientes: Integer read FNumClientes write SetNumClientes; property Username: String read FUsername write SetUsername; property Nome: String read FNome write SetNome; property Admin: Boolean read FAdmin write SetAdmin; property Senha: String read FSenha write SetSenha; property Direitos: String read FDireitos write SetDireitos; property Email: String read FEmail write FEmail; property LimiteDesc: Double read FLimiteDesc write FLimiteDesc; property Inativo: Boolean read FInativo write FInativo; end; TncListaUsuarios = class ( TListaClasseCS ) private function GetUsuario(I: Integer): TncUsuario; function GetUsuarioPorUsername(N: String): TncUsuario; public constructor Create; function EmailUsuario(aUsername: String): String; function AdminAtivos: Integer; property Itens[I: Integer]: TncUsuario read GetUsuario; default; property PorUsername[N: String]: TncUsuario read GetUsuarioPorUsername; end; TncEnviaEvento = procedure (aMsg: Integer; aDados: Pointer) of object; TncServidorBase = class ( TComponent ) private FUltimoHandle : Integer; FOnEnviaEvento : TncEnviaEvento; function NumClientesLocais: Integer; protected FClientes: TThreadList; FAtivo : Boolean; procedure AoRemoverCliente(Cliente: TncCliente); virtual; function ObtemCliente(aHandle: Integer): TncCliente; procedure EnviaEvento(Mensagem: Integer; Dados: Pointer); procedure AddCliente(Obj: TncCliente); procedure RemoveCliente(Obj: TncCliente); function ProximoHandle: Integer; procedure SetAtivo(Valor: Boolean); virtual; procedure DesativaClientes; procedure ChecaErro(Erro: Integer); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class procedure Lock; class procedure Unlock; procedure ObtemSessionSocketArray(var SS: TArraySessionSocket); function ObtemUsernameHandlePorSessionID(aSessionID: Integer; var aUsername: String; var aHandle: Integer): Boolean; function ObtemLista(aTipoClasse: Integer): TListaClasseCS; virtual; abstract; function ObtemClientePorSocket(Socket: Integer): TncCliente; function ObtemClientePorSessionID(aSessionID: Integer): TncCliente; function ObtemPastaServ(var NomePastaServ: String): Integer; virtual; function SalvaMovEst(aObj: TObject): Integer; virtual; abstract; function SalvaDebito(aObj: TObject): Integer; virtual; abstract; function SalvaLancExtra(aObj: TObject): Integer; virtual; abstract; function SalvaCredito(aObj: TObject): Integer; virtual; abstract; function AbreCaixa(aFunc: String; aSaldo: Currency; var NovoCx: Integer): Integer; virtual; abstract; function FechaCaixa(aFunc: String; aSaldo: Currency; aID: Integer): Integer; virtual; abstract; function ReprocCaixa(aFunc: String; aID: Integer): Integer; virtual; abstract; function CorrigeDataCaixa(aFunc: String; aID: Integer; aNovaAbertura, aNovoFechamento: TDateTime): integer; virtual; abstract; function AjustaPontosFid(aFunc: String; aCliente: Integer; aFator: Smallint; aPontos: Double; aObs: String): Integer; virtual; abstract; function ZerarEstoque(aFunc: String): integer; virtual; abstract; function ObtemCertificados(sl: TStrings): integer; virtual; abstract; function ReemitirNFCe(aTran: TGuid): integer; virtual; abstract; function GeraXMLProt(aChave: String): integer; virtual; abstract; function InutilizarNFCE(aNFe: Boolean; aAno: Word; aInicio, aFim: Cardinal; aJust: String; aResposta: TStrings): integer; virtual; abstract; function ConsultarSAT(aResposta: TStrings): integer; virtual; abstract; function InstalaNFCeDepend : Integer; virtual; abstract; function InstalaNFeDepend : Integer; virtual; abstract; function Upload(aFonte, aDestino: String): Integer; virtual; function Download(aFonte, aDestino: String): Integer; virtual; function DownloadArqInterno(aArq: String; aVerCli: Integer; aDestino: String): Integer; virtual; abstract; function SalvaStreamObj(Novo: Boolean; S: TStream): Integer; virtual; abstract; function ObtemStreamConfig(S: TStream): integer; virtual; abstract; function ObtemStreamListaObj(Cliente: Integer; TipoClasse: Integer; S: TStream): Integer; virtual; abstract; function ApagaObj(Cliente: Integer; TipoClasse: Integer; Chave: String): Integer; virtual; abstract; function Login(aUsername, aSenha: String; aFuncAtual: Boolean; aRemoto: Boolean; aWndHandle: HWND; aProxyHandle: Integer; aSocket: Integer; aSessionID: Integer; aIP: String; var Handle: Integer): Integer; virtual; function CancelaTran(aID: Integer; aFunc: String): integer; virtual; abstract; function SalvaLic(aLic: String): Integer; virtual; abstract; function SalvaApp(aApp: String): Integer; virtual; abstract; function BaixaNovaVersao(Programa, Versao, ArqDestino: String): Integer; virtual; function TableUpdated(aIDTab : Byte): integer; virtual; abstract; function EnviarMsg(const aDe, aPara: Integer; const aTexto: String): Integer; virtual; abstract; procedure Logout(Cliente: Integer); virtual; procedure LogoutSocket(Socket: Integer); virtual; procedure LogoutSession(aSessionID: Integer); virtual; function EnviarEventos: Boolean; virtual; published property OnEnviaEvento: TncEnviaEvento read FOnEnviaEvento write FOnEnviaEvento; property Ativo: Boolean read FAtivo write SetAtivo; end; TThreadRename = class ( TThread ) private FArqNovo: String; FArqVelho: String; public constructor Create(aArqNovo, aArqVelho: String); procedure Execute; override; end; TThreadDeleteFile = class ( TThread ) private FArq: String; FTryForMS: Cardinal; public constructor Create(aArq: String; aTryForMS: Cardinal); procedure Execute; override; end; function TicksToHMSSt(Ticks: Cardinal): String; function TicksToDateTime(Ticks: Cardinal): TDateTime; function MinutosToDateTime(M: Double): TDateTime; function MinutosToHoraStr(aMinutos: Extended): String; function SegundosToHMSSt(Seg: Cardinal): String; function SegundosToDateTime(Seg: Cardinal): TDateTime; function DateTimeToTicks(D: TDateTime): Cardinal; function DateTimeToSegundos(D: TDateTime): Cardinal; function DateTimeToMinutos(D: TDateTime): Cardinal; function HMSToMinutos(S: String): Double; function HMToMinutos(S: String): Double; function MSToMinutos(S: String): Double; function MinutosToTicks(M: Double): Cardinal; function TicksToMinutos(Ticks: Cardinal): Double; function Senha(D: TDateTime; NS: Cardinal; NumMaq: Integer): String; function VolumeSerial(DriveChar: Char): string; function CalcAcesso(Acesso, Sinal, Desc: Double): Double; function FormataNumVersao(St: String): String; function DuasCasas(D: Extended; aCasas: Integer = -1): Extended; function ObtemCred(I: Integer): Cardinal; function StringToBool(S: String): Boolean; function FloatParaStr(Valor: Extended): String; function QuantToStr(Valor: Extended): String; function StrParaFloat(S: String): Extended; function GetDTStr(D: TDateTime): String; function DTFromStr(S: String): TDateTime; function GetNextStrDelim(var S: String; aClassID: Byte): String; function GetNextListItem(var sItems, sItem: String; aClassID: Byte): Boolean; function GetNextStrDelimCustom(var S: String; aDelim: String): String; { function StringListToListDelim(aSL: String; aClassID: Byte): String; function StringListFromListDelim(aListDelim: String; aClassID: Byte): String;} procedure StrToLista(S: String; SL: TStrings); function ListaToStr(S: String): String; function MenorCardinal(C1, C2: Cardinal): Cardinal; function MaiorCardinal(C1, C2: Cardinal): Cardinal; function MinutosToHMSStr(aMinutos: Extended): String; function MinutosToHMSAbrev(aMinutos: Extended): String; function CurrencyToStr(C: Currency): String; function PontosFidToStr(D: Double): String; function PercToStr(P: Double): String; function FormataSiteStr(S: String): String; function DomainAndSubdomain(S: String): String; function SetBit(Valor, Bit: Integer; Lig: Boolean): Integer; function BitIsSet(Valor, Bit: Integer): Boolean; function GetVersionBuild(S: String): Integer; function MesmoComputerName(aComp1, aComp2: String): Boolean; function IsWOW64: Boolean; function GuidStringClean(S: String): String; function GuidStringFmt(S: String): String; procedure DeleteFromArraySessionSocket(var SS: TArraySessionSocket; aIndex: Integer); function IsPDFFromNexCafe(aArq: String): Boolean; procedure BroadcastAtualizaDireitosConfig; function LimitaCasasDec(C: Currency): Currency; function SemAcento(S: String): String; function SameTextSemAcento(A, B: String): Boolean; function sFldDelim(aClassID: Byte): String; function sListaDelim(aClassID: Byte): String; function SplitParams(S: String): TStrings; function RemoveAspas(S: String): String; function CodigoCliKey(S: String): String; function FormatEmail(aNome, aEmail: String): String; function EmailValido(aEmail: String): Boolean; function GetValueFromStr(aStr, aName: String): String; procedure SetValueFromStr(var aStr: String; aName, aValue: String); function TimeZoneStr: String; function isCPF(CPF: string): boolean; function isCNPJ(xCNPJ: String): Boolean; function imprimeCPF(CPF: string): string; function SoDig(S: String): String; function StrToBool(S: String; const aDef: Boolean = False): Boolean; function ObsToinfCpl(S: String): String; function infCplToObs(S: String): String; function YMD_Date(S: String): TDateTime; procedure SetTagValue(var S: String; aTag, aValue: String); function INIFName(aServer: Boolean): String; function GetCountryCode: String; function LinguaPT: Boolean; function LinguaES: Boolean; function LinguaEN: Boolean; function TipoTranToStr(const aTipoTran: Byte): String; procedure CheckImgLimit(aSize: Cardinal); function GetFileSize(const FileName: string): LongInt; function RemoveAcento(S: String): String; function FmtNFe(S: String): String; function TipoTranEstoque(aTipo: Byte): Boolean; function TipoTranCaixa(aTipo: Byte): Boolean; function CFOPTemSt(aCFOP: Word): Boolean; function CSOSNTemSt(aCSOSN: Word): Boolean; function ZeroC(C: Cardinal; Tam: Byte): String; function FormatValorSped(aValor: Extended; aDecimais: Integer): String; var glTolerancia: Cardinal = 0; gConfig : TncConfig = nil; EncerrarThreads : Boolean = False; LadoServidor : Boolean = False; NomeCompServ : String = ''; csServ : TCriticalSection; slDadosMin : TStrings; ServidorAtivo : Boolean = False; VerProg : String = ''; gGuardSide : Boolean = True; handleFrmPri : HWND; gPodeCancelarOutroCaixa : Boolean = False; gTabConfigNF : TDataset = nil; slIni : TThreadStringList; DocParams : Array of String; threadvar HandleCliAtual : Integer; UsernameAtual: String; implementation uses Graphics, md5, ncVersoes, forms, ncDebug, math, nexUrls, DateUtils, ncGuidUtils; function ZeroC(C: Cardinal; Tam: Byte): String; begin Result := C.ToString; while Length(Result)<Tam do Result := '0'+Result; end; function CFOPTemSt(aCFOP: Word): Boolean; begin Result := (aCFOP=5401) or (aCFOP=5402) or (aCFOP=5403) or (aCFOP=5405) or (aCFOP=6401) or (aCFOP=6402) or (aCFOP=6403) or (aCFOP=6404); end; function CSOSNTemSt(aCSOSN: Word): Boolean; begin Result := (aCSOSN=201) or (aCSOSN=202) or (aCSOSN=203) or (aCSOSN=900); end; function TipoTranEstoque(aTipo: Byte): Boolean; begin Result := (aTipo>=50) or (aTipo in [ trEstVenda, trEstCompra, trEstEntrada, trEstSaida, trAjustaCusto, trZerarEstoque, trEstDevolucao, trEstDevFor, trEstTransf, trEstTransfEnt, trEstOutEntr]); end; function TipoTranCaixa(aTipo: Byte): Boolean; begin Result := (aTipo in [ trAddCredito, trRemCredito, trEstVenda, trPagDebito, trCaixaEnt, trCaixaSai, trCorrDataCx, trAjustaFid, trEstDevolucao, trEstDevFor, trEstTransf, trEstTransfEnt, trEstOutEntr]); end; function TipoTranToStr(const aTipoTran: Byte): String; begin case aTipoTran of trAddCredito : Result := rsAddCred; trRemCredito : Result := rsRemoverCred; trEstVenda : Result := rsVenda; trEstCompra : Result := rsCompra; trEstEntrada : Result := rsEntradaEst; trEstSaida : Result := rsSaidaEst; trPagDebito : Result := rsPagDebito; trCaixaEnt : Result := rsSuprCaixa; trCaixaSai : Result := rsSangriaCaixa; trCorrDataCx : Result := rsCorrecaoCaixa; trAjustaFid : Result := rsCorrecaoFid; trAjustaCusto : Result := rsAjustaCusto; trZerarEstoque : Result := rsZerarEstoque; trEstDevolucao : Result := rsDevolucao; trEstDevFor : Result := rsDevFor; trEstTransf : Result := rsTransf; trEstTransfEnt : Result := rsTasnsfEnt; trEstOutEntr : Result := rsOutEntr; else Result := ''; end; end; function GetFileSize(const FileName: string): LongInt; var SearchRec: TSearchRec; begin try if FindFirst(ExpandFileName(FileName), faAnyFile, SearchRec) = 0 then Result := SearchRec.Size else Result := -1; finally SysUtils.FindClose(SearchRec); end; end; procedure CheckImgLimit(aSize: Cardinal); begin if aSize>250000 then raise Exception.Create(rsImagemMuitoGrande); end; function LinguaPT: Boolean; begin Result := SameText(SLingua, 'pt') or SameText(SLingua, ''); end; function LinguaES: Boolean; begin Result := SameText(SLingua, 'es'); end; function LinguaEN: Boolean; begin Result := SameText(SLingua, 'en'); end; function GetCountryCode: String; var acBuf : array[0..1024] of Char; begin if GetLocaleInfo( LOCALE_SYSTEM_DEFAULT, LOCALE_SISO3166CTRYNAME, acBuf, sizeof(acBuf)-1) > 0 then Result := String(acBuf) else Result := 'erro'; end; function INIFName(aServer: Boolean): String; begin if aServer then Result := ExtractFilePath(ParamStr(0))+'nexserv.ini' else Result := ExtractFilePath(ParamStr(0))+'nexadmin.ini'; end; procedure SetTagValue(var S: String; aTag, aValue: String); var P, I, F: Integer; begin I := Pos('<'+aTag+'>', S); F := Pos('</'+aTag+'>', S); if (I=0) or (F=0) then Exit; S := Copy(S, 1, I-1) + '<'+aTag+'>' + aValue + '</'+aTag+'>' + Copy(S, F+Length(aTag)+3, High(Integer)); end; function YMD_Date(S: String): TDateTime; begin Result := EncodeDate(StrToInt(Copy(S, 1, 4)), StrToInt(Copy(S, 5, 2)), StrToInt(Copy(S, 7, 2))); end; function ObsToinfCpl(S: String): String; var a: TStrings; i : integer; begin Result := ''; a := TStringList.Create; try a.Text := S; for I := 0 to a.Count-1 do if Trim(a[i])>'' then begin if Result>'' then Result := Result + '; '; Result := Result + Trim(a[i]); end; finally a.Free; end; end; function infCplToObs(S: String): String; var a, b: TStrings; i : integer; begin a := TStringList.Create; b := TStringList.Create; try a.LineBreak := ';'; a.text := S; for I := 0 to a.Count-1 do b.Add(Trim(a[i])); Result := b.Text; finally a.Free; b.Free; end; end; function StrToBool(S: String; const aDef: Boolean = False): Boolean; begin if Trim(S)>'' then Result := SameText(Trim(S), 'S') or (StrToIntDef(Trim(S), 0)>0) or SameText(Trim(S), 'Y') else Result := aDef; end; function TimeZoneStr: String; var I : Integer; aNeg : Boolean; begin I := TTimeZone.Local.UtcOffset.Hours; aNeg := (I<0); if aNeg then I := I*-1; Result := IntToStr(I); if Length(Result)=1 then Result := '0'+Result; Result := Result + ':00'; if aNeg then Result := '-'+Result else Result := '+'+Result; end; function SoDig(S: String): String; var I : Integer; begin Result := ''; for I := 1 to Length(S) do if S[I] in ['0'..'9'] then Result := Result + S[I]; end; function isCnpj(xCNPJ: String):Boolean; Var d1,d4,xx,nCount,fator,resto,digito1,digito2 : Integer; Check : String; begin xCNPJ := SoDig(xCNPJ); d1 := 0; d4 := 0; xx := 1; for nCount := 1 to Length( xCNPJ )-2 do begin if Pos( Copy( xCNPJ, nCount, 1 ), '/-.' ) = 0 then begin if xx < 5 then begin fator := 6 - xx; end else begin fator := 14 - xx; end; d1 := d1 + StrToInt( Copy( xCNPJ, nCount, 1 ) ) * fator; if xx < 6 then begin fator := 7 - xx; end else begin fator := 15 - xx; end; d4 := d4 + StrToInt( Copy( xCNPJ, nCount, 1 ) ) * fator; xx := xx+1; end; end; resto := (d1 mod 11); if resto < 2 then begin digito1 := 0; end else begin digito1 := 11 - resto; end; d4 := d4 + 2 * digito1; resto := (d4 mod 11); if resto < 2 then begin digito2 := 0; end else begin digito2 := 11 - resto; end; Check := IntToStr(Digito1) + IntToStr(Digito2); if Check <> copy(xCNPJ,succ(length(xCNPJ)-2),2) then begin Result := False; end else begin Result := True; end; end; function isCPF(CPF: string): boolean; var dig10, dig11: string; s, i, r, peso: integer; begin CPF := SoDig(CPF); // length - retorna o tamanho da string (CPF é um número formado por 11 dígitos) if ((CPF = '00000000000') or (CPF = '11111111111') or (CPF = '22222222222') or (CPF = '33333333333') or (CPF = '44444444444') or (CPF = '55555555555') or (CPF = '66666666666') or (CPF = '77777777777') or (CPF = '88888888888') or (CPF = '99999999999') or (length(CPF)<>11)) then begin isCPF := false; exit; end; // try - protege o código para eventuais erros de conversão de tipo na função StrToInt try { *-- Cálculo do 1o. Digito Verificador --* } s := 0; peso := 10; for i := 1 to 9 do begin // StrToInt converte o i-ésimo caractere do CPF em um número s := s + (StrToInt(CPF[i]) * peso); peso := peso - 1; end; r := 11 - (s mod 11); if ((r = 10) or (r = 11)) then dig10 := '0' else str(r:1, dig10); // converte um número no respectivo caractere numérico { *-- Cálculo do 2o. Digito Verificador --* } s := 0; peso := 11; for i := 1 to 10 do begin s := s + (StrToInt(CPF[i]) * peso); peso := peso - 1; end; r := 11 - (s mod 11); if ((r = 10) or (r = 11)) then dig11 := '0' else str(r:1, dig11); { Verifica se os digitos calculados conferem com os digitos informados. } if ((dig10 = CPF[10]) and (dig11 = CPF[11])) then isCPF := true else isCPF := false; except isCPF := false end; end; function imprimeCPF(CPF: string): string; begin CPF := SoDig(CPF); Result := ''; if Length(CPF)<>11 then Exit; Result := copy(CPF, 1, 3) + '.' + copy(CPF, 4, 3) + '.' + copy(CPF, 7, 3) + '-' + copy(CPF, 10, 2); end; function EmailValido(aEmail: String): Boolean; begin Result := (Length(Trim(aEmail))>2) and (Pos('@', aEmail)>0); end; function GetValueFromStr(aStr, aName: String): String; var sl : TStrings; begin sl := TStringList.Create; try sl.Text := aStr; Result := sl.Values[aName]; finally sl.Free; end; end; procedure SetValueFromStr(var aStr: String; aName, aValue: String); var sl : TStrings; begin sl := TStringList.Create; try sl.Text := aStr; sl.Values[aName] := aValue; aStr := sl.Text; finally sl.Free; end; end; function FormatEmail(aNome, aEmail: String): String; begin if Trim(aEmail)='' then Result := '' else if Trim(aNome)>'' then Result := aNome + ' <' + aEmail + '>' else Result := aEmail; end; function CodigoCliKey(S: String): String; var Dig: Boolean; I: Integer; begin S := Trim(S); Dig := True; for I := 1 to Length(S) do if not (S[I] in ['0'..'9']) then begin Dig := False; Break; end; if Dig then begin while Length(S)<15 do S := '0'+S; end else S := UpperCase(S); Result := S; end; function SplitParams(S: String): TStrings; var P: Integer; s2: String; begin Result := TStringList.Create; repeat P := Pos(',', S); if P>0 then begin s2 := Trim(Copy(S, 1, P-1)); Delete(S, 1, P); end else begin s2 := Trim(S); S := ''; end; if s2>'' then Result.Add(s2); until S=''; end; function RemoveAspas(S: String): String; begin S := Trim(S); if Copy(S, 1, 1)='"' then Delete(S, 1, 1); if Copy(S, Length(S), 1)='"' then Delete(S, Length(S), 1); Result := S; end; function SemAcento(S: String): String; const Acentos = 'éêèýýúùûîiíìõôòóãáàñç'; SAcentos = 'eeeyyuuuiiiiooooaaanc'; var I, P : Integer; begin S := lowercase(S); Result := ''; for I := 1 to Length(S) do begin P := Pos(S[i], Acentos); if P>0 then Result := Result + SAcentos[P] else Result := Result + S[i]; end; end; function RemoveAcento(S: String): String; const Acentos = 'éêèýýúùûîiíìõôòóãáàñçÉÊÈÝÝÚÙÛÎIÍÌÕÔÒÓÃÁÀÑÇ'; SAcentos = 'eeeyyuuuiiiiooooaaancEEEYYUUUIIIIOOOOAAANC'; var I, P : Integer; begin Result := ''; for I := 1 to Length(S) do begin P := Pos(S[i], Acentos); if P>0 then Result := Result + SAcentos[P] else Result := Result + S[i]; end; end; function FmtNFe(S: String): String; begin Result := Trim(RemoveAcento(S)); end; function SameTextSemAcento(A, B: String): Boolean; begin Result := SameText(SemAcento(A), SemAcento(B)); end; function LimitaCasasDec(C: Currency): Currency; begin Result := DuasCasas(C); { if CurrencyDecimals>0 then Result := Int(C*Power(10, SysUtils.CurrencyDecimals)) / Power(10, SysUtils.CurrencyDecimals) else Result := C;} end; function CurrencyToStr(C: Currency): String; begin Result := FloatToStrF(C, ffCurrency, 15, SysUtils.FormatSettings.CurrencyDecimals); end; function PercToStr(P: Double): String; var lastCH: char; begin Result := FloatToStrF(P, ffFixed, 15, 2); while (Length(Result)>0) and (Result[Length(Result)] in ['0', '.', ',']) do begin lastCH := Result[Length(Result)]; Delete(Result, Length(Result), 1); if lastCH in [',', '.'] then Break; end; if Result='' then Result := '0'; Result := Result + '%'; end; function PontosFidToStr(D: Double): String; begin Str(D:0:1, Result); Result := Copy(Result, 1, Pos('.', Result)+1); if (Result>'') and (Result[Length(Result)]='0') then Delete(Result, Pos('.', Result), 10); end; procedure BroadcastAtualizaDireitosConfig; var I: Integer; begin for I := 0 to screen.FormCount-1 do PostMessage(Screen.Forms[I].Handle, wm_AtualizaDireitosConfig, 0, 0); end; function IsPDFFromNexCafe(aArq: String): Boolean; {5184B62F-3BD3-4C6F-BB56-1892185A1EA6} begin aArq := ExtractFileName(aArq); if Length(aArq)=42 then Result := SameText(Copy(aArq, 38, 5), '}.pdf') and // do not localize SameText(aArq[1], '{') and SameText(aArq[10], '-') and SameText(aArq[15], '-') and SameText(aArq[20], '-') and SameText(aArq[25], '-') else Result := False; DebugMsg('IsPDFFromNexCafe: Result: '+BoolStr[result]+' - aArq: ' + aArq); // do not localize end; procedure DeleteFromArraySessionSocket(var SS: TArraySessionSocket; aIndex: Integer); var I: Integer; begin if Length(SS)=0 then Exit; for I := aIndex to High(SS)-1 do SS[I] := SS[I+1]; SetLength(SS, Length(SS)-1); end; function GuidStringClean(S: String): String; var I: Integer; begin Result := ''; for I := 1 to Length(S) do if not (S[i] in ['{', '}', '-']) then Result := Result + S[i]; end; function GuidStringFmt(S: String): String; begin Result := '{' + Copy(S, 1, 8)+ '-' + Copy(S, 9, 4)+ '-' + Copy(S, 13, 4)+ '-' + Copy(S, 17, 4)+ '-' + Copy(S, 21, 12) + '}'; end; function IsWOW64: Boolean; type TIsWow64Process = function( // Type of IsWow64Process API fn Handle: THandle; var Res: BOOL ): BOOL; stdcall; var IsWow64Result: BOOL; // result from IsWow64Process IsWow64Process: TIsWow64Process; // IsWow64Process fn reference begin // Try to load required function from kernel32 IsWow64Process := GetProcAddress( GetModuleHandle('kernel32'), 'IsWow64Process' // do not localize ); if Assigned(IsWow64Process) then begin // Function is implemented: call it if not IsWow64Process(GetCurrentProcess, IsWow64Result) then raise Exception.Create('Bad process handle'); // do not localize // Return result of function Result := IsWow64Result; end else // Function not implemented: can't be running on Wow64 Result := False; end; function GetVersionBuild(S: String): Integer; var I : integer; begin I := Length(S); while (I>0) and (S[I]<>'.') do Dec(I); if I>0 then begin Delete(S, 1, I); Result := StrToIntDef(S, 0); end else Result := 0; end; function ZeroPad(St: String; Len: Integer): String; begin Result := St; while Length(Result)<Len do Result := '0'+Result; end; function SetBit(Valor, Bit: Integer; Lig: Boolean): Integer; begin if Lig then Result := (Valor or Bit) else Result := Valor and (not Bit); end; function BitIsSet(Valor, Bit: Integer): Boolean; var R: Boolean; begin Result := ((Valor and Bit)=Bit); end; function FormataSiteStr(S: String): String; var I: Integer; begin if Copy(S, 1, 1)='"' then begin Delete(S, 1, 1); I := Pos('"', S); if I>0 then S := Copy(S, 1, I-1); end; if (copy(lowercase(S), 1, 5)='http:') or // do not localize (copy(lowercase(S), 1, 4)='ftp:') then // do not localize begin Delete(S, 1, Pos(':', S)); while (S>'') and (S[1] in ['/', ':', '\']) do Delete(S, 1, 1); while (S>'') and (S[Length(S)] in ['/', ':', '\']) do Delete(S, Length(S), 1); Result := S; end else Result := S; end; function DomainAndSubdomain(S: String): String; var p: integer; begin p := pos('/', S); if p>0 then Result := copy(S, 1, P-1) else Result := S; end; function MinutosToHoraStr(aMinutos: Extended): String; var H, M, S: Integer; aNeg: Boolean; begin aNeg := (aMinutos<0); if aNeg then aMinutos := -1 * aMinutos; if aMinutos>0.000001 then begin H := Trunc(aMinutos / 60); M := Trunc(aMinutos) Mod 60; S := Trunc(aMinutos * 60) mod 60; if (H>0) or (M>0) or (S>0) then Result := ZeroPad(IntToStr(H), 2)+':'+ ZeroPad(IntToStr(M), 2)+':'+ ZeroPad(IntToStr(S), 2); end else Result := '00:00:00'; // do not localize if aNeg then Result := '-' + Result; end; function HMSToMinutos(S: String): Double; begin if Length(S)=8 then Result := StrToIntDef(Copy(S, 1, 2), 0) * 60 + StrToIntDef(Copy(S, 4, 2), 0) + StrToIntDef(Copy(S, 7, 2), 0) / 60 else Result := 0; end; function MSToMinutos(S: String): Double; begin Result := StrToIntDef(Copy(S, 1, Pos(':', S)-1), 0) + StrToIntDef(Copy(S, Pos(':', S)+1, 2), 0) / 60; end; function HMToMinutos(S: String): Double; var H, M : Integer; St: String; begin St := Copy(S, 1, Pos(':', S)-1); H := StrToIntDef(St, 0); St := Copy(S, Pos(':', S)+1, 2); M := StrToIntDef(St, 0); Result := (H*60) + M; end; function MinutosToHMSStr(aMinutos: Extended): String; var H, M, S: Integer; aNeg: Boolean; begin Result := ''; aNeg := (aMinutos<0); if aNeg then aMinutos := -1 * aMinutos; if aMinutos>0.000001 then begin H := Trunc(aMinutos / 60); M := Trunc(aMinutos) Mod 60; S := Trunc(aMinutos * 60) mod 60; if H>0 then Result := IntToStr(H)+'h'; if M>0 then Result := Result + IntToStr(M)+'m'; if S>0 then Result := Result + IntToStr(S)+'s'; end; if aNeg then Result := '-' + Result; end; function MinutosToHMSAbrev(aMinutos: Extended): String; var H, M, S: Integer; aNeg: Boolean; begin Result := ''; aNeg := (aMinutos<0); if aNeg then aMinutos := -1 * aMinutos; if aMinutos>0.000001 then begin H := Trunc(aMinutos) div 60; M := Trunc(aMinutos) Mod 60; S := Trunc(aMinutos * 60) mod 60; if H>0 then Result := IntToStr(H)+'h'; if M>0 then Result := Result + IntToStr(M)+'m'; if H<1 then if S>0 then Result := Result + IntToStr(S)+'s'; end; if aNeg then Result := '-' + Result; end; function DateTimeToMinutos(D: TDateTime): Cardinal; begin Result := DateTimeToSegundos(D) div 60; end; constructor TThreadRename.Create(aArqNovo, aArqVelho: String); begin FreeOnTerminate := True; FArqNovo := aArqNovo; FArqVelho := aArqVelho; inherited Create(False); end; procedure TThreadRename.Execute; var Ok: Boolean; begin Ok := False; if FileExists(FArqNovo) then while (not Ok) and (not Terminated) and (not EncerrarThreads) do begin Ok := DeleteFile(PChar(FArqNovo)); if not OK then Sleep(100) else DebugMsg('TThreadRename.Execute - FArqNovo: '+FArqNovo+' - DELETED.'); // do not localize end; Ok := False; if (FArqVelho<>'') then while (not Ok) and (not Terminated) and (not EncerrarThreads) do begin Ok := RenameFile(FArqVelho, FArqNovo); if not OK then Sleep(100) else DebugMsg('TThreadRename.Execute - FArqVelho: '+FArqVelho+' RENOMEADO PARA: ' + FArqNovo); // do not localize end; end; function MenorCardinal(C1, C2: Cardinal): Cardinal; begin if C1<C2 then Result := C1 else Result := C2; end; function MaiorCardinal(C1, C2: Cardinal): Cardinal; begin if C2>C1 then Result := C2 else Result := C1; end; function GetNextStrDelimCustom(var S: String; aDelim: String): String; var P : Integer; begin P := Pos(aDelim, S); if P>0 then begin Result := Copy(S, 1, P-1); Delete(S, 1, P+Length(aDelim)-1); end else begin Result := S; S := ''; end; end; function sFldDelim(aClassID: Byte): String; begin Result := chFldDelim + Char(aClassID); end; function sListaDelim(aClassID: Byte): String; begin Result := chListaDelim + Char(aClassID); end; function GetNextListItem(var sItems, sItem: String; aClassID: Byte): Boolean; var P : Integer; aDelim: String; begin aDelim := sListaDelim(aClassID); P := Pos(aDelim, sItems); if P>0 then begin Result := True; sItem := Copy(sItems, 1, P-1); Delete(sItems, 1, P+Length(aDelim)-1); end else begin Result := False; sItems := ''; end; end; function GetNextStrDelim(var S: String; aClassID: Byte): String; begin Result := GetNextStrDelimCustom(S, sFldDelim(aClassID)); end; {function StringListToListDelim(aSL: String; aClassID: Byte): String; var sl: TStrings; I: Integer; begin Result := ''; sl := TStringList.Create; try sl.Text := aSL; for I := 0 to sl.Count - 1 do Result := Result + sl[i] + sListaDelim(aClassID); finally sl.Free; end; end; function StringListFromListDelim(aListDelim: String; aClassID: Byte): String; var aDelim: String; sl: TStrings; begin Result := ''; aDelim := sListaDelim(aClassID); sl := TStringList.Create; try while Pos(aDelim, aListDelim)>0 do sl.Add(GetNextStrDelimCustom(aListDelim, aDelim)); Result := sl.Text; finally sl.Free; end; end; } procedure StrToLista(S: String; SL: TStrings); begin SL.Clear; while S>'' do SL.Add(GetNextStrDelimCustom(S, chFldDelim)); end; function ListaToStr(S: String): String; var I : Integer; begin Result := ''; with TStringList.Create do try Text := S; for I := 0 to Count-1 do Result := Result + Strings[I] + chListaDelim; finally Free; end; end; function GetDTStr(D: TDateTime): String; begin Str(D, Result); end; function DTFromStr(S: String): TDateTime; var Code: Integer; begin Val(S, Result, Code); if Code<>0 then Result := 0; end; function FloatParaStr(Valor: Extended): String; begin Str(Valor, Result); end; function QuantToStr(Valor: Extended): String; begin Str(Valor:0:3, Result); while (Result>'') and (Result[Length(Result)]='0') do Delete(Result, Length(Result), 1); if (Result>'') and (Result[Length(Result)]='.') then Delete(Result, Length(Result), 1); end; function StrParaFloat(S: String): Extended; var Code: Integer; begin Val(S, Result, Code); if Code<>0 then Result := 0; end; function StringToBool(S: String): Boolean; begin S := UpperCase(S); Result := (S='T') or (S='TRUE') OR (S='S') or (S='SIM') or (S='1') or (S='Y') or (S='YES'); // do not localize end; function ObtemCred(I: Integer): Cardinal; begin if I>0 then Result := I else Result := 0; end; function DuasCasas(D: Extended; aCasas: Integer = -1): Extended; var I, C : Integer; S : String; begin Str(D:10:10, S); with FormatSettings do if aCasas=-1 then aCasas := CurrencyDecimals; if aCasas>0 then S := Copy(S, 1, Pos('.', S)+aCasas) else begin I := Pos('.', S); if I>0 then S := Copy(S, 1, I-1); end; Val(S, Result, I); { S := D; C := 1; DebugMsg('DuasCasas - D: '+FloatToStr(D)); for I := 1 to CurrencyDecimals do C := C * 10; D := Int(D * C); Result := D / C; DebugMsg('DuasCasas - Result: '+FloatToStr(Result)); DebugMsg('Plano B: '+FloatToStr(Trunc(S*C)/C));} end; function LimpaTraco(S: String): String; var I : Integer; begin Result := ''; for I := 1 to Length(S) do if S[I] <> '-' then Result := Result + S[I]; end; function NumStr(I, Tam: Integer): String; begin Result := ZeroPad(IntToStr(I), Tam); end; function FormataNumVersao(St: String): String; var I : Integer; begin Result := St; I := Length(Result); while (I>0) and (Result[I]<>'.') do Dec(I); if (I>0) and (Result[I]='.') then Result := Copy(Result, 1, I)+ZeroPad(Copy(Result, I+1, Length(Result)), 4); end; function CalcAcesso(Acesso, Sinal, Desc: Double): Double; begin if Sinal > Acesso then Result := 0 - Desc else Result := Acesso - Sinal - Desc; end; function VolumeSerial(DriveChar: Char): string; var OldErrorMode: Integer; Serial, NotUsed, VolFlags: DWORD; Buf: array [0..MAX_PATH] of Char; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Buf[0] := #$00; if GetVolumeInformation(PChar(DriveChar + ':\'), nil, 0, @Serial, NotUsed, VolFlags, nil, 0) then Result := IntToHex(Integer(Serial), 0) else Result := ''; finally SetErrorMode(OldErrorMode); end; end; function Senha(D: TDateTime; NS: Cardinal; NumMaq: Integer): String; var E : Extended; S : String; begin try E := NS + (Int(D)*1000) + (NumMaq * 1000) - 3; E := Ln(E); Str(E:0:30, S); S := Copy(S, Pos('.', S)+4, 8); Result := S[2] + S[8] + S[7] + S[3] + S[1] + S[4] + S[6] + S[5]; except Result := 'Kznq098s'; // do not localize end; end; { TncClasse } function Z2(I: Integer): String; begin Result := IntToStr(I); if Length(Result)=1 then Result := '0' + Result; end; function TicksToHMSSt(Ticks: Cardinal): String; var H, M, S : Integer; begin H := Ticks div (1000 * 60 * 60); Ticks := Ticks mod (1000 * 60 * 60); M := Ticks div (1000 * 60); Ticks := Ticks mod (1000 * 60); S := Ticks div 1000; Result := Z2(H) + ':' + Z2(M) + ':' + Z2(S); end; function TicksToDateTime(Ticks: Cardinal): TDateTime; var H, M, S : Integer; begin // Result := Ticks / 1000 / 60 / 60 / 24; H := Ticks div (1000 * 60 * 60); Ticks := Ticks mod (1000 * 60 * 60); M := Ticks div (1000 * 60); Ticks := Ticks mod (1000 * 60); S := Ticks div 1000; if (H>23) then H := 23; Result := EncodeTime(H, M, S, 0); end; function MinutosToDateTime(M: Double): TDateTime; begin Result := M / 24 / 60; end; function SegundosToHMSSt(Seg: Cardinal): String; begin Result := IntToStr(Seg div (60 * 60)); Seg := Seg mod (60 * 60); Result := Result + ':' + Z2(Seg div 60); Seg := Seg mod 60; Result := Result + ':' + Z2(Seg); end; function SegundosToDateTime(Seg: Cardinal): TDateTime; var H, M: Integer; begin H := Seg div (60 * 60); Seg := Seg mod (60 * 60); M := Seg div 60; Seg := Seg mod 60; Result := EncodeTime(H, M, Seg, 0); end; function MinutosToTicks(M: Double): Cardinal; begin Result := Trunc(M * 60 * 1000); end; function TicksToMinutos(Ticks: Cardinal): Double; begin Result := Ticks / 1000 / 60; end; function DateTimeToTicks(D: TDateTime): Cardinal; var H, M, S, MS : Word; Dia : Int64; I : Int64; begin I := Trunc(D * (24*60*60*1000)); { Dia := Trunc(Int(D)); I := (Dia * 24 * 60 * 60 * 1000) + (H * 60 * 60 * 1000) + (M * 60 * 1000) + (S * 1000) + MS;} if I>High(Cardinal) then I := High(Cardinal); Result := I; end; function DateTimeToSegundos(D: TDateTime): Cardinal; var H, M, S, MS : Word; begin DecodeTime(D, H, M, S, MS); Result := (H * 60 * 60) + (M * 60) + S; end; constructor TncClasse.Create; begin inherited; FProcNotificar := nil; end; destructor TncClasse.Destroy; begin try Notificar(tnDestruicao); except on E: Exception do DebugMsg('TncClasse.Destroy - TipoClasse: ' + IntToStr(TipoClasse) + ' - Chave: ' + Chave + ' - Erro: ' + E.Message); // do not localize end; inherited; end; procedure TncClasse.Notificar(TipoNot: TTipoNotificacao); begin if Assigned(FProcNotificar) then FProcNotificar(Self, TipoNot); end; { TncServidorBase } procedure TncServidorBase.ChecaErro(Erro: Integer); begin try if Erro > 0 then if Erro > ncErrUltimo then begin try Ativo := False; except end; raise EErroNexCafe.Create(ncerrConexaoPerdida); end else raise EErroNexCafe.Create(Erro); except on e: exception do begin DebugMsgEsp(Self, E.Message, False, True); raise e; end; end; end; constructor TncServidorBase.Create(AOwner: TComponent); begin inherited; FClientes := TThreadList.Create; FUltimoHandle := 0; FAtivo := False; FOnEnviaEvento := nil; end; destructor TncServidorBase.Destroy; begin FreeAndNil(FClientes); inherited; end; function TncServidorBase.Download(aFonte, aDestino: String): Integer; begin Result := 0; end; procedure TncServidorBase.EnviaEvento(Mensagem: Integer; Dados: Pointer); var I, Faltam : Integer; CopiaDados: Pointer; C : TncCliente; begin if Assigned(FOnEnviaEvento) then begin // DebugMsg('TncServidorBase.EnviaEvento 1 - Não Enviou Mensagem: ' + GetMsgIDString(Mensagem)); // do not localize FOnEnviaEvento(Mensagem, Dados); Exit; end; with FClientes.LockList do try Faltam := NumClientesLocais; if Faltam = 0 then begin // DebugMsg('TncServidorBase.EnviaEvento 2 - Não há clients. Não Enviou Mensagem: ' + GetMsgIDString(Mensagem)); // do not localize FreeDados(Mensagem, Dados); Exit; end; for I := 0 to pred(Count) do begin C := Items[I]; if (C.WndHandle>0) and (not C.Remoto) then begin // DebugMsg('TncServidorBase.EnviaEvento 3 - C.WndHandle: ' + IntToStr(C.WndHandle) + ' - Mensagem: ' + GetMsgIDString(Mensagem)); // do not localize if (Faltam>1) then CopiaDados := ClonaDados(Mensagem, Dados); EnviaMsg(C.WndHandle, Mensagem, 0, Integer(Dados)); Dados := CopiaDados; Dec(Faltam); end; end; finally FClientes.UnlockList; end; end; function TncServidorBase.EnviarEventos: Boolean; begin Result := (NumClientesLocais>0); end; procedure TncServidorBase.AddCliente(Obj: TncCliente); begin with FClientes.LockList do try Add(Obj); finally FClientes.UnlockList; end; end; function TncServidorBase.ProximoHandle: Integer; begin Inc(FUltimoHandle); Result := FUltimoHandle; end; procedure TncServidorBase.RemoveCliente(Obj: TncCliente); var I : Integer; C : TncCliente; begin with FClientes.LockList do try I := 0; if Obj.Proxy then begin while I < Count do begin C := TncCliente(Items[I]); if (C.ProxyHandle=Obj.Handle) then begin if C.Proxy then I := 0; RemoveCliente(C); end else Inc(I); end; end; Remove(Obj); AoRemoverCliente(Obj); Obj.Free; finally FClientes.UnlockList; end; end; function TncServidorBase.NumClientesLocais: Integer; var I : Integer; C : TncCliente; begin with FClientes.LockList do try Result := 0; for I := 0 to pred(Count) do begin C := TncCliente(Items[I]); if (not C.Remoto) and (C.WndHandle>0) then Inc(Result); end; finally FClientes.UnlockList; end; end; class procedure TncServidorBase.Lock; begin // DebugMsg('TncServidorBase.Lock - ThreadID: '+IntToStr(GetCurrentThreadID)); // do not localize csServ.Enter; // DebugMsg('TncServidorBase.Lock OK - ThreadID: '+IntToStr(GetCurrentThreadID)); // do not localize end; function TncServidorBase.Login(aUsername, aSenha: String; aFuncAtual: Boolean; aRemoto: Boolean; aWndHandle: HWND; aProxyHandle: Integer; aSocket: Integer; aSessionID: Integer; aIP: String; var Handle: Integer): Integer; var C : TncCliente; begin Result := 0; C := TncCliente.Create; C.UserName := aUserName; C.Handle := Handle; C.Remoto := aRemoto; C.WndHandle := aWndHandle; C.ProxyHandle := aProxyHandle; C.Socket := aSocket; C.Inicio := Now; C.SessionID := aSessionID; AddCliente(C); end; procedure TncServidorBase.Logout(Cliente: Integer); var C : TncCliente; begin C := ObtemCliente(Cliente); if C <> nil then RemoveCliente(C); end; procedure TncServidorBase.LogoutSession(aSessionID: Integer); var I : Integer; begin with FClientes.LockList do try for I := 0 to pred(Count) do if TncCliente(Items[I]).SessionID = aSessionID then begin RemoveCliente(TncCliente(Items[I])); Exit; end; finally FClientes.UnlockList; end; end; procedure TncServidorBase.LogoutSocket(Socket: Integer); var C : TncCliente; begin C := ObtemClientePorSocket(Socket); while (C<>nil) do begin RemoveCliente(C); C := ObtemClientePorSocket(Socket); end; end; function TncServidorBase.ObtemCliente(aHandle: Integer): TncCliente; var I : Integer; begin Result := nil; if FClientes=nil then Exit; with FClientes.LockList do try for I := 0 to pred(Count) do if TncCliente(Items[I]).Handle = aHandle then begin Result := Items[I]; Exit; end; finally FClientes.UnlockList; end; end; function TncServidorBase.ObtemClientePorSessionID(aSessionID: Integer): TncCliente; var I : Integer; begin with FClientes.LockList do try if aSessionID > 0 then for I := 0 to pred(Count) do if TncCliente(Items[I]).SessionID = aSessionID then begin Result := Items[I]; Exit; end; Result := nil; finally FClientes.UnlockList; end; end; function TncServidorBase.ObtemClientePorSocket(Socket: Integer): TncCliente; var I : Integer; begin with FClientes.LockList do try if Socket > 0 then for I := 0 to pred(Count) do if TncCliente(Items[I]).Socket = Socket then begin Result := Items[I]; Exit; end; Result := nil; finally FClientes.UnlockList; end; end; function TncServidorBase.ObtemPastaServ(var NomePastaServ: String): Integer; begin Result := 0; NomePastaServ := ExtractFilePath(ParamStr(0)); end; procedure TncServidorBase.ObtemSessionSocketArray(var SS: TArraySessionSocket); var I, C: Integer; begin SetLength(SS, 0); C := 0; with FClientes.LockList do try for I := 0 to pred(count) do with TncCliente(Items[i]) do if (SessionID>0) then begin Inc(C); SetLength(SS, C); SS[C-1].ssSession := SessionID; SS[C-1].ssSocket := Socket; end; finally FClientes.UnlockList; end; end; function TncServidorBase.ObtemUsernameHandlePorSessionID(aSessionID: Integer; var aUsername: String; var aHandle: Integer): Boolean; var I: Integer; begin with FClientes.LockList do try for I := 0 to pred(count) do with TncCliente(Items[i]) do if aSessionID=SessionID then begin aUsername := Username; aHandle := Handle; Result := True; Exit; end; finally FClientes.UnlockList; end; aUsername := ''; aHandle := -1; Result := False; end; procedure TncServidorBase.SetAtivo(Valor: Boolean); begin if not Valor then DesativaClientes; FAtivo := Valor; end; class procedure TncServidorBase.Unlock; begin // DebugMsg('TncServidorbase.Unlock'); // do not localize csServ.Leave; end; function TncServidorBase.Upload(aFonte, aDestino: String): Integer; begin Result := 0; end; procedure TncServidorBase.DesativaClientes; begin EnviaEvento(ncmc_ServidorDesativado, nil); with FClientes.LockList do try while Count > 0 do begin TncCliente(Items[0]).Free; Delete(0); end; finally FClientes.UnlockList; end; end; procedure TncServidorBase.AoRemoverCliente(Cliente: TncCliente); begin end; function TncServidorBase.BaixaNovaVersao(Programa, Versao, ArqDestino: String): Integer; begin Result := ncerrSemNovaVersao; end; { TncCliente } constructor TncCliente.Create; begin inherited; FHandle := 0; FRemoto := False; FUsername := ''; FWndHandle:= 0; FSocket := 0; FInicio := 0; end; function TncCliente.TipoClasse: Integer; begin Result := tcCliente; end; function TncCliente.Proxy: Boolean; begin Result := (Username = ProxyUsername); end; function TncCliente.GetChave: Variant; begin Result := FHandle; end; function MesmoComputerName(aComp1, aComp2: String): Boolean; begin Result := False; if Trim(aComp1)='' then Exit; if Trim(aComp2)='' then Exit; while Copy(aComp1, 1, 1)='\' do Delete(aComp1, 1, 1); while Copy(aComp2, 1, 1)='\' do Delete(aComp2, 1, 1); Result := SameText(aComp1, aComp2); end; constructor EErroNexCafe.Create(CE: Integer); begin inherited Create(SncClassesBase_ErroNexCafé+IntToStr(CE)+'): '+StringErro(CE)); CodigoErro := CE; end; { TncListaUsuarios } function TncListaUsuarios.AdminAtivos: Integer; var I : Integer; begin Result := 0; for I := 0 to Count-1 do if Itens[i].Admin and (not Itens[i].Inativo) then Inc(Result); end; constructor TncListaUsuarios.Create; begin inherited Create(tcUsuario); end; function TncListaUsuarios.EmailUsuario(aUsername: String): String; var U : TncUsuario; begin U := PorUsername[aUsername]; if Assigned(U) then Result := U.Email else Result := ''; end; function TncListaUsuarios.GetUsuario(I: Integer): TncUsuario; begin Result := TncUsuario(GetItem(I)); end; function TncListaUsuarios.GetUsuarioPorUsername(N: String): TncUsuario; begin Result := TncUsuario(GetItemPorChave(N)); end; { TncUsuario } constructor TncUsuario.Create; begin inherited; FNumClientes := 0; FUsername := ''; FAdmin := False; FSenha := ''; FDireitos := ''; FLimiteDesc := 0; FInativo := False; end; function TncUsuario.GetChave: Variant; begin Result := FUsername; end; function TncUsuario.LimiteDescOk(aPerc: Double): Boolean; begin Result := Admin or (aPerc<=FLimiteDesc) or (FLimiteDesc<0.00001); end; function TncUsuario.PodeDesconto(aTotal, aDesc: Currency): Boolean; begin Result := (not gConfig.IsPremium) or Admin or (((aDesc/aTotal)*100)<=FLimiteDesc); end; procedure TncUsuario.SetAdmin(Valor: Boolean); begin FAdmin := Valor; end; procedure TncUsuario.SetDireitos(Valor: String); begin FDireitos := Valor; end; procedure TncUsuario.SetNome(Valor: String); begin FNome := Valor; end; procedure TncUsuario.SetNumClientes(Valor: Integer); begin FNumClientes := Valor; end; procedure TncUsuario.SetSenha(Valor: String); begin FSenha := Valor; end; procedure TncUsuario.SetUsername(Valor: String); begin FUsername := Valor; end; function TncUsuario.TipoClasse: Integer; begin Result := tcUsuario; end; { TncConfig } constructor TncConfig.Create; begin inherited; FLastApplyFmtMoeda := ''; FslFlags := TStringList.Create; FCamposCliCC := TStringList.Create; fMargem := 0; fPrecoAuto := False; FComissaoPerc := 0; FComissaoLucro := False; FEndereco_Loja := TGuidEx.Empty; FQuickCad := True; FTranspEntPadrao := 0; FFretePadrao := 0; FDesativarFrete := False; FmodFretePadrao := 9; FDesativarTranspEnt := False; FCodBarBal := False; FCodBarBalTam := 13; FCodBarBalIdent := '2'; FCodBarBalInicioCod := 2; FCodBarBalTamCod := 5; FCodBarBalValor := True; FCodBarBalPPInicio := 7; FCodBarBalPPTam := 5; FCodBarBalPPDig := 2; FCodBarMaxQtdDig := 3; FCodBarArredondar := 4; FRecImprimir := 0; FRecMatricial := False; FRecTipoImpressora := ''; FRecPorta := '1'; // do not localize FRecSalto := 10; FRecLargura := 40; FRecCortaFolha := False; FRecRodape := ''; FRecNomeLoja := SncClassesBase_NOMEDALOJA; FRecImprimeMeioPagto := True; FRecPrefixoMeioPagto := ''; FDocParam_Email := ''; FDocParam_Tel := ''; FDocParam_Tel2 := ''; FDocParam_Cidade := ''; FDocParam_End := ''; FDocParam_CEP := ''; FDocParam_CNPJ := ''; FDocParam_IE := ''; FDocParam_Site := ''; FDocParam_Facebook := ''; FDocParam_Instagram := ''; FDocParam_Whats := ''; FDocParam_Whats2 := ''; FDocParam_InfoExtra := ''; FRecAddObsItem := True; FManterSaldoCaixa := False; FEscondeTextoBotoes := False; FCampoLocalizaCli := 0; FLimitePadraoDebito := 0; FConta := ''; FCodEquip := ''; FQtdLic := 0; FStatusConta := scSemConta; FVerPri := 0; FFreePremium := False; FPro := False; FDataLic := 0; FDVA := 0; FProxAvisoAss := 0; FPreLib := False; FAlertaAssinatura := True; FJaFoiPremium := False; FMeioPagto := 0; FEmailDestino := ''; FEmailEnviarCaixa := False; FEmailIdent := ''; FEmailConteudo := ''; FExigeDadosMinimos := False; FCidadePadrao := ''; FUFPadrao := ''; FDadosMinimos := ''; FPedirSaldoI := True; FPedirSaldoF := True; FRelCaixaAuto := True; FNaoVenderAlemEstoque := False; FAutoSortGridCaixa := False; FAutoObsAoCancelar := False; FFidAtivo := False; FFidVendaValor := 0; FFidVendaPontos := 0; FFidParcial := False; FFidMsg := False; FFidMsgTitulo := ''; FFidMsgTexto := ''; if PaisBrasil then FTrocoMax := 100 else FTrocoMax := 1000; FPais := GetCountryCode; Ftax_id_default := 0; FNomeCodigo2 := ''; FFidAutoPremiar := False; FFidAutoPremiarValor := 0; FFidAutoPremiarPontos := 0; FFidMostrarSaldoAdmin := False; FPastaDownload := ''; FTelaPosVenda_Mostrar := True; FTelaPosVenda_BtnDef := 1; FExigirVendedor := False; FTamCodigoAuto := 6; Ffmt_moeda := False; Ffmt_decimais := 2; Ffmt_simbmoeda := ''; Ffmt_sep_decimal := ''; Ffmt_sep_milhar := ''; FValOrc_Tempo := 0; FValOrc_UTempo := 0; FObsPadraoOrcamento := ''; FObsNF := False; FEmailOrc_Enviar := True; FEmailOrc_FromName := ''; FEmailOrc_FromEmail := ''; FEmailOrc_Subject := ''; FEmailOrc_Body := ''; FDocOrc_Imprimir := True; FDocOrc_NomeLoja := ''; FServerDir := ''; FBotoes := ''; FBanners := ''; FRecursos := ''; FConfirmarDebito := True; end; function TncConfig.cxMaskUnitario: String; var S: String; D: Byte; M: String; F: TFormatSettings; function zeros: string; begin Result := ''; while (Length(Result)<Self.Ffmt_decimais) do Result := Result + '0'; end; begin S := ''; if Ffmt_moeda then begin D := FFmt_decimais; M := FFmt_SimbMoeda; end else begin F := TFormatSettings.Create; D := F.CurrencyDecimals; M := F.CurrencyString; end; while Length(S)<Ffmt_decimais do S := S + '0'; while Length(S)<10 do S := S + '#'; Result := M+' ,0.'+S+';-'+M+' ,0.'+S; end; function TncConfig.DadosMinOk(T: TDataset): Boolean; var I, P, N : Integer; F : TField; S, sFld : String; function NextFld: Integer; var sNum: String; begin P := Pos(',', S); if P=0 then begin sNum := S; S := ''; end else begin sNum := Copy(S, 1, P-1); Delete(S, 1, P); end; Result := StrToIntDef(SoDig(sNum), -1); end; begin if ExigeDadosMinimos and (Trim(DadosMinimos)>'') then begin Result := False; S := Trim(DadosMinimos); while S>'' do begin N := NextFld; if N>=0 then sFld := slDadosMin.ValueFromIndex[N] else sFld := ''; if sFld>'' then begin F := T.FindField(sFld); if F<>nil then begin if (F.DataType in [ftDate, ftDateTime]) then begin if F.IsNull then Exit; end else if F.IsNull or (Trim(F.AsString)='') then Exit; end; end; end; end; Result := True; end; function TncConfig.DecodeCodBarBalanca(aCodigo: String; var aInfo: TncCodBarBalInfo): Boolean; begin aInfo.Codigo := ''; Result := False; if not CodBarBal then Exit; if CodBarBalIdent = '' then Exit; if CodBarBalTam < 1 then Exit; if Length(aCodigo) <> CodBarBalTam then Exit; if Copy(aCodigo, 1, Length(CodBarBalIdent))<>CodBarBalIdent then Exit; Result := True; aInfo.Codigo := Copy(aCodigo, CodBarBalInicioCod, CodBarBalTamCod); aInfo.PesoValor := StrToIntDef(Copy(aCodigo, CodBarBalPPInicio, CodBarBalPPTam), 0) / Power(10, CodBarBalPPDig); aInfo.BalValor := CodBarBalValor; end; destructor TncConfig.Destroy; begin FslFlags.Free; FCamposCliCC.Free; inherited; end; function TncConfig.FidAutoPremiarAtivo: Boolean; begin Result := FidAtivo and FidAutoPremiar and (FidAutoPremiarValor>0.01); end; function TncConfig.FidPremiarAutomaticamente(aPontos: Double): Boolean; begin Result := FidAutoPremiarAtivo and (aPontos>=FidAutoPremiarPontos); end; procedure TncConfig.SetVerPri(const Value: Word); begin FVerPri := Value; if not LadoServidor then Versoes.Versao := Value; end; function TncConfig.CalcPontos(aValor: Currency): Double; var Valor: Currency; Pontos : Integer; begin Result := 0; if not FFidAtivo then Exit; Valor := FFidVendaValor; Pontos := FFidVendaPontos; if (Valor=0) or (Pontos=0) then Exit; Result := aValor/Valor; if not FFidParcial then Result := Trunc(Int(Result)); Result := Result * Pontos; end; function TncConfig.CalcPreco(aMargem: Variant; aCusto: Currency): Currency; var M: Double; begin if VarIsNull(aMargem) then M := gConfig.Margem else M := aMargem; if M>0.009 then begin Result := aCusto * (1 + (M/100)); Result := LimitaCasasDec(Result); end else Result := 0; end; function TncConfig.cce(acce: Integer): Boolean; begin Result := (Copy(FEmailConteudo, acce+1, 1)='1'); end; function TncConfig.CodLojaInt: Integer; begin Result := StrToCodLoja(FConta); end; function TncConfig.ImpOutras: Boolean; begin Result := SameText(Self.RecTipoImpressora, SncaFrmConfigRec_OutraSerial); end; function TncConfig.GetCamposCliCCText: String; begin Result := FCamposCliCC.Text; end; function TncConfig.GetChave: Variant; begin Result := 0; end; function TncConfig.GetDTol: Byte; begin Result := gDTol; end; function TncConfig.GetEndereco_Loja: String; begin if TGuidEx.IsEmpty(FEndereco_Loja) then Result := '' else Result := TGuidEx.ToString(FEndereco_Loja); end; function TncConfig.GetFlags: String; begin Result := FslFlags.Text; end; function TncConfig.GetRecBobina: Boolean; begin Result := RecMatricial; end; function TncConfig.GetRecursoOn(aIndex: Integer): Boolean; begin Result := SameText(Copy(FRecursos, aIndex, 1), '1'); end; function TncConfig.GetServerDir: String; begin if LadoServidor then Result := ExtractFilePath(ParamStr(0)) else Result := FServerDir; end; function TncConfig.GetUrls: String; begin Result := gUrls.AsString; end; function TncConfig.IsFree: Boolean; begin Result := gConfig.FreePremium and (not gConfig.IsPremium); end; function TncConfig.IsPremium: Boolean; begin if gDTol>9 then gDTol := 9; Result := (gConfig.StatusConta=scPremium); end; function TncConfig.TipoClasse: Integer; begin Result := tcConfig; end; function TncConfig.TolDiasRestantes: Integer; begin Result := TolerandoPor; if Result>0 then Result := DTol - Result; end; function TncConfig.TolerandoPor: Integer; begin if (StatusConta=scPremium) and (DVA>0) and (DataLic>0) and (Date>DVA) and (not PreLib) and (DTol>0) then Result := (Trunc(Date)-Trunc(DVA)) else Result := 0; if Result>DTol then Result := 0; end; function TncConfig.TrialDiasRestantes: Integer; begin if OnTrial then Result := Trunc(DataLic-Date) else Result := 0; end; function TncConfig.TrialPremium: Boolean; begin Result := (OnTrial or TrialVencido) and not PRO; end; function TncConfig.TrialPro: Boolean; begin Result := (OnTrial or TrialVencido) and PRO; end; function TncConfig.TrialVencido: Boolean; begin Result := (FDVA=0) and (FPreLib=True) and (gConfig.StatusConta=scPremiumVenc); end; procedure TncConfig.ApplyFmtMoeda; var F: TFormatSettings; function zeros: string; begin Result := ''; while Length(Result)<Ffmt_decimais do Result := Result + '0'; end; function zerosf: string; begin Result := ''; while Length(Result)<F.CurrencyDecimals do Result := Result + '0'; end; function strparmoeda: String; begin Result := FFmt_Moeda.ToString+ FFmt_decimais.ToString+ FFmt_simbmoeda+ FFmt_sep_decimal+ FFmt_sep_milhar; end; begin if FLastApplyFmtMoeda=strparmoeda then Exit; FLastApplyFmtMoeda := strparmoeda; try if Ffmt_moeda then begin DebugMsg(Self, 'ApplyFmtMoeda 1'); dxFormatSettings.CurrencyDecimals := Ffmt_decimais; dxFormatSettings.CurrencyString := FFmt_simbmoeda; if FFmt_sep_decimal>'' then dxFormatSettings.DecimalSeparator := FFmt_sep_decimal[1] else dxFormatSettings.DecimalSeparator := #0; if FFmt_sep_milhar>'' then dxFormatSettings.ThousandSeparator := FFmt_sep_milhar[1] else dxFormatSettings.ThousandSeparator := #0; if Ffmt_decimais>0 then cxFormatController.CurrencyFormat := Ffmt_simbmoeda+' ,0.'+zeros+';-'+Ffmt_simbmoeda+' ,0.'+zeros else cxFormatController.CurrencyFormat := Ffmt_simbmoeda+' ,0.'+zeros+';-'+Ffmt_simbmoeda+' ,0.'+zeros; end else begin DebugMsg(Self, 'ApplyFmtMoeda 2'); F := TFormatSettings.Create; dxFormatSettings.CurrencyDecimals := F.CurrencyDecimals; dxFormatSettings.CurrencyString := F.CurrencyString; dxFormatSettings.DecimalSeparator := F.DecimalSeparator; dxFormatSettings.ThousandSeparator := F.ThousandSeparator; if F.CurrencyDecimals > 0 then cxFormatController.CurrencyFormat := F.CurrencyString+' ,0.'+zerosf+';-'+F.CurrencyString+' ,0.'+zerosf else cxFormatController.CurrencyFormat := F.CurrencyString+' ,0.'+zerosf+';-'+F.CurrencyString+' ,0.'+zerosf; end; DebugMsg(Self, 'ApplyFmtMoeda 3'); if not LadoServidor then begin DebugMsg(Self, 'TranslationChanged'); cxFormatController.TranslationChanged; end; DebugMsg(Self, 'ApplyFmtMoeda 4'); except on E: Exception do DebugEx(Self, 'ApplytFmtMoeda', E); end; end; procedure TncConfig.AssignConfig(C: TncConfig); begin FEndereco_Loja := C.FEndereco_Loja; FManterSaldoCaixa := C.FManterSaldoCaixa ; FEscondeTextoBotoes := C.FEscondeTextoBotoes ; FRecImprimir := C.FRecImprimir ; FRecTipoImpressora := C.FRecTipoImpressora ; FRecMatricial := C.FRecMatricial ; FRecPorta := C.FRecPorta ; FRecSalto := C.FRecSalto ; FRecLargura := C.FRecLargura ; FRecCortaFolha := C.FRecCortaFolha ; FRecRodape := C.FRecRodape ; FRecNomeLoja := C.FRecNomeLoja ; FRecImprimeMeioPagto := C.FRecImprimeMeioPagto ; FRecPrefixoMeioPagto := C.FRecPrefixoMeioPagto ; FDocParam_Email := C.FDocParam_Email ; FDocParam_Tel := C.FDocParam_Tel ; FDocParam_Tel2 := C.FDocParam_Tel2 ; FDocParam_Cidade := C.FDocParam_Cidade ; FDocParam_End := C.FDocParam_End ; FDocParam_CEP := C.FDocParam_CEP ; FDocParam_CNPJ := C.FDocParam_CNPJ ; FDocParam_IE := C.FDocParam_IE ; FDocParam_Site := C.FDocParam_Site ; FDocParam_Facebook := C.FDocParam_Facebook ; FDocParam_Instagram := C.FDocParam_Instagram ; FDocParam_Whats := C.FDocParam_Whats ; FDocParam_Whats2 := C.FDocParam_Whats2 ; FDocParam_InfoExtra := C.FDocParam_InfoExtra ; FRecAddObsItem := C.FRecAddObsItem ; FEmailIdent := C.FEmailIdent ; FEmailConteudo := C.FEmailConteudo ; FCampoLocalizaCli := C.FCampoLocalizaCli ; FLimitePadraoDebito := C.FLimitePadraoDebito ; FConta := C.FConta ; FCodEquip := C.FCodEquip ; FQtdLic := C.FQtdLic ; FStatusConta := C.FStatusConta ; FVerPri := C.FVerPri ; FFreePremium := C.FFreePremium ; FPro := C.FPro ; FDataLic := C.FDataLic ; FDVA := C.FDVA ; FProxAvisoAss := C.FProxAvisoAss ; FPreLib := C.FPreLib ; FAlertaAssinatura := C.FAlertaAssinatura ; FJaFoiPremium := C.FJaFoiPremium ; FMeioPagto := C.FMeioPagto ; FEmailEnviarCaixa := C.FEmailEnviarCaixa ; FEmailDestino := C.FEmailDestino ; FEmailConteudo := C.FEmailConteudo ; FRelCaixaAuto := C.FRelCaixaAuto ; FNaoVenderAlemEstoque := C.FNaoVenderAlemEstoque ; FAutoSortGridCaixa := C.FAutoSortGridCaixa ; FFidAtivo := C.FFidAtivo ; FFidVendaValor := C.FFidVendaValor ; FFidVendaPontos := C.FFidVendaPontos ; FFidParcial := C.FFidParcial ; FFidAutoPremiar := C.FFidAutoPremiar ; FFidAutoPremiarValor := C.FFidAutoPremiarValor ; FFidAutoPremiarPontos := C.FFidAutoPremiarPontos ; FFidMostrarSaldoAdmin := C.FFidMostrarSaldoAdmin ; FFidMsg := C.FFidMsg ; FFidMsgTitulo := C.FFidMsgTitulo ; FFidMsgTexto := C.FFidMsgTexto ; FAutoObsAoCancelar := C.FAutoObsAoCancelar ; FPastaDownload := C.FPastaDownload ; FExigeDadosMinimos := C.FExigeDadosMinimos ; FCidadePadrao := C.FCidadePadrao ; FUFPadrao := C.FUFPadrao ; FDadosMinimos := C.FDadosMinimos ; FPedirSaldoI := C.FPedirSaldoI ; FPedirSaldoF := C.FPedirSaldoF ; fAutoCad := C.fAutoCad ; fQuickCad := C.fQuickCad ; fCodProdutoDuplicados := C.fCodProdutoDuplicados ; fMargem := C.fMargem ; fPrecoAuto := C.fPrecoAuto ; FServerDir := C.FServerDir ; FBanners := C.FBanners ; FBotoes := C.FBotoes ; FRecursos := C.FRecursos ; FConfirmarDebito := C.FConfirmarDebito ; FComissaoPerc := C.FComissaoPerc ; FComissaoLucro := C.FComissaoLucro ; FCodBarBal := C.FCodBarBal ; FCodBarBalTam := C.FCodBarBalTam ; FCodBarBalIdent := C.FCodBarBalIdent ; FCodBarBalInicioCod := C.FCodBarBalInicioCod ; FCodBarBalTamCod := C.FCodBarBalTamCod ; FCodBarBalValor := C.FCodBarBalValor ; FCodBarBalPPInicio := C.FCodBarBalPPInicio ; FCodBarBalPPTam := C.FCodBarBalPPTam ; FCodBarBalPPDig := C.FCodBarBalPPDig ; FCodBarMaxQtdDig := C.FCodBarMaxQtdDig ; FCodBarArredondar := C.FCodBarArredondar ; FTelaPosVenda_Mostrar := C.FTelaPosVenda_Mostrar ; FTelaPosVenda_BtnDef := C.FTelaPosVenda_BtnDef ; FExigirVendedor := C.FExigirVendedor ; FTamCodigoAuto := C.FTamCodigoAuto; Ffmt_moeda := C.Ffmt_moeda; Ffmt_decimais := C.Ffmt_decimais; Ffmt_simbmoeda := C.Ffmt_simbmoeda; Ffmt_sep_decimal := C.Ffmt_sep_decimal; Ffmt_sep_milhar := C.Ffmt_sep_milhar; FValOrc_Tempo := C.FValOrc_Tempo ; FValOrc_UTempo := C.FValOrc_UTempo ; FEmailOrc_Enviar := C.FEmailOrc_Enviar ; FEmailOrc_FromName := C.FEmailOrc_FromName ; FEmailOrc_FromEmail := C.FEmailOrc_FromEmail ; FEmailOrc_Subject := C.FEmailOrc_Subject ; FEmailOrc_Body := C.FEmailOrc_Body ; FDocOrc_Imprimir := C.FDocOrc_Imprimir ; FDocOrc_NomeLoja := C.FDocOrc_NomeLoja ; FObsPadraoOrcamento := C.FObsPadraoOrcamento ; FTrocoMax := C.FTrocoMax ; FPais := C.Fpais; Ftax_id_default := C.Ftax_id_default; FObsNF := C.FObsNF; FTranspEntPadrao := C.FTranspEntPadrao; FFretePadrao := C.FFretePadrao; FDesativarFrete := C.FDesativarFrete; FmodFretePadrao := C.FmodFretePadrao; FDesativarTranspEnt := C.FDesativarTranspEnt; FCamposCliCC.Text := C.FCamposCliCC.Text; FslFlags.Text := C.FslFlags.Text; end; function TncConfig.OnTrial: Boolean; begin Result := (FDVA=0) and (FPreLib=True) and IsPremium; end; function TncConfig.PaisBrasil: Boolean; begin Result := SameText(PaisNorm, 'BR'); end; function TncConfig.PaisNorm: String; begin if Pais='' then Result := GetCountryCode else Result := Pais; end; function TncConfig.PodeFidelidade: Boolean; begin Result := FidAtivo; end; function FormatValorSped(aValor: Extended; aDecimais: Integer): String; begin Str(aValor:0:aDecimais,Result); end; function TncConfig.PrecisaoBalanca(aValor: Extended): Extended; var I, M : Integer; V : Extended; begin M := 1; if CodBarMaxQtdDig>0 then for I := 1 to CodBarMaxQtdDig do M := M * 10; V := aValor; aValor := Int(aValor * M); if (CodBarArredondar>0) then begin V := (V * (M*10)) - (aValor * 10); if V>=CodBarArredondar then aValor := aValor + 1; end; Result := aValor / M; end; function TncConfig.RecPrinterGeneric: Boolean; begin Result := (Pos('Generic', RecTipoImpressora)>0); end; procedure TncConfig.SetCamposCliCCText(const Value: String); begin FCamposCliCC.Text := Value; end; procedure TncConfig.SetConta(const Value: String); begin FConta := Value; end; procedure TncConfig.SetDTol(const Value: Byte); begin gDTol := Value; if gDTol>9 then gDTol := 9; end; procedure TncConfig.SetEndereco_Loja(const Value: String); begin if Value='' then FEndereco_Loja := TGuidEx.Empty else FEndereco_Loja := TGuidEx.FromString(Value); end; procedure TncConfig.SetFlags(const Value: String); begin FslFlags.Text := Value; end; procedure TncConfig.SetRecBobina(const Value: Boolean); begin RecMatricial := Value; end; procedure TncConfig.SetRecursoOn(aIndex: Integer; const Value: Boolean); begin while Length(FRecursos)<aIndex do FRecursos := FRecursos + '0'; if Value then FRecursos[aIndex] := '1' else FRecursos[aIndex] := '0'; end; procedure TncConfig.SetUrls(const Value: String); begin FUrls := Value; gUrls.SetString(Value); end; { TThreadDeleteFile } constructor TThreadDeleteFile.Create(aArq: String; aTryForMS: Cardinal); begin FArq := aArq; FTryForMS := aTryForMS; inherited Create(False); end; procedure TThreadDeleteFile.Execute; var C: Cardinal; Ok : Boolean; begin try C := GetTickCount + FTryForMS; Ok := True; repeat Sleep(Random(100)+5); Ok := SysUtils.DeleteFile(FArq); until Ok or (GetTickCount>C) or EncerrarThreads; finally Free; end; end; { TncCodBarBalInfo } procedure TncCodBarBalInfo.Clear; begin Codigo := ''; PesoValor := 0; BalValor := False; end; function TncCodBarBalInfo.IsEmpty: Boolean; begin Result := (Codigo=''); end; procedure LoadDocParams; var I : Integer; begin SetLength(DocParams, 18); // if LinguaPT then begin for I := 0 to High(DocParams_pt) do DocParams[I] := DocParams_pt[I]; { end else begin for I := 0 to High(DocParams_en) do DocParams[I] := DocParams_en[I]; end;} end; class function Estados.porID(aID: Byte): String; begin if aID in [1..27] then Result := cEstados[aID] else Result := ''; end; class function Estados.porUF(aUF: String): Byte; begin for Result := 1 to 27 do if SameText(aUF, cEstados[Result]) then Exit; Result := 0; end; initialization LoadDocParams; slIni := TThreadStringList.Create; csServ := TCriticalSection.Create; gConfig := TncConfig.Create; slDadosMin := TStringList.Create; slDadosMin.Add('Nome=Nome'); // do not localize slDadosMin.Add('Endereço=Endereco'); // do not localize slDadosMin.Add('Cidade=Cidade'); // do not localize slDadosMin.Add('Bairro=Bairro'); // do not localize slDadosMin.Add('CEP=CEP'); // do not localize slDadosMin.Add('Estado=UF'); // do not localize slDadosMin.Add('RG=RG'); // do not localize slDadosMin.Add('CPF=CPF'); // do not localize slDadosMin.Add('Data de Nascimento=DataNasc'); // do not localize slDadosMin.Add('Telefone=Telefone'); // do not localize slDadosMin.Add('Celular=Celular'); // do not localize slDadosMin.Add('Username=Username'); // do not localize slDadosMin.Add('Escola=Escola'); // do not localize slDadosMin.Add('Nome do Pai=Pai'); // do not localize slDadosMin.Add('Nome da Mãe=Mae'); // do not localize slDadosMin.Add('E-mail=Email'); // do not localize finalization gConfig.Free; csServ.Free; slDadosMin.Free; slIni.Free; end.