text
stringlengths
14
6.51M
unit Mensajes; interface resourcestring // mensajes de error rsInformeNoEncontrado = 'Error! Informe no Encontrado'; rsErrorFechaVencida = 'FECHA de comprobante (%s) ' + #13 + 'corresponde a periodo CERRADO (%s)' + #13 + 'Debe Modificar la fecha. Imposible Continuar'; rsClienteSinPedido = 'Cliente NO tiene pedidos pendientes'; rsCompleteDatos = 'Falta completar datos de Registro'; rsNoEliminar = 'No se puede eliminar (%s) ya que Hay (%s) que la referencian'; rsDatosIncompletos = 'Datos Incompletos. (%s)'; rsArticuloNoValido = 'Articulo %s no es valido'; rsCantidadCero = 'Cantidad no puede ser 0'; rsTasaIVA = 'No se pueden incluir en la misma factura articulos con distintas tasas de IVA'; rsPrecioNulo = 'Por favor, indique precio de venta'; rsErrorGrabacion = 'Error al grabar Factura'; rsDescuentoErroneo = 'Porcentaje de Descuento es erroneo'; implementation end.
unit SimpleDaemon; interface uses DirServerSession, Daemons; function CreateDaemon(const Session : IDirServerSession) : IDaemon; implementation uses Windows, SyncObjs; type TSimpleDaemon = class(TInterfacedObject, IDaemon) public constructor Create(const Session : IDirServerSession); destructor Destroy; override; private // IDaemon procedure SetSession(const Session : IDirServerSession); function GetName : string; function GetDescription : string; function IsRunning : boolean; procedure Run; function GetPeriod : integer; procedure SetPeriod(period : integer); function LastRun : integer; function ShowPropertiesUI : boolean; private fSession : IDirServerSession; fLock : TCriticalSection; fPeriod : integer; fRunning : boolean; fLastRun : integer; end; function CreateDaemon(const Session : IDirServerSession) : IDaemon; begin Result := TSimpleDaemon.Create(Session); end; constructor TSimpleDaemon.Create(const Session : IDirServerSession); begin inherited Create; fSession := Session; fLock := TCriticalSection.Create; fPeriod := 5000; end; destructor TSimpleDaemon.Destroy; begin fLock.Free; inherited; end; procedure TSimpleDaemon.SetSession(const Session : IDirServerSession); begin fSession := Session; end; function TSimpleDaemon.GetName : string; begin Result := 'Simple daemon'; end; function TSimpleDaemon.GetDescription : string; begin Result := 'This is a test daemon'; end; function TSimpleDaemon.IsRunning : boolean; begin fLock.Enter; try Result := fRunning; finally fLock.Leave; end; end; procedure TSimpleDaemon.Run; begin fLock.Enter; try fRunning := true; fLastRun := GetTickCount; finally fLock.Leave; end; MessageBeep(0); fLock.Enter; try fRunning := false; finally fLock.Leave; end; end; function TSimpleDaemon.GetPeriod : integer; begin Result := fPeriod; end; procedure TSimpleDaemon.SetPeriod(period : integer); begin fPeriod := period; end; function TSimpleDaemon.LastRun : integer; begin fLock.Enter; try Result := fLastRun; finally fLock.Leave; end; end; function TSimpleDaemon.ShowPropertiesUI : boolean; begin Result := false; 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.53 29/12/2004 11:01:56 CCostelloe IsMsgSinglePartMime now cleared in TIdMessage.Clear. Rev 1.52 28/11/2004 20:06:28 CCostelloe Enhancement to preserve case of MIME boundary Rev 1.51 10/26/2004 10:25:44 PM JPMugaas Updated refs. Rev 1.50 2004.10.26 9:10:00 PM czhower TIdStrings Rev 1.49 24.08.2004 18:01:44 Andreas Hausladen Added AttachmentBlocked property to TIdAttachmentFile. Rev 1.48 6/29/04 12:29:04 PM RLebeau Updated TIdMIMEBoundary.FindBoundary() to check the string length after calling Sys.Trim() before referencing the string data Rev 1.47 6/9/04 5:38:48 PM RLebeau Updated ClearHeader() to clear the MsgId and UID properties. Updated SetUseNowForDate() to support AValue being set to False Rev 1.46 16/05/2004 18:54:42 CCostelloe New TIdText/TIdAttachment processing Rev 1.45 03/05/2004 20:43:08 CCostelloe Fixed bug where QP or base64 encoded text part got header encoding incorrectly outputted as 8bit. Rev 1.44 4/25/04 1:29:34 PM RLebeau Bug fix for SaveToStream Rev 1.42 23/04/2004 20:42:18 CCostelloe Bug fixes plus support for From containing multiple addresses Rev 1.41 2004.04.18 1:39:20 PM czhower Bug fix for .NET with attachments, and several other issues found along the way. Rev 1.40 2004.04.16 11:30:56 PM czhower Size fix to IdBuffer, optimizations, and memory leaks Rev 1.39 14/03/2004 17:47:54 CCostelloe Bug fix: quoted-printable attachment encoding was changed to base64. Rev 1.38 2004.02.03 5:44:00 PM czhower Name changes Rev 1.37 2004.02.03 2:12:14 PM czhower $I path change Rev 1.36 26/01/2004 01:51:14 CCostelloe Changed implementation of supressing BCC List generation Rev 1.35 25/01/2004 21:15:42 CCostelloe Added SuppressBCCListInHeader property for use by TIdSMTP Rev 1.34 1/21/2004 1:17:14 PM JPMugaas InitComponent Rev 1.33 1/19/04 11:36:02 AM RLebeau Updated GenerateHeader() to remove support for the BBCList property Rev 1.32 16/01/2004 17:30:18 CCostelloe Added support for BinHex4.0 encoding Rev 1.31 11/01/2004 19:53:20 CCostelloe Revisions for TIdMessage SaveToFile & LoadFromFile for D7 & D8 Rev 1.29 08/01/2004 23:43:40 CCostelloe LoadFromFile/SaveToFile now work in D7 again Rev 1.28 1/7/04 11:07:16 PM RLebeau Bug fix for various TIdMessage properties that were not previously using setter methods correctly. Rev 1.27 08/01/2004 00:30:26 CCostelloe Start of reimplementing LoadFrom/SaveToFile Rev 1.26 21/10/2003 23:04:32 CCostelloe Bug fix: removed AttachmentEncoding := '' in SetEncoding. Rev 1.25 21/10/2003 00:33:04 CCostelloe meMIME changed to meDefault in TIdMessage.Create Rev 1.24 10/17/2003 7:42:54 PM BGooijen Changed default Encoding to MIME Rev 1.23 10/17/2003 12:14:08 AM DSiders Added localization comments. Rev 1.22 2003.10.14 9:57:04 PM czhower Compile todos Rev 1.21 10/12/2003 1:55:46 PM BGooijen Removed IdStrings from uses Rev 1.20 2003.10.11 10:01:26 PM czhower .inc path Rev 1.19 10/10/2003 10:42:26 PM BGooijen DotNet Rev 1.18 9/10/2003 1:50:54 PM SGrobety DotNet Rev 1.17 10/8/2003 9:53:12 PM GGrieve use IdCharsets Rev 1.16 05/10/2003 16:38:50 CCostelloe Restructured MIME boundary output Rev 1.15 2003.10.02 9:27:50 PM czhower DotNet Excludes Rev 1.14 01/10/2003 17:58:52 HHariri More fixes for Multipart Messages and also fixes for incorrect transfer encoding settings Rev 1.12 9/28/03 1:36:04 PM RLebeau Updated GenerateHeader() to support the BBCList property Rev 1.11 26/09/2003 00:29:34 CCostelloe IdMessage.Encoding now set when email decoded; XXencoded emails now decoded; logic added to GenerateHeader Rev 1.10 04/09/2003 20:42:04 CCostelloe GenerateHeader sets From's Name field to Address field if Name blank; trailing spaces removed after boundary in FindBoundary; force generation of InReplyTo header. Rev 1.9 29/07/2003 01:14:30 CCostelloe In-Reply-To fixed in GenerateHeader Rev 1.8 11/07/2003 01:11:02 CCostelloe GenerateHeader changed from function to procedure, results now put in LastGeneratedHeaders. Better for user (can see headers sent) and code still efficient. Rev 1.7 10/07/2003 22:39:00 CCostelloe Added LastGeneratedHeaders field and modified GenerateHeaders so that a copy of the last set of headers generated for this message is maintained (see comments starting "CC") Rev 1.6 2003.06.23 9:46:54 AM czhower Russian, Ukranian support for headers. Rev 1.5 6/3/2003 10:46:54 PM JPMugaas In-Reply-To header now supported. Rev 1.4 1/27/2003 10:07:46 PM DSiders Corrected error setting file stream permissions in LoadFromFile. Bug Report 649502. Rev 1.3 27/1/2003 3:07:10 PM SGrobety X-Priority header only added if priority <> mpNormal (because of spam filters) Rev 1.2 09/12/2002 18:19:00 ANeillans Version: 1.2 Removed X-Library Line that was causing people problems with spam detection software , etc. Rev 1.1 12/5/2002 02:53:56 PM JPMugaas Updated for new API definitions. Rev 1.0 11/13/2002 07:56:52 AM JPMugaas 2004-05-04 Ciaran Costelloe - Replaced meUU with mePlainText. This also meant that UUE/XXE encoding was pushed down from the message-level to the MessagePart level, where it belongs. 2004-04-20 Ciaran Costelloe - Added support for multiple From addresses (per RFC 2822, section 3.6.2) by adding a FromList field. The previous From field now maps to FromList[0]. 2003-10-04 Ciaran Costelloe (see comments starting CC4) 2003-09-20 Ciaran Costelloe (see comments starting CC2) - Added meDefault, meXX to TIdMessageEncoding. Code now sets TIdMessage.Encoding when it decodes an email. Modified TIdMIMEBoundary to work as a straight stack, now Push/Pops ParentPart also. Added meDefault, meXX to TIdMessageEncoding. Moved logic from SendBody to GenerateHeader, added extra logic to avoid exceptions: Change any encodings we dont know to base64 We dont support attachments in an encoded body, change it to a supported combination Made changes to support ConvertPreamble and MIME message bodies with a ContentTransferEncoding of base64, quoted-printable. ProcessHeaders now decodes BCC list. 2003-09-02 Ciaran Costelloe - Added fix to FindBoundary suggested by Juergen Haible to remove trailing space after boundary added by some clients. 2003-07-10 Ciaran Costelloe - Added LastGeneratedHeaders property, see comments starting CC. Changed GenerateHeader from function to procedure, it now puts the generated headers into LastGeneratedHeaders, which is where dependant units should take the results from. This ensures that the headers that were generated are recorded, which some users' programs may need. 2002-12-09 Andrew Neillans - Removed X-Library line 2002-08-30 Andrew P.Rybin - Now InitializeISO is IdMessage method 2001-12-27 Andrew P.Rybin Custom InitializeISO, ExtractCharSet 2001-Oct-29 Don Siders Added EIdMessageCannotLoad exception. Added RSIdMessageCannotLoad constant. Added TIdMessage.LoadFromStream. Modified TIdMessage.LoadFromFile to call LoadFromStream. Added TIdMessage.SaveToStream. Modified TIdMessage.SaveToFile to call SaveToStream. Modified TIdMessage.GenerateHeader to include headers received but not used in properties. 2001-Sep-14 Andrew Neillans Added LoadFromFile Header only 2001-Sep-12 Johannes Berg Fixed upper/Sys.LowerCase in uses clause for Kylix 2001-Aug-09 Allen O'Neill Added line to check for valid charset value before adding second ';' after content-type boundry 2001-Aug-07 Allen O'Neill Added SaveToFile & LoadFromFile ... Doychin fixed 2001-Jul-11 Hadi Hariri Added Encoding for both MIME and UU. 2000-Jul-25 Hadi Hariri - Added support for MBCS 2000-Jun-10 Pete Mee - Fixed some minor but annoying bugs. 2000-May-06 Pete Mee - Added coder support directly into TIdMessage. } unit IdMessage; { 2001-Jul-11 Hadi Hariri TODO: Make checks for encoding and content-type later on. TODO: Add TIdHTML, TIdRelated TODO: CountParts on the fly TODO: Merge Encoding and AttachmentEncoding TODO: Make encoding plugable TODO: Clean up ISO header coding } { TODO : Moved Decode/Encode out and will add later,. Maybe TIdMessageEncode, Decode?? } { TODO : Support any header in TMessagePart } { DESIGN NOTE: The TIdMessage has an fBody which should only ever be the raw message. TIdMessage.fBody is only raw if TIdMessage.fIsEncoded = true The component parts are thus possibly made up of the following order of TMessagePart entries: MP[0] : Possible prologue text (fBoundary is '') MP[0 or 1 - depending on prologue existence] : fBoundary = boundary parameter from Content-Type MP[next...] : various parts with or without fBoundary = '' MP[MP.Count - 1] : Possible epilogue text (fBoundary is '') } { DESIGN NOTE: If TMessagePart.fIsEncoded = True, then TMessagePart.fBody is the encoded raw message part. Otherwise, it is the (decoded) text. } interface {$I IdCompilerDefines.inc} uses Classes, IdAttachment, IdBaseComponent, IdCoderHeader, IdEMailAddress, IdExceptionCore, IdHeaderList, IdMessageParts; type TIdMessagePriority = (mpHighest, mpHigh, mpNormal, mpLow, mpLowest); const ID_MSG_NODECODE = False; ID_MSG_USESNOWFORDATE = True; ID_MSG_PRIORITY = mpNormal; type TIdMIMEBoundary = class(TObject) protected FBoundaryList: TStrings; {CC: Added ParentPart as a TStrings so I dont have to create a TIntegers} FParentPartList: TStrings; function GetBoundary: string; function GetParentPart: integer; public constructor Create; destructor Destroy; override; procedure Push(ABoundary: string; AParentPart: integer); procedure Pop; procedure Clear; function Count: integer; property Boundary: string read GetBoundary; property ParentPart: integer read GetParentPart; end; TIdMessageFlags = ( mfAnswered, //Message has been answered. mfFlagged, //Message is "flagged" for urgent/special attention. mfDeleted, //Message is "deleted" for removal by later EXPUNGE. mfDraft, //Message has not completed composition (marked as a draft). mfSeen, //Message has been read. mfRecent ); //Message is "recently" arrived in this mailbox. TIdMessageFlagsSet = set of TIdMessageFlags; {WARNING: Replaced meUU with mePlainText in Indy 10 due to meUU being misleading. This is the MESSAGE-LEVEL "encoding", really the Sys.Format or layout of the message. When encoding, the user can let Indy decide on the encoding by leaving it at meDefault, or he can pick meMIME or mePlainText } //TIdMessageEncoding = (meDefault, meMIME, meUU, meXX); TIdMessageEncoding = (meDefault, meMIME, mePlainText); TIdInitializeIsoEvent = procedure (var VHeaderEncoding: Char; var VCharSet: string) of object; TIdMessage = class; TIdCreateAttachmentEvent = procedure(const AMsg: TIdMessage; const AHeaders: TStrings; var AAttachment: TIdAttachment) of object; TIdMessage = class(TIdBaseComponent) protected FAttachmentTempDirectory: string; FBccList: TIdEmailAddressList; FBody: TStrings; FCharSet: string; FCcList: TIdEmailAddressList; FContentType: string; FContentTransferEncoding: string; FContentDisposition: string; FDate: TDateTime; FIsEncoded : Boolean; FExtraHeaders: TIdHeaderList; FEncoding: TIdMessageEncoding; FFlags: TIdMessageFlagsSet; FFromList: TIdEmailAddressList; FHeaders: TIdHeaderList; FMessageParts: TIdMessageParts; FMIMEBoundary: TIdMIMEBoundary; FMsgId: string; FNewsGroups: TStrings; FNoEncode: Boolean; FNoDecode: Boolean; FOnInitializeISO: TIdInitializeISOEvent; FOrganization: string; FPriority: TIdMessagePriority; FSubject: string; FReceiptRecipient: TIdEmailAddressItem; FRecipients: TIdEmailAddressList; FReferences: string; FInReplyTo : String; FReplyTo: TIdEmailAddressList; FSender: TIdEMailAddressItem; FUID: String; FXProgram: string; FOnCreateAttachment: TIdCreateAttachmentEvent; FLastGeneratedHeaders: TIdHeaderList; FConvertPreamble: Boolean; FSavingToFile: Boolean; FIsMsgSinglePartMime: Boolean; FExceptionOnBlockedAttachments: Boolean; // used in TIdAttachmentFile // procedure DoInitializeISO(var VHeaderEncoding: Char; var VCharSet: String); virtual; function GetAttachmentEncoding: string; function GetInReplyTo: String; function GetUseNowForDate: Boolean; function GetFrom: TIdEmailAddressItem; procedure SetAttachmentEncoding(const AValue: string); procedure SetAttachmentTempDirectory(const Value: string); procedure SetBccList(const AValue: TIdEmailAddressList); procedure SetBody(const AValue: TStrings); procedure SetCCList(const AValue: TIdEmailAddressList); procedure SetContentType(const AValue: String); procedure SetEncoding(const AValue: TIdMessageEncoding); procedure SetExtraHeaders(const AValue: TIdHeaderList); procedure SetFrom(const AValue: TIdEmailAddressItem); procedure SetFromList(const AValue: TIdEmailAddressList); procedure SetHeaders(const AValue: TIdHeaderList); procedure SetInReplyTo(const AValue : String); procedure SetMsgID(const AValue : String); procedure SetNewsGroups(const AValue: TStrings); procedure SetReceiptRecipient(const AValue: TIdEmailAddressItem); procedure SetRecipients(const AValue: TIdEmailAddressList); procedure SetReplyTo(const AValue: TIdEmailAddressList); procedure SetSender(const AValue: TIdEmailAddressItem); procedure SetUseNowForDate(const AValue: Boolean); procedure InitComponent; override; public destructor Destroy; override; procedure AddHeader(const AValue: string); procedure Clear; virtual; procedure ClearBody; procedure ClearHeader; procedure GenerateHeader; procedure InitializeISO(var VHeaderEncoding: Char; var VCharSet: String); function IsBodyEncodingRequired: Boolean; function IsBodyEmpty: Boolean; procedure LoadFromFile(const AFileName: string; const AHeadersOnly: Boolean = False); procedure LoadFromStream(AStream: TStream; const AHeadersOnly: Boolean = False); procedure ProcessHeaders; procedure SaveToFile(const AFileName : string; const AHeadersOnly: Boolean = False); procedure SaveToStream(AStream: TStream; const AHeadersOnly: Boolean = False); procedure DoCreateAttachment(const AHeaders: TStrings; var VAttachment: TIdAttachment); virtual; // property Flags: TIdMessageFlagsSet read FFlags write FFlags; property IsEncoded : Boolean read FIsEncoded write FIsEncoded; property MsgId: string read FMsgId write SetMsgID; property Headers: TIdHeaderList read FHeaders write SetHeaders; property MessageParts: TIdMessageParts read FMessageParts; property MIMEBoundary: TIdMIMEBoundary read FMIMEBoundary write FMIMEBoundary; property UID: String read FUID write FUID; property IsMsgSinglePartMime: Boolean read FIsMsgSinglePartMime write FIsMsgSinglePartMime; published //TODO: Make a property editor which drops down the registered coder types property AttachmentEncoding: string read GetAttachmentEncoding write SetAttachmentEncoding; property Body: TStrings read FBody write SetBody; property BccList: TIdEmailAddressList read FBccList write SetBccList; property CharSet: string read FCharSet write FCharSet; property CCList: TIdEmailAddressList read FCcList write SetCcList; property ContentType: string read FContentType write SetContentType; property ContentTransferEncoding: string read FContentTransferEncoding write FContentTransferEncoding; property ContentDisposition: string read FContentDisposition write FContentDisposition; property Date: TDateTime read FDate write FDate; // property Encoding: TIdMessageEncoding read FEncoding write SetEncoding; property ExtraHeaders: TIdHeaderList read FExtraHeaders write SetExtraHeaders; property FromList: TIdEmailAddressList read FFromList write SetFromList; property From: TIdEmailAddressItem read GetFrom write SetFrom; property NewsGroups: TStrings read FNewsGroups write SetNewsGroups; property NoEncode: Boolean read FNoEncode write FNoEncode default ID_MSG_NODECODE; property NoDecode: Boolean read FNoDecode write FNoDecode default ID_MSG_NODECODE; property Organization: string read FOrganization write FOrganization; property Priority: TIdMessagePriority read FPriority write FPriority default ID_MSG_PRIORITY; property ReceiptRecipient: TIdEmailAddressItem read FReceiptRecipient write SetReceiptRecipient; property Recipients: TIdEmailAddressList read FRecipients write SetRecipients; property References: string read FReferences write FReferences; property InReplyTo : String read GetInReplyTo write SetInReplyTo; property ReplyTo: TIdEmailAddressList read FReplyTo write SetReplyTo; property Subject: string read FSubject write FSubject; property Sender: TIdEmailAddressItem read FSender write SetSender; property UseNowForDate: Boolean read GetUseNowForDate write SetUseNowForDate default ID_MSG_USESNOWFORDATE; property LastGeneratedHeaders: TIdHeaderList read FLastGeneratedHeaders; property ConvertPreamble: Boolean read FConvertPreamble write FConvertPreamble; property ExceptionOnBlockedAttachments: Boolean read FExceptionOnBlockedAttachments write FExceptionOnBlockedAttachments default False; property AttachmentTempDirectory: string read FAttachmentTempDirectory write SetAttachmentTempDirectory; // Events property OnInitializeISO: TIdInitializeIsoEvent read FOnInitializeISO write FOnInitializeISO; property OnCreateAttachment: TIdCreateAttachmentEvent read FOnCreateAttachment write FOnCreateAttachment; End; TIdMessageEvent = procedure(ASender : TComponent; var AMsg : TIdMessage) of object; EIdTextInvalidCount = class(EIdMessageException); // 2001-Oct-29 Don Siders EIdMessageCannotLoad = class(EIdMessageException); const MessageFlags : array [mfAnswered..mfRecent] of String = ( '\Answered', {Do not Localize} //Message has been answered. '\Flagged', {Do not Localize} //Message is "flagged" for urgent/special attention. '\Deleted', {Do not Localize} //Message is "deleted" for removal by later EXPUNGE. '\Draft', {Do not Localize} //Message has not completed composition (marked as a draft). '\Seen', {Do not Localize} //Message has been read. '\Recent' ); {Do not Localize} //Message is "recently" arrived in this mailbox. INREPLYTO = 'In-Reply-To'; {Do not localize} implementation uses //facilitate inlining only. {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.IO, {$ENDIF} {$ENDIF} IdIOHandlerStream, IdGlobal, IdMessageCoderMIME, // Here so the 'MIME' in create will always suceed IdCharSets, IdGlobalProtocols, IdMessageCoder, IdResourceStringsProtocols, IdMessageClient, IdAttachmentFile, IdText, SysUtils; const cPriorityStrs: array[TIdMessagePriority] of string = ('urgent', 'urgent', 'normal', 'non-urgent', 'non-urgent'); { TIdMIMEBoundary } procedure TIdMIMEBoundary.Clear; begin FBoundaryList.Clear; FParentPartList.Clear; end; function TIdMIMEBoundary.Count: integer; begin Result := FBoundaryList.Count; end; constructor TIdMIMEBoundary.Create; begin inherited; FBoundaryList := TStringList.Create; FParentPartList := TStringList.Create; end; destructor TIdMIMEBoundary.Destroy; begin FreeAndNil(FBoundaryList); FreeAndNil(FParentPartList); inherited; end; function TIdMIMEBoundary.GetBoundary: string; begin if FBoundaryList.Count > 0 then begin Result := FBoundaryList.Strings[0]; end else begin Result := ''; end; end; function TIdMIMEBoundary.GetParentPart: integer; begin if FParentPartList.Count > 0 then begin Result := IndyStrToInt(FParentPartList.Strings[0]); end else begin Result := -1; end; end; procedure TIdMIMEBoundary.Pop; begin if FBoundaryList.Count > 0 then begin FBoundaryList.Delete(0); end; if FParentPartList.Count > 0 then begin FParentPartList.Delete(0); end; end; procedure TIdMIMEBoundary.Push(ABoundary: string; AParentPart: integer); begin {CC: Changed implementation to a simple stack} FBoundaryList.Insert(0, ABoundary); FParentPartList.Insert(0, IntToStr(AParentPart)); end; { TIdMessage } procedure TIdMessage.AddHeader(const AValue: string); begin FHeaders.Add(AValue); end; procedure TIdMessage.Clear; begin ClearHeader; ClearBody; end; procedure TIdMessage.ClearBody; begin MessageParts.Clear; Body.Clear; end; procedure TIdMessage.ClearHeader; begin CcList.Clear; BccList.Clear; Date := 0; FromList.Clear; NewsGroups.Clear; Organization := ''; References := ''; ReplyTo.Clear; Subject := ''; Recipients.Clear; Priority := ID_MSG_PRIORITY; ReceiptRecipient.Text := ''; FContentType := ''; FCharSet := ''; ContentTransferEncoding := ''; ContentDisposition := ''; FSender.Text := ''; Headers.Clear; ExtraHeaders.Clear; FMIMEBoundary.Clear; // UseNowForDate := ID_MSG_USENOWFORDATE; Flags := []; MsgId := ''; UID := ''; FLastGeneratedHeaders.Clear; FEncoding := meDefault; {CC3: Changed initial encoding from meMIME to meDefault} FConvertPreamble := True; {By default, in MIME, we convert the preamble text to the 1st TIdText part} FSavingToFile := False; {Only set True by SaveToFile} FIsMsgSinglePartMime := False; end; procedure TIdMessage.InitComponent; begin inherited; FBody := TStringList.Create; TStringList(FBody).Duplicates := dupAccept; FRecipients := TIdEmailAddressList.Create(Self); FBccList := TIdEmailAddressList.Create(Self); FCcList := TIdEmailAddressList.Create(Self); FMessageParts := TIdMessageParts.Create(Self); FNewsGroups := TStringList.Create; FHeaders := TIdHeaderList.Create(QuoteRFC822); FFromList := TIdEmailAddressList.Create(Self); FReplyTo := TIdEmailAddressList.Create(Self); FSender := TIdEmailAddressItem.Create; FExtraHeaders := TIdHeaderList.Create(QuoteRFC822); FReceiptRecipient := TIdEmailAddressItem.Create; NoDecode := ID_MSG_NODECODE; FMIMEBoundary := TIdMIMEBoundary.Create; FLastGeneratedHeaders := TIdHeaderList.Create(QuoteRFC822); Clear; FEncoding := meDefault; end; destructor TIdMessage.Destroy; begin FreeAndNil(FBody); FreeAndNil(FRecipients); FreeAndNil(FBccList); FreeAndNil(FCcList); FreeAndNil(FMessageParts); FreeAndNil(FNewsGroups); FreeAndNil(FHeaders); FreeAndNil(FExtraHeaders); FreeAndNil(FFromList); FreeAndNil(FReplyTo); FreeAndNil(FSender); FreeAndNil(FReceiptRecipient); FreeAndNil(FMIMEBoundary); FreeAndNil(FLastGeneratedHeaders); inherited Destroy; end; function TIdMessage.IsBodyEmpty: Boolean; //Determine if there really is anything in the body var LN: integer; LOrd: integer; begin Result := False; for LN := 1 to Length(Body.Text) do begin LOrd := Ord(Body.Text[LN]); if ((LOrd <> 13) and (LOrd <> 10) and (LOrd <> 9) and (LOrd <> 32)) then begin Exit; end; end; Result := True; end; procedure TIdMessage.GenerateHeader; var ISOCharset: string; HeaderEncoding: Char; LN: Integer; LEncoding, LCharSet, LMIMEBoundary: string; LDate: TDateTime; LReceiptRecipient: string; begin MessageParts.CountParts; {CC2: If the encoding is meDefault, the user wants us to pick an encoding mechanism:} if Encoding = meDefault then begin if MessageParts.Count = 0 then begin {If there are no attachments, we want the simplest type, just the headers followed by the message body: mePlainText does this for us} Encoding := mePlainText; end else begin {If there are any attachments, default to MIME...} Encoding := meMIME; end; end; for LN := 0 to MessageParts.Count-1 do begin {Change any encodings we don't know to base64 for MIME and UUE for PlainText...} LEncoding := MessageParts[LN].ContentTransfer; if LEncoding <> '' then begin if Encoding = meMIME then begin if PosInStrArray(LEncoding, ['7bit', '8bit', 'binary', 'base64', 'quoted-printable', 'binhex40'], False) = -1 then begin {do not localize} MessageParts[LN].ContentTransfer := 'base64'; {do not localize} end; end else if PosInStrArray(LEncoding, ['UUE', 'XXE'], False) = -1 then begin {do not localize} //mePlainText MessageParts[LN].ContentTransfer := 'UUE'; {do not localize} end; end; end; {RLebeau: should we validate the TIdMessage.ContentTransferEncoding property as well?} {CC2: We dont support attachments in an encoded body. Change it to a supported combination...} if MessageParts.Count > 0 then begin if (ContentTransferEncoding <> '') and (PosInStrArray(ContentTransferEncoding, ['7bit', '8bit', 'binary'], False) = -1) then begin {do not localize} ContentTransferEncoding := ''; end; end; if Encoding = meMIME then begin //HH: Generate Boundary here so we know it in the headers and body //######### SET UP THE BOUNDARY STACK ######## //RLebeau: Moved this logic up from SendBody to here, where it fits better... MIMEBoundary.Clear; LMIMEBoundary := TIdMIMEBoundaryStrings.GenerateBoundary; MIMEBoundary.Push(LMIMEBoundary, -1); //-1 is "top level" //CC: Moved this logic up from SendBody to here, where it fits better... if Length(ContentType) = 0 then begin //User has omitted ContentType. We have to guess here, it is impossible //to determine without having procesed the parts. //See if it is multipart/alternative... if MessageParts.TextPartCount > 1 then begin if MessageParts.AttachmentCount > 0 then begin ContentType := 'multipart/mixed'; {do not localize} end else begin ContentType := 'multipart/alternative'; {do not localize} end; end else begin //Just one (or 0?) text part. if MessageParts.AttachmentCount > 0 then begin ContentType := 'multipart/mixed'; {do not localize} end else begin ContentType := 'text/plain'; {do not localize} end; end; end; TIdMessageEncoderInfo(MessageParts.MessageEncoderInfo).InitializeHeaders(Self); end; InitializeISO(HeaderEncoding, ISOCharSet); LastGeneratedHeaders.Assign(FHeaders); FIsMsgSinglePartMime := (Encoding = meMIME) and (MessageParts.Count = 1) and IsBodyEmpty; with LastGeneratedHeaders do begin {CC: If From has no Name field, use the Address field as the Name field by setting last param to True (for SA)...} Values['From'] := EncodeAddress(FromList, HeaderEncoding, ISOCharSet, True); {do not localize} Values['Subject'] := EncodeHeader(Subject, '', HeaderEncoding, ISOCharSet); {do not localize} Values['To'] := EncodeAddress(Recipients, HeaderEncoding, ISOCharSet); {do not localize} Values['Cc'] := EncodeAddress(CCList, HeaderEncoding, ISOCharSet); {do not localize} {CC: SaveToFile sets FSavingToFile to True so that BCC names are saved when saving to file and omitted otherwise (as required by SMTP)...} if not FSavingToFile then begin Values['Bcc'] := ''; {do not localize} end else begin Values['Bcc'] := EncodeAddress(BCCList, HeaderEncoding, ISOCharSet); {do not localize} end; Values['Newsgroups'] := NewsGroups.CommaText; {do not localize} // RLebeau: Delphi XE introduces a new TStrings.Encoding property, // so we have to qualify which Encoding property to access here... if Self.Encoding = meMIME then begin if IsMsgSinglePartMime then begin {This is a single-part MIME: the part may be a text part or an attachment. The relevant headers need to be taken from MessageParts[0]. The problem, however, is that we have not yet processed MessageParts[0] yet, so we do not have its properties or header content properly set up. So we will let the processing of MessageParts[0] append its headers to the message headers, i.e. DON'T generate Content-Type or Content-Transfer-Encoding headers here.} Values['MIME-Version'] := '1.0'; {do not localize} {RLebeau: need to wipe out the following headers if they were present, otherwise MessageParts[0] will duplicate them instead of replacing them. This is because LastGeneratedHeaders is sent before MessageParts[0] is processed.} Values['Content-Type'] := ''; Values['Content-Transfer-Encoding'] := ''; Values['Content-Disposition'] := ''; end else begin if FContentType <> '' then begin LCharSet := FCharSet; if (LCharSet = '') and IsHeaderMediaType(FContentType, 'text') then begin {do not localize} LCharSet := 'us-ascii'; {do not localize} end; Values['Content-Type'] := FContentType; {do not localize} Params['Content-Type', 'charset'] := LCharSet; {do not localize} if (MessageParts.Count > 0) and (LMIMEBoundary <> '') then begin Params['Content-Type', 'boundary'] := LMIMEBoundary; {do not localize} end; end; {CC2: We may have MIME with no parts if ConvertPreamble is True} Values['MIME-Version'] := '1.0'; {do not localize} Values['Content-Transfer-Encoding'] := ContentTransferEncoding; {do not localize} end; end else begin //CC: non-MIME can have ContentTransferEncoding of base64, quoted-printable... LCharSet := FCharSet; if (LCharSet = '') and IsHeaderMediaType(FContentType, 'text') then begin {do not localize} LCharSet := 'us-ascii'; {do not localize} end; Values['Content-Type'] := FContentType; {do not localize} Params['Content-Type', 'charset'] := LCharSet; {do not localize} Values['Content-Transfer-Encoding'] := ContentTransferEncoding; {do not localize} end; Values['Sender'] := Sender.Text; {do not localize} Values['Reply-To'] := EncodeAddress(ReplyTo, HeaderEncoding, ISOCharSet); {do not localize} Values['Organization'] := EncodeHeader(Organization, '', HeaderEncoding, ISOCharSet); {do not localize} LReceiptRecipient := EncodeAddressItem(ReceiptRecipient, HeaderEncoding, ISOCharSet); Values['Disposition-Notification-To'] := LReceiptRecipient; {do not localize} Values['Return-Receipt-To'] := LReceiptRecipient; {do not localize} Values['References'] := References; {do not localize} if UseNowForDate then begin LDate := Now; end else begin LDate := Self.Date; end; Values['Date'] := LocalDateTimeToGMT(LDate); {do not localize} // S.G. 27/1/2003: Only issue X-Priority header if priority <> mpNormal (for stoopid spam filters) if Priority <> mpNormal then begin Values['Priority'] := cPriorityStrs[Priority]; {do not localize} Values['X-Priority'] := IntToStr(Ord(Priority) + 1) {do not localize} end else begin Values['Priority'] := ''; {do not localize} Values['X-Priority'] := ''; {do not localize} end; {CC: SaveToFile sets FSavingToFile to True so that Message IDs are saved when saving to file and omitted otherwise ...} if not FSavingToFile then begin Values['Message-Id'] := ''; end else begin Values['Message-Id'] := MsgId; end; // Add extra headers created by UA - allows duplicates if (FExtraHeaders.Count > 0) then begin AddStrings(FExtraHeaders); end; {Generate In-Reply-To if at all possible to pacify SA. Do this after FExtraHeaders added in case there is a message-ID present as an extra header.} if InReplyTo = '' then begin if Values['Message-ID'] <> '' then begin {do not localize} Values['In-Reply-To'] := Values['Message-ID']; {do not localize} end else begin {CC: The following was originally present, but it so wrong that it has to go! Values['In-Reply-To'] := Subject; {do not localize} end; end else begin Values['In-Reply-To'] := InReplyTo; {do not localize} end; end; end; procedure TIdMessage.ProcessHeaders; var LBoundary: string; LMIMEVersion: string; // Some mailers send priority as text, number or combination of both function GetMsgPriority(APriority: string): TIdMessagePriority; var s: string; Num: integer; begin // This is for Pegasus. if IndyPos('urgent', LowerCase(APriority)) <> 0 then begin {do not localize} Result := mpHigh; end else if IndyPos('non-urgent', LowerCase(APriority)) <> 0 then begin {do not localize} Result := mpLow; end else begin s := Trim(APriority); Num := IndyStrToInt(Fetch(s, ' '), 3); {do not localize} if (Num < 1) or (Num > 5) then begin Num := 3; end; Result := TIdMessagePriority(Num - 1); end; end; begin // RLebeau: per RFC 2045 Section 5.2: // // Default RFC 822 messages without a MIME Content-Type header are taken // by this protocol to be plain text in the US-ASCII character set, // which can be explicitly specified as: // // Content-type: text/plain; charset=us-ascii // // This default is assumed if no Content-Type header field is specified. // It is also recommend that this default be assumed when a // syntactically invalid Content-Type header field is encountered. In // the presence of a MIME-Version header field and the absence of any // Content-Type header field, a receiving User Agent can also assume // that plain US-ASCII text was the sender's intent. Plain US-ASCII // text may still be assumed in the absence of a MIME-Version or the // presence of an syntactically invalid Content-Type header field, but // the sender's intent might have been otherwise. FContentType := Headers.Values['Content-Type']; {do not localize} if FContentType = '' then begin FContentType := 'text/plain'; {do not localize} FCharSet := 'us-ascii'; {do not localize} end else begin FContentType := RemoveHeaderEntry(FContentType, 'charset', FCharSet, QuoteMIME); {do not localize} if (FCharSet = '') and IsHeaderMediaType(FContentType, 'text') then begin {do not localize} FCharSet := 'us-ascii'; {do not localize} end; end; ContentTransferEncoding := Headers.Values['Content-Transfer-Encoding']; {do not localize} ContentDisposition := Headers.Values['Content-Disposition']; {do not localize} Subject := DecodeHeader(Headers.Values['Subject']); {do not localize} DecodeAddresses(Headers.Values['From'], FromList); {do not localize} MsgId := Headers.Values['Message-Id']; {do not localize} CommaSeparatedToStringList(Newsgroups, Headers.Values['Newsgroups']); {do not localize} DecodeAddresses(Headers.Values['To'], Recipients); {do not localize} DecodeAddresses(Headers.Values['Cc'], CCList); {do not localize} {CC2: Added support for BCCList...} DecodeAddresses(Headers.Values['Bcc'], BCCList); {do not localize} Organization := Headers.Values['Organization']; {do not localize} InReplyTo := Headers.Values['In-Reply-To']; {do not localize} ReceiptRecipient.Text := Headers.Values['Disposition-Notification-To']; {do not localize} if Length(ReceiptRecipient.Text) = 0 then begin ReceiptRecipient.Text := Headers.Values['Return-Receipt-To']; {do not localize} end; References := Headers.Values['References']; {do not localize} DecodeAddresses(Headers.Values['Reply-To'], ReplyTo); {do not localize} if Length(ReplyTo.EmailAddresses) = 0 then begin DecodeAddresses(Headers.Values['Return-Path'], ReplyTo); {do not localize} end; Date := GMTToLocalDateTime(Headers.Values['Date']); {do not localize} Sender.Text := Headers.Values['Sender']; {do not localize} if Length(Headers.Values['Priority']) > 0 then begin {do not localize} Priority := GetMsgPriority(Headers.Values['Priority']); {do not localize} end else begin Priority := GetMsgPriority(Headers.Values['X-Priority']) {do not localize} end; {Note that the following code ensures MIMEBoundary.Count is 0 for single-part MIME messages...} FContentType := RemoveHeaderEntry(FContentType, 'boundary', LBoundary, QuoteMIME); {do not localize} if LBoundary <> '' then begin MIMEBoundary.Push(LBoundary, -1); end; {CC2: Set MESSAGE_LEVEL "encoding" (really the format or layout)} LMIMEVersion := Headers.Values['MIME-Version']; {do not localize} if LMIMEVersion = '' then begin Encoding := mePlainText; end else begin // TODO: this should be true if a MIME boundary is present. // The MIME version is optional... Encoding := meMIME; end; end; procedure TIdMessage.SetBccList(const AValue: TIdEmailAddressList); begin FBccList.Assign(AValue); end; procedure TIdMessage.SetBody(const AValue: TStrings); begin FBody.Assign(AValue); end; procedure TIdMessage.SetCCList(const AValue: TIdEmailAddressList); begin FCcList.Assign(AValue); end; procedure TIdMessage.SetContentType(const AValue: String); var LCharSet: String; begin // RLebeau: per RFC 2045 Section 5.2: // // Default RFC 822 messages without a MIME Content-Type header are taken // by this protocol to be plain text in the US-ASCII character set, // which can be explicitly specified as: // // Content-type: text/plain; charset=us-ascii // // This default is assumed if no Content-Type header field is specified. // It is also recommend that this default be assumed when a // syntactically invalid Content-Type header field is encountered. In // the presence of a MIME-Version header field and the absence of any // Content-Type header field, a receiving User Agent can also assume // that plain US-ASCII text was the sender's intent. Plain US-ASCII // text may still be assumed in the absence of a MIME-Version or the // presence of an syntactically invalid Content-Type header field, but // the sender's intent might have been otherwise. if AValue <> '' then begin FContentType := RemoveHeaderEntry(AValue, 'charset', LCharSet, QuoteMIME); {do not localize} {RLebeau: the ContentType property is streamed after the CharSet property, so do not overwrite it during streaming} if csReading in ComponentState then begin Exit; end; if (LCharSet = '') and IsHeaderMediaType(FContentType, 'text') then begin {do not localize} LCharSet := 'us-ascii'; {do not localize} end; {RLebeau: override the current CharSet only if the header specifies a new value} if LCharSet <> '' then begin FCharSet := LCharSet; end; end else begin FContentType := 'text/plain'; {do not localize} {RLebeau: the ContentType property is streamed after the CharSet property, so do not overwrite it during streaming} if not (csReading in ComponentState) then begin FCharSet := 'us-ascii'; {do not localize} end; end; end; procedure TIdMessage.SetExtraHeaders(const AValue: TIdHeaderList); begin FExtraHeaders.Assign(AValue); end; procedure TIdMessage.SetFrom(const AValue: TIdEmailAddressItem); begin GetFrom.Assign(AValue); end; function TIdMessage.GetFrom: TIdEmailAddressItem; begin if FFromList.Count = 0 then begin FFromList.Add; end; Result := FFromList[0]; end; procedure TIdMessage.SetFromList(const AValue: TIdEmailAddressList); begin FFromList.Assign(AValue); end; procedure TIdMessage.SetHeaders(const AValue: TIdHeaderList); begin FHeaders.Assign(AValue); end; procedure TIdMessage.SetNewsGroups(const AValue: TStrings); begin FNewsgroups.Assign(AValue); end; procedure TIdMessage.SetReceiptRecipient(const AValue: TIdEmailAddressItem); begin FReceiptRecipient.Assign(AValue); end; procedure TIdMessage.SetRecipients(const AValue: TIdEmailAddressList); begin FRecipients.Assign(AValue); end; procedure TIdMessage.SetReplyTo(const AValue: TIdEmailAddressList); begin FReplyTo.Assign(AValue); end; procedure TIdMessage.SetSender(const AValue: TIdEmailAddressItem); begin FSender.Assign(AValue); end; function TIdMessage.GetUseNowForDate: Boolean; begin Result := (FDate = 0); end; procedure TIdMessage.SetUseNowForDate(const AValue: Boolean); begin if GetUseNowForDate <> AValue then begin if AValue then begin FDate := 0; end else begin FDate := Now; end; end; end; procedure TIdMessage.SetAttachmentEncoding(const AValue: string); begin MessageParts.AttachmentEncoding := AValue; end; function TIdMessage.GetAttachmentEncoding: string; begin Result := MessageParts.AttachmentEncoding; end; procedure TIdMessage.SetEncoding(const AValue: TIdMessageEncoding); begin FEncoding := AValue; if AValue = meMIME then begin AttachmentEncoding := 'MIME'; {do not localize} end else begin //Default to UUE for mePlainText, user can override to XXE by calling //TIdMessage.AttachmentEncoding := 'XXE'; AttachmentEncoding := 'UUE'; {do not localize} end; end; procedure TIdMessage.LoadFromFile(const AFileName: string; const AHeadersOnly: Boolean = False); var LStream: TIdReadFileExclusiveStream; begin if not FileExists(AFilename) then begin EIdMessageCannotLoad.Toss(IndyFormat(RSIdMessageCannotLoad, [AFilename])); end; LStream := TIdReadFileExclusiveStream.Create(AFilename); try LoadFromStream(LStream, AHeadersOnly); finally FreeAndNil(LStream); end; end; procedure TIdMessage.LoadFromStream(AStream: TStream; const AHeadersOnly: Boolean = False); begin // clear message properties, headers before loading Clear; with TIdMessageClient.Create do try ProcessMessage(Self, AStream, AHeadersOnly); finally Free; end; end; procedure TIdMessage.SaveToFile(const AFileName: string; const AHeadersOnly: Boolean = False); var LStream : TFileStream; begin LStream := TIdFileCreateStream.Create(AFileName); try FSavingToFile := True; try SaveToStream(LStream, AHeadersOnly); finally FSavingToFile := False; end; finally FreeAndNil(LStream); end; end; procedure TIdMessage.SaveToStream(AStream: TStream; const AHeadersOnly: Boolean = False); var LMsgClient: TIdMessageClient; LIOHandler: TIdIOHandlerStream; begin LMsgClient := TIdMessageClient.Create(nil); try LIOHandler := TIdIOHandlerStream.Create(nil, nil, AStream); try LIOHandler.FreeStreams := False; LMsgClient.IOHandler := LIOHandler; LMsgClient.SendMsg(Self, AHeadersOnly); // add the end of message marker when body is included if not AHeadersOnly then begin LMsgClient.IOHandler.WriteLn('.'); {do not localize} end; finally FreeAndNil(LIOHandler); end; finally FreeAndNil(LMsgClient); end; end; procedure TIdMessage.DoInitializeISO(var VHeaderEncoding: Char; var VCharSet: string); Begin if Assigned(FOnInitializeISO) then begin FOnInitializeISO(VHeaderEncoding, VCharSet);//APR end; End;// procedure TIdMessage.InitializeISO(var VHeaderEncoding: Char; var VCharSet: String); Begin VHeaderEncoding := 'B'; { base64 / quoted-printable } {Do not Localize} VCharSet := IdCharsetNames[IdGetDefaultCharSet]; // it's not clear when VHeaderEncoding should be Q not B. // Comments welcome on atozedsoftware.indy.general case IdGetDefaultCharSet of idcs_ISO_8859_1 : VHeaderEncoding := 'Q'; {Do not Localize} idcs_UNICODE_1_1 : VCharSet := IdCharsetNames[idcs_UTF_8]; else // nothing end; DoInitializeISO(VHeaderEncoding, VCharSet); End; procedure TIdMessage.DoCreateAttachment(const AHeaders: TStrings; var VAttachment: TIdAttachment); begin VAttachment := nil; if Assigned(FOnCreateAttachment) then begin FOnCreateAttachment(Self, AHeaders, VAttachment); end; if VAttachment = nil then begin VAttachment := TIdAttachmentFile.Create(MessageParts); end; end; function TIdMessage.IsBodyEncodingRequired: Boolean; var i,j: Integer; S: String; begin Result := False;//7bit for i:= 0 to FBody.Count - 1 do begin S := FBody[i]; for j := 1 to Length(S) do begin if S[j] > #127 then begin Result := True; Exit; end; end; end; end;// function TIdMessage.GetInReplyTo: String; begin Result := EnsureMsgIDBrackets(FInReplyTo); end; procedure TIdMessage.SetInReplyTo(const AValue: String); begin FInReplyTo := EnsureMsgIDBrackets(AValue); end; procedure TIdMessage.SetMsgID(const AValue: String); begin FMsgId := EnsureMsgIDBrackets(AValue); end; procedure TIdMessage.SetAttachmentTempDirectory(const Value: string); begin if Value <> AttachmentTempDirectory then begin FAttachmentTempDirectory := IndyExcludeTrailingPathDelimiter(Value); end; end; end.
{ ********************************************************************* Gnostice eDocEngine Copyright (c) Gnostice Information Technologies Private Limited http://www.gnostice.com ********************************************************************* } {$I ..\gtSharedDefines.inc} unit gtUtils3; interface uses Windows, SysUtils, Graphics, StdCtrls, Controls, Classes, SyncObjs, ExtCtrls, Dialogs; const { Default word delimiters are any character except the core alphanumerics. } WordDelimiters: set of AnsiChar = [#0 .. #255] - ['a' .. 'z', 'A' .. 'Z', '1' .. '9', '0']; var LockDecimalSep: TCriticalSection; boolTrueType: Boolean; const HoursPerDay = 24; MinsPerHour = 60; SecsPerMin = 60; MSecsPerSec = 1000; MinsPerDay = HoursPerDay * MinsPerHour; SecsPerDay = MinsPerDay * SecsPerMin; SecsPerHour = SecsPerMin * MinsPerHour; MSecsPerDay = SecsPerDay * MSecsPerSec; type // MD5 TgtByteArray1 = array of Byte; MD5Count = array [0 .. 1] of DWORD; MD5State = array [0 .. 3] of DWORD; MD5Block = array [0 .. 15] of DWORD; MD5CBits = array [0 .. 7] of Byte; MD5Digest = array [0 .. 15] of Byte; MD5Buffer = array [0 .. 63] of Byte; MD5Context = record State: MD5State; Count: MD5Count; Buffer: MD5Buffer; end; TgtSigCertLevel = (clNoChange, clFillFormFields, clInsertAnnots); TgtSigFieldAppearenceOption = (sfaoShowName, sfaoShowReason, sfaoShowLocation, sfaoShowDate, sfaoShowLabels); THackWinControl = class(TWinControl); TgtByteArray = array of Byte; TStringSeachOption = (soDown, soMatchCase, soWholeWord); TStringSearchOptions = set of TStringSeachOption; TgtRect = record Left, Top, Right, Bottom: Double; end; { TgtMD5 } TgtMD5 = class(Tobject) private FContext: MD5Context; FBufferPad: MD5Buffer; procedure Transform(ABuffer: Pointer; var AState: MD5State); function F(AX, AY, AZ: DWORD): DWORD; procedure FF(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); function G(AX, AY, AZ: DWORD): DWORD; procedure GG(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); function H(AX, AY, AZ: DWORD): DWORD; procedure HH(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); function I(AX, AY, AZ: DWORD): DWORD; procedure II(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); procedure Rot(var AX: DWORD; AN: Byte); procedure Decode(ASource, ATarget: Pointer; ACount: Longword); procedure Encode(ASource, ATarget: Pointer; ACount: Longword); public constructor Create; destructor Destroy; override; procedure Initilize; procedure Update(AInput: Pointer; ALength: Longword; Flag: Boolean); overload; procedure Update(AInput: array of Byte; ALength: Longword); overload; procedure Finalize(var ADigest: MD5Digest); procedure GetHash(AInput: TgtByteArray1; ALength: Int64; var ADigest: MD5Digest); overload; procedure GetHash(AInput: TStream; var ADigest: MD5Digest); overload; function CompareHash(const AHash1, AHash2: MD5Digest): Boolean; end; TDateOrder = (doMDY, doDMY, doYMD); // Conditional Routines function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = 0): Integer; overload; function IfThen(AValue: Boolean; const ATrue: DWORD; const AFalse: DWORD = 0) : DWORD; overload; function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double = 0.0): Double; overload; function IfThen(AValue: Boolean; const ATrue: String; const AFalse: String = '') : String; overload; // String Handling Routines function RightStr(const AText: String; const ACount: Integer): String; function LeftStr(const AText: String; const ACount: Integer): String; function MidStr(const AText: String; const AStart, ACount: Integer): String; function PosEx(const SubStr, S: String; Offset: Cardinal = 1): Integer; function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer; SearchString: String; Options: TStringSearchOptions = [soDown]): PChar; function TryStrToInt(const S: String; out Value: Integer): Boolean; {$IFDEF gtDelphi5} function CurrentYear: Word; function IsLeadChar(C: AnsiChar): Boolean; function NextCharIndex(const S: AnsiString; Index: Integer): Integer; function StrCharLength(const Str: PAnsiChar): Integer; function GetEraYearOffset(const Name: string): Integer; function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean; function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime) : Boolean; function GetDateOrder(const DateFormat: string): TDateOrder; procedure ScanBlanks(const S: string; var Pos: Integer); function ScanNumber(const S: string; var Pos: Integer; var Number: Word; var CharCount: Byte): Boolean; function ScanString(const S: string; var Pos: Integer; const Symbol: string): Boolean; function ScanChar(const S: string; var Pos: Integer; Ch: Char): Boolean; procedure ScanToNumber(const S: string; var Pos: Integer); function ScanDate(const S: string; var Pos: Integer; var Date: TDateTime): Boolean; function ScanTime(const S: string; var Pos: Integer; var Time: TDateTime): Boolean; function TryStrToDate(const S: string; out Value: TDateTime): Boolean; function TryStrToTime(const S: string; out Value: TDateTime): Boolean; function TryStrToDateTime(const S: string; out Value: TDateTime): Boolean; {$ENDIF} function ReplaceString(const S, OldPattern, NewPattern: WideString) : WideString; overload; function ReplaceStringPos(const S: String; Offset: Integer; OldPattern, NewPattern: String): String; procedure RemoveNullCharacters(var S: String); function AnsiContainsText(const AText, ASubText: String): Boolean; procedure FreeAndNil(var Obj); function TextSize(const Text: String; AFont: TFont): TSize; function ColorToPDFColor(AColor: TColor): String; function ColorBGRToRGB(AColor: TColor): String; procedure CheckSysColor(var Color: TColor); procedure SetControlsEnabled(AControl: TWinControl; AState: Boolean; AIgnoreList: TList = nil); // Unit Conversion Functions. function DegreesToRadians(Degrees: Extended): Extended; function PixelsToPoints(X: Extended): Extended; function PointsToPixels(X: Extended): Extended; function RadiansToDegrees(Radians: Extended): Extended; // Conversion Routines function IsHex(AString: String): Boolean; function IsOctal(AString: String): Boolean; function GetHexOfStr(AString: AnsiString): AnsiString; function GetHexOfStrw(AString: String): String; {$IFNDEF gtDelphi6Up} procedure BinToHex(Buffer, Text: PChar; BufSize: Integer); {$ENDIF} function HexToByteArray(AHex: String): TgtByteArray; function HexToByteValue(AHex: String; out AByte: Byte): Integer; function HexToByteString(AHex: String): String; procedure OctalToByteValue(AOctal: String; out AByte: Byte); procedure EscapeStringToByteArray(AEscapeString: AnsiString; var AByte: array of Byte); procedure EscapeStringToString(AEscapeString: String; var AString: String); function StringToEscapeString(AString: String): String; function ConvertTabsToSpaces(Str: String; Fonts: TFont; TabsStops: TStringList): String; // Float to String Locale function FloatToStrLocale(Value: Double): String; function FloatToStrFLocale(Value: Extended; Format: TFloatFormat; Precision, Digits: Integer): String; // String to Float Locale function StrToFloatLocale(AString: String): Double; function gtRect(Left, Top, Right, Bottom: Double): TgtRect; overload; function gtRect(ARect: TgtRect; AFactor: Double): TgtRect; overload; function gtRect(ARect: TgtRect; AXFactor, AYFactor: Double): TgtRect; overload; // Font Charsets collection procedure GetSupportedCharSets(const FaceName: String; CharSets: TList); { var MD5Data: MD5Context; procedure MD5Final(var AContext: MD5Context; var ADigest: MD5Digest); procedure MD5Init(var AContext: MD5Context); procedure MD5Update(var AContext: MD5Context; AInput: array of Byte; ALength: Longword); function GetHash(AInput: TStream): MD5Digest; overload; function CompareHash(const AHash1, AHash2: MD5Digest): Boolean; } implementation uses Math, gtConsts3, Forms; type TNewTextMetricEx = packed record NewTextMetric: TNewTextMetric; FontSignature: TFontSignature end; (* ---------------------------------------------------------------------------- *) function EnumFontFamExProc(const EnumLogFontEx: TEnumLogFontEx; const NewTextMetricEx: TNewTextMetricEx; FontType: Integer; lParam: TList) : Integer; stdcall; var LI: Integer; begin LI := EnumLogFontEx.elfLogFont.lfCharSet; case (LI) of ANSI_CHARSET, SYMBOL_CHARSET, SHIFTJIS_CHARSET, HANGEUL_CHARSET, GB2312_CHARSET, CHINESEBIG5_CHARSET, OEM_CHARSET, JOHAB_CHARSET, HEBREW_CHARSET, ARABIC_CHARSET, GREEK_CHARSET, TURKISH_CHARSET, VIETNAMESE_CHARSET, THAI_CHARSET, EASTEUROPE_CHARSET, RUSSIAN_CHARSET, MAC_CHARSET, BALTIC_CHARSET: begin if (lParam.IndexOf(Tobject(LI)) = -1) then lParam.Add(Tobject(LI)); end; end; Result := 1; end; (* ---------------------------------------------------------------------------- *) procedure GetSupportedCharSets(const FaceName: String; CharSets: TList); var DC: THandle; LogFont: TLogFont; {$IFDEF gtDelphi2009Up} LWideString: WideString; I: Integer; {$ENDIF} begin DC := GetDC(GetDesktopWindow); if DC <> 0 then try FillChar(LogFont, SizeOf(LogFont), 0); {$IFDEF gtDelphi2009Up} LWideString := FaceName; for I := 0 to Length(LWideString) - 1 do LogFont.lfFaceName[I] := LWideString[I + 1]; {$ELSE} Move(FaceName[1], LogFont.lfFaceName, Length(FaceName)); {$ENDIF} LogFont.lfCharSet := DEFAULT_CHARSET; EnumFontFamiliesEx(DC, LogFont, @EnumFontFamExProc, lParam(CharSets), 0); finally ReleaseDC(GetDesktopWindow, DC) end end; (* ---------------------------------------------------------------------------- *) function GetHexOfStr(AString: AnsiString): AnsiString; begin Result := ''; SetLength(Result, Length(AString) * 2); BinToHex(PAnsiChar(AString), PAnsiChar(Result), Length(AString)); end; function GetHexOfStrw(AString: String): String; var Val: Integer; Len, LI: Integer; begin Result := ''; Len := Length(AString); for LI := 1 to Len do begin Val := Ord(AString[LI]); Result := Result + IntToHex(Val, 4); end; end; (* ---------------------------------------------------------------------------- *) function ColorToPDFColor(AColor: TColor): String; function PDFColor(HexCode: String): String; begin CheckSysColor(AColor); Result := Format('%1.4f', [StrToIntDef('$' + HexCode, 0) / 255]); if {$IFDEF gtDelphiXEUp} FormatSettings. {$ENDIF} DecimalSeparator <> '.' then Result := ReplaceString(Result, {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator, '.'); end; begin Result := Copy(IntToHex(ColorToRGB(AColor), 8), 3, 6); Result := PDFColor(Copy(Result, 5, 2)) + ' ' + PDFColor(Copy(Result, 3, 2)) + ' ' + PDFColor(Copy(Result, 1, 2)); end; (* ---------------------------------------------------------------------------- *) function TextSize(const Text: String; AFont: TFont): TSize; var DC: HDC; SaveFont: HFont; LSize: TSize; begin DC := GetDC(0); SaveFont := SelectObject(DC, AFont.Handle); GetTextExtentPoint32(DC, PChar(Text), Length(Text), LSize); SelectObject(DC, SaveFont); ReleaseDC(0, DC); Result := LSize; end; (* ---------------------------------------------------------------------------- *) function RightStr(const AText: String; const ACount: Integer): String; begin Result := Copy(WideString(AText), Length(WideString(AText)) + 1 - ACount, ACount); end; (* ---------------------------------------------------------------------------- *) function LeftStr(const AText: String; const ACount: Integer): String; begin Result := Copy(WideString(AText), 1, ACount); end; (* ---------------------------------------------------------------------------- *) function MidStr(const AText: String; const AStart, ACount: Integer): String; begin Result := Copy(WideString(AText), AStart, ACount); end; (* ---------------------------------------------------------------------------- *) function PosEx(const SubStr, S: String; Offset: Cardinal = 1): Integer; var I, X: Integer; Len, LenSubStr: Integer; begin if Offset = 1 then Result := Pos(SubStr, S) else begin I := Offset; LenSubStr := Length(SubStr); Len := Length(S) - LenSubStr + 1; while I <= Len do begin if S[I] = SubStr[1] then begin X := 1; while (X < LenSubStr) and (S[I + X] = SubStr[X + 1]) do Inc(X); if (X = LenSubStr) then begin Result := I; exit; end; end; Inc(I); end; Result := 0; end; end; (* ---------------------------------------------------------------------------- *) function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer; SearchString: String; Options: TStringSearchOptions): PChar; var SearchCount, I: Integer; C: Char; Direction: Shortint; ShadowMap: array [0 .. 256] of Char; CharMap: array [Char] of Char absolute ShadowMap; function FindNextWordStart(var BufPtr: PChar): Boolean; begin { (True XOR N) is equivalent to (not N) } { (False XOR N) is equivalent to (N) } { When Direction is forward (1), skip non delimiters, then skip delimiters. } { When Direction is backward (-1), skip delims, then skip non delims } {$IFDEF gtDelphi2009Up} while (SearchCount > 0) and ((Direction = 1) xor SysUtils.CharInSet(BufPtr^, WordDelimiters)) do {$ELSE} while (SearchCount > 0) and ((Direction = 1) xor (BufPtr^ in WordDelimiters)) do {$ENDIF} begin Inc(BufPtr, Direction); Dec(SearchCount); end; {$IFDEF gtDelphi2009Up} while (SearchCount > 0) and ((Direction = -1) xor SysUtils.CharInSet(BufPtr^, WordDelimiters)) do {$ELSE} while (SearchCount > 0) and ((Direction = -1) xor (BufPtr^ in WordDelimiters)) do {$ENDIF} begin Inc(BufPtr, Direction); Dec(SearchCount); end; Result := SearchCount > 0; if Direction = -1 then begin { back up one Char, to leave ptr on first non delim } Dec(BufPtr, Direction); Inc(SearchCount); end; end; begin Result := nil; if BufLen <= 0 then exit; if soDown in Options then begin Direction := 1; Inc(SelStart, SelLength); { start search past end of selection } SearchCount := BufLen - SelStart - Length(SearchString) + 1; if SearchCount < 0 then exit; if Longint(SelStart) + SearchCount > BufLen then exit; end else begin Direction := -1; Dec(SelStart, Length(SearchString)); SearchCount := SelStart + 1; end; if (SelStart < 0) or (SelStart > BufLen) then exit; Result := @Buf[SelStart]; { Using a Char map array is faster than calling AnsiUpper on every character } for C := Low(CharMap) to High(CharMap) do CharMap[C] := C; { Since CharMap is overlayed onto the ShadowMap and ShadowMap is 1 byte longer, we can use that extra byte as a guard NULL } ShadowMap[256] := #0; if not(soMatchCase in Options) then begin {$IFDEF MSWINDOWS} AnsiUpperBuff(PAnsiChar(@CharMap), SizeOf(CharMap)); AnsiUpperBuff(@SearchString[1], Length(SearchString)); {$ENDIF} {$IFDEF LINUX} AnsiStrUpper(@CharMap[#1]); SearchString := AnsiUpperCase(SearchString); {$ENDIF} end; while SearchCount > 0 do begin if (soWholeWord in Options) and (Result <> @Buf[SelStart]) then if not FindNextWordStart(Result) then Break; I := 0; while (CharMap[Result[I]] = SearchString[I + 1]) do begin Inc(I); if I >= Length(SearchString) then begin {$IFDEF gtDelphi2009Up} if (not(soWholeWord in Options)) or (SearchCount = 0) or SysUtils.CharInSet(Result[I], WordDelimiters) then {$ELSE} if (not(soWholeWord in Options)) or (SearchCount = 0) or (Result[I] in WordDelimiters) then {$ENDIF} exit; Break; end; end; Inc(Result, Direction); Dec(SearchCount); end; Result := nil; end; (* ---------------------------------------------------------------------------- *) function TryStrToInt(const S: String; out Value: Integer): Boolean; var E: Integer; begin Val(S, Value, E); Result := E = 0; end; (* ---------------------------------------------------------------------------- *) {$IFDEF gtDelphi5} function CurrentYear: Word; {$IFDEF MSWINDOWS} var SystemTime: TSystemTime; begin GetLocalTime(SystemTime); Result := SystemTime.wYear; end; {$ENDIF} {$IFDEF LINUX} var T: TTime_T; UT: TUnixTime; begin __time(@T); localtime_r(@T, UT); Result := UT.tm_year + 1900; end; {$ENDIF} (* ---------------------------------------------------------------------------- *) function IsLeadChar(C: AnsiChar): Boolean; begin Result := C in LeadBytes; end; (* ---------------------------------------------------------------------------- *) function NextCharIndex(const S: AnsiString; Index: Integer): Integer; begin Result := Index + 1; assert((Index > 0) and (Index <= Length(S))); if IsLeadChar(S[Index]) then Result := Index + StrCharLength(PAnsiChar(S) + Index - 1); end; (* ---------------------------------------------------------------------------- *) function StrCharLength(const Str: PAnsiChar): Integer; begin {$IFDEF LINUX} Result := mblen(Str, MB_CUR_MAX); if (Result = -1) then Result := 1; {$ENDIF} {$IFDEF MSWINDOWS} if SysLocale.FarEast and (Str^ <> #0) then Result := Integer(CharNextA(Str)) - Integer(Str) else Result := 1; {$ENDIF} end; (* ---------------------------------------------------------------------------- *) function GetEraYearOffset(const Name: string): Integer; var I: Integer; begin Result := 0; for I := Low(EraNames) to High(EraNames) do begin if EraNames[I] = '' then Break; if AnsiStrPos(PChar(EraNames[I]), PChar(Name)) <> nil then begin Result := EraYearOffsets[I]; exit; end; end; end; (* ---------------------------------------------------------------------------- *) function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean; var I: Integer; DayTable: PDayTable; begin Result := False; DayTable := @MonthDays[IsLeapYear(Year)]; if (Year >= 1) and (Year <= 9999) and (Month >= 1) and (Month <= 12) and (Day >= 1) and (Day <= DayTable^[Month]) then begin for I := 1 to Month - 1 do Inc(Day, DayTable^[I]); I := Year - 1; Date := I * 365 + I div 4 - I div 100 + I div 400 + Day - DateDelta; Result := True; end; end; (* ---------------------------------------------------------------------------- *) function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean; begin Result := False; if (Hour < HoursPerDay) and (Min < MinsPerHour) and (Sec < SecsPerMin) and (MSec < MSecsPerSec) then begin Time := (Hour * (MinsPerHour * SecsPerMin * MSecsPerSec) + Min * (SecsPerMin * MSecsPerSec) + Sec * MSecsPerSec + MSec) / MSecsPerDay; Result := True; end; end; (* ---------------------------------------------------------------------------- *) function GetDateOrder(const DateFormat: string): TDateOrder; var I: Integer; begin Result := doMDY; I := 1; while I <= Length(DateFormat) do begin case Chr(Ord(DateFormat[I]) and $DF) of 'E': Result := doYMD; 'Y': Result := doYMD; 'M': Result := doMDY; 'D': Result := doDMY; else Inc(I); Continue; end; exit; end; Result := doMDY; end; (* ---------------------------------------------------------------------------- *) procedure ScanBlanks(const S: string; var Pos: Integer); var I: Integer; begin I := Pos; while (I <= Length(S)) and (S[I] = ' ') do Inc(I); Pos := I; end; (* ---------------------------------------------------------------------------- *) function ScanNumber(const S: string; var Pos: Integer; var Number: Word; var CharCount: Byte): Boolean; var I: Integer; N: Word; begin Result := False; CharCount := 0; ScanBlanks(S, Pos); I := Pos; N := 0; while (I <= Length(S)) and (S[I] in ['0' .. '9']) and (N < 1000) do begin N := N * 10 + (Ord(S[I]) - Ord('0')); Inc(I); end; if I > Pos then begin CharCount := I - Pos; Pos := I; Number := N; Result := True; end; end; (* ---------------------------------------------------------------------------- *) function ScanString(const S: string; var Pos: Integer; const Symbol: string): Boolean; begin Result := False; if Symbol <> '' then begin ScanBlanks(S, Pos); if AnsiCompareText(Symbol, Copy(S, Pos, Length(Symbol))) = 0 then begin Inc(Pos, Length(Symbol)); Result := True; end; end; end; (* ---------------------------------------------------------------------------- *) function ScanChar(const S: string; var Pos: Integer; Ch: Char): Boolean; begin Result := False; ScanBlanks(S, Pos); if (Pos <= Length(S)) and (S[Pos] = Ch) then begin Inc(Pos); Result := True; end; end; (* ---------------------------------------------------------------------------- *) procedure ScanToNumber(const S: string; var Pos: Integer); begin while (Pos <= Length(S)) and not(S[Pos] in ['0' .. '9']) do begin if IsLeadChar(AnsiChar(S[Pos])) then Pos := NextCharIndex(S, Pos) else Inc(Pos); end; end; (* ---------------------------------------------------------------------------- *) function ScanDate(const S: string; var Pos: Integer; var Date: TDateTime): Boolean; var DateOrder: TDateOrder; N1, N2, N3, Y, M, D: Word; L1, L2, L3, YearLen: Byte; CenturyBase: Integer; EraName: string; EraYearOffset: Integer; function EraToYear(Year: Integer): Integer; begin {$IFDEF MSWINDOWS} if SysLocale.PriLangID = LANG_KOREAN then begin if Year <= 99 then Inc(Year, (CurrentYear + Abs(EraYearOffset)) div 100 * 100); if EraYearOffset > 0 then EraYearOffset := -EraYearOffset; end else Dec(EraYearOffset); {$ENDIF} Result := Year + EraYearOffset; end; begin Y := 0; M := 0; D := 0; YearLen := 0; Result := False; DateOrder := GetDateOrder(ShortDateFormat); EraYearOffset := 0; if ShortDateFormat[1] = 'g' then // skip over prefix text begin ScanToNumber(S, Pos); EraName := Trim(Copy(S, 1, Pos - 1)); EraYearOffset := GetEraYearOffset(EraName); end else if AnsiPos('e', ShortDateFormat) > 0 then EraYearOffset := EraYearOffsets[1]; if not(ScanNumber(S, Pos, N1, L1) and ScanChar(S, Pos, DateSeparator) and ScanNumber(S, Pos, N2, L2)) then exit; if ScanChar(S, Pos, DateSeparator) then begin if not ScanNumber(S, Pos, N3, L3) then exit; case DateOrder of doMDY: begin Y := N3; YearLen := L3; M := N1; D := N2; end; doDMY: begin Y := N3; YearLen := L3; M := N2; D := N1; end; doYMD: begin Y := N1; YearLen := L1; M := N2; D := N3; end; end; if EraYearOffset > 0 then Y := EraToYear(Y) else if (YearLen <= 2) then begin CenturyBase := CurrentYear - TwoDigitYearCenturyWindow; Inc(Y, CenturyBase div 100 * 100); if (TwoDigitYearCenturyWindow > 0) and (Y < CenturyBase) then Inc(Y, 100); end; end else begin Y := CurrentYear; if DateOrder = doDMY then begin D := N1; M := N2; end else begin M := N1; D := N2; end; end; ScanChar(S, Pos, DateSeparator); ScanBlanks(S, Pos); if SysLocale.FarEast and (System.Pos('ddd', ShortDateFormat) <> 0) then begin // ignore trailing text if ShortTimeFormat[1] in ['0' .. '9'] then // stop at time digit ScanToNumber(S, Pos) else // stop at time prefix repeat while (Pos <= Length(S)) and (S[Pos] <> ' ') do Inc(Pos); ScanBlanks(S, Pos); until (Pos > Length(S)) or (AnsiCompareText(TimeAMString, Copy(S, Pos, Length(TimeAMString))) = 0) or (AnsiCompareText(TimePMString, Copy(S, Pos, Length(TimePMString))) = 0); end; Result := TryEncodeDate(Y, M, D, Date); end; (* ---------------------------------------------------------------------------- *) function ScanTime(const S: string; var Pos: Integer; var Time: TDateTime): Boolean; var BaseHour: Integer; Hour, Min, Sec, MSec: Word; Junk: Byte; begin Result := False; BaseHour := -1; if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then BaseHour := 0 else if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then BaseHour := 12; if BaseHour >= 0 then ScanBlanks(S, Pos); if not ScanNumber(S, Pos, Hour, Junk) then exit; Min := 0; Sec := 0; MSec := 0; if ScanChar(S, Pos, TimeSeparator) then begin if not ScanNumber(S, Pos, Min, Junk) then exit; if ScanChar(S, Pos, TimeSeparator) then begin if not ScanNumber(S, Pos, Sec, Junk) then exit; if ScanChar(S, Pos, DecimalSeparator) then if not ScanNumber(S, Pos, MSec, Junk) then exit; end; end; if BaseHour < 0 then if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then BaseHour := 0 else if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then BaseHour := 12; if BaseHour >= 0 then begin if (Hour = 0) or (Hour > 12) then exit; if Hour = 12 then Hour := 0; Inc(Hour, BaseHour); end; ScanBlanks(S, Pos); Result := TryEncodeTime(Hour, Min, Sec, MSec, Time); end; (* ---------------------------------------------------------------------------- *) function TryStrToDate(const S: string; out Value: TDateTime): Boolean; var Pos: Integer; begin Pos := 1; Result := ScanDate(S, Pos, Value) and (Pos > Length(S)); end; (* ---------------------------------------------------------------------------- *) function TryStrToTime(const S: string; out Value: TDateTime): Boolean; var Pos: Integer; begin Pos := 1; Result := ScanTime(S, Pos, Value) and (Pos > Length(S)); end; (* ---------------------------------------------------------------------------- *) function TryStrToDateTime(const S: string; out Value: TDateTime): Boolean; var Pos: Integer; NumberPos: Integer; BlankPos, LastBlankPos, OrigBlankPos: Integer; LDate, LTime: TDateTime; Stop: Boolean; begin Result := True; Pos := 1; LTime := 0; // jump over all the non-numeric characters before the date data ScanToNumber(S, Pos); // date data scanned; searched for the time data if ScanDate(S, Pos, LDate) then begin // search for time data; search for the first number in the time data NumberPos := Pos; ScanToNumber(S, NumberPos); // the first number of the time data was found if NumberPos < Length(S) then begin // search between the end of date and the start of time for AM and PM // strings; if found, then ScanTime from this position where it is found BlankPos := Pos - 1; Stop := False; while (not Stop) and (BlankPos < NumberPos) do begin // blank was found; scan for AM/PM strings that may follow the blank if (BlankPos > 0) and (BlankPos < NumberPos) then begin Inc(BlankPos); // start after the blank OrigBlankPos := BlankPos; // keep BlankPos because ScanString modifies it Stop := ScanString(S, BlankPos, TimeAMString) or ScanString(S, BlankPos, 'AM') or ScanString(S, BlankPos, TimePMString) or ScanString(S, BlankPos, 'PM'); // ScanString jumps over the AM/PM string; if found, then it is needed // by ScanTime to correctly scan the time BlankPos := OrigBlankPos; end // no more blanks found; end the loop else Stop := True; // search of the next blank if no AM/PM string has been found if not Stop then begin LastBlankPos := BlankPos; BlankPos := PosEx(' ', S, LastBlankPos); end; end; // loop was forcely stopped; check if AM/PM has been found if Stop then // AM/PM has been found; check if it is before or after the time data if BlankPos > 0 then if BlankPos < NumberPos then // AM/PM is before the time number Pos := BlankPos else Pos := NumberPos // AM/PM is after the time number else Pos := NumberPos // the blank found is after the the first number in time data else Pos := NumberPos; // get the time data Result := ScanTime(S, Pos, LTime); // time data scanned with no errors if Result then if LDate >= 0 then Value := LDate + LTime else Value := LDate - LTime end // no time data; return only date data else Value := LDate; end // could not scan date data; try to scan time data else Result := TryStrToTime(S, Value) end; {$ENDIF} (* ---------------------------------------------------------------------------- *) function ReplaceString(const S, OldPattern, NewPattern: WideString) : WideString; var I: Integer; SearchStr, Str, OldPat: WideString; begin Result := ''; if S <> '' then if IsDBCSLeadByte(Byte(S[1])) then begin SearchStr := AnsiUpperCase(S); OldPat := AnsiUpperCase(OldPattern); Str := S; Result := ''; while SearchStr <> '' do begin I := AnsiPos(OldPat, SearchStr); if I = 0 then begin Result := Result + Str; Break; end; Result := Result + Copy(Str, 1, I - 1) + NewPattern; Str := Copy(Str, I + Length(OldPattern), MaxInt); SearchStr := Copy(SearchStr, I + Length(OldPat), MaxInt); end; end else begin SearchStr := AnsiUpperCase(S); OldPat := AnsiUpperCase(OldPattern); Str := S; Result := ''; while SearchStr <> '' do begin I := AnsiPos(OldPat, SearchStr); if I = 0 then begin Result := Result + Str; Break; end; Result := Result + Copy(Str, 1, I - 1) + NewPattern; Str := Copy(Str, I + Length(OldPattern), MaxInt); SearchStr := Copy(SearchStr, I + Length(OldPat), MaxInt); end; end; end; (* ---------------------------------------------------------------------------- *) function ReplaceStringPos(const S: String; Offset: Integer; OldPattern, NewPattern: String): String; var I: Integer; SearchStr, Str, OldPat: String; begin SearchStr := AnsiUpperCase(S); OldPat := AnsiUpperCase(OldPattern); Str := S; Result := ''; Result := Copy(Str, 1, Offset - 1); Str := Copy(Str, Offset, MaxInt); SearchStr := AnsiUpperCase(Str); I := AnsiPos(OldPat, SearchStr); if I = 0 then begin Result := Result + Str; exit; end; Result := Result + Copy(Str, 1, I - 1) + NewPattern; Result := Result + Copy(Str, I + Length(OldPattern), MaxInt); end; (* ---------------------------------------------------------------------------- *) procedure RemoveNullCharacters(var S: String); var I, j: Integer; begin j := 0; for I := 1 to Length(S) do if S[I] <> #0 then begin Inc(j); S[j] := S[I]; end; if j < Length(S) then SetLength(S, j); end; (* ---------------------------------------------------------------------------- *) function AnsiContainsText(const AText, ASubText: String): Boolean; begin Result := AnsiPos(AnsiUpperCase(ASubText), AnsiUpperCase(AText)) > 0; end; (* ---------------------------------------------------------------------------- *) {$IFNDEF gtDelphi6Up} procedure BinToHex(Buffer, Text: PChar; BufSize: Integer); const Convert: array [0 .. 15] of Char = '0123456789ABCDEF'; var I: Integer; begin for I := 0 to BufSize - 1 do begin Text[0] := Convert[Byte(Buffer[I]) shr 4]; Text[1] := Convert[Byte(Buffer[I]) and $F]; Inc(Text, 2); end; end; {$ENDIF} (* ---------------------------------------------------------------------------- *) function StringToEscapeString(AString: String): String; var LI, Tabs, Rem, Pos, I, Count: Integer; TempStr: String; begin Tabs := 8; Count := 8; Result := ''; TempStr := ''; for LI := 1 to Length(AString) do begin case AString[LI] of '(': begin Result := Result + '\('; Count := Count - 1; end; ')': begin Result := Result + '\)'; Count := Count - 1; end; '\': begin Result := Result + '\\'; Count := Count - 1; end; #13: begin Result := Result + '\r'; Count := Count - 1; end; #10: begin Result := Result + '\n'; Count := Count - 1; end; #9: begin Rem := 8 - Count; Pos := Tabs - Rem; for I := LI to (LI + Pos - 1) do begin TempStr := TempStr + ' '; Count := Count - 1; end; Result := Result + TempStr; TempStr := ''; end; #8: Result := Result + '\b'; #12: Result := Result + '\f'; else begin Result := Result + AString[LI]; Count := Count - 1; end; end; if (Count = 0) then Count := 8; end; end; (* ---------------------------------------------------------------------------- *) function GetCountOfSpaces(Spaces: Double; SingleSpaces: Double; UseDefault: Boolean): Integer; var Time: Integer; begin if not UseDefault then Time := round(Spaces / (Double(SingleSpaces) / round(CPixelsPerInch))) else Time := Floor(Spaces / SingleSpaces); Result := Time; end; (* ---------------------------------------------------------------------------- *) function GetRemainingSpaces(DataWidths: Double; TabSpaces: Double): Double; var Spaces, Extras: Double; begin if (DataWidths > TabSpaces) then begin Extras := DataWidths - TabSpaces; while Extras > TabSpaces do Extras := Extras - TabSpaces; Spaces := TabSpaces - Extras; end else Spaces := TabSpaces - DataWidths; Result := Spaces; end; (* ---------------------------------------------------------------------------- *) function ConvertTabsToSpaces(Str: String; Fonts: TFont; TabsStops: TStringList): String; var UseDefaultTab, IsVisited: Boolean; L, N, LI, Times, T, K: Integer; Space, Extra, DataWidth, SingleSpace, TabSpace, Diff, PrevTab: Double; Data: String; begin Data := ''; UseDefaultTab := False; IsVisited := False; L := 0; T := 0; K := 0; PrevTab := 0.0; Diff := 0.0; Space := 0.0; N := TabsStops.Count; Result := ''; for LI := 1 to Length(Str) do begin if Str[LI] = #9 then begin DataWidth := TextSize(Data, Fonts).cx; SingleSpace := TextSize(' ', Fonts).cx; // Conversion of Tab Value from Inches to Pixels TabSpace := (2.083 / 32) * Fonts.Size * CPixelsPerInch; // For none specified in the TStringlist if N = 0 then begin UseDefaultTab := True; Space := GetRemainingSpaces(DataWidth, TabSpace); end else if N = 1 then begin // For only 1 no. in TStringList if ((Double(DataWidth) / round(CPixelsPerInch)) > (StrToFloat(TabsStops.Strings[0]) / 25400)) then begin Extra := (Double(DataWidth) / round(CPixelsPerInch)) - (StrToFloat(TabsStops.Strings[0]) / 25400); while Extra > (StrToFloat(TabsStops.Strings[0]) / 25400) do Extra := Extra - (StrToFloat(TabsStops.Strings[0]) / 25400); Space := (StrToFloat(TabsStops.Strings[0]) / 25400) - Extra; end else Space := (StrToFloat(TabsStops.Strings[0]) / 25400) - (Double(DataWidth) / round(CPixelsPerInch)); end else begin // For more than 1 entries in TSringList if L < N then begin T := L; Diff := (StrToFloat(TabsStops.Strings[L]) / 25400) - PrevTab; end; if ((L + 1) < N) then begin if ((Double(DataWidth) / round(CPixelsPerInch)) > Diff) then begin Extra := (Double(DataWidth) / round(CPixelsPerInch)); while Extra > Diff do begin Extra := Extra - Diff; PrevTab := (StrToFloat(TabsStops.Strings[L]) / 25400); if (((L + 1) <= N) and (L = T)) then begin L := L + 1; T := L; Diff := (StrToFloat(TabsStops.Strings[L]) / 25400) - PrevTab; Space := Diff - Extra; end else begin UseDefaultTab := True; Space := GetRemainingSpaces(DataWidth, TabSpace); end; end; PrevTab := (StrToFloat(TabsStops.Strings[L]) / 25400); if (((L + 1) <= N) and (L = T)) then begin L := L + 1; end else begin UseDefaultTab := True; Space := GetRemainingSpaces(DataWidth, TabSpace); end; end else begin Space := Diff - (Double(DataWidth) / round(CPixelsPerInch)); PrevTab := (StrToFloat(TabsStops.Strings[L]) / 25400); if (((L + 1) <= N) and (L = T)) then begin L := L + 1; end else begin UseDefaultTab := True; Space := GetRemainingSpaces(DataWidth, TabSpace); end; end; end else begin if ((L = N) or (L = (N - 1))) then begin K := K + 1; if IsVisited then begin UseDefaultTab := True; Space := GetRemainingSpaces(DataWidth, TabSpace); end else begin Space := Diff - (Double(DataWidth) / round(CPixelsPerInch)); if K = 2 then IsVisited := True else L := L + 1; end; end else begin UseDefaultTab := True; Space := GetRemainingSpaces(DataWidth, TabSpace); end; end; end; Times := GetCountOfSpaces(Space, SingleSpace, UseDefaultTab); Result := Result + StringOfChar(' ', Times); Data := ''; end else begin Result := Result + Str[LI]; Data := Data + Str[LI]; end; end; end; (* ---------------------------------------------------------------------------- *) procedure FreeAndNil(var Obj); var Temp: Tobject; begin Temp := Tobject(Obj); Pointer(Obj) := nil; Temp.Free; end; (* ---------------------------------------------------------------------------- *) function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = 0): Integer; overload; begin if AValue then Result := ATrue else Result := AFalse; end; (* ---------------------------------------------------------------------------- *) function IfThen(AValue: Boolean; const ATrue: DWORD; const AFalse: DWORD = 0) : DWORD; overload; begin if AValue then Result := ATrue else Result := AFalse; end; (* ---------------------------------------------------------------------------- *) function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double = 0.0): Double; overload; begin if AValue then Result := ATrue else Result := AFalse; end; (* ---------------------------------------------------------------------------- *) function IfThen(AValue: Boolean; const ATrue: String; const AFalse: String = ''): String; overload; begin if AValue then Result := ATrue else Result := AFalse; end; (* ---------------------------------------------------------------------------- *) function DegreesToRadians(Degrees: Extended): Extended; begin Result := Degrees * (PI / 180); end; (* ---------------------------------------------------------------------------- *) function PixelsToPoints(X: Extended): Extended; begin Result := X / CPixelsPerInch * CInchesToPoints; end; (* ---------------------------------------------------------------------------- *) function PointsToPixels(X: Extended): Extended; begin Result := X * CPointsToPixels; end; (* ---------------------------------------------------------------------------- *) function RadiansToDegrees(Radians: Extended): Extended; begin Result := Radians * (180 / PI); end; (* ---------------------------------------------------------------------------- *) function ColorBGRToRGB(AColor: TColor): String; begin CheckSysColor(AColor); Result := IntToHex(GetRValue(AColor), 2) + IntToHex(GetGValue(AColor), 2) + IntToHex(GetBValue(AColor), 2); end; procedure CheckSysColor(var Color: TColor); const CgtSysColor = $FF000000; begin if (Color and CgtSysColor) = CgtSysColor then begin Color := Color and (not CgtSysColor); Color := GetSysColor(Color); end; end; (* ---------------------------------------------------------------------------- *) procedure SetControlsEnabled(AControl: TWinControl; AState: Boolean; AIgnoreList: TList = nil); const StateColor: array [Boolean] of TColor = (clInactiveBorder, clWindow); StatePenMode: array [Boolean] of TPenMode = (pmMask, pmCopy); var I: Integer; begin with AControl do for I := 0 to ControlCount - 1 do begin if (AIgnoreList <> nil) and (AIgnoreList.IndexOf(Controls[I]) <> -1) then Continue; if ((Controls[I] is TWinControl) and (TWinControl(Controls[I]).ControlCount > 0)) then SetControlsEnabled(TWinControl(Controls[I]), AState, AIgnoreList); if (Controls[I] is TCustomEdit) then THackWinControl(Controls[I]).Color := StateColor[AState] else if (Controls[I] is TCustomComboBox) then THackWinControl(Controls[I]).Color := StateColor[AState] else if (Controls[I] is TShape) then TShape(Controls[I]).Pen.Mode := StatePenMode[AState]; Controls[I].Enabled := AState; end; end; (* ---------------------------------------------------------------------------- *) function IsHex(AString: String): Boolean; var LI: Integer; LString: String; begin Result := False; LString := UpperCase(AString); for LI := 1 to Length(AString) do if (LString[LI] < '0') or ((AString[LI] > '9') and (AString[LI] < 'A')) or ((AString[LI] < 'A') and (AString[LI] > 'F')) then exit; Result := True; end; (* ---------------------------------------------------------------------------- *) function HexToByteArray(AHex: String): TgtByteArray; var LS: String; LI, LJ, LLength: Integer; begin SetLength(LS, 2); SetLength(Result, 0); LLength := Length(AHex); LI := 0; LJ := 0; while (LI < LLength) do begin while not(IsHex(AHex[LI])) do Inc(LI); LS[1] := AHex[LI]; Inc(LI); while not(IsHex(AHex[LI])) do Inc(LI); LS[2] := AHex[LI]; Inc(LI); SetLength(Result, Length(Result) + 1); if (HexToByteValue(PChar(LS), Result[LJ]) <> 0) then exit; Inc(LJ); end; end; (* ---------------------------------------------------------------------------- *) function HexToByteValue(AHex: String; out AByte: Byte): Integer; const Convert: array ['0' .. 'f'] of SmallInt = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15); var LI, LJ: Integer; begin Result := -1; AByte := 0; LJ := 0; if not IsHex(AHex) then exit; for LI := Length(AHex) downto 1 do begin AByte := AByte + Convert[AHex[LI]] * Trunc(Power(16, LJ)); Inc(LJ); end; Result := 0; end; (* ---------------------------------------------------------------------------- *) function HexToByteString(AHex: String): String; var LI: Integer; LS: String; LByte: Byte; begin SetLength(LS, 2); LI := 0; while (LI < Length(AHex)) do begin while not(IsHex(AHex[LI])) do Inc(LI); LS[1] := AHex[LI]; Inc(LI); while not(IsHex(AHex[LI])) do Inc(LI); LS[2] := AHex[LI]; Inc(LI); if (HexToByteValue(PChar(LS), LByte) <> 0) then exit else Result := Result + Chr(LByte); end; end; (* ---------------------------------------------------------------------------- *) procedure EscapeStringToByteArray(AEscapeString: AnsiString; var AByte: array of Byte); var LI, LJ, LLength: Integer; LChar: AnsiString; LOctal: AnsiString; LByte: Byte; LIndex: Integer; begin if (Length(AByte) = 0) then exit; LIndex := 0; SetLength(LChar, 1); SetLength(LOctal, 3); LI := 1; LLength := Length(AEscapeString); repeat if (AEscapeString[LI] = '\') then begin case AEscapeString[LI + 1] of 'n': begin LChar := LF; Inc(LI, 2); end; 'r': begin LChar := CR; Inc(LI, 2); end; 't': begin LChar := Tab; Inc(LI, 2); end; '(': begin LChar := '('; Inc(LI, 2); end; ')': begin LChar := ')'; Inc(LI, 2); end; '\': begin LChar := '\'; Inc(LI, 2); end; else begin {$IFDEF gtDelphi2009Up} if SysUtils.CharInSet(AEscapeString[LI + 1], ['0' .. '8']) then {$ELSE} if AEscapeString[LI + 1] in ['0' .. '8'] then {$ENDIF} begin Inc(LI); LJ := 1; LOctal := ''; {$IFDEF gtDelphi2009Up} while SysUtils.CharInSet(AEscapeString[LI], ['0' .. '8']) and (LJ <= 3) do {$ELSE} while (AEscapeString[LI] in ['0' .. '8']) and (LJ <= 3) do {$ENDIF} begin SetLength(LOctal, Length(LOctal) + 1); LOctal[LJ] := AEscapeString[LI]; Inc(LJ); Inc(LI); end; if (LJ = 2) then Insert('00', LOctal, 1) else if (LJ = 3) then Insert('0', LOctal, 1); if (LJ > 1) then begin OctalToByteValue(String(LOctal), LByte); LChar := AnsiChar(LByte); end; end else begin LChar := AEscapeString[LI]; Inc(LI); end; end end; (* End Case *) end else begin LChar := AEscapeString[LI]; Inc(LI); end; AByte[LIndex] := Ord(LChar[1]); Inc(LIndex); until (LI > LLength); end; (* ---------------------------------------------------------------------------- *) procedure EscapeStringToString(AEscapeString: String; var AString: String); var LI, LJ, LLength: Integer; LChar: String; LOctal: String; LByte: Byte; begin if AEscapeString = '' then exit; SetLength(LChar, 1); SetLength(LOctal, 3); LI := 1; LLength := Length(AEscapeString); SetLength(AString, 0); repeat if (AEscapeString[LI] = '\') then begin case AEscapeString[LI + 1] of 'n': begin LChar := LF; Inc(LI, 2); end; 'r': begin LChar := CR; Inc(LI, 2); end; 't': begin LChar := Tab; Inc(LI, 2); end; 'b': begin LChar := BS; Inc(LI, 2); end; 'f': begin LChar := FF; Inc(LI, 2); end; '(': begin LChar := '('; Inc(LI, 2); end; ')': begin LChar := ')'; Inc(LI, 2); end; '\': begin LChar := '\'; Inc(LI, 2); end; else begin {$IFDEF gtDelphi2009Up} if SysUtils.CharInSet(AEscapeString[LI + 1], ['0' .. '8']) then {$ELSE} if AEscapeString[LI + 1] in ['0' .. '8'] then {$ENDIF} begin Inc(LI); LJ := 1; LOctal := ''; {$IFDEF gtDelphi2009Up} while SysUtils.CharInSet(AEscapeString[LI], ['0' .. '8']) and {$ELSE} while (AEscapeString[LI] in ['0' .. '8']) and {$ENDIF} (LJ <= 3) do begin SetLength(LOctal, Length(LOctal) + 1); LOctal[LJ] := AEscapeString[LI]; Inc(LJ); Inc(LI); end; if (LJ = 2) then Insert('00', LOctal, 1) else if (LJ = 3) then Insert('0', LOctal, 1); if (LJ > 1) then begin OctalToByteValue(LOctal, LByte); LChar := Chr(LByte); end; end else begin LChar := AEscapeString[LI]; Inc(LI); end; end end; (* End Case *) end else begin LChar := AEscapeString[LI]; Inc(LI); end; SetLength(AString, (Length(AString) + 1)); AString[Length(AString)] := LChar[1]; until (LI > LLength); end; (* ---------------------------------------------------------------------------- *) procedure OctalToByteValue(AOctal: String; out AByte: Byte); const Convert: array ['0' .. '8'] of SmallInt = (0, 1, 2, 3, 4, 5, 6, 7, 8); var LI, LJ: Integer; begin AByte := 0; LJ := 0; if not IsOctal(AOctal) then exit; for LI := Length(AOctal) downto 1 do begin AByte := AByte + Convert[AOctal[LI]] * Trunc(Power(8, LJ)); Inc(LJ); end; end; (* ---------------------------------------------------------------------------- *) function IsOctal(AString: String): Boolean; var LI: Integer; begin Result := False; for LI := 1 to Length(AString) do if ((AString[LI] < '0') or (AString[LI] > '8')) then exit; Result := True; end; (* ---------------------------------------------------------------------------- *) function FloatToStrLocale(Value: Double): String; var LDesSep: Char; begin LDesSep := {$IFDEF gtDelphiXEUp} FormatSettings. {$ENDIF} DecimalSeparator; if Assigned(LockDecimalSep) then LockDecimalSep.Acquire else begin LockDecimalSep := TCriticalSection.Create; LockDecimalSep.Acquire end; try {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator := '.'; Result := FloatToStr(Value); {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator := LDesSep; finally LockDecimalSep.Release; end; end; { ------------------------------------------------------------------------------ } function CheckWin32Version(AMajor: Integer; AMinor: Integer = 0): Boolean; begin Result := (Win32MajorVersion > AMajor) or ((Win32MajorVersion = AMajor) and (Win32MinorVersion >= AMinor)); end; { ------------------------------------------------------------------------------ } function FloatToStrFLocale(Value: Extended; Format: TFloatFormat; Precision, Digits: Integer): String; var LDesSep: Char; begin LDesSep := {$IFDEF gtDelphiXEUp} FormatSettings. {$ENDIF} DecimalSeparator; if Assigned(LockDecimalSep) then LockDecimalSep.Acquire else begin LockDecimalSep := TCriticalSection.Create; LockDecimalSep.Acquire end; try {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator := '.'; Result := FloatToStrF(Value, Format, Precision, Digits); {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator := LDesSep; finally LockDecimalSep.Release; end; end; { ------------------------------------------------------------------------------ } function StrToFloatLocale(AString: String): Double; var LDesSep: Char; begin LDesSep := {$IFDEF gtDelphiXEUp} FormatSettings. {$ENDIF} DecimalSeparator; if Assigned(LockDecimalSep) then LockDecimalSep.Acquire else begin LockDecimalSep := TCriticalSection.Create; LockDecimalSep.Acquire end; try {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator := '.'; Result := StrToFloat(AString); {$IFDEF gtDelphiXEUp} FormatSettings.{$ENDIF} DecimalSeparator := LDesSep; finally LockDecimalSep.Release; end; end; { ------------------------------------------------------------------------------ } { General Procedure } function gtRect(Left, Top, Right, Bottom: Double): TgtRect; overload; begin Result.Left := Left; Result.Top := Top; Result.Right := Right; Result.Bottom := Bottom; end; { ------------------------------------------------------------------------------ } function gtRect(ARect: TgtRect; AFactor: Double): TgtRect; overload; begin with ARect do begin Result.Left := Left * AFactor; Result.Top := Top * AFactor; Result.Right := Right * AFactor; Result.Bottom := Bottom * AFactor; end; end; { ------------------------------------------------------------------------------ } function gtRect(ARect: TgtRect; AXFactor, AYFactor: Double): TgtRect; overload; begin with ARect do begin Result.Left := Left * AXFactor; Result.Top := Top * AYFactor; Result.Right := Right * AXFactor; Result.Bottom := Bottom * AYFactor; end; end; (* ---------------------------------------------------------------------------- *) { ------------------------------------------------------------------------------ } { MD5 } { ------------------------------------------------------------------------------ } { var BufferPad: MD5Buffer = ($80, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00); function F(AX, AY, AZ: DWORD): DWORD; begin Result := (AX and AY) or ((not AX) and AZ); end; function G(AX, AY, AZ: DWORD): DWORD; begin Result := (AX and AZ) or (AY and (not AZ)); end; function H(AX, AY, AZ: DWORD): DWORD; begin Result := AX xor AY xor AZ; end; function I(AX, AY, AZ: DWORD): DWORD; begin Result := AY xor (AX or (not AZ)); end; procedure Rot(var AX: DWORD; AN: Byte); begin AX := (AX shl AN) or (AX shr (32 - AN)); end; procedure FF(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(AA, F(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure GG(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(AA, G(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure HH(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(AA, H(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure II(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(AA, I(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; } { ------------------------------------------------------------------------------ } // Encode Count bytes at Source into (Count / 4) DWORDs at Target { procedure Encode(ASource, ATarget: Pointer; ACount: Longword); var S: PByte; T: PDWORD; I: Longword; begin S := ASource; T := ATarget; for I := 1 to ACount div 4 do begin T^ := S^; Inc(S); T^ := T^ or (S^ shl 8); Inc(S); T^ := T^ or (S^ shl 16); Inc(S); T^ := T^ or (S^ shl 24); Inc(S); Inc(T); end; end; { ------------------------------------------------------------------------------ } // Decode Count DWORDs at Source into (Count * 4) Bytes at Target { procedure Decode(ASource, ATarget: Pointer; ACount: Longword); var S: PDWORD; T: PByte; I: Longword; begin S := ASource; T := ATarget; for I := 1 to ACount do begin T^ := S^ and $FF; Inc(T); T^ := (S^ shr 8) and $FF; Inc(T); T^ := (S^ shr 16) and $FF; Inc(T); T^ := (S^ shr 24) and $FF; Inc(T); Inc(S); end; end; { ------------------------------------------------------------------------------ } { // Transform State according to first 64 bytes at Buffer procedure Transform(ABuffer: Pointer; var AState: MD5State); var A, B, C, D: DWORD; Block: MD5Block; begin Encode(ABuffer, @Block, 64); A := AState[0]; B := AState[1]; C := AState[2]; D := AState[3]; FF(A, B, C, D, Block[0], 7, $D76AA478); FF(D, A, B, C, Block[1], 12, $E8C7B756); FF(C, D, A, B, Block[2], 17, $242070DB); FF(B, C, D, A, Block[3], 22, $C1BDCEEE); FF(A, B, C, D, Block[4], 7, $F57C0FAF); FF(D, A, B, C, Block[5], 12, $4787C62A); FF(C, D, A, B, Block[6], 17, $A8304613); FF(B, C, D, A, Block[7], 22, $FD469501); FF(A, B, C, D, Block[8], 7, $698098D8); FF(D, A, B, C, Block[9], 12, $8B44F7AF); FF(C, D, A, B, Block[10], 17, $FFFF5BB1); FF(B, C, D, A, Block[11], 22, $895CD7BE); FF(A, B, C, D, Block[12], 7, $6B901122); FF(D, A, B, C, Block[13], 12, $FD987193); FF(C, D, A, B, Block[14], 17, $A679438E); FF(B, C, D, A, Block[15], 22, $49B40821); GG(A, B, C, D, Block[1], 5, $F61E2562); GG(D, A, B, C, Block[6], 9, $C040B340); GG(C, D, A, B, Block[11], 14, $265E5A51); GG(B, C, D, A, Block[0], 20, $E9B6C7AA); GG(A, B, C, D, Block[5], 5, $D62F105D); GG(D, A, B, C, Block[10], 9, $2441453); GG(C, D, A, B, Block[15], 14, $D8A1E681); GG(B, C, D, A, Block[4], 20, $E7D3FBC8); GG(A, B, C, D, Block[9], 5, $21E1CDE6); GG(D, A, B, C, Block[14], 9, $C33707D6); GG(C, D, A, B, Block[3], 14, $F4D50D87); GG(B, C, D, A, Block[8], 20, $455A14ED); GG(A, B, C, D, Block[13], 5, $A9E3E905); GG(D, A, B, C, Block[2], 9, $FCEFA3F8); GG(C, D, A, B, Block[7], 14, $676F02D9); GG(B, C, D, A, Block[12], 20, $8D2A4C8A); HH(A, B, C, D, Block[5], 4, $FFFA3942); HH(D, A, B, C, Block[8], 11, $8771F681); HH(C, D, A, B, Block[11], 16, $6D9D6122); HH(B, C, D, A, Block[14], 23, $FDE5380C); HH(A, B, C, D, Block[1], 4, $A4BEEA44); HH(D, A, B, C, Block[4], 11, $4BDECFA9); HH(C, D, A, B, Block[7], 16, $F6BB4B60); HH(B, C, D, A, Block[10], 23, $BEBFBC70); HH(A, B, C, D, Block[13], 4, $289B7EC6); HH(D, A, B, C, Block[0], 11, $EAA127FA); HH(C, D, A, B, Block[3], 16, $D4EF3085); HH(B, C, D, A, Block[6], 23, $4881D05); HH(A, B, C, D, Block[9], 4, $D9D4D039); HH(D, A, B, C, Block[12], 11, $E6DB99E5); HH(C, D, A, B, Block[15], 16, $1FA27CF8); HH(B, C, D, A, Block[2], 23, $C4AC5665); II(A, B, C, D, Block[0], 6, $F4292244); II(D, A, B, C, Block[7], 10, $432AFF97); II(C, D, A, B, Block[14], 15, $AB9423A7); II(B, C, D, A, Block[5], 21, $FC93A039); II(A, B, C, D, Block[12], 6, $655B59C3); II(D, A, B, C, Block[3], 10, $8F0CCC92); II(C, D, A, B, Block[10], 15, $FFEFF47D); II(B, C, D, A, Block[1], 21, $85845DD1); II(A, B, C, D, Block[8], 6, $6FA87E4F); II(D, A, B, C, Block[15], 10, $FE2CE6E0); II(C, D, A, B, Block[6], 15, $A3014314); II(B, C, D, A, Block[13], 21, $4E0811A1); II(A, B, C, D, Block[4], 6, $F7537E82); II(D, A, B, C, Block[11], 10, $BD3AF235); II(C, D, A, B, Block[2], 15, $2AD7D2BB); II(B, C, D, A, Block[9], 21, $EB86D391); Inc(AState[0], A); Inc(AState[1], B); Inc(AState[2], C); Inc(AState[3], D); end; { ------------------------------------------------------------------------------ } { // Initialize given Context procedure MD5Init(var AContext: MD5Context); begin with AContext do begin State[0] := $67452301; State[1] := $EFCDAB89; State[2] := $98BADCFE; State[3] := $10325476; Count[0] := 0; Count[1] := 0; ZeroMemory(@Buffer, SizeOf(MD5Buffer)); end; end; { ------------------------------------------------------------------------------ } // Update given Context to include Length bytes of Input { procedure MD5Update(var AContext: MD5Context; AInput: array of Byte; ALength: Longword); var Index: Longword; PartLen: Longword; I: Longword; begin with AContext do begin Index := (Count[0] shr 3) and $3F; Inc(Count[0], ALength shl 3); if Count[0] < (ALength shl 3) then Inc(Count[1]); Inc(Count[1], ALength shr 29); end; PartLen := 64 - Index; if ALength >= PartLen then begin CopyMemory(@AContext.Buffer[Index], @AInput, PartLen); Transform(@AContext.Buffer, AContext.State); I := PartLen; while I + 63 < ALength do begin Transform(@AInput[I], AContext.State); Inc(I, 64); end; Index := 0; end else I := 0; CopyMemory(@AContext.Buffer[Index], @AInput[I], ALength - I); end; { ------------------------------------------------------------------------------ } // Finalize given Context, create Digest and zeroize Context { procedure MD5Final(var AContext: MD5Context; var ADigest: MD5Digest); var Bits: MD5CBits; Index: Longword; PadLen: Longword; begin Decode(@AContext.Count, @Bits, 2); Index := (AContext.Count[0] shr 3) and $3F; if Index < 56 then PadLen := 56 - Index else PadLen := 120 - Index; MD5Update(AContext, BufferPad, PadLen); MD5Update(AContext, Bits, 8); Decode(@AContext.State, @ADigest, 4); ZeroMemory(@AContext, SizeOf(MD5Context)); end; {------------------------------------------------------------------------------- function GetHash(AInput: TgtByteArray; ALength: LongWord; var MD5Data: MD5Context): MD5Digest; overload; var LMD5Digest : MD5Digest; begin MD5Update(MD5Data, AInput, ALength); MD5Final(MD5Data, LMD5Digest); Result := LMD5Digest; end; ------------------------------------------------------------------------------- } { function GetHash(AInput: TStream): MD5Digest; overload; var LByteArray: array of Byte; LSize: Integer; LMD5Digest: MD5Digest; LI: Integer; begin MD5Init(MD5Data); LSize := Integer(AInput.Size); SetLength(LByteArray, LSize); AInput.Position := 0; AInput.Read(LByteArray[0], LSize); MD5Update(MD5Data, LByteArray, LSize); MD5Final(MD5Data, LMD5Digest); Result := LMD5Digest; end; {------------------------------------------------------------------------------- } { function CompareHash(const AHash1, AHash2: MD5Digest): Boolean; var LI: Integer; begin for LI := Low(AHash1) to High(AHash1) do begin Result := (AHash1[LI] = AHash2[LI]); if (not Result) then Break; end; end; } { TgtMD5Hash } constructor TgtMD5.Create; var LI: Integer; begin for LI := 0 to 63 do FBufferPad[LI] := $00; FBufferPad[0] := $80; Initilize; end; procedure TgtMD5.Encode(ASource, ATarget: Pointer; ACount: Longword); var S: PByte; T: PDWORD; I: Longword; begin S := ASource; T := ATarget; for I := 1 to ACount div 4 do begin T^ := S^; Inc(S); T^ := T^ or (S^ shl 8); Inc(S); T^ := T^ or (S^ shl 16); Inc(S); T^ := T^ or (S^ shl 24); Inc(S); Inc(T); end; end; { ------------------------------------------------------------------------------ } // Decode Count DWORDs at Source into (Count * 4) Bytes at Target procedure TgtMD5.Decode(ASource, ATarget: Pointer; ACount: Longword); var S: PDWORD; T: PByte; I: Longword; begin S := ASource; T := ATarget; for I := 1 to ACount do begin T^ := S^ and $FF; Inc(T); T^ := (S^ shr 8) and $FF; Inc(T); T^ := (S^ shr 16) and $FF; Inc(T); T^ := (S^ shr 24) and $FF; Inc(T); Inc(S); end; end; procedure TgtMD5.Finalize(var ADigest: MD5Digest); var Bits: MD5CBits; Index: Longword; PadLen: Longword; begin Decode(@FContext.Count, @Bits, 2); Index := (FContext.Count[0] shr 3) and $3F; if Index < 56 then PadLen := 56 - Index else PadLen := 120 - Index; Update(@FBufferPad[0], PadLen, True); Update(@Bits[0], 8, True); Decode(@FContext.State, @ADigest, 4); ZeroMemory(@FContext, SizeOf(MD5Context)); end; procedure TgtMD5.GetHash(AInput: TgtByteArray1; ALength: Int64; var ADigest: MD5Digest); begin Update(AInput, ALength, True); Finalize(ADigest); end; function TgtMD5.F(AX, AY, AZ: DWORD): DWORD; begin Result := (AX and AY) or ((not AX) and AZ); end; function TgtMD5.G(AX, AY, AZ: DWORD): DWORD; begin Result := (AX and AZ) or (AY and (not AZ)); end; function TgtMD5.H(AX, AY, AZ: DWORD): DWORD; begin Result := AX xor AY xor AZ; end; function TgtMD5.I(AX, AY, AZ: DWORD): DWORD; begin Result := AY xor (AX or (not AZ)); end; procedure TgtMD5.Rot(var AX: DWORD; AN: Byte); begin AX := (AX shl AN) or (AX shr (32 - AN)); end; procedure TgtMD5.FF(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin {$Q-,R-} Inc(AA, F(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure TgtMD5.GG(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(DWORD(AA), DWORD(G(AB, AC, AD)) + DWORD(AX) + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure TgtMD5.HH(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(AA, H(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure TgtMD5.II(var AA: DWORD; AB, AC, AD, AX: DWORD; AByte: Byte; ADWORD: DWORD); begin Inc(AA, I(AB, AC, AD) + AX + ADWORD); Rot(AA, AByte); Inc(AA, AB); end; procedure TgtMD5.Initilize; begin with FContext do begin State[0] := $67452301; State[1] := $EFCDAB89; State[2] := $98BADCFE; State[3] := $10325476; Count[0] := 0; Count[1] := 0; ZeroMemory(@Buffer, SizeOf(MD5Buffer)); end; end; procedure TgtMD5.Transform(ABuffer: Pointer; var AState: MD5State); var A, B, C, D: DWORD; Block: MD5Block; begin Encode(ABuffer, @Block, 64); A := AState[0]; B := AState[1]; C := AState[2]; D := AState[3]; FF(A, B, C, D, Block[0], 7, $D76AA478); FF(D, A, B, C, Block[1], 12, $E8C7B756); FF(C, D, A, B, Block[2], 17, $242070DB); FF(B, C, D, A, Block[3], 22, $C1BDCEEE); FF(A, B, C, D, Block[4], 7, $F57C0FAF); FF(D, A, B, C, Block[5], 12, $4787C62A); FF(C, D, A, B, Block[6], 17, $A8304613); FF(B, C, D, A, Block[7], 22, $FD469501); FF(A, B, C, D, Block[8], 7, $698098D8); FF(D, A, B, C, Block[9], 12, $8B44F7AF); FF(C, D, A, B, Block[10], 17, $FFFF5BB1); FF(B, C, D, A, Block[11], 22, $895CD7BE); FF(A, B, C, D, Block[12], 7, $6B901122); FF(D, A, B, C, Block[13], 12, $FD987193); FF(C, D, A, B, Block[14], 17, $A679438E); FF(B, C, D, A, Block[15], 22, $49B40821); GG(A, B, C, D, Block[1], 5, $F61E2562); GG(D, A, B, C, Block[6], 9, $C040B340); GG(C, D, A, B, Block[11], 14, $265E5A51); GG(B, C, D, A, Block[0], 20, $E9B6C7AA); GG(A, B, C, D, Block[5], 5, $D62F105D); GG(D, A, B, C, Block[10], 9, $2441453); GG(C, D, A, B, Block[15], 14, $D8A1E681); GG(B, C, D, A, Block[4], 20, $E7D3FBC8); GG(A, B, C, D, Block[9], 5, $21E1CDE6); GG(D, A, B, C, Block[14], 9, $C33707D6); GG(C, D, A, B, Block[3], 14, $F4D50D87); GG(B, C, D, A, Block[8], 20, $455A14ED); GG(A, B, C, D, Block[13], 5, $A9E3E905); GG(D, A, B, C, Block[2], 9, $FCEFA3F8); GG(C, D, A, B, Block[7], 14, $676F02D9); GG(B, C, D, A, Block[12], 20, $8D2A4C8A); HH(A, B, C, D, Block[5], 4, $FFFA3942); HH(D, A, B, C, Block[8], 11, $8771F681); HH(C, D, A, B, Block[11], 16, $6D9D6122); HH(B, C, D, A, Block[14], 23, $FDE5380C); HH(A, B, C, D, Block[1], 4, $A4BEEA44); HH(D, A, B, C, Block[4], 11, $4BDECFA9); HH(C, D, A, B, Block[7], 16, $F6BB4B60); HH(B, C, D, A, Block[10], 23, $BEBFBC70); HH(A, B, C, D, Block[13], 4, $289B7EC6); HH(D, A, B, C, Block[0], 11, $EAA127FA); HH(C, D, A, B, Block[3], 16, $D4EF3085); HH(B, C, D, A, Block[6], 23, $4881D05); HH(A, B, C, D, Block[9], 4, $D9D4D039); HH(D, A, B, C, Block[12], 11, $E6DB99E5); HH(C, D, A, B, Block[15], 16, $1FA27CF8); HH(B, C, D, A, Block[2], 23, $C4AC5665); II(A, B, C, D, Block[0], 6, $F4292244); II(D, A, B, C, Block[7], 10, $432AFF97); II(C, D, A, B, Block[14], 15, $AB9423A7); II(B, C, D, A, Block[5], 21, $FC93A039); II(A, B, C, D, Block[12], 6, $655B59C3); II(D, A, B, C, Block[3], 10, $8F0CCC92); II(C, D, A, B, Block[10], 15, $FFEFF47D); II(B, C, D, A, Block[1], 21, $85845DD1); II(A, B, C, D, Block[8], 6, $6FA87E4F); II(D, A, B, C, Block[15], 10, $FE2CE6E0); II(C, D, A, B, Block[6], 15, $A3014314); II(B, C, D, A, Block[13], 21, $4E0811A1); II(A, B, C, D, Block[4], 6, $F7537E82); II(D, A, B, C, Block[11], 10, $BD3AF235); II(C, D, A, B, Block[2], 15, $2AD7D2BB); II(B, C, D, A, Block[9], 21, $EB86D391); Inc(AState[0], A); Inc(AState[1], B); Inc(AState[2], C); Inc(AState[3], D); end; procedure TgtMD5.Update(AInput: array of Byte; ALength: Longword); var Index: Longword; PartLen: Longword; I: Longword; begin with FContext do begin Index := (Count[0] shr 3) and $3F; Inc(Count[0], ALength shl 3); if Count[0] < (ALength shl 3) then Inc(Count[1]); Inc(Count[1], ALength shr 29); end; PartLen := 64 - Index; if ALength >= PartLen then begin CopyMemory(@FContext.Buffer[Index], @AInput, PartLen); Transform(@FContext.Buffer, FContext.State); I := PartLen; while I + 63 < ALength do begin Transform(@AInput[I], FContext.State); Inc(I, 64); end; Index := 0; end else I := 0; CopyMemory(@FContext.Buffer[Index], @AInput[I], ALength - I); { with FContext do begin Index := (Count[0] shr 3) and $3f; Inc(Count[0], ALength shl 3); if Count[0] < (ALength shl 3) then Inc(Count[1]); Inc(Count[1], ALength shr 29); end; PartLen := 64 - Index; if ALength >= PartLen then begin CopyMemory(@FContext.Buffer[Index], AInput, PartLen); Transform(@FContext.Buffer, FContext.State); I := PartLen; while I + 63 < ALength do begin LP := AInput; Inc(LP, I); Transform(LP, FContext.State); Inc(I, 64); end; Index := 0; end else I := 0; LP := AInput; Inc(LP, I); CopyMemory(@FContext.Buffer[Index], LP, ALength - I); } end; procedure TgtMD5.Update(AInput: Pointer; ALength: Longword; Flag: Boolean); var Index: Longword; PartLen: Longword; I: Longword; LP: ^Byte; begin with FContext do begin Index := (Count[0] shr 3) and $3F; Inc(Count[0], ALength shl 3); if Count[0] < (ALength shl 3) then Inc(Count[1]); Inc(Count[1], ALength shr 29); end; PartLen := 64 - Index; if ALength >= PartLen then begin CopyMemory(@FContext.Buffer[Index], AInput, PartLen); Transform(@FContext.Buffer, FContext.State); I := PartLen; while I + 63 < ALength do begin LP := AInput; Inc(LP, I); Transform(LP, FContext.State); Inc(I, 64); end; Index := 0; end else I := 0; LP := AInput; Inc(LP, I); if Flag then CopyMemory(@FContext.Buffer[Index], LP, ALength - I); end; destructor TgtMD5.Destroy; begin inherited; end; procedure TgtMD5.GetHash(AInput: TStream; var ADigest: MD5Digest); var LByteArray: TgtBytearray1; LSize: Int64; begin LSize := Integer(AInput.Size); SetLength(LByteArray, LSize); AInput.Position := 0; AInput.Read(LByteArray[0], LSize); GetHash(LByteArray, LSize, ADigest); end; function TgtMD5.CompareHash(const AHash1, AHash2: MD5Digest): Boolean; var LI: Integer; begin for LI := Low(AHash1) to High(AHash1) do begin Result := (AHash1[LI] = AHash2[LI]); if (not Result) then Break; end; end; initialization LockDecimalSep := TCriticalSection.Create; finalization LockDecimalSep.Free; end.
unit NewsServer; interface uses Classes, Collection, News, RDOServer, RDOInterfaces, SyncObjs, Languages; type {$M+} TNewsServer = class public constructor Create( Port : integer; aPath : string; aLog : ILog ); destructor Destroy; override; private fPath : string; fNewsCenters : TLockableCollection; fDAConn : IRDOConnectionsServer; fDAServ : TRDOServer; fNewsLock : TCriticalSection; fLog : ILog; public property NewsCenters : TLockableCollection read fNewsCenters; published procedure RDOCreateNewsCenter ( World : widestring; DAAddr : widestring; DAPort : integer; LangId : widestring ); procedure RDOCreateNewspaper ( World, Name, Style, Town : widestring; aDAAddr : widestring; aDAPort : integer; LangId : widestring ); procedure RDOGenerateNewspapers( World : widestring; Date : TDateTime; aDAAddr : widestring; aDAPort : integer; LangId : widestring ); private function GetNewsCenter( World : string; Language : TLanguageId ) : TNewsCenter; private fAllowGenerate : boolean; public property AllowGenerate : boolean read fAllowGenerate write fAllowGenerate; end; {$M-} const tidRDOHook_NewsServer = 'NewsServer'; implementation uses SysUtils, IniFiles, FileCtrl, WinSockRDOConnectionsServer, NewsRegistry, Windows, Registry; constructor TNewsServer.Create( Port : integer; aPath : string; aLog : ILog ); procedure RegisterNewsServer; var Reg : TRegistry; begin try Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey( tidRegKey_News, true ) then Reg.WriteString( 'Path', fPath ) finally Reg.Free; end; except end end; begin inherited Create; fLog := aLog; fPath := aPath; fNewsCenters := TLockableCollection.Create( 0, rkBelonguer ); fNewsLock := TCriticalSection.Create; fDAConn := TWinSockRDOConnectionsServer.Create( Port ); fDAServ := TRDOServer.Create( fDAConn as IRDOServerConnection, 7, nil ); fDAServ.RegisterObject( tidRDOHook_NewsServer, integer(self) ); fDAConn.StartListening; fDAServ.SetCriticalSection( fNewsLock ); RegisterNewsServer; fLog.LogThis( 'News server started.' ); fAllowGenerate := true; end; destructor TNewsServer.Destroy; begin fDAServ.Free; fNewsCenters.Free; fNewsLock.Free; inherited; end; procedure TNewsServer.RDOCreateNewsCenter( World : widestring; DAAddr : widestring; DAPort : integer; LangId : widestring ); var NewsCenter : TNewsCenter; begin try fLog.LogThis( 'Creating news center for ' + World + '.' ); NewsCenter := GetNewsCenter( World, LangId ); if NewsCenter = nil then begin NewsCenter := TNewsCenter.Create( World, fPath, fLog, DAAddr, DAPort, LangId ); fNewsCenters.Insert( NewsCenter ); end; except on E : Exception do fLog.LogThis( 'ERROR: ' + E.Message ); end end; procedure TNewsServer.RDOCreateNewspaper( World, Name, Style, Town : widestring; aDAAddr : widestring; aDAPort : integer; LangId : widestring ); var NewsCenter : TNewsCenter; Newspaper : TNewspaper; //Properties : TStringList; //path : string; begin fLog.LogThis( 'Registering newspaper: ' + Name + ', world: ' + World + ', town: ' + Town + ', style : ' + Style ); try fNewsLock.Enter; try NewsCenter := GetNewsCenter( World, LangId ); if (Newscenter = nil) or (Newscenter <> nil) and (NewsCenter.GetNewspaper( Name ) = nil) then begin if NewsCenter = nil then begin NewsCenter := TNewsCenter.Create( World, fPath, fLog, aDAAddr, aDAPort, LangId ); fNewsCenters.Insert( NewsCenter ); end; Newspaper := TNewspaper.Create( Name, Style, Town, NewsCenter ); NewsCenter.Newspapers.Insert( Newspaper ); {path := fPath + tidPath_Newspaper + World + '\' + Name; ForceDirectories( path ); Properties := TStringList.Create; try Properties.Values['Name'] := Name; Properties.Values['Style'] := Style; Properties.Values['Town'] := Town; Properties.Values['LastIssue'] := '0'; Properties.SaveToFile( path + '\newspaper.ini' ); finally Properties.Free; end;} end; finally fNewsLock.Leave; end; except on E : Exception do fLog.LogThis( 'ERROR: ' + E.Message ); end; end; procedure TNewsServer.RDOGenerateNewspapers( World : widestring; Date : TDateTime; aDAAddr : widestring; aDAPort : integer; LangId : widestring ); var NewsCenter : TNewsCenter; begin if fAllowGenerate then try NewsCenter := GetNewsCenter( World, LangId ); if NewsCenter = nil then begin NewsCenter := TNewsCenter.Create( World, fPath, fLog, aDAAddr, aDAPort, LangId ); fNewsCenters.Insert( NewsCenter ); end; NewsCenter.RenderNewspapers( Date ); except on E : Exception do fLog.LogThis( 'ERROR: ' + E.Message ); end; end; function TNewsServer.GetNewsCenter( World : string; Language : TLanguageId ) : TNewsCenter; var i : integer; begin fNewsLock.Enter; try i := 0; while (i < fNewsCenters.Count) and (TNewsCenter(fNewsCenters[i]).Name <> World) and (TNewsCenter(fNewsCenters[i]).LangId <> Language) do inc( i ); if i < fNewsCenters.Count then result := TNewsCenter(fNewsCenters[i]) else result := nil; finally fNewsLock.Leave; end; end; end.
unit StockController; interface uses System.Classes, FireDAC.Comp.Client, FireDAC.Stan.Param, System.Generics.Collections, System.SysUtils, InventoryDM; type TStock = class private FStockId: Integer; FItemId: Integer; FQuantity: Integer; FUnitPrice: Double; FUpdated_Date: TDatetime; FItemName: String; FItemDescription: string; FComments: string; public property StockId: Integer read FStockId write FStockId; property ItemId: Integer read FItemId write FItemId; property ItemName: String read FItemName write FItemName; property ItemDescription: string read FItemDescription write FItemDescription; property Updated_Date: TDatetime read FUpdated_Date write FUpdated_Date; property Quantity: Integer read FQuantity write FQuantity; property UnitPrice: Double read FUnitPrice write FUnitPrice; property Comments: string read FComments write FComments; end; TStockList = class (TObjectList<TStock>) end; TStockController = class private FStockList: TStockList; FStockQry: TFDQuery; FOnListChanged: TNotifyEvent; function GetStocksSQL: string; public constructor Create; destructor Destroy; override; procedure LoadStocks; procedure BuildStocksQuery; procedure DoListChanged; procedure AddStock(const AStock: TStock); procedure DeleteStock(const AStock: TStock); procedure EditStock(const AStock: TStock); property StockList: TStockList read FStockList write FStockList; property OnListChanged: TNotifyEvent read FOnListChanged write FOnListChanged; end; implementation { TStockList } procedure TStockController.AddStock(const AStock: TStock); var LInsertQry: TFDQuery; begin LInsertQry := GetNewInventoryQuery; try LInsertQry.SQL.Text := 'insert into stationary_stocks ' + #13#10 + '(stock_id, item_id, available_item_count, last_updated_date, stock_comments, unit_price)' + #13#10 + 'values' + #13#10 + '(:stock_id, :item_id, :available_item_count, :last_updated_date, :stock_comments, :unit_price)'; LInsertQry.Prepare; LInsertQry.ParamByName('stock_id').AsInteger := NextInventorySequenceValue('GEN_STOCK_ID'); LInsertQry.ParamByName('item_id').AsInteger := AStock.ItemId; LInsertQry.ParamByName('available_item_count').AsInteger := AStock.Quantity; LInsertQry.ParamByName('last_updated_date').AsDateTime := AStock.Updated_Date; LInsertQry.ParamByName('unit_price').AsFloat := AStock.UnitPrice; LInsertQry.ParamByName('stock_comments').AsString := AStock.Comments; LInsertQry.ExecSQL; FStockList.Add(AStock); DoListChanged; finally LInsertQry.Free; end; end; procedure TStockController.DeleteStock(const AStock: TStock); var LDeleteQry: TFDQuery; begin LDeleteQry := GetNewInventoryQuery; try LDeleteQry.SQL.Text := 'delete from stationary_stocks where stock_id = :stock_id'; LDeleteQry.Prepare; LDeleteQry.ParamByName('stock_id').AsInteger := AStock.StockId; LDeleteQry.ExecSQL; FStockList.Remove(AStock); DoListChanged; finally LDeleteQry.Free; end; end; procedure TStockController.BuildStocksQuery; begin FStockQry.SQL.Text := GetStocksSQL; end; constructor TStockController.Create; begin FStockList := TStockList.Create; FStockQry := GetNewInventoryQuery; BuildStocksQuery; end; destructor TStockController.Destroy; begin FStockList.Free; FStockQry.Free; inherited; end; procedure TStockController.DoListChanged; begin if Assigned(FOnListChanged) then FOnListChanged(self); end; procedure TStockController.EditStock(const AStock: TStock); var LUpdateQry: TFDQuery; begin LUpdateQry := GetNewInventoryQuery; try LUpdateQry.SQL.Text := 'update stationary_stocks ' + #13#10 + 'set' + #13#10 + #9 + 'available_item_count =:available_item_count,' + #13#10 + #9 + 'last_updated_date =:last_updated_date,' + #13#10 + #9 + 'unit_price =:unit_price,' + #13#10 + #9 + 'stock_comments =:stock_comments' + #13#10 + 'where' + #13#10 + #9 + '1=1' + #13#10 + #9 + 'and stock_id =:stock_id'; LUpdateQry.Prepare; LUpdateQry.ParamByName('stock_id').AsInteger := AStock.StockId; LUpdateQry.ParamByName('available_item_count').AsInteger := AStock.Quantity; LUpdateQry.ParamByName('last_updated_date').Value := AStock.Updated_Date; LUpdateQry.ParamByName('unit_price').Value := AStock.UnitPrice; LUpdateQry.ParamByName('stock_comments').AsString := AStock.Comments; LUpdateQry.ExecSQL; DoListChanged; finally LUpdateQry.Free; end; end; function TStockController.GetStocksSQL: string; begin result := 'select' + #13#10 + #9 + 'ss.stock_id,' + #13#10 + #9 + 'ss.item_id,' + #13#10 + #9 + 'ss.available_item_count,' + #13#10 + #9 + 'ss.last_updated_date,' + #13#10 + #9 + 'ss.stock_comments,' + #13#10 + #9 + 'ss.unit_price,' + #13#10 + #9 + 'ii.item_name,' + #13#10 + #9 + 'ii.item_description' + #13#10 + 'from' + #13#10 + #9 + 'stationary_stocks ss' + #13#10 + #9 + 'left join inventory_items ii on ss.item_id = ii.item_id' + #13#10 + 'where' + #13#10 + #9 + '1=1' end; procedure TStockController.LoadStocks; var LStock: TStock; begin FStockList.Clear; FStockQry.Open; FStockQry.First; while not FStockQry.Eof do begin LStock := TStock.Create; LStock.StockId := FStockQry.FieldByName('stock_id').AsInteger; LStock.ItemId := FStockQry.FieldByName('item_id').AsInteger; LStock.ItemName := FStockQry.FieldByName('item_name').AsString; LStock.ItemDescription := FStockQry.FieldByName('item_description').AsString; LStock.Quantity := FStockQry.FieldByName('available_item_count').AsInteger; LStock.UnitPrice := FStockQry.FieldByName('unit_price').AsFloat; LStock.Updated_Date := FStockQry.FieldByName('last_updated_date').AsDateTime; LStock.Comments := FStockQry.FieldByName('stock_comments').AsString; FStockList.Add(LStock); FStockQry.Next; end; FStockQry.Close; DoListChanged; end; end.
unit mover; interface uses TypInfo, Contnrs, Controls, Classes, Windows, Forms, StdCtrls, ExtCtrls, Graphics, SysUtils; type TMethodArray = array of TMethod; TMover = class(TComponent) private FInReposition : boolean; FNodePositioning: Boolean; oldPos: TPoint; FNodes: TObjectList; FCurrentNodeControl: TWinControl; OnClickMethods : TMethodArray; MouseDownMethods : TMethodArray; MouseMoveMethods : TMethodArray; MouseUpMethods : TMethodArray; FMovableControls : TComponentList; FEnabled: boolean; function GetMovableControls: TComponentList; procedure SetEnabled(const Value: boolean); procedure CreateNodes; procedure SetNodesVisible(Visible: Boolean); procedure PositionNodes(AroundControl: TWinControl); procedure NodeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure NodeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure NodeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); public procedure Add(Control : TControl); property MovableControls : TComponentList read GetMovableControls; property Enabled : boolean read FEnabled write SetEnabled; property InReposition : boolean read FInReposition; constructor Create(AOwner : TComponent); override; destructor Destroy; override; published // must be published so that RTTI know about 'em procedure ControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ControlMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ControlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); end; implementation constructor TMover.Create(AOwner:TComponent); begin inherited Create(AOwner); FEnabled := false; FInReposition := false; FNodes := TObjectList.Create(False); CreateNodes; end; destructor TMover.Destroy; begin if Assigned(FMovableControls) then FMovableControls.Free; FNodes.Free; inherited; end; (*Destroy*) procedure TMover.ControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Enabled) AND (Sender is TWinControl) then begin FInReposition:=True; SetCapture(TWinControl(Sender).Handle); GetCursorPos(oldPos); PositionNodes(TWinControl(Sender)); end; end; procedure TMover.ControlMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); const minWidth = 20; minHeight = 20; var newPos: TPoint; frmPoint : TPoint; begin if inReposition then begin with TWinControl(Sender) do begin GetCursorPos(newPos); if ssShift in Shift then begin //resize Screen.Cursor := crSizeNWSE; frmPoint := ScreenToClient(Mouse.CursorPos); if frmPoint.X > minWidth then Width := frmPoint.X; if frmPoint.Y > minHeight then Height := frmPoint.Y; end else //move begin Screen.Cursor := crSize; Left := Left - oldPos.X + newPos.X; Top := Top - oldPos.Y + newPos.Y; oldPos := newPos; end; end; PositionNodes(TWinControl(Sender)); end; end; procedure TMover.ControlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if inReposition then begin Screen.Cursor := crDefault; ReleaseCapture; FInReposition := False; end; end; procedure TMover.CreateNodes; var Node: Integer; Panel: TPanel; begin for Node := 0 to 7 do begin Panel := TPanel.Create(self); with Panel do begin BevelOuter := bvNone; Color := clBlack; Name := 'Node' + IntToStr(Node); Width := 5; Height := 5; Parent := nil; Visible := false; FNodes.Add(Panel); case Node of 0,4: Cursor := crSizeNWSE; 1,5: Cursor := crSizeNS; 2,6: Cursor := crSizeNESW; 3,7: Cursor := crSizeWE; end; OnMouseDown := NodeMouseDown; OnMouseMove := NodeMouseMove; OnMouseUp := NodeMouseUp; end; end; end; function TMover.GetMovableControls: TComponentList; begin if FMovableControls = nil then begin FMovableControls := TComponentList.Create(false); end; result := FMovableControls; end; (*GetMovableControls*) procedure TMover.NodeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Enabled) AND (Sender is TWinControl) then begin FNodePositioning:=True; SetCapture(TWinControl(Sender).Handle); GetCursorPos(oldPos); end; end; procedure TMover.NodeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); const minWidth = 20; minHeight = 20; var newPos: TPoint; frmPoint : TPoint; OldRect: TRect; AdjL,AdjR,AdjT,AdjB: Boolean; begin if FNodePositioning then begin begin with TWinControl(Sender) do begin GetCursorPos(newPos); with FCurrentNodeControl do begin //resize Screen.Cursor := crSizeNWSE; frmPoint := FCurrentNodeControl.Parent.ScreenToClient(Mouse.CursorPos); OldRect := FCurrentNodeControl.BoundsRect; AdjL := False; AdjR := False; AdjT := False; AdjB := False; case FNodes.IndexOf(TWinControl(Sender)) of 0: begin AdjL := True; AdjT := True; end; 1: begin AdjT := True; end; 2: begin AdjR := True; AdjT := True; end; 3: begin AdjR := True; end; 4: begin AdjR := True; AdjB := True; end; 5: begin AdjB := True; end; 6: begin AdjL := True; AdjB := True; end; 7: begin AdjL := True; end; end; if AdjL then OldRect.Left := frmPoint.X; if AdjR then OldRect.Right := frmPoint.X; if AdjT then OldRect.Top := frmPoint.Y; if AdjB then OldRect.Bottom := frmPoint.Y; SetBounds(OldRect.Left,OldRect.Top,OldRect.Right - OldRect.Left,OldRect.Bottom - OldRect.Top); end; //move node Left := Left - oldPos.X + newPos.X; Top := Top - oldPos.Y + newPos.Y; oldPos := newPos; end; end; PositionNodes(FCurrentNodeControl); end; end; procedure TMover.NodeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FNodePositioning then begin Screen.Cursor := crDefault; ReleaseCapture; FNodePositioning := False; end; end; procedure TMover.PositionNodes(AroundControl: TWinControl); var Node,T,L,CT,CL,FR,FB,FT,FL: Integer; TopLeft: TPoint; begin FCurrentNodeControl := nil; if AroundControl = nil then Exit; for Node := 0 to 7 do begin with AroundControl do begin CL := (Width div 2) + Left -2; CT := (Height div 2) + Top -2; FR := Left + Width - 2; FB := Top + Height - 2; FT := Top - 2; FL := Left - 2; case Node of 0: begin T := FT; L := FL; end; 1: begin T := FT; L := CL; end; 2: begin T := FT; L := FR; end; 3: begin T := CT; L := FR; end; 4: begin T := FB; L := FR; end; 5: begin T := FB; L := CL; end; 6: begin T := FB; L := FL; end; 7: begin T := CT; L := FL; end; else T := 0; L := 0; end; TopLeft := Parent.ClientToScreen(Point(L,T)); end; with TPanel(FNodes[Node]) do begin Parent := AroundControl.Parent; TopLeft := Parent.ScreenToClient(TopLeft); Top := TopLeft.Y; Left := TopLeft.X; end; end; FCurrentNodeControl := AroundControl; SetNodesVisible(True); end; procedure TMover.Add(Control: TControl); begin MovableControls.Add(Control); end; procedure TMover.SetEnabled(const Value: boolean); var idx : integer; oldMethod : TMethod; newMethod : TMethod; nilMethod : TMethod; ctrl : TControl; begin if value = FEnabled then Exit; FEnabled := Value; if Enabled then begin OnClickMethods := nil; //clear; MouseDownMethods := nil; MouseMoveMethods := nil; MouseUpMethods := nil; nilMethod.Data := nil; nilMethod.Code := nil; SetLength(OnClickMethods,MovableControls.Count); SetLength(MouseDownMethods,MovableControls.Count); SetLength(MouseMoveMethods,MovableControls.Count); SetLength(MouseUpMethods,MovableControls.Count); //swap mouse related event handlers for idx := 0 to -1 + MovableControls.Count do begin ctrl := TControl(MovableControls[idx]); oldMethod := GetMethodProp(ctrl, 'OnClick'); OnClickMethods[idx].Code := oldMethod.Code; OnClickMethods[idx].Data := oldMethod.Data; SetMethodProp(ctrl, 'OnClick', nilMethod); oldMethod := GetMethodProp(ctrl, 'OnMouseDown'); MouseDownMethods[idx].Code := oldMethod.Code; MouseDownMethods[idx].Data := oldMethod.Data; newMethod.Code := self.MethodAddress('ControlMouseDown'); newMethod.Data := Pointer(self); SetMethodProp(ctrl, 'OnMouseDown', newMethod); oldMethod := GetMethodProp(ctrl, 'OnMouseMove'); MouseMoveMethods[idx].Code := oldMethod.Code; MouseMoveMethods[idx].Data := oldMethod.Data; newMethod.Code := self.MethodAddress('ControlMouseMove'); newMethod.Data := Pointer(self); SetMethodProp(ctrl, 'OnMouseMove', newMethod); oldMethod := GetMethodProp(ctrl, 'OnMouseUp'); MouseUpMethods[idx].Code := oldMethod.Code; MouseUpMethods[idx].Data := oldMethod.Data; newMethod.Code := self.MethodAddress('ControlMouseUp'); newMethod.Data := Pointer(self); SetMethodProp(ctrl, 'OnMouseUp', newMethod); end; end else //disabled begin //restore default Mouse related event handler for idx := 0 to -1 + MovableControls.Count do begin ctrl := TControl(MovableControls[idx]); if idx >= Length(OnClickMethods) then Break; oldMethod.Code := OnClickMethods[idx].Code; oldMethod.Data := OnClickMethods[idx].Data; SetMethodProp(ctrl, 'OnClick', oldMethod); oldMethod.Code := MouseDownMethods[idx].Code; oldMethod.Data := MouseDownMethods[idx].Data; SetMethodProp(ctrl, 'OnMouseDown', oldMethod); oldMethod.Code := MouseMoveMethods[idx].Code; oldMethod.Data := MouseMoveMethods[idx].Data; SetMethodProp(ctrl, 'OnMouseMove', oldMethod); oldMethod.Code := MouseUpMethods[idx].Code; oldMethod.Data := MouseUpMethods[idx].Data; SetMethodProp(ctrl, 'OnMouseUp', oldMethod); end; end; //refresh nodes if Self.MovableControls.IndexOf(FCurrentNodeControl) < 0 then FCurrentNodeControl := nil; PositionNodes(FCurrentNodeControl); SetNodesVisible(Enabled and (FCurrentNodeControl <> nil)); end; (*SetEnabled*) procedure TMover.SetNodesVisible(Visible: Boolean); var Node: Integer; begin for Node := 0 to 7 do begin TPanel(FNodes.Items[Node]).Visible := Visible; end; end; (*SetNodesVisible*) end.
unit uGenericDAO; interface uses System.Rtti, uTableName, uKeyField, System.SysUtils, System.TypInfo, Vcl.Dialogs, FireDAC.Comp.Client, uDM, Data.DB; type TGenericDAO = class private class function GetTableName<T: class>(Obj: T): String; class function Insert<T: class>(Obj: T): Integer; class procedure Update<T: class>(Obj: T); class function ValorString(AValor: Double): string; public class function Save<T: class>(Obj: T): Integer; class function SelectFrom<T: class>(Obj: T; Id: Integer): string; class function Select<T: class>(Obj: T; AMaisCampos: Boolean=True): string; end; implementation { TGenericDAO } class function TGenericDAO.GetTableName<T>(Obj: T): String; var Contexto: TRttiContext; TypObj: TRttiType; Atributo: TCustomAttribute; strTable: String; begin Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Atributo in TypObj.GetAttributes do begin if Atributo is TableName then Exit(TableName(Atributo).Name); end; end; class function TGenericDAO.Insert<T>(Obj: T): Integer; var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; strInsert, strFields, strValues: String; Atributo: TCustomAttribute; IsKey: Boolean; sValor: string; begin strInsert := ''; strFields := ''; strValues := ''; strInsert := 'INSERT INTO ' + GetTableName(Obj); Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Prop in TypObj.GetProperties do begin IsKey := False; for Atributo in Prop.GetAttributes do begin if Atributo is KeyField then IsKey := True; if Atributo is ForeingKey then Continue; if not IsKey then begin // strFields := strFields + Prop.Name + ','; strFields := strFields + FieldName(Atributo).Name + ','; case Prop.GetValue(TObject(Obj)).Kind of tkWChar, tkLString, tkWString, tkString, tkChar, tkUString: strValues := strValues + QuotedStr(Prop.GetValue(TObject(Obj)).AsString) + ','; tkInteger, tkInt64: begin if Prop.GetValue(TObject(Obj)).AsInteger < 0 then begin strValues := strValues + 'null,'; Continue; end; // else // strValues := strValues + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ','; if Atributo is FieldNull then begin if Prop.GetValue(TObject(Obj)).AsInteger = 0 then strValues := strValues + 'null,' else strValues := strValues + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ','; end else strValues := strValues + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ','; end; tkFloat: begin if Atributo is FieldDate then begin if Prop.GetValue(TObject(Obj)).AsExtended = 0 then strValues := strValues + 'null,' else strValues := strValues + QuotedStr(FormatDateTime('yyyyMMdd', Prop.GetValue(TObject(Obj)).AsExtended)) + ','; end else if Atributo is FieldTime then begin if Prop.GetValue(TObject(Obj)).AsExtended = 0 then strValues := strValues + 'null,' else strValues := strValues + QuotedStr(FormatDateTime('hh:mm:ss', Prop.GetValue(TObject(Obj)).AsExtended)) + ','; end else begin sValor := ValorString(Prop.GetValue(TObject(Obj)).AsExtended); // strValues := strValues + FloatToStr(Prop.GetValue(TObject(Obj)).AsExtended) + ','; strValues := strValues + sValor + ','; end; end; tkEnumeration: begin if Prop.GetValue(TObject(Obj)).AsBoolean then strValues := strValues + '1,' else strValues := strValues + '0,'; end; else raise Exception.Create('Tipo não Suportado'); end; end; end; end; strFields := Copy(strFields, 1, Length(strFields) - 1); strValues := Copy(strValues, 1, Length(strValues) - 1); strInsert := strInsert + '(' + strFields + ') VALUES (' + strValues + '); SELECT SCOPE_IDENTITY()'; Result := dm.Conexao.ExecSQLScalar(strInsert); end; class function TGenericDAO.SelectFrom<T>(Obj: T; Id: Integer): string; var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; strTabela, strFields: string; Atributo: TCustomAttribute; strKeyField: string; begin strFields := ''; strTabela := GetTableName(Obj); Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Prop in TypObj.GetProperties do begin for Atributo in Prop.GetAttributes do begin if Atributo is KeyField then strKeyField := KeyField(Atributo).Name; if Atributo is ForeingKey then Continue; strFields := strFields + FieldName(Atributo).Name + ','; end; end; strFields := Copy(strFields, 1, Length(strFields) - 1); Result := 'SELECT ' + strFields + ' FROM ' + strTabela + ' WHERE ' + strKeyField + ' = ' + IntToStr(Id); end; class function TGenericDAO.Save<T>(Obj: T): Integer; var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; Atributo: TCustomAttribute; isKey: Boolean; Id: Integer; begin Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Prop in TypObj.GetProperties do begin Result := 0; isKey := False; for Atributo in Prop.GetAttributes do begin if Atributo is KeyField then begin id := Prop.GetValue(TObject(Obj)).AsInteger; if Id <= 0 then Result := Insert<T>(Obj) else begin Update<T>(Obj); Result := Id; end; isKey := True; Break; end; end; if isKey then Break; end; end; class function TGenericDAO.Select<T>(Obj: T; AMaisCampos: Boolean): string; var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; strTabela, strFields: string; Atributo: TCustomAttribute; begin strFields := ''; strTabela := GetTableName(Obj); Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Prop in TypObj.GetProperties do begin for Atributo in Prop.GetAttributes do begin if Atributo is ForeingKey then Continue; strFields := strFields + FieldName(Atributo).Name + ','; end; end; if AMaisCampos = False then strFields := Copy(strFields, 1, Length(strFields)- 1); Result := 'SELECT ' + strFields; end; class procedure TGenericDAO.Update<T>(Obj: T); var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; strUpdate, strSet, strKeyField, strKeyValue: String; Atributo: TCustomAttribute; isKey: Boolean; sValor: string; begin strUpdate := ''; strSet := ''; strKeyField := ''; strKeyValue := ''; strUpdate := 'UPDATE ' + GetTableName(Obj); Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Prop in TypObj.GetProperties do begin isKey := False; for Atributo in Prop.GetAttributes do begin if Atributo is KeyField then begin strKeyField := KeyField(Atributo).Name; strKeyValue := IntToStr(Prop.GetValue(TObject(Obj)).AsInteger); isKey := True; end; if isKey then Continue; if Atributo is ForeingKey then Continue; // strSet := strSet + Prop.Name + ' = '; strSet := strSet + FieldName(Atributo).Name + ' = '; case Prop.GetValue(TObject(Obj)).Kind of tkWChar, tkLString, tkWString, tkString,tkChar, tkUString: strSet := strSet + QuotedStr(Prop.GetValue(TObject(Obj)).AsString) + ','; tkInteger, tkInt64: begin if Prop.GetValue(TObject(Obj)).AsInteger < 0 then begin strSet := strSet + 'null' + ','; Continue; end; // else // strSet := strSet + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ','; if Atributo is FieldNull then begin if Prop.GetValue(TObject(Obj)).AsInteger = 0 then strSet := strSet + 'null' + ',' else strSet := strSet + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ','; end else strSet := strSet + IntToStr(Prop.GetValue(TObject(Obj)).AsInteger) + ','; end; tkEnumeration: begin if Prop.GetValue(TObject(Obj)).AsBoolean then strSet := strSet + '1,' else strSet := strSet + '0,'; end; tkFloat: if Atributo is FieldDate then begin if Prop.GetValue(TObject(Obj)).AsExtended = 0 then strSet := strSet + 'null,' else strSet := strSet + QuotedStr(FormatDateTime('yyyyMMdd', Prop.GetValue(TObject(Obj)).AsExtended)) + ','; end else if Atributo is FieldTime then begin if Prop.GetValue(TObject(Obj)).AsExtended = 0 then strSet := strSet + 'null,' else strSet := strSet + QuotedStr(FormatDateTime('hh:mm:ss', Prop.GetValue(TObject(Obj)).AsExtended)) + ','; end else begin sValor := ValorString(Prop.GetValue(TObject(Obj)).AsExtended); // sValor := FloatToStr(Prop.GetValue(TObject(Obj)).AsExtended); // sValor := StringReplace(sValor, ',','.', [rfReplaceAll]); strSet := strSet + sValor + ','; end else raise Exception.Create('Tipo não Suportado!'); end; end; end; strSet := Copy(strSet, 1, Length(strSet) - 1); strUpdate := strUpdate + ' SET ' + strSet + ' WHERE ' + strKeyField + ' = ' + strKeyValue; dm.Conexao.ExecSQL(strUpdate); end; class function TGenericDAO.ValorString(AValor: Double): string; var sValor: string; begin sValor := FloatToStr(AValor); sValor := StringReplace(sValor, ',','.', [rfReplaceAll]); Result := sValor; end; end.
object FormFindText: TFormFindText Left = 298 Top = 346 ActiveControl = edText BorderStyle = bsDialog Caption = 'Search' ClientHeight = 85 ClientWidth = 346 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Shell Dlg' Font.Style = [] OldCreateOrder = False Position = poScreenCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 8 Top = 10 Width = 49 Height = 13 Caption = '&Find what:' FocusControl = edText end object btnOk: TButton Left = 264 Top = 8 Width = 75 Height = 25 Caption = 'Find' Default = True ModalResult = 1 TabOrder = 3 end object btnCancel: TButton Left = 264 Top = 40 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 4 end object chkWords: TCheckBox Left = 8 Top = 40 Width = 249 Height = 17 Caption = '&Whole words only' TabOrder = 1 end object chkCase: TCheckBox Left = 8 Top = 58 Width = 249 Height = 17 Caption = '&Case sensitive' TabOrder = 2 end object edText: TComboBox Left = 72 Top = 8 Width = 185 Height = 21 ItemHeight = 13 TabOrder = 0 end end
unit uMultiTask; {$mode objfpc}{$H+} interface uses Classes, SysUtils, {$IF defined(windows)} Windows, {$ELSEIF defined(freebsd) or defined(darwin)} ctypes, sysctl, {$ELSEIF defined(linux)} {$linklib c} ctypes, {$ENDIF} uCS, uMultiTaskQueue; type tMultiTask = class; tMultiTaskThread = class; tOn_Task_Start_Proc = procedure(const task: tMultiTaskItem); tOn_Task_Start_Method = procedure(const method_name: string; const task: tMultiTaskItem) of object; tOn_BeforeAfter_Task_Method = procedure(const task: tMultiTaskItem; const thrd: tMultiTaskThread) of object; tOnExceptionMethod = procedure (const Task : tMultiTaskItem; const e: Exception) of object; tOnLogMethod = procedure (const s : string) of object; { tMultiTaskThread } tMultiTaskThread = class(tThread) private CS : tCS; fID: integer; fMultiTask: tMultiTask; fHaveNewWork: PRTLEvent; fTask: tMultiTaskItem; function getTask: tMultiTaskItem; procedure setTask(AValue: tMultiTaskItem); procedure _Working(const Task : tMultiTaskItem); procedure _Working_Done; public constructor Create(MultiTask: tMultiTask); destructor Destroy(); override; procedure Execute; override; function Working: boolean; function WorkingOn(const Task: tMultiTaskItem): boolean; procedure Wake_Up_For_New_Work(); procedure Sleep_To_New_Work(); property ID: integer read fID; property Task : tMultiTaskItem read getTask write setTask; end; { tMultiTask } tMultiTask = class private fOnException: tOnExceptionMethod; fOnLog: tOnLogMethod; fOn_Before_Task_Method: tOn_BeforeAfter_Task_Method; fOn_After_Task_Method: tOn_BeforeAfter_Task_Method; fOn_Task_Run_Method: tOn_Task_Start_Method; fOn_Task_Run_Proc: tOn_Task_Start_Proc; fPriorities_Enabled: boolean; fTask_Queue: tMultiTaskQueue; fTThreadPriority: TThreadPriority; gefOn_Task_Run_Method: tOn_Task_Start_Method; fPin_Thread_To_Core: boolean; fThread_Count: byte; fAsync_Run: boolean; fAnyThreadDoneWork: PRTLEvent; function Any_Thread_Working: boolean; function getCores_Count: byte; procedure setAsync_Run(AValue: boolean); procedure setOn_Task_Run_Method(AValue: tOn_Task_Start_Method); procedure setOn_Task_Run_Proc(AValue: tOn_Task_Start_Proc); procedure setPin_Thread_To_Core(AValue: boolean); procedure setThread_Count(AValue: byte); procedure setTThreadPriority(AValue: TThreadPriority); procedure Update_Thread_Configs; procedure On_New_Task_Enqeued; procedure Log(const s : string); procedure Exception(const Task : tMultiTaskItem; const e: Exception); protected fThreadList: TList; procedure Thread_Work(thrd: tMultiTaskThread); public constructor Create; destructor Destroy; override; procedure Start; procedure Stop; procedure WaitFor; function PriorityByID(const id : byte; const unique : boolean) : tMultitaskEnQueueFlags; procedure Enqueue(const proc: tTaskProc; const params: array of const; const flags : tMultitaskEnQueueFlags = [teLast]); procedure Enqueue(const method: tTaskMethod; const params: array of const; const flags : tMultitaskEnQueueFlags = [teLast]; const obj : tObject = nil); function Thread_Running_Count : Byte; function Thread_Running_Count_WO_Calling_Thread : Byte; function Task_Running : String; function isTaskRunning(const Data: tMultiTaskItem): boolean; property Cores_Count: byte read getCores_Count; property Thread_Count: byte read fThread_Count write setThread_Count; property Pin_Thread_To_Core: boolean read fPin_Thread_To_Core write setPin_Thread_To_Core; property Thread_Priorities: TThreadPriority read fTThreadPriority write setTThreadPriority; property Async_Run: boolean read fAsync_Run write setAsync_Run; property Priorities_Enabled : boolean read fPriorities_Enabled write fPriorities_Enabled; property On_Before_Task_Method: tOn_BeforeAfter_Task_Method read fOn_Before_Task_Method write fOn_Before_Task_Method; property On_After_Task_Method: tOn_BeforeAfter_Task_Method read fOn_After_Task_Method write fOn_After_Task_Method; property Task_Queue: tMultiTaskQueue read fTask_Queue; // slouzi k nastaveni parametru dane metody, bez teto definice se vsechny tasky spousti bez parametru ! property On_Task_Run_Proc: tOn_Task_Start_Proc read fOn_Task_Run_Proc write setOn_Task_Run_Proc; property On_Task_Run_Method: tOn_Task_Start_Method read fOn_Task_Run_Method write setOn_Task_Run_Method; property OnLog : tOnLogMethod read fOnLog write fOnLog; property OnException : tOnExceptionMethod read fOnException write fOnException; end; implementation {$IFDEF MultiTaskLOG} uses StrUtils; {$ENDIF} { tMultiTaskThread } constructor tMultiTaskThread.Create(MultiTask: tMultiTask); begin inherited Create(True); CS := InitCS; FreeOnTerminate := False; fHaveNewWork := RTLEventCreate; fMultiTask := MultiTask; end; destructor tMultiTaskThread.Destroy; begin CS.Free; RTLeventdestroy(fHaveNewWork); inherited Destroy; end; procedure tMultiTaskThread.Execute; begin while not Terminated do fMultiTask.Thread_Work(self); end; function tMultiTaskThread.getTask: tMultiTaskItem; begin CS.Enter('getTask'); try result := fTask; finally CS.Leave; end; end; procedure tMultiTaskThread.setTask(AValue: tMultiTaskItem); begin CS.Enter('setTask'); try fTask := AValue; finally CS.Leave; end; end; procedure tMultiTaskThread._Working_Done; begin CS.Enter('Work done'); try fTask := nil; finally CS.Leave; end; end; procedure tMultiTaskThread.Sleep_To_New_Work; begin RtlEventWaitFor(fHaveNewWork, 1000); RTLeventResetEvent(fHaveNewWork); end; procedure tMultiTaskThread.Wake_Up_For_New_Work; begin RtlEventSetEvent(fHaveNewWork); end; function tMultiTaskThread.Working: boolean; begin CS.Enter('Are we Working ?'); try Result := fTask <> nil; finally CS.Leave; end; end; function tMultiTaskThread.WorkingOn(const Task : tMultiTaskItem) : boolean; begin CS.Enter('Are we Working on task X ?'); try Result := (fTask <> nil) and (Task.AsPascalSourceString = self.ftask.AsPascalSourceString); finally CS.Leave; end; end; procedure tMultiTaskThread._Working(const Task: tMultiTaskItem); begin CS.Enter('New work arived'); try fTask := Task; finally CS.Leave; end; end; { tMultiTask } constructor tMultiTask.Create; begin inherited; fAnyThreadDoneWork := RTLEventCreate; fThreadList := TList.Create; fTask_Queue := tMultiTaskQueue.Create(self); fTask_Queue.On_New_Task := @On_New_Task_Enqeued; fPriorities_Enabled:=true; Thread_Count := Cores_Count; Pin_Thread_To_Core := False; Update_Thread_Configs; end; destructor tMultiTask.Destroy; begin RTLeventdestroy(fAnyThreadDoneWork); fThreadList.Free; inherited Destroy; end; procedure tMultiTask.Enqueue(const method: tTaskMethod; const params: array of const; const flags: tMultitaskEnQueueFlags; const obj: tObject); var fl : tMultitaskEnQueueFlags; begin try fl := flags; if not fPriorities_Enabled then fl -= [teFirst,teHighPriority,teNormalPriority,teLowPriority,teLast]; fTask_Queue.Enqueue(method, params, fl, obj); except on E:Exception do Log('Exception in Enqueue method : ' + E.Message); end; end; procedure tMultiTask.Enqueue(const proc: tTaskProc; const params: array of const; const flags: tMultitaskEnQueueFlags); var fl : tMultitaskEnQueueFlags; begin try fl := flags; if not fPriorities_Enabled then fl -= [teFirst,teHighPriority,teNormalPriority,teLowPriority,teLast]; fTask_Queue.Enqueue(proc, params, fl); except on E:Exception do Log('Exception in Enqueue procedure : ' + E.Message); end; end; procedure tMultiTask.Exception(const Task: tMultiTaskItem; const e: Exception); begin if assigned(fOnException) then fOnException(task,e); end; {$IFDEF Linux} const _SC_NPROCESSORS_ONLN = 83; function sysconf(i: cint): clong; cdecl; external Name 'sysconf'; {$ENDIF} function tMultiTask.getCores_Count: byte; {$IF defined(windows)} var i: integer; ProcessAffinityMask, SystemAffinityMask: DWORD_PTR; Mask: DWORD; SystemInfo: SYSTEM_INFO; {$ENDIF} begin {$IF defined(windows)} //returns total number of processors available to system including logical hyperthreaded processors begin if GetProcessAffinityMask(GetCurrentProcess, ProcessAffinityMask, SystemAffinityMask) then begin Result := 0; for i := 0 to 31 do begin Mask := DWord(1) shl i; if (ProcessAffinityMask and Mask) <> 0 then Inc(Result); end; end else begin //can't get the affinity mask so we just report the total number of processors GetSystemInfo(SystemInfo); Result := SystemInfo.dwNumberOfProcessors; end; end; {$ELSEIF defined(linux)} begin Result := sysconf(_SC_NPROCESSORS_ONLN); end; {$ELSE} begin Result := 1; end; {$ENDIF} end; function tMultiTask.isTaskRunning(const Data: tMultiTaskItem): boolean; var i: byte; thrd: tMultiTaskThread; begin result := false; for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); if (TThread.CurrentThread.ThreadID <> thrd.ThreadID) and (thrd.WorkingOn(Data)) then begin Exit(true); end; end; end; procedure tMultiTask.Log(const s: string); begin if assigned(fOnLog) then fOnLog(s); end; procedure tMultiTask.On_New_Task_Enqeued; var i: byte; thrd: tMultiTaskThread; begin for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); thrd.Wake_Up_For_New_Work(); end; end; function tMultiTask.PriorityByID(const id: byte; const unique: boolean): tMultitaskEnQueueFlags; begin case id of 1 : result := [teFirst]; 2 : result := [teHighPriority]; 3 : result := [teNormalPriority]; 4 : result := [teLowPriority]; 5 : result := [teLast]; end; if unique then result += [teUnique]; end; procedure tMultiTask.setAsync_Run(AValue: boolean); begin if fAsync_Run = AVAlue then Exit; fAsync_Run := AVAlue; end; procedure tMultiTask.setOn_Task_Run_Method(AValue: tOn_Task_Start_Method); begin if fOn_Task_Run_Method = AValue then Exit; fOn_Task_Run_Method := AValue; fOn_Task_Run_Proc := nil; end; procedure tMultiTask.setOn_Task_Run_Proc(AValue: tOn_Task_Start_Proc); begin if fOn_Task_Run_Proc = AValue then Exit; fOn_Task_Run_Proc := AValue; fOn_Task_Run_Method := nil; end; procedure tMultiTask.setPin_Thread_To_Core(AValue: boolean); begin fPin_Thread_To_Core := True; Update_Thread_Configs; end; procedure tMultiTask.setThread_Count(AValue: byte); begin if fThread_Count = AValue then Exit; fThread_Count := AValue; Update_Thread_Configs; end; procedure tMultiTask.setTThreadPriority(AValue: TThreadPriority); var i: byte; thrd: tMultiTaskThread; begin if fTThreadPriority = AValue then Exit; fTThreadPriority := AValue; for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); thrd.Priority := AValue; end; end; procedure tMultiTask.Start; var i: byte; thrd: tMultiTaskThread; begin for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); thrd.Start(); end; end; procedure tMultiTask.Stop; var i: byte; thrd: tMultiTaskThread; begin for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); thrd.Wake_Up_For_New_Work(); thrd.Terminate(); end; end; function tMultiTask.Task_Running: String; var i: integer; thrd: tMultiTaskThread; begin result := ''; for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); if thrd.Working then begin if TThread.CurrentThread.ThreadID = thrd.ThreadID then result += thrd.Task.AsPascalSourceString + ' - this Thread' + #13#10 else result += thrd.Task.AsPascalSourceString + #13#10; end; end; end; function tMultiTask.Thread_Running_Count: Byte; var i,cnt: integer; thrd: tMultiTaskThread; begin cnt := 0; for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); if thrd.Working then Inc(cnt); end; result := cnt; end; function tMultiTask.Thread_Running_Count_WO_Calling_Thread: Byte; var i,cnt: integer; thrd: tMultiTaskThread; begin cnt := 0; for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); if thrd.Working and (TThread.CurrentThread.ThreadID <> thrd.ThreadID) then Inc(cnt); end; result := cnt; end; procedure tMultiTask.Thread_Work(thrd: tMultiTaskThread); var task: tMultiTaskItem; begin task := fTask_Queue.DeQueue(thrd); while task <> nil do begin try // thrd._Working(Task); try if assigned(fOn_Before_Task_Method) then fOn_Before_Task_Method(task, thrd); finally end; try if assigned(fOn_Task_Run_Method) then begin if task.Name <> '' then fOn_Task_Run_Method(task.Name, task) else begin Stop; end; end else if assigned(fOn_Task_Run_Proc) then fOn_Task_Run_Proc(task) else Stop; try if assigned(fOn_After_Task_Method) then fOn_After_Task_Method(task, thrd); thrd._Working_Done(); finally end; except on E: Exception do begin if assigned(fOnException) then fOnException(task,E); end; end; finally task.Free; RtlEventSetEvent(fAnyThreadDoneWork); end; task := fTask_Queue.DeQueue(thrd); end; thrd.Sleep_To_New_Work(); end; procedure tMultiTask.Update_Thread_Configs; var i: integer; thrd: tMultiTaskThread; begin if fThreadList.Count <> fThread_Count then begin for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); // mozna chyba, zkusit opravit thrd.Start; thrd.Terminate; thrd.WaitFor; thrd.Free; end; fThreadList.Clear; for i := 1 to fThread_Count do begin thrd := tMultiTaskThread.Create(self); thrd.fID := i; fThreadList.Add(thrd); end; end; end; function tMultiTask.Any_Thread_Working: boolean; var i: integer; thrd: tMultiTaskThread; begin Result := False; for i := 0 to fThreadList.Count - 1 do begin thrd := tMultiTaskThread(fThreadList[i]); if thrd.Working and (TThread.CurrentThread.ThreadID <> thrd.ThreadID) then Exit(True); end; end; procedure tMultiTask.WaitFor; begin while (fTask_Queue.Length > 0) or Any_Thread_Working do begin RtlEventWaitFor(fAnyThreadDoneWork, 5000); On_New_Task_Enqeued(); end; end; end.
unit AddPolygonTerritoryUnit; interface uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit; type TAddPolygonTerritory = class(TBaseExample) public function Execute: NullableString; end; implementation uses TerritoryContourUnit, TerritoryUnit, PositionUnit; function TAddPolygonTerritory.Execute: NullableString; var ErrorString: String; TerritoryContour: TTerritoryContour; TerritoryName, TerritoryColor: String; TerritoryId: NullableString; begin Result := NullableString.Null; TerritoryName := 'Polygon Territory'; TerritoryColor := 'ff0000'; TerritoryContour := TTerritoryContour.MakePolygonContour([ TPosition.Create(37.7697528227865, -77.6783325195313), TPosition.Create(37.7588671630534, -77.6897480010986), TPosition.Create(37.7476396605445, -77.6917221069336), TPosition.Create(37.7465508430681, -77.6886322021484), TPosition.Create(37.7502255383101, -77.6812507629394), TPosition.Create(37.7479799127443, -77.6749851226806), TPosition.Create(37.7332796020606, -77.6411678314209), TPosition.Create(37.7443051067953, -77.6317264556884), TPosition.Create(37.7664192584704, -77.6684619903564) ]); TerritoryId := Route4MeManager.Territory.Add( TerritoryName, TerritoryColor, TerritoryContour, ErrorString); WriteLn(''); if (TerritoryId.IsNotNull) then begin WriteLn('AddPolygonTerritory executed successfully'); WriteLn(Format('Territory ID: %s', [Result.Value])); end else WriteLn(Format('AddPolygonTerritory error: "%s"', [ErrorString])); Result := TerritoryId; end; end.
unit UDMPrincipal; interface uses System.SysUtils, System.Classes, UCM, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.FireDACJSONReflect, UTipos, System.JSON, DataSetConverter4D.Helper, DataSetConverter4D.Impl; type TDMPrincipal = class(TDataModule) CDSCidade: TFDMemTable; CDSCidadeUF: TFDMemTable; DSCidadeUF: TDataSource; CDSCidadeCODCID: TIntegerField; CDSCidadeNOMCID: TStringField; CDSCidadeESTCID: TStringField; CDSCidadeCEPCID: TStringField; CDSCidadeCODMUN: TStringField; CDSCidadeCODEST: TIntegerField; CDSCidadeDISTRITO: TIntegerField; CDSCidadeUFIDIBGE: TIntegerField; CDSCidadeUFUF: TStringField; CDSCidadeUFDESCRICAO: TStringField; procedure CDSCidadeAfterInsert(DataSet: TDataSet); private { Private declarations } public { Public declarations } class function CidadePesqJSON(ID: Integer; Recurso, Fields, Filtro: String): TJsonArray; function GetIDFromTable(Table: String): Integer; procedure CidadePesqUF(JSONType: TJSONType); procedure CidadePesq(ID: Integer; Recurso, Fields, Filtro: String; JSONType: TJSONType); procedure CidadeApplyUpdatesRemoto(JSONType: TJSONType); procedure CidadeDelete(ID: Integer); end; var DMPrincipal: TDMPrincipal; implementation uses System.Threading, Vcl.Dialogs; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDMPrincipal } function TDMPrincipal.GetIDFromTable(Table: String): Integer; begin result:=FCM.MetodosGeraisClient.GetIDFromTable(Table); end; procedure TDMPrincipal.CidadePesqUF(JSONType: TJSONType); var DataSet: TFDJSONDatasets; xArray: TJSONArray; begin CDSCidadeUF.Active:=False; case JSONType of jtJSONDefault: Begin xArray:=FCM.MetodosGeraisClient.CidadeUFJSON(0, '*', ''); CDSCidadeUF.Open; CDSCidadeUF.FromJSONArray(xArray); End; jtJSONFiredac: Begin DataSet := FCM.MetodosGeraisClient.CidadeUF(0, '*', ''); Assert(TFDJSONDataSetsReader.GetListCount(DataSet)=1); CDSCidadeUF.AppendData(TFDJSONDataSetsReader.GetListValue(DataSet,0)); End; end; end; procedure TDMPrincipal.CDSCidadeAfterInsert(DataSet: TDataSet); begin CDSCidadeDISTRITO.AsInteger :=0; CDSCidadeCODEST.AsInteger :=35; end; procedure TDMPrincipal.CidadeApplyUpdatesRemoto(JSONType: TJSONType); var LDeltaList: TFDJSONDeltas; result: TResult; begin Try ShowMessage(CDSCidade.AsJSONObjectString); if CDSCidade.State in dsEditModes then CDSCidade.Post; case JSONType of jtJSONDefault: Begin result:=FCM.MetodosGeraisClient.UpdateCidadeJSONApplyUpdates(CDSCidadeCODCID.AsString, CDSCidade.AsJSONObject); End; jtJSONFiredac: Begin LDeltaList := TFDJSONDeltas.Create; TFDJSONDeltasWriter.ListAdd(LDeltaList,'CIDADE',CDSCidade); result:=FCM.MetodosGeraisClient.UpdateCidadeApplyUpdates(LDeltaList); End; end; if result.ReturnCode=0 then CDSCidade.CommitUpdates else raise Exception.Create(result.ErrorMessage); Finally End; end; procedure TDMPrincipal.CidadeDelete(ID: Integer); var result: TResult; begin result:=FCM.MetodosGeraisClient.cancelCidade(ID.ToString()); if result.ReturnCode=0 then CDSCidade.CommitUpdates else raise Exception.Create(result.ErrorMessage); end; procedure TDMPrincipal.CidadePesq(ID: Integer; Recurso, Fields, Filtro: String; JSONType: TJSONType); var DSCliente: TFDJSONDatasets; xArray: TJSONArray; begin CDSCidade.Active:=False; case JSONType of jtJSONDefault: Begin xArray:= FCM.MetodosGeraisClient.CidadeJSON(ID, Recurso, Fields, Filtro); CDSCidade.Open; Try CDSCidade.DisableControls; CDSCidade.FromJSONArray(xArray); CDSCidade.First; Finally CDSCidade.EnableControls; End; End; jtJSONFiredac: Begin DSCliente := FCM.MetodosGeraisClient.Cidade(ID, Recurso,Fields,Filtro); Assert(TFDJSONDataSetsReader.GetListCount(DSCliente)=1); CDSCidade.AppendData(TFDJSONDataSetsReader.GetListValue(DSCliente,0)); End; end; end; class function TDMPrincipal.CidadePesqJSON(ID: Integer; Recurso, Fields, Filtro: String): TJsonArray; begin result:=FCM.MetodosGeraisClient.CidadeJSON(ID,'','',''); end; end.
unit snk68_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,ym_3812,nz80,upd7759,sound_engine; function iniciar_snk68:boolean; implementation const //POW pow_rom:array[0..1] of tipo_roms=( (n:'dg1ver1.j14';l:$20000;p:0;crc:$8e71a8af),(n:'dg2ver1.l14';l:$20000;p:$1;crc:$4287affc)); pow_char:array[0..1] of tipo_roms=( (n:'dg9.l25';l:$8000;p:0;crc:$df864a08),(n:'dg10.m25';l:$8000;p:$8000;crc:$9e470d53)); pow_sound:tipo_roms=(n:'dg8.e25';l:$10000;p:0;crc:$d1d61da3); pow_upd:tipo_roms=(n:'dg7.d20';l:$10000;p:0;crc:$aba9a9d3); pow_sprites:array[0..15] of tipo_roms=( (n:'snk880.11a';l:$20000;p:$0;crc:$e70fd906),(n:'snk880.15a';l:$20000;p:$1;crc:$7a90e957), (n:'snk880.12a';l:$20000;p:$40000;crc:$628b1aed),(n:'snk880.16a';l:$20000;p:$40001;crc:$e40a6c13), (n:'snk880.13a';l:$20000;p:$80000;crc:$19dc8868),(n:'snk880.17a';l:$20000;p:$80001;crc:$c7931cc2), (n:'snk880.14a';l:$20000;p:$c0000;crc:$47cd498b),(n:'snk880.18a';l:$20000;p:$c0001;crc:$eed72232), (n:'snk880.19a';l:$20000;p:$100000;crc:$1775b8dd),(n:'snk880.23a';l:$20000;p:$100001;crc:$adb6ad68), (n:'snk880.20a';l:$20000;p:$140000;crc:$f8e752ec),(n:'snk880.24a';l:$20000;p:$140001;crc:$dd41865a), (n:'snk880.21a';l:$20000;p:$180000;crc:$27e9fffe),(n:'snk880.25a';l:$20000;p:$180001;crc:$055759ad), (n:'snk880.22a';l:$20000;p:$1c0000;crc:$aa9c00d8),(n:'snk880.26a';l:$20000;p:$1c0001;crc:$9bc261c5)); //Street Smart streetsm_rom:array[0..1] of tipo_roms=( (n:'s2-1ver2.14h';l:$20000;p:0;crc:$655f4773),(n:'s2-2ver2.14k';l:$20000;p:$1;crc:$efae4823)); streetsm_char:array[0..1] of tipo_roms=( (n:'s2-9.25l';l:$8000;p:0;crc:$09b6ac67),(n:'s2-10.25m';l:$8000;p:$8000;crc:$89e4ee6f)); streetsm_sound:tipo_roms=(n:'s2-5.16c';l:$10000;p:0;crc:$ca4b171e); streetsm_upd:tipo_roms=(n:'s2-6.18d';l:$20000;p:0;crc:$47db1605); streetsm_sprites:array[0..5] of tipo_roms=( (n:'stsmart.900';l:$80000;p:$0;crc:$a8279a7e),(n:'stsmart.902';l:$80000;p:$80000;crc:$2f021aa1), (n:'stsmart.904';l:$80000;p:$100000;crc:$167346f7),(n:'stsmart.901';l:$80000;p:$200000;crc:$c305af12), (n:'stsmart.903';l:$80000;p:$280000;crc:$73c16d35),(n:'stsmart.905';l:$80000;p:$300000;crc:$a5beb4e2)); //Ikari 3 ikari3_rom:array[0..1] of tipo_roms=( (n:'ik3-2-ver1.c10';l:$20000;p:0;crc:$1bae8023),(n:'ik3-3-ver1.c9';l:$20000;p:$1;crc:$10e38b66)); ikari3_char:array[0..1] of tipo_roms=( (n:'ik3-7.bin';l:$8000;p:0;crc:$0b4804df),(n:'ik3-8.bin';l:$8000;p:$8000;crc:$10ab4e50)); ikari3_sound:tipo_roms=(n:'ik3-5.bin';l:$10000;p:0;crc:$ce6706fc); ikari3_upd:tipo_roms=(n:'ik3-6.bin';l:$20000;p:0;crc:$59d256a4); ikari3_sprites:array[0..19] of tipo_roms=( (n:'ik3-23.bin';l:$20000;p:$000000;crc:$d0fd5c77),(n:'ik3-13.bin';l:$20000;p:$000001;crc:$9a56bd32), (n:'ik3-22.bin';l:$20000;p:$040000;crc:$4878d883),(n:'ik3-12.bin';l:$20000;p:$040001;crc:$0ce6a10a), (n:'ik3-21.bin';l:$20000;p:$080000;crc:$50d0fbf0),(n:'ik3-11.bin';l:$20000;p:$080001;crc:$e4e2be43), (n:'ik3-20.bin';l:$20000;p:$0c0000;crc:$9a851efc),(n:'ik3-10.bin';l:$20000;p:$0c0001;crc:$ac222372), (n:'ik3-19.bin';l:$20000;p:$100000;crc:$4ebdba89),(n:'ik3-9.bin';l:$20000;p:$100001;crc:$c33971c2), (n:'ik3-14.bin';l:$20000;p:$200000;crc:$453bea77),(n:'ik3-24.bin';l:$20000;p:$200001;crc:$e9b26d68), (n:'ik3-15.bin';l:$20000;p:$240000;crc:$781a81fc),(n:'ik3-25.bin';l:$20000;p:$240001;crc:$073b03f1), (n:'ik3-16.bin';l:$20000;p:$280000;crc:$80ba400b),(n:'ik3-26.bin';l:$20000;p:$280001;crc:$9c613561), (n:'ik3-17.bin';l:$20000;p:$2c0000;crc:$0cc3ce4a),(n:'ik3-27.bin';l:$20000;p:$2c0001;crc:$16dd227e), (n:'ik3-18.bin';l:$20000;p:$300000;crc:$ba106245),(n:'ik3-28.bin';l:$20000;p:$300001;crc:$711715ae)); ikari3_rom2:array[0..1] of tipo_roms=( (n:'ik3-1.c8';l:$10000;p:0;crc:$47e4d256),(n:'ik3-4.c12';l:$10000;p:$1;crc:$a43af6b5)); //Search and Rescue sar_rom:array[0..1] of tipo_roms=( (n:'bhw.2';l:$20000;p:0;crc:$e1430138),(n:'bhw.3';l:$20000;p:$1;crc:$ee1f9374)); sar_char:array[0..1] of tipo_roms=( (n:'bh.7';l:$8000;p:0;crc:$b0f1b049),(n:'bh.8';l:$8000;p:$8000;crc:$174ddba7)); sar_sound:tipo_roms=(n:'bh.5';l:$10000;p:0;crc:$53e2fa76); sar_upd:tipo_roms=(n:'bh.v1';l:$20000;p:0;crc:$07a6114b); sar_sprites:array[0..5] of tipo_roms=( (n:'bh.c1';l:$80000;p:$000000;crc:$1fb8f0ae),(n:'bh.c3';l:$80000;p:$080000;crc:$fd8bc407), (n:'bh.c5';l:$80000;p:$100000;crc:$1d30acc3),(n:'bh.c2';l:$80000;p:$200000;crc:$7c803767), (n:'bh.c4';l:$80000;p:$280000;crc:$eede7c43),(n:'bh.c6';l:$80000;p:$300000;crc:$9f785cd9)); sar_rom2:array[0..1] of tipo_roms=( (n:'bhw.1';l:$20000;p:0;crc:$62b60066),(n:'bhw.4';l:$20000;p:$1;crc:$16d8525c)); var rom,rom2:array[0..$1ffff] of word; ram:array[0..$1fff] of word; video_ram:array[0..$7ff] of word; sprite_ram:array[0..$3fff] of word; sound_latch,dsw1,sound_stat,protection:byte; fg_tile_offset:word; is_pow,sprite_flip:boolean; update_video_nmk68:procedure; {Primer bloque de $1000bytes 0:$FF -> Fijo 1:----xxxx xxxx---- 2 y 3:xxxxyyyy yyyyyyyy} procedure poner_sprites(group:byte); var f,i,nchar,atrib,color,x:word; tiledata_pos:word; y:integer; flipx,flipy:boolean; begin tiledata_pos:=$800*2*group; for f:=0 to $1f do begin x:=(sprite_ram[((f*$80)+4*group) shr 1] and $ff) shl 4; y:=sprite_ram[(((f*$80)+4*group) shr 1)+1]; x:=x or (y shr 12); x:=(((x+16) and $1ff)-16) and $1ff; y:=-y; //every sprite is a column 32 tiles (512 pixels) tall for i:=0 to $1f do begin y:=y and $1ff; if ((y<=256) and ((y+15)>=0)) then begin color:=sprite_ram[tiledata_pos shr 1] and $7f; atrib:=sprite_ram[(tiledata_pos shr 1)+1]; if is_pow then begin nchar:=atrib and $3fff; flipx:=(atrib and $4000)<>0; flipy:=(atrib and $8000)<>0; if nchar<>$ff then begin put_gfx_sprite(nchar,color shl 4,flipx,flipy,1); actualiza_gfx_sprite(x,y,2,1); end; end else begin if sprite_flip then begin flipx:=false; flipy:=(atrib and $8000)<>0; end else begin flipx:=(atrib and $8000)<>0; flipy:=false; end; nchar:=atrib and $7fff; if nchar<>$7fff then begin put_gfx_sprite(nchar,color shl 4,flipx,flipy,1); actualiza_gfx_sprite(x,y,2,1); end; end; end; tiledata_pos:=tiledata_pos+4; y:=y+16; end; end; end; procedure update_video_pow; var f:word; color:word; x,y,nchar:word; begin fill_full_screen(2,$7ff); for f:=$0 to $3ff do begin color:=video_ram[((f*4) shr 1)+1] and $7; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f div 32; y:=f mod 32; nchar:=fg_tile_offset+(video_ram[(f*4) shr 1] and $ff); put_gfx_trans(x*8,y*8,nchar,color shl 4,1,0); gfx[0].buffer[f]:=false; end; end; poner_sprites(2); poner_sprites(3); poner_sprites(1); actualiza_trozo(0,0,256,256,1,0,0,256,256,2); actualiza_trozo_final(0,16,256,224,2); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure update_video_ikari3; var f,atrib,nchar:word; color,x,y:byte; begin fill_full_screen(2,$7ff); for f:=$0 to $3ff do begin atrib:=video_ram[(f*4) shr 1]; color:=(atrib shr 12) and $7; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f div 32; y:=f mod 32; nchar:=atrib and $7ff; if (atrib and $8000)<>0 then put_gfx(x*8,y*8,nchar,color shl 4,1,0) else put_gfx_trans(x*8,y*8,nchar,color shl 4,1,0); gfx[0].buffer[f]:=false; end; end; poner_sprites(2); poner_sprites(3); poner_sprites(1); actualiza_trozo(0,0,256,256,1,0,0,256,256,2); actualiza_trozo_final(0,16,256,224,2); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_pow; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $Fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $F7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //P2 if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); //COIN if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); end; end; procedure snk68_principal; var frame_m,frame_s:single; f:word; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin //Main CPU m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //Sound CPU z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; if f=239 then begin m68000_0.irq[1]:=HOLD_LINE; update_video_nmk68; end; end; eventos_pow; video_sync; end; end; function pow_getword(direccion:dword):word; begin case direccion of $0..$3ffff:pow_getword:=rom[direccion shr 1]; $40000..$43fff:pow_getword:=ram[(direccion and $3fff) shr 1]; $80000:pow_getword:=(marcade.in1 shl 8)+marcade.in0; $c0000:pow_getword:=marcade.in2; $f0000:pow_getword:=(dsw1 shl 8) or $ff; $f0008:pow_getword:=$00ff; $f8000:pow_getword:=sound_stat shl 8; $100000..$101fff:pow_getword:=video_ram[(direccion and $fff) shr 1] or $ff00; $200000..$207fff:if (direccion and $2)=0 then pow_getword:=sprite_ram[(direccion and $7fff) shr 1] or $ff00 else pow_getword:=sprite_ram[(direccion and $7fff) shr 1]; $400000..$400fff:pow_getword:=buffer_paleta[(direccion and $fff) shr 1]; end; end; procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.r:=pal5bit(((tmp_color shr 7) and $1e) or ((tmp_color shr 14) and $01)); color.g:=pal5bit(((tmp_color shr 3) and $1e) or ((tmp_color shr 13) and $01)); color.b:=pal5bit(((tmp_color shl 1) and $1e) or ((tmp_color shr 12) and $01)); set_pal_color(color,numero); buffer_color[(numero shr 4) and $7]:=true; end; procedure pow_putword(direccion:dword;valor:word); begin case direccion of 0..$3ffff:; $40000..$43fff:ram[(direccion and $3fff) shr 1]:=valor; $80000:begin sound_latch:=valor shr 8; z80_0.change_nmi(PULSE_LINE); end; $c0000:begin fg_tile_offset:=(valor and $70) shl 4; sprite_flip:=(valor and 4)<>0; end; $100000..$101fff:if video_ram[(direccion and $fff) shr 1]<>valor then begin video_ram[(direccion and $fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) div 4]:=true; end; $200000..$207fff:sprite_ram[(direccion and $7fff) shr 1]:=valor; $400000..$400fff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color(valor,(direccion and $fff) shr 1); end; end; end; function pow_snd_getbyte(direccion:word):byte; begin if direccion=$f800 then pow_snd_getbyte:=sound_latch else pow_snd_getbyte:=mem_snd[direccion]; end; procedure pow_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$efff:; $f800:sound_stat:=valor; else mem_snd[direccion]:=valor; end; end; function pow_snd_inbyte(puerto:word):byte; begin if (puerto and $ff)=0 then pow_snd_inbyte:=ym3812_0.status; end; procedure pow_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $00:ym3812_0.control(valor); $20:ym3812_0.write(valor); $40:begin upd7759_0.port_w(valor); upd7759_0.start_w(0); upd7759_0.start_w(1); end; $80:upd7759_0.reset_w(valor and $80); end; end; procedure snk68_sound_update; begin YM3812_0.update; upd7759_0.update; end; procedure snd_irq(irqstate:byte); begin z80_0.change_irq(irqstate); end; //Ikari 3 function ikari3_getword(direccion:dword):word; begin case direccion of $0..$3ffff:ikari3_getword:=rom[direccion shr 1]; $40000..$43fff:ikari3_getword:=ram[(direccion and $3fff) shr 1]; $80000:ikari3_getword:=marcade.in0 xor protection; $80002:ikari3_getword:=marcade.in1 xor protection; $80004:ikari3_getword:=marcade.in2 xor protection; $f0000:ikari3_getword:=$00ff; $f0008:ikari3_getword:=$80ff; $f8000:ikari3_getword:=sound_stat shl 8; $100000..$107fff:if (direccion and $2)=0 then ikari3_getword:=sprite_ram[(direccion and $7fff) shr 1] or $ff00 else ikari3_getword:=sprite_ram[(direccion and $7fff) shr 1]; $200000..$201fff:ikari3_getword:=video_ram[(direccion and $fff) shr 1]; $300000..$33ffff:ikari3_getword:=rom2[(direccion and $3ffff) shr 1]; $400000..$400fff:ikari3_getword:=buffer_paleta[(direccion and $fff) shr 1]; end; end; procedure ikari3_putword(direccion:dword;valor:word); begin case direccion of 0..$3ffff,$300000..$33ffff:; $40000..$43fff:ram[(direccion and $3fff) shr 1]:=valor; $80000:begin sound_latch:=valor shr 8; z80_0.change_nmi(PULSE_LINE); end; $80006:if (valor=7) then protection:=$ff else protection:=0; $c0000:sprite_flip:=(valor and $4)<>0; $100000..$107fff:sprite_ram[(direccion and $7fff) shr 1]:=valor; $200000..$201fff:if video_ram[(direccion and $fff) shr 1]<>valor then begin video_ram[(direccion and $fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) div 4]:=true; end; $400000..$400fff:if (buffer_paleta[(direccion and $fff) shr 1]<>valor) then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color(valor,((direccion and $fff) shr 1)); end; end; end; //Main procedure reset_snk68; begin m68000_0.reset; z80_0.reset; ym3812_0.reset; upd7759_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; fg_tile_offset:=0; sound_latch:=0; sound_stat:=0; protection:=0; sprite_flip:=false; end; function iniciar_snk68:boolean; const pc_x:array[0..7] of dword=(8*8+3, 8*8+2, 8*8+1, 8*8+0, 3, 2, 1, 0); pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); ps_x:array[0..15] of dword=(32*8+7,32*8+6,32*8+5,32*8+4,32*8+3,32*8+2,32*8+1,32*8+0, 7,6,5,4,3,2,1,0); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16 ); var memoria_temp:pbyte; procedure convert_chars; begin init_gfx(0,8,8,$800); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,16*8,0,4,$800*16*8+0,$800*16*8+4); convert_gfx(0,0,memoria_temp,@pc_x,@pc_y,false,false); end; procedure convert_sprites(num:dword); begin init_gfx(1,16,16,num); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,64*8,0,8,num*64*8+0,num*64*8+8); convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false); end; begin llamadas_maquina.bucle_general:=snk68_principal; llamadas_maquina.reset:=reset_snk68; llamadas_maquina.fps_max:=59.185606; iniciar_snk68:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_init(2,512,512,false,true); //SIEMPRE ANTES DE INICIAR EL VIDEO!!! if main_vars.tipo_maquina=150 then main_screen.rot90_screen:=true; iniciar_video(256,224); //Main CPU getmem(memoria_temp,$400000); m68000_0:=cpu_m68000.create(9000000,264); //Sound CPU z80_0:=cpu_z80.create(4000000,264); z80_0.change_ram_calls(pow_snd_getbyte,pow_snd_putbyte); z80_0.change_io_calls(pow_snd_inbyte,pow_snd_outbyte); z80_0.init_sound(snk68_sound_update); //Sound Chips ym3812_0:=ym3812_chip.create(YM3812_FM,4000000); ym3812_0.change_irq_calls(snd_irq); upd7759_0:=upd7759_chip.create(0.5); case main_vars.tipo_maquina of 136:begin //POW m68000_0.change_ram16_calls(pow_getword,pow_putword); //cargar roms if not(roms_load16w(@rom,pow_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,pow_sound)) then exit; //ADPCM Sounds if not(roms_load(upd7759_0.get_rom_addr,pow_upd)) then exit; //convertir chars if not(roms_load(memoria_temp,pow_char)) then exit; convert_chars; //sprites if not(roms_load16b(memoria_temp,pow_sprites)) then exit; convert_sprites($4000); is_pow:=true; dsw1:=$10; update_video_nmk68:=update_video_pow; end; 137:begin //Street Smart m68000_0.change_ram16_calls(pow_getword,pow_putword); //cargar roms if not(roms_load16w(@rom,streetsm_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,streetsm_sound)) then exit; //ADPCM Sounds if not(roms_load(upd7759_0.get_rom_addr,streetsm_upd)) then exit; //convertir chars if not(roms_load(memoria_temp,streetsm_char)) then exit; convert_chars; //sprites if not(roms_load(memoria_temp,streetsm_sprites)) then exit; convert_sprites($8000); is_pow:=false; dsw1:=0; update_video_nmk68:=update_video_pow; end; 149:begin //Ikari 3 m68000_0.change_ram16_calls(ikari3_getword,ikari3_putword); //cargar roms if not(roms_load16w(@rom,ikari3_rom)) then exit; if not(roms_load16w(@rom2,ikari3_rom2)) then exit; //cargar sonido if not(roms_load(@mem_snd,ikari3_sound)) then exit; //ADPCM Sounds if not(roms_load(upd7759_0.get_rom_addr,ikari3_upd)) then exit; //convertir chars if not(roms_load(memoria_temp,ikari3_char)) then exit; convert_chars; //sprites if not(roms_load16b(memoria_temp,ikari3_sprites)) then exit; convert_sprites($8000); is_pow:=false; update_video_nmk68:=update_video_ikari3; end; 150:begin //Search and Rescue m68000_0.change_ram16_calls(ikari3_getword,ikari3_putword); //cargar roms if not(roms_load16w(@rom,sar_rom)) then exit; if not(roms_load16w(@rom2,sar_rom2)) then exit; //cargar sonido if not(roms_load(@mem_snd,sar_sound)) then exit; //ADPCM Sounds if not(roms_load(upd7759_0.get_rom_addr,sar_upd)) then exit; //convertir chars if not(roms_load(memoria_temp,sar_char)) then exit; convert_chars; //sprites if not(roms_load(memoria_temp,sar_sprites)) then exit; convert_sprites($8000); is_pow:=false; update_video_nmk68:=update_video_ikari3; end; end; //final freemem(memoria_temp); reset_snk68; iniciar_snk68:=true; end; end.
unit expressraider_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,m6809,main_engine,controls_engine,ym_2203,ym_3812,gfx_engine, rom_engine,pal_engine,sound_engine,qsnapshot; function iniciar_expraid:boolean; implementation const expraid_rom:array[0..1] of tipo_roms=( (n:'cz01-2e.16b';l:$4000;p:$4000;crc:$a0ae6756),(n:'cz00-4e.15a';l:$8000;p:$8000;crc:$910f6ccc)); expraid_char:tipo_roms=(n:'cz07.5b';l:$4000;p:$0000;crc:$686bac23); expraid_tiles:array[0..2] of tipo_roms=( (n:'cz04.8e';l:$8000;p:$0000;crc:$643a1bd3),(n:'cz05.8f';l:$8000;p:$10000;crc:$c44570bf), (n:'cz06.8h';l:$8000;p:$18000;crc:$b9bb448b)); expraid_snd:tipo_roms=(n:'cz02-1.2a';l:$8000;p:$8000;crc:$552e6112); expraid_tiles_mem:tipo_roms=(n:'cz03.12d';l:$8000;p:$0000;crc:$6ce11971); expraid_sprites:array[0..5] of tipo_roms=( (n:'cz09.16h';l:$8000;p:$0000;crc:$1ed250d1),(n:'cz08.14h';l:$8000;p:$8000;crc:$2293fc61), (n:'cz13.16k';l:$8000;p:$10000;crc:$7c3bfd00),(n:'cz12.14k';l:$8000;p:$18000;crc:$ea2294c8), (n:'cz11.13k';l:$8000;p:$20000;crc:$b7418335),(n:'cz10.11k';l:$8000;p:$28000;crc:$2f611978)); expraid_proms:array[0..3] of tipo_roms=( (n:'cy-17.5b';l:$100;p:$000;crc:$da31dfbc),(n:'cy-16.6b';l:$100;p:$100;crc:$51f25b4c), (n:'cy-15.7b';l:$100;p:$200;crc:$a6168d7f),(n:'cy-14.9b';l:$100;p:$300;crc:$52aad300)); expraid_dip_a:array [0..5] of def_dip=( (mask:$3;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$1;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$4;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Coin Mode';number:2;dip:((dip_val:$10;dip_name:'Mode 1'),(dip_val:$0;dip_name:'Mode 2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Flip Screen';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$40;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); expraid_dip_b:array [0..4] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$1;dip_name:'1'),(dip_val:$3;dip_name:'3'),(dip_val:$5;dip_name:'2'),(dip_val:$0;dip_name:'Infinite'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Bonus Life';number:2;dip:((dip_val:$0;dip_name:'50K 80K'),(dip_val:$4;dip_name:'50K only'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Difficulty';number:4;dip:((dip_val:$18;dip_name:'Easy'),(dip_val:$10;dip_name:'Normal'),(dip_val:$8;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var vb,prot_val,sound_latch,scroll_x,scroll_y,scroll_x2:byte; mem_tiles:array[0..$7fff] of byte; bg_tiles:array[0..3] of byte; bg_tiles_cam:array[0..3] of boolean; old_val,old_val2:boolean; procedure update_video_expraid; var f,i,nchar,color,atrib:word; x,y,pos_ini:word; rest_scroll:word; begin //Background for i:=0 to 3 do begin if bg_tiles_cam[i] then begin pos_ini:=bg_tiles[i]*$100; for f:=0 to $ff do begin x:=(f mod 16)*16; y:=(f div 16)*16; if i>1 then y:=y+256; x:=x+(256*(i and 1)); atrib:=mem_tiles[$4000+pos_ini+f]; nchar:=mem_tiles[pos_ini+f]+((atrib and $03) shl 8); color:=atrib and $18; put_gfx_flip(x,y,nchar,color,2,2,(atrib and 4)<>0,false); if (atrib and $80)<>0 then put_gfx_trans_flip(x,y,nchar,color,4,2,(atrib and 4)<>0,false) else put_gfx_block_trans(x,y,4,16,16); end; bg_tiles_cam[i]:=false; end; end; //Para acelerar las cosas (creo) rest_scroll:=256-scroll_y; //Express Rider divide en dos la pantalla vertical, con dos scrolls //diferentes, en total 512x256 y otra de 512x256 actualiza_trozo(scroll_x,scroll_y,256,rest_scroll,2,0,0,256,rest_scroll,1); actualiza_trozo(scroll_x2,256,256,scroll_y,2,0,rest_scroll,256,scroll_y,1); //Sprites for f:=0 to $7f do begin x:=((248-memoria[$602+(f*4)]) and $ff)-8; y:=memoria[$600+(f*4)]; nchar:=memoria[$603+(f*4)]+((memoria[$601+(f*4)] and $e0) shl 3); color:=((memoria[$601+(f*4)] and $03) + ((memoria[$601+(f*4)] and $08) shr 1)) shl 3; put_gfx_sprite(nchar,64+color,(memoria[$601+(f*4)] and 4)<>0,false,1); actualiza_gfx_sprite(x,y,1,1); if (memoria[$601+(f*4)] and $10)<>0 then begin put_gfx_sprite(nchar+1,64+color,(memoria[$601+(f*4)] and 4)<>0,false,1); actualiza_gfx_sprite(x,y+16,1,1); end; end; //Prioridad del fondo actualiza_trozo(scroll_x,scroll_y,256,rest_scroll,4,0,0,256,rest_scroll,1); actualiza_trozo(scroll_x2,256,256,scroll_y,4,0,rest_scroll,256,scroll_y,1); //Foreground for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=f mod 32; y:=f div 32; nchar:=memoria[$800+f]+((memoria[$c00+f] and $07) shl 8); color:=(memoria[$c00+f] and $10) shr 2; put_gfx_trans(x*8,y*8,nchar,128+color,6,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,6,0,0,256,256,1); actualiza_trozo_final(8,8,240,240,1); end; procedure eventos_expraid; begin if event.arcade then begin if arcade_input.right[0] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1; if arcade_input.left[0] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2; if arcade_input.up[0] then marcade.in0:=marcade.in0 and $fb else marcade.in0:=marcade.in0 or 4; if arcade_input.down[0] then marcade.in0:=marcade.in0 and $f7 else marcade.in0:=marcade.in0 or 8; if arcade_input.but0[0] then marcade.in0:=marcade.in0 and $ef else marcade.in0:=marcade.in0 or $10; if arcade_input.but1[0] then marcade.in0:=marcade.in0 and $df else marcade.in0:=marcade.in0 or $20; if (arcade_input.coin[0] and not(old_val)) then begin marcade.in2:=(marcade.in2 and $bf); m6502_0.change_nmi(ASSERT_LINE); end else begin marcade.in2:=(marcade.in2 or $40); end; if (arcade_input.coin[1] and not(old_val2)) then begin marcade.in2:=(marcade.in2 and $7f); m6502_0.change_nmi(ASSERT_LINE); end else begin marcade.in2:=(marcade.in2 or $80); end; old_val:=arcade_input.coin[0]; old_val2:=arcade_input.coin[1]; if arcade_input.start[0] then marcade.in0:=marcade.in0 and $bf else marcade.in0:=marcade.in0 or $40; if arcade_input.start[1] then marcade.in0:=marcade.in0 and $7f else marcade.in0:=marcade.in0 or $80; end; end; procedure principal_expraid; var frame_m,frame_s:single; f:word; begin init_controls(false,false,false,true); frame_m:=m6502_0.tframes; frame_s:=m6809_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin m6502_0.run(frame_m); frame_m:=frame_m+m6502_0.tframes-m6502_0.contador; //Sound m6809_0.run(frame_s); frame_s:=frame_s+m6809_0.tframes-m6809_0.contador; case f of 7:vb:=0; 247:begin update_video_expraid; vb:=$2; end; end; end; eventos_expraid; video_sync; end; end; function getbyte_expraid(direccion:word):byte; begin case direccion of 0..$fff,$4000..$ffff:getbyte_expraid:=memoria[direccion]; $1800:getbyte_expraid:=marcade.dswa; $1801:getbyte_expraid:=marcade.in0; $1802:getbyte_expraid:=marcade.in2; $1803:getbyte_expraid:=marcade.dswb; $2800:getbyte_expraid:=prot_val; $2801:getbyte_expraid:=$2; end; end; procedure putbyte_expraid(direccion:word;valor:byte); begin case direccion of 0..$7ff:memoria[direccion]:=valor; $800..$fff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $2000:m6502_0.change_nmi(CLEAR_LINE); $2001:begin sound_latch:=valor; m6809_0.change_nmi(ASSERT_LINE); end; $2002:main_screen.flip_main_screen:=(valor and $1)<>0; $2800..$2803:if bg_tiles[direccion and $3]<>(valor and $3f) then begin bg_tiles[direccion and $3]:=valor and $3f; bg_tiles_cam[direccion and $3]:=true; end; $2804:scroll_y:=valor; $2805:scroll_x:=valor; $2806:scroll_x2:=valor; $2807:case valor of $20,$60:; $80:prot_val:=prot_val+1; $90:prot_val:=0; end; $4000..$ffff:; //ROM end; end; function get_io_expraid:byte; begin get_io_expraid:=vb; end; function getbyte_snd_expraid(direccion:word):byte; begin case direccion of 0..$1fff,$8000..$ffff:getbyte_snd_expraid:=mem_snd[direccion]; $2000:getbyte_snd_expraid:=ym2203_0.status; $2001:getbyte_snd_expraid:=ym2203_0.Read; $4000:getbyte_snd_expraid:=ym3812_0.status; $6000:begin getbyte_snd_expraid:=sound_latch; m6809_0.change_nmi(CLEAR_LINE); end; end; end; procedure putbyte_snd_expraid(direccion:word;valor:byte); begin case direccion of 0..$1fff:mem_snd[direccion]:=valor; $2000:ym2203_0.control(valor); $2001:ym2203_0.write(valor); $4000:ym3812_0.control(valor); $4001:ym3812_0.write(valor); $8000..$ffff:; //ROM end; end; procedure expraid_sound_update; begin ym2203_0.Update; ym3812_0.update; end; procedure snd_irq(irqstate:byte); begin m6809_0.change_irq(irqstate); end; //Main procedure expraid_qsave(nombre:string); var data:pbyte; buffer:array[0..15] of byte; size:word; begin open_qsnapshot_save('expressraider'+nombre); getmem(data,20000); //CPU size:=m6502_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=m6809_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=ym2203_0.save_snapshot(data); savedata_com_qsnapshot(data,size); size:=ym3812_0.save_snapshot(data); savedata_com_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[0],$4000); savedata_com_qsnapshot(@mem_snd[0],$8000); //MISC buffer[0]:=vb; buffer[1]:=prot_val; buffer[2]:=sound_latch; buffer[3]:=scroll_x; buffer[4]:=scroll_y; buffer[5]:=scroll_x2; buffer[6]:=bg_tiles[0]; buffer[7]:=bg_tiles[1]; buffer[8]:=bg_tiles[2]; buffer[9]:=bg_tiles[3]; buffer[10]:=byte(bg_tiles_cam[0]); buffer[11]:=byte(bg_tiles_cam[1]); buffer[12]:=byte(bg_tiles_cam[2]); buffer[13]:=byte(bg_tiles_cam[3]); buffer[14]:=byte(old_val); buffer[15]:=byte(old_val2); savedata_qsnapshot(@buffer,16); freemem(data); close_qsnapshot; end; procedure expraid_qload(nombre:string); var data:pbyte; buffer:array[0..15] of byte; begin if not(open_qsnapshot_load('expressraider'+nombre)) then exit; getmem(data,20000); //CPU loaddata_qsnapshot(data); m6502_0.load_snapshot(data); loaddata_qsnapshot(data); m6809_0.load_snapshot(data); //SND loaddata_qsnapshot(data); ym2203_0.load_snapshot(data); loaddata_qsnapshot(data); ym3812_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria); loaddata_qsnapshot(@mem_snd); //MISC vb:=buffer[0]; prot_val:=buffer[1]; sound_latch:=buffer[2]; scroll_x:=buffer[3]; scroll_y:=buffer[4]; scroll_x2:=buffer[5]; bg_tiles[0]:=buffer[6]; bg_tiles[1]:=buffer[7]; bg_tiles[2]:=buffer[8]; bg_tiles[3]:=buffer[9]; bg_tiles_cam[0]:=buffer[10]<>0; bg_tiles_cam[1]:=buffer[11]<>0; bg_tiles_cam[2]:=buffer[12]<>0; bg_tiles_cam[3]:=buffer[13]<>0; old_val:=buffer[14]<>0; old_val2:=buffer[15]<>0; freemem(data); close_qsnapshot; //END fillchar(gfx[0].buffer,$400,1); end; procedure reset_expraid; begin m6502_0.reset; m6809_0.reset; YM2203_0.Reset; YM3812_0.reset; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; vb:=0; prot_val:=0; sound_latch:=0; old_val:=false; old_val2:=false; scroll_x:=0; scroll_y:=0; scroll_x2:=0; end; function iniciar_expraid:boolean; const pc_x:array[0..7] of dword=(0+($2000*8),1+($2000*8), 2+($2000*8), 3+($2000*8), 0, 1, 2, 3); ps_x:array[0..15] of dword=(128+0, 128+1, 128+2, 128+3, 128+4, 128+5, 128+6, 128+7, 0, 1, 2, 3, 4, 5, 6, 7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); pt_x:array[0..15] of dword=(0, 1, 2, 3, 1024*32*2,1024*32*2+1,1024*32*2+2,1024*32*2+3, 128+0,128+1,128+2,128+3,128+1024*32*2,128+1024*32*2+1,128+1024*32*2+2,128+1024*32*2+3); var colores:tpaleta; f,offs:byte; memoria_temp:array[0..$2ffff] of byte; begin llamadas_maquina.bucle_general:=principal_expraid; llamadas_maquina.reset:=reset_expraid; llamadas_maquina.fps_max:=59.637405; llamadas_maquina.save_qsnap:=expraid_qsave; llamadas_maquina.load_qsnap:=expraid_qload; iniciar_expraid:=false; iniciar_audio(false); screen_init(1,512,256,false,true); screen_init(2,512,512); screen_init(3,512,512,true); screen_init(4,512,512,true); screen_init(6,256,256,true); iniciar_video(240,240); //Main CPU m6502_0:=cpu_m6502.create(1500000,262,TCPU_DECO16); m6502_0.change_ram_calls(getbyte_expraid,putbyte_expraid); m6502_0.change_io_calls(nil,get_io_expraid); //Sound CPU m6809_0:=cpu_m6809.Create(1500000,262,TCPU_M6809); m6809_0.change_ram_calls(getbyte_snd_expraid,putbyte_snd_expraid); m6809_0.init_sound(expraid_sound_update); //Sound Chip ym2203_0:=ym2203_chip.create(1500000,0.3,0.3); ym3812_0:=ym3812_chip.create(YM3526_FM,3000000,0.6); ym3812_0.change_irq_calls(snd_irq); //cargar roms if not(roms_load(@memoria,expraid_rom)) then exit; //cargar roms audio if not(roms_load(@mem_snd,expraid_snd)) then exit; //Cargar chars if not(roms_load(@memoria_temp,expraid_char)) then exit; init_gfx(0,8,8,1024); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,false); //sprites if not(roms_load(@memoria_temp,expraid_sprites)) then exit; init_gfx(1,16,16,2048); gfx[1].trans[0]:=true; gfx_set_desc_data(3,0,32*8,2*2048*32*8,2048*32*8,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //Cargar tiles if not(roms_load(@memoria_temp,expraid_tiles)) then exit; //Mover los datos de los tiles para poder usar las rutinas de siempre... offs:=$10-$1; for f:=$7 downto 0 do begin copymemory(@memoria_temp[offs*$1000],@memoria_temp[f*$1000],$1000); offs:=offs-$1; copymemory(@memoria_temp[offs*$1000],@memoria_temp[f*$1000],$1000); offs:=offs-$1; end; init_gfx(2,16,16,1024); gfx[2].trans[0]:=true; for f:=0 to 3 do begin gfx_set_desc_data(3,8,32*8,4+(f*$4000)*8,($10000+f*$4000)*8+0,($10000+f*$4000)*8+4); convert_gfx(2,f*$100*16*16,@memoria_temp,@pt_x,@ps_y,false,false); gfx_set_desc_data(3,8,32*8,0+(f*$4000)*8,($11000+f*$4000)*8+0,($11000+f*$4000)*8+4); convert_gfx(2,(f*$100*16*16)+($80*16*16),@memoria_temp,@pt_x,@ps_y,false,false); end; if not(roms_load(@mem_tiles,expraid_tiles_mem)) then exit; //Paleta if not(roms_load(@memoria_temp,expraid_proms)) then exit; for f:=0 to $ff do begin colores[f].r:=((memoria_temp[f] and $f) shl 4) or (memoria_temp[f] and $f); colores[f].g:=((memoria_temp[f+$100] and $f) shl 4) or (memoria_temp[f+$100] and $f); colores[f].b:=((memoria_temp[f+$200] and $f) shl 4) or (memoria_temp[f+$200] and $f); end; set_pal(colores,256); //DIP marcade.dswa:=$bf; marcade.dswa_val:=@expraid_dip_a; marcade.dswb:=$ff; marcade.dswb_val:=@expraid_dip_b; //final reset_expraid; iniciar_expraid:=true; end; end.
{ vector upbound lobound num_cells = ord(ub) - ord(lb) + 1 [1..10] 10 1 10 - 1 + 1 = 10 [-3..2] 2 -3 2 - (-3) + 1 = 6 ['a'..'z'] z a 'z' - 'a' + 1 = 26 } program basicVector(input, output); type direction = 0 .. 2; vector = array [direction] of real; var u, v, w : vector; function sum(u : vector) : real; var ans : real; i : direction; begin ans := 0.0; for i := 0 to 2 do ans := ans + u[i]; sum := ans end; function norm(u : vector) : real; var ans : real; i : direction; begin ans := 0.0; for i := 0 to 2 do ans := ans + sqr(u[i]); norm := sqrt(ans) end; function innerProduct(u, v : vector) : real; var ans : real; i : direction; begin ans := 0.0; for i := 0 to 2 do ans := ans + (u[i] * v[i]); innerProduct := ans; end; procedure sum(u, v : vector; var w : vector); var i : direction; begin for i := 0 to 2 do w[i] := u[i] + v[i] end; procedure difference(u, v : vector; var w : vector); var i : direction; begin for i := 0 to 2 do w[i] := u[i] - v[i] end; procedure assign(u : vector; var v : vector); var i : direction; begin for i := 0 to 2 do v[i] := u[i] end; procedure printVector(u : vector); var i : direction; begin for i := 0 to 2 do write(u[i] : 1 : 4, ' '); writeln(); end; begin writeln(); u[0] := 1.0; u[1] := 2.0; u[2] := 3.0; v[0] := 3.6; v[1] := 2.9; v[2] := 1.0; printVector(u); printVector(v); writeln(); writeln('SUM([1.0, 2.0, 3.0]): ', sum(u) : 1 : 4); writeln('SUM([3.6, 2.9, 1.0]): ', sum(v) : 1 : 4); writeln(); writeln('NORM([1.0, 2.0, 3.0]): ', norm(u) : 1 : 4); writeln('NORM([3.6, 2.9, 1.0]): ', norm(v) : 1 : 4); writeln(); writeln('[3.6, 2.9, 1.0] * [1.0, 2.0, 3.0]: ', innerProduct(u, v) : 1 : 4); writeln(); assign(u, v); printVector(u); printVector(v); writeln(); printVector(w); sum(u, v, w); printVector(w); writeln(); printVector(w); difference(u, v, w); printVector(w); writeln(); 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 ClpSecP384R1Field; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpNat384, ClpBits, ClpBigInteger, ClpCryptoLibTypes; type // 2^384 - 2^128 - 2^96 + 2^32 - 1 TSecP384R1Field = class sealed(TObject) strict private const P11 = UInt32($FFFFFFFF); PExt23 = UInt32($FFFFFFFF); class var FP, FPExt, FPExtInv: TCryptoLibUInt32Array; class function GetP: TCryptoLibUInt32Array; static; inline; class procedure AddPInvTo(const z: TCryptoLibUInt32Array); static; class procedure SubPInvFrom(const z: TCryptoLibUInt32Array); static; class constructor SecP384R1Field(); public class procedure Add(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure AddExt(const xx, yy, zz: TCryptoLibUInt32Array); static; inline; class procedure AddOne(const x, z: TCryptoLibUInt32Array); static; inline; class function FromBigInteger(const x: TBigInteger): TCryptoLibUInt32Array; static; inline; class procedure Half(const x, z: TCryptoLibUInt32Array); static; inline; class procedure Multiply(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure Negate(const x, z: TCryptoLibUInt32Array); static; inline; class procedure Reduce(const xx, z: TCryptoLibUInt32Array); static; class procedure Reduce32(x: UInt32; const z: TCryptoLibUInt32Array); static; class procedure Square(const x, z: TCryptoLibUInt32Array); static; inline; class procedure SquareN(const x: TCryptoLibUInt32Array; n: Int32; const z: TCryptoLibUInt32Array); static; inline; class procedure Subtract(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure SubtractExt(const xx, yy, zz: TCryptoLibUInt32Array); static; inline; class procedure Twice(const x, z: TCryptoLibUInt32Array); static; inline; class property P: TCryptoLibUInt32Array read GetP; end; implementation { TSecP384R1Field } class constructor TSecP384R1Field.SecP384R1Field; begin FP := TCryptoLibUInt32Array.Create($FFFFFFFF, $00000000, $00000000, $FFFFFFFF, $FFFFFFFE, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF); FPExt := TCryptoLibUInt32Array.Create($00000001, $FFFFFFFE, $00000000, $00000002, $00000000, $FFFFFFFE, $00000000, $00000002, $00000001, $00000000, $00000000, $00000000, $FFFFFFFE, $00000001, $00000000, $FFFFFFFE, $FFFFFFFD, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF); FPExtInv := TCryptoLibUInt32Array.Create($FFFFFFFF, $00000001, $FFFFFFFF, $FFFFFFFD, $FFFFFFFF, $00000001, $FFFFFFFF, $FFFFFFFD, $FFFFFFFE, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $00000001, $FFFFFFFE, $FFFFFFFF, $00000001, $00000002); end; class function TSecP384R1Field.GetP: TCryptoLibUInt32Array; begin result := FP; end; class procedure TSecP384R1Field.AddPInvTo(const z: TCryptoLibUInt32Array); var c: Int64; begin c := Int64(z[0]) + 1; z[0] := UInt32(c); c := TBits.Asr64(c, 32); c := c + (Int64(z[1]) - 1); z[1] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin c := c + Int64(z[2]); z[2] := UInt32(c); c := TBits.Asr64(c, 32); end; c := c + (Int64(z[3]) + 1); z[3] := UInt32(c); c := TBits.Asr64(c, 32); c := c + (Int64(z[4]) + 1); z[4] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin TNat.IncAt(12, z, 5); end; end; class procedure TSecP384R1Field.SubPInvFrom(const z: TCryptoLibUInt32Array); var c: Int64; begin c := Int64(z[0]) - 1; z[0] := UInt32(c); c := TBits.Asr64(c, 32); c := c + (Int64(z[1]) + 1); z[1] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin c := c + Int64(z[2]); z[2] := UInt32(c); c := TBits.Asr64(c, 32); end; c := c + (Int64(z[3]) - 1); z[3] := UInt32(c); c := TBits.Asr64(c, 32); c := c + (Int64(z[4]) - 1); z[4] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin TNat.DecAt(12, z, 5); end; end; class procedure TSecP384R1Field.Add(const x, y, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Add(12, x, y, z); if ((c <> 0) or ((z[11] = P11) and (TNat.Gte(12, z, FP)))) then begin AddPInvTo(z); end; end; class procedure TSecP384R1Field.AddExt(const xx, yy, zz: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Add(24, xx, yy, zz); if ((c <> 0) or ((zz[23] = PExt23) and (TNat.Gte(24, zz, FPExt)))) then begin if (TNat.AddTo(System.Length(FPExtInv), FPExtInv, zz) <> 0) then begin TNat.IncAt(24, zz, System.Length(FPExtInv)); end; end; end; class procedure TSecP384R1Field.AddOne(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Inc(12, x, z); if ((c <> 0) or ((z[11] = P11) and (TNat.Gte(12, z, FP)))) then begin AddPInvTo(z); end; end; class function TSecP384R1Field.FromBigInteger(const x: TBigInteger) : TCryptoLibUInt32Array; var z: TCryptoLibUInt32Array; begin z := TNat.FromBigInteger(384, x); if ((z[11] = P11) and (TNat.Gte(12, z, FP))) then begin TNat.SubFrom(12, FP, z); end; result := z; end; class procedure TSecP384R1Field.Half(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin if ((x[0] and 1) = 0) then begin TNat.ShiftDownBit(12, x, 0, z); end else begin c := TNat.Add(12, x, FP, z); TNat.ShiftDownBit(12, z, c); end; end; class procedure TSecP384R1Field.Reduce32(x: UInt32; const z: TCryptoLibUInt32Array); var cc, xx12: Int64; begin cc := 0; if (x <> 0) then begin xx12 := x; cc := cc + (Int64(z[0]) + xx12); z[0] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(z[1]) - xx12); z[1] := UInt32(cc); cc := TBits.Asr64(cc, 32); if (cc <> 0) then begin cc := cc + Int64(z[2]); z[2] := UInt32(cc); cc := TBits.Asr64(cc, 32); end; cc := cc + (Int64(z[3]) + xx12); z[3] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(z[4]) + xx12); z[4] := UInt32(cc); cc := TBits.Asr64(cc, 32); {$IFDEF DEBUG} System.Assert((cc = 0) or (cc = 1)); {$ENDIF DEBUG} end; if (((cc <> 0) and (TNat.IncAt(12, z, 5) <> 0)) or ((z[11] = P11) and (TNat.Gte(12, z, FP)))) then begin AddPInvTo(z); end; end; class procedure TSecP384R1Field.Reduce(const xx, z: TCryptoLibUInt32Array); const n: Int64 = 1; var cc, xx16, xx17, xx18, xx19, xx20, xx21, xx22, xx23, t0, t1, t2, t3, t4, t5, t6, t7: Int64; begin xx16 := xx[16]; xx17 := xx[17]; xx18 := xx[18]; xx19 := xx[19]; xx20 := xx[20]; xx21 := xx[21]; xx22 := xx[22]; xx23 := xx[23]; t0 := Int64(xx[12]) + xx20 - n; t1 := Int64(xx[13]) + xx22; t2 := Int64(xx[14]) + xx22 + xx23; t3 := Int64(xx[15]) + xx23; t4 := xx17 + xx21; t5 := xx21 - xx23; t6 := xx22 - xx23; t7 := t0 + t5; cc := 0; cc := cc + (Int64(xx[0]) + t7); z[0] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[1]) + xx23 - t0 + t1); z[1] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[2]) - xx21 - t1 + t2); z[2] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[3]) - t2 + t3 + t7); z[3] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[4]) + xx16 + xx21 + t1 - t3 + t7); z[4] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[5]) - xx16 + t1 + t2 + t4); z[5] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[6]) + xx18 - xx17 + t2 + t3); z[6] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[7]) + xx16 + xx19 - xx18 + t3); z[7] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[8]) + xx16 + xx17 + xx20 - xx19); z[8] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[9]) + xx18 - xx20 + t4); z[9] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[10]) + xx18 + xx19 - t5 + t6); z[10] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[11]) + xx19 + xx20 - t6); z[11] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (n); {$IFDEF DEBUG} System.Assert(cc >= 0); {$ENDIF DEBUG} Reduce32(UInt32(cc), z); end; class procedure TSecP384R1Field.Multiply(const x, y, z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin tt := TNat.Create(24); TNat384.Mul(x, y, tt); Reduce(tt, z); end; class procedure TSecP384R1Field.Negate(const x, z: TCryptoLibUInt32Array); begin if (TNat.IsZero(12, x)) then begin TNat.Zero(12, z); end else begin TNat.Sub(12, FP, x, z); end; end; class procedure TSecP384R1Field.Square(const x, z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin tt := TNat.Create(24); TNat384.Square(x, tt); Reduce(tt, z); end; class procedure TSecP384R1Field.SquareN(const x: TCryptoLibUInt32Array; n: Int32; const z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin {$IFDEF DEBUG} System.Assert(n > 0); {$ENDIF DEBUG} tt := TNat.Create(24); TNat384.Square(x, tt); Reduce(tt, z); System.Dec(n); while (n > 0) do begin TNat384.Square(z, tt); Reduce(tt, z); System.Dec(n); end; end; class procedure TSecP384R1Field.Subtract(const x, y, z: TCryptoLibUInt32Array); var c: Int32; begin c := TNat.Sub(12, x, y, z); if (c <> 0) then begin SubPInvFrom(z); end; end; class procedure TSecP384R1Field.SubtractExt(const xx, yy, zz: TCryptoLibUInt32Array); var c: Int32; begin c := TNat.Sub(24, xx, yy, zz); if (c <> 0) then begin if (TNat.SubFrom(System.Length(FPExtInv), FPExtInv, zz) <> 0) then begin TNat.DecAt(24, zz, System.Length(FPExtInv)); end; end; end; class procedure TSecP384R1Field.Twice(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.ShiftUpBit(12, x, 0, z); if ((c <> 0) or ((z[11] = P11) and (TNat.Gte(12, z, FP)))) then begin AddPInvTo(z); end; end; end.
unit mp_loader; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Variants, DateUtils, XMLRead,XMLWrite,Dom,mp_types; type { TMPStorage } TMPStorage = class(TNetwork) public procedure LoadFromXmlFile(aFileName: string); procedure SaveToXmlFile(aFileName: string); end; implementation { TMPStorage } procedure TMPStorage.LoadFromXmlFile(aFileName: string); procedure DoLoadPC(aParentNode: TDOMNode; aNetworkItem: TNetworkItem); var I: Integer; oPingItem: TPingItem; oNode: TDOMNode; begin for I := 0 to aParentNode.ChildNodes.Count - 1 do begin oPingItem:=aNetworkItem.PCList.AddItem; oNode:=aParentNode.ChildNodes[i]; oPingItem.Name:= VarToStr(oNode.Attributes.GetNamedItem('compname').NodeValue); oPingItem.ip := VarToStr(oNode.Attributes.GetNamedItem('ip').NodeValue); oPingItem.melody := VarToStr(oNode.Attributes.GetNamedItem('melody').NodeValue); oPingItem.AlarmTimeout := StrToInt(VarToStr(oNode.Attributes.GetNamedItem('alarm').NodeValue)); oPingItem.CheckTimeout:= StrToInt(VarToStr(oNode.Attributes.GetNamedItem('timeout').NodeValue)); oPingItem.PlaySound:= StrToInt(VarToStr(oNode.Attributes.GetNamedItem('play').NodeValue)); // oPingItem.ashost:= StrTobool(VarToStr(oNode.Attributes.GetNamedItem('ashost').NodeValue)); end; end; procedure DoLoadNetworks(aNode: TDOMNode); var I: Integer; oNode: TDOMNode; oNetworkItem: TNetworkItem; begin for I := 0 to aNode.ChildNodes.Count - 1 do begin oNetworkItem:=AddItem; oNode:=aNode.ChildNodes[i]; oNetworkItem.Name:= oNode.Attributes.GetNamedItem('name').NodeValue; // oNetworkItem.Log:= oNode.Attributes.GetNamedItem('logfile').NodeValue; DoLoadPC(oNode, oNetworkItem); end; end; var oXmlDocument: TXmlDocument; begin oXMLDocument:=TXMLDocument.Create; ReadXMLFile(oXmlDocument,aFileName); DoLoadNetworks (oXmlDocument.DocumentElement); FreeAndNil(oXmlDocument); end; procedure TMPStorage.SaveToXmlFile(aFileName: string); var oXmlDocument: TXmlDocument; vRoot,NetworkNode,PingItemNode: TDOMNode; i,d: integer; oPingItem: TPingItem; begin oXmlDocument:=TXmlDocument.Create; // oXmlDocument.Encoding:='UTF-8'; vRoot:=oXmlDocument.CreateElement('Document'); oXmlDocument.AppendChild(vroot); vRoot:=oXMLDocument.DocumentElement; for i:=0 to count -1 do begin NetworkNode:=oXmlDocument.CreateElement('network'); TDOMElement(NetworkNode).SetAttribute('name',Items[i].Name); // TDOMElement(NetworkNode).SetAttribute('logfile',Items[i].Log); for d:=0 to Items[i].PCList.Count - 1 do begin oPingItem:=Items[i].PCList.Items[d]; PingItemNode:=oXMLDocument.CreateElement('workstation'); TDOMElement(PingItemNode).SetAttribute('compname',oPingItem.Name); TDOMElement(PingItemNode).SetAttribute('ip',oPingItem.IP); TDOMElement(PingItemNode).SetAttribute('melody',oPingItem.Melody); TDOMElement(PingItemNode).SetAttribute('alarm',intToStr(oPingItem.AlarmTimeout)); TDOMElement(PingItemNode).SetAttribute('play',IntToStr(oPingItem.PlaySound)); TDOMElement(PingItemNode).SetAttribute('timeout',IntToStr(oPingItem.CheckTimeout)); // TDOMElement(PingItemNode).SetAttribute('ashost',BoolToStr(oPingItem.AsHost)); NetworkNode.AppendChild(PingItemNode); end; vRoot.AppendChild(NetworkNode); end; WriteXMLFile (oXmlDocument,aFileName); FreeAndNil(oXmlDocument); end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ExtCtrls; type TForm1 = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; Open1: TMenuItem; OpenDialog1: TOpenDialog; Memo1: TMemo; Panel1: TPanel; RadioGroup1: TRadioGroup; Exit1: TMenuItem; procedure Open1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); private { Private-Deklarationen } procedure ImportFile(const filename:string); procedure ImportFile2(const filename:string); procedure AddLine(const line:string); public { Public-Deklarationen } end; var Form1: TForm1; implementation {$R *.DFM} function FileToString(const FileName: string): AnsiString; var fs: TFileStream; Len: Integer; begin fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Len := fs.Size; SetLength(Result, Len); if Len > 0 then fs.ReadBuffer(Result[1], Len); finally fs.Free; end; end; procedure TForm1.AddLine(const line: string); begin Memo1.Lines.Add(line); end; function Char2Pas(c:char):string; begin if (c < ' ') or (c >=#128) or (c='''') then begin Result := '#'+IntToStr(ord(c)); end else Result := c; end; function Char2PasQ(c:char):string; begin if (c < ' ') or (c >=#128) or (c='''') then begin Result := '#'+IntToStr(ord(c)); end else Result := ''''+c+''''; end; procedure TForm1.ImportFile(const filename: string); var s : string; i : Integer; line : string; begin s := FileToString(filename); Addline('resourcestring'); line := ChangeFileExt(ExtractFilename(filename), '')+' = '''; for i := 1 to length(s) do begin line := line + Char2Pas(s[i]); if Length(line) > 80 then begin line := line + ''''; if i < Length(s) then line := line + ' +'; Addline(line); line := ''''; end; end; if line <> '''' then Addline(line + ''';'); end; procedure TForm1.ImportFile2(const filename: string); var s : string; i : Integer; line : string; begin s := FileToString(filename); Addline('const'); line := ChangeFileExt(ExtractFilename(filename), '')+':array[0..'+ IntToStr(length(s)-1)+'] = ('; for i := 1 to length(s) do begin if i <> 1 then line := line+ ','; line := line + Char2PasQ(s[i]); if Length(line) > 80 then begin Addline(line); line := ''; end; end; if line <> '''' then Addline(line + ');') else AddLine(');'); end; procedure TForm1.Open1Click(Sender: TObject); begin if opendialog1.Execute then begin Memo1.Lines.Clear; Memo1.Lines.BeginUpdate; try if RadioGroup1.ItemIndex = 1 then ImportFile2(OpenDialog1.FileName) else ImportFile(OpenDialog1.FileName); finally Memo1.Lines.EndUpdate; end; end; end; procedure TForm1.Exit1Click(Sender: TObject); begin close; end; end.
unit URandomString; interface uses Classes; function RandomString(const len: Integer = 10; const CharSet: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): string;overload; function RandomString(const x:array of string): string;overload; function RandomString(s:TStrings):string;overload; function RandomDigitString(const len:Integer):string; function RandomBytes(const len: Integer):string; procedure RandomizeTStrings(list:TStrings); implementation uses Sysutils; {************************************************************************** * NAME: RandomString * DESC: Erzeugt einen zufälligen String * PARAMS: len: länge des erzeugten strings * CharSet: string der die zu verwendenden Zeichen enthält * RESULT: [-] *************************************************************************} function RandomString(const len: Integer; const CharSet: string): string; var i: Integer; pResult : PChar; begin SetLength(Result,len); // Speicher im Result-String reservieren pResult := PChar(Result); for i := 1 to len do begin pResult^ := CharSet[1+Random(Length(CharSet))]; Inc(pResult); end; end; {************************************************************************** * NAME: RandomString * DESC: Es wird ein String aus dem offenen String-Array x zufällig * ausgewählt und zurückgegeben * PARAMS: [-] * RESULT: [-] *************************************************************************} function RandomString(const x:array of string): string;overload; begin Result := x[Random(Length(x))]; end; {************************************************************************** * NAME: RandomString * DESC: Es wird ein String aus der StringListe s zufällig * ausgewählt und zurückgegeben * PARAMS: [-] * RESULT: [-] *************************************************************************} function RandomString(s: TStrings): string; begin Assert(Assigned(s)); if s.Count = 0 then Result := '' else Result := Trim(s.Strings[Random(s.Count)]); end; function RandomDigitString(const len:Integer):string; begin Result := RandomString(len, '0123456789'); end; function RandomBytes(const len: Integer):string; const MAX_BYTE = 256; var i: Integer; pResult : PChar; begin SetLength(Result,len); // Speicher im Result-String reservieren pResult := PChar(Result); for i := 1 to len do begin pResult^ := Chr(Random(MAX_BYTE)); Inc(pResult); end; end; procedure RandomizeTStrings(list:TStrings); var list2 : TStrings; i : Integer; begin list2 := TStringList.Create; list.BeginUpdate; try while list.Count > 1 do begin i := Random(list.Count); list2.AddObject(list.Strings[i], list.Objects[i]); list.Delete(i); end; list.AddStrings(list2); finally list.EndUpdate; list2.Free; end; end; procedure RandomizeTStrings2(list:TStrings); var z : Integer; begin list.BeginUpdate; try for z := 0 to list.Count-1 do list.Exchange(z,Random(list.Count)); finally list.EndUpdate; end; end; end.
{ *************************************************************************** Copyright (c) 2015-2021 Kike Pérez Unit : Quick.Amazon Description : Amazon object operations Author : Kike Pérez Version : 1.4 Created : 18/11/2016 Modified : 18/11/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Amazon; {$i QuickLib.inc} interface uses Classes, System.SysUtils, System.Generics.Collections, IPPeerClient, Data.Cloud.CloudAPI, Data.Cloud.AmazonAPI, Quick.Commons; const AWSRegionSet : array of string = [ 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-central-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-east-1', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ca-central-1', 'sa-east-1', 'us-east-1', // deprecated 'eu-west-1', // deprecated 'cn-north-1', 'cn-northwest-1', 'eu-north-1', 'me-south-1']; type TAmazonProtocol = (amHTTP,amHTTPS); TAmazonStorage = TAmazonStorageService; TAmazonACLAccess = TAmazonACLType; TAmazonRegion = Data.Cloud.AmazonAPI.TAmazonRegion; TAmazonObject = class Name : string; Modified : TDateTime; Size : Int64; IsDeleted : Boolean; end; TAmazonObjects = class(TObjectList<TAmazonObject>); TAmazonResponseInfo = record StatusCode : Integer; StatusMsg : string; end; TQuickAmazon = class private fconAmazon : TAmazonConnectionInfo; fAccountName : string; fAccountKey : string; fAWSRegion : TAmazonRegion; fAmazonProtocol : TAmazonProtocol; procedure SetAccountName(amAccountName : string); procedure SetAccountKey(amAccountKey : string); procedure SetAmazonProtocol(amProtocol : TAmazonProtocol); procedure SetAWSRegion(Value : TAmazonRegion); function FileToArray(cFilename : string) : TArray<Byte>; function ByteContent(DataStream: TStream): TBytes; public constructor Create; overload; constructor Create(amAccountName, amAccountKey : string); overload; destructor Destroy; override; property AccountName : string read fAccountName write SetAccountName; property AccountKey : string read fAccountKey write SetAccountKey; property AmazonProtocol : TAmazonProtocol read fAmazonProtocol write SetAmazonProtocol; property AWSRegion : TAmazonRegion read fAWSRegion write SetAWSRegion; function StorageURL(amBucket : string) : string; function PutObject(amBucket, cFilename, amObjectName : string; amACLType : TAmazonACLType; var amResponseInfo : TAmazonResponseInfo) : Boolean; overload; function PutObject(amBucket : string; cStream : TStream; amObjectName : string; amACLType : TAmazonACLType; var amResponseInfo : TAmazonResponseInfo) : Boolean; overload; function GetObject(amBucket, amObjectName, cFilenameTo : string; var amResponseInfo : TAmazonResponseInfo) : Boolean; overload; function GetObject(amBucket, amObjectName : string; var amResponseInfo : TAmazonResponseInfo) : TMemoryStream; overload; function ExistsObject(amBucket, amObjectName : string; amRegion : TAmazonRegion) : Boolean; function DeleteObject(amBucket,amObjectName : string; var amResponseInfo : TAmazonResponseInfo) : Boolean; function ListObjects(amBucket : string; amObjectsStartWith : string; amRegion : TAmazonRegion; var amResponseInfo : TAmazonResponseInfo) : TAmazonObjects; function ListObjectsNames(amBucket : string; amObjectsStartWith : string; amRegion : TAmazonRegion; var amResponseInfo : TAmazonResponseInfo) : TStrings; function ExistsBucket(amBucketName : string) : Boolean; function ListBuckets(var amResponseInfo : TAmazonResponseInfo) : TStrings; function CreateBucket(amBucket : string; amBucketRegion : TAmazonRegion; amACLType : TAmazonACLAccess; var amResponseInfo : TAmazonResponseInfo) : Boolean; function DeleteBucket(amBucket : string; amBucketRegion : TAmazonRegion; var amResponseInfo : TAmazonResponseInfo) : Boolean; {$IFNDEF DELPHISYDNEY_UP} class function GetAWSRegion(Region: TAmazonRegion): string; overload; {$ELSE} class function GetAWSRegion(const Region : string) : TAmazonRegion; overload; {$ENDIF} end; implementation constructor TQuickAmazon.Create; begin inherited; fconAmazon := TAmazonConnectionInfo.Create(nil); fAmazonProtocol := amHTTP; fconAmazon.UseDefaultEndpoints := False; end; constructor TQuickAmazon.Create(amAccountName, amAccountKey : string); begin Create; SetAccountName(amAccountName); SetAccountKey(amAccountKey); end; destructor TQuickAmazon.Destroy; begin if Assigned(fconAmazon) then fconAmazon.Free; inherited; end; procedure TQuickAmazon.SetAWSRegion(Value : TAmazonRegion); begin fAWSRegion := Value; //fconAmazon.StorageEndpoint := Format('s3-%s.amazonaws.com',[GetAWSRegion(Value)]); //fconAmazon.StorageEndpoint := Format('s3.%s.amazonaws.com',[GetAWSRegion(Value)]); {$IFDEF DELPHISYDNEY_UP} if not StrInArray(Value,AWSRegionSet) then raise Exception.CreateFmt('%s is not a valid region for AmazonS3!',[Value]); fconAmazon.Region := Value; {$ELSE} fconAmazon.StorageEndpoint := Format('s3.%s.amazonaws.com',[GetAWSRegion(Value)]); {$ENDIF} end; procedure TQuickAmazon.SetAccountName(amAccountName : string); begin if fAccountName <> amAccountName then begin fAccountName := amAccountName; fconAmazon.AccountName := amAccountName; end; end; procedure TQuickAmazon.SetAccountKey(amAccountKey : string); begin if fAccountKey <> amAccountKey then begin fAccountKey := amAccountKey ; fconAmazon.AccountKey := amAccountKey; end; end; procedure TQuickAmazon.SetAmazonProtocol(amProtocol: TAmazonProtocol); begin if fAmazonProtocol <> amProtocol then begin fAmazonProtocol := amProtocol; if amProtocol = amHTTP then fconAmazon.Protocol := 'http' else fconAmazon.Protocol := 'https'; end; end; function TQuickAmazon.FileToArray(cFilename : string) : TArray<Byte>; var fs : TFileStream; bs : TBytesStream; begin fs := TFileStream.Create(cFilename, fmOpenRead); try Result := ByteContent(fs); finally fs.Free; end; end; function TQuickAmazon.ByteContent(DataStream: TStream): TBytes; var Buffer: TBytes; begin if not Assigned(DataStream) then Exit(nil); SetLength(Buffer, DataStream.Size); // the content may have been read DataStream.Position := 0; if DataStream.Size > 0 then DataStream.Read(Buffer[0], DataStream.Size); Result := Buffer; end; function GetResponseInfo(amResponseInfo : TCloudResponseInfo) : TAmazonResponseInfo; begin Result.StatusCode := amResponseInfo.StatusCode; Result.StatusMsg := amResponseInfo.StatusMessage; end; function TQuickAmazon.StorageURL(amBucket : string) : string; begin Result := fconAmazon.StorageURL(amBucket) end; function TQuickAmazon.PutObject(amBucket, cFilename, amObjectName : string; amACLType : TAmazonACLType; var amResponseInfo : TAmazonResponseInfo) : Boolean; var AmazonS3 : TAmazonStorage; Content : TArray<Byte>; CloudResponseInfo : TCloudResponseInfo; begin AmazonS3 := TAmazonStorage.Create(fconAmazon); if amBucket = '' then amBucket := '$root'; try Content := FileToArray(cFilename); if amObjectName = '' then amObjectName := cFilename; if amObjectName.StartsWith('/') then amObjectName := Copy(amObjectName,2,Length(amObjectName)); CloudResponseInfo := TCloudResponseInfo.Create; try Result := AmazonS3.UploadObject(amBucket,amObjectName,Content,False,nil,nil,amACLType,CloudResponseInfo{$IFDEF DELPHIRX11_UP},fAWSRegion{$ENDIF}); amResponseInfo := GetResponseInfo(CloudResponseInfo); finally CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; function TQuickAmazon.PutObject(amBucket : string; cStream : TStream; amObjectName : string; amACLType : TAmazonACLType; var amResponseInfo : TAmazonResponseInfo) : Boolean; var AmazonS3 : TAmazonStorage; Content : TBytes; CloudResponseInfo : TCloudResponseInfo; begin amResponseInfo.StatusCode := 500; if amBucket = '' then amBucket := '$root'; if amObjectName.StartsWith('/') then amObjectName := Copy(amObjectName,2,Length(amObjectName)); try AmazonS3 := TAmazonStorage.Create(fconAmazon); try //AmazonS3.Timeout := fTimeout; CloudResponseInfo := TCloudResponseInfo.Create; try //CloudResponseInfo.Headers.AddPair(); Content := ByteContent(cStream); Result := AmazonS3.UploadObject(amBucket,amObjectName,Content,False,nil,nil,amACLType,CloudResponseInfo{$IFDEF DELPHIRX11_UP},fAWSRegion{$ENDIF}); amResponseInfo := GetResponseInfo(CloudResponseInfo); finally CloudResponseInfo.Free; end; finally AmazonS3.Free; SetLength(Content,0); Content := nil; end; except Result := False; end; end; function TQuickAmazon.GetObject(amBucket, amObjectName, cFilenameTo : string; var amResponseInfo : TAmazonResponseInfo) : Boolean; var AmazonS3 : TAmazonStorage; fs : TFileStream; CloudResponseInfo : TCloudResponseInfo; //amParams : TAmazonGetObjectOptionals; begin Result := False; if amBucket = '' then amBucket := '$root'; if amObjectName.StartsWith('/') then amObjectName := Copy(amObjectName,2,Length(amObjectName)); AmazonS3 := TAmazonStorage.Create(fconAmazon); try //AmazonS3.Timeout := fTimeout; CloudResponseInfo := TCloudResponseInfo.Create; if FileExists(cFilenameTo) then fs := TFileStream.Create(cFilenameTo,fmOpenWrite) else fs := TFileStream.Create(cFilenameTo,fmCreate); try try AmazonS3.GetObject(amBucket,amObjectName,fs,CloudResponseInfo{$IFDEF DELPHIRX11_UP},fAWSRegion{$ENDIF}); amResponseInfo := GetResponseInfo(CloudResponseInfo); if amResponseInfo.StatusCode = 200 then Result := True; except Result := False; end; finally fs.Free; CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; function TQuickAmazon.GetObject(amBucket, amObjectName : string; var amResponseInfo : TAmazonResponseInfo) : TMemoryStream; var AmazonS3 : TAmazonStorage; CloudResponseInfo : TCloudResponseInfo; begin Result := TMemoryStream.Create; if amBucket = '' then amBucket := '$root'; if amObjectName.StartsWith('/') then amObjectName := Copy(amObjectName,2,Length(amObjectName)); AmazonS3 := TAmazonStorage.Create(fconAmazon); try //AmazonS3.Timeout := fTimeout; CloudResponseInfo := TCloudResponseInfo.Create; try try AmazonS3.GetObject(amBucket,amObjectName,Result,CloudResponseInfo{$IFDEF DELPHIRX11_UP},fAWSRegion{$ENDIF}); amResponseInfo := GetResponseInfo(CloudResponseInfo); except Result := nil; end; finally CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; function TQuickAmazon.ExistsObject(amBucket, amObjectName : string; amRegion : TAmazonRegion) : Boolean; var amObject : string; amObjects : TStrings; ResponseInfo : TAmazonResponseInfo; begin Result := False; amObjects := ListObjectsNames(amBucket,amObjectName,amRegion,ResponseInfo); try if (ResponseInfo.StatusCode = 200) and (Assigned(amObjects)) then begin for amObject in amObjects do begin if amObject = amObjectName then begin Result := True; Break; end; end; end; finally amObjects.Free; end; end; function TQuickAmazon.DeleteObject(amBucket,amObjectName : string; var amResponseInfo : TAmazonResponseInfo) : Boolean; var AmazonS3 : TAmazonStorage; CloudResponseInfo : TCloudResponseInfo; begin if amBucket = '' then amBucket := '$root'; if amObjectName.StartsWith('/') then amObjectName := Copy(amObjectName,2,Length(amObjectName)); AmazonS3 := TAmazonStorage.Create(fconAmazon); try //AmazonS3.Timeout := fTimeout; CloudResponseInfo := TCloudResponseInfo.Create; try Result := AmazonS3.DeleteObject(amBucket,amObjectName,CloudResponseInfo); amResponseInfo := GetResponseInfo(CloudResponseInfo); finally CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; function TQuickAmazon.ListObjects(amBucket : string; amObjectsStartWith : string; amRegion : TAmazonRegion; var amResponseInfo : TAmazonResponseInfo) : TAmazonObjects; var AmazonS3 : TAmazonStorage; amObject : TAmazonObject; i : Integer; amBucketResult : TAmazonBucketResult; CloudResponseInfo : TCloudResponseInfo; cNextMarker : string; amParams : TStrings; begin Result := TAmazonObjects.Create(True); cNextMarker := ''; if amBucket = '' then amBucket := '$root'; AmazonS3 := TAmazonStorage.Create(fconAmazon); CloudResponseInfo := TCloudResponseInfo.Create; try //AmazonS3.Timeout := fTimeout; repeat amParams := TStringList.Create; try amParams.Values['prefix'] := amObjectsStartWith; if cNextMarker <> '' then amParams.Values['marker'] := cNextMarker; amBucketResult := AmazonS3.GetBucket(amBucket,amParams,CloudResponseInfo,amRegion); amResponseInfo := GetResponseInfo(CloudResponseInfo); if Assigned(amBucketResult) then begin try Result.Capacity := amBucketResult.Objects.Count; for i := 0 to amBucketResult.Objects.Count-1 do begin amObject := TAmazonObject.Create; amObject.Name := amBucketResult.Objects[i].Name; amObject.Modified := StrToDateTime(amBucketResult.Objects[i].LastModified); amObject.Size := amBucketResult.Objects[i].Size; amObject.IsDeleted := amBucketResult.Objects[i].IsDeleted; Result.Add(amObject); end; finally amBucketResult.Free; end; cNextMarker := amBucketResult.Marker; end; finally amParams.Free; end; until (cNextMarker = '') or (amResponseInfo.StatusCode <> 200); finally AmazonS3.Free; CloudResponseInfo.Free; end; end; function TQuickAmazon.ListObjectsNames(amBucket : string; amObjectsStartWith : string; amRegion : TAmazonRegion; var amResponseInfo : TAmazonResponseInfo) : TStrings; var AmazonS3 : TAmazonStorage; i : Integer; amBucketResult : TAmazonBucketResult; CloudResponseInfo : TCloudResponseInfo; cNextMarker : string; amParams : TStrings; begin Result := TStringList.Create; cNextMarker := ''; if amBucket = '' then amBucket := '$root'; AmazonS3 := TAmazonStorage.Create(fconAmazon); CloudResponseInfo := TCloudResponseInfo.Create; try //AmazonS3.Timeout := fTimeout; repeat amParams := TStringList.Create; try if amObjectsStartWith <> '' then amParams.Values['prefix'] := amObjectsStartWith; if cNextMarker <> '' then amParams.Values['marker'] := cNextMarker; amBucketResult := AmazonS3.GetBucket(amBucket,amParams,CloudResponseInfo,amRegion); amResponseInfo := GetResponseInfo(CloudResponseInfo); if Assigned(amBucketResult) then begin try Result.Capacity := amBucketResult.Objects.Count; for i := 0 to amBucketResult.Objects.Count-1 do Result.Add(amBucketResult.Objects[i].Name); finally amBucketResult.Free; end; cNextMarker := amBucketResult.Marker; end; finally amParams.Free; end; until (cNextMarker = '') or (amResponseInfo.StatusCode <> 200); finally AmazonS3.Free; CloudResponseInfo.Free; end; end; function TQuickAmazon.ExistsBucket(amBucketName : string) : Boolean; var amBucket : string; amBuckets : TStrings; ResponseInfo : TAmazonResponseInfo; begin Result := False; amBuckets := ListBuckets(ResponseInfo); try if (ResponseInfo.StatusCode = 200) and (Assigned(amBuckets)) then begin for amBucket in amBuckets do begin if amBucket = amBucketName then begin Result := True; Break; end; end; end; finally amBuckets.Free; end; end; function TQuickAmazon.ListBuckets(var amResponseInfo : TAmazonResponseInfo) : TStrings; var AmazonS3 : TAmazonStorageService; CloudResponseInfo : TCloudResponseInfo; Buckets : TStrings; i : Integer; begin AmazonS3 := TAmazonStorageService.Create(fconAmazon); Result := TStringList.Create; try //AmazonS3.Timeout := fTimeout; CloudResponseInfo := TCloudResponseInfo.Create; try Buckets := AmazonS3.ListBuckets(CloudResponseInfo); try Result.Capacity := Buckets.Count; for i := 0 to Buckets.Count -1 do begin Result.Add(Buckets.Names[i]); end; amResponseInfo := GetResponseInfo(CloudResponseInfo); finally Buckets.Free; end; finally CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; function TQuickAmazon.CreateBucket(amBucket : string; amBucketRegion : TAmazonRegion; amACLType : TAmazonACLAccess; var amResponseInfo : TAmazonResponseInfo) : Boolean; var AmazonS3 : TAmazonStorageService; CloudResponseInfo : TCloudResponseInfo; begin Result := False; if amBucket = '' then Exit; AmazonS3 := TAmazonStorageService.Create(fconAmazon); try CloudResponseInfo := TCloudResponseInfo.Create; try Result := AmazonS3.CreateBucket(amBucket,amACLType,amBucketRegion,CloudResponseInfo); amResponseInfo := GetResponseInfo(CloudResponseInfo); finally CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; function TQuickAmazon.DeleteBucket(amBucket : string; amBucketRegion : TAmazonRegion; var amResponseInfo : TAmazonResponseInfo) : Boolean; var AmazonS3 : TAmazonStorageService; CloudResponseInfo : TCloudResponseInfo; begin Result := False; if amBucket = '' then Exit; AmazonS3 := TAmazonStorageService.Create(fconAmazon); try CloudResponseInfo := TCloudResponseInfo.Create; try Result := AmazonS3.DeleteBucket(amBucket,CloudResponseInfo,amBucketRegion); amResponseInfo := GetResponseInfo(CloudResponseInfo); finally CloudResponseInfo.Free; end; finally AmazonS3.Free; end; end; {$IFNDEF DELPHISYDNEY_UP} class function TQuickAmazon.GetAWSRegion(Region: TAmazonRegion): string; begin Result := TAmazonStorageService.GetRegionString(Region); end; {$ELSE} class function TQuickAmazon.GetAWSRegion(const Region : string) : TAmazonRegion; begin Result := TAmazonStorageService.GetRegionFromString(Region); end; {$ENDIF} end.
unit williams_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,m680x,main_engine,controls_engine,gfx_engine,dac,rom_engine, pal_engine,sound_engine,pia6821,file_engine,blitter_williams; function iniciar_williams:boolean; implementation const //Defender defender_rom:array[0..10] of tipo_roms=( (n:'defend.1';l:$800;p:$0;crc:$c3e52d7e),(n:'defend.4';l:$800;p:$800;crc:$9a72348b), (n:'defend.2';l:$1000;p:$1000;crc:$89b75984),(n:'defend.3';l:$1000;p:$2000;crc:$94f51e9b), (n:'defend.9';l:$800;p:$3000;crc:$6870e8a5),(n:'defend.12';l:$800;p:$3800;crc:$f1f88938), (n:'defend.8';l:$800;p:$4000;crc:$b649e306),(n:'defend.11';l:$800;p:$4800;crc:$9deaf6d9), (n:'defend.7';l:$800;p:$5000;crc:$339e092e),(n:'defend.10';l:$800;p:$5800;crc:$a543b167), (n:'defend.6';l:$800;p:$9000;crc:$65f4efd1)); defender_snd:tipo_roms=(n:'defend.snd';l:$800;p:$f800;crc:$fefd5b48); //Mayday mayday_rom:array[0..6] of tipo_roms=( (n:'mayday.c';l:$1000;p:$0;crc:$a1ff6e62),(n:'mayday.b';l:$1000;p:$1000;crc:$62183aea), (n:'mayday.a';l:$1000;p:$2000;crc:$5dcb113f),(n:'mayday.d';l:$1000;p:$3000;crc:$ea6a4ec8), (n:'mayday.e';l:$1000;p:$4000;crc:$0d797a3e),(n:'mayday.f';l:$1000;p:$5000;crc:$ee8bfcd6), (n:'mayday.g';l:$1000;p:$9000;crc:$d9c065e7)); mayday_snd:tipo_roms=(n:'ic28-8.bin';l:$800;p:$f800;crc:$fefd5b48); //Colony7 colony7_rom:array[0..8] of tipo_roms=( (n:'cs03.bin';l:$1000;p:$0;crc:$7ee75ae5),(n:'cs02.bin';l:$1000;p:$1000;crc:$c60b08cb), (n:'cs01.bin';l:$1000;p:$2000;crc:$1bc97436),(n:'cs06.bin';l:$800;p:$3000;crc:$318b95af), (n:'cs04.bin';l:$800;p:$3800;crc:$d740faee),(n:'cs07.bin';l:$800;p:$4000;crc:$0b23638b), (n:'cs05.bin';l:$800;p:$4800;crc:$59e406a8),(n:'cs08.bin';l:$800;p:$5000;crc:$3bfde87a), (n:'cs08.bin';l:$800;p:$5800;crc:$3bfde87a)); colony7_snd:tipo_roms=(n:'cs11.bin';l:$800;p:$f800;crc:$6032293c); colony7_dip_a:array [0..2] of def_dip=( (mask:$1;name:'Lives';number:2;dip:((dip_val:$0;dip_name:'2'),(dip_val:$1;dip_name:'3'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Bonus At';number:2;dip:((dip_val:$0;dip_name:'20K/40K or 30K/50K'),(dip_val:$2;dip_name:'30K/50K or 40K/70K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); //Joust joust_rom:array[0..11] of tipo_roms=( (n:'joust_rom_10b_3006-22.a7';l:$1000;p:$0;crc:$3f1c4f89),(n:'joust_rom_11b_3006-23.c7';l:$1000;p:$1000;crc:$ea48b359), (n:'joust_rom_12b_3006-24.e7';l:$1000;p:$2000;crc:$c710717b),(n:'joust_rom_1b_3006-13.e4';l:$1000;p:$3000;crc:$fe41b2af), (n:'joust_rom_2b_3006-14.c4';l:$1000;p:$4000;crc:$501c143c),(n:'joust_rom_3b_3006-15.a4';l:$1000;p:$5000;crc:$43f7161d), (n:'joust_rom_4b_3006-16.e5';l:$1000;p:$6000;crc:$db5571b6),(n:'joust_rom_5b_3006-17.c5';l:$1000;p:$7000;crc:$c686bb6b), (n:'joust_rom_6b_3006-18.a5';l:$1000;p:$8000;crc:$fac5f2cf),(n:'joust_rom_7b_3006-19.e6';l:$1000;p:$9000;crc:$81418240), (n:'joust_rom_8b_3006-20.c6';l:$1000;p:$a000;crc:$ba5359ba),(n:'joust_rom_9b_3006-21.a6';l:$1000;p:$b000;crc:$39643147)); joust_snd:tipo_roms=(n:'video_sound_rom_4_std_780.ic12';l:$1000;p:$f000;crc:$f1835bdd); //Robotron robotron_rom:array[0..11] of tipo_roms=( (n:'2084_rom_10b_3005-22.a7';l:$1000;p:$0;crc:$13797024),(n:'2084_rom_11b_3005-23.c7';l:$1000;p:$1000;crc:$7e3c1b87), (n:'2084_rom_12b_3005-24.e7';l:$1000;p:$2000;crc:$645d543e),(n:'2084_rom_1b_3005-13.e4';l:$1000;p:$3000;crc:$66c7d3ef), (n:'2084_rom_2b_3005-14.c4';l:$1000;p:$4000;crc:$5bc6c614),(n:'2084_rom_3b_3005-15.a4';l:$1000;p:$5000;crc:$e99a82be), (n:'2084_rom_4b_3005-16.e5';l:$1000;p:$6000;crc:$afb1c561),(n:'2084_rom_5b_3005-17.c5';l:$1000;p:$7000;crc:$62691e77), (n:'2084_rom_6b_3005-18.a5';l:$1000;p:$8000;crc:$bd2c853d),(n:'2084_rom_7b_3005-19.e6';l:$1000;p:$9000;crc:$49ac400c), (n:'2084_rom_8b_3005-20.c6';l:$1000;p:$a000;crc:$3a96e88c),(n:'2084_rom_9b_3005-21.a6';l:$1000;p:$b000;crc:$b124367b)); robotron_snd:tipo_roms=(n:'video_sound_rom_3_std_767.ic12';l:$1000;p:$f000;crc:$c56c1d28); //Stargate stargate_rom:array[0..11] of tipo_roms=( (n:'stargate_rom_10-a_3002-10.a7';l:$1000;p:$0;crc:$60b07ff7),(n:'stargate_rom_11-a_3002-11.c7';l:$1000;p:$1000;crc:$7d2c5daf), (n:'stargate_rom_12-a_3002-12.e7';l:$1000;p:$2000;crc:$a0396670),(n:'stargate_rom_1-a_3002-1.e4';l:$1000;p:$3000;crc:$88824d18), (n:'stargate_rom_2-a_3002-2.c4';l:$1000;p:$4000;crc:$afc614c5),(n:'stargate_rom_3-a_3002-3.a4';l:$1000;p:$5000;crc:$15077a9d), (n:'stargate_rom_4-a_3002-4.e5';l:$1000;p:$6000;crc:$a8b4bf0f),(n:'stargate_rom_5-a_3002-5.c5';l:$1000;p:$7000;crc:$2d306074), (n:'stargate_rom_6-a_3002-6.a5';l:$1000;p:$8000;crc:$53598dde),(n:'stargate_rom_7-a_3002-7.e6';l:$1000;p:$9000;crc:$23606060), (n:'stargate_rom_8-a_3002-8.c6';l:$1000;p:$a000;crc:$4ec490c7),(n:'stargate_rom_9-a_3002-9.a6';l:$1000;p:$b000;crc:$88187b64)); stargate_snd:tipo_roms=(n:'video_sound_rom_2_std_744.ic12';l:$800;p:$f800;crc:$2fcf6c4d); CPU_SYNC=8; var ram_bank,sound_latch,xoff:byte; rom_data:array[0..$f,0..$fff] of byte; nvram:array[0..$3ff] of byte; linea:word; palette:array[0..$f] of word; pal_lookup:array[0..$ff] of word; events_call:procedure; //joust ram_rom_set,player:boolean; procedure update_video_williams(linea:word); var x,pix:word; puntos:array[0..303] of word; begin if linea>247 then exit; for x:=0 to 151 do begin pix:=memoria[linea+(x*256)]; puntos[x*2]:=pal_lookup[palette[pix shr 4]]; puntos[(x*2)+1]:=pal_lookup[palette[pix and $f]]; end; putpixel(0+ADD_SPRITE,linea+ADD_SPRITE,304,@puntos,1); end; procedure eventos_defender; begin if event.arcade then begin //p1 if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.but3[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.but4[0] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); end; end; procedure eventos_mayday; begin if event.arcade then begin //p1 if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.but3[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); end; end; procedure eventos_colony7; begin if event.arcade then begin //p1 if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.left[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.up[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); end; end; procedure eventos_joust; begin if event.arcade then begin if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); //p1 if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); //p2 if arcade_input.left[1] then marcade.in3:=(marcade.in3 or $1) else marcade.in3:=(marcade.in3 and $fe); if arcade_input.right[1] then marcade.in3:=(marcade.in3 or $2) else marcade.in3:=(marcade.in3 and $fd); if arcade_input.but0[1] then marcade.in3:=(marcade.in3 or $4) else marcade.in3:=(marcade.in3 and $fb); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); end; end; procedure eventos_robotron; begin if event.arcade then begin //p1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.left[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.up[1] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); if arcade_input.down[1] then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); if arcade_input.left[1] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.right[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); end; end; procedure eventos_stargate; begin if event.arcade then begin //p1 if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.but5[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.but3[0] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.but4[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); end; end; procedure williams_principal; var frame_m,frame_s:single; h:byte; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=m6800_0.tframes; while EmuStatus=EsRuning do begin for linea:=0 to 259 do begin for h:=1 to CPU_SYNC do begin //main m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //snd m6800_0.run(frame_s); frame_s:=frame_s+m6800_0.tframes-m6800_0.contador; end; update_video_williams(linea); case linea of 0,32,64,96,128,160,192,224:pia6821_1.cb1_w((linea and $20)<>0); 239:begin actualiza_trozo_final(xoff,7,292,240,1); pia6821_1.ca1_w(true); end; 240:pia6821_1.ca1_w(false); end; end; events_call; video_sync; end; end; function williams_getbyte(direccion:word):byte; begin case direccion of 0..$bfff,$d000..$ffff:williams_getbyte:=memoria[direccion]; $c000..$cfff:case ram_bank of 0:case (direccion and $fff) of $400..$7ff:williams_getbyte:=nvram[direccion and $ff]; $800..$bff:if (linea<$100) then williams_getbyte:=linea and $fc else williams_getbyte:=$fc; $c00..$fff:case (direccion and $1f) of 0..3:williams_getbyte:=pia6821_1.read(direccion and $3); 4..7:williams_getbyte:=pia6821_0.read(direccion and $3); end; end; 1..$f:williams_getbyte:=rom_data[ram_bank-1,direccion and $fff]; end; end; end; procedure williams_putbyte(direccion:word;valor:byte); begin case direccion of $0..$bfff:memoria[direccion]:=valor; $c000..$cfff:case ram_bank of 0:case (direccion and $fff) of 0..$3fe:case (direccion and $1f) of 0..$f:palette[direccion and $f]:=valor; $10..$1f:; //m_cocktail end; $3ff:; //Watch dog $400..$7ff:nvram[direccion and $ff]:=$f0 or valor; $c00..$fff:case (direccion and $1f) of 0..3:pia6821_1.write(direccion and $3,valor); 4..7:pia6821_0.write(direccion and $3,valor); end; end; $1..$f:; end; $d000..$dfff:ram_bank:=valor and $f; $e000..$ffff:; end; end; function williams_snd_getbyte(direccion:word):byte; begin case direccion of 0..$7f:williams_snd_getbyte:=m6800_0.internal_ram[direccion]; $80..$ff:williams_snd_getbyte:=mem_snd[direccion]; $400..$403,$8400..$8403:williams_snd_getbyte:=pia6821_2.read(direccion and $3); $b000..$ffff:williams_snd_getbyte:=mem_snd[direccion]; end; end; procedure williams_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7f:m6800_0.internal_ram[direccion]:=valor; $80..$ff:mem_snd[direccion]:=valor; $400..$403,$8400..$8403:pia6821_2.write(direccion and $3,valor); $b000..$ffff:; end; end; procedure main_irq(state:boolean); begin if (pia6821_1.irq_a_state or pia6821_1.irq_b_state) then m6809_0.change_irq(ASSERT_LINE) else m6809_0.change_irq(CLEAR_LINE); end; procedure snd_irq(state:boolean); begin if (pia6821_2.irq_a_state or pia6821_2.irq_b_state) then m6800_0.change_irq(ASSERT_LINE) else m6800_0.change_irq(CLEAR_LINE); end; procedure snd_write_dac(valor:byte); begin dac_0.data8_w(valor); end; procedure williams_sound; begin dac_0.update; end; procedure sound_write(valor:byte); begin sound_latch:=valor or $c0; pia6821_2.portb_w(sound_latch); pia6821_2.cb1_w(not(sound_latch=$ff)); end; function get_in0:byte; begin get_in0:=marcade.in0; end; function get_in1:byte; begin get_in1:=marcade.in1; end; function get_in2:byte; begin get_in2:=marcade.in2+marcade.dswa; end; //Mayday function mayday_getbyte(direccion:word):byte; begin case direccion of 0..$a192,$a195..$bfff,$d000..$ffff:mayday_getbyte:=memoria[direccion]; $a193:mayday_getbyte:=memoria[$a190]; //Proteccion 1 $a194:mayday_getbyte:=memoria[$a191]; //Proteccion 2 $c000..$cfff:case ram_bank of 0:case (direccion and $fff) of $400..$7ff:mayday_getbyte:=nvram[direccion and $ff]; $800..$bff:if (linea<$100) then mayday_getbyte:=linea and $fc else mayday_getbyte:=$fc; $c00..$fff:case (direccion and $1f) of 0..3:mayday_getbyte:=pia6821_1.read(direccion and $3); 4..7:mayday_getbyte:=pia6821_0.read(direccion and $3); end; end; 1..$f:mayday_getbyte:=rom_data[ram_bank-1,direccion and $fff]; end; end; end; //Joust function joust_getbyte(direccion:word):byte; begin case direccion of 0..$8fff:if ram_rom_set then joust_getbyte:=rom_data[direccion shr 12,direccion and $fff] else joust_getbyte:=memoria[direccion]; $9000..$bfff,$d000..$ffff:joust_getbyte:=memoria[direccion]; $c800..$c8ff:case (direccion and $f) of 4..7:joust_getbyte:=pia6821_0.read(direccion and $3); $c..$f:joust_getbyte:=pia6821_1.read(direccion and $3); end; $cb00..$cbff:if (linea<$100) then joust_getbyte:=linea and $fc else joust_getbyte:=$fc; $cc00..$cfff:joust_getbyte:=nvram[direccion and $3ff]; end; end; procedure joust_putbyte(direccion:word;valor:byte); begin case direccion of $0..$bfff:memoria[direccion]:=valor; $c000..$c3ff:palette[direccion and $f]:=valor; $c800..$c8ff:case (direccion and $f) of 4..7:pia6821_0.write(direccion and $3,valor); $c..$f:pia6821_1.write(direccion and $3,valor); end; $c900..$c9ff:ram_rom_set:=(valor and 1)<>0; $ca00..$caff:blitter_0.blitter_w(direccion and 7,valor); $cbff:; //watchdog $cc00..$cfff:nvram[direccion and $3ff]:=$f0 or valor; $d000..$ffff:; end; end; function joust_in0:byte; begin if player then joust_in0:=marcade.in0 or marcade.in1 else joust_in0:=marcade.in0 or marcade.in3; end; function joust_in1:byte; begin joust_in1:=0; end; procedure joust_cb2(state:boolean); begin player:=state; end; //Main procedure reset_williams; begin m6809_0.reset; m6800_0.reset; pia6821_0.reset; pia6821_1.reset; pia6821_2.reset; if (main_vars.tipo_maquina=321) or (main_vars.tipo_maquina=322) or (main_vars.tipo_maquina=323) then blitter_0.reset; dac_0.reset; reset_audio; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; marcade.in3:=0; ram_bank:=0; sound_latch:=0; ram_rom_set:=false; player:=false; end; procedure close_williams; begin case main_vars.tipo_maquina of 246:write_file(Directory.Arcade_nvram+'defender.nv',@nvram,$100); 248:write_file(Directory.Arcade_nvram+'mayday.nv',@nvram,$100); 249:write_file(Directory.Arcade_nvram+'colony7.nv',@nvram,$100); 321:write_file(Directory.Arcade_nvram+'joust.nv',@nvram,$400); 322:write_file(Directory.Arcade_nvram+'robotron.nv',@nvram,$400); 323:write_file(Directory.Arcade_nvram+'stargate.nv',@nvram,$400); end; end; function iniciar_williams:boolean; const resistances:array[0..2] of integer=(1200,560,330); var color:tcolor; f:byte; memoria_temp:array[0..$ffff] of byte; rweights,gweights,bweights:array[0..2] of single; longitud:integer; begin llamadas_maquina.bucle_general:=williams_principal; llamadas_maquina.reset:=reset_williams; llamadas_maquina.close:=close_williams; llamadas_maquina.fps_max:=60.096154; iniciar_williams:=false; iniciar_audio(false); if main_vars.tipo_maquina=249 then main_screen.rot270_screen:=true; screen_init(1,304,247,false,true); iniciar_video(292,240); //Main CPU m6809_0:=cpu_m6809.Create(12000000 div 3 div 4,260*CPU_SYNC,TCPU_MC6809E); //Sound CPU m6800_0:=cpu_m6800.create(3579545,260*CPU_SYNC,TCPU_M6808); m6800_0.change_ram_calls(williams_snd_getbyte,williams_snd_putbyte); m6800_0.init_sound(williams_sound); //Misc pia6821_0:=pia6821_chip.Create; pia6821_0.change_in_out(get_in0,get_in1,nil,nil); pia6821_1:=pia6821_chip.Create; pia6821_1.change_in_out(get_in2,nil,nil,sound_write); pia6821_1.change_irq(main_irq,main_irq); pia6821_2:=pia6821_chip.Create; pia6821_2.change_in_out(nil,nil,snd_write_dac,nil); pia6821_2.change_irq(snd_irq,snd_irq); //Sound Chip dac_0:=dac_chip.Create; marcade.dswa:=0; xoff:=12; case main_vars.tipo_maquina of 246:begin //defender m6809_0.change_ram_calls(williams_getbyte,williams_putbyte); //cargar roms if not(roms_load(@memoria_temp,defender_rom)) then exit; copymemory(@memoria[$d000],@memoria_temp[0],$3000); for f:=0 to 7 do copymemory(@rom_data[f,0],@memoria_temp[$3000+(f*$1000)],$1000); //roms sonido if not(roms_load(@mem_snd,defender_snd)) then exit; events_call:=eventos_defender; //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'defender.nv',longitud) then read_file(Directory.Arcade_nvram+'defender.nv',@nvram,longitud); end; 248:begin //mayday m6809_0.change_ram_calls(mayday_getbyte,williams_putbyte); //cargar roms if not(roms_load(@memoria_temp,mayday_rom)) then exit; copymemory(@memoria[$d000],@memoria_temp[0],$3000); for f:=0 to 7 do copymemory(@rom_data[f,0],@memoria_temp[$3000+(f*$1000)],$1000); //roms sonido if not(roms_load(@mem_snd,mayday_snd)) then exit; events_call:=eventos_mayday; //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'mayday.nv',longitud) then read_file(Directory.Arcade_nvram+'mayday.nv',@nvram,longitud); end; 249:begin //colony 7 m6809_0.change_ram_calls(williams_getbyte,williams_putbyte); //cargar roms if not(roms_load(@memoria_temp,colony7_rom)) then exit; copymemory(@memoria[$d000],@memoria_temp[0],$3000); for f:=0 to 7 do copymemory(@rom_data[f,0],@memoria_temp[$3000+(f*$1000)],$1000); //roms sonido if not(roms_load(@mem_snd,colony7_snd)) then exit; events_call:=eventos_colony7; marcade.dswa:=$1; marcade.dswa_val:=@colony7_dip_a; //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'colony7.nv',longitud) then read_file(Directory.Arcade_nvram+'colony7.nv',@nvram,longitud); end; 321:begin //joust m6809_0.change_ram_calls(joust_getbyte,joust_putbyte); pia6821_0.change_in_out(joust_in0,joust_in1,nil,nil); pia6821_0.change_cb(joust_cb2); //cargar roms if not(roms_load(@memoria_temp,joust_rom)) then exit; copymemory(@memoria[$d000],@memoria_temp[0],$3000); for f:=0 to 8 do copymemory(@rom_data[f,0],@memoria_temp[$3000+(f*$1000)],$1000); //roms sonido if not(roms_load(@mem_snd,joust_snd)) then exit; events_call:=eventos_joust; blitter_0:=williams_blitter.create(4,false,$c000); blitter_0.set_read_write(joust_getbyte,joust_putbyte); xoff:=6; //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'joust.nv',longitud) then read_file(Directory.Arcade_nvram+'joust.nv',@nvram,longitud); end; 322:begin //robotron m6809_0.change_ram_calls(joust_getbyte,joust_putbyte); //cargar roms if not(roms_load(@memoria_temp,robotron_rom)) then exit; copymemory(@memoria[$d000],@memoria_temp[0],$3000); for f:=0 to 8 do copymemory(@rom_data[f,0],@memoria_temp[$3000+(f*$1000)],$1000); //roms sonido if not(roms_load(@mem_snd,robotron_snd)) then exit; events_call:=eventos_robotron; blitter_0:=williams_blitter.create(4,false,$c000); blitter_0.set_read_write(joust_getbyte,joust_putbyte); xoff:=6; //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'robotron.nv',longitud) then read_file(Directory.Arcade_nvram+'robotron.nv',@nvram,longitud); end; 323:begin //stargate m6809_0.change_ram_calls(joust_getbyte,joust_putbyte); //cargar roms if not(roms_load(@memoria_temp,stargate_rom)) then exit; copymemory(@memoria[$d000],@memoria_temp[0],$3000); for f:=0 to 8 do copymemory(@rom_data[f,0],@memoria_temp[$3000+(f*$1000)],$1000); //roms sonido if not(roms_load(@mem_snd,stargate_snd)) then exit; events_call:=eventos_stargate; blitter_0:=williams_blitter.create(4,false,$c000); blitter_0.set_read_write(joust_getbyte,joust_putbyte); xoff:=6; //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'stargate.nv',longitud) then read_file(Directory.Arcade_nvram+'stargate.nv',@nvram,longitud); end; end; //Palette compute_resistor_weights(0, 255, -1.0, 3,@resistances[0],@rweights[0],0,0, 3,@resistances[0],@gweights[0],0,0, 2,@resistances[1],@bweights[0],0,0); for f:=0 to $ff do begin color.r:=combine_3_weights(@rweights[0],(f shr 0) and 1,(f shr 1) and 1,(f shr 2) and 1); color.g:=combine_3_weights(@gweights[0],(f shr 3) and 1,(f shr 4) and 1,(f shr 5) and 1); color.b:=combine_2_weights(@bweights[0],(f shr 6) and 1,(f shr 7) and 1); pal_lookup[f]:=convert_pal_color(color); end; //final reset_williams; iniciar_williams:=true; end; end.
unit Character.Status; interface Uses System.SysUtils, Base.Def, Base.Struct, Thread.Main, FireDAC.Comp.Client; Type tCharacterStatus = Class Private { Private class } FId_Character: Integer; FLevel: Cardinal; FDefence: Cardinal; FAttack: Cardinal; FMerchant: Byte; FSpeed: Byte; FInu1: Byte; FInu2: Byte; FMaxHP: Cardinal; FMaxMP: Cardinal; // integer FHP: Cardinal; FMP: Cardinal; // integer FStr: Word; FInt: Word; // smallint FDex: Word; FCon: Word; // smallint FwMaster: Word; FfMaster: Word; FsMaster: Word; FtMaster: Word; Public { Public class } property Id_Character: Integer read FId_Character write FId_Character; property Level: Cardinal read FLevel write FLevel; property Defence: Cardinal read FDefence write FDefence; property Attack: Cardinal read FAttack write FAttack; property Merchant: Byte read FMerchant write FMerchant; property Speed: Byte read FSpeed write FSpeed; property Inu1: Byte read FInu1 write FInu1; property Inu2: Byte read FInu2 write FInu2; property MaxHP: Cardinal read FMaxHP write FMaxHP; property MaxMP: Cardinal read FMaxMP write FMaxMP; property HP: Cardinal read FHP write FHP; property MP: Cardinal read FMP write FMP; property Str: Word read FStr write FStr; property Int: Word read FInt write FInt; property Dex: Word read FDex write FDex; property Con: Word read FCon write FCon; property wMaster: Word read FwMaster write FwMaster; property fMaster: Word read FfMaster write FfMaster; property sMaster: Word read FsMaster write FsMaster; property tMaster: Word read FtMaster write FtMaster; class function CreatCharacterStatus(Player: sPlayer; CharID: Word): Boolean; class function LoadCharacterStatus(CharID: Word): sPlayer; End; implementation class function tCharacterStatus.LoadCharacterStatus(CharID: Word): sPlayer; var qStatus: TFDQuery; sSQL: String; id_Slot: Word; begin sSQL := 'WHERE id_character=' + IntToStr(CharID); qStatus := FunctionBase.SelectTable(TableCharacterStatus, '*', '', sSQL); end; class function tCharacterStatus.CreatCharacterStatus(Player: sPlayer; CharID: Word): Boolean; var qCharacter: TFDQuery; qStatus: TFDQuery; cSQL, sSQL: String; begin cSQL := 'WHERE id_account=' + IntToStr(Player.ID_ACC) + ' AND character_Slot=' + IntToStr(CharID); qCharacter := FunctionBase.SelectTable(TableCharacter, 'ID,Character_Slot', '', cSQL); if Not qCharacter.IsEmpty then begin sSQL := 'WHERE id_character=' + qCharacter.FieldByName('ID').AsString; qStatus := FunctionBase.SelectTable(TableCharacterStatus, '', '', sSQL); if qStatus.IsEmpty then begin With qStatus Do begin Try Insert; FieldByName('id_character').AsInteger := qCharacter.FieldByName('id') .AsInteger; FieldByName('level').AsInteger := 0; FieldByName('defence').AsInteger := 0; FieldByName('attack').AsInteger := 0; FieldByName('merchant').AsInteger := Player.Character[CharID] .Equip[0].Index; FieldByName('speed').AsInteger := 1; FieldByName('inu1').AsInteger := 0; FieldByName('inu2').AsInteger := 0; FieldByName('maxHP').AsInteger := 100; FieldByName('maxMP').AsInteger := 100; FieldByName('HP').AsInteger := 100; FieldByName('MP').AsInteger := 100; FieldByName('s_str').AsInteger := Player.Character[CharID] .bStatus.Str; FieldByName('s_int').AsInteger := Player.Character[CharID] .bStatus.Int; FieldByName('s_dex').AsInteger := Player.Character[CharID] .bStatus.Dex; FieldByName('s_con').AsInteger := Player.Character[CharID] .bStatus.Con; FieldByName('wMaster').AsInteger := Player.Character[CharID] .bStatus.wMaster; FieldByName('fMaster').AsInteger := Player.Character[CharID] .bStatus.fMaster; FieldByName('sMaster').AsInteger := Player.Character[CharID] .bStatus.sMaster; FieldByName('tMaster').AsInteger := Player.Character[CharID] .bStatus.tMaster; // FieldByName('character_slot').AsInteger := CharID; //desativado Post; Result := True Except On E: Exception do begin Result := False; end; End; end; end; end; end; end.
{$OPTIMIZATION OFF} unit VncServerAsDll; interface uses Windows; const C_MAXPWLEN = 8; C_OK = 0; type PvncPropertiesStruct = ^TvncPropertiesStruct; TVncServerAsDll = class protected class var FDll: THandle; FStarted: Boolean; public class function Load : Boolean; class function UnLoad : Boolean; class function IsLoaded: Boolean; class function Started : Boolean; class function WinVNCDll_Init (aInstance: LongWord): Integer; class function WinVNCDll_CreateServer (): Integer; class function WinVNCDll_GetProperties (aStruct: PvncPropertiesStruct): Integer; class function WinVNCDll_SetProperties (aStruct: PvncPropertiesStruct): Integer; class function WinVNCDll_GetPollProperties(): Integer; class function WinVNCDll_RunServer (): Integer; class function WinVNCDll_DestroyServer (): Integer; end; //vncProperties.h TvncPropertiesStruct = record DebugMode: Integer; Avilog: Integer; path: PAnsiChar; DebugLevel: Integer; AllowLoopback: Integer; LoopbackOnly: Integer; AllowShutdown: Integer; AllowProperties: Integer; AllowEditClients: Integer; FileTransferTimeout: Integer; KeepAliveInterval: Integer; SocketKeepAliveTimeout: Integer; DisableTrayIcon: Integer; MSLogonRequired: Integer; NewMSLogon: Integer; UseDSMPlugin: Integer; ConnectPriority: Integer; DSMPlugin : PAnsiChar; DSMPluginConfig: PAnsiChar; //user settings: //*************************** FileTransferEnabled: Integer; FTUserImpersonation: Integer; BlankMonitorEnabled: Integer; BlankInputsOnly: Integer; CaptureAlphaBlending: Integer; BlackAlphaBlending: Integer; DefaultScale: Integer; //int UseDSMPlugin; //char * DSMPlugin; //char * DSMPluginConfig; primary: Integer; secondary: Integer; // Connection prefs SocketConnect: Integer; HTTPConnect: Integer; XDMCPConnect: Integer; AutoPortSelect: Integer; PortNumber: Integer; HTTPPortNumber: Integer; InputsEnabled: Integer; LocalInputsDisabled: Integer; IdleTimeout: Integer; EnableJapInput: Integer; clearconsole: Integer; sendbuffer: Integer; // Connection querying settings QuerySetting: Integer; QueryTimeout: Integer; QueryAccept: Integer; QueryIfNoLogon: Integer; // Lock settings LockSetting: Integer; // Wallpaper removal RemoveWallpaper: Integer; // UI Effects RemoveEffects: Integer; RemoveFontSmoothing: Integer; // Composit desktop removal RemoveAero: Integer; password : array[0..C_MAXPWLEN-1] of AnsiChar; password_view: array[0..C_MAXPWLEN-1] of AnsiChar; end; implementation type //WinVNCdll.cpp TWinVNCDll_Init = function(hInstance: LongWord): Integer;stdcall; TWinVNCDll_CreateServer = function(): Integer;stdcall; TWinVNCDll_GetProperties = function(aStruct: PvncPropertiesStruct): Integer;stdcall; TWinVNCDll_SetProperties = function(aStruct: PvncPropertiesStruct): Integer;stdcall; TWinVNCDll_GetPollProperties = function(): Integer;stdcall; TWinVNCDll_RunServer = function(): Integer;stdcall; TWinVNCDll_DestroyServer = function(): Integer;stdcall; var pWinVNCDll_Init : TWinVNCDll_Init; pWinVNCDll_CreateServer : TWinVNCDll_CreateServer; pWinVNCDll_GetProperties : TWinVNCDll_GetProperties; pWinVNCDll_SetProperties : TWinVNCDll_SetProperties; pWinVNCDll_GetPollProperties: TWinVNCDll_GetPollProperties; pWinVNCDll_RunServer : TWinVNCDll_RunServer; pWinVNCDll_DestroyServer : TWinVNCDll_DestroyServer; { TVncServerAsDll } class function TVncServerAsDll.IsLoaded: Boolean; begin Result := (FDll > 0); end; class function TVncServerAsDll.Load: Boolean; begin FDll := LoadLibrary(PChar('winvncdll.dll')); Result := (FDll > 0); if not Result then Exit; pWinVNCDll_Init := GetProcAddress(FDll, 'WinVNCDll_Init'); pWinVNCDll_CreateServer := GetProcAddress(FDll, 'WinVNCDll_CreateServer'); pWinVNCDll_GetProperties := GetProcAddress(FDll, 'WinVNCDll_GetProperties'); pWinVNCDll_SetProperties := GetProcAddress(FDll, 'WinVNCDll_SetProperties'); pWinVNCDll_GetPollProperties := GetProcAddress(FDll, 'WinVNCDll_GetPollProperties'); pWinVNCDll_RunServer := GetProcAddress(FDll, 'WinVNCDll_RunServer'); pWinVNCDll_DestroyServer := GetProcAddress(FDll, 'WinVNCDll_DestroyServer'); end; class function TVncServerAsDll.UnLoad: Boolean; begin Result := FreeLibrary(FDll); FDll := 0; FStarted := False; end; class function TVncServerAsDll.Started: Boolean; begin Result := IsLoaded and FStarted; end; class function TVncServerAsDll.WinVNCDll_Init(aInstance: LongWord): Integer; begin Assert(FDll > 0); Assert(Assigned(pWinVNCDll_Init)); Result := pWinVNCDll_Init(aInstance); Assert(Result = 0); end; class function TVncServerAsDll.WinVNCDll_CreateServer: Integer; begin Assert(FDll > 0); Assert(Assigned(pWinVNCDll_CreateServer)); Result := pWinVNCDll_CreateServer; end; class function TVncServerAsDll.WinVNCDll_GetPollProperties: Integer; begin Assert(FDll > 0); Assert(Assigned(pWinVNCDll_GetPollProperties)); Result := pWinVNCDll_GetPollProperties; end; class function TVncServerAsDll.WinVNCDll_GetProperties(aStruct: PvncPropertiesStruct): Integer; begin Assert(FDll > 0); Assert(Assigned(pWinVNCDll_GetProperties)); //note: properties are default or loaded from "ultravnc.ini" Result := pWinVNCDll_GetProperties(aStruct); Assert(Result = 0); end; class function TVncServerAsDll.WinVNCDll_SetProperties(aStruct: PvncPropertiesStruct): Integer; begin Assert(FDll > 0); Assert(Assigned(pWinVNCDll_SetProperties)); Result := pWinVNCDll_SetProperties(aStruct); Assert(Result = 0); end; class function TVncServerAsDll.WinVNCDll_RunServer: Integer; begin FStarted := False; Assert(FDll > 0); Assert(Assigned(pWinVNCDll_RunServer)); Result := pWinVNCDll_RunServer; FStarted := (Result = C_OK); end; class function TVncServerAsDll.WinVNCDll_DestroyServer: Integer; begin FStarted := False; Assert(FDll > 0); Assert(Assigned(pWinVNCDll_DestroyServer)); Result := pWinVNCDll_DestroyServer; end; end.
unit vos_win32_storemem; interface uses Windows; const MEM_PHYSICAL = $400000; // Address Windowing Extensions (AWE) for Delphi allows your 32bit applications to // quickly manipulate physical memory greater than 4GB type PPhysicalMemory = ^TPhysicalMemory; TPhysicalMemory = packed record MemoryHandle : LongWord; Map : Pointer; end; PMemoryItem = ^TMemoryItem; TMemoryItem = record Memory : Pointer; PageCount : LongWord; Pages : array [0..MaxInt div 8] of LongWord; end; // size of total physical memory in bytes function TotalPhysicalMemory: Int64; // size of available physical memory in bytes function AvailablePhysicalMemory: Int64; function GetMemoryPageSize: LongWord; function UnmapPhysicalMemory(Handle: LongWord): Boolean; implementation type TMEMORYSTATUSEX = record dwLength : DWORD; dwMemoryLoad : DWORD; ullTotalPhys : Int64; ullAvailPhys : Int64; ullTotalPageFile : Int64; ullAvailPageFile : Int64; ullTotalVirtual : Int64; ullAvailVirtual : Int64; ullAvailExtendedVirtual: Int64; end; function AllocateUserPhysicalPages(hProcess: THANDLE; var NumberOfPages: ULONG; PageArray: Pointer): BOOL; stdcall; external kernel32 name 'AllocateUserPhysicalPages'; function FreeUserPhysicalPages(hProcess: THANDLE; var NumberOfPages: ULONG; PageArray: Pointer): BOOL; stdcall; external kernel32 name 'FreeUserPhysicalPages'; function MapUserPhysicalPages(VirtualAddress: Pointer; NumberOfPages: ULONG; PageArray: Pointer): BOOL; stdcall; external kernel32 name 'MapUserPhysicalPages'; function MapUserPhysicalPagesScatter(var VirtualAddresses: Pointer; var NumberOfPages: ULONG; PageArray: Pointer): BOOL; stdcall; external kernel32 name 'MapUserPhysicalPagesScatter'; function GlobalMemoryStatusEx(var lpBuffer: TMEMORYSTATUSEX): BOOL; stdcall; external kernel32 name 'GlobalMemoryStatusEx'; // size of the memory page function GetMemoryPageSize: LongWord; var SystemInfo: TSystemInfo; begin GetSystemInfo(SystemInfo); Result := SystemInfo.dwPageSize; end; // size of total physical memory function TotalPhysicalMemory: Int64; var MemoryStatus: TMEMORYSTATUSEX; begin MemoryStatus.dwLength := SizeOf(MemoryStatus); if GlobalMemoryStatusEx(MemoryStatus) then Result := MemoryStatus.ullTotalPhys else Result := 0; end; // size of available physical memory function AvailablePhysicalMemory: Int64; var MemoryStatus: TMEMORYSTATUSEX; begin MemoryStatus.dwLength := SizeOf(MemoryStatus); if GlobalMemoryStatusEx(MemoryStatus) then Result := MemoryStatus.ullAvailPhys else Result := 0; end; // obtain or release the privilege of locking physical pages function SetLockPagesPrivilege(AProcessHandle: THANDLE; AIsEnabled: Boolean): Boolean; const SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege'; type DWORDPTR = ^DWORD; var tmpToken: THANDLE; tmpTokenInfo: TTokenPrivileges; begin // open the token Result := Windows.OpenProcessToken(AProcessHandle, TOKEN_ADJUST_PRIVILEGES, tmpToken); if not Result then Exit; try // enable or disable tmpTokenInfo.PrivilegeCount := 1; if AIsEnabled then tmpTokenInfo.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED else tmpTokenInfo.Privileges[0].Attributes := 0; // get the LUID Result := Windows.LookupPrivilegeValue(nil, SE_LOCK_MEMORY_NAME, tmpTokenInfo.Privileges[0].Luid); if not Result then Exit; // adjust the privilege Result := Windows.AdjustTokenPrivileges(tmpToken, False, tmpTokenInfo, 0, PTokenPrivileges(nil)^, DWORDPTR(nil)^); if not Result then Exit; Result := Windows.GetLastError = ERROR_SUCCESS; finally Windows.CloseHandle(tmpToken); end; end; // allocate physical memory (returns 0 if cannot allocate) function AllocPhysicalMemory(ASize: LongWord): LongWord; var PageCount: LongWord; MemoryItem: PMemoryItem; begin Result := 0; if not SetLockPagesPrivilege(GetCurrentProcess, True) then Exit; PageCount := ASize div GetMemoryPageSize; if ASize mod GetMemoryPageSize <> 0 then Inc(PageCount); MemoryItem := System.AllocMem(8 + PageCount * SizeOf(LongWord)); if MemoryItem = nil then Exit; try // allocate the physical memory MemoryItem.PageCount := PageCount; if not AllocateUserPhysicalPages(GetCurrentProcess, PageCount, @MemoryItem.Pages[0]) then Exit; // check whether all pages was allocated if PageCount <> MemoryItem.PageCount then begin FreeUserPhysicalPages(GetCurrentProcess, PageCount, @MemoryItem.Pages[0]); Exit; end; Result := LongWord(MemoryItem); finally if Result = 0 then FreeMem(MemoryItem); end; end; // free physical memory function FreePhysicalMemory(Handle: LongWord): Boolean; var MemoryItem: PMemoryItem; begin Result := UnmapPhysicalMemory(Handle); // free the physical pages MemoryItem := PMemoryItem(Handle); if not FreeUserPhysicalPages(GetCurrentProcess, MemoryItem.PageCount, @MemoryItem.Pages[0]) then Result := False; FreeMem(MemoryItem); end; // map physical memory to virtual memory space function MapPhysicalMemory(Handle: LongWord): Pointer; var MemoryItem: PMemoryItem; begin MemoryItem := PMemoryItem(Handle); Result := MemoryItem.Memory; if Result <> nil then Exit; // already mapped // reserve the virtual memory Result := Windows.VirtualAlloc(nil, MemoryItem.PageCount * GetMemoryPageSize, MEM_RESERVE or MEM_PHYSICAL, PAGE_READWRITE); if Result = nil then Exit; // map the physical memory into the virtual memory space if not MapUserPhysicalPages(Result, MemoryItem.PageCount, @MemoryItem.Pages[0]) then begin VirtualFree(Result, 0, MEM_RELEASE); Result := nil; Exit; end; MemoryItem.Memory := Result; end; // unmap physical memory from virtual memory space function UnmapPhysicalMemory(Handle: LongWord): Boolean; var MemoryItem: PMemoryItem; begin Result := True; MemoryItem := PMemoryItem(Handle); if MemoryItem.Memory = nil then Exit; // already unmapped // unmap physical memory if not MapUserPhysicalPages(MemoryItem.Memory, MemoryItem.PageCount, nil) then Result := False; // free virtual memory if not Windows.VirtualFree(MemoryItem.Memory, 0, MEM_RELEASE) then Result := False; MemoryItem.Memory := nil; end; end.
unit eAtasOrais.Controller.Atas; interface uses eAtasOrais.Controller.interfaces, System.Generics.Collections, eAtasOrais.Model.ClasseAlunosConceitos, System.Classes; Type TControllerAtas = Class(TInterfacedObject, iControllerAtas) Private FPeriodo : string; FAlunos : TStrings; FConceitos : TStrings; FExaminador : String; FTurma : string; FDias : string; Fhorario : string; Public Constructor Create; Destructor Destroy; Override; Class function New: iControllerAtas; Function Periodo (Value : String) : iControllerAtas; function Alunos (Value : TStrings) : iControllerAtas; function Conceitos (Value : TStrings) : iControllerAtas; Function Examinador (Value : String) : iControllerAtas; Function Turma (Value : string) : iControllerAtas; Function Dias (Value : String) : iControllerAtas; Function horario (Value : string) : iControllerAtas; Function Gerar : Boolean; End; implementation uses eAtasOrais.view.principal, eAtasOrais.Model.Atas, FMX.Dialogs; { TControllerAtas } function TControllerAtas.Alunos(Value: TStrings): iControllerAtas; begin Result := self; FAlunos := Value; end; function TControllerAtas.Conceitos(Value: TStrings): iControllerAtas; begin Result := self; FConceitos := Value; end; constructor TControllerAtas.Create; begin end; destructor TControllerAtas.Destroy; begin inherited; end; function TControllerAtas.Dias(Value: String): iControllerAtas; begin Result := self; FDias := Value; end; function TControllerAtas.Examinador(Value: String): iControllerAtas; begin Result := self; FExaminador := Value; end; function TControllerAtas.Gerar: Boolean; Var Periodo, Turma, Dias, Horario, Examinador : string; Alunos : TStrings; Conceitos : TStrings; begin Periodo := FPeriodo; Turma := FTurma; Dias := FDias; Horario := Fhorario; Examinador := FExaminador; Alunos := FAlunos; Conceitos := FConceitos; formprincipal.LayMsg.Visible := true; FormPrincipal.TabMensagem.ActiveTab := formprincipal.TabProcessando; FormPrincipal.MsgAnimation.Enabled := true; tthread.CreateAnonymousThread( Procedure var Teste : boolean; begin teste := tmodelAtas.New .Periodo(Periodo) .Turma(Turma) .Dias(dias) .horario(horario) .Examinador(Examinador) .Alunos(Alunos) .Conceitos(Conceitos) .Gerar; tthread.Synchronize(tthread.CurrentThread, Procedure begin if teste = true then begin FormPrincipal.MsgAnimation.Enabled := False; FormPrincipal.TabMensagem.Next(); FormPrincipal.AnimaMsgFecha.Start; end; end ); end ).Start; Result := True; end; function TControllerAtas.horario(Value: string): iControllerAtas; begin Result := self; Fhorario := Value; end; class function TControllerAtas.New: iControllerAtas; begin Result := Self.Create; end; function TControllerAtas.Periodo(Value: String): iControllerAtas; begin Result := self; FPeriodo := Value; end; function TControllerAtas.Turma(Value: string): iControllerAtas; begin Result := self; Fturma := Value; end; end.
unit kwPopComboBoxDropDown; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopComboBoxDropDown.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::ControlsProcessing::pop_ComboBox_DropDown // // *Формат:* // {code} // aDown aControlObj pop:ComboBox:DropDown // {code} // *Описание:* Показывает/прячет выпадающий список у ComboBox'а в зависимости от значения параметра // aDown. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses StdCtrls, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} TkwPopComboBoxDropDown = {final} class(_kwComboBoxFromStack_) {* *Формат:* [code] aDown aControlObj pop:ComboBox:DropDown [code] *Описание:* Показывает/прячет выпадающий список у ComboBox'а в зависимости от значения параметра aDown. } protected // realized methods procedure DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopComboBoxDropDown {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopComboBoxDropDown; {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} // start class TkwPopComboBoxDropDown procedure TkwPopComboBoxDropDown.DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); //#UC START# *5049C8740203_504D87D30327_var* //#UC END# *5049C8740203_504D87D30327_var* begin //#UC START# *5049C8740203_504D87D30327_impl* if aCtx.rEngine.IsTopBool then aCombobox.DroppedDown := aCtx.rEngine.PopBool else Assert(False, 'Не задан флаг для выпадающего списка.'); //#UC END# *5049C8740203_504D87D30327_impl* end;//TkwPopComboBoxDropDown.DoWithComboBox class function TkwPopComboBoxDropDown.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:ComboBox:DropDown'; end;//TkwPopComboBoxDropDown.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} {$IfEnd} //not NoScripts end.
unit clEnderecosCadastro; interface uses clendereco, clConexao, Vcl.Dialogs, System.SysUtils; type TEndrecosCadastro = class(TEndereco) private FCadastro: Integer; FTipo: String; FCorrespondencia: Integer; conexao : TConexao; procedure SetEmpresa(val: Integer); procedure SetTipo(val: String); procedure SetCorrespondencia(val: Integer); public property Cadastro: Integer read FCadastro write SetEmpresa; property Tipo: String read FTipo write SetTipo; property Correspondencia: Integer read FCorrespondencia write SetCorrespondencia; constructor Create; destructor Destroy; override; function Validar: Boolean; function Insert: Boolean; function Update: Boolean; function Delete(sFiltro: String): Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getField(sCampo: String; sColuna: String): String; function getObjects: Boolean; end; const TABLENAME = 'CAD_ENDERECOS_CADASTRO'; implementation uses udm; procedure TEndrecosCadastro.SetEmpresa(val: Integer); begin FCadastro := val; end; procedure TEndrecosCadastro.SetTipo(val: String); begin fTipo := val; end; procedure TEndrecosCadastro.SetCorrespondencia(val: Integer); begin FCorrespondencia := val; end; constructor TEndrecosCadastro.Create; begin inherited Create; conexao := TConexao.Create; end; destructor TEndrecosCadastro.Destroy; begin conexao.Free; inherited Destroy; end; function TEndrecosCadastro.Validar: Boolean; begin Result := False; if Self.Cadastro = 0 then begin MessageDlg('Código de Cadastro inválido!',mtWarning,[mbCancel],0); Exit; end; {if Self.Cadastro = 0 then begin MessageDlg('Sequência de Endereço inválida!',mtWarning,[mbCancel],0); Exit; end;} if Self.Tipo.IsEmpty then begin MessageDlg('Informe o Tipo de Endereço!',mtWarning,[mbCancel],0); Exit; end; if Self.Endereco.IsEmpty then begin MessageDlg('Informe o Endereço!',mtWarning,[mbCancel],0); Exit; end; if Self.Numero.IsEmpty then begin MessageDlg('Informe o Número do Endereço (caso não exista informe SN ou 0)!',mtWarning,[mbCancel],0); Exit; end; if Self.Bairro.IsEmpty then begin MessageDlg('Informe o Bairro do Endereço!',mtWarning,[mbCancel],0); Exit; end; if Self.Cidade.IsEmpty then begin MessageDlg('Informe a Cidade do Endereço!',mtWarning,[mbCancel],0); Exit; end; if Self.UF.IsEmpty then begin MessageDlg('Informe a Sigla do Estado do Endereço!',mtWarning,[mbCancel],0); Exit; end; Result := True; end; function TEndrecosCadastro.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; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_CADASTRO, ' + 'DES_TIPO, ' + 'DOM_CORRESPONDENCIA,' + 'DES_LOGRADOURO, ' + 'NUM_LOGRADOURO, ' + 'DES_COMPLEMENTO, ' + 'DES_BAIRRO, ' + 'NOM_CIDADE, ' + 'UF_ESTADO, ' + 'NUM_CEP, ' + 'DES_REFERENCIA) ' + 'VALUES(' + ':CODIGO, ' + ':SEQUENCIA, ' + ':TIPO, ' + ':CORRESPONDENCIA, ' + ':ENDERECO, ' + ':NUMERO, ' + ':COMPLEMENTO, ' + ':BAIRRO, ' + ':CIDADE, ' + ':UF, ' + ':CEP, ' + ':REFERENCIA);'; dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Cadastro; dm.QryCRUD.ParamByName('TIPO').AsString := Self.Tipo; dm.QryCRUD.ParamByName('ENDERECO').AsString := Self.Endereco; dm.QryCRUD.ParamByName('NUMERO').AsString := Self.Numero; dm.QryCRUD.ParamByName('COMPLEMENTO').AsString := Self.Complemento; dm.QryCRUD.ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia; dm.QryCRUD.ParamByName('BAIRRO').AsString := Self.Bairro; dm.QryCRUD.ParamByName('CIDADE').AsString := Self.Cidade; dm.QryCRUD.ParamByName('UF').AsString := Self.UF; dm.QryCRUD.ParamByName('CEP').AsString := Self.Cep; dm.QryCRUD.ParamByName('REFERENCIA').AsString := Self.Referencia; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosCadastro.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; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DOM_CORRESPONDENCIA = :CORRESPONDENCIA, ' + 'DES_LOGRADOURO = :ENDERECO, ' + 'NUM_LOGRADOURO = :NUMERO, ' + 'DES_COMPLEMENTO = :COMPLEMENTO, ' + 'DES_BAIRRO = :BAIRRO, ' + 'NOM_CIDADE = :CIDADE, ' + 'UF_ESTADO = :UF, ' + 'NUM_CEP = :CEP, ' + 'DES_REFERENCIA = :REFERENCIA ' + 'WHERE COD_CASTRO = :CODIGO AND DES_TIPO = :TIPO'; dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Cadastro; dm.QryCRUD.ParamByName('TIPO').AsString := Self.Tipo; dm.QryCRUD.ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia; dm.QryCRUD.ParamByName('ENDERECO').AsString := Self.Endereco; 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.UF; dm.QryCRUD.ParamByName('CEP').AsString := Self.Cep; dm.QryCRUD.ParamByName('REFERENCIA').AsString := Self.Referencia; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosCadastro.Delete(sFiltro: String): Boolean; begin try Result := False; if sFiltro.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.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('DELETE FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin dm.QryCRUD.SQL.Add('WHERE COD_EMPRESA = :CODIGO'); dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Cadastro; end else if sFiltro = 'TIPO' then begin dm.QryCRUD.SQL.Add('WHERE COD_EMPRESA = :CODIGO AND DES_TIPO = :TIPO'); dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Cadastro; dm.QryCRUD.ParamByName('TIPO').AsString := Self.Tipo; end; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosCadastro.getObject(sId: String; sFiltro: String): Boolean; begin try Result := False; if sId.IsEmpty then begin Exit; end; if sFiltro.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.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin dm.QryGetObject.SQL.Add('WHERE COD_CADASTRO = :CODIGO'); dm.QryGetObject.ParamByName('CODIGO').AsInteger := StrToInt(sId); end else if sFiltro = 'CHAVE' then begin dm.QryGetObject.SQL.Add('WHERE COD_CADASTRO = :CODIGO AND DES_TIPO = :TIPO'); dm.QryGetObject.ParamByName('CODIGO').AsInteger := Self.Cadastro; dm.QryGetObject.ParamByName('TIPO').AsString := sId; end else if sFiltro = 'TIPO' then begin dm.QryGetObject.SQL.Add('WHERE DES_TIPO = :TIPO'); dm.QryGetObject.ParamByName('TIPO').AsString := sId; end else if sFiltro = 'ENDERECO' then begin dm.QryGetObject.SQL.Add('WHERE DES_LOGRADOURO LIKE :ENDERECO'); dm.QryGetObject.ParamByName('ENDERECO').AsString := sId; end else if sFiltro = 'BAIRRO' then begin dm.QryGetObject.SQL.Add('WHERE DES_BAIRRO LIKE :BAIRRO'); dm.QryGetObject.ParamByName('BAIRRO').AsString := sId; end else if sFiltro = 'CIDADE' then begin dm.QryGetObject.SQL.Add('WHERE DES_CIDADE LIKE :CIDADE'); dm.QryGetObject.ParamByName('CIDADE').AsString := sId; end else if sFiltro = 'UF' then begin dm.QryGetObject.SQL.Add('WHERE UF_ESTADO = :UF'); dm.QryGetObject.ParamByName('UF').AsString := sId; end else if sFiltro = 'CEP' then begin dm.QryGetObject.SQL.Add('WHERE NUM_CEP = :CEP'); dm.QryGetObject.ParamByName('CEP').AsString := sId; end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; Self.Cadastro := dm.QryGetObject.FieldByName('COD_CADASTRO').AsInteger; Self.Tipo := dm.QryGetObject.FieldByName('DES_TIPO').AsString; Self.Endereco := 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('DES_BAIRRO').AsString; Self.Cidade := dm.QryGetObject.FieldByName('NOM_CIDADE').AsString; Self.Cep := dm.QryGetObject.FieldByName('NUM_CEP').AsString; Self.Referencia := dm.QryGetObject.FieldByName('DES_REFERENCIA').AsString; Self.UF := dm.QryGetObject.FieldByName('UF_ESTADO').AsString; Self.Correspondencia := dm.QryGetObject.FieldByName('DOM_CORRESPONDENCIA').AsInteger; Result := True; Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosCadastro.getField(sCampo: String; sColuna: String): String; begin try 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 = 'CODIGO' then begin dm.qryFields.SQL.Add('WHERE COD_CADASTRO = :CODIGO'); dm.qryFields.ParamByName('CODIGO').AsInteger := sELF.Cadastro; end else if sColuna = 'TIPO' then begin dm.qryFields.SQL.Add('WHERE DES_TIPO = :TIPO'); dm.qryFields.ParamByName('TIPO').AsString := Self.Tipo; end else if sColuna = 'ENDERECO' then begin dm.qryFields.SQL.Add('WHERE DES_LOGRADOURO = :ENDERECO'); dm.qryFields.ParamByName('ENDERECO').AsString := Self.Endereco; end else if sColuna = 'BAIRRO' then begin dm.qryFields.SQL.Add('WHERE DES_BAIRRO = :BAIRRO'); dm.qryFields.ParamByName('BAIRRO').AsString := Self.Bairro; end else if sColuna = 'CIDADE' then begin dm.qryFields.SQL.Add('WHERE DES_CIDADE = :CIDADE'); dm.qryFields.ParamByName('CIDADE').AsString := Self.Cidade; end else if sColuna = 'UF' then begin dm.qryFields.SQL.Add('WHERE UF_ESTADO = :UF'); dm.qryFields.ParamByName('UF').AsString := Self.UF; end else if sColuna = 'CEP' then begin dm.qryFields.SQL.Add('WHERE NUM_CEP = :CEP'); dm.qryFields.ParamByName('CEP').AsString := Self.Cep; end; dm.ZConn.PingServer; dm.qryFields.Open; 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; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosCadastro.getObjects: 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.qryGetObject.Active then begin dm.qryGetObject.Close; end; dm.qryGetObject.SQL.Clear; dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; dm.qryGetObject.Open; if (not dm.qryGetObject.IsEmpty) then begin Result := True; Exit; end; dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end.
unit kwRenameFile; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwRenameFile.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FileProcessing::RenameFile // // RenameFile - переименовывает файл. // *Формат:* aOldFileName aNewFileName RenameFile // * aNewFileName - новое имя файла. // * aOldFileName - старое имя файла. // В стек помещается результат операции: true - если успешно, false - если переименование не // получилось. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} TkwRenameFile = {final} class(_tfwAutoregisteringWord_) {* RenameFile - переименовывает файл. *Формат:* aOldFileName aNewFileName RenameFile * aNewFileName - новое имя файла. * aOldFileName - старое имя файла. В стек помещается результат операции: true - если успешно, false - если переименование не получилось. } protected // realized methods procedure DoDoIt(const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwRenameFile {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses SysUtils, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwRenameFile; {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} // start class TkwRenameFile procedure TkwRenameFile.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_509111620309_var* var l_NewFileName: AnsiString; l_OldFileName: AnsiString; //#UC END# *4DAEEDE10285_509111620309_var* begin //#UC START# *4DAEEDE10285_509111620309_impl* if aCtx.rEngine.IsTopString then begin l_NewFileName := aCtx.rEngine.PopDelphiString; if aCtx.rEngine.IsTopString then begin l_OldFileName := aCtx.rEngine.PopDelphiString; aCtx.rEngine.PushBool(RenameFile(l_OldFileName, l_NewFileName)); end // if aCtx.rEngine.IsTopString then else Assert(False, 'Не задано старое имя файла!'); end // if aCtx.rEngine.IsTopString then else Assert(False, 'Не задано новое имя файла!'); //#UC END# *4DAEEDE10285_509111620309_impl* end;//TkwRenameFile.DoDoIt class function TkwRenameFile.GetWordNameForRegister: AnsiString; {-} begin Result := 'RenameFile'; end;//TkwRenameFile.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} {$IfEnd} //not NoScripts end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, OAuth.GMail, Quick.OAuth, FMX.Objects; type TForm1 = class(TForm) Label1: TLabel; efClientID: TEdit; Label2: TLabel; efSecretID: TEdit; Label3: TLabel; efCallbackURL: TEdit; Label5: TLabel; btnAuthorise: TButton; lbAccessToken: TLabel; Label6: TLabel; Label7: TLabel; btnRefresh: TButton; cbUseExisting: TCheckBox; Label4: TLabel; crcAuthorise: TCircle; crcRefresh: TCircle; cbMakeTokenExpire: TCheckBox; RoundRect1: TRoundRect; RoundRect2: TRoundRect; lbExpiration: TLabel; RoundRect3: TRoundRect; lbRefreshToken: TLabel; RoundRect4: TRoundRect; lbReloadedToken: TLabel; Label8: TLabel; procedure btnAuthoriseClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fGMail: TOAuthGMail; fRetrieved: TDateTime; procedure SaveCredentials (const aToken: TOAuthToken); procedure LoadCredentials (var aToken: TOAuthToken); public { Public declarations } end; var Form1: TForm1; implementation uses System.DateUtils; {$R *.fmx} procedure TForm1.btnAuthoriseClick(Sender: TObject); begin crcAuthorise.Fill.Color:=TAlphaColorRec.Red; FreeAndNil(fGMail); fGMail:=TOAuthGMail.Create(efClientID.Text, efSecretID.Text); fGMail.CallbackURL:=efCallbackURL.Text; fGMail.OnSaveToken:=SaveCredentials; fGMail.OnLoadToken:=LoadCredentials; try fGMail.Authorize(procedure (const aToken: TOAuthToken) begin crcAuthorise.Fill.Color:=TAlphaColorRec.Green; end); except end; end; procedure TForm1.btnRefreshClick(Sender: TObject); begin crcRefresh.Fill.Color:=TAlphaColorRec.Red; fGMail.RefreshToken(procedure (const aToken: TOAuthToken) begin crcRefresh.Fill.Color:=TAlphaColorRec.Green; lbReloadedToken.Text:=fGMail.AccessToken; end); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin fGMail.Free; end; procedure TForm1.LoadCredentials(var aToken: TOAuthToken); begin if cbUseExisting.IsChecked then begin aToken.AccessToken:=lbAccessToken.Text; aToken.AccessTokenExpiration:=lbExpiration.Text.ToInteger; aToken.RefreshToken:=lbRefreshToken.Text; aToken.RetrieveDateTime:=fRetrieved; end else begin aToken.AccessToken:=''; aToken.AccessTokenExpiration:=0; aToken.RefreshToken:=''; aToken.RetrieveDateTime:=IncMinute(Now, -100); end; if cbMakeTokenExpire.IsChecked then aToken.RetrieveDateTime:=IncMinute(Now, -100); end; procedure TForm1.SaveCredentials(const aToken: TOAuthToken); begin lbAccessToken.Text:=aToken.AccessToken; lbExpiration.Text:=aToken.AccessTokenExpiration.ToString; lbRefreshToken.Text:=aToken.RefreshToken; fRetrieved:=aToken.RetrieveDateTime; end; end.
unit GX_eSort; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GX_BaseForm; type TeSortOrder = (esoAscending, esoDescending, esoReverse); type TfmeSortConfig = class(TfmBaseForm) btnAscending: TButton; btnDescending: TButton; btnReverse: TButton; btnCancel: TButton; chkIgnoreFunction: TCheckBox; private public class function Execute(out _SortOrder: TeSortOrder; out _Ignore: Boolean): Boolean; end; implementation {$R *.dfm} uses GX_EditorExpert, GX_eSelectionEditorExpert, StrUtils; { TfmeSortConfig } class function TfmeSortConfig.Execute(out _SortOrder: TeSortOrder; out _Ignore: Boolean): Boolean; var frm: TfmeSortConfig; begin frm := TfmeSortConfig.Create(nil); try Result := True; case frm.ShowModal of mrYes: _SortOrder := esoAscending; mrNo: _SortOrder := esoDescending; mrRetry: _SortOrder := esoReverse; else Result := False; _Ignore := frm.chkIgnoreFunction.Checked; end; finally FreeAndNil(frm); end; end; type TSortExpert = class(TSelectionEditorExpert) protected function ProcessSelected(Lines: TStrings): Boolean; override; public class function GetName: string; override; function GetDisplayName: string; override; function GetHelpString: string; override; function HasConfigOptions: boolean; override; end; { TSortExpert } function TSortExpert.GetDisplayName: string; resourcestring SSortName = 'Sort Selected Lines'; begin Result := SSortName; end; function TSortExpert.GetHelpString: string; resourcestring SSortHelp = ' This expert sorts the lines in a selected block of code. ' + 'To use it, select several lines in the IDE code editor and ' + 'activate this expert.'; begin Result := SSortHelp; end; class function TSortExpert.GetName: string; begin Result := 'SortLines'; end; function TSortExpert.HasConfigOptions: boolean; begin Result := False; end; function TSortExpert.ProcessSelected(Lines: TStrings): Boolean; function StripPrefix(const _Prefix: string; var _Line: string): boolean; begin Result := AnsiStartsText(_Prefix, _Line); if Result then _Line := Copy(_Line, Length(_Prefix), 255); end; var TrimList, SortedList: TStringList; i: Integer; SortOrder: TESortOrder; Direction: integer; IgnoreFunction: Boolean; s: string; begin Result := False; if Lines.Count > 1 then begin if not TfmeSortConfig.Execute(SortOrder, IgnoreFunction) then exit; // The trim mess here is so we can ignore whitespace when sorting SortedList := nil; TrimList := TStringList.Create; try SortedList := TStringList.Create; for i := 0 to Lines.Count - 1 do begin s := TrimLeft(Lines[i]); if IgnoreFunction then if not StripPrefix('procedure ', s) then StripPrefix('function ', s); TrimList.AddObject(s, TObject(i)); end; case SortOrder of esoAscending: begin i := 0; Direction := 1; TrimList.Sort; end; esoDescending: begin i := TrimList.Count - 1; Direction := -1; TrimList.Sort; end else // esoReverse: i := TrimList.Count - 1; Direction := -1; end; while (i >= 0) and (i < TrimList.Count) do begin SortedList.Add(Lines[Integer(TrimList.Objects[i])]); i := i + Direction; end; Lines.Clear; Lines.AddStrings(SortedList); finally FreeAndNil(SortedList); FreeAndNil(TrimList); end; Result := True; end; end; initialization RegisterEditorExpert(TSortExpert); end.
unit clRelatorioDiario; interface uses clConexao; type TRelatorioDiario = Class(TObject) private function getChegadaFranquia: TTime; function getData: TDate; function getDivergenciaPeso: Integer; function getExpedidores: Integer; function getMotorista: String; function getObservacoes: String; function getPlaca: String; function getrDivergenciaAvaria: Integer; function getRegistro: TDateTime; function getSaidaFranquia: TTime; function getSaidaOrigem: TTime; function getSequencia: Integer; function getUsuario: String; procedure setChegadaFranquia(const Value: TTime); procedure setData(const Value: TDate); procedure setDivergenciaAvaria(const Value: Integer); procedure setDivergenciaPeso(const Value: Integer); procedure setExpedidores(const Value: Integer); procedure setMotorista(const Value: String); procedure setObservacoes(const Value: String); procedure setPlaca(const Value: String); procedure setRegistro(const Value: TDateTime); procedure setSaidaFranquia(const Value: TTime); procedure setSaidaOrigem(const Value: TTime); procedure setSequencia(const Value: Integer); procedure setUsuario(const Value: String); procedure MaxSeq; function getOperacao: String; procedure setOperacao(const Value: String); constructor Create; destructor Destroy; protected _sequencia: Integer; _data: TDate; _placa: String; _motorista: String; _saidaorigem: TTime; _chegadafranquia: TTime; _saidafranquia: TTime; _expedidores: Integer; _divergenciapeso: Integer; _divergenciaavaria: Integer; _observacoes: String; _usuario: String; _registro: TDateTime; _operacao: String; _conexao: TConexao; public property Sequencia: Integer read getSequencia write setSequencia; property Data: TDate read getData write setData; property Placa: String read getPlaca write setPlaca; property Motorista: String read getMotorista write setMotorista; property SaidaOrigem: TTime read getSaidaOrigem write setSaidaOrigem; property ChegadaFranquia: TTime read getChegadaFranquia write setChegadaFranquia; property SaidaFranquia: TTime read getSaidaFranquia write setSaidaFranquia; property Expedidores: Integer read getExpedidores write setExpedidores; property DivergenciaPeso: Integer read getDivergenciaPeso write setDivergenciaPeso; property DivergenciaAvaria: Integer read getrDivergenciaAvaria write setDivergenciaAvaria; property Observacoes: String read getObservacoes write setObservacoes; property Usuario: String read getUsuario write setUsuario; property Registro: TDateTime read getRegistro write setRegistro; property Operacao: String read getOperacao write setOperacao; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; function Insert(): Boolean; function Update(): Boolean; End; const TABLENAME = 'TBRELATORIODIARIO'; implementation { TRelatorioDiario } uses SysUtils, Dialogs, udm, clUtil, DB, Math, DateUtils; constructor TRelatorioDiario.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TRelatorioDiario.Destroy; begin _conexao.Free; end; function TRelatorioDiario.getChegadaFranquia: TTime; begin Result := _chegadafranquia; end; function TRelatorioDiario.getData: TDate; begin Result := _data; end; function TRelatorioDiario.getDivergenciaPeso: Integer; begin Result := _divergenciapeso; end; function TRelatorioDiario.getExpedidores: Integer; begin Result := _expedidores; end; function TRelatorioDiario.getMotorista: String; begin Result := _motorista; end; function TRelatorioDiario.getObservacoes: String; begin Result := _observacoes; end; function TRelatorioDiario.getOperacao: String; begin Result := _operacao; end; function TRelatorioDiario.getPlaca: String; begin Result := _placa; end; function TRelatorioDiario.getrDivergenciaAvaria: Integer; begin Result := _divergenciaavaria; end; function TRelatorioDiario.getRegistro: TDateTime; begin Result := _registro end; function TRelatorioDiario.getSaidaFranquia: TTime; begin Result := _saidafranquia; end; function TRelatorioDiario.getSaidaOrigem: TTime; begin Result := _saidaorigem; end; function TRelatorioDiario.getSequencia: Integer; begin Result := _sequencia; end; function TRelatorioDiario.getUsuario: String; begin Result := _usuario; end; function TRelatorioDiario.Validar(): Boolean; begin Result := False; if TUTil.Empty(DateToStr(Self.Data)) then begin MessageDlg('Informe a Data da Ocorrência!', mtWarning, [mbOK], 0); Exit; end; if TUTil.Empty(Self.Placa) then begin MessageDlg('Informe a Placa do Veículo!', mtWarning, [mbOK], 0); Exit; end; if TUTil.Empty(Self.Operacao) then begin MessageDlg('Informe o Tipo de Operação!', mtWarning, [mbOK], 0); Exit; end; if Length(Trim(Self.Placa)) <> 7 then begin MessageDlg('Placa do Veículo informada é inválida!', mtWarning, [mbOK], 0); Exit; end; if TUTil.Empty(Self.Motorista) then begin MessageDlg('Informe o Nome do Motorista!', mtWarning, [mbOK], 0); Exit; end; { if Self.Expedidores = 0 then begin MessageDlg('Informe a Quantidade de Expedidores!', mtWarning, [mbOK], 0); Exit; end; } Result := True; end; function TRelatorioDiario.Delete(filtro: string): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'SEQUENCIA' then begin SQL.Add('WHERE SEQ_RELATORIO = :SEQUENCIA'); ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; end; if filtro = 'DATA' then begin SQL.Add('WHERE DAT_RELATORIO = :DATA'); ParamByName('DATA').AsDate := Self.Data; end; if filtro = 'PLACA' then begin SQL.Add('WHERE DES_PLACA = :PLACA'); ParamByName('PLACA').AsString := Self.Placa; end; if filtro = 'MOTORISTA' then begin SQL.Add('WHERE NOM_MOTORISTA = :MOTORISTA'); ParamByName('MOTORISTA').AsString := Self.Motorista; end; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TRelatorioDiario.getObject(id: string; filtro: string): Boolean; begin try Result := False; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'SEQUENCIA' then begin SQL.Add('WHERE SEQ_RELATORIO = :SEQUENCIA'); ParamByName('SEQUENCIA').AsInteger := StrToInt(id); end; if filtro = 'DATA' then begin SQL.Add('WHERE DAT_RELATORIO = :DATA'); ParamByName('DATA').AsDate := StrToDate(id); end; if filtro = 'PLACA' then begin SQL.Add('WHERE DES_PLACA = :PLACA'); ParamByName('PLACA').AsString := id; end; if filtro = 'MOTORISTA' then begin SQL.Add('WHERE NOM_MOTORISTA = :MOTORISTA'); ParamByName('MOTORISTA').AsString := id; end; if filtro = 'CHAVE' then begin SQL.Add('WHERE DAT_RELATORIO = :DATA AND DES_OPERACAO = :OPERACAO AND DES_PLACA = :PLACA AND NOM_MOTORISTA = :MOTORISTA ' + 'AND HOR_SAIDA_FRANQUIA = :SAIDA'); ParamByName('DATA').AsDate := Self.Data; ParamByName('OPERACAO').AsString := Self.Operacao; ParamByName('PLACA').AsString := Self.Placa; ParamByName('MOTORISTA').AsString := Self.Motorista; ParamByName('SAIDA').asTime := Self.SaidaFranquia; end; dm.ZConn.PingServer; Open; if not(IsEmpty) then begin First; Self.Sequencia := FieldByName('SEQ_RELATORIO').AsInteger; Self.Data := FieldByName('DAT_RELATORIO').AsDateTime; Self.Placa := FieldByName('DES_PLACA').AsString; Self.Motorista := FieldByName('NOM_MOTORISTA').AsString; Self.SaidaOrigem := FieldByName('HOR_SAIDA_ORIGEM').AsDateTime; Self.ChegadaFranquia := FieldByName('HOR_CHEGADA_FRANQUIA').AsDateTime; Self.SaidaFranquia := FieldByName('HOR_SAIDA_FRANQUIA').AsDateTime; Self.Expedidores := FieldByName('QTD_EXPEDIDORES').AsInteger; Self.DivergenciaPeso := FieldByName('QTD_PESO_DIVERGENCIA').AsInteger; Self.DivergenciaAvaria := FieldByName('QTD_AVARIAS_DIVERGENCIA') .AsInteger; Self.Observacoes := FieldByName('DES_OBSERVACOES').AsString; Self.Usuario := FieldByName('NOM_USUARIO').AsString; Self.Registro := FieldByName('DAT_REGISTRO').AsDateTime; Self.Operacao := FieldByName('DES_OPERACAO').AsString; if RecordCount = 1 then begin Close; SQL.Clear; end; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TRelatorioDiario.getObjects(): Boolean; begin try Result := False; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if IsEmpty then begin MessageDlg('Nenhum registro encontrado!', mtWarning, [mbOK], 0); Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TRelatorioDiario.getField(campo: string; coluna: string): String; begin try Result := ''; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT ' + campo + ' FROM ' + TABLENAME); if coluna = 'SEQUENCIA' then begin SQL.Add('WHERE SEQ_RELATORIO = :SEQUENCIA'); ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; end; if coluna = 'PLACA' then begin SQL.Add('WHERE DES_PLACA = :PLACA'); ParamByName('PLACA').AsString := Self.Placa; end; dm.ZConn.PingServer; Open; if IsEmpty then begin MessageDlg('Nenhum registro encontrado!', mtWarning, [mbOK], 0); end else begin Result := FieldByName(campo).AsString; end; Close; SQL.Clear; end; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; procedure TRelatorioDiario.MaxSeq; begin try with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT MAX(SEQ_RELATORIO) AS NUMERO FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not(IsEmpty) then begin Self.Sequencia := FieldByName('NUMERO').AsInteger + 1; end else begin Self.Sequencia := 1; end; Close; SQL.Clear; end; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TRelatorioDiario.Insert(): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(SEQ_RELATORIO, ' + 'DAT_RELATORIO, ' + 'DES_PLACA, ' + 'NOM_MOTORISTA, ' + 'HOR_SAIDA_ORIGEM, ' + 'HOR_CHEGADA_FRANQUIA, ' + 'HOR_SAIDA_FRANQUIA, ' + 'QTD_EXPEDIDORES, ' + 'QTD_PESO_DIVERGENCIA, ' + 'QTD_AVARIAS_DIVERGENCIA, ' + 'DES_OBSERVACOES, ' + 'NOM_USUARIO, ' + 'DAT_REGISTRO, ' + 'DES_OPERACAO) ' + 'VALUES (' + ':SEQUENCIA, ' + ':DATA, ' + ':PLACA, ' + ':MOTORISTA, ' + ':SAIDAORIGEM, ' + ':CHEGADAFRANQUIA, ' + ':SAIDAFRANQUIA, ' + ':EXPEDIDORES, ' + ':PESODIVERGENCIA, ' + ':AVARIASDIVERGENCIA, ' + ':OBSERVACOES, ' + ':USUARIO, ' + ':REGISTRO, ' + ':OPERACAO)'; MaxSeq; ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; ParamByName('DATA').AsDate := Self.Data; ParamByName('PLACA').AsString := Self.Placa; ParamByName('MOTORISTA').AsString := Self.Motorista; ParamByName('SAIDAORIGEM').asTime := Self.SaidaOrigem; ParamByName('CHEGADAFRANQUIA').asTime := Self.ChegadaFranquia; ParamByName('SAIDAFRANQUIA').asTime := Self.SaidaFranquia; ParamByName('EXPEDIDORES').AsInteger := Self.Expedidores; ParamByName('PESODIVERGENCIA').AsInteger := Self.DivergenciaPeso; ParamByName('AVARIASDIVERGENCIA').AsInteger := Self.DivergenciaAvaria; ParamByName('OBSERVACOES').AsString := Self.Observacoes; ParamByName('USUARIO').AsString := Self.Usuario; ParamByName('REGISTRO').AsDateTime := Self.Registro; ParamByName('OPERACAO').AsString := Self.Operacao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TRelatorioDiario.Update(): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_RELATORIO = :DATA, ' + 'DES_PLACA = :PLACA, ' + 'NOM_MOTORISTA = :MOTORISTA, ' + 'HOR_SAIDA_ORIGEM = :SAIDAORIGEM, ' + 'HOR_CHEGADA_FRANQUIA = :CHEGADAFRANQUIA, ' + 'HOR_SAIDA_FRANQUIA = :SAIDAFRANQUIA, ' + 'QTD_EXPEDIDORES = :EXPEDIDORES, ' + 'QTD_PESO_DIVERGENCIA = :PESODIVERGENCIA, ' + 'QTD_AVARIAS_DIVERGENCIA = :AVARIASDIVERGENCIA, ' + 'DES_OBSERVACOES = :OBSERVACOES, ' + 'NOM_USUARIO = :USUARIO, ' + 'DAT_REGISTRO = :REGISTRO, ' + 'DES_OPERACAO = :OPERACAO ' + 'WHERE ' + 'SEQ_RELATORIO = :SEQUENCIA'; ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; ParamByName('DATA').AsDate := Self.Data; ParamByName('PLACA').AsString := Self.Placa; ParamByName('MOTORISTA').AsString := Self.Motorista; ParamByName('SAIDAORIGEM').asTime := Self.SaidaOrigem; ParamByName('CHEGADAFRANQUIA').asTime := Self.ChegadaFranquia; ParamByName('SAIDAFRANQUIA').asTime := Self.SaidaFranquia; ParamByName('EXPEDIDORES').AsInteger := Self.Expedidores; ParamByName('PESODIVERGENCIA').AsInteger := Self.DivergenciaPeso; ParamByName('AVARIASDIVERGENCIA').AsInteger := Self.DivergenciaAvaria; ParamByName('OBSERVACOES').AsString := Self.Observacoes; ParamByName('USUARIO').AsString := Self.Usuario; ParamByName('REGISTRO').AsDateTime := Self.Registro; ParamByName('OPERACAO').AsString := Self.Operacao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; procedure TRelatorioDiario.setChegadaFranquia(const Value: TTime); begin _chegadafranquia := Value; end; procedure TRelatorioDiario.setData(const Value: TDate); begin _data := Value; end; procedure TRelatorioDiario.setDivergenciaAvaria(const Value: Integer); begin _divergenciaavaria := Value; end; procedure TRelatorioDiario.setDivergenciaPeso(const Value: Integer); begin _divergenciapeso := Value; end; procedure TRelatorioDiario.setExpedidores(const Value: Integer); begin _expedidores := Value; end; procedure TRelatorioDiario.setMotorista(const Value: String); begin _motorista := Value; end; procedure TRelatorioDiario.setObservacoes(const Value: String); begin _observacoes := Value; end; procedure TRelatorioDiario.setOperacao(const Value: String); begin _operacao := Value; end; procedure TRelatorioDiario.setPlaca(const Value: String); begin _placa := Value; end; procedure TRelatorioDiario.setRegistro(const Value: TDateTime); begin _registro := Value; end; procedure TRelatorioDiario.setSaidaFranquia(const Value: TTime); begin _saidafranquia := Value; end; procedure TRelatorioDiario.setSaidaOrigem(const Value: TTime); begin _saidaorigem := Value; end; procedure TRelatorioDiario.setSequencia(const Value: Integer); begin _sequencia := Value; end; procedure TRelatorioDiario.setUsuario(const Value: String); begin _usuario := Value; end; end.
unit QuickList_DealItem; interface uses QuickSortList, define_dealitem; type PDealItemListItem = ^TDealItemListItem; TDealItemListItem = record StockPackCode: integer; DealItem: PRT_DealItem; end; TDealItemList = class(TALBaseQuickSortList) public function GetItem(Index: Integer): Integer; procedure SetItem(Index: Integer; const AStockPackCode: Integer); function GetDealItem(Index: Integer): PRT_DealItem; procedure PutDealItem(Index: Integer; ADealItem: PRT_DealItem); public procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure InsertItem(Index: Integer; const AStockPackCode: integer; ADealItem: PRT_DealItem); function CompareItems(const Index1, Index2: Integer): Integer; override; public function IndexOf(AStockPackCode: Integer): Integer; function IndexOfDealItem(ADealItem: PRT_DealItem): Integer; Function AddDealItem(const AStockPackCode: integer; ADealItem: PRT_DealItem): Integer; function Find(AStockPackCode: Integer; var Index: Integer): Boolean; procedure InsertObject(Index: Integer; const AStockPackCode: integer; ADealItem: PRT_DealItem); //property Items[Index: Integer]: Integer read GetItem write SetItem; default; property StockPackCode[Index: Integer]: Integer read GetItem write SetItem; default; property DealItem[Index: Integer]: PRT_DealItem read GetDealItem write PutDealItem; end; implementation function TDealItemList.AddDealItem(const AStockPackCode: integer; ADealItem: PRT_DealItem): Integer; begin if not Sorted then begin Result := FCount end else if Find(AStockPackCode, Result) then begin case Duplicates of lstDupIgnore: Exit; lstDupError: Error(@SALDuplicateItem, 0); end; end; InsertItem(Result, AStockPackCode, ADealItem); end; {*****************************************************************************************} procedure TDealItemList.InsertItem(Index: Integer; const AStockPackCode: integer; ADealItem: PRT_DealItem); var tmpDealItemListItem: PDealItemListItem; begin New(tmpDealItemListItem); tmpDealItemListItem^.StockPackCode := AStockPackCode; tmpDealItemListItem^.DealItem := ADealItem; try inherited InsertItem(index, tmpDealItemListItem); except Dispose(tmpDealItemListItem); raise; end; end; {***************************************************************************} function TDealItemList.CompareItems(const Index1, Index2: integer): Integer; begin result := PDealItemListItem(Get(Index1))^.StockPackCode - PDealItemListItem(Get(Index2))^.StockPackCode; end; {***********************************************************************} function TDealItemList.Find(AStockPackCode: Integer; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; C := GetItem(I) - AStockPackCode; if C < 0 then begin L := I + 1 end else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> lstDupAccept then L := I; end; end; end; Index := L; end; {*******************************************************} function TDealItemList.GetItem(Index: Integer): Integer; begin Result := PDealItemListItem(Get(index))^.StockPackCode end; {******************************************************} function TDealItemList.IndexOf(AStockPackCode: Integer): Integer; begin if not Sorted then Begin Result := 0; while (Result < FCount) and (GetItem(result) <> AStockPackCode) do Inc(Result); if Result = FCount then Result := -1; end else if not Find(AStockPackCode, Result) then Result := -1; end; {*******************************************************************************************} procedure TDealItemList.InsertObject(Index: Integer; const AStockPackCode: integer; ADealItem: PRT_DealItem); var tmpDealItemListItem: PDealItemListItem; begin New(tmpDealItemListItem); tmpDealItemListItem^.StockPackCode := AStockPackCode; tmpDealItemListItem^.DealItem := ADealItem; try inherited insert(index, tmpDealItemListItem); except Dispose(tmpDealItemListItem); raise; end; end; {***********************************************************************} procedure TDealItemList.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lstDeleted then dispose(ptr); inherited Notify(Ptr, Action); end; {********************************************************************} procedure TDealItemList.SetItem(Index: Integer; const AStockPackCode: Integer); Var aPDealItemListItem: PDealItemListItem; begin New(aPDealItemListItem); aPDealItemListItem^.StockPackCode := AStockPackCode; aPDealItemListItem^.DealItem := nil; Try Put(Index, aPDealItemListItem); except Dispose(aPDealItemListItem); raise; end; end; {*********************************************************} function TDealItemList.GetDealItem(Index: Integer): PRT_DealItem; begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); Result := PDealItemListItem(Get(index))^.DealItem; end; {***************************************************************} function TDealItemList.IndexOfDealItem(ADealItem: PRT_DealItem): Integer; begin for Result := 0 to Count - 1 do begin if GetDealItem(Result) = ADealItem then begin Exit; end; end; Result := -1; end; {*******************************************************************} procedure TDealItemList.PutDealItem(Index: Integer; ADealItem: PRT_DealItem); begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); PDealItemListItem(Get(index))^.DealItem := ADealItem; end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower 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 ***** *) {NOTE: THIS UNIT IS NOT TO BE DISTRIBUTED} unit STCOMLic; interface uses StDate, StRegEx, StMime, StExpr, StFin; function COMIsValidKey(const S : string) : boolean; {-called by the COM object License method} function COMHasBeenLicensed : boolean; {-called by each routine prior to processing} implementation {Note: the routines in this unit are designed to trash various typed constants, unless a valid key is entered. If the constants are trashed, various SysTools routines will not work properly and produce bogus results. There are five units: StDate, StRegEx, StMime, StExpr, StFin. In StDate, five longints are trashed that hold some constant values used in date calculations. In StRegEx the word delimiter characters are trashed. In StMime the standard MIME string constants are trashed. In StExpr the operators characters are trashed. In StFin the delta, epsilon and max iteration values are trashed, meaning that iterative routines may not end. Systools COM keys have the following format: STD999999XXXXXXXX where 999999 is the serial number and XXXXXXXX is the hex string linked to that serial number. The validation works like this: calculate the hash of the Systools serial number starting with zero divide hash by 32 and take the modulus base 10 calculate that many random numbers use the final random number as the initial value to calculate the hash of the hex string the answer should be $5764 Instead of checking against $5764 we use the hash value to untrash the signatures. Of course if the hash value is bogus the signatures won't be valid and Systools won't work.} uses Windows; const MagicSeed = $6457; type PLongint = ^longint; PLongintArray = ^TLongintArray; TLongintArray = array [1..5] of longint; PWordArray = ^TWordArray; TWordArray = array [0..25] of word; var RandSeed : PLongint; KeyString : string; KeyHash : longint; StDateSig : PWordArray; StRegExSig : PWordArray; StMimeSig : PWordArray; StExprSig : PWordArray; StFinSig : PWordArray; procedure Reference(var Dummy); {new !!.01} begin {a do-nothing routine that forces a variable to be linked in} end; function RandomNumber : integer; begin {simple linear congruential random number generator} Result := ((RandSeed^ * 4561) + 51349) mod 243000; RandSeed^ := Result; end; function HashBKDR(const S : string; Lower, Upper : integer; StartValue : longint) : longint; var i : integer; begin {slightly modified Kernighan and Ritchie hash} Result := StartValue; for i := Lower to Upper do begin Result := (Result * 31) + ord(S[i]); end; end; function COMIsValidKey(const S : string) : boolean; function Min(a, b : integer) : integer; begin if a < b then Result := a else Result := b; end; var SN1, SN2 : integer; HS1, HS2 : integer; i : integer; TempResult: integer; SNHash : longint; NextHash : longint; StartHash : longint; TempSeed : longint; begin {Note: ignore all the code that manipulates TempResult--it's designed so that the routine always returns true, and confuses a potential hacker} {calculate the serial number and hex digit ranges} SN1 := Min(4, length(S)); HS1 := Min(10, length(S)); SN2 := pred(HS1); HS2 := length(S); Reference(Date1970); {!!.01} {calculate the serial number hash: this will give us an index between 0 and 9} SNHash := HashBKDR(S, SN1, SN2, 0); SNHash := (SNHash shr 5) mod 10; {always return true} TempResult := (SN2 - SN1 + 1); {6} Reference(Date1980); {!!.01} {calculate the start value for the hex string hash} KeyString := S; RandSeed^ := MagicSeed; {trash start of StDate} StartHash := RandomNumber; for i := 0 to 33 do begin TempSeed := RandSeed^; case i of 1 : RandSeed := PLongint(StRegExSig); 14 : RandSeed := PLongint(StMimeSig); 26 : RandSeed := PLongint(StExprSig); 28 : RandSeed := PLongint(StFinSig); else inc(RandSeed, 1); end; RandSeed^ := TempSeed; NextHash := RandomNumber; if (i = SNHash) then StartHash := NextHash; end; {always return true} if Odd(TempResult) then {false} TempResult := TempResult + 1 else TempResult := TempResult div 2; {3} Reference(Date2000); {!!.01} {calculate the hash for the hex string--the lower word should be MagicHash ($5746)} KeyHash := HashBKDR(S, HS1, HS2, StartHash); {always return true} Result := TempResult = 3; Reference(Days400Yr); {!!.01} end; function COMHasBeenLicensed : boolean; const StDateMagicNumbers : array [0..3] of word = ($FB43, $5747, $6DF7, $5744); StRegexMagicNumbers : array [0..25] of word = ($5E5B, $7666, $7164, $7E6E, $7C6C, $7A6A, $7868, $6C7C, $6A7A, $6878, $0C06, $0A1A, $3718, $2B3D, $293B, $5746, $6756, $6577, $6375, $6173, $6F71, $167F, $1404, $1202, $5700, $5746); StMimeMagicNumbers : array [0..23] of word = ($364C, $2332, $3427, $3A2E, $3923, $5732, $365E, $2736, $3E2A, $3625, $3E32, $3929, $3869, $2325, $2323, $246B, $2532, $3623, $572B, $5746, $3540, $2427, $6123, $5772); StExprMagicNumbers : array [0..3] of word = ($7E6E, $7C6A, $7D6B, $6A69); StFinMagicNumbers : array [0..11] of word = ($D365, $4C01, $FB01, $F083, $68A8, $97CD, $D365, $4C01, $FB01, $F083, $68A8, $97CD); var i : integer; begin {always returns true} Result := not Odd(longint(KeyString)); Reference(StHexDigitString); {!!.01} {repatch the signatures - won't provide good results unless the key hashed correctly (ie was valid). Ignore all the messing around with KeyHash, it's to put people off on the wrong scent <g>} {StDate} KeyHash := KeyHash or $43210000; for i := 0 to 3 do StDateSig^[i] := StDateMagicNumbers[i] xor KeyHash; {StRegex} KeyHash := KeyHash or $54320000; for i := 0 to 25 do StRegexSig^[i] := StRegexMagicNumbers[i] xor KeyHash; Reference(DefStContentType); {!!.01} {StMime} KeyHash := KeyHash or $65430000; for i := 0 to 23 do StMimeSig^[i] := StMimeMagicNumbers[i] xor KeyHash; {StExpr} KeyHash := KeyHash or $76540000; for i := 0 to 3 do StExprSig^[i] := StExprMagicNumbers[i] xor KeyHash; Reference(DefStMimeEncoding); {!!.01} {StExpr} KeyHash := KeyHash or longint($87650000); for i := 0 to 11 do StFinSig^[i] := StFinMagicNumbers[i] xor KeyHash; end; procedure InitUnit; begin {get ready to trash a few signatures} StDateSig := @Date1900; StRegExSig := @StWordDelimString; StMimeSig := @DefStContentDisposition; StExprSig := @StExprOperators; StFinSig := @StDelta; {trash a bit o' regex} StRegExSig^[11] := GetTickCount; Reference(StEpsilon); {!!.01} Reference(StMaxIterations); {!!.01} {make RandSeed point to the second 4 bytes of the StDate section} RandSeed := PLongint(StDateSig); end; initialization InitUnit; end.
unit UAccountComp; interface uses UAccountKey, UAccountInfo, Classes, URawBytes, UCrypto, UAccount, UOperationBlock, UBlockAccount, UECPrivateKey; type { TAccountComp } TAccountComp = Class private public Class Function IsValidAccountKey(const account: TAccountKey; var errors : AnsiString): Boolean; Class Function IsValidAccountInfo(const accountInfo: TAccountInfo; var errors : AnsiString): Boolean; Class Function IsAccountForSale(const accountInfo: TAccountInfo) : Boolean; Class Function IsAccountForSaleAcceptingTransactions(const accountInfo: TAccountInfo) : Boolean; Class Function GetECInfoTxt(Const EC_OpenSSL_NID: Word) : AnsiString; Class Procedure ValidsEC_OpenSSL_NID(list : TList); Class Function AccountKey2RawString(const account: TAccountKey): TRawBytes; overload; Class procedure AccountKey2RawString(const account: TAccountKey; var dest: TRawBytes); overload; Class Function RawString2Accountkey(const rawaccstr: TRawBytes): TAccountKey; overload; Class procedure RawString2Accountkey(const rawaccstr: TRawBytes; var dest: TAccountKey); overload; Class Function PrivateToAccountkey(key: TECPrivateKey): TAccountKey; Class Function IsAccountBlockedByProtocol(account_number, blocks_count : Cardinal) : Boolean; Class Function EqualAccountInfos(const accountInfo1,accountInfo2 : TAccountInfo) : Boolean; Class Function EqualAccountKeys(const account1,account2 : TAccountKey) : Boolean; Class Function EqualAccounts(const account1,account2 : TAccount) : Boolean; Class Function EqualOperationBlocks(const opBlock1,opBlock2 : TOperationBlock) : Boolean; Class Function EqualBlockAccounts(const blockAccount1,blockAccount2 : TBlockAccount) : Boolean; Class Function AccountNumberToAccountTxtNumber(account_number : Cardinal) : AnsiString; Class function AccountTxtNumberToAccountNumber(Const account_txt_number : AnsiString; var account_number : Cardinal) : Boolean; Class function FormatMoney(Money : Int64) : AnsiString; Class function FormatMoneyDecimal(Money : Int64) : Single; Class Function TxtToMoney(Const moneytxt : AnsiString; var money : Int64) : Boolean; Class Function AccountKeyFromImport(Const HumanReadable : AnsiString; var account : TAccountKey; var errors : AnsiString) : Boolean; Class Function AccountPublicKeyExport(Const account : TAccountKey) : AnsiString; Class Function AccountPublicKeyImport(Const HumanReadable : AnsiString; var account : TAccountKey; var errors : AnsiString) : Boolean; Class Function AccountBlock(Const account_number : Cardinal) : Cardinal; Class Function AccountInfo2RawString(const AccountInfo : TAccountInfo) : TRawBytes; overload; Class procedure AccountInfo2RawString(const AccountInfo : TAccountInfo; var dest : TRawBytes); overload; Class procedure SaveAccountToAStream(Stream: TStream; const Account : TAccount); Class Function RawString2AccountInfo(const rawaccstr: TRawBytes): TAccountInfo; overload; Class procedure RawString2AccountInfo(const rawaccstr: TRawBytes; var dest : TAccountInfo); overload; Class Function IsAccountLocked(const AccountInfo : TAccountInfo; blocks_count : Cardinal) : Boolean; Class procedure SaveTOperationBlockToStream(const stream : TStream; const operationBlock:TOperationBlock); Class Function LoadTOperationBlockFromStream(const stream : TStream; var operationBlock:TOperationBlock) : Boolean; Class Function AccountToTxt(const Account : TAccount) : AnsiString; End; implementation uses UConst, UAccountState, UStreamOp, SysUtils, UBaseType, Math, UOpenSSL, UBigNum, UECDSA_Public; { TAccountComp } Const CT_Base58 : AnsiString = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; class function TAccountComp.AccountBlock(const account_number: Cardinal): Cardinal; begin Result := account_number DIV CT_AccountsPerBlock; end; class function TAccountComp.AccountInfo2RawString(const AccountInfo: TAccountInfo): TRawBytes; begin AccountInfo2RawString(AccountInfo,Result); end; class procedure TAccountComp.AccountInfo2RawString(const AccountInfo: TAccountInfo; var dest: TRawBytes); Var ms : TMemoryStream; w : Word; begin case AccountInfo.state of as_Normal: AccountKey2RawString(AccountInfo.accountKey,dest); as_ForSale: begin ms := TMemoryStream.Create; Try w := CT_AccountInfo_ForSale; ms.Write(w,SizeOf(w)); // TStreamOp.WriteAccountKey(ms,AccountInfo.accountKey); ms.Write(AccountInfo.locked_until_block,SizeOf(AccountInfo.locked_until_block)); ms.Write(AccountInfo.price,SizeOf(AccountInfo.price)); ms.Write(AccountInfo.account_to_pay,SizeOf(AccountInfo.account_to_pay)); TStreamOp.WriteAccountKey(ms,AccountInfo.new_publicKey); SetLength(dest,ms.Size); ms.Position := 0; ms.Read(dest[1],ms.Size); Finally ms.Free; end; end; else raise Exception.Create('DEVELOP ERROR 20170214-1'); end; end; class procedure TAccountComp.SaveAccountToAStream(Stream: TStream; const Account: TAccount); begin Stream.Write(Account.account,Sizeof(Account.account)); TStreamOp.WriteAnsiString(Stream,AccountInfo2RawString(Account.accountInfo)); Stream.Write(Account.balance,Sizeof(Account.balance)); Stream.Write(Account.updated_block,Sizeof(Account.updated_block)); Stream.Write(Account.n_operation,Sizeof(Account.n_operation)); TStreamOp.WriteAnsiString(Stream,Account.name); Stream.Write(Account.account_type,SizeOf(Account.account_type)); end; class function TAccountComp.AccountKey2RawString(const account: TAccountKey): TRawBytes; begin AccountKey2RawString(account,Result); end; class procedure TAccountComp.AccountKey2RawString(const account: TAccountKey; var dest: TRawBytes); Var s : TMemoryStream; begin s := TMemoryStream.Create; try TStreamOp.WriteAccountKey(s,account); SetLength(dest,s.Size); s.Position := 0; s.Read(dest[1],s.Size); finally s.Free; end; end; class function TAccountComp.AccountKeyFromImport(const HumanReadable: AnsiString; var account: TAccountKey; var errors : AnsiString): Boolean; Var raw : TRawBytes; BN, BNAux, BNBase : TBigNum; i,j : Integer; s1,s2 : AnsiString; i64 : Int64; b : Byte; begin result := false; errors := 'Invalid length'; account := CT_TECDSA_Public_Nul; if length(HumanReadable)<20 then exit; BN := TBigNum.Create(0); BNAux := TBigNum.Create; BNBase := TBigNum.Create(1); try for i := length(HumanReadable) downto 1 do begin if (HumanReadable[i]<>' ') then begin j := pos(HumanReadable[i],CT_Base58); if j=0 then begin errors := 'Invalid char "'+HumanReadable[i]+'" at pos '+inttostr(i)+'/'+inttostr(length(HumanReadable)); exit; end; BNAux.Value := j-1; BNAux.Multiply(BNBase); BN.Add(BNAux); BNBase.Multiply(length(CT_Base58)); end; end; // Last 8 hexa chars are the checksum of others s1 := Copy(BN.HexaValue,3,length(BN.HexaValue)); s2 := copy(s1,length(s1)-7,8); s1 := copy(s1,1,length(s1)-8); raw := TCrypto.HexaToRaw(s1); s1 := TCrypto.ToHexaString( TCrypto.DoSha256(raw) ); if copy(s1,1,8)<>s2 then begin // Invalid checksum errors := 'Invalid checksum'; exit; end; try account := TAccountComp.RawString2Accountkey(raw); Result := true; errors := ''; except // Nothing to do... invalid errors := 'Error on conversion from Raw to Account key'; end; Finally BN.Free; BNBase.Free; BNAux.Free; end; end; class function TAccountComp.AccountNumberToAccountTxtNumber(account_number: Cardinal): AnsiString; Var an : int64; begin an := account_number; // Converting to int64 to prevent overflow when *101 an := ((an * 101) MOD 89)+10; Result := IntToStr(account_number)+'-'+Inttostr(an); end; class function TAccountComp.AccountPublicKeyExport(const account: TAccountKey): AnsiString; Var raw : TRawBytes; BN, BNMod, BNDiv : TBigNum; i : Integer; begin Result := ''; raw := AccountKey2RawString(account); BN := TBigNum.Create; BNMod := TBigNum.Create; BNDiv := TBigNum.Create(Length(CT_Base58)); try BN.HexaValue := '01'+TCrypto.ToHexaString( raw )+TCrypto.ToHexaString(Copy(TCrypto.DoSha256(raw),1,4)); while (Not BN.IsZero) do begin BN.Divide(BNDiv,BNMod); If (BNMod.Value>=0) And (BNMod.Value<length(CT_Base58)) then Result := CT_Base58[Byte(BNMod.Value)+1] + Result else raise Exception.Create('Error converting to Base 58'); end; finally BN.Free; BNMod.Free; BNDiv.Free; end; end; class function TAccountComp.AccountPublicKeyImport( const HumanReadable: AnsiString; var account: TAccountKey; var errors: AnsiString): Boolean; Var raw : TRawBytes; BN, BNAux, BNBase : TBigNum; i,j : Integer; s1,s2 : AnsiString; i64 : Int64; b : Byte; begin result := false; errors := 'Invalid length'; account := CT_TECDSA_Public_Nul; if length(HumanReadable)<20 then exit; BN := TBigNum.Create(0); BNAux := TBigNum.Create; BNBase := TBigNum.Create(1); try for i := length(HumanReadable) downto 1 do begin j := pos(HumanReadable[i],CT_Base58); if j=0 then begin errors := 'Invalid char "'+HumanReadable[i]+'" at pos '+inttostr(i)+'/'+inttostr(length(HumanReadable)); exit; end; BNAux.Value := j-1; BNAux.Multiply(BNBase); BN.Add(BNAux); BNBase.Multiply(length(CT_Base58)); end; // Last 8 hexa chars are the checksum of others s1 := Copy(BN.HexaValue,3,length(BN.HexaValue)); s2 := copy(s1,length(s1)-7,8); s1 := copy(s1,1,length(s1)-8); raw := TCrypto.HexaToRaw(s1); s1 := TCrypto.ToHexaString( TCrypto.DoSha256(raw) ); if copy(s1,1,8)<>s2 then begin // Invalid checksum errors := 'Invalid checksum'; exit; end; try account := TAccountComp.RawString2Accountkey(raw); Result := true; errors := ''; except // Nothing to do... invalid errors := 'Error on conversion from Raw to Account key'; end; Finally BN.Free; BNBase.Free; BNAux.Free; end; end; class function TAccountComp.AccountTxtNumberToAccountNumber(const account_txt_number: AnsiString; var account_number: Cardinal): Boolean; Var i : Integer; char1 : AnsiChar; char2 : AnsiChar; an,rn,anaux : Int64; begin Result := false; if length(trim(account_txt_number))=0 then exit; an := 0; i := 1; while (i<=length(account_txt_number)) do begin if account_txt_number[i] in ['0'..'9'] then begin an := (an * 10) + ord( account_txt_number[i] ) - ord('0'); end else begin break; end; inc(i); end; account_number := an; if (i>length(account_txt_number)) then begin result := true; exit; end; if (account_txt_number[i] in ['-','.',' ']) then inc(i); if length(account_txt_number)-1<>i then exit; rn := StrToIntDef(copy(account_txt_number,i,length(account_txt_number)),0); anaux := ((an * 101) MOD 89)+10; Result := rn = anaux; end; class function TAccountComp.EqualAccountInfos(const accountInfo1,accountInfo2 : TAccountInfo) : Boolean; begin Result := (accountInfo1.state = accountInfo2.state) And (EqualAccountKeys(accountInfo1.accountKey,accountInfo2.accountKey)) And (accountInfo1.locked_until_block = accountInfo2.locked_until_block) And (accountInfo1.price = accountInfo2.price) And (accountInfo1.account_to_pay = accountInfo2.account_to_pay) and (EqualAccountKeys(accountInfo1.new_publicKey,accountInfo2.new_publicKey)); end; class function TAccountComp.EqualAccountKeys(const account1, account2: TAccountKey): Boolean; begin Result := (account1.EC_OpenSSL_NID=account2.EC_OpenSSL_NID) And (account1.x=account2.x) And (account1.y=account2.y); end; class function TAccountComp.EqualAccounts(const account1, account2: TAccount): Boolean; begin Result := (account1.account = account2.account) And (EqualAccountInfos(account1.accountInfo,account2.accountInfo)) And (account1.balance = account2.balance) And (account1.updated_block = account2.updated_block) And (account1.n_operation = account2.n_operation) And (TBaseType.BinStrComp(account1.name,account2.name)=0) And (account1.account_type = account2.account_type) And (account1.previous_updated_block = account2.previous_updated_block); end; class function TAccountComp.EqualOperationBlocks(const opBlock1, opBlock2: TOperationBlock): Boolean; begin Result := (opBlock1.block = opBlock1.block) And (EqualAccountKeys(opBlock1.account_key,opBlock2.account_key)) And (opBlock1.reward = opBlock2.reward) And (opBlock1.fee = opBlock2.fee) And (opBlock1.protocol_version = opBlock2.protocol_version) And (opBlock1.protocol_available = opBlock2.protocol_available) And (opBlock1.timestamp = opBlock2.timestamp) And (opBlock1.compact_target = opBlock2.compact_target) And (opBlock1.nonce = opBlock2.nonce) And (TBaseType.BinStrComp(opBlock1.block_payload,opBlock2.block_payload)=0) And (TBaseType.BinStrComp(opBlock1.initial_safe_box_hash,opBlock2.initial_safe_box_hash)=0) And (TBaseType.BinStrComp(opBlock1.operations_hash,opBlock2.operations_hash)=0) And (TBaseType.BinStrComp(opBlock1.proof_of_work,opBlock2.proof_of_work)=0); end; class function TAccountComp.EqualBlockAccounts(const blockAccount1, blockAccount2: TBlockAccount): Boolean; Var i : Integer; begin Result := (EqualOperationBlocks(blockAccount1.blockchainInfo,blockAccount2.blockchainInfo)) And (TBaseType.BinStrComp(blockAccount1.block_hash,blockAccount2.block_hash)=0) And (blockAccount1.accumulatedWork = blockAccount2.accumulatedWork); If Result then begin for i:=Low(blockAccount1.accounts) to High(blockAccount1.accounts) do begin Result := EqualAccounts(blockAccount1.accounts[i],blockAccount2.accounts[i]); If Not Result then Exit; end; end; end; class function TAccountComp.FormatMoney(Money: Int64): AnsiString; begin Result := FormatFloat('#,###0.0000',(Money/10000)); end; class function TAccountComp.FormatMoneyDecimal(Money : Int64) : Single; begin Result := RoundTo( Money / 10000.0, -4); end; class function TAccountComp.GetECInfoTxt(const EC_OpenSSL_NID: Word): AnsiString; begin case EC_OpenSSL_NID of CT_NID_secp256k1 : begin Result := 'secp256k1'; end; CT_NID_secp384r1 : begin Result := 'secp384r1'; end; CT_NID_sect283k1 : Begin Result := 'secp283k1'; End; CT_NID_secp521r1 : begin Result := 'secp521r1'; end else Result := '(Unknown ID:'+inttostr(EC_OpenSSL_NID)+')'; end; end; class function TAccountComp.IsAccountBlockedByProtocol(account_number, blocks_count: Cardinal): Boolean; begin if blocks_count<CT_WaitNewBlocksBeforeTransaction then result := true else begin Result := ((blocks_count-CT_WaitNewBlocksBeforeTransaction) * CT_AccountsPerBlock) <= account_number; end; end; class function TAccountComp.IsAccountForSale(const accountInfo: TAccountInfo): Boolean; begin Result := (AccountInfo.state=as_ForSale); end; class function TAccountComp.IsAccountForSaleAcceptingTransactions(const accountInfo: TAccountInfo): Boolean; var errors : AnsiString; begin Result := (AccountInfo.state=as_ForSale) And (IsValidAccountKey(AccountInfo.new_publicKey,errors)); end; class function TAccountComp.IsAccountLocked(const AccountInfo: TAccountInfo; blocks_count: Cardinal): Boolean; begin Result := (AccountInfo.state=as_ForSale) And ((AccountInfo.locked_until_block)>=blocks_count); end; class procedure TAccountComp.SaveTOperationBlockToStream(const stream: TStream; const operationBlock: TOperationBlock); begin stream.Write(operationBlock.block, Sizeof(operationBlock.block)); TStreamOp.WriteAccountKey(stream,operationBlock.account_key); stream.Write(operationBlock.reward, Sizeof(operationBlock.reward)); stream.Write(operationBlock.fee, Sizeof(operationBlock.fee)); stream.Write(operationBlock.protocol_version, Sizeof(operationBlock.protocol_version)); stream.Write(operationBlock.protocol_available, Sizeof(operationBlock.protocol_available)); stream.Write(operationBlock.timestamp, Sizeof(operationBlock.timestamp)); stream.Write(operationBlock.compact_target, Sizeof(operationBlock.compact_target)); stream.Write(operationBlock.nonce, Sizeof(operationBlock.nonce)); TStreamOp.WriteAnsiString(stream, operationBlock.block_payload); TStreamOp.WriteAnsiString(stream, operationBlock.initial_safe_box_hash); TStreamOp.WriteAnsiString(stream, operationBlock.operations_hash); TStreamOp.WriteAnsiString(stream, operationBlock.proof_of_work); end; class function TAccountComp.LoadTOperationBlockFromStream(const stream: TStream; var operationBlock: TOperationBlock): Boolean; begin Result := False; operationBlock := CT_OperationBlock_NUL; If stream.Read(operationBlock.block, Sizeof(operationBlock.block))<Sizeof(operationBlock.block) then Exit; TStreamOp.ReadAccountKey(stream,operationBlock.account_key); stream.Read(operationBlock.reward, Sizeof(operationBlock.reward)); stream.Read(operationBlock.fee, Sizeof(operationBlock.fee)); stream.Read(operationBlock.protocol_version, Sizeof(operationBlock.protocol_version)); stream.Read(operationBlock.protocol_available, Sizeof(operationBlock.protocol_available)); stream.Read(operationBlock.timestamp, Sizeof(operationBlock.timestamp)); stream.Read(operationBlock.compact_target, Sizeof(operationBlock.compact_target)); stream.Read(operationBlock.nonce, Sizeof(operationBlock.nonce)); if TStreamOp.ReadAnsiString(stream, operationBlock.block_payload) < 0 then Exit; if TStreamOp.ReadAnsiString(stream, operationBlock.initial_safe_box_hash) < 0 then Exit; if TStreamOp.ReadAnsiString(stream, operationBlock.operations_hash) < 0 then Exit; if TStreamOp.ReadAnsiString(stream, operationBlock.proof_of_work) < 0 then Exit; Result := True; end; class function TAccountComp.AccountToTxt(const Account: TAccount): AnsiString; begin Result := Format('%s Balance:%s N_Op:%d UpdB:%d Type:%d Name:%s PK:%s',[AccountNumberToAccountTxtNumber(Account.account), FormatMoney(Account.balance),Account.n_operation,Account.updated_block,Account.account_type, Account.name,TCrypto.ToHexaString(TAccountComp.AccountInfo2RawString(Account.accountInfo))]); end; class function TAccountComp.IsValidAccountInfo(const accountInfo: TAccountInfo; var errors: AnsiString): Boolean; Var s : AnsiString; begin errors := ''; case accountInfo.state of as_Unknown: begin errors := 'Account state is unknown'; Result := false; end; as_Normal: begin Result := IsValidAccountKey(accountInfo.accountKey,errors); end; as_ForSale: begin If Not IsValidAccountKey(accountInfo.accountKey,s) then errors := errors +' '+s; Result := errors=''; end; else raise Exception.Create('DEVELOP ERROR 20170214-3'); end; end; class function TAccountComp.IsValidAccountKey(const account: TAccountKey; var errors : AnsiString): Boolean; begin errors := ''; case account.EC_OpenSSL_NID of CT_NID_secp256k1,CT_NID_secp384r1,CT_NID_sect283k1,CT_NID_secp521r1 : begin Result := TECPrivateKey.IsValidPublicKey(account); if Not Result then begin errors := Format('Invalid AccountKey type:%d - Length x:%d y:%d Error:%s',[account.EC_OpenSSL_NID,length(account.x),length(account.y), ERR_error_string(ERR_get_error(),nil)]); end; end; else errors := Format('Invalid AccountKey type:%d (Unknown type) - Length x:%d y:%d',[account.EC_OpenSSL_NID,length(account.x),length(account.y)]); Result := False; end; if (errors='') And (Not Result) then errors := ERR_error_string(ERR_get_error(),nil); end; class function TAccountComp.PrivateToAccountkey(key: TECPrivateKey): TAccountKey; begin Result := key.PublicKey; end; class function TAccountComp.RawString2AccountInfo(const rawaccstr: TRawBytes): TAccountInfo; begin RawString2AccountInfo(rawaccstr,Result); end; class procedure TAccountComp.RawString2AccountInfo(const rawaccstr: TRawBytes; var dest: TAccountInfo); Var ms : TMemoryStream; w : Word; begin if length(rawaccstr)=0 then begin dest := CT_AccountInfo_NUL; exit; end; ms := TMemoryStream.Create; Try ms.WriteBuffer(rawaccstr[1],length(rawaccstr)); ms.Position := 0; If ms.Read(w,SizeOf(w))<>SizeOf(w) then exit; case w of CT_NID_secp256k1,CT_NID_secp384r1,CT_NID_sect283k1,CT_NID_secp521r1 : Begin dest.state := as_Normal; RawString2Accountkey(rawaccstr,dest.accountKey); dest.locked_until_block:=CT_AccountInfo_NUL.locked_until_block; dest.price:=CT_AccountInfo_NUL.price; dest.account_to_pay:=CT_AccountInfo_NUL.account_to_pay; dest.new_publicKey:=CT_AccountInfo_NUL.new_publicKey; End; CT_AccountInfo_ForSale : Begin TStreamOp.ReadAccountKey(ms,dest.accountKey); ms.Read(dest.locked_until_block,SizeOf(dest.locked_until_block)); ms.Read(dest.price,SizeOf(dest.price)); ms.Read(dest.account_to_pay,SizeOf(dest.account_to_pay)); TStreamOp.ReadAccountKey(ms,dest.new_publicKey); dest.state := as_ForSale; End; else raise Exception.Create('DEVELOP ERROR 20170214-2'); end; Finally ms.Free; end; end; class function TAccountComp.RawString2Accountkey(const rawaccstr: TRawBytes): TAccountKey; begin RawString2Accountkey(rawaccstr,Result); end; class procedure TAccountComp.RawString2Accountkey(const rawaccstr: TRawBytes; var dest: TAccountKey); Var ms : TMemoryStream; begin if length(rawaccstr)=0 then begin dest := CT_TECDSA_Public_Nul; exit; end; ms := TMemoryStream.Create; try ms.WriteBuffer(rawaccstr[1],length(rawaccstr)); ms.Position := 0; TStreamOp.ReadAccountKey(ms,dest); finally ms.Free; end; end; class function TAccountComp.TxtToMoney(const moneytxt: AnsiString; var money: Int64): Boolean; Var s : AnsiString; i : Integer; begin money := 0; if Trim(moneytxt)='' then begin Result := true; exit; end; try // Delphi 6 introduced "conditional compilation" and Delphi XE 6 (27) introduced FormatSettings variable. {$IF Defined(DCC) and Declared(CompilerVersion) and (CompilerVersion >= 27.0)} If pos(FormatSettings.DecimalSeparator,moneytxt)<=0 then begin // No decimal separator, consider ThousandSeparator as a decimal separator s := StringReplace(moneytxt,FormatSettings.ThousandSeparator,FormatSettings.DecimalSeparator,[rfReplaceAll]); end else begin s := StringReplace(moneytxt,FormatSettings.ThousandSeparator,'',[rfReplaceAll]); end; {$ELSE} If pos(DecimalSeparator,moneytxt)<=0 then begin // No decimal separator, consider ThousandSeparator as a decimal separator s := StringReplace(moneytxt,ThousandSeparator,DecimalSeparator,[rfReplaceAll]); end else begin s := StringReplace(moneytxt,ThousandSeparator,'',[rfReplaceAll]); end; {$IFEND} money := Round( StrToFloat(s)*10000 ); Result := true; Except result := false; end; end; class procedure TAccountComp.ValidsEC_OpenSSL_NID(list: TList); begin list.Clear; list.Add(TObject(CT_NID_secp256k1)); // = 714 list.Add(TObject(CT_NID_secp384r1)); // = 715 list.Add(TObject(CT_NID_sect283k1)); // = 729 list.Add(TObject(CT_NID_secp521r1)); // = 716 end; end.
unit Model.LacresDevolucao; interface uses Common.ENum, FireDAC.Comp.Client; type TLacresDevolucao = class private FAcao: TAcao; FStatus: Integer; FManutencao: TDateTime; FBase: Integer; FUsuario: String; FLacre: String; public property Base: Integer read FBase write FBase; property Lacre: String read FLacre write FLacre; property Status: Integer read FStatus write FStatus; property Usuario: String read FUsuario write FUsuario; property Manutencao: TDateTime read FManutencao write FManutencao; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TLacresDevolucao } uses DAO.LacresDevolucao; function TLacresDevolucao.Gravar: Boolean; var lacreDAO : TlacresDevolucaoDAO; begin try Result := False; lacreDAO := TlacresDevolucaoDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := lacreDAO.Inserir(Self); Common.ENum.tacAlterar: Result := lacreDAO.Alterar(Self); Common.ENum.tacExcluir: Result := lacreDAO.Excluir(Self); end; finally lacreDAO.Free; end; end; function TLacresDevolucao.Localizar(aParam: array of variant): TFDQuery; var lacreDAO : TlacresDevolucaoDAO; begin try lacreDAO := TlacresDevolucaoDAO.Create; Result := lacreDAO.Pesquisar(aParam); finally lacreDAO.Free; end; end; end.
/// <summary> /// This is an extract from u_dzClassUtils in dzlib http://blog.dummzeuch.de/dzlib/ </summary> unit GX_dzClassUtils; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, GX_GenericUtils; ///<summary> /// Assigns st to sl and sorts it. /// sl.Objects contains the index into st+1 /// so st[Integer(ls.Objects[i])] = sl[i] </summary> procedure TStrings_GetAsSortedList(_st: TStrings; _sl: TStringList; _Duplicates: TDuplicates = dupAccept); ///<summary> /// assign the current index to the Objects property and then sort the list </summary> procedure TStringList_MakeIndex(_sl: TStringList); procedure TGXUnicodeStringList_MakeIndex(_sl: TGXUnicodeStringList); function TStrings_ValueFromIndex(_st: TStrings; _Idx: integer): string; implementation procedure TStrings_GetAsSortedList(_st: TStrings; _sl: TStringList; _Duplicates: TDuplicates = dupAccept); begin Assert(Assigned(_st)); Assert(Assigned(_sl)); _sl.Sorted := False; _sl.Assign(_st); TStringList_MakeIndex(_sl); end; function TStrings_ValueFromIndex(_st: TStrings; _Idx: integer): string; var Name: string; begin Assert(Assigned(_st)); Name := _st.Names[_Idx]; Result := _st.Values[Name]; end; procedure TStringList_MakeIndex(_sl: TStringList); var i: integer; begin Assert(Assigned(_sl)); _sl.Sorted := False; for i := 0 to _sl.Count - 1 do _sl.Objects[i] := POinter(i + 1); _sl.Sorted := true; end; procedure TGXUnicodeStringList_MakeIndex(_sl: TGXUnicodeStringList); var i: integer; begin Assert(Assigned(_sl)); _sl.Sorted := False; for i := 0 to _sl.Count - 1 do _sl.Objects[i] := POinter(i + 1); _sl.Sorted := true; end; end.
unit U_ExtFileCopy; {$mode objfpc}{$H+} { Composant TExtFileCopy Développé par: Matthieu GIROUX Composant non visuel permettant de copier un fichier plus rapidement que par le fonction copy de windows. Compatible Linux Attention: La gestion de la RAM étant calamiteuse sous Win9x, l' utilisation de ce composant provoque une grosse une forte baisse de la mémoire disponible. Sous WinNT/2000 il n' y a pas de problèmes Version actuelle: 1.0 Mises à jour: } interface uses SysUtils, Classes,ComCtrls, StrUtils, lresources ; var GS_COPYFILES_ERROR_DIRECTORY_CREATE : String = 'Erreur à la création du répertoire' ; GS_COPYFILES_ERROR_IS_FILE : String = 'Ne peut copier dans le fichier' ; GS_COPYFILES_ERROR_CANT_COPY : String = 'Impossible de copier ' ; GS_COPYFILES_ERROR_PARTIAL_COPY : String = 'Copie partielle du fichier ' ; GS_COPYFILES_ERROR_PARTIAL_COPY_SEEK: String = 'Erreur à la copie partielle du fichier ' ; GS_COPYFILES_ERROR_CANT_READ : String = 'Impossible de lire le fichier ' ; GS_COPYFILES_ERROR_CANT_CHANGE_DATE : String = 'Impossible d''affecter la date au fichier ' ; GS_COPYFILES_ERROR_CANT_CREATE : String = 'Impossible de créer le fichier ' ; GS_COPYFILES_ERROR_CANT_APPEND : String = 'Impossible d''ajouter au fichier ' ; GS_COPYFILES_ERROR_FILE_DELETE : String = 'Impossible d''effacer le fichier ' ; GS_COPYFILES_CONFIRM_FILE_DELETE : String = 'Voulez-vous effacer le fichier ' ; GS_COPYFILES_CONFIRM : String = 'Demande de confirmation' ; type TECopyOption = ( cpCopyAll, cpUseFilter, cpNoStructure, cpCreateBackup, cpCreateDestination, cpDestinationIsFile ); TECopyOptions = set of TECopyOption; TECopyEvent = procedure(Sender : Tobject; const BytesCopied,BytesTotal : cardinal) of object; TEReturnEvent = procedure(Sender : Tobject; var Continue : Boolean ) of object; TECopyErrorEvent = procedure(Sender : Tobject; const ErrorCode : Integer ; var ErrorMessage : AnsiString ; var ContinueCopy : Boolean ) of object; TECopyFinishEvent = procedure(Sender : Tobject; const ASource, ADestination : AnsiString ; const Errors : Integer ) of object; TEChangeDirectoryEvent = procedure(Sender : Tobject; const NewDirectory, DestinationDirectory : AnsiString ) of object; const lco_Default = [cpCopyAll,cpUseFilter]; CST_COPYFILES_ERROR_IS_READONLY = faReadOnly ; CST_COPYFILES_ERROR_UNKNOWN = -1 ; CST_COPYFILES_ERROR_IS_DIRECTORY = faDirectory ; CST_COPYFILES_ERROR_IS_FILE = 1 ; CST_COPYFILES_ERROR_DIRECTORY_CREATE = 2 ; CST_COPYFILES_ERROR_CANT_COPY = 3 ; CST_COPYFILES_ERROR_CANT_READ = 4 ; CST_COPYFILES_ERROR_CANT_CREATE = 5 ; CST_COPYFILES_ERROR_CANT_APPEND = 6 ; CST_COPYFILES_ERROR_FILE_DELETE = 7 ; CST_COPYFILES_ERROR_PARTIAL_COPY = 8 ; CST_COPYFILES_ERROR_PARTIAL_COPY_SEEK = 9 ; CST_COPYFILES_ERROR_CANT_CHANGE_DATE = 10 ; type { TExtFileCopy } TExtFileCopy = class(TComponent) private FOnChange : TEChangeDirectoryEvent ; FSizeTotal : Int64 ; FErrors , FSizeProgress : Integer ; FOnSuccess : TECopyFinishEvent; FOnFailure : TECopyErrorEvent ; FBeforeCopy : TEReturnEvent ; FBeforeCopyBuffer , FOnProgress : TECopyEvent; FBufferSize : integer; FOptions : TECopyOptions ; FFilter, FSource,FDestination : string; FInProgress : Boolean; procedure SetBufferSize (Value : integer); procedure SetDestination(Value : String); procedure SetSource(Value: String); protected FBuffer : array[0..65535] of char; function BeforeCopyBuffer ( var li_SizeRead, li_BytesTotal : Longint ) : Boolean ; virtual ; function BeforeCopy : Boolean ; virtual ; procedure AfterCopyBuffer ; virtual ; { Déclarations protégées } public function EventualFailure ( const ai_Error : Integer ; as_Message : AnsiString ):Boolean; virtual ; function InternalDefaultCopyFile ( const as_Source, as_Destination : String ):Boolean; virtual ; procedure InternalFinish ( const as_Source, as_Destination : String ); virtual ; constructor Create(AOwner : Tcomponent);override; property InProgress : Boolean read FInprogress; Function CopyFile ( const as_Source, as_Destination : String ; const ab_AppendFile, ab_CreateBackup : Boolean ):Integer; Procedure CopySourceToDestination; published property BufferSize : integer read FBufferSize write SetBufferSize default 65536; property Source : string read FSource write SetSource; property Mask : string read FFilter write FFilter; property Destination : string read FDestination write SetDestination; property Options : TECopyOptions read FOptions write FOptions default lco_Default ; property OnSuccess : TECopyFinishEvent read FOnSuccess write FOnSuccess; property OnFailure : TECopyErrorEvent read FOnFailure write FOnFailure; property OnProgress : TECopyEvent read FOnProgress write Fonprogress; property OnBeforeCopyBuffer : TECopyEvent read FBeforeCopyBuffer write FBeforeCopyBuffer; property OnBeforeCopy : TEReturnEvent read FBeforeCopy write FBeforeCopy; property OnChange : TEChangeDirectoryEvent read FOnChange write FOnChange; end; {TExtFilePartialCopy} TExtFilePartialCopy = class(TExtFileCopy) private lb_ExcludedFound : Boolean ; lpch_excludeStart, lpch_excludeEnd : String ; FExcludeStart , FExcludeEnd : String ; FExcludeReading : Boolean; protected function BeforeCopyBuffer ( var li_SizeRead, li_BytesTotal : Longint ) : Boolean ; override ; function BeforeCopy : Boolean ; override ; procedure AfterCopyBuffer ; override ; { Déclarations protégées } public constructor Create(AOwner : Tcomponent);override; published property ExcludeReading : Boolean read FExcludeReading write FExcludeReading default False ; property ExcludeStart : String read FExcludeStart write FExcludeStart ; property ExcludeEnd : String read FExcludeEnd write FExcludeEnd ; end; procedure Register; implementation uses functions_file, Forms, Dialogs, Controls ; {TExtFileCopy} constructor TExtFileCopy.Create(AOwner :Tcomponent); begin inherited Create(AOwner); Options := lco_Default ; FBufferSize := 65536; FInProgress := False; end; procedure TExtFileCopy.SetBufferSize(Value : integer); begin If not FInprogress then begin If Value > high ( FBuffer ) then Value := high ( FBuffer ) + 1 Else FBufferSize := Value; end; end; procedure TExtFileCopy.SetDestination(Value: String); begin if FDestination <> Value Then Begin FDestination := Value; End; end; procedure TExtFileCopy.SetSource(Value: String); begin if FSource <> Value Then Begin FSource := Value; if not ( csDesigning in ComponentState ) and Assigned ( @FOnChange ) Then FOnChange ( Self, FSource, FDestination ); End; end; function TExtFileCopy.BeforeCopyBuffer(var li_SizeRead, li_BytesTotal : Longint ): Boolean; begin Result := True ; if Assigned ( FBeforeCopyBuffer ) Then FBeforeCopyBuffer ( Self, li_SizeRead, li_BytesTotal ); end; function TExtFileCopy.BeforeCopy: Boolean; begin Result := True ; if Assigned ( FBeforeCopy ) Then FBeforeCopy ( Self, Result ); end; procedure TExtFileCopy.AfterCopyBuffer; begin end; Function TExtFileCopy.CopyFile ( const as_Source, as_Destination : String ; const ab_AppendFile, ab_CreateBackup : Boolean ):Integer; var li_SizeRead,li_SizeWrite,li_TotalW, li_RealTotal : Longint; li_SizeTotal : Int64 ; li_HandleSource,li_HandleDest, li_pos, li_Confirm : integer; ls_FileName, ls_FileExt,ls_Destination : String ; lb_FoundFile : Boolean; lsr_data : Tsearchrec; begin Result := 0 ; li_Confirm := mrYes ; FindFirst(as_Source,faanyfile,lsr_data); li_RealTotal := lsr_data.size ; li_SizeTotal := lsr_data.Size; inc ( FSizeTotal, li_SizeTotal ); li_TotalW := 0; findclose(lsr_data); try li_HandleSource := fileopen(as_Source,fmopenread); Except On E: Exception do Begin Result := CST_COPYFILES_ERROR_CANT_READ ; EventualFailure ( Result, GS_COPYFILES_ERROR_CANT_READ + as_Destination ); Exit ; End ; End ; ls_Destination := as_Destination ; if ab_AppendFile and fileexists(as_Destination) then try FindFirst(as_Destination,faanyfile,lsr_data); li_HandleDest := FileOpen(as_Destination, fmopenwrite ); FileSeek ( li_HandleDest, lsr_data.Size, 0 ); findclose(lsr_data); Except Result := CST_COPYFILES_ERROR_CANT_APPEND ; EventualFailure ( Result, GS_COPYFILES_ERROR_CANT_APPEND + as_Destination ); Exit ; End Else Begin If fileexists(ls_Destination) then Begin FindFirst(as_Destination,faanyfile,lsr_data); if ( ab_CreateBackup ) Then try ls_FileName := lsr_data.Name; ls_FileExt := '' ; li_pos := 1; while ( PosEx ( '.', ls_FileName, li_pos + 1 ) > 0 ) Do li_pos := PosEx ( '.', ls_FileName, li_pos + 1 ); if ( li_Pos > 1 ) Then Begin ls_FileExt := Copy ( ls_FileName, li_pos, length ( ls_FileName ) - li_pos + 1 ); ls_FileName := Copy ( ls_FileName, 1, li_pos - 1 ); End ; li_pos := 0 ; while FileExists ( ls_Destination ) do Begin inc ( li_pos ); ls_Destination := ExtractFilePath ( as_Destination ) + DirectorySeparator + ls_FileName + '-' + IntToStr ( li_pos ) + ls_FileExt ; End Except Result := -1 ; EventualFailure ( Result, as_Destination ); Exit ; End Else try if li_Confirm <> mrAll Then li_Confirm := MessageDlg ( GS_COPYFILES_CONFIRM, GS_COPYFILES_CONFIRM_FILE_DELETE, mtConfirmation, [mbYes,mbNo,mbAll,mbCancel], 0 ); if li_Confirm = mrCancel Then Abort ; if li_Confirm = mrNo Then Exit ; Deletefile(as_Destination); Except Result := CST_COPYFILES_ERROR_FILE_DELETE ; EventualFailure ( Result, GS_COPYFILES_ERROR_FILE_DELETE + as_Destination ); Exit ; End ; findclose(lsr_data); End ; try li_HandleDest := filecreate(ls_Destination); Except Result := CST_COPYFILES_ERROR_CANT_CREATE ; EventualFailure ( Result, GS_COPYFILES_ERROR_CANT_CREATE + as_Destination ); Exit ; End end ; if not BeforeCopy Then Exit ; lb_FoundFile := False; while not lb_FoundFile do try li_SizeRead := FileRead(li_HandleSource,FBuffer,FbufferSize); if ( li_SizeRead <= 0 ) and ( li_TotalW < li_RealTotal ) Then try FileSeek ( li_HandleSource, 64, li_TotalW ); Inc ( li_TotalW, 64 ); Continue ; Except Result := CST_COPYFILES_ERROR_PARTIAL_COPY_SEEK ; EventualFailure ( Result, GS_COPYFILES_ERROR_PARTIAL_COPY_SEEK + as_Destination ); End ; if BeforeCopyBuffer ( li_SizeRead, li_TotalW ) Then Begin li_SizeWrite := Filewrite(li_HandleDest,Fbuffer,li_SizeRead); Application.ProcessMessages; inc( li_TotalW, li_SizeWrite ); if ( li_SizeRead < FBufferSize ) and ( li_TotalW >= li_RealTotal ) then lb_FoundFile := True; if li_SizeWrite < li_SizeRead then Begin Result := CST_COPYFILES_ERROR_PARTIAL_COPY ; EventualFailure ( Result, GS_COPYFILES_ERROR_PARTIAL_COPY + as_Destination ); End ; if assigned(FonProgress) then FonProgress(self, FSizeProgress + li_TotalW,FSizeTotal); End ; AfterCopyBuffer ; Except Result := CST_COPYFILES_ERROR_CANT_COPY ; EventualFailure ( Result, GS_COPYFILES_ERROR_CANT_COPY + '( ' + as_Source + ' -> ' + as_Destination + ' )' ); Exit ; End ; try filesetdate(li_HandleDest,filegetdate(li_HandleSource)); Except Result := CST_COPYFILES_ERROR_CANT_CHANGE_DATE ; EventualFailure ( Result, GS_COPYFILES_ERROR_CANT_CHANGE_DATE + as_Destination ); Exit ; End ; fileclose(li_HandleSource); fileclose(li_HandleDest); if Result = 0 then Begin inc ( FSizeProgress, li_TotalW ); InternalFinish ( as_Source, as_Destination ); Result := 0 ; End ; Application.ProcessMessages ; end; function TExtFileCopy.InternalDefaultCopyFile ( const as_Source, as_Destination : String ):Boolean; var li_Error : Integer ; begin Result := True ; li_Error := CopyFile ( as_Source, as_Destination, cpDestinationIsFile in FOptions, cpCreateBackup in FOptions ); EventualFailure ( li_Error , '' ); End ; function TExtFileCopy.EventualFailure ( const ai_Error : Integer ; as_Message : AnsiString ):Boolean; begin Result := True ; if ( ai_Error <> 0 ) then Begin inc ( FErrors ); if assigned ( FOnFailure ) then Begin FOnFailure ( Self, ai_Error, as_Message, Result ); End ; End ; End ; procedure TExtFileCopy.InternalFinish ( const as_Source, as_Destination : String ); begin if assigned ( @FOnSuccess ) then Begin FOnSuccess ( Self, as_Source, as_Destination, FErrors ); End ; End ; procedure TExtFileCopy.CopySourceToDestination; var lb_Continue : Boolean ; begin Finprogress := true; FSizeTotal := 0 ; FErrors := 0 ; FSizeProgress := 0 ; if ( not FileExists ( FSource ) and not DirectoryExists ( FSource )) Then Exit ; if not DirectoryExists ( FDestination ) and not fb_CreateDirectoryStructure ( FDestination ) Then Exit ; try if ( DirectoryExists ( FSource )) Then Begin lb_Continue := fb_InternalCopyDirectory ( FSource, FDestination, FFilter, not ( cpNoStructure in FOptions ), cpDestinationIsFile in FOptions, cpCopyAll in FOptions, cpCreateBackup in FOptions, Self ); End Else Begin lb_Continue := fb_InternalCopyFile ( FSource, FDestination, cpDestinationIsFile in FOptions, cpCreateBackup in FOptions, Self ); End ; finally FinProgress := false; End ; end; {TExtFilePartialCopy} constructor TExtFilePartialCopy.Create(AOwner :Tcomponent); begin inherited Create(AOwner); FExcludeReading := False ; end; function TExtFilePartialCopy.BeforeCopyBuffer ( var li_SizeRead, li_BytesTotal : Longint ) : Boolean ; var li_pos, li_i : Longint ; Begin Result := inherited BeforeCopyBuffer ( li_SizeRead, li_BytesTotal ); if FExcludeReading and ( FExcludeStart <> '' ) and ( FExcludeEnd <> '' ) Then Begin li_pos := 0 ; li_i := 0 ; while li_pos < li_SizeRead do if lb_ExcludedFound then Begin End Else Begin End; end; End ; procedure TExtFilePartialCopy.AfterCopyBuffer ; Begin End ; function TExtFilePartialCopy.BeforeCopy : Boolean ; Begin Result := inherited BeforeCopy (); if FExcludeReading and ( FExcludeStart <> '' ) and ( FExcludeEnd <> '' ) Then Begin // lpch_excludeStart := fs_HexToString ( FExcludeStart ); // lpch_excludeEnd := fs_HexToString ( FExcludeEnd ); End ; End ; procedure Register; begin RegisterComponents('Extended', [TExtFileCopy]); end; initialization {$i U_ExtFileCopy.lrs} end.
unit K607284377; {* [Requestlink:607284377] } // Модуль: "w:\common\components\rtl\Garant\Daily\K607284377.pas" // Стереотип: "TestCase" // Элемент модели: "K607284377" MUID: (560517DB008C) // Имя типа: "TK607284377" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK607284377 = class(TRTFtoEVDWriterTest) {* [Requestlink:607284377] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK607284377 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *560517DB008Cimpl_uses* //#UC END# *560517DB008Cimpl_uses* ; function TK607284377.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.11'; end;//TK607284377.GetFolder function TK607284377.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '560517DB008C'; end;//TK607284377.GetModelElementGUID initialization TestFramework.RegisterTest(TK607284377.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit USortedList; interface uses Classes; type TSortedList = class(TList) private FSorted:Boolean; FDuplicates: TDuplicates; FCompareFunc: TListSortCompare; procedure QuickSort(L, R: Integer; Compare: TListSortCompare); procedure SetSorted(Value: Boolean); procedure SetCompareFunc(const Value: TListSortCompare); public function Add(Item:Pointer):Integer;reintroduce; function FindAndDelete(Item:Pointer):Boolean; function Find(Item:Pointer; var Index: Integer): Boolean; procedure CustomSort(Compare: TListSortCompare); procedure RemoveLast; procedure RemoveFirst; procedure Sort; property Duplicates: TDuplicates read FDuplicates write FDuplicates; property Sorted: Boolean read FSorted write SetSorted; property CompareFunc:TListSortCompare read FCompareFunc write SetCompareFunc; end; implementation uses SysUtils; function NoCompareFunc(Item1,Item2:Pointer):Integer; begin raise Exception.Create('TSortedList - no CompareFunc specified'); Result:=0; end; { TSortedList } function TSortedList.Add(Item:Pointer): Integer; begin if not Sorted then Result := Count else if Find(Item, Result) then case Duplicates of dupIgnore: Exit; dupError: Error('dupError', 0); end; inherited Insert(Result, Item); end; function TSortedList.Find(Item:Pointer; var Index:Integer): Boolean; var L, H, I, C: Integer; begin if not Sorted then begin I:=IndexOf(Item); Index:=I; Result:=I>=0; exit; end; Result := False; L := 0; H := Count - 1; while L <= H do begin I := (L + H) shr 1; C := FCompareFunc(Items[I], Item); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> dupAccept then L := I; end; end; end; Index := L; end; procedure TSortedList.QuickSort(L, R: Integer; Compare: TListSortCompare); var I, J, P: Integer; IP:Pointer; begin repeat I := L; J := R; P := (L + R) shr 1; repeat IP:=Items[P]; while Compare(Items[I], IP) < 0 do Inc(I); while Compare(Items[J], IP) > 0 do Dec(J); if I <= J then begin IP:=Items[I]; Items[I]:=Items[J]; Items[J]:=IP; if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J, Compare); L := I; until I >= R; end; procedure TSortedList.SetSorted(Value: Boolean); begin if FSorted <> Value then begin if Value then Sort; FSorted := Value; end; end; procedure TSortedList.Sort; begin CustomSort(FCompareFunc); end; procedure TSortedList.CustomSort(Compare: TListSortCompare); begin if not Sorted and (Count > 1) then begin QuickSort(0, Count - 1, Compare); end; end; procedure TSortedList.SetCompareFunc(const Value: TListSortCompare); begin if @Value<>@FCompareFunc then begin FCompareFunc := Value; if Sorted then begin FSorted:=False; Sort; FSorted:=True; end; end; end; procedure TSortedList.RemoveFirst; begin Delete(0); end; procedure TSortedList.RemoveLast; begin Delete(Count-1); end; function TSortedList.FindAndDelete(Item: Pointer): Boolean; var Index:Integer; begin Result:=Find(Item,Index); if Result then Delete(Index); end; end.
unit ironhorse_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,nz80,main_engine,controls_engine,gfx_engine,ym_2203,rom_engine, pal_engine,sound_engine; function iniciar_ironhorse:boolean; implementation const ironhorse_rom:array[0..1] of tipo_roms=( (n:'560_k03.13c';l:$8000;p:$4000;crc:$395351b4),(n:'560_k02.12c';l:$4000;p:$c000;crc:$1cff3d59)); ironhorse_snd:tipo_roms=(n:'560_h01.10c';l:$4000;p:0;crc:$2b17930f); ironhorse_gfx:array[0..3] of tipo_roms=( (n:'560_h06.08f';l:$8000;p:0;crc:$f21d8c93),(n:'560_h05.07f';l:$8000;p:$1;crc:$60107859), (n:'560_h07.09f';l:$8000;p:$10000;crc:$c761ec73),(n:'560_h04.06f';l:$8000;p:$10001;crc:$c1486f61)); ironhorse_pal:array[0..4] of tipo_roms=( (n:'03f_h08.bin';l:$100;p:0;crc:$9f6ddf83),(n:'04f_h09.bin';l:$100;p:$100;crc:$e6773825), (n:'05f_h10.bin';l:$100;p:$200;crc:$30a57860),(n:'10f_h12.bin';l:$100;p:$300;crc:$5eb33e73), (n:'10f_h11.bin';l:$100;p:$400;crc:$a63e37d8)); //Dip ironhorse_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((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:'3C 2C'),(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'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),(dip_val:$0;dip_name:'No Coin B'))),()); ironhorse_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:'30K 70K+'),(dip_val:$10;dip_name:'40K 80K+'),(dip_val:$8;dip_name:'40K'),(dip_val:$0;dip_name:'50K'),(),(),(),(),(),(),(),(),(),(),(),())), (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'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); ironhorse_dip_c:array [0..3] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$1;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Upright Controls';number:2;dip:((dip_val:$2;dip_name:'Single'),(dip_val:$0;dip_name:'Dual'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Button Layout';number:2;dip:((dip_val:$4;dip_name:'Power Attack Squat'),(dip_val:$0;dip_name:'Squat Attack Power'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var pedir_nmi,pedir_firq:boolean; sound_latch,charbank,palettebank:byte; spritebank:word; scroll_x:array[0..$1f] of word; procedure update_video_ironhorse; var x,y,atrib,a,b,c,d:byte; f,nchar,color:word; flipx,flipy:boolean; begin for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=f mod 32; y:=f div 32; atrib:=memoria[$2000+f]; nchar:=memoria[$2400+f]+((atrib and $40) shl 2)+((atrib and $20) shl 4)+(charbank shl 10); color:=((atrib and $f)+16*palettebank) shl 4; put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $10)<>0,(atrib and $20)<>0); gfx[0].buffer[f]:=false; end; end; //Scroll linea a linea scroll__x_part2(1,2,8,@scroll_x); for f:=0 to $32 do begin x:=memoria[spritebank+3+(f*5)]; y:=memoria[spritebank+2+(f*5)]; atrib:=memoria[spritebank+1+(f*5)]; nchar:=(memoria[spritebank+(f*5)] shl 2)+((atrib and $03) shl 10)+((atrib and $0c) shr 2); color:=((((atrib and $f0) shr 4)+16*palettebank) shl 4)+$800; atrib:=memoria[spritebank+4+(f*5)]; flipx:=((atrib and $20) shr 5)<>0; flipy:=((atrib and $40) shr 5)<>0; case (atrib and $c) of $0:begin //16x16 a:=(0 xor byte(flipx)) xor byte(flipy); b:=(1 xor byte(flipx)) xor byte(flipy); c:=(2 xor byte(flipx)) xor byte(flipy); d:=(3 xor byte(flipx)) xor byte(flipy); put_gfx_sprite_diff(nchar+a,color,flipx,flipy,0,0,0); put_gfx_sprite_diff(nchar+b,color,flipx,flipy,0,8,0); put_gfx_sprite_diff(nchar+c,color,flipx,flipy,0,0,8); put_gfx_sprite_diff(nchar+d,color,flipx,flipy,0,8,8); actualiza_gfx_sprite_size(x,y,2,16,16); end; $4:begin //16x8 a:=0 xor byte(flipx); b:=1 xor byte(flipx); put_gfx_sprite_diff(nchar+a,color,flipx,flipy,0,0,0); put_gfx_sprite_diff(nchar+b,color,flipx,flipy,0,8,0); actualiza_gfx_sprite_size(x,y,2,16,8); end; $8:begin //8x16 a:=0 xor byte(flipy); b:=2 xor byte(flipy); put_gfx_sprite_diff(nchar+a,color,flipx,flipy,0,0,0); put_gfx_sprite_diff(nchar+b,color,flipx,flipy,0,0,8); actualiza_gfx_sprite_size(x,y,2,8,16); end; $c:begin //8x8 put_gfx_sprite_mask(nchar,color,flipx,flipy,0,0,$f); actualiza_gfx_sprite(x,y,2,0); end; end; end; actualiza_trozo_final(8,16,240,224,2); end; procedure eventos_ironhorse; begin if event.arcade then begin //p1 if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but2[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); //p2 if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[1] 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); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); end; end; procedure ironhorse_principal; var frame_m,frame_s:single; f:byte; frame:boolean; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=z80_0.tframes; frame:=false; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //snd z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; case f of 47,111,175:if pedir_nmi then m6809_0.change_nmi(PULSE_LINE); 239:begin if (pedir_firq and frame) then m6809_0.change_firq(HOLD_LINE); if pedir_nmi then m6809_0.change_nmi(PULSE_LINE); end; end; end; update_video_ironhorse; eventos_ironhorse; video_sync; frame:=not(frame); end; end; function ironhorse_getbyte(direccion:word):byte; begin case direccion of 0..$1f,$40..$df,$2000..$ffff:ironhorse_getbyte:=memoria[direccion]; $20..$3f:ironhorse_getbyte:=scroll_x[direccion and $1f]; $900:ironhorse_getbyte:=marcade.dswc; //dsw3 $a00:ironhorse_getbyte:=marcade.dswb; //dsw2 $b00:ironhorse_getbyte:=marcade.dswa; //dsw1 $b01:ironhorse_getbyte:=marcade.in1; //p2 $b02:ironhorse_getbyte:=marcade.in0; //p1 $b03:ironhorse_getbyte:=marcade.in2; //system end; end; procedure ironhorse_putbyte(direccion:word;valor:byte); begin case direccion of 0..2,5..$1f,$40..$df,$2800..$3fff:memoria[direccion]:=valor; $3:begin if charbank<>(valor and $3) then begin charbank:=valor and $3; fillchar(gfx[0].buffer[0],$400,1); end; spritebank:=$3000+((valor and $8) shl 8); end; $4:begin pedir_nmi:=(valor and $1)<>0; pedir_firq:=(valor and $4)<>0; end; $20..$3f:scroll_x[direccion and $1f]:=valor; $800:sound_latch:=valor; $900:z80_0.change_irq(HOLD_LINE); $a00:if palettebank<>(valor and $7) then begin palettebank:=valor and $7; fillchar(gfx[0].buffer[0],$400,1); end; $b00:main_screen.flip_main_screen:=(valor and $8)=0; $2000..$27ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $4000..$ffff:; //ROM end; end; function ironhorse_snd_getbyte(direccion:word):byte; begin case direccion of 0..$43ff:ironhorse_snd_getbyte:=mem_snd[direccion]; $8000:ironhorse_snd_getbyte:=sound_latch end; end; procedure ironhorse_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; //ROM $4000..$43ff:mem_snd[direccion]:=valor; end; end; function ironhorse_snd_inbyte(puerto:word):byte; begin if (puerto and $ff)=0 then ironhorse_snd_inbyte:=ym2203_0.status; end; procedure ironhorse_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of 0:ym2203_0.Control(valor); 1:ym2203_0.Write(valor); end; end; procedure ironhorse_sound_update; begin ym2203_0.Update; end; //Main procedure reset_ironhorse; begin m6809_0.reset; z80_0.reset; ym2203_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; pedir_nmi:=false; pedir_firq:=false; charbank:=0; sound_latch:=0; spritebank:=$3800; palettebank:=0; end; function iniciar_ironhorse:boolean; var colores:tpaleta; valor,j:byte; f,valor2:word; memoria_temp:array[0..$1ffff] of byte; const pc_x:array[0..7] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4); pc_y:array[0..7] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32); begin llamadas_maquina.bucle_general:=ironhorse_principal; llamadas_maquina.reset:=reset_ironhorse; llamadas_maquina.fps_max:=61; iniciar_ironhorse:=false; iniciar_audio(false); screen_init(1,256,256); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256,false,true); iniciar_video(240,224); //Main CPU m6809_0:=cpu_m6809.Create(18432000 div 12,$100,TCPU_M6809); m6809_0.change_ram_calls(ironhorse_getbyte,ironhorse_putbyte); //Sound CPU z80_0:=cpu_z80.create(3072000,$100); z80_0.change_ram_calls(ironhorse_snd_getbyte,ironhorse_snd_putbyte); z80_0.change_io_calls(ironhorse_snd_inbyte,ironhorse_snd_outbyte); z80_0.init_sound(ironhorse_sound_update); //Sound Chip ym2203_0:=ym2203_chip.create(3072000); //cargar roms if not(roms_load(@memoria,ironhorse_rom)) then exit; //roms sonido if not(roms_load(@mem_snd,ironhorse_snd)) then exit; //convertir chars if not(roms_load16b(@memoria_temp,ironhorse_gfx)) then exit; init_gfx(0,8,8,$1000); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //paleta if not(roms_load(@memoria_temp,ironhorse_pal)) then exit; for f:=0 to $ff do begin colores[f].r:=((memoria_temp[f] and $f) shl 4) or (memoria_temp[f] and $f); colores[f].g:=((memoria_temp[f+$100] and $f) shl 4) or (memoria_temp[f+$100] shr 4); colores[f].b:=((memoria_temp[f+$200] and $f) shl 4) or (memoria_temp[f+$200] and $f); end; set_pal(colores,256); for f:=0 to $1ff do begin for j:=0 to 7 do begin valor:=(j shl 5) or ((not(f) and $100) shr 4) or (memoria_temp[f+$300] and $0f); valor2:=((f and $100) shl 3) or (j shl 8) or (f and $ff); gfx[0].colores[valor2]:=valor; //chars gfx[1].colores[valor2]:=valor; //sprites end; end; //DIP marcade.dswa:=$ff; marcade.dswb:=$5a; marcade.dswc:=$fe; marcade.dswa_val:=@ironhorse_dip_a; marcade.dswb_val:=@ironhorse_dip_b; marcade.dswc_val:=@ironhorse_dip_c; //final reset_ironhorse; iniciar_ironhorse:=true; end; end.
unit fEnemyIndex; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ByteList,cMegaROM, cConfiguration; type TfrmEnemyIndexEditor = class(TForm) lvwEnemyIndex: TListView; cmdMoveUp: TButton; cmdMoveDown: TButton; cmdAutoSort: TButton; cmdOk: TButton; cmdAutoSortLevel: TButton; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cmdMoveUpClick(Sender: TObject); procedure cmdMoveDownClick(Sender: TObject); procedure cmdAutoSortClick(Sender: TObject); procedure cmdAutoSortLevelClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; _IDs : TByteList; procedure LoadIDs; { Private declarations } public procedure PopulateList; property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmEnemyIndexEditor: TfrmEnemyIndexEditor; implementation {$R *.dfm} uses uGlobal; procedure TfrmEnemyIndexEditor.PopulateList; var i,count : Integer; begin lvwEnemyIndex.Items.BeginUpdate; lvwEnemyIndex.Items.Clear; count := 0; for i := 0 to _IDs.Count -1 do begin with lvwEnemyIndex.Items.Add do begin Caption := IntToHex(Count,2); SubItems.Add(_ROMData.EnemyDescriptions[_ROMData.CurrLevel.Enemies[_IDs[i]].ID] ); SubItems.Add(IntToHex(_ROMData.CurrLevel.Enemies[_IDs[i]].X,2)); SubItems.Add(IntToHex(_ROMData.CurrLevel.Enemies[_IDs[i]].Y,2)); end; inc(count); end; lvwEnemyIndex.Items.EndUpdate; end; procedure TfrmEnemyIndexEditor.LoadIDs; var i : Integer; begin _IDs := TByteList.Create(0); for i := 0 to _ROMData.CurrLevel.Enemies.Count -1 do begin // if _ROMData.CurrLevel.Enemies[i].ScreenID = _ROMData.Room then // begin _IDs.Add(i); // end; end; end; procedure TfrmEnemyIndexEditor.FormShow(Sender: TObject); begin LoadIDs; PopulateList; end; procedure TfrmEnemyIndexEditor.FormDestroy(Sender: TObject); begin FreeAndNil(_IDs); end; procedure TfrmEnemyIndexEditor.cmdMoveUpClick(Sender: TObject); var oldindex : Integer; begin if lvwEnemyIndex.ItemIndex > 0 then begin _ROMData.CurrLevel.Enemies.Exchange(_IDs[lvwEnemyIndex.ItemIndex],_IDs[lvwEnemyIndex.ItemIndex -1]); oldindex := lvwEnemyIndex.ItemIndex - 1; PopulateList; lvwEnemyIndex.ItemIndex := oldindex; _ROMData.Changed := True; end; end; procedure TfrmEnemyIndexEditor.cmdMoveDownClick(Sender: TObject); var oldindex : Integer; begin if (lvwEnemyIndex.ItemIndex < lvwEnemyIndex.Items.Count -1) and (lvwEnemyIndex.ItemIndex > -1) then begin _ROMData.CurrLevel.Enemies.Exchange(_IDs[lvwEnemyIndex.ItemIndex],_IDs[lvwEnemyIndex.ItemIndex+1]); oldindex := lvwEnemyIndex.ItemIndex + 1; PopulateList; lvwEnemyIndex.ItemIndex := oldindex; _ROMData.Changed := True; end; end; procedure TfrmEnemyIndexEditor.cmdAutoSortClick(Sender: TObject); var unsorted : boolean; i : integer; begin if _IDs.Count = 2 then begin if _ROMData.CurrLevel.Enemies[_IDs[0]].X > _ROMData.CurrLevel.Enemies[_IDs[1]].X then _ROMData.CurrLevel.Enemies.Exchange(_IDs[0],_IDs[1]); end else if _IDs.Count > 1 then begin repeat unsorted := true; for i := 0 to _IDs.Count -2 do begin if _ROMData.CurrLevel.Enemies[_IDs[i]].X > _ROMData.CurrLevel.Enemies[_IDs[i + 1]].X then begin _ROMData.CurrLevel.Enemies.Exchange(_IDs[i],_IDs[i+1]); unsorted := false; end; end; until unsorted; end; PopulateList; end; procedure TfrmEnemyIndexEditor.cmdAutoSortLevelClick(Sender: TObject); begin _ROMData.SortEnemyData(_ROMData.CurrentLevel); _ROMData.SortEnemyDataByX(_ROMData.CurrentLevel); PopulateList; end; end.
(*=============================================================================| String functionality |=============================================================================*) {!DOCTOPIC} { Type » String } {!DOCREF} { @method: function String.Len(): Int32; @desc: Returns the length of the String. Same as `Length(Str)` } function String.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function String.StrLen(): Int32; @desc: Returns the null-terinated length of the String. } function String.StrLen(): Int32; var P: PChar; Begin P := @Self[1]; while (P^ <> #0) do Inc(P); Result := Int32(P) - Int32(@Self[1]); end; {!DOCREF} { @method: function String.Slice(Start,Stop: Int32; Step:Int32=1): String; @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 c'length(..) + 1' If `Start >= Stop`, and `Step <= -1` it will result in reversed output. [note]Don't pass positive `Step`, combined with `Start > Stop`, that is undefined[/note] } function String.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): String; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 1; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 1; if (Step = 0) then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result, 0); RaiseException(erOutOfRange,'Must be in range of "1..Length(Self)". [Start='+ToStr(Start)+', Stop='+ToStr(Stop)+', Step='+ToStr(Step)+']'); end; end; {!DOCREF} { @method: procedure String.Extend(Str:String); @desc: Extends the string with a string } procedure String.Extend(Str:String); begin Self := Self + Str; end; {!DOCREF} { @method: function String.Pos(Sub:String): Int32; @desc: Return the lowest index in the string where substring `Sub` is located. 0 if not found } function String.Pos(Sub:String): Int32; begin Result := se.StrPosL(Sub,Self); end; {!DOCREF} { @method: function String.rPos(Sub:String): Int32; @desc: Return the highest index in the string where substring `Sub` is located. 0 if not found } function String.rPos(Sub:String): Int32; begin Result := se.StrPosR(Sub,Self); end; {!DOCREF} { @method: function String.PosMulti(Sub:String): TIntArray; @desc: Return all the index in the string where substring `Sub` is located. Empty is not found } function String.PosMulti(Sub:String): TIntArray; begin Result := se.StrPosEx(Sub,Self); end; {!DOCREF} { @method: function String.Find(Value:String): Int32; @desc: Searces for the given value and returns the first position from the left. [note] Same as `String.Pos(..)` [/note] } function String.Find(Value:String): Int32; begin Result := exp_Find(Self,Value); end; {!DOCREF} { @method: function String.FindAll(Value:String): TIntArray; overload; @desc: Searces for the given value and returns all the position where it was found. [note]Same Result as `String.PosMulti(..)` but less optimized for the task[/note] } function String.FindAll(Value:String): TIntArray; overload; begin Result := exp_FindAll(Self,Value); end; {!DOCREF} { @method: function String.Contains(val:String): Boolean; @desc: Checks if the arr contains the given value c'val' } function String.Contains(val:String): Boolean; begin Result := Self.Find(val) <> 0; end; {!DOCREF} { @method: function String.Count(val:String): Int32; @desc: Counts all the occurances of the given value `val` } function String.Count(val:String): Int32; begin Result := Length(Self.PosMulti(val)); end; {!DOCREF} { @method: function String.Strip(const Chars:String=' '): String; @desc: Return a copy of the string with leading and trailing characters removed. If chars is omitted, whitespace characters are removed. If chars is given, the characters in the string will be stripped from the both ends of the string this method is called on. [code=pascal] >>> WriteLn( ' spacious '.Strip() ); 'spacious' >>> WriteLn( 'www.example.com'.Strip('cmow.') ); 'example' [/code] } function String.Strip(const Chars:String=' '): String; begin Result := exp_StrStrip(Self, Chars); end; {!DOCREF} { @method: function String.lStrip(const Chars:String=' '): String; @desc: Return a copy of the string with leading removed. If chars is omitted, whitespace characters are removed. If chars is given, the characters in the string will be stripped from the beginning of the string this method is called on. [code=pascal] >>> WriteLn( ' spacious '.lStrip() ); 'spacious ' >>> WriteLn( 'www.example.com'.lStrip('cmowz.') ); 'example.com' [/code] } function String.lStrip(const Chars:String=' '): String; begin Result := exp_StrStripL(Self, Chars); end; {!DOCREF} { @method: function String.rStrip(const Chars:String=' '): String; @desc: Return a copy of the string with trailing removed. If chars is omitted, whitespace characters are removed. If chars is given, the characters in the string will be stripped from the end of the string this method is called on. [code=pascal] >>> WriteLn( ' spacious '.rStrip() ); ' spacious' >>> WriteLn( 'mississippi'.rStrip('ipz') ); 'mississ' [/code] } function String.rStrip(const Chars:String=' '): String; begin Result := exp_StrStripR(Self, Chars); end; {!DOCREF} { @method: function String.Reversed(): String; @desc: Creates a reversed copy of the string } function String.Reversed():string; begin Result := Self.Slice(,,-1); end; {!DOCREF} { @method: procedure String.Reverse(); @desc: Reverses the string } procedure String.Reverse(); begin Self := Self.Slice(,,-1); end; {!DOCREF} { @method: function String.Replace(old, new:String; Flags:TReplaceFlags=[rfReplaceAll]): String; @desc: Return a copy of the string with all occurrences of substring old replaced by new. [note]Should be a much faster then Simbas c'Replace(...)'[/note] } function String.Replace(old, new:String; Flags:TReplaceFlags=[rfReplaceAll]): String; begin Result := se.StrReplace(Self, old, new, Flags); end; {!DOCREF} { @method: function String.Split(sep:String): TStringArray; @desc: Return an array of the words in the string, using 'sep' as the delimiter string. [note]Should be a tad faster then Simbas c'Explode(...)'[/note] } function String.Split(Sep:String=' '): TStringArray; begin Result := se.StrExplode(self,sep); end; {!DOCREF} { @method: function String.Join(TSA:TStringArray): String; @desc: Return a string which is the concatenation of the strings in the array 'TSA'. The separator between elements is the string providing this method. } function String.Join(TSA:TStringArray): String; begin Result := Implode(Self, TSA); end; //fix for single char evaulation. function Char.Join(TSA:TStringArray): String; begin Result := Implode(Self, TSA); end; {!DOCREF} { @method: function String.Mul(x:uInt32): String; @desc: Repeats the string `x` times } function String.Mul(x:Int32): String; var i,H: Int32; begin if Length(Self) = 0 then Exit(''); Result := Self; H := Length(Self); SetLength(Result, H*x); Dec(x); for i:=1 to x do MemMove(Self[1], Result[1+H*i], H); end; function Char.Mul(x:Int32): String; var i,H: Int32; begin Result := Self; dec(x); for i:=1 to x do Result := Result + Self; end; {!DOCREF} { @method: function String.StartsWith(Prefix:String): Boolean; @desc: Returns True if the string starts with `Prefix`. } function String.StartsWith(Prefix:String): Boolean; var i: Int32; begin if Length(Prefix) > Length(Self) then Exit(False); Result := True; for i:=1 to Length(Prefix) do if (Prefix[i] <> Self[i]) then Exit(False); end; {!DOCREF} { @method: function String.EndsWith(Suffix:String): Boolean; @desc: Returns True if the string ends with `Suffix`. } function String.EndsWith(Suffix:String): Boolean; var i,l: Int32; begin if Length(Suffix) > Length(Self) then Exit(False); Result := True; l := Length(Self); for i:=1 to Length(Suffix) do if (Suffix[i] <> Self[l-Length(Suffix)+i]) then Exit(False); end; {!DOCREF} { @method: function String.Capital(): String; @desc: Return a copy of the string with the first character in each word capitalized. } function String.Capital(): String; begin Result := Capitalize(Self); end; {!DOCREF} { @method: function String.Upper(): String; @desc: Return a copy of the string with all the chars converted to uppercase. } function String.Upper(): String; begin Result := Uppercase(Self); end; {!DOCREF} { @method: function String.Lower(): String; @desc: Return a copy of the string with all the chars converted to lowercase. } function String.Lower(): String; begin Result := Lowercase(Self); end; {!DOCREF} { @method: function String.IsAlphaNum(): Boolean; @desc: Return true if all characters in the string are alphabetic or numerical and there is at least one character, false otherwise. } function String.IsAlphaNum(): Boolean; var ptr: PChar; hiptr:UInt32; begin if Length(Self) = 0 then Exit(False); ptr := PChar(Self); hiptr := UInt32(UInt32(ptr) + Length(self)); while UInt32(ptr) < hiptr do if not (ptr^ in ['0'..'9','a'..'z','A'..'Z']) then Exit(False) else Inc(ptr); Result := True; end; function Char.IsAlphaNum(): Boolean; begin Result := (Self in ['A'..'Z', 'a'..'z','0'..'9']); end; {!DOCREF} { @method: function String.IsAlpha(): Boolean; @desc: Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. } function String.IsAlpha(): Boolean; var ptr: PChar; hiptr:UInt32; begin if Length(Self) = 0 then Exit(False); ptr := PChar(Self); hiptr := UInt32(UInt32(ptr) + Length(self)); while UInt32(ptr) < hiptr do if not (ptr^ in ['A'..'Z', 'a'..'z']) then Exit(False) else Inc(ptr); Result := True; end; function Char.IsAlpha(): Boolean; begin Result := (Self in ['A'..'Z', 'a'..'z']); end; {!DOCREF} { @method: function String.IsDigit(): Boolean; @desc: Return true if all characters in the string are digits and there is at least one character, false otherwise. } function String.IsDigit(): Boolean; var ptr: PChar; hiptr:UInt32; begin if Length(Self) = 0 then Exit(False); ptr := PChar(Self); hiptr := UInt32(UInt32(ptr) + Length(self)); while UInt32(ptr) < hiptr do if not (ptr^ in ['0'..'9']) then Exit(False) else Inc(ptr); Result := True; end; function Char.IsDigit(): Boolean; begin Result := (Self in ['0'..'9']); end; {!DOCREF} { @method: function String.IsFloat(): Boolean; @desc: Return true if all characters in the string are digits + "." and there is at least one character, false otherwise. } function String.IsFloat(): Boolean; var ptr: PChar; hiptr:UInt32; i:Int32; dotAdded:Boolean; begin if Length(Self) = 0 then Exit(False); ptr := PChar(Self); i:=0; hiptr := UInt32(UInt32(ptr) + Length(self)); while UInt32(ptr) < hiptr do if not (ptr^ in ['0'..'9']) then if (i >= 1) and (ptr^ = '.') and not(dotAdded) then begin Inc(ptr); inc(i); dotAdded:=True; end else Exit(False) else begin Inc(ptr); inc(i); end; Result := True; end; function Char.IsFloat(): Boolean; begin Result := String(Self).IsFloat(); end; {!DOCREF} { @method: function String.GetNumbers(): TIntArray; @desc: Returns all the numbers in the string, does not handle floating point numbers } function String.GetNumbers(): TIntArray; var i,j,l:Int32; NextNum: Boolean; Num: String; begin j := 0; num := ''; L := Length(Self); for i:=1 to L do if Self[i].IsDigit() then begin NextNum := False; if ( i+1 <= L ) then NextNum := Self[i+1].IsDigit(); Num := Num + Self[i]; if not(NextNum) then begin SetLength(Result, j+1); Result[j] := StrToInt(num); inc(j); num := ''; end; end; end; {!DOCREF} { @method: function String.SplitNum(): TStringArray; @desc: Splits the text in to sentances, and numbers, result will EG be: `['My number is', '123', 'sometimes its', '7.5']` } function String.SplitNum(): TStringArray; var i,j,l:Int32; begin L := Length(Self); Self := Self + #0#0; SetLength(Result, 1); j := 0; i := 1; while i <= L do begin if Self[i].IsDigit() then begin Result[j] := Result[j] + Self[i]; inc(i); while (Self[i].IsDigit()) or ((Self[i] = '.') and (Self[i+1].IsDigit())) do begin Result[j] := Result[j] + Self[i]; inc(i); if (i > L) then break; end; if (i > L) then break; SetLength(Result, length(Result)+1); inc(j); end else begin if (Result[j] = '') and (Self[i] = ' ') then begin inc(i) if Self[i].IsDigit() then continue; end; if not(Self[i+1].IsDigit() and (Self[i] = ' ')) then Result[j] := Result[j] + Self[i]; if Self[i+1].IsDigit() then begin SetLength(Result, length(Result)+1); inc(j); end; end; inc(i); end; SetLength(Self, L); end;
unit ex_rx_datapacket; {$mode objfpc}{$H+} interface uses Classes, SysUtils,db; type TRowStateValue = (rsvOriginal, rsvDeleted, rsvInserted, rsvUpdated, rsvDetailUpdates); TRowState = set of TRowStateValue; type TRxDataPacketFormat = (dfBinary,dfXML,dfXMLUTF8,dfAny); type { TRxDatapacketReader } TRxDatapacketReaderClass = class of TRxDatapacketReader; TRxDatapacketReader = class(TObject) FStream : TStream; protected class function RowStateToByte(const ARowState : TRowState) : byte; class function ByteToRowState(const AByte : Byte) : TRowState; public constructor create(AStream : TStream); virtual; // Load a dataset from stream: // Load the field-definitions from a stream. procedure LoadFieldDefs(AFieldDefs : TFieldDefs); virtual; abstract; // Is called before the records are loaded procedure InitLoadRecords; virtual; abstract; // Return the RowState of the current record, and the order of the update function GetRecordRowState(out AUpdOrder : Integer) : TRowState; virtual; abstract; // Returns if there is at least one more record available in the stream function GetCurrentRecord : boolean; virtual; abstract; // Store a record from stream in the current record-buffer procedure RestoreRecord(ADataset : TDataset); virtual; abstract; // Move the stream to the next record procedure GotoNextRecord; virtual; abstract; // Store a dataset to stream: // Save the field-definitions to a stream. procedure StoreFieldDefs(AFieldDefs : TFieldDefs); virtual; abstract; // Save a record from the current record-buffer to the stream procedure StoreRecord(ADataset : TDataset; ARowState : TRowState; AUpdOrder : integer = 0); virtual; abstract; // Is called after all records are stored procedure FinalizeStoreRecords; virtual; abstract; // Checks if the provided stream is of the right format for this class class function RecognizeStream(AStream : TStream) : boolean; virtual; abstract; property Stream: TStream read FStream; end; type TRxDatapacketReaderRegistration = record ReaderClass : TRxDatapacketReaderClass; Format : TRxDatapacketFormat; end; function GetRegisterDatapacketReader(AStream : TStream; AFormat : TRxDatapacketFormat; var ADataReaderClass : TRxDatapacketReaderRegistration) : boolean; procedure RegisterDatapacketReader(ADatapacketReaderClass : TRxDatapacketReaderClass; AFormat : TRxDatapacketFormat); implementation var RxRegisteredDatapacketReaders : Array of TRxDatapacketReaderRegistration; function GetRegisterDatapacketReader(AStream: TStream; AFormat: TRxDatapacketFormat; var ADataReaderClass: TRxDatapacketReaderRegistration): boolean; var i : integer; begin Result := False; for i := 0 to length(RxRegisteredDatapacketReaders)-1 do if ((AFormat=dfAny) or (AFormat=RxRegisteredDatapacketReaders[i].Format)) then begin if (AStream <> nil) then AStream.Seek(0,soFromBeginning); // ensure at start of stream to check value if (AStream=nil) or (RxRegisteredDatapacketReaders[i].ReaderClass.RecognizeStream(AStream)) then begin ADataReaderClass := RxRegisteredDatapacketReaders[i]; Result := True; if (AStream <> nil) then AStream.Seek(0,soFromBeginning); break; end; end; end; procedure RegisterDatapacketReader( ADatapacketReaderClass: TRxDatapacketReaderClass; AFormat: TRxDatapacketFormat ); begin setlength(RxRegisteredDatapacketReaders,length(RxRegisteredDatapacketReaders)+1); with RxRegisteredDatapacketReaders[length(RxRegisteredDatapacketReaders)-1] do begin Readerclass := ADatapacketReaderClass; Format := AFormat; end; end; { TRxDatapacketReader } class function TRxDatapacketReader.RowStateToByte(const ARowState: TRowState ): byte; var RowStateInt : Byte; begin RowStateInt:=0; if rsvOriginal in ARowState then RowStateInt := RowStateInt+1; if rsvDeleted in ARowState then RowStateInt := RowStateInt+2; if rsvInserted in ARowState then RowStateInt := RowStateInt+4; if rsvUpdated in ARowState then RowStateInt := RowStateInt+8; Result := RowStateInt; end; class function TRxDatapacketReader.ByteToRowState(const AByte: Byte ): TRowState; begin result := []; if (AByte and 1)=1 then Result := Result+[rsvOriginal]; if (AByte and 2)=2 then Result := Result+[rsvDeleted]; if (AByte and 4)=4 then Result := Result+[rsvInserted]; if (AByte and 8)=8 then Result := Result+[rsvUpdated]; end; constructor TRxDatapacketReader.create(AStream: TStream); begin FStream := AStream; end; initialization setlength(RxRegisteredDatapacketReaders,0); finalization setlength(RxRegisteredDatapacketReaders,0); end.
unit AddAddressNoteResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, AddressNoteUnit; type TAddAddressNoteResponse = class(TGenericParameters) private [JSONName('status')] FStatus: boolean; [JSONName('note')] FNote: TAddressNote; public property Status: boolean read FStatus write FStatus; property Note: TAddressNote read FNote write FNote; end; implementation end.
unit TestuProtoBufGenerator; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.SysUtils, uProtoBufParserClasses, uAbstractProtoBufClasses, uProtoBufParserAbstractClasses, System.Classes, uProtoBufGenerator; type // Test methods for class TProtoBufGenerator TestTProtoBufGenerator = class(TTestCase) strict private FProtoBufGenerator: TProtoBufGenerator; public procedure SetUp; override; procedure TearDown; override; published procedure TestGenerate; procedure TestGenerateMsgWithBytes; end; implementation uses pbInput, pbOutput; procedure TestTProtoBufGenerator.SetUp; begin FProtoBufGenerator := TProtoBufGenerator.Create; end; procedure TestTProtoBufGenerator.TearDown; begin FProtoBufGenerator.Free; FProtoBufGenerator := nil; end; procedure TestTProtoBufGenerator.TestGenerate; var OutputDir: string; Proto: TProtoFile; iPos: Integer; sProto: string; begin Proto := TProtoFile.Create(nil); try iPos := 1; sProto := '// * Bytes type e.g. optional bytes DefField10 = 10 [default = "123"];'#13#10 + // #13#10 + // 'package test1;'#13#10 + // #13#10 + // //'import "TestImport1.proto";'#13#10 + // //#13#10 + // '// enumeration'#13#10 + // 'enum EnumG0 {'#13#10 + // ' // enum value 1'#13#10+ 'g1 = 1;'#13#10 + // 'g2 = 2;'#13#10 + // '}'#13#10; sProto:=sProto + 'message TestMsg1 {' + #13#10 + '' + #13#10 + '// fields with defaults' + #13#10 + 'optional int32 DefField1 = 1 [default = 2];' + #13#10 + 'required int64 DefField2 = 2 [default = -1];' + #13#10 + 'optional string DefField3 = 3 [default = "yes ''""it is"];' + #13#10 + 'optional double DefField4 = 4 [default = 1.1];' + #13#10 + 'optional bool DefField5 = 5 [default = true];' + #13#10 + 'optional EnumG0 DefField6 = 6 [default = g2];' + #13#10 + 'optional sint64 DefField7 = 7 [default = 100];' + #13#10 + 'optional fixed32 DefField8 = 8 [default = 1];' + #13#10 + 'optional float DefField9 = 9 [default = 1.23e1];' + #13#10 + '' + #13#10 + 'message NestedMsg0 { '#13#10+ ' optional int32 NestedField1 = 1; }'+ '// field of message type' + #13#10 + 'optional TestMsg0 FieldMsg1 = 20;' + #13#10 + '' + #13#10 + '// repeated fields' + #13#10 + 'repeated int32 FieldArr1 = 40;' + #13#10 + 'repeated int32 FieldArr2 = 41 [packed = true];' + #13#10 + 'repeated string FieldArr3 = 42;' + #13#10 + 'repeated NestedMsg0 FieldMArr2 = 44;' + #13#10 + '' + #13#10 + '// fields of imported types' + #13#10 + '' + #13#10 + '// extensions 1000 to 1999;' + #13#10 + '}'; sProto:=sProto +// 'message TestMsg0 {}'#13#10; OutputDir:=ExtractFilePath(ParamStr(0)); Proto.ParseFromProto(sProto, iPos); FProtoBufGenerator.Generate(Proto, OutputDir); // TODO: Validate method results finally Proto.Free; end; end; procedure TestTProtoBufGenerator.TestGenerateMsgWithBytes; var OutputDir: string; Proto: TProtoFile; iPos: Integer; sProto: string; begin // TODO: Setup method call parameters Proto := TProtoFile.Create(nil); try iPos := 1; sProto := '// * Bytes type e.g. optional bytes DefField10 = 10 [default = "123"];'#13#10 + // #13#10 + // 'package test2;'#13#10 + // #13#10 + // //'import "TestImport1.proto";'#13#10 + // //#13#10 + // '// enumeration'#13#10 + // 'enum EnumG0 {'#13#10 + // ' // enum value 1'#13#10+ 'g1 = 1;'#13#10 + // 'g2 = 2;'#13#10 + // '}'#13#10; sProto:=sProto + 'message TestMsg1 {' + #13#10 + '' + #13#10 + '// fields with defaults' + #13#10 + 'optional int32 DefField1 = 1 [default = 2];' + #13#10 + 'required int64 DefField2 = 2 [default = -1];' + #13#10 + 'optional string DefField3 = 3 [default = "yes ""it is"];' + #13#10 + 'optional double DefField4 = 4 [default = 1.1];' + #13#10 + 'optional bool DefField5 = 5 [default = true];' + #13#10 + 'optional EnumG0 DefField6 = 6 [default = g2];' + #13#10 + 'optional sint64 DefField7 = 7 [default = 100];' + #13#10 + 'optional fixed32 DefField8 = 8 [default = 1];' + #13#10 + 'optional float DefField9 = 9 [default = 1.23e1];' + #13#10 + 'optional bytes DefField10 = 10;' + #13#10 + '' + #13#10 + 'message NestedMsg0 { '#13#10+ ' optional int32 NestedField1 = 1; }'+ '// field of message type' + #13#10 + 'optional TestMsg0 FieldMsg1 = 20;' + #13#10 + '' + #13#10 + '// repeated fields' + #13#10 + 'repeated int32 FieldArr1 = 40;' + #13#10 + 'repeated int32 FieldArr2 = 41 [packed = true];' + #13#10 + 'repeated string FieldArr3 = 42;' + #13#10 + 'repeated NestedMsg0 FieldMArr2 = 44;' + #13#10 + '' + #13#10 + '// fields of imported types' + #13#10 + '' + #13#10 + '// extensions 1000 to 1999;' + #13#10 + '}'; sProto:=sProto +// 'message TestMsg0 {}'#13#10; OutputDir:=ExtractFilePath(ParamStr(0)); Proto.ParseFromProto(sProto, iPos); FProtoBufGenerator.Generate(Proto, OutputDir); // TODO: Validate method results finally Proto.Free; end; end; initialization // Register any test cases with the test runner RegisterTest(TestTProtoBufGenerator.Suite); 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 ClpConstructedOctetStream; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpCryptoLibTypes, ClpBaseInputStream, ClpIAsn1OctetStringParser, ClpIAsn1StreamParser; type TConstructedOctetStream = class(TBaseInputStream) strict private var F_parser: IAsn1StreamParser; F_first: Boolean; F_currentStream: TStream; public constructor Create(const parser: IAsn1StreamParser); function Read(buffer: TCryptoLibByteArray; offset, count: LongInt) : LongInt; override; function ReadByte(): Int32; override; end; implementation uses ClpStreamSorter; // included here to avoid circular dependency :) { TConstructedOctetStream } constructor TConstructedOctetStream.Create(const parser: IAsn1StreamParser); begin Inherited Create(); F_parser := parser; F_first := true; end; function TConstructedOctetStream.Read(buffer: TCryptoLibByteArray; offset, count: LongInt): LongInt; var s, aos: IAsn1OctetStringParser; totalRead, numRead: Int32; begin if (F_currentStream = Nil) then begin if (not F_first) then begin result := 0; Exit; end; if (not Supports(F_parser.ReadObject(), IAsn1OctetStringParser, s)) then begin result := 0; Exit; end; F_first := false; F_currentStream := s.GetOctetStream(); end; totalRead := 0; while true do begin numRead := TStreamSorter.Read(F_currentStream, buffer, offset + totalRead, count - totalRead); if (numRead > 0) then begin totalRead := totalRead + numRead; if (totalRead = count) then begin result := totalRead; Exit; end; end else begin if (not Supports(F_parser.ReadObject(), IAsn1OctetStringParser, aos)) then begin F_currentStream := Nil; result := totalRead; Exit; end; F_currentStream := aos.GetOctetStream(); end end; result := 0; end; function TConstructedOctetStream.ReadByte: Int32; var s, aos: IAsn1OctetStringParser; b: Int32; begin if (F_currentStream = Nil) then begin if (not F_first) then begin result := 0; Exit; end; if (not Supports(F_parser.ReadObject(), IAsn1OctetStringParser, s)) then begin result := 0; Exit; end; F_first := false; F_currentStream := s.GetOctetStream(); end; while true do begin // b := F_currentStream.ReadByte(); b := TStreamSorter.ReadByte(F_currentStream); if (b >= 0) then begin result := b; Exit; end; if (not Supports(F_parser.ReadObject(), IAsn1OctetStringParser, aos)) then begin F_currentStream := Nil; result := -1; Exit; end; F_currentStream := aos.GetOctetStream(); end; result := 0; end; end.
unit Script.WordsInterfaces; interface uses System.Generics.Collections, Core.Obj, Script.Interfaces ; type TscriptValueType = (script_vtUnknown, script_vtString, script_vtObject); TscriptValue = record public rValueType : TscriptValueType; private rAsString : String; rAsObject : TObject; public constructor Create(const aString: String); overload; constructor Create(anObject: TObject); overload; function AsString: String; function AsObject: TObject; end;//TscriptValue TscriptValuesStack = TList<TscriptValue>; TscriptContext = class(TCoreObject) private f_Log : IscriptLog; f_Stack : TscriptValuesStack; protected procedure Cleanup; override; public constructor Create(const aLog: IscriptLog); procedure Log(const aString: String); {* - Выводит сообщение в лог. } function PopString: String; procedure PushString(const aString: String); function PopObject: TObject; procedure PushObject(const anObject: TObject); end;//TscriptContext IscriptCompiler = interface; TscriptCompileContext = class(TscriptContext) private f_Parser : IscriptParser; f_Compiler : IscriptCompiler; protected procedure Cleanup; override; public constructor Create(const aLog : IscriptCompileLog; const aParser : IscriptParser; const aCompiler : IscriptCompiler); property Parser: IscriptParser read f_Parser; property Compiler: IscriptCompiler read f_Compiler; end;//TscriptCompileContext TscriptRunContext = class(TscriptContext) public constructor Create(const aLog: IscriptRunLog); end;//TscriptRunContext IscriptWord = interface {* - слово скриптовой машины. } procedure DoIt(aContext: TscriptContext); {* - собственно процедура для выполнения слова словаря. } end;//IscriptWord IscriptCode = interface {* - компилированный код скриптовой машины. } procedure Run(aContext : TscriptRunContext); {* - выполняет компилированный код. } end;//IscriptCode IscriptCompiler = interface {* - компилятор кода скриптовой машины. } procedure CompileWord(const aWord: IscriptWord); {* - компилирует указанное слово в код. } function CompiledCode: IscriptCode; {* - скомпилированный код } end;//IscriptCompiler implementation uses System.SysUtils ; // TscriptValue constructor TscriptValue.Create(const aString: String); begin inherited; rValueType := script_vtString; rAsString := aString; end; constructor TscriptValue.Create(anObject: TObject); begin inherited; rValueType := script_vtObject; rAsObject := anObject; end; function TscriptValue.AsString: String; begin Assert(rValueType = script_vtString); Result := rAsString; end; function TscriptValue.AsObject: TObject; begin Assert(rValueType = script_vtObject); Result := rAsObject; end; // TscriptContext constructor TscriptContext.Create(const aLog: IscriptLog); begin inherited Create; f_Log := aLog; f_Stack := TscriptValuesStack.Create; end; procedure TscriptContext.Log(const aString: String); {* - Выводит сообщение в лог. } begin if (f_Log <> nil) then f_Log.Log(aString); end; function TscriptContext.PopString: String; begin Assert(f_Stack.Count > 0); Result := f_Stack.Last.AsString; f_Stack.Delete(f_Stack.Count - 1); end; procedure TscriptContext.PushString(const aString: String); begin f_Stack.Add(TscriptValue.Create(aString)); end; function TscriptContext.PopObject: TObject; begin Assert(f_Stack.Count > 0); Result := f_Stack.Last.AsObject; f_Stack.Delete(f_Stack.Count - 1); end; procedure TscriptContext.PushObject(const anObject: TObject); begin f_Stack.Add(TscriptValue.Create(anObject)); end; procedure TscriptContext.Cleanup; begin f_Log := nil; FreeAndNil(f_Stack); inherited; end; // TscriptCompileContext constructor TscriptCompileContext.Create(const aLog : IscriptCompileLog; const aParser : IscriptParser; const aCompiler : IscriptCompiler); begin Assert(aParser <> nil); Assert(aCompiler <> nil); inherited Create(aLog); f_Parser := aParser; f_Compiler := aCompiler; end; procedure TscriptCompileContext.Cleanup; begin f_Parser := nil; f_Compiler := nil; inherited; end; // TscriptRunContext constructor TscriptRunContext.Create(const aLog: IscriptRunLog); begin inherited Create(aLog); end; end.
unit GetActivitiesQueryUnit; interface uses HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, EnumsUnit; type TGetActivitiesQuery = class(TGenericParameters) private [HttpQueryMember('route_id')] [Nullable] FRouteId: NullableString; [HttpQueryMember('limit')] [Nullable] FLimit: NullableInteger; [HttpQueryMember('offset')] [Nullable] FOffset: NullableInteger; [HttpQueryMember('activity_type')] FActivityType: String; public constructor Create; overload; override; constructor Create(ActivityType: TActivityType); reintroduce; overload; constructor Create(ActivityType: TActivityType; Limit, Offset: integer); reintroduce; overload; constructor Create(ActivityType: TActivityType; RouteId: String; Limit, Offset: integer); reintroduce; overload; end; implementation constructor TGetActivitiesQuery.Create; begin Inherited Create; FRouteId := NullableString.Null; FLimit := NullableInteger.Null; FOffset := NullableInteger.Null; FActivityType := ''; end; constructor TGetActivitiesQuery.Create(ActivityType: TActivityType); begin Create(); FActivityType := TActivityTypeDescription[ActivityType]; end; constructor TGetActivitiesQuery.Create(ActivityType: TActivityType; Limit, Offset: integer); begin Create(ActivityType); FLimit := Limit; FOffset := Offset; end; constructor TGetActivitiesQuery.Create(ActivityType: TActivityType; RouteId: String; Limit, Offset: integer); begin Create(ActivityType, Limit, Offset); FRouteId := RouteId; end; end.
(* Base class for all loaders. Each loader handles one file type. *) unit ae3DModelLoaderBase; interface uses windows, types, System.Generics.Collections, aeGeometry, sysutils; Type TaeLoaderFiletype = (AE_LOADER_FILETYPE_3DS, AE_LOADER_FILETYPE_AIONCGF); type Tae3DModelLoaderBase = class public Constructor Create; function loadFromFile(file_name: string; var geo: TaeGeometry): boolean; virtual; abstract; function getHandledFileExtension: string; function getLoaderType: TaeLoaderFiletype; private _fileExtension: string; protected _fileType: TaeLoaderFiletype; procedure setHandledFileExtension(extension: string); end; implementation { TaeLoaderBase } constructor Tae3DModelLoaderBase.Create; begin self._fileExtension := ''; end; function Tae3DModelLoaderBase.getHandledFileExtension: string; begin result := self._fileExtension; end; function Tae3DModelLoaderBase.getLoaderType: TaeLoaderFiletype; begin result := self._fileType; end; procedure Tae3DModelLoaderBase.setHandledFileExtension(extension: string); begin self._fileExtension := lowercase(extension); end; end.
unit mod_testhttp; {$mode delphi} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, browsermodules, browserconfig; type { TformTestHttp } TformTestHttp = class(TForm) buttonHttpTest: TButton; checkProxy: TCheckBox; comboRequest: TComboBox; comboUserAgent: TComboBox; comboURL: TComboBox; editProxy: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; memoTestHttpDebug: TMemo; procedure buttonHttpTestClick(Sender: TObject); private { private declarations } public { public declarations } end; { TTestHttpBrowserModule } TTestHttpBrowserModule = class(TBrowserModule) public constructor Create; override; function GetModuleUIElements(): TBrowserModuleUIElements; override; // For expansions function GetCommandCount: Integer; override; function GetCommandName(AID: Integer): string; override; procedure ExecuteCommand(AID: Integer); override; end; var formTestHttp: TformTestHttp; implementation uses httpsend; { TformTestHttp } procedure TformTestHttp.buttonHttpTestClick(Sender: TObject); var Client: THttpSend; ContentsList: TStringList; AURL: string; begin AURL := comboURL.Text; Client := THttpSend.Create; ContentsList := TStringList.Create; try // Preparation of headers and proxy Client.Headers.Add('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'); Client.Headers.Add('Accept-Language: en-gb,en;q=0.5'); //Client.Headers.Add('Accept-Encoding: gzip,deflate'); Client.Headers.Add('Accept-Charset: utf-8;q=0.7,*;q=0.7'); // ISO-8859-1, Client.UserAgent := comboUserAgent.Text; if checkProxy.Checked then begin Client.ProxyHost := editProxy.Text; Client.ProxyPort := '80'; end; // Make the syncronous request via Synapse Client.HttpMethod(comboRequest.Text, AURL); Client.Document.Position := 0; ContentsList.Clear(); ContentsList.LoadFromStream(Client.Document); memoTestHttpDebug.Clear(); memoTestHttpDebug.Lines.Add(Format('Requesting HTTP %s to: %s', [comboRequest.Text, AURL])); memoTestHttpDebug.Lines.Add(''); memoTestHttpDebug.Lines.Add('HTTP Headers:'); memoTestHttpDebug.Lines.Add(''); memoTestHttpDebug.Lines.AddStrings(Client.Headers); memoTestHttpDebug.Lines.Add(''); finally ContentsList.Free; Client.Free; end; end; { TTestHttpBrowserModule } constructor TTestHttpBrowserModule.Create; begin inherited Create; ShortDescription := 'HTTP Test'; end; function TTestHttpBrowserModule.GetModuleUIElements: TBrowserModuleUIElements; begin Result := [bmueCommandsSubmenu]; end; function TTestHttpBrowserModule.GetCommandCount: Integer; begin Result := 1; end; function TTestHttpBrowserModule.GetCommandName(AID: Integer): string; begin Result := 'HTTP Test Dialog'; end; procedure TTestHttpBrowserModule.ExecuteCommand(AID: Integer); begin formTestHttp.ShowModal(); end; initialization {$I mod_testhttp.lrs} RegisterBrowserModule(TTestHttpBrowserModule.Create()); end.
unit task_1; { TBook--------- | | TBook | TMagazine } interface { Базовый класс для товаров } type TGoods=class private fName: String; fPrice: Integer; fDescription: String; procedure set_name(_name: String); procedure set_price(_price: Integer); procedure set_description(_description: String); function get_name: String; function get_price: Integer; function get_description: String; public { Запись данных о товаре в файл} procedure write_on_file(fPath: String); overload; { Конвертирование в строку} function stringfy: String; Virtual; { Преобразуем в строковое представление JSON объекта} function to_json_string: String; Virtual; property Name: String read get_name write set_name; property Price: Integer read get_price write set_price; property Description: String read get_description write set_description; constructor __init__(_name: String; _price: Integer; _description: String); overload; virtual; constructor __init__(_name: String; _price: Integer); overload; virtual; end; { Товар.Книга } type TBook=class(TGoods) private fAuthor: String; procedure set_author(_author: String); function get_author: String; public constructor __init__(_name: String; _price: Integer; _author: String; _description: String); overload; constructor __init__(_name: String; _price: Integer; _author: String); overload; property Author: String read get_author write set_author; function stringfy: String; end; { Товар.Журнал } type TMagazine=class(TGoods) private fNumber: Integer; // Номер журнала procedure set_number(_number: Integer); function get_number: Integer; public constructor __init__(_name: String; _price: Integer; _number: Integer; _description: String); overload; constructor __init__(_name: String; _price: Integer; _number: Integer); overload; property Number: Integer read get_number write set_number; function stringfy: String; end; implementation uses SysUtils; { TGoods } { Конструктор } constructor TGoods.__init__(_name: string; _price: Integer; _description: string); begin self.Name := _name; self.Price := _price; self.Description := _description; end; constructor TGoods.__init__(_name: string; _price: Integer); begin self.Name := _name; self.Price := _price; self.Description := 'No description'; end; { Управление свойством Name } procedure TGoods.set_name(_name: string); begin if Length(_name) = 0 then raise Exception.Create('Goods name must be bigger than 0.'); self.fName := _name; end; function TGoods.get_name; begin result := self.fName; end; { Управление свойством Price } procedure TGoods.set_price(_price: Integer); begin if _price < 0 then raise Exception.Create('Price must be -le or -eq 0.'); self.fPrice := _price; end; function TGoods.get_price; begin result := self.fPrice; end; { Управление свойством Description } procedure TGoods.set_description(_description: string); begin if Length(_description) = 0 then begin self.fDescription := 'No description'; end else begin self.fDescription := _description; end; end; function TGoods.get_description; begin result := self.fDescription; end; { Функции } function TGoods.stringfy; begin result := '"name": "' + self.fName + '",' + ^M + ^J + '"price": ' + IntToStr(self.fPrice) + ',' + ^M + ^J + '"description": "' + self.fDescription + '"'; end; function TGoods.to_json_string; begin result := '{' + ^M + ^J + self.stringfy + ^M + ^J + '}'; end; { Процедуры } procedure TGoods.write_on_file(fPath: string); var tFile: TextFile; begin if FileExists(fPath) then raise Exception.Create('File :"' + fPath + '", is exists.'); AssignFile(tFile, fPath); write(tFile, self.to_json_string); CloseFile(tFile); end; { TGoods.TBook} { конструктор } constructor TBook.__init__(_name: string; _price: Integer; _author: string; _description: string); begin inherited __init__(_name, _price, _description); self.fAuthor := _author; end; constructor TBook.__init__(_name: string; _price: Integer; _author: string); begin inherited __init__(_name, _price); self.Author := _author; end; { Управление свойством Author } procedure TBook.set_author(_author: string); begin if Length(_author) = 0 then raise Exception.Create('Book author -eq null!'); self.fAuthor := _author; end; function TBook.get_author; begin result := self.fAuthor; end; {Функции} function TBook.stringfy; begin result := inherited stringfy + ',' + '"author": "' + self.Author + '"' +^M + ^J; end; { TGoods.TMagazine } { конструктор } constructor TMagazine.__init__(_name: string; _price: Integer; _number: Integer; _description: string); begin inherited __init__(_name, _price, _description); self.Number := _number; end; constructor TMagazine.__init__(_name: string; _price: Integer; _number: Integer); begin inherited __init__(_name, _price); self.Number := _number; end; { Управление свойством Number } procedure TMagazine.set_number(_number: Integer); begin if _number < 0 then raise Exception.Create('Nummber must be bigger then -1'); self.fNumber := _number; end; function TMagazine.get_number; begin result := self.fNumber; end; {Функции} function TMagazine.stringfy; begin result := inherited stringfy + ',' + '"number": "' + IntToStr(self.Number) + '"' +^M + ^J; end; end.
unit MultipleDepotMultipleDriverTimeWindowUnit; interface uses SysUtils, DataObjectUnit, BaseOptimizationExampleUnit; type TMultipleDepotMultipleDriverTimeWindow = class(TBaseOptimizationExample) public function Execute: TDataObject; end; implementation uses IOptimizationParametersProviderUnit, OptimizationParametersUnit, MultipleDepotMultipleDriverTimeWindowTestDataProviderUnit; function TMultipleDepotMultipleDriverTimeWindow.Execute: TDataObject; var DataProvider: IOptimizationParametersProvider; ErrorString: String; Parameters: TOptimizationParameters; begin DataProvider := TMultipleDepotMultipleDriverTimeWindowTestDataProvider.Create; Parameters := DataProvider.OptimizationParameters; try Result := Route4MeManager.Optimization.Run(Parameters, ErrorString); finally FreeAndNil(Parameters); end; PrintExampleOptimizationResult( 'MultipleDepotMultipleDriverTimeWindow', Result, ErrorString); end; end.
unit EnumClasses.TDataType; interface type TDataType = record const dtBoolean = 'Boolean'; dtCurrency = 'Currency'; dtDateTime = 'DateTime'; dtInteger = 'Integer'; dtNumeric = 'Numeric'; dtString = 'String'; end; implementation end.
unit CallerForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ConvertIntf, SoapHTTPClient, InvokeRegistry; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; EditAmount: TEdit; ComboBoxFrom: TComboBox; ComboBoxTo: TComboBox; LabelResult: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); private Invoker: THTTPRio; ConvIntf: IConvert; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin LabelResult.Caption := Format ('%n', [(ConvIntf.ConvertCurrency( ComboBoxFrom.Text, ComboBoxTo.Text, StrToFloat (EditAmount.Text)))]); end; procedure TForm1.FormCreate(Sender: TObject); begin Invoker := THTTPRio.Create(nil); Invoker.URL := 'http://localhost/scripts/ConvertService.exe/soap/iconvert'; ConvIntf := Invoker as IConvert; end; procedure TForm1.Button2Click(Sender: TObject); var TypeNames: string; begin TypeNames := ConvIntf.TypesList; ComboBoxFrom.Items.Text := StringReplace (TypeNames, ';', sLineBreak, [rfReplaceAll]); ComboBoxTo.Items := ComboBoxFrom.Items; end; end.
unit Uninstall; { Inno Setup Copyright (C) 1997-2012 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Uninstaller NOTE: This unit was derived from Uninst.dpr rev 1.38. } interface procedure RunUninstaller; procedure HandleUninstallerEndSession; implementation uses Windows, SysUtils, Messages, Forms, PathFunc, CmnFunc, CmnFunc2, Undo, Msgs, MsgIDs, InstFunc, Struct, SetupEnt, UninstProgressForm, UninstSharedFileForm, FileClass, ScriptRunner, DebugClient, SetupTypes, Logging, Main, Helper, SpawnServer; type TExtUninstallLog = class(TUninstallLog) private FLastUpdateTime: DWORD; FNoSharedFileDlgs: Boolean; FRemoveSharedFiles: Boolean; protected procedure HandleException; override; function ShouldRemoveSharedFile(const Filename: String): Boolean; override; procedure StatusUpdate(StartingCount, CurCount: Integer); override; end; const WM_KillFirstPhase = WM_USER + 333; var UninstallExitCode: DWORD = 1; UninstExeFile, UninstDataFile, UninstMsgFile: String; UninstLogFile: TFile; UninstLog: TExtUninstallLog = nil; Title: String; DidRespawn, SecondPhase: Boolean; EnableLogging, Silent, VerySilent, NoRestart: Boolean; LogFilename: String; InitialProcessWnd, FirstPhaseWnd, DebugWnd: HWND; OldWindowProc: Pointer; {$IFNDEF UNICODE} UninstLeadBytes: set of Char; {$ENDIF} procedure ShowExceptionMsg; var Msg: String; begin if ExceptObject is EAbort then Exit; Msg := GetExceptMessage; Log('Exception message:'); LoggedAppMessageBox(PChar(Msg), Pointer(SetupMessages[msgErrorTitle]), MB_OK or MB_ICONSTOP, True, IDOK); { ^ use a Pointer cast instead of a PChar cast so that it will use "nil" if SetupMessages[msgErrorTitle] is empty due to the messages not being loaded yet. MessageBox displays 'Error' as the caption if the lpCaption parameter is nil. } end; procedure TExtUninstallLog.HandleException; begin ShowExceptionMsg; end; function TExtUninstallLog.ShouldRemoveSharedFile(const Filename: String): Boolean; const SToAll: array[Boolean] of String = ('', ' to All'); begin if Silent or VerySilent then Result := True else begin if not FNoSharedFileDlgs then begin { FNoSharedFileDlgs will be set to True if a "...to All" button is clicked } FRemoveSharedFiles := ExecuteRemoveSharedFileDlg(Filename, FNoSharedFileDlgs); LogFmt('Remove shared file %s? User chose %s%s', [Filename, SYesNo[FRemoveSharedFiles], SToAll[FNoSharedFileDlgs]]); end; Result := FRemoveSharedFiles; end; end; procedure InitializeUninstallProgressForm; begin UninstallProgressForm := TUninstallProgressForm.Create(nil); UninstallProgressForm.Initialize(Title, UninstLog.AppName); if CodeRunner <> nil then begin try CodeRunner.RunProcedure('InitializeUninstallProgressForm', [''], False); except Log('InitializeUninstallProgressForm raised an exception (fatal).'); raise; end; end; if not VerySilent then begin UninstallProgressForm.Show; { Ensure the form is fully painted now in case CurUninstallStepChanged(usUninstall) take a long time to return } UninstallProgressForm.Update; end; end; procedure TExtUninstallLog.StatusUpdate(StartingCount, CurCount: Integer); var NowTime: DWORD; begin { Only update the progress bar if it's at the beginning or end, or if 30 ms has passed since the last update (so that updating the progress bar doesn't slow down the actual uninstallation process). } NowTime := GetTickCount; if (Cardinal(NowTime - FLastUpdateTime) >= Cardinal(30)) or (StartingCount = CurCount) or (CurCount = 0) then begin FLastUpdateTime := NowTime; UninstallProgressForm.UpdateProgress(StartingCount - CurCount, StartingCount); end; Application.ProcessMessages; end; function LoggedMessageBoxFmt1(const ID: TSetupMessageID; const Arg1: String; const Title: String; const Flags: UINT; const Suppressible: Boolean; const Default: Integer): Integer; begin Result := LoggedAppMessageBox(PChar(FmtSetupMessage1(ID, Arg1)), PChar(Title), Flags, Suppressible, Default); end; procedure RaiseLastError(const S: String); var ErrorCode: DWORD; begin ErrorCode := GetLastError; raise Exception.Create(FmtSetupMessage(msgLastErrorMessage, [S, IntToStr(ErrorCode), Win32ErrorString(ErrorCode)])); end; function Exec(const Filename: String; const Parms: String): THandle; var CmdLine: String; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin CmdLine := '"' + Filename + '" ' + Parms; FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); if not CreateProcess(nil, PChar(CmdLine), nil, nil, False, 0, nil, nil, StartupInfo, ProcessInfo) then RaiseLastError(SetupMessages[msgLdrCannotExecTemp]); CloseHandle(ProcessInfo.hThread); Result := ProcessInfo.hProcess; end; function ProcessMsgs: Boolean; var Msg: TMsg; begin Result := False; while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin if Msg.Message = WM_QUIT then begin Result := True; Break; end; TranslateMessage(Msg); DispatchMessage(Msg); end; end; function FirstPhaseWindowProc(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin Result := 0; case Msg of WM_QUERYENDSESSION: ; { Return zero to deny any shutdown requests } WM_KillFirstPhase: begin PostQuitMessage(0); { If we got WM_KillFirstPhase, the second phase must have been successful (up until now, at least). Set an exit code of 0. } UninstallExitCode := 0; end; else Result := CallWindowProc(OldWindowProc, Wnd, Msg, wParam, lParam); end; end; procedure DeleteUninstallDataFiles; var ProcessWnd: HWND; ProcessID: DWORD; Process: THandle; begin Log('Deleting Uninstall data files.'); { Truncate the .dat file to zero bytes just before relinquishing exclusive access to it } try UninstLogFile.Seek(0); UninstLogFile.Truncate; except { ignore any exceptions, just in case } end; FreeAndNil(UninstLogFile); { Delete the .dat and .msg files } DeleteFile(UninstDataFile); DeleteFile(UninstMsgFile); { Tell the first phase to terminate, then delete its .exe } if FirstPhaseWnd <> 0 then begin if InitialProcessWnd <> 0 then { If the first phase respawned, wait on the initial process } ProcessWnd := InitialProcessWnd else ProcessWnd := FirstPhaseWnd; ProcessID := 0; if GetWindowThreadProcessId(ProcessWnd, @ProcessID) <> 0 then Process := OpenProcess(SYNCHRONIZE, False, ProcessID) else Process := 0; { shouldn't get here } SendNotifyMessage(FirstPhaseWnd, WM_KillFirstPhase, 0, 0); if Process <> 0 then begin WaitForSingleObject(Process, INFINITE); CloseHandle(Process); end; { Sleep for a bit to allow pre-Windows 2000 Add/Remove Programs to finish bringing itself to the foreground before we take it back below. Also helps the DelayDeleteFile call succeed on the first try. } if not Debugging then Sleep(500); end; UninstallExitCode := 0; DelayDeleteFile(False, UninstExeFile, 13, 50, 250); if Debugging then DebugNotifyUninstExe(''); { Pre-Windows 2000 Add/Remove Programs will try to bring itself to the foreground after the first phase terminates. Take it back. } Application.BringToFront; end; procedure ProcessCommandLine; var WantToSuppressMsgBoxes: Boolean; I: Integer; ParamName, ParamValue: String; begin WantToSuppressMsgBoxes := False; for I := 1 to NewParamCount do begin SplitNewParamStr(I, ParamName, ParamValue); if CompareText(ParamName, '/Log') = 0 then begin EnableLogging := True; LogFilename := ''; end else if CompareText(ParamName, '/Log=') = 0 then begin EnableLogging := True; LogFilename := ParamValue; end else if CompareText(ParamName, '/INITPROCWND=') = 0 then begin DidRespawn := True; InitialProcessWnd := StrToInt(ParamValue); end else if CompareText(ParamName, '/SECONDPHASE=') = 0 then begin SecondPhase := True; UninstExeFile := ParamValue; end else if CompareText(ParamName, '/FIRSTPHASEWND=') = 0 then FirstPhaseWnd := StrToInt(ParamValue) else if CompareText(ParamName, '/SILENT') = 0 then Silent := True else if CompareText(ParamName, '/VERYSILENT') = 0 then VerySilent := True else if CompareText(ParamName, '/NoRestart') = 0 then NoRestart := True else if CompareText(ParamName, '/SuppressMsgBoxes') = 0 then WantToSuppressMsgBoxes := True else if CompareText(ParamName, '/DEBUGWND=') = 0 then DebugWnd := StrToInt(ParamValue); end; if WantToSuppressMsgBoxes and (Silent or VerySilent) then InitSuppressMsgBoxes := True; end; procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep; HandleException: Boolean); begin if CodeRunner <> nil then begin try CodeRunner.RunProcedure('CurUninstallStepChanged', [Ord(CurUninstallStep)], False); except if HandleException then begin Log('CurUninstallStepChanged raised an exception.'); ShowExceptionMsg; end else begin Log('CurUninstallStepChanged raised an exception (fatal).'); raise; end; end; end; end; function OpenUninstDataFile(const AAccess: TFileAccess): TFile; begin Result := nil; { avoid warning } try Result := TFile.Create(UninstDataFile, fdOpenExisting, AAccess, fsNone); except on E: EFileError do begin SetLastError(E.ErrorCode); RaiseLastError(FmtSetupMessage1(msgUninstallOpenError, UninstDataFile)); end; end; end; function RespawnFirstPhaseIfNeeded: Boolean; var F: TFile; Flags: TUninstallLogFlags; RequireAdmin: Boolean; begin Result := False; if DidRespawn then Exit; F := OpenUninstDataFile(faRead); try Flags := ReadUninstallLogFlags(F, UninstDataFile); finally F.Free; end; RequireAdmin := (ufAdminInstalled in Flags) or (ufPowerUserInstalled in Flags); if NeedToRespawnSelfElevated(RequireAdmin, False) then begin { Hide the taskbar button } SetWindowPos(Application.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_HIDEWINDOW); try RespawnSelfElevated(UninstExeFile, Format('/INITPROCWND=$%x ', [Application.Handle]) + GetCmdTail, UninstallExitCode); except { Re-show the taskbar button and re-raise } if not(ExceptObject is EAbort) then ShowWindow(Application.Handle, SW_SHOW); raise; end; Result := True; end; end; procedure RunFirstPhase; var TempFile: String; Wnd: HWND; ProcessHandle: THandle; begin { Copy self to TEMP directory with a name like _iu14D2N.tmp. The actual uninstallation process must be done from somewhere outside the application directory since EXE's can't delete themselves while they are running. } if not GenerateNonRandomUniqueFilename(GetTempDir, TempFile) then try RestartReplace(False, TempFile, ''); except { ignore exceptions } end; if not CopyFile(PChar(UninstExeFile), PChar(TempFile), False) then RaiseLastError(SetupMessages[msgLdrCannotCreateTemp]); { Don't want any attribute like read-only transferred } SetFileAttributes(PChar(TempFile), FILE_ATTRIBUTE_NORMAL); { Create first phase window. This window waits for a WM_KillFirstPhase message from the second phase process, and terminates itself in response. The reason the first phase doesn't just terminate immediately is because the Control Panel Add/Remove applet refreshes its list as soon as the program terminates. So it waits until the uninstallation is complete before terminating. } Wnd := CreateWindowEx(0, 'STATIC', '', 0, 0, 0, 0, 0, HWND_DESKTOP, 0, HInstance, nil); Longint(OldWindowProc) := SetWindowLong(Wnd, GWL_WNDPROC, Longint(@FirstPhaseWindowProc)); try { Hide the application window so that we don't end up with two taskbar buttons once the second phase starts } SetWindowPos(Application.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_HIDEWINDOW); { Execute the copy of itself ("second phase") } ProcessHandle := Exec(TempFile, Format('/SECONDPHASE="%s" /FIRSTPHASEWND=$%x ', [NewParamStr(0), Wnd]) + GetCmdTail); { Wait till the second phase process unexpectedly dies or is ready for the first phase to terminate. } repeat until ProcessMsgs or (MsgWaitForMultipleObjects(1, ProcessHandle, False, INFINITE, QS_ALLINPUT) <> WAIT_OBJECT_0+1); CloseHandle(ProcessHandle); finally DestroyWindow(Wnd); end; end; procedure AssignCustomMessages(AData: Pointer; ADataSize: Cardinal); procedure Corrupted; begin InternalError('Custom message data corrupted'); end; procedure Read(var Buf; const Count: Cardinal); begin if Count > ADataSize then Corrupted; Move(AData^, Buf, Count); Dec(ADataSize, Count); Inc(Cardinal(AData), Count); end; procedure ReadString(var S: String); var N: Integer; begin Read(N, SizeOf(N)); if (N < 0) or (N > $FFFFF) then { sanity check } Corrupted; SetString(S, nil, N); if N <> 0 then Read(Pointer(S)^, N * SizeOf(S[1])); end; var Count, I: Integer; CustomMessageEntry: PSetupCustomMessageEntry; begin Read(Count, SizeOf(Count)); Entries[seCustomMessage].Capacity := Count; for I := 0 to Count-1 do begin CustomMessageEntry := AllocMem(SizeOf(TSetupCustomMessageEntry)); try ReadString(CustomMessageEntry.Name); ReadString(CustomMessageEntry.Value); CustomMessageEntry.LangIndex := -1; except SEFreeRec(CustomMessageEntry, SetupCustomMessageEntryStrings, SetupCustomMessageEntryAnsiStrings); raise; end; Entries[seCustomMessage].Add(CustomMessageEntry); end; end; function ExtractCompiledCodeText(S: String): AnsiString; begin {$IFDEF UNICODE} SetString(Result, PAnsiChar(Pointer(S)), Length(S)*SizeOf(S[1])); {$ELSE} Result := S; {$ENDIF} end; procedure RunSecondPhase; const RemovedMsgs: array[Boolean] of TSetupMessageID = (msgUninstalledMost, msgUninstalledAll); var RestartSystem: Boolean; CompiledCodeData: array[0..6] of String; CompiledCodeText: AnsiString; Res, RemovedAll, UninstallNeedsRestart: Boolean; StartTime: DWORD; begin if VerySilent then SetTaskbarButtonVisibility(False); RestartSystem := False; AllowUninstallerShutdown := (WindowsVersion shr 16 >= $0600); try if DebugWnd <> 0 then SetDebugWnd(DebugWnd, True); if EnableLogging then begin try if LogFilename = '' then StartLogging('Uninstall') else StartLoggingWithFixedFilename(LogFilename); except on E: Exception do begin E.Message := 'Error creating log file:' + SNewLine2 + E.Message; raise; end; end; end; Log('Setup version: ' + SetupTitle + ' version ' + SetupVersion); Log('Original Uninstall EXE: ' + UninstExeFile); Log('Uninstall DAT: ' + UninstDataFile); Log('Uninstall command line: ' + GetCmdTail); LogWindowsVersion; { Open the .dat file for read access } UninstLogFile := OpenUninstDataFile(faRead); { Load contents of the .dat file } UninstLog := TExtUninstallLog.Create; UninstLog.Load(UninstLogFile, UninstDataFile); Title := FmtSetupMessage1(msgUninstallAppFullTitle, UninstLog.AppName); { If install was done in Win64, verify that we're still running Win64. This test shouldn't fail unless the user somehow downgraded their Windows version, or they're running an uninstaller from another machine (which they definitely shouldn't be doing). } if (ufWin64 in UninstLog.Flags) and not IsWin64 then begin LoggedAppMessageBox(PChar(SetupMessages[msgUninstallOnlyOnWin64]), PChar(Title), MB_OK or MB_ICONEXCLAMATION, True, IDOK); Abort; end; { Check if admin privileges are needed to uninstall } if (ufAdminInstalled in UninstLog.Flags) and not IsAdminLoggedOn then begin LoggedAppMessageBox(PChar(SetupMessages[msgOnlyAdminCanUninstall]), PChar(Title), MB_OK or MB_ICONEXCLAMATION, True, IDOK); Abort; end; { Reopen the .dat file for exclusive, read/write access and keep it open for the duration of the uninstall process to prevent a second instance of the same uninstaller from running. } FreeAndNil(UninstLogFile); UninstLogFile := OpenUninstDataFile(faReadWrite); if not UninstLog.ExtractLatestRecData(utCompiledCode, SetupBinVersion {$IFDEF UNICODE} or Longint($80000000) {$ENDIF}, CompiledCodeData) then InternalError('Cannot find utCompiledCode record for this version of the uninstaller'); if DebugWnd <> 0 then CompiledCodeText := DebugClientCompiledCodeText else CompiledCodeText := ExtractCompiledCodeText(CompiledCodeData[0]); {$IFNDEF UNICODE} { Initialize ConstLeadBytes } if Length(CompiledCodeData[1]) <> SizeOf(UninstLeadBytes) then InternalError('utCompiledCode[1] is invalid'); Move(Pointer(CompiledCodeData[1])^, UninstLeadBytes, SizeOf(UninstLeadBytes)); ConstLeadBytes := @UninstLeadBytes; {$ENDIF} { Initialize install mode } if UninstLog.InstallMode64Bit then begin { Sanity check: InstallMode64Bit should never be set without ufWin64 } if not IsWin64 then InternalError('Install was done in 64-bit mode but not running 64-bit Windows now'); Initialize64BitInstallMode(True); end else Initialize64BitInstallMode(False); { Create temporary directory and extract 64-bit helper EXE if necessary } CreateTempInstallDir; if CompiledCodeText <> '' then begin { Setup some global variables which are accessible to [Code] } InitMainNonSHFolderConsts; LoadSHFolderDLL; UninstallExeFilename := UninstExeFile; UninstallExpandedAppId := UninstLog.AppId; UninstallSilent := Silent or VerySilent; UninstallExpandedApp := CompiledCodeData[2]; UninstallExpandedGroup := CompiledCodeData[3]; UninstallExpandedGroupName := CompiledCodeData[4]; UninstallExpandedLanguage := CompiledCodeData[5]; AssignCustomMessages(Pointer(CompiledCodeData[6]), Length(CompiledCodeData[6])*SizeOf(CompiledCodeData[6][1])); CodeRunner := TScriptRunner.Create(); CodeRunner.OnDllImport := CodeRunnerOnDllImport; CodeRunner.OnDebug := CodeRunnerOnDebug; CodeRunner.OnDebugIntermediate := CodeRunnerOnDebugIntermediate; CodeRunner.OnException := CodeRunnerOnException; CodeRunner.LoadScript(CompiledCodeText, DebugClientCompiledCodeDebugInfo); end; try try if CodeRunner <> nil then begin try Res := CodeRunner.RunBooleanFunction('InitializeUninstall', [''], False, True); except Log('InitializeUninstall raised an exception (fatal).'); raise; end; if not Res then begin Log('InitializeUninstall returned False; aborting.'); Abort; end; end; { Confirm uninstall } if not Silent and not VerySilent then begin if LoggedMessageBoxFmt1(msgConfirmUninstall, UninstLog.AppName, Title, MB_ICONQUESTION or MB_YESNO or MB_DEFBUTTON2, True, IDYES) <> IDYES then Abort; end; CurUninstallStepChanged(usAppMutexCheck, False); { Is the app running? } while UninstLog.CheckMutexes do { Yes, tell user to close it } if LoggedMessageBoxFmt1(msgUninstallAppRunningError, UninstLog.AppName, Title, MB_OKCANCEL or MB_ICONEXCLAMATION, True, IDCANCEL) <> IDOK then Abort; { Check for active WM_QUERYENDSESSION/WM_ENDSESSION } while AcceptedQueryEndSessionInProgress do begin Sleep(10); Application.ProcessMessages; end; { Disable Uninstall shutdown } AllowUninstallerShutdown := False; ShutdownBlockReasonCreate(Application.Handle, FmtSetupMessage1(msgShutdownBlockReasonUninstallingApp, UninstLog.AppName)); { Create and show the progress form } InitializeUninstallProgressForm; CurUninstallStepChanged(usUninstall, False); { Start the actual uninstall process } StartTime := GetTickCount; UninstLog.FLastUpdateTime := StartTime; RemovedAll := UninstLog.PerformUninstall(True, DeleteUninstallDataFiles); LogFmt('Removed all? %s', [SYesNo[RemovedAll]]); UninstallNeedsRestart := UninstLog.NeedRestart or (ufAlwaysRestart in UninstLog.Flags); if (CodeRunner <> nil) and CodeRunner.FunctionExists('UninstallNeedRestart') then begin if not UninstallNeedsRestart then begin try if CodeRunner.RunBooleanFunction('UninstallNeedRestart', [''], False, False) then begin UninstallNeedsRestart := True; Log('Will restart because UninstallNeedRestart returned True.'); end; except Log('UninstallNeedRestart raised an exception.'); ShowExceptionMsg; end; end else Log('Not calling UninstallNeedRestart because a restart has already been deemed necessary.'); end; LogFmt('Need to restart Windows? %s', [SYesNo[UninstallNeedsRestart]]); { Ensure at least 1 second has passed since the uninstall process began, then destroy the form } if not VerySilent then begin while True do begin Application.ProcessMessages; if Cardinal(GetTickCount - StartTime) >= Cardinal(1000) then Break; { Delay for 10 ms, or until a message arrives } MsgWaitForMultipleObjects(0, THandle(nil^), False, 10, QS_ALLINPUT); end; end; FreeAndNil(UninstallProgressForm); CurUninstallStepChanged(usPostUninstall, True); if not UninstallNeedsRestart then begin if not Silent and not VerySilent then LoggedMessageBoxFmt1(RemovedMsgs[RemovedAll], UninstLog.AppName, Title, MB_ICONINFORMATION or MB_OK or MB_SETFOREGROUND, True, IDOK); end else begin if not NoRestart then begin if VerySilent or (LoggedMessageBoxFmt1(msgUninstalledAndNeedsRestart, UninstLog.AppName, Title, MB_ICONINFORMATION or MB_YESNO or MB_SETFOREGROUND, True, IDYES) = IDYES) then RestartSystem := True; end; if not RestartSystem then Log('Will not restart Windows automatically.'); end; CurUninstallStepChanged(usDone, True); except { Show any pending exception here *before* DeinitializeUninstall is called, which could display an exception message of its own } ShowExceptionMsg; Abort; end; finally { Free the form here, too, in case an exception occurred above } try FreeAndNil(UninstallProgressForm); except ShowExceptionMsg; end; if CodeRunner <> nil then begin try CodeRunner.RunProcedure('DeinitializeUninstall', [''], False); except Log('DeinitializeUninstall raised an exception.'); ShowExceptionMsg; end; end; ShutdownBlockReasonDestroy(Application.Handle); end; finally FreeAndNil(CodeRunner); UnloadSHFolderDLL; RemoveTempInstallDir; UninstLog.Free; FreeAndNil(UninstLogFile); end; if RestartSystem then begin if not Debugging then begin Log('Restarting Windows.'); RestartInitiatedByThisProcess := True; if not RestartComputer then begin { If another app denied the shutdown, we probably lost the foreground; try to take it back. (Note: Application.BringToFront can't be used because we have no visible forms, and MB_SETFOREGROUND doesn't make the app's taskbar button blink.) } SetForegroundWindow(Application.Handle); LoggedAppMessageBox(PChar(SetupMessages[msgErrorRestartingComputer]), PChar(SetupMessages[msgErrorTitle]), MB_OK or MB_ICONEXCLAMATION, True, IDOK); end; end else Log('Not restarting Windows because Uninstall is being run from the debugger.'); end; end; procedure RunUninstaller; var F: TFile; UninstallerMsgTail: TUninstallerMsgTail; begin { Set default title; it's set again below after the messages are read } Application.Title := 'Uninstall'; { This is needed for D3+: Must force the application window visible since we aren't displaying any forms } ShowWindow(Application.Handle, SW_SHOW); try InitializeCommonVars; SetCurrentDir(GetSystemDir); UninstExeFile := NewParamStr(0); ProcessCommandLine; { note: may change UninstExeFile } UninstDataFile := PathChangeExt(UninstExeFile, '.dat'); UninstMsgFile := PathChangeExt(UninstExeFile, '.msg'); { Initialize messages } F := TFile.Create(UninstExeFile, fdOpenExisting, faRead, fsRead); try F.Seek(F.Size.Lo - SizeOf(UninstallerMsgTail)); F.ReadBuffer(UninstallerMsgTail, SizeOf(UninstallerMsgTail)); if UninstallerMsgTail.ID <> UninstallerMsgTailID then begin { No valid UninstallerMsgTail record found at the end of the EXE; load messages from an external .msg file. } LoadSetupMessages(UninstMsgFile, 0, True); end else LoadSetupMessages(UninstExeFile, UninstallerMsgTail.Offset, True); finally F.Free; end; LangOptions.DialogFontName := MessagesLangOptions.DialogFontName; LangOptions.DialogFontSize := MessagesLangOptions.DialogFontSize; LangOptions.RightToLeft := lfRightToLeft in MessagesLangOptions.Flags; SetMessageBoxRightToLeft(LangOptions.RightToLeft); SetMessageBoxCaption(mbInformation, PChar(SetupMessages[msgInformationTitle])); SetMessageBoxCaption(mbConfirmation, PChar(SetupMessages[msgConfirmTitle])); SetMessageBoxCaption(mbError, PChar(SetupMessages[msgErrorTitle])); SetMessageBoxCaption(mbCriticalError, PChar(SetupMessages[msgErrorTitle])); Application.Title := SetupMessages[msgUninstallAppTitle]; { Verify that uninstall data file exists } if not NewFileExists(UninstDataFile) then begin LoggedMessageBoxFmt1(msgUninstallNotFound, UninstDataFile, SetupMessages[msgUninstallAppTitle], MB_ICONSTOP or MB_OK, True, IDOK); Abort; end; if not SecondPhase then begin if not RespawnFirstPhaseIfNeeded then RunFirstPhase; end else RunSecondPhase; except ShowExceptionMsg; end; { Call EndDebug after all exception messages have been shown and logged in the IDE's Debug Output } EndDebug; Halt(UninstallExitCode); end; procedure HandleUninstallerEndSession; begin { If second phase, remove the temp dir. The self copy made by the first phase will be deleted on restart. } if SecondPhase then begin Log('Detected restart. Removing temporary directory.'); try UnloadSHFolderDLL; RemoveTempInstallDir; except ShowExceptionMsg; end; EndDebug; { Don't use Halt. See Setup.dpr } TerminateProcess(GetCurrentProcess, UninstallExitCode); end; end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uWMConsts; interface uses QGraphics, QMenus, XLib; const { TODO : Extract these values from the system metrics } ICON_WIDTH=32; ICON_HEIGHT=32; MINI_ICON_WIDTH=16; MINI_ICON_HEIGHT=16; maxAtoms=78; atomsSupported=43; atom_net_wm_name =0; atom_wm_protocols =1; atom_wm_take_focus =2; atom_wm_delete_window =3; atom_wm_state =4; atom_net_close_window =5; atom_net_wm_state =6; atom_motif_wm_hints =7; atom_net_wm_state_shaded =8; atom_net_wm_state_maximized_horz =9; atom_net_wm_state_maximized_vert =10; atom_net_wm_desktop =11; atom_net_number_of_desktops =12; atom_wm_change_state =13; atom_sm_client_id =14; atom_wm_client_leader =15; atom_wm_window_role =16; atom_net_current_desktop =17; atom_net_supporting_wm_check =18; atom_net_supported =19; atom_net_wm_window_type =20; atom_net_wm_window_type_desktop =21; atom_net_wm_window_type_dock =22; atom_net_wm_window_type_toolbar =23; atom_net_wm_window_type_menu =24; atom_net_wm_window_type_dialog =25; atom_net_wm_window_type_normal =26; atom_net_wm_state_modal =27; atom_net_client_list =28; atom_net_client_list_stacking =29; atom_net_wm_state_skip_taskbar =30; atom_net_wm_state_skip_pager =31; atom_win_workspace =32; atom_win_layer =33; atom_win_protocols =34; atom_win_supporting_wm_check =35; atom_net_wm_icon_name =36; atom_net_wm_icon =37; atom_net_wm_icon_geometry =38; atom_utf8_string =39; atom_wm_icon_size =40; atom_kwm_win_icon =41; atom_net_wm_moveresize =42; atom_net_active_window =43; atom_metacity_restart_message =44; atom_net_wm_strut =45; atom_win_hints =46; atom_metacity_reload_theme_message =47; atom_metacity_set_keybindings_message =48; atom_net_wm_state_hidden =49; atom_net_wm_window_type_utility =50; atom_net_wm_window_type_splashscreen =51; atom_net_wm_state_fullscreen =52; atom_net_wm_ping =53; atom_net_wm_pid =54; atom_wm_client_machine =55; atom_net_workarea =56; atom_net_showing_desktop =57; atom_net_desktop_layout =58; atom_manager =59; atom_targets =60; atom_multiple =61; atom_timestamp =62; atom_version =63; atom_atom_pair =64; atom_net_desktop_names =65; atom_net_wm_allowed_actions =66; atom_net_wm_action_move =67; atom_net_wm_action_resize =68; atom_net_wm_action_shade =69; atom_net_wm_action_stick =70; atom_net_wm_action_maximize_horz =71; atom_net_wm_action_maximize_vert =72; atom_net_wm_action_change_desktop =73; atom_net_wm_action_close =74; atom_net_wm_state_above =75; atom_net_wm_state_below =76; atom_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR=77; atom_BY_PASS_WM=78; type { TODO : Make this interface an standard } IWMClient=interface ['{8225D62E-CEE8-D611-927C-000244219999}'] procedure focus; procedure minimize; procedure maximize; procedure beginresize; procedure endresize; procedure restore; procedure close; procedure map; procedure bringtofront; procedure updateactivestate; function isactive:boolean; procedure activate(restore:boolean=true); function getTitle: widestring; function getBitmap: TBitmap; function getSystemMenu: TPopupMenu; function getWindow: Window; end; implementation end.
unit VtasCli; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBTables, ppCtrls, ppBands, ppPrnabl, ppClass, ppProd, ppReport, ppComm, ppCache, ppDB, ppDBBDE, Db, ppVar, ppRelatv, ppDBPipe, ppParameter, ADODB; type TFVtasCli = class(TForm) DSaldos: TDataSource; ppBDEPipeline1: TppBDEPipeline; ppR: TppReport; ppRHeaderBand1: TppHeaderBand; ppRLabel1: TppLabel; ppRShape1: TppShape; ppRLabel2: TppLabel; ppRLabel3: TppLabel; ppRLabel4: TppLabel; Saldos: TppLabel; Periodo: TppLabel; ppRDetailBand1: TppDetailBand; ppRDBText1: TppDBText; ppRDBText2: TppDBText; ppRDBText3: TppDBText; ppRFooterBand1: TppFooterBand; ppRSummaryBand1: TppSummaryBand; ppRShape2: TppShape; ppRLabel5: TppLabel; ppRDBCalc1: TppDBCalc; ppRCalc1: TppSystemVariable; ppRCalc2: TppSystemVariable; Empresa: TppLabel; TDatos: TADOTable; QVentas: TADOQuery; procedure FormCreate(Sender: TObject); procedure EmpresaPrint(Sender: TObject); private { Private declarations } procedure ActualSesion; public { Public declarations } procedure SetRango(FecIni, FecFin: TDateTime; Saldo: double); end; var FVtasCli: TFVtasCli; implementation uses DMIng; {$R *.DFM} procedure TFVtasCli.SetRango(FecIni, FecFin: TDateTime; Saldo: double); begin QVentas.Parameters.paramByName( 'FECINI' ).value := FecIni; QVentas.Parameters.paramByName( 'FECFIN' ).value := FecFin; QVentas.Parameters.paramByName( 'IMPORTE' ).value := Saldo; Saldos.Caption := 'Ventas Superiores a: ' + format( '%12.2f', [ Saldo ] ); Periodo.Caption := 'Entre el ' + DateToStr( FecIni ) + ' y el ' + DateToStr( FecFin ); QVentas.Open; end; procedure TFVtasCli.FormCreate(Sender: TObject); begin ActualSesion; TDatos.Open; end; procedure TFVtasCli.EmpresaPrint(Sender: TObject); begin Empresa.caption := TDatos.FieldByName( 'DENOMINA' ).value; end; procedure TFVtasCli.ActualSesion; begin end; end.
unit l3CustomString; {* Базовый класс для "строк". Определяет операции и свойства, но не способ хранения данных. } // Модуль: "w:\common\components\rtl\Garant\L3\l3CustomString.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3CustomString" MUID: (4773DEF0021B) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3Variant , l3Types , l3Interfaces , l3IID , Classes ; type Tl3CustomString = {abstract} class(Tl3PrimString) {* Базовый класс для "строк". Определяет операции и свойства, но не способ хранения данных. } private class procedure l3SayConstString; protected function pm_GetSt: PAnsiChar; function pm_GetLen: Integer; virtual; procedure pm_SetLen(aValue: Integer); virtual; function pm_GetCodePage: Integer; procedure pm_SetCodePage(aValue: Integer); function pm_GetIsOEM: Boolean; function pm_GetIsOEMEx: Boolean; function pm_GetIsANSI: Boolean; function pm_GetAsPCharLen: Tl3PCharLen; procedure pm_SetAsPCharLen(const aValue: Tl3PCharLen); function pm_GetFirst: AnsiChar; function pm_GetLast: AnsiChar; function pm_GetCh(aPos: Integer): AnsiChar; procedure pm_SetCh(aPos: Integer; aValue: AnsiChar); function pm_GetRTrimLen: Integer; function pm_GetLTrimLen: Integer; function pm_GetAsChar: AnsiChar; procedure pm_SetAsChar(aValue: AnsiChar); function pm_GetAsPWideChar: PWideChar; procedure pm_SetAsPWideChar(aValue: PWideChar); function pm_GetAsWideString: WideString; procedure pm_SetAsWideString(const aValue: WideString); procedure DoSetCodePage(aValue: Integer); virtual; procedure CheckUnicode; procedure DoSetAsPCharLen(const Value: Tl3PCharLen); override; function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } public function Offset(Delta: Integer): Tl3CustomString; virtual; function AssignSt(aSt: PAnsiChar; O1: Integer; 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 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; 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: Integer; aCount: Integer): PAnsiChar; virtual; {* удаляет aCount символов с позиции aPos } procedure SetSt(aStr: PAnsiChar; aLen: Integer = -1); {* присваивает новое значение строке, считая, что aStr имеет ту же кодировку, что и строка } function JoinWith(P: Tl3PrimString): Integer; virtual; {* операция объединения двух объектов } procedure Assign(Source: TPersistent); override; public 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; property IsOEMEx: Boolean read pm_GetIsOEMEx; property IsANSI: Boolean read pm_GetIsANSI; property AsPCharLen: Tl3PCharLen read pm_GetAsPCharLen write pm_SetAsPCharLen; property First: AnsiChar read pm_GetFirst; property Last: AnsiChar read pm_GetLast; property Ch[aPos: Integer]: AnsiChar read pm_GetCh write pm_SetCh; 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 l3ImplUses , l3BMSearch , SysUtils , l3Base , l3String , l3StringEx , l3Memory , l3StringAdapter , l3Chars //#UC START# *4773DEF0021Bimpl_uses* //#UC END# *4773DEF0021Bimpl_uses* ; function Tl3CustomString.pm_GetSt: PAnsiChar; //#UC START# *54C62FCA01B2_4773DEF0021Bget_var* //#UC END# *54C62FCA01B2_4773DEF0021Bget_var* begin //#UC START# *54C62FCA01B2_4773DEF0021Bget_impl* if (Self = nil) then Result := nil else Result := GetAsPCharLen.S; //#UC END# *54C62FCA01B2_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetSt function Tl3CustomString.pm_GetLen: Integer; //#UC START# *54C63008010F_4773DEF0021Bget_var* //#UC END# *54C63008010F_4773DEF0021Bget_var* begin //#UC START# *54C63008010F_4773DEF0021Bget_impl* if (Self = nil) then Result := 0 else Result := GetAsPCharLen.SLen; //#UC END# *54C63008010F_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetLen procedure Tl3CustomString.pm_SetLen(aValue: Integer); //#UC START# *54C63008010F_4773DEF0021Bset_var* //#UC END# *54C63008010F_4773DEF0021Bset_var* begin //#UC START# *54C63008010F_4773DEF0021Bset_impl* //#UC END# *54C63008010F_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetLen function Tl3CustomString.pm_GetCodePage: Integer; //#UC START# *54C6307003BB_4773DEF0021Bget_var* //#UC END# *54C6307003BB_4773DEF0021Bget_var* begin //#UC START# *54C6307003BB_4773DEF0021Bget_impl* Result := AsPCharLen.SCodePage; //#UC END# *54C6307003BB_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetCodePage procedure Tl3CustomString.pm_SetCodePage(aValue: Integer); //#UC START# *54C6307003BB_4773DEF0021Bset_var* //#UC END# *54C6307003BB_4773DEF0021Bset_var* begin //#UC START# *54C6307003BB_4773DEF0021Bset_impl* if (Self <> nil) then DoSetCodePage(aValue); //#UC END# *54C6307003BB_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetCodePage function Tl3CustomString.pm_GetIsOEM: Boolean; //#UC START# *54C630BC0157_4773DEF0021Bget_var* //#UC END# *54C630BC0157_4773DEF0021Bget_var* begin //#UC START# *54C630BC0157_4773DEF0021Bget_impl* Result := l3IsOEM(CodePage); //#UC END# *54C630BC0157_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetIsOEM function Tl3CustomString.pm_GetIsOEMEx: Boolean; //#UC START# *54C630DC0134_4773DEF0021Bget_var* //#UC END# *54C630DC0134_4773DEF0021Bget_var* begin //#UC START# *54C630DC0134_4773DEF0021Bget_impl* Result := l3IsOEMEx(CodePage); //#UC END# *54C630DC0134_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetIsOEMEx function Tl3CustomString.pm_GetIsANSI: Boolean; //#UC START# *54C631160124_4773DEF0021Bget_var* //#UC END# *54C631160124_4773DEF0021Bget_var* begin //#UC START# *54C631160124_4773DEF0021Bget_impl* Result := l3IsANSI(CodePage); //#UC END# *54C631160124_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetIsANSI function Tl3CustomString.pm_GetAsPCharLen: Tl3PCharLen; //#UC START# *54C6321A0320_4773DEF0021Bget_var* //#UC END# *54C6321A0320_4773DEF0021Bget_var* begin //#UC START# *54C6321A0320_4773DEF0021Bget_impl* if (Self = nil) then l3AssignNil(Result) else Tl3WString(Result) := GetAsPCharLen; //#UC END# *54C6321A0320_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetAsPCharLen procedure Tl3CustomString.pm_SetAsPCharLen(const aValue: Tl3PCharLen); //#UC START# *54C6321A0320_4773DEF0021Bset_var* //#UC END# *54C6321A0320_4773DEF0021Bset_var* begin //#UC START# *54C6321A0320_4773DEF0021Bset_impl* if (Self <> nil) then DoSetAsPCharLen(aValue); //#UC END# *54C6321A0320_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetAsPCharLen function Tl3CustomString.pm_GetFirst: AnsiChar; //#UC START# *54C63409007E_4773DEF0021Bget_var* //#UC END# *54C63409007E_4773DEF0021Bget_var* begin //#UC START# *54C63409007E_4773DEF0021Bget_impl* if not Empty then Result := Ch[0] else Result := #0; //#UC END# *54C63409007E_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetFirst function Tl3CustomString.pm_GetLast: AnsiChar; //#UC START# *54C6352E0043_4773DEF0021Bget_var* //#UC END# *54C6352E0043_4773DEF0021Bget_var* begin //#UC START# *54C6352E0043_4773DEF0021Bget_impl* if not Empty then Result := Ch[Pred(Len)] else Result := #0; //#UC END# *54C6352E0043_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetLast function Tl3CustomString.pm_GetCh(aPos: Integer): AnsiChar; //#UC START# *54C6356B0095_4773DEF0021Bget_var* var l_S : Tl3WString; //#UC END# *54C6356B0095_4773DEF0021Bget_var* begin //#UC START# *54C6356B0095_4773DEF0021Bget_impl* 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; //#UC END# *54C6356B0095_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetCh procedure Tl3CustomString.pm_SetCh(aPos: Integer; aValue: AnsiChar); //#UC START# *54C6356B0095_4773DEF0021Bset_var* var l_S : Tl3WString; //#UC END# *54C6356B0095_4773DEF0021Bset_var* begin //#UC START# *54C6356B0095_4773DEF0021Bset_impl* 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(aValue) else l_S.S[aPos] := aValue; CheckUnicode; end//S <> nil else Insert(l3PCharLen(@aValue, 1, CodePage), aPos); end;{aPos >= 0} //#UC END# *54C6356B0095_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetCh function Tl3CustomString.pm_GetRTrimLen: Integer; //#UC START# *54C6360A0301_4773DEF0021Bget_var* //#UC END# *54C6360A0301_4773DEF0021Bget_var* begin //#UC START# *54C6360A0301_4773DEF0021Bget_impl* if Empty then Result := 0 else Result := l3RTrim(AsPCharLen).SLen; //#UC END# *54C6360A0301_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetRTrimLen function Tl3CustomString.pm_GetLTrimLen: Integer; //#UC START# *54C6365D02F7_4773DEF0021Bget_var* //#UC END# *54C6365D02F7_4773DEF0021Bget_var* begin //#UC START# *54C6365D02F7_4773DEF0021Bget_impl* if Empty then Result := 0 else Result := l3LTrim(Self.AsWStr).SLen; //#UC END# *54C6365D02F7_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetLTrimLen function Tl3CustomString.pm_GetAsChar: AnsiChar; //#UC START# *54C63686017E_4773DEF0021Bget_var* //#UC END# *54C63686017E_4773DEF0021Bget_var* begin //#UC START# *54C63686017E_4773DEF0021Bget_impl* Result := Ch[0]; //#UC END# *54C63686017E_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetAsChar procedure Tl3CustomString.pm_SetAsChar(aValue: AnsiChar); //#UC START# *54C63686017E_4773DEF0021Bset_var* //#UC END# *54C63686017E_4773DEF0021Bset_var* begin //#UC START# *54C63686017E_4773DEF0021Bset_impl* AsPCharLen := l3PCharLen(@aValue, 1, CodePage); //#UC END# *54C63686017E_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetAsChar function Tl3CustomString.pm_GetAsPWideChar: PWideChar; //#UC START# *54C636F400CA_4773DEF0021Bget_var* //#UC END# *54C636F400CA_4773DEF0021Bget_var* begin //#UC START# *54C636F400CA_4773DEF0021Bget_impl* Result := PWideChar(St); //#UC END# *54C636F400CA_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetAsPWideChar procedure Tl3CustomString.pm_SetAsPWideChar(aValue: PWideChar); //#UC START# *54C636F400CA_4773DEF0021Bset_var* //#UC END# *54C636F400CA_4773DEF0021Bset_var* begin //#UC START# *54C636F400CA_4773DEF0021Bset_impl* AsPCharLen := l3PCharLen(PAnsiChar(aValue), -1, CP_Unicode); //#UC END# *54C636F400CA_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetAsPWideChar function Tl3CustomString.pm_GetAsWideString: WideString; //#UC START# *54C637680235_4773DEF0021Bget_var* {$IfDef XE4} var l_S : Tl3PCharLen; {$EndIf XE4} //#UC END# *54C637680235_4773DEF0021Bget_var* begin //#UC START# *54C637680235_4773DEF0021Bget_impl* {$IfDef XE4} l_S := AsPCharLen; Result := Tl3Str(l_S).AsWideString; {$Else XE4} Result := Tl3Str(AsPCharLen).AsWideString; {$EndIf XE4} //#UC END# *54C637680235_4773DEF0021Bget_impl* end;//Tl3CustomString.pm_GetAsWideString procedure Tl3CustomString.pm_SetAsWideString(const aValue: WideString); //#UC START# *54C637680235_4773DEF0021Bset_var* //#UC END# *54C637680235_4773DEF0021Bset_var* begin //#UC START# *54C637680235_4773DEF0021Bset_impl* AsPCharLen := l3PCharLen(aValue); //#UC END# *54C637680235_4773DEF0021Bset_impl* end;//Tl3CustomString.pm_SetAsWideString function Tl3CustomString.Offset(Delta: Integer): Tl3CustomString; //#UC START# *4E568A7E0120_4773DEF0021B_var* var l_S: Tl3WString; //#UC END# *4E568A7E0120_4773DEF0021B_var* begin //#UC START# *4E568A7E0120_4773DEF0021B_impl* l_S := AsWStr; AsWStr := l3PCharLen(l_S.S + Delta, l_S.SLen - Delta, l_S.SCodePage); Result := Self; //#UC END# *4E568A7E0120_4773DEF0021B_impl* end;//Tl3CustomString.Offset procedure Tl3CustomString.DoSetCodePage(aValue: Integer); //#UC START# *4E568AB6016C_4773DEF0021B_var* //#UC END# *4E568AB6016C_4773DEF0021B_var* begin //#UC START# *4E568AB6016C_4773DEF0021B_impl* //#UC END# *4E568AB6016C_4773DEF0021B_impl* end;//Tl3CustomString.DoSetCodePage procedure Tl3CustomString.CheckUnicode; //#UC START# *54C6388203A0_4773DEF0021B_var* const cCodePages : array [0..7] of Integer = (CP_RussianWin, CP_EastEurope, CP_Greek, CP_Turkish, CP_WesternWin, CP_Tatar, CP_TatarOEM, CP_RussianDOS); var l_Index: Integer; l_S: Tl3Str; l_W: Tl3WString; //#UC END# *54C6388203A0_4773DEF0021B_var* begin //#UC START# *54C6388203A0_4773DEF0021B_impl* 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 //#UC END# *54C6388203A0_4773DEF0021B_impl* end;//Tl3CustomString.CheckUnicode function Tl3CustomString.AssignSt(aSt: PAnsiChar; O1: Integer; O2: Integer; aCodePage: Integer): Tl3CustomString; //#UC START# *54C639280275_4773DEF0021B_var* var L : Integer; //#UC END# *54C639280275_4773DEF0021B_var* begin //#UC START# *54C639280275_4773DEF0021B_impl* if (O2 > O1) then L := O2 - O1 else L := 0; if aCodePage = CP_Unicode then O1 := O1 * SizeOf(WideChar); AsPCharLen := l3PCharLen(aSt + O1, L, aCodePage); Result := Self; //#UC END# *54C639280275_4773DEF0021B_impl* end;//Tl3CustomString.AssignSt procedure Tl3CustomString.LPad(aCh: AnsiChar; aCodePage: Integer = CP_ANSI; aRepeat: Integer = 1); {* добавляет к строке слева символ aCh aRepeat раз } //#UC START# *54C6397F033C_4773DEF0021B_var* //#UC END# *54C6397F033C_4773DEF0021B_var* begin //#UC START# *54C6397F033C_4773DEF0021B_impl* Insert(l3PCharLen(@aCh, 1, aCodePage), 0, aRepeat); //#UC END# *54C6397F033C_4773DEF0021B_impl* end;//Tl3CustomString.LPad procedure Tl3CustomString.Append(const aSt: Tl3WString; aRepeat: Integer = 1); {* добавляет строку aSt к данной строке aRepeat раз } //#UC START# *54C639EC034A_4773DEF0021B_var* //#UC END# *54C639EC034A_4773DEF0021B_var* begin //#UC START# *54C639EC034A_4773DEF0021B_impl* //#UC END# *54C639EC034A_4773DEF0021B_impl* end;//Tl3CustomString.Append procedure Tl3CustomString.Append(const aCh: Tl3Char; aRepeat: Integer = 1); {* добавляет символ aCh к данной строке aRepeat раз } //#UC START# *54C63A210201_4773DEF0021B_var* //#UC END# *54C63A210201_4773DEF0021B_var* begin //#UC START# *54C63A210201_4773DEF0021B_impl* Append(l3PCharLen(@aCh.rWC, 1, aCh.rCodePage), aRepeat); //#UC END# *54C63A210201_4773DEF0021B_impl* end;//Tl3CustomString.Append procedure Tl3CustomString.Append(aCh: AnsiChar; aRepeat: Integer = 1; aCodePage: Integer = CP_ANSI); {* добавляет символ aCh к данной строке aRepeat раз } //#UC START# *54C63A550261_4773DEF0021B_var* //#UC END# *54C63A550261_4773DEF0021B_var* begin //#UC START# *54C63A550261_4773DEF0021B_impl* Append(l3PCharLen(@aCh, 1, aCodePage), aRepeat); //#UC END# *54C63A550261_4773DEF0021B_impl* end;//Tl3CustomString.Append procedure Tl3CustomString.Insert(const aSt: Tl3WString; aPos: Integer; aRepeat: Integer = 1); {* вставляет строку aSt в позицию aPos, aRepeat раз } //#UC START# *54C63A9901CE_4773DEF0021B_var* //#UC END# *54C63A9901CE_4773DEF0021B_var* begin //#UC START# *54C63A9901CE_4773DEF0021B_impl* l3SayConstString; //#UC END# *54C63A9901CE_4773DEF0021B_impl* end;//Tl3CustomString.Insert procedure Tl3CustomString.Insert(aCh: AnsiChar; aPos: Integer; aRepeat: Integer = 1); {* вставляет символ aCh в позицию aPos, aRepeat раз } //#UC START# *54C63AD303DA_4773DEF0021B_var* //#UC END# *54C63AD303DA_4773DEF0021B_var* begin //#UC START# *54C63AD303DA_4773DEF0021B_impl* Insert(l3PCharLen(PAnsiChar(@aCh), 1), aPos, aRepeat); //#UC END# *54C63AD303DA_4773DEF0021B_impl* end;//Tl3CustomString.Insert procedure Tl3CustomString.Insert(S: Tl3CustomString; aPos: Integer; aRepeat: Integer = 1); {* вставляет строку S в позицию aPos, aRepeat раз } //#UC START# *54C63AF80344_4773DEF0021B_var* //#UC END# *54C63AF80344_4773DEF0021B_var* begin //#UC START# *54C63AF80344_4773DEF0021B_impl* if not S.Empty then Insert(S.AsPCharLen, aPos, aRepeat); //#UC END# *54C63AF80344_4773DEF0021B_impl* end;//Tl3CustomString.Insert function Tl3CustomString.Trim: Tl3CustomString; {* удаляет конечные и начальные пробелы } //#UC START# *54C63B82016A_4773DEF0021B_var* //#UC END# *54C63B82016A_4773DEF0021B_var* begin //#UC START# *54C63B82016A_4773DEF0021B_impl* LTrim; Result := RTrim; //#UC END# *54C63B82016A_4773DEF0021B_impl* end;//Tl3CustomString.Trim function Tl3CustomString.TrimAll: Tl3CustomString; {* удаляет конечные, начальные и дублирующиеся пробелы } //#UC START# *54C63BA70371_4773DEF0021B_var* //#UC END# *54C63BA70371_4773DEF0021B_var* begin //#UC START# *54C63BA70371_4773DEF0021B_impl* Result := Trim.DeleteDoubleSpace; //#UC END# *54C63BA70371_4773DEF0021B_impl* end;//Tl3CustomString.TrimAll procedure Tl3CustomString.LTrim; {* удаляет из строки ведущие пробелы } //#UC START# *54C63BCF01AC_4773DEF0021B_var* //#UC END# *54C63BCF01AC_4773DEF0021B_var* begin //#UC START# *54C63BCF01AC_4773DEF0021B_impl* Assert(false); //#UC END# *54C63BCF01AC_4773DEF0021B_impl* end;//Tl3CustomString.LTrim function Tl3CustomString.RTrim: Tl3CustomString; {* удаляет из строки конечные пробелы } //#UC START# *54C63BEF0044_4773DEF0021B_var* //#UC END# *54C63BEF0044_4773DEF0021B_var* begin //#UC START# *54C63BEF0044_4773DEF0021B_impl* if not Empty then begin Len := l3RTrim(AsPCharLen).SLen; if Empty then Clear; end;//not Empty Result := Self; //#UC END# *54C63BEF0044_4773DEF0021B_impl* end;//Tl3CustomString.RTrim procedure Tl3CustomString.TrimEOL; {* удаляет из строки конечные cc_SoftEnter и cc_HardEnter } //#UC START# *54C63C5E0104_4773DEF0021B_var* //#UC END# *54C63C5E0104_4773DEF0021B_var* begin //#UC START# *54C63C5E0104_4773DEF0021B_impl* while (Len > 0) and (St[Pred(Len)] in [cc_SoftEnter, cc_HardEnter, cc_Null]) do Len := Pred(Len); //#UC END# *54C63C5E0104_4773DEF0021B_impl* end;//Tl3CustomString.TrimEOL function Tl3CustomString.DeleteDoubleSpace: Tl3CustomString; {* удаляет из строки дублирующиеся пробелы } //#UC START# *54C63C7C01C4_4773DEF0021B_var* //#UC END# *54C63C7C01C4_4773DEF0021B_var* begin //#UC START# *54C63C7C01C4_4773DEF0021B_impl* Result := Self; //#UC END# *54C63C7C01C4_4773DEF0021B_impl* end;//Tl3CustomString.DeleteDoubleSpace function Tl3CustomString.DeleteAllChars(aChar: AnsiChar): Integer; {* удаляет из строки все символы aChar и возвращает количество удаленных } //#UC START# *54C63CAA03E0_4773DEF0021B_var* var l_Pos : Integer; //#UC END# *54C63CAA03E0_4773DEF0021B_var* begin //#UC START# *54C63CAA03E0_4773DEF0021B_impl* 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 //#UC END# *54C63CAA03E0_4773DEF0021B_impl* end;//Tl3CustomString.DeleteAllChars function Tl3CustomString.ReplaceNonReadable: Tl3CustomString; {* заменяет "нечитаемые" символы пробелами } //#UC START# *54C63CED01C7_4773DEF0021B_var* //#UC END# *54C63CED01C7_4773DEF0021B_var* begin //#UC START# *54C63CED01C7_4773DEF0021B_impl* Result := Self; l3SayConstString; //#UC END# *54C63CED01C7_4773DEF0021B_impl* end;//Tl3CustomString.ReplaceNonReadable function Tl3CustomString.FindChar(Pos: Integer; C: AnsiChar): Integer; {* ищет символ в строке с позиции Pos и возвращает позицию найденного символа или -1 } //#UC START# *54C63EA70259_4773DEF0021B_var* var P, P1 : PAnsiChar; //#UC END# *54C63EA70259_4773DEF0021B_var* begin //#UC START# *54C63EA70259_4773DEF0021B_impl* 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.. //#UC END# *54C63EA70259_4773DEF0021B_impl* end;//Tl3CustomString.FindChar procedure Tl3CustomString.FindCharEx(C: AnsiChar; aSt: Tl3CustomString); //#UC START# *54C63F2D0242_4773DEF0021B_var* var l_S : Tl3PCharLen; //#UC END# *54C63F2D0242_4773DEF0021B_var* begin //#UC START# *54C63F2D0242_4773DEF0021B_impl* l_S := AsPCharLen; aSt.AsPCharLen := l3FindChar(C, l_S); if not aSt.Empty then Len := l_S.SLen; //#UC END# *54C63F2D0242_4773DEF0021B_impl* end;//Tl3CustomString.FindCharEx function Tl3CustomString.Indent: Integer; //#UC START# *54C63F5400AC_4773DEF0021B_var* //#UC END# *54C63F5400AC_4773DEF0021B_var* begin //#UC START# *54C63F5400AC_4773DEF0021B_impl* if Empty then Result := 0 else Result := ev_lpIndent(St, Len); //#UC END# *54C63F5400AC_4773DEF0021B_impl* end;//Tl3CustomString.Indent procedure Tl3CustomString.MakeBMTable(var BT: Tl3BMTable); {* создает таблицу Boyer-Moore для строки } //#UC START# *54C63F7801B0_4773DEF0021B_var* var l_S : Tl3PCharLen; //#UC END# *54C63F7801B0_4773DEF0021B_var* begin //#UC START# *54C63F7801B0_4773DEF0021B_impl* l_S := AsPCharLen; if (l_S.SCodePage = CP_Unicode) then l3FillChar(BT, SizeOf(BT)) else l3BMSearch.BMMakeTable(l_S.S, BT, l_S.SLen); //#UC END# *54C63F7801B0_4773DEF0021B_impl* end;//Tl3CustomString.MakeBMTable function Tl3CustomString.BMSearch(S: Tl3CustomString; const BT: Tl3BMTable; var Pos: Cardinal): Boolean; {* ищет данную строку в строке S с учетом регистра } //#UC START# *54C63FB802C8_4773DEF0021B_var* var l_S : Tl3PCharLen; l_SS : Tl3PCharLen; //#UC END# *54C63FB802C8_4773DEF0021B_var* begin //#UC START# *54C63FB802C8_4773DEF0021B_impl* l_S := S.AsPCharLen; l_SS := AsPCharLen; if l3IsNil(l_SS) then Result := false else Result := l3SearchStr(l_S, BT, l_SS, Pos); //#UC END# *54C63FB802C8_4773DEF0021B_impl* end;//Tl3CustomString.BMSearch function Tl3CustomString.BMSearchUC(S: Tl3CustomString; const BT: Tl3BMTable; var Pos: Cardinal): Boolean; {* ищет данную строку в строке S без учета регистра ВНИМАНИЕ! Для успешного поиска без учёта регистра подстрока (S) должна быть в ВЕРХНЕМ РЕГИСТРЕ! И таблица (BT) должна быть построена для этой строки в верхнем регистре! } //#UC START# *54C63FE7008C_4773DEF0021B_var* var l_S : Tl3PCharLen; l_SS : Tl3PCharLen; //#UC END# *54C63FE7008C_4773DEF0021B_var* begin //#UC START# *54C63FE7008C_4773DEF0021B_impl* l_S := S.AsPCharLen; l_SS := AsPCharLen; if l3IsNil(l_SS) then Result := false else Result := l3SearchStrUC(l_S, BT, l_SS, Pos); //#UC END# *54C63FE7008C_4773DEF0021B_impl* end;//Tl3CustomString.BMSearchUC procedure Tl3CustomString.MakeUpper; {* преобразует строку к верхнему регистру } //#UC START# *54C640230216_4773DEF0021B_var* //#UC END# *54C640230216_4773DEF0021B_var* begin //#UC START# *54C640230216_4773DEF0021B_impl* l3MakeUpperCase(St, Len, CodePage); //#UC END# *54C640230216_4773DEF0021B_impl* end;//Tl3CustomString.MakeUpper procedure Tl3CustomString.MakeLower; {* преобразует строку к нижнему регистру } //#UC START# *54C64032026A_4773DEF0021B_var* //#UC END# *54C64032026A_4773DEF0021B_var* begin //#UC START# *54C64032026A_4773DEF0021B_impl* l3MakeLowerCase(St, Len, CodePage); //#UC END# *54C64032026A_4773DEF0021B_impl* end;//Tl3CustomString.MakeLower function Tl3CustomString.Delete(aPos: Integer; aCount: Integer): PAnsiChar; {* удаляет aCount символов с позиции aPos } //#UC START# *54C640510217_4773DEF0021B_var* //#UC END# *54C640510217_4773DEF0021B_var* begin //#UC START# *54C640510217_4773DEF0021B_impl* Result := St; //#UC END# *54C640510217_4773DEF0021B_impl* end;//Tl3CustomString.Delete procedure Tl3CustomString.SetSt(aStr: PAnsiChar; aLen: Integer = -1); {* присваивает новое значение строке, считая, что aStr имеет ту же кодировку, что и строка } //#UC START# *54C640BB0399_4773DEF0021B_var* //#UC END# *54C640BB0399_4773DEF0021B_var* begin //#UC START# *54C640BB0399_4773DEF0021B_impl* AsPCharLen := l3PCharLen(aStr, aLen, CodePage); //#UC END# *54C640BB0399_4773DEF0021B_impl* end;//Tl3CustomString.SetSt function Tl3CustomString.JoinWith(P: Tl3PrimString): Integer; {* операция объединения двух объектов } //#UC START# *54C641A901E6_4773DEF0021B_var* //#UC END# *54C641A901E6_4773DEF0021B_var* begin //#UC START# *54C641A901E6_4773DEF0021B_impl* Result := -1; //#UC END# *54C641A901E6_4773DEF0021B_impl* end;//Tl3CustomString.JoinWith class procedure Tl3CustomString.l3SayConstString; //#UC START# *54C68EF4028F_4773DEF0021B_var* //#UC END# *54C68EF4028F_4773DEF0021B_var* begin //#UC START# *54C68EF4028F_4773DEF0021B_impl* raise Exception.Create('Данный тип строки не может быть модифицирован'); //#UC END# *54C68EF4028F_4773DEF0021B_impl* end;//Tl3CustomString.l3SayConstString procedure Tl3CustomString.Assign(Source: TPersistent); //#UC START# *478CF34E02CE_4773DEF0021B_var* //#UC END# *478CF34E02CE_4773DEF0021B_var* begin //#UC START# *478CF34E02CE_4773DEF0021B_impl* if (Source = nil) then Clear else if (Source Is Tl3PrimString) then AssignString(Tl3PrimString(Source)) else inherited; //#UC END# *478CF34E02CE_4773DEF0021B_impl* end;//Tl3CustomString.Assign procedure Tl3CustomString.DoSetAsPCharLen(const Value: Tl3PCharLen); //#UC START# *47A869D10074_4773DEF0021B_var* //#UC END# *47A869D10074_4773DEF0021B_var* begin //#UC START# *47A869D10074_4773DEF0021B_impl* Assert(false); //#UC END# *47A869D10074_4773DEF0021B_impl* end;//Tl3CustomString.DoSetAsPCharLen function Tl3CustomString.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* Реализация запроса интерфейса } //#UC START# *4A60B23E00C3_4773DEF0021B_var* //#UC END# *4A60B23E00C3_4773DEF0021B_var* begin //#UC START# *4A60B23E00C3_4773DEF0021B_impl* 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); //#UC END# *4A60B23E00C3_4773DEF0021B_impl* end;//Tl3CustomString.COMQueryInterface end.
unit Form_Mensagem; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls; type TFrm_Mensagem = class(TForm) rect_fundo: TRectangle; img_erro: TImage; img_alerta: TImage; img_sucesso: TImage; img_pergunta: TImage; rect_msg: TRectangle; lbl_titulo: TLabel; lbl_msg: TLabel; img_icone: TImage; layout_botao: TLayout; rect_btn1: TRectangle; lbl_btn1: TLabel; rect_btn2: TRectangle; lbl_btn2: TLabel; procedure FormCreate(Sender: TObject); procedure lbl_btn1Click(Sender: TObject); procedure lbl_btn2Click(Sender: TObject); private { Private declarations } public { Public declarations } retorno: string; procedure Exibir_Mensagem(icone, tipo_mensagem, titulo, texto_msg, texto_btn1, texto_btn2: string; cor_btn1, cor_btn2: Cardinal); end; var Frm_Mensagem: TFrm_Mensagem; implementation {$R *.fmx} procedure TFrm_Mensagem.FormCreate(Sender: TObject); begin img_erro.Visible := false; img_alerta.Visible := false; img_sucesso.Visible := false; img_pergunta.Visible := false; end; procedure TFrm_Mensagem.lbl_btn1Click(Sender: TObject); begin retorno := '1'; close; end; procedure TFrm_Mensagem.lbl_btn2Click(Sender: TObject); begin retorno := '2'; close; end; { icone: ALERTA, PERGUNTA, ERRO ou SUCESSO tipo_mensagem: ALERTA ou PERGUNTA cor: exemplo... $FFA0A0A0 } procedure TFrm_Mensagem.Exibir_Mensagem(icone, tipo_mensagem, titulo, texto_msg, texto_btn1, texto_btn2: string; cor_btn1, cor_btn2: Cardinal); begin // Icone... if icone = 'ALERTA' then img_icone.Bitmap := img_alerta.Bitmap else if icone = 'PERGUNTA' then img_icone.Bitmap := img_pergunta.Bitmap else if icone = 'ERRO' then img_icone.Bitmap := img_erro.Bitmap else img_icone.Bitmap := img_sucesso.Bitmap; // Tipo mensagem... rect_btn2.Visible := false; if tipo_mensagem = 'PERGUNTA' then begin rect_btn1.Width := 102; rect_btn2.Width := 102; rect_btn1.Align := TAlignLayout.Left; rect_btn2.Align := TAlignLayout.Right; rect_btn2.Visible := true; end else begin rect_btn1.Width := 160; rect_btn1.Align := TAlignLayout.Center; end; // Textos da Mensagem... lbl_titulo.Text := titulo; lbl_msg.Text := texto_msg; // Textos Botoes... lbl_btn1.Text := texto_btn1; lbl_btn2.Text := texto_btn2; // Cor Botoes... rect_btn1.Fill.Color := cor_btn1; rect_btn2.Fill.Color := cor_btn2; self.Show; end; end.
unit UCheckRadioGroupDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSRadioGroup, FMX.TMSBaseControl, FMX.TMSBaseGroup, FMX.TMSCheckGroup, FMX.ListBox, FMX.TMSBitmapContainer, FMX.Objects, FMX.TMSRadioGroupPicker, FMX.TMSCustomPicker, FMX.TMSCheckGroupPicker; type TForm3 = class(TForm) TMSFMXCheckGroup1: TTMSFMXCheckGroup; TMSFMXRadioGroup1: TTMSFMXRadioGroup; GroupBox1: TGroupBox; Label1: TLabel; cbColumns: TComboBox; TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; cbGroupCheck: TCheckBox; cbBitmaps: TCheckBox; Label2: TLabel; Label3: TLabel; TMSFMXCheckGroupPicker1: TTMSFMXCheckGroupPicker; TMSFMXRadioGroupPicker1: TTMSFMXRadioGroupPicker; Label4: TLabel; Label5: TLabel; procedure cbColumnsChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cbGroupCheckChange(Sender: TObject); procedure cbBitmapsChange(Sender: TObject); private { Private declarations } public { Public declarations } procedure SetColumns; procedure SetGroupCheckBox; end; var Form3: TForm3; implementation {$R *.fmx} procedure TForm3.SetColumns; begin TMSFMXCheckGroup1.Columns := cbColumns.ItemIndex + 1; TMSFMXRadioGroup1.Columns := cbColumns.ItemIndex + 1; TMSFMXCheckGroupPicker1.Columns := cbColumns.ItemIndex + 1; TMSFMXRadioGroupPicker1.Columns := cbColumns.ItemIndex + 1; end; procedure TForm3.SetGroupCheckBox; begin TMSFMXCheckGroup1.GroupCheckBox := cbGroupCheck.IsChecked; TMSFMXRadioGroup1.GroupCheckBox := cbGroupCheck.IsChecked; TMSFMXCheckGroupPicker1.GroupCheckBox := cbGroupCheck.IsChecked; end; procedure TForm3.cbBitmapsChange(Sender: TObject); begin if cbBitmaps.IsChecked then begin TMSFMXCheckGroup1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXRadioGroup1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXCheckGroupPicker1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXRadioGroupPicker1.BitmapContainer := TMSFMXBitmapContainer1; end else begin TMSFMXCheckGroup1.BitmapContainer := nil; TMSFMXRadioGroup1.BitmapContainer := nil; TMSFMXCheckGroupPicker1.BitmapContainer := nil; TMSFMXRadioGroupPicker1.BitmapContainer := nil; end; end; procedure TForm3.cbColumnsChange(Sender: TObject); begin SetColumns; end; procedure TForm3.cbGroupCheckChange(Sender: TObject); begin SetGroupCheckBox; end; procedure TForm3.FormCreate(Sender: TObject); var it: TTMSFMXGroupItem; begin TMSFMXRadioGroup1.BeginUpdate; TMSFMXRadioGroup1.Width := 300; TMSFMXRadioGroup1.Height := 185; TMSFMXRadioGroup1.Text := 'Select OS'; TMSFMXRadioGroup1.Items.Clear; it := TMSFMXRadioGroup1.Items.Add; it.Text := 'Windows <b>7</b>'; it := TMSFMXRadioGroup1.Items.Add; it.Text := 'Windows <b>8</b>'; it := TMSFMXRadioGroup1.Items.Add; it.Text := 'Mac OS X'; it := TMSFMXRadioGroup1.Items.Add; it.Text := 'iOS'; it := TMSFMXRadioGroup1.Items.Add; it.Text := 'Android'; SetColumns; SetGroupCheckBox; TMSFMXRadioGroup1.GroupCheckBoxType := TTMSRadioGroupCheckBoxType.ctToggleEnabled; TMSFMXRadioGroup1.GroupCheckBoxChecked := true; TMSFMXRadioGroup1.ItemIndex := 1; TMSFMXRadioGroup1.EndUpdate; TMSFMXCheckGroup1.BeginUpdate; TMSFMXCheckGroup1.Width := 300; TMSFMXCheckGroup1.Height := 185; TMSFMXCheckGroup1.Text := 'Available Browsers'; TMSFMXCheckGroup1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXCheckGroup1.Items.Clear; it := TMSFMXCheckGroup1.Items.Add; it.Text := 'Chrome'; it.BitmapName := 'Chrome'; it := TMSFMXCheckGroup1.Items.Add; it.Text := 'Internet Explorer'; it.BitmapName := 'IE'; it := TMSFMXCheckGroup1.Items.Add; it.Text := 'Firefox'; it.BitmapName := 'Firefox'; it := TMSFMXCheckGroup1.Items.Add; it.Text := 'Opera'; it.BitmapName := 'Opera'; it := TMSFMXCheckGroup1.Items.Add; it.Text := 'Safari'; it.BitmapName := 'Safari'; it := TMSFMXCheckGroup1.Items.Add; it.Text := 'Other'; SetColumns; SetGroupCheckBox; TMSFMXCheckGroup1.GroupCheckBoxType := TTMSCheckGroupCheckBoxType.ctCheckAll; TMSFMXCheckGroup1.GroupCheckBoxChecked := false; TMSFMXCheckGroup1.IsChecked[0] := true; TMSFMXCheckGroup1.IsChecked[4] := true; TMSFMXCheckGroup1.EndUpdate; TMSFMXRadioGroupPicker1.BeginUpdate; TMSFMXRadioGroupPicker1.DropDownAutoSize := true; TMSFMXRadioGroupPicker1.Items.Clear; it := TMSFMXRadioGroupPicker1.Items.Add; it.Text := 'Windows <b>7</b>'; it := TMSFMXRadioGroupPicker1.Items.Add; it.Text := 'Windows <b>8</b>'; it := TMSFMXRadioGroupPicker1.Items.Add; it.Text := 'Mac OS X'; it := TMSFMXRadioGroupPicker1.Items.Add; it.Text := 'iOS'; it := TMSFMXRadioGroupPicker1.Items.Add; it.Text := 'Android'; SetColumns; SetGroupCheckBox; TMSFMXRadioGroupPicker1.ItemIndex := 1; TMSFMXRadioGroupPicker1.EndUpdate; TMSFMXCheckGroupPicker1.BeginUpdate; TMSFMXCheckGroupPicker1.DropDownAutosize := true; TMSFMXCheckGroupPicker1.GroupCheckBoxText := 'Check All'; TMSFMXCheckGroupPicker1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXCheckGroupPicker1.Items.Clear; it := TMSFMXCheckGroupPicker1.Items.Add; it.Text := 'Chrome'; it.BitmapName := 'Chrome'; it := TMSFMXCheckGroupPicker1.Items.Add; it.Text := 'Internet Explorer'; it.BitmapName := 'IE'; it := TMSFMXCheckGroupPicker1.Items.Add; it.Text := 'Firefox'; it.BitmapName := 'Firefox'; it := TMSFMXCheckGroupPicker1.Items.Add; it.Text := 'Opera'; it.BitmapName := 'Opera'; it := TMSFMXCheckGroupPicker1.Items.Add; it.Text := 'Safari'; it.BitmapName := 'Safari'; it := TMSFMXCheckGroupPicker1.Items.Add; it.Text := 'Other'; SetColumns; SetGroupCheckBox; TMSFMXCheckGroupPicker1.GroupCheckBoxType := TTMSFMXPickerGroupCheckBoxType.ctCheckAll; TMSFMXCheckGroupPicker1.GroupCheckBoxChecked := false; TMSFMXCheckGroupPicker1.IsChecked[0] := true; TMSFMXCheckGroupPicker1.IsChecked[4] := true; TMSFMXCheckGroupPicker1.EndUpdate; end; end.
unit Dt_RecalcHLinkFilter; { Описание: Фильтр проверяет и, при необходимости, заменяет адреса гиперссылок.} { Алгоритм: у каждой гиперссылки читается Handle. Если в таблице HLINK имеется хоть одна запись с ID = этот Handle и SourDoc = заданным DocID, то тогда все адреса этой гиперссылки (DestDoc, DestSub) заменяются на адреса, найденные в HLINK (для указанных ID и SourDoc). Иначе - адреса пропускаются без изменений.} { $Id: Dt_RecalcHLinkFilter.pas,v 1.47 2016/06/16 05:40:06 lukyanets Exp $ } // $Log: Dt_RecalcHLinkFilter.pas,v $ // Revision 1.47 2016/06/16 05:40:06 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.46 2014/03/28 06:13:29 dinishev // Bug fix: не собиралось почити ничего. // // Revision 1.45 2013/10/21 15:43:09 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.44 2013/10/21 10:30:56 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.43 2013/10/18 15:38:58 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.42 2013/05/13 17:23:52 lulin // - разборки с упавшими тестами. // // Revision 1.41 2012/08/22 07:28:27 dinishev // Bug fix: отъехали тесты. // // Revision 1.40 2012/08/20 12:32:37 voba // - K: 385977491 // // Revision 1.39 2012/05/17 12:36:35 voba // - k:363574319 // // Revision 1.38 2009/06/23 07:32:59 voba // - стандартизация доступа к атрибутам // // Revision 1.37 2009/03/04 16:26:03 lulin // - <K>: 137470629. Bug fix: не собирался Архивариус. // // Revision 1.36 2008/05/08 14:04:12 fireton // - перенос объектов в потоках из ветки // // Revision 1.35 2008/03/21 14:09:27 lulin // - cleanup. // // Revision 1.34 2008/02/21 16:32:51 lulin // - cleanup. // // Revision 1.33 2008/02/19 11:38:38 lulin // - восстановил компилируемость Архивариуса. // // Revision 1.32 2008/02/14 09:40:39 lulin // - удалён ненужный класс. // // Revision 1.31 2008/02/13 20:20:11 lulin // - <TDN>: 73. // // Revision 1.30 2008/02/13 16:03:08 lulin // - убраны излишне гибкие методы поиска. // // Revision 1.29 2008/02/07 19:13:11 lulin // - избавляемся от излишне универсальных методов базовых списков. // // Revision 1.28 2008/02/06 15:37:06 lulin // - каждому базовому объекту по собственному модулю. // // Revision 1.27 2008/02/05 09:58:05 lulin // - выделяем базовые объекты в отдельные файлы и переносим их на модель. // // Revision 1.26 2008/02/04 11:56:16 lulin // - bug fix: падали при открытии документа в Архивариусе. // // Revision 1.25 2008/02/01 15:14:48 lulin // - избавляемся от излишней универсальности списков. // // Revision 1.24 2007/08/09 18:05:27 lulin // - избавляемся от излишнего использования интерфейсов, т.к. переносимость может быть достигнута другими методами. // // Revision 1.23 2007/08/09 11:19:23 lulin // - cleanup. // // Revision 1.22 2007/04/10 10:37:32 voba // - change Sab to ISab // // Revision 1.21 2006/06/15 09:45:06 voba // -bug fix : не восстанавливались ссылки из таблицы // // Revision 1.20 2006/03/24 14:40:08 fireton // - change: список ссылок набирается не в OpenStream, а в AddAtomEx, когда приезжает DocumentID // // Revision 1.19 2005/03/28 11:32:25 lulin // - интерфейсы переехали в "правильный" модуль. // // Revision 1.18 2005/03/21 10:05:03 lulin // - new interface: _Ik2Type. // // Revision 1.17 2004/09/21 12:04:20 lulin // - Release заменил на Cleanup. // // Revision 1.16 2004/08/26 17:06:30 step // speed optimization // // Revision 1.15 2004/08/03 08:52:51 step // замена dt_def.pas на DtDefine.inc // // Revision 1.14 2004/06/02 08:45:46 law // - удален конструктор Tl3VList.MakePersistentSorted - пользуйтесь _Tl3ObjectRefList.MakeSorted. // // Revision 1.13 2004/05/14 16:58:47 law // - new units: k2TagTerminator, k2TagFilter. // // Revision 1.12 2004/05/14 14:48:59 law // - исправлены префиксы у констант. // // Revision 1.11 2004/05/14 14:29:05 law // - change: TevVariant переименован в Tk2Variant и переехал в k2Types. // // Revision 1.10 2003/12/29 12:39:03 voba // -bug fix: учитывает дополнительные теги (шрифт) внутри ссылки // // Revision 1.9 2003/12/24 11:45:26 step // speed optimization // // Revision 1.8 2003/12/23 15:08:17 step // bug fix: учтен произвольный порядок следования Handle и Addresses // // Revision 1.7 2003/12/22 15:59:59 step // bug fix: сброс флага f_RecalcNeeded перенесен из StartChild в CloseStructure // // Revision 1.6 2003/12/22 14:02:19 step // bug fix: исправлена CloseStructure // // Revision 1.5 2003/12/17 15:01:16 voba // - bug fix // // Revision 1.4 2003/12/17 14:39:30 voba // - speed optimize // // Revision 1.3 2003/12/16 13:13:08 voba // - change: create - заменил reintroduce на override // // Revision 1.2 2003/12/04 12:15:51 step // bug fix: список д.б. сортированым // // Revision 1.1 2003/12/04 10:30:04 step // Новый фильтр для проверки гиперссылок // {$Include DtDefine.inc} interface uses Classes, Contnrs, l3Types, l3Base, l3Variant, l3BaseWithIDList, l3ObjectRefList, k2Prim, k2TagGen, k2Types, k2TagFilter, daTypes, dt_Types; type TRecalcAction = (raUndefined, raPassThru, raReplace); TRecalcHLinksFilter = class(Tk2TagFilter) private f_Family : TdaFamilyID; f_DocID : TDocID; f_Links : Tl3BaseWithIDList; f_Addresses : Tl3ObjectRefList; // флаги f_ExternalDocID : Boolean; // True когда пользователь руками задает DocID, при этом информация из тега игнорируется f_NeedLoadLinks : Boolean; // требуется загрузка списка ссылок f_FoundIndex : Integer; f_LinkId : Longint; f_RecalcAction : TRecalcAction; f_InPara : Boolean; f_InHyperlink : Boolean; f_InAddress : Boolean; // обработчики соотв. событий procedure AfterOpenHyperlink; procedure BeforeCloseHyperLink; procedure BeforeOpenAddress; procedure AfterCloseAddress; procedure FillLinksList; procedure OnReadDocId(const Value: Tk2Variant); procedure OnReadSubId(const Value: Tk2Variant); procedure OnReadHandle(const Value: Tk2Variant); function GetLinks : Tl3BaseWithIDList; function GetAddresses : Tl3ObjectRefList; procedure SetFamily(aValue : TdaFamilyID); procedure SetDocIDPrim(aValue: TDocID); procedure SetDocID(aValue : TDocID); protected procedure Cleanup; override; procedure CloseStructure(NeedUndo: Bool); override; public constructor Create(anOwner: Tk2TagGeneratorOwner = nil); override; procedure OpenStream; override; procedure CloseStream(NeedUndo : Boolean); override; procedure StartChild(TypeID: Tl3VariantDef); override; procedure AddAtomEx(AtomIndex: Long; const Value: Tk2Variant); override; class function SetTo(var theGenerator : Tk2TagGenerator; aDocFamily : TdaFamilyID; aDocID : TDocID): Pointer; overload; property Addresses : Tl3ObjectRefList read GetAddresses; property Links : Tl3BaseWithIDList read GetLinks; property Family : TdaFamilyID read f_Family write SetFamily; property DocID : TDocID read f_DocID write SetDocID; end; implementation uses SysUtils, l3BaseWithID, k2Interfaces, k2Tags, k2Base, Dt_err, Dt_Hyper, Dt_LinkServ, HT_Const, HT_Dll, Math, Address_Const, Hyperlink_Const, TextPara_Const, AnnoTopic_Const, Document_Const ; type THLinkData = class(Tl3BaseWithId) public Doc: TDocID; Sub: TSubID; constructor Create(anId: LongInt; aDoc: TDocID; aSub: TSubID); end; TAddress = class(Tl3Base) public DocId: TDocID; SubId: TSubID; constructor Create; end; constructor TRecalcHLinksFilter.Create(anOwner: Tk2TagGeneratorOwner = nil); begin inherited Create(anOwner); //f_Links := Tl3BaseWithIDList.MakeSorted(l3_dupAccept); //f_Addresses := _TObjectList.Create(True); end; function TRecalcHLinksFilter.GetLinks : Tl3BaseWithIDList; begin if f_Links = nil then f_Links := Tl3BaseWithIDList.MakeSorted(l3_dupAccept); if f_NeedLoadLinks then FillLinksList; Result := f_Links; end; function TRecalcHLinksFilter.GetAddresses : Tl3ObjectRefList; begin if f_Addresses = nil then f_Addresses := Tl3ObjectRefList.Make; Result := f_Addresses; end; procedure TRecalcHLinksFilter.Cleanup; begin //f_Links.Clear; l3Free(f_Links); FreeAndNil(f_Addresses); inherited; end; procedure TRecalcHLinksFilter.CloseStructure(NeedUndo: Bool); var CT : Tk2Type; l_WasInAddress : Boolean; begin l_WasInAddress := false; CT := CurrentType; if f_InAddress and CT.IsKindOf(k2_typAddress) and f_InHyperlink then begin // - закрываем именно адрес ссылки l_WasInAddress := true; f_InAddress := False; end//f_InAddress.. else if f_InHyperlink and CT.IsKindOf(k2_typHyperlink) then begin // - закрываем именно ссылку BeforeCloseHyperLink; f_InHyperlink := False; end//f_InHyperlink else if f_InPara and CT.IsKindOf(k2_typTextPara) then begin // - закрываем именно текстовый параграф // - здесь, например можно добавить что-нибудь к закрываемому параграфу f_InPara := False; end;//f_InPara inherited; if l_WasInAddress then AfterCloseAddress; end; procedure TRecalcHLinksFilter.StartChild(TypeID: Tl3VariantDef); var CT : Tk2Type; begin CT := Tk2Type(TypeID); if CT.IsKindOf(k2_typAddress) and f_InHyperlink then BeforeOpenAddress; inherited; CT := CurrentType; if not f_InPara then f_InPara := CT.IsKindOf(k2_typTextPara) else if not f_InHyperlink then f_InHyperlink := CT.IsKindOf(k2_typHyperlink) else if not f_InAddress then f_InAddress := CT.IsKindOf(k2_typAddress); if f_InHyperlink and not f_InAddress then AfterOpenHyperlink; end; procedure TRecalcHLinksFilter.AddAtomEx(AtomIndex: Long; const Value: Tk2Variant); var lSkipTag : Boolean; begin lSkipTag := False; if f_InHyperlink and not f_InAddress and (AtomIndex = k2_tiHandle) then OnReadHandle(Value); if f_InAddress then case AtomIndex of k2_tiDocID: OnReadDocId(Value); k2_tiSubID: OnReadSubId(Value); k2_tiName : lSkipTag := True; end; if not lSkipTag then inherited; if (not f_ExternalDocID) and (AtomIndex = k2_tiInternalHandle) and (TopType[0].IsKindOf(k2_typDocument) or TopType[0].IsKindOf(k2_typAnnoTopic)) then begin if (Value.Kind = k2_vkInteger) then SetDocIDPrim(TDocID(Value.AsInteger)) else ConvertErrorEx(Value.Kind) end; end; procedure TRecalcHLinksFilter.SetDocID(aValue: TDocID); begin f_ExternalDocID := True; SetDocIDPrim(aValue); end; procedure TRecalcHLinksFilter.SetDocIDPrim(aValue: TDocID); begin if f_DocID <> aValue then begin f_NeedLoadLinks := True; f_DocID := aValue; end; end; procedure TRecalcHLinksFilter.SetFamily(aValue: TdaFamilyID); begin if f_Family <> aValue then begin if StreamOpened then raise EHtErrors.CreateInt(ecNotEnable) else f_Family := aValue; end; end; procedure TRecalcHLinksFilter.CloseStream(NeedUndo: Boolean); begin if f_Links <> nil then f_Links.Clear; inherited; end; procedure TRecalcHLinksFilter.OpenStream; begin inherited; f_InPara :=False; f_InHyperlink :=False; f_InAddress :=False; if f_Addresses <> nil then f_Addresses.Clear; end; { THLinkData } constructor THLinkData.Create(anId: Integer; aDoc: TDocID; aSub: TSubID); begin inherited Create(anId); Doc := aDoc; Sub := aSub; end; { TAddress } constructor TAddress.Create; begin inherited Create; DocId := 0; SubId := 0; end; procedure TRecalcHLinksFilter.AfterCloseAddress; begin if f_RecalcAction in [raUndefined, raReplace] then DecSkipTags; end; procedure TRecalcHLinksFilter.BeforeCloseHyperLink; var l_LinkData : THLinkData; I: Integer; begin if Generator = nil then Exit; if f_RecalcAction = raReplace then for I := f_FoundIndex to Pred(Links.Count) do begin l_LinkData := THLinkData(Links.Items[I]); if (l_LinkData.ID <> f_LinkId) then Break; Generator.StartChild(k2_typAddress); try Generator.AddIntegerAtom(k2_tiDocID, l_LinkData.Doc); Generator.AddIntegerAtom(k2_tiSubID, l_LinkData.Sub); finally Generator.Finish; end; end else for I := 0 to Pred(Addresses.Count) do begin Generator.StartChild(k2_typAddress); try Generator.AddIntegerAtom(k2_tiDocID, TAddress(Addresses.Items[I]).DocId); Generator.AddIntegerAtom(k2_tiSubID, TAddress(Addresses.Items[I]).SubId); finally Generator.Finish; end; end; // for Addresses.Clear; end; procedure TRecalcHLinksFilter.AfterOpenHyperlink; begin f_RecalcAction := raUndefined; f_FoundIndex := -1; f_LinkId := -1; end; procedure TRecalcHLinksFilter.OnReadDocId(const Value: Tk2Variant); begin if f_RecalcAction = raUndefined then if (Value.Kind = k2_vkInteger) and (Addresses.Count > 0) then TAddress(Addresses.Items[Pred(Addresses.Count)]).DocId := Value.AsInteger; end; procedure TRecalcHLinksFilter.OnReadHandle(const Value: Tk2Variant); begin if Value.Kind = k2_vkInteger then begin f_LinkId := Value.AsInteger; if (f_LinkId > 0) and Links.FindData(f_LinkId, f_FoundIndex) then f_RecalcAction := raReplace else f_RecalcAction := raPassThru; end; end; procedure TRecalcHLinksFilter.OnReadSubId(const Value: Tk2Variant); begin if f_RecalcAction = raUndefined then if (Value.Kind = k2_vkInteger) and (Addresses.Count > 0) then TAddress(Addresses.Items[Pred(Addresses.Count)]).SubId := Value.AsInteger; end; procedure TRecalcHLinksFilter.BeforeOpenAddress; var l_A : TAddress; begin if (f_RecalcAction in [raUndefined, raReplace]) then IncSkipTags; if f_RecalcAction = raUndefined then begin l_A := TAddress.Create; try Addresses.Add(l_A); // вставка пустого адреса (наполним при чтении DocId и SubId) finally FreeAndNil(l_A); end;//try..finally end;// end; procedure TRecalcHLinksFilter.FillLinksList; const hlFldCount = 4; hlFldArr: array[1..hlFldCount] of SmallInt = (hlID_fld, hlSourD_fld, hlDestD_fld, hlDestS_fld); var l_LinksSab : Sab; l_pLinkRec : PHyperLinkRec; l_Item : THLinkData; l_Buffer : PChar; l_BufferSize: Integer; l_BytesInBuffer: Integer; I: Integer; begin // набираем в список f_Links все линки для документа DocID if (f_Family <> 0) and (f_DocID <> 0) then begin l_LinksSab := LinkServer(f_Family).HLinkTbl.GetHListOnDoc(f_DocID).HTSab; // уже отсортированные по Id f_Links.Clear; if l_LinksSab.gFoundCnt > 0 then begin Ht(htOpenResults(l_LinksSab, ROPEN_READ, @hlFldArr, hlFldCount)); try l_BufferSize := Min(MAX_BUF_LEN, l_LinksSab.gFoundCnt * SizeOf(THyperLinkRec)); l3System.GetLocalMem(l_Buffer, l_BufferSize); try repeat l_BytesInBuffer := htReadResults(l_LinksSab, l_Buffer, l_BufferSize); for I := 0 to (l_BytesInBuffer div SizeOf(THyperLinkRec)) - 1 do begin l_pLinkRec := PHyperLinkRec(l_Buffer + I * SizeOf(THyperLinkRec)); if l_pLinkRec^.ID <> 0 then begin l_Item := THLinkData.Create(l_pLinkRec^.ID, l_pLinkRec^.DDoc, l_pLinkRec^.DSub); try f_Links.Add(l_Item); finally l3Free(l_Item); end; end; // if end; // for until l_BytesInBuffer = 0; finally l3System.FreeLocalMem(l_Buffer); end; finally htCloseResults(l_LinksSab); end; end; end; f_NeedLoadLinks := False; end; class function TRecalcHLinksFilter.SetTo(var theGenerator : Tk2TagGenerator; aDocFamily : TdaFamilyID; aDocID : TDocID): Pointer; begin Result := inherited SetTo(theGenerator); with (theGenerator as TRecalcHLinksFilter) do begin Family := aDocFamily; DocID := aDocID; end; end; end.
unit PermGroups; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, AdvGrid, FFSAdvStringGrid, StdCtrls, Buttons, ActnList, InputDialog, sBitBtn, AdvUtil, System.Actions, AdvObj, BaseGrid; type TfrmPermGroups = class(TForm) grdList: TFFSAdvStringGrid; ActionList1: TActionList; actNew: TAction; actEdit: TAction; actDelete: TAction; idName: TInputDialog; btnNew: TsBitBtn; btnEdit: TsBitBtn; btnDel: TsBitBtn; btnClose: TsBitBtn; procedure FormShow(Sender: TObject); procedure actNewExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure grdListMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure grdListMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); private { Private declarations } sl : TStringList; currname : string; procedure EditPermission; procedure LoadList; public { Public declarations } constructor create(AOwner:TComponent);override; destructor destroy;override; end; var frmPermGroups: TfrmPermGroups; implementation uses datamod, PermEdit, ffsutils,TicklerTypes; {$R *.DFM} constructor TfrmPermGroups.create(AOwner: TComponent); begin inherited; sl := TStringList.create; end; destructor TfrmPermGroups.destroy; begin sl.free; inherited; end; procedure TfrmPermGroups.FormShow(Sender: TObject); begin LoadList; end; procedure TfrmPermGroups.LoadList; var x : integer; begin sl.CommaText := Daapi.PermGrpGetNameList; sl.delete(0); if sl.Count = 0 then grdList.rowcount := 2 else grdList.rowcount := sl.count + 1; grdList.ClearRows(1,1); for x := 0 to sl.count - 1 do grdList.cells[0,x+1] := sl[x]; grdList.FitLastColumn; end; procedure TfrmPermGroups.actNewExecute(Sender: TObject); var x : integer; found : boolean; begin idname.Text := ''; found := false; if idName.Execute then begin for x := 1 to grdList.rowcount - 1 do begin if grdList.cells[0,x] = idname.Text then begin found := true; break; end; end; if found then begin TrMsgInformation('The group name you entered alreay exists. Please choose a unique name.'); exit; end; currname := idName.Text; EditPermission; end; LoadList; end; procedure TfrmPermGroups.actEditExecute(Sender: TObject); begin currname := grdList.cells[0,grdList.row]; EditPermission; end; procedure TfrmPermGroups.EditPermission; begin frmPermEdit := TfrmPermEdit.Create(self); frmPermEdit.Caption := 'Modify Permissions: ' + currName; frmPermEdit.bufPerm.Data.PRights := daapi.PermGrpGetRights(CurrName); if frmPermEdit.ShowModal = mrOk then daapi.PermGrpSetRights(CurrName, frmPermEdit.BufPerm.data.PRights); frmPermEdit.free; end; procedure TfrmPermGroups.actDeleteExecute(Sender: TObject); begin currname := grdList.Cells[0,grdList.row]; if trim(currname) = '' then exit; if TrMsgConfirmation('Delete this permission group?') = ID_yes then daapi.PermGrpDelGroup(currname); LoadList; end; procedure TfrmPermGroups.grdListMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdList.SetFocus; end; procedure TfrmPermGroups.grdListMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdList.SetFocus; end; end.
(*!------------------------------------------------------------ * [[APP_NAME]] ([[APP_URL]]) * * @link [[APP_REPOSITORY_URL]] * @copyright Copyright (c) [[COPYRIGHT_YEAR]] [[COPYRIGHT_HOLDER]] * @license [[LICENSE_URL]] ([[LICENSE]]) *------------------------------------------------------------- *) unit UserController; interface {$MODE OBJFPC} {$H+} uses fano; type (*!----------------------------------------------- * controller that handle route : * /user * * See Routes/User/routes.inc * * @author [[AUTHOR_NAME]] <[[AUTHOR_EMAIL]]> *------------------------------------------------*) TUserController = class(TController) private fUserModel : IModelReader; public constructor create( const view : IView; const params : IViewParameters; const userModel : IModelReader ); destructor destroy(); override; function handleRequest( const request : IRequest; const response : IResponse; const args : IRouteArgsReader ) : IResponse; override; end; implementation constructor TUserController.create( const view : IView; const params : IViewParameters; const userModel : IModelReader ); begin inherited create(view, params); fUserModel := userModel; end; destructor TUserController.destroy(); begin fUserModel := nil; inherited destroy(); end; function TUserController.handleRequest( const request : IRequest; const response : IResponse; const args : IRouteArgsReader ) : IResponse; begin fUserModel.read(); result := inherited handleRequest(request, response, args); end; end.
unit ce_projinspect; {$I ce_defines.inc} interface uses Classes, SysUtils, FileUtil, TreeFilterEdit, Forms, Controls, Graphics, actnlist, Dialogs, ExtCtrls, ComCtrls, Menus, Buttons, lcltype, ce_project, ce_interfaces, ce_common, ce_widget, ce_observer; type TCEProjectInspectWidget = class(TCEWidget, ICEProjectObserver) btnRemFold: TSpeedButton; imgList: TImageList; pnlToolBar: TPanel; btnAddFile: TSpeedButton; btnProjOpts: TSpeedButton; btnAddFold: TSpeedButton; btnRemFile: TSpeedButton; Tree: TTreeView; TreeFilterEdit1: TTreeFilterEdit; procedure btnAddFileClick(Sender: TObject); procedure btnAddFoldClick(Sender: TObject); procedure btnRemFileClick(Sender: TObject); procedure btnRemFoldClick(Sender: TObject); procedure FormDropFiles(Sender: TObject; const FileNames: array of String); procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeSelectionChanged(Sender: TObject); protected procedure updateImperative; override; procedure updateDelayed; override; procedure SetVisible(Value: boolean); override; private fActOpenFile: TAction; fActSelConf: TAction; fProject: TCEProject; fFileNode, fConfNode: TTreeNode; fImpsNode, fInclNode: TTreeNode; fXtraNode: TTreeNode; fLastFileOrFolder: string; procedure actUpdate(sender: TObject); procedure TreeDblClick(sender: TObject); procedure actOpenFileExecute(sender: TObject); // procedure projNew(aProject: TCEProject); procedure projClosing(aProject: TCEProject); procedure projFocused(aProject: TCEProject); procedure projChanged(aProject: TCEProject); procedure projCompiling(aProject: TCEProject); protected function contextName: string; override; function contextActionCount: integer; override; function contextAction(index: integer): TAction; override; public constructor create(aOwner: TComponent); override; destructor destroy; override; end; implementation {$R *.lfm} uses ce_symstring; {$REGION Standard Comp/Obj------------------------------------------------------} constructor TCEProjectInspectWidget.create(aOwner: TComponent); var png: TPortableNetworkGraphic; begin fActOpenFile := TAction.Create(self); fActOpenFile.Caption := 'Open file in editor'; fActOpenFile.OnExecute := @actOpenFileExecute; fActSelConf := TAction.Create(self); fActSelConf.Caption := 'Select configuration'; fActSelConf.OnExecute := @actOpenFileExecute; fActSelConf.OnUpdate := @actUpdate; // inherited; // png := TPortableNetworkGraphic.Create; try png.LoadFromLazarusResource('document_add'); btnAddFile.Glyph.Assign(png); png.LoadFromLazarusResource('document_delete'); btnRemFile.Glyph.Assign(png); png.LoadFromLazarusResource('folder_add'); btnAddFold.Glyph.Assign(png); png.LoadFromLazarusResource('folder_delete'); btnRemFold.Glyph.Assign(png); png.LoadFromLazarusResource('wrench_orange'); btnProjOpts.Glyph.Assign(png); finally png.Free; end; // Tree.OnDblClick := @TreeDblClick; fFileNode := Tree.Items[0]; fConfNode := Tree.Items[1]; fImpsNode := Tree.Items[2]; fInclNode := Tree.Items[3]; fXtraNode := Tree.Items[4]; // Tree.PopupMenu := contextMenu; // EntitiesConnector.addObserver(self); end; destructor TCEProjectInspectWidget.destroy; begin EntitiesConnector.removeObserver(self); inherited; end; procedure TCEProjectInspectWidget.SetVisible(Value: boolean); begin inherited; if Value then updateImperative; end; {$ENDREGION} {$REGION ICEContextualActions---------------------------------------------------} function TCEProjectInspectWidget.contextName: string; begin exit('Inspector'); end; function TCEProjectInspectWidget.contextActionCount: integer; begin exit(2); end; function TCEProjectInspectWidget.contextAction(index: integer): TAction; begin case index of 0: exit(fActOpenFile); 1: exit(fActSelConf); else exit(nil); end; end; procedure TCEProjectInspectWidget.actOpenFileExecute(sender: TObject); begin TreeDblClick(sender); end; {$ENDREGION} {$REGION ICEProjectMonitor -----------------------------------------------------} procedure TCEProjectInspectWidget.projNew(aProject: TCEProject); begin fProject := aProject; fLastFileOrFolder := ''; if Visible then updateImperative; end; procedure TCEProjectInspectWidget.projClosing(aProject: TCEProject); begin if fProject <> aProject then exit; fProject := nil; fLastFileOrFolder := ''; updateImperative; end; procedure TCEProjectInspectWidget.projFocused(aProject: TCEProject); begin fProject := aProject; if Visible then beginDelayedUpdate; end; procedure TCEProjectInspectWidget.projChanged(aProject: TCEProject); begin if fProject <> aProject then exit; if Visible then beginDelayedUpdate; end; procedure TCEProjectInspectWidget.projCompiling(aProject: TCEProject); begin end; {$ENDREGION} {$REGION Inspector things -------------------------------------------------------} procedure TCEProjectInspectWidget.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then TreeDblClick(nil); end; procedure TCEProjectInspectWidget.TreeSelectionChanged(Sender: TObject); begin actUpdate(sender); if fProject = nil then exit; if Tree.Selected = nil then exit; if (Tree.Selected.Parent = fFileNode) then fLastFileOrFolder := fProject.getAbsoluteFilename(tree.Selected.Text) else fLastFileOrFolder := tree.Selected.Text; end; procedure TCEProjectInspectWidget.TreeDblClick(sender: TObject); var fname: string; i: NativeInt; begin if fProject = nil then exit; if Tree.Selected = nil then exit; // if (Tree.Selected.Parent = fFileNode) or (Tree.Selected.Parent = fXtraNode) then begin fname := Tree.Selected.Text; i := fProject.Sources.IndexOf(fname); if i > -1 then fname := fProject.getAbsoluteSourceName(i); if dExtList.IndexOf(ExtractFileExt(fname)) <> -1 then if fileExists(fname) then getMultiDocHandler.openDocument(fname); end else if Tree.Selected.Parent = fConfNode then begin i := Tree.Selected.Index; fProject.ConfigurationIndex := i; beginDelayedUpdate; end; end; procedure TCEProjectInspectWidget.actUpdate(sender: TObject); begin fActSelConf.Enabled := false; fActOpenFile.Enabled := false; if Tree.Selected = nil then exit; fActSelConf.Enabled := Tree.Selected.Parent = fConfNode; fActOpenFile.Enabled := Tree.Selected.Parent = fFileNode; end; procedure TCEProjectInspectWidget.btnAddFileClick(Sender: TObject); begin if fProject = nil then exit; // with TOpenDialog.Create(nil) do try if FileExists(fLastFileOrFolder) then InitialDir := ExtractFilePath(fLastFileOrFolder) else if DirectoryExists(fLastFileOrFolder) then InitialDir := fLastFileOrFolder; filter := DdiagFilter; if execute then begin fProject.beginUpdate; fProject.addSource(filename); fProject.endUpdate; end; finally free; end; end; procedure TCEProjectInspectWidget.btnAddFoldClick(Sender: TObject); var dir, fname, ext: string; lst: TStringList; i: NativeInt; begin if fProject = nil then exit; // dir := ''; if FileExists(fLastFileOrFolder) then dir := extractFilePath(fLastFileOrFolder) else if DirectoryExists(fLastFileOrFolder) then dir := fLastFileOrFolder else if fileExists(fProject.fileName) then dir := extractFilePath(fProject.fileName); if selectDirectory('sources', dir, dir, true, 0) then begin fProject.beginUpdate; lst := TStringList.Create; try listFiles(lst, dir, true); for i := 0 to lst.Count-1 do begin fname := lst.Strings[i]; ext := extractFileExt(fname); if dExtList.IndexOf(ext) <> -1 then fProject.addSource(fname); end; finally lst.Free; fProject.endUpdate; end; end; end; procedure TCEProjectInspectWidget.btnRemFoldClick(Sender: TObject); var dir, fname: string; i: Integer; begin if fProject = nil then exit; if Tree.Selected = nil then exit; if Tree.Selected.Parent <> fFileNode then exit; // fname := Tree.Selected.Text; i := fProject.Sources.IndexOf(fname); if i = -1 then exit; fname := fProject.getAbsoluteSourceName(i); dir := extractFilePath(fname); if not DirectoryExists(dir) then exit; // fProject.beginUpdate; for i:= fProject.Sources.Count-1 downto 0 do if extractFilePath(fProject.getAbsoluteSourceName(i)) = dir then fProject.Sources.Delete(i); fProject.endUpdate; end; procedure TCEProjectInspectWidget.btnRemFileClick(Sender: TObject); var fname: string; i: NativeInt; begin if fProject = nil then exit; if Tree.Selected = nil then exit; // if Tree.Selected.Parent = fFileNode then begin fname := Tree.Selected.Text; i := fProject.Sources.IndexOf(fname); if i > -1 then begin fProject.beginUpdate; fProject.Sources.Delete(i); fProject.endUpdate; end; end; end; procedure TCEProjectInspectWidget.FormDropFiles(Sender: TObject; const FileNames: array of String); procedure addFile(const aFilename: string); var ext: string; begin ext := ExtractFileExt(aFilename); if (dExtList.IndexOf(ext) = -1) and (ext <> '.obj') and (ext <> '.o') and (ext <> '.a') and (ext <> '.lib') then exit; fProject.addSource(aFilename); if (dExtList.IndexOf(ext) <> -1) then getMultiDocHandler.openDocument(aFilename); end; var fname, direntry: string; lst: TStringList; begin if fProject = nil then exit; lst := TStringList.Create; fProject.beginUpdate; try for fname in Filenames do if FileExists(fname) then addFile(fname) else if DirectoryExists(fname) then begin lst.Clear; listFiles(lst, fname, true); for direntry in lst do addFile(dirEntry); end; finally fProject.endUpdate; lst.Free; end; end; procedure TCEProjectInspectWidget.updateDelayed; begin updateImperative; end; procedure TCEProjectInspectWidget.updateImperative; var src, fold, conf: string; lst: TStringList; itm: TTreeNode; hasProj: boolean; i: NativeInt; begin fConfNode.DeleteChildren; fFileNode.DeleteChildren; fImpsNode.DeleteChildren; fInclNode.DeleteChildren; fXtraNode.DeleteChildren; // hasProj := fProject <> nil; pnlToolBar.Enabled := hasProj; if not hasProj then exit; // Tree.BeginUpdate; // display main sources for src in fProject.Sources do begin itm := Tree.Items.AddChild(fFileNode, src); itm.ImageIndex := 2; itm.SelectedIndex := 2; end; // display configurations for i := 0 to fProject.OptionsCollection.Count-1 do begin conf := fProject.configuration[i].name; if i = fProject.ConfigurationIndex then conf += ' (active)'; itm := Tree.Items.AddChild(fConfNode, conf); itm.ImageIndex := 3; itm.SelectedIndex:= 3; end; // display Imports (-J) for fold in FProject.currentConfiguration.pathsOptions.importStringPaths do begin if fold = '' then continue; fold := fProject.getAbsoluteFilename(fold); fold := symbolExpander.get(fold); itm := Tree.Items.AddChild(fImpsNode, fold); itm.ImageIndex := 5; itm.SelectedIndex := 5; end; fImpsNode.Collapse(false); // display Includes (-I) for fold in FProject.currentConfiguration.pathsOptions.importModulePaths do begin if fold = '' then continue; fold := fProject.getAbsoluteFilename(fold); fold := symbolExpander.get(fold); itm := Tree.Items.AddChild(fInclNode, fold); itm.ImageIndex := 5; itm.SelectedIndex := 5; end; fInclNode.Collapse(false); // display extra sources (external .lib, *.a, *.d) for src in FProject.currentConfiguration.pathsOptions.extraSources do begin if src = '' then continue; src := fProject.getAbsoluteFilename(src); src := symbolExpander.get(src); lst := TStringList.Create; try if listAsteriskPath(src, lst) then for src in lst do begin itm := Tree.Items.AddChild(fXtraNode, src); itm.ImageIndex := 2; itm.SelectedIndex := 2; end else begin itm := Tree.Items.AddChild(fXtraNode, src); itm.ImageIndex := 2; itm.SelectedIndex := 2; end; finally lst.Free; end; end; fXtraNode.Collapse(false); Tree.EndUpdate; end; {$ENDREGION --------------------------------------------------------------------} end.
unit MFichas.Model.Permissoes.Interfaces; interface uses MFichas.Model.Entidade.USUARIOPERMISSOES, ORMBR.Container.ObjectSet.Interfaces; type iModelPermissoes = interface; iModelPermissoesEditar = interface; iModelPermissoesLista = interface; iModelPermissoes = interface ['{10B0BC27-5241-4CDF-A08A-4A82EF6C97DD}'] function ListaDePermissoes: iModelPermissoesLista; function EditarPermissoes : iModelPermissoesEditar; function DAO : iContainerObjectSet<TUSUARIOPERMISSOES>; end; iModelPermissoesEditar = interface ['{CCC73878-CBEE-4A28-ABDB-6A114102BE28}'] function AbrirCaixa(ABoolean: Integer) : iModelPermissoesEditar; function FecharCaixa(ABoolean: Integer) : iModelPermissoesEditar; function Suprimento(ABoolean: Integer) : iModelPermissoesEditar; function Sangria(ABoolean: Integer) : iModelPermissoesEditar; function CadastrarProdutos(ABoolean: Integer) : iModelPermissoesEditar; function CadastrarGrupos(ABoolean: Integer) : iModelPermissoesEditar; function CadastrarUsuarios(ABoolean: Integer) : iModelPermissoesEditar; function AcessarRelatorios(ABoolean: Integer) : iModelPermissoesEditar; function AcessarConfiguracoes(ABoolean: Integer) : iModelPermissoesEditar; function ExcluirProdutosPosImpressao(ABoolean: Integer): iModelPermissoesEditar; function Executar : iModelPermissoesEditar; function &End : iModelPermissoes; end; iModelPermissoesLista = interface ['{2A53116B-5568-444E-B011-04B74238D1E8}'] function AbrirCaixa : Integer; function FecharCaixa : Integer; function Suprimento : Integer; function Sangria : Integer; function CadastrarProdutos : Integer; function CadastrarGrupos : Integer; function CadastrarUsuarios : Integer; function AcessarRelatorios : Integer; function AcessarConfiguracoes : Integer; function ExcluirProdutosPosImpressao: Integer; function &End : iModelPermissoes; end; implementation end.
unit uCadastroUsuario; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrmPadrao, Data.DB, Vcl.ComCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.DBCtrls, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Mask, Vcl.Grids, Vcl.DBGrids,cAcaoAcesso,uFuncaoLogin,uEnun,uDtmPrincipal; type TfrmCadUsuario = class(TfrmPadrao) edtCodigo: TLabeledEdit; lblLogin: TLabeledEdit; edtNome: TLabeledEdit; edtSenha: TLabeledEdit; edtSenha2: TLabeledEdit; edtSetor: TLabeledEdit; cbTipo: TComboBox; Label1: TLabel; zqPrincipalNOME: TWideStringField; zqPrincipalACESSO_ID: TIntegerField; zqPrincipalLOGIN: TWideStringField; zqPrincipalSENHA: TWideStringField; zqPrincipalTIPO: TWideStringField; zqPrincipalSETOR: TWideStringField; procedure btnAlterarClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnInserirClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtSenha2Exit(Sender: TObject); private vUsuario:TUsuario; function Gravar(EstadoDoCadastro:TEstadoCadastro):boolean; override; function Apagar:Boolean; override; { Private declarations } public { Public declarations } end; var frmCadUsuario: TfrmCadUsuario; implementation {$R *.dfm} { TfrmCadUsuario } function TfrmCadUsuario.Apagar: Boolean; begin if vUsuario.Selecionar(zqPrincipal.FieldByName('Acesso_id').AsInteger) then begin Result:=vUsuario.Apagar; end; end; procedure TfrmCadUsuario.btnAlterarClick(Sender: TObject); begin if vUsuario.Selecionar(zqPrincipal.FieldByName('Acesso_id').AsInteger) then begin edtCodigo.Text:=IntToStr(vUsuario.codigo); lblLogin.Text :=vUsuario.Login; edtSenha.Text :=vUsuario.senha; edtNome.Text :=vUsuario.nome; // edtSetor.text :=vUsuario.Setor; // cbTipo.text :=Vusuario.tipo; end else begin btnCancelar.Click; Abort; end; inherited; end; procedure TfrmCadUsuario.btnGravarClick(Sender: TObject); begin if vUsuario.UsuarioExiste(lblLogin.Text) then begin MessageDlg('Usuário já cadastrado', mtInformation, [mbok],0); lblLogin.SetFocus; abort; end; if edtCodigo.Text<>EmptyStr then vUsuario.codigo:=StrToInt(edtCodigo.Text) else vUsuario.codigo:=0; vUsuario.Login :=lblLogin.Text; vUsuario.senha:=edtSenha.Text; vUsuario.Nome := EdtNome.Text; vUsuario.Tipo := cbTipo.text; vUsuario.Setor := edtSetor.text; inherited; end; procedure TfrmCadUsuario.btnInserirClick(Sender: TObject); begin inherited; lblLogin.SetFocus; end; procedure TfrmCadUsuario.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if Assigned(vUsuario) then FreeAndNil(vUsuario); zqPrincipal.Close; end; procedure TfrmCadUsuario.FormCreate(Sender: TObject); begin inherited; vUsuario:=TUsuario.Create(DtmPrincipal.ConexaoDB); IndiceAtual:='nome'; end; procedure TfrmCadUsuario.FormShow(Sender: TObject); begin inherited; zqPrincipal.Open; end; function TfrmCadUsuario.Gravar(EstadoDoCadastro: TEstadoCadastro): boolean; begin if EstadoDoCadastro=ecInserir then Result:= vUsuario.Inserir else if EstadoDoCadastro=ecAlterar then Result:= vUsuario.Atualizar; TAcaoAcesso.PreencherUsuariosVsAcoes(DtmPrincipal.ConexaoDB); end; procedure TfrmCadUsuario.edtSenha2Exit(Sender: TObject); begin inherited; if edtSenha.Text <> edtSenha2.text then ShowMessage('Senha precisam ser iguais!'); end; end.
unit EULA_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Common/Forms/EULA_Form.pas" // Начат: 24.08.2009 20:35 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMFinalForm::Class>> F1 Core::Common::View::Common::PrimF1Common::EULA // // Условия использования // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses Classes {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmUserControls {$IfEnd} //not NoVCM , PrimEULA_Form, l3StringIDEx {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwInteger {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , EULA_ut_EULA_UserType, vtLabel, vtButton, eeMemoWithEditOperations, l3InterfacedComponent {a}, vcmComponent {a}, vcmBaseEntities {a}, vcmEntities {a}, vcmExternalInterfaces {a}, vcmEntityForm {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} const { EULAIDs } fm_efEULA : TvcmFormDescriptor = (rFormID : (rName : 'efEULA'; rID : 0); rFactory : nil); { Идентификатор формы TefEULA } type EULAFormDef = interface(IUnknown) {* Идентификатор формы EULA } ['{DF5FBE77-74EC-44AD-8636-CBFDE4947FC7}'] end;//EULAFormDef TefEULA = {final form} class(TvcmEntityFormRef, EULAFormDef) {* Условия использования } Entities : TvcmEntities; protected procedure MakeControls; override; end;//TefEULA TEULAForm = TefEULA; {$IfEnd} //not Admin AND not Monitorings implementation {$R *.DFM} {$If not defined(Admin) AND not defined(Monitorings)} uses SysUtils {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts , l3MessageID ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} var { Локализуемые строки ut_EULALocalConstants } str_ut_EULACaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ut_EULACaption'; rValue : 'Условия использования'); { Заголовок пользовательского типа "Условия использования" } type Tkw_Form_EULA = class(TtfwControlString) {* Слово словаря для идентификатора формы EULA ---- *Пример использования*: [code] 'aControl' форма::EULA TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_EULA // start class Tkw_Form_EULA {$If not defined(NoScripts)} function Tkw_Form_EULA.GetString: AnsiString; {-} begin Result := 'efEULA'; end;//Tkw_Form_EULA.GetString {$IfEnd} //not NoScripts type Tkw_EULA_ShellCaptionLabel_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола ShellCaptionLabel формы EULA } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_EULA_ShellCaptionLabel_ControlInstance // start class Tkw_EULA_ShellCaptionLabel_ControlInstance {$If not defined(NoScripts)} procedure Tkw_EULA_ShellCaptionLabel_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TefEULA).ShellCaptionLabel); end;//Tkw_EULA_ShellCaptionLabel_ControlInstance.DoDoIt {$IfEnd} //not NoScripts type Tkw_EULA_OkButton_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола OkButton формы EULA } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_EULA_OkButton_ControlInstance // start class Tkw_EULA_OkButton_ControlInstance {$If not defined(NoScripts)} procedure Tkw_EULA_OkButton_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TefEULA).OkButton); end;//Tkw_EULA_OkButton_ControlInstance.DoDoIt {$IfEnd} //not NoScripts type Tkw_EULA_eeMemoWithEditOperations1_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола eeMemoWithEditOperations1 формы EULA } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_EULA_eeMemoWithEditOperations1_ControlInstance // start class Tkw_EULA_eeMemoWithEditOperations1_ControlInstance {$If not defined(NoScripts)} procedure Tkw_EULA_eeMemoWithEditOperations1_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TefEULA).eeMemoWithEditOperations1); end;//Tkw_EULA_eeMemoWithEditOperations1_ControlInstance.DoDoIt {$IfEnd} //not NoScripts procedure TefEULA.MakeControls; begin inherited; with AddUsertype(ut_EULAName, str_ut_EULACaption, str_ut_EULACaption, false, -1, -1, '', nil, nil, nil, vcm_ccNone) do begin end;//with AddUsertype(ut_EULAName end; {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация фабрики формы EULA fm_efEULA.SetFactory(TefEULA.Make); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Form_EULA Tkw_Form_EULA.Register('форма::EULA', TefEULA); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_EULA_ShellCaptionLabel_ControlInstance TtfwScriptEngine.GlobalAddWord('.TefEULA.ShellCaptionLabel', Tkw_EULA_ShellCaptionLabel_ControlInstance); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_EULA_OkButton_ControlInstance TtfwScriptEngine.GlobalAddWord('.TefEULA.OkButton', Tkw_EULA_OkButton_ControlInstance); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_EULA_eeMemoWithEditOperations1_ControlInstance TtfwScriptEngine.GlobalAddWord('.TefEULA.eeMemoWithEditOperations1', Tkw_EULA_eeMemoWithEditOperations1_ControlInstance); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ut_EULACaption str_ut_EULACaption.Init; {$IfEnd} //not Admin AND not Monitorings end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, jpeg, ExtCtrls, StdCtrls, Spin; type TformCalsLost = class(TForm) imgRun: TImage; spinJogging: TSpinEdit; spinRowing: TSpinEdit; lblJoggin: TLabel; lblRowing: TLabel; lblTitle: TLabel; btnCalc: TButton; btnReset: TButton; btnAddNote: TButton; edtResultGrams: TEdit; lblResultGrams: TLabel; memNotes: TMemo; edtResultKG: TEdit; lblResultKG: TLabel; procedure btnCalcClick(Sender: TObject); procedure btnAddNoteClick(Sender: TObject); private { Private declarations } public { Public declarations } Function AddGrams(agJoggingHours,agRowingHours : Real) : Real; Procedure AddNote; end; var formCalsLost: TformCalsLost; implementation {$R *.dfm} {************* AddGrams *************} function TformCalsLost.AddGrams(agJoggingHours, agRowingHours: Real): Real; var // Declare required Vars TotalCal, GramsLost : Integer; begin // Calculate Total cals TotalCal := Round(agJoggingHours * 200) + Round(agRowingHours * 475); // Calculate Grams Lost Gramslost := TotalCal * 10 DIV 77; // Return Grams lost as function result Result := GramsLost; end; {************* AddNote *************} procedure TformCalsLost.AddNote; Var // Declare required Vars tmpNote : String; tmpDate : String; begin // Set Defualt Values tmpDate := DateTimeToStr(Now); // Get Required input from user tmpNote := InputBox('Cal Cals Lost','Add Personal Comment?',''); // Check if user entered valid input If (tmpNote <> '') Then Begin // Display user input formCalsLost.memNotes.Lines.Add(tmpDate); formCalsLost.memNotes.Lines.Add(tmpNote); formCalsLost.memNotes.Lines.Add('***********'); End Else Begin // Inform user if input not correct ShowMessage('Note can''t be blank!'); End; end; procedure TformCalsLost.btnCalcClick(Sender: TObject); Var GramsLost : Real; begin GramsLost := AddGrams(formCalsLost.spinJogging.Value,formCalsLost.spinRowing.Value); edtResultGrams.Text := FloatToStr(GramsLost) + ' GRAMS'; edtResultKG.Text := FloatToStr(GramsLost/1000) + ' KG'; end; procedure TformCalsLost.btnAddNoteClick(Sender: TObject); begin AddNote; end; end.
unit uClasse.Veiculo.Terrestre; interface uses uClasse.Veiculo, System.SysUtils; type TTerrestre = class(TVeiculo) private public Valor_Pedagio : currency; Tipo_tracao: string; IPVA: Currency; DPVAT: Currency; Habilitacao: string; placa: string; km_percorridos: double; end; implementation { TTerrestre } end.
{ Copyright (C) <2005> <Andrew Haines> chmtypes.pas This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } { See the file COPYING.FPC, included in this distribution, for details about the copyright. } unit chmtypes; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TSectionName = (snMSCompressed, snUnCompressed); TSectionNames = set of TSectionName; { TDirectoryChunk } TDirectoryChunk = class(TObject) private FHeaderSize: Integer; FQuickRefEntries: Word; Buffer: array[0..$1000-1] of byte; CurrentPos: Integer; FItemCount: Word; FClearCount: Integer; public function CanHold(ASize: Integer): Boolean; function FreeSpace: Integer; procedure WriteHeader(AHeader: Pointer); procedure WriteEntry(Size: Integer; Data: Pointer); procedure WriteChunkToStream(Stream: TStream); overload; procedure Clear; property ItemCount: Word read FItemCount; constructor Create(AHeaderSize: Integer); end; { TPMGIDirectoryChunk } TPMGIDirectoryChunk = class(TDirectoryChunk) private FChunkLevelCount: Integer; FParentChunk: TPMGIDirectoryChunk; public procedure WriteChunkToStream(Stream: TStream; var AIndex: Integer; Final: Boolean = False); overload; property ParentChunk: TPMGIDirectoryChunk read FParentChunk write FParentChunk; property ChunkLevelCount: Integer read FChunkLevelCount write FChunkLevelCount; end; PFileEntryRec = ^TFileEntryRec; TFileEntryRec = record Path: String; Name: String; DecompressedOffset: QWord; DecompressedSize: QWord; Compressed: Boolean; // True means it goes in section1 False means section0 end; { TFileEntryList } TFileEntryList = class(TList) private FPaths: TStringList; function GetFileEntry(Index: Integer): TFileEntryRec; procedure SetFileEntry(Index: Integer; const AValue: TFileEntryRec); public function AddEntry(AFileEntry: TFileEntryRec; CheckPathIsAdded: Boolean = True): Integer; procedure Delete(Index: Integer); property FileEntry[Index: Integer]: TFileEntryRec read GetFileEntry write SetFileEntry; procedure Sort; constructor Create; destructor Destroy; override; end; TTOCIdxHeader = record BlockSize: DWord; // 4096 EntriesOffset: DWord; EntriesCount: DWord; TopicsOffset: DWord; EmptyBytes: array[0..4079] of byte; end; const TOC_ENTRY_HAS_NEW = 2; TOC_ENTRY_HAS_CHILDREN = 4; TOC_ENTRY_HAS_LOCAL = 8; type PTOCEntryPageBookInfo = ^TTOCEntryPageBookInfo; TTOCEntryPageBookInfo = record Unknown1: Word; // = 0 EntryIndex: Word; // multiple entry info's can have this value but the TTocEntry it points to points back to the first item with this number. Wierd. Props: DWord; // BitField. See TOC_ENTRY_* TopicsIndexOrStringsOffset: DWord; // if TOC_ENTRY_HAS_LOCAL is in props it's the Topics Index // else it's the Offset In Strings of the Item Text ParentPageBookInfoOffset: DWord; NextPageBookOffset: DWord; // same level of tree only // Only if TOC_ENTRY_HAS_CHILDREN is set are these written FirstChildOffset: DWord; Unknown3: DWord; // = 0 end; TTocEntry = record PageBookInfoOffset: DWord; IncrementedInt: DWord; // first is $29A TopicsIndex: DWord; // Index of Entry in #TOPICS file end; TTopicEntry = record TocOffset, StringsOffset, URLTableOffset: DWord; InContents: Word;// 2 = in contents 6 = not in contents Unknown: Word; // 0,2,4,8,10,12,16,32 end; TBtreeHeader = packed record ident : array[0..1] of ansichar; // $3B $29 flags : word; // bit $2 is always 1, bit $0400 1 if dir? (always on) blocksize : word; // size of blocks (2048) dataformat : array[0..15] of ansichar; // "X44" always the same, see specs. unknown0 : dword; // always 0 lastlstblock : dword; // index of last listing block in the file; indexrootblock : dword; // Index of the root block in the file. unknown1 : dword; // always -1 nrblock : dword; // Number of blocks treedepth : word; // The depth of the tree of blocks (1 if no index blocks, 2 one level of index blocks, ...) nrkeywords : dword; // number of keywords in the file. codepage : dword; // Windows code page identifier (usually 1252 - Windows 3.1 US (ANSI)) lcid : dword; // LCID from the HHP file. ischm : dword; // 0 if this a BTREE and is part of a CHW file, 1 if it is a BTree and is part of a CHI or CHM file unknown2 : dword; // Unknown. Almost always 10031. Also 66631 (accessib.chm, ieeula.chm, iesupp.chm, iexplore.chm, msoe.chm, mstask.chm, ratings.chm, wab.chm). unknown3 : dword; // unknown 0 unknown4 : dword; // unknown 0 unknown5 : dword; // unknown 0 end; PBTreeBlockHeader = ^TBtreeBlockHeader; TBtreeBlockHeader = packed record Length : word; // Length of free space at the end of the block. NumberOfEntries : word; // Number of entries in the block. IndexOfPrevBlock : dword; // Index of the previous block. -1 if this is the first listing block. IndexOfNextBlock : dword; // Index of the next block. -1 if this is the last listing block. end; PBtreeBlockEntry = ^TBtreeBlockEntry; TBtreeBlockEntry = packed record isseealso : word; // 2 if this keyword is a See Also keyword, 0 if it is not. entrydepth : word; // Depth of this entry into the tree. charindex : dword;// Character index of the last keyword in the ", " separated list. unknown0 : dword;// 0 (unknown) NrPairs : dword;// Number of Name, Local pairs end; PBtreeIndexBlockHeader = ^TBtreeIndexBlockHeader; TBtreeIndexBlockHeader = packed record length : word; // Length of free space at the end of the block. NumberOfEntries : word; // Number of entries in the block. IndexOfChildBlock : dword; // Index of Child Block end; PBtreeIndexBlockEntry = ^TBtreeIndexBlockEntry; TBtreeIndexBlockEntry = packed record isseealso : word; // 2 if this keyword is a See Also keyword, 0 if it is not. entrydepth : word; // Depth of this entry into the tree. charindex : dword;// Character index of the last keyword in the ", " separated list. unknown0 : dword;// 0 (unknown) NrPairs : dword;// Number of Name, Local pairs end; function PageBookInfoRecordSize(ARecord: PTOCEntryPageBookInfo): Integer; implementation uses chmbase; function PageBookInfoRecordSize(ARecord: PTOCEntryPageBookInfo): Integer; begin if (TOC_ENTRY_HAS_CHILDREN and ARecord^.Props) > 0 then Result := 28 else Result := 20; end; { TDirectoryChunk } function TDirectoryChunk.CanHold(ASize: Integer): Boolean; begin Result := CurrentPos < $1000 - ASize - (SizeOf(Word) * (FQuickRefEntries+2)); end; function TDirectoryChunk.FreeSpace: Integer; begin Result := $1000 - CurrentPos; end; procedure TDirectoryChunk.WriteHeader(AHeader: Pointer); begin Move(AHeader^, Buffer[0], FHeaderSize); end; procedure TDirectoryChunk.WriteEntry(Size: Integer; Data: Pointer); var ReversePos: Integer; Value: Word; begin if not CanHold(Size) then Raise Exception.Create('Trying to write past the end of the buffer'); Move(Data^, Buffer[CurrentPos], Size); Inc(CurrentPos, Size); Inc(FItemCount); // now put a quickref entry if needed if ItemCount mod 5 = 0 then begin Inc(FQuickRefEntries); ReversePos := ($1000) - SizeOf(Word) - (SizeOf(Word)*FQuickRefEntries); Value := NtoLE(Word(CurrentPos - Size - FHeaderSize)); Move(Value, Buffer[ReversePos], SizeOf(Word)); end; end; procedure TDirectoryChunk.WriteChunkToStream(Stream: TStream); var ReversePos: Integer; TmpItemCount: Word; begin ReversePos := $1000 - SizeOf(Word); TmpItemCount := NtoLE(Word(FItemCount)); Move(TmpItemCount, Buffer[ReversePos], SizeOf(Word)); Stream.Write(Buffer[0], $1000); {$IFDEF DEBUG_CHM_CHUNKS} WriteLn('Writing ', Copy(PChar(@Buffer[0]),0,4),' ChunkToStream'); {$ENDIF} end; procedure TDirectoryChunk.Clear; begin FillChar(Buffer, $1000, 0); FItemCount := 0; CurrentPos := FHeaderSize; FQuickRefEntries := 0; Inc(FClearCount); end; constructor TDirectoryChunk.Create(AHeaderSize: Integer); begin FHeaderSize := AHeaderSize; CurrentPos := FHeaderSize; end; { TFileEntryList } function TFileEntryList.GetFileEntry(Index: Integer): TFileEntryRec; begin Result := PFileEntryRec(Items[Index])^; end; procedure TFileEntryList.SetFileEntry(Index: Integer; const AValue: TFileEntryRec); begin PFileEntryRec(Items[Index])^ := AValue; end; function TFileEntryList.AddEntry(AFileEntry: TFileEntryRec; CheckPathIsAdded: Boolean = True): Integer; var TmpEntry: PFileEntryRec; begin New(TmpEntry); //WriteLn('Adding: ', AFileEntry.Path+AFileEntry.Name,' Size = ', AFileEntry.DecompressedSize,' Offset = ', AFileEntry.DecompressedOffset); if CheckPathIsAdded and (FPaths.IndexOf(AFileEntry.Path) < 0) then begin // all paths are included in the list of files in section 0 with a size and offset of 0 FPaths.Add(AFileEntry.Path); TmpEntry^.Path := AFileEntry.Path; TmpEntry^.Name := ''; TmpEntry^.DecompressedOffset := 0; TmpEntry^.DecompressedSize := 0; TmpEntry^.Compressed := False; (Self as TList).Add(TmpEntry); New(TmpEntry); end; TmpEntry^ := AFileEntry; Result := (Self as TList).Add(TmpEntry); end; procedure TFileEntryList.Delete(Index: Integer); begin Dispose(PFileEntryRec(Items[Index])); Inherited Delete(Index); end; function FileEntrySortFunc(Item1, Item2: PFileEntryRec): Integer; var Str1, Str2: String; begin Str1 := Item1^.Path + Item1^.Name; Str2 := Item2^.Path + Item2^.Name; Result := ChmCompareText(Str1, Str2); end; procedure TFileEntryList.Sort; begin Inherited Sort(TListSortCompare(@FileEntrySortFunc)); end; constructor TFileEntryList.Create; begin Inherited Create; FPaths := TStringList.Create; end; destructor TFileEntryList.Destroy; var I: Integer; begin for I := Count-1 downto 0 do Delete(I); FPaths.Free; inherited Destroy; end; { TPMGIDirectoryChunk } procedure TPMGIDirectoryChunk.WriteChunkToStream(Stream: TStream; var AIndex: Integer ; Final: Boolean = False); var NewBuffer: array[0..512] of byte; EntryLength, WriteSize: Integer; OldPos, NewPos, NewStart: Int64; procedure FinishBlock; var Header: TPMGIIndexChunk; begin Inc(AIndex); Header.PMGIsig := 'PMGI'; Header.UnusedSpace := FParentChunk.FreeSpace; FParentChunk.WriteHeader(@Header); FParentChunk.WriteChunkToStream(Stream, AIndex, Final); FParentChunk.Clear; end; begin if FItemCount < 1 then begin WriteLn('WHAT ARE YOU DOING!!'); Dec(AIndex); Exit; end; OldPos := Stream.Position; WriteChunkToStream(Stream); NewPos := Stream.Position; Inc(FChunkLevelCount); if Final and (ChunkLevelCount < 2) then begin FParentChunk.Free; FParentChunk := nil; Exit; end; if FParentChunk = nil then FParentChunk := TPMGIDirectoryChunk.Create(FHeaderSize); NewStart := OldPos+FHeaderSize; Stream.Position := NewStart; EntryLength := GetCompressedInteger(Stream); WriteSize := (Stream.Position - NewStart) + EntryLength; Move(Buffer[FHeaderSize], NewBuffer[0], WriteSize); Inc(WriteSize, WriteCompressedInteger(@NewBuffer[WriteSize], AIndex)); Stream.Position := NewPos; if not FParentChunk.CanHold(WriteSize) then begin FinishBlock; end; FParentChunk.WriteEntry(WriteSize, @NewBuffer[0]); if Final then FinishBlock; //WriteLn(ChunkLevelCount); end; end.
unit flower_audio; interface uses sound_engine,timer_engine{$ifdef windows},windows{$endif}; const MAX_VOICES=8; DEFGAIN=48; MIXER_LOOKUP=MAX_VOICES*128; type flower_sound_channel=record start_nibbles:array[0..5] of byte; raw_frequency:array[0..3] of byte; start_address:dword; position:dword; frequency:word; volume:byte; volume_bank:byte; effect:byte; enable:boolean; repeat_:boolean; end; flower_chip=class(snd_chip_class) constructor create(clock:dword); destructor free; public sample_rom:array[0..$7fff] of byte; sample_vol:array[0..$3fff] of byte; procedure reset; procedure write(direccion,valor:byte); procedure update; private channel_list:array[0..(MAX_VOICES-1)] of flower_sound_channel; mixer_table:array[0..(256*MAX_VOICES)-1] of smallint; buffer:array[0..1] of smallint; buffer_pos:byte; procedure make_mixer_table; end; var flower_0:flower_chip; implementation procedure flower_chip.make_mixer_table; var f:word; val:integer; begin // fill in the table - 16 bit case for f:=0 to (MAX_VOICES*128)-1 do begin val:=(f*DEFGAIN*16) div MAX_VOICES; if (val>32767) then val:=32767; mixer_table[mixer_lookup+f]:=val; mixer_table[mixer_lookup-f]:=-val; end; end; procedure internal_update_flower; var voice,volume,raw_sample:byte; frequency:word; res:integer; begin res:=0; for voice:=0 to (MAX_VOICES-1) do begin if not(flower_0.channel_list[voice].enable) then continue; volume:=flower_0.channel_list[voice].volume; frequency:=flower_0.channel_list[voice].frequency; if flower_0.channel_list[voice].repeat_ then begin raw_sample:=flower_0.sample_rom[((flower_0.channel_list[voice].start_address shr 7) and $7e00) or ((flower_0.channel_list[voice].position shr 7) and $1ff)]; // guess: cut off after a number of repetitions if ((flower_0.channel_list[voice].position shr 7) and $20000)<>0 then flower_0.channel_list[voice].enable:=false; end else begin raw_sample:=flower_0.sample_rom[((flower_0.channel_list[voice].start_address+flower_0.channel_list[voice].position) shr 7) and $7fff]; if (raw_sample=$ff) then flower_0.channel_list[voice].enable:=false; end; volume:=volume or flower_0.channel_list[voice].volume_bank; res:=res+flower_0.sample_vol[((volume shl 8) or raw_sample) and $3fff]-$80; flower_0.channel_list[voice].position:=flower_0.channel_list[voice].position+frequency; end; flower_0.buffer[flower_0.buffer_pos]:=flower_0.mixer_table[MIXER_LOOKUP+res]; flower_0.buffer_pos:=flower_0.buffer_pos+1; end; constructor flower_chip.create(clock:dword); begin self.make_mixer_table; self.tsample_num:=init_channel; timers.init(sound_status.cpu_num,sound_status.cpu_clock/(clock/2),internal_update_flower,nil,true); end; destructor flower_chip.free; begin end; procedure flower_chip.reset; var f:byte; begin for f:=0 to (MAX_VOICES-1) do begin channel_list[f].start_address:=0; channel_list[f].position:=0; channel_list[f].volume:=0; channel_list[f].enable:=false; channel_list[f].repeat_:=false; end; self.buffer_pos:=0; self.buffer[0]:=0; self.buffer[1]:=0; end; procedure flower_chip.write(direccion,valor:byte); var ch,f:byte; begin ch:=(direccion shr 3) and $7; case (direccion and $47) of 0..3:begin //frequency_w channel_list[ch].raw_frequency[direccion and $3]:=valor and $f; channel_list[ch].frequency:=channel_list[ch].raw_frequency[2] shl 12; channel_list[ch].frequency:=channel_list[ch].frequency or (channel_list[ch].raw_frequency[3] shl 8); channel_list[ch].frequency:=channel_list[ch].frequency or (channel_list[ch].raw_frequency[0] shl 4); channel_list[ch].frequency:=channel_list[ch].frequency or (channel_list[ch].raw_frequency[1] shl 0); end; 4:channel_list[ch].repeat_:=(valor and $10)<>0; 5:; //unk_w 7:channel_list[ch].volume:=valor shr 4; $40..$45:begin channel_list[ch].start_nibbles[direccion and 7]:=valor and $f; if ((direccion and 7)=4) then channel_list[ch].effect:=valor shr 4; end; $47:begin channel_list[ch].enable:=true; channel_list[ch].volume_bank:=(valor and 3) shl 4; channel_list[ch].start_address:=0; channel_list[ch].position:=0; for f:=5 downto 0 do channel_list[ch].start_address:=(channel_list[ch].start_address shl 4) or channel_list[ch].start_nibbles[f]; end; end; end; procedure flower_chip.update; function sshr(num:int64;fac:byte):int64; begin if num<0 then sshr:=-(abs(num) shr fac) else sshr:=num shr fac; end; var f:byte; res:integer; begin res:=0; for f:=0 to (self.buffer_pos-1) do res:=res+self.buffer[f]; res:=sshr(res,self.buffer_pos-1); if res>32767 then res:=32767 else if res<-32767 then res:=-32767; tsample[self.tsample_num,sound_status.posicion_sonido]:=res; flower_0.buffer_pos:=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 ClpBase58; {$I ..\..\Include\CryptoLib.inc} interface uses SbpBase58, {$IFDEF DELPHI} SbpIBase58, {$ENDIF DELPHI} ClpCryptoLibTypes; type TBase58 = class sealed(TObject) public class function Encode(const Input: TCryptoLibByteArray): String; static; class function Decode(const Input: String): TCryptoLibByteArray; static; end; implementation { TBase58 } class function TBase58.Decode(const Input: String): TCryptoLibByteArray; begin result := SbpBase58.TBase58.BitCoin.Decode(Input); end; class function TBase58.Encode(const Input: TCryptoLibByteArray): String; begin result := SbpBase58.TBase58.BitCoin.Encode(Input); end; end.
unit TCClient; {$LONGSTRINGS ON} interface uses TypInfo, ActiveX; const CMakeAsTCClient = '/MakeAsTCClient'; function GetIDispatch(AObject: Pointer): IDispatch; procedure UnitTesting(const Classes: array of TClass); type TCallType = (cRegister, cPascal, cCdecl, cStdCall, cSafeCall); TMethodType = (mtProc, mtMethod, mtClassMethod, mtConstructor, mtDestructor); PArgList = PVariantArgList; TPropGetProc = function(Instance : TObject; Index : PArgList) : OleVariant; TPropSetProc = procedure(Instance : TObject; Params : PArgList); const PCharTypeInfo = 1; PWideCharTypeInfo = 2; RealTypeInfo = 3; UntypedTypeInfo = 4; ArrayOfConstInfo = 5; PointerInfo = 6; PWideCharInfo = 7; TypeInfoPChar = pointer(PCharTypeInfo); TypeInfoPWideChar = pointer(PWideCharTypeInfo); TypeInfoReal = pointer(RealTypeInfo); TypeInfoUntyped = pointer(UntypedTypeInfo); TypeInfoArrayOfConst = pointer(ArrayOfConstInfo); TypeInfoPointer = pointer(PointerInfo); MinVMTOffset = - 200; var NoParams : array [0..0] of PTypeInfo = (pointer(1)); procedure RegisterProc(AClass : TClass; const ProcName : string; MethodType : TMethodType; ProcInfo : PTypeInfo; Params : array of PTypeInfo; addr : pointer; CallType : TCallType); procedure RegisterProperty(AClass : TClass; const PropName : string; AGetProc : TPropGetProc; ASetProc : TPropSetProc); procedure RegisterIndexedProperty(AClass : TClass; const PropName : string; AIndexCount : integer; IsDefault : boolean; AGetProc : TPropGetProc; ASetProc : TPropSetProc); procedure RegRegisterMethod(AClass : TClass; const ProcName : string; ProcInfo : PTypeInfo; Params : array of PTypeInfo; addr : pointer); procedure RegisterClasses_(AClasses : array of TClass); procedure RegisterEvent(ProcInfo : PTypeInfo; Params : array of PTypeInfo); function VarFromObject(Instance : TObject) : OleVariant; function VarFromSet(const s; size : Integer) : Integer; procedure VarToSet(var s; size : Integer; const v : OleVariant); function VarToObject(const v : OleVariant) : TObject; function VarToChar(const v : OleVariant) : Char; function VarToPointer(const v : OleVariant) : Pointer; function VarToInterface(const v: Variant): IDispatch; function ArrayInfo(TInfo : PTypeInfo) : PTypeInfo; procedure RemoveClient; procedure InitClient; implementation uses Windows, Classes, Controls, Forms, SysUtils, OleCtrls; type TRegisterProc = procedure(AClass : TClass; const ProcName : string; MethodType : TMethodType; ProcInfo : PTypeInfo; Params : array of PTypeInfo; addr : pointer; CallType : TCallType); TRegisterProperty = procedure(AClass : TClass; const PropName : string; AGetProc : TPropGetProc; ASetProc : TPropSetProc); TRegisterIndexedProperty = procedure(AClass : TClass; const PropName : string; AIndexCount : integer; IsDefault : boolean; AGetProc : TPropGetProc; ASetProc : TPropSetProc); TRegRegisterMethod = procedure(AClass : TClass; const ProcName : string; ProcInfo : PTypeInfo; Params : array of PTypeInfo; addr : pointer); TRegisterClasses = procedure(AClasses : array of TClass); TRegisterEvent = procedure(ProcInfo : PTypeInfo; Params : array of PTypeInfo); TVarFromObject = function(Instance : TObject) : OleVariant; TVarFromSet = function(const s; size : Integer) : Integer; TVarToSet = procedure(var s; size : Integer; const v : OleVariant); TVarToObject = function(const v : OleVariant) : TObject; TVarToChar = function(const v : OleVariant) : Char; TVarToPointer = function(const v : OleVariant) : Pointer; TVarToInterface = function(const v: Variant) : IDispatch; TArrayInfo = function(TInfo : PTypeInfo) : PTypeInfo; TGetIDispatch = function(AObject: Pointer) : IDispatch; var _RegisterProc : TRegisterProc; _RegisterProperty : TRegisterProperty; _RegisterIndexedProperty : TRegisterIndexedProperty; _RegisterClasses : TRegisterClasses; _RegisterEvent : TRegisterEvent; _RegRegisterMethod : TRegRegisterMethod; _VarFromObject : TVarFromObject; _VarFromSet : TVarFromSet; _VarToSet : TVarToSet; _VarToObject : TVarToObject; _VarToChar : TVarToChar; _VarToPointer : TVarToPointer; _VarToInterface : TVarToInterface; _ArrayInfo : TArrayInfo; _GetIDispatch : TGetIDispatch; DllHandle : THandle; function TComponent_GetComponentCount(FComponent: Pointer): Integer; begin Result := TComponent(FComponent).ComponentCount; end; function TComponent_GetComponents(FComponent: Pointer; Index: Integer): Pointer; begin Result := TComponent(FComponent).Components[Index]; end; function TComponent_GetName(FComponent: Pointer): String; begin Result := TComponent(FComponent).Name; end; function TComponent_GetOwner(FComponent: Pointer): Pointer; begin Result := TComponent(FComponent).Owner; end; function TComponent_FunFindComponent(FComponent: Pointer; Name: String): Pointer; begin Result := TComponent(FComponent).FindComponent(String(Name)); end; procedure TControl_FunClientToScreen(FControl: Pointer; var Point: TPoint); begin Point := TControl(FControl).ClientToScreen(Point); end; procedure TControl_FunScreenToClient(FControl: Pointer; var Point: TPoint); begin Point := TControl(FControl).ScreenToClient(Point); end; function TControl_GetParent(FControl: Pointer): Pointer; begin Result := TControl(FControl).Parent; end; function TControl_GetEnabled(FControl: Pointer): Boolean; begin Result := TControl(FControl).Enabled; end; function TControl_GetVisible(FControl: Pointer): Boolean; begin Result := TControl(FControl).Visible; end; function TControl_GetWidth(FControl: Pointer): Integer; begin Result := TControl(FControl).Width; end; function TControl_GetHeight(FControl: Pointer): Integer; begin Result := TControl(FControl).Height; end; function TControl_GetLeft(FControl: Pointer): Integer; begin Result := TControl(FControl).Left; end; function TControl_GetTop(FControl: Pointer): Integer; begin Result := TControl(FControl).Top; end; type TWinControlEx = class(TWinControl) function _Handle: HWND; end; function TWinControlEx._Handle: HWND; begin Result := WindowHandle; end; function TWinControl_GetHandle(FWinControl: Pointer): Integer; begin Result := TWinControlEx(FWinControl)._Handle; end; function TWinControl_FunControlAtPos(FWinControl: Pointer; Pos: TPoint): Pointer; begin Result := TWinControl(FWinControl).ControlAtPos(Pos, True); end; function TOleControl_GetOleObject(FOleControl: Pointer): Variant; begin Result := TOleControl(FOleControl).OleObject; end; function TScreen_GetDataModules(Index: Integer): Pointer; begin Result := Screen.DataModules[Index]; end; function TScreen_GetDataModuleCount: Integer; begin Result := Screen.DataModuleCount; end; function FunFindControl(Handle: HWnd): Pointer; begin Result := FindControl(Handle); end; procedure FunGetMemoryManager(var MemMgr: TMemoryManager); begin GetMemoryManager(MemMgr); end; // ---------------------------------------- function GetIDispatch(AObject: Pointer): IDispatch; begin if DllHandle <> 0 then Result := _GetIDispatch(AObject); end; procedure RegisterProc(AClass : TClass; const ProcName : string; MethodType : TMethodType; ProcInfo : PTypeInfo; Params : array of PTypeInfo; addr : pointer; CallType : TCallType); begin if DllHandle <> 0 then _RegisterProc(AClass, ProcName, MethodType, ProcInfo, Params, addr, CallType); end; procedure RegisterProperty(AClass : TClass; const PropName : string; AGetProc : TPropGetProc; ASetProc : TPropSetProc); begin if DllHandle <> 0 then _RegisterProperty(AClass, PropName, AGetProc, ASetProc); end; procedure RegisterIndexedProperty(AClass : TClass; const PropName : string; AIndexCount : integer; IsDefault : boolean; AGetProc : TPropGetProc; ASetProc : TPropSetProc); begin if DllHandle <> 0 then _RegisterIndexedProperty(AClass, PropName, AIndexCount, IsDefault, AGetProc, ASetProc); end; procedure RegRegisterMethod(AClass : TClass; const ProcName : string; ProcInfo : PTypeInfo; Params : array of PTypeInfo; addr : pointer); begin if DllHandle <> 0 then _RegRegisterMethod(AClass, ProcName, ProcInfo, Params, addr); end; procedure RegisterClasses_(AClasses : array of TClass); begin if DllHandle <> 0 then _RegisterClasses(AClasses); end; procedure RegisterEvent(ProcInfo : PTypeInfo; Params : array of PTypeInfo); begin if DllHandle <> 0 then _RegisterEvent(ProcInfo, Params); end; function VarFromObject(Instance : TObject) : OleVariant; begin if DllHandle <> 0 then Result := _VarFromObject(Instance); end; function VarFromSet(const s; size : Integer) : Integer; begin if DllHandle <> 0 then Result := _VarFromSet(s, size) else Result := 0; end; procedure VarToSet(var s; size : Integer; const v : OleVariant); begin if DllHandle <> 0 then _VarToSet(s, size, v); end; function VarToObject(const v : OleVariant) : TObject; begin if DllHandle <> 0 then Result := _VarToObject(v) else Result := nil; end; function VarToChar(const v : OleVariant) : Char; begin if DllHandle <> 0 then Result := _VarToChar(v) else Result := #0; end; function VarToPointer(const v : OleVariant) : Pointer; begin if DllHandle <> 0 then Result := _VarToPointer(v) else Result := nil; end; function VarToInterface(const v: Variant): IDispatch; begin if DllHandle <> 0 then Result := _VarToInterface(V); end; function ArrayInfo(TInfo : PTypeInfo) : PTypeInfo; begin if DllHandle <> 0 then Result := _ArrayInfo(TInfo) else Result := nil; end; type TComponent_ComponentCount = function(FComponent: Pointer): Integer; TComponent_Components = function(FComponent: Pointer; Index: Integer): Pointer; TComponent_Name = function(FComponent: Pointer): String; TComponent_Owner = function(FComponent: Pointer): Pointer; TComponent_FindComponent = function(FComponent: Pointer; Name: String): Pointer; TControl_ClientToScreen = procedure(FControl: Pointer; var Point: TPoint); TControl_ScreenToClient = procedure(FControl: Pointer; var Point: TPoint); TControl_Parent = function(FControl: Pointer): Pointer; TControl_Enabled = function(FControl: Pointer): Boolean; TControl_Visible = function(FControl: Pointer): Boolean; TControl_Width = function(FControl: Pointer): Integer; TControl_Height = function(FControl: Pointer): Integer; TControl_Left = function(FControl: Pointer): Integer; TControl_Top = function(FControl: Pointer): Integer; TWinControl_Handle = function(FWinControl: Pointer): Integer; TWinControl_ControlAtPos = function(FWinControl: Pointer; Pos: TPoint): Pointer; TOleControl_OleObject = function(FOleControl: Pointer): Variant; TScreen_DataModules = function(Index: Integer): Pointer; TScreen_DataModuleCount = function: Integer; T_FindControl = function(Handle: HWnd): Pointer; T_GetMemoryManager = procedure(var MemMgr: TMemoryManager); TDelphiClient = record Version : Integer; PComponent_ComponentCount : TComponent_ComponentCount; PComponent_Components : TComponent_Components; PComponent_Name : TComponent_Name; PComponent_Owner : TComponent_Owner; PComponent_FindComponent : TComponent_FindComponent; PControl_ClientToScreen : TControl_ClientToScreen; PControl_ScreenToClient : TControl_ScreenToClient; PControl_Parent : TControl_Parent; PControl_Enabled : TControl_Enabled; PControl_Visible : TControl_Visible; PControl_Width : TControl_Width; PControl_Height : TControl_Height; PControl_Left : TControl_Left; PControl_Top : TControl_Top; PWinControl_Handle : TWinControl_Handle; PWinControl_ControlAtPos : TWinControl_ControlAtPos; PScreen_DataModules : TScreen_DataModules; PScreen_DataModuleCount : TScreen_DataModuleCount; PFindControl : T_FindControl; POleControl_OleObject : TOleControl_OleObject; PGetMemoryManager : T_GetMemoryManager; PBoolean_TypeInfo : Pointer; POleVariant_TypeInfo : Pointer; PVariant_TypeInfo : Pointer; PShortString_TypeInfo : Pointer; PString_TypeInfo : Pointer; PSingle_TypeInfo : Pointer; PTObject_TypeInfo : Pointer; HInstance : DWORD; PvmtSelfPtr : Integer; PvmtTypeInfo : Integer; PvmtClassName : Integer; PvmtInstanceSize : Integer; PvmtParent : Integer; PCallDynaInstAddr : Pointer; end; TAddDelphiClient = procedure (const dc: TDelphiClient); stdcall; TRemoveDelphiClient = procedure; stdcall; TDUnitTesting = procedure (const Classes: array of TClass); stdcall; var dc: TDelphiClient; a : TAddDelphiClient; r : TRemoveDelphiClient; const ClientsDLL = 'tcclients.dll'; procedure ShowError; begin {$IFNDEF HIDE_TC_CLIENT_ERROR} MessageBox(Application.Handle, 'Could not load ' + ClientsDLL + ' library', 'Error', MB_OK or MB_ICONSTOP) {$ENDIF} end; function IsCommandParameter(const Param: string): Boolean; var i: Integer; begin Result := True; for i := 1 to ParamCount do if ParamStr(i) = Param then Exit; Result := False; end; function GetCallDynaInstAddr: Pointer; asm lea eax, System.@CallDynaInst end; procedure InitClient; begin if DllHandle <> 0 then Exit; {$IFDEF USE_TC_CLIENT_COMMAND_LINE} if not IsCommandParameter(CMakeAsTCClient) then Exit; {$ENDIF} dc.Version := 1; dc.PComponent_ComponentCount := @TComponent_GetComponentCount; dc.PComponent_Components := @TComponent_GetComponents; dc.PComponent_Name := @TComponent_GetName; dc.PComponent_Owner := @TComponent_GetOwner; dc.PComponent_FindComponent := @TComponent_FunFindComponent; dc.PControl_ClientToScreen := @TControl_FunClientToScreen; dc.PControl_ScreenToClient := @TControl_FunScreenToClient; dc.PControl_Parent := @TControl_GetParent; dc.PControl_Enabled := @TControl_GetEnabled; dc.PControl_Visible := @TControl_GetVisible; dc.PControl_Width := @TControl_GetWidth; dc.PControl_Height := @TControl_GetHeight; dc.PControl_Left := @TControl_GetLeft; dc.PControl_Top := @TControl_GetTop; dc.PWinControl_Handle := @TWinControl_GetHandle; dc.PWinControl_ControlAtPos := @TWinControl_FunControlAtPos; dc.PScreen_DataModules := @TScreen_GetDataModules; dc.PScreen_DataModuleCount := @TScreen_GetDataModuleCount; dc.PFindControl := @FunFindControl; dc.POleControl_OleObject := @TOleControl_GetOleObject; dc.PGetMemoryManager := @FunGetMemoryManager; dc.PBoolean_TypeInfo := TypeInfo(Boolean); dc.POleVariant_TypeInfo := TypeInfo(OleVariant); dc.PVariant_TypeInfo := TypeInfo(Variant); dc.PShortString_TypeInfo := TypeInfo(ShortString); dc.PString_TypeInfo := TypeInfo(String); dc.PSingle_TypeInfo := TypeInfo(Single); dc.PTObject_TypeInfo := TypeInfo(TObject); dc.HInstance := HInstance; dc.PvmtSelfPtr := vmtSelfPtr; dc.PvmtTypeInfo := vmtTypeInfo; dc.PvmtClassName := vmtClassName; dc.PvmtInstanceSize := vmtInstanceSize; dc.PvmtParent := vmtParent; dc.PCallDynaInstAddr := GetCallDynaInstAddr; DllHandle := LoadLibrary(ClientsDLL); if DllHandle <> 0 then begin a := GetProcAddress(DllHandle, 'AddDelphiClient'); a(dc); _RegisterProc := GetProcAddress(DllHandle, 'RegisterProc'); _RegisterProperty := GetProcAddress(DllHandle, 'RegisterProperty'); _RegisterIndexedProperty := GetProcAddress(DllHandle, 'RegisterIndexedProperty'); _RegisterClasses := GetProcAddress(DllHandle, 'RegisterClasses'); _RegisterEvent := GetProcAddress(DllHandle, 'RegisterEvent'); _RegRegisterMethod := GetProcAddress(DllHandle, 'RegRegisterMethod'); _VarFromObject := GetProcAddress(DllHandle, 'VarFromObject'); _VarFromSet := GetProcAddress(DllHandle, 'VarFromSet'); _VarToSet := GetProcAddress(DllHandle, 'VarToSet'); _VarToObject := GetProcAddress(DllHandle, 'VarToObject'); _VarToChar := GetProcAddress(DllHandle, 'VarToChar'); _VarToPointer := GetProcAddress(DllHandle, 'VarToPointer'); _VarToInterface:= GetProcAddress(DllHandle, 'VarToInterface'); _ArrayInfo := GetProcAddress(DllHandle, 'ArrayInfo'); _GetIDispatch := GetProcAddress(DllHandle, 'GetIDispatch'); end else ShowError; end; procedure RemoveClient; begin if DllHandle <> 0 then begin r := GetProcAddress(DllHandle, 'RemoveDelphiClient'); r(); FreeLibrary(DllHandle); DllHandle := 0; end; end; procedure UnitTesting(const Classes: array of TClass); var Proc: TDUnitTesting; begin InitClient; if DllHandle <> 0 then begin Proc := GetProcAddress(DllHandle, 'DUnitTesting'); if @Proc <> nil then Proc(Classes); end; end; initialization InitClient; finalization RemoveClient; end.
unit InfoWORKMAILTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoWORKMAILRecord = record PLender: String[4]; PImageID: String[9]; PStatus: String[10]; End; TInfoWORKMAILBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoWORKMAILRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoWORKMAIL = (InfoWORKMAILPrimaryKey, InfoWORKMAILByStatus); TInfoWORKMAILTable = class( TDBISAMTableAU ) private FDFLender: TStringField; FDFImageID: TStringField; FDFStatus: TStringField; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPImageID(const Value: String); function GetPImageID:String; procedure SetPStatus(const Value: String); function GetPStatus:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoWORKMAIL); function GetEnumIndex: TEIInfoWORKMAIL; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoWORKMAILRecord; procedure StoreDataBuffer(ABuffer:TInfoWORKMAILRecord); property DFLender: TStringField read FDFLender; property DFImageID: TStringField read FDFImageID; property DFStatus: TStringField read FDFStatus; property PLender: String read GetPLender write SetPLender; property PImageID: String read GetPImageID write SetPImageID; property PStatus: String read GetPStatus write SetPStatus; published property Active write SetActive; property EnumIndex: TEIInfoWORKMAIL read GetEnumIndex write SetEnumIndex; end; { TInfoWORKMAILTable } procedure Register; implementation function TInfoWORKMAILTable.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 { TInfoWORKMAILTable.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; { TInfoWORKMAILTable.GenerateNewFieldName } function TInfoWORKMAILTable.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; { TInfoWORKMAILTable.CreateField } procedure TInfoWORKMAILTable.CreateFields; begin FDFLender := CreateField( 'Lender' ) as TStringField; FDFImageID := CreateField( 'ImageID' ) as TStringField; FDFStatus := CreateField( 'Status' ) as TStringField; end; { TInfoWORKMAILTable.CreateFields } procedure TInfoWORKMAILTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoWORKMAILTable.SetActive } procedure TInfoWORKMAILTable.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TInfoWORKMAILTable.GetPLender:String; begin result := DFLender.Value; end; procedure TInfoWORKMAILTable.SetPImageID(const Value: String); begin DFImageID.Value := Value; end; function TInfoWORKMAILTable.GetPImageID:String; begin result := DFImageID.Value; end; procedure TInfoWORKMAILTable.SetPStatus(const Value: String); begin DFStatus.Value := Value; end; function TInfoWORKMAILTable.GetPStatus:String; begin result := DFStatus.Value; end; procedure TInfoWORKMAILTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Lender, String, 4, N'); Add('ImageID, String, 9, N'); Add('Status, String, 10, N'); end; end; procedure TInfoWORKMAILTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Lender;ImageID, Y, Y, N, N'); Add('ByStatus, Lender;Status;ImageID, N, N, N, N'); end; end; procedure TInfoWORKMAILTable.SetEnumIndex(Value: TEIInfoWORKMAIL); begin case Value of InfoWORKMAILPrimaryKey : IndexName := ''; InfoWORKMAILByStatus : IndexName := 'ByStatus'; end; end; function TInfoWORKMAILTable.GetDataBuffer:TInfoWORKMAILRecord; var buf: TInfoWORKMAILRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLender := DFLender.Value; buf.PImageID := DFImageID.Value; buf.PStatus := DFStatus.Value; result := buf; end; procedure TInfoWORKMAILTable.StoreDataBuffer(ABuffer:TInfoWORKMAILRecord); begin DFLender.Value := ABuffer.PLender; DFImageID.Value := ABuffer.PImageID; DFStatus.Value := ABuffer.PStatus; end; function TInfoWORKMAILTable.GetEnumIndex: TEIInfoWORKMAIL; var iname : string; begin result := InfoWORKMAILPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoWORKMAILPrimaryKey; if iname = 'BYSTATUS' then result := InfoWORKMAILByStatus; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoWORKMAILTable, TInfoWORKMAILBuffer ] ); end; { Register } function TInfoWORKMAILBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..3] of string = ('LENDER','IMAGEID','STATUS' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 3) and (flist[x] <> s) do inc(x); if x <= 3 then result := x else result := 0; end; function TInfoWORKMAILBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; end; end; function TInfoWORKMAILBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLender; 2 : result := @Data.PImageID; 3 : result := @Data.PStatus; end; end; end.
unit Entity; interface uses gm_engine; type TEntity = class(TObject) private FPos: TPoint; FName: string; function GetPos: TPoint; procedure SetName(const Value: string); public procedure SetPosition(const A: TPoint); overload; procedure SetPosition(const X, Y: Integer); overload; constructor Create(); procedure Empty; destructor Destroy; override; property Pos: TPoint read GetPos; property Name: string read FName write SetName; end; implementation { TEntity } constructor TEntity.Create; begin Empty end; destructor TEntity.Destroy; begin inherited; end; procedure TEntity.Empty; begin Name := '' end; function TEntity.GetPos: TPoint; begin Result := FPos end; procedure TEntity.SetName(const Value: string); begin FName := Value end; procedure TEntity.SetPosition(const X, Y: Integer); begin FPos := Point(X, Y) end; procedure TEntity.SetPosition(const A: TPoint); begin FPos := A end; end.
unit DataRegistry; interface uses Classes, MapStringToObject; type TDataRegistry = class; TDataRegistry = class public constructor Create; destructor Destroy; override; private fRegistry : TMapStringToObject; // TStringList; public procedure Add(const aKey : string; Obj : TObject); procedure Remove(const aKey : string); private function GetObject(const aKey : string) : TObject; public property Objects[const aKey : string] : TObject read GetObject; default; end; implementation // TDataRegistry constructor TDataRegistry.Create; begin inherited Create; fRegistry := TMapStringToObject.Create(mmOwn); //TStringList.Create; { with fRegistry do begin Sorted := true; Duplicates := dupError; end; } end; destructor TDataRegistry.Destroy; {var i : integer;} begin {for i := 0 to pred(fRegistry.Count) do fRegistry.Objects[i].Free;} fRegistry.Free; inherited; end; procedure TDataRegistry.Add(const aKey : string; Obj : TObject); begin try fRegistry[aKey] := Obj; //fRegistry.AddObject(aKey, Obj); except Obj.Free; raise; end; end; procedure TDataRegistry.Remove(const aKey : string); {var index : integer;} begin {index := fRegistry.IndexOf(aKey); if index <> -1 then begin fRegistry.Objects[index].Free; fRegistry.Delete(index); end;} fRegistry.Remove(aKey); end; function TDataRegistry.GetObject(const aKey : string) : TObject; {var index : integer;} begin result := fRegistry[aKey]; {index := fRegistry.IndexOf(aKey); if index <> -1 then result := fRegistry.Objects[index] else result := nil;} end; end.
unit sdsCompareEditions; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Editions" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Editions/sdsCompareEditions.pas" // Начат: 30.07.2009 15:52 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UseCaseControllerImp::Class>> F1 Пользовательские сервисы::CompareEditions::Editions::Editions::TsdsCompareEditions // // Реализация прецедента "Сравнение редакций документа" // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses DocumentUnit {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmControllers {$IfEnd} //not NoVCM , EditionsInterfaces, l3ProtoObjectWithCOMQI, l3Interfaces, l3NotifyPtrList {$If not defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} //not NoVCM , DocumentAndListInterfaces {a}, nevTools, eeInterfaces, l3Tree_TLB, afwInterfaces, FoldersDomainInterfaces, DocumentInterfaces, l3TreeInterfaces, bsTypesNew ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsDiffData = DocumentUnit.TDiffData; IsdsCompareEditionsState = interface(IvcmData) {* Состояние прецедента TsdsCompareEditions } ['{58401E22-1A19-4B3D-90EE-616BC5328B1A}'] function Get_EditionForCompare: TRedactionID; function Get_UseCaseData: InsCompareEditionsInfo; function Get_CompareRootPair: TnsDiffData; property EditionForCompare: TRedactionID read Get_EditionForCompare; property UseCaseData: InsCompareEditionsInfo read Get_UseCaseData; property CompareRootPair: TnsDiffData read Get_CompareRootPair; end;//IsdsCompareEditionsState _InitDataType_ = InsCompareEditionsInfo; _SetDataType_ = IsdsCompareEditionsState; _SetType_ = IsdsCompareEditions; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmFormSetDataSource.imp.pas} _VScroll_Parent_ = _vcmFormSetDataSource_; {$Include ..\Editions\VScroll.imp.pas} TsdsCompareEditions = {final ucc} class(_VScroll_, IsdsCompareEditions, InsVScrollController {from IsdsCompareEditions}, InsDocumentTextProviderFactory {from IsdsCompareEditions}, IsdsPrimDocument {from IsdsCompareEditions}, IsdsEditionsHolder {from IsdsCompareEditions}) {* Реализация прецедента "Сравнение редакций документа" } private // private fields f_Left : IvcmViewAreaControllerRef; {* Поле для области вывода Left} f_Right : IvcmViewAreaControllerRef; {* Поле для области вывода Right} f_EditionsContainerData : IvcmViewAreaControllerRef; {* Поле для области вывода EditionsContainerData} f_EditionsList : IvcmViewAreaControllerRef; {* Поле для области вывода EditionsList} private // private methods procedure NotifyEditionChanged; {* Нотификация о смене редакции } protected // realized methods {$If not defined(NoVCM)} function MakeData: _SetDataType_; override; {* Данные сборки. } {$IfEnd} //not NoVCM function pm_GetLeft: IdsLeftEdition; function DoGet_Left: IdsLeftEdition; function pm_GetRight: IdsRightEdition; function DoGet_Right: IdsRightEdition; function pm_GetEditionsContainerData: IdsEditionsContainerData; function DoGet_EditionsContainerData: IdsEditionsContainerData; function Get_ChangedParas: IDiffIterator; function Get_EditionForCompare: TRedactionID; procedure Set_EditionForCompare(aValue: TRedactionID); function pm_GetDocInfo: IdeDocInfo; function Get_Node(aIsLeft: Boolean): TDocumentRoot; function pm_GetEditionsList: IdsEditions; function DoGet_EditionsList: IdsEditions; function Get_Position: TbsDocPos; protected // overridden protected methods {$If not defined(NoVCM)} procedure ClearAreas; override; {* Очищает ссылки на области ввода } {$IfEnd} //not NoVCM protected // Методы преобразования к реализуемым интерфейсам function As_InsVScrollController: InsVScrollController; function As_InsDocumentTextProviderFactory: InsDocumentTextProviderFactory; function As_IsdsPrimDocument: IsdsPrimDocument; function As_IsdsEditionsHolder: IsdsEditionsHolder; end;//TsdsCompareEditions {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses dsEditionsContainerData, dsRightEdition, dsLeftEdition, nsEditionDiffData, nsEditionsContainerData {$If not defined(NoVCM)} , vcmFormSetRefreshParams {$IfEnd} //not NoVCM , sdsCompareEditionsState, deDocInfo, dsEditions {$If not defined(NoVCM)} , vcmLocalInterfaces {$IfEnd} //not NoVCM , l3Base, SysUtils, vcmFormDataSourceRef {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TsdsCompareEditions; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmFormSetDataSource.imp.pas} {$Include ..\Editions\VScroll.imp.pas} // start class TsdsCompareEditions procedure TsdsCompareEditions.NotifyEditionChanged; //#UC START# *4A841D40037E_4A7181A301E3_var* var l_Index : Integer; l_Intf : InsEditionListner; l_Item : IUnknown; //#UC END# *4A841D40037E_4A7181A301E3_var* begin //#UC START# *4A841D40037E_4A7181A301E3_impl* if (NotifiedObjList <> nil) then for l_Index := NotifiedObjList.Hi downto 0 do try l_Item := f_NotifiedObjList[l_Index]; if Supports(l_Item, InsEditionListner, l_Intf) AND (l_Item = l_Intf) then try l_Intf.EditionChanged; finally l_Intf := nil; end;//try..finaly except on E: Exception do l3System.Exception2Log(E); end;//try..except //#UC END# *4A841D40037E_4A7181A301E3_impl* end;//TsdsCompareEditions.NotifyEditionChanged {$If not defined(NoVCM)} function TsdsCompareEditions.MakeData: _SetDataType_; //#UC START# *47F3778403D9_4A7181A301E3_var* //#UC END# *47F3778403D9_4A7181A301E3_var* begin //#UC START# *47F3778403D9_4A7181A301E3_impl* Result := TsdsCompareEditionsState.Make(InitialUseCaseData, InitialUseCaseData.EditionForCompare); //#UC END# *47F3778403D9_4A7181A301E3_impl* end;//TsdsCompareEditions.MakeData {$IfEnd} //not NoVCM function TsdsCompareEditions.pm_GetLeft: IdsLeftEdition; //#UC START# *4A6D579203BC_4A7181A301E3get_var* //#UC END# *4A6D579203BC_4A7181A301E3get_var* begin if (f_Left = nil) then begin f_Left := TvcmViewAreaControllerRef.Make; //#UC START# *4A6D579203BC_4A7181A301E3get_init* // - код инициализации ссылки на ViewArea //#UC END# *4A6D579203BC_4A7181A301E3get_init* end;//f_Left = nil if f_Left.IsEmpty //#UC START# *4A6D579203BC_4A7181A301E3get_need* // - условие создания ViewArea //#UC END# *4A6D579203BC_4A7181A301E3get_need* then f_Left.Referred := DoGet_Left; Result := IdsLeftEdition(f_Left.Referred); end; function TsdsCompareEditions.DoGet_Left: IdsLeftEdition; //#UC START# *4A6D579203BC_4A7181A301E3area_var* //#UC END# *4A6D579203BC_4A7181A301E3area_var* begin //#UC START# *4A6D579203BC_4A7181A301E3area_impl* SetData.CompareRootPair; Result := TdsLeftEdition.Make(Self, TnsEditionDiffData.Make(InitialUseCaseData.Document, InitialUseCaseData.RedactionCurrentPara, InitialUseCaseData.DocumentForReturn)); //#UC END# *4A6D579203BC_4A7181A301E3area_impl* end;//TsdsCompareEditions.DoGet_Left function TsdsCompareEditions.pm_GetRight: IdsRightEdition; //#UC START# *4A6D57C80079_4A7181A301E3get_var* //#UC END# *4A6D57C80079_4A7181A301E3get_var* begin if (f_Right = nil) then begin f_Right := TvcmViewAreaControllerRef.Make; //#UC START# *4A6D57C80079_4A7181A301E3get_init* // - код инициализации ссылки на ViewArea //#UC END# *4A6D57C80079_4A7181A301E3get_init* end;//f_Right = nil if f_Right.IsEmpty //#UC START# *4A6D57C80079_4A7181A301E3get_need* // - условие создания ViewArea //#UC END# *4A6D57C80079_4A7181A301E3get_need* then f_Right.Referred := DoGet_Right; Result := IdsRightEdition(f_Right.Referred); end; function TsdsCompareEditions.DoGet_Right: IdsRightEdition; //#UC START# *4A6D57C80079_4A7181A301E3area_var* //#UC END# *4A6D57C80079_4A7181A301E3area_var* begin //#UC START# *4A6D57C80079_4A7181A301E3area_impl* SetData.CompareRootPair; Result := TdsRightEdition.Make(Self, TnsEditionDiffData.Make(InitialUseCaseData.Document, InitialUseCaseData.RedactionCurrentPara, InitialUseCaseData.DocumentForReturn)); //#UC END# *4A6D57C80079_4A7181A301E3area_impl* end;//TsdsCompareEditions.DoGet_Right function TsdsCompareEditions.pm_GetEditionsContainerData: IdsEditionsContainerData; //#UC START# *4A6EC18E02E3_4A7181A301E3get_var* //#UC END# *4A6EC18E02E3_4A7181A301E3get_var* begin if (f_EditionsContainerData = nil) then begin f_EditionsContainerData := TvcmViewAreaControllerRef.Make; //#UC START# *4A6EC18E02E3_4A7181A301E3get_init* // - код инициализации ссылки на ViewArea //#UC END# *4A6EC18E02E3_4A7181A301E3get_init* end;//f_EditionsContainerData = nil if f_EditionsContainerData.IsEmpty //#UC START# *4A6EC18E02E3_4A7181A301E3get_need* // - условие создания ViewArea //#UC END# *4A6EC18E02E3_4A7181A301E3get_need* then f_EditionsContainerData.Referred := DoGet_EditionsContainerData; Result := IdsEditionsContainerData(f_EditionsContainerData.Referred); end; function TsdsCompareEditions.DoGet_EditionsContainerData: IdsEditionsContainerData; //#UC START# *4A6EC18E02E3_4A7181A301E3area_var* //#UC END# *4A6EC18E02E3_4A7181A301E3area_var* begin //#UC START# *4A6EC18E02E3_4A7181A301E3area_impl* SetData.CompareRootPair; Result := TdsEditionsContainerData.Make(Self, TnsEditionsContainerData.Make(InitialUseCaseData.Document, InitialUseCaseData.DocumentForReturn)); //#UC END# *4A6EC18E02E3_4A7181A301E3area_impl* end;//TsdsCompareEditions.DoGet_EditionsContainerData function TsdsCompareEditions.Get_ChangedParas: IDiffIterator; //#UC START# *4B4F2EAD0183_4A7181A301E3get_var* //#UC END# *4B4F2EAD0183_4A7181A301E3get_var* begin //#UC START# *4B4F2EAD0183_4A7181A301E3get_impl* Result := SetData.CompareRootPair.rDiffIterator; //#UC END# *4B4F2EAD0183_4A7181A301E3get_impl* end;//TsdsCompareEditions.Get_ChangedParas function TsdsCompareEditions.Get_EditionForCompare: TRedactionID; //#UC START# *4B6BD5E001F4_4A7181A301E3get_var* //#UC END# *4B6BD5E001F4_4A7181A301E3get_var* begin //#UC START# *4B6BD5E001F4_4A7181A301E3get_impl* Result := SetData.EditionForCompare; //#UC END# *4B6BD5E001F4_4A7181A301E3get_impl* end;//TsdsCompareEditions.Get_EditionForCompare procedure TsdsCompareEditions.Set_EditionForCompare(aValue: TRedactionID); //#UC START# *4B6BD5E001F4_4A7181A301E3set_var* var l_Data : IvcmData; //#UC END# *4B6BD5E001F4_4A7181A301E3set_var* begin //#UC START# *4B6BD5E001F4_4A7181A301E3set_impl* if (SetData.EditionForCompare <> aValue) then begin l_Data := Self.SetData.Clone; ClearAreas; f_SetData := TsdsCompareEditionsState.Make(InitialUseCaseData, aValue); NotifyEditionChanged; Refresh(vcmMakeDataRefreshParams(sfsOnlyIfDataSourceChanged, l_Data)); end;//aValue <> SetData.EditionForCompare //#UC END# *4B6BD5E001F4_4A7181A301E3set_impl* end;//TsdsCompareEditions.Set_EditionForCompare function TsdsCompareEditions.pm_GetDocInfo: IdeDocInfo; //#UC START# *4DF9D63B0360_4A7181A301E3get_var* //#UC END# *4DF9D63B0360_4A7181A301E3get_var* begin //#UC START# *4DF9D63B0360_4A7181A301E3get_impl* Result := TdeDocInfo.Make(InitialUseCaseData.Document); //#UC END# *4DF9D63B0360_4A7181A301E3get_impl* end;//TsdsCompareEditions.pm_GetDocInfo function TsdsCompareEditions.Get_Node(aIsLeft: Boolean): TDocumentRoot; //#UC START# *4EA7F1C400B0_4A7181A301E3get_var* //#UC END# *4EA7F1C400B0_4A7181A301E3get_var* begin //#UC START# *4EA7F1C400B0_4A7181A301E3get_impl* if aIsLeft then Result := SetData.CompareRootPair.rPrev else Result := SetData.CompareRootPair.rCur; //#UC END# *4EA7F1C400B0_4A7181A301E3get_impl* end;//TsdsCompareEditions.Get_Node function TsdsCompareEditions.pm_GetEditionsList: IdsEditions; //#UC START# *4ED906420134_4A7181A301E3get_var* //#UC END# *4ED906420134_4A7181A301E3get_var* begin if (f_EditionsList = nil) then begin f_EditionsList := TvcmViewAreaControllerRef.Make; //#UC START# *4ED906420134_4A7181A301E3get_init* // - код инициализации ссылки на ViewArea //#UC END# *4ED906420134_4A7181A301E3get_init* end;//f_EditionsList = nil if f_EditionsList.IsEmpty //#UC START# *4ED906420134_4A7181A301E3get_need* // - условие создания ViewArea //#UC END# *4ED906420134_4A7181A301E3get_need* then f_EditionsList.Referred := DoGet_EditionsList; Result := IdsEditions(f_EditionsList.Referred); end; function TsdsCompareEditions.DoGet_EditionsList: IdsEditions; //#UC START# *4ED906420134_4A7181A301E3area_var* //#UC END# *4ED906420134_4A7181A301E3area_var* begin //#UC START# *4ED906420134_4A7181A301E3area_impl* Result := TdsEditions.Make(Self); //#UC END# *4ED906420134_4A7181A301E3area_impl* end;//TsdsCompareEditions.DoGet_EditionsList function TsdsCompareEditions.Get_Position: TbsDocPos; //#UC START# *5214A46601C7_4A7181A301E3get_var* //#UC END# *5214A46601C7_4A7181A301E3get_var* begin //#UC START# *5214A46601C7_4A7181A301E3get_impl* Result := InitialUseCaseData.Position; //#UC END# *5214A46601C7_4A7181A301E3get_impl* end;//TsdsCompareEditions.Get_Position {$If not defined(NoVCM)} procedure TsdsCompareEditions.ClearAreas; {-} begin if (f_Left <> nil) then f_Left.Referred := nil; if (f_Right <> nil) then f_Right.Referred := nil; if (f_EditionsContainerData <> nil) then f_EditionsContainerData.Referred := nil; if (f_EditionsList <> nil) then f_EditionsList.Referred := nil; inherited; end;//TsdsCompareEditions.ClearAreas {$IfEnd} //not NoVCM // Методы преобразования к реализуемым интерфейсам function TsdsCompareEditions.As_InsVScrollController: InsVScrollController; begin Result := Self; end; function TsdsCompareEditions.As_InsDocumentTextProviderFactory: InsDocumentTextProviderFactory; begin Result := Self; end; function TsdsCompareEditions.As_IsdsPrimDocument: IsdsPrimDocument; begin Result := Self; end; function TsdsCompareEditions.As_IsdsEditionsHolder: IsdsEditionsHolder; begin Result := Self; end; {$IfEnd} //not Admin AND not Monitorings end.
unit FoldersElementInfoKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы FoldersElementInfo } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Folders\FoldersElementInfoKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "FoldersElementInfoKeywordsPack" MUID: (F42993E6E810) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtPanel , eeMemoWithEditOperations , vtLabel {$If Defined(Nemesis)} , nscComboBoxWithReadOnly {$IfEnd} // Defined(Nemesis) , vtCheckBox ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , FoldersElementInfo_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_FoldersElementInfo = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы FoldersElementInfo ---- *Пример использования*: [code] 'aControl' форма::FoldersElementInfo TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_FoldersElementInfo Tkw_FoldersElementInfo_Control_CommentPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола CommentPanel ---- *Пример использования*: [code] контрол::CommentPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_CommentPanel Tkw_FoldersElementInfo_Control_CommentPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола CommentPanel ---- *Пример использования*: [code] контрол::CommentPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_CommentPanel_Push Tkw_FoldersElementInfo_Control_ElementComment = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ElementComment ---- *Пример использования*: [code] контрол::ElementComment TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_ElementComment Tkw_FoldersElementInfo_Control_ElementComment_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ElementComment ---- *Пример использования*: [code] контрол::ElementComment:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_ElementComment_Push Tkw_FoldersElementInfo_Control_CaptionPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола CaptionPanel ---- *Пример использования*: [code] контрол::CaptionPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_CaptionPanel Tkw_FoldersElementInfo_Control_CaptionPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола CaptionPanel ---- *Пример использования*: [code] контрол::CaptionPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_CaptionPanel_Push Tkw_FoldersElementInfo_Control_lblComment = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола lblComment ---- *Пример использования*: [code] контрол::lblComment TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_lblComment Tkw_FoldersElementInfo_Control_lblComment_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола lblComment ---- *Пример использования*: [code] контрол::lblComment:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_lblComment_Push Tkw_FoldersElementInfo_Control_TopPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола TopPanel ---- *Пример использования*: [code] контрол::TopPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_TopPanel Tkw_FoldersElementInfo_Control_TopPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола TopPanel ---- *Пример использования*: [code] контрол::TopPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_TopPanel_Push Tkw_FoldersElementInfo_Control_NamePanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола NamePanel ---- *Пример использования*: [code] контрол::NamePanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_NamePanel Tkw_FoldersElementInfo_Control_NamePanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола NamePanel ---- *Пример использования*: [code] контрол::NamePanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_NamePanel_Push Tkw_FoldersElementInfo_Control_lblElementName = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола lblElementName ---- *Пример использования*: [code] контрол::lblElementName TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_lblElementName Tkw_FoldersElementInfo_Control_lblElementName_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола lblElementName ---- *Пример использования*: [code] контрол::lblElementName:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_lblElementName_Push Tkw_FoldersElementInfo_Control_ElementName = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ElementName ---- *Пример использования*: [code] контрол::ElementName TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_ElementName Tkw_FoldersElementInfo_Control_ElementName_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ElementName ---- *Пример использования*: [code] контрол::ElementName:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_ElementName_Push Tkw_FoldersElementInfo_Control_cbShared = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола cbShared ---- *Пример использования*: [code] контрол::cbShared TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_cbShared Tkw_FoldersElementInfo_Control_cbShared_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола cbShared ---- *Пример использования*: [code] контрол::cbShared:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_cbShared_Push Tkw_FoldersElementInfo_Control_InfoName = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола InfoName ---- *Пример использования*: [code] контрол::InfoName TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_InfoName Tkw_FoldersElementInfo_Control_InfoName_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола InfoName ---- *Пример использования*: [code] контрол::InfoName:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersElementInfo_Control_InfoName_Push TkwEnFoldersElementInfoCommentPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.CommentPanel } private function CommentPanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.CommentPanel } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoCommentPanel TkwEnFoldersElementInfoElementComment = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.ElementComment } private function ElementComment(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TeeMemoWithEditOperations; {* Реализация слова скрипта .TenFoldersElementInfo.ElementComment } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoElementComment TkwEnFoldersElementInfoCaptionPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.CaptionPanel } private function CaptionPanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.CaptionPanel } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoCaptionPanel TkwEnFoldersElementInfoLblComment = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.lblComment } private function lblComment(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtLabel; {* Реализация слова скрипта .TenFoldersElementInfo.lblComment } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoLblComment TkwEnFoldersElementInfoTopPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.TopPanel } private function TopPanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.TopPanel } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoTopPanel TkwEnFoldersElementInfoNamePanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.NamePanel } private function NamePanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.NamePanel } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoNamePanel TkwEnFoldersElementInfoLblElementName = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.lblElementName } private function lblElementName(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtLabel; {* Реализация слова скрипта .TenFoldersElementInfo.lblElementName } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoLblElementName TkwEnFoldersElementInfoElementName = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.ElementName } private function ElementName(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TnscComboBoxWithReadOnly; {* Реализация слова скрипта .TenFoldersElementInfo.ElementName } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoElementName TkwEnFoldersElementInfoCbShared = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.cbShared } private function cbShared(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtCheckBox; {* Реализация слова скрипта .TenFoldersElementInfo.cbShared } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoCbShared TkwEnFoldersElementInfoInfoName = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFoldersElementInfo.InfoName } private function InfoName(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtLabel; {* Реализация слова скрипта .TenFoldersElementInfo.InfoName } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFoldersElementInfoInfoName function Tkw_Form_FoldersElementInfo.GetString: AnsiString; begin Result := 'enFoldersElementInfo'; end;//Tkw_Form_FoldersElementInfo.GetString class function Tkw_Form_FoldersElementInfo.GetWordNameForRegister: AnsiString; begin Result := 'форма::FoldersElementInfo'; end;//Tkw_Form_FoldersElementInfo.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_CommentPanel.GetString: AnsiString; begin Result := 'CommentPanel'; end;//Tkw_FoldersElementInfo_Control_CommentPanel.GetString class procedure Tkw_FoldersElementInfo_Control_CommentPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_FoldersElementInfo_Control_CommentPanel.RegisterInEngine class function Tkw_FoldersElementInfo_Control_CommentPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CommentPanel'; end;//Tkw_FoldersElementInfo_Control_CommentPanel.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_CommentPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('CommentPanel'); inherited; end;//Tkw_FoldersElementInfo_Control_CommentPanel_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_CommentPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CommentPanel:push'; end;//Tkw_FoldersElementInfo_Control_CommentPanel_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_ElementComment.GetString: AnsiString; begin Result := 'ElementComment'; end;//Tkw_FoldersElementInfo_Control_ElementComment.GetString class procedure Tkw_FoldersElementInfo_Control_ElementComment.RegisterInEngine; begin inherited; TtfwClassRef.Register(TeeMemoWithEditOperations); end;//Tkw_FoldersElementInfo_Control_ElementComment.RegisterInEngine class function Tkw_FoldersElementInfo_Control_ElementComment.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElementComment'; end;//Tkw_FoldersElementInfo_Control_ElementComment.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_ElementComment_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ElementComment'); inherited; end;//Tkw_FoldersElementInfo_Control_ElementComment_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_ElementComment_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElementComment:push'; end;//Tkw_FoldersElementInfo_Control_ElementComment_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_CaptionPanel.GetString: AnsiString; begin Result := 'CaptionPanel'; end;//Tkw_FoldersElementInfo_Control_CaptionPanel.GetString class procedure Tkw_FoldersElementInfo_Control_CaptionPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_FoldersElementInfo_Control_CaptionPanel.RegisterInEngine class function Tkw_FoldersElementInfo_Control_CaptionPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CaptionPanel'; end;//Tkw_FoldersElementInfo_Control_CaptionPanel.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_CaptionPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('CaptionPanel'); inherited; end;//Tkw_FoldersElementInfo_Control_CaptionPanel_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_CaptionPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CaptionPanel:push'; end;//Tkw_FoldersElementInfo_Control_CaptionPanel_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_lblComment.GetString: AnsiString; begin Result := 'lblComment'; end;//Tkw_FoldersElementInfo_Control_lblComment.GetString class procedure Tkw_FoldersElementInfo_Control_lblComment.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_FoldersElementInfo_Control_lblComment.RegisterInEngine class function Tkw_FoldersElementInfo_Control_lblComment.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblComment'; end;//Tkw_FoldersElementInfo_Control_lblComment.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_lblComment_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('lblComment'); inherited; end;//Tkw_FoldersElementInfo_Control_lblComment_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_lblComment_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblComment:push'; end;//Tkw_FoldersElementInfo_Control_lblComment_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_TopPanel.GetString: AnsiString; begin Result := 'TopPanel'; end;//Tkw_FoldersElementInfo_Control_TopPanel.GetString class procedure Tkw_FoldersElementInfo_Control_TopPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_FoldersElementInfo_Control_TopPanel.RegisterInEngine class function Tkw_FoldersElementInfo_Control_TopPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TopPanel'; end;//Tkw_FoldersElementInfo_Control_TopPanel.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_TopPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('TopPanel'); inherited; end;//Tkw_FoldersElementInfo_Control_TopPanel_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_TopPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TopPanel:push'; end;//Tkw_FoldersElementInfo_Control_TopPanel_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_NamePanel.GetString: AnsiString; begin Result := 'NamePanel'; end;//Tkw_FoldersElementInfo_Control_NamePanel.GetString class procedure Tkw_FoldersElementInfo_Control_NamePanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_FoldersElementInfo_Control_NamePanel.RegisterInEngine class function Tkw_FoldersElementInfo_Control_NamePanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::NamePanel'; end;//Tkw_FoldersElementInfo_Control_NamePanel.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_NamePanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('NamePanel'); inherited; end;//Tkw_FoldersElementInfo_Control_NamePanel_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_NamePanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::NamePanel:push'; end;//Tkw_FoldersElementInfo_Control_NamePanel_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_lblElementName.GetString: AnsiString; begin Result := 'lblElementName'; end;//Tkw_FoldersElementInfo_Control_lblElementName.GetString class procedure Tkw_FoldersElementInfo_Control_lblElementName.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_FoldersElementInfo_Control_lblElementName.RegisterInEngine class function Tkw_FoldersElementInfo_Control_lblElementName.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblElementName'; end;//Tkw_FoldersElementInfo_Control_lblElementName.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_lblElementName_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('lblElementName'); inherited; end;//Tkw_FoldersElementInfo_Control_lblElementName_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_lblElementName_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblElementName:push'; end;//Tkw_FoldersElementInfo_Control_lblElementName_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_ElementName.GetString: AnsiString; begin Result := 'ElementName'; end;//Tkw_FoldersElementInfo_Control_ElementName.GetString class procedure Tkw_FoldersElementInfo_Control_ElementName.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscComboBoxWithReadOnly); end;//Tkw_FoldersElementInfo_Control_ElementName.RegisterInEngine class function Tkw_FoldersElementInfo_Control_ElementName.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElementName'; end;//Tkw_FoldersElementInfo_Control_ElementName.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_ElementName_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ElementName'); inherited; end;//Tkw_FoldersElementInfo_Control_ElementName_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_ElementName_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElementName:push'; end;//Tkw_FoldersElementInfo_Control_ElementName_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_cbShared.GetString: AnsiString; begin Result := 'cbShared'; end;//Tkw_FoldersElementInfo_Control_cbShared.GetString class procedure Tkw_FoldersElementInfo_Control_cbShared.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtCheckBox); end;//Tkw_FoldersElementInfo_Control_cbShared.RegisterInEngine class function Tkw_FoldersElementInfo_Control_cbShared.GetWordNameForRegister: AnsiString; begin Result := 'контрол::cbShared'; end;//Tkw_FoldersElementInfo_Control_cbShared.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_cbShared_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('cbShared'); inherited; end;//Tkw_FoldersElementInfo_Control_cbShared_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_cbShared_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::cbShared:push'; end;//Tkw_FoldersElementInfo_Control_cbShared_Push.GetWordNameForRegister function Tkw_FoldersElementInfo_Control_InfoName.GetString: AnsiString; begin Result := 'InfoName'; end;//Tkw_FoldersElementInfo_Control_InfoName.GetString class procedure Tkw_FoldersElementInfo_Control_InfoName.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_FoldersElementInfo_Control_InfoName.RegisterInEngine class function Tkw_FoldersElementInfo_Control_InfoName.GetWordNameForRegister: AnsiString; begin Result := 'контрол::InfoName'; end;//Tkw_FoldersElementInfo_Control_InfoName.GetWordNameForRegister procedure Tkw_FoldersElementInfo_Control_InfoName_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('InfoName'); inherited; end;//Tkw_FoldersElementInfo_Control_InfoName_Push.DoDoIt class function Tkw_FoldersElementInfo_Control_InfoName_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::InfoName:push'; end;//Tkw_FoldersElementInfo_Control_InfoName_Push.GetWordNameForRegister function TkwEnFoldersElementInfoCommentPanel.CommentPanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.CommentPanel } begin Result := aenFoldersElementInfo.CommentPanel; end;//TkwEnFoldersElementInfoCommentPanel.CommentPanel class function TkwEnFoldersElementInfoCommentPanel.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.CommentPanel'; end;//TkwEnFoldersElementInfoCommentPanel.GetWordNameForRegister function TkwEnFoldersElementInfoCommentPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnFoldersElementInfoCommentPanel.GetResultTypeInfo function TkwEnFoldersElementInfoCommentPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoCommentPanel.GetAllParamsCount function TkwEnFoldersElementInfoCommentPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoCommentPanel.ParamsTypes procedure TkwEnFoldersElementInfoCommentPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству CommentPanel', aCtx); end;//TkwEnFoldersElementInfoCommentPanel.SetValuePrim procedure TkwEnFoldersElementInfoCommentPanel.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CommentPanel(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoCommentPanel.DoDoIt function TkwEnFoldersElementInfoElementComment.ElementComment(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TeeMemoWithEditOperations; {* Реализация слова скрипта .TenFoldersElementInfo.ElementComment } begin Result := aenFoldersElementInfo.ElementComment; end;//TkwEnFoldersElementInfoElementComment.ElementComment class function TkwEnFoldersElementInfoElementComment.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.ElementComment'; end;//TkwEnFoldersElementInfoElementComment.GetWordNameForRegister function TkwEnFoldersElementInfoElementComment.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TeeMemoWithEditOperations); end;//TkwEnFoldersElementInfoElementComment.GetResultTypeInfo function TkwEnFoldersElementInfoElementComment.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoElementComment.GetAllParamsCount function TkwEnFoldersElementInfoElementComment.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoElementComment.ParamsTypes procedure TkwEnFoldersElementInfoElementComment.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ElementComment', aCtx); end;//TkwEnFoldersElementInfoElementComment.SetValuePrim procedure TkwEnFoldersElementInfoElementComment.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ElementComment(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoElementComment.DoDoIt function TkwEnFoldersElementInfoCaptionPanel.CaptionPanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.CaptionPanel } begin Result := aenFoldersElementInfo.CaptionPanel; end;//TkwEnFoldersElementInfoCaptionPanel.CaptionPanel class function TkwEnFoldersElementInfoCaptionPanel.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.CaptionPanel'; end;//TkwEnFoldersElementInfoCaptionPanel.GetWordNameForRegister function TkwEnFoldersElementInfoCaptionPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnFoldersElementInfoCaptionPanel.GetResultTypeInfo function TkwEnFoldersElementInfoCaptionPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoCaptionPanel.GetAllParamsCount function TkwEnFoldersElementInfoCaptionPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoCaptionPanel.ParamsTypes procedure TkwEnFoldersElementInfoCaptionPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству CaptionPanel', aCtx); end;//TkwEnFoldersElementInfoCaptionPanel.SetValuePrim procedure TkwEnFoldersElementInfoCaptionPanel.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CaptionPanel(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoCaptionPanel.DoDoIt function TkwEnFoldersElementInfoLblComment.lblComment(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtLabel; {* Реализация слова скрипта .TenFoldersElementInfo.lblComment } begin Result := aenFoldersElementInfo.lblComment; end;//TkwEnFoldersElementInfoLblComment.lblComment class function TkwEnFoldersElementInfoLblComment.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.lblComment'; end;//TkwEnFoldersElementInfoLblComment.GetWordNameForRegister function TkwEnFoldersElementInfoLblComment.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnFoldersElementInfoLblComment.GetResultTypeInfo function TkwEnFoldersElementInfoLblComment.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoLblComment.GetAllParamsCount function TkwEnFoldersElementInfoLblComment.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoLblComment.ParamsTypes procedure TkwEnFoldersElementInfoLblComment.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству lblComment', aCtx); end;//TkwEnFoldersElementInfoLblComment.SetValuePrim procedure TkwEnFoldersElementInfoLblComment.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(lblComment(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoLblComment.DoDoIt function TkwEnFoldersElementInfoTopPanel.TopPanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.TopPanel } begin Result := aenFoldersElementInfo.TopPanel; end;//TkwEnFoldersElementInfoTopPanel.TopPanel class function TkwEnFoldersElementInfoTopPanel.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.TopPanel'; end;//TkwEnFoldersElementInfoTopPanel.GetWordNameForRegister function TkwEnFoldersElementInfoTopPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnFoldersElementInfoTopPanel.GetResultTypeInfo function TkwEnFoldersElementInfoTopPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoTopPanel.GetAllParamsCount function TkwEnFoldersElementInfoTopPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoTopPanel.ParamsTypes procedure TkwEnFoldersElementInfoTopPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству TopPanel', aCtx); end;//TkwEnFoldersElementInfoTopPanel.SetValuePrim procedure TkwEnFoldersElementInfoTopPanel.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(TopPanel(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoTopPanel.DoDoIt function TkwEnFoldersElementInfoNamePanel.NamePanel(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtPanel; {* Реализация слова скрипта .TenFoldersElementInfo.NamePanel } begin Result := aenFoldersElementInfo.NamePanel; end;//TkwEnFoldersElementInfoNamePanel.NamePanel class function TkwEnFoldersElementInfoNamePanel.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.NamePanel'; end;//TkwEnFoldersElementInfoNamePanel.GetWordNameForRegister function TkwEnFoldersElementInfoNamePanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnFoldersElementInfoNamePanel.GetResultTypeInfo function TkwEnFoldersElementInfoNamePanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoNamePanel.GetAllParamsCount function TkwEnFoldersElementInfoNamePanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoNamePanel.ParamsTypes procedure TkwEnFoldersElementInfoNamePanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству NamePanel', aCtx); end;//TkwEnFoldersElementInfoNamePanel.SetValuePrim procedure TkwEnFoldersElementInfoNamePanel.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(NamePanel(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoNamePanel.DoDoIt function TkwEnFoldersElementInfoLblElementName.lblElementName(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtLabel; {* Реализация слова скрипта .TenFoldersElementInfo.lblElementName } begin Result := aenFoldersElementInfo.lblElementName; end;//TkwEnFoldersElementInfoLblElementName.lblElementName class function TkwEnFoldersElementInfoLblElementName.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.lblElementName'; end;//TkwEnFoldersElementInfoLblElementName.GetWordNameForRegister function TkwEnFoldersElementInfoLblElementName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnFoldersElementInfoLblElementName.GetResultTypeInfo function TkwEnFoldersElementInfoLblElementName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoLblElementName.GetAllParamsCount function TkwEnFoldersElementInfoLblElementName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoLblElementName.ParamsTypes procedure TkwEnFoldersElementInfoLblElementName.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству lblElementName', aCtx); end;//TkwEnFoldersElementInfoLblElementName.SetValuePrim procedure TkwEnFoldersElementInfoLblElementName.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(lblElementName(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoLblElementName.DoDoIt function TkwEnFoldersElementInfoElementName.ElementName(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TnscComboBoxWithReadOnly; {* Реализация слова скрипта .TenFoldersElementInfo.ElementName } begin Result := aenFoldersElementInfo.ElementName; end;//TkwEnFoldersElementInfoElementName.ElementName class function TkwEnFoldersElementInfoElementName.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.ElementName'; end;//TkwEnFoldersElementInfoElementName.GetWordNameForRegister function TkwEnFoldersElementInfoElementName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscComboBoxWithReadOnly); end;//TkwEnFoldersElementInfoElementName.GetResultTypeInfo function TkwEnFoldersElementInfoElementName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoElementName.GetAllParamsCount function TkwEnFoldersElementInfoElementName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoElementName.ParamsTypes procedure TkwEnFoldersElementInfoElementName.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ElementName', aCtx); end;//TkwEnFoldersElementInfoElementName.SetValuePrim procedure TkwEnFoldersElementInfoElementName.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ElementName(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoElementName.DoDoIt function TkwEnFoldersElementInfoCbShared.cbShared(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtCheckBox; {* Реализация слова скрипта .TenFoldersElementInfo.cbShared } begin Result := aenFoldersElementInfo.cbShared; end;//TkwEnFoldersElementInfoCbShared.cbShared class function TkwEnFoldersElementInfoCbShared.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.cbShared'; end;//TkwEnFoldersElementInfoCbShared.GetWordNameForRegister function TkwEnFoldersElementInfoCbShared.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtCheckBox); end;//TkwEnFoldersElementInfoCbShared.GetResultTypeInfo function TkwEnFoldersElementInfoCbShared.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoCbShared.GetAllParamsCount function TkwEnFoldersElementInfoCbShared.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoCbShared.ParamsTypes procedure TkwEnFoldersElementInfoCbShared.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству cbShared', aCtx); end;//TkwEnFoldersElementInfoCbShared.SetValuePrim procedure TkwEnFoldersElementInfoCbShared.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(cbShared(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoCbShared.DoDoIt function TkwEnFoldersElementInfoInfoName.InfoName(const aCtx: TtfwContext; aenFoldersElementInfo: TenFoldersElementInfo): TvtLabel; {* Реализация слова скрипта .TenFoldersElementInfo.InfoName } begin Result := aenFoldersElementInfo.InfoName; end;//TkwEnFoldersElementInfoInfoName.InfoName class function TkwEnFoldersElementInfoInfoName.GetWordNameForRegister: AnsiString; begin Result := '.TenFoldersElementInfo.InfoName'; end;//TkwEnFoldersElementInfoInfoName.GetWordNameForRegister function TkwEnFoldersElementInfoInfoName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnFoldersElementInfoInfoName.GetResultTypeInfo function TkwEnFoldersElementInfoInfoName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFoldersElementInfoInfoName.GetAllParamsCount function TkwEnFoldersElementInfoInfoName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFoldersElementInfo)]); end;//TkwEnFoldersElementInfoInfoName.ParamsTypes procedure TkwEnFoldersElementInfoInfoName.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству InfoName', aCtx); end;//TkwEnFoldersElementInfoInfoName.SetValuePrim procedure TkwEnFoldersElementInfoInfoName.DoDoIt(const aCtx: TtfwContext); var l_aenFoldersElementInfo: TenFoldersElementInfo; begin try l_aenFoldersElementInfo := TenFoldersElementInfo(aCtx.rEngine.PopObjAs(TenFoldersElementInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFoldersElementInfo: TenFoldersElementInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(InfoName(aCtx, l_aenFoldersElementInfo)); end;//TkwEnFoldersElementInfoInfoName.DoDoIt initialization Tkw_Form_FoldersElementInfo.RegisterInEngine; {* Регистрация Tkw_Form_FoldersElementInfo } Tkw_FoldersElementInfo_Control_CommentPanel.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_CommentPanel } Tkw_FoldersElementInfo_Control_CommentPanel_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_CommentPanel_Push } Tkw_FoldersElementInfo_Control_ElementComment.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_ElementComment } Tkw_FoldersElementInfo_Control_ElementComment_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_ElementComment_Push } Tkw_FoldersElementInfo_Control_CaptionPanel.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_CaptionPanel } Tkw_FoldersElementInfo_Control_CaptionPanel_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_CaptionPanel_Push } Tkw_FoldersElementInfo_Control_lblComment.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_lblComment } Tkw_FoldersElementInfo_Control_lblComment_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_lblComment_Push } Tkw_FoldersElementInfo_Control_TopPanel.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_TopPanel } Tkw_FoldersElementInfo_Control_TopPanel_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_TopPanel_Push } Tkw_FoldersElementInfo_Control_NamePanel.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_NamePanel } Tkw_FoldersElementInfo_Control_NamePanel_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_NamePanel_Push } Tkw_FoldersElementInfo_Control_lblElementName.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_lblElementName } Tkw_FoldersElementInfo_Control_lblElementName_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_lblElementName_Push } Tkw_FoldersElementInfo_Control_ElementName.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_ElementName } Tkw_FoldersElementInfo_Control_ElementName_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_ElementName_Push } Tkw_FoldersElementInfo_Control_cbShared.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_cbShared } Tkw_FoldersElementInfo_Control_cbShared_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_cbShared_Push } Tkw_FoldersElementInfo_Control_InfoName.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_InfoName } Tkw_FoldersElementInfo_Control_InfoName_Push.RegisterInEngine; {* Регистрация Tkw_FoldersElementInfo_Control_InfoName_Push } TkwEnFoldersElementInfoCommentPanel.RegisterInEngine; {* Регистрация enFoldersElementInfo_CommentPanel } TkwEnFoldersElementInfoElementComment.RegisterInEngine; {* Регистрация enFoldersElementInfo_ElementComment } TkwEnFoldersElementInfoCaptionPanel.RegisterInEngine; {* Регистрация enFoldersElementInfo_CaptionPanel } TkwEnFoldersElementInfoLblComment.RegisterInEngine; {* Регистрация enFoldersElementInfo_lblComment } TkwEnFoldersElementInfoTopPanel.RegisterInEngine; {* Регистрация enFoldersElementInfo_TopPanel } TkwEnFoldersElementInfoNamePanel.RegisterInEngine; {* Регистрация enFoldersElementInfo_NamePanel } TkwEnFoldersElementInfoLblElementName.RegisterInEngine; {* Регистрация enFoldersElementInfo_lblElementName } TkwEnFoldersElementInfoElementName.RegisterInEngine; {* Регистрация enFoldersElementInfo_ElementName } TkwEnFoldersElementInfoCbShared.RegisterInEngine; {* Регистрация enFoldersElementInfo_cbShared } TkwEnFoldersElementInfoInfoName.RegisterInEngine; {* Регистрация enFoldersElementInfo_InfoName } TtfwTypeRegistrator.RegisterType(TypeInfo(TenFoldersElementInfo)); {* Регистрация типа TenFoldersElementInfo } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TeeMemoWithEditOperations)); {* Регистрация типа TeeMemoWithEditOperations } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscComboBoxWithReadOnly)); {* Регистрация типа TnscComboBoxWithReadOnly } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtCheckBox)); {* Регистрация типа TvtCheckBox } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit StockDayData_Load; interface uses BaseApp, StockDayDataAccess; function LoadStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess): Boolean; function CheckNeedLoadStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess; ALastDate: Word): Boolean; implementation uses Sysutils, BaseWinFile, define_Price, define_datasrc, //UtilsLog, define_stock_quotes, define_dealstore_header, define_dealstore_file; {$IFNDEF RELEASE} const LOGTAG = 'StockDayData_Load.pas'; {$ENDIF} function LoadStockDayDataFromBuffer(ADataAccess: TStockDayDataAccess; AMemory: pointer): Boolean; forward; function LoadStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess): Boolean; var tmpWinFile: TWinFile; tmpFileUrl: WideString; tmpFileMapView: Pointer; begin Result := false; tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType, GetDealDataSourceCode(ADataAccess.DataSource), Integer(ADataAccess.WeightMode), ADataAccess.StockItem); //Log(LOGTAG, 'LoadStockDayData FileUrl:' + tmpFileUrl); if App.Path.IsFileExists(tmpFileUrl) then begin //Log(LOGTAG, 'FileUrl exist'); tmpWinFile := TWinFile.Create; try if tmpWinFile.OpenFile(tmpFileUrl, false) then begin tmpFileMapView := tmpWinFile.OpenFileMap; if nil <> tmpFileMapView then begin Result := LoadStockDayDataFromBuffer(ADataAccess, tmpFileMapView); end else begin //Log(LOGTAG, 'FileUrl map fail'); end; end else begin //Log(LOGTAG, 'FileUrl open fail'); end; finally tmpWinFile.Free; end; end; end; function ReadStockDayDataHeader(ADataAccess: TStockDayDataAccess; AMemory: pointer): PStore_Quote_M1_Day_Header_V1Rec; var tmpHead: PStore_Quote_M1_Day_Header_V1Rec; begin Result := nil; tmpHead := AMemory; if tmpHead.Header.BaseHeader.CommonHeader.HeadSize = SizeOf(TStore_Quote_M1_Day_Header_V1Rec) then begin if (tmpHead.Header.BaseHeader.CommonHeader.DataType = DataType_Stock) then begin if (tmpHead.Header.BaseHeader.CommonHeader.DataMode = DataMode_DayData) then begin if src_unknown = ADataAccess.DataSource then ADataAccess.DataSource := GetDealDataSource(tmpHead.Header.BaseHeader.CommonHeader.DataSourceId); if ADataAccess.DataSource = GetDealDataSource(tmpHead.Header.BaseHeader.CommonHeader.DataSourceId) then begin Result := tmpHead; end; end; end; end; end; function LoadStockDayDataFromBuffer(ADataAccess: TStockDayDataAccess; AMemory: pointer): Boolean; var tmpHead: PStore_Quote_M1_Day_Header_V1Rec; tmpQuoteData: PStore64; tmpStoreDayData: PStore_Quote64_Day; tmpRTDayData: PRT_Quote_Day; tmpRecordCount: integer; i: integer; begin Result := false; //Log('LoadStockDayData', 'LoadStockDayDataFromBuffer'); tmpHead := ReadStockDayDataHeader(ADataAccess, AMemory); if nil <> tmpHead then begin tmpRecordCount := tmpHead.Header.BaseHeader.CommonHeader.RecordCount; //Log('LoadStockDayData', 'LoadStockDayDataFromBuffer record count:' + IntToStr(tmpRecordCount)); Inc(tmpHead); tmpQuoteData := PStore64(tmpHead); for i := 0 to tmpRecordCount - 1 do begin Result := true; tmpStoreDayData := PStore_Quote64_Day(tmpQuoteData); tmpRTDayData := ADataAccess.CheckOutRecord(tmpStoreDayData.DealDate); if nil <> tmpRTDayData then begin StorePriceRange2RTPricePackRange(@tmpRTDayData.PriceRange, @tmpStoreDayData.PriceRange); tmpRTDayData.DealVolume := tmpStoreDayData.DealVolume; // 8 - 24 成交量 tmpRTDayData.DealAmount := tmpStoreDayData.DealAmount; // 8 - 32 成交金额 tmpRTDayData.Weight.Value := tmpStoreDayData.Weight.Value; // 4 - 40 复权权重 * 100 tmpRTDayData.TotalValue := tmpStoreDayData.TotalValue; // 8 - 48 总市值 tmpRTDayData.DealValue := tmpStoreDayData.DealValue; // 8 - 56 流通市值 end; Inc(tmpQuoteData); end; ADataAccess.Sort; end; end; function CheckNeedLoadStockDayData(App: TBaseApp; ADataAccess: TStockDayDataAccess; ALastDate: Word): Boolean; var tmpWinFile: TWinFile; tmpFileUrl: string; tmpFileMapView: Pointer; tmpHead: PStore_Quote_M1_Day_Header_V1Rec; begin Result := true; tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType, GetDealDataSourceCode(ADataAccess.DataSource), Integer(ADataAccess.WeightMode), ADataAccess.StockItem); if App.Path.IsFileExists(tmpFileUrl) then begin tmpWinFile := TWinFile.Create; try if tmpWinFile.OpenFile(tmpFileUrl, false) then begin tmpFileMapView := tmpWinFile.OpenFileMap; if nil <> tmpFileMapView then begin tmpHead := ReadStockDayDataHeader(ADataAccess, tmpFileMapView); if nil <> tmpHead then begin if tmpHead.Header.LastDealDate >= ALastDate then begin Result := false; end; if Result then begin LoadStockDayDataFromBuffer(ADataAccess, tmpFileMapView); if 1 > ADataAccess.RecordCount then begin if nil <> ADataAccess.StockItem then begin if 0 < ADataAccess.StockItem.FirstDealDate then begin ADataAccess.StockItem.FirstDealDate := 0; ADataAccess.StockItem.IsDataChange := 1; end; end; end; end; end; end; end; finally tmpWinFile.Free; end; end; end; end.
unit TTSRPTRUNTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSRPTRUNRecord = record PAutoInc: Integer; PLenderNum: String[8]; PType: String[6]; PStart: String[20]; PStop: String[20]; PStopStatus: String[10]; PUserID: String[10]; PDescription: String[100]; PNoticeScanDate: String[10]; PLetterDate: String[10]; PNoticeType: String[1]; PReprint: Boolean; PLimit1: Boolean; PLimitNo1: Integer; PLimit2: Boolean; PLimitNo2: Integer; PLimit3: Boolean; PLimitNo3: Integer; PLimit4: Boolean; PLimitNo4: Integer; PLimit5: Boolean; PLimitNo5: Integer; PSortOrder: String[10]; PLoanCif: Integer; PCifs: Integer; PBalanceFrom: Currency; PBalanceTo: Currency; PSeperateNotice: Integer; PPaidouts: Boolean; PMatureFrom: String[10]; PMatureTo: String[10]; POpenFrom: String[10]; POpenTo: String[10]; PReportTitle: String[40]; PPaidDatesFrom: String[10]; PPaidDatesTo: String[10]; PSelectTIDate: Boolean; PSelectTICont: Boolean; PSelectTIWaived: Boolean; PSelectTIHistory: Boolean; PSelectTISatisfied: Boolean; PSelectTINA: Boolean; PExpireDateFrom: String[10]; PExpireDateTo: String[10]; PIncludeTI: Boolean; PNoticeItems: Boolean; PNoticeItemFrom: String[10]; PNoticeItemTo: String[10]; PLoanNotes: Boolean; PTINotes: Boolean; PCoMaker: Boolean; PGuarantor: Boolean; PGroupBy: Integer; PItemCollDesc: Boolean; PItemOfficer: Boolean; PItemBalance: Boolean; PItemBranch: Boolean; PItemDivision: Boolean; PItemOpenDate: Boolean; PItemMatDate: Boolean; PItemAddress: Boolean; PItemCategory: Boolean; PItemPhone: Boolean; PItemStatus: Boolean; PItemDescription: Boolean; PLeadTimeOfficer: Boolean; PLeadTimeNotice: Boolean; PLeadTimeYouPick: Boolean; PLeadTime: Integer; PIncLoans: Boolean; PIncActiveCifs: Boolean; PIncInactiveCifs: Boolean; PIncNotPaidOut: Boolean; PIncPaidOut: Boolean; PIncLoanWithNotes: Boolean; PIncLoanWONotes: Boolean; PIncWithTracked: Boolean; PIncWOTracked: Boolean; PIncWithNoticeItems: Boolean; PIncWONoticeItems: Boolean; PIncLoanNotes: Boolean; PIncCifs: Boolean; PELRecapOnly: Boolean; PExpLoanCif: Boolean; PExpLoanCifNotes: Boolean; PExpTracked: Boolean; PExpTrackedNotes: Boolean; PExpTrackedExtend: Boolean; PExpFormat: Integer; PExpOpt1: Boolean; PExpOpt2: Boolean; PExpOpt3: Boolean; PItemEntryFrom: String[10]; PItemEntryTo: String[10]; PItemEntryBy: String[100]; PShowTIUser: Boolean; PShowTIEntryDate: Boolean; PExcludeCats: Boolean; PDescriptHow: Integer; PDescriptWhat: String[15]; PReferenceHow: Integer; PReferenceWhat: String[15]; PControlStatus: String[10]; PControlMsg: String[30]; PTestRun:Boolean ; PRemoveAll: Boolean; PCifNumber: string[20]; End; TTTSRPTRUNBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSRPTRUNRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSRPTRUN = (TTSRPTRUNPrimaryKey, TTSRPTRUNByLenderType); TTTSRPTRUNTable = class( TDBISAMTableAU ) private FDFAutoInc: TAutoIncField; FDFLenderNum: TStringField; FDFType: TStringField; FDFStart: TStringField; FDFStop: TStringField; FDFStopStatus: TStringField; FDFUserID: TStringField; FDFDescription: TStringField; FDFNoticeScanDate: TStringField; FDFLetterDate: TStringField; FDFNoticeType: TStringField; FDFReprint: TBooleanField; FDFLimit1: TBooleanField; FDFLimitNo1: TIntegerField; FDFLimit2: TBooleanField; FDFLimitNo2: TIntegerField; FDFLimit3: TBooleanField; FDFLimitNo3: TIntegerField; FDFLimit4: TBooleanField; FDFLimitNo4: TIntegerField; FDFLimit5: TBooleanField; FDFLimitNo5: TIntegerField; FDFSortOrder: TStringField; FDFLoanCif: TIntegerField; FDFCifs: TIntegerField; FDFBalanceFrom: TCurrencyField; FDFBalanceTo: TCurrencyField; FDFSeperateNotice: TIntegerField; FDFPaidouts: TBooleanField; FDFMatureFrom: TStringField; FDFMatureTo: TStringField; FDFOpenFrom: TStringField; FDFOpenTo: TStringField; FDFCats: TBlobField; FDFCollCodes: TBlobField; FDFOfficers: TBlobField; FDFBranchs: TBlobField; FDFDivisions: TBlobField; FDFReportTitle: TStringField; FDFPaidDatesFrom: TStringField; FDFPaidDatesTo: TStringField; FDFSelectTIDate: TBooleanField; FDFSelectTICont: TBooleanField; FDFSelectTIWaived: TBooleanField; FDFSelectTIHistory: TBooleanField; FDFSelectTISatisfied: TBooleanField; FDFSelectTINA: TBooleanField; FDFExpireDateFrom: TStringField; FDFExpireDateTo: TStringField; FDFIncludeTI: TBooleanField; FDFNoticeItems: TBooleanField; FDFNoticeItemFrom: TStringField; FDFNoticeItemTo: TStringField; FDFLoanNotes: TBooleanField; FDFTINotes: TBooleanField; FDFCoMaker: TBooleanField; FDFGuarantor: TBooleanField; FDFGroupBy: TIntegerField; FDFItemCollDesc: TBooleanField; FDFItemOfficer: TBooleanField; FDFItemBalance: TBooleanField; FDFItemBranch: TBooleanField; FDFItemDivision: TBooleanField; FDFItemOpenDate: TBooleanField; FDFItemMatDate: TBooleanField; FDFItemAddress: TBooleanField; FDFItemCategory: TBooleanField; FDFItemPhone: TBooleanField; FDFItemStatus: TBooleanField; FDFItemDescription: TBooleanField; FDFLeadTimeOfficer: TBooleanField; FDFLeadTimeNotice: TBooleanField; FDFLeadTimeYouPick: TBooleanField; FDFLeadTime: TIntegerField; FDFIncLoans: TBooleanField; FDFIncActiveCifs: TBooleanField; FDFIncInactiveCifs: TBooleanField; FDFIncNotPaidOut: TBooleanField; FDFIncPaidOut: TBooleanField; FDFIncLoanWithNotes: TBooleanField; FDFIncLoanWONotes: TBooleanField; FDFIncWithTracked: TBooleanField; FDFIncWOTracked: TBooleanField; FDFIncWithNoticeItems: TBooleanField; FDFIncWONoticeItems: TBooleanField; FDFIncLoanNotes: TBooleanField; FDFIncCifs: TBooleanField; FDFELRecapOnly: TBooleanField; FDFExpLoanCif: TBooleanField; FDFExpLoanCifNotes: TBooleanField; FDFExpTracked: TBooleanField; FDFExpTrackedNotes: TBooleanField; FDFExpTrackedExtend: TBooleanField; FDFExpFormat: TIntegerField; FDFExpOpt1: TBooleanField; FDFExpOpt2: TBooleanField; FDFExpOpt3: TBooleanField; FDFItemEntryFrom: TStringField; FDFItemEntryTo: TStringField; FDFItemEntryBy: TStringField; FDFShowTIUser: TBooleanField; FDFShowTIEntryDate: TBooleanField; FDFExcludeCats: TBooleanField; FDFDescriptHow: TIntegerField; FDFDescriptWhat: TStringField; FDFReferenceHow: TIntegerField; FDFReferenceWhat: TStringField; FDFControlStatus: TStringField; FDFControlMsg: TStringField; FDFTestRun: TBooleanField ; FDFRemoveAll: TBooleanField ; FDFCIFNumber: TStringField ; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPType(const Value: String); function GetPType:String; procedure SetPStart(const Value: String); function GetPStart:String; procedure SetPStop(const Value: String); function GetPStop:String; procedure SetPStopStatus(const Value: String); function GetPStopStatus:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPNoticeScanDate(const Value: String); function GetPNoticeScanDate:String; procedure SetPLetterDate(const Value: String); function GetPLetterDate:String; procedure SetPNoticeType(const Value: String); function GetPNoticeType:String; procedure SetPReprint(const Value: Boolean); function GetPReprint:Boolean; procedure SetPLimit1(const Value: Boolean); function GetPLimit1:Boolean; procedure SetPLimitNo1(const Value: Integer); function GetPLimitNo1:Integer; procedure SetPLimit2(const Value: Boolean); function GetPLimit2:Boolean; procedure SetPLimitNo2(const Value: Integer); function GetPLimitNo2:Integer; procedure SetPLimit3(const Value: Boolean); function GetPLimit3:Boolean; procedure SetPLimitNo3(const Value: Integer); function GetPLimitNo3:Integer; procedure SetPLimit4(const Value: Boolean); function GetPLimit4:Boolean; procedure SetPLimitNo4(const Value: Integer); function GetPLimitNo4:Integer; procedure SetPLimit5(const Value: Boolean); function GetPLimit5:Boolean; procedure SetPLimitNo5(const Value: Integer); function GetPLimitNo5:Integer; procedure SetPSortOrder(const Value: String); function GetPSortOrder:String; procedure SetPLoanCif(const Value: Integer); function GetPLoanCif:Integer; procedure SetPCifs(const Value: Integer); function GetPCifs:Integer; procedure SetPBalanceFrom(const Value: Currency); function GetPBalanceFrom:Currency; procedure SetPBalanceTo(const Value: Currency); function GetPBalanceTo:Currency; procedure SetPSeperateNotice(const Value: Integer); function GetPSeperateNotice:Integer; procedure SetPPaidouts(const Value: Boolean); function GetPPaidouts:Boolean; procedure SetPMatureFrom(const Value: String); function GetPMatureFrom:String; procedure SetPMatureTo(const Value: String); function GetPMatureTo:String; procedure SetPOpenFrom(const Value: String); function GetPOpenFrom:String; procedure SetPOpenTo(const Value: String); function GetPOpenTo:String; procedure SetPReportTitle(const Value: String); function GetPReportTitle:String; procedure SetPPaidDatesFrom(const Value: String); function GetPPaidDatesFrom:String; procedure SetPPaidDatesTo(const Value: String); function GetPPaidDatesTo:String; procedure SetPSelectTIDate(const Value: Boolean); function GetPSelectTIDate:Boolean; procedure SetPSelectTICont(const Value: Boolean); function GetPSelectTICont:Boolean; procedure SetPSelectTIWaived(const Value: Boolean); function GetPSelectTIWaived:Boolean; procedure SetPSelectTIHistory(const Value: Boolean); function GetPSelectTIHistory:Boolean; procedure SetPSelectTISatisfied(const Value: Boolean); function GetPSelectTISatisfied:Boolean; procedure SetPSelectTINA(const Value: Boolean); function GetPSelectTINA:Boolean; procedure SetPExpireDateFrom(const Value: String); function GetPExpireDateFrom:String; procedure SetPExpireDateTo(const Value: String); function GetPExpireDateTo:String; procedure SetPIncludeTI(const Value: Boolean); function GetPIncludeTI:Boolean; procedure SetPNoticeItems(const Value: Boolean); function GetPNoticeItems:Boolean; procedure SetPNoticeItemFrom(const Value: String); function GetPNoticeItemFrom:String; procedure SetPNoticeItemTo(const Value: String); function GetPNoticeItemTo:String; procedure SetPLoanNotes(const Value: Boolean); function GetPLoanNotes:Boolean; procedure SetPTINotes(const Value: Boolean); function GetPTINotes:Boolean; procedure SetPCoMaker(const Value: Boolean); function GetPCoMaker:Boolean; procedure SetPGuarantor(const Value: Boolean); function GetPGuarantor:Boolean; procedure SetPGroupBy(const Value: Integer); function GetPGroupBy:Integer; procedure SetPItemCollDesc(const Value: Boolean); function GetPItemCollDesc:Boolean; procedure SetPItemOfficer(const Value: Boolean); function GetPItemOfficer:Boolean; procedure SetPItemBalance(const Value: Boolean); function GetPItemBalance:Boolean; procedure SetPItemBranch(const Value: Boolean); function GetPItemBranch:Boolean; procedure SetPItemDivision(const Value: Boolean); function GetPItemDivision:Boolean; procedure SetPItemOpenDate(const Value: Boolean); function GetPItemOpenDate:Boolean; procedure SetPItemMatDate(const Value: Boolean); function GetPItemMatDate:Boolean; procedure SetPItemAddress(const Value: Boolean); function GetPItemAddress:Boolean; procedure SetPItemCategory(const Value: Boolean); function GetPItemCategory:Boolean; procedure SetPItemPhone(const Value: Boolean); function GetPItemPhone:Boolean; procedure SetPItemStatus(const Value: Boolean); function GetPItemStatus:Boolean; procedure SetPItemDescription(const Value: Boolean); function GetPItemDescription:Boolean; procedure SetPLeadTimeOfficer(const Value: Boolean); function GetPLeadTimeOfficer:Boolean; procedure SetPLeadTimeNotice(const Value: Boolean); function GetPLeadTimeNotice:Boolean; procedure SetPLeadTimeYouPick(const Value: Boolean); function GetPLeadTimeYouPick:Boolean; procedure SetPLeadTime(const Value: Integer); function GetPLeadTime:Integer; procedure SetPIncLoans(const Value: Boolean); function GetPIncLoans:Boolean; procedure SetPIncActiveCifs(const Value: Boolean); function GetPIncActiveCifs:Boolean; procedure SetPIncInactiveCifs(const Value: Boolean); function GetPIncInactiveCifs:Boolean; procedure SetPIncNotPaidOut(const Value: Boolean); function GetPIncNotPaidOut:Boolean; procedure SetPIncPaidOut(const Value: Boolean); function GetPIncPaidOut:Boolean; procedure SetPIncLoanWithNotes(const Value: Boolean); function GetPIncLoanWithNotes:Boolean; procedure SetPIncLoanWONotes(const Value: Boolean); function GetPIncLoanWONotes:Boolean; procedure SetPIncWithTracked(const Value: Boolean); function GetPIncWithTracked:Boolean; procedure SetPIncWOTracked(const Value: Boolean); function GetPIncWOTracked:Boolean; procedure SetPIncWithNoticeItems(const Value: Boolean); function GetPIncWithNoticeItems:Boolean; procedure SetPIncWONoticeItems(const Value: Boolean); function GetPIncWONoticeItems:Boolean; procedure SetPIncLoanNotes(const Value: Boolean); function GetPIncLoanNotes:Boolean; procedure SetPIncCifs(const Value: Boolean); function GetPIncCifs:Boolean; procedure SetPELRecapOnly(const Value: Boolean); function GetPELRecapOnly:Boolean; procedure SetPExpLoanCif(const Value: Boolean); function GetPExpLoanCif:Boolean; procedure SetPExpLoanCifNotes(const Value: Boolean); function GetPExpLoanCifNotes:Boolean; procedure SetPExpTracked(const Value: Boolean); function GetPExpTracked:Boolean; procedure SetPExpTrackedNotes(const Value: Boolean); function GetPExpTrackedNotes:Boolean; procedure SetPExpTrackedExtend(const Value: Boolean); function GetPExpTrackedExtend:Boolean; procedure SetPExpFormat(const Value: Integer); function GetPExpFormat:Integer; procedure SetPExpOpt1(const Value: Boolean); function GetPExpOpt1:Boolean; procedure SetPExpOpt2(const Value: Boolean); function GetPExpOpt2:Boolean; procedure SetPExpOpt3(const Value: Boolean); function GetPExpOpt3:Boolean; procedure SetPItemEntryFrom(const Value: String); function GetPItemEntryFrom:String; procedure SetPItemEntryTo(const Value: String); function GetPItemEntryTo:String; procedure SetPItemEntryBy(const Value: String); function GetPItemEntryBy:String; procedure SetPShowTIUser(const Value: Boolean); function GetPShowTIUser:Boolean; procedure SetPShowTIEntryDate(const Value: Boolean); function GetPShowTIEntryDate:Boolean; procedure SetPExcludeCats(const Value: Boolean); function GetPExcludeCats:Boolean; procedure SetPDescriptHow(const Value: Integer); function GetPDescriptHow:Integer; procedure SetPDescriptWhat(const Value: String); function GetPDescriptWhat:String; procedure SetPReferenceHow(const Value: Integer); function GetPReferenceHow:Integer; procedure SetPReferenceWhat(const Value: String); function GetPReferenceWhat:String; procedure SetPControlStatus(const Value: String); function GetPControlStatus:String; procedure SetPControlMsg(const Value: String); function GetPControlMsg:String; procedure SetPTestRun(const Value: Boolean); function GetPTestRun:Boolean; procedure SetPRemoveAll(const Value: Boolean); function GetPRemoveAll:Boolean; procedure SetPCIFNumber(const Value: String); function GetPCIFNumber:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSRPTRUN); function GetEnumIndex: TEITTSRPTRUN; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSRPTRUNRecord; procedure StoreDataBuffer(ABuffer:TTTSRPTRUNRecord); property DFAutoInc: TAutoIncField read FDFAutoInc; property DFLenderNum: TStringField read FDFLenderNum; property DFType: TStringField read FDFType; property DFStart: TStringField read FDFStart; property DFStop: TStringField read FDFStop; property DFStopStatus: TStringField read FDFStopStatus; property DFUserID: TStringField read FDFUserID; property DFDescription: TStringField read FDFDescription; property DFNoticeScanDate: TStringField read FDFNoticeScanDate; property DFLetterDate: TStringField read FDFLetterDate; property DFNoticeType: TStringField read FDFNoticeType; property DFReprint: TBooleanField read FDFReprint; property DFLimit1: TBooleanField read FDFLimit1; property DFLimitNo1: TIntegerField read FDFLimitNo1; property DFLimit2: TBooleanField read FDFLimit2; property DFLimitNo2: TIntegerField read FDFLimitNo2; property DFLimit3: TBooleanField read FDFLimit3; property DFLimitNo3: TIntegerField read FDFLimitNo3; property DFLimit4: TBooleanField read FDFLimit4; property DFLimitNo4: TIntegerField read FDFLimitNo4; property DFLimit5: TBooleanField read FDFLimit5; property DFLimitNo5: TIntegerField read FDFLimitNo5; property DFSortOrder: TStringField read FDFSortOrder; property DFLoanCif: TIntegerField read FDFLoanCif; property DFCifs: TIntegerField read FDFCifs; property DFBalanceFrom: TCurrencyField read FDFBalanceFrom; property DFBalanceTo: TCurrencyField read FDFBalanceTo; property DFSeperateNotice: TIntegerField read FDFSeperateNotice; property DFPaidouts: TBooleanField read FDFPaidouts; property DFMatureFrom: TStringField read FDFMatureFrom; property DFMatureTo: TStringField read FDFMatureTo; property DFOpenFrom: TStringField read FDFOpenFrom; property DFOpenTo: TStringField read FDFOpenTo; property DFCats: TBlobField read FDFCats; property DFCollCodes: TBlobField read FDFCollCodes; property DFOfficers: TBlobField read FDFOfficers; property DFBranchs: TBlobField read FDFBranchs; property DFDivisions: TBlobField read FDFDivisions; property DFReportTitle: TStringField read FDFReportTitle; property DFPaidDatesFrom: TStringField read FDFPaidDatesFrom; property DFPaidDatesTo: TStringField read FDFPaidDatesTo; property DFSelectTIDate: TBooleanField read FDFSelectTIDate; property DFSelectTICont: TBooleanField read FDFSelectTICont; property DFSelectTIWaived: TBooleanField read FDFSelectTIWaived; property DFSelectTIHistory: TBooleanField read FDFSelectTIHistory; property DFSelectTISatisfied: TBooleanField read FDFSelectTISatisfied; property DFSelectTINA: TBooleanField read FDFSelectTINA; property DFExpireDateFrom: TStringField read FDFExpireDateFrom; property DFExpireDateTo: TStringField read FDFExpireDateTo; property DFIncludeTI: TBooleanField read FDFIncludeTI; property DFNoticeItems: TBooleanField read FDFNoticeItems; property DFNoticeItemFrom: TStringField read FDFNoticeItemFrom; property DFNoticeItemTo: TStringField read FDFNoticeItemTo; property DFLoanNotes: TBooleanField read FDFLoanNotes; property DFTINotes: TBooleanField read FDFTINotes; property DFCoMaker: TBooleanField read FDFCoMaker; property DFGuarantor: TBooleanField read FDFGuarantor; property DFGroupBy: TIntegerField read FDFGroupBy; property DFItemCollDesc: TBooleanField read FDFItemCollDesc; property DFItemOfficer: TBooleanField read FDFItemOfficer; property DFItemBalance: TBooleanField read FDFItemBalance; property DFItemBranch: TBooleanField read FDFItemBranch; property DFItemDivision: TBooleanField read FDFItemDivision; property DFItemOpenDate: TBooleanField read FDFItemOpenDate; property DFItemMatDate: TBooleanField read FDFItemMatDate; property DFItemAddress: TBooleanField read FDFItemAddress; property DFItemCategory: TBooleanField read FDFItemCategory; property DFItemPhone: TBooleanField read FDFItemPhone; property DFItemStatus: TBooleanField read FDFItemStatus; property DFItemDescription: TBooleanField read FDFItemDescription; property DFLeadTimeOfficer: TBooleanField read FDFLeadTimeOfficer; property DFLeadTimeNotice: TBooleanField read FDFLeadTimeNotice; property DFLeadTimeYouPick: TBooleanField read FDFLeadTimeYouPick; property DFLeadTime: TIntegerField read FDFLeadTime; property DFIncLoans: TBooleanField read FDFIncLoans; property DFIncActiveCifs: TBooleanField read FDFIncActiveCifs; property DFIncInactiveCifs: TBooleanField read FDFIncInactiveCifs; property DFIncNotPaidOut: TBooleanField read FDFIncNotPaidOut; property DFIncPaidOut: TBooleanField read FDFIncPaidOut; property DFIncLoanWithNotes: TBooleanField read FDFIncLoanWithNotes; property DFIncLoanWONotes: TBooleanField read FDFIncLoanWONotes; property DFIncWithTracked: TBooleanField read FDFIncWithTracked; property DFIncWOTracked: TBooleanField read FDFIncWOTracked; property DFIncWithNoticeItems: TBooleanField read FDFIncWithNoticeItems; property DFIncWONoticeItems: TBooleanField read FDFIncWONoticeItems; property DFIncLoanNotes: TBooleanField read FDFIncLoanNotes; property DFIncCifs: TBooleanField read FDFIncCifs; property DFELRecapOnly: TBooleanField read FDFELRecapOnly; property DFExpLoanCif: TBooleanField read FDFExpLoanCif; property DFExpLoanCifNotes: TBooleanField read FDFExpLoanCifNotes; property DFExpTracked: TBooleanField read FDFExpTracked; property DFExpTrackedNotes: TBooleanField read FDFExpTrackedNotes; property DFExpTrackedExtend: TBooleanField read FDFExpTrackedExtend; property DFExpFormat: TIntegerField read FDFExpFormat; property DFExpOpt1: TBooleanField read FDFExpOpt1; property DFExpOpt2: TBooleanField read FDFExpOpt2; property DFExpOpt3: TBooleanField read FDFExpOpt3; property DFItemEntryFrom: TStringField read FDFItemEntryFrom; property DFItemEntryTo: TStringField read FDFItemEntryTo; property DFItemEntryBy: TStringField read FDFItemEntryBy; property DFShowTIUser: TBooleanField read FDFShowTIUser; property DFShowTIEntryDate: TBooleanField read FDFShowTIEntryDate; property DFExcludeCats: TBooleanField read FDFExcludeCats; property DFDescriptHow: TIntegerField read FDFDescriptHow; property DFDescriptWhat: TStringField read FDFDescriptWhat; property DFReferenceHow: TIntegerField read FDFReferenceHow; property DFReferenceWhat: TStringField read FDFReferenceWhat; property DFControlStatus: TStringField read FDFControlStatus; property DFControlMsg: TStringField read FDFControlMsg; property DFTestRun: TBooleanField read FDFTestRun ; property DFRemoveAll: TBooleanField read FDFRemoveAll ; property DFCIFNumber: TStringField read FDFCIFNumber ; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PType: String read GetPType write SetPType; property PStart: String read GetPStart write SetPStart; property PStop: String read GetPStop write SetPStop; property PStopStatus: String read GetPStopStatus write SetPStopStatus; property PUserID: String read GetPUserID write SetPUserID; property PDescription: String read GetPDescription write SetPDescription; property PNoticeScanDate: String read GetPNoticeScanDate write SetPNoticeScanDate; property PLetterDate: String read GetPLetterDate write SetPLetterDate; property PNoticeType: String read GetPNoticeType write SetPNoticeType; property PReprint: Boolean read GetPReprint write SetPReprint; property PLimit1: Boolean read GetPLimit1 write SetPLimit1; property PLimitNo1: Integer read GetPLimitNo1 write SetPLimitNo1; property PLimit2: Boolean read GetPLimit2 write SetPLimit2; property PLimitNo2: Integer read GetPLimitNo2 write SetPLimitNo2; property PLimit3: Boolean read GetPLimit3 write SetPLimit3; property PLimitNo3: Integer read GetPLimitNo3 write SetPLimitNo3; property PLimit4: Boolean read GetPLimit4 write SetPLimit4; property PLimitNo4: Integer read GetPLimitNo4 write SetPLimitNo4; property PLimit5: Boolean read GetPLimit5 write SetPLimit5; property PLimitNo5: Integer read GetPLimitNo5 write SetPLimitNo5; property PSortOrder: String read GetPSortOrder write SetPSortOrder; property PLoanCif: Integer read GetPLoanCif write SetPLoanCif; property PCifs: Integer read GetPCifs write SetPCifs; property PBalanceFrom: Currency read GetPBalanceFrom write SetPBalanceFrom; property PBalanceTo: Currency read GetPBalanceTo write SetPBalanceTo; property PSeperateNotice: Integer read GetPSeperateNotice write SetPSeperateNotice; property PPaidouts: Boolean read GetPPaidouts write SetPPaidouts; property PMatureFrom: String read GetPMatureFrom write SetPMatureFrom; property PMatureTo: String read GetPMatureTo write SetPMatureTo; property POpenFrom: String read GetPOpenFrom write SetPOpenFrom; property POpenTo: String read GetPOpenTo write SetPOpenTo; property PReportTitle: String read GetPReportTitle write SetPReportTitle; property PPaidDatesFrom: String read GetPPaidDatesFrom write SetPPaidDatesFrom; property PPaidDatesTo: String read GetPPaidDatesTo write SetPPaidDatesTo; property PSelectTIDate: Boolean read GetPSelectTIDate write SetPSelectTIDate; property PSelectTICont: Boolean read GetPSelectTICont write SetPSelectTICont; property PSelectTIWaived: Boolean read GetPSelectTIWaived write SetPSelectTIWaived; property PSelectTIHistory: Boolean read GetPSelectTIHistory write SetPSelectTIHistory; property PSelectTISatisfied: Boolean read GetPSelectTISatisfied write SetPSelectTISatisfied; property PSelectTINA: Boolean read GetPSelectTINA write SetPSelectTINA; property PExpireDateFrom: String read GetPExpireDateFrom write SetPExpireDateFrom; property PExpireDateTo: String read GetPExpireDateTo write SetPExpireDateTo; property PIncludeTI: Boolean read GetPIncludeTI write SetPIncludeTI; property PNoticeItems: Boolean read GetPNoticeItems write SetPNoticeItems; property PNoticeItemFrom: String read GetPNoticeItemFrom write SetPNoticeItemFrom; property PNoticeItemTo: String read GetPNoticeItemTo write SetPNoticeItemTo; property PLoanNotes: Boolean read GetPLoanNotes write SetPLoanNotes; property PTINotes: Boolean read GetPTINotes write SetPTINotes; property PCoMaker: Boolean read GetPCoMaker write SetPCoMaker; property PGuarantor: Boolean read GetPGuarantor write SetPGuarantor; property PGroupBy: Integer read GetPGroupBy write SetPGroupBy; property PItemCollDesc: Boolean read GetPItemCollDesc write SetPItemCollDesc; property PItemOfficer: Boolean read GetPItemOfficer write SetPItemOfficer; property PItemBalance: Boolean read GetPItemBalance write SetPItemBalance; property PItemBranch: Boolean read GetPItemBranch write SetPItemBranch; property PItemDivision: Boolean read GetPItemDivision write SetPItemDivision; property PItemOpenDate: Boolean read GetPItemOpenDate write SetPItemOpenDate; property PItemMatDate: Boolean read GetPItemMatDate write SetPItemMatDate; property PItemAddress: Boolean read GetPItemAddress write SetPItemAddress; property PItemCategory: Boolean read GetPItemCategory write SetPItemCategory; property PItemPhone: Boolean read GetPItemPhone write SetPItemPhone; property PItemStatus: Boolean read GetPItemStatus write SetPItemStatus; property PItemDescription: Boolean read GetPItemDescription write SetPItemDescription; property PLeadTimeOfficer: Boolean read GetPLeadTimeOfficer write SetPLeadTimeOfficer; property PLeadTimeNotice: Boolean read GetPLeadTimeNotice write SetPLeadTimeNotice; property PLeadTimeYouPick: Boolean read GetPLeadTimeYouPick write SetPLeadTimeYouPick; property PLeadTime: Integer read GetPLeadTime write SetPLeadTime; property PIncLoans: Boolean read GetPIncLoans write SetPIncLoans; property PIncActiveCifs: Boolean read GetPIncActiveCifs write SetPIncActiveCifs; property PIncInactiveCifs: Boolean read GetPIncInactiveCifs write SetPIncInactiveCifs; property PIncNotPaidOut: Boolean read GetPIncNotPaidOut write SetPIncNotPaidOut; property PIncPaidOut: Boolean read GetPIncPaidOut write SetPIncPaidOut; property PIncLoanWithNotes: Boolean read GetPIncLoanWithNotes write SetPIncLoanWithNotes; property PIncLoanWONotes: Boolean read GetPIncLoanWONotes write SetPIncLoanWONotes; property PIncWithTracked: Boolean read GetPIncWithTracked write SetPIncWithTracked; property PIncWOTracked: Boolean read GetPIncWOTracked write SetPIncWOTracked; property PIncWithNoticeItems: Boolean read GetPIncWithNoticeItems write SetPIncWithNoticeItems; property PIncWONoticeItems: Boolean read GetPIncWONoticeItems write SetPIncWONoticeItems; property PIncLoanNotes: Boolean read GetPIncLoanNotes write SetPIncLoanNotes; property PIncCifs: Boolean read GetPIncCifs write SetPIncCifs; property PELRecapOnly: Boolean read GetPELRecapOnly write SetPELRecapOnly; property PExpLoanCif: Boolean read GetPExpLoanCif write SetPExpLoanCif; property PExpLoanCifNotes: Boolean read GetPExpLoanCifNotes write SetPExpLoanCifNotes; property PExpTracked: Boolean read GetPExpTracked write SetPExpTracked; property PExpTrackedNotes: Boolean read GetPExpTrackedNotes write SetPExpTrackedNotes; property PExpTrackedExtend: Boolean read GetPExpTrackedExtend write SetPExpTrackedExtend; property PExpFormat: Integer read GetPExpFormat write SetPExpFormat; property PExpOpt1: Boolean read GetPExpOpt1 write SetPExpOpt1; property PExpOpt2: Boolean read GetPExpOpt2 write SetPExpOpt2; property PExpOpt3: Boolean read GetPExpOpt3 write SetPExpOpt3; property PItemEntryFrom: String read GetPItemEntryFrom write SetPItemEntryFrom; property PItemEntryTo: String read GetPItemEntryTo write SetPItemEntryTo; property PItemEntryBy: String read GetPItemEntryBy write SetPItemEntryBy; property PShowTIUser: Boolean read GetPShowTIUser write SetPShowTIUser; property PShowTIEntryDate: Boolean read GetPShowTIEntryDate write SetPShowTIEntryDate; property PExcludeCats: Boolean read GetPExcludeCats write SetPExcludeCats; property PDescriptHow: Integer read GetPDescriptHow write SetPDescriptHow; property PDescriptWhat: String read GetPDescriptWhat write SetPDescriptWhat; property PReferenceHow: Integer read GetPReferenceHow write SetPReferenceHow; property PReferenceWhat: String read GetPReferenceWhat write SetPReferenceWhat; property PControlStatus: String read GetPControlStatus write SetPControlStatus; property PControlMsg: String read GetPControlMsg write SetPControlMsg; property PTestRun: Boolean read GetPTestRun write SetPTestRun ; property PRemoveAll: Boolean read GetPRemoveAll write SetPRemoveAll ; property PCIFNumber: String read GetPCIFNumber write SetPCIFNumber ; published property Active write SetActive; property EnumIndex: TEITTSRPTRUN read GetEnumIndex write SetEnumIndex; end; { TTTSRPTRUNTable } procedure Register; implementation function TTTSRPTRUNTable.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 { TTTSRPTRUNTable.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; { TTTSRPTRUNTable.GenerateNewFieldName } function TTTSRPTRUNTable.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; { TTTSRPTRUNTable.CreateField } procedure TTTSRPTRUNTable.CreateFields; begin FDFAutoInc := CreateField( 'AutoInc' ) as TAutoIncField; FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFType := CreateField( 'Type' ) as TStringField; FDFStart := CreateField( 'Start' ) as TStringField; FDFStop := CreateField( 'Stop' ) as TStringField; FDFStopStatus := CreateField( 'StopStatus' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFNoticeScanDate := CreateField( 'NoticeScanDate' ) as TStringField; FDFLetterDate := CreateField( 'LetterDate' ) as TStringField; FDFNoticeType := CreateField( 'NoticeType' ) as TStringField; FDFReprint := CreateField( 'Reprint' ) as TBooleanField; FDFLimit1 := CreateField( 'Limit1' ) as TBooleanField; FDFLimitNo1 := CreateField( 'LimitNo1' ) as TIntegerField; FDFLimit2 := CreateField( 'Limit2' ) as TBooleanField; FDFLimitNo2 := CreateField( 'LimitNo2' ) as TIntegerField; FDFLimit3 := CreateField( 'Limit3' ) as TBooleanField; FDFLimitNo3 := CreateField( 'LimitNo3' ) as TIntegerField; FDFLimit4 := CreateField( 'Limit4' ) as TBooleanField; FDFLimitNo4 := CreateField( 'LimitNo4' ) as TIntegerField; FDFLimit5 := CreateField( 'Limit5' ) as TBooleanField; FDFLimitNo5 := CreateField( 'LimitNo5' ) as TIntegerField; FDFSortOrder := CreateField( 'SortOrder' ) as TStringField; FDFLoanCif := CreateField( 'LoanCif' ) as TIntegerField; FDFCifs := CreateField( 'Cifs' ) as TIntegerField; FDFBalanceFrom := CreateField( 'BalanceFrom' ) as TCurrencyField; FDFBalanceTo := CreateField( 'BalanceTo' ) as TCurrencyField; FDFSeperateNotice := CreateField( 'SeperateNotice' ) as TIntegerField; FDFPaidouts := CreateField( 'Paidouts' ) as TBooleanField; FDFMatureFrom := CreateField( 'MatureFrom' ) as TStringField; FDFMatureTo := CreateField( 'MatureTo' ) as TStringField; FDFOpenFrom := CreateField( 'OpenFrom' ) as TStringField; FDFOpenTo := CreateField( 'OpenTo' ) as TStringField; FDFCats := CreateField( 'Cats' ) as TBlobField; FDFCollCodes := CreateField( 'CollCodes' ) as TBlobField; FDFOfficers := CreateField( 'Officers' ) as TBlobField; FDFBranchs := CreateField( 'Branchs' ) as TBlobField; FDFDivisions := CreateField( 'Divisions' ) as TBlobField; FDFReportTitle := CreateField( 'ReportTitle' ) as TStringField; FDFPaidDatesFrom := CreateField( 'PaidDatesFrom' ) as TStringField; FDFPaidDatesTo := CreateField( 'PaidDatesTo' ) as TStringField; FDFSelectTIDate := CreateField( 'SelectTIDate' ) as TBooleanField; FDFSelectTICont := CreateField( 'SelectTICont' ) as TBooleanField; FDFSelectTIWaived := CreateField( 'SelectTIWaived' ) as TBooleanField; FDFSelectTIHistory := CreateField( 'SelectTIHistory' ) as TBooleanField; FDFSelectTISatisfied := CreateField( 'SelectTISatisfied' ) as TBooleanField; FDFSelectTINA := CreateField( 'SelectTINA' ) as TBooleanField; FDFExpireDateFrom := CreateField( 'ExpireDateFrom' ) as TStringField; FDFExpireDateTo := CreateField( 'ExpireDateTo' ) as TStringField; FDFIncludeTI := CreateField( 'IncludeTI' ) as TBooleanField; FDFNoticeItems := CreateField( 'NoticeItems' ) as TBooleanField; FDFNoticeItemFrom := CreateField( 'NoticeItemFrom' ) as TStringField; FDFNoticeItemTo := CreateField( 'NoticeItemTo' ) as TStringField; FDFLoanNotes := CreateField( 'LoanNotes' ) as TBooleanField; FDFTINotes := CreateField( 'TINotes' ) as TBooleanField; FDFCoMaker := CreateField( 'CoMaker' ) as TBooleanField; FDFGuarantor := CreateField( 'Guarantor' ) as TBooleanField; FDFGroupBy := CreateField( 'GroupBy' ) as TIntegerField; FDFItemCollDesc := CreateField( 'ItemCollDesc' ) as TBooleanField; FDFItemOfficer := CreateField( 'ItemOfficer' ) as TBooleanField; FDFItemBalance := CreateField( 'ItemBalance' ) as TBooleanField; FDFItemBranch := CreateField( 'ItemBranch' ) as TBooleanField; FDFItemDivision := CreateField( 'ItemDivision' ) as TBooleanField; FDFItemOpenDate := CreateField( 'ItemOpenDate' ) as TBooleanField; FDFItemMatDate := CreateField( 'ItemMatDate' ) as TBooleanField; FDFItemAddress := CreateField( 'ItemAddress' ) as TBooleanField; FDFItemCategory := CreateField( 'ItemCategory' ) as TBooleanField; FDFItemPhone := CreateField( 'ItemPhone' ) as TBooleanField; FDFItemStatus := CreateField( 'ItemStatus' ) as TBooleanField; FDFItemDescription := CreateField( 'ItemDescription' ) as TBooleanField; FDFLeadTimeOfficer := CreateField( 'LeadTimeOfficer' ) as TBooleanField; FDFLeadTimeNotice := CreateField( 'LeadTimeNotice' ) as TBooleanField; FDFLeadTimeYouPick := CreateField( 'LeadTimeYouPick' ) as TBooleanField; FDFLeadTime := CreateField( 'LeadTime' ) as TIntegerField; FDFIncLoans := CreateField( 'IncLoans' ) as TBooleanField; FDFIncActiveCifs := CreateField( 'IncActiveCifs' ) as TBooleanField; FDFIncInactiveCifs := CreateField( 'IncInactiveCifs' ) as TBooleanField; FDFIncNotPaidOut := CreateField( 'IncNotPaidOut' ) as TBooleanField; FDFIncPaidOut := CreateField( 'IncPaidOut' ) as TBooleanField; FDFIncLoanWithNotes := CreateField( 'IncLoanWithNotes' ) as TBooleanField; FDFIncLoanWONotes := CreateField( 'IncLoanWONotes' ) as TBooleanField; FDFIncWithTracked := CreateField( 'IncWithTracked' ) as TBooleanField; FDFIncWOTracked := CreateField( 'IncWOTracked' ) as TBooleanField; FDFIncWithNoticeItems := CreateField( 'IncWithNoticeItems' ) as TBooleanField; FDFIncWONoticeItems := CreateField( 'IncWONoticeItems' ) as TBooleanField; FDFIncLoanNotes := CreateField( 'IncLoanNotes' ) as TBooleanField; FDFIncCifs := CreateField( 'IncCifs' ) as TBooleanField; FDFELRecapOnly := CreateField( 'ELRecapOnly' ) as TBooleanField; FDFExpLoanCif := CreateField( 'ExpLoanCif' ) as TBooleanField; FDFExpLoanCifNotes := CreateField( 'ExpLoanCifNotes' ) as TBooleanField; FDFExpTracked := CreateField( 'ExpTracked' ) as TBooleanField; FDFExpTrackedNotes := CreateField( 'ExpTrackedNotes' ) as TBooleanField; FDFExpTrackedExtend := CreateField( 'ExpTrackedExtend' ) as TBooleanField; FDFExpFormat := CreateField( 'ExpFormat' ) as TIntegerField; FDFExpOpt1 := CreateField( 'ExpOpt1' ) as TBooleanField; FDFExpOpt2 := CreateField( 'ExpOpt2' ) as TBooleanField; FDFExpOpt3 := CreateField( 'ExpOpt3' ) as TBooleanField; FDFItemEntryFrom := CreateField( 'ItemEntryFrom' ) as TStringField; FDFItemEntryTo := CreateField( 'ItemEntryTo' ) as TStringField; FDFItemEntryBy := CreateField( 'ItemEntryBy' ) as TStringField; FDFShowTIUser := CreateField( 'ShowTIUser' ) as TBooleanField; FDFShowTIEntryDate := CreateField( 'ShowTIEntryDate' ) as TBooleanField; FDFExcludeCats := CreateField( 'ExcludeCats' ) as TBooleanField; FDFDescriptHow := CreateField( 'DescriptHow' ) as TIntegerField; FDFDescriptWhat := CreateField( 'DescriptWhat' ) as TStringField; FDFReferenceHow := CreateField( 'ReferenceHow' ) as TIntegerField; FDFReferenceWhat := CreateField( 'ReferenceWhat' ) as TStringField; FDFControlStatus := CreateField( 'ControlStatus' ) as TStringField; FDFControlMsg := CreateField( 'ControlMsg' ) as TStringField; FDFTestRun := CreateField( 'TestRun' ) as TBooleanField; FDFRemoveAll := CreateField( 'RemoveAll' ) as TBooleanField; FDFCIFNumber := CreateField( 'CIFNumber' ) as TStringField; end; { TTTSRPTRUNTable.CreateFields } procedure TTTSRPTRUNTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSRPTRUNTable.SetActive } procedure TTTSRPTRUNTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSRPTRUNTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSRPTRUNTable.SetPType(const Value: String); begin DFType.Value := Value; end; function TTTSRPTRUNTable.GetPType:String; begin result := DFType.Value; end; procedure TTTSRPTRUNTable.SetPStart(const Value: String); begin DFStart.Value := Value; end; function TTTSRPTRUNTable.GetPStart:String; begin result := DFStart.Value; end; procedure TTTSRPTRUNTable.SetPStop(const Value: String); begin DFStop.Value := Value; end; function TTTSRPTRUNTable.GetPStop:String; begin result := DFStop.Value; end; procedure TTTSRPTRUNTable.SetPStopStatus(const Value: String); begin DFStopStatus.Value := Value; end; function TTTSRPTRUNTable.GetPStopStatus:String; begin result := DFStopStatus.Value; end; procedure TTTSRPTRUNTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TTTSRPTRUNTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TTTSRPTRUNTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSRPTRUNTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSRPTRUNTable.SetPNoticeScanDate(const Value: String); begin DFNoticeScanDate.Value := Value; end; function TTTSRPTRUNTable.GetPNoticeScanDate:String; begin result := DFNoticeScanDate.Value; end; procedure TTTSRPTRUNTable.SetPLetterDate(const Value: String); begin DFLetterDate.Value := Value; end; function TTTSRPTRUNTable.GetPLetterDate:String; begin result := DFLetterDate.Value; end; procedure TTTSRPTRUNTable.SetPNoticeType(const Value: String); begin DFNoticeType.Value := Value; end; function TTTSRPTRUNTable.GetPNoticeType:String; begin result := DFNoticeType.Value; end; procedure TTTSRPTRUNTable.SetPReprint(const Value: Boolean); begin DFReprint.Value := Value; end; function TTTSRPTRUNTable.GetPReprint:Boolean; begin result := DFReprint.Value; end; procedure TTTSRPTRUNTable.SetPLimit1(const Value: Boolean); begin DFLimit1.Value := Value; end; function TTTSRPTRUNTable.GetPLimit1:Boolean; begin result := DFLimit1.Value; end; procedure TTTSRPTRUNTable.SetPLimitNo1(const Value: Integer); begin DFLimitNo1.Value := Value; end; function TTTSRPTRUNTable.GetPLimitNo1:Integer; begin result := DFLimitNo1.Value; end; procedure TTTSRPTRUNTable.SetPLimit2(const Value: Boolean); begin DFLimit2.Value := Value; end; function TTTSRPTRUNTable.GetPLimit2:Boolean; begin result := DFLimit2.Value; end; procedure TTTSRPTRUNTable.SetPLimitNo2(const Value: Integer); begin DFLimitNo2.Value := Value; end; function TTTSRPTRUNTable.GetPLimitNo2:Integer; begin result := DFLimitNo2.Value; end; procedure TTTSRPTRUNTable.SetPLimit3(const Value: Boolean); begin DFLimit3.Value := Value; end; function TTTSRPTRUNTable.GetPLimit3:Boolean; begin result := DFLimit3.Value; end; procedure TTTSRPTRUNTable.SetPLimitNo3(const Value: Integer); begin DFLimitNo3.Value := Value; end; function TTTSRPTRUNTable.GetPLimitNo3:Integer; begin result := DFLimitNo3.Value; end; procedure TTTSRPTRUNTable.SetPLimit4(const Value: Boolean); begin DFLimit4.Value := Value; end; function TTTSRPTRUNTable.GetPLimit4:Boolean; begin result := DFLimit4.Value; end; procedure TTTSRPTRUNTable.SetPLimitNo4(const Value: Integer); begin DFLimitNo4.Value := Value; end; function TTTSRPTRUNTable.GetPLimitNo4:Integer; begin result := DFLimitNo4.Value; end; procedure TTTSRPTRUNTable.SetPLimit5(const Value: Boolean); begin DFLimit5.Value := Value; end; function TTTSRPTRUNTable.GetPLimit5:Boolean; begin result := DFLimit5.Value; end; procedure TTTSRPTRUNTable.SetPLimitNo5(const Value: Integer); begin DFLimitNo5.Value := Value; end; function TTTSRPTRUNTable.GetPLimitNo5:Integer; begin result := DFLimitNo5.Value; end; procedure TTTSRPTRUNTable.SetPSortOrder(const Value: String); begin DFSortOrder.Value := Value; end; function TTTSRPTRUNTable.GetPSortOrder:String; begin result := DFSortOrder.Value; end; procedure TTTSRPTRUNTable.SetPLoanCif(const Value: Integer); begin DFLoanCif.Value := Value; end; function TTTSRPTRUNTable.GetPLoanCif:Integer; begin result := DFLoanCif.Value; end; procedure TTTSRPTRUNTable.SetPCifs(const Value: Integer); begin DFCifs.Value := Value; end; function TTTSRPTRUNTable.GetPCifs:Integer; begin result := DFCifs.Value; end; procedure TTTSRPTRUNTable.SetPBalanceFrom(const Value: Currency); begin DFBalanceFrom.Value := Value; end; function TTTSRPTRUNTable.GetPBalanceFrom:Currency; begin result := DFBalanceFrom.Value; end; procedure TTTSRPTRUNTable.SetPBalanceTo(const Value: Currency); begin DFBalanceTo.Value := Value; end; function TTTSRPTRUNTable.GetPBalanceTo:Currency; begin result := DFBalanceTo.Value; end; procedure TTTSRPTRUNTable.SetPSeperateNotice(const Value: Integer); begin DFSeperateNotice.Value := Value; end; function TTTSRPTRUNTable.GetPSeperateNotice:Integer; begin result := DFSeperateNotice.Value; end; procedure TTTSRPTRUNTable.SetPPaidouts(const Value: Boolean); begin DFPaidouts.Value := Value; end; function TTTSRPTRUNTable.GetPPaidouts:Boolean; begin result := DFPaidouts.Value; end; procedure TTTSRPTRUNTable.SetPMatureFrom(const Value: String); begin DFMatureFrom.Value := Value; end; function TTTSRPTRUNTable.GetPMatureFrom:String; begin result := DFMatureFrom.Value; end; procedure TTTSRPTRUNTable.SetPMatureTo(const Value: String); begin DFMatureTo.Value := Value; end; function TTTSRPTRUNTable.GetPMatureTo:String; begin result := DFMatureTo.Value; end; procedure TTTSRPTRUNTable.SetPOpenFrom(const Value: String); begin DFOpenFrom.Value := Value; end; function TTTSRPTRUNTable.GetPOpenFrom:String; begin result := DFOpenFrom.Value; end; procedure TTTSRPTRUNTable.SetPOpenTo(const Value: String); begin DFOpenTo.Value := Value; end; function TTTSRPTRUNTable.GetPOpenTo:String; begin result := DFOpenTo.Value; end; procedure TTTSRPTRUNTable.SetPReportTitle(const Value: String); begin DFReportTitle.Value := Value; end; function TTTSRPTRUNTable.GetPReportTitle:String; begin result := DFReportTitle.Value; end; procedure TTTSRPTRUNTable.SetPPaidDatesFrom(const Value: String); begin DFPaidDatesFrom.Value := Value; end; function TTTSRPTRUNTable.GetPPaidDatesFrom:String; begin result := DFPaidDatesFrom.Value; end; procedure TTTSRPTRUNTable.SetPPaidDatesTo(const Value: String); begin DFPaidDatesTo.Value := Value; end; function TTTSRPTRUNTable.GetPPaidDatesTo:String; begin result := DFPaidDatesTo.Value; end; procedure TTTSRPTRUNTable.SetPSelectTIDate(const Value: Boolean); begin DFSelectTIDate.Value := Value; end; function TTTSRPTRUNTable.GetPSelectTIDate:Boolean; begin result := DFSelectTIDate.Value; end; procedure TTTSRPTRUNTable.SetPSelectTICont(const Value: Boolean); begin DFSelectTICont.Value := Value; end; function TTTSRPTRUNTable.GetPSelectTICont:Boolean; begin result := DFSelectTICont.Value; end; procedure TTTSRPTRUNTable.SetPSelectTIWaived(const Value: Boolean); begin DFSelectTIWaived.Value := Value; end; function TTTSRPTRUNTable.GetPSelectTIWaived:Boolean; begin result := DFSelectTIWaived.Value; end; procedure TTTSRPTRUNTable.SetPSelectTIHistory(const Value: Boolean); begin DFSelectTIHistory.Value := Value; end; function TTTSRPTRUNTable.GetPSelectTIHistory:Boolean; begin result := DFSelectTIHistory.Value; end; procedure TTTSRPTRUNTable.SetPSelectTISatisfied(const Value: Boolean); begin DFSelectTISatisfied.Value := Value; end; function TTTSRPTRUNTable.GetPSelectTISatisfied:Boolean; begin result := DFSelectTISatisfied.Value; end; procedure TTTSRPTRUNTable.SetPSelectTINA(const Value: Boolean); begin DFSelectTINA.Value := Value; end; function TTTSRPTRUNTable.GetPSelectTINA:Boolean; begin result := DFSelectTINA.Value; end; procedure TTTSRPTRUNTable.SetPExpireDateFrom(const Value: String); begin DFExpireDateFrom.Value := Value; end; function TTTSRPTRUNTable.GetPExpireDateFrom:String; begin result := DFExpireDateFrom.Value; end; procedure TTTSRPTRUNTable.SetPExpireDateTo(const Value: String); begin DFExpireDateTo.Value := Value; end; function TTTSRPTRUNTable.GetPExpireDateTo:String; begin result := DFExpireDateTo.Value; end; procedure TTTSRPTRUNTable.SetPIncludeTI(const Value: Boolean); begin DFIncludeTI.Value := Value; end; function TTTSRPTRUNTable.GetPIncludeTI:Boolean; begin result := DFIncludeTI.Value; end; procedure TTTSRPTRUNTable.SetPNoticeItems(const Value: Boolean); begin DFNoticeItems.Value := Value; end; function TTTSRPTRUNTable.GetPNoticeItems:Boolean; begin result := DFNoticeItems.Value; end; procedure TTTSRPTRUNTable.SetPNoticeItemFrom(const Value: String); begin DFNoticeItemFrom.Value := Value; end; function TTTSRPTRUNTable.GetPNoticeItemFrom:String; begin result := DFNoticeItemFrom.Value; end; procedure TTTSRPTRUNTable.SetPNoticeItemTo(const Value: String); begin DFNoticeItemTo.Value := Value; end; function TTTSRPTRUNTable.GetPNoticeItemTo:String; begin result := DFNoticeItemTo.Value; end; procedure TTTSRPTRUNTable.SetPLoanNotes(const Value: Boolean); begin DFLoanNotes.Value := Value; end; function TTTSRPTRUNTable.GetPLoanNotes:Boolean; begin result := DFLoanNotes.Value; end; procedure TTTSRPTRUNTable.SetPTINotes(const Value: Boolean); begin DFTINotes.Value := Value; end; function TTTSRPTRUNTable.GetPTINotes:Boolean; begin result := DFTINotes.Value; end; procedure TTTSRPTRUNTable.SetPCoMaker(const Value: Boolean); begin DFCoMaker.Value := Value; end; function TTTSRPTRUNTable.GetPCoMaker:Boolean; begin result := DFCoMaker.Value; end; procedure TTTSRPTRUNTable.SetPGuarantor(const Value: Boolean); begin DFGuarantor.Value := Value; end; function TTTSRPTRUNTable.GetPGuarantor:Boolean; begin result := DFGuarantor.Value; end; procedure TTTSRPTRUNTable.SetPGroupBy(const Value: Integer); begin DFGroupBy.Value := Value; end; function TTTSRPTRUNTable.GetPGroupBy:Integer; begin result := DFGroupBy.Value; end; procedure TTTSRPTRUNTable.SetPItemCollDesc(const Value: Boolean); begin DFItemCollDesc.Value := Value; end; function TTTSRPTRUNTable.GetPItemCollDesc:Boolean; begin result := DFItemCollDesc.Value; end; procedure TTTSRPTRUNTable.SetPItemOfficer(const Value: Boolean); begin DFItemOfficer.Value := Value; end; function TTTSRPTRUNTable.GetPItemOfficer:Boolean; begin result := DFItemOfficer.Value; end; procedure TTTSRPTRUNTable.SetPItemBalance(const Value: Boolean); begin DFItemBalance.Value := Value; end; function TTTSRPTRUNTable.GetPItemBalance:Boolean; begin result := DFItemBalance.Value; end; procedure TTTSRPTRUNTable.SetPItemBranch(const Value: Boolean); begin DFItemBranch.Value := Value; end; function TTTSRPTRUNTable.GetPItemBranch:Boolean; begin result := DFItemBranch.Value; end; procedure TTTSRPTRUNTable.SetPItemDivision(const Value: Boolean); begin DFItemDivision.Value := Value; end; function TTTSRPTRUNTable.GetPItemDivision:Boolean; begin result := DFItemDivision.Value; end; procedure TTTSRPTRUNTable.SetPItemOpenDate(const Value: Boolean); begin DFItemOpenDate.Value := Value; end; function TTTSRPTRUNTable.GetPItemOpenDate:Boolean; begin result := DFItemOpenDate.Value; end; procedure TTTSRPTRUNTable.SetPItemMatDate(const Value: Boolean); begin DFItemMatDate.Value := Value; end; function TTTSRPTRUNTable.GetPItemMatDate:Boolean; begin result := DFItemMatDate.Value; end; procedure TTTSRPTRUNTable.SetPItemAddress(const Value: Boolean); begin DFItemAddress.Value := Value; end; function TTTSRPTRUNTable.GetPItemAddress:Boolean; begin result := DFItemAddress.Value; end; procedure TTTSRPTRUNTable.SetPItemCategory(const Value: Boolean); begin DFItemCategory.Value := Value; end; function TTTSRPTRUNTable.GetPItemCategory:Boolean; begin result := DFItemCategory.Value; end; procedure TTTSRPTRUNTable.SetPItemPhone(const Value: Boolean); begin DFItemPhone.Value := Value; end; function TTTSRPTRUNTable.GetPItemPhone:Boolean; begin result := DFItemPhone.Value; end; procedure TTTSRPTRUNTable.SetPItemStatus(const Value: Boolean); begin DFItemStatus.Value := Value; end; function TTTSRPTRUNTable.GetPItemStatus:Boolean; begin result := DFItemStatus.Value; end; procedure TTTSRPTRUNTable.SetPItemDescription(const Value: Boolean); begin DFItemDescription.Value := Value; end; function TTTSRPTRUNTable.GetPItemDescription:Boolean; begin result := DFItemDescription.Value; end; procedure TTTSRPTRUNTable.SetPLeadTimeOfficer(const Value: Boolean); begin DFLeadTimeOfficer.Value := Value; end; function TTTSRPTRUNTable.GetPLeadTimeOfficer:Boolean; begin result := DFLeadTimeOfficer.Value; end; procedure TTTSRPTRUNTable.SetPLeadTimeNotice(const Value: Boolean); begin DFLeadTimeNotice.Value := Value; end; function TTTSRPTRUNTable.GetPLeadTimeNotice:Boolean; begin result := DFLeadTimeNotice.Value; end; procedure TTTSRPTRUNTable.SetPLeadTimeYouPick(const Value: Boolean); begin DFLeadTimeYouPick.Value := Value; end; function TTTSRPTRUNTable.GetPLeadTimeYouPick:Boolean; begin result := DFLeadTimeYouPick.Value; end; procedure TTTSRPTRUNTable.SetPLeadTime(const Value: Integer); begin DFLeadTime.Value := Value; end; function TTTSRPTRUNTable.GetPLeadTime:Integer; begin result := DFLeadTime.Value; end; procedure TTTSRPTRUNTable.SetPIncLoans(const Value: Boolean); begin DFIncLoans.Value := Value; end; function TTTSRPTRUNTable.GetPIncLoans:Boolean; begin result := DFIncLoans.Value; end; procedure TTTSRPTRUNTable.SetPIncActiveCifs(const Value: Boolean); begin DFIncActiveCifs.Value := Value; end; function TTTSRPTRUNTable.GetPIncActiveCifs:Boolean; begin result := DFIncActiveCifs.Value; end; procedure TTTSRPTRUNTable.SetPIncInactiveCifs(const Value: Boolean); begin DFIncInactiveCifs.Value := Value; end; function TTTSRPTRUNTable.GetPIncInactiveCifs:Boolean; begin result := DFIncInactiveCifs.Value; end; procedure TTTSRPTRUNTable.SetPIncNotPaidOut(const Value: Boolean); begin DFIncNotPaidOut.Value := Value; end; function TTTSRPTRUNTable.GetPIncNotPaidOut:Boolean; begin result := DFIncNotPaidOut.Value; end; procedure TTTSRPTRUNTable.SetPIncPaidOut(const Value: Boolean); begin DFIncPaidOut.Value := Value; end; function TTTSRPTRUNTable.GetPIncPaidOut:Boolean; begin result := DFIncPaidOut.Value; end; procedure TTTSRPTRUNTable.SetPIncLoanWithNotes(const Value: Boolean); begin DFIncLoanWithNotes.Value := Value; end; function TTTSRPTRUNTable.GetPIncLoanWithNotes:Boolean; begin result := DFIncLoanWithNotes.Value; end; procedure TTTSRPTRUNTable.SetPIncLoanWONotes(const Value: Boolean); begin DFIncLoanWONotes.Value := Value; end; function TTTSRPTRUNTable.GetPIncLoanWONotes:Boolean; begin result := DFIncLoanWONotes.Value; end; procedure TTTSRPTRUNTable.SetPIncWithTracked(const Value: Boolean); begin DFIncWithTracked.Value := Value; end; function TTTSRPTRUNTable.GetPIncWithTracked:Boolean; begin result := DFIncWithTracked.Value; end; procedure TTTSRPTRUNTable.SetPIncWOTracked(const Value: Boolean); begin DFIncWOTracked.Value := Value; end; function TTTSRPTRUNTable.GetPIncWOTracked:Boolean; begin result := DFIncWOTracked.Value; end; procedure TTTSRPTRUNTable.SetPIncWithNoticeItems(const Value: Boolean); begin DFIncWithNoticeItems.Value := Value; end; function TTTSRPTRUNTable.GetPIncWithNoticeItems:Boolean; begin result := DFIncWithNoticeItems.Value; end; procedure TTTSRPTRUNTable.SetPIncWONoticeItems(const Value: Boolean); begin DFIncWONoticeItems.Value := Value; end; function TTTSRPTRUNTable.GetPIncWONoticeItems:Boolean; begin result := DFIncWONoticeItems.Value; end; procedure TTTSRPTRUNTable.SetPIncLoanNotes(const Value: Boolean); begin DFIncLoanNotes.Value := Value; end; function TTTSRPTRUNTable.GetPIncLoanNotes:Boolean; begin result := DFIncLoanNotes.Value; end; procedure TTTSRPTRUNTable.SetPIncCifs(const Value: Boolean); begin DFIncCifs.Value := Value; end; function TTTSRPTRUNTable.GetPIncCifs:Boolean; begin result := DFIncCifs.Value; end; procedure TTTSRPTRUNTable.SetPELRecapOnly(const Value: Boolean); begin DFELRecapOnly.Value := Value; end; function TTTSRPTRUNTable.GetPELRecapOnly:Boolean; begin result := DFELRecapOnly.Value; end; procedure TTTSRPTRUNTable.SetPExpLoanCif(const Value: Boolean); begin DFExpLoanCif.Value := Value; end; function TTTSRPTRUNTable.GetPExpLoanCif:Boolean; begin result := DFExpLoanCif.Value; end; procedure TTTSRPTRUNTable.SetPExpLoanCifNotes(const Value: Boolean); begin DFExpLoanCifNotes.Value := Value; end; function TTTSRPTRUNTable.GetPExpLoanCifNotes:Boolean; begin result := DFExpLoanCifNotes.Value; end; procedure TTTSRPTRUNTable.SetPExpTracked(const Value: Boolean); begin DFExpTracked.Value := Value; end; function TTTSRPTRUNTable.GetPExpTracked:Boolean; begin result := DFExpTracked.Value; end; procedure TTTSRPTRUNTable.SetPExpTrackedNotes(const Value: Boolean); begin DFExpTrackedNotes.Value := Value; end; function TTTSRPTRUNTable.GetPExpTrackedNotes:Boolean; begin result := DFExpTrackedNotes.Value; end; procedure TTTSRPTRUNTable.SetPExpTrackedExtend(const Value: Boolean); begin DFExpTrackedExtend.Value := Value; end; function TTTSRPTRUNTable.GetPExpTrackedExtend:Boolean; begin result := DFExpTrackedExtend.Value; end; procedure TTTSRPTRUNTable.SetPExpFormat(const Value: Integer); begin DFExpFormat.Value := Value; end; function TTTSRPTRUNTable.GetPExpFormat:Integer; begin result := DFExpFormat.Value; end; procedure TTTSRPTRUNTable.SetPExpOpt1(const Value: Boolean); begin DFExpOpt1.Value := Value; end; function TTTSRPTRUNTable.GetPExpOpt1:Boolean; begin result := DFExpOpt1.Value; end; procedure TTTSRPTRUNTable.SetPExpOpt2(const Value: Boolean); begin DFExpOpt2.Value := Value; end; function TTTSRPTRUNTable.GetPExpOpt2:Boolean; begin result := DFExpOpt2.Value; end; procedure TTTSRPTRUNTable.SetPExpOpt3(const Value: Boolean); begin DFExpOpt3.Value := Value; end; function TTTSRPTRUNTable.GetPExpOpt3:Boolean; begin result := DFExpOpt3.Value; end; procedure TTTSRPTRUNTable.SetPItemEntryFrom(const Value: String); begin DFItemEntryFrom.Value := Value; end; function TTTSRPTRUNTable.GetPItemEntryFrom:String; begin result := DFItemEntryFrom.Value; end; procedure TTTSRPTRUNTable.SetPItemEntryTo(const Value: String); begin DFItemEntryTo.Value := Value; end; function TTTSRPTRUNTable.GetPItemEntryTo:String; begin result := DFItemEntryTo.Value; end; procedure TTTSRPTRUNTable.SetPItemEntryBy(const Value: String); begin DFItemEntryBy.Value := Value; end; function TTTSRPTRUNTable.GetPItemEntryBy:String; begin result := DFItemEntryBy.Value; end; procedure TTTSRPTRUNTable.SetPShowTIUser(const Value: Boolean); begin DFShowTIUser.Value := Value; end; function TTTSRPTRUNTable.GetPShowTIUser:Boolean; begin result := DFShowTIUser.Value; end; procedure TTTSRPTRUNTable.SetPShowTIEntryDate(const Value: Boolean); begin DFShowTIEntryDate.Value := Value; end; function TTTSRPTRUNTable.GetPShowTIEntryDate:Boolean; begin result := DFShowTIEntryDate.Value; end; procedure TTTSRPTRUNTable.SetPExcludeCats(const Value: Boolean); begin DFExcludeCats.Value := Value; end; function TTTSRPTRUNTable.GetPExcludeCats:Boolean; begin result := DFExcludeCats.Value; end; procedure TTTSRPTRUNTable.SetPDescriptHow(const Value: Integer); begin DFDescriptHow.Value := Value; end; function TTTSRPTRUNTable.GetPDescriptHow:Integer; begin result := DFDescriptHow.Value; end; procedure TTTSRPTRUNTable.SetPDescriptWhat(const Value: String); begin DFDescriptWhat.Value := Value; end; function TTTSRPTRUNTable.GetPDescriptWhat:String; begin result := DFDescriptWhat.Value; end; procedure TTTSRPTRUNTable.SetPReferenceHow(const Value: Integer); begin DFReferenceHow.Value := Value; end; function TTTSRPTRUNTable.GetPReferenceHow:Integer; begin result := DFReferenceHow.Value; end; procedure TTTSRPTRUNTable.SetPReferenceWhat(const Value: String); begin DFReferenceWhat.Value := Value; end; function TTTSRPTRUNTable.GetPReferenceWhat:String; begin result := DFReferenceWhat.Value; end; procedure TTTSRPTRUNTable.SetPControlStatus(const Value: String); begin DFControlStatus.Value := Value; end; function TTTSRPTRUNTable.GetPControlStatus:String; begin result := DFControlStatus.Value; end; procedure TTTSRPTRUNTable.SetPControlMsg(const Value: String); begin DFControlMsg.Value := Value; end; function TTTSRPTRUNTable.GetPControlMsg:String; begin result := DFControlMsg.Value; end; function TTTSRPTRUNTable.GetPTestRun:Boolean; begin result := DFTestRun.Value; end; procedure TTTSRPTRUNTable.SetPTestRun(const Value: Boolean); begin DFTestRun.Value := Value; end; function TTTSRPTRUNTable.GetPRemoveAll:Boolean; begin result := DFRemoveAll.Value; end; procedure TTTSRPTRUNTable.SetPRemoveAll(const Value: Boolean); begin DFRemoveAll.Value := Value; end; function TTTSRPTRUNTable.GetPCIFNumber:String; begin result := DFCIFNumber.Value; end; procedure TTTSRPTRUNTable.SetPCIFNumber(const Value: String); begin DFCIFNumber.Value := Value; end; procedure TTTSRPTRUNTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AutoInc, AutoInc, 0, N'); Add('LenderNum, String, 8, N'); Add('Type, String, 6, N'); Add('Start, String, 20, N'); Add('Stop, String, 20, N'); Add('StopStatus, String, 10, N'); Add('UserID, String, 10, N'); Add('Description, String, 100, N'); Add('NoticeScanDate, String, 10, N'); Add('LetterDate, String, 10, N'); Add('NoticeType, String, 1, N'); Add('Reprint, Boolean, 0, N'); Add('Limit1, Boolean, 0, N'); Add('LimitNo1, Integer, 0, N'); Add('Limit2, Boolean, 0, N'); Add('LimitNo2, Integer, 0, N'); Add('Limit3, Boolean, 0, N'); Add('LimitNo3, Integer, 0, N'); Add('Limit4, Boolean, 0, N'); Add('LimitNo4, Integer, 0, N'); Add('Limit5, Boolean, 0, N'); Add('LimitNo5, Integer, 0, N'); Add('SortOrder, String, 10, N'); Add('LoanCif, Integer, 0, N'); Add('Cifs, Integer, 0, N'); Add('BalanceFrom, Currency, 0, N'); Add('BalanceTo, Currency, 0, N'); Add('SeperateNotice, Integer, 0, N'); Add('Paidouts, Boolean, 0, N'); Add('MatureFrom, String, 10, N'); Add('MatureTo, String, 10, N'); Add('OpenFrom, String, 10, N'); Add('OpenTo, String, 10, N'); Add('Cats, Memo, 0, N'); Add('CollCodes, Memo, 0, N'); Add('Officers, Memo, 0, N'); Add('Branchs, Memo, 0, N'); Add('Divisions, Memo, 0, N'); Add('ReportTitle, String, 40, N'); Add('PaidDatesFrom, String, 10, N'); Add('PaidDatesTo, String, 10, N'); Add('SelectTIDate, Boolean, 0, N'); Add('SelectTICont, Boolean, 0, N'); Add('SelectTIWaived, Boolean, 0, N'); Add('SelectTIHistory, Boolean, 0, N'); Add('SelectTISatisfied, Boolean, 0, N'); Add('SelectTINA, Boolean, 0, N'); Add('ExpireDateFrom, String, 10, N'); Add('ExpireDateTo, String, 10, N'); Add('IncludeTI, Boolean, 0, N'); Add('NoticeItems, Boolean, 0, N'); Add('NoticeItemFrom, String, 10, N'); Add('NoticeItemTo, String, 10, N'); Add('LoanNotes, Boolean, 0, N'); Add('TINotes, Boolean, 0, N'); Add('CoMaker, Boolean, 0, N'); Add('Guarantor, Boolean, 0, N'); Add('GroupBy, Integer, 0, N'); Add('ItemCollDesc, Boolean, 0, N'); Add('ItemOfficer, Boolean, 0, N'); Add('ItemBalance, Boolean, 0, N'); Add('ItemBranch, Boolean, 0, N'); Add('ItemDivision, Boolean, 0, N'); Add('ItemOpenDate, Boolean, 0, N'); Add('ItemMatDate, Boolean, 0, N'); Add('ItemAddress, Boolean, 0, N'); Add('ItemCategory, Boolean, 0, N'); Add('ItemPhone, Boolean, 0, N'); Add('ItemStatus, Boolean, 0, N'); Add('ItemDescription, Boolean, 0, N'); Add('LeadTimeOfficer, Boolean, 0, N'); Add('LeadTimeNotice, Boolean, 0, N'); Add('LeadTimeYouPick, Boolean, 0, N'); Add('LeadTime, Integer, 0, N'); Add('IncLoans, Boolean, 0, N'); Add('IncActiveCifs, Boolean, 0, N'); Add('IncInactiveCifs, Boolean, 0, N'); Add('IncNotPaidOut, Boolean, 0, N'); Add('IncPaidOut, Boolean, 0, N'); Add('IncLoanWithNotes, Boolean, 0, N'); Add('IncLoanWONotes, Boolean, 0, N'); Add('IncWithTracked, Boolean, 0, N'); Add('IncWOTracked, Boolean, 0, N'); Add('IncWithNoticeItems, Boolean, 0, N'); Add('IncWONoticeItems, Boolean, 0, N'); Add('IncLoanNotes, Boolean, 0, N'); Add('IncCifs, Boolean, 0, N'); Add('ELRecapOnly, Boolean, 0, N'); Add('ExpLoanCif, Boolean, 0, N'); Add('ExpLoanCifNotes, Boolean, 0, N'); Add('ExpTracked, Boolean, 0, N'); Add('ExpTrackedNotes, Boolean, 0, N'); Add('ExpTrackedExtend, Boolean, 0, N'); Add('ExpFormat, Integer, 0, N'); Add('ExpOpt1, Boolean, 0, N'); Add('ExpOpt2, Boolean, 0, N'); Add('ExpOpt3, Boolean, 0, N'); Add('ItemEntryFrom, String, 10, N'); Add('ItemEntryTo, String, 10, N'); Add('ItemEntryBy, String, 100, N'); Add('ShowTIUser, Boolean, 0, N'); Add('ShowTIEntryDate, Boolean, 0, N'); Add('ExcludeCats, Boolean, 0, N'); Add('DescriptHow, Integer, 0, N'); Add('DescriptWhat, String, 15, N'); Add('ReferenceHow, Integer, 0, N'); Add('ReferenceWhat, String, 15, N'); Add('ControlStatus, String, 10, N'); Add('ControlMsg, String, 30, N'); Add('TestRun, Boolean, 0, N'); Add('RemoveAll, Boolean, 0, N'); Add('CIFNumber, String, 20, N'); end; end; procedure TTTSRPTRUNTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AutoInc, Y, Y, N, N'); Add('ByLenderType, LenderNum;Type;AutoInc, N, N, N, Y'); end; end; procedure TTTSRPTRUNTable.SetEnumIndex(Value: TEITTSRPTRUN); begin case Value of TTSRPTRUNPrimaryKey : IndexName := ''; TTSRPTRUNByLenderType : IndexName := 'ByLenderType'; end; end; function TTTSRPTRUNTable.GetDataBuffer:TTTSRPTRUNRecord; var buf: TTTSRPTRUNRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAutoInc := DFAutoInc.Value; buf.PLenderNum := DFLenderNum.Value; buf.PType := DFType.Value; buf.PStart := DFStart.Value; buf.PStop := DFStop.Value; buf.PStopStatus := DFStopStatus.Value; buf.PUserID := DFUserID.Value; buf.PDescription := DFDescription.Value; buf.PNoticeScanDate := DFNoticeScanDate.Value; buf.PLetterDate := DFLetterDate.Value; buf.PNoticeType := DFNoticeType.Value; buf.PReprint := DFReprint.Value; buf.PLimit1 := DFLimit1.Value; buf.PLimitNo1 := DFLimitNo1.Value; buf.PLimit2 := DFLimit2.Value; buf.PLimitNo2 := DFLimitNo2.Value; buf.PLimit3 := DFLimit3.Value; buf.PLimitNo3 := DFLimitNo3.Value; buf.PLimit4 := DFLimit4.Value; buf.PLimitNo4 := DFLimitNo4.Value; buf.PLimit5 := DFLimit5.Value; buf.PLimitNo5 := DFLimitNo5.Value; buf.PSortOrder := DFSortOrder.Value; buf.PLoanCif := DFLoanCif.Value; buf.PCifs := DFCifs.Value; buf.PBalanceFrom := DFBalanceFrom.Value; buf.PBalanceTo := DFBalanceTo.Value; buf.PSeperateNotice := DFSeperateNotice.Value; buf.PPaidouts := DFPaidouts.Value; buf.PMatureFrom := DFMatureFrom.Value; buf.PMatureTo := DFMatureTo.Value; buf.POpenFrom := DFOpenFrom.Value; buf.POpenTo := DFOpenTo.Value; buf.PReportTitle := DFReportTitle.Value; buf.PPaidDatesFrom := DFPaidDatesFrom.Value; buf.PPaidDatesTo := DFPaidDatesTo.Value; buf.PSelectTIDate := DFSelectTIDate.Value; buf.PSelectTICont := DFSelectTICont.Value; buf.PSelectTIWaived := DFSelectTIWaived.Value; buf.PSelectTIHistory := DFSelectTIHistory.Value; buf.PSelectTISatisfied := DFSelectTISatisfied.Value; buf.PSelectTINA := DFSelectTINA.Value; buf.PExpireDateFrom := DFExpireDateFrom.Value; buf.PExpireDateTo := DFExpireDateTo.Value; buf.PIncludeTI := DFIncludeTI.Value; buf.PNoticeItems := DFNoticeItems.Value; buf.PNoticeItemFrom := DFNoticeItemFrom.Value; buf.PNoticeItemTo := DFNoticeItemTo.Value; buf.PLoanNotes := DFLoanNotes.Value; buf.PTINotes := DFTINotes.Value; buf.PCoMaker := DFCoMaker.Value; buf.PGuarantor := DFGuarantor.Value; buf.PGroupBy := DFGroupBy.Value; buf.PItemCollDesc := DFItemCollDesc.Value; buf.PItemOfficer := DFItemOfficer.Value; buf.PItemBalance := DFItemBalance.Value; buf.PItemBranch := DFItemBranch.Value; buf.PItemDivision := DFItemDivision.Value; buf.PItemOpenDate := DFItemOpenDate.Value; buf.PItemMatDate := DFItemMatDate.Value; buf.PItemAddress := DFItemAddress.Value; buf.PItemCategory := DFItemCategory.Value; buf.PItemPhone := DFItemPhone.Value; buf.PItemStatus := DFItemStatus.Value; buf.PItemDescription := DFItemDescription.Value; buf.PLeadTimeOfficer := DFLeadTimeOfficer.Value; buf.PLeadTimeNotice := DFLeadTimeNotice.Value; buf.PLeadTimeYouPick := DFLeadTimeYouPick.Value; buf.PLeadTime := DFLeadTime.Value; buf.PIncLoans := DFIncLoans.Value; buf.PIncActiveCifs := DFIncActiveCifs.Value; buf.PIncInactiveCifs := DFIncInactiveCifs.Value; buf.PIncNotPaidOut := DFIncNotPaidOut.Value; buf.PIncPaidOut := DFIncPaidOut.Value; buf.PIncLoanWithNotes := DFIncLoanWithNotes.Value; buf.PIncLoanWONotes := DFIncLoanWONotes.Value; buf.PIncWithTracked := DFIncWithTracked.Value; buf.PIncWOTracked := DFIncWOTracked.Value; buf.PIncWithNoticeItems := DFIncWithNoticeItems.Value; buf.PIncWONoticeItems := DFIncWONoticeItems.Value; buf.PIncLoanNotes := DFIncLoanNotes.Value; buf.PIncCifs := DFIncCifs.Value; buf.PELRecapOnly := DFELRecapOnly.Value; buf.PExpLoanCif := DFExpLoanCif.Value; buf.PExpLoanCifNotes := DFExpLoanCifNotes.Value; buf.PExpTracked := DFExpTracked.Value; buf.PExpTrackedNotes := DFExpTrackedNotes.Value; buf.PExpTrackedExtend := DFExpTrackedExtend.Value; buf.PExpFormat := DFExpFormat.Value; buf.PExpOpt1 := DFExpOpt1.Value; buf.PExpOpt2 := DFExpOpt2.Value; buf.PExpOpt3 := DFExpOpt3.Value; buf.PItemEntryFrom := DFItemEntryFrom.Value; buf.PItemEntryTo := DFItemEntryTo.Value; buf.PItemEntryBy := DFItemEntryBy.Value; buf.PShowTIUser := DFShowTIUser.Value; buf.PShowTIEntryDate := DFShowTIEntryDate.Value; buf.PExcludeCats := DFExcludeCats.Value; buf.PDescriptHow := DFDescriptHow.Value; buf.PDescriptWhat := DFDescriptWhat.Value; buf.PReferenceHow := DFReferenceHow.Value; buf.PReferenceWhat := DFReferenceWhat.Value; buf.PControlStatus := DFControlStatus.Value; buf.PControlMsg := DFControlMsg.Value; buf.PTestRun := DFTestRun.Value; buf.PRemoveAll := DFRemoveAll.Value; buf.PCifNumber := DFCIFNumber.Value; result := buf; end; procedure TTTSRPTRUNTable.StoreDataBuffer(ABuffer:TTTSRPTRUNRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFType.Value := ABuffer.PType; DFStart.Value := ABuffer.PStart; DFStop.Value := ABuffer.PStop; DFStopStatus.Value := ABuffer.PStopStatus; DFUserID.Value := ABuffer.PUserID; DFDescription.Value := ABuffer.PDescription; DFNoticeScanDate.Value := ABuffer.PNoticeScanDate; DFLetterDate.Value := ABuffer.PLetterDate; DFNoticeType.Value := ABuffer.PNoticeType; DFReprint.Value := ABuffer.PReprint; DFLimit1.Value := ABuffer.PLimit1; DFLimitNo1.Value := ABuffer.PLimitNo1; DFLimit2.Value := ABuffer.PLimit2; DFLimitNo2.Value := ABuffer.PLimitNo2; DFLimit3.Value := ABuffer.PLimit3; DFLimitNo3.Value := ABuffer.PLimitNo3; DFLimit4.Value := ABuffer.PLimit4; DFLimitNo4.Value := ABuffer.PLimitNo4; DFLimit5.Value := ABuffer.PLimit5; DFLimitNo5.Value := ABuffer.PLimitNo5; DFSortOrder.Value := ABuffer.PSortOrder; DFLoanCif.Value := ABuffer.PLoanCif; DFCifs.Value := ABuffer.PCifs; DFBalanceFrom.Value := ABuffer.PBalanceFrom; DFBalanceTo.Value := ABuffer.PBalanceTo; DFSeperateNotice.Value := ABuffer.PSeperateNotice; DFPaidouts.Value := ABuffer.PPaidouts; DFMatureFrom.Value := ABuffer.PMatureFrom; DFMatureTo.Value := ABuffer.PMatureTo; DFOpenFrom.Value := ABuffer.POpenFrom; DFOpenTo.Value := ABuffer.POpenTo; DFReportTitle.Value := ABuffer.PReportTitle; DFPaidDatesFrom.Value := ABuffer.PPaidDatesFrom; DFPaidDatesTo.Value := ABuffer.PPaidDatesTo; DFSelectTIDate.Value := ABuffer.PSelectTIDate; DFSelectTICont.Value := ABuffer.PSelectTICont; DFSelectTIWaived.Value := ABuffer.PSelectTIWaived; DFSelectTIHistory.Value := ABuffer.PSelectTIHistory; DFSelectTISatisfied.Value := ABuffer.PSelectTISatisfied; DFSelectTINA.Value := ABuffer.PSelectTINA; DFExpireDateFrom.Value := ABuffer.PExpireDateFrom; DFExpireDateTo.Value := ABuffer.PExpireDateTo; DFIncludeTI.Value := ABuffer.PIncludeTI; DFNoticeItems.Value := ABuffer.PNoticeItems; DFNoticeItemFrom.Value := ABuffer.PNoticeItemFrom; DFNoticeItemTo.Value := ABuffer.PNoticeItemTo; DFLoanNotes.Value := ABuffer.PLoanNotes; DFTINotes.Value := ABuffer.PTINotes; DFCoMaker.Value := ABuffer.PCoMaker; DFGuarantor.Value := ABuffer.PGuarantor; DFGroupBy.Value := ABuffer.PGroupBy; DFItemCollDesc.Value := ABuffer.PItemCollDesc; DFItemOfficer.Value := ABuffer.PItemOfficer; DFItemBalance.Value := ABuffer.PItemBalance; DFItemBranch.Value := ABuffer.PItemBranch; DFItemDivision.Value := ABuffer.PItemDivision; DFItemOpenDate.Value := ABuffer.PItemOpenDate; DFItemMatDate.Value := ABuffer.PItemMatDate; DFItemAddress.Value := ABuffer.PItemAddress; DFItemCategory.Value := ABuffer.PItemCategory; DFItemPhone.Value := ABuffer.PItemPhone; DFItemStatus.Value := ABuffer.PItemStatus; DFItemDescription.Value := ABuffer.PItemDescription; DFLeadTimeOfficer.Value := ABuffer.PLeadTimeOfficer; DFLeadTimeNotice.Value := ABuffer.PLeadTimeNotice; DFLeadTimeYouPick.Value := ABuffer.PLeadTimeYouPick; DFLeadTime.Value := ABuffer.PLeadTime; DFIncLoans.Value := ABuffer.PIncLoans; DFIncActiveCifs.Value := ABuffer.PIncActiveCifs; DFIncInactiveCifs.Value := ABuffer.PIncInactiveCifs; DFIncNotPaidOut.Value := ABuffer.PIncNotPaidOut; DFIncPaidOut.Value := ABuffer.PIncPaidOut; DFIncLoanWithNotes.Value := ABuffer.PIncLoanWithNotes; DFIncLoanWONotes.Value := ABuffer.PIncLoanWONotes; DFIncWithTracked.Value := ABuffer.PIncWithTracked; DFIncWOTracked.Value := ABuffer.PIncWOTracked; DFIncWithNoticeItems.Value := ABuffer.PIncWithNoticeItems; DFIncWONoticeItems.Value := ABuffer.PIncWONoticeItems; DFIncLoanNotes.Value := ABuffer.PIncLoanNotes; DFIncCifs.Value := ABuffer.PIncCifs; DFELRecapOnly.Value := ABuffer.PELRecapOnly; DFExpLoanCif.Value := ABuffer.PExpLoanCif; DFExpLoanCifNotes.Value := ABuffer.PExpLoanCifNotes; DFExpTracked.Value := ABuffer.PExpTracked; DFExpTrackedNotes.Value := ABuffer.PExpTrackedNotes; DFExpTrackedExtend.Value := ABuffer.PExpTrackedExtend; DFExpFormat.Value := ABuffer.PExpFormat; DFExpOpt1.Value := ABuffer.PExpOpt1; DFExpOpt2.Value := ABuffer.PExpOpt2; DFExpOpt3.Value := ABuffer.PExpOpt3; DFItemEntryFrom.Value := ABuffer.PItemEntryFrom; DFItemEntryTo.Value := ABuffer.PItemEntryTo; DFItemEntryBy.Value := ABuffer.PItemEntryBy; DFShowTIUser.Value := ABuffer.PShowTIUser; DFShowTIEntryDate.Value := ABuffer.PShowTIEntryDate; DFExcludeCats.Value := ABuffer.PExcludeCats; DFDescriptHow.Value := ABuffer.PDescriptHow; DFDescriptWhat.Value := ABuffer.PDescriptWhat; DFReferenceHow.Value := ABuffer.PReferenceHow; DFReferenceWhat.Value := ABuffer.PReferenceWhat; DFControlStatus.Value := ABuffer.PControlStatus; DFControlMsg.Value := ABuffer.PControlMsg; DFTestRun.Value := ABuffer.PTestRun ; DFRemoveAll.Value := ABuffer.PRemoveAll ; DFCIFNumber.Value := ABuffer.PCifNumber; end; function TTTSRPTRUNTable.GetEnumIndex: TEITTSRPTRUN; var iname : string; begin result := TTSRPTRUNPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSRPTRUNPrimaryKey; if iname = 'BYLENDERTYPE' then result := TTSRPTRUNByLenderType; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSRPTRUNTable, TTTSRPTRUNBuffer ] ); end; { Register } function TTTSRPTRUNBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..107] of string = ('AUTOINC','LENDERNUM','TYPE','START','STOP','STOPSTATUS' ,'USERID','DESCRIPTION','NOTICESCANDATE','LETTERDATE','NOTICETYPE' ,'REPRINT','LIMIT1','LIMITNO1','LIMIT2','LIMITNO2' ,'LIMIT3','LIMITNO3','LIMIT4','LIMITNO4','LIMIT5' ,'LIMITNO5','SORTORDER','LOANCIF','CIFS','BALANCEFROM' ,'BALANCETO','SEPERATENOTICE','PAIDOUTS','MATUREFROM','MATURETO' ,'OPENFROM','OPENTO','REPORTTITLE','PAIDDATESFROM','PAIDDATESTO' ,'SELECTTIDATE','SELECTTICONT','SELECTTIWAIVED','SELECTTIHISTORY','SELECTTISATISFIED' ,'SELECTTINA','EXPIREDATEFROM','EXPIREDATETO','INCLUDETI','NOTICEITEMS' ,'NOTICEITEMFROM','NOTICEITEMTO','LOANNOTES','TINOTES','COMAKER' ,'GUARANTOR','GROUPBY','ITEMCOLLDESC','ITEMOFFICER','ITEMBALANCE' ,'ITEMBRANCH','ITEMDIVISION','ITEMOPENDATE','ITEMMATDATE','ITEMADDRESS' ,'ITEMCATEGORY','ITEMPHONE','ITEMSTATUS','ITEMDESCRIPTION','LEADTIMEOFFICER' ,'LEADTIMENOTICE','LEADTIMEYOUPICK','LEADTIME','INCLOANS','INCACTIVECIFS' ,'INCINACTIVECIFS','INCNOTPAIDOUT','INCPAIDOUT','INCLOANWITHNOTES','INCLOANWONOTES' ,'INCWITHTRACKED','INCWOTRACKED','INCWITHNOTICEITEMS','INCWONOTICEITEMS','INCLOANNOTES' ,'INCCIFS','ELRECAPONLY','EXPLOANCIF','EXPLOANCIFNOTES','EXPTRACKED' ,'EXPTRACKEDNOTES','EXPTRACKEDEXTEND','EXPFORMAT','EXPOPT1','EXPOPT2' ,'EXPOPT3','ITEMENTRYFROM','ITEMENTRYTO','ITEMENTRYBY','SHOWTIUSER' ,'SHOWTIENTRYDATE','EXCLUDECATS','DESCRIPTHOW','DESCRIPTWHAT','REFERENCEHOW' ,'REFERENCEWHAT','CONTROLSTATUS','CONTROLMSG','TESTRUN','REMOVEALL','CIFNUMBER' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 107) and (flist[x] <> s) do inc(x); if x <= 107 then result := x else result := 0; end; function TTTSRPTRUNBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftAutoInc; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftBoolean; 13 : result := ftBoolean; 14 : result := ftInteger; 15 : result := ftBoolean; 16 : result := ftInteger; 17 : result := ftBoolean; 18 : result := ftInteger; 19 : result := ftBoolean; 20 : result := ftInteger; 21 : result := ftBoolean; 22 : result := ftInteger; 23 : result := ftString; 24 : result := ftInteger; 25 : result := ftInteger; 26 : result := ftCurrency; 27 : result := ftCurrency; 28 : result := ftInteger; 29 : result := ftBoolean; 30 : result := ftString; 31 : result := ftString; 32 : result := ftString; 33 : result := ftString; 34 : result := ftString; 35 : result := ftString; 36 : result := ftString; 37 : result := ftBoolean; 38 : result := ftBoolean; 39 : result := ftBoolean; 40 : result := ftBoolean; 41 : result := ftBoolean; 42 : result := ftBoolean; 43 : result := ftString; 44 : result := ftString; 45 : result := ftBoolean; 46 : result := ftBoolean; 47 : result := ftString; 48 : result := ftString; 49 : result := ftBoolean; 50 : result := ftBoolean; 51 : result := ftBoolean; 52 : result := ftBoolean; 53 : result := ftInteger; 54 : result := ftBoolean; 55 : result := ftBoolean; 56 : result := ftBoolean; 57 : result := ftBoolean; 58 : result := ftBoolean; 59 : result := ftBoolean; 60 : result := ftBoolean; 61 : result := ftBoolean; 62 : result := ftBoolean; 63 : result := ftBoolean; 64 : result := ftBoolean; 65 : result := ftBoolean; 66 : result := ftBoolean; 67 : result := ftBoolean; 68 : result := ftBoolean; 69 : result := ftInteger; 70 : result := ftBoolean; 71 : result := ftBoolean; 72 : result := ftBoolean; 73 : result := ftBoolean; 74 : result := ftBoolean; 75 : result := ftBoolean; 76 : result := ftBoolean; 77 : result := ftBoolean; 78 : result := ftBoolean; 79 : result := ftBoolean; 80 : result := ftBoolean; 81 : result := ftBoolean; 82 : result := ftBoolean; 83 : result := ftBoolean; 84 : result := ftBoolean; 85 : result := ftBoolean; 86 : result := ftBoolean; 87 : result := ftBoolean; 88 : result := ftBoolean; 89 : result := ftInteger; 90 : result := ftBoolean; 91 : result := ftBoolean; 92 : result := ftBoolean; 93 : result := ftString; 94 : result := ftString; 95 : result := ftString; 96 : result := ftBoolean; 97 : result := ftBoolean; 98 : result := ftBoolean; 99 : result := ftInteger; 100 : result := ftString; 101 : result := ftInteger; 102 : result := ftString; 103 : result := ftString; 104 : result := ftString; 105 : result := ftBoolean; 106 : result := ftBoolean; 107 : result := ftString; end; end; function TTTSRPTRUNBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAutoInc; 2 : result := @Data.PLenderNum; 3 : result := @Data.PType; 4 : result := @Data.PStart; 5 : result := @Data.PStop; 6 : result := @Data.PStopStatus; 7 : result := @Data.PUserID; 8 : result := @Data.PDescription; 9 : result := @Data.PNoticeScanDate; 10 : result := @Data.PLetterDate; 11 : result := @Data.PNoticeType; 12 : result := @Data.PReprint; 13 : result := @Data.PLimit1; 14 : result := @Data.PLimitNo1; 15 : result := @Data.PLimit2; 16 : result := @Data.PLimitNo2; 17 : result := @Data.PLimit3; 18 : result := @Data.PLimitNo3; 19 : result := @Data.PLimit4; 20 : result := @Data.PLimitNo4; 21 : result := @Data.PLimit5; 22 : result := @Data.PLimitNo5; 23 : result := @Data.PSortOrder; 24 : result := @Data.PLoanCif; 25 : result := @Data.PCifs; 26 : result := @Data.PBalanceFrom; 27 : result := @Data.PBalanceTo; 28 : result := @Data.PSeperateNotice; 29 : result := @Data.PPaidouts; 30 : result := @Data.PMatureFrom; 31 : result := @Data.PMatureTo; 32 : result := @Data.POpenFrom; 33 : result := @Data.POpenTo; 34 : result := @Data.PReportTitle; 35 : result := @Data.PPaidDatesFrom; 36 : result := @Data.PPaidDatesTo; 37 : result := @Data.PSelectTIDate; 38 : result := @Data.PSelectTICont; 39 : result := @Data.PSelectTIWaived; 40 : result := @Data.PSelectTIHistory; 41 : result := @Data.PSelectTISatisfied; 42 : result := @Data.PSelectTINA; 43 : result := @Data.PExpireDateFrom; 44 : result := @Data.PExpireDateTo; 45 : result := @Data.PIncludeTI; 46 : result := @Data.PNoticeItems; 47 : result := @Data.PNoticeItemFrom; 48 : result := @Data.PNoticeItemTo; 49 : result := @Data.PLoanNotes; 50 : result := @Data.PTINotes; 51 : result := @Data.PCoMaker; 52 : result := @Data.PGuarantor; 53 : result := @Data.PGroupBy; 54 : result := @Data.PItemCollDesc; 55 : result := @Data.PItemOfficer; 56 : result := @Data.PItemBalance; 57 : result := @Data.PItemBranch; 58 : result := @Data.PItemDivision; 59 : result := @Data.PItemOpenDate; 60 : result := @Data.PItemMatDate; 61 : result := @Data.PItemAddress; 62 : result := @Data.PItemCategory; 63 : result := @Data.PItemPhone; 64 : result := @Data.PItemStatus; 65 : result := @Data.PItemDescription; 66 : result := @Data.PLeadTimeOfficer; 67 : result := @Data.PLeadTimeNotice; 68 : result := @Data.PLeadTimeYouPick; 69 : result := @Data.PLeadTime; 70 : result := @Data.PIncLoans; 71 : result := @Data.PIncActiveCifs; 72 : result := @Data.PIncInactiveCifs; 73 : result := @Data.PIncNotPaidOut; 74 : result := @Data.PIncPaidOut; 75 : result := @Data.PIncLoanWithNotes; 76 : result := @Data.PIncLoanWONotes; 77 : result := @Data.PIncWithTracked; 78 : result := @Data.PIncWOTracked; 79 : result := @Data.PIncWithNoticeItems; 80 : result := @Data.PIncWONoticeItems; 81 : result := @Data.PIncLoanNotes; 82 : result := @Data.PIncCifs; 83 : result := @Data.PELRecapOnly; 84 : result := @Data.PExpLoanCif; 85 : result := @Data.PExpLoanCifNotes; 86 : result := @Data.PExpTracked; 87 : result := @Data.PExpTrackedNotes; 88 : result := @Data.PExpTrackedExtend; 89 : result := @Data.PExpFormat; 90 : result := @Data.PExpOpt1; 91 : result := @Data.PExpOpt2; 92 : result := @Data.PExpOpt3; 93 : result := @Data.PItemEntryFrom; 94 : result := @Data.PItemEntryTo; 95 : result := @Data.PItemEntryBy; 96 : result := @Data.PShowTIUser; 97 : result := @Data.PShowTIEntryDate; 98 : result := @Data.PExcludeCats; 99 : result := @Data.PDescriptHow; 100 : result := @Data.PDescriptWhat; 101 : result := @Data.PReferenceHow; 102 : result := @Data.PReferenceWhat; 103 : result := @Data.PControlStatus; 104 : result := @Data.PControlMsg; 105 : result := @Data.PTestRun; 106 : result := @Data.PRemoveAll; 107 : result := @Data.PCIFNumber; end; end; end.
unit ChromeLikeTabSetStyles; interface uses GDIPAPI, GDIPOBJ, Types, ChromeLikeTabSetTypes; type TChromeLikeTabSetStyles = class public class function MakeBrush(aElement: TChromeLikeTabSetStyleElement; aState: TChromeLikeTabSetElementState): TGPBrush; class function MakePen(aElement: TChromeLikeTabSetStyleElement; aState: TChromeLikeTabSetElementState): TGPPen; class function MakeFont(aElement: TChromeLikeTabSetStyleElement; aState: TChromeLikeTabSetElementState): TGPFont; end; implementation uses SysUtils, Windows, Graphics, l3Base, ChromeLikeTabSetUtils; var g_ChromeLikeTabSetStyles: TChromeLikeTabSetStyles = nil; const // General // Tab text font cTabTextFontName : WideString = 'Tahoma'; cTabTextFontSize : Integer = 11; cTabTextFontUnits : GDIPAPI.TUnit = GDIPAPI.UnitPixel; cTabTextFontStyle : GDIPAPI.TFontStyle = GDIPAPI.FontStyleRegular; // Tab edge cTabEdgeWidth : Single = 1.0; // Close button cross cCloseButtonCrossWidth : Single = 1.0; // Normal cTabColor : TGPColor = $99FAF8F7; cTabLeftEdgeColor : TGPColor = $99FFFFFF; cTabRightEdgeColor : TGPColor = $99919191; cTabBottomEdgeColor : TGPColor = $FFB2B2B2; // Selected cSelectedTabColor : TGPColor = $FFFAF8F9; cSelectedTabLeftEdgeColor : TGPColor = $FFFAF8F9; cSelectedTabRightEdgeColor : TGPColor = $FF919191; cSelectedTabBottomEdgeColor: TGPColor = $FFFAF8F9; { TChromeLikeTabSetStyles } class function TChromeLikeTabSetStyles.MakeBrush(aElement: TChromeLikeTabSetStyleElement; aState: TChromeLikeTabSetElementState): TGPBrush; var l_Color: TGPColor; begin l_Color := aclTransparent; case aElement of tsseTabBackground: if (aState = tsesNormal) then l_Color := cTabColor else if (aState = tsesActive) then l_Color := cSelectedTabColor; tsseNewTabButtonBackground: if (aState = tsesNormal) then l_Color := aclTransparent else if (aState = tsesHot) then l_Color := MakeGDIPcolor(RGB(0, 0, 0), 38); tsseNewTabButtonPlusSignBody: l_Color := MakeGDIPColor(RGB(0, 0, 0), 77); end; Result := TGPSolidBrush.Create(l_Color); end; class function TChromeLikeTabSetStyles.MakePen(aElement: TChromeLikeTabSetStyleElement; aState: TChromeLikeTabSetElementState): TGPPen; var l_Width: Single; l_Color: TGPColor; begin l_Color := aclTransparent; l_Width := cTabEdgeWidth; case aElement of tsseTabBorderLeft: if (aState = tsesActive) then l_Color := cSelectedTabLeftEdgeColor else l_Color := cTabLeftEdgeColor; tsseTabBorderRight: if (aState = tsesActive) then l_Color := cSelectedTabRightEdgeColor else l_Color := cTabLeftEdgeColor; tsseTabBorderBottom: if (aState = tsesActive) then l_Color := cSelectedTabBottomEdgeColor else l_Color := cSelectedTabBottomEdgeColor; tsseTabCloseButtonCross: begin if (aState = tsesHot) then l_Color := MakeGDIPColor(RGB(106, 106, 106)) else l_Color := MakeGDIPColor(RGB(148, 148, 148)); l_Width := cCloseButtonCrossWidth; end; tsseNewTabButtonPlusSignOutline: l_Color := MakeGDIPColor(RGB(255, 255, 255), 166); end; Result := TGPPen.Create(l_Color, l_Width); end; class function TChromeLikeTabSetStyles.MakeFont(aElement: TChromeLikeTabSetStyleElement; aState: TChromeLikeTabSetElementState): TGPFont; begin case aElement of tsseTabText: Result := TGPFont.Create(cTabTextFontName, cTabTextFontSize, cTabTextFontStyle, cTabTextFontUnits); else begin Result := nil; Assert(false); end; end; end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Decorators.MaxTime; interface uses System.JSON, Behavior3, Behavior3.Core.Decorator, Behavior3.Core.BaseNode, Behavior3.Core.Tick; type (** * The MaxTime decorator limits the maximum time the node child can execute. * Notice that it does not interrupt the execution itself (i.e., the child * must be non-preemptive), it only interrupts the node after a `RUNNING` * status. * * @module b3 * @class MaxTime * @extends Decorator **) TB3MaxTime = class(TB3Decorator) private protected public MaxTime: Integer; constructor Create; override; (** * Open method. * @method open * @param {Tick} tick A tick instance. **) procedure Open(Tick: TB3Tick); override; (** * Tick method. * @method tick * @param {Tick} tick A tick instance. * @return {Constant} A state constant. **) function Tick(Tick: TB3Tick): TB3Status; override; procedure Load(JsonNode: TJSONValue); override; end; implementation { TB3MaxTime } uses System.SysUtils, System.Diagnostics, System.TimeSpan, Behavior3.Helper, Behavior3.Core.BehaviorTree; constructor TB3MaxTime.Create; begin inherited; (** * Node name. Default to `MaxTime`. * @property {String} name * @readonly **) Name := 'MaxTime'; (** * Node title. Default to `Max XXms`. Used in Editor. * @property {String} title * @readonly **) Title := 'Max <maxTime>ms'; end; procedure TB3MaxTime.Open(Tick: TB3Tick); begin Tick.Blackboard.&Set('startTime', TStopWatch.GetTimeStamp, Tick.Tree.Id, Id); end; function TB3MaxTime.Tick(Tick: TB3Tick): TB3Status; var ElapsedTime, CurrTime, StartTime: Int64; Status: TB3Status; begin if not Assigned(Child) then begin Result := Behavior3.Error; Exit; end; StartTime := Tick.Blackboard.Get('startTime', Tick.Tree.Id, Id).AsInt64; CurrTime := TStopWatch.GetTimeStamp; ElapsedTime := (CurrTime - StartTime) div TTimeSpan.TicksPerMillisecond; Status := Child._Execute(Tick); if ElapsedTime > MaxTime then Result := Behavior3.Failure else Result := Status; end; procedure TB3MaxTime.Load(JsonNode: TJSONValue); begin inherited; MaxTime := LoadProperty(JsonNode, 'maxTime', MaxTime); end; end.
{------------------------------------------------------------------------------ TDzListHeader component Developed by Rodrigo Depiné Dalpiaz (digão dalpiaz) Control to create header columns to a list box https://github.com/digao-dalpiaz/DzListHeader Please, read the documentation at GitHub link. ------------------------------------------------------------------------------} unit DzListHeader; interface uses Vcl.Controls, System.Classes, Vcl.StdCtrls, Winapi.Messages, Vcl.Graphics, Vcl.ExtCtrls, System.Types; const LH_DEF_HEADERHEIGHT = 20; LH_DEF_COLORNORMALCOL = $00804000; LH_DEF_COLORHOVERCOL = $00F27900; LH_DFF_COLORSHAPE = clRed; LH_DEF_COLORLINESEL = $006FEAFB; LH_DEF_COLORLINEODD = $00F5F5F5; LH_DEF_COLORLINENORMAL = clWindow; LH_DEF_TEXTMARGIN = 2; type TDzListHeader = class; TDzListHeader_DwCol = class; TDzListHeader_DwColsPanel = class; TDzListHeaderColsEnum = class; TDzListHeaderCol = class(TCollectionItem) private Comp: TDzListHeader; CompDw: TDzListHeader_DwCol; //visual component for column painting FName: String; //name used to identify the column, and to find / to load / to save (should not be duplicated) FData: Pointer; //pointer to free-use FAlignment: TAlignment; //align used in ListBox drawitem painting FTextFont: TFont; FCustomTextFont: Boolean; FCaption: String; FCaptionEx: String; //extended caption (optional), to show in customization FHint: String; FWidth: Integer; FMinWidth: Integer; FMaxWidth: Integer; FSizeable: Boolean; FVisible: Boolean; FCustomizable: Boolean; //column non-customizable won't be loaded/saved function GetNormalizedWidth(W: Integer): Integer; //get width fixed by bounds procedure SetName(const Value: String); procedure SetCaption(const Value: String); procedure SetWidth(const Value: Integer); procedure SetMaxWidth(const Value: Integer); procedure SetMinWidth(const Value: Integer); procedure SetVisible(const Value: Boolean); procedure SetHint(const Value: String); function GetTextFontStored: Boolean; procedure OnTextFontChanged(Sender: TObject); procedure SetTextFont(const Value: TFont); protected function GetDisplayName: string; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; property Data: Pointer read FData write FData; function GetLeft: Integer; function GetRight: Integer; published property Name: String read FName write SetName; property Aligmnent: TAlignment read FAlignment write FAlignment default taLeftJustify; property TextFont: TFont read FTextFont write SetTextFont stored GetTextFontStored; property CustomTextFont: Boolean read FCustomTextFont write FCustomTextFont default False; property Caption: String read FCaption write SetCaption; property CaptionEx: String read FCaptionEx write FCaptionEx; property Hint: String read FHint write SetHint; property Width: Integer read FWidth write SetWidth; property MinWidth: Integer read FMinWidth write SetMinWidth default 0; property MaxWidth: Integer read FMaxWidth write SetMaxWidth default 0; property Sizeable: Boolean read FSizeable write FSizeable default True; property Visible: Boolean read FVisible write SetVisible default True; property Customizable: Boolean read FCustomizable write FCustomizable default True; end; TDzListHeaderColumns = class(TCollection) private Comp: TDzListHeader; function GetItem(Index: Integer): TDzListHeaderCol; protected procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TDzListHeader); reintroduce; function GetEnumerator: TDzListHeaderColsEnum; property Items[Index: Integer]: TDzListHeaderCol read GetItem; default; function FindItemID(ID: Integer): TDzListHeaderCol; function FindByName(const aName: String): TDzListHeaderCol; end; TDzListHeaderColsEnum = class{(TInterfacedObject, IEnumerator<TDzListHeaderCol>)} private List: TDzListHeaderColumns; Index: Integer; protected function GetCurrent: TDzListHeaderCol; virtual; public constructor Create(xList: TDzListHeaderColumns); function MoveNext: Boolean; property Current: TDzListHeaderCol read GetCurrent; end; {TDzListHeader_DwCol This component paints the column on header, and eighter the blank space after last column. These objects are inside the TDzListHeader_DwColsPanel.} TDzListHeader_DwCol = class(TGraphicControl) private StartPosX: Integer; ResizeReady: Boolean; //indicates when mouse is in the resizing area ResizeCol: TDzListHeaderCol; //column that will be resized (can be Col ou ColAnt) Resizing: Boolean; //indicates resizing in progress (while mouse pressed) Moving: Boolean; //indicated column repositioning in progress (while mouse pressed) Moving_DwCol: TDzListHeader_DwCol; //column at position in which actual column will be moved MouseMoved: Boolean; //indicates if mouse was moved while Down/Move/Up sequence Hover: Boolean; //indicated mouse over column (selected) Blank: Boolean; //indicates blank area (does not have column related) First: Boolean; //indicates the first visible column Head: TDzListHeader_DwColsPanel; //object that contains the visible columns Comp: TDzListHeader; Col, ColAnt: TDzListHeaderCol; //pointer to this column and previous column procedure DoUpdMouseResizing; //set resize flags by actual mouse position protected procedure Paint; override; procedure CMMouseenter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseleave(var Message: TMessage); message CM_MOUSELEAVE; procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; public constructor Create(AOwner: TDzListHeader_DwColsPanel; xCol: TDzListHeaderCol); reintroduce; end; {TDzListHeader_DwColsPanel Object inside the TDzListHeader_Top and contains all visible columns. This component does not stay align, because it should be resized according the columns size, to work together with scroll.} TDzListHeader_DwColsPanel = class(TCustomControl) private Comp: TDzListHeader; BlankArea: TDzListHeader_DwCol; //object for blank area at the end of columns at right procedure RepaintCols; //force invalidate to all visible columns procedure Build; //update visible columns function FindColAtMousePos: TDzListHeader_DwCol; //get column by actual mouse position public constructor Create(AOwner: TDzListHeader); reintroduce; end; {TDzListHeader_Top Object aligned to the Top of TDzListHeader, and contains only child component TDzListHeader_DwColsPanel, that contains the columns} TDzListHeader_Top = class(TCustomControl) private Comp: TDzListHeader; protected procedure Resize; override; public constructor Create(AOwner: TDzListHeader); reintroduce; end; TEvDzListHeaderColumnDraw = procedure(Sender: TObject; Col: TDzListHeaderCol; Canvas: TCanvas; Rect: TRect; Hover: Boolean) of object; TEvDzListHeaderColumnOp = procedure(Sender: TObject; Col: TDzListHeaderCol) of object; TEvDzListHeaderOnDrawItem = procedure(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState) of object; //Vcl.StdCtrls.TDrawItemEvent TDzListHeader = class(TCustomControl) private FAbout: String; FAllowResize: Boolean; FAllowMoving: Boolean; FHeaderHeight: Integer; FTitleFont: TFont; CTop: TDzListHeader_Top; Head: TDzListHeader_DwColsPanel; FColumns: TDzListHeaderColumns; FListBox: TCustomListBox; SB: TScrollBar; FColorHoverCol: TColor; FColorNormalCol: TColor; FColorShape: TColor; FColorLineSel: TColor; FColorLineOdd: TColor; FColorLineNormal: TColor; FUseOdd: Boolean; FAutoDrawTabbedText: Boolean; FLineCenter: Boolean; FLineTop: Integer; FTextMargin: Integer; FEvColumnDraw: TEvDzListHeaderColumnDraw; FEvColumnClick, FEvColumnRClick, FEvColumnResize, FEvMouseEnterCol, FEvMouseLeaveCol: TEvDzListHeaderColumnOp; FEvOnDrawItem: TEvDzListHeaderOnDrawItem; Shape: TPanel; //dash to indicate resizing or moving function GetStored_Columns: Boolean; function GetStored_TitleFont: Boolean; procedure OnScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); procedure OnTitleFontChange(Sender: TObject); procedure SetListBox(const Value: TCustomListBox); procedure SetHeaderHeight(const Value: Integer); procedure SetColorNormalCol(const Value: TColor); procedure SetColorHoverCol(const Value: TColor); procedure SetTitleFont(const Value: TFont); procedure CreateShape(bResizing: Boolean); procedure FreeShape; procedure UpdListBox; procedure ListBoxOnDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure DoEnsureListBoxAssigned; procedure DrawTabbedText(Index: Integer; Rect: TRect); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadCustom(const A: String); function SaveCustom: String; function ColByID(ID: Integer): TDzListHeaderCol; function ColByName(const aName: String): TDzListHeaderCol; procedure DwCol(ID: Integer; Rect: TRect; const Value: Variant; Margin: Integer = 0); function AddItem(const Ar: TArray<String>): Integer; function GetItemArray(Index: Integer): TArray<String>; published property About: String read FAbout; property Anchors; property Align; property Enabled; property Visible; property ShowHint; property ParentShowHint; property PopupMenu; property ListBox: TCustomListBox read FListBox write SetListBox; property Columns: TDzListHeaderColumns read FColumns write FColumns stored GetStored_Columns; property AllowResize: Boolean read FAllowResize write FAllowResize default True; property AllowMoving: Boolean read FAllowMoving write FAllowMoving default True; property HeaderHeight: Integer read FHeaderHeight write SetHeaderHeight default LH_DEF_HEADERHEIGHT; property ColorHoverCol: TColor read FColorHoverCol write SetColorHoverCol default LH_DEF_COLORHOVERCOL; property ColorNormalCol: TColor read FColorNormalCol write SetColorNormalCol default LH_DEF_COLORNORMALCOL; property ColorShape: TColor read FColorShape write FColorShape default LH_DFF_COLORSHAPE; property ColorLineSel: TColor read FColorLineSel write FColorLineSel default LH_DEF_COLORLINESEL; property ColorLineOdd: TColor read FColorLineOdd write FColorLineOdd default LH_DEF_COLORLINEODD; property ColorLineNormal: TColor read FColorLineNormal write FColorLineNormal default LH_DEF_COLORLINENORMAL; property UseOdd: Boolean read FUseOdd write FUseOdd default False; property AutoDrawTabbedText: Boolean read FAutoDrawTabbedText write FAutoDrawTabbedText default False; property LineCenter: Boolean read FLineCenter write FLineCenter default True; property LineTop: Integer read FLineTop write FLineTop default 0; property TextMargin: Integer read FTextMargin write FTextMargin default LH_DEF_TEXTMARGIN; property TitleFont: TFont read FTitleFont write SetTitleFont stored GetStored_TitleFont; property OnColumnDraw: TEvDzListHeaderColumnDraw read FEvColumnDraw write FEvColumnDraw; property OnColumnClick: TEvDzListHeaderColumnOp read FEvColumnClick write FEvColumnClick; property OnColumnRClick: TEvDzListHeaderColumnOp read FEvColumnRClick write FEvColumnRClick; property OnColumnResize: TEvDzListHeaderColumnOp read FEvColumnResize write FEvColumnResize; property OnMouseEnterCol: TEvDzListHeaderColumnOp read FEvMouseEnterCol write FEvMouseEnterCol; property OnMouseLeaveCol: TEvDzListHeaderColumnOp read FEvMouseLeaveCol write FEvMouseLeaveCol; property OnDrawItem: TEvDzListHeaderOnDrawItem read FEvOnDrawItem write FEvOnDrawItem; end; procedure Register; implementation uses System.SysUtils, Winapi.Windows, System.Math, Vcl.Forms, System.UITypes, System.StrUtils, DzListHeaderCustom; procedure Register; begin RegisterComponents('Digao', [TDzListHeader]); end; type TAcListBox = class(TCustomListBox); //to access listbox properties procedure TDzListHeader.CreateShape(bResizing: Boolean); begin Shape := TPanel.Create(Self); Shape.BevelOuter := bvNone; Shape.ParentBackground := False; Shape.Color := FColorShape; Shape.Caption := ''; if bResizing then begin Shape.Parent := Self; Shape.Width := 1; Shape.Top := CTop.Height; Shape.Height := Height-Shape.Top-IfThen(SB.Visible, SB.Height); end else begin Shape.Parent := Head; Shape.Width := 2; Shape.Top := 0; Shape.Height := Head.Height; end; end; procedure TDzListHeader.FreeShape; begin if Assigned(Shape) then FreeAndNil(Shape); end; { TDzListHeader } constructor TDzListHeader.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csAcceptsControls]; //accept sub-controls FAbout := 'Digão Dalpiaz / Version 1.0'; FAllowResize := True; FAllowMoving := True; FColorHoverCol := LH_DEF_COLORHOVERCOL; FColorNormalCol := LH_DEF_COLORNORMALCOL; FColorShape := LH_DFF_COLORSHAPE; FColorLineSel := LH_DEF_COLORLINESEL; FColorLineOdd := LH_DEF_COLORLINEODD; FColorLineNormal := LH_DEF_COLORLINENORMAL; FLineCenter := True; FTextMargin := LH_DEF_TEXTMARGIN; FColumns := TDzListHeaderColumns.Create(Self); FTitleFont := TFont.Create; FTitleFont.Name := 'Segoe UI'; FTitleFont.Color := clWhite; FTitleFont.OnChange := OnTitleFontChange; //--Create main panel align at Top CTop := TDzListHeader_Top.Create(Self); CTop.Parent := Self; CTop.Align := alTop; //-- //--Create columns panel (this object remains inside the Top panel) Head := TDzListHeader_DwColsPanel.Create(Self); Head.Parent := CTop; Head.Left := 0; //initial position //-- SetHeaderHeight(LH_DEF_HEADERHEIGHT); //set property and redefine Head height //--Create scroll bar control SB := TScrollBar.Create(Self); SB.Parent := Self; SB.Align := alBottom; SB.TabStop := False; SB.OnScroll := OnScroll; //-- end; destructor TDzListHeader.Destroy; begin FColumns.Free; FTitleFont.Free; inherited; end; procedure TDzListHeader.DoEnsureListBoxAssigned; begin if not Assigned(FListBox) then raise Exception.Create('ListBox not assigned'); end; function TDzListHeader.AddItem(const Ar: TArray<String>): Integer; var A, Line: String; begin DoEnsureListBoxAssigned; for A in Ar do Line := Line + A + #9; Result := FListBox.Items.Add(Line); end; function TDzListHeader.GetItemArray(Index: Integer): TArray<String>; begin DoEnsureListBoxAssigned; Result := FListBox.Items[Index].Split([#9]); end; function TDzListHeader.ColByID(ID: Integer): TDzListHeaderCol; begin Result := FColumns.FindItemID(ID); end; function TDzListHeader.ColByName(const aName: String): TDzListHeaderCol; begin Result := FColumns.FindByName(aName); end; procedure TDzListHeader.ListBoxOnDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin if TAcListBox(FListBox).Font.Color=clWindowText then FListBox.Canvas.Font.Color := clBlack; //fix invert color when selected FListBox.Canvas.Brush.Color := FColorLineNormal; if FUseOdd then if Odd(Index) then FListBox.Canvas.Brush.Color := FColorLineOdd; if odSelected in State then FListBox.Canvas.Brush.Color := FColorLineSel; FListBox.Canvas.FillRect(Rect); if FAutoDrawTabbedText then DrawTabbedText(Index, Rect) else if Assigned(FEvOnDrawItem) then FEvOnDrawItem(Control, Index, Rect, State); //fix focus rectangle when using colors FListBox.Canvas.Font.Color := clBlack; FListBox.Canvas.TextOut(0, 0, ''); end; procedure TDzListHeader.DrawTabbedText(Index: Integer; Rect: TRect); var Ar: TArray<String>; I: Integer; begin Ar := GetItemArray(Index); I := 0; while I<FColumns.Count do begin DwCol(I, Rect, Ar[I]); Inc(I); end; end; procedure TDzListHeader.DwCol(ID: Integer; Rect: TRect; const Value: Variant; Margin: Integer = 0); var C: TDzListHeaderCol; R: TRect; A: String; X, Y: Integer; OriginalFont: TFont; begin DoEnsureListBoxAssigned; // C := FColumns.FindItemID(ID); if not C.FVisible then Exit; OriginalFont := nil; //avoid warning if C.FCustomTextFont then //column has specific font begin OriginalFont := TFont.Create; OriginalFont.Assign(FListBox.Canvas.Font); //save current font FListBox.Canvas.Font.Assign(C.FTextFont); //assign custom font end; R := System.Types.Rect(C.GetLeft+FTextMargin+Margin, Rect.Top, C.GetRight-FTextMargin, Rect.Bottom); A := Value; X := 0; if C.FAlignment in [taRightJustify, taCenter] then begin X := R.Width-FListBox.Canvas.TextWidth(A); if C.FAlignment=taCenter then X := X div 2; end; if FLineCenter then Y := (TAcListBox(FListBox).ItemHeight-FListBox.Canvas.TextHeight('A')) div 2 else Y := FLineTop; FListBox.Canvas.TextRect(R, R.Left+X, R.Top+Y, A); //draw text // if C.FCustomTextFont then begin FListBox.Canvas.Font.Assign(OriginalFont); //get back original font OriginalFont.Free; end; end; procedure TDzListHeader.UpdListBox; begin if Assigned(FListBox) then FListBox.Invalidate; end; procedure TDzListHeader.LoadCustom(const A: String); var Ar: TArray<String>; aInfoCol, aName: String; Col: TDzListHeaderCol; Vis: Boolean; I, X, W: Integer; begin Ar := A.Split(['|']); FColumns.BeginUpdate; try for I := 0 to High(Ar) do begin try aInfoCol := Ar[I]; Vis := not aInfoCol.StartsWith('~'); if not Vis then Delete(aInfoCol, 1, 1); X := Pos('=', aInfoCol); if X=0 then raise Exception.Create('Separator not found'); aName := Copy(aInfoCol, 1, X-1); if aName='' then raise Exception.Create('Blank name'); Delete(aInfoCol, 1, X); if not TryStrToInt(aInfoCol, W) then raise Exception.Create('Invalid value'); Col := FColumns.FindByName(aName); if Col<>nil then //the column may no longer exist in the project if Col.FCustomizable then begin Col.Index := I; //using published properties to values processing Col.Visible := Vis; Col.Width := W; end; except on E: Exception do raise Exception.CreateFmt('Error on loading customization of header "%s" at index %d ["%s"]: %s', [Name, I, Ar[I], E.Message]); end; end; finally FColumns.EndUpdate; end; end; function TDzListHeader.SaveCustom: String; var C: TDzListHeaderCol; I: Integer; begin Result := ''; for I := 0 to FColumns.Count-1 do begin C := FColumns[I]; if C.FCustomizable then begin if C.FName='' then //the column must have a name to save raise Exception.CreateFmt('Column %d without a name', [I]); Result := Result+'|'+Format('%s%s=%d', [IfThen(not C.FVisible, '~'), C.FName, C.FWidth]); end; end; Delete(Result, 1, 1); end; function TDzListHeader.GetStored_Columns: Boolean; begin Result := FColumns.Count>0; end; function TDzListHeader.GetStored_TitleFont: Boolean; begin Result := not ( (FTitleFont.Charset = DEFAULT_CHARSET) and (FTitleFont.Color = clWhite) and (FTitleFont.Name = 'Segoe UI') and (FTitleFont.Size = 8) and (FTitleFont.Style = []) and (FTitleFont.Quality = fqDefault) and (FTitleFont.Pitch = fpDefault) and (FTitleFont.Orientation = 0) ); end; procedure TDzListHeader.SetListBox(const Value: TCustomListBox); begin if Value <> FListBox then begin //check for correct parent if Value<>nil then if Value.Parent<>Self then raise Exception.Create('ListBox should be inside ListHeader'); if FListBox<>nil then //old begin FListBox.RemoveFreeNotification(Self); if not (csDesigning in ComponentState) then TAcListBox(FListBox).OnDrawItem := nil; end; if Value<>nil then //new begin Value.FreeNotification(Self); if not (csDesigning in ComponentState) then TAcListBox(Value).OnDrawItem := ListBoxOnDrawItem; //automatic definitions to listbox TAcListBox(Value).Align := alClient; if TAcListBox(Value).Style=lbStandard then begin TAcListBox(Value).Style := lbOwnerDrawFixed; TAcListBox(Value).ItemHeight := 20; end; end; FListBox := Value; end; end; procedure TDzListHeader.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent=FListBox) and (Operation=opRemove) then FListBox := nil; end; procedure TDzListHeader.OnScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); var Limit: Integer; begin Limit := SB.Max{+1}-SB.PageSize; {+1 because PageSize remains always 1 pixel more?} if ScrollPos>Limit then ScrollPos := Limit; Head.Left := -ScrollPos; UpdListBox; end; procedure TDzListHeader.SetHeaderHeight(const Value: Integer); begin FHeaderHeight := Value; CTop.Height := Value; //update Top panel height (will run resize event) end; procedure TDzListHeader.SetTitleFont(const Value: TFont); begin if FTitleFont<>Value then begin FTitleFont.Assign(Value); //Head.RepaintCols; ??? end; end; procedure TDzListHeader.OnTitleFontChange(Sender: TObject); begin Head.RepaintCols; end; procedure TDzListHeader.SetColorHoverCol(const Value: TColor); begin if FColorHoverCol<>Value then begin FColorHoverCol := Value; Head.RepaintCols; end; end; procedure TDzListHeader.SetColorNormalCol(const Value: TColor); begin if FColorNormalCol<>Value then begin FColorNormalCol := Value; Head.RepaintCols; end; end; { TDzListHeaderColumns } constructor TDzListHeaderColumns.Create(AOwner: TDzListHeader); begin inherited Create(TDzListHeaderCol); Comp := AOwner; end; function TDzListHeaderColumns.FindByName(const aName: String): TDzListHeaderCol; var Col: TDzListHeaderCol; begin Result := nil; if aName='' then raise Exception.Create('Name not specified to find'); for Col in Self do if SameText(Col.FName, aName) then begin Result := Col; Break; end; end; function TDzListHeaderColumns.FindItemID(ID: Integer): TDzListHeaderCol; begin Result := TDzListHeaderCol( inherited FindItemID(ID) ); end; function TDzListHeaderColumns.GetEnumerator: TDzListHeaderColsEnum; begin Result := TDzListHeaderColsEnum.Create(Self); end; function TDzListHeaderColumns.GetItem(Index: Integer): TDzListHeaderCol; begin Result := TDzListHeaderCol( inherited GetItem(Index) ); end; procedure TDzListHeaderColumns.Update(Item: TCollectionItem); begin inherited; Comp.Head.Build; //on change collection properties, needs rebuild columns end; { TDzListHeaderColsEnum } constructor TDzListHeaderColsEnum.Create(xList: TDzListHeaderColumns); begin List := xList; Index := -1; end; function TDzListHeaderColsEnum.GetCurrent: TDzListHeaderCol; begin Result := List[Index]; end; function TDzListHeaderColsEnum.MoveNext: Boolean; begin Result := Index < List.Count-1; if Result then Inc(Index); end; { TDzListHeaderCol } constructor TDzListHeaderCol.Create(Collection: TCollection); begin inherited; Comp := TDzListHeaderColumns(Collection).Comp; FTextFont := TFont.Create; FTextFont.OnChange := OnTextFontChanged; FAlignment := taLeftJustify; FSizeable := True; FVisible := True; FCustomizable := True; FWidth := 100; //initial width (not default!) end; destructor TDzListHeaderCol.Destroy; begin if Assigned(CompDw) then CompDw.Free; FTextFont.Free; inherited; end; function TDzListHeaderCol.GetDisplayName: string; begin Result := FName; if FName='' then Result := inherited GetDisplayName; end; procedure TDzListHeaderCol.SetName(const Value: String); begin if Value.IndexOfAny(['|','~','='])<>-1 then raise Exception.Create('Character not allowed'); //because coding used in load/save customization string FName := Trim(Value); end; procedure TDzListHeaderCol.SetCaption(const Value: String); begin if FCaption<>Value then begin FCaption := Value; if Assigned(CompDw) then CompDw.Invalidate; //repaint this column visual object end; end; procedure TDzListHeaderCol.SetTextFont(const Value: TFont); begin FTextFont.Assign(Value); end; function TDzListHeaderCol.GetTextFontStored: Boolean; begin Result := FCustomTextFont; //textfont property will be stored if is custom end; procedure TDzListHeaderCol.OnTextFontChanged(Sender: TObject); begin FCustomTextFont := True; end; procedure TDzListHeaderCol.SetHint(const Value: String); begin if FHint<>Value then begin FHint := Value; if Assigned(CompDw) then CompDw.Hint := Value; {the hint is set in Build eigther} end; end; procedure TDzListHeaderCol.SetMaxWidth(const Value: Integer); begin if FMaxWidth<>Value then begin FMaxWidth := Value; if Value<FWidth then SetWidth(Value); end; end; procedure TDzListHeaderCol.SetMinWidth(const Value: Integer); begin if FMinWidth<>Value then begin FMinWidth := Value; if Value>FWidth then SetWidth(Value); end; end; function TDzListHeaderCol.GetNormalizedWidth(W: Integer): Integer; begin if FMinWidth>0 then if W<FMinWidth then W := FMinWidth; if FMaxWidth>0 then if W>FMaxWidth then W := FMaxWidth; if W<10 then W := 10; Result := W; end; procedure TDzListHeaderCol.SetWidth(const Value: Integer); var W: Integer; begin W := GetNormalizedWidth(Value); if FWidth<>W then begin FWidth := W; Changed(False); end; end; procedure TDzListHeaderCol.SetVisible(const Value: Boolean); begin if FVisible<>Value then begin FVisible := Value; Changed(False); end; end; function TDzListHeaderCol.GetLeft: Integer; begin if not FVisible then raise Exception.Create('Column not visible'); Result := Comp.Head.Left+CompDw.Left; end; function TDzListHeaderCol.GetRight: Integer; begin //* The check for visible column already ocurrs on GetLeft Result := GetLeft+CompDw.Width; end; { TListHeader_DwPanel } constructor TDzListHeader_DwColsPanel.Create(AOwner: TDzListHeader); begin inherited Create(AOwner); Comp := AOwner; BlankArea := TDzListHeader_DwCol.Create(Self, nil); BlankArea.Blank := True; end; function TDzListHeader_DwColsPanel.FindColAtMousePos: TDzListHeader_DwCol; var X, iMax: Integer; begin //get visual column by actual mouse position (always return a column) X := ScreenToClient(Mouse.CursorPos).X; if X<0 then X := 0 else begin iMax := Width-BlankArea.Width-1; //-1 bacuse the full width already outside objects area if X>iMax then X := iMax; end; Result := TDzListHeader_DwCol( ControlAtPos(Point(X, 0), False) ); end; procedure TDzListHeader_DwColsPanel.Build; var Col, ColAnt: TDzListHeaderCol; X, W, Wtot: Integer; Count: Integer; ItFits: Boolean; const SOBRINHA = 20; //safety space of listbox vertical scroll bar begin if csLoading in Comp.ComponentState then Exit; Count := 0; ColAnt := nil; X := 0; for Col in Comp.FColumns do begin if Col.FVisible then begin Inc(Count); if not Assigned(Col.CompDw) then Col.CompDw := TDzListHeader_DwCol.Create(Self, Col); Col.CompDw.Hint := Col.FHint; //update hint Col.CompDw.First := Count=1; Col.CompDw.ColAnt := ColAnt; W := Col.FWidth; Col.CompDw.SetBounds(X, 0, W, Height); Inc(X, W); ColAnt := Col; end else begin if Assigned(Col.CompDw) then FreeAndNil(Col.CompDw); end; end; Wtot := X+1+SOBRINHA; //get full size including final dash ItFits := Wtot<=Comp.CTop.Width; if ItFits then //columns and waste fits on total width Width := Comp.CTop.Width //set Head width equals full width else Width := Wtot; //--Set blank area at right corner BlankArea.SetBounds(X, 0, Width-X, Height); BlankArea.ColAnt := ColAnt; //-- X := X+BlankArea.Width; //calc all columns size including blank area if X+Left<Comp.CTop.Width then begin //is decreasing column, then should move all objects to ensure not left blank space Left := Comp.CTop.Width-X; end; Comp.SB.Visible := not ItFits; if Comp.SB.Visible then begin Comp.SB.PageSize := 0; //avoid error Comp.SB.Max := Width{-1}; //-1 else scroll always jump 1 pixel more Comp.SB.PageSize := Comp.CTop.Width; Comp.SB.Position := -Left; //update scroll bar position end else begin Comp.SB.PageSize := 0; Comp.SB.Max := 0; Comp.SB.Position := 0; end; Comp.UpdListBox; end; procedure TDzListHeader_DwColsPanel.RepaintCols; var I: Integer; begin //if csLoading in Comp.ComponentState then Exit; //Repaint all columns for I := 0 to ControlCount-1 do if Controls[I] is TDzListHeader_DwCol then //should all be (lol!) Controls[I].Invalidate; end; { TDzListHeader_DwCol } constructor TDzListHeader_DwCol.Create(AOwner: TDzListHeader_DwColsPanel; xCol: TDzListHeaderCol); begin inherited Create(AOwner); Head := AOwner; Comp := AOwner.Comp; Col := xCol; Parent := AOwner; ShowHint := True; end; procedure TDzListHeader_DwCol.CMMouseenter(var Message: TMessage); begin DoUpdMouseResizing; if not Blank then begin Hover := True; Invalidate; if Assigned(Comp.FEvMouseEnterCol) then Comp.FEvMouseEnterCol(Comp, Col); end; end; procedure TDzListHeader_DwCol.CMMouseleave(var Message: TMessage); begin DoUpdMouseResizing; if not Blank then begin Hover := False; Invalidate; if Assigned(Comp.FEvMouseLeaveCol) then Comp.FEvMouseLeaveCol(Comp, Col); end; end; procedure TDzListHeader_DwCol.DoUpdMouseResizing; var P: TPoint; OK: Boolean; tmpCol: TDzListHeaderCol; begin //if Resizing then Exit; P := CalcCursorPos; //get mouse actual position relative to this control OK := False; tmpCol := nil; if Comp.FAllowResize then if Comp.FColumns.Count>0 then //if no columns, there be only then blank area, which does not have ColAnt if PtInRect(Comp.CTop.ClientRect, Comp.CTop.CalcCursorPos) then //when mouseup outside the area //if PtInRect(ClientRect, P) then //mouse is inside this control if ((not First) and (P.X<4)) or ((not Blank) and (P.X>Width-4)) then begin if P.X<4 then tmpCol := ColAnt else tmpCol := Col; if tmpCol.FSizeable then OK := True; end; if OK then begin Screen.Cursor := crHSplit; ResizeReady := True; ResizeCol := tmpCol; end else begin Screen.Cursor := crDefault; ResizeReady := False; ResizeCol := nil; end; end; procedure TDzListHeader_DwCol.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Button=mbLeft then begin StartPosX := X; //save initial position to resize or move MouseMoved := False; //reset moved flag if ResizeReady then begin //resizing Comp.CreateShape(True); Comp.Shape.Left := Head.Left+ResizeCol.CompDw.Left+ResizeCol.CompDw.Width; Resizing := True; end; end; end; procedure TDzListHeader_DwCol.MouseMove(Shift: TShiftState; X, Y: Integer); var I: Integer; begin inherited; if ssLeft in Shift then //left mouse pressed begin MouseMoved := True; if Resizing then begin I := ResizeCol.GetNormalizedWidth(ResizeCol.CompDw.Width+X-StartPosX); Comp.Shape.Left := Comp.Head.Left+ResizeCol.CompDw.Left+I; end else if Comp.FAllowMoving and not Blank then begin if not Moving then begin Moving := True; Comp.CreateShape(False); end; Moving_DwCol := Head.FindColAtMousePos; I := Moving_DwCol.Left; if X>StartPosX then //moving ahead Inc(I, Moving_DwCol.Width); Comp.Shape.Left := I; end; end else DoUpdMouseResizing; end; procedure TDzListHeader_DwCol.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Resizing then begin Resizing := False; Comp.FreeShape; ResizeCol.SetWidth(ResizeCol.CompDw.Width+X-StartPosX); Comp.UpdListBox; if Assigned(Comp.FEvColumnResize) then Comp.FEvColumnResize(Comp, ResizeCol); end else if Moving then begin Moving := False; Comp.FreeShape; Col.Index := Moving_DwCol.Col.Index; Comp.UpdListBox; end else if Button=mbRight then DoListHeaderCustomizeDlg(Comp) else if (not MouseMoved) and (not Blank) then case Button of mbLeft: if Assigned(Comp.FEvColumnClick) then Comp.FEvColumnClick(Comp, Col); mbRight: if Assigned(Comp.FEvColumnRClick) then Comp.FEvColumnRClick(Comp, Col); end; end; procedure TDzListHeader_DwCol.Paint; var B: Vcl.Graphics.TBitmap; R: TRect; Fmt: Cardinal; H, altTxt: Integer; A: String; C: TColor; begin inherited; B := Vcl.Graphics.TBitmap.Create; try B.SetSize(Width, Height); // if Hover then C := Comp.FColorHoverCol else C := Comp.FColorNormalCol; B.Canvas.Brush.Color := C; B.Canvas.Pen.Color := clBtnShadow; B.Canvas.Rectangle(0, 0, Width+IfThen(not Blank, 1), Height+1); if not Blank then begin B.Canvas.Font.Assign(Comp.FTitleFont); A := Col.FCaption; Fmt := DT_NOPREFIX; H := DrawText(B.Canvas.Handle, A, -1, R, DT_CALCRECT or Fmt); //calc text height altTxt := (Height+1-H) div 2; if altTxt<1 then altTxt := 1; R := Rect(2, altTxt, Width, Height); DrawText(B.Canvas.Handle, A, -1, R, Fmt); if Assigned(Comp.FEvColumnDraw) then Comp.FEvColumnDraw(Comp, Col, B.Canvas, ClientRect, Hover) end; // Canvas.Draw(0, 0, B); finally B.Free; end; end; { TDzListHeader_Top } constructor TDzListHeader_Top.Create(AOwner: TDzListHeader); begin inherited Create(AOwner); Comp := AOwner; end; procedure TDzListHeader_Top.Resize; begin inherited; Comp.Head.Height := Height; Comp.Head.Build; //rebuild columns (Width or Height may be changed) end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.CloudStorage Description : CloudStorage Author : Kike Pérez Version : 1.8 Created : 14/10/2018 Modified : 07/10/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.CloudStorage; {$i QuickLib.inc} interface uses Classes, System.SysUtils, System.Generics.Collections, Data.Cloud.CloudAPI; type TCloudActionStatus = (stNone, stSearching, stRetrieving, stDone, stFailed); TCloudProtocol = (cpHTTP,cpHTTPS); TResponseInfo = record StatusCode : Integer; StatusMsg : string; procedure Get(aStatusCode : Integer; const aStatusMsg : string); overload; procedure Get(aCloudResponseInfo : TCloudResponseInfo); overload; end; TCloudItem = class private fName : string; fIsDir : Boolean; fSize : Int64; fDate : TDateTime; public property Name : string read fName write fName; property IsDir : Boolean read fIsDir write fIsDir; property Size : Int64 read fSize write fSize; property Date : TDateTime read fDate write fDate; end; TCloudItemList = TObjectList<TCloudItem>; TReadDirEvent = procedure(const aDir : string) of object; TGetListItemEvent = procedure(aItem : TCloudItem) of object; TChangeStatusEvent = procedure(aStatus : TCloudActionStatus) of object; ICloudStorage = interface ['{5F36CD88-405F-45C1-89E0-9114146CA8D9}'] function GetName : string; function GetRootFolders : TStrings; procedure OpenDir(const aPath : string); function GetFile(const aSourcePath: string; out stream : TStream) : Boolean; overload; function GetFile(const aSourcePath, aTargetLocalFile : string) : Boolean; overload; function GetURL(const aPath : string) : string; end; TCloudPermissions = class private fCanList : Boolean; fCanRead : Boolean; fCanWrite : Boolean; fCanDelete : Boolean; public property CanList : Boolean read fCanList write fCanList; property CanRead : Boolean read fCanRead write fCanRead; property CanWrite : Boolean read fCanWrite write fCanWrite; property CanDelete : Boolean read fCanDelete write fCanDelete; end; TCloudStorageProvider = class(TInterfacedObject,ICloudStorage) private fName : string; fResponseInfo : TResponseInfo; fCurrentPath : string; fOnGetListItem : TGetListItemEvent; fOnBeginReadDir : TReadDirEvent; fOnRefresReadDir : TReadDirEvent; fOnEndReadDir : TReadDirEvent; fOnChangeStatus : TChangeStatusEvent; fStatus: TCloudActionStatus; fRootFolder : string; fTimeout : Integer; fSecure : Boolean; fPermissions : TCloudPermissions; procedure SetStatus(aStatus : TCloudActionStatus); protected fCancelOperation : Boolean; procedure SetSecure(aValue : Boolean); virtual; function GMT2DateTime(const gmtdate : string):TDateTime; public constructor Create; virtual; destructor Destroy; override; property Name : string read fName write fName; property ResponseInfo : TResponseInfo read fResponseInfo write fResponseInfo; property Timeout : Integer read fTimeout write fTimeout; property CurrentPath : string read fCurrentPath write fCurrentPath; property RootFolder : string read fRootFolder write fRootFolder; property OnBeginReadDir : TReadDirEvent read fOnBeginReadDir write fOnBeginReadDir; property OnRefreshReadDir : TReadDirEvent read fOnRefresReadDir write fOnRefresReadDir; property OnEndReadDir : TReadDirEvent read fOnEndReadDir write fOnEndReadDir; property OnGetListItem : TGetListItemEvent read fOnGetListItem write fOnGetListItem; property Status : TCloudActionStatus read fStatus write SetStatus; property Secure : Boolean read fSecure write SetSecure; property OnChangeStatus : TChangeStatusEvent read fOnChangeStatus write fOnChangeStatus; property Permissions : TCloudPermissions read fPermissions write fPermissions; class function GetStatusStr(aStatus : TCloudActionStatus) : string; function GetName : string; function GetRootFolders : TStrings; virtual; abstract; procedure OpenDir(const aPath : string); virtual; abstract; function GetFile(const aPath: string; out stream : TStream) : Boolean; overload; virtual; abstract; function GetFile(const aSourcePath, aTargetLocalFile : string) : Boolean; overload; virtual; function GetURL(const aPath : string) : string; virtual; abstract; end; implementation const CloudActionStatusStr : array of string = ['','Searching...','Retrieving...','Done','Failed']; constructor TCloudStorageProvider.Create; begin fCancelOperation := False; fPermissions := TCloudPermissions.Create; fTimeout := 30; fSecure := True; fPermissions.CanList := True; fPermissions.CanRead := True; fPermissions.CanWrite := True; fPermissions.CanDelete := True; end; destructor TCloudStorageProvider.Destroy; begin if Assigned(fPermissions) then fPermissions.Free; inherited; end; function TCloudStorageProvider.GetFile(const aSourcePath, aTargetLocalFile: string): Boolean; var stream : TStream; begin stream := TFileStream.Create(aTargetLocalFile,fmCreate); try Result := GetFile(aSourcePath,stream); finally stream.Free; end; end; function TCloudStorageProvider.GetName: string; begin Result := fName; end; class function TCloudStorageProvider.GetStatusStr(aStatus: TCloudActionStatus): string; begin Result := CloudActionStatusStr[Integer(aStatus)]; end; function TCloudStorageProvider.GMT2DateTime(const gmtdate: string): TDateTime; function GetMonthDig(Value : string):Integer; const aMonth : array[1..12] of string = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); var idx : Integer; begin Result := 0; for idx := 1 to 12 do begin if CompareText(Value,aMonth[idx]) = 0 then begin Result := idx; Break; end; end; end; var i : Integer; Len : Integer; wDay, wMonth, wYear, wHour, wMinute, wSec : Word; begin //GMT Format: 'Mon, 12 Jan 2014 16:20:35 GMT' Result := 0; Len := 0; if gmtdate = '' then Exit; try for i := 0 to Length(gmtdate) do begin if gmtdate[i] in ['0'..'9'] then begin Len := i; Break; end; end; //Day wDay := StrToIntDef(Copy(gmtdate,Len,2),0); if wDay = 0 then Exit; Inc(Len,3); //Month wMonth := GetMonthDig(Copy(gmtdate,Len,3)); if wMonth = 0 then Exit; Inc(Len,4); //Year wYear := StrToIntDef(Copy(gmtdate,Len,4),0); if wYear = 0 then Exit; Inc(Len,5); //Hour wHour := StrToIntDef(Copy(gmtdate,Len,2),99); if wHour = 99 then Exit; Inc(Len,3); //Min wMinute := StrToIntDef(Copy(gmtdate,Len,2),99); if wMinute = 99 then Exit; Inc(Len,3); //Sec wSec := StrToIntDef(Copy(gmtdate,Len,2),99); if wSec = 99 then Exit; Result := EncodeDate(wYear,wMonth,wDay) + EncodeTime(wHour,wMinute,wSec,0); except Result := 0; end; end; procedure TCloudStorageProvider.SetSecure(aValue: Boolean); begin fSecure := aValue; end; procedure TCloudStorageProvider.SetStatus(aStatus: TCloudActionStatus); begin fStatus := aStatus; if Assigned(fOnChangeStatus) then fOnChangeStatus(aStatus); end; { TResponseInfo } procedure TResponseInfo.Get(aStatusCode: Integer; const aStatusMsg: string); begin Self.StatusCode := aStatusCode; Self.StatusMsg := aStatusMsg; end; procedure TResponseInfo.Get(aCloudResponseInfo : TCloudResponseInfo); begin Self.StatusCode := aCloudResponseInfo.StatusCode; Self.StatusMsg := aCloudResponseInfo.StatusMessage; end; end.
unit ThdRemoveNoticeScan; interface uses Classes, ThreadReportBase, TTSTitmTable, TTSHitmTable, dbisamtb, TicklerTypes; type TRemoveNoticeScan = class(TThdReportBase) private tblTitm : TTTSTitmTable; tblHitm : TTTSHitmTable; ScanID : integer; protected procedure Execute; override; public constructor create(ARptID:integer;DoOnTerminate:TNotifyEvent); override; destructor destroy; override; end; implementation uses programsettings, ffsutils, sysutils, db; constructor TRemoveNoticeScan.create(ARptID: integer; DoOnTerminate: TNotifyEvent); begin inherited create(ARptID, DoOnTerminate); priority := tpLowest; // Tables tblTitm := TTTSTitmTable.create(pSession, dbase, 'TITM'); tblHitm := TTTSHitmTable.create(pSession, dbase, 'HITM'); ScanID := rptOptions.ScanID; // start it up now resume; end; destructor TRemoveNoticeScan.destroy; begin tblTitm.Free; tblHitm.Free; inherited; end; procedure TRemoveNoticeScan.Execute; begin try UpdateStatus(rsScan); tblTitm.Open; tblHitm.Open; ResetCounter(tblTitm.RecordCount); tblTitm.First; // scan through all the tracked items while not tblTitm.Eof do begin ScanOne; try // if it fits the scanid if tblTitm.PNoticeScanID=ScanID then begin // if its no longer in a notice stage if tblTitm.PNoticeNum='' then Continue // do nothing else begin tblTitm.Edit; // we know we are gonna change it // if its in notice stage 1 if tblTitm.PNoticeNum='1' then begin tblTitm.PNoticeNum := ''; // blank out the notice stage tblTitm.PNoticeDate := ''; // and notice date tblTitm.PNoticeScanID := 0; // and Notice Scan ID end; // if its above notice stage 1 if (tblTitm.PNoticeNum<>'1') and (tblTitm.PNoticeNum<>'') then begin if tblHitm.FindKey([tblTitm.PLenderNum,tblTitm.PCifFlag,tblTitm.PLoanCif,tblTitm.PCollNum,tblTitm.PTrackCode,tblTitm.PSubNum]) then begin tblTitm.PNoticeNum := tblHitm.PNoticeNum; tblTitm.PNoticeScanID := tblHitm.PNoticeScanID; tblTitm.PNoticeDate := tblHitm.PNoticeDate; tblHitm.Delete; // remove the last history item end else begin // should I EVER get here? end; end; tblTitm.Post; end; end; finally tblTitm.Next; end; end; finally tblTitm.Close; tblHitm.Close; UpdateStatus(rsDone, 'Done'); end; end; end.
unit FormStarsUnit; interface uses SysUtils, Types, UITypes, Classes, Variants, FMX_Types, FMX_Controls, FMX_Forms, FMX_Dialogs, AllStars; type TForm1 = class(TForm) Timer1: TTimer; procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); procedure FormResize(Sender: TObject); private FApp: TStarsApp; public { Public declarations } end; var Form1: TForm1; implementation {$R *.lfm} procedure TForm1.FormCreate(Sender: TObject); begin FApp := TStarsApp.Create(self.Width, self.Height); end; procedure TForm1.FormDestroy(Sender: TObject); begin FApp.Free; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Invalidate; end; procedure TForm1.FormPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); begin FApp.Update; FApp.Draw(Canvas); end; procedure TForm1.FormResize(Sender: TObject); begin FApp.ResizeView(self.Width, self.Height); end; end.
{ Subroutine SST_R_SYO_JTARGET_SYM (JT, SYM_P) * * Return pointer to descriptor of label corresponding to jump target JT. * A label is implicitly created, if one didn't already exist. } module sst_r_syo_jtarget_sym; define sst_r_syo_jtarget_sym; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_jtarget_sym ( {get or make symbol for jump target label} in out jt: jump_target_t; {descriptor for this jump target} out sym_p: sst_symbol_p_t); {will point to label symbol descriptor} const max_msg_parms = 1; {max parameters we can pass to a message} var jt_p: jump_target_p_t; {pointer to base jump target descriptor} name: string_var32_t; {label name} token: string_var32_t; {scratch token for number conversion} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; begin name.max := sizeof(name.str); {init local var strings} token.max := sizeof(token.str); jt_p := addr(jt); {init base descriptor to first descriptor} while jflag_indir_k in jt_p^.flags do begin {this is an indirect descriptor ?} jt_p := jt_p^.indir_p; {resolve one level of indirection} end; {back to resolve next level of indirection} { * JT_P is pointing to the base jump target descriptor. } if jt_p^.lab_p <> nil then begin {a label symbol already exists here ?} sym_p := jt_p^.lab_p; {fetch label symbol pointer from jump desc} return; end; { * No label symbol exists for this jump target. Create one and pass back * the pointer to it. } string_vstring (name, 'lab', 3); {set static part of label name} string_f_int (token, seq_label); {make sequence number string} seq_label := seq_label + 1; {update sequence number for next time} string_append (name, token); {make full label name} sst_symbol_new_name (name, sym_p, stat); {add symbol to symbol table} sys_error_abort (stat, 'sst_syo_read', 'symbol_label_create', msg_parm, 1); sym_p^.symtype := sst_symtype_label_k; {fill in new label symbol descriptor} sym_p^.label_opc_p := nil; jt_p^.lab_p := sym_p; {save symbol pointer in jump descriptor} end;
PROGRAM isPrime(INPUT, OUTPUT); CONST Max = 100; Min = 2; TYPE SetOfNumbers = SET OF Min..Max; VAR IntSet: SetOfNumbers; I, J, Prime: INTEGER; BEGIN {isPrime} IntSet := [Min..Max]; I := Min; WHILE I * I <= Max DO BEGIN J := I; IF J IN IntSet THEN BEGIN Prime := J; J := J + Prime; WHILE J <= Max DO BEGIN IntSet := IntSet - [J]; J := J + Prime; END; END; I := I + 1; END; J := Min; WRITE(OUTPUT,'Все простые числа до ', Max, ' :{ '); WHILE J <= Max DO BEGIN IF J IN IntSet THEN WRITE(OUTPUT, J, ' '); J := J + 1 END; WRITE(OUTPUT, '}') END. {isPrime}
unit kwCompiledWordContainer; {* Контейнер для зарезервированных слов. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwCompiledWordContainer.pas" // Стереотип: "SimpleClass" // Элемент модели: "TkwCompiledWordContainer" MUID: (4DB6E4630256) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwSourcePointWord , tfwScriptingInterfaces ; type TkwCompiledWordContainer = {abstract} class(TkwSourcePointWord) {* Контейнер для зарезервированных слов. } private f_WordToWork: TtfwWord; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aCompiled: TtfwWord; const aCtx: TtfwContext); reintroduce; public property WordToWork: TtfwWord read f_WordToWork; end;//TkwCompiledWordContainer {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , l3Base //#UC START# *4DB6E4630256impl_uses* //#UC END# *4DB6E4630256impl_uses* ; constructor TkwCompiledWordContainer.Create(aCompiled: TtfwWord; const aCtx: TtfwContext); //#UC START# *4DB6E4AB01B1_4DB6E4630256_var* //#UC END# *4DB6E4AB01B1_4DB6E4630256_var* begin //#UC START# *4DB6E4AB01B1_4DB6E4630256_impl* inherited Create(aCtx); aCompiled.SetRefTo(f_WordToWork); //#UC END# *4DB6E4AB01B1_4DB6E4630256_impl* end;//TkwCompiledWordContainer.Create procedure TkwCompiledWordContainer.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4DB6E4630256_var* //#UC END# *479731C50290_4DB6E4630256_var* begin //#UC START# *479731C50290_4DB6E4630256_impl* FreeAndNil(f_WordToWork); inherited; //#UC END# *479731C50290_4DB6E4630256_impl* end;//TkwCompiledWordContainer.Cleanup initialization TkwCompiledWordContainer.RegisterClass; {* Регистрация TkwCompiledWordContainer } {$IfEnd} // NOT Defined(NoScripts) end.
//Exercicio : { Solução em Portugol Algoritmo Exercicio 62; Var capital_inicial, juros: real; mes, contador: inteiro; Inicio exiba("Programa que calcula quanto de dinheiro uma aplicação rende."); exiba("Digite o seu capital inicial: "); leia(capital_inicial); enquanto(capital_inicial <= 0)faça exiba("Digite um capital inicial maior que 0."); leia(capital_inicial); fimenquanto; exiba("Digite o tempo, em meses, da aplicação: "); leia(mes); enquanto(mes <= 0)faça exiba("Digite um tempo maior que 0."); leia(mes); fimenquanto; exiba("Digite a taxa de juros da aplicação: "); leia(juros); enquanto(juros <= 0)faça exiba("Digite uma taxa de juros válida."); leia(juros); fimenquanto; para contador <- 1 até mes faça exiba("No ",mes,"º mês o valor foi de", (capital_inicial * (1 + juros/100) ^ mes)," reais."); fimpara; Fim. } // Solução em Pascal Program Exercicio; uses crt; Var mes, contador: integer; capital_inicial, juros: real; begin clrscr; writeln('Programa que calcula quanto de dinheiro uma aplicação rende.'); writeln('Digite o seu capital inicial: '); readln(capital_inicial); while(capital_inicial <= 0)do Begin writeln('Digite um capital inicial maior que 0.'); readln(capital_inicial); End; writeln('Digite o tempo, em meses, da aplicação: '); readln(mes); while(mes <= 0)do Begin writeln('Digite um tempo maior que 0.'); readln(mes); End; writeln('Digite a taxa de juros da aplicação: '); readln(juros); while(juros <= 0)do Begin writeln('Digite uma taxa de juros válida.'); readln(juros); End; for contador := 1 to mes do writeln('No ',contador,'º mês o valor foi de ', (capital_inicial * (exp(mes*ln(juros/100 + 1)))):0:2,' reais.'); repeat until keypressed; end.
unit LogonHandler; interface uses VoyagerInterfaces, Classes, Controls, MPlayer, LogonHandlerViewer; type TLogonHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler ) public constructor Create; destructor Destroy; override; private fControl : TLogonHandlerView; // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; fStarted : boolean; end; const tidMetaHandler_LogonHandler = 'LogonHandler'; implementation uses URLParser, SysUtils, Events, Forms; // TLogonHandler constructor TLogonHandler.Create; begin inherited Create; fControl := TLogonHandlerView.Create( nil ); end; destructor TLogonHandler.Destroy; begin fControl.Free; inherited; end; function TLogonHandler.getName : string; begin result := tidMetaHandler_LogonHandler; end; function TLogonHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TLogonHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TLogonHandler.Instantiate : IURLHandler; begin result := self; end; function TLogonHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlHandled; end; function TLogonHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; begin result := evnHandled; case EventId of evnHandlerExposed : if not fStarted then begin fControl.Start; fStarted := true; end; end; end; function TLogonHandler.getControl : TControl; begin result := fControl; end; procedure TLogonHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); var cache : string; begin fMasterURLHandler := URLHandler; fControl.MasterURLHandler := URLHandler; URLHandler.HandleEvent( evnAnswerPrivateCache, cache ); fControl.Cache := cache; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** } { Implements generic collection classes (lists and iterators) } Unit TERRA_Collections; {$I terra.inc} {-$DEFINE DEBUG} Interface Uses TERRA_String, TERRA_Utils {$IFNDEF DISABLETHREADS}, TERRA_Mutex{$ENDIF}; Function GetStringSort(Const A,B:TERRAString):Integer; Const { Checks that the collection contains no duplicate values } coNoDuplicates = 2; { Insert fails if object already added } coCheckReferencesOnAdd = 4; coCheckReferencesOnDelete = 8; { The collection will be thread-safe, meaning adds, deletes and iterators will be protected by a critical section. } coThreadSafe = 32; Type Collection = Class; CollectionSortOrder = ( { The collection is unsorted. Add() does a very fast insertion without sorting.} collection_Unsorted, { The collection is sorted} collection_Sorted_Ascending, { The collection is reversed sorted} collection_Sorted_Descending ); // must implement at least copy value and sort CollectionObject = Class(TERRAObject) Protected _Collection:Collection; _Next:CollectionObject; _Discarded:Boolean; Function IsCompatible(Other:CollectionObject):Boolean; Procedure Internal_Copy(Other:CollectionObject); Function Internal_Sort(Other:CollectionObject):Integer; Public { Release this object } Procedure Release(); Override; { Mark this object for release. It will be auto-released as soon as possible.} Procedure Discard(); { Links this object to a specific collection. Internal use. } Procedure Link(Col:Collection); { Clones this object. } Procedure CopyValue(Other:CollectionObject); Virtual; Function ToString():TERRAString; {$IFDEF FPC}Reintroduce;{$ENDIF} Virtual; { Compares this object with a similar object. If not implemented, no sorting will happen. } Function Sort(Other:CollectionObject):Integer; Virtual; Property Collection:Collection Read _Collection; Property Next:CollectionObject Read _Next Write _Next; // FIXME should not have write acess Property Discarded:Boolean Read _Discarded; End; Iterator = Class(TERRAObject) Private _Value:CollectionObject; _Index:Integer; _Collection:Collection; _Finished:Boolean; {$IFNDEF DISABLEALLOCOPTIMIZATIONS} Class Function NewInstance:TObject; Override; Procedure FreeInstance; Override; {$ENDIF} Protected Function ObtainNext():CollectionObject; Virtual; Abstract; Procedure Reset(); Virtual; Procedure JumpToIndex(Position: Integer); Virtual; Procedure Release(); Override; Function GetPosition():Integer; Property Index:Integer Read _Index; Public Constructor Create(Col:Collection); Function HasNext():Boolean; Function Seek(Position:Integer):Boolean; Property Value:CollectionObject Read _Value; Property Position:Integer Read GetPosition; Property Collection:TERRA_Collections.Collection Read _Collection; End; CollectionVisitor = Function(Item:CollectionObject; UserData:Pointer):Boolean; CDecl; Collection = Class(TERRAObject) Protected _ItemCount:Integer; _Options:Cardinal; _SortOrder:CollectionSortOrder; _Share:Collection; {$IFNDEF DISABLETHREADS} _Mutex:CriticalSection; {$ENDIF} _HasDiscards:Boolean; Procedure Init(Options:Integer; Share:Collection); Procedure Update(); Procedure RemoveDiscardedItems(); Virtual; Public Procedure Release(); Override; Function GetIterator:Iterator; Virtual; // removes all items Procedure Clear(); Virtual; Procedure Lock; Procedure Unlock; Function Search(Visitor:CollectionVisitor; UserData:Pointer = Nil):CollectionObject; Virtual; Procedure Visit(Visitor:CollectionVisitor; UserData:Pointer = Nil); Virtual; // Should return True if Item contains Key Function ContainsReference(Item:CollectionObject):Boolean; Virtual; Function ContainsDuplicate(Item:CollectionObject):Boolean; Virtual; Function GetItemByIndex(Index:Integer):CollectionObject; Virtual; // Function FindByValue(Const Value:TERRAString):CollectionObject; Virtual; Property Objects[Index: Integer]:CollectionObject Read GetItemByIndex; Default; Property Count:Integer Read _ItemCount; Property Options:Cardinal Read _Options; Property SortOrder:CollectionSortOrder Read _SortOrder; End; List = Class(Collection) Protected _First:CollectionObject; _Last:CollectionObject; Procedure RemoveDiscardedItems(); Override; Public Constructor Create(SortOrder:CollectionSortOrder = collection_Unsorted; Options:Integer = 0); Procedure Clear(); Override; Function GetIterator:Iterator; Override; Function GetItemByIndex(Index:Integer):CollectionObject; Override; // adds copies of items, not references! Function Merge(C:Collection):List; // Returns true if insertion was sucessful Function Add(Item:CollectionObject):Boolean;Virtual; // Returns true if deletion was sucessful Function Delete(Item:CollectionObject):Boolean; Virtual; Function ContainsReference(Item:CollectionObject):Boolean; Override; Function Search(Visitor:CollectionVisitor; UserData:Pointer = Nil):CollectionObject; Override; Procedure Visit(Visitor:CollectionVisitor; UserData:Pointer = Nil); Override; Property First:CollectionObject Read _First; End; ListIterator = Class(Iterator) Protected _Current:CollectionObject; Function ObtainNext:CollectionObject; Override; Procedure Reset(); Override; Public End; IntegerArrayObject = Object Items:Array Of Integer; Count:Integer; Procedure Clear; Procedure Replace(A,B:Integer); Function Contains(N:Integer):Boolean; Procedure Add(N:Integer; AllowDuplicates:Boolean = False); Procedure Remove(N:Integer); Procedure Merge(A:IntegerArrayObject); Function Pop:Integer; End; Implementation Uses TERRA_Error, TERRA_Log, TERRA_OS, TERRA_FileStream, TERRA_Stream {$IFNDEF DISABLEALLOCOPTIMIZATIONS}, TERRA_StackObject{$ENDIF}; {$IFDEF DEBUG_ITERATORS} Var _Iterator_Count:Integer; {$ENDIF} Function GetStringSort(Const A,B:TERRAString):Integer; Begin If (A<B) Then Result := 1 Else If (A>B) Then Result := -1 Else Result := 0; End; { Collection } Procedure Collection.Release(); Begin Self.Clear(); {$IFNDEF DISABLETHREADS} ReleaseObject(_Mutex); {$ENDIF} End; Procedure Collection.Lock(); Begin {$IFNDEF DISABLETHREADS} If Assigned(_Share) Then Begin _Share.Lock(); End Else If Assigned(_Mutex) Then Begin _Mutex.Lock(); End; {$ENDIF} End; Procedure Collection.Unlock(); Begin {$IFNDEF DISABLETHREADS} If Assigned(_Share) Then Begin _Share.Unlock(); End Else If Assigned(_Mutex) Then _Mutex.Unlock(); {$ENDIF} End; Procedure Collection.Init(Options:Integer; Share:Collection); Begin {$IFNDEF DISABLETHREADS} If (Assigned(Share)) Then Begin _Share := Share; _Mutex := Nil; End Else Begin _Share := Nil; If (Options And coThreadSafe<>0) Then _Mutex := CriticalSection.Create({Self.ClassName +CardinalToString(GetTime())}) Else _Mutex := Nil; End; {$ENDIF} _Options := Options; End; Function Collection.Search(Visitor: CollectionVisitor; UserData:Pointer = Nil): CollectionObject; Var It:Iterator; P:CollectionObject; Begin Result := Nil; It := Self.GetIterator(); While (It.HasNext()) Do Begin P := It.Value; If (Visitor(P, UserData)) Then Begin Result := P; Break; End; End; ReleaseObject(It); End; Procedure Collection.Visit(Visitor: CollectionVisitor; UserData:Pointer = Nil); Var It:Iterator; Begin It := Self.GetIterator(); While (It.HasNext()) Do Begin Visitor(It.Value, UserData); End; End; Function Collection.ContainsReference(Item:CollectionObject):Boolean; Var P:CollectionObject; It:Iterator; Begin Result := False; It := Self.GetIterator(); While (It.HasNext()) Do Begin If (It.Value = Item) Then Begin Result := True; Break; End; End; ReleaseObject(It); End; Function Collection.ContainsDuplicate(Item:CollectionObject):Boolean; Var P:CollectionObject; It:Iterator; Begin Result := False; It := Self.GetIterator(); While (It.HasNext()) Do Begin If (StringEquals(It.Value.ToString(), Item.ToString())) Then Begin Result := True; Break; End; End; ReleaseObject(It); End; {Function Collection.FindByValue(Const Value:TERRAString): CollectionObject; Var It:Iterator; P:CollectionObject; Begin Result := Nil; It := Self.GetIterator(); While It.HasNext() Do Begin P := It.GetNext(); If StringEquals(P.ToString(), Value) Then Begin Result := P; Break; End; End; ReleaseObject(It); End;} Procedure Collection.RemoveDiscardedItems; Begin // dummy End; Procedure Collection.Update; Begin If Not _HasDiscards Then Exit; _HasDiscards := False; Self.RemoveDiscardedItems(); End; Procedure IntegerArrayObject.Clear; Begin Count := 0; SetLength(Items, 0); End; Function IntegerArrayObject.Contains(N:Integer):Boolean; Var I:Integer; Begin Result := True; For I:=0 To Pred(Count) Do If (Items[I]=N) Then Exit; Result := False; End; Procedure IntegerArrayObject.Replace(A,B:Integer); Var I:Integer; Begin For I:=0 To Pred(Count) Do If (Items[I]=A) Then Items[I] := B; End; Procedure IntegerArrayObject.Add(N:Integer; AllowDuplicates:Boolean = False); Begin If (Not AllowDuplicates) And (Contains(N)) Then Exit; Inc(Count); SetLength(Items, Count); Items[Pred(Count)] := N; End; Procedure IntegerArrayObject.Remove(N:Integer); Var I:Integer; Begin For I:=0 To Pred(Count) Do If (Items[I]=N) Then Begin Items[I] := Items[Pred(Count)]; Dec(Count); SetLength(Items, Count); Exit; End; End; Procedure IntegerArrayObject.Merge(A:IntegerArrayObject); Var I:Integer; Begin For I:=0 To Pred(A.Count) Do Self.Add(A.Items[I]); End; Function IntegerArrayObject.Pop:Integer; Begin Result := Items[0]; Items[0] := Items[Pred(Count)]; Dec(Count); SetLength(Items, Count); End; Function Collection.GetItemByIndex(Index: Integer): CollectionObject; Var It:Iterator; Begin It := Self.GetIterator(); It.Seek(Index); Result := It.Value; ReleaseObject(It); End; Function Collection.GetIterator: Iterator; Begin Result := Nil; End; Procedure Collection.Clear; Var It:Iterator; Begin It := Self.GetIterator(); While It.HasNext() Do Begin It.Value.Discard(); End; ReleaseObject(It); End; { Iterator } Constructor Iterator.Create(Col: Collection); Begin _Collection := Col; If Assigned(_Collection) Then Begin _Collection.Lock(); _Collection.Update(); End; {$IFDEF DEBUG_ITERATORS} Inc(_Iterator_Count); If (_Iterator_Count>100) Then Begin DebugBreak; End; {$ENDIF} Self.Seek(0); End; {$IFNDEF DISABLEALLOCOPTIMIZATIONS} Class Function Iterator.NewInstance: TObject; Var ObjSize, GlobalSize:Integer; Begin ObjSize := InstanceSize(); Result := StackAlloc(ObjSize); InitInstance(Result); End; Procedure Iterator.FreeInstance; Begin End; {$ENDIF} Procedure Iterator.Reset(); Begin // do nothing End; Procedure Iterator.Release(); Begin If _Finished Then Exit; _Finished := True; {$IFDEF DEBUG_ITERATORS} Dec(_Iterator_Count); {$ENDIF} If Assigned(_Collection) Then Begin _Collection.Update(); _Collection.Unlock(); End; End; Function Iterator.HasNext: Boolean; Begin _Value := Self.ObtainNext(); Result := Assigned(_Value); If (Result) Then Inc(_Index) Else If (Not _Finished) Then Self.Release(); End; Function Iterator.GetPosition():Integer; Begin Result := Pred(_Index); End; Function Iterator.Seek(Position: Integer):Boolean; Begin _Finished := False; _Value := Nil; _Index := 0; Self.Reset(); If Position>0 Then Begin JumpToIndex(Position); _Index := Position; End; If Assigned(_Collection) Then Result := (Position<Self._Collection.Count) Else Result := True; End; Procedure Iterator.JumpToIndex(Position: Integer); Begin While (Self.Index<Position) Do Begin If Not Self.HasNext() Then Exit; End; End; { CollectionObject } Procedure CollectionObject.CopyValue(Other: CollectionObject); Begin // do nothing End; Procedure CollectionObject.Release(); Begin // do nothing End; Procedure CollectionObject.Internal_Copy(Other: CollectionObject); Begin If (IsCompatible(Other)) Then Self.CopyValue(Other); End; Function CollectionObject.Internal_Sort(Other: CollectionObject): Integer; Begin If (IsCompatible(Other)) Then Result := Self.Sort(Other) Else Result := 0; End; Function CollectionObject.IsCompatible(Other: CollectionObject): Boolean; Begin Result := (Self Is Other.ClassType); If Not Result Then RaiseError('Cannot copy list objects, '+Self.ClassName +' and '+ Other.ClassName+' are not compatible!'); End; Function CollectionObject.Sort(Other: CollectionObject): Integer; Begin If (Other<>Nil) Then Result := 0 Else Result := 1; End; Function CollectionObject.ToString:TERRAString; Begin Result := Self.ClassName+'@'+HexStr(Cardinal(Self)); End; Procedure CollectionObject.Discard(); Begin Self._Discarded := True; If Assigned(Self._Collection) Then Self._Collection._HasDiscards := True Else DebugBreak; End; Procedure CollectionObject.Link(Col: Collection); Begin _Collection := Col; End; { List } Constructor List.Create(SortOrder:CollectionSortOrder; Options:Integer); Begin _SortOrder := SortOrder; _First := Nil; _ItemCount := 0; Self.Init(Options, Nil); End; Procedure List.RemoveDiscardedItems(); Var P, Prev:CollectionObject; Begin Prev := Nil; P := _First; While (Assigned(P)) Do Begin If P._Discarded Then Begin If Assigned(Prev) Then Begin Prev._Next := P.Next; ReleaseObject(P); Dec(_ItemCount); P := Prev.Next; End Else Begin _First := P.Next; ReleaseObject(P); P := _First; End; End Else Begin Prev := P; P := P.Next; End; End; End; Function List.GetItemByIndex(Index:Integer):CollectionObject; Var I:Integer; Begin If (Index<0) Or (Index>=Self.Count) Then Begin Result := Nil; Exit; End; If (Index=0) Then Begin Result := _First; Exit; End; Self.Lock(); Result := Self._First; I := 0; While (Result<>Nil) Do Begin Result := Result.Next; Inc(I); If (I = Index) Then Break; End; Self.Unlock(); End; Function List.Merge(C:Collection):List; Var I:Iterator; Temp, N:CollectionObject; Begin Result := Self; If (C = Self) Then Exit; Self.Update(); I := C.GetIterator(); While I.HasNext Do Begin Temp := I.Value; N := CollectionObject(Temp.ClassType.Create()); N.CopyValue(Temp); Self.Add(N); End; ReleaseObject(C); End; Function List.Search(Visitor: CollectionVisitor; UserData:Pointer = Nil): CollectionObject; Var P:CollectionObject; Begin Result := Nil; Self.Lock(); P := _First; While (Assigned(P)) Do Begin If (Visitor(P, UserData)) Then Begin Result := P; Break; End; P := P.Next; End; Self.Unlock(); End; Procedure List.Visit(Visitor: CollectionVisitor; UserData:Pointer = Nil); Var P:CollectionObject; Begin Self.Lock(); P := _First; While (Assigned(P)) Do Begin Visitor(P, UserData); P := P.Next; End; Self.Unlock(); End; Procedure List.Clear(); Var List,Next:CollectionObject; Begin Self.Lock(); List := _First; While Assigned(List)Do Begin Next := List.Next; ReleaseObject(List); List := Next; End; _First := Nil; _ItemCount := 0; Self.Unlock(); End; Function List.Add(Item:CollectionObject):Boolean; Var N:Integer; P, Prev:CollectionObject; Inserted:Boolean; Begin Result := False; If (Item = Nil) Or ((Options And coCheckReferencesOnAdd<>0) And (Self.ContainsReference(Item))) Then Begin Log(logWarning, Self.ClassName, 'Reference already inside collection: '+Item.ToString()); Exit; End; If ((Options And coNoDuplicates<>0) And (Self.ContainsDuplicate(Item))) Then Begin Log(logWarning, Self.ClassName, 'Item duplicated in collection: '+Item.ToString()); Exit; End; If (Item.Collection<>Nil) Then Begin Log(logWarning, Self.ClassName, 'Item already belongs to a collection: '+Item.ToString()); Exit; End; Result := True; Item._Collection := Self; Self.Update(); Self.Lock(); If Assigned(_First) Then Begin If (_SortOrder = collection_Unsorted) Then Begin _Last._Next := Item; Item._Next := Nil; _Last := Item; End Else {If (_SortOrder = collection_Unsorted) Then Begin P := _First; _First := Item; Item._Next := P; End Else} Begin Inserted := False; P := _First; Prev := Nil; While Assigned(P) Do Begin N := P.Sort(Item); If ((_SortOrder = collection_Sorted_Ascending) And (N>=0)) Or ((_SortOrder = collection_Sorted_Descending) And (N<=0)) Then Begin If Assigned(Prev) Then Begin Prev._Next := Item; Item._Next := P; End Else Begin _First := Item; Item._Next := P; End; Inserted := True; Break; End; Prev := P; P := P.Next; End; If Not Inserted Then Begin Prev._Next := Item; Item._Next := Nil; End; End; End Else Begin _First := Item; _Last := _First; Item._Next := Nil; End; Inc(_ItemCount); Self.Unlock(); {P := _First; PRev := Nil; While P<>Nil Do Begin S := S + P.ToString() + ','; Prev := P; P := P.Next; End; IF (Prev<>_Last) Then Begin S := Item.ToString(); IntToSTring(2+Length(S)); End;} End; Function List.Delete(Item:CollectionObject):Boolean; Var List,Prev, Next:CollectionObject; Begin Result := False; Self.Lock(); List := _First; Prev := Nil; {$IFDEF DEBUG}Log(logDebug, 'List', 'Testing deletion...');{$ENDIF} While Assigned(List) Do Begin {$IFDEF DEBUG}Log(logDebug, 'List', 'Testing key contains '+HexStr(Cardinal(List)));{$ENDIF} If List = Item Then Begin {$IFDEF DEBUG}Log(logDebug, 'List', 'Match found!');{$ENDIF} Next := Item.Next; ReleaseObject(Item); {$IFDEF DEBUG}Log(logDebug, 'List', 'Discarded item!');{$ENDIF} If Assigned(Prev) Then Prev._Next := Next Else _First := Next; Dec(_ItemCount); Result := True; Break; End; Prev := List; List := List.Next; End; Self.Unlock(); End; Function List.ContainsReference(Item:CollectionObject):Boolean; Var P:CollectionObject; Begin Result := False; Self.Lock(); P := _First; While (P<>Nil) Do Begin If (P = Item) Then Begin Result := True; Break; End; P := P.Next; End; Self.Unlock(); End; Function List.GetIterator:Iterator; Begin Result := ListIterator.Create(Self); End; Procedure ListIterator.Reset; Begin Inherited; _Current := List(_Collection)._First; End; Function ListIterator.ObtainNext:CollectionObject; Begin If Assigned(_Current) Then Begin Result := _Current; _Current := _Current.Next; End Else Result := Nil; End; End.
unit CloneOptions; interface const // Block [0-7] cloneOption_SameTown = $00000001; cloneOption_SameCompany = $00000002; cloneOption_Suppliers = $00000004; cloneOption_Clients = $00000008; // Work Center [8-15] cloneOption_Salaries = $00000100; // Eval Blocks [16-23] cloneOption_OutputPrices = $00010000; // Office & Residentials cloneOption_Rent = $00010000; cloneOption_Maint = $00020000; // Stores cloneOption_SrvPrices = $00010000; cloneOption_Ads = $00020000; implementation end.
unit App; { Based on Stencil_Test.c from Book: OpenGL(R) ES 2.0 Programming Guide Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner ISBN-10: 0321502795 ISBN-13: 9780321502797 Publisher: Addison-Wesley Professional URLs: http://safari.informit.com/9780321563835 http://www.opengles-book.com } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App; type TStencilOpApp = class(TApplication) private FProgram: TGLProgram; FAttrPosition: TGLVertexAttrib; FUniColor: TGLUniform; public function NeedStencilBuffer: Boolean; override; procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes; { TStencilOpApp } procedure TStencilOpApp.Initialize; var VertexShader, FragmentShader: TGLShader; begin { Compile vertex and fragment shaders } VertexShader.New(TGLShaderType.Vertex, 'attribute vec4 a_position;'#10+ 'void main()'#10+ '{'#10+ ' gl_Position = a_position;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'uniform vec4 u_color;'#10+ 'void main()'#10+ '{'#10+ ' gl_FragColor = u_color;'#10+ '}'); FragmentShader.Compile; { Link shaders into program } FProgram.New(VertexShader, FragmentShader); FProgram.Link; { We don't need the shaders anymore. Note that the shaders won't actually be deleted until the program is deleted. } VertexShader.Delete; FragmentShader.Delete; { Initialize vertex attribute } FAttrPosition.Init(FProgram, 'a_position'); { Initialize uniform } FUniColor.Init(FProgram, 'u_color'); { Set clear color to black } gl.ClearColor(0, 0, 0, 0); { Set the stencil clear value } gl.ClearStencil($01); { Set the depth clear value } gl.ClearDepth(0.75); { Enable the depth and stencil tests } gl.Enable(TGLCapability.DepthTest); gl.Enable(TGLCapability.StencilTest); end; procedure TStencilOpApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; function TStencilOpApp.NeedStencilBuffer: Boolean; begin Result := True; end; procedure TStencilOpApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); const VERTICES: array [0..5 * 4 - 1] of TVector3 = ( // Quad #0 (X: -0.75; Y: 0.25; Z: 0.50), (X: -0.25; Y: 0.25; Z: 0.50), (X: -0.25; Y: 0.75; Z: 0.50), (X: -0.75; Y: 0.75; Z: 0.50), // Quad #1 (X: 0.25; Y: 0.25; Z: 0.90), (X: 0.75; Y: 0.25; Z: 0.90), (X: 0.75; Y: 0.75; Z: 0.90), (X: 0.25; Y: 0.75; Z: 0.90), // Quad #2 (X: -0.75; Y: -0.75; Z: 0.50), (X: -0.25; Y: -0.75; Z: 0.50), (X: -0.25; Y: -0.25; Z: 0.50), (X: -0.75; Y: -0.25; Z: 0.50), // Quad #3 (X: 0.25; Y: -0.75; Z: 0.50), (X: 0.75; Y: -0.75; Z: 0.50), (X: 0.75; Y: -0.25; Z: 0.50), (X: 0.25; Y: -0.25; Z: 0.50), // Big Quad (X: -1.00; Y: -1.00; Z: 0.00), (X: 1.00; Y: -1.00; Z: 0.00), (X: 1.00; Y: 1.00; Z: 0.00), (X: -1.00; Y: 1.00; Z: 0.00)); const INDICES0: array [0..5] of UInt8 = ( 0, 1, 2, 0, 2, 3); // Quad #0 INDICES1: array [0..5] of UInt8 = ( 4, 5, 6, 4, 6, 7); // Quad #1 INDICES2: array [0..5] of UInt8 = ( 8, 9, 10, 8, 10, 11); // Quad #2 INDICES3: array [0..5] of UInt8 = (12, 13, 14, 12, 14, 15); // Quad #3 INDICES4: array [0..5] of UInt8 = (16, 17, 18, 16, 18, 19); // Big Quad const TEST_COUNT = 4; const COLORS: array [0..TEST_COUNT - 1] of TVector4 = ( (R: 1; G: 0; B: 0; A: 1), (R: 0; G: 1; B: 0; A: 1), (R: 0; G: 0; B: 1; A: 1), (R: 1; G: 1; B: 0; A: 0)); var StencilValues: array [0..TEST_COUNT - 1] of Byte; I: Integer; begin StencilValues[0] := $07; // Result of test 0 StencilValues[1] := $00; // Result of test 1 StencilValues[2] := $02; // Result of test 2 { Clear the color, depth, and stencil buffers. At this point, the stencil buffer will be $01 for all pixels. } gl.Clear([TGLClear.Color, TGLClear.Depth, TGLClear.Stencil]); { Use the program } FProgram.Use; { Set the data for the vertex attribute } FAttrPosition.SetData(VERTICES); FAttrPosition.Enable; { Test 0: Initialize upper-left region. In this case, the stencil-buffer values will be replaced because the stencil test for the rendered pixels will fail the stencil test, which is: ref mask stencil mask ($07 and $03) < ($01 and $07 ) The value in the stencil buffer for these pixels will be $07. } gl.StencilFunc(TGLCompareFunc.Less, $07, $03); gl.StencilOp(TGLStencilOp.Replace, TGLStencilOp.Decrement, TGLStencilOp.Decrement); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES0); { Test 1: Initialize upper-right region. Here, we'll decrement the stencil-buffer values where the stencil test passes but the depth test fails. The stencil test is: ref mask stencil mask ($03 and $03) > ($01 and $03 ) But where the geometry fails the depth test. The stencil values for these pixels will be $00. } gl.StencilFunc(TGLCompareFunc.Greater, $03, $03); gl.StencilOp(TGLStencilOp.Keep, TGLStencilOp.Decrement, TGLStencilOp.Keep); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES1); { Test 2: Initialize the lower-left region. Here we'll increment (with saturation) the stencil value where both the stencil and depth tests pass. The stencil test for these pixels will be: ref mask stencil mask ($01 and $03) = ($01 and $03 ) The stencil values for these pixels will be $02. } gl.StencilFunc(TGLCompareFunc.Equal, $01, $03); gl.StencilOp(TGLStencilOp.Keep, TGLStencilOp.Increment, TGLStencilOp.Increment); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES2); { Test 3: Finally, initialize the lower-right region. We'll invert the stencil value where the stencil tests fails. The stencil test for these pixels will be: ref mask stencil mask ($02 and $01) = ($01 and $01 ) The stencil value here will be set to (not ((2^s-1) and $01)), (with the $01 being from the stencil clear value), where 's' is the number of bits in the stencil buffer } gl.StencilFunc(TGLCompareFunc.Equal, $02, $01); gl.StencilOp(TGLStencilOp.Invert, TGLStencilOp.Keep, TGLStencilOp.Keep); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES3); { Since we don't know at compile time how many stencil bits are present, we'll query, and update the value correct value in the StencilValues arrays for the fourth tests. We'll use this value later in rendering. } StencilValues[3] := (not (((1 shl TGLFramebuffer.GetCurrent.GetStencilBits) - 1) and $01)) and $FF; { Use the stencil buffer for controlling where rendering will occur. We disable writing to the stencil buffer so we can test against them without modifying the values we generated. } gl.StencilMask($00); for I := 0 to TEST_COUNT - 1 do begin gl.StencilFunc(TGLCompareFunc.Equal, StencilValues[I], $FF); FUniColor.SetValue(COLORS[I]); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES4); end; { Reset the stencil mask } gl.StencilMask($FF); end; procedure TStencilOpApp.Shutdown; begin { Release resources } FProgram.Delete; end; end.
{ Copyright (C) 2013-2021 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit ts.RichEditor.View.KMemo; {$MODE DELPHI} { A richtext editor view based on KMemo } { TODO: - paste formatted text (HTML?) - copy formatted text (WIKI, HTML?) - Undo/Redo is not yet supported by the KMemo component - drag and drop images in editor view } interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ActnList, ExtCtrls, Menus, Types, KControls, KMemo, KMemoDlgTextStyle, KMemoDlgHyperlink, KMemoDlgImage, KMemoDlgNumbering, KMemoDlgContainer, KMemoDlgParaStyle, DropComboTarget, DropTarget, ts.RichEditor.Interfaces; type { TRichEditorViewKMemo } TRichEditorViewKMemo = class(TForm, IRichEditorView) dctMain : TDropComboTarget; pnlRichEditor : TPanel; procedure dctMainDrop( Sender : TObject; ShiftState : TShiftState; APoint : TPoint; var Effect : Longint ); procedure FormDropFiles( Sender : TObject; const FileNames : array of string ); private FEditor : TKMemo; FTextStyle : TKMemoTextStyle; FParaStyle : TKMemoParaStyle; FUpdateLock : Integer; FDefaultIndent : Integer; FOnChange : TNotifyEvent; FOnDropFiles : TDropFilesEvent; FParaStyleForm : TKMemoParaStyleForm; FTextStyleForm : TKMemoTextStyleForm; FContainerForm : TKMemoContainerForm; FHyperlinkForm : TKMemoHyperlinkForm; FNumberingForm : TKMemoNumberingForm; FImageForm : TKMemoImageForm; FFileName : string; FIsFile : Boolean; {$REGION 'event handlers'} procedure FEditorChange(Sender: TObject); procedure FEditorBlockClick( Sender : TObject; ABlock : TKMemoBlock; var Result : Boolean ); procedure FEditorBlockEdit( Sender : TObject; ABlock : TKMemoBlock; var Result : Boolean ); procedure FParaStyleChanged(Sender: TObject; AReasons: TKMemoUpdateReasons); procedure FTextStyleChanged(Sender: TObject); {$ENDREGION} function SelectedBlock: TKMemoBlock; function EditContainer(AItem: TKMemoBlock): Boolean; virtual; protected {$REGION 'property access mehods'} function GetActions: IRichEditorActions; function GetAlignCenter: Boolean; function GetAlignJustify: Boolean; function GetAlignLeft: Boolean; function GetAlignRight: Boolean; function GetCanPaste: Boolean; function GetCanRedo: Boolean; function GetCanUndo: Boolean; function GetContentSize: Int64; function GetEditor: TComponent; function GetEvents: IRichEditorEvents; function GetFileName: string; function GetFont: TFont; function GetForm: TCustomForm; function GetIsEmpty: Boolean; function GetIsFile: Boolean; function GetModified: Boolean; function GetOnChange: TNotifyEvent; function GetOnDropFiles: TDropFilesEvent; function GetPopupMenu: TPopupMenu; override; function GetRTFText: string; function GetSelAvail: Boolean; function GetSelEnd: Integer; function GetSelStart: Integer; function GetSelText: string; function GetShowSpecialChars: Boolean; function GetText: string; function GetWordWrap: Boolean; procedure SetAlignCenter(AValue: Boolean); procedure SetAlignJustify(AValue: Boolean); procedure SetAlignLeft(AValue: Boolean); procedure SetAlignRight(AValue: Boolean); procedure SetFileName(const AValue: string); procedure SetIsFile(AValue: Boolean); procedure SetModified(const AValue: Boolean); procedure SetOnChange(const AValue: TNotifyEvent); procedure SetOnDropFiles(const AValue: TDropFilesEvent); procedure SetPopupMenu(const AValue: TPopupMenu); reintroduce; procedure SetSelEnd(const AValue: Integer); procedure SetSelStart(const AValue: Integer); procedure SetSelText(const AValue: string); procedure SetShowSpecialChars(AValue: Boolean); procedure SetText(const AValue: string); procedure SetWordWrap(const AValue: Boolean); {$ENDREGION} procedure SelectAll; procedure LoadFromFile(const AFileName: string); procedure Load(const AStorageName: string = ''); procedure LoadFromStream(AStream: TStream); procedure Save(const AStorageName: string = ''); procedure SaveToStream(AStream: TStream); procedure SaveToFile(const AFileName: string); procedure BeginUpdate; function IsUpdating: Boolean; procedure EndUpdate; procedure InsertImageFile(const AFileName: string); procedure InsertImage(AImage: TPicture); overload; function InsertImage: Boolean; overload; procedure InsertHyperlink( const AText : string = ''; const AURL : string = '' ); procedure InsertBulletList; procedure InsertTextBox; procedure IncIndent; procedure DecIndent; procedure AdjustParagraphStyle; procedure Clear; // clipboard commands procedure Cut; procedure Copy; procedure Paste; procedure Undo; procedure Redo; // event dispatch methods procedure DoDropFiles(const AFileNames: array of string); procedure DoChange; public procedure AfterConstruction; override; destructor Destroy; override; procedure UpdateActions; override; function Focused: Boolean; override; property Actions: IRichEditorActions read GetActions; property CanPaste: Boolean read GetCanPaste; property CanUndo: Boolean read GetCanUndo; property CanRedo: Boolean read GetCanRedo; property ContentSize: Int64 read GetContentSize; property Events: IRichEditorEvents read GetEvents; property Editor: TComponent read GetEditor; property FileName: string read GetFileName write SetFileName; property Font: TFont read GetFont; property SelStart: Integer read GetSelStart write SetSelStart; property SelEnd: Integer read GetSelEnd write SetSelEnd; property SelAvail: Boolean read GetSelAvail; property SelText: string read GetSelText write SetSelText; property AlignLeft: Boolean read GetAlignLeft write SetAlignLeft; property AlignRight: Boolean read GetAlignRight write SetAlignRight; property AlignCenter: Boolean read GetAlignCenter write SetAlignCenter; property AlignJustify: Boolean read GetAlignJustify write SetAlignJustify; property Modified: Boolean read GetModified write SetModified; property PopupMenu: TPopupMenu read GetPopupMenu write SetPopupMenu; property Form: TCustomForm read GetForm; property IsEmpty: Boolean read GetIsEmpty; property IsFile: Boolean read GetIsFile write SetIsFile; property Text: string read GetText write SetText; property RTFText: string read GetRTFText; property ShowSpecialChars: Boolean read GetShowSpecialChars write SetShowSpecialChars; property WordWrap: Boolean read GetWordWrap write SetWordWrap; property OnDropFiles: TDropFilesEvent read GetOnDropFiles write SetOnDropFiles; property OnChange: TNotifyEvent read GetOnChange write SetOnChange; end; implementation {$R *.lfm} uses StdCtrls, Math, StrUtils, keditcommon, kgraphics, ts.Core.Logger; {$REGION 'construction and destruction'} procedure TRichEditorViewKMemo.AfterConstruction; begin Logger.Enter(Self, 'AfterConstruction'); inherited AfterConstruction; FEditor := TKMemo.Create(Self); FEditor.Parent := pnlRichEditor; FEditor.BorderStyle := bsNone; FEditor.ScrollBars := ssBoth; FEditor.Align := alClient; FEditor.DoubleBuffered := True; FEditor.OnChange := FEditorChange; FEditor.OnBlockEdit := FEditorBlockEdit; FEditor.OnBlockClick := FEditorBlockClick; FEditor.Options := FEditor.Options + [eoWantTab]; dctMain.Target := FEditor; FDefaultIndent := 20; FTextStyle := TKMemoTextStyle.Create; FTextStyle.OnChanged := FTextStyleChanged; FParaStyle := TKMemoParaStyle.Create; FParaStyle.OnChanged := FParaStyleChanged; // TODO: these should be created by the manager and passed to the view FContainerForm := TKMemoContainerForm.Create(Self); FHyperlinkForm := TKMemoHyperlinkForm.Create(Self); FImageForm := TKMemoImageForm.Create(Self); FNumberingForm := TKMemoNumberingForm.Create(Self); FTextStyleForm := TKMemoTextStyleForm.Create(Self); FParaStyleForm := TKMemoParaStyleForm.Create(Self); Logger.Leave(Self, 'AfterConstruction'); end; destructor TRichEditorViewKMemo.Destroy; begin FTextStyle.Free; FParaStyle.Free; inherited Destroy; Logger.Info('TRichEditorViewKMemo.Destroy'); end; {$ENDREGION} {$REGION 'property access mehods'} function TRichEditorViewKMemo.GetActions: IRichEditorActions; begin Result := Owner as IRichEditorActions; end; function TRichEditorViewKMemo.GetCanPaste: Boolean; begin Result := FEditor.CommandEnabled(ecPaste); end; function TRichEditorViewKMemo.GetCanUndo: Boolean; begin Result := FEditor.CommandEnabled(ecUndo); end; function TRichEditorViewKMemo.GetEditor: TComponent; begin Result := FEditor; end; function TRichEditorViewKMemo.GetFileName: string; begin Result := FFileName; end; procedure TRichEditorViewKMemo.SetFileName(const AValue: string); begin if AValue <> FileName then begin FFileName := AValue; end; end; function TRichEditorViewKMemo.GetFont: TFont; begin Result := FTextStyle.Font; end; function TRichEditorViewKMemo.GetForm: TCustomForm; begin Result := Self; end; function TRichEditorViewKMemo.GetEvents: IRichEditorEvents; begin Result := Owner as IRichEditorEvents; end; function TRichEditorViewKMemo.GetIsEmpty: Boolean; begin Result := FEditor.Blocks.Count <= 1; end; function TRichEditorViewKMemo.GetIsFile: Boolean; begin Result := FIsFile; end; procedure TRichEditorViewKMemo.SetIsFile(AValue: Boolean); begin FIsFile := AValue; end; function TRichEditorViewKMemo.GetModified: Boolean; begin Result := FEditor.Modified; end; procedure TRichEditorViewKMemo.SetModified(const AValue: Boolean); begin FEditor.Modified := AValue; end; function TRichEditorViewKMemo.GetOnChange: TNotifyEvent; begin Result := FOnChange; end; procedure TRichEditorViewKMemo.SetOnChange(const AValue: TNotifyEvent); begin FOnChange := AValue; end; function TRichEditorViewKMemo.GetOnDropFiles: TDropFilesEvent; begin Result := FOnDropFiles; end; procedure TRichEditorViewKMemo.SetOnDropFiles(const AValue: TDropFilesEvent); begin FOnDropFiles := AValue; end; function TRichEditorViewKMemo.GetSelAvail: Boolean; begin Result := FEditor.SelAvail; end; function TRichEditorViewKMemo.GetSelEnd: Integer; begin Result := FEditor.SelEnd; end; procedure TRichEditorViewKMemo.SetSelEnd(const AValue: Integer); begin FEditor.SelEnd := AValue; end; function TRichEditorViewKMemo.GetSelStart: Integer; begin Result := FEditor.SelStart; end; procedure TRichEditorViewKMemo.SetSelStart(const AValue: Integer); begin FEditor.SelStart := AValue; end; function TRichEditorViewKMemo.GetSelText: string; begin Result := FEditor.SelText; end; procedure TRichEditorViewKMemo.SetSelText(const AValue: string); begin FEditor.DeleteSelectedBlock; FEditor.InsertString(FEditor.SelStart, AValue); end; function TRichEditorViewKMemo.GetWordWrap: Boolean; begin Result := FParaStyle.WordWrap; end; procedure TRichEditorViewKMemo.SetWordWrap(const AValue: Boolean); begin FParaStyle.WordWrap := AValue; end; function TRichEditorViewKMemo.GetPopupMenu: TPopupMenu; begin Result := FEditor.PopupMenu; end; procedure TRichEditorViewKMemo.SetPopupMenu(const AValue: TPopupMenu); begin FEditor.PopupMenu := AValue; end; function TRichEditorViewKMemo.GetText: string; begin Result := FEditor.Text; end; procedure TRichEditorViewKMemo.SetText(const AValue: string); begin FEditor.Text := AValue; end; function TRichEditorViewKMemo.GetAlignCenter: Boolean; begin Result := FParaStyle.HAlign = halCenter; end; procedure TRichEditorViewKMemo.SetAlignCenter(AValue: Boolean); begin if AValue then FParaStyle.HAlign := halCenter; end; function TRichEditorViewKMemo.GetAlignJustify: Boolean; begin Result := FParaStyle.HAlign = halJustify; end; procedure TRichEditorViewKMemo.SetAlignJustify(AValue: Boolean); begin if AValue then FParaStyle.HAlign := halJustify; end; function TRichEditorViewKMemo.GetAlignLeft: Boolean; begin Result := FParaStyle.HAlign = halLeft; end; procedure TRichEditorViewKMemo.SetAlignLeft(AValue: Boolean); begin if AValue then FParaStyle.HAlign := halLeft; end; function TRichEditorViewKMemo.GetAlignRight: Boolean; begin Result := FParaStyle.HAlign = halRight; end; procedure TRichEditorViewKMemo.SetAlignRight(AValue: Boolean); begin if AValue then FParaStyle.HAlign := halRight; end; function TRichEditorViewKMemo.GetCanRedo: Boolean; begin Result := FEditor.CommandEnabled(ecRedo); end; function TRichEditorViewKMemo.GetRTFText: string; var SS : TStringStream; begin SS := TStringStream.Create; try FEditor.SaveToRTFStream(SS, False, True); Result := SS.DataString; finally SS.Free; end; end; function TRichEditorViewKMemo.GetShowSpecialChars: Boolean; begin Result := eoShowFormatting in FEditor.Options; end; procedure TRichEditorViewKMemo.SetShowSpecialChars(AValue: Boolean); begin if AValue then FEditor.Options := FEditor.Options + [eoShowFormatting] else FEditor.Options := FEditor.Options - [eoShowFormatting]; end; function TRichEditorViewKMemo.GetContentSize: Int64; begin Result := Length(FEditor.RTF); end; {$ENDREGION} {$REGION 'event handlers'} procedure TRichEditorViewKMemo.FormDropFiles(Sender: TObject; const FileNames: array of string); begin DoDropFiles(FileNames); end; procedure TRichEditorViewKMemo.dctMainDrop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Longint); begin InsertHyperlink(dctMain.Title, dctMain.URL); end; {$REGION 'Editor'} procedure TRichEditorViewKMemo.FEditorChange(Sender: TObject); begin Modified := True; DoChange; end; procedure TRichEditorViewKMemo.FEditorBlockClick(Sender: TObject; ABlock: TKMemoBlock; var Result: Boolean); begin Modified := True; DoChange; end; procedure TRichEditorViewKMemo.FEditorBlockEdit(Sender: TObject; ABlock: TKMemoBlock; var Result: Boolean); begin Modified := True; DoChange; end; procedure TRichEditorViewKMemo.FParaStyleChanged(Sender: TObject; AReasons: TKMemoUpdateReasons); begin FEditor.SelectionParaStyle := FParaStyle; Modified := True; DoChange; end; procedure TRichEditorViewKMemo.FTextStyleChanged(Sender: TObject); var LSelAvail : Boolean; LSelEnd : TKMemoSelectionIndex; LStartIndex : TKMemoSelectionIndex; LEndIndex : TKMemoSelectionIndex; begin // if there is no selection then simulate one word selection or set style for new text LSelAvail := FEditor.SelAvail; LSelEnd := FEditor.SelEnd; if LSelAvail then FEditor.SelectionTextStyle := FTextStyle else if FEditor.GetNearestWordIndexes(LSelEnd, False, LStartIndex, LEndIndex) and (LStartIndex < LSelEnd) and (LSelEnd < LEndIndex) then // simulate MS Word behavior here, LSelEnd is caret position // do not select the word if we are at the beginning or end of the word // and allow set another text style for newly added text FEditor.SetRangeTextStyle(LStartIndex, LEndIndex, FTextStyle) else FEditor.NewTextStyle := FTextStyle; DoChange; end; {$ENDREGION} {$ENDREGION} {$REGION 'event dispatch methods'} procedure TRichEditorViewKMemo.DoDropFiles(const AFileNames: array of string); begin if Assigned(FOnDropFiles) then FOnDropFiles(Self, AFileNames); end; procedure TRichEditorViewKMemo.DoChange; begin if Assigned(OnChange) and not IsUpdating then begin OnChange(Self); end; Logger.Watch('ContentHeight', FEditor.ContentHeight); Logger.Watch('ContentWidth', FEditor.ContentWidth); Logger.Watch('ContentLeft', FEditor.ContentLeft); Logger.Watch('ContentTop', FEditor.ContentTop); Logger.Watch('SelText', FEditor.Blocks.SelText); end; {$ENDREGION} {$REGION 'private methods'} function TRichEditorViewKMemo.SelectedBlock: TKMemoBlock; begin Result := FEditor.SelectedBlock; if not Assigned(Result) then Result := FEditor.ActiveInnerBlock; end; function TRichEditorViewKMemo.EditContainer(AItem: TKMemoBlock): Boolean; var Cont: TKMemoContainer; Blocks: TKMemoBlocks; Created: Boolean; begin Result := False; Created := False; if (AItem is TKMemoContainer) and (AItem.Position <> mbpText) then Cont := TKMemoContainer(AItem) else begin Blocks := AItem.ParentRootBlocks; if (Blocks.Parent is TKMemoContainer) and (Blocks.Parent.Position <> mbpText) then Cont := TKMemoContainer(Blocks.Parent) else begin Cont := TKMemoContainer.Create; //Cont.BlockStyle.ContentPadding.All := Editor.Pt2PxX(FDefaultTextBoxPadding); //Cont.BlockStyle.ContentMargin.All := Editor.Pt2PxX(FDefaultTextBoxMargin); //Cont.FixedWidth := True; //Cont.FixedHeight := True; //Cont.RequiredWidth := Editor.Pt2PxX(FDefaultTextBoxSize.X); //Cont.RequiredHeight := Editor.Pt2PxY(FDefaultTextBoxSize.Y); //Cont.BlockStyle.BorderWidth := Editor.Pt2PxX(FDefaultTextBoxBorderWidth); //Cont.InsertString(sMemoSampleTextBox + cEOL); Created := True; end; end; //FContainerForm.Load(Editor, Cont); if FContainerForm.ShowModal = mrOk then begin FContainerForm.Save(Cont); //if Created then //begin // if Editor.SelAvail then // Editor.ClearSelection; // Editor.ActiveBlocks.AddAt(Cont, Editor.NearestParagraphIndex + 1); //end; //Editor.Modified := True; //Result := True; end else if Created then Cont.Free; end; {$ENDREGION} {$REGION 'protected methods'} procedure TRichEditorViewKMemo.SelectAll; begin FEditor.Select(0, FEditor.SelectableLength); end; procedure TRichEditorViewKMemo.LoadFromFile(const AFileName: string); begin FEditor.LoadFromFile(AFileName); end; procedure TRichEditorViewKMemo.Load(const AStorageName: string); begin Events.DoLoad(AStorageName); if IsFile then begin if (AStorageName <> '') and FileExists(AStorageName) then FileName := AStorageName; LoadFromFile(FFileName); Modified := False; end; end; procedure TRichEditorViewKMemo.SaveToFile(const AFileName: string); begin FEditor.SaveToFile(AFileName); FEditor.ClearUndo; end; procedure TRichEditorViewKMemo.LoadFromStream(AStream: TStream); begin BeginUpdate; try Clear; FEditor.LoadFromRTFStream(AStream); // TS: probably due to a bug an empty line gets inserted after loading // content using LoadFromRTFStream FEditor.DeleteLine(0); finally EndUpdate; end; end; procedure TRichEditorViewKMemo.Save(const AStorageName: string); begin Logger.Enter(Self, 'Save'); Events.DoBeforeSave(AStorageName); if IsFile then begin FileName := AStorageName; SaveToFile(AStorageName); end; Events.DoAfterSave(AStorageName); Modified := False; Logger.Leave(Self, 'Save'); end; procedure TRichEditorViewKMemo.SaveToStream(AStream: TStream); begin FEditor.SaveToRTFStream(AStream, False, True); FEditor.ClearUndo; end; procedure TRichEditorViewKMemo.BeginUpdate; begin // do not call FEditor.LockUpdate as it causes problems if used in // combination with FEditor.LoadFromRTFStream. Inc(FUpdateLock); end; procedure TRichEditorViewKMemo.EndUpdate; begin if FUpdateLock > 0 then Dec(FUpdateLock); // do not call FEditor.UnlLockUpdate as it causes problems if used in // combination with FEditor.LoadFromRTFStream. end; { Inserts a new image block for the given image file at the current cursor position. } procedure TRichEditorViewKMemo.InsertImageFile(const AFileName: string); var P : TPicture; begin P := TPicture.Create; try P.LoadFromFile(AFileName); InsertImage(P); finally P.Free; end; end; procedure TRichEditorViewKMemo.InsertImage(AImage: TPicture); begin // TKMemo does only handle jpg and png well, so we convert any other // image types to jpeg first. if not MatchStr(AImage.Graphic.MimeType, ['image/jpg', 'image/png']) then begin AImage.Assign(AImage.Jpeg); end; FEditor.Blocks.AddImageBlock(AImage); end; { Creates new or updates an existing image block. } function TRichEditorViewKMemo.InsertImage: Boolean; var LImage : TKMemoImageBlock; LCreated : Boolean; begin Result := False; LCreated := False; if SelectedBlock is TKMemoImageBlock then LImage := TKMemoImageBlock(SelectedBlock) else begin LImage := TKMemoImageBlock.Create; LCreated := True; end; FImageForm.Load(FEditor, LImage); if FImageForm.ShowModal = mrOk then begin FImageForm.Save(LImage); if LCreated then begin if FEditor.SelAvail then FEditor.ClearSelection; FEditor.ActiveInnerBlocks.AddAt(LImage, FEditor.SplitAt(FEditor.SelEnd)); end; Modified := True; Result := True; end else if LCreated then LImage.Free; end; { Creates a new or updates an existing hyperlink block. } procedure TRichEditorViewKMemo.InsertHyperlink(const AText: string; const AURL: string); var LBlock : TKMemoBlock; LHyperlink : TKMemoHyperlink; LCreated : Boolean; begin LCreated := False; if FEditor.SelAvail then begin LHyperlink := TKMemoHyperlink.Create; LHyperlink.Text := FEditor.SelText; LBlock := FEditor.ActiveInnerBlock; if LBlock is TKMemoHyperlink then LHyperlink.URL := TKMemoHyperlink(LBlock).URL; LCreated := True; end else begin LBlock := FEditor.ActiveInnerBlock; if LBlock is TKMemoHyperlink then LHyperlink := TKMemoHyperlink(LBlock) else begin LHyperlink := TKMemoHyperlink.Create; LHyperlink.Text := AText; LHyperlink.URL := AURL; LCreated := True; end; end; FHyperlinkForm.Load(LHyperlink); if FHyperlinkForm.ShowModal = mrOk then begin FHyperlinkForm.Save(LHyperlink); if LCreated then begin if FEditor.SelAvail then FEditor.ClearSelection; FEditor.ActiveInnerBlocks.AddHyperlink( LHyperlink, FEditor.SplitAt(FEditor.SelEnd) ); end; Modified := True; end else if LCreated then LHyperlink.Free; end; procedure TRichEditorViewKMemo.InsertBulletList; begin FNumberingForm.Load(FEditor, FEditor.ListTable, FEditor.NearestParagraph); if FNumberingForm.ShowModal = mrOk then FNumberingForm.Save; end; procedure TRichEditorViewKMemo.InsertTextBox; begin //FContainerForm.Load(FEditor, FEditor.ActiveBlock); //if FContainerForm.ShowModal = mrOK then // FContainerForm.Save; end; procedure TRichEditorViewKMemo.IncIndent; begin FParaStyle.LeftPadding := Min( FParaStyle.LeftPadding + FEditor.Pt2PxX(FDefaultIndent), FEditor.RequiredContentWidth - FParaStyle.RightPadding - FEditor.Pt2PxX(FDefaultIndent) ); end; procedure TRichEditorViewKMemo.DecIndent; begin FParaStyle.LeftPadding := Max( FParaStyle.LeftPadding - FEditor.Pt2PxX(FDefaultIndent), 0 ); end; procedure TRichEditorViewKMemo.AdjustParagraphStyle; begin FParaStyleForm.Load(FEditor, FParaStyle); if FParaStyleForm.ShowModal = mrOk then FParaStyleForm.Save(FParaStyle); end; function TRichEditorViewKMemo.IsUpdating: Boolean; begin Result := FUpdateLock > 0; end; procedure TRichEditorViewKMemo.Clear; begin FEditor.Clear; end; procedure TRichEditorViewKMemo.Cut; begin FEditor.ExecuteCommand(ecCut); end; procedure TRichEditorViewKMemo.Copy; begin FEditor.ExecuteCommand(ecCopy); end; procedure TRichEditorViewKMemo.Paste; begin FEditor.ExecuteCommand(ecPaste); end; procedure TRichEditorViewKMemo.Undo; begin FEditor.ExecuteCommand(ecUndo); // not supported yet by TKMemo end; procedure TRichEditorViewKMemo.Redo; begin FEditor.ExecuteCommand(ecRedo); // not supported yet by TKMemo end; {$ENDREGION} {$REGION 'public methods'} function TRichEditorViewKMemo.Focused: Boolean; begin Result := FEditor.Focused; end; procedure TRichEditorViewKMemo.UpdateActions; begin FTextStyle.OnChanged := nil; try if FEditor.NewTextStyleValid then FTextStyle.Assign(FEditor.NewTextStyle) else FTextStyle.Assign(FEditor.SelectionTextStyle); finally FTextStyle.OnChanged := FTextStyleChanged; end; FParaStyle.OnChanged := nil; try FParaStyle.Assign(FEditor.SelectionParaStyle) finally FParaStyle.OnChanged := FParaStyleChanged; end; if Assigned(Actions) then Actions.UpdateActions; inherited UpdateActions; end; {$ENDREGION} end.
unit CsReplyProcedures; { $Id: CsReplyProcedures.pas,v 1.4 2013/04/24 09:35:37 lulin Exp $ } // $Log: CsReplyProcedures.pas,v $ // Revision 1.4 2013/04/24 09:35:37 lulin // - портируем. // // Revision 1.3 2011/12/08 12:32:12 narry // Отображается не вся очередь заданий (304874341) // // Revision 1.2 2006/03/10 09:29:12 voba // - enh. убрал CsFree etc. // // Revision 1.1 2006/02/08 17:24:29 step // выполнение запросов перенесено из классов-потомков в процедуры объектов // {$I CsDefine.inc} interface uses Classes, Contnrs, SysUtils, IdGlobal, CsCommon, CsObject, CsDataPipe, CsQueryTypes; type TCsReplyProc = procedure (aPipe: TCsDataPipe) of object; TCsProcWithId = class(TCsObject) public QueryId: TCsQueryId; Proc: TCsReplyProc; constructor Create(aQueryId: TCsQueryId; aProc: TCsReplyProc); reintroduce; end; TCsReplyProcedures = class(TCsObject) private f_List: TObjectList; f_Synchronizer: TMultiReadExclusiveWriteSynchronizer; protected procedure Cleanup; override; function ListItemBy(aQueryId: TCsQueryId): TCsProcWithId; public constructor Create; procedure Add(aQueryId: TCsQueryId; aProc: TCsReplyProc); procedure Clear; function ProcBy(aQueryId: TCsQueryId): TCsReplyProc; end; implementation uses l3Base, TypInfo; { TCsProcWithId } constructor TCsProcWithId.Create(aQueryId: TCsQueryId; aProc: TCsReplyProc); begin QueryId := aQueryId; Proc := aProc; end; { TCsReplyProcedures } procedure TCsReplyProcedures.Add(aQueryId: TCsQueryId; aProc: TCsReplyProc); var l_ProcWithId: TCsProcWithId; begin Assert(Assigned(aProc)); f_Synchronizer.BeginWrite; try l_ProcWithId := ListItemBy(aQueryId); if l_ProcWithId <> nil then begin l_ProcWithId.Proc := aProc; l3System.Msg2Log('Переопределение обработчика для %s', [GetEnumName(TypeInfo(TcsQueryID), ord(aQueryID))]); end else f_List.Add(TCsProcWithId.Create(aQueryId, aProc)); finally f_Synchronizer.EndWrite; end; end; procedure TCsReplyProcedures.Cleanup; begin l3Free(f_Synchronizer); l3Free(f_List); inherited; end; procedure TCsReplyProcedures.Clear; begin f_Synchronizer.BeginWrite; try f_List.Clear; finally f_Synchronizer.EndWrite; end; end; constructor TCsReplyProcedures.Create; begin f_List := TObjectList.Create(True); f_Synchronizer := TMultiReadExclusiveWriteSynchronizer.Create; end; function TCsReplyProcedures.ListItemBy(aQueryId: TCsQueryId): TCsProcWithId; var I: Integer; begin Result := nil; for I := 0 to f_List.Count - 1 do if TCsProcWithId(f_List[I]).QueryId = aQueryId then begin Result := TCsProcWithId(f_List[I]); Break; end; end; function TCsReplyProcedures.ProcBy(aQueryId: TCsQueryId): TCsReplyProc; var l_ProcWithId: TCsProcWithId; begin f_Synchronizer.BeginRead; try l_ProcWithId := ListItemBy(aQueryId); if l_ProcWithId <> nil then Result := l_ProcWithId.Proc else Result := nil; finally f_Synchronizer.EndRead; end; end; end.
unit ProfilerFuncts; interface type TProfileKind = 0..30; TProfileId = 0..30; procedure RequestProfile( Kind : TProfileKind; Id : TProfileId; Name : string ); procedure ProcStarted( Kind : TProfileKind; Id : TProfileId ); procedure ProcEnded( Kind : TProfileKind; Id : TProfileId ); procedure Reset( Kind : TProfileKind ); procedure LogResults( Kind : TProfileKind; LogName : string ); implementation uses Windows, Logs, SysUtils; type TProfileRec = record Name : string; Active : boolean; TotalTicks : comp; MarkerStart : comp; TimeElapsed : comp; end; var Profiles : array[TProfileKind, TProfileId] of TProfileRec; MarkerStart : array[TProfileKind] of comp; procedure RequestProfile( Kind : TProfileKind; Id : TProfileId; Name : string ); begin Profiles[Kind, Id].Name := Name; Profiles[Kind, Id].Active := true; Profiles[Kind, Id].TotalTicks := 0; Profiles[Kind, Id].MarkerStart := 0; end; procedure ProcStarted( Kind : TProfileKind; Id : TProfileId ); begin QueryPerformanceCounter( TLargeInteger(Profiles[Kind, Id].MarkerStart) ); end; procedure ProcEnded( Kind : TProfileKind; Id : TProfileId ); var counter : comp; delta : comp; begin QueryPerformanceCounter( TLargeInteger(counter) ); delta := counter - Profiles[Kind, Id].MarkerStart; Profiles[Kind, Id].TotalTicks := Profiles[Kind, Id].TotalTicks + delta; end; procedure Reset( Kind : TProfileKind ); var id : TProfileId; begin // reset profiles for id := low(id) to high(id) do Profiles[Kind, id].TotalTicks := 0; // start total counting QueryPerformanceCounter( TLargeInteger(MarkerStart[Kind]) ); end; procedure LogResults( Kind : TProfileKind; LogName : string ); var freq : comp; function TicksToMSecStr( tics : comp ) : string; begin try if freq > 0 then result := IntToStr(round(1000*tics/freq)) + ' msecs' else result := 'UNKNOWN FREQUENCY'; except result := 'NUMERIC ERROR'; end; end; function RatioToStr( num, dem : comp ) : string; begin if dem > 0 then result := IntToStr(round((100*num)/dem)) + '%' else result := '0%'; end; var id : TProfileId; absTime : comp; relTime : comp; begin // stop total counting QueryPerformanceCounter( TLargeInteger(absTime) ); absTime := absTime - MarkerStart[Kind]; // compute total relTime := 0; for id := low(id) to high(id) do if Profiles[Kind, id].Active then relTime := relTime + Profiles[Kind, id].TotalTicks; // produce report if (relTime > 0) and (absTime > 0) then begin QueryPerformanceFrequency( TLargeInteger(freq) ); Logs.Log( LogName, '-------------------------------------' ); Logs.Log( LogName, 'Abs Time sampled: ' + TicksToMSecStr(absTime) ); Logs.Log( LogName, 'Rel Time sampled: ' + TicksToMSecStr(relTime) ); for id := low(id) to high(id) do if Profiles[Kind, id].Active then begin Logs.Log( LogName, 'Profile: ' + Profiles[Kind, id].Name ); Logs.Log( LogName, #9'Time running: ' + TicksToMSecStr(Profiles[Kind, id].TotalTicks) ); Logs.Log( LogName, #9'Relative usage: ' + RatioToStr(Profiles[Kind, id].TotalTicks, relTime) ); Logs.Log( LogName, #9'Absolute usage: ' + RatioToStr(Profiles[Kind, id].TotalTicks, absTime) ); end; Logs.Log( LogName, 'Other tasks: ' ); Logs.Log( LogName, #9'Time running: ' + TicksToMSecStr(absTime - relTime) ); Logs.Log( LogName, #9'usage: ' + RatioToStr(absTime - relTime, absTime) ); end; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Assimp * Implements Assimp model importing (requires DLL) *********************************************************************************************************************** } Unit TERRA_Assimp; {$I terra.inc} Interface Uses TERRA_Mesh, TERRA_Math, TERRA_Utils, TERRA_Stream, TERRA_FileStream, TERRA_FileUtils, TERRA_MeshFilter, TERRA_OS, TERRA_Quaternion, TERRA_Vector3D, TERRA_Vector2D, TERRA_Color, TERRA_Matrix, Assimp; Function ASSIMP_Import(SourceFile, TargetDir:TERRAString):TERRAString; Type AssimpBone = Class(TERRAObject) ID:Integer; Name:TERRAString; LocalTransform:Matrix; GlobalTransform:Matrix; Parent:AssimpBone; Node:PAINode; End; AssimpFilter = Class(MeshFilter) Protected scene:PaiScene; Bones:Array Of AssimpBone; BoneCount:Integer; Function FindNode(Name:TERRAString; Root:pAiNode):pAiNode; //Function GetBoneAt(Var BoneID:Integer):Integer; Function GetBoneIDByName(Name:TERRAString):Integer; Public Constructor Create(Source:TERRAString); Procedure Release; Function GetGroupCount:Integer; Override; Function GetGroupName(GroupID:Integer):TERRAString; Override; Function GetGroupFlags(GroupID:Integer):Cardinal; Override; Function GetGroupBlendMode(GroupID:Integer):Cardinal; Override; Function GetTriangleCount(GroupID:Integer):Integer; Override; Function GetTriangle(GroupID, Index:Integer):Triangle; Override; Function GetVertexCount(GroupID:Integer):Integer; Override; Function GetVertexFormat(GroupID:Integer):Cardinal; Override; Function GetVertexPosition(GroupID, Index:Integer):Vector3D; Override; Function GetVertexNormal(GroupID, Index:Integer):Vector3D; Override; Function GetVertexTangent(GroupID, Index:Integer):Vector3D; Override; Function GetVertexHandness(GroupID, Index:Integer):Single; Override; Function GetVertexBone(GroupID, Index:Integer):Integer; Override; Function GetVertexColor(GroupID, Index:Integer):Color; Override; Function GetVertexUV(GroupID, Index:Integer):Vector2D; Override; Function GetVertexUV2(GroupID, Index:Integer):Vector2D; Override; Function GetDiffuseColor(GroupID:Integer):Color; Override; Function GetDiffuseMapName(GroupID:Integer):TERRAString; Override; Function GetSpecularMapName(GroupID:Integer):TERRAString; Override; Function GetEmissiveMapName(GroupID:Integer):TERRAString; Override; Function GetAnimationCount():Integer; Override; Function GetAnimationName(Index:Integer):TERRAString; Override; Function GetAnimationDuration(Index:Integer):Single; Override; Function GetPositionKeyCount(AnimationID, BoneID:Integer):Integer; Override; Function GetRotationKeyCount(AnimationID, BoneID:Integer):Integer; Override; Function GetScaleKeyCount(AnimationID, BoneID:Integer):Integer; Override; Function GetPositionKey(AnimationID, BoneID:Integer; Index:Integer):MeshVectorKey; Override; Function GetScaleKey(AnimationID, BoneID:Integer; Index:Integer):MeshVectorKey; Override; Function GetRotationKey(AnimationID, BoneID:Integer; Index:Integer):MeshVectorKey; Override; Function GetBoneCount():Integer; Override; Function GetBoneName(BoneID:Integer):TERRAString; Override; Function GetBoneParent(BoneID:Integer):Integer; Override; Function GetBonePosition(BoneID:Integer):Vector3D; Override; End; Implementation Uses TERRA_GraphicsManager; Function ASSIMP_Import(SourceFile, TargetDir:TERRAString):TERRAString; Var dest:FileStream; mymesh:Mesh; group:MeshGroup; I, J, K, N:Integer; X,Y,Z:Single; T:Triangle; Filter:MeshFilter; Begin WriteLn('ASSIMP_Import: ',SourceFile); filter := ASSimpFilter.Create(SourceFile); If Assigned(ASSimpFilter(Filter).scene) Then Begin MyMesh := Mesh.CreateFromFilter(Filter); //ModelMilkshape3D.Save(TargetDir + PathSeparator + GetFileName(SourceFile, True)+'.ms3d', Filter); WriteLn('Saving...'); Result := TargetDir + PathSeparator + GetFileName(SourceFile, True)+'.mesh'; Dest := FileStream.Create(Result); MyMesh.Save(Dest); Dest.Release; MyMesh.Release; Filter.Release; End Else Begin Writeln('ASSIMP:Error!'); Result := ''; End; End; Var c:aiLogStream; { AssimpFilter } Constructor AssimpFilter.Create(Source:TERRAString); Var Flags:Cardinal; I, J, N:Integer; node, P:PAInode; S:TERRAString; M:Matrix; Begin flags := aiProcess_CalcTangentSpace Or aiProcess_GenSmoothNormals Or // aiProcess_JoinIdenticalVertices Or aiProcess_ImproveCacheLocality Or aiProcess_LimitBoneWeights Or aiProcess_RemoveRedundantMaterials Or aiProcess_SplitLargeMeshes Or aiProcess_Triangulate Or aiProcess_GenUVCoords Or aiProcess_SortByPType Or //aiProcess_FindDegenerates Or aiProcess_FindInvalidData; scene := aiImportFile(PTERRAChar(Source), flags); If (Scene = Nil) Then Exit; BoneCount := 0; For I:=0 To Pred(scene.mNumMeshes) Do If (scene.mMeshes[I].mNumBones>0) Then Begin BoneCount := 1; SetLength(Bones, BoneCount); Bones[0] := AssimpBone.Create; Bones[0].ID := 0; Bones[0].Name := aiStringGetValue(Scene.mRootNode.mName); Bones[0].Parent := Nil; Bones[0].Node := Scene.mRootNode; Break; End; For I:=0 To Pred(scene.mNumMeshes) Do For J:=0 To Pred(Scene.mMeshes[I].mNumBones) Do If (Self.GetBoneIDByName(aiStringGetValue(Scene.mMeshes[I].mBones[J].mName))<0) Then Begin Inc(BoneCount); SetLength(Bones, BoneCount); Bones[Pred(BoneCount)] := AssimpBone.Create; Bones[Pred(BoneCount)].ID := Pred(BoneCount); Bones[Pred(BoneCount)].Name := aiStringGetValue(Scene.mMeshes[I].mBones[J].mName); Bones[Pred(BoneCount)].Parent := Nil; Bones[Pred(BoneCount)].Node := Self.FindNode(Bones[Pred(BoneCount)].Name, Scene.mRootNode); End; For I:=0 To Pred(BoneCount) Do Begin Node := Bones[I].Node; For J:=0 To 15 Do Bones[I].LocalTransform.V[J] := Node.mTransformation.V[J]; Bones[I].LocalTransform := MatrixTranspose(Bones[I].LocalTransform); Bones[I].GlobalTransform := Bones[I].LocalTransform; Node := Node.mParent; While Assigned(Node) Do Begin For J:=0 To 15 Do M.V[J] := Node.mTransformation.V[J]; M := MatrixTranspose(M); Bones[I].GlobalTransform := MatrixMultiply4x3(M, Bones[I].GlobalTransform); N := Self.GetBoneIDByName(aiStringGetValue(Node.mName)); If (N>=0) And (Bones[I].Parent = Nil) Then Begin Bones[I].Parent := Bones[N]; WriteLn(Bones[I].Name ,' parent is ', Bones[N].Name); End; Node := Node.mParent; End; End; ///Bones[I].Transform := MatrixInverse(Bones[I].Transform); For I:=0 To Pred(BoneCount) Do If Bones[I].Parent = Nil Then Begin WriteLn(Bones[I].Name,' has no parent!'); End; //ReadLn; End; Procedure AssimpFilter.Release; Begin aiReleaseImport(scene); End; Function AssimpFilter.GetDiffuseColor(GroupID: Integer): Color; Begin Result := ColorWhite; End; Function AssimpFilter.GetDiffuseMapName(GroupID: Integer):TERRAString; Var prop:PAImaterialProperty; Begin aiGetMaterialProperty(scene.mMaterials[scene.mMeshes[GroupID].mMaterialIndex], _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0, prop); If Assigned(Prop) Then Begin SetLength(Result, Prop.mDataLength); Move(Prop.mData^, Result[1], Prop.mDataLength); Result := TrimLeft(TrimRight(Result)); Result := GetFileName(Result, False); StringTofloat(Result); End Else Result := ''; End; Function AssimpFilter.GetEmissiveMapName(GroupID: Integer):TERRAString; Begin Result := ''; End; Function AssimpFilter.GetGroupBlendMode(GroupID: Integer): Cardinal; Begin Result := blendBlend; End; Function AssimpFilter.GetGroupCount: Integer; Begin Result := Scene.mNumMeshes; End; Function AssimpFilter.GetGroupFlags(GroupID: Integer): Cardinal; Begin Result := meshGroupCastShadow Or meshGroupPick; End; function AssimpFilter.GetGroupName(GroupID: Integer):TERRAString; begin Result := aiStringGetValue(scene.mMeshes[GroupID].mName); Result := TrimLeft(TrimRight(Result)); If (Result='') Then Result := 'group'+IntToString(GroupID); end; Function AssimpFilter.GetSpecularMapName(GroupID: Integer):TERRAString; Begin Result := ''; End; function AssimpFilter.GetTriangle(GroupID, Index: Integer): Triangle; begin Result.Indices[0] := scene.mMeshes[GroupID].mFaces[Index].mIndices[0]; Result.Indices[1] := scene.mMeshes[GroupID].mFaces[Index].mIndices[1]; Result.Indices[2] := scene.mMeshes[GroupID].mFaces[Index].mIndices[2]; end; function AssimpFilter.GetTriangleCount(GroupID: Integer): Integer; begin Result := scene.mMeshes[GroupID].mNumFaces; end; Function AssimpFilter.GetVertexBone(GroupID, Index: Integer): Integer; Var I, J ,K:Integer; W:Single; Begin Result := -1; If (GroupID<0) Or (GroupID>=scene.mNumMeshes) Or (scene = Nil) Then Exit; W := -1; K := GroupID; For I:=0 To Pred(scene.mMeshes[K].mNumBones) Do Begin For J:=0 To Pred(scene.mMeshes[K].mBones[I].mNumWeights) Do Begin If (scene.mMeshes[K].mBones[I].mWeights[J].mVertexId=Index) And (scene.mMeshes[K].mBones[I].mWeights[J].mWeight>W) Then Begin Result := GetBoneIDByName(aiStringGetValue(scene.mMeshes[K].mBones[I].mName)); W := scene.mMeshes[K].mBones[I].mWeights[J].mWeight; End; End; End; End; Function AssimpFilter.GetVertexColor(GroupID, Index: Integer): Color; Begin Result := ColorWhite; End; Function AssimpFilter.GetVertexCount(GroupID: Integer): Integer; Begin Result := scene.mMeshes[GroupID].mNumVertices; End; Function AssimpFilter.GetVertexFormat(GroupID: Integer): Cardinal; Begin Result := meshFormatNormal Or meshFormatTangent Or meshFormatUV1; End; Function AssimpFilter.GetVertexHandness(GroupID, Index: Integer): Single; Begin Result := 1; End; function AssimpFilter.GetVertexNormal(GroupID, Index: Integer): Vector3D; begin Result.X := scene.mMeshes[GroupID].mNormals[Index].X; Result.Y := scene.mMeshes[GroupID].mNormals[Index].Y; Result.Z := scene.mMeshes[GroupID].mNormals[Index].Z; end; Function AssimpFilter.GetVertexPosition(GroupID, Index: Integer): Vector3D; begin Result.X := scene.mMeshes[GroupID].mVertices[Index].X; Result.Y := scene.mMeshes[GroupID].mVertices[Index].Y; Result.Z := scene.mMeshes[GroupID].mVertices[Index].Z; end; Function AssimpFilter.GetVertexTangent(GroupID, Index: Integer): Vector3D; begin Result.X := scene.mMeshes[GroupID].mTangents[Index].X; Result.Y := scene.mMeshes[GroupID].mTangents[Index].Y; Result.Z := scene.mMeshes[GroupID].mTangents[Index].Z; end; Function AssimpFilter.GetVertexUV(GroupID, Index: Integer): Vector2D; begin Result.X := scene.mMeshes[GroupID].mTextureCoords[0][Index].X; Result.Y := 1 - scene.mMeshes[GroupID].mTextureCoords[0][Index].Y; end; Function AssimpFilter.GetVertexUV2(GroupID, Index: Integer): Vector2D; begin Result.X := scene.mMeshes[GroupID].mTextureCoords[1][Index].X; Result.Y := 1- scene.mMeshes[GroupID].mTextureCoords[1][Index].Y; End; Function AssimpFilter.GetAnimationCount():Integer; Begin Result := Scene.mNumAnimations; End; Function AssimpFilter.GetAnimationName(Index:Integer):TERRAString; Begin Result := aiStringGetValue(Scene.mAnimations[Index].mName); End; Function AssimpFilter.GetBoneCount: Integer; Begin Result := Self.BoneCount; end; Function AssimpFilter.GetBoneName(BoneID: Integer):TERRAString; Begin Result := Bones[boneID].Name; End; Function AssimpFilter.GetAnimationDuration(Index:Integer):Single; Begin Result := Scene.mAnimations[Index].mDuration; End; Function AssimpFilter.GetPositionKeyCount(AnimationID, BoneID:Integer):Integer; Var Channel:Integer; Begin If (AnimationID>=Scene.mNumAnimations) Then Begin Result := 0; Exit; End; Channel := aiAnimationGetChannel(Scene.mAnimations[AnimationID], Bones[BoneID].Name); If (Channel<0) Then Begin Result := 0; Exit; End; Result := Scene.mAnimations[AnimationID].mChannels[Channel].mNumPositionKeys; End; Function AssimpFilter.GetRotationKeyCount(AnimationID, BoneID:Integer):Integer; Var Channel:Integer; Begin If (AnimationID>=Scene.mNumAnimations) Then Begin Result := 0; Exit; End; Channel := aiAnimationGetChannel(Scene.mAnimations[AnimationID], Bones[BoneID].Name); If (Channel<0) Then Begin Result := 0; Exit; End; Result := Scene.mAnimations[AnimationID].mChannels[Channel].mNumRotationKeys; End; Function AssimpFilter.GetScaleKeyCount(AnimationID, BoneID:Integer):Integer; Var Channel:Integer; Begin If (AnimationID>=Scene.mNumAnimations) Then Begin Result := 0; Exit; End; Channel := aiAnimationGetChannel(Scene.mAnimations[AnimationID], Bones[BoneID].Name); If (Channel<0) Then Begin Result := 0; Exit; End; Result := Scene.mAnimations[AnimationID].mChannels[Channel].mNumScalingKeys; End; Function AssimpFilter.GetPositionKey(AnimationID, BoneID:Integer; Index:Integer):MeshVectorKey; Var Channel:Integer; Begin Channel := aiAnimationGetChannel(Scene.mAnimations[AnimationID], Bones[BoneID].Name); If (Channel<0) Then Exit; Result.Value.X := Scene.mAnimations[AnimationID].mChannels[Channel].mPositionKeys[Index].mValue.x; Result.Value.Y := Scene.mAnimations[AnimationID].mChannels[Channel].mPositionKeys[Index].mValue.Y; Result.Value.Z := Scene.mAnimations[AnimationID].mChannels[Channel].mPositionKeys[Index].mValue.Z; Result.Time := Scene.mAnimations[AnimationID].mChannels[Channel].mPositionKeys[Index].mTime; End; Function AssimpFilter.GetScaleKey(AnimationID, BoneID:Integer; Index:Integer):MeshVectorKey; Var Channel:Integer; Begin Channel := aiAnimationGetChannel(Scene.mAnimations[AnimationID], Bones[BoneID].Name); If (Channel<0) Then Exit; Result.Value.X := Scene.mAnimations[AnimationID].mChannels[Channel].mScalingKeys[Index].mValue.x; Result.Value.Y := Scene.mAnimations[AnimationID].mChannels[Channel].mScalingKeys[Index].mValue.Y; Result.Value.Z := Scene.mAnimations[AnimationID].mChannels[Channel].mScalingKeys[Index].mValue.Z; Result.Time := Scene.mAnimations[AnimationID].mChannels[Channel].mScalingKeys[Index].mTime; End; Function AssimpFilter.GetRotationKey(AnimationID, BoneID:Integer; Index:Integer):MeshVectorKey; Var Channel:Integer; Q:Quaternion; Begin Channel := aiAnimationGetChannel(Scene.mAnimations[AnimationID], Bones[BoneID].Name); If (Channel<0) Then Exit; With Scene.mAnimations[AnimationID].mChannels[Channel].mRotationKeys[Index].mValue Do Q := QuaternionCreate(x, y, z, w); Result.Value := QuaternionToEuler(Q); Result.Time := Scene.mAnimations[AnimationID].mChannels[Channel].mRotationKeys[Index].mTime; End; Function AssimpFilter.FindNode(Name:TERRAString; Root:pAiNode): pAiNode; Var I:Integer; Begin If (aiStringGetValue(Root.mName) = Name) Then Begin Result := Root; Exit; End; For I:=0 To Pred(Root.mNumChildren) Do Begin Result := FindNode(Name, root.mChildren[I]); If Assigned(Result) Then Exit; End; Result := Nil; End; Function AssimpFilter.GetBoneParent(BoneID: Integer): Integer; Begin If Assigned(Bones[BoneID].Parent) Then Result := Bones[BoneID].Parent.ID Else Result := -1; End; Function AssimpFilter.GetBoneIDByName(Name:TERRAString): Integer; Var I, J, N:Integer; Begin Result := -1; For I:=0 To Pred(BoneCount) Do If (Bones[I].Name = Name) Then Begin Result := I; Exit; End; End; Function AssimpFilter.GetBonePosition(BoneID: Integer): Vector3D; Var A,B:Vector3D; Begin A := Bones[BoneID].GlobalTransform.Transform(VectorZero); If Assigned(Bones[BoneID].Parent) Then Begin B := Bones[Bones[BoneID].Parent.ID].GlobalTransform.Transform(VectorZero); Result := VectorSubtract(A, B); End Else Result := A; End; Initialization // c:= aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT, Nil); // aiAttachLogStream(@c); Finalization // aiDetachAllLogStreams(); End.
{*********************************************************} {* VPSQLBDE.PAS 1.03 *} {*********************************************************} {* ***** 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 Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* Hannes Danzl *} {* *} {* ***** END LICENSE BLOCK ***** *} {This unit was provided by Hannes Danzl and is used here with permission } unit VPSQLBDE; interface uses classes, VPDbIntf, dbtables, db, sysutils; type // implements the ISQLDataSet interface for TQuery TshwBDEDataset = class(TQuery, ISQLDataSet) protected // see ISQLDataset.iConnectionParams fConnectionParams: TStringlist; // see ISQLDataset.iSQL procedure SetiSQL(const value: String); virtual; // see ISQLDataset.iSQL function GetiSQL:String; virtual; // see ISQLDataset.iExecSQL procedure IExecSQL; virtual; // see ISQLDataset.iConnectionParams procedure SetiConnectionParams(const value: String); virtual; // see ISQLDataset.iConnectionParams function GetiConnectionParams:String; virtual; public // constructor constructor Create(aOwner: TComponent); override; // destructor destructor Destroy; override; end; implementation constructor TshwBDEDataset.Create(aOwner: TComponent); begin inherited; fConnectionParams:=TStringlist.Create; RequestLive:=true; end; destructor TshwBDEDataset.Destroy; begin fConnectionParams.free; inherited; end; function TshwBDEDataset.GetiConnectionParams: String; begin result:=fConnectionParams.Text; end; function TshwBDEDataset.GetiSQL: String; begin result:=sql.text; end; procedure TshwBDEDataset.IExecSQL; begin ExecSQL; end; procedure TshwBDEDataset.SetiConnectionParams(const value: String); begin fConnectionParams.Text:=value; Close; DatabaseName:=fConnectionParams.Values['DatabaseName']; end; procedure TshwBDEDataset.SetiSQL(const value: String); begin sql.text:=value; end; function CreateBDESQLDataset(InterfaceClass: String): TDataset; begin result:=TshwBDEDataset.Create(nil); end; initialization // IMPORTANT: register it sSQLDatasetFactory.RegisterInterfaceType('BDE', @CreateBDESQLDataset); end.
unit fmAttrSelection; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.StrUtils, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, ADC.Common, ADC.Types, ADC.GlobalVar, ADC.DC, System.ImageList, Vcl.ImgList, System.Types, Winapi.CommCtrl, Winapi.UxTheme, ADC.ImgProcessor, Vcl.ToolWin, Vcl.ExtCtrls; type TComboBox = class(Vcl.StdCtrls.TComboBox) private procedure CN_DrawItem(var Message : TWMDrawItem); message CN_DRAWITEM; end; type TForm_AttrSelect = class(TForm) ListView_Attributes: TListView; Button_Cancel: TButton; Button_OK: TButton; ComboBox_DC: TComboBox; ToolBar: TToolBar; ToolButton_Refresh: TToolButton; ToolButton2: TToolButton; ToolButton_ShowAll: TToolButton; ImageList_ToolBar: TImageList; ToolButton_ShowSuitable: TToolButton; Label_Search: TLabel; Edit_Search: TButtonedEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ListView_AttributesClick(Sender: TObject); procedure ListView_AttributesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Button_CancelClick(Sender: TObject); procedure Button_OKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ComboBox_DCSelect(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ListView_AttributesData(Sender: TObject; Item: TListItem); procedure ListView_AttributesDrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); procedure ComboBox_DCDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure ListView_AttributesResize(Sender: TObject); procedure ListView_AttributesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ToolButton_RefreshClick(Sender: TObject); procedure ToolButton_ShowAllClick(Sender: TObject); procedure ToolButton_ShowSuitableClick(Sender: TObject); procedure Edit_SearchChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Edit_SearchRightButtonClick(Sender: TObject); private type PAttrItem = ^TAttrItem; TAttrItem = packed record Selected: Boolean; AttrName: string[255]; AttrType: string[255]; function IsType(const AType: string): Boolean; end; type TAttrItems = class(TList) private FOwnsObjects: Boolean; function Get(Index: Integer): PAttrItem; protected function Add(Value: PAttrItem): Integer; procedure Clear; override; property Items[Index: Integer]: PAttrItem read Get; default; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; procedure SelectItem(AIndex: Integer); function SelectedIndex: Integer; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; const ATTR_ITEM_NOT_SELECTED = 0; ATTR_ITEM_SELECTED = 1; ATTR_ITEM_DISABLED_NOT_SELECTED = 2; ATTR_ITEM_DISABLED_SELECTED = 3; private { Private declarations } FCallingForm: TForm; FSelectedAttr: string; FAttributes: TAttrItems; FAttributeList: TAttrItems; FOutputField: TEdit; FAttrType: string; FStateImages: TImageList; FListViewWndProc: TWndMethod; procedure ListViewWndProc(var Msg: TMessage); procedure FillAttributeList(AShowAll: Boolean); procedure SetOutputField(Fld: TEdit); procedure SetAttributeType(AAttrType: string); procedure SetCallingForm(const Value: TForm); procedure ClearFields; public { Public declarations } property OutputField: TEdit read FOutputField write SetOutputField; property AttributeType: string read FAttrType write SetAttributeType; property CallingForm: TForm write SetCallingForm; end; var Form_AttrSelect: TForm_AttrSelect; implementation {$R *.dfm} procedure TForm_AttrSelect.Button_CancelClick(Sender: TObject); begin Close; end; procedure TForm_AttrSelect.Button_OKClick(Sender: TObject); begin FOutputField.Text := FSelectedAttr; Close; end; procedure TForm_AttrSelect.ClearFields; begin FAttrType := ATTR_TYPE_ANY; FSelectedAttr := ''; ComboBox_DC.Clear; ListView_Attributes.Clear; FAttributes.Clear; FAttributeList.Clear; Edit_Search.Clear; end; procedure TForm_AttrSelect.ComboBox_DCDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); const _margin: Integer = 6; var Columns: TStringDynArray; ColCount: Integer; ItemText: string; C: TCanvas; // DC: HDC; DrawRect: TRect; DeviderPos: Integer; TextWidth: Integer; begin DeviderPos := 0; { Вычисляем положение отрисовки разделителя } if odComboBoxEdit in State then begin Columns := SplitString(ComboBox_DC.Items[Index], '|'); DeviderPos := GetTextWidthInPixels(Columns[0], ComboBox_DC.Font) + 6; end else for ItemText in ComboBox_DC.Items do begin Columns := SplitString(ItemText, '|'); if Length(Columns) > 0 then begin TextWidth := GetTextWidthInPixels(Columns[0], ComboBox_DC.Font); if DeviderPos < TextWidth then DeviderPos := TextWidth; end; end; DeviderPos := DeviderPos + _margin * 2; ItemText := ComboBox_DC.Items[Index]; Columns := SplitString(ItemText, '|'); ColCount := Length(Columns); // DC := ComboBox_DC.Canvas.Handle; C := ComboBox_DC.Canvas; if ( odSelected in State ) or ( odFocused in State ) then begin C.Brush.Color := clHighlight; C.Pen.Color := clHighlightText; end else begin C.Brush.Color := clWhite; C.Pen.Color := clSilver; end; C.FillRect(Rect); { Рисуем разделитель } C.Pen.Width := 1; C.MoveTo(DeviderPos, Rect.Top); C.LineTo(DeviderPos, Rect.Bottom); { Выводим имя домена в фромате DNS } if ColCount > 0 then begin DrawRect := Rect; OffsetRect(DrawRect, _margin, 1); if DeviderPos - _margin < Rect.Right then DrawRect.Right := DeviderPos - _margin else DrawRect.Right := Rect.Right; with C.Font do begin Style := C.Font.Style + [fsBold]; if ( odSelected in State ) or ( odFocused in State ) then Color := clHighlightText else Color := clWindowText; end; C.TextRect(DrawRect, Columns[0], [tfLeft, tfEndEllipsis]); end; { Выводим имя домена контроллера домена } if ColCount > 1 then begin DrawRect := Rect; OffsetRect(DrawRect, DeviderPos + _margin, 1); DrawRect.Right := Rect.Right; with C.Font do begin Style := C.Font.Style - [fsBold]; if ( odSelected in State ) or ( odFocused in State ) then Color := clHighlightText else Color := COLOR_GRAY_TEXT; end; C.TextRect(DrawRect, Columns[1], [tfEndEllipsis]); end; end; procedure TForm_AttrSelect.ComboBox_DCSelect(Sender: TObject); begin ToolButton_RefreshClick(Self); end; procedure TForm_AttrSelect.Edit_SearchChange(Sender: TObject); var a: PAttrItem; begin Edit_Search.RightButton.Visible := Edit_Search.Text <> ''; ListView_Attributes.Clear; FAttributes.Clear; if Edit_Search.Text = '' then begin for a in FAttributeList do FAttributes.Add(a); end else for a in FAttributeList do begin if ContainsText(a^.AttrName, Edit_Search.Text) then FAttributes.Add(a); end; ListView_Attributes.Items.Count := FAttributes.Count; end; procedure TForm_AttrSelect.Edit_SearchRightButtonClick(Sender: TObject); begin Edit_Search.Clear; end; procedure TForm_AttrSelect.FillAttributeList(AShowAll: Boolean); var src: TStringList; i: Integer; s: string; attr: PAttrItem; begin ListView_Attributes.Items.Clear; FSelectedAttr := FOutputField.Text; FAttributes.Clear; FAttributeList.Clear; try src := TDCInfo(ComboBox_DC.Items.Objects[ComboBox_DC.ItemIndex]).UserAttributes; except Exit; end; for i := 0 to src.Count - 1 do begin if (AShowAll) or (AnsiLowerCase(src[i]).Contains(AnsiLowerCase(FAttrType))) then begin // GetMem(attr, SizeOf(TAttrItem)); New(attr); attr^.Selected := CompareText(src.Names[i], FSelectedAttr) = 0; attr^.AttrName := src.Names[i]; attr^.AttrType := src.ValueFromIndex[i]; FAttributeList.Add(attr); end; Application.ProcessMessages; end; Edit_SearchChange(Self); end; procedure TForm_AttrSelect.FormClose(Sender: TObject; var Action: TCloseAction); begin ClearFields; if FCallingForm <> nil then begin FCallingForm.Enabled := True; FCallingForm.Show; FCallingForm := nil; end; end; procedure TForm_AttrSelect.FormCreate(Sender: TObject); begin FStateImages := TImageList.Create(Self); FStateImages.ColorDepth := cd32Bit; TImgProcessor.GetThemeButtons( Self.Handle, ListView_Attributes.Canvas.Handle, BP_RADIOBUTTON, ListView_Attributes.Color, FStateImages ); ListView_Attributes.StateImages := FStateImages; FListViewWndProc := ListView_Attributes.WindowProc; ListView_Attributes.WindowProc := ListViewWndProc; FAttributeList := TAttrItems.Create; FAttributes := TAttrItems.Create(False); end; procedure TForm_AttrSelect.FormDestroy(Sender: TObject); begin FAttributes.Free; FAttributeList.Free; FStateImages.Free; end; procedure TForm_AttrSelect.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_F5: begin ToolButton_RefreshClick(Self); end; Ord('F'): begin if ssCtrl in Shift then Edit_Search.SetFocus; end; VK_ESCAPE: begin Close; end; end; end; procedure TForm_AttrSelect.FormShow(Sender: TObject); var R: TRect; begin if FAttributes.SelectedIndex = -1 then Exit; if ListView_IsItemVisible(ListView_Attributes.Handle, FAttributes.SelectedIndex) = 0 then begin R := ListView_Attributes.Items[FAttributes.SelectedIndex].DisplayRect(drBounds); ListView_Attributes.Scroll(0, R.Top - ListView_Attributes.ClientHeight div 2); end; end; procedure TForm_AttrSelect.ListViewWndProc(var Msg: TMessage); begin ShowScrollBar(ListView_Attributes.Handle, SB_HORZ, False); FListViewWndProc(Msg); end; procedure TForm_AttrSelect.ListView_AttributesClick(Sender: TObject); var hts : THitTests; lvCursosPos : TPoint; li : TListItem; R: TRect; Key: Word; begin inherited; Key := VK_SPACE; //position of the mouse cursor related to ListView lvCursosPos := ListView_Attributes.ScreenToClient(Mouse.CursorPos) ; //click where? hts := ListView_Attributes.GetHitTestInfoAt(lvCursosPos.X, lvCursosPos.Y); //locate the state-clicked item if htOnItem in hts then begin li := ListView_Attributes.GetItemAt(lvCursosPos.X, lvCursosPos.Y); if li <> nil then begin ListView_GetItemRect(ListView_Attributes.Handle, li.Index, R, LVIR_BOUNDS); { Величины R.Width и R.Offset см. в отрисовке значка состояния атрибута } { в процедуре ListView_AttributesDrawItem } R.Width := 16; R.Offset(6, 0); if PtInRect(R, lvCursosPos) then ListView_AttributesKeyDown(ListView_Attributes, Key, []); end; end; end; procedure TForm_AttrSelect.ListView_AttributesData(Sender: TObject; Item: TListItem); var attr: TAttrItem; begin attr := FAttributes[Item.Index]^; Item.Caption := attr.AttrName; Item.SubItems.Add(attr.AttrType); if attr.IsType(FAttrType) then begin if attr.Selected then Item.StateIndex := ATTR_ITEM_SELECTED else Item.StateIndex := ATTR_ITEM_NOT_SELECTED end else Item.StateIndex := ATTR_ITEM_DISABLED_NOT_SELECTED end; procedure TForm_AttrSelect.ListView_AttributesDrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); var C: TCanvas; R: TRect; S: string; ColOrder: array of Integer; SubIndex: Integer; txtAlign: UINT; i: Integer; attr: PADAttribute; begin C := Sender.Canvas; if (odSelected in State) or (FAttributes[Item.Index].Selected) then C.Brush.Color := IncreaseBrightness(COLOR_SELBORDER, 95); C.FillRect(Rect); { Выводим значек состояния атрибута } R := Rect; R.Width := 16; R.Offset(5, 0); ListView_Attributes.StateImages.Draw(c, R.TopLeft.X, R.TopLeft.Y, Item.StateIndex); { Выводим имя атрибута } if not FAttributes[Item.Index].IsType(FAttrType) then C.Font.Color := clGrayText; R := Rect; R.Right := R.Left + Sender.Column[0].Width; R.Inflate(-6, 0); if FAttributes[Item.Index]^.Selected then begin C.Font.Style := [fsBold]; end; C.Refresh; R.Width := R.Width - 22; R.Offset(22, 0); S := Item.Caption; DrawText( C.Handle, S, Length(S), R, DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_END_ELLIPSIS ); { Выводим тип данных атрибуда } ListView_GetSubItemRect(Sender.Handle, Item.Index, 1, 0, @R); R.Inflate(-6, 0); C.Refresh; S := Item.SubItems[0]; DrawText( C.Handle, S, Length(S), R, DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_END_ELLIPSIS ); { Отрисовываем рамку вокруг записи } R := Rect; R.Height := R.Height - 1; R.Width := R.Width - 1; if odSelected in State then begin C.Pen.Color := COLOR_SELBORDER; C.Pen.Width := 1; C.Refresh; C.Polyline( [ R.TopLeft, Point(R.BottomRight.X, R.TopLeft.Y), R.BottomRight, Point(R.TopLeft.X, R.BottomRight.Y), R.TopLeft ] ); end else begin C.Pen.Color := IncreaseBrightness(clBtnFace, 35); C.Pen.Width := 1; C.Refresh; C.Polyline( [ Point(R.TopLeft.X, R.BottomRight.Y), R.BottomRight ] ) end; end; procedure TForm_AttrSelect.ListView_AttributesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var li: TListItem; begin case Key of VK_SPACE: begin li := ListView_Attributes.Selected; if (li <> nil) then if FAttributes[li.Index].IsType(FAttrType) then FAttributes.SelectItem(li.Index); FSelectedAttr := FAttributes[FAttributes.SelectedIndex].AttrName; ListView_Attributes.Invalidate; end; end; end; procedure TForm_AttrSelect.ListView_AttributesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var k: Word; li: TListItem; HitPoint: TPoint; HitInfo: TLVHitTestInfo; MsgRes: Integer; begin if (Button = mbLeft) and (ssDouble in Shift) or (Button = mbLeft) and (ssCtrl in Shift) then begin HitPoint := ListView_Attributes.ScreenToClient(Mouse.Cursorpos); FillChar(HitInfo, SizeOf(TLVHitTestInfo), 0); HitInfo.pt := HitPoint; MsgRes := ListView_Attributes.Perform(LVM_SUBITEMHITTEST, 0, LPARAM(@HitInfo)); if MsgRes <> -1 then begin ListView_Attributes.Selected := ListView_Attributes.Items[HitInfo.iItem]; k := VK_SPACE; ListView_AttributesKeyDown(Sender, k, []); end; end; end; procedure TForm_AttrSelect.ListView_AttributesResize(Sender: TObject); var w: Integer; begin w := ListView_Attributes.ClientWidth; ListView_Attributes.Columns[0].Width := Round(w * 65 / 100); ListView_Attributes.Columns[1].Width := w - ListView_Attributes.Columns[0].Width; end; procedure TForm_AttrSelect.SetAttributeType(AAttrType: string); begin ToolButton_ShowSuitable.Down := AAttrType <> ATTR_TYPE_ANY; with ToolButton_ShowAll do begin Enabled := not (AAttrType = ATTR_TYPE_ANY); Down := AAttrType = ATTR_TYPE_ANY; end; ToolButton_ShowSuitable.Enabled := ToolButton_ShowAll.Enabled; FAttrType := AAttrType; FillAttributeList((FAttrType = ATTR_TYPE_ANY) or (ToolButton_ShowAll.Down)); end; procedure TForm_AttrSelect.SetCallingForm(const Value: TForm); begin FCallingForm := Value; end; procedure TForm_AttrSelect.SetOutputField(Fld: TEdit); begin FOutputField := Fld; FSelectedAttr := Fld.Text; end; procedure TForm_AttrSelect.ToolButton_RefreshClick(Sender: TObject); begin // TDCInfo(ComboBox_DC.Items.Objects[ComboBox_DC.ItemIndex]).RefreshData; FillAttributeList((FAttrType = ATTR_TYPE_ANY) or (ToolButton_ShowAll.Down)); OnShow(Self); end; procedure TForm_AttrSelect.ToolButton_ShowAllClick(Sender: TObject); begin ToolButton_RefreshClick(Self); end; procedure TForm_AttrSelect.ToolButton_ShowSuitableClick(Sender: TObject); begin ToolButton_RefreshClick(Self); end; { TForm_AttrSelect.TAttrItems } function TForm_AttrSelect.TAttrItems.Add(Value: PAttrItem): Integer; begin Result := inherited Add(Value); end; procedure TForm_AttrSelect.TAttrItems.Clear; var i: Integer; begin if FOwnsObjects then for i := Self.Count - 1 downto 0 do Dispose(Self.Items[i]); inherited; end; constructor TForm_AttrSelect.TAttrItems.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TForm_AttrSelect.TAttrItems.Destroy; begin inherited; end; function TForm_AttrSelect.TAttrItems.Get(Index: Integer): PAttrItem; begin Result := PAttrItem(inherited Get(Index)); end; function TForm_AttrSelect.TAttrItems.SelectedIndex: Integer; var i: Integer; begin Result := -1; for i := 0 to Self.Count - 1 do if Self[i]^.Selected then begin Result := i; Break; end; end; procedure TForm_AttrSelect.TAttrItems.SelectItem(AIndex: Integer); var i: Integer; begin if not Self[AIndex]^.Selected then for i:= 0 to Self.Count - 1 do Self.Items[i]^.Selected := i = AIndex; end; { TForm_AttrSelect.TAttrItem } function TForm_AttrSelect.TAttrItem.IsType(const AType: string): Boolean; begin Result := (CompareText(AttrType, AType) = 0) or (CompareText(AType, ATTR_TYPE_ANY) = 0) end; { TComboBox } procedure TComboBox.CN_DrawItem(var Message: TWMDrawItem); begin with Message do DrawItemStruct.itemState := DrawItemStruct.itemState and not ODS_FOCUS; inherited; end; end.