text
stringlengths
14
6.51M
unit ServerSocket; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SocketComp, StdCtrls; type TServerForm = class(TForm) Trace: TEdit; procedure ServerSocketClientRead(Sender: TObject;Socket: TCustomWinSocket); procedure ServerSocketAccept(Sender: TObject;Socket: TCustomWinSocket); procedure FormCreate(Sender: TObject); private { Private declarations } ServerSocket : TServerSocket; fReceivedText : string; fCount : integer; public { Public declarations } end; var ServerForm: TServerForm; implementation {$R *.DFM} procedure TServerForm.ServerSocketClientRead(Sender: TObject;Socket: TCustomWinSocket); begin try fReceivedText := Socket.ReceiveText; inc(fCount, length(fReceivedText)); Caption := IntToStr(fCount); //Trace.Text := fReceivedText; // Socket.SendText( fReceivedText ) except on ESocketError do Trace.Text := 'Error reading from socket' else Trace.Text := 'Unexpected error' end end; procedure TServerForm.ServerSocketAccept(Sender: TObject;Socket: TCustomWinSocket); begin Trace.Text := 'Accepting call'; fCount := 0; end; procedure TServerForm.FormCreate(Sender: TObject); begin ServerSocket := TServerSocket.Create( Self ); ServerSocket.OnAccept := ServerSocketAccept; Serversocket.OnClientRead := ServerSocketClientRead; ServerSocket.Port := 5000; ServerSocket.Active := true end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMailMessage; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows,{$IFDEF DEMO} Forms,{$ENDIF} {$ELSE} System.Classes, System.SysUtils, Winapi.Windows,{$IFDEF DEMO} Vcl.Forms,{$ENDIF} {$ENDIF} clMailHeader, clEncoder, clEmailAddress, clWUtils, clDkim; type TclMessagePriority = (mpLow, mpNormal, mpHigh); TclMessageFormat = (mfNone, mfMIME, mfUUencode); TclMailMessage = class; TclMessageBodies = class; TclMessageBody = class; TclAttachmentBody = class; TclGetBodyStreamEvent = procedure (Sender: TObject; ABody: TclAttachmentBody; var AFileName: string; var AData: TStream; var Handled: Boolean) of object; TclAttachmentSavedEvent = procedure (Sender: TObject; ABody: TclAttachmentBody; const AFileName: string; AData: TStream) of object; TclBodyDataAddedEvent = procedure (Sender: TObject; ABody: TclMessageBody; AData: TStream) of object; TclBodyEncodingProgress = procedure (Sender: TObject; ABody: TclMessageBody; ABytesProceed, ATotalBytes: Int64) of object; TclMessageBody = class(TPersistent) private FOwner: TclMessageBodies; FContentType: string; FEncoding: TclEncodeMethod; FEncoder: TclEncoder; FContentDisposition: string; FExtraFields: TStrings; FKnownFields: TStrings; FRawHeader: TStrings; FEncodedSize: Integer; FEncodedLines: Integer; FEncodedStart: Integer; FRawStart: Integer; procedure SetContentDisposition(const Value: string); procedure SetEncoding(const Value: TclEncodeMethod); procedure DoOnListChanged(Sender: TObject); procedure DoOnEncoderProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); function GetIndex: Integer; procedure SetExtraFields(const Value: TStrings); protected procedure SetContentType(const Value: string); virtual; procedure SetListChangedEvent(AList: TStringList); function GetMailMessage: TclMailMessage; procedure ReadData(Reader: TReader); virtual; procedure WriteData(Writer: TWriter); virtual; function HasEncodedData: Boolean; virtual; procedure AddData(AData: TStream; AEncodedLines: Integer); function GetData: TStream; function GetEncoding: TclEncodeMethod; virtual; procedure AssignBodyHeader(AFieldList: TclMailHeaderFieldList); virtual; procedure ParseBodyHeader(AFieldList: TclMailHeaderFieldList); virtual; function GetSourceStream: TStream; virtual; abstract; function GetDestinationStream: TStream; virtual; abstract; procedure BeforeDataAdded(AData: TStream); virtual; procedure DataAdded(AData: TStream); virtual; procedure DecodeData(ASource, ADestination: TStream); virtual; procedure EncodeData(ASource, ADestination: TStream); virtual; procedure DoCreate; virtual; procedure AssignEncodingIfNeed; virtual; procedure RegisterField(const AField: string); procedure RegisterFields; virtual; property KnownFields: TStrings read FKnownFields; public constructor Create(AOwner: TclMessageBodies); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; procedure Clear(); virtual; property RawHeader: TStrings read FRawHeader; property MailMessage: TclMailMessage read GetMailMessage; property ContentType: string read FContentType write SetContentType; property ContentDisposition: string read FContentDisposition write SetContentDisposition; property Encoding: TclEncodeMethod read GetEncoding write SetEncoding; property Index: Integer read GetIndex; property ExtraFields: TStrings read FExtraFields write SetExtraFields; property EncodedSize: Integer read FEncodedSize; property EncodedLines: Integer read FEncodedLines; property EncodedStart: Integer read FEncodedStart; property RawStart: Integer read FRawStart; end; TclMessageBodyClass = class of TclMessageBody; TclTextBody = class(TclMessageBody) private FCharSet: string; FStrings: TStrings; procedure SetStrings(const Value: TStrings); procedure SetCharSet(const Value: string); procedure DoOnStringsChanged(Sender: TObject); function GetCharSet: string; protected procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; procedure AssignBodyHeader(AFieldList: TclMailHeaderFieldList); override; procedure ParseBodyHeader(AFieldList: TclMailHeaderFieldList); override; function GetSourceStream: TStream; override; function GetDestinationStream: TStream; override; procedure DataAdded(AData: TStream); override; procedure DoCreate; override; public destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; override; property Strings: TStrings read FStrings write SetStrings; property CharSet: string read GetCharSet write SetCharSet; end; TclMultipartBody = class(TclMessageBody) private FSelfMailMessage: TclMailMessage; FContentSubType: string; procedure SetBodies(const Value: TclMessageBodies); procedure SetBoundary(const Value: string); procedure SetContentSubType(const Value: string); function GetBoundary: string; procedure DoOnSaveAttachment(Sender: TObject; ABody: TclAttachmentBody; var AFileName: string; var AStream: TStream; var Handled: Boolean); procedure DoOnLoadAttachment(Sender: TObject; ABody: TclAttachmentBody; var AFileName: string; var AStream: TStream; var Handled: Boolean); procedure DoOnAttachmentSaved(Sender: TObject; ABody: TclAttachmentBody; const AFileName: string; AData: TStream); procedure DoOnDataAdded(Sender: TObject; ABody: TclMessageBody; AData: TStream); procedure FixRawBodyStart(ABodies: TclMessageBodies); function GetBodies: TclMessageBodies; protected procedure SetContentType(const Value: string); override; procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; function HasEncodedData: Boolean; override; procedure AssignBodyHeader(AFieldList: TclMailHeaderFieldList); override; procedure ParseBodyHeader(AFieldList: TclMailHeaderFieldList); override; function GetSourceStream: TStream; override; function GetDestinationStream: TStream; override; procedure DataAdded(AData: TStream); override; procedure DoCreate; override; public destructor Destroy(); override; procedure Assign(Source: TPersistent); override; procedure Clear(); override; property Boundary: string read GetBoundary; property Bodies: TclMessageBodies read GetBodies write SetBodies; property ContentSubType: string read FContentSubType write SetContentSubType; end; TclAttachmentBody = class(TclMessageBody) private FContentID: string; FFileName: string; FCheckFileExists: Boolean; procedure SetContentID(const Value: string); function GetContentID(AFieldList: TclMailHeaderFieldList): string; function GetMessageRfc822FileName(ABodyPos: Integer; ASource: TStrings): string; protected procedure SetFileName(const Value: string); virtual; procedure DataAdded(AData: TStream); override; procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; function GetEncoding: TclEncodeMethod; override; procedure AssignBodyHeader(AFieldList: TclMailHeaderFieldList); override; procedure ParseBodyHeader(AFieldList: TclMailHeaderFieldList); override; function GetSourceStream: TStream; override; function GetDestinationStream: TStream; override; procedure RegisterFields; override; procedure AssignEncodingIfNeed; override; public procedure Assign(Source: TPersistent); override; procedure Clear(); override; property FileName: string read FFileName write SetFileName; property ContentID: string read FContentID write SetContentID; end; TclAttachmentBodyClass = class of TclAttachmentBody; TclImageBody = class(TclAttachmentBody) private function GetUniqueContentID(const AFileName: string): string; function GetFileType(const AFileName: string): string; protected procedure SetFileName(const Value: string); override; procedure AssignBodyHeader(AFieldList: TclMailHeaderFieldList); override; procedure ParseBodyHeader(AFieldList: TclMailHeaderFieldList); override; public procedure Clear(); override; end; TclMessageBodies = class(TPersistent) private FOwner: TclMailMessage; FList: TList; function GetItem(Index: Integer): TclMessageBody; function GetCount: Integer; procedure AddItem(AItem: TclMessageBody); protected procedure DefineProperties(Filer: TFiler); override; procedure ReadData(Reader: TReader); virtual; procedure WriteData(Writer: TWriter); virtual; public constructor Create(AOwner: TclMailMessage); destructor Destroy; override; procedure Assign(Source: TPersistent); override; function Add(AItemClass: TclMessageBodyClass): TclMessageBody; function AddText(const AText: string): TclTextBody; function AddHtml(const AText: string): TclTextBody; function AddMultipart: TclMultipartBody; function AddAttachment(const AFileName: string): TclAttachmentBody; function AddImage(const AFileName: string): TclImageBody; procedure Delete(Index: Integer); procedure Move(CurIndex, NewIndex: Integer); procedure Clear; property Items[Index: Integer]: TclMessageBody read GetItem; default; property Count: Integer read GetCount; property Owner: TclMailMessage read FOwner; end; TclAttachmentList = class private FList: TList; function GetCount: Integer; protected procedure Clear; procedure Add(AItem: TclAttachmentBody); function GetItem(Index: Integer): TclAttachmentBody; public constructor Create; destructor Destroy; override; property Items[Index: Integer]: TclAttachmentBody read GetItem; default; property Count: Integer read GetCount; end; TclImageList = class(TclAttachmentList) private function GetItem(Index: Integer): TclImageBody; public property Items[Index: Integer]: TclImageBody read GetItem; default; end; TclMailMessage = class(TComponent) private FCharSet: string; FSubject: string; FPriority: TclMessagePriority; FDate: TDateTime; FBodies: TclMessageBodies; FBCCList: TclEmailAddressList; FCCList: TclEmailAddressList; FToList: TclEmailAddressList; FFrom: TclEmailAddressItem; FMessageFormat: TclMessageFormat; FBoundary: string; FEncoding: TclEncodeMethod; FHeaderEncoding: TclEncodeMethod; FUpdateCount: Integer; FDataStream: TMemoryStream; FIsParse: Integer; FContentType: string; FContentSubType: string; FHeaderSource: TStrings; FBodiesSource: TStrings; FMessageSource: TStrings; FIncludeRFC822Header: Boolean; FReplyTo: string; FMessageID: string; FExtraFields: TStrings; FNewsGroups: TStrings; FReferences: TStrings; FLinesFieldPos: Integer; FReadReceiptTo: string; FContentDisposition: string; FKnownFields: TStrings; FMimeOLE: string; FRawHeader: TStrings; FCharsPerLine: Integer; FEncodedStart: Integer; FAttachmentList: TclAttachmentList; FImageList: TclImageList; FEmptyList: TStrings; FOnChanged: TNotifyEvent; FOnSaveAttachment: TclGetBodyStreamEvent; FOnLoadAttachment: TclGetBodyStreamEvent; FOnDataAdded: TclBodyDataAddedEvent; FOnAttachmentSaved: TclAttachmentSavedEvent; FOnEncodingProgress: TclBodyEncodingProgress; FAllowESC: Boolean; FDateZoneBias: TDateTime; FDkim: TclDkim; FListUnsubscribe: string; procedure InternalParseHeader(ASource: TStrings); function ParseBodyHeader(AStartFrom: Integer; ASource: TStrings): TclMessageBody; procedure AssignBodyHeader(AStartFrom: Integer; ASource: TStrings; ABody: TclMessageBody); procedure AfterAddData(ABody: TclMessageBody; AEncodedLines: Integer); procedure GetBodyFromSource(const ASource: string); procedure AddBodyToSource(ASource: TStrings; ABody: TclMessageBody); procedure SetBCCList(const Value: TclEmailAddressList); procedure SetBodies(const Value: TclMessageBodies); procedure SetCCList(const Value: TclEmailAddressList); procedure SetToList(const Value: TclEmailAddressList); procedure SetCharSet(const Value: string); procedure SetDate(const Value: TDateTime); procedure SetEncoding(const Value: TclEncodeMethod); procedure SetHeaderEncoding(const Value: TclEncodeMethod); procedure SetFrom(Value: TclEmailAddressItem); procedure SetMessageFormat(const Value: TclMessageFormat); procedure SetPriority(const Value: TclMessagePriority); procedure SetSubject(const Value: string); procedure SetContentSubType(const Value: string); procedure DoOnListChanged(Sender: TObject); function BuildImages(ABodies: TclMessageBodies; const AText, AHtml: string; AImages: TStrings): string; function BuildAlternative(ABodies: TclMessageBodies; const AText, AHtml: string): string; procedure BuildAttachments(ABodies: TclMessageBodies; Attachments: TStrings); function GetHeaderSource: TStrings; function GetBodiesSource: TStrings; function GetMessageSource: TStrings; procedure SetHeaderSource(const Value: TStrings); procedure SetMessageSource(const Value: TStrings); procedure SetIncludeRFC822Header(const Value: Boolean); procedure SetCharsPerLine(const Value: Integer); procedure ParseDate(AFieldList: TclMailHeaderFieldList; var ADate, ADateZoneBias: TDateTime); procedure SetExtraFields(const Value: TStrings); procedure SetNewsGroups(const Value: TStrings); procedure SetReferences(const Value: TStrings); procedure SetReplyTo(const Value: string); function BuildDelimitedField(AValues: TStrings; const ADelimiter: string): string; procedure GetBodyList(ABodies: TclMessageBodies; ABodyType: TclAttachmentBodyClass; AList: TclAttachmentList); procedure SetReadReceiptTo(const Value: string); procedure SetMessageID(const Value: string); procedure SetContentDisposition(const Value: string); procedure SetListUnsubscribe(const Value: string); function IsUUEBodyStart(const ALine: string; var AFileName: string): Boolean; function IsUUEBodyEnd(const ALine: string): Boolean; procedure SetMimeOLE(const Value: string); procedure SetAllowESC(const Value: Boolean); procedure SetISO2022JP; function GetAttachments: TclAttachmentList; function GetHtml: TclTextBody; function GetImages: TclImageList; function GetMessageText: TStrings; function GetText: TclTextBody; function GetCalendar: TclTextBody; function GetIsParse: Boolean; function GetDateUTC: TDateTime; procedure SetDkim(const Value: TclDkim); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure BeginParse; procedure EndParse; procedure SafeClear; virtual; function GetHeaderEncoding: TclEncodeMethod; procedure SetContentType(const Value: string); procedure SetBoundary(const Value: string); procedure ParseBodies(ASource: TStrings); function ParseAllHeaders(AStartFrom: Integer; ASource, AHeaders: TStrings): Integer; procedure ParseExtraFields(AHeader, AKnownFields, AExtraFields: TStrings); procedure InternalAssignBodies(ASource: TStrings); procedure InternalAssignHeader(ASource: TStrings); procedure GenerateBoundary; function CreateBody(ABodies: TclMessageBodies; const AContentType, ADisposition: string): TclMessageBody; virtual; function CreateSingleBody(ASource: TStrings; ABodies: TclMessageBodies): TclMessageBody; virtual; function CreateUUEAttachmentBody(ABodies: TclMessageBodies; const AFileName: string): TclAttachmentBody; virtual; procedure Changed; virtual; procedure DoSaveAttachment(ABody: TclAttachmentBody; var AFileName: string; var AData: TStream; var Handled: Boolean); virtual; procedure DoLoadAttachment(ABody: TclAttachmentBody; var AFileName: string; var AData: TStream; var Handled: Boolean); virtual; procedure DoAttachmentSaved(ABody: TclAttachmentBody; const AFileName: string; AData: TStream); virtual; procedure DoDataAdded(ABody: TclMessageBody; AData: TStream); virtual; procedure DoEncodingProgress(ABody: TclMessageBody; ABytesProceed, ATotalBytes: Int64); virtual; procedure Loaded; override; procedure ParseContentType(AFieldList: TclMailHeaderFieldList); virtual; procedure ParseMimeHeader(AFieldList: TclMailHeaderFieldList); procedure AssignContentType(AFieldList: TclMailHeaderFieldList); virtual; function GetIsMultiPartContent: Boolean; virtual; procedure RegisterField(const AField: string); procedure RegisterFields; virtual; property KnownFields: TStrings read FKnownFields; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; virtual; procedure Update; procedure BeginUpdate; procedure EndUpdate; procedure BuildMessage(const AText, AHtml: string; AImages, Attachments: TStrings); overload; procedure BuildMessage(const AText, AHtml: string; const AImages, Attachments: array of string); overload; procedure BuildMessage(const AText: string; Attachments: TStrings); overload; procedure BuildMessage(const AText: string; const Attachments: array of string); overload; procedure BuildMessage(const AText, AHtml: string); overload; procedure LoadMessage(const AFileName: string); overload; procedure LoadMessage(const AFileName, ACharSet: string); overload; procedure LoadMessage(AStream: TStream); overload; procedure LoadMessage(AStream: TStream; const ACharSet: string); overload; procedure LoadHeader(const AFileName: string); overload; procedure LoadHeader(const AFileName, ACharSet: string); overload; procedure LoadHeader(AStream: TStream); overload; procedure LoadHeader(AStream: TStream; const ACharSet: string); overload; procedure SaveMessage(const AFileName: string); overload; procedure SaveMessage(const AFileName, ACharSet: string); overload; procedure SaveMessage(AStream: TStream); overload; procedure SaveMessage(AStream: TStream; const ACharSet: string); overload; procedure SaveHeader(const AFileName: string); overload; procedure SaveHeader(const AFileName, ACharSet: string); overload; procedure SaveHeader(AStream: TStream); overload; procedure SaveHeader(AStream: TStream; const ACharSet: string); overload; procedure SaveBodies(const AFileName: string); overload; procedure SaveBodies(const AFileName, ACharSet: string); overload; procedure SaveBodies(AStream: TStream); overload; procedure SaveBodies(AStream: TStream; const ACharSet: string); overload; function GetTextBody(ABodies: TclMessageBodies; const AContentType: string): TclTextBody; property RawHeader: TStrings read FRawHeader; property EncodedStart: Integer read FEncodedStart; property IsMultiPartContent: Boolean read GetIsMultiPartContent; property IsParse: Boolean read GetIsParse; property Boundary: string read FBoundary; property HeaderSource: TStrings read GetHeaderSource write SetHeaderSource; property BodiesSource: TStrings read GetBodiesSource; property MessageSource: TStrings read GetMessageSource write SetMessageSource; property IncludeRFC822Header: Boolean read FIncludeRFC822Header write SetIncludeRFC822Header; property Text: TclTextBody read GetText; property Html: TclTextBody read GetHtml; property Calendar: TclTextBody read GetCalendar; property Attachments: TclAttachmentList read GetAttachments; property Images: TclImageList read GetImages; property MessageText: TStrings read GetMessageText; property DateZoneBias: TDateTime read FDateZoneBias; property DateUTC: TDateTime read GetDateUTC; published property Bodies: TclMessageBodies read FBodies write SetBodies; property Subject: string read FSubject write SetSubject; property From: TclEmailAddressItem read FFrom write SetFrom; property ToList: TclEmailAddressList read FToList write SetToList; property CCList: TclEmailAddressList read FCCList write SetCCList; property BCCList: TclEmailAddressList read FBCCList write SetBCCList; property Priority: TclMessagePriority read FPriority write SetPriority default mpNormal; property Date: TDateTime read FDate write SetDate; property CharSet: string read FCharSet write SetCharSet; property ContentType: string read FContentType write SetContentType; property ContentSubType: string read FContentSubType write SetContentSubType; property ContentDisposition: string read FContentDisposition write SetContentDisposition; property MessageFormat: TclMessageFormat read FMessageFormat write SetMessageFormat default mfNone; property Encoding: TclEncodeMethod read FEncoding write SetEncoding default cmNone; property HeaderEncoding: TclEncodeMethod read FHeaderEncoding write SetHeaderEncoding default cmNone; property MimeOLE: string read FMimeOLE write SetMimeOLE; property ReplyTo: string read FReplyTo write SetReplyTo; property References: TStrings read FReferences write SetReferences; property NewsGroups: TStrings read FNewsGroups write SetNewsGroups; property ExtraFields: TStrings read FExtraFields write SetExtraFields; property ReadReceiptTo: string read FReadReceiptTo write SetReadReceiptTo; property MessageID: string read FMessageID write SetMessageID; property ListUnsubscribe: string read FListUnsubscribe write SetListUnsubscribe; property CharsPerLine: Integer read FCharsPerLine write SetCharsPerLine default DefaultCharsPerLine; property AllowESC: Boolean read FAllowESC write SetAllowESC default False; property Dkim: TclDkim read FDkim write SetDkim; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property OnSaveAttachment: TclGetBodyStreamEvent read FOnSaveAttachment write FOnSaveAttachment; property OnLoadAttachment: TclGetBodyStreamEvent read FOnLoadAttachment write FOnLoadAttachment; property OnAttachmentSaved: TclAttachmentSavedEvent read FOnAttachmentSaved write FOnAttachmentSaved; property OnDataAdded: TclBodyDataAddedEvent read FOnDataAdded write FOnDataAdded; property OnEncodingProgress: TclBodyEncodingProgress read FOnEncodingProgress write FOnEncodingProgress; end; procedure RegisterBody(AMessageBodyClass: TclMessageBodyClass); function GetRegisteredBodyItems: TList; function NormalizeFilePath(const APath: string; const AReplaceWith: string = '_'): string; const DefaultContentType = 'text/plain'; DefaultCharSet = 'iso-8859-1'; ISO2022JP = 'iso-2022-jp'; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsMailMessageDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation uses clUtils, clTranslator{$IFDEF LOGGER}, clLogger{$ENDIF}; const ImportanceMap: array[TclMessagePriority] of string = ('Low', '', 'High'); PiorityMap: array[TclMessagePriority] of string = ('5', '', '1'); EncodingMap: array[TclEncodeMethod] of string = ('7bit', 'quoted-printable', 'base64', '', '8bit'); MessageFormatMap: array[Boolean] of TclMessageFormat = (mfUUencode, mfMIME); var RegisteredBodyItems: TList = nil; procedure RegisterBody(AMessageBodyClass: TclMessageBodyClass); begin GetRegisteredBodyItems().Add(AMessageBodyClass); {$IFDEF DELPHIXE2}System.{$ENDIF}Classes.RegisterClass(AMessageBodyClass); end; function GetRegisteredBodyItems: TList; begin if (RegisteredBodyItems = nil) then begin RegisteredBodyItems := TList.Create(); end; Result := RegisteredBodyItems; end; function NormalizeFilePath(const APath, AReplaceWith: string): string; var i: Integer; begin Result := ''; for i := 1 to Length(APath) do begin if CharInSet(APath[i], ['"', '*', '/', ':', '<', '>', '?', '\', '|', #0]) then begin Result := Result + AReplaceWith; end else begin Result := Result + APath[i]; end; end; if (Length(Result) > 0) and CharInSet(Result[Length(Result)], [' ', '.']) then begin Delete(Result, Length(Result), 1); if (Result = '') then begin Result := AReplaceWith; end; end; end; { TclMessageBodies } function TclMessageBodies.AddAttachment(const AFileName: string): TclAttachmentBody; begin Result := TclAttachmentBody.Create(Self); Result.FileName := AFileName; end; function TclMessageBodies.AddHtml(const AText: string): TclTextBody; begin Result := AddText(AText); Result.ContentType := 'text/html'; end; function TclMessageBodies.AddImage(const AFileName: string): TclImageBody; begin Result := TclImageBody.Create(Self); Result.FileName := AFileName; end; procedure TclMessageBodies.AddItem(AItem: TclMessageBody); begin FList.Add(AItem); Owner.Update(); end; function TclMessageBodies.Add(AItemClass: TclMessageBodyClass): TclMessageBody; begin Result := AItemClass.Create(Self); end; function TclMessageBodies.AddMultipart: TclMultipartBody; begin Result := TclMultipartBody.Create(Self); end; function TclMessageBodies.AddText(const AText: string): TclTextBody; begin Result := TclTextBody.Create(Self); Result.Strings.Text := AText; end; procedure TclMessageBodies.Assign(Source: TPersistent); var i: Integer; Item: TclMessageBody; begin Owner.BeginUpdate(); try if (Source is TclMessageBodies) then begin Clear(); for i := 0 to TclMessageBodies(Source).Count - 1 do begin Item := TclMessageBodies(Source).Items[i]; Add(TclMessageBodyClass(Item.ClassType)).Assign(Item); end; end else begin inherited Assign(Source); end; finally Owner.EndUpdate(); end; end; procedure TclMessageBodies.Clear; var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].Free(); end; FList.Clear(); Owner.Update(); end; constructor TclMessageBodies.Create(AOwner: TclMailMessage); begin inherited Create(); Assert(AOwner <> nil); FOwner := AOwner; FList := TList.Create(); end; procedure TclMessageBodies.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('Items', ReadData, WriteData, (FList.Count > 0)); end; procedure TclMessageBodies.Delete(Index: Integer); begin Items[Index].Free(); FList.Delete(Index); Owner.Update(); end; destructor TclMessageBodies.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclMessageBodies.GetCount: Integer; begin Result := FList.Count; end; function TclMessageBodies.GetItem(Index: Integer): TclMessageBody; begin Result := TclMessageBody(FList[Index]); end; procedure TclMessageBodies.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); Owner.Update(); end; procedure TclMessageBodies.ReadData(Reader: TReader); var ItemClass: TclMessageBodyClass; begin Clear(); Reader.ReadListBegin(); while not Reader.EndOfList() do begin ItemClass := TclMessageBodyClass(GetClass(Reader.ReadString())); if (ItemClass <> nil) then begin Add(ItemClass).ReadData(Reader); end; end; Reader.ReadListEnd(); end; procedure TclMessageBodies.WriteData(Writer: TWriter); var i: Integer; begin Writer.WriteListBegin(); for i := 0 to Count - 1 do begin Writer.WriteString(Items[i].ClassName); Items[i].WriteData(Writer); end; Writer.WriteListEnd(); end; { TclMailMessage } procedure TclMailMessage.GenerateBoundary; begin SetBoundary('Mark=_' + IntToStr(Integer(GetTickCount())) + IntToStr(Integer(GetTickCount()) div 2) + IntToStr(Random(1000))); end; procedure TclMailMessage.AssignContentType(AFieldList: TclMailHeaderFieldList); var s: string; begin if (MessageFormat = mfUUencode) then Exit; s := Trim(ContentType); if IsMultiPartContent then begin if (s = '') then begin s := 'multipart/mixed'; end; AFieldList.AddField('Content-Type', s); if (ContentSubType <> '') then begin AFieldList.AddQuotedFieldItem('Content-Type', 'type', ContentSubType); end; AFieldList.AddQuotedFieldItem('Content-Type', 'boundary', Boundary); end else begin if (s = '') then begin s := 'text/plain'; end; AFieldList.AddField('Content-Type', s); if (CharSet <> '') then begin AFieldList.AddQuotedFieldItem('Content-Type', 'charset', CharSet); end; end; end; function TclMailMessage.BuildDelimitedField(AValues: TStrings; const ADelimiter: string): string; var i: Integer; Comma: array[Boolean] of string; begin Result := ''; Comma[False] := ''; Comma[True] := ADelimiter; for i := 0 to AValues.Count - 1 do begin Result := Result + Comma[i > 0] + AValues[i]; end; end; procedure TclMailMessage.InternalAssignHeader(ASource: TStrings); var fieldList: TclMailHeaderFieldList; enc: TclEncodeMethod; begin fieldList := TclMailHeaderFieldList.Create(CharSet, GetHeaderEncoding(), CharsPerLine); try fieldList.Parse(0, ASource); GenerateBoundary(); if IncludeRFC822Header then begin fieldList.AddField('Message-ID', MessageID); fieldList.AddEncodedEmail('From', From.FullAddress); fieldList.AddEncodedEmail('Reply-To', ReplyTo); fieldList.AddField('Newsgroups', BuildDelimitedField(NewsGroups, ',')); fieldList.AddField('References', BuildDelimitedField(References, #32)); fieldList.AddEncodedEmailList('To', ToList); fieldList.AddEncodedEmailList('Cc', CCList); fieldList.AddEncodedEmailList('Bcc', BCCList); fieldList.AddEncodedField('Subject', Subject); fieldList.AddField('Date', DateTimeToMimeTime(Self.Date)); FLinesFieldPos := ASource.Count; if (MessageFormat <> mfUUencode) then begin fieldList.AddField('MIME-Version', '1.0'); end; end; AssignContentType(fieldList); fieldList.AddField('Content-Disposition', ContentDisposition); if not IsMultiPartContent then begin enc := Encoding; if (enc = cmNone) and (Bodies.Count = 1) then begin enc := Bodies[0].Encoding; end; fieldList.AddField('Content-Transfer-Encoding', EncodingMap[enc]); end; if IncludeRFC822Header then begin fieldList.AddField('Importance', ImportanceMap[Priority]); fieldList.AddField('X-Priority', PiorityMap[Priority]); fieldList.AddField('X-MimeOLE', MimeOLE); fieldList.AddEncodedEmail('Disposition-Notification-To', ReadReceiptTo); fieldList.AddNonFoldedField('List-Unsubscribe', ListUnsubscribe); fieldList.AddFields(ExtraFields); end; fieldList.AddEndOfHeader(); finally fieldList.Free(); end; end; function TclMailMessage.ParseAllHeaders(AStartFrom: Integer; ASource, AHeaders: TStrings): Integer; var i: Integer; begin Result := AStartFrom; AHeaders.Clear(); for i := AStartFrom to ASource.Count - 1 do begin Result := i; if (ASource[i] = '') then Break; AHeaders.Add(ASource[i]); end; end; procedure TclMailMessage.ParseContentType(AFieldList: TclMailHeaderFieldList); var s, chrset: string; begin s := AFieldList.GetFieldValue('Content-Type'); MessageFormat := MessageFormatMap[(s <> '') or (AFieldList.GetFieldValue('MIME-Version') <> '')]; ContentType := AFieldList.GetFieldValueItem(s, ''); ContentSubType := AFieldList.GetFieldValueItem(s, 'type'); SetBoundary(AFieldList.GetFieldValueItem(s, 'boundary')); chrset := AFieldList.GetFieldValueItem(s, 'charset'); if (chrset <> '') then begin CharSet := chrset; AFieldList.CharSet := CharSet; end; end; procedure TclMailMessage.ParseMimeHeader(AFieldList: TclMailHeaderFieldList); var s: string; begin BeginParse(); try ParseContentType(AFieldList); s := AFieldList.GetFieldValue('Content-Disposition'); ContentDisposition := AFieldList.GetFieldValueItem(s, ''); s := LowerCase(AFieldList.GetFieldValue('Content-Transfer-Encoding')); Encoding := cmNone; if (s = 'quoted-printable') then begin Encoding := cmQuotedPrintable; end else if (s = 'base64') then begin Encoding := cmBase64; end; AFieldList.Encoding := GetHeaderEncoding(); finally EndParse(); end; end; function TclMailMessage.GetIsParse: Boolean; begin Result := (FIsParse > 0); end; procedure TclMailMessage.InternalParseHeader(ASource: TStrings); procedure AssignPriority(const ASource, ALowLexem, AHighLexem: string); begin if (Priority <> mpNormal) or (ASource = '') then Exit; if (LowerCase(ASource) = LowerCase(ALowLexem)) then begin Priority := mpLow; end else if (LowerCase(ASource) = LowerCase(AHighLexem)) then begin Priority := mpHigh; end; end; var FieldList: TclMailHeaderFieldList; begin BeginParse(); FieldList := nil; try FieldList := TclMailHeaderFieldList.Create(CharSet, GetHeaderEncoding(), CharsPerLine); FieldList.Parse(0, ASource); ParseMimeHeader(FieldList); From.FullAddress := FieldList.GetDecodedEmail('From'); FieldList.GetDecodedEmailList('To', ToList); FieldList.GetDecodedEmailList('Cc', CCList); FieldList.GetDecodedEmailList('Bcc', BCCList); Subject := FieldList.GetDecodedFieldValue('Subject'); try ParseDate(FieldList, FDate, FDateZoneBias); except end; AssignPriority(FieldList.GetFieldValue('Importance'), 'Low', 'High'); AssignPriority(FieldList.GetFieldValue('X-Priority'), '5', '1'); AssignPriority(FieldList.GetFieldValue('X-MSMail-Priority'), 'Low', 'High'); ReplyTo := FieldList.GetDecodedEmail('Reply-To'); ReadReceiptTo := FieldList.GetDecodedEmail('Disposition-Notification-To'); ListUnsubscribe := FieldList.GetDecodedEmail('List-Unsubscribe'); MessageID := FieldList.GetFieldValue('Message-ID'); SplitText(FieldList.GetFieldValue('Newsgroups'), NewsGroups, ','); SplitText(FieldList.GetFieldValue('References'), References, #32); MimeOLE := FieldList.GetFieldValue('X-MimeOLE'); FEncodedStart := ParseAllHeaders(0, ASource, RawHeader) + 1; ParseExtraFields(RawHeader, FKnownFields, ExtraFields); finally FieldList.Free(); EndParse(); end; end; procedure TclMailMessage.RegisterField(const AField: string); begin if (FindInStrings(FKnownFields, AField) < 0) then begin FKnownFields.Add(AField); end; end; procedure TclMailMessage.RegisterFields; begin RegisterField('Content-Type'); RegisterField('Content-Disposition'); RegisterField('Content-Transfer-Encoding'); RegisterField('From'); RegisterField('To'); RegisterField('Cc'); RegisterField('Bcc'); RegisterField('Subject'); RegisterField('Date'); RegisterField('Importance'); RegisterField('X-Priority'); RegisterField('X-MSMail-Priority'); RegisterField('X-MimeOLE'); RegisterField('Reply-To'); RegisterField('Disposition-Notification-To'); RegisterField('Message-ID'); RegisterField('MIME-Version'); RegisterField('Newsgroups'); RegisterField('References'); end; procedure TclMailMessage.ParseExtraFields(AHeader, AKnownFields, AExtraFields: TStrings); var i: Integer; FieldList: TclMailHeaderFieldList; begin FieldList := TclMailHeaderFieldList.Create(CharSet, GetHeaderEncoding(), CharsPerLine); try AExtraFields.Clear(); FieldList.Parse(0, AHeader); for i := 0 to FieldList.FieldList.Count - 1 do begin if (FindInStrings(AKnownFields, FieldList.FieldList[i]) < 0) then begin AExtraFields.Add(FieldList.GetFieldName(i) + ': ' + FieldList.GetFieldValue(i)); end; end; finally FieldList.Free(); end; end; procedure TclMailMessage.ParseDate(AFieldList: TclMailHeaderFieldList; var ADate, ADateZoneBias: TDateTime); var ind: Integer; s: string; begin ADate := Now(); ADateZoneBias := TimeZoneBiasToDateTime(TimeZoneBiasString()); s := AFieldList.GetDecodedFieldValue('Date');//TODO change to FieldValue and test if (s <> '') then begin ParseMimeTime(s, ADate, ADateZoneBias); end else begin s := AFieldList.GetDecodedFieldValue('Received');//TODO change to FieldValue and test ind := RTextPos(';', s); if (ind > 0) then begin ParseMimeTime(Trim(System.Copy(s, ind + 1, 1000)), ADate, ADateZoneBias); end; end; end; procedure TclMailMessage.InternalAssignBodies(ASource: TStrings); var i: Integer; begin if (FBoundary = '') then begin GenerateBoundary(); end; for i := 0 to FBodies.Count - 1 do begin if (MessageFormat <> mfUUencode) and IsMultiPartContent then begin ASource.Add('--' + Boundary); AssignBodyHeader(ASource.Count, ASource, Bodies[i]); ASource.Add(''); end; AddBodyToSource(ASource, Bodies[i]); if IsMultiPartContent then begin ASource.Add(''); end; end; if (MessageFormat <> mfUUencode) and IsMultiPartContent then begin ASource.Add('--' + Boundary + '--'); end; end; procedure TclMailMessage.AssignBodyHeader(AStartFrom: Integer; ASource: TStrings; ABody: TclMessageBody); var fieldList: TclMailHeaderFieldList; begin fieldList := TclMailHeaderFieldList.Create(CharSet, GetHeaderEncoding(), CharsPerLine); try fieldList.Parse(AStartFrom, ASource); ABody.AssignBodyHeader(fieldList); finally fieldList.Free(); end; end; function TclMailMessage.CreateBody(ABodies: TclMessageBodies; const AContentType, ADisposition: string): TclMessageBody; begin if (system.Pos('multipart/', LowerCase(AContentType)) = 1) then begin Result := TclMultipartBody.Create(ABodies); end else if (system.Pos('image/', LowerCase(AContentType)) = 1) and (LowerCase(ADisposition) <> 'attachment') then begin Result := TclImageBody.Create(ABodies); end else if (LowerCase(ADisposition) = 'attachment') or (system.Pos('application/', LowerCase(AContentType)) = 1) or (system.Pos('message/', LowerCase(AContentType)) = 1) or (system.Pos('audio/', LowerCase(AContentType)) = 1) or (system.Pos('video/', LowerCase(AContentType)) = 1) or (system.Pos('image/', LowerCase(AContentType)) = 1) then begin Result := TclAttachmentBody.Create(ABodies); end else if (system.Pos('text/', LowerCase(AContentType)) = 1) then begin Result := TclTextBody.Create(ABodies); end else begin Result := TclAttachmentBody.Create(ABodies); end; end; function TclMailMessage.ParseBodyHeader(AStartFrom: Integer; ASource: TStrings): TclMessageBody; var ContType, Disposition: string; FieldList: TclMailHeaderFieldList; begin FieldList := TclMailHeaderFieldList.Create(CharSet, GetHeaderEncoding(), CharsPerLine); try FieldList.Parse(AStartFrom, ASource); ContType := FieldList.GetFieldValue('Content-Type'); Disposition := FieldList.GetFieldValue('Content-Disposition'); Result := CreateBody(Bodies, FieldList.GetFieldValueItem(ContType, ''), FieldList.GetFieldValueItem(Disposition, '')); Result.ParseBodyHeader(FieldList); finally FieldList.Free(); end; end; procedure TclMailMessage.AddBodyToSource(ASource: TStrings; ABody: TclMessageBody); var Src: TStream; stringsUtils: TclStringsUtils; begin if (MessageFormat = mfUUencode) and (ABody is TclAttachmentBody) then begin ASource.Add('begin 644 ' + ExtractFileName(TclAttachmentBody(ABody).FileName)); end; Src := nil; stringsUtils := nil; try Src := ABody.GetData(); stringsUtils := TclStringsUtils.Create(ASource); stringsUtils.OnProgress := ABody.DoOnEncoderProgress; stringsUtils.AddTextStream(Src); finally stringsUtils.Free(); Src.Free(); end; if (MessageFormat = mfUUencode) and (ABody is TclAttachmentBody) then begin ASource.Add('end'); end; end; procedure TclMailMessage.AfterAddData(ABody: TclMessageBody; AEncodedLines: Integer); begin if (ABody <> nil) and (FDataStream.Size > 0) then begin try FDataStream.Position := 0; ABody.AddData(FDataStream, AEncodedLines); finally FDataStream.Clear(); end; end; end; procedure TclMailMessage.GetBodyFromSource(const ASource: string); var buf: TclByteArray; begin buf := TclTranslator.GetBytes(ASource); if (Length(buf) > 0) then begin FDataStream.Write(buf[0], Length(buf)); end; end; procedure TclMailMessage.GetBodyList(ABodies: TclMessageBodies; ABodyType: TclAttachmentBodyClass; AList: TclAttachmentList); var i: Integer; begin for i := 0 to ABodies.Count - 1 do begin if (ABodies[i] is TclMultipartBody) then begin GetBodyList(TclMultipartBody(ABodies[i]).Bodies, ABodyType, AList); end else if (ABodies[i].ClassType = ABodyType) then begin AList.Add(TclAttachmentBody(ABodies[i])); end; end; end; function TclMailMessage.GetCalendar: TclTextBody; begin Result := GetTextBody(Bodies, 'text/calendar'); end; function TclMailMessage.GetDateUTC: TDateTime; begin Result := Date; Result := Result - DateZoneBias; end; function TclMailMessage.IsUUEBodyStart(const ALine: string; var AFileName: string): Boolean; var ind: Integer; s: string; begin AFileName := ''; Result := (system.Pos('begin', LowerCase(ALine)) = 1); if Result then begin Result := False; ind := system.Pos(#32, ALine); if (ind > 0) then begin s := TrimLeft(system.Copy(ALine, ind + 1, 1000)); ind := system.Pos(#32, s); Result := (ind > 0) and (StrToIntDef(Trim(system.Copy(s, 1, ind)), -1) > -1); if Result then begin AFileName := Trim(system.Copy(s, ind + 1, 1000)); end; end; end; end; function TclMailMessage.IsUUEBodyEnd(const ALine: string): Boolean; begin Result := (Trim(LowerCase(ALine)) = 'end'); end; function TclMailMessage.CreateUUEAttachmentBody(ABodies: TclMessageBodies; const AFileName: string): TclAttachmentBody; begin Result := Bodies.AddAttachment(AFileName); Result.Encoding := cmUUEncode; end; procedure TclMailMessage.ParseBodies(ASource: TStrings); procedure ParseMultiPartBodies(ASource: TStrings); var i, StartBody: Integer; s: string; BodyItem: TclMessageBody; begin BodyItem := nil; StartBody := 0; s := ''; for i := 0 to ASource.Count - 1 do begin if (('--' + Boundary) = ASource[i]) or (('--' + Boundary + '--') = ASource[i]) then begin if (BodyItem <> nil) and (i > StartBody) then begin GetBodyFromSource(s + #13#10); end; AfterAddData(BodyItem, i - StartBody); BodyItem := nil; if (('--' + Boundary + '--') <> ASource[i]) then begin BodyItem := ParseBodyHeader(i, ASource); StartBody := ParseAllHeaders(i + 1, ASource, BodyItem.RawHeader); BodyItem.FRawStart := i + 1; BodyItem.FEncodedStart := StartBody + 1; ParseExtraFields(BodyItem.RawHeader, BodyItem.FKnownFields, BodyItem.ExtraFields); if (StartBody < ASource.Count - 1) then begin Inc(StartBody); end; s := ASource[StartBody]; end; end else begin if (BodyItem <> nil) and (i > StartBody) then begin GetBodyFromSource(s + #13#10); s := ASource[i]; end; end; end; if (BodyItem <> nil) then begin GetBodyFromSource(s + #13#10); end; AfterAddData(BodyItem, ASource.Count - 1 - StartBody); end; procedure ParseSingleBody(ASource: TStrings); var i, bodyStart: Integer; singleBodyItem, BodyItem: TclMessageBody; fileName: string; begin bodyStart := 0; BodyItem := nil; singleBodyItem := nil; for i := 0 to ASource.Count - 1 do begin if (ASource[i] = '') and (singleBodyItem = nil) then begin singleBodyItem := CreateSingleBody(ASource, Bodies); bodyStart := i; singleBodyItem.FRawStart := 0; singleBodyItem.FEncodedStart := bodyStart + 1; end else if (singleBodyItem <> nil) then begin if IsUUEBodyStart(ASource[i], fileName) then begin MessageFormat := mfUUencode; if (BodyItem <> nil) then begin AfterAddData(BodyItem, 0); end else begin AfterAddData(singleBodyItem, 0); end; BodyItem := CreateUUEAttachmentBody(Bodies, fileName); end else if (MessageFormat = mfUUencode) and IsUUEBodyEnd(ASource[i]) then begin AfterAddData(BodyItem, 0); BodyItem := nil; end else begin GetBodyFromSource(ASource[i] + #13#10); end; end; end; AfterAddData(singleBodyItem, ASource.Count - 1 - bodyStart); end; procedure RemoveEmptySingleBody; var i: Integer; begin for i := Bodies.Count - 1 downto 0 do begin if (Bodies[i] is TclTextBody) and (Trim(TclTextBody(Bodies[i]).Strings.Text) = '') then begin Bodies.Delete(i); end; end; end; begin BeginParse(); try if IsMultiPartContent then begin ParseMultiPartBodies(ASource); if (Bodies.Count = 0) then begin ParseSingleBody(ASource); RemoveEmptySingleBody(); end; end else begin ParseSingleBody(ASource); RemoveEmptySingleBody(); end; finally EndParse(); end; end; procedure TclMailMessage.DoOnListChanged(Sender: TObject); begin Update(); end; constructor TclMailMessage.Create(AOwner: TComponent); procedure SetListChangedEvent(AList: TStringList); begin AList.OnChange := DoOnListChanged; end; begin inherited Create(AOwner); FAttachmentList := TclAttachmentList.Create(); FImageList := TclImageList.Create(); FHeaderSource := TStringList.Create(); FBodiesSource := TStringList.Create(); FMessageSource := TStringList.Create(); FDataStream := TMemoryStream.Create(); FUpdateCount := 0; FBodies := TclMessageBodies.Create(Self); FFrom := TclEmailAddressItem.Create(); FBCCList := TclEmailAddressList.Create(Self, TclEmailAddressItem); FCCList := TclEmailAddressList.Create(Self, TclEmailAddressItem); FToList := TclEmailAddressList.Create(Self, TclEmailAddressItem); FIncludeRFC822Header := True; FReferences := TStringList.Create(); SetListChangedEvent(FReferences as TStringList); FNewsGroups := TStringList.Create(); SetListChangedEvent(FNewsGroups as TStringList); FExtraFields := TStringList.Create(); SetListChangedEvent(FExtraFields as TStringList); FKnownFields := TStringList.Create(); RegisterFields(); FRawHeader := TStringList.Create(); FCharsPerLine := DefaultCharsPerLine; FEmptyList := nil; Clear(); end; destructor TclMailMessage.Destroy; begin FEmptyList.Free(); FRawHeader.Free(); FKnownFields.Free(); FExtraFields.Free(); FNewsGroups.Free(); FReferences.Free(); FToList.Free(); FCCList.Free(); FBCCList.Free(); FFrom.Free(); FBodies.Free(); FDataStream.Free(); FMessageSource.Free(); FBodiesSource.Free(); FHeaderSource.Free(); FImageList.Free(); FAttachmentList.Free(); inherited Destroy(); end; procedure TclMailMessage.SetAllowESC(const Value: Boolean); begin if (FAllowESC <> Value) then begin FAllowESC := Value; Update(); end; end; procedure TclMailMessage.SetBCCList(const Value: TclEmailAddressList); begin FBCCList.Assign(Value); Update(); end; procedure TclMailMessage.SetBodies(const Value: TclMessageBodies); begin FBodies.Assign(Value); end; procedure TclMailMessage.SetCCList(const Value: TclEmailAddressList); begin FCCList.Assign(Value); Update(); end; procedure TclMailMessage.SetToList(const Value: TclEmailAddressList); begin FToList.Assign(Value); Update(); end; function TclMailMessage.GetImages: TclImageList; begin if (FImageList.Count = 0) then begin GetBodyList(Bodies, TclImageBody, FImageList); end; Result := FImageList; end; function TclMailMessage.GetIsMultiPartContent: Boolean; begin Result := (Bodies.Count > 1) or (system.Pos('multipart/', LowerCase(FContentType)) = 1); end; procedure TclMailMessage.Clear; begin BeginUpdate(); try SetBoundary(''); Subject := ''; From.Clear(); ToList.Clear(); CCList.Clear(); BCCList.Clear(); Priority := mpNormal; Date := Now(); Bodies.Clear(); MessageFormat := mfNone; ContentType := DefaultContentType; ContentSubType := ''; MimeOLE := ''; FMessageID := ''; ReplyTo := ''; References.Clear(); NewsGroups.Clear(); ExtraFields.Clear(); ReadReceiptTo := ''; ListUnsubscribe := ''; ContentDisposition := ''; RawHeader.Clear(); FEncodedStart := 0; CharSet := DefaultCharSet; Encoding := cmNone; HeaderEncoding := cmNone; finally EndUpdate(); end; end; procedure TclMailMessage.Changed; begin if Assigned(OnChanged) then begin OnChanged(Self); end; end; procedure TclMailMessage.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin if (LowerCase(Value) = ISO2022JP) then begin SetISO2022JP(); end else begin FCharSet := Value; end; Update(); end; end; procedure TclMailMessage.SetDate(const Value: TDateTime); begin if (FDate <> Value) then begin FDate := Value; FDateZoneBias := TimeZoneBiasToDateTime(TimeZoneBiasString()); Update(); end; end; procedure TclMailMessage.SetDkim(const Value: TclDkim); begin if (FDkim <> Value) then begin if (FDkim <> nil) then begin FDkim.RemoveFreeNotification(Self); end; FDkim := Value; if (FDkim <> nil) then begin FDkim.FreeNotification(Self); end; end; end; procedure TclMailMessage.SetEncoding(const Value: TclEncodeMethod); begin if (FEncoding <> Value) then begin FEncoding := Value; Update(); end; end; procedure TclMailMessage.SetFrom(Value: TclEmailAddressItem); begin FFrom.Assign(Value); Update(); end; procedure TclMailMessage.SetMessageFormat(const Value: TclMessageFormat); begin if (FMessageFormat <> Value) then begin FMessageFormat := Value; Update(); end; end; procedure TclMailMessage.SetPriority(const Value: TclMessagePriority); begin if (FPriority <> Value) then begin FPriority := Value; Update(); end; end; procedure TclMailMessage.SetSubject(const Value: string); begin if (FSubject <> Value) then begin FSubject := Value; Update(); end; end; procedure TclMailMessage.BeginUpdate; begin Inc(FUpdateCount); end; procedure TclMailMessage.EndUpdate; begin if (FUpdateCount > 0) then begin Dec(FUpdateCount); end; Update(); end; procedure TclMailMessage.Update; begin if (not (csDestroying in ComponentState)) and (not (csLoading in ComponentState)) and (not (csDesigning in ComponentState)) and (FUpdateCount = 0) then begin FAttachmentList.Clear(); FImageList.Clear(); FHeaderSource.Clear(); FBodiesSource.Clear(); FMessageSource.Clear(); Changed(); end; end; procedure TclMailMessage.DoSaveAttachment(ABody: TclAttachmentBody; var AFileName: string; var AData: TStream; var Handled: Boolean); begin if Assigned(OnSaveAttachment) then begin OnSaveAttachment(Self, ABody, AFileName, AData, Handled); end; end; procedure TclMailMessage.DoAttachmentSaved(ABody: TclAttachmentBody; const AFileName: string; AData: TStream); begin if Assigned(OnAttachmentSaved) then begin OnAttachmentSaved(Self, ABody, AFileName, AData); end; end; procedure TclMailMessage.DoDataAdded(ABody: TclMessageBody; AData: TStream); begin if Assigned(OnDataAdded) then begin OnDataAdded(Self, ABody, AData); end; end; procedure TclMailMessage.DoEncodingProgress(ABody: TclMessageBody; ABytesProceed, ATotalBytes: Int64); begin if Assigned(OnEncodingProgress) then begin OnEncodingProgress(Self, ABody, ABytesProceed, ATotalBytes); end; end; procedure TclMailMessage.Loaded; begin inherited Loaded(); Update(); end; procedure TclMailMessage.LoadHeader(AStream: TStream; const ACharSet: string); var src: TStrings; begin src := TclStringsUtils.LoadStrings(AStream, ACharSet); try HeaderSource := src; finally src.Free(); end; end; procedure TclMailMessage.LoadHeader(const AFileName, ACharSet: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadHeader(stream, ACharSet); finally stream.Free(); end; end; procedure TclMailMessage.SetContentType(const Value: string); begin if (FContentType <> Value) then begin FContentType := Value; Update(); end; end; function TclMailMessage.GetHeaderEncoding: TclEncodeMethod; begin Result := HeaderEncoding; if (Result = cmNone) then begin Result := Encoding; end; end; function TclMailMessage.GetHeaderSource: TStrings; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (FHeaderSource.Count = 0) then begin InternalAssignHeader(FHeaderSource); end; Result := FHeaderSource; end; function TclMailMessage.GetHtml: TclTextBody; begin Result := GetTextBody(Bodies, 'text/html'); end; procedure TclMailMessage.SetBoundary(const Value: string); begin if (FBoundary <> Value) then begin FBoundary := Value; Update(); end; end; function TclMailMessage.BuildImages(ABodies: TclMessageBodies; const AText, AHtml: string; AImages: TStrings): string; var i: Integer; Multipart: TclMultipartBody; HtmlWithImages: string; ImageBody: TclImageBody; begin HtmlWithImages := AHtml; for i := 0 to AImages.Count - 1 do begin ImageBody := ABodies.AddImage(AImages[i]); HtmlWithImages := StringReplace(HtmlWithImages, ImageBody.FileName, 'cid:' + ImageBody.ContentID, [rfReplaceAll, rfIgnoreCase]); end; if (AText <> '') and (AHtml <> '') then begin Multipart := ABodies.AddMultipart(); Multipart.ContentType := BuildAlternative(Multipart.Bodies, AText, HtmlWithImages); Result := Multipart.ContentType; end else begin Result := BuildAlternative(ABodies, AText, HtmlWithImages); end; ABodies.Move(ABodies.Count - 1, 0); end; procedure TclMailMessage.BuildAttachments(ABodies: TclMessageBodies; Attachments: TStrings); var i: Integer; begin for i := 0 to Attachments.Count - 1 do begin ABodies.AddAttachment(Attachments[i]); end; end; function TclMailMessage.BuildAlternative(ABodies: TclMessageBodies; const AText, AHtml: string): string; var cnt: Integer; begin cnt := 0; Result := ''; if (AText <> '') then begin Inc(cnt); ABodies.AddText(AText); Result := 'text/plain'; end; if (AHtml <> '') then begin Inc(cnt); ABodies.AddHtml(AHtml); Result := 'text/html'; end; if (cnt > 1) then begin Result := 'multipart/alternative'; end; end; procedure TclMailMessage.BuildMessage(const AText, AHtml: string; AImages, Attachments: TStrings); var Multipart: TclMultipartBody; dummyImg, dummyAttach: TStrings; begin dummyImg := nil; dummyAttach := nil; try if (AImages = nil) then begin dummyImg := TStringList.Create(); AImages := dummyImg; end; if (Attachments = nil) then begin dummyAttach := TStringList.Create(); Attachments := dummyAttach; end; Assert((AText <> '') or (AHtml <> '') or (Attachments.Count > 0)); Assert((AImages.Count = 0) or (AHtml <> '')); BeginUpdate(); try SafeClear(); if (AImages.Count = 0) and (Attachments.Count = 0) then begin ContentType := BuildAlternative(Bodies, AText, AHtml); end else if (AImages.Count = 0) and (Attachments.Count > 0) then begin if (AText <> '') and (AHtml <> '') then begin Multipart := Bodies.AddMultipart(); Multipart.ContentType := BuildAlternative(Multipart.Bodies, AText, AHtml); end else begin BuildAlternative(Bodies, AText, AHtml); if (Bodies.Count = 0) then begin Bodies.AddText(''); end; end; BuildAttachments(Bodies, Attachments); ContentType := 'multipart/mixed'; end else if (AImages.Count > 0) and (Attachments.Count = 0) then begin ContentSubType := BuildImages(Bodies, AText, AHtml, AImages); ContentType := 'multipart/related'; end else if (AImages.Count > 0) and (Attachments.Count > 0) then begin Multipart := Bodies.AddMultipart(); Multipart.ContentSubType := BuildImages(Multipart.Bodies, AText, AHtml, AImages); Multipart.ContentType := 'multipart/related'; BuildAttachments(Bodies, Attachments); ContentType := 'multipart/mixed'; end else begin Assert(False); end; finally EndUpdate(); end; finally dummyAttach.Free(); dummyImg.Free(); end; end; procedure TclMailMessage.SetContentSubType(const Value: string); begin if (FContentSubType <> Value) then begin FContentSubType := Value; Update(); end; end; procedure TclMailMessage.BuildMessage(const AText, AHtml: string); begin BuildMessage(AText, AHtml, nil, nil); end; procedure TclMailMessage.BuildMessage(const AText: string; Attachments: TStrings); begin BuildMessage(AText, '', nil, Attachments); end; procedure TclMailMessage.LoadMessage(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadMessage(stream, ''); finally stream.Free(); end; end; procedure TclMailMessage.LoadMessage(AStream: TStream); begin LoadMessage(AStream, ''); end; procedure TclMailMessage.LoadHeader(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadHeader(stream, ''); finally stream.Free(); end; end; procedure TclMailMessage.LoadHeader(AStream: TStream); begin LoadHeader(AStream, ''); end; procedure TclMailMessage.LoadMessage(AStream: TStream; const ACharSet: string); var src: TStrings; begin src := TclStringsUtils.LoadStrings(AStream, ACharSet); try MessageSource := src; finally src.Free(); end; end; procedure TclMailMessage.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FDkim) and (Operation = opRemove) then begin FDkim := nil; end; end; procedure TclMailMessage.LoadMessage(const AFileName, ACharSet: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadMessage(stream, ACharSet); finally stream.Free(); end; end; procedure TclMailMessage.SaveMessage(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try SaveMessage(stream, ''); finally stream.Free(); end; end; procedure TclMailMessage.SaveMessage(AStream: TStream); begin SaveMessage(AStream, ''); end; procedure TclMailMessage.SaveMessage(const AFileName, ACharSet: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try SaveMessage(stream, ACharSet); finally stream.Free(); end; end; procedure TclMailMessage.SaveHeader(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try SaveHeader(stream, ''); finally stream.Free(); end; end; procedure TclMailMessage.SaveHeader(AStream: TStream); begin SaveHeader(AStream, ''); end; procedure TclMailMessage.SaveBodies(const AFileName: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try SaveBodies(stream, ''); finally stream.Free(); end; end; procedure TclMailMessage.SaveBodies(AStream: TStream); begin SaveBodies(AStream, ''); end; procedure TclMailMessage.SaveBodies(const AFileName, ACharSet: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try SaveBodies(stream, ACharSet); finally stream.Free(); end; end; procedure TclMailMessage.SaveHeader(const AFileName, ACharSet: string); var stream: TStream; begin stream := TFileStream.Create(AFileName, fmCreate); try SaveHeader(stream, ACharSet); finally stream.Free(); end; end; function TclMailMessage.GetAttachments: TclAttachmentList; begin if (FAttachmentList.Count = 0) then begin GetBodyList(Bodies, TclAttachmentBody, FAttachmentList); end; Result := FAttachmentList; end; function TclMailMessage.GetBodiesSource: TStrings; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (FBodiesSource.Count = 0) then begin InternalAssignBodies(FBodiesSource); end; Result := FBodiesSource; end; function TclMailMessage.GetMessageSource: TStrings; var lines: Integer; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetMessageSource');{$ENDIF} if (FMessageSource.Count = 0) then begin FLinesFieldPos := 0; InternalAssignHeader(FMessageSource); if IsMultiPartContent and (MessageFormat <> mfUUencode) then begin FMessageSource.Add('This is a multi-part message in MIME format.'); FMessageSource.Add(''); end; lines := FMessageSource.Count; InternalAssignBodies(FMessageSource); lines := FMessageSource.Count - lines; if (NewsGroups.Count > 0) and (FLinesFieldPos > 0) then begin FMessageSource.Insert(FLinesFieldPos, 'Lines: ' + IntToStr(lines)); end; if (Dkim <> nil) then begin Dkim.Sign(FMessageSource); end; {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GetMessageSource message re-composed');{$ENDIF} end; Result := FMessageSource; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetMessageSource'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetMessageSource', E); raise; end; end;{$ENDIF} end; function TclMailMessage.GetMessageText: TStrings; var body: TclTextBody; begin body := Html; if (body = nil) then begin body := Text; end; if (body = nil) then begin body := GetTextBody(Bodies, ''); end; if (body = nil) then begin if (FEmptyList = nil) then begin FEmptyList := TStringList.Create(); end; Result := FEmptyList; end else begin Result := body.Strings; end; end; function TclMailMessage.GetText: TclTextBody; begin Result := GetTextBody(Bodies, 'text/plain'); end; procedure TclMailMessage.SetHeaderEncoding(const Value: TclEncodeMethod); begin if (FHeaderEncoding <> Value) then begin FHeaderEncoding := Value; Update(); end; end; procedure TclMailMessage.SetHeaderSource(const Value: TStrings); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} BeginUpdate(); try SafeClear(); InternalParseHeader(Value); finally EndUpdate(); end; end; procedure TclMailMessage.SetMessageSource(const Value: TStrings); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} BeginUpdate(); try SafeClear(); InternalParseHeader(Value); ParseBodies(Value); if (Dkim <> nil) then begin Dkim.Verify(Value); end; finally EndUpdate(); end; end; function TclMailMessage.CreateSingleBody(ASource: TStrings; ABodies: TclMessageBodies): TclMessageBody; var FieldList: TclMailHeaderFieldList; begin FieldList := TclMailHeaderFieldList.Create(CharSet, GetHeaderEncoding(), CharsPerLine); try FieldList.Parse(0, ASource); if (LowerCase(ContentDisposition) = 'attachment') or (system.Pos('application/', LowerCase(ContentType)) = 1) or (system.Pos('message/', LowerCase(ContentType)) = 1) or (system.Pos('audio/', LowerCase(ContentType)) = 1) or (system.Pos('video/', LowerCase(ContentType)) = 1) then begin Result := TclAttachmentBody.Create(ABodies); end else begin Result := TclTextBody.Create(ABodies); end; Result.ParseBodyHeader(FieldList); ParseAllHeaders(0, ASource, Result.RawHeader); ParseExtraFields(Result.RawHeader, Result.KnownFields, Result.ExtraFields); finally FieldList.Free(); end; end; procedure TclMailMessage.SetIncludeRFC822Header(const Value: Boolean); begin if (FIncludeRFC822Header <> Value) then begin FIncludeRFC822Header := Value; Update(); end; end; procedure TclMailMessage.SetISO2022JP; begin FCharSet := ISO2022JP; FEncoding := cm8Bit; FAllowESC := True; end; procedure TclMailMessage.SetListUnsubscribe(const Value: string); begin if (FListUnsubscribe <> Value) then begin FListUnsubscribe := Value; Update(); end; end; procedure TclMailMessage.SetExtraFields(const Value: TStrings); begin FExtraFields.Assign(Value); end; procedure TclMailMessage.SetNewsGroups(const Value: TStrings); begin FNewsGroups.Assign(Value); end; procedure TclMailMessage.SetReferences(const Value: TStrings); begin FReferences.Assign(Value); end; procedure TclMailMessage.SetReplyTo(const Value: string); begin if (FReplyTo <> Value) then begin FReplyTo := Value; Update(); end; end; function TclMailMessage.GetTextBody(ABodies: TclMessageBodies; const AContentType: string): TclTextBody; var i: Integer; begin for i := 0 to ABodies.Count - 1 do begin if (ABodies[i] is TclMultipartBody) then begin Result := GetTextBody((ABodies[i] as TclMultipartBody).Bodies, AContentType); if (Result <> nil) then Exit; end else if (ABodies[i] is TclTextBody) and ((AContentType = '') or SameText(ABodies[i].ContentType, AContentType)) then begin Result := TclTextBody(ABodies[i]); Exit; end; end; Result := nil; end; procedure TclMailMessage.SetReadReceiptTo(const Value: string); begin if (FReadReceiptTo <> Value) then begin FReadReceiptTo := Value; Update(); end; end; procedure TclMailMessage.SetMessageID(const Value: string); begin if (FMessageID <> Value) then begin FMessageID := Value; Update(); end; end; procedure TclMailMessage.DoLoadAttachment(ABody: TclAttachmentBody; var AFileName: string; var AData: TStream; var Handled: Boolean); begin if Assigned(OnLoadAttachment) then begin OnLoadAttachment(Self, ABody, AFileName, AData, Handled); {$IFDEF LOGGER} if (AData <> nil) then begin clPutLogMessage(Self, edInside, 'DoLoadAttachment: FileName="%s" (AData <> nil) Handled=%d', nil, [AFileName, Integer(Handled)]); end else begin clPutLogMessage(Self, edInside, 'DoLoadAttachment: FileName="%s" (AData = nil) Handled=%d', nil, [AFileName, Integer(Handled)]); end; {$ENDIF} end; end; procedure TclMailMessage.BuildMessage(const AText: string; const Attachments: array of string); var i: Integer; list: TStrings; begin list := TStringList.Create(); try for i := Low(Attachments) to High(Attachments) do begin list.Add(Attachments[i]); end; BuildMessage(AText, list); finally list.Free(); end; end; procedure TclMailMessage.BuildMessage(const AText, AHtml: string; const AImages, Attachments: array of string); var i: Integer; imgs, attachs: TStrings; begin imgs := TStringList.Create(); attachs := TStringList.Create(); try for i := Low(AImages) to High(AImages) do begin imgs.Add(AImages[i]); end; for i := Low(Attachments) to High(Attachments) do begin attachs.Add(Attachments[i]); end; BuildMessage(AText, AHtml, imgs, attachs); finally attachs.Free(); imgs.Free(); end; end; procedure TclMailMessage.SetContentDisposition(const Value: string); begin if (FContentDisposition <> Value) then begin FContentDisposition := Value; Update(); end; end; procedure TclMailMessage.SetMimeOLE(const Value: string); begin if (FMimeOLE <> Value) then begin FMimeOLE := Value; Update(); end; end; procedure TclMailMessage.SetCharsPerLine(const Value: Integer); begin if (FCharsPerLine <> Value) then begin FCharsPerLine := Value; Update(); end; end; procedure TclMailMessage.BeginParse; begin Inc(FIsParse); end; procedure TclMailMessage.EndParse; begin Dec(FIsParse); if (FIsParse < 0) then begin FIsParse := 0; end; end; procedure TclMailMessage.SafeClear; var oldCharSet: string; oldEncoding: TclEncodeMethod; oldHeaderEncoding: TclEncodeMethod; begin BeginUpdate(); try oldCharSet := CharSet; oldEncoding := Encoding; oldHeaderEncoding := HeaderEncoding; Clear(); CharSet := oldCharSet; Encoding := oldEncoding; HeaderEncoding := oldHeaderEncoding; finally EndUpdate(); end; end; procedure TclMailMessage.SaveMessage(AStream: TStream; const ACharSet: string); begin TclStringsUtils.SaveStrings(MessageSource, AStream, ACharSet); end; procedure TclMailMessage.SaveHeader(AStream: TStream; const ACharSet: string); begin TclStringsUtils.SaveStrings(HeaderSource, AStream, ACharSet); end; procedure TclMailMessage.SaveBodies(AStream: TStream; const ACharSet: string); begin TclStringsUtils.SaveStrings(BodiesSource, AStream, ACharSet); end; { TclMessageBody } procedure TclMessageBody.Assign(Source: TPersistent); var Src: TclMessageBody; begin MailMessage.BeginUpdate(); try if (Source is TclMessageBody) then begin Src := (Source as TclMessageBody); ExtraFields.Assign(Src.ExtraFields); ContentType := Src.ContentType; Encoding := Src.Encoding; ContentDisposition := Src.ContentDisposition; RawHeader.Assign(Src.RawHeader); FEncodedSize := Src.EncodedSize; FEncodedLines := Src.EncodedLines; FEncodedStart := Src.EncodedStart; FRawStart := Src.RawStart; end else begin inherited Assign(Source); end; finally MailMessage.EndUpdate(); end; end; procedure TclMessageBody.Clear; begin FExtraFields.Clear(); ContentType := ''; Encoding := MailMessage.Encoding; ContentDisposition := ''; RawHeader.Clear(); FEncodedSize := 0; FEncodedLines := 0; FEncodedStart := 0; FRawStart := 0; end; procedure TclMessageBody.SetListChangedEvent(AList: TStringList); begin AList.OnChange := DoOnListChanged; end; constructor TclMessageBody.Create(AOwner: TclMessageBodies); begin inherited Create(); Assert(AOwner <> nil); FOwner := AOwner; FOwner.AddItem(Self); DoCreate(); Clear(); end; destructor TclMessageBody.Destroy(); begin FRawHeader.Free(); FKnownFields.Free(); FExtraFields.Free(); FEncoder.Free(); inherited Destroy(); end; procedure TclMessageBody.DoOnListChanged(Sender: TObject); begin MailMessage.Update(); end; function TclMessageBody.GetMailMessage: TclMailMessage; begin Result := FOwner.Owner; end; procedure TclMessageBody.ReadData(Reader: TReader); begin ExtraFields.Text := Reader.ReadString(); ContentType := Reader.ReadString(); Encoding := TclEncodeMethod(Reader.ReadInteger()); ContentDisposition := Reader.ReadString(); end; procedure TclMessageBody.WriteData(Writer: TWriter); begin Writer.WriteString(ExtraFields.Text); Writer.WriteString(ContentType); Writer.WriteInteger(Integer(Encoding)); Writer.WriteString(ContentDisposition); end; procedure TclMessageBody.SetContentType(const Value: string); begin if (FContentType <> Value) then begin FContentType := Value; MailMessage.Update(); end; end; procedure TclMessageBody.SetEncoding(const Value: TclEncodeMethod); begin if (FEncoding <> Value) then begin FEncoding := Value; MailMessage.Update(); end; end; procedure TclMessageBody.AssignBodyHeader(AFieldList: TclMailHeaderFieldList); begin end; procedure TclMessageBody.AssignEncodingIfNeed; var Stream: TStream; begin if (Encoding = cmNone) and (not MailMessage.IsParse) then begin Stream := GetSourceStream(); try if (Stream <> nil) then begin FEncoder.AllowESC := MailMessage.AllowESC; FEncoder.CharsPerLine := MailMessage.CharsPerLine; Encoding := FEncoder.GetPreferredEncoding(Stream); end; finally Stream.Free(); end; end; end; procedure TclMessageBody.ParseBodyHeader(AFieldList: TclMailHeaderFieldList); var s: string; begin s := AFieldList.GetFieldValue('Content-Type'); ContentType := AFieldList.GetFieldValueItem(s, ''); s := LowerCase(AFieldList.GetFieldValue('Content-Transfer-Encoding')); Encoding := MailMessage.Encoding; if (s = 'quoted-printable') then begin Encoding := cmQuotedPrintable; end else if (s = 'base64') then begin Encoding := cmBase64; end; AFieldList.Encoding := Encoding; s := AFieldList.GetFieldValue('Content-Disposition'); ContentDisposition := AFieldList.GetFieldValueItem(s, ''); end; procedure TclMessageBody.EncodeData(ASource, ADestination: TStream); begin FEncoder.AllowESC := MailMessage.AllowESC; FEncoder.CharsPerLine := MailMessage.CharsPerLine; FEncoder.EncodeMethod := Encoding; FEncoder.Encode(ASource, ADestination); end; procedure TclMessageBody.DecodeData(ASource, ADestination: TStream); begin try FEncoder.EncodeMethod := Encoding; FEncoder.Decode(ASource, ADestination); except ADestination.Size := 0; ASource.Position := 0; FEncoder.EncodeMethod := cmNone; FEncoder.Decode(ASource, ADestination); end; end; function TclMessageBody.HasEncodedData: Boolean; begin Result := True; end; procedure TclMessageBody.AddData(AData: TStream; AEncodedLines: Integer); var Dst: TStream; begin Dst := GetDestinationStream(); try if HasEncodedData() and (AData.Size > 0) and (AEncodedLines > 0) then begin FEncodedSize := AData.Size; FEncodedLines := AEncodedLines; end; BeforeDataAdded(AData); AData.Position := 0; if (Dst <> nil) then begin DecodeData(AData, Dst); DataAdded(Dst); end; finally Dst.Free(); end; end; function TclMessageBody.GetData: TStream; var Src: TStream; begin Src := GetSourceStream(); try Result := TMemoryStream.Create(); try if (Src <> nil) then begin EncodeData(Src, Result); end; Result.Position := 0; except Result.Free(); raise; end; finally Src.Free(); end; end; procedure TclMessageBody.BeforeDataAdded(AData: TStream); var buf: array[0..1] of TclChar; begin if (AData.Size > 1) then begin AData.Position := AData.Size - 2; AData.Read(buf, 2); if (buf = #13#10) then begin AData.Size := AData.Size - 2; end; end; end; procedure TclMessageBody.DataAdded(AData: TStream); begin AData.Position := 0; MailMessage.DoDataAdded(Self, AData); end; function TclMessageBody.GetEncoding: TclEncodeMethod; begin if not MailMessage.IsMultiPartContent then begin Result := MailMessage.Encoding; if (Result = cmNone) then begin Result := FEncoding; end; end else begin Result := FEncoding; end; end; procedure TclMessageBody.DoOnEncoderProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin MailMessage.DoEncodingProgress(Self, ABytesProceed, ATotalBytes); end; function TclMessageBody.GetIndex: Integer; begin Result := FOwner.FList.IndexOf(Self); end; procedure TclMessageBody.DoCreate; begin FEncoder := TclEncoder.Create(nil); FEncoder.SuppressCrlf := False; FEncoder.OnProgress := DoOnEncoderProgress; FExtraFields := TStringList.Create(); SetListChangedEvent(FExtraFields as TStringList); FKnownFields := TStringList.Create(); RegisterFields(); FRawHeader := TStringList.Create(); end; procedure TclMessageBody.SetContentDisposition(const Value: string); begin if (FContentDisposition <> Value) then begin FContentDisposition := Value; MailMessage.Update(); end; end; procedure TclMessageBody.SetExtraFields(const Value: TStrings); begin FExtraFields.Assign(Value); end; procedure TclMessageBody.RegisterField(const AField: string); begin if (FindInStrings(FKnownFields, AField) < 0) then begin FKnownFields.Add(AField); end; end; procedure TclMessageBody.RegisterFields; begin RegisterField('Content-Type'); RegisterField('Content-Transfer-Encoding'); RegisterField('Content-Disposition'); end; { TclTextBody } procedure TclTextBody.ReadData(Reader: TReader); begin Strings.Text := Reader.ReadString(); CharSet := Reader.ReadString(); inherited ReadData(Reader); end; procedure TclTextBody.WriteData(Writer: TWriter); begin Writer.WriteString(Strings.Text); Writer.WriteString(CharSet); inherited WriteData(Writer); end; procedure TclTextBody.SetStrings(const Value: TStrings); begin FStrings.Assign(Value); end; destructor TclTextBody.Destroy; begin FStrings.Free(); inherited Destroy(); end; procedure TclTextBody.Assign(Source: TPersistent); begin MailMessage.BeginUpdate(); try if (Source is TclTextBody) then begin Strings.Assign((Source as TclTextBody).Strings); CharSet := (Source as TclTextBody).CharSet; end; inherited Assign(Source); finally MailMessage.EndUpdate(); end; end; procedure TclTextBody.Clear; begin inherited Clear(); Strings.Clear(); ContentType := DefaultContentType; CharSet := MailMessage.CharSet; end; procedure TclTextBody.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; MailMessage.Update(); end; end; procedure TclTextBody.AssignBodyHeader(AFieldList: TclMailHeaderFieldList); begin AFieldList.AddField('Content-Type', ContentType); if (ContentType <> '') and (CharSet <> '') then begin AFieldList.AddQuotedFieldItem('Content-Type', 'charset', CharSet); end; AFieldList.AddField('Content-Transfer-Encoding', EncodingMap[Encoding]); AFieldList.AddFields(ExtraFields); end; procedure TclTextBody.ParseBodyHeader(AFieldList: TclMailHeaderFieldList); var s: string; begin inherited ParseBodyHeader(AFieldList); s := AFieldList.GetFieldValue('Content-Type'); CharSet := AFieldList.GetFieldValueItem(s, 'charset'); AFieldList.CharSet := CharSet; end; function TclTextBody.GetSourceStream: TStream; var size: Integer; s, chrSet: string; buf: TclByteArray; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} Result := TMemoryStream.Create(); try s := FStrings.Text; size := Length(s); if (size - Length(#13#10) > 0) then begin s := system.Copy(s, 1, size - Length(#13#10)) end; chrSet := CharSet; if (chrSet = '') then begin chrSet := MailMessage.CharSet; end; buf := TclTranslator.GetBytes(s, chrSet); if (Length(buf) > 0) then begin Result.WriteBuffer(buf[0], Length(buf)); Result.Position := 0; end; except Result.Free(); raise; end; end; function TclTextBody.GetCharSet: string; begin if not MailMessage.IsMultiPartContent then begin Result := MailMessage.CharSet; end else begin Result := FCharSet; end; end; function TclTextBody.GetDestinationStream: TStream; begin Result := TMemoryStream.Create(); end; procedure TclTextBody.DataAdded(AData: TStream); var res: string; buf: TclByteArray; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} if (AData.Size > 0) then begin SetLength(buf, AData.Size); AData.Position := 0; AData.Read(buf[0], AData.Size); res := TclTranslator.GetString(buf, 0, AData.Size, CharSet); AddTextStr(FStrings, res); inherited DataAdded(AData); end; end; procedure TclTextBody.DoCreate; begin inherited DoCreate(); FStrings := TStringList.Create(); TStringList(FStrings).OnChange := DoOnStringsChanged; end; procedure TclTextBody.DoOnStringsChanged(Sender: TObject); begin AssignEncodingIfNeed(); MailMessage.Update(); end; { TclAttachmentBody } procedure TclAttachmentBody.Assign(Source: TPersistent); begin MailMessage.BeginUpdate(); try if (Source is TclAttachmentBody) then begin FileName := (Source as TclAttachmentBody).FileName; ContentID := (Source as TclAttachmentBody).ContentID; end; inherited Assign(Source); finally MailMessage.EndUpdate(); end; end; procedure TclAttachmentBody.AssignBodyHeader(AFieldList: TclMailHeaderFieldList); var disposition: string; begin AFieldList.AddField('Content-Type', ContentType); if (ContentType <> '') and (FileName <> '') then begin AFieldList.AddEncodedFieldItem('Content-Type', 'name', ExtractFileName(FileName)); end; AFieldList.AddField('Content-Transfer-Encoding', EncodingMap[Encoding]); disposition := ContentDisposition; if (disposition = '') then begin disposition := 'attachment'; end; AFieldList.AddField('Content-Disposition', disposition); if (disposition <> '') and (FileName <> '') then begin AFieldList.AddEncodedFieldItem('Content-Disposition', 'filename', ExtractFileName(FileName)); end; if (ContentID <> '') then begin AFieldList.AddField('Content-ID', '<' + ContentID + '>'); end; AFieldList.AddFields(ExtraFields); end; procedure TclAttachmentBody.Clear; begin inherited Clear(); FileName := ''; ContentType := 'application/octet-stream'; ContentID := ''; end; procedure TclAttachmentBody.DataAdded(AData: TStream); begin inherited DataAdded(AData); AData.Position := 0; MailMessage.DoAttachmentSaved(Self, FileName, AData); end; function TclAttachmentBody.GetMessageRfc822FileName(ABodyPos: Integer; ASource: TStrings): string; var filedList: TclMailHeaderFieldList; begin filedList := TclMailHeaderFieldList.Create(MailMessage.CharSet, MailMessage.GetHeaderEncoding(), MailMessage.CharsPerLine); try filedList.Parse(ABodyPos, ASource); Result := NormalizeFilePath(filedList.GetFieldValue('Subject') + '.eml'); finally filedList.Free(); end; end; procedure TclAttachmentBody.ParseBodyHeader(AFieldList: TclMailHeaderFieldList); var s: string; begin inherited ParseBodyHeader(AFieldList); s := AFieldList.GetFieldValue('Content-Disposition'); FileName := AFieldList.GetDecodedFieldValueItem(s, 'filename'); if (FileName = '') then begin s := AFieldList.GetFieldValue('Content-Type'); FileName := AFieldList.GetDecodedFieldValueItem(s, 'filename'); end; if (FileName = '') then begin FileName := AFieldList.GetDecodedFieldValue('Content-Description'); if (Length(FileName) > 3) and (FileName[Length(FileName) - 3] <> '.') then begin FileName := NormalizeFilePath(FileName + '.dat'); end; end; if (FileName = '') then begin s := AFieldList.GetFieldValue('Content-Type'); FileName := NormalizeFilePath(AFieldList.GetDecodedFieldValueItem(s, 'name')); end; if (FileName = '') and SameText('message/rfc822', ContentType) then begin FileName := GetMessageRfc822FileName(AFieldList.HeaderEnd + 1, AFieldList.Source); end; ContentID := GetContentID(AFieldList); end; function TclAttachmentBody.GetContentID(AFieldList: TclMailHeaderFieldList): string; begin Result := ExtractQuotedString(AFieldList.GetFieldValue('Content-ID'), '<', '>'); end; procedure TclAttachmentBody.ReadData(Reader: TReader); begin FileName := Reader.ReadString(); inherited ReadData(Reader); end; procedure TclAttachmentBody.SetFileName(const Value: string); begin if (FFileName <> Value) then begin FFileName := Value; AssignEncodingIfNeed(); MailMessage.Update(); end; end; procedure TclAttachmentBody.AssignEncodingIfNeed; begin FCheckFileExists := True; try inherited AssignEncodingIfNeed(); finally FCheckFileExists := False; end; end; procedure TclAttachmentBody.WriteData(Writer: TWriter); begin Writer.WriteString(FileName); inherited WriteData(Writer); end; function TclAttachmentBody.GetDestinationStream: TStream; var Handled: Boolean; s: string; begin Result := nil; Handled := False; s := FileName; MailMessage.DoSaveAttachment(Self, s, Result, Handled); FileName := s; end; function TclAttachmentBody.GetSourceStream: TStream; var Handled: Boolean; s: string; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetSourceStream');{$ENDIF} Result := nil; Handled := False; s := FileName; MailMessage.DoLoadAttachment(Self, s, Result, Handled); FileName := s; if not Handled then begin Result.Free(); if (not FCheckFileExists or FileExists(FileName)) then begin {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GetSourceStream need to open the attachment file: "%s"', nil, [FileName]);{$ENDIF} Result := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); end; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetSourceStream'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetSourceStream', E); raise; end; end;{$ENDIF} end; function TclAttachmentBody.GetEncoding: TclEncodeMethod; begin if (MailMessage.MessageFormat = mfUUencode) then begin Result := cmUUEncode; end else begin Result := inherited GetEncoding(); end; end; procedure TclAttachmentBody.SetContentID(const Value: string); begin if (FContentID <> Value) then begin FContentID := Value; MailMessage.Update(); end; end; procedure TclAttachmentBody.RegisterFields; begin inherited RegisterFields(); RegisterField('Content-Description'); RegisterField('Content-ID'); end; { TclImageBody } function TclImageBody.GetUniqueContentID(const AFileName: string): string; begin Result := AFileName + '@' + FloatToStr(Now()) + '.' + IntToStr(Random(1000)); end; procedure TclImageBody.AssignBodyHeader(AFieldList: TclMailHeaderFieldList); begin AFieldList.AddField('Content-Type', ContentType); if (ContentType <> '') and (FileName <> '') then begin AFieldList.AddEncodedFieldItem('Content-Type', 'name', ExtractFileName(FileName)); end; AFieldList.AddField('Content-Transfer-Encoding', EncodingMap[Encoding]); AFieldList.AddField('Content-Disposition', ContentDisposition); if (ContentDisposition <> '') and (FileName <> '') then begin AFieldList.AddEncodedFieldItem('Content-Disposition', 'filename', ExtractFileName(FileName)); end; if (ContentID <> '') then begin AFieldList.AddField('Content-ID', '<' + ContentID + '>'); end; AFieldList.AddFields(ExtraFields); end; procedure TclImageBody.Clear; begin inherited Clear(); ContentType := ''; Encoding := cmBase64; end; procedure TclImageBody.ParseBodyHeader(AFieldList: TclMailHeaderFieldList); var s: string; begin inherited ParseBodyHeader(AFieldList); s := AFieldList.GetFieldValue('Content-Type'); FileName := AFieldList.GetDecodedFieldValueItem(s, 'name'); ContentType := AFieldList.GetFieldValueItem(s, ''); ContentID := GetContentID(AFieldList); end; {$IFNDEF DELPHI6} const PathDelim = '\'; DriveDelim = ':'; {$ENDIF} function TclImageBody.GetFileType(const AFileName: string): string; var i: Integer; begin i := LastDelimiter('.' + PathDelim + DriveDelim, FileName); if (i > 0) and (FileName[i] = '.') then Result := Copy(FileName, i + 1, 1000) else Result := ''; end; procedure TclImageBody.SetFileName(const Value: string); begin inherited SetFileName(Value); if (FileName <> '') and (ContentID = '') then begin ContentID := GetUniqueContentID(ExtractFileName(FileName)); end; if (FileName <> '') and (ContentType = '') then begin ContentType := 'image/' + GetFileType(FileName); end; end; { TclMultipartBody } procedure TclMultipartBody.Assign(Source: TPersistent); var Multipart: TclMultipartBody; begin MailMessage.BeginUpdate(); try if (Source is TclMultipartBody) then begin Multipart := (Source as TclMultipartBody); Bodies := Multipart.Bodies; SetBoundary(Multipart.Boundary); ContentSubType := Multipart.ContentSubType; end; inherited Assign(Source); finally MailMessage.EndUpdate(); end; end; procedure TclMultipartBody.AssignBodyHeader(AFieldList: TclMailHeaderFieldList); begin FSelfMailMessage.GenerateBoundary(); AFieldList.AddField('Content-Type', ContentType); if (ContentType <> '') and (ContentSubType <> '') then begin AFieldList.AddQuotedFieldItem('Content-Type', 'type', ContentSubType); end; AFieldList.AddQuotedFieldItem('Content-Type', 'boundary', Boundary); AFieldList.AddFields(ExtraFields); AFieldList.AddEndOfHeader(); end; procedure TclMultipartBody.Clear; begin inherited Clear(); Bodies.Clear(); ContentType := 'multipart/mixed'; ContentSubType := ''; Encoding := cmNone; SetBoundary(''); end; procedure TclMultipartBody.FixRawBodyStart(ABodies: TclMessageBodies); var i: Integer; body: TclMessageBody; begin for i := 0 to ABodies.Count - 1 do begin body := ABodies[i]; body.FEncodedStart := body.EncodedStart + EncodedStart; body.FRawStart := body.RawStart + EncodedStart; if(body is TclMultipartBody) then begin FixRawBodyStart(TclMultipartBody(body).Bodies); end; end; end; procedure TclMultipartBody.DataAdded(AData: TStream); var list: TStrings; begin list := TStringList.Create(); try AData.Position := 0; AddTextStream(list, AData); FSelfMailMessage.ParseBodies(list); FixRawBodyStart(Bodies); FEncodedLines := list.Count; finally list.Free(); end; end; destructor TclMultipartBody.Destroy; begin FSelfMailMessage.Free(); inherited Destroy(); end; procedure TclMultipartBody.DoCreate; begin inherited DoCreate(); FSelfMailMessage := TclMailMessage.Create(nil); FSelfMailMessage.OnSaveAttachment := DoOnSaveAttachment; FSelfMailMessage.OnAttachmentSaved := DoOnAttachmentSaved; FSelfMailMessage.OnLoadAttachment := DoOnLoadAttachment; FSelfMailMessage.OnDataAdded := DoOnDataAdded; FSelfMailMessage.Bodies.FOwner := MailMessage; end; procedure TclMultipartBody.DoOnAttachmentSaved(Sender: TObject; ABody: TclAttachmentBody; const AFileName: string; AData: TStream); begin MailMessage.DoAttachmentSaved(ABody, AFileName, AData); end; procedure TclMultipartBody.DoOnDataAdded(Sender: TObject; ABody: TclMessageBody; AData: TStream); begin AData.Position := 0; MailMessage.DoDataAdded(ABody, AData); end; procedure TclMultipartBody.DoOnLoadAttachment(Sender: TObject; ABody: TclAttachmentBody; var AFileName: string; var AStream: TStream; var Handled: Boolean); begin MailMessage.DoLoadAttachment(ABody, AFileName, AStream, Handled); end; procedure TclMultipartBody.DoOnSaveAttachment(Sender: TObject; ABody: TclAttachmentBody; var AFileName: string; var AStream: TStream; var Handled: Boolean); begin MailMessage.DoSaveAttachment(ABody, AFileName, AStream, Handled); end; function TclMultipartBody.GetBodies: TclMessageBodies; begin Result := FSelfMailMessage.Bodies; end; function TclMultipartBody.GetBoundary: string; begin Result := FSelfMailMessage.Boundary; end; function TclMultipartBody.GetDestinationStream: TStream; begin Result := TMemoryStream.Create(); end; function TclMultipartBody.GetSourceStream: TStream; var list: TStrings; buf: TclByteArray; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} Result := TMemoryStream.Create(); list := TStringList.Create(); try FSelfMailMessage.InternalAssignBodies(list); buf := TclTranslator.GetBytes(list.Text); if (Length(buf) > 0) then begin Result.WriteBuffer(buf[0], Length(buf)); end; Result.Position := 0; finally list.Free(); end; end; function TclMultipartBody.HasEncodedData: Boolean; begin Result := False; end; procedure TclMultipartBody.ParseBodyHeader(AFieldList: TclMailHeaderFieldList); var s: string; begin inherited ParseBodyHeader(AFieldList); s := AFieldList.GetFieldValue('Content-Type'); SetBoundary(AFieldList.GetFieldValueItem(s, 'boundary')); ContentSubType := AFieldList.GetFieldValueItem(s, 'type'); Encoding := cmNone; end; procedure TclMultipartBody.ReadData(Reader: TReader); begin ContentSubType := Reader.ReadString(); Bodies.ReadData(Reader); inherited ReadData(Reader); end; procedure TclMultipartBody.SetBodies(const Value: TclMessageBodies); begin FSelfMailMessage.Bodies.Assign(Value); end; procedure TclMultipartBody.SetBoundary(const Value: string); begin if (Boundary <> Value) then begin FSelfMailMessage.SetBoundary(Value); MailMessage.Update(); end; end; procedure TclMultipartBody.SetContentSubType(const Value: string); begin if (FContentSubType <> Value) then begin FContentSubType := Value; MailMessage.Update(); end; end; procedure TclMultipartBody.SetContentType(const Value: string); begin inherited SetContentType(Value); FSelfMailMessage.SetContentType(Value); end; procedure TclMultipartBody.WriteData(Writer: TWriter); begin Writer.WriteString(ContentSubType); Bodies.WriteData(Writer); inherited WriteData(Writer); end; { TclAttachmentList } procedure TclAttachmentList.Add(AItem: TclAttachmentBody); begin FList.Add(AItem); end; procedure TclAttachmentList.Clear; begin FList.Clear(); end; constructor TclAttachmentList.Create; begin inherited Create(); FList := TList.Create(); end; destructor TclAttachmentList.Destroy; begin FList.Free(); inherited Destroy(); end; function TclAttachmentList.GetCount: Integer; begin Result := FList.Count; end; function TclAttachmentList.GetItem(Index: Integer): TclAttachmentBody; begin Result := TclAttachmentBody(FList[Index]); end; { TclImageList } function TclImageList.GetItem(Index: Integer): TclImageBody; begin Result := TclImageBody(inherited GetItem(Index)); end; initialization RegisterBody(TclTextBody); RegisterBody(TclAttachmentBody); RegisterBody(TclMultipartBody); RegisterBody(TclImageBody); finalization RegisteredBodyItems.Free(); 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.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, Quick.IOC, Dependencies; type TForm1 = class(TForm) meInfo: TMemo; Panel1: TPanel; btnCheckIOC: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCheckIOCClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; iocContainer : TIocContainer; sumservice : ISumService; multservice : IMultService; bigservice : IBigService; divideservice : TDivideService; executions : Integer = 0; implementation {$R *.fmx} procedure TForm1.btnCheckIOCClick(Sender: TObject); var res : Integer; i : Integer; times : Integer; numoperations : Integer; begin times := 100; res := 0; Inc(executions); //test1: class injection as singleton for i := 1 to times do begin sumservice := iocContainer.Resolve<ISumService>; res := sumservice.Sum(2,2); end; if sumservice.NumOperations = times * executions + (times * (executions - 1)) then meInfo.Lines.Add('Test1: Class injection as Singleton test ok') else meInfo.Lines.Add('Test1: Class injection as Singleton test error'); meInfo.Lines.Add(Format('SumService.Sum = %d (calls: %d)',[res,sumservice.NumOperations])); //test2: class injection as transient for i := 1 to times do begin multservice := iocContainer.Resolve<IMultService>; res := multservice.Mult(2,4); end; if multservice.NumOperations = 1 then meInfo.Lines.Add('Test2: Class injection as Transient test ok') else meInfo.Lines.Add('Test2: Class injection as Transient test error'); meInfo.Lines.Add(Format('MultService.Mult = %d (calls: %d)',[res,multservice.NumOperations])); //test3: constructor injection as singleton for i := 1 to times do begin bigservice := iocContainer.Resolve<IBigService>('one'); res := bigservice.Sum(2,2); end; if bigservice.NumOperations = times * executions then meInfo.Lines.Add('Test3: Constructor injection as Singleton test ok') else meInfo.Lines.Add('Test3: Constructor injection as Singleton test error'); meInfo.Lines.Add(Format('BigService.Sum = %d (calls: %d to BigService / calls: %d to SumService (as singleton))',[res,bigservice.NumOperations,bigservice.sumservice.NumOperations])); //test4: constructor injection as transient for i := 1 to times do begin bigservice := iocContainer.Resolve<IBigService>('other'); res := bigservice.Mult(2,4); end; if bigservice.NumOperations = 1 then meInfo.Lines.Add('Test4: Constructor injection as Transient test ok') else meInfo.Lines.Add('Test4: Constructor injection as Transient test error'); meInfo.Lines.Add(Format('BigService.Mult = %d (calls: %d to BigService / calls: %d to MultService (as transient))',[res,bigservice.NumOperations,bigservice.multservice.NumOperations])); //test5: class instance injection as singleton for i := 1 to times do begin divideservice := iocContainer.Resolve<TDivideService>('one'); res := divideservice.Divide(100,2); end; if divideservice.NumOperations = times * executions then meInfo.Lines.Add('Test5: Class instance injection as Singleton test ok') else meInfo.Lines.Add('Test5: Class instance injection as Singleton test error'); meInfo.Lines.Add(Format('DivideService.Divide = %d (calls: %d)',[res,divideservice.NumOperations])); //test6: class instance injection as transient for i := 1 to times do begin divideservice := iocContainer.Resolve<TDivideService>('other'); res := divideservice.Divide(100,2); numoperations := divideservice.NumOperations; //transient instances must be manual free divideservice.Free; end; if numoperations = 1 then meInfo.Lines.Add('Test6: Class instance injection as Transient test ok') else meInfo.Lines.Add('Test6: Class instance injection as Transient test error'); meInfo.Lines.Add(Format('DivideService.Divide = %d (calls: %d)',[res,numoperations])); meInfo.Lines.Add('Test finished'); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin iocContainer.Free; end; procedure TForm1.FormCreate(Sender: TObject); begin iocContainer := TIocContainer.Create; iocContainer.RegisterType<ISumService,TSumService>.AsSingleTon.DelegateTo(function : TSumService begin Result := TSumService.Create; end); iocContainer.RegisterType<IMultService,TMultService>.AsTransient; iocContainer.RegisterType<IBigService,TBigService>('one').AsSingleTon; iocContainer.RegisterType<IBigService,TBigService>('other').AsTransient; iocContainer.RegisterInstance<TDivideService>('one').AsSingleton.DelegateTo(function : TDivideService begin Result := TDivideService.Create(True); end); iocContainer.RegisterInstance<TDivideService>('other').AsTransient.DelegateTo(function : TDivideService begin Result := TDivideService.Create(True); end); end; end.
unit kwKeyValuesPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwKeyValuesPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "kwKeyValuesPack" MUID: (567ACC1F028D) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , kwKeyValues , tfwClassLike , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *567ACC1F028Dimpl_uses* //#UC END# *567ACC1F028Dimpl_uses* ; type TkwKeyValuesCreate = {final} class(TtfwClassLike) {* Слово скрипта KeyValues:Create } private function Create(const aCtx: TtfwContext): TkwKeyValues; {* Реализация слова скрипта KeyValues:Create } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwKeyValuesCreate function TkwKeyValuesCreate.Create(const aCtx: TtfwContext): TkwKeyValues; {* Реализация слова скрипта KeyValues:Create } //#UC START# *567ACC37033D_567ACC37033D_567ACBF70376_Word_var* //#UC END# *567ACC37033D_567ACC37033D_567ACBF70376_Word_var* begin //#UC START# *567ACC37033D_567ACC37033D_567ACBF70376_Word_impl* Result := TkwKeyValues.Create(nil{Prodicer}, Self{nil}{Finder}, aCtx.rTypeInfo, aCtx, {nil}Key); //#UC END# *567ACC37033D_567ACC37033D_567ACBF70376_Word_impl* end;//TkwKeyValuesCreate.Create class function TkwKeyValuesCreate.GetWordNameForRegister: AnsiString; begin Result := 'KeyValues:Create'; end;//TkwKeyValuesCreate.GetWordNameForRegister function TkwKeyValuesCreate.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TkwKeyValues); end;//TkwKeyValuesCreate.GetResultTypeInfo function TkwKeyValuesCreate.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwKeyValuesCreate.GetAllParamsCount function TkwKeyValuesCreate.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TkwKeyValues)]); end;//TkwKeyValuesCreate.ParamsTypes procedure TkwKeyValuesCreate.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushObj(Create(aCtx)); end;//TkwKeyValuesCreate.DoDoIt initialization TkwKeyValuesCreate.RegisterInEngine; {* Регистрация KeyValues_Create } TtfwTypeRegistrator.RegisterType(TypeInfo(TkwKeyValues)); {* Регистрация типа TkwKeyValues } {$IfEnd} // NOT Defined(NoScripts) end.
program main_modular; uses crt, parser, konversi, tipe_data, proses_user_program, proses_data, proses_buku; (*Unit yang dibutuhkan dalam eksekusi program utama ini*) var array_buku : tabBuku; //array data buku array_user : tabUser; //array data user array_pinjam : tabPinjam; //array data pinjam array_kembali : tabKembali; //array data kembali array_hilang : tabHilang; //array data kehilangan pilihan_menu : string; //variabel yang menyimpan input menu pilihan active_user : tuser; //variabel yang menyimpan nama username yg lagi login isLogin : boolean; //variabel yang menentukan apakah lagi ada user yang aktif isSave : boolean; //variabel yang menyatakan apakah data sudah disimpan atau belum willExit : Boolean; //variabel yang menentukan apakah program akan berhenti nama_file_buku, nama_file_user, nama_file_pinjam, nama_file_kembali, nama_file_hilang: string; //nama file csv yang dimuat oleh program begin isLogin := False; (*State awal tidak ada yang sedang login*) willExit := False; (*State awal aplikasi sedang berjalan dan belum akan keluar*) writeln(''); writeln('Muat database terlebih dahulu...'); writeln(''); (*Prosedur load dijalankan pertama kali*) writeln('$ load'); writeln(''); load(array_buku,array_user,array_pinjam,array_kembali,array_hilang,nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang); clrscr; writeln('=========================================================================================='); writeln('=========================================================================================='); writeln('----------------------Selamat datang di Perpustakaan Ba Sing Tse!-------------------------'); writeln('------Gunakan keyword "help" untuk melihat semua menu pada aplikasi perpustakaan ini------'); writeln('--------------------Kontak administrator terdekat untuk membuat akun!---------------------'); writeln('=========================================================================================='); writeln('=========================================================================================='); repeat isSave := True; (*Awalnya belum ada perubahan data array sehingga tidak diperlukan penyimpanan*) repeat writeln(''); write('$ '); readln(pilihan_menu); case (pilihan_menu) of (*Percabangan yang disesuaikan dengan input user*) 'login' : loginAnggota(array_user,nama_file_user,active_user,isLogin); 'cari' : CetakKategori(array_buku); 'caritahunterbit' : CetakDariTahun(array_buku); 'exit' : exiting_program(array_buku, array_user, array_pinjam, array_kembali, array_hilang, nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang, willExit,isLogin,isSave); 'help' : showHelp(isLogin); end; until (willExit or isLogin); (*Menu awal saat belum ada yang log in*) if (not willExit) then begin (*Menu ketika sudah ada yang login*) repeat write('$ '); readln(pilihan_menu); case (pilihan_menu) of 'register' : registerAnggota( array_user, active_user, isSave); 'cari' : CetakKategori(array_buku); 'caritahunterbit' : CetakDariTahun(array_buku); 'exit' : exiting_program(array_buku,array_user,array_pinjam,array_kembali,array_hilang,nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang,willExit,isLogin,isSave); 'help' : showHelp(isLogin); 'pinjam_buku': pinjam_buku(array_buku,array_pinjam,active_user,isSave); 'kembalikan_buku' : kembalikan_buku (array_buku, array_pinjam, array_kembali, active_user, isSave ) ; 'lapor_hilang' : RegLost (array_hilang, isSave); 'lihat_laporan' : SeeLost (array_hilang, active_user); 'tambah_buku' : AddBook (array_buku, active_user, isSave); 'tambah_jumlah_buku' : AddJumlahBuku (array_buku, active_user, isSave); 'riwayat' : Riwayat (array_pinjam, array_buku, active_user); 'statistik' : Statistik (array_user, array_buku, active_user); 'save' : save(array_buku,array_user,array_pinjam ,array_kembali,array_hilang,nama_file_kembali,nama_file_pinjam,nama_file_user,nama_file_buku,nama_file_hilang,isSave); 'cari_anggota' : cariAnggota(array_user, active_user); 'logout' : logout(array_buku,array_user,array_pinjam ,array_kembali,array_hilang,nama_file_kembali,nama_file_pinjam,nama_file_user,nama_file_buku,nama_file_hilang,isSave,isLogin); end; until (not isLogin) or willExit; (*Ulangi input user hingga logout atau keluar dari aplikasi.*) end; until(willExit); (*Jika willExit bernilai true, user keluar dari aplikasi*) end.
unit MailBrowser_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { MailBrowser Library } { Version 1.0 } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_MailBrowser: TGUID = '{4F7EC360-AD33-11D1-A1A8-0080C817C099}'; const { Component class GUIDs } Class_MailBrowser: TGUID = '{4F7EC362-AD33-11D1-A1A8-0080C817C099}'; type { Forward declarations: Interfaces } IMailBrowser = interface; IMailBrowserDisp = dispinterface; { Forward declarations: CoClasses } MailBrowser = IMailBrowser; { Dispatch interface for MailBrowser Object } IMailBrowser = interface(IDispatch) ['{4F7EC361-AD33-11D1-A1A8-0080C817C099}'] function Get_Account: WideString; safecall; procedure Set_Account(const Value: WideString); safecall; function Get_Folder: WideString; safecall; procedure Set_Folder(const Value: WideString); safecall; procedure Reset; safecall; function Next: WordBool; safecall; function DeleteMessage(const MsgPath: WideString): WordBool; safecall; function Get_Empty: WordBool; safecall; function Get_World: WideString; safecall; procedure Set_World(const Value: WideString); safecall; function Get_Header(const Name: WideString): WideString; safecall; function FullPath: WideString; safecall; property Account: WideString read Get_Account write Set_Account; property Folder: WideString read Get_Folder write Set_Folder; property Empty: WordBool read Get_Empty; property World: WideString read Get_World write Set_World; property Header[const Name: WideString]: WideString read Get_Header; end; { DispInterface declaration for Dual Interface IMailBrowser } IMailBrowserDisp = dispinterface ['{4F7EC361-AD33-11D1-A1A8-0080C817C099}'] property Account: WideString dispid 1; property Folder: WideString dispid 2; procedure Reset; dispid 4; function Next: WordBool; dispid 5; function DeleteMessage(const MsgPath: WideString): WordBool; dispid 11; property Empty: WordBool readonly dispid 8; property World: WideString dispid 10; property Header[const Name: WideString]: WideString readonly dispid 6; function FullPath: WideString; dispid 3; end; { MailBrowserObject } CoMailBrowser = class class function Create: IMailBrowser; class function CreateRemote(const MachineName: string): IMailBrowser; end; implementation uses ComObj; class function CoMailBrowser.Create: IMailBrowser; begin Result := CreateComObject(Class_MailBrowser) as IMailBrowser; end; class function CoMailBrowser.CreateRemote(const MachineName: string): IMailBrowser; begin Result := CreateRemoteComObject(MachineName, Class_MailBrowser) as IMailBrowser; end; end.
unit GroupListKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы GroupList } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Admin\Forms\GroupListKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "GroupListKeywordsPack" MUID: (4AA8E4CD0348_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , GroupList_Form , tfwPropertyLike , vtPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , eeTreeView , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4AA8E4CD0348_Packimpl_uses* //#UC END# *4AA8E4CD0348_Packimpl_uses* ; type TkwEfGroupListBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TefGroupList.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aefGroupList: TefGroupList): TvtPanel; {* Реализация слова скрипта .TefGroupList.BackgroundPanel } 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;//TkwEfGroupListBackgroundPanel TkwEfGroupListGroupsTree = {final} class(TtfwPropertyLike) {* Слово скрипта .TefGroupList.GroupsTree } private function GroupsTree(const aCtx: TtfwContext; aefGroupList: TefGroupList): TeeTreeView; {* Реализация слова скрипта .TefGroupList.GroupsTree } 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;//TkwEfGroupListGroupsTree Tkw_Form_GroupList = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы GroupList ---- *Пример использования*: [code]форма::GroupList TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_GroupList Tkw_GroupList_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_GroupList_Control_BackgroundPanel Tkw_GroupList_Control_BackgroundPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_GroupList_Control_BackgroundPanel_Push Tkw_GroupList_Control_GroupsTree = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола GroupsTree ---- *Пример использования*: [code]контрол::GroupsTree TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_GroupList_Control_GroupsTree Tkw_GroupList_Control_GroupsTree_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола GroupsTree ---- *Пример использования*: [code]контрол::GroupsTree:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_GroupList_Control_GroupsTree_Push function TkwEfGroupListBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aefGroupList: TefGroupList): TvtPanel; {* Реализация слова скрипта .TefGroupList.BackgroundPanel } begin Result := aefGroupList.BackgroundPanel; end;//TkwEfGroupListBackgroundPanel.BackgroundPanel class function TkwEfGroupListBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TefGroupList.BackgroundPanel'; end;//TkwEfGroupListBackgroundPanel.GetWordNameForRegister function TkwEfGroupListBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEfGroupListBackgroundPanel.GetResultTypeInfo function TkwEfGroupListBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfGroupListBackgroundPanel.GetAllParamsCount function TkwEfGroupListBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefGroupList)]); end;//TkwEfGroupListBackgroundPanel.ParamsTypes procedure TkwEfGroupListBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEfGroupListBackgroundPanel.SetValuePrim procedure TkwEfGroupListBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aefGroupList: TefGroupList; begin try l_aefGroupList := TefGroupList(aCtx.rEngine.PopObjAs(TefGroupList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefGroupList: TefGroupList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aefGroupList)); end;//TkwEfGroupListBackgroundPanel.DoDoIt function TkwEfGroupListGroupsTree.GroupsTree(const aCtx: TtfwContext; aefGroupList: TefGroupList): TeeTreeView; {* Реализация слова скрипта .TefGroupList.GroupsTree } begin Result := aefGroupList.GroupsTree; end;//TkwEfGroupListGroupsTree.GroupsTree class function TkwEfGroupListGroupsTree.GetWordNameForRegister: AnsiString; begin Result := '.TefGroupList.GroupsTree'; end;//TkwEfGroupListGroupsTree.GetWordNameForRegister function TkwEfGroupListGroupsTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TeeTreeView); end;//TkwEfGroupListGroupsTree.GetResultTypeInfo function TkwEfGroupListGroupsTree.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfGroupListGroupsTree.GetAllParamsCount function TkwEfGroupListGroupsTree.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefGroupList)]); end;//TkwEfGroupListGroupsTree.ParamsTypes procedure TkwEfGroupListGroupsTree.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству GroupsTree', aCtx); end;//TkwEfGroupListGroupsTree.SetValuePrim procedure TkwEfGroupListGroupsTree.DoDoIt(const aCtx: TtfwContext); var l_aefGroupList: TefGroupList; begin try l_aefGroupList := TefGroupList(aCtx.rEngine.PopObjAs(TefGroupList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefGroupList: TefGroupList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GroupsTree(aCtx, l_aefGroupList)); end;//TkwEfGroupListGroupsTree.DoDoIt function Tkw_Form_GroupList.GetString: AnsiString; begin Result := 'efGroupList'; end;//Tkw_Form_GroupList.GetString class procedure Tkw_Form_GroupList.RegisterInEngine; begin inherited; TtfwClassRef.Register(TefGroupList); end;//Tkw_Form_GroupList.RegisterInEngine class function Tkw_Form_GroupList.GetWordNameForRegister: AnsiString; begin Result := 'форма::GroupList'; end;//Tkw_Form_GroupList.GetWordNameForRegister function Tkw_GroupList_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_GroupList_Control_BackgroundPanel.GetString class procedure Tkw_GroupList_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_GroupList_Control_BackgroundPanel.RegisterInEngine class function Tkw_GroupList_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_GroupList_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_GroupList_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_GroupList_Control_BackgroundPanel_Push.DoDoIt class function Tkw_GroupList_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_GroupList_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_GroupList_Control_GroupsTree.GetString: AnsiString; begin Result := 'GroupsTree'; end;//Tkw_GroupList_Control_GroupsTree.GetString class procedure Tkw_GroupList_Control_GroupsTree.RegisterInEngine; begin inherited; TtfwClassRef.Register(TeeTreeView); end;//Tkw_GroupList_Control_GroupsTree.RegisterInEngine class function Tkw_GroupList_Control_GroupsTree.GetWordNameForRegister: AnsiString; begin Result := 'контрол::GroupsTree'; end;//Tkw_GroupList_Control_GroupsTree.GetWordNameForRegister procedure Tkw_GroupList_Control_GroupsTree_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('GroupsTree'); inherited; end;//Tkw_GroupList_Control_GroupsTree_Push.DoDoIt class function Tkw_GroupList_Control_GroupsTree_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::GroupsTree:push'; end;//Tkw_GroupList_Control_GroupsTree_Push.GetWordNameForRegister initialization TkwEfGroupListBackgroundPanel.RegisterInEngine; {* Регистрация efGroupList_BackgroundPanel } TkwEfGroupListGroupsTree.RegisterInEngine; {* Регистрация efGroupList_GroupsTree } Tkw_Form_GroupList.RegisterInEngine; {* Регистрация Tkw_Form_GroupList } Tkw_GroupList_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_GroupList_Control_BackgroundPanel } Tkw_GroupList_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_GroupList_Control_BackgroundPanel_Push } Tkw_GroupList_Control_GroupsTree.RegisterInEngine; {* Регистрация Tkw_GroupList_Control_GroupsTree } Tkw_GroupList_Control_GroupsTree_Push.RegisterInEngine; {* Регистрация Tkw_GroupList_Control_GroupsTree_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TefGroupList)); {* Регистрация типа TefGroupList } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TeeTreeView)); {* Регистрация типа TeeTreeView } {$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit UserSetupDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TCWODT, CaptionList; type TUserSetupDialog = class(TComponent) private FCaptionList: TCaptionList; procedure SetCaptionList(const Value: TCaptionList); { Private declarations } protected { Protected declarations } public { Public declarations } procedure Execute(ADaapi:IDaapiGlobal); published { Published declarations } property CaptionList:TCaptionList read FCaptionList write SetCaptionList; end; procedure Register; implementation uses UserSetupForm; procedure Register; begin RegisterComponents('FFS Common', [TUserSetupDialog]); end; { TUserSetupDialog } procedure TUserSetupDialog.Execute(ADaapi:IDaapiGlobal); var userform : TfrmUserSetup; begin if not assigned(ADaapi) then raise EDAAPINotAssigned.create; userform := TfrmUserSetup.create(self, ADaapi); if assigned(FCaptionList) then userform.LenderCaption := CaptionList.CaptionFormat('Lender','%s'); try userform.showmodal; finally userform.free; end; end; procedure TUserSetupDialog.SetCaptionList(const Value: TCaptionList); begin FCaptionList := Value; end; end.
unit MdiChilds.DocList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GsDocument, Contnrs, Generics.Collections, MDIChilds.CustomDialog, Vcl.StdCtrls, Vcl.ExtCtrls, JvComponentBase, JvDragDrop, MdiChilds.ProgressForm, MdiChilds.Reg, GlobalData; type TFmDocList = class(TFmProcess) lbFiles: TListBox; btnClear: TButton; lblDocuments: TLabel; lblDocCount: TLabel; JvDragDrop1: TJvDragDrop; btnSave: TButton; Label1: TLabel; procedure btnClearClick(Sender: TObject); procedure JvDragDrop1Drop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure btnSaveClick(Sender: TObject); protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; class function GetDataProcessorKind: TDataProcessorKind; override; procedure DoResize(Sender: TObject); override; public procedure AfterConstruction; override; end; implementation {$R *.dfm} procedure TFmDocList.AfterConstruction; begin inherited; lblDocCount.Caption := IntToStr(Documents.Count); end; procedure TFmDocList.btnClearClick(Sender: TObject); begin Documents.Clear; lblDocCount.Caption := '0'; end; procedure TFmDocList.btnSaveClick(Sender: TObject); var I: Integer; begin for I := 0 to Documents.Count - 1 do Documents[I].Save; end; procedure TFmDocList.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; D: TGsDocument; begin ShowMessage := True; ProgressForm.InitPB(lbFiles.Count); ProgressForm.Show; for I := 0 to lbFiles.Count - 1 do begin D := NewGsDocument; try D.LoadFromFile(lbFiles.Items[I]); Documents.Add(D); lblDocCount.Caption := IntToStr(Documents.Count); ProgressForm.StepIt(ExtractFileName(lbFiles.Items[I])); except on E: Exception do begin D.Free; raise Exception.CreateFmt('Ошибка при загрузке файла: %s',[ExtractFileName(lbFiles.Items[I])]); end; end; end; end; procedure TFmDocList.DoResize(Sender: TObject); begin inherited DoResize(Sender); btnClear.Top := Bevel.Height + 10; btnSave.Top := Bevel.Height + 10; end; class function TFmDocList.GetDataProcessorKind: TDataProcessorKind; begin Result := dpkCustom; end; procedure TFmDocList.JvDragDrop1Drop(Sender: TObject; Pos: TPoint; Value: TStrings); var I: Integer; begin for I := 0 to Value.Count - 1 do lbFiles.Items.Add(Value[I]); end; initialization //FormsRegistrator.RegisterForm(TFmDocList, 'Загрузка документов в программу', 'Системные утилиты', true, dpkCustom, '/LOADDOCS', 0); end.
unit PolOperationsGUI; interface uses Windows, Messages, SysUtils, StrUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, PolUnit; const OPERATIONS_SYMBOLS: array[0..3] of char = ('+', 'Ц', 'Х', ':'); type TMainForm = class(TForm) lblTitle: TLabel; pnlInput: TPanel; lblLeftPol: TLabel; edtLeftPol: TEdit; lblLeftPolInputError: TLabel; lblRightPol: TLabel; edtRightPol: TEdit; lblRightPolInputError: TLabel; lblOptions: TLabel; cbbOptions: TComboBox; btnCalculate: TButton; pnlOutput: TPanel; lblTask: TLabel; mmoTask: TMemo; lblResult: TLabel; mmoResult: TMemo; procedure edtLeftPolKeyPress(Sender: TObject; var Key: Char); procedure edtRightPolKeyPress(Sender: TObject; var Key: Char); procedure edtLeftPolExit(Sender: TObject); procedure edtRightPolEnter(Sender: TObject); procedure edtRightPolExit(Sender: TObject); procedure btnCalculateClick(Sender: TObject); procedure cbbOptionsChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); end; var MainForm: TMainForm; leftPol, rightPol: TPolynomial; leftPolString, rightPolString: string; implementation {$R *.dfm} procedure TMainForm.FormCreate(Sender: TObject); begin TryStrToPol('1 0 1 0 -3 -3 8 2 -5', leftPol); TryStrToPol('3 0 5 0 -4 -9 21', rightPol); leftPolString := '(x^8 + x^6 Ц 3x^4 Ц 3x^2 + 8x^2 + 2x Ц 5)'; rightPolString := '(3x^6 + 5x^4 Ц 4x^2 Ц 9x + 21)'; mmoTask.Lines[0] := leftPolString + ' + ' + rightPolString; mmoResult.Lines[0] := 'x^8 + 4x^6 + 2x^4 Ц 3x^3 + 4x^2 Ц 7x + 16'; end; function IsKeyValid(Key: Char): Boolean; begin Result := Key in ['0'..'9', '-', '.', #8, #32]; end; procedure TMainForm.edtLeftPolKeyPress(Sender: TObject; var Key: Char); begin if IsKeyValid(Key) then lblLeftPolInputError.Caption := '' else begin lblLeftPolInputError.Caption := '—имвол "' + Key + '" не входит в список допустимых символов'; Key := #0; end end; procedure TMainForm.edtRightPolKeyPress(Sender: TObject; var Key: Char); begin if IsKeyValid(Key) then lblRightPolInputError.Caption := '' else begin lblRightPolInputError.Caption := '—имвол "' + Key + '" не входит в список допустимых символов'; Key := #0; end end; procedure TMainForm.edtLeftPolExit(Sender: TObject); begin if TryStrToPol(edtLeftPol.Text, leftPol) then begin leftPolString := PolToStr(leftPol); if Pos(' ', leftPolString) <> 0 then leftPolString := '(' + leftPolString + ')'; mmoTask.Clear(); mmoTask.Lines[0] := leftPolString; if rightPolString <> '' then mmoTask.Lines[0] := mmoTask.Lines[0] + ' ' + OPERATIONS_SYMBOLS[cbbOptions.ItemIndex] + ' ' + rightPolString; lblLeftPolInputError.Caption := ''; end else begin leftPolString := ''; mmoTask.Lines[0] := rightPolString; lblLeftPolInputError.Caption := 'ќшибка, проверьте правильность ввода данных' end; end; procedure TMainForm.edtRightPolEnter(Sender: TObject); begin btnCalculate.Enabled := True; end; procedure TMainForm.edtRightPolExit(Sender: TObject); begin if TryStrToPol(edtRightPol.Text, rightPol) then begin rightPolString := PolToStr(rightPol); if Pos(' ', rightPolString) <> 0 then rightPolString := '(' + rightPolString + ')'; mmoTask.Clear(); mmoTask.Lines[0] := rightPolString; if leftPolString <> '' then mmoTask.Lines[0] := leftPolString + ' ' + OPERATIONS_SYMBOLS[cbbOptions.ItemIndex] + ' ' + mmoTask.Lines[0]; lblRightPolInputError.Caption := ''; end else begin rightPolString := ''; mmoTask.Lines[0] := leftPolString; lblRightPolInputError.Caption := 'ќшибка, проверьте правильность ввода данных' end; end; procedure TMainForm.cbbOptionsChange(Sender: TObject); begin if (leftPolString <> '') and (rightPolString <> '') then mmoTask.Lines[0] := leftPolString + ' ' + OPERATIONS_SYMBOLS[cbbOptions.ItemIndex] + ' ' + rightPolString; end; procedure TMainForm.btnCalculateClick(Sender: TObject); var quotient, remainder: TPolynomial; begin if (leftPolString <> '') and (rightPolString <> '') then begin mmoResult.Clear(); case cbbOptions.ItemIndex of 0: mmoResult.Lines[0] := PolToStr(PolSum(leftPol, rightPol)); 1: mmoResult.Lines[0] := PolToStr(PolSub(leftPol, rightPol)); 2: mmoResult.Lines[0] := PolToStr(PolMult(leftPol, rightPol)); else begin quotient := PolDiv(leftPol, rightPol, remainder); if remainder = nil then if quotient = nil then mmoResult.Lines[0] := 'ќшибка: ƒеление на 0 невозможно' else mmoResult.Lines[0] := '÷ела€ часть: ' + PolToStr(quotient) + #13#10 + 'ќстаток: 0' else mmoResult.Lines[0] := '÷ела€ часть: ' + PolToStr(quotient) + #13#10 + 'ќстаток: ' + PolToStr(remainder); end; end; end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if leftPol <> nil then PolDestroy(leftPol); if rightPol <> nil then PolDestroy(rightPol); 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.6 2004.10.27 9:17:46 AM czhower For TIdStrings Rev 1.5 10/26/2004 11:08:08 PM JPMugaas Updated refs. Rev 1.4 13.04.2004 12:56:44 ARybin M$ IE behavior Rev 1.3 2004.02.03 5:45:00 PM czhower Name changes Rev 1.2 2004.01.22 6:09:02 PM czhower IdCriticalSection Rev 1.1 1/22/2004 7:09:58 AM JPMugaas Tried to fix AnsiSameText depreciation. Rev 1.0 11/14/2002 02:16:20 PM JPMugaas Mar-31-2001 Doychin Bondzhev - Changes in the class heirarchy to implement Netscape specification[Netscape], RFC 2109[RFC2109] & 2965[RFC2965] Feb-2001 Doychin Bondzhev - Initial release } unit IdCookie; { Implementation of the HTTP State Management Mechanism as specified in RFC 6265. Author: Remy Lebeau (remy@lebeausoftware.org) Copyright: (c) Chad Z. Hower and The Indy Team. TIdCookie - The base code used in all cookies. REFERENCES ------------------- [RFC6265] Barth, A, "HTTP State Management Mechanism", RFC 6265, April 2011. [DRAFT-ORIGIN-01] Pettersen, Y, "Identifying origin server of HTTP Cookies", Internet-Draft, March 07, 2010. http://www.ietf.org/id/draft-pettersen-cookie-origin-01.txt [DRAFT-COOKIEv2-05] Pettersen, Y, "HTTP State Management Mechanism v2", Internet-Draft, March 07, 2010. http://www.ietf.org/id/draft-pettersen-cookie-v2-05.txt } interface {$I IdCompilerDefines.inc} uses Classes, IdGlobal, IdException, IdGlobalProtocols, IdURI, SysUtils; type TIdCookie = class; TIdCookieList = class(TList) protected function GetCookie(Index: Integer): TIdCookie; procedure SetCookie(Index: Integer; AValue: TIdCookie); public function IndexOfCookie(ACookie: TIdCookie): Integer; property Cookies[Index: Integer]: TIdCookie read GetCookie write SetCookie; default; end; { Base Cookie class as described in [RFC6265] } TIdCookie = class(TCollectionItem) protected FDomain: String; FExpires: TDateTime; FHttpOnly: Boolean; FName: String; FPath: String; FSecure: Boolean; FValue: String; FCreatedAt: TDateTime; FHostOnly: Boolean; FLastAccessed: TDateTime; FPersistent: Boolean; function GetIsExpired: Boolean; function GetServerCookie: String; virtual; function GetClientCookie: String; virtual; function GetMaxAge: Int64; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function IsAllowed(AURI: TIdURI; SecureOnly: Boolean): Boolean; virtual; function ParseClientCookie(const ACookieText: String): Boolean; virtual; function ParseServerCookie(const ACookieText: String; AURI: TIdURI): Boolean; virtual; property ClientCookie: String read GetClientCookie; property CookieName: String read FName write FName; property CookieText: String read GetServerCookie; // {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPECATED_MSG} 'Use ServerCookie property instead'{$ENDIF};{$ENDIF} property Domain: String read FDomain write FDomain; property Expires: TDateTime read FExpires write FExpires; property HttpOnly: Boolean read FHttpOnly write FHttpOnly; property Path: String read FPath write FPath; property Secure: Boolean read FSecure write FSecure; property ServerCookie: String read GetServerCookie; property Value: String read FValue write FValue; property MaxAge: Int64 read GetMaxAge; property CreatedAt: TDateTime read FCreatedAt write FCreatedAt; property IsExpired: Boolean read GetIsExpired; property HostOnly: Boolean read FHostOnly write FHostOnly; property LastAccessed: TDateTime read FLastAccessed write FLastAccessed; property Persistent: Boolean read FPersistent write FPersistent; end; TIdCookieClass = class of TIdCookie; { The Cookie collection } TIdCookieAccess = (caRead, caReadWrite); TIdCookies = class(TOwnedCollection) protected FCookieList: TIdCookieList; FRWLock: TMultiReadExclusiveWriteSynchronizer; function GetCookieByNameAndDomain(const AName, ADomain: string): TIdCookie; function GetCookie(Index: Integer): TIdCookie; procedure SetCookie(Index: Integer; const Value: TIdCookie); public constructor Create(AOwner: TPersistent); destructor Destroy; override; function Add: TIdCookie; reintroduce; function AddCookie(ACookie: TIdCookie; AURI: TIdURI; AReplaceOld: Boolean = True): Boolean; function AddClientCookie(const ACookie: string): TIdCookie; procedure AddClientCookies(const ACookie: string); overload; procedure AddClientCookies(const ACookies: TStrings); overload; function AddServerCookie(const ACookie: string; AURI: TIdURI): TIdCookie; procedure AddServerCookies(const ACookies: TStrings; AURI: TIdURI); procedure AddCookies(ASource: TIdCookies); procedure Assign(ASource: TPersistent); override; procedure Clear; reintroduce; function GetCookieIndex(const AName: string; FirstIndex: Integer = 0): Integer; overload; function GetCookieIndex(const AName, ADomain: string; FirstIndex: integer = 0): Integer; overload; function LockCookieList(AAccessType: TIdCookieAccess): TIdCookieList; procedure UnlockCookieList(AAccessType: TIdCookieAccess); property Cookie[const AName, ADomain: string]: TIdCookie read GetCookieByNameAndDomain; property Cookies[Index: Integer]: TIdCookie read GetCookie write SetCookie; Default; end; EIdCookieError = class(EIdException); function IsDomainMatch(const AUriHost, ACookieDomain: String): Boolean; function IsPathMatch(const AUriPath, ACookiePath: String): Boolean; function CanonicalizeHostName(const AHost: String): String; implementation uses {$IFDEF VCL_XE3_OR_ABOVE} System.Types, {$ENDIF} IdAssignedNumbers, IdResourceStringsProtocols; function GetDefaultPath(const AURL: TIdURI): String; var Idx: Integer; begin { Per RFC 6265, Section 5.1.4: The user agent MUST use an algorithm equivalent to the following algorithm to compute the default-path of a cookie: 1. Let uri-path be the path portion of the request-uri if such a portion exists (and empty otherwise). For example, if the request-uri contains just a path (and optional query string), then the uri-path is that path (without the %x3F ("?") character or query string), and if the request-uri contains a full absoluteURI, the uri-path is the path component of that URI. 2. If the uri-path is empty or if the first character of the uri- path is not a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. 3. If the uri-path contains no more than one %x2F ("/") character, output %x2F ("/") and skip the remaining steps. 4. Output the characters of the uri-path from the first character up to, but not including, the right-most %x2F ("/"). } if TextStartsWith(AURL.Path, '/') then begin {do not localize} Idx := RPos('/', AURL.Path); {do not localize} if Idx > 1 then begin Result := Copy(AURL.Path, 1, Idx-1); Exit; end; end; Result := '/'; {do not localize} end; function CanonicalizeHostName(const AHost: String): String; begin // TODO: implement this { Per RFC 6265 Section 5.1.2: A canonicalized host name is the string generated by the following algorithm: 1. Convert the host name to a sequence of individual domain name labels. 2. Convert each label that is not a Non-Reserved LDH (NR_LDH) label, to an A-label (see Section 2.3.2.1 of [RFC5890] for the fomer and latter), or to a "punycode label" (a label resulting from the "ToASCII" conversion in Section 4 of [RFC3490]), as appropriate (see Section 6.3 of this specification). 3. Concatentate the resulting labels, separated by a %x2E (".") character. } Result := AHost; end; function IsDomainMatch(const AUriHost, ACookieDomain: String): Boolean; var LHost, LDomain: String; begin { Per RFC 6265 Section 5.1.3: A string domain-matches a given domain string if at least one of the following conditions hold: o The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.) o All of the following conditions hold: * The domain string is a suffix of the string. * The last character of the string that is not included in the domain string is a %x2E (".") character. * The string is a host name (i.e., not an IP address). } Result := False; LHost := CanonicalizeHostName(AUriHost); LDomain := CanonicalizeHostName(ACookieDomain); if (LHost <> '') and (LDomain <> '') then begin if TextIsSame(LHost, LDomain) then begin Result := True; end else if TextEndsWith(LHost, LDomain) then begin if TextEndsWith(Copy(LHost, 1, Length(LHost)-Length(LDomain)), '.') then begin Result := IsHostName(LHost); end; end; end; end; function IsPathMatch(const AUriPath, ACookiePath: String): Boolean; begin { Per RFC 6265 Section 5.1.4: A request-path path-matches a given cookie-path if at least one of the following conditions hold: o The cookie-path and the request-path are identical. o The cookie-path is a prefix of the request-path and the last character of the cookie-path is %x2F ("/"). o The cookie-path is a prefix of the request-path and the first character of the request-path that is not included in the cookie- path is a %x2F ("/") character. } Result := TextIsSame(AUriPath, ACookiePath) or ( TextStartsWith(AUriPath, ACookiePath) and ( TextEndsWith(ACookiePath, '/') or CharEquals(AUriPath, Length(ACookiePath)+1, '/') ) ); end; function IsHTTP(const AProtocol: String): Boolean; begin Result := PosInStrArray(AProtocol, ['http', 'https'], False) <> -1; {do not localize} end; { base functions used for construction of Cookie text } procedure AddCookieProperty(var VCookie: String; const AProperty, AValue: String); begin if Length(AValue) > 0 then begin if Length(VCookie) > 0 then begin VCookie := VCookie + '; '; {Do not Localize} end; // TODO: encode illegal characters? VCookie := VCookie + AProperty + '=' + AValue; {Do not Localize} end; end; procedure AddCookieFlag(var VCookie: String; const AFlag: String); begin if Length(VCookie) > 0 then begin VCookie := VCookie + '; '; { Do not Localize } end; VCookie := VCookie + AFlag; end; { TIdCookieList } function TIdCookieList.GetCookie(Index: Integer): TIdCookie; begin Result := TIdCookie(Items[Index]); end; procedure TIdCookieList.SetCookie(Index: Integer; AValue: TIdCookie); begin Items[Index] := AValue; end; function TIdCookieList.IndexOfCookie(ACookie: TIdCookie): Integer; begin for Result := 0 to Count - 1 do begin if GetCookie(Result) = ACookie then begin Exit; end; end; Result := -1; end; { TIdCookie } constructor TIdCookie.Create(ACollection: TCollection); begin inherited Create(ACollection); FCreatedAt := Now; FLastAccessed := FCreatedAt; end; destructor TIdCookie.Destroy; var LCookieList: TIdCookieList; begin try if Assigned(Collection) then begin LCookieList := TIdCookies(Collection).LockCookieList(caReadWrite); try LCookieList.Remove(Self); finally TIdCookies(Collection).UnlockCookieList(caReadWrite); end; end; finally inherited Destroy; end; end; procedure TIdCookie.Assign(Source: TPersistent); begin if Source is TIdCookie then begin with TIdCookie(Source) do begin Self.FDomain := FDomain; Self.FExpires := FExpires; Self.FHttpOnly := FHttpOnly; Self.FName := FName; Self.FPath := FPath; Self.FSecure := FSecure; Self.FValue := FValue; Self.FCreatedAt := FCreatedAt; Self.FHostOnly := FHostOnly; Self.FLastAccessed := FLastAccessed; Self.FPersistent := FPersistent; end; end else begin inherited Assign(Source); end; end; function TIdCookie.IsAllowed(AURI: TIdURI; SecureOnly: Boolean): Boolean; function MatchesHost: Boolean; begin if HostOnly then begin Result := TextIsSame(CanonicalizeHostName(AURI.Host), Domain); end else begin Result := IsDomainMatch(AURI.Host, Domain); end; end; begin // using the algorithm defined in RFC 6265 section 5.4... Result := MatchesHost and IsPathMatch(AURI.Path, Path) and ((not Secure) or (Secure and SecureOnly)) and ((not HttpOnly) or (HttpOnly and IsHTTP(AURI.Protocol))); end; {$IFNDEF HAS_TryStrToInt64} function TryStrToInt64(const S: string; out Value: Int64): Boolean; {$IFDEF USE_INLINE}inline;{$ENDIF} var E: Integer; begin Val(S, Value, E); Result := E = 0; end; {$ENDIF} function TIdCookie.ParseServerCookie(const ACookieText: String; AURI: TIdURI): Boolean; const cTokenSeparators = '()<>@,;:\"/[]?={} '#9; var CookieProp: TStringList; S: string; LSecs: Int64; procedure SplitCookieText; var LNameValue, LAttrs, LAttr, LName, LValue: String; LExpiryTime: TDateTime; i: Integer; begin I := Pos(';', ACookieText); if I > 0 then begin LNameValue := Copy(ACookieText, 1, I-1); LAttrs := Copy(ACookieText, I, MaxInt); end else begin LNameValue := ACookieText; LAttrs := ''; end; I := Pos('=', LNameValue); if I = 0 then begin Exit; end; LName := Trim(Copy(LNameValue, 1, I-1)); if LName = '' then begin Exit; end; LValue := Trim(Copy(LNameValue, I+1, MaxInt)); if TextStartsWith(LValue, '"') then begin IdDelete(LValue, 1, 1); LNameValue := LValue; LValue := Fetch(LNameValue, '"'); end; CookieProp.Add(LName + '=' + LValue); while LAttrs <> '' do begin IdDelete(LAttrs, 1, 1); I := Pos(';', LAttrs); if I > 0 then begin LAttr := Copy(LAttrs, 1, I-1); LAttrs := Copy(LAttrs, I, MaxInt); end else begin LAttr := LAttrs; LAttrs := ''; end; I := Pos('=', LAttr); if I > 0 then begin LName := Trim(Copy(LAttr, 1, I-1)); LValue := Trim(Copy(LAttr, I+1, MaxInt)); // RLebeau: RFC 6265 does not account for quoted attribute values, // despite several complaints asking for it. We'll do it anyway in // the hopes that the RFC will be updated to "do the right thing"... if TextStartsWith(LValue, '"') then begin IdDelete(LValue, 1, 1); LNameValue := LValue; LValue := Fetch(LNameValue, '"'); end; end else begin LName := Trim(LAttr); LValue := ''; end; case PosInStrArray(LName, ['Expires', 'Max-Age', 'Domain', 'Path', 'Secure', 'HttpOnly'], False) of 0: begin if TryStrToInt64(LValue, LSecs) then begin // Not in the RFCs, but some servers specify Expires as an // integer number in seconds instead of using Max-Age... if LSecs >= 0 then begin LExpiryTime := (Now + LSecs * 1000 / MSecsPerDay); end else begin LExpiryTime := EncodeDate(1, 1, 1); end; CookieProp.Add('EXPIRES=' + FloatToStr(LExpiryTime)); end else begin LExpiryTime := CookieStrToLocalDateTime(LValue); if LExpiryTime <> 0.0 then begin CookieProp.Add('EXPIRES=' + FloatToStr(LExpiryTime)); end; end; end; 1: begin if TryStrToInt64(LValue, LSecs) then begin if LSecs >= 0 then begin LExpiryTime := (Now + LSecs * 1000 / MSecsPerDay); end else begin LExpiryTime := EncodeDate(1, 1, 1); end; CookieProp.Add('MAX-AGE=' + FloatToStr(LExpiryTime)); end; end; 2: begin if LValue <> '' then begin if TextStartsWith(LValue, '.') then begin {do not localize} LValue := Copy(LValue, 2, MaxInt); end; // RLebeau: have encountered one cookie in the 'Set-Cookie' header that // includes a port number in the domain, though the RFCs do not indicate // this is allowed. RFC 2965 defines an explicit "port" attribute in the // 'Set-Cookie2' header for that purpose instead. We'll just strip it off // here if present... I := Pos(':', LValue); if I > 0 then begin LValue := Copy(S, 1, I-1); end; CookieProp.Add('DOMAIN=' + LowerCase(LValue)); end; end; 3: begin if (LValue = '') or (not TextStartsWith(LValue, '/')) then begin LValue := GetDefaultPath(AURI); end; CookieProp.Add('PATH=' + LValue); end; 4: begin CookieProp.Add('SECURE='); end; 5: begin CookieProp.Add('HTTPONLY='); end; end; end; end; function GetLastValueOf(const AName: String; var VValue: String): Boolean; var I: Integer; begin Result := False; for I := CookieProp.Count-1 downto 0 do begin if TextIsSame(CookieProp.Names[I], AName) then begin {$IFDEF HAS_TStrings_ValueFromIndex} VValue := CookieProp.ValueFromIndex[I]; {$ELSE} VValue := Copy(CookieProp[I], Pos('=', CookieProp[I])+1, MaxInt); {Do not Localize} {$ENDIF} Result := True; Exit; end; end; end; begin Result := False; // using the algorithm defined in RFC 6265 section 5.2... CookieProp := TStringList.Create; try SplitCookieText; if CookieProp.Count = 0 then begin Exit; end; FName := CookieProp.Names[0]; {$IFDEF HAS_TStrings_ValueFromIndex} FValue := CookieProp.ValueFromIndex[0]; {$ELSE} S := CookieProp[0]; FValue := Copy(S, Pos('=', S)+1, MaxInt); {$ENDIF} CookieProp.Delete(0); FCreatedAt := Now; FLastAccessed := FCreatedAt; // using the algorithms defined in RFC 6265 section 5.3... if GetLastValueOf('MAX-AGE', S) then begin {Do not Localize} FPersistent := True; FExpires := StrToFloat(S); end else if GetLastValueOf('EXPIRES', S) then {Do not Localize} begin FPersistent := True; FExpires := StrToFloat(S); end else begin FPersistent := False; FExpires := EncodeDate(9999, 12, 31) + EncodeTime(23, 59, 59, 999); end; S := ''; if GetLastValueOf('DOMAIN', S) then {Do not Localize} begin // TODO { If the user agent is configured to reject "public suffixes" and the domain-attribute is a public suffix: If the domain-attribute is identical to the canonicalized request-host: Let the domain-attribute be the empty string. Otherwise: Ignore the cookie entirely and abort these steps. NOTE: A "public suffix" is a domain that is controlled by a public registry, such as "com", "co.uk", and "pvt.k12.wy.us". This step is essential for preventing attacker.com from disrupting the integrity of example.com by setting a cookie with a Domain attribute of "com". Unfortunately, the set of public suffixes (also known as "registry controlled domains") changes over time. If feasible, user agents SHOULD use an up-to-date public suffix list, such as the one maintained by the Mozilla project at <http://publicsuffix.org/>. } { if RejectPublicSuffixes and IsPublicSuffix(S) then begin if S <> CanonicalizeHostName(AURI.Host) then begin Exit; end; S := ''; end; } end; if Length(S) > 0 then begin if not IsDomainMatch(AURI.Host, S) then begin Exit; end; FHostOnly := False; FDomain := S; end else begin FHostOnly := True; FDomain := CanonicalizeHostName(AURI.Host); end; if GetLastValueOf('PATH', S) then begin {Do not Localize} FPath := S; end else begin FPath := GetDefaultPath(AURI); end; FSecure := CookieProp.IndexOfName('SECURE') <> -1; { Do not Localize } FHttpOnly := CookieProp.IndexOfName('HTTPONLY') <> -1; { Do not Localize } if FHttpOnly and (not IsHTTP(AURI.Protocol)) then begin Exit; end; Result := True; finally FreeAndNil(CookieProp); end; end; function TIdCookie.GetIsExpired: Boolean; begin Result := (FExpires <> 0.0) and (FExpires < Now); end; function TIdCookie.GetMaxAge: Int64; begin if FExpires <> 0.0 then begin Result := Trunc((FExpires - Now) * MSecsPerDay / 1000); end else begin Result := -1; end; end; { set-cookie-header = "Set-Cookie:" SP set-cookie-string set-cookie-string = cookie-pair *( ";" SP cookie-av ) cookie-pair = cookie-name "=" cookie-value cookie-name = token cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E ; US-ASCII characters excluding CTLs, ; whitespace DQUOTE, comma, semicolon, ; and backslash token = <token, defined in [RFC2616], Section 2.2> cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / httponly-av / extension-av expires-av = "Expires=" sane-cookie-date sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1> max-age-av = "Max-Age=" non-zero-digit *DIGIT ; In practice, both expires-av and max-age-av ; are limited to dates representable by the ; user agent. non-zero-digit = %x31-39 ; digits 1 through 9 domain-av = "Domain=" domain-value domain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as ; enhanced by [RFC1123], Section 2.1 path-av = "Path=" path-value path-value = <any CHAR except CTLs or ";"> secure-av = "Secure" httponly-av = "HttpOnly" extension-av = <any CHAR except CTLs or ";"> } function TIdCookie.GetServerCookie: String; var LExpires: TDateTime; LMaxAge: Int64; begin Result := FName + '=' + FValue; {Do not Localize} AddCookieProperty(Result, 'Path', FPath); {Do not Localize} AddCookieProperty(Result, 'Domain', FDomain); {Do not Localize} if FSecure then begin AddCookieFlag(Result, 'Secure'); {Do not Localize} end; if FHttpOnly then begin AddCookieFlag(Result, 'HttpOnly'); {Do not Localize} end; LMaxAge := MaxAge; if LMaxAge >= 0 then begin AddCookieProperty(Result, 'Max-Age', IntToStr(LMaxAge)); {Do not Localize} end; LExpires := Expires; if LExpires <> 0.0 then begin AddCookieProperty(Result, 'Expires', LocalDateTimeToCookieStr(LExpires)); {Do not Localize} end; end; { Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ... } function TIdCookie.GetClientCookie: String; begin Result := FName + '=' + FValue; end; { cookie-header = "Cookie:" OWS cookie-string OWS cookie-string = cookie-pair *( ";" SP cookie-pair ) } function TIdCookie.ParseClientCookie(const ACookieText: String): Boolean; var CookieProp: TStringList; procedure SplitCookieText; var LTemp, LName, LValue: String; i: Integer; IsFlag: Boolean; begin LTemp := Trim(ACookieText); while LTemp <> '' do {Do not Localize} begin i := FindFirstOf('=;', LTemp); {Do not Localize} if i = 0 then begin CookieProp.Add(LTemp); Break; end; IsFlag := (LTemp[i] = ';'); {Do not Localize} LName := TrimRight(Copy(LTemp, 1, i-1)); LTemp := TrimLeft(Copy(LTemp, i+1, MaxInt)); LValue := ''; if (not IsFlag) and (LTemp <> '') then begin if LTemp[1] = '"' then begin IdDelete(LTemp, 1, 1); LValue := Fetch(LTemp, '"'); {Do not Localize} Fetch(LTemp, ';'); {Do not Localize} end else begin LValue := Trim(Fetch(LTemp, ';')); {Do not Localize} end; LTemp := TrimLeft(LTemp); end; if LName <> '' then begin CookieProp.Add(LName + '=' + LValue); {Do not Localize} end; end; end; begin Result := False; CookieProp := TStringList.Create; try SplitCookieText; if CookieProp.Count = 0 then begin Exit; end; FName := CookieProp.Names[0]; {$IFDEF HAS_TStrings_ValueFromIndex} FValue := CookieProp.ValueFromIndex[0]; {$ELSE} FValue := Copy(CookieProp[0], Pos('=', CookieProp[0])+1, MaxInt); {$ENDIF} Result := True; finally FreeAndNil(CookieProp); end; end; { TIdCookies } constructor TIdCookies.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdCookie); FRWLock := TMultiReadExclusiveWriteSynchronizer.Create; FCookieList := TIdCookieList.Create; end; destructor TIdCookies.Destroy; begin // This will force the Cookie removing process before we free FCookieList and FRWLock Self.Clear; FreeAndNil(FCookieList); FreeAndNil(FRWLock); inherited Destroy; end; function TIdCookies.Add: TIdCookie; begin Result := TIdCookie(inherited Add); end; function TIdCookies.AddCookie(ACookie: TIdCookie; AURI: TIdURI; AReplaceOld: Boolean = True): Boolean; var LOldCookie: TIdCookie; I: Integer; begin Result := False; LockCookieList(caReadWrite); try if AReplaceOld then begin for I := 0 to FCookieList.Count-1 do begin LOldCookie := FCookieList[I]; if not TextIsSame(LOldCookie.CookieName, ACookie.CookieName) then begin Continue; end; if not TextIsSame(LOldCookie.Domain, ACookie.Domain) then begin Continue; end; if not TextIsSame(LOldCookie.Path, ACookie.Path) then begin Continue; end; if ((AURI <> nil) and (not IsHTTP(AURI.Protocol))) and LOldCookie.HttpOnly then begin Exit; end; ACookie.FCreatedAt := LOldCookie.CreatedAt; FCookieList.Delete(I); LOldCookie.Collection := nil; LOldCookie.Free; Break; end; end; if not ACookie.IsExpired then begin FCookieList.Add(ACookie); Result := True; end; finally UnlockCookieList(caReadWrite); end; end; procedure TIdCookies.Assign(ASource: TPersistent); begin if (ASource = nil) or (ASource is TIdCookies) then begin LockCookieList(caReadWrite); try Clear; AddCookies(TIdCookies(ASource)); finally UnlockCookieList(caReadWrite); end; end else begin inherited Assign(ASource); end; end; function TIdCookies.GetCookie(Index: Integer): TIdCookie; begin Result := inherited GetItem(Index) as TIdCookie; end; procedure TIdCookies.SetCookie(Index: Integer; const Value: TIdCookie); begin inherited SetItem(Index, Value); end; function TIdCookies.AddClientCookie(const ACookie: string): TIdCookie; var LCookie: TIdCookie; begin Result := nil; LCookie := Add; try if LCookie.ParseClientCookie(ACookie) then begin LockCookieList(caReadWrite); try FCookieList.Add(LCookie); Result := LCookie; LCookie := nil; finally UnlockCookieList(caReadWrite); end; end; finally if LCookie <> nil then begin LCookie.Collection := nil; LCookie.Free; end; end; end; procedure TIdCookies.AddClientCookies(const ACookie: string); var Temp: TStringList; LCookie, S: String; I: Integer; begin S := Trim(ACookie); if S <> '' then begin Temp := TStringList.Create; try repeat LCookie := Fetch(S, ';'); if LCookie <> '' then begin Temp.Add(LCookie); end; until S = ''; for I := 0 to Temp.Count-1 do begin AddClientCookie(Temp[I]); end; finally Temp.Free; end; end; end; procedure TIdCookies.AddClientCookies(const ACookies: TStrings); var i: Integer; begin for i := 0 to ACookies.Count - 1 do begin AddClientCookies(ACookies[i]); end; end; function TIdCookies.AddServerCookie(const ACookie: string; AURI: TIdURI): TIdCookie; var LCookie: TIdCookie; begin Result := nil; LCookie := Add; try if LCookie.ParseServerCookie(ACookie, AURI) then begin if AddCookie(LCookie, AURI) then begin Result := LCookie; LCookie := nil; end; end; finally if LCookie <> nil then begin LCookie.Collection := nil; LCookie.Free; end; end; end; procedure TIdCookies.AddServerCookies(const ACookies: TStrings; AURI: TIdURI); var i: Integer; begin for i := 0 to ACookies.Count - 1 do begin AddServerCookie(ACookies[i], AURI); end; end; procedure TIdCookies.AddCookies(ASource: TIdCookies); var LSrcCookies: TIdCookieList; LSrcCookie, LDestCookie: TIdCookie; i: Integer; begin if (ASource <> nil) and (ASource <> Self) then begin LSrcCookies := ASource.LockCookieList(caRead); try LockCookieList(caReadWrite); try for i := 0 to LSrcCookies.Count - 1 do begin LSrcCookie := LSrcCookies.Cookies[i]; LDestCookie := TIdCookieClass(LSrcCookie.ClassType).Create(Self); try LDestCookie.Assign(LSrcCookie); FCookieList.Add(LDestCookie); except LDestCookie.Collection := nil; LDestCookie.Free; raise; end; end; finally UnlockCookieList(caReadWrite); end; finally ASource.UnlockCookieList(caRead); end; end; end; function TIdCookies.GetCookieByNameAndDomain(const AName, ADomain: string): TIdCookie; var i: Integer; begin i := GetCookieIndex(AName, ADomain); if i = -1 then begin Result := nil; end else begin Result := Cookies[i]; end; end; function TIdCookies.GetCookieIndex(const AName: string; FirstIndex: Integer = 0): Integer; var i: Integer; begin Result := -1; for i := FirstIndex to Count - 1 do begin if TextIsSame(Cookies[i].CookieName, AName) then begin Result := i; Exit; end; end; end; function TIdCookies.GetCookieIndex(const AName, ADomain: string; FirstIndex: Integer = 0): Integer; var LCookie: TIdCookie; i: Integer; begin Result := -1; for i := FirstIndex to Count - 1 do begin LCookie := Cookies[i]; if TextIsSame(LCookie.CookieName, AName) and TextIsSame(CanonicalizeHostName(LCookie.Domain), CanonicalizeHostName(ADomain)) then begin Result := i; Exit; end; end; end; procedure TIdCookies.Clear; begin LockCookieList(caReadWrite); try FCookieList.Clear; inherited Clear; finally UnlockCookieList(caReadWrite); end; end; function TIdCookies.LockCookieList(AAccessType: TIdCookieAccess): TIdCookieList; begin case AAccessType of caRead: begin FRWLock.BeginRead; end; caReadWrite: begin FRWLock.BeginWrite; end; end; Result := FCookieList; end; procedure TIdCookies.UnlockCookieList(AAccessType: TIdCookieAccess); begin case AAccessType of caRead: begin FRWLock.EndRead; end; caReadWrite: begin FRWLock.EndWrite; end; end; end; end.
program Tester(input, output); var I: Integer; begin {tester} Writeln; Writeln; Write('Please enter an integer value for I: '); Read(I); I := I + 1; Writeln('The current value of I is ', I:0); Writeln; Writeln; end. {tester}
unit vcmBaseOperationsCollectionItem; {* Элемент коллекции операций. } { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmBaseOperationsCollectionItem - } { Начат: 11.03.2003 12:22 } { $Id: vcmBaseOperationsCollectionItem.pas,v 1.188 2013/07/18 12:28:34 morozov Exp $ } // $Log: vcmBaseOperationsCollectionItem.pas,v $ // Revision 1.188 2013/07/18 12:28:34 morozov // {RequestLink:273597589} // // Revision 1.187 2013/07/01 12:28:52 morozov // {RequestLink:382416588} // // Revision 1.186 2013/04/25 14:22:38 lulin // - портируем. // // Revision 1.185 2013/04/24 09:35:37 lulin // - портируем. // // Revision 1.184 2013/02/14 15:20:04 lulin // {RequestLink:430737914} // // Revision 1.183 2012/11/23 08:23:29 kostitsin // чиню сборку // // Revision 1.182 2012/11/22 12:47:46 kostitsin // [$407738353] // // Revision 1.181 2012/08/07 14:37:42 lulin // {RequestLink:358352265} // // Revision 1.180 2012/07/17 11:12:09 lulin // {RequestLink:378541134} // // Revision 1.179 2012/04/13 18:22:34 lulin // {RequestLink:237994598} // // Revision 1.178 2012/04/09 08:38:58 lulin // {RequestLink:237994598} // - думаем о VGScene. // // Revision 1.177 2012/03/22 06:40:09 lulin // - чистим код от мусора. // // Revision 1.176 2011/12/08 16:30:03 lulin // {RequestLink:273590436} // - чистка кода. // // Revision 1.175 2011/06/20 13:46:02 lulin // {RequestLink:269081712}. // // Revision 1.174 2011/01/24 16:11:50 lulin // {RequestLink:236719144}. // // Revision 1.173 2010/09/15 18:15:01 lulin // {RequestLink:235047275}. // // Revision 1.172 2010/09/13 10:37:10 lulin // {RequestLink:197496539}. // // Revision 1.171 2010/09/10 16:24:33 lulin // {RequestLink:197496539}. // // Revision 1.170 2010/09/10 16:12:44 lulin // {RequestLink:197496539}. // // Revision 1.169 2010/08/31 18:25:46 lulin // {RequestLink:224134305}. // // Revision 1.168 2010/07/15 11:40:33 lulin // {RequestLink:207389954}. // // Revision 1.167 2010/07/12 12:57:39 lulin // {RequestLink:207389954}. // - переносим на модель форму "Документ". // // Revision 1.166 2010/07/06 15:28:58 lulin // {RequestLink:197496539}. // - убираем опции операций модулей. Оставляем их только в StdRes. // // Revision 1.165 2010/04/30 15:15:44 lulin // {RequestLink:207389954}. // - чистка комментариев. // // Revision 1.164 2010/03/16 15:47:49 lulin // {RequestLink:196968958}. // - bug fix: отвалились кнопки в КЗ. // // Revision 1.163 2010/03/16 14:50:54 lulin // {RequestLink:196968958}. // [$197496457]. // [$197496566]. // // Revision 1.162 2010/01/15 14:34:57 lulin // {RequestLink:178324372}. // // Revision 1.161 2009/11/18 13:06:00 lulin // - используем базовые параметры операции. // // Revision 1.160 2009/11/12 18:07:34 lulin // - убираем ненужные возвращаемые значения. // // Revision 1.159 2009/11/12 14:32:02 lulin // - убираем возможность менять список параметров. // // Revision 1.158 2009/11/06 13:06:19 lulin // - избавился от ручной передачи параметров через поле Data. // // Revision 1.157 2009/10/23 12:46:05 lulin // {RequestLink:167353056}. Пляски с бубном вокруг тулбаров. // // Revision 1.156 2009/09/30 15:23:00 lulin // - убираем ненужное приведение ко вполне понятным интерфейсам. // // Revision 1.155 2009/09/28 17:12:48 lulin // {RequestLink:159360578}. №31. // // Revision 1.154 2009/09/17 09:47:24 lulin // - операции модуля публикуем в run-time, а не в формах. // // Revision 1.153 2009/08/28 17:15:47 lulin // - начинаем публикацию и описание внутренних операций. // // Revision 1.152 2009/08/20 17:19:04 lulin // {RequestLink:159360595}. // // Revision 1.151 2009/08/11 14:24:03 lulin // {RequestLink:129240934}. №16. // // Revision 1.150 2009/08/06 13:27:16 lulin // {RequestLink:129240934}. №26. // // Revision 1.149 2009/02/20 18:50:23 lulin // - <K>: 136941122. Убираем передачу параметров при запросе состояния операции. // // Revision 1.148 2009/02/20 17:57:39 lulin // - <K>: 136941122. Чистка кода. // // Revision 1.147 2009/02/20 17:29:20 lulin // - чистка комментариев. // // Revision 1.146 2009/02/20 15:19:00 lulin // - <K>: 136941122. // // Revision 1.145 2009/02/20 13:44:19 lulin // - <K>: 136941122. // // Revision 1.144 2009/02/12 17:09:15 lulin // - <K>: 135604584. Выделен модуль с внутренними константами. // // Revision 1.143 2009/02/04 15:33:55 lulin // - исправляем ошибку ненахождения методов. http://mdp.garant.ru/pages/viewpage.action?pageId=136260278&focusedCommentId=136260289#comment-136260289 // // Revision 1.142 2009/02/04 09:53:46 lulin // - неправильная методика лечения <K>: 136259417. // // Revision 1.141 2009/02/03 15:44:42 lulin // - <K>: 135136020. Заготовка для переноса на модель. // // Revision 1.140 2008/03/24 08:48:43 lulin // - <K>: 87591840. // // Revision 1.139 2007/08/08 13:26:06 lulin // - были недоступны пункты меню (<K>-34505100). // // Revision 1.138 2007/08/08 10:06:49 lulin // - присвоенность обработчиков операций проверяем один раз. // // Revision 1.137 2007/08/08 08:17:22 lulin // - по-другому подкладываем отбаботчики от формы - чтобы не было коллизий с обработчиками ит контролов. // // Revision 1.136 2007/08/07 18:51:41 lulin // - если для активного контрола не найдены обработчики операции, то пытаемся найти их для формы, которая этот контрол содержит. // // Revision 1.135 2007/07/10 12:40:10 lulin // - теперь если у формы в фокусе нет операции, то транслируем операцию форме в Parent-зоне (CQ-25867, <K>-29392957). // // Revision 1.134 2007/04/26 13:29:43 oman // - new: Жирность можно задавать в DesignTime - добавилось // свойство <_Operation>.IsDefault (cq24612) // // Revision 1.133 2007/04/26 11:43:11 oman // - fix: Жирность в пункте меню теперь делается не типом операции // vcm_otLabel, а флагом vcm_ofDefault (cq24612) // // Revision 1.132 2007/04/04 10:24:19 oman // - new: Новый тип операции vcm_otLabel - метка которая показывается // только в меню и не вылезает на тулбар. В меню всегда // отображается как Default (жирным) (cq24612) // // Revision 1.131 2007/02/13 13:28:24 lulin // - переводим на строки с кодировкой. // // Revision 1.130 2007/02/13 12:09:00 lulin // - переводим на строки с кодировкой. // // Revision 1.129 2007/02/07 12:58:11 oman // - fix: Множество vcm_InternalOperations переименовано в // vcm_HiddenOperations и из него выделены собственно // vcm_InternalOperations - иначе не выливались Hidden операции // (cq24357) // // Revision 1.128 2007/01/26 11:53:02 oman // - fix: Операции без назначенных обработчиков не были видимы // пользователю (cq24210) // // Revision 1.127 2007/01/23 13:31:36 lulin // - убран метод установки контейнера. // // Revision 1.126 2007/01/20 20:28:50 lulin // - удаляем с параметров операции диспетчера. // // Revision 1.125 2007/01/20 17:35:45 lulin // - разрешаем вызывать операции только по заранее известным идентификаторам. // // Revision 1.124 2007/01/20 15:31:09 lulin // - разделяем параметры операции для выполнения и для тестирования. // // Revision 1.123 2007/01/18 13:13:44 lulin // - разводим в стороны параметры для теста и для выполнения. // // Revision 1.122 2007/01/18 12:09:20 lulin // - разводим в стороны параметры для теста и для выполнения. // // Revision 1.121 2007/01/18 09:06:51 lulin // - с общих параметров убраны тестовые опции. // // Revision 1.120 2007/01/17 18:47:33 lulin // - сужаем список параметров для тестирования операции. // // Revision 1.119 2007/01/17 17:53:40 lulin // - сужаем список параметров для тестирования операции. // // Revision 1.118 2007/01/17 14:02:44 lulin // - вычищены последние нефиксированные параметры в тестах операций. // // Revision 1.117 2007/01/17 12:27:30 lulin // - избавляемся от нефиксированного параметра - расширенной подсказки операции. // // Revision 1.116 2007/01/16 14:27:30 lulin // - избавляемся от нефиксированного параметра - подсказки операции. // // Revision 1.115 2007/01/16 14:13:11 lulin // - избавляемся от нефиксированного параметра - заголовка операции. // // Revision 1.114 2007/01/16 13:47:31 lulin // - избавляемся от нефиксированного параметра - горячей клавиши. // // Revision 1.113 2007/01/16 12:06:38 lulin // - избавляемся от нефиксированного параметра - индекс картинки. // // Revision 1.112 2007/01/15 17:17:07 lulin // - cleanup. // // Revision 1.111 2007/01/11 11:15:06 lulin // - вводим "родные" ноды. // // Revision 1.110 2007/01/05 18:17:33 lulin // - используем базовые ноды для выпадающих списков. // // Revision 1.109 2007/01/05 12:05:39 lulin // - убрано вредное непосредственное приведение к интерфейсу. // // Revision 1.108 2006/12/28 14:42:05 lulin // - bug fix: пропадал Shortcut операции, если он не был определен у текущего состояния. // // Revision 1.107 2006/11/14 12:02:20 oman // Merge from B_NEMESIS_6_4 // // Revision 1.106 2006/11/03 11:00:32 lulin // - объединил с веткой 6.4. // // Revision 1.105.2.1.2.1 2006/11/14 12:00:35 oman // - fix: Паразитные операции (cq23620, 23621) // // Revision 1.105.2.1 2006/10/31 13:36:17 mmorozov // - bugfix: для Exclude операций вызывался OnTest (CQ: OIT5-23330); // // Revision 1.105 2006/09/07 10:41:57 oman // - fix: Если у операции опубликованной контролом нет ни одного // OnTest, то она запрещалась и больше не разрешалась. // // Revision 1.104 2006/06/15 12:22:15 oman // - fix: Для публикуемых контролом операций OnTest и OnExecute от // контрола вызывался до перекрытых на форме обработчиков (cq21328) // // Revision 1.103 2006/06/07 12:53:02 oman // - fix: При восстановлении настроек терялись DesignTime шорткаты - // другим макаром (cq21257) // // Revision 1.102 2006/06/06 10:55:56 oman // - fix: Проблемы с вычитыванием шорткатов при переключении конфигураций (cq17830) // // Revision 1.101 2006/05/18 10:50:35 mmorozov // - new behavour: значение по умолчанию для операции публикуемых компонентом "показывать в контекстном меню" ; // // Revision 1.100 2006/04/19 14:53:12 mmorozov // - bugfix: измененные ExludeUserTypes не являлись основанием для сохранения операции; // // Revision 1.99 2006/03/31 07:41:46 lulin // - изменен тип параметров, подаваемый в Execte операции. // // Revision 1.98 2006/03/30 15:31:16 lulin // - изменен тип параметров в OnTest. // // Revision 1.97 2006/03/30 10:36:26 lulin // - делаем индекс состояния составным типом, чтобы сложнее было пользоваться не константами. // // Revision 1.96 2006/03/15 15:38:30 oman // - new beh: vcm_DefaultOperationState переехала в более правильное место // // Revision 1.95 2006/03/10 08:01:55 mmorozov // - new behaviour: установленность событий у элемента коллекции определяем с помощь RTTI; // // Revision 1.94 2006/03/09 15:30:51 lulin // - new behavior: если к операции привязан контрол, который ее не поддерживает, то запрещаем эту операцию. // // Revision 1.93 2006/03/09 15:29:11 mmorozov // - bugfix: при определенных условиях в dfm не писались обработчики событий; // // Revision 1.92 2006/03/07 13:00:48 mmorozov // - bugfix: при пустых _options операции публикумые компонентами все равно появлялись в меню; // // Revision 1.91 2006/02/15 12:05:28 mmorozov // - bugfix: в некоторых случаях флаг Enabled не обновлялся, в следствии чего не работал Execute операции (CQ: 19614); // // Revision 1.90 2006/02/07 07:59:36 mmorozov // new behaviour: для операций связанных с компонентами можно указывать пустые _Options; // // Revision 1.89 2006/02/02 16:49:27 oman // - fix: при выполнении операции вызываем onTest не только когда // операция запрещена, но и для не Internal-операций - всегда // // Revision 1.88 2006/01/20 11:33:06 mmorozov // 1. Нельзя было на панель инструментов положить неколько операций из разных сущностей с одинаковыми именами; // 2. Если в панели инструментов встречаются операции с одинаковыми названиями, то им автоматически добавляется суффикс в виде названия сущности; // 3. Появилась возможность указать, что контекстные операции сущности должны показываться в отдельном пункте меню; // 3. // // Revision 1.87 2005/09/13 13:18:22 mmorozov // - warning fix; // // Revision 1.86 2005/07/14 16:02:48 lulin // - new behavior: в run-time получаем ID операции по ее имени из информации, содержащейся в MenuManager'е. // // Revision 1.85 2005/02/02 14:09:06 lulin // - bug fix: было перепутано условие. // // Revision 1.84 2005/02/02 13:16:46 am // bugfix: IfNDef -> IfDef в _Handled // // Revision 1.83 2005/02/02 12:53:55 am // change: правки, связанные с переделками TvcmBaseOperationCollectionItem._Handled() // // Revision 1.82 2005/02/01 15:09:40 am // new: function _Handled // // Revision 1.81 2005/02/01 15:04:50 am // new: function _Handled // // Revision 1.80 2005/01/27 15:24:03 am // change: показываем в настройке тулбаров операции, публикуемые самими контролами // // Revision 1.79 2005/01/27 14:01:14 am // change: показываем в настройке тулбаров только те операции, для которых установлен OnExecute. // // Revision 1.78 2005/01/27 13:43:28 lulin // - bug fix: не все контролы отвязывались от операций (CQ OIT5-11924). // // Revision 1.77 2005/01/25 10:25:53 lulin // - bug fix: в настройке не показывались операции, которые по-умолчанию не показываются на Toolbar'ах. // // Revision 1.76 2005/01/21 11:10:05 lulin // - new behavior: не сохраняем операции, привязанные только к контролам. // // Revision 1.75 2005/01/20 13:25:18 lulin // - new consts: _vcm_otModuleInternal, _vcm_otFormConstructor. // // Revision 1.74 2005/01/20 10:55:29 demon // - fix: syntax fix // // Revision 1.73 2005/01/20 10:49:46 demon // - new behavior: свойство у операции LongProcess (Обрамление выполнения операции курсором crHourGlass). // // Revision 1.72 2005/01/19 12:34:15 lulin // - new behavior: для ReadOnly-редакторов не публикуем операции редактирования. // // Revision 1.71 2005/01/14 10:42:30 lulin // - методы Get*ParentForm переехали в библиотеку AFW. // // Revision 1.70 2004/11/25 10:44:11 lulin // - rename type: _TvcmExecuteEvent -> TvcmControlExecuteEvent. // - rename type: _TvcmTestEvent -> TvcmControlTestEvent. // - new type: TvcmControlGetTargetEvent. // // Revision 1.69 2004/11/25 10:14:10 lulin // - bug fix: AV при вызове операции контрола. // // Revision 1.68 2004/11/25 09:58:15 lulin // - new methods: _IvcmParams.SetControlEvent, CallControl. // - new behavior: если определен обработчик на форме, то зовем его - если дано отдать обработку контролу можно вызвать aParams.CallControl. // // Revision 1.67 2004/11/25 09:39:29 lulin // - убран лишний параметр aContext - т.к. он вычисляется из aParams._Target. // // Revision 1.66 2004/11/24 13:47:52 lulin // - new behavior: обработчики операций от контролов теперь вызываются, когда надо выполнить операции. // // Revision 1.65 2004/11/24 12:35:55 lulin // - new behavior: обработчики операций от контролов теперь привязываются к операциям. // // Revision 1.64 2004/11/18 17:57:22 lulin // - new class: TvcmActiveControlsCollection. // // Revision 1.63 2004/11/18 16:29:55 lulin // - отвязываем библиотеки от VCM без использования inc'ов. // // Revision 1.62 2004/10/26 13:11:35 mmorozov // bugfix: в vcm_omExecute с f_Enabled = False перед вызовом OnTest формировались aParams c Container = nil; // // Revision 1.61 2004/10/07 14:17:01 lulin // - new: теперь у _IvcmParams можно присваивать только свойство DoneStatus - код завершения. На основе этого "по-хитрому" обрабатываем ShortCut'ы для запрещенных операций (CQ OIT5-10123). // // Revision 1.60 2004/10/05 11:41:47 lulin // - bug fix: при вызове операции, однажды запрещенной не вызывался OnTest и поэтому она больше не вызывалась, через метод _Operation, а не из контрола (CQ OIT5-9844). // // Revision 1.59 2004/09/27 15:18:06 lulin // - new behavior: для операций с типом vcm_otInternal не даем присваивать _Options. // // Revision 1.58 2004/09/22 15:50:10 lulin // - cleanup. // // Revision 1.57 2004/09/22 13:34:41 mmorozov // change: не вызываем Now в _Operation; // // Revision 1.56 2004/09/22 06:12:34 lulin // - оптимизация - методу TvcmBaseCollection.FindItemByID придана память о последнем найденном элементе. // // Revision 1.55 2004/09/22 05:41:24 lulin // - оптимизация - убраны код и данные, не используемые в Run-Time. // // Revision 1.54 2004/09/21 16:23:31 mmorozov // new: возвращает интерфейс IvcmIdentifiedUserFriendlyControl; // // Revision 1.53 2004/09/13 08:56:10 lulin // - new behavior: TvcmPrimCollectionItem теперь может кешироваться и распределяться в пуле объектов. // // Revision 1.52 2004/09/10 16:47:16 lulin // - оптимизация - удалось избежать повторного пересоздания OpDef. // // Revision 1.51 2004/09/10 16:21:46 lulin // - оптимизация - кешируем OpDef и передаем ссылку на OperationItem, а не на кучу параметров. // // Revision 1.50 2004/09/10 12:47:40 lulin // - new type: TvcmEffectiveUserType. // - new behavior: не возвращаем интерфейсы для операции, если у нее нету имени. // // Revision 1.49 2004/09/07 10:32:12 am // change: оптимизация и багфикс, связанный с _VisibleToUser // // Revision 1.48 2004/09/02 09:19:12 am // change: не дёргаем OnTest если диспетчер залочен // // Revision 1.47 2004/08/31 07:56:43 am // change: перенёс вычисление "видимости" операции с def'а на item // // Revision 1.46 2004/08/11 14:29:58 law // - new behavior: сделан вызов Help'а для пунктов меню. // // Revision 1.45 2004/07/30 13:07:18 law // - cleanup. // // Revision 1.44 2004/07/30 10:00:05 nikitin75 // корректно мержим предустановленные (disigntime) шорткаты и прочитанные из настроек, bugfix // // Revision 1.43 2004/07/30 08:44:04 law // - bug fix: неправильно определалась необходимость сохранения свойства SecondaryShortCuts. // // Revision 1.42 2004/07/29 10:16:08 nikitin75 // SetShortCuts fix // // Revision 1.41 2004/07/22 16:29:36 law // - добавлена функция-helper. // // Revision 1.40 2004/07/20 11:04:26 law // - "откручено" прореживание OnTest. // // Revision 1.39 2004/07/19 11:03:08 law // - сделал "прореживание" дерганий OnTest (CQ OIT5-6989). // // Revision 1.38 2004/06/30 04:45:44 mmorozov // bugfix: AutoFocus; // // Revision 1.37 2004/06/29 13:14:21 mmorozov // bugfix: переключение форм при AutoFocus; // // Revision 1.36 2004/04/19 15:50:21 mmorozov // change: TvcmBaseOperationsCollectionItem._pm_GetParams ADD "const aObject : TObject"; // // Revision 1.35 2004/04/15 15:10:13 am // new prop: AutoFocus. если установлено - перед выполнением операции отдаём фокус контролу, который связан с сущностью, или форме, на которой эта сущность лежит. // // Revision 1.34 2004/03/16 10:59:34 law // - new const: _vcm_omAggregateExecute. // - new behavior: для операции агрегации не учитываем состояние Enabled. // // Revision 1.33 2004/03/13 14:09:48 law // - bug fix: не выполняем операцию, если в OnTest нам сказали, что она недоступна (CQ OIT5-6232). // // Revision 1.32 2004/03/11 15:16:08 nikitin75 // fix: SecondaryShortCuts терялись в designtime; // // Revision 1.31 2004/03/11 14:49:29 nikitin75 // + OnSecondaryShortCutsChange; // // Revision 1.30 2004/03/11 12:30:44 nikitin75 // + передаем SecondaryShortCuts в TvcmBaseOperationDef.Make; // // Revision 1.29 2004/03/11 11:42:32 nikitin75 // + function SecondaryShortCutsStored: Boolean; // // Revision 1.28 2004/03/11 10:49:34 nikitin75 // fix: не присваивались SecondaryShortCuts в disign-time; // // Revision 1.27 2004/03/09 11:37:03 nikitin75 // + поддержка нескольких shortcut'ов для операции; // // Revision 1.26 2004/03/09 07:17:57 nikitin75 // + поддержка нескольких shortcut'ов для операции; // // Revision 1.25 2004/03/02 09:23:30 nikitin75 // + try..except; // // Revision 1.24 2004/03/01 11:42:47 nikitin75 // + published _vcmByteShift(aShift: TShiftState): Byte; // // Revision 1.23 2004/02/27 19:22:16 law // - bug fix: поправлена обработка ShortCut'ов для операций модулей. // - bug fix: поправдена ДВОЙНАЯ обработка ShortCut'ов в случае редактора. // // Revision 1.22 2004/02/27 15:55:01 nikitin75 // + OvcController для поддержки shortcuts; // // Revision 1.21 2004/02/02 15:02:42 law // - remove proc: vcmMakeBaseOperationDef. // - new method: TvcmBaseOperationDef.Make. // // Revision 1.20 2004/01/14 18:38:10 law // - bug fix. // // Revision 1.19 2004/01/14 17:25:07 law // - new behavior: мапируем свойство _States на операцию, живущую в StdRes. // // Revision 1.18 2004/01/14 16:34:38 law // - new methods: TvcmBaseOperationsCollectionItem.pm_GetStates, StatesStored. // // Revision 1.17 2004/01/14 16:24:32 law // - new method: TvcmBaseOperationsCollectionItem.StatesClass. // // Revision 1.16 2004/01/14 16:18:17 law // - new units: vcmBaseOperationState, vcmBaseOperationStates. // // Revision 1.15 2004/01/14 15:07:04 law // - перенес тип в vcmInterfaces. // // Revision 1.14 2004/01/14 14:45:45 law // - new prop: TvcmOperationState.Checked. // // Revision 1.13 2004/01/14 13:58:03 law // - new units: vcmOperationState, vcmOperationStates. // // Revision 1.12 2004/01/14 13:07:52 law // - new units: vcmOperationState, vcmOperationStates. // // Revision 1.11 2004/01/14 12:58:47 law // - new units: vcmOperationParams. // // Revision 1.10 2004/01/14 12:40:39 law // - new class: _TvcmOperationParams. // // Revision 1.9 2003/11/28 18:08:35 law // - change: подточил, для тоо, чтобы из ComboTree можно было возвращать выбранную ноду. // // Revision 1.8 2003/11/25 09:02:14 law // - new behavior: если операция привязана к форме UserType которой входит в _ExcludeUserTypes операции, то обработчики On*Execute вообще не вызываются. // // Revision 1.7 2003/11/25 08:45:33 law // - new method: TvcmBaseOperationsCollectionItem.OwnerUserType. // // Revision 1.6 2003/11/24 11:56:35 law // - bug fix: Hint'ы тоже теперь берутся из централизованного хранилища. // // Revision 1.5 2003/11/19 18:38:39 law // - new prop: TvcmBaseOperationsCollectionItem.Params - описывает список параметров операции. // - new prop: TvcmOperationsCollectionItem.Linked - показывает связана операция с централизованным хранилищем или нет. // // Revision 1.4 2003/11/19 15:41:24 law // - change: свойство _ExcludeUserTypes перенес на TvcmOperationsCollectionItem. // // Revision 1.3 2003/11/19 13:21:07 law // - new behavior: отобразил свойство ShortCut операций на формах на централизованное хранилище. // // Revision 1.2 2003/11/19 12:56:52 law // - new behavior: отобразил свойства операций на формах на централизованное хранилище (_Caption, _ImageIndex, _GroupID, _Category, OperationType). // // Revision 1.1 2003/11/19 11:38:25 law // - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано. // {$Include vcmDefine.inc } interface uses Classes, ActnList, vcmUserControls, vcmInterfaces, vcmExternalInterfaces, vcmBase, vcmOperationParams, vcmBaseOperationState, vcmBaseOperationStates, vcmForm, vcmAction, vcmActiveControlsCollection {$IfDef XE} , System.Actions {$EndIf XE} ; const vcm_DefaultOperationOptions = [vcm_ooShowInMainToolbar, vcm_ooShowInChildToolbar, vcm_ooShowInContextMenu, vcm_ooShowInMainMenu, vcm_ooShowInChildMenu]; { Набор параметров по умолчанию для свойсва TvcmOperationsCollectionItem.Options. } type TvcmGetStateEvent = procedure(var State: TvcmOperationStateIndex) of object; {-} TvcmContextTestEvent = TvcmTestEvent; { Вызывается в момент проверки доступности операции из контекстного меню. } TvcmContextExecuteEvent = TvcmExecuteEvent; { Вызывается при выполнении операции из контекстного меню. } TvcmHandleType = (vcm_htContext, vcm_htGlobal, vcm_htControl); TvcmHandleTypes = set of TvcmHandleType; TvcmBaseOperationsCollectionItem = class(TvcmOperationParams) {* Элемент коллекции операций. } protected // property fields f_OperationType : TvcmOperationType; f_Options : TvcmOperationOptions; f_ContextMenuWeight : Integer; private // property fields f_OperationID : Integer; f_AutoLock : Boolean; f_AutoFocus : Boolean; f_LongProcess : Boolean; f_GroupID : Integer; f_States : TvcmBaseOperationStates; f_State : TvcmOperationStateIndex; f_Enabled : Boolean; f_VisibleToUser : Integer; f_OpDef : IvcmOperationDef; f_Controls : TvcmActiveControlsCollection; f_OnGetState : TvcmGetStateEvent; f_OnTest : TvcmTestEvent; f_OnExecute : TvcmExecuteEvent; f_FormGetState : TvcmControlGetStateEvent; f_FormTest : TvcmControlTestEvent; f_FormExecute : TvcmControlExecuteEvent; f_OnContextTest : TvcmContextTestEvent; f_OnContextExecute : TvcmContextExecuteEvent; f_IsCaptionUnique : Boolean; f_SaveShortcut: TShortcut; f_SaveSecondaryShortcuts: AnsiString; f_IsDefault: Boolean; protected // property methods function pm_GetVisibleToUser: Boolean; {-} procedure pm_SetOptions(aValue: TvcmOperationOptions); {-} function pm_GetOptions: TvcmOperationOptions; virtual; {-} function GetDefaultOptions: TvcmOperationOptions; virtual; {-} function pm_GetOperationDef: IvcmOperationDef; {-} {$IfNDef DesignTimeLibrary} function pm_GetCategory: AnsiString; virtual; {-} {$EndIf DesignTimeLibrary} function pm_GetGroupID: Integer; virtual; procedure pm_SetGroupID(aValue: Integer); virtual; function GroupIDStored: Boolean; virtual; {-} function pm_GetOperationType: TvcmOperationType; virtual; procedure pm_SetOperationType(aValue: TvcmOperationType); virtual; function OperationTypeStored: Boolean; virtual; {-} function pm_GetExcludeUserTypes: TvcmEffectiveUserTypes; virtual; procedure pm_SetExcludeUserTypes(aValue: TvcmEffectiveUserTypes); virtual; {-} function pm_GetStates: TvcmBaseOperationStates; virtual; procedure pm_SetStates(aValue: TvcmBaseOperationStates); {-} procedure pm_SetState(const aValue: TvcmOperationStateIndex); {-} function pm_GetCurrentState: TvcmBaseOperationState; {-} function pm_GetIsDefault: Boolean; virtual; {-} procedure pm_SetIsDefault(const aValue: Boolean); virtual; {-} function IsDefaultStored: Boolean; virtual; {-} procedure OnSecondaryShortCutsChange(Sender: TObject); {-} class procedure ResetShortCutHandler(var aValue: TShortCut; aCommandID: Word = 0); {-} function IsLinkedToModule: Boolean; {-} function ParentID: Integer; {-} function ControllerCommand: Word; {-идентификатор комманды-shortcut} function GetLinkedAction: TvcmAction; {* - Action к которому привязана операция. } function pm_GetLinked: Boolean; virtual; procedure pm_SetLinked(aValue: Boolean); virtual; {-} function IsHandledToControl: Boolean; {* - операция опубликована компонентом. } function pm_GetContextMenuWeight: Integer; procedure pm_SetContextMenuWeight(aValue : Integer); {-} protected // internal methods procedure DoFormGetState(var State: TvcmOperationStateIndex); procedure DoFormTest(const aParams: IvcmTestParamsPrim); procedure DoFormExecute(const aParams: IvcmExecuteParams); {-} procedure FakeControlTest(const aParams: IvcmTestParamsPrim); {-} procedure ChangeName(const anOld, aNew: AnsiString); override; { Вызывается при изменении имени. } procedure ChangeCaption(const anOld, aNew: AnsiString); override; { Вызывается при изменении заголовка. } function OwnerUserType: TvcmEffectiveUserType; { Возвращает пользовательский тип "формы" на которой определена операция. } procedure Cleanup; override; {-} procedure BeforeAddToCache; override; {-} class function StatesClass: RvcmBaseOperationStates; virtual; {-} procedure SetShortCuts(aShortCut: TShortCut; aSecondaryShortCuts: TShortCutList); virtual; {-} procedure ClearOp; {-} public // public methods constructor Create(Collection: TCollection); override; {-} function OwnerForm: TvcmForm; { Возвращает "форму" на которой определена операция. } procedure ReplaceShortCuts(aShortCut: TShortCut; aSecondaryShortCuts: {$IfDef XE}TCustomShortCutList{$Else}TShortCutList{$EndIf}); {-} procedure StoreDesignTimeShortcuts; {-} function MakeID(const aName: AnsiString): Integer; override; {-} function GetID: Integer; override; {-} function SomePropStored: Boolean; {-} procedure Operation(aControl : TComponent; const aTarget : IUnknown; aMode : TvcmOperationMode; const aParams : IvcmParams; aForce : Boolean); { Выполнение операции. } function QueryInterface(const IID: TGUID; out Obj): HResult; override; {-} procedure Assign(P: TPersistent); override; {-} procedure RemoveShortCut(aShortCut: TShortCut); virtual; {-} procedure PublishOp(const aControl : TComponent; anExecute : TvcmControlExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); overload; {* - опубликовать операцию. } procedure PublishOp(const aControl : TComponent; anExecute : TvcmExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); overload; {* - опубликовать операцию. } procedure UnlinkControl(aControl : TComponent); {* - отвязать контрол. } function Handled(aTypes: TvcmHandleTypes): Boolean; virtual; {-} public // public properties property OperationID: Integer read f_OperationID; { Идентификатор операции. } property OperationDef: IvcmOperationDef read pm_GetOperationDef; {* - описатель операции. } property ExcludeUserTypes: TvcmEffectiveUserTypes read pm_GetExcludeUserTypes write pm_SetExcludeUserTypes default []; {-} property State: TvcmOperationStateIndex read f_State write pm_SetState; {-} property CurrentState: TvcmBaseOperationState read pm_GetCurrentState; {-} property VisibleToUser: Boolean read pm_GetVisibleToUser; {-} property Linked: Boolean read pm_GetLinked write pm_SetLinked stored false; {-} property Controls: TvcmActiveControlsCollection read f_Controls; {-} property IsCaptionUnique: Boolean read f_IsCaptionUnique write f_IsCaptionUnique; {-} property SaveShortcut: TShortcut read f_SaveShortcut; {-} property SaveSecondaryShortcuts: AnsiString read f_SaveSecondaryShortcuts; {-} property States: TvcmBaseOperationStates read pm_GetStates write pm_SetStates; {-} property OperationType: TvcmOperationType read pm_GetOperationType write pm_SetOperationType stored OperationTypeStored default vcm_otButton; { Тип операции. Description В зависимости от типа операции меняется отображение операции в меню и на панели инструментов. See Also TvcmOperationType } property GroupID: Integer read pm_GetGroupID write pm_SetGroupID stored GroupIDStored default 0; {-} property IsDefault: Boolean read pm_GetIsDefault write pm_SetIsDefault stored IsDefaultStored default False; property Options: TvcmOperationOptions read pm_GetOptions write pm_SetOptions; { Настройки операции. See Also <LINK vcm_DefaultOperationOptions> } property OnGetState: TvcmGetStateEvent read f_OnGetState write f_OnGetState; {-} {$IfNDef DesignTimeLibrary} property Category: AnsiString read pm_GetCategory; { Категория операции. Note Задается на стадии проектирования формы. Используется для группировки операций. } {$EndIf DesignTimeLibrary} property ContextMenuWeight: Integer read pm_GetContextMenuWeight write pm_SetContextMenuWeight; published // published properties property AutoLock: Boolean read f_AutoLock write f_AutoLock default false; { Управление перерисовской приложения во время выполнения операции. Description Если AutoLock = True, с начала и до окончания выполения операции запрещается всякая перерисовка приложения. } property AutoFocus: Boolean read f_AutoFocus write f_AutoFocus default false; { Установка фокуса до выполнения операции. Description Если AutoFocus = True, перед выполнением операции, фокус передаётся форме или контролу, с которым связана эта операция } property LongProcess: Boolean read f_LongProcess write f_LongProcess default false; { Обрамление выполнения операции курсором crHourGlass. Нужно только для длительных внутренних (vcm_otInternal) операций, т.к. все вызовы через Action и так обрамлены подобным образом. Description Если LongProcess = True, перед выполнением операции курсор заменяется на crHourGlass, а после выполнения возвращается к первоначальному виду } published // published events property OnTest: TvcmTestEvent read f_OnTest write f_OnTest; { Description Вызывается для перерисовки состояния операции. Данный обработчик вызывается для определения доступности операции. В массиве aParams можно вернуть изменившее состояние. <TABLE noborder> Индекс параметра Тип Значение ----------------- --------- -------------------------------- vcm_opEnabled Boolean Доступность выполнения операции vcm_opVisible Boolean Видимость операции в меню и на панели инструментов vcm_opChecked Boolean Операция помечена vcm_opLongHint AnsiString Текст подсказки, отображаемой в статусной строке vcm_opCaption AnsiString Заголовок пункта меню </TABLE> Note Для типа операции vcm_otCombo в aParams.Op.SubItems нужно вернуть список строк, представляющий список элементов выпадающего списка. Summary Проверка разрешенности операции. } property OnExecute: TvcmExecuteEvent read f_OnExecute write f_OnExecute; { Обработчик операции. Вызывается из меню главной формы или панели инструментов. } property OnContextTest: TvcmContextTestEvent read f_OnContextTest write f_OnContextTest; { Description Вызывается из контекстного меню. Данный обработчик вызывается для определения доступности операции. В массиве aParams можно вернуть изменившее состояние. <TABLE noborder> Индекс параметра Тип Значение ----------------- --------- -------------------------------- vcm_opEnabled Boolean Доступность выполнения операции vcm_opVisible Boolean Видимость операции в меню и на панели инструментов vcm_opChecked Boolean Операция помечена vcm_opLongHint AnsiString Текст подсказки, отображаемой в статусной строке vcm_opCaption AnsiString Заголовок пункта меню </TABLE> Note Для типа операции vcm_otCombo в aParams.Op.SubItems нужно вернуть список строк, представляющий список элементов выпадающего списка. Summary Проверка разрешенности контекстной операции. } property OnContextExecute: TvcmContextExecuteEvent read f_OnContextExecute write f_OnContextExecute; { Description Обработчик операции. Вызывается из контекстного меню. } end;{ Описатель операции } function vcmByteShift(aShift: TShiftState): Byte; implementation uses TypInfo, SysUtils, DateUtils, Forms, Menus, Controls, OvcBase, OvcCmd, OvcData, {$IfDef vcmNeedL3} l3Types, {$EndIf vcmNeedL3} afwFacade, vcmBaseOperationDef, vcmModuleDef, vcmRepositoryEx, vcmBaseEntitiesCollection, vcmBaseEntitiesCollectionItem, vcmEntitiesCollectionItem, vcmEntities, vcmModule, vcmContainerForm, vcmModulesCollectionItem, vcmEntityAction, vcmModuleAction, vcmActiveControlsCollectionItem, vcmBaseCollection, vcmUtils, vcmInternalConst, vcmOVCCommands, vcmEntityForm, vcmBaseMenuManager ; function vcmByteShift(aShift: TShiftState): Byte; begin result := OvcByteShift(aShift); end; // start class TvcmBaseOperationsCollectionItem constructor TvcmBaseOperationsCollectionItem.Create(Collection: TCollection); //override; {-} begin inherited; //f_Controls := TvcmActiveControlsCollection.Create(Self); f_State := vcm_DefaultOperationState; f_States := StatesClass.Create(Self); f_Enabled := true; f_VisibleToUser := -1; f_IsCaptionUnique := True; SecondaryShortCuts.OnChange := OnSecondaryShortCutsChange; f_SaveShortcut := TShortcut(0); f_SaveSecondaryShortcuts := ''; f_ContextMenuWeight := 0; end; class function TvcmBaseOperationsCollectionItem.StatesClass: RvcmBaseOperationStates; //virtual; {-} begin Result := TvcmBaseOperationStates; end; procedure TvcmBaseOperationsCollectionItem.SetShortCuts(aShortCut: TShortCut; aSecondaryShortCuts: TShortCutList); //virtual; {-} begin end; procedure TvcmBaseOperationsCollectionItem.Cleanup; //override; {-} begin f_FormGetState := nil; f_FormTest := nil; f_FormExecute := nil; FreeAndNil(f_Controls); ClearOp; SetShortCuts(TShortcut(0), nil); f_SaveShortcut := TShortcut(0); f_SaveSecondaryShortcuts := ''; FreeAndNil(f_States); inherited; end; procedure TvcmBaseOperationsCollectionItem.BeforeAddToCache; //override; {-} begin inherited; f_Options := []; f_OperationType := Low(TvcmOperationType); f_AutoLock := false; f_AutoFocus := false; f_LongProcess := false; f_OnGetState := nil; f_OnTest := nil; f_OnExecute := nil; f_OnContextTest := nil; f_OnContextExecute := nil; f_IsDefault := False; end; procedure TvcmBaseOperationsCollectionItem.ClearOp; {-} var l_Op : IvcmOpHolder; begin if Supports(f_OpDef, IvcmOpHolder, l_Op) then try l_Op.ClearOp; finally l_Op := nil; end;//try..finally f_OpDef := nil; end; function TvcmBaseOperationsCollectionItem.OwnerForm: TvcmForm; {-} var l_Col : TCollection; l_Ow : TPersistent; l_Form : TCustomForm; begin Result := nil; l_Col := Collection; if (l_Col <> nil) then begin l_Ow := l_Col.Owner; if (l_Ow Is TvcmEntitiesCollectionItem) then begin l_Col := TvcmEntitiesCollectionItem(l_Ow).Collection; if (l_Col <> nil) then begin l_Ow := l_Col.Owner; if (l_Ow <> nil) then begin l_Form := afw.GetParentForm(l_Ow); if (l_Form is TvcmEntityForm) then Result := TvcmEntityForm(l_Form); end; end;//l_Col <> nil end;//l_Ow Is vcmEntitiesCollectionItem end;//l_Col <> nil end; function TvcmBaseOperationsCollectionItem.OwnerUserType: TvcmEffectiveUserType; { Возвращает пользовательский тип "формы" на которой определена операция. } Var l_Form: TvcmEntityForm; begin Result := 0; l_Form := TvcmEntityForm(OwnerForm); if l_Form <> nil then Result := l_Form.UserType; end; function TvcmBaseOperationsCollectionItem.GetID: Integer; //override; {-} begin Result := OperationID; end; procedure TvcmBaseOperationsCollectionItem.Operation(aControl : TComponent; const aTarget : IUnknown; aMode : TvcmOperationMode; const aParams : IvcmParams; aForce : Boolean); {* - выполняет операцию сущности. } var l_FD : IvcmFormDispatcher; l_AL : Boolean; l_State : TvcmOperationStateIndex; l_CurState : TvcmBaseOperationState; l_Form : TvcmEntityForm; l_ParentForm : TCustomForm; {$IfDef vcmNeedL3} l_Test : TvcmTestEvent; l_TestM : Tl3Method absolute l_Test; {$EndIf vcmNeedL3} l_Action : TvcmAction; l_ActionParams : IvcmTestParams; l_Control : TvcmActiveControlsCollectionItem; l_Cursor : TCursor; l_IsOpExcluded : Boolean; l_Part : IvcmExecuteParams; l_TPart : IvcmTestParams; l_Enabled : Boolean; begin Assert(Ord(AMode) <= Ord(High(TvcmOperationMode))); l_FD := vcmDispatcher.FormDispatcher; l_AL := AutoLock AND (l_FD <> nil) AND (aMode in vcm_omExecutes); if l_AL then l_FD.Lock; try aParams.Target := aTarget; aParams.Control := aControl; if (Controls = nil) then l_Control := nil else l_Control := Controls.FindItemByControl(aControl) As TvcmActiveControlsCollectionItem; Case aMode of vcm_omTest : begin l_TPart := aParams.TestPart; if (l_Control = nil) then l_TPart.SetControlEvent(nil) else if Assigned(l_Control.OnTest) then l_TPart.SetControlEvent(l_Control.OnTest) else l_TPart.SetControlEvent(FakeControlTest); aParams.DoneStatus := vcm_dsDone; if not aForce AND l_FD.Locked then Exit; if Assigned(f_OnGetState) then begin l_State := State; f_OnGetState(l_State); State := l_State; end;//Assigned(f_OnGetState) l_CurState := CurrentState; l_IsOpExcluded := (ExcludeUserTypes <> []) AND (OwnerUserType in ExcludeUserTypes); if l_IsOpExcluded then begin l_TPart.Op.Flag[vcm_ofEnabled] := false; aParams.DoneStatus := vcm_dsExcludedInUserType; end//l_IsOpExcluded else begin if (l_CurState = nil) then l_TPart.Op.Flag[vcm_ofEnabled] := true else l_TPart.Op.Flag[vcm_ofEnabled] := l_CurState.Enabled; end;//ExcludeUserTypes <> [] if (OperationType in vcm_HiddenOperations) then l_TPart.Op.Flag[vcm_ofVisible] := false else if (l_CurState <> nil) then l_TPart.Op.Flag[vcm_ofVisible] := l_CurState.Visible; if (l_CurState = nil) then begin l_TPart.Op.Hint := vcmCStr(Hint); l_TPart.Op.LongHint := vcmCStr(LongHint); l_TPart.Op.ShortCut := Integer(ShortCut); l_TPart.Op.ImageIndex := Integer(ImageIndex); end//l_CurState = nil else begin l_TPart.Op.Caption := vcmCStr(l_CurState.Caption); l_TPart.Op.Flag[vcm_ofChecked] := l_CurState.Checked; l_TPart.Op.Hint := vcmCStr(l_CurState.Hint); l_TPart.Op.LongHint := vcmCStr(l_CurState.LongHint); if (l_CurState.ShortCut = 0) then l_TPart.Op.ShortCut := Integer(ShortCut) else l_TPart.Op.ShortCut := Integer(l_CurState.ShortCut); l_TPart.Op.ImageIndex := Integer(l_CurState.ImageIndex); end;//l_CurState = nil if (aTarget <> nil) and Assigned(f_OnContextTest) then f_OnContextTest(l_TPart) else//(aTarget <> nil) and Assigned(f_OnContextTest) if Assigned(f_OnTest) and not l_IsOpExcluded then begin {$IfDef vcmNeedL3} l_Test := f_OnTest; if not (TObject(l_TestM.Data) Is TComponent) OR not (csDestroying in TComponent(l_TestM.Data).ComponentState) then {$EndIf vcmNeedL3} begin f_OnTest(l_TPart); end;//not (TObject(l_TestM.Data) Is TComponent).. end//Assigned(f_OnTest) else begin // Если на форме нет обработчиков пытаемся отдать контролу l_Enabled := l_TPart.Op.Flag[vcm_ofEnabled]; if not l_TPart.CallControl then begin // Если контрол не проверился и нет обработчиков - запрещаем операцию вообще. if not ((Assigned(l_Control) and Assigned(l_Control.OnExecute)) OR Assigned(f_OnExecute) OR Assigned(f_OnContextExecute)) then l_TPart.Op.Flag[vcm_ofEnabled] := false else l_TPart.Op.Flag[vcm_ofEnabled] := l_Enabled; end;//not l_TPart.CallControl end;//Assigned(f_OnTest) and not l_IsOpExcluded f_Enabled := l_TPart.Op.Flag[vcm_ofEnabled]; //aParams.DoneStatus := vcm_dsDone; end;//vcm_omTest vcm_omExecute, vcm_omAggregateExecute: begin l_Part := aParams.ExecutePart; if (l_Control = nil) then l_Part.SetControlEvent(nil) else l_Part.SetControlEvent(l_Control.OnExecute); if ((not f_Enabled or not (OperationType in vcm_HiddenOperations)) OR ((aMode = vcm_omAggregateExecute) AND (OperationType = vcm_otInternal))) // - чтобы из обработчика операций агрегации можно было запрещать операцию // Может что-то отвалиться: // http://mdp.garant.ru/pages/viewpage.action?pageId=178324372&focusedCommentId=178324544#comment-178324544 AND (((l_Control <> nil) AND Assigned(l_Control.OnTest)) OR (Assigned(f_OnTest) OR Assigned(f_OnContextTest))) then begin // - надо вызвать OnTest l_Action := GetLinkedAction; if (l_Action <> nil) then begin l_ActionParams := l_Action.MakeTestParams; // в параметрах определим контейнер if not Assigned(l_ActionParams.Container) then begin l_Form := TvcmEntityForm(OwnerForm); // для операций модуля OwnerForm = nil, поэтому берем текущую главную if not Assigned(l_Form) and Assigned(Dispatcher.FormDispatcher.CurrentMainForm) then l_Form := (Dispatcher.FormDispatcher.CurrentMainForm.VCLWinControl As TvcmEntityForm); if Assigned(l_Form) then begin if (l_Form is TvcmContainerForm) then l_ActionParams.BasePart.SetContainerPrim(TvcmContainerForm(l_Form), true) else l_ActionParams.BasePart.SetContainerPrim(l_Form.Container, true); end;//not Assigned(l_Form) end;//not Assigned(l_ActionParams.Container) // вызываем OnTest Operation(aControl, aTarget, vcm_omTest, l_ActionParams.BasePart, True); end;//l_Action <> nil end;//not f_Enabled AND (OperationType in vcm_HiddenOperations) if not f_Enabled AND ((aMode = vcm_omExecute) OR (OperationType = vcm_otInternal)) // - чтобы таки не звать запрещённую внутренюю операцию агрегации // Может что-то отвалиться: // http://mdp.garant.ru/pages/viewpage.action?pageId=178324372&focusedCommentId=178324544#comment-178324544 then begin if ((ExcludeUserTypes <> []) AND (OwnerUserType in ExcludeUserTypes)) then aParams.DoneStatus := vcm_dsExcludedInUserType else aParams.DoneStatus := vcm_dsDisabled; end//not f_Enabled else if ((ExcludeUserTypes <> []) AND (OwnerUserType in ExcludeUserTypes)) then aParams.DoneStatus := vcm_dsExcludedInUserType else begin aParams.DoneStatus := vcm_dsDone; l_Cursor := Screen.Cursor; if f_LongProcess then Screen.Cursor := crHourGlass; try if (aTarget <> nil) and Assigned(f_OnContextExecute) then f_OnContextExecute(l_Part) else //(aTarget <> nil) and Assigned(f_OnContextExecute) if ((l_Control <> nil) AND Assigned(l_Control.OnExecute)) OR Assigned(f_OnExecute) then begin if (aMode = vcm_omExecute) and f_AutoFocus then begin if (aControl <> nil) then begin l_ParentForm := afw.GetTopParentForm(aControl); if Assigned(l_ParentForm) and l_ParentForm.Active and (aControl is TWinControl) then (aControl as TWinControl).SetFocus end else begin l_Form := TvcmEntityForm(OwnerForm); if l_Form <> nil then l_Form.SetFocus; end; end;//aMode = vcm_omExecute) and f_AutoFocus if Assigned(f_OnExecute) then f_OnExecute(l_Part) else l_Part.CallControl; end;//Assigned(f_OnExecute) finally if f_LongProcess then Screen.Cursor := l_Cursor; end;//try..finally end;//ExcludeUserTypes <> [].. end;//vcm_omExecute end;//Case aMode finally if l_AL then l_FD.Unlock; end;//try..finally end; function TvcmBaseOperationsCollectionItem.QueryInterface(const IID: TGUID; out Obj): HResult; //override; {-} begin if IsEqualGUID(IID, IvcmUserFriendlyControl) then begin Result := S_Ok; IvcmUserFriendlyControl(Obj) := OperationDef; if (IUnknown(Obj) = nil) then Result := E_NoInterface; end else if IsEqualGUID(IID, IvcmOperationDef) then begin Result := S_Ok; IvcmOperationDef(Obj) := OperationDef; if (IUnknown(Obj) = nil) then Result := E_NoInterface; end else if IsEqualGUID(IID, IvcmIdentifiedUserFriendlyControl) then begin Result := S_Ok; IvcmIdentifiedUserFriendlyControl(Obj) := OperationDef; if (IUnknown(Obj) = nil) then Result := E_NoInterface; end else Result := inherited QueryInterface(IID, Obj); end; procedure TvcmBaseOperationsCollectionItem.Assign(P: TPersistent); //override; {-} begin inherited; if (P Is TvcmBaseOperationsCollectionItem) then begin GroupID := TvcmBaseOperationsCollectionItem(P).GroupID; OperationType := TvcmBaseOperationsCollectionItem(P).OperationType; AutoLock := TvcmBaseOperationsCollectionItem(P).AutoLock; ExcludeUserTypes := TvcmBaseOperationsCollectionItem(P).ExcludeUserTypes; OnTest := TvcmBaseOperationsCollectionItem(P).OnTest; OnExecute := TvcmBaseOperationsCollectionItem(P).OnExecute; OnContextTest := TvcmBaseOperationsCollectionItem(P).OnContextTest; OnContextExecute := TvcmBaseOperationsCollectionItem(P).OnContextExecute; Options := TvcmBaseOperationsCollectionItem(P).Options; IsDefault := TvcmBaseOperationsCollectionItem(P).IsDefault; end;//TvcmBaseOperationsCollectionItem end; procedure TvcmBaseOperationsCollectionItem.RemoveShortCut(aShortCut: TShortCut); //virtual; {-} begin Assert(false); end; procedure TvcmBaseOperationsCollectionItem.DoFormGetState(var State: TvcmOperationStateIndex); begin f_FormGetState(State); end; procedure TvcmBaseOperationsCollectionItem.DoFormTest(const aParams: IvcmTestParamsPrim); {-} begin f_FormTest(aParams); end; procedure TvcmBaseOperationsCollectionItem.DoFormExecute(const aParams: IvcmExecuteParams); {-} begin Assert(Assigned(f_FormExecute)); f_FormExecute(aParams); end; procedure TvcmBaseOperationsCollectionItem.FakeControlTest(const aParams: IvcmTestParamsPrim); {-} begin end; procedure TvcmBaseOperationsCollectionItem.PublishOp(const aControl : TComponent; anExecute : TvcmControlExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); {* - опубликовать операцию. } begin if (aControl Is TvcmEntityForm) OR (aControl Is TvcmModule) then begin if not Assigned(f_OnTest) AND not Assigned(f_OnExecute) then begin //Assert(not Assigned(f_OnContextTest)); //Assert(not Assigned(f_OnContextExecute)); f_FormTest := aTest; f_FormExecute := anExecute; f_FormGetState := aGetState; if Assigned(f_FormTest) then begin f_OnTest := DoFormTest; //f_OnContextTest := DoFormTest; end;//Assigned(f_FormTest) if Assigned(f_FormExecute) then begin f_OnExecute := DoFormExecute; //f_OnContextExecute := DoFormExecute; end;//Assigned(f_FormExecute) if Assigned(f_FormGetState) then f_OnGetState := DoFormGetState; // - это заготовка для модели end;//not Assigned(f_OnTest) end//aControl Is TvcmEntityForm else begin if (aControl <> nil) then begin if (f_Controls = nil) then f_Controls := TvcmActiveControlsCollection.Create(Self); f_Controls.PublishOp(aControl, anExecute, aTest); end;//aControl <> nil end;//aControl Is TvcmEntityForm end; procedure TvcmBaseOperationsCollectionItem.PublishOp(const aControl : TComponent; anExecute : TvcmExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); //overload; {* - опубликовать операцию. } begin if (aControl Is TvcmEntityForm) then begin if not Assigned(f_OnTest) AND not Assigned(f_OnExecute) then begin Assert(not Assigned(f_OnContextTest)); Assert(not Assigned(f_OnContextExecute)); f_FormTest := aTest; //f_FormExecute := anExecute; f_FormGetState := aGetState; if Assigned(f_FormTest) then begin f_OnTest := DoFormTest; //f_OnContextTest := DoFormTest; end;//Assigned(f_FormTest) (* if Assigned(f_FormExecute) then begin*) f_OnExecute := anExecute; //f_OnContextExecute := DoFormExecute; (* end;//Assigned(f_FormExecute)*) if Assigned(f_FormGetState) then f_OnGetState := DoFormGetState; // - это заготовка для модели end;//not Assigned(f_OnTest) end//aControl Is TvcmEntityForm else begin Assert(false); (* if (f_Controls = nil) then f_Controls := TvcmActiveControlsCollection.Create(Self); f_Controls.PublishOp(aControl, anExecute, aTest);*) end;//aControl Is TvcmEntityForm end; procedure TvcmBaseOperationsCollectionItem.UnlinkControl(aControl : TComponent); {* - отвязать контрол. } begin if (f_Controls <> nil) then f_Controls.UnlinkControl(aControl); end; function TvcmBaseOperationsCollectionItem.MakeID(const aName: AnsiString): Integer; //override; {-} begin Result := vcmGetID(vcm_repOperation, aName, ParentID); end; procedure TvcmBaseOperationsCollectionItem.ChangeName(const anOld, aNew: AnsiString); //override; {* - вызывается при изменении имени. } begin inherited; f_OperationID := MakeID(aNew); end; function TvcmBaseOperationsCollectionItem.pm_GetOptions: TvcmOperationOptions; {-} begin if (f_Options = []) then begin Result := GetDefaultOptions; {$IfNDef DesignTimeLibrary} f_Options := Result; {$EndIf DesignTimeLibrary} end//f_Options = [] else Result := f_Options; end; procedure TvcmBaseOperationsCollectionItem.pm_SetOptions(aValue: TvcmOperationOptions); begin if (Options <> aValue) then begin if (OperationType in vcm_HiddenOperations) then if (aValue <> []) then Exit; f_Options := aValue; end;//Options <> aValue end; function TvcmBaseOperationsCollectionItem.SomePropStored: Boolean; {-} begin Result := OperationTypeStored OR GroupIDStored OR IsDefaultStored or vcmHasSetEvent(Self){ OR (ExcludeUserTypes <> [])}; end; function TvcmBaseOperationsCollectionItem.GetDefaultOptions: TvcmOperationOptions; {-} var l_Owner : TObject; begin if (OperationType in vcm_HiddenOperations) then Result := [] else if IsLinkedToModule then Result := [] else if Handled([vcm_htGlobal, vcm_htControl]) then begin Result := vcm_DefaultOperationOptions; if (Collection <> nil) then begin l_Owner := Collection.Owner; if (l_Owner Is TvcmEntitiesCollectionItem) then begin // - это операция сущности if (TvcmEntitiesCollectionItem(l_Owner).Controls <> nil) AND not TvcmEntitiesCollectionItem(l_Owner).Controls.LinkedToForm then begin // - сущность привязана к контролу, а не к форме целиком Exclude(Result, vcm_ooShowInMainToolbar); Exclude(Result, vcm_ooShowInMainMenu); end;//not TvcmEntitiesCollectionItem(l_Owner).Controls.LinkedToForm end;//l_Owner Is TvcmEntitiesCollectionItem end;//Collection <> nil if IsHandledToControl then begin Exclude(Result, vcm_ooShowInChildToolbar); Exclude(Result, vcm_ooShowInChildMenu); end;//HandledOnlyByControl end//Assigned(f_OnExecute) else if Handled([vcm_htContext]) then Result := [vcm_ooShowInContextMenu] else Result := []; end; function TvcmBaseOperationsCollectionItem.pm_GetOperationDef: IvcmOperationDef; {-} begin if (Name = '') then // - имени нету - значит об операции ничего вразумительного пока сказать нечего Result := nil else begin if (f_OpDef = nil) then f_OpDef := TvcmBaseOperationDef.Make(Self); Result := f_OpDef; end;//Name = '' end; {$IfNDef DesignTimeLibrary} function TvcmBaseOperationsCollectionItem.pm_GetCategory: AnsiString; {-} var l_Collection : TCollection; l_Owner : TPersistent; begin Result := ''; l_Collection := Collection; if (l_Collection <> nil) then begin l_Owner := l_Collection.Owner; if (l_Owner <> nil) then begin if (GetPropInfo(l_Owner, 'Caption') <> nil) then Result := GetStrProp(l_Owner, 'Caption') else if (l_Owner Is TvcmCustomModuleDef) then Result := vcmStr(TvcmCustomModuleDef(l_Owner).ModuleDef.Caption); end;//l_Owner <> nil end;//l_Collection <> nil end; {$EndIf DesignTimeLibrary} function TvcmBaseOperationsCollectionItem.pm_GetGroupID: Integer; //virtual; {-} begin Result := f_GroupID; end; procedure TvcmBaseOperationsCollectionItem.pm_SetGroupID(aValue: Integer); //virtual; {-} begin f_GroupID := aValue; end; function TvcmBaseOperationsCollectionItem.GroupIDStored: Boolean; //virtual; {-} begin Result := (f_GroupID > 0); end; function TvcmBaseOperationsCollectionItem.pm_GetOperationType: TvcmOperationType; //virtual; {-} begin Result := f_OperationType; end; procedure TvcmBaseOperationsCollectionItem.pm_SetOperationType(aValue: TvcmOperationType); //virtual; {-} begin f_OperationType := aValue; end; function TvcmBaseOperationsCollectionItem.OperationTypeStored: Boolean; //virtual; {-} begin Result := (f_OperationType <> vcm_otButton); end; function TvcmBaseOperationsCollectionItem.pm_GetExcludeUserTypes: TvcmEffectiveUserTypes; //virtual; {-} begin Result := []; end; procedure TvcmBaseOperationsCollectionItem.pm_SetExcludeUserTypes(aValue: TvcmEffectiveUserTypes); //virtual; {-} begin end; procedure TvcmBaseOperationsCollectionItem.ChangeCaption(const anOld, aNew: AnsiString); //override; {* - вызывается при изменении пользовательского имени. } begin inherited; {$IfDef DesignTimeLibrary} vcmGetID(vcm_repOperationCaption, aNew); {$EndIf DesignTimeLibrary} end; function TvcmBaseOperationsCollectionItem.pm_GetStates: TvcmBaseOperationStates; //virtual; begin Result := f_States; end; procedure TvcmBaseOperationsCollectionItem.pm_SetStates(aValue: TvcmBaseOperationStates); {-} begin States.Assign(aValue); end; function TvcmBaseOperationsCollectionItem.pm_GetLinked: Boolean; //virtual; {-} begin Result := false; end; function TvcmBaseOperationsCollectionItem.IsHandledToControl: Boolean; {* - операция опубликована компонентом. } begin Result := Handled([vcm_htControl]) and not Handled([vcm_htGlobal, vcm_htContext]); end; procedure TvcmBaseOperationsCollectionItem.pm_SetLinked(aValue: Boolean); //virtual; {-} begin end; procedure TvcmBaseOperationsCollectionItem.pm_SetState(const aValue: TvcmOperationStateIndex); {-} begin if (f_State.rID <> aValue.rID) then begin if (aValue.rID >= vcm_DefaultOperationState.rID) AND (aValue.rID < States.Count) then begin f_State := aValue; end;//aValue >= vcm_DefaultOperationState.. end;//f_State <> aValue end; function TvcmBaseOperationsCollectionItem.pm_GetCurrentState: TvcmBaseOperationState; {-} begin if (f_State.rID = vcm_DefaultOperationState.rID) then Result := nil else Result := TvcmBaseOperationState(States.Items[f_State.rID]); end; procedure TvcmBaseOperationsCollectionItem.OnSecondaryShortCutsChange(Sender: TObject); {-} begin SetShortCuts(ShortCut, SecondaryShortCuts); end; class procedure TvcmBaseOperationsCollectionItem.ResetShortCutHandler(var aValue: TShortCut; aCommandID: Word); {-} var l_Controller : TOvcController; l_Key : Word; l_Shift : TShiftState; begin if (aValue <> 0) then begin l_Controller := GetDefController; if Assigned(l_Controller) then with l_Controller.EntryCommands do begin if GetCommandTableIndex(c_vcmTableName) < 0 then CreateCommandTable(c_vcmTableName, true); if (aCommandID = 0) then begin ShortCutToKey(aValue, l_Key, l_Shift); DeleteCommand(c_vcmTableName, l_Key, vcmByteShift(l_Shift), 0, 0); end else begin ShortCutToKey(aValue, l_Key, l_Shift); try AddCommand(c_vcmTableName, l_Key, vcmByteShift(l_Shift), 0, 0, aCommandID); except aValue := 0; end;//try..except end;//aCommandID = 0 end;//l_Controller.EntryCommands end;//aValue <> 0 end; function TvcmBaseOperationsCollectionItem.IsLinkedToModule: Boolean; {-} begin Result := false; if Assigned(Collection) then if (Collection.Owner is TvcmModulesCollectionItem) then Result := true else if (Collection.Owner is TvcmBaseEntitiesCollectionItem) then Result := false else if (Collection.Owner is TvcmCustomModuleDef) then with TvcmCustomModuleDef(Collection.Owner) do if Assigned(Owner) and (Owner is TvcmModule) then Result := true; end; function TvcmBaseOperationsCollectionItem.ParentID: Integer; {-} begin Result := 0; if Assigned(Collection) then if (Collection.Owner is TvcmModulesCollectionItem) then with TvcmModulesCollectionItem(Collection.Owner) do Result := -ModuleID else if (Collection.Owner is TvcmBaseEntitiesCollectionItem) then with TvcmBaseEntitiesCollectionItem(Collection.Owner) do Result := EntityID else if (Collection.Owner is TvcmCustomModuleDef) then with TvcmCustomModuleDef(Collection.Owner) do if Assigned(Owner) and (Owner is TvcmModule) then with TvcmModule(Owner) do Result := -ID; end; function TvcmBaseOperationsCollectionItem.ControllerCommand: Word; var l_ParentID : Integer; begin Result := 0; l_ParentID := ParentID; if (l_ParentID > 0) then Result := vcmCommandID(l_ParentID, false, OperationID) else if (l_ParentID < 0) then Result := vcmCommandID(-l_ParentID, true, OperationID) else Assert(false, 'Операция не привязана ни к сущности, ни к модулю'); end; function TvcmBaseOperationsCollectionItem.GetLinkedAction: TvcmAction; {* - Action к которому привязана операция. } begin Result := nil; if Assigned(Collection) then if (Collection.Owner is TvcmModulesCollectionItem) then with TvcmModulesCollectionItem(Collection.Owner) do Result := TvcmModuleAction.Make(Dispatcher.GetModuleByID(ModuleID).ModuleDef, OperationDef) else if (Collection.Owner is TvcmBaseEntitiesCollectionItem) then with TvcmBaseEntitiesCollectionItem(Collection.Owner) do Result := TvcmEntityAction.Make(EntityDef, OperationDef) else if (Collection.Owner is TvcmCustomModuleDef) then with TvcmCustomModuleDef(Collection.Owner) do if Assigned(Owner) and (Owner is TvcmModule) then with TvcmModule(Owner) do Result := TvcmModuleAction.Make(GetModuleDef, OperationDef); end; function TvcmBaseOperationsCollectionItem.pm_GetVisibleToUser: Boolean; begin if f_VisibleToUser = -1 then if (Caption <> '') AND (OperationType in vcmToolbarOpTypes) then f_VisibleToUser := 1 else f_VisibleToUser := 0; Result := f_VisibleToUser > 0; end; function TvcmBaseOperationsCollectionItem.Handled(aTypes: TvcmHandleTypes): Boolean; var l_Index : Integer; begin {$IfNDef DesignTimeLibrary} Result := ((vcm_htGlobal in aTypes) and Assigned(f_OnExecute)) or ((vcm_htContext in aTypes) and Assigned(f_OnContextExecute)); {$Else DesignTimeLibrary} Result := ((vcm_htGlobal in aTypes) and (GetMethodProp(Self, 'OnExecute').Code <> nil)) or ((vcm_htContext in aTypes) and (GetMethodProp(Self, 'OnContextExecute').Code <> nil)); {$EndIf DesignTimeLibrary} if not Result and (vcm_htControl in aTypes) and ((Controls <> nil) AND (Controls.Count > 0)) then for l_Index := 0 to Pred(Controls.Count) do if Assigned(TvcmActiveControlsCollectionItem(Controls.Items[l_Index]).OnExecute) then begin Result := True; break; end; end; procedure TvcmBaseOperationsCollectionItem.ReplaceShortCuts( aShortCut: TShortCut; aSecondaryShortCuts: {$IfDef XE}TCustomShortCutList{$Else}TShortCutList{$EndIf}); begin SetShortCuts(aShortCut, TShortCutList(aSecondaryShortCuts)); end; procedure TvcmBaseOperationsCollectionItem.StoreDesignTimeShortcuts; begin f_SaveShortcut := Shortcut; f_SaveSecondaryShortcuts := SecondaryShortCuts.Text; end; function TvcmBaseOperationsCollectionItem.IsDefaultStored: Boolean; begin Result := (f_IsDefault <> False); end; function TvcmBaseOperationsCollectionItem.pm_GetIsDefault: Boolean; begin Result := f_IsDefault; end; procedure TvcmBaseOperationsCollectionItem.pm_SetIsDefault( const aValue: Boolean); begin f_IsDefault := aValue; end; function TvcmBaseOperationsCollectionItem.pm_GetContextMenuWeight: Integer; begin Result := f_ContextMenuWeight; end; procedure TvcmBaseOperationsCollectionItem.pm_SetContextMenuWeight(aValue : Integer); begin f_ContextMenuWeight := aValue; end; end.
unit fb_2_rb_plugin; {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, ActiveX, Classes, ComObj, FB2_to_RB_TLB, StdVcl; type TFB2_2_RB_FBE_export = class(TTypedComObject, IFBEExportPlugin) protected function Export(hWnd: Integer; const filename: WideString; const document: IDispatch): HResult; stdcall; end; TOverridedComObjectFaactory=class(TTypedComObjectFactory) procedure UpdateRegistry(Register: Boolean); override; end; implementation uses ComServ,registry,fb_2_rb_dialog,MSXML2_TLB,SysUtils; function TFB2_2_RB_FBE_export.Export(hWnd: Integer; const filename: WideString; const document: IDispatch): HResult; begin Try Result:=ExportDOM(hWnd,IXMLDOMDocument2(document),filename); Except on E: Exception do Begin MessageBox(hWnd,PChar(E.Message),'Error',MB_OK or MB_ICONERROR); Result:=E_FAIL; end; end; end; Procedure TOverridedComObjectFaactory.UpdateRegistry; Var FBEPluginKey,fb2batchKey:String; Reg:TRegistry; DLLPath:String; Begin Inherited UpdateRegistry(Register); FBEPluginKey := 'SOFTWARE\Haali\FBE\Plugins\'+GUIDToString(CLASS_FB2_2_RB_FBE_export); fb2batchKey:= 'Software\Grib Soft\FB2Batch\Plugins\'+GUIDToString(CLASS_FB2AnyQuickExport); Reg:=TRegistry.Create; Try Reg.RootKey:=HKEY_LOCAL_MACHINE; If Register then Begin SetLength(DLLPath,2000); GetModuleFileName(HInstance,@DLLPath[1],1999); SetLength(DLLPath,Pos(#0,DLLPath)-1); Reg.OpenKey(FBEPluginKey,True); Reg.WriteString('','"FB to rb v0.1" plugin by GribUser grib@gribuser.ru'); Reg.WriteString('Menu','&FB2->RB by GribUser'); Reg.WriteString('Type','Export'); Reg.WriteString('Icon',DLLPath+',0'); Reg.CloseKey; Reg.OpenKey(fb2batchKey,True); Reg.WriteString('','"FB to rb v0.1" plugin by GribUser grib@gribuser.ru'); Reg.WriteString('Title','FB2->RB by GribUser'); Reg.WriteString('ext','rb'); Reg.WriteString('Icon',DLLPath+',0'); end else Begin Reg.DeleteKey(FBEPluginKey); Reg.DeleteKey(fb2batchKey); Reg.RootKey:=HKEY_CURRENT_USER; Reg.DeleteKey('software\Grib Soft\FB2 to RB\1.0') end; finally Reg.Free; end; end; initialization TOverridedComObjectFaactory.Create(ComServer, TFB2_2_RB_FBE_export, Class_FB2_2_RB_FBE_export, ciMultiInstance, tmApartment); end.
unit tfwClassLike; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwClassLike.pas" // Стереотип: "SimpleClass" // Элемент модели: "TtfwClassLike" MUID: (55CCAE000335) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces , tfwTypeInfo , kwCompiledWordPrimPrim , tfwWordRefList ; type TtfwClassLikeRunner = class(TkwCompiledWordPrimPrim) private f_LeftWordRefs: TtfwWordRefList; protected procedure PushParams(const aCtx: TtfwContext); procedure DoDoIt(const aCtx: TtfwContext); override; procedure Cleanup; override; {* Функция очистки полей объекта. } function pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; override; public constructor Create(aWordProducer: TtfwWord; const aCtx: TtfwContext; aLeftWordRefs: TtfwWordRefList); reintroduce; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; function GetValue(const aCtx: TtfwContext): TtfwStackValue; override; function RightParamsCount(const aCtx: TtfwContext): Integer; override; function LeftWordRefParamsCount(const aCtx: TtfwContext): Integer; override; function GetLeftWordRefValue(const aCtx: TtfwContext; anIndex: Integer): TtfwWord; override; function LeftWordRefValuesCount(const aCtx: TtfwContext): Integer; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; procedure SetValue(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TtfwClassLikeRunner TtfwClassLike = {abstract} class(TtfwRegisterableWord) protected function BindParams: Boolean; virtual; function StrictChecking: Boolean; virtual; procedure PushAdditionalParams(const aCtx: TtfwContext); override; public function LeftWordRefParamsCount(const aCtx: TtfwContext): Integer; override; function MakeRefForCompile(const aCtx: TtfwContext; aSNI: TtfwSuppressNextImmediate): TtfwWord; override; procedure SetValue(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TtfwClassLike {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , kwCompiledWordPrim , TypInfo , tfwValueTypes , SysUtils //#UC START# *55CCAE000335impl_uses* //#UC END# *55CCAE000335impl_uses* ; constructor TtfwClassLikeRunner.Create(aWordProducer: TtfwWord; const aCtx: TtfwContext; aLeftWordRefs: TtfwWordRefList); //#UC START# *55EEDC7E039C_55EEDC5001F3_var* //#UC END# *55EEDC7E039C_55EEDC5001F3_var* begin //#UC START# *55EEDC7E039C_55EEDC5001F3_impl* inherited Create(aWordProducer, aCtx, aWordProducer.Key); aLeftWordRefs.SetRefTo(f_LeftWordRefs); //#UC END# *55EEDC7E039C_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.Create procedure TtfwClassLikeRunner.PushParams(const aCtx: TtfwContext); //#UC START# *5617E35E018C_55EEDC5001F3_var* var l_Index : Integer; //#UC END# *5617E35E018C_55EEDC5001F3_var* begin //#UC START# *5617E35E018C_55EEDC5001F3_impl* for l_Index := 0 to Pred(f_LeftWordRefs.Count) do f_LeftWordRefs.Items[l_Index].DoIt(aCtx); //#UC END# *5617E35E018C_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.PushParams procedure TtfwClassLikeRunner.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_55EEDC5001F3_var* //#UC END# *4DAEEDE10285_55EEDC5001F3_var* begin //#UC START# *4DAEEDE10285_55EEDC5001F3_impl* PushParams(aCtx); WordProducer.DoIt(aCtx); //#UC END# *4DAEEDE10285_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.DoDoIt procedure TtfwClassLikeRunner.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_55EEDC5001F3_var* //#UC END# *479731C50290_55EEDC5001F3_var* begin //#UC START# *479731C50290_55EEDC5001F3_impl* FreeAndNil(f_LeftWordRefs); inherited; //#UC END# *479731C50290_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.Cleanup function TtfwClassLikeRunner.pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; //#UC START# *52CFC11603C8_55EEDC5001F3get_var* //#UC END# *52CFC11603C8_55EEDC5001F3get_var* begin //#UC START# *52CFC11603C8_55EEDC5001F3get_impl* Result := WordProducer.ResultTypeInfo[aCtx]; //#UC END# *52CFC11603C8_55EEDC5001F3get_impl* end;//TtfwClassLikeRunner.pm_GetResultTypeInfo procedure TtfwClassLikeRunner.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); //#UC START# *52D00B00031A_55EEDC5001F3_var* //#UC END# *52D00B00031A_55EEDC5001F3_var* begin //#UC START# *52D00B00031A_55EEDC5001F3_impl* PushParams(aCtx); WordProducer.SetValuePrim(aValue, aCtx); //#UC END# *52D00B00031A_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.SetValuePrim function TtfwClassLikeRunner.GetValue(const aCtx: TtfwContext): TtfwStackValue; //#UC START# *52D399A00173_55EEDC5001F3_var* //#UC END# *52D399A00173_55EEDC5001F3_var* begin //#UC START# *52D399A00173_55EEDC5001F3_impl* Result := WordProducer.GetValue(aCtx); //#UC END# *52D399A00173_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.GetValue function TtfwClassLikeRunner.RightParamsCount(const aCtx: TtfwContext): Integer; //#UC START# *52E9282B0271_55EEDC5001F3_var* //#UC END# *52E9282B0271_55EEDC5001F3_var* begin //#UC START# *52E9282B0271_55EEDC5001F3_impl* Result := WordProducer.RightParamsCount(aCtx); //#UC END# *52E9282B0271_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.RightParamsCount function TtfwClassLikeRunner.LeftWordRefParamsCount(const aCtx: TtfwContext): Integer; //#UC START# *53E4914101D2_55EEDC5001F3_var* //#UC END# *53E4914101D2_55EEDC5001F3_var* begin //#UC START# *53E4914101D2_55EEDC5001F3_impl* Result := WordProducer.LeftWordRefParamsCount(aCtx); //#UC END# *53E4914101D2_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.LeftWordRefParamsCount function TtfwClassLikeRunner.GetLeftWordRefValue(const aCtx: TtfwContext; anIndex: Integer): TtfwWord; //#UC START# *53E4A3C100AB_55EEDC5001F3_var* //#UC END# *53E4A3C100AB_55EEDC5001F3_var* begin //#UC START# *53E4A3C100AB_55EEDC5001F3_impl* CompilerAssert(f_LeftWordRefs <> nil, 'Нету значений для левых параметров по ссылке', aCtx); CompilerAssert((anIndex >= 0) AND (anIndex < f_LeftWordRefs.Count), 'Нету значения для левого параметра по ссылке, для индекса ' + IntToStr(anIndex), aCtx); Result := f_LeftWordRefs.Items[anIndex]; //#UC END# *53E4A3C100AB_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.GetLeftWordRefValue function TtfwClassLikeRunner.LeftWordRefValuesCount(const aCtx: TtfwContext): Integer; //#UC START# *53E4A96A0085_55EEDC5001F3_var* //#UC END# *53E4A96A0085_55EEDC5001F3_var* begin //#UC START# *53E4A96A0085_55EEDC5001F3_impl* if (f_LeftWordRefs = nil) then Result := 0 else Result := f_LeftWordRefs.Count; //#UC END# *53E4A96A0085_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.LeftWordRefValuesCount function TtfwClassLikeRunner.GetAllParamsCount(const aCtx: TtfwContext): Integer; //#UC START# *559687E6025A_55EEDC5001F3_var* //#UC END# *559687E6025A_55EEDC5001F3_var* begin //#UC START# *559687E6025A_55EEDC5001F3_impl* Result := WordProducer.GetAllParamsCount(aCtx); //#UC END# *559687E6025A_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.GetAllParamsCount procedure TtfwClassLikeRunner.SetValue(const aValue: TtfwStackValue; const aCtx: TtfwContext); //#UC START# *56096688024A_55EEDC5001F3_var* //#UC END# *56096688024A_55EEDC5001F3_var* begin //#UC START# *56096688024A_55EEDC5001F3_impl* PushParams(aCtx); WordProducer.SetValue(aValue, aCtx); //#UC END# *56096688024A_55EEDC5001F3_impl* end;//TtfwClassLikeRunner.SetValue function TtfwClassLike.BindParams: Boolean; //#UC START# *5617C8A30023_55CCAE000335_var* //#UC END# *5617C8A30023_55CCAE000335_var* begin //#UC START# *5617C8A30023_55CCAE000335_impl* //Result := false; Result := true; //#UC END# *5617C8A30023_55CCAE000335_impl* end;//TtfwClassLike.BindParams function TtfwClassLike.StrictChecking: Boolean; //#UC START# *561916700342_55CCAE000335_var* //#UC END# *561916700342_55CCAE000335_var* begin //#UC START# *561916700342_55CCAE000335_impl* Result := false; //#UC END# *561916700342_55CCAE000335_impl* end;//TtfwClassLike.StrictChecking function TtfwClassLike.LeftWordRefParamsCount(const aCtx: TtfwContext): Integer; //#UC START# *53E4914101D2_55CCAE000335_var* //#UC END# *53E4914101D2_55CCAE000335_var* begin //#UC START# *53E4914101D2_55CCAE000335_impl* if BindParams then Result := GetAllParamsCount(aCtx) - RightParamsCount(aCtx) else Result := 0; //#UC END# *53E4914101D2_55CCAE000335_impl* end;//TtfwClassLike.LeftWordRefParamsCount function TtfwClassLike.MakeRefForCompile(const aCtx: TtfwContext; aSNI: TtfwSuppressNextImmediate): TtfwWord; //#UC START# *55CB5B8C004E_55CCAE000335_var* var l_LeftWordRefCount : Integer; l_CodeIndex : Integer; l_Code : TtfwWordRefList; l_Index : Integer; l_AllParamsValid : Boolean; l_Refs : TtfwWordRefList; l_Types : PTypeInfoArray; l_TI : TtfwWordInfo; l_TypeIndex : Integer; l_ParamType : PTypeInfo; //#UC END# *55CB5B8C004E_55CCAE000335_var* begin //#UC START# *55CB5B8C004E_55CCAE000335_impl* if (aSNI = tfw_sniNo) then begin //if BindParams then if false then begin l_LeftWordRefCount := Self.LeftWordRefParamsCount(aCtx); if (l_LeftWordRefCount > 0) AND (aCtx.rWordCompilingNow <> nil) then begin l_CodeIndex := aCtx.rWordCompilingNow.CodeCount; if (l_LeftWordRefCount <= l_CodeIndex) then begin Dec(l_CodeIndex); if (aCtx.rWordCompilingNow Is TkwCompiledWordPrim) then begin l_Code := TkwCompiledWordPrim(aCtx.rWordCompilingNow).GetCode(aCtx); if (l_Code <> nil) then begin l_AllParamsValid := true; l_Types := ParamsTypes; l_TypeIndex := RightParamsCount(aCtx); for l_Index := l_CodeIndex downto l_CodeIndex - l_LeftWordRefCount + 1 do begin if not l_Code.Items[l_Index].IsCompleted(aCtx) then begin l_AllParamsValid := false; break; end;//not l_Code.Items[l_Index].IsCompleted(aCtx) l_TI := l_Code.Items[l_Index].ResultTypeInfo[aCtx]; l_ParamType := l_Types[l_TypeIndex]; if (l_TI.ValueTypes.AcceptableBy(TtfwTypeInfo_C(l_ParamType)) = tfw_vtaNo) then begin l_AllParamsValid := false; break; end; Inc(l_TypeIndex); end;//for l_Index if l_AllParamsValid then begin l_Refs := TtfwWordRefList.Create; try while (l_LeftWordRefCount > 0) do begin l_Refs.Insert(0, l_Code.Items[l_CodeIndex]); l_Code.Delete(l_CodeIndex); Dec(l_LeftWordRefCount); Dec(l_CodeIndex); end;//l_LeftWordRefCount > 0) Result := TtfwClassLikeRunner.Create(Self, aCtx, l_Refs); finally FreeAndNil(l_Refs); end;//try..finally Exit; end;//l_AllParamsValid end;//l_Code <> nil end;//aContext.rWordCompilingNow Is TkwCompiledWordPrim end;//l_LeftWordRefCount <= l_CodeIndex end;//l_LeftWordRefCount > 0 end;//BindParams end;//aSNI = tfw_sniNo Result := inherited MakeRefForCompile(aCtx, aSNI); //#UC END# *55CB5B8C004E_55CCAE000335_impl* end;//TtfwClassLike.MakeRefForCompile procedure TtfwClassLike.PushAdditionalParams(const aCtx: TtfwContext); //#UC START# *55EED3920052_55CCAE000335_var* //#UC END# *55EED3920052_55CCAE000335_var* begin //#UC START# *55EED3920052_55CCAE000335_impl* inherited; //#UC END# *55EED3920052_55CCAE000335_impl* end;//TtfwClassLike.PushAdditionalParams procedure TtfwClassLike.SetValue(const aValue: TtfwStackValue; const aCtx: TtfwContext); //#UC START# *56096688024A_55CCAE000335_var* //#UC END# *56096688024A_55CCAE000335_var* begin //#UC START# *56096688024A_55CCAE000335_impl* SetValuePrim(aValue, aCtx); //#UC END# *56096688024A_55CCAE000335_impl* end;//TtfwClassLike.SetValue initialization TtfwClassLikeRunner.RegisterClass; {* Регистрация TtfwClassLikeRunner } TtfwClassLike.RegisterClass; {* Регистрация TtfwClassLike } {$IfEnd} // NOT Defined(NoScripts) end.
unit K620665614_Hk0900071; {* [RequestLink:620665614] } // Модуль: "w:\common\components\rtl\Garant\Daily\K620665614_Hk0900071.pas" // Стереотип: "TestCase" // Элемент модели: "K620665614_Hk0900071" MUID: (56FA6D77032E) // Имя типа: "TK620665614_Hk0900071" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoBothNSRCWriterTest ; type TK620665614_Hk0900071 = class(TEVDtoBothNSRCWriterTest) {* [RequestLink:620665614] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK620665614_Hk0900071 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56FA6D77032Eimpl_uses* //#UC END# *56FA6D77032Eimpl_uses* ; function TK620665614_Hk0900071.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'CrossSegments'; end;//TK620665614_Hk0900071.GetFolder function TK620665614_Hk0900071.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56FA6D77032E'; end;//TK620665614_Hk0900071.GetModelElementGUID initialization TestFramework.RegisterTest(TK620665614_Hk0900071.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
//****************************************************************// // This is cut-and-pasted version of JclSysUtils.pas library from // // JEDI Code Library (JCL). Copyright (c) see contributors // // // // For use with History++ plugin // // // // This unit is not covered under GPL license, // // actual license is provided below // //****************************************************************// {**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { 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 JclSysUtils.pas. } { } { The Initial Developer of the Original Code is Marcel van Brakel. } { Portions created by Marcel van Brakel are Copyright (C) Marcel van Brakel. All rights reserved. } { } { Contributors: } { Alexander Radchenko, } { Andreas Hausladen (ahuser) } { Anthony Steele } { Bernhard Berger } { Heri Bender } { Jeff } { Jeroen Speldekamp } { Marcel van Brakel } { Peter Friese } { Petr Vones (pvones) } { Python } { Robert Marquardt (marquardt) } { Robert R. Marsh } { Robert Rossmair (rrossmair) } { Rudy Velthuis } { Uwe Schuster (uschuster) } { Wayne Sherman } { } {**************************************************************************************************} { } { Description: Various pointer and class related routines. } { } {**************************************************************************************************} // Last modified: $Date: 2005/12/26 20:30:07 $ // For history see end of file unit hpp_JclSysUtils; interface uses Windows, Classes, TypInfo; type TDynByteArray = array of Byte; Float = Extended; PFloat = ^Float; // Binary search function SearchSortedList(List: TList; SortFunc: TListSortCompare; Item: Pointer; Nearest: Boolean = False): Integer; type TUntypedSearchCompare = function(Param: Pointer; ItemIndex: Integer; const Value): Integer; function SearchSortedUntyped(Param: Pointer; ItemCount: Integer; SearchFunc: TUntypedSearchCompare; const Value; Nearest: Boolean = False): Integer; // Dynamic array sort and search routines type TDynArraySortCompare = function (Item1, Item2: Pointer): Integer; procedure SortDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare); // Usage: SortDynArray(Array, SizeOf(Array[0]), SortFunction); function SearchDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare; ValuePtr: Pointer; Nearest: Boolean = False): Integer; // Usage: SearchDynArray(Array, SizeOf(Array[0]), SortFunction, @SearchedValue); { Various compare functions for basic types } function DynArrayCompareByte(Item1, Item2: Pointer): Integer; function DynArrayCompareShortInt(Item1, Item2: Pointer): Integer; function DynArrayCompareWord(Item1, Item2: Pointer): Integer; function DynArrayCompareSmallInt(Item1, Item2: Pointer): Integer; function DynArrayCompareInteger(Item1, Item2: Pointer): Integer; function DynArrayCompareCardinal(Item1, Item2: Pointer): Integer; function DynArrayCompareInt64(Item1, Item2: Pointer): Integer; function DynArrayCompareSingle(Item1, Item2: Pointer): Integer; function DynArrayCompareDouble(Item1, Item2: Pointer): Integer; function DynArrayCompareExtended(Item1, Item2: Pointer): Integer; function DynArrayCompareFloat(Item1, Item2: Pointer): Integer; function DynArrayCompareAnsiString(Item1, Item2: Pointer): Integer; function DynArrayCompareAnsiText(Item1, Item2: Pointer): Integer; function DynArrayCompareString(Item1, Item2: Pointer): Integer; function DynArrayCompareText(Item1, Item2: Pointer): Integer; implementation uses Types, SysUtils; //=== Binary search ========================================================== function SearchSortedList(List: TList; SortFunc: TListSortCompare; Item: Pointer; Nearest: Boolean): Integer; var L, H, I, C: Integer; B: Boolean; begin Result := -1; if List <> nil then begin L := 0; H := List.Count - 1; B := False; while L <= H do begin I := (L + H) shr 1; C := SortFunc(List.List^[I], Item); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin B := True; L := I; end; end; end; if B then Result := L else if Nearest and (H >= 0) then Result := H; end; end; function SearchSortedUntyped(Param: Pointer; ItemCount: Integer; SearchFunc: TUntypedSearchCompare; const Value; Nearest: Boolean): Integer; var L, H, I, C: Integer; B: Boolean; begin Result := -1; if ItemCount > 0 then begin L := 0; H := ItemCount - 1; B := False; while L <= H do begin I := (L + H) shr 1; C := SearchFunc(Param, I, Value); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin B := True; L := I; end; end; end; if B then Result := L else if Nearest and (H >= 0) then Result := H; end; end; //=== Dynamic array sort and search routines ================================= procedure SortDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare); var TempBuf: TDynByteArray; function ArrayItemPointer(Item: Integer): Pointer; begin Result := Pointer(Cardinal(ArrayPtr) + (Cardinal(Item) * ElementSize)); end; procedure QuickSort(L, R: Integer); var I, J, T: Integer; P, IPtr, JPtr: Pointer; begin repeat I := L; J := R; P := ArrayItemPointer((L + R) shr 1); repeat while SortFunc(ArrayItemPointer(I), P) < 0 do Inc(I); while SortFunc(ArrayItemPointer(J), P) > 0 do Dec(J); if I <= J then begin IPtr := ArrayItemPointer(I); JPtr := ArrayItemPointer(J); case ElementSize of SizeOf(Byte): begin T := PByte(IPtr)^; PByte(IPtr)^ := PByte(JPtr)^; PByte(JPtr)^ := T; end; SizeOf(Word): begin T := PWord(IPtr)^; PWord(IPtr)^ := PWord(JPtr)^; PWord(JPtr)^ := T; end; SizeOf(Integer): begin T := PInteger(IPtr)^; PInteger(IPtr)^ := PInteger(JPtr)^; PInteger(JPtr)^ := T; end; else Move(IPtr^, TempBuf[0], ElementSize); Move(JPtr^, IPtr^, ElementSize); Move(TempBuf[0], JPtr^, ElementSize); end; if P = IPtr then P := JPtr else if P = JPtr then P := IPtr; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; begin if ArrayPtr <> nil then begin SetLength(TempBuf, ElementSize); QuickSort(0, PInteger(Cardinal(ArrayPtr) - 4)^ - 1); end; end; function SearchDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare; ValuePtr: Pointer; Nearest: Boolean): Integer; var L, H, I, C: Integer; B: Boolean; begin Result := -1; if ArrayPtr <> nil then begin L := 0; H := PInteger(Cardinal(ArrayPtr) - 4)^ - 1; B := False; while L <= H do begin I := (L + H) shr 1; C := SortFunc(Pointer(Cardinal(ArrayPtr) + (Cardinal(I) * ElementSize)), ValuePtr); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin B := True; L := I; end; end; end; if B then Result := L else if Nearest and (H >= 0) then Result := H; end; end; { Various compare functions for basic types } function DynArrayCompareByte(Item1, Item2: Pointer): Integer; begin Result := PByte(Item1)^ - PByte(Item2)^; end; function DynArrayCompareShortInt(Item1, Item2: Pointer): Integer; begin Result := PShortInt(Item1)^ - PShortInt(Item2)^; end; function DynArrayCompareWord(Item1, Item2: Pointer): Integer; begin Result := PWord(Item1)^ - PWord(Item2)^; end; function DynArrayCompareSmallInt(Item1, Item2: Pointer): Integer; begin Result := PSmallInt(Item1)^ - PSmallInt(Item2)^; end; function DynArrayCompareInteger(Item1, Item2: Pointer): Integer; begin Result := PInteger(Item1)^ - PInteger(Item2)^; end; function DynArrayCompareCardinal(Item1, Item2: Pointer): Integer; begin Result := PInteger(Item1)^ - PInteger(Item2)^; end; function DynArrayCompareInt64(Item1, Item2: Pointer): Integer; begin Result := PInt64(Item1)^ - PInt64(Item2)^; end; function DynArrayCompareSingle(Item1, Item2: Pointer): Integer; begin if PSingle(Item1)^ < PSingle(Item2)^ then Result := -1 else if PSingle(Item1)^ > PSingle(Item2)^ then Result := 1 else Result := 0; end; function DynArrayCompareDouble(Item1, Item2: Pointer): Integer; begin if PDouble(Item1)^ < PDouble(Item2)^ then Result := -1 else if PDouble(Item1)^ > PDouble(Item2)^ then Result := 1 else Result := 0; end; function DynArrayCompareExtended(Item1, Item2: Pointer): Integer; begin if PExtended(Item1)^ < PExtended(Item2)^ then Result := -1 else if PExtended(Item1)^ > PExtended(Item2)^ then Result := 1 else Result := 0; end; function DynArrayCompareFloat(Item1, Item2: Pointer): Integer; begin if PFloat(Item1)^ < PFloat(Item2)^ then Result := -1 else if PFloat(Item1)^ > PFloat(Item2)^ then Result := 1 else Result := 0; end; function DynArrayCompareAnsiString(Item1, Item2: Pointer): Integer; begin Result := AnsiCompareStr(PAnsiString(Item1)^, PAnsiString(Item2)^); end; function DynArrayCompareAnsiText(Item1, Item2: Pointer): Integer; begin Result := AnsiCompareText(PAnsiString(Item1)^, PAnsiString(Item2)^); end; function DynArrayCompareString(Item1, Item2: Pointer): Integer; begin Result := CompareStr(PAnsiString(Item1)^, PAnsiString(Item2)^); end; function DynArrayCompareText(Item1, Item2: Pointer): Integer; begin Result := CompareText(PAnsiString(Item1)^, PAnsiString(Item2)^); end; end.
unit xn.grid.Sort.test; { 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 cSampleData, TestFramework, Generics.Collections, xn.grid.data, xn.grid.common, xn.grid.link; type TestTxnGridLinkSampleGridData = class(TTestCase) strict private fGridDataFilterSort: TxnGridLink; fGridSortItems: IxnGridSortItems; fGridFilterItems: IxnGridFilterItems; function BuildArray(aNumber: double): TArray<variant>; strict protected fGridData: IxnGridData; public procedure GridDataCreate; virtual; procedure SetUp; override; procedure TearDown; override; published procedure Test_RowCount; procedure Test_Value_0_0; procedure Test_Value_3_15; procedure Test_AsDebug_NoFilter_NoSort_Ok; procedure Test_Sort_Column_0_Str_Asc_Ok; procedure Test_Sort_Column_0_Str_Desc_Ok; procedure Test_Sort_Column_0_Num_Asc_Ok; procedure Test_Sort_Column_0_Num_Desc_Ok; procedure Test_Sort_Column_2_Str_Asc_Column_0_Num_Desc_Ok; procedure Test_Sort_Column_3_Num_Asc_Column_0_Num_Desc_Ok; procedure Test_SeekActual_0_Found; procedure Test_SeekActual_1_Not_Found; procedure Test_SeekActual_2_Found; procedure Test_SeekActual_37_Not_Found; procedure Test_SeekActual_38_Found; procedure Test_SeekActual_39_Not_Found; procedure Test_SeekExpected_0_Found; procedure Test_SeekExpected_1_Not_Found; procedure Test_SeekExpected_2_Found; procedure Test_SeekExpected_37_Not_Found; procedure Test_SeekExpected_38_Found; procedure Test_SeekExpected_39_Not_Found; procedure Test_Filter_Column_2_LA_CI_Ok; procedure Test_Filter_Column_5_F_CI_Ok; procedure Test_Filter_Column_5_F_CI_Column_1_Lime_CS_Ok; procedure Test_Filter_Column_3_376_Ok; end; TestTxnGridLinkSampleGridList = class(TestTxnGridLinkSampleGridData) public procedure GridDataCreate; override; end; implementation function TestTxnGridLinkSampleGridData.BuildArray(aNumber: double): TArray<variant>; begin SetLength(Result, 1); Result[0] := aNumber; end; procedure TestTxnGridLinkSampleGridData.GridDataCreate; begin fGridData := TSampleGridData.Create; end; procedure TestTxnGridLinkSampleGridData.SetUp; begin GridDataCreate; fGridSortItems := TxnGridSortItems.Create; fGridFilterItems := TxnGridFilterItems.Create; fGridDataFilterSort := TxnGridLink.Create(fGridData, fGridFilterItems, fGridSortItems); end; procedure TestTxnGridLinkSampleGridData.TearDown; begin fGridDataFilterSort.Free; fGridDataFilterSort := nil; end; procedure TestTxnGridLinkSampleGridData.Test_AsDebug_NoFilter_NoSort_Ok; begin CheckEquals('0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Filter_Column_2_LA_CI_Ok; begin fGridFilterItems.Add(TxnGridFilterItem.Create(2, 'la', gfkStr, gfcCaseInsensitive)); fGridDataFilterSort.Fill; CheckEquals('2,8,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Filter_Column_3_376_Ok; begin fGridFilterItems.Add(TxnGridFilterItem.Create(3, '3,76', gfkNum, gfcCaseInsensitive)); fGridDataFilterSort.Fill; CheckEquals('2,30,36,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Filter_Column_5_F_CI_Column_1_Lime_CS_Ok; begin fGridFilterItems.Add(TxnGridFilterItem.Create(5, 'f', gfkStr, gfcCaseInsensitive)); fGridFilterItems.Add(TxnGridFilterItem.Create(1, 'Lime', gfkStr, gfcCaseSensitive)); fGridDataFilterSort.Fill; CheckEquals('12,16,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Filter_Column_5_F_CI_Ok; begin fGridFilterItems.Add(TxnGridFilterItem.Create(5, 'f', gfkStr, gfcCaseInsensitive)); fGridDataFilterSort.Fill; CheckEquals('6,8,12,16,18,20,22,28,30,34,36,38,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_RowCount; begin CheckEquals(20, fGridDataFilterSort.RowCountGet); end; procedure TestTxnGridLinkSampleGridData.Test_SeekExpected_0_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek2(BuildArray(0)), 0); end; procedure TestTxnGridLinkSampleGridData.Test_SeekExpected_1_Not_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek2(BuildArray(1)), 1); end; procedure TestTxnGridLinkSampleGridData.Test_SeekExpected_2_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek2(BuildArray(2)), 1); end; procedure TestTxnGridLinkSampleGridData.Test_SeekExpected_37_Not_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek2(BuildArray(37)), 19); end; procedure TestTxnGridLinkSampleGridData.Test_SeekExpected_38_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek2(BuildArray(38)), 19); end; procedure TestTxnGridLinkSampleGridData.Test_SeekExpected_39_Not_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek2(BuildArray(39)), -1); end; procedure TestTxnGridLinkSampleGridData.Test_SeekActual_0_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek1(BuildArray(0)), 0); end; procedure TestTxnGridLinkSampleGridData.Test_SeekActual_1_Not_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek1(BuildArray(1)), -1); end; procedure TestTxnGridLinkSampleGridData.Test_SeekActual_2_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek1(BuildArray(2)), 1); end; procedure TestTxnGridLinkSampleGridData.Test_SeekActual_37_Not_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek1(BuildArray(37)), -1); end; procedure TestTxnGridLinkSampleGridData.Test_SeekActual_38_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek1(BuildArray(38)), 19); end; procedure TestTxnGridLinkSampleGridData.Test_SeekActual_39_Not_Found; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals(fGridDataFilterSort.Seek1(BuildArray(39)), -1); end; procedure TestTxnGridLinkSampleGridData.Test_Sort_Column_0_Num_Asc_Ok; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals('0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Sort_Column_0_Num_Desc_Ok; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoDesc)); fGridDataFilterSort.Sort; CheckEquals('38,36,34,32,30,28,26,24,22,20,18,16,14,12,10,8,6,4,2,0,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Sort_Column_0_Str_Asc_Ok; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskStr, gsoAsc)); fGridDataFilterSort.Sort; CheckEquals('0,10,12,14,16,18,2,20,22,24,26,28,30,32,34,36,38,4,6,8,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Sort_Column_0_Str_Desc_Ok; begin fGridSortItems.Add(TxnGridSortItem.Create(0, gskStr, gsoDesc)); fGridDataFilterSort.Sort; CheckEquals('8,6,4,38,36,34,32,30,28,26,24,22,20,2,18,16,14,12,10,0,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Sort_Column_2_Str_Asc_Column_0_Num_Desc_Ok; begin fGridSortItems.Add(TxnGridSortItem.Create(2, gskStr, gsoAsc)); fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoDesc)); fGridDataFilterSort.Sort; CheckEquals('30,34,38,12,8,2,0,26,32,28,6,36,10,20,24,14,18,16,4,22,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Sort_Column_3_Num_Asc_Column_0_Num_Desc_Ok; begin fGridSortItems.Add(TxnGridSortItem.Create(3, gskNum, gsoAsc)); fGridSortItems.Add(TxnGridSortItem.Create(0, gskNum, gsoDesc)); fGridDataFilterSort.Sort; CheckEquals('20,0,10,6,38,22,12,8,14,26,18,16,28,36,30,2,34,32,24,4,', fGridDataFilterSort.AsDebug); end; procedure TestTxnGridLinkSampleGridData.Test_Value_0_0; begin CheckEquals('0', fGridDataFilterSort.ValueString(0, 0)); end; procedure TestTxnGridLinkSampleGridData.Test_Value_3_15; begin CheckEquals('3,76', fGridDataFilterSort.ValueString(3, 15)); end; { TestTxnGridLinkSampleGridList } procedure TestTxnGridLinkSampleGridList.GridDataCreate; begin fGridData := TSampleGridDataList.Create; end; initialization RegisterTest(TestTxnGridLinkSampleGridData.Suite); //RegisterTest(TestTxnGridLinkSampleGridList.Suite); end.
unit MdiChilds.FmNotesProcessor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, Parsers.Excel.Notes, GsDocument, ActionHandler; type TFmNoteProcess = class(TFmProcess) edtDoc: TLabeledEdit; btnOpenDoc: TButton; edtExcel: TLabeledEdit; btnOpenExcel: TButton; OpenDialog: TOpenDialog; procedure btnOpenDocClick(Sender: TObject); procedure btnOpenExcelClick(Sender: TObject); private { Private declarations } protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public { Public declarations } end; TNotesActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmNoteProcess: TFmNoteProcess; implementation {$R *.dfm} procedure TFmNoteProcess.btnOpenDocClick(Sender: TObject); begin if OpenDialog.Execute then edtDoc.Text := OpenDialog.FileName; end; procedure TFmNoteProcess.btnOpenExcelClick(Sender: TObject); begin if OpenDialog.Execute then edtExcel.Text := OpenDialog.FileName; end; procedure TFmNoteProcess.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var D: TGsDocument; P: TExcelNotesParser; begin ShowMessage := True; D := TGsDocument.Create; try D.LoadFromFile(edtDoc.Text); P := TExcelNotesParser.Create(D); try P.ParseDoc(edtExcel.Text); finally P.Free; end; finally D.Free; end; end; { TNotesActionHandler } procedure TNotesActionHandler.ExecuteAction(UserData: Pointer); begin TFmNoteProcess.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Добавление примечания в сборник', hkDefault, TNotesActionHandler); end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit LoginUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TLoginForm = class(TForm) AccountEdit: TEdit; AccountLabel: TLabel; PasswordEdit: TEdit; PasswordLabel: TLabel; SavePassCheckBox: TCheckBox; OKButton: TButton; CancelButton: TButton; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure TranslateForm; end; {$ENDREGION} var LoginForm: TLoginForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses UtilsUnit, VarsUnit, MainUnit; {$ENDREGION} {$REGION 'FormCreate'} procedure TLoginForm.FormCreate(Sender: TObject); begin // Переводим окно на другие языки TranslateForm; // Делаем окно независимым и помещаем его кнопку на панель задач SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end; {$ENDREGION} {$REGION 'TranslateForm'} procedure TLoginForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); // Другое CancelButton.Caption := Lang_Vars[9].L_S; end; {$ENDREGION} 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.21 2/23/2005 6:34:28 PM JPMugaas New property for displaying permissions ina GUI column. Note that this should not be used like a CHMOD because permissions are different on different platforms - you have been warned. Rev 1.20 10/26/2004 9:56:00 PM JPMugaas Updated refs. Rev 1.19 8/5/2004 11:18:16 AM JPMugaas Should fix a parsing problem I introeduced that caused errors with Unitree servers. Rev 1.18 8/4/2004 12:40:12 PM JPMugaas Fix for problem with total line. Rev 1.17 7/15/2004 4:02:48 AM JPMugaas Fix for some FTP servers. In a Unix listing, a : at the end of a filename was wrongly being interpretted as a subdirectory entry in a recursive listing. Rev 1.16 6/14/2004 12:05:54 AM JPMugaas Added support for the following Item types that appear in some Unix listings (particularly a /dev or /tmp dir): FIFO, Socket, Character Device, Block Device. Rev 1.15 6/13/2004 10:44:06 PM JPMugaas Fixed a problem with some servers returning additional columns in the owner and group feilds. Note that they will not be parsed correctly in all cases. That's life. drwx------ 1 BUILTIN NT AUTHORITY 0 Dec 7 2001 System Volume Information Rev 1.14 4/20/2004 4:01:18 PM JPMugaas Fix for nasty typecasting error. The wrong create was being called. Rev 1.13 4/19/2004 5:05:20 PM JPMugaas Class rework Kudzu wanted. Rev 1.12 2004.02.03 5:45:18 PM czhower Name changes Rev 1.11 2004.01.23 9:53:32 PM czhower REmoved unneded check because of CharIsInSet functinoalty. Also was a short circuit which is not permitted. Rev 1.10 1/23/2004 12:49:52 PM SPerry fixed set problems Rev 1.9 1/22/2004 8:29:02 AM JPMugaas Removed Ansi*. Rev 1.8 1/22/2004 7:20:48 AM JPMugaas System.Delete changed to IdDelete so the code can work in NET. Rev 1.7 10/19/2003 3:48:10 PM DSiders Added localization comments. Rev 1.6 9/28/2003 03:02:30 AM JPMugaas Now can handle a few non-standard date types. Rev 1.5 9/3/2003 07:34:40 PM JPMugaas Parsing for /bin/ls with devices now should work again. Rev 1.4 4/7/2003 04:04:26 PM JPMugaas User can now descover what output a parser may give. Rev 1.3 4/3/2003 03:37:36 AM JPMugaas Fixed a bug in the Unix parser causing it not to work properly with Unix BSD servers using the -T switch. Note that when a -T switch s used on a FreeBSD server, the server outputs the millaseconds and an extra column giving the year instead of either the year or time (the regular /bin/ls standard behavior). Rev 1.2 3/3/2003 07:17:58 PM JPMugaas Now honors the FreeBSD -T flag and parses list output from a program using it. Minor changes to the File System component. Rev 1.1 2/19/2003 05:53:14 PM JPMugaas Minor restructures to remove duplicate code and save some work with some formats. The Unix parser had a bug that caused it to give a False positive for Xercom MicroRTOS. Rev 1.0 2/19/2003 02:02:02 AM JPMugaas Individual parsing objects for the new framework. } unit IdFTPListParseUnix; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; { Notes: - The Unitree and Unix parsers are closely tied together and share just about all of the same code. The reason is that Unitee is very similar to a Unix dir list except it has an extra column which the Unix line parser can handle in the Unitree type. - The Unix parser can parse MACOS - Peters server (no relationship to this author :-) ). - It is worth noting that the parser does handle /bin/ls -s and -i switches as well as -g and -o. This is important sometimes as the Unix format comes from FTP servers that simply piped output from the Unix /bin/ls command. - This parser also handles recursive lists which is good for mirroring software. } type { Note that for this, I am violating a convention. The violation is that I am putting parsers for two separate servers in the same unit. The reason is this, Unitree has two additional columns (a file family and a file migration status. The line parsing code is the same because I thought it was easier to do that way in this case. } TIdUnixFTPListItem = class(TIdUnixBaseFTPListItem) protected FNumberBlocks : Integer; FInode : Integer; public property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks; property Inode : Integer read FInode write FInode; end; TIdUnitreeFTPListItem = class(TIdUnixFTPListItem) protected FMigrated : Boolean; FFileFamily : String; public property Migrated : Boolean read FMigrated write FMigrated; property FileFamily : String read FFileFamily write FFileFamily; end; TIdFTPLPUnix = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function InternelChkUnix(const AData : String) : Boolean; virtual; class function IsUnitree(const AData: string): Boolean; virtual; class function IsUnitreeBanner(const AData: String): Boolean; virtual; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; class function ParseListing(AListing : TStrings; ADir : TIdFTPListItems) : Boolean; override; end; TIdFTPLPUnitree = class(TIdFTPLPUnix) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; public class function GetIdent : String; override; end; const UNIX = 'Unix'; {do not localize} UNITREE = 'Unitree'; {do not localize} // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseUnix"'*) implementation uses IdException, IdGlobal, IdFTPCommon, IdGlobalProtocols, {$IFDEF VCL_6_OR_ABOVE}DateUtils,{$ENDIF} SysUtils; { TIdFTPLPUnix } class function TIdFTPLPUnix.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var i : Integer; begin // TODO: return True if ASysDescript starts with 'Unix'? Result := False; for i := 0 to AListing.Count - 1 do begin if AListing[i] <> '' then begin //workaround for the XBox MediaCenter FTP Server //which returns something like this: // //dr-xr-xr-x 1 ftp ftp 1 Feb 23 00:00 D: //and the trailing : is falsely assuming that a ":" means //a subdirectory entry in a recursive list. if InternelChkUnix(AListing[i]) then begin if GetIdent = UNITREE then begin Result := IsUnitree(AListing[i]); end else begin Result := not IsUnitree(AListing[i]); end; Break; end; if not (IsTotalLine(AListing[i]) or IsSubDirContentsBanner(AListing[i])) then begin Break; end; end; end; end; class function TIdFTPLPUnix.GetIdent: String; begin Result := UNIX; end; class function TIdFTPLPUnix.InternelChkUnix(const AData: String): Boolean; var s : TStrings; LCData : String; begin //pos 1 values // d - dir // - - file // l - symbolic link // b - block device // c - charactor device // p - pipe (FIFO) // s - socket LCData := UpperCase(AData); Result := IsValidUnixPerms(AData); if Result then begin //Do NOT attempt to do Novell Netware Print Services for Unix FTPD in NFS //namespace if we have a block device. if CharIsInSet(LCData, 1, 'CB') then begin Exit; end; //This extra complexity is required to distinguish Unix from //a Novell Netware server in NFS namespace which is somewhat similar //to a Unix listing. Beware. s := TStringList.Create; try SplitColumns(LCData, s); if s.Count > 9 then begin Result := PosInStrArray(s[9], ['AM', 'PM']) = -1; {do not localize} if Result then begin // allow localized months longer than 3 characters Result := not ((IndyPos(':', s[8]) = 0) and (StrToMonth(s[6]) > 0)); {do not localize} end; end; finally FreeAndNil(s); end; end else begin //we make an additional check for two additional rows before the //the permissions. These are the inode and block count for the item. //These are specified with the -i and -s parameters. s := TStringList.Create; try SplitColumns(LCData, s); if s.Count > 3 then begin if IsNumeric(s[0]) then begin Result := IsValidUnixPerms(S[1]); if not Result then begin Result := IsNumeric(s[1]) and IsValidUnixPerms(S[2]); end; end; end; finally FreeAndNil(s); end; end; end; class function TIdFTPLPUnix.IsUnitree(const AData: string): Boolean; var s : TStrings; begin s := TStringList.Create; try SplitColumns(AData, s); Result := (s.Count > 4) and (PosInStrArray(s[4], UnitreeStoreTypes) <> -1); if not Result then begin Result := IsUnitreeBanner(AData); end; finally FreeAndNil(s); end; end; class function TIdFTPLPUnix.IsUnitreeBanner(const AData: String): Boolean; begin Result := TextStartsWith(AData, '/') and TextEndsWith(AData, ').') and (IndyPos('(', AData) > 0); {do not localize} end; class function TIdFTPLPUnix.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdUnixFTPListItem.Create(AOwner); end; class function TIdFTPLPUnix.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; {Note that we also use this parser for Unitree FTP Servers because that server is like Unix except that in Unitree, there's two additional columns before the size. Those are: Storage Type - AR - archived or migrated to tape and DK File family - } type TParseUnixSteps = (pusINode, pusBlocks, pusPerm, pusCount, pusOwner, pusGroup, pusSize, pusMonth, pusDay, pusYear, pusTime, pusName, pusDone); var LStep: TParseUnixSteps; LData, LTmp: String; LInode, LBlocks, LDir, LGPerm, LOPerm, LUPerm, LCount, LOwner, LGroup: String; LName, LSize, LLinkTo: String; wYear, wMonth, wDay: Word; wCurrYear, wCurrMonth, wCurrDay: Word; // wYear, LCurrentMonth, wMonth, wDay: Word; wHour, wMin, wSec, wMSec: Word; ADate: TDateTime; i: Integer; LI : TIdUnixFTPListItem; wDayStr: string; function IsGOSwitches(const AString : String) : Boolean; var s : TStrings; begin //check to see if both the -g and -o switches were used. Both //owner and group are surpressed in that case. We have to check //that so our interpretation does not cause an error. Result := False; s := TStringList.Create; try SplitColumns(AString, s); if s.Count > 2 then begin //if either inode or block count were given if IsNumeric(s[0]) then begin s.Delete(0); end; //if both inode and block count were given if IsNumeric(s[0]) then begin s.Delete(0); end; if s.Count > 5 then begin if StrToMonth(s[3]) > 0 then begin Result := IsNumeric(s[4]) and (IsNumeric(s[5]) or (IndyPos(':', s[5]) > 0)); {do not localize} end; end; end; finally FreeAndNil(s); end; end; function FixBonkedYear(const AStrPart : String) : String; var LB : String; begin LB := AStrPart; Result := Fetch(LB); Result := StringReplace(Result, '-', ' ', [rfReplaceAll]); {do not localize} Result := StringReplace(Result, '/', ' ', [rfReplaceAll]); {do not localize} Result := Result + ' ' + LB; {do not localize} end; begin LI := AItem as TIdUnixFTPListItem; // Get defaults for modified date/time ADate := Now; DecodeDate(ADate, wYear, wMonth, wDay); DecodeTime(ADate, wHour, wMin, wSec, wMSec); LData := AItem.Data; LStep := pusINode; repeat case LStep of pusINode: begin //we do it this way because the column for inode is right justified //and we don't want to create a problem if the -i parameter was never used LTmp := TrimLeft(LData); LTmp := Fetch(LTmp); if IsValidUnixPerms(LTmp) then begin LStep := pusPerm; end else begin //the inode column is right justified LData := TrimLeft(LData); LTmp := Fetch(LData); LData := TrimLeft(LData); LInode := LTmp; LStep := pusBlocks; end; end; pusBlocks: begin //Note that there is an ambigioutity because this value could //be the inode if only the -i switch was used. LTmp := Fetch(LData, ' ', False); {do not localize} if not IsValidUnixPerms(LTmp) then begin LTmp := Fetch(LData); LData := TrimLeft(LData); LBlocks := LTmp; end; LStep := pusPerm; end; pusPerm: begin //1.-rw-rw-rw- LTmp := Fetch(LData); LData := TrimLeft(LData); // Copy the predictable pieces LI.PermissionDisplay := Copy(LTmp, 1, 10); LDir := UpperCase(Copy(LTmp, 1, 1)); LOPerm := Copy(LTmp, 2, 3); LGPerm := Copy(LTmp, 5, 3); LUPerm := Copy(LTmp, 8, 3); LStep := pusCount; end; pusCount: begin LData := TrimLeft(LData); LTmp := Fetch(LData); LData := TrimLeft(LData); //Patch for NetPresenz // "-------r-- 326 1391972 1392298 Nov 22 1995 MegaPhone.sit" */ // "drwxrwxr-x folder 2 May 10 1996 network" */ if TextIsSame(LTmp, 'folder') then begin {do not localize} LStep := pusSize; end else begin //APR //Patch for overflow -r--r--r-- 0526478 128 Dec 30 2002 DE292000 if (Length(LTmp) > 3) and (LTmp[1] = '0') then begin LData := Copy(LTmp, 2, MaxInt) + ' ' + LData; LCount := '0'; end else begin LCount := LTmp; end; //this check is necessary if both the owner and group were surpressed. if IsGOSwitches(AItem.Data) then begin LStep := pusSize; end else begin LStep := pusOwner; end; end; LData := TrimLeft(LData); end; pusOwner: begin LTmp := Fetch(LData); LData := TrimLeft(LData); LOwner := LTmp; LStep := pusGroup; end; pusGroup: begin LTmp := Fetch(LData); LData := TrimLeft(LData); LGroup := LTmp; LStep := pusSize; end; pusSize: begin //Ericsson - Switch FTP returns empty owner //Do not apply Ericson patch to Unitree if IsAlpha(LData, 1, 1) and (GetIdent <> UNITREE) then begin LSize := LGroup; LGroup := LOwner; LOwner := ''; //we do this just after the erickson patch because //a few servers might return additional columns. // //e.g. // //drwx------ 1 BUILTIN NT AUTHORITY 0 Dec 7 2001 System Volume Information if not IsNumeric(LSize) then begin //undo the Ericson patch LOwner := LGroup; LGroup := ''; repeat LGroup := LGroup + ' ' + LSize; LOwner := LGroup; LData := TrimLeft(LData); LSize := Fetch(LData); until IsNumeric(LSize); //delete the initial space we had added in the repeat loop IdDelete(LGroup, 1, 1); end; end else begin LTmp := Fetch(LData); //This is necessary for cases where are char device is listed //e.g. //crw-rw-rw- 1 0 1 11, 42 Aug 8 2000 tcp // //Note sure what 11, 42 is so size is not returned. if IndyPos(',', LTmp) > 0 then begin {do not localize} LData := TrimLeft(LData); Fetch(LData); LData := TrimLeft(LData); LSize := ''; end else begin LSize := LTmp; end; LData := TrimLeft(LData); case PosInStrArray(LSize, UnitreeStoreTypes) of 0 : //AR - archived to tape - migrated begin if AItem is TIdUnitreeFTPListItem then begin (LI as TIdUnitreeFTPListItem).Migrated := True; (LI as TIdUnitreeFTPListItem).FileFamily := Fetch(LData); end; LData := TrimLeft(LData); LSize := Fetch(LData); LData := TrimLeft(LData); end; 1 : //DK - disk begin if AItem is TIdUnitreeFTPListItem then begin (LI as TIdUnitreeFTPListItem).FileFamily := Fetch(LData); end; LData := TrimLeft(LData); LSize := Fetch(LData); LData := TrimLeft(LData); end; end; end; LStep := pusMonth; end; pusMonth: begin // Scan modified MMM // Handle Chinese listings; the month, day, and year may not have spaces between them if IndyPos(ChineseYear, LData) > 0 then begin wYear := IndyStrToInt(Fetch(LData, ChineseYear)); LData := TrimLeft(LData); // Set time info to 00:00:00.999 wHour := 0; wMin := 0; wSec := 0; wMSec := 999; LStep := pusName end; if IndyPos(ChineseDay, LData) > 0 then begin wMonth := IndyStrToInt(Fetch(LData, ChineseMonth)); LData := TrimLeft(LData); wDay := IndyStrToInt(Fetch(LData, ChineseDay)); LData := TrimLeft(LData); if LStep <> pusName then begin LTmp := Fetch(LData); LStep := pusTime; end; Continue; end; //fix up a bonked date such as: //-rw-r--r-- 1 root other 531 09-26 13:45 README3 LData := FixBonkedYear(LData); //we do this in case there's a space LTmp := Fetch(LData); if (Length(LTmp) > 3) and IsNumeric(LTmp) then begin //must be a year wYear := IndyStrToInt(LTmp, wYear); LTmp := Fetch(LData); end; LData := TrimLeft(LData); // HPUX can output the dates like "28. Jan., 16:48", "5. Mai, 05:34" or // "7. Nov. 2004" if TextEndsWith(LTmp, '.') then begin Delete(LTmp, Length(LTmp), 1); end; // Korean listings will have the Korean "month" character DeleteSuffix(LTmp,KoreanMonth); // Just in case DeleteSuffix(LTmp,KoreanEUCMonth); { if IndyPos(KoreanMonth, LTmp) = Length(LTmp) - Length(KoreanMonth) + 1 then begin Delete(LTmp, Length(LTmp) - Length(KoreanMonth) + 1, Length(KoreanMonth)); end; // Japanese listings will have the Japanese "month" character } DeleteSuffix(LTmp,JapaneseMonth); if IsNumeric(LTmp) then begin wMonth := IndyStrToInt(LTmp, wMonth); // HPUX LTmp := Fetch(LData, ' ', False); if TextEndsWith(LTmp, ',') then begin Delete(LTmp, Length(LTmp), 1); end; if TextEndsWith(LTmp, '.') then begin Delete(LTmp, Length(LTmp), 1); end; // Handle dates where the day preceeds a string month (French, Dutch) i := StrToMonth(LTmp); if i > 0 then begin wDay := wMonth; LTmp := Fetch(LData); LData := TrimLeft(LData); wMonth := i; LStep := pusYear; end else begin if wMonth > 12 then begin wDay := wMonth; LTmp := Fetch(LData); LData := TrimLeft(LData); wMonth := IndyStrToInt(LTmp, wMonth); LStep := pusYear; end else begin LStep := pusDay; end; end; end else begin wMonth := StrToMonth(LTmp); LStep := pusDay; // Korean listings can have dates in the form "2004.10.25" if wMonth = 0 then begin wYear := IndyStrToInt(Fetch(LTmp, '.'), wYear); wMonth := IndyStrToInt(Fetch(LTmp, '.'), 0); wDay := IndyStrToInt(LTmp); LStep := pusName; end; end; end; pusDay: begin // Scan DD LTmp := Fetch(LData); LData := TrimLeft(LData); // Korean dates can have their "Day" character as included { if IndyPos(KoreanDay, LTmp) = Length(LTmp) - Length(KoreanDay) + 1 then begin Delete(LTmp, Length(LTmp) - Length(KoreanDay) + 1, Length(KoreanDay)); end; } DeleteSuffix(LTmp,KoreanDay); //Ditto for Japanese DeleteSuffix(LTmp,JapaneseDay); wDay := IndyStrToInt(LTmp, wDay); LStep := pusYear; end; pusYear: begin LTmp := Fetch(LData); //Some localized Japanese listings include a year sybmol DeleteSUffix(LTmp,JapaneseYear); // Not time info, scan year if IndyPos(':', LTmp) = 0 then begin {Do not Localize} wYear := IndyStrToInt(LTmp, wYear); // Set time info to 00:00:00.999 wHour := 0; wMin := 0; wSec := 0; wMSec := 999; LStep := pusName; end else begin // Time info, scan hour, min LStep := pusTime; end; end; pusTime: begin // correct year and Scan hour wYear := AddMissingYear(wDay, wMonth); wHour:= IndyStrToInt(Fetch(LTmp, ':'), 0); {Do not Localize} // Set sec and ms to 0.999 except for Serv-U or FreeBSD with the -T parameter //with the -T parameter, Serve-U returns something like this: // //drwxrwxrwx 1 user group 0 Mar 3 04:49:59 2003 upload // //instead of: // //drwxrwxrwx 1 user group 0 Mar 3 04:49 upload if (IndyPos(':', LTmp) > 0) and (IsNumeric(Fetch(LData, ' ', False))) then begin {Do not localize} // Scan minutes wMin := IndyStrToInt(Fetch(LTmp, ':'), 0); {Do not localize} wSec := IndyStrToInt(Fetch(LTmp, ':'), 0); {Do not localize} wMSec := IndyStrToInt(Fetch(LTmp,':'), 999); {Do not localize} LTmp := Fetch(LData); wYear := IndyStrToInt(LTmp, wYear); end else begin // Scan minutes wMin := IndyStrToInt(Fetch(LTmp, ':'), 0); {Do not localize} wSec := IndyStrToInt(Fetch(LTmp, ':'), 0); {Do not localize} wMSec := IndyStrToInt(Fetch(LTmp), 999); end; LStep := pusName; end; pusName: begin LName := LData; LStep := pusDone; end; end;//case LStep until LStep = pusDone; AItem.ItemType := ditFile; if LDir <> '' then begin case LDir[1] of 'D' : AItem.ItemType := ditDirectory; {Do not Localize} 'L' : AItem.ItemType := ditSymbolicLink; {Do not Localize} 'B' : AItem.ItemType := ditBlockDev; {Do not Localize} 'C' : AItem.ItemType := ditCharDev; {Do not Localize} 'P' : AItem.ItemType := ditFIFO; {Do not Localize} 'S' : AItem.ItemType := ditSocket; {Do not Localize} end; end; LI.UnixOwnerPermissions := LOPerm; LI.UnixGroupPermissions := LGPerm; LI.UnixOtherPermissions := LUPerm; LI.LinkCount := IndyStrToInt(LCount, 0); LI.OwnerName := LOwner; LI.GroupName := LGroup; LI.Size := IndyStrToInt64(LSize, 0); if (wMonth = 2) and (wDay = 29) and (not IsLeapYear(wYear)) then begin {temporary workaround for Leap Year, February 29th. Encode with day - 1, but do NOT decrement wDay since this will give us the wrong day when we adjust/re-calculate the date later} LI.ModifiedDate := EncodeDate(wYear, wMonth, wDay - 1) + EncodeTime(wHour, wMin, wSec, wMSec); end else begin LI.ModifiedDate := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMin, wSec, wMSec); end; {PATCH: If Indy incorrectly decremented the year then it will be almost a year behind. Certainly well past 90 days and so we will have the day and year in the raw data. (Files that are from within the last 90 days do not show the year as part of the date.)} wdayStr := IntToStr(wDay); while Length(wDayStr) < 2 do begin wDayStr := '0' + wDayStr; {do not localize} end; DecodeDate(Now, wCurrYear, wCurrMonth, wCurrDay); if (wYear < wCurrYear) and ((Now-LI.ModifiedDate) > 90) and (Pos(IntToStr(wMonth) + ' ' + IntToStr(wYear), LI.Data) = 0) and (Pos(IntToStr(wMonth) + ' ' + wDayStr + ' ' + IntToStr(wYear), LI.Data) = 0) and (Pos(monthNames[wMonth] + ' ' + IntToStr(wYear), LI.Data) = 0) and (Pos(monthNames[wMonth] + ' ' + wDayStr + ' ' + IntToStr(wYear), LI.Data) = 0) then begin {sanity check to be sure we aren't making future dates!!} {$IFDEF VCL_6_OR_ABOVE} if IncYear(LI.ModifiedDate) <= (Now + 7) then {$ELSE} if IncMonth(LI.ModifiedDate,12) <= (Now + 7) then {$ENDIF} begin Inc(wYear); LI.ModifiedDate := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMin, wSec, wMSec); end; end; if LI.ItemType = ditSymbolicLink then begin i := IndyPos(UNIX_LINKTO_SYM, LName); LLinkTo := Copy(LName, i + 4, Length(LName) - i - 3); LName := Copy(LName, 1, i - 1); //with ls -F (DIR -F in FTP, you will sometimes symbolic links with the linked //to item file name ending with a /. That indicates that the item being pointed to //is a directory if TextEndsWith(LLinkTo, PATH_FILENAME_SEP_UNIX) then begin LI.ItemType := ditSymbolicLinkDir; LLinkTo := Copy(LLinkTo, 1, Length(LLinkTo)-1); end; LI.LinkedItemName := LLinkTo; end; LI.NumberBlocks := IndyStrToInt(LBlocks, 0); LI.Inode := IndyStrToInt(LInode, 0); //with servers using ls -F, / is returned after the name of dir names and a * //will be returned at the end of a file name for an executable program. //Based on info at http://www.skypoint.com/help/tipgettingaround.html //Note that many FTP servers obtain their DIR lists by piping output from the /bin/ls -l command. //The -F parameter does work with ftp.netscape.com and I have also tested a NcFTP server //which simulates the output of the ls command. if CharIsInSet(LName, Length(LName), PATH_FILENAME_SEP_UNIX + '*') then begin {Do not localize} LName := Copy(LName, 1, Length(LName)-1); end; if APath <> '' then begin // a path can sometimes come into the form of: // pub: // or // ./pub // //Deal with both cases LI.LocalFileName := LName; LName := APath + PATH_FILENAME_SEP_UNIX + LName; if TextStartsWith(LName, UNIX_CURDIR) then begin IdDelete(LName, 1, Length(UNIX_CURDIR)); if TextStartsWith(LName, PATH_FILENAME_SEP_UNIX) then begin IdDelete(LName, 1, Length(PATH_FILENAME_SEP_UNIX)); end; end; end; LI.FileName := LName; Result := True; end; class function TIdFTPLPUnix.ParseListing(AListing: TStrings; ADir: TIdFTPListItems): Boolean; var i : Integer; LPathSpec : String; LItem : TIdFTPListItem; begin for i := 0 to AListing.Count-1 do begin if not ((AListing[i] = '') or IsTotalLine(AListing[i]) or IsUnixLsErr(AListing[i]) or IsUnitreeBanner(AListing[i])) then begin //workaround for the XBox MediaCenter FTP Server //which returns something like this: // //dr-xr-xr-x 1 ftp ftp 1 Feb 23 00:00 D: //and the trailing : is falsely assuming that a ":" means //a subdirectory entry in a recursive list. if (not InternelChkUnix(AListing[i])) and IsSubDirContentsBanner(AListing[i]) then begin LPathSpec := Copy(AListing[i], 1, Length(AListing[i])-1); end else begin LItem := MakeNewItem(ADir); LItem.Data := AListing[i]; Result := ParseLine(LItem, LPathSpec); if not Result then begin FreeAndNil(LItem); Exit; end; end; end; end; Result := True; end; { TIdFTPLPUnitree } class function TIdFTPLPUnitree.GetIdent: String; begin Result := UNITREE; end; class function TIdFTPLPUnitree.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdUnitreeFTPListItem.Create(AOwner); end; initialization RegisterFTPListParser(TIdFTPLPUnix); RegisterFTPListParser(TIdFTPLPUnitree); finalization UnRegisterFTPListParser(TIdFTPLPUnix); UnRegisterFTPListParser(TIdFTPLPUnitree); end.
unit xCtrls; interface uses SysUtils, Classes, Controls, Forms, Messages, Graphics, Windows, Contnrs; var Delims: set of char = [' ']; type TxLabelExClickEvent = procedure (Sender: TObject; Index: Integer) of object; TxOnGetHintTextEvent = procedure (Sender: TObject; Index: Integer; var AText: string) of object; TxLabelEx = class; TxRgnType = (rgtRect); TxRegion = class private FRect: TRect; FHandle: HRGN; FType: TxRgnType; public procedure Add(ARect: TRect); constructor CreateRectRgn(ARect: TRect); virtual; destructor Destroy; override; function PointInRegion(const X, Y: Integer): Boolean; property Handle: HRGN read FHandle; property Rect: TRect read FRect; end; TxLabItem = class private FRegion: TxRegion; FCaption: TCaption; FActive: Boolean; FLabel: TxLabelEx; procedure SetActive(const Value: Boolean); public constructor Create(ACaption: string; AParent: TxLabelEx); virtual; destructor Destroy; override; procedure CreateRegion(ARect: TRect); property Region: TxRegion read FRegion; property Caption: TCaption read FCaption write FCaption; property Active: Boolean read FActive write SetActive; end; TxLabelEx = class(TGraphicControl) private FAlignment: TAlignment; FCaptions: TStrings; FHotTrack: Boolean; FHotTrackColor: TColor; FList: TObjectList; FOnItemClick: TxLabelExClickEvent; FTransparent: Boolean; FAutoSize: Boolean; FInResize: Boolean; FCurrItem: TxLabItem; FOnGetHintText: TxOnGetHintTextEvent; procedure SetAlignment(const Value: TAlignment); procedure SetCaptions(const Value: TStrings); procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure SetHotTrack(const Value: Boolean); procedure SetHotTrackColor(const Value: TColor); function GetItem(Index: Integer): TxLabItem; procedure CaptionsChange(Sender: TObject); procedure SetTransparent(const Value: Boolean); procedure SetAutoSize(const Value: Boolean); reintroduce; procedure DoAutoResize; protected FOver: Boolean; procedure Paint; override; procedure Loaded; override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Click; override; procedure Resize; override; procedure ResetRegions; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ResetItems; virtual; property Items[Index: Integer]: TxLabItem read GetItem; published property Anchors; property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property Captions: TStrings read FCaptions write SetCaptions; property Color; property Font; property HotTrack: Boolean read FHotTrack write SetHotTrack default True; property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor default clBlue; property ShowHint; property Transparent: Boolean read FTransparent write SetTransparent default True; property OnItemClick: TxLabelExClickEvent read FOnItemClick write FOnItemClick; property OnGetHintText: TxOnGetHintTextEvent read FOnGetHintText write FOnGetHintText; end; implementation uses Types, xStrUtils; //uses Windows; procedure TxLabelEx.CaptionsChange(Sender: TObject); begin ResetItems; end; procedure TxLabelEx.Click; var i: Integer; begin inherited; if Assigned(FOnItemClick) then begin for i := 0 to FList.Count - 1 do if Items[i].Active then begin FOnItemClick(Self, i); Exit; end; end; end; procedure TxLabelEx.CMMouseEnter(var Message: TMessage); var i: Integer; begin FOver := True; for i := 0 to FList.Count - 1 do Items[i].Active := False; if FHotTrack and not (csDesigning in ComponentState) then Cursor := crHandPoint; end; procedure TxLabelEx.CMMouseLeave(var Message: TMessage); var i: Integer; begin FOver := False; for i := 0 to FList.Count - 1 do Items[i].Active := False; FCurrItem := nil; end; constructor TxLabelEx.Create(AOwner: TComponent); begin inherited; FCaptions := TStringList.Create; (FCaptions as TStringList).OnChange := CaptionsChange; FHotTrack := True; FHotTrackColor := clBlue; FTransparent := True; FList := TObjectList.Create; Height := 13; Width := 100; end; destructor TxLabelEx.Destroy; begin FCaptions.Free; FList.Free; inherited; end; procedure TxLabelEx.DoAutoResize; var R: TRect; Flags: Longint; S: string; begin FInResize := True; try S := DelCharsEx(FCaptions.Text, [#10, #13]); R := Self.ClientRect; R.Right := R.Left + Screen.Width; with Self.Canvas do begin Font := Self.Font; Flags := DT_CALCRECT or DT_EXPANDTABS; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(S), -1, R, Flags); end; Self.Width := R.Right - R.Left; finally FInResize := False; end; end; function TxLabelEx.GetItem(Index: Integer): TxLabItem; begin Result := TxLabItem(FList[Index]); end; procedure TxLabelEx.Loaded; begin inherited; ResetItems; end; procedure TxLabelEx.MouseMove(Shift: TShiftState; X, Y: Integer); var i: Integer; FTxt: string; begin inherited; for i := 0 to FList.Count - 1 do if Items[i].Region.PointInRegion(X, Y) then begin Items[i].Active := True; if ShowHint and (FCurrItem <> Items[i]) then begin Application.CancelHint; FTxt := ''; if Assigned(FOnGetHintText) then FOnGetHintText(Self, i, FTxt); if FTxt <> '' then Self.Hint := FTxt; FCurrItem := Items[i]; end; end else Items[i].Active := False; // Invalidate; end; procedure TxLabelEx.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var R, RR: TRect; Flags: Longint; S, SS, SrcS: string; i, j: Integer; X, Y, TW, TWW, TH, C, WIndex: Integer; FDone: Boolean; procedure LocalDrawText(ACanvas: TCanvas; const AText: string; R: TRect; AItem: TxLabItem); begin with ACanvas do begin if FOver and AItem.Active and FHotTrack then Font.Color := FHotTrackColor else Font.Color := Self.Font.Color; Flags := DT_EXPANDTABS or DT_VCENTER or Alignments[taLeftJustify]; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(AText), -1, R, Flags); end; end; begin R := ClientRect; with Canvas do begin if not FTransparent then begin Brush.Color := Self.Color; FillRect(R); end; Font := Self.Font; Brush.Style := bsClear; S := 'T'; X := 0; Y := 0; R := Self.ClientRect; Flags := DT_CALCRECT or DT_EXPANDTABS; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(S), -1, R, Flags); TH := R.Bottom - R.Top; for i := 0 to FList.Count - 1 do begin FDone := False; SrcS := Items[i].Caption; while not FDone do begin C := WordCount(Trim(SrcS), Delims); TW := TextWidth(SrcS); if X + TW <= Self.ClientRect.Right then begin RR.Left := X; RR.Top := Y; RR.Right := X + TW; RR.Bottom := Y + TH; LocalDrawText(Canvas, SrcS, RR, Items[i]); X := X + TW; FDone := True; Break; end else begin if (C = 1) and (X = 0) then begin FDone := True; Break; end; SS := ''; for j := C downto 1 do begin if (C = 1) then begin X := 0; Y := Y + TH; Break; end; if SS = '' then SS := ExtractWord(j, SrcS, Delims) + ' ' else SS := ExtractWord(j, SrcS, Delims) + ' ' + SS; S := Copy(SrcS, 1, Length(SrcS) - Length(SS)); TWW := TextWidth(S); if (X + TWW <= Self.ClientRect.Right) then begin //влезла RR.Left := X; RR.Top := Y; RR.Right := X + TWW; RR.Bottom := Y + TH; LocalDrawText(Canvas, S, RR, Items[i]); X := 0; Y := Y + TH; SrcS := SS; Break; end end; //for j end; end; //while end; //for i end; end; procedure TxLabelEx.ResetItems; var i: Integer; begin FList.Clear; for i := 0 to FCaptions.Count - 1 do FList.Add(TxLabItem.Create(FCaptions[i], Self)); if FAutoSize then DoAutoResize; ResetRegions; Invalidate; end; procedure TxLabelEx.ResetRegions; var i, j, C: Integer; S, SrcS, SS: string; R, RR: TRect; X, Y, TW, TWW, TH: Integer; FDone: Boolean; Flags: Longint; begin S := ''; with Canvas do begin Font := Self.Font; { XL := 0; YL := 0; XB := 0; YB := 0; for i := 0 to FList.Count - 1 do begin R := Self.ClientRect; TW := TextWidth(Items[i].Caption); XB := XB + TW; YB := R.Bottom - R.Top; Items[i].CreateRegion(Rect(XL, YL, XB, YB)); XL := XL + TW; end;} S := 'T'; X := 0; Y := 0; R := Self.ClientRect; Flags := DT_CALCRECT or DT_EXPANDTABS; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(S), -1, R, Flags); TH := R.Bottom - R.Top; for i := 0 to FList.Count - 1 do begin Items[i].CreateRegion(Rect(0, 0, 0, 0)); FDone := False; SrcS := Items[i].Caption; while not FDone do begin C := WordCount(Trim(SrcS), Delims); TW := TextWidth(SrcS); if X + TW <= Self.ClientRect.Right then begin RR.Left := X; RR.Top := Y; RR.Right := X + TW; RR.Bottom := Y + TH; Items[i].Region.Add(RR); X := X + TW; FDone := True; Break; end else begin if (C = 1) and (X = 0) then begin FDone := True; Break; end; SS := ''; for j := C downto 1 do begin if (C = 1) then begin X := 0; Y := Y + TH; Break; end; if SS = '' then SS := ExtractWord(j, SrcS, Delims) + ' ' else SS := ExtractWord(j, SrcS, Delims) + ' ' + SS; S := Copy(SrcS, 1, Length(SrcS) - Length(SS)); TWW := TextWidth(S); if (X + TWW <= Self.ClientRect.Right) then begin //влезла RR.Left := X; RR.Top := Y; RR.Right := X + TWW; RR.Bottom := Y + TH; Items[i].Region.Add(RR); X := 0; Y := Y + TH; SrcS := SS; Break; end end; //for j end; end; //while end; //for i end; end; procedure TxLabelEx.Resize; begin inherited; if FAutoSize and not FInResize then DoAutoResize; if Assigned(Parent) then ResetRegions; end; procedure TxLabelEx.SetAlignment(const Value: TAlignment); begin FAlignment := Value; Invalidate; end; procedure TxLabelEx.SetAutoSize(const Value: Boolean); begin FAutoSize := Value; DoAutoResize; end; procedure TxLabelEx.SetCaptions(const Value: TStrings); begin FCaptions.Assign(Value); ResetItems; end; procedure TxLabelEx.SetHotTrack(const Value: Boolean); begin FHotTrack := Value; Invalidate; end; procedure TxLabelEx.SetHotTrackColor(const Value: TColor); begin FHotTrackColor := Value; Invalidate; end; { TxRegion } procedure TxRegion.Add(ARect: TRect); var FH: HRGN; begin FH := CreateRectRgnIndirect(ARect); CombineRgn(FHandle, FH, FHandle, RGN_OR); DeleteObject(FH); end; constructor TxRegion.CreateRectRgn(ARect: TRect); begin FRect := ARect; FHandle := CreateRectRgnIndirect(ARect); FType := rgtRect; end; destructor TxRegion.Destroy; begin DeleteObject(FHandle); inherited; end; function TxRegion.PointInRegion(const X, Y: Integer): Boolean; begin Result := PtInRegion(FHandle, X, Y); end; { TxLabItem } constructor TxLabItem.Create(ACaption: string; AParent: TxLabelEx); begin Caption := ACaption; FLabel := AParent; end; procedure TxLabItem.CreateRegion(ARect: TRect); begin if Assigned(FRegion) then FRegion.Free; FRegion := TxRegion.CreateRectRgn(ARect); end; destructor TxLabItem.Destroy; begin if Assigned(FRegion) then FreeAndNil(FRegion); inherited; end; procedure TxLabItem.SetActive(const Value: Boolean); begin if FActive <> Value then begin FActive := Value; FLabel.Invalidate; end; end; procedure TxLabelEx.SetTransparent(const Value: Boolean); begin FTransparent := Value; Invalidate; end; end.
unit csInterfaces; interface uses Classes, ActiveX, ddProgressObj, ddAppConfigTypes, csRequestTypes, DT_Types; type IcsRequest = interface(IInterface) ['{1FC5B642-EAEA-423C-9404-08DE415C3E15}'] procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); function pm_GetData: TddAppConfigNode; stdcall; function pm_GetDate: TDateTime; stdcall; function pm_GetDescription: string; stdcall; function pm_GetIndex: LongInt; stdcall; function pm_GetOnChange: TcsRequestNotifyEvent; stdcall; function pm_GetPriority: Integer; stdcall; function pm_GetTaskFolder: string; stdcall; function pm_GetTaskID: ShortString; function pm_GetTaskType: TcsRequestType; stdcall; function pm_GetUserID: TUserID; stdcall; function pm_GetVersion: Integer; stdcall; procedure pm_SetDescription(const Value: string); stdcall; procedure pm_SetIndex(const Value: LongInt); stdcall; procedure pm_SetOnChange(const Value: TcsRequestNotifyEvent); stdcall; procedure pm_SetPriority(const Value: Integer); stdcall; procedure pm_SetTaskFolder(const Value: string); procedure pm_SetTaskType(const Value: TcsRequestType); stdcall; procedure pm_SetUserID(const Value: TUserID); stdcall; procedure pm_SetVersion(const Value: Integer); stdcall; procedure SaveTo(aStream: TStream; aIsPipe: Boolean); property Data: TddAppConfigNode read pm_GetData; property Date: TDateTime read pm_GetDate; property Description: string read pm_GetDescription write pm_SetDescription; property Index: LongInt read pm_GetIndex write pm_SetIndex; property Priority: Integer read pm_GetPriority write pm_SetPriority; property TaskFolder: string read pm_GetTaskFolder write pm_SetTaskFolder; property TaskID: ShortString read pm_GetTaskID; property TaskType: TcsRequestType read pm_GetTaskType write pm_SetTaskType; property UserID: TUserID read pm_GetUserID write pm_SetUserID; property Version: Integer read pm_GetVersion write pm_SetVersion; property OnChange: TcsRequestNotifyEvent read pm_GetOnChange write pm_SetOnChange; end; type IcsRequestHandler = interface(IInterface) ['{CF36C1D7-4075-4521-A385-E570D30478E4}'] procedure Abort; stdcall; function DoHandle(aRequest: IcsRequest; aProgressor: TddProgressObject): Boolean; stdcall; procedure WriteResult(aStream: IStream); stdcall; end; implementation end.
{***** THIS IS NOT THE handout program for Assignment #8 *****} {***** this is just a portion of the handout program *****} {***** that you should bring to class Monday, March 15 *****} program simulator (input,output) ; { the following constants give symbolic names for the opcodes } const lda = 91 ; { Load Accumulator from memory } sta = 39 ; { Store Accumulator into memory } cla = 08 ; { Clear (set to zero) the Accumulator } inc = 10 ; { Increment (add 1 to) the Accumulator } add = 99 ; { Add to Accumulator } sub = 61 ; { Subtract from Accumulator } jmp = 15 ; { Jump ("go to") } jz = 17 ; { Jump if the Zero status bit is TRUE } jn = 19 ; { Jump if the Negative status bit is TRUE } dsp = 01 ; { Display (write on the screen) } hlt = 64 ; { Halt } type byte = -99..99 ; word = 0000..9999 ; bit = boolean ; var memory: array[word] of byte ; { the following are the registers in the CPU } pc: word ; { program counter } a: byte ; { accumulator } opCode: byte ; { the opcode of the current instruction } opAddr: word ; { the operand of the current instruction - it is always an address } z: bit ; { "Zero" status bit } n: bit ; { "Negative" status bit } h: bit ; { "Halt" status bit } mar: word ; { Memory Address register } mdr: byte ; { Memory Data register } rw: bit ; { Read/Write bit. Read = True; Write = False } { Loads a machine language program into memory starting at location 0 } { *** NOTE: assumes a line does not contain any TRAILING blanks. } procedure load ; var address: word ; first_character, ch: char ; inputfile : string ; progfile : text ; BEGIN writeln('Enter the name of the file with the program.') ; readln(inputfile) ; assign(progfile, inputfile) ; reset(progfile) ; address := 0 ; while not EOF(progfile) do BEGIN if not eoln(progfile) then BEGIN read(progfile, first_character); if first_character <> ' ' then { non-blank indicates a comment } repeat { skip over comment } read(progfile, ch) until ch = first_character ; while not eoln(progfile) do BEGIN read(progfile, memory[address]) ; address := address + 1 END { while not eoln } END; { if not eoln } readln(progfile) END; { while not eof } close(progfile) END; { proc load } procedure access_memory ; BEGIN if rw then mdr := memory[mar] { TRUE = read = copy a value from memory into the CPU } else memory[mar] := mdr { FALSE = write = copy a value into memory from the CPU } END ; procedure run ; { This implements the Fetch-Execute cycle } BEGIN pc := 0 ; { always start execution at location 0 } h := false ; { reset the Halt status bit } REPEAT { FETCH OPCODE } mar := pc ; pc := pc + 1 ; { NOTE that pc is incremented immediately } rw := true ; access_memory ; opCode := mdr ; { If the opcode is odd, it needs an operand. FETCH THE ADDRESS OF THE OPERAND } if (opCode mod 2) = 1 then BEGIN mar := pc ; pc := pc + 1 ; { NOTE that pc is incremented immediately } rw := true ; access_memory ; opAddr := mdr ; { this is just the HIGH byte of the opAddr } mar := pc ; pc := pc + 1 ; { NOTE that pc is incremented immediately } rw := true ; access_memory ; { this gets the LOW byte } opAddr := 100*opAddr + mdr { put the two bytes together } END; { if } { EXECUTE THE OPERATION } case opCode of lda: begin mar := opAddr ; { Get the Operand's value from memory } rw := true ; access_memory ; a := mdr { and store it in the Accumulator } end; sta: begin mar := opAddr ; { Get the memory address of the location to store the value } rw := false ; mdr := a ; { Store the value of the Accumulator in the MDR } access_memory { Transfer the MDR value to memory } end; cla: begin a := 0 ; { set a to zero } z := (a = 0) ; { set the Status Bits appropriately } n := (a < 0) end; inc: begin a := a + 1 ; { increment a } z := (a = 0) ; { set the Status Bits appropriately } n := (a < 0) end; add: begin mar := opAddr ; { Get the Operand's value from memory } rw := true ; access_memory ; a := (a + mdr) mod 100 ; { and add it to the Accumulator } z := (a = 0) ; { set the Status Bits appropriately } n := (a < 0) end; sub: begin mar := opAddr ; { Get the Operand's value from memory } rw := true ; access_memory ; a := (a - mdr) mod 100 ; { and subtract it from the Accumulator } z := (a = 0) ; { set the Status Bits appropriately } n := (a < 0) end; jmp : pc := opAddr ; { jump to the instruction at opAddr } jz : if z then pc := opAddr ; { if the Z status bit is true then the next instruction to execute is at address opAddr } jn : if n then pc := opAddr ; { if the N status bit is true then the next instruction to execute is at address opAddr } hlt: h := true ; { set the Halt status bit } dsp: begin mar := opAddr ; { Get the Operand's value from memory } rw := true ; access_memory ; writeln('memory location ', mar:5, ' contains the value ', mdr:3) end end { case } UNTIL h { continue the Fetch-Execute cycle until Halt bit is set } END; { proc run } BEGIN { main program } load ; run ; writeln('PROGRAM ENDED.') END.
unit WinSockRDOConnectionsServer; interface uses Windows, Classes, SyncObjs, SmartThreads, SocketComp, RDOInterfaces; type TWinSockRDOConnectionsServer = class( TInterfacedObject, IRDOServerConnection, IRDOConnectionsServer ) public constructor Create( Prt : integer; QuearyThrPrior : TThreadPriority = tpNormal); destructor Destroy; override; protected // IRDOServerConnection procedure SetQueryServer( const QueryServer : IRDOQueryServer ); function GetMaxQueryThreads : integer; procedure SetMaxQueryThreads( MaxQueryThreads : integer ); protected // IRDOConnectionsServer procedure StartListening; procedure StopListening; function GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection; function GetClientConnectionById( Id : integer ) : IRDOConnection; procedure InitEvents( const EventSink : IRDOConnectionServerEvents ); private procedure ClientConnected( Sender : TObject; Socket : TCustomWinSocket ); procedure ClientDisconnected( Sender : TObject; Socket : TCustomWinSocket ); procedure DoClientRead( Sender : TObject; Socket : TCustomWinSocket ); procedure HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); procedure RemoveQuery(Socket : TCustomWinSocket); function GetStuckQueries : string; private fQueryServer : IRDOQueryServer; fSocketComponent : TServerSocket; fMsgLoopThread : TSmartThread; fEventSink : IRDOConnectionServerEvents; fQueryQueue : TList; fQueryWaiting : THandle; fQueryQueueLock : TCriticalSection; fMaxQueryThreads : integer; fQueryThreads : TList; fTerminateEvent : THandle; fLabel : string; fThreadPriority : TThreadPriority; public property theLabel : string read fLabel write fLabel; end; const MaxDebugServers = 5; MaxQueryLength = 1024*1024; // 1 Mb var DebugServers : array[0..MaxDebugServers] of TWinSockRDOConnectionsServer; ServerCount : integer = 0; implementation uses SysUtils, Messages, ActiveX, WinSock, RDOProtocol, RDOUtils, {$IFDEF LogsEnabled} LogFile, {$ENDIF} Logs, ErrorCodes, RDOQueryServer, WinSockRDOServerClientConnection; const QUERY_COUNT_ENQUIRE = 'GetQueryCount;'; type TSocketWrap = class(TInterfacedObject, IWinSocketWrap) public constructor Create(aSocket : TCustomWinSocket); destructor Destroy; override; public function isValid : boolean; function getSocket : TCustomWinSocket; function getConnection : IRDOConnection; function getConnectionData : pointer; procedure setConnectionData(info : pointer); procedure Invalidate; procedure Lock; procedure Unlock; private fSocket : TCustomWinSocket; fLock : TCriticalSection; end; type TSocketData = record RDOConnection : IRDOConnection; Buffer : string; Owner : IWinSocketWrap; Data : pointer; end; PSocketData = ^TSocketData; type TQueryToService = record Valid : boolean; Text : string; //Socket : TCustomWinSocket; Socket : IWinSocketWrap; end; PQueryToService = ^TQueryToService; type TQueryThread = class( TSmartThread ) private fConnectionsServer : TWinSockRDOConnectionsServer; fLock : TCriticalSection; fQueryToService : PQueryToService; fStatus : integer; fQueryStatus : integer; fRDOCallCnt : integer; fExecClientSocket : IWinSocketWrap; public constructor Create( theConnServer : TWinSockRDOConnectionsServer; Prior : TThreadPriority); destructor Destroy; override; procedure Execute; override; public procedure Lock; procedure Unlock; procedure CheckQuery(Socket : TCustomWinSocket); public property TheLock : TCriticalSection read fLock; public procedure Dispatch(var Message); override; end; type TMsgLoopThread = class( TSmartThread ) private fRDOConnServ : TWinSockRDOConnectionsServer; public constructor Create(RDOConnServ : TWinSockRDOConnectionsServer; Prior : TThreadPriority); procedure Execute; override; end; // TSocketWrap constructor TSocketWrap.Create(aSocket : TCustomWinSocket); begin inherited Create; fSocket := aSocket; fLock := TCriticalSection.Create; end; destructor TSocketWrap.Destroy; begin fLock.Free; inherited; end; function TSocketWrap.isValid : boolean; begin Lock; try result := fSocket <> nil; finally Unlock; end; end; function TSocketWrap.getSocket : TCustomWinSocket; begin Lock; try result := fSocket; finally Unlock; end; end; function TSocketWrap.getConnection : IRDOConnection; begin Lock; try if (fSocket <> nil) and (fSocket.Data <> nil) then result := PSocketData(fSocket.Data).RDOConnection else result := nil; finally Unlock; end; end; function TSocketWrap.getConnectionData : pointer; begin Lock; try if (fSocket <> nil) and (fSocket.Data <> nil) then result := PSocketData(fSocket.Data).Data else result := nil; finally Unlock; end; end; procedure TSocketWrap.setConnectionData(info : pointer); begin Lock; try if (fSocket <> nil) and (fSocket.Data <> nil) then PSocketData(fSocket.Data).Data := info; finally Unlock; end; end; procedure TSocketWrap.Invalidate; begin Lock; try fSocket := nil; finally Unlock; end; end; procedure TSocketWrap.Lock; begin fLock.Enter; end; procedure TSocketWrap.Unlock; begin fLock.Leave; end; // TQueryThread constructor TQueryThread.Create(theConnServer : TWinSockRDOConnectionsServer; Prior : TThreadPriority); begin inherited Create( true ); fConnectionsServer := theConnServer; fLock := TCriticalSection.Create; Priority := Prior; Resume; end; destructor TQueryThread.Destroy; begin Terminate; WaitFor; fLock.Free; inherited; end; procedure TQueryThread.Execute; var QueryResult : string; QueryText : string; Sckt : integer; QueryThreadEvents : array [ 1 .. 2 ] of THandle; WaitRes : integer; WinSock : TCustomWinSocket; begin CoInitialize(nil); try with fConnectionsServer do begin QueryThreadEvents[ 1 ] := fQueryWaiting; QueryThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do try fStatus := 1; {1} WaitRes := WaitForMultipleObjects( 2, @QueryThreadEvents[ 1 ], false, INFINITE ); fStatus := 2; {2} if WaitRes = WAIT_OBJECT_0 + 1 then Terminate; if not Terminated and (WaitRes = WAIT_OBJECT_0) then begin fQueryQueueLock.Acquire; fStatus := 3; {3} try if fQueryQueue.Count <> 0 then begin fQueryToService := fQueryQueue[ 0 ]; fQueryQueue.Delete( 0 ); end else begin fQueryToService := nil; ResetEvent( fQueryWaiting ); end finally fQueryQueueLock.Release end; // Catch the query fStatus := 4; {4} Lock; fStatus := 5; {5} try if (fQueryToService <> nil) and fQueryToService.Valid then begin QueryText := fQueryToService.Text; Sckt := integer(fQueryToService.Socket.getSocket); fExecClientSocket := fQueryToService.Socket; end else begin QueryText := ''; Sckt := 0; fExecClientSocket := nil; end; finally Unlock; end; fStatus := 6; {6} // Check if there is something to excecute if QueryText <> '' then begin // Execute the query try QueryResult := fQueryServer.ExecQuery(QueryText, Sckt, fQueryStatus, fRDOCallCnt); fExecClientSocket := nil; except QueryResult := ''; end; // Check result if QueryResult = '' then begin {$IFDEF LogsEnabled} LogThis( 'No result' ); {$ENDIF} end else begin // Check if can send result back fStatus := 7; {7} Lock; try fStatus := 8; {8} if (fQueryToService <> nil) and fQueryToService.Valid and fQueryToService.Socket.isValid then try fQueryToService.Socket.Lock; try WinSock := fQueryToService.Socket.getSocket; if WinSock <> nil then WinSock.SendText( AnswerId + QueryResult ); // >> ?? finally fQueryToService.Socket.Unlock; end; {$IFDEF LogsEnabled} LogThis( 'Result : ' + QueryResult ); {$ENDIF} except {$IFDEF LogsEnabled} LogThis( 'Error sending query result' ) {$ENDIF} end; finally Unlock; end; end; // Free the Query fStatus := 9; {9} Lock; fStatus := 10; {10} try if fQueryToService <> nil then begin fQueryToService.Socket := nil; Dispose( fQueryToService ); fQueryToService := nil; end finally Unlock; end; end; end; except {$IFDEF USELogs} Logs.Log('Survival', DateTimeToStr(Now) + 'Un handled exception in the Servicing Query Thread loop! Status: ' + IntToStr(fStatus) + ' ' + QueryText) {$ENDIF} end; end finally CoUninitialize; end; end; procedure TQueryThread.Lock; begin fLock.Enter; end; procedure TQueryThread.Unlock; begin fLock.Leave; end; procedure TQueryThread.CheckQuery(Socket : TCustomWinSocket); begin Lock; try //if (fQueryToService <> nil) and (fQueryToService.Socket = Socket) //then fQueryToService.Valid := false; // lockear finally Unlock; end; end; procedure TQueryThread.Dispatch(var Message); var msg : TMessage absolute Message; begin case msg.msg of MSG_GETTHREADDATA : begin if fExecClientSocket <> nil then msg.Result := integer(fExecClientSocket.getConnectionData) else msg.Result := integer(nil); end; MSG_SETTHREADDATA : begin if fExecClientSocket <> nil then fExecClientSocket.setConnectionData(pointer(msg.LParam)) end; else inherited Dispatch(Message); end; end; // TMsgLoopThread constructor TMsgLoopThread.Create(RDOConnServ : TWinSockRDOConnectionsServer; Prior : TThreadPriority); begin inherited Create( true ); fRDOConnServ := RDOConnServ; Priority := Prior; Resume; end; procedure TMsgLoopThread.Execute; var Msg : TMsg; alive : boolean; begin with fRDOConnServ do begin try with fSocketComponent do if not Active then Active := true except {$IFDEF USELogs} Logs.Log('Survival', 'Error establishing connection' ) {$ENDIF} end; alive := true; while not Terminated and alive do if PeekMessage( Msg, 0, 0, 0, PM_REMOVE ) then try DispatchMessage( Msg ) except {$IFDEF USELogs} on E : Exception do Logs.Log('Survival', 'Loop thread error: ' + E.Message); {$ENDIF} end else alive := MsgWaitForMultipleObjects( 1, fTerminateEvent, false, INFINITE, QS_ALLINPUT ) = WAIT_OBJECT_0 + 1; fSocketComponent.Active := false; end end; // TWinSockRDOConnectionsServer constructor TWinSockRDOConnectionsServer.Create( Prt : integer; QuearyThrPrior : TThreadPriority); begin inherited Create; fSocketComponent := TServerSocket.Create( nil ); with fSocketComponent do begin Active := false; //ServerType := stNonBlocking; Port := Prt; OnClientConnect := ClientConnected; OnClientDisconnect := ClientDisconnected; OnClientRead := DoClientRead; OnClientError := HandleError end; fQueryQueue := TList.Create; fQueryThreads := TList.Create; fQueryWaiting := CreateEvent( nil, true, false, nil ); fQueryQueueLock := TCriticalSection.Create; fTerminateEvent := CreateEvent( nil, true, false, nil ); // Temporary debug patch.. fThreadPriority := QuearyThrPrior; DebugServers[ServerCount] := self; inc(ServerCount); end; destructor TWinSockRDOConnectionsServer.Destroy; procedure FreeQueryQueue; var QueryIdx : integer; Query : PQueryToService; begin for QueryIdx := 0 to fQueryQueue.Count - 1 do begin Query := PQueryToService(fQueryQueue[ QueryIdx ]); Dispose(Query); end; fQueryQueue.Free end; begin StopListening; fSocketComponent.Free; fQueryThreads.Free; FreeQueryQueue; CloseHandle( fQueryWaiting ); CloseHandle( fTerminateEvent ); fQueryQueueLock.Free; inherited Destroy end; procedure TWinSockRDOConnectionsServer.SetQueryServer( const QueryServer : IRDOQueryServer ); begin fQueryServer := QueryServer end; function TWinSockRDOConnectionsServer.GetMaxQueryThreads : integer; begin Result := fMaxQueryThreads end; procedure TWinSockRDOConnectionsServer.SetMaxQueryThreads( MaxQueryThreads : integer ); begin fMaxQueryThreads := MaxQueryThreads end; procedure TWinSockRDOConnectionsServer.StartListening; var i : integer; begin ResetEvent( fTerminateEvent ); fMsgLoopThread := TMsgLoopThread.Create(Self, fThreadPriority); for i := 1 to fMaxQueryThreads do fQueryThreads.Add(TQueryThread.Create(Self, fThreadPriority)); end; procedure TWinSockRDOConnectionsServer.StopListening; procedure FreeQueryThreads; var i : integer; aQueryThread : TSmartThread; begin for i := 0 to pred(fQueryThreads.Count) do begin aQueryThread := TSmartThread( fQueryThreads[i] ); aQueryThread.Free; end; fQueryThreads.Clear; end; begin SetEvent( fTerminateEvent ); if fMsgLoopThread <> nil then begin fMsgLoopThread.Free; fMsgLoopThread := nil; end; if fQueryThreads <> nil then FreeQueryThreads; end; function TWinSockRDOConnectionsServer.GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection; var ConnIdx : integer; ConnCount : integer; FoundConn : IRDOConnection; UseIPAddr : boolean; CurrConn : TCustomWinSocket; CurConnRmtAddr : string; begin ConnIdx := 0; with fSocketComponent do begin Socket.Lock; try ConnCount := Socket.ActiveConnections; FoundConn := nil; if inet_addr( PChar( ClientAddress ) ) = u_long(INADDR_NONE) then UseIPAddr := false else UseIPAddr := true; while ( ConnIdx < ConnCount ) and ( FoundConn = nil ) do begin CurrConn := Socket.Connections[ ConnIdx ]; if UseIPAddr then CurConnRmtAddr := CurrConn.RemoteAddress else CurConnRmtAddr := CurrConn.RemoteHost; if ( CurConnRmtAddr = ClientAddress ) and ( CurrConn.RemotePort = ClientPort ) then begin // >> 16/8/01 Add the connection when requested if not created (avoid creating useless threads) FoundConn := PSocketData( CurrConn.Data ).RDOConnection; if FoundConn = nil then begin FoundConn := TWinSockRDOServerClientConnection.Create(PSocketData(CurrConn.Data).Owner); PSocketData(CurrConn.Data).RDOConnection := FoundConn; end; end else inc(ConnIdx); end finally Socket.Unlock; end; end; Result := FoundConn end; function TWinSockRDOConnectionsServer.GetClientConnectionById( Id : integer ) : IRDOConnection; var ConnIdx : integer; ConnCount : integer; FoundConn : IRDOConnection; CurrConn : TCustomWinSocket; begin ConnIdx := 0; with fSocketComponent do begin Socket.Lock; try ConnCount := Socket.ActiveConnections; FoundConn := nil; while ( ConnIdx < ConnCount ) and ( FoundConn = nil ) do begin CurrConn := Socket.Connections[ ConnIdx ]; if integer(CurrConn) = Id then begin // >> 16/8/01 Add the connection when requested if not created (avoid creating useless threads) FoundConn := PSocketData(CurrConn.Data).RDOConnection; if FoundConn = nil then begin FoundConn := TWinSockRDOServerClientConnection.Create(PSocketData(CurrConn.Data).Owner); PSocketData(CurrConn.Data).RDOConnection := FoundConn; end; end else inc(ConnIdx); end; finally Socket.Unlock; end; end; Result := FoundConn end; procedure TWinSockRDOConnectionsServer.InitEvents( const EventSink : IRDOConnectionServerEvents ); begin fEventSink := EventSink end; procedure TWinSockRDOConnectionsServer.ClientConnected( Sender : TObject; Socket : TCustomWinSocket ); var SocketData : PSocketData; begin New( SocketData ); SocketData.Owner := TSocketWrap.Create(Socket); // >> 16/8/01 SocketData.RDOConnection := nil; //SocketData.RDOConnection := TWinSockRDOServerClientConnection.Create(SocketData.Owner);//, fTerminateEvent); Socket.Data := SocketData; {if fEventSink <> nil then fEventSink.OnClientConnect(SocketData.RDOConnection);} // >> 16/8/01 end; procedure TWinSockRDOConnectionsServer.ClientDisconnected( Sender : TObject; Socket : TCustomWinSocket ); var SocketData : PSocketData; begin SocketData := PSocketData( Socket.Data ); SocketData.Owner.Invalidate; try if fEventSink <> nil then fEventSink.OnClientDisconnect( SocketData.RDOConnection ); except {$IFDEF USELogs} Logs.Log('Survival', DateTimeToStr(Now) + ' TWinSockRDOConnectionsServer.ClientDisconnected (1)' ); {$ENDIF} end; try if (SocketData.RDOConnection <> nil) and Assigned(SocketData.RDOConnection.OnDisconnect) then SocketData.RDOConnection.OnDisconnect(SocketData.RDOConnection); except {$IFDEF USELogs} Logs.Log('Survival', DateTimeToStr(Now) + ' TWinSockRDOConnectionsServer.ClientDisconnected (2)' ); {$ENDIF} end; {$IFDEF USELogs} //Logs.Log('Survival', 'RemoveQuery start..' ); {$ENDIF} RemoveQuery(Socket); // >> check this {$IFDEF USELogs} //Logs.Log('Survival', 'RemoveQuery end' ); {$ENDIF} try SocketData.Owner := nil; dispose(SocketData); except {$IFDEF USELogs} Logs.Log('Survival', DateTimeToStr(Now) + ' TWinSockRDOConnectionsServer.ClientDisconnected (3)' ); {$ENDIF} end; end; procedure TWinSockRDOConnectionsServer.DoClientRead( Sender : TObject; Socket : TCustomWinSocket ); var NonWSPCharIdx : integer; QueryToService : PQueryToService; QueryText : string; ReadError : boolean; ReceivedText : string; SocketData : PSocketData; ServClienConn : IRDOServerClientConnection; begin try ReadError := false; try ReceivedText := Socket.ReceiveText; {$IFDEF LogsEnabled} if ReceivedText <> '' then LogThis( 'Read : ' + ReceivedText ) {$ENDIF} except on E : Exception do begin ReadError := true; Logs.Log('Survival', DateTimeToStr(Now) + ' Error while reading from socket ' + E.Message); end; end; if not ReadError and ( fQueryServer <> nil ) then begin SocketData := PSocketData( Socket.Data ); SocketData.Buffer := SocketData.Buffer + ReceivedText; QueryText := GetQueryText( SocketData.Buffer ); if Length(SocketData.Buffer) > MaxQueryLength // >> this is to avoid data bulk hacks.. then begin SocketData.Buffer := ''; Logs.Log('RDO', DateTimeToStr(Now) + ' Socket sending too much data for one query, address: ' + Socket.RemoteAddress); Socket.Close; end else while QueryText <> '' do begin NonWSPCharIdx := 1; SkipSpaces( QueryText, NonWSPCharIdx ); if QueryText[ NonWSPCharIdx ] = CallId then begin Delete( QueryText, NonWSPCharIdx, 1 ); {$IFDEF LogsEnabled} LogThis( 'Query : ' + QueryText ); {$ENDIF} New( QueryToService ); QueryToService.Text := QueryText; QueryToService.Socket := PSocketData(Socket.Data).Owner; QueryToService.Valid := true; fQueryQueueLock.Acquire; try if pos(QUERY_COUNT_ENQUIRE, QueryText) = 0 then begin if not fQueryServer.Busy then begin fQueryQueue.Add( QueryToService ); if fQueryQueue.Count > 0 then SetEvent( fQueryWaiting ); end else Socket.SendText(AnswerId + CreateErrorMessage(errServerBusy)); end else begin Dispose(QueryToService); try Socket.SendText('res = ' + IntToStr(fQueryQueue.Count) + ' ' + GetStuckQueries); except Socket.SendText('Internal error!'); end; end; finally fQueryQueueLock.Release end end else if QueryText[ NonWSPCharIdx ] = AnswerId then begin try Delete( QueryText, NonWSPCharIdx, 1 ); if SocketData.RDOConnection <> nil // >> 16/8/01 then begin ServClienConn := SocketData.RDOConnection as IRDOServerClientConnection; ServClienConn.OnQueryResultArrival( QueryText ) end; except end end; QueryText := GetQueryText( SocketData.Buffer ) end; end; except {$IFDEF USELogs} on E : Exception do Logs.Log('Survival', 'Error in DoClientRead ' + E.Message) {$ENDIF} end; end; procedure TWinSockRDOConnectionsServer.HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : Integer ); begin ErrorCode := 0; {$IFDEF USELogs} case ErrorEvent of eeGeneral: Logs.Log('Survival', 'General socket error' ); eeSend: Logs.Log('Survival', 'Error writing to socket' ); eeReceive: Logs.Log('Survival', 'Error reading from socket' ); eeConnect: Logs.Log('Survival', 'Error establishing connection' ); eeDisconnect: Logs.Log('Survival', 'Error closing connection' ); eeAccept: Logs.Log('Survival', 'Error accepting connection' ) end {$ENDIF} end; procedure TWinSockRDOConnectionsServer.RemoveQuery(Socket : TCustomWinSocket); //var //i : integer; //Query : PQueryToService; begin { try fQueryQueueLock.Enter; try if fQueryQueue.Count > 0 then Logs.Log('Survival', 'Remove from Queue start..' ); i := 0; while i < fQueryQueue.Count do begin Query := PQueryToService(fQueryQueue[i]); if Query.Socket = Socket then begin Dispose(Query); fQueryQueue.Delete(i); end else inc(i); end; if fQueryQueue.Count > 0 then Logs.Log('Survival', 'Remove from Queue end..' ); finally fQueryQueueLock.Leave; end; Logs.Log('Survival', 'Remove from Threads start..' ); for i := 0 to pred(fQueryThreads.Count) do TQueryThread(fQueryThreads[i]).CheckQuery(Socket); Logs.Log('Survival', 'Remove from Threads end..' ); except end; } end; function TWinSockRDOConnectionsServer.GetStuckQueries : string; var i : integer; Q : PQueryToService; Thread : TQueryThread; status : string; begin result := ''; for i := 0 to pred(fQueryThreads.Count) do try Thread := TQueryThread(fQueryThreads[i]); status := IntToStr(Thread.fStatus) + ',' + IntToStr(Thread.fQueryStatus) + ',' + IntToStr(Thread.fRDOCallCnt); Q := Thread.fQueryToService; if Q <> nil then result := result + IntToStr(i) + '(' + status + '):' + Q.Text + ' ' else result := result + IntToStr(i) + '(' + status + '): None '; except end; end; initialization fillchar(DebugServers, sizeof(DebugServers), 0); end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCNBKP1.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcNbkP1; {-Property editor for the notebook component} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Graphics, Forms, Controls, Buttons, StdCtrls, SysUtils, ExtCtrls, OvcHelp; type TOvcfrmTabPageInfo = class(TForm) edPageName: TEdit; edPageHint: TEdit; edPageContext: TEdit; cbPageEnabled: TCheckBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; btnOk: TBitBtn; btnCancel: TBitBtn; btnHelp: TBitBtn; procedure OKClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); protected function GetPageContext : THelpContext; function GetPageEnabled : Boolean; function GetPageHint : string; function GetPageName : string; procedure SetPageContext(Value : THelpContext); procedure SetPageEnabled(Value : Boolean); procedure SetPageHint(const Value : string); procedure SetPageName(const Value : string); public property PageContext : THelpContext read GetPageContext write SetPageContext; property PageEnabled : Boolean read GetPageEnabled write SetPageEnabled; property PageHint : string read GetPageHint write SetPageHint; property PageName : string read GetPageName write SetPageName; end; implementation {$R *.DFM} function TOvcfrmTabPageInfo.GetPageContext : THelpContext; begin Result := StrToInt(edPageContext.Text); end; function TOvcfrmTabPageInfo.GetPageEnabled : Boolean; begin Result := cbPageEnabled.Checked; end; function TOvcfrmTabPageInfo.GetPageHint : string; begin Result := edPageHint.Text; end; function TOvcfrmTabPageInfo.GetPageName : string; begin Result := edPageName.Text; end; procedure TOvcfrmTabPageInfo.SetPageContext(Value : THelpContext); begin edPageContext.Text := IntToStr(Value); edPageContext.SelectAll; end; procedure TOvcfrmTabPageInfo.SetPageEnabled(Value : Boolean); begin cbPageEnabled.Checked := Value; end; procedure TOvcfrmTabPageInfo.SetPageHint(const Value : string); begin edPageHint.Text := Value; edPageHint.SelectAll; end; procedure TOvcfrmTabPageInfo.SetPageName(const Value : string); begin edPageName.Text := Value; edPageName.SelectAll; end; procedure TOvcfrmTabPageInfo.OKClick(Sender: TObject); begin try StrToInt(edPageContext.Text); {see if it converts without error} except ModalResult := 0; ActiveControl := edPageContext; edPageContext.SelectAll; raise; end; end; procedure TOvcfrmTabPageInfo.btnHelpClick(Sender: TObject); begin ShowHelpContext(hcNotebookPageInfo); end; end.
unit entradaDao; interface uses Abastecimento, DB, DM, IBQuery, IBDataBase, Classes, SysUtils, DateUtils, entrada; type T_EntradaDao = class(TObject) private F_Qr: TIBQuery; F_Lista: TList; public constructor Create(db: TIBDataBase); destructor Destroy(); function NewID(): Integer; function incluir(entrada: T_Entrada): Integer; procedure atualizar(entrada: T_Entrada); procedure remover(entrada: T_Entrada); overload; procedure remover(entrada_id: Integer); overload; function listarTudo(): TList; function listarPorPeriodo(inicio, fim: TDateTime): TList; function get(id: Integer): T_Entrada; end; implementation uses tanqueDao, tanque; var vtanqueDao: T_TanqueDao; vtanque: T_Tanque; ventrada: T_Entrada; ventrada_id: Integer; const SQL_ID = 'SELECT GEN_ID( ENTRADA_ID_GEN, 1 ) AS ID FROM RDB$DATABASE; '; SQL_INCLUIR = 'INSERT INTO Entrada(Id, Tanque_Id, Litros, ValorPorLitro, ValorDaEntrada, DataHora) '#13#10 + 'VALUES( :id , :tanque_id , :litros , :valorporlitro , :valordaentrada , :datahora ) '; SQL_ATUALIZAR = 'UPDATE Entrada '#13#10 + 'SET '#13#10 + ' Tanque_Id = :tanque_id , '#13#10 + ' Litros = :litros , '#13#10 + ' ValorPorLitro = :valorporlitro , '#13#10 + ' ValorDaEntrada = :valordaentrada , '#13#10 + ' DataHora = :datahora '#13#10 + 'WHERE Id = :id '#13#10; SQL_EXCLUIR = 'DELETE FROM Entrada WHERE Id = :id '; SQL_LISTARTUDO = 'SELECT * FROM Entrada ORDER BY DataHora DESC '; SQL_LISTARPORPERIODO = 'SELECT * FROM Entrada WHERE DataHora BETWEEN :inicio AND :fim ORDER BY DataHora DESC '; SQL_GET = 'SELECT * FROM Entrada WHERE ID = :id '; constructor T_EntradaDao.Create(db: TIBDataBase); begin F_Qr := TIBQuery.Create(db); F_Qr.Database := db; F_QR.Transaction := db.DefaultTransaction; F_Lista := TList.Create(); vtanqueDao := T_TanqueDao.Create(dm._dm.IBDataBase1); vtanque := T_Tanque.Create(); end; destructor T_EntradaDao.Destroy(); begin F_Lista.Free(); end; function T_EntradaDao.NewID(): Integer; var id: Integer; begin F_Qr.Active := False; F_Qr.SQL.Clear(); F_Qr.SQL.Text := SQL_ID; F_Qr.Prepare(); F_Qr.Open(); result := F_Qr.FieldByName('Id').AsInteger; F_Qr.Active := False; end; function T_EntradaDao.incluir(entrada: T_Entrada): Integer; var id: Integer; vtanque: T_Tanque; begin id := NewID(); F_QR.Active := False; F_QR.SQL.Clear(); F_Qr.SQL.Text := SQL_INCLUIR; F_Qr.ParamByName('id').Value := id; F_Qr.ParamByName('tanque_id').Value := Entrada.Tanque_Id; F_Qr.ParamByName('litros').Value := Entrada.Litros; F_Qr.ParamByName('valorporlitro').Value := Entrada.ValorPorLitro; F_Qr.ParamByName('valordaentrada').Value := Entrada.ValorDaEntrada; F_Qr.ParamByName('datahora').Value := Entrada.DataHora; F_QR.Prepare(); F_Qr.ExecSQL(); Entrada.Id := id; ventrada_id := id; result := id; end; procedure T_EntradaDao.atualizar(Entrada: T_Entrada); begin F_Qr.SQL.Text := SQL_ATUALIZAR; F_Qr.ParamByName('id').Value := entrada.id; F_Qr.ParamByName('tanque_id').Value := Entrada.Tanque_Id; F_Qr.ParamByName('litros').Value := Entrada.Litros; F_Qr.ParamByName('valorporlitro').Value := Entrada.ValorPorLitro; F_Qr.ParamByName('valordaentrada').Value := Entrada.ValorDaEntrada; F_Qr.ParamByName('datahora').Value := Entrada.DataHora; F_QR.Prepare(); F_Qr.ExecSQL(); end; procedure T_EntradaDao.remover(Entrada: T_Entrada); begin F_Qr.SQL.Text := SQL_EXCLUIR; F_Qr.ParamByName('id').Value := Entrada.Id; F_QR.Prepare(); F_Qr.ExecSQL(); end; procedure T_EntradaDao.remover(entrada_id: Integer); begin F_Qr.SQL.Text := SQL_EXCLUIR; F_Qr.ParamByName('id').Value := entrada_id; F_QR.Prepare(); F_Qr.ExecSQL(); end; function T_EntradaDao.listarTudo(): TList; var a: T_Entrada; begin F_Qr.SQL.Text := SQL_LISTARTUDO; F_Qr.Prepare(); F_Qr.Open(); result := TList.Create(); F_Qr.First(); while not F_Qr.Eof do begin result.Add( T_Entrada.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Tanque_Id').AsInteger, F_Qr.FieldByName('Litros').AsFloat, F_Qr.FieldByName('ValorPorLitro').AsFloat, F_Qr.FieldByName('DataHora').AsDateTime) ); F_Qr.Next(); end; if F_Qr.Active then F_Qr.Close(); end; function T_EntradaDao.listarPorPeriodo(inicio, fim: TDateTime): TList; begin F_Qr.SQL.Text := SQL_LISTARPORPERIODO; F_Qr.ParamByName('inicio').Value := inicio; F_Qr.ParamByName('fim').Value := fim; F_Qr.Prepare(); F_Qr.Open(); result := TList.Create(); F_Qr.First(); while not F_Qr.Eof do begin result.Add( T_Entrada.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Tanque_Id').AsInteger, F_Qr.FieldByName('Litros').AsFloat, F_Qr.FieldByName('ValorPorLitro').AsFloat, F_Qr.FieldByName('DataHora').AsDateTime) ); F_Qr.Next(); end; if F_Qr.Active then F_Qr.Close(); end; function T_EntradaDao.get(id: Integer): T_Entrada; var a: T_Entrada; begin F_Qr.SQL.Text := SQL_GET; F_Qr.ParamByName('id').Value := id; F_Qr.Prepare(); F_Qr.Open(); result := nil; if not F_Qr.Eof then begin result := T_Entrada.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Tanque_Id').AsInteger, F_Qr.FieldByName('Litros').AsFloat, F_Qr.FieldByName('ValorPorLitro').AsFloat, F_Qr.FieldByName('DataHora').AsDateTime); end; if F_Qr.Active then F_Qr.Close(); end; end.
unit DataContainers.TFile; interface uses System.SysUtils, System.Classes, Framework.Interfaces; type TFile = class(TInterfacedObject, IFIle) strict private FFile: TStringList; function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure LoadFromFile(const AFileName: string); overload; procedure LoadFromFile(const AFileName: string; AEncoding: TEncoding); overload; procedure SaveToFile(const AFileName: string); overload; procedure SaveToFile(const AFileName: string; AEncoding: TEncoding); overload; function Add(const AString: string): Integer; procedure Clear; property Count: Integer read GetCount; end; implementation { TFile } function TFile.Add(const AString: string): Integer; begin Result := FFile.Add(AString); end; procedure TFile.Clear; begin FFile.Clear; end; constructor TFile.Create; begin inherited; FFile := TStringList.Create; end; destructor TFile.Destroy; begin FFile.Free; inherited; end; function TFile.GetCount: Integer; begin Result := FFile.Count; end; procedure TFile.LoadFromFile(const AFileName: string; AEncoding: TEncoding); begin FFile.Clear; FFile.LoadFromFile(AFileNAme, AEncoding); end; procedure TFile.SaveToFile(const AFileName: string; AEncoding: TEncoding); begin FFile.SaveToFile(AFileName, AEncoding); end; procedure TFile.SaveToFile(const AFileName: string); begin FFile.SaveToFile(AFileName); FFile.Count end; procedure TFile.LoadFromFile(const AFileName: string); begin FFile.Clear; FFile.LoadFromFile(AFileNAme); end; end.
unit kwPopEditorSelectCells; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSelectCells.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SelectCells // // *Формат:* aStartCell aStartRow aFinshCell aFinishRow anEditorControl pop:editor:SelectCells // *Описание:* Выделяет диапазон ячеек с помощью мыши начиная от начальной (aStartCell, aRowCell) // до конечной (aFinishCell, aFinishRow). Курсор должен уже находится в таблице. Положение курсора // в таблице не имеет значения. Параметры aStartCell aStartRow aFinshCell aFinishRow - Integer // *Пример:* // {code} // 0 0 2 2 focused:control:push pop:editor:SelectCells // {code} // *Результат:* Выделяет диапазон ячеек в таблице от (0, 0) до (2, 2) у текущего редактора. // *Примечание:* В каждой ячейке должен быть только один параграф, иначе выделение будет // неправильным. // *Примечание 2:* Текст в начальной ячейке должен быть выровнен по левому краю. Иначе появится // сообщение об ошибке. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes, nevTools ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwSelectCellsWord.imp.pas} TkwPopEditorSelectCells = {final} class(_kwSelectCellsWord_) {* *Формат:* aStartCell aStartRow aFinshCell aFinishRow anEditorControl pop:editor:SelectCells *Описание:* Выделяет диапазон ячеек с помощью мыши начиная от начальной (aStartCell, aRowCell) до конечной (aFinishCell, aFinishRow). Курсор должен уже находится в таблице. Положение курсора в таблице не имеет значения. Параметры aStartCell aStartRow aFinshCell aFinishRow - Integer *Пример:* [code] 0 0 2 2 focused:control:push pop:editor:SelectCells [code] *Результат:* Выделяет диапазон ячеек в таблице от (0, 0) до (2, 2) у текущего редактора. *Примечание:* В каждой ячейке должен быть только один параграф, иначе выделение будет неправильным. *Примечание 2:* Текст в начальной ячейке должен быть выровнен по левому краю. Иначе появится сообщение об ошибке. } protected // realized methods function IsVertical: Boolean; override; {* При выделении мышь движется сверху вниз. } public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorSelectCells {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses l3Base, l3Units, evConst, nevGUIInterfaces, tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms, Table_Const ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorSelectCells; {$Include ..\ScriptEngine\kwSelectCellsWord.imp.pas} // start class TkwPopEditorSelectCells function TkwPopEditorSelectCells.IsVertical: Boolean; //#UC START# *4F6042D20081_4F4DD643008C_var* //#UC END# *4F6042D20081_4F4DD643008C_var* begin //#UC START# *4F6042D20081_4F4DD643008C_impl* Result := False; //#UC END# *4F6042D20081_4F4DD643008C_impl* end;//TkwPopEditorSelectCells.IsVertical class function TkwPopEditorSelectCells.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:SelectCells'; end;//TkwPopEditorSelectCells.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwSelectCellsWord.imp.pas} {$IfEnd} //not NoScripts end.
unit arOneTaskDeliverer; // Модуль: "w:\archi\source\projects\Archi\Processing\arOneTaskDeliverer.pas" // Стереотип: "SimpleClass" // Элемент модели: "TarOneTaskDeliverer" MUID: (546AFE0D01CB) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(AppClientSide)} uses l3IntfUses , l3ProtoObject {$If NOT Defined(Nemesis)} , ncsMessageInterfaces {$IfEnd} // NOT Defined(Nemesis) {$If NOT Defined(Nemesis)} , ncsGetTaskDescriptionReply {$IfEnd} // NOT Defined(Nemesis) , ddProgressObj , evdNcsTypes ; type TarOneTaskDeliverer = class(Tl3ProtoObject) private f_Transporter: IncsTransporter; f_TaskID: AnsiString; f_Reply: TncsGetTaskDescriptionReply; f_ProgressDescription: AnsiString; f_ProgressPercent: Integer; f_Progressor: TddProgressObject; f_ReceiveTime: Double; f_WriteTime: Double; private procedure ProgressUpdate(Sender: TObject; aTotalPercent: Integer); procedure SetProgress(aNewPercent: Integer; const aNewDescription: AnsiString); protected function pm_GetTargetFolder: AnsiString; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aTransporter: IncsTransporter; const aTaskID: AnsiString); reintroduce; function Execute: TncsResultKind; public property TargetFolder: AnsiString read pm_GetTargetFolder; property ReceiveTime: Double read f_ReceiveTime; property WriteTime: Double read f_WriteTime; end;//TarOneTaskDeliverer {$IfEnd} // Defined(AppClientSide) implementation {$If Defined(AppClientSide)} uses l3ImplUses , SysUtils {$If NOT Defined(Nemesis)} , ncsGetTaskDescription {$IfEnd} // NOT Defined(Nemesis) {$If NOT Defined(Nemesis)} , ncsMessage {$IfEnd} // NOT Defined(Nemesis) {$If NOT Defined(Nemesis)} , ncsFileListDeliverer {$IfEnd} // NOT Defined(Nemesis) , l3Base {$If NOT Defined(Nemesis)} , ncsTaskProgress {$IfEnd} // NOT Defined(Nemesis) //#UC START# *546AFE0D01CBimpl_uses* //#UC END# *546AFE0D01CBimpl_uses* ; function TarOneTaskDeliverer.pm_GetTargetFolder: AnsiString; //#UC START# *546AFEAB00E6_546AFE0D01CBget_var* //#UC END# *546AFEAB00E6_546AFE0D01CBget_var* begin //#UC START# *546AFEAB00E6_546AFE0D01CBget_impl* if Assigned(f_Reply) then Result := f_Reply.LocalFolder else Result := ''; //#UC END# *546AFEAB00E6_546AFE0D01CBget_impl* end;//TarOneTaskDeliverer.pm_GetTargetFolder constructor TarOneTaskDeliverer.Create(const aTransporter: IncsTransporter; const aTaskID: AnsiString); //#UC START# *546AFEF1001C_546AFE0D01CB_var* //#UC END# *546AFEF1001C_546AFE0D01CB_var* begin //#UC START# *546AFEF1001C_546AFE0D01CB_impl* inherited Create; f_Transporter := aTransporter; f_TaskID := aTaskID; f_Progressor := TddProgressObject.Create; f_Progressor.AllowProgressDecrement := True; f_Progressor.OnUpdate := ProgressUpdate; f_ReceiveTime := 0; f_WriteTime := 0; //#UC END# *546AFEF1001C_546AFE0D01CB_impl* end;//TarOneTaskDeliverer.Create procedure TarOneTaskDeliverer.ProgressUpdate(Sender: TObject; aTotalPercent: Integer); //#UC START# *5474528D0320_546AFE0D01CB_var* //#UC END# *5474528D0320_546AFE0D01CB_var* begin //#UC START# *5474528D0320_546AFE0D01CB_impl* SetProgress(f_Progressor.TotalPercent, f_Progressor.Caption); //#UC END# *5474528D0320_546AFE0D01CB_impl* end;//TarOneTaskDeliverer.ProgressUpdate procedure TarOneTaskDeliverer.SetProgress(aNewPercent: Integer; const aNewDescription: AnsiString); //#UC START# *547452F8012B_546AFE0D01CB_var* var l_Message: TncsTaskProgress; //#UC END# *547452F8012B_546AFE0D01CB_var* begin //#UC START# *547452F8012B_546AFE0D01CB_impl* if (f_ProgressPercent <> aNewPercent) or (f_ProgressDescription <> aNewDescription) then begin f_ProgressPercent := aNewPercent; f_ProgressDescription := aNewDescription; l_Message := TncsTaskProgress.Create; try l_Message.TaskID := f_TaskID; l_Message.Percent := f_ProgressPercent; l_Message.Description := f_ProgressDescription; if f_Transporter.Processing then f_Transporter.Send(l_Message) else l3System.Msg2Log('ALERT - SetProgress on disconected result delivery'); finally FreeAndNil(l_Message); end; end; //#UC END# *547452F8012B_546AFE0D01CB_impl* end;//TarOneTaskDeliverer.SetProgress function TarOneTaskDeliverer.Execute: TncsResultKind; //#UC START# *546AFE51021F_546AFE0D01CB_var* var l_TaskDesc: TncsGetTaskDescription; l_Reply: TncsMessage; l_Deliverer: TncsFileListDeliverer; const cMap: array [Boolean] of TncsResultKind = (ncs_rkFail, ncs_rkOk); //#UC END# *546AFE51021F_546AFE0D01CB_var* begin //#UC START# *546AFE51021F_546AFE0D01CB_impl* Result := ncs_rkFail; l_TaskDesc := TncsGetTaskDescription.Create; try l_TaskDesc.TaskID := f_TaskID; f_Transporter.Send(l_TaskDesc); l_Reply := nil; try if f_Transporter.WaitForReply(l_TaskDesc, l_Reply) then begin if not f_Transporter.Processing then begin l3System.Msg2Log('Обшика доставки - обрыв связи'); Exit; end; l_Reply.SetRefTo(f_Reply); l_Deliverer := TncsFileListDeliverer.Create(f_Transporter, f_Progressor, f_TaskID, f_Reply.LocalFolder); try try try Result := cMap[l_Deliverer.Execute(f_Reply.FileDesc)]; except on E: Exception do begin l3System.Exception2Log(E); raise; end; end; except on EOSError do Result := ncs_rkRetry; on EInOutError do Result := ncs_rkRetry; on EncsEmptyResults do Result := ncs_rkEmpty; end; finally f_ReceiveTime := f_ReceiveTime + l_Deliverer.ReceiveTime; f_WriteTime := f_WriteTime + l_Deliverer.WriteTime; FreeAndNil(l_Deliverer); end; end; finally FreeAndNil(l_Reply) end; finally FreeAndNil(l_TaskDesc); end; //#UC END# *546AFE51021F_546AFE0D01CB_impl* end;//TarOneTaskDeliverer.Execute procedure TarOneTaskDeliverer.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_546AFE0D01CB_var* //#UC END# *479731C50290_546AFE0D01CB_var* begin //#UC START# *479731C50290_546AFE0D01CB_impl* f_Transporter := nil; FreeAndNil(f_Reply); FreeAndNil(f_Progressor); inherited; //#UC END# *479731C50290_546AFE0D01CB_impl* end;//TarOneTaskDeliverer.Cleanup {$IfEnd} // Defined(AppClientSide) end.
unit UTime; interface type TIME_STAMP = Int64; var GetMyTime:function:TDateTime; function MyTimeStamp:TIME_STAMP; function UTCTimeStamp:TIME_STAMP; procedure SetMyTimeType(MTT:Integer); function GetLocTime:TDateTime; function GetUTCTime:TDateTime; function GetMSKTime:TDateTime; function GetNullTime:TDateTime; procedure SetUTCTime(Time:TDateTime); procedure SetLocTime(Time:TDateTime); function ToTimeStamp(const Time:TDateTime):TIME_STAMP; function ToDateTime(const Time:TIME_STAMP):TDateTime; const nSecsPerDay=24*60*60; LLTicksPerSec=1000; LLTicksPerDay=nSecsPerDay*LLTicksPerSec; dtLLTickPeriod=1/LLTicksPerDay; dtOneSecond=1/nSecsPerDay; // dtOneMSec=1/MSecsPerDay; mttLocal=0; mttUTC=1; mttMSK=2; mttNull=High(Integer); const // Timeouts toTypeMask = $C0000000; { toTypeNext = 0xC000 toNext10ms = 0xC001 toNext100ms = 0xC002 toNextSecond= 0xC003 //} toTypeMs = $00000000; toTypeSec = $40000000; type TTimeout = type Cardinal; TTimeoutObj = object protected StopTime:TIME_STAMP; public procedure start(Timeout:TTimeout); procedure stop(); procedure setSignaled(Signaled:Boolean = True); function IsSignaled():Boolean; function wait(Timeout:TTimeout):Boolean; end; implementation uses Windows,SysUtils; var MSKTZI:TIME_ZONE_INFORMATION; function ToDateTime(const Time:TIME_STAMP):TDateTime; begin Result:=Time*dtLLTickPeriod; end; function ToTimeStamp(const Time:TDateTime):TIME_STAMP; begin Result:=Round(Time*LLTicksPerDay); end; //***************** TTimeoutObj procedure TTimeoutObj.setSignaled(Signaled:Boolean = True); begin if Signaled then StopTime := 0 else StopTime := High(TIME_STAMP); end; procedure TTimeoutObj.start(Timeout: TTimeout); var T:TTimeout; begin T:=Timeout and not toTypeMask; case Timeout and toTypeMask of toTypeMs: StopTime := UTCTimeStamp+T; toTypeSec: StopTime := UTCTimeStamp+T*LLTicksPerSec; end; end; procedure TTimeoutObj.stop; begin setSignaled(False); end; function TTimeoutObj.IsSignaled():Boolean; begin Result:=StopTime <= UTCTimeStamp; end; function TTimeoutObj.wait(Timeout: TTimeout): Boolean; var too:TTimeoutObj; begin Result:=False; too.start(Timeout); while True do begin Result := IsSignaled(); if Result or too.IsSignaled() then break; Windows.Sleep(1); end; end; // **************************************** function UTCTimeStamp:TIME_STAMP; begin Result:=Round(GetUTCTime*LLTicksPerDay); end; function MyTimeStamp:TIME_STAMP; begin Result:=Round(GetMyTime*LLTicksPerDay); end; procedure SetMyTimeType(MTT:Integer); begin case MTT of mttLocal:GetMyTime:=Now; mttUTC: GetMyTime:=GetUTCTime; mttMSK: GetMyTime:=GetMSKTime; else GetMyTime:=GetNullTime; end; end; function GetNullTime:TDateTime; begin Result:=0; end; function GetMSKTime:TDateTime; var UTC,MSK:TSystemTime; begin GetSystemTime(UTC); SystemTimeToTzSpecificLocalTime(@MSKTZI,UTC,MSK); Result:=SystemTimeToDateTime(MSK); end; function GetUTCTime:TDateTime; var ST:TSystemTime; begin GetSystemTime(ST); Result:=SystemTimeToDateTime(ST); end; procedure SetUTCTime(Time:TDateTime); var ST:TSystemTime; begin DateTimeToSystemTime(Time,ST); SetSystemTime(ST); end; function GetLocTime:TDateTime; begin Result:=Now; end; procedure SetLocTime(Time:TDateTime); var ST:TSystemTime; begin DateTimeToSystemTime(Time,ST); SetLocalTime(ST); end; initialization MSKTZI.Bias:=-180; // TZI.StandardName:='Московское время (зима)'; MSKTZI.StandardDate.wMonth:=10; MSKTZI.StandardDate.wDay:=5; MSKTZI.StandardDate.wHour:=3; MSKTZI.StandardBias:=0; // TZI.DaylightName:='Московское время (лето)'; MSKTZI.DaylightDate.wMonth:=3; MSKTZI.DaylightDate.wDay:=5; MSKTZI.DaylightDate.wHour:=2; MSKTZI.DaylightBias:=-60; SetMyTimeType(mttNull); end.
program ch15(input, output, data11); { Chapter 15 Assignment Alberto Villalobos May 1, 2014 Description: Given a mileage chart matrix, detect if there are symmetry or diagonal errors, in other words, make sure that the distance from A to B is the same as B to A. And that the distance from A to A is always 0. Input: a file that contains several matrixes separated but a single random number Output: On screen success or error message level 0: Initialize variables Reset buffer Read first line as height of matrix Loop through the matrix height times Put those values into a multidimensional array Pass by reference to check function, return success or fail After height times, get next matrix. } type theMatrix = array[1..26, 1..26] of integer; {sub-programs here} procedure printTableHeader(elements : integer); var letter: char; i : integer; begin writeln(''); writeln(''); writeln(''); write('City':5); for i := 1 to elements do begin letter := char(i+64); write(letter:5); end; writeln(' '); for i := 0 to elements do begin write('-------':5); end; end; procedure printTableRow(rowNumber : integer); var letter :char; begin letter := char(rowNumber+65); writeln(''); write(letter,' |':5); end; function checkError(var suspiciousArray : theMatrix; arrayLength : integer): string; var errorOn: Boolean; i, j : integer; errorMessage: string; xLetter, yLetter : char; begin errorOn := false; errorMessage:='Mileage Chart OK!'; { check diagonals} for i := 1 to arrayLength do begin if ((suspiciousArray[i,i] <> 0) AND (errorOn = false)) then begin {writeln("Error!");} xLetter := char(i+64); yLetter := char(i+64); errorMessage := concat('Mileage Chart in Error. First error found in row ', xLetter, ' column ', yLetter); errorOn := true; end; end; { check symmetry } for i := 1 to arrayLength do begin for j := 1 to arrayLength do begin if (suspiciousArray[i,j] <> suspiciousArray[j,i]) and (errorOn = false) then begin xLetter := char(i+64); yLetter := char(j+64); errorMessage := concat('Mileage Chart in Error. First error found in row ', yLetter, ' column ', xLetter); errorOn := true; end; end; end; checkError := errorMessage; end; { main program stuff } var data11: text; lineCount, matrixHeight, currentToken, x, y: integer; currentMatrix : theMatrix; begin lineCount := 0; y := 1; x := 1; matrixHeight := 0; reset(data11, 'datafiles/data11.dat'); while not eof(data11) do begin if lineCount = 0 then begin read(data11, matrixHeight); printTableHeader(matrixHeight); end else begin read(data11, currentToken); currentMatrix[x,y] := currentToken; write(currentMatrix[x,y]:5); x := x+1; end; if eoln(data11) then begin lineCount := lineCount + 1; y := lineCount; x := 1; readln(data11); if lineCount > matrixHeight then begin writeln(''); writeln(checkError(currentMatrix, lineCount)); lineCount := 0; y := lineCount; matrixHeight := currentToken; end else begin printTableRow(y-1); end; end; end; end.
unit suna8_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,timer_engine,ym_3812,ay_8910, rom_engine,misc_functions,pal_engine,sound_engine,dac,gfx_engine; function iniciar_suna_hw:boolean; implementation const //Hard Head hardhead_rom:array[0..7] of tipo_roms=( (n:'p1';l:$8000;p:0;crc:$c6147926),(n:'p2';l:$8000;p:$8000;crc:$faa2cf9a), (n:'p3';l:$8000;p:$10000;crc:$3d24755e),(n:'p4';l:$8000;p:$18000;crc:$0241ac79), (n:'p7';l:$8000;p:$20000;crc:$beba8313),(n:'p8';l:$8000;p:$28000;crc:$211a9342), (n:'p9';l:$8000;p:$30000;crc:$2ad430c4),(n:'p10';l:$8000;p:$38000;crc:$b6894517)); hardhead_sprites:array[0..7] of tipo_roms=( (n:'p5';l:$8000;p:$0;crc:$e9aa6fba),(n:'p5';l:$8000;p:$8000;crc:$e9aa6fba), (n:'p6';l:$8000;p:$10000;crc:$15d5f5dd),(n:'p6';l:$8000;p:$18000;crc:$15d5f5dd), (n:'p11';l:$8000;p:$20000;crc:$055f4c29),(n:'p11';l:$8000;p:$28000;crc:$055f4c29), (n:'p12';l:$8000;p:$30000;crc:$9582e6db),(n:'p12';l:$8000;p:$38000;crc:$9582e6db)); hardhead_dac:tipo_roms=(n:'p14';l:$8000;p:0;crc:$41314ac1); hardhead_sound:tipo_roms=(n:'p13';l:$8000;p:0;crc:$493c0b41); //Hard Head 2 hardhead2_rom:array[0..4] of tipo_roms=( (n:'hrd-hd9';l:$8000;p:0;crc:$69c4c307),(n:'hrd-hd10';l:$10000;p:$10000;crc:$77ec5b0a), (n:'hrd-hd11';l:$10000;p:$20000;crc:$12af8f8e),(n:'hrd-hd12';l:$10000;p:$30000;crc:$35d13212), (n:'hrd-hd13';l:$10000;p:$40000;crc:$3225e7d7)); hardhead2_sprites:array[0..7] of tipo_roms=( (n:'hrd-hd1';l:$10000;p:$0;crc:$7e7b7a58),(n:'hrd-hd2';l:$10000;p:$10000;crc:$303ec802), (n:'hrd-hd3';l:$10000;p:$20000;crc:$3353b2c7),(n:'hrd-hd4';l:$10000;p:$30000;crc:$dbc1f9c1), (n:'hrd-hd5';l:$10000;p:$40000;crc:$f738c0af),(n:'hrd-hd6';l:$10000;p:$50000;crc:$bf90d3ca), (n:'hrd-hd7';l:$10000;p:$60000;crc:$992ce8cb),(n:'hrd-hd8';l:$10000;p:$70000;crc:$359597a4)); hardhead2_pcm:tipo_roms=(n:'hrd-hd15';l:$10000;p:0;crc:$bcbd88c3); hardhead2_sound:tipo_roms=(n:'hrd-hd14';l:$8000;p:0;crc:$79a3be51); //DIPS hardhead_dip_a:array [0..4] of def_dip=( (mask:$1;name:'Demo Sounds';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$e;name:'Bonus Life';number:8;dip:((dip_val:$e;dip_name:'No Bonus'),(dip_val:$c;dip_name:'10K'),(dip_val:$a;dip_name:'20K'),(dip_val:$8;dip_name:'50K'),(dip_val:$6;dip_name:'50K+'),(dip_val:$4;dip_name:'100K 50K+'),(dip_val:$2;dip_name:'100K 100K+'),(dip_val:$0;dip_name:'200K 100K+'),(),(),(),(),(),(),(),())), (mask:$70;name:'Coinage';number:8;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$10;dip_name:'4C 1C'),(dip_val:$20;dip_name:'3C 1C'),(dip_val:$30;dip_name:'2C 1C'),(dip_val:$70;dip_name:'1C 1C'),(dip_val:$60;dip_name:'1C 2C'),(dip_val:$50;dip_name:'1C 3C'),(dip_val:$40;dip_name:'1C 4C'),(),(),(),(),(),(),(),())), (mask:$80;name:'Invulnerability';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); hardhead_dip_b:array [0..5] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Cabinet';number:2;dip:((dip_val:$2;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Play Together';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$4;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Lives';number:4;dip:((dip_val:$18;dip_name:'2'),(dip_val:$10;dip_name:'3'),(dip_val:$8;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$e0;name:'Difficulty';number:8;dip:((dip_val:$e0;dip_name:'Easiest'),(dip_val:$c0;dip_name:'Very Easy'),(dip_val:$a0;dip_name:'Easy'),(dip_val:$80;dip_name:'Moderate'),(dip_val:$60;dip_name:'Normal'),(dip_val:$40;dip_name:'Harder'),(dip_val:$20;dip_name:'Very Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),())),()); hardhead2_dip_a:array [0..3] of def_dip=( (mask:$7;name:'Coinage';number:8;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$1;dip_name:'4C 1C'),(dip_val:$2;dip_name:'3C 1C'),(dip_val:$3;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Difficulty';number:8;dip:((dip_val:$38;dip_name:'Easiest'),(dip_val:$30;dip_name:'Very Easy'),(dip_val:$28;dip_name:'Easy'),(dip_val:$20;dip_name:'Moderate'),(dip_val:$18;dip_name:'Normal'),(dip_val:$10;dip_name:'Harder'),(dip_val:$8;dip_name:'Very Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); hardhead2_dip_b:array [0..5] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Cabinet';number:2;dip:((dip_val:$2;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Play Together';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$4;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$38;name:'Bonus Life';number:8;dip:((dip_val:$38;dip_name:'No Bonus'),(dip_val:$30;dip_name:'10K'),(dip_val:$28;dip_name:'30K'),(dip_val:$18;dip_name:'50K 50K+'),(dip_val:$20;dip_name:'50K'),(dip_val:$10;dip_name:'100K 50K+'),(dip_val:$8;dip_name:'100K 100K+'),(dip_val:$0;dip_name:'200K 100K+'),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$80;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom_bank:array[0..$f,0..$3fff] of byte; suna_dac:array[0..$ffff] of smallint; mem_opcodes:array[0..$7fff] of byte; ram_bank:array[0..1,0..$17ff] of byte; sprite_bank:array[0..$3fff] of byte; banco_rom,banco_sprite,banco_ram:byte; soundlatch,soundlatch2,protection_val,hardhead_ip,vblank:byte; haz_nmi:boolean; dac_timer,dac_tsample:byte; //DAC dac_play,dac_sample,dac_index:byte; dac_value:smallint; dac_pos:word; //Hard Head procedure update_video_hardhead; var x,y,nchar,bank:word; f,ty,tx:byte; real_ty,addr:word; dimy,srcx,srcy,srcpg:word; mx:word; atrib,color:word; flipx,flipy:boolean; sx,sy:word; begin fill_full_screen(1,$ff); //primero sprites mx:=0; for f:=0 to $bf do begin y:=memoria[$fd00+(f shl 2)]; nchar:=memoria[$fd01+(f shl 2)]; x:=memoria[$fd02+(f shl 2)]; bank:=memoria[$fd03+(f shl 2)]; srcx:=(nchar and $f) shl 1; if (nchar and $80)=$80 then begin dimy:=32; srcy:=0; srcpg:=(nchar shr 4) and 3; end else begin dimy:=2; srcy:=(((nchar shr 5) and $3) shl 3)+6; srcpg:=(nchar shr 4) and 1; end; if (bank and $40)<>0 then x:=x-$100; y:=($100-y-(dimy shl 3)) and $ff; // Multi Sprite if ((nchar and $c0)=$c0) then begin mx:=mx+$10; x:=mx; end else begin mx:=x; end; bank:=(bank and $3f) shl 10; for ty:=0 to dimy-1 do begin for tx:=0 to 1 do begin addr:=((srcpg shl 10)+(((srcx+tx) and $1f) shl 5)+((srcy+ty) and $1f)) shl 1; atrib:=memoria[addr+$e001]; nchar:=memoria[addr+$e000]+((atrib and $3) shl 8)+bank; color:=(atrib and $3c) shl 2; flipx:=(atrib and $40)<>0; flipy:=(atrib and $80)<>0; sx:=x+(tx shl 3); sy:=y+(ty shl 3); put_gfx_sprite(nchar,color,flipx,flipy,0); actualiza_gfx_sprite(sx,sy,1,0); end; end; end; //por ultimo char sprites for f:=0 to $3f do begin nchar:=memoria[$f901+(f shl 2)]; if (not(nchar) and $80)<>0 then continue; y:=memoria[$f900+(f shl 2)]; x:=memoria[$f902+(f shl 2)]; bank:=memoria[$f903+(f shl 2)]; srcx:=(nchar and $f) shl 1; srcy:=(y and $f0) shr 3; srcpg:=(nchar shr 4) and 3; if (bank and $40)<>0 then x:=x-$100; bank:=(bank and $3f) shl 10; for ty:=0 to 11 do begin for tx:=0 to 2 do begin if (ty<6) then real_ty:=ty else real_ty:=ty+$14; addr:=((srcpg shl 10)+(((srcx+tx) and $1f) shl 5)+((srcy+real_ty) and $1f)) shl 1; atrib:=memoria[addr+$e001]; nchar:=memoria[addr+$e000]+((atrib and $3) shl 8)+bank; color:=(atrib and $3c) shl 2; flipx:=(atrib and $40)<>0; flipy:=(atrib and $80)<>0; sx:=x+(tx shl 3); sy:=real_ty shl 3; put_gfx_sprite(nchar,color,flipx,flipy,0); actualiza_gfx_sprite(sx,sy,1,0); end; end; end; actualiza_trozo_final(0,16,256,224,1); end; procedure eventos_suna_hw; begin if event.arcade then begin //P1 if arcade_input.down[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 $fe) else marcade.in0:=(marcade.in0 or 1); 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 $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //P2 if arcade_input.down[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 $fe) else marcade.in1:=(marcade.in1 or 1); 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 $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); end; end; procedure hardhead_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; if f=239 then begin z80_0.change_irq(HOLD_LINE); update_video_hardhead; end; end; eventos_suna_hw; video_sync; end; end; function hardhead_getbyte(direccion:word):byte; var res_prot:byte; begin case direccion of 0..$7fff,$c000..$d7ff,$e000..$ffff:hardhead_getbyte:=memoria[direccion]; $8000..$bfff:hardhead_getbyte:=rom_bank[banco_rom,(direccion and $3fff)]; $d800..$d9ff:hardhead_getbyte:=buffer_paleta[direccion and $1ff]; $da00:case hardhead_ip of 0:hardhead_getbyte:=marcade.in0; 1:hardhead_getbyte:=marcade.in1; 2:hardhead_getbyte:=marcade.dswa; 3:hardhead_getbyte:=marcade.dswb; end; $da80:hardhead_getbyte:=soundlatch2; $dd80..$ddff:begin //proteccion if (not(direccion) and $20)<>0 then res_prot:=$20 else res_prot:=0; if (protection_val and $80)<>0 then begin if (protection_val and $4)<>0 then res_prot:=res_prot or $80; if (protection_val and $1)<>0 then res_prot:=res_prot or $4; end else begin if ((direccion xor protection_val) and $1)<>0 then res_prot:=res_prot or $84; end; hardhead_getbyte:=res_prot; end; end; end; procedure cambiar_color(dir:word); var tmp_color:byte; color:tcolor; begin tmp_color:=buffer_paleta[dir]; color.r:=pal4bit(tmp_color shr 4); color.g:=pal4bit(tmp_color); tmp_color:=buffer_paleta[dir+1]; color.b:=pal4bit(tmp_color shr 4); set_pal_color(color,dir shr 1); end; procedure hardhead_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; $c000..$d7ff,$e000..$ffff:memoria[direccion]:=valor; $d800..$d9ff:if buffer_paleta[direccion and $1ff]<>valor then begin buffer_paleta[direccion and $1ff]:=valor; cambiar_color(direccion and $1fe); end; $da00:hardhead_ip:=valor; $da80:banco_rom:=valor and $f; $db00:soundlatch:=valor; $db80:main_screen.flip_main_screen:=(valor and 4)<>0; $dd80..$ddff:if (valor and $80)<>0 then protection_val:=valor //proteccion else protection_val:=direccion and 1; end; end; function hardhead_snd_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$c000..$c7ff:hardhead_snd_getbyte:=mem_snd[direccion]; $a000:hardhead_snd_getbyte:=ym3812_0.read; $c800:hardhead_snd_getbyte:=ym3812_0.status; $d800:hardhead_snd_getbyte:=soundlatch; end; end; procedure hardhead_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $a000:ym3812_0.control(valor); $a001:ym3812_0.write(valor); $a002:ay8910_0.control(valor); $a003:ay8910_0.write(valor); $c000..$c7ff:mem_snd[direccion]:=valor; $d000:soundlatch2:=valor; end; end; procedure hardhead_play_sound; begin ym3812_0.update; ay8910_0.update; tsample[dac_tsample,sound_status.posicion_sonido]:=dac_value; end; procedure hardhead_snd; begin z80_1.change_irq(HOLD_LINE); end; procedure hardhead_portaw(valor:byte); begin // At boot: ff (ay reset) -> 00 (game writes ay enable) -> f9 (game writes to port A). // Then game writes f9 -> f1 -> f9. Is bit 3 stop/reset? if ((dac_play=$e9) and (valor=$f9)) then begin dac_index:=dac_sample and $f; dac_pos:=0; timers.enabled(dac_timer,true); end else if ((dac_play=$b9) and (valor=$f9)) then begin // second sample rom dac_index:=((dac_sample shr 4) and $f)+$10; dac_pos:=0; timers.enabled(dac_timer,true); end; dac_play:=valor; end; procedure hardhead_portbw(valor:byte); begin dac_sample:=valor; end; procedure dac_sound; begin dac_value:=suna_dac[dac_pos+dac_index*$1000]; dac_pos:=dac_pos+1; if dac_pos=$1000 then begin timers.enabled(dac_timer,false); dac_value:=0; end; end; //Hard Head 2 procedure update_video_hardhead2; var bank,code,sy,y,dimx,dimy,f,ty,tx,attr,srcx,srcy,srcpg:byte; gfxbank,nchar,addr,colorbank,sx,x,mx,color:word; flipx,flipy,multisprite,tile_flipx,tile_flipy:boolean; begin mx:=0; fill_full_screen(1,$ff); for f:=0 to $bf do begin colorbank:=0; y:=sprite_bank[$1d00+(f*4)]; code:=sprite_bank[$1d01+(f*4)]; x:=sprite_bank[$1d02+(f*4)]; bank:=sprite_bank[$1d03+(f*4)]; flipx:=false; flipy:=false; case (code and $c0) of $c0:begin dimx:=4; dimy:=32; srcx:=(code and $e)*2; srcy:=0; flipx:=(code and $1)<>0; gfxbank:=bank and $1f; srcpg:=(code shr 4) and 3; end; $80:begin dimx:=2; dimy:=32; srcx:=(code and $f)*2; srcy:=0; gfxbank:=bank and $1f; srcpg:=(code shr 4) and 3; end; // hardhea2: fire code=52/54 bank=a4; player code=02/04/06 bank=08; arrow:code=16 bank=27 $40:begin dimx:=4; dimy:=4; srcx:=(code and $e)*2; flipx:=(code and $01)<>0; flipy:=(bank and $10)<>0; srcy:=(((bank and $80) shr 4)+(bank and $04)+((not(bank) shr 4) and 2))*2; srcpg:=((code shr 4) and 3)+4; gfxbank:=bank and $3; gfxbank:=gfxbank+4; // brickzn: 06,a6,a2,b2->6 colorbank:=(bank and 8) shr 3; end; else begin dimx:=2; dimy:=2; srcx:=(code and $f)*2; srcy:=(((bank and $80) shr 4)+(bank and $04)+((not(bank) shr 4) and 3))*2; srcpg:=(code shr 4) and 3; gfxbank:=bank and $03; end; end; multisprite:=(((code and $80)<>0) and ((bank and $80)<>0)); if (bank and $40)<>0 then x:=x-$100; y:=($100-y-dimy*8) and $ff; // Multi Sprite if multisprite then begin mx:=mx+dimx*8; x:=mx; end else mx:=x; gfxbank:=gfxbank*$400; for ty:=0 to dimy-1 do begin for tx:=0 to dimx-1 do begin addr:=srcpg*$20*$20; if flipx then addr:=addr+((srcx+(dimx-tx-1)) and $1f)*$20 else addr:=addr+((srcx+tx) and $1f)*$20; if flipy then addr:=addr+((srcy+(dimy-ty-1)) and $1f) else addr:=addr+((srcy+ty) and $1f); attr:=sprite_bank[addr*2+1]; tile_flipx:=(attr and $40)<>0; tile_flipy:=(attr and $80)<>0; sx:=x+tx*8; sy:=(y+ty*8) and $ff; if (flipx) then tile_flipx:=not(tile_flipx); if (flipy) then tile_flipy:=not(tile_flipy); color:=(((attr shr 2) and $f) xor colorbank);//+$10*palettebank; nchar:=sprite_bank[addr*2+0]+(attr and $3)*$100+gfxbank; put_gfx_sprite(nchar,color shl 4,tile_flipx,tile_flipy,0); actualiza_gfx_sprite(sx,sy,1,0); end; end; end; actualiza_trozo_final(0,16,256,224,1); end; procedure hardhead2_principal; var frame_m,frame_s,frame_dac:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; frame_dac:=z80_2.tframes; while EmuStatus=EsRuning do begin for f:=0 to 255 do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; //Sound DAC z80_2.run(frame_dac); frame_dac:=frame_dac+z80_2.tframes-z80_2.contador; case f of 22:vblank:=0; 111:if haz_nmi then z80_0.change_nmi(PULSE_LINE); 239:begin z80_0.change_irq(HOLD_LINE); update_video_hardhead2; vblank:=$40; end; end; end; eventos_suna_hw; video_sync; end; end; function hardhead2_getbyte(direccion:word):byte; begin case direccion of 0..$7fff:if z80_0.opcode then hardhead2_getbyte:=mem_opcodes[direccion] else hardhead2_getbyte:=memoria[direccion]; $8000..$bfff:hardhead2_getbyte:=rom_bank[banco_rom,direccion and $3fff]; $c000:hardhead2_getbyte:=marcade.in0; $c001:hardhead2_getbyte:=marcade.in1; $c002:hardhead2_getbyte:=marcade.dswa; $c003:hardhead2_getbyte:=marcade.dswb; $c080:hardhead2_getbyte:=$bf or vblank; $c600..$c7ff:hardhead2_getbyte:=buffer_paleta[direccion-$c600]; $c800..$dfff:hardhead2_getbyte:=ram_bank[banco_ram,direccion-$c800]; $e000..$ffff:hardhead2_getbyte:=sprite_bank[banco_sprite*$2000+(direccion and $1fff)]; end; end; procedure hardhead2_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; $c200:banco_sprite:=(valor shr 1) and 1; $c280,$c28c:banco_rom:=valor and $f; $c300:main_screen.flip_main_screen:=(valor and 1)<>0; $c380:haz_nmi:=(valor and 1)<>0; $c400:; //leds $c500:soundlatch:=valor; $c507,$c556,$c560:banco_ram:=1; $c508:banco_sprite:=0; $c522,$c528,$c533:banco_ram:=0; $c50f:banco_sprite:=1; $c600..$c7ff:begin direccion:=direccion-$c600; if buffer_paleta[direccion]<>valor then begin buffer_paleta[direccion]:=valor; cambiar_color(direccion and $1fe); end; end; $c800..$dfff:ram_bank[banco_ram,direccion-$c800]:=valor; $e000..$ffff:sprite_bank[banco_sprite*$2000+(direccion and $1fff)]:=valor; end; end; function hardhead2_snd_getbyte(direccion:word):byte; begin case direccion of 0..$bfff,$e000..$e7ff:hardhead2_snd_getbyte:=mem_snd[direccion]; $f800:hardhead2_snd_getbyte:=soundlatch; end; end; procedure hardhead2_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; $c000:ym3812_0.control(valor); $c001:ym3812_0.write(valor); $c002:ay8910_0.control(valor); $c003:ay8910_0.write(valor); $e000..$e7ff:mem_snd[direccion]:=valor; $f000:soundlatch2:=valor; end; end; function hardhead2_dac_getbyte(direccion:word):byte; begin hardhead2_dac_getbyte:=mem_misc[direccion]; end; procedure hardhead2_dac_putbyte(direccion:word;valor:byte); begin end; function hardhead2_dac_inbyte(puerto:word):byte; begin if (puerto and $ff)=0 then hardhead2_dac_inbyte:=soundlatch2; end; procedure hardhead2_dac_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of 0:dac_0.data8_w(valor); 1:dac_1.data8_w(valor); 2:dac_2.data8_w(valor); 3:dac_3.data8_w(valor); end; end; procedure hardhead2_snd(status:byte); begin z80_1.change_irq(status); end; procedure hardhead2_play_sound; begin ym3812_0.update; ay8910_0.update; dac_0.update; dac_1.update; dac_2.update; dac_3.update; end; //Main procedure reset_suna_hw; begin z80_0.reset; z80_1.reset; ay8910_0.reset; ym3812_0.reset; if main_vars.tipo_maquina=68 then begin dac_0.reset; dac_1.reset; dac_2.reset; dac_3.reset; end; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; banco_rom:=0; soundlatch:=0; soundlatch2:=0; hardhead_ip:=0; dac_sample:=0; dac_play:=0; dac_value:=0; dac_index:=0; dac_pos:=0; banco_sprite:=0; banco_ram:=0; haz_nmi:=false; vblank:=0; end; function iniciar_suna_hw:boolean; const pc_x:array[0..7] of dword=(3,2,1,0,11,10,9,8); pc_y:array[0..7] of dword=(0*16,1*16,2*16,3*16,4*16,5*16,6*16,7*16); swaptable_hh:array[0..7] of byte=(1,1,0,1,1,1,1,0); swaptable_data_hh2:array[0..7] of byte=(1,1,0,1,0,1,1,0); swaptable_lines_hh2:array[0..79] of byte=( 1,1,1,1,0,0,1,1, 0,0,0,0,0,0,0,0, // 8000-ffff not used 1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0); swaptable_opcodes_hh2:array[0..31] of byte=( 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1, 1,1,0,1,1,1,1,1,1,1,1,1,0,1,0,0); xortable_hh2:array[0..31] of byte=( $04,$04,$00,$04,$00,$04,$00,$00,$04,$45,$00,$04,$00,$04,$00,$00, $04,$45,$00,$04,$00,$04,$00,$00,$04,$04,$00,$04,$00,$04,$00,$00); var f,addr:dword; valor,table:byte; mem_final:array[0..$4ffff] of byte; memoria_temp:array[0..$7ffff] of byte; begin llamadas_maquina.reset:=reset_suna_hw; iniciar_suna_hw:=false; iniciar_audio(false); screen_init(1,512,512,false,true); iniciar_video(256,224); case main_vars.tipo_maquina of 67:begin llamadas_maquina.bucle_general:=hardhead_principal; llamadas_maquina.fps_max:=59.1; //Main CPU z80_0:=cpu_z80.create(6000000,256); z80_0.change_ram_calls(hardhead_getbyte,hardhead_putbyte); //Sound CPU z80_1:=cpu_z80.create(3000000,256); z80_1.change_ram_calls(hardhead_snd_getbyte,hardhead_snd_putbyte); z80_1.init_sound(hardhead_play_sound); timers.init(z80_1.numero_cpu,3000000/(60*4),hardhead_snd,nil,true); //sound chips ym3812_0:=ym3812_chip.create(YM3812_FM,3000000); ay8910_0:=ay8910_chip.create(1500000,AY8910,0.8); ay8910_0.change_io_calls(nil,nil,hardhead_portaw,hardhead_portbw); //Y para el DAC 8Khz dac_timer:=timers.init(z80_1.numero_cpu,3000000/8000,dac_sound,nil,false); //cargar roms y rom en bancos if not(roms_load(@memoria_temp,hardhead_rom)) then exit; for f:=0 to $f do copymemory(@rom_bank[f,0],@memoria_temp[$8000+(f*$4000)],$4000); for f:=0 to $7fff do begin table:=((f and $0c00) shr 10) or ((f and $4000) shr 12); if (swaptable_hh[table])<>0 then memoria[f]:=BITSWAP8(memoria_temp[f],7,6,5,3,4,2,1,0) xor $58 else memoria[f]:=memoria_temp[f]; end; //cargar sonido if not(roms_load(@mem_snd,hardhead_sound)) then exit; if not(roms_load(@memoria_temp,hardhead_dac)) then exit; //Convierto los samples for f:=0 to $7fff do begin suna_dac[f*2]:=shortint((((memoria_temp[f] and $f) shl 4) xor $80))*$100; suna_dac[(f*2)+1]:=shortint(((memoria_temp[f] and $f0) xor $80))*$100; end; dac_tsample:=init_channel; //convertir sprites e invertirlos, solo hay sprites!! if not(roms_load(@memoria_temp,hardhead_sprites)) then exit; for f:=0 to $3ffff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(0,8,8,$2000); gfx[0].trans[15]:=true; gfx_set_desc_data(4,0,8*8*2,$20000*8+0,$20000*8+4,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //DIP marcade.dswa:=$fc; marcade.dswb:=$77; marcade.dswa_val:=@hardhead_dip_a; marcade.dswb_val:=@hardhead_dip_b; end; 68:begin llamadas_maquina.bucle_general:=hardhead2_principal; //Main CPU z80_0:=cpu_z80.create(6000000,256); z80_0.change_ram_calls(hardhead2_getbyte,hardhead2_putbyte); //Sound CPU z80_1:=cpu_z80.create(6000000,256); z80_1.change_ram_calls(hardhead2_snd_getbyte,hardhead2_snd_putbyte); z80_1.init_sound(hardhead2_play_sound); //cargar sonido if not(roms_load(@mem_snd,hardhead2_sound)) then exit; //DAC CPU z80_2:=cpu_z80.create(6000000,256); z80_2.change_ram_calls(hardhead2_dac_getbyte,hardhead2_dac_putbyte); z80_2.change_io_calls(hardhead2_dac_inbyte,hardhead2_dac_outbyte); if not(roms_load(@mem_misc,hardhead2_pcm)) then exit; //sound chips ym3812_0:=ym3812_chip.create(YM3812_FM,3000000); ym3812_0.change_irq_calls(hardhead2_snd); ay8910_0:=ay8910_chip.create(1500000,AY8910,0.3); dac_0:=dac_chip.create(1); dac_1:=dac_chip.create(1); dac_2:=dac_chip.create(1); dac_3:=dac_chip.create(1); //cargar roms if not(roms_load(@memoria_temp,hardhead2_rom)) then exit; //desencriptarlas //Primero muevo los datos a su sitio copymemory(@mem_final,@memoria_temp,$50000); for f:=0 to $4ffff do begin addr:=f; if (swaptable_lines_hh2[(f and $ff000) shr 12])<>0 then addr:=(addr and $f0000) or BITSWAP16(addr,15,14,13,12,11,10,9,8,6,7,5,4,3,2,1,0); memoria_temp[f]:=mem_final[addr]; end; //Pongo los bancos ROM for f:=0 to $f do copymemory(@rom_bank[f,0],@memoria_temp[$10000+(f*$4000)],$4000); //Y ahora desencripto los opcodes for f:=0 to $7fff do begin table:=(f and 1) or ((f and $400) shr 9) or ((f and $7000) shr 10); valor:=memoria_temp[f]; valor:=BITSWAP8(valor,7,6,5,3,4,2,1,0) xor $41 xor xortable_hh2[table]; if (swaptable_opcodes_hh2[table])<>0 then valor:=BITSWAP8(valor,5,6,7,4,3,2,1,0); mem_opcodes[f]:=valor; end; //Y despues los datos for f:=0 to $7fff do begin if (swaptable_data_hh2[(f and $7000) shr 12])<>0 then memoria[f]:=BITSWAP8(memoria_temp[f],5,6,7,4,3,2,1,0) xor $41 else memoria[f]:=memoria_temp[f]; end; //convertir sprites e invertirlos, solo hay sprites!! if not(roms_load(@memoria_temp,hardhead2_sprites)) then exit; for f:=0 to $7ffff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(0,8,8,$4000); gfx[0].trans[15]:=true; gfx_set_desc_data(4,0,8*8*2,$40000*8+0,$40000*8+4,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //DIP marcade.dswa:=$5f; marcade.dswb:=$F7; marcade.dswa_val:=@hardhead2_dip_a; marcade.dswb_val:=@hardhead2_dip_b; end; end; //final reset_suna_hw; iniciar_suna_hw:=true; end; end.
unit GX_CopyComponentNames; interface uses GX_Experts, ActnList; type TCopyComponentNamesExpert = class(TGX_Expert) protected procedure UpdateAction(Action: TCustomAction); override; public constructor Create; override; function GetActionCaption: string; override; class function GetName: string; override; procedure Execute(Sender: TObject); override; function HasConfigOptions: Boolean; override; function HasDesignerMenuItem: Boolean; override; end; implementation uses SysUtils, Classes, Clipbrd, ToolsAPI, GX_OtaUtils; { TCopyComponentNamesExpert } procedure TCopyComponentNamesExpert.UpdateAction(Action: TCustomAction); begin Action.Enabled := GxOtaFormEditorHasSelectedComponent; end; procedure TCopyComponentNamesExpert.Execute(Sender: TObject); var FormEditor: IOTAFormEditor; SelCount: Integer; CurrentComponent: IOTAComponent; Names: TStringList; ComponentName: WideString; i: Integer; begin if not GxOtaTryGetCurrentFormEditor(FormEditor) then Exit; SelCount := FormEditor.GetSelCount; Names := TStringList.Create; try for i := 0 to SelCount - 1 do begin CurrentComponent := FormEditor.GetSelComponent(i); ComponentName := GxOtaGetComponentName(CurrentComponent); if ComponentName <> '' then Names.Add(ComponentName); end; Clipboard.AsText := Trim(Names.Text); finally FreeAndNil(Names); end end; constructor TCopyComponentNamesExpert.Create; begin inherited Create; //ShortCut := scCtrl + scShift + Ord('N'); end; function TCopyComponentNamesExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Copy Component &Names'; begin Result := SMenuCaption; end; class function TCopyComponentNamesExpert.GetName: string; begin Result := 'CopyComponentNames'; end; function TCopyComponentNamesExpert.HasConfigOptions: Boolean; begin Result := False; end; function TCopyComponentNamesExpert.HasDesignerMenuItem: Boolean; begin Result := True; end; initialization RegisterGX_Expert(TCopyComponentNamesExpert); end.
Program Interpolation; var x ,Result ,Max ,Min : Real; i,j,n : integer; T : Array [-1..100,0..100] of Real; procedure Lagrange; function L(m:Byte):Real; var p:Real; Begin p:=1; for j:=0 to n do if(j <> m) then p:=p * (x - T[-1,j]) / (T[-1,m] - T[-1,j]); L:=p; end; begin Result:=0; for i:=0 to n do Result:=Result + L(i) * T[0,i]; end; procedure Newton; function C(m:Byte):Real; var p:Real; Begin p:=1; for j:=0 to (m-1) do p:=p * (x - T[-1,j]); C:=p; end; Begin for i:=1 to n do for j:= 0 to (n-i) do T[i,j]:=(T[i-1,j+1] - T[i-1,j]) / (T[-1,j+i] - T[-1,j]); Result:= T[0,0]; for i:=1 to n do Result:= Result + C(i) * T[i,0]; end; procedure Forward; var r:Real; function C(m:Byte):Real; var p:Real; Begin p:=1; for j:=0 to (m-1) do p:=p * (r-j) / (j+1); C:=p; end; Begin r:=(x - T[-1,0]) / (T[-1,1] - T[-1,0]); for i:=1 to n do for j:=0 to (n-i) do T[i,j]:=(T[i-1,j+1] - T[i-1,j]); Result:=T[0,0]; for i:=1 to n do Result:=Result + C(i) * T[i,0]; end; procedure Backward; var r:Real; function C(m:Byte):Real; var p:Real; Begin p:=1; for j:=0 to (m-1) do p:=p * (r+j) / (j+1); C:=p; end; Begin r:=(x - T[-1,0]) / (T[-1,0] - T[-1,1]); for i:=1 to n do for j:=0 to (n-i) do T[i,j]:=(T[i-1,j] - T[i-1,j+1]); Result:=T[0,0]; for i:=1 to n do Result:=Result + C(i) * T[i,0]; end; procedure Decision; var Count:Byte; Input:Char; Begin Count:=1; for i:=0 to (n-2) do if (abs(2*T[-1,i+1] - T[-1,i] - T[-1,i+2]) < 0.000000001) then Count:=Count + 1; if (Count = n) and (n>1) then Begin if ((T[-1,1] - T[-1,0]) > 0) then Forward else Backward end else Begin Writeln; Writeln('Input <L> for "Lagrange Method" '); Writeln(' or <N> for "Newton Method" and then press Enter:'); Repeat Read(Input); until(Upcase(Input)='L') or (Upcase(Input)='N'); if (Input = 'L') then Lagrange else Newton; end; end; Begin Write('Enter N:'); Readln(n); n:=n-1; Writeln('Enter the X values:'); for j:= 0 to n do begin Readln(T[-1,j]); if j=0 then begin Max:=T[-1,j]; Min:=T[-1,j]; end; if (T[-1,j] > Max) then Max:=T[-1,j]; if (T[-1,j] < Min) then Min:=T[-1,j]; end; Writeln('Enter the f(x) values:'); for j:= 0 to n do Readln(T[0,j]); Repeat Write('Enter A Valid X:'); Readln(x); Until (x>=Min) and (x<=Max); Decision; writeln; writeln('Result = ',Result:10:9); 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$ } unit IdStreamNET; interface uses IdObjs, IdGlobal; type TIdStreamHelperNET = class public class function ReadBytes(AStream: TIdStream; var VBytes: TIdBytes; ACount: Integer = -1; AOffset: Integer = 0): Integer; static; class procedure Write( const AStream: TIdStream; const ABytes: TIdBytes; const ACount: Integer = -1); static; end; implementation class function TIdStreamHelperNET.ReadBytes(AStream: TIdStream; var VBytes: TIdBytes; ACount, AOffset: Integer): Integer; var aActual:Integer; begin Assert(AStream<>nil); Result:=0; if VBytes = nil then begin SetLength(VBytes, 0); end; //check that offset<length(buffer)? offset+count? //is there a need for this to be called with an offset into a nil buffer? aActual:=ACount; if aActual = -1 then begin aActual := AStream.Size - AStream.Position; end; //this prevents eg reading 0 bytes at Offset=10 from allocating memory if aActual=0 then begin Exit; end; if Length(VBytes) < (AOffset+aActual) then begin SetLength(VBytes, AOffset+aActual); end; Assert(VBytes<>nil); Result := AStream.Read(VBytes, AOffset, AActual); end; class procedure TIdStreamHelperNET.Write(const AStream: TIdStream; const ABytes: TIdBytes; const ACount: Integer); var aActual:Integer; begin Assert(AStream<>nil); aActual:=ACount; //should we raise assert instead of this nil check? if ABytes <> nil then begin if aActual = -1 then begin aActual := Length(ABytes); end else begin aActual := Min(aActual, Length(ABytes)); end; if aActual > 0 then begin AStream.Write(ABytes, aActual); end; end; end; end.
unit TransparentBitmaps; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, CommCtrl, SysUtils, Classes, Graphics, Dibs; const clrDefault = CLR_DEFAULT; clrNone = CLR_NONE; const dsTransparent = ILD_TRANSPARENT; dsNormal = ILD_NORMAL; dsMask = ILD_MASK; dsImage = ILD_IMAGE; dsBlend = ILD_BLEND; // Same as Blend50 dsBlend25 = ILD_BLEND25; dsBlend50 = ILD_BLEND50; dsOverlayMask = ILD_OVERLAYMASK; type TTransparentBitmap = class private fImageList : HIMAGELIST; fBitmap : HBITMAP; fMask : HBITMAP; private fBackgroundColor : TColorRef; fTransparentColor : TColorRef; fStyle : integer; fWidth : integer; fHeight : integer; fBitCount : integer; procedure SetBackgroundColor( aColor : TColorRef ); procedure SetTransparentColor( aColor : TColorRef ); procedure SetStyle( NewStyle : integer ); procedure Release; function AddBitmapAndMask( ImageList : HIMAGELIST; BitmapHandle : HBITMAP ) : boolean; function GetImageList( aWidth, aHeight, aBitCount : integer ) : HIMAGELIST; procedure FreeImageList; protected procedure SetHandle( BitmapHandle : HBITMAP ); procedure Update; public property TransparentColor : TColorRef read fTransparentColor write SetTransparentColor; property BackgroundColor : TColorRef read fBackgroundColor write SetBackgroundColor; property Width : integer read fWidth; property Height : integer read fHeight; property BitCount : integer read fBitCount; property Style : integer read fStyle write SetStyle; property Handle : HBITMAP write SetHandle; constructor Create; destructor Destroy; override; procedure LoadFromDib( DibHeader : PDib; DibBits : pointer ); virtual; procedure LoadFromStream( Stream : TStream ); procedure LoadFromResourceName( Instance : THandle; const ResourceName : string ); procedure LoadFromResourceID( Instance : THandle; ResourceId : Integer ); procedure LoadFromFile( const Filename : string ); function Empty : boolean; procedure DrawOnDC( dc : HDC; x, y : integer ); procedure Draw( Canvas : TCanvas; x, y : integer ); end; implementation // Visuals procedure TTransparentBitmap.DrawOnDC( dc : HDC; x, y : integer ); begin assert( dc <> 0, 'NULL DC in TransparentBitmaps.TTransparentBitmap.DrawOnDC!!' ); assert( not Empty, 'Image empty in TransparentBitmaps.TTransparentBitmap.DrawOnDC!!' ); ImageList_Draw( fImageList, 0, dc, x, y, fStyle ); end; procedure TTransparentBitmap.Draw( Canvas : TCanvas; x, y : integer ); begin DrawOnDC( Canvas.Handle, x, y ); end; procedure TTransparentBitmap.SetStyle( NewStyle : integer ); begin fStyle := NewStyle; end; procedure TTransparentBitmap.SetTransparentColor( aColor : TColorRef ); begin fTransparentColor := aColor; Update; end; procedure TTransparentBitmap.SetBackgroundColor( aColor : TColorRef ); begin assert( not Empty, 'NULL ImageList in TransparentBitmaps.TTransparentBitmap.SetBackgroundColor!!' ); fBackgroundColor := aColor; ImageList_SetBkColor( fImageList, fBackgroundColor ); end; function TTransparentBitmap.GetImageList( aWidth, aHeight, aBitCount : integer ) : HIMAGELIST; begin Result := ImageList_Create( aWidth, aHeight, ILC_MASK or aBitCount, 1, 1 ); if Result <> 0 then begin fWidth := aWidth; fHeight := aHeight; fBitCount := aBitCount; ImageList_SetBkColor( fImageList, fBackgroundColor ); end; end; function TTransparentBitmap.AddBitmapAndMask( ImageList : HIMAGELIST; BitmapHandle : HBITMAP ) : boolean; var ImageInfo : TImageInfo; begin Result := false; if ImageList <> 0 then if ImageList_AddMasked( ImageList, BitmapHandle, TransparentColor ) <> -1 then begin ImageList_GetImageInfo( ImageList, 0, ImageInfo ); fBitmap := ImageInfo.hbmImage; fMask := ImageInfo.hbmMask; Result := true; end; end; procedure TTransparentBitmap.FreeImageList; begin if fImageList <> 0 then ImageList_Destroy( fImageList ); fImageList := 0; end; procedure TTransparentBitmap.SetHandle( BitmapHandle : HBITMAP ); var BitmapInfo : Windows.TBITMAP; begin FreeImageList; if GetObject( BitmapHandle, sizeof(BitmapInfo), @BitmapInfo ) <> 0 then with BitmapInfo do begin fImageList := GetImageList( bmWidth, bmHeight, bmBitsPixel * bmPlanes ); if not AddBitmapAndMask( fImageList, BitmapHandle ) then FreeImageList; end; end; procedure TTransparentBitmap.Update; var ilHandle : HIMAGELIST; ImageInfo : TImageInfo; begin if not Empty then begin ImageList_GetImageInfo( fImageList, 0, ImageInfo ); ilHandle := GetImageList( Width, Height, BitCount ); if AddBitmapAndMask( ilHandle, ImageInfo.hbmImage ) then begin FreeImageList; fImageList := ilHandle; end else ImageList_Destroy( ilHandle ); end; end; function TTransparentBitmap.Empty : boolean; begin Result := not Assigned( Self) or ( fImageList = 0 ); end; // Object creation/destruction procedure TTransparentBitmap.Release; begin FreeImageList; end; constructor TTransparentBitmap.Create; begin inherited; fStyle := dsNormal; fBackgroundColor := clrNone; end; destructor TTransparentBitmap.Destroy; begin Release; inherited; end; // Bitmap loading methods ----- procedure TTransparentBitmap.LoadFromDib( DibHeader : PDib; DibBits : pointer ); var bmpHandle : HBITMAP; begin bmpHandle := SectionFromDib( DibHeader, DibBits ); try SetHandle( bmpHandle ); finally DeleteObject( bmpHandle ); end; end; procedure TTransparentBitmap.LoadFromStream( Stream : TStream ); var Dib : PDib; begin Dib := DibLoadFromStream( Stream, false ); try LoadFromDib( Dib, DibPtr( Dib ) ); finally DibFree( Dib ); end; end; procedure TTransparentBitmap.LoadFromResourceName( Instance : THandle; const ResourceName : string ); var Stream : TCustomMemoryStream; begin Stream := TResourceStream.Create( Instance, ResourceName, RT_BITMAP ); try LoadFromStream( Stream ) finally Stream.Free; end; end; procedure TTransparentBitmap.LoadFromResourceID( Instance : THandle; ResourceId : Integer ); var Stream : TCustomMemoryStream; begin Stream := TResourceStream.CreateFromID( Instance, ResourceId, RT_BITMAP ); try LoadFromStream( Stream ) finally Stream.Free; end; end; procedure TTransparentBitmap.LoadFromFile( const Filename : string ); var Stream : TStream; begin Stream := TFileStream.Create( FileName, fmOpenRead or fmShareDenyWrite ); try LoadFromStream( Stream ); finally Stream.Free; end; end; end.
unit uProjetos; interface uses System.Generics.Collections, System.SysUtils; type TProjeto = class private FValor: Currency; FId: Integer; FNome: String; procedure SetValor(const Value: Currency); public property Id: Integer read FId write FId; property Nome: String read FNome write FNome; property Valor: Currency read FValor write SetValor; end; TProjetos = class private FItems: TList<TProjeto>; FValorMaxProjeto: Currency; FMaxItens: Integer; function SortearValor: Currency; public constructor Create; destructor Destroy; override; procedure SetItem(Projeto: TProjeto); procedure SetValorMaxProjeto(Value: Currency); procedure SetItensMaximo(Value: Integer); procedure GerarItensAleatorios(QtdMaxItens: Integer; ValorMaxProjeto: Currency); property Items: TList<TProjeto> read FItems; end; implementation { TProjetos } procedure TProjeto.SetValor(const Value: Currency); begin FValor := Value; end; { TProjetos } constructor TProjetos.Create; begin inherited; FItems := TList<TProjeto>.Create; end; destructor TProjetos.Destroy; begin FItems.Free; inherited; end; procedure TProjetos.GerarItensAleatorios(QtdMaxItens: Integer; ValorMaxProjeto: Currency); var I: Integer; begin SetItensMaximo(QtdMaxItens); SetValorMaxProjeto(ValorMaxProjeto); for I := 0 to FMaxItens-1 do begin FItems.Add(TProjeto.Create); FItems[I].Id := I+1; FItems[I].Nome := 'Projeto ' + IntToStr(I+1); FItems[I].Valor := SortearValor; end; end; procedure TProjetos.SetItem(Projeto: TProjeto); begin FItems.Add(Projeto); end; procedure TProjetos.SetItensMaximo(Value: Integer); begin if Value <= 0 then raise Exception.Create('TProjetos - Quantidade de itens dos projetos deve ser no mínimo um'); FMaxItens := Value; end; procedure TProjetos.SetValorMaxProjeto(Value: Currency); begin if Value <= 0 then raise Exception.Create('TProjetos - Valor máximo dos projetos deve ser maior que zero'); FValorMaxProjeto := Value; end; function TProjetos.SortearValor: Currency; begin Randomize; Result := Random(Trunc(FValorMaxProjeto)); end; end.
unit AddressNoteUnit; interface uses REST.Json.Types, System.Generics.Collections, Generics.Defaults, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, EnumsUnit; type /// <summary> /// Address Note /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/note.dtd /// </remarks> TAddressNote = class(TGenericParameters) private [JSONName('note_id')] [Nullable] FNoteId: NullableInteger; [JSONName('route_id')] [Nullable] FRouteId: NullableString; [JSONName('route_destination_id')] FRouteDestinationId: Integer; [JSONName('upload_id')] [Nullable] FUploadId: NullableString; [JSONName('ts_added')] [Nullable] FTimestampAdded: NullableInteger; [JSONName('lat')] [Nullable] FLatitude: NullableDouble; [JSONName('lng')] [Nullable] FLongitude: NullableDouble; [JSONName('activity_type')] [Nullable] FActivityType: NullableString; [JSONName('contents')] [Nullable] FContents: NullableString; [JSONName('upload_type')] [Nullable] FUploadType: NullableString; [JSONName('upload_url')] [Nullable] FUploadUrl: NullableString; [JSONName('upload_extension')] [Nullable] FUploadExtension: NullableString; [JSONName('device_type')] [Nullable] FDeviceType: NullableString; function GetDeviceType: TDeviceType; procedure SetDeviceType(const Value: TDeviceType); function GetUploadType: TUploadType; procedure SetUploadType(const Value: TUploadType); public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// The id of the note in the system /// </summary> property NoteId: NullableInteger read FNoteId write FNoteId; /// <summary> /// Route ID /// </summary> property RouteId: NullableString read FRouteId write FRouteId; /// <summary> /// Route Destination ID /// </summary> property RouteDestinationId: Integer read FRouteDestinationId write FRouteDestinationId; /// <summary> /// The unique and randomly generated ID of the file attachment that is associated with this note /// </summary> property UploadId: NullableString read FUploadId write FUploadId; /// <summary> /// The unix timestamp when the note was added /// </summary> property TimestampAdded: NullableInteger read FTimestampAdded write FTimestampAdded; /// <summary> /// Latitude /// </summary> property Latitude: NullableDouble read FLatitude write FLatitude; /// <summary> /// Longitude /// </summary> property Longitude: NullableDouble read FLongitude write FLongitude; /// <summary> /// Activity Type /// </summary> property ActivityType: NullableString read FActivityType write FActivityType; /// <summary> /// Contents /// </summary> property Contents: NullableString read FContents write FContents; /// <summary> /// Upload Type /// </summary> property UploadType: TUploadType read GetUploadType write SetUploadType; /// <summary> /// The direct CDN URL of the attachment uploaded with a note /// </summary> property UploadUrl: NullableString read FUploadUrl write FUploadUrl; /// <summary> /// The extension of the attachment ('pdf', 'csv' etc) /// </summary> property UploadExtension: NullableString read FUploadExtension write FUploadExtension; /// <summary> /// Device type ('web', 'phone', 'ipad', 'android phone', 'android tablet' etc) /// </summary> property DeviceType: TDeviceType read GetDeviceType write SetDeviceType; end; TAddressNoteArray = TArray<TAddressNote>; TAddressNoteList = TObjectList<TAddressNote>; function SortAddressNotes(AddressNotes: TAddressNoteArray): TAddressNoteArray; implementation function SortAddressNotes(AddressNotes: TAddressNoteArray): TAddressNoteArray; begin SetLength(Result, Length(AddressNotes)); if Length(AddressNotes) = 0 then Exit; TArray.Copy<TAddressNote>(AddressNotes, Result, Length(AddressNotes)); TArray.Sort<TAddressNote>(Result, TComparer<TAddressNote>.Construct( function (const AddressNote1, AddressNote2: TAddressNote): Integer begin Result := AddressNote1.NoteId.Compare(AddressNote2.NoteId); end)); end; { TAddressNote } constructor TAddressNote.Create; begin Inherited Create; FRouteDestinationId := 0; FLatitude := NullableDouble.Null; FLongitude := NullableDouble.Null; FNoteId := NullableInteger.Null; FRouteId := NullableString.Null; FUploadId := NullableString.Null; FTimestampAdded := NullableInteger.Null; FActivityType := NullableString.Null; FContents := NullableString.Null; FUploadType := NullableString.Null; FUploadUrl := NullableString.Null; FUploadExtension := NullableString.Null; FDeviceType := NullableString.Null; end; function TAddressNote.Equals(Obj: TObject): Boolean; var Other: TAddressNote; begin Result := False; if not (Obj is TAddressNote) then Exit; Other := TAddressNote(Obj); Result := (FNoteId = Other.FNoteId) and (FRouteId = Other.FRouteId) and (FRouteDestinationId = Other.FRouteDestinationId) and (FUploadId = Other.FUploadId) and (FTimestampAdded = Other.FTimestampAdded) and (FLatitude = Other.FLatitude) and (FLongitude = Other.FLongitude) and (FActivityType = Other.FActivityType) and (FContents = Other.FContents) and (FUploadType = Other.FUploadType) and (FUploadUrl = Other.FUploadUrl) and (FUploadExtension = Other.FUploadExtension) and (FDeviceType = Other.FDeviceType); end; function TAddressNote.GetDeviceType: TDeviceType; var DeviceType: TDeviceType; begin Result := TDeviceType.UnknownDevice; if FDeviceType.IsNotNull then for DeviceType := Low(TDeviceType) to High(TDeviceType) do if (FDeviceType = TDeviceTypeDescription[DeviceType]) then Exit(DeviceType); end; function TAddressNote.GetUploadType: TUploadType; var UploadType: TUploadType; begin Result := TUploadType.UnknownUploadType; if FUploadType.IsNotNull then for UploadType := Low(TUploadType) to High(TUploadType) do if (FUploadType = TUploadTypeDescription[UploadType]) then Exit(UploadType); end; procedure TAddressNote.SetDeviceType(const Value: TDeviceType); begin FDeviceType := TDeviceTypeDescription[Value]; end; procedure TAddressNote.SetUploadType(const Value: TUploadType); begin FUploadType := TUploadTypeDescription[Value]; end; end.
unit Test.ModelsDTO; interface uses Spring; type TAddressRecord = record Street: string; NumHouse: integer; end; TNewAddressRecord = record Street: string; Num_House: integer; end; TAddressDTO = class private FStreet: string; FNumHouse: integer; procedure SetNumHouse(const Value: integer); procedure SetStreet(const Value: string); public property Street: string read FStreet write SetStreet; property NumHouse: integer read FNumHouse write SetNumHouse; end; {$M+} TPersonDTO = class private FAge: Nullable<integer>; FLastName: string; FMiddleName: Nullable<string>; FAddress: TAddressDTO; FFirstName: string; FStatus: Nullable<integer>; procedure SetAddress(const Value: TAddressDTO); procedure SetAge(const Value: Nullable<integer>); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); procedure SetMiddleName(const Value: Nullable<string>); procedure SetStatus(const Value: Nullable<integer>); public Post: string; published property LastName: string read FLastName write SetLastName; property FirstName: string read FFirstName write SetFirstName; property MiddleName: Nullable<string> read FMiddleName write SetMiddleName; property Age: Nullable<integer> read FAge write SetAge; property Address: TAddressDTO read FAddress write SetAddress; property Status: Nullable<integer> read FStatus write SetStatus; end; TUserDTO = class private FFullName: string; FAddress: string; procedure SetAddress(const Value: string); procedure SetFullName(const Value: string); public property FullName: string read FFullName write SetFullName; property Address: string read FAddress write SetAddress; end; TSimplePersonDTO = class private FMiddle_Name: string; FFirst_Name: string; FLast_Name: string; FStatus: Nullable<integer>; procedure SetFirst_Name(const Value: string); procedure SetLast_Name(const Value: string); procedure SetMiddle_Name(const Value: string); procedure SetStatus(const Value: Nullable<integer>); public Post: string; published property Last_Name: string read FLast_Name write SetLast_Name; property First_Name: string read FFirst_Name write SetFirst_Name; property Middle_Name: string read FMiddle_Name write SetMiddle_Name; property Status: Nullable<integer> read FStatus write SetStatus; end; implementation { TUserDTO } procedure TUserDTO.SetAddress(const Value: string); begin FAddress := Value; end; procedure TUserDTO.SetFullName(const Value: string); begin FFullName := Value; end; { TPersonDTO } procedure TPersonDTO.SetAddress(const Value: TAddressDTO); begin FAddress := Value; end; procedure TPersonDTO.SetAge(const Value: Nullable<integer>); begin FAge := Value; end; procedure TPersonDTO.SetFirstName(const Value: string); begin FFirstName := Value; end; procedure TPersonDTO.SetLastName(const Value: string); begin FLastName := Value; end; procedure TPersonDTO.SetMiddleName(const Value: Nullable<string>); begin FMiddleName := Value; end; procedure TPersonDTO.SetStatus(const Value: Nullable<integer>); begin FStatus := Value; end; { TAddressDTO } procedure TAddressDTO.SetNumHouse(const Value: integer); begin FNumHouse := Value; end; procedure TAddressDTO.SetStreet(const Value: string); begin FStreet := Value; end; { TSimplePersonDTO } procedure TSimplePersonDTO.SetFirst_Name(const Value: string); begin FFirst_Name := Value; end; procedure TSimplePersonDTO.SetLast_Name(const Value: string); begin FLast_Name := Value; end; procedure TSimplePersonDTO.SetMiddle_Name(const Value: string); begin FMiddle_Name := Value; end; procedure TSimplePersonDTO.SetStatus(const Value: Nullable<integer>); begin FStatus := Value; end; end.
unit TestRouteSamplesUnit; interface uses TestFramework, Classes, SysUtils, DateUtils, BaseTestOnlineExamplesUnit; type TTestRouteSamples = class(TTestOnlineExamples) private published procedure AddRoute; procedure AddOrderToRoute; procedure GetListByText; procedure RemoveRoute; end; implementation uses AddressUnit, DataObjectUnit, RouteParametersUnit, EnumsUnit, MultipleDepotMultipleDriverTestDataProviderUnit, OptimizationParametersUnit, IOptimizationParametersProviderUnit, CommonTypesUnit, NullableBasicTypesUnit; var FRouteId: NullableString; FAllRouteIds: TArray<String>; FOptimizationProblemId: NullableString; procedure TTestRouteSamples.AddOrderToRoute; {var Route: TDataObjectRoute; Parameters: TRouteParameters; Addresses: TOrderedAddress; ErrorString: String; RouteId: String;} begin // todo 4: сделать unit-тест { RouteId := 'qwe'; Parameters := TRouteParameters.Create; Parameters.RouteName := 'Test Route'; Parameters.Optimize := TOptimize.Time; Parameters.AlgorithmType := TAlgorithmType.TSP; Parameters.MemberId := '1116'; Parameters.DisableOptimization := False; try Route := FRoute4MeManager.Route.AddOrder(FRouteId, Parameters, Addresses, ErrorString); CheckNull(Route); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Parameters); end;} end; procedure TTestRouteSamples.AddRoute; var DataProvider: IOptimizationParametersProvider; DataObject: TDataObject; OptimizationProblemDetails: TDataObject; Parameters: TOptimizationParameters; ErrorString: String; i: integer; begin FOptimizationProblemId := NullableString.Null; FRouteId := NullableString.Null; DataProvider := TMultipleDepotMultipleDriverTestDataProvider.Create; try Parameters := DataProvider.OptimizationParameters; try DataObject := FRoute4MeManager.Optimization.Run(Parameters, ErrorString); try CheckNotNull(DataObject); CheckEquals(EmptyStr, ErrorString); FOptimizationProblemId := DataObject.OptimizationProblemId; finally FreeAndNil(DataObject); end; finally FreeAndNil(Parameters); end; OptimizationProblemDetails := FRoute4MeManager.Optimization.Get( FOptimizationProblemId, ErrorString); try CheckNotNull(OptimizationProblemDetails); CheckEquals(EmptyStr, ErrorString); CheckTrue(Length(OptimizationProblemDetails.Routes) > 0); FRouteId := OptimizationProblemDetails.Routes[0].RouteId; SetLength(FAllRouteIds, Length(OptimizationProblemDetails.Routes) - 1); for i := 1 to High(OptimizationProblemDetails.Routes) do FAllRouteIds[i - 1] := OptimizationProblemDetails.Routes[i].RouteId; finally FreeAndNil(OptimizationProblemDetails); end; finally DataProvider := nil; end; end; procedure TTestRouteSamples.GetListByText; var ErrorString: String; Text: String; Routes: TDataObjectRouteList; begin Text := 'SomeUniqueText#d27zz'; Routes := FRoute4MeManager.Route.GetList(Text, ErrorString); try CheckNotNull(Routes); CheckEquals(0, Routes.Count); finally FreeAndNil(Routes); end; Text := 'Tbilisi'; Routes := FRoute4MeManager.Route.GetList(Text, ErrorString); try CheckNotNull(Routes); CheckTrue(Routes.Count > 0); finally FreeAndNil(Routes); end; end; procedure TTestRouteSamples.RemoveRoute; var ErrorString: String; DeletedRouteIds: TStringArray; begin DeletedRouteIds := FRoute4MeManager.Route.Delete(['qwe'], ErrorString); CheckEquals(0, Length(DeletedRouteIds)); CheckNotEquals(EmptyStr, ErrorString); CheckTrue(FRouteId.IsNotNull); DeletedRouteIds := FRoute4MeManager.Route.Delete([FRouteId], ErrorString); CheckEquals(1, Length(DeletedRouteIds)); CheckEquals(FRouteId, DeletedRouteIds[0]); CheckEquals(EmptyStr, ErrorString); DeletedRouteIds := FRoute4MeManager.Route.Delete(FAllRouteIds, ErrorString); CheckTrue(Length(DeletedRouteIds) > 0); CheckEquals(EmptyStr, ErrorString); end; initialization RegisterTest('Examples\Online\Routes\', TTestRouteSamples.Suite); end.
unit IngAlertWindow; interface uses Windows, SysUtils, Classes, Controls, Graphics, Forms, Types, ExtCtrls; type TPopupLocation = (plLeft, plRight); TAlertDirection = (adNone, adUp, adDown); TBackgroundStyle = (bgsAuto, bgsSolid, bgsVerticalGradient, bgsHorizontalGradient); TVerticalAlignment = (taAlignTop, taAlignBottom, taVerticalCenter); TWrapKind = (wkNone, wkEllipsis, wkPathEllipsis, wkWordWrap); TIngAlertWindow = class(TCustomControl) private fAlertDirection: TAlertDirection; fAlignment: TAlignment; fBackgroundStyle: TBackgroundStyle; fBorderColor: TColor; fCloseDelay: Cardinal; fCloseTimer: TTimer; fColor: TColor; fHeaderColor: TColor; fHeaderBackgroundStyle: TBackgroundStyle; fHeaderFont: TFont; fHeaderSize: Byte; fHeaderText: WideString; fHeaderToColor: TColor; fOnClose: TNotifyEvent; fOnPopup: TNotifyEvent; fPopupLocation: TPopupLocation; fText: WideString; fToColor: TColor; fVerticalAlignment: TVerticalAlignment; fWordWrap: Boolean; procedure DrawFmtText(Canvas: TCanvas; TextRect: TRect; Value: WideString; Alignment: TAlignment; VerticalAlignment: TVerticalAlignment; WrapKind: TWrapKind; BiDiMode: TBiDiMode; Disabled: Boolean = False); procedure DrawGradient(ACanvas: TCanvas; ARect: TRect; AHoricontal: Boolean; AFromColor, AToColor: TColor); procedure DrawHeader(Rect: TRect); virtual; procedure DrawHeaderContent(Rect: TRect); virtual; procedure DrawMessage(Rect: TRect); virtual; procedure DrawMessageContent(Rect: TRect); virtual; procedure DrawTextRect(Canvas: TCanvas; ARect: TRect; Text: WideString; BidiMode: TBiDiMode = bdLeftToRight); function GetHeaderRect: TRect; function GetTextRect: TRect; function Lighten(C: TColor; Amount: Integer): TColor; procedure SetHeaderSize(const Value: Byte); procedure SetHeaderText(const Value: WideString); procedure SetCloseDelay(const Value: Cardinal); procedure SetBackgroundStyle(const Value: TBackgroundStyle); procedure SetHeaderBackgroundStyle(const Value: TBackgroundStyle); procedure SetAlignment(const Value: TAlignment); procedure SetHeaderFont(const Value: TFont); procedure SetText(const Value: WideString); procedure SetVerticalAlignment(const Value: TVerticalAlignment); procedure SetWordWrap(const Value: Boolean); procedure SetColor(const Value: TColor); procedure SetHeaderColor(const Value: TColor); procedure SetHeaderToColor(const Value: TColor); procedure SetToColor(const Value: TColor); procedure SetBorderColor(const Value: TColor); protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure DoCloseTimer(Sender: TObject); public procedure Close; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoClosed; dynamic; procedure DoPopup; dynamic; procedure Paint; override; procedure Popup; overload; procedure Popup(const Text: WideString; CloseDelay: Cardinal = 0); overload; published property Alignment: TAlignment read fAlignment write SetAlignment default taCenter; property BackgroundStyle: TBackgroundStyle read fBackgroundStyle write SetBackgroundStyle default bgsAuto; property BiDiMode; property BorderColor: TColor read fBorderColor write SetBorderColor default clActiveCaption; property CloseDelay: Cardinal read fCloseDelay write SetCloseDelay default 0; property Color: TColor read fColor write SetColor default clWindow; property Font; property HeaderBackgroundStyle: TBackgroundStyle read fHeaderBackgroundStyle write SetHeaderBackgroundStyle default bgsAuto; property HeaderColor: TColor read fHeaderColor write SetHeaderColor default clActiveCaption; property HeaderFont: TFont read fHeaderFont write SetHeaderFont; property HeaderSize: Byte read fHeaderSize write SetHeaderSize default 18; property HeaderToColor: TColor read fHeaderToColor write SetHeaderToColor default clGradientActiveCaption; property HeaderText: WideString read fHeaderText write SetHeaderText; property OnClick; property OnClose: TNotifyEvent read FOnClose write FOnClose; property OnDblClick; property OnPopup: TNotifyEvent read FOnPopup write FOnPopup; property PopupLocation: TPopupLocation read fPopupLocation write fPopupLocation default plRight; property Showing; property Text: WideString read fText write SetText; property ToColor: TColor read fToColor write SetToColor default clBtnFace; property VerticalAlignment: TVerticalAlignment read fVerticalAlignment write SetVerticalAlignment default taVerticalCenter; property WordWrap: Boolean read fWordWrap write SetWordWrap default false; end; procedure Register; var IsUnicodeSupported: Boolean; implementation procedure Register; begin RegisterComponents('Standard', [TIngAlertWindow]); end; { TIngAlertWindow } function TIngAlertWindow.Lighten(C: TColor; Amount: Integer): TColor; var R, G, B: Integer; begin if C < 0 then C := GetSysColor(C and $000000FF); R := C and $FF + Amount; G := C shr 8 and $FF + Amount; B := C shr 16 and $FF + Amount; if R < 0 then R := 0 else if R > 255 then R := 255; if G < 0 then G := 0 else if G > 255 then G := 255; if B < 0 then B := 0 else if B > 255 then B := 255; Result := R or (G shl 8) or (B shl 16); end; {procedure DrawGradient(ACanvas: TCanvas; ARect: TRect; AHoricontal: Boolean; AColors: array of TColor); type RGBArray = array[0..2] of Byte; var merkp: TColor; merks: TPenStyle; merkw: integer; x, y, z, stelle, mx, bis, faColorsh, mass, x1, x2, y1, y2: Integer; Faktor: Double; A: RGBArray; B: array of RGBArray; begin mx := High(AColors); if mx < 1 then begin if mx = 0 then begin ACanvas.Brush.Color := AColors[0]; ACanvas.FillRect(ARect); end; Exit; end; if AHoricontal then mass := ARect.Right - ARect.Left else mass := ARect.Bottom - ARect.Top; SetLength(b, mx + 1); for x := 0 to mx do begin AColors[x] := ColorToRGB(AColors[x]); b[x][0] := GetRValue(AColors[x]); b[x][1] := GetGValue(AColors[x]); b[x][2] := GetBValue(AColors[x]); end; merkw := ACanvas.Pen.Width; merks := ACanvas.Pen.Style; merkp := ACanvas.Pen.Color; ACanvas.Pen.Width := 1; ACanvas.Pen.Style := psSolid; faColorsh := Round(mass / mx); x1 := ARect.Left; x2 := ARect.Right; y1 := ARect.Top; y2 := ARect.Bottom; for y := 0 to mx - 1 do begin if y = mx - 1 then bis := mass - y * faColorsh - 1 else bis := faColorsh; for x := 0 to bis do begin Stelle := x + y * faColorsh; faktor := x / bis; for z := 0 to 3 do a[z] := Trunc(b[y][z] + ((b[y + 1][z] - b[y][z]) * Faktor)); ACanvas.Pen.Color := RGB(a[0], a[1], a[2]); if AHoricontal then begin x1 := ARect.Left + Stelle; x2 := ARect.Left + Stelle; end else begin y1 := ARect.Top + Stelle; y2 := ARect.Top + Stelle; end; ACanvas.MoveTo(x1, y1); ACanvas.LineTo(x2, y2); end; end; b := nil; ACanvas.Pen.Width := merkw; ACanvas.Pen.Style := merks; ACanvas.Pen.Color := merkp; end;} procedure TIngAlertWindow.DrawGradient(ACanvas: TCanvas; ARect: TRect; AHoricontal: Boolean; AFromColor, AToColor: TColor); var i, n, x1, x2, y1, y2: Integer; Faktor: Double; StartRGB, EndRGB: array[0..2] of Byte; begin if AHoricontal then n := ARect.Right - ARect.Left - 1 else n := ARect.Bottom - ARect.Top - 1; AFromColor := ColorToRGB(AFromColor); AToColor := ColorToRGB(AToColor); StartRGB[0] := GetRValue(AFromColor); StartRGB[1] := GetGValue(AFromColor); StartRGB[2] := GetBValue(AFromColor); EndRGB[0] := GetRValue(AToColor); EndRGB[1] := GetGValue(AToColor); EndRGB[2] := GetBValue(AToColor); ACanvas.Pen.Width := 1; ACanvas.Pen.Style := psSolid; x1 := ARect.Left; x2 := ARect.Right; y1 := ARect.Top; y2 := ARect.Bottom; if AHoricontal then for i := 0 to n do begin Faktor := i / n; ACanvas.Pen.Color := RGB( Trunc(StartRGB[0] + ((EndRGB[0] - StartRGB[0]) * Faktor)), Trunc(StartRGB[1] + ((EndRGB[1] - StartRGB[1]) * Faktor)), Trunc(StartRGB[2] + ((EndRGB[2] - StartRGB[2]) * Faktor)) ); x1 := ARect.Left + i; ACanvas.MoveTo(x1, y1); ACanvas.LineTo(x1, y2); end else for i := 0 to n do begin Faktor := i / n; ACanvas.Pen.Color := RGB( Trunc(StartRGB[0] + ((EndRGB[0] - StartRGB[0]) * Faktor)), Trunc(StartRGB[1] + ((EndRGB[1] - StartRGB[1]) * Faktor)), Trunc(StartRGB[2] + ((EndRGB[2] - StartRGB[2]) * Faktor)) ); y1 := ARect.Top + i; ACanvas.MoveTo(x1, y1); ACanvas.LineTo(x2, y1); end; end; constructor TIngAlertWindow.Create(AOwner: TComponent); begin inherited; Visible := csDesigning in ComponentState; Width := 210; Height := 140; fAlertDirection := adDown; fPopupLocation := plRight; fBorderColor := clActiveCaption; fCloseTimer := TTimer.Create(Self); fCloseTimer.Enabled := false; fCloseTimer.OnTimer := DoCloseTimer; fCloseDelay := 0; fHeaderText := 'Внимание'; fHeaderColor := clActiveCaption; fHeaderToColor := clGradientActiveCaption; fHeaderFont := TFont.Create; fHeaderFont.Style := [fsBold]; fHeaderBackgroundStyle := bgsAuto; fHeaderSize := 18; fText := 'Сообщение'; fColor := clWindow; fToColor := clBtnFace; fBackgroundStyle := bgsAuto; fVerticalAlignment := taVerticalCenter; fAlignment := taCenter; fWordWrap := false; end; procedure TIngAlertWindow.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do if not (csDesigning in ComponentState) then begin WndParent := GetDesktopWindow; Style := WS_CLIPSIBLINGS or WS_CHILD; ExStyle := WS_EX_TOPMOST or WS_EX_TOOLWINDOW; WindowClass.Style := CS_DBLCLKS or CS_SAVEBITS and not (CS_HREDRAW or CS_VREDRAW); end; end; procedure TIngAlertWindow.CreateWnd; begin inherited; end; destructor TIngAlertWindow.Destroy; begin fCloseTimer.Enabled := false; fCloseTimer.FreeAndNil; fHeaderFont.FreeAndNil; inherited; end; procedure TIngAlertWindow.Paint; var BorderRect: TRect; begin BorderRect := ClientRect; BorderRect.Bottom := Height; Canvas.Brush.Color := fBorderColor; Canvas.FrameRect(BorderRect); InflateRect(BorderRect, -1, -1); Canvas.Brush.Color := clWhite; Canvas.FrameRect(BorderRect); DrawHeader(GetHeaderRect); DrawHeaderContent(GetHeaderRect); DrawMessage(Rect(1, fHeaderSize + 1, ClientWidth - 1, Height - 1)); DrawMessageContent(Rect(1, fHeaderSize + 1, ClientWidth - 1, Height - 1)); end; procedure TIngAlertWindow.Popup; var X, Y, i, Delta, YD: Integer; begin X := Screen.WorkAreaLeft; Y := 0; ShowWindow(Handle, SW_HIDE); if fPopupLocation = plRight then X := Screen.WorkAreaWidth - Width; case fAlertDirection of adDown: Y := Screen.WorkAreaHeight - Height; adNone: ; adUp: Y := Screen.WorkAreaTop; end; Delta := Height div 10; YD := 0; for i := 0 to 10 do begin case fAlertDirection of adDown: YD := Y + Height - Delta * i; adUp: YD := Y - Height + Delta * i; end; SetWindowPos(Handle, HWND_TOPMOST, X, YD, Width, Height, SWP_SHOWWINDOW); Repaint; Sleep(1); end; SetWindowPos(Handle, HWND_TOPMOST, X, Y, Width, Height, SWP_SHOWWINDOW); fCloseTimer.Enabled := (fCloseDelay > 0); end; procedure TIngAlertWindow.SetHeaderSize(const Value: Byte); begin fHeaderSize := Value; Invalidate; end; function TIngAlertWindow.GetHeaderRect: TRect; begin Result := Rect(1, 1, ClientWidth - 1, 2 + fHeaderSize); end; function TIngAlertWindow.GetTextRect: TRect; begin Result := Rect(1, fHeaderSize + 1, ClientWidth - 2, ClientHeight - 2); with Result do begin Left := 12; Top := 7 + fHeaderSize; Right := ClientWidth - 12; Bottom := Height - 6; end; end; procedure TIngAlertWindow.DrawHeader(Rect: TRect); var PaintRect: TRect; begin PaintRect := Rect; Dec(PaintRect.Bottom, 1); case fHeaderBackgroundStyle of bgsSolid: DrawGradient(Canvas, PaintRect, false, fHeaderColor, fHeaderColor); bgsAuto, bgsVerticalGradient, bgsHorizontalGradient: DrawGradient(Canvas, PaintRect, (fHeaderBackgroundStyle = bgsHorizontalGradient), fHeaderColor, fHeaderToColor); end; Canvas.Pen.Color := fHeaderColor; Canvas.Polyline([Point(1, PaintRect.Bottom - 2), Point(ClientWidth - 1, PaintRect.Bottom - 2)]); Canvas.Pen.Color := fHeaderToColor; Canvas.Polyline([Point(1, PaintRect.Bottom - 1), Point(ClientWidth - 1, PaintRect.Bottom - 1)]); end; procedure TIngAlertWindow.DrawTextRect(Canvas: TCanvas; ARect: TRect; Text: WideString; BidiMode: TBiDiMode = bdLeftToRight); var Flags: Integer; StringText: string; begin Flags := DT_NOPREFIX or DT_VCENTER or DT_END_ELLIPSIS or DT_EXTERNALLEADING or DT_SINGLELINE or DT_LEFT; if BidiMode = bdRightToLeft then Flags := Flags or DT_RTLREADING; Canvas.Brush.Style := bsClear; if IsUnicodeSupported then DrawTextW(Canvas.Handle, PWideChar(Text), Length(Text), ARect, Flags) else begin StringText := Text; Windows.DrawText(Canvas.Handle, PAnsiChar(StringText), Length(StringText), ARect, Flags); end; Canvas.Brush.Style := bsSolid; end; procedure TIngAlertWindow.DrawFmtText(Canvas: TCanvas; TextRect: TRect; Value: WideString; Alignment: TAlignment; VerticalAlignment: TVerticalAlignment; WrapKind: TWrapKind; BiDiMode: TBiDiMode; Disabled: Boolean = False); var Flags: Integer; R: TRect; StringText: string; begin R := TextRect; Flags := DT_NOPREFIX; { don't replace & char } with Canvas do begin case WrapKind of wkNone: Flags := Flags or DT_SINGLELINE; wkEllipsis: Flags := Flags or DT_END_ELLIPSIS or DT_SINGLELINE; wkPathEllipsis: Flags := Flags or DT_PATH_ELLIPSIS; wkWordWrap: Flags := Flags or DT_WORDBREAK; end; case Alignment of taLeftJustify: Flags := Flags or DT_LEFT; taRightJustify: Flags := Flags or DT_RIGHT; taCenter: Flags := Flags or DT_CENTER; end; case VerticalAlignment of taAlignTop: Flags := Flags or DT_TOP; taVerticalCenter: Flags := Flags or DT_VCENTER; taAlignBottom: Flags := Flags or DT_BOTTOM; end; if BiDiMode <> bdLeftToRight then Flags := Flags or DT_RTLREADING; Brush.Style := bsClear; if IsUnicodeSupported then begin if Disabled then begin OffsetRect(R, 1, 1); Font.Color := clBtnHighlight; end; DrawTextW(Canvas.Handle, PWideChar(Value), Length(Value), R, Flags); if Disabled then begin OffsetRect(R, -1, -1); Font.Color := clBtnShadow; DrawTextW(Canvas.Handle, PWideChar(Value), Length(Value), R, Flags); end; end else begin StringText := Value; Windows.DrawText(Canvas.Handle, PAnsiChar(StringText), Length(StringText), R, Flags); end; Brush.Style := Graphics.bsSolid; end; end; procedure TIngAlertWindow.DrawHeaderContent(Rect: TRect); begin Canvas.Font.Assign(fHeaderFont); DrawTextRect(Canvas, Types.Rect(4, 1, ClientWidth, fHeaderSize), fHeaderText, BiDiMode); end; procedure TIngAlertWindow.SetHeaderText(const Value: WideString); begin fHeaderText := Value; Invalidate; end; procedure TIngAlertWindow.Close; begin DoClosed; end; procedure TIngAlertWindow.DoCloseTimer(Sender: TObject); begin DoClosed; end; procedure TIngAlertWindow.SetCloseDelay(const Value: Cardinal); begin fCloseDelay := Value; fCloseTimer.Interval := fCloseDelay; end; procedure TIngAlertWindow.DrawMessage(Rect: TRect); var PaintRect: TRect; begin PaintRect := Rect; case fBackgroundStyle of bgsSolid: DrawGradient(Canvas, PaintRect, false, fColor, fColor); bgsAuto, bgsVerticalGradient, bgsHorizontalGradient: DrawGradient(Canvas, PaintRect, (fBackgroundStyle = bgsHorizontalGradient), fColor, fToColor); end; end; procedure TIngAlertWindow.DrawMessageContent(Rect: TRect); var WrapKind: TWrapKind; begin Canvas.Font.Assign(Self.Font); if WordWrap then WrapKind := wkWordWrap else WrapKind := wkNone; DrawFmtText(Canvas, GetTextRect, Text, Alignment, VerticalAlignment, WrapKind, BiDiMode); end; procedure TIngAlertWindow.SetBackgroundStyle(const Value: TBackgroundStyle); begin fBackgroundStyle := Value; if Value = bgsAuto then begin Color := clWindow; ToColor := clBtnFace; end; Invalidate; end; procedure TIngAlertWindow.SetHeaderBackgroundStyle(const Value: TBackgroundStyle); begin fHeaderBackgroundStyle := Value; if Value = bgsAuto then begin HeaderColor := clActiveCaption; HeaderToColor := clGradientActiveCaption; end; Invalidate; end; procedure TIngAlertWindow.SetAlignment(const Value: TAlignment); begin FAlignment := Value; Invalidate; end; procedure TIngAlertWindow.SetHeaderFont(const Value: TFont); begin fHeaderFont.Assign(Value); Repaint; end; procedure TIngAlertWindow.SetText(const Value: WideString); begin FText := Value; Invalidate; end; procedure TIngAlertWindow.SetVerticalAlignment( const Value: TVerticalAlignment); begin fVerticalAlignment := Value; Invalidate; end; procedure TIngAlertWindow.SetWordWrap(const Value: Boolean); begin fWordWrap := Value; Invalidate; end; procedure TIngAlertWindow.DoPopup; begin if Assigned(fOnPopup) then fOnPopup(Self); end; procedure TIngAlertWindow.DoClosed; begin fCloseTimer.Enabled := False; ShowWindow(Handle, SW_HIDE); if Assigned(fOnClose) then fOnClose(Self); end; procedure TIngAlertWindow.Popup(const Text: WideString; CloseDelay: Cardinal); begin if Text <> '' then fText := Text; fCloseDelay := CloseDelay; Popup; end; procedure TIngAlertWindow.SetColor(const Value: TColor); begin fColor := Value; Invalidate; end; procedure TIngAlertWindow.SetHeaderColor(const Value: TColor); begin fHeaderColor := Value; Invalidate; end; procedure TIngAlertWindow.SetHeaderToColor(const Value: TColor); begin fHeaderToColor := Value; Invalidate; end; procedure TIngAlertWindow.SetToColor(const Value: TColor); begin fToColor := Value; Invalidate; end; procedure TIngAlertWindow.SetBorderColor(const Value: TColor); begin fBorderColor := Value; Invalidate; end; end.
unit Controller.Observer.Item; interface uses Controller.Observer.Interfaces, System.Generics.Collections; type TControllerObserverItem = class(TInterfacedObject, iSubjectItem) private FList : TList<iObserverItem>; public constructor Create; destructor Destroy; override; class function New : iSubjectItem; function Add(Value : iObserverItem) : iSubjectItem; function Notify(Value : TRecordItem) : iSubjectItem; end; implementation uses System.SysUtils; function TControllerObserverItem.Add(Value: iObserverItem): iSubjectItem; begin Result := Self; FList.Add(Value); end; constructor TControllerObserverItem.Create; begin FList := TList<iObserverItem>.Create; end; destructor TControllerObserverItem.Destroy; begin FreeAndNil(FList); inherited; end; class function TControllerObserverItem.New : iSubjectItem; begin Result := Self.Create; end; function TControllerObserverItem.Notify(Value: TRecordItem): iSubjectItem; var I: Integer; begin Result := Self; for I := 0 to Pred(FList.Count) do FList[I].UpdateItem(Value); end; end.
unit InventionData; interface const tidMSXML = 'msxml'; type TInventionData = class public constructor Create(url : string); private fRoot : OleVariant; private function GetAttr(name : string) : string; function GetDesc : string; public property Attr[name : string] : string read GetAttr; property Desc : string read GetDesc; end; implementation uses ComObj; // TInventionData constructor TInventionData.Create(url : string); var O : OleVariant; begin inherited Create; O := CreateOLEObject(tidMSXML); try O.url := url; fRoot := O.root; except fRoot := Unassigned; end; end; function TInventionData.GetAttr(name : string) : string; begin try if not VarIsEmpty(fRoot) then result := fRoot.getAttribute(name) else result := ''; except result := ''; end; end; function TInventionData.GetDesc : string; begin try if not VarIsEmpty(fRoot) then result := fRoot.text else result := ''; except result := ''; end; end; end.
unit RemoveOptimizationResponseUnit; interface uses REST.Json.Types, GenericParametersUnit; type TRemoveOptimizationResponse = class(TGenericParameters) private [JSONName('status')] FStatus: boolean; [JSONName('removed')] FRemoved: Boolean; public property Status: boolean read FStatus write FStatus; property Removed: Boolean read FRemoved write FRemoved; end; implementation end.
{ File: HIToolbox/HIView.h Contains: HIView routines Version: HIToolbox-219.4.81~2 Copyright: © 2001-2005 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { File: HIView.p(.pas) } { } { Contains: CodeWarrior Pascal( GPC) translation of Apple's Mac OS X 10.3 HIView.h } { Translation compatible with make-gpc-interfaces.pl generated MWPInterfaces } { (GPCPInterfaces). For the 10.2 available APIs, the CodeWarrior Pascal translation } { is linkable with Mac OS X 10.2.x or higher CFM CarbonLib and the GPC translation is } { linkable with Mac OS X 10.2.x or higher Mach-O Carbon.framework. For the 10.3 } { available APIs, the CodeWarrior Pascal translation is only selectively linkable with } { Mac OS X 10.3.x or higher CFM CarbonLib and the GPC translation is linkable with Mac } { OS X 10.3.x or higher Mach-O Carbon.framework. } { } { Version: 1.1 } { } { Pascal Translation: Gale Paeper, <gpaeper@empirenet.com>, 2004 } { } { Copyright: Subject to the constraints of Apple's original rights, you're free to use this } { translation as you deem fit. } { } { Bugs?: This is an AS IS translation with no express guarentees of any kind. } { If you do find a bug, please help out the Macintosh Pascal programming community by } { reporting your bug finding and possible fix to either personal e-mail to Gale Paeper } { or a posting to the MacPascal mailing list. } { Change History (most recent first ): <4> 4/8/04 GRP Completed new additions from HIView.h, version HIToolbox-145.33~1. <3> ?/?/04 PNL Added most new additions from HIView.h, version HIToolbox-145.33~1. <2> 10/02/04 GRP Added support for GPC as well as CodeWarrior Pascal. <1> 9/8/03 GRP First Pascal translation of HIView.h, version HIToolbox-123.6~10. } { Translation assisted by: } {This file was processed by Dan's Source Converter} {version 1.3 (this version modified by Ingemar Ragnemalm)} { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit HIView; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFArray,CFBase,CGContext,CGImage,CarbonEventsCore,Drag,Events,Quickdraw,Menus,Appearance,Controls,CarbonEvents,HIGeometry,Icons,HIShape; {$ALIGN MAC68K} type HIViewRef = ControlRef; type HIViewID = ControlID; { * kHIViewWindowContentID * * Discussion: * The standard view ID for the content view of a window. * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } {GRP translation note: kHIViewWindowContentID is really a C language external constant exported from CarbonLib (Carbon.framework). Treating it as an externally declared variable works as long as it used as a READ ONLY variable. CodeWarrior Pascal has no capability for enforcing READ ONLY usage so it is up to the programmer to obey the READ ONLY rule. GPC does enforce READ ONLY usage with the attribute (const).} {WARNING: The CFM CarbonLib export for kHIViewWindowContentID is broken. For CFM CodeWarrior Pascal, some workarounds are: 1. Use CFBundle loading and CFBundleGetDataPointerForName to obtain the correct data. 2. For composting windows, the correct data can be obtained with code similar to: ignoreResult := GetRootControl( theWind, theContentRoot ); ignoreResult := GetControlID( theContentRoot, theContentControlID ); The correct data for kHIViewWindowContentID is in theContentControlID. } var kHIViewWindowContentID: HIViewID; external name '_kHIViewWindowContentID'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * kHIViewWindowGrowBoxID * * Discussion: * The standard view ID for the grow box view of a window. Not all * windows have grow boxes, so be aware that you might not find this * view if you look for it. * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } {GRP translation note: kHIViewWindowGrowBoxID is really a C language external constant exported from CarbonLib (Carbon.framework). Treating it as an externally declared variable works as long as it used as a READ ONLY variable. CodeWarrior Pascal has no capability for enforcing READ ONLY usage so it is up to the programmer to obey the READ ONLY rule. GPC does enforce READ ONLY usage with the attribute (const).} var kHIViewWindowGrowBoxID: HIViewID; external name '_kHIViewWindowGrowBoxID'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * Discussion: * HIViewZOrderOp } const { * Indicates we wish to order a view above another view. } kHIViewZOrderAbove = 1; { * Indicates we wish to order a view below another view. } kHIViewZOrderBelow = 2; type HIViewZOrderOp = UInt32; { * HIViewFrameMetrics * * Summary: * Describes the offsets from the structure to the content area of a * view; for example, the top metric is the difference between the * vertical coordinate of the top edge of the view’s structure * region and the vertical coordinate of the top edge of the view’s * content region. This structure is returned by a view in response * to a kEventControlGetFrameMetrics event. } type HIViewFrameMetrics = record { * Height of the top of the structure area. } top: Float32; { * Width of the left of the structure area. } left: Float32; { * Height of the bottom of the structure area. } bottom: Float32; { * Width of the right of the structure area. } right: Float32; end; {==============================================================================} { ATTRIBUTES } {==============================================================================} { * Summary: * View attributes are generally determined by clients of the view; * the view itself should observe the attributes and behave * accordingly. * * Discussion: * View Attributes } const { * When set, the control will send the command it generates to the * user focus and propagate as it would naturally from there. The * default is to send the command to itself and then to its parent * and so forth. } kHIViewAttributeSendCommandToUserFocus = 1 shl 0; { * Indicates that a text editing control should behave appropriately * for editing fields in a dialog; specifically, the control should * ignore the Return, Enter, Escape, and Tab keys, and allow them to * be processed by other participants in the event flow. Available on * Mac OS X 10.3 and later. } kHIViewAttributeIsFieldEditor = 1 shl 1; { * Legacy synonym for kHIViewAttributeSendCommandToUserFocus. Please * use it instead. } kHIViewSendCommandToUserFocus = kHIViewAttributeSendCommandToUserFocus; { * HIView features * * Summary: * View feature flags are generally determined by the view itself, * and are not typically changed by clients of the view. } const { * This view supports using the ghosting protocol when live tracking * is not enabled. } kHIViewFeatureSupportsGhosting = 1 shl 0; { * This view allows subviews to be embedded within it. } kHIViewFeatureAllowsSubviews = 1 shl 1; { * If this view is clicked, the keyboard focus should be set to this * view automatically. This is primarily used for edit text controls. } kHIViewFeatureGetsFocusOnClick = 1 shl 8; { * This view supports the live feedback protocol. Necessary to * implement live scroll bar tracking. Clients of a view should never * disable this. } kHIViewFeatureSupportsLiveFeedback = 1 shl 10; { * This view can be put into a radio group. Radio buttons and bevel * buttons report this behavior. } kHIViewFeatureSupportsRadioBehavior = 1 shl 11; { * This view supports the auto-toggle protocol and should at the very * least auto- toggle from off to on and back. The view can support a * carbon event for more advanced auto-toggling of its value. The tab * view supports this, for example, so that when a tab is clicked its * value changes automatically. } kHIViewFeatureAutoToggles = 1 shl 14; { * This is merely informational. Turning it off would not necessarily * disable any timer a view might be using, but it could obey this * bit if it so desired. } kHIViewFeatureIdlesWithTimer = 1 shl 23; { * This tells the control manager that the up button part increases * the value of the control instead of decreasing it. For example, * the Little Arrows (Spinner) control increase its value when the up * button is pressed. Scroll bars, on the other hand, decrease the * value when their up buttons are pressed. } kHIViewFeatureInvertsUpDownValueMeaning = 1 shl 24; { * This is an optimization for determining a view's opaque region. * When set, the view system just uses the view's structure region, * and can usually avoid having to call the view at all. } kHIViewFeatureIsOpaque = 1 shl 25; { * This is an optimization for determining what gets invalidated when * views are dirtied. For example, on a metal window, the content * view is actually fully transparent, so invalidating it doesn't * really help things. By telling the control manager that the view * is transparent and does not do any drawing, we can avoid trying to * invalidate it and instead invalidate views behind it. } kHIViewFeatureDoesNotDraw = 1 shl 27; { * Indicates to the Control Manager that this view doesn't use the * special part codes for indicator, inactive, and disabled. * Available in Mac OS X 10.3 and later. } kHIViewFeatureDoesNotUseSpecialParts = 1 shl 28; { * This is an optimization for determining the clickable region of a * window (used for metal windows, for example, when doing async * window dragging). The presence of this bit tells us not to bother * asking the control for the clickable region. A view like the * visual separator would set this bit. It's typically used in * conjunction with the kHIViewFeatureDoesNotDraw bit. } kHIViewFeatureIgnoresClicks = 1 shl 29; { * HIView valid feature sets * * Summary: * These are sets of features that are available on the version of * Mac OS X corresponding to that named in the constant. } const kHIViewValidFeaturesForPanther = $3B804D03; { * HIView feature synonyms * * Summary: * Legacy synonyms for HIView feature bit names. Please use the * newer names. } const kHIViewSupportsGhosting = kHIViewFeatureSupportsGhosting; kHIViewAllowsSubviews = kHIViewFeatureAllowsSubviews; kHIViewGetsFocusOnClick = kHIViewFeatureGetsFocusOnClick; kHIViewSupportsLiveFeedback = kHIViewFeatureSupportsLiveFeedback; kHIViewSupportsRadioBehavior = kHIViewFeatureSupportsRadioBehavior; kHIViewAutoToggles = kHIViewFeatureAutoToggles; kHIViewIdlesWithTimer = kHIViewFeatureIdlesWithTimer; kHIViewInvertsUpDownValueMeaning = kHIViewFeatureInvertsUpDownValueMeaning; kHIViewIsOpaque = kHIViewFeatureIsOpaque; kHIViewDoesNotDraw = kHIViewFeatureDoesNotDraw; kHIViewDoesNotUseSpecialParts = kHIViewFeatureDoesNotUseSpecialParts; kHIViewIgnoresClicks = kHIViewFeatureIgnoresClicks; type HIViewFeatures = UInt64; {==============================================================================} { VIEW PART CODES } {==============================================================================} type HIViewPartCode = ControlPartCode; HIViewPartCodePtr = ^HIViewPartCode; { * HIViewPartCodes * } const kHIViewNoPart = 0; kHIViewIndicatorPart = 129; kHIViewDisabledPart = 254; kHIViewInactivePart = 255; { * Use this constant when not referring to a specific part, but * rather the entire view. } kHIViewEntireView = kHIViewNoPart; { * HIView Meta-Parts * * Summary: * A meta-part is a part used in a call to the HIViewCopyShape API. * These parts are parts that might be defined by a view. They * define a region of a view. Along with these parts, you can also * pass in normal part codes to get the regions of those parts. Not * all views fully support this feature. } const { * The structure region is the total area over which the view draws. } kHIViewStructureMetaPart = -1; { * The content region is only defined by views that can embed other * views. It is the area that embedded content can live. } kHIViewContentMetaPart = -2; { * Mac OS X 10.2 or later } kHIViewOpaqueMetaPart = -3; { * Mac OS X 10.3 or later, only used for async window dragging. * Default is structure region. } kHIViewClickableMetaPart = -4; { * HIView Focus Parts * } const { * Tells view to clear its focus } kHIViewFocusNoPart = kHIViewNoPart; { * Tells view to focus on the next part } kHIViewFocusNextPart = -1; { * Tells view to focus on the previous part } kHIViewFocusPrevPart = -2; {==============================================================================} { CONTENT } {==============================================================================} type HIViewImageContentType = ControlContentType; type HIViewImageContentInfo = ControlImageContentInfo; type HIViewContentType = SInt16; { * HIViewContentTypes * } const { * The view has no content besides text. } kHIViewContentTextOnly = 0; { * The view has no content. } kHIViewContentNone = 0; { * The view's content is an IconSuiteRef. } kHIViewContentIconSuiteRef = 129; { * The view's content is an IconRef. } kHIViewContentIconRef = 132; { * The view's content is a CGImageRef. } kHIViewContentCGImageRef = 134; { * HIViewContentInfo } type HIViewContentInfo = record { * The type of content referenced in the content union. } contentType: HIViewContentType; case SInt16 of 0: ( iconSuite: IconSuiteRef; ); 1: ( iconRef: IconRef_fix; ); 2: ( imageRef: CGImageRef; ); end; type HIViewContentInfoPtr = ^HIViewContentInfo; {==============================================================================} { ERROR CODES } {==============================================================================} { * Discussion: * View/Control Error Codes } const { * This value will be returned from an HIView API or a Control * Manager API when an action that is only supported on a compositing * window is attempted on a non-compositing window. This doesn't * necessarily mean that the API is only callable for compositing * windows; sometimes the legality of the action is based on other * parameters of the API. See HIViewAddSubview for one particular use * of this error code. } errNeedsCompositedWindow = -30598; {==============================================================================} { HIOBJECT SUPPORT } { Setting Initial Bounds } { When creating a view using HIObjectCreate, you can set the initial bounds } { automatically by passing in an initialization event into HIObjectCreate } { with a kEventParamBounds parameter as typeHIRect or typeQDRectangle. } {==============================================================================} { The HIObject class ID for the HIView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIViewClassID CFSTRP('com.apple.hiview')} {$endc} {==============================================================================} { EMBEDDING } {==============================================================================} { * HIViewGetRoot() * * Discussion: * Returns the root view for a window. * * Mac OS X threading: * Not thread safe * * Parameters: * * inWindow: * The window to get the root for. * * Result: * The root view for the window, or NULL if an invalid window is * passed. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetRoot( inWindow: WindowRef ): HIViewRef; external name '_HIViewGetRoot'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewAddSubview() * * Discussion: * Adds a subview to the given parent. The new subview is added to * the front of the list of subviews (i.e., it is made topmost). * * The subview being added is not retained by the new parent view. * Do not release the view after adding it, or it will cease to * exist. All views in a window will be released automatically when * the window is destroyed. * * Mac OS X threading: * Not thread safe * * Parameters: * * inParent: * The view which will receive the new subview. * * inNewChild: * The subview being added. * * Result: * An operating system result code. * errNeedsCompositedWindow will be returned when you try to embed * into the content view in a non-compositing window; you can only * embed into the content view in compositing windows. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewAddSubview( inParent: HIViewRef; inNewChild: HIViewRef ): OSStatus; external name '_HIViewAddSubview'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewRemoveFromSuperview() * * Discussion: * Removes a view from its parent. * The subview being removed from the parent is not released and * still exists. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to remove. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewRemoveFromSuperview( inView: HIViewRef ): OSStatus; external name '_HIViewRemoveFromSuperview'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetSuperview() * * Discussion: * Returns a view's parent view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose parent you are interested in getting. * * Result: * An HIView reference, or NULL if this view has no parent or is * invalid. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetSuperview( inView: HIViewRef ): HIViewRef; external name '_HIViewGetSuperview'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetFirstSubview() * * Discussion: * Returns the first subview of a container. The first subview is * the topmost subview in z-order. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose subview you are fetching. * * Result: * An HIView reference, or NULL if this view has no subviews or is * invalid. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetFirstSubview( inView: HIViewRef ): HIViewRef; external name '_HIViewGetFirstSubview'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetLastSubview() * * Discussion: * Returns the last subview of a container. The last subview is the * bottommost subview in z-order. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose subview you are fetching. * * Result: * An HIView reference, or NULL if this view has no subviews or is * invalid. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetLastSubview( inView: HIViewRef ): HIViewRef; external name '_HIViewGetLastSubview'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetNextView() * * Discussion: * Returns the next view after the one given, in z-order. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to use as reference. * * Result: * An HIView reference, or NULL if this view has no view behind it * or is invalid. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetNextView( inView: HIViewRef ): HIViewRef; external name '_HIViewGetNextView'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetPreviousView() * * Discussion: * Returns the previous view before the one given, in z-order. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to use as reference. * * Result: * An HIView reference, or NULL if this view has no view in front of * it or is invalid. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetPreviousView( inView: HIViewRef ): HIViewRef; external name '_HIViewGetPreviousView'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewCountSubviews() * * Summary: * Counts the number of subviews embedded in a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to count subviews. * * outSubviewCount: * * Result: * The number of subviews of the specified view. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewCountSubviews( inView: HIViewRef ): CFIndex; external name '_HIViewCountSubviews'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetIndexedSubview() * * Summary: * Get the Nth subview of a view. * * Discussion: * Instead of calling HIViewGetIndexedSubview repeatedly, it may be * more efficient to iterate through the subviews of a view with * calls HIViewGetFirstSubview and HIViewGetNextView. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose indexed sub-view is being requested. * * inSubviewIndex: * The index of the subview to get. * * outSubview: * An HIViewRef to be filled with the indexed subview. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetIndexedSubview( inView: HIViewRef; inSubviewIndex: CFIndex; var outSubview: HIViewRef ): OSStatus; external name '_HIViewGetIndexedSubview'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetZOrder() * * Discussion: * Allows you to change the front-to-back ordering of sibling views. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose Z-order you wish to change. * * inOp: * Indicates to order inView above or below inOther. * * inOther: * Another optional view to use as a reference. You can pass NULL * to mean an absolute position. For example, passing * kHIViewZOrderAbove and NULL will move a view to the front of * all of its siblings. Likewise, passing kHIViewZOrderBelow and * NULL will move it to the back. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetZOrder( inView: HIViewRef; inOp: HIViewZOrderOp; inOther: HIViewRef { can be NULL } ): OSStatus; external name '_HIViewSetZOrder'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { STATE and VALUES } {==============================================================================} { * HIViewKind } type HIViewKind = record { * The signature of the view. Apple reserves all signatures made up * of only lowercase characters. } signature: OSType; { * The kind of the view. Apple reserves all kinds made up of only * lowercase characters. } kind: OSType; end; { * View signature kind * } const { * The signature of all HIToolbox views. } kHIViewKindSignatureApple = FourCharCode('appl'); { * HIViewSetVisible() * * Discussion: * Hides or shows a view. Marks the area the view will occupy or * used to occupy as needing to be redrawn later. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to hide or show. * * inVisible: * A boolean value which indicates whether you wish to hide the * view (false) or show the view (true). * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetVisible( inView: HIViewRef; inVisible: Boolean ): OSStatus; external name '_HIViewSetVisible'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewIsVisible() * * Summary: * Returns whether a view is visible. * * Discussion: * Note that HIViewIsVisible returns a view's effective visibility, * which is determined both by the view's own visibility and the * visibility of its parent views. If a parent view is invisible, * then this view is considered to be invisible also. * * Latent visibility can be determined with HIViewIsLatentlyVisible. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose visibility you wish to determine. * * Result: * A boolean value indicating whether the view is visible (true) or * hidden (false). * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewIsVisible( inView: HIViewRef ): Boolean; external name '_HIViewIsVisible'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewIsLatentlyVisible() * * Summary: * Returns whether or not a view is latently visible. * * Discussion: * The view's visibility is also affected by the visibility of its * parents; if any parent view is invisible, this view is considered * invisible as well. HIViewIsLatentlyVisible returns whether a view * is latently visible, even if its parents are invisible. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose latent visibility is to be checked. * * Result: * True if the view is latently visible, otherwise false. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewIsLatentlyVisible( inView: HIViewRef ): Boolean; external name '_HIViewIsLatentlyVisible'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetHilite() * * Summary: * Changes the highlighting of a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view on which to set the highlight. * * inHilitePart: * An HIViewPartCode indicating the part of the view to highlight. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetHilite( inView: HIViewRef; inHilitePart: HIViewPartCode ): OSStatus; external name '_HIViewSetHilite'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewIsActive() * * Summary: * Returns whether or not a view is active. * * Discussion: * The view's active state is also affected by the active state of * its parents; if any parent view is inactive, this view is * considered inactive as well. HIViewIsActive can optionally check * to see if a view is latently active, even if its parents are * inactive. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose active state is to be checked. * * outIsLatentActive: * A pointer to a Boolean to be filled in with the latent active * state of the view. The Boolean is set to true if the view is * latently active, otherwise false. Can be NULL. * * Result: * True if the view is active, otherwise false. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewIsActive( inView: HIViewRef; outIsLatentActive: BooleanPtr { can be NULL } ): Boolean; external name '_HIViewIsActive'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetActivated() * * Summary: * Sets whether or not a view is active or inactive. If any children * of the view have a latent active state, they will be adjusted * accordingly. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to activate or deactivate. * * inSetActivated: * True if setting the view to active, false if setting the view * to inactive. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetActivated( inView: HIViewRef; inSetActivated: Boolean ): OSStatus; external name '_HIViewSetActivated'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewIsEnabled() * * Summary: * Tests whether or not a view is enabled. * * Discussion: * The view's enabled state is also affected by the enabled state of * its parents; if any parent view is disabled, this view is * considered disabled as well. HIViewIsEnabled can optionally check * to see if a view is latently enabled, even if its parents are * disabled. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to test. * * outIsLatentEnabled: * A pointer to a Boolean to be filled in with the latent enabled * state of the view. The Boolean is set to true if the view is * latently enabled, otherwise false. Can be NULL. * * Result: * True if the view is enabled, otherwise false. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewIsEnabled( inView: HIViewRef; outIsLatentEnabled: BooleanPtr { can be NULL } ): Boolean; external name '_HIViewIsEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetEnabled() * * Summary: * Sets whether or not a view (and any subviews) are enabled or * disabled. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to enable or disable. * * inSetEnabled: * True if setting the view to enabled, false if setting the view * to disabled. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetEnabled( inView: HIViewRef; inSetEnabled: Boolean ): OSStatus; external name '_HIViewSetEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewIsCompositingEnabled() * * Summary: * Returns whether a view is being used in a compositing hierarchy. * * Discussion: * A view that supports both compositing mode and non-compositing * mode can use this routine to determine which mode it is currently * running in. Looking for a window's kWindowCompositingAttribute is * not sufficient, since some windows with that attribute have some * of its views in non-compositing mode and vice-versa. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose compositing state you wish to determine. * * Result: * A boolean value indicating whether the view is in compositing * mode (true) or non-compositing mode (false). * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewIsCompositingEnabled( inView: HIViewRef ): Boolean; external name '_HIViewIsCompositingEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetText() * * Summary: * Sets the text of a view to the specified string. * * Discussion: * The "text" of the view is the text that will be displayed when * drawing the view. This API first attempts to set the view's text * (generally successful on views that handle the * kControlEditTextCFStringTag SetControlData tag). If the attempt * is unsuccessful, the view's title is set instead. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose text is being set. * * inText: * The text to set for the view. The string is copied by the view, * and may be released by the caller afterwards. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetText( inView: HIViewRef; inText: CFStringRef ): OSStatus; external name '_HIViewSetText'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewCopyText() * * Summary: * Makes a copy of the view's text as a CFString. * * Discussion: * The "text" of the view is the text that will be displayed when * drawing the view. This API first attempts to get the view's text * (generally successful on views that handle the * kControlEditTextCFStringTag GetControlData tag). If the attempt * is unsuccessful, the view's title is copied instead. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the text. * * Result: * A CFStringRef containing a copy of the view's text. The caller of * HIViewCopyText is responsible for releasing the returned text. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewCopyText( inView: HIViewRef ): CFStringRef; external name '_HIViewCopyText'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetValue() * * Summary: * Gets a view's value. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the value. * * Result: * The view's value. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetValue( inView: HIViewRef ): SInt32; external name '_HIViewGetValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetValue() * * Summary: * Sets a view's value. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose value is to be set. * * inValue: * The new value. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetValue( inView: HIViewRef; inValue: SInt32 ): OSStatus; external name '_HIViewSetValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetMinimum() * * Summary: * Gets a view's minimum value. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the minimum value. * * Result: * The view's minimum value. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetMinimum( inView: HIViewRef ): SInt32; external name '_HIViewGetMinimum'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetMinimum() * * Summary: * Sets a view's minimum value. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose minimum value is to be set. * * inMinimum: * The new minimum value. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetMinimum( inView: HIViewRef; inMinimum: SInt32 ): OSStatus; external name '_HIViewSetMinimum'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetMaximum() * * Summary: * Gets a view's maximum value. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the maximum value. * * Result: * The view's maximum value. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetMaximum( inView: HIViewRef ): SInt32; external name '_HIViewGetMaximum'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetMaximum() * * Summary: * Sets a view's maximum value. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose maximum value is to be set. * * inMaximum: * The new maximum value. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetMaximum( inView: HIViewRef; inMaximum: SInt32 ): OSStatus; external name '_HIViewSetMaximum'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetViewSize() * * Summary: * Gets a view's view size. * * Discussion: * The view size is the size of the content to which a view's * display is proportioned. Most commonly used to set the * proportional size of a scroll bar's thumb indicator. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the view size. * * Result: * The view size. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetViewSize( inView: HIViewRef ): SInt32; external name '_HIViewGetViewSize'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetViewSize() * * Summary: * Sets a view's view size. * * Discussion: * The view size is the size of the content to which a view's * display is proportioned. Most commonly used to set the * proportional size of a scroll bar's thumb indicator. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose view size is to be set. * * inViewSize: * The new view size. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetViewSize( inView: HIViewRef; inViewSize: SInt32 ): OSStatus; external name '_HIViewSetViewSize'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewIsValid() * * Summary: * HIViewIsValid tests to see if the passed in view is a view that * HIToolbox knows about. It does not sanity check the data in the * view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to test for validity. * * Result: * True if the view is a valid view, otherwise, false. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewIsValid( inView: HIViewRef ): Boolean; external name '_HIViewIsValid'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetID() * * Summary: * Sets the HIViewID of a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to set the ID. * * inID: * The ID to set on the view. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetID( inView: HIViewRef; inID: HIViewID ): OSStatus; external name '_HIViewSetID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetID() * * Summary: * Gets the HIViewID of a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the ID. * * outID: * A pointer to an HIViewID to be filled with the view's ID. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetID( inView: HIViewRef; var outID: HIViewID ): OSStatus; external name '_HIViewGetID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetCommandID() * * Summary: * Sets the command ID of a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to set the command ID. * * inCommandID: * The command ID to set on the view. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetCommandID( inView: HIViewRef; inCommandID: UInt32 ): OSStatus; external name '_HIViewSetCommandID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetCommandID() * * Summary: * Gets the command ID of a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to get the command ID. * * outCommandID: * A pointer to a UInt32 to fill with the view's command id. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetCommandID( inView: HIViewRef; var outCommandID: UInt32 ): OSStatus; external name '_HIViewGetCommandID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetKind() * * Summary: * Returns the kind of the given view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose kind to get. * * outViewKind: * On successful exit, this will contain the view signature and * kind. See ControlDefinitions.h or HIView.h for the kinds of * each system view. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetKind( inView: HIViewRef; var outViewKind: HIViewKind ): OSStatus; external name '_HIViewGetKind'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {==============================================================================} { POSITIONING } {==============================================================================} { * HIViewGetBounds() * * Discussion: * Returns the local bounds of a view. The local bounds are the * coordinate system that is completely view-relative. A view's top * left coordinate starts out at 0, 0. Most operations are done in * these local coordinates. Moving a view is done via the frame * instead. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose bounds you wish to determine. * * outRect: * The local bounds of the view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetBounds( inView: HIViewRef; var outRect: HIRect ): OSStatus; external name '_HIViewGetBounds'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetFrame() * * Discussion: * Returns the frame of a view. The frame is the bounds of a view * relative to its parent's local coordinate system. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose frame you wish to determine. * * outRect: * The frame of the view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetFrame( inView: HIViewRef; var outRect: HIRect ): OSStatus; external name '_HIViewGetFrame'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetFrame() * * Discussion: * Sets the frame of a view. This effectively moves the view within * its parent. It also marks the view (and anything that was exposed * behind it) to be redrawn. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose frame you wish to change. * * inRect: * The new frame of the view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetFrame( inView: HIViewRef; const (*var*) inRect: HIRect ): OSStatus; external name '_HIViewSetFrame'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewMoveBy() * * Discussion: * Moves a view by a certain distance, relative to its current * location. This affects a view's frame, but not its bounds. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view you wish to move. * * inDX: * The horizontal distance to move the view. Negative values move * the view to the left, positive values to the right. * * inDY: * The vertical distance to move the view. Negative values move * the view upward, positive values downward. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewMoveBy( inView: HIViewRef; inDX: Float32; inDY: Float32 ): OSStatus; external name '_HIViewMoveBy'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewPlaceInSuperviewAt() * * Discussion: * Places a view at an absolute location within its parent. This * affects the view's frame, but not its bounds. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view you wish to position. * * inX: * The absolute horizontal coordinate at which to position the * view. * * inY: * The absolute vertical coordinate at which to position the view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewPlaceInSuperviewAt( inView: HIViewRef; inX: Float32; inY: Float32 ): OSStatus; external name '_HIViewPlaceInSuperviewAt'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewReshapeStructure() * * Discussion: * This is for use by custom views. If a view decides that its * structure will change shape, it should call this. This tells the * Toolbox to recalc things and invalidate as appropriate. You might * use this when gaining/losing a focus ring, for example. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to reshape and invalidate. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewReshapeStructure( inView: HIViewRef ): OSStatus; external name '_HIViewReshapeStructure'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewRegionChanged() * * Discussion: * Allows a view to tell the view system that a region of itself has * changed. The view system might choose to react in some way. For * example, if a view's clickable region has changed, this can be * called to tell the Toolbox to resync the region it uses for async * window dragging, if enabled. Likewise, if a view's opaque region * changes, we can adjust the window's opaque shape as well. When * views are moved, resizes, this stuff is taken care of for you. So * this only need be called when there's a change in your view that * occurs outside of those times. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to deal with. * * inRegionCode: * The region that was changed. This can only be the structure * opaque, and clickable regions at present. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewRegionChanged( inView: HIViewRef; inRegionCode: HIViewPartCode ): OSStatus; external name '_HIViewRegionChanged'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewCopyShape() * * Summary: * Copies the shape of a part of a view. See the discussion on * meta-parts in this header for more information * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view for which to copy the shape. * * inPart: * The part of the view whose shape is to be copied. * * outShape: * On exit, contains a newly created shape. The caller of * HIViewCopyShape is responsible for releasing the copied shape. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewCopyShape( inView: HIViewRef; inPart: HIViewPartCode; var outShape: HIShapeRef ): OSStatus; external name '_HIViewCopyShape'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetOptimalBounds() * * Summary: * Obtain a view's optimal size and/or text placement. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to examine. * * outBounds: * A pointer to an HIRect to be filled with the view's optimal * bounds. Can be NULL. * * outBaseLineOffset: * A pointer to a float to be filled with the view's optimal text * placement. Can be NULL. * * Result: * A result code indicating success or failure. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetOptimalBounds( inView: HIViewRef; outBounds: HIRectPtr { can be NULL }; outBaseLineOffset: Float32Ptr { can be NULL } ): OSStatus; external name '_HIViewGetOptimalBounds'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {==============================================================================} { HIT TESTING/EVENT HANDLING } {==============================================================================} { * HIViewGetViewForMouseEvent() * * Discussion: * Returns the appropriate view to handle a mouse event. This is a * little higher-level than HIViewGetSubviewHit. This routine will * find the deepest view that should handle the mouse event, but * along the way, it sends Carbon Events to each view asking it to * return the appropriate subview. This allows parent views to catch * clicks on their subviews. This is the recommended function to use * before processing mouse events. Using one of the more primitive * functions may result in an undefined behavior. In general we * recommend the use of the Standard Window Handler instead of * calling this function yourself. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to start from. You should pass the window's root view. * * inEvent: * The mouse event in question. * * outView: * The view that the mouse event should be sent to. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetViewForMouseEvent( inView: HIViewRef; inEvent: EventRef; var outView: HIViewRef ): OSStatus; external name '_HIViewGetViewForMouseEvent'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewClick() * * Discussion: * After a successful call to HIViewGetViewForMouseEvent for a mouse * down event, you should call this function to have the view handle * the click. In general we recommend the use of the Standard Window * Handler instead of calling this function yourself. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to handle the event. * * inEvent: * The mouse event to handle. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewClick( inView: HIViewRef; inEvent: EventRef ): OSStatus; external name '_HIViewClick'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSimulateClick() * * Discussion: * This function is used to simulate a mouse click on a given view. * It sends a kEventControlSimulateHit event to the specified view, * and also sends kEventControlHit and (if the Hit event is not * handled) kEventCommandProcess events. * * Note that not all windows will respond to the events that are * sent by this API. A fully Carbon-event-based window most likely * will respond exactly as if the user had really clicked in the * view. A window that is handled using classic EventRecord-based * APIs (WaitNextEvent or ModalDialog) will typically not respond at * all; to simulate a click in such a window, you may need to post a * mouse-down/mouse-up pair, or use a Dialog Manager event filter * proc to simulate a hit in a dialog item. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to test the part hit. * * inPartToClick: * The part the view should consider to be clicked. * * inModifiers: * The modifiers the view can consider for its click action. * * outPartClicked: * The part that was hit, can be kControlNoPart if no action * occurred. May be NULL if you don't need the part code returned. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSimulateClick( inView: HIViewRef; inPartToClick: HIViewPartCode; inModifiers: UInt32; outPartClicked: HIViewPartCodePtr { can be NULL } ): OSStatus; external name '_HIViewSimulateClick'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetPartHit() * * Discussion: * Given a view, and a view-relative point, this function returns * the part code hit as determined by the view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to test the part hit. * * inPoint: * The view-relative point to use. * * outPart: * The part hit by inPoint. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetPartHit( inView: HIViewRef; const (*var*) inPoint: HIPoint; var outPart: HIViewPartCode ): OSStatus; external name '_HIViewGetPartHit'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetSubviewHit() * * Discussion: * Returns the child of the given view hit by the point passed in. * This is more primitive than using HIViewGetViewForMouseEvent, and * should be used only in non-event-handling cases. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view you wish to start from. * * inPoint: * The mouse coordinate to use. This is passed in the local * coordinate system of inView. * * inDeep: * Pass true to find the deepest child hit, false to go only one * level deep (just check direct children of inView). * * outView: * The view hit by inPoint, or NULL if no subview was hit. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetSubviewHit( inView: HIViewRef; const (*var*) inPoint: HIPoint; inDeep: Boolean; var outView: HIViewRef ): OSStatus; external name '_HIViewGetSubviewHit'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { HIView-based tracking areas } {==============================================================================} type HIViewTrackingAreaRef = ^SInt32; { an opaque 32-bit type } const kEventParamHIViewTrackingArea = FourCharCode('ctra'); { typeHIViewTrackingAreaRef} typeHIViewTrackingAreaRef = FourCharCode('ctra'); { * kEventClassControl / kEventControlTrackingAreaEntered * * Summary: * The mouse has entered a tracking area owned by your control. * * Discussion: * If you have installed a mouse tracking area in your view, you * will receive this event when the mouse enters that area. The * tracking area reference is sent with the event. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamHIViewTrackingArea (in, typeHIViewTrackingAreaRef) * The tracking area that was entered. * * --> kEventParamKeyModifiers (in, typeUInt32) * The keyboard modifiers that were in effect when the mouse * entered. * * --> kEventParamMouseLocation (in, typeHIPoint) * The location of the mouse in view coordinates. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventControlTrackingAreaEntered = 23; { * kEventClassControl / kEventControlTrackingAreaExited * * Summary: * The mouse has exited a tracking area owned by your control. * * Discussion: * If you have installed a mouse tracking area in your view, you * will receive this event when the mouse leaves that area. The * tracking area reference is sent with the event. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamHIViewTrackingArea (in, typeHIViewTrackingAreaRef) * The tracking area that was entered. * * --> kEventParamKeyModifiers (in, typeUInt32) * The keyboard modifiers that were in effect when the mouse * left. * * --> kEventParamMouseLocation (in, typeHIPoint) * The location of the mouse in view coordinates. This point * may or may not lie on the boundary of the mouse region. It * is merely where the mouse was relative to the view when the * exit event was generated. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventControlTrackingAreaExited = 24; type HIViewTrackingAreaID = UInt64; { * HIViewNewTrackingArea() * * Summary: * Creates a new tracking area for a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to create a tracking area for. * * inShape: * The shape to use. Pass NULL to indicate the entire structure * region of the view is to be used. * * inID: * An identifier for this tracking area. This value is completely * up to the view to define. Pass zero if you don't care. * * outRef: * A reference to the newly created tracking area. This references * is NOT refcounted. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewNewTrackingArea( inView: HIViewRef; inShape: HIShapeRef { can be NULL }; inID: HIViewTrackingAreaID; var outRef: HIViewTrackingAreaRef ): OSStatus; external name '_HIViewNewTrackingArea'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewChangeTrackingArea() * * Summary: * Alters the shape of an existing tracking area. * * Mac OS X threading: * Not thread safe * * Parameters: * * inArea: * The area to change. * * inShape: * The shape to use. Pass NULL to indicate the entire structure * region of the view is to be used. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewChangeTrackingArea( inArea: HIViewTrackingAreaRef; inShape: HIShapeRef ): OSStatus; external name '_HIViewChangeTrackingArea'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetTrackingAreaID() * * Summary: * Retrieves the HIViewTrackingAreaID of an existing tracking area. * This value was set upon creation of the HIViewTrackingArea. * * Mac OS X threading: * Not thread safe * * Parameters: * * inArea: * The area whose HIViewTrackingAreaID to retrieve. * * outID: * The HIViewTrackingAreaID for this tracking area. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetTrackingAreaID( inArea: HIViewTrackingAreaRef; var outID: HIViewTrackingAreaID ): OSStatus; external name '_HIViewGetTrackingAreaID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewDisposeTrackingArea() * * Summary: * Disposes an existing tracking area. The reference is considered * to be invalid after calling this function. * * Mac OS X threading: * Not thread safe * * Parameters: * * inArea: * The area to dispose. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewDisposeTrackingArea( inArea: HIViewTrackingAreaRef ): OSStatus; external name '_HIViewDisposeTrackingArea'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {==============================================================================} { DISPLAY } {==============================================================================} { * HIViewGetNeedsDisplay() * * Discussion: * Returns true if the view passed in or any subview of it requires * redrawing (i.e. part of it has been invalidated). * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to inspect. * * Result: * A boolean result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetNeedsDisplay( inView: HIViewRef ): Boolean; external name '_HIViewGetNeedsDisplay'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetNeedsDisplay() * * Discussion: * Marks a view as needing to be completely redrawn, or completely * valid. If the view is not visible, or is obscured completely by * other views, no action is taken. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to mark dirty. * * inNeedsDisplay: * A boolean which indicates whether inView needs to be redrawn or * not. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetNeedsDisplay( inView: HIViewRef; inNeedsDisplay: Boolean ): OSStatus; external name '_HIViewSetNeedsDisplay'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetNeedsDisplayInRect() * * Discussion: * Marks a portion of a view as needing to be redrawn, or valid. If * the view is not visible, or is obscured completely by other * views, no action is taken. The rectangle passed is effectively * intersected with the view's visible region. It should be in * view-relative coordinates. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to mark dirty. * * inRect: * The rectangle encompassing the area to mark dirty or clean. * * inNeedsDisplay: * A boolean which indicates whether or not inRect should be added * to the invalid region or removed from it. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetNeedsDisplayInRect( inView: HIViewRef; const (*var*) inRect: HIRect; inNeedsDisplay: Boolean ): OSStatus; external name '_HIViewSetNeedsDisplayInRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetNeedsDisplayInShape() * * Discussion: * Marks a portion of a view as needing to be redrawn, or valid. If * the view is not visible, or is obscured completely by other * views, no action is taken. The shape passed is effectively * intersected with the view's visible region. It should be in * view-relative coordinates. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to mark dirty. * * inArea: * The area to mark dirty or clean. * * inNeedsDisplay: * A boolean which indicates whether or not inArea should be added * to the invalid region or removed from it. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewSetNeedsDisplayInShape( inView: HIViewRef; inArea: HIShapeRef; inNeedsDisplay: Boolean ): OSStatus; external name '_HIViewSetNeedsDisplayInShape'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewSetNeedsDisplayInRegion() * * Discussion: * Marks a portion of a view as needing to be redrawn, or valid. If * the view is not visible, or is obscured completely by other * views, no action is taken. The region passed is effectively * intersected with the view's visible region. It should be in * view-relative coordinates. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to mark dirty. * * inRgn: * The region to mark dirty or clean. * * inNeedsDisplay: * A boolean which indicates whether or not inRgn should be added * to the invalid region or removed from it. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetNeedsDisplayInRegion( inView: HIViewRef; inRgn: RgnHandle; inNeedsDisplay: Boolean ): OSStatus; external name '_HIViewSetNeedsDisplayInRegion'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewRender() * * Discussion: * Renders the invalid portions of a view (as marked with * HIViewSetNeedsDisplay[InRegion]) immediately. Normally, these * areas are redrawn at event loop time, but there might be * situations where you need an immediate draw. Use this sparingly, * as it does cause a fully composited draw for the area of the * view; that is, all other views that intersect the area of the * specified view will also be drawn. Calling this for several views * at a particular level of a hierarchy can be costly. We highly * recommend that you only pass the root view of a window to this * API. The behavior of this API when passed a non-root view was * poorly defined in Mac OS X 10.3 and has changed in Mac OS X 10.4. * In 10.3, calling this API on a non-root view would entirely * validate all of the views in the window that intersect the * specified view, including portions that did not intersect the * specified view and so were not actually drawn. In 10.4, calling * this API on a non-root view will only validate those portions of * each view that intersect the specified view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to draw. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewRender( inView: HIViewRef ): OSStatus; external name '_HIViewRender'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewFlashDirtyArea() * * Discussion: * Debugging aid. Flashes the region which would be redrawn at the * next draw time for an entire window. * * Mac OS X threading: * Not thread safe * * Parameters: * * inWindow: * The window to flash the dirty region for. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewFlashDirtyArea( inWindow: WindowRef ): OSStatus; external name '_HIViewFlashDirtyArea'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetSizeConstraints() * * Discussion: * Return the minimum and maximum size for a control. A control must * respond to this protocol to get meaningful results. These sizes * can be used to help autoposition subviews, for example. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to inspect. * * outMinSize: * The minimum size the view can be. May be NULL if you don't need * this information. * * outMaxSize: * The maximum size the view can be. May be NULL if you don't need * this information. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetSizeConstraints( inView: HIViewRef; outMinSize: HISizePtr { can be NULL }; outMaxSize: HISizePtr { can be NULL } ): OSStatus; external name '_HIViewGetSizeConstraints'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { COORDINATE SYSTEM CONVERSION } {==============================================================================} { * HIViewConvertPoint() * * Discussion: * Converts a point from one view to another. Both views must have a * common ancestor, i.e. they must both be in the same window. * * Mac OS X threading: * Not thread safe * * Parameters: * * ioPoint: * The point to convert. * * inSourceView: * The view whose coordinate system ioPoint is starting out in. * You can pass NULL to indicate that ioPoint is a window-relative * point. * * inDestView: * The view whose coordinate system ioPoint should end up in. You * can pass NULL to indicate that ioPoint is a window-relative * point. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewConvertPoint( var ioPoint: HIPoint; inSourceView: HIViewRef; inDestView: HIViewRef ): OSStatus; external name '_HIViewConvertPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewConvertRect() * * Discussion: * Converts a rectangle from one view to another. Both views must * have a common ancestor, i.e. they must both be in the same window. * * Mac OS X threading: * Not thread safe * * Parameters: * * ioRect: * The rectangle to convert. * * inSourceView: * The view whose coordinate system ioRect is starting out in. You * can pass NULL to indicate that ioRect is a window-relative * rectangle. * * inDestView: * The view whose coordinate system ioRect should end up in. You * can pass NULL to indicate that ioRect is a window-relative * rectangle. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewConvertRect( var ioRect: HIRect; inSourceView: HIViewRef; inDestView: HIViewRef ): OSStatus; external name '_HIViewConvertRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewConvertRegion() * * Discussion: * Converts a region from one view to another. Both views must have * a common ancestor, i.e. they must both be in the same window. * * Mac OS X threading: * Not thread safe * * Parameters: * * ioRgn: * The region to convert. * * inSourceView: * The view whose coordinate system ioRgn is starting out in. You * can pass NULL to indicate that ioRgn is a window-relative * region. * * inDestView: * The view whose coordinate system ioRgn should end up in. You * can pass NULL to indicate that ioRgn is a window-relative * region. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewConvertRegion( ioRgn: RgnHandle; inSourceView: HIViewRef; inDestView: HIViewRef ): OSStatus; external name '_HIViewConvertRegion'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetDrawingEnabled() * * Discussion: * Turns control drawing on or off. You can use this to ensure that * no drawing events are sent to the control. Even Draw1Control will * not draw! HIViewSetNeedsDisplay is also rendered useless when * drawing is off. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to enable or disable drawing for. * * inEnabled: * A boolean value indicating whether drawing should be on (true) * or off (false). * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetDrawingEnabled( inView: HIViewRef; inEnabled: Boolean ): OSStatus; external name '_HIViewSetDrawingEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewIsDrawingEnabled() * * Discussion: * Determines if drawing is currently enabled for a control. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to get the drawing state for. * * Result: * A boolean value indicating whether drawing is on (true) or off * (false). * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewIsDrawingEnabled( inView: HIViewRef ): Boolean; external name '_HIViewIsDrawingEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewScrollRect() * * Discussion: * Scrolls a view's contents, or a portion thereof. A view's * contents are the pixels that it or any of its descendent views * has drawn into. This will actually blit the contents of the view * as appropriate to scroll, and then invalidate those portions * which need to be redrawn. Be warned that this is a raw bit * scroll. Anything that might overlap the target view will get * thrashed as well. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to scroll. The bits drawn by the view's descendent * views will also be scrolled. * * inRect: * The rect to scroll. Pass NULL to mean the entire view. The rect * passed cannot be bigger than the view's bounds. It must be in * the local coordinate system of the view. * * inDX: * The horizontal distance to scroll. Positive values shift to the * right, negative values shift to the left. * * inDY: * The vertical distance to scroll. Positive values shift * downward, negative values shift upward. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewScrollRect( inView: HIViewRef; {const} inRect: HIRectPtr { can be NULL }; inDX: Float32; inDY: Float32 ): OSStatus; external name '_HIViewScrollRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetBoundsOrigin() * * Discussion: * This API sets the origin of the view. This effectively also moves * all subcontrols of a view as well. This call will NOT invalidate * the view. This is because you might want to move the contents * with HIViewScrollRect instead of redrawing the complete content. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose origin you wish to adjust. * * inX: * The X coordinate. * * inY: * The Y coordinate. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetBoundsOrigin( inView: HIViewRef; inX: Float32; inY: Float32 ): OSStatus; external name '_HIViewSetBoundsOrigin'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { KEYBOARD FOCUS } {==============================================================================} { * HIViewAdvanceFocus() * * Discussion: * Advances the focus to the next most appropriate view. Unless * overriden in some fashion (either by overriding certain carbon * events or using the HIViewSetNextFocus API), the Toolbox will use * a spacially determinant method of focusing, attempting to focus * left to right, top to bottom in a window, taking groups of * controls into account. * * Mac OS X threading: * Not thread safe * * Parameters: * * inRootForFocus: * The subtree to manipulate. The focus will never leave * inRootToFocus. Typically you would pass the content of the * window, or the root. If focused on the toolbar, for example, * the focus is limited to the toolbar only. In this case, the * Toolbox passes the toolbar view in as the focus root for * example. * * inModifiers: * The EventModifiers of the keyboard event that ultimately caused * the call to HIViewAdvanceFocus. These modifiers are used to * determine the focus direction as well as other alternate * focusing behaviors. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewAdvanceFocus( inRootForFocus: HIViewRef; inModifiers: EventModifiers ): OSStatus; external name '_HIViewAdvanceFocus'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetFocusPart() * * Discussion: * Returns the currently focused part of the given view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to inquire about. * * outFocusPart: * The part currently focused. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetFocusPart( inView: HIViewRef; var outFocusPart: HIViewPartCode ): OSStatus; external name '_HIViewGetFocusPart'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSubtreeContainsFocus() * * Discussion: * Given a view, this function checks to see if it or any of its * children currently are the keyboard focus. If so, true is * returned as the function result. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSubtreeStart: * The view to start searching at. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSubtreeContainsFocus( inSubtreeStart: HIViewRef ): Boolean; external name '_HIViewSubtreeContainsFocus'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetNextFocus() * * Discussion: * This function hard-wires the next sibling view to shift focus to * whenever the keyboard focus is advanced. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to set the next focus view for. This parameter and the * inNextFocus parameter must both have the same parent view. * * inNextFocus: * The view to set focus to next. This parameter and the inView * parameter must both have the same parent view. Pass NULL to * tell the view system to use the default rules. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetNextFocus( inView: HIViewRef; inNextFocus: HIViewRef { can be NULL } ): OSStatus; external name '_HIViewSetNextFocus'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewSetFirstSubViewFocus() * * Discussion: * This function hard-wires the first subview to shift focus to * whenever the keyboard focus is advanced and the container view is * entered. * * Mac OS X threading: * Not thread safe * * Parameters: * * inParent: * The parent view. * * inSubView: * The first child which should receive focus. Pass NULL to tell * the view system to use the default rules. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewSetFirstSubViewFocus( inParent: HIViewRef; inSubView: HIViewRef { can be NULL } ): OSStatus; external name '_HIViewSetFirstSubViewFocus'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { LAYOUT } { Mac OS X 10.3 provides a layout engine for HIViews that allows applications } { to specify the layout relationships between multiple views. The layout } { engine will automatically reposition and resize views that have layout } { information when necessary. } {==============================================================================} { * Summary: * Since horizontal and vertical bindings are very similar in * application, except along different axes, the binding kinds have * been abstracted to minimum and maximum. Synonyms have been * provided for convenience. You are encouraged to use them. * * Discussion: * HIBindingKind constants. } const { * No binding is to occur. } kHILayoutBindNone = 0; { * Bind to the minimum of the axis. } kHILayoutBindMin = 1; { * Bind to the maximum of the axis. } kHILayoutBindMax = 2; kHILayoutBindLeft = kHILayoutBindMin; kHILayoutBindRight = kHILayoutBindMax; { * Synonyms for convenience and clarity. } kHILayoutBindTop = kHILayoutBindMin; kHILayoutBindBottom = kHILayoutBindMax; type HIBindingKind = UInt16; { * HISideBinding * * Summary: * A binding for a side of an HIView. * * Discussion: * A side binding is entirely related to the change of the parent's * position or size (but only as the size affects the maximum edge * position). A side binding doesn't mean "move to where my * relative's side is" but rather "move as my relative's side has * moved". } type HISideBinding = record { * An HIViewRef to the view to which this side is bound. Can be NULL, * indicating that the the side is bound to its parent view. } toView: HIViewRef; { NULL means parent} { * An HIBindingKind indicating the bind kind. } kind: HIBindingKind; { * Not currently used. Must be set to 0. } offset: Float32; end; { const HISideBinding kHISideNoBinding = ( NULL, kHILayoutBindNone ); } { * HIBinding * * Summary: * A set of Top, Left, Bottom, and Right bindings for an HIView. } type HIBinding = record { * The top side bindings. } top: HISideBinding; { * The left side bindings. } left: HISideBinding; { * The bottom side bindings. } bottom: HISideBinding; { * The right side bindings. } right: HISideBinding; end; { const HIBinding kHINoBinding = ( kHISideNoBinding, kHISideNoBinding, kHISideNoBinding, kHISideNoBinding ); } { * Discussion: * HIScaleKind constants. } const { * The scale is determined from the axis size. } kHILayoutScaleAbsolute = 0; type HIScaleKind = UInt16; { * HIAxisScale * * Summary: * A scale description for an axis of an HIView. } type HIAxisScale = record { * An HIViewRef to the view to which this axis is scaled. Can be * NULL, indicating that the the axis is scaled relative to its * parent view. } toView: HIViewRef; { NULL means parent} { * An HIScaleKind describing the type of scaling to be applied. * Currently, this field can't be anything other than * kScalingAbsolute. } kind: HIScaleKind; { * A float indicating how much to scale the HIView. 0 indicates no * scaling. A value of 1 indicates that the view is to always have * the same axial size. } ratio: Float32; end; { * HIScaling * * Summary: * A set of scaling descriptions for the axes of an HIView. } type HIScaling = record { * An HIAxisScale describing the horizontal scaling for an HIView. } x: HIAxisScale; y: HIAxisScale; end; { * Summary: * Since horizontal and vertical positions are very similar in * application, except along different axes, the position kinds have * been abstracted to minimum and maximum. Synonyms have been * provided for convenience. You are encouraged to use them. * * Discussion: * HIPositionKind constants. } const { * No positioning is to occur. } kHILayoutPositionNone = 0; { * Centered positioning will occur. The view will be centered * relative to the specified view. } kHILayoutPositionCenter = 1; { * Minimum positioning will occur. The view will be left or top * aligned relative to the specified view. } kHILayoutPositionMin = 2; { * Maximum positioning will occur. The view will be right or bottom * aligned relative to the specified view. } kHILayoutPositionMax = 3; { * Synonyms for convenience and clarity. } kHILayoutPositionLeft = kHILayoutPositionMin; kHILayoutPositionRight = kHILayoutPositionMax; kHILayoutPositionTop = kHILayoutPositionMin; kHILayoutPositionBottom = kHILayoutPositionMax; type HIPositionKind = UInt16; { * HIAxisPosition * * Summary: * An axial position description for an HIView. } type HIAxisPosition = record { * An HIViewRef to the view relative to which a view will be * positioned. Can be NULL, indicating that the the view is * positioned relative to its parent view. } toView: HIViewRef; { NULL means parent} { * An HIPositionKind indicating the kind of positioning to apply. } kind: HIPositionKind; { * After the position kind has been applied, the origin component * that corresponds to the positioning axis is offet by this value. * (ex: Left aligned + 10 ). } offset: Float32; end; { * HIPositioning * * Summary: * A positioning description for an HIView. } type HIPositioning = record { * An HIAxisPosition describing the horizontal positioning for an * HIView. } x: HIAxisPosition; y: HIAxisPosition; end; { * HILayoutInfo * * Summary: * A layout description for an HIView. * * Discussion: * The different layout transformations are applied sequentially to * the HIView. First, the bindings are applied. Note that the * bindings are applied recursively to a container's HIViews. This * requires care on your part, especially when applying * inter-relational bindings. Then the scaling (which could * potentially override some of the previously applied bindings). * Then the positioning (which could potentially override some of * the previously applied bindings). } type HILayoutInfo = record { * The version of the structure. The current version is * kHILayoutInfoVersionZero. } version: UInt32; { * An HIBinding structure describing the kinds of bindings to apply * to the sides of an HIView. } binding: HIBinding; { * An HIScaling structure describing the axial scaling to apply to an * HIView. } scale: HIScaling; { * An HIPositioning structure positioning to apply to an HIView. } position: HIPositioning; end; const kHILayoutInfoVersionZero = 0; { const HILayoutInfo kHILayoutInfoNone = ( kHILayoutInfoVersionZero, kHINoBinding, ( ( NULL, 0.0 ), ( NULL, 0.0 ) ), ( ( NULL, kHILayoutPositionNone ), ( NULL, kHILayoutPositionNone ) ) ); } { * HIViewGetLayoutInfo() * * Summary: * Get the layout info of an HIView. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose layout info is to be retreived. * * outLayoutInfo: * A pointer to an HILayoutInfo record into which to copy the * layout info of the HIView. The version field of this record * must be valid or the call will fail. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewGetLayoutInfo( inView: HIViewRef; var outLayoutInfo: HILayoutInfo ): OSStatus; external name '_HIViewGetLayoutInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewSetLayoutInfo() * * Summary: * Set the layout info of an HIView. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose layout info is to be retreived. * * inLayoutInfo: * A pointer to an HILayoutInfo record from which to copy the * layout info for the HIView. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewSetLayoutInfo( inView: HIViewRef; const (*var*) inLayoutInfo: HILayoutInfo ): OSStatus; external name '_HIViewSetLayoutInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewSuspendLayout() * * Summary: * Suspends all layout handling for this layout and its children. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose layout handling is to be suspended. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewSuspendLayout( inView: HIViewRef ): OSStatus; external name '_HIViewSuspendLayout'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewResumeLayout() * * Summary: * Resumes all layout handling for this layout and its children. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose layout handling is to be resumed. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewResumeLayout( inView: HIViewRef ): OSStatus; external name '_HIViewResumeLayout'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewIsLayoutActive() * * Summary: * Tests the view to determine if layout is active or suspended. * Note that this test does not determine whether or not the view * has a valid layout, only whether or not the layout engine is * active for the view. * * Discussion: * The view's layout active state is also affected by the layout * active state of its parents; if any parent view has inactive * layout, this view is considered to have inactive layout as well. * See HIViewIsLayoutLatentlyActive if latent layout active state is * required. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose layout handling is to be tested. * * Result: * True if the view would respond to any linked relative's changes, * otherwise false. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewIsLayoutActive( inView: HIViewRef ): Boolean; external name '_HIViewIsLayoutActive'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewIsLayoutLatentlyActive() * * Summary: * The view's layout active state is also affected by the layout * active state of its parents; if any parent view has inactive * layout, this view is considered to have inactive layout as well. * HIViewIsLayoutLatentlyActive returns whether a view's layout is * latently active, even if one of its parent's layouts is not. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose latent layout handling is to be tested. * * Result: * True if the view would latently respond to any linked relative's * changes, otherwise false. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewIsLayoutLatentlyActive( inView: HIViewRef ): Boolean; external name '_HIViewIsLayoutLatentlyActive'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewApplyLayout() * * Summary: * Applies the current layout into to the specified view. Side * bindings have no effect, but positioning and scaling will occur, * in that order. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The HIView whose layout info is to be applied. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewApplyLayout( inView: HIViewRef ): OSStatus; external name '_HIViewApplyLayout'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {==============================================================================} { MISCELLANEOUS } {==============================================================================} { * HIViewGetWindow() * * Discussion: * Returns a reference to the window a given view is bound to. If * the view reference passed is invalid, or the view is not embedded * into any window, NULL is returned. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to query. * * Result: * A window reference. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewGetWindow( inView: HIViewRef ): WindowRef; external name '_HIViewGetWindow'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewFindByID() * * Discussion: * Allows you to find a particular view by its ID. Currently, this * call uses the ControlID type as its IDs. * * Mac OS X threading: * Not thread safe * * Parameters: * * inStartView: * The view to start searching at. * * inID: * The ID of the view you are looking for. * * outControl: * Receives the control if found. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewFindByID( inStartView: HIViewRef; inID: HIViewID; var outControl: HIViewRef ): OSStatus; external name '_HIViewFindByID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetAttributes() * * Discussion: * Allows you to get the attributes of a view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to inspect. * * outAttrs: * The attributes of the view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewGetAttributes( inView: HIViewRef; var outAttrs: OptionBits ): OSStatus; external name '_HIViewGetAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewChangeAttributes() * * Discussion: * Allows you to change the attributes of a view. You can * simultaneously set and clear attributes. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to muck with. * * inAttrsToSet: * The attributes you wish to set. * * inAttrsToClear: * The attributes you wish to clear. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewChangeAttributes( inView: HIViewRef; inAttrsToSet: OptionBits; inAttrsToClear: OptionBits ): OSStatus; external name '_HIViewChangeAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewCreateOffscreenImage() * * Discussion: * Creates an CGImageRef for the view passed in. The view and any * children it has are rendered in the resultant image. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view you wish to create an image of. * * inOptions: * Options. Currently you must pass 0. * * outFrame: * The frame of the view within the resultant image. It is in the * coordinate system of the image, where 0,0 is the top left * corner of the image. This is so you can know exactly where the * control lives in the image when the control draws outside its * bounds for things such as shadows. * * outImage: * The image of the view, including anything that would be drawn * outside the view's frame. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewCreateOffscreenImage( inView: HIViewRef; inOptions: OptionBits; outFrame: HIRectPtr { can be NULL }; var outImage: CGImageRef ): OSStatus; external name '_HIViewCreateOffscreenImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewDrawCGImage() * * Discussion: * Draws an image in the right direction for an HIView. This is * functionally the same as CGContextDrawImage, but it flips the * context appropriately so that the image is drawn correctly. * Because HIViews have their origin at the top, left, you are * really drawing upside-down, so if you were to use the CG image * drawing, you'd see what I mean! This call attempts to insulate * you from that fact. * * Mac OS X threading: * Not thread safe * * Parameters: * * inContext: * The context to draw in. * * inBounds: * The bounds to draw the image into. * * inImage: * The image to draw. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIViewDrawCGImage( inContext: CGContextRef; const (*var*) inBounds: HIRect; inImage: CGImageRef ): OSStatus; external name '_HIViewDrawCGImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIViewGetFeatures() * * Discussion: * Returns the features for the current view. This only returns * feature bits for the HIView space. Older Control Manager features * such as kControlSupportsDataAccess are not returned. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to query * * outFeatures: * On output, the features for the view. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewGetFeatures( inView: HIViewRef; var outFeatures: HIViewFeatures ): OSStatus; external name '_HIViewGetFeatures'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIViewChangeFeatures() * * Discussion: * Allows you to change a view's features on the fly. Typically, * this is up to the view itself to control. For example, it might * decide that under some situations it is opaque and other others * it is transparent. In general entities outside of the view itself * should not call this function. The only exception might be UI * building tools, where it would want to make sure a view always * responds to clicks, for example, so it could override mouse * tracking to drag items around. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to change * * inFeaturesToSet: * The features to enable * * inFeaturesToClear: * The features to disable * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIViewChangeFeatures( inView: HIViewRef; inFeaturesToSet: HIViewFeatures; inFeaturesToClear: HIViewFeatures ): OSStatus; external name '_HIViewChangeFeatures'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * Summary: * Constants for use with the HICreateTransformedCGImage API. } const { * No visual transform should be applied. } kHITransformNone = $00; { * The image should be transformed to use a disabled appearance. This * transform should not be combined with any other transform. } kHITransformDisabled = $01; { * The image should be transformed to use a selected appearance. This * transform should not be combined with any other transform. } kHITransformSelected = $4000; { * HICreateTransformedCGImage() * * Summary: * Creates a new CGImage with a standard selected or disabled * appearance. * * Mac OS X threading: * Not thread safe * * Parameters: * * inImage: * The original image. * * inTransform: * The transform to apply to the image. * * outImage: * The new image. This image should be released by the caller. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HICreateTransformedCGImage( inImage: CGImageRef; inTransform: OptionBits; var outImage: CGImageRef ): OSStatus; external name '_HICreateTransformedCGImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIViewGetEventTarget() * * Discussion: * Returns the EventTargetRef for the specified view. Once you * obtain this reference, you can send events to the target and * install event handler on it. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to return the target for. * * Result: * An EventTargetRef. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIViewGetEventTarget( inView: HIViewRef ): EventTargetRef; external name '_HIViewGetEventTarget'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {==============================================================================} { HIGrowBoxView } { The grow box view is a new view starting in Mac OS 10.2. It can be used in } { both the new compositing mode, as well as the traditional control manager } { mode. Like all new HIFoo views, this view is created invisibly. You must } { show the view after creation if you want to, like, see it and stuff. } {==============================================================================} { The HIObject class ID for the HIGrowBoxView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIGrowBoxViewClassID CFSTRP('com.apple.higrowboxview')} {$endc} { Control Kind} const kControlKindHIGrowBoxView = FourCharCode('grow'); { Currently there is no direct creation API for the grow box, so you must use } { HIObjectCreate if you wish to create one directly. Normally, a window will } { create one for you, so you should generally never need to do this. } { * HIGrowBoxViewSetTransparent() * * Discussion: * Sets a grow box view as transparent, meaning it will draw the * grow box lines over any content below it. When not transparent, * it's an opaque white square with the grow lines. * * Mac OS X threading: * Not thread safe * * Parameters: * * inGrowBoxView: * The grow box view reference. * * inTransparent: * Pass true to make the grow view use its transparent look, false * to give it the opaque look. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIGrowBoxViewSetTransparent( inGrowBoxView: HIViewRef; inTransparent: Boolean ): OSStatus; external name '_HIGrowBoxViewSetTransparent'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIGrowBoxViewIsTransparent() * * Discussion: * Returns true if a grow box view is set to be transparent. * * Mac OS X threading: * Not thread safe * * Parameters: * * inGrowBoxView: * The grow box view reference. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIGrowBoxViewIsTransparent( inGrowBoxView: HIViewRef ): Boolean; external name '_HIGrowBoxViewIsTransparent'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { HIScrollView } { The scroll view is a new view starting in Mac OS 10.2. It can be used in } { the new compositing mode ONLY due to the nature of how it works. Like all } { new HIFoo views, this view is created invisibly. You must show the view } { after creation if you want to, like, see it and stuff. } { The HIScrollView will set the frame of the contained view when its bounds } { change, so it is not necessary to set up the layout of the embedded view. } { Using an HIScrollView requires a few steps: } { 1. Install your scrollable content view into the HIScrollView instance using } { HIViewAddSubview. } { 2. If the scrollable content view doesn't already handle the } { kEventScrollableGetInfo and kEventScrollableScrollTo events, you must } { install handlers on your scrollable content view and handle those events } { manually. More details on those events can be found below. } { 3. If the scrollable content view doesn't already send out the } { kEventScrollableInfoChanged event to its parent view, you must send this } { event to the HIScrollView instance whenever your scrollable content } { view's size or origin changes. More details on this even can be found } { below. } {==============================================================================} { The HIObject class ID for the HIScrollView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIScrollViewClassID CFSTRP('com.apple.HIScrollView')} {$endc} { Control Kind} const kControlKindHIScrollView = FourCharCode('scrl'); { kEventClassScrollable quick reference: kEventScrollableGetInfo = 1, kEventScrollableInfoChanged = 2, %% kEventScrollableEmbedded = 3, %% kEventScrollableRemoved = 4, kEventScrollableScrollTo = 10 } const kEventClassScrollable = FourCharCode('scrl'); const kEventParamImageSize = FourCharCode('imsz'); { typeHISize} kEventParamViewSize = FourCharCode('vwsz'); { typeHISize} kEventParamLineSize = FourCharCode('lnsz'); { typeHISize} kEventParamOrigin = FourCharCode('orgn'); { typeHIPoint} { * kEventClassScrollable / kEventScrollableGetInfo * * Summary: * Requests information from an HIScrollView’s scrollable view about * its size and origin. * * Discussion: * This event is sent by an HIScrollView to its scrollable view to * determine the current size and origin of the scrollable view. A * scrollable view must implement this event in order to scroll * properly inside an HIScrollView. * * Mac OS X threading: * Not thread safe * * Parameters: * * <-- kEventParamImageSize (out, typeHISize) * On exit, contains the size of the entire scrollable view. * * <-- kEventParamViewSize (out, typeHISize) * On exit, contains the amount of the scrollable view that is * visible. * * <-- kEventParamLineSize (out, typeHISize) * On exit, contains the amount that should be scrolled in * response to a single click on a scrollbar arrow. * * <-- kEventParamOrigin (out, typeHIPoint) * On exit, contains the scrollable view’s current origin (the * view-relative coordinate that is drawn at the top left * corner of its frame). These coordinates should always be * greater than or equal to zero. They should be less than or * equal to the view’s image size minus its view size. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available } const kEventScrollableGetInfo = 1; { * kEventClassScrollable / kEventScrollableInfoChanged * * Summary: * Notification that the size or origin of an HIScrollView’s * scrollable view has changed. * * Discussion: * This event is not sent by HIScrollView itself; rather, it may be * sent to an instance of HIScrollView to notify the scroll view * that the size or origin of its scrollable view have changed. The * HIScrollView responds to this event by sending a * kEventScrollableGetInfo to its scrollable view. It then updates * the scroll bars appropriately to reflect the new reality of the * scrollable view. It does NOT move the origin of the scrollable * view at all. It is just a notification to allow the scroll view * to sync up with its scrollable view. * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available } const kEventScrollableInfoChanged = 2; { * kEventClassScrollable / kEventScrollableScrollTo * * Summary: * Requests that an HIScrollView’s scrollable view should scroll to * a particular origin. * * Discussion: * This event is sent by an HIScrollView to its scrollable view to * request that the scrollable view update its current origin and * redraw. Typically, a scrollable view will record its current * origin in its own instance data; it should update the origin in * response to this event. A scrollable view should also use either * HIViewScrollRect to scroll its content, or HIViewSetNeedsDisplay * to cause itself to redraw using the new origin point. A * scrollable view must implement this event in order to scroll * properly inside an HIScrollView. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamOrigin (in, typeHIPoint) * The new origin for the scrollable view. The origin * coordinates will vary from (0,0) to scrollable view’s image * size minus its view size. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available } const kEventScrollableScrollTo = 10; { * Summary: * HIScrollView options } const { * This indicates that a vertical scroll bar is desired. } kHIScrollViewOptionsVertScroll = 1 shl 0; { * This indicates that a horizontal scroll bar is desired. } kHIScrollViewOptionsHorizScroll = 1 shl 1; { * This indicates that space for a grow box should be taken into * account when laying out scroll bars. On Mac OS X 10.3 and earlier, * if both the horizontal and vertical scroll bars are requested, * this attribute is assumed. On Mac OS X 10.4 and later, this * attribute is *NOT* assumed; this allows the scroll view to support * auto-hiding of the two scroll bars independently on Mac OS X 10.4 * and later. If you want to preserve space for the grow box on all * systems, specify this option bit. } kHIScrollViewOptionsAllowGrow = 1 shl 2; kHIScrollViewValidOptions = kHIScrollViewOptionsVertScroll or kHIScrollViewOptionsHorizScroll or kHIScrollViewOptionsAllowGrow; { * HIScrollViewAction * * Summary: * HIScrollView navigation actions. See HIScrollViewNavigate for * more information. } type HIScrollViewAction = UInt32; const { * The scroll view should move to the top of the content. } kHIScrollViewScrollToTop = 1 shl 0; { * The scroll view should move to the bottom of the content. } kHIScrollViewScrollToBottom = 1 shl 1; { * The scroll view should move to the left of the content. } kHIScrollViewScrollToLeft = 1 shl 2; { * The scroll view should move to the right of the content. } kHIScrollViewScrollToRight = 1 shl 3; { * The scroll view should page up. } kHIScrollViewPageUp = 1 shl 4; { * The scroll view should page down. } kHIScrollViewPageDown = 1 shl 5; { * The scroll view should page left. } kHIScrollViewPageLeft = 1 shl 6; { * The scroll view should page right. } kHIScrollViewPageRight = 1 shl 7; { * HIScrollViewCreate() * * Discussion: * Creates a scroll view. This view has 3 parts, essentially. It can * have one or two scroll bars (horizontal/vertical), and a view to * be scrolled. The view to be scrolled is merely added via * HIViewAddSubview. The scroll view will automatically connect it * up appropriately. **** THIS MAY CHANGE * * Mac OS X threading: * Not thread safe * * Parameters: * * inOptions: * Options for our scroll view. You must specify either a * horizontal or a vertical scroll bar. If neither is passed, an * error is returned. * * outView: * The new scroll view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIScrollViewCreate( inOptions: OptionBits; var outView: HIViewRef ): OSStatus; external name '_HIScrollViewCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIScrollViewSetScrollBarAutoHide() * * Discussion: * Sets a scroll view's scroll bars to auto-hide when the entire * scrollable view it is managing can be fully displayed in its * bounds. This is similar to the behavior you see in the Preview * application. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to affect. * * inAutoHide: * The new auto-hide setting (true == auto-hide). * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIScrollViewSetScrollBarAutoHide( inView: HIViewRef; inAutoHide: Boolean ): OSStatus; external name '_HIScrollViewSetScrollBarAutoHide'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIScrollViewGetScrollBarAutoHide() * * Discussion: * Gets a scroll view's current scroll bar auto-hide setting. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to examine. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIScrollViewGetScrollBarAutoHide( inView: HIViewRef ): Boolean; external name '_HIScrollViewGetScrollBarAutoHide'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIScrollViewNavigate() * * Discussion: * Allows you to programmatically change what portion of a scroll * view's target you are seeing. For example, you can move to the * beginning or end of a document. You can also page up, down, left * and right. In general, you should not call this from embedded * content (i.e. the scrollable view inside the scroll view). For * those cases, you should instead position yourself appropriately * and tell the scroll view you changed via the * kEventScrollableInfoChanged carbon event. This routine merely is * a programmatic way to scroll as one would by hand using the * scroll bars. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The scroll view to affect. * * inAction: * The action to take. * * Result: * A operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIScrollViewNavigate( inView: HIViewRef; inAction: HIScrollViewAction ): OSStatus; external name '_HIScrollViewNavigate'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIScrollViewCanNavigate() * * Discussion: * Allows you to tell whether it is currently possible to navigate * somehow in a scroll view. For example, if a scroll view is * already at the top of the scrollable content, it is not possible * to navigate upward, so home and page up actions would not be * possible. You might use this function to help you update the * state of menu items or the like. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view to examine. * * inAction: * The action to test. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIScrollViewCanNavigate( inView: HIViewRef; inAction: HIScrollViewAction ): Boolean; external name '_HIScrollViewCanNavigate'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {==============================================================================} { HIImageView } { The image view is a new view starting in Mac OS 10.2. It can only be used } { in a compositing window. Like all new HIFoo views, this view is initially } { invisible. You must show the view after creation. } {==============================================================================} { The HIObject class ID for the HIImageView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIImageViewClassID CFSTRP('com.apple.HIImageView')} {$endc} { ControlKind} const kControlKindHIImageView = FourCharCode('imag'); { * HIImageViewCreate() * * Discussion: * Creates an image view. The view responds to the scrollable * interface and can be used in a scrolling view. You can pass an * image initially, or set one later. * * Mac OS X threading: * Not thread safe * * Parameters: * * inImage: * An initial image, or NULL. You can set the image later via * SetControlData. * * outControl: * The new image view. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewCreate( inImage: CGImageRef { can be NULL }; var outControl: ControlRef ): OSStatus; external name '_HIImageViewCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) const kHIImageViewImageTag = FourCharCode('imag'); { CGImageRef (THIS TAG IS GOING AWAY!!! USE THE APIS BELOW!)} { * HIImageViewSetOpaque() * * Discussion: * Allows you to set whether an image view should be treated as * opaque. If this is set to true, the image view can make certain * optimizations for compositing and scrolling. The alpha-related * image view APIs are rendered useless if opacity it set to true. * An image view, when created, is transparent by default. * * NOTE: In Mac OS X 10.2, this control was documented as being * opaque by default, but the implementation did not enforce that. * So in Mac OS X 10.3 and beyond, the control is transparent by * default, and you can make it opaque by calling * HIImageViewSetOpaque. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to affect. * * inOpaque: * The new opacity setting. Pass true to indicate you want the * image to be treated as opaque. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewSetOpaque( inView: HIViewRef; inOpaque: Boolean ): OSStatus; external name '_HIImageViewSetOpaque'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewIsOpaque() * * Discussion: * Allows you to determine whether an image view is opaque or not. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to query. * * Result: * A boolean result, where true indicates the image view is opaque. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewIsOpaque( inView: HIViewRef ): Boolean; external name '_HIImageViewIsOpaque'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewSetAlpha() * * Discussion: * Allows you to set the alpha for an image, making it more or less * transparent. An alpha of 1.0 is fully opaque, and 0.0 is fully * transparent. The default alpha for an image is 1.0. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to affect. * * inAlpha: * The new alpha value. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewSetAlpha( inView: HIViewRef; inAlpha: Float32 ): OSStatus; external name '_HIImageViewSetAlpha'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewGetAlpha() * * Discussion: * Allows you to get the alpha for an image. An alpha of 1.0 is * fully opaque, and 0.0 is fully transparent. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to query. * * Result: * A floating point number representing the alpha from 0.0 through * 1.0. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewGetAlpha( inView: HIViewRef ): Float32; external name '_HIImageViewGetAlpha'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewSetScaleToFit() * * Discussion: * Normally an image view will clip to the view's bounds. Using this * API, you can instead tell the image view to size the image to fit * into the view bounds specified. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to affect. * * inScaleToFit: * A boolean indicating whether the image should be scaled to fit * the view bounds (true) or merely clip to the view bounds * (false). * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewSetScaleToFit( inView: HIViewRef; inScaleToFit: Boolean ): OSStatus; external name '_HIImageViewSetScaleToFit'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewGetScaleToFit() * * Discussion: * Returns whether or not an image view will scale the image it * displays to the view bounds or merely clip to the view bounds. A * true result means it scales. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to query. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewGetScaleToFit( inView: HIViewRef ): Boolean; external name '_HIImageViewGetScaleToFit'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewSetImage() * * Discussion: * Sets the image to display in an image view. The image passed in * is retained by the view, so you may release the image after * calling this API if you no longer need to reference it. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to affect. * * inImage: * The image to set. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewSetImage( inView: HIViewRef; inImage: CGImageRef { can be NULL } ): OSStatus; external name '_HIImageViewSetImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIImageViewCopyImage() * * Discussion: * Gets the image for an image view. If there is no image set on the * view, or the view ref is invalid, NULL is returned. The image is * retained, so you should take care to release it when you are * finished with it. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The image view to query. * * Result: * A CoreGraphics (Quartz) image ref. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIImageViewCopyImage( inView: HIViewRef ): CGImageRef; external name '_HIImageViewCopyImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {==============================================================================} { HIComboBox } { The combo box is a new view starting in Mac OS 10.2. It can be used in } { both the new compositing mode, as well as the traditional control manager } { mode. Like all new HIFoo views, this view is created invisible. You must } { show the view after creation if you want to, like, see it and stuff. } {==============================================================================} { The HIObject class ID for the HIComboBox class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIComboBoxClassID CFSTRP('com.apple.HIComboBox')} {$endc} { kEventClassHIComboBox quick reference: kEventComboBoxListItemSelected = 1 } const kEventClassHIComboBox = FourCharCode('hicb'); const kEventParamComboBoxListSelectedItemIndex = FourCharCode('cbli'); { * kEventClassHIComboBox / kEventComboBoxListItemSelected * * Summary: * Notification that an item in the ComboBox disclosure list has * been selected. * * Discussion: * This event is sent as a notification when an item in the ComboBox * disclosure list has been selected. This event is sent to all * handlers installed on the control. This does not imply that the * selection has been accepted; for that you will need to register * for the kEventClassTextField/kEventTextAccepted event; you can * register for that event in order to make live selections however. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamDirectObject (in, typeControlRef) * The ComboBox view that has sent the notification. * * --> kEventParamComboBoxListSelectedItemIndex (in, typeCFIndex) * The index of the combo box list item that has been selected. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventComboBoxListItemSelected = 1; { * Summary: * ComboBox attributes } const { * A constant with value zero; the lack of any attributes. } kHIComboBoxNoAttributes = 0; { * The control will attempt to auto complete the text the user is * typing with an item in the ComboBox list that is the closest * appropriate match. } kHIComboBoxAutoCompletionAttribute = 1 shl 0; { * The control will disclose the ComboBox list after the user enters * text. } kHIComboBoxAutoDisclosureAttribute = 1 shl 1; { * The items in the ComboBox list will be automatically sorted in * alphabetical order. } kHIComboBoxAutoSortAttribute = 1 shl 2; { * The ComboBox list will be automatically sized to fit the Human * Interface Guidelines. } kHIComboBoxAutoSizeListAttribute = 1 shl 3; { * The minimum set of ComboBox attributes commonly used. } kHIComboBoxStandardAttributes = kHIComboBoxAutoCompletionAttribute or kHIComboBoxAutoDisclosureAttribute or kHIComboBoxAutoSizeListAttribute; { ControlKind} const kControlKindHIComboBox = FourCharCode('cbbx'); { ComboBox Part codes} const kHIComboBoxEditTextPart = 5; kHIComboBoxDisclosurePart = 28; { The ComboBox view supports these tags previously defined for the EditUnicodeText control. These tags are available through Get/SetControlData with a ControlPartCode of kHIComboBoxEditTextPart: kControlFontStyleTag kControlEditTextFixedTextTag kControlEditTextTextTag kControlEditTextKeyFilterTag kControlEditTextValidationProcTag kControlEditUnicodeTextPostUpdateProcTag kControlEditTextSelectionTag kControlEditTextKeyScriptBehaviorTag kControlEditTextCharCount kControlEditTextCFStringTag } { * Discussion: * ComboBox ControlData tags available with Mac OS X 10.2 and later. } const { * Extract the contents of the ComboBox list as a CFArray. The * CFArray will be retained: if you get the array, you own it and * will be required to release it; if you set it the toolbox makes a * copy of it and you are free to release your reference. } kHIComboBoxListTag = FourCharCode('cbls'); { CFArrayRef; bumps the refCount on get/retains on set} { * The width of the ComboBox list. This can be customized. This * disables the autosize attribute. } kHIComboBoxListPixelWidthTag = FourCharCode('cblw'); { UInt32 } { * The height of the ComboBox list. This can be customized. This * disables the autosize attribute. } kHIComboBoxListPixelHeightTag = FourCharCode('cblh'); { UInt32} { * The number of visible items in the list. This can be customized. * This disables the autosize attribute. } kHIComboBoxNumVisibleItemsTag = FourCharCode('cbni'); { UInt32} { * HIComboBoxCreate() * * Summary: * Creates a combo box control. The new control is initially * invisible. * * Mac OS X threading: * Not thread safe * * Parameters: * * boundsRect: * The bounding box of the control. * * text: * The default text in the editable portion of the control. Can be * NULL. * * style: * The font style of the both editable text and the text in the * disclosure list. Can be NULL. * * list: * The default values available in the disclosure list. Can be * NULL. * * inAttributes: * The default attributes of the combo box. * * outComboBox: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxCreate( const (*var*) boundsRect: HIRect; text: CFStringRef { can be NULL }; {const} style: ControlFontStyleRecPtr { can be NULL }; list: CFArrayRef { can be NULL }; inAttributes: OptionBits; var outComboBox: HIViewRef ): OSStatus; external name '_HIComboBoxCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxGetItemCount() * * Summary: * Get the number of items in the combo box disclosure list. * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box. * * Result: * The number of items in the combo box disclosure list. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxGetItemCount( inComboBox: HIViewRef ): ItemCount; external name '_HIComboBoxGetItemCount'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxInsertTextItemAtIndex() * * Summary: * Inserts a CFString in the disclosure list * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box whose disclosure list the text will be inserted * in. * * inIndex: * The index that the text should be inserted in. If the index * does not fall within the number of items in the combo box list, * it will be appended to the end of the list. * * inText: * The text item to be inserted in the combo box disclosure list. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxInsertTextItemAtIndex( inComboBox: HIViewRef; inIndex: CFIndex; inText: CFStringRef ): OSStatus; external name '_HIComboBoxInsertTextItemAtIndex'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxAppendTextItem() * * Summary: * Appends a text item to the combo box disclosure list. * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box whose disclosure list the text will be appended * to. * * inText: * The text item to be appended to the combo box disclosure list. * * outIndex: * On exit, the index of the new item. Can be NULL if the caller * does not require this information. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxAppendTextItem( inComboBox: HIViewRef; inText: CFStringRef; outIndex: CFIndexPtr { can be NULL } ): OSStatus; external name '_HIComboBoxAppendTextItem'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxCopyTextItemAtIndex() * * Summary: * Copy the text from the combo box disclosure list * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box that contains the text item you would like to * copy. * * inIndex: * The index of the text item. Will return paramErr if the index * is out of bounds of the combo box list. * * outString: * A copy of the string at the given index. Remember this is now * your copy that you will need to release. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxCopyTextItemAtIndex( inComboBox: HIViewRef; inIndex: CFIndex; var outString: CFStringRef ): OSStatus; external name '_HIComboBoxCopyTextItemAtIndex'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxRemoveItemAtIndex() * * Summary: * Remove an item from a combo box disclosure list. * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box that contains the disclosure list that you would * like to remove an item from. * * inIndex: * The index of the item to remove. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxRemoveItemAtIndex( inComboBox: HIViewRef; inIndex: CFIndex ): OSStatus; external name '_HIComboBoxRemoveItemAtIndex'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxChangeAttributes() * * Summary: * Change the attributes of a combo box * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box whose attributes you would like to change. * * inAttributesToSet: * The attributes to set. * * inAttributesToClear: * The attributes to clear. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxChangeAttributes( inComboBox: HIViewRef; inAttributesToSet: OptionBits; inAttributesToClear: OptionBits ): OSStatus; external name '_HIComboBoxChangeAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxGetAttributes() * * Summary: * Get the attributes of a combo box. * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box whose attributes you would like to obtain. * * outAttributes: * The attributes of the combo box. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIComboBoxGetAttributes( inComboBox: HIViewRef; var outAttributes: OptionBits ): OSStatus; external name '_HIComboBoxGetAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIComboBoxIsListVisible() * * Summary: * Returns whether the combo box list is currently disclosed. * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box whose list visibility you would like to obtain. * * Result: * A boolean value indicating whether the combo box list is * disclosed (true) or hidden (false). * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIComboBoxIsListVisible( inComboBox: HIViewRef ): Boolean; external name '_HIComboBoxIsListVisible'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIComboBoxSetListVisible() * * Summary: * Hides or shows the combo box list. * * Mac OS X threading: * Not thread safe * * Parameters: * * inComboBox: * The combo box whose list will be hidden or shown. * * inVisible: * A boolean value indicating whether you wish to hide the list * (false) or show the list (true). * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIComboBoxSetListVisible( inComboBox: HIViewRef; inVisible: Boolean ): OSStatus; external name '_HIComboBoxSetListVisible'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {==============================================================================} { HISearchField } { HISearchField is a new view available in Mac OS X 10.3. } { This view is designed to be used for applications that provide searching } { functionality. Visually, it is a standard text field optionally adorned } { with a search icon on the left and/or a cancel image on the right. } { When the user has accepted the text by pressing the return or enter key } { a Carbon Event of kEventClassTextField / kEventTextAccepted will be sent } { to the control. This will be the indication that the search should begin. } { This control will also respond to all the standard control tags that are } { used by the EditUnicodeText control. } {==============================================================================} { The HIObject class ID for the HISearchField class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHISearchFieldClassID CFSTRP('com.apple.HISearchField')} {$endc} { ControlKind} const kControlKindHISearchField = FourCharCode('srfd'); { HISearchField part codes} const kControlSearchFieldCancelPart = 30; kControlSearchFieldMenuPart = 31; { The SearchField view supports those tags previously defined for the EditUnicodeText control. These tags are available through Get/SetControlData with ControlPartCode of kControlEditTextPart: kControlFontStyleTag kControlEditTextFixedTextTag kControlEditTextTextTag kControlEditTextKeyFilterTag kControlEditTextValidationProcTag kControlEditUnicodeTextPostUpdateProcTag kControlEditTextSelectionTag kControlEditTextKeyScriptBehaviorTag kControlEditTextCharCount kControlEditTextCFStringTag } { * Summary: * HISearchField attributes } const { * A constant with value zero; the lack of any attributes. } kHISearchFieldNoAttributes = 0; { * This view contains the cancel icon in the text field. } kHISearchFieldAttributesCancel = 1 shl 0; { * This view contains the search icon in the text field. If a menu is * associated with the search field, this attribute is implicitly set * and the search icon will display with a menu disclosure badge. * Available in Mac OS X 10.4 and later. } kHISearchFieldAttributesSearchIcon = 1 shl 1; { Event Classes} const kEventClassSearchField = FourCharCode('srfd'); { * kEventClassSearchField / kEventSearchFieldCancelClicked * * Summary: * Notification that the cancel icon has been depressed. * * Discussion: * This event is sent by the HISearchField view if the cancel icon * is enabled (attribute of kHISearchFieldAtttributesCancel), and * the cancel has been clicked. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamDirectObject (in, typeControlRef) * The HISearchField that has sent the notification. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available } const kEventSearchFieldCancelClicked = 1; { * kEventClassSearchField / kEventSearchFieldSearchClicked * * Summary: * Notification that the search icon has been depressed. * * Discussion: * This event is sent by the HISearchField view if the search icon * is enabled (attribute of kHISearchFieldAttributesSearchIcon or a * menu is associated with the search field), and the search icon * has been clicked. If a menu is associated with the search field, * the search field will handle the display and tracking of the menu * by default. This event is sent to the search field only, it will * not propagate. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamDirectObject (in, typeControlRef) * The HISearchField that has sent the notification. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventSearchFieldSearchClicked = 2; { * HISearchFieldCreate() * * Summary: * Creates a search field control. The new control is initially * invisible. * * Mac OS X threading: * Not thread safe * * Parameters: * * inBounds: * The initial bounds of the view. If this parameter is NULL, the * view defaults to have empty bounds ( 0, 0, 0, 0 ). * * inAttributes: * The initial attributes of the search field. Indicates whether * the field should contain the cancel icon. * * inSearchMenu: * The menu to be associated with this search field. If * inSearchMenu is non-NULL, it will be retained by the search * field and the search icon will be enabled in the left side of * the text field. If this parameter is NULL, the view will not * display the search icon in the left portion of the text field. * You are expected to install handlers on this menu to handle the * visual appearance of the menu (for example, to draw check marks * or enable items when the menu receives the * kEventMenuEnableItems Carbon Event), and to keep track of what * action should be performed by associating HICommands with each * menu item and installing a handler for the ( * kEventClassCommand, kEventCommandProcess ) Carbon Event. * * inDescriptiveText: * The text to be displayed in the text field when the field does * not have focus and contains no user entered text. This is meant * to be an indication of what the search criteria is. For * example, you may wish to identify to the user that the search * will cover the "Subject" or "Contents" of a selected range of * items. If inDescriptiveText is non-NULL it will be retained by * the search field. * * outRef: * On exit, contains the new view. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldCreate( {const} inBounds: HIRectPtr { can be NULL }; inAttributes: OptionBits; inSearchMenu: MenuRef { can be NULL }; inDescriptiveText: CFStringRef { can be NULL }; var outRef: HIViewRef ): OSStatus; external name '_HISearchFieldCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISearchFieldSetSearchMenu() * * Summary: * Set the search menu associated with the view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSearchField: * The search field to associate the search menu with. * * inSearchMenu: * The menu to associate with the search field. If there is * already a menu associated with the search field, that menu will * be released. If inSearchMenu is non-NULL, it will be retained * by the search field and the search icon will be enabled in the * left side of the text field. You are expected to install * handlers on this menu to handle the visual appearance of the * menu (for example, to draw check marks or enable items when the * menu receives the kEventMenuEnableItems Carbon Event), and to * keep track of what action should be performed by associating * HICommands with each menu item and installing a handler for the * ( kEventClassCommand, kEventCommandProcess ) Carbon Event. If * inSearchMenu is NULL, the search icon will be removed from the * left side of the text field and no menu will be associated with * this field. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldSetSearchMenu( inSearchField: HIViewRef; inSearchMenu: MenuRef { can be NULL } ): OSStatus; external name '_HISearchFieldSetSearchMenu'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISearchFieldGetSearchMenu() * * Summary: * Get the menu that is associated with the search field * * Mac OS X threading: * Not thread safe * * Parameters: * * inSearchField: * The search field you wish to retrieve the search menu from. * * outSearchMenu: * On exit, will contain the menu that is associated with search * field. The menu will _not_ be retained on output and this * parameter cannot be NULL. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldGetSearchMenu( inSearchField: HIViewRef; var outSearchMenu: MenuRef ): OSStatus; external name '_HISearchFieldGetSearchMenu'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISearchFieldChangeAttributes() * * Summary: * Set the attributes for the given search field. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSearchField: * The search field to change the attributes of. * * inAttributesToSet: * The attributes to set. * * inAttributesToClear: * The attributes to clear. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldChangeAttributes( inSearchField: HIViewRef; inAttributesToSet: OptionBits; inAttributesToClear: OptionBits ): OSStatus; external name '_HISearchFieldChangeAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISearchFieldGetAttributes() * * Summary: * Returns the attributes of the search field. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSearchField: * The search field to get the attributes of. * * outAttributes: * On exit, will contain the attributes of the search field. This * parameter cannot be NULL. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldGetAttributes( inSearchField: HIViewRef; var outAttributes: OptionBits ): OSStatus; external name '_HISearchFieldGetAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISearchFieldSetDescriptiveText() * * Summary: * Set the description of the search action of the search field. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSearchField: * The search field to change the description of. * * inDescription: * The new description for the search field. If the search field * contains a description, it will be released. If inDescription * is non-NULL, it will be retained by the search field. If it is * NULL, no description will be associated with the search field. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldSetDescriptiveText( inSearchField: HIViewRef; inDescription: CFStringRef { can be NULL } ): OSStatus; external name '_HISearchFieldSetDescriptiveText'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISearchFieldCopyDescriptiveText() * * Summary: * Get the description that is associated with the search field. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSearchField: * The search field you wish to retrieve the description from. * * outDescription: * On exit, will contain the description that is associated with * the search field. This parameter cannot be NULL. If there is no * description associated with the search field, outDescription * will be set to NULL. If there is a description, a CFStringRef * will be created that contains the contents of the description. * You posess ownership of this string and will need to release it * when you no longer need it. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISearchFieldCopyDescriptiveText( inSearchField: HIViewRef; var outDescription: CFStringRef ): OSStatus; external name '_HISearchFieldCopyDescriptiveText'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {==============================================================================} { Text field events } { A text field is the part of some controls that you can enter text into. } { A text field is common to the EditText, EditUnicodeText, ComboBox, } { HISearchField, and HITextView views. The kEventClassTextField event allows } { you to receive notifications when the text has been accepted by the user. } { For example, you can install a handler for a } { kEventClassTextField / kEventTextAccepted event on a HISearchField view to } { receive a notification that the user has initiated a search by hitting the } { return or enter key. You can also filter the text that will replace a } { selection before the change has been made to either accept or reject the } { replacement. } {==============================================================================} { kEventClassTextField quick reference: kEventTextAccepted = 1, kEventTextShouldChangeInRange = 2, kEventTextDidChange = 3 } const kEventClassTextField = FourCharCode('txfd'); const kEventParamTextSelection = FourCharCode('txsl'); { typeCFRange} kEventParamCandidateText = FourCharCode('tstx'); { typeCFStringRef} kEventParamReplacementText = FourCharCode('trtx'); { typeCFStringRef} kEventParamUnconfirmedRange = FourCharCode('tunr'); { typeCFRange} kEventParamUnconfirmedText = FourCharCode('txun'); { typeCFStringRef} { * kEventClassTextField / kEventTextAccepted * * Summary: * Notification that the text in a control's editable text field has * been accepted. * * Discussion: * This event is sent as a notification when the text contained in a * control's editable text field has been accepted by the user. Text * is accepted when the user presses return or enter on the keyboard * for the EditUnicodeText, HIComboBox, and HISearchField controls, * or when the text has changed in the field and the field loses * focus for the EditUnicodeText, HIComboBox, HISearchField and * HITextView controls. * * This event is sent to the control containing the text field only, * it will not propagate. It is sent to all handlers installed on * the control containing the text field. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamDirectObject (in, typeControlRef) * The editable text field that has sent the notification. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available } const kEventTextAccepted = 1; { * kEventClassTextField / kEventTextShouldChangeInRange * * Summary: * Returns whether the text should be changed in editable text * fields. * * Discussion: * There are several editable text field views, such as the * HIComboBox, HISearchField, HITextView, and EditUnicodeText * controls. There are times when you may require fine-grained * control over what text is inserted into the text field and either * accept the changes, reject them or modify what is to be entered. * This event is sent whenever the text is about to be modified in a * text field, either by user input or in other scenarios such as a * paste from the clipboard, spell-checking word correction, or Mac * OS X Service operation. You can change what text is inserted by * providing a replacement string as a parameter to this event. This * event is only sent for Unicode text controls; it is not sent for * the classic non-Unicode EditText control. * * This event is not sent prior to programmatic modification of the * text field contents using SetControlData. * * This event is not sent while an active inline editing session is * in progress. Once the inline text has been confirmed, this event * will be sent prior to the confirmed text being inserted into the * text field. If you need control over keystrokes during an inline * editing session, you can use the kEventTextInputFilterText event. * * * This event is sent to the control containing the text field only; * it will not propagate. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamTextSelection (in, typeCFRange) * The range of the selection that is about to be changed. The * units of the selection are in the same units that are * returned in a EditTextSelectionRec, when called with * GetControlData using kControlEditTextSelectionTag. * * --> kEventParamCandidateText (in, typeCFStringRef) * The text that is going to replace the selection. Note that * this string was originally created with * CFStringCreateWithCharactersNoCopy, and the original text * has a limited lifespan. If for some reason you need to * retain the text past the end of your event handler, you * should extract the characters from the string with * CFStringGetCharacters, and then store those characters or * create a new CFString from them. * * <-- kEventParamReplacementText (out, typeCFStringRef) * On output, can contain optional replacement text. * * Result: * If noErr is returned from your handler and the * kEventParamReplacementText parameter is added to the event, then * the contents of that parameter, rather than the candidate text, * will be added to the text field. * * If noErr is returned from your handler and the * kEventParamReplacementText parameter is _not_ added to the event, * then the candidate text will be filtered out and no text will be * entered in the text field. The current selection will be deleted, * however. * * If userCanceledErr is returned from your handler, then no text * will be entered in the text field and the current selection will * remain unchanged. Effectively, the editing operation will be * ignored. * * If eventNotHandledErr is returned from your handler, the contents * of the kEventParamReplacementText parameter are ignored, and the * candidate text will replace the selection. * * Any other return value will result in the default behavior, as if * eventNotHandledErr had been returned. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventTextShouldChangeInRange = 2; { * kEventClassTextField / kEventTextDidChange * * Summary: * Indicates that the contents of an editable text field have * changed. * * Discussion: * This event is sent by all of the Unicode-based editable text * views: HIComboBox, HISearchField, HITextView and EditUnicodeText. * This event is not sent for the classic non-Unicode EditText * control. * * Note that this event is sent after inline editing operations, * such as pressing a dead key, or using a input method that creates * an inline editing hole. Most clients of this event should ignore * the event during inline editing, and only respond to changes to * the text after inline editing completes. A client can check for * the presence of the kEventParamUnconfirmedRange parameter to * determine whether inline editing is currently active; if this * parameter is present, the client may wish to ignore the event. * * * This event is not sent after programmatic modification of the * text field contents using SetControlData. * * This event is sent only to the control containing the text field; * it will not propagate. It is sent to all handlers registered for * it. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamUnconfirmedRange (in, typeCFRange) * If the text field currently has an open inline hole, this * parameter contains the range of text inside the hole. This * parameter is optional and is only present during inline * editing. * * --> kEventParamUnconfirmedText (in, typeCFStringRef) * If the text field currently has an open inline hole, this * parameter contains the non-confirmed text currently being * edited inside the hole. This parameter is optional and is * only present during inline editing. Note that this string * was originally created with * CFStringCreateWithCharactersNoCopy, and the original text * has a limited lifespan. If for some reason you need to * retain the text past the end of your event handler, you * should extract the characters from the string with * CFStringGetCharacters, and then store those characters or * create a new CFString from them. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventTextDidChange = 3; {==============================================================================} { HIMenuView } { HIMenuView and HIStandardMenuView are new views available in Mac OS X 10.3. } { HIMenuView is intended for use as a base class for custom menu item views; } { it does not draw or handle events itself, but provides useful functionality } { that all menu views need to implement. HIStandardMenuView is the standard } { HIView used by the Menu Manager to draw menu item content, beginning with } { Mac OS X 10.3. It can also be subclassed by custom menu item views. } { Both of these views are meant to be used only in compositing windows. } { Because HIMenuView and HIStandardMenuView are not typically created } { directly by applications, no API is provided to create instances of these } { views. If you need to create an instance of either view, you can use } { HIObjectCreate. } {==============================================================================} { the HIObject class ID for the HIMenuView class} {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIMenuViewClassID CFSTRP('com.apple.HIMenuView')} {$endc} { the HIObject class ID for the standard menu HIView class} {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIStandardMenuViewClassID CFSTRP('com.apple.HIStandardMenuView')} {$endc} { Control Kinds (only used in Mac OS X 10.4 and later)} const kControlKindHIMenuView = FourCharCode('menu'); kControlKindHIStandardMenuView = FourCharCode('smnu'); { The kEventHIObjectInitialize event for HIMenuView and HIStandardMenuView is expected to contain the following parameters. Be sure to include these parameters in the init event if you create an instance of these views with HIObjectCreate. --> kEventParamMenuRef (in, typeMenuRef) The menu that the view should draw. } { * kHIViewMenuContentID * * Summary: * The HIViewID for the menu content view. The Menu Manager assigns * this view ID to all menu content views. * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kHIViewMenuContentID: HIViewID; external name '_kHIViewMenuContentID'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIMenuViewGetMenu() * * Summary: * Returns the MenuRef that is associated with an HIView that is a * subclass of HIMenuView. * * Discussion: * An HIMenuView subclass might use this API to determine the menu * that it should draw. * * Mac OS X threading: * Not thread safe * * Parameters: * * inView: * The view whose menu to return. * * Result: * The MenuRef associated with the HIView, or NULL if an HIView is * passed that is not a subclass of HIMenuView. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIMenuViewGetMenu( inView: HIViewRef ): MenuRef; external name '_HIMenuViewGetMenu'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HIMenuGetContentView() * * Summary: * Returns the HIViewRef that will be used to draw menu content for * this menu, if any. * * Discussion: * If the content view has not yet been created, the Menu Manager * will create the content view using the view class ID and * initialization event associated with the menu. Note that the menu * content view is not the same as the window content view; the menu * content view is embedded inside the window content view. If the * menu uses an MDEF instead of an HIView to draw its content, noErr * is returned but the output HIViewRef is set to NULL. * * Mac OS X threading: * Not thread safe * * Parameters: * * inMenu: * The menu. * * inMenuType: * The type of menu for which the menu content view should be * returned. The same MenuRef may have multiple content views, * depending on the menu type being displayed. * * outView: * On exit, contains the view. May be set to NULL if the menu does * not use an HIView to draw its content. The caller should not * release this view. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HIMenuGetContentView( inMenu: MenuRef; inMenuType: ThemeMenuType; var outView: HIViewRef ): OSStatus; external name '_HIMenuGetContentView'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {==============================================================================} { HISegmentedView } { HISegmentedView is a new view available in Mac OS X 10.3. } { Examples of the segmented view are the Finder's icon/column/list view } { switcher, and the back/forward buttons in Open panels. } { The segmented view operates as a group of buttons, each of which can be } { configured with different behaviors and content. } { Accessibility Notes: Those of you who wish to customize the accessibility } { information provided for individual segments of the segmented view -- by } { handling various kEventClassAccessibility Carbon Events, by calling } { HIObjectSetAuxiliaryAccessibilityAttribute, etc. -- need to know how to } { interpret and/or build AXUIElementRefs that represent individual segments. } { The AXUIElement representing an individual segment will/must be constructed } { using the segmented view's HIViewRef and the UInt64 identifier of the } { one-based index of the segment the element refers to. As usual, a UInt64 } { identifier of zero represents the segmented view as a whole. You must } { neither interpret nor create segmented view elements whose identifiers are } { greater than the count of segments in the segmented view. } {==============================================================================} { The HIObject class ID for the HISegmentedView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHISegmentedViewClassID CFSTRP('com.apple.HISegmentedView')} {$endc} { Control Kind} const kHISegmentedViewKind = FourCharCode('sgmt'); { * HISegmentedViewCreate() * * Summary: * Creates a segmented view. This is the type of view you would use * to implement the icon/column/list view switcher as seen in the * Finder. After creating a segmented view, you need to set the * number of segments via HISegmentedViewSetSegmentCount. Each * segment can be configured independently with via the other * HISegmentedView APIs. Changing the number of segments and * configuring each segment will change the appearance of the * segmented view. After you configure the view, you may want to * call GetBestControlRect on the view and resize it so the content * will fit optimally. The value of the whole segmented view * corresponds to the index of the currently selected segment with * the radio behavior. If you set the value of the whole segmented * view to n via SetControl32BitValue, every radio-behavior segment * will have its value set to zero except for the segment at index * n; if segment n also has the radio behavior, it will have its * value set to one. When a radio-behavior segment is clicked, the * value of the whole segmented view will be set to the segment's * index. The segmented view works in both compositing and * non-compositing modes. * * Mac OS X threading: * Not thread safe * * Parameters: * * inBounds: * The bounds of the view to be created. Can be NULL, in which * case the view is created with CGRectZero bounds. * * outRef: * A valid pointer to an HIViewRef. On successful completion of * this routine, the destination HIViewRef will be filled with the * HIViewRef of the newly created view. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewCreate( {const} inBounds: HIRectPtr { can be NULL }; var outRef: HIViewRef ): OSStatus; external name '_HISegmentedViewCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentCount() * * Summary: * Sets the number of segments for the segmented view. Any previous * segments beyond the new count will have their content released. * All new segments beyond the previous count be initialized with * the most basic settings possible: Momentary, no attributes, zero * value, enabled, no command, no label, no content, and * auto-calculated content width. You should configure any new * segments to match your needs. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view for which the content is to be set. * * inSegmentCount: * A positive integer indicating how many segments the view is to * have. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentCount( inSegmentedView: HIViewRef; inSegmentCount: UInt32 ): OSStatus; external name '_HISegmentedViewSetSegmentCount'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentCount() * * Summary: * Get the number of segments in the segmented view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view for which the content is to be set. * * Result: * A UInt32 indicating the number of segments in the segmented view. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentCount( inSegmentedView: HIViewRef ): UInt32; external name '_HISegmentedViewGetSegmentCount'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * Summary: * HISegmentBehavior constants } const { * Pops back up after being pressed, just like a push button. } kHISegmentBehaviorMomentary = 1; { * Stays pressed until another segment with the radio behavior is * pressed. This makes the segment behave like a radio button. After * this segment is clicked, the segmented view's value will be * changed to this segment's one-based index. } kHISegmentBehaviorRadio = 2; { * Like a check box. When clicked, it toggles back and forth between * checked and unchecked states. } kHISegmentBehaviorToggles = 3; { * After being pressed, this type of segment stays pressed until you * programatically unpress it. } kHISegmentBehaviorSticky = 4; type HISegmentBehavior = UInt32; { * HISegmentedViewSetSegmentBehavior() * * Summary: * Changes the behavior of an individual segment of a segmented * view. By default, a segment has the kHISegmentBehaviorMomentary * behavior. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose behavior you * want to change. * * inSegmentIndexOneBased: * The one-based index of the segment whose behavior you want to * change. This must be a non-zero value that is no higher than * the segmented view's current segment count. * * inBehavior: * A HISegmentBehavior describing the behavior you wish the * segment to have. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentBehavior( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inBehavior: HISegmentBehavior ): OSStatus; external name '_HISegmentedViewSetSegmentBehavior'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentBehavior() * * Summary: * Returns the behavior of an individual segment of a segmented view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment whose behavior you desire. * This must be a non-zero value that is no higher than the * segmented view's current segment count. * * Result: * A HISegmentBehavior describing the behavior of the given segment. * If you pass an illegal segment index, the result is undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentBehavior( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32 ): HISegmentBehavior; external name '_HISegmentedViewGetSegmentBehavior'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * Summary: * HISegmentedView segment attributes * * Discussion: * These attribute bits are for use with * HISegmentedViewChangeSegmentAttributes and * HISegmentedViewGetSegmentAttributes. } const { * Pass this to indicate no attributes at all. } kHISegmentNoAttributes = 0; { * If this attribute bit is set, the command that gets sent out when * the segment is clicked will be directed at the user focus instead * of up the segmented view's containment hierarchy. } kHISegmentSendCmdToUserFocus = 1 shl 0; { * HISegmentedViewChangeSegmentAttributes() * * Summary: * Changes the attributes of an individual segment of a segmented * view. By default, a segment has no attribute bits set. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose attributes you * want to change. * * inSegmentIndexOneBased: * The one-based index of the segment whose attributes you want to * change. This must be a non-zero value that is no higher than * the segmented view's current segment count. * * inAttributesToSet: * The attribute bits you wish to set/enable for the segment. * * inAttributesToClear: * The attribute bits you wish to clear/disable for the segment. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewChangeSegmentAttributes( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inAttributesToSet: OptionBits; inAttributesToClear: OptionBits ): OSStatus; external name '_HISegmentedViewChangeSegmentAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentAttributes() * * Summary: * Returns the attributes of an individual segment of a segmented * view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment whose attributes you desire. * This must be a non-zero value that is no higher than the * segmented view's current segment count. * * Result: * The attribute bits that are set/enabled for the given segment. If * you pass an illegal segment index, the result is undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentAttributes( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32 ): OptionBits; external name '_HISegmentedViewGetSegmentAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentValue() * * Summary: * Change the value of an individual segment of a segmented view. * This is only meaningful for segments with the sticky, toggles, or * radio behaviors. If you set the value of momentary segments to * something other than zero, the behavior is undefined. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose value you want * to change. * * inSegmentIndexOneBased: * The one-based index of the segment whose value you want to * change. This must be a non-zero value that is no higher than * the segmented view's current segment count. * * inValue: * The value you wish the segment to have. Zero means * unpressed/unselected and one means pressed/selected. Other * values will result in undefined behavior. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentValue( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inValue: SInt32 ): OSStatus; external name '_HISegmentedViewSetSegmentValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentValue() * * Summary: * Determine the value of an individual segment of a segmented view. * This is only meaningful for segments with the sticky, toggles, or * radio behaviors. The value of a momentary segment is undefined. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment whose value you desire. This * must be a non-zero value that is no higher than the segmented * view's current segment count. * * Result: * A SInt32 indicating the value of the given segment. If you pass * an illegal segment index, the result is undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentValue( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32 ): SInt32; external name '_HISegmentedViewGetSegmentValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentEnabled() * * Summary: * Enable or disable an individual segment of a segmented view. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment to enable or disable. * * inSegmentIndexOneBased: * The one-based index of the segment to disable or enable. This * must be a non-zero value that is no higher than the segmented * view's current segment count. * * inEnabled: * A Boolean indicating whether the segment is to become enabled * or disabled. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentEnabled( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inEnabled: Boolean ): OSStatus; external name '_HISegmentedViewSetSegmentEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewIsSegmentEnabled() * * Summary: * Test an individual segment of a segmented view to see if it is * enabled or disabled. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment to test. This must be a * non-zero value that is no higher than the segmented view's * current segment count. * * Result: * True if the segment is enabled or false if the segment is * disabled. If you pass an illegal segment index, the result is * undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewIsSegmentEnabled( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32 ): Boolean; external name '_HISegmentedViewIsSegmentEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentCommand() * * Summary: * Set the command ID for the given segment. By default, the command * is zero. If you set any non-zero command ID, the segmented view * will send an HICommand whenever the segment is clicked. By * default, the command is sent to the segmented view and up the * containment hierarchy. You can request that the command start at * the user focus instead by turning on the * kHISegmentSendCmdToUserFocus attribute for the segment. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose command you * wish to set. * * inSegmentIndexOneBased: * The one-based index of the segment whose command you wish to * set. This must be a non-zero value that is no higher than the * segmented view's current segment count. * * inCommand: * The command ID you wish to associate with the segment. A value * of zero signifies "no command". * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentCommand( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inCommand: UInt32 ): OSStatus; external name '_HISegmentedViewSetSegmentCommand'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentCommand() * * Summary: * Get the command ID associated with the given segment. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment to query. This must be a * non-zero value that is no higher than the segmented view's * current segment count. * * Result: * Returns the command ID associated with the segment. If you pass * an illegal segment index, the result is undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentCommand( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32 ): UInt32; external name '_HISegmentedViewGetSegmentCommand'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentLabel() * * Summary: * Set the label string for the given segment. By default, a segment * has no label string. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose label you wish * to set. * * inSegmentIndexOneBased: * The one-based index of the segment whose label you wish to set. * This must be a non-zero value that is no higher than the * segmented view's current segment count. * * inLabel: * A CFStringRef with the text of the label. The segmented view * will copy the string passed in. You may pass NULL or an empty * CFStringRef if you wish to eliminate the label from the segment. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentLabel( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inLabel: CFStringRef ): OSStatus; external name '_HISegmentedViewSetSegmentLabel'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewCopySegmentLabel() * * Summary: * Get the label associated with the given segment. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment to query. This must be a * non-zero value that is no higher than the segmented view's * current segment count. * * outLabel: * On exit, outLabel will be a copy of the label associated with * the segment; you must release this string. If there is no label * associated with the segment, outLabel will be set to NULL. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewCopySegmentLabel( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; var outLabel: CFStringRef ): OSStatus; external name '_HISegmentedViewCopySegmentLabel'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentContentWidth() * * Summary: * Sets whether you want the segment to automatically calculate its * own width or whether you want to determine the segment's width * manually. The content width is the horizontal area taken up by a * segment's label and/or image. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose content width * you wish to set. * * inSegmentIndexOneBased: * The one-based index of the segment whose content width you wish * to set. This must be a non-zero value that is no higher than * the segmented view's current segment count. * * inAutoCalculateWidth: * A Boolean indicating whether you want the segment to calculate * its own width. If you pass true, the inWidth parameter is * ignored. * * inWidth: * If you passed false in inAutoCalculateWidth, this parameter * specifies the width you want to manually associate with the * segment. If you pass a negative width, the behavior is * undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentContentWidth( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; inAutoCalculateWidth: Boolean; inWidth: Float32 ): OSStatus; external name '_HISegmentedViewSetSegmentContentWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentContentWidth() * * Summary: * Get the content width of the given segment. This also optionall * passes back a Boolean indicating whether the width was * automatically calculated. The content width is the horizontal * area taken up by a segment's label and/or image. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment to query. This must be a * non-zero value that is no higher than the segmented view's * current segment count. * * outAutoCalculated: * On exit, this is a Boolean indicating whether the width was * automatically calculated. You may pass NULL if you don't need * this information. * * Result: * Returns the width of the content for the given segment. If you * pass an illegal segment index, the result is undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentContentWidth( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; outAutoCalculated: BooleanPtr { can be NULL } ): Float32; external name '_HISegmentedViewGetSegmentContentWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewSetSegmentImage() * * Summary: * Sets or clears the image associated with a given segment. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment whose image you wish * to set. * * inSegmentIndexOneBased: * The one-based index of the segment whose image you wish to set. * This must be a non-zero value that is no higher than the * segmented view's current segment count. * * inImage: * An HIViewImageContentInfo structure with the image information * for the given segment. Segments only support three types of * image content: kControlNoContent (no image), * kControlContentIconRef, and kControlContentCGImageRef. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewSetSegmentImage( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; const (*var*) inImage: HIViewImageContentInfo ): OSStatus; external name '_HISegmentedViewSetSegmentImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewGetSegmentImageContentType() * * Summary: * Get the type of image content drawn by the given segment. You * will need to call this before calling * HISegmentedViewCopySegmentImage so you know what type of image * content to request from the latter API. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment to query. This must be a * non-zero value that is no higher than the segmented view's * current segment count. * * Result: * Returns the image content type of the image drawn by the given * segment. If you pass an illegal segment index, the result is * undefined. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewGetSegmentImageContentType( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32 ): HIViewImageContentType; external name '_HISegmentedViewGetSegmentImageContentType'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * HISegmentedViewCopySegmentImage() * * Summary: * Gives you a copy of the image (if any) drawn by the given * segment. You are responsible for releasing any image passed back * by this function. You request the image by asking for a * particular type of image. If the segment isn't using the * requested type of image, an error will be returned. If you wish * to know the actual type of image displayed by the segment, you * can call HISegmentedViewGetSegmentImageContentType. * * Mac OS X threading: * Not thread safe * * Parameters: * * inSegmentedView: * The segmented view which owns the segment being queried. * * inSegmentIndexOneBased: * The one-based index of the segment to query. This must be a * non-zero value that is no higher than the segmented view's * current segment count. * * ioImage: * On entry, you must fill out the contentType field of this * structure with the type of image you desire. On exit, if that * type of image is used by the segment, the appropriate field of * the union will be filled in with a copy of the image. You are * responsible for releasing the image. * * Availability: * Mac OS X: in version 10.3 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.3 and later * Non-Carbon CFM: not available } function HISegmentedViewCopySegmentImage( inSegmentedView: HIViewRef; inSegmentIndexOneBased: UInt32; var ioImage: HIViewImageContentInfo ): OSStatus; external name '_HISegmentedViewCopySegmentImage'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {==============================================================================} { Clock view events } {==============================================================================} const kEventClassClockView = FourCharCode('cloc'); { * kEventClassClockView / kEventClockDateOrTimeChanged * * Summary: * Allows clients to determine when the user has changed the date or * time in the clock control. * * Discussion: * This event is sent by the clock control when the user has changed * the date or time. Clients could register for this notification in * order to update some state based on the date or time in the * clock, for instance. This event is sent to the view only, it will * not propagate. It is sent to all handlers installed on the * control. * * Mac OS X threading: * Not thread safe * * Parameters: * * --> kEventParamDirectObject (in, typeControlRef) * The view whose date has changed. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available } const kEventClockDateOrTimeChanged = 1; end.
unit CompressZlib; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Declarations for zlib functions & structures $jrsoftware: issrc/Projects/CompressZlib.pas,v 1.5 2010/09/07 03:09:36 jr Exp $ } interface uses Windows, SysUtils, Compress; function ZlibInitCompressFunctions(Module: HMODULE): Boolean; function ZlibInitDecompressFunctions(Module: HMODULE): Boolean; type TZAlloc = function(AppData: Pointer; Items, Size: Cardinal): Pointer; stdcall; TZFree = procedure(AppData, Block: Pointer); stdcall; TZStreamRec = packed record next_in: Pointer; { next input byte } avail_in: Cardinal; { number of bytes available at next_in } total_in: Cardinal; { total nb of input bytes read so far } next_out: Pointer; { next output byte should be put here } avail_out: Cardinal; { remaining free space at next_out } total_out: Cardinal; { total nb of bytes output so far } msg: PAnsiChar; { last error message, NULL if no error } internal: Pointer; { not visible by applications } zalloc: TZAlloc; { used to allocate the internal state } zfree: TZFree; { used to free the internal state } AppData: Pointer; { private data object passed to zalloc and zfree } data_type: Integer; { best guess about the data type: ascii or binary } adler: Longint; { adler32 value of the uncompressed data } reserved: Longint; { reserved for future use } end; TZCompressor = class(TCustomCompressor) private FCompressionLevel: Integer; FInitialized: Boolean; FStrm: TZStreamRec; FBuffer: array[0..65535] of Byte; procedure EndCompress; procedure FlushBuffer; procedure InitCompress; protected procedure DoCompress(const Buffer; Count: Longint); override; procedure DoFinish; override; public constructor Create(AWriteProc: TCompressorWriteProc; AProgressProc: TCompressorProgressProc; CompressionLevel: Integer; ACompressorProps: TCompressorProps); override; destructor Destroy; override; end; TZDecompressor = class(TCustomDecompressor) private FInitialized: Boolean; FStrm: TZStreamRec; FReachedEnd: Boolean; FBuffer: array[0..65535] of Byte; public constructor Create(AReadProc: TDecompressorReadProc); override; destructor Destroy; override; procedure DecompressInto(var Buffer; Count: Longint); override; procedure Reset; override; end; implementation const SZlibDataError = 'zlib: Compressed data is corrupted'; SZlibInternalError = 'zlib: Internal error. Code %d'; ZLIB_VERSION = '1.2.1'; { Do not change this! } Z_NO_FLUSH = 0; Z_PARTIAL_FLUSH = 1; Z_SYNC_FLUSH = 2; Z_FULL_FLUSH = 3; Z_FINISH = 4; Z_OK = 0; Z_STREAM_END = 1; Z_NEED_DICT = 2; Z_ERRNO = -1; Z_STREAM_ERROR = -2; Z_DATA_ERROR = -3; Z_MEM_ERROR = -4; Z_BUF_ERROR = -5; Z_VERSION_ERROR = -6; var deflateInit_: function(var strm: TZStreamRec; level: Integer; version: PAnsiChar; stream_size: Integer): Integer; stdcall; deflate: function(var strm: TZStreamRec; flush: Integer): Integer; stdcall; deflateEnd: function(var strm: TZStreamRec): Integer; stdcall; inflateInit_: function(var strm: TZStreamRec; version: PAnsiChar; stream_size: Integer): Integer; stdcall; inflate: function(var strm: TZStreamRec; flush: Integer): Integer; stdcall; inflateEnd: function(var strm: TZStreamRec): Integer; stdcall; inflateReset: function(var strm: TZStreamRec): Integer; stdcall; function ZlibInitCompressFunctions(Module: HMODULE): Boolean; begin deflateInit_ := GetProcAddress(Module, 'deflateInit_'); deflate := GetProcAddress(Module, 'deflate'); deflateEnd := GetProcAddress(Module, 'deflateEnd'); Result := Assigned(deflateInit_) and Assigned(deflate) and Assigned(deflateEnd); if not Result then begin deflateInit_ := nil; deflate := nil; deflateEnd := nil; end; end; function ZlibInitDecompressFunctions(Module: HMODULE): Boolean; begin inflateInit_ := GetProcAddress(Module, 'inflateInit_'); inflate := GetProcAddress(Module, 'inflate'); inflateEnd := GetProcAddress(Module, 'inflateEnd'); inflateReset := GetProcAddress(Module, 'inflateReset'); Result := Assigned(inflateInit_) and Assigned(inflate) and Assigned(inflateEnd) and Assigned(inflateReset); if not Result then begin inflateInit_ := nil; inflate := nil; inflateEnd := nil; inflateReset := nil; end; end; function zlibAllocMem(AppData: Pointer; Items, Size: Cardinal): Pointer; stdcall; begin try GetMem(Result, Items * Size); except { trap any exception, because zlib expects a NULL result if it's out of memory } Result := nil; end; end; procedure zlibFreeMem(AppData, Block: Pointer); stdcall; begin FreeMem(Block); end; function Check(const Code: Integer; const ValidCodes: array of Integer): Integer; var I: Integer; begin if Code = Z_MEM_ERROR then OutOfMemoryError; Result := Code; for I := Low(ValidCodes) to High(ValidCodes) do if ValidCodes[I] = Code then Exit; raise ECompressInternalError.CreateFmt(SZlibInternalError, [Code]); end; procedure InitStream(var strm: TZStreamRec); begin FillChar(strm, SizeOf(strm), 0); with strm do begin zalloc := zlibAllocMem; zfree := zlibFreeMem; end; end; { TZCompressor } constructor TZCompressor.Create(AWriteProc: TCompressorWriteProc; AProgressProc: TCompressorProgressProc; CompressionLevel: Integer; ACompressorProps: TCompressorProps); begin inherited; FCompressionLevel := CompressionLevel; InitCompress; end; destructor TZCompressor.Destroy; begin EndCompress; inherited; end; procedure TZCompressor.InitCompress; begin { Note: This really ought to use the more efficient deflateReset when starting a new stream, but our DLL doesn't currently export it. } if not FInitialized then begin InitStream(FStrm); FStrm.next_out := @FBuffer; FStrm.avail_out := SizeOf(FBuffer); Check(deflateInit_(FStrm, FCompressionLevel, zlib_version, SizeOf(FStrm)), [Z_OK]); FInitialized := True; end; end; procedure TZCompressor.EndCompress; begin if FInitialized then begin FInitialized := False; deflateEnd(FStrm); end; end; procedure TZCompressor.FlushBuffer; begin if FStrm.avail_out < SizeOf(FBuffer) then begin WriteProc(FBuffer, SizeOf(FBuffer) - FStrm.avail_out); FStrm.next_out := @FBuffer; FStrm.avail_out := SizeOf(FBuffer); end; end; procedure TZCompressor.DoCompress(const Buffer; Count: Longint); begin InitCompress; FStrm.next_in := @Buffer; FStrm.avail_in := Count; while FStrm.avail_in > 0 do begin Check(deflate(FStrm, Z_NO_FLUSH), [Z_OK]); if FStrm.avail_out = 0 then FlushBuffer; end; if Assigned(ProgressProc) then ProgressProc(Count); end; procedure TZCompressor.DoFinish; begin InitCompress; FStrm.next_in := nil; FStrm.avail_in := 0; { Note: This assumes FStrm.avail_out > 0. This shouldn't be a problem since Compress always flushes when FStrm.avail_out reaches 0. } while Check(deflate(FStrm, Z_FINISH), [Z_OK, Z_STREAM_END]) <> Z_STREAM_END do FlushBuffer; FlushBuffer; EndCompress; end; { TZDecompressor } constructor TZDecompressor.Create(AReadProc: TDecompressorReadProc); begin inherited Create(AReadProc); InitStream(FStrm); FStrm.next_in := @FBuffer; FStrm.avail_in := 0; Check(inflateInit_(FStrm, zlib_version, SizeOf(FStrm)), [Z_OK]); FInitialized := True; end; destructor TZDecompressor.Destroy; begin if FInitialized then inflateEnd(FStrm); inherited Destroy; end; procedure TZDecompressor.DecompressInto(var Buffer; Count: Longint); begin FStrm.next_out := @Buffer; FStrm.avail_out := Count; while FStrm.avail_out > 0 do begin if FReachedEnd then { unexpected EOF } raise ECompressDataError.Create(SZlibDataError); if FStrm.avail_in = 0 then begin FStrm.next_in := @FBuffer; FStrm.avail_in := ReadProc(FBuffer, SizeOf(FBuffer)); { Note: If avail_in is zero while zlib still needs input, inflate() will return Z_BUF_ERROR. We interpret that as a data error (see below). } end; case Check(inflate(FStrm, Z_NO_FLUSH), [Z_OK, Z_STREAM_END, Z_DATA_ERROR, Z_BUF_ERROR]) of Z_STREAM_END: FReachedEnd := True; Z_DATA_ERROR, Z_BUF_ERROR: raise ECompressDataError.Create(SZlibDataError); end; end; end; procedure TZDecompressor.Reset; begin FStrm.next_in := @FBuffer; FStrm.avail_in := 0; Check(inflateReset(FStrm), [Z_OK]); FReachedEnd := False; end; end.
program Demo2; {$APPTYPE CONSOLE} var i: Integer; begin for i := 0 to 10 do WriteLn('Hello ', i); end.
unit uFiltroSolicitacao; interface uses uFiltroCliente, System.SysUtils; type TFiltroSolicitacao = class private FIdTipo: string; FIdAnalista: string; FIdModulo: string; FIdProduto: string; FIdCliente: string; FIdUsuarioAbertura: string; FDataFinal: string; FDataInicial: string; FIdOperador: string; FIdDesenvolvedor: string; FIdStatus: string; FNivel: Integer; FCliente: TFiltroCliente; FidVersao: string; FMostrarTempo: Boolean; FId: Integer; FIdCategoria: string; procedure SetidVersao(const Value: string); public constructor Create(); destructor destroy; override; property DataInicial: string read FDataInicial write FDataInicial; property DataFinal: string read FDataFinal write FDataFinal; property IdUsuarioAbertura: string read FIdUsuarioAbertura write FIdUsuarioAbertura; property IdCliente: string read FIdCliente write FIdCliente; property IdModulo: string read FIdModulo write FIdModulo; property IdProduto: string read FIdProduto write FIdProduto; property IdAnalista: string read FIdAnalista write FIdAnalista; property IdTipo: string read FIdTipo write FIdTipo; property IdDesenvolvedor: string read FIdDesenvolvedor write FIdDesenvolvedor; property IdOperador: string read FIdOperador write FIdOperador; property IdStatus: string read FIdStatus write FIdStatus; property Nivel: Integer read FNivel write FNivel; property Cliente: TFiltroCliente read FCliente write FCliente; property idVersao: string read FidVersao write SetidVersao; property Id: Integer read FId write FId; property IdCategoria: string read FIdCategoria write FIdCategoria; end; implementation { TFiltroSolicitacao } constructor TFiltroSolicitacao.Create; begin inherited Create(); FCliente := TFiltroCliente.Create; end; destructor TFiltroSolicitacao.destroy; begin FreeAndNil(FCliente); inherited; end; procedure TFiltroSolicitacao.SetidVersao(const Value: string); begin FidVersao := Value; end; end.
unit NotesDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TNotesOptions = (nopReadOnly, nopReadWrite, nopWriteAll, nopTemplate); TNotesDialog = class(TComponent) private FNoteOption: TNotesOptions; FNotes: string; FNewNote: string; FCaption1: string; FCaption3: string; FCaption2: string; FCaption4: string; FShowCaptions: boolean; FDlgCaption: string; FWantReturns: boolean; FTemplate: boolean; procedure SetNoteOption(const Value: TNotesOptions); procedure SetNotes(const Value: string); procedure SetNewNote(const Value: string); procedure SetCaption1(const Value: string); procedure SetCaption2(const Value: string); procedure SetCaption3(const Value: string); procedure SetCaption4(const Value: string); procedure SetShowCaptions(const Value: boolean); procedure SetDlgCaption(const Value: string); procedure SetWantReturns(const Value: boolean); procedure SetTemplate(const Value: boolean); { Private declarations } protected { Protected declarations } public { Public declarations } function Execute:boolean; procedure Clear; published { Published declarations } property Notes : string read FNotes write SetNotes; property NewNote : string read FNewNote write SetNewNote; property NoteOption:TNotesOptions read FNoteOption write SetNoteOption; property Caption1:string read FCaption1 write SetCaption1; property Caption2:string read FCaption2 write SetCaption2; property Caption3:string read FCaption3 write SetCaption3; property Caption4:string read FCaption4 write SetCaption4; property ShowCaptions:boolean read FShowCaptions write SetShowCaptions; property DlgCaption:string read FDlgCaption write SetDlgCaption; property WantReturns:boolean read FWantReturns write SetWantReturns; property Template:boolean read FTemplate write SetTemplate; end; procedure Register; implementation uses NotesForm; const CRLF = #13#10; procedure Register; begin RegisterComponents('FFS Dialogs', [TNotesDialog]); end; { TNotesDialog } procedure TNotesDialog.Clear; begin FNotes := ''; FNewNote := ''; end; function TNotesDialog.Execute: boolean; var frmNotes: TfrmNotes; begin frmNotes := TfrmNotes.create(self); frmNotes.CaptionPanel.Visible := ShowCaptions; frmNotes.Label1.Caption := Caption1; frmNotes.Label2.Caption := Caption2; frmNotes.Label3.Caption := Caption3; frmNotes.Label4.Caption := Caption4; frmNotes.caption := DlgCaption; frmNotes.Template := false; frmNotes.memNotes.WantReturns := WantReturns; case NoteOption of nopReadOnly: begin frmNotes.memNotes.Visible := false; frmNotes.memNotes.Clear; frmNotes.memViewNotes.Visible := true; frmNotes.memViewNotes.Text := Notes; end; nopReadWrite: begin frmNotes.memNotes.Visible := true; frmNotes.memNotes.Text := NewNote; frmNotes.memViewNotes.Visible := true; frmNotes.memViewNotes.Text := Notes; end; nopWriteAll: begin frmNotes.memNotes.Visible := true; frmNotes.memNotes.Text := NewNote + CRLF + CRLF + Notes; frmNotes.memViewNotes.Visible := false; frmNotes.memViewNotes.Clear; frmNotes.memNotes.Align := alClient; end; nopTemplate: begin frmNotes.memNotes.Visible := true; frmNotes.memNotes.Text := NewNote + Notes; frmNotes.memViewNotes.Visible := false; frmNotes.memViewNotes.Clear; frmNotes.memNotes.Align := alClient; frmNotes.Template := true; end; end; // show the Dialog if frmNotes.ShowModal = mrOk then begin Notes := frmNotes.MemNotes.Text; if NoteOption = nopReadWrite then Notes := Notes + CRLF + CRLF; // line between new notes and old notes Notes := Notes + frmNotes.MemViewNotes.Text; result := true; end else result := false; frmNotes.Free; end; procedure TNotesDialog.SetCaption1(const Value: string); begin FCaption1 := Value; end; procedure TNotesDialog.SetCaption2(const Value: string); begin FCaption2 := Value; end; procedure TNotesDialog.SetCaption3(const Value: string); begin FCaption3 := Value; end; procedure TNotesDialog.SetCaption4(const Value: string); begin FCaption4 := Value; end; procedure TNotesDialog.SetDlgCaption(const Value: string); begin FDlgCaption := Value; end; procedure TNotesDialog.SetNewNote(const Value: string); begin FNewNote := value; end; procedure TNotesDialog.SetNoteOption(const Value: TNotesOptions); begin FNoteOption := Value; end; procedure TNotesDialog.SetNotes(const Value: string); begin FNotes := value; end; procedure TNotesDialog.SetShowCaptions(const Value: boolean); begin FShowCaptions := Value; end; procedure TNotesDialog.SetTemplate(const Value: boolean); begin FTemplate := Value; end; procedure TNotesDialog.SetWantReturns(const Value: boolean); begin FWantReturns := Value; end; end.
unit mr_StrUtils; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. // // Notes: // // Ported from the UtStr unit. // // Old functions: Use instead: // // - UpCaseStr: UpperCase or AnsiUpperCase ( SysUtils ) // - LoCaseStr: LowerCase or AnsiLowerCase ( SysUtils ) // - CleanSpaces, CleanStr: Trim ( SysUtils ) // - SkipSpaces: TrimLeft ( SysUtils ) // - CleanTrailingSpaces: TrimRight ( SysUtils ) // - TrimSpaces PackSpaces ( new name ) interface uses SysUtils, Windows, Classes; const chBEEP = ^G; chBS = ^H; chTAB = ^I; chLF = ^J; chNP = ^L; chCR = ^M; chSPACE = ' '; const DefaultTabStop = 8; type TCharSet = set of char; function CleanTabs( const Str : string; TabStop : integer ) : string; // Converts TABs to Spaces function StripHiBit( const Str : string ) : string; // Converts 8bit ASCII to 7 bits function KillSpaces( const Str : string ) : string; // Delete all spaces function PackSpaces( const Str : string ) : string; // Replaces contiguous spaces by one space function LeftAlign( const Str : string; Width : integer ) : string; // Align left to a field of specified width function RightAlign( const Str : string; Width : integer ) : string; // Align right to a field of specified width function CenterAlign( const Str : string; Width : integer ) : string; // Center in a field of specified width function AdjustStr( const Str : string; Width : integer ) : string; // Trims control characters leading spaces and aligns to left function CapitalizeStr( const Str : string ) : string; // Guess what: First letter in upper case and the rest in lower case function ReplaceChar( const Str : string; Old, New : char ) : string; // Replaces all "Old" characters by "New" function ReplaceStr( const Str : string; const Old, New : string ) : string; // Replaces all "Old" substrings by "New" function Spaces( Count : integer ) : string; // Returns "Count" spaces function DupChar( Ch : char; Count : integer ) : string; // ( "a", 3 ) => "aaa" function DupStr( const Str : string; Count : integer ) : string; // ( "abc", 3 ) => "abcabcabc" function StrEqual( Str1, Str2 : pchar; Len : integer ) : boolean; // Check for equality between "Str1" & "Str2", ignores #0 function CharPos( Str : pchar; Ch : char; Len : integer ) : integer; function RightStr( const Str : string; Count : integer ) : string; // Get last "Count" characters function LeftStr( const Str : string; Count : integer ) : string; // Get first "Count" characters function FirstNot( const Str : string; Ch : char; At : integer ) : integer; // First character that is not "Ch", starting at "At" function Pos( const SubStr, Str : string; At : integer ) : integer; // Same as System cousin function BackPos( const SubStr, Str : string; At : integer ) : integer; // Backwards version function EndsWith( const SubStr, Str : string ) : boolean; function StartsWith( const SubStr, Str : string ) : boolean; function BeforeStr( const SubStr, Str : string ) : string; // Portion of "Str" before "SubStr" function AfterStr ( const SubStr, Str : string ) : string; // Portion of "Str" after "SubStr" function JoinStrings( Strings : array of string ) : pchar; // Return a NUL terminated list of ASCIIZ strings from an array of strings function JoinStringList( List : TStrings ) : pchar; // Same, but from a string list function SplitStringList( StringList : pchar ) : TStrings; // Obtain a list of strings from a NUL terminated list function SplitStrings( const Strings, Separator : string ) : TStrings; function AnsiToAscii( const Str : string ) : string; function AsciiToAnsi( const Str : string ) : string; // --- Number to string --- const HexDigits : array[0..15] of char = '0123456789ABCDEF'; function NumToStr( Num : integer; Base, Width : integer ) : string; // NumToStr( 8, 9, 2 ) = '10' function Hex( Num, Width : integer ) : string; // Hex( 31, 4 ) = '001F' function IndxOf( const IndxStr, Prefix : string ) : integer; // IndxOf( 'Foobar01', 'Foobar' ) = 1 // Internal structure of AnsiString type StrInternalStruct = record AllocSize : longint; RefCount : longint; Length : longint; end; const StrSkew = sizeof( StrInternalStruct ); StrOverhead = sizeof( StrInternalStruct ) + 1; function GetNextString(const str : string; var pos : integer; sep : TCharSet) : string; function GetNextWord(const str : string; var pos : integer; sep : TCharSet) : string; implementation function IndxOf( const IndxStr, Prefix : string ) : integer; // IndxOf( 'Foobar01', 'Foobar' ) = 1 begin if Prefix = copy( IndxStr, 1, length( Prefix ) ) then try Result := StrToInt( copy( IndxStr, length( Prefix ) + 1, MaxInt ) ); except Result := -1; end else Result := -1; end; // --- Number to string --- function Hex( Num, Width : integer ) : string; begin Result := NumToStr( Num, 16, Width ); end; function NumToStr( Num : integer; Base, Width : integer ) : string; begin SetLength( Result, Width ); repeat dec( Width ); pchar(Result)[Width] := HexDigits[Num mod Base]; Num := Num div Base; until Width <= 0; end; function SplitStrings( const Strings, Separator : string ) : TStrings; var ChPos : integer; OldPos : integer; Len : integer; begin OldPos := 0; Len := length( Strings ); Result := TStringList.Create; repeat ChPos := Pos( Separator, Strings, OldPos + Len ); if ChPos <> 0 then Result.Add( copy( Strings, OldPos + Len, ChPos - OldPos - 1 ) ) else Result.Add( copy( Strings, OldPos + Len, MaxInt ) ); OldPos := ChPos; until ChPos = 0; end; function SplitStringList( StringList : pchar ) : TStrings; var s : string; begin Result := TStringList.Create; while StrLen( StringList ) <> 0 do begin s := StringList; Result.Add( s ); Inc( StringList, length( s ) + 1 ); end; end; function JoinStrings( Strings : array of string ) : pchar; var i : integer; ListSize : integer; StrPtr : pchar; CurrStr : string; begin ListSize := 1; for i := low( Strings ) to high( Strings ) do Inc( ListSize, length( Strings[i] ) + 1 ); GetMem( Result, ListSize ); StrPtr := Result; for i := low( Strings ) to high( Strings ) do begin CurrStr := Strings[i]; System.Move( pchar(CurrStr)[0], StrPtr[0], length( CurrStr ) + 1 ); Inc( StrPtr, length( CurrStr ) + 1 ); end; StrPtr[0] := #0; end; function JoinStringList( List : TStrings ) : pchar; var i : integer; LastIndx : integer; ListSize : integer; StrPtr : pchar; CurrStr : string; begin ListSize := 1; with List do begin LastIndx := List.Count - 1; for i := 0 to LastIndx do Inc( ListSize, length( Strings[i] ) + 1 ); GetMem( Result, ListSize ); StrPtr := Result; for i := 0 to LastIndx do begin CurrStr := Strings[i]; System.Move( pchar(CurrStr)[0], StrPtr[0], length( CurrStr ) + 1 ); Inc( StrPtr, length( CurrStr ) + 1 ); end; StrPtr[0] := #0; end; end; function AnsiToAscii( const Str : string ) : string; begin SetLength( Result, length( Str ) ); CharToOemA( pchar( Str ), pchar( Result ) ); end; function AsciiToAnsi( const Str : string ) : string; begin SetLength( Result, length( Str ) ); OemToCharA( pchar( Str ), pchar( Result ) ); end; function CapitalizeStr( const Str : string ) : string; begin Result := LowerCase( Str ); Result[1] := UpCase( Result[1] ); end; function ReplaceChar( const Str : string; Old, New : char ) : string; var i : integer; begin SetString( Result, pchar(Str), length( Str ) ); for i := 0 to length( Str ) - 1 do if pchar( Result )[i] = Old then pchar( Result )[i] := New; end; function ReplaceStr( const Str : string; const Old, New : string ) : string; var Indx : integer; LastIndx : integer; ResLen : integer; Delta : integer; begin // Reserve space for max new length if New = '' then SetLength( Result, length( Str ) ) else if length( New ) > length( Old ) // Reserve space for max new length then SetLength( Result, length(Str) * length( New ) div length( Old ) ) else SetLength( Result, length(Str) * length( Old ) div length( New ) ); ResLen := 0; Indx := 1; repeat LastIndx := Indx; Indx := Pos( Old, Str, LastIndx ); if Indx <> 0 then begin Delta := Indx - LastIndx; Move( pchar(Str)[LastIndx - 1], pchar(Result)[ResLen], Delta ); // Copy original piece Move( pchar(New)[0], pchar(Result)[ResLen + Delta], length( New ) ); // Copy New Inc( ResLen, Delta + length( New ) ); Inc( Indx, length( Old ) ); end; until Indx = 0; Move( pchar(Str)[LastIndx - 1], pchar(Result)[ResLen], length(Str) - LastIndx + 1 ); // Copy last piece SetLength( Result, ResLen + length(Str) - LastIndx + 1 ); end; function KillSpaces( const Str : string ) : string; var i, j : integer; s : string; Len : integer; begin Len := Length( Str ); SetLength( s, Len ); j := 0; for i := 0 to Len - 1 do if pchar( Str )[i] > ' ' then begin pchar( s )[j] := pchar( Str )[i]; Inc( j ); end; SetString( Result, pchar( s ), j ); end; function PackSpaces( const Str : string ) : string; var i, j : integer; Len : integer; begin Len := Length( Str ); SetLength( Result, Len ); j := 0; pchar( Result )[0] := pchar( Str )[0]; for i := 1 to Len - 1 do if ( pchar( Str )[ i - 1 ] > ' ' ) or ( pchar( Str )[i] > ' ' ) then begin Inc( j ); pchar( Result )[j] := pchar( Str )[i]; end; SetLength( Result, j + 1 ); end; function DupStr( const Str : string; Count : integer ) : string; var i : integer; Len : integer; begin Len := Length( Str ); SetLength( Result, Count * length( Str ) ); for i := 0 to Count - 1 do Move( pchar( Str )[0], pchar( Result )[i * Len], Len ); end; function DupChar( Ch : char; Count : integer ) : string; begin SetLength( Result, Count ); FillChar( pchar( Result )[0], Count, Ch ); end; function Spaces( Count : integer ) : string; begin SetLength( Result, Count ); FillChar( pchar( Result )[0], Count, ' ' ); end; function CleanTabs( const Str : string; TabStop : integer ) : string; // Converts TABs to Spaces var ResStr : pchar; CurrLine : pchar; i : integer; SpcCount : integer; begin if TabStop = 0 then TabStop := DefaultTabStop; SetLength( Result, length( Str ) * 8 ); // Worst case! CurrLine := pchar(Result); // For multi-line strings, see later ResStr := CurrLine; for i := 1 to length( Str ) do case Str[i] of chTAB : begin SpcCount := ( ResStr - CurrLine ) mod TabStop; FillChar( ResStr, SpcCount, ' ' ); Inc( ResStr, SpcCount ); end; chCR : begin CurrLine := pchar( Result ) + i; // This function can format a multi-line string: here // we update CurrLine if we found a new line ResStr := pchar(Str) + i - 1; Inc( ResStr ); end; else begin ResStr := pchar(Str) + i - 1; Inc( ResStr ); end; end; SetLength( Result, ResStr - pchar(Result) ); end; function AdjustStr( const Str : string; Width : integer ) : string; begin AdjustStr := LeftAlign( TrimLeft( CleanTabs( Str, 0 ) ), Width ); end; function FirstNot( const Str : string; Ch : char; At : integer ) : integer; var Len : integer; begin Len := Length( Str ); Result := At; while ( Str[Result] = Ch ) and ( Result <= Len ) do Inc( Result ); if Result > Len then Result := 0; end; function Pos( const SubStr, Str : string; At : integer ) : integer; asm test eax, eax je @@noWork test edx, edx je @@stringEmpty push ebx push esi push edi mov esi, eax // Point ESI to substr mov edi, edx // Point EDI to s dec ecx jns @@offsetOK xor ecx, ecx @@offsetOK: mov eax, [edi - StrSkew].StrInternalStruct.Length // ECX = Length( s ) push edi // remember s position to calculate index add edi, ecx sub eax, ecx js @@fail mov ecx, eax mov edx, [esi - StrSkew].StrInternalStruct.Length // EDX = Length( substr ) dec edx // EDX = Length( substr ) - 1 js @@fail // < 0 ? return 0 mov al, [esi] // AL = first char of substr inc esi // Point ESI to 2'nd char of substr sub ecx, edx // #positions in s to look at // = Length( s ) - Length( substr ) + 1 jle @@fail @@loop: repne scasb jne @@fail mov ebx, ecx // save outer loop counter push esi // save outer loop substr pointer push edi // save outer loop s pointer mov ecx, edx repe cmpsb pop edi // restore outer loop s pointer pop esi // restore outer loop substr pointer je @@found mov ecx, ebx // restore outer loop counter jmp @@loop @@fail: pop edx // get rid of saved s pointer xor eax, eax jmp @@exit @@stringEmpty: xor eax, eax jmp @@noWork @@found: pop edx // restore pointer to first char of s mov eax, edi // EDI points of char after match sub eax, edx // the difference is the correct index @@exit: pop edi pop esi pop ebx @@noWork: end; function BackPos( const SubStr, Str : string; At : integer ) : integer; var // This was coded by Meddy MaxPos : integer; Len : integer; i, j : integer; Aux : pchar; begin Len := length( SubStr ); assert( ( Len > 0 ) and ( length( Str ) > 0 ), 'Empty string passed in StrUtils.BackPos' ); if Len = 1 then // [JRG opt] begin if At > 0 then Result := At else Result := Length( Str ); while ( Str[Result] <> SubStr[1] ) and ( Result > 0 ) do dec( Result ); end else // [Med's stuff] begin if At = 0 then MaxPos := length( Str ) - Len else MaxPos := At - Len; i := 0; j := -1; Result := -1; repeat Aux := StrPos( pchar( Str ) + i, pchar( SubStr ) ); // Should be opt'zd [JRG note] if ( Aux <> nil ) and ( Aux - pchar( Str ) <= MaxPos ) then begin j := Aux - pchar( Str ); i := j + Len; end else Result := j + 1; until Result >= 0; end end; function StripHiBit( const Str : string ) : string; var i : integer; begin Result := Str; for i := 0 to length( Result ) - 1 do byte( pchar( Result )[i] ) := byte( pchar( Result )[i] ) and 127; end; function RightAlign( const Str : string; Width : integer ) : string; begin if length( Str ) < Width then Result := Spaces( Width - length( Str ) ) + Str else SetString( Result, pchar( Str ), Width ); end; function LeftAlign( const Str : string; Width : integer ) : string; begin if length( Str ) < Width then Result := Str + Spaces( Width - length( Str ) ) else SetString( Result, pchar( Str ), Width ); end; function CenterAlign( const Str : string; Width : integer ) : string; var n : integer; s : string; begin n := ( Width - length( Str ) ) div 2; if n > 0 then begin s := Spaces( n ); Result := s + Str + s; end else Result := Str end; function CharPos( Str : pchar; Ch : char; Len : integer ) : integer; // EAX = Str // EDX = Ch // ECX = Len asm push ebx mov ebx, eax // Str mov eax, ecx // Backup Len or ecx, ecx jz @@NotFound or ebx, ebx jz @@NotFound @@Loop: cmp [ebx], dl je @@Exit inc ebx dec ecx jnz @@Loop @@NotFound: lea ecx, [eax + 1] // Not found, make EAX = -1 @@Exit: sub eax, ecx pop ebx end; function StrEqual( Str1, Str2 : pchar; Len : integer ) : boolean; asm push ebx or eax, eax jz @@NoWork or edx, edx jz @@Exit or ecx, ecx jz @@Exit @@Loop: mov bl, [eax] cmp bl, [edx] jne @@Exit inc eax inc edx dec ecx jnz @@Loop @@Exit: setz al pop ebx @@NoWork: end; function StartsWith( const SubStr, Str : string ) : boolean; begin Result := StrEqual( pchar(SubStr), pchar(Str), length( SubStr ) ); end; function EndsWith( const SubStr, Str : string ) : boolean; begin Result := StrEqual( pchar(SubStr), pchar(Str)+(length(Str) - length(SubStr)), length( SubStr ) ); end; function RightStr( const Str : string; Count : integer ) : string; begin if Length( Str ) > Count then Result := copy( Str, length( Str ) - Count + 1, Count ) else Result := Str; end; function LeftStr( const Str : string; Count : integer ) : string; begin SetString( Result, pchar( Str ), Count ); end; function BeforeStr( const SubStr, Str : string ) : string; begin SetString( Result, pchar( Str ), System.Pos( SubStr, Str ) - 1 ); end; function AfterStr( const SubStr, Str : string ) : string; var pos : integer; begin pos := System.Pos( SubStr, Str ); SetString( Result, pchar( Str ) + pos, Length( Str ) - pos ); end; function GetNextString(const str : string; var pos : integer; sep : TCharSet) : string; var OldPos : integer; count : integer; len : integer; begin len := length(str); OldPos := pos; while (pos <= len) and not (str[pos] in sep) do inc(pos); count := pos - OldPos; if count > 0 then begin SetLength(result, count); Move(str[OldPos], result[1], count); end else result := ''; end; function GetNextWord(const str : string; var pos : integer; sep : TCharSet) : string; var p, q, r : pchar; begin r := pchar(str); p := r+pos-1; while (p[0] in sep) and (p[0]<>#0) do inc(p); if p[0]<>#0 then begin q := p; while not(p[0] in sep) and (p[0]<>#0) do inc(p); result := copy(str, q-r+1, p-q); pos := p-r+1; end else result := ''; end; end.
unit GX_FavUtil; {$I GX_CondDefine.inc} interface uses Classes; type TFolderType = (ftNormal, ftSource, ftBitmap, ftGlyph, ftDocs); TExecType = (etLoadInIDE, etShell, etCustom, etProject); TGXFile = class; // forward TGXFolder = class; // forward TGXFavItem = class private FOwner: TGXFolder; function GetContainingList: TList; virtual; abstract; procedure Detach; procedure AttachTo(AOwner: TGXFolder); procedure SetOwner(const Value: TGXFolder); public constructor Create(AOwner: TGXFolder); virtual; destructor Destroy; override; property Owner: TGXFolder read FOwner write SetOwner; end; TGXFolder = class(TGXFavItem) private FFolderName: string; FFolderType: TFolderType; FFileList: TList; FFolderList: TList; function GetFileCount: Integer; function GetFile(Index: Integer): TGXFile; function GetFolder(Index: Integer): TGXFolder; function GetFolderCount: Integer; procedure ClearList(AList: TList); function GetContainingList: TList; override; public constructor Create(AOwner: TGXFolder); override; destructor Destroy; override; property FolderName: string read FFolderName write FFolderName; property FolderType: TFolderType read FFolderType write FFolderType; property FolderCount: Integer read GetFolderCount; property Folders[Index: Integer]: TGXFolder read GetFolder; property FileCount: Integer read GetFileCount; property Files[Index: Integer]: TGXFile read GetFile; procedure Clear; end; TGXFile = class(TGXFavItem) private FDName: string; FFileName: string; FDescription: string; FExecType: TExecType; FExecProg: string; public constructor Create(AOwner: TGXFolder); override; function GetContainingList: TList; override; property Description: string read FDescription write FDescription; property FileName: string read FFileName write FFileName; property DName: string read FDName write FDName; property ExecType: TExecType read FExecType write FExecType; property ExecProg: string read FExecProg write FExecProg; end; const FolderNames: array[TFolderType] of string = ('Normal', 'Source', 'Bitmaps', 'Glyphs', 'Documentation'); ExecTypeNames: array[TExecType] of string = ('Load In IDE', 'Shell Execute', 'Custom', 'Project'); var Root: TGXFolder; implementation uses SysUtils; { TGXFavItem } constructor TGXFavItem.Create(AOwner: TGXFolder); begin inherited Create; AttachTo(AOwner); end; destructor TGXFavItem.Destroy; begin Detach; inherited Destroy; end; procedure TGXFavItem.Detach; begin if Owner <> nil then GetContainingList.Remove(Self); FOwner := nil; end; procedure TGXFavItem.AttachTo(AOwner: TGXFolder); begin FOwner := AOwner; if Owner <> nil then GetContainingList.Add(Self); end; procedure TGXFavItem.SetOwner(const Value: TGXFolder); begin if Value <> Owner then begin Detach; AttachTo(Value); end; end; { TGXFolder } constructor TGXFolder.Create(AOwner: TGXFolder); begin inherited Create(AOwner); FFileList := TList.Create; FFolderList := TList.Create; end; destructor TGXFolder.Destroy; begin Clear; FreeAndNil(FFileList); FreeAndNil(FFolderList); inherited Destroy; end; procedure TGXFolder.Clear; begin ClearList(FFileList); ClearList(FFolderList); end; procedure TGXFolder.ClearList(AList: TList); var i: Integer; CurrItem: TGXFavItem; begin for i := 0 to AList.Count - 1 do begin CurrItem := TGXFavItem(AList[i]); CurrItem.FOwner := nil; // Avoid CurrItem removing itself from list FreeAndNil(CurrItem); end; AList.Clear; end; function TGXFolder.GetContainingList: TList; begin Result := Owner.FFolderList; end; function TGXFolder.GetFolderCount: Integer; begin Result := FFolderList.Count; end; function TGXFolder.GetFolder(Index: Integer): TGXFolder; begin Result := FFolderList[Index]; end; function TGXFolder.GetFileCount: Integer; begin Result := FFileList.Count; end; function TGXFolder.GetFile(Index: Integer): TGXFile; begin Result := FFileList[Index]; end; { TGXFile } constructor TGXFile.Create(AOwner: TGXFolder); begin inherited Create(AOwner); end; function TGXFile.GetContainingList: TList; begin Result := Owner.FFileList; end; initialization Root := TGXFolder.Create(nil); finalization FreeAndNil(Root); end.
unit uNFeComandos; interface uses Classes, SysUtils; procedure EnviaNFe(AServidor, ACnpj: string; ANFe: TStream; var ARecibo, ANroProtocolo, AChaveAcesso: string; AContingencia, AConvTXT2XML: Boolean; var ACodigoErro: integer; var AMensagemErro: string); function EnviarNFe(AServidor, ACnpj: string; ANFe: TStream; AContingencia: Boolean): string; procedure BuscarStatusNF(AServidor, ACnpj: string; AChaveAcesso: string; AContingencia: Boolean; ANFe: TStream; var ARecibo, ANroProtocolo: string; var ACodigoErro: integer; var AMensagemErro: string); procedure CancelaNFe(AServidor, ACnpj, ANroProtocolo, AChaveAcesso, AJustificativa: string; var ANroProtocoloCancelamento: string; ANFe: TStream; AContingencia: Boolean); function VerificaStatusNFe(AServidor, ACnpj: string; AContingencia: Boolean): Boolean; function ConectadoInternet(AServidor, ACnpj: string): Boolean; function CriaChaveNFe(AServidor, ACnpj: string; ADataEmissao: TDateTime; AUf, AModelo, ASerie, ANumero, ATipoEmissao: string; AVersaoAntiga: Boolean = False): string; function NFe_Consultar(AServidor, ACnpj, AChaveNFe: string; AContingencia: Boolean): string; procedure NFe_AdicionaProtNFe(AServidor, ACnpj: string; ANFe: TStream; AContingencia: Boolean); procedure NFe_GerarDANFE(AServidor, ACnpj: string; ANFe, ADANFE: TStream); function EnviarCartaCorrecao(AServidor, ACnpj: string; AChaveNFe, ATextoCorrecao: WideString; ANroCorrecao: Integer; AContingencia: Boolean; AXML: TStream): string; function ConsultarNFeDestinada(AServidor, ACnpj: string; ANFeConsultada, AEmissorNFe: Integer; AUltNSU: string; AXml: TStream; var AIndCont: Integer): String; procedure EnviarManifestacao(AServidor, ACnpj, AChaveAcesso: string; ATipoEvento: Integer; AJustificativa: string; AContingencia: Boolean; AXml: TStream; var AProtocolo, ADataProtocolo: string); procedure ConsultarCadastro(AServidor, ACnpj: string; ATipoArgumento: Integer; AUF, AArgumento: string; AXML: TStream); procedure DownloadNFe(AServidor, ACnpj, AChaveAcesso: string; AXML: TStream); //08/10/2009 procedure SalvarUTF8(AXMLStream: TStream; AArquivo: string); procedure InutilizaNFe(AServidor, ACnpj: string; AUf, AAno, AModelo, ASerie, ANfeInicial, ANfeFinal, AJustificativa: string; var ANroProtocoloInutilizacao: string; ANFe: TStream; AContingencia: Boolean); function ConsultarNFe(AServidor, ACnpj: string; AChaveNFe: WideString; AXML: TStream; AContingencia: Boolean): WideString; procedure EnviarEmail(AServidor, ACnpj, AEmailDestinatario, AEmailBCC, AAssunto, AMensagem: string; AListBoxAnexos: TStrings ); procedure ImportarNFeFornecedor(AServidor, ACnpj: string; ANFe: TStream); type TTipoEmissao = (teContFS = 2, teContFSDA = 5); TICMS = (icComDestaque = 1, icSemDestaque = 2); function GeraCodigoBarras(AServidor, ACNPJ, AUF, ACNPJBarras: string; AValorNF: Extended; ATipoEmissao: TTipoEmissao; AICMSProprio, AICMSSubstituicao: TICMS; ADataEmissao: TDateTime): string; implementation uses IdTCPClient, uNFeConsts, StrUtils, Dialogs, IdAntiFreeze, IdAntiFreezeBase, Forms, StdCtrls, JvTransparentForm, IdIOHandlerSocket, IdTCPConnection; type IAguarde = interface end; TAguarde = class(TInterfacedObject, IAguarde) private FTela: TForm; FLabel: TLabel; FAntiFreeze: TIdAntiFreeze; FTransparent: TJvTransparentForm; FMensagem: string; WindowList: Pointer; public class function Mostrar(AMensagem: String): IAguarde; public constructor Create(AMensagem: string); procedure AfterConstruction; override; procedure BeforeDestruction; override; end; TTCPClient = class(TIdTCPClient) private FAguarde: IAguarde; public procedure AfterConstruction; override; procedure BeforeDestruction; override; end; function CriarTCPClient(AServidor: string): TIdTCPClient; begin Result := TTCPClient.Create(nil); Result.Name := 'TCPClient'; Result.Host := AServidor; Result.Port := 7001; Result.IOHandler := TIdIOHandlerSocket.Create(Result); Result.IOHandler.Name := 'IdIOHandlerStack'; end; procedure EnviaNFe(AServidor, ACnpj: string; ANFe: TStream; var ARecibo, ANroProtocolo, AChaveAcesso: string; AContingencia, AConvTXT2XML: Boolean; var ACodigoErro: integer; var AMensagemErro: string); var TCPClient: TIdTCPClient; Codigo: Integer; Retorno: TStrings; begin ACodigoErro := 0; AMensagemErro := EmptyStr; TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(NFe_Envia)); TCPClient.WriteStream(ANFe, True, True); TCPClient.WriteInteger(Integer(AContingencia)); TCPClient.WriteInteger(Integer(AConvTXT2XML)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Retorno := TStringList.Create; try Retorno.Text := TCPClient.ReadLn; Retorno.Text := AnsiReplaceText(Retorno.Text, #8, sLineBreak); ARecibo := Retorno[0]; ANroProtocolo := Retorno[1]; AChaveAcesso := Retorno[2]; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); finally FreeAndNil(Retorno); end; end else if (Codigo = NFe_ErrorEnvioNfe) then begin Retorno := TStringList.Create; try Retorno.Text := TCPClient.ReadLn; Retorno.Text := AnsiReplaceText(Retorno.Text, #8, sLineBreak); ARecibo := Retorno[0]; ANroProtocolo := Retorno[1]; AChaveAcesso := Retorno[2]; finally FreeAndNil(Retorno); end; AMensagemErro := TCPClient.ReadLn; ACodigoErro := TCPClient.ReadInteger; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; function EnviarNFe(AServidor, ACnpj: string; ANFe: TStream; AContingencia: Boolean): string; var TCPClient: TIdTCPClient; Codigo: Integer; begin Result := EmptyStr; TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(NFe_EnviarNF)); TCPClient.WriteStream(ANFe, True, True); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; MessageDlg('Parte Código = ' + IntToStr(Codigo), mtError, [mbno], 0); if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure BuscarStatusNF(AServidor, ACnpj: string; AChaveAcesso: string; AContingencia: Boolean; ANFe: TStream; var ARecibo, ANroProtocolo: string; var ACodigoErro: integer; var AMensagemErro: string); var TCPClient: TIdTCPClient; Codigo: Integer; Retorno: TStrings; begin ACodigoErro := 0; AMensagemErro := EmptyStr; TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(NFe_BuscarStatusNF)); TCPClient.WriteInteger(Integer(AContingencia)); TCPClient.WriteLn(AChaveAcesso); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Retorno := TStringList.Create; try Retorno.Text := TCPClient.ReadLn; Retorno.Text := AnsiReplaceText(Retorno.Text, #8, sLineBreak); ARecibo := Retorno[0]; ANroProtocolo := Retorno[1]; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); finally FreeAndNil(Retorno); end; end else if (Codigo = NFe_ErrorEnvioNfe) then begin Retorno := TStringList.Create; try Retorno.Text := TCPClient.ReadLn; Retorno.Text := AnsiReplaceText(Retorno.Text, #8, sLineBreak); ARecibo := Retorno[0]; ANroProtocolo := Retorno[1]; finally FreeAndNil(Retorno); end; AMensagemErro := TCPClient.ReadLn; ACodigoErro := TCPClient.ReadInteger; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure CancelaNFe(AServidor, ACnpj, ANroProtocolo, AChaveAcesso, AJustificativa: string; var ANroProtocoloCancelamento: string; ANFe: TStream; AContingencia: Boolean); var TCPClient: TIdTCPClient; Codigo: Integer; Dados: TStrings; DadosStream: TMemoryStream; begin TCPClient := CriarTCPClient(AServidor); try Dados := TStringList.Create; DadosStream := TMemoryStream.Create; try Dados.Add(ANroProtocolo); Dados.Add(AChaveAcesso); Dados.Add(AJustificativa); Dados.SaveToStream(DadosStream); DadosStream.Position := 0; try TCPClient.Connect(1000); TCPClient.WriteLn(ACNPJ); TCPClient.WriteInteger(Integer(NFe_Cancela)); TCPClient.WriteStream(DadosStream, True, True); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin ANroProtocoloCancelamento := TCPClient.ReadLn; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(DadosStream); FreeAndNil(Dados); end; finally FreeAndNil(TCPClient); end; end; function VerificaStatusNFe(AServidor, ACnpj: string; AContingencia:Boolean): Boolean; var TCPClient: TIdTCPClient; Codigo: Integer; begin Result := False; TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACNPJ); if AContingencia then TCPClient.WriteInteger(Integer(NFe_VerificaContingencia)) else TCPClient.WriteInteger(Integer(NFe_Verifica)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then Result := StrToBool(TCPClient.ReadLn) else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; function ConectadoInternet(AServidor, ACnpj: string): Boolean; var TCPClient: TIdTCPClient; Codigo: Integer; begin Result := False; TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACNPJ); TCPClient.WriteInteger(Integer(NFe_Conectado)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then Result := StrToBool(TCPClient.ReadLn) else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; function GeraCodigoBarras(AServidor, ACNPJ, AUF, ACNPJBarras: string; AValorNF: Extended; ATipoEmissao: TTipoEmissao; AICMSProprio, AICMSSubstituicao: TICMS; ADataEmissao: TDateTime): string; var TCPClient: TIdTCPClient; Codigo: Integer; Dados: TStrings; DadosStream: TMemoryStream; begin ACNPJ := AnsiReplaceText(AnsiReplaceText(AnsiReplaceStr(ACNPJ, '-',''), '.', ''), '/', ''); TCPClient := CriarTCPClient(AServidor); try Dados := TStringList.Create; DadosStream := TMemoryStream.Create; try Dados.Add(AUF); Dados.Add(IntToStr(Ord(ATipoEmissao))); Dados.Add(ACNPJBarras); Dados.Add(FormatFloat('0.00', AValorNF)); Dados.Add(IntToStr(Ord(AICMSProprio))); Dados.Add(IntToStr(Ord(AICMSSubstituicao))); Dados.Add(FormatDateTime('dd/mm/yyyy', ADataEmissao)); Dados.SaveToStream(DadosStream); DadosStream.Position := 0; try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(NFe_CodigoBarrasContingencia)); TCPClient.WriteStream(DadosStream, True, True); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(DadosStream); FreeAndNil(Dados); end; finally FreeAndNil(TCPClient); end; end; function CriaChaveNFe(AServidor, ACnpj: string; ADataEmissao: TDateTime; AUf, AModelo, ASerie, ANumero, ATipoEmissao: string; AVersaoAntiga: Boolean): string; var TCPClient: TIdTCPClient; Codigo: Integer; Dados: TStrings; DadosStream: TMemoryStream; begin TCPClient := CriarTCPClient(AServidor); try Dados := TStringList.Create; DadosStream := TMemoryStream.Create; try Dados.Add(AUF); Dados.Add(FormatDateTime('YY', ADataEmissao)); Dados.Add(FormatDateTime('MM', ADataEmissao)); Dados.Add(AModelo); Dados.Add(ASerie); Dados.Add(ANumero); Dados.Add(ATipoEmissao); // 1- Normal, 2-Contingência FS, 3-Contingência SCAN, 4-DPEC e 5-Contigência FS-DA Dados.SaveToStream(DadosStream); DadosStream.Position := 0; try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(NFe_ChaveAcesso)); TCPClient.WriteStream(DadosStream, True, True); TCPClient.WriteInteger(Integer(AVersaoAntiga)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(DadosStream); FreeAndNil(Dados); end; finally FreeAndNil(TCPClient); end; end; function NFe_Consultar(AServidor, ACnpj, AChaveNFe: string; AContingencia: Boolean): string; var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_Consultar)); TCPClient.WriteLn(AChaveNFe); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure NFe_AdicionaProtNFe(AServidor, ACnpj: string; ANFe: TStream; AContingencia: Boolean); var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_AdicionaProtNFe)); TCPClient.WriteStream(ANFe, True, True); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin TCPClient.ReadLn; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure InutilizaNFe(AServidor, ACnpj: string; AUf, AAno, AModelo, ASerie, ANfeInicial, ANfeFinal, AJustificativa: string; var ANroProtocoloInutilizacao: string; ANFe: TStream; AContingencia: Boolean); var TCPClient: TIdTCPClient; Codigo: Integer; Dados: TStrings; DadosStream: TMemoryStream; begin TCPClient := CriarTCPClient(AServidor); try Dados := TStringList.Create; DadosStream := TMemoryStream.Create; try Dados.Add(AUf); Dados.Add(AAno); Dados.Add(AModelo); Dados.Add(ASerie); Dados.Add(ANfeInicial); Dados.Add(ANFeFinal); Dados.Add(AJustificativa); Dados.SaveToStream(DadosStream); DadosStream.Position := 0; try TCPClient.Connect(1000); TCPClient.WriteLn(ACNPJ); TCPClient.WriteInteger(Integer(NFe_Inutilizar)); TCPClient.WriteStream(DadosStream, True, True); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin ANroProtocoloInutilizacao := TCPClient.ReadLn; TMemoryStream(ANFe).Clear; TCPClient.ReadStream(ANFe); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(DadosStream); FreeAndNil(Dados); end; finally FreeAndNil(TCPClient); end; end; function ConsultarNFe(AServidor, ACnpj: string; AChaveNFe: WideString; AXML: TStream; AContingencia: Boolean): WideString; var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_ConsultarNFe)); TCPClient.WriteLn(AChaveNFe); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; TMemoryStream(AXML).Clear; TCPClient.ReadStream(AXML); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure NFe_GerarDANFE(AServidor, ACnpj: string; ANFe, ADANFE: TStream); var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_GerarDANFE)); TCPClient.WriteStream(ANFe, True, True); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin TCPClient.ReadLn; TMemoryStream(ADANFE).Clear; TCPClient.ReadStream(ADANFE); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; function EnviarCartaCorrecao(AServidor, ACnpj: string; AChaveNFe, ATextoCorrecao: WideString; ANroCorrecao: Integer; AContingencia: Boolean; AXML: TStream): string; var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_EnviarCartaCorrecao)); TCPClient.WriteLn(AChaveNFe); TCPClient.WriteLn(ATextoCorrecao); TCPClient.WriteInteger(Integer(ANroCorrecao)); TCPClient.WriteInteger(Integer(AContingencia)); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; TMemoryStream(AXML).Clear; TCPClient.ReadStream(AXML); end else if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure SalvarUTF8(AXMLStream: TStream; AArquivo: string); var F: System.TextFile; Texto: String; StrStream: TStringStream; begin StrStream := TStringStream.Create(''); try AXMLStream.Position := 0; StrStream.CopyFrom(AXMLStream, AXMLStream.Size); Texto := StrStream.DataString; finally FreeAndNil(StrStream); end; try if FileExists(AArquivo) then DeleteFile( AArquivo ); AssignFile(f, AArquivo); Rewrite(f); // Criar Arquivo Write(f, #239+#187+#191); Writeln(F, UTF8Encode( Texto )); finally CloseFile(f); end; end; procedure EnviarEmail(AServidor, ACnpj, AEmailDestinatario, AEmailBCC, AAssunto, AMensagem: string; AListBoxAnexos: TStrings ); var TCPClient: TIdTCPClient; I, Codigo: Integer; Arquivo: TFileStream; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_EnviarEmail)); TCPClient.WriteLn(AEmailDestinatario); TCPClient.WriteLn(AEmailBCC); TCPClient.WriteLn(AAssunto); TCPClient.WriteLn(AMensagem); TCPClient.WriteInteger(Integer(AListBoxAnexos.Count)); if AListBoxAnexos.Count > 0 then begin for I := 0 to AListBoxAnexos.Count - 1 do begin Arquivo := TFileStream.Create( AListBoxAnexos[I], fmOpenRead or fmShareDenyNone ); try Arquivo.Seek(0, soEnd); Arquivo.Seek(0, soBeginning); Arquivo.Position := 0; TCPClient.WriteLn( ExtractFileName(AListBoxAnexos[I]) ); TCPClient.WriteStream(Arquivo, True, True); finally FreeAndNil(Arquivo); end; end; end; Codigo := TCPClient.ReadInteger; if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn) else TCPClient.ReadLn; finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure ImportarNFeFornecedor(AServidor, ACnpj: string; ANFe: TStream); var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_ImportarNFeFornecedor)); TCPClient.WriteStream(ANFe, True, True); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_Error) then raise Exception.Create(TCPClient.ReadLn) else TCPClient.ReadLn finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; function ConsultarNFeDestinada(AServidor, ACnpj: string; ANFeConsultada, AEmissorNFe: Integer; AUltNSU: string; AXml: TStream; var AIndCont: Integer): String; var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_ConsultarNFeDestinadas)); TCPClient.WriteInteger(ANFeConsultada); TCPClient.WriteInteger(AEmissorNFe); TCPClient.WriteLn(AUltNSU); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin Result := TCPClient.ReadLn; AIndCont := TCPClient.ReadInteger; TMemoryStream(AXml).Clear; TCPClient.ReadStream(AXml); end else raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure EnviarManifestacao(AServidor, ACnpj, AChaveAcesso: string; ATipoEvento: Integer; AJustificativa: string; AContingencia: Boolean; AXml: TStream; var AProtocolo, ADataProtocolo: string); var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_EnviarManifestacao)); TCPClient.WriteInteger(Integer(AContingencia)); TCPClient.WriteLn(AChaveAcesso); TCPClient.WriteInteger(ATipoEvento); TCPClient.WriteLn(AJustificativa); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin AProtocolo := TCPClient.ReadLn; ADataProtocolo := Copy(AProtocolo, Pos(#8, AProtocolo) + 1, Length(AProtocolo)); AProtocolo := Copy(AProtocolo, 1, Pos(#8, AProtocolo) - 1); TMemoryStream(AXml).Clear; TCPClient.ReadStream(AXml); end else raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure ConsultarCadastro(AServidor, ACnpj: string; ATipoArgumento: Integer; AUF, AArgumento: string; AXML: TStream); var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_ConsultarContribuintes)); TCPClient.WriteInteger(Integer(ATipoArgumento)); TCPClient.WriteLn(AArgumento); TCPClient.WriteLn(AUF); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin TMemoryStream(AXml).Clear; TCPClient.ReadStream(AXml); end else raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; procedure DownloadNFe(AServidor, ACnpj, AChaveAcesso: string; AXML: TStream); var TCPClient: TIdTCPClient; Codigo: Integer; begin TCPClient := CriarTCPClient(AServidor); try try TCPClient.Connect(1000); TCPClient.WriteLn(ACnpj); TCPClient.WriteInteger(Integer(uNFeConsts.NFe_DownloadNFe)); TCPClient.WriteLn(AChaveAcesso); Codigo := TCPClient.ReadInteger; if (Codigo = NFe_OK) then begin TMemoryStream(AXml).Clear; TCPClient.ReadStream(AXml); end else raise Exception.Create(TCPClient.ReadLn); finally TCPClient.Disconnect; end; finally FreeAndNil(TCPClient); end; end; { TAguarde } procedure TAguarde.AfterConstruction; begin inherited AfterConstruction; FAntiFreeze := TIdAntiFreeze.Create(nil); FTela := TForm.Create(nil); FTela.Name := 'frmTelaAguarde'; FTela.Position := poMainFormCenter; FTela.Caption := 'Aguarde!'; FTela.BorderStyle := bsNone; FTela.FormStyle := fsStayOnTop; FLabel := TLabel.Create(nil); FLabel.Name := 'lblMensagem'; FLabel.AutoSize := False; FLabel.Parent := FTela; FLabel.Left := 0; FLabel.Top := 0; FLabel.Caption := FMensagem; FLabel.AutoSize := True; FTransparent := TJvTransparentForm.Create(FTela); FTransparent.Name := 'JvTransparentForm'; FTransparent.Enable := False; FTransparent.AutoSize := False; FTela.BorderWidth := 30; FTela.AutoSize := True; FTela.Show; WindowList := DisableTaskWindows(FTela.Handle); // Application.ProcessMessages; end; procedure TAguarde.BeforeDestruction; begin inherited BeforeDestruction; EnableTaskWindows(WindowList); FreeAndNil(FTransparent); FreeAndNil(FLabel); FreeAndNil(FTela); FreeAndNil(FAntiFreeze); end; constructor TAguarde.Create(AMensagem: string); begin inherited Create; FMensagem := AMensagem; end; class function TAguarde.Mostrar(AMensagem: String): IAguarde; begin Result := Self.Create(AMensagem); end; { TTCPClient } procedure TTCPClient.AfterConstruction; begin inherited; FAguarde := TAguarde.Mostrar('Conectando com o servidor.'); end; procedure TTCPClient.BeforeDestruction; begin inherited; FAguarde := nil; end; end.
unit MyStrUtils; interface uses sgTypes; {$ifndef FPC} // Delphi land function ExtractDelimited(index: integer; value: string; delim: TSysCharSet): string; {$endif} function CountDelimiter(value: String; delim: Char): LongInt; function CountDelimiterWithRanges(value: String; delim: Char): LongInt; function ExtractDelimitedWithRanges(index: LongInt; value: String): String; function ProcessRange(value: String): LongIntArray; implementation uses SysUtils, Math, Classes, StrUtils, sgShared; {$ifndef FPC} // Delphi land function ExtractDelimited(index: integer; value: string; delim: TSysCharSet): string; var strs: TStrings; begin // Assumes that delim is [','] and uses simple commatext mode - better check if delim <> [','] then raise Exception.create('Internal SG bug using ExtractDelimited'); // okay - let a stringlist do the work strs := TStringList.Create(); strs.CommaText := value; if (index >= 0) and (index < strs.Count) then result := strs.Strings[index - 1] else result := ''; // cleanup strs.Free(); end; {$else} // proper ExtractDelimited provided by StrUtils {$endif} function ExtractDelimitedWithRanges(index: LongInt; value: String): String; var i, count, start: LongInt; inRange: Boolean; begin SetLength(result, 0); inRange := false; result := ''; count := 1; //1 is the first index... not 0 // Find the start of this delimited range for i := Low(value) to Length(value) do begin if count = index then break; if (not inRange) and (value[i] = ',') then count += 1 else if (inRange) and (value[i] = ']') then inRange := false else if (not inRange) and (value[i] = '[') then inRange := true; end; if count <> index then exit; inRange := false; start := i; for i := start to Length(value) do begin if (not inRange) and (value[i] = ',') then break else if (inRange) and (value[i] = ']') then inRange := false else if (not inRange) and (value[i] = '[') then inRange := true; result += value[i]; end; end; function CountDelimiter(value: String; delim: Char): LongInt; var i: Integer; begin result := 0; for i := Low(value) to Length(value) do begin if value[i] = delim then result := result + 1; end; end; function CountDelimiterWithRanges(value: String; delim: Char): LongInt; var i: Integer; inRange: Boolean; begin inRange := false; result := 0; for i := Low(value) to Length(value) do begin if (not inRange) and (value[i] = delim) then result := result + 1 else if (value[i] = '[') then inRange := true else if (value[i] = ']') then inRange := false; end; end; function ProcessRange(value: String): LongIntArray; var i, j, count, temp, lowPart, highPart, dashCount: LongInt; part: String; procedure _AddToResult(val: LongInt); begin SetLength(result, Length(result) + 1); result[High(result)] := val; end; function MyStrToInt(str: String): LongInt; begin if Length(str) = 0 then result := 0 else result := StrToInt(Trim(str)); end; begin value := Trim(value); SetLength(result, 0); if (value[1] <> '[') or (value[Length(value)] <> ']') then exit; //not a range value := MidStr(value, 2, Length(value) - 2); i := 0; count := CountDelimiter(value, ','); while i <= count do begin part := Trim(ExtractDelimited(i + 1, value, [','])); if TryStrToInt(part, temp) then begin //just "a" so... _AddToResult(temp); end else //Should be range begin dashCount := CountDelimiter(part, '-'); if (dashCount = 1) or ((dashCount = 2) and (part[1] <> '-')) then //a-b or a--b lowPart := MyStrToInt(ExtractDelimited(1, part, ['-'])) else //assume -a... lowPart := -MyStrToInt(ExtractDelimited(2, part, ['-'])); if (dashCount = 1) then //a-b highPart := MyStrToInt(ExtractDelimited(2, part, ['-'])) else if (dashCount = 2) and (part[1] = '-') then //-a-b highPart := MyStrToInt(ExtractDelimited(3, part, ['-'])) else if dashCount = 3 then //assume -a--b highPart := -MyStrToInt(ExtractDelimited(4, part, ['-'])) //read last string else if dashCount = 2 then //assume a--b highPart := -MyStrToInt(ExtractDelimited(3, part, ['-'])) else begin RaiseException('Error in range.'); SetLength(result, 0); exit; end; for j := 0 to abs(highPart - lowPart) do begin //lowPart + j * (-1 or +1) _AddToResult(lowPart + (j * sign(highPart - lowPart))); end; end; i := i + 1; end; end; end.
unit EasyUpdateMailForm; interface uses Windows , Buttons , Classes , Controls , ExtCtrls , Forms , StdCtrls // , LocaleMessages ; type TEasyUpdateMailForm = class(TForm) f_MainPanel: TPanel; f_InformationMemo: TMemo; f_MailFromLabel: TLabel; f_MailFromEdit: TEdit; f_MailToLabel: TLabel; f_MailToEdit: TEdit; f_MailServerLabel: TLabel; f_MailServerEdit: TEdit; f_MailServerUserLabel: TLabel; f_MailServerUserEdit: TEdit; f_MailServerPasswordLabel: TLabel; f_MailServerPasswordEdit: TEdit; f_BottomPanel: TPanel; f_CommonSaveBitBtn: TBitBtn; f_CommonCancelBitBtn: TBitBtn; // procedure FormCreate(a_Sender: TObject); end; var g_EasyUpdateMailForm: TEasyUpdateMailForm; implementation {$R *.dfm} procedure TEasyUpdateMailForm.FormCreate(a_Sender: TObject); begin Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormCaption); // f_InformationMemo.Lines.Text := GetCurrentLocaleMessage(c_EasyUpdateMailFormInformationMemoLinesText); // f_MailFromLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormMailFromLabelCaption); f_MailToLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormMailToLabelCaption); // f_MailServerLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormMailServerLabelCaption); f_MailServerUserLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormMailServerUserLabelCaption); f_MailServerPasswordLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormMailServerPasswordLabelCaption); // f_CommonSaveBitBtn.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormCommonSaveBitBtnCaption); f_CommonCancelBitBtn.Caption := GetCurrentLocaleMessage(c_EasyUpdateMailFormCommonCancelBitBtnCaption); end; end.
unit linear_eq; interface uses classes,variants,VariantWrapper,littleFuncs; type TSLEQStatus = (slOneSolution,slNoSolution,slManySolutions); IEquationNode=interface //отобразить красиво свое значение, чтоб не заморачивать ['{5E7FBCDD-61C6-4860-8AFC-F8B2F47B439E}'] //интерфейс решения лин. уравнений function ShowNodeName: string; function ShowNodeUnit: string; procedure SetValue(value: Variant); function GetValue: Variant; function ShowValue(value: Variant): string; property value: Variant read GetValue write SetValue; end; TVariableForEq=record reference: IEquationNode; coeff: Variant; //могут быть комплексные числа end; TVariableForEqArray=array of TVariableForEq; IKirhgofSLEQ=interface procedure SetRootComponent(comp: TComponent); procedure AddEquation(vars: TVariableForEqArray; equals: Variant); procedure SetTolerance(value: real); function GetVariable(p: IEquationNode): Variant; function GetStatus: TSLEQStatus; procedure Solve; function GetEquationsAsString: string; function GetSolutionAsString: string; end; IAbstractSLEQ=interface procedure SetDimensions(NumOfVars,NumOfEqs: Integer); procedure SetMatrix(i,j: Integer; value: Variant); procedure SetTolerance(value: real); function GetMatrix(i,j: Integer): Variant; function GetInvMatrix(i,j: Integer): Variant; function GetVariable(i: Integer): Variant; procedure SetVariableName(i: Integer; value: string); function GetVariableName(i: Integer): string; function GetStatus: TSLEQStatus; procedure Solve; procedure InvertMatrix; property Matrix[i,j: Integer]: Variant read GetMatrix write SetMatrix; property InvMatrix[i,j: Integer]: Variant read GetInvMatrix; property VariableName[i: Integer]: string read GetVariableName write SetVariableName; end; TManySolutionsDataType = class(TAbstractWrapperData) protected function Multiplier(value: Real): string; public InitValue: Real; Vars: array of Real; tolerance: Real; VarNames: array of string; procedure Assign(Source: TPersistent); override; procedure DoAdd(const value: TAbstractWrapperData); override; procedure DoSubtract(const right: TAbstractWrapperData); override; procedure Mul(value: Real); procedure DoMultiply(const right: TAbstractWrapperData); override; procedure Divide(value: Real); procedure DoDivide(const right: TAbstractWrapperData); override; procedure DoNegate; override; function IsPlainNumber: boolean; // function AreProportional(other: TManySolutionsDataType): boolean; // procedure SetString(value: string); function GetAsString: string; override; end; TManySolutionsVariantType=class(TAbstractWrapperVariantType) public procedure Cast(var Dest: TVarData; const Source: TVarData); override; procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override; end; TSimpleGaussLEQ=class(TInterfacedObject,IAbstractSLEQ) private fmatrix: array of array of Variant; fIndexes: array of Integer; fInvIndexes: array of Integer; fVariables: array of Variant; fVariableNames: array of string; fNumOfVars,fNumOfEqs: Integer; ftolerance: Real; fstatus: TSLEQStatus; finvMatrix: array of array of Variant; protected procedure SwitchRows(row1,row2: Integer); procedure SwitchCols(col1,col2: Integer); procedure FullSwitchRows(row1,row2: Integer); procedure SolveOneSolution; procedure SolveManySolutions; procedure SolveInvOneSolution; procedure SolveInvManySolutions; public destructor Destroy; override; //for debug purposes procedure SetDimensions(NumOfVars,NumOfEqs: Integer); procedure SetMatrix(i,j: Integer; value: Variant); procedure SetTolerance(value: real); function GetMatrix(i,j: Integer): Variant; function GetInvMatrix(i,j: Integer): Variant; function GetVariable(i: Integer): Variant; function GetStatus: TSLEQStatus; procedure SetVariableName(i: Integer; value: string); function GetVariableName(i: Integer): string; procedure Solve; procedure InvertMatrix; // property Matrix[i,j: Integer]: Real read GetMatrix write SetMatrix; end; TSimpleGaussLEQForKirhgof = class(TInterfacedObject,IKirhgofSLEQ) private fSolver: TSimpleGaussLEQ; fList: TInterfaceList; fRootComponent: TComponent; public constructor Create; destructor Destroy; override; procedure SetRootComponent(c: TComponent); procedure AddEquation(vars: TVariableForEqArray; equals: Variant); procedure SetTolerance(value: real); function GetVariable(p: IEquationNode): Variant; function GetStatus: TSLEQStatus; procedure Solve; function GetEquationsAsString: string; function GetSolutionAsString: string; end; function VarManySolutionsDataCreate(data: TManySolutionsDataType): Variant; function VarIsManySolutions(V: Variant): Boolean; function VarManySolutionsIsNumber(V: Variant): Boolean; //function GetLengthSquared(value: Variant): Real; implementation uses varCmplx,streaming_class_lib,sysUtils,new_phys_unit_lib; var ManySolutionsVariantType: TManySolutionsVariantType; // AllThreadsStopped: TEvent; (* Фабрики рабочим! *) function VarManySolutionsDataCreate(data: TManySolutionsDataType): Variant; begin VarClear(Result); TWrapperVarData(Result).VType:=ManySolutionsVariantType.VarType; TWrapperVarData(Result).data:=data; end; function VarIsManySolutions(V: Variant): Boolean; begin Result:=TWrapperVarData(V).VType=ManySolutionsVariantType.VarType; end; function VarManySolutionsIsNumber(V: Variant): Boolean; begin Result:=VarIsNumeric(V) or (VarIsManySolutions(V) and (TWrapperVarData(V).Data as TManySolutionsDataType).IsPlainNumber); end; (* function GetLengthSquared(value: Variant): Real; begin if value=null then Result:=-1 else if VarIsNumeric(value) then result:=Sqr(value) else if VarIsComplex(value) then result:=VarComplexAbsSqr(value) else Result:=value.GetLengthSquared; //если не поддерживается - выругается, делов-то! end; *) (* TSimpleGaussLEQ *) destructor TSimpleGaussLEQ.Destroy; begin inherited Destroy; end; procedure TSimpleGaussLEQ.SetDimensions(NumOfVars,NumOfEqs: Integer); var i,j: Integer; begin SetLength(fmatrix,NumOfVars+1,NumOfEqs); SetLength(findexes,NumOfVars); SetLength(fInvIndexes,NumOfVars); SetLength(fvariables,NumOfVars); SetLength(fVariableNames,NumOfVars); if NumOfVars>fNumOfVars then for i:=0 to fNumOfEqs-1 do begin fmatrix[NumOfVars,i]:=fmatrix[fNumOfVars,i]; for j:=fNumOfVars to NumOfVars-1 do fmatrix[j,i]:=0; end; //очистили место справа от исх. матрицы if NumOfEqs>fNumOfEqs then for i:=0 to NumOfVars do for j:=fNumOfEqs to NumOfEqs-1 do fmatrix[i,j]:=0; fNumOfVars:=NumOfVars; fNumOfEqs:=NumOfEqs; for i:=0 to fNumOfVars-1 do begin findexes[i]:=i; fInvIndexes[i]:=i; end; end; procedure TSimpleGaussLEQ.SetMatrix(i,j: Integer; value: Variant); begin fmatrix[i,j]:=value; end; procedure TSimpleGaussLEQ.SetTolerance(value: Real); begin ftolerance:=value; end; function TSimpleGaussLEQ.GetMatrix(i,j: Integer): Variant; begin Result:=fmatrix[i,j]; end; function TSimpleGaussLEQ.GetInvMatrix(i,j: Integer): Variant; begin //i здесь - номер уравнения по сути //j - номер переменной, до их перепутывания if findexes[j]>=fNumOfEqs then Result:=0.0 else Result:=finvmatrix[i,findexes[j]]; end; function TSimpleGaussLEQ.GetStatus: TSLEQStatus; begin Result:=fstatus; end; function TSimpleGaussLEQ.GetVariable(i: Integer): Variant; begin Result:=fVariables[findexes[i]]; end; procedure TSimpleGaussLEQ.SetVariableName(i: Integer; value: string); begin fVariableNames[i]:=value; end; function TSimpleGaussLEQ.GetVariableName(i: Integer): string; begin Result:=fVariableNames[i]; end; procedure TSimpleGaussLEQ.Solve; var i,j,k: Integer; max_elem: Real; row_num,col_num: Integer; ratio: Variant; begin //обеспечиваем нули в нижнем треугольнике for j:=0 to fNumOfEqs-1 do begin //ищем макс. элем не выше и не левее (j,j) max_elem:=-1; row_num:=-1; //при попытке заменить такие элем. выругается на index out of bounds col_num:=-1; for i:=j to fNumOfVars-1 do for k:=j to fNumOfEqs-1 do if VarGetLengthSquared(fmatrix[i,k])>max_elem then begin max_elem:=VarGetLengthSquared(fmatrix[i,k]); row_num:=k; col_num:=i; end; if max_elem<=ftolerance then begin //сплошь одни нули, не можем новый диаг. элем найти for i:=j to fNumOfEqs-1 do if VarGetLengthSquared(fmatrix[fNumOfVars,i])>ftolerance then begin fstatus:=slNoSolution; //получилось уравнение вида 0=1 - все тлен Exit; end; fNumOfEqs:=j; //несколько нижних уравнений имеют вид 0=0 - выкидываем их break; end; SwitchRows(j,row_num); SwitchCols(j,col_num); //элем (j,j) - лучший из лучших! ratio:=fmatrix[j,j]; //чтобы знак не потерять, вверху же абс. знач if (not IsDimensionless(ratio)) or (VarGetLengthSquared(ratio-1)>ftolerance) then begin ratio:=1/ratio; fmatrix[j,j]:=1; for i:=j+1 to fNumOfVars do fmatrix[i,j]:=fmatrix[i,j]*ratio; end; //вычитаем строку из нижних, чтобы получить нули в столбце j for i:=j+1 to fNumOfEqs-1 do begin if VarGetLengthSquared(fmatrix[j,i])<=ftolerance then continue; //довольно частый случай ratio:=fmatrix[j,i]; fmatrix[j,i]:=0; for k:=j+1 to fNumOfVars do fmatrix[k,i]:=fmatrix[k,i]-ratio*fmatrix[k,j]; end; end; //получаем матрицу, с ед. диаг. элементами от 0-го до (fNumOfEqs-1)-го //с нулевыми элем. в нижнем треугольнике. if fNumOfEqs=fNumOfVars then begin fstatus:=slOneSolution; SolveOneSolution; end else begin fstatus:=slManySolutions; SolveManySolutions; end; end; procedure TSimpleGaussLEQ.InvertMatrix; var i,j,k: Integer; max_elem: Real; row_num,col_num: Integer; ratio: Variant; begin SetLength(finvMatrix,fNumOfEqs,fNumOfEqs); for i:=0 to fNumOfEqs-1 do for j:=0 to fNumOfEqs-1 do if i=j then finvMatrix[i,j]:=1.0 else fInvMatrix[i,j]:=0.0; //преобразуем исходную матрицу в единичную for j:=0 to fNumOfEqs-1 do begin //ищем макс. элем не выше и не левее (j,j) max_elem:=-1; row_num:=-1; //при попытке заменить такие элем. выругается на index out of bounds col_num:=-1; for i:=j to fNumOfVars-1 do for k:=j to fNumOfEqs-1 do if VarGetLengthSquared(fmatrix[i,k])>max_elem then begin max_elem:=VarGetLengthSquared(fmatrix[i,k]); row_num:=k; col_num:=i; end; if max_elem<=ftolerance then begin //сплошь одни нули, не можем новый диаг. элем найти for i:=j to fNumOfEqs-1 do if VarGetLengthSquared(fmatrix[fNumOfVars,i])>ftolerance then begin fstatus:=slNoSolution; //получилось уравнение вида 0=1 - все тлен Exit; end; fNumOfEqs:=j; //несколько нижних уравнений имеют вид 0=0 - выкидываем их break; end; FullSwitchRows(j,row_num); SwitchCols(j,col_num); //элем (j,j) - лучший из лучших! ratio:=fmatrix[j,j]; //чтобы знак не потерять, вверху же абс. знач if VarGetLengthSquared(ratio-1)>ftolerance then begin ratio:=1/ratio; fmatrix[j,j]:=1; for i:=j+1 to fNumOfVars do fmatrix[i,j]:=fmatrix[i,j]*ratio; for i:=0 to fNumOfEqs-1 do finvmatrix[i,j]:=finvmatrix[i,j]*ratio; end; //вычитаем строку из всех прочих, чтобы получить нули в столбце j for i:=0 to fNumOfEqs-1 do if i<>j then begin if VarGetLengthSquared(fmatrix[j,i])<=ftolerance then continue; //довольно частый случай ratio:=fmatrix[j,i]; fmatrix[j,i]:=0; for k:=j+1 to fNumOfVars do fmatrix[k,i]:=fmatrix[k,i]-ratio*fmatrix[k,j]; for k:=0 to fNumOfEqs-1 do finvmatrix[k,i]:=finvmatrix[k,i]-ratio*finvmatrix[k,j]; end; end; //получаем единичную матрицу слева (возможно, нулевые строки и столбцы) if fNumOfEqs=fNumOfVars then begin fstatus:=slOneSolution; SolveInvOneSolution; end else begin fstatus:=slManySolutions; SolveInvManySolutions; end; end; procedure TSimpleGaussLEQ.SwitchRows(row1,row2: Integer); var i: Integer; begin if row1<>row2 then for i:=0 to fNumOfVars do SwapVariants(fmatrix[i,row1],fmatrix[i,row2]); end; procedure TSimpleGaussLEQ.FullSwitchRows(row1,row2: Integer); var i: Integer; begin if row1<>row2 then begin for i:=0 to fNumOfEqs-1 do SwapVariants(finvMatrix[i,row1],finvmatrix[i,row2]); SwitchRows(row1,row2); end; end; procedure TSimpleGaussLEQ.SwitchCols(col1,col2: Integer); var i: Integer; begin if col1<>col2 then begin SwapIntegers(fInvIndexes[col1],fInvIndexes[col2]); SwapIntegers(findexes[fInvIndexes[col1]],findexes[fInvIndexes[col2]]); for i:=0 to fNumOfEqs-1 do SwapVariants(fmatrix[col1,i],fmatrix[col2,i]); end; end; procedure TSimpleGaussLEQ.SolveOneSolution; var i,j: Integer; val: Variant; tmp: Variant; begin for j:=fNumOfEqs-1 downto 0 do begin val:=fmatrix[fNumOfVars,j]; for i:=j+1 to fNumOfVars-1 do begin tmp:=fvariables[i]*fmatrix[i,j]; // if VarGetLengthSquared(tmp)>ftolerance then val:=val-tmp; end; fvariables[j]:=val; end; end; procedure TSimpleGaussLEQ.SolveInvOneSolution; begin SolveOneSolution; end; procedure TSimpleGaussLEQ.SolveInvManySolutions; begin SolveManySolutions; end; procedure TSimpleGaussLEQ.SolveManySolutions; var i,j: Integer; val: TManySolutionsDataType; begin for j:=fNumOfEqs to fNumOfVars-1 do begin val:=TManySolutionsDataType.Create; SetLength(val.Vars,fNumOfVars-fNumOfEqs); SetLength(val.VarNames,fNumOfVars-fNumOfEqs); val.Vars[j-fNumOfEqs]:=1; for i:=fNumOfEqs to fNumOfVars-1 do if fvariableNames[i]<>'' then val.VarNames[i-fNumOfEqs]:=fvariableNames[i]; fvariables[j]:=VarManySolutionsDataCreate(val); end; SolveOneSolution; end; (* TManySolutionsDataType *) procedure TManySolutionsDataType.Assign(Source: TPersistent); var s: TManySolutionsDataType absolute Source; begin if Source is TManySolutionsDataType then begin Vars:=Copy(s.Vars); InitValue:=s.InitValue; end else inherited Assign(Source); end; function TManySolutionsDataType.Multiplier(value: Real): string; begin if abs(value-1)<=tolerance then Result:='' else Result:=FloatToStr(value)+'*'; end; function TManySolutionsDataType.GetAsString: string; var i: Integer; begin if abs(InitValue)<=tolerance then Result:='' else Result:=FloatToStr(InitValue); for i:=0 to Length(vars)-1 do begin if abs(vars[i])<=tolerance then continue; if vars[i]>0 then if Result='' then Result:=Multiplier(vars[i]) else Result:=Result+'+'+Multiplier(vars[i]) else Result:=Result+'-'+Multiplier(-vars[i]); if (i>=Length(varNames)) or (varNames[i]='') then Result:=Result+'a'+IntToStr(i+1) else Result:=Result+varNames[i]; end; if Result='' then Result:='0'; end; function TManySolutionsDataType.IsPlainNumber: Boolean; var i: Integer; begin Result:=true; for i:=0 to Length(vars)-1 do if abs(vars[i])>tolerance then begin Result:=false; break; end; end; (* function TManySolutionsDataType.AreProportional(other: TManySolutionDataType): Boolean; var i: Integer; begin end; *) procedure TManySolutionsDataType.DoAdd(const value: TAbstractWrapperData); var i: Integer; v: TManySolutionsDataType absolute value; begin if value is TManySolutionsDataType then begin InitValue:=InitValue+v.InitValue; if Length(v.Vars)>Length(vars) then SetLength(vars,Length(v.Vars)); for i:=0 to Length(v.Vars)-1 do Vars[i]:=Vars[i]+v.vars[i]; end else inherited; end; procedure TManySolutionsDataType.DoSubtract(const right: TAbstractWrapperData); var i: Integer; v: TManySolutionsDataType absolute right; begin if right is TManySolutionsDataType then begin InitValue:=InitValue-v.InitValue; if Length(v.Vars)>Length(vars) then SetLength(vars,Length(v.Vars)); for i:=0 to Length(v.Vars)-1 do Vars[i]:=Vars[i]-v.vars[i]; end else inherited; end; procedure TManySolutionsDataType.Mul(value: Real); var i: Integer; begin InitValue:=InitValue*value; for i:=0 to Length(Vars)-1 do Vars[i]:=Vars[i]*value; end; procedure TManySolutionsDataType.DoNegate; begin Mul(-1); end; procedure TManySolutionsDataType.DoMultiply(const right: TAbstractWrapperData); var v: TManySolutionsDataType absolute right; begin if right is TManySolutionsDataType then begin if v.IsPlainNumber then Mul(v.InitValue) else raise Exception.Create('ManySolutionsDataType: multiplication of 2 fundamental solutions is unacceptable!'); end else inherited; end; procedure TManySolutionsDataType.Divide(value: Real); var i: Integer; begin InitValue:=InitValue/value; for i:=0 to Length(Vars)-1 do Vars[i]:=Vars[i]/value; end; procedure TManySolutionsDataType.DoDivide(const right: TAbstractWrapperData); var v: TManySolutionsDataType absolute right; begin if right is TManySolutionsDataType then begin if v.IsPlainNumber then Divide(v.InitValue) else raise Exception.Create('ManySolutionsDataType: division of 2 fundamental solutions is unacceptable!'); end else inherited; end; (* TManySolutionsVariantType *) procedure TManySolutionsVariantType.Cast(var Dest: TVarData; const Source: TVarData); var d: TManySolutionsDataType; begin with TWrapperVarData(Dest) do begin dest.VType:=VarType; d:=TManySolutionsDataType.Create; //либо строка, либо целое, либо с плавающей точкой. case Source.VType of varSmallInt: d.InitValue:=Source.VSmallInt; varInteger: d.InitValue:=Source.VInteger; varSingle: d.InitValue:=Source.VSingle; varDouble: d.InitValue:=Source.VDouble; varCurrency: d.InitValue:=Source.VCurrency; varShortInt: d.InitValue:=Source.VShortInt; varByte: d.InitValue:=Source.VByte; varWord: d.InitValue:=Source.VWord; varLongWord: d.InitValue:=Source.VLongWord; varInt64: d.InitValue:=Source.VInt64; // varstring: //а так ли уж нужно? или строго его и сделать? else d.Free; RaiseCastError; end; data:=d; end; end; procedure TManySolutionsVariantType.CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); var LTemp: TVarData; begin with TWrapperVarData(Source) do begin if Source.VType = VarType then //бывает еще не определенный Variant case AVarType of varOleStr: VarDataFromOleStr(Dest, data.GetAsString); varString: VarDataFromStr(Dest, data.GetAsString); else VarDataInit(LTemp); try VarDataFromStr(Ltemp,data.GetAsString); VarDataCastTo(Dest, LTemp, AVarType); finally VarDataClear(LTemp); end; end else inherited; end; end; (* TSimpleGaussLEQForKirhgof *) constructor TSimpleGaussLEQForKirhgof.Create; begin inherited Create; fSolver:=TSimpleGaussLEQ.Create; fList:=TInterfaceList.Create; end; destructor TSimpleGaussLEQForKirhgof.Destroy; begin fList.Free; fSolver.Free; inherited Destroy; end; procedure TSimpleGaussLEQForKirhgof.Solve; var i: Integer; begin fSolver.Solve; for i:=0 to flist.Count-1 do IEquationNode(flist[i]).SetValue(fSolver.GetVariable(i)); end; procedure TSimpleGaussLEQForKirhgof.SetTolerance(value: Real); begin fSolver.SetTolerance(value); end; procedure TSimpleGaussLEQForKirhgof.AddEquation(vars: TVariableForEqArray; equals: Variant); var i,j: Integer; begin if Length(vars)=0 then begin if VarGetLengthSquared(equals)>fsolver.ftolerance then //0=1 - сразу нет решений Raise Exception.Create('AddEquation: 0=1 type adding, it''s absurd') else //0=0 - игнорируем Exit; end; fSolver.SetDimensions(fSolver.fNumOfVars,fSolver.fNumOfEqs+1); // for i:=0 to fSolver.fNumOfVars-1 do // fSolver.SetMatrix(i,fSolver.fNumOfEqs-1,); for i:=0 to Length(vars)-1 do begin j:=fList.IndexOf(vars[i].reference); if j=-1 then begin j:=fList.Add(vars[i].reference); fSolver.SetDimensions(fSolver.fNumOfVars+1,fSolver.fNumOfEqs); fSolver.fVariableNames[j]:=vars[i].reference.ShowNodeName; end; fSolver.SetMatrix(j,fSolver.fNumOfEqs-1,vars[i].coeff); end; fSolver.SetMatrix(fSolver.fNumOfVars,fSolver.fNumOfEqs-1,equals); end; function TSimpleGaussLEQForKirhgof.GetVariable(p: IEquationNode): Variant; begin Result:=fSolver.GetVariable(fList.IndexOf(p)); end; function TSimpleGaussLEQForKirhgof.GetStatus: TSLEQStatus; begin Result:=fSolver.GetStatus; end; function TSimpleGaussLEQForKirhgof.GetEquationsAsString: string; var i,j: Integer; notfirst: boolean; begin Result:=''; for j:=0 to fsolver.fNumOfEqs-1 do begin notfirst:=false; for i:=0 to fsolver.fNumOfVars-1 do if VarGetLengthSquared(fsolver.GetMatrix(i,j))>fsolver.ftolerance then begin if (not VarIsNumeric(fsolver.GetMatrix(i,j))) or ((fsolver.GetMatrix(i,j)>0) and notfirst) then Result:=Result+'+' else if VarIsNumeric(fsolver.GetMatrix(i,j)) and (fsolver.GetMatrix(i,j)<0) then Result:=Result+'-'; notfirst:=true; Result:=Result+fsolver.GetVariableName(i); if VarIsNumeric(fsolver.GetMatrix(i,j)) and ((abs(fsolver.GetMatrix(i,j))-1)>fsolver.ftolerance) then Result:=Result+'*'+FloatToStr(abs(fsolver.GetMatrix(i,j))) else if not VarIsNumeric(fsolver.GetMatrix(i,j)) then Result:=Result+'*'+fsolver.GetMatrix(i,j); end; Result:=Result+'='+VarToStr(fsolver.GetMatrix(fsolver.fNumOfVars,j))+';'+#13#10; end; end; function TSimpleGaussLEQForKirhgof.GetSolutionAsString: string; var i: Integer; s: string; begin if fsolver.GetStatus=slNoSolution then result:='No solution' else begin (* Result:='('; for i:=0 to fsolver.fNumOfVars-1 do begin s:=fsolver.GetVariable(i); Result:=Result+s; if i<fsolver.fNumOfVars-1 then Result:=Result+';'; end; Result:=Result+')'; *) Result:=''; for i:=0 to fsolver.fNumOfVars-1 do begin s:=fsolver.GetVariable(i); Result:=Result+IEquationNode(flist[i]).ShowValue(fsolver.GetVariable(i)); if i<fsolver.fNumOfVars-1 then Result:=Result+#13#10; end; end; end; procedure TSimpleGaussLEQForKirhgof.SetRootComponent(c: TComponent); begin fRootComponent:=c; end; initialization ManySolutionsVariantType:=TManySolutionsVariantType.Create; finalization FreeAndNil(ManySolutionsVariantType); end.
unit module; interface uses Forms, Dialogs, SysUtils, Classes, DB, ADODB, IniFiles; type TDm = class(TDataModule) sqlCity: TADOQuery; ADOConnection1: TADOConnection; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Dm: TDm; implementation {$R *.dfm} procedure TDm.DataModuleCreate(Sender: TObject); var conf: TIniFile; strConn: String; begin conf := TIniFile.Create(extractfilepath(ParamStr(0)) + 'conf.ini'); strConn := conf.ReadString('access', 'stringConnection', 'Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog="";Data Source=localhost;Initial File Name="";Server SPN=""'); ADOConnection1.Close; ADOConnection1.ConnectionString := strConn; Try ADOConnection1.Open(); Except on E: Exception do begin ShowMessage('Não foi possível se conectar ao banco de dados.' + #13 + 'Erro: ' + E.Message + #13 + 'Tente alterar a string de conexão em ./conf.ini.'); Application.Terminate; exit; end; end; Try //Cria o banco de dados e as tabelas de clientes e cidade, caso não existam sqlCity.SQL.Clear; sqlCity.SQL.Add('IF NOT EXISTS(SELECT name FROM master.dbo.sysdatabases WHERE name = ' + QuotedStr('NEWCON_TEST') + ')' + 'BEGIN ' + ' CREATE DATABASE NEWCON_TEST; ' + 'END '); sqlCity.SQL.Add('USE NEWCON_TEST;'); sqlCity.SQL.Add('IF NOT EXISTS(SELECT name FROM sysobjects WHERE xtype = ' + QuotedStr('U') + ' AND name = ' + QuotedStr('clientes') + ')' + 'BEGIN ' + 'CREATE TABLE clientes ( ' + ' codigo_cliente BIGINT NOT NULL, ' + ' cgc_cpf_cliente NVARCHAR(14) NOT NULL, ' + ' nome NVARCHAR(150) NOT NULL, ' + ' telefone NVARCHAR(50) NOT NULL, ' + ' endereco NVARCHAR(150) NOT NULL, ' + ' bairro NVARCHAR(150) NOT NULL, ' + ' complemento NVARCHAR(150) NOT NULL, ' + ' e_mail NVARCHAR(100) NOT NULL, ' + ' codigo_cidade BIGINT NOT NULL, ' + ' cep NVARCHAR(14) NOT NULL ' + '); ' + 'END '); sqlCity.SQL.Add('IF NOT EXISTS(SELECT name FROM sysobjects WHERE xtype = ' + QuotedStr('U') + ' AND name = ' + QuotedStr('cidades') + ')' + 'BEGIN ' + 'CREATE TABLE cidades ( ' + ' codigo_cidade BIGINT NOT NULL, ' + ' nome NVARCHAR(100) NOT NULL, ' + ' estado NVARCHAR(100) NOT NULL, ' + ' cep_inicial NVARCHAR(8) NOT NULL, ' + ' cep_final NVARCHAR(8) NOT NULL ' + '); ' + 'END '); sqlCity.ExecSQL; Except on E: Exception do begin ShowMessage('Não foi possível criar as tabelas Cidades e Clientes automaticamente!' + #13 + 'Erro: ' + E.Message); Application.Terminate; exit; end; end; end; end.
unit Control.CadastroGeral; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.CadastroGeral; type TCadastrosControl = class private FCadastro : TCadastroGeral; public constructor Create(); destructor Destroy(); override; property Cadastro: TCadastroGeral read FCadastro write FCadastro; function GetID(): Integer; function ValidaCampos(): Boolean; function Localizar(aParam: array of variant): Boolean; function Gravar(): Boolean; end; implementation { TCadastrosControl } uses Common.Utils; constructor TCadastrosControl.Create; begin FCadastro := TCadastroGeral.Create; end; destructor TCadastrosControl.Destroy; begin FCadastro.Free; inherited; end; function TCadastrosControl.GetID: Integer; begin Result := FCadastro.GetID; end; function TCadastrosControl.Gravar: Boolean; begin Result := False; if not ValidaCampos() then Exit; Result := FCadastro.Gravar; end; function TCadastrosControl.Localizar(aParam: array of variant): Boolean; begin Result := FCadastro.Localizar(aParam); end; function TCadastrosControl.ValidaCampos: Boolean; var FDQuery : TFDQuery; aParam: Array of variant; begin try Result := False; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; if FCadastro.Acao = tacAlterar then begin if FCadastro.ID = 0 then begin Application.MessageBox('Informe o ID do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; if FCadastro.Nome.IsEmpty then begin Application.MessageBox('Informe o nome do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FCadastro.Pessoa = 0 then begin Application.MessageBox('Informe o tipo de pessoa do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if not FCadastro.CPF.IsEmpty then begin if FCadastro.Pessoa = 1 then begin if not TUtils.CPF(FCadastro.CPF) then begin Application.MessageBox('Número do CPF inválido!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end else if FCadastro.Pessoa = 2 then begin if not TUtils.CNPJ(FCadastro.CPF) then begin Application.MessageBox('Número do CNPJ inválido!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; SetLength(aParam,2); aParam[0] := 'CPFCNPJ'; aParam[1] := FCadastro.CPF; if FCadastro.Localizar(aParam) then begin FDQuery := FCadastro.Query; end; Finalize(aParam); if FDQuery.RecordCount >= 1 then begin if FCadastro.Acao = tacIncluir then begin Application.MessageBox('CPF/CNPJ já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); FDQuery.Close; Exit; end; end; end; if FCadastro.Pessoa = 1 then begin if FCadastro.Sexo = 0 then begin Application.MessageBox('Informe o sexo do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; Result := True; finally FDQuery.Free; end; end; end.
unit MFichas.Model.Pagamento.Formas.Dinheiro; interface uses MFichas.Model.Pagamento.Interfaces, MFichas.Model.Pagamento.Formas.Dinheiro.Estornar, MFichas.Model.Pagamento.Formas.Dinheiro.Processar; type TModelPagamentoFormasDinheiro = class(TInterfacedObject, iModelPagamentoMetodos) private [weak] FParent: iModelPagamento; constructor Create(AParent: iModelPagamento); public destructor Destroy; override; class function New(AParent: iModelPagamento): iModelPagamentoMetodos; function Processar: iModelPagamentoMetodosProcessar; function Estornar : iModelPagamentoMetodosEstornar; function &End : iModelPagamento; end; implementation { TModelPagamentoFormasDinheiro } function TModelPagamentoFormasDinheiro.&End: iModelPagamento; begin Result := FParent; end; constructor TModelPagamentoFormasDinheiro.Create(AParent: iModelPagamento); begin FParent := AParent; end; destructor TModelPagamentoFormasDinheiro.Destroy; begin inherited; end; function TModelPagamentoFormasDinheiro.Estornar: iModelPagamentoMetodosEstornar; begin Result := TModelPagamentoFormasDinheiroEstornar.New(FParent); end; class function TModelPagamentoFormasDinheiro.New(AParent: iModelPagamento): iModelPagamentoMetodos; begin Result := Self.Create(AParent); end; function TModelPagamentoFormasDinheiro.Processar: iModelPagamentoMetodosProcessar; begin Result := TModelPagamentoFormasDinheiroProcessar.New(FParent); end; end.
unit uKeyValue; interface type IKeyValue = interface(IInterface) ['{D737DB46-298F-4A8E-9311-1E861E31FF91}'] function GetKey: Variant; stdcall; function GetValue: Variant; stdcall; procedure SetKey(const Value: Variant); stdcall; procedure SetValue(const Value: Variant); stdcall; property Key: Variant read GetKey write SetKey; property Value: Variant read GetValue write SetValue; end; function CreateKeyValue(AKey, AValue: Variant): IKeyValue; implementation type TKeyValue = class(TInterfacedObject, IKeyValue) private FKey: Variant; FValue: Variant; public function GetKey: Variant; stdcall; function GetValue: Variant; stdcall; procedure SetKey(const Value: Variant); stdcall; procedure SetValue(const Value: Variant); stdcall; // property Key: Variant read GetKey write SetKey; property Value: Variant read GetValue write SetValue; end; function TKeyValue.GetKey: Variant; begin Result := FKey; end; function TKeyValue.GetValue: Variant; begin Result := FValue; end; procedure TKeyValue.SetKey(const Value: Variant); begin if FKey <> Value then begin FKey := Value; end; end; procedure TKeyValue.SetValue(const Value: Variant); begin if FValue <> Value then begin FValue := Value; end; end; function CreateKeyValue(AKey, AValue: Variant): IKeyValue; begin Result := TKeyValue.Create(); Result.Key := AKey; Result.Value := AValue; end; end.
{******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2008 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} unit CnPropSheetFrm; { |<PRE> ================================================================================ * 软件名称:CnPack 公用单元 * 单元名称:对象 RTTI 信息显示窗体单元 * 单元作者:刘啸(LiuXiao) liuxiao@cnpack.org * 备 注: * 开发平台:PWinXP + Delphi 5 * 兼容测试:未测试 * 本 地 化:该窗体中的字符串暂不符合本地化处理方式 * 单元标识:$Id: CnPropSheetFrm.pas,v 1.10 2008/08/05 15:27:23 zjy Exp $ * 修改记录:2006.11.23 * 加入对象类继承关系的显示 * 2006.11.07 * 创建单元,实现功能 ================================================================================ |</PRE>} interface {$I CnPack.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, ExtCtrls, TypInfo, Contnrs, Buttons, ComCtrls, Tabs, Commctrl {$IFDEF VER130}{$ELSE}, Variants{$ENDIF}; const CN_INSPECTOBJECT = WM_USER + $C10; // Cn Inspect Object type TCnPropContentType = (pctProps, pctEvents, pctCollectionItems, pctStrings, pctComponents, pctControls, pctHierarchy); TCnPropContentTypes = set of TCnPropContentType; TCnDisplayObject = class(TObject) {* 描述一供显示内容的基类 } private FChanged: Boolean; FDisplayValue: string; FObjStr: string; FObjValue: TObject; FObjClassName: string; public property Changed: Boolean read FChanged write FChanged; property DisplayValue: string read FDisplayValue write FDisplayValue; property ObjClassName: string read FObjClassName write FObjClassName; property ObjValue: TObject read FObjValue write FObjValue; property ObjStr: string read FObjStr write FObjStr; end; TCnPropertyObject = class(TCnDisplayObject) {* 描述一属性 } private FIsObject: Boolean; FPropName: string; FPropType: TTypeKind; FPropValue: Variant; public property PropName: string read FPropName write FPropName; property PropType: TTypeKind read FPropType write FPropType; property IsObject: Boolean read FIsObject write FIsObject; property PropValue: Variant read FPropValue write FPropValue; end; TCnEventObject = class(TCnDisplayObject) {* 描述一事件及其处理函数 } private FHandlerName: string; FEventType: string; FEventName: string; public property EventName: string read FEventName write FEventName; property EventType: string read FEventType write FEventType; property HandlerName: string read FHandlerName write FHandlerName; end; TCnStringsObject = class(TCnDisplayObject) private public procedure Clear; end; TCnCollectionItemObject = class(TCnDisplayObject) {* 描述一 Collection Item } private FIndex: Integer; FItemName: string; public property ItemName: string read FItemName write FItemName; property Index: Integer read FIndex write FIndex; end; TCnComponentObject = class(TCnDisplayObject) {* 描述一 Component } private FIndex: Integer; FCompName: string; FDisplayName: string; public property DisplayName: string read FDisplayName write FDisplayName; property CompName: string read FCompName write FCompName; property Index: Integer read FIndex write FIndex; end; TCnControlObject = class(TCnDisplayObject) {* 描述一 Component } private FIndex: Integer; FCtrlName: string; FDisplayName: string; public property DisplayName: string read FDisplayName write FDisplayName; property CtrlName: string read FCtrlName write FCtrlName; property Index: Integer read FIndex write FIndex; end; TCnObjectInspector = class(TObject) {* 对象属性方法的管理基础类 } private FObjectAddr: Pointer; FProperties: TObjectList; FEvents: TObjectList; FInspectComplete: Boolean; FObjClassName: string; FContentTypes: TCnPropContentTypes; FComponents: TObjectList; FControls: TObjectList; FStrings: TCnStringsObject; FIsRefresh: Boolean; FCollectionItems: TObjectList; FHierarchy: string; FOnAfterEvaluateHierarchy: TNotifyEvent; FOnAfterEvaluateCollections: TNotifyEvent; FOnAfterEvaluateControls: TNotifyEvent; FOnAfterEvaluateProperties: TNotifyEvent; FOnAfterEvaluateComponents: TNotifyEvent; function GetEventCount: Integer; function GetPropCount: Integer; function GetInspectComplete: Boolean; function GetCompCount: Integer; function GetControlCount: Integer; function GetCollectionItemCount: Integer; procedure SetInspectComplete(const Value: Boolean); protected procedure SetObjectAddr(const Value: Pointer); virtual; procedure DoEvaluate; virtual; abstract; procedure DoAfterEvaluateComponents; virtual; procedure DoAfterEvaluateControls; virtual; procedure DoAfterEvaluateCollections; virtual; procedure DoAfterEvaluateProperties; virtual; procedure DoAfterEvaluateHierarchy; virtual; function IndexOfProperty(AProperties: TObjectList; const APropName: string): TCnPropertyObject; function IndexOfEvent(AEvents: TObjectList; const AEventName: string): TCnEventObject; public constructor Create(Data: Pointer); virtual; destructor Destroy; override; procedure InspectObject; procedure Clear; property ObjectAddr: Pointer read FObjectAddr write SetObjectAddr; {* 主要供外部写,写入 Object,或 String } property Properties: TObjectList read FProperties; property Events: TObjectList read FEvents; property Strings: TCnStringsObject read FStrings; property Components: TObjectList read FComponents; property Controls: TObjectList read FControls; property CollectionItems: TObjectList read FCollectionItems; property PropCount: Integer read GetPropCount; property EventCount: Integer read GetEventCount; property CompCount: Integer read GetCompCount; property ControlCount: Integer read GetControlCount; property CollectionItemCount: Integer read GetCollectionItemCount; property IsRefresh: Boolean read FIsRefresh write FIsRefresh; property InspectComplete: Boolean read GetInspectComplete write SetInspectComplete; property ContentTypes: TCnPropContentTypes read FContentTypes write FContentTypes; property ObjClassName: string read FObjClassName write FObjClassName; property Hierarchy: string read FHierarchy write FHierarchy; property OnAfterEvaluateProperties: TNotifyEvent read FOnAfterEvaluateProperties write FOnAfterEvaluateProperties; property OnAfterEvaluateComponents: TNotifyEvent read FOnAfterEvaluateComponents write FOnAfterEvaluateComponents; property OnAfterEvaluateControls: TNotifyEvent read FOnAfterEvaluateControls write FOnAfterEvaluateControls; property OnAfterEvaluateCollections: TNotifyEvent read FOnAfterEvaluateCollections write FOnAfterEvaluateCollections; property OnAfterEvaluateHierarchy: TNotifyEvent read FOnAfterEvaluateHierarchy write FOnAfterEvaluateHierarchy; end; TCnObjectInspectorClass = class of TCnObjectInspector; TCnLocalObjectInspector = class(TCnObjectInspector) {* 同一进程内的对象属性方法的管理类 } private FObjectInstance: TObject; protected procedure SetObjectAddr(const Value: Pointer); override; procedure DoEvaluate; override; public property ObjectInstance: TObject read FObjectInstance; end; TCnPropSheetForm = class(TForm) pnlTop: TPanel; tsSwitch: TTabSet; pnlMain: TPanel; lvProp: TListView; mmoText: TMemo; lvEvent: TListView; pnlInspectBtn: TPanel; btnInspect: TSpeedButton; lvCollectionItem: TListView; lvComp: TListView; lvControl: TListView; lblClassName: TLabel; btnRefresh: TSpeedButton; btnTop: TSpeedButton; edtObj: TEdit; lblDollar: TLabel; btnEvaluate: TSpeedButton; pnlHierarchy: TPanel; bvlLine: TBevel; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tsSwitchChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure btnInspectClick(Sender: TObject); procedure lvPropCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure lvPropSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure lvPropCustomDrawSubItem(Sender: TCustomListView; Item: TListItem; SubItem: Integer; State: TCustomDrawState; var DefaultDraw: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnRefreshClick(Sender: TObject); procedure btnTopClick(Sender: TObject); procedure btnEvaluateClick(Sender: TObject); procedure edtObjKeyPress(Sender: TObject; var Key: Char); private FListViewHeaderHeight: Integer; FContentTypes: TCnPropContentTypes; FPropListPtr: PPropList; FPropCount: Integer; FObjectPointer: Pointer; // 指向 Object 实例或 标识字符串 FInspector: TCnObjectInspector; FInspectParam: Pointer; FCurrObj: TObject; FHierarchys: TStrings; FHierPanels: TComponentList; FOnEvaluateBegin: TNotifyEvent; FOnEvaluateEnd: TNotifyEvent; FOnAfterEvaluateHierarchy: TNotifyEvent; FOnAfterEvaluateCollections: TNotifyEvent; FOnAfterEvaluateControls: TNotifyEvent; FOnAfterEvaluateProperties: TNotifyEvent; FOnAfterEvaluateComponents: TNotifyEvent; procedure SetContentTypes(const Value: TCnPropContentTypes); procedure UpdateContentTypes; procedure UpdateUIStrings; procedure UpdateHierarchys; procedure UpdatePanelPositions; procedure MsgInspectObject(var Msg: TMessage); message CN_INSPECTOBJECT; procedure DoEvaluateBegin; virtual; procedure DoEvaluateEnd; virtual; // 事件转移导出到外面 procedure AfterEvaluateComponents(Sender: TObject); procedure AfterEvaluateControls(Sender: TObject); procedure AfterEvaluateCollections(Sender: TObject); procedure AfterEvaluateProperties(Sender: TObject); procedure AfterEvaluateHierarchy(Sender: TObject); public procedure SetPropListSize(const Value: Integer); procedure InspectObject(Data: Pointer); procedure Clear; property ObjectPointer: Pointer read FObjectPointer write FObjectPointer; property ContentTypes: TCnPropContentTypes read FContentTypes write SetContentTypes; property OnEvaluateBegin: TNotifyEvent read FOnEvaluateBegin write FOnEvaluateBegin; property OnEvaluateEnd: TNotifyEvent read FOnEvaluateEnd write FOnEvaluateEnd; property OnAfterEvaluateProperties: TNotifyEvent read FOnAfterEvaluateProperties write FOnAfterEvaluateProperties; property OnAfterEvaluateComponents: TNotifyEvent read FOnAfterEvaluateComponents write FOnAfterEvaluateComponents; property OnAfterEvaluateControls: TNotifyEvent read FOnAfterEvaluateControls write FOnAfterEvaluateControls; property OnAfterEvaluateCollections: TNotifyEvent read FOnAfterEvaluateCollections write FOnAfterEvaluateCollections; property OnAfterEvaluateHierarchy: TNotifyEvent read FOnAfterEvaluateHierarchy write FOnAfterEvaluateHierarchy; end; function EvaluatePointer(Address: Pointer; Data: Pointer = nil; AForm: TCnPropSheetForm = nil): TCnPropSheetForm; function GetPropValueStr(Instance: TObject; PropInfo: PPropInfo): string; var ObjectInspectorClass: TCnObjectInspectorClass = nil; implementation {$R *.DFM} type PParamData = ^TParamData; TParamData = record // Copy from TypInfo Flags: TParamFlags; ParamName: ShortString; TypeName: ShortString; end; const SCnPropContentType: array[TCnPropContentType] of string = ('Properties', 'Events', 'CollectionItems', 'Strings', 'Components', 'Controls', 'Hierarchy'); var FSheetList: TComponentList = nil; CnFormLeft: Integer = 50; CnFormTop: Integer = 50; Closing: Boolean = False; function IndexOfContentTypeStr(const AStr: string): TCnPropContentType; var I: TCnPropContentType; begin Result := pctProps; for I := Low(TCnPropContentType) to High(TCnPropContentType) do if AStr = SCnPropContentType[I] then begin Result := I; Exit; end; end; function EvaluatePointer(Address: Pointer; Data: Pointer = nil; AForm: TCnPropSheetForm = nil): TCnPropSheetForm; begin Result := nil; if Address = nil then Exit; if AForm = nil then AForm := TCnPropSheetForm.Create(nil); AForm.ObjectPointer := Address; AForm.Clear; // AForm.Show; // Don't show here. Show it after message PostMessage(AForm.Handle, CN_INSPECTOBJECT, WPARAM(Data), 0); Result := AForm; end; function PropInfoName(PropInfo: PPropInfo): string; begin Result := string(PropInfo^.Name); end; function GetPropValueStr(Instance: TObject; PropInfo: PPropInfo): string; var iTmp: Integer; S, ObjClassName: string; IntToId: TIntToIdent; function GetParamFlagsName(AParamFlags: TParamFlags): string; const SParamFlag: array[TParamFlag] of string = ('var', 'const', 'array of', 'address', '', 'out'); var I: TParamFlag; begin Result := ''; for I := Low(TParamFlag) to High(TParamFlag) do begin if (I <> pfAddress) and (I in AParamFlags) then Result := Result + SParamFlag[I]; end; end; function GetMethodDeclare: string; var CompName, MthName: string; TypeStr: PShortString; T: PTypeData; P: PParamData; I: Integer; AMethod: TMethod; begin CompName := '*'; if Instance is TComponent then CompName := (Instance as TComponent).Name; MthName := PropInfoName(PropInfo); AMethod := GetMethodProp(Instance, PropInfo); if AMethod.Data <> nil then begin try MthName := TObject(AMethod.Data).MethodName(AMethod.Code); if TObject(AMethod.Data) is TComponent then CompName := (TObject(AMethod.Data) as TComponent).Name; except ; end; end; T := GetTypeData(PropInfo^.PropType^); if T^.MethodKind = mkFunction then Result := Result + 'function ' + CompName + '.' + MthName + '(' else Result := Result + 'procedure ' + CompName + '.' + MthName + '('; P := PParamData(@T^.ParamList); for I := 1 to T^.ParamCount do begin TypeStr := Pointer(Integer(@P^.ParamName) + Length(P^.ParamName) + 1); if Pos('array of', GetParamFlagsName(P^.Flags)) > 0 then Result := Result + Trim(Format('%s: %s %s;', [(P^.ParamName), (GetParamFlagsName(P^.Flags)), TypeStr^])) else Result := Result + trim(Format('%s %s: %s;', [(GetParamFlagsName(P^.Flags)), (P^.ParamName), TypeStr^])); P := PParamData(Integer(P) + SizeOf(TParamFlags) + Length(P^.ParamName) + Length(TypeStr^) + 2); end; Delete(Result, Length(Result), 1); Result := Result + ')'; if T^.MethodKind = mkFunction then Result := Result + ': ' + string(PShortString(P)^); Result := Result + ';'; end; begin Result := ''; case PropInfo^.PropType^^.Kind of tkInteger: begin S := IntToStr(GetOrdProp(Instance, PropInfo)); IntToId := FindIntToIdent(PropInfo^.PropType^); if Assigned(IntToId) and IntToId(GetOrdProp(Instance, PropInfo), S) then else begin if PropInfo^.PropType^^.Name = 'TColor' then S := Format('$%8.8x', [GetOrdProp(Instance, PropInfo)]) else S := IntToStr(GetOrdProp(Instance, PropInfo)); end; end; tkChar, tkWChar: S := IntToStr(GetOrdProp(Instance, PropInfo)); tkClass: begin iTmp := GetOrdProp(Instance, PropInfo); if iTmp <> 0 then begin try ObjClassName := TObject(iTmp).ClassName; except ObjClassName := 'Unknown Object'; end; S := Format('(%s.$%8.8x)', [ObjClassName, iTmp]) end else S := 'nil'; end; tkEnumeration: S := GetEnumProp(Instance, PropInfo); tkSet: S := GetSetProp(Instance, PropInfo); tkFloat: S := FloatToStr(GetFloatProp(Instance, PropInfo)); tkMethod: begin iTmp := GetOrdProp(Instance, PropInfo); if iTmp <> 0 then S := Format('%s: ($%8.8x, $%8.8x): %s', [PropInfo^.PropType^^.Name, Integer(GetMethodProp(Instance, PropInfo).Code), Integer(GetMethodProp(Instance, PropInfo).Data), GetMethodDeclare()]) else S := 'nil'; end; tkString, tkLString, tkWString{$IFDEF DELPHI2009_UP}, tkUString{$ENDIF}: S := GetStrProp(Instance, PropInfo); tkVariant: S := VarToStr(GetVariantProp(Instance, PropInfo)); tkInt64: S := FloatToStr(GetInt64Prop(Instance, PropInfo) + 0.0); end; Result := S; end; { TCnStringsObject } procedure TCnStringsObject.Clear; begin FDisplayValue := ''; Changed := False; end; { TCnObjectInspector } procedure TCnObjectInspector.Clear; begin FStrings.DisplayValue := ''; FObjClassName := ''; FInspectComplete := False; FContentTypes := []; end; constructor TCnObjectInspector.Create(Data: Pointer); begin inherited Create; FProperties := TObjectList.Create(True); FEvents := TObjectList.Create(True); FStrings := TCnStringsObject.Create; FComponents := TObjectList.Create(True); FControls := TObjectList.Create(True); FCollectionItems := TObjectList.Create(True); end; destructor TCnObjectInspector.Destroy; begin FCollectionItems.Free; FControls.Free; FComponents.Free; FStrings.Free; FEvents.Free; FProperties.Free; inherited; end; function TCnObjectInspector.GetCompCount: Integer; begin Result := FComponents.Count; end; function TCnObjectInspector.GetControlCount: Integer; begin Result := FControls.Count; end; function TCnObjectInspector.GetEventCount: Integer; begin Result := FEvents.Count; end; function TCnObjectInspector.GetPropCount: Integer; begin Result := FProperties.Count; end; function TCnObjectInspector.GetCollectionItemCount: Integer; begin Result := FCollectionItems.Count; end; function TCnObjectInspector.GetInspectComplete: Boolean; begin Result := FInspectComplete; end; procedure TCnObjectInspector.InspectObject; begin if FObjectAddr <> nil then begin Clear; try DoEvaluate; except Include(FContentTypes, pctProps); FInspectComplete := True; end; end; end; procedure TCnObjectInspector.SetObjectAddr(const Value: Pointer); begin if FObjectAddr <> Value then begin FObjectAddr := Value; Clear; end; end; procedure TCnObjectInspector.SetInspectComplete(const Value: Boolean); begin FInspectComplete := Value; end; function TCnObjectInspector.IndexOfEvent(AEvents: TObjectList; const AEventName: string): TCnEventObject; var I: Integer; AEvent: TCnEventObject; begin Result := nil; if AEvents <> nil then begin for I := 0 to AEvents.Count - 1 do begin AEvent := TCnEventObject(AEvents.Items[I]); if AEvent.EventName = AEventName then begin Result := AEvent; Exit; end; end; end; end; function TCnObjectInspector.IndexOfProperty(AProperties: TObjectList; const APropName: string): TCnPropertyObject; var I: Integer; AProp: TCnPropertyObject; begin Result := nil; if AProperties <> nil then begin for I := 0 to AProperties.Count - 1 do begin AProp := TCnPropertyObject(AProperties.Items[I]); if AProp.PropName = APropName then begin Result := AProp; Exit; end; end; end; end; procedure TCnObjectInspector.DoAfterEvaluateCollections; begin if Assigned(FOnAfterEvaluateCollections) then FOnAfterEvaluateCollections(Self); end; procedure TCnObjectInspector.DoAfterEvaluateComponents; begin if Assigned(FOnAfterEvaluateComponents) then FOnAfterEvaluateComponents(Self); end; procedure TCnObjectInspector.DoAfterEvaluateControls; begin if Assigned(FOnAfterEvaluateControls) then FOnAfterEvaluateControls(Self); end; procedure TCnObjectInspector.DoAfterEvaluateHierarchy; begin if Assigned(FOnAfterEvaluateHierarchy) then FOnAfterEvaluateHierarchy(Self); end; procedure TCnObjectInspector.DoAfterEvaluateProperties; begin if Assigned(FOnAfterEvaluateProperties) then FOnAfterEvaluateProperties(Self); end; { TCnLocalObjectInspector } procedure TCnLocalObjectInspector.SetObjectAddr(const Value: Pointer); begin IsRefresh := (Value = FObjectAddr); inherited; try FObjectInstance := TObject(Value); except FObjectInstance := nil; FObjClassName := 'Unknown Object'; end; end; procedure TCnLocalObjectInspector.DoEvaluate; var PropListPtr: PPropList; I, APropCount: Integer; PropInfo: PPropInfo; AProp: TCnPropertyObject; AEvent: TCnEventObject; ACollection: TCollection; AComp: TComponent; AControl: TWinControl; AItemObj: TCnCollectionItemObject; ACompObj: TCnComponentObject; AControlObj: TCnControlObject; S: string; IsExisting: Boolean; Hies: TStrings; ATmpClass: TClass; begin if ObjectInstance <> nil then begin if not IsRefresh then begin Properties.Clear; Events.Clear; Components.Clear; Controls.Clear; CollectionItems.Clear; Strings.Clear; end; ContentTypes := [pctHierarchy]; ObjClassName := FObjectInstance.ClassName; Hies := TStringList.Create; ATmpClass := ObjectInstance.ClassType; Hies.Add(ATmpClass.ClassName); while ATmpClass.ClassParent <> nil do begin ATmpClass := ATmpClass.ClassParent; Hies.Add(ATmpClass.ClassName); end; Hierarchy := Hies.Text; Hies.Free; DoAfterEvaluateHierarchy; if ObjectInstance is TStrings then begin Include(FContentTypes, pctStrings); if Strings.DisplayValue <> (FObjectInstance as TStrings).Text then begin Strings.Changed := True; Strings.DisplayValue := (FObjectInstance as TStrings).Text; end; end; APropCount := GetTypeData(PTypeInfo(FObjectInstance.ClassInfo))^.PropCount; GetMem(PropListPtr, APropCount * SizeOf(Pointer)); GetPropList(PTypeInfo(FObjectInstance.ClassInfo), tkAny, PropListPtr); for I := 0 to APropCount - 1 do begin PropInfo := PropListPtr^[I]; if PropInfo^.PropType^^.Kind in tkProperties then begin if not IsRefresh then AProp := TCnPropertyObject.Create else AProp := IndexOfProperty(Properties, PropInfoName(PropInfo)); AProp.PropName := PropInfoName(PropInfo); AProp.PropType := PropInfo^.PropType^^.Kind; AProp.IsObject := AProp.PropType = tkClass; AProp.PropValue := GetPropValue(FObjectInstance, PropInfoName(PropInfo)); if AProp.IsObject then AProp.ObjValue := GetObjectProp(FObjectInstance, PropInfo) else AProp.ObjValue := nil; S := GetPropValueStr(FObjectInstance, PropInfo); if S <> AProp.DisplayValue then begin AProp.DisplayValue := S; AProp.Changed := True; end else AProp.Changed := False; if not IsRefresh then Properties.Add(AProp); Include(FContentTypes, pctProps); end; if PropInfo^.PropType^^.Kind = tkMethod then begin if not IsRefresh then AEvent := TCnEventObject.Create else AEvent := IndexOfEvent(FEvents, PropInfoName(PropInfo)); AEvent.EventName := PropInfoName(PropInfo); AEvent.EventType := VarToStr(GetPropValue(FObjectInstance, PropInfoName(PropInfo))); S := GetPropValueStr(FObjectInstance, PropInfo); if S <> AEvent.DisplayValue then begin AEvent.DisplayValue := S; AEvent.Changed := True; end else AEvent.Changed := False; if not IsRefresh then FEvents.Add(AEvent); Include(FContentTypes, pctEvents); end; end; FreeMem(PropListPtr); DoAfterEvaluateProperties; // 处理 CollectionItem,Components 和 Controls,取来直接比较是否 Changed 即可。 if ObjectInstance is TCollection then begin // 获得其 Items ACollection := (FObjectInstance as TCollection); for I := 0 to ACollection.Count - 1 do begin IsExisting := IsRefresh and (I < FCollectionItems.Count); if IsExisting then AItemObj := TCnCollectionItemObject(FCollectionItems.Items[I]) else AItemObj := TCnCollectionItemObject.Create; AItemObj.ObjClassName := ACollection.ItemClass.ClassName; AItemObj.Index := I; if AItemObj.ObjValue <> ACollection.Items[I] then begin AItemObj.ObjValue := ACollection.Items[I]; AItemObj.Changed := True; end else AItemObj.Changed := False; S := ACollection.GetNamePath; if S = '' then S := '*'; AItemObj.ItemName := Format('%s.Item[%d]', [S, I]); AItemObj.DisplayValue := Format('%s: $%8.8x', [AItemObj.ObjClassName, Integer(AItemObj.ObjValue)]); if not IsExisting then CollectionItems.Add(AItemObj); Include(FContentTypes, pctCollectionItems); end; DoAfterEvaluateCollections; end else if ObjectInstance is TComponent then begin // 获得其 Componets AComp := (FObjectInstance as TComponent); for I := 0 to AComp.ComponentCount - 1 do begin IsExisting := IsRefresh and (I < FComponents.Count); if IsExisting then ACompObj := TCnComponentObject(FComponents.Items[I]) else ACompObj := TCnComponentObject.Create; ACompObj.ObjClassName := AComp.Components[I].ClassName; ACompObj.CompName := AComp.Components[I].Name; ACompObj.Index := I; if ACompObj.ObjValue <> AComp.Components[I] then begin ACompObj.ObjValue := AComp.Components[I]; ACompObj.Changed := True; end else ACompObj.Changed := False; ACompObj.DisplayName := Format('%s.Components[%d]', [AComp.Name, I]); ACompObj.DisplayValue := Format('%s: %s: $%8.8x', [ACompObj.CompName, ACompObj.ObjClassName, Integer(ACompObj.ObjValue)]); if not IsExisting then Components.Add(ACompObj); Include(FContentTypes, pctComponents); end; DoAfterEvaluateComponents; // 获得其 Controls if ObjectInstance is TWinControl then begin AControl:= (FObjectInstance as TWinControl); for I := 0 to AControl.ControlCount - 1 do begin IsExisting := IsRefresh and (I < FControls.Count); if IsExisting then AControlObj := TCnControlObject(FControls.Items[I]) else AControlObj := TCnControlObject.Create; AControlObj.ObjClassName := AControl.Controls[I].ClassName; AControlObj.CtrlName := AControl.Controls[I].Name; AControlObj.Index := I; if AControlObj.ObjValue <> AControl.Controls[I] then begin AControlObj.ObjValue := AControl.Controls[I]; AControlObj.Changed := True; end else AControlObj.Changed := False; AControlObj.DisplayName := Format('%s.Controls[%d]', [AControl.Name, I]); AControlObj.DisplayValue := Format('%s: %s: $%8.8x', [AControlObj.CtrlName, AControlObj.ObjClassName, Integer(AControlObj.ObjValue)]); if not IsExisting then Controls.Add(AControlObj); Include(FContentTypes, pctControls); end; DoAfterEvaluateControls; end; end; end; if FContentTypes = [] then Include(FContentTypes, pctProps); FInspectComplete := True; end; { TCnPropSheetForm } procedure TCnPropSheetForm.FormCreate(Sender: TObject); begin FSheetList.Add(Self); FContentTypes := []; FHierarchys := TStringList.Create; FHierPanels := TComponentList.Create(True); btnInspect.Height := lvProp.Canvas.TextHeight('lj') - 1; btnInspect.Width := btnInspect.Height; UpdateUIStrings; // FListViewHeaderHeight := ListView_GetItemSpacing(lvProp.Handle, 1); FListViewHeaderHeight := 8; // 列头高度 Left := CnFormLeft; Top := CnFormTop; Inc(CnFormLeft, 20); Inc(CnFormTop, 20); if CnFormLeft >= Screen.Width - Self.Width - 30 then CnFormLeft := 50; if CnFormTop >= Screen.Height - Self.Height - 30 then CnFormTop := 50; end; procedure TCnPropSheetForm.InspectObject(Data: Pointer); var I: Integer; begin if ObjectInspectorClass = nil then Exit; if FInspector = nil then begin FInspector := TCnObjectInspector(ObjectInspectorClass.NewInstance); FInspector.Create(Data); end; // 接收内部事件 FInspector.OnAfterEvaluateProperties := AfterEvaluateProperties; FInspector.OnAfterEvaluateComponents := AfterEvaluateComponents; FInspector.OnAfterEvaluateControls := AfterEvaluateControls; FInspector.OnAfterEvaluateCollections := AfterEvaluateCollections; FInspector.OnAfterEvaluateHierarchy := AfterEvaluateHierarchy; FInspector.ObjectAddr := FObjectPointer; FInspector.InspectObject; while not FInspector.InspectComplete do Application.ProcessMessages; lvProp.Items.Clear; lvEvent.Items.Clear; lvCollectionItem.Items.Clear; lvComp.Items.Clear; lvControl.Items.Clear; if FInspector.ObjClassName <> '' then lblClassName.Caption := FInspector.ObjClassName else lblClassName.Caption := 'Unknown Object'; edtObj.Text := Format('%8.8x', [Integer(FInspector.ObjectAddr)]); lblClassName.Caption := Format('%s: $%8.8x', [lblClassName.Caption, Integer(FInspector.ObjectAddr)]); for I := 0 to FInspector.PropCount - 1 do begin with lvProp.Items.Add do begin Data := FInspector.Properties.Items[I]; Caption := TCnPropertyObject(FInspector.Properties.Items[I]).PropName; SubItems.Add(TCnPropertyObject(FInspector.Properties.Items[I]).DisplayValue); end; end; for I := 0 to FInspector.EventCount - 1 do begin with lvEvent.Items.Add do begin Data := FInspector.Events.Items[I]; Caption := TCnEventObject(FInspector.Events.Items[I]).EventName; SubItems.Add(TCnEventObject(FInspector.Events.Items[I]).DisplayValue); end; end; for I := 0 to FInspector.CollectionItemCount - 1 do begin with lvCollectionItem.Items.Add do begin Data := FInspector.CollectionItems.Items[I]; Caption := TCnCollectionItemObject(FInspector.CollectionItems.Items[I]).ItemName; SubItems.Add(TCnCollectionItemObject(FInspector.CollectionItems.Items[I]).DisplayValue); end; end; for I := 0 to FInspector.CompCount - 1 do begin with lvComp.Items.Add do begin Data := FInspector.Components.Items[I]; Caption := TCnComponentObject(FInspector.Components.Items[I]).DisplayName; SubItems.Add(TCnComponentObject(FInspector.Components.Items[I]).DisplayValue); end; end; for I := 0 to FInspector.ControlCount - 1 do begin with lvControl.Items.Add do begin Data := FInspector.Controls.Items[I]; Caption := TCnControlObject(FInspector.Controls.Items[I]).DisplayName; SubItems.Add(TCnControlObject(FInspector.Controls.Items[I]).DisplayValue); end; end; mmoText.Lines.Text := FInspector.Strings.DisplayValue; FHierarchys.Text := FInspector.Hierarchy; UpdateHierarchys; ContentTypes := FInspector.ContentTypes; end; procedure TCnPropSheetForm.SetContentTypes(const Value: TCnPropContentTypes); begin if Value <> FContentTypes then begin FContentTypes := Value; UpdateContentTypes; end; end; procedure TCnPropSheetForm.SetPropListSize(const Value: Integer); begin if (FPropListPtr <> nil) and (FPropCount > 0) then begin FreeMem(FPropListPtr, FPropCount * SizeOf(Pointer)); FPropCount := 0; FPropListPtr := nil; end; if Value > 0 then begin GetMem(FPropListPtr, Value * SizeOf(Pointer)); FPropCount := Value; end; end; procedure TCnPropSheetForm.UpdateContentTypes; var AType: TCnPropContentType; begin tsSwitch.Tabs.Clear; for AType := Low(TCnPropContentType) to High(TCnPropContentType) do if AType in FContentTypes then tsSwitch.Tabs.Add(SCnPropContentType[AType]); tsSwitch.TabIndex := 0; end; procedure TCnPropSheetForm.UpdateUIStrings; begin end; procedure TCnPropSheetForm.FormResize(Sender: TObject); var FixWidth: Integer; begin if Parent <> nil then FixWidth := 20 else FixWidth := 28; lvProp.Columns[1].Width := Self.Width - lvProp.Columns[0].Width - FixWidth; lvEvent.Columns[1].Width := Self.Width - lvEvent.Columns[0].Width - FixWidth; lvCollectionItem.Columns[1].Width := Self.Width - lvCollectionItem.Columns[0].Width - FixWidth; lvComp.Columns[1].Width := Self.Width - lvComp.Columns[0].Width - FixWidth; lvControl.Columns[1].Width := Self.Width - lvControl.Columns[0].Width - FixWidth; UpdatePanelPositions; end; procedure TCnPropSheetForm.FormDestroy(Sender: TObject); begin FHierarchys.Free; FHierPanels.Free; if FInspector <> nil then FreeAndNil(FInspector); end; procedure TCnPropSheetForm.Clear; begin mmoText.Lines.Clear; UpdateUIStrings; end; procedure TCnPropSheetForm.UpdateHierarchys; var I: Integer; APanel: TPanel; begin // 根据 FHierarchys 绘制 Hierarchy 图 FHierPanels.Clear; for I := 0 to FHierarchys.Count - 1 do begin APanel := TPanel.Create(nil); APanel.Caption := FHierarchys.Strings[I]; APanel.BevelOuter := bvNone; APanel.BevelInner := bvRaised; APanel.Parent := pnlHierarchy; FHierPanels.Add(APanel); end; UpdatePanelPositions; end; procedure TCnPropSheetForm.tsSwitchChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); var AControl: TWinControl; NeedChangePanel: Boolean; begin AControl := nil; NeedChangePanel := False; case IndexOfContentTypeStr(tsSwitch.Tabs.Strings[NewTab]) of pctProps: AControl := lvProp; pctEvents: AControl := lvEvent; pctCollectionItems: AControl := lvCollectionItem; pctStrings: AControl := mmoText; pctComponents: AControl := lvComp; pctControls: AControl := lvControl; pctHierarchy: begin AControl := pnlHierarchy; NeedChangePanel := True; end; end; if AControl <> nil then begin AControl.BringToFront; AControl.Visible := True; AControl.Align := alClient; if NeedChangePanel then UpdatePanelPositions; end; end; procedure TCnPropSheetForm.btnInspectClick(Sender: TObject); begin if FCurrObj <> nil then EvaluatePointer(FCurrObj, FInspectParam); end; procedure TCnPropSheetForm.lvPropCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); var ARect: TRect; ALv: TListView; begin if Sender is TListView then begin ALv := Sender as TListView; ListView_GetSubItemRect(ALv.Handle, Item.Index, 0, LVIR_BOUNDS, @ARect); ALv.Canvas.Brush.Color := $00FFBBBB; ALv.Canvas.FillRect(ARect); if ALv.Focused then begin if (Item <> nil) and (Item.Data <> nil) and (ALv.Selected = Item) and (TCnDisplayObject(Item.Data).ObjValue <> nil) then begin ARect := Item.DisplayRect(drSelectBounds); FCurrObj := TCnDisplayObject(Item.Data).ObjValue; if ARect.Top >= FListViewHeaderHeight then begin pnlInspectBtn.Parent := ALv; pnlInspectBtn.Left := ARect.Right - pnlInspectBtn.Width - 1; pnlInspectBtn.Top := ARect.Top + 1; pnlInspectBtn.Visible := True; end else pnlInspectBtn.Visible := False; end; Exit; end; pnlInspectBtn.Visible := False; end; end; procedure TCnPropSheetForm.lvPropSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Sender is TListView then begin if (Item <> nil) and (Item.Data <> nil) and ((Sender as TListView).Selected = Item) and (TCnDisplayObject(Item.Data).ObjValue <> nil) then else pnlInspectBtn.Visible := False; end; end; procedure TCnPropSheetForm.lvPropCustomDrawSubItem(Sender: TCustomListView; Item: TListItem; SubItem: Integer; State: TCustomDrawState; var DefaultDraw: Boolean); var ARect: TRect; ALv: TListView; begin if Sender is TListView then begin ALv := Sender as TListView; ListView_GetSubItemRect(ALv.Handle, Item.Index, 1, LVIR_BOUNDS, @ARect); ALv.Canvas.Brush.Color := $00AAFFFF; ALv.Canvas.FillRect(ARect); if (Item <> nil) and (Item.Data <> nil) and TCnDisplayObject(Item.Data).Changed then begin ALv.Canvas.Font.Color := clRed; ALv.Canvas.Font.Style := [fsBold]; end else begin ALv.Canvas.Font.Color := clBlack; ALv.Canvas.Font.Style := []; end; end; end; procedure TCnPropSheetForm.FormClose(Sender: TObject; var Action: TCloseAction); var KeyState: TKeyboardState; I: Integer; begin if Closing then Exit; GetKeyboardState(KeyState); if (KeyState[VK_SHIFT] and $80) <> 0 then // 按 Shift 全关 begin Closing := True; try for I := FSheetList.Count - 1 downto 0 do if FSheetList.Items[I] <> Self then FSheetList.Delete(I); finally Closing := False; end; end; end; procedure TCnPropSheetForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TCnPropSheetForm.btnRefreshClick(Sender: TObject); begin EvaluatePointer(FObjectPointer, FInspectParam, Self); end; procedure TCnPropSheetForm.btnTopClick(Sender: TObject); begin if btnTop.Down then FormStyle := fsStayOnTop else FormStyle := fsNormal; end; procedure TCnPropSheetForm.btnEvaluateClick(Sender: TObject); var P: Integer; begin P := StrToIntDef('$' + edtObj.Text, 0); if P <> 0 then EvaluatePointer(Pointer(P), FInspectParam, Self); end; procedure TCnPropSheetForm.edtObjKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then btnEvaluate.Click; end; procedure TCnPropSheetForm.UpdatePanelPositions; const PanelMargin = 20; PanelStep = 45; var I: Integer; APanel: TPanel; begin APanel := nil; for I := 0 to FHierPanels.Count - 1 do begin APanel := TPanel(FHierPanels.Items[I]); APanel.Left := PanelMargin; APanel.Width := Width - PanelMargin * 2; APanel.Top := PanelMargin + I * PanelStep; APanel.Height := PanelStep - PanelMargin; end; if (APanel <> nil) and (FHierPanels.Count > 1) then begin bvlLine.Left := pnlHierarchy.Width div 2; bvlLine.Top := PanelMargin; bvlLine.Height := APanel.Top - bvlLine.Top; bvlLine.SendToBack; bvlLine.Visible := True; end else begin bvlLine.Visible := False; end; end; procedure TCnPropSheetForm.MsgInspectObject(var Msg: TMessage); begin DoEvaluateBegin; try FInspectParam := Pointer(Msg.WParam); InspectObject(FInspectParam); finally DoEvaluateEnd; Show; // After Evaluation. Show the form. end; end; procedure TCnPropSheetForm.DoEvaluateBegin; begin if Assigned(FOnEvaluateBegin) then FOnEvaluateBegin(Self); end; procedure TCnPropSheetForm.DoEvaluateEnd; begin if Assigned(FOnEvaluateEnd) then FOnEvaluateEnd(Self); end; procedure TCnPropSheetForm.AfterEvaluateCollections(Sender: TObject); begin if Assigned(FOnAfterEvaluateCollections) then FOnAfterEvaluateCollections(Sender); end; procedure TCnPropSheetForm.AfterEvaluateComponents(Sender: TObject); begin if Assigned(FOnAfterEvaluateComponents) then FOnAfterEvaluateComponents(Sender); end; procedure TCnPropSheetForm.AfterEvaluateControls(Sender: TObject); begin if Assigned(FOnAfterEvaluateControls) then FOnAfterEvaluateControls(Sender); end; procedure TCnPropSheetForm.AfterEvaluateHierarchy(Sender: TObject); begin if Assigned(FOnAfterEvaluateHierarchy) then FOnAfterEvaluateHierarchy(Sender); end; procedure TCnPropSheetForm.AfterEvaluateProperties(Sender: TObject); begin if Assigned(FOnAfterEvaluateProperties) then FOnAfterEvaluateProperties(Sender); end; initialization FSheetList := TComponentList.Create(True); ObjectInspectorClass := TCnLocalObjectInspector; finalization // Free All Form Instances. FreeAndNil(FSheetList); end.
unit m3Endings; interface uses m3EndingReplaceList; procedure InitEndings(const aBasePath: AnsiString); implementation Uses l3Memory, l3FileUtils, m0LngLib, ZipForge, SysUtils, Classes; const gBasePath: AnsiString = ''; const cZipName = 'scdata.zip'; cERFileName = 'endings.txt'; function m3LoadEndings(const aList: Tm3EndingReplaceList; const aBasePath: AnsiString): Boolean; var l_Path: AnsiString; l_MS : Tl3MemoryStream; l_Zip : TZipForge; begin Result := False; l_Path := ConcatDirName(aBasePath, cZipName); if FileExists(l_Path) then begin l_Zip := TZipForge.Create(nil); try l_Zip.FileName := l_Path; l_Zip.Password := 'Run-time error 216'; l_Zip.OpenArchive; l_MS := Tl3MemoryStream.Create; try l_Zip.ExtractToStream(cERFileName, l_MS); l_MS.Seek(0, 0); aList.Load(l_MS); Result := True; finally FreeAndNil(l_MS); end; finally FreeAndNil(l_Zip); end; end; end; procedure InitEndingListProc(aERList: Tm3EndingReplaceList); begin if not m3LoadEndings(aERList, gBasePath) then raise EListError.CreateFmt('Ошибка загрузки словаря окончаний из файла %s', [cZipName]); end; procedure InitEndings(const aBasePath: AnsiString); begin gBasePath:= aBasePath; g_InitEndingListProc := InitEndingListProc; end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Lists Description : Generic Lists functions Author : Kike Pérez Version : 1.2 Created : 04/11/2018 Modified : 12/03/2020 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.Lists; {$i QuickLib.inc} interface uses Classes, SysUtils, RTTI, TypInfo, Generics.Collections, Generics.Defaults, Quick.RTTI.Utils, Quick.Arrays, Quick.Value; //enable use of property paths (like namespaces) in search {$DEFINE PROPERTYPATH_MODE} type TClassField = (cfField, cfProperty); TSearchDictionary<TKey,TValue> = class(TObjectDictionary<TKey,TValue>) private fIndexName : string; fFieldName : string; fClassField : TClassField; public property IndexName : string read fIndexName write fIndexName; property FieldName : string read fFieldName write fFieldName; property ClassField : TClassField read fClassField write fClassField; end; TIndexList<T> = class private fList : TList<TSearchDictionary<Variant,T>>; fDictionaryIndex : TObjectDictionary<string,TSearchDictionary<Variant,T>>; public constructor Create; destructor Destroy; override; property List : TList<TSearchDictionary<Variant,T>> read fList; function Get(const aIndexName : string) : TSearchDictionary<Variant,T>; procedure Add(const aIndexName, aFieldName : string; aClassField : TClassField = cfProperty); procedure Remove(const aIndexName : string); end; TIndexedObjectList<T: class> = class(TList<T>) private fOwnsObjects: Boolean; fIndexes : TIndexList<T>; protected procedure Notify(const Value: T; Action: TCollectionNotification); override; public constructor Create(aOwnsObjects: Boolean = True); overload; constructor Create(const aComparer: IComparer<T>; aOwnsObjects: Boolean = True); overload; constructor Create(const aCollection: TEnumerable<T>; aOwnsObjects: Boolean = True); overload; destructor Destroy; override; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; property Indexes : TIndexList<T> read fIndexes; function Get(const aIndexName : string; aValue : Variant) : T; end; TSearchObjectList<T: class> = class(TObjectList<T>) public function Get(const aFieldName: string; const aValue: string; aClassField : TClassField = cfProperty) : T; overload; function Get(const aFieldName : string; aValue : Int64; aClassField : TClassField = cfProperty) : T; overload; function Get(const aFieldName : string; aValue : Double; aClassField : TClassField = cfProperty) : T; overload; function Get(const aFieldName : string; aValue : TDateTime; aClassField : TClassField = cfProperty) : T; overload; end; implementation { TIndexedObjectList<T> } constructor TIndexedObjectList<T>.Create(aOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := aOwnsObjects; fIndexes := TIndexList<T>.Create; end; constructor TIndexedObjectList<T>.Create(const aComparer: IComparer<T>; aOwnsObjects: Boolean); begin inherited Create(aComparer); FOwnsObjects := aOwnsObjects; fIndexes := TIndexList<T>.Create; end; constructor TIndexedObjectList<T>.Create(const aCollection: TEnumerable<T>; aOwnsObjects: Boolean); begin inherited Create(aCollection); FOwnsObjects := aOwnsObjects; fIndexes := TIndexList<T>.Create; end; procedure TIndexedObjectList<T>.Notify(const Value: T; Action: TCollectionNotification); var sindex : TSearchDictionary<Variant,T>; propvalue : TValue; begin inherited; if Action = cnAdded then begin for sindex in fIndexes.List do begin try if sindex.ClassField = TClassField.cfField then propvalue := TRTTI.GetFieldValue(TObject(Value),sindex.FieldName) else begin {$IFNDEF PROPERTYPATH_MODE} propvalue := TRTTI.GetPropertyValue(TObject(Value),sindex.FieldName); {$ELSE} propvalue := TRTTI.GetPathValue(TObject(Value),sindex.FieldName); {$ENDIF} end; except raise Exception.CreateFmt('Cannot add value to "%s" search dictionary!',[sindex.IndexName]); end; sindex.Add(propvalue.AsVariant,Value); end; end; //remove object if owned if OwnsObjects and ((Action = cnRemoved) or (Action = cnExtracted)) then begin for sindex in fIndexes.List do begin try if sindex.ClassField = TClassField.cfField then propvalue := TRTTI.GetFieldValue(TObject(Value),sindex.FieldName) else begin {$IFNDEF PROPERTYPATH_MODE} propvalue := TRTTI.GetPropertyValue(TObject(Value),sindex.FieldName); {$ELSE} propvalue := TRTTI.GetPathValue(TObject(Value),sindex.FieldName); {$ENDIF} end; except raise Exception.CreateFmt('Cannot remove value to "%s" search dictionary!',[sindex.IndexName]); end; sindex.Remove(propvalue.AsVariant); end; Value.DisposeOf; end; end; destructor TIndexedObjectList<T>.Destroy; begin inherited; fIndexes.Free; end; function TIndexedObjectList<T>.Get(const aIndexName: string; aValue : Variant): T; var sindex : TSearchDictionary<Variant,T>; begin Result := nil; sindex := fIndexes.Get(aIndexName.ToLower); if sindex <> nil then sindex.TryGetValue(aValue,Result) else raise Exception.CreateFmt('Index "%s" not found!',[aIndexName]); end; { TIndexList<T> } procedure TIndexList<T>.Add(const aIndexName, aFieldName : string; aClassField : TClassField = cfProperty); var sdict : TSearchDictionary<Variant,T>; begin if aClassField = TClassField.cfField then begin if not TRTTI.FieldExists(TypeInfo(T),aFieldName) then raise Exception.CreateFmt('Not found field "%s" to create a search dictionary!',[aFieldName]); end else begin if not TRTTI.PropertyExists(TypeInfo(T),aFieldName) then raise Exception.CreateFmt('Not found property "%s" to create a search dictionary!',[aFieldName]); end; sdict := TSearchDictionary<Variant,T>.Create; sdict.IndexName := aIndexName; sdict.FieldName := aFieldName; sdict.ClassField := aClassField; fList.Add(sdict); fDictionaryIndex.Add(aIndexName.ToLower,sdict); end; procedure TIndexList<T>.Remove(const aIndexName: string); var sdict : TSearchDictionary<Variant,T>; begin if not fDictionaryIndex.ContainsKey(aIndexName) then raise Exception.CreateFmt('Cannot remove an inexistent "%s" search dictionary!',[aIndexName]); fList.Remove(sdict); fDictionaryIndex.Remove(aIndexName.ToLower); sdict.Free; end; constructor TIndexList<T>.Create; begin fList := TList<TSearchDictionary<Variant,T>>.Create; fDictionaryIndex := TObjectDictionary<string,TSearchDictionary<Variant,T>>.Create; end; destructor TIndexList<T>.Destroy; var sindex : TSearchDictionary<Variant,T>; begin for sindex in fList do sindex.Free; fList.Free; fDictionaryIndex.Free; inherited; end; function TIndexList<T>.Get(const aIndexName: string): TSearchDictionary<Variant, T>; begin Result := nil; fDictionaryIndex.TryGetValue(aIndexName,Result); end; { TSearchObjectList<T> } function TSearchObjectList<T>.Get(const aFieldName: string; const aValue: string; aClassField : TClassField = cfProperty): T; var val : T; begin Result := nil; for val in List do begin if aClassField = TClassField.cfField then begin if (val <> nil) and (TRTTI.GetFieldValue(TObject(val),aFieldName).AsString = aValue) then Exit(val); end else begin if (val <> nil) and (GetStrProp(TObject(val),aFieldName) = aValue) then Exit(val); end; end; end; function TSearchObjectList<T>.Get(const aFieldName: string; aValue: Int64; aClassField : TClassField = cfProperty): T; var val : T; begin Result := nil; for val in List do begin if aClassField = TClassField.cfField then begin if TRTTI.GetFieldValue(TObject(val),aFieldName).AsInt64 = aValue then Exit(val); end else begin if GetInt64Prop(TObject(val),aFieldName) = aValue then Exit(val); end; end; end; function TSearchObjectList<T>.Get(const aFieldName: string; aValue: Double; aClassField : TClassField = cfProperty): T; var val : T; begin Result := nil; for val in List do begin if aClassField = TClassField.cfField then begin if TRTTI.GetFieldValue(TObject(val),aFieldName).AsExtended = aValue then Exit(val); end else begin if GetFloatProp(TObject(val),aFieldName) = aValue then Exit(val); end; end; end; function TSearchObjectList<T>.Get(const aFieldName: string; aValue: TDateTime; aClassField : TClassField = cfProperty): T; var val : T; begin Result := nil; for val in List do begin if aClassField = TClassField.cfField then begin if TRTTI.GetFieldValue(TObject(val),aFieldName).AsExtended = aValue then Exit(val); end else begin if GetFloatProp(TObject(val),aFieldName) = aValue then Exit(val); end; end; end; end.
unit UManipulacaoINI; interface uses FireDAc.Comp.Client, System.SysUtils, System.IniFiles; type vtTipoRetono = (vtpDB , vtpHOST); type TManipulacaoINI = class(TObject) private FServidor : String; FUsuario : String; FSenha : String; FPorta : Integer; FDatabase : String; FDriver : String; FPath : String; FSecao : String; function fncDATABASE(vlTipoRetornoDBouHost : vtTipoRetono; vlDatabase:String) : String; public constructor Create(Path: string; Secao: string); procedure Conectar(var Conexao: TFDConnection); virtual; procedure LeINIDbx; virtual; end; implementation { TManipulacaoINI } procedure TManipulacaoINI.Conectar(var Conexao: TFDConnection); begin LeINIDbx; try //Passa os parâmetros para o objeto Conexão Conexao.Connected := False; Conexao.LoginPrompt := False; Conexao.Params.Clear; Conexao.Params.Add('hostname='+ FServidor); Conexao.Params.Add('user_name='+ FUsuario); Conexao.Params.Add('password='+ FSenha); Conexao.Params.Add('port='+ IntToStr(FPorta)); Conexao.Params.Add('Database='+ FDatabase); Conexao.Params.Add('DriverID='+ FDriver); Except on E:Exception do raise Exception.Create('Erro ao carregar parâmetros de conexão!'#13#10 + E.Message); end; end; constructor TManipulacaoINI.Create(Path, Secao: string); begin if FileExists(Path) then begin FPath := Path; FSecao := Secao; end else raise Exception.Create('Arquivo INI para configuração não encontrado.'#13#10'Aplicação será finalizada.'); end; function TManipulacaoINI.fncDATABASE(vlTipoRetornoDBouHost: vtTipoRetono; vlDatabase: String): String; var i : Integer; vlAchou : Boolean; vlRetorno : String; begin vlAchou := False; vlRetorno := ''; if vlTipoRetornoDBouHost = vtpHOST then begin for i := 1 to Length(vlDatabase) do begin if Copy(vlDatabase, i,1) = ':' then begin break; end; if not vlAchou then vlRetorno := vlRetorno + Copy(vlDatabase, i,1); end; end else if vlTipoRetornoDBouHost = vtpDB then begin for i := 1 to Length(vlDatabase) do begin if vlAchou then vlRetorno := vlRetorno + Copy(vlDatabase, i,1); if Copy(vlDatabase, i,1) = ':' then begin vlAchou := True; end; end; end; Result := vlRetorno; end; procedure TManipulacaoINI.LeINIDbx; var ArqIni : TIniFile; begin ArqIni := TIniFile.Create(FPath); try FServidor := fncDATABASE(vtpHOST, ArqIni.ReadString(FSecao, 'Database', '')); FPorta := 3050; FDatabase := fncDATABASE(vtpDB, ArqIni.ReadString(FSecao, 'Database', '')); FSenha := ArqIni.ReadString(FSecao, 'Password', ''); FUsuario := ArqIni.ReadString(FSecao, 'User_Name', ''); FDriver := 'FB'; finally FreeAndNil(ArqIni); end; end; end.
program exFunction; var a,b, ret : integer; c : string; function max(num1, num2: integer): integer; var (* local variable declaration *) result: integer; begin if (num1 > num2) then result := num1 else result := num2; max := result; end; begin c := max(a,b) end.
unit uSettlementARAP; interface uses uModel, uAR, uSupplier, System.SysUtils, System.Generics.Collections; type TSettlementARAPItemAR = class; TSettlementARAPItemAP = class; TSettlementARAP = class(TAPPobject) private FKeterangan: string; FNoBukti: string; FSettlementARAPItemAPs: TObjectList<TSettlementARAPItemAP>; FSettlementARAPItemARs: TObjectList<TSettlementARAPItemAR>; FSupplier: TSupplier; FTglBukti: TDatetime; function GetSettlementARAPItemAPs: TObjectList<TSettlementARAPItemAP>; function GetSettlementARAPItemARs: TObjectList<TSettlementARAPItemAR>; public destructor Destroy; override; published property Keterangan: string read FKeterangan write FKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property SettlementARAPItemAPs: TObjectList<TSettlementARAPItemAP> read GetSettlementARAPItemAPs write FSettlementARAPItemAPs; property SettlementARAPItemARs: TObjectList<TSettlementARAPItemAR> read GetSettlementARAPItemARs write FSettlementARAPItemARs; property Supplier: TSupplier read FSupplier write FSupplier; property TglBukti: TDatetime read FTglBukti write FTglBukti; end; TSettlementARAPItemAR = class(TAppObjectItem) private FAR: TAR; FNominal: Double; FSettlementARAP: TSettlementARAP; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property AR: TAR read FAR write FAR; property Nominal: Double read FNominal write FNominal; property SettlementARAP: TSettlementARAP read FSettlementARAP write FSettlementARAP; end; TSettlementARAPItemAP = class(TAppObjectItem) private FAP: TAP; FNominal: Double; FSettlementARAP: TSettlementARAP; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property AP: TAP read FAP write FAP; property Nominal: Double read FNominal write FNominal; property SettlementARAP: TSettlementARAP read FSettlementARAP write FSettlementARAP; end; implementation destructor TSettlementARAP.Destroy; begin inherited; FreeAndNil(FSupplier); SettlementARAPItemAPs.Clear; SettlementARAPItemARs.Clear; FreeAndNil(FSettlementARAPItemAPs); FreeAndNil(FSettlementARAPItemARs); end; function TSettlementARAP.GetSettlementARAPItemAPs: TObjectList<TSettlementARAPItemAP>; begin if FSettlementARAPItemAPs = nil then FSettlementARAPItemAPs := TObjectList<TSettlementARAPItemAP>.Create(); Result := FSettlementARAPItemAPs; end; function TSettlementARAP.GetSettlementARAPItemARs: TObjectList<TSettlementARAPItemAR>; begin if FSettlementARAPItemARs = nil then FSettlementARAPItemARs := TObjectList<TSettlementARAPItemAR>.Create(); Result := FSettlementARAPItemARs; end; function TSettlementARAPItemAR.GetHeaderField: string; begin Result := 'SettlementARAP'; end; procedure TSettlementARAPItemAR.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.SettlementARAP := TSettlementARAP(AHeaderProperty); end; function TSettlementARAPItemAP.GetHeaderField: string; begin Result := 'SettlementARAP'; end; procedure TSettlementARAPItemAP.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.SettlementARAP := TSettlementARAP(AHeaderProperty); end; end.
unit RemoveUserRequestUnit; interface uses REST.Json.Types, GenericParametersUnit; type TRemoveUserRequest = class(TGenericParameters) private [JSONName('member_id')] FMemberId: integer; public constructor Create(MemberId: integer); reintroduce; end; implementation constructor TRemoveUserRequest.Create(MemberId: integer); begin Inherited Create; FMemberId := MemberId; end; end.
unit ColdStorage; interface uses Warehouses, Kernel, Surfaces, WorkCenterBlock, BackupInterfaces, CacheAgent; type TMetaColdStorage = class(TMetaWarehouse) public constructor Create(anId : string; aCapacities : array of TFluidValue; aFreshFoodMax : TFluidValue; aElabFoodMax : TFluidValue; aLiquorMax : TFluidValue; theOverPrice : TPercent; aBlockClass : CBlock); end; TColdStorage = class(TWarehouse) private fFreshFoodIn : TInputData; fElabFoodIn : TInputData; fLiquorIn : TInputData; fFreshFoodOut : TOutputData; fElabFoodOut : TOutputData; fLiquorOut : TOutputData; end; procedure RegisterBackup; implementation uses ClassStorage, StdFluids; // TMetaColdStorage constructor TMetaColdStorage.Create(anId : string; aCapacities : array of TFluidValue; aFreshFoodMax : TFluidValue; aElabFoodMax : TFluidValue; aLiquorMax : TFluidValue; theOverPrice : TPercent; aBlockClass : CBlock); var Sample : TColdStorage; begin inherited Create(anId, aCapacities, aBlockClass); Sample := nil; // Inputs NewMetaInput( tidGate_FreshFood, tidFluid_FreshFood, aFreshFoodMax, sizeof(Sample.fFreshFoodIn), Sample.Offset(Sample.fFreshFoodIn)); NewMetaInput( tidGate_ElabFood, tidFluid_ElabFood, aElabFoodMax, sizeof(Sample.fElabFoodIn), Sample.Offset(Sample.fElabFoodIn)); NewMetaInput( tidGate_Liquors, tidFluid_Liquors, aLiquorMax, sizeof(Sample.fLiquorIn), Sample.Offset(Sample.fLiquorIn)); // Outputs NewMetaOutput( tidGate_FreshFood, tidFluid_FreshFood, aFreshFoodMax, sizeof(Sample.fFreshFoodOut), Sample.Offset(Sample.fFreshFoodOut)); NewMetaOutput( tidGate_ElabFood, tidFluid_ElabFood, aElabFoodMax, sizeof(Sample.fElabFoodIn), Sample.Offset(Sample.fElabFoodOut)); NewMetaOutput( tidGate_Liquors, tidFluid_Liquors, aLiquorMax, sizeof(Sample.fLiquorIn), Sample.Offset(Sample.fLiquorOut)); // Wares RegisterWare(tidGate_FreshFood, 60, 0, theOverPrice, aFreshFoodMax); RegisterWare(tidGate_ElabFood, 40, 0, theOverPrice, aElabFoodMax); RegisterWare(tidGate_Liquors, 40, 0, theOverPrice, aLiquorMax); end; // Register backup procedure RegisterBackup; begin BackupInterfaces.RegisterClass(TColdStorage); end; end.
unit NtUtils.Tokens; interface uses Winapi.WinNt, Ntapi.ntdef, Ntapi.ntseapi, NtUtils.Exceptions, NtUtils.Security.Sid, NtUtils.Security.Acl; { ------------------------------ Creation ---------------------------------- } // Open a token of a process function NtxOpenProcessToken(out hToken: THandle; hProcess: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; function NtxOpenProcessTokenById(out hToken: THandle; PID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Open a token of a thread function NtxOpenThreadToken(out hToken: THandle; hThread: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; function NtxOpenThreadTokenById(out hToken: THandle; TID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Copy an effective security context of a thread via direct impersonation function NtxOpenEffectiveToken(out hToken: THandle; hThread: THandle; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; EffectiveOnly: Boolean = False): TNtxStatus; function NtxOpenEffectiveTokenById(out hToken: THandle; TID: THandle; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; EffectiveOnly: Boolean = False): TNtxStatus; // Duplicate existing token function NtxDuplicateToken(out hToken: THandle; hExistingToken: THandle; DesiredAccess: TAccessMask; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel = SecurityImpersonation; HandleAttributes: Cardinal = 0; EffectiveOnly: Boolean = False): TNtxStatus; // Open anonymous token function NtxOpenAnonymousToken(out hToken: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Filter a token function NtxFilterToken(out hNewToken: THandle; hToken: THandle; Flags: Cardinal; SidsToDisable: TArray<ISid>; PrivilegesToDelete: TArray<TLuid>; SidsToRestrict: TArray<ISid>): TNtxStatus; // Create a new token from scratch. Requires SeCreateTokenPrivilege. function NtxCreateToken(out hToken: THandle; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel; AuthenticationId: TLuid; ExpirationTime: TLargeInteger; User: TGroup; Groups: TArray<TGroup>; Privileges: TArray<TPrivilege>; Owner: ISid; PrimaryGroup: ISid; DefaultDacl: IAcl; const TokenSource: TTokenSource; DesiredAccess: TAccessMask = TOKEN_ALL_ACCESS; HandleAttributes: Cardinal = 0) : TNtxStatus; { ------------------------- Query / set information ------------------------ } type NtxToken = class // Query fixed-size information class function Query<T>(hToken: THandle; InfoClass: TTokenInformationClass; out Buffer: T): TNtxStatus; static; // Set fixed-size information class function SetInfo<T>(hToken: THandle; InfoClass: TTokenInformationClass; const Buffer: T): TNtxStatus; static; end; // Query variable-length token information without race conditions function NtxQueryBufferToken(hToken: THandle; InfoClass: TTokenInformationClass; out Status: TNtxStatus; ReturnedSize: PCardinal = nil): Pointer; // Set variable-length token information function NtxSetInformationToken(hToken: THandle; InfoClass: TTokenInformationClass; TokenInformation: Pointer; TokenInformationLength: Cardinal): TNtxStatus; // Query an SID (Owner, Primary group, ...) function NtxQuerySidToken(hToken: THandle; InfoClass: TTokenInformationClass; out Sid: ISid): TNtxStatus; // Query SID and attributes (User, ...) function NtxQueryGroupToken(hToken: THandle; InfoClass: TTokenInformationClass; out Group: TGroup): TNtxStatus; // Query groups (Groups, RestrictingSIDs, LogonSIDs, ...) function NtxQueryGroupsToken(hToken: THandle; InfoClass: TTokenInformationClass; out Groups: TArray<TGroup>): TNtxStatus; // Query privileges function NtxQueryPrivilegesToken(hToken: THandle; out Privileges: TArray<TPrivilege>): TNtxStatus; // Query default DACL function NtxQueryDefaultDaclToken(hToken: THandle; out DefaultDacl: IAcl): TNtxStatus; // Set default DACL function NtxSetDefaultDaclToken(hToken: THandle; DefaultDacl: IAcl): TNtxStatus; // Query token flags function NtxQueryFlagsToken(hToken: THandle; out Flags: Cardinal): TNtxStatus; // Query integrity level of a token function NtxQueryIntegrityToken(hToken: THandle; out IntegrityLevel: Cardinal): TNtxStatus; // Set integrity level of a token function NtxSetIntegrityToken(hToken: THandle; IntegrityLevel: Cardinal): TNtxStatus; { --------------------------- Other operations ---------------------------- } // Adjust privileges function NtxAdjustPrivileges(hToken: THandle; Privileges: TArray<TLuid>; NewAttribute: Cardinal): TNtxStatus; function NtxAdjustPrivilege(hToken: THandle; Privilege: TLuid; NewAttribute: Cardinal): TNtxStatus; // Adjust groups function NtxAdjustGroups(hToken: THandle; Sids: TArray<ISid>; NewAttribute: Cardinal; ResetToDefault: Boolean): TNtxStatus; implementation uses Ntapi.ntstatus, Ntapi.ntobapi, Ntapi.ntpsapi, NtUtils.Objects, NtUtils.Tokens.Misc, NtUtils.Processes, NtUtils.Tokens.Impersonate, NtUtils.Threads, NtUtils.Access.Expected; { Creation } function NtxOpenProcessToken(out hToken: THandle; hProcess: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; begin Result.Location := 'NtOpenProcessTokenEx'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @TokenAccessType; Result.LastCall.Expects(PROCESS_QUERY_LIMITED_INFORMATION, @ProcessAccessType); Result.Status := NtOpenProcessTokenEx(hProcess, DesiredAccess, HandleAttributes, hToken); end; function NtxOpenProcessTokenById(out hToken: THandle; PID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hProcess: THandle; begin Result := NtxOpenProcess(hProcess, PID, PROCESS_QUERY_LIMITED_INFORMATION); if not Result.IsSuccess then Exit; Result := NtxOpenProcessToken(hToken, hProcess, DesiredAccess, HandleAttributes); NtxSafeClose(hProcess); end; function NtxOpenThreadToken(out hToken: THandle; hThread: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; begin Result.Location := 'NtOpenThreadTokenEx'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @TokenAccessType; Result.LastCall.Expects(THREAD_QUERY_LIMITED_INFORMATION, @ThreadAccessType); // When opening other thread's token use our effective (thread) security // context. When reading a token from the current thread use the process' // security context. Result.Status := NtOpenThreadTokenEx(hThread, DesiredAccess, (hThread = NtCurrentThread), HandleAttributes, hToken); end; function NtxOpenThreadTokenById(out hToken: THandle; TID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hThread: THandle; begin Result := NtxOpenThread(hThread, TID, THREAD_QUERY_LIMITED_INFORMATION); if not Result.IsSuccess then Exit; Result := NtxOpenThreadToken(hToken, hThread, DesiredAccess, HandleAttributes); NtxSafeClose(hThread); end; function NtxOpenEffectiveToken(out hToken: THandle; hThread: THandle; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; EffectiveOnly: Boolean): TNtxStatus; var hOldToken: THandle; QoS: TSecurityQualityOfService; begin // Backup our impersonation token hOldToken := NtxBackupImpersonation(NtCurrentThread); InitializaQoS(QoS, ImpersonationLevel, EffectiveOnly); // Direct impersonation makes the server thread to impersonate the effective // security context of the client thread. We use our thead as a server and the // target thread as a client, and then read the token from our thread. Result.Location := 'NtImpersonateThread'; Result.LastCall.Expects(THREAD_IMPERSONATE, @ThreadAccessType); // Server Result.LastCall.Expects(THREAD_DIRECT_IMPERSONATION, @ThreadAccessType); // Client // No access checks are performed on the client's token, we obtain a copy Result.Status := NtImpersonateThread(NtCurrentThread, hThread, QoS); if not Result.IsSuccess then Exit; // Read it back from our thread Result := NtxOpenThreadToken(hToken, NtCurrentThread, DesiredAccess, HandleAttributes); // Restore our previous impersonation NtxRestoreImpersonation(NtCurrentThread, hOldToken); if hOldToken <> 0 then NtxSafeClose(hOldToken); end; function NtxOpenEffectiveTokenById(out hToken: THandle; TID: THandle; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; EffectiveOnly: Boolean): TNtxStatus; var hThread: THandle; begin Result := NtxOpenThread(hThread, TID, THREAD_DIRECT_IMPERSONATION); if not Result.IsSuccess then Exit; Result := NtxOpenEffectiveToken(hToken, hThread, ImpersonationLevel, DesiredAccess, HandleAttributes, EffectiveOnly); NtxSafeClose(hThread); end; function NtxDuplicateToken(out hToken: THandle; hExistingToken: THandle; DesiredAccess: TAccessMask; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel; HandleAttributes: Cardinal; EffectiveOnly: Boolean): TNtxStatus; var ObjAttr: TObjectAttributes; QoS: TSecurityQualityOfService; begin InitializaQoS(QoS, ImpersonationLevel, EffectiveOnly); InitializeObjectAttributes(ObjAttr, nil, HandleAttributes, 0, @QoS); Result.Location := 'NtDuplicateToken'; Result.LastCall.Expects(TOKEN_DUPLICATE, @TokenAccessType); Result.Status := NtDuplicateToken(hExistingToken, DesiredAccess, @ObjAttr, EffectiveOnly, TokenType, hToken); end; function NtxOpenAnonymousToken(out hToken: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hOldToken: THandle; begin // Backup our impersonation context hOldToken := NtxBackupImpersonation(NtCurrentThread); // Set our thread to impersonate anonymous token Result.Location := 'NtImpersonateAnonymousToken'; Result.LastCall.Expects(THREAD_IMPERSONATE, @ThreadAccessType); Result.Status := NtImpersonateAnonymousToken(NtCurrentThread); // Read the token from the thread if Result.IsSuccess then Result := NtxOpenThreadToken(hToken, NtCurrentThread, DesiredAccess, HandleAttributes); // Restore previous impersonation NtxRestoreImpersonation(NtCurrentThread, hOldToken); if hOldToken <> 0 then NtxSafeClose(hOldToken); end; function NtxFilterToken(out hNewToken: THandle; hToken: THandle; Flags: Cardinal; SidsToDisable: TArray<ISid>; PrivilegesToDelete: TArray<TLuid>; SidsToRestrict: TArray<ISid>): TNtxStatus; var DisableSids, RestrictSids: PTokenGroups; DeletePrivileges: PTokenPrivileges; begin DisableSids := NtxpAllocGroups(SidsToDisable, 0); RestrictSids := NtxpAllocGroups(SidsToRestrict, 0); DeletePrivileges := NtxpAllocPrivileges(PrivilegesToDelete, 0); Result.Location := 'NtFilterToken'; Result.LastCall.Expects(TOKEN_DUPLICATE, @TokenAccessType); Result.Status := NtFilterToken(hToken, Flags, DisableSids, DeletePrivileges, RestrictSids, hNewToken); FreeMem(DisableSids); FreeMem(RestrictSids); FreeMem(DeletePrivileges); end; function NtxCreateToken(out hToken: THandle; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel; AuthenticationId: TLuid; ExpirationTime: TLargeInteger; User: TGroup; Groups: TArray<TGroup>; Privileges: TArray<TPrivilege>; Owner: ISid; PrimaryGroup: ISid; DefaultDacl: IAcl; const TokenSource: TTokenSource; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var QoS: TSecurityQualityOfService; ObjAttr: TObjectAttributes; TokenUser: TSidAndAttributes; TokenGroups: PTokenGroups; TokenPrivileges: PTokenPrivileges; TokenOwner: TTokenOwner; pTokenOwnerRef: PTokenOwner; TokenPrimaryGroup: TTokenPrimaryGroup; TokenDefaultDacl: TTokenDefaultDacl; pTokenDefaultDaclRef: PTokenDefaultDacl; begin InitializaQoS(QoS, ImpersonationLevel); InitializeObjectAttributes(ObjAttr, nil, HandleAttributes, 0, @QoS); // Prepare user Assert(Assigned(User.SecurityIdentifier)); TokenUser.Sid := User.SecurityIdentifier.Sid; TokenUser.Attributes := User.Attributes; // Prepare groups and privileges TokenGroups := NtxpAllocGroups2(Groups); TokenPrivileges:= NtxpAllocPrivileges2(Privileges); // Owner is optional if Assigned(Owner) then begin TokenOwner.Owner := Owner.Sid; pTokenOwnerRef := @TokenOwner; end else pTokenOwnerRef := nil; // Prepare primary group Assert(Assigned(PrimaryGroup)); TokenPrimaryGroup.PrimaryGroup := PrimaryGroup.Sid; // Default Dacl is optional if Assigned(DefaultDacl) then begin TokenDefaultDacl.DefaultDacl := DefaultDacl.Acl; pTokenDefaultDaclRef := @TokenDefaultDacl; end else pTokenDefaultDaclRef := nil; Result.Location := 'NtCreateToken'; Result.LastCall.ExpectedPrivilege := SE_CREATE_TOKEN_PRIVILEGE; Result.Status := NtCreateToken(hToken, DesiredAccess, @ObjAttr, TokenType, AuthenticationId, ExpirationTime, TokenUser, TokenGroups, TokenPrivileges, pTokenOwnerRef, TokenPrimaryGroup, pTokenDefaultDaclRef, TokenSource); // Clean up FreeMem(TokenGroups); FreeMem(TokenPrivileges); end; { Query / set operations } class function NtxToken.Query<T>(hToken: THandle; InfoClass: TTokenInformationClass; out Buffer: T): TNtxStatus; var ReturnedBytes: Cardinal; begin Result.Location := 'NtQueryInformationToken'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TTokenInformationClass); RtlxComputeTokenQueryAccess(Result.LastCall, InfoClass); Result.Status := NtQueryInformationToken(hToken, InfoClass, @Buffer, SizeOf(Buffer), ReturnedBytes); end; class function NtxToken.SetInfo<T>(hToken: THandle; InfoClass: TTokenInformationClass; const Buffer: T): TNtxStatus; begin Result := NtxSetInformationToken(hToken, InfoClass, @Buffer, SizeOf(Buffer)); end; function NtxQueryBufferToken(hToken: THandle; InfoClass: TTokenInformationClass; out Status: TNtxStatus; ReturnedSize: PCardinal): Pointer; var BufferSize, Required: Cardinal; begin Status.Location := 'NtQueryInformationToken'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TTokenInformationClass); RtlxComputeTokenQueryAccess(Status.LastCall, InfoClass); BufferSize := 0; repeat Result := AllocMem(BufferSize); Required := 0; Status.Status := NtQueryInformationToken(hToken, InfoClass, Result, BufferSize, Required); if not Status.IsSuccess then begin FreeMem(Result); Result := nil; end; until not NtxExpandBuffer(Status, BufferSize, Required); if Status.IsSuccess and Assigned(ReturnedSize) then ReturnedSize^ := BufferSize; end; function NtxSetInformationToken(hToken: THandle; InfoClass: TTokenInformationClass; TokenInformation: Pointer; TokenInformationLength: Cardinal): TNtxStatus; begin Result.Location := 'NtSetInformationToken'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TTokenInformationClass); RtlxComputeTokenSetAccess(Result.LastCall, InfoClass); Result.Status := NtSetInformationToken(hToken, InfoClass, TokenInformation, TokenInformationLength); end; function NtxQuerySidToken(hToken: THandle; InfoClass: TTokenInformationClass; out Sid: ISid): TNtxStatus; var Buffer: PTokenOwner; // aka PTokenPrimaryGroup and ^PSid begin Buffer := NtxQueryBufferToken(hToken, InfoClass, Result); if not Result.IsSuccess then Exit; try Sid := TSid.CreateCopy(Buffer.Owner); finally FreeMem(Buffer); end; end; function NtxQueryGroupToken(hToken: THandle; InfoClass: TTokenInformationClass; out Group: TGroup): TNtxStatus; var Buffer: PSidAndAttributes; // aka PTokenUser begin Buffer := NtxQueryBufferToken(hToken, InfoClass, Result); if not Result.IsSuccess then Exit; try Group.SecurityIdentifier := TSid.CreateCopy(Buffer.Sid); Group.Attributes := Buffer.Attributes; finally FreeMem(Buffer); end; end; function NtxQueryGroupsToken(hToken: THandle; InfoClass: TTokenInformationClass; out Groups: TArray<TGroup>): TNtxStatus; var Buffer: PTokenGroups; i: Integer; begin Buffer := NtxQueryBufferToken(hToken, InfoClass, Result); if not Result.IsSuccess then Exit; try SetLength(Groups, Buffer.GroupCount); for i := 0 to High(Groups) do begin Groups[i].SecurityIdentifier := TSid.CreateCopy(Buffer.Groups{$R-}[i]{$R+}.Sid); Groups[i].Attributes := Buffer.Groups{$R-}[i]{$R+}.Attributes; end; finally FreeMem(Buffer); end; end; function NtxQueryPrivilegesToken(hToken: THandle; out Privileges: TArray<TPrivilege>): TNtxStatus; var Buffer: PTokenPrivileges; i: Integer; begin Buffer := NtxQueryBufferToken(hToken, TokenPrivileges, Result); if not Result.IsSuccess then Exit; SetLength(Privileges, Buffer.PrivilegeCount); for i := 0 to High(Privileges) do Privileges[i] := Buffer.Privileges{$R-}[i]{$R+}; FreeMem(Buffer); end; function NtxQueryDefaultDaclToken(hToken: THandle; out DefaultDacl: IAcl): TNtxStatus; var Buffer: PTokenDefaultDacl; begin Buffer := NtxQueryBufferToken(hToken, TokenDefaultDacl, Result); if not Result.IsSuccess then Exit; try if Assigned(Buffer.DefaultDacl) then DefaultDacl := TAcl.CreateCopy(Buffer.DefaultDacl) else DefaultDacl := nil; finally FreeMem(Buffer); end; end; function NtxSetDefaultDaclToken(hToken: THandle; DefaultDacl: IAcl): TNtxStatus; var Dacl: TTokenDefaultDacl; begin Dacl.DefaultDacl := DefaultDacl.Acl; Result := NtxToken.SetInfo<TTokenDefaultDacl>(hToken, TokenDefaultDacl, Dacl); end; function NtxQueryFlagsToken(hToken: THandle; out Flags: Cardinal): TNtxStatus; var Buffer: PTokenAccessInformation; begin Buffer := NtxQueryBufferToken(hToken, TokenAccessInformation, Result); // TODO: Return more access information if Result.IsSuccess then begin Flags := Buffer.Flags; FreeMem(Buffer); end; end; function NtxQueryIntegrityToken(hToken: THandle; out IntegrityLevel: Cardinal): TNtxStatus; var Integrity: TGroup; begin Result := NtxQueryGroupToken(hToken, TokenIntegrityLevel, Integrity); if not Result.IsSuccess then Exit; // Integrity level is the last sub-authority (RID) of the integrity SID with Integrity.SecurityIdentifier do if SubAuthorities > 0 then IntegrityLevel := Rid else IntegrityLevel := SECURITY_MANDATORY_UNTRUSTED_RID end; function NtxSetIntegrityToken(hToken: THandle; IntegrityLevel: Cardinal): TNtxStatus; var LabelSid: ISid; MandatoryLabel: TSidAndAttributes; begin // Prepare SID for integrity level with 1 sub authority: S-1-16-X. LabelSid := TSid.CreateNew(SECURITY_MANDATORY_LABEL_AUTHORITY, 1, IntegrityLevel); MandatoryLabel.Sid := LabelSid.Sid; MandatoryLabel.Attributes := SE_GROUP_INTEGRITY_ENABLED; Result := NtxToken.SetInfo<TSidAndAttributes>(hToken, TokenIntegrityLevel, MandatoryLabel); end; { Other opeations } function NtxAdjustPrivileges(hToken: THandle; Privileges: TArray<TLuid>; NewAttribute: Cardinal): TNtxStatus; var Buffer: PTokenPrivileges; begin Buffer := NtxpAllocPrivileges(Privileges, NewAttribute); Result.Location := 'NtAdjustPrivilegesToken'; Result.LastCall.Expects(TOKEN_ADJUST_PRIVILEGES, @TokenAccessType); Result.Status := NtAdjustPrivilegesToken(hToken, False, Buffer, 0, nil, nil); FreeMem(Buffer); end; function NtxAdjustPrivilege(hToken: THandle; Privilege: TLuid; NewAttribute: Cardinal): TNtxStatus; var Privileges: TArray<TLuid>; begin SetLength(Privileges, 1); Privileges[0] := Privilege; Result := NtxAdjustPrivileges(hToken, Privileges, NewAttribute); end; function NtxAdjustGroups(hToken: THandle; Sids: TArray<ISid>; NewAttribute: Cardinal; ResetToDefault: Boolean): TNtxStatus; var Buffer: PTokenGroups; begin Buffer := NtxpAllocGroups(Sids, NewAttribute); Result.Location := 'NtAdjustGroupsToken'; Result.LastCall.Expects(TOKEN_ADJUST_GROUPS, @TokenAccessType); Result.Status := NtAdjustGroupsToken(hToken, ResetToDefault, Buffer, 0, nil, nil); FreeMem(Buffer); end; end.
unit evCellsWidthCorrecter; {* Инструмент для выравнивания границ ячеек. } // Модуль: "w:\common\components\gui\Garant\Everest\evCellsWidthCorrecter.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevCellsWidthCorrecter" MUID: (4F2B767D015E) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evRowAndTableTypeSupport , evCellsOffsetsPairList , evCellsOffsetsPair , l3LongintList , evEditorInterfaces , evCellWidthCorrecterSpy , evCellsOffsetsList , nevBase , l3Interfaces , evEditorInterfacesTypes ; type TevFoundSuitebleType = ( ev_fstNone , ev_fstTemplate , ev_fstInList );//TevFoundSuitebleType TevCellsWidthCorrecter = class(TevRowAndTableTypeSupport) {* Инструмент для выравнивания границ ячеек. } private f_CellsOffsetPairList: TevCellsOffsetsPairList; {* Список с парами значений выравненных и невыравненных. } f_Index: Integer; {* Индекс для прохода с установкой ширины ячеек. } f_PrevRowWidth: Integer; {* Закешированная ширина предыдущей строки - используется при выравнивании строк. } f_PriorityTemplateRow: TevCellsOffsetsPair; {* Текущий шаблон для выравнивания. Используется если при анализе таблицы был найден загооловок (в начале таблицы закончились объединенные ячеки или была найдена строка с номерами). После этого такой шаблон обновляется ближайшим подходящим. } f_RowsWithSingleCell: Tl3LongintList; {* Список номеров строк с одиночными или "притворящимися" такими ячейками. } f_Row: IedRow; {* Указатель на текущую строку. } f_LogSpy: TevCellWidthCorrecterSpy; {* Сохраняльщик результатов выравнивания для тестов. } f_WasNotEqualRows: Boolean; {* Флаг - были после выранивания неодинаковые строки. } f_HeadAlignment: Boolean; {* Выравнивание заголовка таблицы. Выставляется при повторном выравнивании заголовка на основе выравненных перед этим строк. } f_ForegnTemplates: TevCellsOffsetsList; {* Список для выравнивания "из вне" - применяется при копировании/вставке вершин. } f_NumbericData: TevCellsOffsetsPair; private procedure ApplyChanges(const anOp: InevOp; const anIterator: IedBackCellsIterator; aCellCount: Integer); function TryToCopyFromSuitableList: Boolean; function GetTemplate: TevCellsOffsetsPair; function GetRowsWithSingleCell: Tl3LongintList; function AddevCellsOffsetsPair(const aCellIterator: IedCellsIterator): TevCellsOffsetsPair; function GetSuitableList(out aFoundType: TevFoundSuitebleType): TevCellsOffsetsPair; procedure CopyFromSuitableList(const aList: TevCellsOffsetsPair; aFoundType: TevFoundSuitebleType); function GetIterator: IedCellsIterator; function CheckPreparrePriorityTemplate(out aFoundType: TevFoundSuitebleType): TevCellsOffsetsPair; {* Инициализация шаблона строк таблицы с проверокой. Шаблон строк может потребовать дополнительного выравнивани или просто не подходить для выравнивания. } function FoundPriorityTemplate: Boolean; procedure AlighHeader; {* Повторное выравнивание заголовка. } function TryToCopyForeignList: Boolean; function FindSuitableListInPrevious(const anIterator: IedCellsIterator; out aFoundType: TevFoundSuitebleType): TevCellsOffsetsPair; procedure SaveCellsTypeList(const aCellIterator: IedCellsIterator; const aCellOffsetPair: TevCellsOffsetsPair); protected function GetPrevRowType: TedRowType; override; function GetCellsCountInPreviousRow: Integer; override; {* Возвращает число ячеек в последней выравненной строке } procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aForegnTemplates: TevCellsOffsetsList); reintroduce; procedure CheckRowsWithSingleCell; procedure CheckLog; class function DoCorrection(const aTable: IedTable; const aForegnTemplates: TevCellsOffsetsList; aSeparateOp: Boolean; const aProgress: Il3Progress = nil): Boolean; procedure CorrectCells(const aRow: IedRow); procedure ApplyChanges2Row(const anOp: InevOp; const aRow: IedRow; aFirst: Boolean); end;//TevCellsWidthCorrecter implementation uses l3ImplUses {$If Defined(k2ForEditor)} , evTableCellUtils {$IfEnd} // Defined(k2ForEditor) , l3Base , l3Types , afwFacade , k2Op , evOp , evMsgCode , evCellsCharOffsets , edCellTypesList //#UC START# *4F2B767D015Eimpl_uses* //#UC END# *4F2B767D015Eimpl_uses* ; procedure TevCellsWidthCorrecter.ApplyChanges(const anOp: InevOp; const anIterator: IedBackCellsIterator; aCellCount: Integer); //#UC START# *4F2F734203C7_4F2B767D015E_var* var l_WidthList : TevCellsOffsetsPair; procedure lp_SaveLogRowData; begin if f_LogSpy <> nil then f_LogSpy.SaveRowData(f_Index, l_WidthList.GetRowWidth(False), l_WidthList.GetRowWidth(True)); end; var l_Width : Integer; l_CellIndex: Integer; l_Cell : IedCell; l_CellData : TevCellLogData; procedure lp_SaveCellData; begin if f_LogSpy <> nil then begin with l_CellData do begin l_CellData.rCellID := l_CellIndex; l_CellData.rCellText := l_Cell.GetFirstLineText; l_CellData.rOldWidth := l_Cell.Width; l_CellData.rNewWidth := l_Width; end; // with l_CellData do f_LogSpy.SaveAlignmentData(l_CellData); end; // if f_LogSpy <> nil then end; var //l_Delta : Integer; l_PrevList : TevCellsOffsetsPair; l_DeletingCell : IedCell; //#UC END# *4F2F734203C7_4F2B767D015E_var* begin //#UC START# *4F2F734203C7_4F2B767D015E_impl* l_Cell := anIterator.Last(False); l_WidthList := f_CellsOffsetPairList[f_Index]; if f_Index > 0 then l_PrevList := f_CellsOffsetPairList[f_Index - 1] else l_PrevList := nil; l_Width := l_WidthList.LastNewWidth; l_CellIndex := aCellCount - 1; //l_Delta := 0; while (l_Cell <> nil) do begin (*if l_WidthList.CellsType[l_CellIndex] = ed_NeedDelete then begin l_DeletingCell := l_Cell; Inc(l_Delta, l_Width); l_Cell := anIterator.Prev; l_DeletingCell.Delete(anOp, True); end // if l_WidthList.CellsType[[l_CellIndex] = ed_NeedDelete then else*) begin lp_SaveCellData; if l_Width > 0 then begin //Inc(l_Width, l_Delta); l_Cell.UpdateWidthAndCheckHead(l_Width); end; // if l_Width > 0 then //l_Delta := 0; l_Cell := anIterator.Prev; end; Dec(l_CellIndex); l_Width := l_WidthList.PrevNewWidth; end; // while (l_Cell <> nil) do lp_SaveLogRowData; //#UC END# *4F2F734203C7_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.ApplyChanges constructor TevCellsWidthCorrecter.Create(const aForegnTemplates: TevCellsOffsetsList); //#UC START# *4F2F73CD01D1_4F2B767D015E_var* //#UC END# *4F2F73CD01D1_4F2B767D015E_var* begin //#UC START# *4F2F73CD01D1_4F2B767D015E_impl* inherited Create; f_CellsOffsetPairList := TevCellsOffsetsPairList.Create; f_PrevRowWidth := 0; f_WasNotEqualRows := False; f_HeadAlignment := False; f_ForegnTemplates := aForegnTemplates; //#UC END# *4F2F73CD01D1_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.Create function TevCellsWidthCorrecter.TryToCopyFromSuitableList: Boolean; //#UC START# *4FA504FF0217_4F2B767D015E_var* var l_FindList : TevCellsOffsetsPair; l_FoundType : TevFoundSuitebleType; l_WasTemlate : Boolean; //#UC END# *4FA504FF0217_4F2B767D015E_var* begin //#UC START# *4FA504FF0217_4F2B767D015E_impl* Result := False; l_WasTemlate := FoundPriorityTemplate; if f_CellsOffsetPairList.Count = 0 then Exit; l_FindList := GetSuitableList(l_FoundType); if l_FindList <> nil then begin Result := True; CopyFromSuitableList(l_FindList, l_FoundType); if CurrentRowType = ed_rtNumericCels then f_NumbericData := f_CellsOffsetPairList.Last; end; // if l_FindList <> nil then if not l_WasTemlate and FoundPriorityTemplate and f_WasNotEqualRows then // Значит - пора выравнивать предыдущие... AlighHeader; //#UC END# *4FA504FF0217_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.TryToCopyFromSuitableList function TevCellsWidthCorrecter.GetTemplate: TevCellsOffsetsPair; //#UC START# *4FA5095F01AE_4F2B767D015E_var* //#UC END# *4FA5095F01AE_4F2B767D015E_var* begin //#UC START# *4FA5095F01AE_4F2B767D015E_impl* if FoundPriorityTemplate then Result := f_PriorityTemplateRow else Result := f_CellsOffsetPairList.PenultimateItem; //#UC END# *4FA5095F01AE_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.GetTemplate function TevCellsWidthCorrecter.GetRowsWithSingleCell: Tl3LongintList; //#UC START# *4FA5209302CC_4F2B767D015E_var* //#UC END# *4FA5209302CC_4F2B767D015E_var* begin //#UC START# *4FA5209302CC_4F2B767D015E_impl* if f_RowsWithSingleCell = nil then f_RowsWithSingleCell := Tl3LongintList.Create; Result := f_RowsWithSingleCell; //#UC END# *4FA5209302CC_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.GetRowsWithSingleCell function TevCellsWidthCorrecter.AddevCellsOffsetsPair(const aCellIterator: IedCellsIterator): TevCellsOffsetsPair; //#UC START# *4FA52C7A027C_4F2B767D015E_var* var l_Index: Integer; //#UC END# *4FA52C7A027C_4F2B767D015E_var* begin //#UC START# *4FA52C7A027C_4F2B767D015E_impl* if f_HeadAlignment then begin Result := f_CellsOffsetPairList[f_Index]; Result.Clear; end // if f_HeadAlignment then else begin Result := TevCellsOffsetsPair.Create; l_Index := f_CellsOffsetPairList.Add(Result); SaveRowType(Result); SaveCellsTypeList(GetIterator, Result); if CurrentRowType in edSingleCell then GetRowsWithSingleCell.Add(l_Index); end; //#UC END# *4FA52C7A027C_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.AddevCellsOffsetsPair procedure TevCellsWidthCorrecter.CheckRowsWithSingleCell; //#UC START# *4FA530670256_4F2B767D015E_var* function lp_CheckItem(aData: PInteger; anIndex: Integer): Boolean; var l_Index : Integer; l_PrevWidth : TevCellsOffsetsPair; begin l_Index := aData^; if l_Index > 0 then begin l_PrevWidth := f_CellsOffsetPairList[l_Index - 1]; f_CellsOffsetPairList[l_Index].AlignByPrevious(l_PrevWidth); end; // if l_PrevIndex > 0 then Result := True; end; //#UC END# *4FA530670256_4F2B767D015E_var* begin //#UC START# *4FA530670256_4F2B767D015E_impl* if f_RowsWithSingleCell <> nil then f_RowsWithSingleCell.IterateAllF(l3L2IA(@lp_CheckItem)); //#UC END# *4FA530670256_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.CheckRowsWithSingleCell function TevCellsWidthCorrecter.GetSuitableList(out aFoundType: TevFoundSuitebleType): TevCellsOffsetsPair; //#UC START# *4FC5D31C000E_4F2B767D015E_var* var l_CellIterator: IedCellsIterator; //#UC END# *4FC5D31C000E_4F2B767D015E_var* begin //#UC START# *4FC5D31C000E_4F2B767D015E_impl* aFoundType := ev_fstNone; Result := CheckPreparrePriorityTemplate(aFoundType); if Result = nil then begin l_CellIterator := GetIterator; try Result := FindSuitableListInPrevious(l_CellIterator, aFoundType); if FoundPriorityTemplate and (f_PriorityTemplateRow = Result) then aFoundType := ev_fstTemplate; finally l_CellIterator := nil; end; end; // if Result = nil then //#UC END# *4FC5D31C000E_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.GetSuitableList procedure TevCellsWidthCorrecter.CopyFromSuitableList(const aList: TevCellsOffsetsPair; aFoundType: TevFoundSuitebleType); //#UC START# *4FC5D4D2033A_4F2B767D015E_var* var l_WidthList : TevCellsOffsetsPair; l_CellIterator: IedCellsIterator; //#UC END# *4FC5D4D2033A_4F2B767D015E_var* begin //#UC START# *4FC5D4D2033A_4F2B767D015E_impl* l_CellIterator := GetIterator; l_WidthList := AddevCellsOffsetsPair(l_CellIterator); try l_WidthList.CopyData(aList, l_CellIterator); if aFoundType = ev_fstTemplate then // Если нашли такую, то используем именно её f_PriorityTemplateRow := f_CellsOffsetPairList.Last; finally if not f_HeadAlignment then l3Free(l_WidthList); l_CellIterator := nil; end; //#UC END# *4FC5D4D2033A_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.CopyFromSuitableList function TevCellsWidthCorrecter.GetIterator: IedCellsIterator; //#UC START# *4FC5EA5B0165_4F2B767D015E_var* //#UC END# *4FC5EA5B0165_4F2B767D015E_var* begin //#UC START# *4FC5EA5B0165_4F2B767D015E_impl* if f_Row = nil then Result := nil else Result := f_Row.CellsIterator; //#UC END# *4FC5EA5B0165_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.GetIterator function TevCellsWidthCorrecter.CheckPreparrePriorityTemplate(out aFoundType: TevFoundSuitebleType): TevCellsOffsetsPair; {* Инициализация шаблона строк таблицы с проверокой. Шаблон строк может потребовать дополнительного выравнивани или просто не подходить для выравнивания. } //#UC START# *4FC5FBF401A8_4F2B767D015E_var* //#UC END# *4FC5FBF401A8_4F2B767D015E_var* begin //#UC START# *4FC5FBF401A8_4F2B767D015E_impl* Result := nil; aFoundType := ev_fstNone; if not FoundPriorityTemplate then begin if CurrentRowType = ed_rtNumericCels then begin Result := f_CellsOffsetPairList.Last; aFoundType := ev_fstTemplate; // Строку с номерами ячеек лучше выровнять по предыдущей end // if f_CurrentRowType = ed_NumericCels then else if TableStyle <> ed_tsForm then begin if (CurrentRowType in edSingleCell) and (GetPrevRowType in edAllowCellInHeadRow) then begin f_PriorityTemplateRow := f_CellsOffsetPairList.Last; aFoundType := ev_fstInList; end // if (CurrentRowType in edSingleCell) and (GetPrevRowType in edAllowCellInHeadRow) then else if (GetPrevRowType = ed_rtHasMergedCell) and (CurrentRowType = ed_rtSimpleCells) then begin f_PriorityTemplateRow := f_CellsOffsetPairList.Last; aFoundType := ev_fstTemplate; end; // if (GetPrevRowType = ed_HasMergedCell) and (f_CurrentRowType = ed_SimpleCells) then end; // if f_TableStyle <> ev_tsForm then end; //#UC END# *4FC5FBF401A8_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.CheckPreparrePriorityTemplate procedure TevCellsWidthCorrecter.CheckLog; //#UC START# *4FC72703007E_4F2B767D015E_var* //#UC END# *4FC72703007E_4F2B767D015E_var* begin //#UC START# *4FC72703007E_4F2B767D015E_impl* if TevCellWidthCorrecterSpy.Exists and TevCellWidthCorrecterSpy.Instance.NeedLog then f_LogSpy := TevCellWidthCorrecterSpy.Instance else f_LogSpy := nil; //#UC END# *4FC72703007E_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.CheckLog function TevCellsWidthCorrecter.FoundPriorityTemplate: Boolean; //#UC START# *4FC8655F01B4_4F2B767D015E_var* //#UC END# *4FC8655F01B4_4F2B767D015E_var* begin //#UC START# *4FC8655F01B4_4F2B767D015E_impl* Result := f_PriorityTemplateRow <> nil; //#UC END# *4FC8655F01B4_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.FoundPriorityTemplate procedure TevCellsWidthCorrecter.AlighHeader; {* Повторное выравнивание заголовка. } //#UC START# *4FC86F1E023D_4F2B767D015E_var* var l_OldRow : IedRow; l_PrevWidth : Integer; procedure lp_PushOldParams; begin l_PrevWidth := f_PrevRowWidth; l_OldRow := f_Row; end; procedure lp_PopOldParams; begin f_PrevRowWidth := l_PrevWidth; f_Row := l_OldRow; end; var l_Row : IedRow; l_StartIndex : Integer; l_RecalcCount : Integer; l_RowIterator : IedRowsIterator; procedure lp_InitStartIndex; var i : Integer; begin // Анализируем случай, когда таблица сложная - фактически две или более таблиц в одной... l_StartIndex := l_RecalcCount; for i := l_RecalcCount downto 0 do if (f_CellsOffsetPairList[i].RowType in [ed_rtNumericCels, ed_rtSingleCell, ed_rtPsevdoSingleCells, ev_rtFormCells, ed_rtSimpleEmptyCells]) then Break; l_StartIndex := i + 1; if l_StartIndex > 0 then for i := 0 to l_StartIndex - 1 do l_Row := l_RowIterator.Next; end; var l_Index: Integer; //#UC END# *4FC86F1E023D_4F2B767D015E_var* begin //#UC START# *4FC86F1E023D_4F2B767D015E_impl* l_RecalcCount := f_CellsOffsetPairList.Count - 2; l_RowIterator := f_Row.Table.RowsIterator; l_Row := l_RowIterator.First; f_HeadAlignment := True; lp_PushOldParams; try lp_InitStartIndex; for l_Index := l_StartIndex to l_RecalcCount do begin f_Index := l_Index; CorrectCells(l_Row); l_Row := l_RowIterator.Next; end; // for l_Index := 0 to l_RecalcCount do finally lp_PopOldParams; l_RowIterator := nil; f_HeadAlignment := False; end; //#UC END# *4FC86F1E023D_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.AlighHeader class function TevCellsWidthCorrecter.DoCorrection(const aTable: IedTable; const aForegnTemplates: TevCellsOffsetsList; aSeparateOp: Boolean; const aProgress: Il3Progress = nil): Boolean; //#UC START# *50923EED0279_4F2B767D015E_var* var l_Index : Integer; l_Correct : Boolean; l_RowCount : Integer; procedure lp_IniProgress; begin if aProgress <> nil then begin l_RowCount := aTable.RowCount; aProgress.Start(l_RowCount * 2, l3CStr('Выравнивание границ ячеек.')); end; // if aProgress <> nil then end; procedure lp_CheckProgress; begin if aProgress <> nil then begin aProgress.Progress(l_RowCount * Ord(l_Correct) + l_Index); if (l_Index > 0) then if l_RowCount < 100 then begin if (l_Index mod 20) = 0 then afw.ProcessMessages; end // if l_RowCount < 100 then else if (l_Index mod 100) = 0 then afw.ProcessMessages; end; // if aProgress <> nil then end; procedure lp_DeinitProgress; begin if aProgress <> nil then aProgress.Finish; end; var l_Op : InevOp; l_Processor : InevProcessor; procedure lp_Hack; begin // V - хакерский трюк для потабличной откатки. if aSeparateOp then begin l_Op := l_Processor.StartOp; try Tk2Op.ToUndo(l_Op); finally l_Op := nil; end; end; // if aSeparateOp then end; var l_Row : IedRow; l_RowsIterator : IedRowsIterator; l_CellCorrector : TevCellsWidthCorrecter; //#UC END# *50923EED0279_4F2B767D015E_var* begin //#UC START# *50923EED0279_4F2B767D015E_impl* Result := False; if (aTable <> nil) then begin l_Processor := aTable.Processor; l_Op := l_Processor.StartOp(ev_msgChangeParam); try l_RowsIterator := aTable.RowsIterator; if (l_RowsIterator <> nil) then begin Result := True; lp_IniProgress; l_CellCorrector := TevCellsWidthCorrecter.Create(aForegnTemplates); try l_CellCorrector.CheckLog; for l_Correct := False to True do begin l_Index := 0; l_Row := l_RowsIterator.First; while (l_Row <> nil) do begin if l_Correct then l_CellCorrector.ApplyChanges2Row(l_Op, l_Row, l_Index = 0) else l_CellCorrector.CorrectCells(l_Row); lp_CheckProgress; l_Row := l_RowsIterator.Next; Inc(l_Index); end;//while (l_Row <> nil) if not l_Correct then l_CellCorrector.CheckRowsWithSingleCell; end; // for l_Correct := True to False do finally lp_DeinitProgress; l3Free(l_CellCorrector); end; end;//l_RowsIterator <> nil finally l_Op := nil; end; lp_Hack; end;//aTable <> nil //#UC END# *50923EED0279_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.DoCorrection function TevCellsWidthCorrecter.TryToCopyForeignList: Boolean; //#UC START# *5092588F021F_4F2B767D015E_var* var l_Found : TevCellsCharOffsets; l_WidthList : TevCellsOffsetsPair; l_CellIterator : IedCellsIterator; //#UC END# *5092588F021F_4F2B767D015E_var* begin //#UC START# *5092588F021F_4F2B767D015E_impl* Result := False; if not f_HeadAlignment and (f_ForegnTemplates <> nil) then begin l_Found := nil; l_CellIterator := GetIterator; if f_ForegnTemplates.Count > 0 then l_Found := f_ForegnTemplates.FindList(l_CellIterator, False); //IterateAllF(l3L2IA(@lp_CheckItem)); if l_Found <> nil then begin l_WidthList := AddevCellsOffsetsPair(l_CellIterator); try l_WidthList.CopyData(l_Found, l_CellIterator); Result := True; finally l3Free(l_WidthList); end; end; // if l_Found <> nil then end; // if f_PriorityTemplateRow = nil then //#UC END# *5092588F021F_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.TryToCopyForeignList function TevCellsWidthCorrecter.FindSuitableListInPrevious(const anIterator: IedCellsIterator; out aFoundType: TevFoundSuitebleType): TevCellsOffsetsPair; //#UC START# *4F2FA52C00EC_4F2B767D015E_var* function lp_CheckItem(aData: PObject; anIndex: Integer): Boolean; begin Result := not TevCellsOffsetsPair(aData^).EqualCells(anIterator); if not Result then FindSuitableListInPrevious := TevCellsOffsetsPair(aData^); end; var l_CellIteraor: IedCellsIterator; //#UC END# *4F2FA52C00EC_4F2B767D015E_var* begin //#UC START# *4F2FA52C00EC_4F2B767D015E_impl* Result := nil; if FoundPriorityTemplate and f_PriorityTemplateRow.EqualCells(anIterator) then begin Result := f_PriorityTemplateRow; aFoundType := ev_fstTemplate; end // if FoundPriorityTemplate and f_PriorityTemplateRow.EqualCells(anIterator) then else begin if not f_HeadAlignment then begin if f_CellsOffsetPairList.Count > 0 then f_CellsOffsetPairList.IterateBackF(f_CellsOffsetPairList.Hi, f_CellsOffsetPairList.Lo, l3L2IA(@lp_CheckItem)); if Result <> nil then aFoundType := ev_fstInList; end // if f_PriorityTemplateRow = nil then end; //#UC END# *4F2FA52C00EC_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.FindSuitableListInPrevious procedure TevCellsWidthCorrecter.SaveCellsTypeList(const aCellIterator: IedCellsIterator; const aCellOffsetPair: TevCellsOffsetsPair); //#UC START# *528DDD5B0275_4F2B767D015E_var* var l_Cell : IedCell; l_CurrentCellsTypeList : TedCellTypesList; //#UC END# *528DDD5B0275_4F2B767D015E_var* begin //#UC START# *528DDD5B0275_4F2B767D015E_impl* l_Cell := aCellIterator.First(False); l_CurrentCellsTypeList := TedCellTypesList.Create; try while l_Cell <> nil do begin l_CurrentCellsTypeList.Add(l_Cell.GetCellType); l_Cell := aCellIterator.Next; end; // while l_Cell <> nil do aCellIterator.First(False); // Не надо "портить" итератор. aCellOffsetPair.CellsType := l_CurrentCellsTypeList; finally l_CurrentCellsTypeList := nil; end; //#UC END# *528DDD5B0275_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.SaveCellsTypeList procedure TevCellsWidthCorrecter.CorrectCells(const aRow: IedRow); //#UC START# *4F2BC62D00FE_4F2B767D015E_var* var l_WidthList : TevCellsOffsetsPair; procedure lp_CheckAndRememberPrevWidth; var l_CurrWidth : Integer; begin l_CurrWidth := l_WidthList.GetOffset(True); if not f_HeadAlignment and (f_PrevRowWidth > 0) and not f_WasNotEqualRows then f_WasNotEqualRows := l_CurrWidth <> f_PrevRowWidth; f_PrevRowWidth := l_CurrWidth; end; var l_Cell : IedCell; l_Index : Integer; l_NewWidth : Integer; l_OldCellWidth : Integer; procedure lp_InitWidth; (*var l_NeedDelete: Boolean;*) begin l_OldCellWidth := l_Cell.Width; l_NewWidth := evCheckCellWidth(l_OldCellWidth, True); l_WidthList.SetWidthPair(l_NewWidth, l_Cell.Width); (*l_NeedDelete := (l_NewWidth <= 3 * evGetMinimalCellWidth) and (l_Index = l_WidthList.CellsType.Count - 1) and (l_WidthList.CellsType[l_Index] = ed_EmptyAndNotFramed); if l_NeedDelete then l_WidthList.CellsType[l_Index] := ed_NeedDelete;*) end; var l_NeedBreak : Boolean; l_PrevWidthList : TevCellsOffsetsPair; procedure lp_CheckPrevList; var l_CellPos: TedCellPosType; begin if l_PrevWidthList <> nil then begin l_CellPos := ed_cpNone; if l_Cell = nil then begin l_CellPos := ed_cpLast; if FoundPriorityTemplate then l_CellPos := ed_cpIgnoreLast; end; // if l_Cell = nil then l_PrevWidthList.CheckCurrentRow(l_WidthList, l_NewWidth, l_OldCellWidth, f_PrevRowWidth, l_CellPos, l_NeedBreak); end; // if l_PrevWidthList <> nil then end; var l_PrevList : TevCellsOffsetsPair; l_CellIterator : IedCellsIterator; //#UC END# *4F2BC62D00FE_4F2B767D015E_var* begin //#UC START# *4F2BC62D00FE_4F2B767D015E_impl* f_Row := aRow; try l_CellIterator := GetIterator; if l_CellIterator <> nil then try if not f_HeadAlignment then AnalizeRowType(f_Row); l_Cell := l_CellIterator.First(False); if (l_Cell <> nil) then begin if not TryToCopyForeignList then if not TryToCopyFromSuitableList then begin if f_CellsOffsetPairList.Count > 0 then l_PrevList := f_CellsOffsetPairList.Last else l_PrevList := nil; l_WidthList := AddevCellsOffsetsPair(l_CellIterator); try l_Index := 0; l_PrevWidthList := GetTemplate; l_NeedBreak := False; while (l_Cell <> nil) do begin lp_InitWidth; l_Cell := l_CellIterator.Next; lp_CheckPrevList; if l_NeedBreak then Break; l_WidthList.AddCellWidthAndRecalc; Inc(l_Index); end; // while (l_Cell <> nil) if not f_HeadAlignment then l_WidthList.CheckPrevAlignment(l_PrevList); lp_CheckAndRememberPrevWidth; finally if not f_HeadAlignment then l3Free(l_WidthList); end; end; // if not TryToCopyFromSuitableList then end; // if l_Cell <> nil then finally l_CellIterator := nil; end; finally f_Row := nil; end; //#UC END# *4F2BC62D00FE_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.CorrectCells procedure TevCellsWidthCorrecter.ApplyChanges2Row(const anOp: InevOp; const aRow: IedRow; aFirst: Boolean); //#UC START# *4F2BC6810005_4F2B767D015E_var* var l_CellIterator: IedCellsIterator; //#UC END# *4F2BC6810005_4F2B767D015E_var* begin //#UC START# *4F2BC6810005_4F2B767D015E_impl* l_CellIterator := aRow.CellsIterator; if l_CellIterator <> nil then begin if aFirst then f_Index := 0 else Inc(f_Index); ApplyChanges(anOp, l_CellIterator.BackIterator, l_CellIterator.CellsCount); end; // if l_CellIterator <> nil then //#UC END# *4F2BC6810005_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.ApplyChanges2Row function TevCellsWidthCorrecter.GetPrevRowType: TedRowType; //#UC START# *5114D749037C_4F2B767D015E_var* //#UC END# *5114D749037C_4F2B767D015E_var* begin //#UC START# *5114D749037C_4F2B767D015E_impl* Result := f_CellsOffsetPairList.Last.RowType; //#UC END# *5114D749037C_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.GetPrevRowType function TevCellsWidthCorrecter.GetCellsCountInPreviousRow: Integer; {* Возвращает число ячеек в последней выравненной строке } //#UC START# *5152D812036E_4F2B767D015E_var* //#UC END# *5152D812036E_4F2B767D015E_var* begin //#UC START# *5152D812036E_4F2B767D015E_impl* if (f_CellsOffsetPairList = nil) or (f_CellsOffsetPairList.Count = 0) then Result := 0 else Result := f_CellsOffsetPairList.Last.CellsType.Count; //#UC END# *5152D812036E_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.GetCellsCountInPreviousRow procedure TevCellsWidthCorrecter.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4F2B767D015E_var* //#UC END# *479731C50290_4F2B767D015E_var* begin //#UC START# *479731C50290_4F2B767D015E_impl* f_ForegnTemplates := nil; if f_RowsWithSingleCell <> nil then f_RowsWithSingleCell.Clear; l3Free(f_RowsWithSingleCell); f_PriorityTemplateRow := nil; if f_CellsOffsetPairList <> nil then f_CellsOffsetPairList.Clear; l3Free(f_CellsOffsetPairList); f_PrevRowWidth := 0; f_WasNotEqualRows := False; f_HeadAlignment := False; f_Row := nil; f_NumbericData := nil; inherited; //#UC END# *479731C50290_4F2B767D015E_impl* end;//TevCellsWidthCorrecter.Cleanup end.
unit MsSqlDBManager; interface uses Classes, iniFiles, DB, Variants, HashMap, DCL_intf, ADODB, StrUtils, SysUtils, DBManager, DBTables, QueryReader, Data.SqlExpr; const MSSQL_SQL_CREATE = 'if db_id(''%s'') is null begin create database %s end;'; MSSQL_SQL_DROP = 'drop database %s;'; MSSQL_SQL_BACKUP = 'backup database %s to disk = ''%s'' with init'; MSSQL_SQL_DBLIST = 'select name FROM sys.databases;'; MSSQL_DBFILE_FOLDER_X64 = 'C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data'; MSSQL_DBFILE_FOLDER_X86 = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data'; type //-----------------------------------------------------------------+ // 클래스명: TMsSqlDBManager // 주요역할: MS-SQL Server를 관리 하기 위한 클래스 이다. // 기본적으로 localhost이며 id및 pw가 설정되어 있지 않은 곳에서 쓰인다. //-----------------------------------------------------------------+ TMsSqlDBManager = Class(TAbsDBServer) private FConnect: TADOConnection; FQuery: TADOQuery; protected function GetLogicalDBName(filePath: String): String; function GetLocalDBLocation(): String; public Constructor Create(); Destructor Destroy(); override; procedure SetTableNames(); override; procedure SetColumnNames(); override; function ExecuteQuery(query: String): TDataSet; override; function ExecuteNonQuery(query: String): Integer; override; function Backup(backupPath: String): Boolean; override; function Open(): Boolean; override; function IsOpen(): Boolean; override; procedure Close(); override; function Restore(filePath, RestoreName: String): Boolean; override; function CreateDB(DBName: String): Boolean; override; function DropDB(DbName: String): Boolean; override; function GetDBList(isFilter: Boolean): TStringList; override; function ClearTrash(wantQuery, issueDBName, restoreFileName: String): Boolean; function Login(id, pw, defDB, addr: String): Boolean; override; function GetDBMSName: String; override; end; implementation { TMsSqlDBManager } //-----------------------------------------------------------------+ // 지정한 경로에 DB를 백업 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.Backup(backupPath: String): Boolean; begin if FileExists( backupPath ) = true then DeleteFile( backupPath ); try ExecuteNonQuery( Format( MSSQL_SQL_BACKUP, [DBName, backupPath] ) ); result := true; except on e: Exception do WriteErrorMessage( e.Message ); end; result := false; end; //-----------------------------------------------------------------+ // DB 복원시 발생된 예외를 처리 한다. // 복원 하려는 DB가 이미 존재할 경우 Drop 시키고, // Drop시 오류가 날 경우 DB가 존재하지 않기에 복원 경로에 문제가 있다고 판단, // 같은 경로내 관련된 DB 파일들을 모두 삭제 하고 DB를 재 복원 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.ClearTrash(wantQuery, issueDBName, restoreFileName: String): Boolean; begin try ExecuteNonQuery( 'use master drop database ' + issueDBName ); result := true; except try DeleteFile( restoreFileName + '.mdf' ); DeleteFile( restoreFileName + '_Log.log' ); DeleteFile( restoreFileName + '_Log.LDF' ); ExecuteNonQuery( wantQuery ); result := true; except on e: Exception do begin WriteErrorMessage( e.Message ); result := false; end; end; end; end; //-----------------------------------------------------------------+ // 열려진 DB를 닫는다. //-----------------------------------------------------------------+ procedure TMsSqlDBManager.Close; begin inherited; FConnect.Close; FQuery.Close; end; //-----------------------------------------------------------------+ // 생성자. 내부 맴버를 생성하고 초기화 한다. //-----------------------------------------------------------------+ constructor TMsSqlDBManager.Create; begin FConnStr := DEFAULT_MSSQL_CONN_STR; FConnect := TADOConnection.Create( nil ); FDataSource := TDataSource.Create( nil ); FQuery := TADOQuery.Create( nil ); FConnect.ConnectionString := FConnStr; FConnect.Provider := 'SQLOLEDB'; FConnect.LoginPrompt := false; FConnect.Mode := cmReadWrite; FQuery.Connection := FConnect; end; //-----------------------------------------------------------------+ // 지정한 이름으로 DB를 새로 생성 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.CreateDB(DBName: String): Boolean; var ret: Integer; begin ret := ExecuteNonQuery( Format( MSSQL_SQL_CREATE, [dbName, dbName] ) ); result := ret > 0; end; //-----------------------------------------------------------------+ // 지정된 이름의 DB를 삭제 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.DropDB(DbName: String): Boolean; var ret: Integer; begin ret := ExecuteNonQuery( Format( MSSQL_SQL_DROP, [DbName] ) ); result := ret > -1; end; //-----------------------------------------------------------------+ // DB파일 (.bak)을 복원 한다. // 복원시 내부적으로 예외가 발생할 경우 ClearTrash를 호출하여 예외 처리를 시도 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.Restore(filePath, RestoreName: String): Boolean; var sQuery: String; sLogicalName: String; sDirectory: String; sRestoreFileName: String; begin sLogicalName := GetLogicalDBName( filePath ); sDirectory := GetLocalDBLocation; sRestoreFileName := StringReplace( ExtractFileName( filePath ), '.', '_', [ rfReplaceAll, rfIgnoreCase ] ); sQuery := 'use master restore database ' + RestoreName + ' from disk = ''' + filePath + ''' with recovery, ' + 'move ''' + sLogicalName + ''' to ''' + sDirectory + '\' + RestoreName + '.mdf'', ' + 'move ''' + sLogicalName + '_Log'' to ''' + sDirectory + '\' + RestoreName + '_Log.log'' '; try begin WriteErrorMessage( sQuery ); ExecuteNonQuery( sQuery ); result := true; end; except on e: Exception do begin result := self.ClearTrash( sQuery, sLogicalName, sDirectory + '\' + RestoreName ); end; end; end; //-----------------------------------------------------------------+ // 소멸자. 현재 DB 관리자를 메모리에서 제거 한다. //-----------------------------------------------------------------+ destructor TMsSqlDBManager.Destroy; begin self.Close; FConnect.Free; FQuery.Close; FDataSource.Free; end; //-----------------------------------------------------------------+ // Select문을 제외한 모든 쿼리문을 수행 한다. // 리턴값이 -1일 경우는 오류가 난 것이다. //-----------------------------------------------------------------+ function TMsSqlDBManager.ExecuteNonQuery(query: String): Integer; begin try if AnsiContainsText( LowerCase( query ), 'use master' ) = false then query := 'use ' + DBName + ' ' + query; FQuery.SQL.Clear; FQuery.SQL.Add( query ); result := FQuery.ExecSQL; except on e: Exception do begin WriteErrorMessage( query + '::::' + e.Message ); result := -1; end; end; end; //-----------------------------------------------------------------+ // Select문과 같이 검색 결과가 있는 쿼리문을 수행 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.ExecuteQuery(query: String): TDataSet; var objQuery: TADOQuery; begin try objQuery := TADOQuery.Create( nil ); objQuery.Connection := FConnect; if AnsiContainsText( LowerCase( query ), 'use master' ) = false then query := 'use ' + DBName + ' ' + query; objQuery.SQL.Clear; //query := StringReplace( query, #$A, ' ', [ rfReplaceAll, rfIgnoreCase ] ); //query := StringReplace( query, #9, ' ', [ rfReplaceAll, rfIgnoreCase ] ); objQuery.SQL.Append( query ); objQuery.Open; result := objQuery; except on e: Exception do begin WriteErrorMessage( query + '::::' + e.Message ); result := nil; end; end; end; //-----------------------------------------------------------------+ // 현재 등록된 모든 Database의 이름들을 얻는다. //-----------------------------------------------------------------+ function TMsSqlDBManager.GetDBList(isFilter: Boolean): TStringList; var sQuery: String; sList: TStringList; field: TField; data: TDataSet; begin sList := TStringList.Create; sQuery := MSSQL_SQL_DBLIST; if isFilter = true then begin sQuery := sQuery + 'where name like ''' + DEFAULT_DB_LIST_FILTER + ''' '; end; sQuery := sQuery + 'ORDER BY database_id'; data := ExecuteQuery( sQuery ); while data.Eof = false do begin sList.Add( data.FieldList[0].CurValue ) end; data.Free; result := sList; end; function TMsSqlDBManager.GetDBMSName: String; begin result := 'mssql'; end; function TMsSqlDBManager.GetLocalDBLocation: String; begin if DirectoryExists( MSSQL_DBFILE_FOLDER_X64 ) = true then begin result := MSSQL_DBFILE_FOLDER_X64; end else begin result := MSSQL_DBFILE_FOLDER_X86; end; end; //-----------------------------------------------------------------+ // 지정한 경로의 bak파일에서 실제 DB 이름을 얻는다. //-----------------------------------------------------------------+ function TMsSqlDBManager.GetLogicalDBName(filePath: String): String; var sQuery: String; datasourceTemp: TDataSource; dataset: TDataSet; fieldData: TField; sDBName: String; begin datasourceTemp := TDataSource.Create( nil ); sQuery := 'restore headeronly from disk = ''' + filePath + ''' '; FQuery.SQL.Clear; FQuery.SQL.Add( sQuery ); FQuery.Open; FQuery.ExecSQL; datasourceTemp.DataSet := FQuery; dataset := datasourceTemp.DataSet; fieldData := dataset.FieldByName( 'DatabaseName' ); sDBName := fieldData.Value; FreeAndNil( datasourceTemp ); result := sDBName; end; //-----------------------------------------------------------------+ // DB가 열린 상태인지 확인 한다. //-----------------------------------------------------------------+ function TMsSqlDBManager.IsOpen: Boolean; begin result := FConnect.Connected; end; function TMsSqlDBManager.Login(id, pw, defDB, addr: String): Boolean; begin if FConnect.Connected = true then FConnect.Connected := false; try FConnect.ConnectionString := Format( SERVER_MSSQL_CONN_STR, [id, pw, defDB, addr] ); DBName := defDB; result := true; except on e: Exception do WriteErrorMessage( e.Message ); end; result := false; end; //-----------------------------------------------------------------+ // DB를 연다. //-----------------------------------------------------------------+ function TMsSqlDBManager.Open: Boolean; begin try if IsOpen = false then begin FConnect.ConnectionString := DEFAULT_MSSQL_CONN_STR; FConnect.Connected := true; end; result := true; except on e: Exception do WriteErrorMessage( e.Message ); end; result := false; end; //-----------------------------------------------------------------+ // DB내의 각 Table 이름별 열이름을 설정 한다. //-----------------------------------------------------------------+ procedure TMsSqlDBManager.SetColumnNames; var sQuery: String; sCompQuery: String; sTableName: String; enumerator: Classes.TStringsEnumerator; dataset: TDataSet; field: TField; iCnt: Integer; List_Columns: TStringList; begin inherited; if FTableNames = nil then self.SetTableNames; FColumnNames := TStrHashMap.Create; sQuery := 'use ' + DBName + ' SELECT COLUMN_NAME as name FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = '''; enumerator := FTableNames.GetEnumerator; while enumerator.MoveNext do begin sCompQuery := sQuery + enumerator.Current + ''' '; FQuery.SQL.Clear; FQuery.SQL.Add(sCompQuery); FQuery.Open; dataset := FQuery; field := dataset.FieldByName( 'name' ); List_Columns := TStringList.Create; for iCnt := 0 to dataset.RecordCount - 1 do begin List_Columns.Add(field.Value); dataset.Next; end; FColumnNames.PutValue(enumerator.Current, List_Columns); end; end; //-----------------------------------------------------------------+ // DB내 모든 Table의 이름을 설정한다. //-----------------------------------------------------------------+ procedure TMsSqlDBManager.SetTableNames; var sQuery: String; sCompQuery: String; sTableName: String; field: TField; dataset: TDataSet; begin inherited; FTableNames := TStringList.Create; sQuery := 'use ' + DBName + ' SELECT name FROM sysobjects WHERE Type = ''U'' ORDER BY name'; dataset := ExecuteQuery(sQuery); field := dataset.FieldByName('name'); while dataset.Eof = false do begin FTableNames.Add(field.Value); dataset.Next; end; end; end.
unit WinSockRDOServerClientConnection; interface uses SmartThreads, Classes, ComObj, Windows, RDOInterfaces, SocketComp, SyncObjs; type TWinSockRDOServerClientConnection = class( TInterfacedObject, IRDOConnection, IRDOServerClientConnection ) public constructor Create(Sock : IWinSocketWrap; termEvent : THandle); //Create( Socket : TCustomWinSocket ); destructor Destroy; override; protected // IRDOConnection function Alive : boolean; function SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; stdcall; procedure Send( const QueryText : string ); stdcall; function GetLocalAddress : string; stdcall; function GetLocalHost : string; stdcall; function GetLocalPort : integer; stdcall; function GetOnConnect : TRDOClientConnectEvent; procedure SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); function GetOnDisconnect : TRDOClientDisconnectEvent; procedure SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); protected // IRDOServerClientConnection procedure OnQueryResultArrival( const QueryResult : string ); private fUnsentQueries : TList; fSentQueries : TList; fSenderThread : TSmartThread; fSentQueriesLock : TCriticalSection; fSocket : IWinSocketWrap; //TCustomWinSocket; fUnsentQueryWaiting : THandle; fTerminateEvent : THandle; fOnConnect : TRDOClientConnectEvent; fOnDisconnect : TRDOClientDisconnectEvent; private function GetTimeOut : integer; procedure SetTimeOut(TimeOut : integer); end; implementation uses SysUtils, RDOUtils, RDOProtocol, {$IFDEF Logs} LogFile, {$ENDIF} ErrorCodes, Logs; // Query id generation routines and variables var LastQueryId : word; function GenerateQueryId : integer; begin Result := LastQueryId; LastQueryId := ( LastQueryId + 1 ) mod 65536 end; type TQueryToSend = record Id : word; Text : string; WaitForAnsw : boolean; Result : string; Event : THandle; ErrorCode : integer; end; PQueryToSend = ^TQueryToSend; // TWinSockRDOServerClientConnection constructor TWinSockRDOServerClientConnection.Create(Sock : IWinSocketWrap; termEvent : THandle); begin inherited Create; fSocket := Sock; fSentQueriesLock := TCriticalSection.Create; fUnsentQueries := TList.Create; fSentQueries := TList.Create; fUnsentQueryWaiting := CreateEvent( nil, true, false, nil ); fTerminateEvent := termEvent; end; destructor TWinSockRDOServerClientConnection.Destroy; begin SetEvent( fTerminateEvent ); fSenderThread.Free; fSentQueriesLock.Free; fUnsentQueries.Free; fSentQueries.Free; CloseHandle( fUnsentQueryWaiting ); inherited end; function TWinSockRDOServerClientConnection.Alive : boolean; begin result := fSocket.isValid; end; function TWinSockRDOServerClientConnection.SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; var theQuery : PQueryToSend; WaitRes : cardinal; WinSocket : TCustomWinSocket; begin try New( theQuery ); try theQuery.Id := GenerateQueryId; theQuery.Text := QueryText; theQuery.WaitForAnsw := true; theQuery.Result := ''; theQuery.Event := CreateEvent( nil, false, false, nil ); theQuery.ErrorCode := errNoError; try // Add to Sent Queue fSentQueriesLock.Acquire; try fSentQueries.Add(theQuery); finally fSentQueriesLock.Release end; // Send the Query try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then WinSocket.SendText(CallId + Blank + IntToStr( theQuery.Id ) + Blank + theQuery.Text); finally fSocket.Unlock; end; except fSentQueriesLock.Acquire; try fSentQueries.Remove(theQuery) finally fSentQueriesLock.Release end end; // Wait for result WaitRes := WaitForSingleObject( theQuery.Event, TimeOut ); if WaitRes = WAIT_OBJECT_0 then begin Result := theQuery.Result; ErrorCode := theQuery.ErrorCode; end else begin Result := ''; ErrorCode := errQueryTimedOut; end finally fSentQueriesLock.Acquire; try fSentQueries.Remove(theQuery); CloseHandle(theQuery.Event); finally fSentQueriesLock.Release end; end; finally Dispose(theQuery); end except ErrorCode := errUnknownError end end; procedure TWinSockRDOServerClientConnection.Send( const QueryText : string ); var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then WinSocket.SendText(CallId + Blank + QueryText); finally fSocket.Unlock; end; except Logs.Log('Survival', '(10)- Error sending query'); // (10) end; end; function TWinSockRDOServerClientConnection.GetLocalAddress : string; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.LocalAddress else Result := ''; finally fSocket.Unlock; end; except Result := ''; end; end; function TWinSockRDOServerClientConnection.GetLocalHost : string; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.LocalHost else Result := ''; finally fSocket.Unlock; end; except Result := ''; end; end; function TWinSockRDOServerClientConnection.GetLocalPort : integer; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.LocalPort else Result := 0; finally fSocket.Unlock; end; except Result := 0; end; end; function TWinSockRDOServerClientConnection.GetOnConnect : TRDOClientConnectEvent; begin result := fOnConnect; end; procedure TWinSockRDOServerClientConnection.SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); begin fOnConnect := OnConnectHandler; end; function TWinSockRDOServerClientConnection.GetOnDisconnect : TRDOClientDisconnectEvent; begin result := fOnDisconnect; end; procedure TWinSockRDOServerClientConnection.SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); begin fOnDisconnect := OnDisconnectHandler; end; procedure TWinSockRDOServerClientConnection.OnQueryResultArrival( const QueryResult : string ); function FindServicedQuery( QueryText : string ) : PQueryToSend; var CharIdx : integer; IdDigits : string; QueryId : integer; QueryIdx : integer; SentQueries : integer; ServicedQuery : PQueryToSend; QueryTextLen : integer; begin IdDigits := ''; CharIdx := 1; SkipSpaces( QueryText, CharIdx ); IdDigits := ReadNumber( QueryText, CharIdx ); try QueryId := StrToInt( IdDigits ); except QueryId := -1 end; if QueryId <> -1 then begin QueryIdx := 0; SentQueries := fSentQueries.Count; while ( QueryIdx < SentQueries ) and ( QueryId <> PQueryToSend( fSentQueries[ QueryIdx ] ).Id ) do inc( QueryIdx ); if QueryIdx < SentQueries then begin ServicedQuery := fSentQueries[ QueryIdx ]; QueryTextLen := Length( QueryText ); while CharIdx <= QueryTextLen do begin ServicedQuery.Result := ServicedQuery.Result + QueryText[ CharIdx ]; inc( CharIdx ) end; Result := ServicedQuery end else Result := nil end else Result := nil; end; var ServicedQuery : PQueryToSend; begin fSentQueriesLock.Acquire; try ServicedQuery := FindServicedQuery( QueryResult ); if ServicedQuery <> nil then begin fSentQueries.Remove( ServicedQuery ); ServicedQuery.ErrorCode := errNoError; SetEvent( ServicedQuery.Event ) end finally fSentQueriesLock.Release end end; function TWinSockRDOServerClientConnection.GetTimeOut : integer; begin result := 60*1000; end; procedure TWinSockRDOServerClientConnection.SetTimeOut(TimeOut : integer); begin end; end.
unit db_add_account_test; interface uses DUnitX.TestFramework, encrypter, add_account, delphi.mocks, db_add_account; type ISutType = interface ['{6B289352-E5CA-4F63-845F-523EC2A99E86}'] function Sut: IAddAccount; function EncrypterStub: TMock<IEncrypter>; end; TSutType = class(TInterfacedObject, ISutType) private FSutType: IAddAccount; FEncrypterStub: TMock<IEncrypter>; function Sut: IAddAccount; function EncrypterStub: TMock<IEncrypter>; constructor Create; private class function New: ISutType; end; [TestFixture] TDBADDAccountTest = class function MakeSut: ISutType; public [Test] procedure ShouldCallEncrypterWithCorrectPassword; end; implementation function TDBADDAccountTest.MakeSut: ISutType; begin result := TSutType.New; result.EncrypterStub.Setup.WillReturnDefault('encrypt', 'default_password'); end; procedure TDBADDAccountTest.ShouldCallEncrypterWithCorrectPassword; var lSutType: ISutType; accountDataStub: IAddAccountModel; begin lSutType := MakeSut; lSutType.EncrypterStub.Setup.Expect.AtLeastOnce.When.encrypt('valid_password'); accountDataStub := TAddAccountModel.New // .name('valid_name') // .email('valid_email') // .password('valid_password'); lSutType.Sut.add(accountDataStub); lSutType.EncrypterStub.Verify; end; constructor TSutType.Create; begin FEncrypterStub := TMock<IEncrypter>.Create; FSutType := TDBADDAccount.New(FEncrypterStub); end; function TSutType.EncrypterStub: TMock<IEncrypter>; begin result := FEncrypterStub; end; function TSutType.Sut: IAddAccount; begin result := FSutType; end; class function TSutType.New: ISutType; begin result := TSutType.Create; end; initialization TDUnitX.RegisterTestFixture(TDBADDAccountTest); end.
{ \file DGLE_Types.pas \author Korotkov Andrey aka DRON \version 2:0.3.1 \date 17.11.2014 (c)Korotkov Andrey \brief Engine types definition header. This header is a part of DGLE_SDK. } unit DGLE_Types; interface {$I include.inc} {$IFNDEF DGLE_TYPES} {$DEFINE DGLE_TYPES} {$ENDIF} uses Windows {$IF COMPILERVERSION >= 20}, Generics.Collections{$IFEND}; const Minus1 = $FFFFFFFF; //E_ENGINE_WINDOW_FLAGS EWF_DEFAULT = $00000000;//< This flag is suitable in most cases. EWF_ALLOW_SIZEING = $00000001;//< User can resize engine window arbitrarily EWF_TOPMOST = $00000002;//< Engine window will be always on top. EWF_DONT_HOOK_MAINLOOP = $00000004;//< If flag set and engine doesn't owns window, host applications main loop will not be hooked. User must call window repaint manually. EWF_DONT_HOOK_ROOT_WINDOW = $00000008;//< If flag set and engine doesn't owns window, main host application window will not be hooked. User must redirect windows messages manually. EWF_RESTRICT_FULLSCREEN_HOTKEY = $00000010;//< Switching between fullscreen and windowed modes by pressing "Alt-Enter" will be restricted. EWF_RESTRICT_CONSOLE_HOTKEY = $00000020;//< Restricts calling engine console window by pressing "~" key. // E_MULTISAMPLING_MODE MM_NONE = $00000000;//**< Multisampling is off. */ MM_2X = $00000001;//**< 2xMSAA */ MM_4X = $00000002;//**< 4xMSAA \note This value is recomended. */ MM_8X = $00000004;//**< 8xMSAA */ MM_16X = $00000008;//**< 16xMSAA */ type E_WINDOW_MESSAGE_TYPE = ( WMT_UNKNOWN = 0, WMT_REDRAW = 1, WMT_PRESENT = 2, WMT_CLOSE = 3, WMT_CREATE = 4, WMT_DESTROY = 5, WMT_RELEASED = 6, WMT_ACTIVATED = 7, WMT_DEACTIVATED = 8, WMT_MINIMIZED = 9, WMT_RESTORED = 10, WMT_MOVE = 11, WMT_SIZE = 12, WMT_KEY_UP = 13, WMT_KEY_DOWN = 14, WMT_ENTER_CHAR = 15, WMT_MOUSE_LEAVE = 16, WMT_MOUSE_MOVE = 17, WMT_MOUSE_DOWN = 18, WMT_MOUSE_UP = 19, WMT_MOUSE_WHEEL = 20 ); // Variant data type definiton // E_DGLE_VARIANT_TYPE = ( DVT_UNKNOWN = 0, DVT_INT = 1, DVT_FLOAT = 2, DVT_BOOL = 3, DVT_POINTER = 4, DVT_DATA = 5 ); DGLE_RESULT = Integer; TWindowHandle = HWND; TWindowDrawHandle = HDC; TCRndrInitResults = Boolean; GLUInt = Cardinal; PByte = Pointer; TEngineWindow = packed record uiWidth : Cardinal; uiHeight : Cardinal; bFullScreen : Boolean; bVSync : Boolean; eMultiSampling : {E_MULTISAMPLING_MODE} Cardinal; uiFlags : {ENG_WINDOW_FLAGS} Cardinal; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(var dummy); overload; constructor Create(uiWidth, uiHeight : Integer; bFullScreen : Boolean; bVSync : Boolean = False; eMSampling: {E_MULTISAMPLING_MODE} Cardinal = MM_NONE; uiFlags:{ENG_WINDOW_FLAGS}Integer = EWF_DEFAULT); overload; {$ENDIF} end; TSystemInfo = packed record cOSName : array[0..127] of AnsiChar; cCPUName : array[0..127] of AnsiChar; uiCPUCount : Cardinal; uiCPUFrequency : Cardinal; uiRAMTotal : Cardinal; uiRAMAvailable : Cardinal; cVideocardName : array[0..127] of AnsiChar; uiVideocardCount : Cardinal; uiVideocardRAM : Cardinal; end; TPluginInfo = packed record ui8PluginSDKVersion : Byte; cName : array[0..127] of AnsiChar; cVersion : array[0..64] of AnsiChar; cVendor : array[0..127] of AnsiChar; cDescription : array[0..256] of AnsiChar; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(var dummy); {$ENDIF} end; TWindowMessage = packed record eMsgType : E_WINDOW_MESSAGE_TYPE; ui32Param1 : Cardinal; ui32Param2 : Cardinal; pParam3 : Pointer; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(var dummy); overload; constructor Create(msg: E_WINDOW_MESSAGE_TYPE; param1: Cardinal = 0; param2: Cardinal = 0; param3: Pointer = nil); overload; {$ENDIF} end; TColor4 = packed record {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(var dummy); overload; constructor Create(ui32ABGR: Cardinal); overload; constructor Create(ui32RGB: Cardinal; ubA: byte); overload; constructor Create(ubR, ubG, ubB, ubA: Byte); overload; constructor Create(fR, fG, fB, fA: Single); overload; constructor Create(const rgba: array of Single); overload; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} procedure SetColorF(fR, fG, fB, fA: Single); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetColorB(ubR, ubG, ubB, ubA: Byte); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorRGB(): Cardinal; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorRGBA(): Cardinal; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator {$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(Color: TColor4): Cardinal; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} case Byte of 0: (r, g, b, a : Single); 1: (_rgba : array[0..3] of Single); end; PColor4 = ^TColor4; type TPoint3 = packed record {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create (var dummy); overload; constructor Create (x, y, z : Single); overload; constructor Create (all : Single); overload; constructor Create (const Floats: array of Single); overload; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} function Dot(const stPoint: TPoint3): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Cross(const stPoint: TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function FlatDistTo(const stPoint: TPoint3): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistTo(const stPoint: TPoint3): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistToQ(const stPoint: TPoint3): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function LengthQ(): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Length(): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Normalize(): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Lerp(const stPoint: TPoint3; coeff: Single): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Angle(const stPoint: TPoint3): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Rotate(const Axis: TPoint3; fAngle: Single): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Reflect(const normal : TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator {$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} case byte of 0: (_1D : array[0..2] of Single); 1: (x, y, z : Single); end; PPoint3 = ^TPoint3; TVector3 = TPoint3; TVec3 = TPoint3; TPoint2 = packed record {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create (var dummy); overload; constructor Create (x, y: Single); overload; constructor Create (All: Single); overload; constructor Create (const Floats: array of Single); overload; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} function Dot(const stPoint: TPoint2): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Cross(const stPoint: TPoint2): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistTo(const stPoint: TPoint2): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistToQ(const stPoint: TPoint2): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function LengthQ(): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Length(): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Normalize(): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Lerp(const stPoint: TPoint2; coeff: Single): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Angle(const stPoint: TPoint2): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Rotate(fAngle: Single): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Reflect(const normal : TPoint2): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator {$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} case byte of 0: (_1D : array[0..1] of Single); 1: (x, y : Single); end; PPoint2 = ^TPoint2; TVector2 = TPoint2; TVec2 = TPoint2; TVertex2 = packed record case byte of 0: (_1D : array[0..7] of Single); 1: (x, y, u, w, r, g, b, a : Single); end; PVertex2 = ^TVertex2; TRectf = packed record x, y, width, height : Single; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(var dummy); overload; constructor Create(x, y, width, height : Single); overload; constructor Create(const stLeftTop, stRightBottom: TPoint2); overload; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} function IntersectRect(const stRect: TRectf):Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function PointInRect(const stPoint : TPoint2):Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function RectInRect(const stRect : TRectf): Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function GetIntersectionRect(const stRect : TRectf): TRectf; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} end; PRectf = ^TRectf; TMatrix4x4 = packed record {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator {$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} case byte of 0: (_1D : array[0..15] of Single); 1: (_2D : array[0..3, 0..3] of Single); end; PMatrix = ^TMatrix4x4; TMatrix = TMatrix4x4; TMat4 = TMatrix4x4; TMatrix4 = TMatrix4x4; TTransformStack = class private {$IF COMPILERVERSION >= 20} Stack: TStack<TMatrix>; {$ELSE} Stack: array of TMatrix; {$IFEND} constructor Create(); overload; function GetTop(): TMatrix4x4; procedure SetTop(const Value: TMatrix4x4); public constructor Create(const base_transform: TMatrix4x4); overload; {$IF COMPILERVERSION >= 20} destructor Destroy(); override; {$IFEND} procedure Clear(const base_transform: TMatrix4x4); procedure Push(); procedure Pop(); procedure MultGlobal(const transform: TMatrix4x4); procedure MultLocal(const transform: TMatrix4x4); property Top: TMatrix4x4 read GetTop write SetTop; end; TMouseStates = packed record iX : Integer; iY : Integer; iDeltaX : Integer; iDeltaY : Integer; iDeltaWheel : Integer; bLeftButton : Boolean; bRightButton : Boolean; bMiddleButton : Boolean; end; TKeyboardStates = packed record bCapsLock : Boolean; bShiftL : Boolean; bShiftR : Boolean; bCtrlL : Boolean; bCtrlR : Boolean; bAltL : Boolean; bAltR : Boolean; end; TJoystickStates = packed record uiButtonsCount: Cardinal; bButtons : array[0..31] of Boolean; iXAxes : Integer; iYAxes : Integer; iZAxes : Integer; iRAxes : Integer; iUAxes : Integer; iVAxes : Integer; iPOV : Integer; end; TVariant = packed record _type: E_DGLE_VARIANT_TYPE; _Data: Pointer; {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator {$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Integer; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} class operator {$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Pointer; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} procedure Clear(); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetInt(iVal: Integer); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetFloat(fVal: Single); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetBool(bVal: Boolean); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetPointer(pPointer: Pointer); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetData(pData: Pointer; uiDataSize: Cardinal); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsInt(): Integer; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsFloat(): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsBool(): Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsPointer(): Pointer; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure GetData(out pData: Pointer; out uiDataSize: Cardinal); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function GetType(): E_DGLE_VARIANT_TYPE; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$ENDIF} end; type E_KEYBOARD_KEY_CODES = ( KEY_ESCAPE = $01, // Escape KEY_TAB = $0F, // Tab KEY_GRAVE = $29, // accent grave "~" KEY_CAPSLOCK = $3A, // Caps Lock KEY_BACKSPACE = $0E, // Backspace KEY_RETURN = $1C, // Enter KEY_SPACE = $39, // Space KEY_SLASH = $35, // "/" KEY_BACKSLASH = $2B, // "\" KEY_SYSRQ = $B7, // PtrScr (SysRq) KEY_SCROLL = $46, // Scroll Lock KEY_PAUSE = $C5, // Pause KEY_INSERT = $D2, // Insert KEY_DELETE = $D3, // Delete KEY_HOME = $C7, // Home KEY_END = $CF, // End KEY_PGUP = $C9, // PgUp KEY_PGDN = $D1, // PgDn KEY_LSHIFT = $2A, // Left Shift KEY_RSHIFT = $36, // Right Shift KEY_LALT = $38, // Left Alt KEY_RALT = $B8, // Right Alt KEY_LWIN_OR_CMD = $DB, // Left Windows key KEY_RWIN_OR_CMD = $DC, // Right Windows key KEY_LCONTROL = $1D, // Left Control KEY_RCONTROL = $9D, // Right Control KEY_UP = $C8, // UpArrow KEY_RIGHT = $CD, // RightArrow KEY_LEFT = $CB, // LeftArrow KEY_DOWN = $D0, // DownArrow KEY_1 = $02, KEY_2 = $03, KEY_3 = $04, KEY_4 = $05, KEY_5 = $06, KEY_6 = $07, KEY_7 = $08, KEY_8 = $09, KEY_9 = $0A, KEY_0 = $0B, KEY_F1 = $3B, KEY_F2 = $3C, KEY_F3 = $3D, KEY_F4 = $3E, KEY_F5 = $3F, KEY_F6 = $40, KEY_F7 = $41, KEY_F8 = $42, KEY_F9 = $43, KEY_F10 = $44, KEY_F11 = $57, KEY_F12 = $58, KEY_Q = $10, KEY_W = $11, KEY_E = $12, KEY_R = $13, KEY_T = $14, KEY_Y = $15, KEY_U = $16, KEY_I = $17, KEY_O = $18, KEY_P = $19, KEY_A = $1E, KEY_S = $1F, KEY_D = $20, KEY_F = $21, KEY_G = $22, KEY_H = $23, KEY_J = $24, KEY_K = $25, KEY_L = $26, KEY_Z = $2C, KEY_X = $2D, KEY_C = $2E, KEY_V = $2F, KEY_B = $30, KEY_N = $31, KEY_M = $32, KEY_MINUS = $0C, // "-" KEY_PLUS = $0D, // "+" KEY_LBRACKET = $1A, // "[" KEY_RBRACKET = $1B, // "]" KEY_SEMICOLON = $27, // ";" KEY_APOSTROPHE = $28, // '"' KEY_COMMA = $33, // "," KEY_PERIOD = $34, // "." KEY_NUMPAD0 = $52, KEY_NUMPAD1 = $4F, KEY_NUMPAD2 = $50, KEY_NUMPAD3 = $51, KEY_NUMPAD4 = $4B, KEY_NUMPAD5 = $4C, KEY_NUMPAD6 = $4D, KEY_NUMPAD7 = $47, KEY_NUMPAD8 = $48, KEY_NUMPAD9 = $49, KEY_NUMPADPERIOD = $53, // "." on numpad KEY_NUMPADENTER = $9C, // Enter on numpad KEY_NUMPADSTAR = $37, // "*" on numpad KEY_NUMPADPLUS = $4E, // "+" on numpad KEY_NUMPADMINUS = $4A, // "-" on numpad KEY_NUMPADSLASH = $B5, // "/" on numpad KEY_NUMLOCK = $45 // Num Lock on numpad ); function PluginInfo(): TPluginInfo; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function WindowMessage(): TWindowMessage; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function WindowMessage(msg: E_WINDOW_MESSAGE_TYPE; param1: Cardinal = 0; param2: Cardinal = 0; param3: Pointer = nil): TWindowMessage; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Color4(r,g,b,a: Single): TColor4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Color4(r,g,b,a: Byte): TColor4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Color4(color : Cardinal; alpha : Byte = 255): TColor4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Color4(): TColor4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Color4(const rgba: array of Single): TColor4; overload; function ColorRGB(Color: TColor4): Cardinal; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorRGBA(Color: TColor4): Cardinal; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorClear(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorWhite(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorBlack(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorRed(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorGreen(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorBlue(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorAqua(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorBrown(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorCyan(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorFuchsia(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorGray(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorGrey(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorMagenta(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorMaroon(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorNavy(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorOlive(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorOrange(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorPink(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorPurple(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorSilver(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorTeal(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorViolet(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorYellow(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorOfficialOrange(alpha: Byte = 255): TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ColorOfficialBlack(alpha: Byte = 255) : TColor4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point2(): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point2(x, y: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point2(All: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point2(const Floats: array of Single): TPoint2; overload; // TPoint2 operators function Add(const stLeft, stRight: TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Subtract(const stLeft, stRight: TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Multiply(const stLeft, stRight: TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Divide(const stLeft, stRight: TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Add(const stLeft: TPoint2; fRight: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Subtract(const stLeft: TPoint2; fRight: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Multiply(const stLeft: TPoint2; fRight: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Divide(const stLeft: TPoint2; fRight: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} // TPoint2 functions function Dot(const stLeft, stRight: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Cross(const stLeft, stRight: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistTo(const stLeft, stRight: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistToQ(const stLeft, stRight: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function LengthQ(stPoint: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Length(const stPoint: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Normalize(const stPoint: TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Lerp(const stLeft, stRight: TPoint2; coeff: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Angle(const stLeft, stRight: TPoint2): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Rotate(const stLeft: TPoint2; fAngle: Single): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Reflect(const stLeft, normal : TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point3(): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point3(x, y, z: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point3(All: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Point3(const Floats: array of Single): TPoint3; overload; // TPoint3 operators function Add(const stLeft, stRight: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Subtract(const stLeft, stRight: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Multiply(const stLeft, stRight: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Divide(const stLeft, stRight: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Add(const stLeft: TPoint3; fRight: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Subtract(const stLeft: TPoint3; fRight: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Multiply(const stLeft: TPoint3; fRight: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Divide(const stLeft: TPoint3; fRight: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} // TPoint3 functions function Dot(const stLeft, stRight: TPoint3): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Cross(const stLeft, stRight: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function FlatDistTo(const stLeft, stRight: TPoint3): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistTo(const stLeft, stRight: TPoint3): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DistToQ(const stLeft, stRight: TPoint3): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function LengthQ(const stPoint: TPoint3): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Length(const stPoint: TPoint3): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Normalize(const stPoint: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Lerp(const stLeft, stRight: TPoint3; coeff: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Angle(const stLeft, stRight: TPoint3): Single; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Rotate(const stLeft, Axis: TPoint3; fAngle: Single): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Reflect(const stLeft, normal : TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Vertex2(x,y,u,w,r,g,b,a : Single): TVertex2; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function RectF(): TRectf; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function RectF(x, y, width, height: Single): TRectf; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function RectF(const stLeftTop, stRightBottom: TPoint2): TRectf; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function IntersectRect(const stRect1, stRect2: TRectf):Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function PointInRect(const stPoint: TPoint2; const stRect: TRectf):Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function RectInRect(const stRect1, stRect2: TRectf): Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function GetIntersectionRect(const stRect1, stRect2: TRectf): TRectf; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Matrix(): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function Matrix(const RowMajorFloats: array of Single): TMatrix4x4; overload; function Matrix(_00, _01, _02, _03, _10, _11, _12, _13, _20, _21, _22, _23, _30, _31, _32, _33: Single): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixMulGL(stMLeft, stMRight : TMatrix4x4): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixInverse(const stMatrix : TMatrix4x4): TMatrix4x4; function MatrixTranspose(const stMatrix : TMatrix4x4): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixIdentity(): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixScale(const fVec : TPoint3): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixTranslate(const fVec : TPoint3): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixRotate(angle : Single; const stAxis : TPoint3): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixBillboard(const stMatrix : TMatrix4x4): TMatrix4x4; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure Decompose(const stMatrix : TMatrix4x4; out stScale: TPoint3; out stRotation: TMatrix4x4; out stTranslation: TPoint3); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} // Matrix operators function MatrixSub(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixAdd(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixMul(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixSub(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixAdd(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixDiv(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function MatrixMul(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ApplyToPoint(const stLeftMatrix: TMatrix4x4; stPoint: TPoint3): TPoint3; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ApplyToPoint(const stLeftMatrix: TMatrix4x4; stPoint: TPoint2): TPoint2; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function ApplyToVector(const stLeftMatrix: TMatrix4x4; stPoint: TPoint3): TPoint3; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function EngineWindow(): TEngineWindow; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function EngineWindow(uiWidth, uiHeight: Integer; bFullScreen: Boolean; bVSync: Boolean = False; eMSampling: {E_MULTISAMPLING_MODE}Cardinal = MM_NONE; uiFlags: {ENG_WINDOW_FLAGS}Integer = EWF_DEFAULT): TEngineWindow; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} // TVariant operations procedure Clear(var AVar: TVariant); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetInt(var AVar: TVariant; iVal: Integer); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetFloat(var AVar: TVariant; fVal: Single); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetBool(var AVar: TVariant; bVal: Boolean); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetPointer(var AVar: TVariant; pPointer: Pointer); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure SetData(var AVar: TVariant; pData: Pointer; uiDataSize: Cardinal); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsInt(var AVar: TVariant): Integer; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsFloat(var AVar: TVariant): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsBool(var AVar: TVariant): Boolean; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function AsPointer(var AVar: TVariant): Pointer; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} procedure GetData(var AVar: TVariant;out pData: Pointer; out uiDataSize: Cardinal); {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function GetType(var AVar: TVariant): E_DGLE_VARIANT_TYPE; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} implementation uses Math, DGLE; // gets constants about SDK function Color4(r,g,b,a: Single): TColor4; begin Result.r := r; Result.g := g; Result.b := b; Result.a := a; end; function Color4(r,g,b,a: Byte): TColor4; overload; begin Result.r := r/255.; Result.g := g/255.; Result.b := b/255.; Result.a := a/255.; end; function Color4(color : Cardinal; alpha : Byte = 255): TColor4; overload; begin Result.r := Byte(color)/255.; Result.g := Byte(color shr 8)/255.; Result.b := Byte(color shr 16)/255.; Result.a := alpha/255.; end; function Color4(): TColor4; overload; begin Result.r := 1.; Result.g := 1.; Result.b := 1.; Result.a := 1.; end; function Color4(const rgba: array of Single): TColor4; begin Result.r := rgba[0]; Result.g := rgba[1]; Result.b := rgba[2]; Result.a := rgba[3]; end; function ColorRGB(Color: TColor4): Cardinal; begin Result := Round($FF * Color.r) + (Round($FF * Color.g) shl 8) + (Round($FF * Color.b) shl 16); end; function ColorRGBA(Color: TColor4): Cardinal; begin Result := ColorRGB(Color) + (Round($FF * Color.a) shl 24); end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TColor4.Create(var dummy); begin Self := Color4(); end; constructor TColor4.Create(ui32ABGR: Cardinal); begin Self := Color4(ui32ABGR); end; constructor TColor4.Create(ui32RGB: Cardinal; ubA: byte); begin Self := Color4(ui32RGB, ubA); end; constructor TColor4.Create(ubR, ubG, ubB, ubA: Byte); begin Self := Color4(ubR, ubG, ubB, ubA); end; constructor TColor4.Create(fR, fG, fB, fA: Single); begin Self := Color4(fR, fG, fB, fA); end; constructor TColor4.Create(const rgba: array of Single); begin Self := Color4(rgba); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} procedure TColor4.SetColorF(fR, fG, fB, fA: Single); begin Self := Color4(fR, fG, fB, fA); end; procedure TColor4.SetColorB(ubR, ubG, ubB, ubA: Byte); begin Self := Color4(ubR, ubG, ubB, ubA); end; function TColor4.ColorRGB(): Cardinal; begin Result := Round($FF * r) + (Round($FF * g) shl 8) + (Round($FF * b) shl 16); end; function TColor4.ColorRGBA(): Cardinal; begin Result := ColorRGB + (Round($FF * a) shl 24); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator TColor4.{$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(Color: TColor4): Cardinal; begin Result := Color.ColorRGBA(); end; {$ENDIF} function ColorClear(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $00, $00, alpha); end; function ColorWhite(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $FF, $FF, alpha); end; function ColorBlack(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $00, $00, alpha); end; function ColorRed(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $00, $00, alpha); end; function ColorGreen(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $FF, $00, alpha); end; function ColorBlue(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $00, $FF, alpha); end; function ColorAqua(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $FF, $FF, alpha); end; function ColorBrown(alpha: Byte = 255) : TColor4; begin Result := Color4($A5, $2A, $2A, alpha); end; function ColorCyan(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $FF, $FF, alpha); end; function ColorFuchsia(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $00, $FF, alpha); end; function ColorGray(alpha: Byte = 255) : TColor4; begin Result := Color4($80, $80, $80, alpha); end; function ColorGrey(alpha: Byte = 255) : TColor4; begin Result := Color4($80, $80, $80, alpha); end; function ColorMagenta(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $00, $FF, alpha); end; function ColorMaroon(alpha: Byte = 255) : TColor4; begin Result := Color4($80, $00, $00, alpha); end; function ColorNavy(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $00, $80, alpha); end; function ColorOlive(alpha: Byte = 255) : TColor4; begin Result := Color4($80, $80, $00, alpha); end; function ColorOrange(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $A5, $00, alpha); end; function ColorPink(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $C0, $CB, alpha); end; function ColorPurple(alpha: Byte = 255) : TColor4; begin Result := Color4($80, $00, $80, alpha); end; function ColorSilver(alpha: Byte = 255) : TColor4; begin Result := Color4($C0, $C0, $C0, alpha); end; function ColorTeal(alpha: Byte = 255) : TColor4; begin Result := Color4($00, $80, $80, alpha); end; function ColorViolet(alpha: Byte = 255) : TColor4; begin Result := Color4($EE, $82, $EE, alpha); end; function ColorYellow(alpha: Byte = 255) : TColor4; begin Result := Color4($FF, $FF, $00, alpha); end; function ColorOfficialOrange(alpha: Byte = 255): TColor4; begin Result := Color4($E7, $78, $17, alpha); end; function ColorOfficialBlack(alpha: Byte = 255) : TColor4; begin Result := Color4($38, $34, $31, alpha); end; function Point2(): TPoint2; overload; begin Result.x := 0.; Result.y := 0.; end; function Point2(x, y: Single): TPoint2; overload; begin Result.x := x; Result.y := y; end; function Point2(All: Single): TPoint2; overload; begin Result.x := All; Result.y := All; end; function Point2(const Floats: array of Single): TPoint2; overload; begin Assert(System.Length(Floats) = 2); Result.x := Floats[Low(Floats)]; Result.y := Floats[Low(Floats) + 1]; end; function Add(const stLeft, stRight: TPoint2): TPoint2; begin Result := Point2(stLeft.x + stRight.x, stLeft.y + stRight.y); end; function Subtract(const stLeft, stRight: TPoint2): TPoint2; begin Result := Point2(stLeft.x - stRight.x, stLeft.y - stRight.y); end; function Multiply(const stLeft, stRight: TPoint2): TPoint2; begin Result := Point2(stLeft.x * stRight.x, stLeft.y * stRight.y); end; function Divide(const stLeft, stRight: TPoint2): TPoint2; begin Result := Point2(stLeft.x / stRight.x, stLeft.y / stRight.y); end; function Add(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := Point2(stLeft.x + fRight, stLeft.y + fRight); end; function Subtract(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := Point2(stLeft.x - fRight, stLeft.y - fRight); end; function Multiply(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := Point2(stLeft.x * fRight, stLeft.y * fRight); end; function Divide(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := Point2(stLeft.x / fRight, stLeft.y / fRight); end; {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator TPoint2.{$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; begin Result := DGLE_Types.Add(stLeft, stRight); end; class operator TPoint2.{$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; begin Result := DGLE_Types.Subtract(stLeft, stRight); end; class operator TPoint2.{$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; begin Result := DGLE_Types.Multiply(stLeft, stRight); end; class operator TPoint2.{$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft, stRight: TPoint2): TPoint2; begin Result := DGLE_Types.Divide(stLeft, stRight); end; class operator TPoint2.{$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := DGLE_Types.Add(stLeft, fRight); end; class operator TPoint2.{$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := DGLE_Types.Subtract(stLeft, fRight); end; class operator TPoint2.{$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := DGLE_Types.Multiply(stLeft, fRight); end; class operator TPoint2.{$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft: TPoint2; fRight: Single): TPoint2; begin Result := DGLE_Types.Divide(stLeft, fRight); end; {$ENDIF} function Dot(const stLeft, stRight: TPoint2): Single; begin Result := stLeft.x * stRight.x + stLeft.y * stRight.y; end; function Cross(const stLeft, stRight: TPoint2): Single; begin Result := stLeft.x * stRight.y - stRight.x * stLeft.y; end; function DistTo(const stLeft, stRight: TPoint2): Single; begin Result := Sqrt(Sqr(stRight.x - stLeft.x) + Sqr(stRight.y - stLeft.y)); end; function DistToQ(const stLeft, stRight: TPoint2): Single; begin Result := LengthQ(Subtract(stRight, stLeft)); end; function LengthQ(stPoint: TPoint2): Single; begin Result := Sqr(stPoint.x) + Sqr(stPoint.y); end; function Length(const stPoint: TPoint2): Single; begin Result := Sqrt(LengthQ(stPoint)); end; function Normalize(const stPoint: TPoint2): TPoint2; begin Result := Divide(stPoint, Length(stPoint)); end; function Lerp(const stLeft, stRight: TPoint2; coeff: Single): TPoint2; begin Result := Add(stLeft, Multiply(Subtract(stRight, stLeft), coeff)); end; function Angle(const stLeft, stRight: TPoint2): Single; begin Result := ArcTan2(stLeft.x * stRight.y - stLeft.y * stRight.x, stLeft.x * stRight.x + stLeft.y * stRight.y); end; function Rotate(const stLeft: TPoint2; fAngle: Single): TPoint2; var s, c: Single; begin s := Sin(fAngle); c := Cos(fAngle); Result := Point2(stLeft.x * c - stLeft.y * s, stLeft.x * s + stLeft.y * c); end; function Reflect(const stLeft, normal : TPoint2): TPoint2; begin Result := Subtract(stLeft, Multiply(normal, Dot(stLeft, normal) * 2)); end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TPoint2.Create(var dummy); begin Self := Point2(); end; constructor TPoint2.Create(x, y : Single); begin Self := Point2(x, y); end; constructor TPoint2.Create(All: Single); begin Self := Point2(All); end; constructor TPoint2.Create(const Floats: array of Single); begin Self := Point2(Floats); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} function TPoint2.Dot(const stPoint: TPoint2): Single; begin Result := DGLE_Types.Dot(Self, stPoint); end; function TPoint2.Cross(const stPoint: TPoint2): Single; begin Result := DGLE_Types.Cross(Self, stPoint); end; function TPoint2.DistTo(const stPoint: TPoint2): Single; begin Result := DGLE_Types.DistTo(Self, stPoint); end; function TPoint2.DistToQ(const stPoint: TPoint2): Single; begin Result := DGLE_Types.DistToQ(Self, stPoint); end; function TPoint2.LengthQ(): Single; begin Result := DGLE_Types.LengthQ(Self); end; function TPoint2.Length(): Single; begin Result := DGLE_Types.Length(Self); end; function TPoint2.Normalize(): TPoint2; begin Self := DGLE_Types.Normalize(Self); Result := Self; end; function TPoint2.Lerp(const stPoint: TPoint2; coeff: Single): TPoint2; begin Result := DGLE_Types.Lerp(Self, stPoint, coeff); end; function TPoint2.Angle(const stPoint: TPoint2): Single; begin Result := DGLE_Types.Angle(Self, stPoint); end; function TPoint2.Rotate(fAngle: Single): TPoint2; begin Result := DGLE_Types.Rotate(Self, fAngle); end; function TPoint2.Reflect(const normal : TPoint2): TPoint2; begin Result := DGLE_Types.Reflect(Self, normal); end; {$ENDIF} function Point3(): TPoint3; overload; begin Result.x := 0.; Result.y := 0.; Result.z := 0.; end; function Point3(x, y, z: Single): TPoint3; overload; begin Result.x := x; Result.y := y; Result.z := z; end; function Point3(All: Single): TPoint3; overload; begin Result.x := All; Result.y := All; Result.z := All; end; function Point3(const Floats: array of Single): TPoint3; overload; begin Assert(System.Length(Floats) = 3); Result.x := Floats[Low(Floats)]; Result.y := Floats[Low(Floats) + 1]; Result.z := Floats[Low(Floats) + 2]; end; function Add(const stLeft, stRight: TPoint3): TPoint3; begin Result := Point3(stLeft.x + stRight.x, stLeft.y + stRight.y, stLeft.z + stRight.z); end; function Subtract(const stLeft, stRight: TPoint3): TPoint3; begin Result := Point3(stLeft.x - stRight.x, stLeft.y - stRight.y, stLeft.z - stRight.z); end; function Multiply(const stLeft, stRight: TPoint3): TPoint3; begin Result := Point3(stLeft.x * stRight.x, stLeft.y * stRight.y, stLeft.z * stRight.z); end; function Divide(const stLeft, stRight: TPoint3): TPoint3; begin Result := Point3(stLeft.x / stRight.x, stLeft.y / stRight.y, stLeft.z / stRight.z); end; function Add(const stLeft: TPoint3; fRight: Single): TPoint3; begin Result := Point3(stLeft.x + fRight, stLeft.y + fRight, stLeft.z + fRight); end; function Subtract(const stLeft: TPoint3; fRight: Single): TPoint3; begin Result := Point3(stLeft.x - fRight, stLeft.y - fRight, stLeft.z - fRight); end; function Multiply(const stLeft: TPoint3; fRight: Single): TPoint3; begin Result := Point3(stLeft.x * fRight, stLeft.y * fRight, stLeft.z * fRight); end; function Divide(const stLeft: TPoint3; fRight: Single): TPoint3; begin Result := Point3(stLeft.x / fRight, stLeft.y / fRight, stLeft.z / fRight); end; {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator TPoint3.{$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; begin Result := DGLE_Types.Add(stLeft, stRight); end; class operator TPoint3.{$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; begin Result := DGLE_Types.Subtract(stLeft, stRight); end; class operator TPoint3.{$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; begin Result := DGLE_Types.Multiply(stLeft, stRight); end; class operator TPoint3.{$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft, stRight: TPoint3): TPoint3; begin Result := DGLE_Types.Divide(stLeft, stRight); end; class operator TPoint3.{$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeft: TPoint3;const fRight: Single): TPoint3; begin Result := DGLE_Types.Add(stLeft, fRight); end; class operator TPoint3.{$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; begin Result := DGLE_Types.Subtract(stLeft, fRight); end; class operator TPoint3.{$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; begin Result := DGLE_Types.Multiply(stLeft, fRight); end; class operator TPoint3.{$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeft: TPoint3; const fRight: Single): TPoint3; begin Result := DGLE_Types.Divide(stLeft, fRight); end; {$ENDIF} function Dot(const stLeft, stRight: TPoint3): Single; begin Result := stLeft.x * stRight.x + stLeft.y * stRight.y + stLeft.z * stRight.z; end; function Cross(const stLeft, stRight: TPoint3): TPoint3; begin Result := Point3(stLeft.y * stRight.z - stLeft.z * stRight.y, stLeft.z * stRight.x - stLeft.x * stRight.z, stLeft.x * stRight.y - stLeft.y * stRight.x); end; function FlatDistTo(const stLeft, stRight: TPoint3): Single; begin Result := Sqrt(Sqr(stRight.x - stLeft.x) + Sqr(stRight.y - stLeft.y)); end; function DistTo(const stLeft, stRight: TPoint3): Single; begin Result := Sqrt(Sqr(stRight.x - stLeft.x) + Sqr(stRight.y - stLeft.y) + Sqr(stRight.z - stLeft.z)); end; function DistToQ(const stLeft, stRight: TPoint3): Single; begin Result := LengthQ(Subtract(stRight, stLeft)); end; function LengthQ(const stPoint: TPoint3): Single; begin Result := Sqr(stPoint.x) + Sqr(stPoint.y) + Sqr(stPoint.z); end; function Length(const stPoint: TPoint3): Single; begin Result := Sqrt(LengthQ(stPoint)); end; function Normalize(const stPoint: TPoint3): TPoint3; begin Result := Divide(stPoint, Length(stPoint)); end; function Lerp(const stLeft, stRight: TPoint3; coeff: Single): TPoint3; begin Result := Add(stLeft, Multiply(Subtract(stRight, stLeft), coeff)); end; function Angle(const stLeft, stRight: TPoint3): Single; begin Result := ArcCos(Dot (stLeft, stRight)/ Sqrt(LengthQ(stLeft) * LengthQ(stRight))); end; function Rotate(const stLeft, Axis: TPoint3; fAngle: Single): TPoint3; var s, c: Single; v: array[0..2] of TPoint3; begin s := sin(fAngle); c := cos(fAngle); v[0] := Multiply(Axis, Dot(stLeft, Axis)); v[1] := Subtract(stLeft, v[0]); v[2] := Cross(Axis, v[1]); Result := Point3(v[0].x + v[1].x * c + v[2].x * s, v[0].y + v[1].y * c + v[2].y * s, v[0].z + v[1].z * c + v[2].z * s); end; function Reflect(const stLeft, normal : TPoint3): TPoint3; begin Result := Subtract(stLeft, Multiply(normal, Dot(stLeft,normal) * 2)); end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TPoint3.Create (var dummy); begin Self := Point3(); end; constructor TPoint3.Create (x, y, z : Single); begin Self := Point3(x, y, z); end; constructor TPoint3.Create (All: Single); begin Self := Point3(All); end; constructor TPoint3.Create (const Floats: array of Single); begin Self := Point3(Floats); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} function TPoint3.Dot(const stPoint: TPoint3): Single; begin Result := DGLE_Types.Dot(Self, stPoint); end; function TPoint3.Cross(const stPoint: TPoint3): TPoint3; begin Result := DGLE_Types.Cross(Self, stPoint); end; function TPoint3.FlatDistTo(const stPoint: TPoint3): Single; begin Result := DGLE_Types.FlatDistTo(Self, stPoint); end; function TPoint3.DistTo(const stPoint: TPoint3): Single; begin Result := DGLE_Types.DistTo(Self, stPoint); end; function TPoint3.DistToQ(const stPoint: TPoint3): Single; begin Result := DGLE_Types.DistToQ(Self, stPoint); end; function TPoint3.LengthQ(): Single; begin Result := DGLE_Types.LengthQ(Self); end; function TPoint3.Length(): Single; begin Result := DGLE_Types.Length(Self); end; function TPoint3.Normalize(): TPoint3; begin Self := DGLE_Types.Normalize(Self); Result := Self; end; function TPoint3.Lerp(const stPoint: TPoint3; coeff: Single): TPoint3; begin Result := DGLE_Types.Lerp(Self, stPoint, coeff); end; function TPoint3.Angle(const stPoint: TPoint3): Single; begin Result := DGLE_Types.Angle(Self, stPoint); end; function TPoint3.Rotate(const Axis: TPoint3; fAngle: Single): TPoint3; begin Result := DGLE_Types.Rotate(Self, Axis, fAngle); end; function TPoint3.Reflect(const normal : TPoint3): TPoint3; begin Result := DGLE_Types.Reflect(Self, normal); end; {$ENDIF} function Vertex2(x,y,u,w,r,g,b,a : Single): TVertex2; begin Result.x := x; Result.y := y; Result.u := u; Result.w := w; Result.r := r; Result.g := g; Result.b := b; Result.a := a; end; function RectF(x, y, width, height : Single): TRectf; overload; begin Result.x := x; Result.y := y; Result.width := width; Result.height := height; end; function RectF(): TRectf; overload; begin Result.x := 0; Result.y := 0; Result.width := 0; Result.height := 0; end; function RectF(const stLeftTop, stRightBottom: TPoint2): TRectf; overload; begin Result.x := stLeftTop.x; Result.y := stLeftTop.y; Result.width := stRightBottom.x - stLeftTop.x; Result.height := stRightBottom.y - stLeftTop.y; end; function IntersectRect(const stRect1, stRect2 : TRectf):Boolean; begin Result := ((stRect1.x < stRect2.x + stRect2.width) and (stRect1.x + stRect1.width > stRect2.x) and (stRect1.y < stRect2.y + stRect2.height) and (stRect1.y + stRect1.height > stRect2.y)) or ((stRect2.x + stRect2.width < stRect1.x) and (stRect2.x > stRect1.x + stRect1.width) and (stRect2.y + stRect2.height < stRect1.y) and (stRect2.y > stRect1.y + stRect1.height)); end; function PointInRect(const stPoint : TPoint2; const stRect : TRectf):Boolean; begin Result := (stPoint.x > stRect.x) and (stPoint.x < stRect.x + stRect.width) and (stPoint.y > stRect.y) and (stPoint.y < stRect.y + stRect.height); end; function RectInRect(const stRect1, stRect2 : TRectf): Boolean; begin Result := (stRect1.x < stRect2.x) and (stRect1.y < stRect2.y) and (stRect1.x + stRect1.width > stRect2.x + stRect2.width) and (stRect1.y + stRect1.height > stRect2.y + stRect2.height); end; function GetIntersectionRect(const stRect1, stRect2: TRectf): TRectf; begin Result := stRect1; if stRect2.x > stRect1.x then Result.x := stRect2.x; if stRect2.y > stRect1.y then Result.y := stRect2.y; Result.width := Min(stRect2.x + stRect2.width, stRect1.x+ stRect1.width) - Result.x; Result.height := Min(stRect2.y + stRect2.height, stRect1.y + stRect1.height) - Result.y; if (Result.width <= 0) or (Result.height <= 0) then Result := Rectf; end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TRectF.Create(var dummy); begin Self := RectF(); end; constructor TRectF.Create(x, y, width, height : Single); begin Self := RectF(x, y, width, height); end; constructor TRectF.Create(const stLeftTop, stRightBottom: TPoint2); begin Self := RectF(stLeftTop, stRightBottom); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDMETHODS} function TRectF.IntersectRect(const stRect: TRectf):Boolean; begin Result := DGLE_Types.IntersectRect(Self, stRect); end; function TRectF.PointInRect(const stPoint: TPoint2):Boolean; begin Result := DGLE_Types.PointInRect(stPoint, Self); end; function TRectF.RectInRect(const stRect: TRectf): Boolean; begin Result := DGLE_Types.RectInRect(Self, stRect); end; function TRectF.GetIntersectionRect(const stRect: TRectf): TRectf; begin Result := DGLE_Types.GetIntersectionRect(Self, stRect); end; {$ENDIF} function Matrix(): TMatrix4x4; begin ZeroMemory(@Result._1D, 16 * SizeOf(Single)); end; function Matrix(const RowMajorFloats: array of Single): TMatrix4x4; var I: Integer; begin Assert(System.Length(RowMajorFloats) = 16); for I := 0 to 15 do Result._1D[I] := RowMajorFloats[i]; end; function Matrix(_00, _01, _02, _03, _10, _11, _12, _13, _20, _21, _22, _23, _30, _31, _32, _33: Single): TMatrix4x4; begin Result := Matrix([_00, _01, _02, _03, _10, _11, _12, _13, _20, _21, _22, _23, _30, _31, _32, _33]); end; function MatrixMulGL(stMLeft, stMRight : TMatrix4x4): TMatrix4x4; begin Result := MatrixMul(stMRight, stMLeft); end; function MatrixInverse(const stMatrix : TMatrix4x4): TMatrix4x4; { TODO : Refactor routine due to FreePascal "not portable int-ptr cast" warning } type MatrixRows = array[0..7] of Single; PMatrixRows = ^MatrixRows; var mat : array[0..3] of MatrixRows; rows : array[0..3] of PMatrixRows; i, r, row_num, c : Integer; major, cur_ABS, factor : Single; begin mat[0, 0] := stMatrix._2D[0][0]; mat[0, 1] := stMatrix._2D[0][1]; mat[0, 2] := stMatrix._2D[0][2]; mat[0, 3] := stMatrix._2D[0][3]; mat[0, 4] := 1.0; mat[0, 5] := 0.0; mat[0, 6] := 0.0; mat[0, 7] := 0.0; mat[1, 0] := stMatrix._2D[1][0]; mat[1, 1] := stMatrix._2D[1][1]; mat[1, 2] := stMatrix._2D[1][2]; mat[1, 3] := stMatrix._2D[1][3]; mat[1, 4] := 0.0; mat[1, 5] := 1.0; mat[1, 6] := 0.0; mat[1, 7] := 0.0; mat[2, 0] := stMatrix._2D[2][0]; mat[2, 1] := stMatrix._2D[2][1]; mat[2, 2] := stMatrix._2D[2][2]; mat[2, 3] := stMatrix._2D[2][3]; mat[2, 4] := 0.0; mat[2, 5] := 0.0; mat[2, 6] := 1.0; mat[2, 7] := 0.0; mat[3, 0] := stMatrix._2D[3][0]; mat[3, 1] := stMatrix._2D[3][1]; mat[3, 2] := stMatrix._2D[3][2]; mat[3, 3] := stMatrix._2D[3][3]; mat[3, 4] := 0.0; mat[3, 5] := 0.0; mat[3, 6] := 0.0; mat[3, 7] := 1.0; rows[0] := PMatrixRows(@mat[0]); rows[1] := PMatrixRows(@mat[1]); rows[2] := PMatrixRows(@mat[2]); rows[3] := PMatrixRows(@mat[3]); for i := 0 to 3 do begin row_num := i; major := Abs(rows[i]^[i]); for r := i + 1 to 3 do begin cur_ABS := Abs(rows[r]^[i]); if cur_ABS > major then begin major := cur_ABS; row_num := r; end; end; if row_num <> i then begin rows[i] := Pointer(Integer(rows[i]) xor Integer(rows[row_num])); rows[row_num] := Pointer(Integer(rows[i]) xor Integer(rows[row_num])); rows[i] := Pointer(Integer(rows[i]) xor Integer(rows[row_num])); end; for r := i + 1 to 3 do begin factor := rows[r]^[i] / rows[i]^[i]; for c := i to 7 do rows[r]^[c] := rows[r]^[c] - factor * rows[i]^[c]; end; end; for i := 3 downto 1 do for r := 0 to i - 1 do begin factor := rows[r]^[i] / rows[i]^[i]; for c := 4 to 7 do rows[r]^[c] := rows[r]^[c] - factor * rows[i]^[c]; end; Result._2D[0, 0] := rows[0]^[4] / rows[0]^[0]; Result._2D[0, 1] := rows[0]^[5] / rows[0]^[0]; Result._2D[0, 2] := rows[0]^[6] / rows[0]^[0]; Result._2D[0, 3] := rows[0]^[7] / rows[0]^[0]; Result._2D[1, 0] := rows[1]^[4] / rows[1]^[1]; Result._2D[1, 1] := rows[1]^[5] / rows[1]^[1]; Result._2D[1, 2] := rows[1]^[6] / rows[1]^[1]; Result._2D[1, 3] := rows[1]^[7] / rows[1]^[1]; Result._2D[2, 0] := rows[2]^[4] / rows[2]^[2]; Result._2D[2, 1] := rows[2]^[5] / rows[2]^[2]; Result._2D[2, 2] := rows[2]^[6] / rows[2]^[2]; Result._2D[2, 3] := rows[2]^[7] / rows[2]^[2]; Result._2D[3, 0] := rows[3]^[4] / rows[3]^[3]; Result._2D[3, 1] := rows[3]^[5] / rows[3]^[3]; Result._2D[3, 2] := rows[3]^[6] / rows[3]^[3]; Result._2D[3, 3] := rows[3]^[7] / rows[3]^[3]; end; function MatrixTranspose(const stMatrix : TMatrix4x4): TMatrix4x4; begin Result._2D[0, 0] := stMatrix._2D[0, 0]; Result._2D[0, 1] := stMatrix._2D[1, 0]; Result._2D[0, 2] := stMatrix._2D[2, 0]; Result._2D[0, 3] := stMatrix._2D[3, 0]; Result._2D[1, 0] := stMatrix._2D[0, 1]; Result._2D[1, 1] := stMatrix._2D[1, 1]; Result._2D[1, 2] := stMatrix._2D[2, 1]; Result._2D[1, 3] := stMatrix._2D[3, 1]; Result._2D[2, 0] := stMatrix._2D[0, 2]; Result._2D[2, 1] := stMatrix._2D[1, 2]; Result._2D[2, 2] := stMatrix._2D[2, 2]; Result._2D[2, 3] := stMatrix._2D[3, 2]; Result._2D[3, 0] := stMatrix._2D[0, 3]; Result._2D[3, 1] := stMatrix._2D[1, 3]; Result._2D[3, 2] := stMatrix._2D[2, 3]; Result._2D[3, 3] := stMatrix._2D[3, 3]; end; function MatrixIdentity(): TMatrix4x4; begin Result := MatrixScale(Point3(1.0,1.0,1.0)); end; function MatrixScale(const fVec : TPoint3): TMatrix4x4; begin Result._2D[0, 0] := fVec.x; Result._2D[0, 1] := 0.0; Result._2D[0, 2] := 0.0; Result._2D[0, 3] := 0.0; Result._2D[1, 0] := 0.0; Result._2D[1, 1] := fVec.y; Result._2D[1, 2] := 0.0; Result._2D[1, 3] := 0.0; Result._2D[2, 0] := 0.0; Result._2D[2, 1] := 0.0; Result._2D[2, 2] := fVec.z; Result._2D[2, 3] := 0.0; Result._2D[3, 0] := 0.0; Result._2D[3, 1] := 0.0; Result._2D[3, 2] := 0.0; Result._2D[3, 3] := 1.0; end; function MatrixTranslate(const fVec : TPoint3): TMatrix4x4; begin Result := MatrixIdentity(); Result._1D[12] := fVec.x; Result._1D[13] := fVec.y; Result._1D[14] := fVec.z; end; function MatrixRotate(angle : Single; const stAxis : TPoint3): TMatrix4x4; var axis_norm, x, y, z, sin_angle, cos_angle : Single; begin axis_norm := sqrt(stAxis.x * stAxis.x + stAxis.y * stAxis.y + stAxis.z * stAxis.z); x := stAxis.x / axis_norm; y := stAxis.y / axis_norm; z := stAxis.z / axis_norm; sin_angle := sin(angle*Pi/180.0); cos_angle := cos(angle*Pi/180.0); Result := MatrixIdentity(); Result._2D[0][0] := (1.0 - x * x) * cos_angle + x * x; Result._2D[0][1] := z * sin_angle + x * y * (1.0 - cos_angle); Result._2D[0][2] := x * z * (1.0 - cos_angle) - y * sin_angle; Result._2D[1][0] := x * y * (1.0 - cos_angle) - z * sin_angle; Result._2D[1][1] := (1.0 - y * y) * cos_angle + y * y; Result._2D[1][2] := y * z * (1.0 - cos_angle) + x * sin_angle; Result._2D[2][0] := x * z * (1.0 - cos_angle) + y * sin_angle; Result._2D[2][1] := y * z * (1.0 - cos_angle) - x * sin_angle; Result._2D[2][2] := (1.0 - z * z) * cos_angle + z * z; end; function RowFactor(const M : TMatrix4x4; X: Integer): Single; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} begin Result := DGLE_Types.Length(Point3(M._2D[0, X], M._2D[1, X], M._2D[2, X])) * Sign(M._2D[0, X] * M._2D[1, X] * M._2D[2, X] * M._2D[3, X]); end; function MatrixBillboard(const stMatrix : TMatrix4x4): TMatrix4x4; begin Result := Matrix(); Result._2D[3, 0] := stMatrix._2D[3, 0]; Result._2D[3, 1] := stMatrix._2D[3, 1]; Result._2D[3, 2] := stMatrix._2D[3, 2]; Result._2D[0, 3] := stMatrix._2D[0, 3]; Result._2D[1, 3] := stMatrix._2D[1, 3]; Result._2D[2, 3] := stMatrix._2D[2, 3]; Result._2D[3, 3] := stMatrix._2D[3, 3]; Result._2D[0, 0] := RowFactor(stMatrix, 0); Result._2D[1, 1] := RowFactor(stMatrix, 1); Result._2D[2, 2] := RowFactor(stMatrix, 2); end; procedure Decompose(const stMatrix : TMatrix4x4; out stScale: TPoint3; out stRotation: TMatrix4x4; out stTranslation: TPoint3); begin stTranslation.x := stMatrix._2D[3][0]; stTranslation.y := stMatrix._2D[3][1]; stTranslation.z := stMatrix._2D[3][2]; stScale.x := RowFactor(stMatrix, 0); stScale.y := RowFactor(stMatrix, 1); stScale.z := RowFactor(stMatrix, 2); if (stScale.x = 0) or (stScale.x = 0) or (stScale.x = 0) then stRotation := Matrix() else stRotation := Matrix( stMatrix._2D[0][0] / stScale.x, stMatrix._2D[0][1] / stScale.x, stMatrix._2D[0][2] / stScale.x, 0, stMatrix._2D[1][0] / stScale.y, stMatrix._2D[1][1] / stScale.y, stMatrix._2D[1][2] / stScale.y, 0, stMatrix._2D[2][0] / stScale.z, stMatrix._2D[2][1] / stScale.z, stMatrix._2D[2][2] / stScale.z, 0, 0, 0, 0, 1); end; function MatrixSub(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; var i: Integer; begin Result := Matrix(); for i := 0 to 15 do begin Result._1D[i] := stLeftMatrix._1D[i] - stRightMatrix._1D[i]; end; end; function MatrixAdd(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; var i: Integer; begin Result := Matrix(); for i := 0 to 15 do begin Result._1D[i] := stLeftMatrix._1D[i] + stRightMatrix._1D[i]; end; end; function MatrixMul(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; //var // i, j, k: Integer; begin Result := Matrix(); // for i := 0 to 3 do // for j := 0 to 3 do // for k := 0 to 3 do // Result._2D[i][j] := Result._2D[i][j] + stLeftMatrix._2D[i][k] * stRightMatrix._2D[k][j]; {This BLOCK of code, instead of cycle, makes very nice performance improvement} Result._2D[0][0] := stLeftMatrix._2D[0][0] * stRightMatrix._2D[0][0] + stLeftMatrix._2D[0][1] * stRightMatrix._2D[1][0] + stLeftMatrix._2D[0][2] * stRightMatrix._2D[2][0] + stLeftMatrix._2D[0][3] * stRightMatrix._2D[3][0]; Result._2D[1][0] := stLeftMatrix._2D[1][0] * stRightMatrix._2D[0][0] + stLeftMatrix._2D[1][1] * stRightMatrix._2D[1][0] + stLeftMatrix._2D[1][2] * stRightMatrix._2D[2][0] + stLeftMatrix._2D[1][3] * stRightMatrix._2D[3][0]; Result._2D[2][0] := stLeftMatrix._2D[2][0] * stRightMatrix._2D[0][0] + stLeftMatrix._2D[2][1] * stRightMatrix._2D[1][0] + stLeftMatrix._2D[2][2] * stRightMatrix._2D[2][0] + stLeftMatrix._2D[2][3] * stRightMatrix._2D[3][0]; Result._2D[3][0] := stLeftMatrix._2D[3][0] * stRightMatrix._2D[0][0] + stLeftMatrix._2D[3][1] * stRightMatrix._2D[1][0] + stLeftMatrix._2D[3][2] * stRightMatrix._2D[2][0] + stLeftMatrix._2D[3][3] * stRightMatrix._2D[3][0]; Result._2D[0][1] := stLeftMatrix._2D[0][0] * stRightMatrix._2D[0][1] + stLeftMatrix._2D[0][1] * stRightMatrix._2D[1][1] + stLeftMatrix._2D[0][2] * stRightMatrix._2D[2][1] + stLeftMatrix._2D[0][3] * stRightMatrix._2D[3][1]; Result._2D[1][1] := stLeftMatrix._2D[1][0] * stRightMatrix._2D[0][1] + stLeftMatrix._2D[1][1] * stRightMatrix._2D[1][1] + stLeftMatrix._2D[1][2] * stRightMatrix._2D[2][1] + stLeftMatrix._2D[1][3] * stRightMatrix._2D[3][1]; Result._2D[2][1] := stLeftMatrix._2D[2][0] * stRightMatrix._2D[0][1] + stLeftMatrix._2D[2][1] * stRightMatrix._2D[1][1] + stLeftMatrix._2D[2][2] * stRightMatrix._2D[2][1] + stLeftMatrix._2D[2][3] * stRightMatrix._2D[3][1]; Result._2D[3][1] := stLeftMatrix._2D[3][0] * stRightMatrix._2D[0][1] + stLeftMatrix._2D[3][1] * stRightMatrix._2D[1][1] + stLeftMatrix._2D[3][2] * stRightMatrix._2D[2][1] + stLeftMatrix._2D[3][3] * stRightMatrix._2D[3][1]; Result._2D[0][2] := stLeftMatrix._2D[0][0] * stRightMatrix._2D[0][2] + stLeftMatrix._2D[0][1] * stRightMatrix._2D[1][2] + stLeftMatrix._2D[0][2] * stRightMatrix._2D[2][2] + stLeftMatrix._2D[0][3] * stRightMatrix._2D[3][2]; Result._2D[1][2] := stLeftMatrix._2D[1][0] * stRightMatrix._2D[0][2] + stLeftMatrix._2D[1][1] * stRightMatrix._2D[1][2] + stLeftMatrix._2D[1][2] * stRightMatrix._2D[2][2] + stLeftMatrix._2D[1][3] * stRightMatrix._2D[3][2]; Result._2D[2][2] := stLeftMatrix._2D[2][0] * stRightMatrix._2D[0][2] + stLeftMatrix._2D[2][1] * stRightMatrix._2D[1][2] + stLeftMatrix._2D[2][2] * stRightMatrix._2D[2][2] + stLeftMatrix._2D[2][3] * stRightMatrix._2D[3][2]; Result._2D[3][2] := stLeftMatrix._2D[3][0] * stRightMatrix._2D[0][2] + stLeftMatrix._2D[3][1] * stRightMatrix._2D[1][2] + stLeftMatrix._2D[3][2] * stRightMatrix._2D[2][2] + stLeftMatrix._2D[3][3] * stRightMatrix._2D[3][2]; Result._2D[0][3] := stLeftMatrix._2D[0][0] * stRightMatrix._2D[0][3] + stLeftMatrix._2D[0][1] * stRightMatrix._2D[1][3] + stLeftMatrix._2D[0][2] * stRightMatrix._2D[2][3] + stLeftMatrix._2D[0][3] * stRightMatrix._2D[3][3]; Result._2D[1][3] := stLeftMatrix._2D[1][0] * stRightMatrix._2D[0][3] + stLeftMatrix._2D[1][1] * stRightMatrix._2D[1][3] + stLeftMatrix._2D[1][2] * stRightMatrix._2D[2][3] + stLeftMatrix._2D[1][3] * stRightMatrix._2D[3][3]; Result._2D[2][3] := stLeftMatrix._2D[2][0] * stRightMatrix._2D[0][3] + stLeftMatrix._2D[2][1] * stRightMatrix._2D[1][3] + stLeftMatrix._2D[2][2] * stRightMatrix._2D[2][3] + stLeftMatrix._2D[2][3] * stRightMatrix._2D[3][3]; Result._2D[3][3] := stLeftMatrix._2D[3][0] * stRightMatrix._2D[0][3] + stLeftMatrix._2D[3][1] * stRightMatrix._2D[1][3] + stLeftMatrix._2D[3][2] * stRightMatrix._2D[2][3] + stLeftMatrix._2D[3][3] * stRightMatrix._2D[3][3]; end; function MatrixSub(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; var i: Integer; begin Result := Matrix(); for i := 0 to 15 do begin Result._1D[i] := stLeftMatrix._1D[i] - right; end; end; function MatrixAdd(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; var i: Integer; begin Result := Matrix(); for i := 0 to 15 do begin Result._1D[i] := stLeftMatrix._1D[i] + right; end; end; function MatrixDiv(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; var i: Integer; begin Result := Matrix(); for i := 0 to 15 do begin Result._1D[i] := stLeftMatrix._1D[i] / right; end; end; function MatrixMul(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; var i: Integer; begin Result := Matrix(); for i := 0 to 15 do begin Result._1D[i] := stLeftMatrix._1D[i] * right; end; end; function ApplyToPoint(const stLeftMatrix: TMatrix4x4; stPoint: TPoint3): TPoint3; begin Result.x := stPoint.x * stLeftMatrix._2d[0, 0] + stPoint.y * stLeftMatrix._2d[1, 0] + stPoint.z * stLeftMatrix._2d[2, 0] + stLeftMatrix._2d[3, 0]; Result.y := stPoint.x * stLeftMatrix._2d[0, 1] + stPoint.y * stLeftMatrix._2d[1, 1] + stPoint.z * stLeftMatrix._2d[2, 1] + stLeftMatrix._2d[3, 1]; Result.z := stPoint.x * stLeftMatrix._2d[0, 2] + stPoint.y * stLeftMatrix._2d[1, 2] + stPoint.z * stLeftMatrix._2d[2, 2] + stLeftMatrix._2d[3, 2]; end; function ApplyToPoint(const stLeftMatrix: TMatrix4x4; stPoint: TPoint2): TPoint2; begin Result.x := stPoint.x * stLeftMatrix._2d[0, 0] + stPoint.y * stLeftMatrix._2d[1, 0] + stLeftMatrix._2d[3, 0]; Result.y := stPoint.x * stLeftMatrix._2d[0, 1] + stPoint.y * stLeftMatrix._2d[1, 1] + stLeftMatrix._2d[3, 1]; end; function ApplyToVector(const stLeftMatrix: TMatrix4x4; stPoint: TPoint3): TPoint3; begin Result.x := stPoint.x * stLeftMatrix._2d[0, 0] + stPoint.y * stLeftMatrix._2d[1, 0] + stPoint.z * stLeftMatrix._2d[2, 0]; Result.y := stPoint.x * stLeftMatrix._2d[0, 1] + stPoint.y * stLeftMatrix._2d[1, 1] + stPoint.z * stLeftMatrix._2d[2, 1]; Result.z := stPoint.x * stLeftMatrix._2d[0, 2] + stPoint.y * stLeftMatrix._2d[1, 2] + stPoint.z * stLeftMatrix._2d[2, 2]; end; {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator TMatrix4x4.{$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; begin Result := DGLE_Types.MatrixAdd(stLeftMatrix, stRightMatrix); end; class operator TMatrix4x4.{$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; begin Result := DGLE_Types.MatrixSub(stLeftMatrix, stRightMatrix); end; class operator TMatrix4x4.{$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeftMatrix, stRightMatrix : TMatrix4x4): TMatrix4x4; begin Result := DGLE_Types.MatrixMul(stLeftMatrix, stRightMatrix); end; class operator TMatrix4x4.{$IFDEF FPC} + {$ELSE} Add {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; begin Result := DGLE_Types.MatrixAdd(stLeftMatrix, right); end; class operator TMatrix4x4.{$IFDEF FPC} - {$ELSE} Subtract {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; begin Result := DGLE_Types.MatrixSub(stLeftMatrix, right); end; class operator TMatrix4x4.{$IFDEF FPC} / {$ELSE} Divide {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; begin Result := DGLE_Types.MatrixDiv(stLeftMatrix, right); end; class operator TMatrix4x4.{$IFDEF FPC} * {$ELSE} Multiply {$ENDIF}(const stLeftMatrix: TMatrix4x4; right: Single): TMatrix4x4; begin Result := DGLE_Types.MatrixMul(stLeftMatrix, right); end; {$ENDIF} {$IF COMPILERVERSION >= 20} constructor TTransformStack.Create(); begin inherited; Stack := TStack<TMatrix>.Create(); end; procedure TTransformStack.Clear(const base_transform: TMatrix4x4); begin while Stack.Count <> 0 do Pop(); SetTop(base_transform); end; constructor TTransformStack.Create(const base_transform: TMatrix4x4); begin Create; Stack.Push(base_transform); end; destructor TTransformStack.Destroy(); begin Stack.Free(); inherited; end; procedure TTransformStack.Push(); begin Stack.Push(Stack.Peek()); end; procedure TTransformStack.Pop(); begin if Stack.Count > 1 then Stack.Pop(); end; function TTransformStack.GetTop(): TMatrix4x4; begin Result := Stack.Peek(); end; procedure TTransformStack.SetTop(const Value: TMatrix4x4) ; begin Stack.Pop(); Stack.Push(Value); end; procedure TTransformStack.MultGlobal(const transform: TMatrix4x4); begin Stack.Push(MatrixMul(Stack.Pop(), transform)); end; procedure TTransformStack.MultLocal(const transform: TMatrix4x4); begin Stack.Push(MatrixMul(transform, Stack.Pop())); end; {$ELSE} constructor TTransformStack.Create(); begin inherited; SetLength(Stack, 0); end; procedure TTransformStack.Clear(const base_transform: TMatrix4x4); begin SetLength(Stack, 1); SetTop(base_transform); end; constructor TTransformStack.Create(const base_transform: TMatrix4x4); begin SetLength(Stack, 1); Stack[0] := base_transform; end; function TTransformStack.GetTop(): TMatrix4x4; begin Result := Stack[High(Stack)]; end; procedure TTransformStack.MultGlobal(const transform: TMatrix); begin Stack[High(Stack)] := MatrixMul(Stack[High(Stack)], transform); end; procedure TTransformStack.MultLocal(const transform: TMatrix); begin Stack[High(Stack)] := MatrixMul(transform, Stack[High(Stack)]); end; procedure TTransformStack.Pop(); begin if(System.Length(Stack) > 1) then SetLength(Stack, System.Length(Stack) - 1); end; procedure TTransformStack.Push(); begin SetLength(Stack, System.Length(Stack) + 1); Stack[High(Stack)] := Stack[High(Stack) - 1]; end; procedure TTransformStack.SetTop(const Value: TMatrix4x4); begin Stack[High(Stack)] := Value; end; {$IFEND} function EngineWindow(): TEngineWindow; overload; begin Result.uiWidth := 800; Result.uiHeight := 600; Result.bFullScreen := False; Result.bVSync := False; Result.eMultiSampling := MM_NONE; Result.uiFlags := EWF_DEFAULT; end; function EngineWindow(uiWidth, uiHeight : Integer; bFullScreen : Boolean; bVSync : Boolean = False; eMSampling: {E_MULTISAMPLING_MODE} Cardinal = MM_NONE; uiFlags:{ENG_WINDOW_FLAGS}Integer = EWF_DEFAULT): TEngineWindow; overload; begin Result.uiWidth := uiWidth; Result.uiHeight := uiHeight; Result.bFullScreen := bFullScreen; Result.bVSync := bVSync; Result.eMultiSampling := eMSampling; Result.uiFlags := uiFlags; end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TEngineWindow.Create(var dummy); begin Self := EngineWindow(); end; constructor TEngineWindow.Create(uiWidth, uiHeight : Integer; bFullScreen : Boolean; bVSync : Boolean = False; eMSampling: {E_MULTISAMPLING_MODE} Cardinal = MM_NONE; uiFlags:{ENG_WINDOW_FLAGS}Integer = EWF_DEFAULT); begin Self := EngineWindow(uiWidth, uiHeight, bFullScreen, bVSync, eMSampling, uiFlags); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TPluginInfo.Create(var dummy); begin Self := PluginInfo(); end; {$ENDIF} function PluginInfo(): TPluginInfo; begin Result.ui8PluginSDKVersion := _DGLE_PLUGIN_SDK_VER_; end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TWindowMessage.Create(var dummy); begin Self := WindowMessage(); end; constructor TWindowMessage.Create(msg: E_WINDOW_MESSAGE_TYPE; param1: Cardinal = 0; param2: Cardinal = 0; param3: Pointer = nil); begin Self := WindowMessage(Msg, param1, param2, param3); end; {$ENDIF} function WindowMessage(): TWindowMessage; overload; begin Result.eMsgType := WMT_UNKNOWN; Result.ui32Param1 := 0; Result.ui32Param2 := 0; Result.pParam3 := nil; end; function WindowMessage(msg: E_WINDOW_MESSAGE_TYPE; param1: Cardinal = 0; param2: Cardinal = 0; param3: Pointer = nil): TWindowMessage; overload; begin Result.eMsgType := msg; Result.ui32Param1 := param1; Result.ui32Param2 := param2; Result.pParam3 := param3; end; procedure Clear(var AVar: TVariant); begin with AVar do begin _type := DVT_UNKNOWN; if Assigned(_Data) then FreeMem(_Data); _Data := nil; end; end; procedure SetInt(var AVar: TVariant; iVal: Integer); begin with AVar do begin DGLE_Types.Clear(AVar); _type := DVT_INT; GetMem(_Data, SizeOf(Integer)); CopyMemory(_Data, @iVal, SizeOf(Integer)); end; end; procedure SetFloat(var AVar: TVariant; fVal: Single); begin with AVar do begin DGLE_Types.Clear(AVar); _type := DVT_FLOAT; GetMem(_Data, SizeOf(Single)); CopyMemory(_Data, @fVal, SizeOf(Single)); end; end; procedure SetBool(var AVar: TVariant; bVal: Boolean); begin with AVar do begin DGLE_Types.Clear(AVar); _type := DVT_BOOL; GetMem(_Data, SizeOf(LongBool)); if bVal then PInteger(_Data)^ := 1 else PInteger(_Data)^ := 0; end; end; procedure SetPointer(var AVar: TVariant; pPointer: Pointer); begin with AVar do begin DGLE_Types.Clear(AVar); _type := DVT_POINTER; _Data := pPointer; end; end; procedure SetData(var AVar: TVariant; pData: Pointer; uiDataSize: Cardinal); begin with AVar do begin DGLE_Types.Clear(AVar); _type := DVT_DATA; GetMem(_Data, uiDataSize + SizeOf(Integer)); CopyMemory(_Data, @uiDataSize, SizeOf(Integer)); CopyMemory(Pointer(Integer(_Data) + SizeOf(Integer)), pData, uiDataSize); end; end; function AsInt(var AVar: TVariant): Integer; begin with AVar do if (_type <> DVT_INT) then Result := 0 else CopyMemory(@Result, _Data, SizeOf(Integer)); end; function AsFloat(var AVar: TVariant): Single; begin with AVar do if (_type <> DVT_FLOAT) then Result := 0. else CopyMemory(@Result, _Data, SizeOf(Single)); end; function AsBool(var AVar: TVariant): Boolean; begin with AVar do if (_type <> DVT_BOOL) then Result := False else Result := not (PInteger(_Data)^ = 0); end; function AsPointer(var AVar: TVariant): Pointer; begin with AVar do if (_type <> DVT_POINTER) then Result := nil else Result := _Data; end; procedure GetData(var AVar: TVariant; out pData: Pointer; out uiDataSize: Cardinal); begin with AVar do if (_type <> DVT_DATA) then begin pData := nil; uiDataSize := 0; end else begin GetMem(_Data, uiDataSize + SizeOf(Integer)); CopyMemory(@uiDataSize, _Data, SizeOf(Integer)); GetMem(pData, uiDataSize); CopyMemory(pData, Pointer(Integer(_Data) + SizeOf(Integer)), uiDataSize); end; end; function GetType(var AVar: TVariant): E_DGLE_VARIANT_TYPE; begin Result := AVar._type; end; {$IFDEF DGLE_PASCAL_RECORDMETHODS} procedure TVariant.Clear(); begin DGLE_Types.Clear(Self); end; procedure TVariant.SetInt(iVal: Integer); begin DGLE_Types.SetInt(Self, iVal); end; procedure TVariant.SetFloat(fVal: Single); begin DGLE_Types.SetFloat(Self, fVal); end; procedure TVariant.SetBool(bVal: Boolean); begin DGLE_Types.SetBool(Self, bVal); end; procedure TVariant.SetPointer(pPointer: Pointer); begin DGLE_Types.SetPointer(Self, pPointer); end; procedure TVariant.SetData(pData: Pointer; uiDataSize: Cardinal); begin DGLE_Types.SetData(Self, pData, uiDataSize); end; function TVariant.AsInt(): Integer; begin Result := DGLE_Types.AsInt(Self); end; function TVariant.AsFloat(): Single; begin Result := DGLE_Types.AsFloat(Self); end; function TVariant.AsBool(): Boolean; begin Result := DGLE_Types.AsBool(Self); end; function TVariant.AsPointer(): Pointer; begin Result := DGLE_Types.AsPointer(Self); end; procedure TVariant.GetData(out pData: Pointer; out uiDataSize: Cardinal); begin DGLE_Types.GetData(Self, pData, uiDataSize); end; function TVariant.GetType(): E_DGLE_VARIANT_TYPE; begin Result := _type; end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator TVariant.{$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Integer; begin Result := AVar.AsInt(); end; class operator TVariant.{$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Single; begin Result := AVar.AsFloat(); end; class operator TVariant.{$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Boolean; begin Result := AVar.AsBool(); end; class operator TVariant.{$IFDEF FPC} := {$ELSE} Implicit {$ENDIF}(AVar: TVariant): Pointer; begin Result := AVar.AsPointer(); end; {$ENDIF} begin end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Angus Robertson, Magenta Systems Ltd Description: One Time Password support functions, see RFC2289/1938 (aka S/KEY) Creation: 12 November 2007 Updated: 06 August 2008 Version: 1.06 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1997-2012 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Updates: 16 Nov 2007 - 1.00 baseline Angus 12 May 2008 - 1.01 Uses OverbyteIcsUtils.pas for atoi 06 Aug 2008 - 1.02 Changed two strings to AnsiStrings so it works under Delphi 2009 5 Nov 2008 - 1.03 added OtpGetMethod, OtpKeyNames public 15 Apr 2011 - 1.04 Arno prepared for 64-bit, use functions from OverbyteIcsUtils. 14 Aug 2011 - 1.05 Arno fixed a bug that showed up since Delphi XE only and made two small optimizations. Feb 29, 2012 1.06 Arno - Use IcsRandomInt Background: There is a test and demo application OverbyteIcsOneTimePassword for this unit. See RFC2289, RFC1938 (old), the MD4 version was called S/KEY RFC1760 RFC2444 describes System Authentication and Secure Logon (SASL) using OTP-EXT RFC2243, which is not yet supported here One Time Passwords (also called S/Key) are a means of protecting passwords from being logged or sniffed while on route to a server. This is done by the server generated information that is sent to the client, combined with the clear password to create a 64-bit one-way hash digest called a One Time Password, that is then returned to the server instead of the clear password. The server then calculates the same OTP from it's known clear password which should match the one created by the client assuming both clear passwords are the same. The OTP is usually sent by the client in a format called 'six words' where combinations of six words taken from a 2,048 word dictionary encode the 64-bit password. This is historic because words are easier to type than a long hex string in a manual client. Note that One Time Password simply protect the password being sent, not any subsequent data, but do prevent the clear password being stolen for later logon to the server. One Time Passwords are typically supported by FTP and mail servers, but may be used with any telnet type protocol. This unit contains two main functions used in servers to generate the challenge and test the one time password returned, and one function for the client to process the challenge and create the one time password. Note the server needs to save the hash method (MD5, MD4 or SHA1), sequence number and seed word with the account details of each logon, and update the sequence number after each logon so the same sequence and seed are never repeated. RFC2289 states the clear password should be between 10 and 63 characters long and OtpIsValidPassword may be used to check this, but the minimum length is NOT enforced in these functions. OtpCreateChallenge - server software The first function used in server software to create a password challenge once an account logon name from a client has been checked. The challenge comprises the hash method, sequence number and seed and is returned to the client. For a new account set the sequence to -1 to initialise it and create a new random seed, but the sequence and seed must then be saved with the account details for checking when the one time password calculated from them is returned by the client. Example Challenges: otp-md5 99 test otp-md4 99 test otp-sha1 99 test OtpProcessChallenge - client software The main function used in client software to generate a one time password from the challenge sent by the server in response to an account logon name, using the clear account password. The OTP is usually sent in 'six words' format, but there is an option here to send a hex OTP instead. Example One Time Passwords: BAIL TUFT BITS GANG CHEF THY 50FE1962C4965880 OtpTestPassword - server software The second function used in server software to test the one time password returned by the client. The server calculates a OTP from the account clear password and the same information sent in the challenge (which was stored with the account details) and then compares it with the one sent by the client (in six word and hex formats) to check for a valid login. If valid, the sequence number is decremented and should be saved with the account details so the same OTP is not generated during the next login. } {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsOneTimePw; {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} interface uses SysUtils, Classes, OverbyteIcsMD5, OverbyteIcsMD4, OverbyteIcsSha1, OverbyteIcsFtpSrvT, OverbyteIcsUtils; const OneTimePwVersion = 106; CopyRight : String = ' OneTimePw (c) 1997-2012 F. Piette V1.06 '; OtpKeyNames: array [0..3] of string = ('none', 'otp-md5', 'otp-md4', 'otp-sha1') ; type { 64-bit result of OTP hash } TOtp64bit = array [0..7] of byte; { type conversion record } TInt64Rec = packed record case Integer of 0: (Lo, Hi: Cardinal); 1: (Cardinals: array [0..1] of Cardinal); 2: (Words: array [0..3] of Word); 3: (Bytes: array [0..7] of Byte); 4: (Quad: Int64); end; { OTP hash methods } TOtpMethod = (OtpKeyNone, OtpKeyMd5, OtpKeyMd4, OtpKeySha1); { Q-} { R-} function OtpIsValidPassword (const OtpPassword: string): boolean; function OtpIsValidSeed (const OptSeed: string): boolean; function OtpLowNoSpace (const AString: string): string; function OtpParseChallenge (const OtpChallenge: string; var OtpMethod: TOtpMethod; var OtpSequence: integer; var OtpSeed: string): boolean; function OtpIsValidChallenge (const OtpChallenge: string): Boolean; function OtpProcessChallenge (const OtpChallenge, OtpPassword: string; HexResp: boolean ; var OtpRespKey: string): boolean; function OtpCreateChallenge (OtpMethod: TOtpMethod; var OtpSequence: integer; var OtpSeed: string): string; function OtpTestPassword (const OtpRespKey, OtpPassword: string; OtpMethod: TOtpMethod; var OtpSequence: integer; const OtpSeed: string): boolean; function OtpGetMethod (const S: string): TOtpMethod; implementation const InitialSequence = 999; { six words list taken from RCF2289 document - each word represents 11-bits of a 64-bit number } SixWordsList: array [0..2047] of string = ('A', 'ABE', 'ACE', 'ACT', 'AD', 'ADA', 'ADD', 'AGO', 'AID', 'AIM', 'AIR', 'ALL', 'ALP', 'AM', 'AMY', 'AN', 'ANA', 'AND', 'ANN', 'ANT', 'ANY', 'APE', 'APS', 'APT', 'ARC', 'ARE', 'ARK', 'ARM', 'ART', 'AS', 'ASH', 'ASK', 'AT', 'ATE', 'AUG', 'AUK', 'AVE', 'AWE', 'AWK', 'AWL', 'AWN', 'AX', 'AYE', 'BAD', 'BAG', 'BAH', 'BAM', 'BAN', 'BAR', 'BAT', 'BAY', 'BE', 'BED', 'BEE', 'BEG', 'BEN', 'BET', 'BEY', 'BIB', 'BID', 'BIG', 'BIN', 'BIT', 'BOB', 'BOG', 'BON', 'BOO', 'BOP', 'BOW', 'BOY', 'BUB', 'BUD', 'BUG', 'BUM', 'BUN', 'BUS', 'BUT', 'BUY', 'BY', 'BYE', 'CAB', 'CAL', 'CAM', 'CAN', 'CAP', 'CAR', 'CAT', 'CAW', 'COD', 'COG', 'COL', 'CON', 'COO', 'COP', 'COT', 'COW', 'COY', 'CRY', 'CUB', 'CUE', 'CUP', 'CUR', 'CUT', 'DAB', 'DAD', 'DAM', 'DAN', 'DAR', 'DAY', 'DEE', 'DEL', 'DEN', 'DES', 'DEW', 'DID', 'DIE', 'DIG', 'DIN', 'DIP', 'DO', 'DOE', 'DOG', 'DON', 'DOT', 'DOW', 'DRY', 'DUB', 'DUD', 'DUE', 'DUG', 'DUN', 'EAR', 'EAT', 'ED', 'EEL', 'EGG', 'EGO', 'ELI', 'ELK', 'ELM', 'ELY', 'EM', 'END', 'EST', 'ETC', 'EVA', 'EVE', 'EWE', 'EYE', 'FAD', 'FAN', 'FAR', 'FAT', 'FAY', 'FED', 'FEE', 'FEW', 'FIB', 'FIG', 'FIN', 'FIR', 'FIT', 'FLO', 'FLY', 'FOE', 'FOG', 'FOR', 'FRY', 'FUM', 'FUN', 'FUR', 'GAB', 'GAD', 'GAG', 'GAL', 'GAM', 'GAP', 'GAS', 'GAY', 'GEE', 'GEL', 'GEM', 'GET', 'GIG', 'GIL', 'GIN', 'GO', 'GOT', 'GUM', 'GUN', 'GUS', 'GUT', 'GUY', 'GYM', 'GYP', 'HA', 'HAD', 'HAL', 'HAM', 'HAN', 'HAP', 'HAS', 'HAT', 'HAW', 'HAY', 'HE', 'HEM', 'HEN', 'HER', 'HEW', 'HEY', 'HI', 'HID', 'HIM', 'HIP', 'HIS', 'HIT', 'HO', 'HOB', 'HOC', 'HOE', 'HOG', 'HOP', 'HOT', 'HOW', 'HUB', 'HUE', 'HUG', 'HUH', 'HUM', 'HUT', 'I', 'ICY', 'IDA', 'IF', 'IKE', 'ILL', 'INK', 'INN', 'IO', 'ION', 'IQ', 'IRA', 'IRE', 'IRK', 'IS', 'IT', 'ITS', 'IVY', 'JAB', 'JAG', 'JAM', 'JAN', 'JAR', 'JAW', 'JAY', 'JET', 'JIG', 'JIM', 'JO', 'JOB', 'JOE', 'JOG', 'JOT', 'JOY', 'JUG', 'JUT', 'KAY', 'KEG', 'KEN', 'KEY', 'KID', 'KIM', 'KIN', 'KIT', 'LA', 'LAB', 'LAC', 'LAD', 'LAG', 'LAM', 'LAP', 'LAW', 'LAY', 'LEA', 'LED', 'LEE', 'LEG', 'LEN', 'LEO', 'LET', 'LEW', 'LID', 'LIE', 'LIN', 'LIP', 'LIT', 'LO', 'LOB', 'LOG', 'LOP', 'LOS', 'LOT', 'LOU', 'LOW', 'LOY', 'LUG', 'LYE', 'MA', 'MAC', 'MAD', 'MAE', 'MAN', 'MAO', 'MAP', 'MAT', 'MAW', 'MAY', 'ME', 'MEG', 'MEL', 'MEN', 'MET', 'MEW', 'MID', 'MIN', 'MIT', 'MOB', 'MOD', 'MOE', 'MOO', 'MOP', 'MOS', 'MOT', 'MOW', 'MUD', 'MUG', 'MUM', 'MY', 'NAB', 'NAG', 'NAN', 'NAP', 'NAT', 'NAY', 'NE', 'NED', 'NEE', 'NET', 'NEW', 'NIB', 'NIL', 'NIP', 'NIT', 'NO', 'NOB', 'NOD', 'NON', 'NOR', 'NOT', 'NOV', 'NOW', 'NU', 'NUN', 'NUT', 'O', 'OAF', 'OAK', 'OAR', 'OAT', 'ODD', 'ODE', 'OF', 'OFF', 'OFT', 'OH', 'OIL', 'OK', 'OLD', 'ON', 'ONE', 'OR', 'ORB', 'ORE', 'ORR', 'OS', 'OTT', 'OUR', 'OUT', 'OVA', 'OW', 'OWE', 'OWL', 'OWN', 'OX', 'PA', 'PAD', 'PAL', 'PAM', 'PAN', 'PAP', 'PAR', 'PAT', 'PAW', 'PAY', 'PEA', 'PEG', 'PEN', 'PEP', 'PER', 'PET', 'PEW', 'PHI', 'PI', 'PIE', 'PIN', 'PIT', 'PLY', 'PO', 'POD', 'POE', 'POP', 'POT', 'POW', 'PRO', 'PRY', 'PUB', 'PUG', 'PUN', 'PUP', 'PUT', 'QUO', 'RAG', 'RAM', 'RAN', 'RAP', 'RAT', 'RAW', 'RAY', 'REB', 'RED', 'REP', 'RET', 'RIB', 'RID', 'RIG', 'RIM', 'RIO', 'RIP', 'ROB', 'ROD', 'ROE', 'RON', 'ROT', 'ROW', 'ROY', 'RUB', 'RUE', 'RUG', 'RUM', 'RUN', 'RYE', 'SAC', 'SAD', 'SAG', 'SAL', 'SAM', 'SAN', 'SAP', 'SAT', 'SAW', 'SAY', 'SEA', 'SEC', 'SEE', 'SEN', 'SET', 'SEW', 'SHE', 'SHY', 'SIN', 'SIP', 'SIR', 'SIS', 'SIT', 'SKI', 'SKY', 'SLY', 'SO', 'SOB', 'SOD', 'SON', 'SOP', 'SOW', 'SOY', 'SPA', 'SPY', 'SUB', 'SUD', 'SUE', 'SUM', 'SUN', 'SUP', 'TAB', 'TAD', 'TAG', 'TAN', 'TAP', 'TAR', 'TEA', 'TED', 'TEE', 'TEN', 'THE', 'THY', 'TIC', 'TIE', 'TIM', 'TIN', 'TIP', 'TO', 'TOE', 'TOG', 'TOM', 'TON', 'TOO', 'TOP', 'TOW', 'TOY', 'TRY', 'TUB', 'TUG', 'TUM', 'TUN', 'TWO', 'UN', 'UP', 'US', 'USE', 'VAN', 'VAT', 'VET', 'VIE', 'WAD', 'WAG', 'WAR', 'WAS', 'WAY', 'WE', 'WEB', 'WED', 'WEE', 'WET', 'WHO', 'WHY', 'WIN', 'WIT', 'WOK', 'WON', 'WOO', 'WOW', 'WRY', 'WU', 'YAM', 'YAP', 'YAW', 'YE', 'YEA', 'YES', 'YET', 'YOU', 'ABED', 'ABEL', 'ABET', 'ABLE', 'ABUT', 'ACHE', 'ACID', 'ACME', 'ACRE', 'ACTA', 'ACTS', 'ADAM', 'ADDS', 'ADEN', 'AFAR', 'AFRO', 'AGEE', 'AHEM', 'AHOY', 'AIDA', 'AIDE', 'AIDS', 'AIRY', 'AJAR', 'AKIN', 'ALAN', 'ALEC', 'ALGA', 'ALIA', 'ALLY', 'ALMA', 'ALOE', 'ALSO', 'ALTO', 'ALUM', 'ALVA', 'AMEN', 'AMES', 'AMID', 'AMMO', 'AMOK', 'AMOS', 'AMRA', 'ANDY', 'ANEW', 'ANNA', 'ANNE', 'ANTE', 'ANTI', 'AQUA', 'ARAB', 'ARCH', 'AREA', 'ARGO', 'ARID', 'ARMY', 'ARTS', 'ARTY', 'ASIA', 'ASKS', 'ATOM', 'AUNT', 'AURA', 'AUTO', 'AVER', 'AVID', 'AVIS', 'AVON', 'AVOW', 'AWAY', 'AWRY', 'BABE', 'BABY', 'BACH', 'BACK', 'BADE', 'BAIL', 'BAIT', 'BAKE', 'BALD', 'BALE', 'BALI', 'BALK', 'BALL', 'BALM', 'BAND', 'BANE', 'BANG', 'BANK', 'BARB', 'BARD', 'BARE', 'BARK', 'BARN', 'BARR', 'BASE', 'BASH', 'BASK', 'BASS', 'BATE', 'BATH', 'BAWD', 'BAWL', 'BEAD', 'BEAK', 'BEAM', 'BEAN', 'BEAR', 'BEAT', 'BEAU', 'BECK', 'BEEF', 'BEEN', 'BEER', 'BEET', 'BELA', 'BELL', 'BELT', 'BEND', 'BENT', 'BERG', 'BERN', 'BERT', 'BESS', 'BEST', 'BETA', 'BETH', 'BHOY', 'BIAS', 'BIDE', 'BIEN', 'BILE', 'BILK', 'BILL', 'BIND', 'BING', 'BIRD', 'BITE', 'BITS', 'BLAB', 'BLAT', 'BLED', 'BLEW', 'BLOB', 'BLOC', 'BLOT', 'BLOW', 'BLUE', 'BLUM', 'BLUR', 'BOAR', 'BOAT', 'BOCA', 'BOCK', 'BODE', 'BODY', 'BOGY', 'BOHR', 'BOIL', 'BOLD', 'BOLO', 'BOLT', 'BOMB', 'BONA', 'BOND', 'BONE', 'BONG', 'BONN', 'BONY', 'BOOK', 'BOOM', 'BOON', 'BOOT', 'BORE', 'BORG', 'BORN', 'BOSE', 'BOSS', 'BOTH', 'BOUT', 'BOWL', 'BOYD', 'BRAD', 'BRAE', 'BRAG', 'BRAN', 'BRAY', 'BRED', 'BREW', 'BRIG', 'BRIM', 'BROW', 'BUCK', 'BUDD', 'BUFF', 'BULB', 'BULK', 'BULL', 'BUNK', 'BUNT', 'BUOY', 'BURG', 'BURL', 'BURN', 'BURR', 'BURT', 'BURY', 'BUSH', 'BUSS', 'BUST', 'BUSY', 'BYTE', 'CADY', 'CAFE', 'CAGE', 'CAIN', 'CAKE', 'CALF', 'CALL', 'CALM', 'CAME', 'CANE', 'CANT', 'CARD', 'CARE', 'CARL', 'CARR', 'CART', 'CASE', 'CASH', 'CASK', 'CAST', 'CAVE', 'CEIL', 'CELL', 'CENT', 'CERN', 'CHAD', 'CHAR', 'CHAT', 'CHAW', 'CHEF', 'CHEN', 'CHEW', 'CHIC', 'CHIN', 'CHOU', 'CHOW', 'CHUB', 'CHUG', 'CHUM', 'CITE', 'CITY', 'CLAD', 'CLAM', 'CLAN', 'CLAW', 'CLAY', 'CLOD', 'CLOG', 'CLOT', 'CLUB', 'CLUE', 'COAL', 'COAT', 'COCA', 'COCK', 'COCO', 'CODA', 'CODE', 'CODY', 'COED', 'COIL', 'COIN', 'COKE', 'COLA', 'COLD', 'COLT', 'COMA', 'COMB', 'COME', 'COOK', 'COOL', 'COON', 'COOT', 'CORD', 'CORE', 'CORK', 'CORN', 'COST', 'COVE', 'COWL', 'CRAB', 'CRAG', 'CRAM', 'CRAY', 'CREW', 'CRIB', 'CROW', 'CRUD', 'CUBA', 'CUBE', 'CUFF', 'CULL', 'CULT', 'CUNY', 'CURB', 'CURD', 'CURE', 'CURL', 'CURT', 'CUTS', 'DADE', 'DALE', 'DAME', 'DANA', 'DANE', 'DANG', 'DANK', 'DARE', 'DARK', 'DARN', 'DART', 'DASH', 'DATA', 'DATE', 'DAVE', 'DAVY', 'DAWN', 'DAYS', 'DEAD', 'DEAF', 'DEAL', 'DEAN', 'DEAR', 'DEBT', 'DECK', 'DEED', 'DEEM', 'DEER', 'DEFT', 'DEFY', 'DELL', 'DENT', 'DENY', 'DESK', 'DIAL', 'DICE', 'DIED', 'DIET', 'DIME', 'DINE', 'DING', 'DINT', 'DIRE', 'DIRT', 'DISC', 'DISH', 'DISK', 'DIVE', 'DOCK', 'DOES', 'DOLE', 'DOLL', 'DOLT', 'DOME', 'DONE', 'DOOM', 'DOOR', 'DORA', 'DOSE', 'DOTE', 'DOUG', 'DOUR', 'DOVE', 'DOWN', 'DRAB', 'DRAG', 'DRAM', 'DRAW', 'DREW', 'DRUB', 'DRUG', 'DRUM', 'DUAL', 'DUCK', 'DUCT', 'DUEL', 'DUET', 'DUKE', 'DULL', 'DUMB', 'DUNE', 'DUNK', 'DUSK', 'DUST', 'DUTY', 'EACH', 'EARL', 'EARN', 'EASE', 'EAST', 'EASY', 'EBEN', 'ECHO', 'EDDY', 'EDEN', 'EDGE', 'EDGY', 'EDIT', 'EDNA', 'EGAN', 'ELAN', 'ELBA', 'ELLA', 'ELSE', 'EMIL', 'EMIT', 'EMMA', 'ENDS', 'ERIC', 'EROS', 'EVEN', 'EVER', 'EVIL', 'EYED', 'FACE', 'FACT', 'FADE', 'FAIL', 'FAIN', 'FAIR', 'FAKE', 'FALL', 'FAME', 'FANG', 'FARM', 'FAST', 'FATE', 'FAWN', 'FEAR', 'FEAT', 'FEED', 'FEEL', 'FEET', 'FELL', 'FELT', 'FEND', 'FERN', 'FEST', 'FEUD', 'FIEF', 'FIGS', 'FILE', 'FILL', 'FILM', 'FIND', 'FINE', 'FINK', 'FIRE', 'FIRM', 'FISH', 'FISK', 'FIST', 'FITS', 'FIVE', 'FLAG', 'FLAK', 'FLAM', 'FLAT', 'FLAW', 'FLEA', 'FLED', 'FLEW', 'FLIT', 'FLOC', 'FLOG', 'FLOW', 'FLUB', 'FLUE', 'FOAL', 'FOAM', 'FOGY', 'FOIL', 'FOLD', 'FOLK', 'FOND', 'FONT', 'FOOD', 'FOOL', 'FOOT', 'FORD', 'FORE', 'FORK', 'FORM', 'FORT', 'FOSS', 'FOUL', 'FOUR', 'FOWL', 'FRAU', 'FRAY', 'FRED', 'FREE', 'FRET', 'FREY', 'FROG', 'FROM', 'FUEL', 'FULL', 'FUME', 'FUND', 'FUNK', 'FURY', 'FUSE', 'FUSS', 'GAFF', 'GAGE', 'GAIL', 'GAIN', 'GAIT', 'GALA', 'GALE', 'GALL', 'GALT', 'GAME', 'GANG', 'GARB', 'GARY', 'GASH', 'GATE', 'GAUL', 'GAUR', 'GAVE', 'GAWK', 'GEAR', 'GELD', 'GENE', 'GENT', 'GERM', 'GETS', 'GIBE', 'GIFT', 'GILD', 'GILL', 'GILT', 'GINA', 'GIRD', 'GIRL', 'GIST', 'GIVE', 'GLAD', 'GLEE', 'GLEN', 'GLIB', 'GLOB', 'GLOM', 'GLOW', 'GLUE', 'GLUM', 'GLUT', 'GOAD', 'GOAL', 'GOAT', 'GOER', 'GOES', 'GOLD', 'GOLF', 'GONE', 'GONG', 'GOOD', 'GOOF', 'GORE', 'GORY', 'GOSH', 'GOUT', 'GOWN', 'GRAB', 'GRAD', 'GRAY', 'GREG', 'GREW', 'GREY', 'GRID', 'GRIM', 'GRIN', 'GRIT', 'GROW', 'GRUB', 'GULF', 'GULL', 'GUNK', 'GURU', 'GUSH', 'GUST', 'GWEN', 'GWYN', 'HAAG', 'HAAS', 'HACK', 'HAIL', 'HAIR', 'HALE', 'HALF', 'HALL', 'HALO', 'HALT', 'HAND', 'HANG', 'HANK', 'HANS', 'HARD', 'HARK', 'HARM', 'HART', 'HASH', 'HAST', 'HATE', 'HATH', 'HAUL', 'HAVE', 'HAWK', 'HAYS', 'HEAD', 'HEAL', 'HEAR', 'HEAT', 'HEBE', 'HECK', 'HEED', 'HEEL', 'HEFT', 'HELD', 'HELL', 'HELM', 'HERB', 'HERD', 'HERE', 'HERO', 'HERS', 'HESS', 'HEWN', 'HICK', 'HIDE', 'HIGH', 'HIKE', 'HILL', 'HILT', 'HIND', 'HINT', 'HIRE', 'HISS', 'HIVE', 'HOBO', 'HOCK', 'HOFF', 'HOLD', 'HOLE', 'HOLM', 'HOLT', 'HOME', 'HONE', 'HONK', 'HOOD', 'HOOF', 'HOOK', 'HOOT', 'HORN', 'HOSE', 'HOST', 'HOUR', 'HOVE', 'HOWE', 'HOWL', 'HOYT', 'HUCK', 'HUED', 'HUFF', 'HUGE', 'HUGH', 'HUGO', 'HULK', 'HULL', 'HUNK', 'HUNT', 'HURD', 'HURL', 'HURT', 'HUSH', 'HYDE', 'HYMN', 'IBIS', 'ICON', 'IDEA', 'IDLE', 'IFFY', 'INCA', 'INCH', 'INTO', 'IONS', 'IOTA', 'IOWA', 'IRIS', 'IRMA', 'IRON', 'ISLE', 'ITCH', 'ITEM', 'IVAN', 'JACK', 'JADE', 'JAIL', 'JAKE', 'JANE', 'JAVA', 'JEAN', 'JEFF', 'JERK', 'JESS', 'JEST', 'JIBE', 'JILL', 'JILT', 'JIVE', 'JOAN', 'JOBS', 'JOCK', 'JOEL', 'JOEY', 'JOHN', 'JOIN', 'JOKE', 'JOLT', 'JOVE', 'JUDD', 'JUDE', 'JUDO', 'JUDY', 'JUJU', 'JUKE', 'JULY', 'JUNE', 'JUNK', 'JUNO', 'JURY', 'JUST', 'JUTE', 'KAHN', 'KALE', 'KANE', 'KANT', 'KARL', 'KATE', 'KEEL', 'KEEN', 'KENO', 'KENT', 'KERN', 'KERR', 'KEYS', 'KICK', 'KILL', 'KIND', 'KING', 'KIRK', 'KISS', 'KITE', 'KLAN', 'KNEE', 'KNEW', 'KNIT', 'KNOB', 'KNOT', 'KNOW', 'KOCH', 'KONG', 'KUDO', 'KURD', 'KURT', 'KYLE', 'LACE', 'LACK', 'LACY', 'LADY', 'LAID', 'LAIN', 'LAIR', 'LAKE', 'LAMB', 'LAME', 'LAND', 'LANE', 'LANG', 'LARD', 'LARK', 'LASS', 'LAST', 'LATE', 'LAUD', 'LAVA', 'LAWN', 'LAWS', 'LAYS', 'LEAD', 'LEAF', 'LEAK', 'LEAN', 'LEAR', 'LEEK', 'LEER', 'LEFT', 'LEND', 'LENS', 'LENT', 'LEON', 'LESK', 'LESS', 'LEST', 'LETS', 'LIAR', 'LICE', 'LICK', 'LIED', 'LIEN', 'LIES', 'LIEU', 'LIFE', 'LIFT', 'LIKE', 'LILA', 'LILT', 'LILY', 'LIMA', 'LIMB', 'LIME', 'LIND', 'LINE', 'LINK', 'LINT', 'LION', 'LISA', 'LIST', 'LIVE', 'LOAD', 'LOAF', 'LOAM', 'LOAN', 'LOCK', 'LOFT', 'LOGE', 'LOIS', 'LOLA', 'LONE', 'LONG', 'LOOK', 'LOON', 'LOOT', 'LORD', 'LORE', 'LOSE', 'LOSS', 'LOST', 'LOUD', 'LOVE', 'LOWE', 'LUCK', 'LUCY', 'LUGE', 'LUKE', 'LULU', 'LUND', 'LUNG', 'LURA', 'LURE', 'LURK', 'LUSH', 'LUST', 'LYLE', 'LYNN', 'LYON', 'LYRA', 'MACE', 'MADE', 'MAGI', 'MAID', 'MAIL', 'MAIN', 'MAKE', 'MALE', 'MALI', 'MALL', 'MALT', 'MANA', 'MANN', 'MANY', 'MARC', 'MARE', 'MARK', 'MARS', 'MART', 'MARY', 'MASH', 'MASK', 'MASS', 'MAST', 'MATE', 'MATH', 'MAUL', 'MAYO', 'MEAD', 'MEAL', 'MEAN', 'MEAT', 'MEEK', 'MEET', 'MELD', 'MELT', 'MEMO', 'MEND', 'MENU', 'MERT', 'MESH', 'MESS', 'MICE', 'MIKE', 'MILD', 'MILE', 'MILK', 'MILL', 'MILT', 'MIMI', 'MIND', 'MINE', 'MINI', 'MINK', 'MINT', 'MIRE', 'MISS', 'MIST', 'MITE', 'MITT', 'MOAN', 'MOAT', 'MOCK', 'MODE', 'MOLD', 'MOLE', 'MOLL', 'MOLT', 'MONA', 'MONK', 'MONT', 'MOOD', 'MOON', 'MOOR', 'MOOT', 'MORE', 'MORN', 'MORT', 'MOSS', 'MOST', 'MOTH', 'MOVE', 'MUCH', 'MUCK', 'MUDD', 'MUFF', 'MULE', 'MULL', 'MURK', 'MUSH', 'MUST', 'MUTE', 'MUTT', 'MYRA', 'MYTH', 'NAGY', 'NAIL', 'NAIR', 'NAME', 'NARY', 'NASH', 'NAVE', 'NAVY', 'NEAL', 'NEAR', 'NEAT', 'NECK', 'NEED', 'NEIL', 'NELL', 'NEON', 'NERO', 'NESS', 'NEST', 'NEWS', 'NEWT', 'NIBS', 'NICE', 'NICK', 'NILE', 'NINA', 'NINE', 'NOAH', 'NODE', 'NOEL', 'NOLL', 'NONE', 'NOOK', 'NOON', 'NORM', 'NOSE', 'NOTE', 'NOUN', 'NOVA', 'NUDE', 'NULL', 'NUMB', 'OATH', 'OBEY', 'OBOE', 'ODIN', 'OHIO', 'OILY', 'OINT', 'OKAY', 'OLAF', 'OLDY', 'OLGA', 'OLIN', 'OMAN', 'OMEN', 'OMIT', 'ONCE', 'ONES', 'ONLY', 'ONTO', 'ONUS', 'ORAL', 'ORGY', 'OSLO', 'OTIS', 'OTTO', 'OUCH', 'OUST', 'OUTS', 'OVAL', 'OVEN', 'OVER', 'OWLY', 'OWNS', 'QUAD', 'QUIT', 'QUOD', 'RACE', 'RACK', 'RACY', 'RAFT', 'RAGE', 'RAID', 'RAIL', 'RAIN', 'RAKE', 'RANK', 'RANT', 'RARE', 'RASH', 'RATE', 'RAVE', 'RAYS', 'READ', 'REAL', 'REAM', 'REAR', 'RECK', 'REED', 'REEF', 'REEK', 'REEL', 'REID', 'REIN', 'RENA', 'REND', 'RENT', 'REST', 'RICE', 'RICH', 'RICK', 'RIDE', 'RIFT', 'RILL', 'RIME', 'RING', 'RINK', 'RISE', 'RISK', 'RITE', 'ROAD', 'ROAM', 'ROAR', 'ROBE', 'ROCK', 'RODE', 'ROIL', 'ROLL', 'ROME', 'ROOD', 'ROOF', 'ROOK', 'ROOM', 'ROOT', 'ROSA', 'ROSE', 'ROSS', 'ROSY', 'ROTH', 'ROUT', 'ROVE', 'ROWE', 'ROWS', 'RUBE', 'RUBY', 'RUDE', 'RUDY', 'RUIN', 'RULE', 'RUNG', 'RUNS', 'RUNT', 'RUSE', 'RUSH', 'RUSK', 'RUSS', 'RUST', 'RUTH', 'SACK', 'SAFE', 'SAGE', 'SAID', 'SAIL', 'SALE', 'SALK', 'SALT', 'SAME', 'SAND', 'SANE', 'SANG', 'SANK', 'SARA', 'SAUL', 'SAVE', 'SAYS', 'SCAN', 'SCAR', 'SCAT', 'SCOT', 'SEAL', 'SEAM', 'SEAR', 'SEAT', 'SEED', 'SEEK', 'SEEM', 'SEEN', 'SEES', 'SELF', 'SELL', 'SEND', 'SENT', 'SETS', 'SEWN', 'SHAG', 'SHAM', 'SHAW', 'SHAY', 'SHED', 'SHIM', 'SHIN', 'SHOD', 'SHOE', 'SHOT', 'SHOW', 'SHUN', 'SHUT', 'SICK', 'SIDE', 'SIFT', 'SIGH', 'SIGN', 'SILK', 'SILL', 'SILO', 'SILT', 'SINE', 'SING', 'SINK', 'SIRE', 'SITE', 'SITS', 'SITU', 'SKAT', 'SKEW', 'SKID', 'SKIM', 'SKIN', 'SKIT', 'SLAB', 'SLAM', 'SLAT', 'SLAY', 'SLED', 'SLEW', 'SLID', 'SLIM', 'SLIT', 'SLOB', 'SLOG', 'SLOT', 'SLOW', 'SLUG', 'SLUM', 'SLUR', 'SMOG', 'SMUG', 'SNAG', 'SNOB', 'SNOW', 'SNUB', 'SNUG', 'SOAK', 'SOAR', 'SOCK', 'SODA', 'SOFA', 'SOFT', 'SOIL', 'SOLD', 'SOME', 'SONG', 'SOON', 'SOOT', 'SORE', 'SORT', 'SOUL', 'SOUR', 'SOWN', 'STAB', 'STAG', 'STAN', 'STAR', 'STAY', 'STEM', 'STEW', 'STIR', 'STOW', 'STUB', 'STUN', 'SUCH', 'SUDS', 'SUIT', 'SULK', 'SUMS', 'SUNG', 'SUNK', 'SURE', 'SURF', 'SWAB', 'SWAG', 'SWAM', 'SWAN', 'SWAT', 'SWAY', 'SWIM', 'SWUM', 'TACK', 'TACT', 'TAIL', 'TAKE', 'TALE', 'TALK', 'TALL', 'TANK', 'TASK', 'TATE', 'TAUT', 'TEAL', 'TEAM', 'TEAR', 'TECH', 'TEEM', 'TEEN', 'TEET', 'TELL', 'TEND', 'TENT', 'TERM', 'TERN', 'TESS', 'TEST', 'THAN', 'THAT', 'THEE', 'THEM', 'THEN', 'THEY', 'THIN', 'THIS', 'THUD', 'THUG', 'TICK', 'TIDE', 'TIDY', 'TIED', 'TIER', 'TILE', 'TILL', 'TILT', 'TIME', 'TINA', 'TINE', 'TINT', 'TINY', 'TIRE', 'TOAD', 'TOGO', 'TOIL', 'TOLD', 'TOLL', 'TONE', 'TONG', 'TONY', 'TOOK', 'TOOL', 'TOOT', 'TORE', 'TORN', 'TOTE', 'TOUR', 'TOUT', 'TOWN', 'TRAG', 'TRAM', 'TRAY', 'TREE', 'TREK', 'TRIG', 'TRIM', 'TRIO', 'TROD', 'TROT', 'TROY', 'TRUE', 'TUBA', 'TUBE', 'TUCK', 'TUFT', 'TUNA', 'TUNE', 'TUNG', 'TURF', 'TURN', 'TUSK', 'TWIG', 'TWIN', 'TWIT', 'ULAN', 'UNIT', 'URGE', 'USED', 'USER', 'USES', 'UTAH', 'VAIL', 'VAIN', 'VALE', 'VARY', 'VASE', 'VAST', 'VEAL', 'VEDA', 'VEIL', 'VEIN', 'VEND', 'VENT', 'VERB', 'VERY', 'VETO', 'VICE', 'VIEW', 'VINE', 'VISE', 'VOID', 'VOLT', 'VOTE', 'WACK', 'WADE', 'WAGE', 'WAIL', 'WAIT', 'WAKE', 'WALE', 'WALK', 'WALL', 'WALT', 'WAND', 'WANE', 'WANG', 'WANT', 'WARD', 'WARM', 'WARN', 'WART', 'WASH', 'WAST', 'WATS', 'WATT', 'WAVE', 'WAVY', 'WAYS', 'WEAK', 'WEAL', 'WEAN', 'WEAR', 'WEED', 'WEEK', 'WEIR', 'WELD', 'WELL', 'WELT', 'WENT', 'WERE', 'WERT', 'WEST', 'WHAM', 'WHAT', 'WHEE', 'WHEN', 'WHET', 'WHOA', 'WHOM', 'WICK', 'WIFE', 'WILD', 'WILL', 'WIND', 'WINE', 'WING', 'WINK', 'WINO', 'WIRE', 'WISE', 'WISH', 'WITH', 'WOLF', 'WONT', 'WOOD', 'WOOL', 'WORD', 'WORE', 'WORK', 'WORM', 'WORN', 'WOVE', 'WRIT', 'WYNN', 'YALE', 'YANG', 'YANK', 'YARD', 'YARN', 'YAWL', 'YAWN', 'YEAH', 'YEAR', 'YELL', 'YOGA', 'YOKE' ) ; const CharMap = 'abcdefghijklmnopqrstuvwxyz1234567890'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpGetRandomSeed: string ; var I: Integer ; Maplen, Seedlen: integer ; begin //result := '' ; Seedlen := IcsRandomInt (12) + 4 ; { seed length 4 to 16 } Maplen := Length (CharMap) - 1 ; SetLength(Result, SeedLen); for I := 1 to Seedlen do //result := result + CharMap [IcsRandomInt (Maplen) + 1] ; Result[I] := CharMap [IcsRandomInt (Maplen) + 1]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpIsValidPassword (const OtpPassword: string): boolean; begin result := (Length(OtpPassword) > 9) and (Length(OtpPassword) <= 63); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpIsValidSeed (const OptSeed: string): boolean; var I: integer; begin result := (OptSeed <> '') and (Length (OptSeed) <= 16); if not Result then exit; for I := 1 to Length (OptSeed) do begin if Pos (OptSeed [I], CharMap) <= 0 then begin result := false; break; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpLowNoSpace (const AString: string): string; var I, J: integer; begin {result := ''; for I := 1 to Length(AString) do begin if (AString[I] <> ' ') and (AString[I] <> #9) then result := result + LowerCase (AString [I]); end;} SetLength(Result, Length(AString)); J := 0; for I := 1 to Length(AString) do begin if (AString[I] <> ' ') and (AString[I] <> #9) then begin Inc(J); Result[J] := AString[I]; end; end; SetLength(Result, J); Result := LowerCase(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* function RevEndian64(X: Int64): Int64; begin result := (X and $00000000000000FF) shl 56; result := result + (X and $000000000000FF00) shl 40; result := result + (X and $0000000000FF0000) shl 24; result := result + (X and $00000000FF000000) shl 8; result := result + (X and $000000FF00000000) shr 8; result := result + (X and $0000FF0000000000) shr 24; result := result + (X and $00FF000000000000) shr 40; result := result + (X and $FF00000000000000) shr 56; end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function KeyToHex(OtpKey: TOtp64bit): string; {$IFDEF USE_INLINE} inline; {$ENDIF} {var I: integer ;} begin {result := ''; for I := 0 to 7 do result := result + IntToHex(OtpKey [I], 2);} Result := IcsBufferToHex(OtpKey[0], SizeOf(OtpKey)); end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function KeyToSixWordFormat (OtpKey: TOtp64bit): string; var I, parity: integer; Key64: int64; function GetBits (Start: integer; Count: integer): word; begin result := (Key64 shl Start) shr (64 - Count); end; begin { convert 8 bytes to int64 } //Key64 := RevEndian64 (TInt64Rec (OtpKey).Quad) ; //IcsSwap64Buf(@TInt64Rec(OtpKey).Quad, @Key64, 1); Key64 := IcsSwap64(TInt64Rec(OtpKey).Quad); // New and faster { get 11-bits five times and get five words from dictionary } for I := 0 to 4 do Result := Result + SixWordsList [GetBits (I * 11, 11)] + ' ' ; parity := 0; { sixth word includes two parity bits } for I := 0 to 31 do inc (parity, GetBits (I * 2, 2)); parity := parity and 3; result := result + SixWordsList [GetBits (55, 11) + parity]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetMD4Half (Buffer: Pointer; BufSize: Integer): TOtp64bit; var I: integer; MD4Context: TMD4Context; MD4Digest: TMD4Digest; begin { get normal 128-bit MD4 hash } MD4Init (MD4Context); MD4Update (MD4Context, Buffer^, BufSize); MD4Final (MD4Context, MD4Digest); { fold 128-bits of MD4 hash into 64-bits } for I := 0 to 7 do Result [I] := MD4Digest [I] XOR MD4Digest [I + 8]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetMD5Half (Buffer: Pointer; BufSize: Integer): TOtp64bit; var I: integer; MD5Context: TMD5Context; MD5Digest: TMD5Digest; begin { get normal 128-bit MD5 hash } MD5Init (MD5Context); MD5UpdateBuffer (MD5Context, Buffer, BufSize); MD5Final (MD5Digest, MD5Context); { fold 128-bits of MD5 hash into 64-bits } for I := 0 to 7 do result [I] := MD5Digest [I] XOR MD5Digest [I + 8]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* procedure SwapIntBuf(Source, Dest: Pointer; Count: Integer); asm TEST ECX,ECX JLE @Exit PUSH EBX SUB EAX,4 SUB EDX,4 @@1: MOV EBX,[EAX + ECX * 4] BSWAP EBX MOV [EDX + ECX * 4],EBX DEC ECX JNZ @@1 POP EBX @Exit: end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetSha1Half (Buffer: Pointer; BufSize: Integer): TOtp64bit; var I: integer; Digest: AnsiString; { V1.02 } begin Digest := SHA1ofBuf (Buffer, BufSize); if Length (Digest) <> 20 then exit; { sanity check } { fold 160-bits of Sha1 hash into 64-bits } for I := 0 to 7 do Result [I] := Ord (Digest [I + 1]) XOR Ord (Digest [I + 9]); for I := 0 to 3 do Result [I] := Result [I] XOR Ord (Digest [I + 17]); { change endian order } //SwapIntBuf(@Result[0], @Result[0], 2); IcsSwap32Buf(@Result[0], @Result[0], 2); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GenerateKey64 (OtpMethod: TOtpMethod; const OptSeed: string; const OtpPassword: string; const OtpSequence: Integer): TOtp64bit; var I: integer; HashText: AnsiString; { V1.02 } begin { hash seed and password (max 63) into 64-bits } HashText := AnsiString (LowerCase (OptSeed) + OtpPassword); { V1.02 } case OtpMethod of OtpKeyMd5: result := GetMD5Half (@HashText [1], Length (HashText)); OtpKeyMd4: result := GetMD4Half (@HashText [1], Length (HashText)); OtpKeySha1: result := GetSha1Half (@HashText [1], Length (HashText)); end; { rehash the 64-bits repeatedly, according to sequence number in challenge } if OtpSequence <= 0 then exit ; for I := 1 to OtpSequence do begin case OtpMethod of OtpKeyMd5: result := GetMD5Half (@result, 8); OtpKeyMd4: result := GetMD4Half (@result, 8); OtpKeySha1: result := GetSha1Half (@result, 8); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpGetMethod (const S: string): TOtpMethod; var Method: TOtpMethod; begin { find hash method from string } for Method := Low (TOtpMethod) to High (TOtpMethod) do begin if Pos (OtpKeyNames [Ord (Method)], S) = 1 then begin result := Method; exit; end ; end; result := OtpKeyNone; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpParseChallenge (const OtpChallenge: string; var OtpMethod: TOtpMethod; var OtpSequence: integer; var OtpSeed: string): boolean; var J: integer; Method: TOtpMethod; S: string ; begin { challenge example: Response to otp-md5 999 sill116 required for skey. } result := false; OtpMethod := OtpKeyNone; OtpSequence := 0; OtpSeed := ''; { find hash method from challenge } for Method := Low (TOtpMethod) to High (TOtpMethod) do begin J := Pos (OtpKeyNames [Ord (Method)], OtpChallenge); if J >= 1 then begin OtpMethod := Method; S := Trim (Copy (OtpChallenge, J + Length (OtpKeyNames [Ord (OtpMethod)]), 999)); break; end ; end; if OtpMethod = OtpKeyNone then exit; { find Sequence - 0 to 999 } J := Pos (' ', S); if J <= 1 then exit; OtpSequence := atoi (Copy (S, 1, J)); { find Seed } S := Trim (Copy (S, J, 999)) + ' ' ; J := Pos (' ', S); OtpSeed := Lowercase (Trim (Copy (S, 1, J))); result := OtpIsValidSeed (OtpSeed); end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpIsValidChallenge (const OtpChallenge: string): boolean; var OtpMethod: TOtpMethod; OtpSequence: integer; OtpSeed: string; begin result := OtpParseChallenge (OtpChallenge, OtpMethod, OtpSequence, OtpSeed) ; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpProcessChallenge (const OtpChallenge, OtpPassword: string; HexResp: boolean ; var OtpRespKey: string): boolean; var OtpMethod: TOtpMethod; OtpSequence: integer; OtpSeed: string; Key64: TOtp64bit; begin OtpRespKey := ''; { check for valid challenge, extract parameters } result := OtpParseChallenge (OtpChallenge, OtpMethod, OtpSequence, OtpSeed); if not Result then exit; { generate 64-bit response key, convert to 'six words' or hex one time password } Key64 := GenerateKey64 (OtpMethod, OtpSeed, OtpPassword, OtpSequence); if NOT HexResp then OtpRespKey := KeyToSixWordFormat (Key64) else OtpRespKey := KeyToHex (Key64); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpCreateChallenge (OtpMethod: TOtpMethod; var OtpSequence: integer; var OtpSeed: string): string; begin result := ''; if OtpMethod = OtpKeyNone then exit; OtpSeed := LowerCase (OtpSeed) ; if (OtpSequence < 0) or (NOT OtpIsValidSeed (OtpSeed)) then begin OtpSequence := InitialSequence; OtpSeed := OtpGetRandomSeed; end ; result := OtpKeyNames [Ord (OtpMethod)] + ' ' + IntToStr(OtpSequence) + ' ' + OtpSeed; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OtpTestPassword ( const OtpRespKey, OtpPassword: string; OtpMethod: TOtpMethod; var OtpSequence: integer; const OtpSeed: string): boolean; var Key64: TOtp64bit; KeyHex, Key6W, RespKey: string; begin Key64 := GenerateKey64 (OtpMethod, OtpSeed, OtpPassword, OtpSequence); RespKey := OtpLowNoSpace (OtpRespKey) ; KeyHex := OtpLowNoSpace (KeyToHex (Key64)); Key6W := OtpLowNoSpace (KeyToSixWordFormat (Key64)); result := (RespKey = Key6W); if not Result then Result := (RespKey = KeyHex); if (NOT result) and (OtpMethod = OtpKeyNone) then result := (OtpRespKey = OtpPassword) ; if Result then Dec (OtpSequence); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
PROGRAM d1a; USES sysutils; FUNCTION answer(filename:string) : longint; VAR f: text; l: string; elf_total_calories: longint = 0; BEGIN answer := 0; assign(f, filename); reset(f); REPEAT readln(f, l); IF l <> '' THEN elf_total_calories += strtoint(l) ELSE BEGIN{next elf} IF elf_total_calories > answer THEN answer := elf_total_calories; elf_total_calories := 0; continue; END; UNTIL eof(f); IF elf_total_calories > answer THEN answer := elf_total_calories; close(f); END; CONST testfile = 'd1.test.1'; filename = 'd1.input'; BEGIN{d1a} assert(answer(testfile) = 24000, 'test faal'); writeln('answer: ', answer(filename)); END.
unit nsUtils; {------------------------------------------------------------------------------} { Библиотека : Бизнес слой проекта "Немезис"; } { Автор : Морозов М.А; } { Начат : 29.09.2005 12.42; } { Модуль : nsUtils } { Описание : Общие функции проекта Немезис. } {------------------------------------------------------------------------------} // $Id: nsUtils.pas,v 1.53 2016/10/28 14:11:41 kostitsin Exp $ // $Log: nsUtils.pas,v $ // Revision 1.53 2016/10/28 14:11:41 kostitsin // {requestlink: 631999129 } // // Revision 1.52 2016/09/30 06:45:28 morozov // {RequestLink: 630816084} // // Revision 1.51 2016/09/14 13:01:18 kostitsin // {requestlink: 630222434 } // // Revision 1.50 2016/08/03 13:13:06 lulin // - перегенерация. // // Revision 1.49 2016/08/02 17:12:48 lulin // - перегенерация. // // Revision 1.48 2016/07/26 12:56:07 lulin // - перегенерация. // // Revision 1.47 2016/07/15 11:25:37 lulin // - выпрямляем зависимости. // // Revision 1.46 2016/07/14 11:31:38 morozov // {RequestLink: 627015303} // // Revision 1.45 2016/04/14 12:13:34 morozov // {RequestLink: 621277863} // // Revision 1.44 2015/07/30 10:11:21 kostitsin // {requestlink: 604032841 } - вынес логирование в отдельный пакет из помойки "data" // // Revision 1.43 2015/04/16 16:51:32 lulin // - перерисовываем. // // Revision 1.42 2015/03/18 11:42:35 morozov // {RequestLink: 591142224} // // Revision 1.41 2014/11/14 11:15:42 kostitsin // {requestlink: 573687343 } // // Revision 1.40 2014/11/14 10:50:16 kostitsin // {requestlink: 573687343 } // // Revision 1.39 2014/10/13 11:46:14 morozov // {RequestLink: 567553873} // // Revision 1.38 2014/08/01 11:47:46 morozov // {RequestLink: 530839714} - контекстное меню для списка // // Revision 1.37 2014/07/17 07:26:17 morozov // {RequestLink: 340174500} // // Revision 1.36 2014/06/27 09:12:16 morozov // {RequestLink: 340174500} // // Revision 1.35 2014/01/15 12:57:28 kostitsin // {requestlink: 451251129} // // Revision 1.34 2013/10/04 06:20:46 morozov // {RequestLink: 488611207} // // Revision 1.33 2013/09/23 07:33:22 morozov // {RequestLink: 484018812} // // Revision 1.32 2013/09/17 09:24:19 morozov // {RequestLink: 483399976} // // Revision 1.31 2013/09/12 13:34:45 morozov // {RequestLink: 481813781} // // Revision 1.30 2013/09/09 11:12:46 morozov // {RequestLink: 480833251} // // Revision 1.29 2013/09/09 11:08:27 morozov // {RequestLink: 480833251} // // Revision 1.28 2013/04/24 09:35:56 lulin // - портируем. // // Revision 1.27 2012/08/03 13:19:35 kostitsin // [$380616604] // - nsUtils // // Revision 1.26 2012/07/26 18:34:56 lulin // {RequestLink:378540022} // // Revision 1.25 2012/07/24 18:26:04 lulin // - чистка кода. // // Revision 1.24 2012/03/23 17:55:05 lulin // - выпиливаем настройки. // // Revision 1.23 2011/11/25 14:27:28 gensnet // http://mdp.garant.ru/pages/viewpage.action?pageId=304875977 // // Revision 1.22 2011/11/15 11:12:25 gensnet // http://mdp.garant.ru/pages/viewpage.action?pageId=298419252 // // Revision 1.21 2011/06/27 13:54:04 lulin // {RequestLink:254944102}. // // Revision 1.20 2011/06/02 12:36:14 lulin // {RequestLink:265396831}. // // Revision 1.19 2011/04/21 14:48:32 migel // - spell: `Exiension` -> `Extension`. // // Revision 1.18 2011/04/21 12:30:55 migel // - add: поддержка для новых типов ExternalObjects. // // Revision 1.17 2010/11/29 08:44:32 lulin // {RequestLink:243698529}. // // Revision 1.16 2010/10/28 06:56:45 demon // - Функции "Открыть по номеру" теперь могут принимать адрес параграфа // // Revision 1.15 2010/10/25 08:36:46 lulin // {RequestLink:237502802}. // Шаг №2. // // Revision 1.14 2010/10/04 12:32:31 oman // - new: Заглушки и не падаем {RequestLink:235057812} // // Revision 1.13 2010/03/22 15:44:17 lulin // {RequestLink:198672893}. // - упрощаем сигнатуры фабрик. // // Revision 1.12 2010/03/22 14:42:30 lulin // {RequestLink:198672893}. // // Revision 1.11 2009/12/09 13:08:20 lulin // {RequestLink:124453871}. // // Revision 1.10 2009/12/09 09:23:34 lulin // - убиваем неиспользуемый класс. // // Revision 1.9 2009/12/08 15:27:29 lulin // - переносим TdeSearchInfo на модель. // // Revision 1.8 2009/12/07 18:36:34 lulin // - переносим "интерфейсы обмена данными" в правильные места. // // Revision 1.7 2009/11/25 10:19:37 oman // - new: LE_TIME_MACHINE_ON {RequestLink:121157219} // // Revision 1.6 2009/10/15 08:33:31 oman // - new: Готовим к переносу на модель {RequestLink:122652464} // // Revision 1.5 2009/10/06 14:39:37 lulin // {RequestLink:162596818}. Добавляем кнопки. // // Revision 1.4 2009/09/29 16:34:51 lulin // {RequestLink:159360578}. №39. // Поправил использование пакетов. // // Revision 1.3 2009/09/28 19:14:22 lulin // - вычищаем ненужные возвращаемые параметры. // // Revision 1.2 2009/09/25 17:14:51 lulin // - убрал ужасную зависимость папок от консультаций. // // Revision 1.1 2009/09/14 11:28:53 lulin // - выводим пути и для незавершённых модулей. // // Revision 1.128 2009/09/07 12:26:52 lulin // - сделана фабрика для открытия списков. // // Revision 1.127 2009/09/04 17:08:23 lulin // {RequestLink:128288497}. // // Revision 1.126 2009/08/24 08:36:38 lulin // - переносим системные операции на модель. // // Revision 1.125 2009/08/05 10:09:55 oman // - new: Обрабатываем локальные ссылки - {RequestLink:158795570} // // Revision 1.124 2009/08/04 11:25:42 lulin // [$159351827]. // // Revision 1.123 2009/07/31 17:29:55 lulin // - убираем мусор. // // Revision 1.122 2009/06/03 12:28:03 oman // - new: компилируемся - [$148014435] // // Revision 1.121 2009/02/20 17:57:44 lulin // - <K>: 136941122. Чистка кода. // // Revision 1.120 2009/02/10 19:03:55 lulin // - <K>: 133891247. Вычищаем морально устаревший модуль. // // Revision 1.119 2009/02/09 19:17:25 lulin // - <K>: 133891247. Выделяем интерфейсы поиска. // // Revision 1.118 2009/02/09 13:21:27 lulin // - <K>: 133891247. // // Revision 1.117 2009/01/29 13:25:39 lulin // - <K>: 136253229. Заготовка приложения. // // Revision 1.116 2009/01/29 09:00:57 lulin // http://mdp.garant.ru/pages/viewpage.action?pageId=136253229&focusedCommentId=136253790#comment-136253790 // // Revision 1.115 2009/01/21 19:18:18 lulin // - <K>: 135602528. // // Revision 1.114 2009/01/19 13:12:41 lulin // - <K>: 134316707. // // Revision 1.113 2009/01/11 16:09:49 lulin // - <K>: 133138664. №14. // // Revision 1.112 2008/12/29 18:16:31 lulin // - приводим модель в порядок. // // Revision 1.111 2008/12/29 17:23:46 lulin // - чистим код. // // Revision 1.110 2008/12/29 17:07:48 lulin // - обобщаем код. // // Revision 1.109 2008/12/29 16:52:38 lulin // - чистка кода. // // Revision 1.108 2008/12/29 16:26:12 lulin // - <K>: 133891773. // // Revision 1.107 2008/12/29 15:56:03 lulin // - <K>: 133891773. // // Revision 1.106 2008/12/29 12:57:35 lulin // - <K>: 133891773. // // Revision 1.105 2008/12/25 15:56:20 lulin // - <K>: 133891729. // // Revision 1.104 2008/12/25 12:20:11 lulin // - <K>: 121153186. // // Revision 1.103 2008/12/24 19:49:44 lulin // - <K>: 121153186. // // Revision 1.102 2008/12/10 16:46:14 lulin // - <K>: 128297578. // // Revision 1.101 2008/12/08 11:12:54 oman // - fix: Запрещаем контекстное меню во всех флешах (К-128297304) // // Revision 1.100 2008/12/08 09:33:21 lulin // - <K>: 128292941. // // Revision 1.99 2008/12/05 14:58:09 lulin // - переименован базовый модуль. // // Revision 1.98 2008/11/27 20:39:11 lulin // - <K>: 122674167. // // Revision 1.97 2008/11/14 10:35:02 lulin // - <K>: 122675356. // // Revision 1.96 2008/10/24 14:56:35 lulin // - чистка кода. // // Revision 1.95 2008/10/01 12:22:13 oman // - fix: Новый тип встроенного объекта (К-120718929) // // Revision 1.94 2008/09/30 17:32:10 lulin // - bug fix: не масштабировался flash-splash. // // Revision 1.93 2008/09/30 12:43:22 lulin // - <K>: 119472469. // // Revision 1.92 2008/09/26 08:00:51 oman // - new: Поддержка CDR и PPT (К-119473376) // // Revision 1.91 2008/08/21 09:32:58 mmorozov // - new behaviour: не работаем с FlashActiveX, если недоступна загрузка из потока (<K> - 108626065); // // Revision 1.90 2008/08/04 12:15:04 mmorozov // - new behaviour: определяем наличие flash-компонента созданием самого компонента, в реестре читать нельзя, т.к. в молебокс версии он доступен, но в ОС не зарегистирован (K<104434872>); // // Revision 1.89 2008/07/31 12:55:31 mmorozov // - new: умеем работать без компонента FlashActiveX (K<104434872>). // // Revision 1.88 2008/07/23 11:56:01 mmorozov // - change: интерфейс открытия документа по номеру (K<100958789>); // // Revision 1.87 2008/07/23 11:49:06 mmorozov // - change: интерфейс открытия документа по номеру (K<100958789>); // // Revision 1.86 2008/07/23 06:16:06 mmorozov // - new: новый логотип (K<96484097>); // // Revision 1.85 2008/07/22 10:42:45 oman // - new: Отключение пищалки - везде кроме КЗ (К-103940886) // // Revision 1.84 2008/07/22 08:47:05 mmorozov // - new: сохранение\загрузка документов-схем из моих документов, сохранение в журнал работы (K<103940108>); // // Revision 1.83 2008/07/22 07:34:39 oman // - new: Поддержка pdf и tiff в качестве внешних ссылок (К-103940329) // // Revision 1.82 2008/07/18 17:15:35 mmorozov // - bugfix: Не сразу меняется имя документа на вкладке "на контроле" (K<99647730>); // // Revision 1.81 2008/07/02 08:03:36 mmorozov // - change: состояние консультации стало множеством (K<97354368>). // // Revision 1.80 2008/06/23 12:28:41 mmorozov // - работа над документом-схемой... обработка ссылок из схемы (CQ: OIT5-29377). // // Revision 1.79 2008/06/19 13:06:46 mmorozov // - убрана проверка. // // Revision 1.78 2008/05/14 11:37:47 mmorozov // - bugfix: при возврате в список из документа не применяем постоянные фильтры. // // Revision 1.77 2008/05/08 06:27:58 mmorozov // - применение постоянных фильтров; // // Revision 1.76 2008/05/08 04:58:28 mmorozov // - rename: QueryInfo -> SearchInfo; // // Revision 1.75 2008/05/05 12:05:55 mmorozov // - new: показ документа в извлечениях доступен только после поиска в котором выбрано значение реквизита "Раздел\Тема" (CQ: OIT5-9285, 9656). // // Revision 1.74 2008/04/21 10:53:49 mmorozov // - new: при фильтрации элементов моих документов используется параметр для чего вызвали мои документы: документы | препараты. // // Revision 1.73 2008/04/14 12:20:21 mmorozov // - работа с моими документами из списка; // // Revision 1.72 2008/04/02 11:43:07 mmorozov // - пилим общую функциональность списка (создать новый список); // // Revision 1.71 2008/03/25 10:56:20 oman // Cleanup - расчищаем под HyperlinkManager // // Revision 1.70 2008/02/19 11:09:25 mmorozov // - format code; // // Revision 1.69 2008/01/30 08:24:58 mmorozov // - new: отложенное обновление представлений при перемещении по деревьям ППС 6.х (CQ: OIT5-28303); // // Revision 1.68 2008/01/17 06:45:19 mmorozov // - new: подписка слушателя на уведомления об изменении настройки; // // Revision 1.67 2008/01/10 07:23:30 oman // Переход на новый адаптер // // Revision 1.66 2007/12/26 07:57:48 mmorozov // - new: данные дерева уведомляют слушателей о своём обновлении + подписываем тех, кому это интересно (в рамках CQ: OIT5-27823); // // Revision 1.65 2007/12/25 11:32:10 mmorozov // - new: подписка на обновление данных приложения (CQ: OIT5-27823); // // Revision 1.64 2007/12/17 12:22:31 mmorozov // - уведомления о начале редактирования, а также изменения пользовательских настроек + избавляемся от операции enSystem.opConfigUpdated (в рамках CQ: OIT5-27823); // // Revision 1.63 2007/12/10 12:51:10 mmorozov // - new: реализуем шаблон publisher\subscriber при редактировании настроек, замены настроек (переключения конфигураций), настройке панелей инструментов (в рамках CQ: OIT5-27823); // // Revision 1.62.2.3 2007/11/27 07:21:50 oman // Перепиливаем на новый адаптер - логгирование // // Revision 1.62.2.2 2007/11/23 10:15:37 oman // Перепиливаем на новый адаптер // // Revision 1.62.2.1 2007/11/16 14:03:50 oman // Перепиливаем на новый адаптер // // Revision 1.63 2007/12/10 12:51:10 mmorozov // - new: реализуем шаблон publisher\subscriber при редактировании настроек, замены настроек (переключения конфигураций), настройке панелей инструментов (в рамках CQ: OIT5-27823); // // Revision 1.64 2007/12/17 12:22:31 mmorozov // - уведомления о начале редактирования, а также изменения пользовательских настроек + избавляемся от операции enSystem.opConfigUpdated (в рамках CQ: OIT5-27823); // // Revision 1.62 2007/10/20 14:11:39 mmorozov // - Рефакторинг работы с консультациями ввел недостающее для нормальной работы состояние bs_csPaymentRefusalOldFormat; // - Изжил интерфейс (и реализацию) IdeConsultation, по сути частично дублировала _IbsConsultation; // - cleanup; // // Revision 1.61 2007/10/03 12:49:20 mmorozov // - new: разрешаем включать машину времени на дату ревизии базы + для документов с открытой датой действия делаем недоступной операцию включить машину времени с даты действия текущей редакции + сопуствующий рефакторинг (в рамках CQ: OIT5-26843; K<56295615>); // // Revision 1.60 2007/09/28 07:03:07 mmorozov // - небольшой рефакторинг _StdRes и _nsSaveDialog; // - разделяем получение имени файла для диалогов сохранения и временных файлов + сопутствующий рефакторинг (в рамках работы над CQ: OIT5-26809); // // Revision 1.59 2007/08/15 16:16:31 mmorozov // - change: изолируем мониторинги от знания bsConsultation; // // Revision 1.58 2007/08/14 07:32:32 mmorozov // - new: поддержка работы с удаленной консультаций (CQ: OIT5-25868); // // Revision 1.57 2007/07/26 12:27:48 oman // - fix: Заточки для локализации vtHeader (cq24480) // // Revision 1.56 2007/07/19 13:24:06 mmorozov // - add comment; // // Revision 1.55 2007/07/17 13:26:44 mmorozov // - new: изменены интерфейсы логирования событий (в рамках CQ: OIT5-25852); // // Revision 1.54 2007/06/29 07:58:26 mmorozov // - new: новые статусы консультаций "Ответ получен, но его получение не подтверждено в компании Гарант", "Ответ прочитан, но его получение не подтверждено в компании Гарант" (CQ: OIT5-25338); // // Revision 1.53 2007/05/17 12:04:16 oman // cleanup // // Revision 1.52 2007/04/17 12:27:39 lulin // - используем функции преобразования строки с кодировкой к имени файла. // // Revision 1.51 2007/04/05 13:42:47 lulin // - избавляемся от лишних преобразований строк. // // Revision 1.50 2007/03/20 11:38:18 lulin // - не теряем кодировку при присваивании заголовков форм и контролов. // // Revision 1.49 2007/03/16 16:57:11 lulin // - избавляемся от излишнего копирования и преобразования строк. // // Revision 1.48 2007/03/16 09:56:43 lulin // - переводим на строки с кодировкой. // // Revision 1.47 2007/03/05 13:47:21 lulin // - переводим на строки с кодировкой. // // Revision 1.46 2007/02/27 09:17:55 lulin // - используем более простые ноды при работе с папками. // // Revision 1.45 2007/02/27 08:07:08 lulin // - cleanup. // // Revision 1.44 2007/02/16 19:19:20 lulin // - в выпадающих списках используем родной список строк. // // Revision 1.43 2007/02/13 14:33:26 lulin // - cleanup. // // Revision 1.42 2007/02/07 17:48:45 lulin // - избавляемся от копирования строк при чтении из настроек. // // Revision 1.41 2007/02/07 15:14:19 mmorozov // - change: TbsListAdditionalDataSource -> _TbsListSynchroForm; // // Revision 1.40 2007/02/07 14:47:33 lulin // - переводим на строки с кодировкой. // // Revision 1.39 2007/02/07 09:15:59 lulin // - переводим на строки с кодировкой. // // Revision 1.38 2007/02/06 09:03:05 lulin // - переводим на строки с кодировкой. // // Revision 1.37 2007/01/15 18:15:47 lulin // - требуем необходимости задания контейнера. // // Revision 1.36 2007/01/05 16:16:17 lulin // - cleanup. // // Revision 1.35 2006/12/04 08:14:54 mmorozov // - rename: some Il3LocaleInfo properties; // // Revision 1.34 2006/12/01 15:20:37 mmorozov // - new: информация о локали выделана в отдельный интерфейс; // // Revision 1.33 2006/11/28 15:35:26 mmorozov // - опубликован идентификатор языка приложения IafwApplication.LocateId: LCID; // - существовавшее свойство LocateId переименовано в DetailedLanguageId; // - после чтения строкового идентфикатора языка приложения проверяем его на допустимость; // - формируем идентфикаторы языков приложения по первому требованию; // - при определении языка прилоежния используем идентфикаторы опубликованные в afwInterfaces; // // Revision 1.32 2006/11/09 11:10:52 migel // - fix: вместо `SHGetFolderPath` используем `SHGetSpecialFolderLocation` для более полной совместимости между разными версиями Windows (CQ: 23536). // // Revision 1.31 2006/11/03 09:46:00 oman // Merge with B_NEMESIS_6_4_0 // // Revision 1.30.2.2 2006/10/25 07:29:50 oman // Продолжаем избавлятся от StdStr // // Revision 1.30.2.1 2006/10/13 11:07:46 mmorozov // - bugfix: после сохранения списка в папки устанавливаем правильный заголовок окна (CQ: OIT5-18745); // // Revision 1.30 2006/09/06 10:44:22 civ // fix: переименованы константы // // Revision 1.29 2006/07/25 09:39:26 mmorozov // - change: для получения отображаемого типа функции используем функцию вместо массива (элементы могут поменять свой порядок); // // Revision 1.28 2006/07/12 15:03:10 oman // - new beh: Формирование заголовка для новостной ленты другим макаром (cq21699) // // Revision 1.27 2006/07/07 15:23:29 mmorozov // - new: в письмо о консультации добавился статус (CQ: OIT500021512); // // Revision 1.26 2006/06/30 14:59:11 mmorozov // - new: секретная операция "Информация о консультации" вызываемая по секретному shortcut-у. Операция открыавет вежливое письмо сопровождая его информаций о консультации; // - change: обобщен код по работе с mailto (перенесено в nsUtils); // - change: переименованы функции модуля bsConvert; // // Revision 1.25 2006/06/29 11:56:09 mmorozov // - change: изменения в связи с поялением типа GblAdapter.TDateTime; // // Revision 1.24 2006/06/07 10:32:23 mmorozov // - bugfix: при повторном экспорте списка в Word имели системную ошибку, пытались писать в файл, который держал Word. Кроме того при экспорте создавалось два файла, первый пустой без расширения, второй с расшением с экпортированной информацией (CQ: OIT500021216); // // Revision 1.23 2006/05/30 15:19:27 dinishev // Remove procedure nsMakeImageListWrapper // // Revision 1.22 2006/05/25 10:41:45 oman // - new beh: Поддержка Il3ImageList для ProxyIngList // // Revision 1.21 2006/05/25 10:14:59 oman // - fix: закциливание // // Revision 1.20 2006/05/25 06:39:52 oman // - fix: Убрана зависимость l3 от vt. Новая функция nsMakeImageListWrapper // для получения правильной реализации Il3ImageList // // Revision 1.19 2006/05/23 10:39:41 mmorozov // - new behaviour: при выборе пункта меню "Мои консультации" раворачиваем узел со всеми вложенными; // // Revision 1.18 2006/05/23 07:31:58 mmorozov // - change: сохранение в настройки перед переключением конфигураций, открытием диалога настроек; // // Revision 1.17 2006/05/12 07:14:44 mmorozov // - изменения накопившиеся за время отсутствия CVS; // // Revision 1.16 2006/05/05 14:55:00 mmorozov // - change: обобщен код открытие журнала работы по позиционированию на узле в папках (подготовка почвы для открытия моих консультаций); // // Revision 1.15 2006/04/18 08:53:43 mmorozov // - new: оценка консультации; // - new: менеджер ссылок (bsHyperlinkManager); // - warnings fix; // // Revision 1.14 2006/04/18 08:22:02 oman // - new beh: перекладываем StdStr в _StdRes // // Revision 1.13 2006/04/17 12:09:01 oman // - change: Избавляем бизнес-объекты (слой модели) от обязательств // контроллера (хинты, imageindex) // - new beh: перекладываем StdStr в _StdRes // // Revision 1.12 2006/04/17 11:46:58 mmorozov // - не собиралось; // // Revision 1.11 2006/04/14 15:01:03 mmorozov // - new: новые иконки для прецедента консультации; // - change: выносим код с форм (они должны быть тонкими) и с бизнес объектов, который относиться к визуалке; // // Revision 1.10 2006/04/11 14:12:41 mmorozov // - change: выносим код с формы; // - bugfix: при сохранении файла не выдавалось подтверждение при если такой файл уже существовал (CQ: 20383); // // Revision 1.9 2006/04/11 12:07:04 mmorozov // - получение первого выбранного перенесено в nsUtils; // // Revision 1.8 2006/03/22 08:16:48 oman // - new beh: Вынос дублирующегося кода в общее место // // Revision 1.7 2006/03/20 09:47:53 mmorozov // - new: выводим дату в длинном формате в соответствии с текущей локалью (CQ: OIT500020043); // // Revision 1.6 2006/03/10 12:03:08 mmorozov // - new: при сохранении списка в xml пользователю предлагается две операции "Весь список", "Выделенные документы"; // - new: в качестве пути по умолчанию предлагается папка "Мои документы"; // // Revision 1.5 2005/12/02 13:27:02 mmorozov // - bugfix: правильным образом управляем выключением машины времени (cq: 00018418); // // Revision 1.4 2005/11/14 15:29:01 mmorozov // - cleanup: вычищены типы списка - "Переходом по рубрикатору", "Сохраненный", "После поиска"; // - new: переносим возвращение бизнес объектов списка на фабрику сборки; // // Revision 1.3 2005/09/30 14:07:38 mmorozov // - открытие мультиссылок; // // Revision 1.2 2005/09/30 07:58:41 mmorozov // change: общие части выносим за скобки; // // Revision 1.1 2005/09/29 10:12:39 mmorozov // new: открытие документа в новом/текущем окне; // {$Include nsDefine.inc} interface uses Dialogs, Classes, Controls, ImgList, SysUtils, ExtCtrls, Graphics, l3Interfaces, l3TreeInterfaces, l3InternalInterfaces, afwInterfaces, eeInterfaces, eeTreeView, vtSaveDialog, vtHeader, vtPngImgList, //vtShockwaveEx, vcmInterfaces, BaseTypesUnit, DocumentUnit, DynamicDocListUnit, {$If not Defined(Admin) AND not Defined(Monitorings) } FiltersUnit, {$IfEnd} bsTypes, nsTypes, StdRes, bsInterfaces, SearchInterfaces, FoldersDomainInterfaces ; {------------------------------------------------------------------------------} { Мои документы. } {------------------------------------------------------------------------------} {$If not Defined(Admin) AND not Defined(Monitorings) } function nsListTypeToFilterFor(aType: TbsListType): TnsFolderFilterFor; {-} {$IfEnd} {------------------------------------------------------------------------------} { Консультации } {------------------------------------------------------------------------------} procedure nsWriteLetterAboutConsultation(const aNode: Il3SimpleNode); {* - открывает письмо в почтовой программе по умолчанию. aNode - узел в папках. } {------------------------------------------------------------------------------} { Файлы } {------------------------------------------------------------------------------} function nsDeleteFileNameDots(const aFileName: Il3CString): Il3CString; {* - удаляет многоточие в конце файла. } {------------------------------------------------------------------------------} { Дерево } {------------------------------------------------------------------------------} procedure nsSelectAndExpand(const aTreeView: TeeTreeView; const aNode : IeeNode; const aAll : Boolean = False); {-} {$If not (defined(Monitorings) or defined(Admin))} procedure nsTimeMachineOn(const aDocument : IDocument; const aDate : BaseTypesUnit.TDate); {* - включить машину времени. } {$IfEnd} {------------------------------------------------------------------------------} { Документ } {------------------------------------------------------------------------------} {$If not (defined(Monitorings) or defined(Admin))} procedure nsSaveExternalObject(const aObject : IUnknown; const aType : TLinkedObjectType); {* - сохранить документ во внешний файл. } {$IfEnd} procedure nsParseDocumentNumber(const aNumber : Il3CString; var aDocId : Integer; var aPosID : Integer; var aPosType : TDocumentPositionType); overload; procedure nsParseDocumentNumber(const aNumber : Il3CString; var aDocID : Integer; var aPosID : Integer; var aPosType : TDocumentPositionType; var aNumberWrong : Boolean); overload; {* - строку с документов перевести в идентификатор документа и номер вхождения. } procedure nsParseDocumentNumber(const aNumber : String; var aDocId : Integer; var aPosID : Integer; var aPosType : TDocumentPositionType; var aNumberWrong : Boolean); overload; {* - строку с документов перевести в идентификатор документа и номер вхождения. } {$If not Defined(Admin) AND not Defined(Monitorings)} function nsOpenDocumentByNumber(aDocId: Integer; out aDocument: IDocument; aFaultMessage: Boolean = True): Boolean; overload; {* - открыть документ по номеру. } function nsOpenDocumentByNumber(aDocId: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aFaultMessage: Boolean = True; aIgnoreRefDoc: Boolean = False; aOpenKind: TvcmMainFormOpenKind = vcm_okInCurrentTab; aShowFaultMessageOnInvalidRef: Boolean = False): Boolean; overload; {* - открыть документ по номеру. } function nsOpenDocumentByNumber(const aDocPosition: String; anInternalID: Boolean = True; aFaultMessage: Boolean = True): Boolean; overload; {* - открыть документ по номеру. } function nsOpenLink(const aDocPosition: String; aInternalID: Boolean; aShowMainMenu: Boolean = False; aFaultMessage: Boolean = True): Boolean; overload; {* - открыть ссылку. } function nsOpenLink(aDocId: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aInternalID: Boolean = True; aShowMainMenu: Boolean = False; aFaultMessage: Boolean = True): Boolean; overload; {* - открыть ссылку. } function nsNeedShellToOpenDocument(const aDocPosition: String; anInternalID: Boolean; out aWrongID: Boolean): Boolean; {$IfEnd} {------------------------------------------------------------------------------} { Дерево } {------------------------------------------------------------------------------} procedure nsSetCurrentFirstSelected(const aTree : TeeTreeView; const aNode : Il3SimpleNode); {* - сделать текущим первый выделенный элемент. } function nsGetFirstSelectedChild(const aParent: Il3SimpleNode) : Il3SimpleNode; {* - получить первого выбранного ребенка. } {------------------------------------------------------------------------------} { Общие } {------------------------------------------------------------------------------} procedure nsPaintImage(aImageList : TvtNonFixedPngImageList; aPaintBox : TPaintBox; anIndex : Integer = 0; aEraseBackGround: Boolean = False); {* - вывести иконку на канвку. } function nsNewWindow(const aMainForm : IvcmContainer; aOpenKind : TvcmMainFormOpenKind = vcm_okInNewWindow; aNeedSwitchTab: Boolean = True): IvcmContainer; {* - открыть новое окно. } {$If not Defined(Admin) AND not Defined(Monitorings)} procedure nsOpenList(const aDynList : IDynList; const aMainForm : IvcmContainer; const aWhatDoingIfOneDoc : TbsWhatDoingIfOneDoc = wdOpenIfUserDefine; const aTimeMachineOff : Boolean = True; const aOpenFrom : TbsListOpenFrom = lofNone); {* - открывает список. } {$IfEnd} {$If not (defined(Monitorings) or defined(Admin))} function nsMyDocumentFolder(const aFileName : Il3CString; const aExtension : String = ''; const aCreate : Boolean = True): Il3CString; {* - возвращает системную папку "Мои документы" для текущего пользователя. } {$IfEnd} function nsDateToStr(const aDate: System.TDateTime): String; {-} function nsConvertAnnoKind(const aValue: Il3CString): Il3CString; {-} function nsPrepareTextForMailto(const aText: Il3CString): Il3CString; {* - конвертирует символы текста для открытия письма в почтовой программе. } function StringToOrientation(const aString : Il3CString): Integer; {-} {------------------------------------------------------------------------------} { Локализация } {------------------------------------------------------------------------------} function nsGetListHeaderLocalizationInfo(const aHeader: TvtCustomHeader): String; {-} procedure nsSetListHeaderLocalizationInfo(const aHeader: TvtCustomHeader; const anInfo: String); {-} {$IfDef InsiderTest} var g_WasBeep : Boolean = false; {$EndIf InsiderTest} procedure nsBeepWrongContext; {-} {------------------------------------------------------------------------------} {$If not Defined(Admin) AND not Defined(Monitorings)} function nsGetFilterCaption(const aFilter : IFilterFromQuery) : Il3CString; {$IfEnd} const cPosDelimiter = '.'; cParaPrefix = '#'; implementation uses Windows, StrUtils, ActiveX, ComObj, ShlObj, ShFolder, l3Base, l3ImageList, l3String, l3Chars, vtImageListWrapper, afwFacade, vcmBase, vcmExternalInterfaces, {$If not (defined(Monitorings) or defined(Admin))} vcmTabbedContainerFormDispatcher, {$IfEnd not (defined(Monitorings) or defined(Admin))} bsUtils, {$If not (defined(Monitorings) or defined(Admin))} bsConsultation, nsLogEvent, LoggingUnit, IOUnit, {$IfEnd not (defined(Monitorings) or defined(Admin))} {$If not (defined(Monitorings) or defined(Admin))} nsExternalObject, nsExternalObjectPrim, {$IfEnd} nsLogicOperationToFlags, nsTreeAttributeNodesNew, nsConst, nsFolderFilterInfo, nsOpenUtils, DataAdapter, DynamicTreeUnit, ExternalObjectUnit, DebugStr, SystemStr, {$If not (defined(Monitorings) or defined(Admin))} ConsultationInterfaces, ConsultationDomainInterfaces, deDocInfo, deListSet, deList, evdTypes, nsInternetUtils, {$IfEnd not (defined(Monitorings) or defined(Admin))} SearchDomainInterfaces, PrimPrimListInterfaces, deSearchInfo, bsTypesNew, bsDocumentMissingMessage, LoggingWrapperInterfaces, l3SimpleObject, nsLogManager, nsLogEventData, Base_Operations_F1Services_Contracts {$If not (defined(Monitorings) or defined(Admin))} , nsTryingToOpenMissingDocumentFromLinkEvent, bsConvert {$IfEnd not (defined(Monitorings) or defined(Admin))} ; {$If not (defined(Monitorings) or defined(Admin))} type TnsTimeMachineOnEvent = class(TnsLogEvent) public // public methods class procedure Log(const aDoc: IDocument; const aDate: BaseTypesUnit.TDate); end;//TnsTimeMachineOnEvent {$IfEnd not (defined(Monitorings) or defined(Admin))} procedure nsPaintImage(aImageList : TvtNonFixedPngImageList; aPaintBox : TPaintBox; anIndex : Integer = 0; aEraseBackGround: Boolean = False); {* - вывести иконку на канвку. } function lp_CalcOffset(const aParent, aChild: Integer): Integer; begin Result := 0; if aChild < aParent then Result := (aParent - aChild) div 2; end;//function lp_CalcOffsetY: Integer; begin if aEraseBackGround then begin aPaintBox.Canvas.Brush.Color := clWindow; aPaintBox.Canvas.Pen.Style := psClear; aPaintBox.Canvas.Rectangle(aPaintBox.Canvas.ClipRect); end; with aImageList do Draw(aPaintBox.Canvas, lp_CalcOffset(aPaintBox.Width, Width), lp_CalcOffset(aPaintBox.Height, Height), anIndex); end; {$If not Defined(Admin) AND not Defined(Monitorings) } function nsListTypeToFilterFor(aType: TbsListType): TnsFolderFilterFor; begin case aType of bs_ltDocument: Result := ns_ffDocument; bs_ltDrug: Result := ns_ffDrug; else begin Result := Low(TnsFolderFilterFor); Assert(False); end; end; end; {$IfEnd} {$If not (defined(Monitorings) or defined(Admin))} function nsOpenDocumentByNumberInternal(aDocId: Integer; out aDocument: IDocument; out aMissingInfo: IMissingInfo; aFaultMessage: Boolean = True): Boolean; forward; {$IfEnd not (defined(Monitorings) or defined(Admin))} { Консультации } procedure nsWriteLetterAboutConsultation(const aNode: Il3SimpleNode); {* - aNode - узел в папках. } { Получить название перечислимого типа } {$If not (defined(Monitorings) or defined(Admin))} function nsTypeToDisplayName(const aValue: TbsConsultationStatuses): Il3CString; {* - статус консультации. } procedure lp_AddStatus(const aStr: Il3CString); begin if l3IsNil(Result) then Result := aStr else Result := l3Cat([Result, l3Cat(', ', aStr)]); end; begin // Отправлена: if bs_csSent in aValue then lp_AddStatus(vcmCStr(str_csProcessing)); // Получен предварительный ответ: if bs_csPaymentRequest in aValue then lp_AddStatus(vcmCStr(str_csNotificationReceived)); // Получен ответ: if bs_csAnswerReceived in aValue then lp_AddStatus(vcmCStr(str_csAnswerReceived)); // Ответ получен, но его получение не подтверждено в компании Гарант: if bs_csAnswerNotConfirm in aValue then lp_AddStatus(vcmCStr(str_csAnswerReceivedAndNotConfirm)); // Ответ прочитан, но его получение не подтверждено в компании Гарант: if bs_csReadNotConfirm in aValue then lp_AddStatus(vcmCStr(str_csReadAndNotConfirm)); // Прочитана: if bs_csRead in aValue then lp_AddStatus(vcmCStr(str_csRead)); // Отправлена оценка: if bs_csEstimationSent in aValue then lp_AddStatus(vcmCStr(str_csEstimationWasSent)); // Ждет отправки: if bs_csDrafts in aValue then lp_AddStatus(vcmCStr(str_csDraft)); // Не отправлена: if [bs_csPaymentRefusal, bs_csPaymentRefusalOldFormat] * aValue <> [] then lp_AddStatus(vcmCStr(str_csNotSent)); // Подтверждена: if bs_csPaymentConfirm in aValue then lp_AddStatus(vcmCStr(str_csPaymentConfirm)); end;//nsTypeToDisplayName {$IfEnd not (defined(Monitorings) or defined(Admin))} {$If not (defined(Monitorings) or defined(Admin))} var l_Consultation : IbsConsultation; l_Mailto : Il3CString; begin l_Consultation := TbsConsultation.Make(bsGetConsultation(aNode)); try with l_Consultation do if (Data <> nil) and not WasDeleted then begin l_Mailto := nsPrepareTextForMailto( vcmFmt(str_strMailtoAboutConsultationProblem, [Caption, nsTypeToDisplayName(Status), Id, FormatDateTime('dd/mm/yyyy', WasCreated), FormatDateTime('dd/mm/yyyy', WasModified)])); nsDoShellExecute(l_Mailto); end;//if (Data <> nil) and not WasDeleted then finally l_Consultation := nil; end;//try..finally {$Else not (defined(Monitorings) or defined(Admin))} begin {$IfEnd not (defined(Monitorings) or defined(Admin))} end; { Файл } function nsDeleteFileNameDots(const aFileName: Il3CString): Il3CString; {* - удаляет многоточие в конце файла. } begin Result := l3RTrim(aFileName, ['.']); // Удалим точки в конце иначе неправильно будет работать диалог сохранения // файла, не будет выдаваться подтверждение при сохранении файла: end; { Дерево } {$If not (defined(Monitorings) or defined(Admin))} procedure nsTimeMachineOn(const aDocument : IDocument; const aDate : BaseTypesUnit.TDate); {* - включить машину времени. } begin TnsTimeMachineOnEvent.Log(aDocument, aDate); defDataAdapter.TimeMachine.Date := aDate; end;//nsTimeMachineOn {$IfEnd} procedure nsSelectAndExpand(const aTreeView : TeeTreeView; const aNode : IeeNode; const aAll : Boolean = False); {-} begin with aTreeView.TreeView do if (GoToNode(aNode) > 0) then begin // Развернуть все: if aAll then Tree.ExpandSubDir(aNode, True, 2) // Только первый уровень: else Tree.ChangeExpand(aNode, ee_sbSelect); aTreeView.DisableAlignTopIndex := True; //aTreeView.TopIndex := l_Index; end;//with aTreeView.TreeView do end;//nsSelectAndExpand { Документ } {$If not Defined(Admin) AND not Defined(Monitorings)} function nsOpenDocumentByNumberInternal(aDocId: Integer; out aDocument: IDocument; out aMissingInfo: IMissingInfo; aFaultMessage: Boolean = True): Boolean; {* - открыть документ по номеру. } begin // http://mdp.garant.ru/pages/viewpage.action?pageId=304875977 try aDocument := nil; Result := DefDataAdapter.CommonInterfaces. GetDocumentOnNumber(aDocId, aDocument, aMissingInfo); if (not Result) and aFaultMessage then TbsDocumentMissingMessage.Show(False, aMissingInfo); except on ECanNotFindData do Result := false; end;{try..except} end; function nsOpenDocumentByNumber(aDocId: Integer; out aDocument: IDocument; aFaultMessage: Boolean = True): Boolean; //overload; {* - открыть документ по номеру. } var l_MI: IMissingInfo; begin Result := nsOpenDocumentByNumberInternal(aDocId, aDocument, l_MI, aFaultMessage); if not Result then begin TnsTryingToOpenMissingDocumentFromLinkEvent.Log(aDocID); if aFaultMessage then TbsDocumentMissingMessage.Show(False, l_MI); end; end; function nsOpenDocumentByNumber(aDocId: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aFaultMessage: Boolean = True; aIgnoreRefDoc: Boolean = False; aOpenKind: TvcmMainFormOpenKind = vcm_okInCurrentTab; aShowFaultMessageOnInvalidRef: Boolean = False): Boolean; overload; // overload; {* - открыть документ по номеру. } var l_Document : IDocument; l_Container: IvcmContainer; l_ContainerMaker: IvcmContainerMaker; l_Topic: TTopic; l_MI: IMissingInfo; begin Result := nsOpenDocumentByNumberInternal(aDocId, l_Document, l_MI, False); if (not Result) then begin l3FillChar(l_Topic, SizeOf(l_Topic), 0); l_Topic.rPid.rObjectId := aDocID; l_Topic.rPid.rClassId := CI_TOPIC; l_Topic.rPosition.rPoint := aPosID; l_Topic.rPosition.rType := bsBusinessToAdapter(aPosType); TnsTryingToOpenMissingDocumentFromLinkEvent.Log(l_Topic); if aShowFaultMessageOnInvalidRef then TbsDocumentMissingMessage.Show(False, l_MI); end; if Result and ((l_Document.GetDocType = DT_REF) and (not aIgnoreRefDoc)) then begin Result := False; if aShowFaultMessageOnInvalidRef then TbsDocumentMissingMessage.Show; Exit; end; if Result then begin l_Container := nil; if TvcmTabbedContainerFormDispatcher.Instance.NeedUseTabs AND Supports(vcmDispatcher.FormDispatcher.CurrentMainForm.VCLWinControl, IvcmContainerMaker, l_ContainerMaker) then try l_Container := TvcmTabbedContainerFormDispatcher.Instance.MakeAndPlaceVCMContainer(l_ContainerMaker, vcmDispatcher.FormDispatcher.CurrentMainForm.AsContainer, aOpenKind, True); finally l_ContainerMaker := nil; end; TDocumentService.Instance.OpenDocument(TdeDocInfo.Make(l_Document, TbsDocPos_C(aPosType, Longword(aPosID))), l_Container); end; end; function nsOpenDocumentByNumber(const aDocPosition: String; anInternalID: Boolean = True; aFaultMessage: Boolean = True): Boolean; //overload; {* - открыть документ по номеру. } var l_DocId : Integer; l_PosID : Integer; l_PosType : TDocumentPositionType; l_NumberWrong : Boolean; begin Result := False; nsParseDocumentNumber(aDocPosition, l_DocId, l_PosID, l_PosType, l_NumberWrong); if not l_NumberWrong then begin if anInternalID then l_DocId := l_DocId + c_InternalDocShift; Result := nsOpenDocumentByNumber(l_DocId, l_PosID, l_PosType, aFaultMessage, False); end; end; function nsGetExternalLink(aDocId : Integer; aPosID : Integer; aPosType : TDocumentPositionType; aInternalId : Boolean; aFaultMessage : Boolean = False): IExternalLink; var l_DocId : Integer; l_Document: IDocument; l_Link: IExternalLink; l_Topic: TTopic; l_ObjType : TLinkedObjectType; l_Obj : IUnknown; l_MI: IMissingInfo; begin Result := nil; l_Link := nil; l_DocId := aDocId; if aInternalId then l_DocId := l_DocId + c_InternalDocShift; if nsOpenDocumentByNumberInternal(l_DocId, l_Document, l_MI, aFaultMessage) then try if (l_Document.GetDocType <> DT_REF) then Exit; l3FillChar(l_Topic, SizeOf(l_Topic), 0); with l_Topic do begin rPid.rObjectId := BaseTypesUnit.TObjectId(l_DocId); rPid.rClassId := CI_REF; rPosition.rPoint := aPosID; rPosition.rType := PT_SUB; end;//with l_Topic try l_Document.GetLinkedObject(l_DocId, l_Topic, 0, l_ObjType, l_Obj); except on EInvalidTopicID do begin Result := nil; Exit; end//on EInvalidTopicID else Assert(False); end;//try..except if (l_ObjType = LO_EXTERNAL_LINK) and Supports(l_Obj, IExternalLink, l_Link) then Result := l_Link; finally l_Obj := nil; l_Document := nil; l_Link := nil; end;//try..finally end;//nsGetExternalLink function nsOpenLink(const aDocPosition: String; aInternalID: Boolean; aShowMainMenu: Boolean = False; aFaultMessage: Boolean = True): Boolean; {* - открыть ссылку. } var l_DocId : Integer; l_PosID : Integer; l_PosType : TDocumentPositionType; l_NumberWrong : Boolean; begin Result := False; nsParseDocumentNumber(aDocPosition, l_DocId, l_PosID, l_PosType, l_NumberWrong); if not l_NumberWrong then Result := nsOpenLink(l_DocId, l_PosID, l_PosType, aInternalID, aShowMainMenu, aFaultMessage); end; function nsOpenLink(aDocId: Integer; aPosID: Integer; aPosType: TDocumentPositionType; aInternalId: Boolean = True; aShowMainMenu: Boolean = False; aFaultMessage: Boolean = True): Boolean; {* - открыть ссылку. } const cPrefixDelimiter = ':'; cScriptPrefix = 'script'; cEnoPrefix = 'eno'; var l_ExternalLink : IExternalLink; l_Url : IString; l_UrlStr : Il3CString; l_UrlWStr : WideString; l_P : Il3CString; l_S : Il3CString; begin l_ExternalLink := nsGetExternalLink(aDocId, aPosId, aPosType, aInternalId, aFaultMessage); if (l_ExternalLink <> nil) then try l_ExternalLink.GetUrl(l_Url); l_UrlStr := nsCStr(l_Url); if l3IsNil(l_UrlStr) then Result := false else begin l3Split(l_UrlStr, cPrefixDelimiter, l_P, l_S); Result := (not l3Same(l_P, cScriptPrefix)) AND (not l3Same(l_P, cEnoPrefix)) AND (not l3IsNil(l_S)); l_UrlWStr := l3WideString(l_UrlStr); // http://mdp.garant.ru/pages/viewpage.action?pageId=484018812 if aShowMainMenu and nsNeedOpenLinkInExternalBrowser(l_UrlWStr) then TMainMenuService.Instance.OpenMainMenuIfNeeded(nil); if Result then Result := nsDoShellExecute(l_UrlStr); end;//l3IsNil(l_UrlStr) finally l_ExternalLink := nil; l_Url := nil; l_UrlStr := nil; l_P := nil; l_S := nil; end;//try..finally end;//nsOpenLink function nsNeedShellToOpenDocument(const aDocPosition: String; anInternalID: Boolean; out aWrongID: Boolean): Boolean; var l_DocID: Integer; l_PosID: Integer; l_PosType: TDocumentPositionType; l_NumberWrong: Boolean; l_Document: IDocument; l_Link: IExternalLink; l_Url: IString; l_UrlStr: WideString; l_MI: IMissingInfo; begin Result := True; nsParseDocumentNumber(aDocPosition, l_DocId, l_PosId, l_PosType, l_NumberWrong); aWrongID := l_NumberWrong; if (not l_NumberWrong) then begin if anInternalID then l_DocId := l_DocId + c_InternalDocShift; if nsOpenDocumentByNumberInternal(l_DocId, l_Document, l_MI, False) then try if (l_Document.GetDocType <> DT_REF) then Exit else begin l_Link := nsGetExternalLink(l_DocId, l_PosID, l_PosType, False, False); if (l_Link = nil) then begin aWrongID := True; Exit; end;//if (l_Link = nil) l_Link.GetUrl(l_Url); l_UrlStr := l3WideString(nsCStr(l_Url)); Result := (nsIsGarantUrl(l_UrlStr) AND (not nsIsContractConstructorURL(l_UrlStr)) AND (not nsIsMobileGarantOnlineURL(l_UrlStr)) AND (not nsIsObtainRequisitesForMobileAccessURL(l_UrlStr))); end; finally l_Document := nil; l_Link := nil; l_Url := nil; end;//try..finally end;//if (not l_NumberWrong) end;//nsNeedShellToOpenDocument {$IfEnd} procedure nsParseDocumentNumber(const aNumber : Il3CString; var aDocId : Integer; var aPosID : Integer; var aPosType : TDocumentPositionType); var l_Wrong: Boolean; begin nsParseDocumentNumber(aNumber, aDocId, aPosID, aPosType, l_Wrong); end; procedure nsParseDocumentNumber(const aNumber : Il3CString; var aDocId : Integer; var aPosID : Integer; var aPosType : TDocumentPositionType; var aNumberWrong : Boolean); {* - строку с документов перевести в идентификатор документа и номер вхождения. } var l_InputStr: String; begin l_InputStr := l3Str(l3Trim(aNumber)); nsParseDocumentNumber(l_InputStr, aDocId, aPosID, aPosType, aNumberWrong); end; procedure nsParseDocumentNumber(const aNumber : String; var aDocId : Integer; var aPosID : Integer; var aPosType : TDocumentPositionType; var aNumberWrong : Boolean); overload; {* - строку с документов перевести в идентификатор документа и номер вхождения. } var l_DelimiterPos, l_PositionLength: Integer; l_PositionStr, l_InputStr: String; begin l_InputStr := aNumber; aPosType := dptSub; // Присваиваем тип Позиции = Блок/Саб, по умолчанию // Пытаемся найти во введенной информации Позицию в джокументе l_DelimiterPos := Pos(cPosDelimiter, l_InputStr); if l_DelimiterPos > 0 then begin Inc(l_DelimiterPos); // Перемещаемся на начало Позиции l_PositionLength := Length(l_InputStr) - l_DelimiterPos + 1; // Длина строки с Позицией l_PositionStr := Copy(l_InputStr, l_DelimiterPos, l_PositionLength); // Строка с Позицией Delete(l_InputStr, l_DelimiterPos - 1, l_PositionLength + 1); // Удаляем все начиная с разделителя и до конца end else l_PositionStr := ''; // Распознаем в строке номер документа aNumberWrong := not TryStrToInt(l_InputStr, aDocId); if not aNumberWrong then begin // Распознаем в строке информацию о позиции if (l_PositionStr = '') then aPosID := 0 else begin if l_PositionStr[1] = cParaPrefix then begin Delete(l_PositionStr, 1, 1); // Удаляем префикс параграфа aPosType := dptPara; // Присваиваем тип Позиции = Параграф end;//if l_PositionStr[1] = cParaPrefix then try aPosID := StrToInt(l_PositionStr); except on EConvertError do aPosID := 0; // Не выводим никакой информации о том, что не распознали Позицию end;//try..except end; end; end; {$If not (defined(Monitorings) or defined(Admin))} procedure nsSaveExternalObject(const aObject : IUnknown; const aType : TLinkedObjectType); {* - сохранить документ во внешний файл. } var l_ExternalObject : IExternalObject; l_ExternalObjectStream : TnsExternalObjectStream; begin if Assigned(aObject) and (aType = LO_EXTERNAL_OBJECT) and Supports(aObject, IExternalObject, l_ExternalObject) then begin l_ExternalObjectStream := TnsExternalObjectStream.Create(l_ExternalObject); try with dmStdRes.sdExternalObject do begin FileName := l3PStr(l_ExternalObjectStream.ExternalObjectName); case l_ExternalObject.GetDataType of EOT_MP3: begin DefaultExt := vcmConstString(str_MP3FileExtension); Filter := vcmConstString(str_MP3FileFilter); end;//EOT_MP3 EOT_PIC: begin DefaultExt := vcmConstString(str_BMPFileExtension); Filter := vcmConstString(str_BMPFileFilter); end;//EOT_PIC EOT_RTF: begin DefaultExt := vcmConstString(str_RTFFileExtension); Filter := vcmConstString(str_RTFFileFilter); end;//EOT_RTF EOT_XLS: begin DefaultExt := vcmConstString(str_XLSFileExtension); Filter := vcmConstString(str_XLSFileFilter); end;//EOT_XLS EOT_XLSX: begin DefaultExt := vcmConstString(str_XLSXFileExtension); Filter := vcmConstString(str_XLSXFileFilter); end;//EOT_XLSX EOT_PDF: begin DefaultExt := vcmConstString(str_PDFFileExtension); Filter := vcmConstString(str_PDFFileFilter); end;//EOT_PDF EOT_PPT: begin DefaultExt := vcmConstString(str_PPTFileExtension); Filter := vcmConstString(str_PPTFileFilter); end;//EOT_PPT EOT_CDR: begin DefaultExt := vcmConstString(str_CDRFileExtension); Filter := vcmConstString(str_CDRFileFilter); end;//EOT_CDR EOT_DOC: begin DefaultExt := vcmConstString(str_DOCFileExtension); Filter := vcmConstString(str_DOCFileFilter); end;//EOT_DOC EOT_DOCX: begin DefaultExt := vcmConstString(str_DOCXFileExtension); Filter := vcmConstString(str_DOCXFileFilter); end;//EOT_DOCX EOT_XML: begin DefaultExt := vcmConstString(str_XMLFileExtension); Filter := vcmConstString(str_XMLFileFilter); end;//EOT_XML EOT_XSD: begin DefaultExt := vcmConstString(str_XSDFileExtension); Filter := vcmConstString(str_XSDFileFilter); end;//EOT_XSD EOT_USR: begin DefaultExt := AnsiUpperCase(Copy(l3PStr(nsGetExternalObjectExt(l_ExternalObject)), 2, MaxInt)); Filter := Format(vcmConstString(str_USRFileFilterFormat), [DefaultExt, DefaultExt]); end;//EOT_USR else begin DefaultExt := ''; Filter := ''; end;//else end;//case l_ExternalObject.GetDataType of if (Filter <> '') then Filter := Filter+'|'; Filter := Filter + vcmConstString(str_AllFileFilter); if (DefaultExt <> '') and (not AnsiSameText(ExtractFileExt(dmStdRes.sdExternalObject.FileName), '.' + DefaultExt)) then // - http://mdp.garant.ru/pages/viewpage.action?pageId=621277863 FileName := FileName+'.'+DefaultExt; if Execute then l_ExternalObjectStream.SaveToFile(FileName); end; finally vcmFree(l_ExternalObjectStream); end;{try..finally} end;//if Assigned(aObject) and (aType = LO_EXTERNAL_OBJECT) and end;//nsSaveExternalObject {$IfEnd} { Дерево } procedure nsSetCurrentFirstSelected(const aTree : TeeTreeView; const aNode : Il3SimpleNode); {* - сделать текущим первый выделенный элемент. } var l_SelectedNode: Il3SimpleNode; begin l_SelectedNode := nsGetFirstSelectedChild(aNode); if Assigned(l_SelectedNode) then try aTree.GotoOnNode(l_SelectedNode); finally l_SelectedNode := nil; end;{try..finally} end;//nsSetCurrentFirstSelected function nsGetFirstSelectedChild(const aParent: Il3SimpleNode) : Il3SimpleNode; {* - получить первого выбранного ребенка. } function lp_GetFirstNode(const aNode: INodeBase; aOp: TLogicOperation): INodeBase; var l_Iterator: INodeIterator; begin l_Iterator := GetOperationIterator(aNode, aOp); try l_Iterator.GetNext(Result); finally l_Iterator := nil; end;{try..finally} end;//lp_GetFirstNode var l_Node : INodeBase; l_Parent : INodeBase; begin Result := nil; if Supports(aParent, INodeBase, l_Parent) then try l_Node := lp_GetFirstNode(l_Parent, loOr); if l_Node = nil then begin l_Node := lp_GetFirstNode(l_Parent, loAnd); if l_Node = nil then l_Node := lp_GetFirstNode(l_Parent, loNot); end; try Result := TnsSelectedNode.Make(l_Node); finally l_Node := nil; end;{try..finally} finally l_Parent := nil; end;{try..finally} end;//nsGetFirstSelectedChild { Общие } function nsPrepareTextForMailto(const aText: Il3CString): Il3CString; {* - конвертирует символы текста для открытия письма в почтовой программе. } begin Result := aText; l3MReplace(Result, [' ', '"', #13, #10, #9], ['%20', '%22', '%0d', '%0a', '%09']); end; function nsDateToStr(const aDate: System.TDateTime): String; {-} var l_Count : Integer; l_Buffer : PAnsiChar; l_SysTime : TSystemTime; begin Result := ''; DateTimeToSystemTime(aDate, l_SysTime); // Определим размер буфера l_Count := Windows.GetDateFormat(afw.Application.LocaleInfo.Id, DATE_LONGDATE, @l_SysTime, nil, nil, 0); // Получим строку l3System.GetLocalMem(l_Buffer, l_Count); try if Windows.GetDateFormatA(afw.Application.LocaleInfo.Id, DATE_LONGDATE, @l_SysTime, nil, l_Buffer, l_Count) <> 0 then Result := l_Buffer; finally l3System.FreeLocalMem(l_Buffer); end;//try..finally end;//nsDateToStr {$If not (defined(Monitorings) or defined(Admin))} function nsMyDocumentFolder(const aFileName : Il3CString; const aExtension : String = ''; const aCreate : Boolean = True): Il3CString; {* - возвращает системную папку "Мои документы" для текущего пользователя. } function GetSpecialFolderPath(const a_CSIDL: Integer): string; var l_Buffer: packed array [0..MAX_PATH] of Char; l_ItemIDList: PItemIDList; l_Malloc: IMalloc; begin//GetSpecialFolderPath Result := ''; // try OleCheck(SHGetMalloc(l_Malloc)); try OleCheck(SHGetSpecialFolderLocation(HWND(0), a_CSIDL, l_ItemIDList)); try if SHGetPathFromIDList(l_ItemIDList, @l_Buffer) then Result := PChar(@l_Buffer); finally l_Malloc.Free(l_ItemIDList); end;//try..finally finally l_Malloc := nil; end;//try..finally except on E: Exception do l3System.Exception2Log(E); end;//try..except end;//GetSpecialFolderPath const c_CSIDL: array [Boolean] of Integer = ( CSIDL_PERSONAL , CSIDL_PERSONAL or CSIDL_FLAG_CREATE ); begin Result := l3Fmt('%s\%s%s', [ GetSpecialFolderPath(c_CSIDL[aCreate]), nsPrepareFileName(aFileName), aExtension ]); end;//nsMyDocumentFolder {$IfEnd} {$If not Defined(Admin) AND not Defined(Monitorings)} procedure nsOpenList(const aDynList : IDynList; const aMainForm : IvcmContainer; const aWhatDoingIfOneDoc : TbsWhatDoingIfOneDoc = wdOpenIfUserDefine; const aTimeMachineOff : Boolean = True; const aOpenFrom : TbsListOpenFrom = lofNone); {* - открывает список. } function lp_MakeListData: IdeList; function lp_QueryInfo: IdeSearchInfo; begin if (aOpenFrom = lofRubricator) then Result := TdeSearchInfo.Make(aDynList, True) else Result := nil; end; begin case aDynList.GetContentType of DLC_LEGAL_DOCUMENTS: begin Result := TdeListSet.Make(aDynList, aWhatDoingIfOneDoc, aOpenFrom, aTimeMachineOff, nil, lp_QueryInfo); end; DLC_MEDICAL_DOCUMENTS: Result := TdeList.Make(aDynList); else begin Assert(False); Result := nil; end; end; end; begin if Assigned(aDynList) then TListService.Instance.OpenList(lp_MakeListData, aMainForm); end; {$IfEnd} function nsNewWindow(const aMainForm : IvcmContainer; aOpenKind : TvcmMainFormOpenKind = vcm_okInNewWindow; aNeedSwitchTab: Boolean = True): IvcmContainer; {* - открыть новое окно. } begin Result := nsOpenNewWindowTabbed(aMainForm, aOpenKind, aNeedSwitchTab); end; function nsConvertAnnoKind(const aValue: Il3CString): Il3CString; begin if (afw.Application.LocaleInfo.Language = afw_lngRussian) then begin if l3Same(aValue, ccakFederalLawFull) then Result := nsCStr(ccakFederalLawShort) else if l3Same(aValue, ccakJudgePracticeLawFull) then Result := nsCStr(ccakJudgePracticeLawShort) else // ЗАТОЧКА: поскольку меню для регионального зак-ва еще нет // считаем что все остальное и есть регионы... Result := nsCStr(ccakRegionalLaw); end//afw.Application.LocaleInfo.Language = afw_lngRussian else Result := aValue; end; function nsGetListHeaderLocalizationInfo(const aHeader: TvtCustomHeader): String; var l_Idx: Integer; begin Result := ''; with aHeader.Sections do for l_Idx := 0 to Count - 1 do begin if l_Idx > 0 then Result := Result + #13#10; Result := Result + Items[l_Idx].Caption; end; end; procedure nsSetListHeaderLocalizationInfo(const aHeader: TvtCustomHeader; const anInfo: String); var P, Start: PChar; S: string; l_Idx: Integer; begin with aHeader.Sections do begin l_Idx := 0; P := Pointer(anInfo); if P <> nil then while P^ <> #0 do begin Start := P; while not (P^ in [#0, #10, #13]) do Inc(P); SetString(S, Start, P - Start); if l_Idx < Count then Items[l_Idx].Caption := S else exit; Inc(l_Idx); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; end; end; procedure nsBeepWrongContext; {-} begin if afw.Application.Settings.LoadBoolean(pi_PlayBeepOnMistake, dv_PlayBeepOnMistake) then Windows.Beep(750, 50); {$IfDef InsiderTest} g_WasBeep := true; {$EndIf InsiderTest} end; function StringToOrientation(const aString: Il3CString): Integer; begin if l3Same(aString, li_Metrics_Orientation1) then Result := DMORIENT_LANDSCAPE else Result := DMORIENT_PORTRAIT; end; { TnsDeleteFromListEvent } {$If not (defined(Monitorings) or defined(Admin))} class procedure TnsTimeMachineOnEvent.Log(const aDoc: IDocument; const aDate: BaseTypesUnit.TDate); var l_Data: InsLogEventData; //#UC END# *4B0A86E800FF_4B0A86AD0232_var* begin //#UC START# *4B0A86E800FF_4B0A86AD0232_impl* l_Data := MakeParamsList; l_Data.AddObject(aDoc); l_Data.AddDate(aDate); GetLogger.AddEvent(LE_TIME_MACHINE_ON, l_Data); end; {$IfEnd not (defined(Monitorings) or defined(Admin))} {$If not Defined(Admin) AND not Defined(Monitorings)} function nsGetFilterCaption(const aFilter : IFilterFromQuery) : Il3CString; var l_Name: IString; begin aFilter.GetName(l_Name); Result := nsCStr(l_Name); end; {$IfEnd} end.
unit group; interface uses crt,lgarray,IOunit; const MAXGRPLEN = 30; MAXGRP = 40; type grouprectype = record index:integer; name:string[MAXGRPLEN] end; grouptype = record size:integer; data:array[1..MAXGRP] of grouprectype end; Procedure savegroup(var groupdata:grouptype;filename:string); Procedure showmembership(p:memberptrtype;var groupdata:grouptype); Procedure maindriver(var groupdata:grouptype;var alldata:dbasetype;currec:longint;var filename:string); implementation Function spaces(x:integer):string; var cnt:integer; temp:string; begin temp := ''; for cnt := 1 to x do temp := temp + ' '; spaces := temp end; Procedure initgroups(var groupdata:grouptype); var cnt:integer; begin for cnt := 1 to MAXGRP do groupdata.data[cnt].index := cnt - 1; groupdata.size := 0 end; Procedure addgroup(var groupdata:grouptype;x:string); var cnt,c:integer; temp:grouprectype; begin x := copy(x,1,MAXGRPLEN); groupdata.size := groupdata.size + 1; groupdata.data[groupdata.size].name := x; cnt := groupdata.size - 1; while (cnt > 0) and (groupdata.data[groupdata.size].name < groupdata.data[cnt].name) do cnt := cnt - 1; temp := groupdata.data[groupdata.size]; for c := groupdata.size downto cnt + 2 do groupdata.data[c] := groupdata.data[c - 1]; groupdata.data[cnt + 1] := temp end; Procedure editgroup(var groupdata:grouptype;num:integer;x:string); var c,cnt:integer; temp:grouprectype; begin cnt := groupdata.size; while (cnt > 0) and (x < groupdata.data[cnt].name) do cnt := cnt - 1; groupdata.data[num].name := copy(x,1,MAXGRPLEN); temp := groupdata.data[num]; if cnt < num then begin for c := num downto cnt + 2 do groupdata.data[c] := groupdata.data[c - 1]; groupdata.data[cnt + 1] := temp end else if cnt > num then begin for c := num to cnt - 1 do groupdata.data[c] := groupdata.data[c + 1]; groupdata.data[cnt] := temp end end; Function numgroups(var groupdata:grouptype):integer; begin numgroups := groupdata.size end; Function groupname(var groupdata:grouptype;num:integer):string; begin groupname := groupdata.data[num].name end; Function groupindex(var groupdata:grouptype;num:integer):integer; begin groupindex := groupdata.data[num].index end; Procedure removegroup(var groupdata:grouptype;num:integer); var cnt:integer; temp:grouprectype; begin temp := groupdata.data[num]; for cnt := num to groupdata.size - 1 do groupdata.data[cnt] := groupdata.data[cnt + 1]; groupdata.data[groupdata.size] := temp; groupdata.size := groupdata.size - 1 end; Procedure inputgroup(var groupdata:grouptype;var num:integer); var cnt,code:integer; temp:string; done,escpressed:boolean; begin done := false; repeat clrscr; writeln('G R O U P S':45); writeln; for cnt := 1 to (numgroups(groupdata) + 1) div 2 do begin write(cnt:2,'. '+groupname(groupdata,cnt)+spaces(34-length(groupname(groupdata,cnt)))); if cnt + (numgroups(groupdata) + 1) div 2 <= numgroups(groupdata) then writeln(cnt + (numgroups(groupdata) + 1) div 2:2,'. '+groupname(groupdata,cnt+ (numgroups(groupdata) + 1) div 2)) else writeln end; writeln; write('Pick one: '); getinput(temp,escpressed); if escpressed then temp := ''; if temp = '' then begin num := -1; done := true end else if temp = '0' then begin num := 0; done := true end else begin val(temp,num,code); if (num >= 1) and (num <= numgroups(groupdata)) then done := true end until done end; Procedure loadgroup(var groupdata:grouptype;filename:string); var f:file; numread:word; begin assign(f,filename); reset(f,1); blockread(f,groupdata,sizeof(groupdata),numread); close(f) end; Procedure savegroup(var groupdata:grouptype;filename:string); var f:file; numwritten:word; begin assign(f,filename); rewrite(f,1); blockwrite(f,groupdata,sizeof(groupdata),numwritten); close(f) end; Procedure showmembership(p:memberptrtype;var groupdata:grouptype); var c1,cnt:integer; begin clrscr; writeln('MEMBERSHIP OF CURRENT RECORD':54); writeln; c1 := 0; for cnt := 1 to numgroups(groupdata) do begin if groupindex(groupdata,cnt) in p^.membership then begin gotoxy(1 + 39*(c1 mod 2),3 + (c1 div 2)); write(groupname(groupdata,cnt)); c1 := c1 + 1 end end; pause end; Procedure addrecgroup(p:memberptrtype;var groupdata:grouptype;num:integer); var cnt:integer; begin if num = 0 then begin for cnt := 1 to numgroups(groupdata) do p^.membership := p^.membership + [groupindex(groupdata,cnt)] end else p^.membership := p^.membership + [groupindex(groupdata,num)] end; Procedure removerecgroup(p:memberptrtype;var groupdata:grouptype;num:integer); begin if num = 0 then p^.membership := [] else p^.membership := p^.membership - [groupindex(groupdata,num)] end; Procedure addmarkedgroup(var alldata:dbasetype;var groupdata:grouptype;num:integer); var count:longint; p:memberptrtype; begin for count := 1 to alldata.fsize do begin assignptr(pointer(p),alldata,count,0,1); if p^.marked then begin addrecgroup(p,groupdata,num); alldata.altered1 := true end end end; Procedure removemarkedgroup(var alldata:dbasetype;var groupdata:grouptype;num:integer); var count:longint; p:memberptrtype; begin for count := 1 to alldata.fsize do begin assignptr(pointer(p),alldata,count,0,1); if p^.marked then begin removerecgroup(p,groupdata,num); alldata.altered1 := true end end end; Procedure addallgroup(var alldata:dbasetype;var groupdata:grouptype;num:integer); var count:longint; p:memberptrtype; begin for count := 1 to alldata.fsize do begin assignptr(pointer(p),alldata,count,0,1); addrecgroup(p,groupdata,num); alldata.altered1 := true end end; Procedure removeallgroup(var alldata:dbasetype;var groupdata:grouptype;num:integer); var count:longint; p:memberptrtype; begin for count := 1 to alldata.fsize do begin assignptr(pointer(p),alldata,count,0,1); removerecgroup(p,groupdata,num); alldata.altered1 := true end end; Procedure markgroup(p:memberptrtype;var groupdata:grouptype;num:integer;ctrl:integer); var ingrp:boolean; begin ingrp := groupindex(groupdata,num) in p^.membership; case ctrl of 1:p^.marked := ingrp; 2:p^.marked := p^.marked and ingrp; 3:p^.marked := p^.marked or ingrp; 4:p^.marked := p^.marked xor ingrp; 5:p^.marked := p^.marked and (not ingrp); 6:p^.marked := p^.marked or (not ingrp); 7:p^.marked := p^.marked xor (not ingrp) end end; Procedure groupeditmenu(var choice:integer); var temp:string; code:integer; escpressed:boolean; begin clrscr; gotoxy(1,5); write('ADD / REMOVE GROUPS MENU':52); gotoxy(10,7); write('1. Add Group'); gotoxy(10,9); write('2. Change Group Name'); gotoxy(10,11); write('3. Remove Group'); gotoxy(10,13); write('4. Return to Main Menu'); gotoxy(1,15); write('Pick one: '); getinput(temp,escpressed); val(temp,choice,code) end; Procedure groupeditdriver(var groupdata:grouptype;var alldata:dbasetype); var escpressed,done:boolean; choice,num:integer; temp:string; begin done := false; repeat groupeditmenu(choice); case choice of 1:if numgroups(groupdata) < MAXGRP then begin clrscr; gotoxy(1,12); write('Enter name of new group: '); getinput(temp,escpressed); if not escpressed then addgroup(groupdata,temp) end; 2:if numgroups(groupdata) > 0 then begin inputgroup(groupdata,num); if num > 0 then begin clrscr; gotoxy(1,12); write('Enter new name for group: '); getinput(temp,escpressed); if not escpressed then editgroup(groupdata,num,temp) end end; 3:if numgroups(groupdata) > 0 then begin inputgroup(groupdata,num); if num > 0 then begin removeallgroup(alldata,groupdata,num); removegroup(groupdata,num) end end; 4:done := true end until done end; Procedure grouprecmenu(var choice:integer); var code:integer; temp:string; escpressed:boolean; begin clrscr; gotoxy(1,5); write('CHANGE MEMBERSHIPS MENU':51); gotoxy(10,7); write('1. Show Memberships of Current Record'); gotoxy(10,8); write('2. Add Current Record to a Group'); gotoxy(10,9); write('3. Add Marked Records to a Group'); gotoxy(10,10); write('4. Add All Records to a Group'); gotoxy(10,11); write('5. Remove Current Record from a Group'); gotoxy(10,12); write('6. Remove Marked Records from a Group'); gotoxy(10,13); write('7. Remove All Records from a Group'); gotoxy(10,14); write('8. Return to Main Menu'); gotoxy(1,16); write('Pick one: '); getinput(temp,escpressed); val(temp,choice,code) end; Procedure grouprecdriver(var groupdata:grouptype;var alldata:dbasetype;currec:longint); var done,escpressed:boolean; choice,num:integer; p:memberptrtype; begin done := false; repeat grouprecmenu(choice); case choice of 1:begin assignptr(pointer(p),alldata,currec,0,1); showmembership(p,groupdata) end; 2:begin inputgroup(groupdata,num); if num >= 0 then begin assignptr(pointer(p),alldata,currec,0,1); addrecgroup(p,groupdata,num); alldata.altered1 := true end end; 3:begin inputgroup(groupdata,num); if num >= 0 then addmarkedgroup(alldata,groupdata,num) end; 4:begin inputgroup(groupdata,num); if num >= 0 then addallgroup(alldata,groupdata,num) end; 5:begin inputgroup(groupdata,num); if num >= 0 then begin assignptr(pointer(p),alldata,currec,0,1); removerecgroup(p,groupdata,num); alldata.altered1 := true end end; 6:begin inputgroup(groupdata,num); if num >= 0 then removemarkedgroup(alldata,groupdata,num) end; 7:begin inputgroup(groupdata,num); if num >= 0 then removeallgroup(alldata,groupdata,num) end; 8:done := true end until done end; Procedure groupmarkmenu(var choice:integer); var temp:string; code:integer; escpressed:boolean; begin clrscr; gotoxy(1,5); write('MARK GROUPS MENU':48); gotoxy(10,7); write('1. Default Option'); gotoxy(10,8); write('2. AND Option'); gotoxy(10,9); write('3. OR Option'); gotoxy(10,10); write('4. XOR Option'); gotoxy(10,11); write('5. AND NOT Option'); gotoxy(10,12); write('6. OR NOT Option'); gotoxy(10,13); write('7. XOR NOT Option'); gotoxy(10,14); write('8. Return to Main Menu'); gotoxy(1,16); write('Pick one: '); getinput(temp,escpressed); val(temp,choice,code) end; Procedure groupmarkdriver(var groupdata:grouptype;var alldata:dbasetype); var count:longint; choice,num:integer; done:boolean; p:memberptrtype; begin done := false; repeat groupmarkmenu(choice); if (choice < 1) or (choice > 7) then done := true else begin inputgroup(groupdata,num); if num > 0 then begin for count := 1 to alldata.fsize do begin assignptr(pointer(p),alldata,count,0,1); markgroup(p,groupdata,num,choice); alldata.altered1 := true end end end until done end; Procedure groupmainmenu(var choice:integer); var temp:string; code:integer; escpressed:boolean; begin clrscr; gotoxy(1,5); write('G R O U P M A I N M E N U':54); gotoxy(10,7); write('1. Load Group File'); gotoxy(10,9); write('2. Add / Remove Groups'); gotoxy(10,11); write('3. Change Memberships'); gotoxy(10,13); write('4. Mark Groups'); gotoxy(10,15); write('5. Quit'); gotoxy(1,17); write('Pick one: '); getinput(temp,escpressed); val(temp,choice,code) end; Procedure maindriver(var groupdata:grouptype;var alldata:dbasetype;currec:longint;var filename:string); var choice:integer; done,escpressed:boolean; temp,tempfile:string; begin done := false; repeat groupmainmenu(choice); case choice of 1:if filename = '' then begin clrscr; gotoxy(1,12); write('Enter name of group file: '); getinput(tempfile,escpressed); if not escpressed then begin if not fileexists(tempfile) then begin gotoxy(1,14); write('Cannot find that file. Create a new one<y,n>? '); getinput(temp,escpressed); if (length(temp) > 0) and (temp[1] in ['Y','y']) then begin if not filecreation(tempfile) then begin gotoxy(1,16); write(chr(7)+'File creation error.'); pause end else begin initgroups(groupdata); filename := tempfile end end end else begin loadgroup(groupdata,tempfile); filename := tempfile end end end; 2:if filename <> '' then groupeditdriver(groupdata,alldata); 3:if (filename <> '') and (numgroups(groupdata) > 0) then grouprecdriver(groupdata,alldata,currec); 4:if (filename <> '') and (numgroups(groupdata) > 0) then groupmarkdriver(groupdata,alldata); 5:done := true end until done end; end.
unit NodeLayouteForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OkCancel_frame, DB, FIBDataSet, pFIBDataSet, DBGridEh, StdCtrls, DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, FIBQuery, PrjConst, System.UITypes; type TNodeLayoutItem = record M_TYPE: Integer; Name: string; NODE_ID: Integer; quant: Double; notice: string; end; TNodeLayouteForm = class(TForm) OkCancelFrame1: TOkCancelFrame; srcDevType: TDataSource; dsDevType: TpFIBDataSet; dbluDevType: TDBLookupComboboxEh; memNotice: TDBMemoEh; lblAttribute: TLabel; CnErrors: TCnErrorProvider; ednCount: TDBNumberEditEh; lbl1: TLabel; procedure OkCancelFrame1bbOkClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private public end; function EditLayoute(var NodeLayoutItem: TNodeLayoutItem): Boolean; implementation uses DM, pFIBQuery; {$R *.dfm} function EditLayoute(var NodeLayoutItem: TNodeLayoutItem): Boolean; begin with TNodeLayouteForm.Create(Application) do begin try dsDevType.ParamByName('M_TYPE').VALUE := NodeLayoutItem.M_TYPE; dsDevType.ParamByName('NODE_ID').VALUE := NodeLayoutItem.NODE_ID; dsDevType.Open; if NodeLayoutItem.M_TYPE <> -1 then begin dbluDevType.VALUE := NodeLayoutItem.M_TYPE; dbluDevType.Enabled := false; end; if NodeLayoutItem.quant <> 0 then ednCount.VALUE := NodeLayoutItem.quant; memNotice.Lines.Text := NodeLayoutItem.notice; if ShowModal = mrOk then begin NodeLayoutItem.M_TYPE := dbluDevType.VALUE; NodeLayoutItem.quant := ednCount.VALUE; NodeLayoutItem.notice := memNotice.Lines.Text; NodeLayoutItem.Name := dbluDevType.Text; result := true; end else result := false; if dsDevType.Active then dsDevType.Close; finally free end; end; end; procedure TNodeLayouteForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then OkCancelFrame1bbOkClick(Sender); end; procedure TNodeLayouteForm.OkCancelFrame1bbOkClick(Sender: TObject); var errors: Boolean; begin errors := false; if (dbluDevType.Text = '') then begin errors := true; CnErrors.SetError(dbluDevType, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(dbluDevType); if (ednCount.Text = '') then begin errors := true; CnErrors.SetError(ednCount, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(ednCount); if not errors then ModalResult := mrOk else ModalResult := mrNone; end; end.
program Registros; type str20 = string[20]; alumnoDestacado = record nombre : str20; promedio : real; end; alumno = record codigo : integer; nombre : str20; promedio : real; destacado : alumnoDestacado; end; procedure comprobarMaximo(var alu :alumno); begin if (alu.promedio >= alu.destacado.promedio) then begin alu.destacado.promedio := alu.promedio; alu.destacado.nombre := alu.nombre; end; end; procedure leer(var alu :alumno); begin writeln('Ingrese el código del alumno: '); readln(alu.codigo); if (alu.codigo <> 0 ) then begin writeln('Ingrese el nombre del alumno:'); readln(alu.nombre); writeln('Ingrese el promedio del alumno: '); readln(alu.promedio); end; end; var a :alumno; contadorAlumnos :integer; begin contadorAlumnos := 0; leer(a); while ( a.codigo <> 0 ) do begin comprobarMaximo(a); contadorAlumnos := contadorAlumnos + 1; leer(a); end; writeln('La cantidad de alumnos leída es: ', contadorAlumnos); writeln('El alumno con el mayor promedio es: ', a.destacado.nombre); end.
unit uAtualizacaobancoDeDados; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, System.SysUtils; type TAtualizabancoDeDados = class private public ConexaoDB:TZConnection; constructor Create(aConecao:TZConnection); procedure ExecutaDiretoBancoDeDados(aScript:string); end; type TAtualizabancoDadosMSSQL = class private ConexaoDB : TZConnection; public function AtualizaBancoDeDadosMSSQL :Boolean; constructor Create (aConexao:TZConnection); end; implementation uses uAtualizacaoTablelaMSSQL,uAtualizacaoCampoMSSQL; { AutualizabancoDeDos } constructor TAtualizabancoDeDados.Create(aConecao: TZConnection); begin ConexaoDB :=aConecao; end; procedure TAtualizabancoDeDados.ExecutaDiretoBancoDeDados(aScript: string); var Qry :TZQuery; begin try Qry := TZQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(aScript); try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; end; finally Qry.Close; if Assigned(Qry) then FreeAndNil(qry); end; end; { TAtualizabancoDadosMSSQL } function TAtualizabancoDadosMSSQL.AtualizaBancoDeDadosMSSQL: Boolean; var vAtualizarBD:TAtualizabancoDeDados; vTabela: TAtualizacaoTabelaMSSQL; vCampo: TAtualizacaoCampoMSSQL; begin try vAtualizarBD := TAtualizabancoDeDados.Create(ConexaoDB); vTabela:= TAtualizacaoTabelaMSSQL.Create(ConexaoDB); vCampo:= TAtualizacaoCampoMSSQL.Create(ConexaoDB); finally FreeAndNil(vAtualizarBD); FreeAndNil(vTabela); FreeAndNil(vCampo); end; end; constructor TAtualizabancoDadosMSSQL.Create(aConexao: TZConnection); begin ConexaoDB := aConexao; end; end.
unit nsDictionTree; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Diction" // Автор: Тучнин Д.А. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Diction/nsDictionTree.pas" // Начат: 2004/02/20 08:36:17 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Встроенные продукты::Diction::Diction::Diction$Unit::TnsDictionTree // // Дерево толкового словаря. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, l3TreeInterfaces, nsDataResetTreeStruct, bsTypes, bsInterfaces, DynamicTreeUnit, afwInterfaces ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsDictionTree = class(TnsDataResetTreeStruct) {* Дерево толкового словаря. } protected // property methods function pm_GetLanguage: TbsLanguage; virtual; protected // realized methods function ReAqurieUnfilteredRoot: INodeBase; override; protected // overridden protected methods function MakeChildNode(const aChild: INodeBase): Il3SimpleNode; override; function MakeFilters: Il3TreeFilters; override; procedure FillFilters(const aFilters: Il3TreeFilters; const anAdapterFilters: InsAdapterFilters); override; function SettingsID: TafwSettingId; override; procedure BeforeReset; override; protected // protected methods function DictFilters: InsLayeredTreeFilters; public // public methods class function Make(aLang: TbsLanguage; const anActiveContext: Il3CString = nil; CalcPartialContext: Boolean = false): Il3SimpleTree; private // private properties property Language: TbsLanguage read pm_GetLanguage; end;//TnsDictionTree {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses nsDictListChild, bsConvert, nsDictCache, SysUtils, nsLayeredTreeFilters, nsConst, nsLayerFilter, l3String ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsDictionTree function TnsDictionTree.pm_GetLanguage: TbsLanguage; //#UC START# *490823D301BE_46836BA203A1get_var* //#UC END# *490823D301BE_46836BA203A1get_var* begin //#UC START# *490823D301BE_46836BA203A1get_impl* Assert(Assigned(DictFilters.Layer)); Result := bsAdapterToBusiness(DictFilters.Layer.LayerID); //#UC END# *490823D301BE_46836BA203A1get_impl* end;//TnsDictionTree.pm_GetLanguage class function TnsDictionTree.Make(aLang: TbsLanguage; const anActiveContext: Il3CString = nil; CalcPartialContext: Boolean = false): Il3SimpleTree; //#UC START# *490823A102D3_46836BA203A1_var* var l_Tree : TnsDictionTree; l_Filterable : Il3FilterableTree; l_TreeFilters : InsLayeredTreeFilters; l_Current : Integer; //#UC END# *490823A102D3_46836BA203A1_var* begin //#UC START# *490823A102D3_46836BA203A1_impl* if TnsDictCache.Instance.ContainsLang(aLang) then begin l_Tree := Create(TnsDictCache.Instance.Root, False); try l_Filterable := l_Tree; Supports(l_Tree.CloneFilters, InsLayeredTreeFilters, l_TreeFilters); Result := l_Filterable.MakeFiltered(l_TreeFilters. SetLayer(TnsLayerFilter.Make(bsBusinessToAdapter(aLang))), nil, l_Current, True); if not l3IsNil(anActiveContext) and Supports(Result, Il3FilterableTree, l_Filterable) then begin Result := l_Filterable.MakeFiltered(l_Filterable.CloneFIlters. SetContext(anActiveContext), nil, l_Current, True, CalcPartialContext); if not Assigned(Result) or (Result.CountView <= 0) then Result := l_Filterable As Il3SimpleTree; end; finally; FreeAndNil(l_Tree); end; end else Result := nil; //#UC END# *490823A102D3_46836BA203A1_impl* end;//TnsDictionTree.Make function TnsDictionTree.DictFilters: InsLayeredTreeFilters; //#UC START# *4908241B0118_46836BA203A1_var* //#UC END# *4908241B0118_46836BA203A1_var* begin //#UC START# *4908241B0118_46836BA203A1_impl* Supports(Filters, InsLayeredTreeFilters, Result); //#UC END# *4908241B0118_46836BA203A1_impl* end;//TnsDictionTree.DictFilters function TnsDictionTree.ReAqurieUnfilteredRoot: INodeBase; //#UC START# *48FF64F60078_46836BA203A1_var* //#UC END# *48FF64F60078_46836BA203A1_var* begin //#UC START# *48FF64F60078_46836BA203A1_impl* Result := TnsDictCache.Instance.Root; //#UC END# *48FF64F60078_46836BA203A1_impl* end;//TnsDictionTree.ReAqurieUnfilteredRoot function TnsDictionTree.MakeChildNode(const aChild: INodeBase): Il3SimpleNode; //#UC START# *48FEE50002EB_46836BA203A1_var* //#UC END# *48FEE50002EB_46836BA203A1_var* begin //#UC START# *48FEE50002EB_46836BA203A1_impl* Result := TnsDictListChild.Make(aChild, Language); //#UC END# *48FEE50002EB_46836BA203A1_impl* end;//TnsDictionTree.MakeChildNode function TnsDictionTree.MakeFilters: Il3TreeFilters; //#UC START# *48FF4C25031E_46836BA203A1_var* //#UC END# *48FF4C25031E_46836BA203A1_var* begin //#UC START# *48FF4C25031E_46836BA203A1_impl* Result := TnsLayeredTreeFilters.Make; //#UC END# *48FF4C25031E_46836BA203A1_impl* end;//TnsDictionTree.MakeFilters procedure TnsDictionTree.FillFilters(const aFilters: Il3TreeFilters; const anAdapterFilters: InsAdapterFilters); //#UC START# *48FF520E03A0_46836BA203A1_var* var l_Filters: InsLayeredTreeFilters; //#UC END# *48FF520E03A0_46836BA203A1_var* begin //#UC START# *48FF520E03A0_46836BA203A1_impl* inherited FillFilters(aFilters, anAdapterFilters); if Supports(aFilters, InsLayeredTreeFilters, l_Filters) and Assigned(l_Filters.Layer) then anAdapterFilters.Layer.SetLayer(l_Filters.Layer.LayerID); //#UC END# *48FF520E03A0_46836BA203A1_impl* end;//TnsDictionTree.FillFilters function TnsDictionTree.SettingsID: TafwSettingId; //#UC START# *48FF56D003E6_46836BA203A1_var* //#UC END# *48FF56D003E6_46836BA203A1_var* begin //#UC START# *48FF56D003E6_46836BA203A1_impl* Result := gi_cpDiction; //#UC END# *48FF56D003E6_46836BA203A1_impl* end;//TnsDictionTree.SettingsID procedure TnsDictionTree.BeforeReset; //#UC START# *48FF64E700E5_46836BA203A1_var* //#UC END# *48FF64E700E5_46836BA203A1_var* begin //#UC START# *48FF64E700E5_46836BA203A1_impl* inherited; TnsDictCache.Instance.ClearCache; //#UC END# *48FF64E700E5_46836BA203A1_impl* end;//TnsDictionTree.BeforeReset {$IfEnd} //not Admin AND not Monitorings end.
program memoria; type docente = record dni :integer; nombre :string; apellido :string; email :string; end; escuela = record nombre :string; cantidadAlumnos :integer; end; proyecto = record codigo :integer; titulo :string; docente :docente; escuela :escuela; localidad :string; end; localidad = record nombre :string; cantidadEscuelas :integer; end; maximos = record primero :escuela; segundo :escuela; end; // Utilidades procedure incrementar(var c:integer); begin c := c + 1; end; // Lectura de datos procedure leerProyecto(var p:proyecto); begin write('Ingrese el código del proyecto: '); readln(p.codigo); write('Ingrese el título: '); readln(p.titulo); write('Ingrese el dni del docente: '); readln(p.docente.dni); write('Ingrese el nombre del docente : '); readln(p.docente.nombre); write('Ingrese el apellido del docente : '); readln(p.docente.apellido); write('Ingrese el email del docente : '); readln(p.docente.email); write('Ingrese la cantidad de alumnos: '); readln(p.escuela.cantidadAlumnos); write('Ingrese el nombre de la escuela: '); readln(p.escuela.nombre); write('Ingrese la localidad: '); readln(p.localidad); end; // Cond 1-2 function mismaLocalidad(ref, val:string):boolean; begin mismaLocalidad := ref = val; end; procedure reiniciarLocalidad(var l:localidad; lNueva:string); begin l.nombre := lNueva; l.cantidadEscuelas := 0; end; procedure informarEscuelasEnLocalidad(l:localidad); begin writeln( 'La cantidad de escuelas en la localidad ', l.nombre, ' es: ', l.cantidadEscuelas, '.' ); end; // Cond 2 procedure comprobarMaximos(var m:maximos; e:escuela); begin if (e.cantidadAlumnos >= m.primero.cantidadAlumnos) then begin m.segundo.nombre := m.primero.nombre; m.segundo.cantidadAlumnos := m.primero.cantidadAlumnos; m.primero.nombre := e.nombre; m.primero.cantidadAlumnos := e.cantidadAlumnos; end else if (e.cantidadAlumnos >= m.segundo.cantidadAlumnos) then begin m.segundo.nombre := e.nombre; m.segundo.cantidadAlumnos := e.cantidadAlumnos; end; end; // Cond 3 procedure comprobarCond3(p :proyecto); function mismosDigitos(codigo :integer):boolean; var pares, impares :integer; begin pares := 0; impares := 0; while (codigo <> 0) do begin if (codigo MOD 2 = 0) then incrementar(pares) else incrementar(impares); codigo := codigo DIV 10; end; mismosDigitos := pares = impares; end; begin if ((p.localidad = 'Daireaux') and mismosDigitos(p.codigo)) then begin writeln( 'El proyecto ', p.titulo, ' de la localidad de Daireaux tiene un código con igual', ' cantidad de dígitos pares e impares.' ); end; end; var p :proyecto; lActual :localidad; m:maximos; cantidadEscuelas :integer; begin lActual.cantidadEscuelas := 0; cantidadEscuelas := 0; m.primero.nombre := ' '; m.primero.cantidadAlumnos := 0; m.segundo.nombre := ' '; m.segundo.cantidadAlumnos := 0; leerProyecto(p); reiniciarLocalidad(lActual, p.localidad); // Inicialización del registro while (p.codigo <> -1) do // Condición de finalización begin if (not mismaLocalidad(lActual.nombre, p.localidad)) then // Cambio de localidad begin informarEscuelasEnLocalidad(lActual); // Cumple cond1-2 reiniciarLocalidad(lActual, p.localidad); // Limpia el registro para el nuevo valor end; incrementar(cantidadEscuelas); comprobarMaximos(m, p.escuela); // Cumple cond 2 comprobarCond3(p); // Cumple cond 3 leerProyecto(p); end; writeln('La cantidad de escuelas que participan es: ', cantidadEscuelas); writeln( 'Las escuelas con mayor cantidad de alumnos participantes son: ', m.primero.nombre, ' y ', m.segundo.nombre, '.' ); end.
unit nsUserDataObject; {* Объект данных для нод дерева пользователей } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Admin\nsUserDataObject.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsUserDataObject" MUID: (49F56C06023C) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If Defined(Admin)} uses l3IntfUses , evPersistentDataObjectEx , bsInterfaces , l3Interfaces , l3IID , evPersistentDataObject , nevBase , evdInterfaces ; type TnsUserDataObject = class(TevPersistentDataObjectEx) {* Объект данных для нод дерева пользователей } private f_Inited: Boolean; {* Данные зачитаны в поток. } f_List: IbsSelectedUsers; protected function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* метод для реализации QueryInterface (Для перекрытия в потомках) } function DataObjectClass: RevDataObject; override; function GetIsQuestionNeedBeforeFlush: Boolean; override; function DoStore(aFormat: TnevFormat; const aPool: IStream; const aFilters: InevTagGenerator; aFlags: TevdStoreFlags): Boolean; override; procedure ClearFields; override; public constructor Create(const aList: IbsSelectedUsers); reintroduce; class function Make(const aList: IbsSelectedUsers): IDataObject; reintroduce; end;//TnsUserDataObject {$IfEnd} // Defined(Admin) implementation {$If Defined(Admin)} uses l3ImplUses , nevTools , evTypes , l3Base , Classes , nsUserInterfacedDataObject , l3Types , k2Tags , evdNativeWriter , Document_Const , TextPara_Const //#UC START# *49F56C06023Cimpl_uses* //#UC END# *49F56C06023Cimpl_uses* ; constructor TnsUserDataObject.Create(const aList: IbsSelectedUsers); //#UC START# *49F56D450147_49F56C06023C_var* var l_OH : InevObjectHolder; //#UC END# *49F56D450147_49F56C06023C_var* begin //#UC START# *49F56D450147_49F56C06023C_impl* f_Inited := false; f_List := aList; l_OH := Holder; try inherited Create(nil, true, cf_EverestBin, l_OH.TagReader, l_OH.TagWriter, l3FormatArray([cf_EverestBin, cf_RTF, cf_UnicodeText, cf_Text, cf_OEMText]), nil); finally l_OH := nil; end;//try..finally //#UC END# *49F56D450147_49F56C06023C_impl* end;//TnsUserDataObject.Create class function TnsUserDataObject.Make(const aList: IbsSelectedUsers): IDataObject; var l_Inst : TnsUserDataObject; begin l_Inst := Create(aList); try Result := l_Inst As IDataObject; finally l_Inst.Free; end;//try..finally end;//TnsUserDataObject.Make function TnsUserDataObject.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* метод для реализации QueryInterface (Для перекрытия в потомках) } //#UC START# *48F475350256_49F56C06023C_var* //#UC END# *48F475350256_49F56C06023C_var* begin //#UC START# *48F475350256_49F56C06023C_impl* if IID.EQ(IbsSelectedUsers) then begin Result.SetOk; IbsSelectedUsers(Obj) := f_List; end//IID.EQ(INodesClipboard) else Result := inherited COMQueryInterface(IID, Obj); //#UC END# *48F475350256_49F56C06023C_impl* end;//TnsUserDataObject.COMQueryInterface function TnsUserDataObject.DataObjectClass: RevDataObject; //#UC START# *48F4795901B5_49F56C06023C_var* //#UC END# *48F4795901B5_49F56C06023C_var* begin //#UC START# *48F4795901B5_49F56C06023C_impl* Result := TnsUserInterfacedDataObject; //#UC END# *48F4795901B5_49F56C06023C_impl* end;//TnsUserDataObject.DataObjectClass function TnsUserDataObject.GetIsQuestionNeedBeforeFlush: Boolean; //#UC START# *48F4818300A5_49F56C06023C_var* //#UC END# *48F4818300A5_49F56C06023C_var* begin //#UC START# *48F4818300A5_49F56C06023C_impl* Result := Assigned(f_List) and (f_List.Count > 1000); //#UC END# *48F4818300A5_49F56C06023C_impl* end;//TnsUserDataObject.GetIsQuestionNeedBeforeFlush function TnsUserDataObject.DoStore(aFormat: TnevFormat; const aPool: IStream; const aFilters: InevTagGenerator; aFlags: TevdStoreFlags): Boolean; //#UC START# *48F481B6035B_49F56C06023C_var* var l_Writer: TevdNativeWriter; l_IDX: Integer; //#UC END# *48F481B6035B_49F56C06023C_var* begin //#UC START# *48F481B6035B_49F56C06023C_impl* if not f_Inited then begin l_Writer := TevdNativeWriter.Create; try l_Writer.Filer.Mode := l3_fmWrite; if aFormat = Format then l_Writer.Filer.COMStream := aPool As IStream else l_Writer.Filer.COMStream := Self As IStream; Result := True; with l_Writer do begin Start; StartChild(k2_typDocument); for l_IDX := 0 to f_List.Count - 1 do begin StartChild(k2_typTextPara); AddStringAtom(k2_tiText, f_List.Name[l_IDX].AsWStr); Finish; end; Finish; Finish; end; finally l3Free(l_Writer); end; f_Inited := true; if aFormat = Format then begin Result := True; Exit; end; end;//not f_Inited Result := inherited DoStore(aFormat, aPool, aFilters, aFlags); //#UC END# *48F481B6035B_49F56C06023C_impl* end;//TnsUserDataObject.DoStore procedure TnsUserDataObject.ClearFields; begin f_List := nil; inherited; end;//TnsUserDataObject.ClearFields {$IfEnd} // Defined(Admin) end.
unit l3StringEx; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3StringEx - } { Начат: 16.02.2000 16:50 } { $Id: l3StringEx.pas,v 1.61 2016/04/20 10:24:48 lulin Exp $ } // $Log: l3StringEx.pas,v $ // Revision 1.61 2016/04/20 10:24:48 lulin // - перегенерация. // // Revision 1.60 2015/10/05 11:41:12 lulin // {RequestLink:607751255}. // // Revision 1.59 2015/10/05 11:29:13 lulin // {RequestLink:607751255}. // // Revision 1.58 2015/10/05 11:02:04 lulin // {RequestLink:607751255}. // // Revision 1.57 2015/02/02 14:20:30 lulin // {RequestLink:586158141}. // // Revision 1.56 2014/12/17 16:57:14 lulin // {RequestLink:585129079}. // // Revision 1.55 2014/11/05 16:59:29 lulin // - перетряхиваем код. // // Revision 1.54 2013/07/08 16:43:15 lulin // - выделяем работу с размером куска памяти. // // Revision 1.53 2013/03/28 14:03:17 lulin // - портируем. // // Revision 1.52 2013/01/15 11:59:27 lulin // {RequestLink:423621421} // // Revision 1.51 2012/11/22 10:33:36 dinishev // {Requestlink:409757935} // // Revision 1.50 2011/09/26 10:45:52 lulin // {RequestLink:287220465}. // // Revision 1.49 2011/09/26 09:43:35 lulin // {RequestLink:287220465}. // // Revision 1.48 2010/10/25 16:08:44 lulin // {RequestLink:237503785}. // // Revision 1.47 2010/05/13 10:39:00 lulin // {RequestLink:211878770}. // // Revision 1.46 2010/05/12 09:33:37 narry // - неправильно конвертировался #149 из Ansi в OEM // // Revision 1.45 2009/07/20 16:44:09 lulin // - убираем из некоторых листьевых параграфов хранение типа конкретного тега, вместо этого "плодим" под каждый тип тега свой тип класса. // // Revision 1.44 2009/01/20 08:44:59 lulin // - <K>: 135600594. // // Revision 1.43 2009/01/15 07:26:06 lulin // - при преобразовании из Unicode в OEM преобразуем № в N. // // Revision 1.42 2008/12/18 14:42:50 lulin // - <K>: 132222370. // // Revision 1.41 2008/12/18 12:39:03 lulin // - <K>: 132222370. Поддерживаем работу с кодировкой TatarOEM. // // Revision 1.40 2008/12/15 16:06:19 lulin // - <K>: 131137753. // // Revision 1.39 2008/12/15 14:24:02 lulin // - <K>: 130744814. // // Revision 1.38 2008/01/23 11:28:54 lulin // - bug fix: не падаем на перекодировки татарского в unicode. // // Revision 1.37 2007/08/14 14:30:13 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.36 2007/03/22 05:56:48 lulin // - cleanup. // // Revision 1.35 2007/03/19 10:40:39 oman // - fix: Зацикливались на пустой строке в Tl3Str.AsWideString // // Revision 1.34 2007/03/16 14:47:31 lulin // - cleanup. // // Revision 1.33 2006/12/01 15:51:04 lulin // - cleanup. // // Revision 1.32 2006/12/01 15:10:33 lulin // - cleanup. // // Revision 1.31 2006/11/27 08:43:26 lulin // - cleanup. // // Revision 1.30 2006/11/25 14:36:23 lulin // - cleanup. // // Revision 1.29 2006/11/25 14:31:53 lulin // - корректнее записываем текст, который в кодировке, отличной от кодировки записываемого файла. // // Revision 1.28 2006/09/21 12:26:27 dinishev // remove procedure l3FixWidthEx // // Revision 1.27 2006/07/06 07:51:03 dinishev // Bug fix: неправильная выливка гипессылок в таблице // // Revision 1.26 2005/09/08 16:09:29 lulin // - bug fix: часть символов неправильно конвертировались из Unicode в ANSI. // // Revision 1.25 2005/09/08 15:23:14 lulin // - bug fix: Unicode-строки неправильно разгонялись по ширине. // // Revision 1.24 2005/04/04 14:01:45 mmorozov // new: - bugfix: корректное преобразование символов алфавита _CP_OEM в Unicode на не русской кодовой странице; // // Revision 1.23 2004/06/18 10:15:46 law // - класс _TevTextPara стал крайне аскетичным. // // Revision 1.22 2004/05/11 17:17:02 law // - cleanup. // // Revision 1.21 2004/04/19 16:08:23 law // - new type: _Tl3PCharLenConst. // // Revision 1.20 2003/09/23 08:38:02 law // - new prop: IevHyperlink.Hint. // - rename proc: ev_plAssignNil -> l3AssignNil. // // Revision 1.19 2003/05/12 09:20:25 law // - rename proc: ev_plIsNil -> l3IsNil. // // Revision 1.18 2003/03/13 16:37:21 law // - change: попытка портировать на Builder. // // Revision 1.17 2002/04/05 14:11:18 law // - bug fix. // // Revision 1.16 2002/02/26 15:48:08 law // - optimization: попытка оптимизации путем уменьшения фрагментации выделяемой памяти. // // Revision 1.15 2002/02/19 09:40:28 law // - bug fix: не рисовался символ § в OEM кодировке. // // Revision 1.14 2001/12/11 13:59:56 law // - new method: _Tm3ParaIndexBuilder.AddPara. // // Revision 1.13 2001/11/20 17:37:28 law // - new behavior: сделана "рыба" для проверки работы индексатора. // // Revision 1.12 2001/10/24 12:57:45 law // - new behavior: при преобразовании ANSI в Unicode нормально перекодируются символы-"стрелки". // // Revision 1.11 2001/10/24 12:19:48 law // - new behavior: при преобразовании OEM в Unicode нормально перекодируются символы-"стрелки". // // Revision 1.10 2001/10/18 11:17:18 law // - new call _format: изменен формат вызова m2XLTConvertBuffEx. // // Revision 1.9 2001/10/17 12:06:06 law // - new behavior: добавлена кодировка CP_KOI8. // // Revision 1.8 2001/10/17 08:07:52 law // - new lib: начинаем использовать m2. // // Revision 1.7 2001/10/01 14:07:23 law // - new unit: l3XLatTables. // // Revision 1.6 2001/05/28 09:44:30 law // - new proc: добавлена процедура l3FixWidth. // // Revision 1.5 2000/12/15 15:19:02 law // - вставлены директивы Log. // {$Include l3Define.inc } interface uses Windows, l3Interfaces, l3Types, l3Chars, l3Base ; type Tl3Str = object(Tl3PCharLen) public // public methods procedure Init(aLen : Long; aCodePage : Long = CP_ANSI; aBuff : PPointer = nil); overload; {-} procedure Init(const aStr : Tl3PCharLenPrim; aCodePage : Long = CP_DefaultValue; aBuff : PPointer = nil); overload; {-} procedure Clear; {-} function Empty: Bool; {-} function AsWideString: WideString; {-} end;//Tl3Str procedure l3FixWidth(S: Tl3String; SL: Long; var DW: Long); overload; {-} procedure l3FixWidth(S: Tl3String; NewLen: Long); overload; {-} function l3MultiByteToWideChar(aCodePage : Integer; aIn : PAnsiChar; aInLen : Integer; aOut : PWideChar; aOutLen : Integer): Integer; {-} function l3WideCharToMultiByte(aCodePage : Integer; aIn : PWideChar; aInLen : Integer; aOut : PAnsiChar; aOutLen : Integer): Integer; function l3HasTatar(const aStr: WideString): Boolean; {-} procedure l3FreeStringMem(var aMem : Tl3PtrRec); {-} implementation uses RTLConsts, SysUtils, Classes, l3Except, {$IfDef l3Requires_m0} m2XltLib, {$EndIf l3Requires_m0} l3String, l3MemorySizeUtils, l3Memory, {$IfDef l3Requires_m0} l3XLatTables, {$EndIf l3Requires_m0} l3DataRefList, l3ProtoDataContainer, l3MinMax ; { start object Tl3Str } procedure l3FixDOSCharsInUnicode(aSt: PWideChar; aLen: Long); var l_Index : Long; begin for l_Index := 0 to Pred(aLen) do begin Case aSt[l_Index] of cc_TriRight: aSt[l_Index] := #$25BA; cc_TriLeft: aSt[l_Index] := #$25C4; cc_OEMParagraphSign : aSt[l_Index] := #$00A7; cc_TriUp: aSt[l_Index] := #$25B2; cc_TriDown: aSt[l_Index] := #$25BC; end;//Case aSt[l_Index] end;//for l_Index end; procedure l3FixUnicode(aSt: PWideChar; aLen: Long); var l_Index : Long; begin for l_Index := 0 to Pred(aLen) do begin Case aSt[l_Index] of #186: aSt[l_Index] := #176; #8211: aSt[l_Index] := #45; end;//Case aSt[l_Index] end;//for l_Index end; type _ItemType_ = Pointer; _l3DataRefList_Parent_ = Tl3ProtoDataContainer; {$Define l3Items_IsProto} {$Include w:\common\components\rtl\Garant\L3\l3DataRefList.imp.pas} Tl3DataRefList = class(_l3DataRefList_) {* Список ссылок на куски памяти. При своём освобождении освобождает хранимые куски памяти. Эта память должна быть выделена функцией l3System.GetLocalMem. } end;//Tl3DataRefList Tl3StrBufCache = class(Tl3DataRefList) protected // internal methods function DeleteTailWithoutFree: Pointer; end;//Tl3StrBufCache type _Instance_R_ = Tl3DataRefList; type _l3DataRefList_R_ = Tl3DataRefList; {$Include w:\common\components\rtl\Garant\L3\l3DataRefList.imp.pas} function Tl3StrBufCache.DeleteTailWithoutFree: Pointer; var l_Pt : PItemType; begin if (f_Count = 0) then Result := nil else begin Dec(f_Count); l_Pt := ItemSlot(f_Count); Result := l_Pt^; l_Pt^ := nil; end;//f_Count = 0 end;//Tl3StrBufCache.DeleteTailWithoutFree var l_Tl3StrBufCache : Tl3StrBufCache; procedure Tl3Str.Init(aLen : Long; aCodePage : Long = CP_ANSI; aBuff : PPointer = nil); {overload;} {-} begin SCodePage := aCodePage; if (aBuff = nil) then begin if (l_Tl3StrBufCache <> nil) AND (l_Tl3StrBufCache.Count > 0) then begin S := l_Tl3StrBufCache.DeleteTailWithoutFree; if (aCodePage = CP_Unicode) then begin if (l3MemorySize(S) < Succ(aLen) * 2) then l3System.ReallocLocalMem(S, Succ(aLen) * 2); PWideChar(S)[aLen] := #0; end//aCodePage = CP_Unicode else begin if (l3MemorySize(S) < Succ(aLen)) then l3System.ReallocLocalMem(S, Succ(aLen)); S[aLen] := #0; end;//aCodePage = CP_Unicode end//l_Tl3StrBufCache <> nil else begin if (aCodePage = CP_Unicode) then begin l3System.GetLocalMem(S, Succ(aLen) * 2); PWideChar(S)[aLen] := #0; end//aCodePage = CP_Unicode else begin l3System.GetLocalMem(S, Succ(aLen)); S[aLen] := #0; end;//aCodePage = CP_Unicode end;//l_Tl3StrBufCache <> nil end//aBuff = nil else begin if (aCodePage = CP_Unicode) then begin if (l3MemorySize(aBuff^) < Succ(aLen) * 2) then l3System.ReallocLocalMem(aBuff^, Succ(aLen) * 2); S := aBuff^; PWideChar(S)[aLen] := #0; end//aCodePage = CP_Unicode else begin if (l3MemorySize(aBuff^) < Succ(aLen)) then l3System.ReallocLocalMem(aBuff^, Succ(aLen)); S := aBuff^; S[aLen] := #0; end;//aCodePage = CP_Unicode end;//aBuff = nil SLen := aLen; end; procedure FreeCache; begin FreeAndNil(l_Tl3StrBufCache); end; procedure CheckTl3StrBufCache; begin if (l_Tl3StrBufCache = nil) then begin l3System.AddExitProc(FreeCache); l_Tl3StrBufCache := Tl3StrBufCache.Create; end;//l_Tl3StrBufCache = nil end; procedure l3StrBufCache_AddString(aStr : PAnsiChar); begin Assert(aStr <> nil); l_Tl3StrBufCache.Add(aStr); end; procedure Tl3Str.Clear; {-} begin CheckTl3StrBufCache; if (S <> nil) then l3StrBufCache_AddString(S); //l3System.FreeLocalMem(S); l3AssignNil(Self); end; procedure l3FreeStringMem(var aMem : Tl3PtrRec); {-} begin if (Tl3Ptr(aMem).GetSize = 0) then Exit; if (aMem.Flag = l3_mfLocal) then begin CheckTl3StrBufCache; l3StrBufCache_AddString(Tl3Ptr(aMem).AsPointer); aMem.Flag := l3_mfNil; aMem.Ptr := nil; Exit; end;//aMem.Flag = l3_mfLocal Tl3Ptr(aMem).Clear; end; function l3HasTatar(const aStr: WideString): Boolean; {-} var l_Index : Integer; begin Result := false; for l_Index := 1 to Length(aStr) do Case aStr[l_Index] of #1240, #1241, #1256, #1257, #1198, #1199, #1174, #1175, #1186, #1187, #1210, #1211: begin Result := true; break; end;//#1240.. end;//Case aStr[l_Index] end; procedure l3TatarToUnicode(aIn : PAnsiChar; aOut : PWideChar; aLen : Integer); var l_Index : Integer; begin for l_Index := 0 to Pred(aLen) do begin Case aIn[l_Index] of #128: aOut[l_Index] := #1240; #144: aOut[l_Index] := #1241; #138: aOut[l_Index] := #1256; #154: aOut[l_Index] := #1257; #140: aOut[l_Index] := #1198; #156: aOut[l_Index] := #1199; #141: aOut[l_Index] := #1174; #157: aOut[l_Index] := #1175; #142: aOut[l_Index] := #1186; #158: aOut[l_Index] := #1187; #143: aOut[l_Index] := #1210; #159: aOut[l_Index] := #1211; else MultiByteToWideChar(CP_RussianWin, 0, @aIn[l_Index], 1, @aOut[l_Index], 1); end;//Case aIn[l_Index] end;//for l_Index end; procedure l3UnicodeToTatar(aIn : PWideChar; aOut : PAnsiChar; aLen : Integer); var l_Index : Integer; begin for l_Index := 0 to Pred(aLen) do begin Case aIn[l_Index] of #1240: aOut[l_Index] := #128; #1241: aOut[l_Index] := #144; #1256: aOut[l_Index] := #138; #1257: aOut[l_Index] := #154; #1198: aOut[l_Index] := #140; #1199: aOut[l_Index] := #156; #1174: aOut[l_Index] := #141; #1175: aOut[l_Index] := #157; #1186: aOut[l_Index] := #142; #1187: aOut[l_Index] := #158; #1210: aOut[l_Index] := #143; #1211: aOut[l_Index] := #159; else WideCharToMultiByte(CP_RussianWin, 0, @aIn[l_Index], 1, @aOut[l_Index], 1, nil, nil); end;//Case aIn[l_Index] end;//for l_Index end; procedure l3TatarOEMToUnicode(aIn : PAnsiChar; aOut : PWideChar; aLen : Integer); var l_Index : Integer; begin for l_Index := 0 to Pred(aLen) do begin Case aIn[l_Index] of #242: aOut[l_Index] := #1240; #248: aOut[l_Index] := #1241; #243: aOut[l_Index] := #1256; #249: aOut[l_Index] := #1257; #244: aOut[l_Index] := #1198; #250: aOut[l_Index] := #1199; #245: aOut[l_Index] := #1174; #251: aOut[l_Index] := #1175; #246: aOut[l_Index] := #1186; #252: aOut[l_Index] := #1187; #247: aOut[l_Index] := #1210; #253: aOut[l_Index] := #1211; else MultiByteToWideChar(CP_RussianDOS, 0, @aIn[l_Index], 1, @aOut[l_Index], 1); end;//Case aIn[l_Index] end;//for l_Index end; procedure l3UnicodeToTatarOEM(aIn : PWideChar; aOut : PAnsiChar; aLen : Integer); var l_Index : Integer; begin for l_Index := 0 to Pred(aLen) do begin Case aIn[l_Index] of #1240: aOut[l_Index] := #242; #1241: aOut[l_Index] := #248; #1256: aOut[l_Index] := #243; #1257: aOut[l_Index] := #249; #1198: aOut[l_Index] := #244; #1199: aOut[l_Index] := #250; #1174: aOut[l_Index] := #245; #1175: aOut[l_Index] := #251; #1186: aOut[l_Index] := #246; #1187: aOut[l_Index] := #252; #1210: aOut[l_Index] := #247; #1211: aOut[l_Index] := #253; #8470: aOut[l_Index] := 'N'; // - знак номера else WideCharToMultiByte(CP_RussianDOS, 0, @aIn[l_Index], 1, @aOut[l_Index], 1, nil, nil); end;//Case aIn[l_Index] end;//for l_Index end; function l3MultiByteToWideChar(aCodePage : Integer; aIn : PAnsiChar; aInLen : Integer; aOut : PWideChar; aOutLen : Integer): Integer; begin Result := aOutLen; Case aCodePage of CP_Tatar : l3TatarToUnicode(aIn, aOut, aInLen); CP_TatarOEM : l3TatarOEMToUnicode(aIn, aOut, aInLen); else Result := MultiByteToWideChar(aCodePage, 0, aIn, aInLen, aOut, aOutLen); end;//Case aCodePage end; function l3WideCharToMultiByte(aCodePage : Integer; aIn : PWideChar; aInLen : Integer; aOut : PAnsiChar; aOutLen : Integer): Integer; var l_Index : Integer; begin Result := aOutLen; Case aCodePage of CP_Tatar : l3UnicodeToTatar(aIn, aOut, aInLen); CP_TatarOEM : l3UnicodeToTatarOEM(aIn, aOut, aInLen); else begin if (aCodePage = CP_RussianDOS) then begin for l_Index := 0 to Pred(aInLen) do begin Case aIn[l_Index] of cc_LTDoubleQuote, cc_RTDoubleQuote: aIn[l_Index] := cc_DoubleQuote; end;//Case aIn[l_Index] end;//for l_Index end;//aCodePage = CP_RussianDOS Result := WideCharToMultiByte(aCodePage, 0, aIn, aInLen, aOut, aOutLen, nil, nil); end;//else end;//Case aCodePage end; procedure Tl3Str.Init(const aStr : Tl3PCharLenPrim; aCodePage : Long = CP_DefaultValue; aBuff : PPointer = nil); {overload;} {-} var l_tmpStr : Tl3Str; begin if l3IsNil(aStr) then l3AssignNil(Self) else if (aCodePage = CP_DefaultValue) OR (aCodePage = aStr.SCodePage) OR (aCodePage = CP_KeepExisting) then begin Init(aStr.SLen, aStr.SCodePage, aBuff); try if SCodePage = CP_Unicode then l3Move(aStr.S^, S^, SLen * 2) else l3Move(aStr.S^, S^, SLen); except if (aBuff = nil) then Clear; raise; end;{try..except} end//aCodePage = CP_DefaultValue else begin Init(aStr.SLen, aCodePage, aBuff); try {$IfDef l3Requires_m0} if (SCodePage = CP_OEMLite) then begin if (aStr.SCodePage = CP_ANSI) OR (aStr.SCodePage = CP_RussianWin) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuff(S, SLen, Cm2XLTAnsi2Oem); end//aStr.SCodePage = CP_ANSI else if l3IsOEMWithOutLiteEx(aStr.SCodePage) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuff(S, SLen, Cm2XLTOem2Special); end//aStr.SCodePage = CP_OEM else begin l_tmpStr.Init(aStr, CP_ANSI); try l3Move(l_tmpStr.S^, S^, SLen); m2XLTConvertBuff(S, SLen, Cm2XLTAnsi2Oem); finally l_tmpStr.Clear; end;{try..finally} end;//aStr.SCodePage = CP_OEM end//SCodePage = CP_OEMLite else if (SCodePage = CP_OEM) then begin if (aStr.SCodePage = CP_ANSI) OR (aStr.SCodePage = CP_RussianWin) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuff(S, SLen, Cm2XLTAnsi2Oem); end//aStr.SCodePage = CP_ANSI else if l3IsOEMEx(aStr.SCodePage) then begin l3Move(aStr.S^, S^, SLen); {-просто копируем исходную строку} //m2XLTConvertBuff(S, SLen, Cm2XLTOem2Special); end//aStr.SCodePage = CP_OEM else if (aStr.SCodePage = CP_Unicode) then begin l3WideCharToMultiByte(SCodePage, PWideChar(aStr.S), aStr.SLen, S, SLen); end//aStr.SCodePage = CP_Unicode else begin l_tmpStr.Init(aStr, CP_ANSI); try l3Move(l_tmpStr.S^, S^, SLen); m2XLTConvertBuff(S, SLen, Cm2XLTAnsi2Oem); finally l_tmpStr.Clear; end;{try..finally} end;//aStr.SCodePage = CP_OEM end//SCodePage = CP_OEM else if l3IsOEMEx(aStr.SCodePage) then begin if (SCodePage = CP_ANSI) OR (SCodePage = CP_RussianWin) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuff(S, SLen, Cm2XLTOem2Ansi); end//SCodePage = CP_ANSI else if l3IsOEMWithOutLiteEx(SCodePage) then begin l3Move(aStr.S^, S^, SLen); {-просто копируем исходную строку} end//SCodePage = CP_OEM else if (SCodePage = CP_Unicode) then begin MultiByteToWideChar(CP_RussianDos, 0, aStr.S, aStr.SLen, PWideChar(S), SLen); l3FixDOSCharsInUnicode(PWideChar(S), SLen); end//SCodePage = CP_Unicode else begin l_tmpStr.Init(aStr, CP_Unicode); try l3WideCharToMultiByte(SCodePage, PWideChar(l_tmpStr.S), l_tmpStr.SLen, S, SLen); finally l_tmpStr.Clear; end;//try..finally end;//SCodePage = CP_Unicode end//aStr.SCodePage = CP_OEMLite else if (SCodePage = CP_KOI8) then begin if (aStr.SCodePage = CP_ANSI) OR (aStr.SCodePage = CP_RussianWin) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuffEx(S, SLen, Win2Koi); end//aStr.SCodePage = CP_ANSI else if (aStr.SCodePage = CP_OEM) OR (aStr.SCodePage = CP_RussianDos) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuffEx(S, SLen, Dos2Koi); end//aStr.SCodePage = CP_OEM else begin l_tmpStr.Init(aStr, CP_ANSI); try l3Move(l_tmpStr.S^, S^, SLen); m2XLTConvertBuffEx(S, SLen, Win2Koi); finally l_tmpStr.Clear; end;//try..finally end;//aStr.SCodePage = CP_OEM end//SCodePage = CP_KOI8 else if (aStr.SCodePage = CP_KOI8) then begin if (SCodePage = CP_ANSI) OR (SCodePage = CP_RussianWin) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuffEx(S, SLen, Koi2Win); end//SCodePage = CP_ANSI else if (SCodePage = CP_OEM) OR (SCodePage = CP_RussianDos) then begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuffEx(S, SLen, Koi2Dos); end//SCodePage = CP_OEM else begin l3Move(aStr.S^, S^, SLen); m2XLTConvertBuffEx(S, SLen, Koi2Win); l_tmpStr.Init(l3PCharLen(S, SLen, CP_ANSI), CP_Unicode); try if SCodePage = CP_Unicode then l3Move(l_tmpStr.S^, S^, SLen * 2) else l3WideCharToMultiByte(SCodePage, PWideChar(l_tmpStr.S), l_tmpStr.SLen, S, SLen); finally l_tmpStr.Clear; end;{try..finally} end;//SCodePage = CP_OEM end//aStr.SCodePage = CP_KOI8 else {$EndIf l3Requires_m0} if (SCodePage = CP_Unicode) then begin Case aStr.SCodePage of CP_OEM, CP_RussianDOS: MultiByteToWideChar(CP_RussianDos, 0, aStr.S, aStr.SLen, PWideChar(S), SLen); CP_ANSI: MultiByteToWideChar(CP_RussianWin, 0, aStr.S, aStr.SLen, PWideChar(S), SLen); CP_Tatar: l3TatarToUnicode(aStr.S, PWideChar(S), SLen); CP_TatarOEM: l3TatarOEMToUnicode(aStr.S, PWideChar(S), SLen); else MultiByteToWideChar(aStr.SCodePage, 0, aStr.S, aStr.SLen, PWideChar(S), SLen); end;//Case aStr.SCodePage l3FixDOSCharsInUnicode(PWideChar(S), SLen); end//SCodePage = CP_Unicode else if (aStr.SCodePage = CP_Unicode) then begin if (SCodePage = CP_Tatar) then l3UnicodeToTatar(PWideChar(aStr.S), S, SLen) else if (SCodePage = CP_TatarOEM) then l3UnicodeToTatarOEM(PWideChar(aStr.S), S, SLen) else begin if (SCodePage = CP_ANSI) then l3FixUnicode(PWideChar(aStr.S), aStr.SLen); l3WideCharToMultiByte(SCodePage, PWideChar(aStr.S), aStr.SLen, S, SLen) end;//SCodePage = CP_Tatar end//aStr.SCodePage = CP_Unicode else begin l_tmpStr.Init(aStr, CP_Unicode); try if (SCodePage = CP_Tatar) then l3UnicodeToTatar(PWideChar(l_tmpStr.S), S, SLen) else if (SCodePage = CP_TatarOEM) then l3UnicodeToTatarOEM(PWideChar(l_tmpStr.S), S, SLen) else l3WideCharToMultiByte(SCodePage, PWideChar(l_tmpStr.S), l_tmpStr.SLen, S, SLen); finally l_tmpStr.Clear; end;//try..finally end;//aStr.SCodePage = CP_Unicode except if (aBuff = nil) then Clear; raise; end;//try..except end;//aCodePage = CP_DefaultValue end; function Tl3Str.Empty: Bool; {-} begin Result := l3IsNil(Self); end; function Tl3Str.AsWideString: WideString; {-} var l_Str : Tl3Str; begin if not l3IsNil(Self) then begin if (SCodePage = CP_Unicode) then begin SetLength(Result, SLen); l3Move(S^, PWideChar(Result)^, SLen * 2); end//SCodePage = CP_Unicode else begin l_Str.Init(Self, CP_Unicode); try Result := l_Str.AsWideString; finally l_Str.Clear; end;//try..finally end;//SCodePage = CP_Unicode end//not l3IsNil(Self) else Result := ''; end; procedure l3FixWidth(S: Tl3String; SL: Long; var DW: Long); {-} var WC : Long; DDW : Long; P : PAnsiChar; CI, O : Long; l_DW : Long; l_Div : Integer; begin if (SL > 0) AND (DW > 0) then begin P := S.St; WC := l3CountOfChar(cc_HardSpace, l3PCharLen(P, SL, S.CodePage)); if (WC > 0) then begin if (S.CodePage = CP_Unicode) then l_Div := 2 else l_Div := 1; O := 0; l_DW := DW; while (l_DW > 0) AND (WC > 0) do begin DDW := l_DW div WC; CI := ev_lpCharIndex(cc_HardSpace, l3PCharLen(P, SL - (P - S.St) div l_Div, S.CodePage)); S.Insert(cc_HardSpace, CI + (P - S.St) div l_Div, DDW); Dec(l_DW, DDW); Dec(WC); Inc(O, CI); Inc(O, DDW); Inc(O); P := S.St + O * l_Div; end;//while l_DW end else DW := 0; //- сигнализируем, что мы не добили пробелами end;//SL > 0 end; procedure l3FixWidth(S: Tl3String; NewLen: Long); //overload; {-} begin Dec(NewLen, S.Len); l3FixWidth(S, S.Len, NewLen); end; end.
inherited dmLctoBancarios: TdmLctoBancarios OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWCPGTLANB' ' (BANCO, AGENCIA, CONTA, DT_LANCAMENTO, TIPO_DOCUMENTO, DOCUMEN' + 'TO, VL_DOCUMENTO, DC, DESCRICAO, HISTORICO, CENTRO_CUSTO, CONTA_' + 'CREDITO, CONTA_DEBITO, DT_ALTERACAO, OPERADOR, ID_TRANSF, FIL_OR' + 'IGEM, FIL_DEBITO)' 'VALUES' ' (:BANCO, :AGENCIA, :CONTA, :DT_LANCAMENTO, :TIPO_DOCUMENTO, :D' + 'OCUMENTO, :VL_DOCUMENTO, :DC, :DESCRICAO, :HISTORICO, :CENTRO_CU' + 'STO, :CONTA_CREDITO, :CONTA_DEBITO, :DT_ALTERACAO, :OPERADOR, :I' + 'D_TRANSF, :FIL_ORIGEM, :FIL_DEBITO)') SQLDelete.Strings = ( 'DELETE FROM STWCPGTLANB' 'WHERE' ' BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old' + '_CONTA AND DT_LANCAMENTO = :Old_DT_LANCAMENTO AND TIPO_DOCUMENTO' + ' = :Old_TIPO_DOCUMENTO AND DOCUMENTO = :Old_DOCUMENTO') SQLUpdate.Strings = ( 'UPDATE STWCPGTLANB' 'SET' ' BANCO = :BANCO, AGENCIA = :AGENCIA, CONTA = :CONTA, DT_LANCAME' + 'NTO = :DT_LANCAMENTO, TIPO_DOCUMENTO = :TIPO_DOCUMENTO, DOCUMENT' + 'O = :DOCUMENTO, VL_DOCUMENTO = :VL_DOCUMENTO, DC = :DC, DESCRICA' + 'O = :DESCRICAO, HISTORICO = :HISTORICO, CENTRO_CUSTO = :CENTRO_C' + 'USTO, CONTA_CREDITO = :CONTA_CREDITO, CONTA_DEBITO = :CONTA_DEBI' + 'TO, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR, ID_TRANS' + 'F = :ID_TRANSF, FIL_ORIGEM = :FIL_ORIGEM, FIL_DEBITO = :FIL_DEBI' + 'TO' 'WHERE' ' BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old' + '_CONTA AND DT_LANCAMENTO = :Old_DT_LANCAMENTO AND TIPO_DOCUMENTO' + ' = :Old_TIPO_DOCUMENTO AND DOCUMENTO = :Old_DOCUMENTO') SQLRefresh.Strings = ( 'SELECT BANCO, AGENCIA, CONTA, DT_LANCAMENTO, TIPO_DOCUMENTO, DOC' + 'UMENTO, VL_DOCUMENTO, DC, DESCRICAO, HISTORICO, CENTRO_CUSTO, CO' + 'NTA_CREDITO, CONTA_DEBITO, DT_ALTERACAO, OPERADOR, ID_TRANSF, FI' + 'L_ORIGEM, FIL_DEBITO FROM STWCPGTLANB' 'WHERE' ' BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old' + '_CONTA AND DT_LANCAMENTO = :Old_DT_LANCAMENTO AND TIPO_DOCUMENTO' + ' = :Old_TIPO_DOCUMENTO AND DOCUMENTO = :Old_DOCUMENTO') SQLLock.Strings = ( 'SELECT NULL FROM STWCPGTLANB' 'WHERE' 'BANCO = :Old_BANCO AND AGENCIA = :Old_AGENCIA AND CONTA = :Old_C' + 'ONTA AND DT_LANCAMENTO = :Old_DT_LANCAMENTO AND TIPO_DOCUMENTO =' + ' :Old_TIPO_DOCUMENTO AND DOCUMENTO = :Old_DOCUMENTO' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' LB.BANCO, ' ' LB.AGENCIA, ' ' LB.CONTA, ' ' LB.DT_LANCAMENTO, ' ' LB.TIPO_DOCUMENTO, ' ' LB.DOCUMENTO, ' ' LB.VL_DOCUMENTO, ' ' LB.DC, ' ' LB.DESCRICAO, ' ' LB.HISTORICO, ' ' LB.CENTRO_CUSTO, ' ' LB.CONTA_CREDITO, ' ' LB.CONTA_DEBITO, ' ' LB.DT_ALTERACAO, ' ' LB.OPERADOR, ' ' LB.ID_TRANSF, ' ' LB.FIL_ORIGEM, ' ' LB.FIL_DEBITO,' ' CC.CENTRO_CUSTO NM_CENTROCUSTOS,' ' HIS.HISTORICO NM_HISTORICO' 'FROM STWCPGTLANB LB' 'LEFT JOIN STWCPGTCCUS CC ON CC.CODIGO = LB.CENTRO_CUSTO' 'LEFT JOIN STWCPGTHIS HIS ON HIS.CODIGO = LB.HISTORICO') object qryManutencaoBANCO: TStringField FieldName = 'BANCO' Required = True Size = 3 end object qryManutencaoAGENCIA: TStringField FieldName = 'AGENCIA' Required = True Size = 10 end object qryManutencaoCONTA: TStringField FieldName = 'CONTA' Required = True Size = 10 end object qryManutencaoDT_LANCAMENTO: TDateTimeField FieldName = 'DT_LANCAMENTO' Required = True end object qryManutencaoTIPO_DOCUMENTO: TStringField FieldName = 'TIPO_DOCUMENTO' Required = True Size = 2 end object qryManutencaoDOCUMENTO: TFloatField FieldName = 'DOCUMENTO' Required = True end object qryManutencaoVL_DOCUMENTO: TFloatField FieldName = 'VL_DOCUMENTO' DisplayFormat = '##0.00' end object qryManutencaoDC: TStringField FieldName = 'DC' Size = 1 end object qryManutencaoDESCRICAO: TStringField FieldName = 'DESCRICAO' Size = 40 end object qryManutencaoHISTORICO: TIntegerField FieldName = 'HISTORICO' end object qryManutencaoCENTRO_CUSTO: TIntegerField FieldName = 'CENTRO_CUSTO' end object qryManutencaoCONTA_CREDITO: TStringField FieldName = 'CONTA_CREDITO' Size = 30 end object qryManutencaoCONTA_DEBITO: TStringField FieldName = 'CONTA_DEBITO' Size = 30 end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoID_TRANSF: TFloatField FieldName = 'ID_TRANSF' end object qryManutencaoFIL_ORIGEM: TStringField FieldName = 'FIL_ORIGEM' Required = True Size = 3 end object qryManutencaoFIL_DEBITO: TStringField FieldName = 'FIL_DEBITO' Required = True Size = 3 end object qryManutencaoNM_CENTROCUSTOS: TStringField FieldName = 'NM_CENTROCUSTOS' ProviderFlags = [] ReadOnly = True Size = 40 end object qryManutencaoNM_HISTORICO: TStringField FieldName = 'NM_HISTORICO' ProviderFlags = [] ReadOnly = True Size = 40 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' LB.BANCO, ' ' LB.AGENCIA, ' ' LB.CONTA, ' ' LB.DT_LANCAMENTO, ' ' LB.TIPO_DOCUMENTO, ' ' LB.DOCUMENTO, ' ' LB.VL_DOCUMENTO, ' ' LB.DC, ' ' LB.DESCRICAO, ' ' LB.HISTORICO, ' ' LB.CENTRO_CUSTO, ' ' LB.CONTA_CREDITO, ' ' LB.CONTA_DEBITO, ' ' LB.DT_ALTERACAO, ' ' LB.OPERADOR, ' ' LB.ID_TRANSF, ' ' LB.FIL_ORIGEM, ' ' LB.FIL_DEBITO,' ' CC.CENTRO_CUSTO NM_CENTROCUSTOS,' ' HIS.HISTORICO NM_HISTORICO' 'FROM STWCPGTLANB LB' 'LEFT JOIN STWCPGTCCUS CC ON CC.CODIGO = LB.CENTRO_CUSTO' 'LEFT JOIN STWCPGTHIS HIS ON HIS.CODIGO = LB.HISTORICO') object qryLocalizacaoBANCO: TStringField FieldName = 'BANCO' Required = True Size = 3 end object qryLocalizacaoAGENCIA: TStringField FieldName = 'AGENCIA' Required = True Size = 10 end object qryLocalizacaoCONTA: TStringField FieldName = 'CONTA' Required = True Size = 10 end object qryLocalizacaoDT_LANCAMENTO: TDateTimeField FieldName = 'DT_LANCAMENTO' Required = True end object qryLocalizacaoTIPO_DOCUMENTO: TStringField FieldName = 'TIPO_DOCUMENTO' Required = True Size = 2 end object qryLocalizacaoDOCUMENTO: TFloatField FieldName = 'DOCUMENTO' Required = True end object qryLocalizacaoVL_DOCUMENTO: TFloatField FieldName = 'VL_DOCUMENTO' end object qryLocalizacaoDC: TStringField FieldName = 'DC' Size = 1 end object qryLocalizacaoDESCRICAO: TStringField FieldName = 'DESCRICAO' Size = 40 end object qryLocalizacaoHISTORICO: TIntegerField FieldName = 'HISTORICO' end object qryLocalizacaoCENTRO_CUSTO: TIntegerField FieldName = 'CENTRO_CUSTO' end object qryLocalizacaoCONTA_CREDITO: TStringField FieldName = 'CONTA_CREDITO' Size = 30 end object qryLocalizacaoCONTA_DEBITO: TStringField FieldName = 'CONTA_DEBITO' Size = 30 end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoID_TRANSF: TFloatField FieldName = 'ID_TRANSF' end object qryLocalizacaoFIL_ORIGEM: TStringField FieldName = 'FIL_ORIGEM' Required = True Size = 3 end object qryLocalizacaoFIL_DEBITO: TStringField FieldName = 'FIL_DEBITO' Required = True Size = 3 end object qryLocalizacaoNM_CENTROCUSTOS: TStringField FieldName = 'NM_CENTROCUSTOS' ReadOnly = True Size = 40 end object qryLocalizacaoNM_HISTORICO: TStringField FieldName = 'NM_HISTORICO' ReadOnly = True Size = 40 end end end
unit lstr; { This is the unit for the longstr datatype. All procedures and functions are of the form lstrXXX. The longstr datatype is a string that can be between 0 and 65520 characters. Memory is allocated as needed as string grows } interface type lstrarraytype = array[0..65519] of char; lstrptrtype = ^lstrarraytype; longstr = record size:word; extent:word; ptr:lstrptrtype end; Procedure lstradjustforsize(var s:longstr;newsize:longint); Function lstrlen(var s:longstr):word; Procedure lstrinit(var s:longstr); Procedure lstrdestroy(var s:longstr); Function lstrcharat(var s:longstr;index:word):char; Procedure lstrsetchar(var s:longstr;index:word;c:char); Procedure lstrremove(var s:longstr;start:word;numBytes:word); Procedure lstrinsertc(var s:longstr;start:word;c:char); Procedure lstrinserts(var s:longstr;start:word;ss:string); Procedure lstrinsertls(var s:longstr;start:word;var ls:longstr); Procedure lstrappendc(var s:longstr;c:char); Procedure lstrappends(var s:longstr;ss:string); Procedure lstrappendls(var s:longstr;var ls:longstr); Procedure lstrclear(var s:longstr); Function lstrtostring(var s:longstr):string; Function lstrsubstrs(var s:longstr;start:word;len:byte):string; Procedure lstrsubstrls(var s:longstr;start:word;len:word;var substr:longstr); Function lstrnextwordwrap(var s:longstr;start:word;charsperline:word):word; Function lstrboyermoore(var ls:longstr;s:string;var posit:word):boolean; Procedure lstrcaps(var ls:longstr); implementation { Returns the length of the string } Function lstrlen(var s:longstr):word; begin lstrlen := s.size end; { Initializes a longstr. } Procedure lstrinit(var s:longstr); begin s.size := 0; s.extent := 16; getmem(s.ptr,16) end; { Frees resources used by a longstr. } Procedure lstrdestroy(var s:longstr); begin freemem(s.ptr,s.extent) end; { Returns 2^x. x - exponent. } Function lstrexp(x:integer):longint; var result:longint; i:integer; begin result := 1; for i := 1 to x do result := result * 2; lstrexp := result end; { Returns the largest integer of log base 2 x. For 0, return 0. For 1, return 0. for 2-3 returns 1. For 4-7 returns 2 etc. } Function lstrlog(x:longint):integer; var result:integer; begin result := 0; while (x > 1) do begin result := result + 1; x := x div 2 end; lstrlog := result end; { Copies characters from one memory location to another. src - characters copied from here dest - characters copied to here numBytes - number of bytes to copy. } Procedure lstrcopycontent(src:lstrptrtype;dest:lstrptrtype;numBytes:word); var i:word; begin for i := 1 to numBytes do dest^[i-1] := src^[i-1] end; { Makes the longstr have a given capacity. s - the longstr newextent - the new capacity. } Procedure lstrchangeextent(var s:longstr;newextent:word); var nptr:lstrptrtype; begin getmem(nptr,newextent); if (newextent >= s.size) then lstrcopycontent(s.ptr,nptr,s.size) else begin lstrcopycontent(s.ptr,nptr,newextent); s.size := newextent end; freemem(s.ptr,s.extent); s.extent := newextent; s.ptr := nptr end; { Adjusts the amount of memory allocated for the longstr. 16 smalles block. Then 32, 64, 128, ..., 32768, 65520. s - the long str newsize - the number of chars the longstr will have. } Procedure lstradjustforsize(var s:longstr;newsize:longint); begin { minimum capacity is 16 } if (newsize < 16) then newsize := 16; { Choose next power of 2 that is equal to or greater than needed capacity } newsize := lstrexp(lstrlog(2*newsize-1)); { Can't have capacity bigger than 65520 } if (newsize > 65520) then newsize := 65520; { only adjust capacity if it differs from original } if (newsize <> s.extent) then lstrchangeextent(s,newsize); end; { Returns the character at the index th position of a long str. s - the long string index - the position. Starts at 0. } Function lstrcharat(var s:longstr;index:word):char; begin lstrcharat := s.ptr^[index] end; { Sets the character at a given position in a long string s - the long string. index - the position to set the character. Starts at 0. c - new value of the character. } Procedure lstrsetchar(var s:longstr;index:word;c:char); begin s.ptr^[index] := c end; { Removes characters from a longstr s - longstr. start - starting place where characters are to be deleted. These start at 0. numBytes - the number of characters to delete. } Procedure lstrremove(var s:longstr;start:word;numBytes:word); var i:word; begin if (start > s.size) then start := s.size; if (numBytes > s.size - start) then numBytes := s.size - start; for i := start+1 to s.size - numBytes do s.ptr^[i-1] := s.ptr^[i+numBytes-1]; s.size := s.size - numBytes; lstradjustforsize(s,s.size) end; { Makes room for numBytes characters at start by moving everything down numBytes. s - the longstr. start - the place to make room. Starts at 0. numBytes - the number of characters for which to make room } Procedure lstrmakeroom(var s:longstr;start:word;numBytes:word); var i:word; begin lstradjustforsize(s,s.size+numBytes); for i := s.size downto start+1 do s.ptr^[i+numBytes-1] := s.ptr^[i-1]; s.size := s.size + numBytes end; { Inserts a single character into a string s- the long string. start-Place to insert the character. starts at 0. c - the char to insert } Procedure lstrinsertc(var s:longstr;start:word;c:char); begin lstrmakeroom(s,start,1); s.ptr^[start] := c end; { Inserts a string of characters into a longstr. s - the long string start - place to insert string. starts at 0. ss - the string. } Procedure lstrinserts(var s:longstr;start:word;ss:string); var i:word; begin lstrmakeroom(s,start,length(ss)); for i := 1 to length(ss) do s.ptr^[start+i-1] := ss[i] end; { Inserts a longstr of characters into a longstr s - the long string start - place to insert string. starts at 0. ls - the longstr to insert. } Procedure lstrinsertls(var s:longstr;start:word;var ls:longstr); var i:word; begin lstrmakeroom(s,start,lstrlen(ls)); for i := 1 to lstrlen(ls) do s.ptr^[start+i-1] := lstrcharat(ls,i-1) end; { Appends a character to the end of a long string } Procedure lstrappendc(var s:longstr;c:char); begin lstrinsertc(s,s.size,c) end; { Appends a string to the end of a long string } Procedure lstrappends(var s:longstr;ss:string); begin lstrinserts(s,s.size,ss) end; { Appends a long string to the end of another longstr. s - the long string to which characters are being appended. ls - the long string that contains the characters that are being appended. } Procedure lstrappendls(var s:longstr;var ls:longstr); begin lstrinsertls(s,s.size,ls) end; { Makes the length of the long string be 0 } Procedure lstrclear(var s:longstr); begin s.size := 0; lstradjustforsize(s,0) end; { Converts a long string to a regular string } Function lstrtostring(var s:longstr):string; var result:string; i:word; begin if (s.size > 255) then result[0] := chr(255) else result[0] := chr(s.size); for i := 1 to ord(result[0]) do result[i] := s.ptr^[i-1]; lstrtostring := result end; { Finds a substring of a long string. Returns as a reglar string. s - the long string. start - the starting position of the substring. starts at 0. len - the length of the substring. } Function lstrsubstrs(var s:longstr;start:word;len:byte):string; var result:string; i:word; begin if (start > s.size) then start := s.size; if (len > s.size-start) then len := s.size-start; result[0] := chr(len); for i := 1 to len do result[i] := s.ptr^[start+i-1]; lstrsubstrs := result end; { Finds a substring of a long string. Result returned in a long string. s - the long string start - Place where substring is to start len - number of characters in substring substr - substring returned here } Procedure lstrsubstrls(var s:longstr;start:word;len:word;var substr:longstr); var i:word; begin if (start > s.size) then start := s.size; if (len > s.size-start) then len := s.size-start; lstradjustforsize(substr,len); for i := 1 to len do substr.ptr^[i-1] := lstrcharat(s,start+i-1); substr.size := len end; { Finds the next place to word wrap. s - the long string start - the starting place of current line. Starts at 0 returns the position of the beginning of the next line or the size of s if end of string is reached. } Function lstrnextwordwrap(var s:longstr;start:word;charsperline:word):word; var lastwordbegin:word; index:word; done:boolean; ch:char; result:word; state:integer; begin { only look if we aren't at end of string already otherwise we are done } if (start >= lstrlen(s)) then lstrnextwordwrap := start else begin { state=0 means not in spaces. state=1 means in spaces. } state := 0; { start looking for wordwrap at beginning of current line } index := start; { Last beginning of a word stored here. For now, it is start. It is the value of lastwordbegin that gets returned. } lastwordbegin := start; done := false; while (not done) do begin { if we've gone 80 chars past the start, we are done, we return the position of the beginning of the last word. } if (index-start = charsperline) then done := true { if we get to the end of the string, we are done. store position in lastwordbegin since we will be returning the size of the string } else if (index = lstrlen(s)) then begin lastwordbegin := index; done := true end else begin { Otherwise, we are not at the end of the string. Get the contents. } ch := lstrcharat(s,index); { If its a carriage return, we will return the position of the next character. } if (ch = chr(13)) then begin lastwordbegin := index + 1; done := true end { If we are at a space, the state becomes 1 } else if (ch = ' ') then state := 1 { Else, we've been in spaces and we have encountered a non space store this position in lastwordbegin, but we still aren't done } else if (state = 1) then begin lastwordbegin := index; state := 0 end; end; index := index + 1 end; { if we haven't found the beginning of a word except for the beginning of this line, just return 80 chars past. } if (lastwordbegin = start) then lstrnextwordwrap := start + charsperline else lstrnextwordwrap := lastwordbegin end end; Function lstrboyermoore(var ls:longstr;s:string;var posit:word):boolean; var boyer:array[0..255] of byte; i:integer; found:boolean; cposit:longint; sposit:longint; boyerindex:longint; begin for i := 0 to 255 do boyer[i] := 0; for i := 1 to length(s) do boyer[ord(s[i])] := i; found := false; sposit := posit; while (sposit+length(s) <= lstrlen(ls)) and (not found) do begin cposit := sposit+length(s)-1; while (cposit >= sposit) and (s[cposit-sposit+1] = lstrcharat(ls,cposit)) do cposit := cposit-1; if (cposit < sposit) then found := true else begin boyerindex := boyer[ord(lstrcharat(ls,cposit))]; boyerindex := cposit - sposit + 1 - boyerindex; if (boyerindex < 1) then boyerindex := 1; sposit := sposit + boyerindex end end; if (found) then posit := sposit; lstrboyermoore := found end; Procedure lstrcaps(var ls:longstr); var i:word; begin for i := 1 to ls.size do ls.ptr^[i-1] := upcase(ls.ptr^[i-1]) end; begin 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.7 2/15/2005 9:25:00 AM DSiders Modified StrHtmlEncode, StrHtmlDecode to ignore apostrophe character and entity (not defined for HTML 4). Added StrXHtmlEncode, StrXHtmlDecode. Added comments to describe various functions. Rev 1.6 7/30/2004 7:49:30 AM JPMugaas Removed unneeded DotNET excludes. Rev 1.5 2004.02.03 5:44:26 PM czhower Name changes Rev 1.4 2004.02.03 2:12:20 PM czhower $I path change Rev 1.3 24/01/2004 19:30:28 CCostelloe Cleaned up warnings Rev 1.2 10/12/2003 2:01:48 PM BGooijen Compiles in DotNet Rev 1.1 10/10/2003 11:06:54 PM SPerry Rev 1.0 11/13/2002 08:02:02 AM JPMugaas 2000-03-27 Pete Mee - Added FindFirstOf, FindFirstNotOf,TrimAllOf functions. 2002-01-03 Andrew P.Rybin - StrHTMLEnc/Dec,BinToHexStr,IsWhiteString } unit IdStrings; interface {$i IdCompilerDefines.inc} { IsWhiteString Returns TRUE when AStr contains only whitespace characters TAB (decimal 9), SPACE (decimal 32), or an empty string. } function IsWhiteString(const AStr: String): Boolean; { BinToHexStr converts the byte value in AData to its representation as a 2-byte hexadecimal value without the '$' prefix. For instance: 'FF', 'FE', or '0A' } function BinToHexStr(AData: Byte): String; { Encode and decode characters representing pre-defined character entities for HTML 4. handles &<>" characters } function StrHtmlEncode (const AStr: String): String; function StrHtmlDecode (const AStr: String): String; { Encode and decode characters representing pre-defined character entities for XHTML, XML. handles &<>"' characters } function StrXHtmlEncode(const ASource: String): String; function StrXHtmlDecode(const ASource: String): String; { SplitString splits a string into left and right parts, i.e. SplitString('Namespace:tag', ':'..) will return 'Namespace' and 'tag' } procedure SplitString(const AStr, AToken: String; var VLeft, VRight: String); { CommaAdd Appends AStr2 to the right of AStr1 and returns the result. If there is any content in AStr1, a comma will be appended prior to the value of AStr2. } function CommaAdd(Const AStr1, AStr2:String):string; implementation uses SysUtils, IdException, IdGlobal, IdGlobalProtocols; function StrHtmlEncode (const AStr: String): String; begin Result := StringReplace(AStr, '&', '&amp;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '<', '&lt;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '>', '&gt;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '"', '&quot;' ,[rfReplaceAll]); {do not localize} end; function StrHtmlDecode (const AStr: String): String; begin Result := StringReplace(AStr, '&quot;', '"',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&gt;', '>',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&lt;', '<',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&amp;', '&',[rfReplaceAll]); {do not localize} end; function StrXHtmlEncode(const ASource: String): String; begin Result := StringReplace(ASource, '&', '&amp;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '<', '&lt;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '>', '&gt;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '"', '&quot;',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '''', '&apos;',[rfReplaceAll]); {do not localize} end; function StrXHtmlDecode(const ASource: String): String; begin Result := StringReplace(ASource, '&apos;', '''',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&quot;', '"',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&gt;', '>',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&lt;', '<',[rfReplaceAll]); {do not localize} Result := StringReplace(Result, '&amp;', '&',[rfReplaceAll]); {do not localize} end; // SP - 10/10/2003 function BinToHexStr(AData: Byte): String; begin Result := IdHexDigits[AData shr 4] + IdHexDigits[AData and $F]; end; function IsWhiteString(const AStr: String): Boolean; var i: Integer; LLen: Integer; begin Result := True; LLen := Length(AStr); if LLen > 0 then begin for i := 1 to LLen do begin if not CharIsInSet(AStr, i, LWS) then begin Result := FALSE; Break; end; end; end; end; procedure SplitString(const AStr, AToken: String; var VLeft, VRight: String); var i: Integer; LLocalStr: String; begin { It is possible that VLeft or VRight may be the same variable as AStr. So we copy it first } LLocalStr := AStr; i := Pos(AToken, LLocalStr); if i = 0 then begin VLeft := LLocalStr; VRight := ''; end else begin VLeft := Copy(LLocalStr, 1, i - 1); VRight := Copy(LLocalStr, i + Length(AToken), Length(LLocalStr)); end; end; function CommaAdd(Const AStr1, AStr2:String):string; begin if AStr1 = '' then result := AStr2 else result := AStr1 + ',' + AStr2; end; end.
unit DuplicateRouteUnit; interface uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit; type TDuplicateRoute = class(TBaseExample) public function Execute(RouteId: String): NullableString; end; implementation uses RouteParametersQueryUnit; function TDuplicateRoute.Execute(RouteId: String): NullableString; var ErrorString: String; Parameters: TRouteParametersQuery; begin Parameters := TRouteParametersQuery.Create; try Parameters.RouteId := RouteId; Result := Route4MeManager.Route.Duplicate(Parameters, ErrorString); WriteLn(''); if (Result.IsNotNull) then begin WriteLn(Format('DuplicateRoute executed successfully, duplicated route ID: %s', [Result.Value])); WriteLn(''); end else WriteLn(Format('DuplicateRoute error "%s"', [ErrorString])); finally FreeAndNil(Parameters); end; end; end.
{ Demo unit of TLS request by means of WinAPI SChannel (c) Fr0sT-Brutal License MIT } unit SChannelSocketRequest; interface uses Forms, Winapi.Windows, System.SysUtils, WinSock, Classes, StrUtils, SChannel.JwaWinError, SChannel.JwaSspi, SChannel.Utils, SChannel.SyncHandshake; type TReqResult = (resConnErr, resTLSErr, resOK); var PrintDumps: Boolean = False; PrintData: Boolean = False; PrintCerts: Boolean = False; ManualCertCheck: Boolean = False; CertCheckIgnoreFlags: TCertCheckIgnoreFlags; Cancel: Boolean = False; LogFn: TDebugFn; SharedSessionCreds: ISharedSessionCreds; function Request(const URL, ReqStr: string): TReqResult; implementation type // Elementary socket class TSyncSocket = class HSocket: TSocket; procedure Connect(const Addr: string; Port: Word); function Send(Buf: Pointer; BufLen: Integer): Integer; function Recv(Buf: Pointer; BufLen: Integer): Integer; procedure Close; end; function BinToHex(Buf: Pointer; BufLen: NativeUInt): string; begin SetLength(Result, BufLen*2); Classes.BinToHex(PAnsiChar(Buf), PChar(Pointer(Result)), BufLen); end; procedure CheckWSResult(Res: Boolean; const Method: string); const SFullErrorMsg = '#%d %s (API method "%s")'; SShortErrorMsg = '#%d %s'; begin if not Res then if Method <> '' then raise Exception.CreateFmt(SFullErrorMsg, [WSAGetLastError, SysErrorMessage(WSAGetLastError), Method]) else raise Exception.CreateFmt(SShortErrorMsg, [WSAGetLastError, SysErrorMessage(WSAGetLastError)]); end; { TSyncSocket } procedure TSyncSocket.Connect(const Addr: string; Port: Word); var SockAddr: TSockAddr; HostEnt: PHostEnt; begin try // create socket handle HSocket := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); CheckWSResult(HSocket <> INVALID_SOCKET, 'socket'); HostEnt := gethostbyname(PAnsiChar(AnsiString(Addr))); CheckWSResult(HostEnt <> nil, 'gethostbyname'); SockAddr := Default(TSockAddr); SockAddr.sin_family := PF_INET; Move(HostEnt^.h_addr^[0], SockAddr.sin_addr, SizeOf(TInAddr)); Port := htons(Port); // network byte order, short int SockAddr.sin_port := Port; CheckWSResult(WinSock.connect(HSocket, SockAddr, SizeOf(TSockAddr)) <> SOCKET_ERROR, 'connect'); except // error - close socket closesocket(HSocket); raise; end; end; function TSyncSocket.Send(Buf: Pointer; BufLen: Integer): Integer; begin Result := WinSock.send(HSocket, Buf^, BufLen, 0); if (Result = SOCKET_ERROR) or (Result = 0) then Exit(-WSAGetLastError); if PrintDumps then LogFn(BinToHex(PAnsiChar(Buf), Result)); end; function TSyncSocket.Recv(Buf: Pointer; BufLen: Integer): Integer; begin Result := WinSock.recv(HSocket, Buf^, BufLen, 0); if (Result = SOCKET_ERROR) and (WSAGetLastError = WSAEWOULDBLOCK) then Exit(0); if Result = SOCKET_ERROR then Exit(-WSAGetLastError); if (Result > 0) and PrintDumps then LogFn(BinToHex(PAnsiChar(Buf), Result)); end; procedure TSyncSocket.Close; begin closesocket(HSocket); HSocket := 0; end; function Request(const URL, ReqStr: string): TReqResult; var pCreds: PSessionCreds; WSAData: TWSAData; HostAddr : TInAddr; socket: TSyncSocket; hCtx: CtxtHandle; IoBuffer: TBytes; cbIoBufferLength: DWORD; Sizes: SecPkgContext_StreamSizes; req: RawByteString; scRet: SECURITY_STATUS; cbRead, cbData: DWORD; buf, ExtraData: TBytes; res: Integer; EncrCnt, DecrCnt: Cardinal; // OutBuffer: SecBuffer; SessionData: TSessionData; arg: u_long; CertCheckRes: TCertCheckResult; Cert: TBytes; begin Result := resConnErr; EncrCnt := 0; DecrCnt := 0; socket := TSyncSocket.Create; try try SessionData := Default(TSessionData); SessionData.SharedCreds := SharedSessionCreds; SessionData.CertCheckIgnoreFlags := CertCheckIgnoreFlags; if ManualCertCheck then Include(SessionData.Flags, sfNoServerVerify); pCreds := GetSessionCredsPtr(SessionData); if SecIsNullHandle(pCreds.hCreds) then begin CreateSessionCreds(pCreds^); LogFn('----- ' + S_Msg_CredsInited); end else LogFn('----- Reusing session'); LogFn('~~~ Checking connect to '+URL); CheckWSResult(WSAStartup(MAKEWORD(2,2), WSAData) = 0, 'WSAStartup'); // check if hostname is an IP HostAddr.S_addr := inet_addr(Pointer(AnsiString(URL))); // Hostname is IP - don't verify it if DWORD(HostAddr.S_addr) <> INADDR_NONE then begin LogFn(Format(S_Msg_AddrIsIP, [URL])); Include(SessionData.Flags, sfNoServerVerify); end; socket.Connect(URL, 443); LogFn('----- Connected, ' + S_Msg_StartingTLS); Result := resTLSErr; // Perform handshake PerformClientHandshake(SessionData, URL, LogFn, socket.Send, socket.Recv, hCtx, ExtraData); if PrintCerts then begin Cert := GetCurrentCert(hCtx); LogFn('Cert data:'); LogFn(BinToHex(Cert, Length(Cert))); end; if sfNoServerVerify in SessionData.Flags then begin CertCheckRes := CheckServerCert(hCtx, IfThen(sfNoServerVerify in SessionData.Flags, '', URL)); // don't check host name if sfNoServerVerify is set // Print debug messages why the cert appeared valid case CertCheckRes of ccrTrusted: LogFn(LogPrefix + S_Msg_CertIsTrusted); ccrValidWithFlags: LogFn(LogPrefix + S_Msg_CertIsValidWithFlags); end; end; LogFn(LogPrefix + S_Msg_SrvCredsAuth); InitBuffers(hCtx, IoBuffer, Sizes); cbIoBufferLength := Length(IoBuffer); // Build the request - must be < maximum message size // message begins after the header req := RawByteString(ReqStr); EncryptData(hCtx, Sizes, Pointer(req), Length(req), PByte(IoBuffer), cbIoBufferLength, cbData); {}// ? что если больше, за два захода понадобится LogFn(Format(S_Msg_Sending, [Length(req), cbData])+ IfThen(PrintData, sLineBreak+string(req))); // Send the encrypted data to the server. res := socket.Send(Pointer(IoBuffer), cbData); if res < Integer(cbData) then if res <= 0 then raise ESSPIError.CreateWinAPI('sending encrypted request to server', 'send', res) else raise ESSPIError.Create('Error sending encrypted request to server: partial sent'); // Receive a Response // cbData is the length of received data in IoBuffer SetLength(buf, Sizes.cbMaximumMessage); cbData := 0; DecrCnt := 0; Move(Pointer(ExtraData)^, Pointer(IoBuffer)^, Length(ExtraData)); Inc(cbData, Length(ExtraData)); // Set socket non-blocking arg := 1; ioctlsocket(socket.HSocket, FIONBIO, arg); repeat Application.ProcessMessages; if Cancel then begin LogFn('~~~ Closed by user request'); socket.Close; Break; end; // get the data res := socket.Recv((PByte(IoBuffer) + cbData), cbIoBufferLength - cbData); if res < 0 then begin if (res = 0) and (WSAGetLastError = WSAEWOULDBLOCK) then begin Sleep(100); Continue; end; raise ESSPIError.CreateWinAPI('reading data from server', 'recv', res); end else // success / disconnect begin if res = 0 then // Server disconnected. begin socket.Close; Break; end; LogFn(Format('%d bytes of encrypted application data received', [res])); Inc(cbData, res); Inc(EncrCnt, res); end; scRet := DecryptData(hCtx, Sizes, PByte(IoBuffer), cbData, PByte(buf), Length(buf), cbRead); case scRet of SEC_E_OK, SEC_E_INCOMPLETE_MESSAGE, SEC_I_CONTEXT_EXPIRED: begin buf[cbRead] := 0; if cbRead = 0 then LogFn('No data') else LogFn('Received '+IntToStr(cbRead)+' bytes'+ IfThen(PrintData, sLineBreak+string(StrPas(PAnsiChar(buf))))); Inc(DecrCnt, cbRead); if scRet = SEC_I_CONTEXT_EXPIRED then begin LogFn('SEC_I_CONTEXT_EXPIRED'); socket.Close; Break; end; end; SEC_I_RENEGOTIATE: begin LogFn(S_Msg_Renegotiate); PerformClientHandshake(SessionData, URL, LogFn, socket.Send, socket.Recv, hCtx, ExtraData); cbData := 0; Move(Pointer(ExtraData)^, Pointer(IoBuffer)^, Length(ExtraData)); Inc(cbData, Length(ExtraData)); end; end; // case until False; {}{ // Send a close_notify alert to the server and close down the connection. GetShutdownData(SessionData, hCtx, OutBuffer); if OutBuffer.cbBuffer > 0 then begin LogFn(Format('Sending close notify - %d bytes of data', [OutBuffer.cbBuffer])); sock.Send(OutBuffer.pvBuffer, OutBuffer.cbBuffer); g_pSSPI.FreeContextBuffer(OutBuffer.pvBuffer); // Free output buffer. end; } LogFn('----- Disconnected From Server'); Result := resOK; except on E: Exception do LogFn(E.Message); end; finally LogFn(Format('~~~ Traffic: %d total / %d payload', [EncrCnt, DecrCnt])); socket.Close; FreeAndNil(socket); DeleteContext(hCtx); LogFn('----- Begin Cleanup'); FinSession(SessionData); LogFn('----- All Done -----'); end; end; end.
unit UFrameUDPLine; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Comctrls, Contnrs, StdCtrls, IniFiles, NMUDP, UTreeItem, UPRT_UDP, UPRT_Liner; type TFrameUDPLine = class(TFrame) GroupBox2: TGroupBox; Memo: TMemo; gbStat: TGroupBox; LabelStatSec: TLabel; LabelStatAll: TLabel; lblStatAll: TLabel; lblStatSec: TLabel; private { Private declarations } public { Public declarations } end; type TUDPConnection = class(TObject) prt1:TPRT_UDP; prt2:TPRT_LINER; Stat:TLinkStat; procedure ProcessIO; constructor Create(IP:String; Port:Integer; UDP:TNMUDP); destructor Destroy;override; end; TItemUDPLine = class(TTreeItem) protected UDP:TNMUDP; FUL:TFrameUDPLine; Links:TStringList; FEvents:String; StatAll,StatSec:TLinkStat; procedure AddEvent(Time:TDateTime; Event:String);overload; procedure AddEvent(Event:String);overload; procedure NMUDPDataReceived(Sender: TComponent; NumberBytes: Integer; FromIP: String; Port: Integer); class function GetKeyStr(IP:String; Port:Integer):String; function GetLink(IP:String; Port:Integer):TUDPConnection; procedure UpdateFrame; public function Enter(Owner:TComponent):TFrame;override; function Leave:Boolean;override; // function Validate:Boolean;override; constructor Load(UDP:TNMUDP; Nodes:TTreeNodes; ParentNode:TTreeNode; Ini,Cfg:TIniFile; const Section:String);reintroduce; destructor Destroy;override; procedure SaveCfg(Cfg:TIniFile);override; procedure TimerProc;override; end; implementation uses Misc, UTime, UNetW, UCRC; {$R *.DFM} { TItemUDPLine } procedure TItemUDPLine.AddEvent(Time: TDateTime; Event: String); begin Event:=LogMsg(Time,Event); if FUL<>nil then begin FUL.Memo.SelStart:=0; FUL.Memo.SelText:=Event; end; FEvents:=Event+FEvents; WriteToLog(Event); end; procedure TItemUDPLine.AddEvent(Event: String); begin AddEvent(GetMyTime,Event); end; destructor TItemUDPLine.Destroy; var i:Integer; begin for i:=Links.Count-1 downto 0 do TUDPConnection(Links.Objects[i]).Free; Links.Free; end; function TItemUDPLine.Enter(Owner: TComponent): TFrame; begin FUL:=TFrameUDPLine.Create(Owner); FUL.Memo.Text:=FEvents; FUL.Memo.SelStart:=Length(FEvents); UpdateFrame; Result:=FUL; end; class function TItemUDPLine.GetKeyStr(IP: String; Port: Integer): String; begin Result:=IP+':'+IntToStr(Port); end; function TItemUDPLine.GetLink(IP: String; Port:Integer): TUDPConnection; var Key:String; i:Integer; begin Key:=GetKeyStr(IP,Port); if not Links.Find(Key,i) then begin i:=Links.AddObject(Key,TUDPConnection.Create(IP,Port,UDP)); AddEvent('UDP/IP-связь с '+Key); end; Result:=Pointer(Links.Objects[i]); end; function TItemUDPLine.Leave: Boolean; begin FUL.Free; FUL:=nil; Result:=True; end; constructor TItemUDPLine.Load(UDP:TNMUDP; Nodes: TTreeNodes; ParentNode: TTreeNode; Ini, Cfg: TIniFile; const Section: String); begin Self.Section:=Section; Node:=Nodes.AddChildObject(ParentNode, Section, Self); Links:=CreateSortedStringList; Self.UDP:=UDP; UDP.OnDataReceived:=NMUDPDataReceived; end; procedure TItemUDPLine.NMUDPDataReceived(Sender: TComponent; NumberBytes: Integer; FromIP: String; Port: Integer); type TCharArray = array[0..MaxInt-1] of char; var InBuf:String; Buf:^TCharArray; Link:TUDPConnection; begin SetLength(InBuf,NumberBytes); Buf:=@(InBuf[1]); UDP.ReadBuffer(Buf^,NumberBytes); if (FromIP<>'127.0.0.1') {and (InBuf[Length(InBuf)]=Chr($0D))} then begin Link:=GetLink(FromIP,Port); Link.prt1.AddToRxQue(InBuf); end; end; procedure TItemUDPLine.SaveCfg(Cfg: TIniFile); begin // nothing to do end; procedure TItemUDPLine.TimerProc; var i:Integer; L:TUDPConnection; begin i:=Links.Count-1; StatAll.Add(StatSec); StatSec.Clear; while i>=0 do begin L:=TUDPConnection(Links.Objects[i]); StatSec.Add(L.Stat); L.Stat.Clear; if L.prt1.LinkTimeout then begin AddEvent('Таймаут связи '+Links[i]); Links.Delete(i); L.Free; end; Dec(i); end; UpdateFrame; end; procedure TItemUDPLine.UpdateFrame; begin if FUL=nil then exit; FUL.lblStatAll.Caption:=StatAll.GetMsg; FUL.lblStatSec.Caption:=StatSec.GetMsg; end; { TUDPConnection } constructor TUDPConnection.Create(IP: String; Port: Integer; UDP: TNMUDP); begin inherited Create; prt1:=TPRT_UDP.Create(UDP,IP,Port); prt2:=TPRT_Liner.Create(prt1); NetW_addProcessIO(ProcessIO); end; destructor TUDPConnection.Destroy; begin NetW_remProcessIO(ProcessIO); NetW_remConn(prt2); prt2.Free; prt1.Free; inherited; end; procedure TUDPConnection.ProcessIO; begin repeat until StdProcessIO(prt2,Stat); end; end.
unit mos6526_old; interface uses {$IFDEF WINDOWS}windows,{$ENDIF}dialogs,sysutils,cpu_misc,main_engine; type mos6526_chip=class constructor create(clock:dword); destructor free; public tod_clock:word; pa,pb,pra,prb:byte; joystick1,joystick2:byte; procedure reset; function read(direccion:byte):byte; procedure write(direccion,valor:byte); procedure change_calls(pa_read,pb_read:cpu_inport_call;pa_write,pb_write,irq_call:cpu_outport_call); procedure sync(frame:single); procedure flag_w(valor:byte); procedure clock_tod; private clock:dword; tod_stopped,irq,icr_read:boolean; flag,ta_pb6,tb_pb7,cra,crb,ddra,ddrb,pa_in,pb_in,imr,icr:byte; alarm,tod:dword; ta_latch,tb_latch,ta,tb:word; tod_count,bits,ta_out,tb_out,ir0,ir1,load_a0,load_a1,load_a2,load_b0,load_b1,load_b2,pc:integer; count_a0,count_a1,count_a2,count_a3,oneshot_a0,count_b0,count_b1,count_b2,count_b3,oneshot_b0,cnt:integer; pa_read,pb_read:cpu_inport_call; pa_write,pb_write:cpu_outport_call; irq_call:cpu_outport_call; procedure write_tod(offset,data:byte); procedure set_cra(data:byte); procedure set_crb(data:byte); procedure update_pa; procedure update_pb; procedure clock_ta; procedure clock_tb; procedure serial_output; procedure update_interrupt; procedure clock_pipeline; end; var mos6526_0,mos6526_1:mos6526_chip; implementation const PRA_=0; PRB_=1; DDRA_=2; DDRB_=3; TA_LO_=4; TA_HI_=5; TB_LO_=6; TB_HI_=7; TOD_10THS=8; TOD_SEC=9; TOD_MIN=$A; TOD_HR=$B; SDR_=$C; ICR_=$D; IMR_=ICR_; CRA_=$E; CRB_=$F; ICR_TA=$01; ICR_TB=$02; ICR_ALARM=$04; ICR_SP=$08; ICR_FLAG=$10; CRA_INMODE_PHI2=0; CRA_INMODE_CNT=1; CRB_INMODE_PHI2=0; CRB_INMODE_CNT=1; CRB_INMODE_TA=2; CRB_INMODE_CNT_TA=3; constructor mos6526_chip.create(clock:dword); begin self.clock:=clock; end; destructor mos6526_chip.free; begin end; procedure mos6526_chip.change_calls(pa_read,pb_read:cpu_inport_call;pa_write,pb_write,irq_call:cpu_outport_call); begin self.pa_read:=pa_read; self.pb_read:=pb_read; self.pa_write:=pa_write; self.pb_write:=pb_write; self.irq_call:=irq_call; end; procedure mos6526_chip.reset; begin self.tod_stopped:=true; self.cra:=0; self.crb:=0; self.alarm:=0; self.tod:=$01000000; self.ta_pb6:=0; self.tb_pb7:=0; self.ta_out:=0; self.tb_out:=0; self.pra:=0; self.prb:=0; self.ddra:=$ff; self.ddrb:=0; self.pa:=$ff; self.pb:=$ff; self.pa_in:=0; self.pb_in:=0; self.imr:=0; self.icr:=0; self.ir0:=0; self.ir1:=0; self.irq:=false; self.bits:=0; self.ta_latch:=$ffff; self.tb_latch:=$ffff; self.load_a0:=0; self.load_a1:=0; self.load_a2:=0; self.load_b0:=0; self.load_b1:=0; self.load_b2:=0; self.ta:=0; self.tb:=0; self.pc:=1; self.count_a0:=0; self.count_a1:=0; self.count_a2:=0; self.count_a3:=0; self.oneshot_a0:=0; self.count_b0:=0; self.count_b1:=0; self.count_b2:=0; self.count_b3:=0; self.oneshot_b0:=0; self.icr_read:=false; self.cnt:=1; self.flag:=1; end; procedure mos6526_chip.sync(frame:single); var tframe:single; begin tframe:=frame; while (tframe>0) do begin if (self.pc=0) then begin self.pc:=1; //MessageDlg('writepc', mtInformation,[mbOk], 0); //self.write_pc(self.pc); end; self.clock_ta; self.serial_output; self.clock_tb; self.update_pb; self.update_interrupt; self.clock_pipeline; tframe:=tframe-1; end; end; //------------------------------------------------- // clock_ta - clock timer A //------------------------------------------------- procedure mos6526_chip.clock_ta; begin if (self.count_a3<>0) then self.ta:=self.ta-1; self.ta_out:=byte((self.count_a2<>0) and (self.ta=0)); if (self.ta_out<>0) then begin self.ta_pb6:=not(self.ta_pb6); if (((self.cra and 8)<>0) or (self.oneshot_a0<>0)) then begin self.cra:=self.cra and $fe; self.count_a0:=0; self.count_a1:=0; self.count_a2:=0; end; self.load_a1:=1; end; if (self.load_a1<>0) then begin self.count_a2:=0; self.ta:=self.ta_latch; end; end; //------------------------------------------------- // clock_tb - clock timer B //------------------------------------------------- procedure mos6526_chip.clock_tb; begin if (self.count_b3<>0) then self.tb:=self.tb-1; self.tb_out:=byte((self.count_b2<>0) and (self.tb=0)); if (self.tb_out<>0) then begin self.tb_pb7:=not(self.tb_pb7); if (((self.crb and 8)<>0) or (self.oneshot_b0<>0)) then begin self.crb:=self.crb and $fe; self.count_b0:=0; self.count_b1:=0; self.count_b2:=0; end; self.load_b1:=1; end; if (self.load_b1<>0) then begin self.count_b2:=0; self.tb:=self.tb_latch; end; end; //------------------------------------------------- // serial_output - //------------------------------------------------- procedure mos6526_chip.serial_output; begin if ((self.ta_out<>0) and ((self.cra and $40)<>0)) then MessageDlg('serial write', mtInformation,[mbOk], 0); end; //------------------------------------------------- // update_interrupt - //------------------------------------------------- procedure mos6526_chip.update_interrupt; begin if (not(self.irq) and (self.ir1<>0)) then begin if addr(self.irq_call)<>nil then self.irq_call(ASSERT_LINE); self.irq:=true; end; if (self.ta_out<>0) then self.icr:=self.icr or ICR_TA; if ((self.tb_out<>0) and not(self.icr_read)) then self.icr:=self.icr or ICR_TB; self.icr_read:=false; end; //------------------------------------------------- // clock_pipeline - clock pipeline //------------------------------------------------- procedure mos6526_chip.clock_pipeline; begin // timer A pipeline self.count_a3:=self.count_a2; if ((self.cra and $20)=CRA_INMODE_PHI2) then self.count_a2:=1; self.count_a2:=self.count_a2 and $1; self.count_a1:=self.count_a0; self.count_a0:=0; self.load_a2:=self.load_a1; self.load_a1:=self.load_a0; self.load_a0:=(self.cra and $10) shr 4; self.cra:=self.cra and $ef; self.oneshot_a0:=(self.cra and 8) shr 3; // timer B pipeline self.count_b3:=self.count_b2; case ((self.crb and $60) shr 5) of CRB_INMODE_PHI2:self.count_b2:=1; CRB_INMODE_TA:self.count_b2:=self.ta_out; CRB_INMODE_CNT_TA:self.count_b2:=byte((self.ta_out<>0) and (self.cnt<>0)); end; self.count_b2:=self.count_b2 and (self.crb and 1); self.count_b1:=self.count_b0; self.count_b0:=0; self.load_b2:=self.load_b1; self.load_b1:=self.load_b0; self.load_b0:=(self.crb and $10) shr 4; self.crb:=self.crb and $ef; self.oneshot_b0:=(self.crb and 8) shr 3; // interrupt pipeline if (self.ir0<>0) then self.ir1:=1; if (self.icr and self.imr)<>0 then self.ir0:=1 else self.ir0:=0; end; //------------------------------------------------- // update_pa - update port A //------------------------------------------------- procedure mos6526_chip.update_pa; var pa:byte; begin pa:=self.pra or (self.pa_in and not(self.ddra)); if (self.pa<>pa) then begin self.pa:=pa; if addr(self.pa_write)<>nil then self.pa_write(pa); end; end; //------------------------------------------------- // update_pb - update port B //------------------------------------------------- procedure mos6526_chip.update_pb; var pb,pb6,pb7:byte; begin pb:=self.prb or (self.pb_in and not(self.ddrb)); if (self.cra and 2)<>0 then begin if (self.cra and 4)<>0 then pb6:=self.ta_pb6 else pb6:=self.ta_out; pb:=pb and $bf; pb:=pb or (pb6 shl 6); end; if (self.crb and 2)<>0 then begin if (self.crb and $4)<>0 then pb7:=self.tb_pb7 else pb7:=self.tb_out; pb:=pb and $7f; pb:=pb or (pb7 shl 7); end; if (self.pb<>pb) then begin if addr(self.pb_write)<>nil then self.pb_write(pb); self.pb:=pb; end; end; //------------------------------------------------- // write_tod - time-of-day write //------------------------------------------------- procedure mos6526_chip.write_tod(offset,data:byte); var shift:byte; begin shift:=8*offset; if (self.crb and $80)<>0 then self.alarm:=(self.alarm and not($ff shl shift)) or (data shl shift) else self.tod:=(self.tod and not($ff shl shift)) or (data shl shift); end; //------------------------------------------------- // set_cra - control register A write //------------------------------------------------- procedure mos6526_chip.set_cra(data:byte); begin if (((self.cra and 1)=0) and ((data and 1)<>0)) then self.ta_pb6:=1; // switching to serial output mode causes sp to go high? if (((self.cra and $40)=0) and ((data and $40)<>0)) then begin self.bits:=0; MessageDlg('writesp 1', mtInformation,[mbOk], 0); //m_write_sp(1); end; // lower sp again when switching back to input? if (((self.cra and $40)<>0) and ((data and $40)=0)) then begin self.bits:=0; MessageDlg('writesp 0', mtInformation,[mbOk], 0); //m_write_sp(0); end; self.cra:=data; self.update_pb; end; procedure mos6526_chip.flag_w(valor:byte); begin if (self.flag<>valor) then begin self.icr:=self.icr or ICR_FLAG; self.flag:=valor; end; end; procedure mos6526_chip.clock_tod; function bcd_increment(value:byte):byte; begin value:=value+1; if ((value and $0f)>=$0a) then value:=value+($10-$0a); bcd_increment:=value; end; var subsecond,second,minute,hour,pm,tempb:byte; begin subsecond:=self.tod shr 0; second:=self.tod shr 8; minute:=self.tod shr 16; hour:=self.tod shr 24; self.tod_count:=self.tod_count+1; if (self.cra and $80)<>0 then tempb:=5 else tempb:=6; if (self.tod_count=tempb) then begin self.tod_count:=0; subsecond:=bcd_increment(subsecond); if (subsecond>=$10) then begin subsecond:=0; second:=bcd_increment(second); if (second>=60) then begin second:=0; minute:=bcd_increment(minute); if (minute>=$60) then begin minute:=0; pm:=hour and $80; hour:=hour and $1f; if (hour=11) then pm:=pm xor $80; if (hour=12) then hour:=0; hour:=bcd_increment(hour); hour:=hour or pm; end; end; end; end; self.tod:= (subsecond shl 0) or (second shl 8) or (minute shl 16) or (hour or 24); end; //------------------------------------------------- // set_crb - control register B write //------------------------------------------------- procedure mos6526_chip.set_crb(data:byte); begin if (((self.crb and 1)=0) and ((data and $1)<>0)) then self.tb_pb7:=1; self.crb:=data; self.update_pb; end; function mos6526_chip.read(direccion:byte):byte; var res,tempb,pb6,pb7:byte; begin res:=0; case (direccion and $f) of PRA_:begin if addr(self.pa_read)<>nil then tempb:=self.pa_read else tempb:=$ff; if (self.ddra<>$ff) then res:=(tempb and not(self.ddra)) or (self.pra and self.ddra) else res:=tempb and self.pra; self.pa_in:=res; end; PRB_:begin if addr(self.pb_read)<>nil then tempb:=self.pb_read else tempb:=$ff; if (self.ddrb<>$ff) then res:=(tempb and not(self.ddrb)) or (self.prb and self.ddrb) else res:=tempb and self.prb; self.pb_in:=res; if (self.cra and $2)<>0 then begin if (self.cra and $4)<>0 then pb6:=self.ta_pb6 else pb6:=self.ta_out; res:=res and $bf; res:=res or (pb6 shl 6); end; if (self.crb and $2)<>0 then begin if (self.crb and 4)<>0 then pb7:=self.tb_pb7 else pb7:=self.tb_out; res:=res and $7f; res:=res or (pb7 shl 7); end; self.pc:=0; //m_write_pc(m_pc); end; DDRA_:res:=self.ddra; DDRB_:res:=self.ddrb; TA_LO_:res:=self.ta and $ff; TA_HI_:res:=self.ta shr 8; TB_LO_:res:=self.tb and $ff; TB_HI_:res:=self.tb shr 8; ICR_:begin res:=(self.ir1 shl 7) or self.icr; self.icr_read:=true; self.ir0:=0; self.ir1:=0; self.icr:=0; self.irq:=false; if addr(self.irq_call)<>nil then self.irq_call(CLEAR_LINE); end; CRA_:res:=self.cra; CRB_:res:=self.crb; else MessageDlg('read mos6526 desconocido '+inttohex(direccion,4), mtInformation,[mbOk], 0); end; read:=res; end; procedure mos6526_chip.write(direccion,valor:byte); begin case (direccion and $f) of PRA_:begin self.pra:=valor; self.update_pa; end; DDRA_:begin self.ddra:=valor; self.update_pa; end; DDRB_:begin self.ddrb:=valor; self.update_pb; end; TA_LO_:begin self.ta_latch:=(self.ta_latch and $ff00) or valor; if (self.load_a2<>0) then self.ta:=(self.ta and $ff00) or valor; end; TA_HI_:begin self.ta_latch:=(valor shl 8) or (self.ta_latch and $ff); if ((self.cra and 1)=0) then self.load_a0:=1; if ((self.cra and $8)<>0) then begin self.ta:=self.ta_latch; self.set_cra(self.cra or 1); end; if (self.load_a2<>0) then self.ta:=(valor shl 8) or (self.ta and $ff); end; TB_LO_:begin self.tb_latch:= (self.tb_latch and $ff00) or valor; if (self.load_b2<>0) then self.tb:=(self.tb and $ff00) or valor; end; TB_HI_:begin self.tb_latch:= (valor shl 8) or (self.tb_latch and $ff); if ((self.crb and 1)=0) then self.load_b0:=1; if ((self.crb and $8)<>0) then begin self.tb:=self.tb_latch; self.set_crb(self.crb or 1); end; if (self.load_b2<>0) then self.tb:=(valor shl 8) or (self.tb and $ff); end; TOD_10THS:begin self.write_tod(0,valor); tod_stopped:=false; end; IMR_:begin //Mascara de las IRQs //Si el bit 7 es 0 --> Lo que esté a 1 lo desabilito //Si el bit 7 es 1 --> Lo que esté a 1 lo habilito if (valor and $80)<>0 then self.imr:=self.imr or (valor and $1f) else self.imr:=self.imr and not(valor and $1f); //Alguna IRQ? if (not(self.irq) and ((self.icr and self.imr)<>0)) then self.ir0:=1; end; CRA_:self.set_cra(valor); CRB_:self.set_crb(valor); else MessageDlg('write mos6526 desconocido '+inttohex(direccion,4), mtInformation,[mbOk], 0); end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2017 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Net.HttpClient.Linux; interface implementation uses System.Classes, System.Generics.Collections, System.SysUtils, System.Net.URLClient, System.Net.HttpClient, System.NetConsts, System.DateUtils, System.Types, Linuxapi.Curl, System.IOUtils, Posix.SysTypes, Posix.SysStat; type TLinuxHTTPClient = class(THTTPClient) private class constructor Create; class destructor Destroy; function GetServerCertInfoFromRequest(const ARequest: THTTPRequest; var ACertificate: TCertificate): Boolean; function GetCertInfo(ACertData: PCurlCertInfo; var ACertificate: TCertificate): Boolean; protected function DoExecuteRequest(const ARequest: THTTPRequest; var AResponse: THTTPResponse; const AContentStream: TStream): THTTPClient.TExecutionResult; override; function DoSetCredential(AnAuthTargetType: TAuthTargetType; const ARequest: THTTPRequest; const ACredential: TCredentialsStorage.TCredential): Boolean; override; function DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream): IAsyncResult; override; function DoGetHTTPRequestInstance(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI): IHTTPRequest; override; function DoProcessStatus(const ARequest: IHTTPRequest; const AResponse: IHTTPResponse): Boolean; override; function DoGetSSLCertificateFromServer(const ARequest: THTTPRequest): TCertificate; override; procedure DoServerCertificateAccepted(const ARequest: THTTPRequest); override; procedure DoGetClientCertificates(const ARequest: THTTPRequest; const ACertificateList: TList<TCertificate>); override; function DoClientCertificateAccepted(const ARequest: THTTPRequest; const AnIndex: Integer): Boolean; override; class function CreateInstance: TURLClient; override; public constructor Create; end; TLinuxHTTPResponse = class; TLinuxHTTPRequest = class(THTTPRequest) private FRequest: PCurl; FHeaders: TDictionary<string, string>; FTempFileName: string; [Weak] FResponse: TLinuxHTTPResponse; FErrorBuff: array [0 .. CURL_ERROR_SIZE] of Byte; FLastMethodString: string; procedure InitRequest; procedure CleanupRequest; protected procedure DoPrepare; override; function GetHeaders: TNetHeaders; override; procedure AddHeader(const AName, AValue: string); override; function RemoveHeader(const AName: string): Boolean; override; function GetHeaderValue(const AName: string): string; override; procedure SetHeaderValue(const AName, Value: string); override; class function CurlReadData(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; cdecl; static; class function CurlWriteData(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; cdecl; static; class function CurlReadHeaders(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; cdecl; static; public constructor Create(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI); destructor Destroy; override; end; TLinuxHTTPResponse = class(THTTPResponse) private [Weak] FRequest: TLinuxHTTPRequest; FNativeHeaders: TStringList; FNativeStatusCode: string; FNativeStatusLine: string; FTotalRead: Int64; LeftToSend: Integer; function ReceiveData(buffer: Pointer; size: size_t; nitems: size_t): size_t; function ReceiveHeader(buffer: Pointer; size: size_t; nitems: size_t): size_t; function SendData(buffer: Pointer; size: size_t; nitems: size_t): size_t; protected procedure DoReadData(const AStream: TStream); override; function GetHeaders: TNetHeaders; override; function GetStatusCode: Integer; override; function GetStatusText: string; override; function GetVersion: THTTPProtocolVersion; override; public constructor Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback; const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: TLinuxHTTPRequest; const AContentStream: TStream); destructor Destroy; override; end; type THTTPRequestMethod = (CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, TRACE, MERGE, PATCH, others); function MethodStringToHTTPMethod(const AMethodString: string): THTTPRequestMethod; var LMethod: string; begin LMethod := AMethodString.ToUpper; if LMethod = sHTTPMethodConnect then Result := THTTPRequestMethod.CONNECT else if LMethod = sHTTPMethodDelete then Result := THTTPRequestMethod.DELETE else if LMethod = sHTTPMethodGet then Result := THTTPRequestMethod.GET else if LMethod = sHTTPMethodHead then Result := THTTPRequestMethod.HEAD else if LMethod = sHTTPMethodOptions then Result := THTTPRequestMethod.OPTIONS else if LMethod = sHTTPMethodPost then Result := THTTPRequestMethod.POST else if LMethod = sHTTPMethodPut then Result := THTTPRequestMethod.PUT else if LMethod = sHTTPMethodTrace then Result := THTTPRequestMethod.TRACE else if LMethod = sHTTPMethodMerge then Result := THTTPRequestMethod.MERGE else if LMethod = sHTTPMethodPatch then Result := THTTPRequestMethod.PATCH else Result := THTTPRequestMethod.others; end; { TLinuxHTTPClient } constructor TLinuxHTTPClient.Create; begin inherited Initializer; end; class constructor TLinuxHTTPClient.Create; begin curl_global_init(CURL_GLOBAL_DEFAULT); end; class function TLinuxHTTPClient.CreateInstance: TURLClient; begin Result := TLinuxHTTPClient.Create; end; class destructor TLinuxHTTPClient.Destroy; begin curl_global_cleanup; end; function TLinuxHTTPClient.DoClientCertificateAccepted(const ARequest: THTTPRequest; const AnIndex: Integer): Boolean; begin { Not needed in Linux } Result := True; end; function TLinuxHTTPClient.DoExecuteRequest(const ARequest: THTTPRequest; var AResponse: THTTPResponse; const AContentStream: TStream): TLinuxHTTPClient.TExecutionResult; var LRequest: TLinuxHTTPRequest; LList: pcurl_slist; LMethod: THTTPRequestMethod; LSize: curl_off_t; //long LOption: CURLoption; LValue: TPair<string, string>; LCode: TCurlCode; LResponseCode: NativeInt; LError: string; begin LRequest := TLinuxHTTPRequest(ARequest); // Cleanup Response Headers SetLength(LRequest.FResponse.FHeaders, 0); LRequest.FResponse.FNativeHeaders.Clear; LRequest.FResponse.FTotalRead := 0; LRequest.FResponse.LeftToSend := 0; try LList := nil; try LMethod := MethodStringToHTTPMethod(LRequest.FMethodString); if LMethod in [THTTPRequestMethod.PUT, THTTPRequestMethod.POST] then begin LList := curl_slist_append(LList, MarshaledAString(UTF8String('Expect:'))); if Assigned(LRequest.FSourceStream) then begin LSize := LRequest.FSourceStream.Size - LRequest.FSourceStream.Position; if LSize < 0 then LSize := 0; end else LSize := 0; LRequest.FResponse.LeftToSend := LSize; if LMethod = THTTPRequestMethod.PUT then LOption := CURLOPT_INFILESIZE_LARGE else LOption := CURLOPT_POSTFIELDSIZE; curl_easy_setopt(LRequest.FRequest, LOption, LSize); end; for LValue in LRequest.FHeaders do LList := curl_slist_append(LList, MarshaledAString(UTF8String(LValue.Key + ': ' + LValue.Value))); curl_easy_setopt(LRequest.FRequest, CURLOPT_HTTPHEADER, LList); LCode := curl_easy_perform(LRequest.FRequest); finally if LList <> nil then curl_slist_free_all(LList); end; case LCode of CURLE_OK: begin Result := TExecutionResult.Success; if curl_easy_getinfo(LRequest.FRequest, CURLINFO_RESPONSE_CODE, @LResponseCode) = CURLE_OK then TLinuxHTTPResponse(AResponse).FNativeStatusCode := LResponseCode.ToString; end; CURLE_SSL_ISSUER_ERROR{?}, CURLE_SSL_INVALIDCERTSTATUS{?}, CURLE_PEER_FAILED_VERIFICATION{?}, CURLE_SSL_CACERT {Server}: Result := TExecutionResult.ServerCertificateInvalid; // CURLE_SSL_CERTPROBLEM: { Local client certificate problem } // Result := TExecutionResult.UnknownError; else LError := UTF8ToString(@LRequest.FErrorBuff[0]); if LError = '' then LError := UTF8ToString(curl_easy_strerror(LCode)); raise ENetHTTPClientException.CreateResFmt(@SNetHttpClientErrorAccessing, [ Integer(LCode), LRequest.FURL.ToString, LError]); end; finally // Update Headers & Cookies LRequest.FResponse.GetHeaders; end; end; procedure TLinuxHTTPClient.DoGetClientCertificates(const ARequest: THTTPRequest; const ACertificateList: TList<TCertificate>); begin inherited; { Not needed in Linux } end; function TLinuxHTTPClient.DoGetHTTPRequestInstance(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI): IHTTPRequest; begin Result := TLinuxHTTPRequest.Create(AClient, ARequestMethod, AURI); end; function TLinuxHTTPClient.DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream): IAsyncResult; begin Result := TLinuxHTTPResponse.Create(AContext, AProc, AsyncCallback, AsyncCallbackEvent, ARequest as TLinuxHTTPRequest, AContentStream); end; function TLinuxHTTPClient.DoGetSSLCertificateFromServer(const ARequest: THTTPRequest): TCertificate; var LRequest: TLinuxHTTPRequest; begin LRequest := TLinuxHTTPRequest(ARequest); if not GetServerCertInfoFromRequest(LRequest, Result) then Result := Default(TCertificate); end; function TLinuxHTTPClient.DoProcessStatus(const ARequest: IHTTPRequest; const AResponse: IHTTPResponse): Boolean; var LRequest: TLinuxHTTPRequest; LResponse: TLinuxHTTPResponse; begin LRequest := ARequest as TLinuxHTTPRequest; LResponse := AResponse as TLinuxHTTPResponse; // If the result is true then the while ends Result := True; if IsAutoRedirect(LResponse) then begin LRequest.FURL := ComposeRedirectURL(LRequest, LResponse); if IsAutoRedirectWithGET(LRequest, LResponse) then begin LRequest.FMethodString := sHTTPMethodGet; // Change to GET LRequest.FSourceStream := nil; // Dont send any data LRequest.SetHeaderValue(sContentType, '');// Dont set content type end; Result := False; end; end; procedure TLinuxHTTPClient.DoServerCertificateAccepted(const ARequest: THTTPRequest); var LRequest: TLinuxHTTPRequest; begin inherited; LRequest := TLinuxHTTPRequest(ARequest); curl_easy_setopt(LRequest.FRequest, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(LRequest.FRequest, CURLOPT_SSL_VERIFYPEER, 0); end; function TLinuxHTTPClient.DoSetCredential(AnAuthTargetType: TAuthTargetType; const ARequest: THTTPRequest; const ACredential: TCredentialsStorage.TCredential): Boolean; var LRequest: TLinuxHTTPRequest; begin LRequest := TLinuxHTTPRequest(ARequest); if AnAuthTargetType = TAuthTargetType.Server then begin curl_easy_setopt(LRequest.FRequest, CURLOPT_USERNAME, UTF8String(ACredential.UserName)); curl_easy_setopt(LRequest.FRequest, CURLOPT_PASSWORD, UTF8String(ACredential.Password)); end else begin curl_easy_setopt(LRequest.FRequest, CURLOPT_PROXYUSERNAME, UTF8String(ACredential.UserName)); curl_easy_setopt(LRequest.FRequest, CURLOPT_PROXYPASSWORD, UTF8String(ACredential.Password)); end; Result := True; end; function TLinuxHTTPClient.GetCertInfo(ACertData: PCurlCertInfo; var ACertificate: TCertificate): Boolean; var LDataList: pcurl_slist; LData: string; LPos: Integer; LKey, LValue: string; function GetDateFromGMT: TDateTime; begin LValue := LValue.Replace(' ', 'T', []); LPos := LValue.IndexOf(' '); if LPos > 0 then LValue := LValue.Substring(0, LPos); TryISO8601ToDate(LValue, Result); end; begin Result := False; LDataList := ACertData.certinfo^; if LDataList <> nil then begin Result := True; repeat LData := UTF8ToString(LDataList^.data); LPos := LData.IndexOf(':'); LKey := LData.Substring(0, LPos); LValue := LData.Substring(LPos + 1); if SameText(LKey, 'Subject') then // do not localize ACertificate.Subject := LValue // do not localize else if SameText(LKey, 'Issuer') then // do not localize ACertificate.Issuer := LValue else if SameText(LKey, 'Expire date') then // do not localizev ACertificate.Expiry := GetDateFromGMT else if SameText(LKey, 'Start date') then // do not localize ACertificate.Start := GetDateFromGMT else if SameText(LKey, 'Signature Algorithm') then // do not localize ACertificate.AlgSignature := LValue; LDataList := LDataList^.next; until LDataList = nil; end; end; function TLinuxHTTPClient.GetServerCertInfoFromRequest(const ARequest: THTTPRequest; var ACertificate: TCertificate): Boolean; var LClone: PCurl; LRequest: TLinuxHTTPRequest; LCode: TCURLcode; LCertData: PCurlCertInfo; begin LRequest := TLinuxHTTPRequest(ARequest); LClone := curl_easy_duphandle(LRequest.FRequest); try { for getting the server certificate information, we need to } { disable the verification process. } curl_easy_setopt(LClone, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(LClone, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(LClone, CURLOPT_CUSTOMREQUEST, UTF8String(sHTTPMethodHead)); curl_easy_setopt(LClone, CURLOPT_NOBODY, 1); curl_easy_perform(LClone); LCode := curl_easy_getinfo(LClone, CURLINFO_CERTINFO, @LCertData); if LCode = CURLE_OK then Result := GetCertInfo(LCertData, ACertificate) else raise ENetHTTPCertificateException.CreateRes(@SNetHttpCertificatesError); finally curl_easy_cleanup(LClone); end; end; { TLinuxHTTPRequest } procedure TLinuxHTTPRequest.AddHeader(const AName, AValue: string); const CDelims: array [Boolean] of Char = (',', ';'); var LCookie: Boolean; LList, LValues: TStringList; I: Integer; procedure TrimList(AList: TStrings); var I: Integer; begin for I := 0 to AList.Count - 1 do AList[I] := AList[I].Trim; end; begin inherited; LCookie := SameText(AName, sCookie); LList := TStringList.Create(#0, CDelims[LCookie], [soStrictDelimiter, soUseLocale]); LList.CaseSensitive := False; LValues := TStringList.Create(#0, CDelims[LCookie], [soStrictDelimiter, soUseLocale]); try LList.DelimitedText := GetHeaderValue(AName); TrimList(LList); LValues.DelimitedText := AValue; TrimList(LValues); for I := 0 to LValues.Count - 1 do if LCookie and (LValues.Names[I] <> '') then LList.Values[LValues.Names[I]] := LValues.ValueFromIndex[I] else if (LValues[I] <> '') and (LList.IndexOf(LValues[I]) = -1) then LList.Add(LValues[I]); SetHeaderValue(AName, LList.DelimitedText); finally LList.Free; LValues.Free; end; end; constructor TLinuxHTTPRequest.Create(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI); begin inherited Create(AClient, ARequestMethod, AURI); FHeaders := TDictionary<string, string>.Create; InitRequest; end; destructor TLinuxHTTPRequest.Destroy; begin CleanupRequest; FHeaders.Free; if FTempFileName <> '' then TFile.Delete(FTempFileName); inherited Destroy; end; procedure TLinuxHTTPRequest.InitRequest; begin FRequest := curl_easy_init; { Setup common options for LibCurl } curl_easy_setopt(FRequest, CURLOPT_WRITEFUNCTION, @CurlReadData); curl_easy_setopt(FRequest, CURLOPT_WRITEDATA, Self); curl_easy_setopt(FRequest, CURLOPT_HEADERFUNCTION, @CurlReadHeaders); curl_easy_setopt(FRequest, CURLOPT_HEADERDATA, Self); curl_easy_setopt(FRequest, CURLOPT_CERTINFO, 1); curl_easy_setopt(FRequest, CURLOPT_TCP_KEEPALIVE, 1); curl_easy_setopt(FRequest, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(FRequest, CURLOPT_ERRORBUFFER, @FErrorBuff[0]); end; procedure TLinuxHTTPRequest.CleanupRequest; begin if FRequest <> nil then begin curl_easy_cleanup(FRequest); FRequest := nil; end; end; class function TLinuxHTTPRequest.CurlReadData(buffer: Pointer; size, nitems: size_t; instream: Pointer): size_t; begin if instream <> nil then Result := TLinuxHTTPRequest(instream).FResponse.ReceiveData(buffer, size, nitems) else Result := 0; end; class function TLinuxHTTPRequest.CurlReadHeaders(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; begin if instream <> nil then Result := TLinuxHTTPRequest(instream).FResponse.ReceiveHeader(buffer, size, nitems) else Result := 0; end; class function TLinuxHTTPRequest.CurlWriteData(buffer: Pointer; size, nitems: size_t; instream: Pointer): size_t; begin if instream <> nil then Result := TLinuxHTTPRequest(instream).FResponse.SendData(buffer, size, nitems) else Result := 0; end; procedure TLinuxHTTPRequest.DoPrepare; var LTmpFile: TFileStream; begin inherited; if (FLastMethodString <> '') and not SameText(FLastMethodString, FMethodString) then begin CleanupRequest; InitRequest; end; FLastMethodString := FMethodString; curl_easy_setopt(FRequest, CURLOPT_URL, UTF8String(FURL.ToString)); if FURL.Username <> '' then begin SetCredential(TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '', FURL.ToString, FURL.Username, FURL.Password)); curl_easy_setopt(FRequest, CURLOPT_USERNAME, UTF8String(FURL.Username)); curl_easy_setopt(FRequest, CURLOPT_PASSWORD, UTF8String(FURL.Password)); end; if FClient.ProxySettings.Host <> '' then begin curl_easy_setopt(FRequest, CURLOPT_PROXY, UTF8String(FClient.ProxySettings.Host)); if FClient.ProxySettings.Port > 0 then curl_easy_setopt(FRequest, CURLOPT_PROXYPORT, FClient.ProxySettings.Port); end; if FClientCertPath <> '' then begin if ExtractFileExt(FClientCertPath).ToLower = 'p12' then curl_easy_setopt(FRequest, CURLOPT_SSLCERTTYPE, UTF8String('P12')) else curl_easy_setopt(FRequest, CURLOPT_SSLCERTTYPE, UTF8String('PEM')); if curl_easy_setopt(FRequest, CURLOPT_SSLCERT, UTF8String(FClientCertPath)) <> CURLE_OK then raise ENetHTTPCertificateException.CreateRes(@SNetHttpCertificateImportError); end else begin if FClientCertificate <> nil then begin FTempFileName := TPath.GetTempFileName + '.pem'; LTmpFile := TFileStream.Create(FTempFileName, fmCreate, S_IRUSR); try FClientCertificate.Position := 0; LTmpFile.CopyFrom(FClientCertificate, FClientCertificate.Size); finally LTmpFile.Free; end; curl_easy_setopt(FRequest, CURLOPT_SSLCERTTYPE, UTF8String('PEM')); if curl_easy_setopt(FRequest, CURLOPT_SSLCERT, UTF8String(FTempFileName)) <> CURLE_OK then raise ENetHTTPCertificateException.CreateRes(@SNetHttpCertificateImportError); end; end; if FClientCertPassword <> '' then curl_easy_setopt(FRequest, CURLOPT_KEYPASSWD, UTF8String(FClientCertPath)); { Handle request methods } case MethodStringToHTTPMethod(FMethodString) of THTTPRequestMethod.GET, THTTPRequestMethod.CONNECT, THTTPRequestMethod.OPTIONS, THTTPRequestMethod.TRACE, THTTPRequestMethod.MERGE, THTTPRequestMethod.PATCH, THTTPRequestMethod.DELETE, THTTPRequestMethod.others: curl_easy_setopt(FRequest, CURLOPT_CUSTOMREQUEST, PUTF8Char(UTF8String(FMethodString)) ); THTTPRequestMethod.PUT: begin curl_easy_setopt(FRequest, CURLOPT_UPLOAD, 1); curl_easy_setopt(FRequest, CURLOPT_READFUNCTION, @CurlWriteData); curl_easy_setopt(FRequest, CURLOPT_READDATA, Self); end; THTTPRequestMethod.HEAD: begin curl_easy_setopt(FRequest, CURLOPT_CUSTOMREQUEST, UTF8String(FMethodString)); curl_easy_setopt(FRequest, CURLOPT_NOBODY, 1); end; THTTPRequestMethod.POST: begin curl_easy_setopt(FRequest, CURLOPT_POST, 1); curl_easy_setopt(FRequest, CURLOPT_READFUNCTION, @CurlWriteData); curl_easy_setopt(FRequest, CURLOPT_READDATA, Self); end; end; end; function TLinuxHTTPRequest.GetHeaders: TNetHeaders; var Value: TPair<string, string>; CntHeader: Integer; begin SetLength(Result, 500); // Max 500 headers CntHeader := 0; for Value in FHeaders do begin Result[CntHeader].Create(Value.Key, Value.Value); Inc(CntHeader); end; SetLength(Result, CntHeader); end; function TLinuxHTTPRequest.GetHeaderValue(const AName: string): string; begin Result := ''; FHeaders.TryGetValue(AName, Result); end; function TLinuxHTTPRequest.RemoveHeader(const AName: string): Boolean; begin Result := True; if GetHeaderValue(AName) = '' then Result := False else FHeaders.Remove(AName); end; procedure TLinuxHTTPRequest.SetHeaderValue(const AName, Value: string); begin inherited; FHeaders.AddOrSetValue(AName, Value); end; { TLinuxHTTPResponse } constructor TLinuxHTTPResponse.Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback; const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: TLinuxHTTPRequest; const AContentStream: TStream); begin inherited Create(AContext, AProc, AAsyncCallback, AAsyncCallbackEvent, ARequest, AContentStream); FRequest := ARequest; FRequest.FResponse := Self; FNativeHeaders := TStringList.Create; end; destructor TLinuxHTTPResponse.Destroy; begin FNativeHeaders.Free; inherited; end; procedure TLinuxHTTPResponse.DoReadData(const AStream: TStream); begin inherited; // Do nothing end; function TLinuxHTTPResponse.GetHeaders: TNetHeaders; var I, P: Integer; LPos: Integer; LName: string; LValue: string; procedure AddOrSetHeader; var J: Integer; begin for J := 0 to P - 1 do begin if SameText(FHeaders[J].Name, LName) then begin FHeaders[J].Value := FHeaders[J].Value + ', ' + LValue; Exit; end; end; FHeaders[P].Create(LName, LValue); Inc(P); end; begin if Length(FHeaders) = 0 then begin SetLength(FHeaders, FNativeHeaders.Count); P := 0; for I := 0 to FNativeHeaders.Count - 1 do begin LPos := FNativeHeaders[I].IndexOf(':'); LName := FNativeHeaders[I].Substring(0, LPos); LValue := FNativeHeaders[I].Substring(LPos + 1).Trim; if SameText(LName, sSetCookie) then InternalAddCookie(LValue) else AddOrSetHeader; end; SetLength(Result, P); end; Result := FHeaders; end; function TLinuxHTTPResponse.GetStatusCode: Integer; begin TryStrToInt(FNativeStatusCode, Result); end; function TLinuxHTTPResponse.GetStatusText: string; begin Result := FNativeStatusLine; end; function TLinuxHTTPResponse.GetVersion: THTTPProtocolVersion; var LVersion: string; LValues: TArray<string>; begin if FNativeStatusLine <> '' then begin LValues := FNativeStatusLine.Split([' ']); LVersion := LValues[0]; if string.CompareText(LVersion, 'HTTP/1.0') = 0 then Result := THTTPProtocolVersion.HTTP_1_0 else if string.CompareText(LVersion, 'HTTP/1.1') = 0 then Result := THTTPProtocolVersion.HTTP_1_1 else if string.CompareText(LVersion, 'HTTP/2.0') = 0 then Result := THTTPProtocolVersion.HTTP_2_0 else Result := THTTPProtocolVersion.UNKNOWN_HTTP; end else Result := THTTPProtocolVersion.UNKNOWN_HTTP; end; function TLinuxHTTPResponse.ReceiveData(buffer: Pointer; size, nitems: size_t): size_t; var LAbort: Boolean; LContentLength: Int64; LStatusCode: Integer; LTotal: Integer; function GetEarlyStatusCode: Integer; var LTmp: TArray<string>; begin Result := GetStatusCode; if Result = 0 then begin LTmp := FNativeStatusLine.Split([' ']); if Length(LTmp) > 2 then begin FNativeStatusCode := LTmp[1]; Result := GetStatusCode; end; end; end; begin LAbort := False; LTotal := nitems * size; Inc(FTotalRead, LTotal); LContentLength := GetContentLength; LStatusCode := GetEarlyStatusCode; FRequest.DoReceiveDataProgress(LStatusCode, LContentLength, FTotalRead, LAbort); if not LAbort then Result := FStream.Write(buffer^, LTotal) else Result := 0 end; function TLinuxHTTPResponse.ReceiveHeader(buffer: Pointer; size, nitems: size_t): size_t; var LHeader: string; LPos: Integer; begin LHeader := UTF8ToString(buffer).Trim; LPos := LHeader.IndexOf(':'); if LPos > 0 then FNativeHeaders.Add(LHeader) else if LHeader <> '' then FNativeStatusLine := LHeader; Result := size * nitems; end; function TLinuxHTTPResponse.SendData(buffer: Pointer; size, nitems: size_t): size_t; begin if LeftToSend > 0 then begin Result := FRequest.FSourceStream.Read(buffer^, size * nitems); Dec(LeftToSend, Result); end else Result := 0; end; initialization TURLSchemes.RegisterURLClientScheme(TLinuxHTTPClient, 'HTTP'); TURLSchemes.RegisterURLClientScheme(TLinuxHTTPClient, 'HTTPS'); finalization TURLSchemes.UnRegisterURLClientScheme('HTTP'); TURLSchemes.UnRegisterURLClientScheme('HTTPS'); end.
unit Frame.Watches; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation; type TFrameWatches = class(TFrame) LabelInstructions1: TLabel; LabelInstructions2: TLabel; LabelCustomWatch: TLabel; TrackBar: TTrackBar; procedure TrackBarChange(Sender: TObject); private { Private declarations } procedure HandleLiveWatches(const Sender: TObject; const M: TMessage); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation {$R *.fmx} uses Grijjy.CloudLogging; constructor TFrameWatches.Create(AOwner: TComponent); begin inherited; { Subscribe to the Live Watches message to provide the Grijjy Log Viewer with a list of watches. Besides this frame, TFormMain also subscribes to this message. } TMessageManager.DefaultManager.SubscribeToMessage(TgoLiveWatchesMessage, HandleLiveWatches); end; destructor TFrameWatches.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TgoLiveWatchesMessage, HandleLiveWatches); inherited; end; procedure TFrameWatches.HandleLiveWatches(const Sender: TObject; const M: TMessage); var Msg: TgoLiveWatchesMessage absolute M; begin Assert(M is TgoLiveWatchesMessage); Msg.Add('Custom Watch', TrackBar.Value, 1); end; procedure TFrameWatches.TrackBarChange(Sender: TObject); begin LabelCustomWatch.Text := Format('Custom watch: %.1f', [TrackBar.Value]); end; end.
namespace Sugar.Legacy; {$HIDE W0} //supress case-mismatch errors interface uses Sugar; // all methods in this module are one-based, as they are for Delphi compatibility. method &Copy(aString: String; aStart, aLength: Int32): String; method Pos(aSubString: String; aString: String): Int32; implementation method Pos(aSubString: String; aString: String): Int32; begin result := aString:IndexOf(aSubString) + 1; end; method &Copy(aString: String; aStart: Int32; aLength: Int32): String; begin if not assigned(aString) then exit ''; // Delphi's copy() handels lengths that exceed the string, and returns what's there. // .NET and Sugar's SubString would throw an exception, so we need to account for that. var l := aString.Length; if (aStart-1)+aLength > l then aLength := l-(aStart+1); result := aString.Substring(aStart-1, aLength); end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.WMI Description : Common functions Author : Kike Pérez Version : 1.1 Created : 04/04/2019 Modified : 22/04/2020 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.WMI; {$i QuickLib.inc} {$TYPEDADDRESS OFF} {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} interface uses SysUtils, ActiveX, ComObj, Quick.Commons, Quick.Collections, Quick.Arrays, Quick.Value, Variants; type IWMIInstance = interface ['{4C81A6A6-4A65-46FB-B05B-5898DF51F9B7}'] function GetProperty(const aPropertyName : string) : TFlexValue; function GetProperties(const aProperties : TArray<string>) : IList<TFlexPair>; function GetName : string; end; TWMIInstance = class(TInterfacedObject,IWMIInstance) private fInstance : string; fWMIItem : OleVariant; public constructor Create(const aInstanceName : string; aWMIItem: OleVariant); destructor Destroy; override; function GetProperty(const aPropertyName : string) : TFlexValue; function GetProperties(const aProperties : TArray<string>) : IList<TFlexPair>; function GetName : string; end; TWMIInstances = TArray<IWMIInstance>; IWMIClass = interface ['{FAFE26ED-28BC-4591-AE5A-9E4543074B5C}'] function GetInstance(const aInstance : string) : IWMIInstance; function GetInstances(const aInstances : TArray<string>) : TWMIInstances; end; TWMIClass = class(TInterfacedObject,IWMIClass) private fClassName : string; fWMIService : OleVariant; fWMIClassItems : IEnumvariant; function GetInstanceName(aWMIClass : OleVariant) : string; public constructor Create(aWMIService : OleVariant; const aClassName : string; aWMIClassItems : IEnumvariant); destructor Destroy; override; function GetInstance(const aInstance : string) : IWMIInstance; function GetInstances(const aInstances : TArray<string>) : TWMIInstances; end; IWMICollector = interface ['{3FFFF0DC-F533-4FE1-A511-73E76EC6BCC8}'] function From(const aRoot, aWMIClass : string) : IWMIClass; overload; function From(const aHost, aRoot, aWMIClass : string) : IWMIClass; overload; end; TWMICollector = class(TInterfacedObject,IWMICollector) private fNamespace : string; fWMIService : OleVariant; public constructor Create; destructor Destroy; override; class function GetObject(const aObjectName: string) : IDispatch; function From(const aRoot, aWMIClass : string) : IWMIClass; overload; function From(const aHost, aRoot, aWMIClass : string) : IWMIClass; overload; end; EWMICollector = class(Exception); implementation const wbemFlagUseAmendedQualifiers = $00020000; wbemFlagReturnImmediately = $00000010; wbemFlagReturnWhenComplete = $00000000; wbemFlagForwardOnly = $00000020; { TWMICollector } constructor TWMICollector.Create; begin fNamespace := ''; CoInitialize(nil); end; destructor TWMICollector.Destroy; begin fWMIService := Unassigned; CoUninitialize; inherited; end; class function TWMICollector.GetObject(const aObjectName: string) : IDispatch; var chEaten : Integer; bindCtx : IBindCtx; moniker : IMoniker; begin OleCheck(CreateBindCtx(0, bindCtx)); OleCheck(MkParseDisplayName(bindCtx, PWideChar(aObjectName), chEaten, moniker)); OleCheck(Moniker.BindToObject(bindCtx, nil, IDispatch, Result)); end; function TWMICollector.From(const aRoot, aWMIClass : string) : IWMIClass; begin Result := From('.',aRoot,aWMIClass); end; function TWMICollector.From(const aHost, aRoot, aWMIClass : string) : IWMIClass; var colItems : OLEVariant; oEnum : IEnumvariant; begin try //only connect if namespace is different from previous connection if fNamespace <> aHost + '\' + aRoot then begin fWMIService := GetObject(Format('winmgmts:\\%s\%s',[aHost,aRoot])); fNamespace := aHost + '\' + aRoot; end; colItems := fWMIService.ExecQuery(Format('SELECT * FROM %s',[aWMIClass]),'WQL',wbemFlagForwardOnly and wbemFlagReturnImmediately); oEnum := IUnknown(colItems._NewEnum) as IEnumVariant; Result := TWMIClass.Create(fWMIService,aWMIClass,oEnum); oEnum := nil; colItems := Unassigned; except on E : Exception do raise EWMICollector.CreateFmt('Error getting WMI Class "\\%s\%s\%s": %s',[aHost,aRoot,aWMIClass,e.Message]); end; end; { TWMIInstance } constructor TWMIInstance.Create(const aInstanceName : string; aWMIItem: OleVariant); begin fInstance := aInstanceName; fWMIItem := aWMIItem; end; destructor TWMIInstance.Destroy; begin fWMIItem := Unassigned; inherited; end; function TWMIInstance.GetName: string; begin Result := fInstance; end; function TWMIInstance.GetProperties(const aProperties : TArray<string>) : IList<TFlexPair>; var prop : string; item : OleVariant; begin Result := TxList<TFlexPair>.Create; for prop in aProperties do begin try item := fWMIItem.Properties_.Item(prop, 0); try Result.Add(TFlexPair.Create(prop,item)); finally item := Unassigned; end; except on E : Exception do raise EWMICollector.CreateFmt('Retrieving "%s" (%s)',[prop,e.message]); end; end; end; function TWMIInstance.GetProperty(const aPropertyName: string): TFlexValue; var item : OleVariant; begin item := fWMIItem.Properties_.Item(aPropertyName, 0); try Result := item; finally item := Unassigned; end; end; { TWMIClass } constructor TWMIClass.Create(aWMIService : OleVariant; const aClassName : string; aWMIClassItems : IEnumvariant); begin fWMIService := aWMIService; fClassName := aClassName; fWMIClassItems := aWMIClassItems; end; destructor TWMIClass.Destroy; begin fWMIClassItems := nil; fWMIService := Unassigned; inherited; end; function TWMIClass.GetInstance(const aInstance: string): IWMIInstance; var propItem : OLEVariant; iValue : LongWord; instanceName : string; begin while fWMIClassItems.Next(1, propItem, iValue) = 0 do begin try instanceName := GetInstanceName(propItem); if CompareText(aInstance,instanceName) = 0 then begin Result := TWMIInstance.Create(instanceName,propItem); Break; end; finally propItem := Unassigned; end; end; end; function TWMIClass.GetInstanceName(aWMIClass : OleVariant) : string; var qualifiers : OleVariant; enumQualif : IEnumVariant; qualifItem : OleVariant; pceltFetched : Cardinal; propItem : OleVariant; enumProp : IEnumVariant; iValue : Cardinal; properties : OleVariant; objSWbemObjectSet : OleVariant; item : OleVariant; begin Result := ''; objSWbemObjectSet:= fWMIService.Get(fClassName, wbemFlagUseAmendedQualifiers and wbemFlagReturnWhenComplete); properties := objSWbemObjectSet.Properties_; enumProp := IUnknown(properties._NewEnum) as IENumVariant; while enumProp.Next(1, propItem, iValue) = 0 do begin qualifiers := propItem.Qualifiers_; enumQualif := IUnknown(qualifiers._NewEnum) as IEnumVariant; //iterate over the qualifiers while enumQualif.Next(1, qualifItem, pceltFetched) = 0 do begin //check the name of the qualifier //Result := rgvarQualif.Name; //Result := rgvarQualif.Value; if qualifItem.Name = 'key' then begin item := aWMIClass.Properties_.Item(propItem.Name,0); try if qualifItem.Value then if Result = '' then Result := item else Result := Format('%s %s',[Result,item]); finally item := Unassigned; end; end; qualifItem := Unassigned; end; enumQualif := nil; qualifiers := Unassigned; propItem := Unassigned; end; enumProp := nil; properties := Unassigned; objSWbemObjectSet := Unassigned; end; function TWMIClass.GetInstances(const aInstances: TArray<string>): TWMIInstances; var propItem : OLEVariant; iValue : LongWord; getAllInstances : Boolean; instanceName : string; begin getAllInstances := (High(aInstances) = 0) and (aInstances[0] = '*'); while fWMIClassItems.Next(1, propItem, iValue) = 0 do begin instanceName := GetInstanceName(propItem); if (getAllInstances) or (StrInArray(instancename,aInstances)) then begin Result := Result + [TWMIInstance.Create(instanceName,propItem)]; end; propItem := Unassigned; end; end; end.
Unit FCache; interface { ---------------------- File Cache -------------------------- } { implements a simple file cache and mimic C getc and ungetc functions. } const BufMemSize = 4096; EOF = ^Z; type Cache = record active : boolean; BildOffset : LongInt; Buffer : array[0..BufMemSize-1] of byte; FVarPtr : ^file; FileOfs : LongInt; BufPos : integer; BufSize : integer; end; Procedure fc_Init(var fc : Cache; var f : file; FPos : LongInt); Procedure fc_Close(var fc : Cache); Procedure fc_Done(var fc : Cache; var f : file); Procedure fc_ReadBlock(var fc : Cache); Function fc_getc(var fc : Cache) : Byte; { Read a byte at the current buffer read-index, increment the buffer read-index } function fc_ungetc (var fc : Cache; ch : char) : Byte; { Read a byte at the current buffer read-index, increment the buffer read-index } procedure fc_WriteTo(var fc : Cache; var Buf; Count : Word); implementation {$IFDEF USE_DOS} uses Dos; {$ENDIF} Procedure fc_Init(var fc : Cache; var f : file; FPos : LongInt); begin with fc do begin active := false; FVarPtr := @f; FileOfs := FPos; BufSize := 0; BufPos := 0; {$IFDEF USE_DOS} if TFileRec(f).Mode <> fmClosed then {$ENDIF} begin {$IFOPT I+} {$DEFINE IOCheck} {$I-} {$ENDIF} Seek(f, FPos); BlockRead(f, Buffer, BufMemSize, BufSize); {$IFDEF IOCheck} {$I+} {$ENDIF} if (IOResult = 0) and (BufSize <> 0) then active := true; end; end; end; Procedure fc_Done(var fc : Cache; var f : file); begin with fc do if FVarPtr = @f then begin active := false; FVarPtr := NIL; FileOfs := 0; BufSize := 0; BufPos := 0; end; end; Procedure fc_Close(var fc : Cache); begin with fc do begin if Assigned(FVarPtr) then Close(FVarPtr^); fc_Done(fc, FVarPtr^); end; end; Procedure fc_ReadBlock(var fc : Cache); Begin with fc do if active then begin {$I-} Seek(FVarPtr^, FileOfs); BlockRead(FVarPtr^, Buffer, BufMemSize, BufSize); {$IFDEF IOCheck} {$I+} {$ENDIF} BufPos := 0; active := (IOResult = 0) and (BufSize <> 0); end; End; Function fc_getc(var fc : Cache) : Byte; { Read a byte at the current buffer read-index, increment the buffer read-index } begin with fc do if active then begin fc_GetC := Buffer[BufPos]; Inc(BufPos); if BufPos = BufSize then begin Inc(FileOfs, BufSize); fc_ReadBlock(fc); end; end else fc_getc := Byte(EOF); end; function fc_ungetc (var fc : Cache; ch : char) : Byte; { Read a byte at the current buffer read-index, increment the buffer read-index } begin with fc do begin fc_UnGetC := Byte(EOF); if active and (FileOfs > 0) then begin if BufPos = 0 then begin Dec(FileOfs); fc_ReadBlock(fc); end; if BufPos > 0 then begin Dec(BufPos); fc_UnGetC := Buffer[BufPos]; end; end; end; end; procedure fc_WriteTo(var fc : Cache; var Buf; Count : Word); type PByte = ^Byte; var ChunkSize : Word; DestPtr : PByte; Begin with fc do if active then begin ChunkSize := BufSize - BufPos; DestPtr := PByte(@Buf); if Count > ChunkSize then begin { the amount we need to read straddles a buffer boundary, we need two or more chunks. This implementation doesn't try to read more than two chunks. } Move(Buffer[BufPos], Buf, ChunkSize); Inc(DestPtr, ChunkSize); Dec(count, ChunkSize); Inc(FileOfs, BufSize); fc_ReadBlock(fc); end; { we are now completely within the buffer boundary, do a simple mem move } Move(Buffer[BufPos], DestPtr^, count); end; End; { ---------------------- End File Cache -------------------------- } end.
unit NewBaseSearch_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, vg_scene, vg_objects, vg_controls, vg_listbox, vg_layouts, OvcBase, afwControlPrim, afwBaseControl, afwControl, nevControl, evCustomEditorWindowPrim, evEditorWindow, evCustomEditorWindowModelPart, evMultiSelectEditorWindow, evCustomEditorModelPart, evCustomEditor, evEditorWithOperations, evCustomMemo, evCustomEdit, elCustomEdit, elCustomButtonEdit, ctButtonEdit, ctAbstractEdit, AbstractDropDown, DropDownTree, nscTreeComboWithHistory, nscTreeComboWithHistoryAndOperations, nscCustomTreeComboWithHistory, NewBaseSearchForDFM_Form, l3InterfacedComponent, vcmComponent, vcmBaseEntities, vcmEntities, vgComponent, vgCustomResources, vgCustomObject, vgCustomControl, vg_effects, vgEffect, vgObject, vgVisualObject, vgScenePrim, vcmExternalInterfaces, evCustomEditorWindow ; type TvcmEntityFormRef = TNewBaseSearchForDFMForm; TNewBaseSearchForm = class(TvcmEntityFormRef) vgScene1: TvgScene; Root1: TvgBackground; Rectangle1: TvgRectangle; BottomMargin: TvgRectangle; MostOuterRectangle: TvgRectangle; vgResources1: TvgResources; CloseBtn: TvgCloseButton; AreaCombo: TvgComboBox; Layout1: TvgLayout; Layout2: TvgLayout; ContextEditPanel: TvgNonVGLayout; ContextEdit: TnscTreeComboWithHistoryAndOperations; DropButton: TvgButton; Path1: TvgPath; ExampleLabel: TvgText; QueryExampleLabel: TvgText; FoundCountLabel: TvgText; FindBtn: TvgPathButton; FindBackBtn: TvgPathButton; Entities: TvcmEntities; Layout3: TvgLayout; Line1: TvgLine; MoreTab: TvgComboBox; GlowEffect1: TvgGlowEffect; GlowEffect2: TvgGlowEffect; Border: TvgRectangle; InnerBorder: TvgRectangle; procedure CloseBtnClick(Sender: TObject); procedure FindBtnClick(Sender: TObject); procedure AreaComboChange(Sender: TObject); procedure FindBackBtnClick(Sender: TObject); procedure DropButtonClick(Sender: TObject); procedure QueryExampleLabelClick(Sender: TObject); procedure QueryExampleLabelKeyDown(Sender: TObject; var Key: Word; var KeyChar: WideChar; Shift: TShiftState); procedure vcmEntityFormRefCreate(Sender: TObject); { При создании формы БП восстанавливаем ширину выпадающего списка } private procedure OnContextEditCloseUp(Sender: TObject); { При закрытии нужно запоминать ширину выпадающего списка } protected procedure InitControls; override; public { Public declarations } end;//TNewBaseSearchForm implementation {$R *.dfm} uses BaseSearchInterfaces, l3Defaults ; procedure TNewBaseSearchForm.CloseBtnClick(Sender: TObject); begin DoCloseBtnClick; end; procedure TNewBaseSearchForm.FindBtnClick(Sender: TObject); begin DoFindBtnClick; end; procedure TNewBaseSearchForm.AreaComboChange(Sender: TObject); begin if (AreaCombo.ItemIndex >= Ord(Low(TnsSearchArea))) AND (AreaCombo.ItemIndex <= Ord(High(TnsSearchArea))) then UpdateSearcherArea(TnsSearchArea(AreaCombo.ItemIndex), f_BaseSearcher.WindowData.ContextKind); end; procedure TNewBaseSearchForm.FindBackBtnClick(Sender: TObject); begin DoFindBackBtnClick; end; procedure TNewBaseSearchForm.DropButtonClick(Sender: TObject); var l_ContextEditPos : TPoint; l_DropButtonPos : TPoint; l_P : TvgPoint; l_MinDropDownWidth : Integer; begin // ширина выпадающего списка имеет ограничения как сверху, так и снизу // http://mdp.garant.ru/pages/viewpage.action?pageId=273598933 l_ContextEditPos := ContextEdit.ClientToScreen(Point(0, 0)); l_P := DropButton.LocalToAbsolute(vgPoint(0, 0)); l_DropButtonPos := vgScene1.ClientToScreen(Point(Trunc(l_P.X), Trunc(l_P.Y))); l_MinDropDownWidth := l_DropButtonPos.X + Trunc(DropButton.Width) - l_ContextEditPos.X; if ContextEdit.Tree is TnscSubTree then with TnscSubTree(ContextEdit.Tree) do begin CustomMinSizeX := l_MinDropDownWidth; end; if (ContextEdit.DropWidth < l_MinDropDownWidth) then ContextEdit.DropWidth := l_MinDropDownWidth; if ContextEdit.CanFocus then ContextEdit.SetFocus; ContextEdit.Button.Click; DropButton.IsPressed := ContextEdit.Dropped; end; procedure TNewBaseSearchForm.QueryExampleLabelClick(Sender: TObject); begin ApplyCurrentExample; end; procedure TNewBaseSearchForm.QueryExampleLabelKeyDown(Sender: TObject; var Key: Word; var KeyChar: WideChar; Shift: TShiftState); begin if (KeyChar = #32) then begin ApplyCurrentExample; KeyChar := #0; end;//KeyChar = #32 end; var // ширину выпадающего списка для ContextEdit храним в глобальной переменной // для синхронизации размеров у разных объектов БП g_ContextEditDropWidth: Integer = 0; procedure TNewBaseSearchForm.vcmEntityFormRefCreate(Sender: TObject); begin ContextEdit.DropWidth := g_ContextEditDropWidth; ContextEdit.KeepLastDropWidth := True; ContextEdit.OnCloseUp := OnContextEditCloseUp; end; procedure TNewBaseSearchForm.OnContextEditCloseUp(Sender: TObject); begin g_ContextEditDropWidth := ContextEdit.DropWidth; end; procedure TNewBaseSearchForm.InitControls; begin inherited; //http://mdp.garant.ru/pages/viewpage.action?pageId=361399733 if ContextEdit.Tree is TnscSubTree then with TnscSubTree(ContextEdit.Tree) do begin HotTrackColor := cGarant2011GradientEndColor; YandexLikeBehaviour := True; end; end; end.
UNIT ModLCGRandom; INTERFACE FUNCTION RandInt() : INTEGER; FUNCTION RandBetween(l, u : INTEGER) : INTEGER; FUNCTION RandBetweenDiv(l, u : INTEGER) : INTEGER; PROCEDURE InitLCG(randSeed : INTEGER); IMPLEMENTATION CONST a = 48721; c = 1; m = 32768; (*2 ^ 16*) VAR x: LONGINT; FUNCTION RandInt : INTEGER; BEGIN x := (a*x+c)MOD m; RandInt := x; END; PROCEDURE InitLCG(randSeed : INTEGER); BEGIN x:= randSeed; END; FUNCTION RandBetweenDiv(l, u : INTEGER) : INTEGER; VAR r, range : INTEGER; BEGIN r := RandInt(); range := u - l; RandBetweenDiv := l + Trunc((r/m)*range); END; FUNCTION RandBetween(l, u : INTEGER) : INTEGER; VAR r, range, max : INTEGER; BEGIN IF l >= u THEN BEGIN WriteLn('l >= u in RandBetween'); HALT; range := u-l; max := m DIV range * range; r := RandInt; WHILE (r >= max) DO r := RandInt; END; RandBetween := l + r MOD range; END; BEGIN END.
program CSVtoSQL; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, sqlite3conn, sqldb, db; type { TCSVtoSQL } TCSVtoSQL = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; end; { TCSVtoSQL } function CreateQuery(pConnection: TSQLConnector; pTransaction: TSQLTransaction): TSQLQuery; begin result := TSQLQuery.Create(nil); result.Database := pConnection; result.Transaction := pTransaction end; function CreateTransaction(pConnection: TSQLConnector): TSQLTransaction; begin result := TSQLTransaction.Create(pConnection); result.Database := pConnection; end; procedure Split (const Delimiter: Char; Input: string; const Strings: TStrings); begin Assert(Assigned(Strings)) ; Strings.Clear; Strings.StrictDelimiter := true; Strings.Delimiter := Delimiter; Strings.DelimitedText := Input; end; procedure TCSVtoSQL.DoRun; var ColumnA, Fields, FileContent: TStringList; Conn: TSQLConnector; FileName: string; idx, idy, parent, SectID: integer; Query1, Query2: TSQLQuery; Trans: TSQLTransaction; begin FileName := 'CatergoriesAndActivities.csv'; Conn := TSQLConnector.Create(nil); with Conn do begin ConnectorType := 'SQLite3'; HostName := ''; // not important DatabaseName := 'geobjects.db'; UserName := ''; // not important Password := ''; // not important end; Writeln; FileContent := TStringList.Create; try FileContent.LoadFromFile(FileName); Trans := CreateTransaction(Conn); Query1 := CreateQuery(Conn, Trans); Query2 := CreateQuery(Conn, Trans); Conn.Open; for idx := 0 to pred(FileContent.Count) do begin Fields := TStringList.Create; try split(',', FileContent.Strings[idx], Fields); // inserting into SheetsTbl ColumnA := TStringList.Create; split('s', Fields[0], ColumnA); if ColumnA.Count = 2 then begin Query1.SQL.Text := 'SELECT * FROM SheetsTbl WHERE sheetnum=:sheetnum AND tablenum=:tablenum;'; Query1.Params.ParamByName('tablenum').AsString := ColumnA[0][Length(ColumnA[0])]; Query1.Params.ParamByName('sheetnum').AsString := ColumnA[1]; Query1.Open; Writeln('Sheet Count: ' + IntToStr(Query1.RecordCount)); if Query1.RecordCount = 0 then begin Query2.SQL.Text := 'INSERT INTO SheetsTbl(datem,creator,changer,setname,sheetnum,tablenum,notes) VALUES(CURRENT_TIMESTAMP,0,0,0,:sheetnum,:tablenum,"");'; Query2.Params.ParamByName('tablenum').AsString := ColumnA[0][Length(ColumnA[0])]; Query2.Params.ParamByName('sheetnum').AsString := ColumnA[1]; Query2.ExecSQL; Trans.Commit; Query2.Close; Query2.Free; end; Query1.Close; end; ColumnA.Free; // inserting into CategoriesTbl Query1.SQL.Text := 'SELECT ID FROM SectorsTbl WHERE sectname=:sname;'; Query1.Params.ParamByName('sname').AsString := Fields[1]; Query1.Open; SectID := Query1.FieldByName('ID').AsInteger; Query1.Close; for idy := 2 to pred(Fields.Count) do begin Writeln('Count Character:' + IntToStr(Fields[idy].Length)); if Fields[idy].Trim.Length = 0 then begin Break; end; Query1.SQL.Text := 'SELECT * FROM CategoriesTbl WHERE catname=:catname;'; Query1.Params.ParamByName('catname').AsString := Fields[idy]; Query1.Open; if Query1.RecordCount = 0 then begin Query1.Close; if idy = 2 then begin parent := 0; end else begin Query1.SQL.Text := 'SELECT * FROM CategoriesTbl WHERE catname=:catname;'; Query1.Params.ParamByName('catname').AsString := Fields[idy-1]; Query1.Open; parent := Query1.FieldByName('ID').AsInteger; Query1.Close; end; Query2.SQL.Text := 'INSERT INTO CategoriesTbl(datem,creator,changer,setname,catname,sect,parent,ismemo,catval,displace,notes) VALUES(CURRENT_TIMESTAMP,0,0,0,:catname,:sect,:parent,"n",0,:displace,"");'; Query2.Params.ParamByName('catname').AsString := Fields[idy]; Query2.Params.ParamByName('sect').AsInteger := SectID; Query2.Params.ParamByName('parent').AsInteger := parent; Query2.Params.ParamByName('displace').AsInteger := idy-1; Query2.ExecSQL; Trans.Commit; Query2.Close; end; Query1.Close; Writeln('Column: ' + IntToStr(idy)); end; finally Fields.Free; end; Writeln('Row: ' + IntToStr(idx)); end; finally FileContent.Free; Query1.Free; Query2.Free; end; // selecting data {Query1.SQL.Text := 'SELECT * FROM testtbl;'; Query1.Open; Writeln(Query1.RecordCount); while not Query1.Eof do begin Writeln('ID: ', Query1.FieldByName('ID').AsInteger); Query1.Next; end;} Conn.Close; Trans.Free; Conn.Free; readln; // stop program loop Terminate; end; constructor TCSVtoSQL.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TCSVtoSQL.Destroy; begin inherited Destroy; end; var Application: TCSVtoSQL; begin Application:=TCSVtoSQL.Create(nil); Application.Title:='CSV to SQL'; Application.Run; Application.Free; end.