text
stringlengths
14
6.51M
{ File: SFNTTypes.p Contains: Font file structures. Version: Technology: Mac OS 9 / Carbon Release: Universal Interfaces 3.4.2 Copyright: © 1994-2002 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit SFNTTypes; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes; {$ALIGN MAC68K} type sfntDirectoryEntryPtr = ^sfntDirectoryEntry; sfntDirectoryEntry = record tableTag: FourCharCode; checkSum: UInt32; offset: UInt32; length: UInt32; end; { The search fields limits numOffsets to 4096. } sfntDirectoryPtr = ^sfntDirectory; sfntDirectory = record format: FourCharCode; numOffsets: UInt16; { number of tables } searchRange: UInt16; { (max2 <= numOffsets)*16 } entrySelector: UInt16; { log2(max2 <= numOffsets) } rangeShift: UInt16; { numOffsets*16-searchRange } table: array [0..0] of sfntDirectoryEntry; { table[numOffsets] } end; const sizeof_sfntDirectory = 12; { Cmap - character id to glyph id mapping } cmapFontTableTag = FourCharCode('cmap'); kFontUnicodePlatform = 0; kFontMacintoshPlatform = 1; kFontReservedPlatform = 2; kFontMicrosoftPlatform = 3; kFontCustomPlatform = 4; kFontUnicodeDefaultSemantics = 0; kFontUnicodeV1_1Semantics = 1; kFontISO10646_1993Semantics = 2; kFontRomanScript = 0; kFontJapaneseScript = 1; kFontTraditionalChineseScript = 2; kFontChineseScript = 2; kFontKoreanScript = 3; kFontArabicScript = 4; kFontHebrewScript = 5; kFontGreekScript = 6; kFontCyrillicScript = 7; kFontRussian = 7; kFontRSymbolScript = 8; kFontDevanagariScript = 9; kFontGurmukhiScript = 10; kFontGujaratiScript = 11; kFontOriyaScript = 12; kFontBengaliScript = 13; kFontTamilScript = 14; kFontTeluguScript = 15; kFontKannadaScript = 16; kFontMalayalamScript = 17; kFontSinhaleseScript = 18; kFontBurmeseScript = 19; kFontKhmerScript = 20; kFontThaiScript = 21; kFontLaotianScript = 22; kFontGeorgianScript = 23; kFontArmenianScript = 24; kFontSimpleChineseScript = 25; kFontTibetanScript = 26; kFontMongolianScript = 27; kFontGeezScript = 28; kFontEthiopicScript = 28; kFontAmharicScript = 28; kFontSlavicScript = 29; kFontEastEuropeanRomanScript = 29; kFontVietnameseScript = 30; kFontExtendedArabicScript = 31; kFontSindhiScript = 31; kFontUninterpretedScript = 32; kFontMicrosoftSymbolScript = 0; kFontMicrosoftStandardScript = 1; kFontMicrosoftUCS4Script = 10; kFontCustom8BitScript = 0; kFontCustom816BitScript = 1; kFontCustom16BitScript = 2; { Language codes are zero based everywhere but within a 'cmap' table } kFontEnglishLanguage = 0; kFontFrenchLanguage = 1; kFontGermanLanguage = 2; kFontItalianLanguage = 3; kFontDutchLanguage = 4; kFontSwedishLanguage = 5; kFontSpanishLanguage = 6; kFontDanishLanguage = 7; kFontPortugueseLanguage = 8; kFontNorwegianLanguage = 9; kFontHebrewLanguage = 10; kFontJapaneseLanguage = 11; kFontArabicLanguage = 12; kFontFinnishLanguage = 13; kFontGreekLanguage = 14; kFontIcelandicLanguage = 15; kFontMalteseLanguage = 16; kFontTurkishLanguage = 17; kFontCroatianLanguage = 18; kFontTradChineseLanguage = 19; kFontUrduLanguage = 20; kFontHindiLanguage = 21; kFontThaiLanguage = 22; kFontKoreanLanguage = 23; kFontLithuanianLanguage = 24; kFontPolishLanguage = 25; kFontHungarianLanguage = 26; kFontEstonianLanguage = 27; kFontLettishLanguage = 28; kFontLatvianLanguage = 28; kFontSaamiskLanguage = 29; kFontLappishLanguage = 29; kFontFaeroeseLanguage = 30; kFontFarsiLanguage = 31; kFontPersianLanguage = 31; kFontRussianLanguage = 32; kFontSimpChineseLanguage = 33; kFontFlemishLanguage = 34; kFontIrishLanguage = 35; kFontAlbanianLanguage = 36; kFontRomanianLanguage = 37; kFontCzechLanguage = 38; kFontSlovakLanguage = 39; kFontSlovenianLanguage = 40; kFontYiddishLanguage = 41; kFontSerbianLanguage = 42; kFontMacedonianLanguage = 43; kFontBulgarianLanguage = 44; kFontUkrainianLanguage = 45; kFontByelorussianLanguage = 46; kFontUzbekLanguage = 47; kFontKazakhLanguage = 48; kFontAzerbaijaniLanguage = 49; kFontAzerbaijanArLanguage = 50; kFontArmenianLanguage = 51; kFontGeorgianLanguage = 52; kFontMoldavianLanguage = 53; kFontKirghizLanguage = 54; kFontTajikiLanguage = 55; kFontTurkmenLanguage = 56; kFontMongolianLanguage = 57; kFontMongolianCyrLanguage = 58; kFontPashtoLanguage = 59; kFontKurdishLanguage = 60; kFontKashmiriLanguage = 61; kFontSindhiLanguage = 62; kFontTibetanLanguage = 63; kFontNepaliLanguage = 64; kFontSanskritLanguage = 65; kFontMarathiLanguage = 66; kFontBengaliLanguage = 67; kFontAssameseLanguage = 68; kFontGujaratiLanguage = 69; kFontPunjabiLanguage = 70; kFontOriyaLanguage = 71; kFontMalayalamLanguage = 72; kFontKannadaLanguage = 73; kFontTamilLanguage = 74; kFontTeluguLanguage = 75; kFontSinhaleseLanguage = 76; kFontBurmeseLanguage = 77; kFontKhmerLanguage = 78; kFontLaoLanguage = 79; kFontVietnameseLanguage = 80; kFontIndonesianLanguage = 81; kFontTagalogLanguage = 82; kFontMalayRomanLanguage = 83; kFontMalayArabicLanguage = 84; kFontAmharicLanguage = 85; kFontTigrinyaLanguage = 86; kFontGallaLanguage = 87; kFontOromoLanguage = 87; kFontSomaliLanguage = 88; kFontSwahiliLanguage = 89; kFontRuandaLanguage = 90; kFontRundiLanguage = 91; kFontChewaLanguage = 92; kFontMalagasyLanguage = 93; kFontEsperantoLanguage = 94; kFontWelshLanguage = 128; kFontBasqueLanguage = 129; kFontCatalanLanguage = 130; kFontLatinLanguage = 131; kFontQuechuaLanguage = 132; kFontGuaraniLanguage = 133; kFontAymaraLanguage = 134; kFontTatarLanguage = 135; kFontUighurLanguage = 136; kFontDzongkhaLanguage = 137; kFontJavaneseRomLanguage = 138; kFontSundaneseRomLanguage = 139; { The following are special "don't care" values to be used in interfaces } kFontNoPlatform = $FFFFFFFF; kFontNoScript = $FFFFFFFF; kFontNoLanguage = $FFFFFFFF; type sfntCMapSubHeaderPtr = ^sfntCMapSubHeader; sfntCMapSubHeader = record format: UInt16; length: UInt16; languageID: UInt16; { base-1 } end; const sizeof_sfntCMapSubHeader = 6; type sfntCMapEncodingPtr = ^sfntCMapEncoding; sfntCMapEncoding = record platformID: UInt16; { base-0 } scriptID: UInt16; { base-0 } offset: UInt32; end; const sizeof_sfntCMapEncoding = 8; type sfntCMapHeaderPtr = ^sfntCMapHeader; sfntCMapHeader = record version: UInt16; numTables: UInt16; encoding: array [0..0] of sfntCMapEncoding; end; const sizeof_sfntCMapHeader = 4; { Name table } nameFontTableTag = FourCharCode('name'); kFontCopyrightName = 0; kFontFamilyName = 1; kFontStyleName = 2; kFontUniqueName = 3; kFontFullName = 4; kFontVersionName = 5; kFontPostscriptName = 6; kFontTrademarkName = 7; kFontManufacturerName = 8; kFontDesignerName = 9; kFontDescriptionName = 10; kFontVendorURLName = 11; kFontDesignerURLName = 12; kFontLicenseDescriptionName = 13; kFontLicenseInfoURLName = 14; kFontLastReservedName = 255; { The following is a special "don't care" value to be used in interfaces } kFontNoName = $FFFFFFFF; type sfntNameRecordPtr = ^sfntNameRecord; sfntNameRecord = record platformID: UInt16; { base-0 } scriptID: UInt16; { base-0 } languageID: UInt16; { base-0 } nameID: UInt16; { base-0 } length: UInt16; offset: UInt16; end; const sizeof_sfntNameRecord = 12; type sfntNameHeaderPtr = ^sfntNameHeader; sfntNameHeader = record format: UInt16; count: UInt16; stringOffset: UInt16; rec: array [0..0] of sfntNameRecord; end; const sizeof_sfntNameHeader = 6; { Fvar table - font variations } variationFontTableTag = FourCharCode('fvar'); { These define each font variation } type sfntVariationAxisPtr = ^sfntVariationAxis; sfntVariationAxis = record axisTag: FourCharCode; minValue: Fixed; defaultValue: Fixed; maxValue: Fixed; flags: SInt16; nameID: SInt16; end; const sizeof_sfntVariationAxis = 20; { These are named locations in style-space for the user } type sfntInstancePtr = ^sfntInstance; sfntInstance = record nameID: SInt16; flags: SInt16; coord: array [0..0] of Fixed; { [axisCount] } { room to grow since the header carries a tupleSize field } end; const sizeof_sfntInstance = 4; type sfntVariationHeaderPtr = ^sfntVariationHeader; sfntVariationHeader = record version: Fixed; { 1.0 Fixed } offsetToData: UInt16; { to first axis = 16 } countSizePairs: UInt16; { axis+inst = 2 } axisCount: UInt16; axisSize: UInt16; instanceCount: UInt16; instanceSize: UInt16; { Éother <count,size> pairs } axis: array [0..0] of sfntVariationAxis; { [axisCount] } instance: array [0..0] of sfntInstance; { [instanceCount] Éother arrays of data } end; const sizeof_sfntVariationHeader = 16; { Fdsc table - font descriptor } descriptorFontTableTag = FourCharCode('fdsc'); type sfntFontDescriptorPtr = ^sfntFontDescriptor; sfntFontDescriptor = record name: FourCharCode; value: Fixed; end; sfntDescriptorHeaderPtr = ^sfntDescriptorHeader; sfntDescriptorHeader = record version: Fixed; { 1.0 in Fixed } descriptorCount: SInt32; descriptor: array [0..0] of sfntFontDescriptor; end; const sizeof_sfntDescriptorHeader = 8; { Feat Table - layout feature table } featureFontTableTag = FourCharCode('feat'); type sfntFeatureNamePtr = ^sfntFeatureName; sfntFeatureName = record featureType: UInt16; settingCount: UInt16; offsetToSettings: SInt32; featureFlags: UInt16; nameID: UInt16; end; sfntFontFeatureSettingPtr = ^sfntFontFeatureSetting; sfntFontFeatureSetting = record setting: UInt16; nameID: UInt16; end; sfntFontRunFeaturePtr = ^sfntFontRunFeature; sfntFontRunFeature = record featureType: UInt16; setting: UInt16; end; sfntFeatureHeaderPtr = ^sfntFeatureHeader; sfntFeatureHeader = record version: SInt32; { 1.0 } featureNameCount: UInt16; featureSetCount: UInt16; reserved: SInt32; { set to 0 } names: array [0..0] of sfntFeatureName; settings: array [0..0] of sfntFontFeatureSetting; runs: array [0..0] of sfntFontRunFeature; end; { OS/2 Table } const os2FontTableTag = FourCharCode('OS/2'); { Special invalid glyph ID value, useful as a sentinel value, for example } nonGlyphID = 65535; { Data type used to access names from font name table } type FontNameCode = UInt32; FontNameCodePtr = ^FontNameCode; { when a VAR xx: FontNameCode parameter can be nil, it is changed to xx: FontNameCodePtr } { Data types for encoding components as used in interfaces } FontPlatformCode = UInt32; FontPlatformCodePtr = ^FontPlatformCode; { when a VAR xx: FontPlatformCode parameter can be nil, it is changed to xx: FontPlatformCodePtr } FontScriptCode = UInt32; FontScriptCodePtr = ^FontScriptCode; { when a VAR xx: FontScriptCode parameter can be nil, it is changed to xx: FontScriptCodePtr } FontLanguageCode = UInt32; FontLanguageCodePtr = ^FontLanguageCode; { when a VAR xx: FontLanguageCode parameter can be nil, it is changed to xx: FontLanguageCodePtr } { ** FontVariation is used to specify a coordinate along a variation axis. The name ** identifies the axes to be applied, and value is the setting to be used. } FontVariationPtr = ^FontVariation; FontVariation = record name: FourCharCode; value: Fixed; end; {$ALIGN MAC68K} end.
{ *************************************************************************** Copyright (c) 2015-2022 Kike Pérez Unit : Quick.Data.Redis Description : Redis client Author : Kike Pérez Version : 1.0 Created : 22/02/2020 Modified : 07/03/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** 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.Data.Redis; {$i QuickLib.inc} interface uses {$IFDEF DEBUG_REDIS} Quick.Debug.Utils, {$ENDIF} System.SysUtils, System.DateUtils, IdTCPClient, IdGlobal, Quick.Commons; type IRedisResponse = interface ['{21EF7ABF-E678-4F18-AE56-8A7C6B817AE3}'] function GetIsDone: Boolean; function GetResponse: string; procedure SetIsDone(const Value: Boolean); procedure SetResponse(const Value: string); property IsDone : Boolean read GetIsDone write SetIsDone; property Response : string read GetResponse write SetResponse; end; TRedisResponse = class(TInterfacedObject,IRedisResponse) private fIsDone : Boolean; fResponse : string; function GetIsDone: Boolean; function GetResponse: string; procedure SetIsDone(const Value: Boolean); procedure SetResponse(const Value: string); public constructor Create; property IsDone : Boolean read GetIsDone write SetIsDone; property Response : string read GetResponse write SetResponse; end; TRedisSortedItem = record Value : string; Score : Int64; end; IRedisCommand = interface ['{13A978D1-C689-403F-8623-3489E4DEE060}'] function AddArgument(const aValue : string) : IRedisCommand; overload; function AddArgument(const aValue : Int64) : IRedisCommand; overload; function AddArgument(const aValue : Extended) : IRedisCommand; overload; function ToCommand : string; end; TRedisCommand = class(TInterfacedObject,IRedisCommand) private fCommand : string; fArguments : array of string; public constructor Create(const aCommand : string); function AddArgument(const aValue : string) : IRedisCommand; overload; function AddArgument(const aValue : Int64) : IRedisCommand; overload; function AddArgument(const aValue : Extended) : IRedisCommand; overload; function ToCommand : string; end; TRedisClient = class private fTCPClient : TIdTCPClient; fHost : string; fPort : Integer; fDataBaseNumber : Integer; fMaxSize : Int64; fPassword : string; fConnectionTimeout : Integer; fReadTimeout : Integer; fConnected : Boolean; fRaiseErrorIfCommandFails : Boolean; procedure SetConnectionTimeout(const Value: Integer); procedure SetReadTimeout(const Value: Integer); function Command(const aCommand : string; const aArguments : string) : IRedisResponse; overload; function Command(const aCommand, aArgumentsFormat : string; aValues : array of const) : IRedisResponse; overload; function Command(const aCommand : string) : IRedisResponse; overload; function EscapeString(const json: string) : string; //function BulkString(const aValue : string) : string; public constructor Create; destructor Destroy; override; property Host : string read fHost write fHost; property Port : Integer read fPort write fPort; property DataBaseNumber : Integer read fDataBaseNumber write fDataBaseNumber; property MaxSize : Int64 read fMaxSize write fMaxSize; property Password : string read fPassword write fPassword; property ConnectionTimeout : Integer read fConnectionTimeout write SetConnectionTimeout; property ReadTimeout : Integer read fReadTimeout write SetReadTimeout; property RaiseErrorIfCommandFails : Boolean read fRaiseErrorIfCommandFails write fRaiseErrorIfCommandFails; property Connected : Boolean read fConnected; function RedisSELECT(dbIndex : Integer) : Boolean; function RedisSET(const aKey, aValue : string; aTTLMs : Integer = -1) : Boolean; function RedisGET(const aKey : string; out oValue : string) : Boolean; function RedisDEL(const aKey : string) : Boolean; function RedisRPUSH(const aKey, aValue : string) : Boolean; function RedisLPUSH(const aKey, aValue : string) : Boolean; function RedisRPOP(const aKey : string; out oValue : string) : Boolean; function RedisBRPOP(const aKey: string; out oValue: string; aWaitTimeoutSecs : Integer): Boolean; function RedisLPOP(const aKey : string; out oValue : string) : Boolean; function RedisBLPOP(const aKey: string; out oValue: string; aWaitTimeoutSecs : Integer): Boolean; function RedisBRPOPLPUSH(const aKey, aKeyToMove: string; out oValue: string; aWaitTimeoutSecs : Integer): Boolean; function RedisLTRIM(const aKey : string; aFirstElement, aMaxSize : Int64) : Boolean; function RedisEXPIRE(const aKey : string; aTTLMs : Integer) : Boolean; overload; function RedisEXPIRE(const aKey : string; aExpireDate : TDateTime) : Boolean; overload; function RedisLINDEX(const aKey: string; aIndex: Integer; out oValue : string): Boolean; function RedisLREM(const aKey, aValue: string; aNumOccurrences: Integer): Boolean; function RedisZADD(const aKey, aValue : string; aScore : Int64) : Boolean; function RedisZREM(const aKey, aValue : string) : Boolean; function RedisZRANGE(const aKey : string; aStartPosition, aEndPosition : Int64) : TArray<string>; function RedisZRANGEBYSCORE(const aKey : string; aMinScore, aMaxScore : Int64) : TArray<TRedisSortedItem>; function RedisLLEN(const aKey : string): Integer; function RedisTTL(const aKey, aValue : string): Integer; function RedisAUTH(const aPassword : string) : Boolean; function RedisPING : Boolean; function RedisQUIT : Boolean; procedure Connect; procedure Disconnect; end; ERedisConnectionError = class(Exception); ERedisAuthError = class(Exception); ERedisCommandError = class(Exception); implementation const DEF_REDIS_PORT = 6379; DEF_CONNECTIONTIMEOUT = 30000; DEF_READTIMETOUT = 10000; { TRedisResponse } constructor TRedisResponse.Create; begin fIsDone := False; fResponse := ''; end; function TRedisResponse.GetIsDone: Boolean; begin Result := fIsDone; end; function TRedisResponse.GetResponse: string; begin Result := fResponse; end; procedure TRedisResponse.SetIsDone(const Value: Boolean); begin fIsDone := Value; end; procedure TRedisResponse.SetResponse(const Value: string); begin fResponse := Value; end; { TRedisClient } constructor TRedisClient.Create; begin inherited; fConnected := False; fHost := 'localhost'; fPort := DEF_REDIS_PORT; fDataBaseNumber := 0; fMaxSize := 0; fPassword := ''; fConnectionTimeout := DEF_CONNECTIONTIMEOUT; fReadTimeout := DEF_READTIMETOUT; fRaiseErrorIfCommandFails := False; fTCPClient := TIdTCPClient.Create; end; destructor TRedisClient.Destroy; begin try try Disconnect; finally fTCPClient.Free; end; except //avoid closing errors end; inherited; end; procedure TRedisClient.Disconnect; begin if fTCPClient.Connected then begin RedisQUIT; fTCPClient.IOHandler.InputBuffer.Clear; fTCPClient.IOHandler.WriteBufferFlush; if fTCPClient.Connected then fTCPClient.Disconnect(False); end; fConnected := False; end; procedure TRedisClient.Connect; begin try //connect password and database if not fTCPClient.Connected then begin fTCPClient.Host := fHost; fTCPClient.Port := fPort; fTCPClient.ConnectTimeout := fConnectionTimeout; fTCPClient.ReadTimeout := fConnectionTimeout; fTCPClient.Connect; if not fTCPClient.Connected then raise ERedisConnectionError.Create('Can''t connect to Redis Server!'); end; fTCPClient.Socket.Binding.SetKeepAliveValues(True,5000,1000); if fPassword <> '' then begin if not RedisAUTH(fPassword) then raise ERedisAuthError.Create('Redis authentication error!'); end; if fDataBaseNumber > 0 then begin if not RedisSELECT(fDataBaseNumber) then raise ERedisConnectionError.CreateFmt('Can''t select Redis Database "%d"',[fDataBaseNumber]); end; fTCPClient.IOHandler.MaxLineLength := MaxInt; fConnected := True; except on E : Exception do raise ERedisConnectionError.CreateFmt('Can''t connect to Redis service %s:%d (%s)',[Self.Host,Self.Port,e.Message]); end; end; function TRedisClient.EscapeString(const json: string): string; begin Result := StringReplace(json,'\','\\',[rfReplaceAll]); Result := StringReplace(Result,'"','\"',[rfReplaceAll]); Result := StringReplace(Result,#13,'\r',[rfReplaceAll]); Result := StringReplace(Result,#10,'\n',[rfReplaceAll]); //Result := StringReplace(Result,'/','\/"',[rfReplaceAll]); end; //function TRedisClient.BulkString(const aValue : string) : string; //begin // Result := Format('$%d%s%s%s',[aValue.Length,CRLF,aValue,CRLF]); //end; procedure TRedisClient.SetConnectionTimeout(const Value: Integer); begin if fConnectionTimeout <> Value then begin fConnectionTimeout := Value; if Assigned(fTCPClient) then fTCPClient.ConnectTimeout := fConnectionTimeout; end; end; procedure TRedisClient.SetReadTimeout(const Value: Integer); begin if fReadTimeout <> Value then begin fReadTimeout := Value; if Assigned(fTCPClient) then fTCPClient.ConnectTimeout := fReadTimeout; end; end; function TRedisClient.Command(const aCommand, aArgumentsFormat : string; aValues : array of const) : IRedisResponse; begin Result := Command(aCommand,Format(aArgumentsFormat,aValues)); end; function TRedisclient.Command(const aCommand : string; const aArguments : string) : IRedisResponse; begin Result := Command(aCommand + ' ' + aArguments + CRLF); end; function TRedisClient.Command(const aCommand : string) : IRedisResponse; function TrimResponse(const aResponse : string) : string; begin Result := Copy(aResponse,Low(aResponse) + 1, aResponse.Length); end; var res : string; begin Result := TRedisResponse.Create; try if not fTCPClient.Connected then Connect; //Writeln('*'+ (aArguments.CountChar('$') + 1).ToString + CRLF + BulkString(aCommand) + aArguments); fTCPClient.IOHandler.Write(aCommand); if fTCPClient.IOHandler.CheckForDataOnSource(fReadTimeout) then begin res := fTCPClient.IOHandler.ReadLn; {$IFDEF DEBUG_REDIS} TDebugger.Trace(Self,Format('Command "%s"',[res])); {$ENDIF} if not res.IsEmpty then case res[Low(res)] of '+' : begin if res.Contains('+OK') then begin Result.IsDone := True; end else Result.Response := TrimResponse(res); end; '-' : Result.Response := TrimResponse(res); ':' : begin Result.Response := TrimResponse(res); Result.IsDone := Result.Response.ToInteger > -1; end; '$' : begin Result.Response := TrimResponse(res); if IsInteger(Result.Response) then begin if Result.Response.ToInteger > -1 then Result.IsDone := True; end else Result.IsDone := True; end; '*' : begin Result.Response := TrimResponse(res); Result.IsDone := True; end; else Result.Response := TrimResponse(res); end; end; if (fRaiseErrorIfCommandFails) and (not Result.IsDone) then raise ERedisCommandError.CreateFmt('command fail (%s)',[Result.Response]); except on E : Exception do raise ERedisCommandError.CreateFmt('Redis error: %s [%s...]',[e.message,aCommand.Substring(0,20)]); end; end; function TRedisClient.RedisRPUSH(const aKey, aValue : string) : Boolean; begin Result := Command('RPUSH','%s "%s"',[aKey,EscapeString(aValue)]).IsDone; end; function TRedisClient.RedisSELECT(dbIndex: Integer): Boolean; begin Result := Command('SELECT',dbIndex.ToString).IsDone; end; function TRedisClient.RedisSET(const aKey, aValue: string; aTTLMs: Integer = -1): Boolean; var rediscmd : IRedisCommand; begin rediscmd := TRedisCommand.Create('SET') .AddArgument(aKey) .AddArgument(aValue) .AddArgument('PX') .AddArgument(aTTLMs); Result := Command(rediscmd.ToCommand).IsDone; end; function TRedisClient.RedisRPOP(const aKey: string; out oValue: string): Boolean; var rediscmd : IRedisCommand; begin rediscmd := TRedisCommand.Create('RPOP') .AddArgument(aKey); if Command(rediscmd.ToCommand).IsDone then begin oValue := fTCPClient.IOHandler.ReadLn; Result := True; end else Result := False; end; function TRedisClient.RedisBRPOP(const aKey: string; out oValue: string; aWaitTimeoutSecs : Integer): Boolean; var rediscmd : IRedisCommand; response : IRedisResponse; begin Result := False; rediscmd := TRedisCommand.Create('BRPOP') .AddArgument(aKey) .AddArgument(aWaitTimeoutSecs); response := Command(rediscmd.ToCommand); if response.IsDone then begin //if response.Response = '-1' then Exit; fTCPClient.IOHandler.ReadLn; //$int fTCPClient.IOHandler.ReadLn; //key fTCPClient.IOHandler.ReadLn; //$int oValue := fTCPClient.IOHandler.ReadLn; //value if not oValue.IsEmpty then Result := True; end else begin if not response.Response.IsEmpty then ERedisCommandError.CreateFmt('BRPOP Error: %s',[response.Response]); end; end; function TRedisClient.RedisBRPOPLPUSH(const aKey, aKeyToMove: string; out oValue: string; aWaitTimeoutSecs: Integer): Boolean; var rediscmd : IRedisCommand; response : IRedisResponse; begin Result := False; rediscmd := TRedisCommand.Create('BRPOPLPUSH') .AddArgument(aKey) .AddArgument(aKeyToMove) .AddArgument(aWaitTimeoutSecs); response := Command(rediscmd.ToCommand); if response.IsDone then begin oValue := fTCPClient.IOHandler.ReadLn; //value if not oValue.IsEmpty then Result := True; end else raise ERedisCommandError.CreateFmt('BRPOPLPUSH Error: %s',[response.Response]); end; function TRedisClient.RedisDEL(const aKey: string): Boolean; var rediscmd : IRedisCommand; begin rediscmd := TRedisCommand.Create('DEL') .AddArgument(aKey); Result := Command(rediscmd.ToCommand).IsDone; end; function TRedisClient.RedisLLEN(const aKey : string): Integer; var rediscmd : IRedisCommand; response : IRedisResponse; begin Result := 0; rediscmd := TRedisCommand.Create('LLEN') .AddArgument(aKey); response := Command(rediscmd.ToCommand); if response.IsDone then begin Result := response.Response.ToInteger; end; end; function TRedisClient.RedisTTL(const aKey, aValue : string): Integer; var rediscmd : IRedisCommand; response : IRedisResponse; begin Result := 0; rediscmd := TRedisCommand.Create('TTL') .AddArgument(aKey) .AddArgument(aValue); response := Command(rediscmd.ToCommand); if response.IsDone then begin Result := response.Response.ToInteger; end; end; function TRedisClient.RedisZADD(const aKey, aValue: string; aScore: Int64): Boolean; var rediscmd : IRedisCommand; response : IRedisResponse; begin rediscmd := TRedisCommand.Create('ZADD') .AddArgument(aKey) .AddArgument(aScore) .AddArgument(aValue); response := Command(rediscmd.ToCommand); if response.IsDone then begin Result := response.Response.ToInteger = 1; end else raise ERedisCommandError.CreateFmt('ZADD %s',[response.Response]); end; function TRedisClient.RedisZRANGE(const aKey: string; aStartPosition, aEndPosition: Int64): TArray<string>; var rediscmd : IRedisCommand; response : IRedisResponse; value : string; i : Integer; begin Result := []; rediscmd := TRedisCommand.Create('ZRANGE') .AddArgument(aKey) .AddArgument(aStartPosition) .AddArgument(aEndPosition); response := Command(rediscmd.ToCommand); if response.IsDone then begin for i := 1 to (response.Response.ToInteger) do begin fTCPClient.IOHandler.ReadLn; //$int value := fTCPClient.IOHandler.ReadLn; //value Result := Result + [value]; end; end else raise ERedisCommandError.CreateFmt('ZRANGE Error: %s',[response.Response]); end; function TRedisClient.RedisZRANGEBYSCORE(const aKey: string; aMinScore, aMaxScore: Int64): TArray<TRedisSortedItem>; var rediscmd : IRedisCommand; response : IRedisResponse; item : TRedisSortedItem; i : Integer; value : string; score : string; begin Result := []; rediscmd := TRedisCommand.Create('ZRANGEBYSCORE') .AddArgument(aKey) .AddArgument(aMinScore) .AddArgument(aMaxScore) .AddArgument('WITHSCORES'); response := Command(rediscmd.ToCommand); if response.IsDone then begin for i := 1 to (response.Response.ToInteger Div 2) do begin fTCPClient.IOHandler.ReadLn; //$int value := fTCPClient.IOHandler.ReadLn; //value fTCPClient.IOHandler.ReadLn; //$int score := fTCPClient.IOHandler.ReadLn; //score item.Value := value; item.Score := score.ToInt64; Result := Result + [item]; end; end else raise ERedisCommandError.CreateFmt('ZRANGE Error: %s',[response.Response]); end; function TRedisClient.RedisZREM(const aKey, aValue: string): Boolean; var rediscmd : IRedisCommand; response : IRedisResponse; begin Result := False; rediscmd := TRedisCommand.Create('ZREM') .AddArgument(aKey) .AddArgument(aValue); response := Command(rediscmd.ToCommand); if response.IsDone then begin Result := response.Response.ToInteger = 1; end; end; function TRedisClient.RedisLPOP(const aKey: string; out oValue: string): Boolean; var rediscmd : IRedisCommand; begin Result := False; rediscmd := TRedisCommand.Create('LPOP') .AddArgument(aKey); if Command(rediscmd.ToCommand).IsDone then begin oValue := fTCPClient.IOHandler.ReadLn; Result := True; end; end; function TRedisClient.RedisBLPOP(const aKey: string; out oValue: string; aWaitTimeoutSecs : Integer): Boolean; var rediscmd : IRedisCommand; response : IRedisResponse; begin rediscmd := TRedisCommand.Create('BLPOP') .AddArgument(aKey) .AddArgument(aWaitTimeoutSecs); response := Command(rediscmd.ToCommand); if response.IsDone then begin fTCPClient.IOHandler.ReadLn; //$int fTCPClient.IOHandler.ReadLn; //key fTCPClient.IOHandler.ReadLn; //$int oValue := fTCPClient.IOHandler.ReadLn; //value Result := True; end else raise ERedisCommandError.CreateFmt('BLPOP Error: %s',[response.Response]); end; function TRedisClient.RedisLPUSH(const aKey, aValue : string) : Boolean; var rediscmd : IRedisCommand; begin rediscmd := TRedisCommand.Create('LPUSH') .AddArgument(aKey) .AddArgument(aValue); Result := Command(rediscmd.ToCommand).IsDone; end; function TRedisClient.RedisLREM(const aKey, aValue: string; aNumOccurrences: Integer): Boolean; var rediscmd : IRedisCommand; begin rediscmd := TRedisCommand.Create('LREM') .AddArgument(aKey) .AddArgument(aNumOccurrences * -1) .AddArgument(aValue); Result := Command(rediscmd.ToCommand).IsDone; end; function TRedisClient.RedisLTRIM(const aKey : string; aFirstElement, aMaxSize : Int64) : Boolean; var rediscmd : IRedisCommand; begin rediscmd := TRedisCommand.Create('LTRIM') .AddArgument(aKey) .AddArgument(aFirstElement) .AddArgument(aMaxSize); Result := Command(rediscmd.ToCommand).IsDone; end; function TRedisClient.RedisAUTH(const aPassword : string) : Boolean; begin Result := Command('AUTH',fPassword).IsDone; end; function TRedisClient.RedisEXPIRE(const aKey: string; aExpireDate: TDateTime): Boolean; begin Result := RedisEXPIRE(aKey,MilliSecondsBetween(Now(),aExpireDate)); end; function TRedisClient.RedisEXPIRE(const aKey: string; aTTLMs: Integer): Boolean; begin Result := Command('PEXPIRE','%s %d',[aKey,aTTLMs]).IsDone; end; function TRedisClient.RedisLINDEX(const aKey: string; aIndex: Integer; out oValue : string): Boolean; var response : IRedisResponse; begin Result := False; response := Command('LINDEX','%s %d',[aKey,aIndex]); if response.IsDone then begin oValue := response.response; Result := True; end; end; function TRedisClient.RedisGET(const aKey: string; out oValue: string): Boolean; var rediscmd : IRedisCommand; begin Result := False; rediscmd := TRedisCommand.Create('GET') .AddArgument(aKey); if Command(rediscmd.ToCommand).IsDone then begin oValue := fTCPClient.IOHandler.ReadLn; Result := True; end; end; function TRedisClient.RedisPING : Boolean; begin Result := False; if Command('PING'+ CRLF).IsDone then begin Result := fTCPClient.IOHandler.ReadLn = 'PONG'; end; end; function TRedisClient.RedisQUIT : Boolean; begin try Result := Command('QUIT' + CRLF).IsDone; except Result := False; end; end; { TRedisCommand } constructor TRedisCommand.Create(const aCommand: string); begin fCommand := aCommand; fArguments := fArguments + [fCommand]; end; function TRedisCommand.AddArgument(const aValue: string) : IRedisCommand; begin Result := Self; fArguments := fArguments + [aValue]; end; function TRedisCommand.AddArgument(const aValue: Extended): IRedisCommand; begin Result := Self; fArguments := fArguments + [aValue.ToString]; end; function TRedisCommand.AddArgument(const aValue: Int64): IRedisCommand; begin Result := Self; fArguments := fArguments + [aValue.ToString]; end; function TRedisCommand.ToCommand: string; var arg : string; begin Result := '*' + (High(fArguments) + 1).ToString + CRLF; for arg in fArguments do begin Result := Result + '$' + arg.Length.ToString + CRLF + arg + CRLF; end; end; end.
unit Well1024; { Delphi Implementation of WELL 1024a Random Number Generator see: http://de.wikipedia.org/wiki/Well_Equidistributed_Long-period_Linear http://en.wikipedia.org/wiki/Well_equidistributed_long-period_linear } interface uses Classes; (* orginal Code see: http://www.iro.umontreal.ca/~panneton/well/WELL1024a.c /* ***************************************************************************** */ /* Copyright: Francois Panneton and Pierre L'Ecuyer, University of Montreal */ /* Makoto Matsumoto, Hiroshima University */ /* Notice: This code can be used freely for personal, academic, */ /* or non-commercial purposes. For commercial purposes, */ /* please contact P. L'Ecuyer at: lecuyer@iro.UMontreal.ca */ /* ***************************************************************************** */ *) type TWellRng1024 = class(TPersistent) private state_i: Cardinal; STATE : array[0..32-1] of Cardinal; function GetState(idx:BYTE):Cardinal; procedure SetState(idx:Byte; Value:Cardinal); public constructor Create; procedure Assign(Source: TPersistent);override; function Random:Cardinal; function RandomFloat:Extended; procedure Randomize; end; implementation const W= 32; R= 32; M1= 3; M2=24; M3= 10; function MAT0POS(t:Byte;v:Cardinal):Cardinal; begin Result := v xor (v shr t); end; function MAT0NEG(t:Byte;v:Cardinal):Cardinal; begin Result := v xor (v shl t); end; { TWellRng1024 } constructor TWellRng1024.Create; begin inherited; STATE[0] := 1; end; procedure TWellRng1024.Assign(Source: TPersistent); begin if Source is TWellRng1024 then begin state_i := TWellRng1024(Source).state_i; Move(TWellRng1024(Source).STATE[0], STATE[0], sizeof(STATE)); end else inherited; end; function TWellRng1024.GetState(idx: BYTE): Cardinal; begin Result := STATE[(state_i+idx) and $1F]; end; procedure TWellRng1024.SetState(idx: Byte; Value: Cardinal); begin STATE[(state_i+idx) and $1F] := Value; end; function TWellRng1024.Random: Cardinal; var z0, z1, z2 : Cardinal; begin z0 := GetState(31); z1 := GetState(0) xor MAT0POS(8, GetState(M1)); z2 := MAT0NEG(19, GetState(M2)) xor MAT0NEG(14, GetState(M3)); SetState(0, z1 xor z2); SetState(31, MAT0NEG (11,z0) xor MAT0NEG(7,z1) xor MAT0NEG(13,z2)) ; state_i := (state_i + 31) and $1f; Result := STATE[state_i]; end; procedure TWellRng1024.Randomize; var i : Integer; begin for i := 0 to 31 do STATE[i] := System.Random(MaxInt); end; function TWellRng1024.RandomFloat: Extended; begin Result := Random * 2.32830643653869628906e-10; end; end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-30 描述: 销售员销售明细 *******************************************************************************} unit UFormReportSalerView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, USkinFormBase, UGridPainter, ExtCtrls, UImageButton, Grids, UGridExPainter, StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit; type TfFormReportSalerView = class(TSkinFormBase) GridList: TDrawGridEx; Panel1: TPanel; BtnOK: TImageButton; Panel2: TPanel; Label1: TLabel; EditDate: TcxTextEdit; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Panel1Resize(Sender: TObject); procedure BtnOKClick(Sender: TObject); private { Private declarations } FPainter: TGridPainter; //绘制对象 procedure ShowSaleDtl(const nSaler: string; nS,nE: TDate); //销售明细 public { Public declarations } class function FormSkinID: string; override; end; function ShowSalerSale(const nSaler: string; nS,nE: TDate): Boolean; //销售明细 implementation {$R *.dfm} uses ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule; function ShowSalerSale(const nSaler: string; nS,nE: TDate): Boolean; begin with TfFormReportSalerView.Create(Application) do begin ShowSaleDtl(nSaler, nS, nE); Result := ShowModal = mrOk; Free; end; end; class function TfFormReportSalerView.FormSkinID: string; begin Result := 'FormDialog'; end; procedure TfFormReportSalerView.FormCreate(Sender: TObject); var nIdx: Integer; begin for nIdx:=ComponentCount-1 downto 0 do if Components[nIdx] is TImageButton then LoadFixImageButton(TImageButton(Components[nIdx])); //xxxxx FPainter := TGridPainter.Create(GridList); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('款式名称', 50); AddHeader('颜色', 50); AddHeader('尺码', 50); AddHeader('件数', 50); AddHeader('会员名称', 50); AddHeader('营销员', 50); AddHeader('营销时间', 50); end; LoadFormConfig(Self); LoadDrawGridConfig(Name, GridList); end; procedure TfFormReportSalerView.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveFormConfig(Self); SaveDrawGridConfig(Name, GridList); FPainter.Free; end; procedure TfFormReportSalerView.BtnOKClick(Sender: TObject); begin Close; end; //Desc: 调整按钮位置 procedure TfFormReportSalerView.Panel1Resize(Sender: TObject); begin BtnOk.Left := Trunc((Panel1.Width - BtnOK.Width) / 2); end; procedure TfFormReportSalerView.ShowSaleDtl(const nSaler: string; nS, nE: TDate); var nStr,nHint: string; nDS: TDataSet; nIdx,nInt,nNum: Integer; nData: TGridDataArray; begin nStr := 'Select dt.*,StyleName,ColorName,SizeName,M_Name, ' + 'S_Man,S_Date From $DT dt ' + ' Left Join $PT pt On pt.ProductID=dt.D_Product ' + ' Left Join $ST st On st.StyleID=pt.StyleID ' + ' Left Join $CR cr On cr.ColorID=pt.ColorID ' + ' Left Join $SZ sz On sz.SizeID=pt.SizeID ' + ' Left Join $SL sl On sl.S_ID=dt.D_SaleID ' + ' Left Join $MM mm On mm.M_ID=dt.D_Member ' + 'Where S_TerminalID=''$ID'' And S_Man=''$Man'' And ' + ' (S_Date>=''$KS'' And S_Date<''$JS'') ' + 'Order By S_Date DESC'; nStr := MacroValue(nStr, [MI('$DT', sTable_SaleDtl), MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$CR', sTable_DL_Color), MI('$SZ', sTable_DL_Size), MI('$SL', sTable_Sale), MI('$MM', sTable_Member), MI('$ID', gSysParam.FTerminalID), MI('$Man', nSaler), MI('$KS', Date2Str(nS)), MI('$JS', Date2Str(nE + 1))]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin nNum := 0; nInt := 1; First; while not Eof do begin SetLength(nData, 8); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FText := ''; nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FieldByName('StyleName').AsString; nData[2].FText := FieldByName('ColorName').AsString; nData[3].FText := FieldByName('SizeName').AsString; nData[4].FText := FieldByName('D_Number').AsString; nNum := nNum + FieldByName('D_Number').AsInteger; nData[5].FText := FieldByName('M_Name').AsString; nData[6].FText := FieldByName('S_Man').AsString; nData[7].FText := DateTime2Str(FieldByName('S_Date').AsDateTime); FPainter.AddData(nData); Next; end; end; SetLength(nData, 8); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FText := ''; nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := Format('总计: %d笔', [nInt - 1]); nData[4].FText := Format('%d件', [nNum]); FPainter.AddData(nData); EditDate.Text := Format('%s至%s 共销售商品 %d 件', [Date2Str(nS), Date2Str(nE), nNum]); //xxxxx finally FDM.ReleaseDataSet(nDS); end; end; end.
unit untFiltreFondu; interface uses StdCtrls, Controls, ExtCtrls, Classes, untHFiltreImageImage, untCalcImage; type TfrmFiltreFondu = class(TfrmHFiltreImageImage) grbParametres: TGroupBox; edtRouge: TEdit; lblRouge: TLabel; edtVert: TEdit; lblBleu: TLabel; edtBleu: TEdit; lblVert: TLabel; procedure edtRougeChange(Sender: TObject); procedure edtVertChange(Sender: TObject); procedure edtBleuChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOKClick(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } PourcentageImage1 : TCouleur; procedure PrevisualiseResultat; override; end; var frmFiltreFondu: TfrmFiltreFondu; procedure CalculerOperation(Image1, Image2 : TCalcImage; PourcentageImage1 : TCouleur; var ImageResultat : TCalcImage); implementation uses SysUtils, Forms, untMDIImage, untPrincipale; {$R *.DFM} { TfrmFiltreFondu } procedure TfrmFiltreFondu.PrevisualiseResultat; var X, Y : Integer; X2, Y2 : Integer; begin if EnabledOK then // Si les images sont "compatibles" begin for X := 0 to CalcImagePrevisualisation.TailleX - 1 do begin X2 := X * (TfrmMDIImage(Image1).CalcImage.TailleX - 1) div (CalcImagePrevisualisation.TailleX - 1); // Calcul le pixel correspondant sur les images d'origines for Y := 0 to CalcImagePrevisualisation.TailleY - 1 do begin Y2 := Y * (TfrmMDIImage(Image1).CalcImage.TailleY - 1) div (CalcImagePrevisualisation.TailleY - 1); // Calcul le pixel correspondant sur les images d'origines CalcImagePrev1.Image[X, Y] := TfrmMDIImage(Image1).CalcImage.Image[X2, Y2]; // Copie les pixels des images CalcImagePrev2.Image[X, Y] := TfrmMDIImage(Image2).CalcImage.Image[X2, Y2]; // d'origine sur les images de prévisualisation end; end; CalculerOperation(CalcImagePrev1, CalcImagePrev2, PourcentageImage1, CalcImagePrevisualisation); // Calcul l'image résultat de la prévisualisation AffichePrevisualisation; // Affiche la prévisualisation end; end; procedure CalculerOperation(Image1, Image2 : TCalcImage; PourcentageImage1 : TCouleur; var ImageResultat : TCalcImage); var X, Y : Integer; begin PourcentageImage1.Rouge := PourcentageImage1.Rouge / 100; // Change les pourcentages (allant de 0 à 100) PourcentageImage1.Vert := PourcentageImage1.Vert / 100; // en valeur décimale PourcentageImage1.Bleu := PourcentageImage1.Bleu / 100; // (allant de 0 à 1) frmPrincipale.ChangeStatus('Calcul'); frmPrincipale.ProgressBar.Max := Image1.TailleX - 1; for X := 0 to Image1.TailleX - 1 do // Parcourt tous les pixels begin frmPrincipale.ProgressBar.Position := X; for Y := 0 to Image1.TailleY - 1 do // de l'image begin ImageResultat.Image[X, Y].Rouge := Image1.Image[X, Y].Rouge * PourcentageImage1.Rouge + Image2.Image[X, Y].Rouge * (1 - PourcentageImage1.Rouge); // Fait le fondu entre les pixels ImageResultat.Image[X, Y].Vert := Image1.Image[X, Y].Vert * PourcentageImage1.Vert + Image2.Image[X, Y].Vert * (1 - PourcentageImage1.Vert); // de l'image 1 et les pixels de ImageResultat.Image[X, Y].Bleu := Image1.Image[X, Y].Bleu * PourcentageImage1.Bleu + Image2.Image[X, Y].Bleu * (1 - PourcentageImage1.Bleu); // l'image 2 suivant le pourcentage donné end; end; frmPrincipale.FinCalcul; end; procedure TfrmFiltreFondu.edtRougeChange(Sender: TObject); begin edtRouge.Text := FormateNombreDecimal(edtRouge.Text, True, PourcentageImage1.Rouge); Application.ProcessMessages; PrevisualiseResultat; end; procedure TfrmFiltreFondu.edtVertChange(Sender: TObject); begin edtVert.Text := FormateNombreDecimal(edtVert.Text, True, PourcentageImage1.Vert); Application.ProcessMessages; PrevisualiseResultat; end; procedure TfrmFiltreFondu.edtBleuChange(Sender: TObject); begin edtBleu.Text := FormateNombreDecimal(edtBleu.Text, True, PourcentageImage1.Bleu); Application.ProcessMessages; PrevisualiseResultat; end; procedure TfrmFiltreFondu.FormCreate(Sender: TObject); begin inherited; PourcentageImage1.Rouge := 50; PourcentageImage1.Vert := 50; PourcentageImage1.Bleu := 50; end; procedure TfrmFiltreFondu.btnOKClick(Sender: TObject); begin inherited; TfrmMDIImage(ListeImages.Last).Caption := Format('Fondu(%s, %s, RGB(%g, %g, %g))', [TfrmMDIImage(Image1).Caption, TfrmMDIImage(Image2).Caption, PourcentageImage1.Rouge, PourcentageImage1.Vert, PourcentageImage1.Bleu]); // Affiche le titre de l'image CalculerOperation(TfrmMDIImage(Image1).CalcImage, TfrmMDIImage(Image2).CalcImage, PourcentageImage1, TfrmMDIImage(ListeImages.Last).CalcImage); // Calcul le résultat TfrmMDIImage(ListeImages.Last).AfficheImage; // Affiche le résultat end; end.
unit udmTabsVeiculos; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmTabsVeiculos = class(TdmPadrao) qryManutencaoCGC: TStringField; qryManutencaoVEICULO: TIntegerField; qryManutencaoPRODUTO: TStringField; qryManutencaoTARIFA: TStringField; qryManutencaoVIGENCIA: TDateTimeField; qryManutencaoVLR_FRETE: TFloatField; qryManutencaoFRT_TONELADA: TFloatField; qryManutencaoEXCEDENTE: TFloatField; qryManutencaoFRT_MINIMO: TFloatField; qryManutencaoFRT_MAXIMO: TFloatField; qryManutencaoFRT_CUBAGEM: TFloatField; qryManutencaoFRT_COMPARATIVO: TFloatField; qryManutencaoKGS_CORRIDO: TFloatField; qryManutencaoAD_VALOREM: TFloatField; qryManutencaoHR_CONTRATO: TFloatField; qryManutencaoHR_EXCEDENTE: TFloatField; qryManutencaoAJUDANTE: TFloatField; qryManutencaoESTIVA: TFloatField; qryManutencaoFRT_PESO_MIN: TFloatField; qryManutencaoVLR_NOTA_MIN: TFloatField; qryManutencaoFRT_VALOR_MIN: TFloatField; qryManutencaoISENTA_ICMS: TStringField; qryManutencaoATIVA_TAXA: TStringField; qryManutencaoCOD_TAXA: TStringField; qryManutencaoCRT_BASE: TFloatField; qryManutencaoCRT_CONDICAO: TStringField; qryManutencaoCRT_AJUDANTE: TFloatField; qryManutencaoCRT_ESTIVAS: TFloatField; qryManutencaoCRT_HREXCEDENTE: TFloatField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoCRT_PEDAGIO: TFloatField; qryManutencaoNM_CLIENTE: TStringField; qryManutencaoNM_TARIFA: TStringField; qryManutencaoNM_TIPOVEICULO: TStringField; qryManutencaoNM_PRODUTO: TStringField; qryLocalizacaoCGC: TStringField; qryLocalizacaoVEICULO: TIntegerField; qryLocalizacaoPRODUTO: TStringField; qryLocalizacaoTARIFA: TStringField; qryLocalizacaoVIGENCIA: TDateTimeField; qryLocalizacaoVLR_FRETE: TFloatField; qryLocalizacaoFRT_TONELADA: TFloatField; qryLocalizacaoEXCEDENTE: TFloatField; qryLocalizacaoFRT_MINIMO: TFloatField; qryLocalizacaoFRT_MAXIMO: TFloatField; qryLocalizacaoFRT_CUBAGEM: TFloatField; qryLocalizacaoFRT_COMPARATIVO: TFloatField; qryLocalizacaoKGS_CORRIDO: TFloatField; qryLocalizacaoAD_VALOREM: TFloatField; qryLocalizacaoHR_CONTRATO: TFloatField; qryLocalizacaoHR_EXCEDENTE: TFloatField; qryLocalizacaoAJUDANTE: TFloatField; qryLocalizacaoESTIVA: TFloatField; qryLocalizacaoFRT_PESO_MIN: TFloatField; qryLocalizacaoVLR_NOTA_MIN: TFloatField; qryLocalizacaoFRT_VALOR_MIN: TFloatField; qryLocalizacaoISENTA_ICMS: TStringField; qryLocalizacaoATIVA_TAXA: TStringField; qryLocalizacaoCOD_TAXA: TStringField; qryLocalizacaoCRT_BASE: TFloatField; qryLocalizacaoCRT_CONDICAO: TStringField; qryLocalizacaoCRT_AJUDANTE: TFloatField; qryLocalizacaoCRT_ESTIVAS: TFloatField; qryLocalizacaoCRT_HREXCEDENTE: TFloatField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoCRT_PEDAGIO: TFloatField; qryLocalizacaoNM_CLIENTE: TStringField; qryLocalizacaoNM_TARIFA: TStringField; qryLocalizacaoNM_TIPOVEICULO: TStringField; qryLocalizacaoNM_PRODUTO: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FTpo_Veiculo: Integer; FTarifa: string; FCliente: string; FProduto: string; FVigencia: TDateTime; public property Cliente: string read FCliente write FCliente; property Produto: string read FProduto write FProduto; property Tpo_Veiculo: Integer read FTpo_Veiculo write FTpo_Veiculo; property Tarifa: string read FTarifa write FTarifa; property Vigencia: TDateTime read FVigencia write FVigencia; function LocalizaTabsCliente(DataSet: TDataSet = nil): Boolean; function LocalizarPorTipo(DataSet: TDataSet = nil): Boolean; end; const SQL_DEFAULT = ' SELECT ' + ' TABV.CGC, ' + ' TABV.VEICULO, ' + ' TABV.PRODUTO, ' + ' TABV.TARIFA, ' + ' TABV.VIGENCIA, ' + ' TABV.VLR_FRETE, ' + ' TABV.FRT_TONELADA, ' + ' TABV.EXCEDENTE, ' + ' TABV.FRT_MINIMO, ' + ' TABV.FRT_MAXIMO, ' + ' TABV.FRT_CUBAGEM, ' + ' TABV.FRT_COMPARATIVO, ' + ' TABV.KGS_CORRIDO, ' + ' TABV.AD_VALOREM, ' + ' TABV.HR_CONTRATO, ' + ' TABV.HR_EXCEDENTE, ' + ' TABV.AJUDANTE, ' + ' TABV.ESTIVA, ' + ' TABV.FRT_PESO_MIN, ' + ' TABV.VLR_NOTA_MIN, ' + ' TABV.FRT_VALOR_MIN, ' + ' TABV.ISENTA_ICMS, ' + ' TABV.ATIVA_TAXA, ' + ' TABV.COD_TAXA, ' + ' TABV.CRT_BASE, ' + ' TABV.CRT_CONDICAO, ' + ' TABV.CRT_AJUDANTE, ' + ' TABV.CRT_ESTIVAS, ' + ' TABV.CRT_HREXCEDENTE, ' + ' TABV.DT_ALTERACAO, ' + ' TABV.OPERADOR, ' + ' TABV.CRT_PEDAGIO, ' + ' CL.NOME NM_CLIENTE, ' + ' CASE ' + ' WHEN TR.DESCRICAO IS NULL THEN ''NAO IDENTIFICADA E/OU CADASTRADA'' ' + ' ELSE TR.DESCRICAO ' + ' END NM_TARIFA, ' + ' TV.DESCRICAO NM_TIPOVEICULO, ' + ' PROD.DESCRICAO NM_PRODUTO ' + ' FROM STWOPETTABV TABV ' + ' JOIN STWOPETCLI CL ON CL.CGC = TABV.CGC ' + ' LEFT JOIN STWOPETTAR TR ON TR.CODIGO = TABV.TARIFA ' + ' LEFT JOIN STWOPETTPVE TV ON TV.CODIGO = TABV.VEICULO ' + //FALTAVA LEFT JOIN AQUI ' JOIN STWARMTPROD PROD ON PROD.CODIGO = TABV.PRODUTO '; var dmTabsVeiculos: TdmTabsVeiculos; implementation {$R *.dfm} { TdmTabsVeiculos } function TdmTabsVeiculos.LocalizarPorTipo(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE TABV.CGC = :CGC'); if Length(FProduto) > 0 then SQL.Add('AND TABV.PRODUTO = :PRODUTO'); if Length(FTarifa) > 0 then SQL.Add('AND TABV.TARIFA = :TARIFA'); SQL.Add('ORDER BY TABV.CGC, TABV.VEICULO, TABV.PRODUTO, TABV.TARIFA, TABV.VIGENCIA'); ParamByName('CGC').AsString := FCliente; if Length(FProduto) > 0 then ParamByName('PRODUTO').AsString := FProduto; if Length(FTarifa) > 0 then ParamByName('TARIFA').AsString := FTarifa; Open; Result := not IsEmpty; end; end; function TdmTabsVeiculos.LocalizaTabsCliente(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE TABV.CGC = :CGC'); SQL.Add('ORDER BY TABV.CGC, TABV.VEICULO, TABV.PRODUTO, TABV.TARIFA, TABV.VIGENCIA'); Params[0].AsString := FCliente; Open; Result := not IsEmpty; end; end; procedure TdmTabsVeiculos.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE TABV.CGC = :CGC'); SQL.Add(' AND TABV.VEICULO = :VEICULO'); SQL.Add(' AND TABV.PRODUTO = :PRODUTO'); SQL.Add(' AND TABV.TARIFA = :TARIFA'); SQL.Add(' AND TABV.VIGENCIA = :VIGENCIA'); SQL.Add('ORDER BY TABV.CGC, TABV.VEICULO, TABV.PRODUTO, TABV.TARIFA, TABV.VIGENCIA'); Params[0].AsString := FCliente; Params[1].AsInteger := FTpo_Veiculo; Params[2].AsString := FProduto; Params[3].AsString := FTarifa; Params[4].AsDate := FVigencia; end; end; procedure TdmTabsVeiculos.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY TABV.CGC, TABV.VEICULO, TABV.PRODUTO, TABV.TARIFA, TABV.VIGENCIA'); end; end; end.
unit uDbTypes; {$mode objfpc}{$H+} interface uses Db; type TDbKeyType = integer; const ftDbKey:TFieldType = ftInteger; procedure DbFieldAssignAsDbKey(D:TDataSet; const FieldName:string; F:TField);overload; procedure DbFieldAssignAsDbKey(D:TDataSet; const FieldName:string; const Val:string);overload; function DBFieldAsDBKey(D:TDataSet; const FieldName:string):TDbKeyType; function StrToDBKey(const S:String):TDbKeyType; implementation uses sysutils; function StrToDBKey(const S:String):TDbKeyType; begin Result:=StrToInt(S); end; procedure DbFieldAssignAsDbKey(D:TDataSet; const FieldName:string; const Val:string);overload; begin D.FieldByName(FieldName).AsInteger:=StrToInt(Val); end; procedure DbFieldAssignAsDbKey(D:TDataSet; const FieldName:string; F:TField); begin D.FieldByName(FieldName).AsInteger:=F.AsInteger; end; function DBFieldAsDBKey(D:TDataSet; const FieldName:string):TDbKeyType; begin Result:=D.FieldByName(FieldName).AsInteger; end; end.
unit configuration; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles; type TUserStatus = (usAdmin, usSimple, usBanned); // in future it can increase enums { TConfig } TConfig = class private FIni: TMemIniFile; FUsers: TStringList; function GetAPIEndPoint: String; function GetAPITimeout: Integer; function GetBotTooken: String; function GetDefaultDir: String; function GetHTTPProxyHost: String; function GetHTTPProxyPort: Word; function GetHTTPProxyPswd: String; function GetHTTPProxyUser: String; function GetScriptsDirectory: String; function GetServiceUser: Int64; function GetUsers(UserID: Int64): TUserStatus; function GetUserList: TStrings; public constructor Create(const AConfFile: String); destructor Destroy; override; property ServiceUser: Int64 read GetServiceUser; property APIEndPoint: String read GetAPIEndPoint; property BotTooken: String read GetBotTooken; property Users[UserID: Int64]: TUserStatus read GetUsers; property APITimeout: Integer read GetAPITimeout; // longpolling timeout property HTTPProxyHost: String read GetHTTPProxyHost; property HTTPProxyPort: Word read GetHTTPProxyPort; property HTTPProxyUser: String read GetHTTPProxyUser; property HTTPProxyPswd: String read GetHTTPProxyPswd; property ScriptsDirectory: String read GetScriptsDirectory; property DefaultDir: String read GetDefaultDir; end; var Cnfg: TConfig; implementation uses tgsendertypes ; var CnfDir: String; { TConfig } function TConfig.GetAPIEndPoint: String; begin Result:=FIni.ReadString('API', 'Endpoint', TelegramAPI_URL); end; function TConfig.GetAPITimeout: Integer; begin Result:=FIni.ReadInteger('API', 'Timeout', 20); // 20 sec for longpolling request ?? end; function TConfig.GetBotTooken: String; begin Result:=FIni.ReadString('API', 'Token', EmptyStr) end; function TConfig.GetDefaultDir: String; begin Result:=FIni.ReadString('File', 'DefaultDir', PathDelim); end; function TConfig.GetHTTPProxyHost: String; begin Result:=FIni.ReadString('Proxy', 'Host', EmptyStr); end; function TConfig.GetHTTPProxyPort: Word; begin Result:=FIni.ReadInteger('Proxy', 'Port', 3128); end; function TConfig.GetHTTPProxyPswd: String; begin Result:=FIni.ReadString('Proxy', 'Password', EmptyStr); end; function TConfig.GetHTTPProxyUser: String; begin Result:=FIni.ReadString('Proxy', 'Username', EmptyStr); end; function TConfig.GetScriptsDirectory: String; begin Result:=IncludeTrailingPathDelimiter(FIni.ReadString('Scripts', 'Directory', CnfDir)); end; function TConfig.GetServiceUser: Int64; begin Result:=FIni.ReadInt64('Service', 'User', 0); end; function TConfig.GetUsers(UserID: Int64): TUserStatus; var s: String; begin s:=GetUserList.Values[IntToStr(UserID)]; if s=EmptyStr then Exit(usSimple); case s[1] of 'a': Result:=usAdmin; 'b': Result:=usBanned; 's': Result:=usSimple; else Result:=usSimple; end; end; function TConfig.GetUserList: TStrings; begin if not Assigned(FUsers) then begin FUsers:=TStringList.Create; FIni.ReadSectionRaw('users', FUsers); FUsers.Sorted:=True; end; Result:=FUsers; end; constructor TConfig.Create(const AConfFile: String); begin FIni:=TMemIniFile.Create(AConfFile); end; destructor TConfig.Destroy; begin FUsers.Free; FIni.Free; inherited Destroy; end; initialization{$ifdef portable} CnfDir:=IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))); Cnfg:=TConfig.Create(CnfDir+ChangeFileExt(ExtractFileName(ParamStr(0)), '.ini'));{$else} CnfDir:=GetAppConfigDir(True); Cnfg:=TConfig.Create(CnfDir+ChangeFileExt(ExtractFileName(ParamStr(0)), '.ini'));{$endif} finalization FreeAndNil(Cnfg); end.
unit StockDetailsFRM; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, System.UITypes, StockController, ItemController; type TStockMode = (smEdit, smNew); type TfrmStockDetails = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; edtItemName: TEdit; edtQuantity: TEdit; edtPrice: TEdit; btnOK: TButton; btnCancel: TButton; dtModifiedDate: TDateTimePicker; edtItemId: TEdit; mmStockComments: TMemo; edtItemDescription: TEdit; btnItemsSearch: TBitBtn; procedure btnItemsSearchClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); private FStock: TStock; FStockMode: TStockMode; procedure LoadStockDetails; function PerformValidations: boolean; procedure CopyStockDetails; procedure PopulateItemFromLookUp(AItem: TItem); { Private declarations } public { Public declarations } property Stock: TStock read FStock write FStock; property StockMode: TStockMode read FStockMode write FStockMode; end; implementation uses ItemsFRM; {$R *.dfm} procedure TfrmStockDetails.btnItemsSearchClick(Sender: TObject); var LItemsFrm: TfrmItems; begin LItemsFrm := TfrmItems.Create(nil); LItemsFrm.IsLookUp := true; try LItemsFrm.ShowModal; PopulateItemFromLookUp(LItemsFrm.SelectedItem); finally LItemsFrm.Free; end; end; procedure TfrmStockDetails.PopulateItemFromLookUp(AItem: TItem); begin if AItem <> nil then begin edtItemId.Text := IntToStr(AItem.ItemId); edtItemName.Text := AItem.ItemName; edtItemDescription.Text := AItem.ItemDescription; end; end; procedure TfrmStockDetails.btnOKClick(Sender: TObject); begin if PerformValidations then begin CopyStockDetails; ModalResult := mrOk; end; end; function TfrmStockDetails.PerformValidations: boolean; begin result := true; if trim(edtItemId.Text) = '' then begin MessageDlg('Please select a valid Item from Lookup.', mtError, [mbOK], 0); result := false; end; end; procedure TfrmStockDetails.CopyStockDetails; begin FStock.ItemId := StrToInt(edtItemId.Text); FStock.ItemName := edtItemName.Text; FStock.ItemDescription := edtItemDescription.Text; FStock.Updated_Date := dtModifiedDate.DateTime; FStock.Quantity := StrToInt(edtQuantity.Text); FStock.UnitPrice := StrToFloat(edtPrice.Text); FStock.Comments := mmStockComments.Text; end; procedure TfrmStockDetails.FormShow(Sender: TObject); begin LoadStockDetails; end; procedure TfrmStockDetails.LoadStockDetails; begin if StockMode = smEdit then begin edtItemId.Text := IntToStr(FStock.ItemId); edtItemName.Text := FStock.ItemName; edtItemDescription.Text := FStock.ItemDescription; dtModifiedDate.DateTime := FStock.Updated_Date; edtQuantity.Text := IntToStr(FStock.Quantity); edtPrice.Text := FloatToStr(FStock.UnitPrice); mmStockComments.Text := FStock.Comments; end; end; end.
unit kwPopEditorEditFormula; {* *Формат:* указатель_на_редактор pop:editor:EditFormula *Описание:* Открывает окно редактирование формулы и нажимает на "Ок". *Пример:* [code] focused:control:push pop:editor:EditFormula [code] *Результат:* Появится диалог редактирования формулы и будет закрыт по нажатии кнопки "Ок" *Примечания:* Не изменяет содерижое формулы. Служит для проверки изменения в формуле, если там в ней присуствовал мусор и работы форматирования после такого изменения. } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwPopEditorEditFormula.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "pop_editor_EditFormula" MUID: (4F5DA0D50129) // Имя типа: "TkwPopEditorEditFormula" {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , kwEditorFromStackWord , tfwScriptingInterfaces , evCustomEditorWindow ; type TkwPopEditorEditFormula = {final} class(TkwEditorFromStackWord) {* *Формат:* указатель_на_редактор pop:editor:EditFormula *Описание:* Открывает окно редактирование формулы и нажимает на "Ок". *Пример:* [code] focused:control:push pop:editor:EditFormula [code] *Результат:* Появится диалог редактирования формулы и будет закрыт по нажатии кнопки "Ок" *Примечания:* Не изменяет содерижое формулы. Служит для проверки изменения в формуле, если там в ней присуствовал мусор и работы форматирования после такого изменения. } protected procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorEditFormula {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , nevTools , l3Units , Types , Messages , Windows {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) //#UC START# *4F5DA0D50129impl_uses* //#UC END# *4F5DA0D50129impl_uses* ; procedure TkwPopEditorEditFormula.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4F5DA0D50129_var* var l_Map : InevMap; l_Point : Tl3Point; l_SPoint : Tl3SPoint; l_MousePos : TSmallPoint; l_InnerPoint : InevBasePoint; //#UC END# *4F4CB81200CA_4F5DA0D50129_var* begin //#UC START# *4F4CB81200CA_4F5DA0D50129_impl* l_InnerPoint := anEditor.Selection.Cursor.MostInner; l_Map := anEditor.View.MapByPoint(l_InnerPoint); if l_Map = nil then Exit; l_Point := l3Point(l_Map.Bounds.Left + l_Map.FI.Width div 2, l_Map.Bounds.Bottom - 150); l_SPoint := anEditor.Canvas.LP2DP(l_Point); l_MousePos := PointToSmallPoint(Point(l_SPoint.X, l_SPoint.Y)); SendMessage(anEditor.Handle, WM_LBUTTONDBLCLK, 0, Longint(l_MousePos)); //#UC END# *4F4CB81200CA_4F5DA0D50129_impl* end;//TkwPopEditorEditFormula.DoWithEditor class function TkwPopEditorEditFormula.GetWordNameForRegister: AnsiString; begin Result := 'pop:editor:EditFormula'; end;//TkwPopEditorEditFormula.GetWordNameForRegister initialization TkwPopEditorEditFormula.RegisterInEngine; {* Регистрация pop_editor_EditFormula } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
{ The builder pattern is similar to abstract factory, except that the consumer only sees the highest level of abstraction. Intermediate products are identified in parameters via some kind of index or other key identifier. } unit Builder; interface uses AbstractFactory; type IMazeBuilder = interface procedure BuildMaze; procedure BuildRoom(ANumber: integer); procedure BuildDoor(AFromRoomIndex, AToRoomIndex: integer); function GetMaze: IMaze; end; // We can pass the builder as a parameter for example // LMaze := MazeGame.CreateMaze(ABuilder); // The game in turn can create the maze in an abstract way. // Difference here between the builder and the factory is that the // Consumer does not need to know constituant parts implementation end.
{ Oasis Digital Touch Screen Slider Control Copyright (c) 2006, Oasis Digital Solutions Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } unit uSlider; interface uses Classes, Windows, Graphics, Controls, ExtCtrls; type TSlider = class(TPaintBox) protected procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure Paint; override; private SliderY, TargetY: integer; WhenPushed: Cardinal; procedure CalculateTargetY(const Y: integer); procedure MoveOneStepCloser; public OnSliderMove: TNotifyEvent; procedure MoveCloser; function Position: integer; end; implementation { TSlider } uses Math; const SliderHeight = 15; procedure TSlider.CalculateTargetY(const Y: integer); begin TargetY := Y - (SliderHeight div 2); if TargetY < 0 then TargetY := 0; if TargetY > Height - SliderHeight then TargetY := Height - SliderHeight; end; procedure TSlider.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; WhenPushed := GetTickCount; CalculateTargetY(Y); MoveOneStepCloser; end; procedure TSlider.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if ssLeft in Shift then begin CalculateTargetY(Y); end; end; procedure TSlider.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; TargetY := SliderY; // stop motion when mouse released end; procedure TSlider.MoveCloser; var SpeedLimit: integer; Gap: integer; CurrentTickCount: Cardinal; begin if TargetY = SliderY then Exit; CurrentTickCount := GetTickCount; // Wait briefly, so a single click does not move it if CurrentTickCount < WhenPushed+120 then Exit; // Go up slowly at first, then after 700 milliseconds go up more quickly SpeedLimit := 1; if CurrentTickCount > WhenPushed+700 then SpeedLimit := 2; // Go down very fast if TargetY > SliderY then SpeedLimit := 15; Gap := Abs(TargetY - SliderY); SliderY := SliderY + Sign(TargetY - SliderY) * Min(Gap, SpeedLimit); if Assigned(OnSliderMove) then OnSliderMove(Self); Invalidate; end; procedure TSlider.MoveOneStepCloser; begin if TargetY = SliderY then Exit; // In this example, assume one step is one pixel. In reality we need to // do all this based on target and actual slider "Value" which is not // the same as pixels, rather it is the configured 0..100 or -72..0 scale. if TargetY > SliderY then SliderY := SliderY + 1; if TargetY < SliderY then SliderY := SliderY - 1; if Assigned(OnSliderMove) then OnSliderMove(Self); Invalidate; end; procedure TSlider.Paint; begin inherited; Canvas.Pen.Color := clGray; Canvas.Rectangle(0, 0, Width, Height); Canvas.Rectangle(30, 5, 34, Height - 5); Canvas.TextOut(2, 1, '0'); Canvas.TextOut(2, Height - canvas.TextHeight('-72')-1, '-72'); Canvas.Pen.Color := clRed; Canvas.Brush.Color := clYellow; Canvas.Rectangle(20, SliderY, Width - 5, SLiderY + SliderHeight); end; function TSlider.Position: integer; begin Result := SliderY; end; end.
unit Map; interface uses Windows, Classes, Graphics, Threads, GameTypes, LanderTypes, MapTypes, ImageCache; type TLandItem = record id : idLand; height : integer; end; type TLandRow = array[word] of TLandItem; TLandItems = array[word] of ^TLandRow; type TLandHeightInfo = THeightInfo; type TLandLuminanceInfo = TLuminanceInfo; type TExtraLandInfoItem = record heightinfo : TLandHeightInfo; luminfo : TLandLuminanceInfo; end; const cBlockBits = 5; cBlockSize = 1 shl cBlockBits; cBlockMask = pred(cBlockSize); type PExtraLandInfoItems = ^TExtraLandInfoItems; TExtraLandInfoItems = array[0 .. pred(cBlockSize), 0 .. pred(cBlockSize)] of TExtraLandInfoItem; type TExtraLandInfoBlock = record validlum : boolean; fItems : PExtraLandInfoItems; end; type TExtraLandInfoBlockRow = array[word] of TExtraLandInfoBlock; TExtraLandInfoBlockItems = array[word] of ^TExtraLandInfoBlockRow; type TWorldMap = class(TInterfacedObject, IWorldMap) public constructor Create(const Manager : ILocalCacheManager); destructor Destroy; override; private // IWorldMap fManager : ILocalCacheManager; fConverter : ICoordinateConverter; procedure InitMap; function GetRows : integer; function GetColumns : integer; function GetGroundInfo(i, j : integer; const focus : IGameFocus; out ground : TObjInfo) : boolean; function GetExtraLandInfo(i, j : integer; out extrainfo : TExtraLandInfo) : boolean; function CreateFocus(const view : IGameView) : IGameFocus; function GetImager(const focus : IGameFocus) : IImager; public procedure SetCoordConverter(const which : ICoordinateConverter); private // Land fColumns : integer; fRows : integer; fLands : ^TLandItems; fExtraLandInfoBlocks : ^TExtraLandInfoBlockItems; fMapImg : TMapImage; procedure CreateLands(Map : TMapImage); procedure DestroyLands; procedure CreateExtraLandInfoBlocks; procedure DestroyExtraLandInfoBlocks; procedure CreateExtraLandInfoItems(row, col : integer; createluminfo : boolean); procedure DestroyExtraLandInfoItems(row, col : integer); function GetLandHeightInfo(i, j : integer; out heightinfo : TLandHeightInfo) : boolean; private procedure ReleaseMap; private // Images fImageCache : TImageCache; private // misc fFocuses : TList; procedure InitViewOrigin(const view : IGameView); end; implementation uses Messages, AxlDebug, SysUtils, Land, MathUtils; type TGameFocus = class(TInterfacedObject, IGameFocus) public constructor Create(Map : TWorldMap; const view : IGameView); destructor Destroy; override; private // IGameUpdater fLockCount : integer; fUpdateDefered : boolean; function Lock : integer; function Unlock : integer; function LockCount : integer; procedure QueryUpdate(Defer : boolean); private // IGameFocus ... Dispatch inherited from TObject procedure MouseMove(x, y : integer); procedure MouseClick; procedure KeyPressed(which : word; const Shift : TShiftState); procedure Refresh; function GetText(kind : integer) : string; function GetObject : TObject; function GetRect : TRect; procedure SetRect(const R : TRect); private fMap : TWorldMap; fView : IGameView; fZoomFactor : single; fImager : IImager; fMouseX : integer; fMouseY : integer; Selection : TSelectionData; function GetImager : IImager; private procedure ViewZoomed(var msg : TViewZoomedMsg); message msgViewZoomed; procedure MoveTo(var msg : TMoveToMsg); message msgMoveTo; end; const cBasicU = 16; // Utils function min(i, j : integer) : integer; begin if i <= j then Result := i else Result := j; end; function max(i, j : integer) : integer; begin if i >= j then Result := i else Result := j; end; procedure SetRectOrigin(var which : TRect; x, y : integer); begin OffsetRect(which, x - which.Left, y - which.Top); end; procedure FreeObject(var which); var aux : TObject; begin aux := TObject(which); TObject(which) := nil; aux.Free; end; function RectFromMapBlock(const view : IGameView; const converter : ICoordinateConverter; i, j : integer) : TRect; var x, y : integer; u : integer; R : TRect; begin converter.MapToScreen(view, i, j, x, y); u := 2 shl view.ZoomLevel; R.Left := x; R.Right := x + 4*u; R.Top := y - u; R.Bottom := y + u; Result := R; end; // TWorldMap constructor TWorldMap.Create(const Manager : ILocalCacheManager); begin inherited Create; fManager := Manager; end; destructor TWorldMap.Destroy; begin assert(RefCount = 0); ReleaseMap; pointer(fConverter) := nil; // Cross referenced inherited; end; function TWorldMap.GetRows : integer; begin Result := fRows; end; function TWorldMap.GetColumns : integer; begin Result := fColumns; end; const cFocusOptions : array[boolean] of TLandOption = (loRedShaded, loShaded); function TWorldMap.GetGroundInfo(i, j : integer; const focus : IGameFocus; out ground : TObjInfo) : boolean; begin Result := (i >= 0) and (i < fRows) and (j >= 0) and (j < fColumns); if Result then begin fillchar(ground, sizeof(ground), 0); ground.Options := []; ground.id := fLands[i, j].id; if LandTypeOf(fLands[i, j].id) = ldtSpecial then fLands[i, j].id := ord(LandClassOf(fLands[i, j].id)) shl lndClassShift; ground.Height := 1 + fLands[i, j].height; end; end; function TWorldMap.GetExtraLandInfo(i, j : integer; out extrainfo : TExtraLandInfo) : boolean; var row, col : integer; begin Result := (i >= 0) and (i < fRows) and (j >= 0) and (j < fColumns); if Result then begin fillchar(extrainfo, sizeof(extrainfo), 0); row := i shr cBlockBits; col := j shr cBlockBits; if (fExtraLandInfoBlocks[row, col].fItems = nil) or not fExtraLandInfoBlocks[row, col].validlum then CreateExtraLandInfoItems(row, col, true); extrainfo.heightinfo := fExtraLandInfoBlocks[row, col].fItems[i and cBlockMask, j and cBlockMask].heightinfo; extrainfo.luminfo := fExtraLandInfoBlocks[row, col].fItems[i and cBlockMask, j and cBlockMask].luminfo; end; end; function TWorldMap.CreateFocus(const view : IGameView) : IGameFocus; begin InitViewOrigin(view); Result := TGameFocus.Create(Self, view); end; function TWorldMap.GetImager(const focus : IGameFocus) : IImager; begin Result := TGameFocus(focus.GetObject).GetImager; end; procedure TWorldMap.InitMap; var Map : TMapImage; i : integer; begin Map := fManager.GetLandMap; fMapImg := Map; fColumns := Map.Width; fRows := Map.Height; fFocuses := TList.Create; fImageCache := TImageCache.Create(fManager); CreateLands(Map); CreateExtraLandInfoBlocks; for i := 0 to pred(fFocuses.Count) do InitViewOrigin(TGameFocus(fFocuses[i]).fView); end; procedure TWorldMap.ReleaseMap; begin DestroyExtraLandInfoBlocks; DestroyLands; FreeObject(fImageCache); assert(fFocuses.Count = 0, Format('fFocuses.Free error, Count = %d', [fFocuses.Count])); FreeObject(fFocuses); // <<>> Members of fFcocused fRows := 0; fColumns := 0; fMapImg := nil; end; procedure TWorldMap.SetCoordConverter(const which : ICoordinateConverter); begin fConverter := which; fConverter._Release; // cross referenced end; procedure TWorldMap.CreateLands(Map : TMapImage); const MaxHeight = 40; var i, j : integer; begin getmem(fLands, fRows*sizeof(fLands[0])); for i := 0 to pred(fRows) do begin getmem(fLands[i], fColumns*sizeof(fLands[0, 0])); for j := 0 to pred(fColumns) do begin fLands[i, j].id := pbyte(Map.PixelAddr[j, i, 0])^; //fLands[i, j].height := 1 + random(3*MaxHeight); { if random(4) = 0 then fLands[i, j].height := round(MaxHeight*sqrt(2 + sqr((cos(i*Pi/5))) + sqr(sin(j*Pi/5)))) else fLands[i, j].height := round(MaxHeight*(2 + sqr((cos(i*Pi/5))) + sqr(sin(j*Pi/5)))); } if LandClassOf(fLands[i, j].id) <> lncZoneD then fLands[i, j].height := round(MaxHeight*(2 + cos(i*Pi/5) + sin(j*Pi/5))) else fLands[i, j].height := 0; //fLands[i, j].height := 10*((j + i) mod 3); //fLands[i, j].height := 10*((i mod 3 + j mod 3)) //fLands[i, j].height := 10; end; end; end; procedure TWorldMap.DestroyLands; begin freemem(fLands); end; procedure TWorldMap.CreateExtraLandInfoBlocks; var i : integer; r, c : integer; begin r := succ(fRows shr cBlockBits); c := succ(fColumns shr cBlockBits); getmem(fExtraLandInfoBlocks, r*sizeof(fExtraLandInfoBlocks[0])); getmem(fExtraLandInfoBlocks[0], r*c*sizeof(fExtraLandInfoBlocks[0, 0])); fillchar(fExtraLandInfoBlocks[0]^, r*c*sizeof(fExtraLandInfoBlocks[0, 0]), 0); for i := 1 to pred(r) do fExtraLandInfoBlocks[i] := @fExtraLandInfoBlocks[i - 1, c]; end; procedure TWorldMap.DestroyExtraLandInfoBlocks; var i, j : integer; r, c : integer; begin r := succ(fRows shr cBlockBits); c := succ(fColumns shr cBlockBits); for i := 0 to pred(r) do for j := 0 to pred(c) do if fExtraLandInfoBlocks[i, j].fItems <> nil then DestroyExtraLandInfoItems(i, j); freemem(fExtraLandInfoBlocks[0]); freemem(fExtraLandInfoBlocks); end; procedure TWorldMap.CreateExtraLandInfoItems(row, col : integer; createluminfo : boolean); var i, j : integer; rr, cc : integer; procedure CalcLandHeightInfo(i, j : integer; out landheightinfo : TLandHeightInfo); var obj : TObjInfo; x1, x2, x3 : integer; y1, y2, y3 : integer; z1, z2, z3 : integer; v1x, v1y, v1z : integer; // triangle-side vectors v2x, v2y, v2z : integer; begin // this is still unefficient, a lot of things can be simplified x1 := 2*cBasicU; y1 := 0; if GetGroundInfo(i + 1, j, nil, obj) then z1 := obj.Height else z1 := 0; x2 := 2*cBasicU; y2 := 2*cBasicU; if GetGroundInfo(i, j - 1, nil, obj) then z2 := obj.Height else z2 := 0; x3 := 0; y3 := cBasicU; if GetGroundInfo(i + 1, j - 1, nil, obj) then z3 := obj.Height else z3 := 0; v1x := x1 - x3; v1y := y1 - y3; v1z := z1 - z3; v2x := x2 - x3; v2y := y2 - y3; v2z := z2 - z3; with landheightinfo do begin lnx := v1y*v2z - v1z*v2y; lny := v1z*v2x - v1x*v2z; lnz := v1x*v2y - v1y*v2x; ld := -lnx*x1 - lny*y1 - lnz*z1; end; x3 := 4*cBasicU; y3 := cBasicU; if GetGroundInfo(i, j, nil, obj) then z3 := obj.Height else z3 := 0; v1x := x1 - x3; v1y := y1 - y3; v1z := z1 - z3; v2x := x2 - x3; v2y := y2 - y3; v2z := z2 - z3; with landheightinfo do begin rnx := v2y*v1z - v2z*v1y; rny := v2z*v1x - v2x*v1z; rnz := v2x*v1y - v2y*v1x; rd := -rnx*x1 - rny*y1 - rnz*z1; end; end; procedure CalcLandLumInfo(i, j : integer; out landluminfo : TLandLuminanceInfo); var lightx : single; lighty : single; lightz : single; lmod : single; var heightinfo : TLandHeightInfo; nmod : single; nx, ny, nz : integer; i1x, i1y, i1z : single; i2x, i2y, i2z : single; i3x, i3y, i3z : single; v1x, v1y, v1z : single; // intensity triangle-side vectors v2x, v2y, v2z : single; begin { lightx := -4; lighty := 3; lightz := 3; } lightx := -4; lighty := 3; lightz := 4; lmod := sqrt(lightx*lightx + lighty*lighty + lightz*lightz); lightx := lightx/lmod; lighty := lighty/lmod; lightz := lightz/lmod; if GetLandHeightInfo(i + 1, j + 1, heightinfo) then begin nx := heightinfo.lnx + heightInfo.rnx; ny := heightinfo.lny + heightInfo.rny; nz := heightinfo.lnz + heightInfo.rnz; end else begin nx := 0; ny := 0; nz := 8*cBasicU*cBasicU; end; if GetLandHeightInfo(i, j + 1, heightinfo) then begin inc(nx, heightinfo.lnx); inc(ny, heightinfo.lny); inc(nz, heightinfo.lnz); end else inc(nz, 4*cBasicU*cBasicU); if GetLandHeightInfo(i, j, heightinfo) then begin inc(nx, heightinfo.lnx + heightinfo.rnx); inc(ny, heightinfo.lny + heightinfo.rny); inc(nz, heightinfo.lnz + heightinfo.rnz); end else inc(nz, 8*cBasicU*cBasicU); if GetLandHeightInfo(i + 1, j, heightinfo) then begin inc(nx, heightinfo.rnx); inc(ny, heightinfo.rny); inc(nz, heightinfo.rnz); end else inc(nz, 4*cBasicU*cBasicU); i1x := nx/6; i1y := ny/6; i1z := nz/6; nmod := sqrt(i1x*i1x + i1y*i1y + i1z*i1z); if nmod <> 0 then i1z := realmax(0, (lightx*i1x + lighty*i1y + lightz*i1z)/nmod) else i1z := 0; i1x := 2*cBasicU; i1y := 0; if GetLandHeightInfo(i, j, heightinfo) then begin nx := heightinfo.lnx + heightInfo.rnx; ny := heightinfo.lny + heightInfo.rny; nz := heightinfo.lnz + heightInfo.rnz; end else begin nx := 0; ny := 0; nz := 8*cBasicU*cBasicU; end; if GetLandHeightInfo(i - 1, j, heightinfo) then begin inc(nx, heightinfo.lnx); inc(ny, heightinfo.lny); inc(nz, heightinfo.lnz); end else inc(nz, 4*cBasicU*cBasicU); if GetLandHeightInfo(i - 1, j - 1, heightinfo) then begin inc(nx, heightinfo.lnx + heightinfo.rnx); inc(ny, heightinfo.lny + heightinfo.rny); inc(nz, heightinfo.lnz + heightinfo.rnz); end else inc(nz, 8*cBasicU*cBasicU); if GetLandHeightInfo(i, j - 1, heightinfo) then begin inc(nx, heightinfo.rnx); inc(ny, heightinfo.rny); inc(nz, heightinfo.rnz); end else inc(nz, 4*cBasicU*cBasicU); i2x := nx/6; i2y := ny/6; i2z := nz/6; nmod := sqrt(i2x*i2x + i2y*i2y + i2z*i2z); if nmod <> 0 then i2z := realmax(0, (lightx*i2x + lighty*i2y + lightz*i2z)/nmod) else i2z := 0; i2x := 2*cBasicU; i2y := 2*cBasicU; if GetLandHeightInfo(i + 1, j, heightinfo) then begin nx := heightinfo.lnx + heightInfo.rnx; ny := heightinfo.lny + heightInfo.rny; nz := heightinfo.lnz + heightInfo.rnz; end else begin nx := 0; ny := 0; nz := 8*cBasicU*cBasicU; end; if GetLandHeightInfo(i, j, heightinfo) then begin inc(nx, heightinfo.lnx); inc(ny, heightinfo.lny); inc(nz, heightinfo.lnz); end else inc(nz, 4*cBasicU*cBasicU); if GetLandHeightInfo(i, j - 1, heightinfo) then begin inc(nx, heightinfo.lnx + heightinfo.rnx); inc(ny, heightinfo.lny + heightinfo.rny); inc(nz, heightinfo.lnz + heightinfo.rnz); end else inc(nz, 8*cBasicU*cBasicU); if GetLandHeightInfo(i + 1, j - 1, heightinfo) then begin inc(nx, heightinfo.rnx); inc(ny, heightinfo.rny); inc(nz, heightinfo.rnz); end else inc(nz, 4*cBasicU*cBasicU); i3x := nx/6; i3y := ny/6; i3z := nz/6; nmod := sqrt(i3x*i3x + i3y*i3y + i3z*i3z); if nmod <> 0 then i3z := realmax(0, (lightx*i3x + lighty*i3y + lightz*i3z)/nmod) else i3z := 0; i3x := 0; i3y := cBasicU; v1x := i1x - i3x; v1y := i1y - i3y; v1z := i1z - i3z; v2x := i2x - i3x; v2y := i2y - i3y; v2z := i2z - i3z; with landluminfo do begin lluma := v1y*v2z - v1z*v2y; llumb := v1z*v2x - v1x*v2z; llumc := v1x*v2y - v1y*v2x; llumd := -lluma*i1x - llumb*i1y - llumc*i1z; end; if GetLandHeightInfo(i, j + 1, heightinfo) then begin nx := heightinfo.lnx + heightInfo.rnx; ny := heightinfo.lny + heightInfo.rny; nz := heightinfo.lnz + heightInfo.rnz; end else begin nx := 0; ny := 0; nz := -8*cBasicU*cBasicU; end; if GetLandHeightInfo(i - 1, j + 1, heightinfo) then begin inc(nx, heightinfo.lnx); inc(ny, heightinfo.lny); inc(nz, heightinfo.lnz); end else inc(nz, -4*cBasicU*cBasicU); if GetLandHeightInfo(i - 1, j, heightinfo) then begin inc(nx, heightinfo.lnx + heightinfo.rnx); inc(ny, heightinfo.lny + heightinfo.rny); inc(nz, heightinfo.lnz + heightinfo.rnz); end else inc(nz, -8*cBasicU*cBasicU); if GetLandHeightInfo(i, j, heightinfo) then begin inc(nx, heightinfo.rnx); inc(ny, heightinfo.rny); inc(nz, heightinfo.rnz); end else inc(nz, -4*cBasicU*cBasicU); i3x := nx/6; i3y := ny/6; i3z := nz/6; nmod := sqrt(i3x*i3x + i3y*i3y + i3z*i3z); if nmod <> 0 then i3z := realmax(0, (lightx*i3x + lighty*i3y + lightz*i3z)/nmod) else i3z := 0; i3x := 4*cBasicU; i3y := cBasicU; v1x := i1x - i3x; v1y := i1y - i3y; v1z := i1z - i3z; v2x := i2x - i3x; v2y := i2y - i3y; v2z := i2z - i3z; with landluminfo do begin rluma := v1y*v2z - v1z*v2y; rlumb := v1z*v2x - v1x*v2z; rlumc := v1x*v2y - v1y*v2x; rlumd := -rluma*i1x - rlumb*i1y - rlumc*i1z; end; end; begin with fExtraLandInfoBlocks[row, col] do begin rr := row shl cBlockBits; cc := col shl cBlockBits; new(fItems); for i := rr to rr + pred(cBlockSize) do for j := cc to cc + pred(cBlockSize) do CalcLandHeightInfo(i, j, fItems[i - rr, j - cc].heightinfo); if createluminfo then for i := rr to rr + pred(cBlockSize) do for j := cc to cc + pred(cBlockSize) do CalcLandLumInfo(i, j, fItems[i - rr, j - cc].luminfo); validlum := createluminfo; end; end; procedure TWorldMap.DestroyExtraLandInfoItems(row, col : integer); begin with fExtraLandInfoBlocks[row, col] do dispose(fItems); end; function TWorldMap.GetLandHeightInfo(i, j : integer; out heightinfo : TLandHeightInfo) : boolean; var row, col : integer; begin Result := (i >= 0) and (i < fRows) and (j >= 0) and (j < fColumns); if Result then begin fillchar(heightinfo, sizeof(heightinfo), 0); row := i shr cBlockBits; col := j shr cBlockBits; if fExtraLandInfoBlocks[row, col].fItems = nil then CreateExtraLandInfoItems(row, col, false); heightinfo := fExtraLandInfoBlocks[row, col].fItems[i and cBlockMask, j and cBlockMask].heightinfo; end; end; procedure TWorldMap.InitViewOrigin(const view : IGameView); var x, y : integer; size : TPoint; begin fConverter.MapToScreen(view, fRows div 2, fColumns div 2, x, y); size := view.GetSize; view.Origin := Point(x - size.x div 2, y - size.y div 2); end; // TGameFocus constructor TGameFocus.Create(Map : TWorldMap; const view : IGameView); begin inherited Create; fMap := Map; fView := view; fImager := nil; fZoomFactor := 2 shl fView.ZoomLevel / cBasicU; Map.fFocuses.Add(Self); end; destructor TGameFocus.Destroy; begin fMap.fFocuses.Remove(Self); inherited; end; function TGameFocus.Lock : integer; begin inc(fLockCount); Result := fLockCount; end; function TGameFocus.Unlock : integer; begin assert(fLockCount > 0); dec(fLockCount); if (fLockCount = 0) and fUpdateDefered then fView.QueryUpdate(false); Result := fLockCount; end; function TGameFocus.LockCount : integer; begin Result := fLockCount; end; procedure TGameFocus.QueryUpdate(Defer : boolean); begin if (fLockCount > 0) and Defer then fUpdateDefered := true else fView.QueryUpdate(false); end; procedure TGameFocus.MouseMove(x, y : integer); begin fMouseX := x; fMouseY := y; end; procedure TGameFocus.MouseClick; begin end; procedure TGameFocus.KeyPressed(which : word; const Shift : TShiftState); begin end; procedure TGameFocus.Refresh; begin end; function TGameFocus.GetText(kind : integer) : string; begin assert(kind = fkSelection); Result := Selection.Text; end; function TGameFocus.GetObject : TObject; begin Result := Self; end; function TGameFocus.GetRect : TRect; var org : TPoint; begin org := fView.Origin; Result := Selection.TextRect; if not IsRectEmpty(Result) then OffsetRect(Result, -org.x, -org.y); end; procedure TGameFocus.SetRect(const R : TRect); begin Selection.TextRect := R; end; function TGameFocus.GetImager : IImager; begin if fImager = nil then fImager := fMap.fImageCache.GetImager(fView); Result := fImager; end; procedure TGameFocus.ViewZoomed(var msg : TViewZoomedMsg); var ci, cj : integer; movetomsg : TMoveToMsg; begin fImager := nil; fMap.fConverter.ScreenToMap(fView, fView.Size.x div 2, fView.Size.y div 2, ci, cj); fView.ZoomLevel := msg.Zoom; fZoomFactor := 2 shl fView.ZoomLevel/cBasicU; movetomsg.id := msgMoveTo; movetomsg.i := ci; movetomsg.j := cj; Dispatch(movetomsg); end; procedure TGameFocus.MoveTo(var msg : TMoveToMsg); var x, y : integer; org : TPoint; size : TPoint; begin with msg do begin fMap.fConverter.MapToScreen(fView, i, j, x, y); org := fView.Origin; size := fView.GetSize; inc(org.x, x - size.x div 2); inc(org.y, y - size.y div 2); fView.Origin := org; end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpISecT283K1Curve; {$I ..\Include\CryptoLib.inc} interface uses ClpIECInterface; type ISecT283K1LookupTable = Interface(IECLookupTable) ['{3AF41553-A108-46D6-9CCC-AB1814A0A247}'] end; type ISecT283K1Curve = Interface(IAbstractF2mCurve) ['{1D88AF22-721F-4E89-82A2-1C1CFFB7830C}'] function GetM: Int32; property M: Int32 read GetM; function GetK1: Int32; property K1: Int32 read GetK1; function GetK2: Int32; property K2: Int32 read GetK2; function GetK3: Int32; property K3: Int32 read GetK3; function GetIsTrinomial: Boolean; property IsTrinomial: Boolean read GetIsTrinomial; end; implementation end.
unit Movie; interface uses Kernel, Surfaces, WorkCenterBlock, StdFluids, ServiceBlock, MediaGates, Protocol; const tidService_Movie = 'Movie'; const MovieAveragePrice = 5; //const //MoviePotencialClients : array[TPeopleKind] of integer = (90, 150, 250); type TMetaMovieBlock = class(TMetaServiceBlock) public constructor Create(anId : string; aCapacities : array of TFluidValue; aCustomerMax : TFluidValue; aPricePerc : TPercent; EvlBuyProb : array of TBuyProbability; aMaxAd : TFluidValue; aBlockClass : CBlock); end; TMovieBlock = class(TServiceBlock) protected function Evaluate : TEvaluationResult; override; public procedure AutoConnect(loaded : boolean); override; function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; procedure CopySettingsFrom(Block : TBlock; Options : integer); override; procedure EndOfPeriod(PeriodType : TPeriodType; PeriodCount : integer); override; protected fFilms : TInputData; fFilmsInput : TMediaInput; end; procedure RegisterBackup; implementation uses ClassStorage, PyramidalModifier, Classes, BackupInterfaces, Population, StdAccounts, MathUtils, MetaInstances, SimHints, CloneOptions; // TMetaMovieBlock constructor TMetaMovieBlock.Create(anId : string; aCapacities : array of TFluidValue; aCustomerMax : TFluidValue; aPricePerc : TPercent; EvlBuyProb : array of TBuyProbability; aMaxAd : TFluidValue; aBlockClass : CBlock); var Sample : TMovieBlock; Films : TFluidValue; begin inherited Create(anId, aCapacities, accIdx_Movie_Supplies, accIdx_Movie_Salaries, accIdx_Movie_Sales, aMaxAd, aBlockClass); Sample := nil; Films := 1; // Inputs MetaInputs.Insert( TMetaInput.Create( tidGate_Films, inputZero, InputData(Films, 100), inputZero, qIlimited, TMediaInput, //TPullInput, TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_Films]), 5, mglBasic, [mgoptCacheable, mgoptEditable], sizeof(Sample.fFilms), Sample.Offset(Sample.fFilms))); // Service: Movie with TMetaServiceEvaluator.Create( TMetaService(TheClassStorage.ClassById[tidClassFamily_Services, tidService_Movie]), 'Movie', aPricePerc, aCustomerMax, 100, EvlBuyProb) do begin RegisterInput( TMetaServiceEvaluatorInput.Create( InputByName[tidGate_Films], 1, 50)); Register(self); end; end; // TMovieBlock function TMovieBlock.Evaluate : TEvaluationResult; var upgrlv : byte; begin result := inherited Evaluate; upgrlv := max(1, UpgradeLevel); if fFilmsInput.ActualMaxFluid.Q > 0 then fFilmsInput.ActualMaxFluid.Q := upgrlv*fFilmsInput.MetaInput.MaxFluid.Q; fFilmsInput.LastExp := min(CustomerCount, round(upgrlv*TMetaMovieBlock(MetaBlock).Services[0].MaxServices)); end; procedure TMovieBlock.AutoConnect(loaded : boolean); begin inherited; fFilmsInput := TMediaInput(InputsByName[tidGate_Films]); end; function TMovieBlock.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; var titles : string; begin result := inherited GetStatusText(kind, ToTycoon); case kind of sttSecondary : if not Facility.CriticalTrouble // >> MLS2 then begin titles := fFilmsInput.Titles; if titles <> '' then result := result + ' ' + mtidNowPlaying.Values[ToTycoon.Language] + ' ' + titles; end; end; end; procedure TMovieBlock.CopySettingsFrom(Block : TBlock; Options : integer); begin inherited; if ObjectIs('TMovieBlock', Block) and (Options and cloneOption_Suppliers <> 0) then fFilmsInput.SortMode := TMovieBlock(Block).fFilmsInput.SortMode; end; procedure TMovieBlock.EndOfPeriod(PeriodType : TPeriodType; PeriodCount : integer); begin inherited; case PeriodType of perDay : if not fFilmsInput.Sorted then fFilmsInput.SortConnections; end; end; // Register backup procedure RegisterBackup; begin BackupInterfaces.RegisterClass(TMovieBlock); end; end.
unit ucFrmTile; interface uses uvMain, umTileData, uvITileView; type TRemoveTileProc = procedure (aTile : ITileView) of object; TFrmTileController<D : TTileDataModel> = class abstract protected fView: TFormMain; fRemoveTileProc : TRemoveTileProc; fTileViewFab : ITileViewFab; class var NameIndex : integer; procedure onTileCloseClick(Sender: ITileView); class function getNextNameIndex : integer; procedure ShowDataIntoFrame(aFrameTile : ITileView; aTileData : D); virtual; abstract; public constructor Create(aView: TFormMain; aTileViewFab : ITileViewFab); function makeFrameTile(aTileData : D) : ITileView; procedure TileClose(aFrameTile : ITileView); procedure InitTileDataModel(aTileData : D); virtual; abstract; property RemoveTileProc : TRemoveTileProc write fRemoveTileProc; end; implementation uses SysUtils, ExtCtrls; class function TFrmTileController<D>.getNextNameIndex : integer; begin inc(NameIndex); result := NameIndex; end; constructor TFrmTileController<D>.Create(aView: TFormMain; aTileViewFab : ITileViewFab); begin inherited Create; fView := aView; fTileViewFab := aTileViewFab; end; procedure TFrmTileController<D>.TileClose(aFrameTile : ITileView); begin if assigned(fRemoveTileProc) then fRemoveTileProc(aFrameTile); end; procedure TFrmTileController<D>.onTileCloseClick(Sender: ITileView); begin TileClose(Sender); end; function TFrmTileController<D>.makeFrameTile(aTileData : D) : ITileView; begin result := fTileViewFab.getTileViewInstance(fView, fView.pnlTiles); result.setTileData(aTileData); result.setOnCloseClick(onTileCloseClick); result.setControlName('FrameTile' + intToStr(TFrmTileController<D>.getNextNameIndex)); ShowDataIntoFrame(result, aTileData); end; end.
(* Usage ( *nix ): get: curl -i http://localhost:8080/api/person wget --quiet --server-response -O- http://localhost:8080/api/person * or point your browser to http://localhost:8080/api/person post: curl -i -d '{"Name":"bill"}' http://localhost:8080/api/person wget --quiet --server-response --post-data='{"Name":"bill"}' -O- http://localhost:8080/api/person * output of post method will be displayed in the stdout *) program ws001; uses heaptrc, Classes, JCoreDIC, JCoreWSIntf, JCoreWSRequest, JCoreWSCGIApp, JCoreWSHTTPServerApp; type { TPerson } TPerson = class(TPersistent) private FName: string; published property Name: string read FName write FName; end; { TPersonController } TPersonController = class(TPersistent) published function Get: TPerson; procedure Post(const APerson: TPerson); end; { TPersonController } function TPersonController.Get: TPerson; begin Result := TPerson.Create; Result.Name := 'jimmy'; end; procedure TPersonController.Post(const APerson: TPerson); begin // Comment out if using CGI-BIN application writeln('Person name: ', APerson.Name); end; var VRouter: IJCoreWSRequestRouter; VHandler: TJCoreWSRESTRequestHandler; VApp: IJCoreWSApplicationHandler; begin TJCoreDIC.Locate(IJCoreWSRequestRouter, VRouter); VHandler := TJCoreWSRESTRequestHandler.Create; VRouter.AddRequestHandler(VHandler, '/api'); VHandler.AddController(TPersonController). AddMethod(@TPersonController.Get, TypeInfo(@TPersonController.Get)). AddMethod(@TPersonController.Post, TypeInfo(@TPersonController.Post)); // Valid qualifiers are HTTP (embedded server) and CGI (cgi-bin application) // Comment out the writeln above if using CGI TJCoreDIC.Locate(IJCoreWSApplicationHandler, 'HTTP', VApp); VApp.Params.Values['Threaded'] := 'False'; VApp.Run; end.
unit K615679638; {* [Requestlink:615679638] } // Модуль: "w:\common\components\rtl\Garant\Daily\K615679638.pas" // Стереотип: "TestCase" // Элемент модели: "K615679638" MUID: (5694C6F30101) // Имя типа: "TK615679638" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK615679638 = class(TRTFtoEVDWriterTest) {* [Requestlink:615679638] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } function TreatExceptionAsSuccess: Boolean; override; end;//TK615679638 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *5694C6F30101impl_uses* //#UC END# *5694C6F30101impl_uses* ; function TK615679638.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK615679638.GetFolder function TK615679638.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '5694C6F30101'; end;//TK615679638.GetModelElementGUID function TK615679638.TreatExceptionAsSuccess: Boolean; //#UC START# *51406117007F_5694C6F30101_var* //#UC END# *51406117007F_5694C6F30101_var* begin //#UC START# *51406117007F_5694C6F30101_impl* Result := True; //#UC END# *51406117007F_5694C6F30101_impl* end;//TK615679638.TreatExceptionAsSuccess initialization TestFramework.RegisterTest(TK615679638.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit uChamadoVO; interface uses System.SysUtils, uChamadoStatusVO, System.Generics.Collections, uChamadoOcorrenciaVO, uChamadoColaboradorVO, uKeyField, uTableName; type [TableName('Chamado')] TChamadoVO = class private FIdStatus: Integer; FDescricao: string; FIdTipo: Integer; FHoraAtendeAtual: TTime; FIdModulo: Integer; FIdProduto: Integer; FId: Integer; FDataAbertura: TDate; FIdUsuarioAtendeAtual: Integer; FNivel: Integer; FContato: string; FHoraAbertura: TTime; FIdCliente: Integer; FTipoMovimento: Integer; FIdUsuarioAbertura: Integer; FListaStatus: TObjectList<TChamadoStatusVO>; FChamadoOcorrencia: TChamadoOcorrenciaVO; FListaChamadoOcorrencia: TObjectList<TChamadoOcorrenciaVO>; FChamadoStatusVO: TChamadoStatusVO; FListaChamadoColaborador: TObjectList<TChamadoColaboradorVO>; FOrigem: Integer; procedure SetContato(const Value: string); procedure SetDataAbertura(const Value: TDate); procedure SetDescricao(const Value: string); procedure SetHoraAbertura(const Value: TTime); procedure SetHoraAtendeAtual(const Value: TTime); procedure SetId(const Value: Integer); procedure SetIdCliente(const Value: Integer); procedure SetIdModulo(const Value: Integer); procedure SetIdProduto(const Value: Integer); procedure SetIdStatus(const Value: Integer); procedure SetIdTipo(const Value: Integer); procedure SetIdUsuarioAbertura(const Value: Integer); procedure SetIdUsuarioAtendeAtual(const Value: Integer); procedure SetNivel(const Value: Integer); procedure SetTipoMovimento(const Value: Integer); procedure SetListaStatus(const Value: TObjectList<TChamadoStatusVO>); procedure SetListaChamadoOcorrencia( const Value: TObjectList<TChamadoOcorrenciaVO>); procedure SetChamadoStatusVO(const Value: TChamadoStatusVO); procedure SetListaChamadoColaborador( const Value: TObjectList<TChamadoColaboradorVO>); procedure SetOrigem(const Value: Integer); public [KeyField('Cha_Id')] property Id: Integer read FId write SetId; [FieldDate('Cha_DataAbertura')] property DataAbertura: TDate read FDataAbertura write SetDataAbertura; [FieldTime('Cha_HoraAbertura')] property HoraAbertura: TTime read FHoraAbertura write SetHoraAbertura; [FieldName('Cha_Cliente')] property IdCliente: Integer read FIdCliente write SetIdCliente; [FieldName('Cha_UsuarioAbertura')] property IdUsuarioAbertura: Integer read FIdUsuarioAbertura write SetIdUsuarioAbertura; [FieldName('Cha_Contato')] property Contato: string read FContato write SetContato; [FieldName('Cha_Nivel')] property Nivel: Integer read FNivel write SetNivel; [FieldNull('Cha_Tipo')] property IdTipo: Integer read FIdTipo write SetIdTipo; [FieldNull('Cha_Status')] property IdStatus: Integer read FIdStatus write SetIdStatus; [FieldName('Cha_Descricao')] property Descricao: string read FDescricao write SetDescricao; [FieldNull('Cha_Modulo')] property IdModulo: Integer read FIdModulo write SetIdModulo; [FieldNull('Cha_Produto')] property IdProduto: Integer read FIdProduto write SetIdProduto; [FieldNull('Cha_UsuarioAtendeAtual')] property IdUsuarioAtendeAtual: Integer read FIdUsuarioAtendeAtual write SetIdUsuarioAtendeAtual; [FieldTime('Cha_HoraAtendeAtual')] property HoraAtendeAtual: TTime read FHoraAtendeAtual write SetHoraAtendeAtual; [FieldNull('Cha_TipoMovimento')] property TipoMovimento: Integer read FTipoMovimento write SetTipoMovimento; [FieldName('Cha_Origem')] property Origem: Integer read FOrigem write SetOrigem; property ListaStatus: TObjectList<TChamadoStatusVO> read FListaStatus write SetListaStatus; property ListaChamadoOcorrencia: TObjectList<TChamadoOcorrenciaVO> read FListaChamadoOcorrencia write SetListaChamadoOcorrencia; property ListaChamadoColaborador: TObjectList<TChamadoColaboradorVO> read FListaChamadoColaborador write SetListaChamadoColaborador; property ChamadoStatusVO: TChamadoStatusVO read FChamadoStatusVO write SetChamadoStatusVO; constructor Create; destructor Destroy; override; end; TListaChamado = TObjectList<TChamadoVO>; TRelChamadoVO = class private FRevendaCodigo: Integer; FRevendaNome: string; FClienteCodigo: Integer; FClienteNome: string; FQtdeDiasSemVisita: Integer; FQtdeDiasSemChamado: Integer; FDataUltChamado: string; FUsuNome: string; FUsuCodigo: Integer; FPerfil: string; FNomeCidade: string; public property RevendaCodigo: Integer read FRevendaCodigo write FRevendaCodigo; property RevendaNome: string read FRevendaNome write FRevendaNome; property ClienteCodigo: Integer read FClienteCodigo write FClienteCodigo; property ClienteNome: string read FClienteNome write FClienteNome; property UsuCodigo: Integer read FUsuCodigo write FUsuCodigo; property UsuNome: string read FUsuNome write FUsuNome; property QtdeDiasSemVisita: Integer read FQtdeDiasSemVisita write FQtdeDiasSemVisita; property QtdeDiasSemChamado: Integer read FQtdeDiasSemChamado write FQtdeDiasSemChamado; property DataUltChamado: string read FDataUltChamado write FDataUltChamado; property Perfil: string read FPerfil write FPerfil; property NomeCidade: string read FNomeCidade write FNomeCidade; end; TListaRelChamado = TObjectList<TRelChamadoVO>; implementation { TChamadoVO } constructor TChamadoVO.Create; begin inherited Create; FListaStatus := TObjectList<TChamadoStatusVO>.Create(); FListaChamadoOcorrencia := TObjectList<TChamadoOcorrenciaVO>.Create; FListaChamadoColaborador := TObjectList<TChamadoColaboradorVO>.Create(); FChamadoStatusVO := TChamadoStatusVO.Create; end; destructor TChamadoVO.Destroy; begin FreeAndNil(FListaStatus); FreeAndNil(FListaChamadoOcorrencia); FreeAndNil(FChamadoStatusVO); FreeAndNil(FListaChamadoColaborador); inherited; end; procedure TChamadoVO.SetChamadoStatusVO(const Value: TChamadoStatusVO); begin FChamadoStatusVO := Value; end; procedure TChamadoVO.SetContato(const Value: string); begin FContato := Value; end; procedure TChamadoVO.SetDataAbertura(const Value: TDate); begin FDataAbertura := Value; end; procedure TChamadoVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TChamadoVO.SetHoraAbertura(const Value: TTime); begin FHoraAbertura := Value; end; procedure TChamadoVO.SetHoraAtendeAtual(const Value: TTime); begin FHoraAtendeAtual := Value; end; procedure TChamadoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TChamadoVO.SetIdCliente(const Value: Integer); begin FIdCliente := Value; end; procedure TChamadoVO.SetIdModulo(const Value: Integer); begin FIdModulo := Value; end; procedure TChamadoVO.SetIdProduto(const Value: Integer); begin FIdProduto := Value; end; procedure TChamadoVO.SetIdStatus(const Value: Integer); begin FIdStatus := Value; end; procedure TChamadoVO.SetIdTipo(const Value: Integer); begin FIdTipo := Value; end; procedure TChamadoVO.SetIdUsuarioAbertura(const Value: Integer); begin FIdUsuarioAbertura := Value; end; procedure TChamadoVO.SetIdUsuarioAtendeAtual(const Value: Integer); begin FIdUsuarioAtendeAtual := Value; end; procedure TChamadoVO.SetListaChamadoColaborador( const Value: TObjectList<TChamadoColaboradorVO>); begin FListaChamadoColaborador := Value; end; procedure TChamadoVO.SetListaChamadoOcorrencia( const Value: TObjectList<TChamadoOcorrenciaVO>); begin FListaChamadoOcorrencia := Value; end; procedure TChamadoVO.SetListaStatus(const Value: TObjectList<TChamadoStatusVO>); begin FListaStatus := Value; end; procedure TChamadoVO.SetNivel(const Value: Integer); begin FNivel := Value; end; procedure TChamadoVO.SetOrigem(const Value: Integer); begin FOrigem := Value; end; procedure TChamadoVO.SetTipoMovimento(const Value: Integer); begin FTipoMovimento := Value; end; end.
unit ddAppConfigRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "dd$AppConfig" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/dd/ddAppConfigRes.pas" // Начат: 11.03.2010 18:41 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::dd$AppConfig::AppConfig::ddAppConfigRes // // Ресурсы для ddAppConfig // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface uses l3StringIDEx ; var { Локализуемые строки Local } str_ddmmSettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ddmmSettingsCaption'; rValue : 'Настройка конфигурации'); { 'Настройка конфигурации' } str_ddmmErrorCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ddmmErrorCaption'; rValue : 'Ошибка'); { 'Ошибка' } var { Локализуемые строки Errors } str_DifferentType : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DifferentType'; rValue : 'Тип свойства "%s" отличается от запрошенного'); { 'Тип свойства "%s" отличается от запрошенного' } str_PropertyAbsent : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PropertyAbsent'; rValue : 'Свойство "%s" отсутствует'); { 'Свойство "%s" отсутствует' } str_PropertyExists : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PropertyExists'; rValue : 'Свойство с именем "%s" уже существует'); { 'Свойство с именем "%s" уже существует' } str_ListEmpty : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEmpty'; rValue : 'Конфигурация пуста'); { 'Конфигурация пуста' } implementation uses l3MessageID ; initialization // Инициализация str_ddmmSettingsCaption str_ddmmSettingsCaption.Init; // Инициализация str_ddmmErrorCaption str_ddmmErrorCaption.Init; // Инициализация str_DifferentType str_DifferentType.Init; // Инициализация str_PropertyAbsent str_PropertyAbsent.Init; // Инициализация str_PropertyExists str_PropertyExists.Init; // Инициализация str_ListEmpty str_ListEmpty.Init; end.
unit GX_Backup; {$I GX_CondDefine.inc} interface uses Classes, Controls, Forms, ExtCtrls, Dialogs, StdCtrls, ToolsAPI, GX_Progress, GX_Experts, GX_ConfigurationInfo, GX_Zipper, AbArcTyp, AbUtils, GX_BaseForm, GX_GenericUtils; type TBackupExpert = class; TBackupType = (btFile, btDir); TBackupScope = (bsActiveProject, bsProjectGroup); TfmBackup = class(TfmBaseForm) pnlButtons: TPanel; pnlFiles: TPanel; gbxFiles: TGroupBox; pnlButtonsRight: TPanel; btnBackup: TButton; btnCancel: TButton; btnHelp: TButton; pnlFileList: TPanel; lbFiles: TListBox; pnlFileButtons: TPanel; pnlFileButtonsRight: TPanel; btnOptions: TButton; btnRemove: TButton; btnAdd: TButton; procedure btnBackupClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure btnOptionsClick(Sender: TObject); procedure lbFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FDoAbortCollectingFiles: Boolean; FHaveCollectedFiles: Boolean; FLastZipFile: string; FZipEncrypted: Boolean; FZipPassword: string; FProgressForm: TfmProgress; FCurrentBackupScope: TBackupScope; FBackupExpert: TBackupExpert; FLibraryPath: TStringList; FFilesFoundNowhere: TStringList; FZipComponent: TGXZipper; FFileSearchThreads: array of TFileFindThread; procedure AbbreviaProgress(Sender : TObject; Progress : Byte; var Abort : Boolean); procedure FileFailure(Sender: TObject; Item: TAbArchiveItem; ProcessType: TAbProcessType; ErrorClass: TAbErrorClass; ErrorCode: Integer); procedure AfterFileListChange; function ListFiles(const FileName, UnitName, FormName: string): Boolean; procedure LocateFileOnPathAndAdd(FilesNotFound: TStrings); procedure DoCollectFilesFromSingleProject(IProject: IOTAProject); procedure DoCollectFiles; procedure PerformBackup(const Path, FileName: string); procedure AddBackupFile(const FileName: string); procedure SaveSettings; procedure LoadSettings; procedure CollectFilesForBackup; procedure IncrementProgress; function ConfigurationKey: string; procedure lbFilesOnFilesDropped(_Sender: TObject; _Files: TStrings); procedure AddFilesInDirs(_Dirs: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TBackupExpert = class(TGX_Expert) private FFollowLibraryPath: Boolean; FBackupInc: Boolean; FBackupType: TBackupType; FBackupDir: string; FIncludeDir: Boolean; FBackupScope: TBackupScope; FAddDirsRecursively: Boolean; FIgnoreHistoryDir: Boolean; FIgnoreScmDirs: Boolean; FIgnoreBackupFiles: Boolean; protected procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public constructor Create; override; procedure Execute(Sender: TObject); override; procedure Configure; override; function GetActionCaption: string; override; class function GetName: string; override; property BackupDir: string read FBackupDir; property BackupScope: TBackupScope read FBackupScope; property BackupType: TBackupType read FBackupType; property DoBackupIncludedFiles: Boolean read FBackupInc; property DoIncludeDirInfoInZip: Boolean read FIncludeDir; property FollowLibraryPath: Boolean read FFollowLibraryPath; end; implementation {$R *.dfm} uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} Windows, SysUtils, AbConst, StrUtils, Math, GX_OtaUtils, GX_MacroParser, GX_GxUtils, GX_BackupOptions, GX_BackupConfig, GX_dzVclUtils, GX_MessageBox, GX_dzFileUtils; const // Do not localize these constants. ItemSeparatorChar = '|'; BackupIncludeDirective: array[0..8] of string = ( '{$I ', '{$INCLUDE ', '{$RESOURCE ', '{$R ', '{#BACKUP ', '(*$I ', '(*$INCLUDE ', '(*$RESOURCE ', '(*$R '); procedure AddFileToList(const FileSpec: string; List: TStrings); var StoreFileName: string; begin Assert(Assigned(List)); StoreFileName := Trim(FileSpec); if (StoreFileName <> '') and (List.IndexOf(FileSpec) = -1) then List.Add(FileSpec); end; procedure ScanForIncludesAndAdd(const FileName: string; FoundFileList, NotFoundFileList: TStrings); function GetIncludePrefix(const Line: string): string; var i: Integer; begin Result := ''; for i := Low(BackupIncludeDirective) to High(BackupIncludeDirective) do begin if CaseInsensitivePos(BackupIncludeDirective[i], Line) = 1 then begin Result := BackupIncludeDirective[i]; Break; end; end; end; procedure GetPasIncludeLines(FileLines: TStrings; IncludeLines: TStrings); var i: Integer; Line: string; IncludePrefix: string; FileSpec: string; CommentPos: Integer; begin Assert(Assigned(FileLines)); Assert(Assigned(IncludeLines)); IncludeLines.Clear; for i := 0 to FileLines.Count - 1 do begin Line := Trim(FileLines[i]); IncludePrefix := GetIncludePrefix(Line); if IncludePrefix <> '' then begin FileSpec := Trim(Copy(Line, Length(IncludePrefix) + 1, 9999)); CommentPos := Pos('//', FileSpec); if CommentPos > 1 then FileSpec := Copy(FileSpec, 1, CommentPos - 1); if FileSpec = '' then Continue; FileSpec := GetQuotedToken(FileSpec); if RightStr(FileSpec, 1) = '}' then FileSpec := Trim(Copy(FileSpec, 1, Length(FileSpec) - 1)); if RightStr(FileSpec, 2) = '*)' then FileSpec := Trim(Copy(FileSpec, 1, Length(FileSpec) - 2)); if FileSpec <> '' then IncludeLines.Add(FileSpec); end; end; end; procedure GetCppPragmaBackupLines(FileLines: TStrings; IncludeLines: TStrings); var i, j: Integer; Line: string; ParsedLine: string; PragmaBackup: string; FileSpec: string; SlashCommentActive: Boolean; StarCommentActive: Boolean; QuoteActive: Boolean; DoubleQuoteActive: Boolean; begin Assert(Assigned(FileLines)); Assert(Assigned(IncludeLines)); StarCommentActive := False; IncludeLines.Clear; for i := 0 to FileLines.Count - 1 do begin SlashCommentActive := False; QuoteActive := False; DoubleQuoteActive := False; Line := Trim(FileLines[i]); ParsedLine := ''; j := 1; while j <= Length(Line) do begin if QuoteActive then begin ParsedLine := ParsedLine + Line[j]; if (Line[j] = #39) and ((j = 1) or (Line[j - 1] <> '\')) then QuoteActive := False; end else if DoubleQuoteActive then begin ParsedLine := ParsedLine + Line[j]; if (Line[j] = '"') and ((j = 1) or (Line[j - 1] <> '\')) then DoubleQuoteActive := False; end else if StarCommentActive then begin if (Line[j] = '/') and (j > 1) and (Line[j - 1] = '*') then StarCommentActive := False; end else if not SlashCommentActive then begin case Line[j] of #39: begin QuoteActive := True; ParsedLine := ParsedLine + Line[j]; end; '"': begin DoubleQuoteActive := True; ParsedLine := ParsedLine + Line[j]; end; '/': if j <> Length(Line) then begin case Line[j + 1] of '*': begin StarCommentActive := True; Inc(j); end; '/': SlashCommentActive := True; else ParsedLine := ParsedLine + Line[j]; end end else ParsedLine := ParsedLine + Line[j]; else ParsedLine := ParsedLine + Line[j]; end; end; Inc(j); end; if (ParsedLine <> '') and (ParsedLine[1] = '#') then begin // This will break filenames with more than one consecutive space PragmaBackup := CompressWhiteSpace(Copy(ParsedLine, 2, MaxInt)); if StrBeginsWith('pragma backup ', PragmaBackup) then begin FileSpec := Trim(Copy(ParsedLine, Pos('backup', ParsedLine) + 6, MaxInt)); if FileSpec = '' then Continue; FileSpec := GetQuotedToken(FileSpec); if FileSpec <> '' then IncludeLines.Add(FileSpec); end; end; end; end; procedure TextFileToStrings(const FileName: string; Strings: TStringList); var AddString: string; begin Assert(Assigned(Strings)); Strings.Clear; try // Don't try to open files with wildcard specifications if not FileNameHasWildcards(FileName) then if FileExists(FileName) then Strings.LoadFromFile(FileName); except // This might be a lie since we might have found it, but since we can not // 'Open' it and 'Read' it it is better to let the user know it now via a message // than find out later when the zip component crashes or reports an error. AddString := FileName + ItemSeparatorChar + FileName; EnsureStringInList(NotFoundFileList, AddString); end; end; procedure AddFilesForInclude(const Line: string; const FileName: string); var StoreFileName: string; BaseFileName: string; CompareExt: string; begin StoreFileName := Trim(Line); if StoreFileName = '' then Exit; CompareExt := AnsiLowerCase(StoreFileName); if (CompareExt = '*.dfm') or (CompareExt = '*.xfm') or (CompareExt = '*.nfm') then Exit; // Included elsewhere if SameText(StoreFileName, '*.res') then StoreFileName := ChangeFileExt(FileName, '.res') else if SameText(StoreFileName, '*.dcr') then StoreFileName := ChangeFileExt(FileName, '.dcr'); BaseFileName := StoreFileName; StoreFileName := ExpandFileName(StoreFileName); if FileNameHasWildcards(StoreFileName) then begin { TODO -oAnyone -cFeature : Search for matching files here and add them to the list so the user can actually see what will be added. } AddFileToList(StoreFileName, FoundFileList); end else begin if FileExists(StoreFileName) then begin AddFileToList(StoreFileName, FoundFileList); if IsDprOrPas(StoreFileName) or IsCpp(StoreFileName) then ScanForIncludesAndAdd(StoreFileName, FoundFileList, NotFoundFileList); end else begin StoreFileName := BaseFileName + ItemSeparatorChar + FileName; AddFileToList(StoreFileName, NotFoundFileList); end; end; end; var CurrentLine: string; OriginalPath: string; CurrentLineNum: Integer; FileLines: TStringList; IncludeLines: TStringList; begin CurrentLine := ''; FileLines := nil; IncludeLines := nil; OriginalPath := GetCurrentDir; try // Changing directories allows ExpandFileName to work on relative paths if DirectoryExists(ExtractFilePath(FileName)) then SafeChangeDirectory(ExtractFilePath(FileName)); FileLines := TStringList.Create; IncludeLines := TStringList.Create; TextFileToStrings(FileName, FileLines); if IsDprOrPas(FileName) then GetPasIncludeLines(FileLines, IncludeLines) else if IsCpp(FileName) then GetCppPragmaBackupLines(FileLines, IncludeLines); for CurrentLineNum := 0 to IncludeLines.Count - 1 do AddFilesForInclude(IncludeLines[CurrentLineNum], FileName); finally FreeAndNil(FileLines); FreeAndNil(IncludeLines); SafeChangeDirectory(OriginalPath); end; end; { TfmBackup } function TfmBackup.ListFiles(const FileName, UnitName, FormName: string): Boolean; var TempFileName: string; begin Result := True; //{$IFOPT D+}SendDebug('Enumerating File: ' + FileName + ' Form: ' + FormName + ' Unit: ' + UnitName);{$ENDIF} // Do not backup DCP/BPI/DLL files TempFileName := ExtractUpperFileExt(FileName); if (TempFileName = '.DCP') or (TempFileName = '.BPI') or (TempFileName = '.DLL') or (TempFileName = '.AQT') then Exit; AddBackupFile(FileName); // Include matching header/bpr/bpk files for CPP files if (TempFileName = '.CPP') then begin AddBackupFile(ChangeFileExt(FileName, '.h')); // Do not localize. AddBackupFile(ChangeFileExt(FileName, '.bpr')); // Do not localize. AddBackupFile(ChangeFileExt(FileName, '.bpk')); // Do not localize. end; // Include all form files, if they exist, just to be safe AddBackupFile(ChangeFileExt(FileName, '.dfm')); // Do not localize. AddBackupFile(ChangeFileExt(FileName, '.xfm')); // Do not localize. AddBackupFile(ChangeFileExt(FileName, '.nfm')); // Do not localize. AddBackupFile(ChangeFileExt(FileName, '.fmx')); // Do not localize. AddBackupFile(ChangeFileExt(FileName, '.todo')); // Do not localize. if FBackupExpert.DoBackupIncludedFiles and (IsDprOrPas(FileName) or IsCpp(FileName)) then begin //{$IFOPT D+}SendDebug('Scanning: ' + FileName);{$ENDIF} ScanForIncludesAndAdd(FileName, lbFiles.Items, FFilesFoundNowhere); end; Result := not FDoAbortCollectingFiles; end; constructor TfmBackup.Create(AOwner: TComponent); begin inherited; FLibraryPath := TStringList.Create; FLibraryPath.Duplicates := dupIgnore; FFilesFoundNowhere := TStringList.Create; FZipEncrypted := False; FHaveCollectedFiles := False; TWinControl_ActivateDropFiles(lbFiles, lbFilesOnFilesDropped); LoadSettings; end; destructor TfmBackup.Destroy; var i: Integer; begin for i := Low(FFileSearchThreads) to High(FFileSearchThreads) do FFileSearchThreads[i].Free; SetLength(FFileSearchThreads, 0); FreeAndNil(FFilesFoundNowhere); FreeAndNil(FLibraryPath); inherited Destroy; end; procedure TfmBackup.LocateFileOnPathAndAdd(FilesNotFound: TStrings); var LastFileChecked: string; LastFileCheckResult: boolean; // Often the same file is included from several places, like the GX_CondDefine.inc // file in GExperts, which is included in >30 units. In that case it is listed in // FilesNotFound multiple times, but we don't need to check it for every entry // (accessing the hard disk is slow, even with caching). Here we simply cache the // result. On modern computers this doesn't make much of a difference (I benchmarked // it with 200000 duplictes where it as 4 seconds faster), but in virtual machines it will. function DoesFileExist(const Filename: string): boolean; begin if Filename <> LastFileChecked then begin LastFileCheckResult := FileExists(Filename); LastFileChecked := Filename; end; Result := LastFileCheckResult; end; procedure SplitUpEntry(const Entry: string; var IncludedFile, RefererFile: string); var SeparatorPos: Integer; begin SeparatorPos := Pos(ItemSeparatorChar, Entry); IncludedFile := Entry; if SeparatorPos > 0 then begin Delete(IncludedFile, SeparatorPos, Length(Entry)); RefererFile := Copy(Entry, SeparatorPos + 1, MaxInt); end else RefererFile := ''; end; var i, j: Integer; IncludedFile: string; RefererFile: string; FileLocation: string; begin // FilesNotFound is a list of files that have not been found, combined // with the filename which contained the reference to that file // Both parts are separated by the ItemSeparatorChar character ('|') // This routine scans the library path for the presence of files; // if a file is found, it is removed from the list of files not found // and adds it to the list(box) of files to be backed up. // Finally the list of *really* not found files is beautified. {$IFOPT D+} if FilesNotFound.Count > 0 then SendDebugError('+++ Files not found:'); for i := 0 to FilesNotFound.Count - 1 do SendDebugError(FilesNotFound[i]); {$ENDIF D+} // Scan each directory on the library path whether // it contains any of the missing files. // Scan one directory completely before progressing // to the next to give the operating system's file cache // an easier job of reading the directory structure; // this should perform better than iterating over all files // and for each file trying to find the containing directory. LastFileChecked := ''; for i := 0 to FLibraryPath.Count - 1 do begin j := FilesNotFound.Count - 1; while j >= 0 do begin SplitUpEntry(FilesNotFound[j], IncludedFile, RefererFile); FileLocation := FLibraryPath[i] + IncludedFile; if DoesFileExist(FileLocation) then begin FilesNotFound.Delete(j); if lbFiles.Items.IndexOf(FileLocation) < 0 then AddBackupFile(FileLocation); end; Dec(j); end; end; // Finally post-process the list of *really* not found files // and give the list a pretty format now. for j := 0 to FilesNotFound.Count - 1 do begin SplitUpEntry(FilesNotFound[j], IncludedFile, RefererFile); FilesNotFound[j] := Format('%s (%s)', [IncludedFile, RefererFile]); end; end; procedure TfmBackup.DoCollectFiles; var ProjectGroupFileName: string; IProjectGroup: IOTAProjectGroup; i: Integer; begin if FCurrentBackupScope = bsActiveProject then DoCollectFilesFromSingleProject(GxOtaGetCurrentProject) else begin // First find the currently active project group. IProjectGroup := GxOtaGetProjectGroup; if IProjectGroup = nil then Exit; ProjectGroupFileName := GxOtaGetProjectGroupFileName; AddBackupFile(ProjectGroupFileName); for i := 0 to IProjectGroup.ProjectCount - 1 do DoCollectFilesFromSingleProject(IProjectGroup.Projects[i]); end; end; procedure TfmBackup.DoCollectFilesFromSingleProject(IProject: IOTAProject); var i: Integer; IModuleInfo: IOTAModuleInfo; IEditor: IOTAEditor; FileName: string; begin if IProject = nil then Exit; Assert(Assigned(FProgressForm)); GxOtaGetEffectiveLibraryPath(FLibraryPath, IProject); // Gather project files for i := 0 to IProject.GetModuleFileCount - 1 do begin IEditor := IProject.GetModuleFileEditor(i); Assert(IEditor <> nil); FileName := IEditor.FileName; if FileName <> '' then ListFiles(IEditor.FileName, '', ''); end; // Delphi 8 project files have ModuleFileCount=0 ListFiles(IProject.FileName, '', ''); for i := 0 to IProject.GetModuleCount - 1 do begin IModuleInfo := IProject.GetModule(i); Assert(IModuleInfo <> nil); FileName := IModuleInfo.FileName; if FileName <> '' then ListFiles(IModuleInfo.FileName, '', IModuleInfo.FormName); end; end; procedure TfmBackup.CollectFilesForBackup; resourcestring SCollectingBackupFiles = 'Collecting Files...'; SFilesNotFound = 'The following included files could not be found for backup:' + sLineBreak + sLineBreak + '%s'; begin lbFiles.Clear; FFilesFoundNowhere.Clear; Assert(FProgressForm = nil); FProgressForm := TfmProgress.Create(nil); try FProgressForm.Caption := SCollectingBackupFiles; Self.Enabled := False; FProgressForm.Show; FProgressForm.Progress.Max := 40; FDoAbortCollectingFiles := False; Screen.Cursor := crHourglass; lbFiles.Items.BeginUpdate; try DoCollectFiles; finally lbFiles.Sorted := True; lbFiles.Items.EndUpdate; Screen.Cursor := crDefault; end; if FBackupExpert.FBackupInc then begin // The "FFilesFoundNowhere" list now contains everything that could not be // found scanning the source text. Process now the path in order to // possibly find items there. // "LocateFileOnPathAndAdd" will remove the files that it finds; // after returning, the list will contain those files that *really* // could not be found, not even on the library path. if FBackupExpert.FollowLibraryPath and (FFilesFoundNowhere.Count > 0) then LocateFileOnPathAndAdd(FFilesFoundNowhere); FFilesFoundNowhere.Text := StringReplace(FFilesFoundNowhere.Text, '|', ' from ', [rfReplaceAll]); FFilesFoundNowhere.Sort; Self.Enabled := True; FreeAndNil(FProgressForm); if FFilesFoundNowhere.Count > 0 then MessageDlg(Format(SFilesNotFound, [FFilesFoundNowhere.Text]), mtWarning, [mbOK], 0); end; finally Self.Enabled := True; FreeAndNil(FProgressForm); end; AfterFileListChange; end; procedure TfmBackup.PerformBackup(const Path, FileName: string); var Cursor: IInterface; DestFile: string; begin Assert(FProgressForm = nil); FZipComponent := nil; FProgressForm := TfmProgress.Create(nil); try DestFile := Path + FileName; FZipComponent := TGXZipper.Create(DestFile, fmCreate or fmShareDenyWrite); Cursor := TempHourGlassCursor; FProgressForm.Progress.Position := 0; Self.Enabled := False; FProgressForm.Show; Application.ProcessMessages; FProgressForm.Progress.Max := 100; FZipComponent.IncludePath := FBackupExpert.DoIncludeDirInfoInZip; if FZipEncrypted then FZipComponent.Password := AnsiString(FZipPassword); FZipComponent.OnProcessItemFailure := FileFailure; FZipComponent.OnArchiveProgress := AbbreviaProgress; FZipComponent.AddFiles(lbFiles.Items); FZipComponent.Save; finally Self.Enabled := True; FreeAndNil(FProgressForm); FreeAndNil(FZipComponent); end; end; procedure TfmBackup.btnBackupClick(Sender: TObject); resourcestring SFileExists = 'File %s already exists, do you want to overwrite this file?'; SDirectoryDoesNotExist = 'Directory %s does not exist, do you want to create this directory?'; const ZipExtension = '.zip'; // Do not localize. var CurrentZipFileName: string; ZipFilePath: string; i: Integer; begin if FBackupExpert.BackupType = btFile then begin CurrentZipFileName := FLastZipFile; if not ShowSaveDialog('Backup As', 'zip', CurrentZipFileName) then Exit; if ExtractFileExt(CurrentZipFileName) = '' then CurrentZipFileName := CurrentZipFileName + ZipExtension; if FileExists(CurrentZipFileName) then begin if MessageDlg(Format(SFileExists, [CurrentZipFileName]), mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin Exit; end; DeleteFile(CurrentZipFileName); end; end else begin CurrentZipFileName := ReplaceStrings(FBackupExpert.BackupDir, True); CurrentZipFileName := TFileSystem.MakeValidFilename(CurrentZipFileName); ZipFilePath := ExtractFilePath(CurrentZipFileName); CurrentZipFileName := ExtractFileName(CurrentZipFileName); if not DirectoryExists(ZipFilePath) then begin if MessageDlg(Format(SDirectoryDoesNotExist, [ZipFilePath]), mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin Exit; end else ForceDirectories(ZipFilePath); end; if ExtractUpperFileExt(CurrentZipFileName) = '.ZIP' then CurrentZipFileName := ChangeFileExt(CurrentZipFileName, ''); if FileExists(ZipFilePath + CurrentZipFileName + ZipExtension) then begin i := 1; while i < 999 do begin if not FileExists(ZipFilePath + CurrentZipFileName + IntToStr(i) + ZipExtension) then begin CurrentZipFileName := CurrentZipFileName + IntToStr(i) + ZipExtension; Break; end; Inc(i); end; end else CurrentZipFileName := CurrentZipFileName + ZipExtension; end; PerformBackup(ZipFilePath, CurrentZipFileName); FLastZipFile := CurrentZipFileName; SaveSettings; ModalResult := mrOk; end; procedure TfmBackup.btnAddClick(Sender: TObject); var i: Integer; Files: TStrings; begin Files := TStringList.Create; try if ShowOpenDialog('Add to Backup', '', Files, 'Delphi Files (*.pas;*.dfm;*.xfm;*.dpr;*.dpk;*.bpg;*.res)|*.pas;*.dfm;*.xfm;*.dpr;*.dpk;*.bpg;*.res') then for i := 0 to Files.Count - 1 do AddBackupFile(Files[i]); AfterFileListChange; finally FreeAndNil(Files); end; end; procedure TfmBackup.btnRemoveClick(Sender: TObject); var i: Integer; OldIndex: Integer; begin i := 0; OldIndex := lbFiles.ItemIndex; while i <= lbFiles.Items.Count - 1 do begin if lbFiles.Selected[i] then lbFiles.Items.Delete(i) else Inc(i); end; OldIndex := Min(OldIndex, lbFiles.Items.Count - 1); if OldIndex > -1 then begin lbFiles.ItemIndex := OldIndex; lbFiles.Selected[OldIndex] := True; end; AfterFileListChange; end; procedure TfmBackup.FormDestroy(Sender: TObject); begin // Aborting isn't actually possible with our current design FDoAbortCollectingFiles := True; end; procedure TfmBackup.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 10); end; procedure TfmBackup.FormActivate(Sender: TObject); begin if not FHaveCollectedFiles then begin FHaveCollectedFiles := True; CollectFilesForBackup; end; end; procedure TfmBackup.btnOptionsClick(Sender: TObject); var Dlg: TfmBackupOptions; RefreshRequired: Boolean; begin Dlg := TfmBackupOptions.Create(nil); try Dlg.cbPassword.Checked := FZipEncrypted; Dlg.edPassword.Text := FZipPassword; Dlg.cbSearchLibraryPath.Checked := FBackupExpert.FollowLibraryPath; Dlg.rgScope.ItemIndex := Ord(FCurrentBackupScope); pnlButtons.Enabled := False; pnlFiles.Enabled := False; if Dlg.ShowModal = mrOk then begin FZipPassword := Dlg.edPassword.Text; FZipEncrypted := Dlg.cbPassword.Checked; RefreshRequired := not (FCurrentBackupScope = TBackupScope(Dlg.rgScope.ItemIndex)); FCurrentBackupScope := TBackupScope(Dlg.rgScope.ItemIndex); RefreshRequired := RefreshRequired or (not (FBackupExpert.FFollowLibraryPath = Dlg.cbSearchLibraryPath.Checked)); FBackupExpert.FFollowLibraryPath := Dlg.cbSearchLibraryPath.Checked; if RefreshRequired then CollectFilesForBackup; end; finally pnlButtons.Enabled := True; pnlFiles.Enabled := True; FreeAndNil(Dlg); end; end; type TGxContainsDirectoriesRecursiveMessage = class(TGxMsgBoxAdaptor) protected function GetMessage: string; override; function GetButtons: TMsgDlgButtons; override; function GetDefaultButton: TMsgDlgBtn; override; end; { TGxContainsDirectoriesRecursiveMessage } function TGxContainsDirectoriesRecursiveMessage.GetButtons: TMsgDlgButtons; begin Result := [mbYes, mbNo, mbCancel]; end; function TGxContainsDirectoriesRecursiveMessage.GetDefaultButton: TMsgDlgBtn; begin Result := mbCancel; end; function TGxContainsDirectoriesRecursiveMessage.GetMessage: string; resourcestring SDroppedFilesContainedDirectories = 'The files you dropped contained at least one directory. ' + 'Do you want to recursively add all files within these directories?'; begin Result := SDroppedFilesContainedDirectories + #13#10 + FData; end; type TGxContainsDirectoriesMessage = class(TGxMsgBoxAdaptor) protected function GetMessage: string; override; function GetButtons: TMsgDlgButtons; override; function GetDefaultButton: TMsgDlgBtn; override; end; { TGxContainsDirectoriesMessage } function TGxContainsDirectoriesMessage.GetButtons: TMsgDlgButtons; begin Result := [mbYes, mbNo, mbCancel]; end; function TGxContainsDirectoriesMessage.GetDefaultButton: TMsgDlgBtn; begin Result := mbCancel; end; function TGxContainsDirectoriesMessage.GetMessage: string; resourcestring SDroppedFilesContainedDirectories = 'The files you dropped contained at least one directory. ' + 'Do you want to add all files within these directories?'; begin Result := SDroppedFilesContainedDirectories + #13#10 + FData; end; type TExtFindFileThread = class(TFileFindThread) private FListBox: TListBox; FIgnoreBackupFiles: Boolean; public constructor Create(_ListBox: TListBox; _IgnoreBackupFiles: boolean); // This method is called in the main thread using synchronize, so access to the // VCL is allowed. procedure SyncFindComplete; end; { TExtFindFileThread } constructor TExtFindFileThread.Create(_ListBox: TListBox; _IgnoreBackupFiles: boolean); begin inherited Create; FListBox := _ListBox; FIgnoreBackupFiles := _IgnoreBackupFiles; end; procedure TExtFindFileThread.SyncFindComplete; function IsBackupFile(const Filename: string): boolean; var Ext: string; begin Ext := ExtractFileExt(Filename); Result := (Copy(Ext, 1, 2) = '.~') or (Copy(Ext, Length(Ext), 1) = '~'); end; var i: Integer; fn: string; sl: TStringList; Idx: Integer; begin LockResults; try FListBox.Items.BeginUpdate; sl := TStringList.Create; try sl.Sorted := True; sl.Duplicates := dupIgnore; sl.Assign(FListBox.Items); for i := 0 to Results.Count - 1 do begin fn := Results[i]; if not DirectoryExists(fn) then if (not FIgnoreBackupFiles or not IsBackupFile(fn)) then if not sl.Find(fn, Idx) then sl.Add(fn); end; FListBox.Items.Assign(sl); finally FreeAndNil(sl); FListBox.Items.EndUpdate; end; finally ReleaseResults; end; end; procedure TfmBackup.AddFilesInDirs(_Dirs: TStrings); var DirThread: TExtFindFileThread; Idx: Integer; begin DirThread := TExtFindFileThread.Create(lbFiles, FBackupExpert.FIgnoreBackupFiles); try DirThread.FileMasks.Add(AllFilesWildCard); if FBackupExpert.FAddDirsRecursively and FBackupExpert.FIgnoreHistoryDir then DirThread.AddDelphiDirsToIgnore; if FBackupExpert.FAddDirsRecursively and FBackupExpert.FIgnoreScmDirs then DirThread.AddSCMDirsToIgnore; if FBackupExpert.FAddDirsRecursively then DirThread.RecursiveSearchDirs.AddStrings(_Dirs) else DirThread.SearchDirs.AddStrings(_Dirs); DirThread.OnFindComplete := DirThread.SyncFindComplete; DirThread.StartFind; Idx := Length(FFileSearchThreads); SetLength(FFileSearchThreads, Idx + 1); FFileSearchThreads[Idx] := DirThread; DirThread := nil; finally FreeAndNil(DirThread); end; end; procedure TfmBackup.lbFilesOnFilesDropped(_Sender: TObject; _Files: TStrings); var i: Integer; fn: string; Dirs: TStringList; begin Dirs := TStringList.Create; try for i := _Files.Count - 1 downto 0 do begin fn := _Files[i]; if DirectoryExists(fn) then begin Dirs.Add(fn); _Files.Delete(i); end; end; if Dirs.Count > 0 then begin if FBackupExpert.FAddDirsRecursively then begin case ShowGxMessageBox(TGxContainsDirectoriesRecursiveMessage, Dirs.Text) of mrYes: begin AddFilesInDirs(Dirs); end; mrNo: begin // nothing to do, we already removed the directories from _Files end else // mrCancel Exit; end; end else begin case ShowGxMessageBox(TGxContainsDirectoriesMessage, Dirs.Text) of mrYes: begin AddFilesInDirs(Dirs); end; mrNo: begin // nothing to do, we already removed the directories from _Files end else // mrCancel Exit; end; end; end; finally FreeAndNil(Dirs); end; for i := 0 to _Files.Count - 1 do begin lbFiles.Items.Add(_Files[i]); end; AfterFileListChange; end; procedure TfmBackup.lbFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DELETE) and (lbFiles.ItemIndex > -1) then begin btnRemove.Click; Key := 0; end; end; // Check for duplicates before adding files to the the backup list // Prevents adding files twice when units are in two projects of a group procedure TfmBackup.AddBackupFile(const FileName: string); begin IncrementProgress; if lbFiles.Items.IndexOf(FileName) = -1 then // Should be case sensitive in Kylix if FileExists(FileName) then lbFiles.Items.Add(FileName); end; procedure TfmBackup.AfterFileListChange; resourcestring SBackupFormCaptionUnknown = 'Backup Project (%d+ Files)'; SBackupFormCaptionPlural = 'Backup Project (%d Files)'; SBackupFormCaptionSingular = 'Backup Project (1 File)'; var NonWildcardFileCount: Integer; i: Integer; begin ListboxHorizontalScrollbar(lbFiles); NonWildcardFileCount := 0; for i := 0 to lbFiles.Items.Count - 1 do begin if not FileNameHasWildcards(lbFiles.Items[i]) then Inc(NonWildcardFileCount); end; if NonWildcardFileCount < lbFiles.Items.Count then Caption := Format(SBackupFormCaptionUnknown, [NonWildcardFileCount]) else if NonWildcardFileCount = 1 then Caption := SBackupFormCaptionSingular else Caption := Format(SBackupFormCaptionPlural, [NonWildcardFileCount]); btnBackup.Enabled := (lbFiles.Items.Count > 0); end; procedure TfmBackup.SaveSettings; var Settings: TGExpertsSettings; begin // Do not localize. Settings := TGExpertsSettings.Create; try Settings.SaveForm(Self, ConfigurationKey + '\Window'); Settings.WriteString(ConfigurationKey, 'LastZipDir', ExtractFilePath(FLastZipFile)); finally FreeAndNil(Settings); end; end; procedure TfmBackup.LoadSettings; var Settings: TGExpertsSettings; fn: string; begin // Do not localize. Settings := TGExpertsSettings.Create; try Settings.LoadForm(Self, ConfigurationKey + '\Window'); if FCurrentBackupScope = bsActiveProject then fn := ChangeFileExt(ExtractFileName(GxOtaGetCurrentProjectFileName), '') else fn := ChangeFileExt(ExtractFileName(GxOtaGetProjectGroupFileName), ''); FLastZipFile := Settings.ReadString(ConfigurationKey, 'LastZipDir', ''); if FLastZipFile <> '' then FLastZipFile := IncludeTrailingPathDelimiter(FLastZipFile) + fn else FLastZipFile := fn; finally FreeAndNil(Settings); end; EnsureFormVisible(Self); end; procedure TfmBackup.IncrementProgress; begin if not Assigned(FProgressForm) then Exit; with FProgressForm.Progress do if Position = Max then Position := 0 else Position := Position + 1; end; function TfmBackup.ConfigurationKey: string; begin Result := TBackupExpert.ConfigurationKey; end; procedure TfmBackup.FileFailure(Sender: TObject; Item: TAbArchiveItem; ProcessType: TAbProcessType; ErrorClass: TAbErrorClass; ErrorCode: Integer); var Msg: string; begin Msg := ''; if ExceptObject is Exception then Msg := Exception(ExceptObject).Message; case ErrorClass of ecAbbrevia: begin if ErrorCode = AbDuplicateName then Exit else Msg := AbStrRes(ErrorCode) + ' ' + Msg; end; ecInOutError: Msg := Format('EInOutError (%d)', [ErrorCode]) + ' ' + Msg; ecFilerError: Msg := 'EFilerError' + ' ' + Msg; ecFileCreateError: Msg := 'EFCreateError' + ' ' + Msg; ecFileOpenError: Msg := 'EFOpenError' + ' ' + Msg; end; Msg := Trim(Msg); MessageDlg('Error processing file: ' + Item.FileName + ' ' + Msg, mtError, [mbOK], 0); end; procedure TfmBackup.AbbreviaProgress(Sender: TObject; Progress: Byte; var Abort: Boolean); begin FProgressForm.Progress.Position := Progress; end; { TBackupExpert } constructor TBackupExpert.Create; begin inherited Create; FBackupType := btFile; FBackupDir := AddSlash('%PROJECTDIR%') + '%PROJECTNAME%'; // Do not localize. FIncludeDir := True; FBackupScope := bsActiveProject; FAddDirsRecursively := True; FIgnoreHistoryDir := True; FIgnoreScmDirs := True; FIgnoreBackupFiles := True; end; function TBackupExpert.GetActionCaption: string; resourcestring SMenuCaption = '&Backup Project...'; begin Result := SMenuCaption; end; class function TBackupExpert.GetName: string; begin Result := 'BackupProject'; // Do not localize. end; procedure TBackupExpert.Execute(Sender: TObject); var Dlg: TfmBackup; begin Dlg := TfmBackup.Create(nil); try SetFormIcon(Dlg); Dlg.FBackupExpert := Self; Dlg.FCurrentBackupScope := BackupScope; Dlg.ShowModal; finally FreeAndNil(Dlg); end; end; procedure TBackupExpert.Configure; var Dlg: TfmBackupConfig; begin Dlg := TfmBackupConfig.Create(nil); try Dlg.cbBackupInc.Checked := FBackupInc; Dlg.cbIncludeDir.Checked := FIncludeDir; Dlg.rbBackupAskForFile.Checked := (FBackupType = btFile); Dlg.rbBackupToDirectory.Checked := (FBackupType = btDir); Dlg.edBackupDir.Text := FBackupDir; Dlg.rgDefaultScope.ItemIndex := Ord(FBackupScope); Dlg.cbSearchOnLibraryPath.Checked := FFollowLibraryPath; Dlg.cbAddRecursively.Checked := FAddDirsRecursively; Dlg.cbIgnoreHistoryDir.Checked := FIgnoreHistoryDir; Dlg.cbIgnoreScmDirs.Checked := FIgnoreScmDirs; Dlg.cbIgnoreBackupFiles.Checked := FIgnoreBackupFiles; if Dlg.ShowModal = mrOk then begin if Dlg.rbBackupAskForFile.Checked then FBackupType := btFile else FBackupType := btDir; FBackupDir := Dlg.edBackupDir.Text; FBackupInc := Dlg.cbBackupInc.Checked; FIncludeDir := Dlg.cbIncludeDir.Checked; FBackupScope := TBackupScope(Dlg.rgDefaultScope.ItemIndex); FFollowLibraryPath := Dlg.cbSearchOnLibraryPath.Checked; FAddDirsRecursively := Dlg.cbAddRecursively.Checked; FIgnoreHistoryDir := Dlg.cbIgnoreHistoryDir.Checked; FIgnoreScmDirs := Dlg.cbIgnoreScmDirs.Checked; FIgnoreBackupFiles := Dlg.cbIgnoreBackupFiles.Checked; end; finally FreeAndNil(Dlg); end; end; procedure TBackupExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); // Do not localize any of the following lines. Settings.WriteBool('Include', FBackupInc); Settings.WriteEnumerated('Type', TypeInfo(TBackupType), Ord(FBackupType)); Settings.WriteString('Directory', FBackupDir); Settings.WriteBool('IncludeDir', FIncludeDir); Settings.WriteEnumerated('BackupScope', TypeInfo(TBackupScope), Ord(FBackupScope)); Settings.WriteBool('FollowLibraryPath', FFollowLibraryPath); Settings.WriteBool('AddDirsRecursively', FAddDirsRecursively); Settings.WriteBool('IgnoreHistoryDir', FIgnoreHistoryDir); Settings.WriteBool('IgnoreScmDirs', FIgnoreScmDirs); Settings.WriteBool('IgnoreBackupFiles', FIgnoreBackupFiles); end; procedure TBackupExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited InternalLoadSettings(Settings); // Do not localize any of the following lines. FBackupInc := Settings.ReadBool('Include', FBackupInc); FBackupType := TBackupType(Settings.ReadEnumerated('Type', TypeInfo(TBackupType), Ord(FBackupType))); FBackupDir := Settings.ReadString('Directory', FBackupDir); FIncludeDir := Settings.ReadBool('IncludeDir', FIncludeDir); FBackupScope := TBackupScope(Settings.ReadEnumerated('BackupScope', TypeInfo(TBackupScope), Ord(FBackupScope))); FFollowLibraryPath := Settings.ReadBool('FollowLibraryPath', FFollowLibraryPath); FAddDirsRecursively := Settings.ReadBool('AddDirsRecursively', FAddDirsRecursively); FIgnoreHistoryDir := Settings.ReadBool('IgnoreHistoryDir', FIgnoreHistoryDir); FIgnoreScmDirs := Settings.ReadBool('IgnoreScmDirs', FIgnoreScmDirs); FIgnoreBackupFiles := Settings.ReadBool('IgnoreBackupFiles', FIgnoreBackupFiles); end; initialization RegisterGX_Expert(TBackupExpert); end.
unit ZMEOC19; (* ZMEOC19.pas - EOC handling Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip modified 2010-05-12 ---------------------------------------------------------------------------*) interface uses Classes, ZipMstr19, ZMStructs19, ZMWorkFile19, ZMCompat19, ZMCore19; type TZMEOC = class(TZMWorkFile) private fCentralDiskNo: Integer; fCentralEntries: Cardinal; fCentralOffset: Int64; fCentralSize: Int64; fEOCOffset: Int64; fMultiDisk: Boolean; fOffsetDelta: Int64; fTotalEntries: Cardinal; fVersionMadeBy: Word; fVersionNeeded: Word; fZ64: Boolean; fZ64VSize: Int64; FZipComment: AnsiString; function GetEOC64(Ret: Integer): Integer; function GetZipCommentLen: Integer; procedure SetZipComment(const Value: AnsiString); procedure SetZipCommentLen(const Value: Integer); protected function OpenEOC1: Integer; public constructor Create(Mstr: TZMCore); override; procedure AfterConstruction; override; procedure AssignFrom(Src: TZMWorkFile); override; function OpenEOC(EOConly: boolean): Integer; function OpenLast(EOConly: boolean; OpenRes: Integer): integer; function WriteEOC: Integer; property CentralDiskNo: Integer read fCentralDiskNo write fCentralDiskNo; property CentralEntries: Cardinal read fCentralEntries write fCentralEntries; property CentralOffset: Int64 read fCentralOffset write fCentralOffset; property CentralSize: Int64 read fCentralSize write fCentralSize; property EOCOffset: Int64 read fEOCOffset write fEOCOffset; property MultiDisk: Boolean read fMultiDisk write fMultiDisk; property OffsetDelta: Int64 read fOffsetDelta write fOffsetDelta; property TotalEntries: Cardinal read fTotalEntries write fTotalEntries; property VersionMadeBy: Word read fVersionMadeBy write fVersionMadeBy; property VersionNeeded: Word read fVersionNeeded write fVersionNeeded; property Z64: Boolean read fZ64 write fZ64; property Z64VSize: Int64 read fZ64VSize write fZ64VSize; property ZipComment: AnsiString read FZipComment write SetZipComment; property ZipCommentLen: Integer read GetZipCommentLen write SetZipCommentLen; end; { TZMEOC } const zfi_EOC: cardinal = $800; // valid EOC found const EOCBadStruct = 2; EOCBadComment = 1; EOCWant64 = 64; implementation uses Windows, SysUtils, ZMXcpt19, ZMMsg19, ZMUtils19; function NameOfPart(const fn: String; Compat: Boolean): String; var r, n: Integer; SRec: TSearchRec; fs: String; begin Result := ''; if Compat then fs := fn + '.z??*' else fs := fn + '???.zip'; r := FindFirst(fs, faAnyFile, SRec); while r = 0 do begin if Compat then begin fs := UpperCase(Copy(ExtractFileExt(SRec.Name), 3, 20)); if fs = 'IP' then n := 99999 else n := StrToIntDef(fs, 0); end else n := StrToIntDef(Copy(SRec.Name, Length(SRec.Name) - 6, 3), 0); if n > 0 then begin Result := SRec.Name; // possible name break; end; r := FindNext(SRec); end; SysUtils.FindClose(SRec); end; {TZMEOC} constructor TZMEOC.Create(Mstr: TZMCore); begin inherited Create(Mstr); end; procedure TZMEOC.AfterConstruction; begin inherited; fMultiDisk := false; fEOCOffset := 0; fZipComment := ''; end; procedure TZMEOC.AssignFrom(Src: TZMWorkFile); var theSrc: TZMEOC; begin inherited; if (Src is TZMEOC) and (Src <> Self) then begin theSrc := TZMEOC(Src); fCentralDiskNo := theSrc.fCentralDiskNo; fCentralEntries := theSrc.fCentralEntries; fCentralOffset := theSrc.fCentralOffset; fCentralSize := theSrc.fCentralSize; fEOCOffset := theSrc.fEOCOffset; fMultiDisk := theSrc.fMultiDisk; fOffsetDelta := theSrc.fOffsetDelta; fTotalEntries := theSrc.fTotalEntries; fVersionMadeBy := theSrc.fVersionMadeBy; fVersionNeeded := theSrc.fVersionNeeded; fZ64 := theSrc.fZ64; fZ64VSize := theSrc.fZ64VSize; FZipComment := theSrc.FZipComment; end; end; function TZMEOC.GetEOC64(Ret: Integer): Integer; var posn: Int64; Loc: TZip64EOCLocator; eoc64: TZipEOC64; CEnd: Int64; // end of central directory function IsLocator(Locp: PZip64EOCLocator): boolean; begin Result := false; if (Locp^.LocSig <> EOC64LocatorSig) then exit; if (DiskNr = MAX_WORD) and (Locp^.NumberDisks < MAX_WORD) then exit; Result := true; end; begin Result := Ret; if (Result <= 0) or ((Result and EOCWant64) = 0) then exit; CEnd := EOCOffset; posn := EOCOffset - sizeof(TZip64EOCLocator); if posn >= 0 then begin if Seek(posn, 0) < 0 then begin result := -DS_FailedSeek; exit; end; if Read(Loc, sizeof(TZip64EOCLocator)) <> sizeof(TZip64EOCLocator) then begin Result := -DS_EOCBadRead; exit; end; if (IsLocator(@Loc)) then begin // locator found fZ64 := true; // in theory anyway - if it has locator it must be Z64 TotalDisks := Loc.NumberDisks; DiskNr := Loc.NumberDisks - 1; // is last disk if Integer(Loc.EOC64DiskStt) <> DiskNr then begin Result := -DS_EOCBadRead; exit; { TODO 1 : handle EOC64 not same disk as locator } // SeekDisk(Loc.EOC64DiskStt); // TODO set up for new disk // test for cancel ? end; if Seek(Loc.EOC64RelOfs, 0) < 0 then begin Result := -DS_FailedSeek; exit; end; if Read(eoc64, sizeof(TZipEOC64)) <> sizeof(TZipEOC64) then begin Result := -DS_EOCBadRead; exit; end; if (eoc64.EOC64Sig = EndCentral64Sig) then begin // read EOC64 fVersionNeeded := eoc64.VersionNeed; if ((VersionNeeded and VerMask) > ZIP64_VER) or (eoc64.vsize < (sizeof(TZipEOC64) - 12)) then begin Result := -DS_Unsupported; exit; end; CEnd := Loc.EOC64RelOfs; fVersionMadeBy := eoc64.VersionMade; fZ64VSize := eoc64.vsize + 12; if CentralDiskNo = MAX_WORD then begin CentralDiskNo := eoc64.CentralDiskNo; fZ64 := true; end; if TotalEntries = MAX_WORD then begin TotalEntries := Cardinal(eoc64.TotalEntries); fZ64 := true; end; if CentralEntries = MAX_WORD then begin CentralEntries := Cardinal(eoc64.CentralEntries); fZ64 := true; end; if CentralSize = MAX_UNSIGNED then begin CentralSize := eoc64.CentralSize; fZ64 := true; end; if CentralOffset = MAX_UNSIGNED then begin CentralOffset := eoc64.CentralOffset; fZ64 := true; end; end; end; // check structure OffsetDelta := CEnd - CentralSize - CentralOffset; if OffsetDelta <> 0 then Result := Result or EOCBadStruct; end; end; function TZMEOC.GetZipCommentLen: Integer; begin Result := Length(ZipComment); end; (*? TZMEOC.OpenEOC // Function to find the EOC record at the end of the archive (on the last disk.) // We can get a return value or an exception if not found. 1.73 28 June 2003 RP change handling split files return <0 - -reason for not finding >=0 - found Warning values (ored) 1 - bad comment 2 - bad structure (Central offset wrong) *) function TZMEOC.OpenEOC(EOConly: boolean): Integer; begin try Result := OpenEOC1; if (Result >= EOCWant64) and not EOConly then Result := GetEOC64(Result); if Result > 0 then Result := Result and (EOCBadComment or EOCBadStruct); except on E: EZipMaster do begin File_Close; Result := -E.ResId; end; else begin File_Close; raise; end; end; end; function TZMEOC.OpenEOC1: Integer; var fEOC: TZipEndOfCentral; pEOC: PZipEndOfCentral; Size, i, j: Integer; Sg: Cardinal; ZipBuf: array of AnsiChar;//Byte; AfterEOC, clen: integer; begin fZipComment := ''; MultiDisk := false; DiskNr := 0; TotalDisks := 0; TotalEntries := 0; CentralEntries := 0; CentralDiskNo := 0; CentralOffset := 0; CentralSize := 0; fEOCOffset := 0; fVersionMadeBy := 0; fVersionNeeded := 0; OffsetDelta := 0; pEOC := nil; Result := 0; // Open the input archive, presumably the last disk. if not IsOpen then File_Open(fmOpenRead + fmShareDenyWrite); if not IsOpen then begin if FileExists(FileName) then Result := -DS_FileOpen else Result := -DS_NoInFile; Exit; end; // First a check for the first disk of a spanned archive, // could also be the last so we don't issue a warning yet. Sig := zfsNone; try // CheckRead(Sg, 4, DS_NoValidZip); if Read(Sg, 4) <> 4 then begin Result := -DS_NoValidZip; exit; end; if (Sg and $FFFF) = IMAGE_DOS_SIGNATURE then Sig := zfsDOS else if (Sg = LocalFileHeaderSig) then Sig := zfsLocal else if (Sg = ExtLocalSig) and (Read(Sg, 4) = 4) and (Sg = LocalFileHeaderSig) then begin Sig := zfsMulti; MultiDisk := True; // will never be true on 'valid' multi-part zip with eoc end; // Next we do a check at the end of the file to speed things up if // there isn't a Zip archive ZipComment. File_Size := Seek(-SizeOf(TZipEndOfCentral), soFromEnd); if File_Size < 0 then Result := -DS_NoValidZip else begin File_Size := File_Size + SizeOf(TZipEndOfCentral); // Save the archive size as a side effect. RealFileSize := File_Size; // There could follow a correction on FFileSize. if Read(fEOC, SizeOf(TZipEndOfCentral)) <> sizeof(TZipEndOfCentral) then Result := -DS_EOCBadRead else if (fEOC.HeaderSig = EndCentralDirSig) then begin fEOCOffset := File_Size - SizeOf(TZipEndOfCentral); Result := 8; // something found if fEOC.ZipCommentLen <> 0 then begin fEOC.ZipCommentLen := 0; // ??? make safe Result := EOCBadComment;//1; // return bad comment end; pEOC := @fEOC; end; end; if Result = 0 then // did not find it - must have ZipComment begin Size := 65535 + SizeOf(TZipEndOfCentral); if File_Size < Size then Size := Integer(File_Size); SetLength(ZipBuf, Size); if Seek(-Size, soFromEnd) < 0 then Result := -DS_FailedSeek else if Read(PByte(ZipBuf)^, Size) <> Size then Result := -DS_EOCBadRead; // end; if Result = 0 then begin for i := Size - SizeOf(TZipEndOfCentral) - 1 downto 0 do if PZipEndOfCentral(PAnsiChar(ZipBuf) + i)^.HeaderSig = EndCentralDirSig then begin fEOCOffset := File_Size - (Size - i); pEOC := @ZipBuf[i]; Result := 8; // something found // If we have ZipComment: Save it AfterEOC := Size - (i + SizeOf(TZipEndOfCentral)); clen := pEOC^.ZipCommentLen; if AfterEOC < clen then clen := AfterEOC; if clen > 0 then begin SetLength(fZipComment, clen); for j := 1 to clen do fZipComment[j] := ZipBuf[i + Sizeof(TZipEndOfCentral) + j - 1]; end; // Check if we really are at the end of the file, if not correct the File_Size // and give a warning. (It should be an error but we are nice.) if i + SizeOf(TZipEndOfCentral) + clen <> Size then begin File_Size := File_Size + ((i + SizeOf(TZipEndOfCentral) + clen) - Size); // // Now we need a check for WinZip Self Extractor which makes SFX files which // // almost always have garbage at the end (Zero filled at 512 byte boundary!) // // In this special case 'we' don't give a warning. // Unfortunately later versions use a different boundary so the test is invalid if i + SizeOf(TZipEndOfCentral) + clen > Size then // HOTFIX-MARX-B begin Result := EOCBadComment; // Comment was cut end; end; break; end; // for end; end; if Result > 0 then begin MultiDisk := pEOC^.ThisDiskNo > 0; // may not have had proper sig DiskNr := pEOC^.ThisDiskNo; TotalDisks := pEOC^.ThisDiskNo + 1; //check TotalEntries := pEOC^.TotalEntries; CentralEntries := pEOC^.CentralEntries; CentralDiskNo := pEOC^.CentralDiskNo; CentralOffset := pEOC^.CentralOffset; CentralSize := pEOC^.CentralSize; if (pEOC^.TotalEntries = MAX_WORD) or (pEOC^.CentralOffset = MAX_UNSIGNED) or (pEOC^.CentralEntries = MAX_WORD) or (pEOC^.CentralSize = MAX_UNSIGNED) or (pEOC^.ThisDiskNo = MAX_WORD) or (pEOC^.CentralDiskNo = MAX_WORD) then begin Result := Result or EOCWant64; end; end; if Result = 0 then Result := -DS_NoValidZip; if Result > 0 then begin Result := Result and (EOCBadComment or EOCBadStruct or EOCWant64); // remove 'found' flag end; finally ZipBuf := nil; if Result < 0 then File_Close; end; end; // GetLastVolume function TZMEOC.OpenLast(EOConly: boolean; OpenRes: Integer): integer; var ext: String; Finding: Boolean; FMVolume: Boolean; Fname: String; OrigName: String; PartNbr: Integer; Path: String; s: String; sName: String; Stamp: Integer; StampTmp: Integer; tmpNumbering: TZipNumberScheme; WasNoFile: Boolean; begin WasNoFile := OpenRes = -DS_NoInFile; PartNbr := -1; Result := -DS_FileOpen; // default failure FMVolume := False; OrigName := FileName; // save it WorkDrive.DriveStr := FileName; Path := ExtractFilePath(FileName); Numbering := znsNone; // unknown as yet tmpNumbering := znsNone; try WorkDrive.HasMedia(False); // check valid drive if WasNoFile then begin ext := UpperCase(ExtractFileExt(FileName)); // get the 'base' name for numbered names Fname := Copy(FileName, 1, Length(FileName) - Length(ext)); // remove extension FMVolume := True; // file did not exist maybe it is a multi volume // if no file exists on harddisk then only Multi volume parts are possible if WorkDrive.DriveIsFixed then begin // filename is of type ArchiveXXX.zip // MV files are series with consecutive partnbrs in filename, // highest number has EOC if ext = EXT_ZIP then begin Finding := True; Stamp := -1; while Finding and (PartNbr < 1000) do begin if Worker.KeepAlive then exit; // cancelled // add part number and extension to base name s := Fname + Copy(IntToStr(1002 + PartNbr), 2, 3) + EXT_ZIPL; StampTmp := Integer(File_Age(s)); if (StampTmp = -1) or ((Stamp <> -1) and (StampTmp <> Stamp)) then begin // not found or stamp does not match Result := -DS_NoInFile; exit; end; if (PartNbr = -1) and not (spAnyTime in {Worker.}SpanOptions) then Stamp := StampTmp; Inc(PartNbr); FileName := s; Result := OpenEOC(EOConly); if Result >= 0 then begin // found possible last part Finding := False; if (TotalDisks - 1) <> PartNbr then begin // was not last disk File_Close; // should happen in 'finally' Result := -DS_FileOpen; exit; end; Numbering := znsName; end; end; // while end; // if Ext = '.zip' if not IsOpen then begin Result := -DS_NoInFile; exit; // not found end; // should be the same as s FileName := Fname + Copy(IntToStr(1001 + PartNbr), 2, 3) + EXT_ZIPL; // check if filename.z01 exists then it is part of MV with compat names // and cannot be used if (FileExists(ChangeFileExt(FileName, '.z01'))) then begin // ambiguous - cannot be used File_Close; // should happen in 'finally' exit; // will return DS_FileOpen end; end // if WorkDrive.Fixed else begin // do we have an MV archive copied to a removable disk // accept any MV filename on disk - then we ask for last part sName := NameOfPart(Fname, False); if sName = '' then sName := NameOfPart(Fname, True); if sName = '' then // none begin Result := -DS_NoInFile; // no file with likely name exit; end; FileName := Path + sName; end; end; // if not exists // zip file exists or we got an acceptable part in multivolume or split // archive // use class variable for other functions while not IsOpen do // only open if found last part on hd begin // does this part contains the central dir Result := OpenEOC(EOConly); // don't load on success if Result >= 0 then break; // found a 'last' disk // it is not the disk with central dir so ask for the last disk NewDisk := True; // new last disk DiskNr := -1; // read operation CheckForDisk(False, False); // does the request for new disk if WorkDrive.DriveIsFixed then begin if not FMVolume then Result := -DS_NoValidZip; break;//exit; // file with EOC is not on fixed disk end; if FMVolume then begin // we have removable disks with multi volume archives // get the file name on this disk tmpNumbering := znsName; // only if part and last part inserted sName := NameOfPart(Fname, False); if sName = '' then begin sName := NameOfPart(Fname, True); tmpNumbering := znsExt; // only if last part inserted end; if sName = '' then // none begin Result := -DS_NoInFile; // no file with likely name // exit; FMVolume := False; break; end; FileName := Path + sName; end; end; // while if FMVolume then // got a multi volume part so we need more checks begin // is this first file of a multi-part if (Sig <> zfsMulti) and ((TotalDisks = 1) and (PartNbr >= 0)) then Result := -DS_FileOpen // check else // part and EOC equal? if WorkDrive.DriveIsFixed and (TotalDisks <> (PartNbr + 1)) then begin File_Close; // should happen in 'finally' Result := -DS_NoValidZip; end; end; finally if Result < 0 then begin File_Close; // close filehandle if OpenLast FileName := ''; // don't use the file end //; else if (Numbering <> znsVolume) and (tmpNumbering <> znsNone) then Numbering := tmpNumbering; end; end; procedure TZMEOC.SetZipComment(const Value: AnsiString); begin fZipComment := Value; end; procedure TZMEOC.SetZipCommentLen(const Value: Integer); var c: AnsiString; begin if (Value <> ZipCommentLen) and (Value < Length(ZipComment))then begin c := ZipComment; SetLength(c, Value); ZipComment := c; end; end; // returns >0 ok = bytes written, <0 -ErrNo function TZMEOC.WriteEOC: Integer; type TEOCrecs = packed record loc: TZip64EOCLocator; eoc: TZipEndOfCentral; end; pEOCrecs = ^TEOCrecs; var t: Integer; er: array of byte; erz: Integer; peoc: pEOCrecs; eoc64: TZipEOC64; Need64: Boolean; clen: Integer; begin Result := -DS_EOCBadWrite; // keeps compiler happy TotalDisks := DiskNr + 1; //check Need64 := false; ZeroMemory(@eoc64, sizeof(eoc64)); clen := Length(ZipComment); ASSERT(clen = ZipCommentLen, ' ZipComment length error'); erz := sizeof(TEOCrecs) + clen; SetLength(er, erz + 1); peoc := @er[0]; peoc^.eoc.HeaderSig := EndCentralDirSig; peoc^.loc.LocSig := EOC64LocatorSig; if clen > 0 then Move(ZipComment[1], er[sizeof(TEOCrecs)], clen); peoc^.eoc.ZipCommentLen := clen; // check Zip64 needed if TotalDisks > MAX_WORD then begin peoc^.eoc.ThisDiskNo := Word(-1); Need64 := true; end else peoc^.eoc.ThisDiskNo := Word(TotalDisks -1); //check if CentralDiskNo >= MAX_WORD then begin peoc^.eoc.CentralDiskNo := Word(-1); Need64 := true; end else peoc^.eoc.CentralDiskNo := CentralDiskNo; if TotalEntries >= MAX_WORD then begin peoc^.eoc.TotalEntries := Word(-1); Need64 := true; end else peoc^.eoc.TotalEntries := Word(TotalEntries); if CentralEntries >= MAX_WORD then begin peoc^.eoc.CentralEntries := Word(-1); Need64 := true; end else peoc^.eoc.CentralEntries := Word(CentralEntries); if CentralSize >= MAX_UNSIGNED then begin peoc^.eoc.CentralSize := Cardinal(-1); Need64 := true; end else peoc^.eoc.CentralSize := CentralSize; if (CentralOffset >= MAX_UNSIGNED) then begin peoc^.eoc.CentralOffset := Cardinal(-1); Need64 := true; end else peoc^.eoc.CentralOffset := CentralOffset; if not Need64 then begin // write 'normal' EOC erz := erz - sizeof(TZip64EOCLocator); // must not split Result := Write(er[sizeof(TZip64EOCLocator)],-(erz or MustFitFlag)); if Result <> erz then begin if Result = MustFitError then begin if DiskNr >= MAX_WORD then Need64 := true else begin peoc^.eoc.ThisDiskNo := Word(DiskNr); Result := Write(er[sizeof(TZip64EOCLocator)],-(erz or MustFitFlag)); if Result <> erz then Result := -DS_EOCBadWrite; end; end else Result := -DS_EOCBadWrite; end; end; if Need64 then begin Z64 := true; eoc64.EOC64Sig := EndCentral64Sig; eoc64.vsize := sizeof(eoc64) - 12; eoc64.VersionMade := ZIP64_VER; eoc64.VersionNeed := ZIP64_VER; eoc64.ThisDiskNo := DiskNr; eoc64.CentralDiskNo := CentralDiskNo; eoc64.TotalEntries := TotalEntries; eoc64.CentralEntries := CentralEntries; eoc64.CentralSize := CentralSize; eoc64.CentralOffset := CentralOffset; peoc^.loc.EOC64RelOfs := Position; peoc^.loc.EOC64DiskStt := DiskNr; Result := Write(eoc64, -sizeof(TZipEOC64)); if Result = sizeof(TZipEOC64) then begin peoc^.loc.NumberDisks := DiskNr + 1; // may be new disk if DiskNr >= MAX_WORD then peoc^.eoc.ThisDiskNo := MAX_WORD else peoc^.eoc.ThisDiskNo := Word(DiskNr);// + 1); Result := sizeof(TZipEndOfCentral) + peoc^.eoc.ZipCommentLen; // if it works t := Write(er[0],-(erz or MustFitFlag)); if t <> erz then begin if t = MustFitError then begin peoc^.loc.NumberDisks := DiskNr + 1; if DiskNr >= MAX_WORD then peoc^.eoc.ThisDiskNo := MAX_WORD else peoc^.eoc.ThisDiskNo := Word(DiskNr);// + 1); t := Write(er[0], -erz); if t <> erz then Result := -DS_EOCBadWrite; end else Result := -DS_EOCBadWrite; end; end; end; end; end.
unit PE.Imports.Func; interface uses System.Generics.Collections, System.SysUtils, PE.Common; type TPEImportFunction = class public Ordinal: uint16; Name: String; procedure Clear; inline; constructor CreateEmpty; constructor Create(const Name: String; Ordinal: uint16 = 0); end; TPEImportFunctionDelayed = class(TPEImportFunction) public end; TPEImportFunctions = TObjectList<TPEImportFunction>; implementation { TImportFunction } procedure TPEImportFunction.Clear; begin self.Ordinal := 0; self.Name := ''; end; constructor TPEImportFunction.Create(const Name: String; Ordinal: uint16); begin self.Name := Name; self.Ordinal := Ordinal; end; constructor TPEImportFunction.CreateEmpty; begin end; end.
unit LocaleMessages; interface type TLocaleMessages = ( c_ApplicationTitle // EasyUpdateForm , c_EasyUpdateFormCaption , c_EasyUpdateFormStatusGroupBoxCaption , c_EasyUpdateFormAutomaticUpdateLabelCaption , c_EasyUpdateFormNextTimeRunLabelCaption , c_EasyUpdateFormLastTimeRunLabelCaption , c_EasyUpdateFormLastRunLabel , c_EasyUpdateFormHelpBitBtnCaption , c_EasyUpdateFormOnBitBtnCaption , c_EasyUpdateFormOffBitBtnCaption , c_EasyUpdateFormRunBitBtnCaption , c_EasyUpdateFormSetupParamsLabelCaption , c_EasyUpdateFormAutomaticUpdateStatusToStringFalse , c_EasyUpdateFormAutomaticUpdateStatusToStringTrue , c_EasyUpdateFormNextTimeToString , c_EasyUpdateFormLastTimeToString , c_EasyUpdateFormLastRunStatusToString , c_EasyUpdateFormLastRunStatusIsStillActiveToString , c_EasyUpdateFormTaskNameLabelHintToString // EasyUpdateAdminForm , c_EasyUpdateAdminFormCaption , c_EasyUpdateAdminFormInformationMemoLinesText , c_EasyUpdateAdminFormAdminNameLabelCaption , c_EasyUpdateAdminFormAdminPasswordLabelCaption , c_EasyUpdateAdminFormAdminPasswordCheckLabelCaption , c_EasyUpdateAdminFormCommonSaveBitBtnCaption , c_EasyUpdateAdminFormCommonCancelBitBtnCaption , c_EasyUpdateAdminFormShowInvalidPasswordErrorText , c_EasyUpdateAdminFormShowInvalidPasswordErrorCaption // EasyUpdateMailForm , c_EasyUpdateMailFormCaption , c_EasyUpdateMailFormInformationMemoLinesText , c_EasyUpdateMailFormMailFromLabelCaption , c_EasyUpdateMailFormMailToLabelCaption , c_EasyUpdateMailFormMailServerLabelCaption , c_EasyUpdateMailFormMailServerUserLabelCaption , c_EasyUpdateMailFormMailServerPasswordLabelCaption , c_EasyUpdateMailFormCommonSaveBitBtnCaption , c_EasyUpdateMailFormCommonCancelBitBtnCaption // EasyUpdateParamsForm , c_EasyUpdateParamsFormCaption , c_EasyUpdateParamsFormDownloadTabSheetCaption , c_EasyUpdateParamsFormDownloadRevisionCheckBoxCaption , c_EasyUpdateParamsFormDownloadRetryCheckBoxCaption , c_EasyUpdateParamsFormDownloadRestoreCheckBoxCaption , c_EasyUpdateParamsFormDownloadRestoreMinutesLabelCaption , c_EasyUpdateParamsFormDownloadResumeCheckBoxCaption , c_EasyUpdateParamsFormDownloadSaveToLabelCaption , c_EasyUpdateParamsFormDownloadUserAgentLabelCaption , c_EasyUpdateParamsFormDownloadSendReportCheckBoxCaption , c_EasyUpdateParamsFormDownloadSendReportStatusLabelTrueCaption , c_EasyUpdateParamsFormDownloadSendReportStatusLabelFalseCaption , c_EasyUpdateParamsFormDownloadSendReportParametersLabelCaption , c_EasyUpdateParamsFormDownloadRestoreAllBitBtnCaption , c_EasyUpdateParamsFormUpdateTabSheetCaption , c_EasyUpdateParamsFormUpdateNoBackupCheckBoxCaption , c_EasyUpdateParamsFormUpdateRemoveZipsCheckBoxCaption , c_EasyUpdateParamsFormUpdateSearchInLabelCaption , c_EasyUpdateParamsFormUpdateAdminPasswordLabelCaption , c_EasyUpdateParamsFormUpdateAdminPasswordCommentLabelCaption , c_EasyUpdateParamsFormUpdateSendReportCheckBoxCaption , c_EasyUpdateParamsFormUpdateSkipWarningCheckBoxCaption , c_EasyUpdateParamsFormUpdateSendReportStatusLabelTrueCaption , c_EasyUpdateParamsFormUpdateSendReportStatusLabelFalseCaption , c_EasyUpdateParamsFormUpdateSendReportParametersLabelCaption , c_EasyUpdateParamsFormUpdateRestoreAllBitBtnCaption , c_EasyUpdateParamsFormScheduleTabSheetCaption , c_EasyUpdateParamsFormScheduleDownloadEnabledCheckBoxCaption , c_EasyUpdateParamsFormScheduleUpdateEnabledCheckBoxCaption , c_EasyUpdateParamsFormScheduleRunAtEndCheckBoxCaption , c_EasyUpdateParamsFormScheduleRunAtEndCommandLineLabelCaption , c_EasyUpdateParamsFormScheduleWeekGroupBoxCaption , c_EasyUpdateParamsFormScheduleMondayCheckBoxCaption , c_EasyUpdateParamsFormScheduleTuesdayCheckBoxCaption , c_EasyUpdateParamsFormScheduleWednesdayCheckBoxCaption , c_EasyUpdateParamsFormScheduleThursdayCheckBoxCaption , c_EasyUpdateParamsFormScheduleFridayCheckBoxCaption , c_EasyUpdateParamsFormScheduleSaturdayCheckBoxCaption , c_EasyUpdateParamsFormScheduleSundayCheckBoxCaption , c_EasyUpdateParamsFormScheduleRestoreAllBitBtnCaption , c_EasyUpdateParamsFormCommonHelpBitBtnCaption , c_EasyUpdateParamsFormCommonSaveBitBtnCaption , c_EasyUpdateParamsFormCommonCancelBitBtnCaption , c_EasyUpdateParamsFormShowInvalidDataFormatErrorText , c_EasyUpdateParamsFormShowInvalidDataFormatErrorCaption // EasyUpdateSupport , c_EasyUpdateSupportDownloadNotTunedText , c_EasyUpdateSupportDownloadNotTunedCaption , c_EasyUpdateSupportRestoreJobFileText , c_EasyUpdateSupportRestoreJobFileCaption , c_EasyUpdateSupportSystemNotCompatibleText , c_EasyUpdateSupportSystemNotCompatibleCaption ); procedure SetCurrentLocale(const a_LocaleValue: string); function GetCurrentLocaleMessage(const a_LocaleMessages: TLocaleMessages): string; implementation uses SysUtils; var g_LocaleMessagesArray: array [TLocaleMessages] of record r_Current: PAnsiChar; // r_English: PAnsiChar; r_Russian: PAnsiChar; end = ( ( r_Current: nil // c_ApplicationTitle ; r_English: 'GARANT aero: Automatic update' ; r_Russian: 'ГАРАНТ аэро: Автоматическое обновление' ) // EasyUpdateForm , ( r_Current: nil // c_EasyUpdateFormCaption ; r_English: 'GARANT aero: Automatic update' ; r_Russian: 'ГАРАНТ аэро: Автоматическое обновление' ) , ( r_Current: nil // c_EasyUpdateFormStatusGroupBoxCaption ; r_English: 'Status' ; r_Russian: 'Состояние' ) , ( r_Current: nil // c_EasyUpdateFormAutomaticUpdateLabelCaption ; r_English: 'Automatic update is:' ; r_Russian: 'Автоматическое обновление:' ) , ( r_Current: nil // c_EasyUpdateFormNextTimeRunLabelCaption ; r_English: 'Next run time:' ; r_Russian: 'Время следующего запуска:' ) , ( r_Current: nil // c_EasyUpdateFormLastTimeRunLabelCaption ; r_English: 'Last run time:' ; r_Russian: 'Время последнего запуска:' ) , ( r_Current: nil // c_EasyUpdateFormLastRunLabelCaption ; r_English: 'Last run status/startup code:' ; r_Russian: 'Статус/Код последнего запуска:' ) , ( r_Current: nil // c_EasyUpdateFormHelpBitBtnCaption ; r_English: 'Help' ; r_Russian: 'Справка' ) , ( r_Current: nil // c_EasyUpdateFormOnBitBtnCaption ; r_English: 'On' ; r_Russian: 'Включить' ) , ( r_Current: nil // c_EasyUpdateFormOffBitBtnCaption ; r_English: 'Off' ; r_Russian: 'Отключить' ) , ( r_Current: nil // c_EasyUpdateFormRunBitBtnCaption ; r_English: 'Run' ; r_Russian: 'Запустить' ) , ( r_Current: nil // c_EasyUpdateFormSetupParamsLabelCaption ; r_English: 'Setup parameters' ; r_Russian: 'Настроить параметры' ) , ( r_Current: nil // c_EasyUpdateFormAutomaticUpdateStatusToStringFalse ; r_English: 'Off' ; r_Russian: 'Выключено' ) , ( r_Current: nil // c_EasyUpdateFormAutomaticUpdateStatusToStringTrue ; r_English: 'On' ; r_Russian: 'Включено' ) , ( r_Current: nil // c_EasyUpdateFormNextTimeToString ; r_English: 'Not set' ; r_Russian: 'Не установлено' ) , ( r_Current: nil // c_EasyUpdateFormLastTimeToString ; r_English: 'Not set' ; r_Russian: 'Не установлено' ) , ( r_Current: nil // c_EasyUpdateFormLastRunStatusToString ; r_English: 'Not defined' ; r_Russian: 'Не определено' ) , ( r_Current: nil // c_EasyUpdateFormLastRunStatusIsStillActiveToString ; r_English: 'Running' ; r_Russian: 'Выполняется' ) , ( r_Current: nil // c_EasyUpdateFormTaskNameLabelHintToString ; r_English: 'Task name' ; r_Russian: 'Имя задания' ) // EasyUpdateAdminForm , ( r_Current: nil // c_EasyUpdateAdminFormCaption ; r_English: 'GARANT: Parameters for ADMIN user' ; r_Russian: 'ГАРАНТ: Параметры пароля пользователя ADMIN' ) , ( r_Current: nil // c_EasyUpdateAdminFormInformationMemoLinesText ; r_English: ' If the administrator account password in GARANT System (ADMIN) is different from the default one,' + ' to launch the updating procedure in the automatic mode please enter a new password in the fields' + ' User Password and Confirm User Password.' ; r_Russian: ' Если пароль администраторской учетной записи с системе ГАРАНТ (ADMIN) отличается от умолчательного значения,' + ' для запуска процедуры применения обновления в автоматическом режиме, введите, пожалуйста,' + ' новое значение пароля в поля "пароль пользователя" и "подтвердите пароль пользователя".' ) , ( r_Current: nil // c_EasyUpdateAdminFormAdminNameLabelCaption ; r_English: 'Enter user name:' ; r_Russian: 'Введите имя пользователя:' ) , ( r_Current: nil // c_EasyUpdateAdminFormAdminPasswordLabelCaption ; r_English: 'Enter user password:' ; r_Russian: 'Введите пароль пользователя:' ) , ( r_Current: nil // c_EasyUpdateAdminFormAdminPasswordCheckLabelCaption ; r_English: 'Confirm user password:' ; r_Russian: 'Подтвердите пароль пользователя:' ) , ( r_Current: nil // c_EasyUpdateAdminFormCommonSaveBitBtnCaption ; r_English: 'Save' ; r_Russian: 'Сохранить' ) , ( r_Current: nil // c_EasyUpdateAdminFormCommonCancelBitBtnCaption ; r_English: 'Cancel' ; r_Russian: 'Отменить' ) , ( r_Current: nil // c_EasyUpdateAdminFormShowInvalidPasswordErrorText ; r_English: 'Password and password confirmation do not match' ; r_Russian: 'Введенные пароли не совпадают' ) , ( r_Current: nil // c_EasyUpdateAdminFormShowInvalidPasswordErrorCaption ; r_English: 'ERROR' ; r_Russian: 'ОШИБКА' ) // EasyUpdateMailForm , ( r_Current: nil // c_EasyUpdateMailFormCaption ; r_English: 'GARANT: Mail parameters' ; r_Russian: 'ГАРАНТ: Параметры почты' ) , ( r_Current: nil // c_EasyUpdateMailFormInformationMemoLinesText ; r_English: ' For notification by e-mail of the termination of downloading and/or application of updating files, please, indicate the settings parameters, including:'#13 + ' - sender e-mail address (to be used to send the notification);'#13 + ' - recipient e-mail address (to be used to receive the notification);'#13 + ' - outgoing mail server name (SMTP server to be used to send the notification).' ; r_Russian: ' Для уведомления по электронной почте о завершении скачивания и(или) применения файлов обновлений, укажите, пожалуйста, параметры настроек, в том числе:'#13 + ' - электронный адрес отправителя (с которого будет отправляться уведомление);'#13 + ' - электронный адрес получателя (на который будет приходить уведомление);'#13 + ' - имя сервера исходящей почты (SMTP-сервер, с которого будет отправляться уведомление).' ) , ( r_Current: nil // c_EasyUpdateMailFormMailFromLabelCaption ; r_English: 'Enter sender e-mail address:' ; r_Russian: 'Введите электронный адрес отправителя:' ) , ( r_Current: nil // c_EasyUpdateMailFormMailToLabelCaption ; r_English: 'Enter recipient e-mail address:' ; r_Russian: 'Введите электронный адрес получателя:' ) , ( r_Current: nil // c_EasyUpdateMailFormMailServerLabelCaption ; r_English: 'Enter outgoing mail server name:' ; r_Russian: 'Введите имя сервера исходящей почты:' ) , ( r_Current: nil // c_EasyUpdateMailFormMailServerUserLabelCaption ; r_English: 'Enter outgoing mail server login:' ; r_Russian: 'Введите логин на почтовом сервере:' ) , ( r_Current: nil // c_EasyUpdateMailFormMailServerPasswordLabelCaption ; r_English: 'Enter outgoing mail server password:' ; r_Russian: 'Введите пароль на почтовом сервере:' ) , ( r_Current: nil // c_EasyUpdateMailFormCommonSaveBitBtnCaption ; r_English: 'Save' ; r_Russian: 'Сохранить' ) , ( r_Current: nil // c_EasyUpdateMailFormCommonCancelBitBtnCaption ; r_English: 'Cancel' ; r_Russian: 'Отменить' ) // EasyUpdateParamsForm , ( r_Current: nil // c_EasyUpdateParamsFormCaption ; r_English: 'GARANT: Automatic update parameters' ; r_Russian: 'ГАРАНТ: Параметры автоматического обновления' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadTabSheetCaption ; r_English: 'Download updates' ; r_Russian: 'Скачивание обновлений' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadRevisionCheckBoxCaption ; r_English: 'Permit follow-up downloading' ; r_Russian: 'Допускать повторные скачивания' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadRetryCheckBoxCaption ; r_English: 'If no updates available, check for them each 20 minutes' ; r_Russian: 'В случае отсутствия обновлений повторять попытку скачивания каждые 20 минут' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadRestoreCheckBoxCaption ; r_English: 'If connection lost, retry within' ; r_Russian: 'При обрыве соединения пытаться восстанавливать в течение' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadRestoreMinutesLabelCaption ; r_English: 'minutes' ; r_Russian: 'минут' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadResumeCheckBoxCaption ; r_English: 'Continue interrupted downloading next time' ; r_Russian: 'Продолжать прерванное скачивание при следующем запуске' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadSaveToLabelCaption ; r_English: 'Save updates to' ; r_Russian: 'Сохранять обновления в' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadUserAgentLabelCaption ; r_English: 'Identify as' ; r_Russian: 'Идентифицировать как' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadSendReportCheckBoxCaption ; r_English: 'At end of download send mail report' ; r_Russian: 'По завершении скачивания посылать уведомление по почте' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadSendReportStatusLabelTrueCaption ; r_English: '[Parameters exist]' ; r_Russian: '[Параметры настроены]' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadSendReportStatusLabelFalseCaption ; r_English: '[Parameters not exist]' ; r_Russian: '[Параметры незаданы]' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadSendReportParametersLabelCaption ; r_English: 'Setup mail parameters' ; r_Russian: 'Настроить параметры почты' ) , ( r_Current: nil // c_EasyUpdateParamsFormDownloadRestoreAllBitBtnCaption ; r_English: 'Restore to default values' ; r_Russian: 'Восстановить значения по умолчанию' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateTabSheetCaption ; r_English: 'Apply updates' ; r_Russian: 'Применение обновлений' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateNoBackupCheckBoxCaption ; r_English: 'No backups (not recommended!)' ; r_Russian: 'Отказаться от создания резервной копии (не рекомендуется!)' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateRemoveZipsCheckBoxCaption ; r_English: 'Remove updates from Archive folder' ; r_Russian: 'Удалять архивы распакованных обновлений из подкаталога Archive' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateSearchInLabelCaption ; r_English: 'Looking for updates in' ; r_Russian: 'Искать обновления в' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateAdminPasswordLabelCaption ; r_English: 'Set user password for ADMIN' ; r_Russian: 'Задать пароль пользователя ADMIN' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateAdminPasswordCommentLabelCaption ; r_English: '(unless set as default)' ; r_Russian: '(если он отличается от умолчательного)' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateSendReportCheckBoxCaption ; r_English: 'At end of apply send mail report' ; r_Russian: 'По завершении применения посылать уведомление по почте' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateSkipWarningCheckBoxCaption ; r_English: 'Launch update even in the absence of space' ; r_Russian: 'Запускать обновление даже в случае нехватки места' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateSendReportStatusLabelTrueCaption ; r_English: '[Parameters exist]' ; r_Russian: '[Параметры настроены]' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateSendReportStatusLabelFalseCaption ; r_English: '[Parameters not exist]' ; r_Russian: '[Параметры незаданы]' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateSendReportParametersLabelCaption ; r_English: 'Setup mail parameters' ; r_Russian: 'Настроить параметры почты' ) , ( r_Current: nil // c_EasyUpdateParamsFormUpdateRestoreAllBitBtnCaption ; r_English: 'Restore default values' ; r_Russian: 'Восстановить значения по умолчанию' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleTabSheetCaption ; r_English: 'Schedule' ; r_Russian: 'Расписание' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleDownloadEnabledCheckBoxCaption ; r_English: 'Enable automatic updates download' ; r_Russian: 'Включить автоматическое скачивание обновлений' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleUpdateEnabledCheckBoxCaption ; r_English: 'Enable automatic updates apply' ; r_Russian: 'Включить автоматическое применение обновлений' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleRunAtEndCheckBoxCaption ; r_English: 'Run at end' ; r_Russian: 'Запускать в конце' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleRunAtEndCommandLineLabelCaption ; r_English: 'with parameters' ; r_Russian: 'с параметрами' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleWeekGroupBoxCaption ; r_English: 'Run any' ; r_Russian: 'Запускать каждый' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleMondayCheckBoxCaption ; r_English: 'Monday' ; r_Russian: 'Понедельник' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleTuesdayCheckBoxCaption ; r_English: 'Tuesday' ; r_Russian: 'Вторник' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleWednesdayCheckBoxCaption ; r_English: 'Wednesday' ; r_Russian: 'Среда' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleThursdayCheckBoxCaption ; r_English: 'Thursday' ; r_Russian: 'Четверг' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleFridayCheckBoxCaption ; r_English: 'Friday' ; r_Russian: 'Пятница' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleSaturdayCheckBoxCaption ; r_English: 'Saturday' ; r_Russian: 'Суббота' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleSundayCheckBoxCaption ; r_English: 'Sunday' ; r_Russian: 'Воскресенье' ) , ( r_Current: nil // c_EasyUpdateParamsFormScheduleRestoreAllBitBtnCaption ; r_English: 'Restore default values' ; r_Russian: 'Восстановить значения по умолчанию' ) , ( r_Current: nil // c_EasyUpdateParamsFormCommonHelpBitBtnCaption ; r_English: 'Help' ; r_Russian: 'Справка' ) , ( r_Current: nil // c_EasyUpdateParamsFormCommonSaveBitBtnCaption ; r_English: 'Save' ; r_Russian: 'Сохранить' ) , ( r_Current: nil // c_EasyUpdateParamsFormCommonCancelBitBtnCaption ; r_English: 'Cancel' ; r_Russian: 'Отменить' ) , ( r_Current: nil // c_EasyUpdateParamsFormShowInvalidDataFormatErrorText ; r_English: 'Data format invalid' ; r_Russian: 'Неправильный формат данных' ) , ( r_Current: nil // c_EasyUpdateParamsFormShowInvalidDataFormatErrorCaption ; r_English: 'ERROR' ; r_Russian: 'ОШИБКА' ) , ( r_Current: nil // c_EasyUpdateSupportDownloadNotTunedText ; r_English: 'Please download update files in manual mode once' ; r_Russian: 'Перед началом работы ПРОГРАММЫ настройки автоматического обновления нужно один раз скачать файлы обновления в ручном режиме' ) , ( r_Current: nil // c_EasyUpdateSupportDownloadNotTunedCaption ; r_English: 'ERROR' ; r_Russian: 'ОШИБКА' ) , ( r_Current: nil // c_EasyUpdateSupportRestoreJobFileText ; r_English: 'Can not restore job-file' ; r_Russian: 'Не могу восстановить job-файл' ) , ( r_Current: nil // c_EasyUpdateSupportRestoreJobFileCaption ; r_English: 'WARNING' ; r_Russian: 'ПРЕДУПРЕЖДЕНИЕ' ) , ( r_Current: nil // c_EasyUpdateSupportSystemNotCompatibleText ; r_English: 'This program is compatible with Windows 2000 and upwards' ; r_Russian: 'Данная программа предназначена только для работы под Windows 2000 и выше' ) , ( r_Current: nil // c_EasyUpdateSupportSystemNotCompatibleCaption ; r_English: 'ERROR' ; r_Russian: 'ОШИБКА' ) ); procedure SetCurrentLocale(const a_LocaleValue: string); const c_English = 1; c_Russian = 2; c_Default = c_English; // function GetLanguage(const a_LocaleValue: string): Word; begin Result := c_Default; // if (StrLIComp(PAnsiChar(a_LocaleValue), PAnsiChar('en'), 2) = 0) then Result := c_English else if (StrLIComp(PAnsiChar(a_LocaleValue), PAnsiChar('ru'), 2) = 0) then Result := c_Russian; end; // var l_Index: TLocaleMessages; l_Language: Word; begin l_Language := GetLanguage(a_LocaleValue); // for l_Index := Low(g_LocaleMessagesArray) to High(g_LocaleMessagesArray) do case l_Language of c_English: g_LocaleMessagesArray[l_Index].r_Current := g_LocaleMessagesArray[l_Index].r_English; c_Russian: g_LocaleMessagesArray[l_Index].r_Current := g_LocaleMessagesArray[l_Index].r_Russian; else g_LocaleMessagesArray[l_Index].r_Current := g_LocaleMessagesArray[l_Index].r_English; end; end; function GetCurrentLocaleMessage(const a_LocaleMessages: TLocaleMessages): string; begin Result := g_LocaleMessagesArray[a_LocaleMessages].r_Current; end; initialization SetCurrentLocale('$(UserDefaultLocale)'); // First initialization as User Default Locale (== English now) end.
unit MorrisASM; {$mode objfpc}{$H+} interface procedure Tokenize(s:ansistring); procedure error(s: ansistring; ln: integer); function isnum(s: ansistring):boolean; function isbinnum(s: ansistring):boolean; procedure ALM; function listlabels:boolean; procedure resetASM; function hex2dec(s: ansistring): int16; function bin2dec(s: ansistring): int16; function dec2hex(x,c: uint16): ansistring; function dec2bin(x,c: uint16): ansistring; function isMRef(s: ansistring): boolean; function isRRef(s: ansistring): boolean; function shiftL(x: ansistring): ansistring; function shiftR(x: ansistring): ansistring; /////////////////////////////////////////////////////////////////////////// type blocktype=(null,lcommand,command,data,lb); MemoryBlock=Record btype : blocktype; //Block Type linenum : integer; //Line number for showing in editor code : int16; //Command Code name : ansistring; //Command Name lblindex: integer; //Label Index I : boolean; //Indirect val : int16; //Value , Address end; lbl=record name : ansistring; addr : int16; end; var origin: int16; fmem: int16; AC: int16; AR: int16; E: byte; FGI: boolean; // flag input FGO: boolean; // flag output IFlag: boolean; // interupt flag LBLCount: integer; mem: array[0..4095] of MemoryBlock; lbls: array[0..4095] of lbl; tk: array[0..4000] of array[0..20] of ansistring; //Tokens' placeholder tc: array[0..4000] of integer; //Token count in each line lastline: integer; //Last Line in Action ctline: integer; gotorigin: boolean; forg: int16; haserror: boolean; const commands: array[0..24] of ansistring=( 'AND','ADD','LDA','STA','BUN','BSA','ISZ' ,'CLA','CLE','CMA','CME','CIR','CIL','INC','SPA','SNA','SZA','SZE','HLT', 'INP','OUT','SKI','SKO','ION','IOF' ); const ccodes: array[0..24] of integer=( 0,4096,8192,12288,16384,20480,24576,{MRI} 30720,29696,29184,28928,28800,28736,28704,28688,28680,28676,28674,28673{7001} ,63488,62464,61952,61696,61568,61504 ); implementation uses Classes, SysUtils,unit1; procedure error(s: ansistring; ln: integer); begin haserror:=true; Form1.Output.Lines.Add('Line ('+IntToStr(ln+1)+') : '+s); end; procedure error(s: ansistring); begin haserror:=true; Form1.Output.Lines.Add('Fatal - '+s); end; procedure Tokenize(s: ansistring); var inword: boolean=false; //Getting a Word (AB, 034, A_1, -100, ...) i: integer; begin tc[lastline]:=0; i:=1; s:=upcase(s); while (true) do begin if (i>length(s)) then break; if (s[i] in [' ',#0,#9]) then //Skip whitespace begin inword:=false; inc(i); continue; end; if (s[i] in [':',',']) then //Signs begin inc(tc[lastline]); tk[lastline,tc[lastline]-1]:=s[i]; inword:=false; inc(i); continue; end; if (s[i]='/') then //Comments if (s[i+1]='/') then begin inword:=false; break; end else begin error('Unknown identifier ( / ) .' , lastline ); inc(i); inword:=false; continue; end; if (s[i] in ['A'..'Z']+['0'..'9']+['_','-','+']) then //Get a Word containing A..Z,0..9,_ begin if (not inword) then begin inword:=true; inc(tc[lastline]); end; tk[lastline,tc[lastline]-1]:=tk[lastline,tc[lastline]-1]+s[i]; inc(i); continue; end; error('Unknown Identifier ( '+s[i]+' ) .',lastline); inc(i); end; end; function isnum(s: ansistring):boolean; var i: integer; begin i:=1; if (length(s)=0) then exit(false); if (s[1] in ['-','+']) then inc(i); for i:=i to length(s) do if not(s[i] in ['0'..'9']) then exit(false); exit(true); end; function ishexnum(s: ansistring):boolean; var i: integer; begin i:=1; if (s[1] in ['-','+']) then inc(i); for i:=i to length(s) do if not(s[i] in ['0'..'9']+['A'..'F']) then exit(false); exit(true); end; function isbinnum(s: ansistring):boolean; var i: integer; begin i:=1; if (s[1] in ['-','+']) then inc(i); for i:=i to length(s) do if not(s[i] in ['0','1']) then exit(false); exit(true); end; function issep(s: ansistring):boolean; begin if (s=',') or (s=':') then exit(true) else exit(false); end; function isvalidname(s: ansistring):boolean; var i: integer; begin s:=upcase(s); if (length(s)<1) then exit(false); if (s[1]='_') then exit(false); if (s[1] in ['0'..'9']) then exit(false); for i:=1 to length(s) do if not (s[i] in ['0'..'9']+['A'..'Z']+['_']) then exit(false); exit(true); end; //////////////////////////////////////////// {----------------Convertions---------------} function ipower(b,e:int16):int16;inline; var i: integer; begin ipower:=1; for i:=0 to e do ipower:=ipower*b; end; function hex2dec(s: ansistring):int16; var i,r,p,sgn: int16; begin r:=0; sgn:=0; if (s[1]='-') then sgn:=-1; if (s[1]='+') then sgn:=1; for i:=1+abs(sgn) to length(s) do begin p:=ipower(16,length(s)-i+abs(sgn)-1); if (s[i] in ['0'..'9']) then r:=r+p*StrToInt(s[i]); if (s[i]='A') then r:=r+p*10; if (s[i]='B') then r:=r+p*11; if (s[i]='C') then r:=r+p*12; if (s[i]='D') then r:=r+p*13; if (s[i]='E') then r:=r+p*14; if (s[i]='F') then r:=r+p*15; end; if (sgn>=0) then exit(r) else exit(-r); end; function bin2dec(s: ansistring):int16;inline; // Binary string to decimal number var i,p,r,sgn: int16; begin r:=0; sgn:=0; if (s[1]='-') then sgn:=-1; if (s[1]='+') then sgn:=1; for i:=length(s) downto 1+abs(sgn) do begin p:=ipower(2,length(s)-i-abs(sgn)-1); r:=r+p*StrToInt(s[i]); end; if (sgn>=0) then exit(r) else exit(-r); end; function dec2hex(x,c: uint16): ansistring; var i,j: uint16; r,r2: ansistring; begin r:=''; r2:=''; for j:=1 to 4 do begin i:=x mod 16; x:=x div 16; if (i in [0..9]) then r:=InttoStr(i)+r; if (i=10) then r:='A'+r; if (i=11) then r:='B'+r; if (i=12) then r:='C'+r; if (i=13) then r:='D'+r; if (i=14) then r:='E'+r; if (i=15) then r:='F'+r; end; for j:=5-c to 4 do begin r2:=r2+r[j]; end; exit(r2); end; function dec2bin(x,c: uint16): ansistring; var i,j: uint16; r,r2: ansistring; begin r2:=''; r:=''; for j:=1 to 16 do begin i:=x mod 2; x:=x div 2; r:=InttoStr(i)+r; end; for j:=17-c to 16 do begin r2:=r2+r[j]; end; exit(r2); end; function shiftL(x: ansistring): ansistring; var i: integer; t: ansistring; begin t:=''; for i:=2 to length(x) do begin t:=t+x[i]; end; t:=t+x[1]; exit(t); end; function shiftR(x: ansistring): ansistring; var i: integer; t: ansistring; begin t:=x[16]; for i:=1 to length(x)-1 do begin t:=t+x[i]; end; exit(t); end; //////////////////////////////////////////// {-----------------Assembler----------------} function iscmd(s: ansistring):boolean; var i:integer; begin s:=upcase(s); for i:=0 to 24 do if (s=commands[i]) then exit(true); exit(false); end; function getcmdcode(s: ansistring):integer; var i:integer; begin s:=upcase(s); for i:=0 to 24 do if (s=commands[i]) then exit(ccodes[i]); end; function islabel(s: ansistring):boolean; var i: integer; begin for i:=0 to LBLCount do if (s=lbls[i].name) then exit(true); exit(false); end; function lblindex(s: ansistring):integer; var i: integer; begin for i:=0 to LBLCount do if (s=lbls[i].name) then exit(i); exit(-1); end; function listlabels:boolean; //List labels and also check for some errors var i: integer; begin LBLCount:=0; for i:=0 to lastline do begin if (tc[i]=0) then continue; if (isvalidname(tk[i,0])) then begin if (iscmd(tk[i,0])) then continue; if (tk[i,0]='HEX') or (tk[i,0]='BIN') or (tk[i,0]='DEC') then continue; if (tk[i,0]='ORG') then continue; if (tk[i,0]='END') then exit(true); if (islabel(tk[i,0])) then begin error('Dupplicate label name !',i); exit(false); end; if (issep(tk[i,1])) then begin lbls[LBLCount].name:=tk[i,0]; inc(LBLCount); end else begin if (tk[i,0]='HEX') or (tk[i,0]='BIN') or (tk[i,0]='DEC') then begin continue; end else begin error('Expected (,) or (:) after label name',i); exit(false); end; end; end else begin error('Unknown Identifier ('+tk[i,0]+')',i); exit(false); end; end; end; ///////////////////////////////////////// function isMRef(s: ansistring): boolean; var i: integer; begin for i:=0 to 6 do begin if (commands[i]=s) then exit(true); end; exit(false); end; function isRRef(s: ansistring): boolean; var i: integer; begin for i:=7 to 24 do begin if (commands[i]=s) then exit(true); end; exit(false); end; function MRef(i: integer):boolean; begin if (tc[ctline]<i+2) then begin error('Expected label name',ctline); exit(false); end; if (islabel(tk[ctline,i+1])) then //2 begin mem[origin].btype:=command; mem[origin].name:=tk[ctline,i+0]; mem[origin].code:=getcmdcode(tk[ctline,i+0]); mem[origin].linenum:=ctline; // For the label address to be found & set later mem[origin].lblindex:=lblindex(tk[ctline,i+1]); if (tc[ctline]>i+2) then //2.5 Check possibility of I's existense ?! if (tk[ctline,i+2]='I') then //3 Is it (I) there or is it error? begin mem[origin].I:=true; inc(ctline); inc(origin); exit(true); end else begin error('Expected (I) , Found Nonsense :-)',ctline); exit(false); end; inc(ctline); inc(origin); exit(true); end else begin error('Invalid label name ('+tk[ctline,i+1]+')',ctline); exit(false); end; end; function RRef(i: integer):boolean; begin mem[origin].btype:=command; mem[origin].name:=tk[ctline,i+0]; mem[origin].code:=getcmdcode(tk[ctline,i+0]); mem[origin].linenum:=ctline; mem[origin].lblindex:=-1; if (tc[ctline]>i+1) then begin error('Unknown identifier ('+tk[ctline,i+1]+')',ctline); exit(false); end; inc(origin); inc(ctline); exit(true); end; /////////////////////////////////////// procedure lbladdrfetch; var i:integer; begin for i:=0 to origin-1 do begin if (isMRef(mem[i].name)) then begin mem[i].val:=lbls[mem[i].lblindex].addr; end else if ((mem[i].btype=lb) or (mem[i].btype=data))and(mem[i].I) then begin mem[i].btype:=data; mem[i].val:=lbls[mem[i].lblindex].addr; end; end; end; ///////////////////////////////////////// //Included assembly procedures in a separate file// procedure ALM; //Assemble & Load in memory begin assembled:=false; if (haserror) then begin error('>> Errors exist - Assembly failed !'); exit; end; ctline:=0; origin:=0; {------------------ Find Labels ----------------------} if (not listlabels) then exit; {------------------ Look for ISR ---------------------} //Moved to step {----------------- Look for 1st ORG ------------------} //Moved to step {==================== Main Part ======================} while (ctline<=lastline) do begin if (tc[ctline]=0) then begin inc(ctline); continue; end; if (tk[ctline,0]='END') then begin Form1.Output.Lines.Add('>> Successfuly assembled !'); lbladdrfetch; assembled:=true; exit; end; //Included assembly conditions in a separate file// {$I asm.pas} end; //Form1.Output.Lines.Add('>> Successfuly assembled !'); error('Program has no END !'); exit; end; ///////////////////////////////////// procedure resetASM; var i,j: integer; begin origin:=0; AC:=0; AR:=0; E:=0; LBLCount:=0; for i:=0 to 4095 do begin mem[i].btype:=null; mem[i].name:=''; mem[i].code:=0; mem[i].I:=false; mem[i].lblindex:=-1; mem[i].linenum:=0; mem[i].val:=0; end; for i:=0 to 4095 do begin lbls[i].name:=''; lbls[i].addr:=0; end; for i:=0 to 4095 do begin tc[i]:=0; end; for i:=0 to 4095 do begin for j:=0 to 20 do setlength(tk[i,j],0); end; origin:=0; forg:=0; gotorigin:=false; lastline:=0; ctline:=0; haserror:=false; end; end.
unit TimerTypes; interface type ITickeable = interface function Enabled : boolean; function Tick : integer; end; type ITicker = interface // private function GetEnabled : boolean; procedure SetEnabled(which : boolean); // public function Count : integer; function GetTickeable(idx : integer) : ITickeable; procedure Attach(const which : ITickeable); procedure Detach(const which : ITickeable); property Enabled : boolean read GetEnabled write SetEnabled; end; implementation end.
{!DOCTOPIC} { Finder functions } const TM_SQDIFF = 0; TM_SQDIFF_NORMED = 1; TM_CCORR = 2; TM_CCORR_NORMED = 3; TM_CCOEFF = 4; TM_CCOEFF_NORMED = 5; {-------------------------------------------------------------------------------] Raw base for MatchTemplate [-------------------------------------------------------------------------------} {$IFNDEF CODEINSIGHT} type CVMat = record Data:Pointer; cols,rows:Int32; end; function __cvLoadFromMatrix(var Mat:TIntMatrix): CVMat; var w,h,y:Int32; data:TIntArray; begin SetLength(Data, Mat.Width()*Mat.Height()); W := Mat.Width(); H := Mat.Height(); for y:=0 to H-1 do MemMove(Mat[y][0], data[y*W], 4*W); Result.Data := nil; cv_MatFromData(PChar(data), W,H, Result.Data); Result.Cols := W; Result.Rows := H; SetLength(data, 0); end; procedure __cvFreeMatrix(var Matrix:CVMat); begin cv_FreeImage(Matrix.data); Matrix.cols := 0; Matrix.rows := 0; end; function __MatchTemplate(var img, templ:CVMat; Algo: Int8; Normed:Boolean=True): TFloatMatrix; var res:Pointer; Ptr:PFloat32; i,j,W,H:Int32; begin if (img.data = nil) or (templ.Data = nil) then begin RaiseWarning('One or both the images are empty!', ERR_WARNING); Exit(); end; if (templ.rows > img.rows) or (templ.cols > templ.cols) then begin RaiseWarning('Sub cannot be larger then Image', ERR_WARNING); Exit(); end; W := img.cols - templ.cols + 1; H := img.rows - templ.rows + 1; SetLength(Result, H,W); Ptr := PFloat32(cv_MatchTemplate(img.Data, templ.Data, algo, normed, res)); if (Ptr = nil) then Exit(); for i:=0 to H-1 do MemMove(Ptr[i*W]^, Result[i][0], 4*W); cv_FreeImage(res); end; {$ENDIF} {-------------------------------------------------------------------------------] [-------------------------------------------------------------------------------} {!DOCREF} { @method: function se.MatchColor(Image:TRafBitmap; Color:Int32; MatchAlgo:TCCorrMode; Colorspace:TColorSpace): TFloatMatrix; @desc: Correlates the color with the given image and stores the comparison results in the `Result`. [params] Image: Image to search in Color: Color to search for MatchAlgo: Algorithm used to compute difference: `CC_EUCLID`, `CC_EUCLID_NORMED`, `CC_EUCLID_SQUARED`, `CC_CHEB` or `CC_CHEB_NORMED` ColorSpace: Color-space used in computation: `_RGB_`, `_XYZ_`, `_LAB_` or `_LCH_` [/params] } function SimbaExt.MatchColor(Image:TRafBitmap; Color:Int32; MatchAlgo:TCCorrMode; ColorSpace:TColorSpace): TFloatMatrix; var Mat:TIntMatrix; begin Mat := Image.ToMatrix(); case ColorSpace of _RGB_: Result := exp_MatchColorRGB(Mat, Color, MatchAlgo); _XYZ_: Result := exp_MatchColorXYZ(Mat, Color, MatchAlgo); _LAB_: Result := exp_MatchColorLAB(Mat, Color, MatchAlgo); _LCH_: Result := exp_MatchColorLCH(Mat, Color, MatchAlgo); end; end; {!DOCREF} { @method: function se.FindColorEx(var TPA:TPointArray; Color:Integer; Area:TBox; Similarity:Single; Colorspace:TColorSpace): Boolean; @desc: Search for a spesific color on your screen with a tolerance.[br] `_LAB_` should be very fast compared to CTS(3) in simba. I assume around 7-9x faster in general. `_LCH_` which is LAB-color measured another way should also be very fast, almost as fast as `_LAB_` for most uses. Due to the way this function works, `_RGB_` correlation is slower then `CTS(1)`, and `CTS(0)`. [params] TPA: The resulting points Color: The color to search for Area: A `TBox` of where to search. Similarity: `0.0` to `1.0` where `+/-1.0` should be exact match. Colorspace: Colorspace used in computation: `_RGB_, _XYZ_, _LAB_ and _LCH_` [/params] } function SimbaExt.FindColorEx(var TPA:TPointArray; Color:Int32; Area:TBox; Similarity:Single; Colorspace:TColorSpace): Boolean; var W,H:Int32; Corr: TFloatMatrix; BMP:TRafBitmap; begin Result := False; GetClientDimensions(W,H); if (Area.X2 >= W) or (Area.X2 <= -1) then Area.X2 := W-1; if (Area.Y2 >= H) or (Area.Y2 <= -1) then Area.Y2 := H-1; if (Area.X1 > Area.X2) or (Area.Y1 > Area.Y2) then Exit; BMP.FromClient(Area.X1,Area.Y1,Area.X2,Area.Y2); case Colorspace of _RGB_: Corr := exp_MatchColorRGB(BMP.ToMatrix(), Color, CC_EUCLID_NORMED); _XYZ_: Corr := exp_MatchColorXYZ(BMP.ToMatrix(), Color, CC_EUCLID_NORMED); _LAB_: Corr := exp_MatchColorLAB(BMP.ToMatrix(), Color, CC_EUCLID_NORMED); _LCH_: Corr := exp_MatchColorLCH(BMP.ToMatrix(), Color, CC_EUCLID_NORMED); end; BMP.Free(); TPA := Corr.Indices(Similarity, __GE__); Result := Length(TPA) < 0; if not(Result) or (Area.X1=0) and (Area.Y1 = 0) then Exit; OffsetTPA(TPA, Point(Area.X1, Area.Y1)); end; {!DOCREF} { @method: function se.FindTemplate(out PT:TPoint; Template:TRafBitmap; Area:TBox; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; @desc: Search for a template image on your screen with a tolerance, returns the point where it best matched. [params] PT: Resulting point Template: Template image to search for Area: A `TBox` of where to search. Similarity: `-1.0` to `1.0` where `+/-1.0` should be exact match. MatchAlgo: Comparison algorithm -> `TM_SQDIFF_NORMED = 1`, `TM_CCORR_NORMED = 3`, `TM_CCOEFF_NORMED = 5` [/params] } function SimbaExt.FindTemplate(out PT:TPoint; Template:TRafBitmap; Area:TBox; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; var W,H:Int32; Corr:TFloatMatrix; Screen:TRafBitmap; templ,img:CVMat; begin if (MatchAlgo = 0) or (MatchAlgo = 2) or (MatchAlgo = 4) then begin RaiseWarning('se.FindTemplate only supports NORMED MatchAlgo: 1, 3 or 5', ERR_WARNING); Exit(); end; GetClientDimensions(W,H); if (Area.X2 >= W) or (Area.X2 <= -1) then Area.X2 := W-1; if (Area.Y2 >= H) or (Area.Y2 <= -1) then Area.Y2 := H-1; if (Area.X1 > Area.X2) or (Area.Y1 > Area.Y2) then Exit; Screen.FromClient(Area.x1,Area.y1,Area.x2,Area.y2); img := __cvLoadFromMatrix(Screen.ToMatrix()); templ := __cvLoadFromMatrix(Template.ToMatrix()); Corr := __MatchTemplate(img,templ,MatchAlgo,False); case (MatchAlgo = TM_SQDIFF_NORMED) and True of True: PT := Corr.ArgMin(); False: PT := Corr.ArgMax(); end; Result := Corr[PT.y][PT.x] > Similarity; PT.y := PT.y + Area.x1; PT.x := PT.x + Area.y1; Screen.Free(); __cvFreeMatrix(img); __cvFreeMatrix(templ); end; {!DOCREF} { @method: function se.FindTemplate(out PT:TPoint; Image, Templ:TRafBitmap; Area:TBox; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; overload; @desc: Search for a template `templ` in the `Image` with a tolerance, returns the point where it best matched. [params] PT: Resulting point Image: Image to search in. Templ: Template image to search for. Similarity: `-1.0` to `1.0` where `+/-1.0` should be exact match. MatchAlgo: Comparison algorithm -> `TM_SQDIFF_NORMED = 1`, `TM_CCORR_NORMED = 3`, TM_CCOEFF_NORMED = 5` [/params] } function SimbaExt.FindTemplate(out PT:TPoint; Image, Templ:TRafBitmap; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; overload; var Corr:TFloatMatrix; patch,img:CVMat; begin if (MatchAlgo = 0) or (MatchAlgo = 2) or (MatchAlgo = 4) then begin RaiseWarning('se.FindTemplate only supports NORMED MatchAlgo: 1, 3 or 5', ERR_WARNING); Exit(); end; if not((Image.Width > 0) and (Image.Height > 0)) then RaiseException(erOutOfRange,'Image is Empty'); if not((Templ.Width > 0) and (Templ.Height > 0)) then RaiseException(erOutOfRange,'Templ is Empty'); img := __cvLoadFromMatrix(Image.ToMatrix()); patch := __cvLoadFromMatrix(Templ.ToMatrix()); Corr := __MatchTemplate(img,patch,MatchAlgo,False); case (MatchAlgo = TM_SQDIFF_NORMED) and True of True: PT := Corr.ArgMin(); False: PT := Corr.ArgMax(); end; Result := Corr[PT.y][PT.x] > Similarity; __cvFreeMatrix(img); __cvFreeMatrix(patch); end; {!DOCREF} { @method: function se.FindTemplateEx(out TPA:TPoint; Templ:TRafBitmap; Area:TBox; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; @desc: Search for a template image `Templ` on your screen with a tolerance, returns all the points over the given similarity. [params] TPA: Resulting points Template: Template image to search for Area: A `TBox` of where to search. Similarity: `-1.0` to `1.0` where `+/-1.0` should be exact match. MatchAlgo: Comparison algorithm -> `TM_SQDIFF_NORMED = 1`, `TM_CCORR_NORMED = 3`, `TM_CCOEFF_NORMED = 5` [/params] } function SimbaExt.FindTemplateEx(out TPA:TPointArray; Templ:TRafBitmap; Area:TBox; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; var W,H:Int32; Corr:TFloatMatrix; Screen:TRafBitmap; patch,img:CVMat; begin if (MatchAlgo = 0) or (MatchAlgo = 2) or (MatchAlgo = 4) then begin RaiseWarning('se.FindTemplate only supports NORMED MatchAlgo: 1, 3 or 5', ERR_WARNING); Exit(); end; GetClientDimensions(W,H); if (Area.X2 >= W) or (Area.X2 <= -1) then Area.X2 := W-1; if (Area.Y2 >= H) or (Area.Y2 <= -1) then Area.Y2 := H-1; if (Area.X1 > Area.X2) or (Area.Y1 > Area.Y2) then Exit; Screen.FromClient(Area.x1,Area.y1,Area.x2,Area.y2); img := __cvLoadFromMatrix(Screen.ToMatrix()); patch := __cvLoadFromMatrix(Templ.ToMatrix()); Corr := __MatchTemplate(img,patch,MatchAlgo,False); case (MatchAlgo = TM_SQDIFF_NORMED) and True of True: TPA := Corr.Indices(1.0-Similarity,__LE__); False: TPA := Corr.Indices(Similarity,__GE__); end; Result := Length(TPA) > 0; Screen.Free(); __cvFreeMatrix(img); __cvFreeMatrix(patch); if not(Result) then Exit(); OffsetTPA(TPA, Point(Area.X1, Area.Y1)); end; {!DOCREF} { @method: function se.FindTemplateEx(out TPA:TPointArray; Image, Templ:TRafBitmap; Area:TBox; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; overload; @desc: Search for a template `Templ` in the `Image` with a tolerance, returns the point where it best matched. [params] TPA: Resulting points Image: Image to search in. Templ: Template image to search for. Similarity: `-1.0` to `1.0` where `+/-1.0` should be exact match. MatchAlgo: Comparison algorithm -> `TM_SQDIFF_NORMED = 1`, `TM_CCORR_NORMED = 3`, `TM_CCOEFF_NORMED = 5` [/params] Example: [code=pascal] var i:Int32; TPA:TPointArray; ATPA:T2DPointArray; BMP,SUB:TRafBitmap; begin BMP.Open('lenas.png'); SUB.Open('lena_sub.png'); se.FindTemplateEx(TPA, BMP, SUB, 0.60, TM_CCOEFF_NORMED); //cluster to remove neighburhood-noise points ATPA := TPA.Cluster(3,False); //draw a box around each location for i:=0 to High(ATPA) do begin TPA[0] := ATPA[i].Mean(); TPA := ToBox(TPA[0].x, TPA[0].y, TPA[0].x+Sub.Width, TPA[0].y+Sub.Height).ToCoords(); BMP.SetPixels(se.ConnectTPA(TPA), 16777215); BMP.SetPixels(se.TPACross(TPA[0], 5), 255); end; BMP.Debug(); SUB.Free(); BMP.Free(); end. [/code] Output: [img]http://slackworld.net/downloads/FindTemplateEx.png[/img] } function SimbaExt.FindTemplateEx(out TPA:TPointArray; Image, Templ:TRafBitmap; Similarity:Single; MatchAlgo: Int8 = 5): Boolean; overload; var Corr:TFloatMatrix; patch,img:CVMat; begin if (MatchAlgo = 0) or (MatchAlgo = 2) or (MatchAlgo = 4) then begin RaiseWarning('se.FindTemplate only supports NORMED MatchAlgo: 1, 3 or 5', ERR_WARNING); Exit(); end; img := __cvLoadFromMatrix(Image.ToMatrix()); patch := __cvLoadFromMatrix(Templ.ToMatrix()); Corr := __MatchTemplate(img,patch,MatchAlgo,False); case (MatchAlgo = TM_SQDIFF_NORMED) and True of True: TPA := Corr.Indices(1.0-Similarity,__LE__); False: TPA := Corr.Indices(Similarity,__GE__); end; Result := Length(TPA) > 0; __cvFreeMatrix(img); __cvFreeMatrix(patch); end; {!DOCREF} { @method: function se.MatchTemplate(Image, Templ:TRafBitmap; MatchAlgo: UInt8; Normalize:Boolean=False): TFloatMatrix; @desc: The function slides through `image`, compares the overlapped patches of size w*h against `templ` using the specified method and stores the comparison results in the `Result`. [params] Image: Image where the search is running. Templ: Searched template. It must be not greater than the source image. MatchAlgo: Comparison algorithm -> `TM_SQDIFF`, `TM_SQDIFF_NORMED`, `TM_CCORR`, `TM_CCORR_NORMED`, `TM_CCOEFF`, `TM_CCOEFF_NORMED` Normalize: Normalizes the result between `0.0` and `1.0` [/params] } function SimbaExt.MatchTemplate(Image, Templ:TRafBitmap; MatchAlgo: UInt8; Normalize:Boolean=False): TFloatMatrix; var W,H:Int32; patch,img:CVMat; begin img := __cvLoadFromMatrix(Image.ToMatrix()); patch := __cvLoadFromMatrix(Templ.ToMatrix()); Result := __MatchTemplate(img,patch,MatchAlgo,Normalize); __cvFreeMatrix(img); __cvFreeMatrix(patch); end; {!DOCREF} { @method: function se.ImFindColorTolEx(const ImgArr:TIntMatrix; var TPA:TPointArray; Color, Tol:Integer): Boolean; @desc: Deprecated, will raise a deprecation-warning. } function SimbaExt.ImFindColorTolEx(const ImgArr:TIntMatrix; var TPA:TPointArray; Color, Tol:Integer): Boolean; begin RaiseWarning('ImFindColorTolEx is deprecated and will be removed, use "se.FindColorEx', ERR_DEPRECATED); Result := exp_ImFindColorTolEx(ImgArr, TPA, Color, Tol); end; {!DOCREF} { @method: function se.ImFindColorsTolEx(const ImgArr:TIntMatrix; var TPA:TPointArray; Colors:TIntegerArray; Tol:Integer): Boolean; @desc: Deprecated, will raise a deprecation-warning. } function SimbaExt.ImFindColorsTolEx(const ImgArr:TIntMatrix; var TPA:TPointArray; Colors:TIntegerArray; Tol:Integer): Boolean; begin RaiseWarning('ImFindColorsTolEx is deprecated and will be removed, use "se.FindColorEx', ERR_DEPRECATED); Result := exp_ImFindColorsTolEx(ImgArr, TPA, Colors, Tol); end; {!DOCREF} { @method: function se.ImFindColorsTolExLCH(const ImgArr:TIntMatrix; var TPA:TPointArray; Colors:TIntegerArray; Tol:Integer): Boolean; @desc: Deprecated, will raise a deprecation-warning. } function SimbaExt.ImFindColorTolExLCH(const ImgArr:TIntMatrix; var TPA:TPointArray; Color, ColorTol, LightTol:Integer): Boolean; begin RaiseWarning('ImFindColorTolExLCH is deprecated and will be removed, use "se.FindColorEx', ERR_DEPRECATED); Result := exp_ImFindColorTolExLCH(ImgArr, TPA, Color, ColorTol, LightTol); end; {!DOCREF} { @method: function se.ImFindColorsTolExLAB(const ImgArr:TIntMatrix; var TPA:TPointArray; Colors:TIntegerArray; Tol:Integer): Boolean; @desc: Deprecated, will raise a deprecation-warning. } function SimbaExt.ImFindColorTolExLAB(const ImgArr:TIntMatrix; var TPA:TPointArray; Color, ColorTol, LightTol:Integer): Boolean; begin RaiseWarning('ImFindColorTolExLAB is deprecated and will be removed, use "se.FindColorEx"', ERR_DEPRECATED); Result := exp_ImFindColorTolExLAB(ImgArr, TPA, Color, ColorTol, LightTol); 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.Graphics; interface uses System.Types, System.UITypes, System.Classes, FMX.Graphics; function RoundLogicPointsToMatchPixel(const LogicPoints: Single; const AtLeastOnePixel: Boolean = False): Single; function RoundToPixel(const Source: TRectF; const AThickness: Single = 1): TRectF; overload; function RoundToPixel(const Source: TPointF; const AThickness: Single = 1): TPointF; overload; function RoundToPixel(const Source: Single; const AThickness: Single = 1): Single; overload; function MakeColor(const ASource: TAlphaColor; AOpacity: Single): TAlphaColor; function Create9PatchShadow(const ASize: TSizeF; const AColor: TAlphaColor): TBitmap; implementation uses System.Math, System.SysUtils, FMX.Forms, FMX.Platform, FGX.Helpers, FGX.Consts, FGX.Asserts, FMX.Types, FMX.Filter.Custom, FMX.Filter, System.UIConsts, FMX.Effects; function RoundLogicPointsToMatchPixel(const LogicPoints: Single; const AtLeastOnePixel: Boolean = False): Single; var Pixels: Single; begin Pixels := Round(LogicPoints * Screen.Scale); if (Pixels < 1) and AtLeastOnePixel then Pixels := 1.0; Result := Pixels / Screen.Scale; end; function RoundToPixel(const Source: Single; const AThickness: Single = 1): Single; overload; begin Result := Source; if SameValue(Round(Source * Screen.Scale), Source * Screen.Scale, EPSILON_SINGLE) then Result := Source - AThickness / 2; end; function RoundToPixel(const Source: TPointF; const AThickness: Single = 1): TPointF; overload; begin Result.X := RoundToPixel(Source.X); Result.Y := RoundToPixel(Source.Y); end; function RoundToPixel(const Source: TRectF; const AThickness: Single = 1): TRectF; overload; begin Result.Left := RoundToPixel(Source.Left); Result.Top := RoundToPixel(Source.Top); Result.Right := RoundToPixel(Source.Right); Result.Bottom := RoundToPixel(Source.Bottom); end; function MakeColor(const ASource: TAlphaColor; AOpacity: Single): TAlphaColor; begin AssertInRange(AOpacity, 0, 1); Result := ASource; TAlphaColorRec(Result).A := Round(255 * AOpacity); end; function Create9PatchShadow(const ASize: TSizeF; const AColor: TAlphaColor): TBitmap; const AShadowThickness = 5; CornerRadius = 2; var CenterRect: TRectF; Filter: TFilter; ContentMargin: Single; begin Result := TBitmap.Create(Round(ASize.Width + 2 * AShadowThickness), Round(ASize.Height + 2 * AShadowThickness)); Result.Clear(TAlphaColorRec.Null); with Result.Canvas do if BeginScene then try CenterRect := TRectF.Create(TPointF.Create(AShadowThickness, AShadowThickness), ASize.Width, ASize.Height); Fill.Color := AColor; Fill.Kind := TBrushKind.Solid; FillRect(CenterRect, 0, 0, AllCorners, 1); finally EndScene; end; Filter := TFilterManager.FilterByName('GlowFilter'); if Assigned(Filter) then begin Filter.ValuesAsColor['Color'] := AColor; Filter.ValuesAsBitmap['Input'] := Result; Filter.ValuesAsFloat['BlurAmount'] := 0.3; Filter.ApplyWithoutCopyToOutput; TFilterManager.FilterContext.CopyToBitmap(Result, TRect.Create(0, 0, Result.Width, Result.Height)); end; ContentMargin := AShadowThickness + CornerRadius / 2; with Result.Canvas do if BeginScene then try CenterRect := TRectF.Create(TPointF.Create(AShadowThickness, AShadowThickness), ASize.Width, ASize.Height); Fill.Color := AColor; Fill.Kind := TBrushKind.Solid; FillRect(CenterRect, CornerRadius, CornerRadius, AllCorners, 1); Stroke.Color := TAlphaColorRec.Black; StrokeThickness := 1; Stroke.Kind := TBrushKind.Solid; DrawLine(TPointF.Create(0.5, ContentMargin + 0.5), TPointF.Create(0.5, ASize.Height + 2 * AShadowThickness - ContentMargin - 0.5), 1); DrawLine(TPointF.Create(ContentMargin + 0.5, 0.5), TPointF.Create(ASize.Width + AShadowThickness - 0.5, 0.5), 1); // DrawLine(TPointF.Create(ASize.Width + 2 * AShadowThickness - 0.5, ContentMargin + 0.5), // TPointF.Create(ASize.Width + 2 * AShadowThickness - 0.5, ASize.Height + AShadowThickness - 0.5), 1); // DrawLine(TPointF.Create(ContentMargin + 0.5, ASize.Height + 2 * AShadowThickness - 0.5), // TPointF.Create(ASize.Width + 2 * AShadowThickness - ContentMargin - 0.5, ASize.Height + 2 * AShadowThickness - 0.5), 1); finally EndScene; end; end; end.
{ Programmname: Befreiungsaufgabe Befreiungsaufgabe PS1 WS 2012 Minesweeper in Pascal ohne GUI, nur Textausgabe. Author: Gerrit Paepcke Erstelldatum: 9.11.2012 Bisherige Änderungen: keine } unit Udisplay; interface type Score = RECORD Name: String[50]; // Name des Spielers in der Highscore Time: Double; // Spieldauer in sec END; procedure showStandartHeader(); procedure showGameScreen(curser_x, curser_y:Byte; bomb_count,flagged_fields:Byte; time:Double; showBombs:Boolean = false); procedure showIndexScreen(selected_index:Byte); procedure showSettingsScreen(selected_index, bomb_percentage:Byte); procedure showHighscoreScreen(gamescore:array of Score); implementation uses SysUtils, Dos, crt, Ulogic; const game_offset_x = 2; // Gameoffset auf der X Achse game_offset_y = 4; // Gameoffset auf der Y Achse procedure showStandartHeader(); // Gibt einen Standartoutput aus begin clrscr; TextColor(White); TextBackground(Black); writeln('Minesweeper by Gerrit Paepcke'); writeln; end; procedure showGameScreen(curser_x, curser_y:Byte; bomb_count,flagged_fields:Byte; time:Double; showBombs:Boolean = false); // Anzeige des Game Screens // param curser_x : Byte = Aktuelle X Position des markierten Feldes // param curser_y : Byte = Aktuelle Y Position des markierten Feldes // param bomb_count : Byte = Anzahl aller Bomben im Spielfeld // param flagged_fields : Byte = Anzahl aller markierter Felder // param time : Double = Derzeitige Spielzeit in Sec var x,y,nearbombs : integer; begin showStandartHeader(); writeln('Spielfeld: '+IntToStr((Ulogic.CMax_X-Ulogic.CMin_X)+1)+'x'+IntToStr((Ulogic.CMax_Y-Ulogic.CMin_Y)+1)); writeln; gotoxy(Ulogic.CMax_X+game_offset_x+3,game_offset_y+2); writeln('Bombem auf dem Spielfeld: '+IntToStr(bomb_count)); gotoxy(Ulogic.CMax_X+game_offset_x+3,game_offset_y+3); writeln('Markierte Felder (Flaggen F): '+IntToStr(flagged_fields)); gotoxy(Ulogic.CMax_X+game_offset_x+3,game_offset_y+4); writeln('Spieldauer: '+FloatToStrF(time,ffFixed,10,2)+'s'); gotoxy(Ulogic.CMax_X+game_offset_x+3,game_offset_y+6); writeln('Auswahl: Arrow Keys, Flagge setzen: Enter'); gotoxy(Ulogic.CMax_X+game_offset_x+3,game_offset_y+7); writeln('Aufdecken: Space, Zum Hauptmenu: Back / b'); for x:=Ulogic.CMin_X to Ulogic.CMax_X do begin for y :=Ulogic.CMin_Y to Ulogic.CMax_Y do begin gotoxy(x+game_offset_x,y+game_offset_y); if (x = curser_x) and (y = curser_y) then begin TextColor(Black); TextBackground(White); end; case Ulogic.Spielfeld[x,y] of fdFlagge_mBombe: begin if (showBombs = true) then begin TextColor(Yellow); write('F'); end else begin TextColor(Green); write('F'); end; end; fdFlagge_oBombe: begin TextColor(Green); write('F'); end; fdBombe: begin if (showBombs = true) then begin TextColor(Yellow); write('X'); end else begin TextColor(White); write('#'); end; end; fdAufgedeckt: begin nearbombs := Ulogic.countNearBombs(x,y); if (nearbombs = 0) then begin TextColor(White); write(' '); end else if (nearbombs = 1) then begin TextColor(9); write(nearbombs); end else if (nearbombs = 2) then begin TextColor(10); write(nearbombs); end else if (nearbombs = 3) then begin TextColor(12); write(nearbombs); end else if (nearbombs = 4) then begin TextColor(13); write(nearbombs); end else begin TextColor(14); write(nearbombs); end; end; fdVerborgen: begin TextColor(White); write('#'); end; end; TextColor(White); TextBackground(Black); end; end; gotoxy(curser_x+game_offset_x,curser_y+game_offset_y); end; procedure showIndexScreen(selected_index:Byte); // Anzeige des Hauptmenüs // param selected_index : Byte = Derzeit ausgewählter Menüpunkt begin showStandartHeader(); writeln('Hauptmenu'); writeln; if selected_index = 1 then begin TextColor(Black); TextBackground(White); end else begin TextColor(White); TextBackground(Black); end; writeln('Neues Spiel'); if selected_index = 2 then begin TextColor(Black); TextBackground(White); end else begin TextColor(White); TextBackground(Black); end; writeln('Highscore anzeigen'); if selected_index = 3 then begin TextColor(Black); TextBackground(White); end else begin TextColor(White); TextBackground(Black); end; writeln('Einstellungen'); if selected_index = 4 then begin TextColor(Black); TextBackground(White); end else begin TextColor(White); TextBackground(Black); end; writeln('Programm schliessen'); TextColor(White); TextBackground(Black); writeln; writeln; writeln('Steuerung: Up/Down, Auswahl: Enter'); end; procedure showSettingsScreen(selected_index,bomb_percentage:Byte); // Anzeige der Einstellungen // param selected_index : Byte = Derzeit ausgewählte Einstellung // bomb_percentage : Byte = Wahrscheinlichkeit von Bomben im Spielfeld begin showStandartHeader(); writeln('Einstellungen'); writeln; write('Bomben pro Spiel: '); if selected_index = 1 then begin TextColor(Black); TextBackground(White); end else begin TextColor(White); TextBackground(Black); end; writeln(IntToStr(bomb_percentage)+'%'); TextColor(White); TextBackground(Black); writeln; writeln; writeln('Steuerung: Up/Down, Wert wechseln: Left/Right, Zum Hauptmenu: Back / b'); end; procedure showHighscoreScreen(gamescore:array of Score); // Anzeige der Highscore // param gamescore : Array of Score = Derzeitige Highscore var i : byte; begin showStandartHeader(); writeln('Highscore'); writeln; for i:=0 to 2 do begin writeln(IntToStr(i+1)+'. Platz: '+gamescore[i].Name+' Zeit: '+FloatToStrF(gamescore[i].Time,ffFixed,10,2)+'s'); // Formatierung des Double Wertes auf max. 2 Stellen nach dem Komma end; writeln; writeln; writeln('Zum Hauptmenu: Back / b'); end; end.
unit enet_consts; (* enet freepascal conversion constant and some functions 1.3.12 freepascal - fix time function - add missing commnet in Packet Flag - fix shift operator on constants - fix decaration of invalid socket *) // for C/C++ interface compatiblity. but useless {.$DEFINE PACK} interface uses {$ifdef WINDOWS} WinSock2 {$else} Sockets {$endif} ; type // types.h <----- enet_uint32 = longword; enet_uint16 = word; enet_uint8 = byte; // -----> types.h penet_uint32 = ^enet_uint32; penet_uint16 = ^enet_uint16; penet_uint8 = pbyte; // for pointer access ppenet_uint8 = ^penet_uint8; //enet_uint8array = array[0..0] of enet_uint8; penet_uint8array = pchar; // ^enet_uint8array; enet_size_t = longword; ENetProtocolCommand = integer; var // enet.h <----- ENetVersion : enet_uint32; // -----> enet.h const // time.h <----- ENET_TIME_OVERFLOW = 86400000; // -----> time.h // enet.h <----- ENET_VERSION_MAJOR = 1; ENET_VERSION_MINOR = 3; ENET_VERSION_PATCH = 12; ENET_VERSION = (ENET_VERSION_MAJOR shl 16) or (ENET_VERSION_MINOR shl 8) or ENET_VERSION_PATCH; //ENetVersion; ENET_SOCKET_TYPE_STREAM = 1; ENET_SOCKET_TYPE_DATAGRAM = 2; //ENetSocketType; ENET_SOCKET_WAIT_NONE = 0; ENET_SOCKET_WAIT_SEND = (1 shl 0); ENET_SOCKET_WAIT_RECEIVE = (1 shl 1); ENET_SOCKET_WAIT_INTERRUPT = (1 shl 2); //ENetSocketWait; ENET_SOCKOPT_NONBLOCK = 1; ENET_SOCKOPT_BROADCAST = 2; ENET_SOCKOPT_RCVBUF = 3; ENET_SOCKOPT_SNDBUF = 4; ENET_SOCKOPT_REUSEADDR = 5; ENET_SOCKOPT_RCVTIMEO = 6; ENET_SOCKOPT_SNDTIMEO = 7; ENET_SOCKOPT_ERROR = 8; ENET_SOCKOPT_NODELAY = 9; //ENetSocketOption; ENET_SOCKET_SHUTDOWN_READ = 0; ENET_SOCKET_SHUTDOWN_WRITE = 1; ENET_SOCKET_SHUTDOWN_READ_WRITE = 2; //ENetSocketShutdown (** * Portable internet address structure. * * The host must be specified in network byte-order, and the port must be in host * byte-order. The constant ENET_HOST_ANY may be used to specify the default * server host. The constant ENET_HOST_BROADCAST may be used to specify the * broadcast address (255.255.255.255). This makes sense for enet_host_connect, * but not for enet_host_create. Once a server responds to a broadcast, the * address is updated from ENET_HOST_BROADCAST to the server's actual IP address. *) ENET_HOST_ANY = 0; (**< specifies the default server host *) ENET_HOST_BROADCAST_= longword($FFFFFFFF); (**< specifies a subnet-wide broadcast *) ENET_PORT_ANY = 0; (**< specifies that a port should be automatically chosen *) (** * Packet flag bit constants. * * The host must be specified in network byte-order, and the port must be in * host byte-order. The constant ENET_HOST_ANY may be used to specify the * default server host. @sa ENetPacket *) (** packet must be received by the target peer and resend attempts should be * made until the packet is delivered *) ENET_SOCKET_NULL = Tsocket({$ifdef WINDOWS}INVALID_SOCKET{$else}-1{$endif}); (** packet must be received by the target peer and resend attempts should be * made until the packet is delivered *) ENET_PACKET_FLAG_RELIABLE = (1 shl 0); (** packet will not be sequenced with other packets * not supported for reliable packets *) ENET_PACKET_FLAG_UNSEQUENCED = (1 shl 1); (** packet will not allocate data, and user must supply it instead *) ENET_PACKET_FLAG_NO_ALLOCATE = (1 shl 2); (** packet will be fragmented using unreliable (instead of reliable) sends * if it exceeds the MTU *) ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT = (1 shl 3); (** whether the packet has been sent from all queues it has been entered into *) ENET_PACKET_FLAG_SENT = (1 shl 8); //ENetPacketFlag // -----> enet.h // protocol.h <----- ENET_PROTOCOL_MINIMUM_MTU = 576; ENET_PROTOCOL_MAXIMUM_MTU = 4096; ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32; ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096; ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 65536; ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1; ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255; ENET_PROTOCOL_MAXIMUM_PEER_ID = $0FFF; // ENET_PROTOCOL_MAXIMUM_PACKET_SIZE = 1024 * 1024 * 1024; ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024; // ENET_PROTOCOL_COMMAND_NONE = 0; ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1; ENET_PROTOCOL_COMMAND_CONNECT = 2; ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3; ENET_PROTOCOL_COMMAND_DISCONNECT = 4; ENET_PROTOCOL_COMMAND_PING = 5; ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6; ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7; ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8; ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9; ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10; ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11; ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12; ENET_PROTOCOL_COMMAND_COUNT = 13; ENET_PROTOCOL_COMMAND_MASK = $0F; //ENetProtocolCommand ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 shl 7); ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 shl 6); ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = (1 shl 14); ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 shl 15); ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_COMPRESSED or ENET_PROTOCOL_HEADER_FLAG_SENT_TIME; ENET_PROTOCOL_HEADER_SESSION_MASK = (3 shl 12); ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12; //ENetProtocolFlag // -----> protocol.h // enet.h <----- (** * An ENet event type, as specified in @ref ENetEvent. *) (** no event occurred within the specified time limit *) ENET_EVENT_TYPE_NONE = 0; (** a connection request initiated by enet_host_connect has completed. * The peer field contains the peer which successfully connected. *) ENET_EVENT_TYPE_CONNECT = 1; (** a peer has disconnected. This event is generated on a successful * completion of a disconnect initiated by enet_pper_disconnect, if * a peer has timed out, or if a connection request intialized by * enet_host_connect has timed out. The peer field contains the peer * which disconnected. The data field contains user supplied data * describing the disconnection, or 0, if none is available. *) ENET_EVENT_TYPE_DISCONNECT = 2; (** a packet has been received from a peer. The peer field specifies the * peer which sent the packet. The channelID field specifies the channel * number upon which the packet was received. The packet field contains * the packet that was received; this packet must be destroyed with * enet_packet_destroy after use. *) ENET_EVENT_TYPE_RECEIVE = 3; //ENetEventType; ENET_PEER_STATE_DISCONNECTED = 0; ENET_PEER_STATE_CONNECTING = 1; ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2; ENET_PEER_STATE_CONNECTION_PENDING = 3; ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4; ENET_PEER_STATE_CONNECTED = 5; ENET_PEER_STATE_DISCONNECT_LATER = 6; ENET_PEER_STATE_DISCONNECTING = 7; ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8; ENET_PEER_STATE_ZOMBIE = 9; //ENetPeerState; //#ifndef ENET_BUFFER_MAXIMUM //#define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS) ENET_BUFFER_MAXIMUM = (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS); //#endif ENET_HOST_RECEIVE_BUFFER_SIZE = 256 * 1024; ENET_HOST_SEND_BUFFER_SIZE = 256 * 1024; ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000; ENET_HOST_DEFAULT_MTU = 1400; ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024; ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024; ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 500; ENET_PEER_DEFAULT_PACKET_THROTTLE = 32; ENET_PEER_PACKET_THROTTLE_SCALE = 32; ENET_PEER_PACKET_THROTTLE_COUNTER = 7; ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2; ENET_PEER_PACKET_THROTTLE_DECELERATION = 2; ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000; ENET_PEER_PACKET_LOSS_SCALE = (1 shl 16); ENET_PEER_PACKET_LOSS_INTERVAL = 10000; ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024; ENET_PEER_TIMEOUT_LIMIT = 32; ENET_PEER_TIMEOUT_MINIMUM = 5000; ENET_PEER_TIMEOUT_MAXIMUM = 30000; ENET_PEER_PING_INTERVAL_ = 500; ENET_PEER_UNSEQUENCED_WINDOWS = 64; ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024; ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32; ENET_PEER_RELIABLE_WINDOWS = 16; ENET_PEER_RELIABLE_WINDOW_SIZE = $1000; ENET_PEER_FREE_RELIABLE_WINDOWS = 8; // enet.h <----- type pENetPacket = ^ENetPacket; ENETPacketFreeCallback = procedure (Packet : pENetPacket); stdcall; (** * ENet packet structure. * * An ENet data packet that may be sent to or received from a peer. The shown * fields should only be read and never modified. The data field contains the * allocated data for the packet. The dataLength fields specifies the length * of the allocated data. The flags field is either 0 (specifying no flags), * or a bitwise-or of any combination of the following flags: * * ENET_PACKET_FLAG_RELIABLE - packet must be received by the target peer * and resend attempts should be made until the packet is delivered * * ENET_PACKET_FLAG_UNSEQUENCED - packet will not be sequenced with other packets * (not supported for reliable packets) * * ENET_PACKET_FLAG_NO_ALLOCATE - packet will not allocate data, and user must supply it instead @sa ENetPacketFlag *) // -----> enet.h // callbacks.h <----- ENETCALLBACK_malloc = function (size : longword):pointer; stdcall; ENETCALLBACK_free = procedure (ptr : pointer); stdcall; ENETCALLBACK_nomemory = procedure; stdcall; pENetCallbacks = ^ENetCallbacks; ENetCallbacks = record malloc : ENETCALLBACK_malloc; free : ENETCALLBACK_free; nomemory : ENETCALLBACK_nomemory; end; // -----> callbacks.h pENetAddress = ^ENetAddress; ENetAddress = record host : enet_uint32; port : enet_uint16; end; // list.h <----- pENetListNode = ^ENetListNode; ENetListNode = record next : pENetListNode; previous : pENetListNode; end; ENetListIterator = pENetListNode; pENetList = ^ENetList; ENetList = record sentinel : ENetListNode; end; // -----> list.h {$push} {$PackRecords 1} // protocol.h <----- pENetProtocolHeader = ^ENetProtocolHeader; ENetProtocolHeader = record peerID : enet_uint16; sentTime : enet_uint16; end; ENetProtocolCommandHeader = record command :enet_uint8; channelID :enet_uint8; reliableSequenceNumber : enet_uint16; end; ENetProtocolAcknowledge = record header : ENetProtocolCommandHeader; receivedReliableSequenceNumber : enet_uint16; receivedSentTime : enet_uint16; end; ENetProtocolConnect = record header : ENetProtocolCommandHeader; outgoingPeerID : enet_uint16; incomingSessionID : enet_uint8; outgoingSessionID : enet_uint8; mtu : enet_uint32; windowSize : enet_uint32; channelCount : enet_uint32; incomingBandwidth : enet_uint32; outgoingBandwidth : enet_uint32; packetThrottleInterval: enet_uint32; packetThrottleAcceleration : enet_uint32; packetThrottleDeceleration : enet_uint32; connectID : enet_uint32; data : enet_uint32; end; ENetProtocolVerifyConnect = record header : ENetProtocolCommandHeader; outgoingPeerID : enet_uint16; incomingSessionID : enet_uint8; outgoingSessionID : enet_uint8; mtu : enet_uint32; windowSize : enet_uint32; channelCount : enet_uint32; incomingBandwidth : enet_uint32; outgoingBandwidth : enet_uint32; packetThrottleInterval : enet_uint32; packetThrottleAcceleration : enet_uint32; packetThrottleDeceleration : enet_uint32; connectID : enet_uint32; end; ENetProtocolBandwidthLimit = record header : ENetProtocolCommandHeader; incomingBandwidth : enet_uint32; outgoingBandwidth : enet_uint32; end; ENetProtocolThrottleConfigure = record header : ENetProtocolCommandHeader; packetThrottleInterval : enet_uint32; packetThrottleAcceleration : enet_uint32; packetThrottleDeceleration : enet_uint32; end; ENetProtocolDisconnect = record header : ENetProtocolCommandHeader; data : enet_uint32; end; ENetProtocolPing = record header : ENetProtocolCommandHeader; end; ENetProtocolSendReliable = record header : ENetProtocolCommandHeader; dataLength :enet_uint16; end; ENetProtocolSendUnreliable = record header : ENetProtocolCommandHeader; unreliableSequenceNumber :enet_uint16; dataLength :enet_uint16; end; ENetProtocolSendUnsequenced = record header : ENetProtocolCommandHeader; unsequencedGroup :enet_uint16; dataLength :enet_uint16; end; ENetProtocolSendFragment = record header : ENetProtocolCommandHeader; startSequenceNumber :enet_uint16; dataLength :enet_uint16; fragmentCount : enet_uint32; fragmentNumber : enet_uint32; totalLength : enet_uint32; fragmentOffset : enet_uint32; end; pENetProtocol = ^ENetProtocol; ENetProtocol = record case integer of 0 : (header : ENetProtocolCommandHeader); 1 : (acknowledge : ENetProtocolAcknowledge); 2 : (connect : ENetProtocolConnect); 3 : (verifyConnect : ENetProtocolVerifyConnect); 4 : (disconnect : ENetProtocolDisconnect); 5 : (ping : ENetProtocolPing ); 6 : (sendReliable : ENetProtocolSendReliable); 7 : (sendUnreliable : ENetProtocolSendUnreliable); 8 : (sendUnsequenced : ENetProtocolSendUnsequenced); 9 : (sendFragment : ENetProtocolSendFragment); 10: (bandwidthLimit : ENetProtocolBandwidthLimit); 11: (throttleConfigure : ENetProtocolThrottleConfigure); end; // -----> protocol.h {$pop} ENetPacket = record referenceCount : enet_uint32; (**< internal use only *) flags : enet_uint32; (**< bitwise-or of ENetPacketFlag constants *) data : pbyte; (**< allocated data for packet *) dataLength : enet_uint32; (**< length of data *) freeCallback : ENetPacketFreeCallback; (**< function to be called when the packet is no longer in use *) userData : Pointer; (**< application private data, may be freely modified *) end; pENetAcknowledgement = ^ENetAcknowledgement; ENetAcknowledgement = record acknowledgementList : ENetListNode; sentTime : enet_uint32; command : ENetProtocol; end; pENetOutgoingCommand= ^ENetOutgoingCommand; ENetOutgoingCommand = record outgoingCommandList : ENetListNode; reliableSequenceNumber :enet_uint16; unreliableSequenceNumber:enet_uint16; sentTime : enet_uint32; roundTripTimeout : enet_uint32; roundTripTimeoutLimit : enet_uint32; fragmentOffset : enet_uint32; fragmentLength :enet_uint16; sendAttempts :enet_uint16; command : ENetProtocol; packet : pENetPacket; end; pENetIncomingCommand = ^ENetIncomingCommand; ENetIncomingCommand = record incomingCommandList : ENetListNode; reliableSequenceNumber :enet_uint16; unreliableSequenceNumber:enet_uint16; command : ENetProtocol; fragmentCount : enet_uint32; fragmentsRemaining : enet_uint32; fragments : penet_uint32; packet : pENetPacket; end; // enet.h <----- pENetChannel = ^ENetChannel; ENetChannel = record outgoingReliableSequenceNumber :enet_uint16; outgoingUnreliableSequenceNumber :enet_uint16; usedReliableWindows :enet_uint16; reliableWindows :array[0..ENET_PEER_RELIABLE_WINDOWS-1] of enet_uint16; incomingReliableSequenceNumber :enet_uint16; incomingUnreliableSequenceNumber :enet_uint16; incomingReliableCommands : ENetList; incomingUnreliableCommands : ENetList; end; ENetChannelArray = array[0..ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT] of ENetChannel; pENetChannelArray = ^ENetChannelArray; (** * An ENet peer which data packets may be sent or received from. * * No fields should be modified unless otherwise specified. *) pENetHost = ^ENetHost; pENetPeer = ^ENetPeer; ENetPeer = record dispatchList : ENetListNode; host : pENetHost; outgoingPeerID :enet_uint16; incomingPeerID :enet_uint16; connectID :enet_uint32; outgoingSessionID:enet_uint8; incomingSessionID:enet_uint8; address : ENetAddress; (**< Internet address of the peer *) data : pointer; (**< Application private data, may be freely modified *) state : integer; // ENetPeerState channels : pENetChannel; channelCount : enet_uint32; (**< Number of channels allocated for communication with peer *) incomingBandwidth : enet_uint32; (**< Downstream bandwidth of the client in bytes/second *) outgoingBandwidth : enet_uint32; (**< Upstream bandwidth of the client in bytes/second *) incomingBandwidthThrottleEpoch : enet_uint32; outgoingBandwidthThrottleEpoch : enet_uint32; incomingDataTotal : enet_uint32; outgoingDataTotal : enet_uint32; lastSendTime : enet_uint32; lastReceiveTime : enet_uint32; nextTimeout : enet_uint32; earliestTimeout : enet_uint32; packetLossEpoch : enet_uint32; packetsSent : enet_uint32; packetsLost : enet_uint32; packetLoss : enet_uint32; (**< mean packet loss of reliable packets as a ratio with respect to the constant ENET_PEER_PACKET_LOSS_SCALE *) packetLossVariance : enet_uint32; packetThrottle : enet_uint32; packetThrottleLimit : enet_uint32; packetThrottleCounter : enet_uint32; packetThrottleEpoch : enet_uint32; packetThrottleAcceleration : enet_uint32; packetThrottleDeceleration : enet_uint32; packetThrottleInterval : enet_uint32; pingInterval : enet_uint32; timeoutLimit : enet_uint32; timeoutMinimum : enet_uint32; timeoutMaximum : enet_uint32; lastRoundTripTime : enet_uint32; lowestRoundTripTime : enet_uint32; lastRoundTripTimeVariance : enet_uint32; highestRoundTripTimeVariance : enet_uint32; roundTripTime : enet_uint32; (**< mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgement *) roundTripTimeVariance : enet_uint32; mtu :enet_uint32; windowSize : enet_uint32; reliableDataInTransit : enet_uint32; outgoingReliableSequenceNumber :enet_uint16; acknowledgements : ENetList; sentReliableCommands : ENetList; sentUnreliableCommands : ENetList; outgoingReliableCommands : ENetList; outgoingUnreliableCommands : ENetList; dispatchedCommands : ENetList; needsDispatch : Integer; incomingUnsequencedGroup :enet_uint16; outgoingUnsequencedGroup :enet_uint16; unsequencedWindow : array[0..(ENET_PEER_UNSEQUENCED_WINDOW_SIZE div 32)-1] of enet_uint32; eventData : enet_uint32; totalWaitingData : enet_size_t; end; ENetPeerArray = array[0..ENET_PROTOCOL_MAXIMUM_PEER_ID] of ENetPeer; pENetPeerArray = ^ENetPeerArray; (** An ENet host for communicating with peers. * * No fields should be modified unless otherwise stated. @sa enet_host_create() @sa enet_host_destroy() @sa enet_host_connect() @sa enet_host_service() @sa enet_host_flush() @sa enet_host_broadcast() @sa enet_host_compress() @sa enet_host_compress_with_range_coder() @sa enet_host_channel_limit() @sa enet_host_bandwidth_limit() @sa enet_host_bandwidth_throttle() *) ENetSocket = TSocket; // SOCKET = UINT_PTR {$push} {$ifdef CPUX86_64} {$PackRecords 8} {$else} {$PackRecords 4} {$endif} pENetBuffer = ^ENetBuffer; ENetBuffer = record dataLength : enet_uint32; data : pointer; end; ENET_CALLBACK_Compress = function (context:Pointer; inBuffers:PEnetBuffer; inBufferCount, inLimit:enet_size_t; outData : penet_uint8; outLimit:enet_size_t):enet_size_t; ENET_CALLBACK_DeCompress = function (context:Pointer; inData:penet_uint8; inLimit:enet_size_t; outData:penet_uint8; outLimit:enet_size_t):enet_size_t; ENET_CALLBACK_Destroy = procedure (context:Pointer); (** An ENet packet compressor for compressing UDP packets before socket sends or receives. *) pENetCompressor = ^ENetCompressor; ENetCompressor = record (** Context data for the compressor. Must be non-NULL. *) context : Pointer; (** Compresses from inBuffers[0:inBufferCount-1], containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. *) compress : ENET_CALLBACK_Compress; (** Decompresses from inData, containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. *) decompress : ENET_CALLBACK_DeCompress; (** Destroys the context when compression is disabled or the host is destroyed. May be NULL. *) destroy : ENET_CALLBACK_Destroy; end; ENetHost = record socket : ENetSocket; address : ENetAddress; (**< Internet address of the host *) incomingBandwidth : enet_uint32; (**< downstream bandwidth of the host *) outgoingBandwidth : enet_uint32; (**< upstream bandwidth of the host *) bandwidthThrottleEpoch : enet_uint32; mtu : enet_uint32; randomSeed : enet_uint32; recalculateBandwidthLimits : integer; peers : pENetPeer; (**< array of peers allocated for this host *) peerCount : enet_uint32; (**< number of peers allocated for this host *) channelLimit : enet_size_t; (**< maximum number of channels allowed for connected peers *) serviceTime : enet_uint32; dispatchQueue : ENetList; lastServicedPeer : pENetPeer; continueSending : integer; packetSize : enet_uint32; headerFlags :enet_uint16; commands : array[0..(ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS)-1] of ENetProtocol; commandCount : enet_uint32; buffers : array[0..(ENET_BUFFER_MAXIMUM)-1] of ENetBuffer; bufferCount : enet_uint32; checksumfunc : Pointer; //ENetChecksumCallback (**< callback the user can set to enable packet checksums for this host *) compressor : ENetCompressor; packetData : array[0..1,0..ENET_PROTOCOL_MAXIMUM_MTU-1] of enet_uint8; receivedAddress : ENetAddress; receivedData : penet_uint8; receivedDataLength : enet_size_t; totalSentData : enet_uint32; (**< total data sent, user should reset to 0 as needed to prevent overflow *) totalSentPackets : enet_uint32; (**< total UDP packets sent, user should reset to 0 as needed to prevent overflow *) totalReceivedData : enet_uint32; (**< total data received, user should reset to 0 as needed to prevent overflow *) totalReceivedPackets : enet_uint32; (**< total UDP packets received, user should reset to 0 as needed to prevent overflow *) interceptfunc : Pointer; //ENetInterceptCallback (**< callback the user can set to intercept received raw UDP packets *) connectedPeers: enet_size_t; bandwidthLimitedPeers : enet_size_t; duplicatePeers : enet_size_t; (**< optional number of allowed peers from duplicate IPs, defaults to ENET_PROTOCOL_MAXIMUM_PEER_ID *) maximumPacketSize : enet_size_t; (**< the maximum allowable packet size that may be sent or received on a peer *) maximumWaitingData : enet_size_t; (**< the maximum aggregate amount of buffer space a peer may use waiting for packets to be delivered *) end; {$pop} (** * An ENet event as returned by enet_host_service(). @sa enet_host_service *) pENetEvent = ^ENetEvent; ENetEvent = record EventType : integer; // ENetEventType (**< type of the event *) peer : pENetPeer; (**< peer that generated a connect, disconnect or receive event *) channelID :enet_uint8; (**< channel on the peer that generated the event, if appropriate *) data : enet_uint32; (**< data associated with the event, if appropriate *) packet : pENetPacket; (**< packet associated with the event, if appropriate *) end; (** Callback that computes the checksum of the data held in buffers[0:bufferCount-1] *) ENET_CALLBACK_ENetChecksumCallback = function (buffers:pENetBuffer; bufferCount:enet_size_t):enet_uint32; (** Callback for intercepting received raw UDP packets. Should return 1 to intercept, 0 to ignore, or -1 to propagate an error. *) ENET_CALLBACK_ENetInterceptCallback = function (host:pENetHost; _event:pENetEvent):Integer; // time.h <----- function ENET_TIME_LESS(a, b:longword):boolean; function ENET_TIME_GREATER(a, b:longword):boolean; function ENET_TIME_LESS_EQUAL(a, b : longword):boolean; function ENET_TIME_GREATER_EQUAL(a, b:longword):boolean; function ENET_TIME_DIFFERENCE(a, b:longword):longword; // -----> time.h // utility.h <----- function ENET_MAX(x, y:longword):longword; function ENET_MIN(x, y:longword):longword; // -----> utility.h implementation {$push} {$R-} function ENET_TIME_LESS(a, b : longword):boolean; var c : enet_uint32; begin c := a - b; result := c >= ENET_TIME_OVERFLOW; end; function ENET_TIME_GREATER(a, b : longword):boolean; var c : enet_uint32; begin c := b - a; result := c >= ENET_TIME_OVERFLOW; end; function ENET_TIME_LESS_EQUAL(a, b : longword):boolean; begin result := not ENET_TIME_GREATER (a, b); end; function ENET_TIME_GREATER_EQUAL(a, b:longword):boolean; begin result := not ENET_TIME_LESS (a, b); end; function ENET_TIME_DIFFERENCE(a, b:longword):longword; var c : enet_uint32; begin c := a - b; if c >= ENET_TIME_OVERFLOW then result := b - a else result := c; end; {$pop} function ENET_MAX(x, y:longword):longword; begin result := y; if x > y then result := x; end; function ENET_MIN(x, y:longword):longword; begin result := y; if x < y then result := x; end; end.
unit ObservFile; interface uses RinexFile, Classes; type PMath = procedure(Sender: TObject; sMath: String) of Object; type TObservFile = Class(TRinexFile) private { Private declarations } FFileName: String; FMath: PMath; function Parse(sRegex: String): String; overload; function Parse(sRegex, Text: String): String; overload; function GetFileName: String; procedure SetFileName(const Value: String); function GetOnMath: PMath; procedure SetOnMath(const Value: PMath); function GetVersionType (): String; public { Public declarations } constructor Create(sFilePath: String); overload; destructor Destroy; override; procedure ParseRegex(sRegex: String); function GetType (): String; function GetVer (): String; function GetSystem (): String; property FileName: String read GetFileName write SetFileName; property OnMath: PMath read GetOnMath write SetOnMath; end; var StringList: TStringList; implementation uses RegExpr; { TObservFile } constructor TObservFile.Create(sFilePath: String); begin inherited; Self.sFilePath := sFilePath; StringList := TStringList.Create; StringList.LoadFromFile (sFilePath); end; destructor TObservFile.Destroy; begin StringList.Free; inherited; end; function TObservFile.GetFileName: String; begin Result := FFileName; end; function TObservFile.GetOnMath: PMath; begin Result := FMath; end; function TObservFile.GetSystem: String; const SystemRE = '.{2}\(MIXED\).{11}'; begin Result := Parse(SystemRE, GetVersionType ()); end; function TObservFile.GetType: String; const TypeRE = '\s{11}(O|G:|N).{19}'; begin Result := Parse (TypeRE, GetVersionType ()); end; function TObservFile.GetVer: String; const VerRE = '.*\d*\.\d{2}\s{11}'; begin Result := Parse (VerRE, GetVersionType ()); end; function TObservFile.GetVersionType: String; const VersionTypeRE = '.*\d*\.\d{2}\s{11}.*RINEX VERSION / TYPE'; begin Result := Parse (VersionTypeRE, StringList.Text); end; function TObservFile.Parse(sRegex: String): String; var r: TRegExpr; begin Result := ''; r := TRegExpr.Create; //r.ModifierG := False; try r.Expression := sRegex; if r.Exec (StringList.Text) then REPEAT Result := Result + r.Match [0];// + ','; UNTIL not r.ExecNext; finally r.Free; end; end; function TObservFile.Parse(sRegex, Text: String): String; var r: TRegExpr; begin Result := ''; r := TRegExpr.Create; //r.ModifierG := False; try r.Expression := sRegex; if r.Exec (Text) then REPEAT Result := Result + r.Match [0];// + ','; UNTIL not r.ExecNext; finally r.Free; end; end; procedure TObservFile.ParseRegex(sRegex: String); var r: TRegExpr; begin //Result := ''; r := TRegExpr.Create; //r.ModifierG := False; try r.Expression := sRegex; if r.Exec (StringList.Text) then begin repeat if @OnMath <> nil then FMath (Self, r.Match [0]); until not r.ExecNext; end finally r.Free; end; end; procedure TObservFile.SetFileName(const Value: String); begin FFileName := Value; end; procedure TObservFile.SetOnMath(const Value: PMath); begin FMath := Value; end; end.
unit DamDialog; {$IFDEF FPC}{$mode delphi}{$ENDIF} interface uses {$IFDEF FPC} Forms, Classes, ActnList, Buttons, Controls, ExtCtrls, {$ELSE} Vcl.Forms, System.Classes, System.Actions, Vcl.ActnList, Vcl.StdCtrls, Vcl.Buttons, Vcl.Controls, Vcl.ExtCtrls, {$ENDIF} // DamUnit, DamLanguage, Vcl.DzHTMLText; type TFrmDamDialog = class(TForm) Ico: TImage; BoxButtons: TPanel; AL: TActionList; Action_Copy: TAction; LbMsg: TDzHTMLText; BoxFloatBtns: TPanel; BtnHelp: TSpeedButton; Action_Help: TAction; procedure FormShow(Sender: TObject); procedure Action_CopyExecute(Sender: TObject); procedure BtnHelpClick(Sender: TObject); procedure Action_HelpExecute(Sender: TObject); procedure LbMsgLinkClick(Sender: TObject; Link: TDHBaseLink; var Handled: Boolean); private DamMsg: TDamMsg; DamResult: TDamMsgRes; LangStrs: TDamLanguageDefinition; procedure OnBtnClick(Sender: TObject); procedure BuildButtons; procedure LoadText(const aText: string); procedure CalcWidth(const aText: string); procedure CalcHeight; procedure SetFormCustomization; procedure SetTitleAndIcon; procedure LoadHelp; procedure AlignButtonsPanel; procedure DoSound; end; function RunDamDialog(DamMsg: TDamMsg; const aText: string): TDamMsgRes; implementation {$R *.dfm} uses {$IFDEF FPC} Windows, SysUtils, Clipbrd, MMSystem, Graphics {$ELSE} Winapi.Windows, System.SysUtils, Vcl.Clipbrd, Winapi.MMSystem, Vcl.Graphics, System.Math {$ENDIF}; {$IFDEF FPC} const {$EXTERNALSYM IDI_HAND} IDI_HAND = MakeIntResource(32513); {$EXTERNALSYM IDI_QUESTION} IDI_QUESTION = MakeIntResource(32514); {$EXTERNALSYM IDI_EXCLAMATION} IDI_EXCLAMATION = MakeIntResource(32515); {$EXTERNALSYM IDI_ASTERISK} IDI_ASTERISK = MakeIntResource(32516); {$EXTERNALSYM IDI_WINLOGO} IDI_WINLOGO = MakeIntResource(32517); {$EXTERNALSYM IDI_WARNING} IDI_WARNING = IDI_EXCLAMATION; {$EXTERNALSYM IDI_ERROR} IDI_ERROR = IDI_HAND; {$EXTERNALSYM IDI_INFORMATION} IDI_INFORMATION = IDI_ASTERISK; {$ENDIF} function RunDamDialog(DamMsg: TDamMsg; const aText: string): TDamMsgRes; var F: TFrmDamDialog; begin F := TFrmDamDialog.Create(Application); try if (csDesigning in DamMsg.ComponentState) then F.LbMsg.StyleElements := []; //do not use themes in Delphi IDE F.DamMsg := DamMsg; F.LangStrs := LoadLanguage(DamMsg.Dam.Language); F.BuildButtons; F.LoadText(aText); F.SetFormCustomization; F.SetTitleAndIcon; F.LoadHelp; F.ShowModal; Result := F.DamResult; finally F.Free; end; end; // function GetButtonWidth(Btn: TBitBtn): Integer; var B: {$IFNDEF FPC}Vcl.{$ENDIF}Graphics.TBitmap; begin B := {$IFNDEF FPC}Vcl.{$ENDIF}Graphics.TBitmap.Create; try B.Canvas.Font.Assign(Btn.Font); Result := Max(B.Canvas.TextWidth(Btn.Caption)+20, 75); finally B.Free; end; end; procedure TFrmDamDialog.BuildButtons; var NumButtons: Byte; I, X: Integer; Btn: TBitBtn; Names: array[1..3] of string; begin case DamMsg.Buttons of dbOne, dbOK: NumButtons := 1; dbTwo, dbYesNo: NumButtons := 2; dbThree: NumButtons := 3; else raise Exception.Create('Unknown buttons kind property'); end; DamResult := NumButtons; //default result - last button Names[1] := DamMsg.Button1; Names[2] := DamMsg.Button2; Names[3] := DamMsg.Button3; case DamMsg.Buttons of dbOK: Names[1] := LangStrs.OK; dbYesNo: begin Names[1] := '&'+LangStrs.Yes; Names[2] := '&'+LangStrs.No; end; end; Btn := nil; X := 0; for I := 1 to NumButtons do begin Btn := TBitBtn.Create(Self); Btn.Parent := BoxFloatBtns; Btn.Caption := Names[I]; Btn.SetBounds(X, 0, GetButtonWidth(Btn), BoxFloatBtns.Height); Btn.OnClick := OnBtnClick; Btn.Tag := I; Inc(X, Btn.Width+8); end; //here btn contains last button reference Btn.Cancel := True; //set last button as cancel (esc) button if DamMsg.SwapFocus then ActiveControl := Btn; //set last button as start focus button BoxFloatBtns.Width := Btn.BoundsRect.Right; end; procedure TFrmDamDialog.LoadText(const aText: string); begin LbMsg.Images := DamMsg.Dam.Images; LbMsg.Font.Assign(DamMsg.Dam.MessageFont); CalcWidth(aText); CalcHeight; end; procedure TFrmDamDialog.CalcWidth(const aText: string); var MinSize: Integer; begin if DamMsg.FixedWidth=0 then LbMsg.Width := Trunc(Monitor.Width * 0.75) //max width else LbMsg.Width := DamMsg.FixedWidth; LbMsg.Text := aText; //set MESSAGE TEXT if (DamMsg.FixedWidth=0) and (LbMsg.TextWidth < LbMsg.Width) then begin MinSize := Max(300, BoxFloatBtns.Width); LbMsg.Width := Max(LbMsg.TextWidth, MinSize); end; ClientWidth := LbMsg.BoundsRect.Right+8; end; procedure TFrmDamDialog.CalcHeight; var Dif: Integer; begin Dif := ClientHeight-LbMsg.Height; LbMsg.Height := LbMsg.TextHeight; ClientHeight := Max(LbMsg.Height, Ico.Height)+Dif; if LbMsg.Height<Ico.Height then //text smaller than icon LbMsg.Top := LbMsg.Top + ((Ico.Height-LbMsg.Height) div 2); end; procedure TFrmDamDialog.SetFormCustomization; var F: TForm; R: TRect; begin //form border if not DamMsg.Dam.DialogBorder then BorderStyle := bsNone; //form screen position case DamMsg.Dam.DialogPosition of dpScreenCenter: {Position := poScreenCenter}; //default dpActiveFormCenter: begin F := Screen.ActiveForm; if Assigned(F) then begin Position := poDesigned; if not GetWindowRect(F.Handle, R) then raise Exception.Create('Error getting window rect'); Left := R.Left + ((R.Width - Width) div 2); Top := R.Top + ((R.Height - Height) div 2); end; end; dpMainFormCenter: Position := poMainFormCenter; else raise Exception.Create('Invalid dialog position property'); end; //form theme colors Color := DamMsg.Dam.MessageColor; BoxButtons.Color := DamMsg.Dam.ButtonsColor; end; procedure TFrmDamDialog.SetTitleAndIcon; function GetIconTitle: string; begin case DamMsg.Icon of diApp : Result := Application.Title; diInfo : Result := LangStrs.Info; diQuest : Result := LangStrs.Quest; diWarn : Result := LangStrs.Warn; diError : Result := LangStrs.Error; diCustom: Result := LangStrs.Msg; else raise Exception.Create('Unknown icon kind property'); end; end; begin case DamMsg.Title of dtApp : Caption := Application.Title; dtParentForm: Caption := TForm(DamMsg.Dam.Owner).Caption; dtMainForm : Caption := Application.MainForm.Caption; dtByIcon : Caption := GetIconTitle; dtCustom : Caption := DamMsg.CustomTitle; else raise Exception.Create('Unknown title kind property'); end; case DamMsg.Icon of diApp : Ico.Picture.Icon := Application.Icon; diInfo : Ico.Picture.Icon.Handle := LoadIcon(0, IDI_INFORMATION); diQuest : Ico.Picture.Icon.Handle := LoadIcon(0, IDI_QUESTION); diWarn : Ico.Picture.Icon.Handle := LoadIcon(0, IDI_WARNING); diError : Ico.Picture.Icon.Handle := LoadIcon(0, IDI_ERROR); diCustom: Ico.Picture.Icon := DamMsg.CustomIcon; else raise Exception.Create('Unknown icon kind property'); end; end; procedure TFrmDamDialog.LoadHelp; begin BtnHelp.Visible := (DamMsg.HelpContext<>0) or (DamMsg.HelpKeyword<>EmptyStr); end; procedure TFrmDamDialog.AlignButtonsPanel; begin if DamMsg.Dam.CenterButtons then BoxFloatBtns.Left := (BoxButtons.Width-BoxFloatBtns.Width) div 2 //center else BoxFloatBtns.Left := BoxButtons.Width-BoxFloatBtns.Width-8; //right end; procedure TFrmDamDialog.DoSound; procedure Play(const aSound: string); begin PlaySound(PChar(aSound), 0, SND_ASYNC); end; begin case DamMsg.Icon of diQuest: Play('SYSTEMQUESTION'); diWarn: Play('SYSTEMEXCLAMATION'); diError: Play('SYSTEMHAND'); end; end; procedure TFrmDamDialog.FormShow(Sender: TObject); begin AlignButtonsPanel; if DamMsg.Dam.PlaySounds then DoSound; end; procedure TFrmDamDialog.Action_CopyExecute(Sender: TObject); begin Clipboard.AsText := TDzHTMLText.HTMLToPlainText(LbMsg.Text); end; procedure TFrmDamDialog.Action_HelpExecute(Sender: TObject); begin if BtnHelp.Visible then BtnHelp.Click; end; procedure TFrmDamDialog.BtnHelpClick(Sender: TObject); begin if DamMsg.HelpContext<>0 then Application.HelpContext(DamMsg.HelpContext) else if DamMsg.HelpKeyword<>EmptyStr then Application.HelpKeyword(DamMsg.HelpKeyword) else raise Exception.Create('Unknown help property'); end; procedure TFrmDamDialog.LbMsgLinkClick(Sender: TObject; Link: TDHBaseLink; var Handled: Boolean); var CloseMsg: Boolean; ImmediateRes: TDamMsgRes; begin if (Link.Kind = lkLinkRef) and Assigned(DamMsg.Dam.OnLinkClick) then begin CloseMsg := False; ImmediateRes := DamResult; DamMsg.Dam.OnLinkClick(DamMsg.Dam, DamMsg, Link.LinkRef.Target, Handled, CloseMsg, ImmediateRes); if CloseMsg then begin DamResult := ImmediateRes; Close; end; end; end; procedure TFrmDamDialog.OnBtnClick(Sender: TObject); begin DamResult := TBitBtn(Sender).Tag; Close; end; end.
program Quadratzahl (input,output); { berechne die Quadrate der Zahlen von 1 bis 10 } const MAXINDEX = 10; type tIndex = 1..MAXINDEX; var i : tIndex; { Laufvariable } begin for i := 1 to MAXINDEX do writeln(i:2, sqr (i):5) end.
unit l3CharSkipper; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3CharSkipper - } { Начат: 03.05.2001 17:39 } { $Id: l3CharSkipper.pas,v 1.5 2015/09/25 09:44:34 dinishev Exp $ } // $Log: l3CharSkipper.pas,v $ // Revision 1.5 2015/09/25 09:44:34 dinishev // {Requestlink:607284377} // // Revision 1.4 2013/04/04 11:22:01 lulin // - портируем. // // Revision 1.3 2008/02/14 17:09:15 lulin // - cleanup. // // Revision 1.2 2001/05/07 06:54:39 law // - new method: к интерфейсу Il3CharSkipper добавлен метод Index. // // Revision 1.1 2001/05/04 11:00:45 law // - new class: сделана базовая реализация Il3CharSkipper. // {$I l3Define.inc } interface uses l3Types, l3Base, l3InternalInterfaces, l3CacheableBase ; type Tl3CharSkipper = class(Tl3CacheableBase, Il3CharSkipper) private //internal fields f_String : Tl3CustomString; f_Index : Long; protected //internal methods procedure Cleanup; override; {-} public //public methods procedure Init(aString: TObject); virtual; {-} function GetChar: AnsiChar; virtual; {-} function Index: Long; {-} function EOL: Boolean; {-} end;//Tl3CharSkipper implementation // start class Tl3CharSkipper procedure Tl3CharSkipper.Cleanup; //override; {-} begin inherited; l3Free(f_String); f_Index := -1; end; procedure Tl3CharSkipper.Init(aString: TObject); {-} begin l3Set(f_String, aString As Tl3CustomString); f_Index := -1; end; function Tl3CharSkipper.GetChar: AnsiChar; {-} begin Inc(f_Index); Result := f_String.Ch[f_Index]; end; function Tl3CharSkipper.Index: Long; {-} begin Result := f_Index; end; function Tl3CharSkipper.EOL: Boolean; begin Result := f_Index >= f_String.Len; end; end.
unit CompFileAssoc; { Inno Setup Copyright (C) 1997-2005 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Functions for registering/unregistering the .iss file association $jrsoftware: issrc/Projects/CompFileAssoc.pas,v 1.13 2009/04/21 13:46:04 mlaan Exp $ } interface procedure RegisterISSFileAssociation; procedure UnregisterISSFileAssociation; implementation uses Windows, SysUtils, PathFunc, ShlObj, CmnFunc2; procedure RegisterISSFileAssociation; procedure SetKeyValue(const Subkey, ValueName: PChar; const Data: String); procedure Check(const Res: Longint); begin if Res <> ERROR_SUCCESS then raise Exception.CreateFmt('Error creating file association:'#13#10'%d - %s', [Res, Win32ErrorString(Res)]); end; var K: HKEY; Disp: DWORD; begin Check(RegCreateKeyExView(rvDefault, HKEY_CLASSES_ROOT, Subkey, 0, nil, 0, KEY_SET_VALUE, nil, K, @Disp)); try Check(RegSetValueEx(K, ValueName, 0, REG_SZ, PChar(Data), (Length(Data)+1)*SizeOf(Data[1]))); finally RegCloseKey(K); end; end; var SelfName: String; begin SelfName := NewParamStr(0); SetKeyValue('.iss', nil, 'InnoSetupScriptFile'); SetKeyValue('.iss', 'Content Type', 'text/plain'); SetKeyValue('InnoSetupScriptFile', nil, 'Inno Setup Script'); SetKeyValue('InnoSetupScriptFile\DefaultIcon', nil, SelfName + ',1'); SetKeyValue('InnoSetupScriptFile\shell\open\command', nil, '"' + SelfName + '" "%1"'); SetKeyValue('InnoSetupScriptFile\shell\OpenWithInnoSetup', nil, 'Open with &Inno Setup'); SetKeyValue('InnoSetupScriptFile\shell\OpenWithInnoSetup\command', nil, '"' + SelfName + '" "%1"'); SetKeyValue('InnoSetupScriptFile\shell\Compile', nil, 'Compi&le'); SetKeyValue('InnoSetupScriptFile\shell\Compile\command', nil, '"' + SelfName + '" /cc "%1"'); SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil); end; procedure UnregisterISSFileAssociation; function KeyValueEquals(const Subkey: PChar; const Data: String): Boolean; var K: HKEY; S: String; begin Result := False; if RegOpenKeyExView(rvDefault, HKEY_CLASSES_ROOT, Subkey, 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin if RegQueryStringValue(K, nil, S) and (PathCompare(Data, S) = 0) then Result := True; RegCloseKey(K); end; end; function KeyExists(const Subkey: PChar): Boolean; var K: HKEY; begin Result := (RegOpenKeyExView(rvDefault, HKEY_CLASSES_ROOT, Subkey, 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS); if Result then RegCloseKey(K); end; function GetKeyNumSubkeysValues(const Subkey: PChar; var NumSubkeys, NumValues: DWORD): Boolean; var K: HKEY; begin Result := False; if RegOpenKeyExView(rvDefault, HKEY_CLASSES_ROOT, Subkey, 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin Result := RegQueryInfoKey(K, nil, nil, nil, @NumSubkeys, nil, nil, @NumValues, nil, nil, nil, nil) = ERROR_SUCCESS; RegCloseKey(K); end; end; procedure DeleteValue(const Subkey, ValueName: PChar); var K: HKEY; begin if RegOpenKeyExView(rvDefault, HKEY_CLASSES_ROOT, Subkey, 0, KEY_SET_VALUE, K) = ERROR_SUCCESS then begin RegDeleteValue(K, ValueName); RegCloseKey(K); end; end; var SelfName: String; NumSubkeys, NumValues: DWORD; begin if not KeyExists('InnoSetupScriptFile') and not KeyExists('.iss') then Exit; SelfName := NewParamStr(0); { NOTE: We can't just blindly delete the entire .iss & InnoSetupScriptFile keys, otherwise we'd remove the association even if we weren't the one who registered it in the first place. } { Clean up 'InnoSetupScriptFile' } if KeyValueEquals('InnoSetupScriptFile\DefaultIcon', SelfName + ',1') then RegDeleteKeyIncludingSubkeys(rvDefault, HKEY_CLASSES_ROOT, 'InnoSetupScriptFile\DefaultIcon'); if KeyValueEquals('InnoSetupScriptFile\shell\open\command', '"' + SelfName + '" "%1"') then RegDeleteKeyIncludingSubkeys(rvDefault, HKEY_CLASSES_ROOT, 'InnoSetupScriptFile\shell\open'); if KeyValueEquals('InnoSetupScriptFile\shell\OpenWithInnoSetup\command', '"' + SelfName + '" "%1"') then RegDeleteKeyIncludingSubkeys(rvDefault, HKEY_CLASSES_ROOT, 'InnoSetupScriptFile\shell\OpenWithInnoSetup'); if KeyValueEquals('InnoSetupScriptFile\shell\Compile\command', '"' + SelfName + '" /cc "%1"') then RegDeleteKeyIncludingSubkeys(rvDefault, HKEY_CLASSES_ROOT, 'InnoSetupScriptFile\shell\Compile'); RegDeleteKeyIfEmpty(rvDefault, HKEY_CLASSES_ROOT, 'InnoSetupScriptFile\shell'); if KeyValueEquals('InnoSetupScriptFile', 'Inno Setup Script') and GetKeyNumSubkeysValues('InnoSetupScriptFile', NumSubkeys, NumValues) and (NumSubkeys = 0) and (NumValues <= 1) then RegDeleteKey(HKEY_CLASSES_ROOT, 'InnoSetupScriptFile'); { Clean up '.iss' } if not KeyExists('InnoSetupScriptFile') and KeyValueEquals('.iss', 'InnoSetupScriptFile') then begin DeleteValue('.iss', nil); DeleteValue('.iss', 'Content Type'); end; RegDeleteKeyIfEmpty(rvDefault, HKEY_CLASSES_ROOT, '.iss'); SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil); end; end.
unit Service; interface uses System.SysUtils, System.SyncObjs, System.Classes, Vcl.ExtCtrls, Constants, XSuperObject, XSuperJSON, System.DateUtils, IniFiles, Forms, Data.Win.ADODB, Data.DB, Data.DBXFirebird, Data.FMTBcd, Data.SqlExpr, IBX.IBDatabase, IBX.IBCustomDataSet, IBX.IBDatabaseInfo, IBX.IBServices, System.IOUtils; type TMCore = class(TDataModule) TimerStart: TTimer; TimerWDog: TTimer; IBDatabaseInfo1: TIBDatabaseInfo; IBSecurityService1: TIBSecurityService; IBServerProperties1: TIBServerProperties; IBConfigService1: TIBConfigService; procedure DataModuleCreate(Sender: TObject); procedure TimerStartTimer(Sender: TObject); procedure TimerWDogTimer(Sender: TObject); private { Private declarations } public DbHost : string; DbBase : string; DbUser : string; DbPass : string; DbPort : word; DBName : string; DbParams : ISuperObject; // параметры БД ServerUID : string; ID : integer; DevClass : integer; LogFileName : string; JSON_DataFile : string; SqlFileName : string; SessionID : string; OnStopService : boolean; KeyFCM : string; ESetUpdateState : TEventSet; // набор событий, которые изменяют статус объекта ESetDeleteAlarm : TEventSet; // набор событий, которые удаляют тревогу ESetAddAlarm : TEventSet; // набор событий, которые создают тревогу ESetSendFCM : TEventCodeSet; // набор событий, которые отправляют FCM EventCodesDeleteAlarms : TEventsSet; // DevList : TStringList; // устройства на связи, которые принадлежат интернет драйверам // InetList : TStringList; // список интернет драйверов в системе Port : word; // TCP port of MainCore ReloadTime : TDateTime; // время переподключения к БД StopTime : TDateTime; ReloadList : string; PacketID : uint8; //UDP номер пакета ShutDownMode : byte; DataVersion : Integer; // версия данных, если = 0, то данные не загружены DataQuery : boolean; // данные запрошены или нет DataQueryTime : TDateTime; // время запроса данных DBEnabled : boolean; NextDriverCheckTime: TDateTime; NextKopCheckTime: TDateTime; UploadEventTime : TDateTime; // AllDbConnected: Boolean; // все базы подключены cs : TCriticalSection; cs2 : TCriticalSection; ServEvents : ISuperArray; // массив событий от серверов const ReloadDelay = 2; KOP_CHECK_PERIOD = 10; // сек, период проверки КОПов DRIVER_CHECK_PERIOD = 3; DB_CONNECT_PERIOD = 5; //sec UploadEventPeriod = 3000; //msec период выгрузки событий на драйвер данных // function GetArrLen(JSON: ISuperArray): integer; // procedure ExecuteChangeData; // обработка изменения данных function ReadIniFile: boolean; procedure IncPacketID; procedure StopService; procedure GenerateEvent(Dev_ID: Integer; Code_ID: Integer; Add_Info: string = ''; Xo_ID: integer = -1; Cust_ID: integer = -1); function ServEventsIO(JSON: ISuperObject): ISuperArray; function CreateDamageEvent(DevID: integer; AddInfo: string; DamageLink: Boolean = False): boolean; procedure CheckKopStates; end; const AppVersion = 2022; var MCore: TMCore; csLog: TCriticalSection; procedure LogOut(LogStr:string); implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses FormMain, DataUnit, HttpServer, EventUnit, ClientUnit, GlobalTypes, UDPClient, FirebirdTools, HttpClientUnit, DataDriverPing; {$R *.dfm} function GetPacket(MesType: string): ISuperObject; begin Result := SO(); Result.S[KEY_MES_TYPE] := MesType; end; procedure TMCore.DataModuleCreate(Sender: TObject); begin AllDbConnected := False; SetLength(Clients, 0); ServEvents := SA(); cs := TCriticalSection.Create; cs2:= TCriticalSection.Create; csLog := TCriticalSection.Create; csState := TCriticalSection.Create; ReloadTime := IncYear(Now, 5); UploadEventTime := IncSecond(Now, 2); //время выгрузки событий на драйвер данных DataVersion := 0; DataQuery := False; DataQueryTime := IncYear(Now, 20); //не будем пока запрашмвать данные OnStopService := False; ShutDownMode := 0; ESetUpdateState := [EvTypeArm, EvTypeDisArm, EvTypeAlarm, EvTypeFire, EvTypeHiJack, EvTypePreAlarm, EvTypeDamageDevice, EvTypeDamageLink, EvTypeDamagePower, EvTypeRepairDevice, EvTypeRepairLink, EvTypeRepairPower, EvTypeDropAlarm, EvTypeDropDamageDevice, EvTypeDropDamageLink, EvTypeDropDamagePower, EvTypeTestUp, EvTypeTestDown]; ESetDeleteAlarm := [EvTypeArm, EvTypeDisArm, EvTypeRepairDevice, EvTypeRepairLink, EvTypeRepairPower, EvTypeTestUp, EvTypeDropAlarm, EvTypeDropDamageDevice, EvTypeDropDamageLink, EvTypeDropDamagePower]; ESetAddAlarm := [EvTypeAlarm, EvTypeFire, EvTypeHiJack, EvTypeDamageDevice, EvTypeDamageLink, EvTypeDamagePower, EvTypeTestDown, EvTypePreAlarm]; ESetSendFCM := [Byte(EventTypeGuardSensorSet), Byte(EventTypeGuardSensorUnset), Byte(EventTypeDisArmed), Byte(EventTypeArmed), Byte(EventTypeQueryToArm), Byte(EventTypeQueryToDisarm)]; EventCodesDeleteAlarms := [EventTypeGuardSensorSet, EventTypeGuardSensorUnset, EventTypeArmedByDuty, EventTypeDisArmedByDuty]; NextDriverCheckTime := IncSecond(Now, 2); end; procedure LogOut(LogStr:string); var log_f: TextFile; begin // csLog.Enter; LogStr := DateTimeToStr(now)+' '+ LogStr; fmMain.Memo1.Lines.Add(LogStr); {$I-} AssignFile(log_f, MCore.LogFileName); Append(log_f); Writeln(log_f,LogStr); CloseFile(log_f); // csLog.Leave; {$I+} end; procedure TMCore.StopService; begin // JSON := SO(); // JSON.I[KeyMesType] := Byte(MsgTypeLastPacket); // for i := 0 to High(TCPLink.Clients) do // TCPLink.Clients[i].ClientBuffer.Add(JSON);// приказ отключиться клиентам // if MCore.TimerWDog.Enabled then // begin // OnStopService := True; // MCore.StopTime := IncSecond(Now, 2); // end else StopService; fmMain.Close; end; procedure TMCore.IncPacketID; begin if PacketID >= 255 then PacketID := 1 else Inc(PacketID); end; function TMCore.ReadIniFile: boolean; var IniFile : TIniFile; FileName:string; F:TextFile; FormatStr:string; IniOK : boolean; begin Result := False; IniOK := True; if not DirectoryExists(ExtractFilePath(Application.ExeName) + 'Logs\Core') then CreateDir(ExtractFilePath(Application.ExeName) + 'Logs\Core'); if not DirectoryExists(ExtractFilePath(Application.ExeName) + 'Data') then CreateDir(ExtractFilePath(Application.ExeName) + 'Data'); FormatStr := FormatDateTime('yyyy-mm-dd hh-mm-ss',Now); LogFileName := 'Logs\Core\Core_' + FormatStr + '.log'; JSON_DataFile := ExtractFilePath(Application.ExeName) + 'Data\DataJSON.txt'; SqlFileName := ExtractFilePath(Application.ExeName) + 'Data\SqlBuf.txt'; AssignFile(F, LogFileName); Rewrite(F); CloseFile(F); FileName := ExtractFilePath(Application.ExeName) + 'Config.ini'; if FileExists(FileName) then begin IniFile := TIniFile.Create(FileName); DBHost := IniFile.ReadString('DataBase','Host',''); DbBase := IniFile.ReadString('DataBase','Base',''); DbUser := IniFile.ReadString('DataBase','User','SECUR'); DbPass := IniFile.ReadString('DataBase','Pass','SECUR'); DbPort := IniFile.ReadInteger('DataBase','Port', 0); if DbPort > 0 then DBName := DBHost + '/' + IntToStr(DbPort) + ':' + DbBase else DBName := DBHost + ':' + DbBase; DbParams := SO(); DbParams.S['DB_HOST'] := DbHost; DbParams.I['DB_PORT'] := DbPort; DbParams.S['DB_BASE'] := DbBase; DbParams.S['DB_USER'] := 'SECUR'; DbParams.S['DB_PASS'] := 'SECUR'; DbParams.S['DB_NAME'] := DbName; DataServer := TAnyClient.Create; DataServer.Host := IniFile.ReadString('DataDriver','Host',''); DataServer.Port := IniFile.ReadInteger('DataDriver','Port', 0); DataServer.DevUID := IniFile.ReadString('DataDriver','UID',''); DataServer.DevClass := Byte(DevClassDriver1C); DataServer.DevID := IniFile.ReadInteger('DataDriver','ID', 0); Port := IniFile.ReadInteger('MainCore','Port', 0); ServerUID := IniFile.ReadString('MainCore','UID',''); ID := IniFile.ReadInteger('MainCore','ID', 0); DevClass := Byte(DevClassCore); KeyFCM := IniFile.ReadString('WebCore','GoogleFCM',''); IniFile.Free; if DataServer.DevID = 0 then begin LogOut('Не заполнен параметр - ID драйвера данных'); IniOK := False; end; if DataServer.DevUID = '' then begin LogOut('Не заполнен параметр - UID драйвера данных'); IniOK := False; end; if DataServer.Host = '' then begin LogOut('Не заполнен параметр - IP драйвера данных'); IniOK := False; end; if DataServer.Port = 0 then begin LogOut('Не заполнен параметр - порт драйвера данных'); IniOK := False; end; if ID = 0 then begin LogOut('Не заполнен параметр - ID ядра'); IniOK := False; end; if ServerUID = '' then begin LogOut('Не заполнен параметр - UID ядра'); IniOK := False; end; if DbHost = '' then begin LogOut('Не заполнен параметр - Сервер базы данных'); IniOK := False; end; if DbBase = '' then begin LogOut('Не заполнен параметр - Файл базы данных'); IniOK := False; end; if Port = 0 then begin LogOut('Не заполнен параметр - Порт ядра'); IniOK := False; end; if not IniOK then begin LogOut('Не верные параметры в файле Config.ini'); StopService; Exit; end; LogOut('ИД = ' + IntToStr(ID)); LogOut('УИД = ' + ServerUID); LogOut('Порт = ' + IntToStr(Port)); LogOut('Драйвер БД ИД = ' + IntToStr(DataServer.DevID)); LogOut('Драйвер БД УИД = ' + DataServer.DevUID); LogOut('Драйвер БД IP = ' + DataServer.Host); LogOut('Драйвер БД Порт = ' + IntToStr(DataServer.Port)); LogOut('DatabaseName = ' + DBName); end else begin LogOut('Не найден файл config.ini'); StopService; Exit; end; Result := True; end; procedure TMCore.TimerStartTimer(Sender: TObject); begin TimerStart.Enabled := False; if not ReadIniFile then begin StopService; Exit; end; AData := TAData.Create; HttpClt := THttpClient.Create; ReloadTime := Now; //через 10 сек загрузим данные из файла DataQuery := False; UdpLink := TFrUdpClient.Create; HTTPLink := THttpLink.Create; // AData.tDB.DatabaseName := MCore.DBName; // if AData.ConnectToDB = False then // begin // StopService; // Exit; // end; NextKopCheckTime := IncSecond(Now, 40); TimerWDog.Enabled := True; end; procedure TMCore.TimerWDogTimer(Sender: TObject); var i, j, c: integer; DrvParams, Item: ISuperObject; MesType: string; JSON: ISuperObject; CodeID, DevID, CustID: integer; AddInfo: string; Pinger: TPinger; LocAllConnected: boolean; Tool: TFBTool; Client: TAnyClient; Drv, Pcn : TDevice; DevState: TDevState; begin // проверка сработок на таймаут // LogOut('ON_TIMER ===================================='); for i := 0 to High(Alarms) do begin if (Alarms[i].EventType = Byte(EvTypePreAlarm)) and (Now > Alarms[i].DateTime) then begin GenerateEvent(Alarms[i].DevID, Byte(EventTypeAlarm), 'Таймаут ожидания снятия'); end; end; if DataVersion = 0 then begin if not HttpClt.RequestData(DataServer) then begin Exit; end; end; if DataVersion = 0 then Exit; if not HTTPLink.HTTPServer.Active then begin if not HTTPLink.Open then begin StopService; Exit; end; end; // if Now > UploadEventTime then // begin // UploadEventTime := IncMilliSecond(Now, UploadEventPeriod); // JSON := SO(); // JSON.S[KEY_MES_TYPE] := MESSAGE_PING; // JSON.A['records'] := DataServer.BufferIO(nil); // Pinger := TPinger.Create(JSON); // if DataServer.OnWork = False then // begin // LogOut('LINK TO DRIVER LOSE +++++++++++++++++++++++++++++++++++++'); // end // // end; if Now > NextKopCheckTime then // проверка не активных КОП begin NextKopCheckTime := IncSecond(Now, KOP_CHECK_PERIOD); CheckKopStates; end; if Now > NextDriverCheckTime then // проверка не активных драйверов begin NextDriverCheckTime := IncSecond(Now, DRIVER_CHECK_PERIOD); for i := 0 to High(Clients) do begin if Clients[i] = nil then Continue; if Clients[i].DevClass = Byte(DevClassCore) then Continue; // if not Clients[i].OnWork then // Continue; if SecondsBetween(Now, Clients[i].LastConTime) < 10 then Continue; AddInfo := 'Timeout: ' + DateTimeToStr(Clients[i].LastConTime); if Clients[i].DevClass = Byte(DevClassARM_DPCO) then begin if Clients[i].OnWork <> False then begin GenerateEvent(Clients[i].DevID, Byte(EventTypeDisConnectPC), AddInfo); end; end else begin CreateDamageEvent(Clients[i].DevID, AddInfo, True); if Clients[i].DevClass = Byte(DevClassDriverRadio) then begin AddInfo := 'При аварии владельца'; Drv := AData.GetDevice(Clients[i].DevID); for j := 0 to High(Drv.Childs) do begin Pcn := Drv.Childs[j]; CreateDamageEvent(Pcn.ID, AddInfo); for c := 0 to High(Pcn.Childs) do begin CreateDamageEvent(Pcn.Childs[c].ID, AddInfo); end; end; end; end; Clients[i].OnWork := False; Clients[i].DropClient; end; end; LocAllConnected := True; try for i := 0 to High(Clients) do begin if Clients[i] = nil then Continue; if Clients[i].SrvEvent.FbTool.Connected = False then begin LocAllConnected := False; if Now > Clients[i].SrvEvent.FbTool.DbConnectTime then begin if not Clients[i].SrvEvent.FbTool.ConnectToDB then Clients[i].SrvEvent.FbTool.DbConnectTime := IncSecond(Now, DB_CONNECT_PERIOD) else begin Clients[i].SrvEvent.FbTool.DbConnectTime := IncYear(Now, 10); end; end; end; end; finally TimerWDog.Enabled := True; end; //момент перехода в состояние CONNECTED. Загружаем SQL запросв if (LocAllConnected = True) and (AllDbConnected = False) then begin if FileExists(SqlFileName) then begin Tool := TFBTool.Create(DbParams, fbUpdate); if Tool.ConnectToDB then begin Tool.LoadSqlFromFile; Tool.DisconnectFromDB; end; Tool.Free; end; end; AllDbConnected := LocAllConnected; end; function TMCore.CreateDamageEvent(DevID: integer; AddInfo: string; DamageLink: Boolean = False): boolean; var DevState: TDevState; CodeID: Byte; DestState: Byte; begin if DamageLink then begin CodeID := Byte(EventTypeDamageLink); DestState := Byte(EvTypeDamageLink); end else begin CodeID := Byte(EventTypeDamageDevice); DestState := Byte(EvTypeDamageDevice); end; Result := False; DevState := AData.GetDevState(DevID); if DevState.State <> DestState then begin GenerateEvent(DevID, CodeID, AddInfo); Result := True; end; end; procedure TMCore.GenerateEvent(Dev_ID: Integer; Code_ID: Integer; Add_Info: string = ''; Xo_ID: integer = -1; Cust_ID: integer = -1); var CoreEvent: TAEvent; begin CoreEvent := TAEvent.Create; CoreEvent.DropToVoid; CoreEvent.ID := 0; CoreEvent.DevID := Dev_ID; CoreEvent.CustID := Cust_ID; CoreEvent.CodeID := Code_ID; CoreEvent.XoID := Xo_ID; CoreEvent.AddInfo := Add_Info; CoreEvent.DateTime := Now; CoreEvent.Write; CoreEvent.Destroy; end; function TMCore.ServEventsIO(JSON: ISuperObject): ISuperArray; begin cs2.Enter; try if JSON = nil then begin Result := ServEvents.Clone; Result.Clear; end else begin ServEvents.Add(JSON); end; finally cs2.Leave end; end; procedure TMCore.CheckKopStates; var i: Integer; begin for i := 0 to High(OnLineDevices) do begin if OnLineDevices[i].State <> StateOnn then begin MCore.CreateDamageEvent(OnLineDevices[i].DevID, 'При проверке на ядре', True); end; end; end; end.
{!DOCTOPIC}{ Type » TDoubleArray } {!DOCREF} { @method: function TDoubleArray.Len(): Int32; @desc: Returns the length of the array. Same as 'Length(arr)' } function TDoubleArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TDoubleArray.IsEmpty(): Boolean; @desc: Returns True if the array is empty. Same as 'Length(arr) = 0' } function TDoubleArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure TDoubleArray.Append(const Value:Double); @desc: Add another item to the array } procedure TDoubleArray.Append(const Value:Double); var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := Value; end; {!DOCREF} { @method: procedure TDoubleArray.Insert(idx:Int32; Value:Double); @desc: Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length, it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br] `Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`. } procedure TDoubleArray.Insert(idx:Int32; Value:Double); var l:Int32; begin l := Length(Self); if (idx < 0) then idx := math.modulo(idx,l); if (l <= idx) then begin self.append(value); Exit(); end; SetLength(Self, l+1); MemMove(Self[idx], self[idx+1], (L-Idx)*SizeOf(Double)); Self[idx] := value; end; {!DOCREF} { @method: procedure TDoubleArray.Del(idx:Int32); @desc: Removes the element at the given index c'idx' } procedure TDoubleArray.Del(idx:Int32); var i,l:Int32; begin l := Length(Self); if (l <= idx) or (idx < 0) then Exit(); if (L-1 <> idx) then MemMove(Self[idx+1], self[idx], (L-Idx)*SizeOf(Double)); SetLength(Self, l-1); end; {!DOCREF} { @method: procedure TDoubleArray.Remove(Value:Double); @desc: Removes the first element from left which is equal to c'Value' } procedure TDoubleArray.Remove(Value:Double); begin Self.Del( Self.Find(Value) ); end; {!DOCREF} { @method: function TDoubleArray.Pop(): Double; @desc: Removes and returns the last item in the array } function TDoubleArray.Pop(): Double; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function TDoubleArray.PopLeft(): Double; @desc: Removes and returns the first item in the array } function TDoubleArray.PopLeft(): Double; begin Result := Self[0]; MemMove(Self[1], Self[0], SizeOf(Double)*Length(Self)); SetLength(Self, High(self)); end; {!DOCREF} { @method: function TDoubleArray.Slice(Start,Stop: Int32; Step:Int32=1): TDoubleArray; @desc: Slicing similar to slice in Python, tho goes from 'start to and including stop' Can be used to eg reverse an array, and at the same time allows you to c'step' past items. You can give it negative start, and stop, then it will wrap around based on length(..) If c'Start >= Stop', and c'Step <= -1' it will result in reversed output. [note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note] } function TDoubleArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TDoubleArray; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 0; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 0; if Step = 0 then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result,0) end; end; {!DOCREF} { @method: procedure TDoubleArray.Extend(Arr:TDoubleArray); @desc: Extends the array with an array } procedure TDoubleArray.Extend(Arr:TDoubleArray); var L:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(Double)); end; {!DOCREF} { @method: function TDoubleArray.Find(Value:Double): Int32; @desc: Searces for the given value and returns the first position from the left. } function TDoubleArray.Find(Value:Double): Int32; begin Result := exp_Find(Self,[Value]); end; {!DOCREF} { @method: function TDoubleArray.Find(Sequence:TDoubleArray): Int32; overload; @desc: Searces for the given sequence and returns the first position from the left. } function TDoubleArray.Find(Sequence:TDoubleArray): Int32; overload; begin Result := exp_Find(Self,Sequence); end; {!DOCREF} { @method: function TDoubleArray.FindAll(Value:Double): TIntArray; @desc: Searces for the given value and returns all the position where it was found. } function TDoubleArray.FindAll(Value:Double): TIntArray; begin Result := exp_FindAll(Self,[value]); end; {!DOCREF} { @method: function TDoubleArray.FindAll(Sequence:TDoubleArray): TIntArray; overload; @desc: Searces for the given sequence and returns all the position where it was found. } function TDoubleArray.FindAll(Sequence:TDoubleArray): TIntArray; overload; begin Result := exp_FindAll(Self,sequence); end; {!DOCREF} { @method: function TDoubleArray.Contains(val:Double): Boolean; @desc: Checks if the arr contains the given value c'val' } function TDoubleArray.Contains(val:Double): Boolean; begin Result := Self.Find(val) <> -1; end; {!DOCREF} { @method: function TDoubleArray.Count(val:Double): Int32; @desc: Counts all the occurances of the given value c'val' } function TDoubleArray.Count(val:Double): Int32; begin Result := Length(Self.FindAll(val)); end; {!DOCREF} { @method: procedure TDoubleArray.Sort(key:TSortKey=sort_Default); @desc: Sorts the array Supported keys: c'sort_Default' } procedure TDoubleArray.Sort(key:TSortKey=sort_Default); begin case key of sort_default: se.SortTDA(Self); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TDoubleArray.Sorted(key:TSortKey=sort_Default): TDoubleArray; @desc: Returns a new sorted array from the input array. Supported keys: c'sort_Default' } function TDoubleArray.Sorted(Key:TSortKey=sort_Default): TDoubleArray; begin Result := Copy(Self); case key of sort_default: se.SortTDA(Result); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TDoubleArray.Reversed(): TDoubleArray; @desc: Creates a reversed copy of the array } function TDoubleArray.Reversed(): TDoubleArray; begin Result := Self.Slice(,,-1); end; {!DOCREF} { @method: procedure TDoubleArray.Reverse(); @desc: Reverses the array } procedure TDoubleArray.Reverse(); begin Self := Self.Slice(,,-1); end; {=============================================================================} // The functions below this line is not in the standard array functionality // // By "standard array functionality" I mean, functions that all standard // array types should have. {=============================================================================} {!DOCREF} { @method: function TDoubleArray.Sum(): Double; @desc: Adds up the array and returns the sum } function TDoubleArray.Sum(): Double; begin Result := exp_SumFPtr(PChar(Self),SizeOf(Double),Length(Self)); end; {!DOCREF} { @method: function TDoubleArray.Sum64(): Double; @desc: Adds up the array and returns the sum } function TDoubleArray.Sum64(): Double; begin Result := exp_SumFPtr(PChar(Self),SizeOf(Double),Length(Self)); end; {!DOCREF} { @method: function TDoubleArray.Mean(): Double; @desc:Returns the mean value of the array } function TDoubleArray.Mean(): Double; begin Result := Self.Sum() / Length(Self); end; {!DOCREF} { @method: function TDoubleArray.Stdev(): Double; @desc: Returns the standard deviation of the array } function TDoubleArray.Stdev(): Double; var i:Int32; avg:Double; square:TDoubleArray; begin avg := Self.Mean(); SetLength(square,Length(Self)); for i:=0 to High(self) do Square[i] := Sqr(Self[i] - avg); Result := sqrt(square.Mean()); end; {!DOCREF} { @method: function TDoubleArray.Variance(): Double; @desc: Return the sample variance. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the array. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. } function TDoubleArray.Variance(): Double; var avg:Double; i:Int32; begin avg := Self.Mean(); for i:=0 to High(Self) do Result := Result + Sqr(Self[i] - avg); Result := Result / length(self); end; {!DOCREF} { @method: function TDoubleArray.Mode(Eps:Double=0.000001): Double; @desc: Returns the sample mode of the array, which is the [u]most frequently occurring value[/u] in the array. When there are multiple values occurring equally frequently, mode returns the smallest of those values. Takes an extra parameter c'Eps', can be used to allow some tolerance in the floating point comparison. } function TDoubleArray.Mode(Eps:Double=0.0000001): Double; var arr:TDoubleArray; i,hits,best: Int32; cur:Double; begin arr := self.sorted(); cur := arr[0]; hits := 1; best := 0; for i:=1 to High(Arr) do begin if (arr[i]-cur > eps) then //arr[i] <> cur begin if (hits > best) then begin best := hits; Result := (Cur+Arr[i-1]) / 2; //Eps fix end; hits := 0; cur := Arr[I]; end; Inc(hits); end; if (hits > best) then Result := cur; end; {!DOCREF} { @method: function TDoubleArray.VarMin(): Double; @desc: Returns the minimum value in the array } function TDoubleArray.VarMin(): Double; var lo,hi:Extended; begin exp_MinMaxFPtr(Pointer(self), 4, length(self), lo,hi); Result := Lo; end; {!DOCREF} { @method: function TDoubleArray.VarMax(): Double; @desc: Returns the maximum value in the array } function TDoubleArray.VarMax(): Double; var lo,hi:Extended; begin exp_MinMaxFPtr(Pointer(self), 4, length(self), lo,hi); Result := Hi; end; {!DOCREF} { @method: function TDoubleArray.ArgMin(): Int32; @desc: Returns the index containing the smallest element in the array. } function TDoubleArray.ArgMin(): Int32; var mat:TDoubleMatrix; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMin(mat).x; end; {!DOCREF} { @method: function TDoubleArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the smallest element in the array. } function TDoubleArray.ArgMin(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TDoubleMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMin(n), Result, _); end; {!DOCREF} { @method: function TDoubleArray.ArgMin(Lo,Hi:int32): Int32; overload; @desc: Returns the index containing the smallest element in the array within the lower and upper bounds c'lo, hi'. } function TDoubleArray.ArgMin(lo,hi:Int32): Int32; overload; var B: TBox; mat:TDoubleMatrix; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMin(mat,B).x; end; {!DOCREF} { @method: function TDoubleArray.ArgMax(): Int32; @desc: Returns the index containing the largest element in the array. } function TDoubleArray.ArgMax(): Int32; var mat:TDoubleMatrix; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMax(mat).x; end; {!DOCREF} { @method: function TDoubleArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the largest element in the array. } function TDoubleArray.ArgMax(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TDoubleMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMax(n), Result, _); end; {!DOCREF} { @method: function TDoubleArray.ArgMax(Lo,Hi:int32): Int32; overload; @desc: Returns the index containing the largest element in the array within the lower and upper bounds c'lo, hi'. } function TDoubleArray.ArgMax(lo,hi:Int32): Int32; overload; var B: TBox; mat:TDoubleMatrix; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMax(mat,B).x; end;
{ Subroutine SST_R_PAS_WRITE * * Process a WRITE or WRITELN statement. The tag indicating a WRITE or * WRITELN statement was just read in the RAW_STATEMENT syntax. } module sst_r_pas_WRITE; define sst_r_pas_write; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_write; {process WRITE and WRITELN statements} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} strh_top: syo_string_t; {string handle for top WRITE/WRITELN tag} fw_max: sys_int_machine_t; {max field width specifiers allowed} fw_n: sys_int_machine_t; {field width specifier number} exp_p: sst_exp_p_t; {scratch pointer to expression descriptor} eol: boolean; {TRUE if need EOL after all writes} label loop_arg, loop_width; begin syo_get_tag_msg ( {get WRITE/WRITELN tag} tag, strh_top, 'sst_pas_read', 'write_sment_bad', nil, 0); case tag of 1: eol := false; {WRITE statement} 2: eol := true; {WRITELN statement} otherwise syo_error_tag_unexp (tag, strh_top); end; { ****************************** * * Loop back here each new WRITELN_ARG syntax. } loop_arg: syo_get_tag_msg ( {get tag for next WRITE/WRITELN argument} tag, str_h, 'sst_pas_read', 'write_sment_bad', nil, 0); case tag of { * This tag in RAW_STATEMENT was for new WRITELN_ARG syntax. } 1: begin {tag was for next argument in list} sst_opcode_new; {make new opcode for this argument} sst_opc_p^.str_h := str_h; {save handle to source stream characters} sst_opc_p^.opcode := sst_opc_write_k; {indicate what kind of opcode this is} syo_level_down; {down into WRITELN_ARG syntax} syo_get_tag_msg ( {tag for expression of value to write} tag, str_h, 'sst_pas_read', 'write_sment_bad', nil, 0); sst_r_pas_exp (str_h, false, sst_opc_p^.write_exp_p); {get write value expression} sst_opc_p^.write_width_exp_p := nil; {init to use free format to write value} sst_opc_p^.write_width2_exp_p := nil; if sst_opc_p^.write_exp_p^.val.dtype = sst_dtype_float_k then fw_max := 2 {2 field widths allowed for floating point} else fw_max := 1; {1 field width allowed for everything else} fw_n := 1; {init number of next field width specifier} loop_width: {back here for each new field width specifier} syo_get_tag_msg ( {tag for next field width expression} tag, str_h, 'sst_pas_read', 'write_sment_bad', nil, 0); case tag of 1: begin {found another field width specifier} if fw_n > fw_max then begin syo_error (str_h, 'sst_pas_read', 'write_fwidths_too_many', nil, 0); end; sst_r_pas_exp (str_h, false, exp_p); {create field width expression descriptor} if exp_p^.val.dtype <> sst_dtype_int_k then begin {field width not integer ?} syo_error (str_h, 'sst_pas_read', 'write_fwidth_not_integer', nil, 0); end; case fw_n of {set the right field width exp pointer} 1: sst_opc_p^.write_width_exp_p := exp_p; 2: sst_opc_p^.write_width2_exp_p := exp_p; end; fw_n := fw_n + 1; {make number of next field width specifier} goto loop_width; {back for next field width specifier} end; {end of tag is field width specifier case} syo_tag_end_k: ; {exit loop on no more field width specifiers} otherwise syo_error_tag_unexp (tag, str_h); end; syo_level_up; {back up from WRITELN_ARG syntax} goto loop_arg; {back for next argument in WRITE/WRITELN} end; {done with tag for this WRITELN_ARG syntax} { * Tag indicates end of RAW_STATEMENT syntax. } syo_tag_end_k: ; {exit args loop} { * Unexpected tag in RAW_STATEMENT. } otherwise syo_error_tag_unexp (tag, str_h); end; { ****************************** * * We have hit the end of the RAW_STATEMENT syntax. This definately ends * the WRITE/WRITELN statement. We still need to indicate writing the EOL * if the original statement was a WRITELN (instead of WRITE). } if eol then begin {need to write end of line ?} sst_opcode_new; {create the "write end of line" opcode} sst_opc_p^.str_h := strh_top; {save handle to source stream characters} sst_opc_p^.opcode := sst_opc_write_eol_k; {set the type of opcode this is} end; end;
{$I ACBr.inc} unit ACBrCIOTOperacoesTransporte; interface uses Classes, Sysutils, Dialogs, Forms, StrUtils, ACBrCIOTUtil, ACBrCIOTConfiguracoes, //ACBrCTeDACTEClass, smtpsend, ssl_openssl, mimemess, mimepart, // units para enviar email pciotCIOT, pciotVeiculoR, pciotVeiculoW, pcnConversao, pcnAuxiliar, pcnLeitor; type OperacaoTransporte = class(TCollectionItem) private FCIOT: TOperacaoTransporte; FXML: AnsiString; FXMLOriginal: AnsiString; FConfirmada : Boolean; FMsg : AnsiString ; FAlertas: AnsiString; FErroValidacao: AnsiString; FErroValidacaoCompleto: AnsiString; FNomeArq: String; function GetCTeXML: AnsiString; public constructor Create(Collection2: TCollection); override; destructor Destroy; override; procedure Imprimir; procedure ImprimirPDF; function SaveToFile(CaminhoArquivo: string = ''): boolean; function SaveToStream(Stream: TStringStream): boolean; procedure EnviarEmail(const sSmtpHost, sSmtpPort, sSmtpUser, sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem : TStrings; SSL : Boolean; EnviaPDF: Boolean = true; sCC: TStrings = nil; Anexos:TStrings=nil; PedeConfirma: Boolean = False; AguardarEnvio: Boolean = False; NomeRemetente: String = ''; TLS : Boolean = True; UsarThread: Boolean = True); property CTe: TOperacaoTransporte read FCIOT write FCIOT; property XML: AnsiString read GetCTeXML write FXML; property XMLOriginal: AnsiString read FXMLOriginal write FXMLOriginal; property Confirmada: Boolean read FConfirmada write FConfirmada; property Msg: AnsiString read FMsg write FMsg; property Alertas: AnsiString read FAlertas write FAlertas; property ErroValidacao: AnsiString read FErroValidacao write FErroValidacao; property ErroValidacaoCompleto: AnsiString read FErroValidacaoCompleto write FErroValidacaoCompleto; property NomeArq: String read FNomeArq write FNomeArq; end; TOperacoesTransporte = class(TOwnedCollection) private FConfiguracoes : TConfiguracoes; FACBrCIOT : TComponent ; function GetItem(Index: Integer): OperacaoTransporte; procedure SetItem(Index: Integer; const Value: OperacaoTransporte); public constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); procedure GerarCTe; procedure Assinar; procedure Valida; function ValidaAssinatura(out Msg : String) : Boolean; procedure Imprimir; procedure ImprimirPDF; function Add: OperacaoTransporte; function Insert(Index: Integer): OperacaoTransporte; property Items[Index: Integer]: OperacaoTransporte read GetItem write SetItem; property Configuracoes: TConfiguracoes read FConfiguracoes write FConfiguracoes; function GetNamePath: string; override ; // Incluido o Parametro AGerarCTe que determina se após carregar os dados do CTe // para o componente, será gerado ou não novamente o XML do CTe. function LoadFromFile(CaminhoArquivo: string; AGerarCTe: Boolean = True): boolean; function LoadFromStream(Stream: TStringStream; AGerarCTe: Boolean = True): boolean; function LoadFromString(AString: String; AGerarCTe: Boolean = True): boolean; function SaveToFile(PathArquivo: string = ''): boolean; property ACBrCIOT : TComponent read FACBrCIOT ; end; TSendMailThread = class(TThread) private FException : Exception; // FOwner: Conhecimento; procedure DoHandleException; public OcorreramErros: Boolean; Terminado: Boolean; smtp : TSMTPSend; sFrom : String; sTo : String; sCC : TStrings; slmsg_Lines : TStrings; constructor Create; destructor Destroy; override; protected procedure Execute; override; procedure HandleException; end; implementation uses ACBrCIOT, ACBrUtil, ACBrDFeUtil, pcnGerador; { Conhecimento } constructor OperacaoTransporte.Create(Collection2: TCollection); begin inherited Create(Collection2); FCIOT := TOperacaoTransporte.Create; // FCIOT.Ide.tpCTe := tcNormal; // FCIOT.Ide.modelo := '57'; // // FCIOT.Ide.verProc := 'ACBrCIOT'; // FCIOT.Ide.tpAmb := TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).Configuracoes.WebServices.Ambiente; // FCIOT.Ide.tpEmis := TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).Configuracoes.Geral.FormaEmissao; // if Assigned(TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTe) then // FCIOT.Ide.tpImp := TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTe.TipoDACTE; end; destructor OperacaoTransporte.Destroy; begin FCIOT.Free; inherited Destroy; end; procedure OperacaoTransporte.Imprimir; begin // if not Assigned( TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE ) then // raise Exception.Create('Componente DACTE não associado.') // else // TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE.ImprimirDACTE(CTe); end; procedure OperacaoTransporte.ImprimirPDF; begin // if not Assigned( TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE ) then // raise Exception.Create('Componente DACTE não associado.') // else // TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE.ImprimirDACTEPDF(CTe); end; function OperacaoTransporte.SaveToFile(CaminhoArquivo: string = ''): boolean; //var // LocCTeW : TCTeW; begin // try // Result := True; // LocCTeW := TCTeW.Create(CIOT); // try // LocCTeW.Gerador.Opcoes.FormatoAlerta := TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).Configuracoes.Geral.FormatoAlerta; // LocCTeW.GerarXml; // if DFeUtil.EstaVazio(CaminhoArquivo) then // CaminhoArquivo := PathWithDelim(TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).Configuracoes.Geral.PathSalvar)+copy(CTe.inFCTe.ID, (length(CTe.inFCTe.ID)-44)+1, 44)+'-cte.xml'; // if DFeUtil.EstaVazio(CaminhoArquivo) or not DirectoryExists(ExtractFilePath(CaminhoArquivo)) then // raise Exception.Create('Caminho Inválido: ' + CaminhoArquivo); // LocCTeW.Gerador.SalvarArquivo(CaminhoArquivo); // NomeArq := CaminhoArquivo; // finally // LocCTeW.Free; // end; // except // raise; // Result := False; // end; end; function OperacaoTransporte.SaveToStream(Stream: TStringStream): boolean; //var // LocCTeW : TCTeW; begin // try // Result := True; // LocCTeW := TCTeW.Create(CTe); // try // LocCTeW.Gerador.Opcoes.FormatoAlerta := TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).Configuracoes.Geral.FormatoAlerta; // LocCTeW.GerarXml; // Stream.WriteString(LocCTeW.Gerador.ArquivoFormatoXML); // finally // LocCTeW.Free; // end; // except // Result := False; // end; end; procedure OperacaoTransporte.EnviarEmail(const sSmtpHost, sSmtpPort, sSmtpUser, sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem : TStrings; SSL : Boolean; EnviaPDF: Boolean = true; sCC: TStrings=nil; Anexos:TStrings=nil; PedeConfirma: Boolean = False; AguardarEnvio: Boolean = False; NomeRemetente: String = ''; TLS : Boolean = True; UsarThread: Boolean = True); var NomeArq : String; AnexosEmail:TStrings ; StreamCTe : TStringStream; begin AnexosEmail := TStringList.Create; StreamCTe := TStringStream.Create(''); try AnexosEmail.Clear; if Anexos <> nil then AnexosEmail.Text := Anexos.Text; if NomeArq <> '' then begin SaveToFile(NomeArq); AnexosEmail.Add(NomeArq); end else begin SaveToStream(StreamCTe) ; end; if (EnviaPDF) then begin // if TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE <> nil then // begin // TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE.ImprimirDACTEPDF(CTe); // NomeArq := StringReplace(CTe.infCTe.ID,'CTe', '', [rfIgnoreCase]); // NomeArq := PathWithDelim(TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).DACTE.PathPDF)+NomeArq+'.pdf'; // AnexosEmail.Add(NomeArq); // end; end; // TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).EnviaEmail(sSmtpHost, // sSmtpPort, // sSmtpUser, // sSmtpPasswd, // sFrom, // sTo, // sAssunto, // sMensagem, // SSL, // sCC, // AnexosEmail, // PedeConfirma, // AguardarEnvio, // NomeRemetente, // TLS, // StreamCTe, // copy(CTe.infCTe.ID, (length(CTe.infCTe.ID)-44)+1, 44)+'-CTe.xml', // UsarThread); finally AnexosEmail.Free ; StreamCTe.Free ; end; end; function OperacaoTransporte.GetCTeXML: AnsiString; //var // LocCTeW : TCTeW; begin // LocCTeW := TCTeW.Create(Self.CTe); // try // LocCTeW.Gerador.Opcoes.FormatoAlerta := TACBrCIOT( TOperacoesTransporte( Collection ).ACBrCTe ).Configuracoes.Geral.FormatoAlerta; // LocCTeW.GerarXml; // Result := LocCTeW.Gerador.ArquivoFormatoXML; // finally // LocCTeW.Free; // end; end; { TOperacoesTransporte } constructor TOperacoesTransporte.Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); begin if not (AOwner is TACBrCIOT ) then raise Exception.Create( 'AOwner deve ser do tipo TACBrCIOT') ; inherited; FACBrCIOT := TACBrCIOT( AOwner ) ; end; function TOperacoesTransporte.Add: OperacaoTransporte; begin Result := OperacaoTransporte(inherited Add); // Result.CTe.Ide.tpAmb := Configuracoes.WebServices.Ambiente ; end; procedure TOperacoesTransporte.Assinar; var i: Integer; vAssinada : AnsiString; // LocCTeW : TCTeW; Leitor: TLeitor; FMsg : AnsiString; begin for i:= 0 to Self.Count-1 do begin // LocCTeW := TCTeW.Create(Self.Items[i].CTe); try // LocCTeW.Gerador.Opcoes.FormatoAlerta := FConfiguracoes.Geral.FormatoAlerta; // LocCTeW.GerarXml; // Self.Items[i].Alertas := LocCTeW.Gerador.ListaDeAlertas.Text; {$IFDEF ACBrCTeOpenSSL} // if not(CTeUtil.Assinar(LocCTeW.Gerador.ArquivoFormatoXML, FConfiguracoes.Certificados.Certificado , FConfiguracoes.Certificados.Senha, vAssinada, FMsg)) then // raise Exception.Create('Falha ao assinar Conhecimento de Transporte Eletrônico '+ // IntToStr(Self.Items[i].CTe.Ide.cCT)+FMsg); {$ELSE} // if not(CTeUtil.Assinar(LocCTeW.Gerador.ArquivoFormatoXML, FConfiguracoes.Certificados.GetCertificado , vAssinada, FMsg)) then // raise Exception.Create('Falha ao assinar Conhecimento de Transporte Eletrônico '+ // IntToStr(Self.Items[i].CTe.Ide.cCT)+FMsg); {$ENDIF} // vAssinada := StringReplace( vAssinada, '<'+ENCODING_UTF8_STD+'>', '', [rfReplaceAll] ) ; // vAssinada := StringReplace( vAssinada, '<?xml version="1.0"?>', '', [rfReplaceAll] ) ; // Self.Items[i].XML := vAssinada; // // Leitor := TLeitor.Create; // leitor.Grupo := vAssinada; // Self.Items[i].CTe.signature.URI := Leitor.rAtributo('Reference URI='); // Self.Items[i].CTe.signature.DigestValue := Leitor.rCampo(tcStr, 'DigestValue'); // Self.Items[i].CTe.signature.SignatureValue := Leitor.rCampo(tcStr, 'SignatureValue'); // Self.Items[i].CTe.signature.X509Certificate := Leitor.rCampo(tcStr, 'X509Certificate'); // Leitor.Free; // // if FConfiguracoes.Geral.Salvar then // FConfiguracoes.Geral.Save(StringReplace(Self.Items[i].CTe.infCTe.ID, 'CTe', '', [rfIgnoreCase])+'-cte.xml', vAssinada); // // if DFeUtil.NaoEstaVazio(Self.Items[i].NomeArq) then // FConfiguracoes.Geral.Save(ExtractFileName(Self.Items[i].NomeArq), vAssinada, ExtractFilePath(Self.Items[i].NomeArq)); finally // LocCTeW.Free; end; end; end; procedure TOperacoesTransporte.GerarCTe; var i: Integer; // LocCTeW : TCTeW; begin for i:= 0 to Self.Count-1 do begin // LocCTeW := TCTeW.Create(Self.Items[i].CTe); // try // LocCTeW.Gerador.Opcoes.FormatoAlerta := FConfiguracoes.Geral.FormatoAlerta; // LocCTeW.GerarXml; // Self.Items[i].XML := LocCTeW.Gerador.ArquivoFormatoXML; // Self.Items[i].Alertas := LocCTeW.Gerador.ListaDeAlertas.Text; // finally // LocCTeW.Free; // end; end; end; function TOperacoesTransporte.GetItem(Index: Integer): OperacaoTransporte; begin Result := OperacaoTransporte(inherited Items[Index]); end; function TOperacoesTransporte.GetNamePath: string; begin Result := 'OperacaoTransporte'; end; procedure TOperacoesTransporte.Imprimir; begin // if not Assigned( TACBrCIOT( FACBrCIOT ).DACTE ) then // raise Exception.Create('Componente DACTE não associado.') // else // TACBrCIOT( FACBrCIOT ).DACTe.ImprimirDACTe(nil); end; procedure TOperacoesTransporte.ImprimirPDF; begin // if not Assigned( TACBrCIOT( FACBrCIOT ).DACTE ) then // raise Exception.Create('Componente DACTE não associado.') // else // TACBrCIOT( FACBrCIOT ).DACTe.ImprimirDACTePDF(nil); end; function TOperacoesTransporte.Insert(Index: Integer): OperacaoTransporte; begin Result := OperacaoTransporte(inherited Insert(Index)); end; procedure TOperacoesTransporte.SetItem(Index: Integer; const Value: OperacaoTransporte); begin Items[Index].Assign(Value); end; procedure TOperacoesTransporte.Valida; var i: Integer; FMsg : AnsiString; begin (* for i:= 0 to Self.Count-1 do begin if pos('<Signature',Self.Items[i].XML) = 0 then Assinar; if not(CTeUtil.Valida(('<CTe xmlns' + RetornarConteudoEntre(Self.Items[i].XML, '<CTe xmlns', '</CTe>')+ '</CTe>'), FMsg, Self.FConfiguracoes.Geral.PathSchemas)) then raise Exception.Create('Falha na validação dos dados do Conhecimento '+ IntToStr(Self.Items[i].CTe.Ide.nCT) + sLineBreak + Self.Items[i].Alertas + FMsg); end; *) // for i:= 0 to Self.Count-1 do // begin // if pos('<Signature',Self.Items[i].XML) = 0 then // Assinar; // if not(CTeUtil.Valida(('<CTe xmlns' + RetornarConteudoEntre(Self.Items[i].XML, '<CTe xmlns', '</CTe>')+ '</CTe>'), // FMsg, Self.FConfiguracoes.Geral.PathSchemas)) then // begin // Self.Items[i].ErroValidacaoCompleto := 'Falha na validação dos dados da nota '+ // IntToStr(Self.Items[i].CTe.Ide.nCT)+sLineBreak+ // Self.Items[i].Alertas+ // FMsg; // Self.Items[i].ErroValidacao := 'Falha na validação dos dados da nota '+ // IntToStr(Self.Items[i].CTe.Ide.nCT)+sLineBreak+ // Self.Items[i].Alertas+ // IfThen(Self.FConfiguracoes.Geral.ExibirErroSchema,FMsg,''); // raise Exception.Create(Self.Items[i].ErroValidacao); // end; // end; end; function TOperacoesTransporte.ValidaAssinatura(out Msg : String) : Boolean; var i: Integer; FMsg : AnsiString; begin Result := True; for i:= 0 to Self.Count-1 do begin // if not(CTeUtil.ValidaAssinatura(Self.Items[i].XMLOriginal, FMsg)) then // begin Result := False; // Msg := 'Falha na validação da assinatura do conhecimento '+ // IntToStr(Self.Items[i].CTe.Ide.nCT)+sLineBreak+FMsg // end // else Result := True; end; end; function TOperacoesTransporte.LoadFromFile(CaminhoArquivo: string; AGerarCTe: Boolean = True): boolean; var LocCTeR : TVeiculoR; ArquivoXML: TStringList; XML, XMLOriginal : AnsiString; begin try ArquivoXML := TStringList.Create; try ArquivoXML.LoadFromFile(CaminhoArquivo {$IFDEF DELPHI2009_UP}, TEncoding.UTF8{$ENDIF}); XMLOriginal := ArquivoXML.Text; Result := True; while pos('</CTe>',ArquivoXML.Text) > 0 do begin if pos('</cteProc>',ArquivoXML.Text) > 0 then begin XML := copy(ArquivoXML.Text,1,pos('</cteProc>',ArquivoXML.Text)+5); ArquivoXML.Text := Trim(copy(ArquivoXML.Text,pos('</cteProc>',ArquivoXML.Text)+10,length(ArquivoXML.Text))); end else begin XML := copy(ArquivoXML.Text,1,pos('</CTe>',ArquivoXML.Text)+5); ArquivoXML.Text := Trim(copy(ArquivoXML.Text,pos('</CTe>',ArquivoXML.Text)+6,length(ArquivoXML.Text))); end; // LocCTeR := TCTeR.Create(Self.Add.CTe); try LocCTeR.Leitor.Arquivo := XML; LocCTeR.LerXml; Items[Self.Count-1].XML := LocCTeR.Leitor.Arquivo; Items[Self.Count-1].XMLOriginal := XMLOriginal; Items[Self.Count-1].NomeArq := CaminhoArquivo; if AGerarCTe then GerarCTe; finally LocCTeR.Free; end; end; finally ArquivoXML.Free; end; except raise; Result := False; end; end; function TOperacoesTransporte.LoadFromStream(Stream: TStringStream; AGerarCTe: Boolean = True): boolean; var LocCTeR : TVeiculoR; begin try Result := True; // LocCTeR := TCTeR.Create(Self.Add.CTe); // try // LocCTeR.Leitor.CarregarArquivo(Stream); // LocCTeR.LerXml; // Items[Self.Count-1].XML := LocCTeR.Leitor.Arquivo; // Items[Self.Count-1].XMLOriginal := Stream.DataString; // if AGerarCTe then GerarCTe; // finally // LocCTeR.Free // end; except Result := False; end; end; function TOperacoesTransporte.SaveToFile(PathArquivo: string = ''): boolean; var i : integer; CaminhoArquivo : String; begin Result := True; try for i:= 0 to TACBrCIOT( FACBrCIOT ).OperacoesTransporte.Count-1 do begin if DFeUtil.EstaVazio(PathArquivo) then PathArquivo := TACBrCIOT( FACBrCIOT ).Configuracoes.Geral.PathSalvar else PathArquivo := ExtractFilePath(PathArquivo); // CaminhoArquivo := PathWithDelim(PathArquivo)+copy(TACBrCIOT( FACBrCIOT ).OperacoesTransporte.Items[i].CTe.inFCTe.ID, (length(TACBrCIOT( FACBrCIOT ).OperacoesTransporte.Items[i].CTe.inFCTe.ID)-44)+1, 44)+'-cte.xml'; TACBrCIOT( FACBrCIOT ).OperacoesTransporte.Items[i].SaveToFile(CaminhoArquivo) end; except Result := False; end; end; function TOperacoesTransporte.LoadFromString(AString: String; AGerarCTe: Boolean = True): boolean; var XMLCTe: TStringStream; begin try XMLCTe := TStringStream.Create(''); try XMLCTe.WriteString(AString); Result := LoadFromStream(XMLCTe, AGerarCTe); finally XMLCTe.Free; end; except Result := False; end; end; { TSendMailThread } procedure TSendMailThread.DoHandleException; begin // TACBrCIOT(TOperacoesTransporte(FOwner.GetOwner).ACBrCTe).SetStatus( stCTeIdle ); // FOwner.Alertas := FException.Message; if FException is Exception then Application.ShowException(FException) else SysUtils.ShowException(FException, nil); end; constructor TSendMailThread.Create; begin smtp := TSMTPSend.Create; slmsg_Lines := TStringList.Create; sCC := TStringList.Create; sFrom := ''; sTo := ''; FreeOnTerminate := True; inherited Create(True); end; destructor TSendMailThread.Destroy; begin slmsg_Lines.Free; sCC.Free; smtp.Free; inherited; end; procedure TSendMailThread.Execute; var i: integer; begin inherited; try Terminado := False; try if not smtp.Login() then raise Exception.Create('SMTP ERROR: Login:' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text); if not smtp.MailFrom( sFrom, Length(sFrom)) then raise Exception.Create('SMTP ERROR: MailFrom:' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text); if not smtp.MailTo(sTo) then raise Exception.Create('SMTP ERROR: MailTo:' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text); if (sCC <> nil) then begin for I := 0 to sCC.Count - 1 do begin if not smtp.MailTo(sCC.Strings[i]) then raise Exception.Create('SMTP ERROR: MailTo:' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text); end; end; if not smtp.MailData(slmsg_Lines) then raise Exception.Create('SMTP ERROR: MailData:' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text); if not smtp.Logout() then raise Exception.Create('SMTP ERROR: Logout:' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text); finally try smtp.Sock.CloseSocket; except end ; Terminado := True; end; except Terminado := True; HandleException; end; end; procedure TSendMailThread.HandleException; begin FException := Exception(ExceptObject); try // Não mostra mensagens de EAbort if not (FException is EAbort) then Synchronize(DoHandleException); finally FException := nil; end; end; end.
unit TableSelectTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Модуль: "w:/common/components/gui/Garant/Daily/TableSelectTest.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TTableSelectTest // // Базовый тест для работы с выделением таблицы // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses nevTools, TextEditorVisitor, PrimTextLoad_Form ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TTableSelectTest = {abstract} class(TTextEditorVisitor) {* Базовый тест для работы с выделением таблицы } protected // realized methods procedure DoVisit(aForm: TPrimTextLoadForm); override; {* Обработать текст } protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } protected // protected methods function GetTablePara(const aDocument: InevParaList): InevParaList; virtual; abstract; {* Возвращает параграф с таблицей } function SelectColumn(var aColID: Integer): Boolean; virtual; {* Выделить колонку aColID } end;//TTableSelectTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses evCursorTools, evOp, TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TTableSelectTest function TTableSelectTest.SelectColumn(var aColID: Integer): Boolean; //#UC START# *4C382DC50185_4C382CB00345_var* //#UC END# *4C382DC50185_4C382CB00345_var* begin //#UC START# *4C382DC50185_4C382CB00345_impl* Result := False; aColID := 0; //#UC END# *4C382DC50185_4C382CB00345_impl* end;//TTableSelectTest.SelectColumn procedure TTableSelectTest.DoVisit(aForm: TPrimTextLoadForm); //#UC START# *4BE419AF0217_4C382CB00345_var* var l_ColID : Integer; l_Selection : InevSelection; //#UC END# *4BE419AF0217_4C382CB00345_var* begin //#UC START# *4BE419AF0217_4C382CB00345_impl* l_Selection := aForm.Text.Selection; if (l_Selection <> nil) and SelectColumn(l_ColID) then evSelectTableColumn(l_Selection, GetTablePara(aForm.Text.Document), l_ColID) //#UC END# *4BE419AF0217_4C382CB00345_impl* end;//TTableSelectTest.DoVisit function TTableSelectTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TTableSelectTest.GetFolder function TTableSelectTest.GetModelElementGUID: AnsiString; {-} begin Result := '4C382CB00345'; end;//TTableSelectTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit vtDebug; {$I vtDefine.inc } {.$Define OutToConsole} interface uses Sysutils; Type TvtDebugException = class(Exception); procedure dbgAppendToLogLN(const aFileName : TFileName; const aText : String); overload; procedure dbgAppendToLogLN(const aText : String); overload; procedure dbgAppendToLog(const aFileName : TFileName; const aText : String); overload; procedure dbgAppendToLog(const aText : String); overload; function dbgStartTimeCounter : Cardinal; function dbgFinishTimeCounter(aStartTime : Cardinal; const aFormat : String = '') : String; implementation uses Windows, vtLogFile; const DbgExt = '.dbg'; var DbgIsFirstTime : Boolean = True; dbgDefFileName : TFileName; procedure AppendToLog(aFileName : TFileName; aText : String); begin if DbgIsFirstTime then begin DbgIsFirstTime := False; vtLogFile.AppendToLog(aFileName, ' -'#4'- Start Debug ' + DateTimeToStr(Now) + #13#10); end; vtLogFile.AppendToLog(aFileName, aText); end; function dbgStartTimeCounter : Cardinal; begin Result := GetTickCount; end; function dbgFinishTimeCounter(aStartTime : Cardinal; const aFormat : String = '') : String; var lFinishTime : Cardinal; lElapsedTime : Int64; begin lFinishTime := GetTickCount; lElapsedTime := Int64(lFinishTime) - Int64(aStartTime); if lElapsedTime < 0 then lElapsedTime := lElapsedTime + High(Cardinal); if aFormat = '' then Result := Format('Elapsed time %d ms',[lElapsedTime]) else Result := Format(aFormat,[lElapsedTime]); end; procedure dbgAppendToLogLN(const aFileName : TFileName; const aText : String); begin AppendToLog(aFileName, aText+#13#10); end; procedure dbgAppendToLogLN(const aText : String); begin //{$Ifdef Console} // WriteLN(aText); //{$else} AppendToLog(dbgDefFileName, aText+#13#10); //{$Endif} end; procedure dbgAppendToLog(const aFileName : TFileName; const aText : String); begin AppendToLog(aFileName, aText); end; procedure dbgAppendToLog(const aText : String); begin //{$Ifdef Console} // Write(aText); //{$else} AppendToLog(dbgDefFileName, aText); //{$endif} end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VT\vtDebug.pas initialization enter'); {$EndIf} //uses Forms; dbgDefFileName := ChangeFileExt(ParamStr(0), DbgExt); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VT\vtDebug.pas initialization leave'); {$EndIf} end.
unit RESTRequest4D.Request.Authentication.Intf; interface type /// <summary> /// Interface that represents the authentication of the request. /// </summary> IRequestAuthentication = interface ['{872B5C31-1FD3-4852-9181-CDAB194F9C38}'] /// <summary> /// Removes authentication data. /// </summary> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Clear: IRequestAuthentication; /// <summary> /// Sets the authentication password. /// </summary> /// <param name="APassword"> /// Password to authenticate the request. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function SetPassword(const APassword: string): IRequestAuthentication; /// <summary> /// Returns the password set for authentication. /// </summary> /// <returns> /// Password set. /// </returns> function GetPassword: string; /// <summary> /// Sets the authentication user. /// </summary> /// <param name="AUser"> /// User to authenticate the request. /// </param> /// <returns> /// Retorna a própria instância seguindo o padrão fluent API. /// </returns> function SetUsername(const AUser: string): IRequestAuthentication; /// <summary> /// Returns the user set for authentication. /// </summary> /// <returns> /// User defined. /// </returns> function GetUsername: string; end; implementation end.
{$INCLUDE ../../flcInclude.inc} {$INCLUDE ../flcCrypto.inc} unit flcTestCryptoHash; interface {$IFDEF CRYPTO_TEST} procedure Test; {$ENDIF} implementation {$IFDEF CRYPTO_TEST} uses flcCryptoUtils, flcCryptoHash; { } { Test } { } {$ASSERTIONS ON} procedure Test; function DupChar(const Count: Integer; const Ch: Byte): RawByteString; var A : RawByteString; I : Integer; begin A := ''; for I := 1 to Count do A := A + AnsiChar(Ch); Result := A; end; const QuickBrownFoxStr = 'The quick brown fox jumps over the lazy dog'; var MillionA, TenThousandA : RawByteString; S, T : RawByteString; U : UnicodeString; begin // SecureClear allocated string reference SetLength(S, 5); FillChar(S[1], 5, #1); SecureClearStrB(S); Assert(Length(S) = 0); // SetLength(U, 5); FillChar(U[1], 10, #1); SecureClearStrU(U); Assert(U = ''); // SecureClear constant string reference S := 'ABC'; SecureClearStrB(S); // U := 'ABC'; SecureClearStrU(U); SetLength(MillionA, 1000000); FillChar(MillionA[1], 1000000, Ord('a')); SetLength(TenThousandA, 10000); FillChar(TenThousandA[1], 10000, Ord('a')); Assert(UnicodeString(MD5DigestToHexA(CalcMD5(''))) = MD5DigestToHexU(CalcMD5(''))); Assert(MD5DigestToHexA(CalcMD5('')) = 'd41d8cd98f00b204e9800998ecf8427e'); Assert(MD5DigestToHexA(CalcMD5('Delphi Fundamentals')) = 'ea98b65da23d19756d46a36faa481dd8'); Assert(UnicodeString(SHA1DigestToHexA(CalcSHA1(''))) = SHA1DigestToHexU(CalcSHA1(''))); Assert(SHA1DigestToHexA(CalcSHA1('')) = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'); Assert(SHA1DigestToHexA(CalcSHA1('Fundamentals')) = '052d8ad81d99f33b2eb06e6d194282b8675fb201'); Assert(SHA1DigestToHexA(CalcSHA1(QuickBrownFoxStr)) = '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12'); Assert(SHA1DigestToHexA(CalcSHA1(TenThousandA)) = 'a080cbda64850abb7b7f67ee875ba068074ff6fe'); Assert(UnicodeString(SHA224DigestToHexA(CalcSHA224(''))) = SHA224DigestToHexU(CalcSHA224(''))); Assert(SHA224DigestToHexA(CalcSHA224('')) = 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f'); Assert(SHA224DigestToHexA(CalcSHA224('Fundamentals')) = '1cccba6b3c6b08494733efb3a77fe8baef5bf6eeae89ec303ef4660e'); Assert(SHA224DigestToHexA(CalcSHA224(QuickBrownFoxStr)) = '730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525'); Assert(SHA224DigestToHexA(CalcSHA224(TenThousandA)) = '00568fba93e8718c2f7dcd82fa94501d59bb1bbcba2c7dc2ba5882db'); Assert(UnicodeString(SHA256DigestToHexA(CalcSHA256(''))) = SHA256DigestToHexU(CalcSHA256(''))); Assert(SHA256DigestToHexA(CalcSHA256('')) = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'); Assert(SHA256DigestToHexA(CalcSHA256('Fundamentals')) = '915ff7435daeac2f66aa866e59bf293f101b79403dbdde2b631fd37fa524f26b'); Assert(SHA256DigestToHexA(CalcSHA256(QuickBrownFoxStr)) = 'd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592'); Assert(SHA256DigestToHexA(CalcSHA256(TenThousandA)) = '27dd1f61b867b6a0f6e9d8a41c43231de52107e53ae424de8f847b821db4b711'); Assert(SHA256DigestToHexA(CalcSHA256(MillionA)) = 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0'); Assert(UnicodeString(SHA384DigestToHexA(CalcSHA384(''))) = SHA384DigestToHexU(CalcSHA384(''))); Assert(SHA384DigestToHexA(CalcSHA384('')) = '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b'); Assert(SHA384DigestToHexA(CalcSHA384('Fundamentals')) = 'cf9380b7d2e0237296093a0f5f09066f0cea0742ba752a1e6c60aed92998eda2c86c1549879007a94e9d75a4a7bdb6e8'); Assert(SHA384DigestToHexA(CalcSHA384(QuickBrownFoxStr)) = 'ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1'); Assert(SHA384DigestToHexA(CalcSHA384(TenThousandA)) = '2bca3b131bb7e922bcd1de98c44786d32e6b6b2993e69c4987edf9dd49711eb501f0e98ad248d839f6bf9e116e25a97c'); Assert(UnicodeString(SHA512DigestToHexA(CalcSHA512(''))) = SHA512DigestToHexU(CalcSHA512(''))); Assert(SHA512DigestToHexA(CalcSHA512('')) = 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'); Assert(SHA512DigestToHexA(CalcSHA512('Fundamentals')) = 'f430fed95ff285843bc68a5e2a1ad8275d7c242a504a5d0b23deb7f8252774a132c3672aeeffa9bf5c25449e8905cdb6f89097a3c88f20a6e0d8945bf4310dd6'); Assert(SHA512DigestToHexA(CalcSHA512(QuickBrownFoxStr)) = '07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6'); Assert(SHA512DigestToHexA(CalcSHA512(TenThousandA)) = '0593036f4f479d2eb8078ca26b1d59321a86bdfcb04cb40043694f1eb0301b8acd20b936db3c916ebcc1b609400ffcf3fa8d569d7e39293855668645094baf0e'); Assert(MD5DigestToHexA(CalcHMAC_MD5('', '')) = '74e6f7298a9c2d168935f58c001bad88'); Assert(MD5DigestToHexA(CalcHMAC_MD5('', 'Delphi Fundamentals')) = 'b9da02d5f94bd6eac410708a72b05d9f'); Assert(MD5DigestToHexA(CalcHMAC_MD5('Delphi Fundamentals', '')) = 'a09f3300c236156d27f4d031db7e91ce'); Assert(MD5DigestToHexA(CalcHMAC_MD5('Delphi', 'Fundamentals')) = '1c4e8a481c2c781eb43ca58d9324c37d'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1('', '')) = 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1('', QuickBrownFoxStr)) = '2ba7f707ad5f187c412de3106583c3111d668de8'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1('Fundamentals', QuickBrownFoxStr)) = '8b52855bbd09842d4ac3e4ff4c574c1f87d63e0b'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1('Fundamentals', '')) = '2208ce7279f26fcb90dbc1900019aa9b2b85456a'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1('Fundamentals', TenThousandA)) = '2f9cf91c82963b54fdbc0a26149be0c1f29746dc'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1(TenThousandA, TenThousandA)) = 'cf792cef5570b47f3e1272581a5af87e5715defd'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256('', '')) = 'b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256('', QuickBrownFoxStr)) = 'fb011e6154a19b9a4c767373c305275a5a69e8b68b0b4c9200c383dced19a416'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256('Fundamentals', QuickBrownFoxStr)) = '853b22d0aa389d8123452710b3d09ed7f0b5afe4114896bfeb8cfd8818963146'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256('Fundamentals', '')) = '28659c86585404fe0e87255bc9a2244ff1d921d48f9c5f8b12b4b40a064a20a3'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256('Fundamentals', TenThousandA)) = '42347405bf2a459054bd95af2c48e070275d0d701ee62108b385a6e925c43163'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256(TenThousandA, TenThousandA)) = '6b7576a741bd2eb2c1c12017d5f4984108ce25a3a427a3d5f52ba93c0ac85e1f'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512('', '')) = 'b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512('', QuickBrownFoxStr)) = '1de78322e11d7f8f1035c12740f2b902353f6f4ac4233ae455baccdf9f37791566e790d5c7682aad5d3ceca2feff4d3f3fdfd9a140c82a66324e9442b8af71b6'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512('Fundamentals', QuickBrownFoxStr)) = 'f0352dff9b8984fb5fcfdd95de7f9db3df990723a2d909b99faf8cd4ccb9a5b1b840282c190ad41e521eb662512782bb9bf0fb81589cc101bfdc625914b1d8ed'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512('Fundamentals', '')) = 'affa539a93acbb675e638aceb0456806564f19bec219c0b6c61d2cd675c37dc3cb7ef4f14831d9638b23d617e6e5c57f586f1804502e4b0b45027a1ae2b254e1'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512('Fundamentals', TenThousandA)) = 'd6e309c24d7fab8da9db0382f50051821df6966fb22121cebfbb2a6623e9849e05f3c9aeba1448353faffbc3b0e52e618efee36d22bf06b9117adc42b33892c2'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512(TenThousandA, TenThousandA)) = 'aacebd574e32713a306598b27583de5e253743dea5d3bd3ed7603fa97e098c9197b76584bf23bb21be242e2dd659626f70a9af68a29e0584890dc3a13480b4a3'); // Test cases from RFC 2202 Assert(MD5DigestToHexA(CalcHMAC_MD5('Jefe', 'what do ya want for nothing?')) = '750c783e6ab0b503eaa86e310a5db738'); S := DupChar(16, $0B); Assert(MD5DigestToHexA(CalcHMAC_MD5(S, 'Hi There')) = '9294727a3638bb1c13f48ef8158bfc9d'); S := DupChar(16, $AA); T := DupChar(50, $DD); Assert(MD5DigestToHexA(CalcHMAC_MD5(S, T)) = '56be34521d144c88dbb8c733f0e8b3f6'); S := DupChar(80, $AA); Assert(MD5DigestToHexA(CalcHMAC_MD5(S, 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data')) = '6f630fad67cda0ee1fb1f562db3aa53e'); Assert(SHA1DigestToHexA(CalcHMAC_SHA1('Jefe', 'what do ya want for nothing?')) = 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79'); S := DupChar(20, $0B); Assert(SHA1DigestToHexA(CalcHMAC_SHA1(S, 'Hi There')) = 'b617318655057264e28bc0b6fb378c8ef146be00'); S := DupChar(80, $AA); Assert(SHA1DigestToHexA(CalcHMAC_SHA1(S, 'Test Using Larger Than Block-Size Key - Hash Key First')) = 'aa4ae5e15272d00e95705637ce8a3b55ed402112'); // Test cases from RFC 4231 Assert(SHA256DigestToHexA(CalcHMAC_SHA256(#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b, 'Hi There')) = 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7'); Assert(SHA256DigestToHexA(CalcHMAC_SHA256('Jefe', 'what do ya want for nothing?')) = '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843'); S := DupChar(131, $aa); Assert(SHA256DigestToHexA(CalcHMAC_SHA256(S, 'This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.')) = '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2'); // see RFC 4231 truncated case --> Assert(SHA256DigestToHex(CalcHMAC_SHA256(#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c#$0c, 'Test With Truncation')) = 'a3b6167473100ee06e0c796c2955552b', 'CalcHMAC_SHA256'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512(#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b#$0b, 'Hi There')) = '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854'); Assert(SHA512DigestToHexA(CalcHMAC_SHA512('Jefe', 'what do ya want for nothing?')) = '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737'); S := DupChar(131, $aa); Assert(SHA512DigestToHexA(CalcHMAC_SHA512(S, 'This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.')) = 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58'); // RipeMD160 Assert(RipeMD160DigestToHexA(CalcRipeMD160('')) = '9c1185a5c5e9fc54612808977ee8f548b2258d31'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('a')) = '0bdc9d2d256b3ee9daae347be6f4dc835a467ffe'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('abc')) = '8eb208f7e05d987a9b044a8e98c6b087f15a0bfc'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('message digest')) = '5d0689ef49d2fae572b881b123a85ffa21595f36'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('abcdefghijklmnopqrstuvwxyz')) = 'f71c27109c692c1b56bbdceb5b9d2865b3708dbc'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq')) = '12a053384a9c0c88e405a06c27dcf49ada62eb2b'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')) = 'b0e20b6e3116640286ed3a87a5713079b21f5189'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('12345678901234567890123456789012345678901234567890123456789012345678901234567890')) = '9b752e45573d4b39f4dbd3323cab82bf63326bfb'); Assert(RipeMD160DigestToHexA(CalcRipeMD160(MillionA)) = '52783243c1697bdbe16d37f97f68f08325dc1528'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('Fundamentals')) = '0b4dfcb4cf845bee8a53bad703e164b50e8199cc'); Assert(RipeMD160DigestToHexA(CalcRipeMD160('12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789')) = 'e5ad452926b1b80e69a8c116748386ed920fd80e'); // 119 bytes Assert(RipeMD160DigestToHexA(CalcRipeMD160('123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890')) = '65aaa2d6fb77e63b02a56ed9eced04fe47da43c1'); // 120 bytes Assert(RipeMD160DigestToHexA(CalcRipeMD160('1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567')) = '5ef3b16743e09d8ac8410d03e72bb2fabb507749'); // 127 bytes Assert(RipeMD160DigestToHexA(CalcRipeMD160('12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678')) = 'e6841f68c8fe1a94cbb8b53d79056d139434b49a'); // 128 bytes end; {$ENDIF} end.
unit uRevendaController; interface uses System.SysUtils, uDMRevenda, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms; type TRevendaController = class private FModel: TDMRevenda; FOperacao: TOperacao; procedure Post; procedure SalvarEmail(AIdRevenda: Integer); function IdAtual: Integer; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer; AMensagem: Boolean=True); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); procedure Salvar(AIdUsuario: Integer); procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, ACodigo: Integer); function CodigoAtual: Integer; procedure FiltrarEmail(AIdRevenda: integer); function MascaraCodigo(ACodigo: string): string; property Model: TDMRevenda read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TRevendaController } uses uFuncoesSIDomper; procedure TRevendaController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TRevendaController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroRev_Codigo.AsInteger; end; constructor TRevendaController.Create; begin inherited Create; FModel := TDMRevenda.Create(nil); end; destructor TRevendaController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TRevendaController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerMethods1Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CRevendaPrograma, dm.IdUsuario, AId); FModel.CDSCadastro.Open; FiltrarEmail(AId); TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerMethods1Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CRevendaPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarRevenda(ACampo, ATexto, AAtivo, dm.IdUsuario, AContem); // Negocio.Filtrar(CRevendaPrograma, Campo, Texto, Ativo, Contem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CRevendaPrograma, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.FiltrarEmail(AIdRevenda: integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try FModel.CDSEmail.Close; Negocio.FiltrarRevendaEmail(AIdRevenda); FModel.CDSEmail.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TRevendaController.IdAtual: Integer; var Negocio: TServerMethods1Client; begin Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := Negocio.RetornaIdAtual('Revenda'); finally FreeAndNil(Negocio); end; end; procedure TRevendaController.Imprimir(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CRevendaPrograma, AIdUsuario); FModel.Rel.Print; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.LocalizarCodigo(ACodigo: integer; AMensagem: Boolean=True); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarCodigoRevenda(ACodigo, dm.IdUsuario, AMensagem); // Negocio.LocalizarCodigo(CRevendaPrograma, Codigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.LocalizarId(AId: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CRevendaPrograma, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TRevendaController.MascaraCodigo(ACodigo: string): string; begin if StrToIntDef(ACodigo, 0) > 0 then Result := FormatFloat('0000', StrToFloat(ACodigo)) else Result := ''; end; procedure TRevendaController.Novo(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CRevendaPrograma, AIdUsuario); FModel.CDSCadastro.Open; FiltrarEmail(0); FModel.CDSCadastro.Append; FModel.CDSCadastroRev_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.Pesquisar(AId, ACodigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(ACodigo); end; procedure TRevendaController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TRevendaController.ProximoCodigo: Integer; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := StrToInt(Negocio.ProximoCodigo(CRevendaPrograma).ToString); dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TRevendaController.ProximoId: Integer; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := StrToInt(Negocio.ProximoId(CRevendaPrograma).ToString); dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.Salvar(AIdUsuario: Integer); var Negocio: TServerMethods1Client; IdRevenda: Integer; begin if FModel.CDSCadastroRev_Codigo.AsInteger <= 0 then raise Exception.Create('Informe o Código!'); if Trim(FModel.CDSCadastroRev_Nome.AsString) = '' then raise Exception.Create('Informe o Nome!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try Post(); FModel.CDSCadastro.ApplyUpdates(0); if FOperacao = opIncluir then IdRevenda := IdAtual() else IdRevenda := FModel.CDSCadastroRev_Id.AsInteger; SalvarEmail(IdRevenda); Negocio.Salvar(CRevendaPrograma, AIdUsuario); FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TRevendaController.SalvarEmail(AIdRevenda: Integer); begin FModel.CDSEmail.DisableControls; try FModel.CDSEmail.First; while not FModel.CDSEmail.Eof do begin FModel.CDSEmail.Edit; FModel.CDSEmailRevEm_Revenda.AsInteger := AIdRevenda; FModel.CDSEmail.Post; FModel.CDSEmail.Next; end; if FModel.CDSEmail.ChangeCount > 0 then FModel.CDSEmail.ApplyUpdates(0); FModel.CDSEmail.First; finally FModel.CDSEmail.EnableControls; end; end; end.
unit aeTransform; interface uses types, aeConst, aeMaths; type TaeTransform = class protected _rotation: TaeMatrix44; // _rotation: TaeQuaternion; _position: TPoint3D; _scale: TPoint3D; public constructor Create; procedure CopyTransformFrom(t: TaeTransform); procedure Reset; procedure RotateRadians(axis: TPoint3D; radians: single); procedure RotateDegrees(axis: TPoint3D; degrees: single); procedure SetRotationMatrix(m: TaeMatrix44); // procedure SetQuaternion(q: TaeQuaternion); function GetRotation: TaeMatrix44; procedure SetScale(s: single); overload; procedure SetScale(X, y, z: single); overload; procedure SetScale(p: TPoint3D); overload; function GetScale: TPoint3D; procedure LookAt(own_pos, target_pos, up_vector: TPoint3D); procedure Orientate(target_pos, up_vector: TPoint3D); function GetPosition: TPoint3D; procedure SetPosition(p: TPoint3D); function Clone: TaeTransform; end; implementation { TaeTransform } function TaeTransform.Clone: TaeTransform; begin result := TaeTransform.Create; result._rotation := self._rotation; result._scale := self._scale; result._position := self._position; end; procedure TaeTransform.CopyTransformFrom(t: TaeTransform); begin if (t <> nil) then begin self.SetRotationMatrix(t.GetRotation); self.SetPosition(t.GetPosition); self.SetScale(t.GetScale); end; end; constructor TaeTransform.Create; begin self.Reset; end; function TaeTransform.GetPosition: TPoint3D; begin result := self._position; end; function TaeTransform.GetRotation: TaeMatrix44; begin result := self._rotation; end; function TaeTransform.GetScale: TPoint3D; begin result := self._scale; end; procedure TaeTransform.LookAt(own_pos, target_pos, up_vector: TPoint3D); var _up, _right, _forward: TPoint3D; begin self.SetPosition(own_pos); self.Orientate(target_pos, up_vector); end; // RIGHT HANDED! // http://gamedev.stackexchange.com/a/8845 procedure TaeTransform.Orientate(target_pos, up_vector: TPoint3D); var _up, _right, _forward: TPoint3D; begin _forward := (self._position - target_pos).Normalize; _right := _forward.CrossProduct(up_vector).Normalize; _up := _right.CrossProduct(_forward).Normalize; self._rotation.loadIdentity; self._rotation.SetRotationVectorX(_right); self._rotation.SetRotationVectorY(_up); self._rotation.SetRotationVectorZ(_forward); end; procedure TaeTransform.Reset; begin self._rotation.loadIdentity; self._scale.Create(1.0, 1.0, 1.0); self._position.Create(0, 0, 0); end; procedure TaeTransform.RotateDegrees(axis: TPoint3D; degrees: single); begin self.RotateRadians(axis, degrees * AE_PI_DIV_180); end; procedure TaeTransform.RotateRadians(axis: TPoint3D; radians: single); begin // _rotation.loadIdentity; _rotation.SetRotation(axis, radians); end; procedure TaeTransform.SetScale(s: single); begin self._scale.Create(s, s, s); end; procedure TaeTransform.SetRotationMatrix(m: TaeMatrix44); begin self._rotation := m; end; procedure TaeTransform.SetScale(p: TPoint3D); begin self._scale := p; end; procedure TaeTransform.SetScale(X, y, z: single); begin self._scale.X := X; self._scale.y := y; self._scale.z := z; end; procedure TaeTransform.SetPosition(p: TPoint3D); begin self._position := p; end; // procedure TaeTransform.SetQuaternion(q: TaeQuaternion); // begin // self._rotation := q; // end; end.
unit ConfigForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, StdCtrls, ActnList, config; type { TFormConfig } TFormConfig = class(TForm) ActionOK: TAction; ActionList: TActionList; ButtonOK: TButton; EditHost: TLabeledEdit; EditPort: TLabeledEdit; EditUserName: TLabeledEdit; EditNickName: TLabeledEdit; EditRealName: TLabeledEdit; EditAltNickName: TLabeledEdit; Label1: TLabel; MemoChannels: TMemo; procedure ActionOKExecute(Sender: TObject); private FConfig: TIRCConfig; procedure CarregarConfiguracao; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; end; implementation {$R *.lfm} { TFormConfig } procedure TFormConfig.ActionOKExecute(Sender: TObject); var Port: integer; begin if not TryStrToInt(EditPort.Text, Port) then raise Exception.Create('Port value is invalid.'); FConfig.Host := EditHost.Text; FConfig.Port := Port; FConfig.Username := EditUserName.Text; FConfig.Nickname := EditNickName.Text; FConfig.AltNickname := EditAltNickName.Text; FConfig.RealName := EditRealName.Text; FConfig.Channels.CommaText := MemoChannels.Lines.CommaText; FConfig.Save; end; procedure TFormConfig.CarregarConfiguracao; begin FConfig.Load; EditHost.Text := FConfig.Host; EditPort.Text := IntToStr(FConfig.Port); EditUserName.Text := FConfig.Username; EditNickName.Text := FConfig.Nickname; EditAltNickName.Text := FConfig.AltNickname; EditRealName.Text := FConfig.RealName; MemoChannels.Lines.AddStrings(FConfig.Channels); end; constructor TFormConfig.Create(TheOwner: TComponent); begin inherited Create(TheOwner); FConfig := TIRCConfig.Create; CarregarConfiguracao; end; destructor TFormConfig.Destroy; begin FConfig.Free; inherited Destroy; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type MathTest = public class (Test) private const Deg: Integer = 30; const Rad: Double = Deg * (Consts.PI / 180); public method AbsDouble; method AbsInt64; method AbsInt; method Acos; method Asin; method Atan; method Atan2; method Ceiling; method Cos; method Cosh; method Exp; method Floor; method IEEERemainder; method Log; method Log10; method MaxDouble; method MaxInt; method MaxInt64; method MinDouble; method MinInt; method MinInt64; method Pow; method Round; method Sign; method Sin; method Sinh; method Sqrt; method Tan; method Tanh; method Truncate; end; implementation method MathTest.AbsDouble; begin Assert.AreEqual(Math.Abs(1.1), 1.1); Assert.AreEqual(Math.Abs(-1.1), 1.1); Assert.AreEqual(Math.Abs(0), 0); Assert.AreEqual(Math.Abs(Consts.MaxDouble), Consts.MaxDouble); Assert.AreEqual(Math.Abs(Consts.MinDouble), Consts.MaxDouble); Assert.IsTrue(Consts.IsInfinity(Math.Abs(Consts.PositiveInfinity))); Assert.IsTrue(Consts.IsInfinity(Math.Abs(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsNaN(Math.Abs(Consts.NaN))); end; method MathTest.AbsInt64; begin Assert.AreEqual(Math.Abs(42), 42); Assert.AreEqual(Math.Abs(-42), 42); Assert.AreEqual(Math.Abs(0), 0); Assert.AreEqual(Math.Abs(Consts.MaxInt64), Consts.MaxInt64); Assert.Throws(->Math.Abs(Consts.MinInt64)); end; method MathTest.AbsInt; begin Assert.AreEqual(Math.Abs(42), 42); Assert.AreEqual(Math.Abs(-42), 42); Assert.AreEqual(Math.Abs(0), 0); Assert.AreEqual(Math.Abs(Consts.MaxInteger), Consts.MaxInteger); Assert.Throws(->Math.Abs(Consts.MinInteger)); end; method MathTest.Acos; begin Assert.AreEqual(Math.Acos(0.75), 0.722734247813416, 0.00000000001); Assert.AreEqual(Math.Acos(1), 0); Assert.AreEqual(Math.Acos(-1), Consts.PI); var Value := Math.Acos(1.1); Assert.IsTrue(Consts.IsNaN(Value)); Value := Math.Acos(-1.1); Assert.IsTrue(Consts.IsNaN(Value)); Assert.IsTrue(Consts.IsNaN(Math.Acos(Consts.NaN))); end; method MathTest.Asin; begin Assert.AreEqual(Math.Asin(0.75), 0.848062078981481, 0.00000000001); Assert.AreEqual(Math.Asin(1), Consts.PI/2); Assert.AreEqual(Math.Asin(-1), -(Consts.PI/2)); var Value := Math.Asin(1.1); Assert.IsTrue(Consts.IsNaN(Value)); Value := Math.Asin(-1.1); Assert.IsTrue(Consts.IsNaN(Value)); Assert.IsTrue(Consts.IsNaN(Math.Asin(Consts.NaN))); end; method MathTest.Atan; begin var Tan30 := Math.Tan(Rad); Assert.AreEqual(Math.Round(Math.Atan(Tan30) * (180 / Consts.PI)), Deg); Assert.IsTrue(Consts.IsNaN(Math.Atan(Consts.NaN))); Assert.AreEqual(Math.Atan(Consts.PositiveInfinity), Consts.PI / 2); Assert.AreEqual(Math.Atan(Consts.NegativeInfinity), -(Consts.PI / 2)); end; method MathTest.Atan2; begin Assert.AreEqual(Math.Atan2(2, 1), 1.10714871779409, 0.00000000001); Assert.IsTrue(Consts.IsNaN(Math.Atan2(1, Consts.NaN))); Assert.IsTrue(Consts.IsNaN(Math.Atan2(Consts.NaN, 1))); Assert.IsTrue(Consts.IsNaN(Math.Atan2(Consts.PositiveInfinity, Consts.NegativeInfinity))); end; method MathTest.Ceiling; begin Assert.AreEqual(Math.Ceiling(7.1), 8); Assert.AreEqual(Math.Ceiling(-7.1), -7); Assert.IsTrue(Consts.IsNaN(Math.Ceiling(Consts.NaN))); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Ceiling(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Ceiling(Consts.PositiveInfinity))); end; method MathTest.Cos; begin Assert.AreEqual(Math.Cos(Rad), Math.Sin(Rad * 2), 0.000000000001); Assert.AreEqual(Math.Cos(Rad), Math.Sqrt(3) / 2, 0.000000000001); Assert.IsTrue(Consts.IsNaN(Math.Cos(Consts.NaN))); Assert.IsTrue(Consts.IsNaN(Math.Cos(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsNaN(Math.Cos(Consts.PositiveInfinity))); end; method MathTest.Cosh; begin var Value := Math.Cosh(Rad); Assert.AreEqual(Value, Math.Cosh(-Rad)); //cosh(x)^2 - sinh(x)^2 = 1 Assert.AreEqual((Value * Value) - (Math.Sinh(Rad) * Math.Sinh(Rad)), 1, 0.1); Assert.IsTrue(Consts.IsNaN(Math.Cosh(Consts.NaN))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Cosh(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Cosh(Consts.PositiveInfinity))); end; method MathTest.Exp; begin Assert.AreEqual(Math.Exp(2), Consts.E * Consts.E, 0.0000000000001); Assert.AreEqual(Math.Exp(0), 1); Assert.IsTrue(Consts.IsNaN(Math.Exp(Consts.NaN))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Exp(Consts.PositiveInfinity))); Assert.AreEqual(Math.Exp(Consts.NegativeInfinity), 0); end; method MathTest.Floor; begin Assert.AreEqual(Math.Floor(7.1), 7); Assert.AreEqual(Math.Floor(-7.1), -8); Assert.IsTrue(Consts.IsNaN(Math.Floor(Consts.NaN))); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Floor(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Floor(Consts.PositiveInfinity))); end; method MathTest.IEEERemainder; begin Assert.AreEqual(Math.IEEERemainder(11, 3), -1); Assert.AreEqual(Math.IEEERemainder(0, 3), 0); var Value := Math.IEEERemainder(11, 0); Assert.IsTrue(Consts.IsNaN(Value)); end; method MathTest.Log; begin Assert.AreEqual(Math.Log(1), 0); Assert.IsTrue(Consts.IsNaN(Math.Log(-1))); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Log(0))); Assert.IsTrue(Consts.IsNaN(Math.Log(Consts.NaN))); Assert.IsTrue(Consts.IsNaN(Math.Log(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Log(Consts.PositiveInfinity))); end; method MathTest.Log10; begin Assert.AreEqual(Math.Log10(1), 0); Assert.AreEqual(Math.Log10(10), 1); Assert.AreEqual(Math.Log10(100), 2); Assert.AreEqual(Math.Log10(4 / 2), Math.Log10(4) - Math.Log10(2)); Assert.IsTrue(Consts.IsNaN(Math.Log10(-1))); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Log10(0))); Assert.IsTrue(Consts.IsNaN(Math.Log10(Consts.NaN))); Assert.IsTrue(Consts.IsNaN(Math.Log10(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Log10(Consts.PositiveInfinity))); end; method MathTest.MaxDouble; begin Assert.AreEqual(Math.Max(1.11, 1.19), 1.19); Assert.AreEqual(Math.Max(0, -1), 0); Assert.AreEqual(Math.Max(-1.11, -1.19), -1.11); Assert.AreEqual(Math.Max(Consts.MaxDouble, Consts.MinDouble), Consts.MaxDouble); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Max(Consts.PositiveInfinity, Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsNaN(Math.Max(Consts.NaN, 1))); Assert.IsTrue(Consts.IsNaN(Math.Max(1, Consts.NaN))); end; method MathTest.MaxInt; begin Assert.AreEqual(Math.Max(5, 4), 5); Assert.AreEqual(Math.Max(-5, -4), -4); Assert.AreEqual(Math.Max(Consts.MaxInteger, Consts.MinInteger), Consts.MaxInteger); end; method MathTest.MaxInt64; begin Assert.AreEqual(Math.Max(Int64(5), Int64(4)), 5); Assert.AreEqual(Math.Max(Int64(-5), Int64(-4)), -4); Assert.AreEqual(Math.Max(Consts.MaxInt64, Consts.MinInt64), Consts.MaxInt64); end; method MathTest.MinDouble; begin Assert.AreEqual(Math.Min(1.1, 1.11), 1.1); Assert.AreEqual(Math.Min(-1.1, -1.11), -1.11); Assert.AreEqual(Math.Min(Consts.MinDouble, Consts.MaxDouble), Consts.MinDouble); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Min(Consts.PositiveInfinity, Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsNaN(Math.Min(Consts.NaN, 1))); Assert.IsTrue(Consts.IsNaN(Math.Min(1, Consts.NaN))); end; method MathTest.MinInt; begin Assert.AreEqual(Math.Min(5,6), 5); Assert.AreEqual(Math.Min(-5, -6), -6); Assert.AreEqual(Math.Min(Consts.MinInteger, Consts.MaxInteger), Consts.MinInteger); end; method MathTest.MinInt64; begin Assert.AreEqual(Math.Min(Int64(5), Int64(6)), 5); Assert.AreEqual(Math.Min(Int64(-5), Int64(-6)), -6); Assert.AreEqual(Math.Min(Consts.MinInt64, Consts.MaxInt64), Consts.MinInt64); end; method MathTest.Pow; begin Assert.AreEqual(Math.Pow(2, 2), 2 * 2); Assert.AreEqual(Math.Pow(2, -2), 0.25); var Value := Math.Pow(0, 55); Assert.AreEqual(Value, 0); Value := Math.Pow(0, -4); Assert.IsTrue(Consts.IsPositiveInfinity(Value)); Assert.AreEqual(Math.Pow(1, 5), 1); Assert.AreEqual(Math.Pow(1, 555), 1); Assert.IsTrue(Consts.IsNaN(Math.Pow(2, Consts.NaN))); //x or y = NaN Assert.IsTrue(Consts.IsNaN(Math.Pow(Consts.NaN, 2))); Assert.AreEqual(Math.Pow(Consts.NegativeInfinity, -2), 0); //x = NegativeInfinity; y < 0. Assert.IsTrue(Consts.IsNegativeInfinity(Math.Pow(Consts.NegativeInfinity, 3))); //-inf if y is odd integer Assert.IsTrue(Consts.IsPositiveInfinity(Math.Pow(Consts.NegativeInfinity, 2))); //+inf if y is not an odd integer Assert.IsTrue(Consts.IsNaN(Math.Pow(-2, 2.2))); //x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity. Assert.IsTrue(Consts.IsNaN(Math.Pow(-1, Consts.PositiveInfinity))); //x = -1; y = NegativeInfinity or PositiveInfinity. Assert.IsTrue(Consts.IsPositiveInfinity(Math.Pow(0.5, Consts.NegativeInfinity))); //-1 < x < 1; y = NegativeInfinity. Assert.AreEqual(Math.Pow(0.5, Consts.PositiveInfinity), 0); //-1 < x < 1; y = PositiveInfinity. Assert.AreEqual(Math.Pow(2, Consts.NegativeInfinity), 0); //x < -1 or x > 1; y = NegativeInfinity. Assert.AreEqual(Math.Pow(Consts.PositiveInfinity, -2), 0); //x = PositiveInfinity; y < 0. Assert.IsTrue(Consts.IsPositiveInfinity(Math.Pow(2, Consts.PositiveInfinity))); //x < -1 or x > 1; y = PositiveInfinity. Assert.IsTrue(Consts.IsPositiveInfinity(Math.Pow(0, -2))); //x = 0; y < 0. Assert.IsTrue(Consts.IsPositiveInfinity(Math.Pow(Consts.PositiveInfinity, 2))); //x = PositiveInfinity; y > 0. end; method MathTest.Round; begin Assert.AreEqual(3, Math.Round(Consts.PI), 3); // Assert.AreEqual(Math.Round(10.0), 10); Assert.AreEqual(Math.Round(10.1), 10); Assert.AreEqual(Math.Round(10.2), 10); Assert.AreEqual(Math.Round(10.3), 10); Assert.AreEqual(Math.Round(10.4), 10); Assert.AreEqual(Math.Round(10.5), 11); Assert.AreEqual(Math.Round(10.6), 11); Assert.AreEqual(Math.Round(10.7), 11); Assert.AreEqual(Math.Round(10.8), 11); Assert.AreEqual(Math.Round(10.9), 11); Assert.AreEqual(Math.Round(11.0), 11); Assert.AreEqual(Math.Round(11.1), 11); Assert.AreEqual(Math.Round(11.2), 11); Assert.AreEqual(Math.Round(11.3), 11); Assert.AreEqual(Math.Round(11.4), 11); Assert.AreEqual(Math.Round(11.5), 12); Assert.AreEqual(Math.Round(11.6), 12); Assert.AreEqual(Math.Round(11.7), 12); Assert.AreEqual(Math.Round(11.8), 12); Assert.AreEqual(Math.Round(11.9), 12); Assert.Throws(->Math.Round(Consts.NaN)); Assert.Throws(->Math.Round(Consts.PositiveInfinity)); Assert.Throws(->Math.Round(Consts.NegativeInfinity)); end; method MathTest.Sign; begin Assert.AreEqual(Math.Sign(-5), -1); Assert.AreEqual(Math.Sign(5), 1); Assert.AreEqual(Math.Sign(0), 0); Assert.Throws(->Math.Sign(Consts.NaN)); end; method MathTest.Sin; begin Assert.AreEqual(Math.Sin(Rad), 0.5, 0.01); Assert.AreEqual(Math.Sin(Rad), Math.Cos(Rad * 2), 0.01); Assert.IsTrue(Consts.IsNaN(Math.Sin(Consts.NaN))); Assert.IsTrue(Consts.IsNaN(Math.Sin(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsNaN(Math.Sin(Consts.PositiveInfinity))); end; method MathTest.Sinh; begin var Value := Math.Sinh(Rad); Assert.AreEqual((Math.Cosh(Rad) * Math.CosH(Rad)) - (Value * Value), 1, 0.1); Assert.AreEqual(Value, Math.Sinh(Consts.PI / 6)); Assert.IsTrue(Consts.IsNaN(Math.Sinh(Consts.NaN))); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Sinh(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Sinh(Consts.PositiveInfinity))); end; method MathTest.Sqrt; begin Assert.AreEqual(Math.Sqrt(4), 2); Assert.AreEqual(Math.Sqrt(0), 0); Assert.IsTrue(Consts.IsNaN(Math.Sqrt(-2))); Assert.IsTrue(Consts.IsNaN(Math.Sqrt(Consts.NaN))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Sqrt(Consts.PositiveInfinity))); end; method MathTest.Tan; begin Assert.AreEqual(Math.Tan(Rad), 1 / Math.Sqrt(3), 0.00000000001); Assert.AreEqual(Math.Tan(45 * (Consts.PI / 180)), 1, 0.1); Assert.IsTrue(Consts.IsNaN(Math.Tan(Consts.NaN))); Assert.IsTrue(Consts.IsNaN(Math.Tan(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsNaN(Math.Tan(Consts.PositiveInfinity))); end; method MathTest.Tanh; begin Assert.AreEqual(Math.Tanh(Rad), Math.Tanh(Consts.PI / 6)); Assert.AreEqual(Math.Tanh(Consts.PositiveInfinity), 1); Assert.AreEqual(Math.Tanh(Consts.NegativeInfinity), -1); Assert.IsTrue(Consts.IsNaN(Math.Tanh(Consts.NaN))); end; method MathTest.Truncate; begin Assert.AreEqual(Math.Truncate(42.464646), 42); Assert.AreEqual(Math.Truncate(-42.464646), -42); Assert.IsTrue(Consts.IsNaN(Math.Truncate(Consts.NaN))); Assert.IsTrue(Consts.IsNegativeInfinity(Math.Truncate(Consts.NegativeInfinity))); Assert.IsTrue(Consts.IsPositiveInfinity(Math.Truncate(Consts.PositiveInfinity))); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpSecP521R1FieldElement; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpMod, ClpSecP521R1Curve, ClpECFieldElement, ClpIECFieldElement, ClpSecP521R1Field, ClpISecP521R1FieldElement, ClpBigInteger, ClpArrayUtils, ClpCryptoLibTypes; resourcestring SInvalidValueForSecP521R1FieldElement = 'Value Invalid for SecP521R1FieldElement "%s"'; type TSecP521R1FieldElement = class(TAbstractFpFieldElement, ISecP521R1FieldElement) strict private function Equals(const other: ISecP521R1FieldElement): Boolean; reintroduce; overload; class function GetQ: TBigInteger; static; inline; strict protected var Fx: TCryptoLibUInt32Array; function GetFieldName: string; override; function GetFieldSize: Int32; override; function GetIsOne: Boolean; override; function GetIsZero: Boolean; override; function GetX: TCryptoLibUInt32Array; inline; property X: TCryptoLibUInt32Array read GetX; public constructor Create(); overload; constructor Create(const X: TBigInteger); overload; constructor Create(const X: TCryptoLibUInt32Array); overload; function TestBitZero: Boolean; override; function ToBigInteger(): TBigInteger; override; function Add(const b: IECFieldElement): IECFieldElement; override; function AddOne(): IECFieldElement; override; function Subtract(const b: IECFieldElement): IECFieldElement; override; function Multiply(const b: IECFieldElement): IECFieldElement; override; function Divide(const b: IECFieldElement): IECFieldElement; override; function Negate(): IECFieldElement; override; function Square(): IECFieldElement; override; function Invert(): IECFieldElement; override; /// <summary> /// return a sqrt root - the routine verifies that the calculation /// returns the right value - if <br />none exists it returns null. /// </summary> function Sqrt(): IECFieldElement; override; function Equals(const other: IECFieldElement): Boolean; overload; override; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI}override; property IsZero: Boolean read GetIsZero; property IsOne: Boolean read GetIsOne; property FieldName: string read GetFieldName; property FieldSize: Int32 read GetFieldSize; class property Q: TBigInteger read GetQ; end; implementation { TSecP521R1FieldElement } class function TSecP521R1FieldElement.GetQ: TBigInteger; begin result := TSecP521R1Curve.SecP521R1Curve_Q; end; function TSecP521R1FieldElement.GetX: TCryptoLibUInt32Array; begin result := Fx; end; constructor TSecP521R1FieldElement.Create; begin Inherited Create(); Fx := TNat.Create(17); end; constructor TSecP521R1FieldElement.Create(const X: TBigInteger); begin if ((not(X.IsInitialized)) or (X.SignValue < 0) or (X.CompareTo(Q) >= 0)) then begin raise EArgumentCryptoLibException.CreateResFmt (@SInvalidValueForSecP521R1FieldElement, ['x']); end; Inherited Create(); Fx := TSecP521R1Field.FromBigInteger(X); end; constructor TSecP521R1FieldElement.Create(const X: TCryptoLibUInt32Array); begin Inherited Create(); Fx := X; end; function TSecP521R1FieldElement.GetFieldName: string; begin result := 'SecP521R1Field'; end; function TSecP521R1FieldElement.GetFieldSize: Int32; begin result := Q.BitLength; end; function TSecP521R1FieldElement.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} begin result := Q.GetHashCode() xor TArrayUtils.GetArrayHashCode(Fx, 0, 17); end; function TSecP521R1FieldElement.GetIsOne: Boolean; begin result := TNat.IsOne(17, Fx); end; function TSecP521R1FieldElement.GetIsZero: Boolean; begin result := TNat.IsZero(17, Fx); end; function TSecP521R1FieldElement.Sqrt: IECFieldElement; var x1, t1, t2: TCryptoLibUInt32Array; begin // Raise this element to the exponent 2^519 x1 := Fx; if ((TNat.IsZero(17, x1)) or (TNat.IsOne(17, x1))) then begin result := Self as IECFieldElement; Exit; end; t1 := TNat.Create(17); t2 := TNat.Create(17); TSecP521R1Field.SquareN(x1, 519, t1); TSecP521R1Field.Square(t1, t2); if TNat.Eq(17, x1, t2) then begin result := TSecP521R1FieldElement.Create(t1); end else begin result := Nil; end; end; function TSecP521R1FieldElement.TestBitZero: Boolean; begin result := TNat.GetBit(Fx, 0) = 1; end; function TSecP521R1FieldElement.ToBigInteger: TBigInteger; begin result := TNat.ToBigInteger(17, Fx); end; function TSecP521R1FieldElement.Add(const b: IECFieldElement): IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TSecP521R1Field.Add(Fx, (b as ISecP521R1FieldElement).X, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.AddOne: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TSecP521R1Field.AddOne(Fx, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Subtract(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TSecP521R1Field.Subtract(Fx, (b as ISecP521R1FieldElement).X, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Multiply(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TSecP521R1Field.Multiply(Fx, (b as ISecP521R1FieldElement).X, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Divide(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TMod.Invert(TSecP521R1Field.P, (b as ISecP521R1FieldElement).X, z); TSecP521R1Field.Multiply(z, Fx, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Negate: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TSecP521R1Field.Negate(Fx, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Square: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TSecP521R1Field.Square(Fx, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Invert: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(17); TMod.Invert(TSecP521R1Field.P, Fx, z); result := TSecP521R1FieldElement.Create(z); end; function TSecP521R1FieldElement.Equals(const other : ISecP521R1FieldElement): Boolean; begin if ((Self as ISecP521R1FieldElement) = other) then begin result := true; Exit; end; if (other = Nil) then begin result := false; Exit; end; result := TNat.Eq(17, Fx, other.X); end; function TSecP521R1FieldElement.Equals(const other: IECFieldElement): Boolean; begin result := Equals(other as ISecP521R1FieldElement); end; end.
unit TestTreeSeacher; {* - поиск в дереве тестов. } interface uses ComCtrls, l3Base, l3Types, l3Interfaces; type TFindStatus = (fsNotStart, fsFound, fsNotFound); TTestTreeSeacher = class private f_FindStr : Tl3WString; {* - строка для поиска. } f_FoundNode : TTreeNode; {* - найденный узел. } f_TreeItems : TTreeNodes; {* - массив узлов дерева. } f_Table : Tl3BMTable; {* - таблица для поиска. } f_FindDown : Boolean; {* - искать вниз. } f_FindStatus : TFindStatus; {* - состояние поиска. } f_FolderMode : Boolean; {* - режим поиска по папкам. } private procedure pm_SetFolderNode(const Value: Boolean); {-} procedure pm_SetFindDown(const Value: Boolean); {-} procedure pm_SetFindStr(const Value: Tl3WString); {-} function GetNextNode(const aNode: TTreeNode): TTreeNode; {* - получение следующего узла. } procedure pm_SetFoundNode(const Value: TTreeNode); {* - результат последнего поиска. } procedure ClearFind; {-} public constructor Create(aTreeItems : TTreeNodes); {-} function Find: Boolean; {* - Процедура поиска. } function GetStartNode: TTreeNode; {* - получения начального узла поиска. } destructor Destroy; override; {-} public property aFindStr: Tl3WString read f_FindStr write pm_SetFindStr; {-} property aFindDown: Boolean read f_FindDown write pm_SetFindDown; {-} property aFoundNode: TTreeNode read f_FoundNode write pm_SetFoundNode; {-} property aFindStatus : TFindStatus read f_FindStatus; {-} property aFolderMode: Boolean read f_FolderMode write pm_SetFolderNode; {-} end; implementation uses SysUtils, FolderSupport, l3String, l3BMSearch; { TTestTreeSeacher } procedure TTestTreeSeacher.ClearFind; begin if f_FindStr.S <> nil then l3StrDispose(f_FindStr.S); end; constructor TTestTreeSeacher.Create(aTreeItems : TTreeNodes); begin f_FindDown := True; f_TreeItems := aTreeItems; f_FindStatus := fsNotStart; f_FolderMode := False; end; destructor TTestTreeSeacher.Destroy; begin ClearFind; inherited; end; function TTestTreeSeacher.Find: Boolean; var l_Node : TTreeNode; function lp_CheckNode: Boolean; var l_Str : string; l_PStr : Tl3PCharLen; l_Pos : Cardinal; begin l_Str := l_Node.Text; l_PStr := l3PCharLen(PChar(@l_Str[1]), Length(l_Str)); l3MakeUpperCase(l_PStr.S, l_PStr.SLen, l_PStr.SCodePage); if l3HasChar('*', f_FindStr) or l3HasChar('?', f_FindStr) then Result := l3MaskCompare(l_Str, l3Str(f_FindStr)) else Result := l3SearchStr(l_PStr, f_Table, f_FindStr, l_Pos); if Result then begin Find := True; f_FoundNode := l_Node; end; // if Result then end; // function lp_CheckNode: Boolean; begin l_Node := GetStartNode; Result := False; f_FindStatus := fsNotFound; while l_Node <> nil do begin if IsNodeFolder(l_Node) then begin if aFolderMode then if lp_CheckNode then Break; end // if IsNodeFolder(aNode) then else if lp_CheckNode then Break; l_Node := GetNextNode(l_Node); end; // while l_Node <> nil do if Result then f_FindStatus := fsFound; end; function TTestTreeSeacher.GetNextNode(const aNode: TTreeNode): TTreeNode; begin if f_FindDown then Result := aNode.GetNext else Result := aNode.GetPrev; end; function TTestTreeSeacher.GetStartNode: TTreeNode; procedure lp_CheckLevel; begin if Result.Level = 0 then Result := Result.GetNext; // Пропускаем начальный узел. end; begin Result := f_FoundNode; if Result = nil then begin if f_FindDown then Result := f_TreeItems.GetFirstNode else Result := f_TreeItems[f_TreeItems.Count - 1]; lp_CheckLevel; end else begin lp_CheckLevel; Result := GetNextNode(Result); // Ищем со следующего... end; end; procedure TTestTreeSeacher.pm_SetFindDown(const Value: Boolean); begin f_FindDown := Value; f_FindStatus := fsNotStart; end; procedure TTestTreeSeacher.pm_SetFindStr(const Value: Tl3WString); begin ClearFind; f_FindStr := l3PCharLen(l3StrNew(Value.S)); l3MakeUpperCase(f_FindStr.S, f_FindStr.SLen, f_FindStr.SCodePage); BMMakeTable(f_FindStr.S, f_Table, f_FindStr.SLen); f_FoundNode := nil; f_FindStatus := fsNotStart; end; procedure TTestTreeSeacher.pm_SetFolderNode(const Value: Boolean); begin f_FolderMode := Value; f_FoundNode := nil; f_FindStatus := fsNotStart; end; procedure TTestTreeSeacher.pm_SetFoundNode(const Value: TTreeNode); begin f_FoundNode := Value; f_FindStatus := fsNotStart; end; end.
unit stListPrintAndExportFontSizeItem; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "stListPrintAndExportFontSizeItem.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: SimpleClass::Class Shared Delphi Sand Box$UC::List::View::List::TstListPrintAndExportFontSizeItem // // Визуализатор для настройки "Использовать для экспорта и печати следующий размер шрифта" // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {$Include w:\common\components\SandBox\VCM\sbDefine.inc} interface uses ddAppConfigTypes ; type TstListPrintAndExportFontSizeItem = class(TddComboBoxConfigItem) {* Визуализатор для настройки "Использовать для экспорта и печати следующий размер шрифта" } public // public methods constructor Create(aMasterItem: TddBaseConfigItem = nil); reintroduce; {* undefined } end;//TstListPrintAndExportFontSizeItem implementation uses ListPrintAndExportFontSizeSettingRes, l3Base, ddAppConfigConst ; // start class TstListPrintAndExportFontSizeItem constructor TstListPrintAndExportFontSizeItem.Create(aMasterItem: TddBaseConfigItem = nil); var l_Value : TddConfigValue; begin l3FillChar(l_Value, SizeOf(l_Value)); l_Value.Kind := dd_vkInteger; l_Value.AsInteger := dv_List_PrintAndExportFontSize; inherited Create(pi_List_PrintAndExportFontSize, str_PrintAndExportFontSize.AsStr, l_Value, TPrintAndExportFontSizeValuesMapImpl.Make, aMasterItem); end;//TstListPrintAndExportFontSizeItem.Create end.
unit ClientModuleUnit1; interface uses System.SysUtils, System.Classes, ClientClassesUnit1, IPPeerClient, Datasnap.DSClientRest; type TClientModule1 = class(TDataModule) DSRestConnection1: TDSRestConnection; private FInstanceOwner: Boolean; FMetodosGeraisClient: TMetodosGeraisClient; FMetodosClienteClient: TMetodosClienteClient; function GetMetodosGeraisClient: TMetodosGeraisClient; function GetMetodosClienteClient: TMetodosClienteClient; { Private declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property InstanceOwner: Boolean read FInstanceOwner write FInstanceOwner; property MetodosGeraisClient: TMetodosGeraisClient read GetMetodosGeraisClient write FMetodosGeraisClient; property MetodosClienteClient: TMetodosClienteClient read GetMetodosClienteClient write FMetodosClienteClient; end; var ClientModule1: TClientModule1; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} constructor TClientModule1.Create(AOwner: TComponent); begin inherited; FInstanceOwner := True; end; destructor TClientModule1.Destroy; begin FMetodosGeraisClient.Free; inherited; end; function TClientModule1.GetMetodosClienteClient: TMetodosClienteClient; begin if FMetodosClienteClient = nil then FMetodosClienteClient:= TMetodosClienteClient.Create(DSRestConnection1, FInstanceOwner); Result := FMetodosClienteClient; end; function TClientModule1.GetMetodosGeraisClient: TMetodosGeraisClient; begin if FMetodosGeraisClient = nil then FMetodosGeraisClient:= TMetodosGeraisClient.Create(DSRestConnection1, FInstanceOwner); Result := FMetodosGeraisClient; end; end.
unit RDOClient_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { RDOClient Library } { Version 1.0 } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_RDOClient: TGUID = '{58C4CB00-873A-11D1-AF26-008029E5CA8C}'; const { Component class GUIDs } Class_WinSockRDOConnection: TGUID = '{58C4CB02-873A-11D1-AF26-008029E5CA8C}'; Class_RDOObjectProxy: TGUID = '{DBA984A1-8C05-11D1-AF26-008029E5CA8C}'; type { Forward declarations: Interfaces } IRDOConnectionInit = interface; IRDOConnectionInitDisp = dispinterface; IRDOObjectProxy = interface; IRDOObjectProxyDisp = dispinterface; { Forward declarations: CoClasses } WinSockRDOConnection = IRDOConnectionInit; RDOObjectProxy = IRDOObjectProxy; { Dispatch interface for WinSockRDOConnection Object } IRDOConnectionInit = interface(IDispatch) ['{58C4CB01-873A-11D1-AF26-008029E5CA8C}'] function Get_Server: WideString; safecall; procedure Set_Server(const Value: WideString); safecall; function Get_Port: Integer; safecall; procedure Set_Port(Value: Integer); safecall; function Connect(TimeOut: Integer): WordBool; safecall; procedure Disconnect; safecall; property Server: WideString read Get_Server write Set_Server; property Port: Integer read Get_Port write Set_Port; end; { DispInterface declaration for Dual Interface IRDOConnectionInit } IRDOConnectionInitDisp = dispinterface ['{58C4CB01-873A-11D1-AF26-008029E5CA8C}'] property Server: WideString dispid 1; property Port: Integer dispid 2; function Connect(TimeOut: Integer): WordBool; dispid 3; procedure Disconnect; dispid 4; end; { Dispatch interface for RDOObjectProxy Object } IRDOObjectProxy = interface(IDispatch) ['{DBA984A0-8C05-11D1-AF26-008029E5CA8C}'] end; { DispInterface declaration for Dual Interface IRDOObjectProxy } IRDOObjectProxyDisp = dispinterface ['{DBA984A0-8C05-11D1-AF26-008029E5CA8C}'] end; { WinSock RDO Connection Object } CoWinSockRDOConnection = class class function Create: IRDOConnectionInit; class function CreateRemote(const MachineName: string): IRDOConnectionInit; end; { RDO ObjectProxy Object } CoRDOObjectProxy = class class function Create: IRDOObjectProxy; class function CreateRemote(const MachineName: string): IRDOObjectProxy; end; implementation uses ComObj; class function CoWinSockRDOConnection.Create: IRDOConnectionInit; begin Result := CreateComObject(Class_WinSockRDOConnection) as IRDOConnectionInit; end; class function CoWinSockRDOConnection.CreateRemote(const MachineName: string): IRDOConnectionInit; begin Result := CreateRemoteComObject(MachineName, Class_WinSockRDOConnection) as IRDOConnectionInit; end; class function CoRDOObjectProxy.Create: IRDOObjectProxy; begin Result := CreateComObject(Class_RDOObjectProxy) as IRDOObjectProxy; end; class function CoRDOObjectProxy.CreateRemote(const MachineName: string): IRDOObjectProxy; begin Result := CreateRemoteComObject(MachineName, Class_RDOObjectProxy) as IRDOObjectProxy; end; end.
unit k2AtomOperation; { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2AtomOperation - } { Начат: 18.10.2005 13:53 } { $Id: k2AtomOperation.pas,v 1.12 2014/04/08 17:13:26 lulin Exp $ } // $Log: k2AtomOperation.pas,v $ // Revision 1.12 2014/04/08 17:13:26 lulin // - переходим от интерфейсов к объектам. // // Revision 1.11 2014/04/03 17:10:38 lulin // - переходим от интерфейсов к объектам. // // Revision 1.10 2014/03/21 12:39:25 lulin // - перетряхиваем работу с тегами. // // Revision 1.9 2014/03/19 18:11:11 lulin // - перетряхиваем работу с тегами. // // Revision 1.8 2014/03/18 10:26:38 lulin // - перетряхиваем работу с тегами. // // Revision 1.7 2014/03/17 16:12:12 lulin // - перетряхиваем работу с тегами. // // Revision 1.6 2012/07/12 18:33:21 lulin // {RequestLink:237994598} // // Revision 1.5 2009/07/23 13:42:34 lulin // - переносим процессор операций туда куда надо. // // Revision 1.4 2009/07/22 17:16:40 lulin // - оптимизируем использование счётчика ссылок и преобразование к интерфейсам при установке атрибутов тегов. // // Revision 1.3 2009/07/06 13:32:12 lulin // - возвращаемся от интерфейсов к объектам. // // Revision 1.2 2008/02/12 12:53:20 lulin // - избавляемся от излишнего метода на базовом классе. // // Revision 1.1 2005/10/18 10:03:09 lulin // - реализация базовой Undo-записи перенесена в правильное место. // {$Include k2Define.inc } interface uses l3Types, l3Variant, k2Op, k2Interfaces ; type Tk2AtomOperation = class(Tk2Op) protected // property fields f_Atom : Tl3Variant; f_Prop : Tk2CustomPropertyPrim; protected // property methods function pm_GetAtom: Tl3Variant; {-} protected // internal methods function SetParam(anAtom : Tl3Variant; const aProp : Tk2CustomPropertyPrim): Tk2AtomOperation; {-} procedure Cleanup; override; {-} public // public methods procedure Clear; virtual; {-} public // public methods property Prop: Tk2CustomPropertyPrim read f_Prop; {-} property Atom: Tl3Variant read pm_GetAtom; {-} end;//Tk2AtomOperation implementation uses SysUtils, k2Base, k2BaseStruct, k2NullTagImpl ; // start class Tk2AtomOperation procedure Tk2AtomOperation.Cleanup; {override;} {-} begin Clear; inherited; end; procedure Tk2AtomOperation.Clear; {override;} {-} begin inherited; FreeAndNil(f_Atom); f_Prop := nil; end; function Tk2AtomOperation.pm_GetAtom: Tl3Variant; {-} begin if (f_Atom = nil) then Result := Tk2NullTagImpl.Instance else Result := f_Atom; end; function Tk2AtomOperation.SetParam(anAtom : Tl3Variant; const aProp : Tk2CustomPropertyPrim): Tk2AtomOperation; {-} begin Clear; f_Prop := aProp; anAtom.SetRef(f_Atom); Result := Self; end; end.
unit fmuEJOperations; interface uses // VCL Windows, StdCtrls, Controls, Classes, SysUtils, Forms, ExtCtrls, Buttons, Graphics, // This untPages, untUtil, untDriver, Spin; type { TfmEKLZ } TfmEJOperations = class(TPage) grpActivization: TGroupBox; btnEKLZActivization: TButton; btnEKLZActivizationResult: TButton; grpArchive: TGroupBox; btnInitEKLZArchive: TButton; btnCloseEKLZArchive: TButton; btnTestEKLZArchiveIntegrity: TButton; grpInterrupt: TGroupBox; btnEKLZInterrupt: TBitBtn; grpResultCode: TGroupBox; btnSetEKLZResultCode: TButton; lblEKLZResultCode: TLabel; seEKLZResultCode: TSpinEdit; procedure btnInitEKLZArchiveClick(Sender: TObject); procedure btnEKLZActivizationClick(Sender: TObject); procedure btnEKLZActivizationResultClick(Sender: TObject); procedure btnCloseEKLZArchiveClick(Sender: TObject); procedure btnTestEKLZArchiveIntegrityClick(Sender: TObject); procedure btnEKLZInterruptClick(Sender: TObject); procedure btnSetEKLZResultCodeClick(Sender: TObject); end; implementation {$R *.DFM} { TfmEKLZ } procedure TfmEJOperations.btnInitEKLZArchiveClick(Sender: TObject); begin EnableButtons(False); try Driver.InitEKLZArchive; finally EnableButtons(True); end; end; procedure TfmEJOperations.btnEKLZActivizationClick(Sender: TObject); var S: string; begin S := 'Вы уверены что хотите активизировать ЭКЛЗ?'; if MessageBox(Handle, PChar(S), PChar(Application.Title), MB_OKCANCEL or MB_DEFBUTTON2 or MB_ICONWARNING)=ID_OK then begin EnableButtons(False); try Driver.EKLZActivization; finally EnableButtons(True); end; end; end; procedure TfmEJOperations.btnEKLZActivizationResultClick(Sender: TObject); begin EnableButtons(False); try Driver.EKLZActivizationResult; finally EnableButtons(True); end; end; procedure TfmEJOperations.btnCloseEKLZArchiveClick(Sender: TObject); var S: string; begin S := 'Вы уверены что хотите закрыть архив ЭКЛЗ?'; if MessageBox(Handle, PChar(S), PChar(Application.Title), MB_OKCANCEL or MB_DEFBUTTON2 or MB_ICONWARNING)=ID_OK then begin EnableButtons(False); try Driver.CloseEKLZArchive; finally EnableButtons(True); end; end; end; procedure TfmEJOperations.btnTestEKLZArchiveIntegrityClick(Sender: TObject); begin EnableButtons(False); try Driver.TestEKLZArchiveIntegrity; finally EnableButtons(True); end; end; procedure TfmEJOperations.btnEKLZInterruptClick(Sender: TObject); begin EnableButtons(False); try Driver.EKLZInterrupt; finally EnableButtons(True); end; end; procedure TfmEJOperations.btnSetEKLZResultCodeClick(Sender: TObject); begin EnableButtons(False); try Driver.EKLZResultCode := seEKLZResultCode.Value; Driver.SetEKLZResultCode; finally EnableButtons(True); end; end; end.
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, EDK.Core, EDK.EmoState, EDK.ErrorCodes, Vcl.ExtCtrls, Vcl.Samples.Spin; type TForm2 = class(TForm) gbEDK: TGroupBox; gbDeviceCount: TGroupBox; btnDeviceCount: TButton; edDeviceCount: TEdit; Timer1: TTimer; sbMouse: TGroupBox; seSensitivity: TSpinEdit; Label1: TLabel; Label2: TLabel; cbAutoCenter: TCheckBox; cbActive: TCheckBox; seMinX: TSpinEdit; Label3: TLabel; seMinY: TSpinEdit; Label4: TLabel; Panel1: TPanel; lblUpperFace: TLabel; lblEye: TLabel; lblLowerFace: TLabel; lblContacts: TLabel; lblStatus: TLabel; procedure FormCreate(Sender: TObject); procedure btnDeviceCountClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure seSensitivityChange(Sender: TObject); private FEmoEvent: EmoEngineEventHandle; FEmoState: EmoStateHandle; FErrCode: Integer; FNumUsers: Integer; FInitialized: Boolean; FUserID: Word; procedure Gyro; procedure Expressiv; procedure ContactQuality; public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} procedure PosOrNeg(var AValue: Integer; const AModifier: Integer); begin if AModifier <> 0 then begin if AValue < 0 then AValue := AValue div AModifier; if AValue > 0 then AValue := AValue div AModifier; end; end; function ExpressiveString(expressive: TExpressivAlgo): string; begin case expressive of EXP_NEUTRAL: Result := 'Neutral'; EXP_BLINK: Result := 'Blink'; EXP_WINK_LEFT: Result := 'Wink Left'; EXP_WINK_RIGHT: Result := 'Wink Right'; EXP_HORIEYE: Result := 'Horizontal Eyes'; EXP_EYEBROW: Result := 'Eye Brows'; EXP_FURROW: Result := 'Furrow'; EXP_SMILE: Result := 'Smile'; EXP_CLENCH: Result := 'Clench'; EXP_LAUGH: Result := 'Laugh'; EXP_SMIRK_LEFT: Result := 'Left Smirk'; EXP_SMIRK_RIGHT: Result := 'Right Smirk'; else Result := IntToStr(Integer(expressive)); end; end; procedure TForm2.ContactQuality; var contacts: array[0..15] of TEEGContactQuality; s: string; I: Integer; begin s := ''; for I := 0 to 15 do begin contacts[i] := ES_GetContactQuality(FEmoState, I); case contacts[i] of EEG_CQ_NO_SIGNAL: s := s + '0'; EEG_CQ_VERY_BAD: s := s + '1'; EEG_CQ_POOR: s := s + '2'; EEG_CQ_FAIR: s := s + '3'; EEG_CQ_GOOD: s := s + '4'; end; end; lblContacts.Caption := s; end; procedure TForm2.Expressiv; var upperFaceType: TExpressivAlgo; upperFacePower: Single; s: string; begin upperFaceType := ES_ExpressivGetUpperFaceAction(FEmoState); upperFacePower := ES_ExpressivGetUpperFaceActionPower(FEmoState); lblUpperFace.Caption := ExpressiveString(upperFaceType); if ES_ExpressivIsBlink(FEmoState) = 1 then lblEye.Caption := 'Blink' else if ES_ExpressivIsLeftWink(FEmoState) = 1 then lblEye.Caption := 'Left Wink' else if ES_ExpressivIsRightWink(FEmoState) = 1 then lblEye.Caption := 'Right Wink' else if ES_ExpressivIsEyesOpen(FEmoState) = 1 then lblEye.Caption := 'Open' else if ES_ExpressivIsLookingUp(FEmoState) = 1 then lblEye.Caption := 'Look Up' else if ES_ExpressivIsLookingLeft(FEmoState) = 1 then lblEye.Caption := 'Look Left' else if ES_ExpressivIsLookingRight(FEmoState) = 1 then lblEye.Caption := 'Look Right' else if ES_ExpressivIsLookingDown(FEmoState) = 1 then lblEye.Caption := 'Look Down'; //lblEye.Caption := 'Undefined'; lblLowerFace.Caption := ExpressiveString(ES_ExpressivGetLowerFaceAction(FEmoState)); end; procedure TForm2.Gyro; var LY: Integer; LMousePos: TPoint; LX: Integer; status: integer; begin status := EE_HeadsetGetGyroDelta(0, @LX, @LY); if status <> EDK_OK then lblStatus.Caption := EDK_ErrorToString(status) else begin lblStatus.Caption := Format('X: %d, Y: %d', [LX, LY]); LMousePos := Mouse.CursorPos; PosOrNeg(LX, seSensitivity.Value); PosOrNeg(LY, seSensitivity.Value); if (LX < -seMinX.Value) or (LX > seMinX.Value) then LMousePos.X := LMousePos.X + LX else if cbAutoCenter.Checked then LMousePos.X := Screen.Width div 2; if (LY < -seMinY.Value) or (LY > seMinY.Value) then LMousePos.Y := LMousePos.Y - LY else if cbAutoCenter.Checked then LMousePos.Y := Screen.Height div 2; if (cbActive.Checked) then Mouse.CursorPos := LMousePos; end; end; procedure TForm2.btnDeviceCountClick(Sender: TObject); begin RaiseEdkError(EE_EngineGetNumUser(@FNumUsers)); edDeviceCount.Text := IntToStr(FNumUsers); if FNumUsers > 0 then Timer1.Enabled := FInitialized; end; procedure TForm2.FormCreate(Sender: TObject); begin FInitialized := EE_EngineConnect(PAnsiChar(AnsiString('Emotiv Systems-5'))) = EDK_OK; if FInitialized then begin RaiseEdkError(EE_EnableDiagnostics(PAnsiChar(AnsiString(ChangeFileExt(Application.ExeName, '.log'))), 1, 0)); //FEmoEvent := EE_EmoEngineEventCreate; FEmoState := EE_EmoStateCreate; //RaiseEdkError(EE_EmoEngineEventGetEmoState(FEmoEvent, FEmoState)); //RaiseEdkError(EE_EmoEngineEventGetUserId(FEmoEvent, @FUserId)); end; end; procedure TForm2.FormDestroy(Sender: TObject); begin if FInitialized then begin EE_EmoStateFree(FEmoState); EE_EmoEngineEventFree(FEmoEvent); EE_EngineDisconnect; end; end; procedure TForm2.FormShow(Sender: TObject); begin gbEDK.Enabled := FInitialized; if FInitialized then btnDeviceCount.Click; end; procedure TForm2.seSensitivityChange(Sender: TObject); begin if seSensitivity.Value < 0 then seSensitivity.Value := 0; end; procedure TForm2.Timer1Timer(Sender: TObject); begin if FNumUsers > 0 then begin Gyro; Expressiv; ContactQuality; end; end; end.
unit IedRangeWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\IedRangeWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "IedRangeWordsPack" MUID: (55E5A40600C8) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , evEditorInterfaces , nevNavigation , nevTools , l3Interfaces , Windows , nevBase ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwClassLike , tfwScriptingInterfaces , TypInfo , IedTableWordsPack , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *55E5A40600C8impl_uses* //#UC END# *55E5A40600C8impl_uses* ; type TkwPopRangeTable = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:Table } private function Table(const aCtx: TtfwContext; const aRange: IedRange): IedTable; {* Реализация слова скрипта pop:Range:Table } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeTable TkwPopRangeHyperlink = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:Hyperlink } private function Hyperlink(const aCtx: TtfwContext; const aRange: IedRange): IevHyperlink; {* Реализация слова скрипта pop:Range:Hyperlink } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeHyperlink TkwPopRangeCollapsed = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:Collapsed } private function Collapsed(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:Collapsed } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeCollapsed TkwPopRangeTextParagraph = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:TextParagraph } private function TextParagraph(const aCtx: TtfwContext; const aRange: IedRange): IedTextParagraph; {* Реализация слова скрипта pop:Range:TextParagraph } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeTextParagraph TkwPopRangeDocument = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:Document } private function Document(const aCtx: TtfwContext; const aRange: IedRange): IevDocument; {* Реализация слова скрипта pop:Range:Document } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeDocument TkwPopRangeDeleteChar = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:DeleteChar } private function DeleteChar(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:DeleteChar } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeDeleteChar TkwPopRangeInsertParaBreak = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:InsertParaBreak } private function InsertParaBreak(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:InsertParaBreak } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeInsertParaBreak TkwPopRangeInsertString = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:InsertString } private function InsertString(const aCtx: TtfwContext; const aRange: IedRange; const aString: Il3CString): Boolean; {* Реализация слова скрипта pop:Range:InsertString } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeInsertString TkwPopRangeDelete = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:Delete } private function Delete(const aCtx: TtfwContext; const aRange: IedRange; aMode: TevClearMode): Boolean; {* Реализация слова скрипта pop:Range:Delete } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeDelete TkwPopRangeContainsOneLeaf = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:ContainsOneLeaf } private function ContainsOneLeaf(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:ContainsOneLeaf } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeContainsOneLeaf TkwPopRangeAsString = {final} class(TtfwClassLike) {* Слово скрипта pop:Range:AsString } private function AsString(const aCtx: TtfwContext; const aRange: IedRange): AnsiString; {* Реализация слова скрипта pop:Range:AsString } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopRangeAsString function TkwPopRangeTable.Table(const aCtx: TtfwContext; const aRange: IedRange): IedTable; {* Реализация слова скрипта pop:Range:Table } //#UC START# *55E5A42D01DD_55E5A42D01DD_48E38399034C_Word_var* //#UC END# *55E5A42D01DD_55E5A42D01DD_48E38399034C_Word_var* begin //#UC START# *55E5A42D01DD_55E5A42D01DD_48E38399034C_Word_impl* Result := aRange.Table; //#UC END# *55E5A42D01DD_55E5A42D01DD_48E38399034C_Word_impl* end;//TkwPopRangeTable.Table class function TkwPopRangeTable.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:Table'; end;//TkwPopRangeTable.GetWordNameForRegister function TkwPopRangeTable.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(IedTable); end;//TkwPopRangeTable.GetResultTypeInfo function TkwPopRangeTable.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeTable.GetAllParamsCount function TkwPopRangeTable.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeTable.ParamsTypes procedure TkwPopRangeTable.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushIntf(Table(aCtx, l_aRange), TypeInfo(IedTable)); end;//TkwPopRangeTable.DoDoIt function TkwPopRangeHyperlink.Hyperlink(const aCtx: TtfwContext; const aRange: IedRange): IevHyperlink; {* Реализация слова скрипта pop:Range:Hyperlink } //#UC START# *55E5A43E00EE_55E5A43E00EE_48E38399034C_Word_var* //#UC END# *55E5A43E00EE_55E5A43E00EE_48E38399034C_Word_var* begin //#UC START# *55E5A43E00EE_55E5A43E00EE_48E38399034C_Word_impl* Result := aRange.Hyperlink; //#UC END# *55E5A43E00EE_55E5A43E00EE_48E38399034C_Word_impl* end;//TkwPopRangeHyperlink.Hyperlink class function TkwPopRangeHyperlink.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:Hyperlink'; end;//TkwPopRangeHyperlink.GetWordNameForRegister function TkwPopRangeHyperlink.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(IevHyperlink); end;//TkwPopRangeHyperlink.GetResultTypeInfo function TkwPopRangeHyperlink.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeHyperlink.GetAllParamsCount function TkwPopRangeHyperlink.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeHyperlink.ParamsTypes procedure TkwPopRangeHyperlink.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushIntf(Hyperlink(aCtx, l_aRange), TypeInfo(IevHyperlink)); end;//TkwPopRangeHyperlink.DoDoIt function TkwPopRangeCollapsed.Collapsed(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:Collapsed } //#UC START# *55E5A44D01A4_55E5A44D01A4_48E38399034C_Word_var* //#UC END# *55E5A44D01A4_55E5A44D01A4_48E38399034C_Word_var* begin //#UC START# *55E5A44D01A4_55E5A44D01A4_48E38399034C_Word_impl* Result := aRange.Collapsed; //#UC END# *55E5A44D01A4_55E5A44D01A4_48E38399034C_Word_impl* end;//TkwPopRangeCollapsed.Collapsed class function TkwPopRangeCollapsed.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:Collapsed'; end;//TkwPopRangeCollapsed.GetWordNameForRegister function TkwPopRangeCollapsed.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopRangeCollapsed.GetResultTypeInfo function TkwPopRangeCollapsed.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeCollapsed.GetAllParamsCount function TkwPopRangeCollapsed.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeCollapsed.ParamsTypes procedure TkwPopRangeCollapsed.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Collapsed(aCtx, l_aRange)); end;//TkwPopRangeCollapsed.DoDoIt function TkwPopRangeTextParagraph.TextParagraph(const aCtx: TtfwContext; const aRange: IedRange): IedTextParagraph; {* Реализация слова скрипта pop:Range:TextParagraph } //#UC START# *55E5A45F032F_55E5A45F032F_48E38399034C_Word_var* //#UC END# *55E5A45F032F_55E5A45F032F_48E38399034C_Word_var* begin //#UC START# *55E5A45F032F_55E5A45F032F_48E38399034C_Word_impl* Result := aRange.TextParagraph; //#UC END# *55E5A45F032F_55E5A45F032F_48E38399034C_Word_impl* end;//TkwPopRangeTextParagraph.TextParagraph class function TkwPopRangeTextParagraph.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:TextParagraph'; end;//TkwPopRangeTextParagraph.GetWordNameForRegister function TkwPopRangeTextParagraph.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(IedTextParagraph); end;//TkwPopRangeTextParagraph.GetResultTypeInfo function TkwPopRangeTextParagraph.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeTextParagraph.GetAllParamsCount function TkwPopRangeTextParagraph.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeTextParagraph.ParamsTypes procedure TkwPopRangeTextParagraph.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushIntf(TextParagraph(aCtx, l_aRange), TypeInfo(IedTextParagraph)); end;//TkwPopRangeTextParagraph.DoDoIt function TkwPopRangeDocument.Document(const aCtx: TtfwContext; const aRange: IedRange): IevDocument; {* Реализация слова скрипта pop:Range:Document } //#UC START# *55E5A4F70193_55E5A4F70193_48E38399034C_Word_var* //#UC END# *55E5A4F70193_55E5A4F70193_48E38399034C_Word_var* begin //#UC START# *55E5A4F70193_55E5A4F70193_48E38399034C_Word_impl* Result := aRange.Document; //#UC END# *55E5A4F70193_55E5A4F70193_48E38399034C_Word_impl* end;//TkwPopRangeDocument.Document class function TkwPopRangeDocument.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:Document'; end;//TkwPopRangeDocument.GetWordNameForRegister function TkwPopRangeDocument.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(IevDocument); end;//TkwPopRangeDocument.GetResultTypeInfo function TkwPopRangeDocument.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeDocument.GetAllParamsCount function TkwPopRangeDocument.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeDocument.ParamsTypes procedure TkwPopRangeDocument.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushIntf(Document(aCtx, l_aRange), TypeInfo(IevDocument)); end;//TkwPopRangeDocument.DoDoIt function TkwPopRangeDeleteChar.DeleteChar(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:DeleteChar } //#UC START# *55E5A51201C5_55E5A51201C5_48E38399034C_Word_var* //#UC END# *55E5A51201C5_55E5A51201C5_48E38399034C_Word_var* begin //#UC START# *55E5A51201C5_55E5A51201C5_48E38399034C_Word_impl* Result := aRange.DeleteChar; //#UC END# *55E5A51201C5_55E5A51201C5_48E38399034C_Word_impl* end;//TkwPopRangeDeleteChar.DeleteChar class function TkwPopRangeDeleteChar.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:DeleteChar'; end;//TkwPopRangeDeleteChar.GetWordNameForRegister function TkwPopRangeDeleteChar.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopRangeDeleteChar.GetResultTypeInfo function TkwPopRangeDeleteChar.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeDeleteChar.GetAllParamsCount function TkwPopRangeDeleteChar.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeDeleteChar.ParamsTypes procedure TkwPopRangeDeleteChar.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(DeleteChar(aCtx, l_aRange)); end;//TkwPopRangeDeleteChar.DoDoIt function TkwPopRangeInsertParaBreak.InsertParaBreak(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:InsertParaBreak } //#UC START# *55E5A525018D_55E5A525018D_48E38399034C_Word_var* //#UC END# *55E5A525018D_55E5A525018D_48E38399034C_Word_var* begin //#UC START# *55E5A525018D_55E5A525018D_48E38399034C_Word_impl* Result := aRange.InsertParaBreak; //#UC END# *55E5A525018D_55E5A525018D_48E38399034C_Word_impl* end;//TkwPopRangeInsertParaBreak.InsertParaBreak class function TkwPopRangeInsertParaBreak.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:InsertParaBreak'; end;//TkwPopRangeInsertParaBreak.GetWordNameForRegister function TkwPopRangeInsertParaBreak.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopRangeInsertParaBreak.GetResultTypeInfo function TkwPopRangeInsertParaBreak.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeInsertParaBreak.GetAllParamsCount function TkwPopRangeInsertParaBreak.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeInsertParaBreak.ParamsTypes procedure TkwPopRangeInsertParaBreak.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(InsertParaBreak(aCtx, l_aRange)); end;//TkwPopRangeInsertParaBreak.DoDoIt function TkwPopRangeInsertString.InsertString(const aCtx: TtfwContext; const aRange: IedRange; const aString: Il3CString): Boolean; {* Реализация слова скрипта pop:Range:InsertString } //#UC START# *55E5A54A0108_55E5A54A0108_48E38399034C_Word_var* //#UC END# *55E5A54A0108_55E5A54A0108_48E38399034C_Word_var* begin //#UC START# *55E5A54A0108_55E5A54A0108_48E38399034C_Word_impl* Result := aRange.InsertString(aString.AsWStr); //#UC END# *55E5A54A0108_55E5A54A0108_48E38399034C_Word_impl* end;//TkwPopRangeInsertString.InsertString class function TkwPopRangeInsertString.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:InsertString'; end;//TkwPopRangeInsertString.GetWordNameForRegister function TkwPopRangeInsertString.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopRangeInsertString.GetResultTypeInfo function TkwPopRangeInsertString.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopRangeInsertString.GetAllParamsCount function TkwPopRangeInsertString.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange), @tfw_tiString]); end;//TkwPopRangeInsertString.ParamsTypes procedure TkwPopRangeInsertString.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; var l_aString: Il3CString; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aString := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aString: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(InsertString(aCtx, l_aRange, l_aString)); end;//TkwPopRangeInsertString.DoDoIt function TkwPopRangeDelete.Delete(const aCtx: TtfwContext; const aRange: IedRange; aMode: TevClearMode): Boolean; {* Реализация слова скрипта pop:Range:Delete } //#UC START# *55E5A5710018_55E5A5710018_48E38399034C_Word_var* //#UC END# *55E5A5710018_55E5A5710018_48E38399034C_Word_var* begin //#UC START# *55E5A5710018_55E5A5710018_48E38399034C_Word_impl* Result := aRange.Delete(aMode); //#UC END# *55E5A5710018_55E5A5710018_48E38399034C_Word_impl* end;//TkwPopRangeDelete.Delete class function TkwPopRangeDelete.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:Delete'; end;//TkwPopRangeDelete.GetWordNameForRegister function TkwPopRangeDelete.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopRangeDelete.GetResultTypeInfo function TkwPopRangeDelete.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopRangeDelete.GetAllParamsCount function TkwPopRangeDelete.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange), TypeInfo(TevClearMode)]); end;//TkwPopRangeDelete.ParamsTypes procedure TkwPopRangeDelete.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; var l_aMode: TevClearMode; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aMode := TevClearMode(aCtx.rEngine.PopInt); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMode: TevClearMode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Delete(aCtx, l_aRange, l_aMode)); end;//TkwPopRangeDelete.DoDoIt function TkwPopRangeContainsOneLeaf.ContainsOneLeaf(const aCtx: TtfwContext; const aRange: IedRange): Boolean; {* Реализация слова скрипта pop:Range:ContainsOneLeaf } //#UC START# *55E5A59300AD_55E5A59300AD_48E38399034C_Word_var* //#UC END# *55E5A59300AD_55E5A59300AD_48E38399034C_Word_var* begin //#UC START# *55E5A59300AD_55E5A59300AD_48E38399034C_Word_impl* Result := aRange.ContainsOneLeaf; //#UC END# *55E5A59300AD_55E5A59300AD_48E38399034C_Word_impl* end;//TkwPopRangeContainsOneLeaf.ContainsOneLeaf class function TkwPopRangeContainsOneLeaf.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:ContainsOneLeaf'; end;//TkwPopRangeContainsOneLeaf.GetWordNameForRegister function TkwPopRangeContainsOneLeaf.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopRangeContainsOneLeaf.GetResultTypeInfo function TkwPopRangeContainsOneLeaf.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeContainsOneLeaf.GetAllParamsCount function TkwPopRangeContainsOneLeaf.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeContainsOneLeaf.ParamsTypes procedure TkwPopRangeContainsOneLeaf.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(ContainsOneLeaf(aCtx, l_aRange)); end;//TkwPopRangeContainsOneLeaf.DoDoIt function TkwPopRangeAsString.AsString(const aCtx: TtfwContext; const aRange: IedRange): AnsiString; {* Реализация слова скрипта pop:Range:AsString } //#UC START# *55E5A5B70005_55E5A5B70005_48E38399034C_Word_var* //#UC END# *55E5A5B70005_55E5A5B70005_48E38399034C_Word_var* begin //#UC START# *55E5A5B70005_55E5A5B70005_48E38399034C_Word_impl* Result := aRange.AsString; //#UC END# *55E5A5B70005_55E5A5B70005_48E38399034C_Word_impl* end;//TkwPopRangeAsString.AsString class function TkwPopRangeAsString.GetWordNameForRegister: AnsiString; begin Result := 'pop:Range:AsString'; end;//TkwPopRangeAsString.GetWordNameForRegister function TkwPopRangeAsString.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopRangeAsString.GetResultTypeInfo function TkwPopRangeAsString.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopRangeAsString.GetAllParamsCount function TkwPopRangeAsString.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(IedRange)]); end;//TkwPopRangeAsString.ParamsTypes procedure TkwPopRangeAsString.DoDoIt(const aCtx: TtfwContext); var l_aRange: IedRange; begin try l_aRange := IedRange(aCtx.rEngine.PopIntf(IedRange)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aRange: IedRange : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(AsString(aCtx, l_aRange)); end;//TkwPopRangeAsString.DoDoIt initialization TkwPopRangeTable.RegisterInEngine; {* Регистрация pop_Range_Table } TkwPopRangeHyperlink.RegisterInEngine; {* Регистрация pop_Range_Hyperlink } TkwPopRangeCollapsed.RegisterInEngine; {* Регистрация pop_Range_Collapsed } TkwPopRangeTextParagraph.RegisterInEngine; {* Регистрация pop_Range_TextParagraph } TkwPopRangeDocument.RegisterInEngine; {* Регистрация pop_Range_Document } TkwPopRangeDeleteChar.RegisterInEngine; {* Регистрация pop_Range_DeleteChar } TkwPopRangeInsertParaBreak.RegisterInEngine; {* Регистрация pop_Range_InsertParaBreak } TkwPopRangeInsertString.RegisterInEngine; {* Регистрация pop_Range_InsertString } TkwPopRangeDelete.RegisterInEngine; {* Регистрация pop_Range_Delete } TkwPopRangeContainsOneLeaf.RegisterInEngine; {* Регистрация pop_Range_ContainsOneLeaf } TkwPopRangeAsString.RegisterInEngine; {* Регистрация pop_Range_AsString } TtfwTypeRegistrator.RegisterType(TypeInfo(IedRange)); {* Регистрация типа IedRange } TtfwTypeRegistrator.RegisterType(TypeInfo(IedTable)); {* Регистрация типа IedTable } TtfwTypeRegistrator.RegisterType(TypeInfo(IevHyperlink)); {* Регистрация типа IevHyperlink } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(TypeInfo(IedTextParagraph)); {* Регистрация типа IedTextParagraph } TtfwTypeRegistrator.RegisterType(TypeInfo(IevDocument)); {* Регистрация типа IevDocument } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа Il3CString } TtfwTypeRegistrator.RegisterType(TypeInfo(TevClearMode)); {* Регистрация типа TevClearMode } {$IfEnd} // NOT Defined(NoScripts) end.
// SAX for Pascal Buffered Helper Classes, Simple API for XML Interfaces in Pascal. // Ver 1.1 July 4, 2003 // http://xml.defined.net/SAX (this will change!) // Based on http://www.saxproject.org/ // No warranty; no copyright -- use this as you will. unit BSAXHelpers; interface uses Classes, SysUtils, SAX, SAXExt, BSAX, BSAXExt; type // Helper Classes TBufferedAttributesImpl = class; TBufferedDefaultHandler = class; TBufferedXMLFilterImpl = class; TBufferedXMLReaderImpl = class; // Extension Helper Classes TBufferedAttributes2Impl = class; TBufferedDefaultHandler2 = class; TBufferedAttributesRecord = record uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; value : PSAXChar; valueLength : Integer; end; // Default implementation of the IBufferedAttributes interface. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This class provides a default implementation of the SAX2 // <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> interface, with the // addition of manipulators so that the list can be modified or // reused.</p> // // <p>There are two typical uses of this class:</p> // // <ol> // <li>to take a persistent snapshot of an Attributes object // in a <a href="../BSAX/IBufferedContentHandler.html#startElement">startElement</a> event; or</li> // <li>to construct or modify an IAttributes object in a SAX2 driver or filter.</li> // </ol> // // <p>This class replaces the now-deprecated SAX1 AttributeListImpl // class; in addition to supporting the updated Attributes // interface rather than the deprecated <a href="../BSAX/IAttributeList.html">IAttributeList</a> // interface, it also includes a much more efficient // implementation using a single array rather than a set of Vectors.</p> // // @since SAX 2.0 TBufferedAttributesImpl = class(TInterfacedObject, IBufferedAttributes) private Flength : Integer; Fdata : array of TBufferedAttributesRecord; // Ensure the internal array's capacity. // // @param n The minimum number of attributes that the array must // be able to hold. procedure ensureCapacity(n : Integer); // Report a bad array index in a manipulator. // // @param index The index to report. // @exception Exception Always. procedure badIndex(index : Integer); protected // Return the number of attributes in the list. // // @return The number of attributes in the list. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> function getLength() : Integer; // Return an attribute's Namespace URI. // // @param index The attribute index (zero-based). // @param uri The Namespace URI, or the empty string if none // is available or if the index is out of range. // @param uriLength The length of the Namespace URI buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getURI">IBufferedAttributes.getURI</a> procedure getURI(index : Integer; out uri: PSAXChar; out uriLength: Integer); // Return an attribute's local name. // // @param index The attribute index (zero-based). // @param localName The local name, or the empty string if Namespace // processing is not being performed or if the // index is out of range. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getLocalName">IBufferedAttributes.getLocalName</a> procedure getLocalName(index : Integer; out localName: PSAXChar; out localNameLength: Integer); // Return an attribute's qualified (prefixed) name. // // @param index The attribute index (zero-based). // @param qName The XML 1.0 qualified name, or the empty string // if none is available or if the index is out of // range. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getQName">IBufferedAttributes.getQName</a> procedure getQName(index : Integer; out qName: PSAXChar; out qNameLength: Integer); // Return an attribute's type by index. // // @param index The attribute index (zero-based). // @param attrType The attribute's type as a string or an empty string if the // index is out of range. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getType.Integer.PSAXChar.Integer">IBufferedAttributes.getType(Integer,PSAXChar,Integer)</a> procedure getType(index : Integer; out attrType: PSAXChar; out attrTypeLength: Integer); overload; // Look up an attribute's type by Namespace-qualified name. // // @param uri The Namespace uri // @param uriLength The length of the uri Buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The XML 1.0 local name // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The Namespace uri // @param attrType The attribute's type as a string or an empty string if the // attribute is not in the list // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getType.PSAXChar.Integer.PSAXChar.Integer.PSAXChar.Integer">IBufferedAttributes.getType(PSAXChar,Integer,PSAXChar,Integer,PSAXChar,Integer)</a> procedure getType(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; out attrType: PSAXChar; out attrTypeLength: Integer); overload; // Look up an attribute's type by qualified (prefixed) name. // // @param qName The XML 1.0 qualified name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attrType The attribute type as a string, or an empty string if the // attribute is not in the list or if qualified names // are not available. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getType.PSAXChar.Integer.PSAXChar.Integer">IBufferedAttributes.getType(PSAXChar,Integer,PSAXChar,Integer)</a> procedure getType(qName: PSAXChar; qNameLength: Integer; out attrType: PSAXChar; out attrTypeLength: Integer); overload; // Return an attribute's value by index. // // @param index The attribute index (zero-based). // @param value The attribute's value as a string, or an empty string if the // index is out of range. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getValue.Integer.PSAXChar.Integer">IBufferedAttributes.getValue(Integer,PSAXChar,Integer)</a> procedure getValue(index : Integer; out value: PSAXChar; out valueLength: Integer); overload; // Look up an attribute's value by Namespace-qualified name. // // @param uri The Namespace URI, or the empty String if the // name has no Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name of the attribute. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value as a string, or an empty string if the // attribute is not in the list. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getValue.PSAXChar.Integer.PSAXChar.Integer">IBufferedAttributes.getValue(PSAXChar,Integer,PSAXChar,Integer)</a> procedure getValue(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; out value: PSAXChar; out valueLength: Integer); overload; // Look up an attribute's value by qualified (prefixed) name. // // @param qName The qualified (prefixed) name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value as a string, or an empty string if the // attribute is not in the list. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getValue.PSAXChar.Integer.PSAXChar.Integer">IBufferedAttributes.getValue(PSAXChar,Integer,PSAXChar,Integer)</a> procedure getValue(qName : PSAXChar; qNameLength : Integer; out value: PSAXChar; out valueLength: Integer); overload; // Look up an attribute's index by Namespace name. // // <p>In many cases, it will be more efficient to look up the name once and // use the index query methods rather than using the name query methods // repeatedly.</p> // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The attribute's local name. // @param loclaNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The index of the attribute, or -1 if it does not // appear in the list. // @see <a href="../BSAX/IBufferedAttributes.html#getIndex.PSAXChar.Integer.PSAXChar.Integer">IBufferedAttributes.getIndex(PSAXChar,Integer,PSAXChar,Integer)</a> function getIndex(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Integer; overload; // Look up an attribute's index by qualified (prefixed) name. // // @param qName The qualified (prefixed) name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The index of the attribute, or -1 if it does not // appear in the list. // @see <a href="../BSAX/IBufferedAttributes.html#getIndex.PSAXChar.Integer">IBufferedAttributes.getIndex(PSAXChar,Integer)</a> function getIndex(qName : PSAXChar; qNameLength : Integer) : Integer; overload; public // Construct a new, empty BufferedAttributesImpl object. constructor Create(); overload; // Copy an existing BufferedAttributes object. // // <p>This constructor is especially useful inside a // <a href="../BSAX/IBufferedContentHandler.html#startElement">startElement</a> event.</p> // // @param atts The existing IBufferedAttributes object. constructor Create(const atts : IBufferedAttributes); overload; // Standard default destructor // // @see <a href="../BSAXHelpers/TBufferedAttributesImpl.html#create">TBufferedAttributesImpl.create</a> destructor Destroy(); override; // Clear the attribute list for reuse. // // <p>Note that little memory is freed by this call: // the current array is kept so it can be // reused.</p> procedure clear(); // Copy an entire Attributes object. // // <p>It may be more efficient to reuse an existing object // rather than constantly allocating new ones.</p> // // @param atts The attributes to copy. procedure setAttributes(const atts : IBufferedAttributes); virtual; // Add an attribute to the end of the list. // // <p>For the sake of speed, this method does no checking // to see if the attribute is already in the list: that is // the responsibility of the application.</p> // // @param uri The Namespace URI, or the empty string if // none is available or Namespace processing is not // being performed. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name, or the empty string if // Namespace processing is not being performed. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified (prefixed) name, or the empty string // if qualified names are not available. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attrType The attribute type as a string. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure addAttribute(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; value : PSAXChar; valueLength : Integer); virtual; // Set an attribute in the list. // // <p>For the sake of speed, this method does no checking // for name conflicts or well-formedness: such checks are the // responsibility of the application.</p> // // @param index The index of the attribute (zero-based). // @param uri The Namespace URI, or the empty string if // none is available or Namespace processing is not // being performed. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name, or the empty string if // Namespace processing is not being performed. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name, or the empty string // if qualified names are not available. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attrType The attribute type as a string. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setAttribute(index : Integer; uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; value : PSAXChar; valueLength : Integer); // Remove an attribute from the list. // // @param index The index of the attribute (zero-based). // @exception Exception when the supplied index does not // point to an attribute in the list. procedure removeAttribute(index : Integer); virtual; // Set the Namespace URI of a specific attribute. // // @param index The index of the attribute (zero-based). // @param uri The attribute's Namespace URI, or the empty // string for none. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setURI(index : Integer; uri : PSAXChar; uriLength : Integer); // Set the local name of a specific attribute. // // @param index The index of the attribute (zero-based). // @param localName The attribute's local name, or the empty // string for none. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setLocalName(index : Integer; localName : PSAXChar; localNameLength : Integer); // Set the qualified name of a specific attribute. // // @param index The index of the attribute (zero-based). // @param qName The attribute's qualified name, or the empty // string for none. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setQName(index : Integer; qName : PSAXChar; qNameLength : Integer); // Set the type of a specific attribute. // // @param index The index of the attribute (zero-based). // @param attrType The attribute's type. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setType(index : Integer; attrType : PSAXChar; attrTypeLength : Integer); // Set the value of a specific attribute. // // @param index The index of the attribute (zero-based). // @param value The attribute's value. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setValue(index : Integer; value : PSAXChar; valueLength : Integer); end; // Default base class for SAX2 Buffered event handlers. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This class is available as a convenience base class for SAX2 // applications: it provides default implementations for all of the // callbacks in the four core SAX2 buffered handler classes:</p> // // <ul> // <li><a href="../SAX/IEntityResolver.html">IEntityResolver</a></li> // <li><a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a></li> // <li><a href="../BSAX/IBufferedContentHandler.html">IBufferedContentHandler</a></li> // <li><a href="../SAX/IErrorHandler.html">IErrorHandler</a></li> // </ul> // // <p>Application writers can extend this class when they need to // implement only part of an interface; parser writers can // instantiate this class to provide default handlers when the // application has not supplied its own.</p> // // <p>This class replaces the deprecated SAX1 // HandlerBase class.</p> // // @since SAX 2.0 // @see <a href="../SAX/IEntityResolver.html">IEntityResolver</a> // @see <a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a> // @see <a href="../BSAX/IBufferedContentHandler.html">IBufferedContentHandler</a> // @see <a href="../SAX/IErrorHandler.html">IErrorHandler</a> TBufferedDefaultHandler = class(TInterfacedObject, IEntityResolver, IBufferedDTDHandler, IBufferedContentHandler, IErrorHandler) protected // Resolve an external entity. // // <p>Always return nil, so that the parser will use the system // identifier provided in the XML document. This method implements // the SAX default behaviour: application writers can override it // in a subclass to do special translations such as catalog lookups // or URI redirection.</p> // // @param publicId The public identifer, or an empty string if none is // available. // @param systemId The system identifier provided in the XML // document. // @return The new input source, or nil to require the // default behaviour. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IEntityResolver.html#resolveEntity">IEntityResolver.resolveEntity</a> function resolveEntity(const publicId, systemId : SAXString) : IInputSource; // Receive notification of a notation declaration. // // <p>By default, do nothing. Application writers may override this // method in a subclass if they wish to keep track of the notations // declared in a document.</p> // // @param name The notation name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The notation's public identifier, or empty if // none was given. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The notation's system identifier, or empty if // none was given. // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#unparsedEntityDecl">TBufferedDefaultHandler.unparsedEntityDecl</a> // @see <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> procedure notationDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); virtual; // Receive notification of an unparsed entity declaration. // // <p>By default, do nothing. Application writers may override this // method in a subclass to keep track of the unparsed entities // declared in a document.</p> // // @exception ESAXException Any SAX exception. // @param name The unparsed entity's name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The entity's public identifier, or empty if none // was given. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The entity's system identifier. // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param notationName The name of the associated notation. // @param notationNameLength The length of the notationNameLength buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#notationDecl">TBufferedDefaultHandler.notationDecl</a> // @see <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> procedure unparsedEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer; notationName : PSAXChar; notationNameLength : Integer); virtual; // Receive a Locator object for document events. // // <p>By default, do nothing. Application writers may override this // method in a subclass if they wish to store the locator for use // with other document events.</p> // // @param locator An object that can return the location of // any SAX document event. // @see <a href="../SAX/ILocator.html">ILocator</a> procedure setDocumentLocator(const locator: ILocator); virtual; // Receive notification of the beginning of the document. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the beginning // of a document (such as allocating the root node of a tree or // creating an output file).</p> // // @exception ESAXException Any SAX exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#endDocument">TBufferedDefaultHandler.endDocument</a> procedure startDocument(); virtual; // Receive notification of the end of the document. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the end // of a document (such as finalising a tree or closing an output // file).</p> // // @exception ESAXException Any SAX exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#startDocument">TBufferedDefaultHandler.startDocument</a> procedure endDocument(); virtual; // Receive notification of the start of a Namespace mapping. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the start of // each Namespace prefix scope (such as storing the prefix mapping).</p> // // @param prefix The Namespace prefix being declared. // An empty string is used for the default element namespace, // which has no prefix. // @param prefixLength The length of the prefix buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The Namespace URI the prefix is mapped to. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The client may throw // an exception during processing. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#endPrefixMapping">TBufferedDefaultHandler.endPrefixMapping</a> // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#startElement">TBufferedDefaultHandler.startElement</a> procedure startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); virtual; // Receive notification of the end of a Namespace mapping. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the end of // each prefix mapping.</p> // // @param prefix The prefix that was being mapping. // Use the empty string when a default mapping scope ends. // @param prefixLength The length of the prefix buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The client may throw // an exception during processing. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#startPrefixMapping">TBufferedDefaultHandler.startPrefixMapping</a> // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#endElement">TBufferedDefaultHandler.endElement</a> procedure endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); virtual; // Receive notification of the start of an element. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the start of // each element (such as allocating a new tree node or writing // output to a file).</p> // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param localNameLength The length of the localName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param qNameLength The length of the qName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param atts The attributes attached to the element. If // there are no attributes, it shall be an empty // IBufferedAttributes object or nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#endElement">TBufferedDefaultHandler.endElement</a> // @see <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> procedure startElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; const atts: IBufferedAttributes); virtual; // Receive notification of the end of an element. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the end of // each element (such as finalising a tree node or writing // output to a file).</p> // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param localNameLength The length of the localName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param qNameLength The length of the qName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure endElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer); virtual; // Receive notification of character data inside an element. // // <p>By default, do nothing. Application writers may override this // method to take specific actions for each chunk of character data // (such as adding the data to a node or buffer, or printing it to // a file).</p> // // @param ch Pointer to the characters from the XML document. // @param chLength The length of the ch buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#ignorableWhitespace">TBufferedDefaultHandler.ignorableWhitespace</a> // @see <a href="../SAX/ILocator.html">ILocator</a> procedure characters(ch : PSAXChar; chLength : Integer); virtual; // Receive notification of ignorable whitespace in element content. // // <p>By default, do nothing. Application writers may override this // method to take specific actions for each chunk of ignorable // whitespace (such as adding data to a node or buffer, or printing // it to a file).</p> // // @param ch Pointer to the characters from the XML document. // @param chLength The length of the ch buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler.html#characters">TBufferedDefaultHandler.characters</a> procedure ignorableWhitespace(ch : PSAXChar; chLength : Integer); virtual; // Receive notification of a processing instruction. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions for each // processing instruction, such as setting status variables or // invoking other methods.</p> // // @param target The processing instruction target. // @param targetLength The length of the target buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param data The processing instruction data, or the empty string // if none was supplied. The data does not include any // whitespace separating it from the target. // @param dataLength The length of the data buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure processingInstruction(target : PSAXChar; targetLength : Integer; data : PSAXChar; dataLength : Integer); virtual; // Receive notification of a skipped entity. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions for each // processing instruction, such as setting status variables or // invoking other methods.</p> // // @param name The name of the skipped entity. If it is a // parameter entity, the name will begin with '%', and if // it is the external DTD subset, it will be the string // "[dtd]". // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure skippedEntity(name : PSAXChar; nameLength : Integer); virtual; // Receive notification of a parser warning. // // <p>The default implementation does nothing. Application writers // may override this method in a subclass to take specific actions // for each warning, such as inserting the message in a log file or // printing it to the console.</p> // // @param e The warning information encoded as an exception. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IErrorHandler.html#warning">IErrorHandler.warning</a> // @see <a href="../SAX/ESAXParseException.html">ESAXParseException</a> procedure warning(const e : ISAXParseError); virtual; // Receive notification of a recoverable parser error. // // <p>The default implementation does nothing. Application writers // may override this method in a subclass to take specific actions // for each error, such as inserting the message in a log file or // printing it to the console.</p> // // @param e The warning information encoded as an exception. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IErrorHandler.html#warning">IErrorHandler.warning</a> // @see <a href="../SAX/ESAXParseException.html">ESAXParseException</a> procedure error(const e : ISAXParseError); virtual; // Report a fatal XML parsing error. // // <p>The default implementation throws a SAXParseException. // Application writers may override this method in a subclass if // they need to take specific actions for each fatal error (such as // collecting all of the errors into a single report): in any case, // the application must stop all regular processing when this // method is invoked, since the document is no longer reliable, and // the parser may no longer report parsing events.</p> // // @param e The error information encoded as an exception. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IErrorHandler.html#fatalError">IErrorHandler.fatalError</a> // @see <a href="../SAX/ESAXParseException.html">ESAXParseException</a> procedure fatalError(const e : ISAXParseError); virtual; end; // Buffered Base class for deriving an XML filter. // // <p>This class is designed to sit between an <a href="../BSAX/IBufferedXMLReader.html">IBufferedXMLReader</a> // and the client application's event handlers. By default, it // does nothing but pass requests up to the reader and events // on to the handlers unmodified, but subclasses can override // specific methods to modify the event stream or the configuration // requests as they pass through.</p> // TBufferedXMLFilterImpl = class(TInterfacedObject, IBufferedXMLFilter, IBufferedXMLReader, IEntityResolver, IBufferedDTDHandler, IBufferedContentHandler, IErrorHandler) private Fparent : IBufferedXMLReader; Flocator : ILocator; FentityResolver : IEntityResolver; FdtdHandler : IBufferedDTDHandler; FcontentHandler : IBufferedContentHandler; FerrorHandler : IErrorHandler; // Set up before a parse. // // <p>Before every parse, check whether the parent is // non-nil, and re-register the filter for all of the // events.</p> procedure setupParse(); protected // Set the parent reader. // // <p>This is the <a href="../BSAX/IBufferedXMLReader.html">IBufferedXMLReader</a> from which // this filter will obtain its events and to which it will pass its // configuration requests. The parent may itself be another filter.</p> // // <p>If there is no parent reader set, any attempt to parse // or to set or get a feature or property will fail.</p> // @param parent The parent reader. // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#getParent">TBufferedXMLFilterImpl.getParent</a> procedure setParent(const parent : IBufferedXMLReader); virtual; // Get the parent reader. // // <p>This method allows the application to query the parent // reader (which may be another filter). It is generally a // bad idea to perform any operations on the parent reader // directly: they should all pass through this filter.</p> // // @return The parent filter, or nil if none has been set. // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#setParent">TBufferedXMLFilterImpl.setParent</a> function getParent() : IBufferedXMLReader; virtual; // Look up the value of a feature. // // <p>This will always fail if the parent is nil.</p> // // @param name The feature name, which is a fully-qualified URI. // @return The current value of the feature (true or false). // @exception ESAXNotRecognizedException If the feature // value can't be assigned or retrieved. // @exception ESAXNotSupportedException When the // XMLReader recognizes the feature name but // cannot determine its value at this time. function getFeature(const name : SAXString) : Boolean; virtual; // Set the value of a feature. // // <p>This will always fail if the parent is nil.</p> // // @param name The feature name, which is a fully-qualified URI. // @param state The requested value of the feature (true or false). // @exception ESAXNotRecognizedException If the feature // value can't be assigned or retrieved. // @exception ESAXNotSupportedException When the // XMLReader recognizes the feature name but // cannot set the requested value. procedure setFeature(const name : SAXString; value : Boolean); virtual; // Look up the interface value of a property. // // @param name The property name, which is a fully-qualified URI. // @returns An Interface that allows the getting and setting of the property // @exception ESAXNotRecognizedException If the property // interface cannot be retrieved. // @exception ESAXNotSupportedException When the // XMLReader recognizes the property name but // cannot determine its interface value at this time. function getProperty(const name : SAXString) : IProperty; virtual; // Set the entity resolver. // // @param resolver The entity resolver. procedure setEntityResolver(const resolver : IEntityResolver); virtual; // Get the current entity resolver. // // @return The current entity resolver, or nil if none // has been registered. function getEntityResolver() : IEntityResolver; virtual; // Set the DTD event handler. // // @param handler The DTD handler. procedure setDTDHandler(const handler : IBufferedDTDHandler); virtual; // Get the current DTD event handler. // // @return The current DTD handler, or null if none // has been registered. function getDTDHandler() : IBufferedDTDHandler; virtual; // Set the content event handler. // // @param handler The content handler. procedure setContentHandler(const handler : IBufferedContentHandler); virtual; // Get the content event handler. // // @return The current content handler, or nil if none // has been registered. function getContentHandler() : IBufferedContentHandler; virtual; // Set the error event handler. // // @param handler The error handler. procedure setErrorHandler(const handler : IErrorHandler); virtual; // Get the current error event handler. // // @return The current error handler, or nil if none // has been registered. function getErrorHandler() : IErrorHandler; virtual; // Parse a document. // // @param source The input source for the top-level of the // XML document. // @exception ESAXException Any SAX exception. // @exception Exception An IO exception from the parser, // possibly from a byte stream // supplied by the application. procedure parse(const input : IInputSource); overload; virtual; // Parse a document. // // @param systemId The system identifier (URI). // @exception ESAXException Any SAX exception. // @exception Exception An IO exception from the parser, // possibly from a byte stream // supplied by the application. procedure parse(const systemId : SAXString); overload; virtual; // Filter an external entity resolution. // // @param publicId The public identifier of the external entity // being referenced, or empty if none was supplied. // @param systemId The system identifier of the external entity // being referenced. // @return An IInputSource interface describing the new input source, // or null to request that the parser open a regular // URI connection to the system identifier. // @exception ESAXException Any SAX exception. // @exception Exception A pascal-specific IO exception, // possibly the result of creating a new Stream // for the InputSource. function resolveEntity(const publicId, systemId : SAXString) : IInputSource; virtual; // Filter a notation declaration event. // // @param name The notation name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The notation's public identifier, or empty if // none was given. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The notation's system identifier, or empty if // none was given. // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure notationDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); virtual; // Filter an unparsed entity declaration event. // // @exception ESAXException Any SAX exception. // @param name The unparsed entity's name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The entity's public identifier, or empty if none // was given. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The entity's system identifier. // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param notationName The name of the associated notation. // @param notationNameLength The length of the notationNameLength buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure unparsedEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer; notationName : PSAXChar; notationNameLength : Integer); virtual; // Filter a new document locator event. // // @param locator The document locator. procedure setDocumentLocator(const locator: ILocator); virtual; // Filter a start document event. // // @exception ESAXException The client may throw // an exception during processing. procedure startDocument(); virtual; // Filter an end document event. // // @exception ESAXException The client may throw // an exception during processing. procedure endDocument(); virtual; // Filter a start Namespace prefix mapping event. // // @param prefix The Namespace prefix being declared. // An empty string is used for the default element namespace, // which has no prefix. // @param prefixLength The length of the prefix buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The Namespace URI the prefix is mapped to. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The client may throw // an exception during processing. procedure startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); virtual; // Filter an end Namespace prefix mapping event. // // @param prefix The prefix that was being mapping. // Use the empty string when a default mapping scope ends. // @param prefixLength The length of the prefix buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The client may throw // an exception during processing. procedure endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); virtual; // Filter a start element event. // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param localNameLength The length of the localName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param qNameLength The length of the qName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param atts The attributes attached to the element. If // there are no attributes, it shall be an empty // IBufferedAttributes object or nil. // @exception ESAXException Any SAX exception. procedure startElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; const atts: IBufferedAttributes); virtual; // Filter an end element event. // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param localNameLength The length of the localName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param qNameLength The length of the qName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure endElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer); virtual; // Filter a character data event. // // @param ch A pointer to a buffer of characters. // @param length The number of characters to use from the buffer. // @exception ESAXException The client may throw // an exception during processing. procedure characters(ch : PSAXChar; length : Integer); virtual; // Filter an ignorable whitespace event. // // @param ch A pointer to a buffer of characters. // @param length The number of characters to use from the array. // @exception ESAXException The client may throw // an exception during processing. procedure ignorableWhitespace(ch : PSAXChar; length : Integer); virtual; // Filter a processing instruction event. // // @param target The processing instruction target. // @param targetLength The length of the target buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param data The processing instruction data, or the empty string // if none was supplied. The data does not include any // whitespace separating it from the target. // @param dataLength The length of the data buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure processingInstruction(target : PSAXChar; targetLength : Integer; data : PSAXChar; dataLength : Integer); virtual; // Filter a skipped entity event. // // @param name The name of the skipped entity. If it is a // parameter entity, the name will begin with '%', and if // it is the external DTD subset, it will be the string // "[dtd]". // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure skippedEntity(name : PSAXChar; nameLength : Integer); virtual; // Filter a warning event. // // @param e The warning as an exception. // @exception ESAXException The client may throw // an exception during processing. procedure warning(const e : ISAXParseError); virtual; // Filter an error event. // // @param e The error as an exception. // @exception ESAXException The client may throw // an exception during processing. procedure error(const e : ISAXParseError); virtual; // Filter a fatal error event. // // @param e The error as an exception. // @exception ESAXException The client may throw // an exception during processing. procedure fatalError(const e : ISAXParseError); virtual; public // Construct an empty XML filter, with no parent. // // <p>This filter will have no parent: you must assign a parent // before you start a parse or do any configuration with // setFeature or getProperty.</p> // // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#setParent">TBufferedXMLFilterImpl.setParent</a> // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#setFeature">TBufferedXMLFilterImpl.setFeature</a> // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#getProperty">TBufferedXMLFilterImpl.getProperty</a> constructor create(); overload; // Construct an XML filter with the specified parent. // // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#setParent">TBufferedXMLFilterImpl.setParent</a> // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html#getParent">TBufferedXMLFilterImpl.getParent</a> constructor create(const parent : IBufferedXMLReader); overload; end; // Buffered Base class for deriving an XML Reader. TBufferedXMLReaderImpl = class(TInterfacedObject, IBufferedXMLReader, ILocator) private FcontentHandler: IBufferedContentHandler; FdtdHandler: IBufferedDTDHandler; FentityResolver: IEntityResolver; FerrorHandler: IErrorHandler; FlineNumber: Integer; FcolumnNumber: Integer; FpublicId: SAXString; FsystemId: SAXString; Fnamespaces: Boolean; Fprefixes: Boolean; Fparsing: Boolean; // Check if we are already parsing // // <p>Throw an exception if we are parsing. Use this method to // detect illegal feature or property changes.</p> // // @param propType A string value containing the type of property that // cannot be changed while parsing. // @param propTypeLength The length of the propTypeBuffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param name A string value containing the name of the property that // cannot be changed while parsing. // @param nameLength The length of the nameBuffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure checkNotParsing(propType, name : SAXString); protected procedure setColumnNumber(value: Integer); virtual; procedure setLineNumber(value: Integer); virtual; procedure setPublicId(value: PSAXChar); virtual; procedure setSystemId(value: PSAXChar); virtual; procedure parseInput(const input: IInputSource); virtual; abstract; property useNamespaces: Boolean read Fnamespaces write Fnamespaces; property usePrefixes: Boolean read Fprefixes write Fprefixes; // Look up the value of a feature. // // <p>The feature name is any fully-qualified URI. It is // possible for an XMLReader to recognize a feature name but // to be unable to return its value; this is especially true // in the case of an adapter for a SAX1 Parser, which has // no way of knowing whether the underlying parser is // performing validation or expanding external entities.</p> // // <p>All XMLReaders are required to recognize the // http://xml.org/sax/features/namespaces and the // http://xml.org/sax/features/namespace-prefixes feature names.</p> // // <p>Some feature values may be available only in specific // contexts, such as before, during, or after a parse.</p> // // <p>Typical usage is something like this:</p> // // <pre> // var // r : IXMLReader; // begin // r:= TMySAXDriver.Create() as IXMLReader; // // // try to activate validation // try // r.setFeature('http://xml.org/sax/features/validation', true); // except // on e : ESAXException do // begin // Showmessage('Cannot activate validation.'); // end; // end; // // // register event handlers // r.setContentHandler(TMyContentHandler.Create() as IContentHandler); // r.setErrorHandler(TMyErrorHandler.Create() as IErrorHandler); // // // parse the first document // try // r.parse('file://c:/mydoc.xml'); // except // on e : ESAXException do // begin // Showmessage('XML exception reading document.'); // end; // on e : Exception do // begin // Showmessage('Exception reading document.'); // end; // end; // </pre> // // <p>Implementors are free (and encouraged) to invent their own features, // using names built on their own URIs.</p> // // @param name The feature name, which is a fully-qualified URI. // @return The current state of the feature (true or false). // @exception ESAXNotRecognizedException When the // XMLReader does not recognize the feature name. // @exception ESAXNotSupportedException When the // XMLReader recognizes the feature name but // cannot determine its value at this time. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setFeature">TBufferedXMLReaderImpl.setFeature</a> function getFeature(const name : SAXString) : Boolean; virtual; // Set the state of a feature. // // <p>The feature name is any fully-qualified URI. It is // possible for an XMLReader to recognize a feature name but // to be unable to set its value; this is especially true // in the case of an adapter for a SAX1 <a href="../SAX/IParser.html">Parser</a>, // which has no way of affecting whether the underlying parser is // validating, for example.</p> // // <p>All XMLReaders are required to support setting // http://xml.org/sax/features/namespaces to true and // http://xml.org/sax/features/namespace-prefixes to false.</p> // // <p>Some feature values may be immutable or mutable only // in specific contexts, such as before, during, or after // a parse.</p> // // @param name The feature name, which is a fully-qualified URI. // @param state The requested state of the feature (true or false). // @exception ESAXNotRecognizedException When the // XMLReader does not recognize the feature name. // @exception ESAXNotSupportedException When the // XMLReader recognizes the feature name but // cannot set the requested value. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getFeature">TBufferedXMLReaderImpl.getFeature</a> procedure setFeature(const name : SAXString; value : Boolean); virtual; // Look up the value of a property. // // <p>The property name is any fully-qualified URI. It is // possible for an XMLReader to recognize a property name but // temporarily be unable to return its value // Some property values may be available only in specific // contexts, such as before, during, or after a parse.</p> // // <p>XMLReaders are not required to recognize any specific // property names, though an initial core set is documented for // SAX2.</p> // // <p>Implementors are free (and encouraged) to invent their own properties, // using names built on their own URIs.</p> // // <p> Within SAX for Pascal property setting is handled through // the interface that is returned by the call to getProperty. This // eliminates the need for multiple lookups in tight loop situations // as a user can maintain a reference to the interface.</p> // // @param name The property name, which is a fully-qualified URI. // @returns An Interface that allows the getting and setting of the property // @exception ESAXNotRecognizedException If the property // interface cannot be retrieved. // @exception ESAXNotSupportedException When the // XMLReader recognizes the property name but // cannot determine its interface value at this time. function getProperty(const name : SAXString) : IProperty; virtual; // Allow an application to register an entity resolver. // // <p>If the application does not register an entity resolver, // the XMLReader will perform its own default resolution.</p> // // <p>Applications may register a new or different resolver in the // middle of a parse, and the SAX parser must begin using the new // resolver immediately.</p> // // @param resolver The entity resolver. // @exception Exception If the resolver argument is nil. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getEntityResolver">TBufferedXMLReaderImpl.getEntityResolver</a> procedure setEntityResolver(const resolver : IEntityResolver); virtual; // Return the current entity resolver. // // @return The current entity resolver, or nil if none // has been registered. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setEntityResolver">TBufferedXMLReaderImpl.setEntityResolver</a> function getEntityResolver() : IEntityResolver; virtual; // Allow an application to register a DTD event handler. // // <p>If the application does not register a DTD handler, all DTD // events reported by the SAX parser will be silently ignored.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The DTD handler. // @exception Exception If the handler argument is nil. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getDTDHandler">TBufferedXMLReaderImpl.getDTDHandler</a> procedure setDTDHandler(const handler : IBufferedDTDHandler); virtual; // Return the current DTD handler. // // @return The current DTD handler, or nil if none // has been registered. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setDTDHandler">TBufferedXMLReaderImpl.setDTDHandler</a> function getDTDHandler() : IBufferedDTDHandler; virtual; // Allow an application to register a content event handler. // // <p>If the application does not register a content handler, all // content events reported by the SAX parser will be silently // ignored.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The content handler. // @exception Exception If the handler argument is nil. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getContentHandler">TBufferedXMLReaderImpl.getContentHandler</a> procedure setContentHandler(const handler : IBufferedContentHandler); virtual; // Return the current content handler. // // @return The current content handler, or nil if none // has been registered. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setContentHandler">TBufferedXMLReaderImpl.setContentHandler</a> function getContentHandler() : IBufferedContentHandler; virtual; // Allow an application to register an error event handler. // // <p>If the application does not register an error handler, all // error events reported by the SAX parser will be silently // ignored; however, normal processing may not continue. It is // highly recommended that all SAX applications implement an // error handler to avoid unexpected bugs.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The error handler. // @exception Exception If the handler argument is nil. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getErrorHandler">TBufferedXMLReaderImpl.getErrorHandler</a> procedure setErrorHandler(const handler : IErrorHandler); virtual; // Return the current error handler. // // @return The current error handler, or nil if none // has been registered. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setErrorHandler">TBufferedXMLReaderImpl.setErrorHandler</a> function getErrorHandler() : IErrorHandler; virtual; // Parse an XML document. // // <p>The application can use this method to instruct the XML // reader to begin parsing an XML document from any valid input // source (a character stream, a byte stream, or a URI).</p> // // <p>Applications may not invoke this method while a parse is in // progress (they should create a new XMLReader instead for each // nested XML document). Once a parse is complete, an // application may reuse the same XMLReader object, possibly with a // different input source.</p> // // <p>During the parse, the XMLReader will provide information // about the XML document through the registered event // handlers.</p> // // <p>This method is synchronous: it will not return until parsing // has ended. If a client application wants to terminate // parsing early, it should throw an exception.</p> // // @param source The input source for the top-level of the // XML document. // @exception ESAXException Any SAX exception. // @exception Exception An IO exception from the parser, // possibly from a byte stream or character stream // supplied by the application. // @see <a href="../SAX/TInputSource.html">TInputSource</a> // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#parse.SAXString">TBufferedXMLReaderImpl.parse(SAXString)</a> // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setEntityResolver">TBufferedXMLReaderImpl.setEntityResolver</a> // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setDTDHandler">TBufferedXMLReaderImpl.setDTDHandler</a> // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setContentHandler">TBufferedXMLReaderImpl.setContentHandler</a> // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#setErrorHandler">TBufferedXMLReaderImpl.setErrorHandler</a> procedure parse(const input : IInputSource); overload; virtual; // Parse an XML document from a system identifier (URI). // // <p>This method is a shortcut for the common case of reading a // document from a system identifier. It is the exact // equivalent of the following:</p> // // <pre> // input:= TInputSource.Create(systemId); // try // parse(input); // finally // input.Free; // end; // </pre> // // <p>If the system identifier is a URL, it must be fully resolved // by the application before it is passed to the parser.</p> // // @param systemId The system identifier (URI). // @exception ESAXException Any SAX exception. // @exception Exception An IO exception from the parser, // possibly from a byte stream or character stream // supplied by the application. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#parse.TInputSource">TBufferedXMLReaderImpl.parse(TInputSource)</a> procedure parse(const systemId : SAXString); overload; virtual; // Return the public identifier for the current document event. // // <p>The return value is the public identifier of the document // entity or of the external parsed entity in which the markup // triggering the event appears.</p> // // @return A string containing the public identifier, or // empty if none is available. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getSystemId">TBufferedXMLReaderImpl.getSystemId</a> function getPublicId() : PSAXChar; virtual; // Return the system identifier for the current document event. // // <p>The return value is the system identifier of the document // entity or of the external parsed entity in which the markup // triggering the event appears.</p> // // <p>If the system identifier is a URL, the parser must resolve it // fully before passing it to the application.</p> // // @return A string containing the system identifier, or empty // if none is available. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getPublicId">TBufferedXMLReaderImpl.getPublicId</a> function getSystemId() : PSAXChar; virtual; // Return the line number where the current document event ends. // // <p><strong>Warning:</strong> The return value from the method // is intended only as an approximation for the sake of error // reporting; it is not intended to provide sufficient information // to edit the character content of the original XML document.</p> // // <p>The return value is an approximation of the line number // in the document entity or external parsed entity where the // markup triggering the event appears.</p> // // <p>If possible, the SAX driver should provide the line position // of the first character after the text associated with the document // event. The first line in the document is line 1.</p> // // @return The line number, or -1 if none is available. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getColumnNumber">TBufferedXMLReaderImpl.getColumnNumber</a> function getLineNumber() : Integer; virtual; // Return the column number where the current document event ends. // // <p><strong>Warning:</strong> The return value from the method // is intended only as an approximation for the sake of error // reporting; it is not intended to provide sufficient information // to edit the character content of the original XML document.</p> // // <p>The return value is an approximation of the column number // in the document entity or external parsed entity where the // markup triggering the event appears.</p> // // <p>If possible, the SAX driver should provide the line position // of the first character after the text associated with the document // event.</p> // // <p>If possible, the SAX driver should provide the line position // of the first character after the text associated with the document // event. The first column in each line is column 1.</p> // // @return The column number, or -1 if none is available. // @see <a href="../BSAXHelpers/TBufferedXMLReaderImpl.html#getLineNumber">TBufferedXMLReaderImpl.getLineNumber</a> function getColumnNumber() : Integer; virtual; public // Construct an empty XML Reader, and initializes its values. constructor Create; // Default destructor for an XML Reader, freeing any items created during // intialization destructor Destroy; override; end; // SAX2 extension helper for additional Attributes information, // implementing the <a href="../BSAXExt/IBufferedAttributes2.html">IBufferedAttributes2</a> interface. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This is not part of core-only SAX2 distributions.</p> // // <p>The <em>specified</em> flag for each attribute will always // be true, unless it has been set to false in the copy constructor // or using <a href="../BSAXHelpers/TBufferedAttributes2Impl.html#setSpecified">setSpecified</a>. // Similarly, the <em>declared</em> flag for each attribute will // always be false, except for defaulted attributes (<em>specified</em> // is false), non-CDATA attributes, or when it is set to true using // <a href="../BSAXHelpers/TBufferedAttributes2Impl.html#setDeclared">setDeclared</a>. // If you change an attribute's type by hand, you may need to modify // its <em>declared</em> flag to match. // </p> // // @since SAX 2.0 (extensions 1.1 alpha) TBufferedAttributes2Impl = class(TBufferedAttributesImpl, IBufferedAttributes2) private Fdeclared : array of Boolean; Fspecified : array of Boolean; protected // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // @param index The attribute index (zero-based). // @return true if the attribute was declared in the DTD, // false otherwise. // @exception Exception When the // supplied index does not identify an attribute. // function isDeclared(index : Integer) : Boolean; overload; // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // @param qName The XML 1.0 qualified name. // @param qNameLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return true if the attribute was declared in the DTD, // false otherwise. // @exception ESAXIllegalArgumentException When the // supplied name does not identify an attribute. function isDeclared(qName : PSAXChar; qNameLength : Integer) : Boolean; overload; // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // <p>Remember that since DTDs do not "understand" namespaces, the // namespace URI associated with an attribute may not have come from // the DTD. The declaration will have applied to the attribute's // <em>qName</em>.</p> // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The attribute's local name. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return true if the attribute was declared in the DTD, // false otherwise. // @exception ESAXIllegalArgumentException When the // supplied names do not identify an attribute. function isDeclared(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Boolean; overload; // Returns the current value of an attribute's "specified" flag. // // @param index The attribute index (zero-based). // @return true if the value was found in the XML text, // false if the value was provided by DTD defaulting. // @exception ESAXIllegalArgumentException When the // supplied index does not identify an attribute. function isSpecified(index : Integer) : Boolean; overload; // Returns the current value of an attribute's "specified" flag. // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The attribute's local name. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return true if the value was found in the XML text, // false if the value was provided by DTD defaulting. // @exception ESAXIllegalArgumentException When the // supplied names do not identify an attribute. function isSpecified(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Boolean; overload; // Returns the current value of an attribute's "specified" flag. // // @param qName The XML 1.0 qualified name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return true if the value was found in the XML text, // false if the value was provided by DTD defaulting. // @exception ESAXIllegalArgumentException When the // supplied name does not identify an attribute. function isSpecified(qName : PSAXChar; qNameLength : Integer) : Boolean; overload; public // Copy an entire Attributes object. The "specified" flags are // assigned as true, unless the object is an Attributes2 object // in which case those values are copied. // // @see <a href="../BSAXHelpers/TBufferedAttributesImpl.html#setAttributes">TBufferedAttributesImpl.setAttributes</a> procedure setAttributes(const atts : IBufferedAttributes); override; // Add an attribute to the end of the list, setting its // "specified" flag to true. To set that flag's value // to false, use <a href="../BSAXHelpers/TBufferedAttributes2Impl.html#setSpecified">setSpecified</a>. // // <p>Unless the attribute <em>type</em> is CDATA, this attribute // is marked as being declared in the DTD. To set that flag's value // to true for CDATA attributes, use <a href="../BSAXHelpers/TBufferedAttributes2Impl.html#setDeclared">setDeclared</a>.</p> // // @see <a href="../BSAXHelpers/TBufferedAttributesImpl.html#addAttribute">TBufferedAttributesImpl.addAttribute</a> // @param uri The Namespace URI, or the empty string if // none is available or Namespace processing is not // being performed. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name, or the empty string if // Namespace processing is not being performed. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified (prefixed) name, or the empty string // if qualified names are not available. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attrType The attribute type as a string. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure addAttribute(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; value : PSAXChar; valueLength : Integer); override; // Remove an attribute declaration. // // @param index The index of the attribute (zero-based). procedure removeAttribute(index : Integer); override; // Assign a value to the "declared" flag of a specific attribute. // This is normally needed only for attributes of type CDATA, // including attributes whose type is changed to or from CDATA. // // @param index The index of the attribute (zero-based). // @param value The desired flag value. // @exception ESAXIllegalArgumentException When the // supplied index does not identify an attribute. // @see <a href="../BSAXHelpers/TBufferedAttributes2Impl.html#setType">TBufferedAttributes2Impl.setType</a> procedure setDeclared(index : Integer; value : Boolean); // Assign a value to the "specified" flag of a specific attribute. // This is the only way this flag can be cleared, except clearing // by initialization with the copy constructor. // // @param index The index of the attribute (zero-based). // @param value The desired flag value. // @exception ESAXIllegalArgumentException When the // supplied index does not identify an attribute. procedure setSpecified(index : Integer; value : Boolean); end; // This class extends the SAX2 base buffered handler class to support the // SAX2 <a href="../BSAXExt/IBufferedLexicalHandler.html">IBufferedLexicalHandler</a>, // <a href="../BSAXExt/IBufferedDeclHandler.html">IBufferedDeclHandler</a>, and // <a href="../SAXExt/IEntityResolver2.html">IEntityResolver2</a> extensions. // Except for overriding the // original SAX1 <a href="../BSAXHelpers/TBufferedDefaultHandler.html#resolveEntity">resolveEntity</a> // method the added handler methods just return. Subclassers may // override everything on a method-by-method basis. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p> <em>Note:</em> this class might yet learn that the // <em>IBufferedContentHandler.setDocumentLocator()</em> call might be passed a // <a href="../BSAXExt/IBufferedLocator2.html">IBufferedLocator2</a> object, and that the // <em>IBufferedContentHandler.startElement()</em> call might be passed a // <a href="../BSAXExt/IBufferedAttributes2.html">IBufferedAttributes2</a> object. </p> // // <p>For reasons of generality and efficiency, strings that are returned // from the interface are declared as pointers (PSAXChar) and lengths. // This requires that the model use procedural out parameters rather // than functions as in the original interfaces.</p> // // @since SAX 2.0 (extensions 1.1 alpha) TBufferedDefaultHandler2 = class(TBufferedDefaultHandler, IBufferedLexicalHandler, IBufferedDeclHandler, IEntityResolver2) protected // Report an element type declaration. // // <p>The content model will consist of the string "EMPTY", the // string "ANY", or a parenthesised group, optionally followed // by an occurrence indicator. The model will be normalized so // that all parameter entities are fully resolved and all whitespace // is removed,and will include the enclosing parentheses. Other // normalization (such as removing redundant parentheses or // simplifying occurrence indicators) is at the discretion of the // parser.</p> // // @param name The element type name. // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param model The content model as a normalized string. // @param modelLength The length of the model buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an exception. /// procedure elementDecl(name : PSAXChar; nameLength : Integer; model : PSAXChar; modelLength : Integer); virtual; // Report an attribute type declaration. // // <p>Only the effective (first) declaration for an attribute will // be reported. The type will be one of the strings "CDATA", // "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", // "ENTITIES", a parenthesized token group with // the separator "|" and all whitespace removed, or the word // "NOTATION" followed by a space followed by a parenthesized // token group with all whitespace removed.</p> // // <p>The value will be the value as reported to applications, // appropriately normalized and with entity and character // references expanded.</p> // // @param eName The name of the associated element. // @param eNameLength The length of the eName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param aName The name of the attribute. // @param aNameLength The length of the aName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attrType A string representing the attribute type. // @param attrTypeLength The length of the attrType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param mode A string representing the attribute defaulting mode // ("#IMPLIED", "#REQUIRED", or "#FIXED") or '' if // none of these applies. // @param modeLength The length of the mode buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value A string representing the attribute's default value, // or an empty string if there is none. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an exception. procedure attributeDecl(eName : PSAXChar; eNameLength : Integer; aName : PSAXChar; aNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; mode : PSAXChar; modeLength : Integer; value : PSAXChar; valueLength : Integer); virtual; // Report an internal entity declaration. // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%'. // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The replacement text of the entity. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#externalEntityDecl">TBufferedDefaultHandler2.externalEntityDecl</a> // @see <a href="../BSAX/IBufferedDTDHandler.html#unparsedEntityDecl">IBufferedDTDHandler.unparsedEntityDecl</a> procedure internalEntityDecl(name : PSAXChar; nameLength : Integer; value : PSAXChar; valueLength : Integer); virtual; // Report a parsed external entity declaration. // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%'. // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The declared public identifier of the entity, or // the empty string if none was declared. // @param publicIdLength The length of the publicId buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The declared system identifier of the entity. // @param systemIdLength The length of the systemId buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#internalEntityDecl">TBufferedDefaultHandler2.internalEntityDecl</a> // @see <a href="../BSAX/IBufferedDTDHandler.html#unparsedEntityDecl">IBufferedDTDHandler.unparsedEntityDecl</a> procedure externalEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); virtual; // Report the start of DTD declarations, if any. // // @param name The document type name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The declared public identifier for the // external DTD subset, or an empty string if none was declared. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The declared system identifier for the // external DTD subset, or an empty string if none was declared. // (Note that this is not resolved against the document // base URI.) // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an // exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#endDTD">TBufferedDefaultHandler2.endDTD</a> // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#startEntity">TBufferedDefaultHandler2.startEntity</a> procedure startDTD(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); virtual; // Report the end of DTD declarations. // // @exception ESAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#startDTD">TBufferedDefaultHandler2.startDTD</a> procedure endDTD(); virtual; // Report the beginning of some internal and external XML entities. // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%', and if it is the // external DTD subset, it will be '[dtd]'. // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception SAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#endEntity">TBufferedDefaultHandler2.endEntity</a> // @see <a href="../BSAXExt/IBufferedDeclHandler.html#internalEntityDecl">IBufferedDeclHandler.internalEntityDecl</a> // @see <a href="../BSAXExt/IBufferedDeclHandler.html#externalEntityDecl">IBufferedDeclHandler.externalEntityDecl</a> /// procedure startEntity(name : PSAXChar; nameLength : Integer); virtual; // Report the end of an entity. // // @param name The name of the entity that is ending. // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#startEntity">TBufferedDefaultHandler2.startEntity</a> procedure endEntity(name : PSAXChar; nameLength : Integer); virtual; // Report the start of a CDATA section. // // @exception ESAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#endCDATA">TBufferedDefaultHandler2.endCDATA</a> procedure startCDATA(); virtual; // Report the end of a CDATA section. // // @exception ESAXException The application may raise an exception. // @see <a href="../BSAXHelpers/TBufferedDefaultHandler2.html#startCDATA">TBufferedDefaultHandler2.startCDATA</a> procedure endCDATA(); virtual; // Report an XML comment anywhere in the document. // // @param ch An array holding the characters in the comment. // @param chLength The length of the ch buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The application may raise an exception. procedure comment(ch : PSAXChar; chLength : Integer); virtual; // Allows applications to provide an external subset for documents // that don't explicitly define one. // // @param name Identifies the document root element. This name comes // from a DOCTYPE declaration (where available) or from the actual // root element. // @param baseURI The document's base URI, serving as an additional // hint for selecting the external subset. This is always an absolute // URI, unless it is an empty string because the IXMLReader was given an // IInputSource without one. // // @return An InputSource object describing the new external subset // to be used by the parser, or nil to indicate that no external // subset is provided. // // @exception ESAXException Any SAX exception. function getExternalSubset(const name, baseURI : SAXString) : IInputSource; virtual; // Tells the parser to resolve the systemId against the baseURI // and read the entity text from that resulting absolute URI. // Note that because the older // <a href="../BSAXHelpers/TBufferedDefaultHandler.html#resolveEntity">TBufferedDefaultHandler.resolveEntity</a> // method is overridden to call this one, this method may sometimes // be invoked with null <em>name</em> and <em>baseURI</em>, and // with the <em>systemId</em> already absolutized. // // @param name Identifies the external entity being resolved. // Either '[dtd]' for the external subset, or a name starting // with '%' to indicate a parameter entity, or else the name of // a general entity. // @param publicId The public identifier of the external entity being // referenced (normalized as required by the XML specification), or // an empty string if none was supplied. // @param baseURI The URI with respect to which relative systemIDs // are interpreted. This is always an absolute URI, unless it is // nil because the XMLReader was given an IInputSource without one. // This URI is defined by the XML specification to be the one // associated with the '&lt;' starting the relevant declaration. // @param systemId The system identifier of the external entity // being referenced; either a relative or absolute URI. // // @return An IInputSource object describing the new input source to // be used by the parser. Returning nil directs the parser to // resolve the system ID against the base URI and open a connection // to resulting URI. // // @exception ESAXException Any SAX exception. function resolveEntity(const name, publicId, baseURI, systemId : SAXString) : IInputSource; reintroduce; overload; virtual; // Invokes // <a href="../SAXExt/IEntityResolver2.html#resolveEntity">IEntityResolver2.resolveEntity</a> // with empty entity name and base URI. // You only need to override that method to use this class. function resolveEntity(const publicId, systemId : SAXString) : IInputSource; reintroduce; overload; virtual; end; const DEFAULT_ATTRIBUTE_COUNT = 5; var BufferedHandlerDefault: TBufferedDefaultHandler; implementation resourcestring sBadIndex = 'Attempt to modify attribute at illegal index: %d'; sCantChange = 'Cannot change %s %s while parsing'; sFeatureName = 'Feature: %s'; sFeatureCheck = 'feature'; sNoParent = 'No parent for filter'; sPropertyName = 'Property: %s'; sNoAttributeAtIndex = 'No attribute at index: %d'; sNoAttributeLocalUri = 'No such attribute: local= %s, namespace= %s'; sNoAttributeQName = 'No such attribute: %s'; { TBufferedAttributesImpl } constructor TBufferedAttributesImpl.Create(); begin inherited Create(); Flength:= 0; Fdata:= nil; end; constructor TBufferedAttributesImpl.Create(const atts : IBufferedAttributes); begin inherited Create(); Flength:= 0; Fdata:= nil; setAttributes(atts); end; destructor TBufferedAttributesImpl.Destroy(); begin inherited Destroy(); end; function TBufferedAttributesImpl.getLength() : Integer; begin Result:= Flength; end; procedure TBufferedAttributesImpl.getURI(index : Integer; out uri: PSAXChar; out uriLength: Integer); begin if ((index >= 0) and (index < Flength)) then begin uri:= Fdata[index].uri; uriLength:= Fdata[index].uriLength; end else begin uri:= nil; uriLength:= 0; end; end; procedure TBufferedAttributesImpl.getLocalName(index : Integer; out localName: PSAXChar; out localNameLength: Integer); begin if ((index >= 0) and (index < Flength)) then begin localName:= Fdata[index].localName; localNameLength:= FData[index].localNameLength; end else begin localName:= nil; localNameLength:= 0; end; end; procedure TBufferedAttributesImpl.getQName(index : Integer; out qName: PSAXChar; out qNameLength: Integer); begin if ((index >= 0) and (index < Flength)) then begin qName:= Fdata[index].qName; qNameLength:= Fdata[index].qNameLength; end else begin qName:= nil; qNameLength:= 0; end; end; procedure TBufferedAttributesImpl.getType(index : Integer; out attrType: PSAXChar; out attrTypeLength: Integer); begin if ((index >= 0) and (index < Flength)) then begin attrType:= Fdata[index].attrType; attrTypeLength:= Fdata[index].attrTypeLength; end else begin attrType:= nil; attrTypeLength:= 0; end; end; procedure TBufferedAttributesImpl.getType(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; out attrType: PSAXChar; out attrTypeLength: Integer); var I : Integer; begin I:= 0; while I < Flength do begin if ((SAXStrEqual(Fdata[I].uri, Fdata[I].uriLength, uri, uriLength)) and (SAXStrEqual(Fdata[I].localName, Fdata[I].localNameLength, localName, localNameLength))) then begin attrType:= Fdata[I].attrType; attrTypeLength:= Fdata[I].attrTypeLength; Exit; end; Inc(I); end; attrType:= nil; attrTypeLength:= 0; end; procedure TBufferedAttributesImpl.getType(qName: PSAXChar; qNameLength: Integer; out attrType: PSAXChar; out attrTypeLength: Integer); var I : Integer; begin I:= 0; while I < Flength do begin if (SAXStrEqual(Fdata[I].qName, Fdata[I].qNameLength, qName, qNameLength)) then begin attrType:= Fdata[I].attrType; attrTypeLength:= Fdata[I].attrTypeLength; Exit; end; Inc(I); end; attrType:= nil; attrTypeLength:= 0; end; procedure TBufferedAttributesImpl.getValue(index : Integer; out value: PSAXChar; out valueLength: Integer); begin if ((index >= 0) and (index < Flength)) then begin value:= Fdata[index].value; valueLength:= Fdata[index].valueLength; end else begin value:= nil; valueLength:= 0; end; end; procedure TBufferedAttributesImpl.getValue(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; out value: PSAXChar; out valueLength: Integer); var I : Integer; begin I:= 0; while I < Flength do begin if ((SAXStrEqual(Fdata[I].uri, Fdata[I].uriLength, uri, uriLength)) and (SAXStrEqual(Fdata[I].localName, Fdata[I].localNameLength, localName, localNameLength))) then begin value:= Fdata[I].value; valueLength:= Fdata[I].valueLength; Exit; end; Inc(I); end; value:= nil; valueLength:= 0; end; procedure TBufferedAttributesImpl.getValue(qName : PSAXChar; qNameLength : Integer; out value: PSAXChar; out valueLength: Integer); var I : Integer; begin I:= 0; while I < Flength do begin if (SAXStrEqual(Fdata[I].qName, Fdata[I].qNameLength, qName, qNameLength)) then begin value:= Fdata[I].value; valueLength:= Fdata[I].valueLength; Exit; end; Inc(I); end; value:= nil; valueLength:= 0; end; function TBufferedAttributesImpl.getIndex(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Integer; var I : Integer; begin I:= 0; while I < Flength do begin if ((SAXStrEqual(Fdata[I].uri, Fdata[I].uriLength, uri, uriLength)) and (SAXStrEqual(Fdata[I].localName, Fdata[I].localNameLength, localName, localNameLength))) then begin Result:= I; Exit; end; Inc(I); end; Result:= -1; end; function TBufferedAttributesImpl.getIndex(qName : PSAXChar; qNameLength : Integer) : Integer; var I : Integer; begin I:= 0; while I < Flength do begin if (SAXStrEqual(Fdata[I].qName, Fdata[I].qNameLength, qName, qNameLength)) then begin Result:= I; Exit; end; Inc(I); end; Result:= -1; end; procedure TBufferedAttributesImpl.clear(); begin // Everything is keyed off of length-- // when space is reused it is reset as well Flength:= 0; end; procedure TBufferedAttributesImpl.setAttributes( const atts : IBufferedAttributes); var I : Integer; begin Flength:= atts.getLength(); ensureCapacity(Flength); for I:= 0 to Flength-1 do begin with FData[I] do begin atts.getURI(I, uri, uriLength); atts.getLocalName(I, localName, localNameLength); atts.getQName(I, qName, qNameLength); atts.getType(I, attrType, attrTypeLength); atts.getValue(I, value, valueLength); end; end; end; procedure TBufferedAttributesImpl.addAttribute(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; value : PSAXChar; valueLength : Integer); begin ensureCapacity(Flength + 1); Fdata[Flength].uri:= uri; Fdata[Flength].uriLength:= uriLength; Fdata[Flength].localName:= localName; Fdata[Flength].localNameLength:= localNameLength; Fdata[Flength].qName:= qName; Fdata[Flength].qNameLength:= qNameLength; Fdata[Flength].attrType:= attrType; Fdata[Flength].attrTypeLength:= attrTypeLength; Fdata[Flength].value:= value; Fdata[Flength].valueLength:= valueLength; Inc(Flength); end; procedure TBufferedAttributesImpl.setAttribute(index : Integer; uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; value : PSAXChar; valueLength : Integer); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index].uri:= uri; Fdata[index].uriLength:= uriLength; Fdata[index].localName:= localName; Fdata[index].localNameLength:= localNameLength; Fdata[index].qName:= qName; Fdata[index].qNameLength:= qNameLength; Fdata[index].attrType:= attrType; Fdata[index].attrTypeLength:= attrTypeLength; Fdata[index].value:= value; Fdata[index].valueLength:= valueLength; end else badIndex(index); end; procedure TBufferedAttributesImpl.removeAttribute(index : Integer); var Source : Pointer; Dest : Pointer; FromBytes, ToBytes, TotalBytes, NewLen: Integer; FromIndex, ToIndex : Integer; begin if ((index >= 0) and (index < Flength)) then begin if (index < Flength-1) then begin // Deletes a block from the array FromIndex:= index; ToIndex:= index; Dest:= Pointer(FData); Source:= Pointer(FData); FromBytes:= SizeOf(SAXString) * FromIndex; ToBytes:= SizeOf(SAXString) * (ToIndex + 1); TotalBytes:= SizeOf(TBufferedAttributesRecord) * (Flength - ToIndex); NewLen:= Flength - ((ToIndex - FromIndex) + 1); Inc(Cardinal(Dest), FromBytes); Inc(Cardinal(Source), ToBytes); Move(Source^, Dest^, TotalBytes); FLength:= NewLen; end else Dec(Flength); end else badIndex(index); end; procedure TBufferedAttributesImpl.setURI(index : Integer; uri : PSAXChar; uriLength : Integer); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index].uri:= uri; Fdata[index].uriLength:= uriLength; end else badIndex(index); end; procedure TBufferedAttributesImpl.setLocalName(index : Integer; localName : PSAXChar; localNameLength : Integer); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index].localName:= localName; Fdata[index].localNameLength:= localNameLength; end else badIndex(index); end; procedure TBufferedAttributesImpl.setQName(index : Integer; qName : PSAXChar; qNameLength : Integer); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index].qName:= qName; Fdata[index].qNameLength:= qNameLength; end else badIndex(index); end; procedure TBufferedAttributesImpl.setType(index : Integer; attrType : PSAXChar; attrTypeLength : Integer); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index].attrType:= attrType; Fdata[index].attrTypeLength:= attrTypeLength; end else badIndex(index); end; procedure TBufferedAttributesImpl.setValue(index : Integer; value : PSAXChar; valueLength : Integer); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index].value:= value; Fdata[index].valueLength:= valueLength; end else badIndex(index); end; procedure TBufferedAttributesImpl.ensureCapacity(n : Integer); begin if (n <= 0) then Exit; if (Fdata <> nil) and (Length(Fdata) >= n) then Exit; SetLength(Fdata, n); end; procedure TBufferedAttributesImpl.badIndex(index : Integer); begin raise ESAXException.Create(Format(sBadIndex, [index])); end; { TBufferedDefaultHandler } function TBufferedDefaultHandler.resolveEntity(const publicId, systemId : SAXString) : IInputSource; begin Result:= nil; end; procedure TBufferedDefaultHandler.notationDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.unparsedEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer; notationName : PSAXChar; notationNameLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.setDocumentLocator(const locator: ILocator); begin // no op end; procedure TBufferedDefaultHandler.startDocument(); begin // no op end; procedure TBufferedDefaultHandler.endDocument(); begin // no op end; procedure TBufferedDefaultHandler.startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); begin // no op end; procedure TBufferedDefaultHandler.endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); begin // no op end; procedure TBufferedDefaultHandler.startElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; const atts: IBufferedAttributes); begin // no op end; procedure TBufferedDefaultHandler.endElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.characters(ch : PSAXChar; chLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.ignorableWhitespace(ch : PSAXChar; chLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.processingInstruction(target : PSAXChar; targetLength : Integer; data : PSAXChar; dataLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.skippedEntity(name : PSAXChar; nameLength : Integer); begin // no op end; procedure TBufferedDefaultHandler.warning(const e : ISAXParseError); begin // no op end; procedure TBufferedDefaultHandler.error(const e : ISAXParseError); begin // no op end; procedure TBufferedDefaultHandler.fatalError(const e : ISAXParseError); begin // no op end; { TBufferedXMLFilterImpl } constructor TBufferedXMLFilterImpl.create; begin inherited Create(); Fparent:= nil; Flocator:= nil; FentityResolver:= nil; FdtdHandler:= nil; FcontentHandler:= nil; FerrorHandler:= nil; end; constructor TBufferedXMLFilterImpl.create( const parent: IBufferedXMLReader); begin inherited Create(); setParent(parent); Flocator:= nil; FentityResolver:= nil; FdtdHandler:= nil; FcontentHandler:= nil; FerrorHandler:= nil; end; procedure TBufferedXMLFilterImpl.setParent( const parent: IBufferedXMLReader); begin Fparent:= parent; end; function TBufferedXMLFilterImpl.getParent: IBufferedXMLReader; begin Result:= Fparent; end; procedure TBufferedXMLFilterImpl.setFeature(const name: SAXString; value: Boolean); begin if (Fparent <> nil) then Fparent.setFeature(name, value) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [Name])); end; function TBufferedXMLFilterImpl.getFeature(const name: SAXString): Boolean; begin if (Fparent <> nil) then Result:= Fparent.getFeature(name) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [Name])); end; function TBufferedXMLFilterImpl.getProperty( const name: SAXString): IProperty; begin if (Fparent <> nil) then Result:= Fparent.getProperty(name) else raise ESAXNotRecognizedException.Create(Format(sPropertyName, [Name])); end; procedure TBufferedXMLFilterImpl.setEntityResolver(const resolver: IEntityResolver); begin FentityResolver:= resolver; end; function TBufferedXMLFilterImpl.getEntityResolver: IEntityResolver; begin Result:= FentityResolver; end; procedure TBufferedXMLFilterImpl.setDTDHandler( const handler: IBufferedDTDHandler); begin FdtdHandler:= handler; end; function TBufferedXMLFilterImpl.getDTDHandler: IBufferedDTDHandler; begin Result:= FdtdHandler; end; procedure TBufferedXMLFilterImpl.setContentHandler( const handler: IBufferedContentHandler); begin FcontentHandler:= handler; end; function TBufferedXMLFilterImpl.getContentHandler: IBufferedContentHandler; begin Result:= FcontentHandler; end; procedure TBufferedXMLFilterImpl.setErrorHandler( const handler: IErrorHandler); begin FerrorHandler:= handler; end; function TBufferedXMLFilterImpl.getErrorHandler: IErrorHandler; begin Result:= FerrorHandler; end; procedure TBufferedXMLFilterImpl.parse(const input: IInputSource); begin setupParse(); Fparent.parse(input); end; procedure TBufferedXMLFilterImpl.parse(const systemId: SAXString); var source : IInputSource; begin source:= TInputSource.Create(systemId) as IInputSource; try parse(source); finally source:= nil; end; end; function TBufferedXMLFilterImpl.resolveEntity(const publicId, systemId: SAXString): IInputSource; begin if (FentityResolver <> nil) then Result:= FentityResolver.resolveEntity(publicId, systemId) else Result:= nil; end; procedure TBufferedXMLFilterImpl.notationDecl(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer); begin if (FdtdHandler <> nil) then FdtdHandler.notationDecl(name, nameLength, publicId, publicIdLength, systemId, systemIdLength); end; procedure TBufferedXMLFilterImpl.unparsedEntityDecl(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer; notationName: PSAXChar; notationNameLength: Integer); begin if (FdtdHandler <> nil) then FdtdHandler.unparsedEntityDecl(name, nameLength, publicId, publicIdLength, systemId, systemIdLength, notationName, notationNameLength); end; procedure TBufferedXMLFilterImpl.setDocumentLocator( const locator: ILocator); begin Flocator:= locator; if (FcontentHandler <> nil) then FcontentHandler.setDocumentLocator(locator); end; procedure TBufferedXMLFilterImpl.startDocument; begin if (FcontentHandler <> nil) then FcontentHandler.startDocument(); end; procedure TBufferedXMLFilterImpl.endDocument; begin if (FcontentHandler <> nil) then FcontentHandler.endDocument(); end; procedure TBufferedXMLFilterImpl.startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.startPrefixMapping(prefix, prefixLength, uri, uriLength); end; procedure TBufferedXMLFilterImpl.endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.endPrefixMapping(prefix, prefixLength); end; procedure TBufferedXMLFilterImpl.startElement(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; qName: PSAXChar; qNameLength: Integer; const atts: IBufferedAttributes); begin if (FcontentHandler <> nil) then FcontentHandler.startElement(uri, uriLength, localName, localNameLength, qName, qNameLength, atts); end; procedure TBufferedXMLFilterImpl.endElement(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; qName: PSAXChar; qNameLength: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.endElement(uri, uriLength, localName, localNameLength, qName, qNameLength); end; procedure TBufferedXMLFilterImpl.characters(ch: PSAXChar; length: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.characters(ch, length); end; procedure TBufferedXMLFilterImpl.ignorableWhitespace(ch: PSAXChar; length: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.ignorableWhitespace(ch, length); end; procedure TBufferedXMLFilterImpl.processingInstruction(target: PSAXChar; targetLength: Integer; data: PSAXChar; dataLength: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.processingInstruction(target, targetLength, data, dataLength); end; procedure TBufferedXMLFilterImpl.skippedEntity(name: PSAXChar; nameLength: Integer); begin if (FcontentHandler <> nil) then FcontentHandler.skippedEntity(name, nameLength); end; procedure TBufferedXMLFilterImpl.warning(const e: ISAXParseError); begin if (FerrorHandler <> nil) then FerrorHandler.warning(e); end; procedure TBufferedXMLFilterImpl.error(const e: ISAXParseError); begin if (FerrorHandler <> nil) then FerrorHandler.error(e); end; procedure TBufferedXMLFilterImpl.fatalError(const e: ISAXParseError); begin if (FerrorHandler <> nil) then FerrorHandler.fatalError(e); end; procedure TBufferedXMLFilterImpl.setupParse; begin if (Fparent = nil) then raise ESAXException.Create(sNoParent) else begin Fparent.setEntityResolver(self); Fparent.setDTDHandler(self); Fparent.setContentHandler(self); Fparent.setErrorHandler(self); end; end; { TBufferedXMLReaderImpl } constructor TBufferedXMLReaderImpl.Create; begin inherited Create; setContentHandler(nil); setDTDHandler(nil); setEntityResolver(nil); setErrorHandler(nil); FcolumnNumber := -1; FlineNumber := -1; Fnamespaces := True; Fparsing := False; Fprefixes := False; FpublicId := ''; FsystemId := ''; end; destructor TBufferedXMLReaderImpl.Destroy; begin FcontentHandler:= nil; FdtdHandler := nil; FentityResolver:= nil; FerrorHandler := nil; inherited; end; procedure TBufferedXMLReaderImpl.checkNotParsing(propType, name: SAXString); begin if Fparsing then raise ESAXNotSupportedException.Create(Format(sCantChange, [propType, name])); end; function TBufferedXMLReaderImpl.getColumnNumber: Integer; begin Result:= FcolumnNumber; end; function TBufferedXMLReaderImpl.getContentHandler: IBufferedContentHandler; begin Result:= FcontentHandler; end; function TBufferedXMLReaderImpl.getDTDHandler: IBufferedDTDHandler; begin Result:= FdtdHandler; end; function TBufferedXMLReaderImpl.getEntityResolver: IEntityResolver; begin Result:= FentityResolver; end; function TBufferedXMLReaderImpl.getErrorHandler: IErrorHandler; begin Result:= FerrorHandler; end; function TBufferedXMLReaderImpl.getFeature(const name: SAXString): Boolean; begin if (name = NamespacesFeature) then Result:= Fnamespaces else if (name = NamespacePrefixesFeature) then Result:= Fprefixes else if (name = ValidationFeature) or (name = ExternalGeneralFeature) or (name = ExternalParameterFeature) then raise ESAXNotSupportedException.Create(Format(sFeatureName, [name])) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [name])); end; function TBufferedXMLReaderImpl.getLineNumber: Integer; begin Result:= FlineNumber; end; function TBufferedXMLReaderImpl.getProperty( const name: SAXString): IProperty; begin raise ESAXNotRecognizedException.Create(Format(sPropertyName, [name])); end; function TBufferedXMLReaderImpl.getPublicId: PSAXChar; begin Result:= PSAXChar(FpublicId); end; function TBufferedXMLReaderImpl.getSystemId: PSAXChar; begin Result:= PSAXChar(FsystemId); end; procedure TBufferedXMLReaderImpl.parse(const input: IInputSource); begin FpublicId:= input.publicId; FsystemId:= input.systemId; Fparsing := True; try parseInput(input); finally Fparsing:= False; end; end; procedure TBufferedXMLReaderImpl.parse(const systemId: SAXString); var input: IInputSource; begin input:= getEntityResolver().resolveEntity('', systemId); if not Assigned(input) then input:= TInputSource.Create(systemId) as IInputSource; try parse(input); finally input:= nil; end; end; procedure TBufferedXMLReaderImpl.setColumnNumber(value: Integer); begin FcolumnNumber:= value; end; procedure TBufferedXMLReaderImpl.setContentHandler( const handler: IBufferedContentHandler); begin if Assigned(handler) then FcontentHandler:= handler else FcontentHandler:= bufferedHandlerDefault; end; procedure TBufferedXMLReaderImpl.setDTDHandler( const handler: IBufferedDTDHandler); begin if Assigned(handler) then FdtdHandler:= handler else FdtdHandler:= bufferedHandlerDefault; end; procedure TBufferedXMLReaderImpl.setEntityResolver(const resolver: IEntityResolver); begin if Assigned(resolver) then FentityResolver:= resolver else FentityResolver:= bufferedHandlerDefault; end; procedure TBufferedXMLReaderImpl.setErrorHandler( const handler: IErrorHandler); begin if Assigned(handler) then FerrorHandler:= handler else FerrorHandler:= bufferedHandlerDefault; end; procedure TBufferedXMLReaderImpl.setFeature(const name: SAXString; value: Boolean); begin // The only features supported are namespaces and namespace-prefixes. if name = namespacesFeature then begin checkNotParsing(sFeatureCheck, name); Fnamespaces:= value; if not Fnamespaces and not Fprefixes then Fprefixes:= True; end else if name = namespacePrefixesFeature then begin checkNotParsing(sFeatureCheck, name); Fprefixes:= Value; if not Fprefixes and not Fnamespaces then Fnamespaces:= True; end else if (name = ValidationFeature) or (name = ExternalGeneralFeature) or (name = ExternalParameterFeature) then raise ESAXNotSupportedException.Create(Format(sFeatureName, [name])) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [name])); end; procedure TBufferedXMLReaderImpl.setLineNumber(value: Integer); begin FlineNumber:= value; end; procedure TBufferedXMLReaderImpl.setPublicId(value: PSAXChar); begin FpublicId:= value; end; procedure TBufferedXMLReaderImpl.setSystemId(value: PSAXChar); begin FsystemId:= value; end; { TBufferedDefaultHandler2 } procedure TBufferedDefaultHandler2.attributeDecl(eName: PSAXChar; eNameLength: Integer; aName: PSAXChar; aNameLength: Integer; attrType: PSAXChar; attrTypeLength: Integer; mode: PSAXChar; modeLength: Integer; value: PSAXChar; valueLength: Integer); begin // do nothing end; procedure TBufferedDefaultHandler2.comment(ch: PSAXChar; chLength: Integer); begin // do nothing end; procedure TBufferedDefaultHandler2.elementDecl(name: PSAXChar; nameLength: Integer; model: PSAXChar; modelLength: Integer); begin // do nothing end; procedure TBufferedDefaultHandler2.endCDATA; begin // do nothing end; procedure TBufferedDefaultHandler2.endDTD; begin // do nothing end; procedure TBufferedDefaultHandler2.endEntity(name: PSAXChar; nameLength: Integer); begin // do nothing end; procedure TBufferedDefaultHandler2.externalEntityDecl(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer); begin // do nothing end; function TBufferedDefaultHandler2.getExternalSubset(const name, baseURI: SAXString): IInputSource; begin Result:= nil; end; procedure TBufferedDefaultHandler2.internalEntityDecl(name: PSAXChar; nameLength: Integer; value: PSAXChar; valueLength: Integer); begin // do nothing end; function TBufferedDefaultHandler2.resolveEntity(const name, publicId, baseURI, systemId: SAXString): IInputSource; begin Result:= nil; end; function TBufferedDefaultHandler2.resolveEntity(const publicId, systemId : SAXString) : IInputSource; begin Result:= resolveEntity('', publicId, '', systemId); end; procedure TBufferedDefaultHandler2.startCDATA; begin // do nothing end; procedure TBufferedDefaultHandler2.startDTD(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer); begin // do nothing end; procedure TBufferedDefaultHandler2.startEntity(name: PSAXChar; nameLength: Integer); begin // do nothing end; { TBufferedAttributes2Impl } procedure TBufferedAttributes2Impl.addAttribute(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; qName: PSAXChar; qNameLength: Integer; attrType: PSAXChar; attrTypeLength: Integer; value: PSAXChar; valueLength: Integer); var len : Integer; begin inherited addAttribute(uri, uriLength, localName, localNameLength, qName, qNameLength, attrType, attrTypeLength, value, valueLength); len:= getLength(); if (Length(Fspecified) < len) then begin SetLength(Fdeclared, len); SetLength(Fspecified, len); end; Fspecified[len - 1]:= true; Fdeclared[len - 1]:= not SAXStrEqual(attrType, attrTypeLength, PSAXChar(SAXString('CDATA')), 5); end; function TBufferedAttributes2Impl.isDeclared(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer): Boolean; var index : Integer; begin index:= getIndex(uri, uriLength, localName, localNameLength); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeLocalUri, [PSAXCharToSAXString(localName, localNameLength), PSAXCharToSAXString(uri, uriLength)]); Result:= Fdeclared[index]; end; function TBufferedAttributes2Impl.isDeclared(index: Integer): Boolean; begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Result:= Fdeclared[index]; end; function TBufferedAttributes2Impl.isDeclared(qName: PSAXChar; qNameLength: Integer): Boolean; var index : Integer; begin index:= getIndex(qName, qNameLength); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeQName, [PSAXCharToSAXString(qName, qNameLength)]); Result:= Fdeclared[index]; end; function TBufferedAttributes2Impl.isSpecified(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer): Boolean; var index : Integer; begin index:= getIndex(uri, uriLength, localName, localNameLength); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeLocalUri, [PSAXCharToSAXString(localName, localNameLength), PSAXCharToSAXString(uri, uriLength)]); Result:= Fspecified[index]; end; function TBufferedAttributes2Impl.isSpecified(index: Integer): Boolean; begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Result:= Fspecified[index]; end; function TBufferedAttributes2Impl.isSpecified(qName: PSAXChar; qNameLength: Integer): Boolean; var index : Integer; begin index:= getIndex(qName, qNameLength); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeQName, [PSAXCharToSAXString(qName, qNameLength)]); Result:= Fspecified[index]; end; procedure TBufferedAttributes2Impl.removeAttribute(index: Integer); var origMax : Integer; PDest, PSource : Pointer; begin origMax:= getLength() - 1; inherited removeAttribute(index); if (index <> origMax) then begin // This is just a faster way of deleting an item PDest:= Pointer(Fspecified); Inc(Cardinal(PDest), index); PSource:= PDest; Inc(Cardinal(PSource), 1); Move(PSource^, PDest^, origMax-index); SetLength(fspecified, origMax-1); // This is just a faster way of deleting an item PDest:= Pointer(Fdeclared); Inc(Cardinal(PDest), index); PSource:= PDest; Inc(Cardinal(PSource), 1); Move(PSource^, PDest^, origMax-index); SetLength(fdeclared, origMax-1); end; end; procedure TBufferedAttributes2Impl.setAttributes( const atts: IBufferedAttributes); var length, I : Integer; flags : array of Boolean; a2 : IBufferedAttributes2; begin length:= atts.getLength(); inherited setAttributes(atts); SetLength(flags, length); if (atts.QueryInterface(IBufferedAttributes2, a2) = 0) then begin for I := 0 to length-1 do flags[I]:= a2.isSpecified(I); end else begin for I := 0 to length-1 do flags[I]:= true; end; end; procedure TBufferedAttributes2Impl.setDeclared(index: Integer; value: Boolean); begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Fdeclared[index]:= value; end; procedure TBufferedAttributes2Impl.setSpecified(index: Integer; value: Boolean); begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Fspecified[index]:= value; end; initialization // Create a default handler object BufferedHandlerDefault := TBufferedDefaultHandler.Create; // Keep it around BufferedHandlerDefault._AddRef; finalization // Release the reference BufferedHandlerDefault._Release; end.
(************************************************************************* ** IXXAT Automation GmbH ************************************************************************** ** ** $Workfile: UnitMain.PAS $ UnitMain ** Summary: Demonstration for configuration and update from a ** CAN-object with VCI V3. ** In this example the use of a own thread for the receive ** function is shown. ** ** $Revision: 1 $ ** Version: @(VERSION) ** $Date: 2006-07-24 $ ** Compiler: Delphi 5.0 ** Author: Peter Wucherer ** ************************************************************************** ** all rights reserved *************************************************************************) unit UnitMain; interface uses Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, Vci3Can, StdCtrls, ExtCtrls, UnitRxThread, ComCtrls, iVCLComponent, iCustomComponent, iPositionComponent, iScaleComponent, iKnob, iThreadTimers, iTimers, iSwitchRocker, iObjectCanvas, iSlider, iOdometer, iAnalogDisplay, iSevenSegmentDisplay, iSevenSegmentHexadecimal, iSwitchPanel, iSwitchLed, iSwitchToggle, sRadioButton, sGroupBox, sCheckBox, sEdit, sSpinEdit, Buttons, sBitBtn, ImgList, acAlphaImageList, sSkinProvider, sSkinManager, Menus, sLabel, sComboBox, Mask, sMaskEdit, sCustomComboEdit, sCurrEdit, sCurrencyEdit, iComponent, VCI3Types; const BitTimingReg0 = CAN_BT0_250KB; BitTimingReg1 = CAN_BT1_250KB; BitTimingString = '250 kbit/s'; type CAN_DATA = array of byte; TFormMain = class(TForm) stbBottom: TStatusBar; pnlCANState: TPanel; lblCANInit: TLabel; lblTxPending: TLabel; lblDataOverrun: TLabel; lblWarningLevel: TLabel; lblBusOff: TLabel; shaCtrlInit: TShape; shaTxPending: TShape; shaDataOverrun: TShape; shaWarningLevel: TShape; shaBusOff: TShape; tmrUpdateInfo: TTimer; btnTransmit: TButton; lblTxResult: TLabel; lblLastRxMsgType: TLabel; lblMsgData: TLabel; iKnob1: TiKnob; iKnob2: TiKnob; iThreadTimers1: TiThreadTimers; iKnob3: TiKnob; iKnob4: TiKnob; iKnob5: TiKnob; iKnob6: TiKnob; iAnalogDisplay1: TiAnalogDisplay; iAnalogDisplay2: TiAnalogDisplay; CheckBox1: TCheckBox; CheckBox3: TCheckBox; CheckBox2: TCheckBox; sGroupBox2: TsGroupBox; sDecimalSpinEdit1: TsDecimalSpinEdit; CheckBox8: TCheckBox; sGroupBox3: TsGroupBox; iSlider4: TiSlider; Label3: TLabel; CheckBox9: TCheckBox; CheckBox10: TCheckBox; sDecimalSpinEdit2: TsDecimalSpinEdit; sGroupBox4: TsGroupBox; Label4: TLabel; iSlider5: TiSlider; CheckBox11: TCheckBox; sGroupBox1: TsGroupBox; sDecimalSpinEdit3: TsDecimalSpinEdit; CheckBox6: TCheckBox; sDecimalSpinEdit4: TsDecimalSpinEdit; sGroupBox5: TsGroupBox; sDecimalSpinEdit5: TsDecimalSpinEdit; CheckBox13: TCheckBox; Bevel1: TBevel; sTimePicker1: TsTimePicker; sBitBtn1: TsBitBtn; sAlphaImageList1: TsAlphaImageList; sBitBtn2: TsBitBtn; sBitBtn3: TsBitBtn; MainMenu1: TMainMenu; Abaut1: TMenuItem; Extit1: TMenuItem; Reset1: TMenuItem; sLabel1: TsLabel; sLabel2: TsLabel; sGroupBox13: TsGroupBox; sDecimalSpinEdit6: TsDecimalSpinEdit; CheckBox27: TCheckBox; sDecimalSpinEdit7: TsDecimalSpinEdit; chk1: TCheckBox; chk2: TCheckBox; grp1: TsGroupBox; chk3: TCheckBox; Label1: TLabel; isldr1: TiSlider; Label2: TLabel; isldr2: TiSlider; lbl3: TLabel; isldr3: TiSlider; grp2: TsGroupBox; chk4: TCheckBox; isldr4: TiSlider; Label5: TLabel; pgc1: TPageControl; ts1: TTabSheet; ts2: TTabSheet; pnl1: TPanel; grp3: TsGroupBox; Label6: TLabel; iSlider6: TiSlider; CheckBox14: TCheckBox; grp4: TsGroupBox; Label7: TLabel; iSlider7: TiSlider; CheckBox15: TCheckBox; grp5: TsGroupBox; Label8: TLabel; iSlider8: TiSlider; CheckBox18: TCheckBox; grp8: TsGroupBox; chk14: TCheckBox; rg5: TRadioGroup; rg6: TRadioGroup; rg7: TRadioGroup; rg8: TRadioGroup; rg9: TRadioGroup; Panel1: TPanel; sGroupBox6: TsGroupBox; CheckBox5: TCheckBox; RadioGroup6: TRadioGroup; grp7: TsGroupBox; CheckBox25: TCheckBox; rg4: TRadioGroup; rg1: TRadioGroup; RadioGroup7: TRadioGroup; RadioGroup3: TRadioGroup; CheckBox7: TCheckBox; RadioGroup1: TRadioGroup; CheckBox4: TCheckBox; grp6: TsGroupBox; CheckBox19: TCheckBox; sComboBox1: TsComboBox; CheckBox20: TCheckBox; CheckBox21: TCheckBox; CheckBox22: TCheckBox; CheckBox23: TCheckBox; sCurrencyEdit1: TsCurrencyEdit; sCurrencyEdit2: TsCurrencyEdit; sCurrencyEdit3: TsCurrencyEdit; RadioGroup5: TRadioGroup; RadioGroup4: TRadioGroup; CheckBox16: TCheckBox; CheckBox17: TCheckBox; sGroupBox12: TsGroupBox; Label9: TLabel; iSlider9: TiSlider; CheckBox26: TCheckBox; sGroupBox8: TsGroupBox; iSlider1: TiSlider; sCurrencyEdit4: TsCurrencyEdit; sGroupBox9: TsGroupBox; CheckBox24: TCheckBox; RadioGroup8: TRadioGroup; RadioGroup9: TRadioGroup; RadioGroup10: TRadioGroup; TabSheet1: TTabSheet; Panel2: TPanel; sGroupBox11: TsGroupBox; CheckBox29: TCheckBox; RadioGroup15: TRadioGroup; RadioGroup16: TRadioGroup; RadioGroup17: TRadioGroup; RadioGroup18: TRadioGroup; RadioGroup19: TRadioGroup; TabSheet2: TTabSheet; Panel3: TPanel; sGroupBox10: TsGroupBox; CheckBox28: TCheckBox; RadioGroup11: TRadioGroup; RadioGroup12: TRadioGroup; RadioGroup13: TRadioGroup; RadioGroup14: TRadioGroup; RadioGroup20: TRadioGroup; RadioGroup21: TRadioGroup; sGroupBox14: TsGroupBox; CheckBox30: TCheckBox; RadioGroup22: TRadioGroup; RadioGroup23: TRadioGroup; RadioGroup24: TRadioGroup; RadioGroup26: TRadioGroup; RadioGroup27: TRadioGroup; RadioGroup28: TRadioGroup; RadioGroup29: TRadioGroup; RadioGroup30: TRadioGroup; RadioGroup31: TRadioGroup; RadioGroup32: TRadioGroup; TabSheet3: TTabSheet; Panel4: TPanel; CheckBox31: TCheckBox; RadioGroup25: TRadioGroup; RadioGroup33: TRadioGroup; CheckBox32: TCheckBox; sGroupBox15: TsGroupBox; CheckBox33: TCheckBox; RadioGroup34: TRadioGroup; RadioGroup35: TRadioGroup; TabSheet4: TTabSheet; Panel5: TPanel; sGroupBox16: TsGroupBox; Label10: TLabel; iSlider2: TiSlider; CheckBox34: TCheckBox; sGroupBox7: TsGroupBox; iKnob7: TiKnob; iKnob8: TiKnob; RadioGroup2: TRadioGroup; CheckBox12: TCheckBox; sGroupBox17: TsGroupBox; Label11: TLabel; iSlider3: TiSlider; CheckBox35: TCheckBox; RadioGroup36: TRadioGroup; CheckBox36: TCheckBox; TabSheet5: TTabSheet; Panel6: TPanel; sGroupBox18: TsGroupBox; Label12: TLabel; iSlider10: TiSlider; CheckBox37: TCheckBox; iSlider11: TiSlider; Label13: TLabel; Label14: TLabel; iSlider12: TiSlider; Label15: TLabel; iSlider13: TiSlider; Label16: TLabel; iSlider14: TiSlider; Label17: TLabel; iSlider15: TiSlider; Label18: TLabel; iSlider16: TiSlider; Label19: TLabel; iSlider17: TiSlider; sLabel3: TsLabel; sLabel4: TsLabel; sLabel5: TsLabel; sLabel6: TsLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tmrUpdateInfoTimer(Sender: TObject); procedure btnTransmitClick(Sender: TObject); procedure Timer50_msTimer(Sender: TObject); procedure iKnob1PositionChange(Sender: TObject); procedure iKnob2PositionChange(Sender: TObject); procedure iThreadTimers1Timer2(Sender: TObject); procedure iThreadTimers1Timer1(Sender: TObject); procedure FormShow(Sender: TObject); procedure isldr1PositionChange(Sender: TObject); procedure iThreadTimers1Timer5(Sender: TObject); procedure isldr2PositionChange(Sender: TObject); procedure isldr3PositionChange(Sender: TObject); procedure iThreadTimers1Timer6(Sender: TObject); procedure iKnob3PositionChange(Sender: TObject); procedure iThreadTimers1Timer3(Sender: TObject); procedure iSwitchRocker2Change(Sender: TObject); procedure CheckBox3Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure CheckBox4Click(Sender: TObject); procedure chk3Click(Sender: TObject); procedure iThreadTimers1Timer7(Sender: TObject); procedure CheckBox7Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure iThreadTimers1Timer9(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure iThreadTimers1Timer8(Sender: TObject); procedure Button3Click(Sender: TObject); procedure sBitBtn1Click(Sender: TObject); procedure sBitBtn2Click(Sender: TObject); procedure sBitBtn3Click(Sender: TObject); procedure Extit1Click(Sender: TObject); procedure Reset1Click(Sender: TObject); procedure Abaut1Click(Sender: TObject); procedure iThreadTimers1Timer4(Sender: TObject); procedure chk1Click(Sender: TObject); procedure ts1ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); private m_hDeviceHandle: THandle; // the handle to the interface m_dwCanNo: LongLong; // the number of the can controller 0/1 m_hCanChannel: THandle; // the handle to the can channel m_hCanChannelRex: THandle; m_hCanControl: THandle; // the handle to the can controller m_dwTimerResolution: LongWord; // the timer resolution of the controller m_dwTimerOverruns: LongWord; // number of timer overruns m_qwOverrunValue: Int64; // stored value to add to every timestamp m_ReceiveQueueThread: TReceiveQueueThread; // a thread to receive data procedure InitSocket(); procedure InitSocketRec(); procedure ShowErrorMessage(errorText: string; hFuncResult: HResult); procedure ShowDataFrame(sCanMsg: CANMSG); procedure ShowInfoFrame(sCanMsg: CANMSG); procedure ShowErrorFrame(sCanMsg: CANMSG); procedure ShowStatusFrame(sCanMsg: CANMSG); procedure ShowWakeUpFrame(sCanMsg: CANMSG); procedure HandleTimerOverrunFrame(sCanMsg: CANMSG); procedure HandleTimerResetFrame(sCanMsg: CANMSG); procedure SendCANMessage(MSG_ID: CANMSG_ID; data: CAN_DATA); procedure SaveOptions(); public procedure ShowCANMessage(sCanMsg: CANMSG); function GetMyVersion: string; end; var FormMain: TFormMain; implementation {$R *.DFM} uses VCI3Error, SysUtils, U_SaveLoadOptions, ABOUT; // for the return codes of VCI 3 functions var TimeWork: Integer; Speed: Integer; EngSpeed: Integer; OilPres: integer; OilLevel: Integer; CoolantLevel: Integer; CoolantTemp: Integer; (************************************************************************ ** ** Function : TFormMain.FormCreate ** Delphi Message Handler ** ** Description : Here the board selection dialog will be shown ** and the controller initializing routines will ** be called in the function InitSocket ** Parameter : ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.Button1Click(Sender: TObject); begin FormDestroy(self); FormCreate(self); end; procedure TFormMain.Button2Click(Sender: TObject); begin TimeWork := 0; end; procedure TFormMain.Button3Click(Sender: TObject); begin SaveOptions; end; procedure TFormMain.CheckBox1Click(Sender: TObject); begin iKnob2.Enabled := CheckBox1.Checked; end; procedure TFormMain.CheckBox2Click(Sender: TObject); begin iKnob3.Enabled := CheckBox2.Checked; end; procedure TFormMain.CheckBox3Click(Sender: TObject); begin iKnob1.Enabled := CheckBox3.Checked; end; procedure TFormMain.CheckBox4Click(Sender: TObject); begin RadioGroup1.Enabled := CheckBox4.Checked; end; procedure TFormMain.chk3Click(Sender: TObject); begin isldr1.Enabled := chk3.Checked; isldr2.Enabled := chk3.Checked; isldr3.Enabled := chk3.Checked; end; procedure TFormMain.CheckBox7Click(Sender: TObject); begin RadioGroup3.Enabled := CheckBox7.Checked; end; procedure TFormMain.chk1Click(Sender: TObject); begin iKnob5.Enabled := chk1.Checked; iKnob6.Enabled := chk1.Checked; iKnob7.Enabled := chk1.Checked; iKnob8.Enabled := chk1.Checked; end; procedure TFormMain.Extit1Click(Sender: TObject); begin Close; end; procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveOptions; end; procedure TFormMain.FormCreate(Sender: TObject); var hFuncResult: HResult; deviceInfo: VCIDEVICEINFO; deviceInfo1: VCIDEVICEINFO; ErrorText: string; szIfaceName: PChar; hEnum: Cardinal; TG: TGUID; deviceName: string; begin // use the first CAN m_dwCanNo := 0; // set the handles to zero m_hDeviceHandle := 0; m_hCanChannel := 0; m_hCanControl := 0; m_dwTimerResolution := 0; m_dwTimerOverruns := 0; m_qwOverrunValue := 0; m_ReceiveQueueThread := nil; //***********Открытие программы без показа диалогового окна выбора устройства********************** deviceName := LoadParamFromIniFiles('Device', 'Number', varString); //Если в файле опций есть информация об устройстве то открываем его if deviceName <> EmptyStr then begin // Поиск устройства по уникальму номеру // Number = 35315748-3230-3035-0000-000000000000 TG.D1 := StrToInt('$' + Copy(deviceName, 1, 8)); TG.D2 := StrToInt('$' + Copy(deviceName, 10, 4)); TG.D3 := StrToInt('$' + Copy(deviceName, 15, 4)); TG.D4[0] := StrToInt('$' + Copy(deviceName, 20, 2)); TG.D4[1] := StrToInt('$' + Copy(deviceName, 22, 2)); TG.D4[2] := StrToInt('$' + Copy(deviceName, 25, 2)); TG.D4[3] := StrToInt('$' + Copy(deviceName, 27, 2)); TG.D4[4] := StrToInt('$' + Copy(deviceName, 29, 2)); TG.D4[5] := StrToInt('$' + Copy(deviceName, 31, 2)); TG.D4[6] := StrToInt('$' + Copy(deviceName, 33, 2)); TG.D4[7] := StrToInt('$' + Copy(deviceName, 35, 2)); hFuncResult := vciFindDeviceByHwid(TG, deviceInfo.VciObjectId); if (hFuncResult = VCI_OK) then begin hFuncResult := vciDeviceOpen(@deviceInfo.VciObjectId, m_hDeviceHandle); szIfaceName := @deviceInfo.Description; stbBottom.Panels[0].Text := szIfaceName; InitSocket(); InitSocketRec(); end else begin ErrorText := 'НЕ найден CAN интерфейс'; end; end //Если и нформация не найдена открываем по списку else begin hFuncResult := vciEnumDeviceOpen(hEnum); if (hFuncResult = VCI_OK) then begin hFuncResult := vciEnumDeviceNext(hEnum, deviceInfo); vciEnumDeviceClose(hEnum); if (hFuncResult = VCI_OK) then begin hFuncResult := vciDeviceOpen(@deviceInfo.VciObjectId, m_hDeviceHandle); szIfaceName := @deviceInfo.Description; stbBottom.Panels[0].Text := szIfaceName; InitSocket(); InitSocketRec(); end else begin ErrorText := 'НЕ найден CAN интерфейс'; end; end; end; //--------------------------------------------------------------- // show a dialog and open the selected device { hFuncResult := vciDeviceOpenDlg(WindowHandle, m_hDeviceHandle); if ( hFuncResult = VCI_OK ) then begin hFuncResult := vciDeviceGetInfo(m_hDeviceHandle, deviceInfo); if ( hFuncResult = VCI_OK ) then begin szIfaceName := @deviceInfo.Description; stbBottom.Panels[0].Text := szIfaceName; // try to open the CAN channel InitSocket(); InitSocketRec(); end else begin ErrorText := 'Error in vciDeviceGetInfo'; end; end else ErrorText := 'Error in vciDeviceOpen'; } if (hFuncResult <> VCI_OK) then ShowErrorMessage(ErrorText, hFuncResult); end; (************************************************************************ ** ** Function : TFormMain.FormDestroy ** Delphi Message Handler ** ** Description : Stop the receive thread and wait until it has finfished, ** close all handles from VCI V3 ** Parameter : ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.FormDestroy(Sender: TObject); begin iThreadTimers1.Enabled1 := false; iThreadTimers1.Enabled2 := false; iThreadTimers1.Enabled3 := false; iThreadTimers1.Enabled4 := false; iThreadTimers1.Enabled5 := false; iThreadTimers1.Enabled6 := false; iThreadTimers1.Enabled7 := false; iThreadTimers1.Enabled8 := false; iThreadTimers1.Enabled9 := false; if (m_ReceiveQueueThread <> nil) then begin // call the thread function to terminate m_ReceiveQueueThread.Terminate; // wait for the thread until it's finfished m_ReceiveQueueThread.WaitFor; // now destroy the object m_ReceiveQueueThread.Destroy; // set the object to nil m_ReceiveQueueThread := nil; end; if (m_hCanControl <> 0) then begin canControlClose(m_hCanControl); m_hCanControl := 0; end; // when a CAN channel was opened then close it now if (m_hCanChannel <> 0) then begin canChannelClose(m_hCanChannel); m_hCanChannel := 0; end; if (m_hCanChannelRex <> 0) then begin canChannelClose(m_hCanChannelRex); m_hCanChannelRex := 0; end; // when a device was opened the close it now if (m_hDeviceHandle <> 0) then begin vciDeviceClose(m_hDeviceHandle); m_hDeviceHandle := 0; end; end; function TFormMain.GetMyVersion: string; type TVerInfo = packed record Nevazhno: array[0..47] of byte; // ненужные нам 48 байт Minor, Major, Build, Release: word; // а тут версия end; var s: TResourceStream; v: TVerInfo; begin result := ''; try s := TResourceStream.Create(HInstance, '#1', RT_VERSION); // достаём ресурс if s.Size > 0 then begin s.Read(v, SizeOf(v)); // читаем нужные нам байты result := IntToStr(v.Major) + '.' + IntToStr(v.Minor); //+'.'+ // вот и версия... //IntToStr(v.Release); //+'.'+IntToStr(v.Build); end; s.Free; except; end; end; procedure TFormMain.FormShow(Sender: TObject); begin Caption := Caption + ' V ' + GetMyVersion; //***************Загрузка параметров************************** TimeWork := LoadParamFromIniFiles('Time', 'TimeWork', varInteger); iKnob1.Position := LoadParamFromIniFiles('Position', 'Speed', varDouble); iKnob2.Position := LoadParamFromIniFiles('Position', 'Tahometer', varDouble); iKnob3.Position := LoadParamFromIniFiles('Position', 'OilTemp', varDouble); iKnob5.Position := LoadParamFromIniFiles('Position', 'Brake1', varDouble); iKnob6.Position := LoadParamFromIniFiles('Position', 'Brake2', varDouble); iKnob7.Position := LoadParamFromIniFiles('Position', 'Brake3', varDouble); iKnob8.Position := LoadParamFromIniFiles('Position', 'Brake4', varDouble); isldr1.Position := LoadParamFromIniFiles('Position', 'OilPress', varDouble); isldr2.Position := LoadParamFromIniFiles('Position', 'OilLevel', varDouble); isldr3.Position := LoadParamFromIniFiles('Position', 'OhlLevel', varDouble); iSlider4.Position := LoadParamFromIniFiles('Position', 'KppOilTemp', varDouble); iSlider5.Position := LoadParamFromIniFiles('Position', 'FuelEkonomy', varDouble); iSlider6.Position := LoadParamFromIniFiles('Position', 'CatalystLevel', varDouble); iSlider7.Position := LoadParamFromIniFiles('Position', 'UreaLevel', varDouble); iSlider8.Position := LoadParamFromIniFiles('Position', 'BatteryPotential', varDouble); CheckBox3.Checked := LoadParamFromIniFiles('Enabled', 'Speed', varBoolean); chk3.Checked := LoadParamFromIniFiles('Enabled', 'EFL', varBoolean); CheckBox1.Checked := LoadParamFromIniFiles('Enabled', 'Tahometer', varBoolean); CheckBox2.Checked := LoadParamFromIniFiles('Enabled', 'OilTemp', varBoolean); CheckBox8.Checked := LoadParamFromIniFiles('Enabled', 'Probeg', varBoolean); CheckBox9.Checked := LoadParamFromIniFiles('Enabled', 'KppOilTemp', varBoolean); CheckBox4.Checked := LoadParamFromIniFiles('Enabled', 'AdBlueStatus', varBoolean); CheckBox12.Checked := LoadParamFromIniFiles('Enabled', 'WFI', varBoolean); CheckBox7.Checked := LoadParamFromIniFiles('Enabled', 'DP12', varBoolean); CheckBox11.Checked := LoadParamFromIniFiles('Enabled', 'FuelEkonomy', varBoolean); CheckBox6.Checked := LoadParamFromIniFiles('Enabled', 'EngineHours', varBoolean); CheckBox10.Checked := LoadParamFromIniFiles('Enabled', 'DateTime', varBoolean); CheckBox13.Checked := LoadParamFromIniFiles('Enabled', 'IdleOperation', varBoolean); CheckBox14.Checked := LoadParamFromIniFiles('Enabled', 'CatalystLevel', varBoolean); CheckBox15.Checked := LoadParamFromIniFiles('Enabled', 'UreaLevel', varBoolean); CheckBox16.Checked := LoadParamFromIniFiles('Enabled', 'FanDriveState', varBoolean); CheckBox17.Checked := LoadParamFromIniFiles('Enabled', 'StartLamp', varBoolean); CheckBox18.Checked := LoadParamFromIniFiles('Enabled', 'BatteryPotential', varBoolean); //-------------------------------------------------------------------- OilPres := Round(isldr1.Position * 100); OilLevel := Round(isldr2.Position); CoolantLevel := Round(isldr3.Position); iThreadTimers1.Enabled1 := true; iThreadTimers1.Enabled2 := true; iThreadTimers1.Enabled3 := true; iThreadTimers1.Enabled4 := true; iThreadTimers1.Enabled5 := true; iThreadTimers1.Enabled6 := true; iThreadTimers1.Enabled7 := true; iThreadTimers1.Enabled8 := true; iThreadTimers1.Enabled9 := true; end; (************************************************************************ ** ** Function : TFormMain.InitSocket ** Private Method ** ** Description : The interface will openended and all needed ** handles to open the CAN controller will be set. ** Then the CAN controller will be initialized, the ** filters set to accept all identifiers and the ** CAN controller will be started. ** Parameter : ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.InitSocket(); var hFuncResult: HResult; wRxFifoSize: Word; wRxThreshold: Word; wTxFifoSize: Word; wTxThreshold: Word; pCanCaps: CANCAPABILITIES; qwTimerTemp: Int64; errorText: string; begin errorText := 'InitSocket was succesful'; hFuncResult := canChannelOpen(m_hDeviceHandle, m_dwCanNo, FALSE, m_hCanChannel); if (hFuncResult = VCI_OK) then begin // device and CAN channel are now open, so initialize the CAN channel wRxFifoSize := 1024; wRxThreshold := 1; wTxFifoSize := 128; wTxThreshold := 1; hFuncResult := canChannelInitialize(m_hCanChannel, wRxFifoSize, wRxThreshold, wTxFifoSize, wTxThreshold); if (hFuncResult <> VCI_OK) then errorText := 'Error in canChannelInitialize'; end; if (hFuncResult = VCI_OK) then begin // device, CAN channel are open and initialized, // so activate now the CAN channel hFuncResult := canChannelActivate(m_hCanChannel, TRUE); if (hFuncResult <> VCI_OK) then errorText := 'Error in canChannelActivate'; end; if (hFuncResult = VCI_OK) then begin // the CAN channel is now activated, open now the CAN controller hFuncResult := canControlOpen(m_hDeviceHandle, m_dwCanNo, m_hCanControl); if (hFuncResult = VCI_OK) then begin stbBottom.Panels[1].Text := 'Ctrl: ' + IntToStr(m_dwCanNo + 1); hFuncResult := canControlGetCaps(m_hCanControl, pCanCaps); if (hFuncResult = VCI_OK) then begin // calulate the time resolution in 100 nSeconds qwTimerTemp := pCanCaps.dwTscDivisor * 10000000; m_dwTimerResolution := Round(qwTimerTemp / pCanCaps.dwClockFreq); end; end else begin errorText := 'Error in canControlOpen'; end; end; if (hFuncResult = VCI_OK) then begin // the CAN control is now open, initialize it now hFuncResult := canControlInitialize(m_hCanControl , CAN_OPMODE_EXTENDED or CAN_OPMODE_ERRFRAME , BitTimingReg0 , BitTimingReg1); if (hFuncResult = VCI_OK) then stbBottom.Panels[2].Text := BitTimingString else errorText := 'Error in canControlInitialize'; end; if (hFuncResult = VCI_OK) then begin // set the acceptance filter hFuncResult := canControlSetAccFilter(m_hCanControl , True , CAN_ACC_CODE_ALL , CAN_ACC_MASK_ALL); if (hFuncResult <> VCI_OK) then errorText := 'Error in canControlSetAccFilter'; end; if (hFuncResult = VCI_OK) then begin // start the CAN controller hFuncResult := canControlStart(m_hCanControl, TRUE); if (hFuncResult <> VCI_OK) then errorText := 'Error in canControlStart'; end; {if (m_hCanChannel <> 0) then begin // start the timer to look every 100 ms for data m_ReceiveQueueThread := TReceiveQueueThread.Create(m_hCanChannel); end;} if (hFuncResult <> VCI_OK) then ShowErrorMessage(errorText, hFuncResult); end; procedure TFormMain.InitSocketRec; var hFuncResult: HResult; wRxFifoSize: Word; wRxThreshold: Word; wTxFifoSize: Word; wTxThreshold: Word; pCanCaps: CANCAPABILITIES; qwTimerTemp: Int64; errorText: string; begin errorText := 'InitSocket was succesful'; hFuncResult := canChannelOpen(m_hDeviceHandle, m_dwCanNo, FALSE, m_hCanChannelRex); if (hFuncResult = VCI_OK) then begin // device and CAN channel are now open, so initialize the CAN channel wRxFifoSize := 1024; wRxThreshold := 1; wTxFifoSize := 128; wTxThreshold := 1; hFuncResult := canChannelInitialize(m_hCanChannelRex, wRxFifoSize, wRxThreshold, wTxFifoSize, wTxThreshold); if (hFuncResult <> VCI_OK) then errorText := 'Error in canChannelInitialize'; end; if (hFuncResult = VCI_OK) then begin // device, CAN channel are open and initialized, // so activate now the CAN channel hFuncResult := canChannelActivate(m_hCanChannelRex, TRUE); if (hFuncResult <> VCI_OK) then errorText := 'Error in canChannelActivate'; end; { if (hFuncResult = VCI_OK) then begin // the CAN channel is now activated, open now the CAN controller hFuncResult := canControlOpen(m_hDeviceHandle, m_dwCanNo, m_hCanControl); if (hFuncResult = VCI_OK) then begin stbBottom.Panels[1].Text := 'Ctrl: ' + IntToStr(m_dwCanNo + 1); hFuncResult := canControlGetCaps( m_hCanControl, pCanCaps); if (hFuncResult = VCI_OK) then begin // calulate the time resolution in 100 nSeconds qwTimerTemp := pCanCaps.dwTscDivisor * 10000000; m_dwTimerResolution := Round(qwTimerTemp / pCanCaps.dwClockFreq); end; end else begin errorText := 'Error in canControlOpen'; end; end; } if (m_hCanChannelRex <> 0) then begin // start the timer to look every 100 ms for data m_ReceiveQueueThread := TReceiveQueueThread.Create(m_hCanChannelRex); end; if (hFuncResult <> VCI_OK) then ShowErrorMessage(errorText, hFuncResult); end; procedure TFormMain.isldr1PositionChange(Sender: TObject); begin OilPres := Round(isldr1.Position * 100); Label1.Caption := 'Давление масла ' + IntToStr(OilPres) + ' kPa'; end; procedure TFormMain.isldr2PositionChange(Sender: TObject); begin OilLevel := Round(isldr2.Position); end; procedure TFormMain.isldr3PositionChange(Sender: TObject); begin CoolantLevel := Round(isldr3.Position); end; procedure TFormMain.iSwitchRocker2Change(Sender: TObject); begin iKnob1.Enabled := CheckBox4.Checked; end; procedure TFormMain.iThreadTimers1Timer1(Sender: TObject); var MSG_ID: CANMSG_ID; tempEngSpeed: Integer; data: CAN_DATA; begin if CheckBox1.Checked then begin SetLength(data, 8); with MSG_ID do begin priority := 3; PDUformat := $F0; PDUspecific := 4; end; tempEngSpeed := EngSpeed * 8; data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := tempEngSpeed and $FF; data[4] := (tempEngSpeed shr 8) and $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; end; procedure TFormMain.iThreadTimers1Timer2(Sender: TObject); var MSG_ID: CANMSG_ID; tempSpeed: Integer; data: CAN_DATA; begin if CheckBox3.Checked then begin SetLength(data, 8); with MSG_ID do begin priority := 3; PDUformat := $FE; PDUspecific := $6C; sourceAddr := $EE; end; tempSpeed := Speed * 256; data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := tempSpeed and $FF; data[7] := (tempSpeed shr 8) and $FF; SendCANMessage(MSG_ID, data); end; end; procedure TFormMain.iThreadTimers1Timer3(Sender: TObject); var MSG_ID: CANMSG_ID; temp: Integer; data: CAN_DATA; begin SetLength(data, 8); if CheckBox4.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $D9; end; data[0] := $FF; data[1] := $FF; data[2] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; case RadioGroup1.ItemIndex of 0: data[3] := $FC; 1: data[3] := $FC or $01; 2: data[3] := $FC or $02; 3: data[3] := $FF; end; SendCANMessage(MSG_ID, data); end; if CheckBox7.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FF; PDUspecific := $0C; end; data[0] := $FF; if RadioGroup3.ItemIndex = 0 then data[1] := $80 else data[1] := $00; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // LFE if CheckBox11.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $F2; sourceAddr := 0; end; temp := Round(iSlider5.Position * 20); data[0] := temp and $FF; data[1] := (temp shr 8) and $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // CCVS if CheckBox25.Checked then begin begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $F1; sourceAddr := Round(sCurrencyEdit4.Value); end; case rg1.ItemIndex of 0: data[0] := $F3; 1: data[0] := $F7; 2: data[0] := $FB; 3: data[0] := $FF; end; temp := Round(iSlider1.Position * 256); data[1] := temp and $FF; data[2] := (temp shr 8) and $FF; data[3] := $FF; case rg4.ItemIndex of 0: data[3] := data[3] and $FC; 1: data[3] := data[3] and $FD; 2: data[3] := data[3] and $FE; 3: data[3] := data[3] and $FF; end; data[4] := $FF; data[5] := $FF; data[6] := $FF; case RadioGroup20.ItemIndex of 0: data[6] := data[6] and $E0; 1: data[6] := data[6] and $E2; 2: data[6] := data[6] and $E1; 3: data[6] := data[6] and $E3; end; data[7] := $FF; SendCANMessage(MSG_ID, data); end; end; // ETC2 if CheckBox5.Checked then begin begin with MSG_ID do begin priority := 6; PDUformat := $F0; PDUspecific := $05; sourceAddr := 30; end; data[0] := $FF; data[1] := $FF; data[2] := $FF; case RadioGroup6.ItemIndex of 0: data[3] := 124; 1: data[3] := 125; 2: data[3] := 251; 3: data[3] := 126; 4: data[3] := 127; 5: data[3] := 128; 6: data[3] := 129; 7: data[3] := 130; 8: data[3] := 131; 9: data[3] := 132; 10: data[3] := 133; 11: data[3] := 134; 12: data[3] := 135; 13: data[3] := 136; 14: data[3] := 137; end; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; end; // EBC1 if chk14.Checked then begin begin with MSG_ID do begin priority := 6; PDUformat := $F0; PDUspecific := $01; sourceAddr := 11; end; data[0] := $FF; // SPN 561 case rg8.ItemIndex of 0: data[0] := data[0] and $FC; 1: data[0] := data[0] and $FD; 2: data[0] := data[0] and $FE; 3: data[0] := data[0] and $FF; end; // SPN 562 case rg9.ItemIndex of 0: data[0] := data[0] and $F3; 1: data[0] := data[0] and $F7; 2: data[0] := data[0] and $FB; 3: data[0] := data[0] and $FF; end; data[1] := $FF; data[2] := $FF; // SPN 575 case rg6.ItemIndex of 0: data[2] := data[2] and $FC; 1: data[2] := data[2] and $FD; 2: data[2] := data[2] and $FE; 3: data[2] := data[2] and $FF; end; // SPN 576 case RadioGroup21.ItemIndex of 0: data[2] := data[2] and $F3; 1: data[2] := data[2] and $F7; 2: data[2] := data[2] and $FB; 3: data[2] := data[2] and $FF; end; data[3] := $FF; data[4] := $FF; data[5] := $FF; // SPN 1439 case rg7.ItemIndex of 0: data[5] := data[5] and $F3; 1: data[5] := data[5] and $F7; 2: data[5] := data[5] and $FB; 3: data[5] := data[5] and $FF; end; // SPN 1438 case rg5.ItemIndex of 0: data[5] := data[5] and $CF; 1: data[5] := data[5] and $DF; 2: data[5] := data[5] and $EF; 3: data[5] := data[5] and $FF; end; data[6] := $FF; data[7] := $FF; // SPN 1792 case RadioGroup7.ItemIndex of 0: data[7] := data[7] and $3F; 1: data[7] := data[7] and $7F; 2: data[7] := data[7] and $BF; 3: data[7] := data[7] and $FF; end; SendCANMessage(MSG_ID, data); end; end; // LD if CheckBox28.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $40; sourceAddr := 30; end; data[0] := $FF; case RadioGroup14.ItemIndex of 0: data[0] := data[0] and $3F; 1: data[0] := data[0] and $7F; end; data[1] := $FF; case RadioGroup11.ItemIndex of 0: data[1] := data[1] and $CF; 1: data[1] := data[1] and $DF; end; case RadioGroup12.ItemIndex of 0: data[1] := data[1] and $3F; 1: data[1] := data[1] and $7F; end; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; case RadioGroup13.ItemIndex of 0: data[7] := data[7] and $FC; 1: data[7] := data[7] and $FD; end; SendCANMessage(MSG_ID, data); end; // AUXIO1 if CheckBox30.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $D9; sourceAddr := 30; end; data[0] := $FF; case RadioGroup22.ItemIndex of 0: data[0] := data[0] and $FC; 1: data[0] := data[0] and $FD; end; case RadioGroup24.ItemIndex of 0: data[0] := data[0] and $F3; 1: data[0] := data[0] and $F7; end; case RadioGroup27.ItemIndex of 0: data[0] := data[0] and $CF; 1: data[0] := data[0] and $DF; end; case RadioGroup26.ItemIndex of 0: data[0] := data[0] and $3F; 1: data[0] := data[0] and $7F; end; data[1] := $FF; case RadioGroup32.ItemIndex of 0: data[1] := data[1] and $FC; 1: data[1] := data[1] and $FD; end; case RadioGroup30.ItemIndex of 0: data[1] := data[1] and $F3; 1: data[1] := data[1] and $F7; end; case RadioGroup28.ItemIndex of 0: data[1] := data[1] and $3F; 1: data[1] := data[1] and $7F; end; data[2] := $FF; case RadioGroup23.ItemIndex of 0: data[2] := data[2] and $F3; 1: data[2] := data[2] and $F7; end; case RadioGroup29.ItemIndex of 0: data[2] := data[2] and $CF; 1: data[2] := data[2] and $DF; end; case RadioGroup31.ItemIndex of 0: data[2] := data[2] and $3F; 1: data[2] := data[2] and $7F; end; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // ASC1 if CheckBox33.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $5A; sourceAddr := 47; end; data[0] := $FF; case RadioGroup34.ItemIndex of 0: data[0] := data[0] and $11; 1: data[0] := data[0] and $00; end; data[1] := $FF; data[2] := $FF; data[3] := $FF; case RadioGroup35.ItemIndex of 0: data[3] := data[3] and $0F; 1: data[3] := data[3] and $EF; end; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // ERC1 if CheckBox26.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $F0; PDUspecific := $00; sourceAddr := 0; end; data[0] := $FF; data[1] := Round(iSlider9.Position + 125); data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; end; procedure TFormMain.iThreadTimers1Timer4(Sender: TObject); begin if shaBusOff.Brush.Color = clRed then sBitBtn3Click(Self); end; procedure TFormMain.iThreadTimers1Timer5(Sender: TObject); var MSG_ID: CANMSG_ID; tempOilPres: Integer; data: CAN_DATA; begin SetLength(data, 8); if chk3.Checked then begin with MSG_ID do begin priority := 6; PDUformat := 254; PDUspecific := 239; end; tempOilPres := Round(OilPres / 4); data[0] := $FF; data[1] := $FF; data[2] := Round(OilLevel / 0.4); data[3] := tempOilPres; data[4] := $FF; data[5] := $FF; data[6] := 0; data[7] := Round(CoolantLevel / 0.4); SendCANMessage(MSG_ID, data); end; if CheckBox24.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FF; PDUspecific := $47; sourceAddr := 0; end; data[0] := $FF; case RadioGroup8.ItemIndex of 0: data[0] := data[0] and $3F; 1: data[0] := data[0] and $7F; end; case RadioGroup9.ItemIndex of 0: data[0] := data[0] and $F3; 1: data[0] := data[0] and $F7; end; data[1] := $FF; case RadioGroup10.ItemIndex of 0: data[1] := data[1] and $CF; 1: data[1] := data[1] and $DF; end; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // EAC1 if CheckBox29.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $F0; PDUspecific := $06; sourceAddr := 21; end; data[0] := $FF; data[1] := $FF; case RadioGroup17.ItemIndex of 0: data[1] := data[1] and $CF; 1: data[1] := data[1] and $DF; end; case RadioGroup18.ItemIndex of 0: data[1] := data[1] and $3F; 1: data[1] := data[1] and $7F; end; data[2] := $FF; case RadioGroup19.ItemIndex of 0: data[2] := data[2] and $FC; 1: data[2] := data[2] and $FD; end; case RadioGroup15.ItemIndex of 0: data[2] := data[2] and $F3; 1: data[2] := data[2] and $F7; end; case RadioGroup16.ItemIndex of 0: data[2] := data[2] and $CF; 1: data[2] := data[2] and $DF; end; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // TC2DIS if CheckBox31.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FF; PDUspecific := $85; sourceAddr := 3; end; data[0] := $FF; case RadioGroup25.ItemIndex of 0: data[0] := data[0] and $F3; 1: data[0] := data[0] and $F7; end; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // IC1 if CheckBox35.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $F6; sourceAddr := 0; end; data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := Round(iSlider3.Position/0.05); data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // ETC5 if CheckBox36.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $C3; sourceAddr := 3; end; data[0] := $FF; case RadioGroup36.ItemIndex of 0: data[0] := data[0] and $F3; 1: data[0] := data[0] and $F7 end; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; end; procedure TFormMain.iThreadTimers1Timer6(Sender: TObject); var MSG_ID: CANMSG_ID; tempEngSpeed: Integer; data: CAN_DATA; msec, sec, min, hour, minGr, hourGr, Day, Month, Year: Word; probeg: Integer; temp: Integer; y: TSystemTime; timeGr: TDateTime; spn, fmi, oc: word; begin SetLength(data, 8); if chk2.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $FC; sourceAddr := 30; end; data[0] := $FF; data[1] := Round(iKnob4.Position * 2.5); data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox2.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $EE; sourceAddr := 0; end; data[0] := CoolantTemp; data[1] := $FF; data[2] := $FF; data[3] := 0; data[4] := 0; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if chk1.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $AE; sourceAddr := 48; end; data[0] := $FF; data[1] := Round(iKnob7.Position * 12.5); data[2] := Round(iKnob5.Position * 12.5); data[3] := Round(iKnob6.Position * 12.5); data[4] := Round(iKnob8.Position * 12.5); data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox10.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $E6; end; GetSystemTime(y); timeGr := SystemTimeToDateTime(y); DecodeTime(Time, hour, min, sec, msec); DecodeTime(timeGr, hourGr, minGr, sec, msec); DecodeDate(timeGr, Year, Month, Day); data[0] := sec * 4; data[1] := minGr; data[2] := hourGr; data[3] := Month; data[4] := Day; data[5] := Year - 1985; data[6] := 125 + min - minGr; data[7] := 125 + hour - hourGr; SendCANMessage(MSG_ID, data); end; if CheckBox8.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $C1; sourceAddr := $EE; end; probeg := Round((sDecimalSpinEdit1.Value * 1000) / 5); data[0] := probeg and $FF; data[1] := (probeg shr 8) and $FF; data[2] := (probeg shr 16) and $FF; data[3] := (probeg shr 24) and $FF; probeg := Round((sDecimalSpinEdit2.Value * 1000) / 5); data[4] := probeg and $FF; data[5] := (probeg shr 8) and $FF; data[6] := (probeg shr 16) and $FF; data[7] := (probeg shr 24) and $FF; SendCANMessage(MSG_ID, data); end; if CheckBox9.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $F8; sourceAddr := 3; end; temp := Round((iSlider4.Position + 273) * 32); data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := temp and $FF; data[5] := (temp shr 8) and $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox6.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $E5; end; probeg := Round((sDecimalSpinEdit3.Value * 100) / 5); data[0] := probeg and $FF; data[1] := (probeg shr 8) and $FF; data[2] := (probeg shr 16) and $FF; data[3] := (probeg shr 24) and $FF; probeg := Round(sDecimalSpinEdit4.Value); data[4] := probeg and $FF; data[5] := (probeg shr 8) and $FF; data[6] := (probeg shr 16) and $FF; data[7] := (probeg shr 24) and $FF; SendCANMessage(MSG_ID, data); end; if CheckBox13.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $DC; end; probeg := Round((sDecimalSpinEdit5.Value * 100) / 5); data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := probeg and $FF; data[5] := (probeg shr 8) and $FF; data[6] := (probeg shr 16) and $FF; data[7] := (probeg shr 24) and $FF; SendCANMessage(MSG_ID, data); end; if CheckBox14.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $56; sourceAddr := 0; end; data[0] := Round(iSlider6.Position * 2.5); data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox15.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FF; PDUspecific := $F0; end; data[0] := $FF; data[1] := $FF; data[2] := Round(iSlider7.Position); data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox16.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $BD; sourceAddr := 0; end; data[0] := $FF; case RadioGroup4.ItemIndex of 0: data[1] := $F0; 1: data[1] := $F9; end; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox17.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $E4; end; data[0] := $FF; data[1] := $FF; data[2] := $FF; if RadioGroup5.ItemIndex = 0 then data[3] := $FD else data[3] := $FC; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox18.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $F7; end; temp := Round(iSlider8.Position * 20); data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := temp and $FF; data[5] := (temp shr 8) and $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox27.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $E9; end; probeg := Round(sDecimalSpinEdit7.Value * 2); data[0] := probeg and $FF; data[1] := (probeg shr 8) and $FF; data[2] := (probeg shr 16) and $FF; data[3] := (probeg shr 24) and $FF; probeg := Round(sDecimalSpinEdit6.Value * 2); data[4] := probeg and $FF; data[5] := (probeg shr 8) and $FF; data[6] := (probeg shr 16) and $FF; data[7] := (probeg shr 24) and $FF; SendCANMessage(MSG_ID, data); end; // SHUTDN if CheckBox32.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $E4; sourceAddr := 0; end; data[0] := $FF; data[1] := $FF; data[2] := $FF; data[3] := $FF; case RadioGroup33.ItemIndex of 0: data[3] := data[3] and $FC; 1: data[3] := data[3] and $FD; end; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; if CheckBox19.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $CA; case sComboBox1.ItemIndex of 0: sourceAddr := $00; 1: sourceAddr := $03; 2: sourceAddr := 30; 3: sourceAddr := 61; end; end; data[0] := $0; if CheckBox20.Checked then data[0] := data[0] or $40; if CheckBox21.Checked then data[0] := data[0] or $10; if CheckBox22.Checked then data[0] := data[0] or $04; if CheckBox23.Checked then data[0] := data[0] or $01; data[1] := $FF; try spn := StrToInt(sCurrencyEdit1.Text); finally end; data[2] := spn and $FF; spn := spn shr 8; data[3] := spn and $FF; spn := spn shr 8; data[4] := (spn shl 5) and $FF; try fmi := StrToInt(sCurrencyEdit2.Text); finally end; fmi := fmi and $1F; data[4] := data[4] or fmi; try data[5] := StrToInt(sCurrencyEdit3.Text); finally end; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; // EBC4 if CheckBox37.Checked then begin with MSG_ID do begin priority := 6; PDUformat := $FE; PDUspecific := $AC; sourceAddr := 11; end; data[0] := Round(iSlider10.Position*2.5); data[1] := Round(iSlider11.Position*2.5);; data[2] := Round(iSlider12.Position*2.5);; data[3] := Round(iSlider13.Position*2.5);; data[4] := Round(iSlider14.Position*2.5);; data[5] := Round(iSlider15.Position*2.5);; data[6] := Round(iSlider16.Position*2.5);; data[7] := Round(iSlider17.Position*2.5);; SendCANMessage(MSG_ID, data); end; end; procedure TFormMain.iThreadTimers1Timer7(Sender: TObject); var MSG_ID: CANMSG_ID; tempEngSpeed: Integer; data: CAN_DATA; begin if CheckBox12.Checked then begin SetLength(data, 8); with MSG_ID do begin priority := 3; PDUformat := $FE; PDUspecific := $FF; end; if RadioGroup2.ItemIndex = 0 then data[0] := $FC else data[0] := $FD; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := $FF; SendCANMessage(MSG_ID, data); end; end; procedure TFormMain.iThreadTimers1Timer8(Sender: TObject); begin SaveParamToIniFiles('Time', 'TimeWork', TimeWork); end; procedure TFormMain.iThreadTimers1Timer9(Sender: TObject); begin Inc(TimeWork); sTimePicker1.Time := TimeWork / 86400; //60*60*24 end; procedure TFormMain.Reset1Click(Sender: TObject); begin sBitBtn3Click(Self); end; (************************************************************************ ** ** Function : TFormMain.ShowCANMessage ** Private Method ** ** Description : Callback function for the receive thread. ** Must be called in a Synchronize function because ** here will be some GUI controls filled with data. ** Parameter : sCanMsg - the CAN message to show ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.SaveOptions; begin SaveParamToIniFiles('Time', 'TimeWork', TimeWork); SaveParamToIniFiles('Position', 'Speed', iKnob1.Position); SaveParamToIniFiles('Position', 'Tahometer', iKnob2.Position); SaveParamToIniFiles('Position', 'OilTemp', iKnob3.Position); SaveParamToIniFiles('Position', 'Brake1', iKnob5.Position); SaveParamToIniFiles('Position', 'Brake2', iKnob6.Position); SaveParamToIniFiles('Position', 'Brake3', iKnob7.Position); SaveParamToIniFiles('Position', 'Brake4', iKnob8.Position); SaveParamToIniFiles('Position', 'OilPress', isldr1.Position); SaveParamToIniFiles('Position', 'OilLevel', isldr2.Position); SaveParamToIniFiles('Position', 'OhlLevel', isldr3.Position); SaveParamToIniFiles('Position', 'KppOilTemp', iSlider4.Position); SaveParamToIniFiles('Position', 'FuelEkonomy', iSlider5.Position); SaveParamToIniFiles('Position', 'CatalystLevel', iSlider6.Position); SaveParamToIniFiles('Position', 'UreaLevel', iSlider7.Position); SaveParamToIniFiles('Position', 'BatteryPotential', iSlider8.Position); SaveParamToIniFiles('Enabled', 'Speed', CheckBox3.Checked); SaveParamToIniFiles('Enabled', 'EFL', chk3.Checked); SaveParamToIniFiles('Enabled', 'Tahometer', CheckBox1.Checked); SaveParamToIniFiles('Enabled', 'OilTemp', CheckBox2.Checked); SaveParamToIniFiles('Enabled', 'Probeg', CheckBox8.Checked); SaveParamToIniFiles('Enabled', 'KppOilTemp', CheckBox9.Checked); SaveParamToIniFiles('Enabled', 'AdBlueStatus', CheckBox4.Checked); SaveParamToIniFiles('Enabled', 'WFI', CheckBox12.Checked); SaveParamToIniFiles('Enabled', 'DP12', CheckBox7.Checked); SaveParamToIniFiles('Enabled', 'FuelEkonomy', CheckBox11.Checked); SaveParamToIniFiles('Enabled', 'EngineHours', CheckBox6.Checked); SaveParamToIniFiles('Enabled', 'DateTime', CheckBox10.Checked); SaveParamToIniFiles('Enabled', 'IdleOperation', CheckBox13.Checked); SaveParamToIniFiles('Enabled', 'CatalystLevel', CheckBox14.Checked); SaveParamToIniFiles('Enabled', 'UreaLevel', CheckBox15.Checked); SaveParamToIniFiles('Enabled', 'FanDriveState', CheckBox16.Checked); SaveParamToIniFiles('Enabled', 'StartLamp', CheckBox17.Checked); SaveParamToIniFiles('Enabled', 'BatteryPotential', CheckBox18.Checked); end; procedure TFormMain.sBitBtn1Click(Sender: TObject); begin SaveOptions; end; procedure TFormMain.sBitBtn2Click(Sender: TObject); begin TimeWork := 0; end; procedure TFormMain.sBitBtn3Click(Sender: TObject); begin stbBottom.Panels[3].Text := 'Выполняется перезагрузка USB_to_CAN'; Application.ProcessMessages; FormDestroy(self); FormCreate(self); iThreadTimers1.Enabled1 := true; iThreadTimers1.Enabled2 := true; iThreadTimers1.Enabled3 := true; iThreadTimers1.Enabled4 := true; iThreadTimers1.Enabled5 := true; iThreadTimers1.Enabled6 := true; iThreadTimers1.Enabled7 := true; iThreadTimers1.Enabled8 := true; iThreadTimers1.Enabled9 := true; stbBottom.Panels[3].Text := ''; Application.ProcessMessages; end; procedure TFormMain.SendCANMessage(MSG_ID: CANMSG_ID; data: CAN_DATA); var sMsgToSend: CANMSG; hFuncResult: HResult; szResultText: PChar; i: Integer; begin with MSG_ID do begin r := 0; dp := 0; //sourceAddr := $00; sMsgToSend.dwMsgId := Integer(sourceAddr) or (Integer(PDUspecific) shl 8) or (Integer(PDUformat) shl 16) or (Integer(dp) shl 24) or (Integer(r) shl 25) or (Integer(priority) shl 26) end; for i := 1 to 8 do sMsgToSend.abData[i] := data[i - 1]; sMsgToSend.dwTime := 0; sMsgToSend.uMsgInfo.bType := CAN_MSGTYPE_DATA; sMsgToSend.uMsgInfo.bRes := 0; sMsgToSend.uMsgInfo.bAfc := 0; // DLC = 8 data bytes sMsgToSend.uMsgInfo.bFlags := 8; // a sample to send a extended (29 bit) CAN message sMsgToSend.uMsgInfo.bFlags := sMsgToSend.uMsgInfo.bFlags or CAN_MSGFLAGS_EXT; if (m_hCanChannel <> 0) then begin hFuncResult := canChannelPostMessage(m_hCanChannel, sMsgToSend); szResultText := StrAlloc(255); vciFormatError(hFuncResult, szResultText, 255); lblTxResult.Caption := szResultText; StrDispose(szResultText); end else lblTxResult.Caption := 'No CAN channel open'; end; procedure TFormMain.ShowCANMessage(sCanMsg: CANMSG); var time: Double; MSG_ID: CANMSG_ID; data: CAN_DATA; i: integer; temper_pcb: Real; Item: TListItem; strData: string; lenData: Integer; temp: Integer; begin // every timetick has 100 nano seconds time := sCanMsg.dwTime * m_dwTimerResolution + m_qwOverrunValue; // we want to show the time in milli seconds // so divide with 10.000 time := time / 10000 / 1000; // show the time stamp in the edit field lblMsgData.Caption := FloatToStr(time); // check what kind of CAN message if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_DATA) then ShowDataFrame(sCanMsg) else if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_INFO) then ShowInfoFrame(sCanMsg) else if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_ERROR) then ShowErrorFrame(sCanMsg) else if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_STATUS) then ShowStatusFrame(sCanMsg) else if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_WAKEUP) then ShowWakeUpFrame(sCanMsg) else if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_TIMEOVR) then HandleTimerOverrunFrame(sCanMsg) else if (sCanMsg.uMsgInfo.bType = CAN_MSGTYPE_TIMERST) then HandleTimerResetFrame(sCanMsg); MSG_ID.sourceAddr := byte(sCanMsg.dwMsgId and $000000FF); MSG_ID.PDUspecific := byte((sCanMsg.dwMsgId and $0000FF00) shr 8); MSG_ID.PDUformat := byte((sCanMsg.dwMsgId and $00FF0000) shr 16); SetLength(data, 8); lenData := sCanMsg.uMsgInfo.bFlags and $0F; for i := 0 to lenData - 1 do begin data[i] := sCanMsg.abData[i + 1]; strData := strData + IntToHex(data[i], 2) + ' '; end; case MSG_ID.PDUformat of $EA: begin case MSG_ID.PDUspecific of $FF: begin if ((data[0] = $8C) and (data[1] = $FE)) then begin // AAI if CheckBox34.Checked then begin with MSG_ID do begin priority := 3; PDUformat := $FE; PDUspecific := $8C; sourceAddr := 30; end; temp := Round(iSlider2.Position); data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := temp and $FF; data[5] := (temp shr 8) and $FF; data[6] := $FF; data[7] := $FF; data[8] := $FF; SendCANMessage(MSG_ID, data); end; end; end; end; end; end; end; (************************************************************************ ** ** Function : TFormMain.ShowDataFrame ** Private Method ** ** Description : Show the data of a normal CAN dataframe. ** Check the CAN mode and if it is a remote request. ** Parameter : sCanMsg - the CAN message to show ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.ShowDataFrame(sCanMsg: CANMSG); var i: longint; dlc: Byte; data: string; begin if (sCanMsg.uMsgInfo.bFlags and CAN_MSGFLAGS_EXT = CAN_MSGFLAGS_EXT) then lblMsgData.Caption := lblMsgData.Caption + ' Extended ' else lblMsgData.Caption := lblMsgData.Caption + ' Standard '; lblMsgData.Caption := lblMsgData.Caption + ' ID:' + IntToHex(sCanMsg.dwMsgId, 2); data := ''; dlc := sCanMsg.uMsgInfo.bFlags and CAN_MSGFLAGS_DLC; if (sCanMsg.uMsgInfo.bFlags and CAN_MSGFLAGS_RTR = CAN_MSGFLAGS_RTR) then begin // it's a remote request frame lblLastRxMsgType.Caption := 'Remote frame'; lblMsgData.Caption := lblMsgData.Caption + ' RTR Length: ' + IntToStr(dlc); end else begin lblLastRxMsgType.Caption := 'Data Frame'; lblMsgData.Caption := lblMsgData.Caption + 'h Data(hex): '; // it's a normal frame with data for i := 1 to dlc do data := data + IntToHex(sCanMsg.abData[i], 2) + ' '; lblMsgData.Caption := lblMsgData.Caption + ' ' + data; end; end; (************************************************************************ ** ** Function : TFormMain.ShowInfoFrame ** Private Method ** ** Description : Show a information frame. ** Parameter : sCanMsg - the CAN message to show ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.ShowInfoFrame(sCanMsg: CANMSG); begin lblLastRxMsgType.Caption := 'Info Frame'; case sCanMsg.abData[1] of CAN_INFO_START: // start of CAN controller lblMsgData.Caption := 'Start Controller'; CAN_INFO_STOP: // stop of CAN controller lblMsgData.Caption := 'Stop Controller'; CAN_INFO_RESET: // reset of CAN controller lblMsgData.Caption := 'Reset Controller'; end; end; (************************************************************************ ** ** Function : TFormMain.ShowErrorFrame ** Private Method ** ** Description : Show a error frame. ** Parameter : sCanMsg - the CAN message to show ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.ShowErrorFrame(sCanMsg: CANMSG); begin lblLastRxMsgType.Caption := 'Error Frame'; case sCanMsg.abData[1] of CAN_ERROR_STUFF: // stuff error lblMsgData.Caption := 'Stuff Error'; CAN_ERROR_FORM: // form error lblMsgData.Caption := 'Form Error'; CAN_ERROR_ACK: // acknowledgment error lblMsgData.Caption := 'Acknowledgment Error'; CAN_ERROR_BIT: // bit error lblMsgData.Caption := 'Bit Error'; CAN_ERROR_CRC: // CRC error lblMsgData.Caption := 'CRC Error'; CAN_ERROR_OTHER: // other (unspecified) error lblMsgData.Caption := 'Other Error'; else lblMsgData.Caption := 'Unknown Error'; end; end; (************************************************************************ ** ** Function : TFormMain.ShowStatusFrame ** Private Method ** ** Description : Show a status frame. ** Parameter : sCanMsg - the CAN message to show ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.ShowStatusFrame(sCanMsg: CANMSG); begin lblLastRxMsgType.Caption := 'Status Frame'; lblMsgData.Caption := 'Data byte 1: ' + IntToHex(sCanMsg.abData[1], 2); end; (************************************************************************ ** ** Function : TFormMain.ShowWakeUpFrame ** Private Method ** ** Description : Show a wakeup frame. ** Parameter : sCanMsg - the CAN message to show ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.ShowWakeUpFrame(sCanMsg: CANMSG); begin lblLastRxMsgType.Caption := 'WakeUp Frame'; end; procedure TFormMain.Timer50_msTimer(Sender: TObject); var MSG_ID: CANMSG_ID; tempSpeed: Integer; tempEngSpeed: Integer; data: CAN_DATA; begin SetLength(data, 8); with MSG_ID do begin priority := 3; PDUformat := $FE; PDUspecific := $6C; end; tempSpeed := Speed * 256; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := $FF; data[5] := $FF; data[6] := $FF; data[7] := tempSpeed and $FF; data[8] := (tempSpeed shr 8) and $FF; SendCANMessage(MSG_ID, data); { unsigned int engSpeed = 0; if (this->EngSpeed->Text!="") engSpeed = (unsigned int)(StrToFloat(this->EngSpeed->Text)/0.125f); msg.priority = 3; msg.PDUformat = 240; msg.PDUspecific = 4; msg.dataLen = 8; msg.data[0] = 0xFF; msg.data[1] = 0xFF; msg.data[2] = 0xFF; msg.data[3] = engSpeed &0xFF; msg.data[4] = (engSpeed>>8)&0xFF; msg.data[5] = 0xFF; msg.data[6] = 0xFF; msg.data[7] = 0xFF;} with MSG_ID do begin priority := 3; PDUformat := 240; PDUspecific := 4; end; tempEngSpeed := EngSpeed * 8; data[1] := $FF; data[2] := $FF; data[3] := $FF; data[4] := tempEngSpeed and $FF; data[5] := (tempEngSpeed shr 8) and $FF; data[6] := $FF; data[7] := $FF; data[8] := $FF; SendCANMessage(MSG_ID, data); end; (************************************************************************ ** ** Function : TFormMain.HandleTimerOverrunFrame ** Private Method ** ** Description : Show and handle a timeoverrun frame. ** Parameter : sCanMsg - the CAN message to use ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.HandleTimerOverrunFrame(sCanMsg: CANMSG); begin lblLastRxMsgType.Caption := 'Timer Overrun'; m_dwTimerOverruns := m_dwTimerOverruns + sCanMsg.dwMsgId; // the overruns can be set to the upper 32 bits of the int64 m_qwOverrunValue := Int64(m_dwTimerOverruns) shl 32; end; (************************************************************************ ** ** Function : TFormMain.HandleTimerResetFrame ** Private Method ** ** Description : Show and handle a timerreset frame. ** Parameter : sCanMsg - the CAN message to use ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.HandleTimerResetFrame(sCanMsg: CANMSG); begin lblLastRxMsgType.Caption := 'Timer Reset'; m_dwTimerOverruns := 0; m_qwOverrunValue := 0; end; procedure TFormMain.iKnob1PositionChange(Sender: TObject); begin iAnalogDisplay1.Value := iKnob1.Position; Speed := Round(iKnob1.Position); end; procedure TFormMain.iKnob2PositionChange(Sender: TObject); begin EngSpeed := Round(iKnob2.Position * 100); iAnalogDisplay2.Value := EngSpeed; end; procedure TFormMain.iKnob3PositionChange(Sender: TObject); begin CoolantTemp := Round(iKnob3.Position) + 40; end; (************************************************************************ ** ** Function : TFormMain.TimerUpdateInfoTimer ** Delphi Message Handler ** ** Description : Called periodically from the timer and show the ** current CAN controller state in some symbolize LEDs ** Parameter : sender - the calling object ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.tmrUpdateInfoTimer(Sender: TObject); var hFuncResult: HResult; pStatus: CANLINESTATUS; fIsDataAvailable: boolean; begin fIsDataAvailable := false; if (m_hCanControl <> 0) then begin hFuncResult := canControlGetStatus(m_hCanControl, pStatus); if (hFuncResult = VCI_OK) then begin fIsDataAvailable := true; if (pStatus.dwStatus and CAN_STATUS_ININIT = CAN_STATUS_ININIT) then shaCtrlInit.Brush.Color := clRed else shaCtrlInit.Brush.Color := clLime; if (pStatus.dwStatus and CAN_STATUS_TXPEND = CAN_STATUS_TXPEND) then shaTxPending.Brush.Color := clRed else shaTxPending.Brush.Color := clLime; if (pStatus.dwStatus and CAN_STATUS_OVRRUN = CAN_STATUS_OVRRUN) then shaDataOverrun.Brush.Color := clRed else shaDataOverrun.Brush.Color := clLime; if (pStatus.dwStatus and CAN_STATUS_ERRLIM = CAN_STATUS_ERRLIM) then shaWarningLevel.Brush.Color := clRed else shaWarningLevel.Brush.Color := clLime; if (pStatus.dwStatus and CAN_STATUS_BUSOFF = CAN_STATUS_BUSOFF) then shaBusOff.Brush.Color := clRed else shaBusOff.Brush.Color := clLime; end; end; if (not fIsDataAvailable) then begin shaCtrlInit.Brush.Color := clBtnFace; shaTxPending.Brush.Color := clBtnFace; shaDataOverrun.Brush.Color := clBtnFace; shaWarningLevel.Brush.Color := clBtnFace; shaBusOff.Brush.Color := clBtnFace; end; end; procedure TFormMain.ts1ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); begin end; (************************************************************************ ** ** Function : TFormMain.ButtonTransmitClick ** Delphi Message Handler ** ** Description : Called when the user press the Transmit ID button. ** Following CAN message will be send one time: ** ID=100, frame format = standard, ** Data = 1 2 3 4 5 6 7 8 ** Parameter : sender - the calling object ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.Abaut1Click(Sender: TObject); begin AboutBox.ShowModal; end; procedure TFormMain.btnTransmitClick(Sender: TObject); var hFuncResult: HResult; sMsgToSend: CANMSG; sIdMsg: CANMSG_ID; iData: integer; szResultText: PChar; begin with sIdMsg do begin priority := 3; r := 0; dp := 0; PDUformat := 40; PDUspecific := 128; sourceAddr := 0; sMsgToSend.dwMsgId := Integer(sourceAddr) or (Integer(PDUspecific) shl 8) or (Integer(PDUformat) shl 16) or (Integer(dp) shl 24) or (Integer(r) shl 25) or (Integer(priority) shl 26) end; for iData := 1 to 8 do sMsgToSend.abData[iData] := iData; sMsgToSend.dwTime := 0; sMsgToSend.uMsgInfo.bType := CAN_MSGTYPE_DATA; sMsgToSend.uMsgInfo.bRes := 0; sMsgToSend.uMsgInfo.bAfc := 0; // DLC = 8 data bytes sMsgToSend.uMsgInfo.bFlags := 8; // add the self reception flag //sMsgToSend.uMsgInfo.bFlags := sMsgToSend.uMsgInfo.bFlags or CAN_MSGFLAGS_SRR; // a sample to send a extended (29 bit) CAN message sMsgToSend.uMsgInfo.bFlags := sMsgToSend.uMsgInfo.bFlags or CAN_MSGFLAGS_EXT; if (m_hCanChannel <> 0) then begin hFuncResult := canChannelPostMessage(m_hCanChannel, sMsgToSend); szResultText := StrAlloc(255); vciFormatError(hFuncResult, szResultText, 255); lblTxResult.Caption := szResultText; StrDispose(szResultText); end else lblTxResult.Caption := 'No CAN channel open'; end; (************************************************************************ ** ** Function : TFormMain.ShowErrorMessage ** Private Method ** ** Description : Show messagebox with the error text ** Parameter : errorText - additiobnal error text ** hFuncResult - a HResult to get the error text from ** the VCI ** ** Returnvalues : - ** ************************************************************************) procedure TFormMain.ShowErrorMessage(errorText: string; hFuncResult: HResult); var szErrorText: PChar; begin if (hFuncResult <> 0) then begin szErrorText := StrAlloc(255); vciFormatError(hFuncResult, szErrorText, 255); ShowMessage(errorText + ' : ' + szErrorText); StrDispose(szErrorText); end else ShowMessage(errorText); end; end.
unit KeyBoardAndDebuggin; interface uses ToolsApi, System.Classes, Vcl.Menus, SysUtils, Windows; type TDebuggingOTAExample = class(TNotifierObject, IOTAWizard) private procedure Execute; function GetIDString: string; function GetName: string; function GetState: TWizardState; public constructor Create; destructor Destroy; override; end; TKeyboardOTABinding = class(TNotifierObject, IOTAKeyboardBinding) private Procedure AddBreakpoint(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices); function GetBindingType: TBindingType; function GetDisplayName: string; function GetName: string; function SourceEditor(Module: IOTAModule): IOTASourceEditor; public end; procedure Register; Function InitialiseWizard(BIDES: IBorlandIDEServices): TDebuggingOTAExample; implementation { TKeyboardBinding } uses Vcl.Forms; Var iWizardIndex: Integer = 0; iKeyBindingIndex: Integer = 0; procedure Register; begin iWizardIndex := (BorlandIDEServices As IOTAWizardServices) .AddWizard(TDebuggingOTAExample.Create); //Application.Handle := (BorlandIDEServices As IOTAServices).GetParentHandle; iKeyBindingIndex := (BorlandIDEServices As IOTAKeyboardServices) .AddKeyboardBinding(TKeyboardOTABinding.Create); end; Function InitialiseWizard(BIDES: IBorlandIDEServices): TDebuggingOTAExample; begin Result := TDebuggingOTAExample.Create; end; Function TKeyboardOTABinding.SourceEditor(Module: IOTAModule): IOTASourceEditor; Var iFileCount: Integer; i: Integer; Begin Result := Nil; If Module = Nil Then Exit; With Module Do Begin iFileCount := GetModuleFileCount; For i := 0 To iFileCount - 1 Do If GetModuleFileEditor(i).QueryInterface(IOTASourceEditor, Result) = S_OK Then Break; End; End; procedure TKeyboardOTABinding.AddBreakpoint(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); var i: Integer; DS: IOTADebuggerServices; MS: IOTAModuleServices; strFileName: String; Source: IOTASourceEditor; CP: TOTAEditPos; BP: IOTABreakpoint; begin MS := BorlandIDEServices As IOTAModuleServices; Source := SourceEditor(MS.CurrentModule); strFileName := Source.FileName; CP := Source.EditViews[0].CursorPos; DS := BorlandIDEServices As IOTADebuggerServices; BP := nil; for i := 0 to DS.SourceBkptCount - 1 do begin if (DS.SourceBkpts[i].LineNumber = CP.Line) and (AnsiCompareFileName(DS.SourceBkpts[0].FileName, strFileName) = 0) then BP := DS.SourceBkpts[i]; end; if not Assigned(BP) then BP := DS.NewSourceBreakpoint(strFileName, CP.Line, nil); If KeyCode = TextToShortCut('Ctrl+Shift+F8') Then BP.Edit(True) Else If KeyCode = TextToShortCut('Ctrl+Alt+F8') Then BP.Enabled := Not BP.Enabled; BindingResult := krHandled; end; procedure TKeyboardOTABinding.BindKeyboard(const BindingServices : IOTAKeyBindingServices); begin BindingServices.AddKeyBinding([TextToShortCut('Ctrl+Shift+F8')], AddBreakpoint, nil); BindingServices.AddKeyBinding([TextToShortCut('Ctrl+Alt+F8')], AddBreakpoint, Nil); end; function TKeyboardOTABinding.GetBindingType: TBindingType; begin Result := btPartial; end; function TKeyboardOTABinding.GetDisplayName: string; begin Result := 'Debugging Tools Bindings'; end; function TKeyboardOTABinding.GetName: string; begin Result := 'Debugging Tools Bindings'; end; { TDebuggingWizard } constructor TDebuggingOTAExample.Create; begin end; destructor TDebuggingOTAExample.Destroy; begin inherited; end; procedure TDebuggingOTAExample.Execute; begin end; function TDebuggingOTAExample.GetIDString: string; begin Result:= 'TDebuggingOTAExample'; end; function TDebuggingOTAExample.GetName: string; begin Result:= 'TDebuggingOTAExample'; end; function TDebuggingOTAExample.GetState: TWizardState; begin Result:= [wsEnabled]; end; initialization finalization If iKeyBindingIndex > 0 Then (BorlandIDEServices As IOTAKeyboardServices).RemoveKeyboardBinding (iKeyBindingIndex); If iWizardIndex > 0 Then (BorlandIDEServices As IOTAWizardServices).RemoveWizard(iWizardIndex); end.
//------------------------------------------------------------------------ // // Name : Cyclic Redundancy Code (CRC) // Authors : Rob F. / Entire Group // Email : RobusAsmoder@ukr.net // Date : 23 june 2008 ... 04.02.2014 // Description : Oh ... // // GenCRC(MAS,$31,CRC_MODE_8); //STANDART CRC8 P=31H // GenCRC(MAS,$8005,CRC_MODE_16 OR CRC_REVERT); //STANDART CRC16 P=8005H + REVERT // GenCRC(MAS,$1021,CRC_MODE_16); //EXPERT CRC16 P=1021H // GenCRC(MAS,$04C11DB7,CRC_MODE_32 OR CRC_REVERT);//STANDART CRC32 P=04C11DB7H + REVERT // GenCRC(MAS,$77073096,CRC_MODE_32); //EXPERT CRC32 P=77073096H // //------------------------------------------------------------------------ Unit RBCRC; Interface uses SysUtils, Windows; CONST CRC_MODE_8 = $0001; CRC_MODE_16 = $0002; CRC_MODE_32 = $0008; CRC_REVERT = $0010; //TYPE DWORD = Cardinal; TYPE tCRC=RECORD MODE:DWORD; CRC_S:DWORD; CRC:DWORD; DAT:POINTER; ID:ShortString; END; CONST rbCRC_ID_STR='RHIWERIOUGHWEIUORGILVDDEBIL'; PROCEDURE GenCRC(VAR MCRC;CRC_S,CRC_MODE:DWORD); STDCALL; FUNCTION GetCRCT32(VAR MCRC;CRC_V:DWORD;CRC_D:BYTE):DWORD; STDCALL; FUNCTION GetCRCT16(VAR MCRC;CRC_V:WORD;CRC_D:BYTE):WORD; STDCALL; FUNCTION GetCRCT8(VAR MCRC;CRC_V:BYTE;CRC_D:BYTE):BYTE; STDCALL; FUNCTION CRC_OPEN(VAR CR:tCRC; CRC_S,CRC_MODE:DWORD):BOOLEAN; STDCALL; FUNCTION CRC_CLOSE(VAR CR:tCRC):BOOLEAN; STDCALL; FUNCTION CRC_BUF(VAR CR:tCRC; VAR BUF; SIZE:DWORD; CRC_START:DWORD=0):DWORD; STDCALL; FUNCTION CRC_STR(VAR CR:tCRC; VAR S:ShortString; CRC_START:DWORD=0):DWORD; STDCALL; Implementation //VAR N,M,I:DWORD; //VAR CRC_TABLE:ARRAY[0..255] OF DWORD; FUNCTION GetCRCT32(VAR MCRC;CRC_V:DWORD;CRC_D:BYTE):DWORD; STDCALL; ASM MOV EAX,CRC_V XOR AL,CRC_D MOVZX EDX,AL SHL EDX,2 ADD EDX,MCRC SHR EAX,8 XOR EAX,[EDX] END; FUNCTION GetCRCT16(VAR MCRC;CRC_V:WORD;CRC_D:BYTE):WORD; STDCALL; ASM MOVZX EAX,CRC_V MOVZX EDX,AL XOR DL,CRC_D SHL EDX,2 ADD EDX,MCRC SHR EAX,8 XOR AX,[EDX] END; FUNCTION GetCRCT8(VAR MCRC;CRC_V:BYTE;CRC_D:BYTE):BYTE; STDCALL; ASM MOVZX EAX,CRC_V XOR AL,CRC_D SHL EAX,2 ADD EAX,MCRC MOVZX EAX,BYTE PTR [EAX] END; { FUNCTION GetCRC32(VAR CRC_V:DWORD;CRC_D:BYTE):DWORD; STDCALL; ASM MOV EAX,CRC_V XOR AL,CRC_D MOVZX EDX,AL SHR EAX,8 XOR EAX,DWORD PTR [CRC_TABLE+EDX*4] END; } //Generator of CRC UNIVERSAL PROCEDURE GenCRC(VAR MCRC;CRC_S,CRC_MODE:DWORD); STDCALL; ASM PUSH EBX PUSH ESI PUSH EDI MOV EAX,CRC_S TEST CRC_MODE,CRC_REVERT JZ @M3x1 MOV ECX,32 @M3: SHR CRC_S,1 RCL EAX,1 LOOP @M3 TEST CRC_MODE,CRC_MODE_32 JNZ @M3x1 SHR EAX,16 TEST CRC_MODE,CRC_MODE_16 JNZ @M3x1 // MOV AL,AH SHR AX,8 @M3x1: MOV CRC_S,EAX // SHR CRC_S,8 MOV EDI,MCRC MOV ECX,256 @M1: MOVZX EAX,CL NEG AL TEST CRC_MODE,CRC_REVERT JNZ @M1x1 TEST CRC_MODE,CRC_MODE_8 JNZ @M1x1 SHL EAX,8 TEST CRC_MODE,CRC_MODE_16 JNZ @M1x1 SHL EAX,16 @M1x1: CALL @M0 CALL @M0 CALL @M0 CALL @M0 CALL @M0 CALL @M0 CALL @M0 CALL @M0 { STOSB TEST CRC_MODE,CRC_MODE_8 JNZ @M1x2 SHR EAX,8 STOSB TEST CRC_MODE,CRC_MODE_16 JNZ @M1x2 SHR EAX,8 STOSW @M1x2: } STOSD LOOP @M1 JMP @EXIT @M0: TEST CRC_MODE,CRC_REVERT JNZ @M0x1 TEST CRC_MODE,CRC_MODE_8 JNZ @M0x2 TEST CRC_MODE,CRC_MODE_16 JNZ @M0x3 SHL EAX,1 JNC @M2 XOR EAX,CRC_S RET 0 @M0x2: SHL AL,1 JNC @M2 XOR EAX,CRC_S RET 0 @M0x3: SHL AX,1 JNC @M2 XOR EAX,CRC_S RET 0 @M0x1: SHR EAX,1 JNC @M2 XOR EAX,CRC_S @M2: RET 0 @EXIT: POP EDI POP ESI POP EBX END; FUNCTION CRC_OPEN(VAR CR:tCRC; CRC_S,CRC_MODE:DWORD):BOOLEAN; STDCALL; VAR N,M,I:LONGINT; BEGIN IF CR.ID<>rbCRC_ID_STR THEN BEGIN CR.DAT:=GetMemory(1024); CR.MODE:=CRC_MODE; CR.CRC_S:=CRC_S; CR.CRC:=0; GenCRC(CR.DAT^, CRC_S, CRC_MODE); CR.ID:=rbCRC_ID_STR; RESULT:=TRUE; END ELSE BEGIN RESULT:=FALSE; END; END; FUNCTION CRC_CLOSE(VAR CR:tCRC):BOOLEAN; STDCALL; BEGIN IF CR.ID=rbCRC_ID_STR THEN BEGIN FreeMem(CR.DAT,1024); CR.ID:=''; RESULT:=TRUE; END ELSE BEGIN RESULT:=FALSE; END; END; FUNCTION CRC_BUF(VAR CR:tCRC; VAR BUF; SIZE:DWORD; CRC_START:DWORD=0):DWORD; STDCALL; VAR N:LONGINT; BEGIN CR.CRC:=CRC_START; IF (CR.MODE AND CRC_MODE_8) <> 0 THEN BEGIN FOR N:=0 TO SIZE-1 DO CR.CRC:=GetCRCT8(CR.DAT^, CR.CRC, PByte(DWORD(@BUF)+N)^); END ELSE IF (CR.MODE AND CRC_MODE_16) <> 0 THEN BEGIN FOR N:=0 TO SIZE-1 DO CR.CRC:=GetCRCT16(CR.DAT^, CR.CRC, PByte(DWORD(@BUF)+N)^); END ELSE IF (CR.MODE AND CRC_MODE_32) <> 0 THEN BEGIN FOR N:=0 TO SIZE-1 DO CR.CRC:=GetCRCT32(CR.DAT^, CR.CRC, PByte(DWORD(@BUF)+N)^); END; RESULT:=CR.CRC; END; FUNCTION CRC_STR(VAR CR:tCRC; VAR S:ShortString; CRC_START:DWORD=0):DWORD; STDCALL; BEGIN RESULT:=CRC_BUF(CR, S[1], Length(S), CRC_START); END; BEGIN // GenCRC32(N,0); END.
unit REST.Handler; interface uses System.Classes, System.SysUtils, FMX.Types, REST.Client, REST.Json, JSON; type THandlerException = class(Exception); TArrayOfString = TArray<string>; TArrayOfStringHelper = record helper for TArrayOfString function ToString: string; overload; inline; function ToJson: string; overload; inline; function Add(const Value: string): Integer; inline; procedure Delete(const Value: string); inline; procedure Assign(Source: TStrings); overload; function IsEmpty: Boolean; function Length: Integer; function IndexOf(const Value: string): Integer; end; TArrayOfInteger = TArray<Integer>; TArrayOfIntegerHelper = record helper for TArrayOfInteger function ToString: string; overload; inline; function ToJson: string; overload; inline; function Add(Value: Integer): Integer; inline; procedure Delete(const Value: Integer); inline; function IsEmpty: Boolean; function Length: Integer; function IndexOf(const Value: Integer): Integer; end; TParam = TArray<string>; TParams = TArray<TParam>; TParamsHelper = record helper for TParams private function AddParam(var Dest: TParams; Param: TParam): Integer; inline; public function Add(Param: TParam): Integer; overload; inline; function Add(Key: string; Value: string): Integer; overload; inline; function Add(Key: string; Value: Integer): Integer; overload; inline; function Add(Key: string; Value: Extended): Integer; overload; inline; function Add(Key: string; Value: TDateTime; Format: string = ''): Integer; overload; inline; function Add(Key: string; Value: Boolean): Integer; overload; inline; function Add(Key: string; Value: TArrayOfString): Integer; overload; inline; function Add(Key: string; Value: TArrayOfInteger): Integer; overload; inline; function KeyExists(Key: string): Boolean; inline; function GetValue(Key: string): string; inline; function Remove(Key: string): string; inline; end; TResponseError = record Code: Integer; Text: string; end; TResponse = record private function AppendItemsTag(JSON: string): string; inline; public Success: Boolean; JSON: string; function GetJSONValue: TJSONValue; function GetValue<T: class, constructor>(const Field: string; var Value: T): Boolean; overload; function GetValue<T: class, constructor>(var Value: T): Boolean; overload; function GetValues<T: class, constructor>(var Value: T): Boolean; overload; end; TOnHandlerError = procedure(Sender: TObject; E: Exception; Code: Integer; Text: string) of object; TOnHandlerLog = procedure(Sender: TObject; const Value: string) of object; TOnHandlerExecute = function(Sender: TObject; Request: TRESTRequest): TResponse; TRequestConstruct = class class var Client: TRESTClient; public class function Request(Resource: string; Params: TParams): TRESTRequest; end; TRESTHandler = class private FStartRequest: Cardinal; FRequests: Integer; FRESTClient: TRESTClient; FOnError: TOnHandlerError; FOnLog: TOnHandlerLog; FUseServiceKeyOnly: Boolean; FExecuting: Integer; FFullLog: Boolean; FRequestLimitPerSecond: Integer; FOnExecute: TOnHandlerExecute; FQueueWaits: Integer; function FExecute(Request: TRESTRequest): TResponse; function GetExecuting: Boolean; function FOnExecuted(Request: TRESTRequest): TResponse; procedure Queue; procedure FLog(const Value: string); procedure SetOnError(const Value: TOnHandlerError); procedure SetOnLog(const Value: TOnHandlerLog); procedure SetUseServiceKeyOnly(const Value: Boolean); procedure SetFullLog(const Value: Boolean); procedure SetRequestLimitPerSecond(const Value: Integer); procedure SetOnExecute(const Value: TOnHandlerExecute); public constructor Create; destructor Destroy; override; procedure Log(Sender: TObject; const Text: string); // function Execute(Request: string; Params: TParams): TResponse; overload; function Execute(Request: string; Param: TParam): TResponse; overload; function Execute(Request: string): TResponse; overload; function Execute(Request: TRESTRequest; FreeRequset: Boolean = False): TResponse; overload; // property OnError: TOnHandlerError read FOnError write SetOnError; property OnLog: TOnHandlerLog read FOnLog write SetOnLog; property OnExecute: TOnHandlerExecute read FOnExecute write SetOnExecute; // property Client: TRESTClient read FRESTClient; property Executing: Boolean read GetExecuting; property QueueWaits: Integer read FQueueWaits; // property UseServiceKeyOnly: Boolean read FUseServiceKeyOnly write SetUseServiceKeyOnly; property FullLog: Boolean read FFullLog write SetFullLog; property RequestLimitPerSecond: Integer read FRequestLimitPerSecond write SetRequestLimitPerSecond; end; function BoolToString(Value: Boolean): string; implementation uses System.DateUtils, System.StrUtils; function BoolToString(Value: Boolean): string; begin Result := IfThen(Value, '1', '0'); end; { TRequsetConstruct } class function TRequestConstruct.Request(Resource: string; Params: TParams): TRESTRequest; var Param: TParam; begin Result := TRESTRequest.Create(nil); Result.Client := Client; Result.Resource := Resource; Result.Response := TRESTResponse.Create(Result); for Param in Params do if (Length(Param) > 1) and (not Param[0].IsEmpty) then Result.Params.AddItem(Param[0], Param[1]); end; { TRESTHandler } constructor TRESTHandler.Create; begin inherited; FExecuting := 0; FStartRequest := 0; FQueueWaits := 0; FRequests := 0; FRequestLimitPerSecond := 3; FRESTClient := TRESTClient.Create(nil); FRESTClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; FRESTClient.AcceptCharset := 'UTF-8, *;q=0.8'; FRESTClient.RaiseExceptionOn500 := False; TRequestConstruct.Client := FRESTClient; end; destructor TRESTHandler.Destroy; begin FRESTClient.Free; inherited; end; function TRESTHandler.Execute(Request: string; Param: TParam): TResponse; begin Result := Execute(TRequestConstruct.Request(Request, [Param]), True); end; function TRESTHandler.Execute(Request: string; Params: TParams): TResponse; begin Result := Execute(TRequestConstruct.Request(Request, Params), True); end; function TRESTHandler.Execute(Request: string): TResponse; begin Result := Execute(TRequestConstruct.Request(Request, []), True); end; function TRESTHandler.Execute(Request: TRESTRequest; FreeRequset: Boolean): TResponse; begin try Inc(FExecuting); Result := FExecute(Request); finally Dec(FExecuting); if FreeRequset then Request.Free; end; end; procedure TRESTHandler.Queue; procedure WaitTime(MS: Int64); begin if MS <= 0 then Exit; MS := TThread.GetTickCount + MS; while MS > TThread.GetTickCount do Sleep(10); end; begin //Без очереди if FRequestLimitPerSecond <= 0 then Exit; Inc(FRequests); //Если был запрос if FStartRequest > 0 then begin Inc(FQueueWaits); //Если предел запросов if FRequests > FRequestLimitPerSecond then begin FRequests := 0; WaitTime(1000 - Int64(TThread.GetTickCount - FStartRequest)); end; Dec(FQueueWaits); end; FStartRequest := TThread.GetTickCount; end; function TRESTHandler.FExecute(Request: TRESTRequest): TResponse; begin if FFullLog then FLog(Request.GetFullRequestURL); Queue; Request.Execute; if FFullLog then FLog(Request.Response.JSONText); Result := FOnExecuted(Request); end; function TRESTHandler.FOnExecuted(Request: TRESTRequest): TResponse; begin if Assigned(FOnExecute) then Result := FOnExecute(Self, Request) else begin Result.JSON := Request.Response.Content; Result.Success := True; end; end; procedure TRESTHandler.FLog(const Value: string); begin if Assigned(FOnLog) then FOnLog(Self, Value); end; function TRESTHandler.GetExecuting: Boolean; begin Result := FExecuting > 0; end; procedure TRESTHandler.Log(Sender: TObject; const Text: string); begin if Assigned(FOnLog) then FOnLog(Sender, Text); end; procedure TRESTHandler.SetOnError(const Value: TOnHandlerError); begin FOnError := Value; end; procedure TRESTHandler.SetOnExecute(const Value: TOnHandlerExecute); begin FOnExecute := Value; end; procedure TRESTHandler.SetOnLog(const Value: TOnHandlerLog); begin FOnLog := Value; end; procedure TRESTHandler.SetRequestLimitPerSecond(const Value: Integer); begin FRequestLimitPerSecond := Value; end; procedure TRESTHandler.SetUseServiceKeyOnly(const Value: Boolean); begin FUseServiceKeyOnly := Value; end; procedure TRESTHandler.SetFullLog(const Value: Boolean); begin FFullLog := Value; end; { TResponse } function TResponse.GetJSONValue: TJSONValue; begin if not JSON.IsEmpty then Result := TJSONObject.ParseJSONValue(JSON) else Result := nil; end; function TResponse.GetValue<T>(var Value: T): Boolean; begin Result := Success; if Result then try Value := TJson.JsonToObject<T>(JSON); except Result := False; end; end; function TResponse.GetValue<T>(const Field: string; var Value: T): Boolean; var JSONItem: TJSONValue; begin Result := Success; if Result then try JSONItem := GetJSONValue; try Value := TJson.JsonToObject<T>(TJSONObject(JSONItem.TryGetValue(Field, Value))); finally JSONItem.Free; end; except Result := False; end; end; function TResponse.GetValues<T>(var Value: T): Boolean; var JSONItem: TJSONValue; begin Result := Success; if Result then try JSONItem := TJSONObject.ParseJSONValue(AppendItemsTag(JSON)); try Value := TJson.JsonToObject<T>(TJSONObject(JSONItem)); finally JSONItem.Free; end; except Result := False; end; end; function TResponse.AppendItemsTag(JSON: string): string; begin Result := '{"Items": ' + JSON + '}'; end; { TArrayOfIntegerHelper } function TArrayOfIntegerHelper.Add(Value: Integer): Integer; begin Result := System.Length(Self) + 1; SetLength(Self, Result); Self[Result - 1] := Value; end; procedure TArrayOfIntegerHelper.Delete(const Value: Integer); var i: Integer; begin i := IndexOf(Value); if i >= 0 then System.Delete(Self, i, 1); end; function TArrayOfIntegerHelper.IndexOf(const Value: Integer): Integer; var i: Integer; begin for i := Low(Self) to High(Self) do if Self[i] = Value then Exit(i); Result := -1; end; function TArrayOfIntegerHelper.IsEmpty: Boolean; begin Result := System.Length(Self) = 0; end; function TArrayOfIntegerHelper.Length: Integer; begin Result := System.Length(Self); end; function TArrayOfIntegerHelper.ToJson: string; var i: Integer; begin Result := '['; for i := Low(Self) to High(Self) do begin if i <> Low(Self) then Result := Result + ','; Result := Result + '"' + Self[i].ToString + '"'; end; Result := Result + ']'; end; function TArrayOfIntegerHelper.ToString: string; var i: Integer; begin for i := Low(Self) to High(Self) do begin if i <> Low(Self) then Result := Result + ','; Result := Result + Self[i].ToString; end; end; { TArrayOfStringHelper } function TArrayOfStringHelper.IndexOf(const Value: string): Integer; var i: Integer; begin for i := Low(Self) to High(Self) do if Self[i] = Value then Exit(i); Result := -1; end; function TArrayOfStringHelper.IsEmpty: Boolean; begin Result := System.Length(Self) = 0; end; function TArrayOfStringHelper.Length: Integer; begin Result := System.Length(Self); end; function TArrayOfStringHelper.ToJson: string; var i: Integer; begin Result := '['; for i := Low(Self) to High(Self) do begin if i <> Low(Self) then Result := Result + ','; Result := Result + '"' + Self[i] + '"'; end; Result := Result + ']'; end; function TArrayOfStringHelper.ToString: string; var i: Integer; begin for i := Low(Self) to High(Self) do begin if i <> Low(Self) then Result := Result + ','; Result := Result + Self[i]; end; end; function TArrayOfStringHelper.Add(const Value: string): Integer; begin Result := System.Length(Self) + 1; SetLength(Self, Result); Self[Result - 1] := Value; end; procedure TArrayOfStringHelper.Assign(Source: TStrings); var i: Integer; begin SetLength(Self, Source.Count); for i := 0 to Source.Count - 1 do Self[i] := Source[i]; end; procedure TArrayOfStringHelper.Delete(const Value: string); var i: Integer; begin i := IndexOf(Value); if i >= 0 then System.Delete(Self, i, 1); end; { TParamsHelper } function TParamsHelper.AddParam(var Dest: TParams; Param: TParam): Integer; var i: Integer; begin for i := Low(Dest) to High(Dest) do if Dest[i][0] = Param[0] then begin Dest[i] := Param; Exit(i); end; Result := Length(Dest) + 1; SetLength(Dest, Result); Dest[Result - 1] := Param; end; function TParamsHelper.Add(Param: TParam): Integer; begin Result := AddParam(Self, Param); end; function TParamsHelper.Add(Key, Value: string): Integer; begin Result := AddParam(Self, [Key, Value]); end; function TParamsHelper.Add(Key: string; Value: Integer): Integer; begin Result := AddParam(Self, [Key, Value.ToString]); end; function TParamsHelper.Add(Key: string; Value: Boolean): Integer; begin Result := AddParam(Self, [Key, BoolToString(Value)]); end; function TParamsHelper.Add(Key: string; Value: TArrayOfInteger): Integer; begin Result := AddParam(Self, [Key, Value.ToString]); end; function TParamsHelper.Add(Key: string; Value: TDateTime; Format: string): Integer; begin if Format.IsEmpty then Result := AddParam(Self, [Key, DateTimeToUnix(Value, False).ToString]) else Result := AddParam(Self, [Key, FormatDateTime(Format, Value)]); end; function TParamsHelper.Add(Key: string; Value: Extended): Integer; begin Result := AddParam(Self, [Key, Value.ToString]); end; function TParamsHelper.GetValue(Key: string): string; var i: Integer; begin Result := ''; for i := Low(Self) to High(Self) do if Self[i][0] = Key then Exit(Self[i][1]); end; function TParamsHelper.Add(Key: string; Value: TArrayOfString): Integer; begin Result := AddParam(Self, [Key, Value.ToString]); end; function TParamsHelper.KeyExists(Key: string): Boolean; var i: Integer; begin Result := False; for i := Low(Self) to High(Self) do if Self[i][0] = Key then Exit(True); end; function TParamsHelper.Remove(Key: string): string; var i: Integer; begin Result := ''; for i := Low(Self) to High(Self) do if Self[i][0] = Key then begin Delete(Self, i, 1); Break; end; end; end.
unit Parser; {$I CSXGuard.inc} interface uses CvarDef; procedure ReadConfig; procedure ProcessCommand(const Command, Value: String; const Host: Byte = HOST_PARSER); procedure Cmd_Debug_Parser; cdecl; procedure Cmd_ShowCVars; cdecl; procedure ShutdownParser; implementation uses HLSDK, VoiceExt, MsgAPI, SysUtils, Common; const COMMAND_TABLE_ENTRIES = 34; LIST_TABLE_ENTRIES = 8; CommandTable: array[1..COMMAND_TABLE_ENTRIES] of record Name: String; VarType: (VAR_BOOLEAN = 0, VAR_INTEGER, VAR_FLOAT, VAR_STRING, VAR_BYTE, VAR_WORD); Ptr: Pointer; ChangeInit: Boolean; end = {v1} ((Name: 'Enabled'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.Enabled), (Name: 'ShowConsole'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.ShowConsole; ChangeInit: True), (Name: 'VerifyGameName'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.VerifyGameName; ChangeInit: True), (Name: 'LogBlocks'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.LogBlocks), (Name: 'LogForwards'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.LogForwards), (Name: 'LogDeveloper'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.LogDeveloper), (Name: 'BlockCommands'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.BlockCommands), (Name: 'BlockCVarQueries'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.BlockCVarQueries), (Name: 'BlockMOTD'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.BlockMOTD), (Name: 'RemoveInterpolationLimit'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.RemoveInterpolationLimit; ChangeInit: True), // v1/v2 compatibility // (Name: 'RemoveFPSLimit'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.RemoveFPSLimit; ChangeInit: True), (Name: 'ExtendedForwarding'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.ExtendedForwarding), (Name: 'BlockAllForwards'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.BlockAllForwards), (Name: 'EnableAllForwards'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.EnableAllForwards), (Name: 'RemoveAliasCheck'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.RemoveAliasCheck; ChangeInit: True), (Name: 'EmulateSpecialAlias'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.EmulateSpecialAlias; ChangeInit: True), (Name: 'FastSpecialAlias'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.FastSpecialAlias), // overridefilecheck (Name: 'MaxExtensionLength'; VarType: VAR_INTEGER; Ptr: @CvarDef.MaxExtensionLength), (Name: 'RemoveCVarProtection'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.RemoveCVarProtection; ChangeInit: True), (Name: 'RemoveCVarValidation'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.RemoveCVarValidation; ChangeInit: True), (Name: 'RemoveLocalInfoValidation'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.RemoveLocalInfoValidation; ChangeInit: True), (Name: 'LocalInfoPatchType'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.LocalInfoPatchType; ChangeInit: True), (Name: 'OverrideFrameMSec'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.OverrideFrameMSec; ChangeInit: True), (Name: 'FrameMSec_Min'; VarType: VAR_BYTE; Ptr: @CvarDef.FrameMSec_Min), {v2} (Name: 'OverrideMovieRecording'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.OverrideMovieRecording; ChangeInit: True), (Name: 'ExtendedVoiceInterface'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.ExtendedVoiceInterface; ChangeInit: True), (Name: 'Voice_ConnectionState'; VarType: VAR_BYTE; Ptr: @VoiceExt.Voice_ConnectionState; ChangeInit: True), (Name: 'Voice_DefaultPacketSize'; VarType: VAR_WORD; Ptr: @VoiceExt.Voice_DefaultPacketSize; ChangeInit: True), (Name: 'Voice_EnableBanManager'; VarType: VAR_BOOLEAN; Ptr: @VoiceExt.Voice_EnableBanManager), (Name: 'ShowCommandParameters'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.ShowCommandParameters), (Name: 'EnableSteamIDSpoof'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.EnableSteamIDSpoof; ChangeInit: True), {v3} (Name: 'OverrideKeyState'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.OverrideKeyState; ChangeInit: True), (Name: 'EnableResourceCheck'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.EnableResourceCheck; ChangeInit: True), {v4} (Name: 'PatchSpawnCommand'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.PatchSpawnCommand; ChangeInit: True), (Name: 'ExtendedScripting'; VarType: VAR_BOOLEAN; Ptr: @CvarDef.ExtendedScripting; ChangeInit: True)); ListTable: array[1..LIST_TABLE_ENTRIES] of record Name: String; ListType: TListType; Data: PPointer; Count: PLongWord; end = {v1} ((Name: 'Commands'; ListType: LIST_STRING; Data: @CvarDef.Commands; Count: @CvarDef.CommandCount), (Name: 'BlockFWD_CL'; ListType: LIST_STRING; Data: @CvarDef.BlockFWD_CL; Count: @CvarDef.BlockFWD_CL_Count), (Name: 'EnableFWD_CL'; ListType: LIST_STRING; Data: @CvarDef.EnableFWD_CL; Count: @CvarDef.EnableFWD_CL_Count), (Name: 'BlockFWD_SV'; ListType: LIST_STRING; Data: @CvarDef.BlockFWD_SV; Count: @CvarDef.BlockFWD_SV_Count), (Name: 'EnableFWD_SV'; ListType: LIST_STRING; Data: @CvarDef.EnableFWD_SV; Count: @CvarDef.EnableFWD_SV_Count), (Name: 'FileNameFilters'; ListType: LIST_EXPRESSION; Data: @CvarDef.FileExpr; Count: @CvarDef.FileExpr_Count), (Name: 'QCC'; ListType: LIST_STRING; Data: @CvarDef.QCC; Count: @CvarDef.QCC_Count), {v3} (Name: 'KeyBinds'; ListType: LIST_STRING; Data: @CvarDef.KeyBinds; Count: @CvarDef.KeyBinds_Count)); var PFile, PFile_Entry: Pointer; function GetToken(const LowerCase: Boolean = True): String; overload; begin Result := PChar(CvarDef.COM_Token); if LowerCase then Result := SysUtils.LowerCase(Result); end; procedure GetToken(var Str: String; const LowerCase: Boolean = True); overload; begin Str := PChar(CvarDef.COM_Token); if LowerCase then Str := SysUtils.LowerCase(Str); end; function GetEntryCount(const ListType: TListType): LongWord; var Name, Value: String; PFile_Default: Pointer; begin PFile_Default := PFile; if ListType = LIST_EXPRESSION then begin Result := 0; PFile := CvarDef.COM_Parse(PFile); Name := GetToken(False); while not ((Name = '}') or (PFile = nil)) do begin PFile := CvarDef.COM_Parse(PFile); Value := GetToken(False); if (Value = '}') or (PFile = nil) then Break; Inc(Result); PFile := CvarDef.COM_Parse(PFile); Name := GetToken(False); end; end else begin Result := 0; repeat PFile := CvarDef.COM_Parse(PFile); Value := GetToken(False); Inc(Result); until (Value = '}') or (PFile = nil); if Result > 0 then Dec(Result); end; PFile := PFile_Default; end; function ParseList_Expression(var Data: PExprArray; const Count: PLongWord): Boolean; var ExprName, ExprValue: String; Index, I, L, Size: LongWord; begin Count^ := GetEntryCount(LIST_EXPRESSION); if Count^ = 0 then begin Result := True; Exit; end; Size := Count^ * SizeOf(TExpression); GetMem(Data, Size); COM_FillChar(Data, Size, $0); Index := 0; PFile := CvarDef.COM_Parse(PFile); ExprName := GetToken; while not ((ExprName = '') or (ExprName = '}') or (PFile = nil)) do begin PFile := CvarDef.COM_Parse(PFile); ExprValue := GetToken(False); if (ExprValue = '') or (ExprValue = '}') or (PFile = nil) then Break; Inc(Index); if (StrLComp(PChar(ExprName), 'stricomp', 8) = 0) or (StrLComp(PChar(ExprName), 'strcomp', 7) = 0) then begin L := Length(ExprValue); if L <= MAX_EXPRESSION_LENGTH then begin if ExprName[4] = 'i' then begin StrLCopy(@Data[Index].Data, PChar(LowerCase(ExprValue)), L); Data[Index].ExprType := EXPR_STRICOMP; end else begin StrLCopy(@Data[Index].Data, PChar(ExprValue), L); Data[Index].ExprType := EXPR_STRCOMP; end; Data[Index].Data[L + 1] := Chr($0); end else begin Print('ParseList_Expression: Exception name is too long (Index = ', IntToStr(Index), ').'); Result := False; Exit; end; I := Pos(',', ExprName); if I = 0 then begin Print('ParseList_Expression: Bad argument delimiter (1) at index ', IntToStr(Index)); Result := False; Exit; end; ExprName := Copy(ExprName, I + 1, MaxInt); I := Pos(',', ExprName); if I = 0 then begin Print('ParseList_Expression: Bad argument delimiter (2) at index ', IntToStr(Index)); Result := False; Exit; end; if not TryStrToInt(Copy(ExprName, 1, I - 1), Data[Index].CmpOffset) then begin Print('ParseList_Expression: Bad CmpOffset at index ', IntToStr(Index)); Result := False; Exit; end; ExprName := Copy(ExprName, I + 1, MaxInt); if not TryStrToInt(ExprName, Data[Index].CmpLength) then begin Print('ParseList_Expression: Bad CmpLength at index ', IntToStr(Index)); Result := False; Exit; end; end else if StrLComp(PChar(ExprName), 'strpos', 6) = 0 then // Case-sensitive position search begin Data[Index].ExprType := EXPR_STRPOS; L := Length(ExprValue); if L <= MAX_EXPRESSION_LENGTH then begin StrLCopy(@Data[Index].Data, PChar(ExprValue), L); Data[Index].Data[L + 1] := Chr($0); end else begin Print('ParseList_Expression: Exception name is too long (Index = ', IntToStr(Index), ').'); Result := False; Exit; end; end else if StrLComp(PChar(ExprName), 'stripos', 6) = 0 then // Default position search begin Data[Index].ExprType := EXPR_STRIPOS; L := Length(ExprValue); if L <= MAX_EXPRESSION_LENGTH then begin StrLCopy(@Data[Index].Data, PChar(LowerCase(ExprValue)), L); Data[Index].Data[L + 1] := Chr($0); end else begin Print('ParseList_Expression: Exception name is too long (Index = ', IntToStr(Index), ').'); Result := False; Exit; end; end else if StrLComp(PChar(ExprName), 'strequal', 8) = 0 then begin Data[Index].ExprType := EXPR_STREQUAL; L := Length(ExprValue); if L <= MAX_EXPRESSION_LENGTH then begin StrLCopy(@Data[Index].Data, PChar(ExprValue), L); Data[Index].Data[L + 1] := Chr($0); end else begin Print('ParseList_Expression: Exception name is too long (Index = ', IntToStr(Index), ').'); Result := False; Exit; end; end else if StrLComp(PChar(ExprName), 'exit', 4) = 0 then begin Data[Index].ExprType := EXPR_EXIT; ExprValue := LowerCase(ExprValue); if ExprValue = 'false' then Data[Index].Data[1] := Chr(0) else if ExprValue = 'true' then Data[Index].Data[1] := Chr(1) else begin Print('ParseList_Expression: Bad argument at (Index = ', IntToStr(Index), ')'); Result := False; Exit; end; end // Add new expressions here else begin if not (StrLComp(PChar(ExprName), 'striequal', 9) = 0) then Print('Unknown expression: "', ExprName, '", expression will be treated as StrIEqual'); Data[Index].ExprType := EXPR_STRIEQUAL; L := Length(ExprValue); if L <= MAX_EXPRESSION_LENGTH then begin StrLCopy(@Data[Index].Data, PChar(LowerCase(ExprValue)), L); Data[Index].Data[L + 1] := Chr($0); end else begin Print('ParseList_Expression: Exception name is too long (Index = ', IntToStr(Index), ').'); Result := False; Exit; end; end; PFile := CvarDef.COM_Parse(PFile); ExprName := GetToken; end; Result := True; end; procedure PrintChangeError; begin Print('This variable cannot be changed in-game.'); end; procedure ProcessCommand(const Command, Value: String; const Host: Byte = HOST_PARSER); var I: LongWord; begin if (Command = '') or (Value = '') then Exit; for I := 1 to COMMAND_TABLE_ENTRIES do with CommandTable[I] do if StrIComp(PChar(Name), PChar(Command)) = 0 then begin if ChangeInit and (Host <> HOST_PARSER) then PrintChangeError else case VarType of VAR_BOOLEAN: PBoolean(Ptr)^ := StrToBoolDef(Value, PBoolean(Ptr)^); VAR_INTEGER: PLongint(Ptr)^ := StrToIntDef(Value, PLongint(Ptr)^); VAR_FLOAT: PSingle(Ptr)^ := StrToFloatDef(Value, PSingle(Ptr)^); VAR_STRING: PString(Ptr)^ := Value; VAR_BYTE: PByte(Ptr)^ := StrToIntDef(Value, PByte(Ptr)^); VAR_WORD: PWord(Ptr)^ := StrToIntDef(Value, PWord(Ptr)^); else Error('Invalid variable type.'); end; Exit; end; // custom variable handlers if StrIComp(PChar(Command), 'OverrideFileCheck') = 0 then if (Host = HOST_PARSER) or (MOTDFile <> nil) or (@CvarDef.IsValidFile_Orig <> nil) then CvarDef.OverrideFileCheck := StrToBoolDef(Value, CvarDef.OverrideFileCheck) else PrintChangeError else if StrIComp(PChar(Command), 'RemoveFPSLimit') = 0 then // for v1-v2 compatibility (obsolete in v3-v4) if Host = HOST_PARSER then if StrToBoolDef(Value, False) then CvarDef.FPSLimitPatchType := [PATCH_30FPS..PATCH_1000FPS] else CvarDef.FPSLimitPatchType := [] else PrintChangeError else if StrIComp(PChar(Command), 'RemoveFPSLimit_30') = 0 then if Host = HOST_PARSER then if StrToBoolDef(Value, False) then Include(CvarDef.FPSLimitPatchType, PATCH_30FPS) else Exclude(CvarDef.FPSLimitPatchType, PATCH_30FPS) else PrintChangeError else if StrIComp(PChar(Command), 'RemoveFPSLimit_100') = 0 then if Host = HOST_PARSER then if StrToBoolDef(Value, False) then Include(CvarDef.FPSLimitPatchType, PATCH_100FPS) else Exclude(CvarDef.FPSLimitPatchType, PATCH_100FPS) else PrintChangeError else if StrIComp(PChar(Command), 'RemoveFPSLimit_1000') = 0 then if Host = HOST_PARSER then if StrToBoolDef(Value, False) then Include(CvarDef.FPSLimitPatchType, PATCH_1000FPS) else Exclude(CvarDef.FPSLimitPatchType, PATCH_1000FPS) else PrintChangeError else Print('Unknown command: "', Command, '"'); end; procedure ParseParameter(const Token: String); var Value: String; begin PFile := CvarDef.COM_Parse(PFile); Value := GetToken(False); ProcessCommand(Token, Value); end; function ParseList_String(var Data: PStringArray; const Count: PLongWord): Boolean; var Value: String; L, Index: LongWord; begin if Count = nil then begin Result := False; Exit; end; Count^ := GetEntryCount(LIST_DEFAULT); if Count^ = 0 then begin Result := True; Exit; end; GetMem(Data, Count^ * DEFAULT_COMMAND_LENGTH); Index := 0; PFile := CvarDef.COM_Parse(PFile); GetToken(Value, True); while not ((Value = '') or (Value = '}') or (PFile = nil)) do begin Inc(Index); L := Length(Value); if L <= MAX_STRINGCMD then begin StrLCopy(@Data[Index], PChar(Value), L); Data[Index][L + 1] := Chr($0); end else Print('ParseList_String: String is too long (Index = ', IntToStr(Index), ').'); PFile := CvarDef.COM_Parse(PFile); GetToken(Value, True); end; Result := True; end; function ParseList_CRC(var Data: PCRCArray; const Count: PLongWord): Boolean; var Value: String; Index: LongWord; begin if Count = nil then begin Result := False; Exit; end; Count^ := GetEntryCount(LIST_DEFAULT); if Count^ = 0 then begin Result := True; Exit; end; GetMem(Data, Count^ shl 2); Index := 0; PFile := CvarDef.COM_Parse(PFile); GetToken(Value, True); while not ((Value = '') or (Value = '}') or (PFile = nil)) do begin Inc(Index); Data[Index] := CRC32_ProcessString(Value); PFile := CvarDef.COM_Parse(PFile); GetToken(Value, True); end; Result := True; end; function ParseList_Default: Boolean; begin repeat PFile := CvarDef.COM_Parse(PFile); until (PByte(CvarDef.COM_Token)^ = Ord('}')) or (PFile = nil); Result := True; end; function ParseList(const Token: String): Boolean; var I: LongWord; begin for I := 1 to LIST_TABLE_ENTRIES do with ListTable[I] do if StrIComp(PChar(Name), PChar(Token)) = 0 then begin case ListType of LIST_STRING: Result := ParseList_String(PStringArray(Data^), Count); LIST_CRC: Result := ParseList_CRC(PCRCArray(Data^), Count); LIST_EXPRESSION: Result := ParseList_Expression(PExprArray(Data^), Count); else Result := ParseList_Default; end; Exit; end; Print('Unknown list: "', Token, '"'); Result := ParseList_Default; end; procedure ReadConfig; var PFile_Backup: Pointer; Token: String; begin PFile := Engine.COM_LoadFile('..\csxguard.ini', 5, nil); if PFile = nil then begin PFile := Engine.COM_LoadFile('csxguard.ini', 5, nil); if PFile = nil then begin EmptyConfig := True; Print('', [PRINT_PREFIX]); Print('WARNING: Missing "CSXGuard.ini".', 255, 40, 0, [PRINT_LINE_BREAK]); Exit; end; end; PFile_Entry := PFile; while not (PFile = nil) do begin PFile := CvarDef.COM_Parse(PFile); PFile_Backup := PFile; Token := GetToken(False); PFile := CvarDef.COM_Parse(PFile); if GetToken(False) = '=' then ParseParameter(Token) else if GetToken(False) = '{' then if not ParseList(Token) then ParseList_Default // if list parsing has failed, parse it as a default list else else PFile := PFile_Backup; end; Engine.COM_FreeFile(PFile_Entry); end; procedure Cmd_Debug_Parser; cdecl; var I: LongWord; begin for I := 1 to CommandCount do begin Print(Commands[I], [PRINT_LINE_BREAK]); Print('', [PRINT_LINE_BREAK]); end; for I := 1 to FileExpr_Count do with FileExpr[I] do begin Print('#' + IntToStr(I) + ': Type = ' + IntToStr(ExprType) + '; CmpOffset = ' + IntToStr(CmpOffset) + '; CmpLength = ' + IntToStr(CmpLength) + '; Data = ' + Data, [PRINT_LINE_BREAK]); Print('', [PRINT_LINE_BREAK]); end; end; procedure Cmd_ShowCVars; cdecl; var I: LongWord; begin for I := 1 to COMMAND_TABLE_ENTRIES do with CommandTable[I] do case VarType of VAR_BOOLEAN: PrintVariable(Name, PBoolean(Ptr)^); VAR_INTEGER: PrintVariable(Name, PLongint(Ptr)^); VAR_FLOAT: PrintVariable(Name, PSingle(Ptr)^); VAR_STRING: PrintVariable(Name, PString(Ptr)^); VAR_BYTE: PrintVariable(Name, PByte(Ptr)^); VAR_WORD: PrintVariable(Name, PWord(Ptr)^); end; PrintVariable('OverrideFileCheck', OverrideFileCheck); PrintVariable('RemoveFPSLimit_30', PATCH_30FPS in FPSLimitPatchType); PrintVariable('RemoveFPSLimit_100', PATCH_100FPS in FPSLimitPatchType); PrintVariable('RemoveFPSLimit_1000', PATCH_1000FPS in FPSLimitPatchType); Print('', [PRINT_LINE_BREAK]); for I := 1 to LIST_TABLE_ENTRIES do with ListTable[I] do Print(Name, ': ', IntToStr(Count^), ' entries', [PRINT_LINE_BREAK]); end; procedure ShutdownParser; var I: LongWord; begin for I := 1 to LIST_TABLE_ENTRIES do FreeMemory(ListTable[I].Data); end; end.
unit PeriodForma; {$I defines.inc} interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Mask, ComCtrls, ToolWin, ActnList, OkCancel_frame, System.Actions, Vcl.ImgList; type TPeriodForm = class(TForm) pnlBtns: TPanel; ActionList1: TActionList; actTodayFilter: TAction; actMonthFilter: TAction; ImageList1: TImageList; actPrevMonth: TAction; actNextMonth: TAction; OkCancelFrame1: TOkCancelFrame; tlb1: TToolBar; btnPrevMonth: TToolButton; btnNextMonth: TToolButton; btnTodayFilter: TToolButton; btnMonthFilter: TToolButton; dePeriodTo: TDateTimePicker; lbl1: TLabel; dePeriodFrom: TDateTimePicker; lbl2: TLabel; procedure bbtnApplyClick(Sender: TObject); procedure actTodayFilterExecute(Sender: TObject); procedure actMonthFilterExecute(Sender: TObject); procedure actPrevMonthExecute(Sender: TObject); procedure actNextMonthExecute(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure ChangeDate(aMonth: Integer); public { Public declarations } end; // возвращает данные по периоду отбора данных function ChangePeriod(var aPeriodFrom, aPeriodTo: TDateTime): boolean; implementation uses AtrCommon, AtrStrUtils; {$R *.DFM} // возвращает период отбора данных // true - ecли отбор произведен корректно function ChangePeriod(var aPeriodFrom, aPeriodTo: TDateTime): boolean; var oldShortDateFormat, oldLongDateFormat: String; fs: TFormatSettings; pf: TPeriodForm; begin {$WARN SYMBOL_PLATFORM OFF} fs := TFormatSettings.Create(LOCALE_SYSTEM_DEFAULT); {$WARN SYMBOL_PLATFORM ON} //GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fs); oldShortDateFormat := fs.ShortDateFormat; oldLongDateFormat := fs.LongDateFormat; pf := TPeriodForm.Create(Application); try with pf do begin dePeriodFrom.DateTime := aPeriodFrom; dePeriodTo.DateTime := aPeriodTo; if ShowModal = mrOk then begin if dePeriodFrom.DateTime < dePeriodTo.DateTime then begin aPeriodFrom := dePeriodFrom.DateTime; aPeriodTo := dePeriodTo.DateTime; end else begin aPeriodTo := dePeriodFrom.DateTime; aPeriodFrom := dePeriodTo.DateTime; end; Result := True end else Result := False; end; finally pf.Free; end; end; procedure TPeriodForm.ChangeDate(aMonth: Integer); begin dePeriodFrom.DateTime := MonthFirstDay(IncMonth(dePeriodFrom.DateTime, aMonth)); dePeriodTo.DateTime := MonthLastDay(IncMonth(dePeriodTo.DateTime, aMonth)); end; procedure TPeriodForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) then begin case Ord(Key) of VK_RETURN: OkCancelFrame1.bbOk.Click; VK_LEFT: actPrevMonth.Execute; VK_RIGHT: actNextMonth.Execute; end; end; end; procedure TPeriodForm.bbtnApplyClick(Sender: TObject); begin try if dePeriodFrom.DateTime > dePeriodTo.DateTime then begin dePeriodFrom.DateTime := dePeriodTo.DateTime; // Начальная дата не должна превышать конечную end; except end; end; procedure TPeriodForm.actTodayFilterExecute(Sender: TObject); begin dePeriodFrom.DateTime := (Now); dePeriodTo.DateTime := (Now); end; procedure TPeriodForm.actMonthFilterExecute(Sender: TObject); begin dePeriodFrom.DateTime := MonthFirstDay(Now); dePeriodTo.DateTime := MonthLastDay(Now); end; procedure TPeriodForm.actPrevMonthExecute(Sender: TObject); begin ChangeDate(-1); end; procedure TPeriodForm.actNextMonthExecute(Sender: TObject); begin ChangeDate(1); end; end.
//****************************************************************************** //*** COMMON FUNCTIONS *** //*** *** //*** (c) Massimo Magnano 2000-2005 *** //*** *** //*** *** //****************************************************************************** // File : EnvironmentStrings.pas // // Description : Functions for expand String with Environment Variables inside. // //****************************************************************************** // Exported Variables : // - All the System Variables like %SYSTEMROOT% , %TEMP% etc... // // %SYSTEM-PATH% Path to System Folder // %PROGRAM-PATH% Application or Dll Path // %PROGRAM-EXE% Application or Dll Full Name // %OS% Operating System Type // 'WIN9X\' // 'WINNT\' // 'WIN32S\' // 'OTHER\' // %OS-MAJOR-VER% Operating System Major Version Number // %OS-MINOR-VER% Operating System Minor Version Number // %MAJOR-VER% Application Major Version Number // %MINOR-VER% Application Minor Version Number // %DATE-TIME% Current Date-Time in the form yyyy-mm-dd-hh-nn-ss-z // // For all Variables (except System Variables) the last char is always '\' // // All Variables can be specified in the form : // %VarName:MaxLength% // In this Case the Var Value is Truncated (if Length>MaxLength) // or Expanded with spaces (if Length<MaxLength) unit EnvironmentStrings; interface uses Windows, SysUtils, ShlObj; type TShellPaths = record VAR_NAME :String; nFolder :Integer; end; const MAX_Vars =5; VAR_SYSTEM_PATH ='SYSTEM-PATH'; VAR_PROGRAM_PATH ='PROGRAM-PATH'; VAR_PROGRAM_EXE ='PROGRAM-EXE'; VAR_APPDATA ='APPDATA'; VAR_OS ='OS'; VAR_OS_MAJOR_VER ='OS-MAJOR-VER'; VAR_OS_MINOR_VER ='OS-MINOR-VER'; VAR_MAJOR_VER ='MAJOR-VER'; VAR_MINOR_VER ='MINOR-VER'; VAR_DATE_TIME ='DATE-TIME'; NumExcludedInStringASPARAM =5; Vars_ExcludedInStringASPARAM :array[0..NumExcludedInStringASPARAM-1] of String = ( VAR_OS_MAJOR_VER, VAR_OS_MINOR_VER, VAR_MAJOR_VER, VAR_MINOR_VER, VAR_DATE_TIME ); Vars :array[0..MAX_Vars-1] of String = ( VAR_SYSTEM_PATH, VAR_PROGRAM_PATH, VAR_PROGRAM_EXE, VAR_APPDATA, VAR_OS ); MAX_VAR_Shell =16; VAR_Shell : array [0..MAX_VAR_Shell-1] of TShellPaths =( (VAR_NAME :'DESKTOP_DIR'; nFolder :CSIDL_DESKTOPDIRECTORY), (VAR_NAME :'DESKTOP'; nFolder :CSIDL_DESKTOP), (VAR_NAME :'STARTMENU'; nFolder :CSIDL_STARTMENU), (VAR_NAME :'RECYCLEBIN'; nFolder :CSIDL_BITBUCKET), (VAR_NAME :'CONTROLPANEL'; nFolder :CSIDL_CONTROLS), (VAR_NAME :'MYCOMPUTER'; nFolder :CSIDL_DRIVES), (VAR_NAME :'FONTS'; nFolder :CSIDL_FONTS), (VAR_NAME :'NETHOOD'; nFolder :CSIDL_NETHOOD), (VAR_NAME :'NETWORK'; nFolder :CSIDL_NETWORK), (VAR_NAME :'PERSONAL'; nFolder :CSIDL_PERSONAL), (VAR_NAME :'PRINTERS'; nFolder :CSIDL_PRINTERS), (VAR_NAME :'PROGRAMS'; nFolder :CSIDL_PROGRAMS), (VAR_NAME :'RECENT'; nFolder :CSIDL_RECENT), (VAR_NAME :'SENDTO'; nFolder :CSIDL_SENDTO), (VAR_NAME :'STARTUP'; nFolder :CSIDL_STARTUP), (VAR_NAME :'TEMPLATES'; nFolder :CSIDL_TEMPLATES) ); MAX_ExportedVars =(MAX_Vars+MAX_VAR_Shell+NumExcludedInStringASPARAM); type TOnGetVariableFunction = function (Tag :TObject; Campo :String; var VarValue :String) :Boolean; Var ExportedVars :array[0..MAX_ExportedVars-1] of String; MyVer :String =''; MyMajorVer :String =''; MyMinorVer :String =''; MyLang :String =''; ProgramPath :String =''; ProgramEXE :String =''; SystemPath :String =''; function ProcessPARAMString(Value: String; OnGetVariable :TOnGetVariableFunction =Nil; OnGetVariableTag :TObject =Nil): String; function StringASPARAM(Value: String; AddVars :array of string; ProcessInternalVars :Boolean=False; OnGetVariable :TOnGetVariableFunction =Nil; OnGetVariableTag :TObject =Nil): String; implementation uses WindowsID, FileVer, Registry, ShellApi, ActiveX; const APPDATA_PATH ='Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'; function GetApplicationDataPath :String; Var Reg :TRegistry; begin SetLength(Result, MAX_PATH); ExpandEnvironmentStrings('%APPDATA%', PChar(Result), MAX_PATH); Result :=PChar(Result); if (Result='') or not(DirectoryExists(Result)) then begin Reg :=TRegistry.Create; Reg.OpenKeyReadOnly(APPDATA_PATH); try Result :=Reg.ReadString('AppData'); except Result :=ExtractFilePath(ParamStr(0)); end; Reg.CloseKey; Reg.Free; end; if (Result<>'') then begin if (Result[Length(Result)]<>'\') then Result :=Result+'\'; end; end; function ProcessPARAMString(Value: String; OnGetVariable :TOnGetVariableFunction =Nil; OnGetVariableTag :TObject =Nil): String; Var auxStr, auxStr2, Campo :String; index2, xpos1, xpos2, oldLength, toDel, maxChars :Integer; Exist :Boolean; LocalVarValue :String; //Non Posso Usare Result in GetStringProc, per problemi di stack function GetStringProc(Campo :String; var Exist :Boolean) :String; Var xStr :String; i :Integer; shellAlloc :IMAlloc; IDList :PItemIDList; begin Exist :=False; if Assigned(OnGetVariable) //new then Exist :=OnGetVariable(OnGetVariableTag, Campo, LocalVarValue);//new if Exist then Result :=LocalVarValue else begin if (Campo=VAR_SYSTEM_PATH) then begin Result :=SystemPath; Exist :=(SystemPath<>''); end else if (Campo=VAR_PROGRAM_PATH) then begin Result :=ProgramPath; Exist :=(ProgramPath<>''); end else if (Campo=VAR_PROGRAM_EXE) then begin Result :=ProgramEXE; Exist :=(ProgramEXE<>''); end else if (Campo=VAR_APPDATA) then begin Result :=GetApplicationDataPath; Exist :=(Result<>''); end else if (Campo=VAR_OS) then begin Exist :=Win32_IsValidInfos; if Exist then Case Win32Platform of VER_PLATFORM_WIN32_WINDOWS : Result :='WIN9X\'; VER_PLATFORM_WIN32_NT : Result :='WINNT\'; VER_PLATFORM_WIN32s : Result :='WIN32S\'; else Result :='OTHER\'; end; end else if (Campo=VAR_OS_MAJOR_VER) then begin Exist :=Win32_IsValidInfos; if Exist then Result :=IntToStr(Win32MajorVersion)+'\'; end else if (Campo=VAR_OS_MINOR_VER) then begin Exist :=Win32_IsValidInfos; if Exist then Result :=IntToStr(Win32MinorVersion)+'\'; end else if (Campo=VAR_MAJOR_VER) then begin Exist :=(MyMajorVer<>''); if Exist then Result :=MyMajorVer+'\'; end else if (Campo=VAR_MINOR_VER) then begin Exist :=(MyMinorVer<>''); if Exist then Result :=MyMinorVer+'\'; end else if (Campo=VAR_DATE_TIME) then begin Exist :=True; DateTimeToString(Result, 'yyyy-mm-dd-hh-nn-ss-z', Now); end else begin for i:=0 to MAX_VAR_Shell-1 do begin if (Campo=VAR_Shell[i].VAR_NAME) then begin if (SHGetMalloc(shellAlloc)=NO_ERROR) then begin SHGetSpecialFolderLocation(GetDesktopWindow, VAR_Shell[i].nFolder, IDList); if (IDList<>Nil) then begin SetLength(xStr, MAX_PATH); SHGetPathFromIDList(IDList, PChar(xStr)); xStr :=PChar(xStr); shellAlloc.Free(IDList); end; end; Exist := (xStr<>''); Break; end; end; if not(Exist) then begin SetLength(xStr, MAX_PATH); ExpandEnvironmentStrings(PChar('%'+Campo+'%'), PChar(xStr), MAX_PATH); xStr :=PChar(xStr); Exist:=(pos('%', xStr)<=0); //Se non c'è % e' una variable di sistema end; if Exist then Result :=xStr; end; end; end; begin auxStr :=Value; xpos1 :=Pos('%', auxStr); While (xpos1>0) do begin auxStr[xpos1] :=' '; toDel :=Pos('%', auxStr)-xpos1+1; auxStr2 :=Copy(auxStr, xpos1+1, toDel-2); xpos2 :=Pos(':', auxStr2); if (xpos2>0) then begin //E' stata specificata la lunghezza massima della //Variabile nella forma %VarName:LunghezzaMax% Campo :=Copy(auxStr2, 1, xpos2-1); maxChars :=StrToInt(Copy(auxStr2, xpos2+1, MaxInt)) end else begin Campo :=auxStr2; maxChars :=-1; end; Exist :=False; auxStr2 :=GetStringProc(Uppercase(Campo), Exist); if Exist then begin if (maxChars>0) then begin oldLength :=Length(auxStr2); SetLength(auxStr2, maxChars); if (oldLength<maxChars) then for index2 :=oldLength+1 to maxChars do auxStr2[index2] :=' '; end; Delete(auxStr, xpos1, toDel); Insert(auxStr2, auxStr, xpos1); end else Delete(auxStr, xpos1, toDel); xpos1 :=Pos('%', auxStr); end; Result :=auxStr; end; function StringASPARAM(Value: String; AddVars :array of string; ProcessInternalVars :Boolean=False; OnGetVariable :TOnGetVariableFunction =Nil; OnGetVariableTag :TObject =Nil): String; Var i :Integer; UValue :String; procedure TryReplace(VarValue :String; VarName :String; var xResult :String); Var UVarValue :String; LVarValue, xpos :Integer; begin UVarValue := Uppercase(VarValue); LVarValue := Length(UVarValue); xpos :=Pos(UVarValue, UValue); while (xpos>0) do begin Delete(UValue, xpos, LVarValue); Delete(xResult, xpos, LVarValue); Insert(VarName, UValue, xpos); Insert(VarName, xResult, xpos); xpos :=Pos(UVarValue, UValue); end; end; begin UValue :=Uppercase(Value); Result :=Value; for i:=0 to Length(AddVars)-1 do TryReplace(ProcessPARAMString(AddVars[i], OnGetVariable, OnGetVariableTag), AddVars[i], Result); if ProcessInternalVars then for i:=0 to MAX_ExportedVars-1 do begin if (ExportedVars[i]=Vars_ExcludedInStringASPARAM[0]) then Break;//Exclude All Versions numbers from replace (ex. MyDir 1\ maybe replaced with "MyDir %OS-MINOR-VER%") TryReplace(ProcessPARAMString('%'+ExportedVars[i]+'%', OnGetVariable, OnGetVariableTag), '%'+ExportedVars[i]+'%', Result); end; end; procedure CalcValues; Var i :Integer; begin SetLength(ProgramEXE, MAX_PATH); GetModuleFileName(HInstance, PChar(ProgramEXE), MAX_PATH); ProgramEXE :=PChar(ProgramEXE); ProgramPath :=ExtractFilePath(ProgramEXE); if (ProgramPath<>'') and (ProgramPath[Length(ProgramPath)]<>'\') then ProgramPath :=ProgramPath+'\'; SetLength(SystemPath, MAX_PATH); GetSystemDirectory(PChar(SystemPath), MAX_PATH); SystemPath :=PChar(SystemPath); if (SystemPath<>'') and (SystemPath[Length(SystemPath)]<>'\') then SystemPath :=SystemPath+'\'; MyVer :=GetFileVerLang(ParamStr(0), MyLang); if (MyVer<>'') then begin MyMajorVer :=Copy(MyVer, 1, Pos('.', MyVer)-1); MyMinorVer :=Copy(MyVer, Length(MyMajorVer)+1, Length(MyVer)); end; for i:=0 to MAX_Vars-1 do begin ExportedVars[i] :=Vars[i]; end; for i:=0 to MAX_VAR_Shell-1 do begin ExportedVars[i+MAX_Vars] :=VAR_Shell[i].VAR_NAME; end; //All Variables from this point are excluded in StringASPARAM for i :=0 to NumExcludedInStringASPARAM-1 do begin ExportedVars[i+MAX_Vars+MAX_VAR_Shell] :=Vars_ExcludedInStringASPARAM[i]; end; end; initialization CalcValues; end.
/// <summary> /// Contains a list of types, constants, variables and generic utility methods used in the whole suite.<para></para> /// You will normally need to use this file when using FlexCel. /// </summary> unit tmsUFlxMessages; {$INCLUDE ..\FLXCOMPILER.INC} {$INCLUDE ..\FLXCONFIG.INC} interface uses Windows, {$IFDEF FLX_NEEDSVARIANTS} variants, varutils, {$ENDIF} {$IFDEF FLX_EXTRAWINDOWS}ActiveX,{$ENDIF} //Delphi 5 {$INCLUDE UsePngLib.inc} Classes, SysUtils; const /// <summary> /// \Internal use. Specifies the default locale. /// </summary> FLX_VAR_LOCALE_USER_DEFAULT = $400; resourcestring /// <summary> /// \Internal use. Specifies the separator character for tags in TFlexCelReport. /// </summary> FieldStr='##'; /// <summary> /// \Internal use. Specifies the characters that a name has to have to be a data range in TFlexCelReport. /// </summary> DataSetStr='__'; /// <summary> /// \Internal use. Specifies the separator character for report variables in TFlexCelReport. /// </summary> VarStr='#.'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> StrOpen='<'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> StrClose='>'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> ExtrasDelim='...'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> MarkedRowStr='...delete row...'; //Remember to change ExtrasDelim if changing this /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> HPageBreakStr='...page break...'; //Remember to change ExtrasDelim if changing this /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> FullDataSetStr='*'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> MainTxt='MAIN'; //This is not strictly necessary... just for checking the template /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> RecordCountPrefix='RC_'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> DefaultDateTimeFormat='mm/dd/yyyy hh:mm'; {$I FlexCelVersion.inc} {$IFDEF SPANISH} {$INCLUDE FlxSpanish.inc} {$ELSE} {$IFDEF FRENCH} {$INCLUDE FlxFrench.inc} {$ELSE} {$IFDEF ITALIAN} {$INCLUDE FlxItalian.inc} {$ELSE} {$IFDEF ROMANIAN} {$INCLUDE FlxRomanian.inc} {$ELSE} {$IFDEF PORTUGUESEBR} {$INCLUDE FlxPortugueseBR.inc} {$ELSE} {$IFDEF CHINESE} {$INCLUDE FlxChinese.inc} {$ELSE} {$IFDEF RUSSIAN} {$INCLUDE FlxRussian.inc} {$ELSE} {$IFDEF GERMAN} {$INCLUDE FlxGerman.inc} {$ELSE} {$IFDEF POLISH} {$INCLUDE FlxPolish.inc} {$ELSE} {$IFDEF FINNISH} {$INCLUDE FlxFinnish.inc} {$ELSE} {$INCLUDE FlxEnglish.inc} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> xls_Emf='EMF'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> xls_Wmf='WMF'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> xls_Jpeg='JPEG'; /// <summary> /// \Internal use. Specifies an special character in TFlexCelReport. /// </summary> xls_Png='PNG'; type {$IFDEF DELPHI2008UP} UTF16String = UnicodeString; UTF16Char = Char; PAddress = PByte; {$ELSE} /// <summary> /// An UTF16 wide string. This type maps to WideString in Delphi less than 2009 or to UnicodeString otherwise. /// </summary> UTF16String = WideString; /// <summary> /// An UTF16 wide char. This type maps to WideChar in Delphi less than 2009 or to Char otherwise. /// </summary> UTF16Char = WideChar; /// <summary> /// Used for pointer arithmetic. Point to PAnsiChar if Delphi is less than 2009, or to PByte otherwise. /// </summary> PAddress = PAnsiChar; UInt32 = LongWord; Int32 = LongInt; UInt16 = word; Int16 = SmallInt; {$ENDIF} {$IFDEF USEPNGLIB} {$IFNDEF DELPHI2008UP} TPngImage = TPNGObject; {$ENDIF} {$ENDIF} /// <summary> /// Image Anchor information. /// </summary> TClientAnchor= packed record /// <summary> /// How the image behaves when copying/inserting cells. It might have 3 values: <para></para> /// 0 - Move and Resize the image. <para></para> /// 2 - Move but don't Resize the image. <para></para> /// 3 - Don't Move and don't Resize the image. <para></para> /// </summary> Flag: word; /// <summary> /// First column of object /// </summary> Col1: word; /// <summary> /// Delta x of image, on 1/1024 of a cell. 0 means totally at the left, 512 on half of the cell, 1024 means at the left of next cell. /// </summary> Dx1: word; /// <summary> /// First Row of object. /// </summary> Row1: word; /// <summary> /// Delta y of image on 1/255 of a cell. 0 means totally at the top, 128 on half of the cell, 255 means at the top of next cell. /// </summary> Dy1: word; /// <summary> /// Last column of object. /// </summary> Col2: word; /// <summary> /// Delta x of image, on 1/1024 of a cell. 0 means totally at the left, 512 on half of the cell, 1024 means at the left of next cell. /// </summary> Dx2: word; /// <summary> /// Last row of object. /// </summary> Row2: word; /// <summary> /// Delta y of image on 1/255 of a cell. 0 means totally at the top, 128 on half of the cell, 255 means at the top of next cell. /// </summary> Dy2: word; end; /// <summary> Pointer to a TClientAnchor </summary> PClientAnchor = ^TClientAnchor; WidestringArray=array of UTF16String; WideCharArray=array of UTF16Char; BooleanArray = Array of Boolean; ByteArray = Array of Byte; /// <summary> /// Printer specific settings. It is a byte array with a Win32 DEVMODE structure. /// </summary> TPrinterDriverSettings = record /// <summary> /// Determines the O.S. this structure was saved in. 0 means windows. /// </summary> OperatingEnviroment: word; /// <summary> /// When OperatingEnviroment=0 (windows) you can cast this Data to a DevMode struct. /// </summary> Data: array of byte; end; /// <summary> /// An integer expressing an Excel standard paper size.<para></para> /// Use TExcelPaperSize_XXX constants for the allowed values. /// </summary> TExcelPaperSize = integer; const /// <summary>Difference in days between the 1900 and 1904 date systems supported by Excel.</summary> Date1904Diff = 4 * 365 + 2; /// <summary>Not defined.</summary> TExcelPaperSize_Undefined=0; ///<summary>Letter - 81/2"" x 11""</summary> TExcelPaperSize_Letter=1; ///<summary>Letter small - 81/2"" x 11""</summary> TExcelPaperSize_Lettersmall=2; ///<summary>Tabloid - 11"" x 17""</summary> TExcelPaperSize_Tabloid=3; ///<summary>Ledger - 17"" x 11""</summary> TExcelPaperSize_Ledger=4; ///<summary>Legal - 81/2"" x 14""</summary> TExcelPaperSize_Legal=5; ///<summary>Statement - 51/2"" x 81/2""</summary> TExcelPaperSize_Statement=6; ///<summary>Executive - 71/4"" x 101/2""</summary> TExcelPaperSize_Executive=7; ///<summary>A3 - 297mm x 420mm</summary> TExcelPaperSize_A3=8; ///<summary>A4 - 210mm x 297mm</summary> TExcelPaperSize_A4=9; ///<summary>A4 small - 210mm x 297mm</summary> TExcelPaperSize_A4small=10; ///<summary>A5 - 148mm x 210mm</summary> TExcelPaperSize_A5=11; ///<summary>B4 (JIS) - 257mm x 364mm</summary> TExcelPaperSize_B4_JIS=12; ///<summary>B5 (JIS) - 182mm x 257mm</summary> TExcelPaperSize_B5_JIS=13; ///<summary>Folio - 81/2"" x 13""</summary> TExcelPaperSize_Folio=14; ///<summary>Quarto - 215mm x 275mm</summary> TExcelPaperSize_Quarto=15; ///<summary>10x14 - 10"" x 14""</summary> TExcelPaperSize_s10x14=16; ///<summary>11x17 - 11"" x 17""</summary> TExcelPaperSize_s11x17=17; ///<summary>Note - 81/2"" x 11""</summary> TExcelPaperSize_Note=18; ///<summary>Envelope #9 - 37/8"" x 87/8""</summary> TExcelPaperSize_Envelope9=19; ///<summary>Envelope #10 - 41/8"" x 91/2""</summary> TExcelPaperSize_Envelope10=20; ///<summary>Envelope #11 - 41/2"" x 103/8""</summary> TExcelPaperSize_Envelope11=21; ///<summary>Envelope #12 - 43/4"" x 11""</summary> TExcelPaperSize_Envelope12=22; ///<summary>Envelope #14 - 5"" x 111/2""</summary> TExcelPaperSize_Envelope14=23; ///<summary>C - 17"" x 22""</summary> TExcelPaperSize_C=24; ///<summary>D - 22"" x 34""</summary> TExcelPaperSize_D=25; ///<summary>E - 34"" x 44""</summary> TExcelPaperSize_E=26; ///<summary>Envelope DL - 110mm x 220mm</summary> TExcelPaperSize_EnvelopeDL=27; ///<summary>Envelope C5 - 162mm x 229mm</summary> TExcelPaperSize_EnvelopeC5=28; ///<summary>Envelope C3 - 324mm x 458mm</summary> TExcelPaperSize_EnvelopeC3=29; ///<summary>Envelope C4 - 229mm x 324mm</summary> TExcelPaperSize_EnvelopeC4=30; ///<summary>Envelope C6 - 114mm x 162mm</summary> TExcelPaperSize_EnvelopeC6=31; ///<summary>Envelope C6/C5 - 114mm x 229mm</summary> TExcelPaperSize_EnvelopeC6_C5=32; ///<summary>B4 (ISO) - 250mm x 353mm</summary> TExcelPaperSize_B4_ISO=33; ///<summary>B5 (ISO) - 176mm x 250mm</summary> TExcelPaperSize_B5_ISO=34; ///<summary>B6 (ISO) - 125mm x 176mm</summary> TExcelPaperSize_B6_ISO=35; ///<summary>Envelope Italy - 110mm x 230mm</summary> TExcelPaperSize_EnvelopeItaly=36; ///<summary>Envelope Monarch - 37/8"" x 71/2""</summary> TExcelPaperSize_EnvelopeMonarch=37; ///<summary>63/4 Envelope - 35/8"" x 61/2""</summary> TExcelPaperSize_s63_4Envelope=38; ///<summary>US Standard Fanfold - 147/8"" x 11""</summary> TExcelPaperSize_USStandardFanfold=39; ///<summary>German Std. Fanfold - 81/2"" x 12""</summary> TExcelPaperSize_GermanStdFanfold=40; ///<summary>German Legal Fanfold - 81/2"" x 13""</summary> TExcelPaperSize_GermanLegalFanfold=41; ///<summary>B4 (ISO) - 250mm x 353mm</summary> TExcelPaperSize_B4_ISO_2=42; ///<summary>Japanese Postcard - 100mm x 148mm</summary> TExcelPaperSize_JapanesePostcard=43; ///<summary>9x11 - 9"" x 11""</summary> TExcelPaperSize_s9x11=44; ///<summary>10x11 - 10"" x 11""</summary> TExcelPaperSize_s10x11=45; ///<summary>15x11 - 15"" x 11""</summary> TExcelPaperSize_s15x11=46; ///<summary>Envelope Invite - 220mm x 220mm</summary> TExcelPaperSize_EnvelopeInvite=47; ///<summary>Undefined - </summary> ///<summary>Letter Extra - 91/2"" x 12""</summary> TExcelPaperSize_LetterExtra=50; ///<summary>Legal Extra - 91/2"" x 15""</summary> TExcelPaperSize_LegalExtra=51; ///<summary>Tabloid Extra - 1111/16"" x 18""</summary> TExcelPaperSize_TabloidExtra=52; ///<summary>A4 Extra - 235mm x 322mm</summary> TExcelPaperSize_A4Extra=53; ///<summary>Letter Transverse - 81/2"" x 11""</summary> TExcelPaperSize_LetterTransverse=54; ///<summary>A4 Transverse - 210mm x 297mm</summary> TExcelPaperSize_A4Transverse=55; ///<summary>Letter Extra Transv. - 91/2"" x 12""</summary> TExcelPaperSize_LetterExtraTransv=56; ///<summary>Super A/A4 - 227mm x 356mm</summary> TExcelPaperSize_SuperA_A4=57; ///<summary>Super B/A3 - 305mm x 487mm</summary> TExcelPaperSize_SuperB_A3=58; ///<summary>Letter Plus - 812"" x 1211/16""</summary> TExcelPaperSize_LetterPlus=59; ///<summary>A4 Plus - 210mm x 330mm</summary> TExcelPaperSize_A4Plus=60; ///<summary>A5 Transverse - 148mm x 210mm</summary> TExcelPaperSize_A5Transverse=61; ///<summary>B5 (JIS) Transverse - 182mm x 257mm</summary> TExcelPaperSize_B5_JIS_Transverse=62; ///<summary>A3 Extra - 322mm x 445mm</summary> TExcelPaperSize_A3Extra=63; ///<summary>A5 Extra - 174mm x 235mm</summary> TExcelPaperSize_A5Extra=64; ///<summary>B5 (ISO) Extra - 201mm x 276mm</summary> TExcelPaperSize_B5_ISO_Extra=65; ///<summary>A2 - 420mm x 594mm</summary> TExcelPaperSize_A2=66; ///<summary>A3 Transverse - 297mm x 420mm</summary> TExcelPaperSize_A3Transverse=67; ///<summary>A3 Extra Transverse - 322mm x 445mm</summary> TExcelPaperSize_A3ExtraTransverse=68; ///<summary>Dbl. Japanese Postcard - 200mm x 148mm</summary> TExcelPaperSize_DblJapanesePostcard=69; ///<summary>A6 - 105mm x 148mm</summary> TExcelPaperSize_A6=70; ///<summary>Letter Rotated - 11"" x 81/2""</summary> TExcelPaperSize_LetterRotated=75; ///<summary>A3 Rotated - 420mm x 297mm</summary> TExcelPaperSize_A3Rotated=76; ///<summary>A4 Rotated - 297mm x 210mm</summary> TExcelPaperSize_A4Rotated=77; ///<summary>A5 Rotated - 210mm x 148mm</summary> TExcelPaperSize_A5Rotated=78; ///<summary>B4 (JIS) Rotated - 364mm x 257mm</summary> TExcelPaperSize_B4_JIS_Rotated=79; ///<summary>B5 (JIS) Rotated - 257mm x 182mm</summary> TExcelPaperSize_B5_JIS_Rotated=80; ///<summary>Japanese Postcard Rot. - 148mm x 100mm</summary> TExcelPaperSize_JapanesePostcardRot=81; ///<summary>Dbl. Jap. Postcard Rot. - 148mm x 200mm</summary> TExcelPaperSize_DblJapPostcardRot=82; ///<summary>A6 Rotated - 148mm x 105mm</summary> TExcelPaperSize_A6Rotated=83; ///<summary>B6 (JIS) - 128mm x 182mm</summary> TExcelPaperSize_B6_JIS=88; ///<summary>B6 (JIS) Rotated - 182mm x 128mm</summary> TExcelPaperSize_B6_JIS_Rotated=89; ///<summary>12x11 - 12"" x 11""</summary> TExcelPaperSize_s12x11=90; const /// <summary> /// Convert the DEFAULT column width to pixels. This is different from ColMult, that goes in a column by column basis. /// </summary> DefColWidthAdapt: integer=Round(256*8/7); //font used here is 8 pixels wide, not 7 //Printer Options ///Print over, then down fpo_LeftToRight = $01; ///0= landscape, 1=portrait fpo_Orientation = $02; /// if 1, then PaperSize, Scale, Res, VRes, Copies, and Landscape data have not been obtained from the printer, so they are not valid. /// MAKE SURE YOU MAKE THIS BIT = 0 *BEFORE* CHANGING ANY OTHER OPTION. THEY WILL NOT CHANGE IF THIS IS NOT SET. fpo_NoPls = $04; ///1= Black and white fpo_NoColor = $08; ///1= Draft quality fpo_Draft = $10; ///1= Print Notes fpo_Notes = $20; ///1=orientation not set fpo_NoOrient = $40; ///1=use custom starting page number. fpo_UsePage = $80; /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Consolidate_Area = AnsiChar($00); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Auto_Open = AnsiChar($01); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Auto_Close = AnsiChar($02); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Extract = AnsiChar($03); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Database = AnsiChar($04); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Criteria = AnsiChar($05); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Print_Area = AnsiChar($06); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Print_Titles = AnsiChar($07); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Recorder = AnsiChar($08); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Data_Form = AnsiChar($09); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Auto_Activate = AnsiChar($0A); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Auto_Deactivate = AnsiChar($0B); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Sheet_Title = AnsiChar($0C); /// <summary> /// Internal range name. /// On Excel, internal range names like "Print_Range" are stored as a 1 character string. /// </summary> InternalNameRange_Filter_DataBase = AnsiChar($0D); var /// <summary> /// Factor to convert from <see cref="Excel Internal Units" /> to pixels or viceversa. Look at <see cref="Excel Internal Units" /> /// for more information. /// </summary> ColMult:extended=256/7; //36.6; /// <summary> /// Factor to convert from <see cref="Excel Internal Units" /> to pixels or viceversa. Look at <see cref="Excel Internal Units" /> /// for more information. /// </summary> RowMult:extended=15; type /// <summary> /// The range of color indexes allowed by Excel 2003 or older. /// </summary> TColorPaletteRange=1..56; /// <summary> /// An Excel Cell range, 1-based. /// </summary> TXlsCellRange=record /// <summary> /// First column on range. /// </summary> Left: integer; /// <summary> /// First row on range. /// </summary> Top: integer; /// <summary> /// Last column on range. /// </summary> Right: integer; /// <summary> /// Last row on range. /// </summary> Bottom: integer; end; {$IFDEF FLX_NO_TSIZE} //delphi 5 TSize = tagSIZE; {$ENDIF} /// <summary> /// An Excel named range. /// </summary> TXlsNamedRange=record /// <summary> /// The name of the range. /// </summary> Name: string; /// <summary> /// This is a formula defining the range. It can be used to define complex ranges. /// For example you can use "=Sheet1!$A1:$B65536,Sheet1!$A1:$IV2". /// </summary> /// <remarks> /// Do not use ranges like "A:B" this is not supported by FlexCel. Always use the full name (A1:B65536). /// </remarks> RangeFormula: string; /// <summary> /// Options of the range as an integer. /// Bit Mask Description /// 0 0001h = 1 if the name is hidden /// 1 0002h = 1 if the name is a function /// 2 0004h = 1 if the name is a Visual Basic procedure /// 3 0008h = 1 if the name is a function or command name on a macro sheet /// 4 0010h = 1 if the name contains a complex function /// 5 0020h = 1 if the name is a built-in name. (NOTE: When setting a built in named range, this bit is automatically set) /// </summary> OptionFlags: integer; /// <summary> /// The sheet index for the name (1 based). A named range can have the same name than other /// as long as they are on different sheets. The default value(0) means a global named range, not tied to /// any specific sheet. /// </summary> NameSheetIndex: integer; end; /// <summary> /// Initializes a TXlsNamedRange record with the default values. /// </summary> /// <remarks> /// Use this method always after creating a new TXlsNamedRange record if you are not getting the value /// from other function.<para></para> /// \Note that initializing the record yourself by setting all the members might fail in the future if /// new members are added to the record. /// </remarks> /// <param name="NamedRange">Record you want to initialize.</param> procedure InitializeNamedRange(out NamedRange: TXlsNamedRange); type /// <summary> /// Sheet margin for printing, in inches. /// </summary> TXlsMargins=packed record //C++ builder gets this struct wrong if we use a normal record. /// <summary> /// Left Margin in inches. /// </summary> Left: extended; /// <summary> /// Top Margin in inches. /// </summary> Top: extended; /// <summary> /// Right Margin in inches. /// </summary> Right: extended; /// <summary> /// Bottom Margin in inches. /// </summary> Bottom: extended; /// <summary> /// Header Margin in inches. Space for the header at top of page, it is taken from Top margin. /// </summary> Header: extended; /// <summary> /// Footer Margin in inches. Space for the footer at bottom of page, it is taken from Bottom margin. /// </summary> Footer: extended; end; /// <summary> /// Sheet visibility. /// </summary> TXlsSheetVisible= ( /// <summary>Sheet is visible to the user.</summary> sv_Visible, /// <summary>Sheet is hidden, can be shown by the user with excel.</summary> sv_Hidden, /// <summary>Sheet is hidden, only way to show it is with a macro. (user can't see it with excel)</summary> sv_VeryHidden); /// <summary> /// One RTF run for the text in a cell. FirstChar is the first (base 1) character to apply the format, and FontIndex is the font index for the text /// </summary> TRTFRun= record /// <summary> /// First character on the string where we will apply the font. (1 based) /// </summary> FirstChar: word; /// <summary> /// Font index for this string part. /// </summary> FontIndex: word; end; /// <summary> /// An array of TRTFRun structures, where each struct identifies a font style for a portion of text.<para></para> /// For example, if you have: <c>Value=&quot;Hello&quot; RTFRuns={FirstChar:1 FontIndex=1, FirstChar=3, /// FontIndex=2}</c><para></para> /// &quot;H&quot; (char 0) will be formatted with the specific cell format. &quot;el&quot; (chars 1 and /// 2) will have font number 1 &quot;lo&quot; (chars 3 and 4) will have font number 2 /// </summary> TRTFRunList= array of TRTFRun; /// <summary> /// A string cell value with its rich text information. /// </summary> TRichString= record /// <summary> /// Cell text. /// </summary> Value: UTF16String; /// <summary> /// Rich text info. /// </summary> RTFRuns: TRTFRunList; end; /// <summary> /// Possible types of cell hyperlinks. /// </summary> THyperLinkType= ( /// <summary> /// Web, file or mail URL. (like http://, file://, mailto://, ftp://) /// </summary> hl_URL, /// <summary> /// A file on the local disk. Not an url or unc file. /// </summary> hl_LocalFile, /// <summary> /// Universal Naming convention. For example: \\server\path\file.ext /// </summary> hl_UNC, /// <summary> /// An hyperlink inside the current file. /// </summary> hl_CurrentWorkbook); /// <summary> /// An encapsulation of an Excel hyperlink. /// </summary> THyperLink= record /// <summary> /// The type of hyperlink: to a local file, to an url, to a cell or to a networked file. /// </summary> LinkType: THyperLinkType; /// <summary> /// Text of the HyperLink. This is empty when linking to a cell. /// </summary> Description: UTF16String; /// <summary> /// Description of the HyperLink. /// </summary> TargetFrame: UTF16String; /// <summary> /// When entering an URL on excel, you can enter additional text following the url with a "#" character (for example www.your_url.com#myurl") The text Mark is the text after the "#" char. When entering an address to a cell, the address goes here too. /// </summary> TextMark: UTF16String; /// <summary> /// This parameter is not documented. You can leave it empty. /// </summary> Text: UTF16String; /// <summary> /// Hint when the mouse hovers over the hyperlink. /// </summary> Hint: UTF16String; end; type /// <summary> /// Event associated with <see cref="TCustomFlexCelReport.OnGetFilename" />. /// </summary> TOnGetFileNameEvent = procedure (Sender: TObject; const FileFormat: integer; var Filename: TFileName) of object; /// <summary> /// Event associated with <see cref="TCustomFlexCelReport.OnGetOutStream" />. /// </summary> TOnGetOutStreamEvent = procedure (Sender: TObject; const FileFormat: integer; var OutStream: TStream) of object; /// <summary> /// Possible image types on an excel sheet. /// </summary> TXlsImgTypes = ( /// <summary> /// Enhanced Windows Metafile. This is a Vectorial image format. /// </summary> xli_Emf, /// <summary> /// Windows Metafile. This is a Vectorial image format. /// </summary> xli_Wmf, /// <summary> /// JPEG Image. This is a losely compressed bitmap, best suited for photos. /// </summary> xli_Jpeg, /// <summary> /// Portable Network Graphics. This is a lossless compressed bitmap, best suited for text. /// </summary> xli_Png, /// <summary> /// Windows Bitmap. As this is not compressed, don't use it except for really small images. /// </summary> xli_Bmp, /// <summary> /// Unsupported image format. /// </summary> xli_Unknown); VariantArray=Array [0..maxint div sizeof(Variant)-1]of variant; ArrayOfVariant=Array of Variant; /// <summary> /// Encapsulates the value in a cell. /// </summary> TXlsCellValue= record /// <summary> Value of the cell </summary> Value: variant; /// <summary> Index to the Format for the cell. </summary> XF: integer; /// <summary> True if the cell contains a formula. If this is the case, you need to use CellFormula to read the value. </summary> IsFormula: boolean; end; {$IFDEF NOFORMATSETTINGS} /// <summary> /// This record is a placeholder for older Delphi versions that don't have FormatSettings defined for /// handling different locales. /// </summary> TFormatSettings = record /// <summary> /// Represents a format setting for Delphi 6. /// </summary> CurrencyString: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> CurrencyFormat: Byte; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> CurrencyDecimals: Byte; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> DateSeparator: Char; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> TimeSeparator: Char; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> ListSeparator: Char; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> ShortDateFormat: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> LongDateFormat: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> TimeAMString: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> TimePMString: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> ShortTimeFormat: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> LongTimeFormat: string; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> ThousandSeparator: Char; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> DecimalSeparator: Char; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> TwoDigitYearCenturyWindow: Word; /// <summary> /// Represents a format setting for Delphi 6. /// </summary> NegCurrFormat: Byte; end; {$ENDIF} PFormatSettings = ^TFormatSettings; ///<summary> Defines how an image is anchored to the sheet.</summary> TFlxAnchorType=( ///<summary>Move and resize the image when inserting rows or columns.</summary> at_MoveAndResize, ///<summary>Move but don't resize the image when inserting rows or columns.</summary> at_MoveAndDontResize, /// <summary> /// Don't move and don't resize the image when inserting rows or columns. /// </summary> at_DontMoveAndDontResize); /// <summary> /// Image information for a normal image. /// </summary> TImageProperties=record /// <summary> /// First column of object /// </summary> Col1: integer; /// <summary> /// Delta x of image, on 1/1024 of a cell. 0 means totally at the left, 512 on half of the cell, 1024 means at the left of next cell. /// </summary> dx1: integer; /// <summary> /// First Row of object. /// </summary> Row1: integer; /// <summary> /// Delta y of image on 1/255 of a cell. 0 means totally at the top, 128 on half of the cell, 255 means at the top of next cell. /// </summary> dy1: integer; /// <summary> /// Last column of object. /// </summary> Col2: integer; /// <summary> /// Delta x of image, on 1/1024 of a cell. 0 means totally at the left, 512 on half of the cell, 1024 means at the left of next cell. /// </summary> dx2: integer; /// <summary> /// Last row of object. /// </summary> Row2: integer; /// <summary> /// Delta y of image on 1/255 of a cell. 0 means totally at the top, 128 on half of the cell, 255 means at the top of next cell. /// </summary> dy2: integer; /// <summary> /// FileName of the image. It sets/gets the original filename of the image before it was inserted. /// (For example: c:\image.jpg) It is not necessary to set this field, and when the image is not inserted /// from a file but pasted, Excel does not set it either. /// </summary> FileName: UTF16String; end; /// <summary> /// This method will search for a file in the disk. /// </summary> /// <remarks> /// You can use this method to quickly find files in your application folder.<para></para> /// <para></para> /// The order in which this method will search for the file is:<para></para> /// 1) If the path is an absolute path, it will return it.<para></para> /// 2) If the path is relative, it will first search for it in the folder where the application is.<para></para> /// 3) If it couldn't find it, it will search for the file in the folder where the package is, if FlexCel /// is in a package. This might be useful if you are running for example in IIS where the the path for /// the Application is the path for IIS and not for your dll. /// </remarks> /// <param name="AFileName">FileName we want to find.</param> /// <returns> /// Fully qualified filename and path to the file. /// </returns> function SearchPathStr(const AFileName: String): String; overload; /// <summary> /// This method will search for a file in the disk. /// </summary> /// <remarks> /// You can use this method to quickly find files in your application folder.<para></para> /// <para></para> /// The order in which this method will search for the file is:<para></para> /// 1) If AFileName is an absolute path, it will return it.<para></para> /// 2) If AFilePath is not empty, this method will look for AFIleName in AFilePath.<para></para> /// 3) If AFilePath is empty and AFileName is relative, it will first search for it in the folder where the application is.<para></para> /// 4) If it couldn't find it in 3), it will search for the file in the folder where the package is, if FlexCel /// is in a package. This might be useful if you are running for example in IIS where the the path for /// the Application is the path for IIS and not for your dll. /// </remarks> /// <param name="AFilePath">Path to append before AFileName. If this string is empty, FlexCel will /// search in the application path.</param> /// <param name="AFileName">FileName we want to find.</param> /// <returns> /// Fully qualified filename and path to the file. /// </returns> function SearchPathStr(const AFilePath, AFileName: String): String; overload; {$IFDEF VER130} function IncludeTrailingPathDelimiter(const S: string): string; function VarIsClear(const v: variant): boolean; function TryStrToInt(const s: string; var i: integer): boolean; function TryStrToFloat(const s: string; var i: extended): boolean; {$ENDIF} /// <summary> /// A simple helper function that will convert a variant to a widestring in Delphi &lt; 2009, and /// to an UnicodeString for Delphi &gt;= 2009 /// </summary> /// <remarks> /// This method is used internally by FlexCel. /// </remarks> /// <param name="v">Variant we want to convert.</param> /// <returns> /// The converted string. /// </returns> function VariantToString(const v: variant): UTF16String; {$IFDEF NOFORMATSETTINGS} procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings); {$ENDIF} procedure EnsureAMPM(var FormatSettings: PFormatSettings); /// <summary> /// Tries to convert a string to a float in an invariant culture. This means &quot;.&quot; is <b>always</b> /// decimal separator. /// </summary> /// <remarks> /// This method is used internally by FlexCel. /// </remarks> /// <param name="s">String we want to convert, in English locale.</param> /// <param name="i">\Returns the converted value.</param> /// <returns> /// True if the string was successfully converted. /// </returns> function TryStrToFloatInvariant(const s: string; out i: extended): boolean; {$IFDEF FLX_NEEDSPOSEX} function PosEx(const SubStr, S: UTF16String; Offset: Cardinal): Integer; {$ENDIF} //Delphi 6 function WideUpperCase98(const s: UTF16String):UTF16String; function StringReplaceSkipQuotes(const S, OldPattern, NewPattern: UTF16String): UTF16String; /// <summary> /// Tries to convert a string to a TDateTime. /// </summary> /// <remarks> /// This routine uses the locale in the machine where the application is running to try to guess the /// correct date.<para></para> /// This means for example that if your locale is &quot;dd/mm/yyyy&quot; the date 5/8/2004 will be /// converted to Agust 5, 2004, while if you have &quot;mm/dd/yyyy&quot; the date will be May 8, 2004. /// </remarks> /// <param name="S">String with the date.</param> /// <param name="Value">S converted to a TDateTime.</param> /// <param name="dFormat">\Returns the date format used to convert.</param> /// <param name="HasDate">\Returns true if the string has a date format.</param> /// <param name="HasTime">\Returns true if the string had a time format.</param> /// <param name="DateFormat">Optional parameter. If you specify a string here like &quot;dd/mm/yyyy&quot; /// this will be returned in dformat if the string contains a date.</param> /// <param name="TimeFormat">Optional parameter. If you specify a string here like &quot;hh\:mm\:ss&quot; /// this will be returned in dformat if the string contains time.</param> /// <param name="FormatSettings">Optional parameter. If you specify a format here it will be used. If not the default format settings in the machine will be.</param> /// <returns> /// True if the string could be converted, false otherwise.<para></para> /// /// </returns> function FlxTryStrToDateTime(const S: UTF16String; out Value: TDateTime; out dFormat: UTF16String; out HasDate, HasTime: boolean; const DateFormat: UTF16String=''; const TimeFormat: UTF16String=''; const FormatSettings: PFormatSettings = nil): Boolean; /// <property name="flag" value="deprecated" /> /// /// <summary> /// This method has been deprecated. Use <see cref="TryFormatDateTime1904@string@TDateTime@boolean" text="TryFormatDateTime1904" /> /// instead. /// </summary> /// <remarks> /// Excel has two different date systems: one starts at 1900 and the other at 1904. While 1900 is the /// most common (it is the default in Windows), 1904 is used in Macs and also might be set in Excel for /// Windows too in the options dialog.<para></para> /// <para></para> /// This method assumes always 1900 dates, so it is not safe to use and you should use &quot;1904&quot; /// overloads instead. /// </remarks> /// <param name="Fmt">Excel format to apply to the date.</param> /// <param name="value">DateTime we want to format.</param> /// <returns> /// A string with the formatted datetime. /// </returns> function TryFormatDateTime(const Fmt: string; value: TDateTime): string; deprecated {$IFDEF FLX_HAS_DEPRECATED_COMMENTS}'Use TryFormatDateTime1904 instead'{$ENDIF}; /// <summary> /// Converts a datetime value to a formatted string, using Excel format strings. /// </summary> /// <remarks> /// This method correctly handles 1904 dates, so it should be used instead of TryFormatDateTime. /// </remarks> /// <param name="Fmt">Format string in Excel notation. (something like &quot;dd/mmm/yyyyy hh\:ss&quot;)</param> /// <param name="value">DateTime we want to format.</param> /// <param name="Dates1904">A boolean indicating if the workbook uses 1904 or 1900 dates. <b>Note that /// the result will be different depending on this parameter.</b> You will /// normally get the value for this parameter from /// TFlexCelImport.Options1904Dates</param> /// <returns> /// The datetime formatted as a string.<para></para> /// /// </returns> function TryFormatDateTime1904(const Fmt: string; value: TDateTime; const Dates1904: boolean): string; overload; /// <summary> /// Converts a datetime value to a formatted string, using Excel format strings. /// </summary> /// <remarks> /// This method correctly handles 1904 dates, so it should be used instead of TryFormatDateTime. /// </remarks> /// <param name="Fmt">Format string in Excel notation. (something like &quot;dd/mmm/yyyyy /// hh\:ss&quot;)</param> /// <param name="value">DateTime we want to format.</param> /// <param name="Dates1904">A boolean indicating if the workbook uses 1904 or 1900 dates. <b>Note /// that the result will be different depending on this parameter.</b> You /// will normally get the value for this parameter from /// TFlexCelImport.Options1904Dates</param> /// <param name="LocalSettings">Locale settings used for the conversion. If for example the locale is /// Spanish, the resulting string might be &quot;5 de Abril&quot; instead of /// &quot;April 5&quot;</param> /// <returns> /// The datetime formatted as a string. /// </returns> function TryFormatDateTime1904(const Fmt: string; value: TDateTime; const Dates1904: boolean; const LocalSettings: TFormatSettings): string; overload; /// <summary> /// Increments a Cell range by an offset. /// </summary> /// <remarks> /// This is a simple method that will take a cell range, increment its columns and rows by a given /// value, and return the new range. /// </remarks> /// <param name="CellRange">Original cell range</param> /// <param name="DeltaRow">Rows to add to the range (both top and bottom rows)</param> /// <param name="DeltaCol">Columns to add to the range (both left and right columns)</param> /// <returns> /// A new range with the rows and columns incremented or decremented. /// </returns> function OffsetRange(const CellRange: TXlsCellRange; const DeltaRow, DeltaCol: integer): TXlsCellRange; //Returns "A" for column 1, "B" for 2 and so on /// <summary> /// \Returns a column identifier for a column index. /// </summary> /// <remarks> /// This method will return &quot;A&quot; for column 1, &quot;B&quot; for column 2, and &quot;IV&quot; /// for column 256. /// </remarks> /// <param name="C">Index to the column (1 based)</param> function EncodeColumn(const C: integer): string; /// <summary> /// \Internal use. Returns a TFormatSettings object with the default settings. /// </summary> /// <remarks> /// This method will return a cached LocalSettings if supported by the Delphi version. /// </remarks> function GetDefaultLocaleFormatSettings: PFormatSettings; /// <summary> /// \Internal use. Returns a TFormatSettings object with invariant settings. /// </summary> /// <remarks> /// This method will return a cached LocalSettings if supported by the Delphi version. /// </remarks> function InvariantFormatSettings: PFormatSettings; implementation function EncodeColumn(const C: integer): string; var Delta: integer; begin Delta:=Ord('Z')-Ord('A')+1; if C<=Delta then Result:=chr(Ord('A')+C-1) else Result:=EncodeColumn(((C-1) div Delta))+ chr(Ord('A')+(C-1) mod Delta); end; function IsAbsolute(const AFileName: string): boolean; begin if ExtractFileDrive(AFileName) <> '' then Result := true //this takes care of UNC drives too. else if (Length(AFileName) > 0) and (AFileName[1] = PathDelim) then Result := true else Result := false; end; function SearchPathStr(const AFileName: String): String; begin Result := SearchPathStr('', AFileName) end; function SearchPathStr(const AFilePath, AFileName: String): String; overload; var SearchPath: string; SearchFile: string; begin if IsAbsolute(AFileName) then begin; if not FileExists(AFileName) then raise Exception.CreateFmt(ErrCantFindFile,[AFileName]); Result := AFileName; exit; end; if Trim(AFilePath) <> '' then begin SearchFile := IncludeTrailingPathDelimiter(AFilePath) + AFileName; if FileExists(SearchFile) then begin; Result := SearchFile; exit; end; raise Exception.CreateFmt(ErrCantFindFile,[SearchFile]); end; SearchPath := ExtractFilePath(ParamStr(0)); SearchFile := IncludeTrailingPathDelimiter(SearchPath) + AFileName; if FileExists(SearchFile) then begin; Result := SearchFile; exit; end; SearchPath := ExtractFilePath(GetModuleName(HINSTANCE)); SearchFile := IncludeTrailingPathDelimiter(SearchPath) + AFileName; if FileExists(SearchFile) then begin; Result := SearchFile; exit; end; raise Exception.CreateFmt(ErrCantFindFile,[AFileName]); end; // SearchRecStr {$IFDEF VER130} function IncludeTrailingPathDelimiter(const S: string): string; begin Result:=IncludeTrailingBackslash(s); end; function VarIsClear(const v: variant): boolean; begin Result:=VarIsNull(v); end; function TryStrToInt(const s: string; var i: integer): boolean; var errcode: integer; begin val(s, i, errcode); Result:= errCode = 0; end; function TryStrToFloat(const s: string; var i: extended): boolean; var errcode: integer; begin val(s, i, errcode); Result:= errCode = 0; end; {$ENDIF} {$IFDEF NOFORMATSETTINGS} procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings); begin //Built in formatsettings are not in Delphi 5/6 FormatSettings.CurrencyString:= CurrencyString; FormatSettings.CurrencyFormat:= CurrencyFormat; FormatSettings.CurrencyDecimals:= CurrencyDecimals; FormatSettings.DateSeparator:= DateSeparator; FormatSettings.TimeSeparator:= TimeSeparator; FormatSettings.ListSeparator:= ListSeparator; FormatSettings.ShortDateFormat:= ShortDateFormat; FormatSettings.LongDateFormat:= LongDateFormat; FormatSettings.TimeAMString:= TimeAMString; FormatSettings.TimePMString:= TimePMString; FormatSettings.ShortTimeFormat:= ShortTimeFormat; FormatSettings.LongTimeFormat:= LongTimeFormat; FormatSettings.ThousandSeparator:= ThousandSeparator; FormatSettings.DecimalSeparator:= DecimalSeparator; FormatSettings.TwoDigitYearCenturyWindow:= TwoDigitYearCenturyWindow; FormatSettings.NegCurrFormat:= NegCurrFormat; end; {$ENDIF} procedure EnsureAMPM(var FormatSettings: PFormatSettings); begin //Windows uses empty AM/PM designators as empty. Excel uses AM/PM. This happens for example on German locale. if (FormatSettings.TimeAMString = '') then begin FormatSettings.TimeAMString := 'AM'; end; if (FormatSettings.TimePMString = '') then begin FormatSettings.TimePMString := 'PM'; end; end; var CachedRegionalCulture: TFormatSettings; //Cached because it is slow. CachedInvariantCulture: TFormatSettings; function GetDefaultLocaleFormatSettings: PFormatSettings; begin {$IFDEF DELPHIXEUP} if (CachedRegionalCulture.DecimalSeparator = #0) then CachedRegionalCulture := TFormatSettings.Create(); {$ELSE} if (CachedRegionalCulture.DecimalSeparator = #0) then GetLocaleFormatSettings(GetThreadLocale, CachedRegionalCulture); {$ENDIF} Result:= @CachedRegionalCulture; end; function InvariantFormatSettings: PFormatSettings; begin {$IFDEF DELPHIXEUP} if CachedInvariantCulture.DecimalSeparator = #0 then CachedInvariantCulture := TFormatSettings.Create('en-US'); {$ELSE} if CachedInvariantCulture.DecimalSeparator = #0 then GetLocaleFormatSettings($0409, CachedInvariantCulture); {$ENDIF} Result := @CachedInvariantCulture; end; function TryStrToFloatInvariant(const s: string; out i: extended): boolean; var errcode: integer; begin i := 0; val(s, i, errcode); Result:= errCode = 0; end; {$IFDEF WIDEUPPEROK} function WideUpperCase98(const s: UTF16String):UTF16String; begin Result:=WideUpperCase(s); end; {$ELSE} function WideUpperCase98(const s: UTF16String):UTF16String; var Len: Integer; begin Len := Length(S); SetString(Result, PWideChar(S), Len); if Len > 0 then CharUpperBuffW(Pointer(Result), Len); if GetLastError> 0 then result := UpperCase(s); end; {$ENDIF} //Defined as there is not posex on d5 function PosEx(const SubStr, S: UTF16String; Offset: Cardinal): Integer; var i,k: integer; Equal: boolean; begin i:= Offset; Result:=-1; while i<=Length(s)-Length(SubStr)+1 do begin if s[i]=Substr[1] then begin Equal:=true; for k:=2 to Length(Substr) do if s[i+k-1]<>Substr[k] then begin Equal:=false; break; end; if Equal then begin Result:=i; exit; end; end; inc(i); end; end; function StartsWith(const SubStr, S: UTF16String; Offset: integer): boolean; var i: integer; begin Result := false; if Offset - 1 + Length(SubStr) > Length(s) then exit; for i := 1 to Length(SubStr) do begin if S[i + Offset - 1] <> SubStr[i] then exit; end; Result:= true; end; function StringReplaceSkipQuotes(const S, OldPattern, NewPattern: UTF16String): UTF16String; var SearchStr, Patt: UTF16String; i,k,z: Integer; InQuote: boolean; begin SearchStr := WideUpperCase98(S); Patt := WideUpperCase98(OldPattern); SetLength(Result, Length(SearchStr)*2); InQuote:=false; i:=1;k:=1; while i<= Length(SearchStr) do begin if SearchStr[i]='"' then InQuote:= not InQuote; if not InQuote and (StartsWith(Patt,SearchStr,i)) then begin if k+Length(NewPattern)-1>Length(Result) then SetLength(Result, k+Length(NewPattern)+100); for z:=1 to Length(NewPattern) do Result[z+k-1]:=NewPattern[z]; inc(k, Length(NewPattern)); inc(i, Length(Patt)); end else begin if k>Length(Result) then SetLength(Result, k+100); Result[k]:=s[i]; inc(i); inc(k); end; end; SetLength(Result, k-1); end; function DateIsOk(s: string; const v: TDateTime): boolean; //We have an issue with a string like '1.2.3' //If we are using german date separator (".") it will be converted to //Feb 1, 2003, which is ok. But, if we use another format, windows will think it //is a time, and will convert it to 1:02:03 am. That's why we added this 'patch' function. var p: integer; i, err, k: integer; begin Result:= true; if (Trunc(v)<>0) then exit; s:=s+'.'; for i:=1 to 3 do begin p:= pos('.',s); if p<=0 then begin if i=3 then Result:=false; exit; end; val(copy(s,1,p-1), k, err); if (err<>0) or (k<0) then exit; s:=copy(s,p+1,Length(s)); end; if trim(s)<'' then exit; Result:=false; end; function FlxTryStrToDateTime(const s:UTF16String; out Value: TDateTime; out dFormat: UTF16String; out HasDate, HasTime: boolean; const DateFormat: UTF16String=''; const TimeFormat: UTF16String=''; const FormatSettings: PFormatSettings = nil): Boolean; var LResult: HResult; aDateFormat, aTimeFormat: UTF16String; {$IFDEF FLX_NOVARDATEFROMSTRING} //Delphi 5 v1: olevariant; {$ENDIF} FmSet: PFormatSettings; begin if FormatSettings = nil then FmSet := GetDefaultLocaleFormatSettings else FmSet := FormatSettings; if DateFormat='' then aDateFormat:= FmSet.ShortDateFormat else aDateFormat:=DateFormat; if TimeFormat='' then aTimeFormat:= FmSet.ShortTimeFormat else aTimeFormat:=TimeFormat; aTimeFormat:=StringReplaceSkipQuotes(aTimeFormat,'AMPM','AM/PM'); //Format AMPM is not recognized by Excel. This is harcoded on sysutils {$IFDEF FLX_NOVARDATEFROMSTRING} //Delphi 5. Doesn't work on kylix LResult:=VariantChangeType(v1, s, 0, varDate); Value:=v1; {$ELSE} //--------------------READ THIS!--------------------------------------------------------------------------------------// // If you get an error here with Delphi 6, make sure to install ALL latest Delphi 6 update packs, including RTL3 update //--------------------------------------------------------------------------------------------------------------------// // available from www.borland.com LResult := VarDateFromStr(PWideChar(S), FLX_VAR_LOCALE_USER_DEFAULT, 0, Value); Result:=(LResult = 0) and DateIsOk(s,Value); //VAR_OK doesnt work on D5; {$ENDIF} //We have a problem with the german date separator "." and a.m. or p.m. //so we cant just test for a "." inside a formula to know it includes a date. HasDate:=(pos('.', s)>0) or (pos('/',s)>0) or (pos('-',s)>0) //hate to hard-code this values, but I see not other viable way or (pos(FmSet.DateSeparator, s)>0); HasDate:= HasDate and (Trunc(Value)>0); HasTime:=(pos(':',s)>0) or (pos(FmSet.TimeSeparator, s)>0); //Again... hard-coding :-( At least is isolated here if not HasDate and not HasTime then Result:=false; //Things like "1A" are converted to times, even when it doesn't make sense. dFormat:=''; if HasDate then dFormat:=dFormat+aDateFormat; if HasTime then begin if dFormat<>'' then dFormat:=dFormat+' '; dFormat:=dFormat+aTimeFormat; end; end; function TryFormatDateTime(const Fmt: string; value: TDateTime): string; begin try Result :=FormatDateTime(Fmt, value); except Result :='##'; end; end; function TryFormatDateTime1904(const Fmt: string; value: TDateTime; const Dates1904: boolean; const LocalSettings: TFormatSettings): string; begin try if (Dates1904) then value:= value + Date1904Diff; {$IFDEF NOFORMATSETTINGS} Result :=FormatDateTime(Fmt, value); {$ELSE} Result :=FormatDateTime(Fmt, value, LocalSettings); {$ENDIF} except Result :='##'; end; end; function TryFormatDateTime1904(const Fmt: string; value: TDateTime; const Dates1904: boolean): string; begin try if (Dates1904) then value:= value + Date1904Diff; Result :=FormatDateTime(Fmt, value); except Result :='##'; end; end; function OffsetRange(const CellRange: TXlsCellRange; const DeltaRow, DeltaCol: integer): TXlsCellRange; begin Result:=CellRange; inc(Result.Top, DeltaRow); inc(Result.Left, DeltaCol); inc(Result.Bottom, DeltaRow); inc(Result.Right, DeltaCol); end; procedure InitializeNamedRange(out NamedRange: TXlsNamedRange); begin NamedRange.Name:=''; NamedRange.RangeFormula:=''; NamedRange.OptionFlags:=0; NamedRange.NameSheetIndex:=0; end; function VariantToString(const v: variant): UTF16String; begin {$IFDEF DELPHI2008UP} Result := VarToStr(v); {$ELSE} Result := VarToWideStr(v); {$ENDIF} end; end.
unit FilterAPI; interface uses SysUtils, Classes, Windows; /// //////////////////////////////////////////////////////////////////////////// // // (C) Copyright 2011 EaseFilter Technologies Inc. // All Rights Reserved // // This software is part of a licensed software product and may // only be used or copied in accordance with the terms of that license. // // This header file includes the structures and exported API from the FilterAPI.DLL // // /// //////////////////////////////////////////////////////////////////////////// // #ifndef __FILTER_API_H__ // #define __FILTER_API_H__ const STATUS_ACCESS_DENIED = $C0000022; MESSAGE_SEND_VERIFICATION_NUMBER = $FF000001; BLOCK_SIZE = 65536; MAX_FILE_NAME_LENGTH = 1024; MAX_SID_LENGTH = 256; MAX_PATH = 260; MAX_EXCLUDED_PROCESS_ID = 200; MAX_INCLUDED_PROCESS_ID = 200; MAX_PROTECTED_PROCESS_ID = 200; MAX_BLOCK_SAVEAS_PROCESS_ID = 200; MAX_ERROR_MESSAGE_SIZE = 1024; MAX_REQUEST_TYPE = 32; // // define the filter driver request message type // MESSAGE_TYPE_RESTORE_BLOCK_OR_FILE = $00000001; // required to restore the block data or full data of the stub file MESSAGE_TYPE_RESTORE_FILE = $00000002; // required to restore the full data of the stub file, for memory // mapping file open or write request, we need to restore the stub file MESSAGE_TYPE_RESTORE_FILE_TO_CACHE = $00000008; // require to download the whole file to the cache folder MESSAGE_TYPE_SEND_EVENT_NOTIFICATION = $00000010; // the send notification event request, don't need to reply this request. EASETAG_KEY = $BBA65D6F; PEERTAG_KEY = $BBA65D77; STATUS_SUCCESS = 0; STATUS_REPARSE = $00000104; STATUS_NO_MORE_FILES = $80000006; STATUS_WARNING = $80000000; STATUS_ERROR = $C0000000; STATUS_UNSUCCESSFUL = $C0000001; STATUS_END_OF_FILE = $C0000011; ENABLE_NO_RECALL_FLAG = $00000001; type TFilterType = ( FILE_SYSTEM_MONITOR = 0, FILE_SYSTEM_CONTROL = 1, FILE_SYSTEM_ENCRYPTION = 2, FILE_SYSTEM_CONTROL_ENCRYPTION = 3, FILE_SYSTEM_MONITOR_ENCRYPTION = 4, FILE_SYSTEM_EASE_FILTER_ALL = 5, FILE_SYSTEM_MONITOR_CONTROL = 8, FILE_SYSTEM_HSM = $10, FILE_SYSTEM_CLOUD = $20 ); type FilterCommand = ( FILTER_SEND_FILE_CHANGED_EVENT = $00010001, FILTER_REQUEST_USER_PERMIT = $00010002, FILTER_REQUEST_ENCRYPTION_KEY = $00010003, FILTER_REQUEST_ENCRYPTION_IV_AND_KEY = $00010004); type PEASETAG_DATA = ^EASETAG_DATA; EASETAG_DATA = Record EaseTagKey: ULONG; Flags: ULONG; FileNameLength: ULONG; //FileName: Array of Char; //FileName: Array [0 .. MAX_FILE_NAME_LENGTH - 1] of Char; FileName: WideChar;//Array [0..1024] of WideChar; end; {///the I/O types of the monitor or control filter can intercept. } type MessageType = ( PRE_CREATE = $00000001, POST_CREATE = $00000002, PRE_FASTIO_READ = $00000004, POST_FASTIO_READ = $00000008, PRE_CACHE_READ = $00000010, POST_CACHE_READ = $00000020, PRE_NOCACHE_READ = $00000040, POST_NOCACHE_READ = $00000080, PRE_PAGING_IO_READ = $00000100, POST_PAGING_IO_READ = $00000200, PRE_FASTIO_WRITE = $00000400, POST_FASTIO_WRITE = $00000800, PRE_CACHE_WRITE = $00001000, POST_CACHE_WRITE = $00002000, PRE_NOCACHE_WRITE = $00004000, POST_NOCACHE_WRITE = $00008000, PRE_PAGING_IO_WRITE = $00010000, POST_PAGING_IO_WRITE = $00020000, PRE_QUERY_INFORMATION = $00040000, POST_QUERY_INFORMATION = $00080000, PRE_SET_INFORMATION = $00100000, POST_SET_INFORMATION = $00200000, PRE_DIRECTORY = $00400000, POST_DIRECTORY = $00800000, PRE_QUERY_SECURITY = $01000000, POST_QUERY_SECURITY = $02000000, PRE_SET_SECURITY = $04000000, POST_SET_SECURITY = $08000000, PRE_CLEANUP = $10000000, POST_CLEANUP = $20000000, PRE_CLOSE = $40000000, POST_CLOSE = $80000000); {///the flags of the access control to the file. } type AccessFlag = ( /// Filter driver will skip all the IO if the file name match the include file mask. EXCLUDE_FILTER_RULE = $00000000, /// Block the file open. EXCLUDE_FILE_ACCESS = $00000001, /// Reparse the file open to the new file name if the reparse file mask was added. REPARSE_FILE_OPEN = $00000002, /// Hide the files from the folder directory list if the hide file mask was added. HIDE_FILES_IN_DIRECTORY_BROWSING = $00000004, /// Enable the transparent file encryption if the encryption key was added. FILE_ENCRYPTION_RULE = $00000008, /// Allow the file open to access the file's security information. ALLOW_OPEN_WTIH_ACCESS_SYSTEM_SECURITY = $00000010, /// Allow the file open for read access. ALLOW_OPEN_WITH_READ_ACCESS = $00000020, /// Allow the file open for write access. ALLOW_OPEN_WITH_WRITE_ACCESS = $00000040, /// Allow the file open for create new file or overwrite access. ALLOW_OPEN_WITH_CREATE_OR_OVERWRITE_ACCESS = $00000080, /// Allow the file open for delete. ALLOW_OPEN_WITH_DELETE_ACCESS = $00000100, /// Allow to read the file data. ALLOW_READ_ACCESS= $00000200, /// Allow write data to the file. ALLOW_WRITE_ACCESS = $00000400, /// Allow to query file information. ALLOW_QUERY_INFORMATION_ACCESS = $00000800, /// Allow to change the file information:file attribute,file size,file name,delete file ALLOW_SET_INFORMATION = $00001000, /// Allow to rename the file. ALLOW_FILE_RENAME = $00002000, /// Allow to delete the file. ALLOW_FILE_DELETE = $00004000, /// Allow to change file size. ALLOW_FILE_SIZE_CHANGE = $00008000, /// Allow query the file security information. ALLOW_QUERY_SECURITY_ACCESS = $00010000, /// Allow change the file security information. ALLOW_SET_SECURITY_ACCESS = $00020000, /// Allow to browse the directory file list. ALLOW_DIRECTORY_LIST_ACCESS = $00040000, /// Allow the remote access via share folder. ALLOW_FILE_ACCESS_FROM_NETWORK = $00080000, /// Allow to encrypt the new file if the encryption filter rule is enabled. ALLOW_NEW_FILE_ENCRYPTION = $00100000, /// Allow the application to create a new file after it opened the protected file. ALLOW_ALL_SAVE_AS = $00200000, /// Allow the application in the inlcude process list to create a new file after it opened the protected file. ALLOW_INCLUDE_PROCESS_SAVE_AS = $00400000, /// Allow the file to be executed. ALLOW_FILE_MEMORY_MAPPED = $00800000, ALLOW_MAX_RIGHT_ACCESS = $fffffff0); type // this is the data structure which send data from kernel to user mode. PMESSAGE_SEND_DATA = ^MESSAGE_SEND_DATA; MESSAGE_SEND_DATA = Record MessageId: ULONG; FileObject: Pointer; FsContext: Pointer; MessageType: ULONG; ProcessId: ULONG; ThreadId: ULONG; Offset: Int64; // read/write offset Length: ULong; // read/write length FileSize: Int64; TransactionTime: Int64; CreationTime: Int64; LastAccessTime: Int64; LastWriteTime: Int64; FileAttributes: ULONG; // The disired access,share access and disposition for Create request. DesiredAccess: ULONG; Disposition: ULONG; ShareAccess: ULONG; CreateOptions: ULONG; CreateStatus: ULONG; // For QueryInformation,SetInformation,Directory request it is information class // For QuerySecurity and SetSecurity request,it is securityInformation. InfoClass: ULONG; Status: ULONG; FileNameLength: ULONG; FileName: Array [0 .. MAX_FILE_NAME_LENGTH - 1] of CHAR; // WCHAR FileName[MAX_FILE_NAME_LENGTH]; SidLength: ULONG; Sid: Array [0 .. MAX_SID_LENGTH - 1] of Byte; // UCHAR Sid[MAX_SID_LENGTH]; DataBufferLength: ULONG; DataBuffer: Array [0 .. BLOCK_SIZE - 1] of Byte; // UCHAR DataBuffer[BLOCK_SIZE]; VerificationNumber: ULONG; end; // This the structure return back to filter,only for call back filter. PMESSAGE_REPLY_DATA = ^MESSAGE_REPLY_DATA; MESSAGE_REPLY_DATA = Record MessageId: ULONG; MessageType: ULONG; ReturnStatus: ULONG; FilterStatus: ULONG; DataBufferLength: ULONG; DataBuffer: Array [0 .. BLOCK_SIZE - 1] of BYTE; // UCHAR DataBuffer[BLOCK_SIZE]; end; type // this is the data structure which send data from kernel to user mode. TEVENT_TYPE = ( FILE_CREATEED = $00000020, FILE_WRITTEN = $00000040, FILE_RENAMED = $00000080, FILE_DELETED = $00000100, FILE_SECURITY_CHANGED = $00000200, FILE_INFO_CHANGED = $00000400, FILE_READ = $00000800); // The status return to filter,instruct filter what process needs to be done. FilterStatus = ( FILTER_MESSAGE_IS_DIRTY = $00000001, // Set this flag if the reply message need to be processed. FILTER_COMPLETE_PRE_OPERATION = $00000002, // Set this flag if complete the pre operation. FILTER_DATA_BUFFER_IS_UPDATED = $00000004, // Set this flag if the databuffer was updated. BLOCK_DATA_WAS_RETURNED = $00000008, // Set this flag if return read block databuffer to filter. CACHE_FILE_WAS_RETURNED = $00000010, RESTORE_STUB_FILE_WITH_CACHE_FILE = $00000020); // Set this flag if the cache file was restored. type // this is the data structure which send data from kernel to user mode. PProto_Message_Callback = ^Proto_Message_Callback; Proto_Message_Callback = Record pSendMessage: MESSAGE_SEND_DATA; pReplyMessage: MESSAGE_REPLY_DATA; end; type // this is the data structure which send data from kernel to user mode. PProto_Disconnect_Callback = ^Proto_Disconnect_Callback; Proto_Disconnect_Callback = Record end; type TMessageCallback = function(MsgOut: String): Boolean of object; type /// /////////////////////////////////////////////////////////////////////////// // FilterAPI.DLL INterface functions TInstallDriver = function(): ULONG; cdecl; TUninstallDriver = function(): ULONG; cdecl; TSetRegistrationKey = function(key: PAnsiChar): ULONG; cdecl; // C++ apparently needs this value to be an AnsiString....... TIsDriverServiceRunning = function(): BOOL; cdecl; TRegisterMessageCallback = function(ThreadCount: ULONG; MessageCallback: Pointer; DisconnectCallback: Pointer): BOOL; cdecl; TDisconnect = procedure(); cdecl; TGetLastErrorMessage = function(Buffer: PChar; var BufferLength: ULONG): ULONG; cdecl; TSetFilterType = function(FilterType:ULONG): ULONG; cdecl; TResetConfigData = function(): ULONG; cdecl; TSetBooleanConfig = function(booleanConfig: ULONG): ULONG; cdecl; TSetConnectionTimeout = function(TimeOutInSeconds: ULONG): ULONG; cdecl; TAddNewFilterRule = function(AccessFlag: ULONG; FilterMask: PChar; IsResident:BOOL): ULONG; cdecl; TAddExcludeFileMaskToFilterRule = function(FilterMask: PChar; ExcludeFileFilterMask:PChar): ULONG; cdecl; TAddHiddenFileMaskToFilterRule = function(FilterMask: PChar; HiddenFileFilterMask:PChar): ULONG; cdecl; TAddReparseFileMaskToFilterRule = function(FilterMask: PChar; ReparseFileFilterMask:PChar): ULONG; cdecl; TAddEncryptionKeyToFilterRule = function(FilterMask: PChar; EncryptionKeyLength:ULONG; EncryptionKey:PBYTE): ULONG; cdecl; TAddIncludeProcessNameToFilterRule = function(FilterMask: PChar; ProcessName:PChar): ULONG; cdecl; //process name format: notepad.exe TAddExcludeProcessNameToFilterRule = function(FilterMask: PChar; ProcessName:PChar): ULONG; cdecl; //process name format: notepad.exe TAddIncludeProcessIdToFilterRule = function(FilterMask: PChar; IncludeProcessId:ULONG): ULONG; cdecl; TAddExcludeProcessIdToFilterRule = function(FilterMask: PChar; ExcludeProcessId:ULONG): ULONG; cdecl; TAddIncludeUserNameToFilterRule = function(FilterMask: PChar; UserName:PChar): ULONG; cdecl; //UserName format: domainName(or computer name)\userName.exe TAddExcludeUserNameToFilterRule = function(FilterMask: PChar; UserName:PChar): ULONG; cdecl; //UserName format: domainName(or computer name)\userName.exe TRegisterEventTypeToFilterRule = function(FilterMask: PChar; EventType:ULONG): ULONG; cdecl; //only works if Monitor Filter feature was enabled TRegisterMoinitorIOToFilterRule = function(FilterMask: PChar; RegisterIO:ULONG): ULONG; cdecl; //only works if Monitor Filter feature was enabled TRegisterControlIOToFilterRule = function(FilterMask: PChar; RegisterIO:ULONG): ULONG; cdecl; //only works if Control Filter feature was enabled TAddProcessRightsToFilterRule = function(FilterMask: PChar;ProcessName:PChar; AccessFlags:ULONG): ULONG; cdecl; TAddUserRightsToFilterRule = function(FilterMask: PChar;UserName:PChar; AccessFlags:ULONG): ULONG; cdecl; TAddExcludedProcessId = function(ProcessId: ULONG): ULONG; cdecl; TRemoveExcludeProcessId = function(ProcessId: ULONG): ULONG; cdecl; TAddIncludedProcessId = function(ProcessID: ULONG): ULONG; cdecl; TRemoveIncludedProcessId = function(ProcessID: ULONG): ULONG; cdecl; TAddProtectedProcessId = function(ProcessID: ULONG): ULONG; cdecl; TRemoveProtectedProcessId = function(ProcessID: ULONG): ULONG; cdecl; TAESEncryptFile = function(FileName: LPCTSTR; KeyLength: DWORD; EncryptionKey: PBYTE; ivLength: DWORD; iv: PBYTE; AddIVTag: BOOL ): ULONG; cdecl; TAESDecryptFile = function(FileName: LPCTSTR; KeyLength: DWORD; EncryptionKey: PBYTE; ivLength: DWORD; iv: PBYTE): ULONG; cdecl; TAESEncryptFileToFile = function(FileName: LPCTSTR; DestFileName: LPCTSTR; KeyLength: DWORD; EncryptionKey: PBYTE; ivLength: DWORD; iv: PBYTE; AddIVTag: BOOL ): ULONG; cdecl; TAESDecryptFileToFile = function(FileName: LPCTSTR; DestFileName: LPCTSTR; KeyLength: DWORD; EncryptionKey: PBYTE; ivLength: DWORD; iv: PBYTE): ULONG; cdecl; TGetFileHandleInFilter = function(FileName: PChar; DesiredAccess: ULONG; var FileHandle: THandle): ULONG; cdecl; TOpenStubFile = function(FileName: LPCTSTR; dwDesiredAccess: DWORD; dwShareMode: DWORD; var pHandle: THandle): ULONG; cdecl; TCreateStubFile = function(FileName: LPCTSTR; FileSize: LONGLONG; FileAttributes: ULONG; tagDataLength: ULONG; // tagData: PEASETAG_DATA; tagData: Pointer; overwriteIfExist: BOOL; var pHandle: THandle): ULONG; cdecl; TGetTagData = function(hFile: THandle; var tagDataLength: ULONG; var tagData: Array of Byte): ULONG; cdecl; TRemoveTagData = function(hFile: THandle; UpdateTimeStamp: Boolean = false): ULONG; cdecl; TAddTagData = function(hFile: THandle; tagDataLength: ULONG; tagData: PBYTE): ULONG; cdecl; function GetLastFilterAPIErrorMsg: String; function LoadFilterAPI(DLLName: String; var DLLFilterAPIHandle: NativeInt; var ErrMsg: String): NativeInt; var InstallDriver: TInstallDriver = nil; UninstallDriver: TUninstallDriver = nil; SetRegistrationKey: TSetRegistrationKey = nil; IsDriverServiceRunning: TIsDriverServiceRunning = nil; RegisterMessageCallback: TRegisterMessageCallback = nil; Disconnect: TDisconnect = nil; GetFDLastErrorMessage: TGetLastErrorMessage = nil; SetFilterType: TSetFilterType = nil; ResetConfigData: TResetConfigData = nil; SetBooleanConfig: TSetBooleanConfig = nil; SetConnectionTimeout: TSetConnectionTimeout = nil; AddIncludedProcessId: TAddIncludedProcessId = nil; RemoveExcludedProcessId: TRemoveIncludedProcessId = nil; AddExcludedProcessId: TAddExcludedProcessId = nil; RemoveExcludeProcessId: TRemoveExcludeProcessId = nil; AddProtectedProcessId: TAddProtectedProcessId = nil; RemoveProtectedProcessId: TRemoveProtectedProcessId = nil; GetFileHandleInFilter: TGetFileHandleInFilter = nil; OpenStubFile: TOpenStubFile = nil; CreateStubFile: TCreateStubFile = nil; GetTagData: TGetTagData = nil; RemoveTagData: TRemoveTagData = nil; AddTagData: TAddTagData = nil; AddNewFilterRule: TAddNewFilterRule = nil; AddExcludeFileMaskToFilterRule: TAddExcludeFileMaskToFilterRule = nil; AddHiddenFileMaskToFilterRule: TAddHiddenFileMaskToFilterRule = nil; AddReparseFileMaskToFilterRule: TAddReparseFileMaskToFilterRule = nil; AddEncryptionKeyToFilterRule: TAddEncryptionKeyToFilterRule = nil; AddIncludeProcessNameToFilterRule: TAddIncludeProcessNameToFilterRule = nil; AddExcludeProcessNameToFilterRule: TAddExcludeProcessNameToFilterRule = nil; AddIncludeProcessIdToFilterRule: TAddIncludeProcessIdToFilterRule = nil; AddExcludeProcessIdToFilterRule: TAddExcludeProcessIdToFilterRule = nil; AddIncludeUserNameToFilterRule: TAddIncludeUserNameToFilterRule = nil; AddExcludeUserNameToFilterRule: TAddExcludeUserNameToFilterRule = nil; RegisterEventTypeToFilterRule: TRegisterEventTypeToFilterRule = nil; RegisterMoinitorIOToFilterRule: TRegisterMoinitorIOToFilterRule = nil; RegisterControlIOToFilterRule: TRegisterControlIOToFilterRule = nil; AddProcessRightsToFilterRule: TAddProcessRightsToFilterRule = nil; AddUserRightsToFilterRule: TAddUserRightsToFilterRule = nil; AESEncryptFile: TAESEncryptFile = nil; AESDecryptFile: TAESDecryptFile = nil; AESEncryptFileToFile: TAESEncryptFileToFile = nil; AESDecryptFileToFile: TAESDecryptFileToFile = nil; implementation function LoadFilterAPI(DLLName: String; var DLLFilterAPIHandle: NativeInt; var ErrMsg: String): NativeInt; begin Result := 0; ErrMsg := ''; if (DLLFilterAPIHandle > 0) then exit; // only need to get this handle once during active session SetLastError(0); DLLFilterAPIHandle := 0; DLLFilterAPIHandle := LoadLibrary(PChar(DLLName)); Result := GetLastError; if (Result <> ERROR_INVALID_HANDLE) and (DLLFilterAPIHandle > 0) then begin Result := 0; InstallDriver := GetProcAddress(DLLFilterAPIHandle, 'InstallDriver'); UninstallDriver := GetProcAddress(DLLFilterAPIHandle, 'UnInstallDriver'); SetRegistrationKey := GetProcAddress(DLLFilterAPIHandle, 'SetRegistrationKey'); IsDriverServiceRunning := GetProcAddress(DLLFilterAPIHandle, 'IsDriverServiceRunning'); RegisterMessageCallback := GetProcAddress(DLLFilterAPIHandle, 'RegisterMessageCallback'); Disconnect := GetProcAddress(DLLFilterAPIHandle, 'Disconnect'); GetFDLastErrorMessage := GetProcAddress(DLLFilterAPIHandle, 'GetLastErrorMessage'); SetFilterType := GetProcAddress(DLLFilterAPIHandle, 'SetFilterType'); ResetConfigData := GetProcAddress(DLLFilterAPIHandle, 'ResetConfigData'); SetBooleanConfig := GetProcAddress(DLLFilterAPIHandle, 'SetBooleanConfig'); SetConnectionTimeout := GetProcAddress(DLLFilterAPIHandle, 'SetConnectionTimeout'); GetFileHandleInFilter := GetProcAddress(DLLFilterAPIHandle, 'GetFileHandleInFilter'); OpenStubFile := GetProcAddress(DLLFilterAPIHandle, 'OpenStubFile'); CreateStubFile := GetProcAddress(DLLFilterAPIHandle, 'CreateStubFile'); GetTagData := GetProcAddress(DLLFilterAPIHandle, 'GetTagData'); RemoveTagData := GetProcAddress(DLLFilterAPIHandle, 'RemoveTagData'); AddTagData := GetProcAddress(DLLFilterAPIHandle, 'AddTagData'); AddExcludedProcessId := GetProcAddress(DLLFilterAPIHandle, 'AddExcludedProcessId'); RemoveExcludeProcessId := GetProcAddress(DLLFilterAPIHandle, 'RemoveExcludeProcessId'); AddExcludedProcessId := GetProcAddress(DLLFilterAPIHandle, 'AddExcludedProcessId'); AddIncludedProcessId := GetProcAddress(DLLFilterAPIHandle, 'AddIncludedProcessId'); AddProtectedProcessId := GetProcAddress(DLLFilterAPIHandle, 'AddProtectedProcessId'); RemoveProtectedProcessId := GetProcAddress(DLLFilterAPIHandle, 'RemoveProtectedProcessId'); AddNewFilterRule := GetProcAddress(DLLFilterAPIHandle, 'AddNewFilterRule'); AddExcludeFileMaskToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddExcludeFileMaskToFilterRule'); AddHiddenFileMaskToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddHiddenFileMaskToFilterRule'); AddReparseFileMaskToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddReparseFileMaskToFilterRule'); AddEncryptionKeyToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddEncryptionKeyToFilterRule'); AddIncludeProcessNameToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddIncludeProcessNameToFilterRule'); AddExcludeProcessNameToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddExcludeProcessNameToFilterRule'); AddIncludeProcessIdToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddIncludeProcessIdToFilterRule'); AddExcludeProcessIdToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddIncludeProcessIdToFilterRule'); AddIncludeUserNameToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddIncludeUserNameToFilterRule'); AddExcludeUserNameToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddExcludeUserNameToFilterRule'); RegisterEventTypeToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'RegisterEventTypeToFilterRule'); RegisterMoinitorIOToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'RegisterMoinitorIOToFilterRule'); RegisterControlIOToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'RegisterControlIOToFilterRule'); AddProcessRightsToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddProcessRightsToFilterRule'); AddUserRightsToFilterRule:= GetProcAddress(DLLFilterAPIHandle, 'AddUserRightsToFilterRule'); AESEncryptFile := GetProcAddress(DLLFilterAPIHandle, 'AESEncryptFile'); AESDecryptFile := GetProcAddress(DLLFilterAPIHandle, 'AESDecryptFile'); AESEncryptFileToFile := GetProcAddress(DLLFilterAPIHandle, 'AESEncryptFileToFile'); AESDecryptFileToFile := GetProcAddress(DLLFilterAPIHandle, 'AESDecryptFileToFile'); end else begin DLLFilterAPIHandle := 0; if Result = 0 then Result := ERROR_DLL_INIT_FAILED; ErrMsg := format('An error occured while loading %s (%s) (%d)', [DLLName, SysErrorMessage(Result), Result]); end; end; function GetLastFilterAPIErrorMsg: String; var buffer: array [0 .. 1024] of char; // Buffer: PChar;//array [0..1024] of char; BufferLength: ULONG; begin BufferLength := 1024; GetFDLastErrorMessage(buffer, BufferLength); if BufferLength > 2 then // account for CRLF for blank return Result := ' - ' + WideString(buffer) else Result := ''; end; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit FileTransferUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, Buttons, OverbyteIcsWndControl, OverbyteIcsHttpProt; type TFileTransferForm = class(TForm) TopInfoPanel: TPanel; FileNamePanel: TPanel; FileSizePanel: TPanel; FileNameLabel: TLabel; FileSizeLabel: TLabel; CancelBitBtn: TBitBtn; CloseBitBtn: TBitBtn; SendProgressBar: TProgressBar; BottomInfoPanel: TPanel; ProgressLabel: TLabel; SendFileHttpClient: THttpCli; DescEdit: TEdit; PassEdit: TEdit; DescLabel: TLabel; SendFileButton: TBitBtn; PassLabel: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CloseBitBtnClick(Sender: TObject); procedure CancelBitBtnClick(Sender: TObject); procedure SendFileHttpClientDocBegin(Sender: TObject); procedure SendFileHttpClientDocEnd(Sender: TObject); procedure SendFileHttpClientSendEnd(Sender: TObject); procedure SendFileHttpClientSessionClosed(Sender: TObject); procedure SendFileButtonClick(Sender: TObject); procedure SendFileHttpClientSendData(Sender: TObject; Buffer: Pointer; Len: Integer); procedure SendFileHttpClientSocksConnected(Sender: TObject; ErrCode: Word); procedure SendFileHttpClientSocksError(Sender: TObject; Error: Integer; Msg: string); procedure SendFileHttpClientRequestDone(Sender: TObject; RqType: THttpRequest; ErrCode: Word); procedure FormDblClick(Sender: TObject); private { Private declarations } public { Public declarations } T_UIN: string; T_UserType: string; T_FilePath: string; T_FileName: string; procedure TranslateForm; end; {$ENDREGION} var FileTransferForm: TFileTransferForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, SettingsUnit, TrafficUnit, VarsUnit, UtilsUnit, IcqProtoUnit, JabberProtoUnit, MraProtoUnit, ChatUnit; {$ENDREGION} {$REGION 'MyConst'} const UpWapRootURL = 'http://upwap.ru'; C_SF = 'SFClient | '; C_DB = 'Doc_Begin; Rcvd_Stream Create'; C_SDA = 'Send_Data; Abort'; C_DE = 'Doc_End'; C_SE = 'Send_End'; C_SesClose = 'Session_Closed; Status_Code = '; C_ReqD = 'Request_Done; Error = '; C_RcvdSE = 'Rcvd_Stream; Enabled'; C_RcvdSF = 'Rcvd_Stream; Free'; C_SendSF = 'Send_Stream; Free'; {$ENDREGION} {$REGION 'SendFileButtonClick'} procedure TFileTransferForm.SendFileButtonClick(Sender: TObject); begin // Блокируем контролы Описания и Пароля CancelBitBtn.Enabled := True; DescEdit.Enabled := False; DescEdit.Color := ClBtnFace; PassEdit.Enabled := False; PassEdit.Color := ClBtnFace; SendFileButton.Enabled := False; // Применяем параметры прокси SendFileHttpClient.Abort; SettingsForm.ApplyProxyHttpClient(SendFileHttpClient); case Tag of 1: begin // Передача через сервис UpWap.ru // Запрашиваем страницу с кодом сессии SendProgressBar.Position := 0; // Ставим флаг события для данных SendFileHttpClient.Tag := 0; // Формируем URL запроса SendFileHttpClient.URL := UpWapRootURL + '/upload/'; // Выводим информацию о начале процесса BottomInfoPanel.Caption := Lang_Vars[89].L_S; Xlog(C_HTTP + C_BN + Log_Get, Lang_Vars[89].L_S + C_BN + SendFileHttpClient.URL, EmptyStr); // Начинаем запрос данных SendFileHttpClient.GetASync; end; end; end; {$ENDREGION} {$REGION 'Other'} procedure TFileTransferForm.SendFileHttpClientDocBegin(Sender: TObject); begin // Создаём блок памяти для приёма http данных //Xlog(C_SF + C_DB, EmptyStr); SendFileHttpClient.RcvdStream := TMemoryStream.Create; end; procedure TFileTransferForm.SendFileHttpClientDocEnd(Sender: TObject); begin //Xlog(C_SF + C_DE, EmptyStr); end; procedure TFileTransferForm.SendFileHttpClientSendData(Sender: TObject; Buffer: Pointer; Len: Integer); begin // Отображаем процесс передачи файла SendProgressBar.Max := SendFileHttpClient.SendStream.Size; SendProgressBar.Position := SendFileHttpClient.SentCount; // Обновляем форму и контролы чтобы видеть изменения Update; // Если прерывание передачи, то останавливаем сокет if SendFileHttpClient.Tag = 2 then begin //Xlog(C_SF + C_SDA, EmptyStr); SendFileHttpClient.CloseAsync; SendFileHttpClient.Abort; end; end; procedure TFileTransferForm.SendFileHttpClientSendEnd(Sender: TObject); begin //Xlog(C_SF + C_SE, EmptyStr); // Увеличиваем статистику исходящего трафика V_TrafSend := V_TrafSend + SendFileHttpClient.SentCount; V_AllTrafSend := V_AllTrafSend + SendFileHttpClient.SentCount; if Assigned(TrafficForm) then MainForm.Traffic_MenuClick(nil); end; procedure TFileTransferForm.SendFileHttpClientSessionClosed(Sender: TObject); begin // Обрабатываем возможные ошибки в работе http сокета with SendFileHttpClient do begin if (StatusCode = 0) or (StatusCode >= 400) then begin BottomInfoPanel.Caption := Format(ErrorHttpClient(StatusCode), [C_BN]); //Xlog(C_SF + C_SesClose + IntToStr(StatusCode), EmptyStr); end; end; end; procedure TFileTransferForm.SendFileHttpClientSocksConnected(Sender: TObject; ErrCode: Word); begin // Если возникла ошибка, то сообщаем об этом if ErrCode <> 0 then begin DAShow(Lang_Vars[17].L_S, NotifyConnectError((Sender as THttpCli).name, ErrCode), EmptyStr, 134, 2, 0); end; end; procedure TFileTransferForm.SendFileHttpClientSocksError(Sender: TObject; Error: Integer; Msg: string); begin // Если возникла ошибка, то сообщаем об этом if Error <> 0 then begin DAShow(Lang_Vars[17].L_S, Lang_Vars[23].L_S + C_RN + Msg + C_RN + Format(Lang_Vars[27].L_S, [Error]) + C_RN + '[ ' + Lang_Vars[94].L_S + C_TN + (Sender as THttpCli).name + ' ]', EmptyStr, 134, 2, 0); end; end; procedure TFileTransferForm.CancelBitBtnClick(Sender: TObject); begin // Блокируем кнопку CancelBitBtn.Enabled := False; // Останавливаем передачу файла SendFileHttpClient.Tag := 2; SendFileHttpClient.CloseAsync; SendFileHttpClient.Abort; // Разблокируем контролы Описания и Пароля DescEdit.Enabled := True; DescEdit.Color := ClWindow; PassEdit.Enabled := True; PassEdit.Color := ClWindow; if Sender <> nil then begin BottomInfoPanel.Caption := Lang_Vars[91].L_S; //Xlog(C_SF + Lang_Vars[91].L_S, EmptyStr); SendFileButton.Enabled := True; end; end; procedure TFileTransferForm.CloseBitBtnClick(Sender: TObject); begin // Закрываем окно Close; end; procedure TFileTransferForm.FormClose(Sender: TObject; var Action: TCloseAction); begin // Если передача закончена, то уничтожаем окно if not CancelBitBtn.Enabled then begin // Уничтожаем форму Action := CaFree; FileTransferForm := nil; end; end; procedure TFileTransferForm.FormDblClick(Sender: TObject); begin // Устанавливаем перевод TranslateForm; end; {$ENDREGION} {$REGION 'FormCreate'} procedure TFileTransferForm.FormCreate(Sender: TObject); begin // Переводим окно на другие языки TranslateForm; // Применяем иконки к окну и кнопкам MainForm.AllImageList.GetIcon(149, Icon); MainForm.AllImageList.GetBitmap(139, CancelBitBtn.Glyph); MainForm.AllImageList.GetBitmap(3, CloseBitBtn.Glyph); MainForm.AllImageList.GetBitmap(166, SendFileButton.Glyph); // Делаем окно независимым и помещаем его кнопку на панель задач SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); // Применяем настройки прокси SettingsForm.ApplyProxyHttpClient(SendFileHttpClient); end; {$ENDREGION} {$REGION 'TranslateForm'} procedure TFileTransferForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); // Другое CancelBitBtn.Caption := Lang_Vars[9].L_S; CloseBitBtn.Caption := Lang_Vars[8].L_S; end; {$ENDREGION} {$REGION 'SendFileHttpClientRequestDone'} procedure TFileTransferForm.SendFileHttpClientRequestDone(Sender: TObject; RqType: THttpRequest; ErrCode: Word); label X; var List: TStringList; Doc, Skey, OKURL, HistoryFile, MsgD: string; FileToSend: TMemoryStream; Buf, Boundry: Utf8String; begin try //Xlog(C_SF + C_ReqD + IntToStr(ErrCode), EmptyStr); // Высвобождаем память отправки данных if SendFileHttpClient.SendStream <> nil then begin SendFileHttpClient.SendStream.Free; SendFileHttpClient.SendStream := nil; //Xlog(C_SF + C_SendSF, EmptyStr); end; // Читаем полученные http данные из блока памяти if SendFileHttpClient.RcvdStream <> nil then begin //Xlog(C_SF + C_RcvdSE, EmptyStr); // Создаём временный лист List := TStringList.Create; try // Увеличиваем статистику входящего трафика V_TrafRecev := V_TrafRecev + SendFileHttpClient.RcvdCount; V_AllTrafRecev := V_AllTrafRecev + SendFileHttpClient.RcvdCount; if Assigned(TrafficForm) then MainForm.Traffic_MenuClick(nil); // Обнуляем позицию начала чтения в блоке памяти SendFileHttpClient.RcvdStream.Position := 0; // Читаем данные в лист List.LoadFromStream(SendFileHttpClient.RcvdStream); // Разбираем данные в листе if List.Text > EmptyStr then begin Doc := UTF8ToString(List.Text); //Xlog(C_SF + C_RN + C_RN + Doc, EmptyStr); case SendFileHttpClient.Tag of // Определяем выполнение задания для данных по флагу 0: begin // Узнаём ключ сессии Skey := EmptyStr; Skey := IsolateTextString(Doc, 'action="', '"'); // Формируем данные для отправки with SendFileHttpClient do begin // Создаём блок памяти для отправки файла методом POST SendStream := TMemoryStream.Create; // Ссылка для приёма данных URL := UpWapRootURL + Skey; //Xlog(C_SF + URL, EmptyStr); // Заполняем переменные для POST Boundry := '------------sZLbqiVRVfOO8NjlMuYJE3'; { Specified in Multipart/form-data RFC } ContentTypePost := UTF8Encode('multipart/form-data; boundary=' + Copy(Boundry, 3, Length(Boundry))); Buf := UTF8Encode(Boundry + C_RN + 'Content-Disposition: form-data; name="file"; filename="' + T_FileName + '"' + C_RN + 'Content-Type: image/jpeg' + C_RN + C_RN); // Записываем переменные в память SendStream.write(Buf[1], Length(Buf)); // Создаём блок памяти для файла FileToSend := TMemoryStream.Create; try FileToSend.LoadFromFile(T_FilePath); FileToSend.SaveToStream(SendStream); finally FileToSend.Free; end; // Записываем переменную описания файла Buf := UTF8Encode(C_RN + Boundry + C_RN + 'Content-Disposition: form-data; name="desc"' + C_RN + C_RN + DescEdit.Text + C_RN + Boundry + C_RN + 'Content-Disposition: form-data; name="password"' + C_RN + C_RN + PassEdit.Text + C_RN + Boundry + C_RN + 'Content-Disposition: form-data; name="send"' + C_RN + C_RN + 'Отправить!' + C_RN + Boundry + '--' + C_RN); SendStream.write(Buf[1], Length(Buf)); SendStream.Seek(0, SoFromBeginning); // Отправляем данные на сервер SendFileHttpClient.Tag := 1; PostAsync; end; end; 1: begin // Ищем информацию об успешной закачке файла на сервер if Pos('Файл размещен', Doc) > 0 then begin BottomInfoPanel.Caption := Lang_Vars[90].L_S; // Воспроизводим звук удачной пересылки файла ImPlaySnd(6); // Формируем текст со ссылкой OKURL := UpWapRootURL + IsolateTextString(Doc, 'action="', '"'); case Tag of 1: OKURL := Format(Lang_Vars[92].L_S, [T_FileName, OKURL, 'upwap.ru', FileSizePanel.Caption]); end; //Xlog(C_SF + C_RN + OKURL, EmptyStr); MsgD := V_YouAt + ' [' + DateTimeChatMess + ']'; CheckMessage_BR(OKURL); DecorateURL(OKURL); // Отправляем сообщение с сылкой на файл if T_UserType = C_Icq then begin // Если нет подключения к серверу ICQ, то выходим if NotProtoOnline(C_Icq) then goto X; // Отправляем сообщение в юникод формате ICQ_SendMessage_0406(T_UIN, OKURL, True); // Формируем файл с историей HistoryFile := V_ProfilePath + C_HistoryFolder + C_Icq + C_BN + ICQ_LoginUIN + C_BN + T_UIN + '.htm'; end else if T_UserType = C_Jabber then begin // Если нет подключения к серверу Jabber, то выходим if NotProtoOnline(C_Jabber) then goto X; // Отправляем сообщение Jab_SendMessage(T_UIN, OKURL); // Формируем файл с историей HistoryFile := V_ProfilePath + C_HistoryFolder + C_Jabber + C_BN + Jabber_LoginUIN + C_BN + T_UIN + '.htm'; end else if T_UserType = C_Mra then begin // Если нет подключения к серверу MRA, то выходим if NotProtoOnline(C_Mra) then goto X; // Формируем файл с историей HistoryFile := V_ProfilePath + C_HistoryFolder + C_Mra + C_BN + MRA_LoginUIN + C_BN + T_UIN + '.htm'; end else goto X; // Записываем историю в файл этого контакта SaveTextInHistory('<span class=a>' + MsgD + '</span><br><span class=c>' + OKURL + '</span><br><br>', HistoryFile); // Если окно сообщений не было создано, то создаём его if not Assigned(ChatForm) then ChatForm := TChatForm.Create(MainForm); // Если вкладка чата совпадает с UIN получателя with ChatForm do begin if UIN_Panel.Caption = T_UIN then begin // Оповещаем о удачной передаче файла NotifyPanel.Caption := Lang_Vars[90].L_S; // Увеличиваем счётчик исходящих сообщений Inc(OutMessIndex); // Добавляем в чат сообщение AddChatText(MsgD, OKURL); // Прокручиваем чат до конца HTMLChatViewer.VScrollBarPosition := HTMLChatViewer.VScrollBar.Max; // Очищаем поле ввода теста InputRichEdit.Clear; InputRichEditChange(Self); end; end; // Возвращаем пункты управления в исходное состояние CancelBitBtn.Enabled := False; if not FileTransferForm.Visible then Close; end; end; end; end; X :; finally //Xlog(C_SF + C_RcvdSF, EmptyStr); // Высвобождаем блок памяти List.Free; SendFileHttpClient.RcvdStream.Free; SendFileHttpClient.RcvdStream := nil; end; end; except on E: Exception do MainForm.IMaderingEventsException(Self, E); end; end; {$ENDREGION} end.
unit Model.Estados; interface uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao; type TEstados = class private FAcao: TAcao; FUF: String; FNome: String; FQuery: TFDQuery; FConexao: TConexao; public property UF: String read FUF write FUF; property Nome: String read FNome write FNome; property Query: TFDQuery read FQuery write FQuery; property Acao: TAcao read FAcao write FAcao; constructor Create; destructor Destroy; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; function EstadoExiste(): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; function PesquisarExt(aParam: array of variant): Boolean; function Gravar(): Boolean; end; const TABLENAME = 'tbestados'; implementation { TEstados } function TEstados.Alterar: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + 'set nom_estado = :pnom_estado' + 'where uf_estado = :puf_estado;', [FNome, FUF]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TEstados.Create; begin FConexao := TConexao.Create; end; destructor TEstados.Destroy; begin FConexao.Free; end; function TEstados.EstadoExiste: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('select * from ' + TABLENAME + 'where uf_estado = :puf_estado;', [FUF]); if FDQuery.IsEmpty then Exit; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEstados.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + 'where uf_estado = :puf_estado;', [FUF]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEstados.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Inserir(); Common.ENum.tacAlterar: Result := Alterar(); Common.ENum.tacExcluir: Result := Excluir(); end; end; function TEstados.Inserir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('insert into ' + TABLENAME + '(uf_estado, nom_estado) values' + '(:puf_estado, :pnom_estado);', [FUF, FNome]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEstados.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; begin FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'UF' then begin FDQuery.SQL.Add('where uf_estado = :puf_estado'); FDQuery.ParamByName('puf_estado').AsString := aParam[1]; end else if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('where nom_estado = :pnom_estado'); FDQuery.ParamByName('pnom_estado').AsString := aParam[1]; end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; function TEstados.PesquisarExt(aParam: array of variant): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'UF' then begin FDQuery.SQL.Add('where uf_estado = :puf_estado'); FDQuery.ParamByName('puf_estado').AsString := aParam[1]; end else if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('where nom_estado = :pnom_estado'); FDQuery.ParamByName('pnom_estado').AsString := aParam[1]; end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; if FDQuery.IsEmpty then begin Exit; end; FQuery := FDQuery; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit nsUnderControlNode; //////////////////////////////////////////////////////////////////////////////// // Библиотека : Проект Немезис; // Назначение : Корень списка документов на контроле; // Версия : $Id: nsUnderControlNode.pas,v 1.7 2015/01/28 12:05:56 kostitsin Exp $ //////////////////////////////////////////////////////////////////////////////// interface uses IOUnit, UnderControlUnit, BaseTypesUnit, l3Tree_TLB, l3IID, l3Interfaces, nsNodes, FoldersDomainInterfaces ; type TnsUnderControlNode = class(TnsCacheableNode, InsUnderControlNode) private // fields f_CaptionString : IString; f_ControlledObj : IControllable; f_IsOpenFlag : Boolean; protected // InsUnderControlNode function pm_getStatus : Integer; {-} function pm_getIsOpened : Boolean; {-} procedure pm_setIsOpened(aValue : Boolean); {-} function pm_GetDocumentStatus: TItemStatus; {-} procedure ResetStatus; {-} protected // methods procedure Cleanup; override; {-} public // methods constructor Create(const aControllable : IControllable; const aNumInParent : Integer; const aTotalNumInParent : Integer); reintroduce; {-} class function Make(const aControllable : IControllable; const aNumInParent : Integer = -1; const aTotalNumInParent : Integer = -1): Il3Node; reintroduce; {-} function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {-} procedure DoDelete; override; {-} function GetAsPCharLen: Tl3PCharLenPrim; override; {-} end;//TnsUnderControlNode implementation uses SysUtils, l3String, DocumentUnit, nsTypes ; class function TnsUnderControlNode.Make(const aControllable : IControllable; const aNumInParent : Integer; const aTotalNumInParent : Integer): Il3Node; var l_Node : TnsUnderControlNode; begin l_Node := Create(aControllable, aNumInParent, aTotalNumInParent); try Result := l_Node; finally FreeAndNil(l_Node); end; end; constructor TnsUnderControlNode.Create(const aControllable : IControllable; const aNumInParent : Integer; const aTotalNumInParent : Integer); begin inherited Create(nil, aNumInParent, aTotalNumInParent); f_ControlledObj := aControllable; end; procedure TnsUnderControlNode.Cleanup; begin f_ControlledObj := nil; f_CaptionString := nil; f_IsOpenFlag := False; inherited; end; function TnsUnderControlNode.pm_getStatus : Integer; begin Result := f_ControlledObj.GetControlStatus; end; function TnsUnderControlNode.pm_getIsOpened : Boolean; begin Result := f_IsOpenFlag; end; procedure TnsUnderControlNode.pm_setIsOpened(aValue : Boolean); begin f_IsOpenFlag := aValue; end; procedure TnsUnderControlNode.ResetStatus; begin Changing; try f_ControlledObj.ResetControlStatus; finally Changed; end; end; function TnsUnderControlNode.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; begin if IID.EQ(IControllable) then begin if (f_ControlledObj = nil) then Result.SetNOINTERFACE else begin Result.SetOk; IControllable(Obj) := f_ControlledObj; end;//l_Controllable = nil end//IID.EQ(IControllable) else Result := inherited COMQueryInterface(IID, Obj); end; procedure TnsUnderControlNode.DoDelete; begin if f_ControlledObj.GetControlled then f_ControlledObj.SetControlled(False); f_CaptionString := nil; inherited; end; function TnsUnderControlNode.GetAsPCharLen: Tl3PCharLenPrim; //override; {-} begin if (f_CaptionString = nil) then begin if (f_ControlledObj <> nil) then f_ControlledObj.GetShortName(f_CaptionString) else begin Result := inherited GetAsPCharLen; Exit; end;//f_ControlledObj <> nil end;//f_CaptionString = nil if (f_CaptionString <> nil) then Result := nsWStr(f_CaptionString) else l3AssignNil(Result); end; function TnsUnderControlNode.pm_GetDocumentStatus: TItemStatus; var l_Document: IDocument; begin if Supports(f_ControlledObj, IDocument, l_Document) then Result := l_Document.GetStatus else Result := IS_UNKNOWN; end; end.
unit seleccionCuenta; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, seleccion, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxRibbonSkins, dxSkinsCore, dxSkinsDefaultPainters, dxSkinsdxRibbonPainter, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, dxSkinsdxBarPainter, cxLocalization, Datasnap.Provider, Datasnap.DBClient, Vcl.DBActns, System.Actions, Vcl.ActnList, JvAppStorage, JvAppIniStorage, JvComponentBase, JvFormPlacement, Vcl.ImgList, dxBar, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, dxStatusBar, dxRibbonStatusBar, dxRibbon; type TFSeleccionCuenta = class(TFSeleccion) cdsCUENTA: TStringField; cdsNOMBRE: TStringField; cdsGRUPO: TStringField; cdsRUBRO: TStringField; cdsSALDO: TFloatField; vistaCUENTA: TcxGridDBColumn; vistaNOMBRE: TcxGridDBColumn; vistaGRUPO: TcxGridDBColumn; vistaRUBRO: TcxGridDBColumn; vistaSALDO: TcxGridDBColumn; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FSeleccionCuenta: TFSeleccionCuenta; implementation uses DmIng; {$R *.dfm} procedure TFSeleccionCuenta.FormCreate(Sender: TObject); begin Campo := 'CUENTA'; Lookup := 'NOMBRE'; inherited; end; end.
unit ioresdecode; {$mode objfpc} {$H+} interface uses Classes, SysUtils; function IOResultDecode(AIOResult:Word):string; implementation Type TIOResultValue = record code : word; value : string; end; const CountIOResultValue = 30; var IOResultValueArray: array [0..CountIOResultValue-1] of TIOResultValue = ( (code:0;value:'Success.'), (code:2;value:'File not found.'), (code:3;value:'Path not found.'), (code:4;value:'Too many open files.'), (code:5;value:'Access denied.'), (code:6;value:'Invalid file handle.'), (code:12;value:'Invalid file-access mode.'), (code:15;value:'Invalid disk number.'), (code:16;value:'Cannot remove current directory.'), (code:17;value:'Cannot rename across volumes.'), (code:100;value:'Error when reading from disk.'), (code:101;value:'Error when writing to disk.'), (code:102;value:'File not assigned.'), (code:103;value:'File not open.'), (code:104;value:'File not opened for input.'), (code:105;value:'File not opened for output.'), (code:106;value:'Invalid number.'), (code:150;value:'Disk is write protected.'), (code:151;value:'Unknown device.'), (code:152;value:'Drive not ready.'), (code:153;value:'Unknown command.'), (code:154;value:'CRC check failed.'), (code:155;value:'Invalid drive specified..'), (code:156;value:'Seek error on disk.'), (code:157;value:'Invalid media type.'), (code:158;value:'Sector not found.'), (code:159;value:'Printer out of paper.'), (code:160;value:'Error when writing to device.'), (code:161;value:'Error when reading from device.'), (code:162;value:'Hardware failure.') ); function IOResultDecode(AIOResult:Word):string; var i: Integer; begin for i:=0 to CountIOResultValue-1 do if IOResultValueArray[i].code = AIOResult then exit(IOResultValueArray[i].value); result := Format('Unknow error code %d',[AIOResult]); end; end.
unit FormTeste; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, Data.FMTBcd, Data.SqlExpr; type TForm1 = class(TForm) btnAction: TButton; FDConnection: TFDConnection; FDQuery: TFDQuery; SQLConnection: TSQLConnection; SQLQuery: TSQLQuery; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; lblOpenedFDConnection: TLabel; lblOpenedSQLConnection: TLabel; lblOpenedFDQuery: TLabel; lblOpenedSQLQuery: TLabel; lblActiveFDConnection: TLabel; lblActiveSQLConnection: TLabel; lblActiveFDQuery: TLabel; lblActiveSQLQuery: TLabel; procedure QueryAfterOpen(DataSet: TDataSet); procedure ConnectionAfterConnect(Sender: TObject); procedure QueryAfterClose(DataSet: TDataSet); procedure ConnectionAfterDisconnect(Sender: TObject); procedure btnActionClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; const LABEL_OPENED = 'lblOpened'; LABEL_ACTIVE = 'lblActive'; SIM_NAO: array[Boolean] of string = ('NÃO', 'SIM'); implementation {$R *.dfm} procedure TForm1.btnActionClick(Sender: TObject); begin FDConnection.Open; SQLConnection.Open; FDQuery.Open; SQLQuery.Open; end; procedure TForm1.ConnectionAfterConnect(Sender: TObject); begin TLabel(FindComponent(LABEL_OPENED + TComponent(Sender).Name)).Caption := SIM_NAO[True]; TLabel(FindComponent(LABEL_ACTIVE + TComponent(Sender).Name)).Caption := SIM_NAO[True]; end; procedure TForm1.ConnectionAfterDisconnect(Sender: TObject); begin TLabel(FindComponent(LABEL_ACTIVE + TComponent(Sender).Name)).Caption := SIM_NAO[False]; end; procedure TForm1.QueryAfterClose(DataSet: TDataSet); begin TLabel(FindComponent(LABEL_ACTIVE + DataSet.Name)).Caption := SIM_NAO[False]; end; procedure TForm1.QueryAfterOpen(DataSet: TDataSet); begin TLabel(FindComponent(LABEL_OPENED + DataSet.Name)).Caption := SIM_NAO[True]; TLabel(FindComponent('lblActive'+DataSet.Name)).Caption := SIM_NAO[True]; end; end.
unit AceMeter; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TAceMeterStyle = (msHorizontal); TAceMeter = class(TPaintBox) private FMeterColor: TColor; FBackGroundColor: TColor; FBorderStyle: TBorderStyle; FStyle: TAceMeterStyle; FMax: Integer; FMin: Integer; FProgress: Integer; FShowText: Boolean; protected procedure SetProgress( Value: Integer ); procedure SetMeterColor( c: TColor ); procedure SetBackgroundColor( c: TColor ); procedure SetBorderStyle( st: TBorderStyle ); procedure SetStyle( st: TAceMeterStyle ); procedure SetMin( m: Integer ); procedure SetMax( m: Integer ); procedure SetShowText( st: Boolean ); procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property MeterColor: TColor read FMeterColor write SetMeterColor; property BackGroundColor: TColor read FBackGroundColor write SetBackGroundColor; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle; property Style: TAceMeterStyle read FStyle write SetStyle; property Min: Integer read FMin write SetMin; property Max: Integer read FMax write SetMax; property Progress: Integer read FProgress write SetProgress; property ShowText: Boolean read FShowText write SetShowText; end; implementation constructor TAceMeter.Create(AOwner: TComponent); begin inherited Create(AOwner); FMeterColor := clRed; FBackgroundColor := clWhite; FBorderStyle := bsSingle; FStyle := msHorizontal; FMax := 100; FMin := 0; FProgress := 0; FShowText := True; end; procedure TAceMeter.SetProgress( Value: Integer ); begin if Value <> FProgress then begin FProgress := Value; Invalidate; end; end; procedure TAceMeter.Paint; var percent: Single; x,y: Integer; begin inherited Paint; if (FProgress > FMin) And (FMax > FMin) then begin if FProgress >= FMax then percent := 1 else if (FMax - FProgress) > 0 then percent := ((FMax-Min)-(FMax-FProgress)) / (FMax - FMin) else percent := 0; end else percent := 0; Canvas.Font := font; with Canvas do begin Brush.Color := FBackgroundColor; Brush.Style := bsSolid; if BorderStyle = bsSingle then Rectangle(0,0,Width,Height) else FillRect( Self.ClientRect ); if FProgress > FMin then begin if FStyle = msHorizontal then begin Brush.Color := FMeterColor; FillRect( Rect(1,1, Round(Width * percent) - 1, Height - 1) ); end; end; if FShowText then begin SetTextAlign(handle, TA_CENTER); Brush.style := bsClear; font := self.font; x := Width div 2; y := (height + font.height) div 2; TextOut(x,y, FloatToStrF( percent * 100, ffNumber, 3,1) + '%'); end; end; end; procedure TAceMeter.SetMeterColor( c: TColor ); begin if FMeterColor <> c then begin FMeterColor := c; Invalidate; end; end; procedure TAceMeter.SetBackgroundColor( c: TColor ); begin if FBackgroundColor <> c then begin FBackgroundColor := c; Invalidate; end; end; procedure TAceMeter.SetBorderStyle( st: TBorderStyle ); begin if FBorderStyle <> st then begin FBorderStyle := st; Invalidate; end; end; procedure TAceMeter.SetStyle( st: TAceMeterStyle ); begin if FStyle <> st then begin FStyle := st; Invalidate; end; end; procedure TAceMeter.SetMin( m: Integer ); begin if FMin <> m then begin FMin := m; Invalidate; end; end; procedure TAceMeter.SetMax( m: Integer ); begin if FMax <> m then begin FMax := m; Invalidate; end; end; procedure TAceMeter.SetShowText( st: Boolean ); begin if FShowText <> st then begin FShowText := st; Invalidate; end; end; end.
object fmUsesExpertOptions: TfmUsesExpertOptions Left = 338 Top = 241 BorderIcons = [biSystemMenu] BorderStyle = bsDialog Caption = 'Uses Clause Manager Options' ClientHeight = 97 ClientWidth = 249 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poScreenCenter DesignSize = ( 249 97) PixelsPerInch = 96 TextHeight = 13 object chkSingleActionMode: TCheckBox Left = 8 Top = 8 Width = 233 Height = 17 Hint = 'If enabled, OK will add the currently selected unit on the right' + ' hand side to the uses clause shown on the left hand side and cl' + 'ose the dialog.' Anchors = [akLeft, akTop, akRight] Caption = 'Single action/quic&k add mode' ParentShowHint = False ShowHint = True TabOrder = 0 end object chkReplaceFileUnit: TCheckBox Left = 8 Top = 32 Width = 233 Height = 17 Hint = 'If enabled, the menu entry File -> Use Unit will call the GExper' + 'ts Uses Clause Manager' Anchors = [akLeft, akTop, akRight] Caption = 'Replace IDE File, Use Unit feature' ParentShowHint = False ShowHint = True TabOrder = 1 end object btnOK: TButton Left = 88 Top = 64 Width = 75 Height = 25 Anchors = [akRight, akBottom] Cancel = True Caption = 'OK' Default = True ModalResult = 1 TabOrder = 2 end object btnCancel: TButton Left = 168 Top = 64 Width = 75 Height = 25 Anchors = [akRight, akBottom] Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 3 end end
unit Json.Conection; interface Uses System.SysUtils, Vcl.Forms; type TjsonConect = class private { private declarations } FIP: String; FDB: String; FUSER: String; FSENHA: String; FPORTA_MYSQL: Integer; FPORTA_CHANNEL1: Integer; FPORTA_CHANNEL2: Integer; FPORTA_CHANNEL3: Integer; FPORTA_CHANNEL4: Integer; FPORTA_CHANNEL5: Integer; FIP_CHANNEL1: String; FIP_CHANNEL2: String; FIP_CHANNEL3: String; FIP_CHANNEL4: String; FIP_CHANNEL5: String; FMAXCHANNEL: Integer; protected { protected declarations } public { public declarations } ConfigFolder: String; LangFolder: String; FolderGame: String; Constructor Create; // declaração do metodo construtor property IP: String read FIP write FIP; property DB: String read FDB write FDB; property USER: String read FUSER write FUSER; property SENHA: String read FSENHA write FSENHA; property PORTA_MYSQL: Integer read FPORTA_MYSQL write FPORTA_MYSQL; property MAXCHANNEL: Integer read FMAXCHANNEL write FMAXCHANNEL; property PORTA_CHANNEL1: Integer read FPORTA_CHANNEL1 write FPORTA_CHANNEL1; property PORTA_CHANNEL2: Integer read FPORTA_CHANNEL2 write FPORTA_CHANNEL2; property PORTA_CHANNEL3: Integer read FPORTA_CHANNEL3 write FPORTA_CHANNEL3; property PORTA_CHANNEL4: Integer read FPORTA_CHANNEL4 write FPORTA_CHANNEL4; property PORTA_CHANNEL5: Integer read FPORTA_CHANNEL5 write FPORTA_CHANNEL5; property IP_CHANNEL1: String read FIP_CHANNEL1 write FIP_CHANNEL1; property IP_CHANNEL2: String read FIP_CHANNEL2 write FIP_CHANNEL2; property IP_CHANNEL3: String read FIP_CHANNEL3 write FIP_CHANNEL3; property IP_CHANNEL4: String read FIP_CHANNEL4 write FIP_CHANNEL4; property IP_CHANNEL5: String read FIP_CHANNEL5 write FIP_CHANNEL5; Destructor Destroy; Override; // declaração do metodo destrutor end; implementation { TjsonRead } constructor TjsonConect.Create; begin ConfigFolder := ExtractFilePath(Application.ExeName) + 'Config\'; LangFolder := ExtractFilePath(Application.ExeName) + 'Lang\'; FolderGame := ExtractFilePath(Application.ExeName); end; destructor TjsonConect.Destroy; begin inherited; ConfigFolder := ''; LangFolder := ''; end; end.
unit CodecIntf; interface uses Windows, CompressIntf; const E_ALLOCATE = hResult(-100); E_BADINFO = hResult(-101); type ICodec = interface['{3A1075C0-652C-11d3-B638-00400566F3E8}'] function GetInfo(lpInfo : pointer; out InfoSize : integer) : hResult; stdcall; function GetCompressor(lpInfo : pointer; InfoSize : integer; out Compressor : ICompressor) : hResult; stdcall; function GetDecompressor(lpInfo : pointer; InfoSize : integer; out Decompressor : IDecompressor) : hResult; stdcall; end; type TCodecLibProc = function : ICodec; stdcall; // 'GetCodec' prototype const CodecLibProcName = 'GetCodec'; // We need to add something to decide which codec to use, and something to find // the codec based on the codec info. type ICodecs = interface // Just Delphi interface, no IID procedure Initialize(const aPath : string); function Count : integer; function OpenCompressor(ndx : integer) : ICompressor; function OpenDecompressor(ndx : integer) : IDecompressor; end; function Codecs : ICodecs; implementation uses Classes, SysUtils, VCLUtils; const CodecWildCard = '*.vcc'; function AddNameToPath(const Path, Name : string) : string; begin if (Path <> '') and (Path[length(Path)] <> '\') then Result := Path + '\' + Name else Result := Path + Name end; function IsCodec(const aLib : string) : boolean; var hLib : hInst; begin hLib := LoadLibrary(pchar(aLib)); if hLib <> 0 then try Result := GetProcAddress(hLib, CodecLibProcName) <> nil; finally FreeLibrary(hLib); end else Result := false; end; type TCodecs = class(TInterfacedObject, ICodecs) public constructor Create; destructor Destroy; override; private // ICodecs procedure Initialize(const aPath : string); function Count : integer; function OpenCompressor(ndx : integer) : ICompressor; function OpenDecompressor(ndx : integer) : IDecompressor; private fLibs : TStringList; function GetCodec(ndx : integer) : ICodec; procedure FreeLibraries; end; constructor TCodecs.Create; begin inherited; fLibs := TStringList.Create; end; destructor TCodecs.Destroy; begin FreeLibraries; fLibs.Free; inherited; end; procedure TCodecs.Initialize(const aPath : string); var F : TSearchRec; code : integer; CodecLib : string; begin code := FindFirst(AddNameToPath(aPath, CodecWildCard), faAnyFile, F); try while code = 0 do begin CodecLib := AddNameToPath(aPath, F.FindData.cFileName); if IsCodec(CodecLib) then fLibs.Add(CodecLib); code := FindNext(F); end; finally FindClose(F); end; end; function TCodecs.Count : integer; begin Result := fLibs.Count; end; function TCodecs.OpenCompressor(ndx : integer) : ICompressor; var aCodec : ICodec; Dummy : array[byte] of byte; DummySize : integer; begin Assert((ndx >= 0) and (ndx < fLibs.Count)); aCodec := GetCodec(ndx); DummySize := sizeof(Dummy); aCodec.GetInfo(@Dummy, DummySize); aCodec.GetCompressor(@Dummy, DummySize, Result); end; function TCodecs.OpenDecompressor(ndx : integer) : IDecompressor; var aCodec : ICodec; Dummy : array[byte] of byte; DummySize : integer; begin Assert((ndx >= 0) and (ndx < fLibs.Count)); aCodec := GetCodec(ndx); DummySize := sizeof(Dummy); aCodec.GetInfo(@Dummy, DummySize); aCodec.GetDecompressor(@Dummy, DummySize, Result); end; function TCodecs.GetCodec(ndx : integer) : ICodec; var Proc : TCodecLibProc; begin Assert((ndx >= 0) and (ndx < fLibs.Count)); if fLibs.Objects[ndx] = nil then fLibs.Objects[ndx] := pointer(LoadLibrary(pchar(fLibs[ndx]))); Proc := GetProcAddress(hInst(fLibs.Objects[ndx]), CodecLibProcName); if Proc <> nil then Result := Proc() else Result := nil; end; procedure TCodecs.FreeLibraries; var lib : hInst; i : integer; begin for i := 0 to pred(fLibs.Count) do begin lib := hInst(fLibs.Objects[i]); if lib <> 0 then FreeLibrary(lib); end; fLibs.Clear; end; var gCodecs : ICodecs = nil; function Codecs : ICodecs; begin if gCodecs = nil then gCodecs := TCodecs.Create; Result := gCodecs; end; initialization finalization gCodecs := nil; end.
{$M+} unit uClass_LancamentoOS; interface uses FireDAC.Comp.Client, FireDAC.Stan.Param, System.SysUtils, Data.DB; type TTotalizador = record HProposta : String; HTrabalhada : String; HSaldo : String; HSaldoNegativo : Boolean; end; type TClass_LancamentoOS = class(TObject) private FConexao : TFDConnection; FQLancamentoOS : TFDQuery; FHoraFinal: TTime; FHoraInicial: TTime; FHoraPerdida: String; FSprint: Integer; FCliente: String; FNumeroOS: String; FDataTrabalhada: TDate; FHoraProposta: String; FHoraDisponivel: String; FDataFinal: TDate; FDataInicial: TDate; FQueryLancamento_Diario: TFDQuery; FHoraTrabalhada: String; function fncCopiaAte(psTexto, psCaracter: String): string; function fncRetornaSubtracaoHora(psHora01, psHora02: String; var HoraNegativa : Boolean) : String; procedure SetCliente(const Value: String); procedure SetDataFinal(const Value: TDate); procedure SetDataInicial(const Value: TDate); procedure SetDataTrabalhada(const Value: TDate); procedure SetHoraDisponivel(const Value: String); procedure SetHoraFinal(const Value: TTime); procedure SetHoraInicial(const Value: TTime); procedure SetHoraPerdida(const Value: String); procedure SetHoraProposta(const Value: String); procedure SetNumeroOS(const Value: String); procedure SetSprint(const Value: Integer); procedure SetQueryLancamento_Diario(const Value: TFDQuery); function fncRetornaMinuto(psTexto: String): string; procedure SetHoraTrabalhada(const Value: String); public constructor Create(poConexao: TFDConnection); destructor Destroy; override; procedure pcdGravarDados; procedure pcdExcluirDados; procedure pcdGravarDados_Diario; procedure pcdExcluirDados_Diario; procedure EncontraDados; function fncTotalizador : TTotalizador; published property NumeroOS : String read FNumeroOS write SetNumeroOS; property Sprint : Integer read FSprint write SetSprint; property Cliente : String read FCliente write SetCliente; property DataInicial : TDate read FDataInicial write SetDataInicial; property HoraInicial : TTime read FHoraInicial write SetHoraInicial; property DataFinal : TDate read FDataFinal write SetDataFinal; property HoraFinal : TTime read FHoraFinal write SetHoraFinal; property HoraProposta : String read FHoraProposta write SetHoraProposta; property DataTrabalhada : TDate read FDataTrabalhada write SetDataTrabalhada; property HoraDisponivel : String read FHoraDisponivel write SetHoraDisponivel; property HoraPerdida : String read FHoraPerdida write SetHoraPerdida; property HoraTrabalhada : String read FHoraTrabalhada write SetHoraTrabalhada; property QueryLancamento_Diario : TFDQuery read FQueryLancamento_Diario write SetQueryLancamento_Diario; end; implementation { TClass_LancamentoOS } constructor TClass_LancamentoOS.Create(poConexao: TFDConnection); begin FHoraFinal := 0; FHoraInicial := 0; FHoraPerdida := ''; FSprint := 0; FCliente := ''; FNumeroOS := ''; FDataTrabalhada := 0; FHoraProposta := ''; FHoraDisponivel := ''; FDataFinal := 0; FDataInicial := 0; FConexao := poConexao; FQLancamentoOS := TFDQuery.Create(nil); FQLancamentoOS.Close; FQLancamentoOS.Connection := FConexao; end; destructor TClass_LancamentoOS.Destroy; begin if Assigned(FQLancamentoOS) then FreeAndNil(FQLancamentoOS); FConexao.Close; inherited; end; procedure TClass_LancamentoOS.EncontraDados; begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('SELECT * FROM LANCAMENTOOS WHERE NUMEROOS = :OS AND SPRINT = :SPRINT'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.Open(); if not FQLancamentoOS.IsEmpty then begin FCliente := FQLancamentoOS.FieldByName('Cliente').AsString; FDataInicial := FQLancamentoOS.FieldByName('DataInicial').AsDateTime; FHoraInicial := FQLancamentoOS.FieldByName('HoraInicial').AsDateTime; FDataFinal := FQLancamentoOS.FieldByName('DataFinal').AsDateTime; FHoraFinal := FQLancamentoOS.FieldByName('HoraFinal').AsDateTime; FHoraProposta := FQLancamentoOS.FieldByName('HoraProposta').AsString; FQueryLancamento_Diario.Close; FQueryLancamento_Diario.SQL.Clear; FQueryLancamento_Diario.SQL.Add('SELECT * FROM LANCAMENTOOS_DIARIO WHERE NUMEROOS = :OS AND SPRINT = :SPRINT ORDER BY DATATRABALHADA'); FQueryLancamento_Diario.ParamByName('OS').AsString := FNumeroOS; FQueryLancamento_Diario.ParamByName('SPRINT').AsInteger := FSprint; FQueryLancamento_Diario.Open(); end else begin FCliente := ''; FDataInicial := 0; FHoraInicial := 0; FDataFinal := 0; FHoraFinal := 0; FHoraProposta := ''; FQueryLancamento_Diario := nil; end; end; function TClass_LancamentoOS.fncCopiaAte(psTexto, psCaracter: String): string; var I: Integer; begin Result := ''; for I := 1 to Length(psTexto) do begin if Copy(psTexto, I, 1) <> psCaracter then Result := Result + Copy(psTexto, I, 1) else Break; end; end; function TClass_LancamentoOS.fncRetornaMinuto(psTexto: String): string; var I: Integer; vlbAchouCaracter : Boolean; begin vlbAchouCaracter := False; Result := ''; for I := 1 to Length(psTexto) do begin if vlbAchouCaracter then begin Result := Result + Copy(psTexto, I, 1) end else begin if Copy(psTexto, I, 1) = ':' then vlbAchouCaracter := True; end end; end; procedure TClass_LancamentoOS.pcdExcluirDados; begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('DELETE FROM LANCAMENTOOS WHERE NUMEROOS = :OS AND SPRINT = :SPRINT'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; try FQLancamentoOS.ExecSQL; try FDataTrabalhada := StrToDate('01/01/1900'); pcdExcluirDados_Diario; except on E:Exception do begin raise Exception.Create(e.Message); end; end; except on E:Exception do begin raise Exception.Create('Houve um erro ao excluir o registro: '+FNumeroOS+' com a mensagem: '+e.Message); end; end; end; procedure TClass_LancamentoOS.pcdExcluirDados_Diario; begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; if FDataTrabalhada <> StrToDate('01/01/1900') then begin FQLancamentoOS.SQL.Add('DELETE FROM LANCAMENTOOS_DIARIO WHERE NUMEROOS = :OS AND SPRINT = :SPRINT AND DATATRABALHADA = :DATATRABALHADA'); FQLancamentoOS.ParamByName('DATATRABALHADA').AsDateTime := FDataTrabalhada; end else FQLancamentoOS.SQL.Add('DELETE FROM LANCAMENTOOS_DIARIO WHERE NUMEROOS = :OS AND SPRINT = :SPRINT'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; try FQLancamentoOS.ExecSQL except on E:Exception do begin raise Exception.Create('Houve um erro ao excluir o registro diário: '+FNumeroOS+' com a mensagem: '+e.Message); end; end; end; procedure TClass_LancamentoOS.pcdGravarDados; begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('SELECT NUMEROOS FROM LANCAMENTOOS WHERE NUMEROOS = :OS AND SPRINT = :SPRINT'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.Open(); FQLancamentoOS.Refresh; if FQLancamentoOS.IsEmpty then begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('INSERT INTO LANCAMENTOOS (NUMEROOS, SPRINT, CLIENTE, DATAINICIAL, HORAINICIAL, DATAFINAL,'); FQLancamentoOS.SQL.Add(' HORAFINAL, HORAPROPOSTA)'); if FDataFinal = 0 then begin FQLancamentoOS.SQL.Add('VALUES (:NUMEROOS, :SPRINT, :CLIENTE, :DATAINICIAL, :HORAINICIAL, null,'); FQLancamentoOS.SQL.Add(' null, :HORAPROPOSTA);'); end else begin FQLancamentoOS.SQL.Add('VALUES (:NUMEROOS, :SPRINT, :CLIENTE, :DATAINICIAL, :HORAINICIAL, :DATAFINAL,'); FQLancamentoOS.SQL.Add(' :HORAFINAL, :HORAPROPOSTA);'); end; end else begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('UPDATE LANCAMENTOOS'); FQLancamentoOS.SQL.Add('SET CLIENTE = :CLIENTE, DATAINICIAL = :DATAINICIAL,'); if FDataFinal = 0 then begin FQLancamentoOS.SQL.Add(' HORAINICIAL = :HORAINICIAL, DATAFINAL = null,'); FQLancamentoOS.SQL.Add(' HORAFINAL = null, HORAPROPOSTA = :HORAPROPOSTA'); end else begin FQLancamentoOS.SQL.Add(' HORAINICIAL = :HORAINICIAL, DATAFINAL = :DATAFINAL,'); FQLancamentoOS.SQL.Add(' HORAFINAL = :HORAFINAL, HORAPROPOSTA = :HORAPROPOSTA'); end; FQLancamentoOS.SQL.Add('WHERE (NUMEROOS = :NUMEROOS) AND (SPRINT = :SPRINT)'); end; FQLancamentoOS.ParamByName('NUMEROOS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.ParamByName('CLIENTE').AsString := FCliente; FQLancamentoOS.ParamByName('DATAINICIAL').AsDateTime := FDataInicial; FQLancamentoOS.ParamByName('HORAINICIAL').AsTime := FHoraInicial; FQLancamentoOS.ParamByName('HORAPROPOSTA').AsString := FHoraProposta; if FDataFinal <> 0 then begin FQLancamentoOS.ParamByName('DATAFINAL').AsDateTime := FDataFinal; FQLancamentoOS.ParamByName('HORAFINAL').AsTime := FHoraFinal; end; try FQLancamentoOS.ExecSQL except on E:Exception do begin raise Exception.Create('Houve um erro ao adicionar/editar o registro: '+FNumeroOS+' com a mensagem: '+e.Message); end; end; end; procedure TClass_LancamentoOS.pcdGravarDados_Diario; begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('SELECT NUMEROOS FROM LANCAMENTOOS_DIARIO WHERE NUMEROOS = :OS AND SPRINT = :SPRINT AND DATATRABALHADA = :DATATRABALHADA'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.ParamByName('DATATRABALHADA').AsDateTime := FDataTrabalhada; FQLancamentoOS.Open(); if FQLancamentoOS.IsEmpty then begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('INSERT INTO LANCAMENTOOS_DIARIO (NUMEROOS, SPRINT, DATATRABALHADA, HORADISPONIVEL, HORAPERDIDA, HORATRABALHADA)'); FQLancamentoOS.SQL.Add('VALUES (:NUMEROOS, :SPRINT, :DATATRABALHADA, :HORADISPONIVEL, :HORAPERDIDA, :HORATRABALHADA)'); end else begin FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('UPDATE LANCAMENTOOS_DIARIO'); FQLancamentoOS.SQL.Add('SET DATATRABALHADA = :DATATRABALHADA,'); FQLancamentoOS.SQL.Add(' HORADISPONIVEL = :HORADISPONIVEL,'); FQLancamentoOS.SQL.Add(' HORAPERDIDA = :HORAPERDIDA,'); FQLancamentoOS.SQL.Add(' HORATRABALHADA = :HORATRABALHADA'); FQLancamentoOS.SQL.Add('WHERE (NUMEROOS = :NUMEROOS) AND (SPRINT = :SPRINT);'); end; FQLancamentoOS.ParamByName('NUMEROOS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.ParamByName('DATATRABALHADA').AsDateTime := FDataTrabalhada; FQLancamentoOS.ParamByName('HORADISPONIVEL').AsString := FHoraDisponivel; FQLancamentoOS.ParamByName('HORAPERDIDA').AsString := FHoraPerdida; FQLancamentoOS.ParamByName('HORATRABALHADA').AsString := FHoraTrabalhada; try FQLancamentoOS.ExecSQL except on E:Exception do begin raise Exception.Create('Houve um erro ao adicionar/editar diários o registro: '+FNumeroOS+' com a mensagem: '+e.Message); end; end; end; function TClass_LancamentoOS.fncRetornaSubtracaoHora(psHora01, psHora02: String; var HoraNegativa : Boolean): String; var vliHora01, vliMinuto01, vliHora02, vliMinuto02 : Integer; begin vliHora01 := StrToInt(fncCopiaAte(psHora01, ':')); vliMinuto01 := StrToInt(fncRetornaMinuto(psHora01)); vliHora02 := StrToInt(fncCopiaAte(psHora02, ':')); vliMinuto02 := StrToInt(fncRetornaMinuto(psHora02)); HoraNegativa := vliHora02 > vliHora01; Result := FormatFloat('00', (vliHora01 - vliHora02)) + ':' + FormatFloat('00', (vliMinuto01 - vliMinuto02)); end; function TClass_LancamentoOS.fncTotalizador: TTotalizador; var HorasPropostas : String; vliHoras, vliMinutos : Integer; begin Result.HProposta := ''; Result.HTrabalhada := ''; Result.HSaldo := ''; Result.HSaldoNegativo := False; HorasPropostas := ''; vliHoras := 0; vliMinutos := 0; FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('SELECT HORAPROPOSTA FROM LANCAMENTOOS WHERE NUMEROOS = :OS AND SPRINT = :SPRINT'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.Open(); HorasPropostas := FQLancamentoOS.FieldByName('HORAPROPOSTA').AsString; Result.HProposta := HorasPropostas; FQLancamentoOS.Close; FQLancamentoOS.SQL.Clear; FQLancamentoOS.SQL.Add('SELECT HORATRABALHADA FROM LANCAMENTOOS_DIARIO WHERE NUMEROOS = :OS AND SPRINT = :SPRINT'); FQLancamentoOS.ParamByName('OS').AsString := FNumeroOS; FQLancamentoOS.ParamByName('SPRINT').AsInteger := FSprint; FQLancamentoOS.Open(); FQLancamentoOS.First; while not FQLancamentoOS.Eof do begin vliHoras := vliHoras + StrToInt(fncCopiaAte(FormatDateTime('hh:mm', FQLancamentoOS.FieldByName('HORATRABALHADA').AsDateTime), ':')); vliMinutos := vliMinutos + StrToInt(fncRetornaMinuto(FormatDateTime('hh:mm', FQLancamentoOS.FieldByName('HORATRABALHADA').AsDateTime))); FQLancamentoOS.Next; end; Result.HTrabalhada := FormatFloat('00', vliHoras) + ':' + FormatFloat('00', vliMinutos); Result.HSaldo := fncRetornaSubtracaoHora(HoraProposta, Result.HTrabalhada, Result.HSaldoNegativo); end; procedure TClass_LancamentoOS.SetCliente(const Value: String); begin FCliente := Value; end; procedure TClass_LancamentoOS.SetDataFinal(const Value: TDate); begin FDataFinal := Value; end; procedure TClass_LancamentoOS.SetDataInicial(const Value: TDate); begin FDataInicial := Value; end; procedure TClass_LancamentoOS.SetDataTrabalhada(const Value: TDate); begin FDataTrabalhada := Value; end; procedure TClass_LancamentoOS.SetHoraDisponivel(const Value: String); begin FHoraDisponivel := Value; end; procedure TClass_LancamentoOS.SetHoraFinal(const Value: TTime); begin FHoraFinal := Value; end; procedure TClass_LancamentoOS.SetHoraInicial(const Value: TTime); begin FHoraInicial := Value; end; procedure TClass_LancamentoOS.SetHoraPerdida(const Value: String); begin FHoraPerdida := Value; end; procedure TClass_LancamentoOS.SetHoraProposta(const Value: String); begin FHoraProposta := Value; end; procedure TClass_LancamentoOS.SetHoraTrabalhada(const Value: String); begin FHoraTrabalhada := Value; end; procedure TClass_LancamentoOS.SetNumeroOS(const Value: String); begin FNumeroOS := Value; end; procedure TClass_LancamentoOS.SetQueryLancamento_Diario(const Value: TFDQuery); begin FQueryLancamento_Diario := Value; end; procedure TClass_LancamentoOS.SetSprint(const Value: Integer); begin FSprint := Value; end; end.
unit TTSPROCESSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSPROCESSRecord = record PAutoInc: Integer; PLenderNum: String[4]; PType: Integer; PStart: String[20]; PStop: String[20]; PStopStatus: String[10]; PUserID: String[10]; PDescription: String[100]; PControlStatus: String[10]; PControlMsg: String[100]; PControlScanMsg: String[30]; End; TTTSPROCESSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSPROCESSRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSPROCESS = (TTSPROCESSPrimaryKey, TTSPROCESSByLenderType); TTTSPROCESSTable = class( TDBISAMTableAU ) private FDFAutoInc: TAutoIncField; FDFLenderNum: TStringField; FDFType: TIntegerField; FDFStart: TStringField; FDFStop: TStringField; FDFStopStatus: TStringField; FDFUserID: TStringField; FDFDescription: TStringField; FDFOptions: TBlobField; FDFControlStatus: TStringField; FDFControlMsg: TStringField; FDFControlScanMsg: TStringField; FDFLenderList: TBlobField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPType(const Value: Integer); function GetPType:Integer; procedure SetPStart(const Value: String); function GetPStart:String; procedure SetPStop(const Value: String); function GetPStop:String; procedure SetPStopStatus(const Value: String); function GetPStopStatus:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPControlStatus(const Value: String); function GetPControlStatus:String; procedure SetPControlMsg(const Value: String); function GetPControlMsg:String; procedure SetPControlScanMsg(const Value: String); function GetPControlScanMsg:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSPROCESS); function GetEnumIndex: TEITTSPROCESS; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSPROCESSRecord; procedure StoreDataBuffer(ABuffer:TTTSPROCESSRecord); property DFAutoInc: TAutoIncField read FDFAutoInc; property DFLenderNum: TStringField read FDFLenderNum; property DFType: TIntegerField read FDFType; property DFStart: TStringField read FDFStart; property DFStop: TStringField read FDFStop; property DFStopStatus: TStringField read FDFStopStatus; property DFUserID: TStringField read FDFUserID; property DFDescription: TStringField read FDFDescription; property DFOptions: TBlobField read FDFOptions; property DFControlStatus: TStringField read FDFControlStatus; property DFControlMsg: TStringField read FDFControlMsg; property DFControlScanMsg: TStringField read FDFControlScanMsg; property DFLenderList: TBlobField read FDFLenderList; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PType: Integer read GetPType write SetPType; property PStart: String read GetPStart write SetPStart; property PStop: String read GetPStop write SetPStop; property PStopStatus: String read GetPStopStatus write SetPStopStatus; property PUserID: String read GetPUserID write SetPUserID; property PDescription: String read GetPDescription write SetPDescription; property PControlStatus: String read GetPControlStatus write SetPControlStatus; property PControlMsg: String read GetPControlMsg write SetPControlMsg; property PControlScanMsg: String read GetPControlScanMsg write SetPControlScanMsg; published property Active write SetActive; property EnumIndex: TEITTSPROCESS read GetEnumIndex write SetEnumIndex; end; { TTTSPROCESSTable } procedure Register; implementation function TTTSPROCESSTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSPROCESSTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSPROCESSTable.GenerateNewFieldName } function TTTSPROCESSTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSPROCESSTable.CreateField } procedure TTTSPROCESSTable.CreateFields; begin FDFAutoInc := CreateField( 'AutoInc' ) as TAutoIncField; FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFType := CreateField( 'Type' ) as TIntegerField; FDFStart := CreateField( 'Start' ) as TStringField; FDFStop := CreateField( 'Stop' ) as TStringField; FDFStopStatus := CreateField( 'StopStatus' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFOptions := CreateField( 'Options' ) as TBlobField; FDFControlStatus := CreateField( 'ControlStatus' ) as TStringField; FDFControlMsg := CreateField( 'ControlMsg' ) as TStringField; FDFControlScanMsg := CreateField( 'ControlScanMsg' ) as TStringField; FDFLenderList := CreateField( 'LenderList' ) as TBlobField; end; { TTTSPROCESSTable.CreateFields } procedure TTTSPROCESSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSPROCESSTable.SetActive } procedure TTTSPROCESSTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSPROCESSTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSPROCESSTable.SetPType(const Value: Integer); begin DFType.Value := Value; end; function TTTSPROCESSTable.GetPType:Integer; begin result := DFType.Value; end; procedure TTTSPROCESSTable.SetPStart(const Value: String); begin DFStart.Value := Value; end; function TTTSPROCESSTable.GetPStart:String; begin result := DFStart.Value; end; procedure TTTSPROCESSTable.SetPStop(const Value: String); begin DFStop.Value := Value; end; function TTTSPROCESSTable.GetPStop:String; begin result := DFStop.Value; end; procedure TTTSPROCESSTable.SetPStopStatus(const Value: String); begin DFStopStatus.Value := Value; end; function TTTSPROCESSTable.GetPStopStatus:String; begin result := DFStopStatus.Value; end; procedure TTTSPROCESSTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TTTSPROCESSTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TTTSPROCESSTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSPROCESSTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSPROCESSTable.SetPControlStatus(const Value: String); begin DFControlStatus.Value := Value; end; function TTTSPROCESSTable.GetPControlStatus:String; begin result := DFControlStatus.Value; end; procedure TTTSPROCESSTable.SetPControlMsg(const Value: String); begin DFControlMsg.Value := Value; end; function TTTSPROCESSTable.GetPControlMsg:String; begin result := DFControlMsg.Value; end; procedure TTTSPROCESSTable.SetPControlScanMsg(const Value: String); begin DFControlScanMsg.Value := Value; end; function TTTSPROCESSTable.GetPControlScanMsg:String; begin result := DFControlScanMsg.Value; end; procedure TTTSPROCESSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AutoInc, AutoInc, 0, N'); Add('LenderNum, String, 4, N'); Add('Type, Integer, 0, N'); Add('Start, String, 20, N'); Add('Stop, String, 20, N'); Add('StopStatus, String, 10, N'); Add('UserID, String, 10, N'); Add('Description, String, 100, N'); Add('Options, Memo, 0, N'); Add('ControlStatus, String, 10, N'); Add('ControlMsg, String, 100, N'); Add('ControlScanMsg, String, 30, N'); Add('LenderList, Memo, 0, N'); end; end; procedure TTTSPROCESSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AutoInc, Y, Y, N, N'); Add('ByLenderType, LenderNum;Type;AutoInc, N, N, N, Y'); end; end; procedure TTTSPROCESSTable.SetEnumIndex(Value: TEITTSPROCESS); begin case Value of TTSPROCESSPrimaryKey : IndexName := ''; TTSPROCESSByLenderType : IndexName := 'ByLenderType'; end; end; function TTTSPROCESSTable.GetDataBuffer:TTTSPROCESSRecord; var buf: TTTSPROCESSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAutoInc := DFAutoInc.Value; buf.PLenderNum := DFLenderNum.Value; buf.PType := DFType.Value; buf.PStart := DFStart.Value; buf.PStop := DFStop.Value; buf.PStopStatus := DFStopStatus.Value; buf.PUserID := DFUserID.Value; buf.PDescription := DFDescription.Value; buf.PControlStatus := DFControlStatus.Value; buf.PControlMsg := DFControlMsg.Value; buf.PControlScanMsg := DFControlScanMsg.Value; result := buf; end; procedure TTTSPROCESSTable.StoreDataBuffer(ABuffer:TTTSPROCESSRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFType.Value := ABuffer.PType; DFStart.Value := ABuffer.PStart; DFStop.Value := ABuffer.PStop; DFStopStatus.Value := ABuffer.PStopStatus; DFUserID.Value := ABuffer.PUserID; DFDescription.Value := ABuffer.PDescription; DFControlStatus.Value := ABuffer.PControlStatus; DFControlMsg.Value := ABuffer.PControlMsg; DFControlScanMsg.Value := ABuffer.PControlScanMsg; end; function TTTSPROCESSTable.GetEnumIndex: TEITTSPROCESS; var iname : string; begin result := TTSPROCESSPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSPROCESSPrimaryKey; if iname = 'BYLENDERTYPE' then result := TTSPROCESSByLenderType; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSPROCESSTable, TTTSPROCESSBuffer ] ); end; { Register } function TTTSPROCESSBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..11] of string = ('AUTOINC','LENDERNUM','TYPE','START','STOP','STOPSTATUS' ,'USERID','DESCRIPTION','CONTROLSTATUS','CONTROLMSG' ,'CONTROLSCANMSG' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 11) and (flist[x] <> s) do inc(x); if x <= 11 then result := x else result := 0; end; function TTTSPROCESSBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftAutoInc; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; end; end; function TTTSPROCESSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAutoInc; 2 : result := @Data.PLenderNum; 3 : result := @Data.PType; 4 : result := @Data.PStart; 5 : result := @Data.PStop; 6 : result := @Data.PStopStatus; 7 : result := @Data.PUserID; 8 : result := @Data.PDescription; 9 : result := @Data.PControlStatus; 10 : result := @Data.PControlMsg; 11 : result := @Data.PControlScanMsg; end; end; end.
unit MobileInternetVersionMenuForm_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, vtHoverButton, ImgList, vtPngImgList, tb97ctls, ExtCtrls; type TmivUserCommand = (mucCancel, mucStartWorkingWithInternetVersion, mucObtainRequisites, mucWorkLocal, mucRunContractConstructor); TProcessCommandProc = procedure(ACommand: TmivUserCommand) of object; TMobileInternetVersionMenuForm = class(TForm) WorkLocalButtonImages: TvtNonFixedPngImageList; ObtainRequisitesButtonImages: TvtNonFixedPngImageList; StartButtonImages: TvtNonFixedPngImageList; BackgroundImages: TvtNonFixedPngImageList; ContractConstructorButtonImages: TvtNonFixedPngImageList; private f_pbBackground: TPaintBox; f_StartButton: TvtHoverButton; f_ObtainRequisitesButton: TvtHoverButton; f_WorkLocalButton: TvtHoverButton; f_ContractConstrutorButton: TvtHoverButton; f_OnCommand: TProcessCommandProc; procedure StartButtonClick(ASender: TObject); procedure ObtainRequisitesButtonClick(ASender: TObject); procedure WorkLocalButtonClick(ASender: TObject); procedure ContractConstructorButtonClick(ASender: TObject); procedure PaintBackground(ASender: TObject); procedure SendCommand(ACommand: TmivUserCommand); protected procedure InitControls; procedure Loaded; override; public property OnCommand: TProcessCommandProc read f_OnCommand write f_OnCommand; end; implementation {$R *.dfm} procedure TMobileInternetVersionMenuForm.ObtainRequisitesButtonClick(ASender: TObject); begin SendCommand(mucObtainRequisites); end;//TMobileInternetVersionMenuForm.ObtainRequisitesButtonClick procedure TMobileInternetVersionMenuForm.StartButtonClick(ASender: TObject); begin SendCommand(mucStartWorkingWithInternetVersion); end;//TMobileInternetVersionMenuForm.StartButtonClick procedure TMobileInternetVersionMenuForm.WorkLocalButtonClick(ASender: TObject); begin SendCommand(mucWorkLocal); end;//TMobileInternetVersionMenuForm.WorkLocalButtonClick procedure TMobileInternetVersionMenuForm.ContractConstructorButtonClick(ASender: TObject); begin SendCommand(mucRunContractConstructor); end;//TMobileInternetVersionMenuForm.ContractConstructorButtonClick procedure TMobileInternetVersionMenuForm.InitControls; const C_SMALL_BUTTON_VERITCAL_SPACING = 8; var l_ClientHorCenter: Integer; begin ClientHeight := 600; ClientWidth := 720; Position := poScreenCenter; l_ClientHorCenter := ClientWidth div 2; f_pbBackground := TPaintBox.Create(Self); with f_pbBackground do begin Parent := Self; Align := alClient; OnPaint := PaintBackground; end;//with f_pbBackground f_StartButton := TvtHoverButton.Create(Self); with f_StartButton do begin DoubleBuffered := True; Parent := Self; Left := l_ClientHorCenter - (StartButtonImages.Width div 2); Top := 254; AutoSize := True; ImageList := StartButtonImages; NormalImageIndex := 0; HoveredImageIndex := 1; PressedImageIndex := 1; OnClick := StartButtonClick; end;//with f_StartButton f_ObtainRequisitesButton := TvtHoverButton.Create(Self); with f_ObtainRequisitesButton do begin DoubleBuffered := True; Parent := Self; Left := l_ClientHorCenter - (ObtainRequisitesButtonImages.Width div 2); Top := 331; AutoSize := True; ImageList := ObtainRequisitesButtonImages; NormalImageIndex := 0; HoveredImageIndex := 1; PressedImageIndex := 1; OnClick := ObtainRequisitesButtonClick; end;//with f_ObtainRequisitesButton f_WorkLocalButton := TvtHoverButton.Create(Self); with f_WorkLocalButton do begin DoubleBuffered := True; Parent := Self; Left := 365; Top := 430; AutoSize := True; ImageList := WorkLocalButtonImages; NormalImageIndex := 0; HoveredImageIndex := 1; PressedImageIndex := 1; OnClick := WorkLocalButtonClick; end;//with f_WorkLocalButton f_ContractConstrutorButton := TvtHoverButton.Create(Self); with f_ContractConstrutorButton do begin DoubleBuffered := True; Parent := Self; Left := f_WorkLocalButton.Left; Top := f_WorkLocalButton.Top + f_WorkLocalButton.Height + C_SMALL_BUTTON_VERITCAL_SPACING; AutoSize := True; ImageList := ContractConstructorButtonImages; NormalImageIndex := 0; HoveredImageIndex := 1; PressedImageIndex := 1; OnClick := ContractConstructorButtonClick; end;//with f_ContractConstrutorButton end;//TMobileInternetVersionMenuForm.InitControls procedure TMobileInternetVersionMenuForm.Loaded; begin inherited; InitControls; end;//TMobileInternetVersionMenuForm.Loaded; procedure TMobileInternetVersionMenuForm.PaintBackground(ASender: TObject); begin BackGroundImages.Draw(f_pbBackground.Canvas, 0, 0, 0); end;//TMobileInternetVersionMenuForm.PaintBackground procedure TMobileInternetVersionMenuForm.SendCommand( ACommand: TmivUserCommand); begin if (Assigned(f_OnCommand)) then f_OnCommand(ACommand) else Assert(False); end;//TMobileInternetVersionMenuForm.SendCommand end.
unit GetAreaAddedActivitiesUnit; interface uses SysUtils, BaseExampleUnit; type TGetAreaAddedActivities = class(TBaseExample) public procedure Execute; end; implementation uses ActivityUnit, EnumsUnit; procedure TGetAreaAddedActivities.Execute; var ErrorString: String; Limit, Offset, Total: integer; Activities: TActivityList; begin Limit := 10; Offset := 0; Activities := Route4MeManager.ActivityFeed.GetActivities( TActivityType.atAreaAdded, Limit, Offset, Total, ErrorString); try WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn(Format('GetAreaAddedActivities executed successfully, ' + '%d activities returned, %d total', [Activities.Count, Total])); WriteLn(''); end else WriteLn(Format('GetAreaAddedActivities error: "%s"', [ErrorString])); finally FreeAndNil(Activities); end; end; end.
unit Model.Tiragem; interface type TTiragem = class private var FId: System.Integer; FData: System.TDate; FRoteiro: System.String; FEntregador: System.Integer; FProduto: System.String; FTiragem: System.Integer; public property ID: System.Integer read FId write FId; property Data: System.TDate read FData write FData; property Roteiro: System.string read FRoteiro write FRoteiro; property Entregador: System.Integer read FEntregador write FEntregador; property Produto: System.string read FProduto write FProduto; property Tiragem: System.Integer read FTiragem write FTiragem; constructor Create; overload; constructor Create(pFId: System.Integer; pFData: System.TDate; pFRoteiro: System.String; pFEntregador: System.Integer; pFProduto: System.String; pFTiragem: System.Integer); overload; end; implementation constructor TTiragem.Create; begin inherited Create; end; constructor TTiragem.Create(pFId: Integer; pFData: TDate; pFRoteiro: string; pFEntregador: Integer; pFProduto: string; pFTiragem: Integer); begin FId := pFId; FData := pFData; FRoteiro := pFRoteiro; FEntregador := pFEntregador; FProduto := pFProduto; FTiragem := pFTiragem; end; end.
// Based on TOmniBaseBoundedStack class from the OmniThreadLibrary, // originally written by GJ and Primoz Gabrijelcic. unit FastMM4LockFreeStack; interface type PReferencedPtr = ^TReferencedPtr; TReferencedPtr = record PData : pointer; Reference: NativeInt; end; PLinkedData = ^TLinkedData; TLinkedData = packed record Next: PLinkedData; Data: record end; //user data, variable size end; TLFStack = record strict private FDataBuffer : pointer; FElementSize : integer; FNumElements : integer; FPublicChainP : PReferencedPtr; FRecycleChainP: PReferencedPtr; class var class var obsIsInitialized: boolean; //default is false class var obsTaskPopLoops : NativeInt; class var obsTaskPushLoops: NativeInt; class function PopLink(var chain: TReferencedPtr): PLinkedData; static; class procedure PushLink(const link: PLinkedData; var chain: TReferencedPtr); static; procedure MeasureExecutionTimes; public procedure Empty; procedure Initialize(numElements, elementSize: integer); procedure Finalize; function IsEmpty: boolean; inline; function IsFull: boolean; inline; function Pop(var value): boolean; function Push(const value): boolean; property ElementSize: integer read FElementSize; property NumElements: integer read FNumElements; end; implementation uses Windows; {$IF CompilerVersion < 23} {$IFNDEF CPUX64} type NativeInt = integer; NativeUInt = cardinal; {$ENDIF} {$IFEND} var CASAlignment: integer; //required alignment for the CAS function - 8 or 16, depending on the platform function RoundUpTo(value: pointer; granularity: integer): pointer; begin Result := pointer((((NativeInt(value) - 1) div granularity) + 1) * granularity); end; function GetCPUTimeStamp: int64; asm rdtsc {$IFDEF CPUX64} shl rdx, 32 or rax, rdx {$ENDIF CPUX64} end; function GetThreadId: NativeInt; //result := GetCurrentThreadId; asm {$IFNDEF CPUX64} mov eax, fs:[$18] //eax := thread information block mov eax, [eax + $24] //eax := thread id {$ELSE CPUX64} mov rax, gs:[abs $30] mov eax, [rax + $48] {$ENDIF CPUX64} end; function CAS(const oldValue, newValue: NativeInt; var destination): boolean; overload; asm {$IFDEF CPUX64} mov rax, oldValue {$ENDIF CPUX64} lock cmpxchg [destination], newValue setz al end; function CAS(const oldValue, newValue: pointer; var destination): boolean; overload; asm {$IFDEF CPUX64} mov rax, oldValue {$ENDIF CPUX64} lock cmpxchg [destination], newValue setz al end; function CAS(const oldData: pointer; oldReference: NativeInt; newData: pointer; newReference: NativeInt; var destination): boolean; overload; asm {$IFNDEF CPUX64} push edi push ebx mov ebx, newData mov ecx, newReference mov edi, destination lock cmpxchg8b qword ptr [edi] pop ebx pop edi {$ELSE CPUX64} .noframe push rbx //rsp := rsp - 8 ! mov rax, oldData mov rbx, newData mov rcx, newReference mov r8, [destination + 8] //+8 with respect to .noframe lock cmpxchg16b [r8] pop rbx {$ENDIF CPUX64} setz al end; { TLFStack } procedure TLFStack.Empty; var linkedData: PLinkedData; begin repeat linkedData := PopLink(FPublicChainP^); if not assigned(linkedData) then break; //repeat PushLink(linkedData, FRecycleChainP^); until false; end; procedure TLFStack.Finalize; begin HeapFree(GetProcessHeap, 0, FDataBuffer); end; procedure TLFStack.Initialize(numElements, elementSize: integer); var bufferElementSize : integer; currElement : PLinkedData; dataBuffer : pointer; iElement : integer; nextElement : PLinkedData; roundedElementSize: integer; begin Assert(SizeOf(NativeInt) = SizeOf(pointer)); Assert(numElements > 0); Assert(elementSize > 0); FNumElements := numElements; FElementSize := elementSize; //calculate element size, round up to next aligned value roundedElementSize := (elementSize + SizeOf(pointer) - 1) AND NOT (SizeOf(pointer) - 1); //calculate buffer element size, round up to next aligned value bufferElementSize := ((SizeOf(TLinkedData) + roundedElementSize) + SizeOf(pointer) - 1) AND NOT (SizeOf(pointer) - 1); //calculate DataBuffer FDataBuffer := HeapAlloc(GetProcessHeap, HEAP_GENERATE_EXCEPTIONS, bufferElementSize * numElements + 2 * SizeOf(TReferencedPtr) + CASAlignment); dataBuffer := RoundUpTo(FDataBuffer, CASAlignment); if NativeInt(dataBuffer) AND (SizeOf(pointer) - 1) <> 0 then // TODO 1 raise exception - how? Halt; //raise Exception.Create('TOmniBaseContainer: obcBuffer is not aligned'); FPublicChainP := dataBuffer; inc(NativeInt(dataBuffer), SizeOf(TReferencedPtr)); FRecycleChainP := dataBuffer; inc(NativeInt(dataBuffer), SizeOf(TReferencedPtr)); //Format buffer to recycleChain, init obsRecycleChain and obsPublicChain. //At the beginning, all elements are linked into the recycle chain. FRecycleChainP^.PData := dataBuffer; currElement := FRecycleChainP^.PData; for iElement := 0 to FNumElements - 2 do begin nextElement := PLinkedData(NativeInt(currElement) + bufferElementSize); currElement.Next := nextElement; currElement := nextElement; end; currElement.Next := nil; // terminate the chain FPublicChainP^.PData := nil; MeasureExecutionTimes; end; function TLFStack.IsEmpty: boolean; begin Result := not assigned(FPublicChainP^.PData); end; function TLFStack.IsFull: boolean; begin Result := not assigned(FRecycleChainP^.PData); end; procedure TLFStack.MeasureExecutionTimes; const NumOfSamples = 10; var TimeTestField: array [0..1] of array [1..NumOfSamples] of int64; function GetMinAndClear(routine, count: cardinal): int64; var m: cardinal; n: integer; x: integer; begin Result := 0; for m := 1 to count do begin x:= 1; for n:= 2 to NumOfSamples do if TimeTestField[routine, n] < TimeTestField[routine, x] then x := n; Inc(Result, TimeTestField[routine, x]); TimeTestField[routine, x] := MaxLongInt; end; end; var oldAffinity: NativeUInt; currElement: PLinkedData; n : integer; begin if not obsIsInitialized then begin oldAffinity := SetThreadAffinityMask(GetCurrentThread, 1); try //Calculate TaskPopDelay and TaskPushDelay counter values depend on CPU speed!!!} obsTaskPopLoops := 1; obsTaskPushLoops := 1; for n := 1 to NumOfSamples do begin SwitchToThread; //Measure RemoveLink rutine delay TimeTestField[0, n] := GetCPUTimeStamp; currElement := PopLink(FRecycleChainP^); TimeTestField[0, n] := GetCPUTimeStamp - TimeTestField[0, n]; //Measure InsertLink rutine delay TimeTestField[1, n] := GetCPUTimeStamp; PushLink(currElement, FRecycleChainP^); TimeTestField[1, n] := GetCPUTimeStamp - TimeTestField[1, n]; end; //Calculate first 4 minimum average for RemoveLink rutine obsTaskPopLoops := GetMinAndClear(0, 4) div 4; //Calculate first 4 minimum average for InsertLink rutine obsTaskPushLoops := GetMinAndClear(1, 4) div 4; //This gives better performance (determined experimentally) obsTaskPopLoops := obsTaskPopLoops * 2; obsTaskPushLoops := obsTaskPushLoops * 2; obsIsInitialized := true; finally SetThreadAffinityMask(GetCurrentThread, oldAffinity); end; end; end; function TLFStack.Pop(var value): boolean; var linkedData: PLinkedData; begin linkedData := PopLink(FPublicChainP^); Result := assigned(linkedData); if not Result then Exit; Move(linkedData.Data, value, ElementSize); PushLink(linkedData, FRecycleChainP^); end; class function TLFStack.PopLink(var chain: TReferencedPtr): PLinkedData; //nil << Link.Next << Link.Next << ... << Link.Next // ^------ < chainHead var AtStartReference: NativeInt; CurrentReference: NativeInt; TaskCounter : NativeInt; ThreadReference : NativeInt; label TryAgain; begin ThreadReference := GetThreadId + 1; //Reference.bit0 := 1 with chain do begin TryAgain: TaskCounter := obsTaskPopLoops; AtStartReference := Reference OR 1; //Reference.bit0 := 1 repeat CurrentReference := Reference; Dec(TaskCounter); until (TaskCounter = 0) or (CurrentReference AND 1 = 0); if (CurrentReference AND 1 <> 0) and (AtStartReference <> CurrentReference) or not CAS(CurrentReference, ThreadReference, Reference) then goto TryAgain; //Reference is set... Result := PData; //Empty test if result = nil then CAS(ThreadReference, 0, Reference) //Clear Reference if task own reference else if not CAS(Result, ThreadReference, Result.Next, 0, chain) then goto TryAgain; end; //with chain end; function TLFStack.Push(const value): boolean; var linkedData: PLinkedData; begin linkedData := PopLink(FRecycleChainP^); Result := assigned(linkedData); if not Result then Exit; Move(value, linkedData.Data, ElementSize); PushLink(linkedData, FPublicChainP^); end; class procedure TLFStack.PushLink(const link: PLinkedData; var chain: TReferencedPtr); var PMemData : pointer; TaskCounter: NativeInt; begin with chain do begin for TaskCounter := 0 to obsTaskPushLoops do if (Reference AND 1 = 0) then break; repeat PMemData := PData; link.Next := PMemData; until CAS(PMemData, link, PData); end; end; procedure InitializeTimingInfo; var stack: TLFStack; begin stack.Initialize(10, 4); // enough for initialization stack.Finalize; end; initialization {$IFDEF CPUX64} CASAlignment := 16; {$ELSE} CASAlignment := 8; {$ENDIF CPUX64} InitializeTimingInfo; end.
{ common procedures} unit procs; interface uses Forms, progressfrm; const appVer : string = '0.1 alpha'; defaultPanels : integer = 2; debugging : boolean = false; W2K : boolean = false; regPath = 'Software\FC'; function getCfgStr(const key,default:string):string; procedure putCfgStr(const key:string; value:string); function getCfgInt(const key:string; default:integer):integer; procedure putCfgInt(const key:string; value:integer); function getCfgBool(const key:string; default:boolean):boolean; procedure putCfgBool(const key:string; value:boolean); procedure CloseReg; procedure ClearReg; function matchWildcard(const wildcard:string; filename:string):boolean; procedure status(s:string); procedure readFormState(form:TForm); procedure saveFormState(form:TForm); function getEnv(const key:string):string; implementation uses Windows, mainfrm, SysUtils, Registry; function getEnv; var buf:array[0..1023] of char; res:DWORD; begin res := GetEnvironmentVariable(PChar(key),@buf,SizeOf(buf)); if res = 0 then Result := '' else begin buf[res] := #0; Result := string(@buf); end; end; procedure saveFormState; var s:string; begin with form do begin s := Name+'_'; putCfgBool(s+'Maximized',WindowState=wsMaximized); putCfgInt(s+'Left',Left); putCfgInt(s+'Top',Top); putCfgInt(s+'Width',Width); putCfgInt(s+'Height',Height); end; end; procedure readFormState; var s:string; begin with form do begin s := Name+'_'; Left := getCfgInt(s+'Left',Left); Top := getCfgInt(s+'Top',Top); Width := getCfgInt(s+'Width',Width); Height := getCfgInt(s+'Height',Height); if getCfgBool(s+'Maximized',false) then WindowState := wsMaximized; if Left > Screen.WorkAreaWidth then Left := 0; if Top > Screen.WorkAreaHeight then Top := 0; end; end; procedure status; begin fMain.sbMain.SimpleText := s; end; const shlwapi = 'shlwapi.dll'; function PathMatchSpecA(pszFileParam,pszSpec:PChar):boolean;stdcall;external shlwapi; function matchWildcard; begin Result := PathMatchSpecA(PChar(filename),PChar(wildcard)); end; {function matchWildcard; var n,w,subn,fln,wln:integer; cw:char; b:boolean; begin Result := false; wln := length(wildcard); if wln = 0 then exit; if pos('.',filename) = 0 then filename := filename+'.'; fln := length(filename); if fln = 0 then exit; n := 1; for w:=1 to wln-1 do begin if n > fln then exit; cw := wildcard[w]; case cw of '*' : begin cw := wildcard[w+1]; b := false; for subn := n to fln do begin if cw = filename[subn] then begin b := true; n := subn; break; end; end; if not b then exit; end; '?' : inc(n); else begin if cw <> filename[n] then exit; inc(n); end; end; end; cw := wildcard[wln]; if (cw <> '*') and (cw <> filename[fln]) then exit; Result := true; end;} function OpenReg:TRegistry; begin Result := TRegistry.Create; Result.OpenKey(regPath,true); end; var reg:TRegistry; procedure CloseReg; begin reg.CloseKey; reg.Free; end; procedure ClearReg; begin reg.CloseKey; reg.DeleteKey(regPath); reg.OpenKey(regPath,true); end; procedure putCfgStr; begin reg.WriteString(key,value); end; function getCfgStr; begin try Result := reg.ReadString(key); if Result = '' then Result := default; except Result := default; end; end; procedure putCfgInt; begin reg.WriteInteger(key,value); end; function getCfgInt; begin try Result := reg.ReadInteger(key); except Result := default; end; end; procedure putCfgBool; begin reg.WriteBool(key,value); end; function getCfgBool; begin try Result := reg.ReadBool(key); except Result := default; end; end; procedure InitOS; var rec:TOSVersionInfo; begin if getCfgBool('W2KExtensions',true) then begin rec.dwOSVersionInfoSize := SizeOf(rec); GetVersionEx(rec); w2k := (rec.dwMajorVersion >= 5) and (rec.dwPlatformId=VER_PLATFORM_WIN32_NT); end else w2k := false; end; initialization begin reg := OpenReg; InitOS; defaultPanels := GetCfgInt('PanelCount',2); if defaultPanels < 2 then defaultPanels := 2; end; finalization begin CloseReg; end; end.
unit ULiveContactsDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSCloudBase, FMX.TMSCloudLiveContacts, FMX.Layouts, FMX.ListBox, FMX.Edit, FMX.Objects, FMX.TMSCloudImage, FMX.Memo, IOUtils, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomLive, FMX.TMSCloudLiveFMX, FMX.TMSCloudCustomLiveContacts; type TForm82 = class(TForm) ToolBar1: TToolBar; Button1: TButton; Button2: TButton; Panel2: TPanel; ListBox1: TListBox; Button4: TButton; TMSFMXCloudLiveContacts1: TTMSFMXCloudLiveContacts; procedure Button1Click(Sender: TObject); procedure TMSFMXCloudLiveContacts1ReceivedAccessToken(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure ListBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; Inserting: boolean; procedure FillContacts; procedure FillContactDetails; procedure ToggleControls; procedure ClearControls; end; var Form82: TForm82; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // LiveAppkey = 'xxxxxxxxx'; // LiveAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm82.Button1Click(Sender: TObject); var acc: boolean; begin TMSFMXCloudLiveContacts1.App.Key := LiveAppkey; TMSFMXCloudLiveContacts1.App.Secret := LiveAppSecret; TMSFMXCloudLiveContacts1.Logging := true; if TMSFMXCloudLiveContacts1.App.Key <> '' then begin TMSFMXCloudLiveContacts1.PersistTokens.Key := TPath.GetDocumentsPath + '/google.ini'; TMSFMXCloudLiveContacts1.PersistTokens.Section := 'tokens'; TMSFMXCloudLiveContacts1.LoadTokens; acc := TMSFMXCloudLiveContacts1.TestTokens; if not acc then begin TMSFMXCloudLiveContacts1.RefreshAccess; TMSFMXCloudLiveContacts1.DoAuth; end else begin Connected := true; ToggleControls; end; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm82.Button2Click(Sender: TObject); begin TMSFMXCloudLiveContacts1.ClearTokens; Connected := false; ClearControls; ListBox1.Clear; ToggleControls; end; procedure TForm82.Button4Click(Sender: TObject); begin FillContacts; end; procedure TForm82.ClearControls; begin end; procedure TForm82.FillContactDetails; var gc: TLiveContactItem; begin if Assigned(ListBox1.Selected) then begin gc := ListBox1.Selected.Data as TLiveContactItem; ShowMessage(gc.FirstName + ' ' + gc.LastName); end; end; procedure TForm82.FillContacts; var i: integer; begin ListBox1.Items.Clear; TMSFMXCloudLiveContacts1.GetContacts; for i := 0 to TMSFMXCloudLiveContacts1.Items.Count - 1 do listbox1.Items.AddObject(TMSFMXCloudLivecontacts1.Items[i].FullName, TMSFMXCloudLiveContacts1.Items[i]); end; procedure TForm82.FormCreate(Sender: TObject); begin Connected := False; ToggleControls; end; procedure TForm82.ListBox1Change(Sender: TObject); begin FillContactDetails; end; procedure TForm82.TMSFMXCloudLiveContacts1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudLiveContacts1.SaveTokens; Connected := true; ToggleControls; end; procedure TForm82.ToggleControls; begin Panel2.Enabled := Connected; Button1.Enabled := not Connected; Button2.Enabled := Connected; end; end.
{ Subroutine SST_W_C_EXP_ARRAY (EXP) * * Write the value of the expression EXP. EXP is a constant array expression. * This is allowed only in the initialization of an array variable. } module sst_w_c_EXP_ARRAY; define sst_w_c_exp_array; %include 'sst_w_c.ins.pas'; procedure sst_w_c_exp_array ( {write exp value, must be array constant} in exp: sst_exp_t); {expression descriptor} const max_msg_parms = 1; {max parameters we can pass to a message} var dt_exp_p: sst_dtype_p_t; {points to base data type of array} dt_ele_p: sst_dtype_p_t; {points to base data type of array elements} ind: sys_int_max_t; {seq number of current array ele, first = 0} ind_max: sys_int_max_t; {seq number of last element with initial val} term_p: sst_exp_term_p_t; {points to current term in expression} term_start_p: sst_exp_term_p_t; {first term with vals at or after curr ele} default: string_var8192_t; {default element value expression} vert: boolean; {TRUE if expand elements vertically} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label term_next, ele_next; begin default.max := sizeof(default.str); {init local var string} { * Resolve and check base data type of array. } dt_exp_p := exp.dtype_p; {resolve expression's base data type} while dt_exp_p^.dtype = sst_dtype_copy_k do dt_exp_p := dt_exp_p^.copy_dtype_p; if dt_exp_p^.dtype <> sst_dtype_array_k then begin {expression dtype not ARRAY ?} sys_msg_parm_int (msg_parm[1], ord(dt_exp_p^.dtype)); sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1); end; { * Resolve base data type of array elements after this subscript. } if dt_exp_p^.ar_dtype_rem_p = nil {make raw pointer to elements data type} then dt_ele_p := dt_exp_p^.ar_dtype_ele_p else dt_ele_p := dt_exp_p^.ar_dtype_rem_p; while dt_ele_p^.dtype = sst_dtype_copy_k {resolve base elements data type} do dt_ele_p := dt_ele_p^.copy_dtype_p; { * Set the default element value and decide on vertical/horizontal element list * expansion. } vert := false; {init to horizontal element expansion} default.len := 0; {init default value string} case dt_ele_p^.dtype of {what is data type of elements} sst_dtype_int_k, {integer} sst_dtype_enum_k, {enumerated (names for each value)} sst_dtype_range_k, {subrange of a simple data type} sst_dtype_pnt_k: begin {pointer} string_appendn (default, '0', 1); end; sst_dtype_rec_k, {record} sst_dtype_set_k: begin {set of an enumerated type} vert := true; {indicate vertical expansion} string_appendn (default, '0', 1); end; sst_dtype_bool_k: begin {TRUE/FALSE (Boolean)} string_appendn (default, 'false', 5); sst_w_c_declare (decl_false_k); sst_w_c_declare (decl_true_k); end; sst_dtype_float_k: begin {floating point} string_appendn (default, '0.0', 3); end; sst_dtype_char_k: begin {character} string_appendn (default, ''' ''', 3); end; sst_dtype_array_k: begin {array} vert := true; {indicate vertical expansion} if dt_ele_p^.ar_string then begin {array is a string of characters} string_appendn (default, '""', 2); end else begin string_appendn (default, '{0}', 3); end ; end; otherwise sys_msg_parm_int (msg_parm[1], ord(dt_ele_p^.dtype)); sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1); end; { * Find the number of the last element that has an initial value. } ind_max := 0; {init to max initialized ele is first ele} term_p := addr(exp.term1); {init current term to first in expression} while term_p <> nil do begin {once for every term in expression} ind_max := {update max element number initialized here} max(ind_max, term_p^.arele_start + term_p^.arele_n - 1); term_p := term_p^.next_p; {advance to next term in expression} end; { * The current state has been set up as follows: * * VERT - TRUE if the elements list should be expanded vertically * (one per line). Otherwise the elements list will be written sequentially * without line breaks, and wrapping will occurr when lines are filled. * * DEFAULT - This is a string of the element value to write when it * is not explicitly initialized. * * IND_MAX - This identifies the maximum element that has an initial * value. This is used to decide when to stop, since all the remaining * elements are allowed to take on arbitrary initial values. IND_MAX * is 0 to indicate the first element, regardless of the ordinal value * of the start of the subscript range. This is also how the elements * are identified in the term descriptor when they are tagged with an * initial value. * * Now write the element value from the first element in the array, to the * last initialized element. For each element sequentially, the initial * values expression is searched to determine whether this element has an * initial value. If so, the value is written out. If not, DEFAULT is * written. * * To make the search for the current element number more efficient, * TERM_START_P will be maintained to point to the first term that contains * any values for elements at or after the current element. This will make * the search much more efficient when the elements are listed in subscript * order. } sst_w.appendn^ ('{', 1); {start of initial values for an array} term_start_p := addr(exp.term1); {init first term to search for curr element} for ind := 0 to ind_max do begin {loop up to max initialized array element} if vert then begin {each element goes on a new line ?} sst_w.line_close^; {start a new line} sst_w.tab_indent^; sst_w.indent^; {extra indent for wrapped lines} end; term_p := term_start_p; {init curr term to first term to search} while term_p <> nil do begin {search all terms from here to end of exp} if (term_p^.arele_start + term_p^.arele_n) <= ind then begin {before element ?} term_start_p := term_p^.next_p; {next time start one term after here} goto term_next; {try again with next term} end; if term_p^.arele_start > ind then begin {this term is after current element ?} goto term_next; {try again with next term} end; { * This term describes the initial value for the current array element. } sst_w_c_exp_const (term_p^.arele_exp_p^, 0, dt_ele_p, enclose_no_k); {ele value} goto ele_next; {done writing value for current element} term_next: {jump here to check next term in expression} term_p := term_p^.next_p; {advance to next term in expression} end; {back and check new term for element value} { * All the terms were checked and none of them had the initial value for the * current element. Write the default value. } sst_w.append^ (default); ele_next: {jump here to advance to next array element} if ind <> ind_max then begin {this was not last element in list ?} sst_w.appendn^ (',', 1); if not vert then begin {writing elements horizontally ?} sst_w.delimit^; end; end; if vert then begin {writing elements vertically ?} sst_w.undent^; {undo extra indent for wrapped lines} end; end; {back and process next element of array} { * Done writing initial values for all the elements. } sst_w.appendn^ ('}', 1); end;
unit sliding_window; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TSlidingForm = class(TForm) private sollpos_left, sollpos_top: integer; sld_timer: TTimer; procedure sld_timer_timer(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SlideTo(aleft, atop: integer); { Public-Deklarationen } end; implementation constructor TSlidingForm.Create(AOwner: TComponent); begin inherited; sld_timer := TTimer.Create(self); sld_timer.Interval := 25; sld_timer.OnTimer := sld_timer_timer; sld_timer.Enabled := true; sollpos_left := Left; sollpos_top := Top; end; destructor TSlidingForm.Destroy; begin sld_timer.Free; inherited; end; procedure TSlidingForm.sld_timer_timer(Sender: TObject); var dist_g: single; dx,dy,dist_x,dist_y: integer; begin dist_x := sollpos_left-left; dist_y := sollpos_top-top; dist_g := sqrt(sqr(dist_x)+sqr(dist_y)); if dist_g > 0 then begin dx := trunc(10* dist_x / dist_g); dy := trunc(10* dist_y / dist_g); if abs(dx) > abs(dist_x) then dx := dist_x; if abs(dy) > abs(dist_y) then dy := dist_y; Left := Left + dx; top := top + dy; end else sld_timer.Enabled := False; end; procedure TSlidingForm.SlideTo(aleft, atop: integer); begin sollpos_left := aleft; sollpos_top := atop; sld_timer.Enabled := true; end; end.
unit nsOpenDocOnNumberData; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/nsOpenDocOnNumberData.pas" // Начат: 28.10.2009 0*07 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Core::Base Operations::View::Navigation::TnsOpenDocOnNumberData // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, NavigationInterfaces, l3CProtoObject, bsTypesNew ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsOpenDocOnNumberData = class(Tl3CProtoObject, InsOpenDocOnNumberData) private // private fields f_DocID : Integer; f_PosID : Integer; f_Internal : Boolean; f_History : Il3CString; f_Done : Boolean; f_PosType : TDocumentPositionType; protected // realized methods function Get_DocID: Integer; procedure Set_DocID(aValue: Integer); function Get_PosID: Integer; procedure Set_PosID(aValue: Integer); function Get_Internal: Boolean; procedure Set_Internal(aValue: Boolean); function Get_History: Il3CString; procedure Set_History(const aValue: Il3CString); function Get_Done: Boolean; procedure Set_Done(aValue: Boolean); function Get_PosType: TDocumentPositionType; procedure Set_PosType(aValue: TDocumentPositionType); protected // overridden protected methods procedure ClearFields; override; public // public methods constructor Create(aDocID: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aInternal: Boolean; const aHistory: Il3CString); reintroduce; class function Make(aDocID: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aInternal: Boolean; const aHistory: Il3CString): InsOpenDocOnNumberData; reintroduce; end;//TnsOpenDocOnNumberData {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsOpenDocOnNumberData constructor TnsOpenDocOnNumberData.Create(aDocID: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aInternal: Boolean; const aHistory: Il3CString); //#UC START# *4AE761950144_4AE760FD0182_var* //#UC END# *4AE761950144_4AE760FD0182_var* begin //#UC START# *4AE761950144_4AE760FD0182_impl* inherited Create; f_Done := false; f_DocID := aDocID; f_PosID := aPosID; f_PosType := aPosType; f_Internal := aInternal; f_History := aHistory; //#UC END# *4AE761950144_4AE760FD0182_impl* end;//TnsOpenDocOnNumberData.Create class function TnsOpenDocOnNumberData.Make(aDocID: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aInternal: Boolean; const aHistory: Il3CString): InsOpenDocOnNumberData; var l_Inst : TnsOpenDocOnNumberData; begin l_Inst := Create(aDocID, aPosID, aPosType, aInternal, aHistory); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TnsOpenDocOnNumberData.Get_DocID: Integer; //#UC START# *4AE760B500BD_4AE760FD0182get_var* //#UC END# *4AE760B500BD_4AE760FD0182get_var* begin //#UC START# *4AE760B500BD_4AE760FD0182get_impl* Result := f_DocID //#UC END# *4AE760B500BD_4AE760FD0182get_impl* end;//TnsOpenDocOnNumberData.Get_DocID procedure TnsOpenDocOnNumberData.Set_DocID(aValue: Integer); //#UC START# *4AE760B500BD_4AE760FD0182set_var* //#UC END# *4AE760B500BD_4AE760FD0182set_var* begin //#UC START# *4AE760B500BD_4AE760FD0182set_impl* f_DocID := aValue; //#UC END# *4AE760B500BD_4AE760FD0182set_impl* end;//TnsOpenDocOnNumberData.Set_DocID function TnsOpenDocOnNumberData.Get_PosID: Integer; //#UC START# *4AE760C90313_4AE760FD0182get_var* //#UC END# *4AE760C90313_4AE760FD0182get_var* begin //#UC START# *4AE760C90313_4AE760FD0182get_impl* Result := f_PosID; //#UC END# *4AE760C90313_4AE760FD0182get_impl* end;//TnsOpenDocOnNumberData.Get_PosID procedure TnsOpenDocOnNumberData.Set_PosID(aValue: Integer); //#UC START# *4AE760C90313_4AE760FD0182set_var* //#UC END# *4AE760C90313_4AE760FD0182set_var* begin //#UC START# *4AE760C90313_4AE760FD0182set_impl* f_PosID := aValue; //#UC END# *4AE760C90313_4AE760FD0182set_impl* end;//TnsOpenDocOnNumberData.Set_PosID function TnsOpenDocOnNumberData.Get_Internal: Boolean; //#UC START# *4AE760D30088_4AE760FD0182get_var* //#UC END# *4AE760D30088_4AE760FD0182get_var* begin //#UC START# *4AE760D30088_4AE760FD0182get_impl* Result := f_Internal; //#UC END# *4AE760D30088_4AE760FD0182get_impl* end;//TnsOpenDocOnNumberData.Get_Internal procedure TnsOpenDocOnNumberData.Set_Internal(aValue: Boolean); //#UC START# *4AE760D30088_4AE760FD0182set_var* //#UC END# *4AE760D30088_4AE760FD0182set_var* begin //#UC START# *4AE760D30088_4AE760FD0182set_impl* f_Internal := aValue; //#UC END# *4AE760D30088_4AE760FD0182set_impl* end;//TnsOpenDocOnNumberData.Set_Internal function TnsOpenDocOnNumberData.Get_History: Il3CString; //#UC START# *4AE760DB01E2_4AE760FD0182get_var* //#UC END# *4AE760DB01E2_4AE760FD0182get_var* begin //#UC START# *4AE760DB01E2_4AE760FD0182get_impl* Result := f_History; //#UC END# *4AE760DB01E2_4AE760FD0182get_impl* end;//TnsOpenDocOnNumberData.Get_History procedure TnsOpenDocOnNumberData.Set_History(const aValue: Il3CString); //#UC START# *4AE760DB01E2_4AE760FD0182set_var* //#UC END# *4AE760DB01E2_4AE760FD0182set_var* begin //#UC START# *4AE760DB01E2_4AE760FD0182set_impl* f_History := aValue; //#UC END# *4AE760DB01E2_4AE760FD0182set_impl* end;//TnsOpenDocOnNumberData.Set_History function TnsOpenDocOnNumberData.Get_Done: Boolean; //#UC START# *4AE81AD9019D_4AE760FD0182get_var* //#UC END# *4AE81AD9019D_4AE760FD0182get_var* begin //#UC START# *4AE81AD9019D_4AE760FD0182get_impl* Result := f_Done; //#UC END# *4AE81AD9019D_4AE760FD0182get_impl* end;//TnsOpenDocOnNumberData.Get_Done procedure TnsOpenDocOnNumberData.Set_Done(aValue: Boolean); //#UC START# *4AE81AD9019D_4AE760FD0182set_var* //#UC END# *4AE81AD9019D_4AE760FD0182set_var* begin //#UC START# *4AE81AD9019D_4AE760FD0182set_impl* f_Done := aValue; //#UC END# *4AE81AD9019D_4AE760FD0182set_impl* end;//TnsOpenDocOnNumberData.Set_Done function TnsOpenDocOnNumberData.Get_PosType: TDocumentPositionType; //#UC START# *4CC90CCA0027_4AE760FD0182get_var* //#UC END# *4CC90CCA0027_4AE760FD0182get_var* begin //#UC START# *4CC90CCA0027_4AE760FD0182get_impl* Result := f_PosType; //#UC END# *4CC90CCA0027_4AE760FD0182get_impl* end;//TnsOpenDocOnNumberData.Get_PosType procedure TnsOpenDocOnNumberData.Set_PosType(aValue: TDocumentPositionType); //#UC START# *4CC90CCA0027_4AE760FD0182set_var* //#UC END# *4CC90CCA0027_4AE760FD0182set_var* begin //#UC START# *4CC90CCA0027_4AE760FD0182set_impl* f_PosType := aValue; //#UC END# *4CC90CCA0027_4AE760FD0182set_impl* end;//TnsOpenDocOnNumberData.Set_PosType procedure TnsOpenDocOnNumberData.ClearFields; {-} begin f_History := nil; inherited; end;//TnsOpenDocOnNumberData.ClearFields {$IfEnd} //not Admin AND not Monitorings end.
unit EditXControl_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { EditXControl Library } { Version 1.0 } { Conversion log: Hint: Class is not registered. Ambient properties cannot be determined. } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_EditXControl: TGUID = '{C9EE07C0-B606-11D1-ABC3-008029EC1811}'; const { TxBorderStyle } bsNone = 0; bsSingle = 1; { TxEditCharCase } ecNormal = 0; ecUpperCase = 1; ecLowerCase = 2; { TxDragMode } dmManual = 0; dmAutomatic = 1; { TxImeMode } imDisable = 0; imClose = 1; imOpen = 2; imDontCare = 3; imSAlpha = 4; imAlpha = 5; imHira = 6; imSKata = 7; imKata = 8; imChinese = 9; imSHanguel = 10; imHanguel = 11; { TxMouseButton } mbLeft = 0; mbRight = 1; mbMiddle = 2; const { Component class GUIDs } Class_EditX: TGUID = '{C9EE07C3-B606-11D1-ABC3-008029EC1811}'; type { Forward declarations: Interfaces } IEditX = interface; IEditXDisp = dispinterface; IEditXEvents = dispinterface; { Forward declarations: CoClasses } EditX = IEditX; { Forward declarations: Enums } TxBorderStyle = TOleEnum; TxEditCharCase = TOleEnum; TxDragMode = TOleEnum; TxImeMode = TOleEnum; TxMouseButton = TOleEnum; { Dispatch interface for EditX Control } IEditX = interface(IDispatch) ['{C9EE07C1-B606-11D1-ABC3-008029EC1811}'] function Get_AutoSelect: WordBool; safecall; procedure Set_AutoSelect(Value: WordBool); safecall; function Get_AutoSize: WordBool; safecall; procedure Set_AutoSize(Value: WordBool); safecall; function Get_BorderStyle: TxBorderStyle; safecall; procedure Set_BorderStyle(Value: TxBorderStyle); safecall; function Get_CharCase: TxEditCharCase; safecall; procedure Set_CharCase(Value: TxEditCharCase); safecall; function Get_Color: Integer; safecall; procedure Set_Color(Value: Integer); safecall; function Get_Ctl3D: WordBool; safecall; procedure Set_Ctl3D(Value: WordBool); safecall; function Get_DragCursor: Smallint; safecall; procedure Set_DragCursor(Value: Smallint); safecall; function Get_DragMode: TxDragMode; safecall; procedure Set_DragMode(Value: TxDragMode); safecall; function Get_Enabled: WordBool; safecall; procedure Set_Enabled(Value: WordBool); safecall; function Get_HideSelection: WordBool; safecall; procedure Set_HideSelection(Value: WordBool); safecall; function Get_ImeMode: TxImeMode; safecall; procedure Set_ImeMode(Value: TxImeMode); safecall; function Get_ImeName: WideString; safecall; procedure Set_ImeName(const Value: WideString); safecall; function Get_MaxLength: Integer; safecall; procedure Set_MaxLength(Value: Integer); safecall; function Get_OEMConvert: WordBool; safecall; procedure Set_OEMConvert(Value: WordBool); safecall; function Get_ParentColor: WordBool; safecall; procedure Set_ParentColor(Value: WordBool); safecall; function Get_ParentCtl3D: WordBool; safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; function Get_PasswordChar: Smallint; safecall; procedure Set_PasswordChar(Value: Smallint); safecall; function Get_ReadOnly: WordBool; safecall; procedure Set_ReadOnly(Value: WordBool); safecall; function Get_Text: WideString; safecall; procedure Set_Text(const Value: WideString); safecall; function Get_Visible: WordBool; safecall; procedure Set_Visible(Value: WordBool); safecall; procedure Clear; safecall; procedure ClearSelection; safecall; procedure CopyToClipboard; safecall; procedure CutToClipboard; safecall; procedure PasteFromClipboard; safecall; procedure SelectAll; safecall; function Get_Modified: WordBool; safecall; procedure Set_Modified(Value: WordBool); safecall; function Get_SelLength: Integer; safecall; procedure Set_SelLength(Value: Integer); safecall; function Get_SelStart: Integer; safecall; procedure Set_SelStart(Value: Integer); safecall; function Get_SelText: WideString; safecall; procedure Set_SelText(const Value: WideString); safecall; function Get_Cursor: Smallint; safecall; procedure Set_Cursor(Value: Smallint); safecall; property AutoSelect: WordBool read Get_AutoSelect write Set_AutoSelect; property AutoSize: WordBool read Get_AutoSize write Set_AutoSize; property BorderStyle: TxBorderStyle read Get_BorderStyle write Set_BorderStyle; property CharCase: TxEditCharCase read Get_CharCase write Set_CharCase; property Color: Integer read Get_Color write Set_Color; property Ctl3D: WordBool read Get_Ctl3D write Set_Ctl3D; property DragCursor: Smallint read Get_DragCursor write Set_DragCursor; property DragMode: TxDragMode read Get_DragMode write Set_DragMode; property Enabled: WordBool read Get_Enabled write Set_Enabled; property HideSelection: WordBool read Get_HideSelection write Set_HideSelection; property ImeMode: TxImeMode read Get_ImeMode write Set_ImeMode; property ImeName: WideString read Get_ImeName write Set_ImeName; property MaxLength: Integer read Get_MaxLength write Set_MaxLength; property OEMConvert: WordBool read Get_OEMConvert write Set_OEMConvert; property ParentColor: WordBool read Get_ParentColor write Set_ParentColor; property ParentCtl3D: WordBool read Get_ParentCtl3D write Set_ParentCtl3D; property PasswordChar: Smallint read Get_PasswordChar write Set_PasswordChar; property ReadOnly: WordBool read Get_ReadOnly write Set_ReadOnly; property Text: WideString read Get_Text write Set_Text; property Visible: WordBool read Get_Visible write Set_Visible; property Modified: WordBool read Get_Modified write Set_Modified; property SelLength: Integer read Get_SelLength write Set_SelLength; property SelStart: Integer read Get_SelStart write Set_SelStart; property SelText: WideString read Get_SelText write Set_SelText; property Cursor: Smallint read Get_Cursor write Set_Cursor; end; { DispInterface declaration for Dual Interface IEditX } IEditXDisp = dispinterface ['{C9EE07C1-B606-11D1-ABC3-008029EC1811}'] property AutoSelect: WordBool dispid 1; property AutoSize: WordBool dispid 2; property BorderStyle: TxBorderStyle dispid 3; property CharCase: TxEditCharCase dispid 4; property Color: Integer dispid 5; property Ctl3D: WordBool dispid 6; property DragCursor: Smallint dispid 7; property DragMode: TxDragMode dispid 8; property Enabled: WordBool dispid 9; property HideSelection: WordBool dispid 10; property ImeMode: TxImeMode dispid 11; property ImeName: WideString dispid 12; property MaxLength: Integer dispid 13; property OEMConvert: WordBool dispid 14; property ParentColor: WordBool dispid 15; property ParentCtl3D: WordBool dispid 16; property PasswordChar: Smallint dispid 17; property ReadOnly: WordBool dispid 18; property Text: WideString dispid 19; property Visible: WordBool dispid 20; procedure Clear; dispid 21; procedure ClearSelection; dispid 22; procedure CopyToClipboard; dispid 23; procedure CutToClipboard; dispid 24; procedure PasteFromClipboard; dispid 25; procedure SelectAll; dispid 26; property Modified: WordBool dispid 27; property SelLength: Integer dispid 28; property SelStart: Integer dispid 29; property SelText: WideString dispid 30; property Cursor: Smallint dispid 31; end; { Events interface for EditX Control } IEditXEvents = dispinterface ['{C9EE07C2-B606-11D1-ABC3-008029EC1811}'] procedure OnChange; dispid 1; procedure OnClick; dispid 2; procedure OnDblClick; dispid 3; procedure OnKeyPress(var Key: Smallint); dispid 4; end; { EditXControl } TEditXOnKeyPress = procedure(Sender: TObject; var Key: Smallint) of object; TEditX = class(TOleControl) private FOnChange: TNotifyEvent; FOnClick: TNotifyEvent; FOnDblClick: TNotifyEvent; FOnKeyPress: TEditXOnKeyPress; FIntf: IEditX; protected procedure InitControlData; override; procedure InitControlInterface(const Obj: IUnknown); override; public procedure Clear; procedure ClearSelection; procedure CopyToClipboard; procedure CutToClipboard; procedure PasteFromClipboard; procedure SelectAll; property ControlInterface: IEditX read FIntf; published property AutoSelect: WordBool index 1 read GetWordBoolProp write SetWordBoolProp stored False; property AutoSize: WordBool index 2 read GetWordBoolProp write SetWordBoolProp stored False; property BorderStyle: TxBorderStyle index 3 read GetTOleEnumProp write SetTOleEnumProp stored False; property CharCase: TxEditCharCase index 4 read GetTOleEnumProp write SetTOleEnumProp stored False; property Color: Integer index 5 read GetIntegerProp write SetIntegerProp stored False; property Ctl3D: WordBool index 6 read GetWordBoolProp write SetWordBoolProp stored False; property DragCursor: Smallint index 7 read GetSmallintProp write SetSmallintProp stored False; property DragMode: TxDragMode index 8 read GetTOleEnumProp write SetTOleEnumProp stored False; property Enabled: WordBool index 9 read GetWordBoolProp write SetWordBoolProp stored False; property HideSelection: WordBool index 10 read GetWordBoolProp write SetWordBoolProp stored False; property ImeMode: TxImeMode index 11 read GetTOleEnumProp write SetTOleEnumProp stored False; property ImeName: WideString index 12 read GetWideStringProp write SetWideStringProp stored False; property MaxLength: Integer index 13 read GetIntegerProp write SetIntegerProp stored False; property OEMConvert: WordBool index 14 read GetWordBoolProp write SetWordBoolProp stored False; property ParentColor: WordBool index 15 read GetWordBoolProp write SetWordBoolProp stored False; property ParentCtl3D: WordBool index 16 read GetWordBoolProp write SetWordBoolProp stored False; property PasswordChar: Smallint index 17 read GetSmallintProp write SetSmallintProp stored False; property ReadOnly: WordBool index 18 read GetWordBoolProp write SetWordBoolProp stored False; property Text: WideString index 19 read GetWideStringProp write SetWideStringProp stored False; property Visible: WordBool index 20 read GetWordBoolProp write SetWordBoolProp stored False; property Modified: WordBool index 27 read GetWordBoolProp write SetWordBoolProp stored False; property SelLength: Integer index 28 read GetIntegerProp write SetIntegerProp stored False; property SelStart: Integer index 29 read GetIntegerProp write SetIntegerProp stored False; property SelText: WideString index 30 read GetWideStringProp write SetWideStringProp stored False; property Cursor: Smallint index 31 read GetSmallintProp write SetSmallintProp stored False; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnClick: TNotifyEvent read FOnClick write FOnClick; property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick; property OnKeyPress: TEditXOnKeyPress read FOnKeyPress write FOnKeyPress; end; procedure Register; implementation uses ComObj; procedure TEditX.InitControlData; const CEventDispIDs: array[0..3] of Integer = ( $00000001, $00000002, $00000003, $00000004); CControlData: TControlData = ( ClassID: '{C9EE07C3-B606-11D1-ABC3-008029EC1811}'; EventIID: '{C9EE07C2-B606-11D1-ABC3-008029EC1811}'; EventCount: 4; EventDispIDs: @CEventDispIDs; LicenseKey: nil; Flags: $00000000; Version: 300); begin ControlData := @CControlData; end; procedure TEditX.InitControlInterface(const Obj: IUnknown); begin FIntf := Obj as IEditX; end; procedure TEditX.Clear; begin ControlInterface.Clear; end; procedure TEditX.ClearSelection; begin ControlInterface.ClearSelection; end; procedure TEditX.CopyToClipboard; begin ControlInterface.CopyToClipboard; end; procedure TEditX.CutToClipboard; begin ControlInterface.CutToClipboard; end; procedure TEditX.PasteFromClipboard; begin ControlInterface.PasteFromClipboard; end; procedure TEditX.SelectAll; begin ControlInterface.SelectAll; end; procedure Register; begin RegisterComponents('ActiveX', [TEditX]); end; end.
Unit MVCBr.FireDACModel; { MVCBr www.tireideletra.com.br amarildo lacerda } interface uses Classes, forms, SysUtils, MVCBr.Interf, MVCBr.Model, MVCBr.FireDACModel.Interf, MVCBr.Controller, MVCBr.DatabaseModel, MVCBr.DatabaseModel.Interf, FireDAC.Comp.Client, FireDAC.Stan.Def; Type TFireDACModel = class(TDatabaseModelFactory<TFDConnection, TFDQuery>, IFireDACModel, IThisAs<TFireDACModel>) private protected public Constructor Create; override; Destructor Destroy; override; class function new(AProc: TProc<IFireDACModel>): IFireDACModel; overload; class function new(const AController: IController): IFireDACModel; overload; function ThisAs: TFireDACModel; // connection function DriverID(const ADriverID: string): IFireDACModel; function ConnectionName(const AConn: string): IFireDACModel; function UserName(const AUser: string): IFireDACModel; function Password(const APass: string): IFireDACModel; procedure SetConnectionString(const Value: string); override; // Query // function NewQuery(const AProcChange: TProc<Q>): IQueryModel<Q>; virtual; end; Implementation function TFireDACModel.ConnectionName(const AConn: string): IFireDACModel; begin result := Self; GetConnection.ConnectionName := AConn; end; constructor TFireDACModel.Create; begin inherited; ModelTypes := [mtPersistent]; with TStringList.Create do try Assign(GetConnection.Params); Delimiter := ';'; FConnectionString := DelimitedText; finally DisposeOf; end; end; destructor TFireDACModel.Destroy; begin inherited; end; function TFireDACModel.DriverID(const ADriverID: string): IFireDACModel; begin result := Self; GetConnection.DriverName := ADriverID; end; class function TFireDACModel.new(AProc: TProc<IFireDACModel>): IFireDACModel; begin result := TFireDACModel.Create; if Assigned(AProc) then AProc(result); end; function TFireDACModel.ThisAs: TFireDACModel; begin result := Self; end; function TFireDACModel.UserName(const AUser: string): IFireDACModel; begin result := Self; GetConnection.Params.Values['USER_NAME'] := AUser; end; class function TFireDACModel.new(const AController: IController): IFireDACModel; begin result := TFireDACModel.Create; result.Controller(AController); end; function TFireDACModel.Password(const APass: string): IFireDACModel; begin result := Self; GetConnection.Params.Values['PASSWORD'] := APass; end; procedure TFireDACModel.SetConnectionString(const Value: string); var Params: TStringList; i:integer; begin inherited; Params := TStringList.Create; try Params.Delimiter := ';'; Params.DelimitedText := Value; for I := 0 to Params.count-1 do GetConnection.Params.Values[ Params.Names[i] ] := Params.ValueFromIndex[i]; finally Params.free; end; end; end.
(* To compile and run: $ fpc ch-1.pas $ ./ch-1 100 13015 *) program Hello(input, output); uses sysutils; var n, x, y, s: integer; function gcd(a, b: integer): integer; var t: integer; begin while b <> 0 do begin t := b; b := a mod b; a := t; end; gcd := a end; begin if paramCount() = 0 then n := 3 else n := StrToInt(paramStr(1)); s := 0; for x := 1 to n do for y := x + 1 to n do s += gcd(x, y); writeln(s); end.
unit Functions; interface uses Forms, Windows, Classes, SysUtils, ShellAPI, ZipMstr19, ZmUtils19, ShlObj, ActiveX; type TLineBreak = (lbWindows, lbLinux, lbMac); function RawFileCopy(ASrc, ADst: string): boolean; function ShellExecuteAndWait(FileName: string; Params: string): boolean; function FileSize(AFilename: string): int64; function LooksLikeDir(s: string): boolean; function GetTempDirectory: String; function NormalizeLineBreaks(s: string; mode: TLineBreak): string; function ExtractFileNameWithoutExt(const fil: string): string; function SearchNextFreeName(s: string; wantDir: boolean): string; function GetSpecialFolderPath(const Folder: integer): string; function IsExtractable(AFilename: string): boolean; function IsDirectoryWritable(const Dir: String): Boolean; function IsAtFlobbyDisk(AFileOrDir: string): boolean; implementation {$IFNDEF UNICODE} type TCharSet = set of AnsiChar; {$ENDIF} {$IFNDEF UNICODE} function CharInSet(C: AnsiChar; const CharSet: TCharSet): Boolean;// overload; begin Result := c in CharSet; end; {$ENDIF} function LooksLikeDir(s: string): boolean; begin result := CharInSet(s[Length(s)], ['/', '\']); end; function RawFileCopy(ASrc, ADst: string): boolean; var SSrc, SDst: TFileStream; begin DeleteFile(PChar(ADst)); SSrc := TFileStream.Create(ASrc, fmOpenRead); try SDst := TFileStream.Create(ADst, fmCreate); try SDst.CopyFrom(SSrc, SSrc.Size); finally SDst.Free; end; finally SSrc.Free; end; result := true; end; // http://www.delphipraxis.net/32234-shellexecuteandwait-status-abfragen.html // Modified. Now CONSOLE compatible and return false if ErrorLevel <> 0 function ShellExecuteAndWait(FileName: string; Params: string): boolean; var exInfo: TShellExecuteInfo; Ph: DWORD; lExitCode: DWord; begin Try FillChar(exInfo, SizeOf(exInfo), 0); with exInfo do begin cbSize := SizeOf(exInfo); fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT; Wnd := GetActiveWindow(); FileName := ExpandUNCFileName(FileName); ExInfo.lpVerb := 'open'; ExInfo.lpParameters := PChar(Params); // ExInfo.lpDirectory := PChar(ExtractFilePath(FileName)); lpFile := PChar(FileName); nShow := SW_SHOWNORMAL; end; if ShellExecuteEx(@exInfo) then begin Ph := exInfo.HProcess; end else begin WriteLn(SysErrorMessage(GetLastError)); Result := False; Exit; end; while WaitForSingleObject(ExInfo.hProcess, 50) <> WAIT_OBJECT_0 do ; (* begin Application.ProcessMessages; end; *) GetExitCodeProcess(Ph, lExitCode); Result := lExitCode = 0; CloseHandle(Ph); Except Result := False; Exit; End; end; function FileSize(AFilename: string): int64; var s: TFileStream; begin s := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite); try result := s.Size; finally s.Free; end; end; // http://www.cryer.co.uk/brian/delphi/howto_get_temp.htm function GetTempDirectory: String; var tempFolder: array[0..MAX_PATH] of Char; begin GetTempPath(MAX_PATH, @tempFolder); result := StrPas(tempFolder); end; function NormalizeLineBreaks(s: string; mode: TLineBreak): string; begin if mode = lbWindows then begin s := StringReplace(s, #13#10, #10, [rfReplaceAll]); s := StringReplace(s, #13, #10, [rfReplaceAll]); s := StringReplace(s, #10, #13#10, [rfReplaceAll]); end else if mode = lbLinux then begin s := StringReplace(s, #13#10, #13, [rfReplaceAll]); s := StringReplace(s, #10, #13, [rfReplaceAll]); end else if mode = lbMac then begin s := StringReplace(s, #13#10, #10, [rfReplaceAll]); s := StringReplace(s, #13, #10, [rfReplaceAll]); end; result := s; end; // http://www.viathinksoft.de/?page=codelib&showid=70 function ExtractFileNameWithoutExt(const fil: string): string; begin result := Copy(ExtractFileName(fil), 1, Length(ExtractFileName(fil))-Length(ExtractFileExt(fil))); end; function SearchNextFreeName(s: string; wantDir: boolean): string; var i: integer; begin if not FileExists(s) and not DirectoryExists(s) then begin result := s; if wantDir then result := IncludeTrailingPathDelimiter(result); Exit; end; i := 2; if wantDir then begin s := ExcludeTrailingPathDelimiter(s); repeat result := Format('%s (%d)', [s, i]); inc(i); until not DirectoryExists(result) and not FileExists(result); result := IncludeTrailingPathDelimiter(result); end else begin repeat result := Format('%s (%d)%s', [ExtractFilePath(s)+ExtractFileNameWithoutExt(s), i, ExtractFileExt(s)]); inc(i); until not DirectoryExists(result) and not FileExists(result); end; end; // GetSpecialFolderPath // Ref: http://www.wer-weiss-was.de/theme159/article1058561.html function GetSpecialFolderPath(const Folder: integer): string; var PIDL: PItemIDList; Path: array[0..MAX_PATH] of char; Malloc: IMalloc; begin Path := ''; if Succeeded((SHGetSpecialFolderLocation(0, Folder, PIDL))) then if (SHGetPathFromIDList(PIDL, Path)) then if Succeeded(ShGetMalloc(Malloc)) then begin Malloc.Free(PIDL); Malloc := nil; end; Result := Path; end; function IsExtractable(AFilename: string): boolean; var q: integer; uz: TZipMaster19; begin // TODO: Ist die Funktion gut? Fraglich, ob EOC64 ein Teil von EOC ist. uz := TZipMaster19.Create(nil); try q := uz.QueryZip(AFilename); result := true; if (q and zqbHasLocal) <> zqbHasLocal then result := false; if (q and zqbHasCentral) <> zqbHasCentral then result := false; if ((q and zqbHasEOC) <> zqbHasEOC) and ((q and zqbHasEOC64) <> zqbHasEOC64) then result := false; finally uz.Free; end; end; // Ref: http://www.delphiarea.com/articles/how-to-find-if-a-directory-is-writable/ function IsDirectoryWritable(const Dir: String): Boolean; var TempFile: array[0..MAX_PATH] of Char; begin if GetTempFileName(PChar(Dir), 'DA', 0, TempFile) <> 0 then Result := Windows.DeleteFile(TempFile) else Result := False; end; function IsAtFlobbyDisk(AFileOrDir: string): boolean; var s: string; begin s := ExtractFileDrive(AFileOrDir); s := UpperCase(s); result := (s = 'A:') or (s = 'B:'); end; end.
unit MFichas.Model.Usuario; interface uses System.SysUtils, MFichas.Model.Usuario.Interfaces, MFichas.Model.Entidade.USUARIO, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, ORMBR.Container.ObjectSet, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.FDMemTable, ORMBR.Container.DataSet.interfaces, FireDAC.Comp.Client; type TModelUsuario = class(TInterfacedObject, iModelUsuario, iModelUsuarioFuncoes) private FEntidade : TUSUARIO; FEntidadeFiscal: TUSUARIO; FConn : iModelConexaoSQL; FDAOObjectSet : IContainerObjectSet<TUSUARIO>; FDAODataSet : IContainerDataSet<TUSUARIO>; FFDMemTable : TFDMemTable; FMetodos : iModelUsuarioMetodos; constructor Create; public destructor Destroy; override; class function New: iModelUsuario; function Metodos(AValue: iModelUsuarioMetodos): iModelUsuarioMetodos; function Funcoes : iModelUsuarioFuncoes; function Entidade : TUSUARIO; overload; function EntidadeFiscal : TUSUARIO; function Entidade(AEntidade: TUSUARIO): iModelUsuario; overload; function DAO : iContainerObjectSet<TUSUARIO>; function DAODataSet : iContainerDataSet<TUSUARIO>; //FUNCOES function Cadastrar : iModelUsuarioFuncoesCadastrar; function Editar : iModelUsuarioFuncoesEditar; function Buscar : iModelUsuarioFuncoesBuscar; function ValidarUsuarioESenha: iModelUsuarioFuncoesValidarUES; function &End : iModelUsuario; end; implementation { TModelUsuario } uses MFichas.Model.Usuario.Funcoes.Buscar, MFichas.Model.Usuario.Funcoes.Cadastrar, MFichas.Model.Usuario.Funcoes.Editar, MFichas.Model.Usuario.Funcoes.Validacao.ValidarUsuarioESenha; function TModelUsuario.Buscar: iModelUsuarioFuncoesBuscar; begin Result := TModelUsuarioFuncoesBuscar.New(Self); end; function TModelUsuario.Cadastrar: iModelUsuarioFuncoesCadastrar; begin Result := TModelUsuarioFuncoesCadastrar.New(Self); end; function TModelUsuario.&End: iModelUsuario; begin Result := Self; end; constructor TModelUsuario.Create; begin FEntidade := TUSUARIO.Create; FEntidadeFiscal := TUSUARIO.Create; FConn := TModelConexaoFactory.New.ConexaoSQL; FDAOObjectSet := TContainerObjectSet<TUSUARIO>.Create(FConn.Conn, 10); FFDMemTable := TFDMemTable.Create(nil); FDAODataSet := TContainerFDMemTable<TUSUARIO>.Create(FConn.Conn, FFDMemTable); end; function TModelUsuario.DAO: iContainerObjectSet<TUSUARIO>; begin Result := FDAOObjectSet; end; function TModelUsuario.DAODataSet: iContainerDataSet<TUSUARIO>; begin Result := FDAODataSet; end; destructor TModelUsuario.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); FreeAndNil(FEntidadeFiscal); FreeAndNil(FFDMemTable); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; FEntidadeFiscal.Free; FEntidadeFiscal.DisposeOf; FFDMemTable.Free; FFDMemTable.DisposeOf; {$ENDIF} inherited; end; function TModelUsuario.Entidade: TUSUARIO; begin Result := FEntidade; end; function TModelUsuario.Editar: iModelUsuarioFuncoesEditar; begin Result := TModelUsuarioFuncoesEditar.New(Self); end; function TModelUsuario.Entidade(AEntidade: TUSUARIO): iModelUsuario; begin Result := Self; FEntidade := AEntidade; end; function TModelUsuario.EntidadeFiscal: TUSUARIO; begin Result := FEntidadeFiscal; end; function TModelUsuario.Funcoes: iModelUsuarioFuncoes; begin Result := Self; end; function TModelUsuario.Metodos( AValue: iModelUsuarioMetodos): iModelUsuarioMetodos; begin FMetodos := AValue; Result := FMetodos; end; class function TModelUsuario.New: iModelUsuario; begin Result := Self.Create; end; function TModelUsuario.ValidarUsuarioESenha: iModelUsuarioFuncoesValidarUES; begin Result := TModelUsuarioFuncoesValidarUES.New(Self) end; end.
unit AddNoteFileResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, AddressNoteUnit; type TAddNoteFileResponse = class(TGenericParameters) private [JSONName('status')] FStatus: Boolean; [JSONName('note_id')] [Nullable] FNodeId: NullableInteger; [JSONName('upload_id')] [Nullable] FUploadId: NullableString; [JSONName('note')] [NullableObject(TAddressNote)] FNote: NullableObject; public constructor Create; override; destructor Destroy; override; property Status: boolean read FStatus write FStatus; property NodeId: NullableInteger read FNodeId write FNodeId; property UploadId: NullableString read FUploadId write FUploadId; property Note: NullableObject read FNote write FNote; end; implementation { TAddNoteFileResponse } constructor TAddNoteFileResponse.Create; begin inherited; FNodeId := NullableInteger.Null; FUploadId := NullableString.Null; FNote := NullableObject.Null; end; destructor TAddNoteFileResponse.Destroy; begin FNote.Free; inherited; end; end.
{ Subroutine SST_W_C_HEADER_DECL (STYPE,POP_NEEDED) * * Set up for a declaration statement. Nothing is done if this * is already the current statement type. POP_NEEDED is returned TRUE, if the * caller must call SST_W_C_POS_POP when done writing the statement. * This will be true if called while writing executable code. In that case, * the position will be temporarily set back to the requested declaration * statement. } module sst_w_c_HEADER_DECL; define sst_w_c_header_decl; %include 'sst_w_c.ins.pas'; procedure sst_w_c_header_decl ( {if needed, set up for declaration statement} in stype: sment_type_k_t; {desired type of declaration statement} out pop_needed: boolean); {TRUE if caller must pop position when done} const max_msg_parms = 1; {max parameters we can pass to a message} var st: sment_type_k_t; {statement type actually switching to} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin pop_needed := false; {init to no POP needed later by caller} st := stype; {init new statement type to desired type} if {will be global declaration anyway ?} (frame_scope_p^.scope_type = scope_type_global_k) or {at global scope ?} (frame_scope_p^.sment_type = sment_type_declg_k) {already at global level ?} then begin st := sment_type_declg_k; {only global declarations possible here} end; { * Handle cases where we need to push the current position on the stack * and temporarily switch back to the requested statement type. POP_NEEDED * will be set to TRUE to indicate that the caller must pop the state later. * Any of the following conditions require state to be saved before switching: * * 1) Currently inside a continuous statement. * * 2) Currently inside executable code. * * 3) The requested statement type is GLOBAL DECLARATION, but the current * position is not at the global level. } if (frame_sment_p <> nil) or {currently inside a statement ?} (frame_scope_p^.sment_type = sment_type_exec_k) or {in executable code ?} ( (st = sment_type_declg_k) and {want global declaration from elsewhere ?} (frame_scope_p^.sment_type <> st) ) then begin sst_w_c_pos_push (st); {push curr state and go to statement start} pop_needed := true; {caller will have to pop position later} return; end; { * All done if already in this statement type anyway. } if st = frame_scope_p^.sment_type {already doing this kind of statement ?} then return; { * We are not inside the start/end of a continuous statement or within * executable code, but are not writing the desired statement type either. * In this case, just switch to the new statement type since there won't be * any need to restore to the current position. } case st of {what kind of statement do we want ?} sment_type_decll_k: begin frame_scope_p^.pos_decll := sst_out.dyn_p^; {init position to here} sst_out.dyn_p := addr(frame_scope_p^.pos_decll); {use pos for this sment type} end; otherwise sys_msg_parm_int (msg_parm[1], ord(st)); sys_message_bomb ('sst_c_write', 'decl_statement_type_bad', msg_parm, 1); end; frame_scope_p^.sment_type := st; {indicate we are now in new statement type} end;
unit xStyleContainer; interface uses SysUtils, Classes, Controls, xGradient; type TxStyleContainer = class(TComponent) private FList: TList; FGradient: TxGradient; procedure SetGradient(const Value: TxGradient); procedure SetStyle; procedure GrChange(Sender: TObject); procedure NotifyCtrls; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RegControl(AControl: TControl); procedure UnregControl(AControl: TControl); published property Gradient: TxGradient read FGradient write SetGradient; end; implementation uses xButton; constructor TxStyleContainer.Create(AOwner: TComponent); begin inherited; FGradient := TxGradient.Create(nil); FGradient.OnChange := GrChange; FList := TList.Create; end; destructor TxStyleContainer.Destroy; begin try NotifyCtrls; FList.Clear; FList.Free; FGradient.Free; except end; inherited; end; procedure TxStyleContainer.GrChange(Sender: TObject); begin SetStyle; end; procedure TxStyleContainer.NotifyCtrls; var i: Integer; begin try for i := 0 to FList.Count - 1 do with TxButton(FList[i]) do ContainerDeleted; except end; end; procedure TxStyleContainer.RegControl(AControl: TControl); begin if FList.IndexOf(AControl) = -1 then FList.Add(AControl); end; procedure TxStyleContainer.SetGradient(const Value: TxGradient); begin FGradient := Value; end; procedure TxStyleContainer.SetStyle; var i: Integer; begin try for i := 0 to FList.Count - 1 do with TxButton(FList[i]) do Gradient.Assign(Self.Gradient); except end; end; procedure TxStyleContainer.UnregControl(AControl: TControl); begin if FList.IndexOf(AControl) <> -1 then FList.Delete(FList.IndexOf(AControl)); end; end.
unit AddressGeocodingUnit; interface uses REST.Json.Types, System.Generics.Collections, SysUtils, Generics.Defaults, JSONNullableAttributeUnit, NullableBasicTypesUnit, DirectionPathPointUnit; type /// <summary> /// Geocoding /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/geocoding.dtd /// </remarks> TAddressGeocoding = class private [JSONName('key')] [Nullable] FKey: NullableString; [JSONName('name')] [Nullable] FName: NullableString; [JSONName('bbox')] [NullableArray(TDirectionPathPoint)] FBoundaryBox: TDirectionPathPointArray; [JSONName('lat')] [Nullable] FLatitude: NullableDouble; [JSONName('lng')] [Nullable] FLongitude: NullableDouble; [JSONName('confidence')] [Nullable] FConfidence: NullableString; [JSONName('type')] [Nullable] FType: NullableString; [JSONName('postalCode')] [Nullable] FPostalCode: NullableString; [JSONName('countryRegion')] [Nullable] FCountryRegion: NullableString; [JSONName('curbside_coordinates')] [NullableArray(TDirectionPathPoint)] FCurbsideCoordinates: TDirectionPathPointArray; public constructor Create; destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// A unique identifier for the geocoding /// </summary> property Key: NullableString read FKey write FKey; /// <summary> /// Specific description of the geocoding result /// </summary> property Name: NullableString read FName write FName; /// <summary> /// Boundary box /// </summary> property BoundaryBox: TDirectionPathPointArray read FBoundaryBox; procedure AddBoundaryBox(Value: TDirectionPathPoint); /// <summary> /// Latitude /// </summary> property Latitude: NullableDouble read FLatitude write FLatitude; /// <summary> /// Longitude /// </summary> property Longitude: NullableDouble read FLongitude write FLongitude; /// <summary> /// Confidence ("high", "medium", "low") /// </summary> property Confidence: NullableString read FConfidence write FConfidence; /// <summary> /// Non-standardized. Is used for tooltip ("Street", "City" etc) /// </summary> property Type_: NullableString read FType write FType; /// <summary> /// If the result has a postal code, it's returned here /// </summary> property PostalCode: NullableString read FPostalCode write FPostalCode; /// <summary> /// If the region is known, it's returned here /// </summary> property CountryRegion: NullableString read FCountryRegion write FCountryRegion; /// <summary> /// Curbside Coordinates /// </summary> property CurbsideCoordinates: TDirectionPathPointArray read FCurbsideCoordinates; procedure AddCurbsideCoordinate(Value: TDirectionPathPoint); end; TAddressGeocodingArray = TArray<TAddressGeocoding>; function SorTAddressGeocodings(Geocodings: TAddressGeocodingArray): TAddressGeocodingArray; implementation function SorTAddressGeocodings(Geocodings: TAddressGeocodingArray): TAddressGeocodingArray; begin SetLength(Result, Length(Geocodings)); if Length(Geocodings) = 0 then Exit; TArray.Copy<TAddressGeocoding>(Geocodings, Result, Length(Geocodings)); TArray.Sort<TAddressGeocoding>(Result, TComparer<TAddressGeocoding>.Construct( function (const Geocoding1, Geocoding2: TAddressGeocoding): Integer begin Result := Geocoding1.Key.Compare(Geocoding2.Key); end)); end; { TAddressGeocoding } procedure TAddressGeocoding.AddBoundaryBox(Value: TDirectionPathPoint); begin SetLength(FBoundaryBox, Length(FBoundaryBox) + 1); FBoundaryBox[High(FBoundaryBox)] := Value; end; procedure TAddressGeocoding.AddCurbsideCoordinate(Value: TDirectionPathPoint); begin SetLength(FCurbsideCoordinates, Length(FCurbsideCoordinates) + 1); FCurbsideCoordinates[High(FCurbsideCoordinates)] := Value; end; constructor TAddressGeocoding.Create; begin Inherited; FKey := NullableString.Null; FName := NullableString.Null; FLatitude := NullableDouble.Null; FLongitude := NullableDouble.Null; FConfidence := NullableString.Null; FType := NullableString.Null; FPostalCode := NullableString.Null; FCountryRegion := NullableString.Null; SetLength(FBoundaryBox, 0); SetLength(FCurbsideCoordinates, 0); end; destructor TAddressGeocoding.Destroy; var i: integer; begin for i := Length(FBoundaryBox) - 1 downto 0 do FreeAndNil(FBoundaryBox[i]); for i := Length(FCurbsideCoordinates) - 1 downto 0 do FreeAndNil(FCurbsideCoordinates[i]); inherited; end; function TAddressGeocoding.Equals(Obj: TObject): Boolean; var Other: TAddressGeocoding; i: integer; SortedBoundaryBox1, SortedBoundaryBox2: TDirectionPathPointArray; SortedCurbsideCoordinates1, SortedCurbsideCoordinates2: TDirectionPathPointArray; begin Result := False; if not (Obj is TAddressGeocoding) then Exit; Other := TAddressGeocoding(Obj); Result := (FKey = Other.FKey) and (FName = Other.FName) and (FLongitude = Other.FLongitude) and (FConfidence = Other.FConfidence) and (FType = Other.FType) and (FPostalCode = Other.FPostalCode) and (FCountryRegion = Other.FCountryRegion); if not Result then Exit; Result := False; if (Length(FBoundaryBox) <> Length(Other.FBoundaryBox)) or (Length(FCurbsideCoordinates) <> Length(Other.FCurbsideCoordinates)) then Exit; SortedBoundaryBox1 := DirectionPathPointUnit.SortDirectionPathPoints(BoundaryBox); SortedBoundaryBox2 := DirectionPathPointUnit.SortDirectionPathPoints(Other.BoundaryBox); for i := 0 to Length(SortedBoundaryBox1) - 1 do if (not SortedBoundaryBox1[i].Equals(SortedBoundaryBox2[i])) then Exit; SortedCurbsideCoordinates1 := DirectionPathPointUnit.SortDirectionPathPoints(CurbsideCoordinates); SortedCurbsideCoordinates2 := DirectionPathPointUnit.SortDirectionPathPoints(Other.CurbsideCoordinates); for i := 0 to Length(SortedCurbsideCoordinates1) - 1 do if (not SortedCurbsideCoordinates1[i].Equals(SortedCurbsideCoordinates2[i])) then Exit; Result := True; end; end.
unit MainFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls; type TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; const // 源文件,被复制的文件 SOURCE_FILE: string = 'E:\群图标.png'; // 目标文件,复制出来的文件 TARGET_FILE: string = 'E:\copy.png'; // 所谓无类型文件,就是二进制文件 implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var SourceFile, TargetFile: file; var // 缓存:临时存放数据的空间 Buf: array [0 .. 255] of Byte; begin // 关联变量 AssignFile(SourceFile, SOURCE_FILE); AssignFile(TargetFile, TARGET_FILE); try // 设置打开方式 Reset(SourceFile); Rewrite(TargetFile); ProgressBar1.Max := FileSize(SourceFile); // 边读边写 while not Eof(SourceFile) do begin // 读取一个字节的数据 BlockRead(SourceFile, Buf, 1); BlockWrite(TargetFile, Buf, 1); ProgressBar1.Position := FileSize(TargetFile); ProgressBar1.Update; end; finally // 关闭文件 CloseFile(SourceFile); CloseFile(TargetFile); end; end; end.
{ MIT License Copyright (c) 2017 Marcos Douglas B. Santos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit James.Data.Tests; {$include james.inc} interface uses Classes, SysUtils, fpcunit, testregistry, James.Data, James.Data.Clss; type TDataStreamTest = class(TTestCase) published procedure AsString; procedure SaveStream; procedure SaveStrings; end; TDataInformationsTest = class(TTestCase) published procedure ReceiveInformation; procedure ReceiveInformations; procedure Counter; end; TFakeConstraint = class(TInterfacedObject, IDataConstraint) private FValue: Boolean; FId: string; FText: string; public constructor Create(Value: Boolean; const Id, Text: string); class function New(Value: Boolean; const Id, Text: string): IDataConstraint; function Checked: IDataResult; end; TDataConstraintsTest = class(TTestCase) published procedure ReceiveConstraint; procedure GetConstraint; procedure CheckedTrue; procedure CheckedFalse; procedure CheckedTrueAndFalse; end; implementation { TFakeConstraint } constructor TFakeConstraint.Create(Value: Boolean; const Id, Text: string); begin inherited Create; FValue := Value; FId := Id; FText := Text; end; class function TFakeConstraint.New(Value: Boolean; const Id, Text: string ): IDataConstraint; begin Result := Create(Value, Id, Text); end; function TFakeConstraint.Checked: IDataResult; begin Result := TDataResult.New(FValue, TDataInformation.New(FId, FText)); end; { TDataStreamTest } procedure TDataStreamTest.AsString; const TXT = 'Line1-'#13#10'Line2-'#13#10'Line3'; var Buf: TMemoryStream; Ss: TStrings; begin Buf := TMemoryStream.Create; Ss := TStringList.Create; try Buf.WriteBuffer(TXT[1], Length(TXT) * SizeOf(Char)); Ss.Text := TXT; AssertEquals('Test Stream', TXT, TDataStream.New(Buf).AsString); AssertEquals('Test String', TXT, TDataStream.New(TXT).AsString); AssertEquals('Test Strings', TXT+#13#10, TDataStream.New(Ss).AsString); finally Buf.Free; Ss.Free; end; end; procedure TDataStreamTest.SaveStream; const TXT = 'ABCDEFG#13#10IJL'; var Buf: TMemoryStream; S: string; begin Buf := TMemoryStream.Create; try TDataStream.New(TXT).Save(Buf); SetLength(S, Buf.Size * SizeOf(Char)); Buf.Position := 0; Buf.ReadBuffer(S[1], Buf.Size); AssertEquals(TXT, S); finally Buf.Free; end; end; procedure TDataStreamTest.SaveStrings; const TXT = 'ABCDEFG#13#10IJLMNO-PQRS'; var Ss: TStrings; begin Ss := TStringList.Create; try TDataStream.New(TXT).Save(Ss); AssertEquals(TXT+#13#10, Ss.Text); finally Ss.Free; end; end; { TDataInformationsTest } procedure TDataInformationsTest.ReceiveInformation; begin AssertEquals( 'foo: data', TDataInformations.New .Add(TDataInformation.New('foo', 'data')) .Text ); end; procedure TDataInformationsTest.ReceiveInformations; begin AssertEquals( 'foo: data 1'#13'foo: data 2'#13'foo: data 3', TDataInformations.New .Add(TDataInformation.New('foo', 'data 1')) .Add(TDataInformation.New('foo', 'data 2')) .Add(TDataInformation.New('foo', 'data 3')) .Text ); end; procedure TDataInformationsTest.Counter; begin AssertEquals( 3, TDataInformations.New .Add(TDataInformation.New('foo')) .Add(TDataInformation.New('foo')) .Add(TDataInformation.New('foo')) .Count ); end; { TDataConstraintsTest } procedure TDataConstraintsTest.ReceiveConstraint; begin AssertTrue( TDataConstraints.New .Add(TFakeConstraint.New(True, 'id', 'foo')) .Checked .OK ); end; procedure TDataConstraintsTest.GetConstraint; begin AssertEquals( 'id: foo', TDataConstraints.New .Add(TFakeConstraint.New(True, 'id', 'foo')) .Get(0) .Checked .Informations .Text ); end; procedure TDataConstraintsTest.CheckedTrue; begin AssertTrue( TDataConstraints.New .Add(TFakeConstraint.New(True, 'id', 'foo')) .Add(TFakeConstraint.New(True, 'id', 'foo')) .Checked .OK ); end; procedure TDataConstraintsTest.CheckedFalse; begin AssertFalse( TDataConstraints.New .Add(TFakeConstraint.New(False, 'id', 'foo')) .Add(TFakeConstraint.New(False, 'id', 'foo')) .Checked .OK ); end; procedure TDataConstraintsTest.CheckedTrueAndFalse; begin AssertFalse( TDataConstraints.New .Add(TFakeConstraint.New(True, 'id', 'foo')) .Add(TFakeConstraint.New(False, 'id', 'foo')) .Checked .OK ); end; initialization RegisterTest('Data', TDataStreamTest); RegisterTest('Data', TDataInformationsTest); RegisterTest('Data', TDataConstraintsTest); end.
unit mebdd_worker_proc; (* MEB-DD's process related functions *) {$MODE OBJFPC} interface uses Classes; const DRIVE_MAX = 99; type Tdrive_string_arr = Array [0..DRIVE_MAX] of AnsiString; Tproc_output_arr = Array [0..DRIVE_MAX] of AnsiString; Texec_params = Record executable : AnsiString; parameters : TStringList; end; Texec_params_array = Array [0..DRIVE_MAX] of Texec_params; var proc_log_file : AnsiString = ''; function is_pid_alive (const pid: DWORD; const proc_name:AnsiString): Boolean; procedure proc_log_filename (filename:AnsiString); procedure proc_log_truncate (); procedure proc_log_writeln (message:AnsiString); procedure proc_log_halt (e:Integer); procedure proc_log_string (message:AnsiString); function run_processes(proc_count:Word; cmdline:Texec_params_array):Tproc_output_arr; function run_processes_count(proc_count:Word; cmdline:Texec_params_array; success_regexp:AnsiString; failure_regexp:AnsiString):Word; implementation uses Sysutils, Windows, JwaTlHelp32, Process, RegExpr; function is_pid_alive (const pid: DWORD; const proc_name:AnsiString): Boolean; var i: integer; _result: Boolean; CPID: DWORD; CProcName: array[0..259] of char; S: HANDLE; PE: TProcessEntry32; begin _result := false; CProcName := ''; S := CreateToolHelp32Snapshot(TH32CS_SNAPALL, 0); // Create snapshot PE.DWSize := SizeOf(PE); // Set size before use I := 1; if Process32First(S, PE) then repeat CProcName := PE.szExeFile; CPID := PE.th32ProcessID; if (CPID=pid) and (UpperCase(CProcName) = UpperCase(proc_name)) then _result := true; Inc(i); until not Process32Next(S, PE); CloseHandle(S); is_pid_alive := _result; end; procedure proc_log_filename (filename:AnsiString); begin proc_log_file := filename; end; procedure proc_log_truncate (); var f: TextFile; begin if proc_log_file <> '' then begin AssignFile(f, proc_log_file); ReWrite(f); CloseFile(f); end; end; procedure proc_log_writeln (message:AnsiString); begin writeln(message); proc_log_string(message); end; procedure proc_log_halt (e:Integer); begin proc_log_string('Exiting with code #'+IntToStr(e)); halt(e); end; procedure proc_log_string (message:AnsiString); var f: TextFile; begin if proc_log_file <> '' then begin AssignFile(f, proc_log_file); {I+} try Append(f); except on E: EInOutError do ReWrite(f); end; writeln(f, message); CloseFile(f); end; end; function run_processes(proc_count:Word; cmdline:Texec_params_array):Tproc_output_arr; var proc_handle: Array [0..DRIVE_MAX] of TProcess; proc_output: Array [0..DRIVE_MAX] of TMemoryStream; proc_finished: Array [0..DRIVE_MAX] of Boolean; proc_output_bytes: Array [0..DRIVE_MAX] of LongInt; proc_output_bytes_available: LongInt; proc_output_bytes_read: LongInt; proc_output_stringlist: TStringList; proc_output_result: Tproc_output_arr; finished_processes:Word; n:Word; cycle_string: Array of AnsiString; cycle_n: Word; // Helper procedure to read process output from the process handle and add it to // the process output stream (proc_output) procedure add_proc_output_data(proc_index:Word); begin proc_output_bytes_available := proc_handle[proc_index].Output.NumBytesAvailable; if proc_output_bytes_available > 0 then begin // The stream has data // Allocate space proc_output[proc_index].SetSize(proc_output_bytes[proc_index] + proc_output_bytes_available); proc_output_bytes_read := proc_handle[proc_index].Output.Read((proc_output[proc_index].Memory + proc_output_bytes[proc_index])^, proc_output_bytes_available); if proc_output_bytes_read > 0 then proc_output_bytes[proc_index] := proc_output_bytes[proc_index] + proc_output_bytes_read; end; end; begin // Debugging code proc_log_string('Running following processes:'); for n := 0 to proc_count-1 do begin proc_log_string(cmdline[n].executable + ': ' + cmdline[n].parameters.CommaText); end; // Set cycle string array SetLength(cycle_string, 4); cycle_string[0] := '.'; cycle_string[1] := 'o'; cycle_string[2] := 'O'; cycle_string[3] := 'o'; cycle_n := 0; // Start processes for n := 0 to proc_count-1 do begin // Initialise process data proc_handle[n] := TProcess.Create(nil); proc_handle[n].Executable := cmdline[n].executable; proc_handle[n].Parameters := cmdline[n].parameters; // Put all I/O through pipes proc_handle[n].Options := [poUsePipes, poStdErrToOutPut]; proc_handle[n].Execute; // Initialise output stream proc_output[n] := TMemoryStream.Create; proc_output_bytes[n] := 0; // Turn finish flag down proc_finished[n] := false; end; // Wait for all processed to end finished_processes := 0; while finished_processes < proc_count do begin // Count cycle pointer cycle_n := cycle_n + 1; cycle_n := cycle_n mod Length(cycle_string); for n := 0 to proc_count-1 do begin // Read output (if available) add_proc_output_data(n); if proc_handle[n].Running then begin // This process is still running //writeln(IntToStr(proc_handle[n].ProcessID) + ': ' + cycle_string[cycle_n]); end else begin // This process has finished // If this is the first time to encounter this, do things if not proc_finished[n] then begin Inc(finished_processes); // Read output (if available) add_proc_output_data(n); // Turn flag up so we don't run this again proc_finished[n] := True; proc_output_stringlist := TStringList.Create; proc_output_stringlist.LoadFromStream(proc_output[n]); // Add exit code to proc_output proc_output_stringlist.Add('exit_code:'+IntToStr(proc_handle[n].ExitStatus)); // Log process output proc_log_string('Process finished:'); proc_log_string(proc_output_stringlist.Text); // Store process output proc_output_result[n] := proc_output_stringlist.Text; end; end; end; // Update status line write('Jobs running: ' + IntToStr(proc_count - finished_processes) + ' ' + cycle_string[cycle_n] + AnsiString(#13)); // Wait a bit until checking the process status again Sleep(1000); end; run_processes := proc_output_result; end; function run_processes_count(proc_count:Word; cmdline:Texec_params_array; success_regexp:AnsiString; failure_regexp:AnsiString):Word; var process_output: Tproc_output_arr; n: Word; RegexObj: TRegExpr; process_failed: Boolean; failed_processes: Word; begin // Call underlying process executer process_output := run_processes(proc_count, cmdline); // Go through all output failed_processes := 0; for n := 0 to proc_count-1 do begin // Check from output whether process output if process has failed process_failed := False; // First check the success regexp if success_regexp <> '' then begin RegexObj := TRegExpr.Create; RegexObj.Expression := success_regexp; RegexObj.ModifierI := True; if RegexObj.Exec(process_output[n]) then begin // This process reported success process_failed := False; end else begin // Oops, the output misses the success match process_failed := True; end; end; if failure_regexp <> '' then begin RegexObj := TRegExpr.Create; RegexObj.Expression := failure_regexp; RegexObj.ModifierI := True; if RegexObj.Exec(process_output[n]) then begin // This process reported failure process_failed := True; end; end; RegexObj.Free; if process_failed then begin proc_log_string('Process finish status: FAILED'); Inc(failed_processes); end else begin proc_log_string('Process finish status: SUCCESS'); end; end; run_processes_count := proc_count - failed_processes; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.10 11/12/2004 11:30:16 AM JPMugaas Expansions for IPv6. Rev 1.9 11/11/2004 10:25:22 PM JPMugaas Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions from the UDP client with SOCKS. You must call OpenProxy before using RecvFrom or SendTo. When you are finished, you must use CloseProxy to close any connection to the Proxy. Connect and disconnect also call OpenProxy and CloseProxy. Rev 1.8 11/11/2004 3:42:52 AM JPMugaas Moved strings into RS. Socks will now raise an exception if you attempt to use SOCKS4 and SOCKS4A with UDP. Those protocol versions do not support UDP at all. Rev 1.7 11/9/2004 8:18:00 PM JPMugaas Attempt to add SOCKS support in UDP. Rev 1.6 6/6/2004 11:51:56 AM JPMugaas Fixed TODO with an exception Rev 1.5 2004.02.03 4:17:04 PM czhower For unit name changes. Rev 1.4 10/15/2003 10:59:06 PM DSiders Corrected spelling error in resource string name. Added resource string for circular links exception in transparent proxy. Rev 1.3 10/15/2003 10:10:18 PM DSiders Added localization comments. Rev 1.2 5/16/2003 9:22:38 AM BGooijen Added Listen(...) Rev 1.1 5/14/2003 6:41:00 PM BGooijen Added Bind(...) Rev 1.0 12/2/2002 05:01:26 PM JPMugaas Rechecked in due to file corruption. } unit IdCustomTransparentProxy; interface {$I IdCompilerDefines.inc} //we need to put this in Delphi mode to work uses Classes, IdComponent, IdException, IdGlobal, IdIOHandler, IdSocketHandle, IdBaseComponent; type EIdTransparentProxyCircularLink = class(EIdException); EIdTransparentProxyUDPNotSupported = class(EIdException); TIdCustomTransparentProxyClass = class of TIdCustomTransparentProxy; TIdCustomTransparentProxy = class(TIdComponent) protected FHost: String; FPassword: String; FPort: TIdPort; FIPVersion : TIdIPVersion; FUsername: String; FChainedProxy: TIdCustomTransparentProxy; // function GetEnabled: Boolean; virtual; abstract; procedure SetEnabled(AValue: Boolean); virtual; procedure MakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetChainedProxy(const AValue: TIdCustomTransparentProxy); public procedure Assign(ASource: TPersistent); override; procedure OpenUDP(AHandle : TIdSocketHandle; const AHost: string = ''; const APort: TIdPort = 0; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; procedure CloseUDP(AHandle: TIdSocketHandle); virtual; function RecvFromUDP(AHandle: TIdSocketHandle; var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion; AMSec: Integer = IdTimeoutDefault): Integer; virtual; procedure SendToUDP(AHandle: TIdSocketHandle; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion; const ABuffer : TIdBytes); virtual; procedure Connect(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); // procedure Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION);overload;virtual; procedure Bind(AIOHandler: TIdIOHandler; const APort: TIdPort); overload; function Listen(AIOHandler: TIdIOHandler; const ATimeOut: Integer): Boolean; virtual; // property Enabled: Boolean read GetEnabled write SetEnabled; property Host: String read FHost write FHost; property Password: String read FPassword write FPassword; property Port: TIdPort read FPort write FPort; property IPVersion : TIdIPVersion read FIPVersion write FIPVersion default ID_DEFAULT_IP_VERSION; property Username: String read FUsername write FUsername; property ChainedProxy: TIdCustomTransparentProxy read FChainedProxy write SetChainedProxy; end; implementation uses IdResourceStringsCore, IdExceptionCore; { TIdCustomTransparentProxy } procedure TIdCustomTransparentProxy.Assign(ASource: TPersistent); Begin if ASource is TIdCustomTransparentProxy then begin with TIdCustomTransparentProxy(ASource) do begin Self.FHost := Host; Self.FPassword := Password; Self.FPort := Port; Self.FIPVersion := IPVersion; Self.FUsername := Username; end end else begin inherited Assign(ASource); end; End;// procedure TIdCustomTransparentProxy.Connect(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin if Assigned(FChainedProxy) and FChainedProxy.Enabled then begin MakeConnection(AIOHandler, FChainedProxy.Host, FChainedProxy.Port); FChainedProxy.Connect(AIOHandler, AHost, APort, AIPVersion); end else begin MakeConnection(AIOHandler, AHost, APort, AIPVersion); end; end; function TIdCustomTransparentProxy.Listen(AIOHandler: TIdIOHandler; const ATimeOut: integer):boolean; begin raise EIdTransparentProxyCantBind.Create(RSTransparentProxyCannotBind); end; procedure TIdCustomTransparentProxy.Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin raise EIdTransparentProxyCantBind.Create(RSTransparentProxyCannotBind); end; procedure TIdCustomTransparentProxy.Bind(AIOHandler: TIdIOHandler; const APort: TIdPort); begin Bind(AIOHandler, '0.0.0.0', APort); {do not localize} end; procedure TIdCustomTransparentProxy.SetEnabled(AValue: Boolean); Begin End; procedure TIdCustomTransparentProxy.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FChainedProxy) then begin FChainedProxy := nil; end; inherited Notification(AComponent,Operation); end; procedure TIdCustomTransparentProxy.SetChainedProxy(const AValue: TIdCustomTransparentProxy); var LNextValue: TIdCustomTransparentProxy; begin LNextValue := AValue; while Assigned(LNextValue) do begin if LNextValue = Self then begin raise EIdTransparentProxyCircularLink.CreateFmt(RSInterceptCircularLink, [ClassName]);// -> One EIDCircularLink exception end; LNextValue := LNextValue.FChainedProxy; end; if Assigned(FChainedProxy) then begin FChainedProxy.RemoveFreeNotification(Self); end; FChainedProxy := AValue; if Assigned(FChainedProxy) then begin FChainedProxy.FreeNotification(Self); end; end; procedure TIdCustomTransparentProxy.CloseUDP(AHandle: TIdSocketHandle); begin raise EIdTransparentProxyUDPNotSupported.Create(RSTransparentProxyCanNotSupportUDP); end; procedure TIdCustomTransparentProxy.OpenUDP(AHandle: TIdSocketHandle; const AHost: string = ''; const APort: TIdPort = 0; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin raise EIdTransparentProxyUDPNotSupported.Create(RSTransparentProxyCanNotSupportUDP); end; function TIdCustomTransparentProxy.RecvFromUDP(AHandle: TIdSocketHandle; var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion; AMSec: Integer = IdTimeoutDefault): Integer; begin raise EIdTransparentProxyUDPNotSupported.Create(RSTransparentProxyCanNotSupportUDP); end; procedure TIdCustomTransparentProxy.SendToUDP(AHandle: TIdSocketHandle; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion; const ABuffer : TIdBytes); begin raise EIdTransparentProxyUDPNotSupported.Create(RSTransparentProxyCanNotSupportUDP); end; end.