text
stringlengths
14
6.51M
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clCertificateStore; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clCertificate, clCertificateKey, clCryptAPI, clCryptUtils, clUtils, clWUtils; type TclRevocationFlags = (rfNone, rfCheckEndOnly, rfCheckAll, rfExcludeRoot); TclCertificateStoreLocation = (slCurrentUser, slLocalMachine); TclCertificateImportFlag = (ifMakeExportable, ifStrongProtection, ifMachineKeyset, ifUserKeyset); TclCertificateImportFlags = set of TclCertificateImportFlag; TclGetCertificateEvent = procedure (Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean) of object; TclCertificateVerifiedEvent = procedure (Sender: TObject; ACertificate: TclCertificate; ATrustStatus, ATrustInfo: Integer) of object; TclCertificateStore = class(TComponent) private FList: TclCertificateList; FStoreHandle: HCERTSTORE; FStoreName: string; FStoreLocation: TclCertificateStoreLocation; FCSP: string; FKeyName: string; FKeyLength: Integer; FKeyType: TclCertificateKeyType; FValidFrom: TDateTime; FValidTo: TDateTime; FCRLFlags: TclRevocationFlags; FOnCertificateVerified: TclCertificateVerifiedEvent; FKeyUsage: Integer; FEnhancedKeyUsage: TStrings; FProviderType: Integer; FCSPPtr: PclChar; function GetCSP: PclChar; function GetItems: TclCertificateList; procedure InternalLoad(hStore: HCERTSTORE; ARemoveDuplicates: Boolean); function InternalImportCER(const ABytes: TclByteArray): TclCertificate; function InternalExportCER(ACertificate: TclCertificate): TclByteArray; function InternalSignCSR(AIssuer: TclCertificate; ARequest: TclByteArray; ASerialNumber: Integer): TclCertificate; function InternalCreateSigned(AIssuer: TclCertificate; ASubject: PCRYPT_DATA_BLOB; ASerialNumber: Integer; AExtensions: PCERT_EXTENSION; AExtensionCount: Integer): TclCertificate; function InternalExportKey(const AName: string): TclByteArray; procedure InternalImportKey(const AName: string; const ABytes: TclByteArray); procedure CreateContext(var context: HCRYPTPROV; var key: HCRYPTKEY); function GetKeyTypeInt: Integer; function GenerateKey(AContext: HCRYPTPROV; AKeySpec: DWORD): HCRYPTKEY; function GenerateSubject(const ASubject: string): TclCryptData; function GetPublicKeyInfo(AContext: HCRYPTPROV; Alg: DWORD): TclCryptData; function GetSerialNumber(ASerialNumber: Integer): Integer; procedure GetCertificatePrivateKey(ACertificate: PCCERT_CONTEXT; var AContext: HCRYPTPROV; var Alg: Integer); function SignAndEncodeRequest(AContext: HCRYPTPROV; Alg: DWORD; AReqInfo: PCERT_REQUEST_INFO; ASigAlg: PCRYPT_ALGORITHM_IDENTIFIER): TclCryptData; function SignAndEncodeCert(AContext: HCRYPTPROV; Alg: DWORD; ACertInfo: PCERT_INFO): TclCryptData; procedure SaveCSR(AEncodedRequest: TclByteArray; AStream: TStream; ABase64Encode: Boolean); procedure FillCertInfo(ACertInfo: PCERT_INFO; ASubject: PCRYPT_DATA_BLOB; AIssuer: PCRYPT_DATA_BLOB); procedure GetCertificateChain(hStore: HCERTSTORE; ACertificate: TclCertificate; var ATrustStatus, ATrustInfo: Integer); function GetExtensions: TclCertificateExtensions; procedure SetEnhancedKeyUsage(const Value: TStrings); function GetExtensionAttribute(AReqInfo: PCERT_REQUEST_INFO): TclCryptData; procedure SetCSP(const Value: string); protected procedure DoCertificateVerified(ACertificate: TclCertificate; ATrustStatus, ATrustInfo: Integer); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open(const AStoreName: string); overload; procedure Open(const AStoreName: string; AStoreLocation: TclCertificateStoreLocation); overload; procedure Open(AStoreHandle: HCERTSTORE); overload; procedure Close; function CreateSelfSigned(const ASubject: string; ASerialNumber: Integer): TclCertificate; function CreateSigned(AIssuer: TclCertificate; const ASubject: string; ASerialNumber: Integer): TclCertificate; procedure CreateCSR(const ASubject, ARequestFile: string); overload; procedure CreateCSR(const ASubject: string; ARequest: TStream; ABase64Encode: Boolean); overload; function SignCSR(AIssuer: TclCertificate; const ARequestFile: string; ASerialNumber: Integer): TclCertificate; overload; function SignCSR(AIssuer: TclCertificate; ARequest: TStream; ASerialNumber: Integer): TclCertificate; overload; procedure ImportFromPFX(const AFileName, APassword: string); overload; procedure ImportFromPFX(const AFileName, APassword: string; AFlags: TclCertificateImportFlags); overload; procedure ImportFromPFX(AStream: TStream; const APassword: string; AFlags: TclCertificateImportFlags); overload; procedure ImportFromCER(const AFileName: string); overload; procedure ImportFromCER(AStream: TStream); overload; procedure ImportSignedCSR(const AFileName: string); overload; procedure ImportSignedCSR(AStream: TStream); overload; procedure ImportFromMessage(const AFileName: string); overload; procedure ImportFromMessage(AStream: TStream); overload; procedure ImportFromMessage(const AData: TclCryptData); overload; procedure ExportToPFX(ACertificate: TclCertificate; const AFileName, APassword: string); overload; procedure ExportToPFX(ACertificate: TclCertificate; const AFileName, APassword: string; AIncludeAll: Boolean); overload; procedure ExportToPFX(ACertificate: TclCertificate; AStream: TStream; const APassword: string; AIncludeAll: Boolean); overload; procedure ExportToCER(ACertificate: TclCertificate; const AFileName: string); overload; procedure ExportToCER(ACertificate: TclCertificate; AStream: TStream; ABase64Encode: Boolean); overload; function Verify(ACertificate: TclCertificate; var ATrustStatus, ATrustInfo: Integer): Boolean; overload; function Verify(ACertificate: TclCertificate): Boolean; overload; procedure Install(ACertificate: TclCertificate); procedure Uninstall(ACertificate: TclCertificate); function IsInstalled(ACertificate: TclCertificate): Boolean; function CertificateByEmail(const AEmail: string): TclCertificate; function CertificateByIssuedTo(const AIssuedTo: string): TclCertificate; function CertificateBySerialNo(const ASerialNumber, AIssuer: string): TclCertificate; function CertificateByThumbprint(const AThumbprint: string): TclCertificate; function CertificateBySKI(const ASubjectKeyIdentifier: string): TclCertificate; function FindByEmail(const AEmail: string): TclCertificate; overload; function FindByEmail(const AEmail: string; ARequirePrivateKey: Boolean): TclCertificate; overload; function FindByIssuedTo(const AIssuedTo: string): TclCertificate; overload; function FindByIssuedTo(const AIssuedTo: string; ARequirePrivateKey: Boolean): TclCertificate; overload; function FindBySerialNo(const ASerialNumber, AIssuer: string): TclCertificate; overload; function FindBySerialNo(const ASerialNumber, AIssuer: string; ARequirePrivateKey: Boolean): TclCertificate; overload; function FindByThumbprint(const AThumbprint: string): TclCertificate; overload; function FindByThumbprint(const AThumbprint: string; ARequirePrivateKey: Boolean): TclCertificate; overload; function FindBySKI(const ASubjectKeyIdentifier: string): TclCertificate; overload; function FindBySKI(const ASubjectKeyIdentifier: string; ARequirePrivateKey: Boolean): TclCertificate; overload; procedure CreateKey(const AName: string); procedure DeleteKey(const AName: string); procedure GetKeyList(AList: TStrings); function KeyExists(const AName: string): Boolean; function GetKey(const AName: string): TclCertificateKey; procedure ExportKey(const AName: string; AStream: TStream; ABase64Encode: Boolean); overload; procedure ExportKey(const AName, AFileName: string); overload; procedure ImportKey(const AName: string; AStream: TStream); overload; procedure ImportKey(const AName, AFileName: string); overload; property Items: TclCertificateList read GetItems; property StoreHandle: HCERTSTORE read FStoreHandle; published property StoreName: string read FStoreName write FStoreName; property StoreLocation: TclCertificateStoreLocation read FStoreLocation write FStoreLocation default slCurrentUser; property CSP: string read FCSP write SetCSP; property ProviderType: Integer read FProviderType write FProviderType default PROV_RSA_FULL; property KeyName: string read FKeyName write FKeyName; property KeyLength: Integer read FKeyLength write FKeyLength default 1024; property KeyType: TclCertificateKeyType read FKeyType write FKeyType default ktKeyExchange; property ValidFrom: TDateTime read FValidFrom write FValidFrom; property ValidTo: TDateTime read FValidTo write FValidTo; property CRLFlags: TclRevocationFlags read FCRLFlags write FCRLFlags default rfNone; property KeyUsage: Integer read FKeyUsage write FKeyUsage default 0; property EnhancedKeyUsage: TStrings read FEnhancedKeyUsage write SetEnhancedKeyUsage; property OnCertificateVerified: TclCertificateVerifiedEvent read FOnCertificateVerified write FOnCertificateVerified; end; function GetStoreLocationInt(AStoreLocation: TclCertificateStoreLocation): Integer; function GetCertificateImportFlagsInt(AFlags: TclCertificateImportFlags): Integer; implementation uses clCryptEncoder, clEncoder, clTranslator{$IFDEF LOGGER}, clLogger{$ENDIF}; function GetStoreLocationInt(AStoreLocation: TclCertificateStoreLocation): Integer; const location: array[TclCertificateStoreLocation] of DWORD = ($00010000, $00020000); begin Result := location[AStoreLocation]; end; function GetCertificateImportFlagsInt(AFlags: TclCertificateImportFlags): Integer; begin Result := 0; if (ifMakeExportable in AFlags) then begin Result := Result or $00000001; end; if (ifStrongProtection in AFlags) then begin Result := Result or $00000002; end; if (ifMachineKeyset in AFlags) then begin Result := Result or $00000020; end; if (ifUserKeyset in AFlags) then begin Result := Result or $00001000; end; end; { TclCertificateStore } procedure TclCertificateStore.Close; begin FList.Clear(); if (FStoreHandle <> nil) then begin CertCloseStore(FStoreHandle, 0); FStoreHandle := nil; end; end; constructor TclCertificateStore.Create(AOwner: TComponent); begin inherited Create(AOwner); FList := TclCertificateList.Create(True); FEnhancedKeyUsage := TStringList.Create(); FKeyUsage := 0; FStoreHandle := nil; FStoreName := 'MY'; FStoreLocation := slCurrentUser; FCSP := DefaultProvider; FProviderType := DefaultProviderType; FKeyLength := 1024; FKeyName := ''; FKeyType := ktKeyExchange; FValidFrom := Date(); FValidTo := Date() + 365; FCRLFlags := rfNone; end; procedure TclCertificateStore.CreateCSR(const ASubject, ARequestFile: string); var stream: TStream; begin stream := TFileStream.Create(ARequestFile, fmCreate); try CreateCSR(ASubject, stream, True); finally stream.Free(); end; end; procedure TclCertificateStore.CreateContext(var context: HCRYPTPROV; var key: HCRYPTKEY); begin if (KeyName = '') then begin KeyName := IntToStr(Integer(GetTickCount())); if not CryptAcquireContext(@context, PclChar(GetTclString(KeyName)), GetCSP(), ProviderType, CRYPT_NEWKEYSET) then begin RaiseCryptError('CryptAcquireContext'); end; key := GenerateKey(context, GetKeyTypeInt()); end else begin if not CryptAcquireContext(@context, PclChar(GetTclString(KeyName)), GetCSP(), ProviderType, 0) then begin RaiseCryptError('CryptAcquireContext'); end; key := nil; if not CryptGetUserKey(context, GetKeyTypeInt(), @key) then begin key := nil; end; end; end; procedure TclCertificateStore.CreateCSR(const ASubject: string; ARequest: TStream; ABase64Encode: Boolean); var context: HCRYPTPROV; key: HCRYPTKEY; subj, keyInfo: TclCryptData; reqInfo: CERT_REQUEST_INFO; sigAlg: CRYPT_ALGORITHM_IDENTIFIER; encodedRequest: TclCryptData; extensions: TclCertificateExtensions; Attrib: CRYPT_ATTRIBUTE; AttrBlob: CRYPT_ATTR_BLOB; Exts: CERT_EXTENSIONS; begin ZeroMemory(@Exts, Sizeof(Exts)); ZeroMemory(@Attrib, Sizeof(Attrib)); ZeroMemory(@AttrBlob, Sizeof(AttrBlob)); context := nil; key := nil; try CreateContext(context, key); subj := nil; keyInfo := nil; encodedRequest := nil; extensions := nil; try subj := GenerateSubject(ASubject); ZeroMemory(@reqInfo, sizeof(reqInfo)); reqInfo.dwVersion := Integer(cvVersion3); reqInfo.Subject.cbData := subj.DataSize; reqInfo.Subject.pbData := subj.Data; keyInfo := GetPublicKeyInfo(context, GetKeyTypeInt()); reqInfo.SubjectPublicKeyInfo := PCERT_PUBLIC_KEY_INFO(keyInfo.Data)^; ZeroMemory(@sigAlg, sizeof(sigAlg)); sigAlg.pszObjId := szOID_RSA_SHA1RSA; sigAlg.Parameters.cbData := 0; extensions := GetExtensions(); if (extensions <> nil) then begin Attrib.pszObjId := szOID_CERT_EXTENSIONS; Attrib.cValue := 1; Attrib.rgValue := @AttrBlob; reqInfo.cAttribute := 1; reqInfo.rgAttribute := @Attrib; Exts.rgExtension := extensions.Extension; Exts.cExtension := extensions.Count; if not CryptEncodeObject(DefaultEncoding, szOID_CERT_EXTENSIONS, @Exts, nil, @AttrBlob.cbData) then begin RaiseCryptError('CryptEncodeObject'); end; GetMem(AttrBlob.pbData, AttrBlob.cbData); ZeroMemory(AttrBlob.pbData, AttrBlob.cbData); if not CryptEncodeObject(DefaultEncoding, szOID_CERT_EXTENSIONS, @Exts, AttrBlob.pbData, @AttrBlob.cbData) then begin RaiseCryptError('CryptEncodeObject'); end; end; encodedRequest := SignAndEncodeRequest(context, GetKeyTypeInt(), @reqInfo, @sigAlg); SaveCSR(encodedRequest.ToBytes(), ARequest, ABase64Encode); finally encodedRequest.Free(); if (AttrBlob.pbData <> nil) then begin FreeMem(AttrBlob.pbData); end; extensions.Free(); keyInfo.Free(); subj.Free(); end; finally if (key <> nil) then begin CryptDestroyKey(key); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; procedure TclCertificateStore.CreateKey(const AName: string); var context: HCRYPTPROV; key: HCRYPTKEY; begin context := nil; key := nil; try if (not CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, 0)) and (not CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, CRYPT_NEWKEYSET)) then begin RaiseCryptError('CryptAcquireContext'); end; if CryptGetUserKey(context, GetKeyTypeInt(), @key) then begin RaiseCryptError(KeyExistsError, KeyExistsErrorCode); end; key := GenerateKey(context, GetKeyTypeInt()); finally if (key <> nil) then begin CryptDestroyKey(key); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; procedure TclCertificateStore.SetCSP(const Value: string); begin if (FCSP <> Value) then begin FCSP := Value; FreeMem(FCSPPtr); FCSPPtr := nil; end; end; procedure TclCertificateStore.SetEnhancedKeyUsage(const Value: TStrings); begin FEnhancedKeyUsage.Assign(Value); end; function TclCertificateStore.GetExtensions: TclCertificateExtensions; begin Result := nil; if (KeyUsage > 0) then begin if (Result = nil) then begin Result := TclCertificateExtensions.Create(); end; Result.Add(TclKeyUsageExtension.Create(KeyUsage)); end; if (EnhancedKeyUsage.Count > 0) then begin if (Result = nil) then begin Result := TclCertificateExtensions.Create(); end; Result.Add(TclEnhancedKeyUsageExtension.Create(EnhancedKeyUsage)); end; end; function TclCertificateStore.CreateSelfSigned(const ASubject: string; ASerialNumber: Integer): TclCertificate; var context: HCRYPTPROV; key: HCRYPTKEY; subj, serialData, keyInfo, encodedCert: TclCryptData; certInfo: CERT_INFO; subjBlob: CRYPT_DATA_BLOB; extensions: TclCertificateExtensions; begin context := nil; key := nil; subj := nil; serialData := nil; keyInfo := nil; encodedCert := nil; extensions := nil; try CreateContext(context, key); subj := GenerateSubject(ASubject); ZeroMemory(@certInfo, sizeof(certInfo)); ASerialNumber := GetSerialNumber(ASerialNumber); serialData := TclCryptData.Create(SizeOf(ASerialNumber)); CopyMemory(serialData.Data, @ASerialNumber, serialData.DataSize); certInfo.SerialNumber.pbData := serialData.Data; certInfo.SerialNumber.cbData := serialData.DataSize; subjBlob.cbData := subj.DataSize; subjBlob.pbData := subj.Data; FillCertInfo(@certInfo, @subjBlob, @subjBlob); keyInfo := GetPublicKeyInfo(context, GetKeyTypeInt()); certInfo.SubjectPublicKeyInfo := PCERT_PUBLIC_KEY_INFO(keyInfo.Data)^; extensions := GetExtensions(); if (extensions <> nil) then begin certInfo.rgExtension := extensions.Extension; certInfo.cExtension := extensions.Count; end; encodedCert := SignAndEncodeCert(context, GetKeyTypeInt(), @certInfo); Result := TclCertificate.Create(encodedCert.Data, encodedCert.DataSize); try Result.SetPrivateKey(KeyName, CSP, ProviderType, GetKeyTypeInt()); except Result.Free(); raise; end; finally encodedCert.Free(); extensions.Free(); keyInfo.Free(); serialData.Free(); subj.Free(); if (key <> nil) then begin CryptDestroyKey(key); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; function TclCertificateStore.CreateSigned(AIssuer: TclCertificate; const ASubject: string; ASerialNumber: Integer): TclCertificate; var subj: TclCryptData; subjBlob: CRYPT_DATA_BLOB; extensions: TclCertificateExtensions; begin subj := nil; extensions := nil; try subj := GenerateSubject(ASubject); extensions := GetExtensions(); subjBlob.cbData := subj.DataSize; subjBlob.pbData := subj.Data; if (extensions <> nil) then begin Result := InternalCreateSigned(AIssuer, @subjBlob, ASerialNumber, extensions.Extension, extensions.Count); end else begin Result := InternalCreateSigned(AIssuer, @subjBlob, ASerialNumber, nil, 0); end; finally extensions.Free(); subj.Free(); end; end; procedure TclCertificateStore.DeleteKey(const AName: string); var context: HCRYPTPROV; begin context := nil; try if not CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, CRYPT_DELETEKEYSET) then begin RaiseCryptError('CryptAcquireContext'); end; finally if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; destructor TclCertificateStore.Destroy; begin SetCSP(''); Close(); FEnhancedKeyUsage.Free(); FList.Free(); inherited Destroy(); end; procedure TclCertificateStore.DoCertificateVerified(ACertificate: TclCertificate; ATrustStatus, ATrustInfo: Integer); begin if Assigned(OnCertificateVerified) then begin OnCertificateVerified(Self, ACertificate, ATrustStatus, ATrustInfo); end; end; procedure TclCertificateStore.Open(const AStoreName: string); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Open(' + AStoreName + ')');{$ENDIF} Close(); FStoreName := AStoreName; FStoreLocation := slCurrentUser; FStoreHandle := CertOpenSystemStore(nil, PclChar(GetTclString(StoreName))); if (FStoreHandle <> nil) then begin InternalLoad(FStoreHandle, False); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Open'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Open', E); raise; end; end;{$ENDIF} end; procedure TclCertificateStore.Open(const AStoreName: string; AStoreLocation: TclCertificateStoreLocation); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Open(' + AStoreName + ', ' + IntToStr(Integer(AStoreLocation)) + ')');{$ENDIF} Close(); FStoreName := AStoreName; FStoreLocation := AStoreLocation; FStoreHandle := CertOpenStore(CERT_STORE_PROV_SYSTEM, DefaultEncoding, nil, GetStoreLocationInt(StoreLocation), PWideChar(WideString(FStoreName))); if (FStoreHandle <> nil) then begin InternalLoad(FStoreHandle, False); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Open'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Open', E); raise; end; end;{$ENDIF} end; procedure TclCertificateStore.Open(AStoreHandle: HCERTSTORE); begin Close(); FStoreName := ''; FStoreLocation := slCurrentUser; FStoreHandle := AStoreHandle; if (FStoreHandle <> nil) then begin InternalLoad(FStoreHandle, False); end; end; function TclCertificateStore.CertificateByEmail(const AEmail: string): TclCertificate; begin Result := FindByEmail(AEmail); if (Result = nil) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; function TclCertificateStore.CertificateByIssuedTo(const AIssuedTo: string): TclCertificate; begin Result := FindByIssuedTo(AIssuedTo); if (Result = nil) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; function TclCertificateStore.CertificateBySerialNo(const ASerialNumber, AIssuer: string): TclCertificate; begin Result := FindBySerialNo(ASerialNumber, AIssuer); if (Result = nil) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; function TclCertificateStore.CertificateBySKI(const ASubjectKeyIdentifier: string): TclCertificate; begin Result := FindBySKI(ASubjectKeyIdentifier); if (Result = nil) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; function TclCertificateStore.CertificateByThumbprint(const AThumbprint: string): TclCertificate; begin Result := FindByThumbprint(AThumbprint); if (Result = nil) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; procedure TclCertificateStore.ImportFromCER(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try ImportFromCER(stream); finally stream.Free(); end; end; procedure TclCertificateStore.ImportFromCER(AStream: TStream); var buf: TclByteArray; len: Integer; begin len := AStream.Size - AStream.Position; SetLength(buf, len); if (len > 0) then begin AStream.Read(buf[0], len); end; InternalImportCER(TclCryptEncoder.DecodeBytes(buf)); end; procedure TclCertificateStore.ImportFromMessage(AStream: TStream); var data: TclCryptData; begin data := TclCryptData.Create(); try data.FromStream(AStream); ImportFromMessage(data); finally data.Free(); end; end; procedure TclCertificateStore.ImportFromMessage(const AData: TclCryptData); var hStore: HCERTSTORE; begin hStore := CryptGetMessageCertificates(DefaultEncoding, nil, 0, AData.Data, AData.DataSize); if (hStore = nil) then begin RaiseCryptError('CryptGetMessageCertificates'); end; try InternalLoad(hStore, True); finally CertCloseStore(hStore, 0); end; end; procedure TclCertificateStore.ImportFromMessage(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try ImportFromMessage(stream); finally stream.Free(); end; end; procedure TclCertificateStore.ImportFromPFX(AStream: TStream; const APassword: string; AFlags: TclCertificateImportFlags); var PFX: CRYPT_DATA_BLOB; data: TclCryptData; psw: PWideChar; hStore: HCERTSTORE; begin data := TclCryptData.Create(); try data.FromStream(AStream); PFX.cbData := data.DataSize; PFX.pbData := data.Data; psw := PWideChar(WideString(APassword)); hStore := PFXImportCertStore(@PFX, psw, GetCertificateImportFlagsInt(AFlags)); if (hStore = nil) and (APassword = '') then begin hStore := PFXImportCertStore(@PFX, nil, GetCertificateImportFlagsInt(AFlags)); end; if (hStore = nil) then begin RaiseCryptError('PFXImportCertStore'); end; try InternalLoad(hStore, True); finally CertCloseStore(hStore, 0); end; finally data.Free(); end; end; procedure TclCertificateStore.ImportFromPFX(const AFileName, APassword: string; AFlags: TclCertificateImportFlags); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try ImportFromPFX(stream, APassword, AFlags); finally stream.Free(); end; end; procedure TclCertificateStore.ImportKey(const AName, AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try ImportKey(AName, stream); finally stream.Free(); end; end; procedure TclCertificateStore.ImportKey(const AName: string; AStream: TStream); var buf: TclByteArray; len: Integer; begin len := AStream.Size - AStream.Position; SetLength(buf, len); if (len > 0) then begin AStream.Read(buf[0], len); end; InternalImportKey(AName, TclCryptEncoder.DecodeBytes(buf)); end; procedure TclCertificateStore.ImportSignedCSR(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try ImportSignedCSR(stream); finally stream.Free(); end; end; procedure TclCertificateStore.ImportSignedCSR(AStream: TStream); var cert: TclCertificate; buf: TclByteArray; len: Integer; begin len := AStream.Size - AStream.Position; SetLength(buf, len); if (len > 0) then begin AStream.Read(buf[0], len); end; cert := InternalImportCER(TclCryptEncoder.DecodeBytes(buf)); cert.SetPrivateKey(KeyName, CSP, ProviderType, GetKeyTypeInt()); end; procedure TclCertificateStore.ImportFromPFX(const AFileName, APassword: string); begin ImportFromPFX(AFileName, APassword, [ifMakeExportable]); end; function TclCertificateStore.InternalCreateSigned(AIssuer: TclCertificate; ASubject: PCRYPT_DATA_BLOB; ASerialNumber: Integer; AExtensions: PCERT_EXTENSION; AExtensionCount: Integer): TclCertificate; var context, issuerCtx: HCRYPTPROV; key: HCRYPTKEY; serialData, keyInfo, encodedCert: TclCryptData; certInfo: CERT_INFO; issuerKeySpec: Integer; begin context := nil; key := nil; serialData := nil; keyInfo := nil; encodedCert := nil; try CreateContext(context, key); ZeroMemory(@certInfo, sizeof(certInfo)); ASerialNumber := GetSerialNumber(ASerialNumber); serialData := TclCryptData.Create(SizeOf(ASerialNumber)); CopyMemory(serialData.Data, @ASerialNumber, serialData.DataSize); certInfo.SerialNumber.pbData := serialData.Data; certInfo.SerialNumber.cbData := serialData.DataSize; FillCertInfo(@certInfo, ASubject, @AIssuer.Context.pCertInfo.Subject); keyInfo := GetPublicKeyInfo(context, GetKeyTypeInt()); certInfo.SubjectPublicKeyInfo := PCERT_PUBLIC_KEY_INFO(keyInfo.Data)^; issuerCtx := nil; issuerKeySpec := 0; GetCertificatePrivateKey(AIssuer.Context, issuerCtx, issuerKeySpec); certInfo.rgExtension := AExtensions; certInfo.cExtension := AExtensionCount; encodedCert := SignAndEncodeCert(issuerCtx, issuerKeySpec, @certInfo); Result := TclCertificate.Create(encodedCert.Data, encodedCert.DataSize); try Result.SetPrivateKey(KeyName, CSP, ProviderType, GetKeyTypeInt()); except Result.Free(); raise; end; finally encodedCert.Free(); keyInfo.Free(); serialData.Free(); if (key <> nil) then begin CryptDestroyKey(key); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; function TclCertificateStore.InternalExportCER(ACertificate: TclCertificate): TclByteArray; begin SetLength(Result, ACertificate.Context.cbCertEncoded); System.Move(ACertificate.Context.pbCertEncoded^, Result[0], Length(Result)); end; function TclCertificateStore.InternalExportKey(const AName: string): TclByteArray; var context: HCRYPTPROV; hKey: HCRYPTKEY; data: TclCryptData; len: Integer; begin {$IFNDEF DELPHI2005}Result := nil;{$ENDIF} context := nil; try if not CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, 0) then begin RaiseCryptError('CryptAcquireContext'); end; hKey := nil; try if not CryptGetUserKey(context, GetKeyTypeInt(), @hKey) then begin RaiseCryptError('CryptGetUserKey'); end; if not CryptExportKey(hKey, nil, PRIVATEKEYBLOB, 0, nil, @len) then begin RaiseCryptError('CryptExportKey'); end; data := TclCryptData.Create(len); try if not CryptExportKey(hKey, nil, PRIVATEKEYBLOB, 0, data.Data, @len) then begin RaiseCryptError('CryptExportKey'); end; data.Reduce(len); Result := data.ToBytes(); finally data.Free(); end; finally if (hKey <> nil) then begin CryptDestroyKey(hKey); end; end; finally if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; function TclCertificateStore.InternalImportCER(const ABytes: TclByteArray): TclCertificate; var data: TclCryptData; begin data := TclCryptData.Create(); try data.FromBytes(ABytes); Result := TclCertificate.Create(data.Data, data.DataSize); Items.Add(Result); finally data.Free(); end; end; procedure TclCertificateStore.InternalImportKey(const AName: string; const ABytes: TclByteArray); var context: HCRYPTPROV; hKey, hNewKey: HCRYPTKEY; data: TclCryptData; begin context := nil; hKey := nil; hNewKey := nil; try if (not CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, 0)) and (not CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, CRYPT_NEWKEYSET)) then begin RaiseCryptError('CryptAcquireContext'); end; if CryptGetUserKey(context, GetKeyTypeInt(), @hKey) then begin RaiseCryptError(KeyExistsError, KeyExistsErrorCode); end; data := TclCryptData.Create(); try data.FromBytes(ABytes); if not CryptImportKey(context, data.Data, data.DataSize, hKey, CRYPT_EXPORTABLE, @hNewKey) then begin RaiseCryptError('CryptImportKey'); end; finally data.Free(); end; finally if (hNewKey <> nil) then begin CryptDestroyKey(hNewKey); end; if (hKey <> nil) then begin CryptDestroyKey(hKey); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; procedure TclCertificateStore.InternalLoad(hStore: HCERTSTORE; ARemoveDuplicates: Boolean); var hCertContext: PCCERT_CONTEXT; cert: TclCertificate; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalLoad');{$ENDIF} hCertContext := nil; repeat hCertContext := CertEnumCertificatesInStore(hStore, hCertContext); if (hCertContext <> nil) then begin cert := TclCertificate.Create(hCertContext); try if (ARemoveDuplicates and (FindBySerialNo(cert.SerialNumber, cert.IssuedBy) <> nil)) then begin FreeAndNil(cert); end; if (cert <> nil) then begin Items.Add(cert); end; except cert.Free(); raise; end; end; until (hCertContext = nil); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalLoad'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalLoad', E); raise; end; end;{$ENDIF} end; function TclCertificateStore.GetExtensionAttribute(AReqInfo: PCERT_REQUEST_INFO): TclCryptData; var i, j: Integer; pAttr: PCRYPT_ATTRIBUTE; pEncodedExt: PCRYPT_ATTR_BLOB; cbStruct: DWORD; begin Result := nil; for i := 0 to Integer(AReqInfo.cAttribute) - 1 do begin pAttr := PCRYPT_ATTRIBUTE(TclIntPtr(AReqInfo.rgAttribute) + i * SizeOf(CRYPT_ATTRIBUTE)); if (string(pAttr.pszObjId) = szOID_CERT_EXTENSIONS) then begin for j := 0 to pAttr.cValue - 1 do begin pEncodedExt := PCRYPT_ATTR_BLOB(TclIntPtr(pAttr.rgValue) + j * SizeOf(CRYPT_ATTR_BLOB)); Result := TclCryptData.Create(); try if not (CryptDecodeObject(DefaultEncoding, szOID_CERT_EXTENSIONS, pEncodedExt.pbData, pEncodedExt.cbData, 0, nil, @cbStruct)) then begin RaiseCryptError('CryptDecodeObject'); end; Result.Allocate(cbStruct); if not (CryptDecodeObject(DefaultEncoding, szOID_CERT_EXTENSIONS, pEncodedExt.pbData, pEncodedExt.cbData, 0, Result.Data, @cbStruct)) then begin RaiseCryptError('CryptDecodeObject'); end; Result.Reduce(cbStruct); except Result.Free(); raise; end; Break; end; Break; end; end; end; function TclCertificateStore.InternalSignCSR(AIssuer: TclCertificate; ARequest: TclByteArray; ASerialNumber: Integer): TclCertificate; var pRequest: TclCryptData; cbStructInfo: DWORD; pReqInfo: PCERT_REQUEST_INFO; context: HCRYPTPROV; key: HCRYPTKEY; extensions: TclCertificateExtensions; reqExtensions: TclCryptData; pReqExts: PCERT_EXTENSIONS; begin pRequest := nil; extensions := nil; reqExtensions := nil; try pRequest := TclCryptData.Create(); pRequest.FromBytes(ARequest); cbStructInfo := 0; if not CryptDecodeObject(DefaultEncoding, X509_CERT_REQUEST_TO_BE_SIGNED, pRequest.Data, pRequest.DataSize, 0, nil, @cbStructInfo) then begin RaiseCryptError('CryptDecodeObject'); end; GetMem(pReqInfo, cbStructInfo); try CryptDecodeObject(DefaultEncoding, X509_CERT_REQUEST_TO_BE_SIGNED, pRequest.Data, pRequest.DataSize, 0, pReqInfo, @cbStructInfo); context := nil; key := nil; try CreateContext(context, key); if not CryptVerifyCertificateSignature(context, DefaultEncoding, pRequest.Data, pRequest.DataSize, @pReqInfo.SubjectPublicKeyInfo) then begin RaiseCryptError('CryptVerifyCertificateSignature'); end; extensions := GetExtensions(); if (extensions <> nil) then begin Result := InternalCreateSigned(AIssuer, @pReqInfo.Subject, ASerialNumber, extensions.Extension, extensions.Count); end else begin reqExtensions := GetExtensionAttribute(pReqInfo); if (reqExtensions <> nil) then begin pReqExts := PCERT_EXTENSIONS(reqExtensions.Data); Result := InternalCreateSigned(AIssuer, @pReqInfo.Subject, ASerialNumber, pReqExts.rgExtension, pReqExts.cExtension); end else begin Result := InternalCreateSigned(AIssuer, @pReqInfo.Subject, ASerialNumber, nil, 0); end; end; finally if (key <> nil) then begin CryptDestroyKey(key); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; finally FreeMem(pReqInfo); end; finally reqExtensions.Free(); extensions.Free(); pRequest.Free(); end; end; procedure TclCertificateStore.Install(ACertificate: TclCertificate); var hStore, hPersistStore: HCERTSTORE; begin hPersistStore := nil; hStore := FStoreHandle; try if (hStore = nil) then begin hPersistStore := CertOpenStore(CERT_STORE_PROV_SYSTEM, DefaultEncoding, nil, GetStoreLocationInt(StoreLocation), PWideChar(WideString(FStoreName))); hStore := hPersistStore; end; if (hStore = nil) or (not CertAddCertificateContextToStore(hStore, ACertificate.Context, CERT_STORE_ADD_NEW, nil)) then begin RaiseCryptError('CertAddCertificateContextToStore'); end; finally if (hPersistStore <> nil) then begin CertCloseStore(hPersistStore, CERT_CLOSE_STORE_FORCE_FLAG); end; end; end; procedure TclCertificateStore.Uninstall(ACertificate: TclCertificate); begin if not CertDeleteCertificateFromStore(CertDuplicateCertificateContext(ACertificate.Context)) then begin RaiseCryptError('CertDeleteCertificateFromStore'); end; end; function TclCertificateStore.Verify(ACertificate: TclCertificate; var ATrustStatus, ATrustInfo: Integer): Boolean; var hStore: HCERTSTORE; begin hStore := CertOpenStore(CERT_STORE_PROV_MEMORY, 0, nil, 0, nil); if (hStore = nil) then begin RaiseCryptError('CertOpenStore'); end; try GetCertificateChain(hStore, ACertificate, ATrustStatus, ATrustInfo); Result := (ATrustStatus = 0); finally CertCloseStore(hStore, 0); end; end; function TclCertificateStore.Verify(ACertificate: TclCertificate): Boolean; var trustStatus, trustInfo: Integer; begin trustStatus := 0; trustInfo := 0; Result := Verify(ACertificate, trustStatus, trustInfo); end; function TclCertificateStore.IsInstalled(ACertificate: TclCertificate): Boolean; var cont: PCCERT_CONTEXT; hStore, hPersistStore: HCERTSTORE; begin hPersistStore := nil; hStore := FStoreHandle; try if (hStore = nil) then begin hPersistStore := CertOpenStore(CERT_STORE_PROV_SYSTEM, DefaultEncoding, nil, GetStoreLocationInt(StoreLocation), PWideChar(WideString(FStoreName))); hStore := hPersistStore; end; if (hStore = nil) then begin RaiseCryptError('CertOpenStore'); end; cont := CertGetSubjectCertificateFromStore(hStore, DefaultEncoding, ACertificate.Context.pCertInfo); Result := (cont <> nil); if Result then begin CertFreeCertificateContext(cont); end; finally if (hPersistStore <> nil) then begin CertCloseStore(hPersistStore, 0); end; end; end; function TclCertificateStore.KeyExists(const AName: string): Boolean; var context: HCRYPTPROV; key: HCRYPTKEY; begin context := nil; key := nil; try Result := CryptAcquireContext(@context, PclChar(GetTclString(AName)), GetCSP(), ProviderType, 0); if Result then begin Result := CryptGetUserKey(context, GetKeyTypeInt(), @key) end; finally if (key <> nil) then begin CryptDestroyKey(key); end; if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; function TclCertificateStore.GenerateKey(AContext: HCRYPTPROV; AKeySpec: DWORD): HCRYPTKEY; var flags: DWORD; begin flags := (KeyLength shl $10) or 1; Result := nil; if not CryptGenKey(AContext, AKeySpec, flags, @Result) then begin RaiseCryptError('CryptGenKey'); end; end; function TclCertificateStore.GenerateSubject(const ASubject: string): TclCryptData; var subjSize: DWORD; p: PWideChar; begin Result := TclCryptData.Create(); try p := PWideChar(WideString(ASubject)); if not CertStrToName(DefaultEncoding, p, CERT_X500_NAME_STR, nil, nil, @subjSize, nil) then begin RaiseCryptError('CertStrToName'); end; Result.Allocate(subjSize); if not CertStrToName(DefaultEncoding, p, CERT_X500_NAME_STR, nil, Result.Data, @subjSize, nil) then begin RaiseCryptError('CertStrToName'); end; Result.Reduce(subjSize); except Result.Free(); raise; end; end; function TclCertificateStore.GetItems: TclCertificateList; begin Result := FList; end; function TclCertificateStore.GetKey(const AName: string): TclCertificateKey; begin Result := TclCertificateKey.Create(AName, CSP, ProviderType); end; procedure TclCertificateStore.GetKeyList(AList: TStrings); var context: HCRYPTPROV; len, isFirst: DWORD; data: TclCryptData; s: TclString; keyName: string; begin context := nil; try if not CryptAcquireContext(@context, nil, GetCSP(), ProviderType, CRYPT_VERIFYCONTEXT) then begin RaiseCryptError('CryptAcquireContext'); end; AList.Clear(); isFirst := CRYPT_FIRST; len := 0; if CryptGetProvParam(context, PP_ENUMCONTAINERS, nil, @len, isFirst) then begin data := TclCryptData.Create(len); try len := data.DataSize; while CryptGetProvParam(context, PP_ENUMCONTAINERS, data.Data, @len, isFirst) do begin isFirst := CRYPT_NEXT; s := GetTclString(PclChar(data.Data)); keyName := string(s); AList.Add(keyName); end; finally data.Free(); end; end; finally if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; function TclCertificateStore.GetKeyTypeInt: Integer; begin Result := clCertificateKey.GetKeyTypeInt(KeyType); end; function TclCertificateStore.GetSerialNumber(ASerialNumber: Integer): Integer; begin Result := ASerialNumber; if (Result <= 0) then begin Result := Integer(GetTickCount()); end; end; function TclCertificateStore.GetPublicKeyInfo(AContext: HCRYPTPROV; Alg: DWORD): TclCryptData; var keyInfoSize: DWORD; begin Result := TclCryptData.Create(); try if not CryptExportPublicKeyInfo(AContext, Alg, DefaultEncoding, nil, @keyInfoSize) then begin RaiseCryptError('CryptExportPublicKeyInfo'); end; Result.Allocate(keyInfoSize); if not CryptExportPublicKeyInfo(AContext, Alg, DefaultEncoding, PCERT_PUBLIC_KEY_INFO(Result.Data), @keyInfoSize) then begin RaiseCryptError('CryptExportPublicKeyInfo'); end; Result.Reduce(keyInfoSize); except Result.Free(); raise; end; end; procedure TclCertificateStore.SaveCSR(AEncodedRequest: TclByteArray; AStream: TStream; ABase64Encode: Boolean); var buf: TclByteArray; begin buf := AEncodedRequest; if ABase64Encode then begin buf := TclCryptEncoder.EncodeToBytes(buf, dtCertificateRequest); end; if (Length(buf) > 0) then begin AStream.Write(buf[0], Length(buf)); end; end; function TclCertificateStore.SignAndEncodeCert(AContext: HCRYPTPROV; Alg: DWORD; ACertInfo: PCERT_INFO): TclCryptData; var encodedSize: DWORD; begin Result := TclCryptData.Create(); try if not CryptSignAndEncodeCertificate(AContext, Alg, X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED, ACertInfo, @ACertInfo.SignatureAlgorithm, nil, nil, @encodedSize) then begin RaiseCryptError('CryptSignAndEncodeCertificate'); end; Result.Allocate(encodedSize); if not CryptSignAndEncodeCertificate(AContext, Alg, X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED, ACertInfo, @ACertInfo.SignatureAlgorithm, nil, Result.Data, @encodedSize) then begin RaiseCryptError('CryptSignAndEncodeCertificate'); end; Result.Reduce(encodedSize); except Result.Free(); raise; end; end; function TclCertificateStore.SignAndEncodeRequest(AContext: HCRYPTPROV; Alg: DWORD; AReqInfo: PCERT_REQUEST_INFO; ASigAlg: PCRYPT_ALGORITHM_IDENTIFIER): TclCryptData; var encodedSize: DWORD; begin Result := TclCryptData.Create(); try if not CryptSignAndEncodeCertificate(AContext, Alg, X509_ASN_ENCODING, X509_CERT_REQUEST_TO_BE_SIGNED, AReqInfo, ASigAlg, nil, nil, @encodedSize) then begin RaiseCryptError('CryptSignAndEncodeCertificate'); end; Result.Allocate(encodedSize); if not CryptSignAndEncodeCertificate(AContext, Alg, X509_ASN_ENCODING, X509_CERT_REQUEST_TO_BE_SIGNED, AReqInfo, ASigAlg, nil, Result.Data, @encodedSize) then begin RaiseCryptError('CryptSignAndEncodeCertificate'); end; Result.Reduce(encodedSize); except Result.Free(); raise; end; end; function TclCertificateStore.SignCSR(AIssuer: TclCertificate; const ARequestFile: string; ASerialNumber: Integer): TclCertificate; var stream: TStream; begin stream := TFileStream.Create(ARequestFile, fmOpenRead or fmShareDenyWrite); try Result := SignCSR(AIssuer, stream, ASerialNumber); finally stream.Free(); end; end; function TclCertificateStore.SignCSR(AIssuer: TclCertificate; ARequest: TStream; ASerialNumber: Integer): TclCertificate; var buf: TclByteArray; len: Integer; begin len := ARequest.Size - ARequest.Position; SetLength(buf, len); if (len > 0) then begin ARequest.Read(buf[0], len); end; Result := InternalSignCSR(AIssuer, TclCryptEncoder.DecodeBytes(buf), ASerialNumber); end; procedure TclCertificateStore.ExportToCER(ACertificate: TclCertificate; const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try ExportToCER(ACertificate, stream, True); finally stream.Free(); end; end; procedure TclCertificateStore.ExportKey(const AName: string; AStream: TStream; ABase64Encode: Boolean); var buf: TclByteArray; begin buf := InternalExportKey(AName); if ABase64Encode then begin buf := TclCryptEncoder.EncodeToBytes(buf, dtRsaPrivateKey); end; if (Length(buf) > 0) then begin AStream.Write(buf[0], Length(buf)); end; end; procedure TclCertificateStore.ExportKey(const AName, AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try ExportKey(AName, stream, True); finally stream.Free(); end; end; procedure TclCertificateStore.ExportToCER(ACertificate: TclCertificate; AStream: TStream; ABase64Encode: Boolean); var buf: TclByteArray; begin buf := InternalExportCER(ACertificate); if ABase64Encode then begin buf := TclCryptEncoder.EncodeToBytes(buf, dtCertificate); end; if (Length(buf) > 0) then begin AStream.Write(buf[0], Length(buf)); end; end; procedure TclCertificateStore.ExportToPFX(ACertificate: TclCertificate; AStream: TStream; const APassword: string; AIncludeAll: Boolean); var i, trustStatus, trustInfo: Integer; hStore: HCERTSTORE; pfxBlob: CRYPT_DATA_BLOB; pfx: TclCryptData; psw: PWideChar; begin hStore := nil; pfx := nil; try hStore := CertOpenStore(CERT_STORE_PROV_MEMORY, 0, nil, 0, nil); if (hStore = nil) then begin RaiseCryptError('CertOpenStore'); end; if (ACertificate <> nil) then begin if AIncludeAll then begin trustStatus := 0; trustInfo := 0; GetCertificateChain(hStore, ACertificate, trustStatus, trustInfo); end else begin if not CertAddCertificateContextToStore(hStore, ACertificate.Context, CERT_STORE_ADD_NEW, nil) then begin RaiseCryptError('CertAddCertificateContextToStore'); end; end; end else begin for i := 0 to Items.Count - 1 do begin if not CertAddCertificateContextToStore(hStore, Items[i].Context, CERT_STORE_ADD_NEW, nil) then begin RaiseCryptError('CertAddCertificateContextToStore'); end; end; end; pfx := TclCryptData.Create(); pfxBlob.cbData := 0; pfxBlob.pbData := nil; psw := PWideChar(WideString(APassword)); if not PFXExportCertStoreEx(hStore, @pfxBlob, psw, nil, EXPORT_PRIVATE_KEYS) then begin RaiseCryptError('PFXExportCertStoreEx'); end; pfx.Allocate(pfxBlob.cbData); pfxBlob.pbData := pfx.Data; if not PFXExportCertStoreEx(hStore, @pfxBlob, psw, nil, EXPORT_PRIVATE_KEYS) then begin RaiseCryptError('PFXExportCertStoreEx'); end; pfx.Reduce(pfxBlob.cbData); pfx.ToStream(AStream); finally pfx.Free(); if (hStore <> nil) then begin CertCloseStore(hStore, 0); end; end; end; procedure TclCertificateStore.ExportToPFX(ACertificate: TclCertificate; const AFileName, APassword: string; AIncludeAll: Boolean); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try ExportToPFX(ACertificate, stream, APassword, AIncludeAll); finally stream.Free(); end; end; procedure TclCertificateStore.FillCertInfo(ACertInfo: PCERT_INFO; ASubject, AIssuer: PCRYPT_DATA_BLOB); function GetCertDate(ADate: TDateTime): TFileTime; var sDate: TSystemTime; begin DateTimeToSystemTime(LocalTimeToGlobalTime(ADate), sDate); SystemTimeToFileTime(sDate, Result); end; begin ACertInfo.NotBefore := GetCertDate(ValidFrom); ACertInfo.NotAfter := GetCertDate(ValidTo); ACertInfo.Subject.cbData := ASubject.cbData; ACertInfo.Subject.pbData := ASubject.pbData; ACertInfo.Issuer.cbData := AIssuer.cbData; ACertInfo.Issuer.pbData := AIssuer.pbData; ACertInfo.dwVersion := Integer(cvVersion3); ACertInfo.SignatureAlgorithm.pszObjId := szOID_RSA_SHA1RSA; end; function TclCertificateStore.FindByEmail(const AEmail: string): TclCertificate; begin Result := FindByEmail(AEmail, False); end; function TclCertificateStore.FindByEmail(const AEmail: string; ARequirePrivateKey: Boolean): TclCertificate; var i: Integer; begin for i := 0 to Items.Count -1 do begin Result := Items[i]; if ((not ARequirePrivateKey) or (Result.PrivateKey <> '')) and SameText(Result.Email, AEmail) then begin Exit; end; end; Result := nil; end; function TclCertificateStore.FindByIssuedTo(const AIssuedTo: string; ARequirePrivateKey: Boolean): TclCertificate; var i: Integer; begin for i := 0 to Items.Count -1 do begin Result := Items[i]; if ((not ARequirePrivateKey) or (Result.PrivateKey <> '')) and SameText(Result.IssuedTo, AIssuedTo) then begin Exit; end; end; Result := nil; end; function TclCertificateStore.FindBySerialNo(const ASerialNumber, AIssuer: string; ARequirePrivateKey: Boolean): TclCertificate; var i: Integer; begin for i := 0 to Items.Count -1 do begin Result := Items[i]; if ((not ARequirePrivateKey) or (Result.PrivateKey <> '')) and ((AIssuer = '') or SameText(Result.IssuedBy, AIssuer)) and SameText(Result.SerialNumber, ASerialNumber) then begin Exit; end; end; Result := nil; end; function TclCertificateStore.FindBySKI(const ASubjectKeyIdentifier: string): TclCertificate; begin Result := FindBySKI(ASubjectKeyIdentifier, False); end; function TclCertificateStore.FindBySKI(const ASubjectKeyIdentifier: string; ARequirePrivateKey: Boolean): TclCertificate; var i: Integer; begin for i := 0 to Items.Count -1 do begin Result := Items[i]; if ((not ARequirePrivateKey) or (Result.PrivateKey <> '')) and SameText(Result.SubjectKeyIdentifier, ASubjectKeyIdentifier) then begin Exit; end; end; Result := nil; end; function TclCertificateStore.FindByThumbprint(const AThumbprint: string): TclCertificate; begin Result := FindByThumbprint(AThumbprint, False); end; function TclCertificateStore.FindByThumbprint(const AThumbprint: string; ARequirePrivateKey: Boolean): TclCertificate; var i: Integer; begin for i := 0 to Items.Count -1 do begin Result := Items[i]; if ((not ARequirePrivateKey) or (Result.PrivateKey <> '')) and SameText(Result.Thumbprint, AThumbprint) then begin Exit; end; end; Result := nil; end; function TclCertificateStore.FindByIssuedTo(const AIssuedTo: string): TclCertificate; begin Result := FindByIssuedTo(AIssuedTo, False); end; function TclCertificateStore.FindBySerialNo(const ASerialNumber, AIssuer: string): TclCertificate; begin Result := FindBySerialNo(ASerialNumber, AIssuer, False); end; procedure TclCertificateStore.GetCertificateChain(hStore: HCERTSTORE; ACertificate: TclCertificate; var ATrustStatus, ATrustInfo: Integer); const revFlags: array[TclRevocationFlags] of DWORD = (0, $10000000, $20000000, $40000000); var pChainContext: PCCERT_CHAIN_CONTEXT; ChainPara: CERT_CHAIN_PARA; pChain: PCERT_SIMPLE_CHAIN; pElement: PCERT_CHAIN_ELEMENT; i, j: Integer; certInChain: TclCertificate; p: Pointer; begin pChainContext := nil; try ZeroMemory(@ChainPara, sizeof(ChainPara)); ChainPara.cbSize := sizeof(ChainPara); if not CertGetCertificateChain(0, ACertificate.Context, nil, ACertificate.Context.hCertStore, @ChainPara, revFlags[CRLFlags], nil, @pChainContext) then begin RaiseCryptError('CertGetCertificateChain'); end; for i := pChainContext.cChain - 1 downto 0 do begin p := Pointer(TclIntPtr(pChainContext.rgpChain) + i * SizeOf(PCERT_SIMPLE_CHAIN)); pChain := PCERT_SIMPLE_CHAIN(p^); for j := pChain.cElement - 1 downto 0 do begin p := Pointer(TclIntPtr(pChain.rgpElement) + j * SizeOf(PCERT_CHAIN_ELEMENT)); pElement := PCERT_CHAIN_ELEMENT(p^); if not CertAddCertificateContextToStore(hStore, pElement.pCertContext, CERT_STORE_ADD_NEW, nil) then begin RaiseCryptError('CertAddCertificateContextToStore'); end; certInChain := TclCertificate.Create(pElement.pCertContext); try DoCertificateVerified(certInChain, pElement.TrustStatus.dwErrorStatus, pElement.TrustStatus.dwInfoStatus); finally certInChain.Free(); end; end; end; ATrustStatus := pChainContext.TrustStatus.dwErrorStatus; ATrustInfo := pChainContext.TrustStatus.dwInfoStatus; finally if (pChainContext <> nil) then begin CertFreeCertificateChain(pChainContext); end; end; end; procedure TclCertificateStore.GetCertificatePrivateKey( ACertificate: PCCERT_CONTEXT; var AContext: HCRYPTPROV; var Alg: Integer); var callerFree: BOOL; begin callerFree := False; if not CryptAcquireCertificatePrivateKey(ACertificate, CRYPT_ACQUIRE_CACHE_FLAG, nil, @AContext, @Alg, @callerFree) then begin RaiseCryptError('CryptAcquireCertificatePrivateKey'); end; end; function TclCertificateStore.GetCSP: PclChar; var s: TclString; len: Integer; begin Result := FCSPPtr; if (Result <> nil) then Exit; if (Trim(CSP) <> '') then begin s := GetTclString(CSP); len := Length(s); GetMem(FCSPPtr, len + SizeOf(TclChar)); system.Move(PclChar(s)^, FCSPPtr^, len); FCSPPtr[len] := #0; end; Result := FCSPPtr; end; procedure TclCertificateStore.ExportToPFX(ACertificate: TclCertificate; const AFileName, APassword: string); begin ExportToPFX(ACertificate, AFileName, APassword, False); end; end.
unit CleanArch_EmbrConf.Adapter.Impl.ParkingLotAdapter; interface uses CleanArch_EmbrConf.Adapter.interfaces, CleanArch_EmbrConf.Core.Entity.Interfaces, CleanArch_EmbrConf.Core.Entity.Impl.ParkingLot; type TParkingLotAdapter = class(TInterfacedObject, iParkingLotAdapter) private FParkingLot : iParkingLot; FCode: String; FCapacity: Integer; FOpenHour: Integer; FCloseHour: Integer; FOccupiedSpaces: Integer; public constructor Create; destructor Destroy; override; class function New : iParkingLotAdapter; function Code(Value : String) : iParkingLotAdapter; overload; function Code : String; overload; function Capacity(Value : Integer) : iParkingLotAdapter; overload; function Capacity : Integer; overload; function OpenHour(Value : Integer) : iParkingLotAdapter; overload; function OpenHour : Integer; overload; function CloseHour(Value : Integer) : iParkingLotAdapter; overload; function CloseHour : Integer; overload; function OccupiedSpaces(Value : Integer) : iParkingLotAdapter; overload; function OccupiedSpaces : Integer; overload; function ParkingLot : iParkingLot; end; implementation function TParkingLotAdapter.Capacity(Value: Integer): iParkingLotAdapter; begin Result := self; FCapacity := Value; end; function TParkingLotAdapter.Capacity: Integer; begin Result := FCapacity; end; function TParkingLotAdapter.CloseHour: Integer; begin Result := FCloseHour; end; function TParkingLotAdapter.CloseHour(Value: Integer): iParkingLotAdapter; begin Result := Self; FCloseHour := Value; end; function TParkingLotAdapter.Code: String; begin Result := FCode; end; function TParkingLotAdapter.Code(Value: String): iParkingLotAdapter; begin Result := Self; FCode := Value; end; constructor TParkingLotAdapter.Create; begin FParkingLot := TParkingLot.New; end; destructor TParkingLotAdapter.Destroy; begin inherited; end; class function TParkingLotAdapter.New : iParkingLotAdapter; begin Result := Self.Create; end; function TParkingLotAdapter.OccupiedSpaces(Value: Integer): iParkingLotAdapter; begin Result := Self; FOccupiedSpaces := Value; end; function TParkingLotAdapter.OccupiedSpaces: Integer; begin Result := FOccupiedSpaces; end; function TParkingLotAdapter.OpenHour: Integer; begin Result := FOpenHour; end; function TParkingLotAdapter.ParkingLot: iParkingLot; begin Result := FParkingLot .Code(FCode) .Capacity(FCapacity) .OpenHour(FOpenHour) .CloseHour(FCloseHour) .OccupiedSpaces(FOccupiedSpaces); end; function TParkingLotAdapter.OpenHour(Value: Integer): iParkingLotAdapter; begin Result := Self; FOpenHour := Value; end; end.
unit ScrollRegions; interface uses Windows; function GetScrollUpdateRegion(const target : HWND; dx, dy : integer) : HRGN; implementation function GetOverlappedRegion(const which : HWND; dx, dy : integer) : HRGN; forward; function GetScrollUpdateRegion(const target : HWND; dx, dy : integer) : HRGN; var ClientRect : TRect; aux : HRGN; begin if (target <> 0) and IsWindowVisible(target) and ((dx <> 0) or (dy <> 0)) then begin GetClientRect(target, ClientRect); if dx <> 0 then if dx < 0 then aux := CreateRectRgn(ClientRect.Right + dx, 0, ClientRect.Right, ClientRect.Bottom) else aux := CreateRectRgn(ClientRect.Left, ClientRect.Top, ClientRect.Left + dx, ClientRect.Bottom) else aux := CreateRectRgn(0, 0, 0, 0); if dy <> 0 then begin if dy < 0 then Result := CreateRectRgn(0, ClientRect.Bottom + dy, ClientRect.Right, ClientRect.Bottom) else Result := CreateRectRgn(ClientRect.Left, ClientRect.Top, ClientRect.Right, ClientRect.Top + dy); CombineRgn(Result, aux, Result, RGN_OR); DeleteObject(aux); end else Result := aux; aux := GetOverlappedRegion(target, dx, dy); if aux <> 0 then begin CombineRgn(Result, Result, aux, RGN_OR); DeleteObject(aux); end; end else Result := 0; end; // utils implementations function GetOverlappedRegion(const which : HWND; dx, dy : integer) : HRGN; var BaseRect : TRect; procedure GetRegion(const current : HWND); var prev : HWND; CurRect : TRect; r1, r2 : HRGN; begin prev := current; repeat prev := GetWindow(prev, GW_HWNDPREV); if (prev <> 0) and IsWindowVisible(prev) then begin GetWindowRect(prev, CurRect); ScreenToClient(which, CurRect.TopLeft); ScreenToClient(which, CurRect.BottomRight); r1 := CreateRectRgnIndirect(CurRect); if dx < 0 then inc(CurRect.Left, dx) else inc(CurRect.Right, dx); if dy < 0 then inc(CurRect.Top, dy) else inc(CurRect.Bottom, dy); r2 := CreateRectRgnIndirect(CurRect); CombineRgn(r1, r2, r1, RGN_DIFF); DeleteObject(r2); r2 := CreateRectRgnIndirect(BaseRect); CombineRgn(r1, r2, r1, RGN_AND); DeleteObject(r2); CombineRgn(Result, Result, r1, RGN_OR); DeleteObject(r1); end; until prev = 0; prev := GetParent(current); if prev <> 0 then GetRegion(prev); end; begin GetClientRect(which, BaseRect); Result := CreateRectRgn(0, 0, 0, 0); GetRegion(which); end; end.
var i, a, b: integer; function mod(x, y: integer): integer; begin mod := x - x / y * y end; begin for i:= 100 to 999 do begin a := i / 100; b := mod(i, 10); if a = b then write(" ", i) end end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StSort.pas 4.04 *} {*********************************************************} {* SysTools: General purpose sorting class using *} {* merge sort algorithm *} {*********************************************************} {$I StDefine.inc} {Notes: The sequence to sort data is this: Sorter := TStSorter.Create(MaxHeap, RecLen); Sorter.Compare := ACompareFunction; repeat ... obtain ADataRecord from somewhere ... Sorter.Put(ADataRecord); until NoMoreData; while Sorter.Get(ADataRecord) do ... do something with ADataRecord ... Sorter.Free; While Put is called, the sorter buffers as many records as it can fit in MaxHeap. When that space is filled, it sorts the buffer and stores that buffer to a temporary merge file. When Get is called, the sorter sorts the last remaining buffer and starts either returning the records from the buffer (if all records fit into memory) or merging the files and returning the records from there. The Compare function can be used as a place to display status and to abort the sort. It is not possible to accurately predict the total number of times Compare will be called, but it is called very frequently throughout the sort. To abort a sort from the Compare function, just raise an exception there. The Reset method can be called to sort another set of data of the same record length. Once Get has been called, Put cannot be called again unless Reset is called first. There is no default Compare function. One must be assigned after creating a TStSorter and before calling Put. Otherwise an exception is raised the first time a Compare function is needed. If Create cannot allocate MaxHeap bytes for a work buffer, it repeatedly divides MaxHeap by two until it can successfully allocate that much space. After finding a block it can allocate, it does not attempt to allocate larger blocks that might still fit. Unlike MSORTP, STSORT always swaps full records. It does not use pointer swapping for large records. If this is desirable, the application should pass pointers to previously allocated records into the TStSorter class. The OptimumHeapToUse, MinimumHeapToUse, and MergeInfo functions can be used to optimize the buffer size before starting a sort. By default, temporary merge files are saved in the current directory with names of the form SORnnnnn.TMP, where nnnnn is a sequential file number. You can supply a different merge name function via the MergeName property to put the files in a different location or use a different form for the names. The sorter is thread-aware and uses critical sections to protect the Put, Get, and Reset methods. Be sure that one thread does not call Put after another thread has already called Get. } unit StSort; interface uses Windows, SysUtils, STConst, STBase; const {.Z+} MinRecsPerRun = 4; {Minimum number of records in run buffer} MergeOrder = 5; {Input files used at a time during merge, >=2, <=10} MedianThreshold = 16; {Threshold for using median-of-three quicksort} {.Z-} type TMergeNameFunc = function (MergeNum : Integer) : string; TMergeInfo = record {Record returned by MergeInfo} SortStatus : Integer; {Predicted status of sort, assuming disk ok} MergeFiles : Integer; {Total number of merge files created} MergeHandles : Integer; {Maximum file handles used} MergePhases : Integer; {Number of merge phases} MaxDiskSpace : Integer; {Maximum peak disk space used} HeapUsed : Integer; {Heap space actually used} end; {.Z+} TMergeIntArray = array[1..MergeOrder] of Integer; TMergeLongArray = array[1..MergeOrder] of Integer; TMergePtrArray = array[1..MergeOrder] of Pointer; {.Z-} TStSorter = class(TObject) {.Z+} protected {property instance variables} FCount : Integer; {Number of records put to sort} FRecLen : Cardinal; {Size of each record} FCompare : TUntypedCompareFunc; {Compare function} FMergeName : TMergeNameFunc; {Merge file naming function} {private instance variables} sorRunCapacity : Integer; {Capacity (in records) of run buffer} sorRunCount : Integer; {Current number of records in run buffer} sorGetIndex : Integer; {Last run element passed back to user} sorPivotPtr : Pointer; {Pointer to pivot record} sorSwapPtr : Pointer; {Pointer to swap record} sorState : Integer; {0 = empty, 1 = adding, 2 = getting} sorMergeFileCount : Integer; {Number of merge files created} sorMergeFileMerged : Integer; {Index of last merge file merged} sorMergeOpenCount : Integer; {Count of open merge files} sorMergeBufSize : Integer; {Usable bytes in merge buffer} sorMergeFileNumber : TMergeIntArray; {File number of each open merge file} sorMergeFiles : TMergeIntArray; {File handles for merge files} sorMergeBytesLoaded: TMergeLongArray;{Count of bytes in each merge buffer} sorMergeBytesUsed : TMergeLongArray; {Bytes used in each merge buffer} sorMergeBases : TMergePtrArray; {Base index for each merge buffer} sorMergePtrs : TMergePtrArray; {Current head elements in each merge buffer} sorOutFile : Integer; {Output file handle} sorOutPtr : Pointer; {Pointer for output buffer} sorOutBytesUsed : Integer; {Number of bytes in output buffer} {$IFDEF ThreadSafe} sorThreadSafe : TRTLCriticalSection;{Windows critical section record} {$ENDIF} sorBuffer : Pointer; {Pointer to global buffer} {protected undocumented methods} procedure sorAllocBuffer(MaxHeap : Integer); procedure sorCreateNewMergeFile(var Handle : Integer); procedure sorDeleteMergeFiles; function sorElementPtr(Index : Integer) : Pointer; procedure sorFlushOutBuffer; procedure sorFreeBuffer; procedure sorGetMergeElementPtr(M : Integer); function sorGetNextElementIndex : Integer; procedure sorMergeFileGroup; procedure sorMoveElement(Src, Dest : Pointer);inline; procedure sorOpenMergeFiles; procedure sorPrimaryMerge; procedure sorRunSort(L, R : Integer); procedure sorStoreElement(Src : Pointer); procedure sorStoreNewMergeFile; procedure sorSwapElements(L, R : Integer); procedure sorSetCompare(Comp : TUntypedCompareFunc); {protected documented methods} procedure EnterCS; {-Enter critical section for this instance} procedure LeaveCS; {-Leave critical section} {.Z-} public constructor Create(MaxHeap : Integer; RecLen : Cardinal); virtual; {-Initialize a sorter} destructor Destroy; override; {-Destroy a sorter} procedure Put(const X); {-Add an element to the sort system} function Get(var X) : Boolean; {-Return next sorted element from the sort system} procedure Reset; {-Reset sorter before starting another sort} property Count : Integer {-Return the number of elements in the sorter} read FCount; property Compare : TUntypedCompareFunc {-Set or read the element comparison function} read FCompare write sorSetCompare; property MergeName : TMergeNameFunc {-Set or read the merge filename function} read FMergeName write FMergeName; property RecLen : Cardinal {-Return the size of each record} read FRecLen; end; function OptimumHeapToUse(RecLen : Cardinal; NumRecs : Integer) : Integer; {-Returns the optimum amount of heap space to sort NumRecs records of RecLen bytes each. Less heap space causes merging; more heap space is partially unused.} function MinimumHeapToUse(RecLen : Cardinal) : Integer; {-Returns the absolute minimum heap that allows MergeSort to succeed} function MergeInfo(MaxHeap : Integer; RecLen : Cardinal; NumRecs : Integer) : TMergeInfo; {-Predicts status and resource usage of a merge sort} function DefaultMergeName(MergeNum : Integer) : string; {-Default function used for returning merge file names} procedure ArraySort(var A; RecLen, NumRecs : Cardinal; Compare : TUntypedCompareFunc); {-Sort a normal Delphi array (A) in place} {======================================================================} implementation {$IFDEF FPC} uses Delphi.Windows; {$ENDIF} const ecOutOfMemory = 8; procedure RaiseError(Code : Integer); var E : ESTSortError; begin if Code = ecOutOfMemory then OutOfMemoryError else begin E := ESTSortError.CreateResTP(Code, 0); E.ErrorCode := Code; raise E; end; end; function DefaultMergeName(MergeNum : Integer) : string; begin Result := 'SOR'+IntToStr(MergeNum)+'.TMP'; end; function MergeInfo(MaxHeap : Integer; RecLen : Cardinal; NumRecs : Integer) : TMergeInfo; type MergeFileSizeArray = array[1..(StMaxBlockSize div SizeOf(Integer))] of Integer; var MFileMerged, MOpenCount, MFileCount : Integer; SizeBufSize, DiskSpace, OutputSpace, PeakDiskSpace : Integer; AllocRecs, RunCapacity, RecordsLeft, RecordsInFile : Integer; MFileSizeP : ^MergeFileSizeArray; begin {Set defaults for the result} FillChar(Result, SizeOf(TMergeInfo), 0); {Validate input parameters} if (RecLen = 0) or (MaxHeap <= 0) or (NumRecs <= 0) then begin Result.SortStatus := stscBadSize; Exit; end; AllocRecs := MaxHeap div Integer(RecLen); if AllocRecs < MergeOrder+1 then begin Result.SortStatus := stscBadSize; Exit; end; RunCapacity := AllocRecs-2; if RunCapacity < MinRecsPerRun then begin Result.SortStatus := stscBadSize; Exit; end; {Compute amount of memory used} Result.HeapUsed := AllocRecs*Integer(RecLen); if RunCapacity >= NumRecs then {All the records fit into memory} Exit; {Compute initial number of merge files and disk space} MFileCount := NumRecs div (AllocRecs-2); if NumRecs mod (AllocRecs-2) <> 0 then inc(MFileCount); {if MFileCount > MaxInt then begin } { Result.SortStatus := stscTooManyFiles;} { Exit; } {end; } DiskSpace := NumRecs*Integer(RecLen); {At least one merge phase required} Result.MergePhases := 1; if MFileCount <= MergeOrder then begin {Only one merge phase, direct to user} Result.MergeFiles := MFileCount; Result.MergeHandles := MFileCount; Result.MaxDiskSpace := DiskSpace; Exit; end; {Compute total number of merge files and merge phases} MFileMerged := 0; while MFileCount-MFileMerged > MergeOrder do begin inc(Result.MergePhases); MOpenCount := 0; while (MOpenCount < MergeOrder) and (MFileMerged < MFileCount) do begin inc(MOpenCount); inc(MFileMerged); end; inc(MFileCount); end; {Store the information we already know} Result.MergeFiles := MFileCount; Result.MergeHandles := MergeOrder+1; {MergeOrder input files, 1 output file} {Determine whether the disk space analysis can proceed} Result.MaxDiskSpace := -1; if MFileCount > (StMaxBlockSize div SizeOf(Integer)) then Exit; SizeBufSize := MFileCount*SizeOf(Integer); try GetMem(MFileSizeP, SizeBufSize); except Exit; end; {Compute size of initial merge files} RecordsLeft := NumRecs; MFileCount := 0; while RecordsLeft > 0 do begin inc(MFileCount); if RecordsLeft >= RunCapacity then RecordsInFile := RunCapacity else RecordsInFile := RecordsLeft; MFileSizeP^[MFileCount] := RecordsInFile*Integer(RecLen); dec(RecordsLeft, RecordsInFile); end; {Carry sizes forward to get disk space used} PeakDiskSpace := DiskSpace; MFileMerged := 0; while MFileCount-MFileMerged > MergeOrder do begin MOpenCount := 0; OutputSpace := 0; while (MOpenCount < MergeOrder) and (MFileMerged < MFileCount) do begin inc(MOpenCount); inc(MFileMerged); inc(OutputSpace, MFileSizeP^[MFileMerged]); end; inc(MFileCount); {Save size of output file} MFileSizeP^[MFileCount] := OutputSpace; {Output file and input files coexist temporarily} inc(DiskSpace, OutputSpace); {Store new peak disk space} if DiskSpace > PeakDiskSpace then PeakDiskSpace := DiskSpace; {Account for deleting input files} dec(DiskSpace, OutputSpace); end; Result.MaxDiskSpace := PeakDiskSpace; FreeMem(MFileSizeP, SizeBufSize); end; function MinimumHeapToUse(RecLen : Cardinal) : Integer; var HeapToUse : Integer; begin HeapToUse := (MergeOrder+1)*RecLen; Result := (MinRecsPerRun+2)*RecLen; if Result < HeapToUse then Result := HeapToUse; end; function OptimumHeapToUse(RecLen : Cardinal; NumRecs : Integer) : Integer; begin if (NumRecs < MergeOrder+1) then NumRecs := MergeOrder+1; Result := Integer(RecLen)*(NumRecs+2); end; {----------------------------------------------------------------------} constructor TStSorter.Create(MaxHeap : Integer; RecLen : Cardinal); begin if (RecLen = 0) or (MaxHeap <= 0) then RaiseError(stscBadSize); FMergeName := DefaultMergeName; FRecLen := RecLen; {Allocate a sort work buffer using at most MaxHeap bytes} sorAllocBuffer(MaxHeap); {$IFDEF ThreadSafe} Windows.InitializeCriticalSection(sorThreadSafe); {$ENDIF} end; destructor TStSorter.Destroy; begin {$IFDEF ThreadSafe} Windows.DeleteCriticalSection(sorThreadSafe); {$ENDIF} sorDeleteMergeFiles; sorFreeBuffer; end; procedure TStSorter.EnterCS; begin {$IFDEF ThreadSafe} EnterCriticalSection(sorThreadSafe); {$ENDIF} end; function TStSorter.Get(var X) : Boolean; var NextIndex : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Result := False; if sorState <> 2 then begin {First call to Get} if sorRunCount > 0 then begin {Still have elements to sort} sorRunSort(0, sorRunCount-1); if sorMergeFileCount > 0 then begin {Already have other merge files} sorStoreNewMergeFile; sorPrimaryMerge; sorOpenMergeFiles; end else {No merging necessary} sorGetIndex := 0; end else if FCount = 0 then {No elements were sorted} Exit; sorState := 2; end; if sorMergeFileCount > 0 then begin {Get next record from merge files} NextIndex := sorGetNextElementIndex; if NextIndex <> 0 then begin {Return the element} sorMoveElement(sorMergePtrs[NextIndex], @X); {Get pointer to next element in the stream just used} sorGetMergeElementPtr(NextIndex); Result := True; end; end else if sorGetIndex < sorRunCount then begin {Get next record from run buffer} sorMoveElement(sorElementPtr(sorGetIndex), @X); inc(sorGetIndex); Result := True; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStSorter.LeaveCS; begin {$IFDEF ThreadSafe} LeaveCriticalSection(sorThreadSafe); {$ENDIF} end; procedure TStSorter.Reset; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} sorDeleteMergeFiles; FCount := 0; sorState := 0; sorRunCount := 0; sorMergeFileCount := 0; sorMergeFileMerged := 0; sorMergeOpenCount := 0; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStSorter.Put(const X); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if sorState = 2 then {Can't Put after calling Get} RaiseError(stscBadState); sorState := 1; if sorRunCount >= sorRunCapacity then begin {Run buffer full; sort buffer and store to disk} sorRunSort(0, sorRunCount-1); sorStoreNewMergeFile; sorRunCount := 0; end; {Store new element into run buffer} sorMoveElement(@X, sorElementPtr(sorRunCount)); inc(sorRunCount); inc(FCount); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStSorter.sorAllocBuffer(MaxHeap : Integer); {-Allocate a work buffer of records in at most MaxHeap bytes} var Status : Integer; AllocRecs : Integer; begin Status := stscBadSize; repeat AllocRecs := MaxHeap div Integer(FRecLen); if AllocRecs < MergeOrder+1 then RaiseError(Status); {$WARN SYMBOL_PLATFORM OFF} sorBuffer := GlobalAllocPtr(HeapAllocFlags, AllocRecs*Integer(FRecLen)); {$WARN SYMBOL_PLATFORM ON} if sorBuffer = nil then begin Status := ecOutOfMemory; MaxHeap := MaxHeap div 2; end else break; until False; sorMergeBufSize := Integer(FRecLen)*(AllocRecs div (MergeOrder+1)); sorRunCapacity := AllocRecs-2; if sorRunCapacity < MinRecsPerRun then RaiseError(Status); sorPivotPtr := sorElementPtr(AllocRecs-1); sorSwapPtr := sorElementPtr(AllocRecs-2); end; procedure TStSorter.sorCreateNewMergeFile(var Handle : Integer); {-Create another merge file and return its handle} begin if sorMergeFileCount = MaxInt then {Too many merge files} RaiseError(stscTooManyFiles); {Create new merge file} inc(sorMergeFileCount); Handle := FileCreate(FMergeName(sorMergeFileCount)); if Handle < 0 then begin dec(sorMergeFileCount); RaiseError(stscFileCreate); end; end; procedure TStSorter.sorDeleteMergeFiles; {-Delete open and already-closed merge files} var I : Integer; begin for I := 1 to sorMergeOpenCount do begin FileClose(sorMergeFiles[I]); SysUtils.DeleteFile(FMergeName(sorMergeFileNumber[I])); end; for I := sorMergeFileMerged+1 to sorMergeFileCount do SysUtils.DeleteFile(FMergeName(I)); end; function TStSorter.sorElementPtr(Index : Integer) : Pointer; {-Return a pointer to the given element in the sort buffer} begin Result := PAnsiChar(sorBuffer)+Index*Integer(FRecLen); end; procedure TStSorter.sorFlushOutBuffer; {-Write the merge output buffer to disk} var BytesWritten : Integer; begin if sorOutBytesUsed <> 0 then begin BytesWritten := FileWrite(sorOutFile, sorOutPtr^, sorOutBytesUsed); if BytesWritten <> sorOutBytesUsed then RaiseError(stscFileWrite); end; end; procedure TStSorter.sorFreeBuffer; begin GlobalFreePtr(sorBuffer); end; procedure TStSorter.sorGetMergeElementPtr(M : Integer); {-Update head pointer in input buffer of specified open merge file} var BytesRead : Integer; begin if sorMergeBytesUsed[M] >= sorMergeBytesLoaded[M] then begin {Try to load new data into buffer} BytesRead := FileRead(sorMergeFiles[M], sorMergeBases[M]^, sorMergeBufSize); if BytesRead < 0 then {Error reading file} RaiseError(stscFileRead); if BytesRead < Integer(FRecLen) then begin {End of file. Close and delete it} FileClose(sorMergeFiles[M]); SysUtils.DeleteFile(FMergeName(sorMergeFileNumber[M])); {Remove file from merge list} if M <> sorMergeOpenCount then begin sorMergeFileNumber[M] := sorMergeFileNumber[sorMergeOpenCount]; sorMergeFiles[M] := sorMergeFiles[sorMergeOpenCount]; sorMergePtrs[M] := sorMergePtrs[sorMergeOpenCount]; sorMergeBytesLoaded[M] := sorMergeBytesLoaded[sorMergeOpenCount]; sorMergeBytesUsed[M] := sorMergeBytesUsed[sorMergeOpenCount]; sorMergeBases[M] := sorMergeBases[sorMergeOpenCount]; end; dec(sorMergeOpenCount); Exit; end; sorMergeBytesLoaded[M] := BytesRead; sorMergeBytesUsed[M] := 0; end; sorMergePtrs[M] := PAnsiChar(sorMergeBases[M])+sorMergeBytesUsed[M]; inc(sorMergeBytesUsed[M], FRecLen); end; function TStSorter.sorGetNextElementIndex : Integer; {-Return index into open merge file of next smallest element} var M : Integer; MinElPtr : Pointer; begin if sorMergeOpenCount = 0 then begin {All merge streams are empty} Result := 0; Exit; end; {Assume first element is the least} MinElPtr := sorMergePtrs[1]; Result := 1; {Scan the other elements} for M := 2 to sorMergeOpenCount do if FCompare(sorMergePtrs[M]^, MinElPtr^) < 0 then begin Result := M; MinElPtr := sorMergePtrs[M]; end; end; procedure TStSorter.sorMergeFileGroup; {-Merge a group of input files into one output file} var NextIndex : Integer; begin sorOutBytesUsed := 0; repeat {Find index of minimum element} NextIndex := sorGetNextElementIndex; if NextIndex = 0 then break else begin {Copy element to output} sorStoreElement(sorMergePtrs[NextIndex]); {Get the next element from its merge stream} sorGetMergeElementPtr(NextIndex); end; until False; {Flush and close the output file} sorFlushOutBuffer; FileClose(sorOutFile); end; procedure TStSorter.sorMoveElement(Src, Dest : Pointer); {$ifndef FPC} assembler; {$endif} {-Copy one record to another location, non-overlapping} begin Move(Src^, Dest^, FRecLen); end; procedure TStSorter.sorOpenMergeFiles; {-Open a group of up to MergeOrder input files} begin sorMergeOpenCount := 0; while (sorMergeOpenCount < MergeOrder) and (sorMergeFileMerged < sorMergeFileCount) do begin inc(sorMergeOpenCount); {Open associated merge file} inc(sorMergeFileMerged); sorMergeFiles[sorMergeOpenCount] := FileOpen(FMergeName(sorMergeFileMerged), fmOpenRead); if sorMergeFiles[sorMergeOpenCount] < 0 then begin dec(sorMergeFileMerged); dec(sorMergeOpenCount); RaiseError(stscFileOpen); end; {File number of merge file} sorMergeFileNumber[sorMergeOpenCount] := sorMergeFileMerged; {Selector for merge file} sorMergePtrs[sorMergeOpenCount] := PAnsiChar(sorBuffer)+ (sorMergeOpenCount-1)*sorMergeBufSize; {Number of bytes currently in merge buffer} sorMergeBytesLoaded[sorMergeOpenCount] := 0; {Number of bytes used in merge buffer} sorMergeBytesUsed[sorMergeOpenCount] := 0; {Save the merge pointer} sorMergeBases[sorMergeOpenCount] := sorMergePtrs[sorMergeOpenCount]; {Get the first element} sorGetMergeElementPtr(sorMergeOpenCount); end; end; procedure TStSorter.sorPrimaryMerge; {-Merge until there are no more than MergeOrder merge files left} begin sorOutPtr := PAnsiChar(sorBuffer)+MergeOrder*sorMergeBufSize; while sorMergeFileCount-sorMergeFileMerged > MergeOrder do begin {Open next group of MergeOrder files} sorOpenMergeFiles; {Create new output file} sorCreateNewMergeFile(sorOutFile); {Merge these files into the output} sorMergeFileGroup; end; end; procedure TStSorter.sorRunSort(L, R : Integer); {-Sort one run buffer full of records in memory using non-recursive QuickSort} const StackSize = 32; type Stack = array[0..StackSize-1] of Integer; var Pl : Integer; {Left edge within partition} Pr : Integer; {Right edge within partition} Pm : Integer; {Mid-point of partition} PartitionLen : Integer; {Size of current partition} StackP : Integer; {Stack pointer} Lstack : Stack; {Pending partitions, left edge} Rstack : Stack; {Pending partitions, right edge} begin {Make sure there's a compare function} if @FCompare = nil then RaiseError(stscNoCompare); {Initialize the stack} StackP := 0; Lstack[0] := L; Rstack[0] := R; {Repeatedly take top partition from stack} repeat {Pop the stack} L := Lstack[StackP]; R := Rstack[StackP]; Dec(StackP); {Sort current partition} repeat Pl := L; Pr := R; PartitionLen := Pr-Pl+1; {$IFDEF MidPoint} Pm := Pl+(PartitionLen shr 1); {$ENDIF} {$IFDEF Random} Pm := Pl+Random(PartitionLen); {$ENDIF} {$IFDEF Median} Pm := Pl+(PartitionLen shr 1); if PartitionLen >= MedianThreshold then begin {Sort elements Pl, Pm, Pr} if FCompare(sorElementPtr(Pm)^, sorElementPtr(Pl)^) < 0 then sorSwapElements(Pm, Pl); if FCompare(sorElementPtr(Pr)^, sorElementPtr(Pl)^) < 0 then sorSwapElements(Pr, Pl); if FCompare(sorElementPtr(Pr)^, sorElementPtr(Pm)^) < 0 then sorSwapElements(Pr, Pm); {Exchange Pm with Pr-1 but use Pm's value as the pivot} sorSwapElements(Pm, Pr-1); Pm := Pr-1; {Reduce range of swapping} inc(Pl); dec(Pr, 2); end; {$ENDIF} {Save the pivot element} sorMoveElement(sorElementPtr(Pm), sorPivotPtr); {Swap items in sort order around the pivot} repeat while FCompare(sorElementPtr(Pl)^, sorPivotPtr^) < 0 do Inc(Pl); while FCompare(sorPivotPtr^, sorElementPtr(Pr)^) < 0 do Dec(Pr); if Pl = Pr then begin {Reached the pivot} Inc(Pl); Dec(Pr); end else if Pl < Pr then begin {Swap elements around the pivot} sorSwapElements(Pl, Pr); Inc(Pl); Dec(Pr); end; until Pl > Pr; {Decide which partition to sort next} if (Pr-L) < (R-Pl) then begin {Left partition is bigger} if Pl < R then begin {Stack the request for sorting right partition} Inc(StackP); Lstack[StackP] := Pl; Rstack[StackP] := R; end; {Continue sorting left partition} R := Pr; end else begin {Right partition is bigger} if L < Pr then begin {Stack the request for sorting left partition} Inc(StackP); Lstack[StackP] := L; Rstack[StackP] := Pr; end; {Continue sorting right partition} L := Pl; end; until L >= R; until StackP < 0; end; procedure TStSorter.sorSetCompare(Comp : TUntypedCompareFunc); {-Set the compare function, with error checking} begin if ((FCount <> 0) or (@Comp = nil)) and (@Comp <> @FCompare) then RaiseError(stscBadCompare); FCompare := Comp; end; procedure TStSorter.sorStoreElement(Src : Pointer); {-Store element in the merge output buffer} begin if sorOutBytesUsed >= sorMergeBufSize then begin sorFlushOutBuffer; sorOutBytesUsed := 0; end; sorMoveElement(Src, PAnsiChar(sorOutPtr)+sorOutBytesUsed); inc(sorOutBytesUsed, FRecLen); end; procedure TStSorter.sorStoreNewMergeFile; {-Create new merge file, write run buffer to it, close file} var BytesToWrite, BytesWritten : Integer; begin sorCreateNewMergeFile(sorOutFile); try BytesToWrite := sorRunCount*Integer(FRecLen); BytesWritten := FileWrite(sorOutFile, sorBuffer^, BytesToWrite); if BytesWritten <> BytesToWrite then RaiseError(stscFileWrite); finally {Close merge file} FileClose(sorOutFile); end; end; procedure TStSorter.sorSwapElements(L, R : Integer); {-Swap elements with indexes L and R} var LPtr : Pointer; RPtr : Pointer; begin LPtr := sorElementPtr(L); RPtr := sorElementPtr(R); sorMoveElement(LPtr, sorSwapPtr); sorMoveElement(RPtr, LPtr); sorMoveElement(sorSwapPtr, RPtr); end; procedure ArraySort(var A; RecLen, NumRecs : Cardinal; Compare : TUntypedCompareFunc); const StackSize = 32; type Stack = array[0..StackSize-1] of Integer; var Pl, Pr, Pm, L, R : Integer; ArraySize, PartitionLen : Integer; PivotPtr : Pointer; SwapPtr : Pointer; StackP : Integer; Lstack, Rstack : Stack; function ElementPtr(Index : Cardinal) : Pointer; begin Result := PAnsiChar(@A)+Index*RecLen; end; procedure SwapElements(L, R : Integer); var LPtr : Pointer; RPtr : Pointer; begin LPtr := ElementPtr(L); RPtr := ElementPtr(R); Move(LPtr^, SwapPtr^, RecLen); Move(RPtr^, LPtr^, RecLen); Move(SwapPtr^, RPtr^, RecLen); end; begin {Make sure there's a compare function} if @Compare = nil then RaiseError(stscNoCompare); {Make sure the array size is reasonable} ArraySize := Integer(RecLen)*Integer(NumRecs); if (ArraySize = 0) {or (ArraySize > MaxBlockSize)} then RaiseError(stscBadSize); {Get pivot and swap elements} GetMem(PivotPtr, RecLen); try GetMem(SwapPtr, RecLen); try {Initialize the stack} StackP := 0; Lstack[0] := 0; Rstack[0] := NumRecs-1; {Repeatedly take top partition from stack} repeat {Pop the stack} L := Lstack[StackP]; R := Rstack[StackP]; Dec(StackP); {Sort current partition} repeat Pl := L; Pr := R; PartitionLen := Pr-Pl+1; {$IFDEF MidPoint} Pm := Pl+(PartitionLen shr 1); {$ENDIF} {$IFDEF Random} Pm := Pl+Random(PartitionLen); {$ENDIF} {$IFDEF Median} Pm := Pl+(PartitionLen shr 1); if PartitionLen >= MedianThreshold then begin {Sort elements Pl, Pm, Pr} if Compare(ElementPtr(Pm)^, ElementPtr(Pl)^) < 0 then SwapElements(Pm, Pl); if Compare(ElementPtr(Pr)^, ElementPtr(Pl)^) < 0 then SwapElements(Pr, Pl); if Compare(ElementPtr(Pr)^, ElementPtr(Pm)^) < 0 then SwapElements(Pr, Pm); {Exchange Pm with Pr-1 but use Pm's value as the pivot} SwapElements(Pm, Pr-1); Pm := Pr-1; {Reduce range of swapping} inc(Pl); dec(Pr, 2); end; {$ENDIF} {Save the pivot element} Move(ElementPtr(Pm)^, PivotPtr^, RecLen); {Swap items in sort order around the pivot} repeat while Compare(ElementPtr(Pl)^, PivotPtr^) < 0 do Inc(Pl); while Compare(PivotPtr^, ElementPtr(Pr)^) < 0 do Dec(Pr); if Pl = Pr then begin {Reached the pivot} Inc(Pl); Dec(Pr); end else if Pl < Pr then begin {Swap elements around the pivot} SwapElements(Pl, Pr); Inc(Pl); Dec(Pr); end; until Pl > Pr; {Decide which partition to sort next} if (Pr-L) < (R-Pl) then begin {Left partition is bigger} if Pl < R then begin {Stack the request for sorting right partition} Inc(StackP); Lstack[StackP] := Pl; Rstack[StackP] := R; end; {Continue sorting left partition} R := Pr; end else begin {Right partition is bigger} if L < Pr then begin {Stack the request for sorting left partition} Inc(StackP); Lstack[StackP] := L; Rstack[StackP] := Pr; end; {Continue sorting right partition} L := Pl; end; until L >= R; until StackP < 0; finally FreeMem(SwapPtr, RecLen); end; finally FreeMem(PivotPtr, RecLen); end; end; end.
namespace Sugar.Shared.Test.Tests; interface uses Sugar, RemObjects.Elements.EUnit; type TimeSpanTest = public class(Test) private protected public method Operators; method FromToDateTime; method &From; method Values; end; implementation method TimeSpanTest.Operators; begin var lTS := new TimeSpan(1,0,0); var lTS2 := lTS + new TimeSpan(2,0,0); Assert.AreEqual(lTS2.Hours, 3); Assert.IsFalse(lTS2 = lTS); Assert.IsTrue(lTS2 <> lTS); Assert.IsTrue(lTS2 > lTS); Assert.IsTrue(lTS2 >= lTS); Assert.IsFalse(lTS2 < lTS); Assert.IsFalse(lTS2 <= lTS); end; method TimeSpanTest.FromToDateTime; begin var lDateTime := new DateTime(2015, 1, 2, 3, 4, 5); Assert.AreEqual(lDateTime.Hour, 3); var lDT2 := lDateTime + new TimeSpan(1,0,0); Assert.AreEqual(lDateTime.Hour, 3); // old should NOT change Assert.AreEqual(lDT2.Hour, 4); var lDT3 := lDT2 - new TimeSpan(1,0,0); Assert.AreEqual(lDT3.Hour, 3); Assert.AreEqual(ldt3.Ticks, lDateTime.Ticks); end; method TimeSpanTest.From; begin Assert.AreEqual(TimeSpan.FromDays(2).Ticks, 1728000000000); Assert.AreEqual(TimeSpan.FromHours(2).Ticks, 72000000000); Assert.AreEqual(TimeSpan.FromMinutes(2).Ticks, 1200000000); Assert.AreEqual(TimeSpan.FromSeconds(2).Ticks, 20000000); Assert.AreEqual(TimeSpan.FromMilliseconds(2).Ticks, 20000); end; method TimeSpanTest.Values; begin Assert.AreEqual(new TimeSpan(15 * TimeSpan.TicksPerSecond).Ticks, 15 * TimeSpan.TicksPerSecond); Assert.AreEqual(new TimeSpan(3,4,5).Ticks, 110450000000); Assert.AreEqual(new TimeSpan(3,4,5).Days, 0); Assert.AreEqual(new TimeSpan(3,4,5).Hours, 3); Assert.AreEqual(new TimeSpan(3,4,5).Minutes, 4); Assert.AreEqual(new TimeSpan(3,4,5).Seconds, 5); Assert.AreEqual(Int64(new TimeSpan(3,4,5).TotalHours), 3); Assert.AreEqual(Int64(new TimeSpan(3,4,5).TotalMinutes), 3 * 60 + 4); Assert.AreEqual(Int64(new TimeSpan(3,4,5).TotalSeconds), (3 * 60 + 4) * 60 + 5); Assert.AreEqual(new TimeSpan(1,2,3,4,5).Ticks, 937840050000); Assert.AreEqual(new TimeSpan(1,2,3,4,5).Days, 1); Assert.AreEqual(new TimeSpan(1,2,3,4,5).hours, 2); Assert.AreEqual(new TimeSpan(1,2,3,4,5).Minutes, 3); Assert.AreEqual(new TimeSpan(1,2,3,4,5).Seconds, 4); Assert.AreEqual(new TimeSpan(1,2,3,4,5).Milliseconds, 5); end; end.
unit evTableHotSpot; {* Реализация интерфейсов IevHotSpotTester и IevAdvancedHotSpot для таблицы. } { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: evTableHotSpot - } { Начат: 03.11.2000 14:12 } { $Id: evTableHotSpot.pas,v 1.58 2015/01/19 18:36:36 lulin Exp $ } // $Log: evTableHotSpot.pas,v $ // Revision 1.58 2015/01/19 18:36:36 lulin // {RequestLink:580710025} // // Revision 1.57 2014/04/30 11:23:52 lulin // - выпрямляем зависимости. // // Revision 1.56 2014/04/29 13:38:51 lulin // - вычищаем ненужные зависимости. // // Revision 1.55 2014/04/21 11:45:00 lulin // - переходим от интерфейсов к объектам. // // Revision 1.54 2014/04/07 17:56:59 lulin // - переходим от интерфейсов к объектам. // // Revision 1.53 2014/01/14 08:59:58 dinishev // Чистка кода. // // Revision 1.52 2013/10/21 15:42:58 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.51 2013/10/21 10:30:41 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.50 2011/09/13 10:48:06 lulin // {RequestLink:278839709}. // // Revision 1.49 2011/02/22 19:41:04 lulin // {RequestLink:182157315}. // // Revision 1.48 2011/02/15 11:24:49 lulin // {RequestLink:231670346}. // // Revision 1.47 2010/06/24 15:16:27 lulin // {RequestLink:219125149}. // - пытаемся скроллировать окно, если ушли за его пределы. // // Revision 1.46 2010/06/24 12:52:54 lulin // {RequestLink:219125149}. // // Revision 1.45 2010/03/02 13:34:35 lulin // {RequestLink:193823544}. // // Revision 1.44 2010/03/01 14:50:06 lulin // {RequestLink:193823544}. // - шаг второй. // // Revision 1.43 2009/07/23 08:14:39 lulin // - вычищаем ненужное использование процессора операций. // // Revision 1.42 2009/07/14 14:56:28 lulin // {RequestLink:141264340}. №25. // // Revision 1.41 2009/07/13 12:31:37 lulin // {RequestLink:141264340}. №23ac. // // Revision 1.40 2009/07/11 17:11:05 lulin // {RequestLink:141264340}. №19. // // Revision 1.39 2009/07/11 15:55:09 lulin // {RequestLink:141264340}. №22. // // Revision 1.38 2009/05/29 17:18:25 lulin // [$142610853]. // // Revision 1.37 2009/05/22 10:22:42 dinishev // [$146905496] // // Revision 1.36 2009/05/22 06:39:40 dinishev // Cleanup // // Revision 1.35 2009/04/14 18:11:55 lulin // [$143396720]. Подготовительная работа. // // Revision 1.34 2009/04/06 09:45:27 lulin // [$140837386]. Убираем старорежимную примесь для списков параграфов. // // Revision 1.33 2009/03/31 12:04:36 lulin // [$140286997]. // // Revision 1.32 2009/03/04 13:32:47 lulin // - <K>: 137470629. Генерируем идентификаторы типов с модели и убираем их из общей помойки. // // Revision 1.31 2008/05/05 12:56:39 lulin // - <K>: 90439843. // // Revision 1.30 2008/04/24 12:26:19 lulin // - изменения в рамках <K>: 89106312. // // Revision 1.29 2008/04/09 17:57:08 lulin // - передаём вью в рамках <K>: 89096854. // // Revision 1.28 2008/04/04 16:17:59 lulin // - теперь у базового вью нельзя получить курсор по точке. // // Revision 1.27 2008/02/29 10:54:50 dinishev // Bug fix: не выдылялась ячейка при щечлке // // Revision 1.26 2008/02/27 17:24:58 lulin // - подгоняем код под модель. // // Revision 1.25 2007/12/04 12:47:05 lulin // - перекладываем ветку в HEAD. // // Revision 1.22.8.35 2007/11/28 15:41:22 dinishev // Корректная работа с выделением ячейки // // Revision 1.22.8.34 2007/06/22 19:18:57 lulin // - cleanup. // // Revision 1.22.8.33 2007/02/12 17:15:59 lulin // - переводим на строки с кодировкой. // // Revision 1.22.8.32 2007/02/12 16:40:20 lulin // - переводим на строки с кодировкой. // // Revision 1.22.8.31 2007/01/24 10:21:42 oman // - new: Локализация библиотек - ev (cq24078) // // Revision 1.22.8.30 2006/11/20 15:55:11 lulin // - cleanup: не используем позицию курсора по вертикали, вне _View_. // // Revision 1.22.8.29 2006/11/03 11:00:07 lulin // - объединил с веткой 6.4. // // Revision 1.22.8.28.2.9 2006/10/31 09:39:37 lulin // - используем карту форматирования переданную сверху, а не привязанную к курсору. // // Revision 1.22.8.28.2.8 2006/10/31 09:21:18 lulin // - при поиске горячей точки подаем уже вычисленную карту форматирования. // // Revision 1.22.8.28.2.7 2006/10/25 14:30:48 lulin // - визуальная точка изничтожена как класс. // // Revision 1.22.8.28.2.6 2006/10/24 11:57:04 lulin // - cleanup: используем позицию, а не дочерний объект. // // Revision 1.22.8.28.2.5 2006/10/23 08:58:09 lulin // - теперь при определении "горячей точки" передаем базовый курсор. // // Revision 1.22.8.28.2.4 2006/10/19 13:33:18 lulin // - переводим курсоры и подсказки на новые рельсы. // // Revision 1.22.8.28.2.3 2006/10/19 12:05:43 lulin // - добавлен метод для выяснения информации о позиции курсора. // // Revision 1.22.8.28.2.2 2006/10/19 10:56:17 lulin // - параметры курсора переехали в более общую библиотеку. // // Revision 1.22.8.28.2.1 2006/10/18 13:06:34 lulin // - вычищены ненужные данные. // // Revision 1.22.8.28 2006/10/06 08:19:42 lulin // - выкидываем ненужный параметр - класс горячей точки. // // Revision 1.22.8.27.2.2 2006/10/04 15:17:08 lulin // - выкидываем ненужный параметр - класс горячей точки. // // Revision 1.22.8.27.2.1 2006/10/04 14:10:20 lulin // - упрощаем механизм получения горячих точек. // // Revision 1.22.8.27 2006/10/04 11:23:02 lulin // - при получении горячей точки передаем "состояние" курсора. // // Revision 1.22.8.26 2006/10/04 08:32:06 lulin // - теперь умолчательное поведение при действиях мышью описывается структурой - чтобы проще было расширять интерфейс. // // Revision 1.22.8.25 2006/10/04 06:23:44 lulin // - точку мыши упаковываем в состояние мыши. // // Revision 1.22.8.24 2006/10/04 04:33:51 lulin // - избавляемся от возвращаемого результа в стиле OLE. // // Revision 1.22.8.23 2006/07/21 11:43:31 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.22.8.22 2006/07/20 18:36:56 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.22.8.21 2006/07/20 12:55:46 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.22.8.20 2006/07/03 11:58:53 lulin // - передаем не множество клавиш, а "состояние мыши". // // Revision 1.22.8.19 2005/11/05 07:55:29 lulin // - cleanup: убраны ненужные преобразования объекта к параграфу. // // Revision 1.22.8.18 2005/11/04 16:47:58 lulin // - базовый объект теперь поддерживает свое удаление. // // Revision 1.22.8.17 2005/08/31 12:04:34 lulin // - удален ненужный модуль. // // Revision 1.22.8.16 2005/08/25 14:12:52 lulin // - new behavior: для КЗ не выводим Hint'ы и прочее для строк и ячеек таблицы с контролами. // // Revision 1.22.8.15 2005/07/20 18:36:11 lulin // - модуль переименован в сответствии с названием интерфейса. // // Revision 1.22.8.14 2005/07/18 11:22:37 lulin // - методу, возвращаещему выделение на параграфе дано более подходящее название. // // Revision 1.22.8.13 2005/07/07 17:15:46 lulin // - InevAnchor и InevViewPoint теперь наследуются от InevLocation. // // Revision 1.22.8.12 2005/07/07 15:38:05 lulin // - InevViewPoint теперь не наследуется от InevAnchor. // // Revision 1.22.8.11 2005/07/07 11:41:17 lulin // - передаем в _GetAdvancedHotSpot специальный интерфейс InevViewPoint. // // Revision 1.22.8.10 2005/07/05 16:02:44 lulin // - bug fix: восстановлен скроллинг при выделении текста мышью. // // Revision 1.22.8.9 2005/06/20 15:42:10 lulin // - cleanup: избавляемся от абсолютных координат. // // Revision 1.22.8.8 2005/06/14 14:51:51 lulin // - new interface: _InevSelection. // - remove interface: IevSelection. // // Revision 1.22.8.7 2005/06/14 12:38:58 lulin // - избавился от передачи безликого интерфейса (теперь передается View). // // Revision 1.22.8.6 2005/06/14 10:01:31 lulin // - избавился от передачи безликого интерфейса (теперь передается View). // // Revision 1.22.8.5 2005/06/11 08:55:38 lulin // - в какой-то мере восстановлена работоспособность HotSpot'ов. // // Revision 1.22.8.4 2005/06/07 13:43:48 lulin // - удален ненужный модуль. // // Revision 1.22.8.3 2005/06/02 12:33:08 lulin // - вчерне заменил прямое создание блока выделения на его получение от фабрики. // // Revision 1.22.8.2 2005/06/01 16:22:25 lulin // - remove unit: evIntf. // // Revision 1.22.8.1 2005/05/18 12:42:47 lulin // - отвел новую ветку. // // Revision 1.22.2.2 2005/04/09 12:48:37 lulin // - метод ParaByOffset переименован в _ShapeByPt и перенесен на интерфейс InevComplexShape. // // Revision 1.22.2.1 2005/04/08 13:35:05 lulin // - _Processor стал обязательным параметром. // // Revision 1.22 2005/04/07 15:42:05 lulin // - cleanup. // // Revision 1.21 2005/04/07 15:12:30 lulin // - удалены ненужные формальные параметры. // // Revision 1.20 2005/04/07 14:59:56 lulin // - new method: _InevShape._TranslatePt. // // Revision 1.19 2005/04/07 14:32:49 lulin // - remove proc: evGetTopPara. // // Revision 1.18 2005/03/28 11:32:08 lulin // - интерфейсы переехали в "правильный" модуль. // // Revision 1.17 2005/03/19 16:39:51 lulin // - спрятаны ненужные методы. // // Revision 1.16 2005/03/16 12:16:52 lulin // - переходим к _Ik2Tag. // // Revision 1.15 2005/03/10 16:40:10 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.14 2005/03/10 16:22:32 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.13 2003/10/02 16:33:24 law // - rename unit: evBseCur -> evBaseCursor. // // Revision 1.12 2003/01/13 15:58:31 law // - new behavior: возможность выделения строки таблицы целиком. // // Revision 1.11 2002/07/09 12:02:21 law // - rename unit: evUnits -> l3Units. // // Revision 1.10 2002/02/08 12:52:19 law // - new unit: evParaListTools. // // Revision 1.9 2002/02/08 12:14:48 law // - new unit: evParaList. // // Revision 1.8 2002/02/07 15:22:30 law // - rename class: IevBlock -> TevBlock, для того чтобы не путать его с интерфейсом. // // Revision 1.7 2002/02/07 15:05:25 law // - rename class: IevCursor -> _TevCursor, для того чтобы не путать его с интерфейсом. // // Revision 1.6 2002/02/06 13:33:50 law // - new behavior: возможность выделения столбцов таблицы при помощи мыши. // // Revision 1.5 2001/11/26 14:31:04 law // - change type: Keys: Long -> Keys: TShiftState. // // Revision 1.4 2001/04/12 16:35:26 law // - new behavior: сделаны стробы при операциях с мышью. // // Revision 1.3 2001/04/04 06:59:00 law // - bug fix: доделано рисование ячеек таблицы, объединенных по вертикали. // // Revision 1.2 2000/12/15 15:10:38 law // - вставлены директивы Log. // {$Include evDefine.inc } interface uses l3Types, l3Base, l3IID, l3Units, afwInterfaces, k2Interfaces, evInternalInterfaces, evParaListHotSpotTester, evSelectingHotSpot, nevTools, nevGUIInterfaces ; type TevTableHotSpotTester = class(TevParaListHotSpotTester) {* - Реализует интерфейс IevHotSpotTester для таблицы. } public //public methods function GetChildHotSpot(const aView : InevControlView; const aState : TevCursorState; const aPt : InevBasePoint; const aMap : InevMap; const aChild : InevObject; out theSpot : IevHotSpot): Boolean; override; {-} end;//TevTableHotSpotTester TevTableHotSpot = class(TevSelectingHotSpot) {* - Реализует интерфейс IevAdvancedHotSpot для таблицы. } private //internal fields f_ColumnIndex : Long; protected //property methods procedure DoHitTest(const aView : InevControlView; const aState : TafwCursorState; var theInfo : TafwCursorInfo); override; {-} protected // internal methods function InitSelection(const aView : InevControlView; const aPt : InevBasePoint; const theStart : InevBasePoint; const theFinish : InevBasePoint): Bool; override; {-} public //public methods constructor Create(aTag : Tl3Variant; const aProcessor : Ik2Processor; aColumnIndex : Integer); reintroduce; {-} class function Make(aTag : Tl3Variant; const aProcessor : Ik2Processor; aColumnIndex : Integer): IevHotSpot; reintroduce; {-} function MouseAction(const aView : InevControlView; aButton : TevMouseButton; anAction : TevMouseAction; const Keys : TevMouseState; var Effect : TevMouseEffect): Bool; override; {* - Обрабатывает событие мыши. } public //public properties property ColumnIndex: Long read f_ColumnIndex write f_ColumnIndex; {* - Индекс колонки таблицы над которой находится мышь. } end;//TevTableHotSpot implementation uses l3MinMax, l3Const, l3String, l3InterfacesMisc, k2Tags, evOp, evConst, evCursorTools, evHotSpotMisc, nevBase, nevInterfaces, ReqRow_Const, TableCell_Const ; // start class TevTableHotSpotTester function TevTableHotSpotTester.GetChildHotSpot(const aView : InevControlView; const aState : TevCursorState; const aPt : InevBasePoint; const aMap : InevMap; const aChild : InevObject; out theSpot : IevHotSpot): Boolean; //override; {* - Возвращает IevAdvancedHotSpot для точки aPt таблицы. } var l_Map : InevMap; begin l_Map := aMap; if (l_Map <> nil) then if (aChild.PID = 0) AND (aState.rPoint.Y - l_Map.Bounds.Top < evEpsilon * 5) then begin {$IfDef Nemesis} if not aChild.AsObject.IsKindOf(k2_typReqRow) then {$EndIf Nemesis} begin if aPt.HasInner then begin Result := True; theSpot := TevTableHotSpot.Make(aChild.OwnerObj.AsObject, Processor, aPt.Inner.Obj.PID); Exit; end;//aPt.HasInner end;//not aChild.IsKindOf(k2_typReqRow) end;//aPt.Y < evEpsilon * 5 Result := inherited GetChildHotSpot(aView, aState, aPt, aMap, aChild, theSpot); end; // start class TevTableHotSpot constructor TevTableHotSpot.Create(aTag : Tl3Variant; const aProcessor : Ik2Processor; aColumnIndex : Integer); //reintroduce; {-} begin inherited Create(aTag, aProcessor); ColumnIndex := aColumnIndex; end; class function TevTableHotSpot.Make(aTag : Tl3Variant; const aProcessor : Ik2Processor; aColumnIndex : Integer): IevHotSpot; //reintroduce; {-} var l_Spot : TevTableHotSpot; begin l_Spot := Create(aTag, aProcessor, aColumnIndex); try Result := TevHotSpotWrap.Make(l_Spot); finally l3Free(l_Spot); end;//try..finally end; procedure TevTableHotSpot.DoHitTest(const aView : InevControlView; const aState : TafwCursorState; var theInfo : TafwCursorInfo); //override; {-} begin inherited; theInfo.rCursor := ev_csSelectColumn; theInfo.rHint := str_nevmhhTableColumn.AsCStr; end; function TevTableHotSpot.MouseAction(const aView : InevControlView; aButton : TevMouseButton; anAction : TevMouseAction; const Keys : TevMouseState; var Effect : TevMouseEffect): Bool; {* - Обрабатывает событие мыши. } begin Result := inherited MouseAction(aView, aButton, anAction, Keys, Effect); case aButton of ev_mbLeft : begin case anAction of ev_maDown : Result := evSelectTableColumn(aView.Control.Selection, ParaX, ColumnIndex); ev_maDouble : begin Result := evSelectTablePara(aView.Control.Selection, ParaX); if Result then Effect.rNeedAsyncLoop := False; end;//ev_maDouble end;//case anAction end;//ev_mbLeft end;//case aButton end; function TevTableHotSpot.InitSelection(const aView: InevControlView; const aPt: InevBasePoint; const theStart, theFinish: InevBasePoint): Bool; var l_Point : InevBasePoint; l_Start : Integer; l_Finish : Integer; begin Result := True; Assert(aView <> nil); l_Point := aPt; while (l_Point <> nil) do begin if l_Point.AsObject.IsKindOf(k2_typTableCell) then Break; l_Point := l_Point.Inner; end;//while (l_Point <> nil) if (l_Point <> nil) then begin theStart.SetAtStart(aView, True); theFinish.SetAtEnd(aView, True); l_Start := Min(f_ColumnIndex, l_Point.Obj.PID); if theStart.HasInner then theStart.Inner.SetEntryPoint(l_Start + 1); l_Finish := Max(f_ColumnIndex, l_Point.Obj.PID); if theFinish.HasInner then theFinish.Inner.SetEntryPoint(l_Finish + 1); end//l_Point <> nil else Result := False; end; end.
unit SysRecords; interface uses Types,Classes,Graphics; type //保留字/关键字 TWWWord = packed record Mode : SmallInt; //类型 BegPos : LongInt; //起始位置 EndPos : LongInt; //结束位置 LinkID : LongInt; //相关联的Word位置 end; TWWWords = array of TWWWord; //程序块 TWWBlock = packed record Mode : SmallInt; //类型 BegPos : LongInt; //起始位置 EndPos : LongInt; //结束位置 Parent : Integer; //父节点ID ChildIDs : TIntegerDynArray; //子块ID数组 Status : Integer; //状态, 0:展开,1:合拢 BegMode : Integer; EndMode : Integer; LastMode : Integer; //最后一个词(除注释)的类型 //LostBeg : Integer; //LostEnd : integer; end; TWWBlocks = array of TWWBlock; //绘图的基本设置 TWWConfig = record Language : Byte; //语言 Indent : Byte; //缩进 RightMargin : Word; // BaseWidth : Integer; //基本宽度 BaseHeight : Integer; //基本高度 AutoSize : Boolean; //是否自动扩大 MaxWidth : Integer; //最大宽度 MaxHeight : Integer; //最大高度 SpaceVert : Integer; //纵向间距 SpaceHorz : Integer; //横向间距 FontName : String; FontSize : Byte; FontColor : TColor; LineColor : TColor; FillColor : TColor; IFColor : TColor; TryColor : TColor; SelectColor : TColor; Scale : Single; //缩放,默认为-1 ShowDetailCode : Boolean; //显示详细代码,默认为True // ChartType : Byte; //0:FlowChart, 1: NSChart AddCaption : Boolean; //生成代码时自动将Caption增加为注释 AddComment : Boolean; //生成代码时自动增加注释 end; TWWCode = record Mode : Integer; Exts : String; //后缀名列表,用逗号分开,比如:"c,cpp" end; // PBlockInfo = ^TBlockInfo; TBlockInfo = packed record FileName : WideString; //文件名称, 主要用于交差引用 // Text : WideString; //显示文本 ID : Integer; //生成Blocks时Index BegEndID : Integer; //如果父类,Begin...end的ID,则大于0,否则为-1 LastMode : Integer; //结尾的类型(除注释),用于粘贴/新建结构 Mode : SmallInt; //节点类型 BegPos : Integer; //起始位置 EndPos : Integer; //结束位置 ExtraBeg : Integer; //保存额外的起始位置, 用于删除函数时使用 ExtraEnd : Integer; // Status : Byte; //节点状态, 目前用于显示展开代码 //流程图参数 X,Y,W,H,E : Single; //X,Y位置,W,H大小,E向左额外的边距 end; TSearchOption = record Keyword : String; AtOnce : Boolean; Mode : Integer; FindInFiles : Boolean; ForwardDirection : Boolean; FromCursor : Boolean; CaseSensitivity : Boolean; WholeWord : Boolean; CaptionOnly : Boolean; RegularExpression : Boolean; end; TBlockCopyMode = record Source : Byte; //0:表示原样复制,1:复制到Block_Set AddMode : Byte; //0:表示Next, 1: Before, 2: LastChild, 3.Prev of LastChild //4: RootAppend, 5: FunctionAppend end; implementation end.
unit gradius3_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,m68000,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,sound_engine,ym_2151,k052109,k051960,k007232; function iniciar_gradius3:boolean; implementation const //gradius3 gradius3_rom:array[0..1] of tipo_roms=( (n:'945_r13.f15';l:$20000;p:0;crc:$cffd103f),(n:'945_r12.e15';l:$20000;p:$1;crc:$0b968ef6)); gradius3_rom_sub:array[0..7] of tipo_roms=( (n:'945_m09.r17';l:$20000;p:0;crc:$b4a6df25),(n:'945_m08.n17';l:$20000;p:$1;crc:$74e981d2), (n:'945_l06b.r11';l:$20000;p:$40000;crc:$83772304),(n:'945_l06a.n11';l:$20000;p:$40001;crc:$e1fd75b6), (n:'945_l07c.r15';l:$20000;p:$80000;crc:$c1e399b6),(n:'945_l07a.n15';l:$20000;p:$80001;crc:$96222d04), (n:'945_l07d.r13';l:$20000;p:$c0000;crc:$4c16d4bd),(n:'945_l07b.n13';l:$20000;p:$c0001;crc:$5e209d01)); gradius3_sound:tipo_roms=(n:'945_r05.d9';l:$10000;p:0;crc:$c8c45365); gradius3_sprites_1:array[0..1] of tipo_roms=( (n:'945_a02.l3';l:$80000;p:0;crc:$4dfffd74),(n:'945_a01.h3';l:$80000;p:2;crc:$339d6dd2)); gradius3_sprites_2:array[0..7] of tipo_roms=( (n:'945_l04a.k6';l:$20000;p:$100000;crc:$884e21ee),(n:'945_l04c.m6';l:$20000;p:$100001;crc:$45bcd921), (n:'945_l03a.e6';l:$20000;p:$100002;crc:$a67ef087),(n:'945_l03c.h6';l:$20000;p:$100003;crc:$a56be17a), (n:'945_l04b.k8';l:$20000;p:$180000;crc:$843bc67d),(n:'945_l04d.m8';l:$20000;p:$180001;crc:$0a98d08e), (n:'945_l03b.e8';l:$20000;p:$180002;crc:$933e68b9),(n:'945_l03d.h8';l:$20000;p:$180003;crc:$f375e87b)); gradius3_k007232:array[0..2] of tipo_roms=( (n:'945_a10.b15';l:$40000;p:0;crc:$1d083e10),(n:'945_l11a.c18';l:$20000;p:$40000;crc:$6043f4eb), (n:'945_l11b.c20';l:$20000;p:$60000;crc:$89ea3baf)); //DIP gradius3_dip_a:array [0..1] of def_dip=( (mask:$f;name:'Coinage';number:16;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'2C 3C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'))),()); gradius3_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'2'),(dip_val:$2;dip_name:'3'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'20k 70k+'),(dip_val:$10;dip_name:'100k 100k+'),(dip_val:$8;dip_name:'50k'),(dip_val:$0;dip_name:'100k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); gradius3_dip_c:array [0..2] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Upright Controls';number:2;dip:((dip_val:$2;dip_name:'Single'),(dip_val:$0;dip_name:'Dual'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom:array[0..$1ffff] of word; rom_sub:array[0..$7ffff] of word; ram,ram_sub,ram_share:array[0..$1fff] of word; ram_gfx:array[0..$ffff] of word; sprite_rom,k007232_rom:pbyte; sound_latch,sprite_colorbase,irqB_mask:byte; layer_colorbase:array[0..2] of byte; irqA_mask,priority:boolean; procedure gradius3_cb(layer,bank:word;var code:dword;var color:word;var flags:word;var priority:word); begin code:=code or (((color and $01) shl 8) or ((color and $1c) shl 7)); color:=layer_colorbase[layer]+((color and $e0) shr 5); end; procedure gradius3_sprite_cb(var code:word;var color:word;var pri:word;var shadow:word); const L0=1; L1=2; L2=3; primask:array[0..1,0..3] of byte=( ( L0 or L2, L0, L0 or L2, L0 or L1 or L2 ), ( L1 or L2, L2, 0, L0 or L1 or L2 )); var prio:byte; begin prio:=((color and $60) shr 5); if not(priority) then pri:=primask[0][prio] else pri:=primask[1][prio]; code:=code or ((color and $01) shl 13); color:=sprite_colorbase+((color and $1e) shr 1); end; procedure gradius3_k007232_cb(valor:byte); begin k007232_0.set_volume(0,(valor shr 4)*$11,0); k007232_0.set_volume(1,0,(valor and $0f)*$11); end; procedure update_video_gradius3; begin k052109_0.write($1d80,$10); k052109_0.write($1f00,$32); k052109_0.draw_tiles; k051960_0.update_sprites; fill_full_screen(4,0); if priority then begin k051960_0.draw_sprites(6,-1); k051960_0.draw_sprites(5,-1); k052109_0.draw_layer(0,4); k051960_0.draw_sprites(4,-1); k051960_0.draw_sprites(3,-1); k052109_0.draw_layer(1,4); k051960_0.draw_sprites(2,-1); k051960_0.draw_sprites(1,-1); k052109_0.draw_layer(2,4); k051960_0.draw_sprites(0,-1); end else begin k051960_0.draw_sprites(6,-1); k051960_0.draw_sprites(5,-1); k052109_0.draw_layer(1,4); k051960_0.draw_sprites(4,-1); k051960_0.draw_sprites(3,-1); k052109_0.draw_layer(2,4); k051960_0.draw_sprites(2,-1); k051960_0.draw_sprites(1,-1); k052109_0.draw_layer(0,4); k051960_0.draw_sprites(0,-1); end; actualiza_trozo_final(96,16,320,224,4); end; procedure eventos_gradius3; begin if event.arcade then begin //P1 if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); //P2 if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40); //COIN if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); end; end; procedure gradius3_principal; var frame_m,frame_sub,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_sub:=m68000_1.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sub m68000_1.run(frame_sub); frame_sub:=frame_sub+m68000_1.tframes-m68000_1.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; case f of 15:if (irqB_mask and 2)<>0 then m68000_1.irq[2]:=HOLD_LINE; 239:begin update_video_gradius3; if irqA_mask then m68000_0.irq[2]:=HOLD_LINE; if (irqB_mask and 1)<>0 then m68000_1.irq[1]:=HOLD_LINE; end; end; end; eventos_gradius3; video_sync; end; end; //Main CPU function gradius3_getword(direccion:dword):word; begin case direccion of 0..$3ffff:gradius3_getword:=rom[direccion shr 1]; $040000..$043fff:gradius3_getword:=ram[(direccion and $3fff) shr 1]; $080000..$080fff:gradius3_getword:=buffer_paleta[(direccion and $fff) shr 1]; $0c8000:gradius3_getword:=marcade.in0; //system $0c8002:gradius3_getword:=marcade.in1; //p1 $0c8004:gradius3_getword:=marcade.in2; //p2 $0c8006:gradius3_getword:=marcade.dswc; //dsw3 $0d0000:gradius3_getword:=marcade.dswa; //dsw1 $0d0002:gradius3_getword:=marcade.dswb; //dsw2 $100000..$103fff:gradius3_getword:=ram_share[(direccion and $3fff) shr 1]; $14c000..$153fff:gradius3_getword:=k052109_0.read((direccion-$14c000) shr 1); $180000..$19ffff:gradius3_getword:=(ram_gfx[(direccion and $1ffff) shr 1] shr 8)+((ram_gfx[(direccion and $1ffff) shr 1] and $ff) shl 8); end; end; procedure gradius3_putword(direccion:dword;valor:word); procedure cambiar_color_gradius3(pos,valor:word); var color:tcolor; begin color.r:=pal5bit(valor shr 10); color.g:=pal5bit(valor shr 5); color.b:=pal5bit(valor); set_pal_color_alpha(color,pos); k052109_0.clean_video_buffer; end; begin case direccion of 0..$3ffff:; //ROM $40000..$43fff:ram[(direccion and $3fff) shr 1]:=valor; $80000..$80fff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color_gradius3((direccion and $fff) shr 1,valor); end; $c0000:begin valor:=valor shr 8; priority:=(valor and $4)<>0; if (valor and $8)<>0 then m68000_1.change_halt(CLEAR_LINE) else m68000_1.change_halt(ASSERT_LINE); irqA_mask:=(valor and $20)<>0; end; $d8000:if (irqB_mask and 4)<>0 then m68000_1.irq[4]:=HOLD_LINE; $e0000:; //wd $e8000:sound_latch:=valor shr 8; $f0000:z80_0.change_irq(HOLD_LINE); $100000..$103fff:ram_share[(direccion and $3fff) shr 1]:=valor; $14c000..$153fff:begin direccion:=(direccion-$14c000) shr 1; if not(m68000_0.write_8bits_lo_dir) then k052109_0.write(direccion,valor); if m68000_0.write_8bits_lo_dir then k052109_0.write(direccion,valor shr 8); end; $180000..$19ffff:if ram_gfx[(direccion and $1ffff) shr 1]<>(((valor and $ff) shl 8)+(valor shr 8)) then begin ram_gfx[(direccion and $1ffff) shr 1]:=((valor and $ff) shl 8)+(valor shr 8); k052109_0.recalc_chars(((direccion and $1ffff) shr 1) div 16); end; end; end; //Sub CPU function gradius3_getword_sub(direccion:dword):word; begin case direccion of 0..$fffff:gradius3_getword_sub:=rom_sub[direccion shr 1]; $100000..$103fff:gradius3_getword_sub:=ram_sub[(direccion and $3fff) shr 1]; $200000..$203fff:gradius3_getword_sub:=ram_share[(direccion and $3fff) shr 1]; $24c000..$253fff:gradius3_getword_sub:=k052109_0.read((direccion-$24c000) shr 1); $280000..$29ffff:gradius3_getword_sub:=(ram_gfx[(direccion and $1ffff) shr 1] shr 8)+((ram_gfx[(direccion and $1ffff) shr 1] and $ff) shl 8); $2c0000..$2c000f:gradius3_getword_sub:=k051960_0.k051937_read((direccion and $f) shr 1); $2c0800..$2c0fff:gradius3_getword_sub:=k051960_0.read((direccion and $7ff) shr 1); $400000..$5fffff:gradius3_getword_sub:=(sprite_rom[(direccion and $1fffff)+1] shl 8)+sprite_rom[direccion and $1fffff]; end; end; procedure gradius3_putword_sub(direccion:dword;valor:word); begin case direccion of 0..$fffff:; //ROM $100000..$103fff:ram_sub[(direccion and $3fff) shr 1]:=valor; $140000:irqB_mask:=(valor shr 8) and $7; $200000..$203fff:ram_share[(direccion and $3fff) shr 1]:=valor; $24c000..$253fff:begin direccion:=(direccion-$24c000) shr 1; if not(m68000_1.write_8bits_lo_dir) then k052109_0.write(direccion,valor); if m68000_1.write_8bits_lo_dir then k052109_0.write(direccion,valor shr 8); end; $280000..$29ffff:if ram_gfx[(direccion and $1ffff) shr 1]<>(((valor and $ff) shl 8)+(valor shr 8)) then begin ram_gfx[(direccion and $1ffff) shr 1]:=((valor and $ff) shl 8)+(valor shr 8); k052109_0.recalc_chars(((direccion and $1ffff) shr 1) div 16); end; $2c0000..$2c000f:k051960_0.k051937_write((direccion and $f) shr 1,valor and $ff); $2c0800..$2c0fff:k051960_0.write((direccion and $7ff) shr 1,valor and $ff); end; end; //Audio CPU function gradius3_snd_getbyte(direccion:word):byte; begin case direccion of 0..$efff,$f800..$ffff:gradius3_snd_getbyte:=mem_snd[direccion]; $f010:gradius3_snd_getbyte:=sound_latch; $f020..$f02d:gradius3_snd_getbyte:=k007232_0.read(direccion and $f); $f031:gradius3_snd_getbyte:=ym2151_0.status; end; end; procedure gradius3_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$efff:; //ROM $f000:k007232_0.set_bank(valor and 3,(valor shr 2) and 3); $f020..$f02d:k007232_0.write(direccion and $f,valor); $f030:ym2151_0.reg(valor); $f031:ym2151_0.write(valor); $f800..$ffff:mem_snd[direccion]:=valor; end; end; procedure gradius3_sound_update; begin ym2151_0.update; k007232_0.update; end; //Main procedure reset_gradius3; begin m68000_0.reset; m68000_1.reset; m68000_1.change_halt(ASSERT_LINE); z80_0.reset; k052109_0.reset; ym2151_0.reset; k051960_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; sound_latch:=0; irqA_mask:=false; irqB_mask:=0; end; procedure cerrar_gradius3; begin if k007232_rom<>nil then freemem(k007232_rom); if sprite_rom<>nil then freemem(sprite_rom); k007232_rom:=nil; sprite_rom:=nil; end; function iniciar_gradius3:boolean; begin llamadas_maquina.close:=cerrar_gradius3; llamadas_maquina.reset:=reset_gradius3; llamadas_maquina.bucle_general:=gradius3_principal; iniciar_gradius3:=false; //Pantallas para el K052109 screen_init(1,512,256,true); screen_init(2,512,256,true); screen_mod_scroll(2,512,512,511,256,256,255); screen_init(3,512,256,true); screen_mod_scroll(3,512,512,511,256,256,255); screen_init(4,1024,1024,false,true); iniciar_video(320,224,true); iniciar_audio(true); //cargar roms if not(roms_load16w(@rom,gradius3_rom)) then exit; if not(roms_load16w(@rom_sub,gradius3_rom_sub)) then exit; //cargar sonido if not(roms_load(@mem_snd,gradius3_sound)) then exit; //Main CPU m68000_0:=cpu_m68000.create(10000000,256); m68000_0.change_ram16_calls(gradius3_getword,gradius3_putword); m68000_1:=cpu_m68000.create(10000000,256); m68000_1.change_ram16_calls(gradius3_getword_sub,gradius3_putword_sub); //Sound CPU z80_0:=cpu_z80.create(3579545,256); z80_0.change_ram_calls(gradius3_snd_getbyte,gradius3_snd_putbyte); z80_0.init_sound(gradius3_sound_update); //Sound Chips ym2151_0:=ym2151_chip.create(3579545); getmem(k007232_rom,$80000); if not(roms_load(k007232_rom,gradius3_k007232)) then exit; k007232_0:=k007232_chip.create(3579545,k007232_rom,$80000,0.20,gradius3_k007232_cb,true); //Iniciar video k052109_0:=k052109_chip.create(1,2,3,0,gradius3_cb,pbyte(@ram_gfx[0]),$20000); getmem(sprite_rom,$200000); if not(roms_load32b(sprite_rom,gradius3_sprites_1)) then exit; if not(roms_load32b_b(sprite_rom,gradius3_sprites_2)) then exit; k051960_0:=k051960_chip.create(4,1,sprite_rom,$200000,gradius3_sprite_cb,1); layer_colorbase[0]:=0; layer_colorbase[1]:=32; layer_colorbase[2]:=48; sprite_colorbase:=16; //DIP marcade.dswa:=$ff; marcade.dswa_val:=@gradius3_dip_a; marcade.dswb:=$5a; marcade.dswb_val:=@gradius3_dip_b; marcade.dswc:=$ff; marcade.dswc_val:=@gradius3_dip_c; //final reset_gradius3; iniciar_gradius3:=true; end; end.
unit uconvert; {$MODE Delphi} interface uses SysUtils, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms, MPHexEditor; type TdlgConvert = class(TForm) Button1: TButton; Button2: TButton; Label1: TLabel; cbFrom: TComboBox; Label2: TLabel; cbTo: TComboBox; procedure cbFromChange(Sender: TObject); end; var dlgConvert: TdlgConvert; // select a from-to translation function SelectConvertTranslation(var AFrom, ATo: TMPHTranslationKind): Boolean; implementation {$R *.lfm} // select a from-to translation function SelectConvertTranslation(var AFrom, ATo: TMPHTranslationKind): Boolean; procedure FillCombo(CBox: TComboBox; const Translation: TMPHTranslationKind); var LEnumTrans: TMPHTranslationKind; begin with CBox.Items do begin Clear; for LEnumTrans := Low(TMPHTranslationKind) to High(TMPHTranslationKind) do AddObject(MPHTranslationDesc[LEnumTrans],Pointer(LEnumTrans)); CBox.ItemIndex := IndexOfObject(Pointer(Translation)); end; end; begin with TdlgConvert.Create(Application) do try FillCombo(cbFrom, AFrom); FillCombo(cbTo, ATo); Result := ShowModal = mrOK; if Result then begin AFrom := TMPHTranslationKind(cbFrom.Items.Objects[cbFrom.ItemIndex]); ATo := TMPHTranslationKind(cbTo.Items.Objects[cbTo.ItemIndex]); end; finally Free; end; end; procedure TdlgConvert.cbFromChange(Sender: TObject); begin // check item indices Button1.Enabled := cbTo.ItemIndex <> cbFrom.ItemIndex end; end.
unit D_TxSrch; {$Include l3Define.inc} interface {$IFDEF ARCHI} {$INCLUDE ArchiDefine.inc} {$ELSE} {$DEFINE NotArchiProject} {$ENDIF ARCHI} uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, ImgList, Menus, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, vtDialogs, vtCtrls, vtForm, vtSpeedButton, DT_Const, DT_Types, D_TxSrch_Types, evTypes, evEditorWindow, evCustomEditor, evSearch, evIntf, evInternalInterfaces, {$IfDef evNeedDisp} evDisp, {$EndIf evNeedDisp} nevBase, nevTools, nevNavigation, {$IFNDEF NotArchiProject} arSearch, SrchWin, {$ENDIF} l3Types, l3Interfaces, l3InterfacedComponent, TB97Ctls, tb97GraphicControl, BottomBtnDlg ; type TDialogMode = (sdmList, sdmEditor); TTextSearchRec = record Operation : Byte; (*0 = none, 1 = Find, 2 = Replace*) Searcher : TevBaseSearcher; Replacer : TevBaseReplacer; SFlags : TevSearchOptionSet; end;{TTextSearchRec} TTextSearchDlg = class(TvtForm, InevConfirm) ScopeGroup: TRadioGroup; OriginGroup: TRadioGroup; OptionGroupBox: TGroupBox; cbCaseSens: TCheckBox; cbWordOnly: TCheckBox; STextComboBox: TvtComboBox; RTextComboBox: TvtComboBox; Panel12: TPanel; Label1: TLabel; Label2: TLabel; cbNormalize: TCheckBox; sbSrchSpecType: TvtSpeedButton; sbReplaceSpecType: TvtSpeedButton; cbRegular: TCheckBox; cbWholePara: TCheckBox; cbAnyTail: TCheckBox; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; mnuRegular: TPopupMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; N6: TMenuItem; N7: TMenuItem; N8: TMenuItem; N9: TMenuItem; mnuSpecials: TPopupMenu; N15: TMenuItem; N16: TMenuItem; N17: TMenuItem; N18: TMenuItem; N19: TMenuItem; N20: TMenuItem; N21: TMenuItem; N22: TMenuItem; N10: TMenuItem; N11: TMenuItem; N12: TMenuItem; N13: TMenuItem; N14: TMenuItem; N23: TMenuItem; btnSymbols: TvtSpeedButton; btnSymbolsR: TvtSpeedButton; mnuSymbolsR: TPopupMenu; N24: TMenuItem; N25: TMenuItem; N26: TMenuItem; N27: TMenuItem; N28: TMenuItem; N29: TMenuItem; N30: TMenuItem; lblOptionsDisp: TLabel; btnCancel: TButton; btnFind: TButton; btnReplaceAll: TButton; btnReplace: TButton; btnMore: TBitBtn; ilOpenClose: TImageList; N31: TMenuItem; N32: TMenuItem; procedure sbSrchSpecTypeClick(Sender: TObject); procedure STextComboBoxDropDown(Sender: TObject); procedure cbRegularClick(Sender: TObject); procedure cbCaseSensClick(Sender: TObject); procedure cbAnyTailClick(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure cbNormalizeClick(Sender: TObject); procedure cbWordOnlyClick(Sender: TObject); procedure mnuSymbolsClick(Sender: TObject); procedure mnuRegularsClick(Sender: TObject); procedure btnSymbolsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnMoreClick(Sender: TObject); procedure FormHide(Sender: TObject); procedure btnFindClick(Sender: TObject); procedure InputsChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnReplaceClick(Sender: TObject); procedure btnReplaceAllClick(Sender: TObject); procedure cbWholeParaClick(Sender: TObject); procedure ScopeGroupClick(Sender: TObject); procedure STextComboBoxChange(Sender: TObject); private FSymbolsMenu: TPopupMenu; FDialogMode: TDialogMode; FInputIsParsed: Boolean; FInReplaceLoop: Boolean; FReplaceResult: Integer; f_OldSelectNotify: TNotifyEvent; f_OwnerToClose: HWND; fIsOptionVisible : boolean; function ConvertTextWildcards(var aStr: string; out NeedRegexp: Boolean; ForReplacer: Boolean = False): Boolean; procedure DisplayOptions; procedure UpdateFindFlag(aFlag: Byte); procedure ParseInput; protected FEditor : TevCustomEditor; FSrchMode : Byte; SType : TtsSrchType; RType : TtsSrchType; fReplaceAllowTypes : TtsSrchTypeSet; LastSrchRec : TTextSearchRec; SubID : TSubID; fHLinkID : Integer; {$IFNDEF NotArchiProject} f_SrchWin : TSearchWin; {$ENDIF} fTextReplacer : TevTextReplacer; fTextSearcher : TevBMTextSearcher; fStyleSearcher : TevStyleSearcher; fStyleReplacer : TevStyleReplacer; fNormalWordSearcher : TevMorphologySearcher; fRegularExpressionSearcher : TevRegExpMultipartSearcher; {$IFNDEF NotArchiProject} fHLinkSearcher : TarHyperlinkSearcher; fHLinkReplacer : TarHyperLinkReplacer; {$ENDIF} fSubReplacer : TevSubReplacer; fRegExpReplacer : TevRegExpReplacer; {$IFNDEF NotArchiProject} function HLinkReplacerHyperlinkReplace(aSender: TObject; const aHLink: IevHyperlink): Boolean; function HLinkSearcherHyperlinkSearch(aSender: TObject; const aHLink: IevHyperlink): Boolean; {$ENDIF} function SubReplacerGetSubHandle(Sender : TObject; const aBlock : InevRange): Integer; function SubReplacerReplaceConfirm(Sender : TObject; const aBlock : InevRange): Shortint; {$IFNDEF NotArchiProject} procedure evntFinishReplace(Sender: TObject; ReplaceCount: Longint); {$ENDIF} procedure SetIsOptionVisible(aValue : boolean); procedure SetSrchMode(Value : Byte); function DropListGetItemImageIndex(Sender : TObject; Index : Longint) : Integer; function GetItemImageIndex(aST : TtsSrchType) : Integer; procedure LoadList(aListID : Byte; aSrchType : TtsSrchType); procedure SaveList(aListID : Byte; aSrchType : TtsSrchType); procedure ShowNotFoundMsg; procedure ShowBadRegExpMsg; procedure Find; procedure SetSrchSpecType(SR : Byte; ST : TtsSrchType); procedure DoSwitchPages; {$IFNDEF NotArchiProject} function GetItemFromList(anIndex: Longint): Il3CString; procedure FindInList(StartIndex: Longint); {$ENDIF} procedure FindEntry; function DefaultCloseAction: TCloseAction; override; function CheckStamp(const aGUID: TGUID): Boolean; {-} class function CheckDialog: TTextSearchDlg; {-} public property SrchMode : Byte Read FSrchMode Write SetSrchMode; class function Execute(aMode : TSearchDialogInitMode; aSrchType, aReplType : TtsSrchType; aCurEditor : TevCustomEditor; aReplaceAllowTypes : TtsSrchTypeSet): Boolean; overload; class function Execute(aMode : TSearchDialogInitMode; CurEditor : TevCustomEditor; aReplaceAllowTypes : TtsSrchTypeSet): Boolean; overload; {$IFNDEF NotArchiProject} class function Execute(aSrchWin: TSearchWin) : Boolean; overload; class procedure FindNext(aSrchWin: TSearchWin); overload; procedure ReplaceReferences(aCurEditor : TevCustomEditor; aSearchHLDocID: TDocID; aReplaceHLDocID: TDocID); {$ENDIF} class procedure FindNext(CurEditor : TevCustomEditor); overload; class procedure FindStyle(aCurEditor : TevCustomEditor; aStyleHandle : Integer); constructor Create(AOwner: TComponent); override; {-} procedure Cleanup; override; {-} function Get_Progress: InevProgress; {-} function ReplaceConfirm(const aBlock : InevRange; aAlienReplaceConfirm : TevReplaceConfirmEvent): ShortInt; {* - запрос на замену. Возвращаемое значение см. TevReplaceConfirmEvent. } function DoReplaceConfirm(Sender : TObject; const aBlock : InevRange): ShortInt; {* - запрос на замену. Возвращаемое значение см. TevReplaceConfirmEvent. } function Get_View: InevView; {-} function DeleteFoundRgn: Bool; {-} procedure ReplUpdate; {-} procedure InevConfirm.Update = ReplUpdate; {-} class procedure HideFindContext; class procedure SwitchActiveEditor(aNewEditor: TevCustomEditor); {-} class procedure ClientFormClosed(aForm: TCustomForm); class function IsInReplaceLoop: Boolean; {$IFDEF InsiderTest} class procedure ClearFindWindow; {$ENDIF InsiderTest} property IsOptionVisible : boolean read fIsOptionVisible write SetIsOptionVisible; end; var g_TextSearchDlg : TTextSearchDlg; implementation uses StrUtils, l3String, l3Except, {$IFNDEF NotArchiProject} EditWin, DocIntf, {$ENDIF} l3Base, l3DatLst, l3Const, evConst, evEditor, evExcept, {$IFNDEF NotArchiProject} l3LongintList, evListBlock, {$EndIf NotArchiProject} D_TxSrch_Res, D_TxSrch_Intf, l3RegEx, vtlister, {$IFNDEF NotArchiProject} daTypes, DT_Doc, DT_Hyper, DT_Err, dt_LinkServ, {$EndIf NotArchiProject} evFacadeSub, l3IniFile, IniShop, l3Chars, afwNavigation {$IFDEF InsiderTest} , l3BatchService, l3ModalService {$ENDIF InsiderTest} ; resourcestring SInvalidSpecialSymbol = 'Невозможно использовать такой спецсимвол: '; SBadRegExp = 'Регулярное выражение некорректно!'; const MaxNumofItemInHistory = 20; // количество поддерживаемых спецсимволов MaxSS = 10; // спецсимволы (значок после крышки ^) spsTab = 't'; spsAnySymbol = '?'; spsAnyDigit = '#'; spsAnyAlpha = '$'; spsReturn = 'l'; spsDash = '='; spsMDash = '+'; spsNBSpace = 's'; spsLid = '^'; spsParagraph = 'p'; SpecialSymbols : array[1..MaxSS] of Char = (spsTab, spsAnySymbol, spsAnyDigit, spsAnyAlpha, spsReturn, spsDash, spsMDash, spsNBSpace, spsLid, spsParagraph); {$R *.DFM} constructor TTextSearchDlg.Create(AOwner: TComponent); begin inherited Create(AOwner); fTextReplacer := TevTextReplacer.Create(Self); fTextSearcher := TevBMTextSearcher.Create(Self); fStyleSearcher := TevStyleSearcher.Create(Self); fStyleReplacer := TevStyleReplacer.Create(Self); fNormalWordSearcher := TevMorphologySearcher.Create(Self); fRegularExpressionSearcher := TevRegExpMultipartSearcher.Create(Self); fRegExpReplacer := TevRegExpReplacer.Create(Self); {$IFNDEF NotArchiProject} fHLinkSearcher := TarHyperlinkSearcher.Create(Self); fHLinkSearcher.OnHyperlinkSearch := HLinkSearcherHyperlinkSearch; fHLinkReplacer := TarHyperLinkReplacer.Create(Self); fHLinkReplacer.OnHyperlinkReplace := HLinkReplacerHyperlinkReplace; fHLinkReplacer.OnFinishReplace := evntFinishReplace; {$ENDIF} {$IFNDEF NotArchiProject} fSubReplacer := TarSubReplacer.Create(Self); fSubReplacer.OnFinishReplace := evntFinishReplace; {$ELSE} fSubReplacer := TevSubReplacer.Create(Self); {$ENDIF} fSubReplacer.OnGetSubHandle := SubReplacerGetSubHandle; fSubReplacer.OnReplaceConfirm := SubReplacerReplaceConfirm; LoadList(1, srtText); LoadList(2, srtText); UserConfig.Section := TextSearchSectName; ScopeGroup .ItemIndex := UserConfig.ReadParamIntDef ('ScopeGroup', 0); OriginGroup .ItemIndex := UserConfig.ReadParamIntDef ('OriginGroup', 0); cbCaseSens .Checked := UserConfig.ReadParamBoolDef('cbCaseSens' , False); cbWordOnly .Checked := UserConfig.ReadParamBoolDef('cbWordOnly' , False); cbNormalize .Checked := UserConfig.ReadParamBoolDef('cbNormalize' , False); cbRegular .Checked := UserConfig.ReadParamBoolDef('cbRegular' , False); cbWholePara .Checked := UserConfig.ReadParamBoolDef('cbWholePara' , False); cbAnyTail .Checked := UserConfig.ReadParamBoolDef('cbAnyTail' , False); sbSrchSpecType.Images := SrchRes.CommonImageList; sbReplaceSpecType.Images := SrchRes.CommonImageList; sbSrchSpecType.ImageIndex := GetItemImageIndex(srtText); sbReplaceSpecType.ImageIndex := GetItemImageIndex(srtText); LastSrchRec.Operation := 0; LastSrchRec.Searcher := fTextSearcher; LastSrchRec.Replacer := fTextReplacer; IsOptionVisible := true; DisplayOptions; FInReplaceLoop := False; end; procedure TTextSearchDlg.Cleanup; begin if (g_TextSearchDlg = Self) then begin g_TextSearchDlg := nil; if not (csDestroying in Application.ComponentState) then l3System.Stack2Log('Убили TTextSearchDlg!'); end; SaveList(1,SType); SaveList(2,RType); UserConfig.Section := TextSearchSectName; UserConfig.WriteParamInt('ScopeGroup' , ScopeGroup .ItemIndex); UserConfig.WriteParamInt('OriginGroup', OriginGroup .ItemIndex); UserConfig.WriteParamBool('cbCaseSens' , cbCaseSens .Checked); UserConfig.WriteParamBool('cbWordOnly' , cbWordOnly .Checked); UserConfig.WriteParamBool('cbNormalize' , cbNormalize .Checked); UserConfig.WriteParamBool('cbRegular' , cbRegular .Checked); UserConfig.WriteParamBool('cbWholePara' , cbWholePara .Checked); UserConfig.WriteParamBool('cbAnyTail' , cbAnyTail .Checked); inherited; end; procedure TTextSearchDlg.LoadList(aListID : Byte; aSrchType : TtsSrchType); begin if UserConfig <> nil then begin case aListID of 1 : begin STextComboBox.Items.Clear; case aSrchType of srtText : UserConfig.Section := FindSectName; {$IFNDEF NotArchiProject} srtHLink : UserConfig.Section := FindSectName+'_HLink'; {$ENDIF} else //srtStyle, srtSub, Exit; end; UserConfig.ReadParamList(FindSectName, STextComboBox.Items); end; 2 : begin RTextComboBox.Items.Clear; case aSrchType of srtText : UserConfig.Section := ReplaceSectName; {$IFNDEF NotArchiProject} srtHLink : UserConfig.Section := ReplaceSectName+'_HLink'; {$ENDIF} else //srtStyle, srtSub, Exit; end; UserConfig.ReadParamList(ReplaceSectName, RTextComboBox.Items); end; end; end; end; procedure TTextSearchDlg.SaveList(aListID : Byte; aSrchType : TtsSrchType); begin if UserConfig <> nil then begin case aListID of 1 : begin case aSrchType of srtText : UserConfig.Section := FindSectName; {$IFNDEF NotArchiProject} srtHLink : UserConfig.Section := FindSectName + '_HLink'; {$ENDIF} else //srtStyle, srtSub, Exit; end; UserConfig.WriteParamList(FindSectName, STextComboBox.Items, MaxNumofItemInHistory); end; 2 : begin case aSrchType of srtText : UserConfig.Section := ReplaceSectName; {$IFNDEF NotArchiProject} srtHLink : UserConfig.Section := ReplaceSectName+'_HLink'; {$ENDIF} else //srtStyle, srtSub, Exit; end; UserConfig.WriteParamList(ReplaceSectName, RTextComboBox.Items, MaxNumofItemInHistory); end; end; end; end; function TranslateForAnyTail(const aSrchText : string; AlreadyRegexp: Boolean = False): string; var lStrPos : Integer; lAddLog : Boolean; begin Result := l3DeleteDoubleSpace(Trim(aSrchText)); if not AlreadyRegexp then Result := ConvertStrToRegular(Result); lStrPos := Length(Result); lAddLog := True; while lStrPos > 0 do begin case Result[lStrPos] of '!' : begin System.Delete(Result, lStrPos, 1); lAddLog := False; end; ' ' : begin System.Delete(Result, lStrPos, 1); If not lAddLog then System.Insert('\s+', Result, lStrPos); lAddLog := True; end; else begin if lAddLog then System.Insert('\w*' {'[[:alpha:]]*'}, Result, Succ(lStrPos)); lAddLog := False; end; end; Dec(lStrPos); end; Result := '>' + Result; end; class function TTextSearchDlg.CheckDialog: TTextSearchDlg; {-} begin if (g_TextSearchDlg = nil) then g_TextSearchDlg := Create(Application); Result := g_TextSearchDlg; end; class function TTextSearchDlg.Execute(aMode : TSearchDialogInitMode; aSrchType, aReplType : TtsSrchType; aCurEditor : TevCustomEditor; aReplaceAllowTypes : TtsSrchTypeSet): Boolean; begin with CheckDialog do begin fEditor := aCurEditor; fReplaceAllowTypes := aReplaceAllowTypes; SetSrchSpecType(0, aSrchType); SetSrchSpecType(1, aReplType); Result := Execute(aMode, aCurEditor, aReplaceAllowTypes); end;//CheckDialog end; class function TTextSearchDlg.Execute(aMode : TSearchDialogInitMode; CurEditor : TevCustomEditor; aReplaceAllowTypes : TtsSrchTypeSet): Boolean; var l_Dialog : TTextSearchDlg; lSrchStr : string; begin l_Dialog := CheckDialog; with l_Dialog do begin try fReplaceAllowTypes := aReplaceAllowTypes; if aMode <> sdiSearchOnly then SetSrchSpecType(1, RType); TabSheet2.TabVisible := aMode <> sdiSearchOnly; if aMode = sdiReplace then PageControl1.ActivePageIndex := 1 else PageControl1.ActivePageIndex := 0; PageControl1Change(l_Dialog); except end; fEditor := CurEditor; sbSrchSpecType.Enabled := True; // Вставляет из текста слово на котором курсор стоит with fEditor.Range do if ContainsOneLeaf then lSrchStr := AsString else lSrchStr := ''; if (lSrchStr = '') or (SType <> srtText) then STextComboBox.ItemIndex := 0 else begin STextComboBox.ItemIndex := 0; //STextComboBox.ItemIndex := -1; STextComboBox.Text := lSrchStr; end; if (SrchMode = 1) then begin if LastSrchRec.Replacer <> nil then RTextComboBox.ItemIndex := 0 //RTextComboBox.Text := LastSrchRec.Replacer.DefaultText else RTextComboBox.Text := ''; end; ActiveControl := STextComboBox; STextComboBoxChange(nil); FDialogMode := sdmEditor; Show; Result := True; {$IFDEF InsiderTest} Tl3BatchService.Instance.ExecuteCurrentModalWorker(se_meInLoop); {$ENDIF InsiderTest} end;//with CheckDialog end; {$IFNDEF NotArchiProject} class function TTextSearchDlg.Execute(aSrchWin: TSearchWin) : Boolean; var lSrchStr : string; begin with CheckDialog do begin sbSrchSpecType.Enabled:= False; SetSrchSpecType(0, srtText); f_SrchWin:= aSrchWin; lSrchStr := ''; if (lSrchStr = '') then STextComboBox.Text := LastSrchRec.Searcher.DefaultText else STextComboBox.Text := lSrchStr; ActiveControl := STextComboBox; {=============} TabSheet2.TabVisible := False; FDialogMode := sdmList; Show; Result := True; {$IFDEF InsiderTest} Tl3BatchService.Instance.ExecuteCurrentModalWorker(se_meInLoop); {$ENDIF InsiderTest} end;//with CheckDialog end; {$ENDIF} procedure TTextSearchDlg.DoSwitchPages; begin with PageControl1 do begin RTextComboBox.Visible := ActivePageIndex = 1; sbReplaceSpecType.Visible := ActivePageIndex = 1; btnSymbolsR.Visible := ActivePageIndex = 1; btnReplace.Visible := ActivePageIndex = 1; btnReplaceAll.Visible := ActivePageIndex = 1; Label2.Visible := ActivePageIndex = 1; cbWholePara .Visible := (ActivePageIndex = 1) and (RType = srtStyle); btnFind.Default := ActivePageIndex = 0; btnReplace.Default := ActivePageIndex = 1; end; end; procedure TTextSearchDlg.PageControl1Change(Sender: TObject); begin DoSwitchPages; with PageControl1 do begin fSrchMode := ActivePageIndex; ActiveControl := STextComboBox; end; InputsChange(nil); end; procedure TTextSearchDlg.SetSrchMode(Value : Byte); begin fSrchMode := Value; PageControl1.ActivePageIndex := Value; DoSwitchPages; end; function TTextSearchDlg.DropListGetItemImageIndex(Sender : TObject; Index : Longint) : Integer; begin if Index < 0 then Result := -1 else Result := GetItemImageIndex(TtsSrchType(TvtDStringlister(Sender).Items.DataInt[Index])); end; function TTextSearchDlg.GetItemImageIndex(aST : TtsSrchType) : Integer; begin case aST of srtText : Result := picSrchText; srtStyle : Result := picSrchStyle; srtSub : Result := picSrchAnchor; {$IFNDEF NotArchiProject} srtHLink : Result := picSrchHLink; {$ENDIF} end; end; procedure TTextSearchDlg.sbSrchSpecTypeClick(Sender: TObject); var l_Type : TtsSrchType; l_Res : Longint; lSTRes : TtsSrchType; SR : Byte; begin try if Sender = sbSrchSpecType then STextComboBox.SetFocus else RTextComboBox.SetFocus; except end; with TvtPopupList.Create(TComponent(Sender), TvtDStringLister) do try AdjustCorner := acBottomRight; Lister.Images := SrchRes.CommonImageList; Lister.OnGetItemImageIndex := DropListGetItemImageIndex; with (Lister as TvtDStringLister).Items do begin DataSize := SizeOf(TtsSrchType); for l_Type := Low(TtsSrchType) to High(TtsSrchType) do begin {$IFNDEF NotArchiProject} if (Sender = sbSrchSpecType) and (l_Type = srtSub) then Continue; // поиск по номеру Sub'a в Архивариусе не поддерживается if (Sender = sbReplaceSpecType) and (fReplaceAllowTypes <> []) and not (l_Type in fReplaceAllowTypes) then Continue; //фильтр по допустимым типам поисков {$ENDIF} AddStr(cSrchTypeNames[l_Type], @l_Type); end; end; if Sender = sbSrchSpecType then Lister.Current := Byte(SType) else Lister.Current := Byte(RType); l_Res := Execute; if l_Res < 0 then Exit; lSTRes := TtsSrchType((Lister as TvtDStringLister).Items.DataInt[l_Res]); if Sender = sbReplaceSpecType then SR := 1 else SR := 0; SetSrchSpecType(SR, lSTRes); finally Free; end; InputsChange(nil); end; procedure TTextSearchDlg.SetSrchSpecType(SR : Byte; ST : TtsSrchType); procedure SetSrchOptionEnabled(Value : Boolean); begin cbCaseSens.Enabled := Value; cbWordOnly.Enabled := Value; cbNormalize.Enabled := Value; cbRegular.Enabled := Value; cbAnyTail.Enabled := Value; btnSymbols.Enabled := Value; end; procedure CorrectSTReplace; var lST : TtsSrchType; begin if (fReplaceAllowTypes <> []) and not (ST in fReplaceAllowTypes) then for lST := Low(TtsSrchType) to High(TtsSrchType) do if lST in fReplaceAllowTypes then begin ST := lST; Exit; end; end; begin if SR = 0 then begin if SType = ST then Exit; SaveList(1,SType); //SNeedLoad := True; SType := ST; LoadList(1,SType); SetSrchOptionEnabled(SType = srtText); if (SType = srtText) or (SType = srtSub) {$IFNDEF NotArchiProject} or (SType = srtHLink) {$ENDIF} then begin STextComboBox.Style := csDropDown; STextComboBox.ItemIndex := 0; end else begin STextComboBox.Style := csDropDownList; STextComboBox.ItemIndex := -1; end; {$IFNDEF NotArchiProject} if (SType = srtHLink) then with TDocEditorWindow(GetParentForm(fEditor)) do fHLinkSearcher.CurrentDoc := DocAddr(DocFamily, DocID); {$ENDIF} sbSrchSpecType.ImageIndex := GetItemImageIndex(ST); //sbSrchSpecType.Glyph := GetDocBMP(GetItemImageIndex(ST)); end else {Replace} begin CorrectSTReplace; if RType = ST then Exit; SaveList(2,RType); RType := ST; LoadList(2,RType); cbWholePara.Visible := (RType = srtStyle); btnSymbolsR.Enabled := (RType = srtText); case RType of srtText : begin RTextComboBox.Style := csDropDown; RTextComboBox.ItemIndex := 0; end; srtStyle : begin RTextComboBox.Style := csDropDownList; RTextComboBox.ItemIndex := -1; end; {$IFNDEF NotArchiProject} srtHLink : begin RTextComboBox.Style := csDropDown; RTextComboBox.ItemIndex := 0; with TDocEditorWindow(GetParentForm(fEditor)) do fHLinkReplacer.CurrentDoc := DocAddr(DocFamily, DocID); end; {$ENDIF} srtSub : begin RTextComboBox.Style := csDropDown; RTextComboBox.Text := ''; //SubReplacer.DefaultText; end; end; sbReplaceSpecType.ImageIndex := GetItemImageIndex(ST); end; DisplayOptions; end; procedure TTextSearchDlg.STextComboBoxDropDown(Sender: TObject); begin if ((Sender = STextComboBox) and (SType = srtStyle)) or ((Sender = RTextComboBox) and (RType = srtStyle)) then begin if FEditor = nil then TComboBox(Sender).Items.Clear else TComboBox(Sender).Items.Assign(FEditor.TextPara.Style.Styles.Items); end; end; procedure TTextSearchDlg.ShowNotFoundMsg; begin vtMessageDlg(l3CStr(LastSrchRec.Searcher.NotFoundMessage), mtWarning, [mbOK], 0 {HelpCtx}); end; procedure TTextSearchDlg.Find; begin try (FEditor As TevEditor).Find(LastSrchRec.Searcher, LastSrchRec.Replacer, LastSrchRec.SFlags); except on EevSearchFailed do ShowNotFoundMsg; end;{try..finally} end; class procedure TTextSearchDlg.FindNext(CurEditor : TevCustomEditor); begin with CheckDialog do begin if (LastSrchRec.Operation >= 1) then begin FEditor := CurEditor; Exclude(LastSrchRec.SFlags, ev_soGlobal); Find; end;{LastSrchRec.Operation >= 1} end;//with CheckDialog end; {$IFNDEF NotArchiProject} class procedure TTextSearchDlg.FindNext(aSrchWin: TSearchWin); begin with CheckDialog do begin if (LastSrchRec.Operation >= 1) then begin f_SrchWin:= aSrchWin; Exclude(LastSrchRec.SFlags, ev_soGlobal); FindInList(f_SrchWin.DocList.SrchResultLister.Current+1); end;{LastSrchRec.Operation >= 1} end;//with CheckDialog end; {$ENDIF} class procedure TTextSearchDlg.FindStyle(aCurEditor : TevCustomEditor; aStyleHandle : Integer); begin with CheckDialog do begin fEditor := aCurEditor; fStyleSearcher.Layer := l3NilLong; LastSrchRec.Searcher := fStyleSearcher; LastSrchRec.Operation := 0; LastSrchRec.SFlags := [ev_soFind {, ev_soGlobal, ev_soSelText}]; fStyleSearcher.Handle := aStyleHandle; Find; end;//with CheckDialog end; class procedure TTextSearchDlg.HideFindContext; {-} begin if (g_TextSearchDlg <> nil) AND g_TextSearchDlg.Showing then g_TextSearchDlg.Close; end; {$IFNDEF NotArchiProject} procedure TTextSearchDlg.ReplaceReferences(aCurEditor : TevCustomEditor; aSearchHLDocID: TDocID; aReplaceHLDocID: TDocID); begin fEditor := aCurEditor; fHLinkSearcher.SearchAddr := DestHLinkRec(aSearchHLDocID, -1); LastSrchRec.Searcher := fHLinkSearcher; fHLinkReplacer.ReplaceAddr := DestHLinkRec(aReplaceHLDocID, -1); LastSrchRec.Replacer := fHLinkReplacer; LastSrchRec.SFlags := [ev_soGlobal, ev_soReplace, ev_soReplaceAll]; LastSrchRec.Searcher.Options := LastSrchRec.SFlags; LastSrchRec.Replacer.Options := LastSrchRec.SFlags; try (FEditor As TevEditor).Find(LastSrchRec.Searcher, LastSrchRec.Replacer, LastSrchRec.SFlags); except on EevSearchFailed do; end; end; {$ENDIF} procedure TTextSearchDlg.cbRegularClick(Sender: TObject); begin if cbRegular.Checked then begin cbNormalize.Checked := False; cbWordOnly.Checked := False; cbAnyTail.Checked := False; FSymbolsMenu := mnuRegular; end else FSymbolsMenu := mnuSpecials; InputsChange(nil); DisplayOptions; end; procedure TTextSearchDlg.cbWordOnlyClick(Sender: TObject); begin if cbWordOnly.Checked then begin cbNormalize.Checked := False; cbAnyTail.Checked := False; cbRegular.Checked := False; end; InputsChange(nil); DisplayOptions; end; procedure TTextSearchDlg.cbNormalizeClick(Sender: TObject); begin if cbNormalize.Checked then begin cbCaseSens.Checked := False; cbWordOnly.Checked := False; cbAnyTail.Checked := False; cbRegular.Checked := False; end; InputsChange(nil); DisplayOptions; end; procedure TTextSearchDlg.cbAnyTailClick(Sender: TObject); begin if cbAnyTail.Checked then begin cbNormalize.Checked := False; cbWordOnly.Checked := False; cbRegular.Checked := False; end; InputsChange(nil); DisplayOptions; end; procedure TTextSearchDlg.cbCaseSensClick(Sender: TObject); begin if cbCaseSens.Checked then cbNormalize.Checked := False; InputsChange(nil); DisplayOptions; end; {$IFNDEF NotArchiProject} procedure TTextSearchDlg.evntFinishReplace(Sender: TObject; ReplaceCount: Longint); var Frm : TCustomForm; begin Frm := GetParentForm(FEditor); If Frm is TDocEditorWindow then TDocEditorWindow(Frm).evntFinishReplace(Sender, ReplaceCount); end; {$ENDIF} function TTextSearchDlg.SubReplacerReplaceConfirm(Sender : TObject; const aBlock : InevRange): Shortint; var l_Form : TCustomForm; l_Search: ISearchDlgOperations; begin Result := 0; l_Form := GetParentForm(FEditor); if Supports(l_Form, ISearchDlgOperations, l_Search) then try Result := l_Search.SubReplaceFunc(aBlock, LastSrchRec.Replacer.Text, True{aWithConfirm}); finally l_Search := nil; end; end; function TTextSearchDlg.SubReplacerGetSubHandle(Sender : TObject; const aBlock : InevRange): Integer; var l_Form : TCustomForm; l_Search : ISearchDlgOperations; begin Result := 0; //Шуре id не давать!! Ставлю сам if (ev_soConfirm in LastSrchRec.Replacer.Options) then Exit; l_Form := GetParentForm(FEditor); if Supports(l_Form, ISearchDlgOperations, l_Search) then try l_Search.SubReplaceFunc(aBlock, LastSrchRec.Replacer.Text, False{aWithConfirm}); finally l_Search := nil; end; end; {$IFNDEF NotArchiProject} function TTextSearchDlg.HLinkSearcherHyperlinkSearch(aSender: TObject; const aHLink: IevHyperlink): Boolean; var lCurAddr : TevAddress; I : Integer; lWrongHlinkList : Tl3LongintList; begin Result := False; if (aHLink.AddressList.Count = 0) then Exit; if (aSender as TarHyperLinkSearcher).SearchAddr.Doc = Pred(MaxInt) //поиск "битых" ссылок then begin lWrongHlinkList := TDocEditorWindow(GetParentForm(fEditor)).CurDocument.GetWrongHlinkList; If (lWrongHlinkList = nil) or (lWrongHlinkList.Count = 0) then Exit; for I := 0 to Pred(lWrongHlinkList.Count) do If aHLink.ID = lWrongHlinkList.Items[I] then begin Result := True; Exit; end; end else if (aSender as TarHyperLinkSearcher).SearchAddr.Doc = MaxInt //поиск по HLinkID then Result := aHLink.ID = (aSender as TarHyperLinkSearcher).SearchAddr.Sub else for I := 0 to Pred(aHLink.AddressList.Count) do begin lCurAddr := aHLink.AddressList[I]; If (((aSender as TarHyperLinkSearcher).SearchAddr.Doc = lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID) or ((aSender as TarHyperLinkSearcher).SearchAddr.Doc < 0)) and (((aSender as TarHyperLinkSearcher).SearchAddr.Sub = lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID) or ((aSender as TarHyperLinkSearcher).SearchAddr.Sub < 0)) then begin Result := True; Break; end; end; end; function TTextSearchDlg.HLinkReplacerHyperlinkReplace(aSender: TObject; const aHLink: IevHyperlink): Boolean; var lCurAddr : TevAddress; lSrchAddr : TDestHLinkRec; lNewAddr : TevAddress; //SL : Tl3StringDataList; I : Integer; lDocID : TDocID; lDocFamily : TdaFamilyID; lSaveReadOnly : boolean; begin Result := False; with TDocEditorWindow(GetParentForm(fEditor)) do begin lDocID := DocID; lDocFamily := DocFamily; end; lSaveReadOnly := fEditor.ReadOnly; try fEditor.ReadOnly := False; if Not aHLink.Exists or (aHLink.AddressList.Count = 0) or not (LastSrchRec.Searcher is TarHyperLinkSearcher) or ((aSender as TarHyperLinkReplacer).ReplaceAddr.Doc = MaxInt) then //поиск по HLinkID begin if ((aSender as TarHyperLinkReplacer).ReplaceAddr.Doc < 0) then lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID := lDocID else lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID := (aSender as TarHyperLinkReplacer).ReplaceAddr.Doc; if ((aSender as TarHyperLinkReplacer).ReplaceAddr.Sub < 0) then lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID := 0 else lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID := (aSender as TarHyperLinkReplacer).ReplaceAddr.Sub; if not LinkServer(lDocFamily).SubTbl.CheckHyperLink(lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID, lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID) {Проверка на валидность lNewAddr} then begin vtMessageDlg(l3Fmt(sidNotValidHyperAddress,[lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID, lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID]), mtError); Exit; end; if not aHLink.Exists then aHLink.Insert; aHLink.AddressList.Add(lNewAddr); end else //поиск по адресу begin I := 0; While I < aHLink.AddressList.Count do begin lCurAddr := aHLink.AddressList[I]; lSrchAddr := (LastSrchRec.Searcher as TarHyperLinkSearcher).SearchAddr; if ((lSrchAddr.Doc = lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID) or (lSrchAddr.Doc < 0)) and ((lSrchAddr.Sub = lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID) or (lSrchAddr.Sub < 0)) then begin if (lSrchAddr.Doc < 0) then lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID := lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID else lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID := (aSender as TarHyperLinkReplacer).ReplaceAddr.Doc; if (lSrchAddr.Sub < 0) then lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID := lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID else lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID := (aSender as TarHyperLinkReplacer).ReplaceAddr.Sub; if not ((aSender as TarHyperLinkReplacer).AbsentDoc or LinkServer(lDocFamily).SubTbl.CheckHyperLink(lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID, lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID)) then {Проверка на валидность lNewAddr} begin vtMessageDlg(l3Fmt(sidNotValidHyperAddress,[lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID, lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID]), mtError); Inc(I); Continue; end; try aHLink.AddressList[I] := lNewAddr; except on E : El3DuplicateItem do begin if vtMessageDlg(l3Fmt(sidDoubletHyperAddress +^M+ sidQstDelDoublet,[lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID, lNewAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID]), mtConfirmation, [mbYes, mbNo]) = mrYes then aHLink.AddressList.Delete(lCurAddr); end; on E : Exception do vtMessageDlg(E); end; end; Inc(I); end; end; finally fEditor.ReadOnly := lSaveReadOnly; end; end; procedure TTextSearchDlg.FindInList(StartIndex: Longint); var l_Pos: Longint; begin try l_Pos:= evSearchList(GetItemFromList, f_SrchWin.DocList.SrchResultLister.Total, LastSrchRec.Searcher, StartIndex + 1); f_SrchWin.DocList.SrchResultLister.Current:= l_Pos - 1; except on EevSearchFailed do ; end; end; function TTextSearchDlg.GetItemFromList(anIndex: Longint): Il3CString; begin f_SrchWin.DocList.GetStrItem(anIndex, Result); end; {$ENDIF} procedure TTextSearchDlg.mnuSymbolsClick(Sender: TObject); var lItem: Integer; S,L: Integer; Combo: TvtComboBox; begin if TMenuItem(Sender).GetParentMenu = mnuSymbolsR then Combo := RTextComboBox else Combo := STextComboBox; S := Combo.SelStart; L := Combo.SelLength; ActiveControl := Combo; Combo.SelStart := S; Combo.SelLength := L; lItem := TMenuItem(Sender).Tag; if lItem in [1..MaxSS] then Combo.SelText := '^'+SpecialSymbols[lItem]; end; procedure TTextSearchDlg.mnuRegularsClick(Sender: TObject); var lItem: Integer; S,L: Integer; begin S := STextComboBox.SelStart; L := STextComboBox.SelLength; ActiveControl := STextComboBox; STextComboBox.SelStart := S; STextComboBox.SelLength := L; lItem := TMenuItem(Sender).Tag; case lItem of 1: STextComboBox.SelText := '.'; 2: STextComboBox.SelText := '?'; 3: STextComboBox.SelText := '[-]'; 4: STextComboBox.SelText := '[^-]'; 5: STextComboBox.SelText := '^'; 6: STextComboBox.SelText := '$'; 7: STextComboBox.SelText := '()'; 8: STextComboBox.SelText := '+'; 9: STextComboBox.SelText := '*'; 10: STextComboBox.SelText := '\t'; 11: STextComboBox.SelText := '\l'; 12: STextComboBox.SelText := '\w'; 13: STextComboBox.SelText := '\_'; 14: STextComboBox.SelText := '\d'; 15: STextComboBox.SelText := '>'; 16: STextComboBox.SelText := '<'; end; end; procedure TTextSearchDlg.btnSymbolsClick(Sender: TObject); var P: TPoint; begin P.X := 0; P.Y := btnSymbols.Top + btnSymbols.Height; P := btnSymbols.ClientToScreen(P); if Sender = btnSymbolsR then mnuSymbolsR.Popup(P.X, P.Y) else FSymbolsMenu.Popup(P.X, P.Y); end; function TTextSearchDlg.ConvertTextWildcards(var aStr: string; out NeedRegexp: Boolean; ForReplacer: Boolean = False): Boolean; var lIdx: Integer; SRegexp: string; procedure ReplaceSubstr(var AStr: string; Start, Length: Integer; Substr: string); begin if NeedRegexp then begin SRegexp := SRegexp + ConvertStrToRegular(System.Copy(AStr, 1, Start-1))+Substr; Delete(AStr, 1, Start+Length-1); lIdx := 1; end else begin Delete(AStr, Start, Length); Insert(Substr, AStr, Start); Inc(lIdx, System.Length(Substr)); end; end; begin Result := False; NeedRegexp := False; SRegexp := ''; lIdx := Pos('^', aStr); while lIdx > 0 do begin if lIdx = Length(aStr) then //последний символ "крышка" так ее и оставим Break else case aStr[lIdx+1] of spsTab: ReplaceSubstr(aStr, lIdx, 2, cc_Tab); spsAnySymbol: if ForReplacer then Exit else begin NeedRegExp := True; ReplaceSubstr(aStr, lIdx, 2, '.'); end; spsAnyDigit: if ForReplacer then Exit else begin NeedRegExp := True; ReplaceSubstr(aStr, lIdx, 2, '\d'); end; spsAnyAlpha: if ForReplacer then Exit else begin NeedRegExp := True; ReplaceSubstr(aStr, lIdx, 2, '[A-Za-zА-Яа-я]'); end; spsReturn: ReplaceSubstr(aStr, lIdx, 2, cc_SoftEnter); spsDash: ReplaceSubstr(aStr, lIdx, 2, #$96); spsMDash: ReplaceSubstr(aStr, lIdx, 2, #$97); spsNBSpace: ReplaceSubstr(aStr, lIdx, 2, cc_SoftSpace); spsLid: ReplaceSubstr(aStr, lIdx, 2, '^'); spsParagraph: if ForReplacer then ReplaceSubstr(aStr, lIdx, 2, #13#10) else begin NeedRegExp := True; ReplaceSubstr(aStr, lIdx, 2, '$'); end; // после "крышки" не спецсимвол, так и оставим, смысл заремленного ниже куска мне не понятен (В.) //else // после "крышки" не спецсимвол, так и оставим //aStr := '^'+aStr[lIdx+1]; //Exit; end; lIdx := Pos('^', aStr); //lIdx := PosEx('^', aStr, lIdx+1); end; if NeedRegexp then aStr := SRegexp + ConvertStrToRegular(aStr); Result := True; end; procedure TTextSearchDlg.FormCreate(Sender: TObject); begin FSymbolsMenu := mnuSpecials; lblOptionsDisp.Caption := ''; IsOptionVisible := false; end; procedure TTextSearchDlg.btnMoreClick(Sender: TObject); begin IsOptionVisible := not IsOptionVisible; end; procedure TTextSearchDlg.FormHide(Sender: TObject); begin if FDialogMode = sdmList then TabSheet2.TabVisible := True; InputsChange(nil); end; procedure TTextSearchDlg.ParseInput; var l_TextToSearch : string; l_IsWeNeedRegexp : Boolean; function lp_InitSeacher4TextFind: Boolean; begin Result := True; if cbNormalize.Checked then LastSrchRec.Searcher := fNormalWordSearcher else if cbRegular.Checked then LastSrchRec.Searcher := fRegularExpressionSearcher else begin try if not ConvertTextWildcards(l_TextToSearch, l_IsWeNeedRegexp) then raise Exception.Create(SInvalidSpecialSymbol + l_TextToSearch); if l_IsWeNeedRegexp or cbAnyTail.Checked then LastSrchRec.Searcher := fRegularExpressionSearcher else LastSrchRec.Searcher := fTextSearcher; except on E : Exception do begin vtMessageDlg(E); ModalResult := mrNone; ActiveControl := STextComboBox; Result := False; end; end; end; end; function lp_InitTextProp: Boolean; begin Result := True; try if cbAnyTail.Checked and (SType = srtText) then LastSrchRec.Searcher.Text := TranslateForAnyTail(l_TextToSearch, l_IsWeNeedRegexp) else LastSrchRec.Searcher.Text := l_TextToSearch; except on E : Exception do begin if not (E is El3NoLoggedException) then vtMessageDlg(E); ModalResult := mrNone; ActiveControl := STextComboBox; Result := False; end; end; end; var l_SubID : Integer; begin if (STextComboBox.Text = '') then begin ModalResult := mrNone; ActiveControl := STextComboBox; Exit; end; l_TextToSearch := STextComboBox.Text; case SType of srtText : begin if not lp_InitSeacher4TextFind then Exit; if not lp_InitTextProp then Exit; STextComboBox.AddToHistory; end; srtStyle: begin fStyleSearcher.Layer := l3NilLong; LastSrchRec.Searcher := fStyleSearcher; if not lp_InitTextProp then Exit; end;{srtStyle} {$IFNDEF NotArchiProject} srtHLink: begin LastSrchRec.Searcher := fHLinkSearcher; if not lp_InitTextProp then Exit; STextComboBox.AddToHistory; end;{srtHLink} {$ENDIF} srtSub: begin LastSrchRec.Searcher := nil; l_SubID := StrToInt(STextComboBox.Text); with (FEditor as TevEditor) do with evGetSubList(TextSource).Sub[l_SubID] do if Exists then Select(Selection) else MessageDlg(Format('Метка %d не найдена.', [l_SubID]), mtWarning, [mbOK], 0); Exit; end;//srtSub end;{case SType} UpdateFindFlag(SrchMode); FInputIsParsed := True; end; procedure TTextSearchDlg.FindEntry; var lRCEvent : TevReplaceConfirmEvent; lDefRCEvent : TevReplaceConfirmEvent; begin if not FInputIsParsed then Exit; if Assigned(LastSrchRec.Replacer) then begin lRCEvent := LastSrchRec.Replacer.OnReplaceConfirm; lDefRCEvent := DoReplaceConfirm; if Assigned(LastSrchRec.Replacer.OnReplaceConfirm) and (TMethod(lRCEvent).Code <> TMethod(lDefRCEvent).Code) then Hide else LastSrchRec.Replacer.OnReplaceConfirm := DoReplaceConfirm; end; IsOptionVisible := false; // схлопываем настройки if not FInReplaceLoop then begin case FDialogMode of sdmEditor: begin try FEditor.Find(LastSrchRec.Searcher, LastSrchRec.Replacer, LastSrchRec.SFlags); if Assigned(FEditor) then FEditor.AdjustForm2Found(Self); {$IFDEF InsiderTest} Tl3BatchService.Instance.ExecuteCurrentModalWorker(se_meAfterLoop); {$ENDIF InsiderTest} if Assigned(LastSrchRec.Replacer) and (f_OwnerToClose <> 0) then PostMessage(f_OwnerToClose, WM_CLOSE, 0, 0); except on EevSearchFailed do ShowNotFoundMsg; on El3RegExError do ShowBadRegExpMsg; end;{try..finally} Exclude(LastSrchRec.SFlags, ev_soGlobal); end; {$IFNDEF NotArchiProject} // поиск в списках - только в Арчи sdmList: begin Assert(SType = srtText, '?? SType <> srtText :('); if OriginGroup.ItemIndex = 1 then FindInList(f_SrchWin.DocList.SrchResultLister.Current + 1) else FindInList(0); OriginGroup.ItemIndex := 1; end; {$ENDIF} end; end else FReplaceResult := mrNo; end; procedure TTextSearchDlg.btnFindClick(Sender: TObject); begin if FInReplaceLoop then FReplaceResult := mrNo else begin if not FInputIsParsed then ParseInput; FindEntry; end; end; procedure TTextSearchDlg.InputsChange(Sender: TObject); begin FInputIsParsed := False; FReplaceResult := mrCancel; end; procedure TTextSearchDlg.FormShow(Sender: TObject); begin FInputIsParsed := False; end; procedure TTextSearchDlg.btnCancelClick(Sender: TObject); begin Close; end; function TTextSearchDlg.Get_View: InevView; begin Result := FEditor.View; end; function TTextSearchDlg.DeleteFoundRgn: Bool; begin Result := FEditor.DeleteFoundRgn; end; function TTextSearchDlg.Get_Progress: InevProgress; {-} begin Result := FEditor.TextSource; end; function TTextSearchDlg.ReplaceConfirm(const aBlock : InevRange; aAlienReplaceConfirm : TevReplaceConfirmEvent): ShortInt; begin if Assigned(aAlienReplaceConfirm) then Result := (FEditor as TevEditor).SetFoundBlock(aBlock, aAlienReplaceConfirm) else Result := (FEditor as TevEditor).SetFoundBlock(aBlock, DoReplaceConfirm); end; function TTextSearchDlg.DoReplaceConfirm(Sender : TObject; const aBlock : InevRange): ShortInt; {* - запрос на замену. Возвращаемое значение см. TevReplaceConfirmEvent. } begin (FEditor as TevEditor).AdjustForm2Found(Self); fInReplaceLoop := True; Result := mrNone; try fReplaceResult := mrNone; while FReplaceResult = mrNone do begin {$IFDEF InsiderTest} if not Tl3BatchService.Instance.ExecuteCurrentModalWorker(se_meInLoop) then FReplaceResult := mrNone; {$ENDIF InsiderTest} Application.ProcessMessages; end; // while FReplaceResult = mrNone do Result := FReplaceResult; finally FInReplaceLoop := False; end; end; procedure TTextSearchDlg.ReplUpdate; begin FEditor.Update; end; procedure TTextSearchDlg.btnReplaceClick(Sender: TObject); begin if FInReplaceLoop then FReplaceResult := mrYes else begin ParseInput; FindEntry; end; end; procedure TTextSearchDlg.btnReplaceAllClick(Sender: TObject); begin if FInReplaceLoop then FReplaceResult := mrAll else begin ParseInput; Exclude(LastSrchRec.SFlags, ev_soConfirm); FindEntry; Include(LastSrchRec.SFlags, ev_soConfirm); end; end; procedure TTextSearchDlg.DisplayOptions; var S: string; procedure AddStringToS(AddStr: string); begin if S <> '' then S := S + ', ' else AddStr[1] := AnsiUpperCase(AddStr[1])[1]; S := S + AddStr; end; procedure AddOption(CB: TCheckBox; OptionString: string); begin if CB.Visible and CB.Checked then AddStringToS(OptionString); end; begin S := ''; if ScopeGroup.ItemIndex = 1 then AddStringToS('выделенный фрагмент'); AddOption(cbCaseSens, 'с учетом регистра'); AddOption(cbWordOnly, 'слова целиком'); AddOption(cbNormalize, 'словоформы'); AddOption(cbAnyTail, 'любые окончания'); AddOption(cbRegular, 'регулярные выражения'); AddOption(cbWholePara, 'ко всему параграфу'); lblOptionsDisp.Caption := S; end; procedure TTextSearchDlg.cbWholeParaClick(Sender: TObject); begin InputsChange(nil); DisplayOptions; end; procedure TTextSearchDlg.SetIsOptionVisible(aValue : boolean); var BM: TBitmap; begin if IsOptionVisible = aValue then Exit; fIsOptionVisible := aValue; if IsOptionVisible then begin Height := 362; BM := TBitmap.Create; ilOpenClose.GetBitmap(0, BM); btnMore.Glyph := BM; OptionGroupBox.Visible := True; ScopeGroup.Visible := True; OriginGroup.Visible := True; end else begin Height := 177; BM := TBitmap.Create; ilOpenClose.GetBitmap(1, BM); btnMore.Glyph := BM; OptionGroupBox.Visible := False; ScopeGroup.Visible := False; OriginGroup.Visible := False; end; end; procedure TTextSearchDlg.ScopeGroupClick(Sender: TObject); begin InputsChange(nil); DisplayOptions; end; procedure TTextSearchDlg.STextComboBoxChange(Sender: TObject); var lEnableButtons: Boolean; begin InputsChange(nil); lEnableButtons := STextComboBox.Text <> ''; btnFind.Enabled := lEnableButtons; btnReplaceAll.Enabled := lEnableButtons; btnReplace.Enabled := lEnableButtons; end; function TTextSearchDlg.DefaultCloseAction: TCloseAction; begin Result := caHide; end; function TTextSearchDlg.CheckStamp(const aGUID: TGUID): Boolean; {-} begin if l3SystemDown then Result := False else Result := IsEqualGUID(l3System.GetStamp, aGUID); end; procedure TTextSearchDlg.ShowBadRegExpMsg; begin vtMessageDlg(l3CStr(@SBadRegExp), mtError, [mbOK], 0 {HelpCtx}); end; class procedure TTextSearchDlg.ClientFormClosed(aForm: TCustomForm); begin if not Assigned(g_TextSearchDlg) then Exit; with g_TextSearchDlg do if (fEditor <> nil) and (GetParentForm(fEditor) = aForm) then begin fEditor := nil; f_OwnerToClose := aForm.Handle; end; end; {$IFDEF InsiderTest} class procedure TTextSearchDlg.ClearFindWindow; begin if Assigned(g_TextSearchDlg) then FreeAndNil(g_TextSearchDlg); end; {$ENDIF InsiderTest} class procedure TTextSearchDlg.SwitchActiveEditor(aNewEditor: TevCustomEditor); begin if not Assigned(g_TextSearchDlg) then Exit; with g_TextSearchDlg do begin try if aNewEditor = FEditor then Exit; Close; except l3System.Stack2Log('Какая-то хрень с g_TextSearchDlg.FEditor'); end; fDialogMode := sdmEditor; fEditor := aNewEditor; if aNewEditor = nil then Exit; end; end; class function TTextSearchDlg.IsInReplaceLoop: Boolean; begin Result := (g_TextSearchDlg <> nil) and g_TextSearchDlg.FInReplaceLoop; end; procedure TTextSearchDlg.UpdateFindFlag(aFlag: Byte); var l_Form : TCustomForm; l_TempBool : Boolean; l_TextToReplace : string; begin if (aFlag = 1) then begin case RType of srtText : begin if (SType = srtText) and cbRegular.Checked then LastSrchRec.Replacer := fRegExpReplacer else LastSrchRec.Replacer := fTextReplacer; RTextComboBox.AddToHistory; end; srtStyle : begin LastSrchRec.Replacer := fStyleReplacer; fStyleReplacer.WholePara := cbWholePara.Checked; end;{srtStyle} srtSub : LastSrchRec.Replacer := fSubReplacer; {$IFNDEF NotArchiProject} srtHLink : begin LastSrchRec.Replacer := fHLinkReplacer; l_Form := GetParentForm(fEditor); if l_Form is TDocEditorWindow then fHLinkReplacer.EnableAbsentDoc := TDocEditorWindow(l_Form).miSetReferenceDirect.Enabled; RTextComboBox.AddToHistory; end; {$ENDIF} end;{case RType} try if RType = srtText then begin l_TextToReplace := RTextComboBox.Text; if not ConvertTextWildcards(l_TextToReplace, l_TempBool, True) then raise Exception.Create(SInvalidSpecialSymbol + l_TextToReplace); LastSrchRec.Replacer.Text := l_TextToReplace; end else LastSrchRec.Replacer.Text := RTextComboBox.Text; except on E : Exception do begin if not (E is El3NoLoggedException) then vtMessageDlg(E); ModalResult := mrNone; ActiveControl := RTextComboBox; Exit; end; end; end else LastSrchRec.Replacer := nil; LastSrchRec.SFlags := []; if cbCaseSens.Checked then Include(LastSrchRec.SFlags, ev_soMatchCase); if cbWordOnly.Checked then Include(LastSrchRec.SFlags, ev_soWholeWord); if ScopeGroup.ItemIndex = 1 then Include(LastSrchRec.SFlags, ev_soSelText); if (aFlag = 1) then begin Include(LastSrchRec.SFlags, ev_soConfirm); Include(LastSrchRec.SFlags, ev_soReplaceAll); end else Include(LastSrchRec.SFlags, ev_soFind); case OriginGroup.ItemIndex of 0 : Include(LastSrchRec.SFlags, ev_soGlobal); 2 : Include(LastSrchRec.SFlags, ev_soBackward); end;{case OriginGroup.ItemIndex} LastSrchRec.Searcher.Options := LastSrchRec.SFlags; if (aFlag = 1) then LastSrchRec.Replacer.Options := LastSrchRec.SFlags; LastSrchRec.Operation := aFlag + 1; end; end.
unit FFSStatusBar; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDCustomStatusBar, LMDStatusBar, lmdgraph, FFSTypes; type TFFSStatusBar = class(TLMDStatusBar) private FFieldsColorScheme: TFieldsColorScheme; procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; procedure SetFieldsColorScheme(const Value: TFieldsColorScheme); protected { Protected declarations } public { Public declarations } published property FieldsColorScheme:TFieldsColorScheme read FFieldsColorScheme write SetFieldsColorScheme; constructor create(AOwner: TComponent); override; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Controls', [TFFSStatusBar]); end; { TFFSStatusBar } constructor TFFSStatusBar.create(AOwner: TComponent); begin inherited; OldStyle := False; bevel.Mode := bmStandard; bevel.StandardStyle := lsNone; SizeGrip := False; FFieldsColorScheme := fcsFormStatusBar; end; procedure TFFSStatusBar.MsgFFSColorChange(var Msg: TMessage); begin color := FFSColor[FFieldsColorScheme]; end; procedure TFFSStatusBar.SetFieldsColorScheme( const Value: TFieldsColorScheme); begin FFieldsColorScheme := Value; color := FFSColor[FFieldsColorScheme]; end; end.
unit BarSettingForma; interface {$I defines.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MemTableDataEh, Db, MemTableEh, GridsEh, DBGridEh, FIBQuery, pFIBQuery, OkCancel_frame, StdCtrls, ComCtrls, ToolWin, ExtCtrls, ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh, PrjConst, System.UITypes, EhLibVCL, DBGridEhGrouping, DynVarsEh; type TBarSettingForm = class(TForm) pnlBody: TPanel; okcnclfrm1: TOkCancelFrame; grdFormat: TDBGridEh; mdFormat: TMemTableEh; dsFormat: TDataSource; strfldFormatDATA: TStringField; intgrfldFormatSIZE: TIntegerField; ToolBar2: TToolBar; tbSrvAdd: TToolButton; tbSrvEdit: TToolButton; tbSrvDelete: TToolButton; ToolButton1: TToolButton; tbSrvOk: TToolButton; tbSrvCancel: TToolButton; pnlTest: TPanel; btn1: TButton; edTest: TEdit; strfldFormatFILL: TStringField; procedure mdFormatNewRecord(DataSet: TDataSet); procedure tbSrvOkClick(Sender: TObject); procedure tbSrvCancelClick(Sender: TObject); procedure tbSrvAddClick(Sender: TObject); procedure tbSrvEditClick(Sender: TObject); procedure tbSrvDeleteClick(Sender: TObject); procedure dsFormatStateChange(Sender: TObject); procedure btn1Click(Sender: TObject); procedure grdFormatExit(Sender: TObject); procedure FormCreate(Sender: TObject); procedure okcnclfrm1bbOkClick(Sender: TObject); private { Private declarations } fCodeType : Integer; function GetBarCode:string; procedure SetBarCode(const value : string); procedure SetCodeType(const value :integer); public { Public declarations } property CodeType:integer write SetCodeType; property BarCodeFormat:string read GetBarCode write SetBarCode; end; var BarSettingForm: TBarSettingForm; implementation uses AtrStrUtils, DM; {$R *.dfm} procedure TBarSettingForm.SetCodeType(const value :integer); var i : Integer; val : TStringArray; cl : TColumnEh; begin case Value of 0: begin Caption := rsSettingsBarCode; val := Explode(';',barcode_fields); end; 1 : begin Caption := rsSettingsAccount; val := Explode(';',ls_fields); end; end; fCodeType := Value; cl := grdFormat.Columns[0]; cl.PickList.Clear; for i := 0 to Length(val) - 1 do begin cl.PickList.Add(Val[i]); end; end; procedure TBarSettingForm.btn1Click(Sender: TObject); var i : Integer; s : string; format : string; begin format := GetBarCode; case fCodeType of 0 : edTest.Text := DMMAIN.GenerateBarCodeFromFormat(format,'1', 100.5, 1, 'ЛЕНИНА','1','1','ШУМКО ДМИТРИЙ ГЕОГРИЕВИЧ'); 1 : begin with TpFIBQuery.Create(Nil) do try DataBase :=dmMain.dbTV; Transaction := dmMain.trReadQ; SQL.Text:='select first 1 h.house_id, c.flat_no from house h inner join customer c on (c.house_id = h.house_id)'; Transaction.StartTransaction; ExecQuery; i := 1; s := ''; if not EOF then begin i := FieldByName('house_id').Value; s := FieldByName('flat_no').Value; end; Close; Transaction.Commit; finally Free; end; edTest.Text := DMMAIN.GenerateDogNumberFromFormat(format,i,s,-1); end; end; end; procedure TBarSettingForm.grdFormatExit(Sender: TObject); begin if mdFormat.State in [dsEdit, dsInsert] then mdFormat.Post; end; procedure TBarSettingForm.dsFormatStateChange(Sender: TObject); begin tbSrvOk.Enabled := not ((sender as TDataSource).DataSet.State = dsBrowse); tbSrvCancel.Enabled := tbSrvOk.Enabled; tbSrvAdd.Enabled := not tbSrvOk.Enabled; tbSrvEdit.Enabled := not tbSrvOk.Enabled; tbSrvDelete.Enabled := not tbSrvOk.Enabled; end; procedure TBarSettingForm.FormCreate(Sender: TObject); begin fCodeType := 0; end; function TBarSettingForm.GetBarCode:string; var s : string; begin Result := ''; if not mdFormat.Active then Exit; mdFormat.First; if mdFormat.EOF then Exit; s := ''; while not mdFormat.Eof do begin s:= s + mdFormat.FieldByName('DATA').AsString+'~'; s:= s + mdFormat.FieldByName('SIZE').AsString+'~'; s:= s + mdFormat.FieldByName('FILL').AsString+'~'; s:= s + '^'; mdFormat.Next; end; Result := Copy(s,0,length(s)-1); end; procedure TBarSettingForm.mdFormatNewRecord(DataSet: TDataSet); begin mdFormat['SIZE'] := 5; mdFormat['FILL'] := '0'; end; procedure TBarSettingForm.okcnclfrm1bbOkClick(Sender: TObject); begin okcnclfrm1.actExitExecute(Sender); end; procedure TBarSettingForm.SetBarCode(const value : string); var sa, sl : TStringArray; cnt, i, j : Integer; begin mdFormat.Close; mdFormat.Open; while not mdFormat.EOF do mdFormat.Delete; if value = '' then Exit; sa := Explode('^',VALUE); cnt := Length(sa); for I := 0 to Cnt - 1 do begin sl := Explode('~',sa[i]); mdFormat.Append; j:= Length(sl); if j>0 then mdFormat['DATA'] := sl[0]; if j>1 then begin try mdFormat['SIZE'] := sl[1]; except mdFormat.FieldByName('SIZE').Clear; end; end; if j>2 then mdFormat['FILL'] := sl[2]; mdFormat.Post; end; end; procedure TBarSettingForm.tbSrvAddClick(Sender: TObject); begin mdFormat.Append; end; procedure TBarSettingForm.tbSrvCancelClick(Sender: TObject); begin mdFormat.Cancel; end; procedure TBarSettingForm.tbSrvDeleteClick(Sender: TObject); begin if MessageDlg(rsDeleteParam, mtConfirmation, [mbYes, mbNo], 0) = mrYes then mdFormat.Delete; end; procedure TBarSettingForm.tbSrvEditClick(Sender: TObject); begin mdFormat.Edit; end; procedure TBarSettingForm.tbSrvOkClick(Sender: TObject); begin mdFormat.Post; 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.3 10/26/2004 10:49:20 PM JPMugaas Updated ref. Rev 1.2 2004.02.03 5:44:30 PM czhower Name changes Rev 1.1 1/21/2004 4:04:06 PM JPMugaas InitComponent Rev 1.0 11/13/2002 08:02:36 AM JPMugaas } unit IdSystatUDP; { Indy Systat Client TIdSystatUDP Copyright (C) 2002 Winshoes Working Group Original author J. Peter Mugaas 2002-August-13 Based on RFC 866 Note that this protocol is officially called Active User } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdUDPBase, IdUDPClient; const DefIdSysUDPTimeout = 1000; //one second type TIdSystatUDP = class(TIdUDPClient) protected procedure InitComponent; override; public procedure GetStat(ADest : TStrings); published property ReceiveTimeout default DefIdSysUDPTimeout; //Infinite Timeout can not be used for UDP reads property Port default IdPORT_SYSTAT; end; { Note that no result parsing is done because RFC 866 does not specify a syntax for a user list. Quoted from RFC 866: There is no specific syntax for the user list. It is recommended that it be limited to the ASCII printing characters, space, carriage return, and line feed. Each user should be listed on a separate line. } implementation uses IdGlobal, SysUtils; { TIdSystatUDP } procedure TIdSystatUDP.InitComponent; begin inherited; Port := IdPORT_SYSTAT; ReceiveTimeout := DefIdSysUDPTimeout; end; procedure TIdSystatUDP.GetStat(ADest: TStrings); var s : String; LTimeout : Integer; begin //we do things this way so that IdTimeoutInfinite can never be used. // Necessary because that will hang the code. // RLebeau 1/5/2011: this does not make sense. If ReceiveTimeout is // IdTimeoutInfinite, then LTimeout will end up still being IdTimeoutInfinite // because ReceiveTimeout is being read a second time. Shouldn't this // be specifying a real timeout value instead? LTimeout := ReceiveTimeout; if LTimeout = IdTimeoutInfinite then begin LTimeout := ReceiveTimeout; end; ADest.Clear; //The string can be anything - The RFC says the server should discard packets Send(' '); {Do not Localize} { We do things this way because RFC 866 says: If the list does not fit in one datagram then send a sequence of datagrams but don't break the information for a user (a line) across a datagram. } repeat s := ReceiveString(LTimeout, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); if s = '' then begin Break; end; ADest.Add(s); until False; end; end.
PROGRAM XPrint(INPUT, OUTPUT); CONST Min = 1; Last = 5; Max = 25; TYPE Sieve = SET OF Min .. Max; VAR SymbolCode: Sieve; PROCEDURE EncodingSymbol(VAR FIn: TEXT; VAR ManyNumbers: Sieve); VAR Ch: CHAR; BEGIN {EncodingSymbol} READ(FIn, Ch); ManyNumbers := []; IF Ch = 'A' THEN ManyNumbers := [2, 3, 4, 6, 10, 11, 13, 15, 16, 20, 21, 25]; IF Ch = 'B' THEN ManyNumbers := [1 .. 4, 6, 10, 11 .. 14, 16, 20, 21 .. 24]; IF Ch = 'C' THEN ManyNumbers := [2 .. 6, 11, 16, 22 .. 25]; IF Ch = 'D' THEN ManyNumbers := [1 .. 4, 6, 10, 11, 15, 16, 20 .. 24]; IF Ch = 'E' THEN ManyNumbers := [1 .. 6, 11 .. 16, 21 .. 25] END; {EncodingSymbol} PROCEDURE PrintSymbol(VAR FOut: TEXT; VAR ManyNumbers: Sieve); VAR WhichNumber, I: INTEGER; BEGIN {PrintSymbol} WhichNumber := Min; WHILE (WhichNumber <= Max) AND (ManyNumbers <> []) DO BEGIN FOR I := Min TO Last DO BEGIN IF WhichNumber IN ManyNumbers THEN WRITE(FOut, 'X') ELSE WRITE(FOut, ' '); WhichNumber := WhichNumber + 1 END; WRITELN(FOut) END END; {PrintSymbol} BEGIN {XPrint} IF NOT EOLN THEN BEGIN EncodingSymbol(INPUT, SymbolCode); PrintSymbol(OUTPUT, SymbolCode) END END. {XPrint}
unit uConsts; interface const CONST_IMAGE_HEIGHT = 64; CONST_IMAGE_WIDTH = 64; CONST_MARGIN_LEFT = 8; CONST_MARGIN_TOP = 8; CONST_FILE_TYPES: array [1..3] of String = ('jpg', 'bmp', 'png'); CONST_MAX_THREADS = 32; implementation 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 ClpZeroBytePadding; {$I ..\..\Include\CryptoLib.inc} interface uses ClpIBlockCipherPadding, ClpIZeroBytePadding, ClpISecureRandom, ClpCryptoLibTypes; type /// <summary> /// A padder that adds Null byte padding to a block. /// </summary> TZeroBytePadding = class sealed(TInterfacedObject, IZeroBytePadding, IBlockCipherPadding) strict private /// <returns> /// return the name of the algorithm the cipher implements. /// </returns> function GetPaddingName: String; inline; public /// <summary> /// Initialise the padder. /// </summary> /// <param name="random"> /// a SecureRandom if available. /// </param> procedure Init(const random: ISecureRandom); /// <summary> /// Return the name of the algorithm the cipher implements. /// </summary> property PaddingName: String read GetPaddingName; /// <summary> /// add the pad bytes to the passed in block, returning the number of /// bytes added. /// </summary> /// <param name="input"> /// input block to pad /// </param> /// <param name="inOff"> /// offset to start the padding from in the block /// </param> /// <returns> /// returns number of bytes added /// </returns> function AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; /// <summary> /// return the number of pad bytes present in the block. /// </summary> /// <param name="input"> /// block to count pad bytes in /// </param> /// <returns> /// the number of pad bytes present in the block. /// </returns> function PadCount(const input: TCryptoLibByteArray): Int32; end; implementation { TZeroBytePadding } function TZeroBytePadding.AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; var added: Int32; begin added := System.Length(input) - inOff; while (inOff < System.Length(input)) do begin input[inOff] := Byte(0); System.Inc(inOff); end; result := added; end; function TZeroBytePadding.GetPaddingName: String; begin result := 'ZeroBytePadding'; end; {$IFNDEF _FIXINSIGHT_} procedure TZeroBytePadding.Init(const random: ISecureRandom); begin // nothing to do. end; {$ENDIF} function TZeroBytePadding.PadCount(const input: TCryptoLibByteArray): Int32; var count: Int32; begin count := System.Length(input); while (count > 0) do begin if (input[count - 1] <> 0) then begin break; end; System.Dec(count); end; result := System.Length(input) - count; end; end.
unit fb2txt_dispatch; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, FB2_to_TXT_TLB, StdVcl, fb2txt_engine; type TFB2TXTExport = class(TAutoObject, IFB2TXTExport) public procedure AfterConstruction; Override; procedure BeforeDestruction; override; protected function Get_Encoding: Integer; safecall; function Get_FixedWidth: Integer; safecall; function Get_Hyphenator: IDispatch; safecall; function Get_LineBr: OleVariant; safecall; function Get_ParaIndent: OleVariant; safecall; function Get_SkipDescr: WordBool; safecall; function Get_XSL: IDispatch; safecall; procedure Convert(const document: IDispatch; FileName: OleVariant); safecall; procedure ConvertInteractive(hWnd: Integer; filename: OleVariant; const document: IDispatch); safecall; procedure Set_Encoding(Value: Integer); safecall; procedure Set_FixedWidth(Value: Integer); safecall; procedure Set_Hyphenator(const Value: IDispatch); safecall; procedure Set_LineBr(Value: OleVariant); safecall; procedure Set_ParaIndent(Value: OleVariant); safecall; procedure Set_SkipDescr(Value: WordBool); safecall; procedure Set_XSL(const Value: IDispatch); safecall; function Get_IgnoreEmphasis: WordBool; safecall; function Get_IgnoreStrong: WordBool; safecall; procedure Set_IgnoreEmphasis(Value: WordBool); safecall; procedure Set_IgnoreStrong(Value: WordBool); safecall; { Protected declarations } private Converter:TTXTConverter; end; implementation uses ComServ,fb2_hyph_TLB,MSXML2_TLB,Dialogs,SysUtils; procedure TFB2TXTExport.AfterConstruction; Begin inherited AfterConstruction; Converter:=TTXTConverter.Create; end; procedure TFB2TXTExport.BeforeDestruction; Begin inherited BeforeDestruction; Converter.Free; end; function TFB2TXTExport.Get_Encoding: Integer; begin Result:=Converter.CodePage; end; function TFB2TXTExport.Get_FixedWidth: Integer; begin Result:=Converter.TextWidth; end; function TFB2TXTExport.Get_Hyphenator: IDispatch; begin Result:=Converter.HyphControler; end; function TFB2TXTExport.Get_LineBr: OleVariant; begin Result:=Converter.BR; end; function TFB2TXTExport.Get_ParaIndent: OleVariant; begin Result:=Converter.Indent; end; function TFB2TXTExport.Get_SkipDescr: WordBool; begin Result:=Converter.SkipDescr; end; function TFB2TXTExport.Get_XSL: IDispatch; begin Result:=Converter.XSL; end; procedure TFB2TXTExport.Convert(const document: IDispatch; FileName: OleVariant); begin Converter.Convert(document,FileName); end; procedure TFB2TXTExport.ConvertInteractive(hWnd: Integer; filename: OleVariant; const document: IDispatch); Var ExpI:IFBEExportPlugin; FN:String; XDoc:IXMLDOMDocument2; begin FN:=filename; if Document=Nil then Begin With TOpenDialog.Create(Nil) do try Filter:='FictionBook 2.0 documents (*.fb2)|*.fb2|All files (*.*)|*.*'; If not Execute then Exit; XDoc:=CoFreeThreadedDOMDocument40.Create; if not XDoc.load(FileName) then Raise Exception.Create('Opening fb2 file:'#10+XDoc.parseError.reason); FN:=FileName; Finally Free; end; end else if document.QueryInterface(IID_IXMLDOMDocument2,XDoc) <> S_OK then Exception.Create('Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2'); ExpI:=CoFB2_to_TXT_.Create; ExpI.Export(hWnd,FN,XDoc); end; procedure TFB2TXTExport.Set_Encoding(Value: Integer); begin Converter.CodePage:=Value; end; procedure TFB2TXTExport.Set_FixedWidth(Value: Integer); begin Converter.TextWidth:=Value; end; procedure TFB2TXTExport.Set_Hyphenator(const Value: IDispatch); Var HC:IFB2Hyphenator; begin if Value.QueryInterface(IID_IFB2Hyphenator,HC) <> S_OK then Exception.Create('Invalid hyphenator interface on enter, should be called with IFB2Hyphenator'); Converter.HyphControler:=HC; end; procedure TFB2TXTExport.Set_LineBr(Value: OleVariant); begin Converter.BR:=Value; end; procedure TFB2TXTExport.Set_ParaIndent(Value: OleVariant); begin Converter.Indent:=Value; end; procedure TFB2TXTExport.Set_SkipDescr(Value: WordBool); begin Converter.SkipDescr:=Value; end; procedure TFB2TXTExport.Set_XSL(const Value: IDispatch); Var OutVar:IXMLDOMDocument2; begin if Value.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then Exception.Create('Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2') else Converter.XSL:=OutVar; end; function TFB2TXTExport.Get_IgnoreEmphasis: WordBool; begin result:=Converter.IgnoreItalic; end; function TFB2TXTExport.Get_IgnoreStrong: WordBool; begin result:=Converter.IgnoreBold; end; procedure TFB2TXTExport.Set_IgnoreEmphasis(Value: WordBool); begin Converter.IgnoreItalic:=Value; end; procedure TFB2TXTExport.Set_IgnoreStrong(Value: WordBool); begin Converter.IgnoreBold:=Value; end; initialization TAutoObjectFactory.Create(ComServer, TFB2TXTExport, Class_FB2TXTExport, ciMultiInstance, tmApartment); end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, Androidapi.JNI.TTS, FMX.StdCtrls, FMX.Layouts, FMX.Memo, AndroidAPI.JNIBridge, Androidapi.JNI.Speech, Androidapi.JNI.Os, Androidapi.JNI.GraphicsContentViewText; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private type TttsOnInitListener = class(TJavaLocal, JTextToSpeech_OnInitListener) private [weak] FParent : TForm1; public constructor Create(AParent : TForm1); procedure onInit(status: Integer); cdecl; end; TRecognitionListener = class(TJavaLocal, JRecognitionListener) private [weak] FParent : TForm1; public constructor Create(AParent : TForm1); procedure onBeginningOfSpeech; cdecl; procedure onBufferReceived(buffer: TJavaArray<byte>); cdecl; procedure onEndOfSpeech; cdecl; procedure onError(error: Integer); cdecl; procedure onEvent(eventType : Integer; params : JBundle); cdecl; procedure onPartialResults(partialResults : JBundle); cdecl; procedure onReadyForSpeech(params : JBundle); cdecl; procedure onResults(results : JBundle); cdecl; procedure onRmsChanged(rmsdB : Single); cdecl; end; private { Private declarations } ttsListener : TttsOnInitListener; tts : JTextToSpeech; RecListener : TRecognitionListener; SpeechRecognizer : JSpeechRecognizer; RecognizerIntent : JIntent; procedure SpeakOut; public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.fmx} // List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); // Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo..."); // startActivityForResult(intent, REQUEST_CODE); //protected void onActivityResult(int requestCode, int resultCode, Intent data) //{ // if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) // { // // Populate the wordsList with the String values the recognition engine thought it heard // ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); // } //} uses Androidapi.JNI.JavaTypes, FMX.Helpers.Android {$IF CompilerVersion >= 27.0} , Androidapi.Helpers {$ENDIF} ; procedure TForm1.Button1Click(Sender: TObject); begin SpeakOut; end; procedure TForm1.Button2Click(Sender: TObject); begin tts := TJTextToSpeech.JavaClass.init(SharedActivityContext, ttsListener); end; procedure TForm1.Button3Click(Sender: TObject); var b : Boolean; begin b := TJSpeechRecognizer.JavaClass.isRecognitionAvailable(SharedActivityContext); if b then begin SpeechRecognizer := TJSpeechRecognizer.JavaClass.createSpeechRecognizer(SharedActivityContext); RecListener := TRecognitionListener.Create(self); RecognizerIntent := TJRecognizerIntent.JavaClass.getVoiceDetailsIntent(SharedActivityContext); RecognizerIntent.putExtra(TJRecognizerIntent.JavaClass.EXTRA_LANGUAGE_MODEL, StringToJString('en-US')); SpeechRecognizer.setRecognitionListener(RecListener); Button3.Enabled := false; Button4.Enabled := true; end; end; procedure TForm1.Button4Click(Sender: TObject); begin if Button4.Text = 'Listen' then SpeechRecognizer.startListening(RecognizerIntent) else SpeechRecognizer.stopListening; end; constructor TForm1.Create(AOwner: TComponent); begin inherited; ttsListener := TttsOnInitListener.Create(self); end; destructor TForm1.Destroy; begin if Assigned(tts) then begin tts.stop; tts.shutdown; tts := nil; end; ttsListener := nil; inherited; end; procedure TForm1.SpeakOut; var text : JString; begin text := StringToJString(Memo1.Lines.Text); tts.speak(text, TJTextToSpeech.JavaClass.QUEUE_FLUSH, nil); end; { TForm1.TttsOnInitListener } constructor TForm1.TttsOnInitListener.Create(AParent: TForm1); begin inherited Create; FParent := AParent end; procedure TForm1.TttsOnInitListener.onInit(status: Integer); var Result : Integer; begin if (status = TJTextToSpeech.JavaClass.SUCCESS) then begin result := FParent.tts.setLanguage(TJLocale.JavaClass.US); if (result = TJTextToSpeech.JavaClass.LANG_MISSING_DATA) or (result = TJTextToSpeech.JavaClass.LANG_NOT_SUPPORTED) then ShowMessage('This Language is not supported') else begin FParent.Button1.Enabled := true; FParent.button2.Enabled := false; end; end else ShowMessage('Initilization Failed!'); end; { TForm1.TRecognitionListener } constructor TForm1.TRecognitionListener.Create(AParent: TForm1); begin inherited Create; FParent := AParent; end; procedure TForm1.TRecognitionListener.onBeginningOfSpeech; begin end; procedure TForm1.TRecognitionListener.onBufferReceived( buffer: TJavaArray<byte>); var tmp : JString; begin tmp := TJString.JavaClass.init(buffer); FParent.Memo1.Lines.Add(JStringToString(tmp)); end; procedure TForm1.TRecognitionListener.onEndOfSpeech; begin FParent.Button4.Text := 'Listen'; end; procedure TForm1.TRecognitionListener.onError(error: Integer); begin end; procedure TForm1.TRecognitionListener.onEvent(eventType: Integer; params: JBundle); begin end; procedure TForm1.TRecognitionListener.onPartialResults(partialResults: JBundle); begin end; procedure TForm1.TRecognitionListener.onReadyForSpeech(params: JBundle); begin FParent.Button4.Text := 'Stop'; end; procedure TForm1.TRecognitionListener.onResults(results: JBundle); begin end; procedure TForm1.TRecognitionListener.onRmsChanged(rmsdB: Single); begin end; end.
{*******************************************************} { } { EldoS Markup Language Generator (MlGen) Demo } { } { Copyright (c) 1999-2001 Mikhail Chernyshev } { } {*******************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Grids, Spin, clMlDemo; type TMainForm = class(TForm) StatusLine: TStatusBar; Panel2: TPanel; LinesOnPageEdit: TSpinEdit; Label3: TLabel; HeaderCheckBox: TCheckBox; FooterCheckBox: TCheckBox; GenerateButton: TButton; MultipageCheckBox: TCheckBox; OutputFilesEdit: TEdit; Label4: TLabel; BrowseOutputButton: TButton; OpenTemplateDialog: TOpenDialog; SaveDialog1: TSaveDialog; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Label1: TLabel; StringGrid: TStringGrid; AddRowBtn: TButton; DeleteRowBtn: TButton; AddColBtn: TButton; DeleteColBtn: TButton; Label2: TLabel; TemplateEdit: TEdit; BrowseTemplateBtn: TButton; Label5: TLabel; TemplateParamsListBox: TListBox; Label6: TLabel; TranslationTableNamesListBox: TListBox; TranslationTableListBox: TListBox; OpenResultBtn: TButton; Splitter1: TSplitter; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ShowHint(Sender: TObject); procedure MultipageCheckBoxClick(Sender: TObject); procedure BrowseTemplateBtnClick(Sender: TObject); procedure BrowseOutputButtonClick(Sender: TObject); procedure AddRowBtnClick(Sender: TObject); procedure DeleteRowBtnClick(Sender: TObject); procedure AddColBtnClick(Sender: TObject); procedure DeleteColBtnClick(Sender: TObject); procedure GenerateButtonClick(Sender: TObject); procedure TemplateEditChange(Sender: TObject); procedure TranslationTableNamesListBoxClick(Sender: TObject); procedure OutputFilesEditChange(Sender: TObject); procedure OpenResultBtnClick(Sender: TObject); private { Private declarations } procedure FillStringGrid; procedure FillStringGridRow(aRow : Integer); procedure FillStringGridCol(aCol : Integer); procedure UpdateFixedRow; procedure UpdateFixedCol; procedure ChangeTranslationTable; public { Public declarations } DemoMlGen : TDemoMlGen; end; var MainForm: TMainForm; ExePath : string; implementation uses ElMlGen, ShellAPI; {$R *.DFM} procedure TMainForm.FormCreate(Sender: TObject); begin DemoMlGen := TDemoMlGen.Create(nil); // DemoMlGen.TagPrefix := 'xx_'; ExePath := CheckPath(ExtractFilePath(Application.ExeName), True); // TemplateEdit.Text := ExePath + 'Templates\FullListTxt.templ'; TemplateEdit.Text := ExePath + 'Templates\Test.templ'; MultipageCheckBoxClick(nil); FillStringGrid; end; procedure TMainForm.FormDestroy(Sender: TObject); begin DemoMlGen.Free; end; procedure TMainForm.ShowHint(Sender: TObject); begin with StatusLine do begin Panels[0].Text := Application.Hint; Update; end; end; procedure TMainForm.MultipageCheckBoxClick(Sender: TObject); var b : boolean; begin b := MultipageCheckBox.Checked; Label3.Enabled := b; LinesOnPageEdit.Enabled := b; end; procedure TMainForm.BrowseTemplateBtnClick(Sender: TObject); var s : string; begin if TemplateEdit.Text = '' then s := ExtractFilePath(ExePath) else s := ExtractFilePath(TemplateEdit.Text); OpenTemplateDialog.InitialDir := s; OpenTemplateDialog.FileName := TemplateEdit.Text; if not OpenTemplateDialog.Execute then exit; TemplateEdit.Text := OpenTemplateDialog.FileName; end; procedure TMainForm.BrowseOutputButtonClick(Sender: TObject); var s : string; begin if TemplateEdit.Text = '' then s := ExtractFilePath(ExePath) else s := ExtractFilePath(OutputFilesEdit.Text); SaveDialog1.InitialDir := s; SaveDialog1.FileName := OutputFilesEdit.Text; if not SaveDialog1.Execute then exit; OutputFilesEdit.Text := SaveDialog1.FileName; end; procedure TMainForm.FillStringGrid; var i : Integer; // Counters begin UpdateFixedCol; UpdateFixedRow; for i := 1 to StringGrid.RowCount - 1 do FillStringGridRow(i); end; procedure TMainForm.FillStringGridRow(aRow: Integer); var i : Integer; // Counters begin for i := 1 to StringGrid.ColCount - 1 do StringGrid.Cells[i, aRow] := Format('Sample [%d, %d]', [i, aRow]); end; procedure TMainForm.FillStringGridCol(aCol: Integer); var i : Integer; // Counters begin for i := 1 to StringGrid.RowCount - 1 do StringGrid.Cells[aCol, i] := Format('Sample [%d, %d]', [aCol, i]); end; procedure TMainForm.UpdateFixedCol; var i : Integer; begin for i := 1 to StringGrid.RowCount - 1 do StringGrid.Cells[0, i] := Format('%d:', [i]); end; procedure TMainForm.UpdateFixedRow; var i : Integer; begin for i := 1 to StringGrid.ColCount - 1 do StringGrid.Cells[i, 0] := Format('Col %d', [i]); end; procedure TMainForm.AddRowBtnClick(Sender: TObject); begin StringGrid.RowCount := StringGrid.RowCount + 1; FillStringGridRow(StringGrid.RowCount - 1); UpdateFixedCol; end; procedure TMainForm.DeleteRowBtnClick(Sender: TObject); var i, j, k : Integer; // Counters begin if StringGrid.RowCount <= 1 then exit; k := StringGrid.Row; for i := k to StringGrid.RowCount - 2 do begin for j := 0 to StringGrid.ColCount - 1 do StringGrid.Cells[j, i] := StringGrid.Cells[j, i+1]; end; // for StringGrid.RowCount := StringGrid.RowCount - 1; UpdateFixedCol; end; procedure TMainForm.AddColBtnClick(Sender: TObject); begin StringGrid.ColCount := StringGrid.ColCount + 1; FillStringGridCol(StringGrid.ColCount - 1); UpdateFixedRow; end; procedure TMainForm.DeleteColBtnClick(Sender: TObject); var i, j, k : Integer; // Counters begin if StringGrid.ColCount <= 1 then exit; k := StringGrid.Col; for i := k to StringGrid.ColCount - 2 do begin for j := 0 to StringGrid.RowCount - 1 do StringGrid.Cells[i, j] := StringGrid.Cells[i+1, j]; end; // for StringGrid.ColCount := StringGrid.ColCount - 1; UpdateFixedRow; end; procedure TMainForm.GenerateButtonClick(Sender: TObject); begin DemoMlGen.OutputFileName := OutputFilesEdit.Text; DemoMlGen.Multipage := MultipageCheckBox.Checked; DemoMlGen.LinesOnPage := LinesOnPageEdit.Value; DemoMlGen.UseHeader := HeaderCheckBox.Checked; DemoMlGen.UseFooter := FooterCheckBox.Checked; DemoMlGen.Execute; OutputFilesEditChange(nil); end; procedure TMainForm.TemplateEditChange(Sender: TObject); begin if FileExists(TemplateEdit.Text) then begin DemoMlGen.Template.LoadFromFile(TemplateEdit.Text); end else begin DemoMlGen.Template.Text := ''; end; // Params DemoMlGen.Parameters.AssignTo(TemplateParamsListBox.Items); // Translation tables TranslationTableNamesListBox.Clear; DemoMlGen.TranslationTables.GetTableNames(TranslationTableNamesListBox.Items); TranslationTableNamesListBox.ItemIndex := DemoMlGen.TranslationTables.DefaultForMacro; ChangeTranslationTable; OutputFilesEdit.Text := ExePath + 'Generated data\' + DemoMlGen.Parameters.GetValueByNameEx('OutputFileName', 'SampleData.txt'); end; procedure TMainForm.TranslationTableNamesListBoxClick(Sender: TObject); begin ChangeTranslationTable; end; procedure TMainForm.ChangeTranslationTable; var TranslationTable : TTranslationTable; begin TranslationTableListBox.Clear; if TranslationTableNamesListBox.ItemIndex >= 0 then begin TranslationTable := DemoMlGen.TranslationTables[TranslationTableNamesListBox.ItemIndex]; TranslationTable.Table.AssignTo(TranslationTableListBox.Items); end; end; procedure TMainForm.OutputFilesEditChange(Sender: TObject); begin OpenResultBtn.Enabled := FileExists(OutputFilesEdit.Text); end; procedure TMainForm.OpenResultBtnClick(Sender: TObject); begin ShellExecute (Application.Handle, 'open', PChar(OutputFilesEdit.Text), nil, nil, SW_NORMAL); end; end.
{$I ok_sklad.inc} unit WBMetaItem; interface uses ssClientDataSet, XMLDoc, XMLIntf, MetaClass, MetaDoc, MetaPrice, Classes; type TWBMetaItemType = (WBMetaItemUnTyped = -1, WBMetaItemTangible = 0, WBMetaItemService = 1); // a single position in waybills, etc TWBMetaItem = class(TMetaClass) protected // taken from WAYBILLDET FProdID: Integer; //MATID INTEGER NOT NULL, //FID=POSID INTEGER NOT NULL, FOwnerID: Integer; //WBILLID INTEGER NOT NULL, FWarehouseID: Integer;//WID INTEGER, FPrice: TMetaPrice; //PRICE NUMERIC(15,8), //PTYPEID INTEGER, //CURRID INTEGER, //DISCOUNT NUMERIC(15,8), //NDS NUMERIC(15,8), FAmount: Extended; //AMOUNT NUMERIC(15,8) NOT NULL, //ONVALUE NUMERIC(15,8), //TOTAL NUMERIC(15,8), //BASEPRICE NUMERIC(15,8) FReserved: Boolean; //CHECKED INTEGER, FPosType: TWBMetaItemType; // for services: FNormedRate: Extended; FPersonID: Integer; FNum: Integer; //NUM INTEGER NOT NULL, it's just internal numerator. //FDate=ondate timestamp, FSerialNumbers: TStringList; function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; function getPrice: TMetaPrice; function getisTangible: Boolean; function getisService: Boolean; procedure setAmount(const Value: Extended); procedure setNormedRate(const Value: Extended); procedure setNum(const Value: Integer); procedure setOwnerID(const Value: Integer); procedure setPersonID(const Value: Integer); procedure setPosType(const Value: TWBMetaItemType); procedure setProdID(const Value: Integer); procedure setReserved(const Value: Boolean); procedure setWarehouseID(const Value: Integer); public constructor Create(const AParent: TMetaClass); destructor Free; procedure Clear; function Load(Ads: TssClientDataSet; const doException: Boolean = False): Boolean; virtual; function Save(const doException: Boolean = False): Boolean; virtual; property Amount: Extended read FAmount write setAmount; property isTangible: Boolean read getisTangible; property isService: Boolean read getisService; property NormedRate: Extended read FnormedRate write setNormedRate; property Num: Integer read FNum write SetNum; property OwnerID: Integer read FOwnerID write setOwnerID; property PersonID: Integer read FPersonID write setPersonID; property PosType: TWBMetaItemType read FPosType write setPosType; property Price: TMetaPrice read getPrice; property ProdID: Integer read FProdID write SetProdID; property Reserved: Boolean read Freserved write setReserved; property WarehouseID: Integer read FWarehouseID write setWarehouseID; end; //********************************************************************** // list of positions TWBMetaItemList = class(TMetaClassList) protected // property processing function getItem(const idx: Integer): TWBMetaItem; procedure setItem(const idx: Integer; const Value: TWBMetaItem); function getTotal: Extended; function getTotalDefCurr: Extended; // in default currency. here = getTotal public constructor Create(const AParent: TMetaClass); destructor Free; procedure Clear; function Load(ADocID: Integer; const doException: Boolean = False): boolean; virtual; function Save(const doException: Boolean = False): Boolean; virtual; function Add(const Value: TWBMetaItem): Integer; property Items[const idx: Integer]: TWBMetaItem read getItem write setItem; default; property Total: Extended read getTotal; property TotalInDefCurr: Extended read getTotalDefCurr; end; // TWBMetaItemList //======================================================================== //======================================================================== //======================================================================== //======================================================================== implementation uses udebug, SysUtils, StrUtils; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; //============================================================================================== //============================================================================================== //============================================================================================== constructor TWBMetaItemList.Create(const AParent: TMetaClass); begin inherited; end; //============================================================================================== destructor TWBMetaItemList.Free; begin inherited; end; //============================================================================================== function TWBMetaItemList.Add(const Value: TWBMetaItem): Integer; begin Result := FItems.Add(Value); isModified := True; end; //============================================================================================== function TWBMetaItemList.getItem(const idx: Integer): TWBMetaItem; begin Result := TWBMetaItem(FItems[idx]); end; //============================================================================================== procedure TWBMetaItemList.setItem(const idx: Integer; const Value: TWBMetaItem); begin FItems[idx] := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItemList.Clear; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWBMetaItemList.Clear') else _udebug := nil;{$ENDIF} inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TWBMetaItemList.Load(ADocID: Integer; const doException: Boolean = False): boolean; begin Result := False; end; //============================================================================================== function TWBMetaItemList.Save(const doException: Boolean = False): Boolean; begin Result := False; end; //============================================================================================== function TWBMetaItemList.getTotal: Extended; var i: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWBMetaItemList.getTotal') else _udebug := nil;{$ENDIF} Result := 0.0; for i := 0 to FItems.Count - 1 do Result := Result + Self[i].Price.Value; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TWBMetaItemList.getTotalDefCurr: Extended; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWBMetaItemList.getTotalDefCurr') else _udebug := nil;{$ENDIF} Result := getTotal; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== procedure TWBMetaItem.Clear; begin inherited; if FPrice <> nil then FPrice.Clear; if FSerialNumbers <> nil then FSerialNumbers.Clear; FAmount := 0.0; FNormedRate := 0.0; FNum := -1; FOwnerID := -1; FPersonID := -1; FProdID := -1; FReserved := False; FWarehouseID := -1; FPosType := WBMetaItemUnTyped; end; //============================================================================================== constructor TWBMetaItem.Create(const AParent: TMetaClass); begin inherited; FSerialNumbers := TStringList.Create; Clear; end; //============================================================================================== destructor TWBMetaItem.Free; begin if FPrice <> nil then FPrice.Free; if FSerialNumbers <> nil then FSerialNumbers.Destroy; inherited; end; //============================================================================================== function TWBMetaItem.getisTangible: Boolean; begin Result := (FPosType = WBMetaItemTangible); end; //============================================================================================== function TWBMetaItem.getisService: Boolean; begin Result := (FPosType = WBMetaItemService); end; //============================================================================================== function TWBMetaItem.getPrice: TMetaPrice; begin if FPrice = nil then FPrice := TMetaPrice.Create(Self); Result := FPrice; end; //============================================================================================== procedure TWBMetaItem.setAmount(const Value: Extended); begin if FAmount = Value then Exit; FAmount := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setNormedRate(const Value: Extended); begin if FNormedRate = Value then Exit; FnormedRate := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setNum(const Value: Integer); begin if FNum = Value then Exit; FNum := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setOwnerID(const Value: Integer); begin if FOwnerID = Value then Exit; FOwnerID := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setPersonID(const Value: Integer); begin if FPersonID = Value then Exit; FPersonID := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setPosType(const Value: TWBMetaItemType); begin if FPosType = Value then Exit; FPosType := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setProdID(const Value: Integer); begin if FProdID = Value then Exit; FProdID := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setReserved(const Value: Boolean); begin if FReserved = Value then Exit; FReserved := Value; isModified := True; end; //============================================================================================== procedure TWBMetaItem.setWarehouseID(const Value: Integer); begin if FWarehouseID = Value then Exit; FWarehouseID := Value; isModified := True; end; //============================================================================================== function TWBMetaItem.Load(Ads: TssClientDataSet; const doException: Boolean = False): Boolean; begin Result := False; end; //============================================================================================== function TWBMetaItem.Save(const doException: Boolean = False): Boolean; begin Result := False; end; //============================================================================================== function TWBMetaItem.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; var name, data: String; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWBMetaItem.loadXMLNode') else _udebug := nil;{$ENDIF} Result := True; Ferror := 0; try // finally name := AnsiLowerCase(Node.NodeName); data := trim(Node.Text); try if (name = 'id') or (name = 'posid') or (name = 'itemid')then begin FID := strToInt(data); Exit; end else if (name = 'prodid') or (name = 'serviceid') then begin FProdID := strToInt(data); Exit; end else if (name = 'ownerid') or (name = 'docid') or (name = 'documentid') then begin FOwnerID := strToInt(data); Exit; end else if (name = 'whid') or (name = 'warehouse') or (name = 'warehouseid') then begin FWarehouseID := strToInt(data); Exit; end else if (name = 'amount') or (name = 'quantity') then begin FAmount := strToFloat(data); Exit; end else if (name = 'reserved') then begin FReserved := strToBool(data); Exit; end else if (name = 'normedrate') then begin FNormedRate := strToFloat(data); Exit; end else if (name = 'personid') then begin FPersonID := strToInt(data); Exit; end else if (name = 'number') then begin FNum := strToInt(data); Exit; end else if (name = 'serialnumber') or (name = 'serialnumbers') then begin FSerialNumbers.Text := data; Exit; end else if (name = 'type') or (name = 'postype') or (name = 'itemtype') then begin if data = 'service' then FPosType := WBMetaItemService else FPosType := WBMetaItemTangible; Exit; end else if (name = 'price') then begin Result := Price.loadXML(node); Exit; end; except Ferror := ap_err_XML_badData; Exit; end; Result := loadXMLNode(topNode, Node); // maybe some base-class stuff finally {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('WBMetaItem', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit l3SimpleMM; {* Простейший менеджер памяти, выделяющий сразу большие куски. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3SimpleMM - } { Начат: 27.02.2002 16:30 } { $Id: l3SimpleMM.pas,v 1.23 2013/04/03 15:29:32 lulin Exp $ } // $Log: l3SimpleMM.pas,v $ // Revision 1.23 2013/04/03 15:29:32 lulin // - портируем. // // Revision 1.22 2011/10/05 09:51:59 voba // - k : 281525254 Борьба с утечками // // Revision 1.21 2011/09/16 06:24:37 lulin // {RequestLink:278824896}. // - убираем ненужные модификаторы. // // Revision 1.20 2008/02/08 12:14:47 lulin // - потенциальная ошибка при пустой строке. // // Revision 1.19 2007/08/30 10:09:23 lulin // - убираем ненужную функцию поиска. // // Revision 1.18 2007/08/14 14:30:13 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.17 2007/01/18 10:49:42 lulin // - заменяем объект менеджера памяти на интерфейс. // // Revision 1.16 2007/01/17 16:54:09 lulin // - защищаем распределение памяти от использования в разных потоках. // // Revision 1.15 2007/01/17 16:47:36 lulin // - подготавливаемся к защите при работе из разных потоков. // // Revision 1.14 2006/12/06 10:34:02 lulin // - "выпрямляем" наследование. // // Revision 1.13 2004/12/05 17:57:24 migel // - fix: не компилировалось (строчный компилятор `dcc32.exe` падал с ошибкой `C13310`). // // Revision 1.12 2004/08/05 17:40:31 law // - избавился от ряда Warning'ов и Hint'ов. // // Revision 1.11 2004/06/01 07:48:41 law // - new defines: l3AssertSimpleMMCanFreeBlocks, _ALCU. // // Revision 1.10 2004/05/31 10:02:55 law // - включен define l3BoxedBitArray - так вроде с ним все заработало. // // Revision 1.9 2004/05/28 18:03:35 law // - new define: l3BoxedBitArray - пока выключен. // // Revision 1.8 2004/05/28 17:12:58 law // - промежуточный commit. // // Revision 1.7 2004/05/28 14:49:05 law // - new bevavior: в пуле сделано освобождение памяти, после освобождения всех выделенных кусков. // // Revision 1.6 2004/05/28 14:43:07 law // - new bevavior: сделан контроль за количеством освобожденных блоков. // // Revision 1.5 2004/05/28 10:42:32 law // - bug fix: неправильно распеределялись объекты в пуле. // // Revision 1.4 2002/04/15 12:19:00 law // - new method: StringAsWideString. // // Revision 1.3 2002/03/04 10:17:04 law // - bug fix. // // Revision 1.2 2002/03/04 09:58:19 law // - buf fix: AV при пустом элементе. // // Revision 1.1 2002/02/27 17:06:54 law // - optimization: попытка оптимизации путем применения менеджера памяти, выделяющего большие блоки. // {$Include l3Define.inc } interface uses Windows, l3Interfaces, l3Types, l3Base ; type Pl3MemoryBlock = ^Tl3MemoryBlock; Tl3MemoryBlock = packed object public // public methods rNext : Pl3MemoryBlock; rFree : Cardinal; end;//Tl3MemoryBlock Tl3SimpleMemoryManager = class(Tl3Base, Il3MemoryManager) {* Простейший менеджер памяти, выделяющий сразу большие куски. } protected // internal fields f_AllocCount : Integer; private // internal fields f_Head : Pl3MemoryBlock; f_BlockSize : Cardinal; f_CS : TRTLCriticalSection; protected // internal methods procedure AllocNewBlock; {-} function CanFreeBlocks: Boolean; virtual; {-} procedure FreeBlocks; virtual; {-} procedure DoGetMem(var P; aSize : Cardinal); virtual; {* - выделяет блок памяти. } procedure DoFreeMem(var P); virtual; {* - освобождает блок памяти. } procedure Cleanup; override; {-} public {$ifdef MMTrace} f_GlobalAlloc : Integer; {$EndIf} // public methods constructor Create(aBlockSize: Cardinal); reintroduce; virtual; {* - создает менеджер. } procedure GetMem(var P; aSize : Cardinal); {* - выделяет блок памяти. } procedure FreeMem(var P); {* - освобождает блок памяти. } end;//Tl3SimpleMemoryManager Tl3SizedPoolManager = class(Tl3SimpleMemoryManager) {* Менеджер "массивов". } private // internal fields f_ItemSize : Cardinal; public // public methods constructor Create(aBlockSize : Cardinal; anItemSize : Cardinal); reintroduce; {* - создает менеджер. } procedure AllocItem(var theItem; aLength : Cardinal); {* - распределяет элемент. } procedure FreeItem(var theItem); {* - освобождает элемент. } function ItemLength(anItem: Pointer): Long; {* - возвращает длину элемента. } end;//Tl3SizedPoolManager Tl3WideStringManager = class(Tl3SizedPoolManager) {* Менеджер Unicode-строк. } public // public methods constructor Create(aBlockSize: Long); reintroduce; {* - создает менеджер. } function AllocString(const aString: WideString): PWideChar; {* - распределяет строку. } procedure FreeString(var theString: PWideChar); {* - освобождает строку. } function StringAsPCharLen(aString: PWideChar): Tl3PCharLen; {* - приводит строку к Tl3PChatLen. } function StringAsWideString(aString: PWideChar): WideString; {* - приводит строку к WideString. } end;//Tl3WideStringManager implementation uses SysUtils, l3String ; // start class Tl3SimpleMemoryManager constructor Tl3SimpleMemoryManager.Create(aBlockSize: Cardinal); //reintroduce; {* - создает менеджер. } begin InitializeCriticalSection(f_CS); inherited Create; f_BlockSize := aBlockSize; AllocNewBlock; f_BlockSize := l3System.GlobalSize(f_Head) // - берем все, что винды выделили //- SizeOf(Tl3MemoryBlock) // - вычитаем размер заголовка ; end; procedure Tl3SimpleMemoryManager.Cleanup; //override; {-} begin {$IfDef l3AssertSimpleMMCanFreeBlocks} Assert(CanFreeBlocks); {$EndIf l3AssertSimpleMMCanFreeBlocks} FreeBlocks; inherited; DeleteCriticalSection(f_CS); end; function Tl3SimpleMemoryManager.CanFreeBlocks: Boolean; //virtual; {-} begin Result := (f_AllocCount = 0); end; procedure Tl3SimpleMemoryManager.FreeBlocks; {-} var l_Next : Pl3MemoryBlock; begin while (f_Head <> nil) do begin l_Next := f_Head^.rNext; l3System.GlobalFreePtr(Pointer(f_Head)); f_Head := l_Next; end;//while (f_Head <> nil) {$ifdef MMTrace} f_GlobalAlloc := 0; {$EndIf} end; procedure Tl3SimpleMemoryManager.AllocNewBlock; {-} var l_New : Pl3MemoryBlock; begin l_New := l3System.GlobalAllocPtr(f_BlockSize); {$ifdef MMTrace} inc(f_GlobalAlloc, f_BlockSize); {$EndIf} Assert(l_New <> nil); with l_New^ do begin rFree := l3System.GlobalSize(l_New) - SizeOf(l_New^); rNext := f_Head; end;//with l_New^ f_Head := l_New; end; procedure RaiseBlockSizeError; begin raise EOutOfMemory.Create('Размер блока больше размера страницы.'); end; procedure Tl3SimpleMemoryManager.GetMem(var P; aSize : Cardinal); {* - выделяет блок памяти. } begin EnterCriticalSection(f_CS); try DoGetMem(P, aSize); finally LeaveCriticalSection(f_CS); end;//try..finally end; procedure Tl3SimpleMemoryManager.FreeMem(var P); {* - освобождает блок памяти. } begin EnterCriticalSection(f_CS); try DoFreeMem(P); finally LeaveCriticalSection(f_CS); end;//try..finally end; procedure Tl3SimpleMemoryManager.DoGetMem(var P; aSize : Cardinal); {* - выделяет блок памяти. } var l_Free : Cardinal; begin if (aSize > f_BlockSize) then RaiseBlockSizeError; if (aSize = 0) then Pointer(P) := nil else begin if (f_Head = nil) then l_Free := 0 else l_Free := f_Head^.rFree; if (l_Free < aSize) then AllocNewBlock; Pointer(P) := PAnsiChar(f_Head) + f_BlockSize - f_Head^.rFree; Dec(f_Head^.rFree, aSize); Inc(f_AllocCount); end;//aSize = 0 end; procedure Tl3SimpleMemoryManager.DoFreeMem(var P); {* - освобождает блок памяти. } begin if (Pointer(P) <> nil) then begin Dec(f_AllocCount); Pointer(P) := nil; if CanFreeBlocks then FreeBlocks; end;//Pointer(P) <> nil end; // start class Tl3SizedPoolManager constructor Tl3SizedPoolManager.Create(aBlockSize : Cardinal; anItemSize : Cardinal); //reintroduce; {* - создает менеджер. } begin inherited Create(Longword(Int64(aBlockSize) * Int64(anItemSize))); // Int64 нужен, чтобы `dcc32.exe` не выдавал ошибку `C13310`. f_ItemSize := anItemSize; end; procedure Tl3SizedPoolManager.AllocItem(var theItem; aLength : Cardinal); {* - распределяет элемент. } begin GetMem(theItem, aLength * f_ItemSize + SizeOf(aLength)); PLong(theItem)^ := aLength; Inc(PAnsiChar(theItem), SizeOf(aLength)); end; procedure Tl3SizedPoolManager.FreeItem(var theItem); {* - освобождает элемент. } begin FreeMem(theItem); end; function Tl3SizedPoolManager.ItemLength(anItem: Pointer): Long; {* - возвращает длину элемента. } begin if (anItem = nil) then Result := 0 else Result := PLong(PAnsiChar(anItem) - SizeOf(Result))^; end; // start class Tl3WideStringManager constructor Tl3WideStringManager.Create(aBlockSize: Long); //reintroduce; {* - создает менеджер. } begin inherited Create(aBlockSize, SizeOf(WideChar)); end; function Tl3WideStringManager.AllocString(const aString: WideString): PWideChar; {* - распределяет строку. } var l_Length : Cardinal; begin l_Length := Length(aString); AllocItem(Result, l_Length); // - надо бы посмотреть - нужно ли что-то распределять, если длина нулевая if (l_Length > 0) then l3Move(aString[1], Result^, l_Length * f_ItemSize); end; procedure Tl3WideStringManager.FreeString(var theString: PWideChar); {* - освобождает строку. } begin FreeItem(theString); end; function Tl3WideStringManager.StringAsPCharLen(aString: PWideChar): Tl3PCharLen; {* - приводит строку с Tl3PChatLen. } begin Result := l3PCharLen(aString, ItemLength(aString)); end; function Tl3WideStringManager.StringAsWideString(aString: PWideChar): WideString; {* - приводит строку к WideString. } begin SetString(Result, aString, ItemLength(aString)); end; end.
unit k2List; { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2List - } { Начат: 22.02.99 19:26 } { $Id: k2List.pas,v 1.102 2011/07/11 17:48:11 lulin Exp $ } // $Log: k2List.pas,v $ // Revision 1.102 2011/07/11 17:48:11 lulin // {RequestLink:228688745}. // // Revision 1.101 2010/01/11 13:17:28 lulin // {RequestLink:175967380}. Правим комментарий. // // Revision 1.100 2009/07/21 18:23:16 lulin // - подготавливаемся к уменьшению преобразования типов при записи атрибутов. // // Revision 1.99 2009/07/20 16:44:07 lulin // - убираем из некоторых листьевых параграфов хранение типа конкретного тега, вместо этого "плодим" под каждый тип тега свой тип класса. // // Revision 1.98 2009/07/17 13:47:23 lulin // - bug fix: неправильно обрабатывали удаление дочерних тегов. // // Revision 1.97 2009/07/16 12:58:18 lulin // - подготавливаемся к объединения списков параграфов с листами. // // Revision 1.95 2009/07/15 16:15:28 lulin // - избавляемся от лишней виртуальности. // // Revision 1.94 2009/07/15 15:12:25 lulin // - удалено ненужное свойство списков параграфов. // // Revision 1.93 2009/07/15 12:34:45 lulin // - списки тегов прирастают по одному элементу. // // Revision 1.92 2009/07/07 16:54:42 lulin // - уменьшаем число дёрганий счётчика ссылок. // // Revision 1.91 2009/07/07 08:58:27 lulin // - вычищаем ненужное. // // Revision 1.90 2009/07/03 16:24:13 lulin // - шаг к переходу от интерфейсов к объектам. // // Revision 1.89 2009/04/07 15:11:49 lulin // [$140837386]. №13. Чистка кода. // // Revision 1.88 2009/03/25 10:34:14 lulin // - чистка кода. // // Revision 1.87 2009/03/04 17:20:04 lulin // - <K>: 137470629. Избавляемся от ненужного использования интерфейса. // // Revision 1.86 2009/02/26 17:28:41 lulin // - <K>: 137465982. №20. // // Revision 1.85 2009/02/26 10:21:28 lulin // - <K>: 137465982. №1 // // Revision 1.84 2009/02/25 15:55:44 lulin // - <K>: 90441983. Переносим на модель. // // Revision 1.83 2009/02/25 12:44:16 lulin // - <K>: 90441983. Чистка кода для переноса на модель. // // Revision 1.82 2008/09/16 11:51:55 lulin // - переносим TnevParaList на модель. // // Revision 1.81 2008/04/15 08:25:46 dinishev // Восстанавливаем старый редактор // // Revision 1.80 2008/03/20 09:48:38 lulin // - cleanup. // // Revision 1.79 2008/02/21 15:12:36 lulin // - упрощаем наследование. // // Revision 1.78 2008/02/21 13:48:21 lulin // - cleanup. // // Revision 1.77 2008/02/18 19:32:04 lulin // - распиливаем поиск. // // Revision 1.76 2008/02/14 19:32:38 lulin // - изменены имена файлов с примесями. // // Revision 1.75 2008/02/14 09:40:42 lulin // - удалён ненужный класс. // // Revision 1.74 2008/02/13 16:03:12 lulin // - убраны излишне гибкие методы поиска. // // Revision 1.73 2008/02/13 12:26:20 lulin // - <TDN>: 72. // // Revision 1.72 2008/02/11 14:22:43 lulin // - bug fix: неправильно искали данные в списке тегов. // // Revision 1.71 2008/02/08 19:52:43 lulin // - продолжаем санацию списков. // // Revision 1.70 2008/02/08 17:59:19 lulin // - теперь теги в списках храним как теги, а не как объекты. // // Revision 1.69 2008/02/08 17:06:20 lulin // - класс _Tk2TagObject переехал на модель. // // Revision 1.68 2008/02/07 16:19:20 lulin // - наводим порядок с наследованием и перекрытием методов. // // Revision 1.67 2008/02/06 15:37:08 lulin // - каждому базовому объекту по собственному модулю. // // Revision 1.66 2008/02/05 09:58:09 lulin // - выделяем базовые объекты в отдельные файлы и переносим их на модель. // // Revision 1.65 2008/01/30 14:25:17 lulin // - bug fix: неинициализированная переменная. // // Revision 1.64 2007/09/14 13:26:19 lulin // - объединил с веткой B_Tag_Clean. // // Revision 1.63.2.5 2007/09/12 18:37:48 lulin // - с интерфейса удален ненужный метод. // // Revision 1.63.2.4 2007/09/12 18:03:17 lulin // - убран ненужный промежуточный метод. // // Revision 1.63.2.3 2007/09/12 17:32:28 lulin // - убрана ненужная установки типа элемента списка. // // Revision 1.63.2.2 2007/09/12 17:27:51 lulin // - используем объект вместо интерфейса. // // Revision 1.63.2.1 2007/09/12 16:14:12 lulin // - убран ненужный параметр по-умолчанию. // // Revision 1.63 2007/09/06 09:37:45 lulin // - переименовано свойство. // // Revision 1.62 2007/09/05 18:08:17 lulin // - убираем накладные расходы. // // Revision 1.61 2007/09/05 13:38:52 lulin // - bug fix: не устанавливалась ссылка (CQ OIT5-26613). // // Revision 1.60 2007/09/04 18:41:31 lulin // - убран ненужный параметр. // // Revision 1.59 2007/09/04 18:06:22 lulin // - cleanup. // // Revision 1.58 2007/09/04 17:44:55 lulin // - cleanup. // // Revision 1.57 2007/09/04 17:27:43 lulin // - убран ненужный параметр. // // Revision 1.56 2007/09/04 14:24:59 lulin // - убран ненужный параметр. // // Revision 1.55 2007/09/03 10:46:48 lulin // - уменьшаем число параметров. // // Revision 1.54 2007/08/31 16:06:30 lulin // - cleanup. // // Revision 1.53 2007/08/21 12:43:31 lulin // - избавляемся от предупреждений компилятора. // // Revision 1.52 2007/03/19 11:42:06 voba // - new realization function _ExpandSize // // Revision 1.51 2006/07/21 11:40:31 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.50 2006/07/21 11:36:39 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.49 2006/04/25 07:26:25 lulin // - упорядочена работа с сортировкой списков и поиском в них. // - начат класс, для хранения записей фиксированного размера. // // Revision 1.48 2006/04/11 16:35:37 lulin // - оптимизируем при помощи вынесения строк (по следам того как Вован наиграл в фильтрах 20% производительности). // // Revision 1.47 2006/01/18 08:54:36 lulin // - изыскания на тему прямой установки целочисленных атрибутов, без преобразования их к тегам. // // Revision 1.46 2006/01/17 15:10:41 lulin // - выделен метод установки атрибута тега. // // Revision 1.45 2006/01/16 16:41:44 lulin // - сделана возможность работать со строками без теговых оберток (почему-то на производительность не повлияло). // // Revision 1.44 2005/12/13 15:38:33 fireton // - bug fix: не заполнялся индекс при поиске ребенка // // Revision 1.43 2005/11/03 16:33:49 lulin // - optimization: при переформатировании документа итерируем только непрогруженные параграфы. // // Revision 1.42 2005/11/02 13:47:42 lulin // - bug fix: ссылки, вставляемые в комментарий из буфера обмена переставали быть ссылками (CQ OIT5-17402). // // Revision 1.41 2005/04/28 15:04:09 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.40.2.10 2005/04/25 15:25:33 lulin // - не сигнализируем никому, если свойство реалтно не поменялось. // // Revision 1.40.2.9 2005/04/25 12:31:51 lulin // - создаем _Tk2List по "правильному". // // Revision 1.40.2.8 2005/04/23 16:07:35 lulin // - удален временный интерфейс Ik2TagBox. // // Revision 1.40.2.7 2005/04/23 13:32:20 lulin // - new define: k2BoxIsList. // // Revision 1.40.2.6 2005/04/23 12:44:13 lulin // - cleanup. // // Revision 1.40.2.5 2005/04/22 12:14:29 lulin // - remove interface: Ik2PropertyBag. // // Revision 1.40.2.4 2005/04/22 09:04:37 lulin // - cleanup: убраны ненужные параметры. // // Revision 1.40.2.3 2005/04/21 17:28:16 lulin // - cleanup. // // Revision 1.40.2.2 2005/04/21 16:30:20 lulin // - избавился от лишних оберточных классов. // // Revision 1.40.2.1 2005/04/21 14:47:02 lulin // - избавляемся от обертки над тегами - теперь объекты посредством шаблонов сами реализуют интерфейс Ik2Tag. // // Revision 1.40 2005/04/21 06:53:43 lulin // - функция сравнения перенесена в шаблон. // // Revision 1.39 2005/04/21 06:42:31 lulin // - cleanup. // // Revision 1.38 2005/04/21 06:33:32 lulin // - привел списки в порядок. // // Revision 1.37 2005/04/21 05:36:05 lulin // - cleanup. // // Revision 1.36 2005/04/21 05:27:04 lulin // - в шаблонах объединил интерфейс и реализацию - чтобы удобнее читать/править было. // // Revision 1.35 2005/04/21 05:11:48 lulin // - используем Box (пока из-за постоянных преобразований туда и обратно - по скорости стало только хуже). // // Revision 1.34 2005/04/20 17:40:57 lulin // - избавился от промежуточного интерфейса Ik2TagBoxQT. // // Revision 1.33 2005/04/20 16:31:20 lulin // - добавлен шаблон для реализации собственно тега. // // Revision 1.32 2005/04/20 16:09:46 lulin // - используем шаблон. // // Revision 1.31 2005/04/20 15:16:46 lulin // - new method: Ik2TagBox.rLong. // // Revision 1.30 2005/04/20 13:38:45 lulin // - new method: Ik2TagBox.InheritsFrom. // // Revision 1.29 2005/04/16 13:17:13 lulin // - не ходим окольным путем за тем, что лежит рядом. // // Revision 1.28 2005/04/16 12:38:22 lulin // - не ходим окольным путем за тем, что лежит рядом. // // Revision 1.27 2005/04/16 12:31:48 lulin // - не ходим окольным путем за тем, что лежит рядом. // // Revision 1.26 2005/04/15 08:59:57 lulin // - теперь держим ссылку на тег, а не собственно тег. // // Revision 1.25.2.1 2005/04/15 08:21:38 lulin // - теперь держим ссылку на тег, а не собственно тег. // // Revision 1.25 2005/04/04 17:07:06 lulin // - new methods: InevShape._ParentToClient, _ClientToParent. // // Revision 1.24 2005/03/24 12:08:21 lulin // - remove method: Ik2TagBox.Tag. // - new method: Ik2TagBox._Target. // // Revision 1.23 2005/03/23 15:29:20 lulin // - итератор по свойствам внутри тега приобрел нормальный вид, а не какой-то шаманский. // // Revision 1.22 2005/03/22 09:53:03 lulin // - убраны ненужные преобразования между Tk2AtomR и Ik2Tag. // // Revision 1.21 2005/03/19 16:40:04 lulin // - спрятаны ненужные методы. // // Revision 1.20 2004/06/01 13:48:16 law // - используем _Tl3LongintList. // // Revision 1.19 2004/06/01 09:07:17 law // - change: класс _Tk2Layer унаследован от Tl3CObjectRefList. // // Revision 1.18 2004/05/31 11:01:59 law // - new method: Ik2PropertyBag.SetMaskEx. // // Revision 1.17 2004/05/31 10:26:01 law // - _Tk2Layer сделан кешируемым. // // Revision 1.16 2004/04/12 14:59:27 law // - remove prop: Ik2PropertyBag.Empty. // // Revision 1.15 2003/12/17 16:36:14 law // - some optimization. // // Revision 1.14 2002/11/20 16:18:45 voba // - bug fix: исправлена предыдущая заглушка. // // Revision 1.13 2002/11/20 13:49:59 law // - stub: Заглушка для исправления неверно сохраненных Sub'ов. Со временем надо убрать. // // Revision 1.12 2002/11/20 13:14:34 law // - bug fix: неправильно брался _Handle от _Tk2Layer при переборе свойств. // // Revision 1.11 2002/11/19 15:09:11 law // - new behavior: обрабатываем параметр AssignTransparent. // // Revision 1.10 2002/01/29 16:18:49 law // - bug fix: Range Check Error при записывании размера маски. // // Revision 1.9 2001/02/28 13:15:03 law // - расширен интерфейс Ik2PropertyBag. // // Revision 1.8 2001/02/20 10:23:52 law // - some tuning // // Revision 1.7 2000/12/15 15:18:58 law // - вставлены директивы Log. // {$Include k2Define.inc } interface uses Classes, l3Types, l3Interfaces, l3IID, l3Base, l3Except, l3Const, l3CObjectRefList, k2InternalInterfaces, k2BaseTypes, k2Interfaces, k2Base, k2BaseStruct, k2TagList ; type _k2Tag_Parent_ = Tk2TagList; {$Define k2TagIsList} {$Define k2TagComplexAssign} // - !!! http://mdp.garant.ru/pages/viewpage.action?pageId=228688745&focusedCommentId=273590280#comment-273590280 !!! {$Include k2Tag.imp.pas} Tk2List = class(_k2Tag_) protected function ExpandSize(aTargetSize: Integer): Integer; override; public // public methods constructor Create(aTagType: Tk2Type); reintroduce; {-} end;//Tk2List implementation uses TypInfo, SysUtils, l3String, l3Stream, l3Dict, k2Const, k2Tags, k2Except, k2Strings, k2Facade ; type _Instance_R_ = Tk2List; {$Include k2Tag.imp.pas} // start class Tk2List constructor Tk2List.Create(aTagType: Tk2Type); //reintroduce; {-} var l_Prop : Tk2ArrayProperty; begin f_TagType := aTagType; inherited Create; l_Prop := TagType.ArrayProp[k2_tiChildren]; if (l_Prop.SortIndex = k2_tiSelfID) then Sorted := false else begin SortIndex := l_Prop.SortIndex; Duplicates := l_Prop.Duplicates; end;//l_Prop.SortIndex = k2_tiSelfID end; function Tk2List.ExpandSize(aTargetSize: Integer): Integer; begin if aTargetSize = 0 then Result := Succ(Capacity) else Result := aTargetSize; end;//Tk2List.ExpandSize end.
unit G2Mobile.Controller.FormaPagamento; interface uses FMX.ListView, System.Classes, Datasnap.DBClient, FireDAC.Comp.Client, FMX.Objects; type iModelFormaPagamento = interface ['{41C159D2-C15E-4FE4-BFA8-BED2E1B4F9C3}'] function BuscaFormaPagamentoServidor(ADataSet: TFDMemTable): iModelFormaPagamento; function PopulaFormaPagamentoSqLite(ADataSet: TFDMemTable): iModelFormaPagamento; function BuscaPagamentoPessoaServidor(ADataSet: TFDMemTable): iModelFormaPagamento; function PopulaPagamentoPessoaSqLite(ADataSet: TFDMemTable): iModelFormaPagamento; function LimpaTabelaFormaPagamento: iModelFormaPagamento; function LimpaTabelaPagamentoPessoa: iModelFormaPagamento; function PopulaListView(Cod: integer; value: TListView; imageForma: Timage): iModelFormaPagamento; function BuscarFormaPagamento(value: integer): String; function BuscaUltimaFormaDePagamentoCliente(value: integer): String; end; implementation end.
unit MdPersonalData; interface uses SysUtils, Classes, Controls, StdCtrls; type TMdPersonalData = class(TComponent) private FAge: Integer; FLastName: string; FFirstName: string; fLabel: TLabel; function GetDescription: string; procedure SetAge(const Value: Integer); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); procedure SetLabel(const Value: TLabel); procedure UpdateLabel; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property FirstName: string read FFirstName write SetFirstName; property LastName: string read FLastName write SetLastName; property Age: Integer read FAge write SetAge; property Description: string read GetDescription; property OutLabel: TLabel read fLabel write SetLabel; end; procedure Register; implementation procedure Register; begin RegisterComponents('Md', [TMdPersonalData]); end; { TMdPersonalData } function TMdPersonalData.GetDescription: string; begin Result := FFirstName + ' ' + FLastName + ' (' + IntToStr (fAge) + ')'; end; procedure TMdPersonalData.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; // remove reference when external component is destroyed if (AComponent = fLabel) and (Operation = opRemove) then fLabel := nil; end; procedure TMdPersonalData.SetAge(const Value: Integer); begin if FAge <> Value then begin FAge := Value; UpdateLabel; end; end; procedure TMdPersonalData.SetFirstName(const Value: string); begin if FFirstName <> Value then begin FFirstName := Value; UpdateLabel; end; end; procedure TMdPersonalData.SetLabel(const Value: TLabel); begin if fLabel <> Value then begin fLabel := Value; if fLabel <> nil then begin UpdateLabel; fLabel.FreeNotification (Self); end; end; end; procedure TMdPersonalData.SetLastName(const Value: string); begin if FLastName <> Value then begin FLastName := Value; UpdateLabel; end; end; procedure TMdPersonalData.UpdateLabel; begin if Assigned (fLabel) then fLabel.Caption := Description; end; end.
unit SearchAndReplaceTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Модуль: "w:/common/components/gui/Garant/Daily/SearchAndReplaceTest.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TSearchAndReplaceTest // // Тест поиска/замены // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses SearchAndReplacePrimTest, nevTools, evTypes ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TSearchAndReplaceTest = {abstract} class(TSearchAndReplacePrimTest) {* Тест поиска/замены } protected // realized methods function Searcher: IevSearcher; override; function Replacer: IevReplacer; override; function Options: TevSearchOptionSet; override; protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } protected // protected methods function StringForSearch: AnsiString; virtual; abstract; {* Строка для поиска } function StringForReplace: AnsiString; virtual; abstract; {* Строка для замены } end;//TSearchAndReplaceTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses evSearch, TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TSearchAndReplaceTest function TSearchAndReplaceTest.Searcher: IevSearcher; //#UC START# *4C288BAA0058_4BE04F030356_var* //#UC END# *4C288BAA0058_4BE04F030356_var* begin //#UC START# *4C288BAA0058_4BE04F030356_impl* Result := TevBMTextSearcher.Make(StringForSearch, Options); //#UC END# *4C288BAA0058_4BE04F030356_impl* end;//TSearchAndReplaceTest.Searcher function TSearchAndReplaceTest.Replacer: IevReplacer; //#UC START# *4C288BFC002C_4BE04F030356_var* //#UC END# *4C288BFC002C_4BE04F030356_var* begin //#UC START# *4C288BFC002C_4BE04F030356_impl* Result := TevTextReplacer.Make(StringForReplace, Options); //#UC END# *4C288BFC002C_4BE04F030356_impl* end;//TSearchAndReplaceTest.Replacer function TSearchAndReplaceTest.Options: TevSearchOptionSet; //#UC START# *4C288CC60231_4BE04F030356_var* //#UC END# *4C288CC60231_4BE04F030356_var* begin //#UC START# *4C288CC60231_4BE04F030356_impl* Result := [ev_soGlobal, ev_soReplace, ev_soReplaceAll]; //#UC END# *4C288CC60231_4BE04F030356_impl* end;//TSearchAndReplaceTest.Options function TSearchAndReplaceTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TSearchAndReplaceTest.GetFolder function TSearchAndReplaceTest.GetModelElementGUID: AnsiString; {-} begin Result := '4BE04F030356'; end;//TSearchAndReplaceTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit VCMSandBoxRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Модуль: "VCMSandBoxRes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: VCMApplication::Class Shared Delphi Sand Box$App::VCMSandBox::VCMSandBox // // Тестовое приложение VCM // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {$Include ..\VCM\sbDefine.inc} interface uses Classes {$If not defined(NoVCM)} , vcmApplication {$IfEnd} //not NoVCM , l3StringIDEx, vcmInterfaces {a}, vcmExternalInterfaces {a}, vcmMainForm {a} ; var { Локализуемые строки Local } str_VCMSandBoxTitle : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'VCMSandBoxTitle'; rValue : 'Тестовое приложение VCM'); { 'Тестовое приложение VCM' } type TVCMSandBoxRes = {final} class(TvcmApplication) {* Тестовое приложение VCM } protected procedure RegisterFormSetFactories; override; class procedure RegisterModules(aMain: TvcmMainForm); override; procedure Loaded; override; public // modules operations class function DocumentPrintAndExportDefaultSetting: Boolean; {* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати размер шрифта, отображаемого на экране" } class function DocumentPrintAndExportCustomSetting: Boolean; {* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати следующий размер шрифта" } class function DocumentPrintAndExportFontSizeSetting: Integer; {* Метод для получения значения настройки "Использовать для экспорта и печати следующий размер шрифта" } class procedure WriteDocumentPrintAndExportFontSizeSetting(aValue: Integer); {* Метод для записи значения настройки "Использовать для экспорта и печати следующий размер шрифта" } class function ListPrintAndExportDefaultSetting: Boolean; {* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати размер шрифта, отображаемого на экране" } class function ListPrintAndExportCustomSetting: Boolean; {* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати следующий размер шрифта" } class function ListPrintAndExportFontSizeSetting: Integer; {* Метод для получения значения настройки "Использовать для экспорта и печати следующий размер шрифта" } class procedure WriteListPrintAndExportFontSizeSetting(aValue: Integer); {* Метод для записи значения настройки "Использовать для экспорта и печати следующий размер шрифта" } end;//TVCMSandBoxRes TvcmApplicationRef = TVCMSandBoxRes; {* Ссылка на приложение для DesignTime редакторов } implementation uses moDocument, moList, l3MessageID, evExtFormat {$If not defined(NoVCM)} , StdRes {$IfEnd} //not NoVCM , Document_Module, List_Module ; // start class TVCMSandBoxRes procedure TVCMSandBoxRes.RegisterFormSetFactories; begin inherited; end; class procedure TVCMSandBoxRes.RegisterModules(aMain: TvcmMainForm); begin inherited; aMain.RegisterModule(Tmo_Document); aMain.RegisterModule(Tmo_List); end; procedure TVCMSandBoxRes.Loaded; begin inherited; PublishModule(Tmo_Document, 'Документ'); PublishModule(Tmo_List, 'Список'); end; // modules operations class function TVCMSandBoxRes.DocumentPrintAndExportDefaultSetting: Boolean; begin Result := TDocumentModule.DocumentPrintAndExportDefaultSetting; end; class function TVCMSandBoxRes.DocumentPrintAndExportCustomSetting: Boolean; begin Result := TDocumentModule.DocumentPrintAndExportCustomSetting; end; class function TVCMSandBoxRes.DocumentPrintAndExportFontSizeSetting: Integer; begin Result := TDocumentModule.DocumentPrintAndExportFontSizeSetting; end; class procedure TVCMSandBoxRes.WriteDocumentPrintAndExportFontSizeSetting(aValue: Integer); begin TDocumentModule.WriteDocumentPrintAndExportFontSizeSetting(aValue); end; class function TVCMSandBoxRes.ListPrintAndExportDefaultSetting: Boolean; begin Result := TListModule.ListPrintAndExportDefaultSetting; end; class function TVCMSandBoxRes.ListPrintAndExportCustomSetting: Boolean; begin Result := TListModule.ListPrintAndExportCustomSetting; end; class function TVCMSandBoxRes.ListPrintAndExportFontSizeSetting: Integer; begin Result := TListModule.ListPrintAndExportFontSizeSetting; end; class procedure TVCMSandBoxRes.WriteListPrintAndExportFontSizeSetting(aValue: Integer); begin TListModule.WriteListPrintAndExportFontSizeSetting(aValue); end; initialization // Инициализация str_VCMSandBoxTitle str_VCMSandBoxTitle.Init; end.
unit Unt_Principal; 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.Samples.Gauges, Vcl.ExtCtrls; type TLoopThread = class(TThread) private FTempoTranscorrido: Integer; procedure ZerarProgressBar; procedure IncrementarProgressBar; protected procedure Execute; override; public property TempoTranscorrido: Integer read FTempoTranscorrido; end; TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; btnLoop: TButton; btnSeep: TButton; RadioGroup1: TRadioGroup; Gauge1: TGauge; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnLoopClick(Sender: TObject); procedure btnSeepClick(Sender: TObject); private FQuantidade: Integer; procedure EventOnTerminate(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation uses Diagnostics; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin Inc(Self.FQuantidade); Self.Memo1.Lines.Insert(0, Format('Botão acionado! [%d]', [Self.FQuantidade])); end; procedure TForm1.btnLoopClick(Sender: TObject); var oThread: TLoopThread; begin Self.btnLoop.Enabled := False; oThread := TLoopThread.Create(True); oThread.OnTerminate := Self.EventOnTerminate; oThread.FreeOnTerminate := True; oThread.Start; end; procedure TForm1.btnSeepClick(Sender: TObject); begin Sleep(5000); end; procedure TForm1.EventOnTerminate(Sender: TObject); var iTempo: Integer; begin iTempo := TLoopThread(Sender).TempoTranscorrido; ShowMessage(Format('Loop executado em [%d] segundos', [iTempo])); Self.btnLoop.Enabled := True; end; procedure TForm1.FormCreate(Sender: TObject); begin Self.Button1.Caption := IntToStr(Self.Button1.Handle); end; { TLoopThread } procedure TLoopThread.Execute; var rCronus: TStopwatch; i : Integer; iTempo : Integer; begin Self.FTempoTranscorrido := -1; rCronus := TStopwatch.StartNew; case Form1.RadioGroup1.ItemIndex of 0: Self.ZerarProgressBar; 1: Self.Synchronize(Self.ZerarProgressBar); 2: Self.Queue(Self.ZerarProgressBar); end; for i := 1 to 15 do begin Sleep(1000); case Form1.RadioGroup1.ItemIndex of 0: Self.IncrementarProgressBar; 1: Self.Synchronize(Self.IncrementarProgressBar); 2: Self.Queue(Self.IncrementarProgressBar); end; end; rCronus.Stop; iTempo := (rCronus.ElapsedMilliseconds div 1000); Self.FTempoTranscorrido := iTempo; end; procedure TLoopThread.IncrementarProgressBar; begin Form1.Gauge1.AddProgress(1); end; procedure TLoopThread.ZerarProgressBar; begin Form1.Gauge1.MaxValue := 15; Form1.Gauge1.Progress := 0; end; end.
{*******************************************************} { } { Delphi FireMonkey Notification Service } { } { Description of interface for notificatione center } { } { Local notifications are ways for an application } { that isnít running in the foreground to let its } { users know it has information for them. } { The information could be a message, an impending } { calendar event. When presented by the operating } { system, local notifications look and sound } { the same. They can display an alert message or } { they can badge the application icon. They can } { also play a sound when the alert or badge number } { is shown. } { } { Copyright(c) 2012-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.Notification; interface type /// <summary> /// Discription of notification for Notification Center /// </summary> TNotification = class public // Unique identificator for determenation notification in Notification list Name: string; AlertBody: string; AlertAction: string; ApplicationIconBadgeNumber: Integer; FireDate: TDateTime; EnableSound: Boolean; HasAction: Boolean; end; /// <summary> /// Interface for work with notification center in Apple's platforms /// </summary> IFMXNotificationCenter = interface ['{5C3C0232-26EF-45D9-A351-336ECE49EABA}'] /// <summary> /// Schedules a local notification for delivery at its /// encapsulated date and time. /// </summary> procedure ScheduleNotification(const ANotification: TNotification); /// <summary> /// Presents a local notification immediately. /// </summary> procedure PresentNotification(const ANotification: TNotification); /// <summary> /// Cancels the delivery of the specified scheduled local notification. /// <param name="AName">Unique identificator of notification</param> /// </summary> procedure CancelNotification(const AName: string); overload; /// <summary> /// Cancels the delivery of the specified scheduled local notification. /// </summary> procedure CancelNotification(const ANotification: TNotification); overload; /// <summary> /// Cancels the delivery of all scheduled local notifications. /// </summary> procedure CancelAllNotifications; /// <summary> /// The number currently set as the badge of the application icon. /// </summary> procedure SetIconBadgeNumber(const ACount: Integer); /// <summary> /// Reset the number of the application icon. /// </summary> procedure ResetIconBadgeNumber; end; implementation {$IFDEF IOS} uses FMX.Notification.iOS; initialization RegisterNotificationService; {$ENDIF} end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. For more information, please refer to <http://unlicense.org>} unit httpserverunit; {$mode objfpc}{$H+} interface uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} SysUtils, Classes, EventLog, //Indy10.6.2.5494 (Laz Menu: Package, open indylaz_runtime.lpk, Use, Add to Project) IdBaseComponent, IdComponent, IdContext,IdSocketHandle, IdGlobal, IdGlobalProtocols, IdAssignedNumbers, IdCustomHTTPServer, IdHTTPServer; type { TServerThread } TServerThread = class(TThread) FLogFile: string; FIP: string; FPort: integer; FHome: string; procedure Execute; override; end; { TServer } TServer = Class(TIdHTTPServer) public LogFile: string; Home: string; procedure ServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); end; var Log: TEventLog; Server: TServer; implementation procedure WriteLog(const ET: TEventType; const msg: string); begin Log.Active:=True; //open log file Log.Log(ET, msg); Log.Active:=False; //close log file to unlock it end; { TServerThread } procedure TServerThread.Execute; var Binding: TIdSocketHandle; begin try Server:=TServer.Create(nil); with Server do begin; OnCommandGet := @ServerCommandGet; Scheduler := nil; //use default thread scheduler MaxConnections := 5; Home := FHome; LogFile := FLogFile; end; Log:=TEventLog.Create(nil); with Log do begin LogType := ltFile; Filename:=Server.LogFile; //default dir is C:\Windows\SysWOW64 DefaultEventType := etDebug; AppendContent := True; Active:=false; end; Server.Bindings.Clear; Binding := Server.Bindings.Add; Binding.IP := FIP; Binding.Port := FPort; Server.Active := true; WriteLog(etInfo, 'Server Started'); repeat Sleep(1000); until not true; finally Server.Free; end; end; { TServer } procedure TServer.ServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var LocalDoc: string; begin LocalDoc:=ARequestInfo.URI; If (Length(LocalDoc)>0) and (LocalDoc[1]='/') then Delete(LocalDoc,1,1); if LocalDoc='' then LocalDoc:=HOME + 'index.html' else LocalDoc:=HOME + LocalDoc; DoDirSeparators(LocalDoc); //fix back and forward slashes WriteLog(etDebug, 'LocalDoc=' + LocalDoc); AResponseInfo.ResponseNo := 200; AResponseInfo.ContentType := MimeTable.GetFileMIMEType(LocalDoc); AResponseInfo.ContentStream := TFileStream.Create(LocalDoc, fmOpenRead + fmShareDenyWrite); end; end.
unit VIORDmp; interface uses SysUtils, Types, Classes, Variants, {$IFDEF LINUX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} orb_int, orb, poa_int, poa_impl, exceptions, except_int, orbtypes, iior_int, ior; type TForm1 = class(TForm) Memo1: TMemo; Memo2: TMemo; Label1: TLabel; Label2: TLabel; Button1: TButton; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; Button3: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } IORFileName : String; strBaseCaption : String; IORFile : Text; Function FormatIOR(strIOR : string) : String; Function FileName(strFile : String) : String; Procedure ProduceInfo; Procedure LoadAndProduceInfo; public { Public declarations } end; var Form1: TForm1; implementation {$IFDEF LINUX} {$R *.xfm} {$ELSE} {$R *.dfm} {$ENDIF} function TForm1.FileName(strFile : String) : String; var strTemp : String; nPos : integer; begin strTemp := strFile; {$IFDEF LINUX} nPos := Pos('/',strTemp); {$ELSE} nPos := Pos('\',strTemp); {$ENDIF} while (nPos > 0) do begin if ((nPos + 1) < length(strTemp) ) then strTemp := copy(strTemp,nPos+1,length(strTemp)-(nPos)); {$IFDEF LINUX} nPos := Pos('/',strTemp); {$ELSE} nPos := Pos('\',strTemp); {$ENDIF} end; result := strTemp; end; function TForm1.FormatIOR(strIOR :String) : String; var strTemp : String; strTemp2 : String; begin //Combined w/ Word Wrap on Memo1 this formats nicely strTemp := ''; strTemp2 := strIOR; while (length(strTemp2) > 0) do begin strTemp := strTemp + copy(strTemp2,0,40); {$IFDEF LINUX} strTemp := strTemp + #13; {$ELSE} strTemp := strTemp + ' '; {$ENDIF} strTemp2 := copy(strTemp2,41,length(strTemp2)); end; Result := StrTemp; end; procedure TForm1.Button1Click(Sender: TObject); var StrTemp : String; begin if OpenDialog1.Execute then begin if FileExists(OpenDialog1.FileName) then begin IORFileName := OpenDialog1.FileName; StrTemp := FileName(IORFileName); Form1.Caption := strBaseCaption + ' : '+strTemp; LoadAndProduceInfo(); end else ShowMessage('File : '+OpenDialog1.FileName+' doesn''t exist,'); end; end; procedure TForm1.FormCreate(Sender: TObject); begin IORFileName := ''; strBaseCaption := Form1.Caption; end; procedure TForm1.ProduceInfo; var dOrb : IORB; Obj : IORBObject; Props : TStrings; ObjectIOR : IIOR; strOut : String; streamTemp : TStringStream; begin Props := TStringList.Create; streamTemp := TStringStream.Create(''); if (Pos('IOR',Memo1.Text) > 0) then begin try dOrb := ORB_Init(Props); assert((dOrb <> nil),'Invalid ORB Reference Returned'); obj := dOrb.string_to_object(AnsiString(Memo1.Text)); if (obj <> nil) then begin strOut := ''; ObjectIOR := obj._ior; streamTemp.Seek(0,soFromBeginning); ObjectIOR.print(streamTemp); strOut := streamTemp.DataString; if (strOut <> '') then begin Memo2.Lines.Clear; Memo2.Lines.Add(strOut); end; end; dOrb.do_shutdown; except ShowMessage('Fatal Error During Translation Process.'); end; end else ShowMessage('This Does not Appear to be a valid IOR.'); end; procedure TForm1.LoadAndProduceInfo; var strTemp : String; begin strTemp :=''; if (IORFileName <> '') then begin AssignFile(IORFile,IORFileName); Reset(IORFile); Readln(IORFile,strTemp); CloseFile(IORFile); if (Pos('IOR',strTemp) > 0) then begin //Could use Memo1.Lines.LoadFromFile() here //But I chose to format the loaded IOR from a //String //---Anyway, 6 of one half dozen of the other :) Memo1.Lines.Clear; //Memo1.Lines.Add( FormatIOR(strTemp)); Memo1.Lines.Add(strTemp); ProduceInfo(); end else ShowMessage('This Does not Appear to be a valid IOR.'); end else ShowMessage('Please Select A File.'); end; procedure TForm1.Button2Click(Sender: TObject); begin ProduceInfo(); end; procedure TForm1.Button3Click(Sender: TObject); begin if (SaveDialog1.Execute) then begin Memo2.Lines.SaveToFile(SaveDialog1.FileName); end; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clDkimSignature; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Contnrs, DateUtils, {$ELSE} System.Classes, System.SysUtils, System.Contnrs, System.DateUtils, {$ENDIF} clHeaderFieldList; type TclDkimVerifyStatus = (dssNone, dssVerified, dssFailed); TclDkimSignatureVerifyStatus = class private FErrorText: string; FStatus: TclDkimVerifyStatus; FErrorCode: Integer; procedure SetStatus(AStatus: TclDkimVerifyStatus; const AErrorText: string; AErrorCode: Integer); public constructor Create; procedure Clear; procedure SetVerified; procedure SetFailed(const AErrorText: string; AErrorCode: Integer); property Status: TclDkimVerifyStatus read FStatus; property ErrorCode: Integer read FErrorCode; property ErrorText: string read FErrorText; end; TclDkimSignature = class private FVersion: Integer; FSignatureTimestamp: TDateTime; FDomain: string; FUserIdentity: string; FBodyLength: Integer; FBodyHash: string; FPublicKeyLocation: string; FSignatureAlgorithm: string; FCopiedHeaderFields: TStrings; FSignature: string; FSignatureExpiration: TDateTime; FSignedHeaderFields: TStrings; FCanonicalization: string; FSelector: string; FStatus: TclDkimSignatureVerifyStatus; procedure Add(AFieldList: TclHeaderFieldList; const AName, AValue: string); procedure AddVersion(AFieldList: TclHeaderFieldList); procedure AddNotNull(AFieldList: TclHeaderFieldList; const AName, AValue: string); procedure AddBodyLength(AFieldList: TclHeaderFieldList); procedure AddDate(AFieldList: TclHeaderFieldList; const AName: string; AValue: TDateTime); procedure CheckTimestamp; function GetDomain: string; function GetUserIdentity: string; function GetCopiedHeaderFields: string; function GetSignedHeaderFields: string; function ParseVersion(const AValue: string): Integer; function ParseBodyLength(const AValue: string): Integer; function ParseDate(const AValue: string): TDateTime; function ParseNotNull(const AValue: string): string; procedure ParseCopiedHeaderFields(const AValue: string); procedure ParseSignedHeaderFields(const AValue: string); procedure SetCopiedHeaderFields(const Value: TStrings); procedure SetSignedHeaderFields(const Value: TStrings); function GetCanonicalization(IsHeader: Boolean): string; function GetHashAlgorithm: string; function GetBodyCanonicalization: string; function GetHeaderCanonicalization: string; public constructor Create; destructor Destroy; override; procedure Parse(AMessage: TStrings); overload; procedure Parse(const ADkimSignatureField: string); overload; virtual; procedure Build(AMessage: TStrings; ACharsPerLine: Integer); virtual; procedure AssignSignature(AMessage: TStrings; ACharsPerLine: Integer); virtual; procedure Clear; virtual; property Status: TclDkimSignatureVerifyStatus read FStatus; property Version: Integer read FVersion write FVersion; property SignatureAlgorithm: string read FSignatureAlgorithm write FSignatureAlgorithm; property Canonicalization: string read FCanonicalization write FCanonicalization; property Domain: string read FDomain write FDomain; property Selector: string read FSelector write FSelector; property SignedHeaderFields: TStrings read FSignedHeaderFields write SetSignedHeaderFields; property BodyLength: Integer read FBodyLength write FBodyLength; property UserIdentity: string read FUserIdentity write FUserIdentity; property PublicKeyLocation: string read FPublicKeyLocation write FPublicKeyLocation; property SignatureTimestamp: TDateTime read FSignatureTimestamp write FSignatureTimestamp; property SignatureExpiration: TDateTime read FSignatureExpiration write FSignatureExpiration; property CopiedHeaderFields: TStrings read FCopiedHeaderFields write SetCopiedHeaderFields; property Signature: string read FSignature write FSignature; property BodyHash: string read FBodyHash write FBodyHash; property HeaderCanonicalization: string read GetHeaderCanonicalization; property BodyCanonicalization: string read GetBodyCanonicalization; property HashAlgorithm: string read GetHashAlgorithm; end; TclDkimSignatureList = class private FList: TObjectList; function GetCount: Integer; function GetItem(Index: Integer): TclDkimSignature; public constructor Create; destructor Destroy; override; function Add(AItem: TclDkimSignature): TclDkimSignature; procedure Delete(Index: Integer); procedure Clear; property Items[Index: Integer]: TclDkimSignature read GetItem; default; property Count: Integer read GetCount; end; const cDkimSignatureField = 'DKIM-Signature'; implementation uses clUtils, clWUtils, clDkimUtils, clMailUtils, clIdnTranslator; { TclDkimSignature } procedure TclDkimSignature.AddVersion(AFieldList: TclHeaderFieldList); begin if (Version < 0) then begin raise EclDkimError.Create(DkimInvalidSignatureParameters, DkimInvalidSignatureParametersCode); end; Add(AFieldList, 'v', IntToStr(Version)); end; procedure TclDkimSignature.AssignSignature(AMessage: TStrings; ACharsPerLine: Integer); var fieldList: TclDkimHeaderFieldList; begin if (Trim(Signature) = '') then begin raise EclDkimError.Create(DkimInvalidSignatureParameters, DkimInvalidSignatureParametersCode); end; fieldList := TclDkimHeaderFieldList.Create(); try fieldList.CharsPerLine := ACharsPerLine; fieldList.Parse(0, AMessage); fieldList.RemoveFieldItem(cDkimSignatureField, 'b'); fieldList.AddFieldItem(cDkimSignatureField, 'b', Signature, True); finally fieldList.Free(); end; end; procedure TclDkimSignature.AddNotNull(AFieldList: TclHeaderFieldList; const AName, AValue: string); begin if (Trim(AValue) = '') then begin raise EclDkimError.Create(DkimInvalidSignatureParameters, DkimInvalidSignatureParametersCode); end; Add(AFieldList, AName, AValue); end; procedure TclDkimSignature.Add(AFieldList: TclHeaderFieldList; const AName, AValue: string); begin AFieldList.AddFieldItem(cDkimSignatureField, AName, AValue); end; procedure TclDkimSignature.AddBodyLength(AFieldList: TclHeaderFieldList); begin if (BodyLength > 0) then begin Add(AFieldList, 'l', IntToStr(BodyLength)); end; end; procedure TclDkimSignature.AddDate(AFieldList: TclHeaderFieldList; const AName: string; AValue: TDateTime); var d: TDateTime; sec: Int64; begin if (AValue > 0) then begin d := LocalTimeToGlobalTime(AValue); sec := SecondsBetween(d, EncodeDate(1970, 1, 1)); Add(AFieldList, AName, IntToStr(sec)); end; end; procedure TclDkimSignature.CheckTimestamp; begin if (SignatureTimestamp > 0) and (SignatureExpiration > 0) and (SignatureTimestamp >= SignatureExpiration) then begin raise EclDkimError.Create(DkimInvalidSignatureParameters, DkimInvalidSignatureParametersCode); end; end; function TclDkimSignature.GetDomain: string; begin Result := Domain; if (Trim(Result) <> '') then begin Result := TclIdnTranslator.GetAscii(Result); end; end; function TclDkimSignature.GetHashAlgorithm: string; begin if (WordCount(SignatureAlgorithm, ['-']) <> 2) then begin raise EclDkimError.Create(DkimInvalidSignatureAlgorihm, DkimInvalidSignatureAlgorihmCode); end; Result := ExtractWord(2, SignatureAlgorithm, ['-']); end; function TclDkimSignature.GetHeaderCanonicalization: string; begin Result := GetCanonicalization(True); end; function TclDkimSignature.GetUserIdentity: string; begin Result := UserIdentity; if (Trim(Result) <> '') then begin Result := TclDkimQuotedPrintableEncoder.Encode(GetIdnEmail(Result)); end; end; function TclDkimSignature.GetBodyCanonicalization: string; begin Result := GetCanonicalization(False); end; function TclDkimSignature.GetCanonicalization(IsHeader: Boolean): string; const section: array[Boolean] of Integer = (2, 1); begin Result := 'simple'; case WordCount(Canonicalization, ['/']) of 1: Result := Canonicalization; 2: Result := ExtractWord(section[IsHeader], Canonicalization, ['/']); end; end; function TclDkimSignature.GetCopiedHeaderFields: string; var i: Integer; begin Result := ''; for i := 0 to CopiedHeaderFields.Count - 1 do begin if not ((CopiedHeaderFields[i] <> '') and CharInSet(CopiedHeaderFields[i][1], [#9, #32])) then begin Result := Result + '|'; end else begin Result := Result + #13#10; end; Result := Result + CopiedHeaderFields[i]; end; if (Length(Result) > 0) then begin System.Delete(Result, 1, 1); end; if (Trim(Result) <> '') then begin Result := TclDkimQuotedPrintableEncoder.Encode(Result); end; end; procedure TclDkimSignature.Build(AMessage: TStrings; ACharsPerLine: Integer); var fieldList: TclDkimHeaderFieldList; begin fieldList := TclDkimHeaderFieldList.Create(); try fieldList.CharsPerLine := ACharsPerLine; fieldList.Parse(0, AMessage); fieldList.InsertEmptyField(0, cDkimSignatureField); AddVersion(fieldList); AddNotNull(fieldList, 'a', SignatureAlgorithm); AddNotNull(fieldList, 'd', GetDomain()); AddNotNull(fieldList, 's', Selector); Add(fieldList, 'c', Canonicalization); AddBodyLength(fieldList); Add(fieldList, 'q', PublicKeyLocation); Add(fieldList, 'i', GetUserIdentity()); CheckTimestamp(); AddDate(fieldList, 't', SignatureTimestamp); AddDate(fieldList, 'x', SignatureExpiration); AddNotNull(fieldList, 'h', GetSignedHeaderFields()); Add(fieldList, 'z', GetCopiedHeaderFields()); AddNotNull(fieldList, 'bh', BodyHash); fieldList.AddEmptyFieldItem(cDkimSignatureField, 'b', True); finally fieldList.Free(); end; end; procedure TclDkimSignature.Clear; begin FVersion := 0; FSignatureAlgorithm := ''; FCanonicalization := ''; FDomain := ''; FSelector := ''; FSignedHeaderFields.Clear(); FBodyLength := 0; FUserIdentity := ''; FPublicKeyLocation := ''; FSignatureTimestamp := 0; FSignatureExpiration := 0; FCopiedHeaderFields.Clear(); FSignature := ''; FBodyHash := ''; FStatus.Clear(); end; constructor TclDkimSignature.Create; begin inherited Create(); FSignedHeaderFields := TStringList.Create(); FCopiedHeaderFields := TStringList.Create(); FStatus := TclDkimSignatureVerifyStatus.Create(); Clear(); end; destructor TclDkimSignature.Destroy; begin FStatus.Free(); FCopiedHeaderFields.Free(); FSignedHeaderFields.Free(); inherited Destroy(); end; function TclDkimSignature.ParseVersion(const AValue: string): Integer; begin Result := StrToIntDef(Trim(AValue), 0); if (Result = 0) then begin raise EclDkimError.Create(DkimInvalidFormat, DkimInvalidFormatCode); end; end; procedure TclDkimSignature.SetCopiedHeaderFields(const Value: TStrings); begin FCopiedHeaderFields.Assign(Value); end; procedure TclDkimSignature.SetSignedHeaderFields(const Value: TStrings); begin FSignedHeaderFields.Assign(Value); end; function TclDkimSignature.ParseNotNull(const AValue: string): string; begin Result := Trim(AValue); if (Result = '') then begin raise EclDkimError.Create(DkimInvalidFormat, DkimInvalidFormatCode); end; end; function TclDkimSignature.GetSignedHeaderFields: string; var i: Integer; begin Result := ''; for i := 0 to SignedHeaderFields.Count - 1 do begin Result := Result + SignedHeaderFields[i] + ':'; end; if (Length(Result) > 0) then begin System.Delete(Result, Length(Result), 1); end; end; function TclDkimSignature.ParseBodyLength(const AValue: string): Integer; begin if (Trim(AValue) = '') then begin Result := 0; Exit; end; Result := StrToIntDef(Trim(AValue), -1); if (Result < 0) then begin raise EclDkimError.Create(DkimInvalidFormat, DkimInvalidFormatCode); end; end; function TclDkimSignature.ParseDate(const AValue: string): TDateTime; var s: string; d: Int64; begin Result := 0; s := Trim(AValue); if (s = '') then Exit; d := StrToInt64Def(System.Copy(s, 1, 12), 0); if (d = 0) then Exit; Result := IncSecond(EncodeDate(1970, 1, 1), d); Result := GlobalTimeToLocalTime(Result); end; procedure TclDkimSignature.ParseCopiedHeaderFields(const AValue: string); var list: TStrings; i: Integer; begin CopiedHeaderFields.Clear(); list := TStringList.Create(); try SplitText(AValue, list, '|'); for i := 0 to list.Count - 1 do begin AddTextStr(CopiedHeaderFields, TclDkimQuotedPrintableEncoder.Decode(list[i])); end; finally list.Free(); end; end; procedure TclDkimSignature.ParseSignedHeaderFields(const AValue: string); begin SplitText(ParseNotNull(AValue), SignedHeaderFields, ':'); end; procedure TclDkimSignature.Parse(AMessage: TStrings); var fieldList: TclHeaderFieldList; begin fieldList := TclDkimHeaderFieldList.Create(); try fieldList.Parse(0, AMessage); Parse(fieldList.GetFieldValue(cDkimSignatureField)); finally fieldList.Free(); end; end; procedure TclDkimSignature.Parse(const ADkimSignatureField: string); var fieldList: TclHeaderFieldList; begin fieldList := TclDkimHeaderFieldList.Create(); try FVersion := ParseVersion(fieldList.GetFieldValueItem(ADkimSignatureField, 'v')); FSignatureAlgorithm := ParseNotNull(fieldList.GetFieldValueItem(ADkimSignatureField, 'a')); FCanonicalization := fieldList.GetFieldValueItem(ADkimSignatureField, 'c'); FDomain := ParseNotNull(fieldList.GetFieldValueItem(ADkimSignatureField, 'd')); FSelector := ParseNotNull(fieldList.GetFieldValueItem(ADkimSignatureField, 's')); ParseSignedHeaderFields(fieldList.GetFieldValueItem(ADkimSignatureField, 'h')); FBodyLength := ParseBodyLength(fieldList.GetFieldValueItem(ADkimSignatureField, 'l')); FUserIdentity := TclDkimQuotedPrintableEncoder.Decode(fieldList.GetFieldValueItem(ADkimSignatureField, 'i')); FPublicKeyLocation := fieldList.GetFieldValueItem(ADkimSignatureField, 'q'); FSignatureTimestamp := ParseDate(fieldList.GetFieldValueItem(ADkimSignatureField, 't')); FSignatureExpiration := ParseDate(fieldList.GetFieldValueItem(ADkimSignatureField, 'x')); ParseCopiedHeaderFields(fieldList.GetFieldValueItem(ADkimSignatureField, 'z')); FSignature := fieldList.GetFieldValueItem(ADkimSignatureField, 'b'); FBodyHash := fieldList.GetFieldValueItem(ADkimSignatureField, 'bh'); finally fieldList.Free(); end; end; { TclDkimSignatureList } function TclDkimSignatureList.Add(AItem: TclDkimSignature): TclDkimSignature; begin FList.Add(AItem); Result := AItem; end; procedure TclDkimSignatureList.Clear; begin FList.Clear(); end; constructor TclDkimSignatureList.Create; begin inherited Create(); FList := TObjectList.Create(True); end; procedure TclDkimSignatureList.Delete(Index: Integer); begin FList.Delete(Index); end; destructor TclDkimSignatureList.Destroy; begin FList.Free(); inherited Destroy(); end; function TclDkimSignatureList.GetCount: Integer; begin Result := FList.Count; end; function TclDkimSignatureList.GetItem(Index: Integer): TclDkimSignature; begin Result := TclDkimSignature(FList[Index]); end; { TclDkimSignatureVerifyStatus } procedure TclDkimSignatureVerifyStatus.Clear; begin SetStatus(dssNone, '', 0); end; constructor TclDkimSignatureVerifyStatus.Create; begin inherited Create(); Clear(); end; procedure TclDkimSignatureVerifyStatus.SetVerified; begin SetStatus(dssVerified, '', 0); end; procedure TclDkimSignatureVerifyStatus.SetFailed(const AErrorText: string; AErrorCode: Integer); begin SetStatus(dssFailed, AErrorText, AErrorCode); end; procedure TclDkimSignatureVerifyStatus.SetStatus(AStatus: TclDkimVerifyStatus; const AErrorText: string; AErrorCode: Integer); begin FStatus := AStatus; FErrorText := AErrorText; FErrorCode := AErrorCode; end; end.
unit NLDTRTTIUtils; { :: NLDTRTTIUtils contains some wrapper classes and functions around the :: RunTime Type Information API provided by Delphi. This makes working with :: RTTI a bit easier. :$ :$ :$ NLDTranslate is released under the zlib/libpng OSI-approved license. :$ For more information: http://www.opensource.org/ :$ /n/n :$ /n/n :$ Copyright (c) 2002 M. van Renswoude :$ /n/n :$ This software is provided 'as-is', without any express or implied warranty. :$ In no event will the authors be held liable for any damages arising from :$ the use of this software. :$ /n/n :$ Permission is granted to anyone to use this software for any purpose, :$ including commercial applications, and to alter it and redistribute it :$ freely, subject to the following restrictions: :$ /n/n :$ 1. The origin of this software must not be misrepresented; you must not :$ claim that you wrote the original software. If you use this software in a :$ product, an acknowledgment in the product documentation would be :$ appreciated but is not required. :$ /n/n :$ 2. Altered source versions must be plainly marked as such, and must not be :$ misrepresented as being the original software. :$ /n/n :$ 3. This notice may not be removed or altered from any source distribution. } {$I NLDTDefines.inc} interface uses SysUtils, TypInfo; type { :$ Provides access to an object's RTTI information :: TNLDTRTTIInfo tries to wrap RTTI functionality in an easy :: to use class. It is build on an on-demand basis, which means it may :: miss functionality which is not required by NLDTranslate itself. } TNLDTRTTIInfo = class(TObject) private FObject: TObject; // Used for caching the last property name / info FCachedName: String; FCachedInfo: PPropInfo; protected procedure SetObject(const Value: TObject); virtual; procedure ClearInfo(); virtual; procedure CacheInfo(const AName: String); virtual; public //:$ Initializes a new TNLDTRTTIInfo instance //:: Set the AObject parameter to the object you want to get RTTI //:: information from. constructor Create(AObject: TObject); virtual; //:$ Searches for a property with the specified name //:: Returns True if the object has a published property with the //:: specified name. False otherwise. function HasProperty(const AName: String): Boolean; virtual; //:$ Returns the type for the specified property function GetPropertyType(const AName: String): TTypeKind; virtual; //:$ Returns the specified property as a string function GetPropertyAsString(const AName: String): String; virtual; //:$ Returns the specified property as an object function GetPropertyAsObject(const AName: String): TObject; virtual; //:$ Sets the specified property as a string procedure SetPropertyAsString(const AName, AValue: String); virtual; //:$ Gets or sets the object to retrieve RTTI information from //:: RTTIObject initially corresponds to the AObject passed in the //:: constructor. property RTTIObject: TObject read FObject write SetObject; end; implementation {************************* TNLDTRTTIInfo Constructor ****************************************} constructor TNLDTRTTIInfo.Create; begin inherited Create(); RTTIObject := AObject; end; {************************* TNLDTRTTIInfo Misc RTTI ****************************************} procedure TNLDTRTTIInfo.ClearInfo; begin FCachedName := ''; FCachedInfo := nil; end; procedure TNLDTRTTIInfo.CacheInfo; begin if AName <> FCachedName then begin FCachedName := AName; FCachedInfo := GetPropInfo(FObject, AName); end; end; function TNLDTRTTIInfo.HasProperty; begin Result := False; CacheInfo(AName); if Assigned(FCachedInfo) then Result := Assigned(FCachedInfo); end; function TNLDTRTTIInfo.GetPropertyType; begin Result := tkUnknown; CacheInfo(AName); if Assigned(FCachedInfo) then Result := FCachedInfo^.PropType^.Kind; end; {************************* TNLDTRTTIInfo GetPropertyAs ****************************************} function TNLDTRTTIInfo.GetPropertyAsObject; begin Result := nil; CacheInfo(AName); if Assigned(FCachedInfo) then if FCachedInfo^.PropType^.Kind = tkClass then Result := GetObjectProp(FObject, FCachedInfo); end; function TNLDTRTTIInfo.GetPropertyAsString; var iValue: Integer; dValue: Extended; eValue: Int64; begin Result := ''; CacheInfo(AName); if Assigned(FCachedInfo) then begin case FCachedInfo^.PropType^.Kind of tkInteger, tkChar, tkWChar: begin iValue := GetOrdProp(FObject, FCachedInfo); Str(iValue, Result); end; tkEnumeration: begin Result := GetEnumProp(FObject, FCachedInfo); end; tkFloat: begin dValue := GetFloatProp(FObject, FCachedInfo); Result := FloatToStr(dValue); end; tkString, tkLString: begin Result := GetStrProp(FObject, FCachedInfo); end; tkSet: begin Result := GetSetProp(FObject, FCachedInfo, True); end; tkWString: begin Result := GetWideStrProp(FObject, FCachedInfo); end; tkVariant: begin Result := GetVariantProp(FObject, FCachedInfo); end; tkInt64: begin eValue := GetInt64Prop(FObject, FCachedInfo); Str(eValue, Result); end; end; end; end; {************************* TNLDTRTTIInfo SetPropertyAs ****************************************} procedure TNLDTRTTIInfo.SetPropertyAsString; var iValue: Integer; dValue: Extended; eValue: Int64; begin CacheInfo(AName); if not Assigned(FCachedInfo) then exit; case FCachedInfo^.PropType^.Kind of tkInteger, tkChar, tkWChar: begin iValue := GetOrdProp(FObject, FCachedInfo); iValue := StrToIntDef(AValue, iValue); SetOrdProp(FObject, FCachedInfo, iValue); end; tkEnumeration: begin iValue := GetEnumValue(FCachedInfo^.PropType^, AValue); if iValue > -1 then SetOrdProp(FObject, FCachedInfo, iValue); end; tkFloat: begin try dValue := StrToFloat(AValue); SetFloatProp(FObject, FCachedInfo, dValue); except // Ignore... end; end; tkString, tkLString: begin SetStrProp(FObject, FCachedInfo, AValue); end; tkSet: begin SetSetProp(FObject, FCachedInfo, AValue); end; tkWString: begin SetWideStrProp(FObject, FCachedInfo, AValue); end; tkVariant: begin SetVariantProp(FObject, FCachedInfo, AValue); end; tkInt64: begin eValue := GetInt64Prop(FObject, FCachedInfo); eValue := StrToInt64Def(AValue, eValue); SetInt64Prop(FObject, FCachedInfo, eValue); end; end; end; {************************* TNLDTRTTIInfo Properties ****************************************} procedure TNLDTRTTIInfo.SetObject; begin if FObject <> Value then begin ClearInfo(); FObject := Value; end; end; end.
unit DataContainers.TestSuite; interface uses TestFramework, System.SysUtils, ValidationRules.TDataTypeValidationRule, System.Variants, Utils.TArrayUtil, Framework.Interfaces, DataContainers.TField, ValidationRules.TMaxLengthValidationRule, ValidationRules.TIsEmptyValidationRule; type TTFieldTest = class(TTestCase) strict private FField: IField; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_BooleanField_AcceptEmpty_EmptyValue; procedure TestParse_BooleanField_AcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_BooleanField_AcceptEmpty_NonEmptyValue_True_Valid; procedure TestParse_BooleanField_AcceptEmpty_NonEmptyValue_False_Valid; procedure TestParse_BooleanField_DoNotAcceptEmpty_EmptyValue; procedure TestParse_BooleanField_DoNotAcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_BooleanField_DoNotAcceptEmpty_NonEmptyValue_True_Valid; procedure TestParse_BooleanField_DoNotAcceptEmpty_NonEmptyValue_False_Valid; procedure TestParse_CurrencyField_AcceptEmpty_EmptyValue; procedure TestParse_CurrencyField_AcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_CurrencyField_AcceptEmpty_NonEmptyValue_Valid; procedure TestParse_CurrencyField_DoNotAcceptEmpty_EmptyValue; procedure TestParse_CurrencyField_DoNotAcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_CurrencyField_DoNotAcceptEmpty_NonEmptyValue_Valid; procedure TestParse_DateTimeField_AcceptEmpty_EmptyValue; procedure TestParse_DateTimeField_AcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_DateTimeField_AcceptEmpty_NonEmptyValue_Valid; procedure TestParse_DateTimeField_DoNotAcceptEmpty_EmptyValue; procedure TestParse_DateTimeField_DoNotAcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_DateTimeField_DoNotAcceptEmpty_NonEmptyValue_Valid; procedure TestParse_IntegerField_AcceptEmpty_EmptyValue; procedure TestParse_IntegerField_AcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_IntegerField_AcceptEmpty_NonEmptyValue_Valid; procedure TestParse_IntegerField_DoNotAcceptEmpty_EmptyValue; procedure TestParse_IntegerField_DoNotAcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_IntegerField_DoNotAcceptEmpty_NonEmptyValue_Valid; procedure TestParse_NumericField_AcceptEmpty_EmptyValue; procedure TestParse_NumericField_AcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_NumericField_AcceptEmpty_NonEmptyValue_Valid; procedure TestParse_NumericField_DoNotAcceptEmpty_EmptyValue; procedure TestParse_NumericField_DoNotAcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_NumericField_DoNotAcceptEmpty_NonEmptyValue_Valid; procedure TestParse_StringField_AcceptEmpty_EmptyValue; procedure TestParse_StringField_AcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_StringField_AcceptEmpty_NonEmptyValue_Valid; procedure TestParse_StringField_DoNotAcceptEmpty_EmptyValue; procedure TestParse_StringField_DoNotAcceptEmpty_NonEmptyValue_Invalid; procedure TestParse_StringField_DoNotAcceptEmpty_NonEmptyValue_Valid; end; implementation procedure TTFieldTest.SetUp; begin inherited; end; procedure TTFieldTest.TearDown; begin inherited; end; procedure TTFieldTest.TestParse_BooleanField_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Boolean', '', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = '') end; procedure TTFieldTest.TestParse_BooleanField_AcceptEmpty_NonEmptyValue_False_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Boolean', '', ADateSeparator, 0); FField.Value := ' fAlsE '; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_BooleanField_AcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Boolean', '', ADateSeparator, 0); FField.Value := 'Tru'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_BooleanField_AcceptEmpty_NonEmptyValue_True_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Boolean', '', ADateSeparator, 0); FField.Value := ' tRuE '; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_BooleanField_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Boolean', '', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> '') end; procedure TTFieldTest.TestParse_BooleanField_DoNotAcceptEmpty_NonEmptyValue_False_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Boolean', '', ADateSeparator, 0); FField.Value := 'falsE'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = '') end; procedure TTFieldTest.TestParse_BooleanField_DoNotAcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Boolean', '', ADateSeparator, 0); FField.Value := 'Fals'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> '') end; procedure TTFieldTest.TestParse_BooleanField_DoNotAcceptEmpty_NonEmptyValue_True_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Boolean', '', ADateSeparator, 0); FField.Value := 'true'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = '') end; procedure TTFieldTest.TestParse_CurrencyField_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Currency', '', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_CurrencyField_AcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Currency', '', ADateSeparator, 0); FField.Value := '125,0.43'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_CurrencyField_AcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Currency', '', ADateSeparator, 0); FField.Value := '1250.43'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_CurrencyField_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Currency', '', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_CurrencyField_DoNotAcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Currency', '', ADateSeparator, 0); FField.Value := '125,0.43'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_CurrencyField_DoNotAcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Currency', '', ADateSeparator, 0); FField.Value := '1250.43'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_DateTimeField_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'DateTime', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_DateTimeField_AcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'DateTime', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '28-13-1973'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_DateTimeField_AcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(True, 'DateTime', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '28-11-1973'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_DateTimeField_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'DateTime', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_DateTimeField_DoNotAcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'DateTime', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '28-13-1973'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_DateTimeField_DoNotAcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(False, 'DateTime', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '28-11-1973'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_IntegerField_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Integer', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_IntegerField_AcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Integer', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := 'Wrong!'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_IntegerField_AcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(True, 'Integer', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '28111973'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_IntegerField_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Integer', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_IntegerField_DoNotAcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Integer', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '28-13-1973'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_IntegerField_DoNotAcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(False, 'Integer', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '10081971'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_NumericField_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Numeric', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_NumericField_AcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'Numeric', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '323,2.2452'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_NumericField_AcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(True, 'Numeric', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '3232123.54354'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_NumericField_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Numeric', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_NumericField_DoNotAcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'Numeric', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '22342,34.543234'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_NumericField_DoNotAcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(False, 'Numeric', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := '104320.81971'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_StringField_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'String', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_StringField_AcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(True, 'String', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := 12345; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_StringField_AcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(True, 'String', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := 'This is a String'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTFieldTest.TestParse_StringField_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'String', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := ''; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_StringField_DoNotAcceptEmpty_NonEmptyValue_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '/'; AReasonForRejection := ''; FField := TField.Create(False, 'String', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := 2234234.543234; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection <> ''); end; procedure TTFieldTest.TestParse_StringField_DoNotAcceptEmpty_NonEmptyValue_Valid; var ReturnValue: Boolean; AReasonForRejection: String; ADateSeparator: Char; begin ADateSeparator := '-'; AReasonForRejection := ''; FField := TField.Create(False, 'String', 'dd/mm/yyyy', ADateSeparator, 0); FField.Value := 'This is another String'; ReturnValue := FField.Parse(AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; initialization RegisterTest(TTFieldTest.Suite); end.
unit MFichas.Model.Entidade.VENDA; interface uses DB, Classes, SysUtils, Generics.Collections, /// orm ormbr.types.blob, ormbr.types.lazy, ormbr.types.mapping, ormbr.types.nullable, ormbr.mapping.classes, ormbr.mapping.register, ormbr.mapping.attributes; type [Entity] [Table('VENDA', '')] [PrimaryKey('GUUID', NotInc, NoSort, False, 'Chave primária')] TVENDA = class private { Private declarations } FGUUID: String; FCAIXA: String; FNUMERO: Integer; FDATAABERTURA: TDateTime; FDATAFECHAMENTO: TDateTime; FSTATUS: Integer; function GetDATAABERTURA: TDateTime; function GetGUUID: String; public { Public declarations } [Column('GUUID', ftString, 38)] [Dictionary('GUUID', 'Mensagem de validação', '', '', '', taLeftJustify)] property GUUID: String read GetGUUID write FGUUID; [Column('CAIXA', ftString, 38)] [Dictionary('CAIXA', 'Mensagem de validação', '', '', '', taLeftJustify)] property CAIXA: String read FCAIXA write FCAIXA; [Column('NUMERO', ftInteger)] [Dictionary('NUMERO', 'Mensagem de validação', '', '', '', taCenter)] property NUMERO: Integer read FNUMERO write FNUMERO; [Column('DATAABERTURA', ftDateTime)] [Dictionary('DATAABERTURA', 'Mensagem de validação', '', '', '', taCenter)] property DATAABERTURA: TDateTime read GetDATAABERTURA write FDATAABERTURA; [Column('DATAFECHAMENTO', ftDateTime)] [Dictionary('DATAFECHAMENTO', 'Mensagem de validação', '', '', '', taCenter)] property DATAFECHAMENTO: TDateTime read FDATAFECHAMENTO write FDATAFECHAMENTO; [Column('STATUS', ftInteger)] [Dictionary('STATUS', 'Mensagem de validação', '', '', '', taCenter)] property STATUS: Integer read FSTATUS write FSTATUS; end; implementation { TVENDA } function TVENDA.GetDATAABERTURA: TDateTime; begin if FDATAABERTURA = StrToDate('30/12/1899') then FDATAABERTURA := Now; Result := FDATAABERTURA; end; function TVENDA.GetGUUID: String; begin if FGUUID.IsEmpty then FGUUID := TGUID.NewGuid.ToString; Result := FGUUID; end; initialization TRegisterClass.RegisterEntity(TVENDA) end.
{!DOCTOPIC}{ Type » TFloatArray } {!DOCREF} { @method: function TFloatArray.Len(): Int32; @desc: Returns the length of the array. Same as 'Length(arr)' } function TFloatArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TFloatArray.IsEmpty(): Boolean; @desc: Returns True if the array is empty. Same as 'Length(arr) = 0' } function TFloatArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure TFloatArray.Append(const Value:Single); @desc: Add another item to the array } procedure TFloatArray.Append(const Value:Single); var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := Value; end; {!DOCREF} { @method: procedure TFloatArray.Insert(idx:Int32; Value:Single); @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 TFloatArray.Insert(idx:Int32; Value:Single); 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(Single)); Self[idx] := value; end; {!DOCREF} { @method: procedure TFloatArray.Del(idx:Int32); @desc: Removes the element at the given index c'idx' } procedure TFloatArray.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(Single)); SetLength(Self, l-1); end; {!DOCREF} { @method: procedure TFloatArray.Remove(Value:Single); @desc: Removes the first element from left which is equal to c'Value' } procedure TFloatArray.Remove(Value:Single); begin Self.Del( Self.Find(Value) ); end; {!DOCREF} { @method: function TFloatArray.Pop(): Single; @desc: Removes and returns the last item in the array } function TFloatArray.Pop(): Single; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function TFloatArray.PopLeft(): Single; @desc: Removes and returns the first item in the array } function TFloatArray.PopLeft(): Single; begin Result := Self[0]; MemMove(Self[1], Self[0], SizeOf(Single)*Length(Self)); SetLength(Self, High(self)); end; {!DOCREF} { @method: function TFloatArray.Slice(Start,Stop: Int32; Step:Int32=1): TFloatArray; @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(..)[br] If c'Start >= Stop', and c'Step <= -1' it will result in reversed output.[br] [note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note] } function TFloatArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TFloatArray; 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 TFloatArray.Extend(Arr:TFloatArray); @desc: Extends the array with an array } procedure TFloatArray.Extend(Arr:TFloatArray); var L:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(Single)); end; {!DOCREF} { @method: function TFloatArray.Find(Value:Single): Int32; @desc: Searces for the given value and returns the first position from the left. } function TFloatArray.Find(Value:Single): Int32; begin Result := exp_Find(Self,[Value]); end; {!DOCREF} { @method: function TFloatArray.Find(Sequence:TFloatArray): Int32; overload; @desc: Searces for the given sequence and returns the first position from the left. } function TFloatArray.Find(Sequence:TFloatArray): Int32; overload; begin Result := exp_Find(Self,Sequence); end; {!DOCREF} { @method: function TFloatArray.FindAll(Value:Single): TIntArray; @desc: Searces for the given value and returns all the position where it was found. } function TFloatArray.FindAll(Value:Single): TIntArray; begin Result := exp_FindAll(Self,[value]); end; {!DOCREF} { @method: function TFloatArray.FindAll(Sequence:TFloatArray): TIntArray; overload; @desc: Searces for the given sequence and returns all the position where it was found. } function TFloatArray.FindAll(Sequence:TFloatArray): TIntArray; overload; begin Result := exp_FindAll(Self,sequence); end; {!DOCREF} { @method: function TFloatArray.Contains(val:Single): Boolean; @desc: Checks if the arr contains the given value c'val' } function TFloatArray.Contains(val:Single): Boolean; begin Result := Self.Find(val) <> -1; end; {!DOCREF} { @method: function TFloatArray.Count(val:Single): Int32; @desc: Counts all the occurances of the given value c'val' } function TFloatArray.Count(val:Single): Int32; begin Result := Length(Self.FindAll(val)); end; {!DOCREF} { @method: procedure TFloatArray.Sort(key:TSortKey=sort_Default); @desc: Sorts the array Supported keys: c'sort_Default' } procedure TFloatArray.Sort(key:TSortKey=sort_Default); begin case key of sort_default: se.SortTFA(Self); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TFloatArray.Sorted(key:TSortKey=sort_Default): TFloatArray; @desc: Returns a new sorted array from the input array. Supported keys: c'sort_Default' } function TFloatArray.Sorted(Key:TSortKey=sort_Default): TFloatArray; begin Result := Copy(Self); case key of sort_default: se.SortTFA(Result); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TFloatArray.Reversed(): TFloatArray; @desc: Creates a reversed copy of the array } function TFloatArray.Reversed(): TFloatArray; begin Result := Self.Slice(,,-1); end; {!DOCREF} { @method: procedure TFloatArray.Reverse(); @desc: Reverses the array } procedure TFloatArray.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 TFloatArray.Sum(): Double; @desc: Adds up the array and returns the sum } function TFloatArray.Sum(): Double; begin Result := exp_SumFPtr(PChar(Self),SizeOf(Single),Length(Self)); end; {!DOCREF} { @method: function TFloatArray.Mean(): Single; @desc:Returns the mean value of the array } function TFloatArray.Mean(): Single; begin Result := Self.Sum() / Length(Self); end; {!DOCREF} { @method: function TFloatArray.Stdev(): Single; @desc: Returns the standard deviation of the array } function TFloatArray.Stdev(): Single; var i:Int32; avg:Single; square:TFloatArray; 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 TFloatArray.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 TFloatArray.Variance(): Double; var avg:Single; 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 TFloatArray.Mode(Eps:Single=0.000001): Single; @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 TFloatArray.Mode(Eps:Single=0.0000001): Single; var arr:TFloatArray; i,hits,best: Int32; cur:Single; 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 TFloatArray.VarMin(): Single; @desc: Returns the minimum value in the array } function TFloatArray.VarMin(): Single; var lo,hi:Extended; begin exp_MinMaxFPtr(Pointer(self), 4, length(self), lo,hi); Result := Lo; end; {!DOCREF} { @method: function TFloatArray.VarMax(): Single; @desc: Returns the maximum value in the array } function TFloatArray.VarMax(): Single; var lo,hi:Extended; begin exp_MinMaxFPtr(Pointer(self), 4, length(self), lo,hi); Result := Hi; end; {!DOCREF} { @method: function TFloatArray.ArgMin(): Int32; @desc: Returns the index containing the smallest element in the array. } function TFloatArray.ArgMin(): Int32; var mat:TFloatMatrix; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMin(mat).x; end; {!DOCREF} { @method: function TFloatArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the smallest element in the array. } function TFloatArray.ArgMin(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TFloatMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMin(n), Result, _); end; {!DOCREF} { @method: function TFloatArray.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 TFloatArray.ArgMin(lo,hi:Int32): Int32; overload; var B: TBox; mat:TFloatMatrix; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMin(mat,B).x; end; {!DOCREF} { @method: function TFloatArray.ArgMax(): Int32; @desc: Returns the index containing the largest element in the array. } function TFloatArray.ArgMax(): Int32; var mat:TFloatMatrix; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMax(mat).x; end; {!DOCREF} { @method: function TFloatArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the largest element in the array. } function TFloatArray.ArgMax(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TFloatMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMax(n), Result, _); end; {!DOCREF} { @method: function TFloatArray.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 TFloatArray.ArgMax(lo,hi:Int32): Int32; overload; var B: TBox; mat:TFloatMatrix; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMax(mat,B).x; end;
unit ce_editoroptions; {$I ce_defines.inc} interface uses Classes, SysUtils, Graphics, SynEdit, SynEditMouseCmds, SynEditMiscClasses, SynEditKeyCmds, Menus, LCLProc, ce_interfaces, ce_observer, ce_common, ce_writableComponent, ce_synmemo, ce_d2syn, ce_txtsyn; type (** * Container for the editor and highlither options. * The base class is also used to backup the settings * to allow a to preview and restore the settings when rejected. * * note: when adding a new property, the default value must be set in * the constructor according to the default value of the member binded * to the property. *) TCEEditorOptionsBase = class(TWritableLfmTextComponent) private // note this is how a TComponent can be edited in // a basic TTIGrid: in the ctor create the component // but expose it as a published TPersistent. fD2Syn: TPersistent; fTxtSyn: TPersistent; // fShortCuts: TCollection; // fSelCol: TSynSelectedColor; fFoldedColor: TSynSelectedColor; fMouseLinkColor: TSynSelectedColor; fBracketMatchColor: TSynSelectedColor; fFont: TFont; // fHintDelay: Integer; fAutoDotDelay: Integer; fTabWidth: Integer; fBlockIdent: Integer; fLineSpacing: Integer; fCharSpacing: Integer; fRightEdge: Integer; fBackground: TColor; fRightEdgeColor: TColor; fOptions1: TSynEditorOptions; fOptions2: TSynEditorOptions2; fMouseOptions: TSynEditorMouseOptions; fCompletionMenuCaseCare: boolean; // procedure setFont(aValue: TFont); procedure setSelCol(aValue: TSynSelectedColor); procedure setFoldedColor(aValue: TSynSelectedColor); procedure setMouseLinkColor(aValue: TSynSelectedColor); procedure setBracketMatchColor(aValue: TSynSelectedColor); procedure setD2Syn(aValue: TPersistent); procedure setTxtSyn(aValue: TPersistent); procedure setShortcuts(aValue: TCollection); procedure setHintDelay(aValue: Integer); procedure setAutoDotDelay(aValue: Integer); published property completionMenuCaseCare: boolean read fCompletionMenuCaseCare write fCompletionMenuCaseCare; property autoDotDelay: integer read fAutoDotDelay write SetautoDotDelay; property hintDelay: Integer read fHintDelay write setHintDelay; property bracketMatchColor: TSynSelectedColor read fBracketMatchColor write setBracketMatchColor; property mouseLinkColor: TSynSelectedColor read fMouseLinkColor write setMouseLinkColor; property selectedColor: TSynSelectedColor read fSelCol write setSelCol; property foldedColor: TSynSelectedColor read fFoldedColor write setFoldedColor; property background: TColor read fBackground write fBackground default clWhite; property tabulationWidth: Integer read fTabWidth write fTabWidth default 4; property blockIdentation: Integer read fBlockIdent write fBlockIdent default 4; property lineSpacing: Integer read fLineSpacing write fLineSpacing default 0; property characterSpacing: Integer read fCharSpacing write fCharSpacing default 0; property rightEdge: Integer read fRightEdge write fRightEdge default 80; property rightEdgeColor: TColor read fRightEdgeColor write fRightEdgeColor default clSilver; property font: TFont read fFont write setFont; property options1: TSynEditorOptions read fOptions1 write fOptions1; property options2: TSynEditorOptions2 read fOptions2 write fOptions2; property mouseOptions: TSynEditorMouseOptions read fMouseOptions write fMouseOptions; property D2Highlighter: TPersistent read fD2Syn write setD2Syn; property TxtHighlighter: TPersistent read fTxtSyn write setTxtSyn; property shortcuts: TCollection read fShortCuts write setShortcuts; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // procedure Assign(src: TPersistent); override; end; (** * Manages and exposes all the editor and highligther options to an TCEOptionsEditor. * It's also responsible to give the current options to a new editor. *) TCEEditorOptions = class(TCEEditorOptionsBase, ICEEditableOptions, ICEMultiDocObserver, ICEEDitableShortcut) private fBackup: TCEEditorOptionsBase; fShortcutCount: Integer; // function optionedWantCategory(): string; function optionedWantEditorKind: TOptionEditorKind; function optionedWantContainer: TPersistent; procedure optionedEvent(anEvent: TOptionEditorEvent); function optionedOptionsModified: boolean; // procedure docNew(aDoc: TCESynMemo); procedure docFocused(aDoc: TCESynMemo); procedure docChanged(aDoc: TCESynMemo); procedure docClosing(aDoc: TCESynMemo); // function scedWantFirst: boolean; function scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; procedure scedSendItem(const category, identifier: string; aShortcut: TShortcut); // procedure applyChangesFromSelf; procedure applyChangeToEditor(anEditor: TCESynMemo); protected procedure afterLoad; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation const edoptFname = 'editor.txt'; var EditorOptions: TCEEditorOptions; {$REGION Standard Comp/Obj -----------------------------------------------------} constructor TCEEditorOptionsBase.Create(AOwner: TComponent); var i: integer; shc: TCEPersistentShortcut; ed: TSynEdit; begin inherited; // fFont := TFont.Create; fFont.Name := 'Courier New'; fFont.Quality := fqProof; fFont.Pitch := fpFixed; fFont.Size := 10; // fD2Syn := TSynD2Syn.Create(self); fD2Syn.Assign(D2Syn); fTxtSyn := TSynTxtSyn.Create(self); fTxtSyn.Assign(TxtSyn); // fHintDelay:=200; fAutoDotDelay:=200; fSelCol := TSynSelectedColor.Create; fFoldedColor := TSynSelectedColor.Create; fMouseLinkColor := TSynSelectedColor.Create; fBracketMatchColor := TSynSelectedColor.Create; // // note: default values come from TSynEditFoldedView ctor. fFoldedColor.Background := clNone; fFoldedColor.Foreground := clDkGray; fFoldedColor.FrameColor := clDkGray; // fMouseLinkColor.Style := [fsUnderline, fsBold]; fMouseLinkColor.StyleMask := []; fMouseLinkColor.Foreground := clNone; fMouseLinkColor.Background := clNone; // fBracketMatchColor.Foreground := clRed; fBracketMatchColor.Background := clNone; // rightEdge := 80; tabulationWidth := 4; blockIdentation := 4; fBackground := clWhite; fRightEdgeColor := clSilver; // options1 := [eoAutoIndent, eoBracketHighlight, eoGroupUndo, eoTabsToSpaces, eoDragDropEditing, eoShowCtrlMouseLinks, eoEnhanceHomeKey, eoTabIndent]; options2 := [eoEnhanceEndKey, eoFoldedCopyPaste, eoOverwriteBlock]; // mouseOptions := MouseOptions + [emAltSetsColumnMode, emDragDropEditing, emCtrlWheelZoom, emShowCtrlMouseLinks]; // fShortCuts := TCollection.Create(TCEPersistentShortcut); ed := TSynEdit.Create(nil); try // note: cant use a TCESynMemo because it'd be added to the EntitiesConnector SetDefaultCoeditKeystrokes(ed); for i:= 0 to ed.Keystrokes.Count-1 do begin shc := TCEPersistentShortcut(fShortCuts.Add); shc.actionName:= EditorCommandToCodeString(ed.Keystrokes.Items[i].Command); shc.shortcut := ed.Keystrokes.Items[i].ShortCut; end; finally ed.free; end; end; destructor TCEEditorOptionsBase.Destroy; begin fFont.Free; fSelCol.Free; fShortCuts.Free; fFoldedColor.Free; fMouseLinkColor.Free; fBracketMatchColor.Free; inherited; end; procedure TCEEditorOptionsBase.Assign(src: TPersistent); var srcopt: TCEEditorOptionsBase; begin if (src is TCEEditorOptionsBase) then begin srcopt := TCEEditorOptionsBase(src); // fCompletionMenuCaseCare:=srcopt.fCompletionMenuCaseCare; fAutoDotDelay:=srcopt.fAutoDotDelay; fHintDelay:=srcopt.fHintDelay; fFont.Assign(srcopt.fFont); fSelCol.Assign(srcopt.fSelCol); fFoldedColor.Assign(srcopt.fFoldedColor); fMouseLinkColor.Assign(srcopt.fMouseLinkColor); fBracketMatchColor.Assign(srcopt.fBracketMatchColor); fD2Syn.Assign(srcopt.fD2Syn); fTxtSyn.Assign(srcopt.fTxtSyn); background := srcopt.background; tabulationWidth := srcopt.tabulationWidth; blockIdentation := srcopt.blockIdentation; lineSpacing := srcopt.lineSpacing; characterSpacing := srcopt.characterSpacing; options1 := srcopt.options1; options2 := srcopt.options2; mouseOptions := srcopt.mouseOptions; rightEdge := srcopt.rightEdge; rightEdgeColor := srcopt.rightEdgeColor; fShortCuts.Assign(srcopt.fShortCuts); end else inherited; end; procedure TCEEditorOptionsBase.setHintDelay(aValue: Integer); begin if aValue > 2000 then aValue := 2000 else if aValue < 20 then aValue := 20; fHintDelay:=aValue; end; procedure TCEEditorOptionsBase.setAutoDotDelay(aValue: Integer); begin if aValue > 2000 then aValue := 2000 else if aValue < 0 then aValue := 0; fAutoDotDelay:=aValue; end; procedure TCEEditorOptionsBase.setShortcuts(aValue: TCollection); begin fShortCuts.Assign(aValue); end; procedure TCEEditorOptionsBase.setFont(aValue: TFont); begin fFont.Assign(aValue); end; procedure TCEEditorOptionsBase.setSelCol(aValue: TSynSelectedColor); begin fSelCol.Assign(aValue); end; procedure TCEEditorOptionsBase.setFoldedColor(aValue: TSynSelectedColor); begin fFoldedColor.Assign(aValue); end; procedure TCEEditorOptionsBase.setMouseLinkColor(aValue: TSynSelectedColor); begin fMouseLinkColor.Assign(aValue); end; procedure TCEEditorOptionsBase.setBracketMatchColor(aValue: TSynSelectedColor); begin fBracketMatchColor.Assign(aValue); end; procedure TCEEditorOptionsBase.setD2Syn(aValue: TPersistent); begin D2Syn.Assign(aValue); end; procedure TCEEditorOptionsBase.setTxtSyn(aValue: TPersistent); begin TxtSyn.Assign(aValue); end; constructor TCEEditorOptions.Create(AOwner: TComponent); var fname: string; begin inherited; fBackup := TCEEditorOptionsBase.Create(self); EntitiesConnector.addObserver(self); // fname := getCoeditDocPath + edoptFname; if fileExists(fname) then loadFromFile(fname); end; destructor TCEEditorOptions.Destroy; begin saveToFile(getCoeditDocPath + edoptFname); // EntitiesConnector.removeObserver(self); inherited; end; procedure TCEEditorOptions.afterLoad; begin inherited; D2Syn.Assign(fD2Syn); TxtSyn.Assign(fTxtSyn); end; {$ENDREGION} {$REGION ICEMultiDocObserver ----------------------------------------------------} procedure TCEEditorOptions.docNew(aDoc: TCESynMemo); begin applyChangeToEditor(aDoc); end; procedure TCEEditorOptions.docFocused(aDoc: TCESynMemo); begin end; procedure TCEEditorOptions.docChanged(aDoc: TCESynMemo); begin end; procedure TCEEditorOptions.docClosing(aDoc: TCESynMemo); begin end; {$ENDREGION} {$REGION ICEEDitableShortcut ---------------------------------------------------} function TCEEditorOptions.scedWantFirst: boolean; begin result := fShortCuts.Count > 0; fShortcutCount := 0; end; function TCEEditorOptions.scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; var shrct: TCEPersistentShortcut; begin shrct := TCEPersistentShortcut(fShortCuts.Items[fShortcutCount]); category := 'Code editor'; identifier:= shrct.actionName; // SynEdit shortcuts start with 'ec' if length(identifier) > 2 then identifier := identifier[3..length(identifier)]; aShortcut := shrct.shortcut; // fShortcutCount += 1; result := fShortcutCount < fShortCuts.Count; end; procedure TCEEditorOptions.scedSendItem(const category, identifier: string; aShortcut: TShortcut); var i: Integer; shc: TCEPersistentShortcut; begin if category <> 'Code editor' then exit; // for i:= 0 to fShortCuts.Count-1 do begin shc := TCEPersistentShortcut(fShortCuts.Items[i]); if length(shc.actionName) > 2 then begin if shc.actionName[3..length(shc.actionName)] <> identifier then continue; end else if shc.actionName <> identifier then continue; shc.shortcut:= aShortcut; break; end; // note: shortcut modifications are not reversible, // they are sent from another option editor. applyChangesFromSelf; end; {$ENDREGION} {$REGION ICEEditableOptions ----------------------------------------------------} function TCEEditorOptions.optionedWantCategory(): string; begin exit('Editor'); end; function TCEEditorOptions.optionedWantEditorKind: TOptionEditorKind; begin exit(oekGeneric); end; function TCEEditorOptions.optionedWantContainer: TPersistent; begin fD2Syn := D2Syn; fTxtSyn := TxtSyn; fBackup.Assign(self); fBackup.fD2Syn.Assign(D2Syn); fBackup.fTxtSyn.Assign(TxtSyn); exit(self); end; procedure TCEEditorOptions.optionedEvent(anEvent: TOptionEditorEvent); begin // restores if anEvent = oeeCancel then begin self.Assign(fBackup); D2Syn.Assign(fBackup.fD2Syn); TxtSyn.Assign(fBackup.fTxtSyn); end; // apply, if change/accept event // to get a live preview if anEvent <> oeeSelectCat then applyChangesFromSelf; // new backup values based on accepted values. if anEvent = oeeAccept then begin fBackup.Assign(self); fBackup.fD2Syn.Assign(D2Syn); fBackup.fTxtSyn.Assign(TxtSyn); end; end; function TCEEditorOptions.optionedOptionsModified: boolean; begin exit(false); end; {$ENDREGION} {$REGION ICEEditableOptions ----------------------------------------------------} procedure TCEEditorOptions.applyChangesFromSelf; var multied: ICEMultiDocHandler; i: Integer; begin multied := getMultiDocHandler; for i := 0 to multied.documentCount - 1 do applyChangeToEditor(multied.document[i]); end; procedure TCEEditorOptions.applyChangeToEditor(anEditor: TCESynMemo); var i, j: Integer; shc: TCEPersistentShortcut; kst: TSynEditKeyStroke; begin anEditor.completionMenuCaseCare:=fCompletionMenuCaseCare; anEditor.autoDotDelay:=fAutoDotDelay; anEditor.hintDelay:=fHintDelay; anEditor.defaultFontSize := font.Size; anEditor.Font.Assign(font); anEditor.SelectedColor.Assign(fSelCol); anEditor.FoldedCodeColor.Assign(fFoldedColor); anEditor.MouseLinkColor.Assign(fMouseLinkColor); anEditor.BracketMatchColor.Assign(fBracketMatchColor); anEditor.TabWidth := tabulationWidth; anEditor.BlockIndent := blockIdentation; anEditor.ExtraLineSpacing := lineSpacing; anEditor.ExtraCharSpacing := characterSpacing; anEditor.Options := options1; anEditor.Options2 := options2; anEditor.MouseOptions := mouseOptions; anEditor.Color := background; anEditor.RightEdge := rightEdge; anEditor.RightEdgeColor := rightEdgeColor; for i := 0 to anEditor.Keystrokes.Count-1 do begin kst := anEditor.Keystrokes.Items[i]; for j := 0 to fShortCuts.Count-1 do begin shc := TCEPersistentShortcut(fShortCuts.Items[j]); if shc.actionName = EditorCommandToCodeString(kst.Command) then begin try // if anEditor.Keystrokes.FindShortcut(); // try to find, if not match cur action, set to 0 kst.ShortCut := shc.shortcut; except kst.ShortCut := 0; shc.shortcut := 0; // TODO-cfeaure: manage shortcuts conflicts // either here or in the shortcut editor. // by default and if a conflict exists synedit will raise an exception here. end; break; end; end; end; end; {$ENDREGION} initialization EditorOptions := TCEEditorOptions.Create(nil); finalization EditorOptions.Free; end.
unit InputDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, buttons ; type TInputDialog = class(TComponent) private FCancelButton: boolean; FHelpButton: boolean; FPasswordChar: char; FMaxLength: integer; FDialogCaption: string; FText: string; FInputCaption: string; FAutoStrings:TStrings; FCharCase: TEditCharCase; FHelpButtonContext: integer; ip : TEdit; FRequired: boolean; btnOk, btnCancel, btnHelp : TBitBtn; procedure SetCancelButton(const Value: boolean); procedure SetCharCase(const Value: TEditCharCase); procedure SetDialogCaption(const Value: string); procedure SetHelpButton(const Value: boolean); procedure SetInputCaption(const Value: string); procedure SetMaxLength(const Value: integer); procedure SetPasswordChar(const Value: char); procedure SetText(const Value: string); procedure SetHelpButtonContext(const Value: integer); procedure OkBtnState(Sender:TObject); procedure inputEnter(Sender:TObject); procedure RefreshButtons; procedure SetRequired(const Value: boolean); procedure SetAutoStrings(Value:TStrings) ; { Private declarations } protected { Protected declarations } public { Public declarations } function Execute:boolean; overload; function Execute ( Value:TStringList ) :boolean;overload; constructor create(AOwner:TComponent);override; destructor destroy ; override; published { Published declarations } property CancelButton:boolean read FCancelButton write SetCancelButton; property HelpButton:boolean read FHelpButton write SetHelpButton; property HelpButtonContext:integer read FHelpButtonContext write SetHelpButtonContext; property DialogCaption:string read FDialogCaption write SetDialogCaption; property InputCaption:string read FInputCaption write SetInputCaption; property Text:string read FText write SetText; property MaxLength:integer read FMaxLength write SetMaxLength; property CharCase:TEditCharCase read FCharCase write SetCharCase; property PasswordChar:char read FPasswordChar write SetPasswordChar; property Required:boolean read FRequired write SetRequired; property AutoStrings:TStrings read FAutoStrings write SetAutoStrings; end; procedure Register; implementation uses uAutoComplete; procedure Register; begin RegisterComponents('FFS Dialogs', [TInputDialog]); end; { TInputDialog } constructor TInputDialog.create(AOwner: TComponent); begin inherited; CancelButton := true; FAutoStrings := TStringList.Create; end; destructor TInputDialog.destroy; begin FAutoStrings.Free; inherited; end; function TInputDialog.Execute: boolean; var f : TForm; lab : TLabel; tp,lf : integer; maxw : integer; begin tp := 4; lf := 5; f := Tform.Create(self); f.BorderStyle := bsDialog; f.Caption := DialogCaption; // label if trim(InputCaption) > '' then begin lab := TLabel.create(f); lab.Parent := f; lab.Caption := InputCaption; lab.Top := tp; lab.left := 5; tp := tp + lab.Height + 2; end; // input box ip := TEdit.Create(f); ip.parent := f; ip.Left := 5; ip.Top := tp; ip.MaxLength := MaxLength; ip.PasswordChar := PasswordChar; ip.CharCase := CharCase; if MaxLength > 0 then begin maxw := 12 * MaxLength; if maxw + 15 > screen.Width then maxw := screen.width - 15; end else maxw := 140; // 20 chars ip.Width := maxw; inc(maxw,15); tp := tp + ip.Height + 9; // buttons btnOk := TBitBtn.create(f); btnOk.Parent := f; btnOk.kind := bkOk; btnOk.Top := tp; btnOk.Left := lf; lf := lf + btnOk.Width + 5; if CancelButton then begin btnCancel := TBitBtn.create(f); btnCancel.Parent := f; btnCancel.kind := bkCancel; btnCancel.Top := tp; btnCancel.Left := lf; lf := lf + btnCancel.Width + 5; end; if HelpButton then begin btnHelp := TBitBtn.create(f); btnHelp.Parent := f; btnHelp.kind := bkHelp; btnHelp.Top := tp; btnHelp.Left := lf; lf := lf + btnHelp.Width + 5; end; tp := tp + btnOk.Height; ip.OnChange := OkBtnState; f.ClientHeight := tp + 5; if lf > maxw then maxw := lf; f.ClientWidth := maxw; f.Position := poScreenCenter; ip.text := Text; SetAutoCompleteControl(ip, FAutoStrings); RefreshButtons; if f.ShowModal = mrOk then begin Text := ip.Text; Result := true; end else Result := false; f.Free; end; procedure TInputDialog.RefreshButtons; begin if not Required then exit; btnOk.Enabled := trim(ip.text) > ''; end; procedure TInputDialog.OkBtnState(Sender: TObject); begin RefreshButtons; //keybd_event( VK_DOWN, 0, KEYEVENTF_KEYDOWN, 0 ); end; procedure TInputDialog.SetCancelButton(const Value: boolean); begin FCancelButton := Value; end; procedure TInputDialog.SetCharCase(const Value: TEditCharCase); begin FCharCase := Value; end; procedure TInputDialog.SetDialogCaption(const Value: string); begin FDialogCaption := Value; end; procedure TInputDialog.SetHelpButton(const Value: boolean); begin FHelpButton := Value; end; procedure TInputDialog.SetHelpButtonContext(const Value: integer); begin FHelpButtonContext := Value; end; procedure TInputDialog.SetInputCaption(const Value: string); begin FInputCaption := Value; end; procedure TInputDialog.SetMaxLength(const Value: integer); begin FMaxLength := Value; end; procedure TInputDialog.SetPasswordChar(const Value: char); begin FPasswordChar := Value; end; procedure TInputDialog.SetText(const Value: string); begin FText := Value; end; procedure TInputDialog.SetRequired(const Value: boolean); begin FRequired := Value; end; procedure TInputDialog.SetAutoStrings(Value: TStrings); begin FAutoStrings.Assign(Value); end; function TInputDialog.Execute(Value: TStringList): boolean; var f : TForm; lab : TLabel; tp,lf : integer; maxw : integer; begin tp := 4; lf := 5; f := Tform.Create(self); f.BorderStyle := bsDialog; f.Caption := DialogCaption; // label if trim(InputCaption) > '' then begin lab := TLabel.create(f); lab.Parent := f; lab.Caption := InputCaption; lab.Top := tp; lab.left := 5; tp := tp + lab.Height + 2; end; // input box ip := TEdit.Create(f); ip.parent := f; ip.Left := 5; ip.Top := tp; ip.MaxLength := MaxLength; ip.PasswordChar := PasswordChar; ip.CharCase := CharCase; SetAutoStrings(Value); SetAutoCompleteControl(ip,FAutoStrings); // SetAutoCompleteControl(ip,Value); if MaxLength > 0 then begin maxw := 12 * MaxLength; if maxw + 15 > screen.Width then maxw := screen.width - 15; end else maxw := 140; // 20 chars ip.Width := maxw; inc(maxw,15); tp := tp + ip.Height + 9; // buttons btnOk := TBitBtn.create(f); btnOk.Parent := f; btnOk.kind := bkOk; btnOk.Top := tp; btnOk.Left := lf; lf := lf + btnOk.Width + 5; if CancelButton then begin btnCancel := TBitBtn.create(f); btnCancel.Parent := f; btnCancel.kind := bkCancel; btnCancel.Top := tp; btnCancel.Left := lf; lf := lf + btnCancel.Width + 5; end; if HelpButton then begin btnHelp := TBitBtn.create(f); btnHelp.Parent := f; btnHelp.kind := bkHelp; btnHelp.Top := tp; btnHelp.Left := lf; lf := lf + btnHelp.Width + 5; end; tp := tp + btnOk.Height; ip.OnChange := OkBtnState; f.ClientHeight := tp + 5; if lf > maxw then maxw := lf; f.ClientWidth := maxw; f.Position := poScreenCenter; ip.OnEnter := inputEnter; ip.text := Text; RefreshButtons; if f.ShowModal = mrOk then begin Text := ip.Text; Result := true; end else Result := false; f.Free; end; procedure TInputDialog.inputEnter(Sender: TObject); begin keybd_event(VK_DOWN, MapVirtualKey(VK_DOWN, 0), 0, 0); SetAutoCompleteControl(ip,FAutoStrings); 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 ClpDerOctetStringParser; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes, ClpDerOctetString, ClpDefiniteLengthInputStream, ClpIProxiedInterface, ClpIDerOctetStringParser, ClpIAsn1OctetStringParser; resourcestring SConvertError = 'EIOCryptoLibException Converting Stream to Byte Array: %s'; type TDerOctetStringParser = class(TInterfacedObject, IAsn1OctetStringParser, IAsn1Convertible, IDerOctetStringParser) strict private var Fstream: TDefiniteLengthInputStream; public constructor Create(stream: TDefiniteLengthInputStream); destructor Destroy(); override; function GetOctetStream(): TStream; inline; function ToAsn1Object(): IAsn1Object; end; implementation { TDerOctetStringParser } constructor TDerOctetStringParser.Create(stream: TDefiniteLengthInputStream); begin Fstream := stream; end; destructor TDerOctetStringParser.Destroy; begin Fstream.Free; inherited Destroy; end; function TDerOctetStringParser.GetOctetStream: TStream; begin result := Fstream; end; function TDerOctetStringParser.ToAsn1Object: IAsn1Object; begin try result := TDerOctetString.Create(Fstream.ToArray()); except on e: EIOCryptoLibException do begin raise EInvalidOperationCryptoLibException.CreateResFmt(@SConvertError, [e.Message]); end; end; end; end.
//** Построитель рамок вокруг фона-изображения. unit uGUIBorder; interface uses Graphics, // Own units UCommon; //** Создатель рамок вокруг фона-изображения. type TGUIBorder = class(THODObject) private public TL, DL, TR, DR, HLine, VLine: TBitMap; procedure Make(var AImage: TBitMap); //** Конструктор. constructor Create; destructor Destroy; override; end; var //** Строим рамку вокруг фона-изображения. GUIBorder: TGUIBorder; implementation uses SysUtils; var //** Путь к базе игры. Path: string; { TGUIBorder } constructor TGUIBorder.Create; begin HLine := TBitMap.Create; HLine.LoadFromFile(Path + 'Data\Images\GUI\HLine.bmp'); VLine := TBitMap.Create; VLine.LoadFromFile(Path + 'Data\Images\GUI\VLine.bmp'); DR := TBitMap.Create; DR.Transparent := True; DR.TransparentColor := clBlack; DR.LoadFromFile(Path + 'Data\Images\GUI\DR.bmp'); TR := TBitMap.Create; TR.Transparent := True; TR.TransparentColor := clBlack; TR.LoadFromFile(Path + 'Data\Images\GUI\TR.bmp'); DL := TBitMap.Create; DL.Transparent := True; DL.TransparentColor := clBlack; DL.LoadFromFile(Path + 'Data\Images\GUI\DL.bmp'); TL := TBitMap.Create; TL.Transparent := True; TL.TransparentColor := clBlack; TL.LoadFromFile(Path + 'Data\Images\GUI\TL.bmp'); end; destructor TGUIBorder.Destroy; begin HLine.Free; VLine.Free; TL.Free; DL.Free; TR.Free; DR.Free; inherited; end; procedure TGUIBorder.Make(var AImage: TBitMap); var TempImage: TBitmap; begin TempImage := TBitMap.Create; try TempImage.Assign(AImage); TempImage.Canvas.Draw(0, 0, HLine); TempImage.Canvas.Draw(0, 0, VLine); TempImage.Canvas.Draw(0, AImage.Height - 1, HLine); TempImage.Canvas.Draw(AImage.Width - 1, 0, VLine); TempImage.Canvas.Draw(0, 0, TL); TempImage.Canvas.Draw(0, AImage.Height - 11, DL); TempImage.Canvas.Draw(AImage.Width - 11, 0, TR); TempImage.Canvas.Draw(AImage.Width - 11, AImage.Height - 11, DR); AImage.Assign(TempImage); finally TempImage.Free; end; end; initialization Path := ExtractFilePath(ParamStr(0)); GUIBorder := TGUIBorder.Create; finalization GUIBorder.Free; end.
{ cocoamsgbox.pas This example shows how to use the objective-c runtime headers to call initialization and finalization code for an objective-c class (in this case NSAutoreleasePool), and also shows a message box using minimal AppKit bindings to demonstrate that this can be used to build Cocoa applications. Compilation of this example requires the following options: -k-framework -kcocoa -k-lobjc This example project is released under public domain AUTHORS: Felipe Monteiro de Carvalho } program cocoamsgbox; {$mode objfpc}{$H+} uses objc, ctypes, FPCMacOSAll; { Very limited appkit bindings, just to run this example independently of the Cocoa bindings } { From AppKit/NSApplication.inc } function NSApplicationLoad(): CBOOL; cdecl; external; { from AppKit/NSPanel.inc } function NSRunAlertPanel(title, msg, defaultButton, alternateButton, otherButton: CFStringRef; others: array of const): cint; cdecl; external; const Str_NSAutoreleasePool = 'NSAutoreleasePool'; Str_alloc = 'alloc'; Str_init = 'init'; Str_release = 'release'; Str_Panel_Title = 'This is the title'; Str_Panel_Message = 'This is the message'; var { classes } NSAutoreleasePoolId: objc.id; { objects } allocbuf, pool: objc.id; { strings } CFTitle, CFMessage: CFStringRef; begin { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; } NSAutoreleasePoolId := objc_getClass(PChar(Str_NSAutoreleasePool)); allocbuf := objc_msgSend(NSAutoreleasePoolId, sel_registerName(PChar(Str_alloc)), []); pool := objc_msgSend(allocbuf, sel_registerName(PChar(Str_init)), []); NSApplicationLoad(); CFTitle := CFStringCreateWithCString(nil, PChar(Str_Panel_Title), kCFStringEncodingUTF8); CFMessage := CFStringCreateWithCString(nil, PChar(Str_Panel_Message), kCFStringEncodingUTF8); { uses a default "OK" button and no alternate buttons } NSRunAlertPanel(CFTitle, CFMessage, nil, nil, nil, []); CFRelease(CFTitle); CFRelease(CFMessage); { [pool release]; } objc_msgSend(pool, sel_registerName(PChar(Str_release)), []); end.
unit Unit1; interface uses Windows, Messages, SysUtils, {Variants,} Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Edit1: TEdit; Button1: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end; var Form1: TForm1; implementation uses BinarySearch; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var data : TIntArray; i, index : integer; bs : TBSearchInteger; found : TBSFound; begin setLength(data, memo1.Lines.Count); for i := 0 to memo1.Lines.Count - 1 do begin data[i] := StrToInt(memo1.lines[i]); end; bs := TBSearchInteger.Create; bs.Data := data; bs.Key := StrToInt(edit1.Text); index := bs.Search(found); case found of bsFound: begin Caption := IntToStr(index); Memo1.SelStart := index; end; bsNotFound: Caption := 'nicht gefunden'; bsLower: Caption := 'Key kleiner als gesamte Datenmenge'; bsHigher: Caption := 'Key grösser als gesamte Datenmenge'; end; bs.free; end; end.
unit clAssinantesJornal; interface uses udm, System.SysUtils, Vcl.Dialogs, clConexao; type TAssinantesJornal = class(TObject) private FID: Integer; FCodigo: String; FModalidade: Integer; FProduto: String; FOrdem: Integer; FQuantidade: Integer; FNome: String; FTipoLogradouro: String; FLogradouro: String; FNumero: String; FComplemento: String; FBairro: String; FCidade: String; FEstado: String; FCEP: String; FReferencia: String; FRoteiro: String; FLOG: String; conexao: TConexao; procedure SetID(val: Integer); procedure SetCodigo(val: String); procedure SetModalidade(val: Integer); procedure SetProduto(val: String); procedure SetOrdem(val: Integer); procedure SetQuantidade(val: Integer); procedure SetNome(val: String); procedure SetTipoLogradouro(val: String); procedure SetLogradouro(val: String); procedure SetNumero(val: String); procedure SetComplemento(val: String); procedure SetBairro(val: String); procedure SetCidade(val: String); procedure SetEstado(val: String); procedure SetCEP(val: String); procedure SetReferencia(val: String); procedure SetRoteiro(val: String); procedure SetLOG(val: String); public property ID: Integer read FID write SetID; property Codigo: String read FCodigo write SetCodigo; property Modalidade: Integer read FModalidade write SetModalidade; property Produto: String read FProduto write SetProduto; property Ordem: Integer read FOrdem write SetOrdem; property Quantidade: Integer read FQuantidade write SetQuantidade; property Nome: String read FNome write SetNome; property TipoLogradouro: String read FTipoLogradouro write SetTipoLogradouro; property Logradouro: String read FLogradouro write SetLogradouro; property Numero: String read FNumero write SetNumero; property Complemento: String read FComplemento write SetComplemento; property Bairro: String read FBairro write SetBairro; property Cidade: String read FCidade write SetCidade; property Estado: String read FEstado write SetEstado; property CEP: String read FCEP write SetCEP; property Referencia: String read FReferencia write SetReferencia; property Roteiro: String read FRoteiro write SetRoteiro; property LOG: String read FLOG write SetLOG; function Validar: Boolean; constructor Create; destructor Destroy; override; function Insert: Boolean; function Update: Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getField(sCampo: String; sColuna: String): String; function Delete(sFiltro: String): Boolean; end; const TABLENAME = 'JOR_ASSINANTES_JORNAL'; implementation uses uGlobais; procedure TAssinantesJornal.SetID(val: Integer); begin FID := val; end; procedure TAssinantesJornal.SetCodigo(val: String); begin FCodigo := val; end; procedure TAssinantesJornal.SetModalidade(val: Integer); begin FModalidade := val; end; procedure TAssinantesJornal.SetProduto(val: String); begin FProduto := val; end; procedure TAssinantesJornal.SetOrdem(val: Integer); begin FOrdem := val; end; procedure TAssinantesJornal.SetQuantidade(val: Integer); begin FQuantidade := val; end; procedure TAssinantesJornal.SetNome(val: String); begin FNome := val; end; procedure TAssinantesJornal.SetTipoLogradouro(val: String); begin FTipoLogradouro := val; end; procedure TAssinantesJornal.SetLogradouro(val: String); begin FLogradouro := val; end; procedure TAssinantesJornal.SetNumero(val: String); begin FNumero := val; end; procedure TAssinantesJornal.SetComplemento(val: String); begin FComplemento := val; end; procedure TAssinantesJornal.SetBairro(val: String); begin FBairro := val; end; procedure TAssinantesJornal.SetCidade(val: String); begin FCidade := val; end; procedure TAssinantesJornal.SetEstado(val: String); begin FEstado := val; end; procedure TAssinantesJornal.SetCEP(val: String); begin FCEP := val; end; procedure TAssinantesJornal.SetReferencia(val: String); begin FReferencia := val; end; procedure TAssinantesJornal.SetRoteiro(val: String); begin FRoteiro := val; end; procedure TAssinantesJornal.SetLOG(val: String); begin FLOG := val; end; function TAssinantesJornal.Validar: Boolean; begin try Result := False; if Self.Codigo.IsEmpty then begin MessageDlg('Informe o código do assinante!',mtWarning, [mbOK],0); Exit; end; if Self.Modalidade = 0 then begin MessageDlg('Informe a modalidade da assinantura!',mtWarning, [mbOK],0); Exit; end; if Self.Produto.IsEmpty then begin MessageDlg('Informe o produto da assinantura!',mtWarning, [mbOK],0); Exit; end; if Self.Quantidade = 0 then begin MessageDlg('Informe a quantidade de exemplares da assinantura!',mtWarning, [mbOK],0); Exit; end; if Self.Nome.IsEmpty then begin MessageDlg('Informe o nome do assinante!',mtWarning, [mbOK],0); Exit; end; if Self.Logradouro.IsEmpty then begin MessageDlg('Informe o endereço da assinantura!',mtWarning, [mbOK],0); Exit; end; if Self.Cidade.IsEmpty then begin MessageDlg('Informe a cidade da assinantura!',mtWarning, [mbOK],0); Exit; end; if Self.Estado.IsEmpty then begin MessageDlg('Informe o estado da assinantura!',mtWarning, [mbOK],0); Exit; end; if Self.CEP.IsEmpty then begin MessageDlg('Informe o CEP da assinantura!',mtWarning, [mbOK],0); Exit; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; constructor TAssinantesJornal.Create; begin inherited Create; conexao := TConexao.Create; end; destructor TAssinantesJornal.Destroy; begin conexao.Free; inherited Destroy; end; function TAssinantesJornal.Insert: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if dm.qryCRUD.Active then begin dm.qryCRUD.Close; end; dm.qryCRUD.SQL.Clear; dm.qryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + '(COD_ASSINANTE, ' + 'COD_MODALIDADE, ' + 'COD_PRODUTO, ' + 'NUM_ORDEM, ' + 'QTD_EXEMPLARES, ' + 'NOM_ASSINANTE, ' + 'DES_TIPO_LOGRADOURO, ' + 'DES_LOGRADOURO, ' + 'NUM_LOGRADOURO , ' + 'DES_COMPLEMENTO, ' + 'NOM_BAIRRO, ' + 'NOM_CIDADE, ' + 'UF_ESTADO, ' + 'NUM_CEP, ' + 'DES_REFERENCIA, ' + 'DES_ROTEIRO, ' + 'DES_LOG) ' + 'VALUES ' + '(:CODIGO, ' + ':MODALIDADE, ' + ':PRODUTO, ' + ':ORDEM, ' + ':EXEMPLARES, ' + ':NOME, ' + ':TIPO, ' + ':LOGRADOURO, ' + ':NUMERO, ' + ':COMPLEMENTO, ' + ':BAIRRO, ' + ':CIDADE, ' + ':UF, ' + ':CEP, ' + ':REFERENCIA, ' + ':ROTEIRO, ' + ':LOG);'; dm.qryCRUD.ParamByName('CODIGO').AsString := Self.Codigo; dm.qryCRUD.ParamByName('MODALIDADE').AsInteger := Self.Modalidade; dm.qryCRUD.ParamByName('PRODUTO').AsString := Self.Produto; dm.qryCRUD.ParamByName('ORDEM').AsInteger := Self.Ordem; dm.qryCRUD.ParamByName('EXEMPLARES').AsInteger := Self.Quantidade; dm.qryCRUD.ParamByName('NOME').AsString := Self.Nome; dm.qryCRUD.ParamByName('TIPO').AsString := Self.TipoLogradouro; dm.qryCRUD.ParamByName('LOGRADOURO').AsString := Self.Logradouro; dm.qryCRUD.ParamByName('NUMERO').AsString := Self.Numero; dm.qryCRUD.ParamByName('COMPLEMENTO').AsString := Self.Complemento; dm.qryCRUD.ParamByName('BAIRRO').AsString := Self.Bairro; dm.qryCRUD.ParamByName('CIDADE').AsString := Self.Cidade; dm.qryCRUD.ParamByName('UF').AsString := Self.Estado; dm.qryCRUD.ParamByName('CEP').AsString := Self.CEP; dm.qryCRUD.ParamByName('REFERENCIA').AsString := Self.Referencia; dm.qryCRUD.ParamByName('ROTEIRO').AsString := Self.Roteiro; dm.qryCRUD.ParamByName('LOG').AsString := Self.Log; dm.ZConn.PingServer; dm.qryCRUD.ExecSQL; dm.qryCRUD.Close; dm.qryCRUD.SQL.Clear; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TAssinantesJornal.Update: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if dm.qryCRUD.Active then begin dm.qryCRUD.Close; end; dm.qryCRUD.SQL.Clear; dm.qryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET '+ 'COD_ASSINANTE = :CODIGO, ' + 'COD_MODALIDADE = :MODALIDADE, ' + 'COD_PRODUTO = :PRODUTO, ' + 'NUM_ORDEM = :ORDEM, ' + 'QTD_EXEMPLARES = :EXEMPLARES, ' + 'NOM_ASSINANTE = :NOME, ' + 'DES_TIPO_LOGRADOURO = :TIPO, ' + 'DES_LOGRADOURO = :LOGRADOURO, ' + 'NUM_LOGRADOURO = :NUMERO, ' + 'DES_COMPLEMENTO = :COMPLEMENTO, ' + 'NOM_BAIRRO = :BAIRRO, ' + 'NOM_CIDADE = :CIDADE, ' + 'UF_ESTADO = :UF, ' + 'NUM_CEP = :CEP, ' + 'DES_REFERENCIA = :REFERENCIA, ' + 'DES_ROTEIRO = :ROTEIRO, ' + 'DES_LOG = :LOG ' + 'WHERE ID_ASSINANTE = :ID;'; dm.qryCRUD.ParamByName('ID').AsInteger := Self.ID; dm.qryCRUD.ParamByName('CODIGO').AsString := Self.Codigo; dm.qryCRUD.ParamByName('MODALIDADE').AsInteger := Self.Modalidade; dm.qryCRUD.ParamByName('PRODUTO').AsString := Self.Produto; dm.qryCRUD.ParamByName('ORDEM').AsInteger := Self.Ordem; dm.qryCRUD.ParamByName('EXEMPLARES').AsInteger := Self.Quantidade; dm.qryCRUD.ParamByName('NOME').AsString := Self.Nome; dm.qryCRUD.ParamByName('TIPO').AsString := Self.TipoLogradouro; dm.qryCRUD.ParamByName('LOGRADOURO').AsString := Self.Logradouro; dm.qryCRUD.ParamByName('NUMERO').AsString := Self.Numero; dm.qryCRUD.ParamByName('COMPLEMENTO').AsString := Self.Complemento; dm.qryCRUD.ParamByName('BAIRRO').AsString := Self.Bairro; dm.qryCRUD.ParamByName('CIDADE').AsString := Self.Cidade; dm.qryCRUD.ParamByName('UF').AsString := Self.Estado; dm.qryCRUD.ParamByName('CEP').AsString := Self.CEP; dm.qryCRUD.ParamByName('REFERENCIA').AsString := Self.Referencia; dm.qryCRUD.ParamByName('ROTEIRO').AsString := Self.Roteiro; dm.qryCRUD.ParamByName('LOG').AsString := Self.Log; dm.ZConn.PingServer; dm.qryCRUD.ExecSQL; dm.qryCRUD.Close; dm.qryCRUD.SQL.Clear; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TAssinantesJornal.getObject(sId: String; sFiltro: String): Boolean; begin Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'ID' then begin dm.QryGetObject.SQL.Add('WHERE ID_ASSINANTE = :ID'); dm.QryGetObject.ParamByName('ID').AsInteger := StrToInt(sId); end else if sFiltro = 'CODIGO' then begin dm.QryGetObject.SQL.Add('WHERE COD_ASSINANTE = :CODIGO'); dm.QryGetObject.ParamByName('CODIGO').AsString := sId; end else if sFiltro = 'ROTEIRO' then begin dm.QryGetObject.SQL.Add('WHERE DES_ROTEIRO = :ROTEIRO'); dm.QryGetObject.ParamByName('ROTEIRO').AsString := sId; end else if sFiltro = 'NOME' then begin dm.QryGetObject.SQL.Add('WHERE NOM_ASSINANTE LIKE :NOME'); dm.QryGetObject.ParamByName('NOME').AsString := '%' + sId + '%'; end else if sFiltro = 'PRODUTO' then begin dm.QryGetObject.SQL.Add('WHERE COD_PRODUTO = :PRODUTO'); dm.QryGetObject.ParamByName('PRODUTO').AsString := sId; end else if sFiltro = 'MODALIDADE' then begin dm.QryGetObject.SQL.Add('WHERE COD_MODALIDADE = :MODALIDADE'); dm.QryGetObject.ParamByName('MODALIDADE').AsInteger := StrToIntDef(sId,0); end else if sFiltro = 'CHAVE' then begin dm.QryGetObject.SQL.Add('WHERE COD_ASSINANTE = :CODIGO AND COD_PRODUTO = :PRODUTO AND COD_MODALIDADE = :MODALIDADE'); dm.QryGetObject.ParamByName('CODIGO').AsString := Self.Codigo; dm.QryGetObject.ParamByName('PRODUTO').AsString := Self.Produto; dm.QryGetObject.ParamByName('MODALIDADE').AsInteger := Self.Modalidade; end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; Self.ID := dm.QryGetObject.FieldByName('ID_ASSINANTE').AsInteger; Self.Codigo := dm.QryGetObject.FieldByName('COD_ASSINANTE').AsString; Self.Modalidade := dm.QryGetObject.FieldByName('COD_MODALIDADE').AsInteger; Self.Produto := dm.QryGetObject.FieldByName('COD_PRODUTO').AsString; Self.Ordem := dm.QryGetObject.FieldByName('NUM_ORDEM').AsInteger; Self.Quantidade := dm.QryGetObject.FieldByName('QTD_EXEMPLARES').AsInteger; Self.Nome := dm.QryGetObject.FieldByName('NOM_ASSINANTE').AsString; Self.TipoLogradouro := dm.QryGetObject.FieldByName('DES_TIPO_LOGRADOURO').AsString; Self.Logradouro := dm.QryGetObject.FieldByName('DES_LOGRADOURO').AsString; Self.Numero := dm.QryGetObject.FieldByName('NUM_LOGRADOURO').AsString; Self.Complemento := dm.QryGetObject.FieldByName('DES_COMPLEMENTO').AsString; Self.Bairro := dm.QryGetObject.FieldByName('NOM_BAIRRO').AsString; Self.Cidade := dm.QryGetObject.FieldByName('NOM_CIDADE').AsString; Self.Estado := dm.QryGetObject.FieldByName('UF_ESTADO').AsString; Self.CEP := dm.QryGetObject.FieldByName('NUM_CEP').AsString; Self.Referencia := dm.QryGetObject.FieldByName('DES_REFERENCIA').AsString; Self.Roteiro := dm.QryGetObject.FieldByName('DES_ROTEIRO').AsString; Self.Log := dm.QryGetObject.FieldByName('DES_LOG').AsString; Result := True; Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; function TAssinantesJornal.getField(sCampo: String; sColuna: String): String; begin Result := ''; if sCampo.IsEmpty then begin Exit; end; if sColuna.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.qryFields.Close; dm.qryFields.SQL.Clear; dm.qryFields.SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME); if sColuna = 'ID' then begin dm.QryGetObject.SQL.Add('WHERE ID_ASSINANTE = :ID'); dm.QryGetObject.ParamByName('ID').AsInteger := Self.ID; end else if sColuna = 'CODIGO' then begin dm.QryGetObject.SQL.Add('WHERE COD_ASSINNTE = :CODIGO'); dm.QryGetObject.ParamByName('CODIGO').AsString := Self.Codigo; end; dm.ZConn.PingServer; dm.qryFields.Open; if (not dm.qryFields.IsEmpty) then begin dm.qryFields.First; Result := dm.qryFields.FieldByName(sCampo).AsString; end; dm.qryFields.Close; dm.qryFields.SQL.Clear; end; function TAssinantesJornal.Delete(sFiltro: String): Boolean; begin Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if dm.qryCRUD.Active then begin dm.qryCRUD.Close; end; dm.qryCRUD.SQL.Clear; dm.qryCRUD.SQL.Add('DELETE FROM' + TABLENAME); if sFiltro = 'ID' then begin dm.QryGetObject.SQL.Add('WHERE ID_ASSINANTE = :ID'); dm.QryGetObject.ParamByName('ID').AsInteger := sELF.ID; end else if sFiltro = 'CODIGO' then begin dm.QryGetObject.SQL.Add('WHERE COD_ASSINNTE = :CODIGO'); dm.QryGetObject.ParamByName('CODIGO').AsString := sELF.Codigo; end else if sFiltro = 'ROTEIRO' then begin dm.QryGetObject.SQL.Add('WHERE DES_ROTEIRO = :ROTEIRO'); dm.QryGetObject.ParamByName('ROTEIRO').AsString := sELF.Roteiro; end else if sFiltro = 'NOME' then begin dm.QryGetObject.SQL.Add('WHERE NOM_ASSINANTE = :NOME'); dm.QryGetObject.ParamByName('NOME').AsString := Self.Nome; end else if sFiltro = 'PRODUTO' then begin dm.QryGetObject.SQL.Add('WHERE COD_PRODUTO = :PRODUTO'); dm.QryGetObject.ParamByName('PRODUTO').AsString := Self.Produto; end else if sFiltro = 'MODALIDADE' then begin dm.QryGetObject.SQL.Add('WHERE COD_MODALIDADE = :MODALIDADE'); dm.QryGetObject.ParamByName('MODALIDADE').AsInteger := Self.Modalidade; end; dm.ZConn.PingServer; dm.qryCRUD.ExecSQL; dm.qryCRUD.Close; dm.qryCRUD.SQL.Clear; Result := True; end; end.
unit DW.PermissionsRequester {$IF CompilerVersion > 32} deprecated 'use System.Permissions'{$ENDIF}; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses DW.PermissionsTypes; type TPermissionsResultEvent = procedure(Sender: TObject; const RequestCode: Integer; const Results: TPermissionResults) of object; TPermissionsRequester = class; TCustomPlatformPermissionsRequester = class(TObject) private FPermissionsRequester: TPermissionsRequester; protected procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); virtual; abstract; public constructor Create(const APermissionsRequester: TPermissionsRequester); virtual; property PermissionsRequester: TPermissionsRequester read FPermissionsRequester; end; TPermissionsRequester = class(TObject) private FIsRequesting: Boolean; FPlatformPermissionsRequester: TCustomPlatformPermissionsRequester; FOnPermissionsResult: TPermissionsResultEvent; protected procedure DoPermissionsResult(const RequestCode: Integer; const Results: TPermissionResults); public constructor Create; destructor Destroy; override; procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); property IsRequesting: Boolean read FIsRequesting; property OnPermissionsResult: TPermissionsResultEvent read FOnPermissionsResult write FOnPermissionsResult; end; implementation uses DW.OSLog, DW.OSDevice, {$IF Defined(ANDROID)} DW.PermissionsRequester.Android; {$ELSE} DW.PermissionsRequester.Default; {$ENDIF} { TCustomPlatformPermissionsRequester } constructor TCustomPlatformPermissionsRequester.Create(const APermissionsRequester: TPermissionsRequester); begin inherited Create; FPermissionsRequester := APermissionsRequester; end; { TPermissionsRequester } constructor TPermissionsRequester.Create; begin inherited; FPlatformPermissionsRequester := TPlatformPermissionsRequester.Create(Self); end; destructor TPermissionsRequester.Destroy; begin FPlatformPermissionsRequester.Free; inherited; end; procedure TPermissionsRequester.DoPermissionsResult(const RequestCode: Integer; const Results: TPermissionResults); begin if Assigned(FOnPermissionsResult) then FOnPermissionsResult(Self, RequestCode, Results); FIsRequesting := False; end; procedure TPermissionsRequester.RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); var LResults: TPermissionResults; begin FIsRequesting := True; if TOSDevice.CheckPermissions(APermissions, LResults) then DoPermissionsResult(ARequestCode, LResults) else FPlatformPermissionsRequester.RequestPermissions(APermissions, ARequestCode); end; end.
unit SensorFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IniFiles, Misc, ExtCtrls, SyncObjs; type TFrameSensor = class(TFrame) Panel1: TPanel; cbRepair: TCheckBox; stStatus: TStaticText; Label3: TLabel; edNetNumber: TEdit; Label7: TLabel; edCoeffK: TEdit; Label6: TLabel; edCoeffB: TEdit; procedure cbRepairClick(Sender: TObject); private { Private declarations } Section:String; public { Public declarations } CS:TCriticalSection; AdrList:TList; NetNumber:Integer; DataList:TStringList; CoeffK,CoeffB:Single; isSensorOn:Boolean; Valid_KB:Boolean; CntP:Integer; P:Single; constructor Create(AOwner:TComponent);override; procedure LoadFromIniSection(Ini:TIniFile; const Section:String); procedure WriteToIni(Ini:TIniFile); function Validate:Boolean; procedure TimerProc; destructor Destroy;override; end; TAddress=class(TObject) Host:String; Port:Integer; constructor Create(const Host:String; Port:Integer); end; implementation {$R *.DFM} uses Main; { TFrameSensor } destructor TFrameSensor.Destroy; var i:Integer; begin if AdrList<>nil then begin for i:=0 to AdrList.Count-1 do TObject(AdrList[i]).Free; AdrList.Free; end; if DataList<>nil then DataList.Free; inherited; end; procedure TFrameSensor.LoadFromIniSection(Ini: TIniFile; const Section: String); var i,Cnt:Integer; begin AdrList:=TList.Create; DataList:=TStringList.Create; Self.Section:=Section; isSensorOn:=Ini.ReadInteger(Section,'On',1)<>0; cbRepair.Checked:=not isSensorOn; edNetNumber.Text:=Ini.ReadString(Section,'NetNumber','1'); edCoeffK.Text:=Ini.ReadString(Section,'CoeffK','1'); edCoeffB.Text:=Ini.ReadString(Section,'CoeffB','0'); Cnt:=Ini.ReadInteger(Section,'DataCopies',0); for i:=1 to Cnt do begin AdrList.Add(TAddress.Create( Ini.ReadString(Section,'Host'+IntToStr(i),''), Ini.ReadInteger(Section,'Port'+IntToStr(i),0) )); end; Valid_KB:=TRUE; end; procedure TFrameSensor.TimerProc; begin if CntP=0 then P:=0; stStatus.Caption:=Format('%3d | %7.3f ',[CntP,P]);; CntP:=0; end; function TFrameSensor.Validate: Boolean; procedure ErrorMsg(const Msg:String); begin Application.MessageBox(PChar(Msg),'Программа опроса контроллера',MB_ICONINFORMATION or MB_OK); raise Exception.Create(''); end; begin Valid_KB:=FALSE; Result:=False; try try CoeffK:=StrToFloat(edCoeffK.Text); except edCoeffK.SetFocus; ErrorMsg('Ошибка в коэффициенте K'); end; try CoeffB:=StrToFloat(edCoeffB.Text); except edCoeffB.SetFocus; ErrorMsg('Ошибка в коэффициенте B'); end; try NetNumber:=StrToInt(edNetNumber.Text); if (NetNumber<0) or (255<NetNumber) then ErrorMsg('Локальный код датчика должен быть числом от 0 до 255'); except edNetNumber.SetFocus; raise; end; except exit; end; Valid_KB:=TRUE; Result:=True; end; procedure TFrameSensor.cbRepairClick(Sender: TObject); var Thd:TMainThread; begin // if cbOn.Checked then cbOn.Checked:=Validate; Thd:=TFormMain(Owner).Thd; if Thd<>nil then Thd.CS.Acquire; isSensorOn:=not cbRepair.Checked; if Thd<>nil then Thd.CS.Release; end; procedure TFrameSensor.WriteToIni(Ini: TIniFile); begin if not Valid_KB then exit; Ini.WriteInteger(Section,'On',Integer(not cbRepair.Checked)); Ini.WriteString(Section,'NetNumber',edNetNumber.Text); Ini.WriteString(Section,'CoeffK',edCoeffK.Text); Ini.WriteString(Section,'CoeffB',edCoeffB.Text); end; constructor TFrameSensor.Create(AOwner: TComponent); begin inherited; CS:=TCriticalSection.Create; end; { TAddress } constructor TAddress.Create(const Host: String; Port: Integer); begin inherited Create; Self.Host:=Host; Self.Port:=Port; end; end.
unit untPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Data.DBXMySQL, Datasnap.DBClient, SimpleDS, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, untProduto, SqlExpr; type TfrmPrincipal = class(TForm) dbgProdutos: TDBGrid; sdsProdutos: TSimpleDataSet; dsrProdutos: TDataSource; btnCadastrar: TButton; btnAlterar: TButton; btnExcluir: TButton; pnlTop: TPanel; pnlBottom: TPanel; pnlProdutos: TPanel; pnlDados: TPanel; Label1: TLabel; edtDescricao: TEdit; edtCusto: TEdit; Label2: TLabel; edtVenda: TEdit; Label3: TLabel; edtQtde: TEdit; Label4: TLabel; btnOk: TButton; btnCancelar: TButton; dtCadastro: TDateTimePicker; Label5: TLabel; edtCodInterno: TEdit; Label6: TLabel; edtCodigo: TEdit; Label7: TLabel; sdsProdutosProdutoId: TIntegerField; sdsProdutosDescricao: TStringField; sdsProdutosCodInterno: TStringField; sdsProdutosVlr_Custo: TFMTBCDField; sdsProdutosVlr_Venda: TFMTBCDField; sdsProdutosQtde: TIntegerField; sdsProdutosDataCadastro: TSQLTimeStampField; btnSair: TButton; procedure FormCreate(Sender: TObject); function IncluirProduto(Produto: TProduto): boolean; function AlterarProduto(Produto: TProduto): boolean; function DeletarProduto(nCodigo: integer): boolean; function EntreAspas(Valor: string): String; function FormatarValor(Valor: double): String; function VerificaDados: boolean; procedure LimpaDados; procedure btnCadastrarClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure edtCustoKeyPress(Sender: TObject; var Key: Char); procedure btnAlterarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); private { Private declarations } public Acao: Integer; // 0: Cadastrar; 1: Alterar end; var frmPrincipal: TfrmPrincipal; implementation uses untConexaoGeral; {$R *.dfm} function TfrmPrincipal.EntreAspas(Valor: string): String; begin result := '"' + Valor + '"'; end; function TfrmPrincipal.FormatarValor(Valor: Double): string; begin result := StringReplace(formatfloat('#0.00', Valor), ',', '.', [rfReplaceAll]) end; procedure TfrmPrincipal.LimpaDados; begin edtDescricao.Clear; edtCusto.Clear; edtVenda.Clear; edtQtde.Clear; edtCodInterno.Clear; end; function TfrmPrincipal.VerificaDados: boolean; begin result := false; if edtDescricao.Text = '' then begin ShowMessage('Insira uma descrição.'); edtDescricao.SetFocus; exit; end; if edtCodInterno.Text = '' then begin ShowMessage('Insira um código interno.'); edtCodInterno.SetFocus; exit; end; if edtQtde.Text = '' then begin ShowMessage('Insira uma quantidade.'); edtQtde.SetFocus; exit; end; if (edtCusto.Text = '') then begin ShowMessage('Insira um valor de custo.'); edtCusto.SetFocus; exit; end else begin try strtofloat(edtCusto.Text); except ShowMessage('Ocorreu um erro. Verifique o valor digitado.'); edtCusto.SetFocus; exit; end; end; if (edtVenda.Text = '') then begin ShowMessage('Insira um valor de venda.'); edtVenda.SetFocus; exit; end else begin try strtofloat(edtVenda.Text); except ShowMessage('Ocorreu um erro. Verifique o valor digitado.'); edtVenda.SetFocus; exit; end; end; result := true; end; procedure TfrmPrincipal.FormCreate(Sender: TObject); begin // Inicializa a conexão dtmConexaoGeral.Create; if not dtmConexaoGeral.Conectar then begin ShowMessage('Ocorreu um erro na conexão.'); exit; end; sdsProdutos.Active := false; sdsProdutos.DataSet.SQLConnection := dtmConexaoGeral.ConexaoGeral; sdsProdutos.Active := true; end; function TfrmPrincipal.IncluirProduto(Produto: TProduto): boolean; var Query: TSQLQuery; sSQL: String; begin try Query := TSQLQuery.Create(nil); Query.SQLConnection := dtmConexaoGeral.ConexaoGeral; Query.SQL.Clear; sSQL := 'INSERT INTO Produtos (Descricao, CodInterno, Vlr_Custo, Vlr_Venda, Qtde, DataCadastro) VALUES ' + '(' + EntreAspas(Produto.pDescricao) + ', ' + EntreAspas(Produto.pCodInterno) + ', ' + FormatarValor(Produto.pCusto) + ', ' + FormatarValor(Produto.pVenda) + ', ' + inttostr(Produto.pQtde) + ', ' + 'now()' + ')'; Query.SQL.Add(sSQL); Query.ExecSQL; result := true; except result := false; end; end; function TfrmPrincipal.AlterarProduto(Produto: TProduto): boolean; var Query: TSQLQuery; sSQL: String; begin try Query := TSQLQuery.Create(nil); Query.SQLConnection := dtmConexaoGeral.ConexaoGeral; Query.SQL.Clear; sSQL := 'UPDATE Produtos SET ' + 'Descricao = ' + EntreAspas(Produto.pDescricao) + ', ' + 'CodInterno = ' + EntreAspas(Produto.pCodInterno) + ', ' + 'Vlr_Custo = ' + FormatarValor(Produto.pCusto) + ', ' + 'Vlr_Venda = ' + FormatarValor(Produto.pVenda) + ', ' + 'Qtde = ' + inttostr(Produto.pQtde) + ' where ProdutoId = ' + inttostr(Produto.pCodigo); Query.SQL.Add(sSQL); Query.ExecSQL; result := true; except result := false; end; end; procedure TfrmPrincipal.btnAlterarClick(Sender: TObject); begin // Mostrar o panel de cadastro pnlDados.Visible := true; // Inativar os componentes que não serão usados pnlProdutos.Enabled := false; pnlTop.Enabled := false; pnlBottom.Enabled := false; Acao := 2; // Alterar edtCodigo.Text := sdsProdutosProdutoId.AsString; edtDescricao.Text := sdsProdutosDescricao.AsString; edtCodInterno.Text := sdsProdutosCodInterno.AsString; edtCusto.Text := formatfloat('#0.00', sdsProdutosVlr_Custo.AsFloat); edtVenda.Text := formatfloat('#0.00', sdsProdutosVlr_Venda.AsFloat); edtQtde.Text := sdsProdutosQtde.AsString; dtCadastro.Date := sdsProdutosDataCadastro.AsDateTime; end; procedure TfrmPrincipal.btnCadastrarClick(Sender: TObject); begin // Mostrar o panel de cadastro pnlDados.Visible := true; // Inativar os componentes que não serão usados pnlProdutos.Enabled := false; pnlTop.Enabled := false; pnlBottom.Enabled := false; Acao := 1; // Incluir dtCadastro.Date := now; end; procedure TfrmPrincipal.btnCancelarClick(Sender: TObject); begin // Limpar os dados do cadastro LimpaDados; // Esconder o panel de cadastro pnlDados.Visible := false; // Ativar novamente os componentes pnlProdutos.Enabled := true; pnlTop.Enabled := true; pnlBottom.Enabled := true; sdsProdutos.Refresh; end; procedure TfrmPrincipal.btnExcluirClick(Sender: TObject); begin if MessageDlg('Você deseja excluir o registro?', mtConfirmation, [mbYes, mbNo], 0, mbYes) = mrYes then DeletarProduto(sdsProdutosProdutoId.AsInteger) else ShowMessage('Operação cancelada pelo usuário.'); sdsProdutos.Refresh; end; procedure TfrmPrincipal.btnOkClick(Sender: TObject); var Produto: TProduto; begin // Verificar dados informados if not VerificaDados then exit; // Instanciar e alimentar o objeto TProduto Produto := TProduto.Create; Produto.pDescricao := edtDescricao.Text; Produto.pCodInterno := edtCodInterno.Text; Produto.pCusto := strtofloat(edtCusto.Text); Produto.pVenda := strtofloat(edtVenda.Text); Produto.pQtde := strtoint(edtQtde.Text); case Acao of 1: begin if not IncluirProduto(Produto) then begin ShowMessage('Ocorreu um erro! Verifique os dados informados.'); exit; end; Showmessage('Produto cadastrado com sucesso!'); end; 2: begin Produto.pCodigo := strtoint(edtCodigo.Text); if not AlterarProduto(Produto) then begin ShowMessage('Ocorreu um erro! Verifique os dados informados.'); exit; end; ShowMessage('Produto atualizado com sucesso!'); end; end; // Limpar os dados do cadastro LimpaDados; // Esconder o panel de cadastro pnlDados.Visible := false; // Ativar novamente os componentes pnlProdutos.Enabled := true; pnlTop.Enabled := true; pnlBottom.Enabled := true; sdsProdutos.Refresh; end; procedure TfrmPrincipal.btnSairClick(Sender: TObject); begin if MessageDlg('Você deseja sair do sistema?', mtConfirmation, [mbYes, mbNo], 0, mbYes) = mrYes then close; end; function TfrmPrincipal.DeletarProduto(nCodigo: Integer): boolean; var Query: TSQLQuery; sSQL: String; begin try Query := TSQLQuery.Create(nil); Query.SQLConnection := dtmConexaoGeral.ConexaoGeral; Query.SQL.Clear; sSQL := 'DELETE from Produtos where ProdutoId = ' + inttostr(nCodigo); Query.SQL.Add(sSQL); Query.ExecSQL; result := true; except result := false; end; end; procedure TfrmPrincipal.edtCustoKeyPress(Sender: TObject; var Key: Char); begin if ((key in ['0'..'9',','] = false) and (word(key) <> vk_back)) then key := #0; end; end.
unit MainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type { TMainForm } TMainForm = class(TForm) NextButton: TButton; ExitButton: TButton; InputEdit: TEdit; OutPutEdit: TEdit; InputLabel: TLabel; OutPutLabel: TLabel; procedure ExitButtonClick(Sender: TObject); { procedure FormCreate(Sender: TObject); } procedure InputEditChange(Sender: TObject); procedure InputLabelClick(Sender: TObject); procedure NextButtonClick(Sender: TObject); procedure InputEditKeyPress(Sender: TObject; var Key:Char); procedure FormActive(Sender: TObject); private public end; {var MainForm: TMainForm;} implementation uses UnitNumber; {описание класса TNumber} {$R *.lfm} { TMainForm } procedure TMainForm.ExitButtonClick(Sender: TObject); begin close; end; {закрываем окно и завершаем приложение} procedure TMainForm.FormActive(Sender: TObject); begin OutputEdit.Visible:=false; {сделать редактор вывода невидимым} OutputLabel.Visible:=false; {сделать метку вывода невидимой} NextButton.Enabled:=false; {сделать лкнопку Следующий} InputEdit.Clear; {очистить редактор ввода} InputEdit.ReadOnly:=false; {разрешить ввод} InputEdit.SetFocus; {установить фокус ввода на редактор ввода} end; procedure TMainForm.InputEditChange(Sender: TObject); begin end; procedure TMainForm.InputEditkeyPress(Sender: TObject; var Key:char); var k:single; code:integer; begin if Key=#13 then begin key:=#10; {чтобы не выдавался звуковой сигнал} val(InputEdit.Text,k,code); if code=0 then begin N:=TNumber.Create(strtofloat(InputEdit.Text)); {создать объект} OutPutEdit.Text:=floattostr(N.SqrNumber); {вывести результат} N.Destroy; {уничтожить объект - деструктор TObject} OutPutEdit.Visible:=true; {сделать редактор вывода видимым} OutputLabel.Visible:=true; {сделать метку вывода видимой} InputEdit.ReadOnly:=true; {запретить ввод} NextButton.Enabled:=true; {сделать кнопку Следующий доступной} NextButton.SetFocus; {установить фокус ввода на кнопку Следующий} end else {вывести сообщение об ошибке} MessageDlg('Stroka soderzhit nedopustimie simvoli',mtError,[mbOk],0) end; end; procedure TMainForm.InputLabelClick(Sender: TObject); begin end; procedure TMainForm.NextButtonClick(Sender: TObject); begin FormActive(NextButton); end; {вызываем метод} { TMainForm } end.
{ Date Created: 5/22/00 11:17:33 AM } unit InfoPOLCOLLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoPOLCOLLRecord = record PlenderID: String[4]; PModCount: SmallInt; Pprefix: String[3]; PpolicyNumber: String[7]; PCollateralIndex: String[1]; PCollateralYear: String[4]; PDescription: String[12]; PSerialNumber: String[5]; Pvin: String[17]; Ptitle: String[1]; Ptitledate: String[10]; PCollateralValue: Integer; PCollateralValueDate: String[10]; PPrintCollateral: String[1]; End; TInfoPOLCOLLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoPOLCOLLRecord end; TEIInfoPOLCOLL = (InfoPOLCOLLPrimaryKey, InfoPOLCOLLpolicy, InfoPOLCOLLDescription, InfoPOLCOLLSerialNumPolicy); TInfoPOLCOLLTable = class( TDBISAMTableAU ) private FDFlenderID: TStringField; FDFModCount: TSmallIntField; FDFprefix: TStringField; FDFpolicyNumber: TStringField; FDFCollateralIndex: TStringField; FDFCollateralYear: TStringField; FDFDescription: TStringField; FDFSerialNumber: TStringField; FDFvin: TStringField; FDFtitle: TStringField; FDFtitledate: TStringField; FDFCollateralValue: TIntegerField; FDFCollateralValueDate: TStringField; FDFPrintCollateral: TStringField; procedure SetPlenderID(const Value: String); function GetPlenderID:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPprefix(const Value: String); function GetPprefix:String; procedure SetPpolicyNumber(const Value: String); function GetPpolicyNumber:String; procedure SetPCollateralIndex(const Value: String); function GetPCollateralIndex:String; procedure SetPCollateralYear(const Value: String); function GetPCollateralYear:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPSerialNumber(const Value: String); function GetPSerialNumber:String; procedure SetPvin(const Value: String); function GetPvin:String; procedure SetPtitle(const Value: String); function GetPtitle:String; procedure SetPtitledate(const Value: String); function GetPtitledate:String; procedure SetPCollateralValue(const Value: Integer); function GetPCollateralValue:Integer; procedure SetPCollateralValueDate(const Value: String); function GetPCollateralValueDate:String; procedure SetPPrintCollateral(const Value: String); function GetPPrintCollateral:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoPOLCOLL); function GetEnumIndex: TEIInfoPOLCOLL; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoPOLCOLLRecord; procedure StoreDataBuffer(ABuffer:TInfoPOLCOLLRecord); property DFlenderID: TStringField read FDFlenderID; property DFModCount: TSmallIntField read FDFModCount; property DFprefix: TStringField read FDFprefix; property DFpolicyNumber: TStringField read FDFpolicyNumber; property DFCollateralIndex: TStringField read FDFCollateralIndex; property DFCollateralYear: TStringField read FDFCollateralYear; property DFDescription: TStringField read FDFDescription; property DFSerialNumber: TStringField read FDFSerialNumber; property DFvin: TStringField read FDFvin; property DFtitle: TStringField read FDFtitle; property DFtitledate: TStringField read FDFtitledate; property DFCollateralValue: TIntegerField read FDFCollateralValue; property DFCollateralValueDate: TStringField read FDFCollateralValueDate; property DFPrintCollateral: TStringField read FDFPrintCollateral; property PlenderID: String read GetPlenderID write SetPlenderID; property PModCount: SmallInt read GetPModCount write SetPModCount; property Pprefix: String read GetPprefix write SetPprefix; property PpolicyNumber: String read GetPpolicyNumber write SetPpolicyNumber; property PCollateralIndex: String read GetPCollateralIndex write SetPCollateralIndex; property PCollateralYear: String read GetPCollateralYear write SetPCollateralYear; property PDescription: String read GetPDescription write SetPDescription; property PSerialNumber: String read GetPSerialNumber write SetPSerialNumber; property Pvin: String read GetPvin write SetPvin; property Ptitle: String read GetPtitle write SetPtitle; property Ptitledate: String read GetPtitledate write SetPtitledate; property PCollateralValue: Integer read GetPCollateralValue write SetPCollateralValue; property PCollateralValueDate: String read GetPCollateralValueDate write SetPCollateralValueDate; property PPrintCollateral: String read GetPPrintCollateral write SetPPrintCollateral; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoPOLCOLL read GetEnumIndex write SetEnumIndex; end; { TInfoPOLCOLLTable } procedure Register; implementation function TInfoPOLCOLLTable.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 { TInfoPOLCOLLTable.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; { TInfoPOLCOLLTable.GenerateNewFieldName } function TInfoPOLCOLLTable.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; { TInfoPOLCOLLTable.CreateField } procedure TInfoPOLCOLLTable.CreateFields; begin FDFlenderID := CreateField( 'lenderID' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFprefix := CreateField( 'prefix' ) as TStringField; FDFpolicyNumber := CreateField( 'policyNumber' ) as TStringField; FDFCollateralIndex := CreateField( 'CollateralIndex' ) as TStringField; FDFCollateralYear := CreateField( 'CollateralYear' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFSerialNumber := CreateField( 'SerialNumber' ) as TStringField; FDFvin := CreateField( 'vin' ) as TStringField; FDFtitle := CreateField( 'title' ) as TStringField; FDFtitledate := CreateField( 'titledate' ) as TStringField; FDFCollateralValue := CreateField( 'CollateralValue' ) as TIntegerField; FDFCollateralValueDate := CreateField( 'CollateralValueDate' ) as TStringField; FDFPrintCollateral := CreateField( 'PrintCollateral' ) as TStringField; end; { TInfoPOLCOLLTable.CreateFields } procedure TInfoPOLCOLLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoPOLCOLLTable.SetActive } procedure TInfoPOLCOLLTable.Validate; begin { Enter Validation Code Here } end; { TInfoPOLCOLLTable.Validate } procedure TInfoPOLCOLLTable.SetPlenderID(const Value: String); begin DFlenderID.Value := Value; end; function TInfoPOLCOLLTable.GetPlenderID:String; begin result := DFlenderID.Value; end; procedure TInfoPOLCOLLTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoPOLCOLLTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoPOLCOLLTable.SetPprefix(const Value: String); begin DFprefix.Value := Value; end; function TInfoPOLCOLLTable.GetPprefix:String; begin result := DFprefix.Value; end; procedure TInfoPOLCOLLTable.SetPpolicyNumber(const Value: String); begin DFpolicyNumber.Value := Value; end; function TInfoPOLCOLLTable.GetPpolicyNumber:String; begin result := DFpolicyNumber.Value; end; procedure TInfoPOLCOLLTable.SetPCollateralIndex(const Value: String); begin DFCollateralIndex.Value := Value; end; function TInfoPOLCOLLTable.GetPCollateralIndex:String; begin result := DFCollateralIndex.Value; end; procedure TInfoPOLCOLLTable.SetPCollateralYear(const Value: String); begin DFCollateralYear.Value := Value; end; function TInfoPOLCOLLTable.GetPCollateralYear:String; begin result := DFCollateralYear.Value; end; procedure TInfoPOLCOLLTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoPOLCOLLTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoPOLCOLLTable.SetPSerialNumber(const Value: String); begin DFSerialNumber.Value := Value; end; function TInfoPOLCOLLTable.GetPSerialNumber:String; begin result := DFSerialNumber.Value; end; procedure TInfoPOLCOLLTable.SetPvin(const Value: String); begin DFvin.Value := Value; end; function TInfoPOLCOLLTable.GetPvin:String; begin result := DFvin.Value; end; procedure TInfoPOLCOLLTable.SetPtitle(const Value: String); begin DFtitle.Value := Value; end; function TInfoPOLCOLLTable.GetPtitle:String; begin result := DFtitle.Value; end; procedure TInfoPOLCOLLTable.SetPtitledate(const Value: String); begin DFtitledate.Value := Value; end; function TInfoPOLCOLLTable.GetPtitledate:String; begin result := DFtitledate.Value; end; procedure TInfoPOLCOLLTable.SetPCollateralValue(const Value: Integer); begin DFCollateralValue.Value := Value; end; function TInfoPOLCOLLTable.GetPCollateralValue:Integer; begin result := DFCollateralValue.Value; end; procedure TInfoPOLCOLLTable.SetPCollateralValueDate(const Value: String); begin DFCollateralValueDate.Value := Value; end; function TInfoPOLCOLLTable.GetPCollateralValueDate:String; begin result := DFCollateralValueDate.Value; end; procedure TInfoPOLCOLLTable.SetPPrintCollateral(const Value: String); begin DFPrintCollateral.Value := Value; end; function TInfoPOLCOLLTable.GetPPrintCollateral:String; begin result := DFPrintCollateral.Value; end; procedure TInfoPOLCOLLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('lenderID, String, 4, N'); Add('ModCount, SmallInt, 0, N'); Add('prefix, String, 3, N'); Add('policyNumber, String, 7, N'); Add('CollateralIndex, String, 1, N'); Add('CollateralYear, String, 4, N'); Add('Description, String, 12, N'); Add('SerialNumber, String, 5, N'); Add('vin, String, 17, N'); Add('title, String, 1, N'); Add('titledate, String, 10, N'); Add('CollateralValue, Integer, 0, N'); Add('CollateralValueDate, String, 10, N'); Add('PrintCollateral, String, 1, N'); end; end; procedure TInfoPOLCOLLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, lenderID;prefix;policyNumber, Y, Y, N, N'); Add('policy, lenderID;prefix;policyNumber, N, N, N, N'); Add('Description, Description;CollateralYear;SerialNumber;CollateralIndex;policyNumber, N, N, Y, N'); Add('SerialNumPolicy, SerialNumber;Description;CollateralIndex;policyNumber, N, N, Y, N'); end; end; procedure TInfoPOLCOLLTable.SetEnumIndex(Value: TEIInfoPOLCOLL); begin case Value of InfoPOLCOLLPrimaryKey : IndexName := ''; InfoPOLCOLLpolicy : IndexName := 'policy'; InfoPOLCOLLDescription : IndexName := 'Description'; InfoPOLCOLLSerialNumPolicy : IndexName := 'SerialNumPolicy'; end; end; function TInfoPOLCOLLTable.GetDataBuffer:TInfoPOLCOLLRecord; var buf: TInfoPOLCOLLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PlenderID := DFlenderID.Value; buf.PModCount := DFModCount.Value; buf.Pprefix := DFprefix.Value; buf.PpolicyNumber := DFpolicyNumber.Value; buf.PCollateralIndex := DFCollateralIndex.Value; buf.PCollateralYear := DFCollateralYear.Value; buf.PDescription := DFDescription.Value; buf.PSerialNumber := DFSerialNumber.Value; buf.Pvin := DFvin.Value; buf.Ptitle := DFtitle.Value; buf.Ptitledate := DFtitledate.Value; buf.PCollateralValue := DFCollateralValue.Value; buf.PCollateralValueDate := DFCollateralValueDate.Value; buf.PPrintCollateral := DFPrintCollateral.Value; result := buf; end; procedure TInfoPOLCOLLTable.StoreDataBuffer(ABuffer:TInfoPOLCOLLRecord); begin DFlenderID.Value := ABuffer.PlenderID; DFModCount.Value := ABuffer.PModCount; DFprefix.Value := ABuffer.Pprefix; DFpolicyNumber.Value := ABuffer.PpolicyNumber; DFCollateralIndex.Value := ABuffer.PCollateralIndex; DFCollateralYear.Value := ABuffer.PCollateralYear; DFDescription.Value := ABuffer.PDescription; DFSerialNumber.Value := ABuffer.PSerialNumber; DFvin.Value := ABuffer.Pvin; DFtitle.Value := ABuffer.Ptitle; DFtitledate.Value := ABuffer.Ptitledate; DFCollateralValue.Value := ABuffer.PCollateralValue; DFCollateralValueDate.Value := ABuffer.PCollateralValueDate; DFPrintCollateral.Value := ABuffer.PPrintCollateral; end; function TInfoPOLCOLLTable.GetEnumIndex: TEIInfoPOLCOLL; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoPOLCOLLPrimaryKey; if iname = 'POLICY' then result := InfoPOLCOLLpolicy; if iname = 'DESCRIPTION' then result := InfoPOLCOLLDescription; if iname = 'SERIALNUMPOLICY' then result := InfoPOLCOLLSerialNumPolicy; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoPOLCOLLTable, TInfoPOLCOLLBuffer ] ); end; { Register } function TInfoPOLCOLLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PlenderID; 2 : result := @Data.PModCount; 3 : result := @Data.Pprefix; 4 : result := @Data.PpolicyNumber; 5 : result := @Data.PCollateralIndex; 6 : result := @Data.PCollateralYear; 7 : result := @Data.PDescription; 8 : result := @Data.PSerialNumber; 9 : result := @Data.Pvin; 10 : result := @Data.Ptitle; 11 : result := @Data.Ptitledate; 12 : result := @Data.PCollateralValue; 13 : result := @Data.PCollateralValueDate; 14 : result := @Data.PPrintCollateral; end; end; end. { InfoPOLCOLLTable }
unit FmFilterSelect; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ShellApi, Vcl.ExtCtrls, Vcl.StdCtrls, VirtualTrees, System.RegularExpressions; type TFmSelelectFilter = class(TForm) pnlMain: TPanel; btnOK: TButton; btnCancel: TButton; edtFilter: TLabeledEdit; cbSearchInCode: TCheckBox; cbSearchInCaption: TCheckBox; cbRegular: TCheckBox; LinkLabel1: TLinkLabel; Memo1: TMemo; procedure LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); private FTree: TVirtualStringTree; function Like(Source, Filter: string): Boolean; public procedure SelectNodes; property Tree: TVirtualStringTree read FTree write FTree; end; var FmSelelectFilter: TFmSelelectFilter; implementation uses DocumentViewer, GsDocument; {$R *.dfm} procedure TFmSelelectFilter.btnCancelClick(Sender: TObject); begin Close; end; procedure TFmSelelectFilter.btnOKClick(Sender: TObject); begin SelectNodes; Close; end; function TFmSelelectFilter.Like(Source, Filter: string): Boolean; begin if cbRegular.Checked then Result := TRegEx.IsMatch(Source, Filter) else Result := Pos(Filter, Source) > 0; end; procedure TFmSelelectFilter.LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin ShellExecute(0, nil, PChar(Link), nil, nil, SW_SHOWNORMAL); end; procedure TFmSelelectFilter.SelectNodes; var Node: PVirtualNode; Data: PVSTDocument; Element: TGsAbstractElement; Code, Caption: string; CodeLike, CaptionLike: Boolean; begin if Not Assigned(FTree) or (edtFilter.Text = '') then Exit; FTree.ClearSelection; for Node in FTree.Nodes do begin Data := FTree.GetNodeData(Node); if (Data.Item is TGsIndexElement) or (Data.Item is TGsPriceElement) or (Data.Item is TGsRow) then begin Element := TGsAbstractElement(Data.Item); if Element is TGsRow then begin Code := TGsRow(Element).Number(True); Caption := TGsRow(Element).FullCaption; end else begin Code := Element.Code; Caption := Element.Caption; end; CodeLike := cbSearchInCode.Checked and Like(Code, edtFilter.Text); CaptionLike := cbSearchInCaption.Checked and Like(Caption, edtFilter.Text); FTree.Selected[Node] := CodeLike or CaptionLike; end; end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Androidapi.JNI.JavaTypes; interface uses Androidapi.JNIBridge; type // ===== Forward declarations ===== JObject = interface;//java.lang.Object JInputStream = interface;//java.io.InputStream JByteArrayInputStream = interface;//java.io.ByteArrayInputStream JOutputStream = interface;//java.io.OutputStream JByteArrayOutputStream = interface;//java.io.ByteArrayOutputStream JAutoCloseable = interface;//java.lang.AutoCloseable JCloseable = interface;//java.io.Closeable JFile = interface;//java.io.File JFileDescriptor = interface;//java.io.FileDescriptor JFileFilter = interface;//java.io.FileFilter JFileInputStream = interface;//java.io.FileInputStream JFileOutputStream = interface;//java.io.FileOutputStream JFilenameFilter = interface;//java.io.FilenameFilter JFilterOutputStream = interface;//java.io.FilterOutputStream JThrowable = interface;//java.lang.Throwable JException = interface;//java.lang.Exception JIOException = interface;//java.io.IOException JPrintStream = interface;//java.io.PrintStream JWriter = interface;//java.io.Writer JPrintWriter = interface;//java.io.PrintWriter JRandomAccessFile = interface;//java.io.RandomAccessFile JReader = interface;//java.io.Reader JSerializable = interface;//java.io.Serializable JAbstractStringBuilder = interface;//java.lang.AbstractStringBuilder JBoolean = interface;//java.lang.Boolean JNumber = interface;//java.lang.Number JByte = interface;//java.lang.Byte JCharSequence = interface;//java.lang.CharSequence Jlang_Class = interface;//java.lang.Class JClassLoader = interface;//java.lang.ClassLoader JComparable = interface;//java.lang.Comparable JDouble = interface;//java.lang.Double JEnum = interface;//java.lang.Enum JFloat = interface;//java.lang.Float JRuntimeException = interface;//java.lang.RuntimeException JIllegalStateException = interface;//java.lang.IllegalStateException JInteger = interface;//java.lang.Integer JIterable = interface;//java.lang.Iterable JLong = interface;//java.lang.Long JPackage = interface;//java.lang.Package JRunnable = interface;//java.lang.Runnable JShort = interface;//java.lang.Short JStackTraceElement = interface;//java.lang.StackTraceElement JString = interface;//java.lang.String JStringBuffer = interface;//java.lang.StringBuffer JStringBuilder = interface;//java.lang.StringBuilder JThread = interface;//java.lang.Thread JThread_State = interface;//java.lang.Thread$State JThread_UncaughtExceptionHandler = interface;//java.lang.Thread$UncaughtExceptionHandler JThreadGroup = interface;//java.lang.ThreadGroup JAnnotation = interface;//java.lang.annotation.Annotation JAccessibleObject = interface;//java.lang.reflect.AccessibleObject JConstructor = interface;//java.lang.reflect.Constructor JField = interface;//java.lang.reflect.Field JGenericDeclaration = interface;//java.lang.reflect.GenericDeclaration JMethod = interface;//java.lang.reflect.Method Jreflect_Type = interface;//java.lang.reflect.Type JTypeVariable = interface;//java.lang.reflect.TypeVariable JBigInteger = interface;//java.math.BigInteger JBuffer = interface;//java.nio.Buffer JByteBuffer = interface;//java.nio.ByteBuffer JByteOrder = interface;//java.nio.ByteOrder JCharBuffer = interface;//java.nio.CharBuffer JDoubleBuffer = interface;//java.nio.DoubleBuffer JFloatBuffer = interface;//java.nio.FloatBuffer JIntBuffer = interface;//java.nio.IntBuffer JLongBuffer = interface;//java.nio.LongBuffer JMappedByteBuffer = interface;//java.nio.MappedByteBuffer JShortBuffer = interface;//java.nio.ShortBuffer JChannel = interface;//java.nio.channels.Channel JAbstractInterruptibleChannel = interface;//java.nio.channels.spi.AbstractInterruptibleChannel JSelectableChannel = interface;//java.nio.channels.SelectableChannel JAbstractSelectableChannel = interface;//java.nio.channels.spi.AbstractSelectableChannel JDatagramChannel = interface;//java.nio.channels.DatagramChannel JFileChannel = interface;//java.nio.channels.FileChannel JFileChannel_MapMode = interface;//java.nio.channels.FileChannel$MapMode JFileLock = interface;//java.nio.channels.FileLock JPipe = interface;//java.nio.channels.Pipe JPipe_SinkChannel = interface;//java.nio.channels.Pipe$SinkChannel JPipe_SourceChannel = interface;//java.nio.channels.Pipe$SourceChannel JReadableByteChannel = interface;//java.nio.channels.ReadableByteChannel JSelectionKey = interface;//java.nio.channels.SelectionKey JSelector = interface;//java.nio.channels.Selector JServerSocketChannel = interface;//java.nio.channels.ServerSocketChannel JSocketChannel = interface;//java.nio.channels.SocketChannel JWritableByteChannel = interface;//java.nio.channels.WritableByteChannel JAbstractSelector = interface;//java.nio.channels.spi.AbstractSelector JSelectorProvider = interface;//java.nio.channels.spi.SelectorProvider JCharset = interface;//java.nio.charset.Charset JCharsetDecoder = interface;//java.nio.charset.CharsetDecoder JCharsetEncoder = interface;//java.nio.charset.CharsetEncoder JCoderResult = interface;//java.nio.charset.CoderResult JCodingErrorAction = interface;//java.nio.charset.CodingErrorAction JAbstractCollection = interface;//java.util.AbstractCollection JAbstractList = interface;//java.util.AbstractList JAbstractMap = interface;//java.util.AbstractMap JAbstractSet = interface;//java.util.AbstractSet JArrayList = interface;//java.util.ArrayList JBitSet = interface;//java.util.BitSet JCalendar = interface;//java.util.Calendar JCollection = interface;//java.util.Collection JComparator = interface;//java.util.Comparator JDate = interface;//java.util.Date JDictionary = interface;//java.util.Dictionary JEnumSet = interface;//java.util.EnumSet JEnumeration = interface;//java.util.Enumeration JGregorianCalendar = interface;//java.util.GregorianCalendar JHashMap = interface;//java.util.HashMap JHashSet = interface;//java.util.HashSet JHashtable = interface;//java.util.Hashtable JIterator = interface;//java.util.Iterator JList = interface;//java.util.List JListIterator = interface;//java.util.ListIterator JLocale = interface;//java.util.Locale JMap = interface;//java.util.Map Jutil_Observable = interface;//java.util.Observable JObserver = interface;//java.util.Observer JProperties = interface;//java.util.Properties JQueue = interface;//java.util.Queue JRandom = interface;//java.util.Random JSet = interface;//java.util.Set JSortedMap = interface;//java.util.SortedMap JTimeZone = interface;//java.util.TimeZone JUUID = interface;//java.util.UUID JBlockingQueue = interface;//java.util.concurrent.BlockingQueue JCallable = interface;//java.util.concurrent.Callable JCountDownLatch = interface;//java.util.concurrent.CountDownLatch JExecutor = interface;//java.util.concurrent.Executor JExecutorService = interface;//java.util.concurrent.ExecutorService JFuture = interface;//java.util.concurrent.Future JTimeUnit = interface;//java.util.concurrent.TimeUnit //JSecretKey = interface;//javax.crypto.SecretKey JEGL = interface;//javax.microedition.khronos.egl.EGL JEGL10 = interface;//javax.microedition.khronos.egl.EGL10 JEGLConfig = interface;//javax.microedition.khronos.egl.EGLConfig JEGLContext = interface;//javax.microedition.khronos.egl.EGLContext JEGLDisplay = interface;//javax.microedition.khronos.egl.EGLDisplay JEGLSurface = interface;//javax.microedition.khronos.egl.EGLSurface JGL = interface;//javax.microedition.khronos.opengles.GL JGL10 = interface;//javax.microedition.khronos.opengles.GL10 JJSONArray = interface;//org.json.JSONArray JJSONException = interface;//org.json.JSONException JJSONObject = interface;//org.json.JSONObject JJSONTokener = interface;//org.json.JSONTokener JXmlPullParser = interface;//org.xmlpull.v1.XmlPullParser JXmlSerializer = interface;//org.xmlpull.v1.XmlSerializer // ===== Interface declarations ===== JObjectClass = interface(IJavaClass) ['{83BD30EE-FE9B-470D-AD6C-23AEAABB7FFA}'] {class} function init: JObject; cdecl; end; [JavaSignature('java/lang/Object')] JObject = interface(IJavaInstance) ['{32321F8A-4001-4BF8-92E7-6190D070988D}'] function equals(o: JObject): Boolean; cdecl; function getClass: Jlang_Class; cdecl; function hashCode: Integer; cdecl; procedure notify; cdecl; procedure notifyAll; cdecl; function toString: JString; cdecl; procedure wait; cdecl; overload; procedure wait(millis: Int64); cdecl; overload; procedure wait(millis: Int64; nanos: Integer); cdecl; overload; end; TJObject = class(TJavaGenericImport<JObjectClass, JObject>) end; JInputStreamClass = interface(JObjectClass) ['{8D8C2F8A-AD54-42D0-ADA4-FC30FD95A933}'] {class} function init: JInputStream; cdecl; end; [JavaSignature('java/io/InputStream')] JInputStream = interface(JObject) ['{5FD3C203-8A19-42A2-8FD2-643501DF62BC}'] function available: Integer; cdecl; procedure close; cdecl; procedure mark(readlimit: Integer); cdecl; function markSupported: Boolean; cdecl; function read: Integer; cdecl; overload; function read(buffer: TJavaArray<Byte>): Integer; cdecl; overload; function read(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer): Integer; cdecl; overload; procedure reset; cdecl; function skip(byteCount: Int64): Int64; cdecl; end; TJInputStream = class(TJavaGenericImport<JInputStreamClass, JInputStream>) end; JByteArrayInputStreamClass = interface(JInputStreamClass) ['{1C0763C7-3F23-4531-A6E1-65AF97251C2F}'] {class} function init(buf: TJavaArray<Byte>): JByteArrayInputStream; cdecl; overload; {class} function init(buf: TJavaArray<Byte>; offset: Integer; length: Integer): JByteArrayInputStream; cdecl; overload; end; [JavaSignature('java/io/ByteArrayInputStream')] JByteArrayInputStream = interface(JInputStream) ['{D8AE245D-6831-48AC-A6F5-1E480815A22D}'] function available: Integer; cdecl; procedure close; cdecl; procedure mark(readlimit: Integer); cdecl; function markSupported: Boolean; cdecl; function read: Integer; cdecl; overload; function read(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer): Integer; cdecl; overload; procedure reset; cdecl; function skip(byteCount: Int64): Int64; cdecl; end; TJByteArrayInputStream = class(TJavaGenericImport<JByteArrayInputStreamClass, JByteArrayInputStream>) end; JOutputStreamClass = interface(JObjectClass) ['{769D969C-3DFB-417B-8B7E-AA5662FB1539}'] {class} function init: JOutputStream; cdecl; end; [JavaSignature('java/io/OutputStream')] JOutputStream = interface(JObject) ['{308A10DA-ACF9-4EC3-B4BD-D9F9CEEB29A5}'] procedure close; cdecl; procedure flush; cdecl; procedure write(buffer: TJavaArray<Byte>); cdecl; overload; procedure write(buffer: TJavaArray<Byte>; offset: Integer; count: Integer); cdecl; overload; procedure write(oneByte: Integer); cdecl; overload; end; TJOutputStream = class(TJavaGenericImport<JOutputStreamClass, JOutputStream>) end; JByteArrayOutputStreamClass = interface(JOutputStreamClass) ['{2F08E462-5F49-4A89-9ACD-F0A5CD01C3A8}'] {class} function init: JByteArrayOutputStream; cdecl; overload; {class} function init(size: Integer): JByteArrayOutputStream; cdecl; overload; end; [JavaSignature('java/io/ByteArrayOutputStream')] JByteArrayOutputStream = interface(JOutputStream) ['{6AD653C4-3A67-4CCD-9B53-2E57D0DC0727}'] procedure close; cdecl; procedure reset; cdecl; function size: Integer; cdecl; function toByteArray: TJavaArray<Byte>; cdecl; function toString: JString; cdecl; overload; function toString(hibyte: Integer): JString; cdecl; overload;//Deprecated function toString(charsetName: JString): JString; cdecl; overload; procedure write(buffer: TJavaArray<Byte>; offset: Integer; len: Integer); cdecl; overload; procedure write(oneByte: Integer); cdecl; overload; procedure writeTo(out_: JOutputStream); cdecl; end; TJByteArrayOutputStream = class(TJavaGenericImport<JByteArrayOutputStreamClass, JByteArrayOutputStream>) end; JAutoCloseableClass = interface(IJavaClass) ['{BC0BF424-12A8-4AA4-ABC4-29A2BCE762E3}'] end; [JavaSignature('java/lang/AutoCloseable')] JAutoCloseable = interface(IJavaInstance) ['{48D31CFB-52DE-4C24-985E-3601B839C436}'] procedure close; cdecl; end; TJAutoCloseable = class(TJavaGenericImport<JAutoCloseableClass, JAutoCloseable>) end; JCloseableClass = interface(JAutoCloseableClass) ['{CAFF3044-E3EC-444F-AF50-403A65BFA20B}'] end; [JavaSignature('java/io/Closeable')] JCloseable = interface(JAutoCloseable) ['{DD3E86BD-46E1-44D8-84DD-B7607A3F9C56}'] procedure close; cdecl; end; TJCloseable = class(TJavaGenericImport<JCloseableClass, JCloseable>) end; JFileClass = interface(JObjectClass) ['{D2CE81B7-01CE-468B-A2F2-B85DD35642EC}'] {class} function _GetpathSeparator: JString; cdecl; {class} function _GetpathSeparatorChar: Char; cdecl; {class} function _Getseparator: JString; cdecl; {class} function _GetseparatorChar: Char; cdecl; {class} function init(dir: JFile; name: JString): JFile; cdecl; overload; {class} function init(path: JString): JFile; cdecl; overload; {class} function init(dirPath: JString; name: JString): JFile; cdecl; overload; {class} //function init(uri: JURI): JFile; cdecl; overload; {class} function createTempFile(prefix: JString; suffix: JString): JFile; cdecl; overload; {class} function createTempFile(prefix: JString; suffix: JString; directory: JFile): JFile; cdecl; overload; {class} function listRoots: TJavaObjectArray<JFile>; cdecl; {class} property pathSeparator: JString read _GetpathSeparator; {class} property pathSeparatorChar: Char read _GetpathSeparatorChar; {class} property separator: JString read _Getseparator; {class} property separatorChar: Char read _GetseparatorChar; end; [JavaSignature('java/io/File')] JFile = interface(JObject) ['{38C3EB7E-315A-47D2-9052-1E61170EB37F}'] function canExecute: Boolean; cdecl; function canRead: Boolean; cdecl; function canWrite: Boolean; cdecl; function compareTo(another: JFile): Integer; cdecl; function createNewFile: Boolean; cdecl; function delete: Boolean; cdecl; procedure deleteOnExit; cdecl; function equals(obj: JObject): Boolean; cdecl; function exists: Boolean; cdecl; function getAbsoluteFile: JFile; cdecl; function getAbsolutePath: JString; cdecl; function getCanonicalFile: JFile; cdecl; function getCanonicalPath: JString; cdecl; function getFreeSpace: Int64; cdecl; function getName: JString; cdecl; function getParent: JString; cdecl; function getParentFile: JFile; cdecl; function getPath: JString; cdecl; function getTotalSpace: Int64; cdecl; function getUsableSpace: Int64; cdecl; function hashCode: Integer; cdecl; function isAbsolute: Boolean; cdecl; function isDirectory: Boolean; cdecl; function isFile: Boolean; cdecl; function isHidden: Boolean; cdecl; function lastModified: Int64; cdecl; function length: Int64; cdecl; function list: TJavaObjectArray<JString>; cdecl; overload; function list(filter: JFilenameFilter): TJavaObjectArray<JString>; cdecl; overload; function listFiles: TJavaObjectArray<JFile>; cdecl; overload; function listFiles(filter: JFilenameFilter): TJavaObjectArray<JFile>; cdecl; overload; function listFiles(filter: JFileFilter): TJavaObjectArray<JFile>; cdecl; overload; function mkdir: Boolean; cdecl; function mkdirs: Boolean; cdecl; function renameTo(newPath: JFile): Boolean; cdecl; function setExecutable(executable: Boolean; ownerOnly: Boolean): Boolean; cdecl; overload; function setExecutable(executable: Boolean): Boolean; cdecl; overload; function setLastModified(time: Int64): Boolean; cdecl; function setReadOnly: Boolean; cdecl; function setReadable(readable: Boolean; ownerOnly: Boolean): Boolean; cdecl; overload; function setReadable(readable: Boolean): Boolean; cdecl; overload; function setWritable(writable: Boolean; ownerOnly: Boolean): Boolean; cdecl; overload; function setWritable(writable: Boolean): Boolean; cdecl; overload; function toString: JString; cdecl; //function toURI: JURI; cdecl; //function toURL: JURL; cdecl;//Deprecated end; TJFile = class(TJavaGenericImport<JFileClass, JFile>) end; JFileDescriptorClass = interface(JObjectClass) ['{B01F2343-4F8E-4FF8-838E-8FB9CFE304E2}'] {class} function _Geterr: JFileDescriptor; cdecl; {class} function _Getin: JFileDescriptor; cdecl; {class} function _Getout: JFileDescriptor; cdecl; {class} function init: JFileDescriptor; cdecl; {class} property err: JFileDescriptor read _Geterr; {class} property &in: JFileDescriptor read _Getin; {class} property &out: JFileDescriptor read _Getout; end; [JavaSignature('java/io/FileDescriptor')] JFileDescriptor = interface(JObject) ['{B6D7B003-DD99-4563-93A3-F902501CD6C1}'] procedure sync; cdecl; function toString: JString; cdecl; function valid: Boolean; cdecl; end; TJFileDescriptor = class(TJavaGenericImport<JFileDescriptorClass, JFileDescriptor>) end; JFileFilterClass = interface(IJavaClass) ['{74779212-F9FA-40FE-A5C2-41FBC7919220}'] end; [JavaSignature('java/io/FileFilter')] JFileFilter = interface(IJavaInstance) ['{5A5564B5-D25E-4D6A-AF92-F0725E9011DE}'] function accept(pathname: JFile): Boolean; cdecl; end; TJFileFilter = class(TJavaGenericImport<JFileFilterClass, JFileFilter>) end; JFileInputStreamClass = interface(JInputStreamClass) ['{A1EB6AE5-8562-4E38-8182-61F57E51733A}'] {class} function init(file_: JFile): JFileInputStream; cdecl; overload; {class} function init(fd: JFileDescriptor): JFileInputStream; cdecl; overload; {class} function init(path: JString): JFileInputStream; cdecl; overload; end; [JavaSignature('java/io/FileInputStream')] JFileInputStream = interface(JInputStream) ['{55CBCA4D-B04C-442A-BD74-ADFFD715A1A5}'] function available: Integer; cdecl; procedure close; cdecl; function getChannel: JFileChannel; cdecl; function getFD: JFileDescriptor; cdecl; function read: Integer; cdecl; overload; function read(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer): Integer; cdecl; overload; function skip(byteCount: Int64): Int64; cdecl; end; TJFileInputStream = class(TJavaGenericImport<JFileInputStreamClass, JFileInputStream>) end; JFileOutputStreamClass = interface(JOutputStreamClass) ['{4808736C-4C9B-46DF-A1B6-EB94324D9666}'] {class} function init(file_: JFile): JFileOutputStream; cdecl; overload; {class} function init(file_: JFile; append: Boolean): JFileOutputStream; cdecl; overload; {class} function init(fd: JFileDescriptor): JFileOutputStream; cdecl; overload; {class} function init(path: JString): JFileOutputStream; cdecl; overload; {class} function init(path: JString; append: Boolean): JFileOutputStream; cdecl; overload; end; [JavaSignature('java/io/FileOutputStream')] JFileOutputStream = interface(JOutputStream) ['{3D49DAFB-A222-4001-9DBE-7FAE66E23404}'] procedure close; cdecl; function getChannel: JFileChannel; cdecl; function getFD: JFileDescriptor; cdecl; procedure write(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer); cdecl; overload; procedure write(oneByte: Integer); cdecl; overload; end; TJFileOutputStream = class(TJavaGenericImport<JFileOutputStreamClass, JFileOutputStream>) end; JFilenameFilterClass = interface(IJavaClass) ['{E466E540-E65D-43EC-8913-E8F8AEEA354F}'] end; [JavaSignature('java/io/FilenameFilter')] JFilenameFilter = interface(IJavaInstance) ['{B55A4F67-1AE9-41F5-BCF8-305D3902A782}'] function accept(dir: JFile; filename: JString): Boolean; cdecl; end; TJFilenameFilter = class(TJavaGenericImport<JFilenameFilterClass, JFilenameFilter>) end; JFilterOutputStreamClass = interface(JOutputStreamClass) ['{4273682E-2DA8-4BA9-BFC7-A9356DC43D40}'] {class} function init(out_: JOutputStream): JFilterOutputStream; cdecl; end; [JavaSignature('java/io/FilterOutputStream')] JFilterOutputStream = interface(JOutputStream) ['{B0DB7F97-9758-43B1-8FC4-19A12503CD3F}'] procedure close; cdecl; procedure flush; cdecl; procedure write(buffer: TJavaArray<Byte>; offset: Integer; length: Integer); cdecl; overload; procedure write(oneByte: Integer); cdecl; overload; end; TJFilterOutputStream = class(TJavaGenericImport<JFilterOutputStreamClass, JFilterOutputStream>) end; JThrowableClass = interface(JObjectClass) ['{9B871585-74E6-4B49-B4C2-4DB387B0E599}'] {class} function init: JThrowable; cdecl; overload; {class} function init(detailMessage: JString): JThrowable; cdecl; overload; {class} function init(detailMessage: JString; cause: JThrowable): JThrowable; cdecl; overload; {class} function init(cause: JThrowable): JThrowable; cdecl; overload; end; [JavaSignature('java/lang/Throwable')] JThrowable = interface(JObject) ['{44BECA0F-21B9-45A8-B21F-8806ABE80CE2}'] procedure addSuppressed(throwable: JThrowable); cdecl; function fillInStackTrace: JThrowable; cdecl; function getCause: JThrowable; cdecl; function getLocalizedMessage: JString; cdecl; function getMessage: JString; cdecl; function getStackTrace: TJavaObjectArray<JStackTraceElement>; cdecl; function getSuppressed: TJavaObjectArray<JThrowable>; cdecl; function initCause(throwable: JThrowable): JThrowable; cdecl; procedure printStackTrace; cdecl; overload; procedure printStackTrace(err: JPrintStream); cdecl; overload; procedure printStackTrace(err: JPrintWriter); cdecl; overload; procedure setStackTrace(trace: TJavaObjectArray<JStackTraceElement>); cdecl; function toString: JString; cdecl; end; TJThrowable = class(TJavaGenericImport<JThrowableClass, JThrowable>) end; JExceptionClass = interface(JThrowableClass) ['{6E1BA58E-A106-4CC0-A40C-99F4E1188B10}'] {class} function init: JException; cdecl; overload; {class} function init(detailMessage: JString): JException; cdecl; overload; {class} function init(detailMessage: JString; throwable: JThrowable): JException; cdecl; overload; {class} function init(throwable: JThrowable): JException; cdecl; overload; end; [JavaSignature('java/lang/Exception')] JException = interface(JThrowable) ['{6EA7D981-2F3C-44C4-B9D2-F581529C08E0}'] end; TJException = class(TJavaGenericImport<JExceptionClass, JException>) end; JIOExceptionClass = interface(JExceptionClass) ['{24D5DABE-094D-45DB-9F6A-A5AB51B47322}'] {class} function init: JIOException; cdecl; overload; {class} function init(detailMessage: JString): JIOException; cdecl; overload; {class} function init(message: JString; cause: JThrowable): JIOException; cdecl; overload; {class} function init(cause: JThrowable): JIOException; cdecl; overload; end; [JavaSignature('java/io/IOException')] JIOException = interface(JException) ['{7318D96A-B3D4-4168-BDAB-356A539E6399}'] end; TJIOException = class(TJavaGenericImport<JIOExceptionClass, JIOException>) end; JPrintStreamClass = interface(JFilterOutputStreamClass) ['{4B5683E3-32D0-4225-9A80-FB961D9B334F}'] {class} function init(out_: JOutputStream): JPrintStream; cdecl; overload; {class} function init(out_: JOutputStream; autoFlush: Boolean): JPrintStream; cdecl; overload; {class} function init(out_: JOutputStream; autoFlush: Boolean; charsetName: JString): JPrintStream; cdecl; overload; {class} function init(file_: JFile): JPrintStream; cdecl; overload; {class} function init(file_: JFile; charsetName: JString): JPrintStream; cdecl; overload; {class} function init(fileName: JString): JPrintStream; cdecl; overload; {class} function init(fileName: JString; charsetName: JString): JPrintStream; cdecl; overload; end; [JavaSignature('java/io/PrintStream')] JPrintStream = interface(JFilterOutputStream) ['{8B23171F-06EF-4D87-A463-863F687A7918}'] function append(c: Char): JPrintStream; cdecl; overload; function append(charSequence: JCharSequence): JPrintStream; cdecl; overload; function append(charSequence: JCharSequence; start: Integer; end_: Integer): JPrintStream; cdecl; overload; function checkError: Boolean; cdecl; procedure close; cdecl; procedure flush; cdecl; procedure print(chars: TJavaArray<Char>); cdecl; overload; procedure print(c: Char); cdecl; overload; procedure print(d: Double); cdecl; overload; procedure print(f: Single); cdecl; overload; procedure print(i: Integer); cdecl; overload; procedure print(l: Int64); cdecl; overload; procedure print(o: JObject); cdecl; overload; procedure print(str: JString); cdecl; overload; procedure print(b: Boolean); cdecl; overload; procedure println; cdecl; overload; procedure println(chars: TJavaArray<Char>); cdecl; overload; procedure println(c: Char); cdecl; overload; procedure println(d: Double); cdecl; overload; procedure println(f: Single); cdecl; overload; procedure println(i: Integer); cdecl; overload; procedure println(l: Int64); cdecl; overload; procedure println(o: JObject); cdecl; overload; procedure println(str: JString); cdecl; overload; procedure println(b: Boolean); cdecl; overload; procedure write(buffer: TJavaArray<Byte>; offset: Integer; length: Integer); cdecl; overload; procedure write(oneByte: Integer); cdecl; overload; end; TJPrintStream = class(TJavaGenericImport<JPrintStreamClass, JPrintStream>) end; JWriterClass = interface(JObjectClass) ['{1B3FE1C9-6FF8-45AE-89D6-267E4CC1F003}'] end; [JavaSignature('java/io/Writer')] JWriter = interface(JObject) ['{50C5DAA8-B851-43A7-8FF9-E827DC14E67B}'] function append(c: Char): JWriter; cdecl; overload; function append(csq: JCharSequence): JWriter; cdecl; overload; function append(csq: JCharSequence; start: Integer; end_: Integer): JWriter; cdecl; overload; procedure close; cdecl; procedure flush; cdecl; procedure write(buf: TJavaArray<Char>); cdecl; overload; procedure write(buf: TJavaArray<Char>; offset: Integer; count: Integer); cdecl; overload; procedure write(oneChar: Integer); cdecl; overload; procedure write(str: JString); cdecl; overload; procedure write(str: JString; offset: Integer; count: Integer); cdecl; overload; end; TJWriter = class(TJavaGenericImport<JWriterClass, JWriter>) end; JPrintWriterClass = interface(JWriterClass) ['{0176F2C9-CDCB-40D9-B26E-E983BE269B0D}'] {class} function init(out_: JOutputStream): JPrintWriter; cdecl; overload; {class} function init(out_: JOutputStream; autoFlush: Boolean): JPrintWriter; cdecl; overload; {class} function init(wr: JWriter): JPrintWriter; cdecl; overload; {class} function init(wr: JWriter; autoFlush: Boolean): JPrintWriter; cdecl; overload; {class} function init(file_: JFile): JPrintWriter; cdecl; overload; {class} function init(file_: JFile; csn: JString): JPrintWriter; cdecl; overload; {class} function init(fileName: JString): JPrintWriter; cdecl; overload; {class} function init(fileName: JString; csn: JString): JPrintWriter; cdecl; overload; end; [JavaSignature('java/io/PrintWriter')] JPrintWriter = interface(JWriter) ['{1C7483CD-045F-4478-A223-A9FBBF9C1D80}'] function append(c: Char): JPrintWriter; cdecl; overload; function append(csq: JCharSequence): JPrintWriter; cdecl; overload; function append(csq: JCharSequence; start: Integer; end_: Integer): JPrintWriter; cdecl; overload; function checkError: Boolean; cdecl; procedure close; cdecl; procedure flush; cdecl; procedure print(charArray: TJavaArray<Char>); cdecl; overload; procedure print(ch: Char); cdecl; overload; procedure print(dnum: Double); cdecl; overload; procedure print(fnum: Single); cdecl; overload; procedure print(inum: Integer); cdecl; overload; procedure print(lnum: Int64); cdecl; overload; procedure print(obj: JObject); cdecl; overload; procedure print(str: JString); cdecl; overload; procedure print(bool: Boolean); cdecl; overload; procedure println; cdecl; overload; procedure println(chars: TJavaArray<Char>); cdecl; overload; procedure println(c: Char); cdecl; overload; procedure println(d: Double); cdecl; overload; procedure println(f: Single); cdecl; overload; procedure println(i: Integer); cdecl; overload; procedure println(l: Int64); cdecl; overload; procedure println(obj: JObject); cdecl; overload; procedure println(str: JString); cdecl; overload; procedure println(b: Boolean); cdecl; overload; procedure write(buf: TJavaArray<Char>); cdecl; overload; procedure write(buf: TJavaArray<Char>; offset: Integer; count: Integer); cdecl; overload; procedure write(oneChar: Integer); cdecl; overload; procedure write(str: JString); cdecl; overload; procedure write(str: JString; offset: Integer; count: Integer); cdecl; overload; end; TJPrintWriter = class(TJavaGenericImport<JPrintWriterClass, JPrintWriter>) end; JRandomAccessFileClass = interface(JObjectClass) ['{A3AAF4BA-F473-4135-AF7F-13B89D0BA76A}'] {class} function init(file_: JFile; mode: JString): JRandomAccessFile; cdecl; overload; {class} function init(fileName: JString; mode: JString): JRandomAccessFile; cdecl; overload; end; [JavaSignature('java/io/RandomAccessFile')] JRandomAccessFile = interface(JObject) ['{59DD1A15-35C5-456F-BBE2-61B628DAE3DB}'] procedure close; cdecl; function getChannel: JFileChannel; cdecl; function getFD: JFileDescriptor; cdecl; function getFilePointer: Int64; cdecl; function length: Int64; cdecl; function read: Integer; cdecl; overload; function read(buffer: TJavaArray<Byte>): Integer; cdecl; overload; function read(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer): Integer; cdecl; overload; function readBoolean: Boolean; cdecl; function readByte: Byte; cdecl; function readChar: Char; cdecl; function readDouble: Double; cdecl; function readFloat: Single; cdecl; procedure readFully(dst: TJavaArray<Byte>); cdecl; overload; procedure readFully(dst: TJavaArray<Byte>; offset: Integer; byteCount: Integer); cdecl; overload; function readInt: Integer; cdecl; function readLine: JString; cdecl; function readLong: Int64; cdecl; function readShort: SmallInt; cdecl; function readUTF: JString; cdecl; function readUnsignedByte: Integer; cdecl; function readUnsignedShort: Integer; cdecl; procedure seek(offset: Int64); cdecl; procedure setLength(newLength: Int64); cdecl; function skipBytes(count: Integer): Integer; cdecl; procedure write(buffer: TJavaArray<Byte>); cdecl; overload; procedure write(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer); cdecl; overload; procedure write(oneByte: Integer); cdecl; overload; procedure writeBoolean(val: Boolean); cdecl; procedure writeByte(val: Integer); cdecl; procedure writeBytes(str: JString); cdecl; procedure writeChar(val: Integer); cdecl; procedure writeChars(str: JString); cdecl; procedure writeDouble(val: Double); cdecl; procedure writeFloat(val: Single); cdecl; procedure writeInt(val: Integer); cdecl; procedure writeLong(val: Int64); cdecl; procedure writeShort(val: Integer); cdecl; procedure writeUTF(str: JString); cdecl; end; TJRandomAccessFile = class(TJavaGenericImport<JRandomAccessFileClass, JRandomAccessFile>) end; JReaderClass = interface(JObjectClass) ['{C04A4F72-F3EC-4774-9336-AA82265956FF}'] end; [JavaSignature('java/io/Reader')] JReader = interface(JObject) ['{D163CFD3-9781-435C-8FF5-98667DCD8189}'] procedure close; cdecl; procedure mark(readLimit: Integer); cdecl; function markSupported: Boolean; cdecl; function read: Integer; cdecl; overload; function read(buffer: TJavaArray<Char>): Integer; cdecl; overload; function read(buffer: TJavaArray<Char>; offset: Integer; count: Integer): Integer; cdecl; overload; function read(target: JCharBuffer): Integer; cdecl; overload; function ready: Boolean; cdecl; procedure reset; cdecl; function skip(charCount: Int64): Int64; cdecl; end; TJReader = class(TJavaGenericImport<JReaderClass, JReader>) end; JSerializableClass = interface(IJavaClass) ['{BFE14BCE-11F1-41B5-A14F-3217521E82BA}'] end; [JavaSignature('java/io/Serializable')] JSerializable = interface(IJavaInstance) ['{D24AB8DC-4E6F-411D-9C40-2210F71A3B0D}'] end; TJSerializable = class(TJavaGenericImport<JSerializableClass, JSerializable>) end; JAbstractStringBuilderClass = interface(JObjectClass) ['{A3321EF2-EA76-44CD-90CE-DFDADB9936BD}'] end; [JavaSignature('java/lang/AbstractStringBuilder')] JAbstractStringBuilder = interface(JObject) ['{39A0E6C5-8F79-44ED-BECB-02252CA2F5C0}'] function capacity: Integer; cdecl; function charAt(index: Integer): Char; cdecl; function codePointAt(index: Integer): Integer; cdecl; function codePointBefore(index: Integer): Integer; cdecl; function codePointCount(start: Integer; end_: Integer): Integer; cdecl; procedure ensureCapacity(min: Integer); cdecl; procedure getChars(start: Integer; end_: Integer; dst: TJavaArray<Char>; dstStart: Integer); cdecl; function indexOf(string_: JString): Integer; cdecl; overload; function indexOf(subString: JString; start: Integer): Integer; cdecl; overload; function lastIndexOf(string_: JString): Integer; cdecl; overload; function lastIndexOf(subString: JString; start: Integer): Integer; cdecl; overload; function length: Integer; cdecl; function offsetByCodePoints(index: Integer; codePointOffset: Integer): Integer; cdecl; procedure setCharAt(index: Integer; ch: Char); cdecl; procedure setLength(length: Integer); cdecl; function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl; function substring(start: Integer): JString; cdecl; overload; function substring(start: Integer; end_: Integer): JString; cdecl; overload; function toString: JString; cdecl; procedure trimToSize; cdecl; end; TJAbstractStringBuilder = class(TJavaGenericImport<JAbstractStringBuilderClass, JAbstractStringBuilder>) end; JBooleanClass = interface(JObjectClass) ['{CD51CE90-BCDA-4291-99B0-7BC70033C3CB}'] {class} function _GetFALSE: JBoolean; cdecl; {class} function _GetTRUE: JBoolean; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(string_: JString): JBoolean; cdecl; overload; {class} function init(value: Boolean): JBoolean; cdecl; overload; {class} function compare(lhs: Boolean; rhs: Boolean): Integer; cdecl; {class} function getBoolean(string_: JString): Boolean; cdecl; {class} function parseBoolean(s: JString): Boolean; cdecl; {class} function toString(value: Boolean): JString; cdecl; overload; {class} function valueOf(string_: JString): JBoolean; cdecl; overload; {class} function valueOf(b: Boolean): JBoolean; cdecl; overload; {class} property FALSE: JBoolean read _GetFALSE; {class} property TRUE: JBoolean read _GetTRUE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Boolean')] JBoolean = interface(JObject) ['{21EAFAED-5848-48C2-9998-141B57439F6F}'] function booleanValue: Boolean; cdecl; function compareTo(that: JBoolean): Integer; cdecl; function equals(o: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; function toString: JString; cdecl; overload; end; TJBoolean = class(TJavaGenericImport<JBooleanClass, JBoolean>) end; JNumberClass = interface(JObjectClass) ['{9A30B143-2018-4C7B-9E9B-316F62D643C5}'] {class} function init: JNumber; cdecl; end; [JavaSignature('java/lang/Number')] JNumber = interface(JObject) ['{DFF915A9-AFBE-4EDA-89AC-D0FE32A85482}'] function byteValue: Byte; cdecl; function doubleValue: Double; cdecl; function floatValue: Single; cdecl; function intValue: Integer; cdecl; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; end; TJNumber = class(TJavaGenericImport<JNumberClass, JNumber>) end; JByteClass = interface(JNumberClass) ['{EDEFB599-A2A8-49AD-B413-C2FCEBD19B11}'] {class} function _GetMAX_VALUE: Byte; cdecl; {class} function _GetMIN_VALUE: Byte; cdecl; {class} function _GetSIZE: Integer; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(value: Byte): JByte; cdecl; overload; {class} function init(string_: JString): JByte; cdecl; overload; {class} function compare(lhs: Byte; rhs: Byte): Integer; cdecl; {class} function decode(string_: JString): JByte; cdecl; {class} function parseByte(string_: JString): Byte; cdecl; overload; {class} function parseByte(string_: JString; radix: Integer): Byte; cdecl; overload; {class} function toString(value: Byte): JString; cdecl; overload; {class} function valueOf(string_: JString): JByte; cdecl; overload; {class} function valueOf(string_: JString; radix: Integer): JByte; cdecl; overload; {class} function valueOf(b: Byte): JByte; cdecl; overload; {class} property MAX_VALUE: Byte read _GetMAX_VALUE; {class} property MIN_VALUE: Byte read _GetMIN_VALUE; {class} property SIZE: Integer read _GetSIZE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Byte')] JByte = interface(JNumber) ['{882439AC-111F-445F-B6CD-2E1E8D793CDE}'] function byteValue: Byte; cdecl; function compareTo(object_: JByte): Integer; cdecl; function doubleValue: Double; cdecl; function equals(object_: JObject): Boolean; cdecl; function floatValue: Single; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; function toString: JString; cdecl; overload; end; TJByte = class(TJavaGenericImport<JByteClass, JByte>) end; JCharSequenceClass = interface(IJavaClass) ['{85DCA69A-F296-4BB4-8FE2-5ECE0EBE6611}'] end; [JavaSignature('java/lang/CharSequence')] JCharSequence = interface(IJavaInstance) ['{D026566C-D7C6-43E7-AECA-030E2C23A8B8}'] function charAt(index: Integer): Char; cdecl; function length: Integer; cdecl; function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl; function toString: JString; cdecl; end; TJCharSequence = class(TJavaGenericImport<JCharSequenceClass, JCharSequence>) end; Jlang_ClassClass = interface(JObjectClass) ['{E1A7F20A-FD87-4D67-9469-7492FD97D55D}'] {class} function forName(className: JString): Jlang_Class; cdecl; overload; {class} function forName(className: JString; shouldInitialize: Boolean; classLoader: JClassLoader): Jlang_Class; cdecl; overload; end; [JavaSignature('java/lang/Class')] Jlang_Class = interface(JObject) ['{B056EDE6-77D8-4CDD-9864-147C201FD87C}'] function asSubclass(c: Jlang_Class): Jlang_Class; cdecl; function cast(obj: JObject): JObject; cdecl; function desiredAssertionStatus: Boolean; cdecl; function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl; function getAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getCanonicalName: JString; cdecl; function getClassLoader: JClassLoader; cdecl; function getClasses: TJavaObjectArray<Jlang_Class>; cdecl; function getComponentType: Jlang_Class; cdecl; function getConstructors: TJavaObjectArray<JConstructor>; cdecl; function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaredClasses: TJavaObjectArray<Jlang_Class>; cdecl; function getDeclaredConstructors: TJavaObjectArray<JConstructor>; cdecl; function getDeclaredField(name: JString): JField; cdecl; function getDeclaredFields: TJavaObjectArray<JField>; cdecl; function getDeclaredMethods: TJavaObjectArray<JMethod>; cdecl; function getDeclaringClass: Jlang_Class; cdecl; function getEnclosingClass: Jlang_Class; cdecl; function getEnclosingConstructor: JConstructor; cdecl; function getEnclosingMethod: JMethod; cdecl; function getEnumConstants: TJavaObjectArray<JObject>; cdecl; function getField(name: JString): JField; cdecl; function getFields: TJavaObjectArray<JField>; cdecl; function getGenericInterfaces: TJavaObjectArray<Jreflect_Type>; cdecl; function getGenericSuperclass: Jreflect_Type; cdecl; function getInterfaces: TJavaObjectArray<Jlang_Class>; cdecl; function getMethods: TJavaObjectArray<JMethod>; cdecl; function getModifiers: Integer; cdecl; function getName: JString; cdecl; function getPackage: JPackage; cdecl; //function getProtectionDomain: JProtectionDomain; cdecl; //function getResource(resourceName: JString): JURL; cdecl; function getResourceAsStream(resourceName: JString): JInputStream; cdecl; function getSigners: TJavaObjectArray<JObject>; cdecl; function getSimpleName: JString; cdecl; function getSuperclass: Jlang_Class; cdecl; function getTypeParameters: TJavaObjectArray<JTypeVariable>; cdecl; function isAnnotation: Boolean; cdecl; function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl; function isAnonymousClass: Boolean; cdecl; function isArray: Boolean; cdecl; function isAssignableFrom(c: Jlang_Class): Boolean; cdecl; function isEnum: Boolean; cdecl; function isInstance(object_: JObject): Boolean; cdecl; function isInterface: Boolean; cdecl; function isLocalClass: Boolean; cdecl; function isMemberClass: Boolean; cdecl; function isPrimitive: Boolean; cdecl; function isSynthetic: Boolean; cdecl; function newInstance: JObject; cdecl; function toString: JString; cdecl; end; TJlang_Class = class(TJavaGenericImport<Jlang_ClassClass, Jlang_Class>) end; JClassLoaderClass = interface(JObjectClass) ['{453BE0D7-B813-4C83-A30C-F24C026FD112}'] {class} function getSystemClassLoader: JClassLoader; cdecl; {class} //function getSystemResource(resName: JString): JURL; cdecl; {class} function getSystemResourceAsStream(resName: JString): JInputStream; cdecl; {class} function getSystemResources(resName: JString): JEnumeration; cdecl; end; [JavaSignature('java/lang/ClassLoader')] JClassLoader = interface(JObject) ['{17B43D0A-2016-44ED-84B5-9EAB55AF8FDD}'] procedure clearAssertionStatus; cdecl; function getParent: JClassLoader; cdecl; //function getResource(resName: JString): JURL; cdecl; function getResourceAsStream(resName: JString): JInputStream; cdecl; function getResources(resName: JString): JEnumeration; cdecl; function loadClass(className: JString): Jlang_Class; cdecl; procedure setClassAssertionStatus(cname: JString; enable: Boolean); cdecl; procedure setDefaultAssertionStatus(enable: Boolean); cdecl; procedure setPackageAssertionStatus(pname: JString; enable: Boolean); cdecl; end; TJClassLoader = class(TJavaGenericImport<JClassLoaderClass, JClassLoader>) end; JComparableClass = interface(IJavaClass) ['{919AEA14-2451-4CFB-BFAB-387DB8BBE854}'] end; [JavaSignature('java/lang/Comparable')] JComparable = interface(IJavaInstance) ['{AE58973C-F988-4AA5-969C-EBB4E2515276}'] function compareTo(another: JObject): Integer; cdecl; end; TJComparable = class(TJavaGenericImport<JComparableClass, JComparable>) end; JDoubleClass = interface(JNumberClass) ['{1B133955-7ECE-4429-97CD-9118396AC3AE}'] {class} function _GetMAX_EXPONENT: Integer; cdecl; {class} function _GetMAX_VALUE: Double; cdecl; {class} function _GetMIN_EXPONENT: Integer; cdecl; {class} function _GetMIN_NORMAL: Double; cdecl; {class} function _GetMIN_VALUE: Double; cdecl; {class} function _GetNEGATIVE_INFINITY: Double; cdecl; {class} function _GetNaN: Double; cdecl; {class} function _GetPOSITIVE_INFINITY: Double; cdecl; {class} function _GetSIZE: Integer; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(value: Double): JDouble; cdecl; overload; {class} function init(string_: JString): JDouble; cdecl; overload; {class} function compare(double1: Double; double2: Double): Integer; cdecl; {class} function doubleToLongBits(value: Double): Int64; cdecl; {class} function doubleToRawLongBits(value: Double): Int64; cdecl; {class} function isInfinite(d: Double): Boolean; cdecl; overload; {class} function isNaN(d: Double): Boolean; cdecl; overload; {class} function longBitsToDouble(bits: Int64): Double; cdecl; {class} function parseDouble(string_: JString): Double; cdecl; {class} function toHexString(d: Double): JString; cdecl; {class} function toString(d: Double): JString; cdecl; overload; {class} function valueOf(string_: JString): JDouble; cdecl; overload; {class} function valueOf(d: Double): JDouble; cdecl; overload; {class} property MAX_EXPONENT: Integer read _GetMAX_EXPONENT; {class} property MAX_VALUE: Double read _GetMAX_VALUE; {class} property MIN_EXPONENT: Integer read _GetMIN_EXPONENT; {class} property MIN_NORMAL: Double read _GetMIN_NORMAL; {class} property MIN_VALUE: Double read _GetMIN_VALUE; {class} property NEGATIVE_INFINITY: Double read _GetNEGATIVE_INFINITY; {class} property NaN: Double read _GetNaN; {class} property POSITIVE_INFINITY: Double read _GetPOSITIVE_INFINITY; {class} property SIZE: Integer read _GetSIZE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Double')] JDouble = interface(JNumber) ['{81639AF9-E21C-4CB0-99E6-1E7F013E11CC}'] function byteValue: Byte; cdecl; function compareTo(object_: JDouble): Integer; cdecl; function doubleValue: Double; cdecl; function equals(object_: JObject): Boolean; cdecl; function floatValue: Single; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function isInfinite: Boolean; cdecl; overload; function isNaN: Boolean; cdecl; overload; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; function toString: JString; cdecl; overload; end; TJDouble = class(TJavaGenericImport<JDoubleClass, JDouble>) end; JEnumClass = interface(JObjectClass) ['{2DB4C98D-F244-4372-9487-E9B9E2F48391}'] {class} function valueOf(enumType: Jlang_Class; name: JString): JEnum; cdecl; end; [JavaSignature('java/lang/Enum')] JEnum = interface(JObject) ['{0CFB5F00-FBF2-469D-806C-471A09BE1BAF}'] function compareTo(o: JEnum): Integer; cdecl; function equals(other: JObject): Boolean; cdecl; function getDeclaringClass: Jlang_Class; cdecl; function hashCode: Integer; cdecl; function name: JString; cdecl; function ordinal: Integer; cdecl; function toString: JString; cdecl; end; TJEnum = class(TJavaGenericImport<JEnumClass, JEnum>) end; JFloatClass = interface(JNumberClass) ['{E2E64017-238D-4910-8DF8-BD66A034BDFE}'] {class} function _GetMAX_EXPONENT: Integer; cdecl; {class} function _GetMAX_VALUE: Single; cdecl; {class} function _GetMIN_EXPONENT: Integer; cdecl; {class} function _GetMIN_NORMAL: Single; cdecl; {class} function _GetMIN_VALUE: Single; cdecl; {class} function _GetNEGATIVE_INFINITY: Single; cdecl; {class} function _GetNaN: Single; cdecl; {class} function _GetPOSITIVE_INFINITY: Single; cdecl; {class} function _GetSIZE: Integer; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(value: Single): JFloat; cdecl; overload; {class} function init(value: Double): JFloat; cdecl; overload; {class} function init(string_: JString): JFloat; cdecl; overload; {class} function compare(float1: Single; float2: Single): Integer; cdecl; {class} function floatToIntBits(value: Single): Integer; cdecl; {class} function floatToRawIntBits(value: Single): Integer; cdecl; {class} function intBitsToFloat(bits: Integer): Single; cdecl; {class} function isInfinite(f: Single): Boolean; cdecl; overload; {class} function isNaN(f: Single): Boolean; cdecl; overload; {class} function parseFloat(string_: JString): Single; cdecl; {class} function toHexString(f: Single): JString; cdecl; {class} function toString(f: Single): JString; cdecl; overload; {class} function valueOf(string_: JString): JFloat; cdecl; overload; {class} function valueOf(f: Single): JFloat; cdecl; overload; {class} property MAX_EXPONENT: Integer read _GetMAX_EXPONENT; {class} property MAX_VALUE: Single read _GetMAX_VALUE; {class} property MIN_EXPONENT: Integer read _GetMIN_EXPONENT; {class} property MIN_NORMAL: Single read _GetMIN_NORMAL; {class} property MIN_VALUE: Single read _GetMIN_VALUE; {class} property NEGATIVE_INFINITY: Single read _GetNEGATIVE_INFINITY; {class} property NaN: Single read _GetNaN; {class} property POSITIVE_INFINITY: Single read _GetPOSITIVE_INFINITY; {class} property SIZE: Integer read _GetSIZE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Float')] JFloat = interface(JNumber) ['{F13BF843-909A-4866-918B-B1B2B1A8F483}'] function byteValue: Byte; cdecl; function compareTo(object_: JFloat): Integer; cdecl; function doubleValue: Double; cdecl; function equals(object_: JObject): Boolean; cdecl; function floatValue: Single; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function isInfinite: Boolean; cdecl; overload; function isNaN: Boolean; cdecl; overload; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; function toString: JString; cdecl; overload; end; TJFloat = class(TJavaGenericImport<JFloatClass, JFloat>) end; JRuntimeExceptionClass = interface(JExceptionClass) ['{58C58616-58EF-4783-92DB-5AE4F2A079A7}'] {class} function init: JRuntimeException; cdecl; overload; {class} function init(detailMessage: JString): JRuntimeException; cdecl; overload; {class} function init(detailMessage: JString; throwable: JThrowable): JRuntimeException; cdecl; overload; {class} function init(throwable: JThrowable): JRuntimeException; cdecl; overload; end; [JavaSignature('java/lang/RuntimeException')] JRuntimeException = interface(JException) ['{7CEA4E55-B247-4073-A601-7C2C6D8BEE22}'] end; TJRuntimeException = class(TJavaGenericImport<JRuntimeExceptionClass, JRuntimeException>) end; JIllegalStateExceptionClass = interface(JRuntimeExceptionClass) ['{C0717EAB-C1D7-4E7A-A545-922D0CC4B532}'] {class} function init: JIllegalStateException; cdecl; overload; {class} function init(detailMessage: JString): JIllegalStateException; cdecl; overload; {class} function init(message: JString; cause: JThrowable): JIllegalStateException; cdecl; overload; {class} function init(cause: JThrowable): JIllegalStateException; cdecl; overload; end; [JavaSignature('java/lang/IllegalStateException')] JIllegalStateException = interface(JRuntimeException) ['{47074700-88B6-49D2-A5F3-43540D5B910D}'] end; TJIllegalStateException = class(TJavaGenericImport<JIllegalStateExceptionClass, JIllegalStateException>) end; JIntegerClass = interface(JNumberClass) ['{DA48E911-AB80-4875-993F-316B9F310559}'] {class} function _GetMAX_VALUE: Integer; cdecl; {class} function _GetMIN_VALUE: Integer; cdecl; {class} function _GetSIZE: Integer; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(value: Integer): JInteger; cdecl; overload; {class} function init(string_: JString): JInteger; cdecl; overload; {class} function bitCount(i: Integer): Integer; cdecl; {class} function compare(lhs: Integer; rhs: Integer): Integer; cdecl; {class} function decode(string_: JString): JInteger; cdecl; {class} function getInteger(string_: JString): JInteger; cdecl; overload; {class} function getInteger(string_: JString; defaultValue: Integer): JInteger; cdecl; overload; {class} function getInteger(string_: JString; defaultValue: JInteger): JInteger; cdecl; overload; {class} function highestOneBit(i: Integer): Integer; cdecl; {class} function lowestOneBit(i: Integer): Integer; cdecl; {class} function numberOfLeadingZeros(i: Integer): Integer; cdecl; {class} function numberOfTrailingZeros(i: Integer): Integer; cdecl; {class} function parseInt(string_: JString): Integer; cdecl; overload; {class} function parseInt(string_: JString; radix: Integer): Integer; cdecl; overload; {class} function reverse(i: Integer): Integer; cdecl; {class} function reverseBytes(i: Integer): Integer; cdecl; {class} function rotateLeft(i: Integer; distance: Integer): Integer; cdecl; {class} function rotateRight(i: Integer; distance: Integer): Integer; cdecl; {class} function signum(i: Integer): Integer; cdecl; {class} function toBinaryString(i: Integer): JString; cdecl; {class} function toHexString(i: Integer): JString; cdecl; {class} function toOctalString(i: Integer): JString; cdecl; {class} function toString(i: Integer): JString; cdecl; overload; {class} function toString(i: Integer; radix: Integer): JString; cdecl; overload; {class} function valueOf(string_: JString): JInteger; cdecl; overload; {class} function valueOf(string_: JString; radix: Integer): JInteger; cdecl; overload; {class} function valueOf(i: Integer): JInteger; cdecl; overload; {class} property MAX_VALUE: Integer read _GetMAX_VALUE; {class} property MIN_VALUE: Integer read _GetMIN_VALUE; {class} property SIZE: Integer read _GetSIZE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Integer')] JInteger = interface(JNumber) ['{A07D13BE-2418-4FCB-8CEB-F4160E5884D5}'] function byteValue: Byte; cdecl; function compareTo(object_: JInteger): Integer; cdecl; function doubleValue: Double; cdecl; function equals(o: JObject): Boolean; cdecl; function floatValue: Single; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; function toString: JString; cdecl; overload; end; TJInteger = class(TJavaGenericImport<JIntegerClass, JInteger>) end; JIterableClass = interface(IJavaClass) ['{EEADA3A8-2116-491E-ACC7-21F84F84D65A}'] end; [JavaSignature('java/lang/Iterable')] JIterable = interface(IJavaInstance) ['{ABC85F3B-F161-4206-882A-FFD5F1DEFEA2}'] function iterator: JIterator; cdecl; end; TJIterable = class(TJavaGenericImport<JIterableClass, JIterable>) end; JLongClass = interface(JNumberClass) ['{BA567CF5-58F3-41A7-BAA4-538606294DE9}'] {class} function _GetMAX_VALUE: Int64; cdecl; {class} function _GetMIN_VALUE: Int64; cdecl; {class} function _GetSIZE: Integer; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(value: Int64): JLong; cdecl; overload; {class} function init(string_: JString): JLong; cdecl; overload; {class} function bitCount(v: Int64): Integer; cdecl; {class} function compare(lhs: Int64; rhs: Int64): Integer; cdecl; {class} function decode(string_: JString): JLong; cdecl; {class} function getLong(string_: JString): JLong; cdecl; overload; {class} function getLong(string_: JString; defaultValue: Int64): JLong; cdecl; overload; {class} function getLong(string_: JString; defaultValue: JLong): JLong; cdecl; overload; {class} function highestOneBit(v: Int64): Int64; cdecl; {class} function lowestOneBit(v: Int64): Int64; cdecl; {class} function numberOfLeadingZeros(v: Int64): Integer; cdecl; {class} function numberOfTrailingZeros(v: Int64): Integer; cdecl; {class} function parseLong(string_: JString): Int64; cdecl; overload; {class} function parseLong(string_: JString; radix: Integer): Int64; cdecl; overload; {class} function reverse(v: Int64): Int64; cdecl; {class} function reverseBytes(v: Int64): Int64; cdecl; {class} function rotateLeft(v: Int64; distance: Integer): Int64; cdecl; {class} function rotateRight(v: Int64; distance: Integer): Int64; cdecl; {class} function signum(v: Int64): Integer; cdecl; {class} function toBinaryString(v: Int64): JString; cdecl; {class} function toHexString(v: Int64): JString; cdecl; {class} function toOctalString(v: Int64): JString; cdecl; {class} function toString(n: Int64): JString; cdecl; overload; {class} function toString(v: Int64; radix: Integer): JString; cdecl; overload; {class} function valueOf(string_: JString): JLong; cdecl; overload; {class} function valueOf(string_: JString; radix: Integer): JLong; cdecl; overload; {class} function valueOf(v: Int64): JLong; cdecl; overload; {class} property MAX_VALUE: Int64 read _GetMAX_VALUE; {class} property MIN_VALUE: Int64 read _GetMIN_VALUE; {class} property SIZE: Integer read _GetSIZE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Long')] JLong = interface(JNumber) ['{F2E23531-34CC-4607-94D6-F85B4F95FB43}'] function byteValue: Byte; cdecl; function compareTo(object_: JLong): Integer; cdecl; function doubleValue: Double; cdecl; function equals(o: JObject): Boolean; cdecl; function floatValue: Single; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; function toString: JString; cdecl; overload; end; TJLong = class(TJavaGenericImport<JLongClass, JLong>) end; JPackageClass = interface(JObjectClass) ['{1FC1C1DD-321C-4601-8946-916E19BD67FA}'] {class} function getPackage(packageName: JString): JPackage; cdecl; {class} function getPackages: TJavaObjectArray<JPackage>; cdecl; end; [JavaSignature('java/lang/Package')] JPackage = interface(JObject) ['{E8F397DF-1FB0-4C08-B9CB-08C8B38917EE}'] function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl; function getAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getImplementationTitle: JString; cdecl; function getImplementationVendor: JString; cdecl; function getImplementationVersion: JString; cdecl; function getName: JString; cdecl; function getSpecificationTitle: JString; cdecl; function getSpecificationVendor: JString; cdecl; function getSpecificationVersion: JString; cdecl; function hashCode: Integer; cdecl; function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl; function isCompatibleWith(version: JString): Boolean; cdecl; function isSealed: Boolean; cdecl; overload; //function isSealed(url: JURL): Boolean; cdecl; overload; function toString: JString; cdecl; end; TJPackage = class(TJavaGenericImport<JPackageClass, JPackage>) end; JRunnableClass = interface(IJavaClass) ['{49A6EA8E-0ADB-4D8E-8FA3-F13D4ADCF281}'] end; [JavaSignature('java/lang/Runnable')] JRunnable = interface(IJavaInstance) ['{BC131B27-7A72-4CAF-BB8E-170B8359B22E}'] procedure run; cdecl; end; TJRunnable = class(TJavaGenericImport<JRunnableClass, JRunnable>) end; JShortClass = interface(JNumberClass) ['{FAD495F3-40B7-46DB-B3B6-8DBBD38D8E16}'] {class} function _GetMAX_VALUE: SmallInt; cdecl; {class} function _GetMIN_VALUE: SmallInt; cdecl; {class} function _GetSIZE: Integer; cdecl; {class} function _GetTYPE: Jlang_Class; cdecl; {class} function init(string_: JString): JShort; cdecl; overload; {class} function init(value: SmallInt): JShort; cdecl; overload; {class} function compare(lhs: SmallInt; rhs: SmallInt): Integer; cdecl; {class} function decode(string_: JString): JShort; cdecl; {class} function parseShort(string_: JString): SmallInt; cdecl; overload; {class} function parseShort(string_: JString; radix: Integer): SmallInt; cdecl; overload; {class} function reverseBytes(s: SmallInt): SmallInt; cdecl; {class} function toString(value: SmallInt): JString; cdecl; overload; {class} function valueOf(string_: JString): JShort; cdecl; overload; {class} function valueOf(string_: JString; radix: Integer): JShort; cdecl; overload; {class} function valueOf(s: SmallInt): JShort; cdecl; overload; {class} property MAX_VALUE: SmallInt read _GetMAX_VALUE; {class} property MIN_VALUE: SmallInt read _GetMIN_VALUE; {class} property SIZE: Integer read _GetSIZE; {class} property &TYPE: Jlang_Class read _GetTYPE; end; [JavaSignature('java/lang/Short')] JShort = interface(JNumber) ['{48D3B355-1222-4BD6-94BF-F40B5EE8EF02}'] function byteValue: Byte; cdecl; function compareTo(object_: JShort): Integer; cdecl; function doubleValue: Double; cdecl; function equals(object_: JObject): Boolean; cdecl; function floatValue: Single; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function longValue: Int64; cdecl; function shortValue: SmallInt; cdecl; function toString: JString; cdecl; overload; end; TJShort = class(TJavaGenericImport<JShortClass, JShort>) end; JStackTraceElementClass = interface(JObjectClass) ['{21CBE31F-4A81-4CB3-ADB1-EA9B3166692E}'] {class} function init(cls: JString; method: JString; file_: JString; line: Integer): JStackTraceElement; cdecl; end; [JavaSignature('java/lang/StackTraceElement')] JStackTraceElement = interface(JObject) ['{3304B89A-29EB-4B53-943F-E70F4252E8FF}'] function equals(obj: JObject): Boolean; cdecl; function getClassName: JString; cdecl; function getFileName: JString; cdecl; function getLineNumber: Integer; cdecl; function getMethodName: JString; cdecl; function hashCode: Integer; cdecl; function isNativeMethod: Boolean; cdecl; function toString: JString; cdecl; end; TJStackTraceElement = class(TJavaGenericImport<JStackTraceElementClass, JStackTraceElement>) end; JStringClass = interface(JObjectClass) ['{E61829D1-1FD3-49B2-BAC6-FB0FFDB1A495}'] {class} function _GetCASE_INSENSITIVE_ORDER: JComparator; cdecl; {class} function init: JString; cdecl; overload; {class} function init(data: TJavaArray<Byte>): JString; cdecl; overload; {class} function init(data: TJavaArray<Byte>; high: Integer): JString; cdecl; overload;//Deprecated {class} function init(data: TJavaArray<Byte>; offset: Integer; byteCount: Integer): JString; cdecl; overload; {class} function init(data: TJavaArray<Byte>; high: Integer; offset: Integer; byteCount: Integer): JString; cdecl; overload;//Deprecated {class} function init(data: TJavaArray<Byte>; offset: Integer; byteCount: Integer; charsetName: JString): JString; cdecl; overload; {class} function init(data: TJavaArray<Byte>; charsetName: JString): JString; cdecl; overload; {class} function init(data: TJavaArray<Byte>; offset: Integer; byteCount: Integer; charset: JCharset): JString; cdecl; overload; {class} function init(data: TJavaArray<Byte>; charset: JCharset): JString; cdecl; overload; {class} function init(data: TJavaArray<Char>): JString; cdecl; overload; {class} function init(data: TJavaArray<Char>; offset: Integer; charCount: Integer): JString; cdecl; overload; {class} function init(toCopy: JString): JString; cdecl; overload; {class} function init(stringBuffer: JStringBuffer): JString; cdecl; overload; {class} function init(codePoints: TJavaArray<Integer>; offset: Integer; count: Integer): JString; cdecl; overload; {class} function init(stringBuilder: JStringBuilder): JString; cdecl; overload; {class} function copyValueOf(data: TJavaArray<Char>): JString; cdecl; overload; {class} function copyValueOf(data: TJavaArray<Char>; start: Integer; length: Integer): JString; cdecl; overload; {class} function valueOf(data: TJavaArray<Char>): JString; cdecl; overload; {class} function valueOf(data: TJavaArray<Char>; start: Integer; length: Integer): JString; cdecl; overload; {class} function valueOf(value: Char): JString; cdecl; overload; {class} function valueOf(value: Double): JString; cdecl; overload; {class} function valueOf(value: Single): JString; cdecl; overload; {class} function valueOf(value: Integer): JString; cdecl; overload; {class} function valueOf(value: Int64): JString; cdecl; overload; {class} function valueOf(value: JObject): JString; cdecl; overload; {class} function valueOf(value: Boolean): JString; cdecl; overload; {class} property CASE_INSENSITIVE_ORDER: JComparator read _GetCASE_INSENSITIVE_ORDER; end; [JavaSignature('java/lang/String')] JString = interface(JObject) ['{8579B374-1E68-4729-AE3C-C8DA0A6D6F9F}'] function charAt(index: Integer): Char; cdecl; function codePointAt(index: Integer): Integer; cdecl; function codePointBefore(index: Integer): Integer; cdecl; function codePointCount(start: Integer; end_: Integer): Integer; cdecl; function compareTo(string_: JString): Integer; cdecl; function compareToIgnoreCase(string_: JString): Integer; cdecl; function concat(string_: JString): JString; cdecl; function &contains(cs: JCharSequence): Boolean; cdecl; function contentEquals(strbuf: JStringBuffer): Boolean; cdecl; overload; function contentEquals(cs: JCharSequence): Boolean; cdecl; overload; function endsWith(suffix: JString): Boolean; cdecl; function equals(other: JObject): Boolean; cdecl; function equalsIgnoreCase(string_: JString): Boolean; cdecl; procedure getBytes(start: Integer; end_: Integer; data: TJavaArray<Byte>; index: Integer); cdecl; overload;//Deprecated function getBytes: TJavaArray<Byte>; cdecl; overload; function getBytes(charsetName: JString): TJavaArray<Byte>; cdecl; overload; function getBytes(charset: JCharset): TJavaArray<Byte>; cdecl; overload; procedure getChars(start: Integer; end_: Integer; buffer: TJavaArray<Char>; index: Integer); cdecl; function hashCode: Integer; cdecl; function indexOf(c: Integer): Integer; cdecl; overload; function indexOf(c: Integer; start: Integer): Integer; cdecl; overload; function indexOf(string_: JString): Integer; cdecl; overload; function indexOf(subString: JString; start: Integer): Integer; cdecl; overload; function intern: JString; cdecl; function isEmpty: Boolean; cdecl; function lastIndexOf(c: Integer): Integer; cdecl; overload; function lastIndexOf(c: Integer; start: Integer): Integer; cdecl; overload; function lastIndexOf(string_: JString): Integer; cdecl; overload; function lastIndexOf(subString: JString; start: Integer): Integer; cdecl; overload; function length: Integer; cdecl; function matches(regularExpression: JString): Boolean; cdecl; function offsetByCodePoints(index: Integer; codePointOffset: Integer): Integer; cdecl; function regionMatches(thisStart: Integer; string_: JString; start: Integer; length: Integer): Boolean; cdecl; overload; function regionMatches(ignoreCase: Boolean; thisStart: Integer; string_: JString; start: Integer; length: Integer): Boolean; cdecl; overload; function replace(oldChar: Char; newChar: Char): JString; cdecl; overload; function replace(target: JCharSequence; replacement: JCharSequence): JString; cdecl; overload; function replaceAll(regularExpression: JString; replacement: JString): JString; cdecl; function replaceFirst(regularExpression: JString; replacement: JString): JString; cdecl; function split(regularExpression: JString): TJavaObjectArray<JString>; cdecl; overload; function split(regularExpression: JString; limit: Integer): TJavaObjectArray<JString>; cdecl; overload; function startsWith(prefix: JString): Boolean; cdecl; overload; function startsWith(prefix: JString; start: Integer): Boolean; cdecl; overload; function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl; function substring(start: Integer): JString; cdecl; overload; function substring(start: Integer; end_: Integer): JString; cdecl; overload; function toCharArray: TJavaArray<Char>; cdecl; function toLowerCase: JString; cdecl; overload; function toLowerCase(locale: JLocale): JString; cdecl; overload; function toString: JString; cdecl; function toUpperCase: JString; cdecl; overload; function toUpperCase(locale: JLocale): JString; cdecl; overload; function trim: JString; cdecl; end; TJString = class(TJavaGenericImport<JStringClass, JString>) end; JStringBufferClass = interface(JAbstractStringBuilderClass) ['{F6BF4ECD-EA63-4AF3-A901-99D4221796D7}'] {class} function init: JStringBuffer; cdecl; overload; {class} function init(capacity: Integer): JStringBuffer; cdecl; overload; {class} function init(string_: JString): JStringBuffer; cdecl; overload; {class} function init(cs: JCharSequence): JStringBuffer; cdecl; overload; end; [JavaSignature('java/lang/StringBuffer')] JStringBuffer = interface(JAbstractStringBuilder) ['{3CECFBBE-9C21-4D67-9F6F-52BB1DB2C638}'] function append(b: Boolean): JStringBuffer; cdecl; overload; function append(ch: Char): JStringBuffer; cdecl; overload; function append(d: Double): JStringBuffer; cdecl; overload; function append(f: Single): JStringBuffer; cdecl; overload; function append(i: Integer): JStringBuffer; cdecl; overload; function append(l: Int64): JStringBuffer; cdecl; overload; function append(obj: JObject): JStringBuffer; cdecl; overload; function append(string_: JString): JStringBuffer; cdecl; overload; function append(sb: JStringBuffer): JStringBuffer; cdecl; overload; function append(chars: TJavaArray<Char>): JStringBuffer; cdecl; overload; function append(chars: TJavaArray<Char>; start: Integer; length: Integer): JStringBuffer; cdecl; overload; function append(s: JCharSequence): JStringBuffer; cdecl; overload; function append(s: JCharSequence; start: Integer; end_: Integer): JStringBuffer; cdecl; overload; function appendCodePoint(codePoint: Integer): JStringBuffer; cdecl; function charAt(index: Integer): Char; cdecl; function codePointAt(index: Integer): Integer; cdecl; function codePointBefore(index: Integer): Integer; cdecl; function codePointCount(beginIndex: Integer; endIndex: Integer): Integer; cdecl; function delete(start: Integer; end_: Integer): JStringBuffer; cdecl; function deleteCharAt(location: Integer): JStringBuffer; cdecl; procedure ensureCapacity(min: Integer); cdecl; procedure getChars(start: Integer; end_: Integer; buffer: TJavaArray<Char>; idx: Integer); cdecl; function indexOf(subString: JString; start: Integer): Integer; cdecl; function insert(index: Integer; ch: Char): JStringBuffer; cdecl; overload; function insert(index: Integer; b: Boolean): JStringBuffer; cdecl; overload; function insert(index: Integer; i: Integer): JStringBuffer; cdecl; overload; function insert(index: Integer; l: Int64): JStringBuffer; cdecl; overload; function insert(index: Integer; d: Double): JStringBuffer; cdecl; overload; function insert(index: Integer; f: Single): JStringBuffer; cdecl; overload; function insert(index: Integer; obj: JObject): JStringBuffer; cdecl; overload; function insert(index: Integer; string_: JString): JStringBuffer; cdecl; overload; function insert(index: Integer; chars: TJavaArray<Char>): JStringBuffer; cdecl; overload; function insert(index: Integer; chars: TJavaArray<Char>; start: Integer; length: Integer): JStringBuffer; cdecl; overload; function insert(index: Integer; s: JCharSequence): JStringBuffer; cdecl; overload; function insert(index: Integer; s: JCharSequence; start: Integer; end_: Integer): JStringBuffer; cdecl; overload; function lastIndexOf(subString: JString; start: Integer): Integer; cdecl; function offsetByCodePoints(index: Integer; codePointOffset: Integer): Integer; cdecl; function replace(start: Integer; end_: Integer; string_: JString): JStringBuffer; cdecl; function reverse: JStringBuffer; cdecl; procedure setCharAt(index: Integer; ch: Char); cdecl; procedure setLength(length: Integer); cdecl; function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl; function substring(start: Integer): JString; cdecl; overload; function substring(start: Integer; end_: Integer): JString; cdecl; overload; function toString: JString; cdecl; procedure trimToSize; cdecl; end; TJStringBuffer = class(TJavaGenericImport<JStringBufferClass, JStringBuffer>) end; JStringBuilderClass = interface(JAbstractStringBuilderClass) ['{D9FACB66-EE60-4BCB-B5B2-248751CCF1B4}'] {class} function init: JStringBuilder; cdecl; overload; {class} function init(capacity: Integer): JStringBuilder; cdecl; overload; {class} function init(seq: JCharSequence): JStringBuilder; cdecl; overload; {class} function init(str: JString): JStringBuilder; cdecl; overload; end; [JavaSignature('java/lang/StringBuilder')] JStringBuilder = interface(JAbstractStringBuilder) ['{F8A75A66-EA10-4337-9ECC-B0CA4FF4D9C5}'] function append(b: Boolean): JStringBuilder; cdecl; overload; function append(c: Char): JStringBuilder; cdecl; overload; function append(i: Integer): JStringBuilder; cdecl; overload; function append(l: Int64): JStringBuilder; cdecl; overload; function append(f: Single): JStringBuilder; cdecl; overload; function append(d: Double): JStringBuilder; cdecl; overload; function append(obj: JObject): JStringBuilder; cdecl; overload; function append(str: JString): JStringBuilder; cdecl; overload; function append(sb: JStringBuffer): JStringBuilder; cdecl; overload; function append(chars: TJavaArray<Char>): JStringBuilder; cdecl; overload; function append(str: TJavaArray<Char>; offset: Integer; len: Integer): JStringBuilder; cdecl; overload; function append(csq: JCharSequence): JStringBuilder; cdecl; overload; function append(csq: JCharSequence; start: Integer; end_: Integer): JStringBuilder; cdecl; overload; function appendCodePoint(codePoint: Integer): JStringBuilder; cdecl; function delete(start: Integer; end_: Integer): JStringBuilder; cdecl; function deleteCharAt(index: Integer): JStringBuilder; cdecl; function insert(offset: Integer; b: Boolean): JStringBuilder; cdecl; overload; function insert(offset: Integer; c: Char): JStringBuilder; cdecl; overload; function insert(offset: Integer; i: Integer): JStringBuilder; cdecl; overload; function insert(offset: Integer; l: Int64): JStringBuilder; cdecl; overload; function insert(offset: Integer; f: Single): JStringBuilder; cdecl; overload; function insert(offset: Integer; d: Double): JStringBuilder; cdecl; overload; function insert(offset: Integer; obj: JObject): JStringBuilder; cdecl; overload; function insert(offset: Integer; str: JString): JStringBuilder; cdecl; overload; function insert(offset: Integer; ch: TJavaArray<Char>): JStringBuilder; cdecl; overload; function insert(offset: Integer; str: TJavaArray<Char>; strOffset: Integer; strLen: Integer): JStringBuilder; cdecl; overload; function insert(offset: Integer; s: JCharSequence): JStringBuilder; cdecl; overload; function insert(offset: Integer; s: JCharSequence; start: Integer; end_: Integer): JStringBuilder; cdecl; overload; function replace(start: Integer; end_: Integer; string_: JString): JStringBuilder; cdecl; function reverse: JStringBuilder; cdecl; function toString: JString; cdecl; end; TJStringBuilder = class(TJavaGenericImport<JStringBuilderClass, JStringBuilder>) end; JThreadClass = interface(JObjectClass) ['{AC2B33CB-D349-4506-8809-B9762209222B}'] {class} function _GetMAX_PRIORITY: Integer; cdecl; {class} function _GetMIN_PRIORITY: Integer; cdecl; {class} function _GetNORM_PRIORITY: Integer; cdecl; {class} function init: JThread; cdecl; overload; {class} function init(runnable: JRunnable): JThread; cdecl; overload; {class} function init(runnable: JRunnable; threadName: JString): JThread; cdecl; overload; {class} function init(threadName: JString): JThread; cdecl; overload; {class} function init(group: JThreadGroup; runnable: JRunnable): JThread; cdecl; overload; {class} function init(group: JThreadGroup; runnable: JRunnable; threadName: JString): JThread; cdecl; overload; {class} function init(group: JThreadGroup; threadName: JString): JThread; cdecl; overload; {class} function init(group: JThreadGroup; runnable: JRunnable; threadName: JString; stackSize: Int64): JThread; cdecl; overload; {class} function activeCount: Integer; cdecl; {class} function currentThread: JThread; cdecl; {class} procedure dumpStack; cdecl; {class} function enumerate(threads: TJavaObjectArray<JThread>): Integer; cdecl; {class} function getAllStackTraces: TJavaObjectArray<JMap>; cdecl; {class} function getDefaultUncaughtExceptionHandler: JThread_UncaughtExceptionHandler; cdecl; {class} function holdsLock(object_: JObject): Boolean; cdecl; {class} function interrupted: Boolean; cdecl; {class} procedure setDefaultUncaughtExceptionHandler(handler: JThread_UncaughtExceptionHandler); cdecl; {class} procedure sleep(time: Int64); cdecl; overload; {class} procedure sleep(millis: Int64; nanos: Integer); cdecl; overload; {class} procedure yield; cdecl; {class} property MAX_PRIORITY: Integer read _GetMAX_PRIORITY; {class} property MIN_PRIORITY: Integer read _GetMIN_PRIORITY; {class} property NORM_PRIORITY: Integer read _GetNORM_PRIORITY; end; [JavaSignature('java/lang/Thread')] JThread = interface(JObject) ['{8E288CBE-F5A4-4D6E-98B7-D0B5075A0FCA}'] procedure checkAccess; cdecl; function countStackFrames: Integer; cdecl;//Deprecated procedure destroy; cdecl;//Deprecated function getContextClassLoader: JClassLoader; cdecl; function getId: Int64; cdecl; function getName: JString; cdecl; function getPriority: Integer; cdecl; function getStackTrace: TJavaObjectArray<JStackTraceElement>; cdecl; function getState: JThread_State; cdecl; function getThreadGroup: JThreadGroup; cdecl; function getUncaughtExceptionHandler: JThread_UncaughtExceptionHandler; cdecl; procedure interrupt; cdecl; function isAlive: Boolean; cdecl; function isDaemon: Boolean; cdecl; function isInterrupted: Boolean; cdecl; procedure join; cdecl; overload; procedure join(millis: Int64); cdecl; overload; procedure join(millis: Int64; nanos: Integer); cdecl; overload; procedure resume; cdecl;//Deprecated procedure run; cdecl; procedure setContextClassLoader(cl: JClassLoader); cdecl; procedure setDaemon(isDaemon: Boolean); cdecl; procedure setName(threadName: JString); cdecl; procedure setPriority(priority: Integer); cdecl; procedure setUncaughtExceptionHandler(handler: JThread_UncaughtExceptionHandler); cdecl; procedure start; cdecl; procedure stop; cdecl; overload;//Deprecated procedure stop(throwable: JThrowable); cdecl; overload;//Deprecated procedure suspend; cdecl;//Deprecated function toString: JString; cdecl; end; TJThread = class(TJavaGenericImport<JThreadClass, JThread>) end; JThread_StateClass = interface(JEnumClass) ['{493F7CE3-3BE4-4CE5-9F96-7563BC2DC814}'] {class} function _GetBLOCKED: JThread_State; cdecl; {class} function _GetNEW: JThread_State; cdecl; {class} function _GetRUNNABLE: JThread_State; cdecl; {class} function _GetTERMINATED: JThread_State; cdecl; {class} function _GetTIMED_WAITING: JThread_State; cdecl; {class} function _GetWAITING: JThread_State; cdecl; {class} function valueOf(name: JString): JThread_State; cdecl; {class} function values: TJavaObjectArray<JThread_State>; cdecl; {class} property BLOCKED: JThread_State read _GetBLOCKED; {class} property NEW: JThread_State read _GetNEW; {class} property RUNNABLE: JThread_State read _GetRUNNABLE; {class} property TERMINATED: JThread_State read _GetTERMINATED; {class} property TIMED_WAITING: JThread_State read _GetTIMED_WAITING; {class} property WAITING: JThread_State read _GetWAITING; end; [JavaSignature('java/lang/Thread$State')] JThread_State = interface(JEnum) ['{E3910394-C461-461E-9C1D-64E9BC367F84}'] end; TJThread_State = class(TJavaGenericImport<JThread_StateClass, JThread_State>) end; JThread_UncaughtExceptionHandlerClass = interface(IJavaClass) ['{3E2F71F3-BF00-457C-9970-9F1DA9EA7498}'] end; [JavaSignature('java/lang/Thread$UncaughtExceptionHandler')] JThread_UncaughtExceptionHandler = interface(IJavaInstance) ['{C9E75389-E9B3-45FF-9EA2-D7BC024DB9DA}'] procedure uncaughtException(thread: JThread; ex: JThrowable); cdecl; end; TJThread_UncaughtExceptionHandler = class(TJavaGenericImport<JThread_UncaughtExceptionHandlerClass, JThread_UncaughtExceptionHandler>) end; JThreadGroupClass = interface(JObjectClass) ['{D7D65FE0-0CB7-4C72-9129-C344705D0F4C}'] {class} function init(name: JString): JThreadGroup; cdecl; overload; {class} function init(parent: JThreadGroup; name: JString): JThreadGroup; cdecl; overload; end; [JavaSignature('java/lang/ThreadGroup')] JThreadGroup = interface(JObject) ['{5BF3F856-7BFB-444A-8059-341CBC2A10B2}'] function activeCount: Integer; cdecl; function activeGroupCount: Integer; cdecl; function allowThreadSuspension(b: Boolean): Boolean; cdecl;//Deprecated procedure checkAccess; cdecl; procedure destroy; cdecl; function enumerate(threads: TJavaObjectArray<JThread>): Integer; cdecl; overload; function enumerate(threads: TJavaObjectArray<JThread>; recurse: Boolean): Integer; cdecl; overload; function enumerate(groups: TJavaObjectArray<JThreadGroup>): Integer; cdecl; overload; function enumerate(groups: TJavaObjectArray<JThreadGroup>; recurse: Boolean): Integer; cdecl; overload; function getMaxPriority: Integer; cdecl; function getName: JString; cdecl; function getParent: JThreadGroup; cdecl; procedure interrupt; cdecl; function isDaemon: Boolean; cdecl; function isDestroyed: Boolean; cdecl; procedure list; cdecl; function parentOf(g: JThreadGroup): Boolean; cdecl; procedure resume; cdecl;//Deprecated procedure setDaemon(isDaemon: Boolean); cdecl; procedure setMaxPriority(newMax: Integer); cdecl; procedure stop; cdecl;//Deprecated procedure suspend; cdecl;//Deprecated function toString: JString; cdecl; procedure uncaughtException(t: JThread; e: JThrowable); cdecl; end; TJThreadGroup = class(TJavaGenericImport<JThreadGroupClass, JThreadGroup>) end; JAnnotationClass = interface(IJavaClass) ['{E8A654D9-AA21-468D-AEF1-9261C6E3F760}'] end; [JavaSignature('java/lang/annotation/Annotation')] JAnnotation = interface(IJavaInstance) ['{508C3063-7E6D-4963-B22F-27538F9D20CE}'] function annotationType: Jlang_Class; cdecl; function equals(obj: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; function toString: JString; cdecl; end; TJAnnotation = class(TJavaGenericImport<JAnnotationClass, JAnnotation>) end; JAccessibleObjectClass = interface(JObjectClass) ['{BFC4376F-593C-474E-804A-B2AD9F617DCC}'] {class} procedure setAccessible(objects: TJavaObjectArray<JAccessibleObject>; flag: Boolean); cdecl; overload; end; [JavaSignature('java/lang/reflect/AccessibleObject')] JAccessibleObject = interface(JObject) ['{C062CF92-1A4F-4E32-94CB-2571A4C6A2DA}'] function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl; function getAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function isAccessible: Boolean; cdecl; function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl; procedure setAccessible(flag: Boolean); cdecl; overload; end; TJAccessibleObject = class(TJavaGenericImport<JAccessibleObjectClass, JAccessibleObject>) end; JConstructorClass = interface(JObjectClass) ['{80E33E85-BECE-4E23-80BE-3F6D2AD32DA6}'] end; [JavaSignature('java/lang/reflect/Constructor')] JConstructor = interface(JObject) ['{D765E763-03C2-4484-BF92-F8C5BC18BBC2}'] function equals(other: JObject): Boolean; cdecl; function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl; function getAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaringClass: Jlang_Class; cdecl; function getExceptionTypes: TJavaObjectArray<Jlang_Class>; cdecl; function getGenericExceptionTypes: TJavaObjectArray<Jreflect_Type>; cdecl; function getGenericParameterTypes: TJavaObjectArray<Jreflect_Type>; cdecl; function getModifiers: Integer; cdecl; function getName: JString; cdecl; function getParameterAnnotations: TJavaObjectBiArray<JAnnotation>; cdecl; function getParameterTypes: TJavaObjectArray<Jlang_Class>; cdecl; function getTypeParameters: TJavaObjectArray<JTypeVariable>; cdecl; function hashCode: Integer; cdecl; function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl; function isSynthetic: Boolean; cdecl; function isVarArgs: Boolean; cdecl; procedure setAccessible(flag: Boolean); cdecl; function toGenericString: JString; cdecl; function toString: JString; cdecl; end; TJConstructor = class(TJavaGenericImport<JConstructorClass, JConstructor>) end; JFieldClass = interface(JAccessibleObjectClass) ['{76F4F74B-58A0-4CA5-A596-B027AE99C55E}'] end; [JavaSignature('java/lang/reflect/Field')] JField = interface(JAccessibleObject) ['{756027C5-4F1B-4A24-BEF9-70D5A951744A}'] function equals(other: JObject): Boolean; cdecl; function &get(object_: JObject): JObject; cdecl; function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl; function getBoolean(object_: JObject): Boolean; cdecl; function getByte(object_: JObject): Byte; cdecl; function getChar(object_: JObject): Char; cdecl; function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaringClass: Jlang_Class; cdecl; function getDouble(object_: JObject): Double; cdecl; function getFloat(object_: JObject): Single; cdecl; function getGenericType: Jreflect_Type; cdecl; function getInt(object_: JObject): Integer; cdecl; function getLong(object_: JObject): Int64; cdecl; function getModifiers: Integer; cdecl; function getName: JString; cdecl; function getShort(object_: JObject): SmallInt; cdecl; function getType: Jlang_Class; cdecl; function hashCode: Integer; cdecl; function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl; function isEnumConstant: Boolean; cdecl; function isSynthetic: Boolean; cdecl; procedure &set(object_: JObject; value: JObject); cdecl; procedure setBoolean(object_: JObject; value: Boolean); cdecl; procedure setByte(object_: JObject; value: Byte); cdecl; procedure setChar(object_: JObject; value: Char); cdecl; procedure setDouble(object_: JObject; value: Double); cdecl; procedure setFloat(object_: JObject; value: Single); cdecl; procedure setInt(object_: JObject; value: Integer); cdecl; procedure setLong(object_: JObject; value: Int64); cdecl; procedure setShort(object_: JObject; value: SmallInt); cdecl; function toGenericString: JString; cdecl; function toString: JString; cdecl; end; TJField = class(TJavaGenericImport<JFieldClass, JField>) end; JGenericDeclarationClass = interface(IJavaClass) ['{193301E7-C0FE-473C-BBC1-94DAF25C4497}'] end; [JavaSignature('java/lang/reflect/GenericDeclaration')] JGenericDeclaration = interface(IJavaInstance) ['{BD87C28A-4E41-4E44-A2F9-03BB724E9ECC}'] function getTypeParameters: TJavaObjectArray<JTypeVariable>; cdecl; end; TJGenericDeclaration = class(TJavaGenericImport<JGenericDeclarationClass, JGenericDeclaration>) end; JMethodClass = interface(JObjectClass) ['{C995BD27-1D77-48E5-B478-EB8E9E607020}'] end; [JavaSignature('java/lang/reflect/Method')] JMethod = interface(JObject) ['{ED1B0770-0BD6-4D4A-B801-9D18AB92C834}'] function equals(other: JObject): Boolean; cdecl; function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl; function getAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl; function getDeclaringClass: Jlang_Class; cdecl; function getDefaultValue: JObject; cdecl; function getExceptionTypes: TJavaObjectArray<Jlang_Class>; cdecl; function getGenericExceptionTypes: TJavaObjectArray<Jreflect_Type>; cdecl; function getGenericParameterTypes: TJavaObjectArray<Jreflect_Type>; cdecl; function getGenericReturnType: Jreflect_Type; cdecl; function getModifiers: Integer; cdecl; function getName: JString; cdecl; function getParameterAnnotations: TJavaObjectBiArray<JAnnotation>; cdecl; function getParameterTypes: TJavaObjectArray<Jlang_Class>; cdecl; function getReturnType: Jlang_Class; cdecl; function getTypeParameters: TJavaObjectArray<JTypeVariable>; cdecl; function hashCode: Integer; cdecl; function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl; function isBridge: Boolean; cdecl; function isSynthetic: Boolean; cdecl; function isVarArgs: Boolean; cdecl; function toGenericString: JString; cdecl; function toString: JString; cdecl; end; TJMethod = class(TJavaGenericImport<JMethodClass, JMethod>) end; Jreflect_TypeClass = interface(IJavaClass) ['{843FF2A0-9372-4F7B-9CF7-C825AFD78970}'] end; [JavaSignature('java/lang/reflect/Type')] Jreflect_Type = interface(IJavaInstance) ['{90AD4932-3D22-4B5B-B279-56EC7A2174CD}'] end; TJreflect_Type = class(TJavaGenericImport<Jreflect_TypeClass, Jreflect_Type>) end; JTypeVariableClass = interface(Jreflect_TypeClass) ['{26AC832B-6883-4CDF-8BDC-49E5A1E6B0EF}'] end; [JavaSignature('java/lang/reflect/TypeVariable')] JTypeVariable = interface(Jreflect_Type) ['{5635CD21-A6AD-420D-B742-599EC17C5931}'] function getBounds: TJavaObjectArray<Jreflect_Type>; cdecl; function getGenericDeclaration: JGenericDeclaration; cdecl; function getName: JString; cdecl; end; TJTypeVariable = class(TJavaGenericImport<JTypeVariableClass, JTypeVariable>) end; JBigIntegerClass = interface(JNumberClass) ['{ACED883B-58FF-466A-80D3-BB30E54F84A5}'] {class} function _GetONE: JBigInteger; cdecl; {class} function _GetTEN: JBigInteger; cdecl; {class} function _GetZERO: JBigInteger; cdecl; {class} function init(numBits: Integer; random: JRandom): JBigInteger; cdecl; overload; {class} function init(bitLength: Integer; certainty: Integer; random: JRandom): JBigInteger; cdecl; overload; {class} function init(value: JString): JBigInteger; cdecl; overload; {class} function init(value: JString; radix: Integer): JBigInteger; cdecl; overload; {class} function init(signum: Integer; magnitude: TJavaArray<Byte>): JBigInteger; cdecl; overload; {class} function init(value: TJavaArray<Byte>): JBigInteger; cdecl; overload; {class} function probablePrime(bitLength: Integer; random: JRandom): JBigInteger; cdecl; {class} function valueOf(value: Int64): JBigInteger; cdecl; {class} property ONE: JBigInteger read _GetONE; {class} property TEN: JBigInteger read _GetTEN; {class} property ZERO: JBigInteger read _GetZERO; end; [JavaSignature('java/math/BigInteger')] JBigInteger = interface(JNumber) ['{4B14E1DC-D46C-4434-BF1C-E804437732C3}'] function abs: JBigInteger; cdecl; function add(value: JBigInteger): JBigInteger; cdecl; function &and(value: JBigInteger): JBigInteger; cdecl; function andNot(value: JBigInteger): JBigInteger; cdecl; function bitCount: Integer; cdecl; function bitLength: Integer; cdecl; function clearBit(n: Integer): JBigInteger; cdecl; function compareTo(value: JBigInteger): Integer; cdecl; function divide(divisor: JBigInteger): JBigInteger; cdecl; function divideAndRemainder(divisor: JBigInteger): TJavaObjectArray<JBigInteger>; cdecl; function doubleValue: Double; cdecl; function equals(x: JObject): Boolean; cdecl; function flipBit(n: Integer): JBigInteger; cdecl; function floatValue: Single; cdecl; function gcd(value: JBigInteger): JBigInteger; cdecl; function getLowestSetBit: Integer; cdecl; function hashCode: Integer; cdecl; function intValue: Integer; cdecl; function isProbablePrime(certainty: Integer): Boolean; cdecl; function longValue: Int64; cdecl; function max(value: JBigInteger): JBigInteger; cdecl; function min(value: JBigInteger): JBigInteger; cdecl; function &mod(m: JBigInteger): JBigInteger; cdecl; function modInverse(m: JBigInteger): JBigInteger; cdecl; function modPow(exponent: JBigInteger; modulus: JBigInteger): JBigInteger; cdecl; function multiply(value: JBigInteger): JBigInteger; cdecl; function negate: JBigInteger; cdecl; function nextProbablePrime: JBigInteger; cdecl; function &not: JBigInteger; cdecl; function &or(value: JBigInteger): JBigInteger; cdecl; function pow(exp: Integer): JBigInteger; cdecl; function remainder(divisor: JBigInteger): JBigInteger; cdecl; function setBit(n: Integer): JBigInteger; cdecl; function shiftLeft(n: Integer): JBigInteger; cdecl; function shiftRight(n: Integer): JBigInteger; cdecl; function signum: Integer; cdecl; function subtract(value: JBigInteger): JBigInteger; cdecl; function testBit(n: Integer): Boolean; cdecl; function toByteArray: TJavaArray<Byte>; cdecl; function toString: JString; cdecl; overload; function toString(radix: Integer): JString; cdecl; overload; function &xor(value: JBigInteger): JBigInteger; cdecl; end; TJBigInteger = class(TJavaGenericImport<JBigIntegerClass, JBigInteger>) end; JBufferClass = interface(JObjectClass) ['{481ABEA6-E331-446F-BF1A-789FC5B36341}'] end; [JavaSignature('java/nio/Buffer')] JBuffer = interface(JObject) ['{0F836282-2E7D-40FE-BFA9-9B58507FB238}'] function &array: JObject; cdecl; function arrayOffset: Integer; cdecl; function capacity: Integer; cdecl; function clear: JBuffer; cdecl; function flip: JBuffer; cdecl; function hasArray: Boolean; cdecl; function hasRemaining: Boolean; cdecl; function isDirect: Boolean; cdecl; function isReadOnly: Boolean; cdecl; function limit: Integer; cdecl; overload; function limit(newLimit: Integer): JBuffer; cdecl; overload; function mark: JBuffer; cdecl; function position: Integer; cdecl; overload; function position(newPosition: Integer): JBuffer; cdecl; overload; function remaining: Integer; cdecl; function reset: JBuffer; cdecl; function rewind: JBuffer; cdecl; function toString: JString; cdecl; end; TJBuffer = class(TJavaGenericImport<JBufferClass, JBuffer>) end; JByteBufferClass = interface(JBufferClass) ['{7B879DB7-5B81-4A1F-B862-6127F1BE739D}'] {class} function allocate(capacity: Integer): JByteBuffer; cdecl; {class} function allocateDirect(capacity: Integer): JByteBuffer; cdecl; {class} function wrap(array_: TJavaArray<Byte>): JByteBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<Byte>; start: Integer; byteCount: Integer): JByteBuffer; cdecl; overload; end; [JavaSignature('java/nio/ByteBuffer')] JByteBuffer = interface(JBuffer) ['{CB03FB80-318C-4812-97DE-59301638C25A}'] function &array: TJavaArray<Byte>; cdecl; function arrayOffset: Integer; cdecl; function asCharBuffer: JCharBuffer; cdecl; function asDoubleBuffer: JDoubleBuffer; cdecl; function asFloatBuffer: JFloatBuffer; cdecl; function asIntBuffer: JIntBuffer; cdecl; function asLongBuffer: JLongBuffer; cdecl; function asReadOnlyBuffer: JByteBuffer; cdecl; function asShortBuffer: JShortBuffer; cdecl; function compact: JByteBuffer; cdecl; function compareTo(otherBuffer: JByteBuffer): Integer; cdecl; function duplicate: JByteBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: Byte; cdecl; overload; function &get(dst: TJavaArray<Byte>): JByteBuffer; cdecl; overload; function &get(dst: TJavaArray<Byte>; dstOffset: Integer; byteCount: Integer): JByteBuffer; cdecl; overload; function &get(index: Integer): Byte; cdecl; overload; function getChar: Char; cdecl; overload; function getChar(index: Integer): Char; cdecl; overload; function getDouble: Double; cdecl; overload; function getDouble(index: Integer): Double; cdecl; overload; function getFloat: Single; cdecl; overload; function getFloat(index: Integer): Single; cdecl; overload; function getInt: Integer; cdecl; overload; function getInt(index: Integer): Integer; cdecl; overload; function getLong: Int64; cdecl; overload; function getLong(index: Integer): Int64; cdecl; overload; function getShort: SmallInt; cdecl; overload; function getShort(index: Integer): SmallInt; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function order: JByteOrder; cdecl; overload; function order(byteOrder: JByteOrder): JByteBuffer; cdecl; overload; function put(b: Byte): JByteBuffer; cdecl; overload; function put(src: TJavaArray<Byte>): JByteBuffer; cdecl; overload; function put(src: TJavaArray<Byte>; srcOffset: Integer; byteCount: Integer): JByteBuffer; cdecl; overload; function put(src: JByteBuffer): JByteBuffer; cdecl; overload; function put(index: Integer; b: Byte): JByteBuffer; cdecl; overload; function putChar(value: Char): JByteBuffer; cdecl; overload; function putChar(index: Integer; value: Char): JByteBuffer; cdecl; overload; function putDouble(value: Double): JByteBuffer; cdecl; overload; function putDouble(index: Integer; value: Double): JByteBuffer; cdecl; overload; function putFloat(value: Single): JByteBuffer; cdecl; overload; function putFloat(index: Integer; value: Single): JByteBuffer; cdecl; overload; function putInt(value: Integer): JByteBuffer; cdecl; overload; function putInt(index: Integer; value: Integer): JByteBuffer; cdecl; overload; function putLong(value: Int64): JByteBuffer; cdecl; overload; function putLong(index: Integer; value: Int64): JByteBuffer; cdecl; overload; function putShort(value: SmallInt): JByteBuffer; cdecl; overload; function putShort(index: Integer; value: SmallInt): JByteBuffer; cdecl; overload; function slice: JByteBuffer; cdecl; end; TJByteBuffer = class(TJavaGenericImport<JByteBufferClass, JByteBuffer>) end; JByteOrderClass = interface(JObjectClass) ['{254AAEC7-B381-4D22-89B2-D2BB46C88689}'] {class} function _GetBIG_ENDIAN: JByteOrder; cdecl; {class} function _GetLITTLE_ENDIAN: JByteOrder; cdecl; {class} function nativeOrder: JByteOrder; cdecl; {class} {class} end; [JavaSignature('java/nio/ByteOrder')] JByteOrder = interface(JObject) ['{70FDB472-70CD-4FB1-B5FC-D6442C186BD2}'] function toString: JString; cdecl; end; TJByteOrder = class(TJavaGenericImport<JByteOrderClass, JByteOrder>) end; JCharBufferClass = interface(JBufferClass) ['{E542BA92-3ABD-4A87-9D97-65DD774C716C}'] {class} function allocate(capacity: Integer): JCharBuffer; cdecl; {class} function wrap(array_: TJavaArray<Char>): JCharBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<Char>; start: Integer; charCount: Integer): JCharBuffer; cdecl; overload; {class} function wrap(chseq: JCharSequence): JCharBuffer; cdecl; overload; {class} function wrap(cs: JCharSequence; start: Integer; end_: Integer): JCharBuffer; cdecl; overload; end; [JavaSignature('java/nio/CharBuffer')] JCharBuffer = interface(JBuffer) ['{C499497D-72A7-49D7-AB4C-ADE9BBCAEA61}'] function append(c: Char): JCharBuffer; cdecl; overload; function append(csq: JCharSequence): JCharBuffer; cdecl; overload; function append(csq: JCharSequence; start: Integer; end_: Integer): JCharBuffer; cdecl; overload; function &array: TJavaArray<Char>; cdecl; function arrayOffset: Integer; cdecl; function asReadOnlyBuffer: JCharBuffer; cdecl; function charAt(index: Integer): Char; cdecl; function compact: JCharBuffer; cdecl; function compareTo(otherBuffer: JCharBuffer): Integer; cdecl; function duplicate: JCharBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: Char; cdecl; overload; function &get(dst: TJavaArray<Char>): JCharBuffer; cdecl; overload; function &get(dst: TJavaArray<Char>; dstOffset: Integer; charCount: Integer): JCharBuffer; cdecl; overload; function &get(index: Integer): Char; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function length: Integer; cdecl; function order: JByteOrder; cdecl; function put(c: Char): JCharBuffer; cdecl; overload; function put(src: TJavaArray<Char>): JCharBuffer; cdecl; overload; function put(src: TJavaArray<Char>; srcOffset: Integer; charCount: Integer): JCharBuffer; cdecl; overload; function put(src: JCharBuffer): JCharBuffer; cdecl; overload; function put(index: Integer; c: Char): JCharBuffer; cdecl; overload; function put(str: JString): JCharBuffer; cdecl; overload; function put(str: JString; start: Integer; end_: Integer): JCharBuffer; cdecl; overload; function read(target: JCharBuffer): Integer; cdecl; function slice: JCharBuffer; cdecl; function subSequence(start: Integer; end_: Integer): JCharBuffer; cdecl; function toString: JString; cdecl; end; TJCharBuffer = class(TJavaGenericImport<JCharBufferClass, JCharBuffer>) end; JDoubleBufferClass = interface(JBufferClass) ['{05DB46C4-1C05-4F67-AE29-98B4A2703C63}'] {class} function allocate(capacity: Integer): JDoubleBuffer; cdecl; {class} function wrap(array_: TJavaArray<Double>): JDoubleBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<Double>; start: Integer; doubleCount: Integer): JDoubleBuffer; cdecl; overload; end; [JavaSignature('java/nio/DoubleBuffer')] JDoubleBuffer = interface(JBuffer) ['{1A1190DA-622D-48E4-A9D4-675ABCFACDCD}'] function &array: TJavaArray<Double>; cdecl; function arrayOffset: Integer; cdecl; function asReadOnlyBuffer: JDoubleBuffer; cdecl; function compact: JDoubleBuffer; cdecl; function compareTo(otherBuffer: JDoubleBuffer): Integer; cdecl; function duplicate: JDoubleBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: Double; cdecl; overload; function &get(dst: TJavaArray<Double>): JDoubleBuffer; cdecl; overload; function &get(dst: TJavaArray<Double>; dstOffset: Integer; doubleCount: Integer): JDoubleBuffer; cdecl; overload; function &get(index: Integer): Double; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function order: JByteOrder; cdecl; function put(d: Double): JDoubleBuffer; cdecl; overload; function put(src: TJavaArray<Double>): JDoubleBuffer; cdecl; overload; function put(src: TJavaArray<Double>; srcOffset: Integer; doubleCount: Integer): JDoubleBuffer; cdecl; overload; function put(src: JDoubleBuffer): JDoubleBuffer; cdecl; overload; function put(index: Integer; d: Double): JDoubleBuffer; cdecl; overload; function slice: JDoubleBuffer; cdecl; end; TJDoubleBuffer = class(TJavaGenericImport<JDoubleBufferClass, JDoubleBuffer>) end; JFloatBufferClass = interface(JBufferClass) ['{A60ABCB4-E169-4F72-B24F-991D48A476C4}'] {class} function allocate(capacity: Integer): JFloatBuffer; cdecl; {class} function wrap(array_: TJavaArray<Single>): JFloatBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<Single>; start: Integer; floatCount: Integer): JFloatBuffer; cdecl; overload; end; [JavaSignature('java/nio/FloatBuffer')] JFloatBuffer = interface(JBuffer) ['{E416608F-FCBC-4B4E-B43B-E2C4794C95A6}'] function &array: TJavaArray<Single>; cdecl; function arrayOffset: Integer; cdecl; function asReadOnlyBuffer: JFloatBuffer; cdecl; function compact: JFloatBuffer; cdecl; function compareTo(otherBuffer: JFloatBuffer): Integer; cdecl; function duplicate: JFloatBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: Single; cdecl; overload; function &get(dst: TJavaArray<Single>): JFloatBuffer; cdecl; overload; function &get(dst: TJavaArray<Single>; dstOffset: Integer; floatCount: Integer): JFloatBuffer; cdecl; overload; function &get(index: Integer): Single; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function order: JByteOrder; cdecl; function put(f: Single): JFloatBuffer; cdecl; overload; function put(src: TJavaArray<Single>): JFloatBuffer; cdecl; overload; function put(src: TJavaArray<Single>; srcOffset: Integer; floatCount: Integer): JFloatBuffer; cdecl; overload; function put(src: JFloatBuffer): JFloatBuffer; cdecl; overload; function put(index: Integer; f: Single): JFloatBuffer; cdecl; overload; function slice: JFloatBuffer; cdecl; end; TJFloatBuffer = class(TJavaGenericImport<JFloatBufferClass, JFloatBuffer>) end; JIntBufferClass = interface(JBufferClass) ['{23604D5E-E540-41E0-8E8C-F43F7B4DA36F}'] {class} function allocate(capacity: Integer): JIntBuffer; cdecl; {class} function wrap(array_: TJavaArray<Integer>): JIntBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<Integer>; start: Integer; intCount: Integer): JIntBuffer; cdecl; overload; end; [JavaSignature('java/nio/IntBuffer')] JIntBuffer = interface(JBuffer) ['{18A20B5E-DB12-4AE4-B1C8-EDAE822D4438}'] function &array: TJavaArray<Integer>; cdecl; function arrayOffset: Integer; cdecl; function asReadOnlyBuffer: JIntBuffer; cdecl; function compact: JIntBuffer; cdecl; function compareTo(otherBuffer: JIntBuffer): Integer; cdecl; function duplicate: JIntBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: Integer; cdecl; overload; function &get(dst: TJavaArray<Integer>): JIntBuffer; cdecl; overload; function &get(dst: TJavaArray<Integer>; dstOffset: Integer; intCount: Integer): JIntBuffer; cdecl; overload; function &get(index: Integer): Integer; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function order: JByteOrder; cdecl; function put(i: Integer): JIntBuffer; cdecl; overload; function put(src: TJavaArray<Integer>): JIntBuffer; cdecl; overload; function put(src: TJavaArray<Integer>; srcOffset: Integer; intCount: Integer): JIntBuffer; cdecl; overload; function put(src: JIntBuffer): JIntBuffer; cdecl; overload; function put(index: Integer; i: Integer): JIntBuffer; cdecl; overload; function slice: JIntBuffer; cdecl; end; TJIntBuffer = class(TJavaGenericImport<JIntBufferClass, JIntBuffer>) end; JLongBufferClass = interface(JBufferClass) ['{2DD88EBD-4825-41DD-81D4-547FE1186E0F}'] {class} function allocate(capacity: Integer): JLongBuffer; cdecl; {class} function wrap(array_: TJavaArray<Int64>): JLongBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<Int64>; start: Integer; longCount: Integer): JLongBuffer; cdecl; overload; end; [JavaSignature('java/nio/LongBuffer')] JLongBuffer = interface(JBuffer) ['{C28DFBB8-1B26-447C-944E-74C879A70A89}'] function &array: TJavaArray<Int64>; cdecl; function arrayOffset: Integer; cdecl; function asReadOnlyBuffer: JLongBuffer; cdecl; function compact: JLongBuffer; cdecl; function compareTo(otherBuffer: JLongBuffer): Integer; cdecl; function duplicate: JLongBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: Int64; cdecl; overload; function &get(dst: TJavaArray<Int64>): JLongBuffer; cdecl; overload; function &get(dst: TJavaArray<Int64>; dstOffset: Integer; longCount: Integer): JLongBuffer; cdecl; overload; function &get(index: Integer): Int64; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function order: JByteOrder; cdecl; function put(l: Int64): JLongBuffer; cdecl; overload; function put(src: TJavaArray<Int64>): JLongBuffer; cdecl; overload; function put(src: TJavaArray<Int64>; srcOffset: Integer; longCount: Integer): JLongBuffer; cdecl; overload; function put(src: JLongBuffer): JLongBuffer; cdecl; overload; function put(index: Integer; l: Int64): JLongBuffer; cdecl; overload; function slice: JLongBuffer; cdecl; end; TJLongBuffer = class(TJavaGenericImport<JLongBufferClass, JLongBuffer>) end; JMappedByteBufferClass = interface(JByteBufferClass) ['{8319CCA3-84E6-4EF9-9891-40E4EAF11FE0}'] end; [JavaSignature('java/nio/MappedByteBuffer')] JMappedByteBuffer = interface(JByteBuffer) ['{744B5B84-744A-436D-ABFB-DC3EB2C9022A}'] function force: JMappedByteBuffer; cdecl; function isLoaded: Boolean; cdecl; function load: JMappedByteBuffer; cdecl; end; TJMappedByteBuffer = class(TJavaGenericImport<JMappedByteBufferClass, JMappedByteBuffer>) end; JShortBufferClass = interface(JBufferClass) ['{7F52529D-4DFE-4414-B069-986D89949E27}'] {class} function allocate(capacity: Integer): JShortBuffer; cdecl; {class} function wrap(array_: TJavaArray<SmallInt>): JShortBuffer; cdecl; overload; {class} function wrap(array_: TJavaArray<SmallInt>; start: Integer; shortCount: Integer): JShortBuffer; cdecl; overload; end; [JavaSignature('java/nio/ShortBuffer')] JShortBuffer = interface(JBuffer) ['{37B8425A-8596-4CA0-966F-629D0F25C8E9}'] function &array: TJavaArray<SmallInt>; cdecl; function arrayOffset: Integer; cdecl; function asReadOnlyBuffer: JShortBuffer; cdecl; function compact: JShortBuffer; cdecl; function compareTo(otherBuffer: JShortBuffer): Integer; cdecl; function duplicate: JShortBuffer; cdecl; function equals(other: JObject): Boolean; cdecl; function &get: SmallInt; cdecl; overload; function &get(dst: TJavaArray<SmallInt>): JShortBuffer; cdecl; overload; function &get(dst: TJavaArray<SmallInt>; dstOffset: Integer; shortCount: Integer): JShortBuffer; cdecl; overload; function &get(index: Integer): SmallInt; cdecl; overload; function hasArray: Boolean; cdecl; function hashCode: Integer; cdecl; function isDirect: Boolean; cdecl; function order: JByteOrder; cdecl; function put(s: SmallInt): JShortBuffer; cdecl; overload; function put(src: TJavaArray<SmallInt>): JShortBuffer; cdecl; overload; function put(src: TJavaArray<SmallInt>; srcOffset: Integer; shortCount: Integer): JShortBuffer; cdecl; overload; function put(src: JShortBuffer): JShortBuffer; cdecl; overload; function put(index: Integer; s: SmallInt): JShortBuffer; cdecl; overload; function slice: JShortBuffer; cdecl; end; TJShortBuffer = class(TJavaGenericImport<JShortBufferClass, JShortBuffer>) end; JChannelClass = interface(JCloseableClass) ['{0902E632-8B6C-4FCD-9C18-C69A76F11C8B}'] end; [JavaSignature('java/nio/channels/Channel')] JChannel = interface(JCloseable) ['{34601709-0C2E-4791-BFBD-703EE16A9203}'] procedure close; cdecl; function isOpen: Boolean; cdecl; end; TJChannel = class(TJavaGenericImport<JChannelClass, JChannel>) end; JAbstractInterruptibleChannelClass = interface(JObjectClass) ['{D731C7B5-9CD9-4511-9F57-5CD66940B97E}'] end; [JavaSignature('java/nio/channels/spi/AbstractInterruptibleChannel')] JAbstractInterruptibleChannel = interface(JObject) ['{DD7C42BD-DAA0-4134-A220-0DFAE23964AF}'] procedure close; cdecl; function isOpen: Boolean; cdecl; end; TJAbstractInterruptibleChannel = class(TJavaGenericImport<JAbstractInterruptibleChannelClass, JAbstractInterruptibleChannel>) end; JSelectableChannelClass = interface(JAbstractInterruptibleChannelClass) ['{F0A109A2-C857-4C0B-91FC-DC9E4EA0D1F5}'] end; [JavaSignature('java/nio/channels/SelectableChannel')] JSelectableChannel = interface(JAbstractInterruptibleChannel) ['{539916DF-2B5B-4EBC-B849-666F3DD4FF0C}'] function blockingLock: JObject; cdecl; function configureBlocking(block: Boolean): JSelectableChannel; cdecl; function isBlocking: Boolean; cdecl; function isRegistered: Boolean; cdecl; function keyFor(sel: JSelector): JSelectionKey; cdecl; function provider: JSelectorProvider; cdecl; function register(selector: JSelector; operations: Integer): JSelectionKey; cdecl; overload; function register(sel: JSelector; ops: Integer; att: JObject): JSelectionKey; cdecl; overload; function validOps: Integer; cdecl; end; TJSelectableChannel = class(TJavaGenericImport<JSelectableChannelClass, JSelectableChannel>) end; JAbstractSelectableChannelClass = interface(JSelectableChannelClass) ['{37576352-D59D-443D-AF66-1C3123236500}'] end; [JavaSignature('java/nio/channels/spi/AbstractSelectableChannel')] JAbstractSelectableChannel = interface(JSelectableChannel) ['{28EB411A-49FE-4194-9591-CC8E2349B35A}'] function blockingLock: JObject; cdecl; function configureBlocking(blockingMode: Boolean): JSelectableChannel; cdecl; function isBlocking: Boolean; cdecl; function isRegistered: Boolean; cdecl; function keyFor(selector: JSelector): JSelectionKey; cdecl; function provider: JSelectorProvider; cdecl; function register(selector: JSelector; interestSet: Integer; attachment: JObject): JSelectionKey; cdecl; end; TJAbstractSelectableChannel = class(TJavaGenericImport<JAbstractSelectableChannelClass, JAbstractSelectableChannel>) end; JDatagramChannelClass = interface(JAbstractSelectableChannelClass) ['{39ACC9DA-3833-4EAA-ABDA-904EBB9D1D82}'] {class} function open: JDatagramChannel; cdecl; end; [JavaSignature('java/nio/channels/DatagramChannel')] JDatagramChannel = interface(JAbstractSelectableChannel) ['{90205C70-B349-480B-BEFA-1B850C27F130}'] //function connect(address: JSocketAddress): JDatagramChannel; cdecl; function disconnect: JDatagramChannel; cdecl; function isConnected: Boolean; cdecl; function read(target: JByteBuffer): Integer; cdecl; overload; function read(targets: TJavaObjectArray<JByteBuffer>; offset: Integer; length: Integer): Int64; cdecl; overload; function read(targets: TJavaObjectArray<JByteBuffer>): Int64; cdecl; overload; //function receive(target: JByteBuffer): JSocketAddress; cdecl; //function send(source: JByteBuffer; address: JSocketAddress): Integer; cdecl; //function socket: JDatagramSocket; cdecl; function validOps: Integer; cdecl; function write(source: JByteBuffer): Integer; cdecl; overload; function write(sources: TJavaObjectArray<JByteBuffer>; offset: Integer; length: Integer): Int64; cdecl; overload; function write(sources: TJavaObjectArray<JByteBuffer>): Int64; cdecl; overload; end; TJDatagramChannel = class(TJavaGenericImport<JDatagramChannelClass, JDatagramChannel>) end; JFileChannelClass = interface(JAbstractInterruptibleChannelClass) ['{35072FC4-075A-45BF-99F9-E2ED20581B95}'] end; [JavaSignature('java/nio/channels/FileChannel')] JFileChannel = interface(JAbstractInterruptibleChannel) ['{DD170413-4811-4479-96FD-C32E336E8FA9}'] procedure force(metadata: Boolean); cdecl; function lock: JFileLock; cdecl; overload; function lock(position: Int64; size: Int64; shared: Boolean): JFileLock; cdecl; overload; function map(mode: JFileChannel_MapMode; position: Int64; size: Int64): JMappedByteBuffer; cdecl; function position: Int64; cdecl; overload; function position(newPosition: Int64): JFileChannel; cdecl; overload; function read(buffer: JByteBuffer): Integer; cdecl; overload; function read(buffer: JByteBuffer; position: Int64): Integer; cdecl; overload; function read(buffers: TJavaObjectArray<JByteBuffer>): Int64; cdecl; overload; function read(buffers: TJavaObjectArray<JByteBuffer>; start: Integer; number: Integer): Int64; cdecl; overload; function size: Int64; cdecl; function transferFrom(src: JReadableByteChannel; position: Int64; count: Int64): Int64; cdecl; function transferTo(position: Int64; count: Int64; target: JWritableByteChannel): Int64; cdecl; function truncate(size: Int64): JFileChannel; cdecl; function tryLock: JFileLock; cdecl; overload; function tryLock(position: Int64; size: Int64; shared: Boolean): JFileLock; cdecl; overload; function write(src: JByteBuffer): Integer; cdecl; overload; function write(buffer: JByteBuffer; position: Int64): Integer; cdecl; overload; function write(buffers: TJavaObjectArray<JByteBuffer>): Int64; cdecl; overload; function write(buffers: TJavaObjectArray<JByteBuffer>; offset: Integer; length: Integer): Int64; cdecl; overload; end; TJFileChannel = class(TJavaGenericImport<JFileChannelClass, JFileChannel>) end; JFileChannel_MapModeClass = interface(JObjectClass) ['{428D8B72-313B-49EE-AC4B-6DD16908BBA5}'] {class} function _GetPRIVATE: JFileChannel_MapMode; cdecl; {class} function _GetREAD_ONLY: JFileChannel_MapMode; cdecl; {class} function _GetREAD_WRITE: JFileChannel_MapMode; cdecl; {class} property &PRIVATE: JFileChannel_MapMode read _GetPRIVATE; {class} property READ_ONLY: JFileChannel_MapMode read _GetREAD_ONLY; {class} property READ_WRITE: JFileChannel_MapMode read _GetREAD_WRITE; end; [JavaSignature('java/nio/channels/FileChannel$MapMode')] JFileChannel_MapMode = interface(JObject) ['{15CFAED9-B5FC-454D-9463-507D14032869}'] function toString: JString; cdecl; end; TJFileChannel_MapMode = class(TJavaGenericImport<JFileChannel_MapModeClass, JFileChannel_MapMode>) end; JFileLockClass = interface(JObjectClass) ['{5E237114-5198-4D43-8490-313B47A05E81}'] end; [JavaSignature('java/nio/channels/FileLock')] JFileLock = interface(JObject) ['{03C7F0F6-5A57-4A51-A083-43258AA01093}'] function channel: JFileChannel; cdecl; procedure close; cdecl; function isShared: Boolean; cdecl; function isValid: Boolean; cdecl; function overlaps(start: Int64; length: Int64): Boolean; cdecl; function position: Int64; cdecl; procedure release; cdecl; function size: Int64; cdecl; function toString: JString; cdecl; end; TJFileLock = class(TJavaGenericImport<JFileLockClass, JFileLock>) end; JPipeClass = interface(JObjectClass) ['{27E376BA-2D69-474C-AE28-C30BC063BEC0}'] {class} function open: JPipe; cdecl; end; [JavaSignature('java/nio/channels/Pipe')] JPipe = interface(JObject) ['{E872278A-401B-414F-9AEF-3D9DC22CD9E9}'] function sink: JPipe_SinkChannel; cdecl; function source: JPipe_SourceChannel; cdecl; end; TJPipe = class(TJavaGenericImport<JPipeClass, JPipe>) end; JPipe_SinkChannelClass = interface(JAbstractSelectableChannelClass) ['{F48BD363-BB19-4354-AFA3-45E78FE4C3FC}'] end; [JavaSignature('java/nio/channels/Pipe$SinkChannel')] JPipe_SinkChannel = interface(JAbstractSelectableChannel) ['{53C39991-334C-48BF-85B4-7DDFD5859755}'] function validOps: Integer; cdecl; end; TJPipe_SinkChannel = class(TJavaGenericImport<JPipe_SinkChannelClass, JPipe_SinkChannel>) end; JPipe_SourceChannelClass = interface(JAbstractSelectableChannelClass) ['{EFD0625C-C800-4F5A-9A61-9E30291FA04F}'] end; [JavaSignature('java/nio/channels/Pipe$SourceChannel')] JPipe_SourceChannel = interface(JAbstractSelectableChannel) ['{256FD88E-5BBC-41E2-97DC-4546CF1220FD}'] function validOps: Integer; cdecl; end; TJPipe_SourceChannel = class(TJavaGenericImport<JPipe_SourceChannelClass, JPipe_SourceChannel>) end; JReadableByteChannelClass = interface(JChannelClass) ['{3B4589E7-BD37-4B54-AC98-44050F3AE209}'] end; [JavaSignature('java/nio/channels/ReadableByteChannel')] JReadableByteChannel = interface(JChannel) ['{D6B0CB63-51D0-48C6-882A-A44D30FD7521}'] function read(buffer: JByteBuffer): Integer; cdecl; end; TJReadableByteChannel = class(TJavaGenericImport<JReadableByteChannelClass, JReadableByteChannel>) end; JSelectionKeyClass = interface(JObjectClass) ['{718617CF-8E56-41EF-982B-1DE5540C7639}'] {class} function _GetOP_ACCEPT: Integer; cdecl; {class} function _GetOP_CONNECT: Integer; cdecl; {class} function _GetOP_READ: Integer; cdecl; {class} function _GetOP_WRITE: Integer; cdecl; {class} property OP_ACCEPT: Integer read _GetOP_ACCEPT; {class} property OP_CONNECT: Integer read _GetOP_CONNECT; {class} property OP_READ: Integer read _GetOP_READ; {class} property OP_WRITE: Integer read _GetOP_WRITE; end; [JavaSignature('java/nio/channels/SelectionKey')] JSelectionKey = interface(JObject) ['{22CE5584-F7C1-41E4-BA87-008827EFEEAA}'] function attach(anObject: JObject): JObject; cdecl; function attachment: JObject; cdecl; procedure cancel; cdecl; function channel: JSelectableChannel; cdecl; function interestOps: Integer; cdecl; overload; function interestOps(operations: Integer): JSelectionKey; cdecl; overload; function isAcceptable: Boolean; cdecl; function isConnectable: Boolean; cdecl; function isReadable: Boolean; cdecl; function isValid: Boolean; cdecl; function isWritable: Boolean; cdecl; function readyOps: Integer; cdecl; function selector: JSelector; cdecl; end; TJSelectionKey = class(TJavaGenericImport<JSelectionKeyClass, JSelectionKey>) end; JSelectorClass = interface(JObjectClass) ['{E1CC5599-DD36-4998-A426-92BE0A6B5DC9}'] {class} function open: JSelector; cdecl; end; [JavaSignature('java/nio/channels/Selector')] JSelector = interface(JObject) ['{0E8BCD73-DAF7-420A-8891-835ED1EC82BF}'] procedure close; cdecl; function isOpen: Boolean; cdecl; function keys: JSet; cdecl; function provider: JSelectorProvider; cdecl; function select: Integer; cdecl; overload; function select(timeout: Int64): Integer; cdecl; overload; function selectNow: Integer; cdecl; function selectedKeys: JSet; cdecl; function wakeup: JSelector; cdecl; end; TJSelector = class(TJavaGenericImport<JSelectorClass, JSelector>) end; JServerSocketChannelClass = interface(JAbstractSelectableChannelClass) ['{D5B3AB40-C62C-4B8B-A579-A8B73DFCA5F8}'] {class} function open: JServerSocketChannel; cdecl; end; [JavaSignature('java/nio/channels/ServerSocketChannel')] JServerSocketChannel = interface(JAbstractSelectableChannel) ['{5485D000-B8EE-4DCE-9DBE-8A094441F255}'] function accept: JSocketChannel; cdecl; //function socket: JServerSocket; cdecl; function validOps: Integer; cdecl; end; TJServerSocketChannel = class(TJavaGenericImport<JServerSocketChannelClass, JServerSocketChannel>) end; JSocketChannelClass = interface(JAbstractSelectableChannelClass) ['{AC06A3C8-B76A-45CD-9CAA-C03E931A3828}'] {class} function open: JSocketChannel; cdecl; overload; {class} //function open(address: JSocketAddress): JSocketChannel; cdecl; overload; end; [JavaSignature('java/nio/channels/SocketChannel')] JSocketChannel = interface(JAbstractSelectableChannel) ['{04388B66-A713-4476-98A7-A20D99310947}'] //function connect(address: JSocketAddress): Boolean; cdecl; function finishConnect: Boolean; cdecl; function isConnected: Boolean; cdecl; function isConnectionPending: Boolean; cdecl; function read(target: JByteBuffer): Integer; cdecl; overload; function read(targets: TJavaObjectArray<JByteBuffer>; offset: Integer; length: Integer): Int64; cdecl; overload; function read(targets: TJavaObjectArray<JByteBuffer>): Int64; cdecl; overload; //function socket: JSocket; cdecl; function validOps: Integer; cdecl; function write(source: JByteBuffer): Integer; cdecl; overload; function write(sources: TJavaObjectArray<JByteBuffer>; offset: Integer; length: Integer): Int64; cdecl; overload; function write(sources: TJavaObjectArray<JByteBuffer>): Int64; cdecl; overload; end; TJSocketChannel = class(TJavaGenericImport<JSocketChannelClass, JSocketChannel>) end; JWritableByteChannelClass = interface(JChannelClass) ['{C4B313F1-68CA-4254-A782-3473DAD7E786}'] end; [JavaSignature('java/nio/channels/WritableByteChannel')] JWritableByteChannel = interface(JChannel) ['{58ABD8D1-20A0-4022-8CDE-C68B6A032191}'] function write(buffer: JByteBuffer): Integer; cdecl; end; TJWritableByteChannel = class(TJavaGenericImport<JWritableByteChannelClass, JWritableByteChannel>) end; JAbstractSelectorClass = interface(JSelectorClass) ['{EF1FBF60-D39E-48AF-9326-CD3B500AFA56}'] end; [JavaSignature('java/nio/channels/spi/AbstractSelector')] JAbstractSelector = interface(JSelector) ['{1583A67A-8E15-44A0-8943-EE898E4216F9}'] procedure close; cdecl; function isOpen: Boolean; cdecl; function provider: JSelectorProvider; cdecl; end; TJAbstractSelector = class(TJavaGenericImport<JAbstractSelectorClass, JAbstractSelector>) end; JSelectorProviderClass = interface(JObjectClass) ['{52BA6B52-FF27-4051-B86B-4465C88E8830}'] {class} function provider: JSelectorProvider; cdecl; end; [JavaSignature('java/nio/channels/spi/SelectorProvider')] JSelectorProvider = interface(JObject) ['{2217E1DD-E7B2-44E1-B932-E01CAAFF013A}'] function inheritedChannel: JChannel; cdecl; function openDatagramChannel: JDatagramChannel; cdecl; function openPipe: JPipe; cdecl; function openSelector: JAbstractSelector; cdecl; function openServerSocketChannel: JServerSocketChannel; cdecl; function openSocketChannel: JSocketChannel; cdecl; end; TJSelectorProvider = class(TJavaGenericImport<JSelectorProviderClass, JSelectorProvider>) end; JCharsetClass = interface(JObjectClass) ['{8BBFEE2C-642D-4F32-8839-0C459948A70A}'] {class} function availableCharsets: JSortedMap; cdecl; {class} function defaultCharset: JCharset; cdecl; {class} function forName(charsetName: JString): JCharset; cdecl; {class} function isSupported(charsetName: JString): Boolean; cdecl; end; [JavaSignature('java/nio/charset/Charset')] JCharset = interface(JObject) ['{0B41CD4C-80D6-45E5-997E-B83EF313AB67}'] function aliases: JSet; cdecl; function canEncode: Boolean; cdecl; function compareTo(charset: JCharset): Integer; cdecl; function &contains(charset: JCharset): Boolean; cdecl; function decode(buffer: JByteBuffer): JCharBuffer; cdecl; function displayName: JString; cdecl; overload; function displayName(l: JLocale): JString; cdecl; overload; function encode(buffer: JCharBuffer): JByteBuffer; cdecl; overload; function encode(s: JString): JByteBuffer; cdecl; overload; function equals(obj: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; function isRegistered: Boolean; cdecl; function name: JString; cdecl; function newDecoder: JCharsetDecoder; cdecl; function newEncoder: JCharsetEncoder; cdecl; function toString: JString; cdecl; end; TJCharset = class(TJavaGenericImport<JCharsetClass, JCharset>) end; JCharsetDecoderClass = interface(JObjectClass) ['{2F0FAD80-3FFC-419C-AD52-28071482CCA1}'] end; [JavaSignature('java/nio/charset/CharsetDecoder')] JCharsetDecoder = interface(JObject) ['{F7AFF095-6D34-470F-B2C6-B68F75C40D26}'] function averageCharsPerByte: Single; cdecl; function charset: JCharset; cdecl; function decode(in_: JByteBuffer): JCharBuffer; cdecl; overload; function decode(in_: JByteBuffer; out_: JCharBuffer; endOfInput: Boolean): JCoderResult; cdecl; overload; function detectedCharset: JCharset; cdecl; function flush(out_: JCharBuffer): JCoderResult; cdecl; function isAutoDetecting: Boolean; cdecl; function isCharsetDetected: Boolean; cdecl; function malformedInputAction: JCodingErrorAction; cdecl; function maxCharsPerByte: Single; cdecl; function onMalformedInput(newAction: JCodingErrorAction): JCharsetDecoder; cdecl; function onUnmappableCharacter(newAction: JCodingErrorAction): JCharsetDecoder; cdecl; function replaceWith(replacement: JString): JCharsetDecoder; cdecl; function replacement: JString; cdecl; function reset: JCharsetDecoder; cdecl; function unmappableCharacterAction: JCodingErrorAction; cdecl; end; TJCharsetDecoder = class(TJavaGenericImport<JCharsetDecoderClass, JCharsetDecoder>) end; JCharsetEncoderClass = interface(JObjectClass) ['{F107BD1C-B97C-4163-BFAC-1F620CC30D02}'] end; [JavaSignature('java/nio/charset/CharsetEncoder')] JCharsetEncoder = interface(JObject) ['{6126DFBE-1E4C-4F67-8F42-A2B312E6CE96}'] function averageBytesPerChar: Single; cdecl; function canEncode(c: Char): Boolean; cdecl; overload; function canEncode(sequence: JCharSequence): Boolean; cdecl; overload; function charset: JCharset; cdecl; function encode(in_: JCharBuffer): JByteBuffer; cdecl; overload; function encode(in_: JCharBuffer; out_: JByteBuffer; endOfInput: Boolean): JCoderResult; cdecl; overload; function flush(out_: JByteBuffer): JCoderResult; cdecl; function isLegalReplacement(replacement: TJavaArray<Byte>): Boolean; cdecl; function malformedInputAction: JCodingErrorAction; cdecl; function maxBytesPerChar: Single; cdecl; function onMalformedInput(newAction: JCodingErrorAction): JCharsetEncoder; cdecl; function onUnmappableCharacter(newAction: JCodingErrorAction): JCharsetEncoder; cdecl; function replaceWith(replacement: TJavaArray<Byte>): JCharsetEncoder; cdecl; function replacement: TJavaArray<Byte>; cdecl; function reset: JCharsetEncoder; cdecl; function unmappableCharacterAction: JCodingErrorAction; cdecl; end; TJCharsetEncoder = class(TJavaGenericImport<JCharsetEncoderClass, JCharsetEncoder>) end; JCoderResultClass = interface(JObjectClass) ['{FDEBE443-A1F2-4DCF-9AA7-5D674CE88E70}'] {class} function _GetOVERFLOW: JCoderResult; cdecl; {class} function _GetUNDERFLOW: JCoderResult; cdecl; {class} function malformedForLength(length: Integer): JCoderResult; cdecl; {class} function unmappableForLength(length: Integer): JCoderResult; cdecl; {class} property OVERFLOW: JCoderResult read _GetOVERFLOW; {class} property UNDERFLOW: JCoderResult read _GetUNDERFLOW; end; [JavaSignature('java/nio/charset/CoderResult')] JCoderResult = interface(JObject) ['{2107C07D-63CF-408D-AAA0-8E36DDD4484C}'] function isError: Boolean; cdecl; function isMalformed: Boolean; cdecl; function isOverflow: Boolean; cdecl; function isUnderflow: Boolean; cdecl; function isUnmappable: Boolean; cdecl; function length: Integer; cdecl; procedure throwException; cdecl; function toString: JString; cdecl; end; TJCoderResult = class(TJavaGenericImport<JCoderResultClass, JCoderResult>) end; JCodingErrorActionClass = interface(JObjectClass) ['{8E806C03-E513-41D4-AA2E-8E0A38670EF9}'] {class} function _GetIGNORE: JCodingErrorAction; cdecl; {class} function _GetREPLACE: JCodingErrorAction; cdecl; {class} function _GetREPORT: JCodingErrorAction; cdecl; {class} property IGNORE: JCodingErrorAction read _GetIGNORE; {class} property REPLACE: JCodingErrorAction read _GetREPLACE; {class} property REPORT: JCodingErrorAction read _GetREPORT; end; [JavaSignature('java/nio/charset/CodingErrorAction')] JCodingErrorAction = interface(JObject) ['{46131CDD-61F4-4F10-8DC3-449D297DF12E}'] function toString: JString; cdecl; end; TJCodingErrorAction = class(TJavaGenericImport<JCodingErrorActionClass, JCodingErrorAction>) end; JAbstractCollectionClass = interface(JObjectClass) ['{27541496-F538-45DB-BFC7-9ED05E5680C3}'] end; [JavaSignature('java/util/AbstractCollection')] JAbstractCollection = interface(JObject) ['{4A5BA15A-2B07-4768-AA91-4BA9C93882C1}'] function add(object_: JObject): Boolean; cdecl; function addAll(collection: JCollection): Boolean; cdecl; procedure clear; cdecl; function &contains(object_: JObject): Boolean; cdecl; function containsAll(collection: JCollection): Boolean; cdecl; function isEmpty: Boolean; cdecl; function iterator: JIterator; cdecl; function remove(object_: JObject): Boolean; cdecl; function removeAll(collection: JCollection): Boolean; cdecl; function retainAll(collection: JCollection): Boolean; cdecl; function size: Integer; cdecl; function toArray: TJavaObjectArray<JObject>; cdecl; overload; function toArray(contents: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload; function toString: JString; cdecl; end; TJAbstractCollection = class(TJavaGenericImport<JAbstractCollectionClass, JAbstractCollection>) end; JAbstractListClass = interface(JAbstractCollectionClass) ['{4495F751-BABA-4349-8D4B-997761ED3876}'] end; [JavaSignature('java/util/AbstractList')] JAbstractList = interface(JAbstractCollection) ['{2E98325B-7293-4E06-A775-240FDD287E27}'] procedure add(location: Integer; object_: JObject); cdecl; overload; function add(object_: JObject): Boolean; cdecl; overload; function addAll(location: Integer; collection: JCollection): Boolean; cdecl; procedure clear; cdecl; function equals(object_: JObject): Boolean; cdecl; function &get(location: Integer): JObject; cdecl; function hashCode: Integer; cdecl; function indexOf(object_: JObject): Integer; cdecl; function iterator: JIterator; cdecl; function lastIndexOf(object_: JObject): Integer; cdecl; function listIterator: JListIterator; cdecl; overload; function listIterator(location: Integer): JListIterator; cdecl; overload; function remove(location: Integer): JObject; cdecl; function &set(location: Integer; object_: JObject): JObject; cdecl; function subList(start: Integer; end_: Integer): JList; cdecl; end; TJAbstractList = class(TJavaGenericImport<JAbstractListClass, JAbstractList>) end; JAbstractMapClass = interface(JObjectClass) ['{05119E45-9501-4270-B2BB-EE7E314695CB}'] end; [JavaSignature('java/util/AbstractMap')] JAbstractMap = interface(JObject) ['{63FD2094-7BFB-41B4-AED8-F781B97F6EB6}'] procedure clear; cdecl; function containsKey(key: JObject): Boolean; cdecl; function containsValue(value: JObject): Boolean; cdecl; function entrySet: JSet; cdecl; function equals(object_: JObject): Boolean; cdecl; function &get(key: JObject): JObject; cdecl; function hashCode: Integer; cdecl; function isEmpty: Boolean; cdecl; function keySet: JSet; cdecl; function put(key: JObject; value: JObject): JObject; cdecl; procedure putAll(map: JMap); cdecl; function remove(key: JObject): JObject; cdecl; function size: Integer; cdecl; function toString: JString; cdecl; function values: JCollection; cdecl; end; TJAbstractMap = class(TJavaGenericImport<JAbstractMapClass, JAbstractMap>) end; JAbstractSetClass = interface(JAbstractCollectionClass) ['{C8EA147C-D0DB-4E27-B8B5-77A04711A2F3}'] end; [JavaSignature('java/util/AbstractSet')] JAbstractSet = interface(JAbstractCollection) ['{A520B68E-843E-46B8-BBB3-1A40DE9E92CE}'] function equals(object_: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; function removeAll(collection: JCollection): Boolean; cdecl; end; TJAbstractSet = class(TJavaGenericImport<JAbstractSetClass, JAbstractSet>) end; JArrayListClass = interface(JAbstractListClass) ['{0CC7FC88-8B13-4F0A-9635-26FEEED49F94}'] {class} function init(capacity: Integer): JArrayList; cdecl; overload; {class} function init: JArrayList; cdecl; overload; {class} function init(collection: JCollection): JArrayList; cdecl; overload; end; [JavaSignature('java/util/ArrayList')] JArrayList = interface(JAbstractList) ['{B1D54E97-F848-4301-BA5B-F32921164AFA}'] function add(object_: JObject): Boolean; cdecl; overload; procedure add(index: Integer; object_: JObject); cdecl; overload; function addAll(collection: JCollection): Boolean; cdecl; overload; function addAll(index: Integer; collection: JCollection): Boolean; cdecl; overload; procedure clear; cdecl; function clone: JObject; cdecl; function &contains(object_: JObject): Boolean; cdecl; procedure ensureCapacity(minimumCapacity: Integer); cdecl; function equals(o: JObject): Boolean; cdecl; function &get(index: Integer): JObject; cdecl; function hashCode: Integer; cdecl; function indexOf(object_: JObject): Integer; cdecl; function isEmpty: Boolean; cdecl; function iterator: JIterator; cdecl; function lastIndexOf(object_: JObject): Integer; cdecl; function remove(index: Integer): JObject; cdecl; overload; function remove(object_: JObject): Boolean; cdecl; overload; function &set(index: Integer; object_: JObject): JObject; cdecl; function size: Integer; cdecl; function toArray: TJavaObjectArray<JObject>; cdecl; overload; function toArray(contents: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload; procedure trimToSize; cdecl; end; TJArrayList = class(TJavaGenericImport<JArrayListClass, JArrayList>) end; JBitSetClass = interface(JObjectClass) ['{1CB74061-9B52-4CCA-AB29-D87B5EE10BCB}'] {class} function init: JBitSet; cdecl; overload; {class} function init(bitCount: Integer): JBitSet; cdecl; overload; {class} function valueOf(longs: TJavaArray<Int64>): JBitSet; cdecl; overload; {class} function valueOf(longBuffer: JLongBuffer): JBitSet; cdecl; overload; {class} function valueOf(bytes: TJavaArray<Byte>): JBitSet; cdecl; overload; {class} function valueOf(byteBuffer: JByteBuffer): JBitSet; cdecl; overload; end; [JavaSignature('java/util/BitSet')] JBitSet = interface(JObject) ['{2FBDF9C9-FEEE-4377-B2A2-D557CF0BEC31}'] procedure &and(bs: JBitSet); cdecl; procedure andNot(bs: JBitSet); cdecl; function cardinality: Integer; cdecl; procedure clear(index: Integer); cdecl; overload; procedure clear; cdecl; overload; procedure clear(fromIndex: Integer; toIndex: Integer); cdecl; overload; function clone: JObject; cdecl; function equals(o: JObject): Boolean; cdecl; procedure flip(index: Integer); cdecl; overload; procedure flip(fromIndex: Integer; toIndex: Integer); cdecl; overload; function &get(index: Integer): Boolean; cdecl; overload; function &get(fromIndex: Integer; toIndex: Integer): JBitSet; cdecl; overload; function hashCode: Integer; cdecl; function intersects(bs: JBitSet): Boolean; cdecl; function isEmpty: Boolean; cdecl; function length: Integer; cdecl; function nextClearBit(index: Integer): Integer; cdecl; function nextSetBit(index: Integer): Integer; cdecl; procedure &or(bs: JBitSet); cdecl; function previousClearBit(index: Integer): Integer; cdecl; function previousSetBit(index: Integer): Integer; cdecl; procedure &set(index: Integer); cdecl; overload; procedure &set(index: Integer; state: Boolean); cdecl; overload; procedure &set(fromIndex: Integer; toIndex: Integer; state: Boolean); cdecl; overload; procedure &set(fromIndex: Integer; toIndex: Integer); cdecl; overload; function size: Integer; cdecl; function toByteArray: TJavaArray<Byte>; cdecl; function toLongArray: TJavaArray<Int64>; cdecl; function toString: JString; cdecl; procedure &xor(bs: JBitSet); cdecl; end; TJBitSet = class(TJavaGenericImport<JBitSetClass, JBitSet>) end; JCalendarClass = interface(JObjectClass) ['{51237FAA-7CDF-4E7E-9AE8-282DC2A930A1}'] {class} function _GetALL_STYLES: Integer; cdecl; {class} function _GetAM: Integer; cdecl; {class} function _GetAM_PM: Integer; cdecl; {class} function _GetAPRIL: Integer; cdecl; {class} function _GetAUGUST: Integer; cdecl; {class} function _GetDATE: Integer; cdecl; {class} function _GetDAY_OF_MONTH: Integer; cdecl; {class} function _GetDAY_OF_WEEK: Integer; cdecl; {class} function _GetDAY_OF_WEEK_IN_MONTH: Integer; cdecl; {class} function _GetDAY_OF_YEAR: Integer; cdecl; {class} function _GetDECEMBER: Integer; cdecl; {class} function _GetDST_OFFSET: Integer; cdecl; {class} function _GetERA: Integer; cdecl; {class} function _GetFEBRUARY: Integer; cdecl; {class} function _GetFIELD_COUNT: Integer; cdecl; {class} function _GetFRIDAY: Integer; cdecl; {class} function _GetHOUR: Integer; cdecl; {class} function _GetHOUR_OF_DAY: Integer; cdecl; {class} function _GetJANUARY: Integer; cdecl; {class} function _GetJULY: Integer; cdecl; {class} function _GetJUNE: Integer; cdecl; {class} function _GetLONG: Integer; cdecl; {class} function _GetMARCH: Integer; cdecl; {class} function _GetMAY: Integer; cdecl; {class} function _GetMILLISECOND: Integer; cdecl; {class} function _GetMINUTE: Integer; cdecl; {class} function _GetMONDAY: Integer; cdecl; {class} function _GetMONTH: Integer; cdecl; {class} function _GetNOVEMBER: Integer; cdecl; {class} function _GetOCTOBER: Integer; cdecl; {class} function _GetPM: Integer; cdecl; {class} function _GetSATURDAY: Integer; cdecl; {class} function _GetSECOND: Integer; cdecl; {class} function _GetSEPTEMBER: Integer; cdecl; {class} function _GetSHORT: Integer; cdecl; {class} function _GetSUNDAY: Integer; cdecl; {class} function _GetTHURSDAY: Integer; cdecl; {class} function _GetTUESDAY: Integer; cdecl; {class} function _GetUNDECIMBER: Integer; cdecl; {class} function _GetWEDNESDAY: Integer; cdecl; {class} function _GetWEEK_OF_MONTH: Integer; cdecl; {class} function _GetWEEK_OF_YEAR: Integer; cdecl; {class} function _GetYEAR: Integer; cdecl; {class} function _GetZONE_OFFSET: Integer; cdecl; {class} function getAvailableLocales: TJavaObjectArray<JLocale>; cdecl; {class} function getInstance: JCalendar; cdecl; overload; {class} function getInstance(locale: JLocale): JCalendar; cdecl; overload; {class} function getInstance(timezone: JTimeZone): JCalendar; cdecl; overload; {class} function getInstance(timezone: JTimeZone; locale: JLocale): JCalendar; cdecl; overload; {class} property ALL_STYLES: Integer read _GetALL_STYLES; {class} property AM: Integer read _GetAM; {class} property AM_PM: Integer read _GetAM_PM; {class} property APRIL: Integer read _GetAPRIL; {class} property AUGUST: Integer read _GetAUGUST; {class} property DATE: Integer read _GetDATE; {class} property DAY_OF_MONTH: Integer read _GetDAY_OF_MONTH; {class} property DAY_OF_WEEK: Integer read _GetDAY_OF_WEEK; {class} property DAY_OF_WEEK_IN_MONTH: Integer read _GetDAY_OF_WEEK_IN_MONTH; {class} property DAY_OF_YEAR: Integer read _GetDAY_OF_YEAR; {class} property DECEMBER: Integer read _GetDECEMBER; {class} property DST_OFFSET: Integer read _GetDST_OFFSET; {class} property ERA: Integer read _GetERA; {class} property FEBRUARY: Integer read _GetFEBRUARY; {class} property FIELD_COUNT: Integer read _GetFIELD_COUNT; {class} property FRIDAY: Integer read _GetFRIDAY; {class} property HOUR: Integer read _GetHOUR; {class} property HOUR_OF_DAY: Integer read _GetHOUR_OF_DAY; {class} property JANUARY: Integer read _GetJANUARY; {class} property JULY: Integer read _GetJULY; {class} property JUNE: Integer read _GetJUNE; {class} property LONG: Integer read _GetLONG; {class} property MARCH: Integer read _GetMARCH; {class} property MAY: Integer read _GetMAY; {class} property MILLISECOND: Integer read _GetMILLISECOND; {class} property MINUTE: Integer read _GetMINUTE; {class} property MONDAY: Integer read _GetMONDAY; {class} property MONTH: Integer read _GetMONTH; {class} property NOVEMBER: Integer read _GetNOVEMBER; {class} property OCTOBER: Integer read _GetOCTOBER; {class} property PM: Integer read _GetPM; {class} property SATURDAY: Integer read _GetSATURDAY; {class} property SECOND: Integer read _GetSECOND; {class} property SEPTEMBER: Integer read _GetSEPTEMBER; {class} property SHORT: Integer read _GetSHORT; {class} property SUNDAY: Integer read _GetSUNDAY; {class} property THURSDAY: Integer read _GetTHURSDAY; {class} property TUESDAY: Integer read _GetTUESDAY; {class} property UNDECIMBER: Integer read _GetUNDECIMBER; {class} property WEDNESDAY: Integer read _GetWEDNESDAY; {class} property WEEK_OF_MONTH: Integer read _GetWEEK_OF_MONTH; {class} property WEEK_OF_YEAR: Integer read _GetWEEK_OF_YEAR; {class} property YEAR: Integer read _GetYEAR; {class} property ZONE_OFFSET: Integer read _GetZONE_OFFSET; end; [JavaSignature('java/util/Calendar')] JCalendar = interface(JObject) ['{2C0409E5-97A4-47CA-9E75-6ACB1CA4515E}'] procedure add(field: Integer; value: Integer); cdecl; function after(calendar: JObject): Boolean; cdecl; function before(calendar: JObject): Boolean; cdecl; procedure clear; cdecl; overload; procedure clear(field: Integer); cdecl; overload; function clone: JObject; cdecl; function compareTo(anotherCalendar: JCalendar): Integer; cdecl; function equals(object_: JObject): Boolean; cdecl; function &get(field: Integer): Integer; cdecl; function getActualMaximum(field: Integer): Integer; cdecl; function getActualMinimum(field: Integer): Integer; cdecl; function getDisplayName(field: Integer; style: Integer; locale: JLocale): JString; cdecl; function getDisplayNames(field: Integer; style: Integer; locale: JLocale): JMap; cdecl; function getFirstDayOfWeek: Integer; cdecl; function getGreatestMinimum(field: Integer): Integer; cdecl; function getLeastMaximum(field: Integer): Integer; cdecl; function getMaximum(field: Integer): Integer; cdecl; function getMinimalDaysInFirstWeek: Integer; cdecl; function getMinimum(field: Integer): Integer; cdecl; function getTime: JDate; cdecl; function getTimeInMillis: Int64; cdecl; function getTimeZone: JTimeZone; cdecl; function hashCode: Integer; cdecl; function isLenient: Boolean; cdecl; function isSet(field: Integer): Boolean; cdecl; procedure roll(field: Integer; value: Integer); cdecl; overload; procedure roll(field: Integer; increment: Boolean); cdecl; overload; procedure &set(field: Integer; value: Integer); cdecl; overload; procedure &set(year: Integer; month: Integer; day: Integer); cdecl; overload; procedure &set(year: Integer; month: Integer; day: Integer; hourOfDay: Integer; minute: Integer); cdecl; overload; procedure &set(year: Integer; month: Integer; day: Integer; hourOfDay: Integer; minute: Integer; second: Integer); cdecl; overload; procedure setFirstDayOfWeek(value: Integer); cdecl; procedure setLenient(value: Boolean); cdecl; procedure setMinimalDaysInFirstWeek(value: Integer); cdecl; procedure setTime(date: JDate); cdecl; procedure setTimeInMillis(milliseconds: Int64); cdecl; procedure setTimeZone(timezone: JTimeZone); cdecl; function toString: JString; cdecl; end; TJCalendar = class(TJavaGenericImport<JCalendarClass, JCalendar>) end; JCollectionClass = interface(JIterableClass) ['{2737AA1B-2E7C-406D-AF35-8B012C7D5803}'] end; [JavaSignature('java/util/Collection')] JCollection = interface(JIterable) ['{9E58EE70-C0A7-4660-BF62-945FAE9F5EC3}'] function add(object_: JObject): Boolean; cdecl; function addAll(collection: JCollection): Boolean; cdecl; procedure clear; cdecl; function &contains(object_: JObject): Boolean; cdecl; function containsAll(collection: JCollection): Boolean; cdecl; function equals(object_: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; function isEmpty: Boolean; cdecl; function iterator: JIterator; cdecl; function remove(object_: JObject): Boolean; cdecl; function removeAll(collection: JCollection): Boolean; cdecl; function retainAll(collection: JCollection): Boolean; cdecl; function size: Integer; cdecl; function toArray: TJavaObjectArray<JObject>; cdecl; overload; function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload; end; TJCollection = class(TJavaGenericImport<JCollectionClass, JCollection>) end; JComparatorClass = interface(IJavaClass) ['{BFB6395F-2694-4292-A1B5-87CC1138FB77}'] end; [JavaSignature('java/util/Comparator')] JComparator = interface(IJavaInstance) ['{0754C41C-92B8-483B-88F0-B48BFE216D46}'] function compare(lhs: JObject; rhs: JObject): Integer; cdecl; function equals(object_: JObject): Boolean; cdecl; end; TJComparator = class(TJavaGenericImport<JComparatorClass, JComparator>) end; JDateClass = interface(JObjectClass) ['{37EABF6D-C7EE-4AB5-BE8B-5E439112E116}'] {class} function init: JDate; cdecl; overload; {class} function init(year: Integer; month: Integer; day: Integer): JDate; cdecl; overload;//Deprecated {class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer): JDate; cdecl; overload;//Deprecated {class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): JDate; cdecl; overload;//Deprecated {class} function init(milliseconds: Int64): JDate; cdecl; overload; {class} function init(string_: JString): JDate; cdecl; overload;//Deprecated {class} function UTC(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): Int64; cdecl;//Deprecated {class} function parse(string_: JString): Int64; cdecl;//Deprecated end; [JavaSignature('java/util/Date')] JDate = interface(JObject) ['{282E2836-B390-44E4-A14F-EF481460BDF7}'] function after(date: JDate): Boolean; cdecl; function before(date: JDate): Boolean; cdecl; function clone: JObject; cdecl; function compareTo(date: JDate): Integer; cdecl; function equals(object_: JObject): Boolean; cdecl; function getDate: Integer; cdecl;//Deprecated function getDay: Integer; cdecl;//Deprecated function getHours: Integer; cdecl;//Deprecated function getMinutes: Integer; cdecl;//Deprecated function getMonth: Integer; cdecl;//Deprecated function getSeconds: Integer; cdecl;//Deprecated function getTime: Int64; cdecl; function getTimezoneOffset: Integer; cdecl;//Deprecated function getYear: Integer; cdecl;//Deprecated function hashCode: Integer; cdecl; procedure setDate(day: Integer); cdecl;//Deprecated procedure setHours(hour: Integer); cdecl;//Deprecated procedure setMinutes(minute: Integer); cdecl;//Deprecated procedure setMonth(month: Integer); cdecl;//Deprecated procedure setSeconds(second: Integer); cdecl;//Deprecated procedure setTime(milliseconds: Int64); cdecl; procedure setYear(year: Integer); cdecl;//Deprecated function toGMTString: JString; cdecl;//Deprecated function toLocaleString: JString; cdecl;//Deprecated function toString: JString; cdecl; end; TJDate = class(TJavaGenericImport<JDateClass, JDate>) end; JDictionaryClass = interface(JObjectClass) ['{33D1971B-B4C5-4FA5-9DE3-BD76F2FCBD29}'] {class} function init: JDictionary; cdecl; end; [JavaSignature('java/util/Dictionary')] JDictionary = interface(JObject) ['{C52483EE-5BB5-4F8A-B6ED-411F1920D533}'] function elements: JEnumeration; cdecl; function &get(key: JObject): JObject; cdecl; function isEmpty: Boolean; cdecl; function keys: JEnumeration; cdecl; function put(key: JObject; value: JObject): JObject; cdecl; function remove(key: JObject): JObject; cdecl; function size: Integer; cdecl; end; TJDictionary = class(TJavaGenericImport<JDictionaryClass, JDictionary>) end; JEnumSetClass = interface(JAbstractSetClass) ['{67EF0287-D91B-44E0-9574-4CA9974FBC38}'] {class} function allOf(elementType: Jlang_Class): JEnumSet; cdecl; {class} function complementOf(s: JEnumSet): JEnumSet; cdecl; {class} function copyOf(s: JEnumSet): JEnumSet; cdecl; overload; {class} function copyOf(c: JCollection): JEnumSet; cdecl; overload; {class} function noneOf(elementType: Jlang_Class): JEnumSet; cdecl; {class} function &of(e: JEnum): JEnumSet; cdecl; overload; {class} function &of(e1: JEnum; e2: JEnum): JEnumSet; cdecl; overload; {class} function &of(e1: JEnum; e2: JEnum; e3: JEnum): JEnumSet; cdecl; overload; {class} function &of(e1: JEnum; e2: JEnum; e3: JEnum; e4: JEnum): JEnumSet; cdecl; overload; {class} function &of(e1: JEnum; e2: JEnum; e3: JEnum; e4: JEnum; e5: JEnum): JEnumSet; cdecl; overload; {class} function range(start: JEnum; end_: JEnum): JEnumSet; cdecl; end; [JavaSignature('java/util/EnumSet')] JEnumSet = interface(JAbstractSet) ['{C8A6B028-B797-406A-9EE4-B65671555D97}'] function clone: JEnumSet; cdecl; end; TJEnumSet = class(TJavaGenericImport<JEnumSetClass, JEnumSet>) end; JEnumerationClass = interface(IJavaClass) ['{5E393BCD-3EF2-4764-A59C-37B4D44C289A}'] end; [JavaSignature('java/util/Enumeration')] JEnumeration = interface(IJavaInstance) ['{8F9F8780-E6BE-4B67-A4F5-8EC28E1AE2EE}'] function hasMoreElements: Boolean; cdecl; function nextElement: JObject; cdecl; end; TJEnumeration = class(TJavaGenericImport<JEnumerationClass, JEnumeration>) end; JGregorianCalendarClass = interface(JCalendarClass) ['{69F4EF00-93DA-4249-8A30-3A3E4A71DA03}'] {class} function _GetAD: Integer; cdecl; {class} function _GetBC: Integer; cdecl; {class} function init: JGregorianCalendar; cdecl; overload; {class} function init(year: Integer; month: Integer; day: Integer): JGregorianCalendar; cdecl; overload; {class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer): JGregorianCalendar; cdecl; overload; {class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): JGregorianCalendar; cdecl; overload; {class} function init(locale: JLocale): JGregorianCalendar; cdecl; overload; {class} function init(timezone: JTimeZone): JGregorianCalendar; cdecl; overload; {class} function init(timezone: JTimeZone; locale: JLocale): JGregorianCalendar; cdecl; overload; {class} property AD: Integer read _GetAD; {class} property BC: Integer read _GetBC; end; [JavaSignature('java/util/GregorianCalendar')] JGregorianCalendar = interface(JCalendar) ['{CB851885-16EA-49E7-8AAF-DBFE900DA328}'] procedure add(field: Integer; value: Integer); cdecl; function equals(object_: JObject): Boolean; cdecl; function getActualMaximum(field: Integer): Integer; cdecl; function getActualMinimum(field: Integer): Integer; cdecl; function getGreatestMinimum(field: Integer): Integer; cdecl; function getGregorianChange: JDate; cdecl; function getLeastMaximum(field: Integer): Integer; cdecl; function getMaximum(field: Integer): Integer; cdecl; function getMinimum(field: Integer): Integer; cdecl; function hashCode: Integer; cdecl; function isLeapYear(year: Integer): Boolean; cdecl; procedure roll(field: Integer; value: Integer); cdecl; overload; procedure roll(field: Integer; increment: Boolean); cdecl; overload; procedure setGregorianChange(date: JDate); cdecl; end; TJGregorianCalendar = class(TJavaGenericImport<JGregorianCalendarClass, JGregorianCalendar>) end; JHashMapClass = interface(JAbstractMapClass) ['{AC953BC1-405B-4CDD-93D2-FBA77D171B56}'] {class} function init: JHashMap; cdecl; overload; {class} function init(capacity: Integer): JHashMap; cdecl; overload; {class} function init(capacity: Integer; loadFactor: Single): JHashMap; cdecl; overload; {class} function init(map: JMap): JHashMap; cdecl; overload; end; [JavaSignature('java/util/HashMap')] JHashMap = interface(JAbstractMap) ['{FD560211-A7FE-4AB5-B510-BB43A31AA75D}'] procedure clear; cdecl; function clone: JObject; cdecl; function containsKey(key: JObject): Boolean; cdecl; function containsValue(value: JObject): Boolean; cdecl; function entrySet: JSet; cdecl; function &get(key: JObject): JObject; cdecl; function isEmpty: Boolean; cdecl; function keySet: JSet; cdecl; function put(key: JObject; value: JObject): JObject; cdecl; procedure putAll(map: JMap); cdecl; function remove(key: JObject): JObject; cdecl; function size: Integer; cdecl; function values: JCollection; cdecl; end; TJHashMap = class(TJavaGenericImport<JHashMapClass, JHashMap>) end; JHashSetClass = interface(JAbstractSetClass) ['{7828E4D4-4F9F-493D-869E-92BE600444D5}'] {class} function init: JHashSet; cdecl; overload; {class} function init(capacity: Integer): JHashSet; cdecl; overload; {class} function init(capacity: Integer; loadFactor: Single): JHashSet; cdecl; overload; {class} function init(collection: JCollection): JHashSet; cdecl; overload; end; [JavaSignature('java/util/HashSet')] JHashSet = interface(JAbstractSet) ['{A57B696D-8331-4C96-8759-7F2009371640}'] function add(object_: JObject): Boolean; cdecl; procedure clear; cdecl; function clone: JObject; cdecl; function &contains(object_: JObject): Boolean; cdecl; function isEmpty: Boolean; cdecl; function iterator: JIterator; cdecl; function remove(object_: JObject): Boolean; cdecl; function size: Integer; cdecl; end; TJHashSet = class(TJavaGenericImport<JHashSetClass, JHashSet>) end; JHashtableClass = interface(JDictionaryClass) ['{0459EE5F-44DF-406D-B0F4-6D2F19D2222F}'] {class} function init: JHashtable; cdecl; overload; {class} function init(capacity: Integer): JHashtable; cdecl; overload; {class} function init(capacity: Integer; loadFactor: Single): JHashtable; cdecl; overload; {class} function init(map: JMap): JHashtable; cdecl; overload; end; [JavaSignature('java/util/Hashtable')] JHashtable = interface(JDictionary) ['{7A995299-3381-4179-A8A2-21C4F0E2E755}'] procedure clear; cdecl; function clone: JObject; cdecl; function &contains(value: JObject): Boolean; cdecl; function containsKey(key: JObject): Boolean; cdecl; function containsValue(value: JObject): Boolean; cdecl; function elements: JEnumeration; cdecl; function entrySet: JSet; cdecl; function equals(object_: JObject): Boolean; cdecl; function &get(key: JObject): JObject; cdecl; function hashCode: Integer; cdecl; function isEmpty: Boolean; cdecl; function keySet: JSet; cdecl; function keys: JEnumeration; cdecl; function put(key: JObject; value: JObject): JObject; cdecl; procedure putAll(map: JMap); cdecl; function remove(key: JObject): JObject; cdecl; function size: Integer; cdecl; function toString: JString; cdecl; function values: JCollection; cdecl; end; TJHashtable = class(TJavaGenericImport<JHashtableClass, JHashtable>) end; JIteratorClass = interface(IJavaClass) ['{2E525F5D-C766-4F79-B800-BA5FFA909E90}'] end; [JavaSignature('java/util/Iterator')] JIterator = interface(IJavaInstance) ['{435EBC1F-CFE0-437C-B49B-45B5257B6953}'] function hasNext: Boolean; cdecl; function next: JObject; cdecl; procedure remove; cdecl; end; TJIterator = class(TJavaGenericImport<JIteratorClass, JIterator>) end; JListClass = interface(JCollectionClass) ['{8EA06296-143F-4381-9369-A77209B622F0}'] end; [JavaSignature('java/util/List')] JList = interface(JCollection) ['{3F85C565-F3F4-42D8-87EE-F724F72113C7}'] procedure add(location: Integer; object_: JObject); cdecl; overload; function add(object_: JObject): Boolean; cdecl; overload; function addAll(location: Integer; collection: JCollection): Boolean; cdecl; overload; function addAll(collection: JCollection): Boolean; cdecl; overload; procedure clear; cdecl; function &contains(object_: JObject): Boolean; cdecl; function containsAll(collection: JCollection): Boolean; cdecl; function equals(object_: JObject): Boolean; cdecl; function &get(location: Integer): JObject; cdecl; function hashCode: Integer; cdecl; function indexOf(object_: JObject): Integer; cdecl; function isEmpty: Boolean; cdecl; function iterator: JIterator; cdecl; function lastIndexOf(object_: JObject): Integer; cdecl; function listIterator: JListIterator; cdecl; overload; function listIterator(location: Integer): JListIterator; cdecl; overload; function remove(location: Integer): JObject; cdecl; overload; function remove(object_: JObject): Boolean; cdecl; overload; function removeAll(collection: JCollection): Boolean; cdecl; function retainAll(collection: JCollection): Boolean; cdecl; function &set(location: Integer; object_: JObject): JObject; cdecl; function size: Integer; cdecl; function subList(start: Integer; end_: Integer): JList; cdecl; function toArray: TJavaObjectArray<JObject>; cdecl; overload; function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload; end; TJList = class(TJavaGenericImport<JListClass, JList>) end; JListIteratorClass = interface(JIteratorClass) ['{7541F5DD-8E71-44AE-ACD9-142ED2D42810}'] end; [JavaSignature('java/util/ListIterator')] JListIterator = interface(JIterator) ['{B66BDA33-5CDD-43B1-B320-7353AE09C418}'] procedure add(object_: JObject); cdecl; function hasNext: Boolean; cdecl; function hasPrevious: Boolean; cdecl; function next: JObject; cdecl; function nextIndex: Integer; cdecl; function previous: JObject; cdecl; function previousIndex: Integer; cdecl; procedure remove; cdecl; procedure &set(object_: JObject); cdecl; end; TJListIterator = class(TJavaGenericImport<JListIteratorClass, JListIterator>) end; JLocaleClass = interface(JObjectClass) ['{0A5D70AA-C01B-437F-97C8-FEE25C595AE7}'] {class} function _GetCANADA: JLocale; cdecl; {class} function _GetCANADA_FRENCH: JLocale; cdecl; {class} function _GetCHINA: JLocale; cdecl; {class} function _GetCHINESE: JLocale; cdecl; {class} function _GetENGLISH: JLocale; cdecl; {class} function _GetFRANCE: JLocale; cdecl; {class} function _GetFRENCH: JLocale; cdecl; {class} function _GetGERMAN: JLocale; cdecl; {class} function _GetGERMANY: JLocale; cdecl; {class} function _GetITALIAN: JLocale; cdecl; {class} function _GetITALY: JLocale; cdecl; {class} function _GetJAPAN: JLocale; cdecl; {class} function _GetJAPANESE: JLocale; cdecl; {class} function _GetKOREA: JLocale; cdecl; {class} function _GetKOREAN: JLocale; cdecl; {class} function _GetPRC: JLocale; cdecl; {class} function _GetPRIVATE_USE_EXTENSION: Char; cdecl; {class} function _GetROOT: JLocale; cdecl; {class} function _GetSIMPLIFIED_CHINESE: JLocale; cdecl; {class} function _GetTAIWAN: JLocale; cdecl; {class} function _GetTRADITIONAL_CHINESE: JLocale; cdecl; {class} function _GetUK: JLocale; cdecl; {class} function _GetUNICODE_LOCALE_EXTENSION: Char; cdecl; {class} function _GetUS: JLocale; cdecl; {class} function init(language: JString): JLocale; cdecl; overload; {class} function init(language: JString; country: JString): JLocale; cdecl; overload; {class} function init(language: JString; country: JString; variant: JString): JLocale; cdecl; overload; {class} function forLanguageTag(languageTag: JString): JLocale; cdecl; {class} function getAvailableLocales: TJavaObjectArray<JLocale>; cdecl; {class} function getDefault: JLocale; cdecl; {class} function getISOCountries: TJavaObjectArray<JString>; cdecl; {class} function getISOLanguages: TJavaObjectArray<JString>; cdecl; {class} procedure setDefault(locale: JLocale); cdecl; {class} property CANADA: JLocale read _GetCANADA; {class} property CANADA_FRENCH: JLocale read _GetCANADA_FRENCH; {class} property CHINA: JLocale read _GetCHINA; {class} property CHINESE: JLocale read _GetCHINESE; {class} property ENGLISH: JLocale read _GetENGLISH; {class} property FRANCE: JLocale read _GetFRANCE; {class} property FRENCH: JLocale read _GetFRENCH; {class} property GERMAN: JLocale read _GetGERMAN; {class} property GERMANY: JLocale read _GetGERMANY; {class} property ITALIAN: JLocale read _GetITALIAN; {class} property ITALY: JLocale read _GetITALY; {class} property JAPAN: JLocale read _GetJAPAN; {class} property JAPANESE: JLocale read _GetJAPANESE; {class} property KOREA: JLocale read _GetKOREA; {class} property KOREAN: JLocale read _GetKOREAN; {class} property PRC: JLocale read _GetPRC; {class} property PRIVATE_USE_EXTENSION: Char read _GetPRIVATE_USE_EXTENSION; {class} property ROOT: JLocale read _GetROOT; {class} property SIMPLIFIED_CHINESE: JLocale read _GetSIMPLIFIED_CHINESE; {class} property TAIWAN: JLocale read _GetTAIWAN; {class} property TRADITIONAL_CHINESE: JLocale read _GetTRADITIONAL_CHINESE; {class} property UK: JLocale read _GetUK; {class} property UNICODE_LOCALE_EXTENSION: Char read _GetUNICODE_LOCALE_EXTENSION; {class} property US: JLocale read _GetUS; end; [JavaSignature('java/util/Locale')] JLocale = interface(JObject) ['{877ADE25-1D13-4963-9A17-17EE17B3A0A8}'] function clone: JObject; cdecl; function equals(object_: JObject): Boolean; cdecl; function getCountry: JString; cdecl; function getDisplayCountry: JString; cdecl; overload; function getDisplayCountry(locale: JLocale): JString; cdecl; overload; function getDisplayLanguage: JString; cdecl; overload; function getDisplayLanguage(locale: JLocale): JString; cdecl; overload; function getDisplayName: JString; cdecl; overload; function getDisplayName(locale: JLocale): JString; cdecl; overload; function getDisplayScript: JString; cdecl; overload; function getDisplayScript(locale: JLocale): JString; cdecl; overload; function getDisplayVariant: JString; cdecl; overload; function getDisplayVariant(locale: JLocale): JString; cdecl; overload; function getExtension(extensionKey: Char): JString; cdecl; function getExtensionKeys: JSet; cdecl; function getISO3Country: JString; cdecl; function getISO3Language: JString; cdecl; function getLanguage: JString; cdecl; function getScript: JString; cdecl; function getUnicodeLocaleAttributes: JSet; cdecl; function getUnicodeLocaleKeys: JSet; cdecl; function getUnicodeLocaleType(keyWord: JString): JString; cdecl; function getVariant: JString; cdecl; function hashCode: Integer; cdecl; function toLanguageTag: JString; cdecl; function toString: JString; cdecl; end; TJLocale = class(TJavaGenericImport<JLocaleClass, JLocale>) end; JMapClass = interface(IJavaClass) ['{2A7CE403-063B-45CA-9F4D-EA1E64304F1C}'] end; [JavaSignature('java/util/Map')] JMap = interface(IJavaInstance) ['{BE6A5DBF-B121-4BF2-BC18-EB64729C7811}'] procedure clear; cdecl; function containsKey(key: JObject): Boolean; cdecl; function containsValue(value: JObject): Boolean; cdecl; function entrySet: JSet; cdecl; function equals(object_: JObject): Boolean; cdecl; function &get(key: JObject): JObject; cdecl; function hashCode: Integer; cdecl; function isEmpty: Boolean; cdecl; function keySet: JSet; cdecl; function put(key: JObject; value: JObject): JObject; cdecl; procedure putAll(map: JMap); cdecl; function remove(key: JObject): JObject; cdecl; function size: Integer; cdecl; function values: JCollection; cdecl; end; TJMap = class(TJavaGenericImport<JMapClass, JMap>) end; Jutil_ObservableClass = interface(JObjectClass) ['{2BD8C696-02FF-4378-A514-ACD431BEE106}'] {class} function init: Jutil_Observable; cdecl; end; [JavaSignature('java/util/Observable')] Jutil_Observable = interface(JObject) ['{B8443F0E-B41C-4475-934B-1C917FCF617B}'] procedure addObserver(observer: JObserver); cdecl; function countObservers: Integer; cdecl; procedure deleteObserver(observer: JObserver); cdecl; procedure deleteObservers; cdecl; function hasChanged: Boolean; cdecl; procedure notifyObservers; cdecl; overload; procedure notifyObservers(data: JObject); cdecl; overload; end; TJutil_Observable = class(TJavaGenericImport<Jutil_ObservableClass, Jutil_Observable>) end; JObserverClass = interface(IJavaClass) ['{8582EA20-ECD9-4C10-95BD-2C89B4D5BA6E}'] end; [JavaSignature('java/util/Observer')] JObserver = interface(IJavaInstance) ['{452A1BDA-4B4E-406E-B455-BC56F012C1B7}'] procedure update(observable: Jutil_Observable; data: JObject); cdecl; end; TJObserver = class(TJavaGenericImport<JObserverClass, JObserver>) end; JPropertiesClass = interface(JHashtableClass) ['{CA354A9C-C42E-41BD-B104-6058143813A5}'] {class} function init: JProperties; cdecl; overload; {class} function init(properties: JProperties): JProperties; cdecl; overload; end; [JavaSignature('java/util/Properties')] JProperties = interface(JHashtable) ['{5F7AA87B-4EF0-4D76-923C-D7586F38760F}'] function getProperty(name: JString): JString; cdecl; overload; function getProperty(name: JString; defaultValue: JString): JString; cdecl; overload; procedure list(out_: JPrintStream); cdecl; overload; procedure list(out_: JPrintWriter); cdecl; overload; procedure load(in_: JInputStream); cdecl; overload; procedure load(in_: JReader); cdecl; overload; procedure loadFromXML(in_: JInputStream); cdecl; function propertyNames: JEnumeration; cdecl; procedure save(out_: JOutputStream; comment: JString); cdecl;//Deprecated function setProperty(name: JString; value: JString): JObject; cdecl; procedure store(out_: JOutputStream; comment: JString); cdecl; overload; procedure store(writer: JWriter; comment: JString); cdecl; overload; procedure storeToXML(os: JOutputStream; comment: JString); cdecl; overload; procedure storeToXML(os: JOutputStream; comment: JString; encoding: JString); cdecl; overload; function stringPropertyNames: JSet; cdecl; end; TJProperties = class(TJavaGenericImport<JPropertiesClass, JProperties>) end; JQueueClass = interface(JCollectionClass) ['{3A0B6ECD-D788-4FFA-9C17-6F7A761FE1DC}'] end; [JavaSignature('java/util/Queue')] JQueue = interface(JCollection) ['{1F7FBC68-484A-4622-AE37-764E1EC7AF04}'] function add(e: JObject): Boolean; cdecl; function element: JObject; cdecl; function offer(e: JObject): Boolean; cdecl; function peek: JObject; cdecl; function poll: JObject; cdecl; function remove: JObject; cdecl; end; TJQueue = class(TJavaGenericImport<JQueueClass, JQueue>) end; JRandomClass = interface(JObjectClass) ['{C50FE36A-6283-4523-BF77-15BB7A7B0F92}'] {class} function init: JRandom; cdecl; overload; {class} function init(seed: Int64): JRandom; cdecl; overload; end; [JavaSignature('java/util/Random')] JRandom = interface(JObject) ['{F1C05381-73F2-4991-853B-B22575DB43D2}'] function nextBoolean: Boolean; cdecl; procedure nextBytes(buf: TJavaArray<Byte>); cdecl; function nextDouble: Double; cdecl; function nextFloat: Single; cdecl; function nextGaussian: Double; cdecl; function nextInt: Integer; cdecl; overload; function nextInt(n: Integer): Integer; cdecl; overload; function nextLong: Int64; cdecl; procedure setSeed(seed: Int64); cdecl; end; TJRandom = class(TJavaGenericImport<JRandomClass, JRandom>) end; JSetClass = interface(JCollectionClass) ['{A3E290FD-FD46-4DA8-B728-07B04920F5DE}'] end; [JavaSignature('java/util/Set')] JSet = interface(JCollection) ['{07BF19A2-0C1C-4ABF-9028-1F99DD0E0A79}'] function add(object_: JObject): Boolean; cdecl; function addAll(collection: JCollection): Boolean; cdecl; procedure clear; cdecl; function &contains(object_: JObject): Boolean; cdecl; function containsAll(collection: JCollection): Boolean; cdecl; function equals(object_: JObject): Boolean; cdecl; function hashCode: Integer; cdecl; function isEmpty: Boolean; cdecl; function iterator: JIterator; cdecl; function remove(object_: JObject): Boolean; cdecl; function removeAll(collection: JCollection): Boolean; cdecl; function retainAll(collection: JCollection): Boolean; cdecl; function size: Integer; cdecl; function toArray: TJavaObjectArray<JObject>; cdecl; overload; function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload; end; TJSet = class(TJavaGenericImport<JSetClass, JSet>) end; JSortedMapClass = interface(JMapClass) ['{7665A1A5-0EE6-483D-A256-B13FA7E65230}'] end; [JavaSignature('java/util/SortedMap')] JSortedMap = interface(JMap) ['{3FD4011C-7238-42A1-8E25-D7B3F130E88F}'] function comparator: JComparator; cdecl; function firstKey: JObject; cdecl; function headMap(endKey: JObject): JSortedMap; cdecl; function lastKey: JObject; cdecl; function subMap(startKey: JObject; endKey: JObject): JSortedMap; cdecl; function tailMap(startKey: JObject): JSortedMap; cdecl; end; TJSortedMap = class(TJavaGenericImport<JSortedMapClass, JSortedMap>) end; JTimeZoneClass = interface(JObjectClass) ['{8F823620-CE10-44D5-82BA-24BFD63DCF80}'] {class} function _GetLONG: Integer; cdecl; {class} function _GetSHORT: Integer; cdecl; {class} function init: JTimeZone; cdecl; {class} function getAvailableIDs: TJavaObjectArray<JString>; cdecl; overload; {class} function getAvailableIDs(offsetMillis: Integer): TJavaObjectArray<JString>; cdecl; overload; {class} function getDefault: JTimeZone; cdecl; {class} function getTimeZone(id: JString): JTimeZone; cdecl; {class} procedure setDefault(timeZone: JTimeZone); cdecl; {class} property LONG: Integer read _GetLONG; {class} property SHORT: Integer read _GetSHORT; end; [JavaSignature('java/util/TimeZone')] JTimeZone = interface(JObject) ['{9D5215F4-A1B5-4B24-8B0B-EB3B88A0328D}'] function clone: JObject; cdecl; function getDSTSavings: Integer; cdecl; function getDisplayName: JString; cdecl; overload; function getDisplayName(locale: JLocale): JString; cdecl; overload; function getDisplayName(daylightTime: Boolean; style: Integer): JString; cdecl; overload; function getDisplayName(daylightTime: Boolean; style: Integer; locale: JLocale): JString; cdecl; overload; function getID: JString; cdecl; function getOffset(time: Int64): Integer; cdecl; overload; function getOffset(era: Integer; year: Integer; month: Integer; day: Integer; dayOfWeek: Integer; timeOfDayMillis: Integer): Integer; cdecl; overload; function getRawOffset: Integer; cdecl; function hasSameRules(timeZone: JTimeZone): Boolean; cdecl; function inDaylightTime(time: JDate): Boolean; cdecl; procedure setID(id: JString); cdecl; procedure setRawOffset(offsetMillis: Integer); cdecl; function useDaylightTime: Boolean; cdecl; end; TJTimeZone = class(TJavaGenericImport<JTimeZoneClass, JTimeZone>) end; JUUIDClass = interface(JObjectClass) ['{F254C874-67C8-4832-9619-9F686CB8E466}'] {class} function init(mostSigBits: Int64; leastSigBits: Int64): JUUID; cdecl; {class} function fromString(uuid: JString): JUUID; cdecl; {class} function nameUUIDFromBytes(name: TJavaArray<Byte>): JUUID; cdecl; {class} function randomUUID: JUUID; cdecl; end; [JavaSignature('java/util/UUID')] JUUID = interface(JObject) ['{B280C48F-E064-4030-BFD0-FB5970A78101}'] function clockSequence: Integer; cdecl; function compareTo(uuid: JUUID): Integer; cdecl; function equals(object_: JObject): Boolean; cdecl; function getLeastSignificantBits: Int64; cdecl; function getMostSignificantBits: Int64; cdecl; function hashCode: Integer; cdecl; function node: Int64; cdecl; function timestamp: Int64; cdecl; function toString: JString; cdecl; function variant: Integer; cdecl; function version: Integer; cdecl; end; TJUUID = class(TJavaGenericImport<JUUIDClass, JUUID>) end; JBlockingQueueClass = interface(JQueueClass) ['{FEAC4030-F87A-4E78-9454-A48238AC00D8}'] end; [JavaSignature('java/util/concurrent/BlockingQueue')] JBlockingQueue = interface(JQueue) ['{4F92390A-DED1-405E-894E-656C3AD20695}'] function add(e: JObject): Boolean; cdecl; function &contains(o: JObject): Boolean; cdecl; function drainTo(c: JCollection): Integer; cdecl; overload; function drainTo(c: JCollection; maxElements: Integer): Integer; cdecl; overload; function offer(e: JObject): Boolean; cdecl; overload; function offer(e: JObject; timeout: Int64; unit_: JTimeUnit): Boolean; cdecl; overload; function poll(timeout: Int64; unit_: JTimeUnit): JObject; cdecl; procedure put(e: JObject); cdecl; function remainingCapacity: Integer; cdecl; function remove(o: JObject): Boolean; cdecl; function take: JObject; cdecl; end; TJBlockingQueue = class(TJavaGenericImport<JBlockingQueueClass, JBlockingQueue>) end; JCallableClass = interface(IJavaClass) ['{F12DB2A8-1E01-44A9-BFBE-C6F3E32F7A65}'] end; [JavaSignature('java/util/concurrent/Callable')] JCallable = interface(IJavaInstance) ['{071A2E40-747B-4702-8DDB-D1749FB9B8FD}'] function call: JObject; cdecl; end; TJCallable = class(TJavaGenericImport<JCallableClass, JCallable>) end; JCountDownLatchClass = interface(JObjectClass) ['{8BB952D3-8BF8-4704-BC03-DCE2997C03AC}'] {class} function init(count: Integer): JCountDownLatch; cdecl; end; [JavaSignature('java/util/concurrent/CountDownLatch')] JCountDownLatch = interface(JObject) ['{302AA7D1-4CD0-45CB-868F-C1CF1209D276}'] procedure await; cdecl; overload; function await(timeout: Int64; unit_: JTimeUnit): Boolean; cdecl; overload; procedure countDown; cdecl; function getCount: Int64; cdecl; function toString: JString; cdecl; end; TJCountDownLatch = class(TJavaGenericImport<JCountDownLatchClass, JCountDownLatch>) end; JExecutorClass = interface(IJavaClass) ['{0606DEEF-30E1-4E40-82A3-20FF3E89BD61}'] end; [JavaSignature('java/util/concurrent/Executor')] JExecutor = interface(IJavaInstance) ['{B846ECEE-83CF-40BB-A4C5-FFC949DCEF15}'] procedure execute(command: JRunnable); cdecl; end; TJExecutor = class(TJavaGenericImport<JExecutorClass, JExecutor>) end; JExecutorServiceClass = interface(JExecutorClass) ['{4CF14DA3-BA41-4F67-A2DE-F62C8B02177F}'] end; [JavaSignature('java/util/concurrent/ExecutorService')] JExecutorService = interface(JExecutor) ['{37810DA0-1254-423D-B181-C62455CB5AE4}'] function awaitTermination(timeout: Int64; unit_: JTimeUnit): Boolean; cdecl; function invokeAll(tasks: JCollection): JList; cdecl; overload; function invokeAll(tasks: JCollection; timeout: Int64; unit_: JTimeUnit): JList; cdecl; overload; function invokeAny(tasks: JCollection): JObject; cdecl; overload; function invokeAny(tasks: JCollection; timeout: Int64; unit_: JTimeUnit): JObject; cdecl; overload; function isShutdown: Boolean; cdecl; function isTerminated: Boolean; cdecl; procedure shutdown; cdecl; function shutdownNow: JList; cdecl; function submit(task: JCallable): JFuture; cdecl; overload; function submit(task: JRunnable; result: JObject): JFuture; cdecl; overload; function submit(task: JRunnable): JFuture; cdecl; overload; end; TJExecutorService = class(TJavaGenericImport<JExecutorServiceClass, JExecutorService>) end; JFutureClass = interface(IJavaClass) ['{1716BCA6-301F-4D84-956C-AC25D1787B40}'] end; [JavaSignature('java/util/concurrent/Future')] JFuture = interface(IJavaInstance) ['{EFD52756-9DF1-45BD-9E0D-A36E3CDE3DB9}'] function cancel(mayInterruptIfRunning: Boolean): Boolean; cdecl; function &get: JObject; cdecl; overload; function &get(timeout: Int64; unit_: JTimeUnit): JObject; cdecl; overload; function isCancelled: Boolean; cdecl; function isDone: Boolean; cdecl; end; TJFuture = class(TJavaGenericImport<JFutureClass, JFuture>) end; JTimeUnitClass = interface(JEnumClass) ['{005AE9B1-228D-48C4-BFD2-41DCEE712F3B}'] {class} function _GetDAYS: JTimeUnit; cdecl; {class} function _GetHOURS: JTimeUnit; cdecl; {class} function _GetMICROSECONDS: JTimeUnit; cdecl; {class} function _GetMILLISECONDS: JTimeUnit; cdecl; {class} function _GetMINUTES: JTimeUnit; cdecl; {class} function _GetNANOSECONDS: JTimeUnit; cdecl; {class} function _GetSECONDS: JTimeUnit; cdecl; {class} function valueOf(name: JString): JTimeUnit; cdecl; {class} function values: TJavaObjectArray<JTimeUnit>; cdecl; {class} property DAYS: JTimeUnit read _GetDAYS; {class} property HOURS: JTimeUnit read _GetHOURS; {class} property MICROSECONDS: JTimeUnit read _GetMICROSECONDS; {class} property MILLISECONDS: JTimeUnit read _GetMILLISECONDS; {class} property MINUTES: JTimeUnit read _GetMINUTES; {class} property NANOSECONDS: JTimeUnit read _GetNANOSECONDS; {class} property SECONDS: JTimeUnit read _GetSECONDS; end; [JavaSignature('java/util/concurrent/TimeUnit')] JTimeUnit = interface(JEnum) ['{97B8E3BD-6430-4597-B01D-CD2AD51ECB2C}'] function convert(sourceDuration: Int64; sourceUnit: JTimeUnit): Int64; cdecl; procedure sleep(timeout: Int64); cdecl; procedure timedJoin(thread: JThread; timeout: Int64); cdecl; procedure timedWait(obj: JObject; timeout: Int64); cdecl; function toDays(duration: Int64): Int64; cdecl; function toHours(duration: Int64): Int64; cdecl; function toMicros(duration: Int64): Int64; cdecl; function toMillis(duration: Int64): Int64; cdecl; function toMinutes(duration: Int64): Int64; cdecl; function toNanos(duration: Int64): Int64; cdecl; function toSeconds(duration: Int64): Int64; cdecl; end; TJTimeUnit = class(TJavaGenericImport<JTimeUnitClass, JTimeUnit>) end; // javax.crypto.SecretKey JEGLClass = interface(IJavaClass) ['{79C069DA-2C75-4159-BE9D-A05ACE86FDCE}'] end; [JavaSignature('javax/microedition/khronos/egl/EGL')] JEGL = interface(IJavaInstance) ['{90E8D73C-9FF7-4CA4-B661-6A58F6A3C6C8}'] end; TJEGL = class(TJavaGenericImport<JEGLClass, JEGL>) end; JEGL10Class = interface(JEGLClass) ['{D1DB03A9-8FA6-44E2-BB75-AE16D5A11CA2}'] {class} function _GetEGL_ALPHA_FORMAT: Integer; cdecl; {class} function _GetEGL_ALPHA_MASK_SIZE: Integer; cdecl; {class} function _GetEGL_ALPHA_SIZE: Integer; cdecl; {class} function _GetEGL_BAD_ACCESS: Integer; cdecl; {class} function _GetEGL_BAD_ALLOC: Integer; cdecl; {class} function _GetEGL_BAD_ATTRIBUTE: Integer; cdecl; {class} function _GetEGL_BAD_CONFIG: Integer; cdecl; {class} function _GetEGL_BAD_CONTEXT: Integer; cdecl; {class} function _GetEGL_BAD_CURRENT_SURFACE: Integer; cdecl; {class} function _GetEGL_BAD_DISPLAY: Integer; cdecl; {class} function _GetEGL_BAD_MATCH: Integer; cdecl; {class} function _GetEGL_BAD_NATIVE_PIXMAP: Integer; cdecl; {class} function _GetEGL_BAD_NATIVE_WINDOW: Integer; cdecl; {class} function _GetEGL_BAD_PARAMETER: Integer; cdecl; {class} function _GetEGL_BAD_SURFACE: Integer; cdecl; {class} function _GetEGL_BLUE_SIZE: Integer; cdecl; {class} function _GetEGL_BUFFER_SIZE: Integer; cdecl; {class} function _GetEGL_COLORSPACE: Integer; cdecl; {class} function _GetEGL_COLOR_BUFFER_TYPE: Integer; cdecl; {class} function _GetEGL_CONFIG_CAVEAT: Integer; cdecl; {class} function _GetEGL_CONFIG_ID: Integer; cdecl; {class} function _GetEGL_CORE_NATIVE_ENGINE: Integer; cdecl; {class} function _GetEGL_DEFAULT_DISPLAY: JObject; cdecl; {class} function _GetEGL_DEPTH_SIZE: Integer; cdecl; {class} function _GetEGL_DONT_CARE: Integer; cdecl; {class} function _GetEGL_DRAW: Integer; cdecl; {class} function _GetEGL_EXTENSIONS: Integer; cdecl; {class} function _GetEGL_GREEN_SIZE: Integer; cdecl; {class} function _GetEGL_HEIGHT: Integer; cdecl; {class} function _GetEGL_HORIZONTAL_RESOLUTION: Integer; cdecl; {class} function _GetEGL_LARGEST_PBUFFER: Integer; cdecl; {class} function _GetEGL_LEVEL: Integer; cdecl; {class} function _GetEGL_LUMINANCE_BUFFER: Integer; cdecl; {class} function _GetEGL_LUMINANCE_SIZE: Integer; cdecl; {class} function _GetEGL_MAX_PBUFFER_HEIGHT: Integer; cdecl; {class} function _GetEGL_MAX_PBUFFER_PIXELS: Integer; cdecl; {class} function _GetEGL_MAX_PBUFFER_WIDTH: Integer; cdecl; {class} function _GetEGL_NATIVE_RENDERABLE: Integer; cdecl; {class} function _GetEGL_NATIVE_VISUAL_ID: Integer; cdecl; {class} function _GetEGL_NATIVE_VISUAL_TYPE: Integer; cdecl; {class} function _GetEGL_NONE: Integer; cdecl; {class} function _GetEGL_NON_CONFORMANT_CONFIG: Integer; cdecl; {class} function _GetEGL_NOT_INITIALIZED: Integer; cdecl; {class} function _GetEGL_NO_CONTEXT: JEGLContext; cdecl; {class} function _GetEGL_NO_DISPLAY: JEGLDisplay; cdecl; {class} function _GetEGL_NO_SURFACE: JEGLSurface; cdecl; {class} function _GetEGL_PBUFFER_BIT: Integer; cdecl; {class} function _GetEGL_PIXEL_ASPECT_RATIO: Integer; cdecl; {class} function _GetEGL_PIXMAP_BIT: Integer; cdecl; {class} function _GetEGL_READ: Integer; cdecl; {class} function _GetEGL_RED_SIZE: Integer; cdecl; {class} function _GetEGL_RENDERABLE_TYPE: Integer; cdecl; {class} function _GetEGL_RENDER_BUFFER: Integer; cdecl; {class} function _GetEGL_RGB_BUFFER: Integer; cdecl; {class} function _GetEGL_SAMPLES: Integer; cdecl; {class} function _GetEGL_SAMPLE_BUFFERS: Integer; cdecl; {class} function _GetEGL_SINGLE_BUFFER: Integer; cdecl; {class} function _GetEGL_SLOW_CONFIG: Integer; cdecl; {class} function _GetEGL_STENCIL_SIZE: Integer; cdecl; {class} function _GetEGL_SUCCESS: Integer; cdecl; {class} function _GetEGL_SURFACE_TYPE: Integer; cdecl; {class} function _GetEGL_TRANSPARENT_BLUE_VALUE: Integer; cdecl; {class} function _GetEGL_TRANSPARENT_GREEN_VALUE: Integer; cdecl; {class} function _GetEGL_TRANSPARENT_RED_VALUE: Integer; cdecl; {class} function _GetEGL_TRANSPARENT_RGB: Integer; cdecl; {class} function _GetEGL_TRANSPARENT_TYPE: Integer; cdecl; {class} function _GetEGL_VENDOR: Integer; cdecl; {class} function _GetEGL_VERSION: Integer; cdecl; {class} function _GetEGL_VERTICAL_RESOLUTION: Integer; cdecl; {class} function _GetEGL_WIDTH: Integer; cdecl; {class} function _GetEGL_WINDOW_BIT: Integer; cdecl; {class} property EGL_ALPHA_FORMAT: Integer read _GetEGL_ALPHA_FORMAT; {class} property EGL_ALPHA_MASK_SIZE: Integer read _GetEGL_ALPHA_MASK_SIZE; {class} property EGL_ALPHA_SIZE: Integer read _GetEGL_ALPHA_SIZE; {class} property EGL_BAD_ACCESS: Integer read _GetEGL_BAD_ACCESS; {class} property EGL_BAD_ALLOC: Integer read _GetEGL_BAD_ALLOC; {class} property EGL_BAD_ATTRIBUTE: Integer read _GetEGL_BAD_ATTRIBUTE; {class} property EGL_BAD_CONFIG: Integer read _GetEGL_BAD_CONFIG; {class} property EGL_BAD_CONTEXT: Integer read _GetEGL_BAD_CONTEXT; {class} property EGL_BAD_CURRENT_SURFACE: Integer read _GetEGL_BAD_CURRENT_SURFACE; {class} property EGL_BAD_DISPLAY: Integer read _GetEGL_BAD_DISPLAY; {class} property EGL_BAD_MATCH: Integer read _GetEGL_BAD_MATCH; {class} property EGL_BAD_NATIVE_PIXMAP: Integer read _GetEGL_BAD_NATIVE_PIXMAP; {class} property EGL_BAD_NATIVE_WINDOW: Integer read _GetEGL_BAD_NATIVE_WINDOW; {class} property EGL_BAD_PARAMETER: Integer read _GetEGL_BAD_PARAMETER; {class} property EGL_BAD_SURFACE: Integer read _GetEGL_BAD_SURFACE; {class} property EGL_BLUE_SIZE: Integer read _GetEGL_BLUE_SIZE; {class} property EGL_BUFFER_SIZE: Integer read _GetEGL_BUFFER_SIZE; {class} property EGL_COLORSPACE: Integer read _GetEGL_COLORSPACE; {class} property EGL_COLOR_BUFFER_TYPE: Integer read _GetEGL_COLOR_BUFFER_TYPE; {class} property EGL_CONFIG_CAVEAT: Integer read _GetEGL_CONFIG_CAVEAT; {class} property EGL_CONFIG_ID: Integer read _GetEGL_CONFIG_ID; {class} property EGL_CORE_NATIVE_ENGINE: Integer read _GetEGL_CORE_NATIVE_ENGINE; {class} property EGL_DEFAULT_DISPLAY: JObject read _GetEGL_DEFAULT_DISPLAY; {class} property EGL_DEPTH_SIZE: Integer read _GetEGL_DEPTH_SIZE; {class} property EGL_DONT_CARE: Integer read _GetEGL_DONT_CARE; {class} property EGL_DRAW: Integer read _GetEGL_DRAW; {class} property EGL_EXTENSIONS: Integer read _GetEGL_EXTENSIONS; {class} property EGL_GREEN_SIZE: Integer read _GetEGL_GREEN_SIZE; {class} property EGL_HEIGHT: Integer read _GetEGL_HEIGHT; {class} property EGL_HORIZONTAL_RESOLUTION: Integer read _GetEGL_HORIZONTAL_RESOLUTION; {class} property EGL_LARGEST_PBUFFER: Integer read _GetEGL_LARGEST_PBUFFER; {class} property EGL_LEVEL: Integer read _GetEGL_LEVEL; {class} property EGL_LUMINANCE_BUFFER: Integer read _GetEGL_LUMINANCE_BUFFER; {class} property EGL_LUMINANCE_SIZE: Integer read _GetEGL_LUMINANCE_SIZE; {class} property EGL_MAX_PBUFFER_HEIGHT: Integer read _GetEGL_MAX_PBUFFER_HEIGHT; {class} property EGL_MAX_PBUFFER_PIXELS: Integer read _GetEGL_MAX_PBUFFER_PIXELS; {class} property EGL_MAX_PBUFFER_WIDTH: Integer read _GetEGL_MAX_PBUFFER_WIDTH; {class} property EGL_NATIVE_RENDERABLE: Integer read _GetEGL_NATIVE_RENDERABLE; {class} property EGL_NATIVE_VISUAL_ID: Integer read _GetEGL_NATIVE_VISUAL_ID; {class} property EGL_NATIVE_VISUAL_TYPE: Integer read _GetEGL_NATIVE_VISUAL_TYPE; {class} property EGL_NONE: Integer read _GetEGL_NONE; {class} property EGL_NON_CONFORMANT_CONFIG: Integer read _GetEGL_NON_CONFORMANT_CONFIG; {class} property EGL_NOT_INITIALIZED: Integer read _GetEGL_NOT_INITIALIZED; {class} property EGL_NO_CONTEXT: JEGLContext read _GetEGL_NO_CONTEXT; {class} property EGL_NO_DISPLAY: JEGLDisplay read _GetEGL_NO_DISPLAY; {class} property EGL_NO_SURFACE: JEGLSurface read _GetEGL_NO_SURFACE; {class} property EGL_PBUFFER_BIT: Integer read _GetEGL_PBUFFER_BIT; {class} property EGL_PIXEL_ASPECT_RATIO: Integer read _GetEGL_PIXEL_ASPECT_RATIO; {class} property EGL_PIXMAP_BIT: Integer read _GetEGL_PIXMAP_BIT; {class} property EGL_READ: Integer read _GetEGL_READ; {class} property EGL_RED_SIZE: Integer read _GetEGL_RED_SIZE; {class} property EGL_RENDERABLE_TYPE: Integer read _GetEGL_RENDERABLE_TYPE; {class} property EGL_RENDER_BUFFER: Integer read _GetEGL_RENDER_BUFFER; {class} property EGL_RGB_BUFFER: Integer read _GetEGL_RGB_BUFFER; {class} property EGL_SAMPLES: Integer read _GetEGL_SAMPLES; {class} property EGL_SAMPLE_BUFFERS: Integer read _GetEGL_SAMPLE_BUFFERS; {class} property EGL_SINGLE_BUFFER: Integer read _GetEGL_SINGLE_BUFFER; {class} property EGL_SLOW_CONFIG: Integer read _GetEGL_SLOW_CONFIG; {class} property EGL_STENCIL_SIZE: Integer read _GetEGL_STENCIL_SIZE; {class} property EGL_SUCCESS: Integer read _GetEGL_SUCCESS; {class} property EGL_SURFACE_TYPE: Integer read _GetEGL_SURFACE_TYPE; {class} property EGL_TRANSPARENT_BLUE_VALUE: Integer read _GetEGL_TRANSPARENT_BLUE_VALUE; {class} property EGL_TRANSPARENT_GREEN_VALUE: Integer read _GetEGL_TRANSPARENT_GREEN_VALUE; {class} property EGL_TRANSPARENT_RED_VALUE: Integer read _GetEGL_TRANSPARENT_RED_VALUE; {class} property EGL_TRANSPARENT_RGB: Integer read _GetEGL_TRANSPARENT_RGB; {class} property EGL_TRANSPARENT_TYPE: Integer read _GetEGL_TRANSPARENT_TYPE; {class} property EGL_VENDOR: Integer read _GetEGL_VENDOR; {class} property EGL_VERSION: Integer read _GetEGL_VERSION; {class} property EGL_VERTICAL_RESOLUTION: Integer read _GetEGL_VERTICAL_RESOLUTION; {class} property EGL_WIDTH: Integer read _GetEGL_WIDTH; {class} property EGL_WINDOW_BIT: Integer read _GetEGL_WINDOW_BIT; end; [JavaSignature('javax/microedition/khronos/egl/EGL10')] JEGL10 = interface(JEGL) ['{5178914E-D8BE-44D4-AD82-ADE844D55BEE}'] function eglChooseConfig(display: JEGLDisplay; attrib_list: TJavaArray<Integer>; configs: TJavaObjectArray<JEGLConfig>; config_size: Integer; num_config: TJavaArray<Integer>): Boolean; cdecl; function eglCopyBuffers(display: JEGLDisplay; surface: JEGLSurface; native_pixmap: JObject): Boolean; cdecl; function eglCreateContext(display: JEGLDisplay; config: JEGLConfig; share_context: JEGLContext; attrib_list: TJavaArray<Integer>): JEGLContext; cdecl; function eglCreatePbufferSurface(display: JEGLDisplay; config: JEGLConfig; attrib_list: TJavaArray<Integer>): JEGLSurface; cdecl; function eglCreatePixmapSurface(display: JEGLDisplay; config: JEGLConfig; native_pixmap: JObject; attrib_list: TJavaArray<Integer>): JEGLSurface; cdecl; function eglCreateWindowSurface(display: JEGLDisplay; config: JEGLConfig; native_window: JObject; attrib_list: TJavaArray<Integer>): JEGLSurface; cdecl; function eglDestroyContext(display: JEGLDisplay; context: JEGLContext): Boolean; cdecl; function eglDestroySurface(display: JEGLDisplay; surface: JEGLSurface): Boolean; cdecl; function eglGetConfigAttrib(display: JEGLDisplay; config: JEGLConfig; attribute: Integer; value: TJavaArray<Integer>): Boolean; cdecl; function eglGetConfigs(display: JEGLDisplay; configs: TJavaObjectArray<JEGLConfig>; config_size: Integer; num_config: TJavaArray<Integer>): Boolean; cdecl; function eglGetCurrentContext: JEGLContext; cdecl; function eglGetCurrentDisplay: JEGLDisplay; cdecl; function eglGetCurrentSurface(readdraw: Integer): JEGLSurface; cdecl; function eglGetDisplay(native_display: JObject): JEGLDisplay; cdecl; function eglGetError: Integer; cdecl; function eglInitialize(display: JEGLDisplay; major_minor: TJavaArray<Integer>): Boolean; cdecl; function eglMakeCurrent(display: JEGLDisplay; draw: JEGLSurface; read: JEGLSurface; context: JEGLContext): Boolean; cdecl; function eglQueryContext(display: JEGLDisplay; context: JEGLContext; attribute: Integer; value: TJavaArray<Integer>): Boolean; cdecl; function eglQueryString(display: JEGLDisplay; name: Integer): JString; cdecl; function eglQuerySurface(display: JEGLDisplay; surface: JEGLSurface; attribute: Integer; value: TJavaArray<Integer>): Boolean; cdecl; function eglSwapBuffers(display: JEGLDisplay; surface: JEGLSurface): Boolean; cdecl; function eglTerminate(display: JEGLDisplay): Boolean; cdecl; function eglWaitGL: Boolean; cdecl; function eglWaitNative(engine: Integer; bindTarget: JObject): Boolean; cdecl; end; TJEGL10 = class(TJavaGenericImport<JEGL10Class, JEGL10>) end; JEGLConfigClass = interface(JObjectClass) ['{96A2CBA0-853E-45DC-95EA-AA707DA29569}'] {class} function init: JEGLConfig; cdecl; end; [JavaSignature('javax/microedition/khronos/egl/EGLConfig')] JEGLConfig = interface(JObject) ['{2647F2E5-3A3D-4D51-AB8D-5819899D7B8E}'] end; TJEGLConfig = class(TJavaGenericImport<JEGLConfigClass, JEGLConfig>) end; JEGLContextClass = interface(JObjectClass) ['{75CB0600-343C-4078-A743-40B5C9E79FFF}'] {class} function init: JEGLContext; cdecl; {class} function getEGL: JEGL; cdecl; end; [JavaSignature('javax/microedition/khronos/egl/EGLContext')] JEGLContext = interface(JObject) ['{768D920B-DB0B-4278-B16D-226D7BF1A971}'] function getGL: JGL; cdecl; end; TJEGLContext = class(TJavaGenericImport<JEGLContextClass, JEGLContext>) end; JEGLDisplayClass = interface(JObjectClass) ['{1BCD3FCD-D59F-4D36-A5D2-F7492B04669F}'] {class} function init: JEGLDisplay; cdecl; end; [JavaSignature('javax/microedition/khronos/egl/EGLDisplay')] JEGLDisplay = interface(JObject) ['{CB130B2B-7534-4FFF-9679-BD9B21F8FEC6}'] end; TJEGLDisplay = class(TJavaGenericImport<JEGLDisplayClass, JEGLDisplay>) end; JEGLSurfaceClass = interface(JObjectClass) ['{E0F463FF-63B5-4F4D-BF36-6CDEDFE151EB}'] {class} function init: JEGLSurface; cdecl; end; [JavaSignature('javax/microedition/khronos/egl/EGLSurface')] JEGLSurface = interface(JObject) ['{6BD5B09A-C1F7-4E46-A4E3-56F96C388D26}'] end; TJEGLSurface = class(TJavaGenericImport<JEGLSurfaceClass, JEGLSurface>) end; JGLClass = interface(IJavaClass) ['{9E0B1F51-CA90-4AEB-8D45-C34729067041}'] end; [JavaSignature('javax/microedition/khronos/opengles/GL')] JGL = interface(IJavaInstance) ['{210EA9DA-F5F9-4849-9FF2-28297F3CD7ED}'] end; TJGL = class(TJavaGenericImport<JGLClass, JGL>) end; JGL10Class = interface(JGLClass) ['{11B00106-3641-4149-833C-F2A15DD0A1FB}'] {class} function _GetGL_ADD: Integer; cdecl; {class} function _GetGL_ALIASED_LINE_WIDTH_RANGE: Integer; cdecl; {class} function _GetGL_ALIASED_POINT_SIZE_RANGE: Integer; cdecl; {class} function _GetGL_ALPHA: Integer; cdecl; {class} function _GetGL_ALPHA_BITS: Integer; cdecl; {class} function _GetGL_ALPHA_TEST: Integer; cdecl; {class} function _GetGL_ALWAYS: Integer; cdecl; {class} function _GetGL_AMBIENT: Integer; cdecl; {class} function _GetGL_AMBIENT_AND_DIFFUSE: Integer; cdecl; {class} function _GetGL_AND: Integer; cdecl; {class} function _GetGL_AND_INVERTED: Integer; cdecl; {class} function _GetGL_AND_REVERSE: Integer; cdecl; {class} function _GetGL_BACK: Integer; cdecl; {class} function _GetGL_BLEND: Integer; cdecl; {class} function _GetGL_BLUE_BITS: Integer; cdecl; {class} function _GetGL_BYTE: Integer; cdecl; {class} function _GetGL_CCW: Integer; cdecl; {class} function _GetGL_CLAMP_TO_EDGE: Integer; cdecl; {class} function _GetGL_CLEAR: Integer; cdecl; {class} function _GetGL_COLOR_ARRAY: Integer; cdecl; {class} function _GetGL_COLOR_BUFFER_BIT: Integer; cdecl; {class} function _GetGL_COLOR_LOGIC_OP: Integer; cdecl; {class} function _GetGL_COLOR_MATERIAL: Integer; cdecl; {class} function _GetGL_COMPRESSED_TEXTURE_FORMATS: Integer; cdecl; {class} function _GetGL_CONSTANT_ATTENUATION: Integer; cdecl; {class} function _GetGL_COPY: Integer; cdecl; {class} function _GetGL_COPY_INVERTED: Integer; cdecl; {class} function _GetGL_CULL_FACE: Integer; cdecl; {class} function _GetGL_CW: Integer; cdecl; {class} function _GetGL_DECAL: Integer; cdecl; {class} function _GetGL_DECR: Integer; cdecl; {class} function _GetGL_DEPTH_BITS: Integer; cdecl; {class} function _GetGL_DEPTH_BUFFER_BIT: Integer; cdecl; {class} function _GetGL_DEPTH_TEST: Integer; cdecl; {class} function _GetGL_DIFFUSE: Integer; cdecl; {class} function _GetGL_DITHER: Integer; cdecl; {class} function _GetGL_DONT_CARE: Integer; cdecl; {class} function _GetGL_DST_ALPHA: Integer; cdecl; {class} function _GetGL_DST_COLOR: Integer; cdecl; {class} function _GetGL_EMISSION: Integer; cdecl; {class} function _GetGL_EQUAL: Integer; cdecl; {class} function _GetGL_EQUIV: Integer; cdecl; {class} function _GetGL_EXP: Integer; cdecl; {class} function _GetGL_EXP2: Integer; cdecl; {class} function _GetGL_EXTENSIONS: Integer; cdecl; {class} function _GetGL_FALSE: Integer; cdecl; {class} function _GetGL_FASTEST: Integer; cdecl; {class} function _GetGL_FIXED: Integer; cdecl; {class} function _GetGL_FLAT: Integer; cdecl; {class} function _GetGL_FLOAT: Integer; cdecl; {class} function _GetGL_FOG: Integer; cdecl; {class} function _GetGL_FOG_COLOR: Integer; cdecl; {class} function _GetGL_FOG_DENSITY: Integer; cdecl; {class} function _GetGL_FOG_END: Integer; cdecl; {class} function _GetGL_FOG_HINT: Integer; cdecl; {class} function _GetGL_FOG_MODE: Integer; cdecl; {class} function _GetGL_FOG_START: Integer; cdecl; {class} function _GetGL_FRONT: Integer; cdecl; {class} function _GetGL_FRONT_AND_BACK: Integer; cdecl; {class} function _GetGL_GEQUAL: Integer; cdecl; {class} function _GetGL_GREATER: Integer; cdecl; {class} function _GetGL_GREEN_BITS: Integer; cdecl; {class} function _GetGL_IMPLEMENTATION_COLOR_READ_FORMAT_OES: Integer; cdecl; {class} function _GetGL_IMPLEMENTATION_COLOR_READ_TYPE_OES: Integer; cdecl; {class} function _GetGL_INCR: Integer; cdecl; {class} function _GetGL_INVALID_ENUM: Integer; cdecl; {class} function _GetGL_INVALID_OPERATION: Integer; cdecl; {class} function _GetGL_INVALID_VALUE: Integer; cdecl; {class} function _GetGL_INVERT: Integer; cdecl; {class} function _GetGL_KEEP: Integer; cdecl; {class} function _GetGL_LEQUAL: Integer; cdecl; {class} function _GetGL_LESS: Integer; cdecl; {class} function _GetGL_LIGHT0: Integer; cdecl; {class} function _GetGL_LIGHT1: Integer; cdecl; {class} function _GetGL_LIGHT2: Integer; cdecl; {class} function _GetGL_LIGHT3: Integer; cdecl; {class} function _GetGL_LIGHT4: Integer; cdecl; {class} function _GetGL_LIGHT5: Integer; cdecl; {class} function _GetGL_LIGHT6: Integer; cdecl; {class} function _GetGL_LIGHT7: Integer; cdecl; {class} function _GetGL_LIGHTING: Integer; cdecl; {class} function _GetGL_LIGHT_MODEL_AMBIENT: Integer; cdecl; {class} function _GetGL_LIGHT_MODEL_TWO_SIDE: Integer; cdecl; {class} function _GetGL_LINEAR: Integer; cdecl; {class} function _GetGL_LINEAR_ATTENUATION: Integer; cdecl; {class} function _GetGL_LINEAR_MIPMAP_LINEAR: Integer; cdecl; {class} function _GetGL_LINEAR_MIPMAP_NEAREST: Integer; cdecl; {class} function _GetGL_LINES: Integer; cdecl; {class} function _GetGL_LINE_LOOP: Integer; cdecl; {class} function _GetGL_LINE_SMOOTH: Integer; cdecl; {class} function _GetGL_LINE_SMOOTH_HINT: Integer; cdecl; {class} function _GetGL_LINE_STRIP: Integer; cdecl; {class} function _GetGL_LUMINANCE: Integer; cdecl; {class} function _GetGL_LUMINANCE_ALPHA: Integer; cdecl; {class} function _GetGL_MAX_ELEMENTS_INDICES: Integer; cdecl; {class} function _GetGL_MAX_ELEMENTS_VERTICES: Integer; cdecl; {class} function _GetGL_MAX_LIGHTS: Integer; cdecl; {class} function _GetGL_MAX_MODELVIEW_STACK_DEPTH: Integer; cdecl; {class} function _GetGL_MAX_PROJECTION_STACK_DEPTH: Integer; cdecl; {class} function _GetGL_MAX_TEXTURE_SIZE: Integer; cdecl; {class} function _GetGL_MAX_TEXTURE_STACK_DEPTH: Integer; cdecl; {class} function _GetGL_MAX_TEXTURE_UNITS: Integer; cdecl; {class} function _GetGL_MAX_VIEWPORT_DIMS: Integer; cdecl; {class} function _GetGL_MODELVIEW: Integer; cdecl; {class} function _GetGL_MODULATE: Integer; cdecl; {class} function _GetGL_MULTISAMPLE: Integer; cdecl; {class} function _GetGL_NAND: Integer; cdecl; {class} function _GetGL_NEAREST: Integer; cdecl; {class} function _GetGL_NEAREST_MIPMAP_LINEAR: Integer; cdecl; {class} function _GetGL_NEAREST_MIPMAP_NEAREST: Integer; cdecl; {class} function _GetGL_NEVER: Integer; cdecl; {class} function _GetGL_NICEST: Integer; cdecl; {class} function _GetGL_NOOP: Integer; cdecl; {class} function _GetGL_NOR: Integer; cdecl; {class} function _GetGL_NORMALIZE: Integer; cdecl; {class} function _GetGL_NORMAL_ARRAY: Integer; cdecl; {class} function _GetGL_NOTEQUAL: Integer; cdecl; {class} function _GetGL_NO_ERROR: Integer; cdecl; {class} function _GetGL_NUM_COMPRESSED_TEXTURE_FORMATS: Integer; cdecl; {class} function _GetGL_ONE: Integer; cdecl; {class} function _GetGL_ONE_MINUS_DST_ALPHA: Integer; cdecl; {class} function _GetGL_ONE_MINUS_DST_COLOR: Integer; cdecl; {class} function _GetGL_ONE_MINUS_SRC_ALPHA: Integer; cdecl; {class} function _GetGL_ONE_MINUS_SRC_COLOR: Integer; cdecl; {class} function _GetGL_OR: Integer; cdecl; {class} function _GetGL_OR_INVERTED: Integer; cdecl; {class} function _GetGL_OR_REVERSE: Integer; cdecl; {class} function _GetGL_OUT_OF_MEMORY: Integer; cdecl; {class} function _GetGL_PACK_ALIGNMENT: Integer; cdecl; {class} function _GetGL_PALETTE4_R5_G6_B5_OES: Integer; cdecl; {class} function _GetGL_PALETTE4_RGB5_A1_OES: Integer; cdecl; {class} function _GetGL_PALETTE4_RGB8_OES: Integer; cdecl; {class} function _GetGL_PALETTE4_RGBA4_OES: Integer; cdecl; {class} function _GetGL_PALETTE4_RGBA8_OES: Integer; cdecl; {class} function _GetGL_PALETTE8_R5_G6_B5_OES: Integer; cdecl; {class} function _GetGL_PALETTE8_RGB5_A1_OES: Integer; cdecl; {class} function _GetGL_PALETTE8_RGB8_OES: Integer; cdecl; {class} function _GetGL_PALETTE8_RGBA4_OES: Integer; cdecl; {class} function _GetGL_PALETTE8_RGBA8_OES: Integer; cdecl; {class} function _GetGL_PERSPECTIVE_CORRECTION_HINT: Integer; cdecl; {class} function _GetGL_POINTS: Integer; cdecl; {class} function _GetGL_POINT_FADE_THRESHOLD_SIZE: Integer; cdecl; {class} function _GetGL_POINT_SIZE: Integer; cdecl; {class} function _GetGL_POINT_SMOOTH: Integer; cdecl; {class} function _GetGL_POINT_SMOOTH_HINT: Integer; cdecl; {class} function _GetGL_POLYGON_OFFSET_FILL: Integer; cdecl; {class} function _GetGL_POLYGON_SMOOTH_HINT: Integer; cdecl; {class} function _GetGL_POSITION: Integer; cdecl; {class} function _GetGL_PROJECTION: Integer; cdecl; {class} function _GetGL_QUADRATIC_ATTENUATION: Integer; cdecl; {class} function _GetGL_RED_BITS: Integer; cdecl; {class} function _GetGL_RENDERER: Integer; cdecl; {class} function _GetGL_REPEAT: Integer; cdecl; {class} function _GetGL_REPLACE: Integer; cdecl; {class} function _GetGL_RESCALE_NORMAL: Integer; cdecl; {class} function _GetGL_RGB: Integer; cdecl; {class} function _GetGL_RGBA: Integer; cdecl; {class} function _GetGL_SAMPLE_ALPHA_TO_COVERAGE: Integer; cdecl; {class} function _GetGL_SAMPLE_ALPHA_TO_ONE: Integer; cdecl; {class} function _GetGL_SAMPLE_COVERAGE: Integer; cdecl; {class} function _GetGL_SCISSOR_TEST: Integer; cdecl; {class} function _GetGL_SET: Integer; cdecl; {class} function _GetGL_SHININESS: Integer; cdecl; {class} function _GetGL_SHORT: Integer; cdecl; {class} function _GetGL_SMOOTH: Integer; cdecl; {class} function _GetGL_SMOOTH_LINE_WIDTH_RANGE: Integer; cdecl; {class} function _GetGL_SMOOTH_POINT_SIZE_RANGE: Integer; cdecl; {class} function _GetGL_SPECULAR: Integer; cdecl; {class} function _GetGL_SPOT_CUTOFF: Integer; cdecl; {class} function _GetGL_SPOT_DIRECTION: Integer; cdecl; {class} function _GetGL_SPOT_EXPONENT: Integer; cdecl; {class} function _GetGL_SRC_ALPHA: Integer; cdecl; {class} function _GetGL_SRC_ALPHA_SATURATE: Integer; cdecl; {class} function _GetGL_SRC_COLOR: Integer; cdecl; {class} function _GetGL_STACK_OVERFLOW: Integer; cdecl; {class} function _GetGL_STACK_UNDERFLOW: Integer; cdecl; {class} function _GetGL_STENCIL_BITS: Integer; cdecl; {class} function _GetGL_STENCIL_BUFFER_BIT: Integer; cdecl; {class} function _GetGL_STENCIL_TEST: Integer; cdecl; {class} function _GetGL_SUBPIXEL_BITS: Integer; cdecl; {class} function _GetGL_TEXTURE: Integer; cdecl; {class} function _GetGL_TEXTURE0: Integer; cdecl; {class} function _GetGL_TEXTURE1: Integer; cdecl; {class} function _GetGL_TEXTURE10: Integer; cdecl; {class} function _GetGL_TEXTURE11: Integer; cdecl; {class} function _GetGL_TEXTURE12: Integer; cdecl; {class} function _GetGL_TEXTURE13: Integer; cdecl; {class} function _GetGL_TEXTURE14: Integer; cdecl; {class} function _GetGL_TEXTURE15: Integer; cdecl; {class} function _GetGL_TEXTURE16: Integer; cdecl; {class} function _GetGL_TEXTURE17: Integer; cdecl; {class} function _GetGL_TEXTURE18: Integer; cdecl; {class} function _GetGL_TEXTURE19: Integer; cdecl; {class} function _GetGL_TEXTURE2: Integer; cdecl; {class} function _GetGL_TEXTURE20: Integer; cdecl; {class} function _GetGL_TEXTURE21: Integer; cdecl; {class} function _GetGL_TEXTURE22: Integer; cdecl; {class} function _GetGL_TEXTURE23: Integer; cdecl; {class} function _GetGL_TEXTURE24: Integer; cdecl; {class} function _GetGL_TEXTURE25: Integer; cdecl; {class} function _GetGL_TEXTURE26: Integer; cdecl; {class} function _GetGL_TEXTURE27: Integer; cdecl; {class} function _GetGL_TEXTURE28: Integer; cdecl; {class} function _GetGL_TEXTURE29: Integer; cdecl; {class} function _GetGL_TEXTURE3: Integer; cdecl; {class} function _GetGL_TEXTURE30: Integer; cdecl; {class} function _GetGL_TEXTURE31: Integer; cdecl; {class} function _GetGL_TEXTURE4: Integer; cdecl; {class} function _GetGL_TEXTURE5: Integer; cdecl; {class} function _GetGL_TEXTURE6: Integer; cdecl; {class} function _GetGL_TEXTURE7: Integer; cdecl; {class} function _GetGL_TEXTURE8: Integer; cdecl; {class} function _GetGL_TEXTURE9: Integer; cdecl; {class} function _GetGL_TEXTURE_2D: Integer; cdecl; {class} function _GetGL_TEXTURE_COORD_ARRAY: Integer; cdecl; {class} function _GetGL_TEXTURE_ENV: Integer; cdecl; {class} function _GetGL_TEXTURE_ENV_COLOR: Integer; cdecl; {class} function _GetGL_TEXTURE_ENV_MODE: Integer; cdecl; {class} function _GetGL_TEXTURE_MAG_FILTER: Integer; cdecl; {class} function _GetGL_TEXTURE_MIN_FILTER: Integer; cdecl; {class} function _GetGL_TEXTURE_WRAP_S: Integer; cdecl; {class} function _GetGL_TEXTURE_WRAP_T: Integer; cdecl; {class} function _GetGL_TRIANGLES: Integer; cdecl; {class} function _GetGL_TRIANGLE_FAN: Integer; cdecl; {class} function _GetGL_TRIANGLE_STRIP: Integer; cdecl; {class} function _GetGL_TRUE: Integer; cdecl; {class} function _GetGL_UNPACK_ALIGNMENT: Integer; cdecl; {class} function _GetGL_UNSIGNED_BYTE: Integer; cdecl; {class} function _GetGL_UNSIGNED_SHORT: Integer; cdecl; {class} function _GetGL_UNSIGNED_SHORT_4_4_4_4: Integer; cdecl; {class} function _GetGL_UNSIGNED_SHORT_5_5_5_1: Integer; cdecl; {class} function _GetGL_UNSIGNED_SHORT_5_6_5: Integer; cdecl; {class} function _GetGL_VENDOR: Integer; cdecl; {class} function _GetGL_VERSION: Integer; cdecl; {class} function _GetGL_VERTEX_ARRAY: Integer; cdecl; {class} function _GetGL_XOR: Integer; cdecl; {class} function _GetGL_ZERO: Integer; cdecl; {class} property GL_ADD: Integer read _GetGL_ADD; {class} property GL_ALIASED_LINE_WIDTH_RANGE: Integer read _GetGL_ALIASED_LINE_WIDTH_RANGE; {class} property GL_ALIASED_POINT_SIZE_RANGE: Integer read _GetGL_ALIASED_POINT_SIZE_RANGE; {class} property GL_ALPHA: Integer read _GetGL_ALPHA; {class} property GL_ALPHA_BITS: Integer read _GetGL_ALPHA_BITS; {class} property GL_ALPHA_TEST: Integer read _GetGL_ALPHA_TEST; {class} property GL_ALWAYS: Integer read _GetGL_ALWAYS; {class} property GL_AMBIENT: Integer read _GetGL_AMBIENT; {class} property GL_AMBIENT_AND_DIFFUSE: Integer read _GetGL_AMBIENT_AND_DIFFUSE; {class} property GL_AND: Integer read _GetGL_AND; {class} property GL_AND_INVERTED: Integer read _GetGL_AND_INVERTED; {class} property GL_AND_REVERSE: Integer read _GetGL_AND_REVERSE; {class} property GL_BACK: Integer read _GetGL_BACK; {class} property GL_BLEND: Integer read _GetGL_BLEND; {class} property GL_BLUE_BITS: Integer read _GetGL_BLUE_BITS; {class} property GL_BYTE: Integer read _GetGL_BYTE; {class} property GL_CCW: Integer read _GetGL_CCW; {class} property GL_CLAMP_TO_EDGE: Integer read _GetGL_CLAMP_TO_EDGE; {class} property GL_CLEAR: Integer read _GetGL_CLEAR; {class} property GL_COLOR_ARRAY: Integer read _GetGL_COLOR_ARRAY; {class} property GL_COLOR_BUFFER_BIT: Integer read _GetGL_COLOR_BUFFER_BIT; {class} property GL_COLOR_LOGIC_OP: Integer read _GetGL_COLOR_LOGIC_OP; {class} property GL_COLOR_MATERIAL: Integer read _GetGL_COLOR_MATERIAL; {class} property GL_COMPRESSED_TEXTURE_FORMATS: Integer read _GetGL_COMPRESSED_TEXTURE_FORMATS; {class} property GL_CONSTANT_ATTENUATION: Integer read _GetGL_CONSTANT_ATTENUATION; {class} property GL_COPY: Integer read _GetGL_COPY; {class} property GL_COPY_INVERTED: Integer read _GetGL_COPY_INVERTED; {class} property GL_CULL_FACE: Integer read _GetGL_CULL_FACE; {class} property GL_CW: Integer read _GetGL_CW; {class} property GL_DECAL: Integer read _GetGL_DECAL; {class} property GL_DECR: Integer read _GetGL_DECR; {class} property GL_DEPTH_BITS: Integer read _GetGL_DEPTH_BITS; {class} property GL_DEPTH_BUFFER_BIT: Integer read _GetGL_DEPTH_BUFFER_BIT; {class} property GL_DEPTH_TEST: Integer read _GetGL_DEPTH_TEST; {class} property GL_DIFFUSE: Integer read _GetGL_DIFFUSE; {class} property GL_DITHER: Integer read _GetGL_DITHER; {class} property GL_DONT_CARE: Integer read _GetGL_DONT_CARE; {class} property GL_DST_ALPHA: Integer read _GetGL_DST_ALPHA; {class} property GL_DST_COLOR: Integer read _GetGL_DST_COLOR; {class} property GL_EMISSION: Integer read _GetGL_EMISSION; {class} property GL_EQUAL: Integer read _GetGL_EQUAL; {class} property GL_EQUIV: Integer read _GetGL_EQUIV; {class} property GL_EXP: Integer read _GetGL_EXP; {class} property GL_EXP2: Integer read _GetGL_EXP2; {class} property GL_EXTENSIONS: Integer read _GetGL_EXTENSIONS; {class} property GL_FALSE: Integer read _GetGL_FALSE; {class} property GL_FASTEST: Integer read _GetGL_FASTEST; {class} property GL_FIXED: Integer read _GetGL_FIXED; {class} property GL_FLAT: Integer read _GetGL_FLAT; {class} property GL_FLOAT: Integer read _GetGL_FLOAT; {class} property GL_FOG: Integer read _GetGL_FOG; {class} property GL_FOG_COLOR: Integer read _GetGL_FOG_COLOR; {class} property GL_FOG_DENSITY: Integer read _GetGL_FOG_DENSITY; {class} property GL_FOG_END: Integer read _GetGL_FOG_END; {class} property GL_FOG_HINT: Integer read _GetGL_FOG_HINT; {class} property GL_FOG_MODE: Integer read _GetGL_FOG_MODE; {class} property GL_FOG_START: Integer read _GetGL_FOG_START; {class} property GL_FRONT: Integer read _GetGL_FRONT; {class} property GL_FRONT_AND_BACK: Integer read _GetGL_FRONT_AND_BACK; {class} property GL_GEQUAL: Integer read _GetGL_GEQUAL; {class} property GL_GREATER: Integer read _GetGL_GREATER; {class} property GL_GREEN_BITS: Integer read _GetGL_GREEN_BITS; {class} property GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES: Integer read _GetGL_IMPLEMENTATION_COLOR_READ_FORMAT_OES; {class} property GL_IMPLEMENTATION_COLOR_READ_TYPE_OES: Integer read _GetGL_IMPLEMENTATION_COLOR_READ_TYPE_OES; {class} property GL_INCR: Integer read _GetGL_INCR; {class} property GL_INVALID_ENUM: Integer read _GetGL_INVALID_ENUM; {class} property GL_INVALID_OPERATION: Integer read _GetGL_INVALID_OPERATION; {class} property GL_INVALID_VALUE: Integer read _GetGL_INVALID_VALUE; {class} property GL_INVERT: Integer read _GetGL_INVERT; {class} property GL_KEEP: Integer read _GetGL_KEEP; {class} property GL_LEQUAL: Integer read _GetGL_LEQUAL; {class} property GL_LESS: Integer read _GetGL_LESS; {class} property GL_LIGHT0: Integer read _GetGL_LIGHT0; {class} property GL_LIGHT1: Integer read _GetGL_LIGHT1; {class} property GL_LIGHT2: Integer read _GetGL_LIGHT2; {class} property GL_LIGHT3: Integer read _GetGL_LIGHT3; {class} property GL_LIGHT4: Integer read _GetGL_LIGHT4; {class} property GL_LIGHT5: Integer read _GetGL_LIGHT5; {class} property GL_LIGHT6: Integer read _GetGL_LIGHT6; {class} property GL_LIGHT7: Integer read _GetGL_LIGHT7; {class} property GL_LIGHTING: Integer read _GetGL_LIGHTING; {class} property GL_LIGHT_MODEL_AMBIENT: Integer read _GetGL_LIGHT_MODEL_AMBIENT; {class} property GL_LIGHT_MODEL_TWO_SIDE: Integer read _GetGL_LIGHT_MODEL_TWO_SIDE; {class} property GL_LINEAR: Integer read _GetGL_LINEAR; {class} property GL_LINEAR_ATTENUATION: Integer read _GetGL_LINEAR_ATTENUATION; {class} property GL_LINEAR_MIPMAP_LINEAR: Integer read _GetGL_LINEAR_MIPMAP_LINEAR; {class} property GL_LINEAR_MIPMAP_NEAREST: Integer read _GetGL_LINEAR_MIPMAP_NEAREST; {class} property GL_LINES: Integer read _GetGL_LINES; {class} property GL_LINE_LOOP: Integer read _GetGL_LINE_LOOP; {class} property GL_LINE_SMOOTH: Integer read _GetGL_LINE_SMOOTH; {class} property GL_LINE_SMOOTH_HINT: Integer read _GetGL_LINE_SMOOTH_HINT; {class} property GL_LINE_STRIP: Integer read _GetGL_LINE_STRIP; {class} property GL_LUMINANCE: Integer read _GetGL_LUMINANCE; {class} property GL_LUMINANCE_ALPHA: Integer read _GetGL_LUMINANCE_ALPHA; {class} property GL_MAX_ELEMENTS_INDICES: Integer read _GetGL_MAX_ELEMENTS_INDICES; {class} property GL_MAX_ELEMENTS_VERTICES: Integer read _GetGL_MAX_ELEMENTS_VERTICES; {class} property GL_MAX_LIGHTS: Integer read _GetGL_MAX_LIGHTS; {class} property GL_MAX_MODELVIEW_STACK_DEPTH: Integer read _GetGL_MAX_MODELVIEW_STACK_DEPTH; {class} property GL_MAX_PROJECTION_STACK_DEPTH: Integer read _GetGL_MAX_PROJECTION_STACK_DEPTH; {class} property GL_MAX_TEXTURE_SIZE: Integer read _GetGL_MAX_TEXTURE_SIZE; {class} property GL_MAX_TEXTURE_STACK_DEPTH: Integer read _GetGL_MAX_TEXTURE_STACK_DEPTH; {class} property GL_MAX_TEXTURE_UNITS: Integer read _GetGL_MAX_TEXTURE_UNITS; {class} property GL_MAX_VIEWPORT_DIMS: Integer read _GetGL_MAX_VIEWPORT_DIMS; {class} property GL_MODELVIEW: Integer read _GetGL_MODELVIEW; {class} property GL_MODULATE: Integer read _GetGL_MODULATE; {class} property GL_MULTISAMPLE: Integer read _GetGL_MULTISAMPLE; {class} property GL_NAND: Integer read _GetGL_NAND; {class} property GL_NEAREST: Integer read _GetGL_NEAREST; {class} property GL_NEAREST_MIPMAP_LINEAR: Integer read _GetGL_NEAREST_MIPMAP_LINEAR; {class} property GL_NEAREST_MIPMAP_NEAREST: Integer read _GetGL_NEAREST_MIPMAP_NEAREST; {class} property GL_NEVER: Integer read _GetGL_NEVER; {class} property GL_NICEST: Integer read _GetGL_NICEST; {class} property GL_NOOP: Integer read _GetGL_NOOP; {class} property GL_NOR: Integer read _GetGL_NOR; {class} property GL_NORMALIZE: Integer read _GetGL_NORMALIZE; {class} property GL_NORMAL_ARRAY: Integer read _GetGL_NORMAL_ARRAY; {class} property GL_NOTEQUAL: Integer read _GetGL_NOTEQUAL; {class} property GL_NO_ERROR: Integer read _GetGL_NO_ERROR; {class} property GL_NUM_COMPRESSED_TEXTURE_FORMATS: Integer read _GetGL_NUM_COMPRESSED_TEXTURE_FORMATS; {class} property GL_ONE: Integer read _GetGL_ONE; {class} property GL_ONE_MINUS_DST_ALPHA: Integer read _GetGL_ONE_MINUS_DST_ALPHA; {class} property GL_ONE_MINUS_DST_COLOR: Integer read _GetGL_ONE_MINUS_DST_COLOR; {class} property GL_ONE_MINUS_SRC_ALPHA: Integer read _GetGL_ONE_MINUS_SRC_ALPHA; {class} property GL_ONE_MINUS_SRC_COLOR: Integer read _GetGL_ONE_MINUS_SRC_COLOR; {class} property GL_OR: Integer read _GetGL_OR; {class} property GL_OR_INVERTED: Integer read _GetGL_OR_INVERTED; {class} property GL_OR_REVERSE: Integer read _GetGL_OR_REVERSE; {class} property GL_OUT_OF_MEMORY: Integer read _GetGL_OUT_OF_MEMORY; {class} property GL_PACK_ALIGNMENT: Integer read _GetGL_PACK_ALIGNMENT; {class} property GL_PALETTE4_R5_G6_B5_OES: Integer read _GetGL_PALETTE4_R5_G6_B5_OES; {class} property GL_PALETTE4_RGB5_A1_OES: Integer read _GetGL_PALETTE4_RGB5_A1_OES; {class} property GL_PALETTE4_RGB8_OES: Integer read _GetGL_PALETTE4_RGB8_OES; {class} property GL_PALETTE4_RGBA4_OES: Integer read _GetGL_PALETTE4_RGBA4_OES; {class} property GL_PALETTE4_RGBA8_OES: Integer read _GetGL_PALETTE4_RGBA8_OES; {class} property GL_PALETTE8_R5_G6_B5_OES: Integer read _GetGL_PALETTE8_R5_G6_B5_OES; {class} property GL_PALETTE8_RGB5_A1_OES: Integer read _GetGL_PALETTE8_RGB5_A1_OES; {class} property GL_PALETTE8_RGB8_OES: Integer read _GetGL_PALETTE8_RGB8_OES; {class} property GL_PALETTE8_RGBA4_OES: Integer read _GetGL_PALETTE8_RGBA4_OES; {class} property GL_PALETTE8_RGBA8_OES: Integer read _GetGL_PALETTE8_RGBA8_OES; {class} property GL_PERSPECTIVE_CORRECTION_HINT: Integer read _GetGL_PERSPECTIVE_CORRECTION_HINT; {class} property GL_POINTS: Integer read _GetGL_POINTS; {class} property GL_POINT_FADE_THRESHOLD_SIZE: Integer read _GetGL_POINT_FADE_THRESHOLD_SIZE; {class} property GL_POINT_SIZE: Integer read _GetGL_POINT_SIZE; {class} property GL_POINT_SMOOTH: Integer read _GetGL_POINT_SMOOTH; {class} property GL_POINT_SMOOTH_HINT: Integer read _GetGL_POINT_SMOOTH_HINT; {class} property GL_POLYGON_OFFSET_FILL: Integer read _GetGL_POLYGON_OFFSET_FILL; {class} property GL_POLYGON_SMOOTH_HINT: Integer read _GetGL_POLYGON_SMOOTH_HINT; {class} property GL_POSITION: Integer read _GetGL_POSITION; {class} property GL_PROJECTION: Integer read _GetGL_PROJECTION; {class} property GL_QUADRATIC_ATTENUATION: Integer read _GetGL_QUADRATIC_ATTENUATION; {class} property GL_RED_BITS: Integer read _GetGL_RED_BITS; {class} property GL_RENDERER: Integer read _GetGL_RENDERER; {class} property GL_REPEAT: Integer read _GetGL_REPEAT; {class} property GL_REPLACE: Integer read _GetGL_REPLACE; {class} property GL_RESCALE_NORMAL: Integer read _GetGL_RESCALE_NORMAL; {class} property GL_RGB: Integer read _GetGL_RGB; {class} property GL_RGBA: Integer read _GetGL_RGBA; {class} property GL_SAMPLE_ALPHA_TO_COVERAGE: Integer read _GetGL_SAMPLE_ALPHA_TO_COVERAGE; {class} property GL_SAMPLE_ALPHA_TO_ONE: Integer read _GetGL_SAMPLE_ALPHA_TO_ONE; {class} property GL_SAMPLE_COVERAGE: Integer read _GetGL_SAMPLE_COVERAGE; {class} property GL_SCISSOR_TEST: Integer read _GetGL_SCISSOR_TEST; {class} property GL_SET: Integer read _GetGL_SET; {class} property GL_SHININESS: Integer read _GetGL_SHININESS; {class} property GL_SHORT: Integer read _GetGL_SHORT; {class} property GL_SMOOTH: Integer read _GetGL_SMOOTH; {class} property GL_SMOOTH_LINE_WIDTH_RANGE: Integer read _GetGL_SMOOTH_LINE_WIDTH_RANGE; {class} property GL_SMOOTH_POINT_SIZE_RANGE: Integer read _GetGL_SMOOTH_POINT_SIZE_RANGE; {class} property GL_SPECULAR: Integer read _GetGL_SPECULAR; {class} property GL_SPOT_CUTOFF: Integer read _GetGL_SPOT_CUTOFF; {class} property GL_SPOT_DIRECTION: Integer read _GetGL_SPOT_DIRECTION; {class} property GL_SPOT_EXPONENT: Integer read _GetGL_SPOT_EXPONENT; {class} property GL_SRC_ALPHA: Integer read _GetGL_SRC_ALPHA; {class} property GL_SRC_ALPHA_SATURATE: Integer read _GetGL_SRC_ALPHA_SATURATE; {class} property GL_SRC_COLOR: Integer read _GetGL_SRC_COLOR; {class} property GL_STACK_OVERFLOW: Integer read _GetGL_STACK_OVERFLOW; {class} property GL_STACK_UNDERFLOW: Integer read _GetGL_STACK_UNDERFLOW; {class} property GL_STENCIL_BITS: Integer read _GetGL_STENCIL_BITS; {class} property GL_STENCIL_BUFFER_BIT: Integer read _GetGL_STENCIL_BUFFER_BIT; {class} property GL_STENCIL_TEST: Integer read _GetGL_STENCIL_TEST; {class} property GL_SUBPIXEL_BITS: Integer read _GetGL_SUBPIXEL_BITS; {class} property GL_TEXTURE: Integer read _GetGL_TEXTURE; {class} property GL_TEXTURE0: Integer read _GetGL_TEXTURE0; {class} property GL_TEXTURE1: Integer read _GetGL_TEXTURE1; {class} property GL_TEXTURE10: Integer read _GetGL_TEXTURE10; {class} property GL_TEXTURE11: Integer read _GetGL_TEXTURE11; {class} property GL_TEXTURE12: Integer read _GetGL_TEXTURE12; {class} property GL_TEXTURE13: Integer read _GetGL_TEXTURE13; {class} property GL_TEXTURE14: Integer read _GetGL_TEXTURE14; {class} property GL_TEXTURE15: Integer read _GetGL_TEXTURE15; {class} property GL_TEXTURE16: Integer read _GetGL_TEXTURE16; {class} property GL_TEXTURE17: Integer read _GetGL_TEXTURE17; {class} property GL_TEXTURE18: Integer read _GetGL_TEXTURE18; {class} property GL_TEXTURE19: Integer read _GetGL_TEXTURE19; {class} property GL_TEXTURE2: Integer read _GetGL_TEXTURE2; {class} property GL_TEXTURE20: Integer read _GetGL_TEXTURE20; {class} property GL_TEXTURE21: Integer read _GetGL_TEXTURE21; {class} property GL_TEXTURE22: Integer read _GetGL_TEXTURE22; {class} property GL_TEXTURE23: Integer read _GetGL_TEXTURE23; {class} property GL_TEXTURE24: Integer read _GetGL_TEXTURE24; {class} property GL_TEXTURE25: Integer read _GetGL_TEXTURE25; {class} property GL_TEXTURE26: Integer read _GetGL_TEXTURE26; {class} property GL_TEXTURE27: Integer read _GetGL_TEXTURE27; {class} property GL_TEXTURE28: Integer read _GetGL_TEXTURE28; {class} property GL_TEXTURE29: Integer read _GetGL_TEXTURE29; {class} property GL_TEXTURE3: Integer read _GetGL_TEXTURE3; {class} property GL_TEXTURE30: Integer read _GetGL_TEXTURE30; {class} property GL_TEXTURE31: Integer read _GetGL_TEXTURE31; {class} property GL_TEXTURE4: Integer read _GetGL_TEXTURE4; {class} property GL_TEXTURE5: Integer read _GetGL_TEXTURE5; {class} property GL_TEXTURE6: Integer read _GetGL_TEXTURE6; {class} property GL_TEXTURE7: Integer read _GetGL_TEXTURE7; {class} property GL_TEXTURE8: Integer read _GetGL_TEXTURE8; {class} property GL_TEXTURE9: Integer read _GetGL_TEXTURE9; {class} property GL_TEXTURE_2D: Integer read _GetGL_TEXTURE_2D; {class} property GL_TEXTURE_COORD_ARRAY: Integer read _GetGL_TEXTURE_COORD_ARRAY; {class} property GL_TEXTURE_ENV: Integer read _GetGL_TEXTURE_ENV; {class} property GL_TEXTURE_ENV_COLOR: Integer read _GetGL_TEXTURE_ENV_COLOR; {class} property GL_TEXTURE_ENV_MODE: Integer read _GetGL_TEXTURE_ENV_MODE; {class} property GL_TEXTURE_MAG_FILTER: Integer read _GetGL_TEXTURE_MAG_FILTER; {class} property GL_TEXTURE_MIN_FILTER: Integer read _GetGL_TEXTURE_MIN_FILTER; {class} property GL_TEXTURE_WRAP_S: Integer read _GetGL_TEXTURE_WRAP_S; {class} property GL_TEXTURE_WRAP_T: Integer read _GetGL_TEXTURE_WRAP_T; {class} property GL_TRIANGLES: Integer read _GetGL_TRIANGLES; {class} property GL_TRIANGLE_FAN: Integer read _GetGL_TRIANGLE_FAN; {class} property GL_TRIANGLE_STRIP: Integer read _GetGL_TRIANGLE_STRIP; {class} property GL_TRUE: Integer read _GetGL_TRUE; {class} property GL_UNPACK_ALIGNMENT: Integer read _GetGL_UNPACK_ALIGNMENT; {class} property GL_UNSIGNED_BYTE: Integer read _GetGL_UNSIGNED_BYTE; {class} property GL_UNSIGNED_SHORT: Integer read _GetGL_UNSIGNED_SHORT; {class} property GL_UNSIGNED_SHORT_4_4_4_4: Integer read _GetGL_UNSIGNED_SHORT_4_4_4_4; {class} property GL_UNSIGNED_SHORT_5_5_5_1: Integer read _GetGL_UNSIGNED_SHORT_5_5_5_1; {class} property GL_UNSIGNED_SHORT_5_6_5: Integer read _GetGL_UNSIGNED_SHORT_5_6_5; {class} property GL_VENDOR: Integer read _GetGL_VENDOR; {class} property GL_VERSION: Integer read _GetGL_VERSION; {class} property GL_VERTEX_ARRAY: Integer read _GetGL_VERTEX_ARRAY; {class} property GL_XOR: Integer read _GetGL_XOR; {class} property GL_ZERO: Integer read _GetGL_ZERO; end; [JavaSignature('javax/microedition/khronos/opengles/GL10')] JGL10 = interface(JGL) ['{4F032613-C505-4409-A116-09343E69472F}'] procedure glActiveTexture(texture: Integer); cdecl; procedure glAlphaFunc(func: Integer; ref: Single); cdecl; procedure glAlphaFuncx(func: Integer; ref: Integer); cdecl; procedure glBindTexture(target: Integer; texture: Integer); cdecl; procedure glBlendFunc(sfactor: Integer; dfactor: Integer); cdecl; procedure glClear(mask: Integer); cdecl; procedure glClearColor(red: Single; green: Single; blue: Single; alpha: Single); cdecl; procedure glClearColorx(red: Integer; green: Integer; blue: Integer; alpha: Integer); cdecl; procedure glClearDepthf(depth: Single); cdecl; procedure glClearDepthx(depth: Integer); cdecl; procedure glClearStencil(s: Integer); cdecl; procedure glClientActiveTexture(texture: Integer); cdecl; procedure glColor4f(red: Single; green: Single; blue: Single; alpha: Single); cdecl; procedure glColor4x(red: Integer; green: Integer; blue: Integer; alpha: Integer); cdecl; procedure glColorMask(red: Boolean; green: Boolean; blue: Boolean; alpha: Boolean); cdecl; procedure glColorPointer(size: Integer; type_: Integer; stride: Integer; pointer: JBuffer); cdecl; procedure glCompressedTexImage2D(target: Integer; level: Integer; internalformat: Integer; width: Integer; height: Integer; border: Integer; imageSize: Integer; data: JBuffer); cdecl; procedure glCompressedTexSubImage2D(target: Integer; level: Integer; xoffset: Integer; yoffset: Integer; width: Integer; height: Integer; format: Integer; imageSize: Integer; data: JBuffer); cdecl; procedure glCopyTexImage2D(target: Integer; level: Integer; internalformat: Integer; x: Integer; y: Integer; width: Integer; height: Integer; border: Integer); cdecl; procedure glCopyTexSubImage2D(target: Integer; level: Integer; xoffset: Integer; yoffset: Integer; x: Integer; y: Integer; width: Integer; height: Integer); cdecl; procedure glCullFace(mode: Integer); cdecl; procedure glDeleteTextures(n: Integer; textures: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glDeleteTextures(n: Integer; textures: JIntBuffer); cdecl; overload; procedure glDepthFunc(func: Integer); cdecl; procedure glDepthMask(flag: Boolean); cdecl; procedure glDepthRangef(zNear: Single; zFar: Single); cdecl; procedure glDepthRangex(zNear: Integer; zFar: Integer); cdecl; procedure glDisable(cap: Integer); cdecl; procedure glDisableClientState(array_: Integer); cdecl; procedure glDrawArrays(mode: Integer; first: Integer; count: Integer); cdecl; procedure glDrawElements(mode: Integer; count: Integer; type_: Integer; indices: JBuffer); cdecl; procedure glEnable(cap: Integer); cdecl; procedure glEnableClientState(array_: Integer); cdecl; procedure glFinish; cdecl; procedure glFlush; cdecl; procedure glFogf(pname: Integer; param: Single); cdecl; procedure glFogfv(pname: Integer; params: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glFogfv(pname: Integer; params: JFloatBuffer); cdecl; overload; procedure glFogx(pname: Integer; param: Integer); cdecl; procedure glFogxv(pname: Integer; params: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glFogxv(pname: Integer; params: JIntBuffer); cdecl; overload; procedure glFrontFace(mode: Integer); cdecl; procedure glFrustumf(left: Single; right: Single; bottom: Single; top: Single; zNear: Single; zFar: Single); cdecl; procedure glFrustumx(left: Integer; right: Integer; bottom: Integer; top: Integer; zNear: Integer; zFar: Integer); cdecl; procedure glGenTextures(n: Integer; textures: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glGenTextures(n: Integer; textures: JIntBuffer); cdecl; overload; function glGetError: Integer; cdecl; procedure glGetIntegerv(pname: Integer; params: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glGetIntegerv(pname: Integer; params: JIntBuffer); cdecl; overload; function glGetString(name: Integer): JString; cdecl; procedure glHint(target: Integer; mode: Integer); cdecl; procedure glLightModelf(pname: Integer; param: Single); cdecl; procedure glLightModelfv(pname: Integer; params: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glLightModelfv(pname: Integer; params: JFloatBuffer); cdecl; overload; procedure glLightModelx(pname: Integer; param: Integer); cdecl; procedure glLightModelxv(pname: Integer; params: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glLightModelxv(pname: Integer; params: JIntBuffer); cdecl; overload; procedure glLightf(light: Integer; pname: Integer; param: Single); cdecl; procedure glLightfv(light: Integer; pname: Integer; params: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glLightfv(light: Integer; pname: Integer; params: JFloatBuffer); cdecl; overload; procedure glLightx(light: Integer; pname: Integer; param: Integer); cdecl; procedure glLightxv(light: Integer; pname: Integer; params: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glLightxv(light: Integer; pname: Integer; params: JIntBuffer); cdecl; overload; procedure glLineWidth(width: Single); cdecl; procedure glLineWidthx(width: Integer); cdecl; procedure glLoadIdentity; cdecl; procedure glLoadMatrixf(m: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glLoadMatrixf(m: JFloatBuffer); cdecl; overload; procedure glLoadMatrixx(m: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glLoadMatrixx(m: JIntBuffer); cdecl; overload; procedure glLogicOp(opcode: Integer); cdecl; procedure glMaterialf(face: Integer; pname: Integer; param: Single); cdecl; procedure glMaterialfv(face: Integer; pname: Integer; params: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glMaterialfv(face: Integer; pname: Integer; params: JFloatBuffer); cdecl; overload; procedure glMaterialx(face: Integer; pname: Integer; param: Integer); cdecl; procedure glMaterialxv(face: Integer; pname: Integer; params: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glMaterialxv(face: Integer; pname: Integer; params: JIntBuffer); cdecl; overload; procedure glMatrixMode(mode: Integer); cdecl; procedure glMultMatrixf(m: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glMultMatrixf(m: JFloatBuffer); cdecl; overload; procedure glMultMatrixx(m: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glMultMatrixx(m: JIntBuffer); cdecl; overload; procedure glMultiTexCoord4f(target: Integer; s: Single; t: Single; r: Single; q: Single); cdecl; procedure glMultiTexCoord4x(target: Integer; s: Integer; t: Integer; r: Integer; q: Integer); cdecl; procedure glNormal3f(nx: Single; ny: Single; nz: Single); cdecl; procedure glNormal3x(nx: Integer; ny: Integer; nz: Integer); cdecl; procedure glNormalPointer(type_: Integer; stride: Integer; pointer: JBuffer); cdecl; procedure glOrthof(left: Single; right: Single; bottom: Single; top: Single; zNear: Single; zFar: Single); cdecl; procedure glOrthox(left: Integer; right: Integer; bottom: Integer; top: Integer; zNear: Integer; zFar: Integer); cdecl; procedure glPixelStorei(pname: Integer; param: Integer); cdecl; procedure glPointSize(size: Single); cdecl; procedure glPointSizex(size: Integer); cdecl; procedure glPolygonOffset(factor: Single; units: Single); cdecl; procedure glPolygonOffsetx(factor: Integer; units: Integer); cdecl; procedure glPopMatrix; cdecl; procedure glPushMatrix; cdecl; procedure glReadPixels(x: Integer; y: Integer; width: Integer; height: Integer; format: Integer; type_: Integer; pixels: JBuffer); cdecl; procedure glRotatef(angle: Single; x: Single; y: Single; z: Single); cdecl; procedure glRotatex(angle: Integer; x: Integer; y: Integer; z: Integer); cdecl; procedure glSampleCoverage(value: Single; invert: Boolean); cdecl; procedure glSampleCoveragex(value: Integer; invert: Boolean); cdecl; procedure glScalef(x: Single; y: Single; z: Single); cdecl; procedure glScalex(x: Integer; y: Integer; z: Integer); cdecl; procedure glScissor(x: Integer; y: Integer; width: Integer; height: Integer); cdecl; procedure glShadeModel(mode: Integer); cdecl; procedure glStencilFunc(func: Integer; ref: Integer; mask: Integer); cdecl; procedure glStencilMask(mask: Integer); cdecl; procedure glStencilOp(fail: Integer; zfail: Integer; zpass: Integer); cdecl; procedure glTexCoordPointer(size: Integer; type_: Integer; stride: Integer; pointer: JBuffer); cdecl; procedure glTexEnvf(target: Integer; pname: Integer; param: Single); cdecl; procedure glTexEnvfv(target: Integer; pname: Integer; params: TJavaArray<Single>; offset: Integer); cdecl; overload; procedure glTexEnvfv(target: Integer; pname: Integer; params: JFloatBuffer); cdecl; overload; procedure glTexEnvx(target: Integer; pname: Integer; param: Integer); cdecl; procedure glTexEnvxv(target: Integer; pname: Integer; params: TJavaArray<Integer>; offset: Integer); cdecl; overload; procedure glTexEnvxv(target: Integer; pname: Integer; params: JIntBuffer); cdecl; overload; procedure glTexImage2D(target: Integer; level: Integer; internalformat: Integer; width: Integer; height: Integer; border: Integer; format: Integer; type_: Integer; pixels: JBuffer); cdecl; procedure glTexParameterf(target: Integer; pname: Integer; param: Single); cdecl; procedure glTexParameterx(target: Integer; pname: Integer; param: Integer); cdecl; procedure glTexSubImage2D(target: Integer; level: Integer; xoffset: Integer; yoffset: Integer; width: Integer; height: Integer; format: Integer; type_: Integer; pixels: JBuffer); cdecl; procedure glTranslatef(x: Single; y: Single; z: Single); cdecl; procedure glTranslatex(x: Integer; y: Integer; z: Integer); cdecl; procedure glVertexPointer(size: Integer; type_: Integer; stride: Integer; pointer: JBuffer); cdecl; procedure glViewport(x: Integer; y: Integer; width: Integer; height: Integer); cdecl; end; TJGL10 = class(TJavaGenericImport<JGL10Class, JGL10>) end; JJSONArrayClass = interface(JObjectClass) ['{34FBA399-2B13-49B4-BD53-5BDFE4653285}'] {class} function init: JJSONArray; cdecl; overload; {class} function init(copyFrom: JCollection): JJSONArray; cdecl; overload; {class} function init(readFrom: JJSONTokener): JJSONArray; cdecl; overload; {class} function init(json: JString): JJSONArray; cdecl; overload; {class} function init(array_: JObject): JJSONArray; cdecl; overload; end; [JavaSignature('org/json/JSONArray')] JJSONArray = interface(JObject) ['{34738D80-ED10-413D-9467-36A3785DBFF4}'] function equals(o: JObject): Boolean; cdecl; function &get(index: Integer): JObject; cdecl; function getBoolean(index: Integer): Boolean; cdecl; function getDouble(index: Integer): Double; cdecl; function getInt(index: Integer): Integer; cdecl; function getJSONArray(index: Integer): JJSONArray; cdecl; function getJSONObject(index: Integer): JJSONObject; cdecl; function getLong(index: Integer): Int64; cdecl; function getString(index: Integer): JString; cdecl; function hashCode: Integer; cdecl; function isNull(index: Integer): Boolean; cdecl; function join(separator: JString): JString; cdecl; function length: Integer; cdecl; function opt(index: Integer): JObject; cdecl; function optBoolean(index: Integer): Boolean; cdecl; overload; function optBoolean(index: Integer; fallback: Boolean): Boolean; cdecl; overload; function optDouble(index: Integer): Double; cdecl; overload; function optDouble(index: Integer; fallback: Double): Double; cdecl; overload; function optInt(index: Integer): Integer; cdecl; overload; function optInt(index: Integer; fallback: Integer): Integer; cdecl; overload; function optJSONArray(index: Integer): JJSONArray; cdecl; function optJSONObject(index: Integer): JJSONObject; cdecl; function optLong(index: Integer): Int64; cdecl; overload; function optLong(index: Integer; fallback: Int64): Int64; cdecl; overload; function optString(index: Integer): JString; cdecl; overload; function optString(index: Integer; fallback: JString): JString; cdecl; overload; function put(value: Boolean): JJSONArray; cdecl; overload; function put(value: Double): JJSONArray; cdecl; overload; function put(value: Integer): JJSONArray; cdecl; overload; function put(value: Int64): JJSONArray; cdecl; overload; function put(value: JObject): JJSONArray; cdecl; overload; function put(index: Integer; value: Boolean): JJSONArray; cdecl; overload; function put(index: Integer; value: Double): JJSONArray; cdecl; overload; function put(index: Integer; value: Integer): JJSONArray; cdecl; overload; function put(index: Integer; value: Int64): JJSONArray; cdecl; overload; function put(index: Integer; value: JObject): JJSONArray; cdecl; overload; function remove(index: Integer): JObject; cdecl; function toJSONObject(names: JJSONArray): JJSONObject; cdecl; function toString: JString; cdecl; overload; function toString(indentSpaces: Integer): JString; cdecl; overload; end; TJJSONArray = class(TJavaGenericImport<JJSONArrayClass, JJSONArray>) end; JJSONExceptionClass = interface(JExceptionClass) ['{D92F06D5-D459-4309-AE86-21A7EF971C64}'] {class} function init(s: JString): JJSONException; cdecl; end; [JavaSignature('org/json/JSONException')] JJSONException = interface(JException) ['{236AB196-CC66-40D5-91E5-C3D202A9293C}'] end; TJJSONException = class(TJavaGenericImport<JJSONExceptionClass, JJSONException>) end; JJSONObjectClass = interface(JObjectClass) ['{32FBF926-19C3-45AF-A29E-C312D95B34CC}'] {class} function _GetNULL: JObject; cdecl; {class} function init: JJSONObject; cdecl; overload; {class} function init(copyFrom: JMap): JJSONObject; cdecl; overload; {class} function init(readFrom: JJSONTokener): JJSONObject; cdecl; overload; {class} function init(json: JString): JJSONObject; cdecl; overload; {class} function init(copyFrom: JJSONObject; names: TJavaObjectArray<JString>): JJSONObject; cdecl; overload; {class} function numberToString(number: JNumber): JString; cdecl; {class} function quote(data: JString): JString; cdecl; {class} function wrap(o: JObject): JObject; cdecl; {class} end; [JavaSignature('org/json/JSONObject')] JJSONObject = interface(JObject) ['{7B4F68E8-ADFC-40EC-A119-37FA9778A11C}'] function accumulate(name: JString; value: JObject): JJSONObject; cdecl; function &get(name: JString): JObject; cdecl; function getBoolean(name: JString): Boolean; cdecl; function getDouble(name: JString): Double; cdecl; function getInt(name: JString): Integer; cdecl; function getJSONArray(name: JString): JJSONArray; cdecl; function getJSONObject(name: JString): JJSONObject; cdecl; function getLong(name: JString): Int64; cdecl; function getString(name: JString): JString; cdecl; function has(name: JString): Boolean; cdecl; function isNull(name: JString): Boolean; cdecl; function keys: JIterator; cdecl; function length: Integer; cdecl; function names: JJSONArray; cdecl; function opt(name: JString): JObject; cdecl; function optBoolean(name: JString): Boolean; cdecl; overload; function optBoolean(name: JString; fallback: Boolean): Boolean; cdecl; overload; function optDouble(name: JString): Double; cdecl; overload; function optDouble(name: JString; fallback: Double): Double; cdecl; overload; function optInt(name: JString): Integer; cdecl; overload; function optInt(name: JString; fallback: Integer): Integer; cdecl; overload; function optJSONArray(name: JString): JJSONArray; cdecl; function optJSONObject(name: JString): JJSONObject; cdecl; function optLong(name: JString): Int64; cdecl; overload; function optLong(name: JString; fallback: Int64): Int64; cdecl; overload; function optString(name: JString): JString; cdecl; overload; function optString(name: JString; fallback: JString): JString; cdecl; overload; function put(name: JString; value: Boolean): JJSONObject; cdecl; overload; function put(name: JString; value: Double): JJSONObject; cdecl; overload; function put(name: JString; value: Integer): JJSONObject; cdecl; overload; function put(name: JString; value: Int64): JJSONObject; cdecl; overload; function put(name: JString; value: JObject): JJSONObject; cdecl; overload; function putOpt(name: JString; value: JObject): JJSONObject; cdecl; function remove(name: JString): JObject; cdecl; function toJSONArray(names: JJSONArray): JJSONArray; cdecl; function toString: JString; cdecl; overload; function toString(indentSpaces: Integer): JString; cdecl; overload; end; TJJSONObject = class(TJavaGenericImport<JJSONObjectClass, JJSONObject>) end; JJSONTokenerClass = interface(JObjectClass) ['{CFDB19D3-6222-4DBF-9012-1EF6EA1D518D}'] {class} function init(in_: JString): JJSONTokener; cdecl; {class} function dehexchar(hex: Char): Integer; cdecl; end; [JavaSignature('org/json/JSONTokener')] JJSONTokener = interface(JObject) ['{A7330D36-4304-4864-BACD-547E8AF8AAAD}'] procedure back; cdecl; function more: Boolean; cdecl; function next: Char; cdecl; overload; function next(c: Char): Char; cdecl; overload; function next(length: Integer): JString; cdecl; overload; function nextClean: Char; cdecl; function nextString(quote: Char): JString; cdecl; function nextTo(excluded: JString): JString; cdecl; overload; function nextTo(excluded: Char): JString; cdecl; overload; function nextValue: JObject; cdecl; procedure skipPast(thru: JString); cdecl; function skipTo(to_: Char): Char; cdecl; function syntaxError(message: JString): JJSONException; cdecl; function toString: JString; cdecl; end; TJJSONTokener = class(TJavaGenericImport<JJSONTokenerClass, JJSONTokener>) end; JXmlPullParserClass = interface(IJavaClass) ['{932020CD-42E1-42D5-A33D-5190366B7EE1}'] {class} function _GetCDSECT: Integer; cdecl; {class} function _GetCOMMENT: Integer; cdecl; {class} function _GetDOCDECL: Integer; cdecl; {class} function _GetEND_DOCUMENT: Integer; cdecl; {class} function _GetEND_TAG: Integer; cdecl; {class} function _GetENTITY_REF: Integer; cdecl; {class} function _GetFEATURE_PROCESS_DOCDECL: JString; cdecl; {class} function _GetFEATURE_PROCESS_NAMESPACES: JString; cdecl; {class} function _GetFEATURE_REPORT_NAMESPACE_ATTRIBUTES: JString; cdecl; {class} function _GetFEATURE_VALIDATION: JString; cdecl; {class} function _GetIGNORABLE_WHITESPACE: Integer; cdecl; {class} function _GetNO_NAMESPACE: JString; cdecl; {class} function _GetPROCESSING_INSTRUCTION: Integer; cdecl; {class} function _GetSTART_DOCUMENT: Integer; cdecl; {class} function _GetSTART_TAG: Integer; cdecl; {class} function _GetTEXT: Integer; cdecl; {class} function _GetTYPES: TJavaObjectArray<JString>; cdecl; {class} property CDSECT: Integer read _GetCDSECT; {class} property COMMENT: Integer read _GetCOMMENT; {class} property DOCDECL: Integer read _GetDOCDECL; {class} property END_DOCUMENT: Integer read _GetEND_DOCUMENT; {class} property END_TAG: Integer read _GetEND_TAG; {class} property ENTITY_REF: Integer read _GetENTITY_REF; {class} property FEATURE_PROCESS_DOCDECL: JString read _GetFEATURE_PROCESS_DOCDECL; {class} property FEATURE_PROCESS_NAMESPACES: JString read _GetFEATURE_PROCESS_NAMESPACES; {class} property FEATURE_REPORT_NAMESPACE_ATTRIBUTES: JString read _GetFEATURE_REPORT_NAMESPACE_ATTRIBUTES; {class} property FEATURE_VALIDATION: JString read _GetFEATURE_VALIDATION; {class} property IGNORABLE_WHITESPACE: Integer read _GetIGNORABLE_WHITESPACE; {class} property NO_NAMESPACE: JString read _GetNO_NAMESPACE; {class} property PROCESSING_INSTRUCTION: Integer read _GetPROCESSING_INSTRUCTION; {class} property START_DOCUMENT: Integer read _GetSTART_DOCUMENT; {class} property START_TAG: Integer read _GetSTART_TAG; {class} property TEXT: Integer read _GetTEXT; {class} property TYPES: TJavaObjectArray<JString> read _GetTYPES; end; [JavaSignature('org/xmlpull/v1/XmlPullParser')] JXmlPullParser = interface(IJavaInstance) ['{047BC31A-D436-4663-A1F8-E304CC9B5CFE}'] procedure defineEntityReplacementText(entityName: JString; replacementText: JString); cdecl; function getAttributeCount: Integer; cdecl; function getAttributeName(index: Integer): JString; cdecl; function getAttributeNamespace(index: Integer): JString; cdecl; function getAttributePrefix(index: Integer): JString; cdecl; function getAttributeType(index: Integer): JString; cdecl; function getAttributeValue(index: Integer): JString; cdecl; overload; function getAttributeValue(namespace: JString; name: JString): JString; cdecl; overload; function getColumnNumber: Integer; cdecl; function getDepth: Integer; cdecl; function getEventType: Integer; cdecl; function getFeature(name: JString): Boolean; cdecl; function getInputEncoding: JString; cdecl; function getLineNumber: Integer; cdecl; function getName: JString; cdecl; function getNamespace(prefix: JString): JString; cdecl; overload; function getNamespace: JString; cdecl; overload; function getNamespaceCount(depth: Integer): Integer; cdecl; function getNamespacePrefix(pos: Integer): JString; cdecl; function getNamespaceUri(pos: Integer): JString; cdecl; function getPositionDescription: JString; cdecl; function getPrefix: JString; cdecl; function getProperty(name: JString): JObject; cdecl; function getText: JString; cdecl; function getTextCharacters(holderForStartAndLength: TJavaArray<Integer>): TJavaArray<Char>; cdecl; function isAttributeDefault(index: Integer): Boolean; cdecl; function isEmptyElementTag: Boolean; cdecl; function isWhitespace: Boolean; cdecl; function next: Integer; cdecl; function nextTag: Integer; cdecl; function nextText: JString; cdecl; function nextToken: Integer; cdecl; procedure require(type_: Integer; namespace: JString; name: JString); cdecl; procedure setFeature(name: JString; state: Boolean); cdecl; procedure setInput(in_: JReader); cdecl; overload; procedure setInput(inputStream: JInputStream; inputEncoding: JString); cdecl; overload; procedure setProperty(name: JString; value: JObject); cdecl; end; TJXmlPullParser = class(TJavaGenericImport<JXmlPullParserClass, JXmlPullParser>) end; JXmlSerializerClass = interface(IJavaClass) ['{358A6AC9-1AF2-497F-BFBE-CF975CCAAF07}'] end; [JavaSignature('org/xmlpull/v1/XmlSerializer')] JXmlSerializer = interface(IJavaInstance) ['{A16E0414-9A1D-499F-839F-E89BDA70DFB5}'] function attribute(namespace: JString; name: JString; value: JString): JXmlSerializer; cdecl; procedure cdsect(text: JString); cdecl; procedure comment(text: JString); cdecl; procedure docdecl(text: JString); cdecl; procedure endDocument; cdecl; function endTag(namespace: JString; name: JString): JXmlSerializer; cdecl; procedure entityRef(text: JString); cdecl; procedure flush; cdecl; function getDepth: Integer; cdecl; function getFeature(name: JString): Boolean; cdecl; function getName: JString; cdecl; function getNamespace: JString; cdecl; function getPrefix(namespace: JString; generatePrefix: Boolean): JString; cdecl; function getProperty(name: JString): JObject; cdecl; procedure ignorableWhitespace(text: JString); cdecl; procedure processingInstruction(text: JString); cdecl; procedure setFeature(name: JString; state: Boolean); cdecl; procedure setOutput(os: JOutputStream; encoding: JString); cdecl; overload; procedure setOutput(writer: JWriter); cdecl; overload; procedure setPrefix(prefix: JString; namespace: JString); cdecl; procedure setProperty(name: JString; value: JObject); cdecl; procedure startDocument(encoding: JString; standalone: JBoolean); cdecl; function startTag(namespace: JString; name: JString): JXmlSerializer; cdecl; function text(text: JString): JXmlSerializer; cdecl; overload; function text(buf: TJavaArray<Char>; start: Integer; len: Integer): JXmlSerializer; cdecl; overload; end; TJXmlSerializer = class(TJavaGenericImport<JXmlSerializerClass, JXmlSerializer>) end; implementation procedure RegisterTypes; begin TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JObject', TypeInfo(Androidapi.JNI.JavaTypes.JObject)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JInputStream', TypeInfo(Androidapi.JNI.JavaTypes.JInputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JByteArrayInputStream', TypeInfo(Androidapi.JNI.JavaTypes.JByteArrayInputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JOutputStream', TypeInfo(Androidapi.JNI.JavaTypes.JOutputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JByteArrayOutputStream', TypeInfo(Androidapi.JNI.JavaTypes.JByteArrayOutputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAutoCloseable', TypeInfo(Androidapi.JNI.JavaTypes.JAutoCloseable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCloseable', TypeInfo(Androidapi.JNI.JavaTypes.JCloseable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFile', TypeInfo(Androidapi.JNI.JavaTypes.JFile)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileDescriptor', TypeInfo(Androidapi.JNI.JavaTypes.JFileDescriptor)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileFilter', TypeInfo(Androidapi.JNI.JavaTypes.JFileFilter)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileInputStream', TypeInfo(Androidapi.JNI.JavaTypes.JFileInputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileOutputStream', TypeInfo(Androidapi.JNI.JavaTypes.JFileOutputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFilenameFilter', TypeInfo(Androidapi.JNI.JavaTypes.JFilenameFilter)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFilterOutputStream', TypeInfo(Androidapi.JNI.JavaTypes.JFilterOutputStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JThrowable', TypeInfo(Androidapi.JNI.JavaTypes.JThrowable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JException', TypeInfo(Androidapi.JNI.JavaTypes.JException)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JIOException', TypeInfo(Androidapi.JNI.JavaTypes.JIOException)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JPrintStream', TypeInfo(Androidapi.JNI.JavaTypes.JPrintStream)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JWriter', TypeInfo(Androidapi.JNI.JavaTypes.JWriter)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JPrintWriter', TypeInfo(Androidapi.JNI.JavaTypes.JPrintWriter)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JRandomAccessFile', TypeInfo(Androidapi.JNI.JavaTypes.JRandomAccessFile)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JReader', TypeInfo(Androidapi.JNI.JavaTypes.JReader)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSerializable', TypeInfo(Androidapi.JNI.JavaTypes.JSerializable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractStringBuilder', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractStringBuilder)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JBoolean', TypeInfo(Androidapi.JNI.JavaTypes.JBoolean)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JNumber', TypeInfo(Androidapi.JNI.JavaTypes.JNumber)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JByte', TypeInfo(Androidapi.JNI.JavaTypes.JByte)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCharSequence', TypeInfo(Androidapi.JNI.JavaTypes.JCharSequence)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.Jlang_Class', TypeInfo(Androidapi.JNI.JavaTypes.Jlang_Class)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JClassLoader', TypeInfo(Androidapi.JNI.JavaTypes.JClassLoader)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JComparable', TypeInfo(Androidapi.JNI.JavaTypes.JComparable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JDouble', TypeInfo(Androidapi.JNI.JavaTypes.JDouble)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEnum', TypeInfo(Androidapi.JNI.JavaTypes.JEnum)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFloat', TypeInfo(Androidapi.JNI.JavaTypes.JFloat)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JRuntimeException', TypeInfo(Androidapi.JNI.JavaTypes.JRuntimeException)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JIllegalStateException', TypeInfo(Androidapi.JNI.JavaTypes.JIllegalStateException)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JInteger', TypeInfo(Androidapi.JNI.JavaTypes.JInteger)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JIterable', TypeInfo(Androidapi.JNI.JavaTypes.JIterable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JLong', TypeInfo(Androidapi.JNI.JavaTypes.JLong)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JPackage', TypeInfo(Androidapi.JNI.JavaTypes.JPackage)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JRunnable', TypeInfo(Androidapi.JNI.JavaTypes.JRunnable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JShort', TypeInfo(Androidapi.JNI.JavaTypes.JShort)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JStackTraceElement', TypeInfo(Androidapi.JNI.JavaTypes.JStackTraceElement)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JString', TypeInfo(Androidapi.JNI.JavaTypes.JString)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JStringBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JStringBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JStringBuilder', TypeInfo(Androidapi.JNI.JavaTypes.JStringBuilder)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JThread', TypeInfo(Androidapi.JNI.JavaTypes.JThread)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JThread_State', TypeInfo(Androidapi.JNI.JavaTypes.JThread_State)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JThread_UncaughtExceptionHandler', TypeInfo(Androidapi.JNI.JavaTypes.JThread_UncaughtExceptionHandler)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JThreadGroup', TypeInfo(Androidapi.JNI.JavaTypes.JThreadGroup)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAnnotation', TypeInfo(Androidapi.JNI.JavaTypes.JAnnotation)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAccessibleObject', TypeInfo(Androidapi.JNI.JavaTypes.JAccessibleObject)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JConstructor', TypeInfo(Androidapi.JNI.JavaTypes.JConstructor)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JField', TypeInfo(Androidapi.JNI.JavaTypes.JField)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JGenericDeclaration', TypeInfo(Androidapi.JNI.JavaTypes.JGenericDeclaration)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JMethod', TypeInfo(Androidapi.JNI.JavaTypes.JMethod)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.Jreflect_Type', TypeInfo(Androidapi.JNI.JavaTypes.Jreflect_Type)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JTypeVariable', TypeInfo(Androidapi.JNI.JavaTypes.JTypeVariable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JBigInteger', TypeInfo(Androidapi.JNI.JavaTypes.JBigInteger)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JByteBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JByteBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JByteOrder', TypeInfo(Androidapi.JNI.JavaTypes.JByteOrder)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCharBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JCharBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JDoubleBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JDoubleBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFloatBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JFloatBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JIntBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JIntBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JLongBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JLongBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JMappedByteBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JMappedByteBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JShortBuffer', TypeInfo(Androidapi.JNI.JavaTypes.JShortBuffer)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JChannel', TypeInfo(Androidapi.JNI.JavaTypes.JChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractInterruptibleChannel', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractInterruptibleChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSelectableChannel', TypeInfo(Androidapi.JNI.JavaTypes.JSelectableChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractSelectableChannel', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractSelectableChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JDatagramChannel', TypeInfo(Androidapi.JNI.JavaTypes.JDatagramChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileChannel', TypeInfo(Androidapi.JNI.JavaTypes.JFileChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileChannel_MapMode', TypeInfo(Androidapi.JNI.JavaTypes.JFileChannel_MapMode)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFileLock', TypeInfo(Androidapi.JNI.JavaTypes.JFileLock)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JPipe', TypeInfo(Androidapi.JNI.JavaTypes.JPipe)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JPipe_SinkChannel', TypeInfo(Androidapi.JNI.JavaTypes.JPipe_SinkChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JPipe_SourceChannel', TypeInfo(Androidapi.JNI.JavaTypes.JPipe_SourceChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JReadableByteChannel', TypeInfo(Androidapi.JNI.JavaTypes.JReadableByteChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSelectionKey', TypeInfo(Androidapi.JNI.JavaTypes.JSelectionKey)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSelector', TypeInfo(Androidapi.JNI.JavaTypes.JSelector)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JServerSocketChannel', TypeInfo(Androidapi.JNI.JavaTypes.JServerSocketChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSocketChannel', TypeInfo(Androidapi.JNI.JavaTypes.JSocketChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JWritableByteChannel', TypeInfo(Androidapi.JNI.JavaTypes.JWritableByteChannel)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractSelector', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractSelector)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSelectorProvider', TypeInfo(Androidapi.JNI.JavaTypes.JSelectorProvider)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCharset', TypeInfo(Androidapi.JNI.JavaTypes.JCharset)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCharsetDecoder', TypeInfo(Androidapi.JNI.JavaTypes.JCharsetDecoder)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCharsetEncoder', TypeInfo(Androidapi.JNI.JavaTypes.JCharsetEncoder)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCoderResult', TypeInfo(Androidapi.JNI.JavaTypes.JCoderResult)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCodingErrorAction', TypeInfo(Androidapi.JNI.JavaTypes.JCodingErrorAction)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractCollection', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractCollection)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractList', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractList)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractMap', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractMap)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JAbstractSet', TypeInfo(Androidapi.JNI.JavaTypes.JAbstractSet)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JArrayList', TypeInfo(Androidapi.JNI.JavaTypes.JArrayList)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JBitSet', TypeInfo(Androidapi.JNI.JavaTypes.JBitSet)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCalendar', TypeInfo(Androidapi.JNI.JavaTypes.JCalendar)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCollection', TypeInfo(Androidapi.JNI.JavaTypes.JCollection)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JComparator', TypeInfo(Androidapi.JNI.JavaTypes.JComparator)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JDate', TypeInfo(Androidapi.JNI.JavaTypes.JDate)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JDictionary', TypeInfo(Androidapi.JNI.JavaTypes.JDictionary)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEnumSet', TypeInfo(Androidapi.JNI.JavaTypes.JEnumSet)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEnumeration', TypeInfo(Androidapi.JNI.JavaTypes.JEnumeration)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JGregorianCalendar', TypeInfo(Androidapi.JNI.JavaTypes.JGregorianCalendar)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JHashMap', TypeInfo(Androidapi.JNI.JavaTypes.JHashMap)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JHashSet', TypeInfo(Androidapi.JNI.JavaTypes.JHashSet)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JHashtable', TypeInfo(Androidapi.JNI.JavaTypes.JHashtable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JIterator', TypeInfo(Androidapi.JNI.JavaTypes.JIterator)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JList', TypeInfo(Androidapi.JNI.JavaTypes.JList)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JListIterator', TypeInfo(Androidapi.JNI.JavaTypes.JListIterator)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JLocale', TypeInfo(Androidapi.JNI.JavaTypes.JLocale)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JMap', TypeInfo(Androidapi.JNI.JavaTypes.JMap)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.Jutil_Observable', TypeInfo(Androidapi.JNI.JavaTypes.Jutil_Observable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JObserver', TypeInfo(Androidapi.JNI.JavaTypes.JObserver)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JProperties', TypeInfo(Androidapi.JNI.JavaTypes.JProperties)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JQueue', TypeInfo(Androidapi.JNI.JavaTypes.JQueue)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JRandom', TypeInfo(Androidapi.JNI.JavaTypes.JRandom)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSet', TypeInfo(Androidapi.JNI.JavaTypes.JSet)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSortedMap', TypeInfo(Androidapi.JNI.JavaTypes.JSortedMap)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JTimeZone', TypeInfo(Androidapi.JNI.JavaTypes.JTimeZone)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JUUID', TypeInfo(Androidapi.JNI.JavaTypes.JUUID)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JBlockingQueue', TypeInfo(Androidapi.JNI.JavaTypes.JBlockingQueue)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCallable', TypeInfo(Androidapi.JNI.JavaTypes.JCallable)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JCountDownLatch', TypeInfo(Androidapi.JNI.JavaTypes.JCountDownLatch)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JExecutor', TypeInfo(Androidapi.JNI.JavaTypes.JExecutor)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JExecutorService', TypeInfo(Androidapi.JNI.JavaTypes.JExecutorService)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JFuture', TypeInfo(Androidapi.JNI.JavaTypes.JFuture)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JTimeUnit', TypeInfo(Androidapi.JNI.JavaTypes.JTimeUnit)); //TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JSecretKey', TypeInfo(Androidapi.JNI.JavaTypes.JSecretKey)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEGL', TypeInfo(Androidapi.JNI.JavaTypes.JEGL)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEGL10', TypeInfo(Androidapi.JNI.JavaTypes.JEGL10)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEGLConfig', TypeInfo(Androidapi.JNI.JavaTypes.JEGLConfig)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEGLContext', TypeInfo(Androidapi.JNI.JavaTypes.JEGLContext)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEGLDisplay', TypeInfo(Androidapi.JNI.JavaTypes.JEGLDisplay)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JEGLSurface', TypeInfo(Androidapi.JNI.JavaTypes.JEGLSurface)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JGL', TypeInfo(Androidapi.JNI.JavaTypes.JGL)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JGL10', TypeInfo(Androidapi.JNI.JavaTypes.JGL10)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JJSONArray', TypeInfo(Androidapi.JNI.JavaTypes.JJSONArray)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JJSONException', TypeInfo(Androidapi.JNI.JavaTypes.JJSONException)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JJSONObject', TypeInfo(Androidapi.JNI.JavaTypes.JJSONObject)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JJSONTokener', TypeInfo(Androidapi.JNI.JavaTypes.JJSONTokener)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JXmlPullParser', TypeInfo(Androidapi.JNI.JavaTypes.JXmlPullParser)); TRegTypes.RegisterType('Androidapi.JNI.JavaTypes.JXmlSerializer', TypeInfo(Androidapi.JNI.JavaTypes.JXmlSerializer)); end; initialization RegisterTypes; end.
unit FFSTabSheet; interface uses ComCtrls, Forms; type TFormType = (ftClaim, ftPolicy, ftLoan, ftEntSoa, ftLendSoa); TFFSTabSheet = class(TTabSheet) private FKey3: String; FKey2: String; FKey1: String; FFormType: TFormType; FSearch: boolean; FForm: TForm; procedure SetFormType(const Value: TFormType); procedure SetKey1(const Value: String); procedure SetKey2(const Value: String); procedure SetKey3(const Value: String); procedure SetSearch(const Value: boolean); procedure SetForm(const Value: TForm); public property Key1: String read FKey1 write SetKey1; property Key2: String read FKey2 write SetKey2; property Key3: String read FKey3 write SetKey3; property FormType : TFormType read FFormType write SetFormType; property Search : boolean read FSearch write SetSearch; property Form : TForm read FForm write SetForm; end; { TFFSTabSheet } implementation procedure TFFSTabSheet.SetForm(const Value: TForm); begin FForm := Value; end; procedure TFFSTabSheet.SetFormType(const Value: TFormType); begin FFormType := Value; end; procedure TFFSTabSheet.SetKey1(const Value: String); begin FKey1 := Value; end; procedure TFFSTabSheet.SetKey2(const Value: String); begin FKey2 := Value; end; procedure TFFSTabSheet.SetKey3(const Value: String); begin FKey3 := Value; end; procedure TFFSTabSheet.SetSearch(const Value: boolean); begin FSearch := Value; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.LinkedLabel; interface uses System.Classes, System.UITypes, FMX.StdCtrls, FMX.Controls, FMX.Objects, FMX.Types, FGX.Consts; type { TfgLinkedLabel } IFGXLaunchService = interface; TfgCustomLinkedLabel = class(TLabel) public const DefaultCursor = crHandPoint; DefaultColor = TAlphaColorRec.Black; DefaultColorHover = TAlphaColorRec.Blue; DefaultColorVisited = TAlphaColorRec.Magenta; DefaultVisited = False; private const IndexColor = 0; IndexHoverColor = 1; IndexVisitedColor = 2; private FLaunchService: IFGXLaunchService; FUrl: string; FVisited: Boolean; FColor: TAlphaColor; FHoverColor: TAlphaColor; FVisitedColor: TAlphaColor; procedure SetColor(const Index: Integer; const Value: TAlphaColor); procedure SetVisited(const Value: Boolean); protected { Styles } function GetDefaultStyleLookupName: string; override; { Painting } procedure Paint; override; { Mouse events } procedure DoMouseEnter; override; procedure DoMouseLeave; override; procedure Click; override; procedure UpdateColor; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; public property Color: TAlphaColor index IndexColor read FColor write SetColor default DefaultColor; property HoverColor: TAlphaColor index IndexHoverColor read FHoverColor write SetColor default DefaultColorHover; property Url: string read FUrl write FUrl; property Cursor default DefaultCursor; property Visited: Boolean read FVisited write SetVisited default DefaultVisited; property VisitedColor: TAlphaColor index IndexVisitedColor read FVisitedColor write SetColor default DefaultColorVisited; end; [ComponentPlatformsAttribute(fgAllPlatform)] TfgLinkedLabel = class(TfgCustomLinkedLabel) published property Cursor; property Color; property HoverColor; property Url; property VisitedColor; property Visited; end; { IFMXLaunchService } IFGXLaunchService = interface ['{5BFFA845-EB02-480C-AFE9-EB15DE06AF10}'] function OpenURL(const AUrl: string): Boolean; end; implementation uses FMX.Platform {$IFDEF MSWINDOWS} , FGX.LinkedLabel.Win {$ENDIF} {$IFDEF IOS} , FGX.LinkedLabel.iOS {$ELSE} {$IFDEF MACOS} , FGX.LinkedLabel.Mac {$ENDIF} {$ENDIF} {$IFDEF ANDROID} , FGX.LinkedLabel.Android {$ENDIF} ; { TLinkedLabel } procedure TfgCustomLinkedLabel.Click; begin if FLaunchService <> nil then begin FVisited := True; Repaint; FLaunchService.OpenURL(Url); end; end; constructor TfgCustomLinkedLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); HitTest := True; Font.Style := [TFontStyle.fsUnderline]; StyledSettings := []; Cursor := DefaultCursor; FVisited := DefaultVisited; FColor := DefaultColor; FHoverColor := DefaultColorHover; FVisitedColor := DefaultColorVisited; TPlatformServices.Current.SupportsPlatformService(IFGXLaunchService, FLaunchService); end; destructor TfgCustomLinkedLabel.Destroy; begin FLaunchService := nil; inherited Destroy; end; procedure TfgCustomLinkedLabel.DoMouseEnter; begin inherited DoMouseEnter; Repaint; end; procedure TfgCustomLinkedLabel.DoMouseLeave; begin inherited DoMouseLeave; Repaint; end; function TfgCustomLinkedLabel.GetDefaultStyleLookupName: string; begin Result := 'LabelStyle'; end; procedure TfgCustomLinkedLabel.Paint; begin UpdateColor; inherited Paint; end; procedure TfgCustomLinkedLabel.SetColor(const Index: Integer; const Value: TAlphaColor); begin case Index of IndexColor: FColor := Value; IndexHoverColor: FHoverColor := Value; IndexVisitedColor: FVisitedColor := Value; end; Repaint; end; procedure TfgCustomLinkedLabel.SetVisited(const Value: Boolean); begin if Visited <> Value then begin FVisited := Value; UpdateColor; end; end; procedure TfgCustomLinkedLabel.UpdateColor; begin if IsMouseOver then TextSettings.FontColor := FHoverColor else if FVisited then TextSettings.FontColor := FVisitedColor else TextSettings.FontColor := Color; end; initialization RegisterFmxClasses([TfgCustomLinkedLabel, TfgLinkedLabel]); RegisterService; finalization UnregisterService; end.
{ Subroutine SST_W_C_VALUE (VAL,ENCLOSE) * * Write a constant value. VAL is the descriptor for the value. * ENCLOSE indicates whether the final expression should be enclosed in * parentheses. Values of ENCLOSE can be: * * ENCLOSE_YES_K - Enclose in parentheses, if neccessary, to make the * entire expression be one term. This is done when the constant is * written with a unary operator (such as minus sign). * * ENCLOSE_NO_K - Don't enclose expression in parentheses, even if * a unary operator is used. } module sst_w_c_VALUE; define sst_w_c_value; %include 'sst_w_c.ins.pas'; procedure sst_w_c_value ( {write the value of a constant} in val: sst_var_value_t; {value descriptor} in enclose: enclose_k_t); {enclose in () yes/no} const quote_char_c = ''''; {character that starts/stops quoted char} quote_char_s = '"'; {character that starts/stops quoted string} esc_char = '\'; {escape char for special characters} max_msg_parms = 1; {max parameters we can pass to a message} var token: string_var8192_t; {sratch string for number conversion, etc} i: sys_int_machine_t; {loop counter} paren: boolean; {TRUE if wrote open parenthesis} stat: sys_err_t; msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label done_fp, done_dtype; begin token.max := sizeof(token.str); {init local var string} paren := false; {init to no open parenthesis written} case val.dtype of { * Data type is integer. } sst_dtype_int_k: begin if {need parentheses around value ?} (enclose = enclose_yes_k) and (val.int_val < 0) then begin sst_w.appendn^ ('(', 1); paren := true; end; string_f_int_max (token, val.int_val); sst_w.append^ (token); end; { * Data type is value of an enumerated type. } sst_dtype_enum_k: begin sst_w.append_sym_name^ (val.enum_p^); end; { * Data type is floating point. } sst_dtype_float_k: begin if {need parentheses around value ?} (enclose = enclose_yes_k) and (val.float_val < 0.0) then begin sst_w.appendn^ ('(', 1); paren := true; end; string_f_fp ( {try to convert without using exp notation} token, {output string} val.float_val, {input floating point number} 0, {free format} 0, {free format for exponent (unused)} 7, {min required significant digits} 6, {max digits allowed left of point} 1, {min digits right of point} 8, {max digits right of point} [string_ffp_exp_no_k], {don't allow exponential notation} stat); {completion status code} if not sys_error(stat) then begin {conversion to string was successfull ?} while {truncate trailing zeros} (token.str[token.len] = '0') and (token.str[token.len-1] >= '0') and (token.str[token.len-1] <= '9') do begin token.len := token.len - 1; end; goto done_fp; {TOKEN all set} end; string_f_fp ( {resort to exponential notation} token, {output string} val.float_val, {input floating point number} 0, {free format} 0, {free format for exponent} 7, {min required significant digits} 0, {max digits allowed left of point (unused)} 0, {min digits right of point} 0, {max digits right of point (unused)} [ string_ffp_exp_k, {use exponential notation} string_ffp_exp_eng_k, {use engineering notation} string_ffp_z_aft_k], {always write at least one digit right of pnt} stat); {completion status code} done_fp: {final floating point number is in TOKEN} sst_w.append^ (token); end; { * Data type is boolean. } sst_dtype_bool_k: begin if val.bool_val then sst_w_c_intrinsic (intr_true_k) else sst_w_c_intrinsic (intr_false_k); end; { * Data type is character. } sst_dtype_char_k: begin sst_w.appendn^ (quote_char_c, 1); {put leading quote} if (val.char_val >= ' ') and (val.char_val <= '~') then begin {this is a printable character} if {this char needs to be "escaped" ?} (val.char_val = quote_char_c) or (val.char_val = esc_char) then begin sst_w.appendn^ (esc_char, 1); {write escape character} end; sst_w.appendn^ (val.char_val, 1); {write the character itself} end else begin {this is not a printable character} sst_w.appendn^ (esc_char, 1); {write escape character} string_f_int_max_base ( {convert character value to octal integer} token, {output string} ord(val.char_val), {character value} 8, {number base of output string} 0, {indicate free-form formatting} [string_fi_unsig_k], {input number if unsigned} stat); {error status code} sys_error_abort (stat, '', '', nil, 0); sst_w.append^ (token); {write octal character value} end ; sst_w.appendn^ (quote_char_c, 1); {put trailing quote} end; { * Data type is an array. We only know how to write string-type arrays. } sst_dtype_array_k: begin if {target system needs special handling ?} (frame_scope_p^.sment_type <> sment_type_exec_k) and {not in executable code ?} (val.ar_str_p^.len > 0) and {string has at least one character ?} (sst_config.os = sys_os_aix_k) and {IBM XLC C compiler ?} (not no_ibm_str_kluge) {this special case not explicitly inhibited ?} then begin {write string as separate characters} sst_w.appendn^ ('{', 1); for i := 1 to val.ar_str_p^.len do begin {once for each character in string} sst_w.appendn^ ('''', 1); {write leading quote for this character} if (val.ar_str_p^.str[i] >= ' ') and (val.ar_str_p^.str[i] <= '~') then begin {this is a printable character} if {this char needs to be "escaped" ?} (val.ar_str_p^.str[i] = quote_char_c) or (val.ar_str_p^.str[i] = esc_char) then begin sst_w.appendn^ (esc_char, 1); {write escape character} end; sst_w.appendn^ (val.ar_str_p^.str[i], 1); {write the character itself} end else begin {this is not a printable character} sst_w.appendn^ (esc_char, 1); {write escape character} string_f_int_max_base ( {convert character value to octal integer} token, {output string} ord(val.ar_str_p^.str[i]), {character value} 8, {number base of output string} 0, {indicate free-form formatting} [string_fi_unsig_k], {input number if unsigned} stat); {error status code} sys_error_abort (stat, '', '', nil, 0); sst_w.append^ (token); {write octal character value} end ; sst_w.appendn^ ('''', 1); {write trailing quote for this character} if i <> val.ar_str_p^.len then begin {another character will follow ?} sst_w.appendn^ (',', 1); sst_w.allow_break^; end; end; {back for next source character} sst_w.appendn^ ('}', 1); goto done_dtype; {all done writing value} end; {done with IBM XLC C special case} token.len := 0; sst_w.appendn^ ('"', 1); {write leading quote} for i := 1 to val.ar_str_p^.len do begin {once for each character in string} if (val.ar_str_p^.str[i] >= ' ') and (val.ar_str_p^.str[i] <= '~') then begin {this is a printable character} if {this char needs to be "escaped" ?} (val.ar_str_p^.str[i] = quote_char_s) or (val.ar_str_p^.str[i] = esc_char) then begin sst_w.appendn^ (esc_char, 1); {write escape character} end; sst_w.appendn^ (val.ar_str_p^.str[i], 1); {write the character itself} end else begin {this is not a printable character} sst_w.appendn^ (esc_char, 1); {write escape character} string_f_int_max_base ( {convert character value to octal integer} token, {output string} ord(val.ar_str_p^.str[i]), {character value} 8, {number base of output string} 3, {we always need 3 digits} [ string_fi_unsig_k, {input number if unsigned} string_fi_leadz_k], {always write leading zeros} stat); {error status code} sys_error_abort (stat, '', '', nil, 0); sst_w.append^ (token); {write octal character value} end ; end; {back for next source character} sst_w.appendn^ ('"', 1); {write trailing quote} end; { * Data type is pointer. } sst_dtype_pnt_k: begin if val.pnt_exp_p = nil then begin {NIL pointer} sst_w_c_intrinsic (intr_nil_k); end else begin {pointing to a real symbol} sst_w_c_exp (val.pnt_exp_p^, 1, nil, enclose); end ; end; { * Unexpected data type. } otherwise sys_msg_parm_int (msg_parm[1], ord(val.dtype)); sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1); end; {end of data type cases} done_dtype: {jump here if done with data type case} if paren then begin {need to write close parenthesis ?} sst_w.appendn^ (')', 1); end; end;
unit l3CustomString; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3CustomString - } { Начат: 05.02.2008 15:53 } { $Id: l3CustomString.pas,v 1.19 2013/05/24 15:59:50 lulin Exp $ } // $Log: l3CustomString.pas,v $ // Revision 1.19 2013/05/24 15:59:50 lulin // - пытаемся портироваться под XE4. // // Revision 1.18 2013/03/28 17:25:04 lulin // - портируем. // // Revision 1.17 2013/03/28 16:13:50 lulin // - портируем. // // Revision 1.16 2012/05/15 12:13:25 dinishev // {Requestlink:363571851} // // Revision 1.15 2011/12/20 13:35:14 fireton // - предупреждения о правильном использовании поиска без учёта регистра // // Revision 1.14 2010/05/14 11:52:30 lulin // {RequestLink:211879983}. // // Revision 1.13 2009/07/23 08:15:07 lulin // - вычищаем ненужное использование процессора операций. // // Revision 1.12 2009/07/21 12:24:40 lulin // {RequestLink:141264340}. №35. // // Revision 1.11 2009/02/05 13:28:53 lulin // - <K>: 125895391. Используем уже посчитанные длины, а не считаем их заново. // // Revision 1.10 2009/02/05 13:02:45 lulin // - <K>: 125895391. // // Revision 1.9 2009/02/05 11:58:31 lulin // - <K>: 125895391. Передаём кодировку, а не флажок. // // Revision 1.8 2009/01/15 09:07:47 lulin // - поддерживаем преобразование регистра символов в татарском. // // Revision 1.7 2008/12/18 13:45:10 lulin // - <K>: 132222370. Поддерживаем работу с кодировкой TatarOEM. // // Revision 1.6 2008/12/18 12:39:02 lulin // - <K>: 132222370. Поддерживаем работу с кодировкой TatarOEM. // // Revision 1.5 2008/12/15 16:06:19 lulin // - <K>: 131137753. // // Revision 1.4 2008/12/12 19:19:30 lulin // - <K>: 129762414. // // Revision 1.3 2008/02/21 12:51:20 mmorozov // - bugfix: не собирался проект без директивы l3Requires_m0; // // Revision 1.2 2008/02/20 17:23:09 lulin // - упрощаем строки. // // Revision 1.1 2008/02/12 10:31:25 lulin // - избавляемся от излишнего метода на базовом классе. // // Revision 1.7 2008/02/06 13:28:19 lulin // - каждому базовому объекту по собственному модулю. // // Revision 1.6 2008/02/05 18:55:11 lulin // - запрещаем напрямую устанавливать буфер строке. // // Revision 1.5 2008/02/05 18:20:42 lulin // - удалено ненужное свойство строк. // // Revision 1.4 2008/02/05 17:39:39 lulin // - избавляемся от ненужного именованного объекта. // // Revision 1.3 2008/02/05 16:13:19 lulin // - избавляем базовый объект от лишнего свойства. // // Revision 1.2 2008/02/05 15:25:21 lulin // - переносим на модель самые базовые объекты. // // Revision 1.1 2008/02/05 13:09:16 lulin // - базовая строка переехала в отжельный файл. // {$Include l3Define.inc } interface uses Classes, l3Interfaces, l3IID, l3Types, l3PrimString ; type Tl3CustomString = class(Tl3PrimString) {* Базовый класс для "строк". Определяет операции и свойства, но не способ хранения данных. } protected // property methods function pm_GetSt: PAnsiChar; {-} function pm_GetLen: Integer; procedure pm_SetLen(Value: Integer); virtual; {-} function pm_GetCodePage: Integer; procedure pm_SetCodePage(Value: Integer); {-} function pm_GetIsOEM: Boolean; {-} function pm_GetIsOEMEx: Boolean; {-} function pm_GetIsANSI: Boolean; {-} procedure DoSetCodePage(Value: Integer); virtual; {-} function pm_GetAsPCharLen: Tl3PCharLen; procedure pm_SetAsPCharLen(const Value: Tl3PCharLen); {-} function pm_GetFirst: AnsiChar; {-} function pm_GetLast: AnsiChar; {-} function pm_GetCh(aPos: Integer): AnsiChar; procedure pm_SetCh(aPos: Integer; Value: AnsiChar); {-} function pm_GetRTrimLen: Integer; {-} function pm_GetLTrimLen: Integer; {-} function pm_GetAsChar: AnsiChar; procedure pm_SetAsChar(Value: AnsiChar); {-} function pm_GetAsPWideChar: PWideChar; procedure pm_SetAsPWideChar(aValue: PWideChar); {-} function pm_GetAsWideString: WideString; procedure pm_SetAsWideString(const aValue: WideString); {-} protected // internal methods procedure DoSetAsPCharLen(const Value: Tl3PCharLen); override; {-} procedure CheckUnicode; {-} public // public methods function AssignSt(aSt : PAnsiChar; O1, O2 : Integer; aCodePage : Integer): Tl3CustomString; {-} procedure LPad(aCh : AnsiChar; aCodePage : Integer = CP_ANSI; aRepeat : Integer = 1); {* - добавляет к строке слева символ aCh aRepeat раз. } procedure Append(const aSt: Tl3WString; aRepeat: Integer = 1); overload; virtual; {* - добавляет строку aSt к данной строке aRepeat раз. } procedure Append(const aCh: Tl3Char; aRepeat: Integer = 1); overload; {* - добавляет символ aCh к данной строке aRepeat раз. } procedure Append(aCh : AnsiChar; aRepeat : Integer = 1; aCodePage : Integer = CP_ANSI); overload; {* - добавляет символ aCh к данной строке aRepeat раз. } procedure Insert(const aSt : Tl3WString; aPos : Integer; aRepeat : Integer = 1); overload; virtual; {* - вставляет строку aSt в позицию aPos, aRepeat раз. } procedure Insert(aCh : AnsiChar; aPos : Integer; aRepeat : Integer = 1); overload; {* - вставляет символ aCh в позицию aPos, aRepeat раз. } procedure Insert(S : Tl3CustomString; aPos : Integer; aRepeat : Integer = 1); overload; {* - вставляет строку S в позицию aPos, aRepeat раз. } function Offset(Delta: Integer): Tl3CustomString; virtual; {-} function Trim: Tl3CustomString; {* - удаляет конечные и начальные пробелы. } function TrimAll: Tl3CustomString; {* - удаляет конечные, начальные и дублирующиеся пробелы. } procedure LTrim; virtual; {* - удаляет из строки ведущие пробелы. } function RTrim: Tl3CustomString; {* - удаляет из строки конечные пробелы. } procedure TrimEOL; {* - удаляет из строки конечные cc_SoftEnter и cc_HardEnter. } function DeleteDoubleSpace: Tl3CustomString; virtual; {* - удаляет из строки дублирующиеся пробелы. } function DeleteAllChars(aChar: AnsiChar): Integer; {* - удаляет из строки все символы aChar и возвращает количество удаленных. } function ReplaceNonReadable: Tl3CustomString; virtual; {* - заменяет "нечитаемые" символы пробелами. } function FindChar(Pos: Integer; C: AnsiChar): Integer; {* - ищет символ в строке с позиции Pos и возвращает позицию найденного символа или -1. } procedure FindCharEx(C: AnsiChar; aSt: Tl3CustomString); {-} function Indent: Integer; {* - возвращает левый отступ строки. } function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {-} procedure Assign(P: TPersistent); override; {-} procedure MakeBMTable(var BT : Tl3BMTable); {* - создает таблицу Boyer-Moore для строки. } function BMSearch(S: Tl3CustomString; const BT : Tl3BMTable; var Pos : Cardinal) : Boolean; {* - ищет данную строку в строке S с учетом регистра. } function BMSearchUC(S: Tl3CustomString; const BT : Tl3BMTable; var Pos : Cardinal) : Boolean; {* - ищет данную строку в строке S без учета регистра. } // ВНИМАНИЕ! Для успешного поиска без учёта регистра подстрока (S) должна быть в ВЕРХНЕМ РЕГИСТРЕ! // И таблица (BT) должна быть построена для этой строки в верхнем регистре! procedure MakeUpper; {* - преобразует строку к верхнему регистру. } procedure MakeLower; {* - преобразует строку к нижнему регистру. } function Delete(aPos, aCount: Integer): PAnsiChar; virtual; {* - удаляет aCount символов с позиции aPos. } procedure SetSt(aStr: PAnsiChar; aLen: Integer = -1); {* - присваивает новое значение строке, считая, что aStr имеет ту же кодировку, что и строка. } function JoinWith(P: Tl3PrimString): Integer; virtual; {* операция объединения двух объектов. } public // public properties property St: PAnsiChar read pm_GetSt; {* - указатель на строку. } property Len: Integer read pm_GetLen write pm_SetLen; {* - длина строки. } property CodePage: Integer read pm_GetCodePage write pm_SetCodePage; {* - кодовая страница для символов строки. } property IsOEM: Boolean read pm_GetIsOEM; {* - строка в кодировке OEM? } property IsOEMEx: Boolean read pm_GetIsOEMEx; {* - строка в кодировке OEM? В обобщённом смысле, например CP_TatarOem. } property IsANSI: Boolean read pm_GetIsANSI; {* - строка в кодировке ANSI? } property AsPCharLen: Tl3PCharLen read pm_GetAsPCharLen write pm_SetAsPCharLen; {* - свойство для преобразования к типу Tl3PCharLen и обратно. } property First: AnsiChar read pm_GetFirst; {* - первый символ строки. } property Last: AnsiChar read pm_GetLast; {* - последний символ строки. } property Ch[aPos: Integer]: AnsiChar read pm_GetCh write pm_SetCh; {* - символ строки на позиции aPos. } property RTrimLen: Integer read pm_GetRTrimLen; {* - длина строки без учета конечных пробелов. } property LTrimLen: Integer read pm_GetLTrimLen; {* - длина строки без учета начальных пробелов. } property AsChar: AnsiChar read pm_GetAsChar write pm_SetAsChar; {* - преобразует строку к символу. } property AsPWideChar: PWideChar read pm_GetAsPWideChar write pm_SetAsPWideChar; {-} property AsWideString: WideString read pm_GetAsWideString write pm_SetAsWideString; {-} end;//Tl3CustomString implementation uses SysUtils, l3BMSearch {$IfDef l3Requires_m0} , m2XLtLib {$Else l3Requires_m0} , Windows {$EndIf l3Requires_m0} , l3String, l3Chars, l3StringEx, l3StringAdapter, l3Memory, l3Base ; // start class Tl3CustomString procedure Tl3CustomString.Assign(P: TPersistent); {override;} {-} begin if (P = nil) then Clear else if (P Is Tl3PrimString) then AssignString(Tl3PrimString(P)) else inherited; end; procedure Tl3CustomString.MakeBMTable(var BT : Tl3BMTable); {-Build a Boyer-Moore link table} var l_S : Tl3PCharLen; begin l_S := AsPCharLen; if (l_S.SCodePage = CP_Unicode) then l3FillChar(BT, SizeOf(BT)) else l3BMSearch.BMMakeTable(l_S.S, BT, l_S.SLen); end; function Tl3CustomString.BMSearch(S: Tl3CustomString; const BT : Tl3BMTable; var Pos : Cardinal) : Boolean; {-Use the Boyer-Moore search method to search a buffer for a string} var l_S : Tl3PCharLen; l_SS : Tl3PCharLen; begin l_S := S.AsPCharLen; l_SS := AsPCharLen; if l3IsNil(l_SS) then Result := false else Result := l3SearchStr(l_S, BT, l_SS, Pos); end; function Tl3CustomString.BMSearchUC(S: Tl3CustomString; const BT : Tl3BMTable; var Pos : Cardinal) : Boolean; {-Use the Boyer-Moore search method to search a buffer for a string. This search is not _case sensitive} var l_S : Tl3PCharLen; l_SS : Tl3PCharLen; begin l_S := S.AsPCharLen; l_SS := AsPCharLen; if l3IsNil(l_SS) then Result := false else Result := l3SearchStrUC(l_S, BT, l_SS, Pos); end; procedure Tl3CustomString.MakeUpper; {-} begin l3MakeUpperCase(St, Len, CodePage); end; procedure Tl3CustomString.MakeLower; {-} begin l3MakeLowerCase(St, Len, CodePage); end; function Tl3CustomString.Delete(aPos, aCount: Integer): PAnsiChar; //virtual; {-} begin Result := St; end; procedure Tl3CustomString.SetSt(aStr: PAnsiChar; aLen: Integer = -1); {* - присваивает новое значение строке, считая, что aStr имеет ту же кодировку, что и строка. } begin AsPCharLen := l3PCharLen(aStr, aLen, CodePage); end; function Tl3CustomString.JoinWith(P: Tl3PrimString): Integer; begin Result := -1; end; function Tl3CustomString.pm_GetSt: PAnsiChar; {virtual;} begin if (Self = nil) then Result := nil else Result := GetAsPCharLen.S; end; function Tl3CustomString.pm_GetLen: Integer; begin if (Self = nil) then Result := 0 else Result := GetAsPCharLen.SLen; end; procedure Tl3CustomString.pm_SetLen(Value: Integer); {virtual;} {-} begin end; function Tl3CustomString.pm_GetAsChar: AnsiChar; begin Result := Ch[0]; end; procedure Tl3CustomString.pm_SetAsChar(Value: AnsiChar); begin AsPCharLen := l3PCharLen(@Value, 1, CodePage); end; procedure Tl3CustomString.DoSetAsPCharLen(const Value: Tl3PCharLen); //virtual; {-} begin Assert(false); end; procedure Tl3CustomString.CheckUnicode; {-} const cCodePages : array [0..4] of Integer = (CP_RussianWin, CP_WesternWin, CP_Tatar, CP_TatarOEM, CP_RussianDOS); var l_Index : Integer; l_S : Tl3Str; l_W : Tl3WString; begin l_W := GetAsPCharLen; if (l_W.SCodePage = CP_Unicode) then begin for l_Index := Low(cCodePages) to High(cCodePages) do begin l_S.Init(l_W, cCodePages[l_Index]); try if l3Same(l_W, l_S) then begin CodePage := cCodePages[l_Index]; break; end;//l3Same(l_S, l_S) finally l_S.Clear; end;//try..finally end;//for l_Index end;//l_W.SCodePage = CP_Unicode end; procedure Tl3CustomString.LPad(aCh : AnsiChar; aCodePage : Integer = CP_ANSI; aRepeat : Integer = 1); {-} begin Insert(l3PCharLen(@aCh, 1, aCodePage), 0, aRepeat); end; procedure Tl3CustomString.Append(const aSt: Tl3WString; aRepeat: Integer = 1); {virtual;} {overload;} {-} begin end; procedure Tl3CustomString.Append(const aCh: Tl3Char; aRepeat: Integer = 1); //overload; {* - добавляет символ aCh к данной строке aRepeat раз. } begin Append(l3PCharLen(@aCh.rWC, 1, aCh.rCodePage), aRepeat); end; procedure Tl3CustomString.Append(aCh : AnsiChar; aRepeat : Integer = 1; aCodePage : Integer = CP_ANSI); {overload;} {-} begin Append(l3PCharLen(@aCh, 1, aCodePage), aRepeat); end; procedure Tl3CustomString.Insert(S : Tl3CustomString; aPos : Integer; aRepeat : Integer = 1); {-} begin if not S.Empty then Insert(S.AsPCharLen, aPos, aRepeat); end; procedure l3SayConstString; {-} begin raise Exception.Create('Данный тип строки не может быть модифицирован'); end; function Tl3CustomString.ReplaceNonReadable: Tl3CustomString; //virtual; {* - заменяет "нечитаемые" символы пробелами. } begin Result := Self; l3SayConstString; end; procedure Tl3CustomString.Insert(const aSt : Tl3WString; aPos : Integer; aRepeat : Integer = 1); //overload; //virtual; begin l3SayConstString; end; procedure Tl3CustomString.Insert(aCh : AnsiChar; aPos : Integer; aRepeat : Integer = 1); {overload;} {-} begin Insert(l3PCharLen(PAnsiChar(@aCh), 1), aPos, aRepeat); end; function Tl3CustomString.pm_GetAsWideString: WideString; {-} {$IfDef XE4} var l_S : Tl3PCharLen; {$EndIf XE4} begin {$IfDef XE4} l_S := AsPCharLen; Result := Tl3Str(l_S).AsWideString; {$Else XE4} Result := Tl3Str(AsPCharLen).AsWideString; {$EndIf XE4} end; procedure Tl3CustomString.pm_SetAsWideString(const aValue: WideString); {-} begin AsPCharLen := l3PCharLen(aValue); end; function Tl3CustomString.pm_GetAsPWideChar: PWideChar; {-} begin Result := PWideChar(St); end; procedure Tl3CustomString.pm_SetAsPWideChar(aValue: PWideChar); {-} begin AsPCharLen := l3PCharLen(PAnsiChar(aValue), -1, CP_Unicode); end; function Tl3CustomString.AssignSt(aSt : PAnsiChar; O1, O2 : Integer; aCodePage : Integer): Tl3CustomString; {-} var L : Integer; begin if (O2 > O1) then L := O2 - O1 else L := 0; AsPCharLen := l3PCharLen(aSt + O1, L, aCodePage); Result := Self; end; function Tl3CustomString.pm_GetCodePage: Integer; begin Result := AsPCharLen.SCodePage; end; function Tl3CustomString.pm_GetIsOEM: Boolean; {-} begin Result := l3IsOEM(CodePage); end; function Tl3CustomString.pm_GetIsOEMEx: Boolean; {-} begin Result := l3IsOEMEx(CodePage); end; function Tl3CustomString.pm_GetIsANSI: Boolean; {-} begin Result := l3IsANSI(CodePage); end; procedure Tl3CustomString.pm_SetCodePage(Value: Integer); {-} begin if (Self <> nil) then DoSetCodePage(Value); end; procedure Tl3CustomString.DoSetCodePage(Value: Integer); {virtual;} {-} begin end; function Tl3CustomString.pm_GetAsPCharLen: Tl3PCharLen; begin if (Self = nil) then l3AssignNil(Result) else Tl3WString(Result) := GetAsPCharLen; end; procedure Tl3CustomString.pm_SetAsPCharLen(const Value: Tl3PCharLen); begin if (Self <> nil) then begin Changing; try DoSetAsPCharLen(Value); finally Changed; end;//try..finally end;//Self <> nil end; function Tl3CustomString.pm_GetFirst: AnsiChar; {-} begin if not Empty then Result := Ch[0] else Result := #0; end; function Tl3CustomString.pm_GetLast: AnsiChar; {-} begin if not Empty then Result := Ch[Pred(Len)] else Result := #0; end; function Tl3CustomString.pm_GetCh(aPos: Integer): AnsiChar; var l_S : Tl3WString; begin l_S := AsPCharLen; if (l_S.S <> nil) AND (aPos >= 0) AND (aPos < l_S.SLen) then begin if (l_S.SCodePage = CP_Unicode) then Result := AnsiChar(PWideChar(l_S.S)[aPos]) else Result := l_S.S[aPos]; end//S <> nil else Result := #0; end; procedure Tl3CustomString.pm_SetCh(aPos: Integer; Value: AnsiChar); var l_S : Tl3WString; begin if (aPos >= 0) then begin l_S := GetAsPCharLen; if (l_S.S <> nil) AND (aPos < l_S.SLen) then begin if (l_S.SCodePage = CP_Unicode) then PWideChar(l_S.S)[aPos] := WideChar(Value) else l_S.S[aPos] := Value; CheckUnicode; end//S <> nil else Insert(l3PCharLen(@Value, 1, CodePage), aPos); end;{aPos >= 0} end; function Tl3CustomString.pm_GetRTrimLen: Integer; {-} begin if Empty then Result := 0 else Result := l3RTrim(AsPCharLen).SLen; end; function Tl3CustomString.Offset(Delta: Integer): Tl3CustomString; {virtual;} {-} var l_S : Tl3WString; begin l_S := AsWStr; AsWStr := l3PCharLen(l_S.S + Delta, l_S.SLen - Delta, l_S.SCodePage); Result := Self; end; procedure Tl3CustomString.LTrim; //virtual; {-} begin Assert(false); end; function Tl3CustomString.RTrim: Tl3CustomString; {-} begin if not Empty then begin Len := l3RTrim(AsPCharLen).SLen; if Empty then Clear; end;//not Empty Result := Self; end; procedure Tl3CustomString.TrimEOL; {* - удаляет из строки конечные cc_SoftEnter и cc_HardEnter. } begin while (Len > 0) AND (St[Pred(Len)] in [cc_SoftEnter, cc_HardEnter, cc_Null]) do Len := Pred(Len); end; function Tl3CustomString.Trim: Tl3CustomString; {-} begin LTrim; Result := RTrim; end; function Tl3CustomString.TrimAll: Tl3CustomString; {-} begin Result := Trim.DeleteDoubleSpace; end; function Tl3CustomString.DeleteDoubleSpace: Tl3CustomString; {virtual;} {-} begin Result := Self; end; function Tl3CustomString.DeleteAllChars(aChar: AnsiChar): Integer; {* - удаляет из строки все символы aChar и возвращает количество удаленных. } var l_Pos : Integer; begin Result := 0; l_Pos := 0; while true do begin l_Pos := FindChar(l_Pos, aChar); if (l_Pos < 0) then break else begin Delete(l_Pos, 1); Inc(Result); end;//l_Pos < 0 end;//while true end; function Tl3CustomString.FindChar(Pos: Integer; C: AnsiChar): Integer; {-} var P, P1 : PAnsiChar; begin if Empty OR (Pos >= Len) then Result := -1 else begin P := St; P1 := ev_lpScan(C, P + Pos, Len - Pos); if (P1 = nil) then Result := -1 else Result := (P1 - P); end;//Empty.. end; procedure Tl3CustomString.FindCharEx(C: AnsiChar; aSt: Tl3CustomString); {-} var l_S : Tl3PCharLen; begin l_S := AsPCharLen; aSt.AsPCharLen := l3FindChar(C, l_S); if not aSt.Empty then Len := l_S.SLen; end; function Tl3CustomString.Indent: Integer; {-} begin if Empty then Result := 0 else Result := ev_lpIndent(St, Len); end; function Tl3CustomString.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {override;} {-} begin Result.SetOk; if IID.EQ(Il3CString) then Il3CString(Obj) := Tl3StringAdapter.MakeS(Self) else if IID.EQ(IStream) then IStream(Obj) := Tl3StringStream.Make(Self) else Result := inherited COMQueryInterface(IID, Obj); end; function Tl3CustomString.pm_GetLTrimLen: Integer; begin if Empty then Result := 0 else Result := l3LTrim(Self.AsWStr).SLen; end; end.
unit SpontaneousBuildings; interface uses Protocol, Kernel, PopulatedBlock, Surfaces, BackupInterfaces; type TGrowthDir = (dirN, dirE, dirS, dirW); type TSpontaneousBuilding = class; TNeighborBuildings = array[TGrowthDir] of TSpontaneousBuilding; TNeighborBlocked = array[TGrowthDir] of boolean; TSpontaneousBuilding = class( TPopulatedBlock ) public destructor Destroy; override; protected function Evaluate : TEvaluationResult; override; public procedure AutoConnect( loaded : boolean ); override; function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; protected function ComputeCrime : TSurfaceValue; override; private fNeighbors : TNeighborBuildings; fBlocked : TNeighborBlocked; fAllBlocked : boolean; private function GetNeighbor( dir : TGrowthDir ) : TSpontaneousBuilding; procedure SetNeighbor( dir : TGrowthDir; N : TSpontaneousBuilding ); function GetBlocked ( dir : TGrowthDir ) : boolean; procedure SetBlocked ( dir : TGrowthDir; Blocked : boolean ); public property Neighbors[dir : TGrowthDir] : TSpontaneousBuilding read GetNeighbor write SetNeighbor; property Blocked[dir : TGrowthDir] : boolean read GetBlocked write SetBlocked; public function GetAvailableDir( out dir : TGrowthDir ) : boolean; public procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; const MinOccupancy = 2; // Building will disappear if occupancy drops below min MinAge = 48; // Min age of building to be destroyed if empty procedure RegisterBackup; implementation uses Population, SysUtils; // TSpontaneousBuilding destructor TSpontaneousBuilding.Destroy; begin TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock).DestroySpontaneousBuilding( Facility ); inherited; end; function TSpontaneousBuilding.Evaluate : TEvaluationResult; function OppositeDir( dir : TGrowthDir ) : TGrowthDir; begin case dir of dirN : result := dirS; dirE : result := dirW; dirS : result := dirN; else result := dirE; end; end; { var dir : TGrowthDir; } begin result := inherited Evaluate; { if (Occupancy < MinOccupancy) and (Facility.Age > MinAge) then begin for dir := low(dir) to high(dir) do if fNeighbors[dir] <> nil then fNeighbors[dir].fNeighbors[OppositeDir(dir)] := nil; TInhabitedTown(Facility.Town).World.RequestDeletion( Facility ); end; } end; procedure TSpontaneousBuilding.AutoConnect( loaded : boolean ); begin inherited; if not loaded then begin fPeople.Q := 1 + random(10); fPeople.K := 0; end; end; function TSpontaneousBuilding.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; begin result := inherited GetStatusText( kind, ToTycoon ); case kind of sttHint : result := 'This house was constructed by poor people that wanted to move to this town ' + 'but did not find a fair offer. You cannot demolish this building. It will ' + 'dissapear once its inhabitants move somewhere else.'; end; end; function TSpontaneousBuilding.ComputeCrime : TSurfaceValue; begin result := 10*inherited ComputeCrime; end; function TSpontaneousBuilding.GetNeighbor( dir : TGrowthDir ) : TSpontaneousBuilding; begin result := fNeighbors[dir]; end; procedure TSpontaneousBuilding.SetNeighbor( dir : TGrowthDir; N : TSpontaneousBuilding ); begin fNeighbors[dir] := N; if N = nil then Blocked[dir] := false; end; function TSpontaneousBuilding.GetBlocked( dir : TGrowthDir ) : boolean; begin result := fBlocked[dir]; end; procedure TSpontaneousBuilding.SetBlocked( dir : TGrowthDir; Blocked : boolean ); begin fBlocked[dir] := Blocked; dir := low(dir); while fBlocked[dir] and (dir < high(dir)) do inc( dir ); fAllBlocked := fBlocked[dir]; end; function TSpontaneousBuilding.GetAvailableDir( out dir : TGrowthDir ) : boolean; var startdir : TGrowthDir; begin if not fAllBlocked then begin startdir := TGrowthDir(random(ord(high(startdir)) + 1)); dir := startdir; repeat if dir < high(dir) then inc( dir ) else dir := low(dir); until (fNeighbors[dir] = nil) and not fBlocked[dir] or (dir = startdir); result := (fNeighbors[dir] = nil) and not fBlocked[dir]; end else result := false; end; procedure TSpontaneousBuilding.LoadFromBackup( Reader : IBackupReader ); var dir : TGrowthDir; begin inherited; for dir := low(dir) to high(dir) do Reader.ReadObject( 'Neighbors' + IntToStr(ord(dir)), fNeighbors[dir], nil ); Reader.ReadBuffer( 'Blocked', fBlocked, nil, sizeof(fBlocked) ); fAllBlocked := Reader.ReadBoolean( 'AllBlocked', false ); end; procedure TSpontaneousBuilding.StoreToBackup( Writer : IBackupWriter ); var dir : TGrowthDir; aux : string; begin inherited; for dir := low(dir) to high(dir) do begin aux := 'Neighbors' + IntToStr(ord(dir)); Writer.WriteObjectRef( aux, fNeighbors[dir] ); end; Writer.WriteBuffer( 'Blocked', fBlocked, sizeof(fBlocked) ); Writer.WriteBoolean( 'AllBlocked', fAllBlocked ); aux := ''; end; // RegisterBackup procedure RegisterBackup; begin BackupInterfaces.RegisterClass( TSpontaneousBuilding ); end; end.
unit DW.iOSapi.Foundation; interface uses Macapi.ObjectiveC, iOSapi.Foundation; type NSLocaleKey = NSString; NSLocaleClass = interface(NSObjectClass) ['{4597A459-6F9B-49F4-8C80-3F8ED8FDB9D1}'] {class} function autoupdatingCurrentLocale: NSLocale; cdecl; {class} function availableLocaleIdentifiers: NSArray; cdecl; {class} function canonicalLanguageIdentifierFromString(&string: NSString): NSString; cdecl; {class} function canonicalLocaleIdentifierFromString(&string: NSString): NSString; cdecl; {class} function characterDirectionForLanguage(isoLangCode: NSString): NSLocaleLanguageDirection; cdecl; {class} function commonISOCurrencyCodes: NSArray; cdecl; {class} function componentsFromLocaleIdentifier(&string: NSString): NSDictionary; cdecl; {class} function currentLocale: NSLocale; cdecl; {class} function ISOCountryCodes: NSArray; cdecl; {class} function ISOCurrencyCodes: NSArray; cdecl; {class} function ISOLanguageCodes: NSArray; cdecl; {class} function lineDirectionForLanguage(isoLangCode: NSString): NSLocaleLanguageDirection; cdecl; {class} function localeIdentifierFromComponents(dict: NSDictionary): NSString; cdecl; {class} function localeIdentifierFromWindowsLocaleCode(lcid: UInt32): NSString; cdecl; {class} function localeWithLocaleIdentifier(ident: NSString): Pointer; cdecl; {class} function preferredLanguages: NSArray; cdecl; {class} function systemLocale: NSLocale; cdecl; {class} function windowsLocaleCodeFromLocaleIdentifier(localeIdentifier: NSString): UInt32; cdecl; end; NSLocale = interface(NSObject) ['{6D772B7D-BE16-4960-A10B-D5BCEE8D3B94}'] function alternateQuotationBeginDelimiter: NSString; cdecl; function alternateQuotationEndDelimiter: NSString; cdecl; function calendarIdentifier: NSString; cdecl; function collationIdentifier: NSString; cdecl; function collatorIdentifier: NSString; cdecl; function countryCode: NSString; cdecl; function currencyCode: NSString; cdecl; function currencySymbol: NSString; cdecl; function decimalSeparator: NSString; cdecl; [MethodName('displayNameForKey:value:')] function displayNameForKey(key: NSLocaleKey; value: Pointer): NSString; cdecl; function exemplarCharacterSet: NSCharacterSet; cdecl; function groupingSeparator: NSString; cdecl; function init: Pointer; cdecl; function initWithCoder(aDecoder: NSCoder): Pointer; cdecl; function initWithLocaleIdentifier(&string: NSString): Pointer; cdecl; function languageCode: NSString; cdecl; function localeIdentifier: NSString; cdecl; function localizedStringForCalendarIdentifier(calendarIdentifier: NSString): NSString; cdecl; function localizedStringForCollationIdentifier(collationIdentifier: NSString): NSString; cdecl; function localizedStringForCollatorIdentifier(collatorIdentifier: NSString): NSString; cdecl; function localizedStringForCountryCode(countryCode: NSString): NSString; cdecl; function localizedStringForCurrencyCode(currencyCode: NSString): NSString; cdecl; function localizedStringForLanguageCode(languageCode: NSString): NSString; cdecl; function localizedStringForLocaleIdentifier(localeIdentifier: NSString): NSString; cdecl; function localizedStringForScriptCode(scriptCode: NSString): NSString; cdecl; function localizedStringForVariantCode(variantCode: NSString): NSString; cdecl; function objectForKey(key: NSLocaleKey): Pointer; cdecl; function quotationBeginDelimiter: NSString; cdecl; function quotationEndDelimiter: NSString; cdecl; function scriptCode: NSString; cdecl; function usesMetricSystem: Boolean; cdecl; function variantCode: NSString; cdecl; end; TNSLocale = class(TOCGenericImport<NSLocaleClass, NSLocale>) end; implementation end.
uses ptcGraph, ptcCrt, functions; type func_t = function (x : real) : real; const AX = -5; BX = 5; AY = -20; BY = 20; intr_a = -2; intr_b = -1; INF = 10000000; YEL = Yellow; SPL_X = 10; SPL_Y = 40; WIDTH = 5; var intr1, intr2, intr3, intr_debug : real; I1, I2, I3, I, I_debug : real; eps_root, eps_integral : real; n0, debug, graph : longint; col, delta_col : word; t, max_f : real; gd, gm, pr1, pr2 : integer; size_x, size_y : integer; {F+} {Поиск точки пересечения} function intersection(f, g, fd1, gd1, fd2, gd2 : func_t; a, b, EPS : real): real; var c : real; begin writeln('Intermediate values in form left_bound, right_bound, function value at root'); while (abs(b - a) > EPS) do begin c := (a + b) / 2; writeln(a:3:pr1, ' ', b:3:pr1, ' ', (f(c) - g(c)):3:pr1); if ((fd1(c) - gd1(c)) * (fd2(c) - gd2(c)) > 0) then begin c := (a * (f(b) - g(b)) - b * (f(a) - g(a))) / ((f(b) - g(b)) - (f(a) - g(a))); a := c; c := b - (f(b) - g(b)) / (fd1(b) - gd1(b)); b := c; end else begin c := (a * (f(b) - g(b)) - b * (f(a) - g(a))) / ((f(b) - g(b)) - (f(a) - g(a))); b := c; c := a - (f(a) - g(a)) / (fd1(a) - gd1(a)); a := c; end; end; c := (a + b) / 2; intersection := (a + b) / 2; end; {Подсчет интеграла} function integral(f : func_t; a, b, EPS : real; n0 : longint) : real; var n, j: longint; h, I, I1: real; begin n := n0; I := INF; I1 := 0; Writeln('Integral, difference between integral and previos integral, number of split points'); while ((abs(I - I1) / 3) > EPS) do begin I1 := I; I := 0; h := (b - a) / n; for j := 0 to n - 1 do begin I := I + f(a + (j + 0.5) * h); end; I := I * h; writeln(I:3:pr2, ' ', (I - I1):3:pr2, ' ', n); n := 2 * n; end; integral := I; end; {Отображение точки на оси ОХ графика в значение функции в этой точке} function point_graph(f : func_t; x : real) : integer; begin point_graph := trunc(((-f(AX + x / size_x * (BX - AX))) - AY) / (BY - AY) * size_y); end; {Рисование системы координат} procedure draw_field(); var i : integer; begin detectgraph(gd, gm); InitGraph(gd, gm, ''); size_x := GetMaxX; size_y := GetMaxY; col := GetMaxColor; delta_col := col div 4; SetColor(col); line(0, size_y div 2, size_x, size_y div 2); line (size_x div 2, 0, size_x div 2, size_y); for i := 0 to SPL_X do begin line(i * size_x div SPL_X, size_y div 2 - WIDTH, i * size_x div SPL_X, size_y div 2 + WIDTH); end; for i := 0 to SPL_Y do begin line(size_x div 2 - WIDTH, i * size_y div SPL_Y, size_x div 2 + WIDTH, i * size_y div SPL_Y); end; end; {Рисование графика} procedure draw_graph(f : func_t; col : word); var x : integer; begin SetColor(col); MoveTo(0, point_graph(f, 0)); for x := 1 to size_x do begin if (x <> round(size_x / (BX - AX) * 3)) then LineTo(x, point_graph(f, x)) else MoveTo(x, point_graph(f, x + 1)); end; end; {Закрашивание области} procedure fill_area(); begin SetFillStyle(2, YEL); FloodFill(round(size_x / (BX - AX) * 3.5), point_graph(@f1, round(size_x / (BX - AX) * 3.5)) + 5, YEL); end; {Отображение точки функции в точку на графике} function func_to_graph(x : real) : integer; begin func_to_graph := trunc((x - AX) / (BX - AX) * size_x); end; {Подписи для графика} procedure draw_labels(); var t : string; begin SetColor(col); OutTextXY(size_x div SPL_X * (SPL_X div 2 + 1), size_y div 2 - 20, '1'); OutTextXY(size_x div 2 - 10, size_y div SPL_Y * (SPL_Y div 2 - 1), '1'); SetColor(col); SetLineStyle(1, 1, 1); Line(func_to_graph(intr1), point_graph(@f1, func_to_graph(intr1)), func_to_graph(intr1), size_y div 2); Str(intr1:3:pr1, t); OutTextXY(func_to_graph(intr1), size_y div 2 + 10, t); Line(func_to_graph(intr2), point_graph(@f2, func_to_graph(intr2)), func_to_graph(intr2), size_y div 2); Str(intr2:3:pr1, t); OutTextXY(func_to_graph(intr2), size_y div 2 + 20, t); Line(func_to_graph(intr3), point_graph(@f2, func_to_graph(intr3)), func_to_graph(intr3), size_y div 2); Str(intr3:3:pr1, t); OutTextXY(func_to_graph(intr3), size_y div 2 + 10, t); Str(I:3:pr2, t); t := 'S = ' + t; OutTextXY(func_to_graph(-1), size_y div 3, t); end; {Поиск максимума} function max(a, b : real) : real; begin if (a < b) then max := b else max := a; end; {Подсчет знаков для точности} function count_precision(eps : real) : integer; var a : real; n : integer; begin a := 0.1; n := 1; while (a > eps) do begin inc(n); a := 0.1 * a; end; count_precision := n; end; begin Writeln('Enable debug mode?(0 - no, 1 - yes)'); Readln(debug); if (debug = 0) then begin Writeln('Enter the precision for root calculation'); Readln(eps_root); pr1 := count_precision(eps_root); Writeln('Enter the precision for integral calculation'); Readln(eps_integral); pr2 := count_precision(eps_integral); Writeln('Enter the initial number of split points'); Readln(n0); Writeln('Show graph? (0 - no, 1 - yes)'); Readln(graph); Writeln('Intersection of f1 and f3'); intr1 := intersection(@f1, @f3, @f1d1, @f3d1, @f1d2, @f3d2, intr_a, intr_b, eps_root); Writeln('Intersection of f2 and f3'); intr2 := intersection(@f2, @f3, @f2d1, @f3d1, @f2d2, @f3d2, intr_a, intr_b, eps_root); Writeln('Intersection of f1 and f2'); intr3 := intersection(@f1, @f2, @f1d1, @f2d1, @f1d2, @f2d2, intr_a, intr_b, eps_root); Writeln('Integral of f1'); I1 := integral(@f1, intr1, intr3, eps_integral, n0); Writeln('Integral of f3'); I2 := integral(@f3, intr1, intr2, eps_integral, n0); Writeln('Integral of f2'); I3 := integral(@f2, intr2, intr3, eps_integral, n0); Writeln('Intersection points:'); Writeln(intr1:2:pr1, ' ', f1(intr1):2:pr1); Writeln(intr2:2:pr1, ' ', f3(intr2):2:pr1); Writeln(intr3:2:pr1, ' ', f2(intr3):2:pr1); t := (intr_a + intr_b) / 2; max_f := max(f1(t), max(f2(t), f3(t))); if (max_f = f1(t)) then I := I1 - I2 - I3 else if (max_f = f2(t)) then I := I3 - I1 - I2 else I := I2 - I1 - I3; Writeln('Square = ', I:3:pr2); if (graph = 1) then begin draw_field; draw_graph(@f1, YEL); draw_graph(@f2, YEL); draw_graph(@f3, YEL); fill_area; draw_graph(@f1, col - delta_col); draw_graph(@f2, col - 2 * delta_col); draw_graph(@f3, col - 3 * delta_col); draw_labels; readln; closegraph; end; end else begin Writeln('Function for root debug: y1 = x^2, y2 = 1 on seg. [0, 5], EPS = 0.001'); pr1 := count_precision(0.001); intr_debug := intersection(@root_debug1, @root_debug2, @root_debug1d1, @root_debug2d1, @root_debug1d2, @root_debug2d2, 0, 5, 0.001); Writeln('x = ', intr_debug:3:pr1); Writeln('Function for integral debug: y = x on seg. [0, 4], EPS = 0.001, n0 = 2'); pr2 := count_precision(0.001); I_debug := integral(@integral_debug, 0, 4, 0.001, 2); Writeln('Integral = ', I_debug:3:pr2); end; end.
(* * 计算 MurmurHash64,根据网友 歼10 的代码修改,支持大文件。 * * https://blog.csdn.net/baiyunpeng42/article/details/45339937 * https://blog.csdn.net/chenxing888/article/details/5912183 *) unit iocp_mmHash; interface {$I in_iocp.inc} uses {$IFDEF DELPHI_XE7UP} Winapi.Windows, System.SysUtils, {$ELSE} Windows, SysUtils, {$ENDIF} iocp_utils; type {$IF CompilerVersion < 18.5} FILE_SIZE = Cardinal; {$ELSE} FILE_SIZE = Int64; {$IFEND} function MurmurHash64(const Key: Pointer; Size: Cardinal): UInt64; overload; function MurmurHash64(const FileName: string): UInt64; overload; function MurmurHash64(Handle: THandle): UInt64; overload; function MurmurHashPart64(Handle: THandle; Offset: FILE_SIZE; PartSize: Cardinal): UInt64; implementation type PMurmurHashInf = ^TMurmurHashInf; TMurmurHashInf = record h1, h2: Cardinal; Data: PInteger; K1, K2: Integer; // 加入,免频繁分配 Tail: array[0..3] of Byte; Result: UInt64; // 结果 end; const m: Cardinal = $5bd1e995; r: Integer = 24; procedure MurmurHash64Init(Inf: PMurmurHashInf; Size: Int64); var KeySize: ULARGE_INTEGER; begin // 源码 Size 为 Cardinal,xor 一次 KeySize.QuadPart := Size; Inf^.h1 := ($EE6B27EB xor KeySize.HighPart) xor KeySize.LowPart; // 两次 Inf^.h2 := 0; Inf^.Data := nil; end; procedure MurmurHash64Update(Inf: PMurmurHashInf; const Key: Pointer; var Size: Cardinal); begin // Size 应是 8 的倍数 Inf^.Data := PInteger(Key); while (Size >= 8) do begin Inf^.K1 := Inf^.Data^; Inc(Inf^.Data); Inf^.K1 := Inf^.K1 * m; Inf^.K1 := Inf^.K1 xor (Inf^.K1 shr r); Inf^.k1 := Inf^.k1 * m; Inf^.h1 := Inf^.h1 * m; Inf^.h1 := Inf^.h1 xor Inf^.k1; Dec(Size, 4); //\\ Inf^.k2 := Inf^.Data^; Inc(Inf^.Data); Inf^.k2 := Inf^.k2 * m; Inf^.k2 := Inf^.k2 xor (Inf^.k2 shr r); Inf^.K2 := Inf^.K2 * m; Inf^.h2 := Inf^.h2 * m; Inf^.h2 := Inf^.h2 xor Inf^.k2; Dec(Size, 4); end; end; procedure MurmurHash64Final(Inf: PMurmurHashInf; const Key: Pointer; var Size: Cardinal); begin // 处理不足 8 字节的内容 if (Size >=4) then begin Inf^.k1 := Inf^.Data^; Inc(Inf^.Data); Inf^.k1 := Inf^.k1 * m; Inf^.K1 := Inf^.k1 xor (Inf^.k1 shr r); Inf^.k1 := Inf^.k1 * m; Inf^.h1 := Inf^.h1 * m; Inf^.h1 := Inf^.h1 xor Inf^.k1; Dec(Size, 4); end; case Size of 3: begin Integer(Inf^.Tail) := Inf^.Data^; Inf^.Tail[3] := 0; Inf^.h2 := Inf^.h2 xor Integer(Inf^.Tail); Inf^.h2 := Inf^.h2 * m; end; 2: begin Inf^.h2 := Inf^.h2 xor PWord(Inf^.Data)^; Inf^.h2 := Inf^.h2 * m; end; 1: begin Inf^.h2 := Inf^.h2 xor PByte(Inf^.Data)^; Inf^.h2 := Inf^.h2 * m; end; end; Inf^.h1 := Inf^.h1 xor (Inf^.h2 shr 18); Inf^.h1 := Inf^.h1 * m; Inf^.h2 := Inf^.h2 xor (Inf^.h1 shr 22); Inf^.h2 := Inf^.h2 * m; Inf^.h1 := Inf^.h1 xor (Inf^.h2 shr 17); Inf^.h1 := Inf^.h1 * m; Inf^.h2 := Inf^.h2 xor (Inf^.h1 shr 19); Inf^.h2 := Inf^.h2 * m; Inf^.Result := Inf^.h1; Inf^.Result := (Inf^.Result shl 32) or Inf^.h2; end; function MurmurHash64(const Key: Pointer; Size: Cardinal): UInt64; var MurmurHash: TMurmurHashInf; begin // 计算内存的 MurmurHash MurmurHash64Init(@MurmurHash, Size); MurmurHash64Update(@MurmurHash, Key, Size); MurmurHash64Final(@MurmurHash, Key, Size); Result := MurmurHash.Result; end; function MurmurHash64(const FileName: string): UInt64; var Handle: THandle; begin // 计算文件的 MurmurHash(支持大文件) Handle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); if (Handle = INVALID_HANDLE_VALUE) then Result := 0 else try Result := MurmurHash64(Handle); finally CloseHandle(Handle); end; end; function MurmurHash64(Handle: THandle): UInt64; var Inf: SYSTEM_INFO; MapHandle: THandle; FileSize, Offset: FILE_SIZE; Granularity, PartSize: Cardinal; MapOffset: LARGE_INTEGER; ViewPointer: Pointer; MurmurHash: TMurmurHashInf; begin // 计算文件句柄的 MurmurHash(支持大文件) if (Handle = 0) or (Handle = INVALID_HANDLE_VALUE) then begin Result := 0; Exit; end; FileSize := GetFileSize64(Handle); MurmurHash64Init(@MurmurHash, FileSize); MapHandle := CreateFileMapping(Handle, nil, PAGE_READONLY, 0, 0, nil); if (MapHandle <> 0) then try {$IFDEF DELPHI_7} GetSystemInfo(Inf); // 取内存分配精度 {$ELSE} GetSystemInfo(&Inf); // 取内存分配精度 {$ENDIF} Granularity := Inf.dwAllocationGranularity * 80; // 8 的倍数 Offset := 0; while (FileSize > 0) do begin if (FileSize > Granularity) then PartSize := Granularity else PartSize := FileSize; // 映射: 位移=Offset, 长度=PartSize(8的倍数) MapOffset.QuadPart := Offset; ViewPointer := MapViewOfFile(MapHandle, FILE_MAP_READ, MapOffset.HighPart, MapOffset.LowPart, PartSize); Inc(Offset, PartSize); Dec(FileSize, PartSize); if (ViewPointer <> nil) then try if (PartSize >= 8) then MurmurHash64Update(@MurmurHash, ViewPointer, PartSize); if (FileSize = 0) then MurmurHash64Final(@MurmurHash, ViewPointer, PartSize); finally UnmapViewOfFile(ViewPointer); end; end; finally CloseHandle(MapHandle); end; Result := MurmurHash.Result; end; function MurmurHashPart64(Handle: THandle; Offset: FILE_SIZE; PartSize: Cardinal): UInt64; var MapHandle: THandle; MapOffset: LARGE_INTEGER; ViewPointer: Pointer; MurmurHash: TMurmurHashInf; begin // 计算文件范围的 MurmurHash(支持大文件) if (Handle = 0) or (Handle = INVALID_HANDLE_VALUE) or (PartSize = 0) then begin Result := 0; Exit; end; MurmurHash64Init(@MurmurHash, PartSize); MapHandle := CreateFileMapping(Handle, nil, PAGE_READONLY, 0, 0, nil); if (MapHandle <> 0) then try // 映射范围: 位移=Offset, 长度=PartSize MapOffset.QuadPart := Offset; ViewPointer := MapViewOfFile(MapHandle, FILE_MAP_READ, MapOffset.HighPart, MapOffset.LowPart, PartSize); if (ViewPointer <> nil) then try MurmurHash64Update(@MurmurHash, ViewPointer, PartSize); MurmurHash64Final(@MurmurHash, ViewPointer, PartSize); finally UnmapViewOfFile(ViewPointer); end; finally CloseHandle(MapHandle); end; Result := MurmurHash.Result; end; end.
unit BaiduMapAPI.LocationService; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 定位服务 单元 //官方链接:http://lbsyun.baidu.com/ //TAndroidBaiduMapLocationService 百度地图 定位服务 interface uses FMX.Maps; type TOnUserLocationWillChanged = procedure(Sender:TObject; UserLocation:TMapCoordinate) of object; IBaiduMapLocationService = interface ['{71804C20-5F9E-4487-BE8D-DE833B68F071}'] procedure InitLocation; procedure StarLocation; procedure StopLocation; end; TBaiduMapLocationService = class(TInterfacedObject, IBaiduMapLocationService) private FUserLocation:TMapCoordinate; FOnUserLocationWillChanged:TOnUserLocationWillChanged; protected procedure DoInitLocation; virtual; abstract; procedure DoStarLocation; virtual; abstract; procedure DoStopLocation; virtual; abstract; procedure UserLocationWillChanged(Coordinate:TMapCoordinate); public procedure InitLocation; procedure StarLocation; procedure StopLocation; constructor Create; virtual; destructor Destroy; override; property UserLocation:TMapCoordinate read FUserLocation; property OnUserLocationWillChanged:TOnUserLocationWillChanged read FOnUserLocationWillChanged write FOnUserLocationWillChanged; end; TBaiduMapLocation = class(TObject) private FLocationService:TBaiduMapLocationService; public constructor Create; destructor Destroy; override; property LocationService:TBaiduMapLocationService read FLocationService; end; implementation {$IFDEF IOS} uses BaiduMapAPI.LocationService.iOS; {$ENDIF} {$IFDEF ANDROID} uses BaiduMapAPI.LocationService.Android; {$ENDIF ANDROID} { TBaiduMapLocationService } constructor TBaiduMapLocationService.Create; begin inherited Create; end; destructor TBaiduMapLocationService.Destroy; begin inherited; end; procedure TBaiduMapLocationService.InitLocation; begin DoInitLocation; end; procedure TBaiduMapLocationService.StarLocation; begin DoStarLocation; end; procedure TBaiduMapLocationService.StopLocation; begin DoStopLocation; end; procedure TBaiduMapLocationService.UserLocationWillChanged( Coordinate: TMapCoordinate); begin if Assigned(FOnUserLocationWillChanged) then FOnUserLocationWillChanged(Self, Coordinate); //更新用户位置 FUserLocation:=Coordinate; end; { TBaiduMapLocation } constructor TBaiduMapLocation.Create; begin inherited Create; {$IFDEF IOS} FLocationService:=TiOSBaiduMapLocationService.Create; {$ENDIF} {$IFDEF ANDROID} FLocationService:=TAndroidBaiduMapLocationService.Create; {$ENDIF ANDROID} end; destructor TBaiduMapLocation.Destroy; begin FLocationService.Free; inherited; end; end.
unit GetComputerInfo; interface uses Winapi.Windows, System.SysUtils, NB30, WinSock; function GetComputerNetName: string; function GetLocalIP: string; function GetAdapterInfo(Lana: Char): string; function GetMACAddress: string; implementation // Функция определения имени компьютера function GetComputerNetName: string; var buffer: array[0..255] of char; size: dword; begin size := 256; if GetComputerName(buffer, size) then Result := buffer else Result := '' end; // Функция определения IP адреса function GetLocalIP: string; const WSVer = $101; var wsaData: TWSAData; P: PHostEnt; Buf: array [0..127] of Char; begin Result := ''; if WSAStartup(WSVer, wsaData) = 0 then begin if GetHostName(@Buf, 128) = 0 then begin P := GetHostByName(@Buf); if P <> nil then Result := iNet_ntoa(PInAddr(p^.h_addr_list^)^); end; WSACleanup; end; end; // Функция получения информации от сетевого адаптера function GetAdapterInfo(Lana: Char): string; var Adapter: TAdapterStatus; NCB: TNCB; begin FillChar(NCB, SizeOf(NCB), 0); NCB.ncb_command := Char(NCBRESET); NCB.ncb_lana_num := AnsiChar(Lana); if Netbios(@NCB) <> Char(NRC_GOODRET) then begin Result := 'Адрес не известен'; Exit; end; FillChar(NCB, SizeOf(NCB), 0); NCB.ncb_command := Char(NCBASTAT); NCB.ncb_lana_num := AnsiChar(Lana); NCB.ncb_callname := '*'; FillChar(Adapter, SizeOf(Adapter), 0); NCB.ncb_buffer := @Adapter; NCB.ncb_length := SizeOf(Adapter); if Netbios(@NCB) <> Char(NRC_GOODRET) then begin Result := 'Адрес не известен'; Exit; end; Result := IntToHex(Byte(Adapter.adapter_address[0]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[1]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[2]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[3]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[4]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[5]), 2); end; // Функция определения МАК адреса адаптера function GetMACAddress: string; var AdapterList: TLanaEnum; NCB: TNCB; begin FillChar(NCB, SizeOf(NCB), 0); NCB.ncb_command := Char(NCBENUM); NCB.ncb_buffer := @AdapterList; NCB.ncb_length := SizeOf(AdapterList); Netbios(@NCB); if Byte(AdapterList.length) > 0 then Result := GetAdapterInfo(Char(AdapterList.lana[0])) else Result := 'Адрес не известен'; end; end.
unit MdiChilds.SplitAltayPriceByZone; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvBaseDlg, JvSelectDirectory, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ExtCtrls, MdiChilds.reg, MdiChilds.ProgressForm, GsDocument, ActionHandler; type TFmSplitAltayPriceByZone = class(TFmProcess) edtDocument: TLabeledEdit; btnOpen: TButton; seZoneCount: TSpinEdit; Label1: TLabel; edtDestPath: TLabeledEdit; btnSelect: TButton; JvSelectDirectory: TJvSelectDirectory; OpenDialog: TOpenDialog; procedure btnOpenClick(Sender: TObject); procedure btnSelectClick(Sender: TObject); private procedure ExtractZone(Document: TGsDocument; I: Integer); protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public { Public declarations } end; TSplitAltayPriceByZoneActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmSplitAltayPriceByZone: TFmSplitAltayPriceByZone; implementation {$R *.dfm} uses GlobalData; procedure TFmSplitAltayPriceByZone.btnOpenClick(Sender: TObject); begin if OpenDialog.Execute then edtDocument.Text := OpenDialog.FileName; end; procedure TFmSplitAltayPriceByZone.btnSelectClick(Sender: TObject); begin if JvSelectDirectory.Execute then edtDestPath.Text := IncludeTrailingPathDelimiter(JvSelectDirectory.Directory); end; procedure TFmSplitAltayPriceByZone.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var Document: TGsDocument; I: Integer; begin Document := NewGsDocument; try Document.LoadFromFile(edtDocument.Text); for I := seZoneCount.MinValue to seZoneCount.Value do ExtractZone(Document, I); finally Document.Free; end; end; procedure TFmSplitAltayPriceByZone.ExtractZone(Document: TGsDocument; I: Integer); var L: TList; ResultDocument: TGsDocument; Index: Integer; Elem: TGsPriceElement; ZoneIndex: Integer; ResultElem: TGsPriceElement; begin ResultDocument := TGsDocument.Create; ResultDocument.DocumentType := dtPrice; try L := TList.Create; try Document.Workers.EnumItems(L, TGsPriceElement, True); ZoneIndex := 0; for Index := 0 to L.Count - 1 do begin Inc(ZoneIndex); Elem := TGsPriceElement(L[Index]); if ZoneIndex = I then begin ResultElem := TGsPriceElement.Create(ResultDocument); ResultElem.Assign(Elem); ResultDocument.Workers.Add(ResultElem); end; if ZoneIndex >= seZoneCount.Value then ZoneIndex := 0; end; finally L.Free; end; //Машины L := TList.Create; try Document.Mashines.EnumItems(L, TGsPriceElement, True); ZoneIndex := 0; for Index := 0 to L.Count - 1 do begin Inc(ZoneIndex); Elem := TGsPriceElement(L[Index]); if ZoneIndex = I then begin ResultElem := TGsPriceElement.Create(ResultDocument); ResultElem.Assign(Elem); ResultDocument.Mashines.Add(ResultElem); end; if ZoneIndex >= seZoneCount.Value then ZoneIndex := 0; end; finally L.Free; end; //Materials L := TList.Create; try Document.Materials.EnumItems(L, TGsPriceElement, True); ZoneIndex := 0; for Index := 0 to L.Count - 1 do begin Inc(ZoneIndex); Elem := TGsPriceElement(L[Index]); if ZoneIndex = I then begin ResultElem := TGsPriceElement.Create(ResultDocument); ResultElem.Assign(Elem); ResultDocument.Materials.Add(ResultElem); end; if ZoneIndex >= seZoneCount.Value then ZoneIndex := 0; end; finally L.Free; end; //Mechanics L := TList.Create; try Document.Mechanics.EnumItems(L, TGsPriceElement, True); ZoneIndex := 0; for Index := 0 to L.Count - 1 do begin Inc(ZoneIndex); Elem := TGsPriceElement(L[Index]); if ZoneIndex = I then begin ResultElem := TGsPriceElement.Create(ResultDocument); ResultElem.Assign(Elem); ResultDocument.Mechanics.Add(ResultElem); end; if ZoneIndex >= seZoneCount.Value then ZoneIndex := 0; end; finally L.Free; end; ResultDocument.SaveToFile(edtDestPath.Text + 'Ценник_зона ' + IntToStr(I)+'.xml'); finally ResultDocument.Free; end; end; { TSplitAltayPriceByZoneActionHandler } procedure TSplitAltayPriceByZoneActionHandler.ExecuteAction; begin TFmSplitAltayPriceByZone.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Разделить последовательно ценник по зонам', hkDefault, TSplitAltayPriceByZoneActionHandler); end.
unit ObjectIndex; interface uses SysUtils, Classes; type TObjectID = integer; type PIndexEntry = ^TIndexEntry; TIndexEntry = packed record Id : TObjectID; Obj : TObject; Flg : boolean; end; const MaxIndexSixe = $7FFFFFFF div sizeof(TIndexEntry); // high(integer); Drives Delphi crazy // IndexEntry utility function function IndexEntry(Id : TObjectID; Obj : TObject; Flg : boolean) : TIndexEntry; type TObjectIndex = class; TObjectHash = class; EObjectIndexError = class(Exception); PIndexArray = ^TIndexArray; TIndexArray = array[0..MaxIndexSixe - 1] of TIndexEntry; PEntryHash = ^TEntryHash; TEntryHash = array[0..255] of pointer; TItrEntry = procedure(var Entry : TIndexEntry) of object; TObjectHash = class public constructor Create; destructor Destroy; override; private fHash : TEntryHash; private function Hash1(id : integer) : integer; function Hash2(id : integer) : integer; public procedure AddEntry(Entry : TIndexEntry); procedure AddObject(Id : TObjectID; Obj : TObject); procedure Iterate(proc : TItrEntry); private function GetEntry(Id : TObjectID) : PIndexEntry; public property Entries[Id : TObjectID] : PIndexEntry read GetEntry; end; TObjectIndex = class public constructor Create(InitialSize : integer); destructor Destroy; override; private fIndexArray : PIndexArray; fSize : integer; fCount : integer; public procedure AddEntry(Entry : TIndexEntry); procedure AddObject(Id : TObjectID; Obj : TObject); procedure DeleteObject(Id : TObjectID); function Exists(Id : TObjectID) : boolean; procedure Iterate(proc : TItrEntry); private function FindId(Id : TObjectID) : integer; function GetPlaceOf(Id : TObjectID) : integer; procedure InsertAt(place : integer; Entry : TIndexEntry); procedure DeleteAt(place : integer); function GetObject(Id : TObjectID) : TObject; function GetIdIndex(Id : TObjectID) : integer; function GetIndexEntry(index : integer) : TIndexEntry; procedure SetIndexEntry(index : integer; Entry : TIndexEntry); public property Count : integer read fCount write fCount; property Index [Id : TObjectID] : TObject read GetObject write AddObject; default; property IdIndex[Id : TObjectID] : integer read GetIdIndex; property Entries[idx : integer] : TIndexEntry read GetIndexEntry write SetIndexEntry; end; implementation // TObjectIndex const NoPlace = -1; function IndexEntry(Id : TObjectID; Obj : TObject; Flg : boolean) : TIndexEntry; begin result.Id := Id; result.Obj := Obj; result.Flg := Flg; end; type TIntRec = record b1 : byte; b2 : byte; b3 : byte; b4 : byte; end; // TObjectHash constructor TObjectHash.Create; var i : integer; E : PEntryHash; begin inherited; for i := low(fHash) to high(fHash) do begin New(E); FillChar(E^, sizeof(E^), 0); fHash[i] := E; end; end; destructor TObjectHash.Destroy; var i, j : integer; Hash : PEntryHash; begin for i := low(fHash) to high(fHash) do begin Hash := PEntryHash(fHash[i]); for j := low(Hash^) to high(Hash^) do TObjectIndex(Hash[j]).Free; end; end; function TObjectHash.Hash1(id : integer) : integer; begin with TIntRec(id) do result := (b1 + b2 + b3 + b4) mod 256; end; function TObjectHash.Hash2(id : integer) : integer; begin with TIntRec(id) do result := (b1 + 2*b2 + 3*b3 + b4) mod 256; end; procedure TObjectHash.AddEntry(Entry : TIndexEntry); var idx1 : integer; idx2 : integer; H1 : PEntryHash; OIdx : TObjectIndex; begin idx1 := Hash1(Entry.Id); idx2 := Hash2(Entry.Id); H1 := fHash[idx1]; OIdx := TObjectIndex(H1[idx2]); if OIdx = nil then begin OIdx := TObjectIndex.Create(256); H1[idx2] := OIdx; end; OIdx.AddEntry(Entry); end; procedure TObjectHash.AddObject(Id : TObjectID; Obj : TObject); begin AddEntry(IndexEntry(Id, Obj, false)); end; procedure TObjectHash.Iterate(proc : TItrEntry); var H : PEntryHash; i, j : integer; OIdx : TObjectIndex; begin for i := low(fHash) to high(fHash) do begin H := PEntryHash(fHash[i]); for j := low(H^) to high(H^) do begin OIdx := TObjectIndex(H[j]); if OIdx <> nil then OIdx.Iterate(proc); end; end; end; function TObjectHash.GetEntry(Id : TObjectID) : PIndexEntry; var idx1, idx2 : integer; OIdx : TObjectIndex; eidx : integer; begin idx1 := Hash1(Id); idx2 := Hash2(Id); OIdx := TObjectIndex(PEntryHash(fHash[idx1])[idx2]); if OIdx <> nil then begin eidx := OIdx.IdIndex[Id]; if eidx <> NoPlace then result := @OIdx.fIndexArray[eidx] else result := nil; end else result := nil; end; // TObjectIndex constructor TObjectIndex.Create(InitialSize : integer); begin inherited Create; fSize := InitialSize; ReallocMem(fIndexArray, fSize * sizeof(fIndexArray[0])); end; destructor TObjectIndex.Destroy; begin ReallocMem(fIndexArray, 0); inherited; end; procedure TObjectIndex.AddEntry(Entry : TIndexEntry); var place : integer; begin if fCount = fSize then begin //inc(fSize, fSize * 3 div 10 + 1); inc(fSize, fSize div 8); ReallocMem(fIndexArray, fSize * sizeof(fIndexArray[0])); end; place := GetPlaceOf(Entry.Id); if place = fCount then begin fIndexArray[fCount] := Entry; inc(fCount); end else begin {$IFDEF DEBUGGING} Assert((place < fCount) and (fIndexArray[place].Id <> Id), 'Trying to reinsert an object in the index...'); {$ENDIF} InsertAt(place, Entry); inc(fCount); end; end; procedure TObjectIndex.AddObject(Id : TObjectID; Obj : TObject); begin AddEntry(IndexEntry(Id, Obj, false)); end; procedure TObjectIndex.DeleteObject(Id : TObjectID); var place : integer; begin place := FindId(Id); if (place <> NoPlace) and (fIndexArray[place].Id = Id) then begin DeleteAt(place); dec(fCount); end; end; function TObjectIndex.Exists(Id : TObjectID) : boolean; var place : integer; begin place := FindId(Id); result := (place <> NoPlace) and (fIndexArray[place].Id = Id); end; procedure TObjectIndex.Iterate(proc : TItrEntry); var i : integer; begin for i := 0 to pred(fCount) do proc(fIndexArray[i]); end; function TObjectIndex.FindId(Id : TObjectID) : integer; var l : integer; m : integer; h : integer; c : integer; begin if fCount > 0 then begin l := 0; h := pred(fCount); repeat m := (l + h) div 2; c := fIndexArray[m].Id; if Id >= c then l := m else h := m until (h - l <= 1) or (c = Id); if Id = fIndexArray[l].Id then result := l else result := h end else result := NoPlace; end; function TObjectIndex.GetPlaceOf(Id : TObjectID) : integer; begin if (fCount = 0) or (fIndexArray[0].Id >= Id) then result := 0 else if fIndexArray[pred(fCount)].Id <= Id then result := fCount else result := FindId(Id); end; procedure TObjectIndex.InsertAt(place : integer; Entry : TIndexEntry); begin move(fIndexArray[place], fIndexArray[place+1], (fCount - place)*sizeof(TIndexEntry)); fIndexArray[place] := Entry; end; procedure TObjectIndex.DeleteAt(place : integer); begin move(fIndexArray[place+1], fIndexArray[place], fCount - place - 1); end; function TObjectIndex.GetObject(Id : TObjectID) : TObject; var place : integer; begin place := GetPlaceOf(Id); if place <> NoPlace then result := fIndexArray[place].Obj else result := nil; end; function TObjectIndex.GetIdIndex(Id : TObjectID) : integer; var Last : TObjectID; begin if fCount > 0 then begin Last := fIndexArray[pred(fCount)].Id; if Id = Last then result := pred(fCount) else if Id < Last then begin result := FindId(Id); if fIndexArray[result].Id <> Id then result := NoPlace; end else result := NoPlace end else result := NoPlace; end; function TObjectIndex.GetIndexEntry(index : integer) : TIndexEntry; begin if index < fCount then result := fIndexArray[index] else raise EObjectIndexError.Create(''); end; procedure TObjectIndex.SetIndexEntry(index : integer; Entry : TIndexEntry); begin if index < fCount then fIndexArray[index] := Entry else raise EObjectIndexError.Create(''); end; end.
unit ValidateSessionUnit; interface uses SysUtils, BaseExampleUnit; type TValidateSession = class(TBaseExample) public procedure Execute(SessionGuid: String; MemberId: integer); end; implementation uses UserUnit; procedure TValidateSession.Execute(SessionGuid: String; MemberId: integer); var ErrorString: String; IsSessionValid: boolean; IsSessionValidStr: String; begin IsSessionValid := Route4MeManager.User.IsSessionValid( SessionGuid, MemberId, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin if IsSessionValid then IsSessionValidStr := 'is valid' else IsSessionValidStr := 'not is valid'; WriteLn(Format('ValidateSession executed successfully, session %s', [IsSessionValidStr])); WriteLn(''); end else WriteLn(Format('ValidateSession error: "%s"', [ErrorString])); end; end.
unit daDataProviderSuperFactory; // Модуль: "w:\common\components\rtl\Garant\DA\daDataProviderSuperFactory.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaDataProviderSuperFactory" MUID: (54F85B590251) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daDataProviderFactory , daDataProviderFactoryList , daInterfaces , daDataProviderParams , daTypes , Classes , l3Variant , ddAppConfig ; type TdaDataProviderSuperFactory = class(Tl3ProtoObject) private f_List: TdaDataProviderFactoryList; f_DefaultFactory: TdaDataProviderFactory; f_ParamsStorage: IdaParamsStorage; private function FindFactoryByKey(const aKey: AnsiString): TdaDataProviderFactory; function MakeFromTaggedData(aData: Tl3Tag): TdaDataProviderParams; function IndexOfParamType(const aKey: AnsiString): Integer; protected procedure pm_SetDefaultFactory(aValue: TdaDataProviderFactory); procedure pm_SetParamsStorage(const aValue: IdaParamsStorage); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; procedure ClearFields; override; public function FindFactoryByParamType(const aKey: AnsiString): TdaDataProviderFactory; procedure CorrectByClient(aParams: TdaDataProviderParams; CorrectTempPath: Boolean = True); function IsParamsValid(aParams: TdaDataProviderParams; Quiet: Boolean = False): Boolean; procedure FillInConfig(aConfig: TddAppConfiguration; aParams: TdaDataProviderParams; ForInfoOnly: Boolean = False); procedure FillOutConfig(aConfig: TddAppConfiguration; aEtalon: TdaDataProviderParams; out aParams: TdaDataProviderParams); procedure BuildConfig(aConfig: TddAppConfiguration; const aProviderKey: AnsiString = ''; ForInfoOnly: Boolean = False); function MakeProvider(aParams: TdaDataProviderParams; AllowClearLocks: Boolean): IdaDataProvider; procedure LoadDBVersion(aParams: TdaDataProviderParams); function CheckLogin(aParams: TdaDataProviderParams; const aLogin: AnsiString; const aPassword: AnsiString; IsRequireAdminRights: Boolean; SuppressExceptions: Boolean = True): TdaLoginError; procedure Register(aFactory: TdaDataProviderFactory); procedure UnRegister(aFactory: TdaDataProviderFactory); function MakeFromConfig: TdaDataProviderParams; procedure SaveToConfig(aParams: TdaDataProviderParams); function MakeParamsFromEVD(aStream: TStream): TdaDataProviderParams; class function Instance: TdaDataProviderSuperFactory; {* Метод получения экземпляра синглетона TdaDataProviderSuperFactory } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property DefaultFactory: TdaDataProviderFactory read f_DefaultFactory write pm_SetDefaultFactory; property ParamsStorage: IdaParamsStorage read f_ParamsStorage write pm_SetParamsStorage; end;//TdaDataProviderSuperFactory implementation uses l3ImplUses , SysUtils , l3Types , ddAppConfigTypes , l3Base //#UC START# *54F85B590251impl_uses* //#UC END# *54F85B590251impl_uses* ; var g_TdaDataProviderSuperFactory: TdaDataProviderSuperFactory = nil; {* Экземпляр синглетона TdaDataProviderSuperFactory } procedure TdaDataProviderSuperFactoryFree; {* Метод освобождения экземпляра синглетона TdaDataProviderSuperFactory } begin l3Free(g_TdaDataProviderSuperFactory); end;//TdaDataProviderSuperFactoryFree procedure TdaDataProviderSuperFactory.pm_SetDefaultFactory(aValue: TdaDataProviderFactory); //#UC START# *54F99D1A0219_54F85B590251set_var* //#UC END# *54F99D1A0219_54F85B590251set_var* begin //#UC START# *54F99D1A0219_54F85B590251set_impl* if f_DefaultFactory <> aValue then begin aValue.SetRefTo(f_DefaultFactory); if Assigned(f_DefaultFactory) then Register(f_DefaultFactory); end; //#UC END# *54F99D1A0219_54F85B590251set_impl* end;//TdaDataProviderSuperFactory.pm_SetDefaultFactory procedure TdaDataProviderSuperFactory.pm_SetParamsStorage(const aValue: IdaParamsStorage); //#UC START# *5507E77B021F_54F85B590251set_var* //#UC END# *5507E77B021F_54F85B590251set_var* begin //#UC START# *5507E77B021F_54F85B590251set_impl* f_ParamsStorage := aValue; //#UC END# *5507E77B021F_54F85B590251set_impl* end;//TdaDataProviderSuperFactory.pm_SetParamsStorage function TdaDataProviderSuperFactory.FindFactoryByKey(const aKey: AnsiString): TdaDataProviderFactory; //#UC START# *550A8A38018C_54F85B590251_var* var l_IDX: Integer; //#UC END# *550A8A38018C_54F85B590251_var* begin //#UC START# *550A8A38018C_54F85B590251_impl* Result := nil; for l_IDX := 0 to f_List.Count - 1 do if AnsiSameText(f_List[l_IDX].Key, aKey) then begin Result := f_List[l_IDX]; Break; end; if Result = nil then Result := DefaultFactory; Assert(Assigned(Result)); Result.ParamsStorage := f_ParamsStorage; //#UC END# *550A8A38018C_54F85B590251_impl* end;//TdaDataProviderSuperFactory.FindFactoryByKey function TdaDataProviderSuperFactory.FindFactoryByParamType(const aKey: AnsiString): TdaDataProviderFactory; //#UC START# *550A8A6701F6_54F85B590251_var* var l_IDX: Integer; //#UC END# *550A8A6701F6_54F85B590251_var* begin //#UC START# *550A8A6701F6_54F85B590251_impl* Result := nil; for l_IDX := 0 to f_List.Count - 1 do if AnsiSameText(f_List[l_IDX].ParamKey, aKey) then begin Result := f_List[l_IDX]; Break; end; Assert(Assigned(Result)); Result.ParamsStorage := f_ParamsStorage; //#UC END# *550A8A6701F6_54F85B590251_impl* end;//TdaDataProviderSuperFactory.FindFactoryByParamType function TdaDataProviderSuperFactory.MakeFromTaggedData(aData: Tl3Tag): TdaDataProviderParams; //#UC START# *550FD1780368_54F85B590251_var* var l_ClassRef: TdaDataProviderParamsClass; //#UC END# *550FD1780368_54F85B590251_var* begin //#UC START# *550FD1780368_54F85B590251_impl* l_ClassRef := FindFactoryByParamType(aData.TagType.AsString).ParamType; if Assigned(l_ClassRef) then begin Result := l_ClassRef.Create; try Result.SetTaggedData(aData); except FreeAndNil(Result); raise; end; end else Result := nil; //#UC END# *550FD1780368_54F85B590251_impl* end;//TdaDataProviderSuperFactory.MakeFromTaggedData procedure TdaDataProviderSuperFactory.CorrectByClient(aParams: TdaDataProviderParams; CorrectTempPath: Boolean = True); //#UC START# *55100AB20241_54F85B590251_var* //#UC END# *55100AB20241_54F85B590251_var* begin //#UC START# *55100AB20241_54F85B590251_impl* FindFactoryByParamType(aParams.ParamsKey).CorrectByClient(aParams, CorrectTempPath); //#UC END# *55100AB20241_54F85B590251_impl* end;//TdaDataProviderSuperFactory.CorrectByClient function TdaDataProviderSuperFactory.IsParamsValid(aParams: TdaDataProviderParams; Quiet: Boolean = False): Boolean; //#UC START# *551166670371_54F85B590251_var* //#UC END# *551166670371_54F85B590251_var* begin //#UC START# *551166670371_54F85B590251_impl* Result := FindFactoryByParamType(aParams.ParamsKey).IsParamsValid(aParams, Quiet); //#UC END# *551166670371_54F85B590251_impl* end;//TdaDataProviderSuperFactory.IsParamsValid procedure TdaDataProviderSuperFactory.FillInConfig(aConfig: TddAppConfiguration; aParams: TdaDataProviderParams; ForInfoOnly: Boolean = False); //#UC START# *5512BB5D0065_54F85B590251_var* var l_Param: TdaDataProviderParams; l_IDX: Integer; l_Factory: TdaDataProviderFactory; //#UC END# *5512BB5D0065_54F85B590251_var* begin //#UC START# *5512BB5D0065_54F85B590251_impl* if not ForInfoOnly then begin for l_IDX := 0 to f_List.Count - 1 do begin l_Param := f_List[l_IDX].MakeFromConfig; try f_List[l_IDX].ParamsStorage := ParamsStorage; f_List[l_IDX].FillInConfig(aConfig, l_Param, ForInfoOnly); finally FreeAndNil(l_Param); end; end; aConfig.AsInteger['Provider'] := IndexOfParamType(aParams.ParamsKey); end; FindFactoryByParamType(aParams.ParamsKey).FillInConfig(aConfig, aParams, ForInfoOnly); //#UC END# *5512BB5D0065_54F85B590251_impl* end;//TdaDataProviderSuperFactory.FillInConfig procedure TdaDataProviderSuperFactory.FillOutConfig(aConfig: TddAppConfiguration; aEtalon: TdaDataProviderParams; out aParams: TdaDataProviderParams); //#UC START# *5512BB8103B4_54F85B590251_var* //#UC END# *5512BB8103B4_54F85B590251_var* begin //#UC START# *5512BB8103B4_54F85B590251_impl* f_List[aConfig.AsInteger['Provider']].FillOutConfig(aConfig, aEtalon, aParams) //#UC END# *5512BB8103B4_54F85B590251_impl* end;//TdaDataProviderSuperFactory.FillOutConfig procedure TdaDataProviderSuperFactory.BuildConfig(aConfig: TddAppConfiguration; const aProviderKey: AnsiString = ''; ForInfoOnly: Boolean = False); //#UC START# *5512BB9801EA_54F85B590251_var* var l_IDX: Integer; l_Container: TddContainerConfigItem; l_Default: String; //#UC END# *5512BB9801EA_54F85B590251_var* begin //#UC START# *5512BB9801EA_54F85B590251_impl* if ForInfoOnly then FindFactoryByParamType(aProviderKey).BuildConfig(aConfig, aProviderKey, ForInfoOnly) else begin if Assigned(DefaultFactory) then l_Default := DefaultFactory.Key else l_Default := ''; l_Container := aConfig.AddContainerGroup('Provider', l_Default) as TddContainerConfigItem; l_Container.ForceComboBox := True; for l_IDX := 0 to f_List.Count - 1 do begin l_Container.AddCase(f_List[l_IDX].Key); f_List[l_IDX].ParamsStorage := ParamsStorage; f_List[l_IDX].BuildConfig(aConfig, aProviderKey, ForInfoOnly); end; aConfig.CloseGroup; end; //#UC END# *5512BB9801EA_54F85B590251_impl* end;//TdaDataProviderSuperFactory.BuildConfig function TdaDataProviderSuperFactory.IndexOfParamType(const aKey: AnsiString): Integer; //#UC START# *5512C7FE0342_54F85B590251_var* var l_IDX: Integer; //#UC END# *5512C7FE0342_54F85B590251_var* begin //#UC START# *5512C7FE0342_54F85B590251_impl* Result := -1; for l_IDX := 0 to f_List.Count - 1 do if AnsiSameText(f_List[l_IDX].ParamKey, aKey) then begin Result := l_IDX; Break; end; Assert(Result <> -1); f_List[Result].ParamsStorage := ParamsStorage; //#UC END# *5512C7FE0342_54F85B590251_impl* end;//TdaDataProviderSuperFactory.IndexOfParamType function TdaDataProviderSuperFactory.MakeProvider(aParams: TdaDataProviderParams; AllowClearLocks: Boolean): IdaDataProvider; //#UC START# *551543F903C6_54F85B590251_var* //#UC END# *551543F903C6_54F85B590251_var* begin //#UC START# *551543F903C6_54F85B590251_impl* Result := FindFactoryByParamType(aParams.ParamsKey).MakeProvider(aParams, AllowClearLocks); //#UC END# *551543F903C6_54F85B590251_impl* end;//TdaDataProviderSuperFactory.MakeProvider procedure TdaDataProviderSuperFactory.LoadDBVersion(aParams: TdaDataProviderParams); //#UC START# *551904D300A1_54F85B590251_var* //#UC END# *551904D300A1_54F85B590251_var* begin //#UC START# *551904D300A1_54F85B590251_impl* FindFactoryByParamType(aParams.ParamsKey).LoadDBVersion(aParams); //#UC END# *551904D300A1_54F85B590251_impl* end;//TdaDataProviderSuperFactory.LoadDBVersion function TdaDataProviderSuperFactory.CheckLogin(aParams: TdaDataProviderParams; const aLogin: AnsiString; const aPassword: AnsiString; IsRequireAdminRights: Boolean; SuppressExceptions: Boolean = True): TdaLoginError; //#UC START# *551BE37C0396_54F85B590251_var* //#UC END# *551BE37C0396_54F85B590251_var* begin //#UC START# *551BE37C0396_54F85B590251_impl* Result := FindFactoryByParamType(aParams.ParamsKey).CheckLogin(aParams, aLogin, aPassword, IsRequireAdminRights, SuppressExceptions); //#UC END# *551BE37C0396_54F85B590251_impl* end;//TdaDataProviderSuperFactory.CheckLogin procedure TdaDataProviderSuperFactory.Register(aFactory: TdaDataProviderFactory); //#UC START# *54F85C450279_54F85B590251_var* //#UC END# *54F85C450279_54F85B590251_var* begin //#UC START# *54F85C450279_54F85B590251_impl* f_List.Add(aFactory); //#UC END# *54F85C450279_54F85B590251_impl* end;//TdaDataProviderSuperFactory.Register procedure TdaDataProviderSuperFactory.UnRegister(aFactory: TdaDataProviderFactory); //#UC START# *54F85C60022E_54F85B590251_var* //#UC END# *54F85C60022E_54F85B590251_var* begin //#UC START# *54F85C60022E_54F85B590251_impl* f_List.Remove(aFactory); //#UC END# *54F85C60022E_54F85B590251_impl* end;//TdaDataProviderSuperFactory.UnRegister function TdaDataProviderSuperFactory.MakeFromConfig: TdaDataProviderParams; //#UC START# *54FEB4CD0070_54F85B590251_var* //#UC END# *54FEB4CD0070_54F85B590251_var* begin //#UC START# *54FEB4CD0070_54F85B590251_impl* Assert(ParamsStorage <> nil); Result := FindFactoryByKey(ParamsStorage.ProviderKey).MakeFromConfig; //#UC END# *54FEB4CD0070_54F85B590251_impl* end;//TdaDataProviderSuperFactory.MakeFromConfig procedure TdaDataProviderSuperFactory.SaveToConfig(aParams: TdaDataProviderParams); //#UC START# *550A89DC03C4_54F85B590251_var* //#UC END# *550A89DC03C4_54F85B590251_var* begin //#UC START# *550A89DC03C4_54F85B590251_impl* Assert(ParamsStorage <> nil); ParamsStorage.ProviderKey := aParams.ParamsKey; FindFactoryByParamType(aParams.ParamsKey).SaveToConfig(aParams); //#UC END# *550A89DC03C4_54F85B590251_impl* end;//TdaDataProviderSuperFactory.SaveToConfig function TdaDataProviderSuperFactory.MakeParamsFromEVD(aStream: TStream): TdaDataProviderParams; //#UC START# *550FCA280214_54F85B590251_var* var l_Data : Tl3Tag; //#UC END# *550FCA280214_54F85B590251_var* begin //#UC START# *550FCA280214_54F85B590251_impl* Result := nil; if aStream.Size = 0 then Exit; l_Data := TdaDataProviderParams.CreateTaggedDataFromEVD(aStream); try Result := MakeFromTaggedData(l_Data); finally FreeAndNil(l_Data); end;//try..finally //#UC END# *550FCA280214_54F85B590251_impl* end;//TdaDataProviderSuperFactory.MakeParamsFromEVD class function TdaDataProviderSuperFactory.Instance: TdaDataProviderSuperFactory; {* Метод получения экземпляра синглетона TdaDataProviderSuperFactory } begin if (g_TdaDataProviderSuperFactory = nil) then begin l3System.AddExitProc(TdaDataProviderSuperFactoryFree); g_TdaDataProviderSuperFactory := Create; end; Result := g_TdaDataProviderSuperFactory; end;//TdaDataProviderSuperFactory.Instance class function TdaDataProviderSuperFactory.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TdaDataProviderSuperFactory <> nil; end;//TdaDataProviderSuperFactory.Exists procedure TdaDataProviderSuperFactory.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_54F85B590251_var* //#UC END# *479731C50290_54F85B590251_var* begin //#UC START# *479731C50290_54F85B590251_impl* FreeAndNil(f_List); FreeAndNil(f_DefaultFactory); f_ParamsStorage := nil; inherited; //#UC END# *479731C50290_54F85B590251_impl* end;//TdaDataProviderSuperFactory.Cleanup procedure TdaDataProviderSuperFactory.InitFields; //#UC START# *47A042E100E2_54F85B590251_var* //#UC END# *47A042E100E2_54F85B590251_var* begin //#UC START# *47A042E100E2_54F85B590251_impl* inherited; f_List := TdaDataProviderFactoryList.MakeSorted(l3_dupIgnore); //#UC END# *47A042E100E2_54F85B590251_impl* end;//TdaDataProviderSuperFactory.InitFields procedure TdaDataProviderSuperFactory.ClearFields; begin ParamsStorage := nil; inherited; end;//TdaDataProviderSuperFactory.ClearFields end.
unit Optimizer.P2P; interface uses SysUtils, Optimizer.Template, Global.LanguageString, Registry.Helper; type TP2POptimizer = class(TOptimizationUnit) public function IsOptional: Boolean; override; function IsCompatible: Boolean; override; function IsApplied: Boolean; override; function GetName: String; override; procedure Apply; override; procedure Undo; override; end; implementation function TP2POptimizer.IsOptional: Boolean; begin exit(false); end; function TP2POptimizer.IsCompatible: Boolean; begin exit(IsAtLeastWindows10); end; function TP2POptimizer.IsApplied: Boolean; begin if not IsAtLeastWindows10 then exit(false); result := NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew('LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', 'DODownloadMode')) = 0; end; function TP2POptimizer.GetName: String; begin exit(CapOptP2P[CurrLang]); end; procedure TP2POptimizer.Apply; begin NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', 'DODownloadMode'), 0); NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('CU', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization', 'SystemSettingsDownloadMode'), 3); end; procedure TP2POptimizer.Undo; begin NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', 'DODownloadMode'), 3); NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('CU', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization', 'DODownloadMode'), 1); end; end.
{ WAV format reader for the fpSound library License: The same modified LGPL as the LCL Authors: JiXian Yang Felipe Monteiro de Carvalho Canonical WAV file description here: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ } unit fpsound_wav; {$mode objfpc} interface uses Classes, SysUtils, Math, fpsound; // WAVE UTILS type // WAV is formed by the following structures in this order // All items are in little endian order, except the char arrays // Items might be in big endian order if the RIFF identifier is RIFX TRiffHeader = packed record ID : array [0..3] of char; // should be RIFF Size : LongWord; // 4 + (8 + SubChunk1Size) + (8 + SubChunk2Size). The entire file size excluding TRiffHeader.ID and .Size Format : array [0..3] of char; // should be WAVE end; TWaveFormat = packed record ID : array [0..3] of char; // Should be "fmt " Size : LongWord; // SubChunk1Size Format : Word; // PCM = 1 (Linear quantization), values > 1 indicate a compressed format Channels : Word; // Mono = 1, Stereo = 2, etc SampleRate : LongWord; // 8000, 44100, etc ByteRate : LongWord; // = SampleRate * NumChannels * BitsPerSample/8 BlockAlign : Word; // = NumChannels * BitsPerSample/8 BitsPerSample : Word; // examples: 8 bits, 16 bits, etc end; // If the format is not PCM then there will also be: // TWaveFormatExtension = packed record // ExtraParamSize: Word; // ExtraParams... // end; TDataChunk = packed record Id : array [0..3] of char; // should be "data" Size : LongWord; // == NumSamples * NumChannels * BitsPerSample/8 end; // And after this header the actual data comes, which is an array of samples { TWaveReader } TWaveReader = class(TSoundReader) public fmt: TWaveFormat; datachunk: TDataChunk; NumSamples: Integer; procedure ReadFromStream(AStream: TStream; ADest: TSoundDocument); override; procedure ReadHeaders(AStream: TStream; ADest: TSoundDocument); procedure ReadAllSamples(AStream: TStream; ADest: TSoundDocument); procedure ReadSample(AStream: TStream; ADest: TSoundDocument); //function ReadBuf(var Buffer; BufferSize: Integer): Integer; end; implementation const ID_RIFF = 'RIFF'; ID_WAVE ='WAVE'; fD_fmt = 'fmt '; ID_data = 'data'; { TWaveReader } procedure TWaveReader.ReadFromStream(AStream:TStream; ADest: TSoundDocument); begin ReadHeaders(AStream, ADest); ReadAllSamples(AStream, ADest); end; procedure TWaveReader.ReadHeaders(AStream: TStream; ADest: TSoundDocument); var riff : TRiffHeader; lKeyElement: TSoundKeyElement; begin AStream.Read(riff, sizeof(riff));//=sizeof(riff); riff.Size:=LEtoN(riff.Size); //Result:=Result and (riff.ID=ID_RIFF) and (riff.Format=ID_WAVE); //if not Result then Exit; AStream.Read(fmt, sizeof(fmt));//=sizeof(fmt); fmt.Size:=LEtoN(fmt.Size); fmt.Format:=LEtoN(fmt.Format); fmt.Channels:=LEtoN(fmt.Channels); fmt.SampleRate:=LEtoN(fmt.SampleRate); fmt.ByteRate:=LEtoN(fmt.ByteRate); fmt.BlockAlign:=LEtoN(fmt.BlockAlign); fmt.BitsPerSample:=LEtoN(fmt.BitsPerSample); AStream.Read(datachunk, sizeof(datachunk)); datachunk.Size := LEtoN(datachunk.Size); NumSamples := fmt.BlockAlign div datachunk.size; //Result:=fmt.ID=ID_fmt; // pos:=-1; // Store the data in the document lKeyElement := TSoundKeyElement.Create; lKeyElement.SampleRate := fmt.SampleRate; lKeyElement.BitsPerSample := fmt.BitsPerSample; lKeyElement.Channels := fmt.Channels; ADest.AddSoundElement(lKeyElement); end; procedure TWaveReader.ReadAllSamples(AStream: TStream; ADest: TSoundDocument); var i: Integer; begin for i := 0 to NumSamples - 1 do ReadSample(AStream, ADest); end; procedure TWaveReader.ReadSample(AStream: TStream; ADest: TSoundDocument); var lSoundSample8: TSoundSample8; lSoundSample16: TSoundSample16; i: Integer; lByteData: Byte; lWordData: SmallInt; begin if fmt.BitsPerSample = 8 then begin lSoundSample8 := TSoundSample8.Create; SetLength(lSoundSample8.ChannelValues, fmt.Channels); for i := 0 to fmt.Channels - 1 do begin lByteData := AStream.ReadByte(); lSoundSample8.ChannelValues[i] := lByteData; end; ADest.AddSoundElement(lSoundSample8); end else if fmt.BitsPerSample = 16 then begin lSoundSample16 := TSoundSample16.Create; SetLength(lSoundSample16.ChannelValues, fmt.Channels); for i := 0 to fmt.Channels - 1 do begin AStream.Read(lWordData, 2); lSoundSample16.ChannelValues[i] := lWordData; end; ADest.AddSoundElement(lSoundSample16); end else raise Exception.Create(Format('[TWaveReader.ReadSample] Invalid number of bits per sample: %d', [fmt.BitsPerSample])); end; {function TWaveReader.ReadBuf(var Buffer;BufferSize:Integer):Integer; var sz : Integer; p : PByteArray; i : Integer; begin FillChar(Buffer, BufferSize, 0); Result:=0; // all data read if eof then Exit; p:=@Buffer; i:=0; while (not eof) and (i<bufferSize) do begin if chunkpos>=chunkdata.Size then begin if pos<0 then fstream.Position:=sizeof(TRiffHeader)+Int64(fmt.Size)+sizeof(TDataChunk) else fstream.Position:=pos+chunkdata.size+SizeOf(chunkdata); eof:=pos>=fStream.Size; if not eof then begin pos:=fStream.Position; sz:=fstream.Read(chunkdata, sizeof(chunkdata)); chunkdata.Size:=LEtoN(chunkdata.Size); if (sz<>sizeof(chunkdata)) or (chunkdata.Id<>ID_data) then chunkpos:=chunkdata.Size else chunkpos:=0; end; end else begin sz:=Min(BufferSize, chunkdata.Size-chunkpos); fStream.Position:=pos+sizeof(chunkdata)+chunkpos; sz:=fStream.Read(p[i], sz); if sz<0 then Exit; inc(chunkpos, sz); inc(i, sz); end; end; Result:=i; end;} initialization RegisterSoundReader(TWaveReader.Create, sfWav); end.
unit MFichas.Model.Configuracao.Metodos.Buscar.View; interface uses System.SysUtils, MFichas.Model.Configuracao.Interfaces, FireDAC.Comp.Client, FireDAC.Comp.DataSet; type TModelConfiguracaoMetodosBuscarView = class(TInterfacedObject, iModelConfiguracaoMetodosBuscarView) private [weak] FParent : iModelConfiguracao; FFDMemTable: TFDMemTable; constructor Create(AParent: iModelConfiguracao); procedure Validacao; procedure CopiarDataSet; public destructor Destroy; override; class function New(AParent: iModelConfiguracao): iModelConfiguracaoMetodosBuscarView; function FDMemTable(AFDMemTable: TFDMemTable): iModelConfiguracaoMetodosBuscarView; function BuscarConfiguracao : iModelConfiguracaoMetodosBuscarView; function &End : iModelConfiguracaoMetodos; end; implementation { TModelConfiguracaoMetodosBuscarView } function TModelConfiguracaoMetodosBuscarView.BuscarConfiguracao: iModelConfiguracaoMetodosBuscarView; begin Result := Self; FParent.DAODataSet.Open; Validacao; CopiarDataSet; end; function TModelConfiguracaoMetodosBuscarView.&End: iModelConfiguracaoMetodos; begin Result := FParent.Metodos; end; procedure TModelConfiguracaoMetodosBuscarView.CopiarDataSet; begin FFDMemTable.CopyDataSet(FParent.DAODataSet.DataSet, [coStructure, coRestart, coAppend]); end; constructor TModelConfiguracaoMetodosBuscarView.Create(AParent: iModelConfiguracao); begin FParent := AParent; end; destructor TModelConfiguracaoMetodosBuscarView.Destroy; begin inherited; end; function TModelConfiguracaoMetodosBuscarView.FDMemTable( AFDMemTable: TFDMemTable): iModelConfiguracaoMetodosBuscarView; begin Result := Self; FFDMemTable := AFDMemTable; end; class function TModelConfiguracaoMetodosBuscarView.New(AParent: iModelConfiguracao): iModelConfiguracaoMetodosBuscarView; begin Result := Self.Create(AParent); end; procedure TModelConfiguracaoMetodosBuscarView.Validacao; begin if FParent.DAODataSet.DataSet.RecordCount = 0 then raise Exception.Create( 'Nenhuma configuração encontrada.' ); if not Assigned(FFDMemTable) then raise Exception.Create( 'Para prosseguir, você deve vincular um FDMemTable ao encadeamento' + ' de funcões do método de Configuracoes.Metodos.BuscarView .' ); end; end.
unit ObjectFromstackWords; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\ObjectFromstackWords.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ObjectFromstackWords" MUID: (507698410297) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwClassLike , tfwScriptingInterfaces , TypInfo , tfwAxiomaticsResNameGetter , kwPopClassInherits , SysUtils , l3RTTI , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *507698410297impl_uses* //#UC END# *507698410297impl_uses* ; type TkwPopObjectInherits = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:Inherits } private function Inherits(const aCtx: TtfwContext; aObject: TObject; const aClass: TtfwStackValue): Boolean; {* Реализация слова скрипта pop:Object:Inherits } 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;//TkwPopObjectInherits TkwPopObjectClassName = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:ClassName } private function ClassName(const aCtx: TtfwContext; aObject: TObject): AnsiString; {* Реализация слова скрипта pop:Object:ClassName } 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;//TkwPopObjectClassName TkwPopObjectGetFloatProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:GetFloatProp } private function GetFloatProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): Integer; {* Реализация слова скрипта pop:Object:GetFloatProp } 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;//TkwPopObjectGetFloatProp TkwPopObjectGetInterfaceProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:GetInterfaceProp } private function GetInterfaceProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): IUnknown; {* Реализация слова скрипта pop:Object:GetInterfaceProp } 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;//TkwPopObjectGetInterfaceProp TkwPopObjectGetObjProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:GetObjProp } private function GetObjProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): TObject; {* Реализация слова скрипта pop:Object:GetObjProp } 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;//TkwPopObjectGetObjProp TkwPopObjectGetOrdProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:GetOrdProp } private function GetOrdProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): Integer; {* Реализация слова скрипта pop:Object:GetOrdProp } 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;//TkwPopObjectGetOrdProp TkwPopObjectGetStrProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:GetStrProp } private function GetStrProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): AnsiString; {* Реализация слова скрипта pop:Object:GetStrProp } 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;//TkwPopObjectGetStrProp TkwPopObjectHasProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:HasProp } private function HasProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): Boolean; {* Реализация слова скрипта pop:Object:HasProp } 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;//TkwPopObjectHasProp TkwPopObjectRTTIInfo = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:RTTIInfo } private function RTTIInfo(const aCtx: TtfwContext; aObject: TObject): AnsiString; {* Реализация слова скрипта pop:Object:RTTIInfo } 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;//TkwPopObjectRTTIInfo TkwPopObjectSetFloatProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:SetFloatProp } private procedure SetFloatProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString; aValue: Integer); {* Реализация слова скрипта pop:Object:SetFloatProp } 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;//TkwPopObjectSetFloatProp TkwPopObjectSetOrdProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:SetOrdProp } private procedure SetOrdProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString; aValue: Integer); {* Реализация слова скрипта pop:Object:SetOrdProp } 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;//TkwPopObjectSetOrdProp TkwPopObjectSetStrProp = {final} class(TtfwClassLike) {* Слово скрипта pop:Object:SetStrProp } private procedure SetStrProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString; const aValue: AnsiString); {* Реализация слова скрипта pop:Object:SetStrProp } 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;//TkwPopObjectSetStrProp TObjectFromstackWordsResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TObjectFromstackWordsResNameGetter function TkwPopObjectInherits.Inherits(const aCtx: TtfwContext; aObject: TObject; const aClass: TtfwStackValue): Boolean; {* Реализация слова скрипта pop:Object:Inherits } //#UC START# *561275A50363_561275A50363_4807745602C8_Word_var* function IsInherits(anObject: TClass; const aClass: AnsiString): Boolean; begin//IsInherits if (anObject = nil) then Result := false else if AnsiSameText(anObject.ClassName, aClass) then Result := true else Result := IsInherits(anObject.ClassParent, aClass); end;//IsInherits //#UC END# *561275A50363_561275A50363_4807745602C8_Word_var* begin //#UC START# *561275A50363_561275A50363_4807745602C8_Word_impl* Case aClass.rType of tfw_vtClass: if (aObject = nil) then Result := false else Result := aObject.ClassType.InheritsFrom(aClass.AsClass); tfw_vtStr: if (aObject = nil) then Result := false else Result := IsInherits(aObject.ClassType, aClass.AsDelphiString); else begin Result := false; BadValueType(aClass.rType, aCtx); end;//else end;//Case aClass.rType //#UC END# *561275A50363_561275A50363_4807745602C8_Word_impl* end;//TkwPopObjectInherits.Inherits class function TkwPopObjectInherits.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:Inherits'; end;//TkwPopObjectInherits.GetWordNameForRegister function TkwPopObjectInherits.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopObjectInherits.GetResultTypeInfo function TkwPopObjectInherits.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectInherits.GetAllParamsCount function TkwPopObjectInherits.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiStruct]); end;//TkwPopObjectInherits.ParamsTypes procedure TkwPopObjectInherits.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aClass: TtfwStackValue; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aClass := aCtx.rEngine.Pop; except on E: Exception do begin RunnerError('Ошибка при получении параметра aClass: TtfwStackValue : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Inherits(aCtx, l_aObject, l_aClass)); end;//TkwPopObjectInherits.DoDoIt function TkwPopObjectClassName.ClassName(const aCtx: TtfwContext; aObject: TObject): AnsiString; {* Реализация слова скрипта pop:Object:ClassName } //#UC START# *561276140246_561276140246_4807745602C8_Word_var* //#UC END# *561276140246_561276140246_4807745602C8_Word_var* begin //#UC START# *561276140246_561276140246_4807745602C8_Word_impl* if (aObject = nil) then Result := 'Запросили имя класса у nil' else Result := aObject.ClassName; //#UC END# *561276140246_561276140246_4807745602C8_Word_impl* end;//TkwPopObjectClassName.ClassName class function TkwPopObjectClassName.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:ClassName'; end;//TkwPopObjectClassName.GetWordNameForRegister function TkwPopObjectClassName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopObjectClassName.GetResultTypeInfo function TkwPopObjectClassName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopObjectClassName.GetAllParamsCount function TkwPopObjectClassName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject)]); end;//TkwPopObjectClassName.ParamsTypes procedure TkwPopObjectClassName.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(ClassName(aCtx, l_aObject)); end;//TkwPopObjectClassName.DoDoIt function TkwPopObjectGetFloatProp.GetFloatProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): Integer; {* Реализация слова скрипта pop:Object:GetFloatProp } //#UC START# *5612877900FD_5612877900FD_4807745602C8_Word_var* //#UC END# *5612877900FD_5612877900FD_4807745602C8_Word_var* begin //#UC START# *5612877900FD_5612877900FD_4807745602C8_Word_impl* Result := Trunc(TypInfo.GetFloatProp(aObject, aName)); //#UC END# *5612877900FD_5612877900FD_4807745602C8_Word_impl* end;//TkwPopObjectGetFloatProp.GetFloatProp class function TkwPopObjectGetFloatProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:GetFloatProp'; end;//TkwPopObjectGetFloatProp.GetWordNameForRegister function TkwPopObjectGetFloatProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwPopObjectGetFloatProp.GetResultTypeInfo function TkwPopObjectGetFloatProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectGetFloatProp.GetAllParamsCount function TkwPopObjectGetFloatProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString]); end;//TkwPopObjectGetFloatProp.ParamsTypes procedure TkwPopObjectGetFloatProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(GetFloatProp(aCtx, l_aObject, l_aName)); end;//TkwPopObjectGetFloatProp.DoDoIt function TkwPopObjectGetInterfaceProp.GetInterfaceProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): IUnknown; {* Реализация слова скрипта pop:Object:GetInterfaceProp } //#UC START# *5612879D0254_5612879D0254_4807745602C8_Word_var* //#UC END# *5612879D0254_5612879D0254_4807745602C8_Word_var* begin //#UC START# *5612879D0254_5612879D0254_4807745602C8_Word_impl* Result := TypInfo.GetInterfaceProp(aObject, aName); //#UC END# *5612879D0254_5612879D0254_4807745602C8_Word_impl* end;//TkwPopObjectGetInterfaceProp.GetInterfaceProp class function TkwPopObjectGetInterfaceProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:GetInterfaceProp'; end;//TkwPopObjectGetInterfaceProp.GetWordNameForRegister function TkwPopObjectGetInterfaceProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(IUnknown); end;//TkwPopObjectGetInterfaceProp.GetResultTypeInfo function TkwPopObjectGetInterfaceProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectGetInterfaceProp.GetAllParamsCount function TkwPopObjectGetInterfaceProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString]); end;//TkwPopObjectGetInterfaceProp.ParamsTypes procedure TkwPopObjectGetInterfaceProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushIntf(GetInterfaceProp(aCtx, l_aObject, l_aName), TypeInfo(IUnknown)); end;//TkwPopObjectGetInterfaceProp.DoDoIt function TkwPopObjectGetObjProp.GetObjProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): TObject; {* Реализация слова скрипта pop:Object:GetObjProp } //#UC START# *561287BB03E6_561287BB03E6_4807745602C8_Word_var* //#UC END# *561287BB03E6_561287BB03E6_4807745602C8_Word_var* begin //#UC START# *561287BB03E6_561287BB03E6_4807745602C8_Word_impl* Result := TypInfo.GetObjectProp(aObject, aName); //#UC END# *561287BB03E6_561287BB03E6_4807745602C8_Word_impl* end;//TkwPopObjectGetObjProp.GetObjProp class function TkwPopObjectGetObjProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:GetObjProp'; end;//TkwPopObjectGetObjProp.GetWordNameForRegister function TkwPopObjectGetObjProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TObject); end;//TkwPopObjectGetObjProp.GetResultTypeInfo function TkwPopObjectGetObjProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectGetObjProp.GetAllParamsCount function TkwPopObjectGetObjProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString]); end;//TkwPopObjectGetObjProp.ParamsTypes procedure TkwPopObjectGetObjProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetObjProp(aCtx, l_aObject, l_aName)); end;//TkwPopObjectGetObjProp.DoDoIt function TkwPopObjectGetOrdProp.GetOrdProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): Integer; {* Реализация слова скрипта pop:Object:GetOrdProp } //#UC START# *561287D60299_561287D60299_4807745602C8_Word_var* //#UC END# *561287D60299_561287D60299_4807745602C8_Word_var* begin //#UC START# *561287D60299_561287D60299_4807745602C8_Word_impl* Result := TypInfo.GetOrdProp(aObject, aName); //#UC END# *561287D60299_561287D60299_4807745602C8_Word_impl* end;//TkwPopObjectGetOrdProp.GetOrdProp class function TkwPopObjectGetOrdProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:GetOrdProp'; end;//TkwPopObjectGetOrdProp.GetWordNameForRegister function TkwPopObjectGetOrdProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwPopObjectGetOrdProp.GetResultTypeInfo function TkwPopObjectGetOrdProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectGetOrdProp.GetAllParamsCount function TkwPopObjectGetOrdProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString]); end;//TkwPopObjectGetOrdProp.ParamsTypes procedure TkwPopObjectGetOrdProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(GetOrdProp(aCtx, l_aObject, l_aName)); end;//TkwPopObjectGetOrdProp.DoDoIt function TkwPopObjectGetStrProp.GetStrProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): AnsiString; {* Реализация слова скрипта pop:Object:GetStrProp } //#UC START# *561287F1013D_561287F1013D_4807745602C8_Word_var* //#UC END# *561287F1013D_561287F1013D_4807745602C8_Word_var* begin //#UC START# *561287F1013D_561287F1013D_4807745602C8_Word_impl* Result := TypInfo.GetStrProp(aObject, aName); //#UC END# *561287F1013D_561287F1013D_4807745602C8_Word_impl* end;//TkwPopObjectGetStrProp.GetStrProp class function TkwPopObjectGetStrProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:GetStrProp'; end;//TkwPopObjectGetStrProp.GetWordNameForRegister function TkwPopObjectGetStrProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopObjectGetStrProp.GetResultTypeInfo function TkwPopObjectGetStrProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectGetStrProp.GetAllParamsCount function TkwPopObjectGetStrProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString]); end;//TkwPopObjectGetStrProp.ParamsTypes procedure TkwPopObjectGetStrProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(GetStrProp(aCtx, l_aObject, l_aName)); end;//TkwPopObjectGetStrProp.DoDoIt function TkwPopObjectHasProp.HasProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString): Boolean; {* Реализация слова скрипта pop:Object:HasProp } //#UC START# *5612881202CE_5612881202CE_4807745602C8_Word_var* //#UC END# *5612881202CE_5612881202CE_4807745602C8_Word_var* begin //#UC START# *5612881202CE_5612881202CE_4807745602C8_Word_impl* Result := TypInfo.IsPublishedProp(aObject, aName); //#UC END# *5612881202CE_5612881202CE_4807745602C8_Word_impl* end;//TkwPopObjectHasProp.HasProp class function TkwPopObjectHasProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:HasProp'; end;//TkwPopObjectHasProp.GetWordNameForRegister function TkwPopObjectHasProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopObjectHasProp.GetResultTypeInfo function TkwPopObjectHasProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopObjectHasProp.GetAllParamsCount function TkwPopObjectHasProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString]); end;//TkwPopObjectHasProp.ParamsTypes procedure TkwPopObjectHasProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(HasProp(aCtx, l_aObject, l_aName)); end;//TkwPopObjectHasProp.DoDoIt function TkwPopObjectRTTIInfo.RTTIInfo(const aCtx: TtfwContext; aObject: TObject): AnsiString; {* Реализация слова скрипта pop:Object:RTTIInfo } //#UC START# *5612883002F0_5612883002F0_4807745602C8_Word_var* //#UC END# *5612883002F0_5612883002F0_4807745602C8_Word_var* begin //#UC START# *5612883002F0_5612883002F0_4807745602C8_Word_impl* Result := l3FormatRTTIInfo(aObject); //#UC END# *5612883002F0_5612883002F0_4807745602C8_Word_impl* end;//TkwPopObjectRTTIInfo.RTTIInfo class function TkwPopObjectRTTIInfo.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:RTTIInfo'; end;//TkwPopObjectRTTIInfo.GetWordNameForRegister function TkwPopObjectRTTIInfo.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopObjectRTTIInfo.GetResultTypeInfo function TkwPopObjectRTTIInfo.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopObjectRTTIInfo.GetAllParamsCount function TkwPopObjectRTTIInfo.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject)]); end;//TkwPopObjectRTTIInfo.ParamsTypes procedure TkwPopObjectRTTIInfo.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(RTTIInfo(aCtx, l_aObject)); end;//TkwPopObjectRTTIInfo.DoDoIt procedure TkwPopObjectSetFloatProp.SetFloatProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString; aValue: Integer); {* Реализация слова скрипта pop:Object:SetFloatProp } //#UC START# *5612884C014B_5612884C014B_4807745602C8_Word_var* //#UC END# *5612884C014B_5612884C014B_4807745602C8_Word_var* begin //#UC START# *5612884C014B_5612884C014B_4807745602C8_Word_impl* TypInfo.SetFloatProp(aObject, aName, aValue); //#UC END# *5612884C014B_5612884C014B_4807745602C8_Word_impl* end;//TkwPopObjectSetFloatProp.SetFloatProp class function TkwPopObjectSetFloatProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:SetFloatProp'; end;//TkwPopObjectSetFloatProp.GetWordNameForRegister function TkwPopObjectSetFloatProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopObjectSetFloatProp.GetResultTypeInfo function TkwPopObjectSetFloatProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopObjectSetFloatProp.GetAllParamsCount function TkwPopObjectSetFloatProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString, TypeInfo(Integer)]); end;//TkwPopObjectSetFloatProp.ParamsTypes procedure TkwPopObjectSetFloatProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; var l_aValue: Integer; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aValue := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetFloatProp(aCtx, l_aObject, l_aName, l_aValue); end;//TkwPopObjectSetFloatProp.DoDoIt procedure TkwPopObjectSetOrdProp.SetOrdProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString; aValue: Integer); {* Реализация слова скрипта pop:Object:SetOrdProp } //#UC START# *5612887002C3_5612887002C3_4807745602C8_Word_var* //#UC END# *5612887002C3_5612887002C3_4807745602C8_Word_var* begin //#UC START# *5612887002C3_5612887002C3_4807745602C8_Word_impl* TypInfo.SetOrdProp(aObject, aName, aValue); //#UC END# *5612887002C3_5612887002C3_4807745602C8_Word_impl* end;//TkwPopObjectSetOrdProp.SetOrdProp class function TkwPopObjectSetOrdProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:SetOrdProp'; end;//TkwPopObjectSetOrdProp.GetWordNameForRegister function TkwPopObjectSetOrdProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopObjectSetOrdProp.GetResultTypeInfo function TkwPopObjectSetOrdProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopObjectSetOrdProp.GetAllParamsCount function TkwPopObjectSetOrdProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString, TypeInfo(Integer)]); end;//TkwPopObjectSetOrdProp.ParamsTypes procedure TkwPopObjectSetOrdProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; var l_aValue: Integer; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aValue := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetOrdProp(aCtx, l_aObject, l_aName, l_aValue); end;//TkwPopObjectSetOrdProp.DoDoIt procedure TkwPopObjectSetStrProp.SetStrProp(const aCtx: TtfwContext; aObject: TObject; const aName: AnsiString; const aValue: AnsiString); {* Реализация слова скрипта pop:Object:SetStrProp } //#UC START# *5612889D0092_5612889D0092_4807745602C8_Word_var* //#UC END# *5612889D0092_5612889D0092_4807745602C8_Word_var* begin //#UC START# *5612889D0092_5612889D0092_4807745602C8_Word_impl* TypInfo.SetStrProp(aObject, aName, aValue); //#UC END# *5612889D0092_5612889D0092_4807745602C8_Word_impl* end;//TkwPopObjectSetStrProp.SetStrProp class function TkwPopObjectSetStrProp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Object:SetStrProp'; end;//TkwPopObjectSetStrProp.GetWordNameForRegister function TkwPopObjectSetStrProp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopObjectSetStrProp.GetResultTypeInfo function TkwPopObjectSetStrProp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopObjectSetStrProp.GetAllParamsCount function TkwPopObjectSetStrProp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TObject), @tfw_tiString, @tfw_tiString]); end;//TkwPopObjectSetStrProp.ParamsTypes procedure TkwPopObjectSetStrProp.DoDoIt(const aCtx: TtfwContext); var l_aObject: TObject; var l_aName: AnsiString; var l_aValue: AnsiString; begin try l_aObject := TObject(aCtx.rEngine.PopObjAs(TObject)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aObject: TObject : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aValue := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetStrProp(aCtx, l_aObject, l_aName, l_aValue); end;//TkwPopObjectSetStrProp.DoDoIt class function TObjectFromstackWordsResNameGetter.ResName: AnsiString; begin Result := 'ObjectFromstackWords'; end;//TObjectFromstackWordsResNameGetter.ResName {$R ObjectFromstackWords.res} initialization TkwPopObjectInherits.RegisterInEngine; {* Регистрация pop_Object_Inherits } TkwPopObjectClassName.RegisterInEngine; {* Регистрация pop_Object_ClassName } TkwPopObjectGetFloatProp.RegisterInEngine; {* Регистрация pop_Object_GetFloatProp } TkwPopObjectGetInterfaceProp.RegisterInEngine; {* Регистрация pop_Object_GetInterfaceProp } TkwPopObjectGetObjProp.RegisterInEngine; {* Регистрация pop_Object_GetObjProp } TkwPopObjectGetOrdProp.RegisterInEngine; {* Регистрация pop_Object_GetOrdProp } TkwPopObjectGetStrProp.RegisterInEngine; {* Регистрация pop_Object_GetStrProp } TkwPopObjectHasProp.RegisterInEngine; {* Регистрация pop_Object_HasProp } TkwPopObjectRTTIInfo.RegisterInEngine; {* Регистрация pop_Object_RTTIInfo } TkwPopObjectSetFloatProp.RegisterInEngine; {* Регистрация pop_Object_SetFloatProp } TkwPopObjectSetOrdProp.RegisterInEngine; {* Регистрация pop_Object_SetOrdProp } TkwPopObjectSetStrProp.RegisterInEngine; {* Регистрация pop_Object_SetStrProp } TObjectFromstackWordsResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(TObject)); {* Регистрация типа TObject } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } TtfwTypeRegistrator.RegisterType(TypeInfo(IUnknown)); {* Регистрация типа IUnknown } TtfwTypeRegistrator.RegisterType(@tfw_tiStruct); {* Регистрация типа TtfwStackValue } {$IfEnd} // NOT Defined(NoScripts) end.
{ A set is a collection of objects of the same type. If S is a set of type T, then every object in T may or may not belong to S. The empty set: [] Basic operations are: + Union * Intersection - Difference = Equality <> Inequality <= Is contained in >= Contains In Inclusion } program sets(input, output); type food = (apples, strawberries, bananas, nuts, icecream, cream, sugar, ice, passionfruit, apple, cinnamon, flour); dessert = set of food; var sundae, applepie, passionDessert, flourPie : dessert; begin sundae := [strawberries] + [ice .. ice]; applepie := [apple, cream, sugar, cinnamon, flour]; passionDessert := [passionfruit, flour, cinnamon, cream, icecream]; flourPie := applepie * passionDessert; writeln(sundae = applepie); writeln([1,2,3] = [3,2,1]); writeln([1,2,3] <> [4,5,6]); writeln([1] <= [1..4]); writeln(flour in flourPie); end.
unit Login; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Imaging.jpeg, Vcl.StdCtrls, Vcl.Buttons; type TFrmLogin = class(TForm) ImgBackground: TImage; edtUsuario: TEdit; edtSenha: TEdit; btnEntrar: TSpeedButton; procedure FormCreate(Sender: TObject); procedure btnEntrarClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var FrmLogin: TFrmLogin; implementation {$R *.dfm} uses Modulo, Principal; procedure ValidarLogin(); begin if Trim(FrmLogin.edtUsuario.Text) = '' then begin MessageDlg('Por favor, informe o usuário.', mtInformation, mbOKCancel, 0); Exit; end; if Trim(FrmLogin.edtSenha.Text) = '' then begin MessageDlg('Por favor, informe a sua senha.', mtInformation, mbOKCancel, 0); Exit; end; nomeUsuario := FrmLogin.edtUsuario.Text; FrmPrincipal := TFrmPrincipal.Create(FrmLogin); FrmLogin.Hide; FrmPrincipal.ShowModal; end; function ConverterRGB(r, g, b : Byte) : TColor; begin Result := RGB(r, g, b); end; procedure TFrmLogin.btnEntrarClick(Sender: TObject); begin ValidarLogin(); end; procedure TFrmLogin.FormCreate(Sender: TObject); begin FrmLogin.Color := ConverterRGB(162, 249, 147); end; procedure TFrmLogin.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then begin ValidarLogin(); end; end; end.
unit WorkWithGrids; interface uses Classes, Grids, Winapi.Windows; // показать файл в стринггриде // CodePage - 0 = DOS866 1 - win1251 procedure ShowFileInStringGrid(sgFile: TStringGrid; const FileName: string; const CodePage: Integer; const SkeepEmpty: Boolean = False); // Загрузка фадйа в StringList // CodePage 0 =(DOS866) 1 = (WIN1251) procedure FileToStrings(const FileName: string; sl: TStringList; const CodePage: Integer; const SkeepEmpty: Boolean = False); implementation uses RxStrUtils, SysUtils; procedure FileToStrings(const FileName: string; sl: TStringList; const CodePage: Integer; const SkeepEmpty: Boolean = False); var i, c: Integer; begin sl.BeginUpdate; sl.Clear; sl.LoadFromFile(FileName); c := sl.Count - 1; i := 0; while i<=c do begin if (SkeepEmpty) and (Trim(sl[i]).IsEmpty) then begin sl.delete(i); c := c - 1; end else begin if CodePage = 0 then sl[i] := OemToAnsiStr(sl[i]); i := i + 1; end; end; sl.EndUpdate; end; // показать файл в стринггриде procedure ShowFileInStringGrid(sgFile: TStringGrid; const FileName: string; const CodePage: Integer; const SkeepEmpty: Boolean = False); var tmp: TStringList; i, w: Integer; begin if Length(FileName) = 0 then Exit; if (not fileexists(FileName)) then Exit; tmp := TStringList.Create; try // tmp.LoadFromFile(FileName); FileToStrings(FileName, tmp, CodePage, SkeepEmpty); sgFile.ColCount := 3; sgFile.RowCount := tmp.Count; sgFile.FixedCols := 2; sgFile.FixedRows := 0; w := 30; for i := 0 to sgFile.RowCount - 1 do begin sgFile.RowHeights[i] := sgFile.Canvas.TextHeight('Ig') + 5; sgFile.Cells[0, i] := IntToStr(i + 1); sgFile.Cells[1, i] := IntToStr(i - sgFile.RowCount + 1); sgFile.Cells[2, i] := tmp[i]; if (w < sgFile.Canvas.TextWidth(tmp[i])) then w := sgFile.Canvas.TextWidth(tmp[i]); end; sgFile.ColWidths[1] := sgFile.Canvas.TextWidth('-' + IntToStr(sgFile.RowCount - 1)) + 5; sgFile.ColWidths[0] := sgFile.Canvas.TextWidth(IntToStr(sgFile.RowCount - 1)) + 5; if sgFile.Width < (w + sgFile.ColWidths[0] + sgFile.ColWidths[1]) then sgFile.ColWidths[2] := w + 5 else sgFile.ColWidths[2] := sgFile.Width - (sgFile.ColWidths[0] + sgFile.ColWidths[1]) - 20; finally FreeAndNil(tmp); end; end; end.
//============================================================================= // sgInput.pas //============================================================================= // // Responsible for input event processing for mouse visibility, movement and // button clicks (including the scroll wheel as button clicks) and keyboard // events for text input and key state checking. // // Change History: // // Version 3.0: // - 2010-02-02: Andrew : Added starting text reading within a region // - 2009-07-24: Andrew : Renamed mouse code // - 2009-07-10: Andrew : Added call to initialise SwinGame. // : Fixed missing const modifier on struct parameters // - 2009-06-15: Clinton: renamed+removed Is/Was and placed Key/Mouse first // moved and added meta comments, tweaked formatting. // - 2009-06-05: Andrew : Using sgShared // // Version 2.2.2: // - 2008-12-17: Andrew : Moved all integers to LongInt // - 2008-12-16: Andrew : Added WasAKeyPressed // // Version 1.1.5: // - 2008-04-18: Andrew : Added EndTextRead // // Version 1.1: // - 2008-02-13: James : changed MoveMouse so it dosnt generate mouse movement event // - 2008-01-25: Stephen: Fixed IsMouseShown // - 2008-01-25: Andrew : Fixed compiler hints // - 2008-01-22: James : changed MoveMouse to Point2D // - 2008-01-17: Aki + Andrew: Refactor // // Version 1.0: // - Various //============================================================================= {$I sgTrace.inc} /// @module Input /// @static unit sgInput; //============================================================================= interface //============================================================================= uses SDL, sgTypes; /// Returns The current window position of the mouse as a `Vector` /// /// @lib function MousePositionAsVector(): Vector; /// Returns the current window position of the mouse as a `Point2D` /// /// @lib function MousePosition(): Point2D; /// Returns the current x value of the mouse's position. /// /// @lib function MouseX(): Single; /// Returns the current y value of the mouse's position. /// /// @lib function MouseY(): Single; /// Returns the amount of accumulated mouse movement, since the last time /// `ProcessEvents` was called, as a `Vector`. /// /// @lib function MouseMovement(): Vector; /// Returns `true` if the specified button is currently pressed down. /// /// @lib function MouseDown(button: MouseButton): Boolean; /// Returns `true` if the specified button is currently up. /// /// @lib function MouseUp(button: MouseButton): Boolean; /// Returns true if the specified button was clicked since the last time /// `ProcessEvents` was called /// /// @lib function MouseClicked(button: MouseButton): Boolean; /// Moves the mouse cursor to the specified screen location. /// /// @lib /// @sn moveMouseToX:%s y:%s procedure MoveMouse(x, y : UInt16); overload; /// Moves the mouse cursor to the specified screen location. /// /// @lib MoveMouseToPoint procedure MoveMouse(const point: Point2D);overload; /// Tells the mouse cursor to be visible if it was previously hidden with /// by a `HideMouse` or `SetMouseVisible(False)` call. /// /// @lib procedure ShowMouse(); overload; /// Used to explicitly set the mouse cursors visible state (if it is showing /// in the window or not) based on the `show` parameter. /// /// @lib SetMouseVisible /// @sn showMouse:%s procedure ShowMouse(show : Boolean); overload; /// Tells the mouse cursor to hide (no longer visible) if it is currently /// showing. Use `ShowMouse` to make the mouse cursor visible again. /// /// @lib procedure HideMouse(); /// Returns `true` if the mouse is currently visible, `false` if not. /// /// @lib function MouseShown(): Boolean; /// Start reading text within an area. Entry is /// completed when the user presses ENTER, and aborted with ESCAPE. /// If the user aborts entry the result is an empty string, and TextEntryCancelled /// will return true. Text entry is updated during `ProcessEvents`, and text is drawn /// to the screen as part of the `RefreshScreen` call. /// /// @lib StartReadingTextWithinArea /// @sn startReadingTextColor:%s maxLen:%s font:%s area:%s procedure StartReadingText(textColor: Color; maxLength: LongInt; theFont: Font; const area: Rectangle); overload; /// The same as `StartReadingText' but with an additional `text` parameter /// that is displayed as default text to the user. /// /// @lib StartReadingTextWithTextInArea /// @sn startReadingTextWith:%s color:%s maxLen:%s font:%s area:%s procedure StartReadingTextWithText(text: String; textColor: Color; maxLength: LongInt; theFont: Font; const area: Rectangle); overload; /// Starts the reading of a string of characters from the user. Entry is /// completed when the user presses ENTER, and aborted with ESCAPE. /// If the user aborts entry the result is an empty string, and TextEntryCancelled will return true. /// Text entry is updated during `ProcessEvents`, and text is drawn to the screen as part /// of the `RefreshScreen` call. /// /// @lib /// @sn startReadingTextColor:%s maxLen:%s font:%s x:%s y:%s procedure StartReadingText(textColor: Color; maxLength: LongInt; theFont: Font; x, y: LongInt); overload; /// The same as `StartReadingText' but with an additional `text` parameter /// that is displayed as default text to the user. /// /// @lib StartReadingTextWithText /// @sn startReadingTextWith:%s color:%s maxLen:%s font:%s x:%s y:%s procedure StartReadingTextWithText(text: String; textColor: Color; maxLength: LongInt; theFont: Font; x, y: LongInt); overload; /// The same as `StartReadingText' but with an additional `text` parameter /// that is displayed as default text to the user. /// /// @lib StartReadingTextWithTextAtPt /// @sn startReadingTextWith:%s color:%s maxLen:%s font:%s at:%s procedure StartReadingTextWithText(text: String; textColor: Color; maxLength: LongInt; theFont: Font; const pt: Point2D); overload; /// Returns the string that has been read since `StartReadingText` or /// `StartReadingTextWithText` was called. /// /// @lib function EndReadingText(): String; /// ReadingText indicates if the API is currently reading text from the /// user. Calling StartReadingText will set this to true, and it becomes /// false when the user presses enter or escape. At this point you can /// read the string entered as either ASCII or Unicode. /// /// @lib function ReadingText(): Boolean; /// Returns true if the text entry started with `StartReadingText` was cancelled. /// /// @lib function TextEntryCancelled(): Boolean; /// TextReadAsASCII allows you to read the value of the string entered by the /// user as ASCII. See TextReasAsUNICODE, StartReadingText and ReadingText /// for more details. /// /// @lib function TextReadAsASCII(): String; /// Returns true when the key requested is being held down. This is updated /// as part of the `ProcessEvents` call. Use the key codes from `KeyCodes` /// to specify the key to be checked. /// /// @lib function KeyDown(key: KeyCode): Boolean; /// Returns true if the specified key was pressed down since the last time /// `ProcessEvents` was called. This occurs only once for the key that is /// pressed and will not return true again until the key is released and /// pressed down again. /// /// @lib function KeyTyped(key: KeyCode): Boolean; /// Checks to see if any key has been pressed since the last time /// `ProcessEvents` was called. /// /// @lib function AnyKeyPressed(): Boolean; /// The KeyName function returns a string name for a given `KeyCode`. For /// example, vk_Comma returns the string 'Comma'. This function could be used /// to display more meaningful key names for configuring game controls, etc. /// /// @lib function KeyName(key: KeyCode): String; //============================================================================= implementation //============================================================================= uses SysUtils, Classes, sgPhysics, sgTrace, sgShared, sgCore, sgText, sgGeometry; //--------------------------------------------------------------------------- function KeyTyped(key: KeyCode): Boolean; begin result := sdlManager.WasKeyTyped(LongInt(key)); end; function KeyDown(key : keyCode): Boolean; begin result := sdlManager.IsKeyPressed(LongInt(key)); end; function AnyKeyPressed(): Boolean; begin result := sdlManager.WasAKeyPressed(); end; //--------------------------------------------------------------------------- procedure StartReadingText(textColor: Color; maxLength: LongInt; theFont: Font; const area: Rectangle); overload; begin if theFont = nil then begin RaiseException('The specified font to start reading text is nil'); exit; end; if maxLength <= 0 then begin RaiseException('Minimum length to start reading text is 1'); exit; end; if ReadingText() then begin RaiseException('Already reading text, cannot start reading text again.'); exit; end; sdlManager.StartReadingText(ToSDLColor(textColor), maxLength, theFont, NewSDLRect(area)); end; procedure StartReadingText(textColor: Color; maxLength: LongInt; theFont: Font; x, y: LongInt); overload; begin StartReadingText(textColor, maxLength, theFont, RectangleFrom(x, y, TextWidth(theFont, StringOfChar('M', maxLength)), TextHeight(theFont, 'M'))); end; procedure StartReadingTextWithText(text: String; textColor: Color; maxLength: LongInt; theFont: Font; const area: Rectangle); overload; begin StartReadingText(textColor, maxLength, theFont, area); sdlManager.SetText(text); end; procedure StartReadingTextWithText(text: String; textColor: Color; maxLength: LongInt; theFont: Font; const pt: Point2D); overload; begin StartReadingTextWithText(text, textColor, maxLength, theFont, Round(pt.x), Round(pt.y)); end; procedure StartReadingTextWithText(text: String; textColor: Color; maxLength: LongInt; theFont: Font; x, y: LongInt); overload; begin StartReadingText(textColor, maxLength, theFont, x, y); sdlManager.SetText(text); end; function ReadingText(): Boolean; begin result := sdlManager.IsReading; end; function TextEntryCancelled(): Boolean; begin result := sdlManager.TextEntryWasCancelled; end; function EndReadingText(): String; begin result := sdlManager.EndReadingText(); end; function TextReadAsASCII(): String; begin result := String(sdlManager.EnteredString); end; var _ButtonsClicked: Array [MouseButton] of Boolean; //--------------------------------------------------------------------------- function MousePositionAsVector(): Vector; var x, y: LongInt; begin x := 0; y := 0; SDL_GetMouseState(x, y); result := VectorTo(x, y); end; procedure ShowMouse(); overload; begin ShowMouse(true); end; procedure HideMouse(); begin ShowMouse(false); end; procedure ShowMouse(show : Boolean); overload; begin try if show then SDL_ShowCursor(1) else SDL_ShowCursor(0); except begin RaiseException('Unable to show or hide mouse'); exit; end; end; end; procedure MoveMouse(x, y : UInt16);overload; begin SDL_WarpMouse(x,y); MouseMovement(); end; procedure MoveMouse(const point : Point2d);overload; begin SDL_WarpMouse(Round(point.x), Round(point.y)); MouseMovement(); end; function MouseShown(): Boolean; begin result := SDL_ShowCursor(-1) = 1; end; function MousePosition(): Point2D; var x, y: LongInt; begin x := 0; y := 0; SDL_GetMouseState(x, y); result := PointAt(x, y); end; function MouseX(): Single; begin result := MousePosition().x; end; function MouseY(): Single; begin result := MousePosition().y; end; function MouseMovement(): Vector; var x, y: LongInt; begin {$IFDEF TRACE} TraceEnter('sgInput', 'MouseMovement'); {$ENDIF} x := 0; y := 0; SDL_GetRelativeMouseState(x, y); result := VectorTo(x, y); {$IFDEF TRACE} TraceExit('sgInput', 'MouseMovement'); {$ENDIF} end; function MouseDown(button: MouseButton): Boolean; var x, y: LongInt; begin x := 0; y := 0; result := (SDL_GetMouseState(x, y) and SDL_BUTTON(LongInt(button))) > 0; end; function MouseUp(button: MouseButton): Boolean; begin result := not MouseDown(button); end; function MouseClicked(button: MouseButton): Boolean; begin result := _ButtonsClicked[button]; end; procedure ProcessMouseEvent(event: PSDL_Event); begin if event = nil then exit; if event^.type_ = SDL_MOUSEBUTTONUP then begin _ButtonsClicked[MouseButton(event^.button.button)] := true; end; end; procedure StartProcessMouseEvents(); var b: MouseButton; begin for b := LeftButton to MouseX2Button do _ButtonsClicked[b] := false; end; function KeyName(key: KeyCode): String; begin case key of vk_Unknown: result := 'Unknown'; vk_BACKSPACE: result := 'Backspace'; vk_TAB: result := 'Tab'; vk_CLEAR: result := 'Clear'; vk_RETURN: result := 'Return'; vk_PAUSE: result := 'Pause'; vk_ESCAPE: result := 'Escape'; vk_SPACE: result := 'Space'; vk_EXCLAIM: result := 'Exclaim'; vk_QUOTEDBL: result := 'Double Quote'; vk_HASH: result := 'Hash'; vk_DOLLAR: result := 'Dollar'; vk_AMPERSAND: result := 'Ampersand'; vk_QUOTE: result := 'Quote'; vk_LEFTPAREN: result := 'Left Parenthesis'; vk_RIGHTPAREN: result := 'Right Parenthesis'; vk_ASTERISK: result := 'Asterisk'; vk_PLUS: result := 'Plus'; vk_COMMA: result := 'Comma'; vk_MINUS: result := 'Minus'; vk_PERIOD: result := 'Period'; vk_SLASH: result := 'Slash'; vk_0: result := '0'; vk_1: result := '1'; vk_2: result := '2'; vk_3: result := '3'; vk_4: result := '4'; vk_5: result := '5'; vk_6: result := '6'; vk_7: result := '7'; vk_8: result := '8'; vk_9: result := '9'; vk_COLON: result := 'Colon'; vk_SEMICOLON: result := 'Semicolon'; vk_LESS: result := 'Less'; vk_EQUALS: result := 'Equals'; vk_GREATER: result := 'Greater'; vk_QUESTION: result := 'Question'; vk_AT: result := 'At'; // Skip uppercase letters vk_LEFTBRACKET: result := 'Left Bracket'; vk_BACKSLASH: result := 'Backslash'; vk_RIGHTBRACKET: result := 'Right Bracket'; vk_CARET: result := 'Caret'; vk_UNDERSCORE: result := 'Underscore'; vk_BACKQUOTE: result := 'Back Quote'; vk_a: result := 'a'; vk_b: result := 'b'; vk_c: result := 'c'; vk_d: result := 'd'; vk_e: result := 'e'; vk_f: result := 'f'; vk_g: result := 'g'; vk_h: result := 'h'; vk_i: result := 'i'; vk_j: result := 'j'; vk_k: result := 'k'; vk_l: result := 'l'; vk_m: result := 'm'; vk_n: result := 'n'; vk_o: result := 'o'; vk_p: result := 'p'; vk_q: result := 'q'; vk_r: result := 'r'; vk_s: result := 's'; vk_t: result := 't'; vk_u: result := 'u'; vk_v: result := 'v'; vk_w: result := 'w'; vk_x: result := 'x'; vk_y: result := 'y'; vk_z: result := 'z'; vk_DELETE: result := 'Delete'; // End of ASCII mapped keysyms // International keyboard syms vk_WORLD_0: result := 'World 0'; vk_WORLD_1: result := 'World 1'; vk_WORLD_2: result := 'World 2'; vk_WORLD_3: result := 'World 3'; vk_WORLD_4: result := 'World 4'; vk_WORLD_5: result := 'World 5'; vk_WORLD_6: result := 'World 6'; vk_WORLD_7: result := 'World 7'; vk_WORLD_8: result := 'World 8'; vk_WORLD_9: result := 'World 9'; vk_WORLD_10: result := 'World 10'; vk_WORLD_11: result := 'World 11'; vk_WORLD_12: result := 'World 12'; vk_WORLD_13: result := 'World 13'; vk_WORLD_14: result := 'World 14'; vk_WORLD_15: result := 'World 15'; vk_WORLD_16: result := 'World 16'; vk_WORLD_17: result := 'World 17'; vk_WORLD_18: result := 'World 18'; vk_WORLD_19: result := 'World 19'; vk_WORLD_20: result := 'World 20'; vk_WORLD_21: result := 'World 21'; vk_WORLD_22: result := 'World 22'; vk_WORLD_23: result := 'World 23'; vk_WORLD_24: result := 'World 24'; vk_WORLD_25: result := 'World 25'; vk_WORLD_26: result := 'World 26'; vk_WORLD_27: result := 'World 27'; vk_WORLD_28: result := 'World 28'; vk_WORLD_29: result := 'World 29'; vk_WORLD_30: result := 'World 30'; vk_WORLD_31: result := 'World 31'; vk_WORLD_32: result := 'World 32'; vk_WORLD_33: result := 'World 33'; vk_WORLD_34: result := 'World 34'; vk_WORLD_35: result := 'World 35'; vk_WORLD_36: result := 'World 36'; vk_WORLD_37: result := 'World 37'; vk_WORLD_38: result := 'World 38'; vk_WORLD_39: result := 'World 39'; vk_WORLD_40: result := 'World 40'; vk_WORLD_41: result := 'World 41'; vk_WORLD_42: result := 'World 42'; vk_WORLD_43: result := 'World 43'; vk_WORLD_44: result := 'World 44'; vk_WORLD_45: result := 'World 45'; vk_WORLD_46: result := 'World 46'; vk_WORLD_47: result := 'World 47'; vk_WORLD_48: result := 'World 48'; vk_WORLD_49: result := 'World 49'; vk_WORLD_50: result := 'World 50'; vk_WORLD_51: result := 'World 51'; vk_WORLD_52: result := 'World 52'; vk_WORLD_53: result := 'World 53'; vk_WORLD_54: result := 'World 54'; vk_WORLD_55: result := 'World 55'; vk_WORLD_56: result := 'World 56'; vk_WORLD_57: result := 'World 57'; vk_WORLD_58: result := 'World 58'; vk_WORLD_59: result := 'World 59'; vk_WORLD_60: result := 'World 60'; vk_WORLD_61: result := 'World 61'; vk_WORLD_62: result := 'World 62'; vk_WORLD_63: result := 'World 63'; vk_WORLD_64: result := 'World 64'; vk_WORLD_65: result := 'World 65'; vk_WORLD_66: result := 'World 66'; vk_WORLD_67: result := 'World 67'; vk_WORLD_68: result := 'World 68'; vk_WORLD_69: result := 'World 69'; vk_WORLD_70: result := 'World 70'; vk_WORLD_71: result := 'World 71'; vk_WORLD_72: result := 'World 72'; vk_WORLD_73: result := 'World 73'; vk_WORLD_74: result := 'World 74'; vk_WORLD_75: result := 'World 75'; vk_WORLD_76: result := 'World 76'; vk_WORLD_77: result := 'World 77'; vk_WORLD_78: result := 'World 78'; vk_WORLD_79: result := 'World 79'; vk_WORLD_80: result := 'World 80'; vk_WORLD_81: result := 'World 81'; vk_WORLD_82: result := 'World 82'; vk_WORLD_83: result := 'World 83'; vk_WORLD_84: result := 'World 84'; vk_WORLD_85: result := 'World 85'; vk_WORLD_86: result := 'World 86'; vk_WORLD_87: result := 'World 87'; vk_WORLD_88: result := 'World 88'; vk_WORLD_89: result := 'World 89'; vk_WORLD_90: result := 'World 90'; vk_WORLD_91: result := 'World 91'; vk_WORLD_92: result := 'World 92'; vk_WORLD_93: result := 'World 93'; vk_WORLD_94: result := 'World 94'; vk_WORLD_95: result := 'World 95'; // Numeric keypad vk_KP0: result := 'Keypad 0'; vk_KP1: result := 'Keypad 1'; vk_KP2: result := 'Keypad 2'; vk_KP3: result := 'Keypad 3'; vk_KP4: result := 'Keypad 4'; vk_KP5: result := 'Keypad 5'; vk_KP6: result := 'Keypad 6'; vk_KP7: result := 'Keypad 7'; vk_KP8: result := 'Keypad 8'; vk_KP9: result := 'Keypad 9'; vk_KP_PERIOD: result := 'Keypad Period'; vk_KP_DIVIDE: result := 'Keypad Divide'; vk_KP_MULTIPLY: result := 'Keypad Multiply'; vk_KP_MINUS: result := 'Keypad Minus'; vk_KP_PLUS: result := 'Keypad Plus'; vk_KP_ENTER: result := 'Keypad Enter'; vk_KP_EQUALS: result := 'Keypad Equals'; // Arrows + Home/End pad vk_UP: result := 'Up'; vk_DOWN: result := 'Down'; vk_RIGHT: result := 'Right'; vk_LEFT: result := 'Left'; vk_INSERT: result := 'Insert'; vk_HOME: result := 'Home'; vk_END: result := 'End'; vk_PAGEUP: result := 'Page Up'; vk_PAGEDOWN: result := 'Page Down'; // Function keys vk_F1: result := 'F1'; vk_F2: result := 'F2'; vk_F3: result := 'F3'; vk_F4: result := 'F4'; vk_F5: result := 'F5'; vk_F6: result := 'F6'; vk_F7: result := 'F7'; vk_F8: result := 'F8'; vk_F9: result := 'F9'; vk_F10: result := 'F10'; vk_F11: result := 'F11'; vk_F12: result := 'F12'; vk_F13: result := 'F13'; vk_F14: result := 'F14'; vk_F15: result := 'F15'; // Key state modifier keys vk_NUMLOCK: result := 'Numlock'; vk_CAPSLOCK: result := 'Caps lock'; vk_SCROLLOCK: result := 'Scroll Lock'; vk_RSHIFT: result := 'Right Shift'; vk_LSHIFT: result := 'Left Shift'; vk_RCTRL: result := 'Right Ctrl'; vk_LCTRL: result := 'Left Ctrl'; vk_RALT: result := 'Right Alt'; vk_LALT: result := 'Left Alt'; vk_RMETA: result := 'Right Meta'; vk_LMETA: result := 'Left Meta'; vk_LSUPER: result := 'Left Super'; vk_RSUPER: result := 'Right Super'; vk_MODE: result := 'Mode'; vk_COMPOSE: result := 'Compose'; // Miscellaneous function keys vk_HELP: result := 'Help'; vk_PRINT: result := 'Print'; vk_SYSREQ: result := 'Sys Req'; vk_BREAK: result := 'Break'; vk_MENU: result := 'Menu'; vk_POWER: result := 'Power'; vk_EURO: result := 'Euro'; end; end; //============================================================================= initialization begin InitialiseSwinGame(); RegisterEventProcessor(@ProcessMouseEvent, @StartProcessMouseEvents); end; end.
unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Mask, ToolEdit; type TForm1 = class(TForm) DirectoryEdit1: TDirectoryEdit; Label1: TLabel; RgpOpenMode: TRadioGroup; RgpShareMode: TRadioGroup; Button1: TButton; Memo1: TMemo; BtnRead: TButton; BtnWrite: TButton; BtnSpeedTest: TButton; ChkFlushCache: TCheckBox; ChkUseAPI: TCheckBox; procedure Button1Click(Sender: TObject); procedure BtnReadClick(Sender: TObject); procedure BtnWriteClick(Sender: TObject); procedure BtnSpeedTestClick(Sender: TObject); private { Private-Deklarationen } FStream : TFileStream; function GetFileStreamMode:Word; procedure MeasureResultHandler(const s:string); public { Public-Deklarationen } end; var Form1: TForm1; implementation uses UStopWatch, USpeedTest; {$R *.DFM} { TForm1 } function TForm1.GetFileStreamMode: Word; var sharemode:Word; begin case RgpOpenMode.ItemIndex of 0: Result := fmCreate; 1: Result := fmOpenRead; 2: Result := fmOpenWrite; 3: Result := fmOpenReadWrite; else raise Exception.Create('Open Mode fehlt'); end; case RgpShareMode.ItemIndex of 0: sharemode := fmShareCompat; 1: sharemode := fmShareExclusive; 2: sharemode := fmShareDenyWrite; 3: sharemode := fmShareDenyRead; 4: sharemode := fmShareDenyNone; else raise Exception.Create('Share Mode fehlt'); end; Result := Result or sharemode; end; procedure TForm1.Button1Click(Sender: TObject); var capt:string; begin if Assigned(FStream) then begin FStream.Free; FStream := nil; capt := 'Open'; DirectoryEdit1.Enabled := True; BtnSpeedTest.Enabled := False; end else begin // FStream := TFileStream.Create(DirectoryEdit1.Text+'test.dat',GetFileStreamMode); FStream := TFileStream.Create(DirectoryEdit1.Text,GetFileStreamMode); capt := 'Close'; DirectoryEdit1.Enabled := False; BtnSpeedTest.Enabled := True; end; (Sender as TButton).Caption := capt; end; procedure TForm1.BtnReadClick(Sender: TObject); begin if not Assigned(FStream) then Exit; FStream.Position := 0; Memo1.Lines.LoadFromStream(FStream); end; procedure TForm1.BtnWriteClick(Sender: TObject); begin if not Assigned(FStream) then Exit; FStream.Position := 0; Memo1.Lines.SaveToStream(FStream); end; procedure TForm1.BtnSpeedTestClick(Sender: TObject); var st : TFileSpeedTest; begin st := TFileSpeedTest.Create(FStream); try st.OnMeasureResult := Self.MeasureResultHandler; // st.FileSize := $200000; st.DoSpeedTest(ChkUseAPI.Checked, ChkFlushCache.Checked); finally st.Free; end; end; procedure TForm1.MeasureResultHandler(const s: string); begin Memo1.Lines.Add(s); Application.ProcessMessages; end; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit CLSearchUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, VarsUnit, JvExComCtrls, JvListView, CategoryButtons, ComCtrls, ExtCtrls, JvSimpleXml; type TCLSearchForm = class(TForm) TopPanel: TPanel; CLSearchLabel: TLabel; CLSearchEdit: TEdit; CLSearchJvListView: TJvListView; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CLSearchEditChange(Sender: TObject); procedure CLSearchJvListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure CLSearchJvListViewDblClick(Sender: TObject); procedure CLSearchJvListViewColumnClick(Sender: TObject; Column: TListColumn); procedure FormDblClick(Sender: TObject); procedure FormDeactivate(Sender: TObject); private { Private declarations } public { Public declarations } procedure TranslateForm; end; {$ENDREGION} var CLSearchForm: TCLSearchForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, UtilsUnit, OverbyteIcsUrl, RosterUnit; {$ENDREGION} {$REGION 'MyConst'} const C_CLSearchForm = 'cl_search_form'; {$ENDREGION} {$REGION 'CLSearchEditChange'} procedure TCLSearchForm.CLSearchEditChange(Sender: TObject); var I: Integer; SearchText: string; procedure FindInRoster(Proto: string); var Z: Integer; XML_Node, Sub_Node, Tri_Node: TJvSimpleXmlElem; UIN, Nick: string; begin if V_Roster <> nil then begin with V_Roster do begin if Root <> nil then begin XML_Node := Root.Items.ItemNamed[Proto]; if XML_Node <> nil then begin // Открываем раздел контактов Sub_Node := XML_Node.Items.ItemNamed[C_Contact + C_SS]; if Sub_Node <> nil then begin // Ищем параметр этого контакта for Z := 0 to Sub_Node.Items.Count - 1 do begin Tri_Node := Sub_Node.Items.Item[Z]; if Tri_Node <> nil then begin UIN := WideUpperCase(UrlDecode(Tri_Node.Properties.Value(C_Login))); Nick := WideUpperCase(UrlDecode(Tri_Node.Properties.Value(C_Nick))); // Если нашли текст в учётной записи или нике if (Pos(SearchText, UIN) > 0) or (Pos(SearchText, Nick) > 0) then begin CLSearchJvListView.Items.Add.Caption := URLDecode(Tri_Node.Properties.Value(C_Login)); CLSearchJvListView.Items[CLSearchJvListView.Items.Count - 1].SubItems.Append(URLDecode(Tri_Node.Properties.Value(C_Nick))); CLSearchJvListView.Items[CLSearchJvListView.Items.Count - 1].SubItems.Append(Proto); CLSearchJvListView.Items[CLSearchJvListView.Items.Count - 1].ImageIndex := StrToInt(Tri_Node.Properties.Value(C_Status)); end; end; end; end; end; end; end; end; end; begin // Делаем поиск совпадений введенных символов в учётных записях и никах контактов в списке // Очищаем список контактов от предыдущего поиска CLSearchJvListView.Clear; // Сбрасываем стрелочки сортировки в других столбцах for I := 0 to CLSearchJvListView.Columns.Count - 1 do CLSearchJvListView.Columns[I].ImageIndex := -1; // Делаем поиск текста if CLSearchEdit.Text <> EmptyStr then begin SearchText := WideUpperCase(CLSearchEdit.Text); // Ищем раздел нужного нам протокола if MainForm.ICQToolButton.Visible then FindInRoster(C_Icq); if MainForm.JabberToolButton.Visible then FindInRoster(C_Jabber); if MainForm.MRAToolButton.Visible then FindInRoster(C_Mra); end; end; {$ENDREGION} {$REGION 'Other'} procedure TCLSearchForm.CLSearchJvListViewColumnClick(Sender: TObject; Column: TListColumn); var I: Integer; begin // Выставляем стрелочку сортировки if Column.ImageIndex <> 234 then Column.ImageIndex := 234 else Column.ImageIndex := 233; // Сбрасываем стрелочки сортировки в других столбцах for I := 0 to CLSearchJvListView.Columns.Count - 1 do if CLSearchJvListView.Columns[I] <> Column then CLSearchJvListView.Columns[I].ImageIndex := -1; end; procedure TCLSearchForm.CLSearchJvListViewDblClick(Sender: TObject); begin // Если выделили контакт, то выделяем его и в КЛ if CLSearchJvListView.Selected <> nil then begin // Открываем чат с этим контактом MainForm.SendMessageForContactClick(nil); end; end; procedure TCLSearchForm.CLSearchJvListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var KL_Item: TButtonItem; begin // Если выделили контакт, то выделяем его и в КЛ if Selected then begin // Отключаем режим КЛ только онлайн контакты if MainForm.OnlyOnlineContactsToolButton.Down then begin MainForm.OnlyOnlineContactsToolButton.Down := false; MainForm.OnlyOnlineContactsToolButtonClick(nil); end; // Получаем этот контакт в КЛ KL_Item := ReqCLContact(Item.SubItems[1], UrlEncode(Item.Caption)); if KL_Item <> nil then begin // Выделяем этот контакт в КЛ MainForm.ContactList.SelectedItem := KL_Item; if KL_Item.Category.Collapsed then KL_Item.Category.Collapsed := False; MainForm.ContactList.ScrollIntoView(KL_Item); end else MainForm.ContactList.SelectedItem := nil; end; end; procedure TCLSearchForm.FormClose(Sender: TObject; var Action: TCloseAction); begin // Выводим окно списка контактов на передний план BringWindowToTop(MainForm.Handle); // Уничтожаем окно CLSearchJvListView.HeaderImages := nil; Action := CaFree; CLSearchForm := nil; end; procedure TCLSearchForm.FormDblClick(Sender: TObject); begin // Устанавливаем перевод TranslateForm; end; {$ENDREGION} {$REGION 'FormCreate'} procedure TCLSearchForm.FormCreate(Sender: TObject); var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin // Загружаем настройки if FileExists(V_ProfilePath + C_SettingsFileName) then begin LoadFromFile(V_ProfilePath + C_SettingsFileName); if Root <> nil then begin XML_Node := Root.Items.ItemNamed[C_CLSearchForm]; if XML_Node <> nil then begin Top := XML_Node.Properties.IntValue('t'); Left := XML_Node.Properties.IntValue('l'); Height := XML_Node.Properties.IntValue('h'); Width := XML_Node.Properties.IntValue('w'); // Определяем не находится ли окно за пределами экрана FormSetInWorkArea(Self); end; end; end; end; finally JvXML.Free; end; // Переводим окно на другие языки TranslateForm; // Применяем иконки к окну и кнопкам MainForm.AllImageList.GetIcon(215, Icon); // Делаем окно независимым и помещаем его кнопку на панель задач SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end; {$ENDREGION} {$REGION 'FormDestroy'} procedure TCLSearchForm.FormDeactivate(Sender: TObject); begin // Сбрасываем выделенние CLSearchJvListView.Selected := nil; end; procedure TCLSearchForm.FormDestroy(Sender: TObject); var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Создаём необходимые папки ForceDirectories(V_ProfilePath); // Сохраняем настройки положения окна в xml // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin if FileExists(V_ProfilePath + C_SettingsFileName) then LoadFromFile(V_ProfilePath + C_SettingsFileName); if Root <> nil then begin // Очищаем раздел формы если он есть XML_Node := Root.Items.ItemNamed[C_CLSearchForm]; if XML_Node <> nil then XML_Node.Clear else XML_Node := Root.Items.Add(C_CLSearchForm); // Сохраняем позицию окна XML_Node.Properties.Add('t', Top); XML_Node.Properties.Add('l', Left); XML_Node.Properties.Add('h', Height); XML_Node.Properties.Add('w', Width); end; // Записываем сам файл SaveToFile(V_ProfilePath + C_SettingsFileName); end; finally JvXML.Free; end; end; {$ENDREGION} {$REGION 'TranslateForm'} procedure TCLSearchForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); end; {$ENDREGION} end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcCipherTest.pas } { File version: 5.08 } { Description: Cipher Test } { } { Copyright: Copyright (c) 2007-2021, David J Butler } { All rights reserved. } { This file is licensed under the BSD License. } { See http://www.opensource.org/licenses/bsd-license.php } { 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. } { 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 REGENTS 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. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2007/01/05 0.01 Initial version. } { 2007/01/07 0.02 ECB and padding support. } { 2008/06/15 0.03 CBC mode. } { 2008/06/17 0.04 CFB and OFB modes. } { 2010/12/16 4.05 AES cipher. } { 2016/01/09 5.06 Revised for Fundamentals 5. } { 2019/06/09 5.07 Tests for Triple-DES-EDE-3. } { 2020/05/20 5.08 Create flcCipherTest unit from flcCipher unit. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$INCLUDE flcCrypto.inc} unit flcCipherTest; interface { } { Test } { } {$IFDEF CIPHER_TEST} procedure Test; {$ENDIF} {$IFDEF CIPHER_PROFILE} procedure Profile; {$ENDIF} implementation uses SysUtils, flcStdTypes, flcUtils, flcCryptoRandom, flcCipherRC2, flcCipherAES, flcCipherDES, flcCipherDH, flcCipherRSA, {$IFDEF Cipher_SupportEC} flcCipherEllipticCurve, {$ENDIF} flcCipher; { } { Test } { } {$IFDEF CIPHER_TEST} {$ASSERTIONS ON} type TCipherTestCase = record Cipher : TCipherType; Mode : TCipherMode; KeyBits : Integer; // Effective key length (bits) Key : RawByteString; InitVector : RawByteString; PlainText : RawByteString; CipherText : RawByteString; end; const CipherTestCaseCount = 36; var CipherTestCases : array[0..CipherTestCaseCount - 1] of TCipherTestCase = ( // RC2 test vectors from RFC 2268 (Cipher: ctRC2; Mode: cmECB; KeyBits: 63; Key: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$eb#$b7#$73#$f9#$93#$27#$8e#$ff)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$ff#$ff#$ff#$ff#$ff#$ff#$ff#$ff); PlainText: RawByteString(#$ff#$ff#$ff#$ff#$ff#$ff#$ff#$ff); CipherText: RawByteString(#$27#$8b#$27#$e4#$2e#$2f#$0d#$49)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$30#$00#$00#$00#$00#$00#$00#$00); PlainText: RawByteString(#$10#$00#$00#$00#$00#$00#$00#$01); CipherText: RawByteString(#$30#$64#$9e#$df#$9b#$e7#$d2#$c2)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$88); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$61#$a8#$a2#$44#$ad#$ac#$cc#$f0)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$88#$bc#$a9#$0e#$90#$87#$5a); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$6c#$cf#$43#$08#$97#$4c#$26#$7f)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$88#$bc#$a9#$0e#$90#$87#$5a#$7f#$0f#$79#$c3#$84#$62#$7b#$af#$b2); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$1a#$80#$7d#$27#$2b#$be#$5d#$b1)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 128; Key: RawByteString(#$88#$bc#$a9#$0e#$90#$87#$5a#$7f#$0f#$79#$c3#$84#$62#$7b#$af#$b2); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$22#$69#$55#$2a#$b0#$f8#$5c#$a6)), (Cipher: ctRC2; Mode: cmECB; KeyBits: 129; Key: RawByteString(#$88#$bc#$a9#$0e#$90#$87#$5a#$7f#$0f#$79#$c3#$84#$62#$7b#$af#$b2#$16#$f8#$0a#$6f#$85#$92#$05#$84#$c4#$2f#$ce#$b0#$be#$25#$5d#$af#$1e); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$5b#$78#$d3#$a4#$3d#$ff#$f1#$f1)), // RC4 test vectors from http://en.wikipedia.org/wiki/RC4 (Cipher: ctRC4; Mode: cmECB; KeyBits: 24; Key: 'Key'; PlainText: 'Plaintext'; CipherText: RawByteString(#$BB#$F3#$16#$E8#$D9#$40#$AF#$0A#$D3)), (Cipher: ctRC4; Mode: cmECB; KeyBits: 32; Key: 'Wiki'; PlainText: 'pedia'; CipherText: RawByteString(#$10#$21#$BF#$04#$20)), (Cipher: ctRC4; Mode: cmECB; KeyBits: 48; Key: 'Secret'; PlainText: 'Attack at dawn'; CipherText: RawByteString(#$45#$A0#$1F#$64#$5F#$C3#$5B#$38#$35#$52#$54#$4B#$9B#$F5)), // RC4 test vectors from Internet Draft on ARCFOUR (Cipher: ctRC4; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$01#$23#$45#$67#$89#$AB#$CD#$EF); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$74#$94#$C2#$E7#$10#$4B#$08#$79)), (Cipher: ctRC4; Mode: cmECB; KeyBits: 40; Key: RawByteString(#$61#$8a#$63#$d2#$fb); PlainText: RawByteString(#$dc#$ee#$4c#$f9#$2c); CipherText: RawByteString(#$f1#$38#$29#$c9#$de)), (Cipher: ctRC4; Mode: cmECB; KeyBits: 128; Key: RawByteString(#$29#$04#$19#$72#$fb#$42#$ba#$5f#$c7#$12#$77#$12#$f1#$38#$29#$c9); PlainText: RawByteString(#$52#$75#$69#$73#$6c#$69#$6e#$6e#$75#$6e#$20#$6c#$61#$75#$6c#$75 + #$20#$6b#$6f#$72#$76#$69#$73#$73#$73#$61#$6e#$69#$2c#$20#$74#$e4 + #$68#$6b#$e4#$70#$e4#$69#$64#$65#$6e#$20#$70#$e4#$e4#$6c#$6c#$e4 + #$20#$74#$e4#$79#$73#$69#$6b#$75#$75#$2e#$20#$4b#$65#$73#$e4#$79 + #$f6#$6e#$20#$6f#$6e#$20#$6f#$6e#$6e#$69#$20#$6f#$6d#$61#$6e#$61 + #$6e#$69#$2c#$20#$6b#$61#$73#$6b#$69#$73#$61#$76#$75#$75#$6e#$20 + #$6c#$61#$61#$6b#$73#$6f#$74#$20#$76#$65#$72#$68#$6f#$75#$75#$2e + #$20#$45#$6e#$20#$6d#$61#$20#$69#$6c#$6f#$69#$74#$73#$65#$2c#$20 + #$73#$75#$72#$65#$20#$68#$75#$6f#$6b#$61#$61#$2c#$20#$6d#$75#$74 + #$74#$61#$20#$6d#$65#$74#$73#$e4#$6e#$20#$74#$75#$6d#$6d#$75#$75 + #$73#$20#$6d#$75#$6c#$6c#$65#$20#$74#$75#$6f#$6b#$61#$61#$2e#$20 + #$50#$75#$75#$6e#$74#$6f#$20#$70#$69#$6c#$76#$65#$6e#$2c#$20#$6d + #$69#$20#$68#$75#$6b#$6b#$75#$75#$2c#$20#$73#$69#$69#$6e#$74#$6f + #$20#$76#$61#$72#$61#$6e#$20#$74#$75#$75#$6c#$69#$73#$65#$6e#$2c + #$20#$6d#$69#$20#$6e#$75#$6b#$6b#$75#$75#$2e#$20#$54#$75#$6f#$6b + #$73#$75#$74#$20#$76#$61#$6e#$61#$6d#$6f#$6e#$20#$6a#$61#$20#$76 + #$61#$72#$6a#$6f#$74#$20#$76#$65#$65#$6e#$2c#$20#$6e#$69#$69#$73 + #$74#$e4#$20#$73#$79#$64#$e4#$6d#$65#$6e#$69#$20#$6c#$61#$75#$6c + #$75#$6e#$20#$74#$65#$65#$6e#$2e#$20#$2d#$20#$45#$69#$6e#$6f#$20 + #$4c#$65#$69#$6e#$6f); CipherText: RawByteString(#$35#$81#$86#$99#$90#$01#$e6#$b5#$da#$f0#$5e#$ce#$eb#$7e#$ee#$21 + #$e0#$68#$9c#$1f#$00#$ee#$a8#$1f#$7d#$d2#$ca#$ae#$e1#$d2#$76#$3e + #$68#$af#$0e#$ad#$33#$d6#$6c#$26#$8b#$c9#$46#$c4#$84#$fb#$e9#$4c + #$5f#$5e#$0b#$86#$a5#$92#$79#$e4#$f8#$24#$e7#$a6#$40#$bd#$22#$32 + #$10#$b0#$a6#$11#$60#$b7#$bc#$e9#$86#$ea#$65#$68#$80#$03#$59#$6b + #$63#$0a#$6b#$90#$f8#$e0#$ca#$f6#$91#$2a#$98#$eb#$87#$21#$76#$e8 + #$3c#$20#$2c#$aa#$64#$16#$6d#$2c#$ce#$57#$ff#$1b#$ca#$57#$b2#$13 + #$f0#$ed#$1a#$a7#$2f#$b8#$ea#$52#$b0#$be#$01#$cd#$1e#$41#$28#$67 + #$72#$0b#$32#$6e#$b3#$89#$d0#$11#$bd#$70#$d8#$af#$03#$5f#$b0#$d8 + #$58#$9d#$bc#$e3#$c6#$66#$f5#$ea#$8d#$4c#$79#$54#$c5#$0c#$3f#$34 + #$0b#$04#$67#$f8#$1b#$42#$59#$61#$c1#$18#$43#$07#$4d#$f6#$20#$f2 + #$08#$40#$4b#$39#$4c#$f9#$d3#$7f#$f5#$4b#$5f#$1a#$d8#$f6#$ea#$7d + #$a3#$c5#$61#$df#$a7#$28#$1f#$96#$44#$63#$d2#$cc#$35#$a4#$d1#$b0 + #$34#$90#$de#$c5#$1b#$07#$11#$fb#$d6#$f5#$5f#$79#$23#$4d#$5b#$7c + #$76#$66#$22#$a6#$6d#$e9#$2b#$e9#$96#$46#$1d#$5e#$4d#$c8#$78#$ef + #$9b#$ca#$03#$05#$21#$e8#$35#$1e#$4b#$ae#$d2#$fd#$04#$f9#$46#$73 + #$68#$c4#$ad#$6a#$c1#$86#$d0#$82#$45#$b2#$63#$a2#$66#$6d#$1f#$6c + #$54#$20#$f1#$59#$9d#$fd#$9f#$43#$89#$21#$c2#$f5#$a4#$63#$93#$8c + #$e0#$98#$22#$65#$ee#$f7#$01#$79#$bc#$55#$3f#$33#$9e#$b1#$a4#$c1 + #$af#$5f#$6a#$54#$7f)), // AES test vectors generated from online AES calculator at http://www.unsw.adfa.edu.au/~lpb/src/AEScalc/AEScalc.html (Cipher: ctAES; Mode: cmECB; KeyBits: 128; Key: RawByteString(#$0f#$15#$71#$c9#$47#$d9#$e8#$59#$0c#$b7#$ad#$d6#$af#$7f#$67#$98); PlainText: '1234567890123456'; CipherText: RawByteString(#$2f#$7d#$76#$42#$5e#$bb#$85#$e4#$f2#$e7#$b0#$08#$68#$bf#$0f#$ce)), (Cipher: ctAES; Mode: cmECB; KeyBits: 128; Key: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00); PlainText: RawByteString(#$14#$0f#$0f#$10#$11#$b5#$22#$3d#$79#$58#$77#$17#$ff#$d9#$ec#$3a); CipherText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00)), (Cipher: ctAES; Mode: cmECB; KeyBits: 192; Key: RawByteString(#$96#$43#$D8#$33#$4A#$63#$DF#$4D#$48#$E3#$1E#$9E#$25#$67#$18#$F2#$92#$29#$31#$9C#$19#$F1#$5B#$A4); PlainText: RawByteString(#$23#$00#$ea#$46#$3f#$43#$72#$64#$12#$75#$5f#$4c#$83#$e2#$cb#$78); CipherText: RawByteString(#$48#$E3#$1E#$9E#$25#$67#$18#$F2#$92#$29#$31#$9C#$19#$F1#$5B#$A4)), (Cipher: ctAES; Mode: cmECB; KeyBits: 256; Key: RawByteString(#$85#$C6#$B2#$BB#$23#$00#$14#$8F#$94#$5A#$EB#$F1#$F0#$21#$CF#$79#$05#$8C#$CF#$FD#$BB#$CB#$38#$2D#$1F#$6F#$56#$58#$5D#$8A#$4A#$DE); PlainText: RawByteString(#$e7#$0f#$9e#$09#$08#$87#$0a#$1d#$cf#$09#$60#$ae#$13#$d0#$7c#$68); CipherText: RawByteString(#$05#$8C#$CF#$FD#$BB#$CB#$38#$2D#$1F#$6F#$56#$58#$5D#$8A#$4A#$DE)), // AES test vectors generated from online AES calculator at http://www.riscure.com/tech-corner/online-crypto-tools/aes.html (Cipher: ctAES; Mode: cmCBC; KeyBits: 128; Key: RawByteString(#$84#$52#$35#$BA#$BE#$BD#$14#$84#$63#$E9#$DB#$46#$74#$77#$F9#$D2); InitVector: RawByteString(#$01#$02#$03#$04#$05#$06#$07#$08#$09#$10#$11#$12#$13#$14#$15#$16); PlainText: RawByteString(#$8F#$98#$3F#$D0#$99#$A3#$6D#$1E#$2F#$A5#$B3#$86#$31#$14#$42#$08); CipherText: RawByteString(#$7E#$50#$7D#$C5#$D8#$ED#$3B#$A9#$F4#$C9#$30#$C8#$13#$D4#$A7#$BC)), // DES test vectors from http://www.aci.net/Kalliste/des.htm (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$13#$34#$57#$79#$9B#$BC#$DF#$F1); PlainText: RawByteString(#$01#$23#$45#$67#$89#$AB#$CD#$EF); CipherText: RawByteString(#$85#$E8#$13#$54#$0F#$0A#$B4#$05)), (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$0E#$32#$92#$32#$EA#$6D#$0D#$73); PlainText: RawByteString(#$87#$87#$87#$87#$87#$87#$87#$87); CipherText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00)), // DES test vectors from http://groups.google.com/group/sci.crypt/msg/1e08a60f44daa890?&hl=en (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$01#$01#$01#$01#$01#$01#$01#$01); PlainText: RawByteString(#$95#$F8#$A5#$E5#$DD#$31#$D9#$00); CipherText: RawByteString(#$80#$00#$00#$00#$00#$00#$00#$00)), (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$7C#$A1#$10#$45#$4A#$1A#$6E#$57); PlainText: RawByteString(#$01#$A1#$D6#$D0#$39#$77#$67#$42); CipherText: RawByteString(#$69#$0F#$5B#$0D#$9A#$26#$93#$9B)), (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$80#$01#$01#$01#$01#$01#$01#$01); PlainText: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00); CipherText: RawByteString(#$95#$A8#$D7#$28#$13#$DA#$A9#$4D)), // DES test vectors from http://tero.co.uk/des/show.php (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: '12345678'; PlainText: 'This is the message to encrypt!!'; CipherText: RawByteString(#$05#$c9#$c4#$ca#$fb#$99#$37#$d9#$5b#$bf#$be#$df#$c5#$d7#$7f#$19 + #$a6#$cd#$5a#$5d#$ab#$18#$8a#$33#$df#$d8#$97#$9f#$c4#$b7#$b2#$be)), (Cipher: ctDES; Mode: cmCBC; KeyBits: 64; Key: '12345678'; InitVector: 'abcdefgh'; PlainText: 'This is the message to encrypt!!'; CipherText: RawByteString(#$6c#$a9#$47#$0c#$84#$9d#$1c#$c1#$a5#$9f#$fc#$14#$8f#$1c#$b5#$e9 + #$cf#$1f#$5c#$03#$28#$a7#$e8#$75#$63#$87#$ff#$4d#$0f#$e4#$60#$50)), (Cipher: ctDES; Mode: cmECB; KeyBits: 64; Key: RawByteString(#$01#$23#$45#$67#$89#$ab#$cd#$ef); PlainText: 'Now is the time for all '; CipherText: RawByteString(#$3f#$a4#$0e#$8a#$98#$4d#$48#$15#$6a#$27#$17#$87#$ab#$88#$83#$f9 + #$89#$3d#$51#$ec#$4b#$56#$3b#$53)), // DES test vectors from http://www.herongyang.com/crypto/des_php_implementation_mcrypt_2.html (Cipher: ctDES; Mode: cmCBC; KeyBits: 64; Key: RawByteString(#$01#$23#$45#$67#$89#$ab#$cd#$ef); InitVector: RawByteString(#$12#$34#$56#$78#$90#$ab#$cd#$ef); PlainText: RawByteString(#$4e#$6f#$77#$20#$69#$73#$20#$74#$68#$65#$20#$74#$69#$6d#$65#$20 + #$66#$6f#$72#$20#$61#$6c#$6c#$20); CipherText: RawByteString(#$e5#$c7#$cd#$de#$87#$2b#$f2#$7c#$43#$e9#$34#$00#$8c#$38#$9c#$0f + #$68#$37#$88#$49#$9a#$7c#$05#$f6)), (Cipher: ctDES; Mode: cmCFB; KeyBits: 64; Key: RawByteString(#$01#$23#$45#$67#$89#$ab#$cd#$ef); InitVector: RawByteString(#$12#$34#$56#$78#$90#$ab#$cd#$ef); PlainText: RawByteString(#$4e#$6f#$77#$20#$69#$73#$20#$74#$68#$65#$20#$74#$69#$6d#$65#$20 + #$66#$6f#$72#$20#$61#$6c#$6c#$20); CipherText: RawByteString(#$f3#$1f#$da#$07#$01#$14#$62#$ee#$18#$7f#$43#$d8#$0a#$7c#$d9#$b5 + #$b0#$d2#$90#$da#$6e#$5b#$9a#$87)), (Cipher: ctDES; Mode: cmOFB; KeyBits: 64; Key: RawByteString(#$01#$23#$45#$67#$89#$ab#$cd#$ef); InitVector: RawByteString(#$12#$34#$56#$78#$90#$ab#$cd#$ef); PlainText: RawByteString(#$4e#$6f#$77#$20#$69#$73#$20#$74#$68#$65#$20#$74#$69#$6d#$65#$20 + #$66#$6f#$72#$20#$61#$6c#$6c#$20); CipherText: RawByteString(#$f3#$4a#$28#$50#$c9#$c6#$49#$85#$d6#$84#$ad#$96#$d7#$72#$e2#$f2 + #$43#$ea#$49#$9a#$be#$e8#$ae#$95)), // Triple-DES test vectors generated from online DES calculator at http://www.riscure.com/tech-corner/online-crypto-tools/des.html (Cipher: ctTripleDESEDE; Mode: cmECB; KeyBits: 128; Key: '1234567890123456'; PlainText: '1234567890123456'; CipherText: RawByteString(#$BC#$57#$08#$BC#$02#$FE#$BF#$2F#$F6#$AD#$24#$D2#$1E#$FB#$70#$3A)), (Cipher: ctTripleDESEDE; Mode: cmECB; KeyBits: 128; Key: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00); PlainText: '1234567890123456'; CipherText: RawByteString(#$62#$DD#$8E#$4A#$61#$4E#$1A#$F9#$BE#$3D#$31#$47#$71#$1F#$A2#$77)), (Cipher: ctTripleDESEDE; Mode: cmCBC; KeyBits: 128; Key: RawByteString(#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00#$00); InitVector: '12345678'; PlainText: '1234567890123456'; CipherText: RawByteString(#$8C#$A6#$4D#$E9#$C1#$B1#$23#$A7#$97#$8D#$A5#$4E#$AE#$E5#$7B#$46)), // Triple-DES-3 from https://www.cosic.esat.kuleuven.be/nessie/testvectors/bc/des/Triple-Des-3-Key-192-64.unverified.test-vectors (Cipher: ctTripleDES3EDE; Mode: cmECB; KeyBits: 192; Key: RawByteString(#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1); InitVector: ''; PlainText: RawByteString(#$F1#$F1#$F1#$F1#$F1#$F1#$F1#$F1); CipherText: RawByteString(#$5D#$1B#$8F#$AF#$78#$39#$49#$4B)), (Cipher: ctTripleDES3EDE; Mode: cmECB; KeyBits: 192; Key: RawByteString(#$00#$01#$02#$03#$04#$05#$06#$07#$08#$09#$0A#$0B#$0C#$0D#$0E#$0F#$10#$11#$12#$13#$14#$15#$16#$17); InitVector: ''; PlainText: RawByteString(#$00#$11#$22#$33#$44#$55#$66#$77); CipherText: RawByteString(#$97#$A2#$5B#$A8#$2B#$56#$4F#$4C)), (Cipher: ctTripleDES3EDE; Mode: cmECB; KeyBits: 192; Key: RawByteString(#$2B#$D6#$45#$9F#$82#$C5#$B3#$00#$95#$2C#$49#$10#$48#$81#$FF#$48#$2B#$D6#$45#$9F#$82#$C5#$B3#$00); InitVector: ''; PlainText: RawByteString(#$EA#$02#$47#$14#$AD#$5C#$4D#$84); CipherText: RawByteString(#$C6#$16#$AC#$E8#$43#$95#$82#$47)) ); procedure Test_TestCases; var I : Integer; B : array[0..1023] of AnsiChar; L : Integer; C : RawByteString; M : RawByteString; X : Integer; begin for I := 0 to CipherTestCaseCount - 1 do with CipherTestCases[I] do try if Assigned(GetCipherInfo(Cipher)) then begin M := IntToStringB(I); L := Length(PlainText); Move(Pointer(PlainText)^, B[0], L); L := Encrypt(Cipher, Mode, cpNone, KeyBits, Pointer(Key), Length(Key), @B[0], L, @B[0], Sizeof(B), Pointer(InitVector), Length(InitVector)); C := ''; SetLength(C, L); Move(B[0], Pointer(C)^, L); if C <> CipherText then begin for X := 1 to L do if C[X] <> CipherText[X] then Writeln(X, '!', Ord(C[X]), '<>', Ord(CipherText[X]), ' L=', L); end; { Freepascal issue with RawByteString constant conversion } { if I = 13 then begin T := CipherText; for X := 1 to L do Write(IntToHex(Ord(T[X]), 2)); Writeln; end; } Assert(C = CipherText, M); L := Decrypt(Cipher, Mode, cpNone, KeyBits, Pointer(Key), Length(Key), @B[0], L, Pointer(InitVector), Length(InitVector)); Move(B[0], PByteChar(C)^, L); Assert(C = PlainText, M); Assert(Encrypt(Cipher, Mode, cpNone, KeyBits, Key, PlainText, InitVector) = CipherText, M); Assert(Decrypt(Cipher, Mode, cpNone, KeyBits, Key, CipherText, InitVector) = PlainText, M); end; except on E : Exception do raise Exception.Create('Test case ' + IntToStr(I) + ': ' + E.Message); end; end; procedure Test_CipherRandom; begin Assert(Length(SecureRandomHexStrB(0)) = 0); Assert(Length(SecureRandomHexStrB(1)) = 1); Assert(Length(SecureRandomHexStrB(511)) = 511); Assert(Length(SecureRandomHexStrB(512)) = 512); Assert(Length(SecureRandomHexStrB(513)) = 513); Assert(Length(SecureRandomHexStr(513)) = 513); Assert(Length(SecureRandomHexStrU(513)) = 513); Assert(Length(SecureRandomStrB(0)) = 0); Assert(Length(SecureRandomStrB(1)) = 1); Assert(Length(SecureRandomStrB(1023)) = 1023); Assert(Length(SecureRandomStrB(1024)) = 1024); Assert(Length(SecureRandomStrB(1025)) = 1025); end; procedure Test; begin Assert(RC2BlockSize = 8); Assert(RC2BlockSize = Sizeof(TRC2Block)); Assert(DESBlockSize = 8); Assert(DESBlockSize = Sizeof(TDESBlock)); flcCipherAES.Test; flcCipherDH.Test; flcCipherRSA.Test; {$IFDEF Cipher_SupportEC} flcCipherEllipticCurve.Test; {$ENDIF} flcCipher.Test; Test_CipherRandom; Test_TestCases; end; {$ENDIF} {$IFDEF CIPHER_PROFILE} procedure Profile; begin end; {$ENDIF} end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Acceso; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, IniFiles; type TfrmAcceso = class(TForm) grpAcceso: TGroupBox; Label1: TLabel; Label2: TLabel; txtUsuario: TEdit; txtContra: TEdit; btnAceptar: TBitBtn; btnCancelar: TBitBtn; chkRecordar: TCheckBox; procedure FormShow(Sender: TObject); procedure btnAceptarClick(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure txtUsuarioKeyPress(Sender: TObject; var Key: Char); private procedure RecuperaConfig; function VerificaDatos: Boolean; public bAcceso : boolean; sNombreUsuario, sUsuario : String; iUsuario : integer; end; var frmAcceso: TfrmAcceso; implementation uses dm, Permisos, Funciones; {$R *.xfm} procedure TfrmAcceso.FormShow(Sender: TObject); begin RecuperaConfig; bAcceso := false; txtContra.Clear; if(Length(txtUsuario.Text) > 0) then txtContra.SetFocus else txtUsuario.SetFocus; end; procedure TfrmAcceso.btnAceptarClick(Sender: TObject); var sContraDes : String; begin if(not VerificaDatos) then Exit; with dmDatos.qryConsulta do begin // Busca el usuario especificado Close; SQL.Clear; SQL.Add('SELECT * FROM usuarios WHERE login = ''' + txtUsuario.Text + ''''); Open; if (not Eof) then begin with TFrmPermisos.Create(Self) do try sContraDes := DesEncripta(Trim(FieldByName('contra').AsString)); finally free; end; // Compara la contraseña escrita con la registrada en la tabla de usuarios if(sContraDes = txtContra.Text) then begin sUsuario := txtUsuario.Text; iUsuario := FieldByName('clave').AsInteger; sNombreUsuario := FieldByName('nombre').AsString; bAcceso := true; Close; Self.Close; end else begin Application.MessageBox('Contraseña incorrecta','Error',[smbOK]); txtContra.SetFocus; txtContra.SelectAll; end; end else begin Application.MessageBox('Usuario no registrado','Error',[smbOK]); txtUsuario.SetFocus; txtUsuario.SelectAll; end; Close; end; end; function TfrmAcceso.VerificaDatos: Boolean; begin Result := True; if(Length(txtUsuario.Text) = 0) then begin Application.MessageBox('Introduzca el usuario', 'Error', [smbOK], smsWarning); txtUsuario.SetFocus; Result := False; end else if(Length(txtContra.Text) = 0) then begin Application.MessageBox('Introduzca su contraseña', 'Error', [smbOK], smsWarning); txtContra.SetFocus; Result := False; end else end; procedure TfrmAcceso.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmAcceso.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Acceso', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Acceso', 'Posx', IntToStr(Left)); if(chkRecordar.Checked) then begin WriteString('Acceso', 'Recordar', 'S'); WriteString('Acceso', 'Usuario', txtUsuario.Text); end else begin WriteString('Acceso', 'Recordar', 'N'); WriteString('Acceso', 'Usuario', ''); end; Free; end; end; procedure TfrmAcceso.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba, sValor : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Acceso', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Acceso', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; //Recupera el ultimo usuario que accedio sValor := ReadString('Acceso', 'Recordar', ''); if (sValor = 'S') then begin chkRecordar.Checked := true; txtUsuario.Text := RemoverCaracteresEsp(ReadString('Acceso', 'Usuario', '')); end else chkRecordar.Checked := false; Free; end; end; procedure TfrmAcceso.txtUsuarioKeyPress(Sender: TObject; var Key: Char); begin if (not (Key in ['A'..'Z', '0'..'9', #8, #9, #13])) then Key:= #0; end; end.
{ Subroutine SST_W_C_IMPLICIT_VAR (DTYPE,V) * * Create an implicit variable. DTYPE is the descriptor for the data type of * the new variable. V is filled in to be the descriptor for the new variable. * The variable will be declared, and installed in the symbol table. } module sst_w_c_IMPLICIT_VAR; define sst_w_c_implicit_var; %include 'sst_w_c.ins.pas'; procedure sst_w_c_implicit_var ( {create an implicit variable} in dtype: sst_dtype_t; {data type descriptor for new variable} out v: sst_var_t); {filled in "variable" desc for new variable} begin sst_sym_var_new_out ( {create var and install in symbol table} dtype, v.mod1.top_sym_p); sst_w_c_symbol (v.mod1.top_sym_p^); {declare the variable} v.dtype_p := addr(dtype); {fill in rest of var descriptor} v.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k]; v.vtype := sst_vtype_var_k; v.mod1.next_p := nil; v.mod1.modtyp := sst_var_modtyp_top_k; v.mod1.top_str_h.first_char.crange_p := nil; v.mod1.top_str_h.first_char.ofs := 0; v.mod1.top_str_h.last_char.crange_p := nil; v.mod1.top_str_h.last_char.ofs := 0; end;
object TClaveDlg: TTClaveDlg Left = 301 Top = 206 ActiveControl = Nombre BorderStyle = bsDialog Caption = 'Ingrese su Nombre y Clave' ClientHeight = 110 ClientWidth = 384 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Verdana' Font.Style = [] OldCreateOrder = True Position = poScreenCenter OnActivate = FormActivate PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = 8 Top = 8 Width = 281 Height = 97 Shape = bsFrame end object Label1: TLabel Left = 28 Top = 30 Width = 45 Height = 13 Caption = 'Nombre' end object Label2: TLabel Left = 28 Top = 66 Width = 33 Height = 13 Caption = 'Clave' end object OKBtn: TButton Left = 300 Top = 20 Width = 75 Height = 25 Caption = 'Acepta' Default = True ModalResult = 1 TabOrder = 0 end object CancelBtn: TButton Left = 300 Top = 58 Width = 75 Height = 25 Cancel = True Caption = 'Anula' ModalResult = 2 TabOrder = 1 end object Nombre: TEdit Left = 96 Top = 26 Width = 157 Height = 21 CharCase = ecUpperCase Color = 16765826 MaxLength = 10 TabOrder = 2 end object Clave: TEdit Left = 96 Top = 62 Width = 157 Height = 21 CharCase = ecUpperCase Color = 16765826 PasswordChar = '*' TabOrder = 3 end end
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit MyPanel; {$ifdef FPC} {$mode objfpc}{$H+} {$endif} interface uses Classes, SysUtils, Graphics, Controls, ExtCtrls, Types; procedure Register; type { TMyPanel } TMyPanel = class(TCustomControl) private FBorderWidth: integer; //new FBorderColor: TColor; public constructor Create(AOwner: TComponent); override; function CanFocus: boolean; override; protected procedure Paint; override; procedure Resize; override; published property Align; property Caption; property Color; property ParentColor; property Enabled; property Font; property Visible; property BorderColor: TColor read FBorderColor write FBorderColor default clBlack; property BorderWidth: integer read FBorderWidth write FBorderWidth default 0; property OnClick; property OnDblClick; property OnResize; end; implementation { TMyPanel } constructor TMyPanel.Create(AOwner: TComponent); begin inherited; Width:= 150; Height:= 100; Caption:= ''; Color:= clWhite; {$ifdef FPC} BorderStyle:= bsNone; {$endif} BorderWidth:= 0; BorderColor:= clBlack; end; function TMyPanel.CanFocus: boolean; begin Result:= false; end; procedure TMyPanel.Paint; var R: TRect; Pnt: TPoint; Size: TSize; i: integer; begin //inherited; R:= ClientRect; Canvas.Brush.Style:= bsSolid; Canvas.Brush.Color:= Color; Canvas.FillRect(R); Canvas.Pen.Color:= BorderColor; for i:= 1 to BorderWidth do begin Canvas.Rectangle(R); InflateRect(R, -1, -1); end; if Caption<>'' then begin Canvas.Font.Assign(Self.Font); Size:= Canvas.TextExtent(Caption); Pnt.X:= (R.Right-Size.cx) div 2; Pnt.Y:= (R.Bottom-Size.cy) div 2; Canvas.TextOut(Pnt.X, Pnt.Y, Caption); end; end; procedure TMyPanel.Resize; begin inherited Resize; Invalidate; end; procedure Register; begin RegisterComponents('Misc', [ TMyPanel ]); end; end.
unit unitAction; interface uses classes; type TAction = class(TObject) private { Private declarations } public { Public declarations } frames: TList; caption: String; nextAction: String; soundfile: String; trigger: String; constructor Create(ncaption: string); end; implementation constructor TAction.Create(ncaption: string); begin inherited Create; caption := ncaption; frames := TList.Create; soundfile := ''; nextAction := ''; end; end.
unit uExportarTipos; interface uses System.SysUtils, System.Classes, uArquivoTexto, uDM, uFireDAC, uTipoVO, System.Generics.Collections, uGenericDAO; type TExportarTipo = class private FArquivo: string; public procedure Exportar(); function Importar(): TObjectList<TTipoVO>; constructor Create(); overload; end; implementation { TExportarTipo } constructor TExportarTipo.Create; begin inherited Create; FArquivo := 'D:\DOMPER\SIDomper\Banco\Tipos.txt'; end; procedure TExportarTipo.Exportar; var obj: TFireDAC; Arq: TArquivoTexto; begin obj := TFireDAC.create; Arq := TArquivoTexto.Create(FArquivo, tpExportar); try obj.OpenSQL('SELECT * FROM Tipo'); while not obj.Model.Eof do begin Arq.ExportarInt(obj.Model.FieldByName('Tip_Codigo').AsInteger, 001, 005); Arq.ExportarString(obj.Model.FieldByName('Tip_Nome').AsString, 006, 050); Arq.ExportarBool(obj.Model.FieldByName('Tip_Ativo').AsBoolean); Arq.ExportarInt(obj.Model.FieldByName('Tip_Programa').AsInteger, 057, 005); Arq.ExportarString(obj.Model.FieldByName('Tip_Conceito').AsString, 062, 500); Arq.NovaLinha(); obj.Model.Next; end; finally FreeAndNil(obj); FreeAndNil(Arq); end; end; function TExportarTipo.Importar: TObjectList<TTipoVO>; var model: TTipoVO; lista: TObjectList<TTipoVO>; Arq: TArquivoTexto; begin lista := TObjectList<TTipoVO>.Create(); Arq := TArquivoTexto.Create(FArquivo, tpImportar); try while not (Arq.FimArquivo()) do begin Arq.ProximoRegistro(); model := TTipoVO.Create; model.Id := 0; model.Codigo := Arq.ImportarInt(001, 005); model.Nome := Arq.ImportarString(006, 050); model.Ativo := Arq.ImportarBool(056, 001); model.Programa := Arq.ImportarInt(057, 005); model.Conceito := Arq.ImportarString(062, 500); lista.Add(model); end; finally FreeAndNil(Arq); end; Result := lista; end; end.
unit MarkAddressAsVisitedUnit; interface uses SysUtils, BaseExampleUnit; type TMarkAddressAsVisited = class(TBaseExample) public procedure Execute(RouteId: String; AddressId, MemberId: integer; IsVisited: boolean); end; implementation procedure TMarkAddressAsVisited.Execute(RouteId: String; AddressId, MemberId: integer; IsVisited: boolean); var ErrorString: String; begin Route4MeManager.Address.MarkAsVisited( RouteId, AddressId, MemberId, IsVisited, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then WriteLn('MarkAddressAsVisited executed successfully') else WriteLn(Format('MarkAddressAsVisited error: "%s"', [ErrorString])); end; end.
unit ExtAINetClient; interface uses Classes, SysUtils, Math, ExtAICommonClasses, ExtAISharedNetworkTypes, ExtAINetClientOverbyte; type TNewDataEvent = procedure (aData: Pointer; aDataType, aLength: Cardinal) of object; TExtAINetClientImplementation = TNetClientOverbyte; TExtAINetClient = class private // Client fClient: TExtAINetClientImplementation; fClientID: TExtAINetHandleIndex; fConnected: Boolean; // Buffers fpStartData: pExtAINewData; fpEndData: pExtAINewData; fBuff: TKExtAIMsgStream; // ExtAI properties fID: Word; fAuthor: UnicodeString; fName: UnicodeString; fDescription: UnicodeString; fAIVersion: Cardinal; // Server properties fServerName: UnicodeString; fServerVersion: Cardinal; // Events fOnConnectSucceed: TNotifyEvent; fOnConnectFailed: TGetStrProc; fOnForcedDisconnect: TNotifyEvent; fOnStatusMessage: TGetStrProc; fOnNewEvent: TNewDataEvent; fOnNewState: TNewDataEvent; procedure NillEvents(); procedure Error(const S: String); procedure ConnectSucceed(Sender: TObject); procedure ConnectFailed(const S: String); procedure ForcedDisconnect(Sender: TObject); procedure RecieveData(aData: Pointer; aLength: Cardinal); procedure GameCfg(aData: Pointer; aTypeCfg, aLength: Cardinal); procedure Performance(aData: Pointer); procedure Event(aData: Pointer; aTypeEvent, aLength: Cardinal); procedure State(aData: Pointer; aTypeState, aLength: Cardinal); procedure Status(const S: String); procedure ServerCfg(DataType: Cardinal); procedure SendExtAICfg(); public constructor Create(const aID: Word; const aAuthor, aName, aDescription: UnicodeString; const aVersion: Cardinal); destructor Destroy; override; property Client: TExtAINetClientImplementation read fClient; property ClientHandle: TExtAINetHandleIndex read fClientID; property Connected: Boolean read fConnected; property OnConnectSucceed: TNotifyEvent write fOnConnectSucceed; property OnConnectFailed: TGetStrProc write fOnConnectFailed; property OnForcedDisconnect: TNotifyEvent write fOnForcedDisconnect; property OnStatusMessage: TGetStrProc write fOnStatusMessage; property OnNewEvent: TNewDataEvent write fOnNewEvent; property OnNewState: TNewDataEvent write fOnNewState; property ID: Word read fID; property Author: UnicodeString read fAuthor; property ClientName: UnicodeString read fName; property Description: UnicodeString read fDescription; property AIVersion: Cardinal read fAIVersion; procedure ConnectTo(const aAddress: String; const aPort: Word); // Try to connect to server procedure Disconnect(); //Disconnect from server procedure SendMessage(aMsg: Pointer; aLengthMsg: TExtAIMsgLengthMsg); procedure ProcessReceivedMessages(); end; implementation const CLIENT_VERSION: Cardinal = 20191026; { TExtAINetClient } constructor TExtAINetClient.Create(const aID: Word; const aAuthor, aName, aDescription: UnicodeString; const aVersion: Cardinal); begin Inherited Create; fID := aID; fAuthor := aAuthor; fName := aName; fDescription := aDescription; fAIVersion := aVersion; NillEvents(); fpStartData := new(pExtAINewData); fpStartData^.Ptr := nil; fpStartData^.Next := nil; fpEndData := fpStartData; fConnected := False; fClient := TExtAINetClientImplementation.Create(); fBuff := TKExtAIMsgStream.Create(); end; destructor TExtAINetClient.Destroy(); begin NillEvents(); if Connected then Disconnect(); fClient.Free; fBuff.Free; repeat fpEndData := fpStartData; fpStartData := fpStartData.Next; if (fpEndData^.Ptr <> nil) then FreeMem(fpEndData^.Ptr, fpEndData^.Length); Dispose(fpEndData); until (fpStartData = nil); Inherited; end; procedure TExtAINetClient.NillEvents(); begin fOnConnectSucceed := nil; fOnConnectFailed := nil; fOnForcedDisconnect := nil; fOnStatusMessage := nil; fOnNewEvent := nil; fOnNewState := nil; end; procedure TExtAINetClient.Error(const S: String); begin Status(Format('NetClient Error: %s',[S])); end; procedure TExtAINetClient.Status(const S: String); begin if Assigned(fOnStatusMessage) then fOnStatusMessage(Format('NetClient: %s',[S])); end; procedure TExtAINetClient.ConnectTo(const aAddress: String; const aPort: Word); begin fBuff.Clear; fClient.OnError := Error; fClient.OnConnectSucceed := ConnectSucceed; fClient.OnConnectFailed := ConnectFailed; fClient.OnSessionDisconnected := ForcedDisconnect; fClient.OnRecieveData := RecieveData; fClient.ConnectTo(aAddress, aPort); Status(Format('Connecting to: %s; Port: %d', [aAddress,aPort])); end; procedure TExtAINetClient.ConnectSucceed(Sender: TObject); begin fConnected := True; if Assigned(fOnConnectSucceed) then fOnConnectSucceed(Self); Status(Format('Connect succeed - IP: %s', [Client.MyIPString()])); end; procedure TExtAINetClient.ConnectFailed(const S: String); begin fConnected := False; if Assigned(fOnConnectFailed) then fOnConnectFailed(S); Status(Format('Connection failed: %s', [S])); end; procedure TExtAINetClient.Disconnect(); begin fConnected := False; fClient.Disconnect; Status('Disconnected'); end; // Connection failed / deliberately disconnection / server disconnect procedure TExtAINetClient.ForcedDisconnect(Sender: TObject); begin if fConnected then begin fConnected := false; // Make sure that we are disconnect before we call the callback Status('Forced disconnect'); if Assigned(fOnForcedDisconnect) then fOnForcedDisconnect(Self); end; fConnected := false; end; // Create message and send it immediately via protocol procedure TExtAINetClient.SendMessage(aMsg: Pointer; aLengthMsg: TExtAIMsgLengthMsg); var Msg: TKExtAIMsgStream; begin Assert(aLengthMsg <= ExtAI_MSG_MAX_SIZE, 'Message over size limit'); if not fConnected then begin Error('The client is not connected to the server'); Exit; end; // Allocate memory Msg := TKExtAIMsgStream.Create(); try // Create head Msg.WriteHead(ExtAI_MSG_ADDRESS_SERVER, fClientID, aLengthMsg); // Copy data field Msg.Write(aMsg^, aLengthMsg); // Send data Msg.Position := 0; fClient.SendData(Msg.Memory, Msg.Size); finally Msg.Free; end; end; procedure TExtAINetClient.ServerCfg(DataType: Cardinal); var pomID: Word; BackupPosition: Cardinal; begin BackupPosition := fBuff.Position; case TExtAIMsgTypeCfgServer(DataType) of csName: begin fBuff.ReadW(fServerName); Status(Format('Server name: %s', [fServerName])); end; csVersion: begin fBuff.Read(fServerVersion); Status(Format('Versions: server = %d, client = %d', [fServerVersion, CLIENT_VERSION])); if (fServerVersion = CLIENT_VERSION) then SendExtAICfg(); end; csClientHandle: begin fBuff.Read(fClientID, SizeOf(fClientID)); Status(Format('Client handle: %d', [fClientID])); end; csExtAIID: begin fBuff.Read(pomID, SizeOf(pomID)); if (fID = 0) then fID := pomID; Status(Format('Client ID: %d', [fID])); end; else Status('Unknown server cfg message'); end; fBuff.Position := BackupPosition; end; procedure TExtAINetClient.GameCfg(aData: Pointer; aTypeCfg, aLength: Cardinal); begin //SendMessage(aData, aLength); end; procedure TExtAINetClient.Performance(aData: Pointer); var ID: Word; //length: Cardinal; pData: Pointer; Msg: TKExtAIMsgStream; typePerf: TExtAIMsgTypePerformance; begin // Check the type of message if (mkPerformance <> TExtAIMsgKind(aData^)) then Exit; // Get type of message pData := Pointer( NativeUInt(aData) + SizeOf(TExtAIMsgKind) ); typePerf := TExtAIMsgTypePerformance(pData^); // Get length pData := Pointer( NativeUInt(pData) + SizeOf(TExtAIMsgTypePerformance) ); //length := Cardinal( TExtAIMsgLengthData(pData^) ); // Get pointer to data pData := Pointer( NativeUInt(pData) + SizeOf(TExtAIMsgLengthData) ); // Process message Msg := TKExtAIMsgStream.Create(); try case typePerf of // Read ping ID and create response prPing: begin ID := Word( pData^ ); Msg.WriteMsgType(mkPerformance, Cardinal(prPong), SizeOf(ID)); Msg.Write(ID, SizeOf(ID)); SendMessage(Msg.Memory, Msg.Size); end; prPong: begin end; prTick: begin end; end; finally Msg.Free; end; end; // Send ExtAI configuration procedure TExtAINetClient.SendExtAICfg(); var M: TKExtAIMsgStream; begin M := TKExtAIMsgStream.Create; try // Add ID (ID is decided by game or DLL, it is equal to zero if it is unknown) M.WriteMsgType(mkExtAICfg, Cardinal(caID), SizeOf(fID)); M.Write(fID); // Add author M.WriteMsgType(mkExtAICfg, Cardinal(caAuthor), SizeOf(Word) + SizeOf(WideChar) * Length(fAuthor)); M.WriteW(fAuthor); // Add name M.WriteMsgType(mkExtAICfg, Cardinal(caName), SizeOf(Word) + SizeOf(WideChar) * Length(fName)); M.WriteW(fName); // Add description M.WriteMsgType(mkExtAICfg, Cardinal(caDescription), SizeOf(Word) + SizeOf(WideChar) * Length(fDescription)); M.WriteW(fDescription); // Add ExtAI version M.WriteMsgType(mkExtAICfg, Cardinal(caVersion), SizeOf(fAIVersion)); M.Write(fAIVersion); //M.Position := 0; SendMessage(M.Memory, M.Size); finally M.Free; end; end; // Receive Event procedure TExtAINetClient.Event(aData: Pointer; aTypeEvent, aLength: Cardinal); begin if Assigned(fOnNewEvent) then fOnNewEvent(aData, aTypeEvent, aLength); end; // Requested State procedure TExtAINetClient.State(aData: Pointer; aTypeState, aLength: Cardinal); begin if Assigned(fOnNewState) then fOnNewState(aData, aTypeState, aLength); end; // Merge recieved data into stream procedure TExtAINetClient.RecieveData(aData: Pointer; aLength: Cardinal); var pNewData: pExtAINewData; begin //Status('New message'); // Mark pointer to data in new record (Thread safe) New(pNewData); pNewData^.Ptr := nil; pNewData^.Next := nil; fpEndData^.Ptr := aData; fpEndData^.Length := aLength; AtomicExchange(fpEndData^.Next, pNewData); fpEndData := pNewData; // Check if new data are top prio (top prio data have its own message and are processed by NET thread) Performance( Pointer( NativeUInt(aData) + ExtAI_MSG_HEAD_SIZE ) ); end; // Process received messages in 2 priorities: // The first prio is for direct communication of client and server // The second prio is for everything else (game state must remain constant for actual loop of the ExtAI, it is updated later before next loop) procedure TExtAINetClient.ProcessReceivedMessages(); var MaxPos, DataType, DataLenIdx: Cardinal; pData: Pointer; pOldData: pExtAINewData; pCopyFrom, pCopyTo: PChar; Recipient: TExtAIMsgRecipient; Sender: TExtAIMsgSender; Kind: TExtAIMsgKind; LengthMsg: TExtAIMsgLengthMsg; LengthData: TExtAIMsgLengthData; begin // Merge incoming data into memory stream (Thread safe) while (fpStartData^.Next <> nil) do begin pOldData := fpStartData; AtomicExchange(fpStartData, fpStartData^.Next); fBuff.Write(pOldData^.Ptr^, pOldData^.Length); FreeMem(pOldData^.Ptr, pOldData^.Length); Dispose(pOldData); end; // Save size of the buffer MaxPos := fBuff.Position; // Set actual index fBuff.Position := 0; // Try to read new messages while (MaxPos - fBuff.Position >= ExtAI_MSG_HEAD_SIZE) do begin // Read head (move fBuff.Position from first byte of head to first byte of data) fBuff.ReadHead(Recipient, Sender, LengthMsg); DataLenIdx := fBuff.Position + LengthMsg; // Check if the message is complete if (fBuff.Position + LengthMsg <= MaxPos) then begin // Get data from the message while (fBuff.Position < DataLenIdx) do begin // Read type of the data - type is Cardinal so it can change its size in dependence on the Kind in the message fBuff.ReadMsgType(Kind, DataType, LengthData); if (fBuff.Position + LengthData <= MaxPos) then begin // Get pointer to data (pointer to memory of stream + idx to actual position) pData := Pointer(NativeUInt(fBuff.Memory) + fBuff.Position); // Process message case Kind of mkServerCfg: ServerCfg(DataType); mkGameCfg: GameCfg(pData, DataType, LengthData); mkExtAICfg: begin end; mkPerformance: begin end; mkAction: begin end; mkEvent: Event(pData, DataType, LengthData); mkState: State(pData, DataType, LengthData); else begin end; end; // Move position to next Head or Data fBuff.Position := fBuff.Position + LengthData; end else Error('Length of the data does not match the length of the message'); end; end else break; end; // Copy the rest at the start of the buffer MaxPos := MaxPos - fBuff.Position; if (fBuff.Position > 0) AND (MaxPos > 0) then begin // Copy the rest of the stream at the start pCopyFrom := Pointer(NativeUInt(fBuff.Memory) + fBuff.Position); pCopyTo := fBuff.Memory; Move(pCopyFrom^, pCopyTo^, MaxPos); end; // Move position at the end fBuff.Position := MaxPos; end; end.
unit k2FileGenerator; {* Базовый писатель тегов в файл. } { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2FileGenerator - } { Начат: 21.02.2005 18:55 } { $Id: k2FileGenerator.pas,v 1.8 2013/04/05 16:44:40 lulin Exp $ } // $Log: k2FileGenerator.pas,v $ // Revision 1.8 2013/04/05 16:44:40 lulin // - портируем. // // Revision 1.7 2013/04/04 11:21:38 lulin // - портируем. // // Revision 1.6 2011/09/19 10:12:45 lulin // - делаем Filer'ам возможность быть не компонентами и кешируемыми. // // Revision 1.5 2011/09/15 12:48:20 voba // - k : 281525254 // // Revision 1.4 2009/03/18 14:59:54 lulin // - делаем возможность отката, если во время записи произошло исключение. // // Revision 1.3 2008/02/05 12:49:23 lulin // - упрощаем базовые объекты. // // Revision 1.2 2005/07/21 10:20:08 lulin // - теперь TextSource не знает как создавать Reader'ы, а про это знает контейнер документа. // // Revision 1.1 2005/02/21 16:04:14 lulin // - new unit: k2FileGenerator. // {$Include k2Define.inc } interface uses l3Types, l3Base, l3Filer, l3KeyWrd, k2InternalInterfaces, k2TagGen, k2StackGenerator ; type Tk2CustomFileGenerator = class(Tk2CustomStackGeneratorEx, Ik2FilerSource) {* Базовый писатель тегов в файл. } protected // property fields f_Filer : Tl3CustomFiler; private // property fields f_KeyWords : Tl3KeyWords; protected {property methods} function pm_GetFiler: Tl3CustomFiler; procedure pm_SetFiler(Value: Tl3CustomFiler); virtual; {-} procedure pm_SetKeyWords(Value: Tl3KeyWords); {-} private {stored specifiers} function FilerStored: Bool; {-} protected {internal methods} procedure FilerChanged(aFiler: Tl3CustomFiler); virtual; {-} procedure OutShortString(const S: ShortString); {-} procedure OutString(S: Tl3PrimString); overload; {-} procedure OutString(const S: AnsiString); overload; {-} procedure OutStringLn(S: Tl3CustomString); overload; {-} procedure OutStringLn(const S: AnsiString); overload; {-} function WriteBuf(B: PAnsiChar; Len: Long): Long; virtual; {-} function WriteLong(L: Long): Long; {-} function WriteWord(W: Word): Long; {-} function WriteByte(B: Byte): Long; {-} procedure Cleanup; override; {-} procedure OpenStream; override; {-} procedure CloseStream(NeedUndo: Bool); override; {-вызывается один раз в конце генерации} public {public methods} class function SetTo(var theGenerator : Tk2TagGenerator; const aFileName : AnsiString): Pointer; overload; {* - создает экземпляр класа и цепляет его к генератору. } class function SetTo(var theGenerator : Tk2TagGenerator; const aStream : IStream): Pointer; overload; {* - создает экземпляр класа и цепляет его к генератору. } procedure OutEOL; virtual; {-} public {public properties} property Filer: Tl3CustomFiler read pm_GetFiler write pm_SetFiler stored FilerStored; {* - файл куда пишутся теги. } property KeyWords: Tl3KeyWords read f_KeyWords write pm_SetKeyWords; {* - таблица ключевых слов. } end;//Tk2CustomFileGenerator {* Предназначен для записи тегов в файл. Для использования как предка для писателей в различные форматы. } implementation uses l3Interfaces, l3String ; // start class Tk2CustomFileGenerator procedure Tk2CustomFileGenerator.OpenStream; {override;} {-} begin inherited; Filer.Mode := l3_fmWrite; Filer.Open; end; procedure Tk2CustomFileGenerator.CloseStream(NeedUndo: Bool); {override;} {-вызывается один раз в конце генерации} begin //Filer.Flush; if NeedUndo then if (f_Filer <> nil) then f_Filer.Rollback; Filer.Close; inherited; end; function Tk2CustomFileGenerator.pm_GetFiler: Tl3CustomFiler; {-} begin if (f_Filer = nil) then f_Filer := Tl3CustomFiler.Create; Result := f_Filer; end; procedure Tk2CustomFileGenerator.pm_SetFiler(Value: Tl3CustomFiler); {-} begin if l3Set(f_Filer, Value) then FilerChanged(f_Filer); end; procedure Tk2CustomFileGenerator.FilerChanged(aFiler: Tl3CustomFiler); //virtual; {-} begin end; procedure Tk2CustomFileGenerator.pm_SetKeyWords(Value: Tl3KeyWords); {-} begin l3Set(f_KeyWords, Value); end; function Tk2CustomFileGenerator.FilerStored: Bool; {-} begin {$IfDef l3FilerIsComponent} Result := (f_Filer <> nil) AND (f_Filer.Owner <> nil); {$Else l3FilerIsComponent} Result := false; {$EndIf l3FilerIsComponent} end; procedure Tk2CustomFileGenerator.OutString(S: Tl3PrimString); {overload;} {-} var l_S : Tl3WString; l_CharSize : Integer; begin l_S := S.AsWStr; if not l3IsNil(l_S) then begin if (l_S.SCodePage = CP_Unicode) then l_CharSize := SizeOf(WideChar) else l_CharSize := SizeOf(ANSIChar); WriteBuf(l_S.S, l_S.SLen * l_CharSize); end;//not S.Empty end; procedure Tk2CustomFileGenerator.OutString(const S: AnsiString); {overload;} {-} begin if (S <> '') then WriteBuf(PAnsiChar(S), Length(S)); end; procedure Tk2CustomFileGenerator.OutShortString(const S: ShortString); {overload;} {-} begin if (Byte(S[0]) > 0) then WriteBuf(PAnsiChar(@S[1]), Byte(S[0])); end; procedure Tk2CustomFileGenerator.OutStringLn(S: Tl3CustomString); //overload; {-} begin OutString(S); OutEOL; end; procedure Tk2CustomFileGenerator.OutStringLn(const S: AnsiString); //overload; {-} begin OutString(S); OutEOL; end; procedure Tk2CustomFileGenerator.Cleanup; {override;} {-} begin KeyWords := nil; Filer := nil; inherited; end; class function Tk2CustomFileGenerator.SetTo(var theGenerator : Tk2TagGenerator; const aFileName : AnsiString): Pointer; //overload; {* - создает экземпляр класа и цепляет его к генератору. } var l_Filer : Tl3CustomFiler; begin Result := SetTo(theGenerator); l_Filer := Tl3CustomDOSFiler.Make(aFileName, l3_fmWrite, false); try (theGenerator As Tk2CustomFileGenerator).Filer := l_Filer; finally l3Free(l_Filer); end;//try..finally end; class function Tk2CustomFileGenerator.SetTo(var theGenerator : Tk2TagGenerator; const aStream : IStream): Pointer; //overload; {* - создает экземпляр класа и цепляет его к генератору. } begin Result := SetTo(theGenerator); (theGenerator As Tk2CustomFileGenerator).Filer.COMStream := aStream; end; procedure Tk2CustomFileGenerator.OutEOL; {-} begin f_Filer.OutEOL; end; function Tk2CustomFileGenerator.WriteBuf(B: PAnsiChar; Len: Long): Long; {-} begin Result := f_Filer.Write(B, Len); end; function Tk2CustomFileGenerator.WriteLong(L: Long): Long; {-} begin Result := WriteBuf(@L, SizeOf(L)); end; function Tk2CustomFileGenerator.WriteWord(W: Word): Long; {-} begin Result := WriteBuf(@W, SizeOf(W)); end; function Tk2CustomFileGenerator.WriteByte(B: Byte): Long; {-} begin Result := WriteBuf(@B, SizeOf(B)); end; end.
program SmartPtr01; {$MODE DELPHI} {$APPTYPE CONSOLE} uses heaptrc, SysUtils, Nullable in '..\sources\Nullable.pas' ; var a: TNullable<string>; b: TNullable<Integer>; nns: TNullable<TNullable<string>>; begin if nns = nil then WriteLn('nullable for nullable string works :)'); try WriteLn(b.Value); except on E: EAccessViolation do WriteLn(b.HasValue); // print false end; b := 0; WriteLn(b.HasValue); // print true if b.HasValue then begin WriteLn(b.Value); // print 0 WriteLn(b^); // print 0 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 ClpOSRandom; {$I ..\..\Include\CryptoLib.inc} interface uses {$IF DEFINED(MSWINDOWS)} Windows, {$ELSEIF DEFINED(IOSDELPHI)} // iOS stuffs for Delphi Macapi.Dispatch, iOSapi.Foundation, {$ELSEIF DEFINED(IOSFPC)} // iOS stuffs for FreePascal {$LINKFRAMEWORK Security} {$ELSE} Classes, SysUtils, {$IFEND MSWINDOWS} ClpCryptoLibTypes; resourcestring {$IF DEFINED(MSWINDOWS)} SMSWIndowsCryptoAPIGenerationError = 'An Error Occured while generating random data using MS WIndows Crypto API.'; {$ELSEIF (DEFINED(IOSDELPHI) OR DEFINED(IOSFPC))} SIOSSecRandomCopyBytesGenerationError = 'An Error Occured while generating random data using SecRandomCopyBytes API.'; {$ELSE} SUnixRandomReadError = 'An Error Occured while reading random data from /dev/urandom or /dev/random.'; {$IFEND MSWINDOWS} type /// <summary> /// <para> /// TOSRandom Number Class. /// </para> /// <para> /// This class returns random bytes from an OS-specific randomness /// source. The returned data should be unpredictable enough for /// cryptographic applications, though its exact quality depends on the /// OS implementation. /// On a UNIX-like system this will read directly from /dev/urandom or /dev/random /// (if the former is not available), /// on iOS, calls SecRandomCopyBytes as /dev/(u)random is sandboxed, /// on MSWINDOWS it will call CryptGenRandom(). /// </para> /// </summary> TOSRandom = class sealed(TObject) strict private class function NoZeroes(const data: TCryptoLibByteArray): Boolean; static; inline; {$IF DEFINED(MSWINDOWS)} class function GenRandomBytesWindows(len: Int32; const data: PByte): Int32; {$ELSEIF DEFINED(IOSDELPHI)} class function GenRandomBytesIOSDelphi(len: Int32; const data: PByte): Int32; {$ELSEIF DEFINED(IOSFPC)} class function GenRandomBytesIOSFPC(len: Int32; const data: PByte): Int32; {$ELSE} class function GenRandomBytesUnix(len: Int32; const data: PByte): Int32; {$IFEND $MSWINDOWS} public class procedure GetBytes(const data: TCryptoLibByteArray); static; class procedure GetNonZeroBytes(const data: TCryptoLibByteArray); static; end; {$IFDEF MSWINDOWS} const ADVAPI32 = 'advapi32.dll'; function CryptAcquireContextW(phProv: Pointer; pszContainer: LPCWSTR; pszProvider: LPCWSTR; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall; external ADVAPI32 Name 'CryptAcquireContextW'; function CryptGenRandom(hProv: THandle; dwLen: DWORD; pbBuffer: PByte): BOOL; stdcall; external ADVAPI32 Name 'CryptGenRandom'; function CryptReleaseContext(hProv: THandle; dwFlags: DWORD): BOOL; stdcall; external ADVAPI32 Name 'CryptReleaseContext'; {$ENDIF MSWINDOWS} {$IFDEF IOSDELPHI} type SecRandomRef = Pointer; const libSecurity = '/System/Library/Frameworks/Security.framework/Security'; function kSecRandomDefault: Pointer; function SecRandomCopyBytes(rnd: SecRandomRef; count: LongWord; bytes: PByte) : Integer; cdecl; external libSecurity Name _PU + 'SecRandomCopyBytes'; {$ENDIF IOSDELPHI} {$IFDEF IOSFPC} type // similar to a TOpaqueData already defined in newer FPC but not available in 3.0.4 __SecRandom = record end; // similar to an OpaquePointer already defined in newer FPC but not available in 3.0.4 SecRandomRef = ^__SecRandom; const { * This is a synonym for NULL, if you'd rather use a named constant. This refers to a cryptographically secure random number generator. * } kSecRandomDefault: SecRandomRef = Nil; function SecRandomCopyBytes(rnd: SecRandomRef; count: LongWord; bytes: PByte) : Integer; cdecl; external; {$ENDIF IOSFPC} implementation {$IFDEF IOSDELPHI} function kSecRandomDefault: Pointer; begin result := CocoaPointerConst(libSecurity, 'kSecRandomDefault'); end; {$ENDIF IOSDELPHI} class function TOSRandom.NoZeroes(const data: TCryptoLibByteArray): Boolean; var i: Int32; begin result := True; for i := System.Low(data) to System.High(data) do begin if data[i] = 0 then begin result := False; Exit; end; end; end; {$IF DEFINED(MSWINDOWS)} class function TOSRandom.GenRandomBytesWindows(len: Int32; const data: PByte): Int32; var hProv: THandle; const PROV_RSA_FULL = 1; CRYPT_VERIFYCONTEXT = DWORD($F0000000); CRYPT_SILENT = $00000040; begin if not CryptAcquireContextW(@hProv, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT or CRYPT_SILENT) then begin result := HResultFromWin32(GetLastError); Exit; end; try if not CryptGenRandom(hProv, len, data) then begin result := HResultFromWin32(GetLastError); Exit; end; finally CryptReleaseContext(hProv, 0); end; result := S_OK; end; {$ELSEIF DEFINED(IOSDELPHI)} class function TOSRandom.GenRandomBytesIOSDelphi(len: Int32; const data: PByte): Int32; begin // UNTESTED !!!, Please Take Note. result := SecRandomCopyBytes(kSecRandomDefault, LongWord(len), data); end; {$ELSEIF DEFINED(IOSFPC)} class function TOSRandom.GenRandomBytesIOSFPC(len: Int32; const data: PByte): Int32; begin // UNTESTED !!!, Please Take Note. result := SecRandomCopyBytes(kSecRandomDefault, LongWord(len), data); end; {$ELSE} class function TOSRandom.GenRandomBytesUnix(len: Int32; const data: PByte): Int32; var LStream: TFileStream; RandGen: String; begin RandGen := '/dev/urandom'; if not FileExists(RandGen) then begin RandGen := '/dev/random'; if not FileExists(RandGen) then begin result := -1; Exit; end; end; LStream := TFileStream.Create(RandGen, fmOpenRead); try try LStream.ReadBuffer(data[0], len); result := 0; except result := -1; end; finally LStream.Free; end; end; {$IFEND MSWINDOWS} class procedure TOSRandom.GetBytes(const data: TCryptoLibByteArray); var count: Int32; begin count := System.Length(data); {$IF DEFINED(MSWINDOWS)} if GenRandomBytesWindows(count, PByte(data)) <> 0 then begin raise EAccessCryptoLibException.CreateRes (@SMSWIndowsCryptoAPIGenerationError); end; {$ELSEIF DEFINED(IOSDELPHI)} if GenRandomBytesIOSDelphi(count, PByte(data)) <> 0 then begin raise EAccessCryptoLibException.CreateRes (@SIOSSecRandomCopyBytesGenerationError); end; {$ELSEIF DEFINED(IOSFPC)} if GenRandomBytesIOSFPC(count, PByte(data)) <> 0 then begin raise EAccessCryptoLibException.CreateRes (@SIOSSecRandomCopyBytesGenerationError); end; {$ELSE} if GenRandomBytesUnix(count, PByte(data)) <> 0 then begin raise EAccessCryptoLibException.CreateRes(@SUnixRandomReadError); end; {$IFEND MSWINDOWS} end; class procedure TOSRandom.GetNonZeroBytes(const data: TCryptoLibByteArray); begin repeat TOSRandom.GetBytes(data); until (NoZeroes(data)); end; end.
unit ChannelEditForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, StdCtrls, DBCtrls, Mask, DBCtrlsEh, ExtDlgs, uDBImages, Vcl.Imaging.Jpeg, Vcl.Imaging.pngimage, EhLibVCL, Vcl.Buttons, DBGridEh, Vcl.Menus, CnErrorProvider, PrjConst, DBLookupEh; type TDBImage = class(TpDBImage); TChannelEditForm = class(TForm) dsChannel: TpFIBDataSet; trSRead: TpFIBTransaction; trSWrite: TpFIBTransaction; Label1: TLabel; srcChannel: TDataSource; Label2: TLabel; Label3: TLabel; Label4: TLabel; DBCheckBox1: TDBCheckBox; Label5: TLabel; Label8: TLabel; Label9: TLabel; DBDateTimeEditEh1: TDBDateTimeEditEh; DBNumberEditEh1: TDBNumberEditEh; DBMemo2: TDBMemoEh; DBNumberEditEh2: TDBNumberEditEh; DBNumberEditEh3: TDBNumberEditEh; edtCH_NAME: TDBEditEh; DBEditEh2: TDBEditEh; DBComboBoxEh1: TDBComboBoxEh; Label6: TLabel; OpenDialog1: TOpenDialog; lbl1: TLabel; cbLANG: TDBComboBoxEh; edtDVBGENRES: TDBEditEh; Label10: TLabel; lbl2: TLabel; edt1: TDBNumberEditEh; imgGraphic: TDBImageEh; lbl3: TLabel; edtACCESS_ID: TDBNumberEditEh; btnCancel: TBitBtn; btnOk: TBitBtn; pmLogo: TPopupMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; SaveDialog: TSavePictureDialog; lbl4: TLabel; edtCH_LIC: TDBEditEh; lbl5: TLabel; edtCH_CERT: TDBEditEh; lbl6: TLabel; CnErrors: TCnErrorProvider; lcbCH_THEME: TDBLookupComboboxEh; trReadQ: TpFIBTransaction; dsTheme: TpFIBDataSet; srcTheme: TDataSource; procedure OkCancelFrame1bbOkClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure logoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtDVBGENRESEditButtons0Click(Sender: TObject; var Handled: Boolean); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure imgGraphicButtonClick(Sender: TObject; var Handled: Boolean); procedure imgGraphicDblClick(Sender: TObject); procedure N1Click(Sender: TObject); procedure N2Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure logoLoad; procedure logoSave; public { Public declarations } end; function EditChannel(const aChannel_ID: Int64; const Mode: integer): Int64; implementation uses DM, DVBGanresForma; {$R *.dfm} function EditChannel(const aChannel_ID: Int64; const Mode: integer): Int64; var ChannelEditForm: TChannelEditForm; vChannel: Int64; begin result := -1; ChannelEditForm := TChannelEditForm.Create(Application); with ChannelEditForm do try trSWrite.Active := true; trSRead.Active := true; dsChannel.ParamByName('Ch_ID').AsInteger := aChannel_ID; dsChannel.Open; if aChannel_ID = -1 then dsChannel.Insert else dsChannel.Edit; if ShowModal = mrOk then begin try if aChannel_ID = -1 then begin vChannel := dmMain.dbTV.Gen_Id('GEN_OPERATIONS_UID', 1, dmMain.trWriteQ); dsChannel['Ch_ID'] := vChannel; end else vChannel := aChannel_ID; dsChannel.Post; result := vChannel; except result := -1; end; end else dsChannel.Cancel; dsChannel.Close; finally ChannelEditForm.free; end; end; procedure TChannelEditForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then OkCancelFrame1bbOkClick(Sender); end; procedure TChannelEditForm.logoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 46 then dsChannel.FieldByName('CH_ICON').Clear; end; procedure TChannelEditForm.OkCancelFrame1bbOkClick(Sender: TObject); var errors: Boolean; begin errors := false; if (edtCH_NAME.Text = '') then begin errors := true; CnErrors.SetError(edtCH_NAME, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtCH_NAME); if not errors then ModalResult := mrOk else ModalResult := mrNone; end; procedure TChannelEditForm.edtDVBGENRESEditButtons0Click(Sender: TObject; var Handled: Boolean); begin edtDVBGENRES.Text := SelectDVBGanres(edtDVBGENRES.Text); Handled := true; end; procedure TChannelEditForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then ModalResult := mrOk; end; procedure TChannelEditForm.FormClose(Sender: TObject; var Action: TCloseAction); begin dsTheme.Close; Action := caFree; end; procedure TChannelEditForm.FormCreate(Sender: TObject); begin dsTheme.Open; end; procedure TChannelEditForm.logoLoad; var fs : TFileStream; begin if OpenDialog1.Execute then begin if not(dsChannel.State in [dsEdit, dsInsert]) then dsChannel.Edit; fs := TFileStream.Create(OpenDialog1.FileName, fmShareDenyNone); try TBlobField(dsChannel.FieldByName('CH_ICON')).LoadFromStream(fs); finally fs.Free; end; end; end; procedure TChannelEditForm.logoSave; begin if not(dsChannel.FieldByName('CH_ICON').IsNull) then begin if SaveDialog.Execute then TBlobField(dsChannel.FieldByName('CH_ICON')).SaveToFile(SaveDialog.FileName); end; end; procedure TChannelEditForm.imgGraphicButtonClick(Sender: TObject; var Handled: Boolean); begin logoLoad; Handled := true; end; procedure TChannelEditForm.imgGraphicDblClick(Sender: TObject); begin logoLoad; end; procedure TChannelEditForm.N1Click(Sender: TObject); begin logoLoad; end; procedure TChannelEditForm.N2Click(Sender: TObject); begin logoSave; end; procedure TChannelEditForm.N3Click(Sender: TObject); begin if not(dsChannel.State in [dsEdit, dsInsert]) then dsChannel.Edit; dsChannel.FieldByName('CH_ICON').Clear; end; end.
unit DAO.AtribuicoesExpressas; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.AtribuicoesExpressas; type TAtribuicoesExpressasDAO= class private FConexao : TConexao; public constructor Create; function GetID(): Integer; function Inserir(AAtribuicoes: TAtribuicoesExpressas): Boolean; function Alterar(AAtribuicoes: TAtribuicoesExpressas): Boolean; function Excluir(AAtribuicoes: TAtribuicoesExpressas): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'expressas_atribuicoes'; implementation { TAtribuicoesExpressasDAO } uses Control.Sistema; function TAtribuicoesExpressasDAO.Alterar(AAtribuicoes: TAtribuicoesExpressas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + ' set cod_atribuicao = :cod_atribuicao, dat_atribuicao = :dat_atribuicao, ' + 'cod_entregador = :cod_entregador, cod_cliente = :cod_cliente, cod_embarcador = :cod_embarcador, ' + 'nom_embarcador = :nom_embarcador, num_nossonumero = :num_nossonumero, cod_retorno = :cod_retorno, ' + 'des_endereco = :des_endereco, num_cep = :num_cep, nom_bairro = :nom_bairro, ' + 'nom_consumidor = :nom_consumidor, qtd_volumes = :qtd_volumes, des_telefone = :des_telefone, ' + 'num_lote_remessa = :num_lote_remessa, dat_retorno = :dat_retorno, dom_retorno = :dom_retorno, ' + 'cod_informativo = :cod_informativo, des_log = :des_log ' + 'where id_atribuicao = :id_atribuicao;', [AAtribuicoes.Codigo, AAtribuicoes.Data, AAtribuicoes.Entregador, AAtribuicoes.Cliente, AAtribuicoes.Embarcador, AAtribuicoes.NomeEmbarcador, AAtribuicoes.NN, AAtribuicoes.CodigoRetorno, AAtribuicoes.Endereco, AAtribuicoes.CEP, AAtribuicoes.Bairro, AAtribuicoes.Consumidor, AAtribuicoes.Volumes, AAtribuicoes.Telefone, AAtribuicoes.Lote, AAtribuicoes.Retorno, AAtribuicoes.FlagRetorno, AAtribuicoes.CodigoInformativo, AAtribuicoes.LOG, AAtribuicoes.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TAtribuicoesExpressasDAO.Create; begin FConexao := TSistemaControl.GetInstance.Conexao; end; function TAtribuicoesExpressasDAO.Excluir(AAtribuicoes: TAtribuicoesExpressas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); if AAtribuicoes.ID <> 0 then begin FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_atribuicao = :id_atribuicao', [AAtribuicoes.ID]); end else if not AAtribuicoes.Codigo.IsEmpty then begin FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_atribuicao = :cod_atribuicao', [AAtribuicoes.Codigo]); end else if not AAtribuicoes.NN.IsEmpty then begin FDQuery.ExecSQL('delete from ' + TABLENAME + ' where num_nossonumero = :num_nossonumero', [AAtribuicoes.NN]); end; Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TAtribuicoesExpressasDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_atribuicao),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAtribuicoesExpressasDAO.Inserir(AAtribuicoes: TAtribuicoesExpressas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); AAtribuicoes.ID := GetID; FDQuery.ExecSQL('insert into ' + TABLENAME + ' (' + 'id_atribuicao, cod_atribuicao, dat_atribuicao, cod_entregador, cod_cliente, cod_embarcador, nom_embarcador, ' + 'num_nossonumero, cod_retorno, des_endereco, num_cep, nom_bairro, nom_consumidor, qtd_volumes, des_telefone, ' + 'num_lote_remessa, dat_retorno, dom_retorno, cod_informativo, des_log) ' + 'VALUES ' + '(:id_atribuicao, :cod_atribuicao, :dat_atribuicao, :cod_entregador, :cod_cliente, :cod_embarcador, ' + ':nom_embarcador, :num_nossonumero, :cod_retorno, :des_endereco, :num_cep, :nom_bairro, :nom_consumidor, '+ ':qtd_volumes, :des_telefone, :num_lote_remessa, :dat_retorno, :dom_retorno, :cod_informtivo, :des_log);', [AAtribuicoes.ID, AAtribuicoes.Codigo, AAtribuicoes.Data, AAtribuicoes.Entregador, AAtribuicoes.Cliente, AAtribuicoes.Embarcador, AAtribuicoes.NomeEmbarcador, AAtribuicoes.NN, AAtribuicoes.CodigoRetorno, AAtribuicoes.Endereco, AAtribuicoes.CEP, AAtribuicoes.Bairro, AAtribuicoes.Consumidor, AAtribuicoes.Volumes, AAtribuicoes.Telefone, AAtribuicoes.Lote, AAtribuicoes.Retorno, AAtribuicoes.FlagRetorno, AAtribuicoes.CodigoInformativo, AAtribuicoes.LOG]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAtribuicoesExpressasDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_atribuicao = :id_atribuicao'); FDQuery.ParamByName('id_atribuicao').AsInteger := aParam[1]; end; if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_atribuicao like :cod_atribuicao'); FDQuery.ParamByName('cod_atribuicao').AsString := aParam[1] + '%'; end; if aParam[0] = 'CODRETORNO' then begin FDQuery.SQL.Add('where cod_retorno = :cod_retorno'); FDQuery.ParamByName('cod_retorno').AsString := aParam[1]; end; if aParam[0] = 'DATA' then begin FDQuery.SQL.Add('where dat_atribuicao = :dat_atribuicao'); FDQuery.ParamByName('dat_atribuicao').AsDateTime := aParam[1]; end; if aParam[0] = 'RETORNO' then begin FDQuery.SQL.Add('where cod_entregador = :cod_entregador and dat_atribuicao between :data1 and :data2 and dom_retorno = 0'); FDQuery.ParamByName('cod_entregador').AsInteger := aParam[1]; FDQuery.ParamByName('data1').AsDateTime := aParam[2]; FDQuery.ParamByName('data2').AsDateTime := aParam[3]; end; if aParam[0] = 'NN' then begin FDQuery.SQL.Add('where num_nossonumero = :num_nossonumero'); FDQuery.ParamByName('num_nossonumero').AsString := aParam[1]; end; if aParam[0] = 'ENTREGADOR' then begin FDQuery.SQL.Add('where cod_entregador = :cod_entregador'); FDQuery.ParamByName('cod_entregador').AsInteger := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; 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; end.
program ejercicio9; const dimF = 500; type vnombres = array[1..dimF] of String; procedure cargarVectorAlumnosA(var v:vnombres; var dimL:Integer); var nom: String; begin write('Ingrese el nombre del alumno: '); readln(nom); while (dimL < dimF) and (nom <> 'zzz') do begin dimL:= dimL + 1; v[dimL]:= nom; write('Ingrese el nombre del alumno: '); readln(nom); end; end; function posicion(v:vnombres; dimL:Integer; nomEliminar: String): Integer; var i: Integer; begin for i := 1 to dimL do begin if (v[i] = nomEliminar) then begin posicion:= i; end; end; end; procedure eliminarNombre(var v: vnombres; var dimL: Integer; var ok: Boolean); var i, pos: Integer; nomEliminar: String; begin nomEliminar:= ''; ok:= false; write('Ingres el nombre a eliminar: '); readln(nomEliminar); pos:= posicion(v,dimL,nomEliminar); if (pos >= 1) and (pos <= dimL) then begin for i := pos to (dimL - 1) do v[i]:= v[i + 1]; ok:= true; dimL:= dimL - 1; end; end; procedure insertarNombre(var v: vnombres; var dimL:Integer); var i: Integer; nomInsertar: String; begin nomInsertar:= ''; write('ingrese el nombre a insertar: '); readln(nomInsertar); if (((dimL + 1) <= dimF)) and (4 <= dimL) and (4 >= 1) then begin for i := dimL downto 4 do v[i+1]:= v[i]; v[4]:= nomInsertar; dimL:= dimL + 1; end; end; procedure agregarNombre(var v:vnombres; var dimL: Integer); var nomAgregar: String; begin write('Ingrese nombre a agregar al vector: '); readln(nomAgregar); if ((dimL + 1) <= dimF) then begin dimL:= dimL + 1; v[dimL]:= nomAgregar; end; end; procedure imprimirVector(v:vnombres; dimL:Integer); var i: Integer; begin for i := 1 to dimL do begin writeln(v[i]); end; end; var v: vnombres; dimL: Integer; ok: Boolean; begin dimL:= 0; cargarVectorAlumnosA(v,dimL); eliminarNombre(v,dimL,ok); imprimirVector(v,dimL); writeln(); insertarNombre(v,dimL); imprimirVector(v,dimL); writeln(); agregarNombre(v,dimL); imprimirVector(v,dimL); readln(); end.
unit evTableRowHotSpot; {* Реализация интерфейсов IevHotSpotTester и IevHotSpot для строки таблицы. } { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: evTableRowHotSpot - } { Начат: 01.11.2000 13:15 } { $Id: evTableRowHotSpot.pas,v 1.72 2015/01/19 18:36:36 lulin Exp $ } // $Log: evTableRowHotSpot.pas,v $ // Revision 1.72 2015/01/19 18:36:36 lulin // {RequestLink:580710025} // // Revision 1.71 2014/04/29 13:38:51 lulin // - вычищаем ненужные зависимости. // // Revision 1.70 2014/04/21 11:45:00 lulin // - переходим от интерфейсов к объектам. // // Revision 1.69 2014/04/07 17:56:59 lulin // - переходим от интерфейсов к объектам. // // Revision 1.68 2013/10/25 10:52:41 morozov // {RequestLink: 254939874} // // Revision 1.67 2013/10/21 15:42:58 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.66 2013/10/21 10:30:41 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.65 2013/04/24 09:35:36 lulin // - портируем. // // Revision 1.64 2011/11/29 13:46:26 dinishev // {Requestlink:109904163} // // Revision 1.63 2011/11/25 12:20:42 dinishev // {Requestlink:109904163}. Самая сложная для нахождения ошибка. ;-) // // Revision 1.62 2011/09/13 10:48:06 lulin // {RequestLink:278839709}. // // Revision 1.61 2011/02/22 19:41:04 lulin // {RequestLink:182157315}. // // Revision 1.60 2011/02/15 11:24:49 lulin // {RequestLink:231670346}. // // Revision 1.59 2010/06/24 15:16:27 lulin // {RequestLink:219125149}. // - пытаемся скроллировать окно, если ушли за его пределы. // // Revision 1.58 2010/04/08 08:11:16 dinishev // [$201490621] // // Revision 1.57 2010/04/06 09:20:42 dinishev // Задел для задачи [$201490621]. Из-за кривого определения границ не всегдя можно было поставить курсор. // // Revision 1.56 2010/03/23 12:16:28 dinishev // [$198673290] // // Revision 1.55 2010/03/02 13:34:35 lulin // {RequestLink:193823544}. // // Revision 1.54 2010/03/01 14:02:56 lulin // {RequestLink:193823544}. // - первый шаг. // // Revision 1.53 2009/07/23 08:14:39 lulin // - вычищаем ненужное использование процессора операций. // // Revision 1.52 2009/07/14 14:56:28 lulin // {RequestLink:141264340}. №25. // // Revision 1.51 2009/07/13 12:31:37 lulin // {RequestLink:141264340}. №23ac. // // Revision 1.50 2009/07/11 15:55:09 lulin // {RequestLink:141264340}. №22. // // Revision 1.49 2009/06/25 12:57:30 lulin // - вычищаем ненужный контекст. // // Revision 1.48 2009/06/02 06:25:58 dinishev // [$148571693] - избавляемся от лишних линий. // // Revision 1.47 2009/05/29 17:18:25 lulin // [$142610853]. // // Revision 1.46 2009/05/26 11:14:50 dinishev // [$146905510]. Не срабатывали на случае, описанном в ошибке. // // Revision 1.45 2009/05/26 07:25:27 dinishev // [$146905510] // // Revision 1.44 2009/04/14 18:11:55 lulin // [$143396720]. Подготовительная работа. // // Revision 1.43 2009/04/06 09:45:27 lulin // [$140837386]. Убираем старорежимную примесь для списков параграфов. // // Revision 1.42 2009/03/31 12:04:36 lulin // [$140286997]. // // Revision 1.41 2009/03/04 13:32:47 lulin // - <K>: 137470629. Генерируем идентификаторы типов с модели и убираем их из общей помойки. // // Revision 1.40 2008/04/15 08:23:46 lulin // - передаём вью в качестве параметра. // // Revision 1.39 2008/04/14 07:48:09 lulin // - передаём вью в рамках <K>: 89096854. // // Revision 1.38 2008/04/10 14:34:05 lulin // - <K>: 89098970. // // Revision 1.37 2008/04/09 17:57:08 lulin // - передаём вью в рамках <K>: 89096854. // // Revision 1.36 2008/04/08 16:41:20 lulin // - передаём View в AssignPoint. <K>: 89096854. // // Revision 1.35 2008/04/04 16:17:59 lulin // - теперь у базового вью нельзя получить курсор по точке. // // Revision 1.34 2008/02/29 10:55:23 dinishev // Bug fix: неправильно расширяли выделение строки // // Revision 1.33 2008/02/27 17:24:58 lulin // - подгоняем код под модель. // // Revision 1.32 2007/12/04 12:47:05 lulin // - перекладываем ветку в HEAD. // // Revision 1.27.4.46 2007/11/28 15:43:47 dinishev // Убираем устаревший код и корректно инициализируем выделение // // Revision 1.27.4.45 2007/09/14 13:26:06 lulin // - объединил с веткой B_Tag_Clean. // // Revision 1.27.4.44.2.1 2007/09/12 15:23:02 lulin // - избавляемся от метода, дублирующего функциональность получения атрибута. // // Revision 1.27.4.44 2007/07/18 15:07:19 lulin // - выпрямляем зависимости. Схема документа, теперь не зависит от Эвереста. // // Revision 1.27.4.43 2007/02/12 18:06:13 lulin // - переводим на строки с кодировкой. // // Revision 1.27.4.42 2007/02/12 17:15:59 lulin // - переводим на строки с кодировкой. // // Revision 1.27.4.41 2007/02/12 16:40:20 lulin // - переводим на строки с кодировкой. // // Revision 1.27.4.40 2007/01/24 10:21:42 oman // - new: Локализация библиотек - ev (cq24078) // // Revision 1.27.4.39 2006/11/03 11:00:07 lulin // - объединил с веткой 6.4. // // Revision 1.27.4.38.2.8 2006/10/31 09:39:37 lulin // - используем карту форматирования переданную сверху, а не привязанную к курсору. // // Revision 1.27.4.38.2.7 2006/10/31 09:21:18 lulin // - при поиске горячей точки подаем уже вычисленную карту форматирования. // // Revision 1.27.4.38.2.6 2006/10/25 10:47:11 lulin // - с видимой точки убрана горизонтальная координата. // // Revision 1.27.4.38.2.5 2006/10/23 08:58:09 lulin // - теперь при определении "горячей точки" передаем базовый курсор. // // Revision 1.27.4.38.2.4 2006/10/19 13:33:18 lulin // - переводим курсоры и подсказки на новые рельсы. // // Revision 1.27.4.38.2.3 2006/10/19 12:05:43 lulin // - добавлен метод для выяснения информации о позиции курсора. // // Revision 1.27.4.38.2.2 2006/10/19 10:56:17 lulin // - параметры курсора переехали в более общую библиотеку. // // Revision 1.27.4.38.2.1 2006/10/18 13:06:34 lulin // - вычищены ненужные данные. // // Revision 1.27.4.38 2006/10/10 12:06:14 lulin // - cleanup. // // Revision 1.27.4.37 2006/10/06 08:24:09 lulin // - убрано предупреждение. // // Revision 1.27.4.36 2006/10/06 08:19:42 lulin // - выкидываем ненужный параметр - класс горячей точки. // // Revision 1.27.4.35.2.2 2006/10/04 15:17:08 lulin // - выкидываем ненужный параметр - класс горячей точки. // // Revision 1.27.4.35.2.1 2006/10/04 14:10:20 lulin // - упрощаем механизм получения горячих точек. // // Revision 1.27.4.35 2006/10/04 11:23:02 lulin // - при получении горячей точки передаем "состояние" курсора. // // Revision 1.27.4.34 2006/10/04 08:32:06 lulin // - теперь умолчательное поведение при действиях мышью описывается структурой - чтобы проще было расширять интерфейс. // // Revision 1.27.4.33 2006/10/04 06:23:44 lulin // - точку мыши упаковываем в состояние мыши. // // Revision 1.27.4.32 2006/10/04 04:33:51 lulin // - избавляемся от возвращаемого результа в стиле OLE. // // Revision 1.27.4.31 2006/08/02 10:51:53 lulin // - объединил с веткой в которой боролся со скроллингом. // // Revision 1.27.4.30.2.1 2006/08/01 10:51:37 lulin // - у отображаемых объектов убрано свойство "ширина". // // Revision 1.27.4.30 2006/07/21 11:43:31 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.27.4.29 2006/07/20 18:36:56 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.27.4.28 2006/07/20 12:55:46 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.27.4.27 2006/07/03 11:58:53 lulin // - передаем не множество клавиш, а "состояние мыши". // // Revision 1.27.4.26 2005/11/21 09:56:54 lulin // - удален ненужный глобальный метод. // // Revision 1.27.4.25 2005/11/08 06:39:37 lulin // - с текстового параграфа и списка параграфов вычищены ненужные методы получения сложной формы параграфа. // // Revision 1.27.4.24 2005/11/07 06:25:22 lulin // - выделяем у якоря и у курсора общую функциональность. // // Revision 1.27.4.23 2005/11/05 07:55:29 lulin // - cleanup: убраны ненужные преобразования объекта к параграфу. // // Revision 1.27.4.22 2005/10/07 10:29:01 lulin // - недоделки помечены специальной меткой. // // Revision 1.27.4.21 2005/08/31 12:04:34 lulin // - удален ненужный модуль. // // Revision 1.27.4.20 2005/08/25 14:12:52 lulin // - new behavior: для КЗ не выводим Hint'ы и прочее для строк и ячеек таблицы с контролами. // // Revision 1.27.4.19 2005/07/20 18:21:14 lulin // - убран переходный интерфейс. // // Revision 1.27.4.18 2005/07/18 11:22:37 lulin // - методу, возвращаещему выделение на параграфе дано более подходящее название. // // Revision 1.27.4.17 2005/07/07 15:10:38 lulin // - new behavior: теперь HotSpot запоминает точку в которой находился курсор. // // Revision 1.27.4.16 2005/07/07 13:09:28 lulin // - упорядочены названия интерфейсов. // // Revision 1.27.4.15 2005/07/07 11:41:17 lulin // - передаем в _GetAdvancedHotSpot специальный интерфейс InevViewPoint. // // Revision 1.27.4.14 2005/07/05 16:02:44 lulin // - bug fix: восстановлен скроллинг при выделении текста мышью. // // Revision 1.27.4.13 2005/06/20 15:42:10 lulin // - cleanup: избавляемся от абсолютных координат. // // Revision 1.27.4.12 2005/06/16 11:24:12 lulin // - убрана косвенная типизация параграфов (при помощи _QI и QT). // // Revision 1.27.4.11 2005/06/15 17:23:52 lulin // - remove proc: _evMoveCursor. // // Revision 1.27.4.10 2005/06/14 14:51:51 lulin // - new interface: _InevSelection. // - remove interface: IevSelection. // // Revision 1.27.4.9 2005/06/14 12:38:58 lulin // - избавился от передачи безликого интерфейса (теперь передается View). // // Revision 1.27.4.8 2005/06/14 10:01:31 lulin // - избавился от передачи безликого интерфейса (теперь передается View). // // Revision 1.27.4.7 2005/06/11 08:55:38 lulin // - в какой-то мере восстановлена работоспособность HotSpot'ов. // // Revision 1.27.4.6 2005/06/06 15:36:09 lulin // - продолжаем бороться со знанием о природе реализации курсоров. // // Revision 1.27.4.5 2005/06/02 12:33:08 lulin // - вчерне заменил прямое создание блока выделения на его получение от фабрики. // // Revision 1.27.4.4 2005/06/01 16:22:25 lulin // - remove unit: evIntf. // // Revision 1.27.4.3 2005/05/31 17:46:39 lulin // - изживаем остатки объектов в качестве курсоров. // // Revision 1.27.4.2 2005/05/31 14:48:01 lulin // - cleanup: при работе с курсорами используем интерфейсы, а не объекты. // // Revision 1.27.4.1 2005/05/18 12:42:47 lulin // - отвел новую ветку. // // Revision 1.25.2.4 2005/05/18 12:32:10 lulin // - очередной раз объединил ветку с HEAD. // // Revision 1.25.2.3 2005/04/28 09:18:30 lulin // - объединил с веткой B_Tag_Box. // // Revision 1.25.2.2 2005/04/09 12:48:37 lulin // - метод ParaByOffset переименован в _ShapeByPt и перенесен на интерфейс InevComplexShape. // // Revision 1.25.2.1 2005/04/08 13:35:05 lulin // - _Processor стал обязательным параметром. // // Revision 1.26.2.1 2005/04/23 16:07:25 lulin // - удален временный интерфейс Ik2TagBox. // // Revision 1.26 2005/04/21 05:11:38 lulin // - используем _Box (пока из-за постоянных преобразований туда и обратно - по скорости стало только хуже). // // Revision 1.27 2005/04/28 15:03:38 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.26.2.1 2005/04/23 16:07:25 lulin // - удален временный интерфейс Ik2TagBox. // // Revision 1.26 2005/04/21 05:11:38 lulin // - используем _Box (пока из-за постоянных преобразований туда и обратно - по скорости стало только хуже). // // Revision 1.25 2005/04/07 15:42:05 lulin // - cleanup. // // Revision 1.24 2005/04/07 15:12:30 lulin // - удалены ненужные формальные параметры. // // Revision 1.23 2005/04/07 14:59:56 lulin // - new method: _InevShape._TranslatePt. // // Revision 1.22 2005/04/07 14:32:49 lulin // - remove proc: evGetTopPara. // // Revision 1.21 2005/03/28 11:32:08 lulin // - интерфейсы переехали в "правильный" модуль. // // Revision 1.20 2005/03/24 13:14:37 lulin // - уделена ненужная функция преобразования Tk2AtomR к _Ik2Tag. // // Revision 1.19 2005/03/16 12:16:52 lulin // - переходим к _Ik2Tag. // // Revision 1.18 2005/03/10 16:40:10 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.17 2005/03/10 16:22:32 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.16 2005/03/10 14:58:38 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.15 2005/03/10 07:05:11 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.14 2005/03/09 18:40:19 lulin // - remove method: Tk2AtomR.DeleteChild. // - new method: _Ik2Tag.DeleteChild. // // Revision 1.13 2003/10/02 16:33:24 law // - rename unit: evBseCur -> evBaseCursor. // // Revision 1.12 2003/01/14 16:47:11 law // - new proc: evTagIndex. // // Revision 1.11 2003/01/13 16:34:04 law // - bug fix: не учитывалось объединение ячеек. // // Revision 1.10 2003/01/13 16:16:32 law // - new behavior: возможность выделения таблицы при DoubleClick на строку. // // Revision 1.9 2003/01/13 15:58:31 law // - new behavior: возможность выделения строки таблицы целиком. // // Revision 1.8 2002/07/09 12:02:21 law // - rename unit: evUnits -> l3Units. // // Revision 1.7 2002/01/29 16:46:25 law // - new behavior: повышаем точность рисования строба. // // Revision 1.6 2002/01/29 16:18:14 law // - new behavior: повышаем точность рисования строба. // // Revision 1.5 2001/04/03 14:13:48 law // - new behavior: теперь evTable_GetMergeHead возвращает все ID начиная с нуля (а не единицы). Также добавлен параметр pRowID. // // Revision 1.4 2001/03/22 15:22:27 law // - сделана трансляция HotSpot'а к головной ячейке. // // Revision 1.3 2000/12/15 15:10:38 law // - вставлены директивы Log. // {$Include evDefine.inc } interface uses l3Types, l3Base, l3IID, l3Units, afwInterfaces, k2Interfaces, k2InternalInterfaces, evInternalInterfaces, evTableColumnHotSpot, evParaListHotSpotTester, evSelectingHotSpot, nevTools, nevGUIInterfaces ; type TevTableRowHotSpotTester = class(TevParaListHotSpotTester) {* - реализует интерфейс IevHotSpotTester для строки таблицы } protected // internal methods function GetTableColumnHotSpot: RevTableColumnHotSpot; virtual; {-} function NeedRowSpot: Boolean; virtual; {-} public //public methods function GetChildHotSpot(const aView : InevControlView; const aState : TevCursorState; const aPt : InevBasePoint; const aMap : InevMap; const aChild : InevObject; out theSpot : IevHotSpot): Boolean; override; {-} end;//TevTableRowHotSpotTester TevTableRowHotSpot = class(TevSelectingHotSpot) private {* - реализует интерфейс IevAdvancedHotSpot для ячейки таблицы. } protected // internal fields f_StartPoint : InevBasePoint; {* - Начальная точка. } protected //property methods procedure DoHitTest(const aView : InevControlView; const aState : TafwCursorState; var theInfo : TafwCursorInfo); override; {-} protected // internal methods function InitSelection(const aView : InevControlView; const aPt : InevBasePoint; const theStart : InevBasePoint; const theFinish : InevBasePoint): Bool; override; {-} function SelectionTable: InevParaList; {-} procedure Cleanup; override; {-} public //public methods function MouseAction(const aView : InevControlView; aButton : TevMouseButton; anAction : TevMouseAction; const Keys : TevMouseState; var Effect : TevMouseEffect): Bool; override; {* - обрабатывает событие мыши. } end;//TevTableRowHotSpot implementation uses l3Const, l3String, k2Tags, evdTypes, evOp, evConst, evParaTools, evTableTools, evCursorTools, evHotSpotMisc, nevInterfaces, TableRow_Const ; // start class TevTableRowHotSpotTester function TevTableRowHotSpotTester.NeedRowSpot: Boolean; //virtual; {-} begin Result := True; end; function TevTableRowHotSpotTester.GetChildHotSpot(const aView : InevControlView; const aState : TevCursorState; const aPt : InevBasePoint; const aMap : InevMap; const aChild : InevObject; out theSpot : IevHotSpot): Boolean; //override; {-} var l_Map : InevMap; l_X : Integer; l_Delta : Integer; begin if NeedRowSpot then begin Result := True; l_Map := aMap; if (l_Map <> nil) then begin if not l_Map.rVisible then l_Map := aView.MapByPoint(aChild.MakePoint, True); Assert(l_Map <> nil); l_X := aState.rPoint.X - l_Map.Bounds.Left; if (l_X < 0) then theSpot := TevHotSpotWrap.Make(TevTableRowHotSpot.Make(aChild.OwnerObj.AsObject, Processor)) else begin l_Delta := l_X - l_Map.FI.Width; if (Abs(l_Delta) <= 4 * evEpsilon) then theSpot := TevHotSpotWrap.Make( GetTableColumnHotSpot.Make(aView, aChild.OwnerObj.AsObject, aChild.PID + 1, str_nevmhCellSize.AsCStr, l_Delta)) else Result := inherited GetChildHotSpot(aView, aState, aPt, aMap, aChild, theSpot); end//l_X < 0 end//l_Map <> nil else Result := inherited GetChildHotSpot(aView, aState, aPt, aMap, aChild, theSpot); end//NeedRowSpot else Result := inherited GetChildHotSpot(aView, aState, aPt, aMap, aChild, theSpot); end; // start class TevTableRowHotSpot procedure TevTableRowHotSpot.DoHitTest(const aView : InevControlView; const aState : TafwCursorState; var theInfo : TafwCursorInfo); //override; {-} begin inherited; theInfo.rCursor := ev_csSelectLine; theInfo.rHint := str_nevmhhTableRow.AsCStr; end; function TevTableRowHotSpot.InitSelection(const aView : InevControlView; const aPt : InevBasePoint; const theStart : InevBasePoint; const theFinish : InevBasePoint): Bool; //override; {-} var l_Point : InevBasePoint; begin Result := True; Assert(aView <> nil); l_Point := aPt; while (l_Point <> nil) do begin if l_Point.AsObject.IsKindOf(k2_typTableRow) then Break; l_Point := l_Point.Inner; end;//while (l_Point <> nil) if (l_Point <> nil) then begin if ((f_StartPoint.Obj.PID) > l_Point.Obj.PID) then begin theFinish.AssignPoint(aView, f_StartPoint); theFinish.Move(aView, ev_ocBottomRight); theStart.AssignPoint(aView, l_Point); theStart.Move(aView, ev_ocTopLeft); end//if (l_Start > l_Finish) then else begin theStart.AssignPoint(aView, f_StartPoint); theStart.Move(aView, ev_ocTopLeft); theFinish.AssignPoint(aView, l_Point); theFinish.Move(aView, ev_ocBottomRight); end;//(f_StartPoint.Obj.PID) > l_Point.Obj.PID end//l_Point <> nil else Result := False; end; function TevTableRowHotSpot.MouseAction(const aView : InevControlView; aButton : TevMouseButton; anAction : TevMouseAction; const Keys : TevMouseState; var Effect : TevMouseEffect): Bool; {* - Обрабатывает событие мыши. } begin Result := inherited MouseAction(aView, aButton, anAction, Keys, Effect); case aButton of ev_mbLeft : begin case anAction of ev_maDown : begin f_StartPoint := ParaX.MakePoint; f_StartPoint.SetAtStart(aView, True); Result := evSelectTablePara(aView.Control.Selection, ParaX); end;//ev_maDown ev_maDouble : begin Result := evSelectTablePara(aView.Control.Selection, SelectionTable); if Result then Effect.rNeedAsyncLoop := False; end;//ev_maDouble end;//case anAction end;//ev_mbLeft end;//case aButton end; function TevTableRowHotSpot.SelectionTable: InevParaList; begin Result := ParaX.OwnerPara; end; procedure TevTableRowHotSpot.Cleanup; begin f_StartPoint := nil; inherited; end; function TevTableRowHotSpotTester.GetTableColumnHotSpot: RevTableColumnHotSpot; begin Result := TevTableColumnHotSpot; end; end.
unit uGnFormProgress; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TFormCzProgress = class(TForm) ProgressBar1: TProgressBar; bCancel: TButton; lMessage: TLabel; procedure bCancelClick(Sender: TObject); private FCancelFlag: Boolean; procedure SetMsg(const AMsg: string); public constructor Create(const AForm: TForm); reintroduce; procedure Show(const ANumberFields: Integer; const ACaption: string = 'Обработка'); reintroduce; procedure Restart(const ANumberFields: Integer); procedure IncProgress; property Msg: string write SetMsg; property CancelFlag: Boolean read FCancelFlag; end; var FormCzProgress: TFormCzProgress; implementation {$R *.dfm} procedure TFormCzProgress.bCancelClick(Sender: TObject); begin FCancelFlag := True; end; constructor TFormCzProgress.Create(const AForm: TForm); begin inherited Create(AForm); PopupMode := pmAuto; PopupParent := AForm; end; procedure TFormCzProgress.IncProgress; begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; procedure TFormCzProgress.Restart(const ANumberFields: Integer); begin ProgressBar1.Position := 0; ProgressBar1.Max := ANumberFields - 1; FCancelFlag := False; end; procedure TFormCzProgress.SetMsg(const AMsg: string); begin lMessage.Caption := AMsg; Application.ProcessMessages; end; procedure TFormCzProgress.Show(const ANumberFields: Integer; const ACaption: string); begin Restart(ANumberFields); inherited Show; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$I ..\ElPack.inc} unit MlCapProp; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, {$ifdef VCL_6_USED} DesignIntf, DesignEditors, DesignWindows, DsnConst, {$else} DsgnIntf, {$endif} Typinfo, {$ifdef ELPACK_UNICODE} ElUnicodeStrings, {$endif} ExtCtrls, StdCtrls, ComCtrls, ElIni, ElFrmPers, ElXPThemedControl, ElEdits, Buttons; type TMlCapEditDialog = class(TForm) Panel1: TPanel; OkButton: TButton; CancelButton: TButton; Panel2: TPanel; LineCounter: TLabel; Memo: TElEdit; Load: TSpeedButton; Save: TSpeedButton; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure MemoChange(Sender : TObject); procedure LoadClick(Sender: TObject); procedure SaveClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); end; type TMlCaptionProperty = class(TStringProperty) private public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; {$ifdef ELPACK_UNICODE} TElWideStringsProperty = class(TClassProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; {$endif} implementation {$R *.DFM} procedure TMlCapEditDialog.MemoChange(Sender : TObject); begin LineCounter.Caption := Format('%d Lines', [Memo.Lines.Count]) end; procedure TMlCaptionProperty.Edit; begin with TMlCapEditDialog.Create(Application) do try {$ifdef D_6_UP} if GetPropType^.Kind = tkWString then begin Memo.Text := TypInfo.GetWideStrProp(GetComponent(0), GetPropInfo); end else {$endif} Memo.Text := GetValue; MemoChange(Self); if ShowModal = mrOk then begin {$ifdef D_6_UP} if GetPropType^.Kind = tkWString then begin SetWideStrProp(GetComponent(0), GetPropInfo, Memo.Text); end else {$endif} SetValue(Memo.Text); end; finally Free end end; function TMlCaptionProperty.GetAttributes : TPropertyAttributes; begin {$ifdef D_6_UP} Result := [paDialog]; {$else} Result := [paMultiSelect, paDialog]; {$endif} end; {$ifdef ELPACK_UNICODE} procedure TElWideStringsProperty.Edit; begin with TMlCapEditDialog.Create(Application) do try Memo.Lines.Assign(TElWideStrings(GetOrdValue)); MemoChange(Memo); if ShowModal = mrOk then begin SetOrdValue(Longint(Memo.Lines)); // TElWideStrings(GetOrdValue).Assign(Memo.Lines); end; finally Free; end end; function TElWideStringsProperty.GetAttributes : TPropertyAttributes; begin Result := inherited GetAttributes + [paDialog] - [paSubProperties]; end; {$endif} procedure TMlCapEditDialog.LoadClick(Sender: TObject); begin if OpenDialog.Execute then Memo.Lines.LoadFromFile(OpenDialog.FileName); end; procedure TMlCapEditDialog.SaveClick(Sender: TObject); begin if SaveDialog.Execute then Memo.Lines.SaveToFile(SaveDialog.FileName); end; procedure TMlCapEditDialog.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27{VK_ESCAPE} then ModalResult := mrCancel; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Program: TNCNX.PAS Object: Delphi component which implement the TCP/IP telnet protocol including some options negociations. RFC854, RFC885, RFC779, RFC1091 Author: François PIETTE EMail: francois.piette@overbyte.be http://www.overbyte.be Creation: April, 1996 Version: 6.00 Support: Use the mailing list twsocket@elists.org See website for details. Legal issues: Copyright (C) 1996-2006 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Updates: Jul 22, 1997 Adapted to Delphi 3 Sep 05, 1997 Added version information, removed old code, added OnTermType Renamed some indentifier to be more standard. Sep 24, 1997 V2.03 Added procedures to negociate options May 12, 1998 V2.04 Changed NegociateOption to properly handle unwanted option as Jan Tomasek <xtomasej@feld.cvut.cz> suggested. Aug 10, 1998 V2.05 Cleared strSubOption after NegociateSubOption as Jan Tomasek <xtomasej@feld.cvut.cz> suggested. Aug 15, 1999 V2.06 Moved Notification procedure to public section for BCB4 compatibility Aug 20, 1999 V2.07 Added compile time options. Revised for BCB4. Jun 18, 2001 V2.08 Use AllocateHWnd and DeallocateHWnd from wsocket. Oct 23, 2002 V2.09 Changed Buffer arg in OnDataAvailable to Pointer instead of PChar to avoid Delphi 7 messing everything with AnsiChar. May 31, 2004 V2.10 Used ICSDEFS.INC, removed unused units. Jan 13, 2005 V2.11 Replaced symbol "Debug" by "DEBUG_OUTPUT" Mar 11, 2006 V2.12 Arno Garrels made it NOFORMS compatible Mar 26, 2006 V6.00 New version 6 started from V5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsTnCnx; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$I OverbyteIcsDefs.inc} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFNDEF VER80} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} interface uses Messages, {$IFDEF USEWINDOWS} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} SysUtils, Classes, OverbyteIcsWndControl, OverbyteIcsWSocket, OverbyteIcsWinsock; const TnCnxVersion = 600; CopyRight : String = ' TTnCnx (c) 1996-2006 F. Piette V6.00 '; { Telnet command characters } TNCH_EOR = #239; { $EF End Of Record (preceded by IAC) } TNCH_SE = #240; { $F0 End of subnegociation parameters } TNCH_NOP = #241; { $F1 No operation } TNCH_DATA_MARK = #242; { $F2 Data stream portion of a Synch } TNCH_BREAK = #243; { $F3 NVT charcater break } TNCH_IP = #244; { $F4 Interrupt process } TNCH_AO = #245; { $F5 Abort output } TNCH_AYT = #246; { $F6 Are you there } TNCH_EC = #247; { $F7 Erase character } TNCH_EL = #248; { $F8 Erase line } TNCH_GA = #249; { $F9 Go ahead } TNCH_SB = #250; { $FA Subnegociation } TNCH_WILL = #251; { $FB Will } TNCH_WONT = #252; { $FC Wont } TNCH_DO = #253; { $FD Do } TNCH_DONT = #254; { $FE Dont } TNCH_IAC = #255; { $FF IAC } { Telnet options } TN_TRANSMIT_BINARY = #0; { $00 } TN_ECHO = #1; { $01 } TN_RECONNECTION = #2; { $02 } TN_SUPPRESS_GA = #3; { $03 } TN_MSG_SZ_NEGOC = #4; { $04 } TN_STATUS = #5; { $05 } TN_TIMING_MARK = #6; { $06 } TN_NOPTIONS = #6; { $06 } TN_DET = #20; { $14 } TN_SEND_LOC = #23; { $17 } TN_TERMTYPE = #24; { $18 } TN_EOR = #25; { $19 } TN_NAWS = #31; { $1F } TN_TERMSPEED = #32; { $20 } TN_TFC = #33; { $21 } TN_XDISPLOC = #35; { $23 } TN_EXOPL = #255; { $FF } TN_TTYPE_SEND = #1; TN_TTYPE_IS = #0; type TTnCnx = class; TTnSessionConnected = procedure (Sender: TTnCnx; Error : word) of object; TTnSessionClosed = procedure (Sender: TTnCnx; Error : word) of object; TTnDataAvailable = procedure (Sender: TTnCnx; Buffer : Pointer; Len : Integer) of object; TTnDisplay = procedure (Sender: TTnCnx; Str : String) of object; TTnCnx= class(TIcsWndControl) private FPort : String; FHost : String; FLocation : String; FTermType : String; RemoteBinMode : Boolean; LocalBinMode : Boolean; FLocalEcho : Boolean; Spga : Boolean; FTType : Boolean; FBuffer : array [0..2048] of char; FBufferCnt : Integer; FOnSessionConnected : TTnSessionConnected; FOnSessionClosed : TTnSessionClosed; FOnDataAvailable : TTnDataAvailable; FOnDisplay : TTnDisplay; FOnEOR : TNotifyEvent; FOnSendLoc : TNotifyEvent; FOnTermType : TNotifyEvent; FOnLocalEcho : TNotifyEvent; procedure SocketSessionConnected(Sender: TObject; Error : word); procedure SocketSessionClosed(Sender: TObject; Error : word); procedure SocketDataAvailable(Sender: TObject; Error : word); procedure Display(Str : String); procedure AddChar(Ch : Char); procedure ReceiveChar(Ch : Char); procedure Answer(chAns : Char; chOption : Char); procedure NegociateSubOption(strSubOption : String); procedure NegociateOption(chAction : Char; chOption : Char); procedure FlushBuffer; function GetState : TSocketState; public Socket : TWSocket; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Send(Data : Pointer; Len : Integer) : integer; function SendStr(Data : String) : integer; procedure Connect; function IsConnected : Boolean; procedure WillOption(chOption : Char); procedure WontOption(chOption : Char); procedure DontOption(chOption : Char); procedure DoOption(chOption : Char); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Close; procedure Pause; procedure Resume; property State : TSocketState read GetState; published property Port : String read FPort write FPort; property Host : String read FHost write FHost; property Location : String read FLocation write FLocation; property TermType : String read FTermType write FTermType; property LocalEcho : Boolean read FLocalEcho write FLocalEcho; property OnSessionConnected : TTnSessionConnected read FOnSessionConnected write FOnSessionConnected; property OnSessionClosed : TTnSessionClosed read FOnSessionClosed write FOnSessionClosed; property OnDataAvailable : TTnDataAvailable read FOnDataAvailable write FOnDataAvailable; property OnDisplay : TTnDisplay read FOnDisplay write FOnDisplay; property OnEndOfRecord : TNotifyEvent read FOnEOR write FOnEOR; property OnSendLoc : TNotifyEvent read FOnSendLoc write FOnSendLoc; property OnTermType : TNotifyEvent read FOnTermType write FOnTermType; property OnLocalEcho : TNotifyEvent read FOnLocalEcho write FOnLocalEcho; end; procedure Register; implementation {-$DEFINE DEBUG_OUTPUT} { Add or remove minus sign before dollar sign to } { generate code for debug message output } {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure Register; begin RegisterComponents('FPiette', [TTnCnx]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure DebugString(Msg : String); const Cnt : Integer = 0; {$IFDEF DEBUG_OUTPUT} var Buf : String[20]; {$ENDIF} begin {$IFDEF DEBUG_OUTPUT} Cnt := Cnt + 1; Buf := IntToHex(Cnt, 4) + ' ' + #0; WinProcs.OutputDebugString(@Buf[1]); {$IFNDEF WIN32} if Length(Msg) < High(Msg) then Msg[Length(Msg) + 1] := #0; {$ENDIF} WinProcs.OutputDebugString(@Msg[1]); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TTnCnx.Create(AOwner: TComponent); begin inherited Create(AOwner); AllocateHWnd; FLocation := 'TNCNX'; FTermType := 'VT100'; FPort := '23'; Socket := TWSocket.Create(Self); Socket.OnSessionConnected := SocketSessionConnected; Socket.OnDataAvailable := SocketDataAvailable; Socket.OnSessionClosed := SocketSessionClosed; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TTnCnx.Destroy; begin if Assigned(Socket) then begin Socket.Free; Socket := nil; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = Socket) and (Operation = opRemove) then Socket := nil; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Pause; begin if not Assigned(Socket) then Exit; Socket.Pause; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Resume; begin if not Assigned(Socket) then Exit; Socket.Resume; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Connect; begin if not Assigned(Socket) then Exit; if Socket.State <> wsClosed then Socket.Close; Socket.Proto := 'tcp'; Socket.Port := FPort; Socket.Addr := FHost; Socket.Connect; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTnCnx.IsConnected : Boolean; begin Result := Socket.State = wsConnected; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Close; begin if Assigned(Socket) then Socket.Close; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Display(Str : String); begin if Assigned(FOnDisplay) then FOnDisplay(Self, Str); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTnCnx.GetState : TSocketState; begin if Assigned(Socket) then Result := Socket.State else Result := wsInvalidState; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.SocketSessionConnected(Sender: TObject; Error : word); begin if Assigned(FOnSessionConnected) then FOnSessionConnected(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.SocketSessionClosed(Sender: TObject; Error : word); begin if Socket.State <> wsClosed then Socket.Close; if Assigned(FOnSessionClosed) then FOnSessionClosed(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.SocketDataAvailable(Sender: TObject; Error : word); var Len, I : Integer; Buffer : array [1..2048] of char; Socket : TWSocket; begin Socket := Sender as TWSocket; Len := Socket.Receive(@Buffer[1], High(Buffer)); if Len = 0 then begin { Remote has closed } Display(#13 + #10 + '**** Remote has closed ****' + #13 + #10); end else if Len < 0 then begin { An error has occured } if Socket.LastError <> WSAEWOULDBLOCK then Display(#13 + #10 + '**** ERROR: ' + IntToStr(Socket.LastError) + ' ****' + #13 + #10); end else begin for I := 1 to Len do ReceiveChar(Buffer[I]); FlushBuffer; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTnCnx.Send(Data : Pointer; Len : Integer) : integer; begin if Assigned(Socket) then Result := Socket.Send(Data, Len) else Result := -1; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTnCnx.SendStr(Data : String) : integer; begin Result := Send(@Data[1], Length(Data)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.Answer(chAns : Char; chOption : Char); var Buf : String[3]; begin { DebugString('Answer ' + IntToHex(ord(chAns), 2) + ' ' + IntToHex(ord(ChOption), 2) + #13 + #10); } Buf := TNCH_IAC + chAns + chOption; Socket.Send(@Buf[1], Length(Buf)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.WillOption(chOption : Char); begin Answer(TNCH_WILL, chOption); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.WontOption(chOption : Char); begin Answer(TNCH_WONT, chOption); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.DontOption(chOption : Char); begin Answer(TNCH_DONT, chOption); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.DoOption(chOption : Char); begin Answer(TNCH_DO, chOption); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.NegociateSubOption(strSubOption : String); var Buf : String; begin { DebugString('SubNegociation ' + IntToHex(ord(strSubOption[1]), 2) + ' ' + IntToHex(ord(strSubOption[2]), 2) + #13 + #10); } case strSubOption[1] of TN_TERMTYPE: begin if strSubOption[2] = TN_TTYPE_SEND then begin { DebugString('Send TermType' + #13 + #10); } if Assigned(FOnTermType) then FOnTermType(Self); Buf := TNCH_IAC + TNCH_SB + TN_TERMTYPE + TN_TTYPE_IS + FTermType + TNCH_IAC + TNCH_SE; Socket.Send(@Buf[1], Length(Buf)); end; end; else { DebugString('Unknown suboption' + #13 + #10); } end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.NegociateOption(chAction : Char; chOption : Char); var Buf : String; begin { DebugString('Negociation ' + IntToHex(ord(chAction), 2) + ' ' + IntToHex(ord(ChOption), 2) + #13 + #10); } case chOption of TN_TRANSMIT_BINARY: begin if chAction = TNCH_WILL then begin Answer(TNCH_DO, chOption); RemoteBinMode := TRUE; LocalBinMode := TRUE; end else if chAction = TNCH_WONT then begin if RemoteBinMode then begin RemoteBinMode := FALSE; LocalBinMode := FALSE; end; end; end; TN_ECHO: begin if chAction = TNCH_WILL then begin Answer(TNCH_DO, chOption); FLocalEcho := FALSE; end else if chAction = TNCH_WONT then begin FLocalEcho := TRUE; end; if Assigned(FOnLocalEcho) then FOnLocalEcho(self); end; TN_SUPPRESS_GA: begin if chAction = TNCH_WILL then begin Answer(TNCH_DO, chOption); spga := TRUE; end; end; TN_TERMTYPE: begin if chAction = TNCH_DO then begin Answer(TNCH_WILL, chOption); FTType := TRUE; end; end; TN_SEND_LOC: begin if chAction = TNCH_DO then begin Answer(TNCH_WILL, chOption); if Assigned(FOnSendLoc) then FOnSendLoc(Self); Buf := TNCH_IAC + TNCH_SB + TN_SEND_LOC + FLocation + TNCH_IAC + TNCH_SE; Socket.Send(@Buf[1], Length(Buf)); end; end; TN_EOR: begin if chAction = TNCH_DO then begin Answer(TNCH_WILL, chOption); FTType := TRUE; end; end; else { Answer(TNCH_WONT, chOption); } { Jan Tomasek <xtomasej@feld.cvut.cz> } if chAction = TNCH_WILL then Answer(TNCH_DONT, chOption) else Answer(TNCH_WONT, chOption); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.FlushBuffer; var Buffer : PChar; Count : Integer; begin try if FBufferCnt > 0 then begin if Assigned(FOnDataAvailable) then begin { We need to make a copy for the data because we can reenter } { during the event processing } Count := FBufferCnt; { How much we received } try GetMem(Buffer, Count + 1); { Alloc memory for the copy } except Buffer := nil; end; if Buffer <> nil then begin try Move(FBuffer, Buffer^, Count); { Actual copy } Buffer[Count] := #0; { Add a nul byte } FBufferCnt := 0; { Reset receivecounter } FOnDataAvailable(Self, Buffer, Count); { Call event handler } finally FreeMem(Buffer, Count + 1); { Release the buffer } end; end; end else begin FBufferCnt := 0 end; end; except raise; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.AddChar(Ch : Char); begin FBuffer[FBufferCnt] := Ch; Inc(FBufferCnt); if FBufferCnt >= SizeOf(FBuffer) then FlushBuffer; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTnCnx.ReceiveChar(Ch : Char); const bIAC : Boolean = FALSE; chVerb : Char = #0; strSubOption : String = ''; bSubNegoc : Boolean = FALSE; begin if chVerb <> #0 then begin NegociateOption(chVerb, Ch); chVerb := #0; strSubOption := ''; Exit; end; if bSubNegoc then begin if Ch = TNCH_SE then begin bSubNegoc := FALSE; NegociateSubOption(strSubOption); strSubOption := ''; end else strSubOption := strSubOption + Ch; Exit; end; if bIAC then begin case Ch of TNCH_IAC: begin AddChar(Ch); bIAC := FALSE; end; TNCH_DO, TNCH_WILL, TNCH_DONT, TNCH_WONT: begin bIAC := FALSE; chVerb := Ch; end; TNCH_EOR: begin DebugString('TNCH_EOR' + #13 + #10); bIAC := FALSE; if Assigned(FOnEOR) then FOnEOR(Self); end; TNCH_SB: begin { DebugString('Subnegociation' + #13 + #10); } bSubNegoc := TRUE; bIAC := FALSE; end; else DebugString('Unknown ' + IntToHex(ord(Ch), 2) + ' ''' + Ch + '''' + #13 + #10); bIAC := FALSE; end; Exit; end; case Ch of TNCH_EL: begin DebugString('TNCH_EL' + #13 + #10); AddChar(Ch); end; TNCH_EC: begin DebugString('TNCH_EC' + #13 + #10); AddChar(Ch); end; TNCH_AYT: begin DebugString('TNCH_AYT' + #13 + #10); AddChar(Ch); end; TNCH_IP: begin DebugString('TNCH_IP' + #13 + #10); AddChar(Ch); end; TNCH_AO: begin DebugString('TNCH_AO' + #13 + #10); AddChar(Ch); end; TNCH_IAC: begin bIAC := TRUE end; else AddChar(Ch); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit uICUGCU300FirmwareDownload; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Gauges, ExtCtrls, RzPanel, RzRadGrp, StdCtrls, Buttons, RzButton, RzLabel, Grids, AdvObj, BaseGrid, AdvGrid, LMDCustomComponent, LMDIniCtrl,iniFiles, uSubForm, CommandArray; type TfmICUGCU300FirmwareDownload = class(TfmASubForm) GroupBox1: TGroupBox; RzLabel41: TRzLabel; btnClose: TRzBitBtn; btnFirmwareUpdate: TRzBitBtn; ed_FirmwareFile: TEdit; btn_FileSearch: TBitBtn; Group_811: TRzCheckGroup; GroupBox2: TGroupBox; ProgressBar1: TGauge; Group_BroadDownLoadBase: TRzCheckGroup; sg_Icu300FirmwareDownload: TAdvStringGrid; OpenDialog1: TOpenDialog; LMDIniCtrl2: TLMDIniCtrl; Label519: TLabel; ed_Icu300broadTime: TEdit; RzOpenDialog1: TOpenDialog; procedure btnCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Group_BroadDownLoadBaseChange(Sender: TObject; Index: Integer; NewState: TCheckBoxState); procedure btn_FileSearchClick(Sender: TObject); procedure btnFirmwareUpdateClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FirmwareDownLoadList_GCU300 : TStringList; FirmwareDownLoadList_ICU300 : TStringList; FDeviceType: string; FDeviceID: string; procedure SetDeviceType(const Value: string); procedure Ecu_GroupCreate; function Check_GCU300ICU300FirmwareComplete : Boolean; procedure Clear_FirmwareDownLoadList; procedure GCUICU300HexSendPacketEvent(Sender: TObject; aSendHexData,aViewHexData: string); function GetFirmWareSelectDevice : string; function GetFirmWarePath : string; procedure StringGrid_Change(aList:TAdvStringGrid;aEcuID,aNo:string;aMaxSize,aCurPosition:integer); procedure MainRequestProcessChange(Sender: TObject; aEcuID,aNo,aDeviceType: string;aMaxSize,aCurPosition:integer); { Private declarations } public procedure ICU300FirmWareProcess(aECUID,aRealPacketData:string); procedure GCU300_ICU300FirmwareDownloadState(aEcuID,aRealPacket:string); public { Public declarations } property DeviceID : string read FDeviceID write FDeviceID; property DeviceType : string read FDeviceType write SetDeviceType; end; var fmICUGCU300FirmwareDownload: TfmICUGCU300FirmwareDownload; implementation uses dllFunction, uCommon, uICU300FirmwareData, uUtil, uSocket, uMain; {$R *.dfm} procedure TfmICUGCU300FirmwareDownload.btnCloseClick(Sender: TObject); begin Close; end; procedure TfmICUGCU300FirmwareDownload.Ecu_GroupCreate; var i : integer; nIndex : integer; begin Group_811.Items.Clear; for I:= 0 to 63 do begin Group_811.Items.Add(FillZeroNumber(i,2)); nIndex := DeviceList.IndexOf(FillZeroNumber(i,2)); if nIndex > -1 then begin if DeviceType = 'SCR302' then begin if (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT811) or (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT812) or (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT813) then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then begin Group_811.ItemChecked[i]:= True; end; end; end else if DeviceType = 'ICU300' then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = ICU300 then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then begin Group_811.ItemChecked[i]:= True; end; end; end; end; end; end; procedure TfmICUGCU300FirmwareDownload.SetDeviceType(const Value: string); var ini_fun : TiniFile; begin FDeviceType := Value; if Value = 'ICU300' then begin sg_Icu300FirmwareDownload.ColWidths[1] := 0; sg_Icu300FirmwareDownload.ColWidths[3] := 0; end else if Value = 'SCR302' then begin sg_Icu300FirmwareDownload.ColWidths[1] := 88; sg_Icu300FirmwareDownload.ColWidths[3] := 0; end; ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI'); ed_FirmwareFile.Text := ini_fun.ReadString(DeviceType,'FileName',''); ini_fun.Free; if FileExists(ed_FirmwareFile.Text) then btnFirmwareUpdate.Enabled := True; end; procedure TfmICUGCU300FirmwareDownload.FormShow(Sender: TObject); begin Ecu_GroupCreate; fmMain.L_bICU300FirmWareSendShow := True; end; procedure TfmICUGCU300FirmwareDownload.Group_BroadDownLoadBaseChange(Sender: TObject; Index: Integer; NewState: TCheckBoxState); var I: Integer; Base: Integer; begin if Index < 7 then begin Base:= Index * 10; if NewState = cbChecked then begin for I:= 0 to 9 do if (Group_811.Items.Count > Base + I) then Group_811.ItemChecked[Base + I]:= True; end else begin for I:= 0 to 9 do if (Group_811.Items.Count > Base + I) then Group_811.ItemChecked[Base + I]:= False; end; end else begin if NewState = cbChecked then begin for I:= 0 to Group_811.Items.Count -1 do Group_811.ItemChecked[I]:= True; for I:= 0 to Group_BroadDownLoadBase.Items.Count -1 do Group_BroadDownLoadBase.ItemChecked[I]:= True; end else begin for I:= 0 to Group_811.Items.Count -1 do Group_811.ItemChecked[I]:= False; for I:= 0 to Group_BroadDownLoadBase.Items.Count -1 do Group_BroadDownLoadBase.ItemChecked[I]:= False; end; end; end; procedure TfmICUGCU300FirmwareDownload.btn_FileSearchClick( Sender: TObject); var st: string; ini_fun : TiniFile; begin RzOpenDialog1.Title:= '펌웨어 설정 파일 찾기'; RzOpenDialog1.DefaultExt:= 'ini'; RzOpenDialog1.Filter := 'INI files (*.ini)|*.INI'; if RzOpenDialog1.Execute then begin st:= RzOpenDialog1.FileName; ed_FirmwareFile.Text:= st; ed_FirmwareFile.SelectAll; ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI'); ini_fun.WriteString(DeviceType,'FileName',ed_FirmwareFile.Text); ini_fun.Free; btnFirmwareUpdate.Enabled := True; end; end; procedure TfmICUGCU300FirmwareDownload.btnFirmwareUpdateClick( Sender: TObject); var ini_fun : TiniFile; stFirmwareFile : string; stDeviceID : string; stTemp : string; i : integer; nFirmwareIndex : integer; begin Clear_FirmwareDownLoadList; dmICU300FirmwareData.DeviceType := DeviceType; if Not FileExists(ed_FirmwareFile.Text) then begin showmessage('INI 파일을 찾을 수 없습니다.'); Exit; end; Try ini_fun := TiniFile.Create(ed_FirmwareFile.Text); if StringReplace(ini_fun.ReadString('Config','TYPE',''),'-','',[rfReplaceAll]) <> DeviceType then begin showmessage(DeviceType + ' 펌웨어 파일이 아닙니다.'); Exit; end; stFirmwareFile := ExtractFileDir(ed_FirmwareFile.Text) + '\' + ini_fun.ReadString('Config','FILE',''); if Not FileExists(stFirmwareFile) then begin showmessage(stFirmwareFile + '펌웨어 파일을 찾을 수 없습니다.'); Exit; end; Finally ini_fun.Free; end; btnFirmwareUpdate.Enabled := False; btnClose.Enabled := False; stDeviceID := '00'; //path 선택 전송 stTemp := GetFirmWarePath; for i:=0 to 5 do //5회 전송 하자. begin dmSocket.DirectSendPacket(stDeviceID,'R','FW10 01' + DeviceType + stTemp,True,1); MyDelay(500); end; //기기 선택 전송 stTemp := GetFirmWareSelectDevice; for i:=0 to 5 do //5회 전송 하자. begin dmSocket.DirectSendPacket(stDeviceID,'R','FW10 11' + DeviceType + stTemp,True,1); MyDelay(500); end; //BootJump stTemp := '00150 '; for i:=0 to 63 do stTemp := stTemp + '1'; //출입문 열고 펌웨어 업데이트 하자. for i:=0 to 5 do //5회 전송 하자. begin dmSocket.DirectSendPacket(stDeviceID,'R','FW10 12' + DeviceType + stTemp,True,1); MyDelay(500); end; dmICU300FirmwareData.FirmwareFileName := stFirmwareFile; dmICU300FirmwareData.DeviceID:= DeviceID + '00'; dmICU300FirmwareData.OnSendPacketEvent := GCUICU300HexSendPacketEvent; dmICU300FirmwareData.PacketSize := 100; for i:=0 to 5 do //5회 전송 하자. begin dmSocket.DirectSendPacket(stDeviceID,'R','FW10 10' + DeviceType + FillZeroNumber(dmICU300FirmwareData.FileSize,6) + ' ' + FillZeroNumber(dmICU300FirmwareData.PacketSize,4),True,1); MyDelay(500); end; nFirmwareIndex := 0; ProgressBar1.MaxValue := dmICU300FirmwareData.FileSize; ProgressBar1.Progress := 0; while true do begin if dmICU300FirmwareData.FileSize < nFirmwareIndex * dmICU300FirmwareData.PacketSize then break; dmICU300FirmwareData.CurrentIndex := nFirmwareIndex; dmICU300FirmwareData.SendMsgNo := 0; dmICU300FirmwareData.SendICU300FirmWarePacket('R','FW10 22' + DeviceType + FillZeroNumber(nFirmwareIndex,5),'K1'); nFirmwareIndex := nFirmwareIndex + 1; ProgressBar1.Progress := dmICU300FirmwareData.PacketSize * nFirmwareIndex; MyDelay(strtoint(ed_Icu300broadTime.text)); Application.ProcessMessages; end; for i:=0 to 5 do //5회 전송 하자. begin dmSocket.DirectSendPacket(stDeviceID,'R','FW10 18' + DeviceType + '00100',True,1); MyDelay(500); end; end; function TfmICUGCU300FirmwareDownload.GetFirmWarePath: string; var stPath : string; i : integer; begin if DeviceType = 'ICU300' then begin stPath := '1'; //확장기 쪽으로만 전송 한다. end else if DeviceType = 'SCR302' then begin if Group_811.ItemChecked[0] = True then stPath := '3' //확장기와 카드리더 두군데 전송한다. else stPath := '1'; //확장기쪽으로만 전송한다. for i:=1 to 63 do begin if Group_811.ItemChecked[i] = True then stPath := stPath + '2' else stPath := stPath + '0'; end; end; result := stPath; end; function TfmICUGCU300FirmwareDownload.GetFirmWareSelectDevice: string; var stSelectDevice : string; i : integer; begin stSelectDevice := ''; if DeviceType = 'ICU300' then begin for i:=0 to 63 do begin if Group_811.ItemChecked[i] = True then stSelectDevice := stSelectDevice + '1' else stSelectDevice := stSelectDevice + '0'; end; end else if DeviceType = 'SCR302' then begin stSelectDevice := '011111111'; //8개 리더 모두 선택 하자. end; result := stSelectDevice; end; procedure TfmICUGCU300FirmwareDownload.FormCreate(Sender: TObject); begin FirmwareDownLoadList_GCU300 := TStringList.Create; FirmwareDownLoadList_ICU300 := TStringList.Create; end; procedure TfmICUGCU300FirmwareDownload.Clear_FirmwareDownLoadList; var i : integer; begin GridInit(sg_Icu300FirmwareDownload,3); if FirmwareDownLoadList_GCU300.Count > 0 then begin for i := FirmwareDownLoadList_GCU300.Count - 1 downto 0 do begin TICU300FirmwareProcess(FirmwareDownLoadList_GCU300.Objects[i]).Free; end; FirmwareDownLoadList_GCU300.Clear; end; if FirmwareDownLoadList_ICU300.Count > 0 then begin for i := FirmwareDownLoadList_ICU300.Count - 1 downto 0 do begin TICU300FirmwareProcess(FirmwareDownLoadList_ICU300.Objects[i]).Free; end; FirmwareDownLoadList_ICU300.Clear; end; end; procedure TfmICUGCU300FirmwareDownload.GCUICU300HexSendPacketEvent( Sender: TObject; aSendHexData, aViewHexData: string); begin dmSocket.HexSendPacketEvent(aSendHexData); end; procedure TfmICUGCU300FirmwareDownload.StringGrid_Change( aList: TAdvStringGrid; aEcuID, aNo: string; aMaxSize, aCurPosition: integer); var stFirmwareID : string; i : integer; stState : string; begin stFirmwareID := aEcuID + aNo; if aCurPosition = 0 then stState := 'Firmware 수신중' else if aMaxSize = aCurPosition then stState := '완료' else stState := inttostr(aCurPosition) + ' / ' + inttostr(aMaxSize); for i := 1 to aList.RowCount - 1 do begin if aList.Cells[3,i] = stFirmwareID then begin aList.Cells[2,i] := stState ; Exit; end; end; if aList.RowCount = 2 then begin if aList.Cells[3,1] = '' then //처음 Add 되는 경우 begin aList.Cells[0,1] := aEcuID; aList.Cells[1,1] := aNo; aList.Cells[2,1] := stState ; aList.Cells[3,1] := stFirmwareID; Exit; end; end; aList.RowCount := aList.RowCount + 1; //한칸 추가 하자. aList.Cells[0,aList.RowCount - 1] := aEcuID; aList.Cells[1,aList.RowCount - 1] := aNo; aList.Cells[2,aList.RowCount - 1] := stState ; aList.Cells[3,aList.RowCount - 1] := stFirmwareID; end; function TfmICUGCU300FirmwareDownload.Check_GCU300ICU300FirmwareComplete: Boolean; var i : integer; bComplete : Boolean; begin bComplete := True; if FirmwareDownLoadList_GCU300.Count > 0 then begin for i := FirmwareDownLoadList_GCU300.Count - 1 downto 0 do begin if TICU300FirmwareProcess(FirmwareDownLoadList_GCU300.Objects[i]).MaxSize <> TICU300FirmwareProcess(FirmwareDownLoadList_GCU300.Objects[i]).CurrentPosition then bComplete := False; end; end; if FirmwareDownLoadList_ICU300.Count > 0 then begin for i := FirmwareDownLoadList_ICU300.Count - 1 downto 0 do begin if TICU300FirmwareProcess(FirmwareDownLoadList_ICU300.Objects[i]).MaxSize <> TICU300FirmwareProcess(FirmwareDownLoadList_ICU300.Objects[i]).CurrentPosition then bComplete := False; end; end; if bComplete then begin btnFirmwareUpdate.Enabled := True; btnClose.Enabled := True; end; end; procedure TfmICUGCU300FirmwareDownload.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; fmMain.L_bICU300FirmWareSendShow := False; end; procedure TfmICUGCU300FirmwareDownload.ICU300FirmWareProcess(aECUID, aRealPacketData: string); var stIndex : string; stDeviceType : string; stNo : string; nIndex : integer; oICU300FirmwareProcess : TICU300FirmwareProcess; begin stIndex := copy(aRealPacketData,6,5); stDeviceType := copy(aRealPacketData,12,6); stNo := copy(aRealPacketData,19,2); //showmessage(stIndex); if Not isDigit(stIndex) then Exit; dmICU300FirmwareData.CurrentIndex := strtoint(stIndex); //dmICU300FirmwareData.SendMsgNo := Send_MsgNo; dmICU300FirmwareData.SendICU300FirmWarePacket('R','FW10 22' + dmICU300FirmwareData.DeviceType + FillZeroNumber(strtoint(stIndex),5),'K1'); if stDeviceType = 'SCR302' then begin nIndex := FirmwareDownLoadList_GCU300.IndexOf(aEcuID+stNo); if nIndex < 0 then begin oICU300FirmwareProcess := TICU300FirmwareProcess.Create(nil); oICU300FirmwareProcess.ECUID := aEcuID; oICU300FirmwareProcess.NO := stNo; oICU300FirmwareProcess.DeviceType := stDeviceType; oICU300FirmwareProcess.MaxSize := dmICU300FirmwareData.FileSize; oICU300FirmwareProcess.CurrentPosition := strtoint(stIndex) * dmICU300FirmwareData.PacketSize; oICU300FirmwareProcess.OnMainRequestProcess := MainRequestProcessChange; FirmwareDownLoadList_GCU300.AddObject(aEcuID+stNo,oICU300FirmwareProcess); StringGrid_Change(sg_Icu300FirmwareDownload,aEcuID,stNo,dmICU300FirmwareData.FileSize,oICU300FirmwareProcess.CurrentPosition); end else begin TICU300FirmwareProcess(FirmwareDownLoadList_GCU300.Objects[nIndex]).CurrentPosition := strtoint(stIndex) * dmICU300FirmwareData.PacketSize; end; end else if stDeviceType = 'ICU300' then begin nIndex := FirmwareDownLoadList_ICU300.IndexOf(aEcuID+stNo); if nIndex < 0 then begin oICU300FirmwareProcess := TICU300FirmwareProcess.Create(nil); oICU300FirmwareProcess.ECUID := aEcuID; oICU300FirmwareProcess.NO := stNo; oICU300FirmwareProcess.DeviceType := stDeviceType; oICU300FirmwareProcess.MaxSize := dmICU300FirmwareData.FileSize; oICU300FirmwareProcess.CurrentPosition := strtoint(stIndex) * dmICU300FirmwareData.PacketSize; oICU300FirmwareProcess.OnMainRequestProcess := MainRequestProcessChange; FirmwareDownLoadList_ICU300.AddObject(aEcuID+stNo,oICU300FirmwareProcess); StringGrid_Change(sg_Icu300FirmwareDownload,aEcuID,stNo,dmICU300FirmwareData.FileSize,oICU300FirmwareProcess.CurrentPosition); end else begin TICU300FirmwareProcess(FirmwareDownLoadList_ICU300.Objects[nIndex]).CurrentPosition := strtoint(stIndex) * dmICU300FirmwareData.PacketSize; end; end; end; procedure TfmICUGCU300FirmwareDownload.MainRequestProcessChange( Sender: TObject; aEcuID, aNo, aDeviceType: string; aMaxSize, aCurPosition: integer); begin if aDeviceType = 'ICU300' then StringGrid_Change(sg_Icu300FirmwareDownload,aEcuID,aNo,aMaxSize,aCurPosition) else if aDeviceType = 'SCR302' then StringGrid_Change(sg_Icu300FirmwareDownload,aEcuID,aNo,aMaxSize,aCurPosition); end; procedure TfmICUGCU300FirmwareDownload.GCU300_ICU300FirmwareDownloadState( aEcuID, aRealPacket: string); var stFirmwarestate : string; stDeviceType : string; stDeviceNumber : string; nIndex : integer; oICU300FirmwareProcess : TICU300FirmwareProcess; begin stFirmwarestate := copy(aRealPacket,5,4); stDeviceType := copy(aRealPacket,10,6); stDeviceNumber := copy(aRealPacket,17,2); if stFirmwarestate = 'fCls' then begin if stDeviceType = 'SCR302' then begin nIndex := FirmwareDownLoadList_GCU300.IndexOf(aEcuID+stDeviceNumber); if nIndex < 0 then begin oICU300FirmwareProcess := TICU300FirmwareProcess.Create(nil); oICU300FirmwareProcess.ECUID := aEcuID; oICU300FirmwareProcess.NO := stDeviceNumber; oICU300FirmwareProcess.DeviceType := stDeviceType; oICU300FirmwareProcess.MaxSize := dmICU300FirmwareData.FileSize; oICU300FirmwareProcess.CurrentPosition := 0; oICU300FirmwareProcess.OnMainRequestProcess := MainRequestProcessChange; FirmwareDownLoadList_GCU300.AddObject(aEcuID+stDeviceNumber,oICU300FirmwareProcess); StringGrid_Change(sg_Icu300FirmwareDownload,aEcuID,stDeviceNumber,dmICU300FirmwareData.FileSize,oICU300FirmwareProcess.CurrentPosition); end; end else if stDeviceType = 'ICU300' then begin nIndex := FirmwareDownLoadList_ICU300.IndexOf(aEcuID+stDeviceNumber); if nIndex < 0 then begin oICU300FirmwareProcess := TICU300FirmwareProcess.Create(nil); oICU300FirmwareProcess.ECUID := aEcuID; oICU300FirmwareProcess.NO := stDeviceNumber; oICU300FirmwareProcess.DeviceType := stDeviceType; oICU300FirmwareProcess.MaxSize := dmICU300FirmwareData.FileSize; oICU300FirmwareProcess.CurrentPosition := 0; oICU300FirmwareProcess.OnMainRequestProcess := MainRequestProcessChange; FirmwareDownLoadList_ICU300.AddObject(aEcuID+stDeviceNumber,oICU300FirmwareProcess); StringGrid_Change(sg_Icu300FirmwareDownload,aEcuID,stDeviceNumber,dmICU300FirmwareData.FileSize,oICU300FirmwareProcess.CurrentPosition); end; end; end else if stFirmwarestate = 'Main' then begin if stDeviceType = 'SCR302' then begin nIndex := FirmwareDownLoadList_GCU300.IndexOf(aEcuID+stDeviceNumber); if nIndex > -1 then begin TICU300FirmwareProcess(FirmwareDownLoadList_GCU300.Objects[nIndex]).CurrentPosition := dmICU300FirmwareData.FileSize; end; end else if stDeviceType = 'ICU300' then begin nIndex := FirmwareDownLoadList_ICU300.IndexOf(aEcuID+stDeviceNumber); if nIndex > -1 then begin TICU300FirmwareProcess(FirmwareDownLoadList_ICU300.Objects[nIndex]).CurrentPosition := dmICU300FirmwareData.FileSize; end; end; Check_GCU300ICU300FirmwareComplete; end; end; end.
unit rtclib; ///////////////////////////////////////////////////////////////////////////// // // library // rtclib // // description // support scanlab's rtc4,5 // // author // hcchoi@koses.co.kr // // history // v1.0 2013.9.16 hcchoi first release // // class diagram // // Rtc // /|\ // | // | // --------- // | | // Rtc4 Rtc5 // // comment // 사용자는 원하는 Rtc4,5 인스턴스를 만들어 (CreateRtc4/5) 사용을 한다. // ///////////////////////////////////////////////////////////////////////////// interface uses Classes, SysUtils, Windows; type TRtc = class public function initialize(kfactor: Single, ACtbFileName:PChar, laserMode:Integer, activeLevel:Boolean): Boolean; virtual; stdcall; abstract; /// control cmd function ctlCtbFile(ACtbFileName:PChar): Boolean; virtual; stdcall; abstract; function ctlKFactor(kfactor: Single): Single; virtual; stdcall; abstract; function ctlManualOn(): Boolean; virtual; stdcall; abstract; function ctlManualOff(): Boolean; virtual; stdcall; abstract; function ctlMove(x.y: Single): Boolean; virtual; stdcall; abstract; function ctlMatrix(AXForm:TXForm): Boolean; virtual; stdcall; abstract; function ctlTiming(frequency, pulsewidth: Single): Boolean; virtual; stdcall; abstract; function ctlDelay(ondelay, offdelay, jump, mark, polygon: Single): Boolean; virtual; stdcall; abstract; function ctlSpeed(jump, mark: Single): Boolean; virtual; stdcall; abstract; function ctlAbort(): Boolean; virtual; stdcall; abstract; function ctlReset(): Boolean; virtual; stdcall; abstract; function ctlLaserMode(laserMode:Integer): Single; virtual; stdcall; abstract; /// queriable control cmd function getStatus(statuscode: Integer): Boolean; virtual; stdcall; abstract; function getErrMsg(errorCode: Integer): PChar; virtual; stdcall; abstract; function getSampleCount(): Integer; virtual; stdcall; abstract; function getSample(ch, index: Integer): Integer; virtual; stdcall; abstract; function waitBusy(): Boolean; virtual; stdcall; abstract; /// list cmd function listBegin(): Boolean; virtual; stdcall; abstract; /// double-buffered list internally function listTiming(frequency, pulsewidth: Single): Boolean; virtual; stdcall; abstract; function listDelay(ondelay, offdelay, jump, mark, polygon: Single): Boolean; virtual; stdcall; abstract; function listSpeed(jump, mark: Single): Boolean; virtual; stdcall; abstract; function listDelay(msec: Single): Boolean; virtual; stdcall; abstract; function listOn(msec: Single): Boolean; virtual; stdcall; abstract; function listJump(x, y: Single): Boolean; virtual; stdcall; abstract; function listMark(x, y: Single): Boolean; virtual; stdcall; abstract; function listArc(cx, cy, angle: Single): Boolean; virtual; stdcall; abstract; function listMatrix(AXForm: TXForm): Boolean; virtual; stdcall; abstract; function listWobbel(amplitude, frequency: Single): Boolean; virtual; stdcall; abstract; function listEnd(): Boolean; virtual; stdcall; abstract; function listExecute(): Boolean; virtual; stdcall; abstract; /// blocked until done end; function CreateRtc4(index:Integer, kfactor:Single): TRtc; stdcall; external 'rtclib.dll'; function CreateRtc5(index:Integer, kfactor:Single): TRtc; stdcall; external 'rtclib.dll'; procedure DestroyRtc(ARtc : TRtc); stdcall; external 'rtclib.dll'; implementation end.
{Realice un programa que lea y almacene el salario de los empleados de una empresa de turismo (a lo sumo 300 empleados). La carga finaliza cuando se lea el salario 0 (que no debe procesarse) o cuando se completa el vector. Una vez finalizada la carga de datos se pide: a. Realizar un módulo que incremente el salario de cada empleado en un 15%. Para ello, implemente un módulo que reciba como parámetro un valor real X, el vector de valores reales y su dimensión lógica y retorne el mismo vector en el cual cada elemento fue multiplicado por el valor X. b.Realizar un modulo que muestre en pantalla el sueldo promedio de los empleados de la empresa. } program ejercicio8; const dimF = 300; type vsalario = array[1..dimF] of Real; procedure cargarVector(var v: vsalario; var dimL: Integer); var num: Real; begin write('Ingrese numero: '); readln(num); while (dimL < dimF) and (num <> 0) do begin dimL:= dimL + 1; v[dimL]:= num; write('Ingrese un numero: '); readln(num); end; end; procedure aumentoSalario(var v:vsalario; dimL:Integer; valorX:Integer); var i: Integer; porce: Real; begin for i := 1 to dimL do begin porce:= v[i] * 0.15; v[i]:= (v[i] * valorX) + porce; end; end; function promedio(v:vsalario; dimL:Integer): real; var i: Integer; suma: Real; begin suma:=0; for i := 1 to dimL do suma:= suma + v[i]; promedio:= suma / dimF; end; procedure imprimirVector(v:vsalario; dimL:Integer); var i: Integer; begin for i := 1 to dimL do begin writeln(v[i]); end; end; var v: vsalario; dimL,valorX: Integer; begin dimL:= 0; valorX:= 0; cargarVector(v,dimL); write('Ingrese un valor X: '); readln(valorX); aumentoSalario(v,dimL,valorX); writeln('##################'); imprimirVector(v,dimL); writeln('El promedio de los salarios es: ', promedio(v,dimL)); readln(); end.
unit nsLangToContextMap; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Diction" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Diction/nsLangToContextMap.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Встроенные продукты::Diction::Diction::Diction$Unit::TnsLangToContextMap // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3CacheableBase, l3TreeInterfaces, bsTypes {$If defined(Nemesis)} , nscNewInterfaces {$IfEnd} //Nemesis {$If defined(Nemesis)} , InscContextFilterStateList {$IfEnd} //Nemesis , nsLangList ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsLangToContextMap = class(Tl3CacheableBase, Il3ContextFilterNotifier) private // private fields f_Langs : TnsLangList; f_Contexts : TInscContextFilterStateList; f_NotifySource : Il3ContextFilterNotifySource; private // private methods function Add(aLang: TbsLanguage; const aContextState: InscContextFilterState): Integer; protected // property methods function pm_GetByLang(aLang: TbsLanguage): InscContextFilterState; virtual; procedure pm_SetByLang(aLang: TbsLanguage; const aValue: InscContextFilterState); virtual; protected // realized methods procedure RequestReapply; {* Желательно переприменить фильтр. } procedure RequestClearAndTurnOff; {* Дерево выключило на себе фильтр. } procedure RequestCheckValid; {* Дерево поменялось - нужно проверить валидность фильтра. } protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // public methods constructor Create(const aNotifySource: Il3ContextFilterNotifySource); reintroduce; public // public properties property ByLang[aLang: TbsLanguage]: InscContextFilterState read pm_GetByLang write pm_SetByLang; default; end;//TnsLangToContextMap {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses SysUtils {$If defined(Nemesis)} , nscContextFilterState {$IfEnd} //Nemesis ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsLangToContextMap function TnsLangToContextMap.pm_GetByLang(aLang: TbsLanguage): InscContextFilterState; //#UC START# *490844030320_490837B901D4get_var* var l_Index : Integer; //#UC END# *490844030320_490837B901D4get_var* begin //#UC START# *490844030320_490837B901D4get_impl* l_Index := f_Langs.IndexOf(aLang); if l_Index = -1 then l_Index := Add(aLang, TnscContextFilterState.Make(False, nil, 0)); Result := f_Contexts[l_Index]; //#UC END# *490844030320_490837B901D4get_impl* end;//TnsLangToContextMap.pm_GetByLang procedure TnsLangToContextMap.pm_SetByLang(aLang: TbsLanguage; const aValue: InscContextFilterState); //#UC START# *490844030320_490837B901D4set_var* var l_Index : Integer; //#UC END# *490844030320_490837B901D4set_var* begin //#UC START# *490844030320_490837B901D4set_impl* l_Index := f_Langs.IndexOf(aLang); if l_Index = -1 then Add(aLang, aValue) else f_Contexts[l_Index] := aValue; //#UC END# *490844030320_490837B901D4set_impl* end;//TnsLangToContextMap.pm_SetByLang constructor TnsLangToContextMap.Create(const aNotifySource: Il3ContextFilterNotifySource); //#UC START# *490843AA003A_490837B901D4_var* //#UC END# *490843AA003A_490837B901D4_var* begin //#UC START# *490843AA003A_490837B901D4_impl* inherited Create; f_Langs := TnsLangList.Create; f_Contexts := TInscContextFilterStateList.Make; f_NotifySource := aNotifySource; if Assigned(f_NotifySource) then f_NotifySource.SubscribeToContextFilter(Self); //#UC END# *490843AA003A_490837B901D4_impl* end;//TnsLangToContextMap.Create function TnsLangToContextMap.Add(aLang: TbsLanguage; const aContextState: InscContextFilterState): Integer; //#UC START# *490844660228_490837B901D4_var* //#UC END# *490844660228_490837B901D4_var* begin //#UC START# *490844660228_490837B901D4_impl* Result := f_Langs.IndexOf(aLang); if Result = -1 then begin Result := f_Langs.Add(aLang); f_Contexts.Add(aContextState); end;//if f_Langs.IndexOf(aLang) = -1 then //#UC END# *490844660228_490837B901D4_impl* end;//TnsLangToContextMap.Add procedure TnsLangToContextMap.RequestReapply; //#UC START# *477250FC0040_490837B901D4_var* //#UC END# *477250FC0040_490837B901D4_var* begin //#UC START# *477250FC0040_490837B901D4_impl* // DoNothing //#UC END# *477250FC0040_490837B901D4_impl* end;//TnsLangToContextMap.RequestReapply procedure TnsLangToContextMap.RequestClearAndTurnOff; //#UC START# *4772510D0043_490837B901D4_var* var l_IDX: Integer; //#UC END# *4772510D0043_490837B901D4_var* begin //#UC START# *4772510D0043_490837B901D4_impl* for l_IDX := 0 to f_Contexts.Count - 1 do if Assigned(f_Contexts.Items[l_IDX]) then //with InscContextFilterState(f_Contexts.Items[l_IDX]) do f_Contexts.Items[l_IDX] := TnscContextFilterState.Make(False, nil, 0); //#UC END# *4772510D0043_490837B901D4_impl* end;//TnsLangToContextMap.RequestClearAndTurnOff procedure TnsLangToContextMap.RequestCheckValid; //#UC START# *4772511D0316_490837B901D4_var* //#UC END# *4772511D0316_490837B901D4_var* begin //#UC START# *4772511D0316_490837B901D4_impl* // DoNothing //#UC END# *4772511D0316_490837B901D4_impl* end;//TnsLangToContextMap.RequestCheckValid procedure TnsLangToContextMap.Cleanup; //#UC START# *479731C50290_490837B901D4_var* //#UC END# *479731C50290_490837B901D4_var* begin //#UC START# *479731C50290_490837B901D4_impl* if Assigned(f_NotifySource) then f_NotifySource.UnSubscribeFromContextFilter(Self); f_NotifySource := nil; FreeAndNil(f_Langs); FreeAndNil(f_Contexts); inherited; //#UC END# *479731C50290_490837B901D4_impl* end;//TnsLangToContextMap.Cleanup {$IfEnd} //not Admin AND not Monitorings end.
unit DocumentPrintAndExportFontSizeSettingRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "DocumentPrintAndExportFontSizeSettingRes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: UtilityPack::Class Shared Delphi Sand Box$UC::Document::View::Document::DocumentPrintAndExportFontSizeSettingRes // // Ресурсы для настройки "Использовать для экспорта и печати следующий размер шрифта" // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {$Include w:\common\components\SandBox\VCM\sbDefine.inc} interface uses l3Interfaces, afwInterfaces, l3CProtoObject, l3StringIDEx ; type PrintAndExportFontSizeEnum = ( {* Ключи для настройки "Использовать для экспорта и печати следующий размер шрифта" } KEY_PrintAndExportFontSize_pef8 // 8 , KEY_PrintAndExportFontSize_pef9 // 9 , KEY_PrintAndExportFontSize_pef10 // 10 , KEY_PrintAndExportFontSize_pef11 // 11 , KEY_PrintAndExportFontSize_pef12 // 12 , KEY_PrintAndExportFontSize_pef14 // 14 , KEY_PrintAndExportFontSize_pef16 // 16 );//PrintAndExportFontSizeEnum const { PrintAndExportFontSizeKey } pi_Document_PrintAndExportFontSize = 'Документ/Использовать для экспорта и печати следующий размер шрифта'; { Идентификатор настройки "Использовать для экспорта и печати следующий размер шрифта" } dv_Document_PrintAndExportFontSize = 0; { Значение по-умолчанию настройки "Использовать для экспорта и печати следующий размер шрифта" } var { Локализуемые строки PrintAndExportFontSizeValues } str_PrintAndExportFontSize_pef8 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef8'; rValue : '8'); { 8 } str_PrintAndExportFontSize_pef9 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef9'; rValue : '9'); { 9 } str_PrintAndExportFontSize_pef10 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef10'; rValue : '10'); { 10 } str_PrintAndExportFontSize_pef11 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef11'; rValue : '11'); { 11 } str_PrintAndExportFontSize_pef12 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef12'; rValue : '12'); { 12 } str_PrintAndExportFontSize_pef14 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef14'; rValue : '14'); { 14 } str_PrintAndExportFontSize_pef16 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef16'; rValue : '16'); { 16 } const { Карта преобразования локализованных строк PrintAndExportFontSizeValues } PrintAndExportFontSizeValuesMap : array [PrintAndExportFontSizeEnum] of Pl3StringIDEx = ( @str_PrintAndExportFontSize_pef8 , @str_PrintAndExportFontSize_pef9 , @str_PrintAndExportFontSize_pef10 , @str_PrintAndExportFontSize_pef11 , @str_PrintAndExportFontSize_pef12 , @str_PrintAndExportFontSize_pef14 , @str_PrintAndExportFontSize_pef16 );//PrintAndExportFontSizeValuesMap type PrintAndExportFontSizeValuesMapHelper = {final} class {* Утилитный класс для преобразования значений PrintAndExportFontSizeValuesMap } public // public methods class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): PrintAndExportFontSizeEnum; {* Преобразование строкового значения к порядковому } end;//PrintAndExportFontSizeValuesMapHelper TPrintAndExportFontSizeValuesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для PrintAndExportFontSizeValuesMap } protected // realized methods function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TPrintAndExportFontSizeValuesMapImplPrim } end;//TPrintAndExportFontSizeValuesMapImplPrim TPrintAndExportFontSizeValuesMapImpl = {final} class(TPrintAndExportFontSizeValuesMapImplPrim) {* Класс для реализации мапы для PrintAndExportFontSizeValuesMap } public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TPrintAndExportFontSizeValuesMapImpl } end;//TPrintAndExportFontSizeValuesMapImpl var { Локализуемые строки PrintAndExportFontSizeName } str_PrintAndExportFontSize : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize'; rValue : 'Использовать для экспорта и печати следующий размер шрифта'); { Использовать для экспорта и печати следующий размер шрифта } implementation uses l3MessageID, l3String, SysUtils, l3Base ; // start class PrintAndExportFontSizeValuesMapHelper class procedure PrintAndExportFontSizeValuesMapHelper.FillStrings(const aStrings: IafwStrings); var l_Index: PrintAndExportFontSizeEnum; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(PrintAndExportFontSizeValuesMap[l_Index].AsCStr); end;//PrintAndExportFontSizeValuesMapHelper.FillStrings class function PrintAndExportFontSizeValuesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): PrintAndExportFontSizeEnum; var l_Index: PrintAndExportFontSizeEnum; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, PrintAndExportFontSizeValuesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "PrintAndExportFontSizeValuesMap"', [l3Str(aDisplayName)]); end;//PrintAndExportFontSizeValuesMapHelper.DisplayNameToValue // start class TPrintAndExportFontSizeValuesMapImplPrim class function TPrintAndExportFontSizeValuesMapImplPrim.Make: Il3IntegerValueMap; var l_Inst : TPrintAndExportFontSizeValuesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TPrintAndExportFontSizeValuesMapImplPrim.pm_GetMapID: Tl3ValueMapID; {-} begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TPrintAndExportFontSizeValuesMapImplPrim.pm_GetMapID procedure TPrintAndExportFontSizeValuesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {-} begin PrintAndExportFontSizeValuesMapHelper.FillStrings(aList); end;//TPrintAndExportFontSizeValuesMapImplPrim.GetDisplayNames function TPrintAndExportFontSizeValuesMapImplPrim.MapSize: Integer; {-} begin Result := Ord(High(PrintAndExportFontSizeEnum)) - Ord(Low(PrintAndExportFontSizeEnum)); end;//TPrintAndExportFontSizeValuesMapImplPrim.MapSize function TPrintAndExportFontSizeValuesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} begin Result := Ord(PrintAndExportFontSizeValuesMapHelper.DisplayNameToValue(aDisplayName)); end;//TPrintAndExportFontSizeValuesMapImplPrim.DisplayNameToValue function TPrintAndExportFontSizeValuesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; {-} begin Assert(aValue >= Ord(Low(PrintAndExportFontSizeEnum))); Assert(aValue <= Ord(High(PrintAndExportFontSizeEnum))); Result := PrintAndExportFontSizeValuesMap[PrintAndExportFontSizeEnum(aValue)].AsCStr; end;//TPrintAndExportFontSizeValuesMapImplPrim.ValueToDisplayName // start class TPrintAndExportFontSizeValuesMapImpl var g_TPrintAndExportFontSizeValuesMapImpl : Pointer = nil; procedure TPrintAndExportFontSizeValuesMapImplFree; begin IUnknown(g_TPrintAndExportFontSizeValuesMapImpl) := nil; end; class function TPrintAndExportFontSizeValuesMapImpl.Make: Il3IntegerValueMap; begin if (g_TPrintAndExportFontSizeValuesMapImpl = nil) then begin l3System.AddExitProc(TPrintAndExportFontSizeValuesMapImplFree); Il3IntegerValueMap(g_TPrintAndExportFontSizeValuesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TPrintAndExportFontSizeValuesMapImpl); end; initialization // Инициализация str_PrintAndExportFontSize_pef8 str_PrintAndExportFontSize_pef8.Init; // Инициализация str_PrintAndExportFontSize_pef9 str_PrintAndExportFontSize_pef9.Init; // Инициализация str_PrintAndExportFontSize_pef10 str_PrintAndExportFontSize_pef10.Init; // Инициализация str_PrintAndExportFontSize_pef11 str_PrintAndExportFontSize_pef11.Init; // Инициализация str_PrintAndExportFontSize_pef12 str_PrintAndExportFontSize_pef12.Init; // Инициализация str_PrintAndExportFontSize_pef14 str_PrintAndExportFontSize_pef14.Init; // Инициализация str_PrintAndExportFontSize_pef16 str_PrintAndExportFontSize_pef16.Init; // Инициализация str_PrintAndExportFontSize str_PrintAndExportFontSize.Init; end.
unit kwPopFormMDIChildCount; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopFormMDIChildCount.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FormsProcessing::pop_form_MDIChildCount // // Use MDIChildCount to get the number of open MDI child forms. // MDIChildCount is meaningful only if the form is an MDI parent (that is, if the form’s FormStyle // property is set to fsMDIForm). // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses Forms, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas} TkwPopFormMDIChildCount = class(_kwFormFromStackWord_) {* Use MDIChildCount to get the number of open MDI child forms. MDIChildCount is meaningful only if the form is an MDI parent (that is, if the form’s FormStyle property is set to fsMDIForm). } protected // realized methods procedure DoForm(aForm: TForm; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopFormMDIChildCount {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopFormMDIChildCount; {$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas} // start class TkwPopFormMDIChildCount procedure TkwPopFormMDIChildCount.DoForm(aForm: TForm; const aCtx: TtfwContext); //#UC START# *4F2145550317_4E4CBBD3020F_var* //#UC END# *4F2145550317_4E4CBBD3020F_var* begin //#UC START# *4F2145550317_4E4CBBD3020F_impl* aCtx.rEngine.PushInt(aForm.MDIChildCount); //#UC END# *4F2145550317_4E4CBBD3020F_impl* end;//TkwPopFormMDIChildCount.DoForm class function TkwPopFormMDIChildCount.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:form:MDIChildCount'; end;//TkwPopFormMDIChildCount.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit gb_sound; interface uses {$IFDEF WINDOWS}windows,{$ENDIF}sound_engine; const NR10=$00; NR11=$01; NR12=$02; NR13=$03; NR14=$04; NR21=$06; NR22=$07; NR23=$08; NR24=$09; NR30=$0A; NR31=$0B; NR32=$0C; NR33=$0D; NR34=$0E; NR41=$10; NR42=$11; NR43=$12; NR44=$13; NR50=$14; NR51=$15; NR52=$16; AUD3W0=$20; AUD3W1=$21; AUD3W2=$22; AUD3W3=$23; AUD3W4=$24; AUD3W5=$25; AUD3W6=$26; AUD3W7=$27; AUD3W8=$28; AUD3W9=$29; AUD3WA=$2A; AUD3WB=$2B; AUD3WC=$2C; AUD3WD=$2D; AUD3WE=$2E; AUD3WF=$2F; LEFT=1; RIGHT=2; MAX_FREQUENCIES=2048; FIXED_POINT=16; // Represents wave duties of 12.5%, 25%, 50% and 75% wave_duty_table:array[0..3] of single=(8.0,4.0,2.0,1.33); type tipo_SOUND=record // Common */ on_:byte; channel:byte; length:integer; pos:integer; period:dword; count:integer; mode:shortint; // Mode 1, 2, 3 */ duty:shortint; // Mode 1, 2, 4 */ env_value:integer; env_direction:shortint; env_length:integer; env_count:integer; signal:shortint; // Mode 1 */ frequency:integer; swp_shift:integer; swp_direction:integer; swp_time:integer; swp_count:integer; // Mode 3 */ level:shortint; offset:byte; dutycount:dword; // Mode 4 */ ply_step:integer; ply_value:smallint; end; tipo_SOUNDC=record on_:byte; vol_left:byte; vol_right:byte; mode1_left:byte; mode1_right:byte; mode2_left:byte; mode2_right:byte; mode3_left:byte; mode3_right:byte; mode4_left:byte; mode4_right:byte; end; gb_sound_tipo=record env_length_table:array[0..7] of integer; swp_time_table:array[0..7] of integer; period_table:array[0..MAX_FREQUENCIES-1] of dword; period_mode3_table:array[0..MAX_FREQUENCIES-1] of dword; period_mode4_table:array[0..7,0..15] of dword; length_table:array[0..63] of dword; length_mode3_table:array[0..$ff] of dword; snd_1:tipo_sound; snd_2:tipo_sound; snd_3:tipo_sound; snd_4:tipo_sound; snd_control:tipo_soundc; snd_regs:array[0..$30-1] of byte; tsample:byte; end; pgb_sound_tipo=^gb_sound_tipo; var gb_snd:pgb_sound_tipo; function gb_sound_r(offset:byte):byte; procedure gb_sound_w(offset,valor:byte); function gb_wave_r(offset:byte):byte; procedure gb_wave_w(offset,valor:byte); procedure gameboy_sound_ini; procedure gameboy_sound_close; procedure gameboy_sound_reset; procedure gameboy_sound_update; implementation function gb_wave_r(offset:byte):byte; begin // TODO: properly emulate scrambling of wave ram area when playback is active */ gb_wave_r:=gb_snd.snd_regs[AUD3W0+offset] or gb_snd.snd_3.on_; end; procedure gb_wave_w(offset,valor:byte); begin gb_snd.snd_regs[AUD3W0+offset]:=valor; end; function gb_sound_r(offset:byte):byte; begin case offset of NR10:gb_sound_r:=$80 or gb_snd.snd_regs[offset]; NR11:gb_sound_r:=$3F or gb_snd.snd_regs[offset]; NR12:gb_sound_r:=gb_snd.snd_regs[offset]; NR13:gb_sound_r:=$FF; NR14:gb_sound_r:=$BF or gb_snd.snd_regs[offset]; NR21:gb_sound_r:=$3f or gb_snd.snd_regs[offset]; NR22:gb_sound_r:=gb_snd.snd_regs[offset]; NR23:gb_sound_r:=$ff; NR24:gb_sound_r:=$bf or gb_snd.snd_regs[offset]; NR41:gb_sound_r:=$FF; NR42:gb_sound_r:=gb_snd.snd_regs[offset]; NR43:gb_sound_r:=gb_snd.snd_regs[offset]; NR44:gb_sound_r:=$BF or gb_snd.snd_regs[offset]; NR50:gb_sound_r:=gb_snd.snd_regs[offset]; NR51:gb_sound_r:=gb_snd.snd_regs[offset]; $05,$0a:gb_sound_r:=$FF; NR52:gb_sound_r:=$70 or gb_snd.snd_regs[offset]; else gb_sound_r:=gb_snd.snd_regs[offset]; end; end; procedure gb_sound_w_internal(offset,valor:byte); begin // Store the value */ gb_snd.snd_regs[offset]:=valor; case offset of // MODE 1 */ NR10:begin // Sweep (R/W) gb_snd.snd_1.swp_shift:= valor and $7; gb_snd.snd_1.swp_direction:=(valor and $8) shr 3; gb_snd.snd_1.swp_direction:=gb_snd.snd_1.swp_direction or (gb_snd.snd_1.swp_direction-1); gb_snd.snd_1.swp_time:=gb_snd.swp_time_table[(valor and $70) shr 4]; end; NR11:begin // Sound length/Wave pattern duty (R/W) */ gb_snd.snd_1.duty:=(valor and $C0) shr 6; gb_snd.snd_1.length:=gb_snd.length_table[valor and $3F]; end; NR12:begin // Envelope (R/W) */ gb_snd.snd_1.env_value:=valor shr 4; gb_snd.snd_1.env_direction:=(valor and $8) shr 3; gb_snd.snd_1.env_direction:=gb_snd.snd_1.env_direction or (gb_snd.snd_1.env_direction-1); gb_snd.snd_1.env_length:=gb_snd.env_length_table[valor and $7]; end; NR13:begin // Frequency lo (R/W) */ gb_snd.snd_1.frequency:=((gb_snd.snd_regs[NR14] and $7) shl 8) or gb_snd.snd_regs[NR13]; gb_snd.snd_1.period:=gb_snd.period_table[gb_snd.snd_1.frequency]; end; NR14:begin // Frequency hi / Initialize (R/W) */ gb_snd.snd_1.mode:= (valor and $40) shr 6; gb_snd.snd_1.frequency:= ((gb_snd.snd_regs[NR14] and $7) shl 8) or gb_snd.snd_regs[NR13]; gb_snd.snd_1.period:= gb_snd.period_table[gb_snd.snd_1.frequency]; if (valor and $80)<>0 then begin if (gb_snd.snd_1.on_=0) then gb_snd.snd_1.pos:=0; gb_snd.snd_1.on_:=1; gb_snd.snd_1.count:=0; gb_snd.snd_1.env_value:=gb_snd.snd_regs[NR12] shr 4; gb_snd.snd_1.env_count:=0; gb_snd.snd_1.swp_count:=0; gb_snd.snd_1.signal:=$1; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] or $1; end; end; // MODE 2 */ NR21:begin // Sound length/Wave pattern duty (R/W) */ gb_snd.snd_2.duty:=(valor and $C0) shr 6; gb_snd.snd_2.length:= gb_snd.length_table[valor and $3F]; end; NR22:begin // Envelope (R/W) gb_snd.snd_2.env_value:= valor shr 4; gb_snd.snd_2.env_direction:= (valor and $8 ) shr 3; gb_snd.snd_2.env_direction:=gb_snd.snd_2.env_direction or (gb_snd.snd_2.env_direction-1); gb_snd.snd_2.env_length:=gb_snd.env_length_table[valor and $7]; end; NR23:begin // Frequency lo (R/W) */ gb_snd.snd_2.period:=gb_snd.period_table[((gb_snd.snd_regs[NR24] and $7) shl 8) or gb_snd.snd_regs[NR23]]; end; NR24:begin // Frequency hi / Initialize (R/W) */ gb_snd.snd_2.mode:=(valor and $40) shr 6; gb_snd.snd_2.period:=gb_snd.period_table[((gb_snd.snd_regs[NR24] and $7) shl 8) or gb_snd.snd_regs[NR23]]; if (valor and $80)<>0 then begin if (gb_snd.snd_2.on_=0) then gb_snd.snd_2.pos:=0; gb_snd.snd_2.on_:=1; gb_snd.snd_2.count:=0; gb_snd.snd_2.env_value:=gb_snd.snd_regs[NR22] shr 4; gb_snd.snd_2.env_count:=0; gb_snd.snd_2.signal:=$1; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] or $2; end; end; // MODE 3 */ NR30:begin // Sound On/Off (R/W) */ gb_snd.snd_3.on_:= (valor and $80) shr 7; end; NR31:begin // Sound Length (R/W) */ gb_snd.snd_3.length:= gb_snd.length_mode3_table[valor]; end; NR32:begin // Select Output Level */ gb_snd.snd_3.level:= (valor and $60) shr 5; end; NR33:begin // Frequency lo (W) */ gb_snd.snd_3.period:= gb_snd.period_mode3_table[((gb_snd.snd_regs[NR34] and $7) shl 8) or gb_snd.snd_regs[NR33]]; end; NR34:begin // Frequency hi / Initialize (W) */ gb_snd.snd_3.mode:= (valor and $40) shr 6; gb_snd.snd_3.period:= gb_snd.period_mode3_table[((gb_snd.snd_regs[NR34] and $7) shl 8) or gb_snd.snd_regs[NR33]]; if (valor and $80)<>0 then begin if (gb_snd.snd_3.on_=0) then begin gb_snd.snd_3.pos:=0; gb_snd.snd_3.offset:=0; gb_snd.snd_3.duty:=0; end; gb_snd.snd_3.on_:=1; gb_snd.snd_3.count:=0; gb_snd.snd_3.duty:=1; gb_snd.snd_3.dutycount:=0; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] or $4; end; end; // MODE 4 */ NR41:begin // Sound Length (R/W) */ gb_snd.snd_4.length:=gb_snd.length_table[valor and $3F]; end; NR42:begin // Envelope (R/W) */ gb_snd.snd_4.env_value:=valor shr 4; gb_snd.snd_4.env_direction:=(valor and $8 ) shr 3; gb_snd.snd_4.env_direction:=gb_snd.snd_4.env_direction or (gb_snd.snd_4.env_direction-1); gb_snd.snd_4.env_length:=gb_snd.env_length_table[valor and $7]; end; NR43:begin // Polynomial Counter/Frequency */ gb_snd.snd_4.period:=gb_snd.period_mode4_table[valor and $7][(valor and $F0) shr 4]; gb_snd.snd_4.ply_step:= (valor and $8) shr 3; end; NR44:begin // Counter/Consecutive / Initialize (R/W) */ gb_snd.snd_4.mode:= (valor and $40) shr 6; if (valor and $80)<>0 then begin if (gb_snd.snd_4.on_=0) then gb_snd.snd_4.pos:=0; gb_snd.snd_4.on_:=1; gb_snd.snd_4.count:=0; gb_snd.snd_4.env_value:=gb_snd.snd_regs[NR42] shr 4; gb_snd.snd_4.env_count:=0; gb_snd.snd_4.signal:=shortint(random(256)); gb_snd.snd_4.ply_value:=$7fff; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] or $8; end; end; // CONTROL */ NR50:begin // Channel Control / On/Off / Volume (R/W) */ gb_snd.snd_control.vol_left:= valor and $7; gb_snd.snd_control.vol_right:= (valor and $70) shr 4; end; NR51:begin // Selection of Sound Output Terminal */ gb_snd.snd_control.mode1_right:= valor and $1; gb_snd.snd_control.mode1_left:= (valor and $10) shr 4; gb_snd.snd_control.mode2_right:= (valor and $2) shr 1; gb_snd.snd_control.mode2_left:= (valor and $20) shr 5; gb_snd.snd_control.mode3_right:= (valor and $4) shr 2; gb_snd.snd_control.mode3_left:= (valor and $40) shr 6; gb_snd.snd_control.mode4_right:= (valor and $8) shr 3; gb_snd.snd_control.mode4_left:= (valor and $80) shr 7; end; NR52:begin // Sound On/Off (R/W) */ // Only bit 7 is writable, writing to bits 0-3 does NOT enable or // disable sound. They are read-only gb_snd.snd_control.on_:= (valor and $80) shr 7; if (gb_snd.snd_control.on_=0) then begin gb_sound_w_internal(NR10,$80); gb_sound_w_internal(NR11,$3F); gb_sound_w_internal(NR12,$00); gb_sound_w_internal(NR13,$FE); gb_sound_w_internal(NR14,$BF); gb_sound_w_internal(NR21,$3F); gb_sound_w_internal(NR22,$00); gb_sound_w_internal(NR23,$FF); gb_sound_w_internal(NR24,$BF); gb_sound_w_internal(NR30,$7F); gb_sound_w_internal(NR31,$FF); gb_sound_w_internal(NR32,$9F); gb_sound_w_internal(NR33,$FF); gb_sound_w_internal(NR34,$BF); gb_sound_w_internal(NR41,$FF); gb_sound_w_internal(NR42,$00); gb_sound_w_internal(NR43,$00); gb_sound_w_internal(NR44,$BF); gb_sound_w_internal(NR50,$00); gb_sound_w_internal(NR51,$00); gb_snd.snd_1.on_:=0; gb_snd.snd_2.on_:=0; gb_snd.snd_3.on_:=0; gb_snd.snd_4.on_:=0; gb_snd.snd_regs[offset]:=0; end; end; end; end; procedure gb_sound_w(offset,valor:byte); begin // Only register NR52 is accessible if the sound controller is disabled if ((gb_snd.snd_control.on_=0) and (offset<>NR52)) then exit; gb_sound_w_internal(offset,valor); end; procedure gameboy_sound_close; begin if gb_snd<>nil then begin freemem(gb_snd); gb_snd:=nil; end; end; procedure gameboy_sound_ini; var i,j:integer; begin getmem(gb_snd,sizeof(gb_sound_tipo)); // Calculate the envelope and sweep tables for i:=0 to 7 do begin gb_snd.env_length_table[i]:=trunc((i*((1 shl FIXED_POINT)/64)*FREQ_BASE_AUDIO)) shr FIXED_POINT; gb_snd.swp_time_table[i]:=trunc((((i shl FIXED_POINT)/128)*FREQ_BASE_AUDIO)) shr (FIXED_POINT-1); end; // Calculate the period tables for i:=0 to (MAX_FREQUENCIES-1) do begin gb_snd.period_table[i]:=trunc(((1 shl FIXED_POINT)/(131072/(2048-i)))*FREQ_BASE_AUDIO); gb_snd.period_mode3_table[i]:=trunc(((1 shl FIXED_POINT)/(65536/(2048-i)))*FREQ_BASE_AUDIO); end; // Calculate the period table for mode 4 for i:=0 to 7 do begin for j:=0 to 15 do begin // I is the dividing ratio of frequencies // J is the shift clock frequency if i=0 then gb_snd.period_mode4_table[i,j]:=trunc(((1 shl FIXED_POINT)/(524288/0.5/(1 shl (j+1))))*FREQ_BASE_AUDIO) else gb_snd.period_mode4_table[i,j]:=trunc(((1 shl FIXED_POINT)/(524288/i/(1 shl (j+1))))*FREQ_BASE_AUDIO); end; end; // Calculate the length table for i:=0 to 63 do begin gb_snd.length_table[i]:=trunc((64-i)*((1 shl FIXED_POINT)/256)*FREQ_BASE_AUDIO) shr FIXED_POINT; end; // Calculate the length table for mode 3 for i:=0 to 255 do begin gb_snd.length_mode3_table[i]:=trunc((256-i)*((1 shl FIXED_POINT)/256)*FREQ_BASE_AUDIO) shr FIXED_POINT; end; gameboy_sound_reset; gb_snd.tsample:=init_channel; end; procedure gameboy_sound_reset; var f:byte; begin for f:=0 to $2f do gb_snd.snd_regs[f]:=0; gb_sound_w_internal(NR52,$00); end; function sshr(num:integer;fac:byte):integer; begin if num<0 then sshr:=-(abs(num) shr fac) else sshr:=num shr fac; end; procedure gameboy_sound_update; var left,right,sample,mode4_mask:integer; begin left:=0; right:=0; // Mode 1 - Wave with Envelope and Sweep */ if (gb_snd.snd_1.on_<>0) then begin sample:= gb_snd.snd_1.signal*gb_snd.snd_1.env_value; gb_snd.snd_1.pos:=gb_snd.snd_1.pos+1; if (gb_snd.snd_1.pos=(trunc(gb_snd.snd_1.period/wave_duty_table[gb_snd.snd_1.duty]) shr 16)) then begin gb_snd.snd_1.signal:=-gb_snd.snd_1.signal; end else if (gb_snd.snd_1.pos>(gb_snd.snd_1.period shr 16)) then begin gb_snd.snd_1.pos:=0; gb_snd.snd_1.signal:=-gb_snd.snd_1.signal; end; if ((gb_snd.snd_1.length<>0) and (gb_snd.snd_1.mode<>0)) then begin gb_snd.snd_1.count:=gb_snd.snd_1.count+1; if (gb_snd.snd_1.count>=gb_snd.snd_1.length) then begin gb_snd.snd_1.on_:=0; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] and $FE; end; end; if (gb_snd.snd_1.env_length<>0) then begin gb_snd.snd_1.env_count:=gb_snd.snd_1.env_count+1; if (gb_snd.snd_1.env_count>=gb_snd.snd_1.env_length) then begin gb_snd.snd_1.env_count:= 0; gb_snd.snd_1.env_value:=gb_snd.snd_1.env_value+gb_snd.snd_1.env_direction; if (gb_snd.snd_1.env_value<0) then gb_snd.snd_1.env_value:=0; if (gb_snd.snd_1.env_value>15) then gb_snd.snd_1.env_value:=15; end; end; if (gb_snd.snd_1.swp_time<>0) then begin gb_snd.snd_1.swp_count:=gb_snd.snd_1.swp_count+1; if (gb_snd.snd_1.swp_count>=gb_snd.snd_1.swp_time) then begin gb_snd.snd_1.swp_count:=0; if (gb_snd.snd_1.swp_direction>0) then begin gb_snd.snd_1.frequency:=gb_snd.snd_1.frequency-(gb_snd.snd_1.frequency div (1 shl gb_snd.snd_1.swp_shift)); if (gb_snd.snd_1.frequency<=0) then begin gb_snd.snd_1.on_:=0; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] and $FE; end; end else begin gb_snd.snd_1.frequency:=gb_snd.snd_1.frequency+(gb_snd.snd_1.frequency div (1 shl gb_snd.snd_1.swp_shift)); if (gb_snd.snd_1.frequency>=MAX_FREQUENCIES) then begin gb_snd.snd_1.frequency:= MAX_FREQUENCIES-1; end; end; gb_snd.snd_1.period:= gb_snd.period_table[gb_snd.snd_1.frequency]; end; end; if (gb_snd.snd_control.mode1_left<>0) then left:=left+sample; if (gb_snd.snd_control.mode1_right<>0) then right:=right+sample; end; // del on1 // Mode 2 - Wave with Envelope */ if (gb_snd.snd_2.on_<>0) then begin sample:=gb_snd.snd_2.signal*gb_snd.snd_2.env_value; gb_snd.snd_2.pos:=gb_snd.snd_2.pos+1; if (gb_snd.snd_2.pos=(trunc(gb_snd.snd_2.period/wave_duty_table[gb_snd.snd_2.duty]) shr 16)) then begin gb_snd.snd_2.signal:=-gb_snd.snd_2.signal; end else if( gb_snd.snd_2.pos>(gb_snd.snd_2.period shr 16)) then begin gb_snd.snd_2.pos:=0; gb_snd.snd_2.signal:=-gb_snd.snd_2.signal; end; if ((gb_snd.snd_2.length<>0) and (gb_snd.snd_2.mode<>0)) then begin gb_snd.snd_2.count:=gb_snd.snd_2.count+1; if (gb_snd.snd_2.count>=gb_snd.snd_2.length) then begin gb_snd.snd_2.on_:=0; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] and $FD; end; end; if (gb_snd.snd_2.env_length<>0) then begin gb_snd.snd_2.env_count:=gb_snd.snd_2.env_count+1; if (gb_snd.snd_2.env_count>=gb_snd.snd_2.env_length) then begin gb_snd.snd_2.env_count:=0; gb_snd.snd_2.env_value:=gb_snd.snd_2.env_value+gb_snd.snd_2.env_direction; if (gb_snd.snd_2.env_value<0) then gb_snd.snd_2.env_value:=0; if (gb_snd.snd_2.env_value>15) then gb_snd.snd_2.env_value:=15; end; end; if (gb_snd.snd_control.mode2_left<>0) then left:=left+sample; if (gb_snd.snd_control.mode2_right<>0) then right:=right+sample; end; // Mode 3 - Wave patterns from WaveRAM */ if (gb_snd.snd_3.on_<>0) then begin // NOTE: This is extremely close, but not quite right. // The problem is for GB frequencies above 2000 the frequency gets // clipped. This is caused because gb_snd.snd_3.pos is never 0 at the test. sample:=gb_snd.snd_regs[AUD3W0+(gb_snd.snd_3.offset div 2)]; if ((gb_snd.snd_3.offset mod 2)=0) then sample:=sample shr 4; sample:=(sample and $f)-8; if (gb_snd.snd_3.level<>0) then sample:=sshr(sample,(gb_snd.snd_3.level-1)) else sample:=0; gb_snd.snd_3.pos:=gb_snd.snd_3.pos+1; if (gb_snd.snd_3.pos>=(dword(gb_snd.snd_3.period shr 21)+gb_snd.snd_3.duty)) then begin gb_snd.snd_3.pos:=0; if (gb_snd.snd_3.dutycount=(dword(gb_snd.snd_3.period shr 16) mod 32)) then begin gb_snd.snd_3.duty:=gb_snd.snd_3.duty-1; end; gb_snd.snd_3.dutycount:=gb_snd.snd_3.dutycount+1; gb_snd.snd_3.offset:=gb_snd.snd_3.offset+1; if (gb_snd.snd_3.offset>31) then begin gb_snd.snd_3.offset:=0; gb_snd.snd_3.duty:=1; gb_snd.snd_3.dutycount:=0; end; end; if ((gb_snd.snd_3.length<>0) and (gb_snd.snd_3.mode<>0)) then begin gb_snd.snd_3.count:=gb_snd.snd_3.count+1; if (gb_snd.snd_3.count>=gb_snd.snd_3.length ) then begin gb_snd.snd_3.on_:=0; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] and $fb; end; end; if (gb_snd.snd_control.mode3_left<>0) then left:=left+sample; if (gb_snd.snd_control.mode3_right<>0) then right:=right+sample; end; // Mode 4 - Noise with Envelope */ if (gb_snd.snd_4.on_<>0) then begin // Similar problem to Mode 3, we seem to miss some notes */ sample:=gb_snd.snd_4.signal and gb_snd.snd_4.env_value; gb_snd.snd_4.pos:=gb_snd.snd_4.pos+1; if (gb_snd.snd_4.pos=(gb_snd.snd_4.period shr 17)) then begin // Using a Polynomial Counter (aka Linear Feedback Shift Register) // Mode 4 has a 7 bit and 15 bit counter so we need to shift the // bits around accordingly if gb_snd.snd_4.ply_step<>0 then mode4_mask:=(((gb_snd.snd_4.ply_value and $2) div 2) xor (gb_snd.snd_4.ply_value and $1)) shl 6 else mode4_mask:=(((gb_snd.snd_4.ply_value and $2) div 2) xor (gb_snd.snd_4.ply_value and $1)) shl 14; gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value div 2; gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value or mode4_mask; if gb_snd.snd_4.ply_step<>0 then gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value and $7f else gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value and $7fff; gb_snd.snd_4.signal:=shortint(gb_snd.snd_4.ply_value); end else if (gb_snd.snd_4.pos>(gb_snd.snd_4.period shr 16)) then begin gb_snd.snd_4.pos:=0; if gb_snd.snd_4.ply_step<>0 then mode4_mask:=(((gb_snd.snd_4.ply_value and $2) div 2) xor (gb_snd.snd_4.ply_value and $1)) shl 6 else mode4_mask:=(((gb_snd.snd_4.ply_value and $2) div 2) xor (gb_snd.snd_4.ply_value and $1)) shl 14; gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value div 2; gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value or mode4_mask; if gb_snd.snd_4.ply_step<>0 then gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value and $7f else gb_snd.snd_4.ply_value:=gb_snd.snd_4.ply_value and $7fff; gb_snd.snd_4.signal:=shortint(gb_snd.snd_4.ply_value); end; if ((gb_snd.snd_4.length<>0) and (gb_snd.snd_4.mode<>0)) then begin gb_snd.snd_4.count:=gb_snd.snd_4.count+1; if (gb_snd.snd_4.count>=gb_snd.snd_4.length) then begin gb_snd.snd_4.on_:=0; gb_snd.snd_regs[NR52]:=gb_snd.snd_regs[NR52] and $F7; end; end; if (gb_snd.snd_4.env_length<>0) then begin gb_snd.snd_4.env_count:=gb_snd.snd_4.env_count+1; if (gb_snd.snd_4.env_count>=gb_snd.snd_4.env_length) then begin gb_snd.snd_4.env_count:=0; gb_snd.snd_4.env_value:=gb_snd.snd_4.env_value+gb_snd.snd_4.env_direction; if (gb_snd.snd_4.env_value<0) then gb_snd.snd_4.env_value:=0; if (gb_snd.snd_4.env_value>15) then gb_snd.snd_4.env_value:=15; end; end; if (gb_snd.snd_control.mode4_left<>0) then left:=left+sample; if (gb_snd.snd_control.mode4_right<>0) then right:=right+sample; end; // Adjust for master volume */ left:=left*gb_snd.snd_control.vol_left; right:=right*gb_snd.snd_control.vol_right; // pump up the volume */ left:=left shl 6; right:=right shl 6; // Update the buffers */ tsample[gb_snd.tsample,sound_status.posicion_sonido]:=left; tsample[gb_snd.tsample,sound_status.posicion_sonido+1]:=right; gb_snd.snd_regs[NR52]:=(gb_snd.snd_regs[NR52] and $f0) or gb_snd.snd_1.on_ or (gb_snd.snd_2.on_ shl 1) or (gb_snd.snd_3.on_ shl 2) or (gb_snd.snd_4.on_ shl 3); end; end.